blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
721
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
5
91
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
321 values
visit_date
timestamp[ns]date
2016-08-12 09:31:09
2023-09-06 10:45:07
revision_date
timestamp[ns]date
2010-09-28 14:01:40
2023-09-06 06:22:19
committer_date
timestamp[ns]date
2010-09-28 14:01:40
2023-09-06 06:22:19
github_id
int64
426
681M
star_events_count
int64
101
243k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[ns]date
2012-06-28 18:51:49
2023-09-14 21:59:16
gha_created_at
timestamp[ns]date
2008-02-11 22:55:26
2023-08-10 11:14:58
gha_language
stringclasses
147 values
src_encoding
stringclasses
26 values
language
stringclasses
2 values
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
6
10.2M
extension
stringclasses
115 values
filename
stringlengths
3
113
content
stringlengths
6
10.2M
a09b244508c08c2663aad85907eadcc27f31420a
19a9f2c19bcb81c4a14ba17831d3098de7731fb5
/ncarg2d/src/libncarg/polypackC/c_ppppap.c
77b46cf4c37651c9671dec664628809f03d26383
[ "Apache-2.0" ]
permissive
NCAR/ncl
243c30eaefce642d53373aa583b73df72eb59f22
8a96101fe14d0cf0f5ed66a5e6b1733084bc69df
refs/heads/develop
2023-03-17T07:53:18.883458
2022-05-11T16:01:03
2022-05-11T16:01:03
67,087,395
254
68
NOASSERTION
2022-10-08T07:20:06
2016-09-01T01:34:28
C
UTF-8
C
false
false
1,106
c
c_ppppap.c
/* * $Id: c_ppppap.c,v 1.5 2008-07-23 16:16:59 haley Exp $ */ /************************************************************************ * * * Copyright (C) 2000 * * University Corporation for Atmospheric Research * * All Rights Reserved * * * * The use of this Software is governed by a License Agreement. * * * ************************************************************************/ #include <ncarg/ncargC.h> extern void NGCALLF(ppppap,PPPPAP)(float*,float*,int*,int*); void c_ppppap #ifdef NeedFuncProto ( float *xcop, float *ycop, int ncop, int nbts ) #else (xcop,ycop,ncop,nbts) float *xcop; float *ycop; int ncop; int nbts; ) #endif { NGCALLF(ppppap,PPPPAP)(xcop,ycop,&ncop,&nbts); }
e36ec77ca114e4a9b45f3264e4c2b849bb58afe5
8d7d6f609ba65eb2650e5f04ab7b2d6db8a192d4
/src/rowMedians.c
da7777bb8e833b1ad91f5667acd1d722f392e250
[]
no_license
HenrikBengtsson/matrixStats
78e0edb5e23265b39a0ceb14f59e317fde401a79
3e8f9ddafc0de61e870534b75fb5f90429a7bd31
refs/heads/develop
2023-07-26T10:52:03.035332
2023-07-10T20:20:44
2023-07-10T20:20:44
20,844,530
196
41
null
2023-05-26T22:51:17
2014-06-14T23:59:10
R
UTF-8
C
false
false
3,785
c
rowMedians.c
/*************************************************************************** Public methods: SEXP rowMedians(SEXP x, ...) Authors: Adopted from rowQuantiles.c by R. Gentleman. Copyright Henrik Bengtsson, 2007 **************************************************************************/ #include <Rdefines.h> #include "000.types.h" #include "rowMedians_lowlevel.h" #include "naming.h" SEXP rowMedians(SEXP x, SEXP dim, SEXP rows, SEXP cols, SEXP naRm, SEXP hasNA, SEXP byRow, SEXP useNames) { int narm, hasna, byrow, usenames; SEXP ans; R_xlen_t nrow, ncol; /* Coercion moved down to C */ PROTECT(dim = coerceVector(dim, INTSXP)); /* Argument 'x' and 'dim': */ assertArgMatrix(x, dim, (R_TYPE_INT | R_TYPE_REAL), "x"); /* Get dimensions of 'x'. */ nrow = asR_xlen_t(dim, 0); ncol = asR_xlen_t(dim, 1); /* Argument 'naRm': */ narm = asLogicalNoNA(naRm, "na.rm"); /* Argument 'hasNA': */ hasna = asLogicalNoNA(hasNA, "hasNA"); /* Argument 'rows' and 'cols': */ R_xlen_t nrows, ncols; int rowsHasNA; int colsHasNA; R_xlen_t *crows = validateIndicesCheckNA(rows, nrow, 0, &nrows, &rowsHasNA); R_xlen_t *ccols = validateIndicesCheckNA(cols, ncol, 0, &ncols, &colsHasNA); /* Argument 'byRow': */ byrow = asLogical(byRow); if (!byrow) { SWAP(R_xlen_t, nrow, ncol); SWAP(R_xlen_t*, crows, ccols); SWAP(R_xlen_t, nrows, ncols); SWAP(int, rowsHasNA, colsHasNA); } /* R allocate a double vector of length 'nrows' Note that 'nrows' means 'ncols' if byrow=FALSE. */ PROTECT(ans = allocVector(REALSXP, nrows)); /* Double matrices are more common to use. */ if (isReal(x)) { rowMedians_dbl(REAL(x), nrow, ncol, crows, nrows, rowsHasNA, ccols, ncols, colsHasNA, narm, hasna, byrow, REAL(ans)); } else if (isInteger(x)) { rowMedians_int(INTEGER(x), nrow, ncol, crows, nrows, rowsHasNA, ccols, ncols, colsHasNA, narm, hasna, byrow, REAL(ans)); } /* Argument 'useNames': */ usenames = asLogical(useNames); if (usenames != NA_LOGICAL && usenames) { SEXP dimnames = getAttrib(x, R_DimNamesSymbol); if (dimnames != R_NilValue) { if (byrow) { SEXP namesVec = VECTOR_ELT(dimnames, 0); if (namesVec != R_NilValue) { setNames(ans, namesVec, nrows, crows); } } else { SEXP namesVec = VECTOR_ELT(dimnames, 1); if (namesVec != R_NilValue) { setNames(ans, namesVec, nrows, crows); } } } } UNPROTECT(2); return(ans); } /* rowMedians() */ /*************************************************************************** HISTORY: 2015-06-07 [DJ] o Supported subsetted computation. 2013-01-13 [HB] o Added argument 'byRow' to rowMedians() and dropped colMedians(). o Using internal arguments 'by_row' instead of 'by_column'. 2011-12-11 [HB] o BUG FIX: rowMediansReal(..., na.rm=TRUE) did not handle NaN:s, only NA:s. Note that NaN:s does not exist for integers. 2011-10-12 [HJ] o Added colMedians(). o Now rowMediansInteger/Real() can operate also by columns, cf. argument 'by_column'. 2007-08-14 [HB] o Added checks for user interrupts every 1000 line. o Added argument 'hasNA' to rowMedians(). 2005-12-07 [HB] o BUG FIX: When calculating the median of an even number (non-NA) values, the length of the second sort was one element too short, which made the method to freeze, i.e. rPsort(rowData, qq, qq) is now (...qq+1, qq). 2005-11-24 [HB] o By implementing a special version for integers, there is no need to coerce to double in R, which would take up twice the amount of memory. o rowMedians() now handles NAs too. o Adopted from rowQuantiles.c in Biobase of Bioconductor. **************************************************************************/
5cb408c945da93954685c871497c5c030c19c4a2
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/simulator/SDL2/include/SDL_test_common.h
0f50967895014f12bd1dc9002f7a2e4b582efd72
[ "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
RT-Thread/rt-thread
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
3602f891211904a27dcbd51e5ba72fefce7326b2
refs/heads/master
2023-09-01T04:10:20.295801
2023-08-31T16:20:55
2023-08-31T16:20:55
7,408,108
9,599
5,805
Apache-2.0
2023-09-14T13:37:26
2013-01-02T14:49:21
C
UTF-8
C
false
false
6,837
h
SDL_test_common.h
/* Simple DirectMedia Layer Copyright (C) 1997-2022 Sam Lantinga <slouken@libsdl.org> 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. */ /** * \file SDL_test_common.h * * Include file for SDL test framework. * * This code is a part of the SDL2_test library, not the main SDL library. */ /* Ported from original test\common.h file. */ #ifndef SDL_test_common_h_ #define SDL_test_common_h_ #include "SDL.h" #if defined(__PSP__) #define DEFAULT_WINDOW_WIDTH 480 #define DEFAULT_WINDOW_HEIGHT 272 #elif defined(__VITA__) #define DEFAULT_WINDOW_WIDTH 960 #define DEFAULT_WINDOW_HEIGHT 544 #else #define DEFAULT_WINDOW_WIDTH 640 #define DEFAULT_WINDOW_HEIGHT 480 #endif #define VERBOSE_VIDEO 0x00000001 #define VERBOSE_MODES 0x00000002 #define VERBOSE_RENDER 0x00000004 #define VERBOSE_EVENT 0x00000008 #define VERBOSE_AUDIO 0x00000010 typedef struct { /* SDL init flags */ char **argv; Uint32 flags; Uint32 verbose; /* Video info */ const char *videodriver; int display; const char *window_title; const char *window_icon; Uint32 window_flags; SDL_bool flash_on_focus_loss; int window_x; int window_y; int window_w; int window_h; int window_minW; int window_minH; int window_maxW; int window_maxH; int logical_w; int logical_h; float scale; int depth; int refresh_rate; int num_windows; SDL_Window **windows; /* Renderer info */ const char *renderdriver; Uint32 render_flags; SDL_bool skip_renderer; SDL_Renderer **renderers; SDL_Texture **targets; /* Audio info */ const char *audiodriver; SDL_AudioSpec audiospec; /* GL settings */ int gl_red_size; int gl_green_size; int gl_blue_size; int gl_alpha_size; int gl_buffer_size; int gl_depth_size; int gl_stencil_size; int gl_double_buffer; int gl_accum_red_size; int gl_accum_green_size; int gl_accum_blue_size; int gl_accum_alpha_size; int gl_stereo; int gl_multisamplebuffers; int gl_multisamplesamples; int gl_retained_backing; int gl_accelerated; int gl_major_version; int gl_minor_version; int gl_debug; int gl_profile_mask; /* Additional fields added in 2.0.18 */ SDL_Rect confine; } SDLTest_CommonState; #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* Function prototypes */ /** * \brief Parse command line parameters and create common state. * * \param argv Array of command line parameters * \param flags Flags indicating which subsystem to initialize (i.e. SDL_INIT_VIDEO | SDL_INIT_AUDIO) * * \returns a newly allocated common state object. */ SDLTest_CommonState *SDLTest_CommonCreateState(char **argv, Uint32 flags); /** * \brief Process one common argument. * * \param state The common state describing the test window to create. * \param index The index of the argument to process in argv[]. * * \returns the number of arguments processed (i.e. 1 for --fullscreen, 2 for --video [videodriver], or -1 on error. */ int SDLTest_CommonArg(SDLTest_CommonState * state, int index); /** * \brief Logs command line usage info. * * This logs the appropriate command line options for the subsystems in use * plus other common options, and then any application-specific options. * This uses the SDL_Log() function and splits up output to be friendly to * 80-character-wide terminals. * * \param state The common state describing the test window for the app. * \param argv0 argv[0], as passed to main/SDL_main. * \param options an array of strings for application specific options. The last element of the array should be NULL. */ void SDLTest_CommonLogUsage(SDLTest_CommonState * state, const char *argv0, const char **options); /** * \brief Returns common usage information * * You should (probably) be using SDLTest_CommonLogUsage() instead, but this * function remains for binary compatibility. Strings returned from this * function are valid until SDLTest_CommonQuit() is called, in which case * those strings' memory is freed and can no longer be used. * * \param state The common state describing the test window to create. * \returns a string with usage information */ const char *SDLTest_CommonUsage(SDLTest_CommonState * state); /** * \brief Open test window. * * \param state The common state describing the test window to create. * * \returns SDL_TRUE if initialization succeeded, false otherwise */ SDL_bool SDLTest_CommonInit(SDLTest_CommonState * state); /** * \brief Easy argument handling when test app doesn't need any custom args. * * \param state The common state describing the test window to create. * \param argc argc, as supplied to SDL_main * \param argv argv, as supplied to SDL_main * * \returns SDL_FALSE if app should quit, true otherwise. */ SDL_bool SDLTest_CommonDefaultArgs(SDLTest_CommonState * state, const int argc, char **argv); /** * \brief Common event handler for test windows. * * \param state The common state used to create test window. * \param event The event to handle. * \param done Flag indicating we are done. * */ void SDLTest_CommonEvent(SDLTest_CommonState * state, SDL_Event * event, int *done); /** * \brief Close test window. * * \param state The common state used to create test window. * */ void SDLTest_CommonQuit(SDLTest_CommonState * state); /** * \brief Draws various window information (position, size, etc.) to the renderer. * * \param renderer The renderer to draw to. * \param window The window whose information should be displayed. * \param usedHeight Returns the height used, so the caller can draw more below. * */ void SDLTest_CommonDrawWindowInfo(SDL_Renderer * renderer, SDL_Window * window, int * usedHeight); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_test_common_h_ */ /* vi: set ts=4 sw=4 expandtab: */
a11c755a626b38af6e30ee127c804107d2f951f3
50dd46b8ece33f3cdd174284b15d1d51f89669d4
/third_party/tomcrypt/src/encauth/chachapoly/chacha20poly1305_setiv.c
5b48fdb37be9e4f347a1a0275c2b405ff050cb71
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
google/google-ctf
f99da1ee07729bbccb869fff1cbaed6a80e43bcc
df02323eaf945d15e124801c74abaadca2749dc7
refs/heads/master
2023-08-31T14:30:27.548081
2023-08-29T13:04:20
2023-08-29T13:04:20
131,317,137
4,136
607
Apache-2.0
2023-08-30T22:17:02
2018-04-27T15:56:03
Go
UTF-8
C
false
false
1,996
c
chacha20poly1305_setiv.c
/* LibTomCrypt, modular cryptographic library -- Tom St Denis * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. */ #include "tomcrypt_private.h" #ifdef LTC_CHACHA20POLY1305_MODE /** Set IV + counter data to the ChaCha20Poly1305 state and reset the context @param st The ChaCha20Poly1305 state @param iv The IV data to add @param ivlen The length of the IV (must be 12 or 8) @return CRYPT_OK on success */ int chacha20poly1305_setiv(chacha20poly1305_state *st, const unsigned char *iv, unsigned long ivlen) { chacha_state tmp_st; int i, err; unsigned char polykey[32]; LTC_ARGCHK(st != NULL); LTC_ARGCHK(iv != NULL); LTC_ARGCHK(ivlen == 12 || ivlen == 8); /* set IV for chacha20 */ if (ivlen == 12) { /* IV 96bit */ if ((err = chacha_ivctr32(&st->chacha, iv, ivlen, 1)) != CRYPT_OK) return err; } else { /* IV 64bit */ if ((err = chacha_ivctr64(&st->chacha, iv, ivlen, 1)) != CRYPT_OK) return err; } /* copy chacha20 key to temporary state */ for(i = 0; i < 12; i++) tmp_st.input[i] = st->chacha.input[i]; tmp_st.rounds = 20; /* set IV */ if (ivlen == 12) { /* IV 32bit */ if ((err = chacha_ivctr32(&tmp_st, iv, ivlen, 0)) != CRYPT_OK) return err; } else { /* IV 64bit */ if ((err = chacha_ivctr64(&tmp_st, iv, ivlen, 0)) != CRYPT_OK) return err; } /* (re)generate new poly1305 key */ if ((err = chacha_keystream(&tmp_st, polykey, 32)) != CRYPT_OK) return err; /* (re)initialise poly1305 */ if ((err = poly1305_init(&st->poly, polykey, 32)) != CRYPT_OK) return err; st->ctlen = 0; st->aadlen = 0; st->aadflg = 1; return CRYPT_OK; } #endif /* ref: HEAD -> develop */ /* git commit: 9c0d7085234bd6baba2ab8fd9eee62254599341c */ /* commit time: 2018-10-15 10:51:17 +0200 */
7176c5ed21c53a748e339af60245571d8e455c52
88ae8695987ada722184307301e221e1ba3cc2fa
/native_client/src/shared/platform/posix/nacl_threads_types.h
d1ca5f5acf3b6d07dca65eafebcc67b8c1fdd67d
[ "BSD-3-Clause", "Zlib", "Classpath-exception-2.0", "BSD-Source-Code", "LZMA-exception", "LicenseRef-scancode-unicode", "LGPL-3.0-only", "LGPL-2.0-or-later", "LicenseRef-scancode-philippe-de-muyter", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-intel-osl-1993", "HPND-sell-variant", "ICU", "LicenseRef-scancode-protobuf", "bzip2-1.0.6", "Spencer-94", "NCSA", "LicenseRef-scancode-nilsson-historical", "CC0-1.0", "LicenseRef-scancode-proprietary-license", "LGPL-2.1-only", "LicenseRef-scancode-other-copyleft", "GPL-2.0-or-later", "NTP", "GPL-2.0-only", "LicenseRef-scancode-other-permissive", "GPL-3.0-only", "GFDL-1.1-only", "W3C", "LicenseRef-scancode-python-cwi", "GCC-exception-3.1", "BSL-1.0", "Python-2.0", "GPL-1.0-or-later", "LGPL-2.1-or-later", "LicenseRef-scancode-unknown-license-reference", "CPL-1.0", "GFDL-1.1-or-later", "W3C-19980720", "LGPL-2.0-only", "LicenseRef-scancode-amd-historical", "LicenseRef-scancode-ietf", "SAX-PD", "LicenseRef-scancode-x11-hanson", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "dtoa", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "PSF-2.0", "LicenseRef-scancode-newlib-historical", "LicenseRef-scancode-generic-exception", "SMLNJ", "HP-1986", "LicenseRef-scancode-free-unknown", "SunPro", "MPL-1.1" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C
false
false
602
h
nacl_threads_types.h
/* * Copyright 2008 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* * NaCl Server Runtime threads implementation layer. */ #ifndef NATIVE_CLIENT_SRC_TRUSTED_PLATFORM_LINUX_NACL_THREADS_TYPES_H_ #define NATIVE_CLIENT_SRC_TRUSTED_PLATFORM_LINUX_NACL_THREADS_TYPES_H_ #include <pthread.h> #include "native_client/src/include/nacl_base.h" EXTERN_C_BEGIN struct NaClThread { pthread_t tid; }; EXTERN_C_END #endif /* NATIVE_CLIENT_SRC_TRUSTED_PLATFORM_LINUX_NACL_THREADS_TYPES_H_ */
241bae3421152398f33a7bbf618e0f0a4bdaaead
1248f70e2bde2898dee5c675adfe36429702b1a0
/llib/lxml.c
41a9a340cec83b7ed7b694123eddc21f0b671d18
[]
no_license
dgod/yong
d009b12cd6e78eeae33a3a3f4ea445aaa7378c60
a7a1f83a0bea4078ee3e615c1a0018f8aef37b2e
refs/heads/master
2023-06-25T08:48:07.342805
2023-06-11T01:55:31
2023-06-11T01:55:31
62,427,557
173
46
null
2018-08-10T01:31:01
2016-07-02T01:03:35
C
UTF-8
C
false
false
9,792
c
lxml.c
#include <ctype.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include "lmem.h" #include "ltypes.h" #include "lstring.h" #include "lslist.h" #include "lxml.h" enum{ REQ_ANY, REQ_PROLOG, REQ_LT, REQ_SYMBOL, REQ_EQ, REQ_STRING, REQ_END, }; enum{ TOK_NONE=0, TOK_PROLOG, TOK_SYMBOL, TOK_STRING, TOK_DATA, TOK_END, TOK_EOF, TOK_LT='<', TOK_GT='>', TOK_EQ='=', TOK_EGT='/', }; static void skip_space(LXml *xml) { int c; while((c=*xml->data)!=0) { if(!isspace(c)) { break; } xml->data++; } } static int next_token(LXml *xml,int peek) { const char *p; int c; restart: skip_space(xml); p=xml->data; c=p[0]; if(!c && xml->status==REQ_LT) return TOK_EOF; if(c) switch(c){ case '<': if(xml->intag) break; if(p[1]=='/') { if(xml->status==REQ_END || xml->status==REQ_ANY) { if(!peek) xml->data+=2; return TOK_END; } } else if(p[1]=='?') { if(xml->status==REQ_PROLOG || xml->status==REQ_ANY) { if(!peek) xml->data+=2; return TOK_PROLOG; } } else if(p[1]=='!') { xml->data+=2; while((c=*xml->data)!=0) { xml->data++; if(c=='>') break; } goto restart; } else if(xml->status==REQ_ANY || xml->status==REQ_LT) { if(!peek) xml->data++; return TOK_LT; } break; case '>': if(!xml->intag) break; if(xml->status==REQ_ANY) { if(!peek) xml->data++; return TOK_GT; } break; case '\"': if(xml->intag) { if(xml->status==REQ_STRING) { if(!peek) xml->data++; return TOK_STRING; } } else if(xml->status==REQ_ANY) { return TOK_DATA; } break; case '=': if(xml->intag) { if(xml->status==REQ_EQ) { if(!peek) xml->data++; return TOK_EQ; } break; } else if(xml->status==REQ_ANY) { return TOK_DATA; } break; case '/': if(xml->intag) { if(xml->status==REQ_ANY && p[1]=='>') { if(!peek) xml->data+=2; return TOK_EGT; } } else { return TOK_DATA; } default: if(xml->intag) { return TOK_SYMBOL; } else if(xml->status==REQ_ANY) { return TOK_DATA; } break; } return TOK_NONE; } static int load_prolog(LXml *xml) { int tok; const char *p; xml->status=REQ_ANY; tok=next_token(xml,1); if(tok==TOK_LT) return 0; if(tok!=TOK_PROLOG) return -1; p=strstr(xml->data,"?>"); if(!p) return -1; xml->data=p+2; return 0; } static char *load_data(LXml *xml) { char temp[128]; int i; int c; for(i=0;i<128;) { c=*xml->data; if(c==0) return NULL; if(c=='<') break; xml->data++; if(c=='&') { if(!strncmp(xml->data,"lt;",3)) { xml->data+=3; temp[i++]='<'; } else if(!strncmp(xml->data,"gt;",3)) { xml->data+=3; temp[i++]='>'; } else if(!strncmp(xml->data,"amp;",4)) { xml->data+=4; temp[i++]='&'; } else if(!strncmp(xml->data,"quot;",5)) { xml->data+=5; temp[i++]='\"'; } else if(!strncmp(xml->data,"apos;",5)) { printf("here\n"); xml->data+=5; temp[i++]='\''; } else if(!strncmp(xml->data,"nbsp;",5)) { xml->data+=5; temp[i++]=' '; } else if(xml->data[0]=='#' && isdigit(xml->data[1])) { char *end; long code=strtol(xml->data+1,&end,10); if(*end!=';') return NULL; xml->data=end+1; temp[i++]=(char)(code&0x7f); } else { temp[i++]=c; } } else { temp[i++]=c; } } temp[i]=0; return l_strdup(temp); } static char *load_symbol(LXml *xml) { char temp[64]; int i; int c; skip_space(xml); for(i=0;i<63;i++) { c=*xml->data; if(c==' ' || c=='=' || c=='>' || c=='/') { if(i>1 && temp[i-1]==':') return NULL; break; } if(isalnum(c) || c=='_' || (i!=0 && c==':')) { if(i==0 && isdigit(c)) return NULL; temp[i]=c; xml->data++; } else { return NULL; } } if(i==0) return NULL; temp[i]=0; return l_strdup(temp); } static char *load_string(LXml *xml) { char temp[128]; int i; int c; for(i=0;i<128;) { c=*xml->data++; if(c==0) return NULL; if(c=='\"') break; if(c=='&') { if(!strncmp(xml->data,"lt;",3)) { xml->data+=3; temp[i++]='<'; } else if(!strncmp(xml->data,"gt;",3)) { xml->data+=3; temp[i++]='>'; } else if(!strncmp(xml->data,"amp;",4)) { xml->data+=4; temp[i++]='&'; } else if(!strncmp(xml->data,"quot;",5)) { xml->data+=5; temp[i++]='\"'; } else if(!strncmp(xml->data,"apos;",5)) { printf("here\n"); xml->data+=5; temp[i++]='\''; } else if(!strncmp(xml->data,"nbsp;",5)) { xml->data+=5; temp[i++]=' '; } else if(xml->data[0]=='#' && isdigit(xml->data[1])) { char *end; long code=strtol(xml->data+1,&end,10); if(*end!=';') return NULL; xml->data=end+1; temp[i++]=(char)(code&0x7f); } else { temp[i++]=c; } } else { temp[i++]=c; } } temp[i]=0; return l_strdup(temp); } static int load_prop(LXml *xml) { LXmlNode *cur=xml->cur; LXmlProp *prop; prop=l_new0(LXmlProp); cur->prop=l_slist_append(cur->prop,prop); prop->name=load_symbol(xml); if(!prop) return -1; xml->status=REQ_EQ; if(next_token(xml,0)!=TOK_EQ) return -1; xml->status=REQ_STRING; if(next_token(xml,0)!=TOK_STRING) { return -1; } prop->value=load_string(xml); if(!prop->value) return -1; return 0; } static int load_node(LXml *xml) { int tok; tok=next_token(xml,1); if(tok==TOK_LT) { LXmlNode *node; xml->deep++; node=l_new0(LXmlNode); xml->cur->child=l_slist_append(xml->cur->child,node); node->parent=xml->cur; xml->cur=node; next_token(xml,0); xml->intag=1; xml->status=REQ_SYMBOL; tok=next_token(xml,0); if(tok!=TOK_SYMBOL) return -1; node->name=load_symbol(xml); if(!node->name) return -1; while(1) { xml->status=REQ_ANY; tok=next_token(xml,1); if(tok==TOK_SYMBOL) { if(0!=load_prop(xml)) { return -1; } } else if(tok==TOK_GT) { next_token(xml,0); xml->intag=0; break; } else if(tok==TOK_EGT) { next_token(xml,0); xml->intag=0; xml->cur=xml->cur->parent; xml->deep--; return 0; } else { return -1; } } if(tok==TOK_GT) { do{ xml->status=REQ_ANY; if(0!=load_node(xml)) return -1; }while(xml->cur==node); return 0; } } else if(tok==TOK_DATA) { if(!xml->cur->name || xml->cur->data) return -1; xml->cur->data=load_data(xml); xml->status=REQ_END; return 0; } else if(tok==TOK_END) { int len=strlen(xml->cur->name); next_token(xml,0); if(memcmp(xml->cur->name,xml->data,len)) return -1; xml->data+=len; if(xml->data[0]!='>') return -1; xml->data++; xml->cur=xml->cur->parent; xml->deep--; xml->status=REQ_LT; return 0; } else if(tok==TOK_EOF) { return 0; } return -1; } static void free_prop(LXmlProp *prop) { if(!prop) return; l_free(prop->name); l_free(prop->value); l_free(prop); } static void free_node(LXmlNode *node) { if(!node) return; l_slist_free(node->child,(LFreeFunc)free_node); l_slist_free(node->prop,(LFreeFunc)free_prop); l_free(node->name); l_free(node->data); l_free(node); } void l_xml_free(LXml *x) { if(!x) return; l_slist_free(x->root.child,(LFreeFunc)free_node); l_free(x); } LXml *l_xml_load(const char *data) { LXml *x; if(!data) return NULL; x=l_new0(LXml); x->data=data; if(0!=load_prolog(x)) { l_xml_free(x); return NULL; } x->cur=&x->root; while(x->data[0]!=0) { x->status=REQ_LT; if(0!=load_node(x)) { printf("%s\n",x->data); l_xml_free(x); return NULL; } } if(x->deep!=0) { l_xml_free(x); return NULL; } return x; } LXmlNode *l_xml_get_child(const LXmlNode *node,const char *name) { LXmlNode *p; for(p=node->child;p!=NULL;p=p->next) { if(!strcmp(p->name,name)) return p; } return NULL; } const char *l_xml_get_prop(const LXmlNode *node,const char *name) { LXmlProp *p; for(p=node->prop;p!=NULL;p=p->next) { if(!strcmp(p->name,name)) return p->value; } return NULL; } #if 0 static void dump_string(LString *s,const char *p,int data) { int c; while((c=*p++)!=0) { switch(c){ case '<': l_string_append(s,"&lt;",4); break; case '>': l_string_append(s,"&gt;",4); break; case '&': l_string_append(s,"&amp;",5); break; case '\"': l_string_append(s,"&quot;",6); break; case '\'': l_string_append(s,"&apos;",6); break; /* xml not have space entity case ' ': if(data) { l_string_append(s,"&nbsp;",6); break; } */ default: l_string_append_c(s,c); break; } } } static void dump_node(LXml *xml,LXmlNode *node,LString *s) { LXmlProp *pp; LXmlNode *pn; int i; for(i=0;i<xml->deep;i++) l_string_append_c(s,'\t'); l_string_append_c(s,'<'); l_string_append(s,node->name,-1); for(pp=node->prop;pp!=NULL;pp=pp->next) { l_string_append_c(s,' '); l_string_append(s,pp->name,-1); l_string_append_c(s,'='); l_string_append_c(s,'\"'); dump_string(s,pp->value,0); l_string_append_c(s,'\"'); } l_string_append_c(s,'>'); if(node->child) { l_string_append_c(s,'\n'); xml->deep++; for(pn=node->child;pn!=NULL;pn=pn->next) dump_node(xml,pn,s); xml->deep--; } else if(node->data) { dump_string(s,node->data,1); } if(node->child) { for(i=0;i<xml->deep;i++) l_string_append_c(s,'\t'); } l_string_append(s,"</",2); l_string_append(s,node->name,-1); l_string_append(s,">\n",2); } char *l_xml_dump(LXml *xml) { char *res; LString *s; LXmlNode *p; if(!xml) return NULL; s=l_string_new(512); printf("<?xml version=\"1.0\" encoding=\"utf8\"?>\n"); for(p=xml->root.child;p!=NULL;p=p->next) dump_node(xml,p,s); res=s->str;s->str=NULL; l_string_free(s); return res; } #endif
bf2e18f60e7fe550e4b2b18e7c055ecfc8685e73
83e7dc1281874779c46dfadcc15b2bb66d8e599c
/demos/multilang/assets/emojis/img_emoji_artist_palette.c
5b8593c678d2499614a7f4a04ced524f818ae5da
[ "MIT" ]
permissive
lvgl/lvgl
7d51d6774d6ac71df7101fc7ded56fea4b70be01
5c984b4a5364b6455966eb3a860153806c51626f
refs/heads/master
2023-08-30T22:39:20.283922
2023-08-30T19:55:29
2023-08-30T19:55:29
60,667,730
9,296
2,218
MIT
2023-09-14T17:59:34
2016-06-08T04:14:34
C
UTF-8
C
false
false
9,127
c
img_emoji_artist_palette.c
#ifdef __has_include #if __has_include("lvgl.h") #ifndef LV_LVGL_H_INCLUDE_SIMPLE #define LV_LVGL_H_INCLUDE_SIMPLE #endif #endif #endif #if defined(LV_LVGL_H_INCLUDE_SIMPLE) #include "lvgl.h" #else #include "lvgl/lvgl.h" #endif #if LV_USE_DEMO_MULTILANG #ifndef LV_ATTRIBUTE_MEM_ALIGN #define LV_ATTRIBUTE_MEM_ALIGN #endif #ifndef LV_ATTRIBUTE_IMG_IMG_EMOJI_ARTIST_PALETTE #define LV_ATTRIBUTE_IMG_IMG_EMOJI_ARTIST_PALETTE #endif const LV_ATTRIBUTE_MEM_ALIGN LV_ATTRIBUTE_LARGE_CONST LV_ATTRIBUTE_IMG_IMG_EMOJI_ARTIST_PALETTE uint8_t img_emoji_artist_palette_map[] = { 0xfe, 0xfa, 0xff, 0xff, 0xf0, 0xf4, 0xf9, 0xff, 0xf1, 0xff, 0xff, 0xff, 0xf0, 0xfa, 0xff, 0xff, 0xff, 0xf8, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xfc, 0xf3, 0xe9, 0xff, 0xef, 0xff, 0xed, 0xff, 0xf3, 0xff, 0xff, 0xff, 0xe4, 0xf7, 0xfc, 0xff, 0xcd, 0xe6, 0xf0, 0xff, 0xcb, 0xe5, 0xf3, 0xff, 0xe6, 0xf6, 0xff, 0xff, 0xfb, 0xfa, 0xff, 0xff, 0xff, 0xf9, 0xff, 0xff, 0xff, 0xf8, 0xff, 0xff, 0xf0, 0xfe, 0xff, 0xff, 0xf8, 0xff, 0xff, 0xff, 0xfd, 0xfc, 0xff, 0xff, 0xf0, 0xff, 0xec, 0xff, 0xf3, 0xff, 0xea, 0xff, 0xfa, 0xff, 0xf4, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xf2, 0xf6, 0xf7, 0xff, 0xb2, 0xd8, 0xea, 0xff, 0x82, 0xca, 0xf4, 0xff, 0x85, 0xaa, 0xee, 0xff, 0x88, 0xb4, 0xf3, 0xff, 0x89, 0xc3, 0xf7, 0xff, 0x82, 0xc7, 0xef, 0xff, 0x78, 0xbe, 0xdc, 0xff, 0x82, 0xbe, 0xd6, 0xff, 0xa5, 0xd4, 0xe9, 0xff, 0xc7, 0xed, 0xff, 0xff, 0xf2, 0xf8, 0xfd, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xf3, 0xf9, 0xff, 0xff, 0xff, 0xeb, 0xff, 0xff, 0xff, 0xee, 0xff, 0xf7, 0xf1, 0xff, 0xff, 0xb7, 0xce, 0xee, 0xff, 0x88, 0xc1, 0xda, 0xff, 0x7a, 0xb1, 0xf4, 0xff, 0x5b, 0x76, 0xfc, 0xff, 0x32, 0x50, 0xe4, 0xff, 0x35, 0x62, 0xe2, 0xff, 0x58, 0x9a, 0xff, 0xff, 0x76, 0xcb, 0xff, 0xff, 0x6d, 0xce, 0xff, 0xff, 0x64, 0xc6, 0xee, 0xff, 0x69, 0xc6, 0xed, 0xff, 0x69, 0xc1, 0xe9, 0xff, 0xd5, 0xe2, 0xf2, 0xff, 0xf6, 0xf9, 0xfe, 0xff, 0xff, 0xfd, 0xfc, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xe1, 0xdf, 0xfc, 0xff, 0xa5, 0xb6, 0xff, 0xff, 0x68, 0xbc, 0xff, 0xff, 0x4f, 0xd0, 0xff, 0xff, 0x6a, 0xb4, 0xff, 0xff, 0x40, 0x2a, 0xd6, 0xff, 0x3e, 0x3b, 0xeb, 0xff, 0x2a, 0x37, 0xcf, 0xff, 0x46, 0x6d, 0xe1, 0xff, 0x6f, 0xae, 0xff, 0xff, 0x6f, 0xc1, 0xfb, 0xff, 0x70, 0xc8, 0xfe, 0xff, 0x72, 0xca, 0xff, 0xff, 0x60, 0xb7, 0xf9, 0xff, 0x95, 0xc2, 0xed, 0xff, 0xbc, 0xde, 0xfc, 0xff, 0xf3, 0xff, 0xff, 0xff, 0xb4, 0xf4, 0xf8, 0xff, 0x84, 0xd7, 0xf3, 0xff, 0x80, 0xbb, 0xf3, 0xff, 0x83, 0xcb, 0xed, 0xff, 0x62, 0xd3, 0xdd, 0xff, 0x66, 0xc4, 0xff, 0xff, 0x2c, 0x4d, 0xd9, 0xff, 0x37, 0x3b, 0xc9, 0xff, 0x3e, 0x4d, 0xc7, 0xff, 0x74, 0x97, 0xf1, 0xff, 0x9c, 0xd5, 0xff, 0xff, 0x87, 0xd0, 0xff, 0xff, 0x70, 0xc1, 0xfa, 0xff, 0x65, 0xb9, 0xff, 0xff, 0x51, 0xa5, 0xf7, 0xff, 0x57, 0xae, 0xf8, 0xff, 0x75, 0xc1, 0xfc, 0xff, 0xfc, 0xf1, 0xff, 0xff, 0x83, 0xd4, 0xe9, 0xff, 0x6c, 0xd1, 0xd3, 0xff, 0xb4, 0xb9, 0x8c, 0xff, 0xf7, 0xaf, 0x61, 0xff, 0xb8, 0x93, 0x59, 0xff, 0x8c, 0xb6, 0xc9, 0xff, 0x5f, 0xb0, 0xff, 0xff, 0x70, 0xa6, 0xfd, 0xff, 0x6f, 0xac, 0xf6, 0xff, 0x81, 0xc6, 0xff, 0xff, 0x80, 0xd2, 0xfc, 0xff, 0x66, 0xbf, 0xeb, 0xff, 0x59, 0xbb, 0xf1, 0xff, 0x63, 0xc7, 0xff, 0xff, 0x62, 0xc8, 0xff, 0xff, 0x40, 0xad, 0xff, 0xff, 0x56, 0xb6, 0xfc, 0xff, 0xfb, 0xf4, 0xff, 0xff, 0x73, 0xb2, 0xe4, 0xff, 0x6c, 0xa4, 0xb7, 0xff, 0xcb, 0x85, 0x31, 0xff, 0xff, 0x95, 0x0b, 0xff, 0xed, 0x7e, 0x2e, 0xff, 0xa4, 0xa3, 0xad, 0xff, 0x83, 0xc8, 0xff, 0xff, 0x6c, 0xc3, 0xff, 0xff, 0x73, 0xca, 0xff, 0xff, 0x79, 0xd0, 0xff, 0xff, 0x78, 0xd0, 0xfe, 0xff, 0x71, 0xcd, 0xfc, 0xff, 0x67, 0xc8, 0xff, 0xff, 0x57, 0xbc, 0xff, 0xff, 0x45, 0xad, 0xfa, 0xff, 0x52, 0xb2, 0xfe, 0xff, 0x6a, 0xbd, 0xfa, 0xff, 0x99, 0xde, 0xd3, 0xff, 0x5b, 0xb2, 0xfc, 0xff, 0x8d, 0xb3, 0xf4, 0xff, 0xbe, 0x7f, 0x43, 0xff, 0xf5, 0x8f, 0x0e, 0xff, 0xa5, 0x80, 0x3c, 0xff, 0x7a, 0x9d, 0xaa, 0xff, 0x8c, 0xcb, 0xed, 0xff, 0x69, 0xc0, 0xff, 0xff, 0x7d, 0xcd, 0xff, 0xff, 0x7e, 0xca, 0xff, 0xff, 0x75, 0xbe, 0xf8, 0xff, 0x79, 0xc1, 0xfd, 0xff, 0x78, 0xc4, 0xff, 0xff, 0x6c, 0xbc, 0xff, 0xff, 0x61, 0xb6, 0xff, 0xff, 0x67, 0xb5, 0xf0, 0xff, 0x89, 0xca, 0xf6, 0xff, 0x60, 0xaf, 0xe8, 0xff, 0x5d, 0xc6, 0xff, 0xff, 0x5a, 0xbd, 0xfb, 0xff, 0x7d, 0xb3, 0xd2, 0xff, 0x7f, 0x98, 0xc2, 0xff, 0x6a, 0x98, 0xe6, 0xff, 0x7a, 0xc5, 0xff, 0xff, 0x70, 0xca, 0xe8, 0xff, 0x8a, 0xd2, 0xf4, 0xff, 0x74, 0xca, 0xff, 0xff, 0x6c, 0xbd, 0xff, 0xff, 0x78, 0xc0, 0xf0, 0xff, 0x72, 0xc7, 0xf7, 0xff, 0x4f, 0xbe, 0xff, 0xff, 0x50, 0xb6, 0xfe, 0xff, 0x75, 0xc1, 0xf1, 0xff, 0x9c, 0xcf, 0xd1, 0xff, 0xce, 0xf4, 0xf4, 0xff, 0x5d, 0xb5, 0xeb, 0xff, 0x51, 0xb1, 0xf7, 0xff, 0x49, 0xc0, 0xf7, 0xff, 0x59, 0xdf, 0xf1, 0xff, 0x66, 0xd1, 0xed, 0xff, 0x72, 0xb3, 0xfd, 0xff, 0x7f, 0xc0, 0xff, 0xff, 0x72, 0xce, 0xf7, 0xff, 0x60, 0xba, 0xe3, 0xff, 0x5c, 0xbd, 0xff, 0xff, 0x61, 0xbb, 0xff, 0xff, 0x76, 0xbd, 0xff, 0xff, 0x73, 0xc0, 0xfe, 0xff, 0x5b, 0xba, 0xff, 0xff, 0x6a, 0xbd, 0xf0, 0xff, 0x9b, 0xd1, 0xe2, 0xff, 0xde, 0xf1, 0xf8, 0xff, 0xf6, 0xff, 0xff, 0xff, 0x5e, 0xba, 0xef, 0xff, 0x4d, 0xab, 0xed, 0xff, 0x3e, 0xd2, 0xff, 0xff, 0x26, 0xf8, 0xff, 0xff, 0x33, 0xea, 0xfe, 0xff, 0x60, 0xc1, 0xff, 0xff, 0x6e, 0xad, 0xfd, 0xff, 0x62, 0xbf, 0xfc, 0xff, 0x72, 0xc4, 0xfb, 0xff, 0x60, 0xc1, 0xff, 0xff, 0x57, 0xb9, 0xff, 0xff, 0x62, 0xb8, 0xfe, 0xff, 0x66, 0xbb, 0xf3, 0xff, 0x6b, 0xbe, 0xf6, 0xff, 0xa6, 0xd8, 0xfc, 0xff, 0xfa, 0xff, 0xff, 0xff, 0xff, 0xfa, 0xff, 0xff, 0xff, 0xfa, 0xff, 0xff, 0x68, 0xb9, 0xf2, 0xff, 0x4c, 0xb3, 0xf2, 0xff, 0x3c, 0xdc, 0xff, 0xff, 0x16, 0xe2, 0xff, 0xff, 0x17, 0xcf, 0xf3, 0xff, 0x4c, 0xc2, 0xfd, 0xff, 0x5a, 0xad, 0xf8, 0xff, 0x5f, 0xb9, 0xff, 0xff, 0x86, 0xc5, 0xff, 0xff, 0x65, 0xb7, 0xff, 0xff, 0x57, 0xb1, 0xf8, 0xff, 0x6f, 0xc0, 0xe3, 0xff, 0x78, 0xc6, 0xdd, 0xff, 0x72, 0xba, 0xe4, 0xff, 0xa9, 0xcc, 0xf7, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xfe, 0xf8, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xff, 0x8f, 0xc4, 0xfd, 0xff, 0x43, 0xb2, 0xea, 0xff, 0x30, 0xc5, 0xff, 0xff, 0x33, 0xbd, 0xff, 0xff, 0x3e, 0xb9, 0xf7, 0xff, 0x4c, 0xcb, 0xf8, 0xff, 0x4d, 0xc0, 0xf3, 0xff, 0x6a, 0xc2, 0xff, 0xff, 0x63, 0xc0, 0xfd, 0xff, 0x60, 0xb4, 0xf6, 0xff, 0x92, 0xc5, 0xed, 0xff, 0xe6, 0xf4, 0xf2, 0xff, 0xe9, 0xfd, 0xf8, 0xff, 0x95, 0xcb, 0xee, 0xff, 0x6c, 0xaf, 0xee, 0xff, 0x8f, 0xc5, 0xff, 0xff, 0xd6, 0xee, 0xf4, 0xff, 0xf3, 0xff, 0xff, 0xff, 0xcd, 0xe5, 0xff, 0xff, 0x5a, 0xb6, 0xdf, 0xff, 0x2f, 0xa4, 0xe9, 0xff, 0x54, 0xa8, 0xff, 0xff, 0x65, 0xb7, 0xfe, 0xff, 0x4d, 0xc6, 0xd9, 0xff, 0x3f, 0xbe, 0xc6, 0xff, 0x5b, 0xb7, 0xda, 0xff, 0x3c, 0xc6, 0xf5, 0xff, 0x5f, 0xc1, 0xf7, 0xff, 0xc2, 0xd9, 0xf9, 0xff, 0xff, 0xfc, 0xf8, 0xff, 0xff, 0xfc, 0xfc, 0xff, 0xa2, 0xd2, 0xff, 0xff, 0x34, 0xa3, 0xf3, 0xff, 0x1e, 0xa5, 0xf7, 0xff, 0xb5, 0xde, 0xe1, 0xff, 0xe3, 0xff, 0xff, 0xff, 0xfa, 0xfb, 0xff, 0xff, 0xa2, 0xd4, 0xe8, 0xff, 0x51, 0xa7, 0xe3, 0xff, 0x4b, 0xa5, 0xff, 0xff, 0x4d, 0xae, 0xe8, 0xff, 0x41, 0xb4, 0xa0, 0xff, 0x42, 0xb8, 0x88, 0xff, 0x3b, 0xa2, 0x8d, 0xff, 0x3d, 0xaf, 0xd8, 0xff, 0x57, 0xb8, 0xf2, 0xff, 0x8f, 0xc4, 0xf7, 0xff, 0xc6, 0xd5, 0xef, 0xff, 0xb8, 0xd5, 0xf4, 0xff, 0x62, 0xb7, 0xfb, 0xff, 0x24, 0x9f, 0xf5, 0xff, 0x23, 0xa1, 0xef, 0xff, 0xc2, 0xdf, 0xe4, 0xff, 0xe6, 0xf7, 0xfa, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xe9, 0xf4, 0xf8, 0xff, 0x7e, 0xbf, 0xf2, 0xff, 0x2e, 0xa7, 0xfd, 0xff, 0x1b, 0x9f, 0xc7, 0xff, 0x3d, 0xaa, 0x7a, 0xff, 0x5c, 0xc1, 0x6c, 0xff, 0x2f, 0xa3, 0x62, 0xff, 0x5f, 0x93, 0xc1, 0xff, 0x5f, 0xaf, 0xf6, 0xff, 0x52, 0xb8, 0xff, 0xff, 0x40, 0xaf, 0xe7, 0xff, 0x30, 0xad, 0xe7, 0xff, 0x26, 0xac, 0xff, 0xff, 0x44, 0xab, 0xff, 0xff, 0x73, 0xae, 0xf3, 0xff, 0xef, 0xf8, 0xff, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xff, 0xfa, 0xff, 0xff, 0xff, 0xe5, 0xf7, 0xfe, 0xff, 0xb4, 0xd6, 0xe6, 0xff, 0x6f, 0xab, 0xc3, 0xff, 0x34, 0x8e, 0xac, 0xff, 0x19, 0x8d, 0xac, 0xff, 0x17, 0x98, 0xb9, 0xff, 0x3f, 0xb1, 0xfe, 0xff, 0x38, 0xb2, 0xff, 0xff, 0x30, 0xb2, 0xff, 0xff, 0x29, 0xa8, 0xff, 0xff, 0x30, 0x9d, 0xeb, 0xff, 0x59, 0xa7, 0xdc, 0xff, 0xa4, 0xd2, 0xea, 0xff, 0xe3, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0xf6, 0xf1, 0xff, 0xff, 0xfe, 0xfe, 0xff, 0xfa, 0xfd, 0xff, 0xff, 0xe9, 0xfa, 0xff, 0xff, 0xbe, 0xe3, 0xf7, 0xff, 0x8b, 0xc9, 0xe1, 0xff, 0x64, 0xb8, 0xd2, 0xff, 0x53, 0xb2, 0xcc, 0xff, 0x5c, 0xb1, 0xef, 0xff, 0x49, 0xa0, 0xe2, 0xff, 0x40, 0x9b, 0xde, 0xff, 0x59, 0xb0, 0xf0, 0xff, 0x88, 0xce, 0xff, 0xff, 0xb9, 0xe6, 0xff, 0xff, 0xe2, 0xf5, 0xff, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfb, 0xff, 0xff, 0xfe, 0xfe, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xfd, 0xfc, 0xff, 0xff, 0xf3, 0xfc, 0xff, 0xff, 0xdf, 0xf8, 0xff, 0xff, 0xc2, 0xea, 0xfc, 0xff, 0xad, 0xdf, 0xf3, 0xff, 0xa7, 0xd9, 0xff, 0xff, 0xa1, 0xd2, 0xfa, 0xff, 0xac, 0xd6, 0xf9, 0xff, 0xcb, 0xec, 0xff, 0xff, 0xe8, 0xfc, 0xff, 0xff, 0xf8, 0xfd, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xfe, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; const lv_img_dsc_t img_emoji_artist_palette = { .header.cf = LV_COLOR_FORMAT_ARGB8888, .header.always_zero = 0, .header.w = 18, .header.h = 19, .data = img_emoji_artist_palette_map, }; #endif
f1c950fde2a1642c34246e70c774db186f9f6f5a
3a30cfb29aac91e5c75d4dbcefddfd1f34d5f18c
/c-tests/gcc/20000112-1.c
8da71155671c6add9ff9d324fff184b141675cfc
[ "MIT", "MPL-1.0", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LGPL-2.0-only", "GPL-3.0-only", "GPL-2.0-only" ]
permissive
vnmakarov/mir
a1725bc9c828e8580df6b7ae94e04175db8abe93
928e28fb3acaa50d051a906e76a55cc48a556574
refs/heads/master
2023-09-02T11:10:37.434581
2023-08-25T19:25:40
2023-08-25T19:25:40
178,932,492
2,005
156
MIT
2023-08-01T20:29:59
2019-04-01T19:24:56
C
UTF-8
C
false
false
356
c
20000112-1.c
#include <string.h> extern void exit(int); static int special_format (fmt) const char *fmt; { return (strchr (fmt, '*') != 0 || strchr (fmt, 'V') != 0 || strchr (fmt, 'S') != 0 || strchr (fmt, 'n') != 0); } main() { if (special_format ("ee")) abort (); if (!special_format ("*e")) abort (); exit (0); }
4c0719ec928a0b5506cf0b4528bfb9a829d74b4d
5a921a79279fc5597e155c3833b1ecc230ab1831
/include/cglm/struct/vec2.h
555b818491ccdd5c015e8abdbc820a0f6b551a98
[ "MIT" ]
permissive
recp/cglm
fd233721ea8b215990e60c29ebf7b9b10af49e59
f496146bce3ac33e6a13a65baeb30d36d1e9bbfb
refs/heads/master
2023-09-04T07:49:30.193832
2023-08-30T10:03:16
2023-08-30T10:03:16
67,952,038
1,947
260
MIT
2023-09-06T21:17:35
2016-09-11T20:15:35
C
UTF-8
C
false
false
12,248
h
vec2.h
/* * Copyright (c), Recep Aslantas. * * MIT License (MIT), http://opensource.org/licenses/MIT * Full license can be found in the LICENSE file */ /* Macros: GLMS_VEC2_ONE_INIT GLMS_VEC2_ZERO_INIT GLMS_VEC2_ONE GLMS_VEC2_ZERO Functions: CGLM_INLINE vec2s glms_vec2(vec3s v3) CGLM_INLINE void glms_vec2_pack(vec2s dst[], vec2 src[], size_t len) CGLM_INLINE void glms_vec2_unpack(vec2 dst[], vec2s src[], size_t len) CGLM_INLINE vec2s glms_vec2_zero(void) CGLM_INLINE vec2s glms_vec2_one(void) CGLM_INLINE float glms_vec2_dot(vec2s a, vec2s b) CGLM_INLINE float glms_vec2_cross(vec2s a, vec2s b) CGLM_INLINE float glms_vec2_norm2(vec2s v) CGLM_INLINE float glms_vec2_norm(vec2s v) CGLM_INLINE vec2s glms_vec2_add(vec2s a, vec2s b) CGLM_INLINE vec2s glms_vec2_adds(vec2s a, float s) CGLM_INLINE vec2s glms_vec2_sub(vec2s a, vec2s b) CGLM_INLINE vec2s glms_vec2_subs(vec2s a, float s) CGLM_INLINE vec2s glms_vec2_mul(vec2s a, vec2s b) CGLM_INLINE vec2s glms_vec2_scale(vec2s v, float s) CGLM_INLINE vec2s glms_vec2_scale_as(vec2s v, float s) CGLM_INLINE vec2s glms_vec2_div(vec2s a, vec2s b) CGLM_INLINE vec2s glms_vec2_divs(vec2s a, float s) CGLM_INLINE vec2s glms_vec2_addadd(vec2s a, vec2s b, vec2s dest) CGLM_INLINE vec2s glms_vec2_subadd(vec2s a, vec2s b, vec2s dest) CGLM_INLINE vec2s glms_vec2_muladd(vec2s a, vec2s b, vec2s dest) CGLM_INLINE vec2s glms_vec2_muladds(vec2s a, float s, vec2s dest) CGLM_INLINE vec2s glms_vec2_maxadd(vec2s a, vec2s b, vec2s dest) CGLM_INLINE vec2s glms_vec2_minadd(vec2s a, vec2s b, vec2s dest) CGLM_INLINE vec2s glms_vec2_negate(vec2s v) CGLM_INLINE vec2s glms_vec2_normalize(vec2s v) CGLM_INLINE vec2s glms_vec2_rotate(vec2s v, float angle, vec2s axis) CGLM_INLINE float glms_vec2_distance(vec2s a, vec2s b) CGLM_INLINE float glms_vec2_distance2(vec2s a, vec2s b) CGLM_INLINE vec2s glms_vec2_maxv(vec2s a, vec2s b) CGLM_INLINE vec2s glms_vec2_minv(vec2s a, vec2s b) CGLM_INLINE vec2s glms_vec2_clamp(vec2s v, float minVal, float maxVal) CGLM_INLINE vec2s glms_vec2_lerp(vec2s from, vec2s to, float t) CGLM_INLINE vec2s glms_vec2_make(float * restrict src) */ #ifndef cglms_vec2s_h #define cglms_vec2s_h #include "../common.h" #include "../types-struct.h" #include "../util.h" #include "../vec2.h" #include "vec2-ext.h" #define GLMS_VEC2_ONE_INIT {GLM_VEC2_ONE_INIT} #define GLMS_VEC2_ZERO_INIT {GLM_VEC2_ZERO_INIT} #define GLMS_VEC2_ONE ((vec2s)GLMS_VEC2_ONE_INIT) #define GLMS_VEC2_ZERO ((vec2s)GLMS_VEC2_ZERO_INIT) /*! * @brief init vec2 using vec2 * * @param[in] v3 vector3 * @returns destination */ CGLM_INLINE vec2s glms_vec2(vec3s v3) { vec2s r; glm_vec2(v3.raw, r.raw); return r; } /*! * @brief pack an array of vec2 into an array of vec2s * * @param[out] dst array of vec2 * @param[in] src array of vec2s * @param[in] len number of elements */ CGLM_INLINE void glms_vec2_(pack)(vec2s dst[], vec2 src[], size_t len) { size_t i; for (i = 0; i < len; i++) { glm_vec2_copy(src[i], dst[i].raw); } } /*! * @brief unpack an array of vec2s into an array of vec2 * * @param[out] dst array of vec2s * @param[in] src array of vec2 * @param[in] len number of elements */ CGLM_INLINE void glms_vec2_(unpack)(vec2 dst[], vec2s src[], size_t len) { size_t i; for (i = 0; i < len; i++) { glm_vec2_copy(src[i].raw, dst[i]); } } /*! * @brief make vector zero * * @returns zero vector */ CGLM_INLINE vec2s glms_vec2_(zero)(void) { vec2s r; glm_vec2_zero(r.raw); return r; } /*! * @brief make vector one * * @returns one vector */ CGLM_INLINE vec2s glms_vec2_(one)(void) { vec2s r; glm_vec2_one(r.raw); return r; } /*! * @brief vec2 dot product * * @param[in] a vector1 * @param[in] b vector2 * * @return dot product */ CGLM_INLINE float glms_vec2_(dot)(vec2s a, vec2s b) { return glm_vec2_dot(a.raw, b.raw); } /*! * @brief vec2 cross product * * REF: http://allenchou.net/2013/07/cross-product-of-2d-vectors/ * * @param[in] a vector1 * @param[in] b vector2 * * @return Z component of cross product */ CGLM_INLINE float glms_vec2_(cross)(vec2s a, vec2s b) { return glm_vec2_cross(a.raw, b.raw); } /*! * @brief norm * norm (magnitude) of vec * * we can use this func instead of calling norm * norm, because it would call * sqrtf fuction twice but with this func we can avoid func call, maybe this is * not good name for this func * * @param[in] v vector * * @return norm * norm */ CGLM_INLINE float glms_vec2_(norm2)(vec2s v) { return glm_vec2_norm2(v.raw); } /*! * @brief norm (magnitude) of vec2 * * @param[in] v vector * * @return norm */ CGLM_INLINE float glms_vec2_(norm)(vec2s v) { return glm_vec2_norm(v.raw); } /*! * @brief add a vector to b vector store result in dest * * @param[in] a vector1 * @param[in] b vector2 * @returns destination vector */ CGLM_INLINE vec2s glms_vec2_(add)(vec2s a, vec2s b) { vec2s r; glm_vec2_add(a.raw, b.raw, r.raw); return r; } /*! * @brief add scalar to v vector store result in dest (d = v + s) * * @param[in] a vector * @param[in] s scalar * @returns destination vector */ CGLM_INLINE vec2s glms_vec2_(adds)(vec2s a, float s) { vec2s r; glm_vec2_adds(a.raw, s, r.raw); return r; } /*! * @brief subtract b vector from a vector store result in dest * * @param[in] a vector1 * @param[in] b vector2 * @returns destination vector */ CGLM_INLINE vec2s glms_vec2_(sub)(vec2s a, vec2s b) { vec2s r; glm_vec2_sub(a.raw, b.raw, r.raw); return r; } /*! * @brief subtract scalar from v vector store result in dest (d = v - s) * * @param[in] a vector * @param[in] s scalar * @returns destination vector */ CGLM_INLINE vec2s glms_vec2_(subs)(vec2s a, float s) { vec2s r; glm_vec2_subs(a.raw, s, r.raw); return r; } /*! * @brief multiply two vectors (component-wise multiplication) * * @param a vector1 * @param b vector2 * @returns result = (a[0] * b[0], a[1] * b[1]) */ CGLM_INLINE vec2s glms_vec2_(mul)(vec2s a, vec2s b) { vec2s r; glm_vec2_mul(a.raw, b.raw, r.raw); return r; } /*! * @brief multiply/scale vec2 vector with scalar: result = v * s * * @param[in] v vector * @param[in] s scalar * @returns destination vector */ CGLM_INLINE vec2s glms_vec2_(scale)(vec2s v, float s) { vec2s r; glm_vec2_scale(v.raw, s, r.raw); return r; } /*! * @brief make vec2 vector scale as specified: result = unit(v) * s * * @param[in] v vector * @param[in] s scalar * @returns destination vector */ CGLM_INLINE vec2s glms_vec2_(scale_as)(vec2s v, float s) { vec2s r; glm_vec2_scale_as(v.raw, s, r.raw); return r; } /*! * @brief div vector with another component-wise division: d = a / b * * @param[in] a vector 1 * @param[in] b vector 2 * @returns result = (a[0]/b[0], a[1]/b[1]) */ CGLM_INLINE vec2s glms_vec2_(div)(vec2s a, vec2s b) { vec2s r; glm_vec2_div(a.raw, b.raw, r.raw); return r; } /*! * @brief div vector with scalar: d = v / s * * @param[in] a vector * @param[in] s scalar * @returns result = (a[0]/s, a[1]/s) */ CGLM_INLINE vec2s glms_vec2_(divs)(vec2s a, float s) { vec2s r; glm_vec2_divs(a.raw, s, r.raw); return r; } /*! * @brief add two vectors and add result to sum * * it applies += operator so dest must be initialized * * @param[in] a vector 1 * @param[in] b vector 2 * @returns dest += (a + b) */ CGLM_INLINE vec2s glms_vec2_(addadd)(vec2s a, vec2s b, vec2s dest) { glm_vec2_addadd(a.raw, b.raw, dest.raw); return dest; } /*! * @brief sub two vectors and add result to dest * * it applies += operator so dest must be initialized * * @param[in] a vector 1 * @param[in] b vector 2 * @returns dest += (a + b) */ CGLM_INLINE vec2s glms_vec2_(subadd)(vec2s a, vec2s b, vec2s dest) { glm_vec2_subadd(a.raw, b.raw, dest.raw); return dest; } /*! * @brief mul two vectors and add result to dest * * it applies += operator so dest must be initialized * * @param[in] a vector 1 * @param[in] b vector 2 * @returns dest += (a * b) */ CGLM_INLINE vec2s glms_vec2_(muladd)(vec2s a, vec2s b, vec2s dest) { glm_vec2_muladd(a.raw, b.raw, dest.raw); return dest; } /*! * @brief mul vector with scalar and add result to sum * * it applies += operator so dest must be initialized * * @param[in] a vector * @param[in] s scalar * @returns dest += (a * b) */ CGLM_INLINE vec2s glms_vec2_(muladds)(vec2s a, float s, vec2s dest) { glm_vec2_muladds(a.raw, s, dest.raw); return dest; } /*! * @brief add max of two vectors to result/dest * * it applies += operator so dest must be initialized * * @param[in] a vector 1 * @param[in] b vector 2 * @returns dest += max(a, b) */ CGLM_INLINE vec2s glms_vec2_(maxadd)(vec2s a, vec2s b, vec2s dest) { glm_vec2_maxadd(a.raw, b.raw, dest.raw); return dest; } /*! * @brief add min of two vectors to result/dest * * it applies += operator so dest must be initialized * * @param[in] a vector 1 * @param[in] b vector 2 * @returns dest += min(a, b) */ CGLM_INLINE vec2s glms_vec2_(minadd)(vec2s a, vec2s b, vec2s dest) { glm_vec2_minadd(a.raw, b.raw, dest.raw); return dest; } /*! * @brief negate vector components * * @param[in] v vector * @returns negated vector */ CGLM_INLINE vec2s glms_vec2_(negate)(vec2s v) { glm_vec2_negate(v.raw); return v; } /*! * @brief normalize vec2 and store result in same vec * * @param[in] v vector * @returns normalized vector */ CGLM_INLINE vec2s glms_vec2_(normalize)(vec2s v) { glm_vec2_normalize(v.raw); return v; } /*! * @brief rotate vec2 by angle using Rodrigues' rotation formula * * @param[in] v vector * @param[in] angle angle by radians * @returns rotated vector */ CGLM_INLINE vec2s glms_vec2_(rotate)(vec2s v, float angle) { vec2s r; glm_vec2_rotate(v.raw, angle, r.raw); return r; } /** * @brief distance between two vectors * * @param[in] a vector1 * @param[in] b vector2 * @return distance */ CGLM_INLINE float glms_vec2_(distance)(vec2s a, vec2s b) { return glm_vec2_distance(a.raw, b.raw); } /** * @brief squared distance between two vectors * * @param[in] a vector1 * @param[in] b vector2 * @return squared distance (distance * distance) */ CGLM_INLINE float glms_vec2_(distance2)(vec2s a, vec2s b) { return glm_vec2_distance2(a.raw, b.raw); } /*! * @brief max values of vectors * * @param[in] a vector1 * @param[in] b vector2 * @returns destination */ CGLM_INLINE vec2s glms_vec2_(maxv)(vec2s a, vec2s b) { vec2s r; glm_vec2_maxv(a.raw, b.raw, r.raw); return r; } /*! * @brief min values of vectors * * @param[in] a vector1 * @param[in] b vector2 * @returns destination */ CGLM_INLINE vec2s glms_vec2_(minv)(vec2s a, vec2s b) { vec2s r; glm_vec2_minv(a.raw, b.raw, r.raw); return r; } /*! * @brief clamp vector's individual members between min and max values * * @param[in] v vector * @param[in] minVal minimum value * @param[in] maxVal maximum value * @returns clamped vector */ CGLM_INLINE vec2s glms_vec2_(clamp)(vec2s v, float minVal, float maxVal) { glm_vec2_clamp(v.raw, minVal, maxVal); return v; } /*! * @brief linear interpolation between two vectors * * formula: from + s * (to - from) * * @param[in] from from value * @param[in] to to value * @param[in] t interpolant (amount) * @returns destination */ CGLM_INLINE vec2s glms_vec2_(lerp)(vec2s from, vec2s to, float t) { vec2s r; glm_vec2_lerp(from.raw, to.raw, t, r.raw); return r; } /*! * @brief Create two dimensional vector from pointer * * @param[in] src pointer to an array of floats * @returns constructed 2D vector from raw pointer */ CGLM_INLINE vec2s glms_vec2_(make)(float * __restrict src) { vec2s dest; glm_vec2_make(src, dest.raw); return dest; } #endif /* cglms_vec2s_h */
02c12ef66148b8fd717b862b627d0c7d15597ff0
eaf22e8a8037df22471d111c421fa0a923f78ee6
/examples/tutorials/custom_timeline_feature/hawktracer-custom-timeline-feature.c
1b61115654f7ce64d063e14cf810954d67907a61
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
amzn/hawktracer
59eb51059231bdebd7bca5afc3626e55deed437b
3c22b3908912e2ec727fd2ddc5dbfe7464e6b4a5
refs/heads/master
2023-07-10T18:53:43.973288
2023-02-24T15:21:39
2023-02-24T15:36:23
128,848,910
131
41
MIT
2023-06-23T19:50:40
2018-04-10T00:17:00
C++
UTF-8
C
false
false
1,303
c
hawktracer-custom-timeline-feature.c
/** * @file hawktracer-custom-timeline-feature.c * The file demonstrates how to use custom timeline feature. */ /* Contains declaration of custome feature's API */ #include "push-counter-feature.h" #include <hawktracer.h> #include <stdio.h> int main(int argc, char** argv) { /* initialize HawkTracer library */ ht_init(argc, argv); /* register our custom feature */ PushCounterFeature_register(); HT_ErrorCode error_code; /* create timeline object. Instead, global timeline could be used (ht_global_timeline_get()) */ HT_Timeline* timeline = ht_timeline_create(1024, HT_FALSE, HT_FALSE, NULL, &error_code); if (!timeline) { printf("Failed to create timeline object: %d\n", error_code); return 1; } /* attach the feature to the timeline object */ push_counter_feature_enable(timeline); /* push 10 events to the timeline through the feature method */ for (int i = 0; i < 10; i++) { HT_DECL_EVENT(HT_Event, event) push_counter_feature_push_event(timeline, &event); } printf("Number of events pushed to the timeline: %d\n", push_counter_feature_get_count(timeline)); /* destroy the timeline. It will also destroy the feature */ ht_timeline_destroy(timeline); return 0; }
d6abfc3d0d33c2c9d8677931f1b4978d0ede7dd6
50e95229b9a1161ac294137120aaba94c9eb06bc
/sources/ippcp/aes_cfb_aesni_mb4.c
be702b1b9b64f577eb69cba4f63ee40203430f42
[ "Apache-2.0", "Intel" ]
permissive
intel/ipp-crypto
f0f05b87203705e82603db67bed5f8def13a5ee8
36e76e2388f3dd10cc440e213dfcf6ef59a0dfb8
refs/heads/develop
2023-09-04T08:15:06.851373
2023-07-27T12:47:12
2023-07-27T12:47:12
140,034,345
304
81
Apache-2.0
2023-08-30T17:18:36
2018-07-06T22:16:28
C
UTF-8
C
false
false
3,228
c
aes_cfb_aesni_mb4.c
/******************************************************************************* * Copyright (C) 2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions * and limitations under the License. * *******************************************************************************/ #include "owndefs.h" #include "owncp.h" #include "pcpaesm.h" #include "pcptool.h" #include "aes_cfb_aesni_mb.h" #if (_IPP32E>=_IPP32E_Y8) static inline void aes_encrypt4_aesni_mb4(__m128i blocks[4], __m128i enc_keys[4][15], int cipherRounds) { blocks[0] = _mm_xor_si128(blocks[0], enc_keys[0][0]); blocks[1] = _mm_xor_si128(blocks[1], enc_keys[1][0]); blocks[2] = _mm_xor_si128(blocks[2], enc_keys[2][0]); blocks[3] = _mm_xor_si128(blocks[3], enc_keys[3][0]); int nr; for (nr = 1; nr < cipherRounds; nr += 1) { blocks[0] = _mm_aesenc_si128(blocks[0], enc_keys[0][nr]); blocks[1] = _mm_aesenc_si128(blocks[1], enc_keys[1][nr]); blocks[2] = _mm_aesenc_si128(blocks[2], enc_keys[2][nr]); blocks[3] = _mm_aesenc_si128(blocks[3], enc_keys[3][nr]); } blocks[0] = _mm_aesenclast_si128(blocks[0], enc_keys[0][nr]); blocks[1] = _mm_aesenclast_si128(blocks[1], enc_keys[1][nr]); blocks[2] = _mm_aesenclast_si128(blocks[2], enc_keys[2][nr]); blocks[3] = _mm_aesenclast_si128(blocks[3], enc_keys[3][nr]); } IPP_OWN_DEFN (void, aes_cfb16_enc_aesni_mb4, (const Ipp8u* const source_pa[4], Ipp8u* const dst_pa[4], const int len[4], const int cipherRounds, const Ipp32u* enc_keys[4], const Ipp8u* pIV[4])) { __m128i* pSrc[4]; __m128i* pDst[4]; __m128i blocks[4]; __m128i plainBlocks[4]; int nBlocks[4]; int maxBlocks = 0; __m128i keySchedule[4][15]; for (int i = 0; i < 4; i++) { pSrc[i] = (__m128i*)source_pa[i]; pDst[i] = (__m128i*)dst_pa[i]; nBlocks[i] = len[i] / CFB16_BLOCK_SIZE; if(nBlocks[i] > 0) { blocks[i] = _mm_loadu_si128((__m128i const*)(pIV[i])); for (int j = 0; j <= cipherRounds; j++) { keySchedule[i][j] = _mm_loadu_si128((__m128i const*)enc_keys[i] + j); } } if (nBlocks[i] > maxBlocks) { maxBlocks = nBlocks[i]; } } for (int block = 0; block < maxBlocks; block++) { aes_encrypt4_aesni_mb4(blocks, keySchedule, cipherRounds); for (int i = 0; i < 4; i++) { if (nBlocks[i] > 0) { plainBlocks[i] = _mm_loadu_si128(pSrc[i]); blocks[i] = _mm_xor_si128(blocks[i], plainBlocks[i]); _mm_storeu_si128(pDst[i], blocks[i]); pSrc[i]+= 1; pDst[i]+= 1; nBlocks[i] -= 1; } } } } #endif
5f418490cd73c93ca7b4abd760ad7b28ffcbf38a
6ff85b80c6fe1b3ad5416a304b93551a5e80de10
/C/Algorithm/Compare.c
3fc1489def83675ff029fc2bc491d3c923b8be2f
[ "MIT" ]
permissive
maniero/SOpt
c600cc2333e0a47ce013be3516bbb8080502ff2a
5d17e1a9cbf115eaea6d30af2079d0c92ffff7a3
refs/heads/master
2023-08-10T16:48:46.058739
2023-08-10T13:42:17
2023-08-10T13:42:17
78,631,930
1,002
136
MIT
2023-01-28T12:10:01
2017-01-11T11:19:24
C#
UTF-8
C
false
false
314
c
Compare.c
#include <stdio.h> int Comparacao(int x, int y) { return x < y ? -1 : x != y; } int main(){ int a, b; puts("Digite um valor para a: "); scanf("%d", &a); puts("Digite um valor para b: "); scanf("%d", &b); printf("%d", Comparacao(a, b)); } //https://pt.stackoverflow.com/q/464605/101
f753689561f69957075fb12d62aac7e4da415042
b4c2b8dc89417e966a67a433267ebb9c156dbff4
/src/vehicles/sounds/straightPipedCompilationKnock.h
6a2859cb9093ccc29fd6352a0af0d75406422d17
[]
no_license
TheDIYGuy999/Rc_Engine_Sound_ESP32
92134030dbc047627310d54ccf1fd34fb3cad791
eeeb47964861b66f8e1db34bffe35657846d8b20
refs/heads/master
2023-08-31T00:17:03.698027
2023-05-04T19:46:51
2023-05-04T19:46:51
225,658,413
230
105
null
2023-08-26T14:38:39
2019-12-03T15:51:13
C
UTF-8
C
false
false
6,057
h
straightPipedCompilationKnock.h
const unsigned int knockSampleRate = 22050; const unsigned int knockSampleCount = 1270; const signed char knockSamples[] = { 0, 0, 3, 6, 8, 11, 14, 16, 17, 19, 20, 22, 25, 26, 27, 27, 27, 27, 26, 25, 25, 24, 24, 24, 23, 23, 22, 22, 21, 21, 21, 20, 20, 19, 17, 17, 15, 14, 14, 14, 14, 14, 14, 14, 14, 14, 13, 12, 11, 11, 10, 9, 9, 8, 8, 8, 8, 9, 10, 11, 12, 13, 14, 17, 18, 21, 23, 26, 30, 32, 36, 38, 42, 44, 47, 49, 51, 53, 55, 57, 60, 62, 64, 65, 66, 66, 66, 66, 66, 67, 67, 69, 69, 70, 71, 72, 73, 76, 78, 81, 84, 85, 88, 87, 87, 88, 89, 89, 91, 91, 91, 91, 91, 90, 89, 88, 87, 85, 83, 83, 82, 81, 81, 81, 81, 82, 83, 84, 85, 87, 88, 89, 89, 89, 88, 88, 87, 88, 87, 87, 88, 89, 89, 88, 87, 86, 85, 83, 82, 82, 81, 79, 78, 77, 75, 75, 75, 73, 73, 71, 70, 68, 66, 65, 63, 62, 61, 61, 61, 59, 57, 55, 53, 52, 50, 49, 46, 45, 44, 44, 44, 46, 47, 49, 51, 52, 53, 55, 56, 57, 58, 59, 61, 65, 68, 72, 76, 80, 84, 86, 88, 89, 90, 91, 92, 93, 94, 95, 96, 99, 101, 102, 104, 105, 106, 106, 105, 103, 101, 98, 96, 93, 92, 90, 89, 87, 85, 82, 79, 75, 72, 69, 62, 59, 56, 53, 50, 48, 45, 43, 42, 41, 40, 39, 37, 36, 35, 34, 34, 34, 35, 37, 40, 43, 46, 50, 53, 56, 59, 62, 63, 67, 69, 71, 72, 73, 74, 75, 76, 77, 76, 77, 76, 74, 73, 71, 68, 65, 63, 60, 58, 57, 56, 55, 54, 53, 52, 51, 50, 47, 45, 44, 42, 41, 41, 40, 40, 40, 40, 39, 40, 39, 39, 38, 38, 39, 39, 40, 41, 42, 44, 48, 51, 53, 56, 58, 59, 60, 61, 61, 62, 63, 64, 66, 67, 70, 72, 73, 74, 75, 76, 75, 74, 73, 71, 70, 69, 69, 68, 68, 67, 66, 64, 62, 60, 56, 53, 49, 46, 42, 39, 35, 34, 33, 33, 33, 33, 33, 32, 32, 31, 31, 30, 30, 31, 32, 34, 36, 40, 42, 44, 46, 47, 47, 47, 46, 45, 44, 43, 40, 38, 37, 36, 34, 33, 32, 31, 30, 28, 25, 23, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 11, 10, 9, 9, 8, 7, 7, 6, 5, 6, 7, 8, 10, 10, 10, 10, 9, 8, 8, 8, 8, 8, 8, 9, 10, 11, 12, 13, 13, 13, 13, 12, 11, 10, 9, 7, 6, 5, 4, 4, 4, 3, 3, 2, -1, -4, -9, -13, -17, -20, -22, -24, -25, -25, -25, -24, -24, -24, -24, -24, -25, -26, -27, -31, -32, -35, -37, -37, -38, -37, -37, -37, -35, -36, -36, -37, -39, -40, -42, -44, -46, -47, -48, -48, -49, -49, -49, -49, -49, -49, -50, -50, -50, -51, -52, -51, -51, -51, -50, -50, -50, -51, -52, -53, -55, -55, -57, -59, -60, -61, -61, -61, -61, -61, -60, -59, -58, -56, -55, -55, -55, -55, -55, -55, -56, -57, -57, -57, -57, -58, -59, -61, -63, -64, -65, -66, -67, -68, -69, -69, -69, -71, -72, -72, -73, -74, -74, -75, -76, -78, -81, -82, -83, -85, -85, -85, -84, -84, -84, -84, -85, -86, -88, -90, -93, -96, -98, -100, -101, -102, -103, -105, -107, -108, -109, -110, -110, -111, -112, -114, -116, -116, -118, -118, -118, -117, -114, -112, -109, -105, -103, -101, -100, -98, -96, -95, -94, -94, -94, -94, -95, -96, -97, -99, -101, -102, -105, -107, -109, -111, -113, -114, -117, -118, -119, -122, -125, -126, -127, -127, -126, -125, -123, -122, -119, -117, -114, -109, -107, -103, -99, -96, -92, -88, -85, -82, -79, -76, -71, -68, -65, -63, -60, -58, -56, -55, -54, -53, -52, -51, -48, -47, -45, -41, -39, -35, -33, -30, -28, -25, -22, -16, -12, -7, -1, 3, 9, 17, 22, 27, 32, 37, 44, 47, 49, 51, 52, 53, 55, 55, 55, 56, 56, 56, 56, 55, 54, 53, 52, 49, 48, 47, 47, 48, 49, 50, 52, 53, 54, 56, 57, 60, 61, 63, 64, 66, 69, 70, 72, 74, 76, 78, 81, 83, 85, 86, 86, 86, 86, 86, 86, 84, 84, 83, 82, 81, 80, 80, 79, 78, 77, 76, 75, 74, 73, 73, 73, 74, 75, 76, 78, 80, 81, 82, 83, 84, 85, 86, 88, 89, 90, 92, 93, 93, 94, 95, 96, 97, 98, 99, 100, 101, 101, 102, 102, 103, 103, 103, 104, 104, 104, 104, 104, 105, 105, 106, 107, 109, 110, 111, 113, 114, 114, 114, 113, 113, 112, 110, 108, 108, 106, 104, 103, 102, 100, 98, 96, 92, 89, 86, 83, 80, 75, 72, 67, 63, 57, 53, 47, 43, 40, 38, 36, 33, 30, 28, 26, 24, 23, 22, 22, 21, 22, 22, 22, 22, 22, 23, 23, 24, 24, 24, 24, 23, 22, 19, 16, 14, 12, 10, 8, 7, 5, 2, 1, -2, -5, -7, -10, -11, -12, -13, -13, -14, -14, -14, -14, -15, -17, -20, -22, -26, -28, -32, -36, -40, -44, -48, -51, -55, -60, -64, -67, -70, -73, -76, -82, -86, -90, -94, -97, -101, -103, -105, -106, -107, -108, -110, -111, -112, -112, -111, -110, -107, -106, -105, -103, -102, -100, -98, -98, -96, -96, -97, -97, -98, -98, -98, -98, -96, -96, -95, -95, -94, -93, -91, -89, -87, -84, -82, -81, -79, -77, -75, -72, -69, -67, -63, -59, -57, -55, -53, -50, -48, -46, -44, -42, -41, -39, -40, -41, -41, -42, -43, -46, -48, -50, -52, -54, -57, -59, -61, -63, -65, -67, -69, -70, -70, -70, -69, -68, -66, -65, -63, -60, -58, -54, -52, -49, -46, -43, -42, -40, -39, -39, -39, -38, -38, -37, -38, -38, -40, -41, -44, -46, -48, -49, -51, -53, -57, -59, -61, -65, -67, -70, -73, -75, -77, -78, -80, -82, -82, -82, -81, -79, -78, -76, -73, -70, -68, -66, -64, -61, -59, -57, -56, -54, -52, -52, -50, -50, -48, -48, -45, -44, -43, -42, -41, -39, -38, -37, -36, -34, -33, -32, -31, -31, -30, -29, -29, -28, -29, -28, -27, -27, -27, -26, -26, -26, -26, -26, -26, -26, -26, -27, -27, -27, -27, -28, -29, -28, -29, -30, -30, -31, -30, -31, -32, -34, -35, -37, -38, -40, -41, -43, -43, -43, -43, -42, -41, -41, -39, -37, -35, -32, -27, -24, -21, -19, -17, -15, -13, -11, -10, -9, -8, -8, -8, -8, -8, -8, -9, -10, -11, -12, -14, -16, -18, -21, -23, -27, -29, -31, -36, -38, -41, -43, -45, -47, -50, -51, -53, -54, -55, -56, -57, -57, -56, -55, -53, -51, -51, -49, -48, -46, -45, -44, -43, -43, -43, -42, -43, -44, -45, -46, -46, -46, -48, -49, -50, -51, -52, -54, -56, -58, -60, -62, -64, -66, -69, -70, -72, -72, -72, -72, -72, -71, -69, -68, -67, -64, -64, -63, -62, -61, -59, -58, -57, -56, -55, -54, -54, -53, -52, -53, -54, -55, -58, -59, -61, -62, -63, -64, -65, -65, -66, -66, -67, -67, -67, -66, -65, -66, -66, -67, -68, -68, -68, -67, -65, -64, -62, -59, -56, -55, -51, -49, -45, -43, -41, -38, -35, -33, -32, -31, -30, -29, -27, -26, -26, -26, -25, -24, -24, -24, -24, -24, -23, -23, -23, -23, -23, -22, -22, -22, -21, -21, -21, -20, -19, -18, -17, -17, -16, -15, -15, -15, -15, -15, -14, -13, -12, -10, -8, -7, -6, -1, 0, 0, };
8d3d79071e09d202beec3ad17ff8103441bb8e19
c67286cd386ecba8b729c6d292bfba8cfba0f43c
/portable/GCC/STR75x/portISR.c
fd66e4cfdf3e8ad12bafd7b24a33c136e2481721
[ "MIT" ]
permissive
FreeRTOS/FreeRTOS-Kernel
d76fab294e3cae53216f00b3a1f6f5e8816658aa
7372519cba39922ce5aeb92b8931cf8694b78bd2
refs/heads/main
2023-08-21T06:08:37.626715
2023-08-18T16:05:10
2023-08-18T16:05:10
207,354,223
1,980
1,026
MIT
2023-09-13T05:52:18
2019-09-09T16:28:01
C
UTF-8
C
false
false
8,158
c
portISR.c
/* * FreeRTOS Kernel <DEVELOPMENT BRANCH> * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: MIT * * 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. * * https://www.FreeRTOS.org * https://github.com/FreeRTOS * */ /*----------------------------------------------------------- * Components that can be compiled to either ARM or THUMB mode are * contained in port.c The ISR routines, which can only be compiled * to ARM mode, are contained in this file. *----------------------------------------------------------*/ /* */ /* Scheduler includes. */ #include "FreeRTOS.h" #include "task.h" /* Constants required to handle critical sections. */ #define portNO_CRITICAL_NESTING ( ( uint32_t ) 0 ) volatile uint32_t ulCriticalNesting = 9999UL; /*-----------------------------------------------------------*/ /* * The scheduler can only be started from ARM mode, hence the inclusion of this * function here. */ void vPortISRStartFirstTask( void ); /*-----------------------------------------------------------*/ void vPortISRStartFirstTask( void ) { /* Simply start the scheduler. This is included here as it can only be called from ARM mode. */ asm volatile ( \ "LDR R0, =pxCurrentTCB \n\t" \ "LDR R0, [R0] \n\t" \ "LDR LR, [R0] \n\t" \ \ /* The critical nesting depth is the first item on the stack. */ \ /* Load it into the ulCriticalNesting variable. */ \ "LDR R0, =ulCriticalNesting \n\t" \ "LDMFD LR!, {R1} \n\t" \ "STR R1, [R0] \n\t" \ \ /* Get the SPSR from the stack. */ \ "LDMFD LR!, {R0} \n\t" \ "MSR SPSR, R0 \n\t" \ \ /* Restore all system mode registers for the task. */ \ "LDMFD LR, {R0-R14}^ \n\t" \ "NOP \n\t" \ \ /* Restore the return address. */ \ "LDR LR, [LR, #+60] \n\t" \ \ /* And return - correcting the offset in the LR to obtain the */ \ /* correct address. */ \ "SUBS PC, LR, #4 \n\t" \ ); } /*-----------------------------------------------------------*/ void vPortTickISR( void ) { /* Increment the RTOS tick count, then look for the highest priority task that is ready to run. */ if( xTaskIncrementTick() != pdFALSE ) { vTaskSwitchContext(); } /* Ready for the next interrupt. */ TB_ClearITPendingBit( TB_IT_Update ); } /*-----------------------------------------------------------*/ /* * The interrupt management utilities can only be called from ARM mode. When * THUMB_INTERWORK is defined the utilities are defined as functions here to * ensure a switch to ARM mode. When THUMB_INTERWORK is not defined then * the utilities are defined as macros in portmacro.h - as per other ports. */ #ifdef THUMB_INTERWORK void vPortDisableInterruptsFromThumb( void ) __attribute__ ((naked)); void vPortEnableInterruptsFromThumb( void ) __attribute__ ((naked)); void vPortDisableInterruptsFromThumb( void ) { asm volatile ( "STMDB SP!, {R0} \n\t" /* Push R0. */ "MRS R0, CPSR \n\t" /* Get CPSR. */ "ORR R0, R0, #0xC0 \n\t" /* Disable IRQ, FIQ. */ "MSR CPSR, R0 \n\t" /* Write back modified value. */ "LDMIA SP!, {R0} \n\t" /* Pop R0. */ "BX R14" ); /* Return back to thumb. */ } void vPortEnableInterruptsFromThumb( void ) { asm volatile ( "STMDB SP!, {R0} \n\t" /* Push R0. */ "MRS R0, CPSR \n\t" /* Get CPSR. */ "BIC R0, R0, #0xC0 \n\t" /* Enable IRQ, FIQ. */ "MSR CPSR, R0 \n\t" /* Write back modified value. */ "LDMIA SP!, {R0} \n\t" /* Pop R0. */ "BX R14" ); /* Return back to thumb. */ } #endif /* THUMB_INTERWORK */ /*-----------------------------------------------------------*/ void vPortEnterCritical( void ) { /* Disable interrupts as per portDISABLE_INTERRUPTS(); */ asm volatile ( "STMDB SP!, {R0} \n\t" /* Push R0. */ "MRS R0, CPSR \n\t" /* Get CPSR. */ "ORR R0, R0, #0xC0 \n\t" /* Disable IRQ, FIQ. */ "MSR CPSR, R0 \n\t" /* Write back modified value. */ "LDMIA SP!, {R0}" ); /* Pop R0. */ /* Now interrupts are disabled ulCriticalNesting can be accessed directly. Increment ulCriticalNesting to keep a count of how many times portENTER_CRITICAL() has been called. */ ulCriticalNesting++; } /*-----------------------------------------------------------*/ void vPortExitCritical( void ) { if( ulCriticalNesting > portNO_CRITICAL_NESTING ) { /* Decrement the nesting count as we are leaving a critical section. */ ulCriticalNesting--; /* If the nesting level has reached zero then interrupts should be re-enabled. */ if( ulCriticalNesting == portNO_CRITICAL_NESTING ) { /* Enable interrupts as per portEXIT_CRITICAL(). */ asm volatile ( "STMDB SP!, {R0} \n\t" /* Push R0. */ "MRS R0, CPSR \n\t" /* Get CPSR. */ "BIC R0, R0, #0xC0 \n\t" /* Enable IRQ, FIQ. */ "MSR CPSR, R0 \n\t" /* Write back modified value. */ "LDMIA SP!, {R0}" ); /* Pop R0. */ } } }
119a6e43b78d7ae9139f54401237130cb3f59f95
70238f403826253b36323e0c4700795788c61187
/thirdparty/minizip-ng/lib/zlib-ng/test/deflate_quick_block_open.c
9526533d0b3abb9f2cabe93b96e23d9d3b674a59
[ "Zlib", "LicenseRef-scancode-public-domain", "CC-BY-4.0", "CC-BY-3.0", "MIT" ]
permissive
tommitytom/RetroPlug
d4d1c9d671cec7373bf3e27030bc0d29b46191be
40c6f01352d50cb31b1d4f31b7cc17fd2cf47ce8
refs/heads/main
2023-06-30T00:28:58.282288
2022-11-01T02:03:57
2022-11-01T02:03:57
185,368,230
262
11
MIT
2021-08-15T04:15:59
2019-05-07T09:23:48
C++
UTF-8
C
false
false
4,693
c
deflate_quick_block_open.c
/* Generated by fuzzing - test block_open handling in deflate_quick(). */ #include "zbuild.h" #ifdef ZLIB_COMPAT # include "zlib.h" #else # include "zlib-ng.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { PREFIX3(stream) strm; memset(&strm, 0, sizeof(strm)); int ret = PREFIX(deflateInit2)(&strm, 1, Z_DEFLATED, -15, 1, Z_FILTERED); if (ret != Z_OK) { fprintf(stderr, "deflateInit2() failed with code %d\n", ret); return EXIT_FAILURE; } z_const unsigned char next_in[494] = "\x1d\x1d\x00\x00\x00\x4a\x4a\x4a\xaf\xaf\xaf\xaf\x4a\x4a\x4a\x4a" "\x3f\x3e\xaf\xff\xff\xff\x11\xff\xff\xff\xff\xdf\x00\x00\x00\x01" "\x3f\x7d\x00\x50\x00\x00\xc8\x01\x2b\x60\xc8\x00\x24\x06\xff\xff" "\x4a\x4e\x4a\x7d\xc8\x01\xf1\x2b\x28\xb2\xb2\x60\x25\xc8\x06\x00" "\x00\x00\x31\x00\x01\xb2\xb2\xb2\xff\xff\xfd\xb2\xb2\x40\xff\x7d" "\x3b\x34\x3e\xff\xff\x4a\x4a\x01\xf1\xff\x02\xff\x3f\xff\x02\xff" "\xff\xff\xbf\x0a\xff\x00\x01\x3f\xb3\xff\x26\x00\x00\x13\x00\xc8" "\x3e\x3e\x3e\x4a\x76\x4a\x4a\x2e\x7d\x3e\x3e\x3e\x3e\x1d\x1d\x1d" "\xfe\xea\xef\x80\x01\x00\x00\x40\x00\x00\xba\x00\x06\xfa\xb9\x11" "\xbf\x98\xee\x45\x7e\x04\x00\xff\xff\xff\x67\xc3\xc3\xc3\xc3\x00" "\x1d\x1d\xe1\xe3\x00\xc3\x1d\x98\x1d\x1d\x1d\x1d\x1d\x00\x00\x00" "\x02\x00\x00\x00\xe8\x00\x00\x1d\x1d\x1d\xfa\x1e\x12\xff\xff\xff" "\x00\x01\xa7\xff\xff\xff\x1d\x1d\x1d\x63\xff\xff\xff\x1f\x00\x00" "\x10\x40\x00\x00\xad\xff\xff\x3f\x51\x00\xf8\xff\xff\x8a\x01\x05" "\x00\x00\x03\x00\x00\xff\x00\x00\x00\x05\x40\x1f\x08\x0a\x00\xff" "\xff\x01\x00\x12\x00\x00\x01\x00\x3f\x40\x1d\x1d\x1d\x1d\x1d\x1d" "\x21\x00\x1d\x00\x00\x00\xe4\x00\x00\x00\x07\x00\x00\xe6\xe6\x34" "\xe6\xe6\xe6\xe6\xff\x2b\xee\x1d\x1d\x1d\x93\x1d\x1d\x1d\xee\x2b" "\xee\x01\x81\x1d\x00\x00\x58\x00\x00\x01\x14\x00\x1b\x00\x00\x2c" "\x00\x00\x00\xdb\x00\x45\x7e\x00\x00\x00\xfb\xbd\x00\x06\x21\xd3" "\x00\xff\xff\xff\xff\xff\x00\x49\x49\xc9\x49\x3d\x00\x34\x01\x00" "\x00\x6a\x2b\x00\x00\x50\x40\xf0\xf0\xf0\xf0\xa3\xa3\xa3\xa3\xf0" "\xf0\x06\xfa\xa9\x01\x10\xbf\x98\x9d\x2b\xee\x2d\x21\x01\xdb\x00" "\x45\x10\x00\x00\x7e\x00\x00\xe7\x00\xff\xff\x00\xf6\x00\x00\x00" "\xf9\x00\x00\x00\x11\x00\x00\x00\xe2\x00\x00\x00\x2d\x00\x00\x00" "\x2f\x00\x3f\x54\x1d\x1d\x1d\x4c\x4c\x4c\x4c\x2a\x4c\x4c\x10\xff" "\xff\x1a\x00\x00\x01\xff\x00\xff\xf9\x00\x3f\x53\xcc\xcc\xcc\xcc" "\x6e\x00\x00\x01\xf8\xff\xff\xff\x49\x04\x2c\x01\x00\x1d\x00\x07" "\x01\xff\x00\x00\x00\xf8\xff\x09\x00\x27\x00\x08\x21\x1c\x00\x00" "\x00\x00\x1d\x05\x00\x00\x00\x2c\x53\x3f\x00\x01\x00\x00\xe6\xff" "\xff\xff\x6a\x2b\xee\xe6\x6a\x2b\xee\x2b\xee\xee\x2b\xee"; strm.next_in = next_in; unsigned char next_out[1116]; strm.next_out = next_out; strm.avail_in = sizeof(next_in); while (1) { strm.avail_out = (uint32_t)(next_out + sizeof(next_out) - strm.next_out); if (strm.avail_out > 38) strm.avail_out = 38; ret = PREFIX(deflate)(&strm, Z_FINISH); if (ret == Z_STREAM_END) break; if (ret != Z_OK) { fprintf(stderr, "deflate() failed with code %d\n", ret); return EXIT_FAILURE; } } uint32_t compressed_size = (uint32_t)(strm.next_out - next_out); ret = PREFIX(deflateEnd)(&strm); if (ret != Z_OK) { fprintf(stderr, "deflateEnd() failed with code %d\n", ret); return EXIT_FAILURE; } memset(&strm, 0, sizeof(strm)); ret = PREFIX(inflateInit2)(&strm, -15); if (ret != Z_OK) { fprintf(stderr, "inflateInit2() failed with code %d\n", ret); return EXIT_FAILURE; } strm.next_in = next_out; strm.avail_in = compressed_size; unsigned char uncompressed[sizeof(next_in)]; strm.next_out = uncompressed; strm.avail_out = sizeof(uncompressed); ret = PREFIX(inflate)(&strm, Z_NO_FLUSH); if (ret != Z_STREAM_END) { fprintf(stderr, "inflate() failed with code %d\n", ret); return EXIT_FAILURE; } ret = PREFIX(inflateEnd)(&strm); if (ret != Z_OK) { fprintf(stderr, "inflateEnd() failed with code %d\n", ret); return EXIT_FAILURE; } if (memcmp(uncompressed, next_in, sizeof(uncompressed)) != 0) { fprintf(stderr, "Uncompressed data differs from the original\n"); return EXIT_FAILURE; } }
9cc7a5f889527ba49466272effca1b8395978a39
4c8dff81d0227bac2577d5be054f58ac26a646df
/examples/c-cursor-no-gen/task_builder.h
81f559b3ff21d4a7218520d4e0001b7dc3f73e11
[ "Apache-2.0" ]
permissive
objectbox/objectbox-c
ecbb545b68a1921d30b2824ba21fcc6afe1a4ac3
d97f7c173ce332152ac0e215e1809f124c8452e4
refs/heads/main
2023-08-15T04:49:07.535399
2022-12-19T11:55:04
2022-12-19T11:55:04
146,648,868
176
31
Apache-2.0
2022-09-06T13:03:43
2018-08-29T19:34:44
C
UTF-8
C
false
false
2,147
h
task_builder.h
#ifndef TASK_BUILDER_H #define TASK_BUILDER_H /* Generated by flatcc 0.6.1-dev FlatBuffers schema compiler for C by dvide.com */ #ifndef TASK_READER_H #include "task_reader.h" #endif #ifndef FLATBUFFERS_COMMON_BUILDER_H #include "flatbuffers_common_builder.h" #endif #include "flatcc/flatcc_prologue.h" #ifndef flatbuffers_identifier #define flatbuffers_identifier 0 #endif #ifndef flatbuffers_extension #define flatbuffers_extension ".bin" #endif static const flatbuffers_voffset_t __Task_required[] = { 0 }; typedef flatbuffers_ref_t Task_ref_t; static Task_ref_t Task_clone(flatbuffers_builder_t *B, Task_table_t t); __flatbuffers_build_table(flatbuffers_, Task, 4) #define __Task_formal_args , uint64_t v0, flatbuffers_string_ref_t v1, uint64_t v2, uint64_t v3 #define __Task_call_args , v0, v1, v2, v3 static inline Task_ref_t Task_create(flatbuffers_builder_t *B __Task_formal_args); __flatbuffers_build_table_prolog(flatbuffers_, Task, Task_file_identifier, Task_type_identifier) __flatbuffers_build_scalar_field(0, flatbuffers_, Task_id, flatbuffers_uint64, uint64_t, 8, 8, UINT64_C(0), Task) __flatbuffers_build_string_field(1, flatbuffers_, Task_text, Task) __flatbuffers_build_scalar_field(2, flatbuffers_, Task_date_created, flatbuffers_uint64, uint64_t, 8, 8, UINT64_C(0), Task) __flatbuffers_build_scalar_field(3, flatbuffers_, Task_date_finished, flatbuffers_uint64, uint64_t, 8, 8, UINT64_C(0), Task) static inline Task_ref_t Task_create(flatbuffers_builder_t *B __Task_formal_args) { if (Task_start(B) || Task_id_add(B, v0) || Task_date_created_add(B, v2) || Task_date_finished_add(B, v3) || Task_text_add(B, v1)) { return 0; } return Task_end(B); } static Task_ref_t Task_clone(flatbuffers_builder_t *B, Task_table_t t) { __flatbuffers_memoize_begin(B, t); if (Task_start(B) || Task_id_pick(B, t) || Task_date_created_pick(B, t) || Task_date_finished_pick(B, t) || Task_text_pick(B, t)) { return 0; } __flatbuffers_memoize_end(B, t, Task_end(B)); } #include "flatcc/flatcc_epilogue.h" #endif /* TASK_BUILDER_H */
2a9ad5ab4531456d9c6fb2b9b32b8d0bd63f7291
e73547787354afd9b717ea57fe8dd0695d161821
/src/world/area_kkj/kkj_27/kkj_27_3_rotating_wall.c
8ddae67956b9ffc703f6240b46e1673402fd2af6
[]
no_license
pmret/papermario
8b514b19653cef8d6145e47499b3636b8c474a37
9774b26d93f1045dd2a67e502b6efc9599fb6c31
refs/heads/main
2023-08-31T07:09:48.951514
2023-08-21T18:07:08
2023-08-21T18:07:08
287,151,133
904
139
null
2023-09-14T02:44:23
2020-08-13T01:22:57
C
UTF-8
C
false
false
5,308
c
kkj_27_3_rotating_wall.c
#include "kkj_27.h" #include "sprite/player.h" s32 N(SpillLightAmount) = 0; API_CALLABLE(N(UpdateRotatingPlayerPosition)) { f32 var = EVT_FIXED_TO_FLOAT(script->varTable[2]); f32 angle; f32 mag; mag = dist2D(-250.0f, 0.0f, script->varTable[9], script->varTable[10]); angle = atan2(-250.0f, 0.0f, script->varTable[9], script->varTable[10]); angle = clamp_angle(angle - var); gPlayerStatus.pos.x = -250.0f + mag * sin_deg(angle); gPlayerStatus.pos.z = 0.0f - mag * cos_deg(angle); return ApiStatus_DONE2; } API_CALLABLE(N(SetSpillLightAmount)) { Bytecode* args = script->ptrReadPos; N(SpillLightAmount) = evt_get_variable(script, *args++); return ApiStatus_DONE2; } void N(setup_gfx_spill_light)(void) { if (N(SpillLightAmount) > 0) { gDPSetCombineLERP(gMainGfxPos++, TEXEL0, 0, SHADE, 0, 0, 0, 0, PRIMITIVE, TEXEL0, 0, SHADE, 0, 0, 0, 0, PRIMITIVE); gDPSetPrimColor(gMainGfxPos++, 0, 0, 0, 0, 0, N(SpillLightAmount)); } } EvtScript N(EVS_Scene_RotatingWall) = { EVT_CALL(ModifyColliderFlags, MODIFY_COLLIDER_FLAGS_SET_BITS, COLLIDER_g29, COLLIDER_FLAGS_UPPER_MASK) EVT_CALL(ModifyColliderFlags, MODIFY_COLLIDER_FLAGS_CLEAR_BITS, COLLIDER_o124, COLLIDER_FLAGS_UPPER_MASK) EVT_THREAD EVT_CALL(PlaySoundAt, SOUND_KKJ_ROTATING_WALL, SOUND_SPACE_DEFAULT, -250, 5, 0) EVT_CALL(GetPlayerPos, LVar9, LVar0, LVarA) EVT_CALL(MakeLerp, 0, -450, 120 * DT, EASING_LINEAR) EVT_LOOP(0) EVT_CALL(UpdateLerp) EVT_SETF(LVar2, LVar0) EVT_DIVF(LVar2, 10) EVT_CALL(RotateGroup, MODEL_g29, LVar2, 0, 1, 0) EVT_CALL(N(UpdateRotatingPlayerPosition)) EVT_WAIT(1) EVT_IF_EQ(LVar1, 0) EVT_BREAK_LOOP EVT_END_IF EVT_END_LOOP EVT_END_THREAD EVT_THREAD EVT_CALL(EnableModel, MODEL_o182, TRUE) EVT_CALL(EnableModel, MODEL_o184, TRUE) EVT_CALL(EnableModel, MODEL_o186, TRUE) EVT_CALL(MakeLerp, 8, 255, 40 * DT, EASING_LINEAR) EVT_LOOP(0) EVT_CALL(UpdateLerp) EVT_CALL(N(SetSpillLightAmount), LVar0) EVT_WAIT(1) EVT_IF_EQ(LVar1, 0) EVT_BREAK_LOOP EVT_END_IF EVT_END_LOOP EVT_END_THREAD EVT_WAIT(80 * DT) EVT_SET(GF_KKJ14_SkipSecretPassage, TRUE) EVT_CALL(GotoMap, EVT_PTR("kkj_15"), kkj_15_ENTRY_1) EVT_WAIT(100 * DT) EVT_RETURN EVT_END }; EvtScript N(EVS_UseRotatingWall) = { EVT_SET_GROUP(EVT_GROUP_1B) EVT_CALL(DisablePlayerInput, TRUE) EVT_CALL(PlayerMoveTo, -205, -10, 15 * DT) EVT_CALL(InterpPlayerYaw, 270, 5) EVT_WAIT(10 * DT) EVT_CALL(SetPlayerAnimation, ANIM_Peach3_ReachForButton) EVT_WAIT(10 * DT) EVT_CALL(PlaySoundAtCollider, COLLIDER_o193, SOUND_KKJ_PRESS_BUTTON, 0) EVT_CALL(SetPlayerAnimation, ANIM_Peach3_PressButton) EVT_WAIT(10 * DT) EVT_CALL(SetPlayerAnimation, ANIM_Peach3_AfterPressButton) EVT_WAIT(10 * DT) EVT_CALL(ShakeCam, CAM_DEFAULT, 0, 10, EVT_FLOAT(1.0)) EVT_EXEC_WAIT(N(EVS_Scene_RotatingWall)) EVT_CALL(DisablePlayerInput, FALSE) EVT_RETURN EVT_END }; EvtScript N(EVS_UseRotatingWall_FirstTime) = { EVT_SET_GROUP(EVT_GROUP_1B) EVT_CALL(DisablePlayerInput, TRUE) EVT_CALL(FacePlayerTowardPoint, -222, 0, 5) EVT_WAIT(10 * DT) EVT_CALL(SetPlayerAnimation, ANIM_Peach3_ReachForButton) EVT_WAIT(10 * DT) EVT_CALL(PlaySoundAtCollider, COLLIDER_o193, SOUND_KKJ_PRESS_BUTTON, 0) EVT_CALL(SetPlayerAnimation, ANIM_Peach3_PressButton) EVT_WAIT(10 * DT) EVT_CALL(SetPlayerAnimation, ANIM_Peach3_AfterPressButton) EVT_WAIT(10 * DT) EVT_THREAD EVT_CALL(DisablePartnerAI, 0) EVT_CALL(SetNpcAnimation, NPC_PARTNER, ANIM_Twink_Cringe) EVT_CALL(GetNpcPos, NPC_PARTNER, LVar0, LVar1, LVar2) EVT_CALL(NpcJump0, NPC_PARTNER, LVar0, LVar1, LVar2, 10) EVT_CALL(EnablePartnerAI) EVT_END_THREAD EVT_THREAD EVT_CALL(InterpPlayerYaw, 270, 0) EVT_WAIT(10 * DT) EVT_CALL(SetPlayerAnimation, ANIM_Peach2_LookAround) EVT_CALL(SpeakToPlayer, NPC_PLAYER, ANIM_Peach2_Gasp, ANIM_Peach2_GaspStill, 5, MSG_Peach_0048) EVT_END_THREAD EVT_CALL(ShakeCam, CAM_DEFAULT, 0, 5, EVT_FLOAT(1.0)) EVT_EXEC_WAIT(N(EVS_Scene_RotatingWall)) EVT_CALL(DisablePlayerInput, FALSE) EVT_RETURN EVT_END }; EvtScript N(EVS_SetupRotatingWall) = { EVT_CALL(EnableModel, MODEL_o182, FALSE) EVT_CALL(EnableModel, MODEL_o184, FALSE) EVT_CALL(EnableModel, MODEL_o186, FALSE) EVT_CALL(SetModelCustomGfx, MODEL_o182, CUSTOM_GFX_1, FOG_MODE_UNCHANGED) EVT_CALL(SetModelCustomGfx, MODEL_o184, CUSTOM_GFX_1, FOG_MODE_UNCHANGED) EVT_CALL(SetModelCustomGfx, MODEL_o186, CUSTOM_GFX_1, FOG_MODE_UNCHANGED) EVT_CALL(SetCustomGfxBuilders, CUSTOM_GFX_1, EVT_PTR(N(setup_gfx_spill_light)), NULL) EVT_IF_EQ(GB_StoryProgress, STORY_CH1_BEGAN_PEACH_MISSION) EVT_BIND_TRIGGER(EVT_PTR(N(EVS_UseRotatingWall_FirstTime)), TRIGGER_WALL_PRESS_A, COLLIDER_o193, 1, 0) EVT_ELSE EVT_BIND_TRIGGER(EVT_PTR(N(EVS_UseRotatingWall)), TRIGGER_WALL_PRESS_A, COLLIDER_o193, 1, 0) EVT_END_IF EVT_RETURN EVT_END };
bab2b5ad596ac427906159cac5a79416a0824bce
1efd2de8bf77ec00eb2fcaf5749278495946d920
/src/vos/ilog.h
767064022dd8a2a4e61d4a00c1d23788ee63d90c
[ "BSD-2-Clause", "BSD-2-Clause-Patent" ]
permissive
daos-stack/daos
6f55bf3061fd830d5b8d28506e1295e2d3a27c38
ed5eed5df43a68571afe123132a743824c02637a
refs/heads/master
2023-08-31T21:43:37.606145
2023-08-31T16:38:00
2023-08-31T16:38:00
69,390,670
631
300
NOASSERTION
2023-09-14T18:55:15
2016-09-27T19:21:29
C
UTF-8
C
false
false
9,623
h
ilog.h
/** * (C) Copyright 2019-2023 Intel Corporation. * * SPDX-License-Identifier: BSD-2-Clause-Patent */ /** * VOS Object/Key incarnation log * vos/ilog.h * * Author: Jeff Olivier <jeffrey.v.olivier@intel.com> */ #ifndef __ILOG_H__ #define __ILOG_H__ #include <daos_types.h> struct ilog_id { /** DTX of entry */ union { uint64_t id_value; struct { uint32_t id_tx_id; uint16_t id_punch_minor_eph; uint16_t id_update_minor_eph; }; }; /** timestamp of entry */ daos_epoch_t id_epoch; }; /** Opaque root for incarnation log */ struct ilog_df { char id_pad[24]; }; struct umem_instance; enum ilog_status { /** Log status is not set */ ILOG_INVALID, /** Log entry is visible to caller */ ILOG_COMMITTED, /** Log entry is not yet visible */ ILOG_UNCOMMITTED, /** Log entry can be removed */ ILOG_REMOVED, }; /** Near term hack to hook things up with existing DTX */ struct ilog_desc_cbs { /** Retrieve the status of a log entry (See enum ilog_status). On error * return error code < 0. */ int (*dc_log_status_cb)(struct umem_instance *umm, uint32_t tx_id, daos_epoch_t epoch, uint32_t intent, bool retry, void *args); void *dc_log_status_args; /** Check if the log entry was created by current transaction */ int (*dc_is_same_tx_cb)(struct umem_instance *umm, uint32_t tx_id, daos_epoch_t epoch, bool *same, void *args); void *dc_is_same_tx_args; /** Register the log entry with the transaction log */ int (*dc_log_add_cb)(struct umem_instance *umm, umem_off_t ilog_off, uint32_t *tx_id, daos_epoch_t epoch, void *args); void *dc_log_add_args; /** Remove the log entry from the transaction log */ int (*dc_log_del_cb)(struct umem_instance *umm, umem_off_t ilog_off, uint32_t tx_id, daos_epoch_t epoch, bool abort, void *args); void *dc_log_del_args; }; /** Globally initialize incarnation log */ int ilog_init(void); /** Create a new incarnation log in place * * \param umm[IN] The umem instance * \param root[IN] A pointer to the allocated root * * \return 0 on success, error code on failure */ int ilog_create(struct umem_instance *umm, struct ilog_df *root); /** Open an existing incarnation log in place and create a handle to * access it. * * \param umm[IN] The umem instance * \param root[IN] A pointer to the allocated root * \param cbs[in] Incarnation log transaction log callbacks * \param loh[OUT] Returned open log handle * * \return 0 on success, error code on failure */ int ilog_open(struct umem_instance *umm, struct ilog_df *root, const struct ilog_desc_cbs *cbs, daos_handle_t *loh); /** Close an open incarnation log handle * * \param loh[in] Open handle to close * * \return 0 on success, error code on failure */ int ilog_close(daos_handle_t loh); /** Destroy an incarnation log * * \param umm[in] The umem instance * \param cbs[in] Incarnation log transaction log callbacks * \param root[IN] A pointer to an initialized incarnation log * * \return 0 on success, error code on failure */ int ilog_destroy(struct umem_instance *umm, struct ilog_desc_cbs *cbs, struct ilog_df *root); /** Logs or updates an entry in the incaration log identified by the epoch * and the currently executing transaction. If a visible creation entry * exists, nothing will be logged and the function will succeed. * * \param loh[in] Open log handle * \param epr[in] Limiting range * \param major_eph[in] Major epoch of update * \param minor_eph[in] Minor epoch of update * \param punch[in] Punch if true, update otherwise * * \return 0 on success, error code on failure */ int ilog_update(daos_handle_t loh, const daos_epoch_range_t *epr, daos_epoch_t major_eph, uint16_t minor_eph, bool punch); /** Updates specified log entry to mark it as persistent (remove * the transaction identifier from the entry. Additionally, this will * remove redundant entries, such as later uncommitted updates. * * \param loh[in] Open log handle * \param id[in] Identifier for log entry * * \return 0 on success, error code on failure */ int ilog_persist(daos_handle_t loh, const struct ilog_id *id); /** Removes an aborted entry from the incarnation log * * \param loh[in] Open log handle * \param id[in] Identifier for log entry * * \return 0 on success, error code on failure */ int ilog_abort(daos_handle_t loh, const struct ilog_id *id); /** Incarnation log entry description */ struct ilog_entry { /** The epoch and tx_id for the log entry */ struct ilog_id ie_id; /** The status of the incarnation log entry. See enum ilog_status */ int32_t ie_status; /** Index of the ilog entry */ int32_t ie_idx; }; #define ILOG_PRIV_SIZE 144 /* Information about ilog entries */ struct ilog_info { /** Status of ilog entry */ int16_t ii_status; /** Used internally to indicate removal during aggregation */ uint16_t ii_removed; }; /** Structure for storing the full incarnation log for ilog_fetch. The * fields shouldn't generally be accessed directly but via the iteration * APIs below. */ struct ilog_entries { /** Array of log entries */ struct ilog_id *ie_ids; /** Parsed information about each ilog entry */ struct ilog_info *ie_info; /** Number of entries in the log */ int64_t ie_num_entries; /** Private log data */ uint8_t ie_priv[ILOG_PRIV_SIZE]; }; /** * Cleanup the incarnation log * * \param umm[in] The umem instance * \param root[in] Pointer to log root * \param cbs[in] Incarnation log transaction log callbacks * \param epr[in] Epoch range for cleanup * \param discard[in] Normally, aggregate will only remove entries * that are provably not needed. If discard is * set, it will remove everything in the epoch * range. * \param inprogress[in] If discarding, leave committed entries alone. * Remove only uncommitted entries. * \param punch_major[in] Max major epoch punch of parent incarnation log * \param punch_major[in] Max minor epoch punch of parent incarnation log * \param entries[in] Used for efficiency since aggregation is used * by vos_iterator * * \return 0 success * 1 success but indicates log is empty * < 0 Error */ int ilog_aggregate(struct umem_instance *umm, struct ilog_df *root, const struct ilog_desc_cbs *cbs, const daos_epoch_range_t *epr, bool discard, bool inprogress, daos_epoch_t punch_major, uint16_t punch_minor, struct ilog_entries *entries); /** Initialize an ilog_entries struct for fetch * * \param entries[in] Allocated structure where entries are stored */ void ilog_fetch_init(struct ilog_entries *entries); /** Assuming src has already been copied to dest, just fix up internal pointers * and reset src * * \param dest[in] Destination entries * \param src[in] Source entries */ void ilog_fetch_move(struct ilog_entries *dest, struct ilog_entries *src); /** Fetch the entire incarnation log. This function will refresh only when * the underlying log or the intent has changed. If the struct is shared * between multiple ULT's fetch should be done after every yield. * * \param umm[in] The umem instance * \param root[in] Pointer to log root * \param cbs[in] Incarnation log transaction log callbacks * \param intent[in] The intent of the operation * \param has_cond[in] Whether for conditional operation or not * \param entries[in,out] Allocated structure passed in will be filled * with incarnation log entries in the range. * * \return 0 on success, error code on failure */ int ilog_fetch(struct umem_instance *umm, struct ilog_df *root, const struct ilog_desc_cbs *cbs, uint32_t intent, bool has_cond, struct ilog_entries *entries); /** Deallocate any memory associated with an ilog_entries struct for fetch * * \param entries[in] Allocated structure to be finalized */ void ilog_fetch_finish(struct ilog_entries *entries); /** For internal use by ilog_foreach* */ static inline bool ilog_cache_entry(const struct ilog_entries *entries, struct ilog_entry *entry, int idx) { entry->ie_id.id_value = entries->ie_ids[idx].id_value; entry->ie_id.id_epoch = entries->ie_ids[idx].id_epoch; entry->ie_status = entries->ie_info[idx].ii_status; return true; } /** Iterator for fetched incarnation log entries * * \param entries[in] The fetched entries */ #define ilog_foreach_entry(ents, entry) \ for ((entry)->ie_idx = 0; (entry)->ie_idx < (ents)->ie_num_entries && \ ilog_cache_entry(ents, entry, (entry)->ie_idx); (entry)->ie_idx++) /** Reverse iterator for fetched incarnation log entries * * \param entries[in] The fetched entries */ #define ilog_foreach_entry_reverse(ents, entry) \ for ((entry)->ie_idx = (ents)->ie_num_entries - 1; (entry)->ie_idx >= 0 && \ ilog_cache_entry(ents, entry, (entry)->ie_idx); (entry)->ie_idx--) /** Fetch the address of the timestamp index from the ilog * * \param entries[in] The incarnation log * * \returns a pointer to the index */ uint32_t * ilog_ts_idx_get(struct ilog_df *ilog_df); /** Retrieve the current version of the incarnation log * * \param loh[in] Open log handle * * Returns the version of the log or 0 if log handle is invalid **/ uint32_t ilog_version_get(daos_handle_t loh); /** Returns true if there is a punch minor epoch */ static inline bool ilog_has_punch(const struct ilog_entry *entry) { return entry->ie_id.id_punch_minor_eph > 0; } static inline bool ilog_is_punch(const struct ilog_entry *entry) { return entry->ie_id.id_punch_minor_eph > entry->ie_id.id_update_minor_eph; } #endif /* __ILOG_H__ */
ce0f623b8fc8b31e23be8641a68f440bdb6a6cc5
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/sparc/mm/fault_64.c
ac2db923e51a254a300bc9bd5686200ae4ed08bd
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
13,975
c
fault_64.c
/* * arch/sparc64/mm/fault.c: Page fault handlers for the 64-bit Sparc. * * Copyright (C) 1996, 2008 David S. Miller (davem@davemloft.net) * Copyright (C) 1997, 1999 Jakub Jelinek (jj@ultra.linux.cz) */ #include <asm/head.h> #include <linux/string.h> #include <linux/types.h> #include <linux/sched.h> #include <linux/ptrace.h> #include <linux/mman.h> #include <linux/signal.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/init.h> #include <linux/perf_event.h> #include <linux/interrupt.h> #include <linux/kprobes.h> #include <linux/kdebug.h> #include <linux/percpu.h> #include <asm/page.h> #include <asm/pgtable.h> #include <asm/openprom.h> #include <asm/oplib.h> #include <asm/uaccess.h> #include <asm/asi.h> #include <asm/lsu.h> #include <asm/sections.h> #include <asm/mmu_context.h> int show_unhandled_signals = 1; static inline __kprobes int notify_page_fault(struct pt_regs *regs) { int ret = 0; /* kprobe_running() needs smp_processor_id() */ if (kprobes_built_in() && !user_mode(regs)) { preempt_disable(); if (kprobe_running() && kprobe_fault_handler(regs, 0)) ret = 1; preempt_enable(); } return ret; } static void __kprobes unhandled_fault(unsigned long address, struct task_struct *tsk, struct pt_regs *regs) { if ((unsigned long) address < PAGE_SIZE) { printk(KERN_ALERT "Unable to handle kernel NULL " "pointer dereference\n"); } else { printk(KERN_ALERT "Unable to handle kernel paging request " "at virtual address %016lx\n", (unsigned long)address); } printk(KERN_ALERT "tsk->{mm,active_mm}->context = %016lx\n", (tsk->mm ? CTX_HWBITS(tsk->mm->context) : CTX_HWBITS(tsk->active_mm->context))); printk(KERN_ALERT "tsk->{mm,active_mm}->pgd = %016lx\n", (tsk->mm ? (unsigned long) tsk->mm->pgd : (unsigned long) tsk->active_mm->pgd)); die_if_kernel("Oops", regs); } static void __kprobes bad_kernel_pc(struct pt_regs *regs, unsigned long vaddr) { printk(KERN_CRIT "OOPS: Bogus kernel PC [%016lx] in fault handler\n", regs->tpc); printk(KERN_CRIT "OOPS: RPC [%016lx]\n", regs->u_regs[15]); printk("OOPS: RPC <%pS>\n", (void *) regs->u_regs[15]); printk(KERN_CRIT "OOPS: Fault was to vaddr[%lx]\n", vaddr); dump_stack(); unhandled_fault(regs->tpc, current, regs); } /* * We now make sure that mmap_sem is held in all paths that call * this. Additionally, to prevent kswapd from ripping ptes from * under us, raise interrupts around the time that we look at the * pte, kswapd will have to wait to get his smp ipi response from * us. vmtruncate likewise. This saves us having to get pte lock. */ static unsigned int get_user_insn(unsigned long tpc) { pgd_t *pgdp = pgd_offset(current->mm, tpc); pud_t *pudp; pmd_t *pmdp; pte_t *ptep, pte; unsigned long pa; u32 insn = 0; if (pgd_none(*pgdp) || unlikely(pgd_bad(*pgdp))) goto out; pudp = pud_offset(pgdp, tpc); if (pud_none(*pudp) || unlikely(pud_bad(*pudp))) goto out; /* This disables preemption for us as well. */ local_irq_disable(); pmdp = pmd_offset(pudp, tpc); if (pmd_none(*pmdp) || unlikely(pmd_bad(*pmdp))) goto out_irq_enable; #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (pmd_trans_huge(*pmdp)) { if (pmd_trans_splitting(*pmdp)) goto out_irq_enable; pa = pmd_pfn(*pmdp) << PAGE_SHIFT; pa += tpc & ~HPAGE_MASK; /* Use phys bypass so we don't pollute dtlb/dcache. */ __asm__ __volatile__("lduwa [%1] %2, %0" : "=r" (insn) : "r" (pa), "i" (ASI_PHYS_USE_EC)); } else #endif { ptep = pte_offset_map(pmdp, tpc); pte = *ptep; if (pte_present(pte)) { pa = (pte_pfn(pte) << PAGE_SHIFT); pa += (tpc & ~PAGE_MASK); /* Use phys bypass so we don't pollute dtlb/dcache. */ __asm__ __volatile__("lduwa [%1] %2, %0" : "=r" (insn) : "r" (pa), "i" (ASI_PHYS_USE_EC)); } pte_unmap(ptep); } out_irq_enable: local_irq_enable(); out: return insn; } static inline void show_signal_msg(struct pt_regs *regs, int sig, int code, unsigned long address, struct task_struct *tsk) { if (!unhandled_signal(tsk, sig)) return; if (!printk_ratelimit()) return; printk("%s%s[%d]: segfault at %lx ip %p (rpc %p) sp %p error %x", task_pid_nr(tsk) > 1 ? KERN_INFO : KERN_EMERG, tsk->comm, task_pid_nr(tsk), address, (void *)regs->tpc, (void *)regs->u_regs[UREG_I7], (void *)regs->u_regs[UREG_FP], code); print_vma_addr(KERN_CONT " in ", regs->tpc); printk(KERN_CONT "\n"); } static void do_fault_siginfo(int code, int sig, struct pt_regs *regs, unsigned long fault_addr, unsigned int insn, int fault_code) { unsigned long addr; siginfo_t info; info.si_code = code; info.si_signo = sig; info.si_errno = 0; if (fault_code & FAULT_CODE_ITLB) { addr = regs->tpc; } else { /* If we were able to probe the faulting instruction, use it * to compute a precise fault address. Otherwise use the fault * time provided address which may only have page granularity. */ if (insn) addr = compute_effective_address(regs, insn, 0); else addr = fault_addr; } info.si_addr = (void __user *) addr; info.si_trapno = 0; if (unlikely(show_unhandled_signals)) show_signal_msg(regs, sig, code, addr, current); force_sig_info(sig, &info, current); } extern int handle_ldf_stq(u32, struct pt_regs *); extern int handle_ld_nf(u32, struct pt_regs *); static unsigned int get_fault_insn(struct pt_regs *regs, unsigned int insn) { if (!insn) { if (!regs->tpc || (regs->tpc & 0x3)) return 0; if (regs->tstate & TSTATE_PRIV) { insn = *(unsigned int *) regs->tpc; } else { insn = get_user_insn(regs->tpc); } } return insn; } static void __kprobes do_kernel_fault(struct pt_regs *regs, int si_code, int fault_code, unsigned int insn, unsigned long address) { unsigned char asi = ASI_P; if ((!insn) && (regs->tstate & TSTATE_PRIV)) goto cannot_handle; /* If user insn could be read (thus insn is zero), that * is fine. We will just gun down the process with a signal * in that case. */ if (!(fault_code & (FAULT_CODE_WRITE|FAULT_CODE_ITLB)) && (insn & 0xc0800000) == 0xc0800000) { if (insn & 0x2000) asi = (regs->tstate >> 24); else asi = (insn >> 5); if ((asi & 0xf2) == 0x82) { if (insn & 0x1000000) { handle_ldf_stq(insn, regs); } else { /* This was a non-faulting load. Just clear the * destination register(s) and continue with the next * instruction. -jj */ handle_ld_nf(insn, regs); } return; } } /* Is this in ex_table? */ if (regs->tstate & TSTATE_PRIV) { const struct exception_table_entry *entry; entry = search_exception_tables(regs->tpc); if (entry) { regs->tpc = entry->fixup; regs->tnpc = regs->tpc + 4; return; } } else { /* The si_code was set to make clear whether * this was a SEGV_MAPERR or SEGV_ACCERR fault. */ do_fault_siginfo(si_code, SIGSEGV, regs, address, insn, fault_code); return; } cannot_handle: unhandled_fault (address, current, regs); } static void noinline __kprobes bogus_32bit_fault_tpc(struct pt_regs *regs) { static int times; if (times++ < 10) printk(KERN_ERR "FAULT[%s:%d]: 32-bit process reports " "64-bit TPC [%lx]\n", current->comm, current->pid, regs->tpc); show_regs(regs); } asmlinkage void __kprobes do_sparc64_fault(struct pt_regs *regs) { struct mm_struct *mm = current->mm; struct vm_area_struct *vma; unsigned int insn = 0; int si_code, fault_code, fault; unsigned long address, mm_rss; unsigned int flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE; fault_code = get_thread_fault_code(); if (notify_page_fault(regs)) return; si_code = SEGV_MAPERR; address = current_thread_info()->fault_address; if ((fault_code & FAULT_CODE_ITLB) && (fault_code & FAULT_CODE_DTLB)) BUG(); if (test_thread_flag(TIF_32BIT)) { if (!(regs->tstate & TSTATE_PRIV)) { if (unlikely((regs->tpc >> 32) != 0)) { bogus_32bit_fault_tpc(regs); goto intr_or_no_mm; } } if (unlikely((address >> 32) != 0)) goto intr_or_no_mm; } if (regs->tstate & TSTATE_PRIV) { unsigned long tpc = regs->tpc; /* Sanity check the PC. */ if ((tpc >= KERNBASE && tpc < (unsigned long) __init_end) || (tpc >= MODULES_VADDR && tpc < MODULES_END)) { /* Valid, no problems... */ } else { bad_kernel_pc(regs, address); return; } } else flags |= FAULT_FLAG_USER; /* * If we're in an interrupt or have no user * context, we must not take the fault.. */ if (in_atomic() || !mm) goto intr_or_no_mm; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address); if (!down_read_trylock(&mm->mmap_sem)) { if ((regs->tstate & TSTATE_PRIV) && !search_exception_tables(regs->tpc)) { insn = get_fault_insn(regs, insn); goto handle_kernel_fault; } retry: down_read(&mm->mmap_sem); } vma = find_vma(mm, address); if (!vma) goto bad_area; /* Pure DTLB misses do not tell us whether the fault causing * load/store/atomic was a write or not, it only says that there * was no match. So in such a case we (carefully) read the * instruction to try and figure this out. It's an optimization * so it's ok if we can't do this. * * Special hack, window spill/fill knows the exact fault type. */ if (((fault_code & (FAULT_CODE_DTLB | FAULT_CODE_WRITE | FAULT_CODE_WINFIXUP)) == FAULT_CODE_DTLB) && (vma->vm_flags & VM_WRITE) != 0) { insn = get_fault_insn(regs, 0); if (!insn) goto continue_fault; /* All loads, stores and atomics have bits 30 and 31 both set * in the instruction. Bit 21 is set in all stores, but we * have to avoid prefetches which also have bit 21 set. */ if ((insn & 0xc0200000) == 0xc0200000 && (insn & 0x01780000) != 0x01680000) { /* Don't bother updating thread struct value, * because update_mmu_cache only cares which tlb * the access came from. */ fault_code |= FAULT_CODE_WRITE; } } continue_fault: if (vma->vm_start <= address) goto good_area; if (!(vma->vm_flags & VM_GROWSDOWN)) goto bad_area; if (!(fault_code & FAULT_CODE_WRITE)) { /* Non-faulting loads shouldn't expand stack. */ insn = get_fault_insn(regs, insn); if ((insn & 0xc0800000) == 0xc0800000) { unsigned char asi; if (insn & 0x2000) asi = (regs->tstate >> 24); else asi = (insn >> 5); if ((asi & 0xf2) == 0x82) goto bad_area; } } if (expand_stack(vma, address)) goto bad_area; /* * Ok, we have a good vm_area for this memory access, so * we can handle it.. */ good_area: si_code = SEGV_ACCERR; /* If we took a ITLB miss on a non-executable page, catch * that here. */ if ((fault_code & FAULT_CODE_ITLB) && !(vma->vm_flags & VM_EXEC)) { BUG_ON(address != regs->tpc); BUG_ON(regs->tstate & TSTATE_PRIV); goto bad_area; } if (fault_code & FAULT_CODE_WRITE) { if (!(vma->vm_flags & VM_WRITE)) goto bad_area; /* Spitfire has an icache which does not snoop * processor stores. Later processors do... */ if (tlb_type == spitfire && (vma->vm_flags & VM_EXEC) != 0 && vma->vm_file != NULL) set_thread_fault_code(fault_code | FAULT_CODE_BLKCOMMIT); flags |= FAULT_FLAG_WRITE; } else { /* Allow reads even for write-only mappings */ if (!(vma->vm_flags & (VM_READ | VM_EXEC))) goto bad_area; } fault = handle_mm_fault(mm, vma, address, flags); if ((fault & VM_FAULT_RETRY) && fatal_signal_pending(current)) return; if (unlikely(fault & VM_FAULT_ERROR)) { if (fault & VM_FAULT_OOM) goto out_of_memory; else if (fault & VM_FAULT_SIGSEGV) goto bad_area; else if (fault & VM_FAULT_SIGBUS) goto do_sigbus; BUG(); } if (flags & FAULT_FLAG_ALLOW_RETRY) { if (fault & VM_FAULT_MAJOR) { current->maj_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address); } else { current->min_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address); } if (fault & VM_FAULT_RETRY) { flags &= ~FAULT_FLAG_ALLOW_RETRY; flags |= FAULT_FLAG_TRIED; /* No need to up_read(&mm->mmap_sem) as we would * have already released it in __lock_page_or_retry * in mm/filemap.c. */ goto retry; } } up_read(&mm->mmap_sem); mm_rss = get_mm_rss(mm); #if defined(CONFIG_HUGETLB_PAGE) || defined(CONFIG_TRANSPARENT_HUGEPAGE) mm_rss -= (mm->context.huge_pte_count * (HPAGE_SIZE / PAGE_SIZE)); #endif if (unlikely(mm_rss > mm->context.tsb_block[MM_TSB_BASE].tsb_rss_limit)) tsb_grow(mm, MM_TSB_BASE, mm_rss); #if defined(CONFIG_HUGETLB_PAGE) || defined(CONFIG_TRANSPARENT_HUGEPAGE) mm_rss = mm->context.huge_pte_count; if (unlikely(mm_rss > mm->context.tsb_block[MM_TSB_HUGE].tsb_rss_limit)) { if (mm->context.tsb_block[MM_TSB_HUGE].tsb) tsb_grow(mm, MM_TSB_HUGE, mm_rss); else hugetlb_setup(regs); } #endif return; /* * Something tried to access memory that isn't in our memory map.. * Fix it, but check if it's kernel or user first.. */ bad_area: insn = get_fault_insn(regs, insn); up_read(&mm->mmap_sem); handle_kernel_fault: do_kernel_fault(regs, si_code, fault_code, insn, address); return; /* * We ran out of memory, or some other thing happened to us that made * us unable to handle the page fault gracefully. */ out_of_memory: insn = get_fault_insn(regs, insn); up_read(&mm->mmap_sem); if (!(regs->tstate & TSTATE_PRIV)) { pagefault_out_of_memory(); return; } goto handle_kernel_fault; intr_or_no_mm: insn = get_fault_insn(regs, 0); goto handle_kernel_fault; do_sigbus: insn = get_fault_insn(regs, insn); up_read(&mm->mmap_sem); /* * Send a sigbus, regardless of whether we were in kernel * or user mode. */ do_fault_siginfo(BUS_ADRERR, SIGBUS, regs, address, insn, fault_code); /* Kernel mode? Handle exceptions or die */ if (regs->tstate & TSTATE_PRIV) goto handle_kernel_fault; }
45c841ea33b43db72678047559daf81c3d99ddd8
01bcef56ade123623725ca78d233ac8653a91ece
/engine/blackbox.h
e172103bc00da8ebff9de675a896dfdf10ce49a8
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
SwagSoftware/Kisak-Strike
1085ba3c6003e622dac5ebc0c9424cb16ef58467
4c2fdc31432b4f5b911546c8c0d499a9cff68a85
refs/heads/master
2023-09-01T02:06:59.187775
2022-09-05T00:51:46
2022-09-05T00:51:46
266,676,410
921
123
null
2022-10-01T16:26:41
2020-05-25T03:41:35
C++
WINDOWS-1252
C
false
false
399
h
blackbox.h
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ========// // // Purpose: // // $NoKeywords: $ // //=============================================================================// #ifndef BLACKBOX_H #define BLACKBOX_H 1 #include "engine/iblackbox.h" extern IBlackBox *gBlackBox; // helper function void BlackBox_Record(const char *type, const char *pFormat, ...); #endif
659768ab6dae30cbbcd22ea9e533e8e869d87af3
047993e61cb0919001f3e0192a0c5e25aff5cc56
/ext/mathematical/cairo_callbacks.h
48d195886b6fac3e9958d4b1d0340155fd34df5e
[ "MIT" ]
permissive
gjtorikian/mathematical
0c21e7ecd865074a0db63a70542ab74f25077808
d6b323a6f7276fdd113334e54247590d5974a492
refs/heads/main
2023-08-11T01:47:23.823225
2023-07-20T00:55:27
2023-07-20T00:55:27
18,828,120
165
36
MIT
2023-07-20T00:53:10
2014-04-16T05:36:49
Ruby
UTF-8
C
false
false
327
h
cairo_callbacks.h
#ifndef CAIRO_OVERRIDES_H #define CAIRO_OVERRIDES_H #include "ruby.h" #include <cairo-svg.h> extern cairo_status_t cairoSvgSurfaceCallback (void *closure, const unsigned char *data, unsigned int length); extern cairo_status_t cairoPngSurfaceCallback (void *closure, const unsigned char *data, unsigned int length); #endif
f4f8b1584ab3d2fdc40c020f4b617a6cee05b976
a12b448f44beb4d521cb7e31677281f41df35f0b
/benchmarks/framework_benchmarking/software/pencil/include/pencil_host_impl.h
968dfc55c966fbad4e3d025b16caefbe993d6e57
[ "MIT" ]
permissive
Tiramisu-Compiler/tiramisu
d45f65dd9c35f643b3531ec79df1203c7ea3371d
f13e480f0ddb142cec371b7d7431a41d8ca885ec
refs/heads/master
2023-08-25T12:21:26.889736
2023-05-09T18:40:52
2023-05-09T18:40:52
58,378,976
906
168
MIT
2023-09-08T11:47:06
2016-05-09T13:33:51
C++
UTF-8
C
false
false
286
h
pencil_host_impl.h
#ifndef PENCIL_HOST_IMPL_H #define PENCIL_HOST_IMPL_H /* TODO: Might avoid this file by macrofying the math defs and enable only when needed. (And not define that macro in pencil.h or pencil_cpp.h, like PENCIL_MATHDECL) */ #include "pencil_mathimpl.h" #endif /* PENCIL_HOST_IMPL_H */
bc59a680e3d8e484017fde22d34a006bd72a8d7a
d8fbc197e4fb03e0f083291ec92b75542bcb4917
/src/crt/protocol/websocketframe.c
f5115d253ad6062c8d63d86cc8fbd81e50fc39e1
[]
no_license
hujianzhe/util
b7576091b9d1daa4e3b7f2e8d3be85501c7877a5
146f6c2395c6d8da7383a41d35ebc8190ba8ea02
refs/heads/master
2023-08-18T13:00:57.886249
2023-08-15T08:57:33
2023-08-15T08:57:33
112,769,785
162
55
null
2020-06-09T16:03:15
2017-12-01T17:49:43
C
UTF-8
C
false
false
5,473
c
websocketframe.c
// // Created by hujianzhe on 18-8-17. // #include "../../../inc/datastruct/base64.h" #include "../../../inc/datastruct/sha1.h" #include "../../../inc/datastruct/memfunc.h" #include "../../../inc/crt/protocol/websocketframe.h" #include <string.h> #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif char* websocketframeComputeSecAccept(const char* sec_key, unsigned int sec_keylen, char sec_accept[60]) { static const char WEB_SOCKET_MAGIC_KEY[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; SHA1_CTX sha1_ctx; unsigned char sha1_key[20]; unsigned char* pk = (unsigned char*)malloc(sec_keylen + sizeof(WEB_SOCKET_MAGIC_KEY) - 1); if (!pk) { return NULL; } memmove(pk, sec_key, sec_keylen); memmove(pk + sec_keylen, WEB_SOCKET_MAGIC_KEY, sizeof(WEB_SOCKET_MAGIC_KEY) - 1); SHA1Init(&sha1_ctx); SHA1Update(&sha1_ctx, (unsigned char*)pk, sec_keylen + sizeof(WEB_SOCKET_MAGIC_KEY) - 1); SHA1Final(sha1_key, &sha1_ctx); free(pk); base64Encode(sha1_key, sizeof(sha1_key), sec_accept); return sec_accept; } int websocketframeDecodeHandshakeRequest(const char* data, unsigned int datalen, const char** sec_key, unsigned int* sec_keylen, const char** sec_protocol, unsigned int* sec_protocol_len) { const char *ks, *ke; const char* e = strStr(data, datalen, "\r\n\r\n", 4); if (!e) { return 0; } ks = strStr(data, e - data, "Sec-WebSocket-Key:", 18); if (!ks) { return -1; } for (ks += 18; ks < e && *ks <= 32; ++ks); if (ks >= e) { return -1; } ke = strChr(ks, e - ks + 1, '\r'); if (!ke) { return -1; } *sec_key = ks; *sec_keylen = ke - ks; *sec_protocol = NULL; *sec_protocol_len = 0; do { ks = strStr(data, e - data, "Sec-WebSocket-Protocol:", 23); if (!ks) { break; } for (ks += 23; ks < e && *ks <= 32; ++ks); if (ks >= e) { break; } ke = strChr(ks, e - ks + 1, '\r'); if (!ke) { break; } *sec_protocol = ks; *sec_protocol_len = ke - ks; } while (0); return e - data + 4; } char* websocketframeEncodeHandshakeResponse(const char* sec_accept, unsigned int sec_accept_len, char buf[162]) { buf[0] = 0; strcat(buf, "HTTP/1.1 101 Switching Protocols\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: "); strncat(buf, sec_accept, sec_accept_len); strcat(buf, "\r\n\r\n"); return buf; } char* websocketframeEncodeHandshakeResponseWithProtocol(const char* sec_accept, unsigned int sec_accept_len, const char* sec_protocol, unsigned int sec_protocol_len) { char* buf; size_t buflen = 162; if (sec_protocol && sec_protocol_len > 0) { buflen += (24 + sec_protocol_len + 2); /* Sec-WebSocket-Protocol: %s\r\n */ } buf = (char*)malloc(buflen); if (!buf) { return NULL; } buf[0] = 0; strcat(buf, "HTTP/1.1 101 Switching Protocols\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: "); strncat(buf, sec_accept, sec_accept_len); if (sec_protocol && sec_protocol_len > 0) { strcat(buf, "\r\nSec-WebSocket-Protocol: "); strncat(buf, sec_protocol, sec_protocol_len); } strcat(buf, "\r\n\r\n"); return buf; } int websocketframeDecode(unsigned char* buf, unsigned long long len, unsigned char** data, unsigned long long* datalen, int* is_fin, int* type) { unsigned char frame_is_fin, frame_type; unsigned int mask_len = 0, ext_payload_filed_len = 0; unsigned char* payload_data = NULL; unsigned long long payload_len; const unsigned int header_size = 2; if (len < header_size) return 0; frame_is_fin = buf[0] >> 7; frame_type = buf[0] & 0x0f; if (buf[1] >> 7) mask_len = 4; payload_len = buf[1] & 0x7f; if (payload_len < 126) { if (len < header_size + ext_payload_filed_len + mask_len) return 0; } else if (payload_len == 126) { ext_payload_filed_len = 2; if (len < header_size + ext_payload_filed_len + mask_len) return 0; payload_len = memFromBE16(*(unsigned short*)&buf[header_size]); } else if (payload_len == 127) { ext_payload_filed_len = 8; if (len < header_size + ext_payload_filed_len + mask_len) return 0; payload_len = memFromBE64(*(unsigned long long*)&data[header_size]); } else return -1; if (len < header_size + ext_payload_filed_len + mask_len + payload_len) return 0; payload_data = &buf[header_size + ext_payload_filed_len + mask_len]; if (mask_len) { unsigned long long i; unsigned char* mask = &buf[header_size + ext_payload_filed_len]; for (i = 0; i < payload_len; ++i) payload_data[i] ^= mask[i % 4]; } *is_fin = frame_is_fin; *type = frame_type; *datalen = payload_len; *data = payload_len ? payload_data : NULL; return header_size + ext_payload_filed_len + mask_len + payload_len; } unsigned int websocketframeEncodeHeadLength(unsigned long long datalen) { if (datalen < 126) return 2; else if (datalen <= 0xffff) return 4; else return 10; } void websocketframeEncode(void* headbuf, int is_fin, int prev_is_fin, int type, unsigned long long datalen) { unsigned char* phead = (unsigned char*)headbuf; if (prev_is_fin && is_fin) { phead[0] = type | 0x80; } else if (prev_is_fin) { phead[0] = type; } else if (is_fin) { phead[0] = WEBSOCKET_CONTINUE_FRAME | 0x80; } else { phead[0] = WEBSOCKET_CONTINUE_FRAME; } if (datalen < 126) { phead[1] = datalen; } else if (datalen <= 0xffff) { phead[1] = 126; *(unsigned short*)&phead[2] = memToBE16(datalen); } else { phead[1] = 127; *(unsigned long long*)&phead[2] = memToBE64(datalen); } } #ifdef __cplusplus } #endif
5008b5a5b7cbc4f9e94656637afde284ae375081
bdec4e67719c2dda02cb7e51f5d426fdc0c23972
/test/unit/util/test.h
e5d7e31e604f91e321ebd0d9261b70c49a72ad26
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
vizzuhq/vizzu-lib
032a653267e22a0ce1f76cbca52c39356fac982b
a048ee50400bc12b336759cf5ab8648ce207f629
refs/heads/main
2023-09-02T20:04:26.929526
2023-08-31T16:03:38
2023-08-31T16:03:38
374,784,415
1,537
93
Apache-2.0
2023-09-14T06:24:21
2021-06-07T19:53:30
JavaScript
UTF-8
C
false
false
133
h
test.h
#ifndef TEST_H #define TEST_H #include "application.h" #include "collection.h" #include "compiler.h" #include "condition.h" #endif
f03f8e53138d9e33f62f33e0feff4ba1c21b6a19
e814383d36a10839104efaa4df277996ab220fa3
/ompi/group/group.h
582518920152cdc49c317d05a37cd2e5088ed270
[ "mpich2", "BSD-3-Clause-Open-MPI" ]
permissive
open-mpi/ompi
a1d7483ae1d83dd8fd8ae3ee95e832e0a0ee04e3
1edfdb025c4450f694600083ad871cf06c8d45cd
refs/heads/main
2023-09-01T01:30:02.040705
2023-08-29T17:32:18
2023-08-29T17:32:18
24,107,001
2,008
973
NOASSERTION
2023-09-14T20:59:26
2014-09-16T16:08:30
C
UTF-8
C
false
false
18,904
h
group.h
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil -*- */ /* * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2020 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2006-2007 University of Houston. All rights reserved. * Copyright (c) 2007-2017 Cisco Systems, Inc. All rights reserved * Copyright (c) 2009 Sun Microsystems, Inc. All rights reserved. * Copyright (c) 2012 Oak Ridge National Labs. All rights reserved. * Copyright (c) 2013-2018 Los Alamos National Security, LLC. All rights * reserved. * Copyright (c) 2016 Research Organization for Information Science * and Technology (RIST). All rights reserved. * Copyright (c) 2018-2022 Triad National Security, LLC. All rights * reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ /** * @file: * * Infrastructure for MPI group support. */ #ifndef OMPI_GROUP_H #define OMPI_GROUP_H #include "ompi_config.h" #include "ompi/proc/proc.h" #include "mpi.h" #include "opal/class/opal_pointer_array.h" #include "opal/mca/threads/threads.h" #include "opal/util/output.h" #include "ompi/instance/instance.h" BEGIN_C_DECLS #define BSIZE ((int)sizeof(unsigned char)*8) struct ompi_group_sporadic_list_t { int rank_first; int length; }; struct ompi_group_sporadic_data_t { struct ompi_group_sporadic_list_t *grp_sporadic_list; /** list to hold the sporadic struct */ int grp_sporadic_list_len;/** length of the structure*/ }; struct ompi_group_strided_data_t { int grp_strided_offset; /** offset to start from when including or excluding */ int grp_strided_stride; /** stride for including or excluding */ int grp_strided_last_element; /** the last element to be included for */ }; struct ompi_group_bitmap_data_t { unsigned char *grp_bitmap_array; /* the bit map array for sparse groups of type BMAP */ int grp_bitmap_array_len; /* length of the bit array */ }; /** * Group structure * Currently we have four formats for storing the process pointers that are members * of the group. * PList: a dense format that stores all the process pointers of the group. * Sporadic: a sparse format that stores the ranges of the ranks from the parent group, * that are included in the current group. * Strided: a sparse format that stores three integers that describe a red-black pattern * that the current group is formed from its parent group. * Bitmap: a sparse format that maintains a bitmap of the included processes from the * parent group. For each process that is included from the parent group * its corresponding rank is set in the bitmap array. */ struct ompi_group_t { opal_object_t super; /**< base class */ int grp_proc_count; /**< number of processes in group */ int grp_my_rank; /**< rank in group */ int grp_f_to_c_index; /**< index in Fortran <-> C translation array */ struct ompi_proc_t **grp_proc_pointers; /**< list of pointers to ompi_proc_t structures for each process in the group */ uint32_t grp_flags; /**< flags, e.g. freed, cannot be freed etc.*/ /** pointer to the original group when using sparse storage */ struct ompi_group_t *grp_parent_group_ptr; union { struct ompi_group_sporadic_data_t grp_sporadic; struct ompi_group_strided_data_t grp_strided; struct ompi_group_bitmap_data_t grp_bitmap; } sparse_data; ompi_instance_t *grp_instance; /**< instance this group was allocated within */ }; typedef struct ompi_group_t ompi_group_t; OMPI_DECLSPEC OBJ_CLASS_DECLARATION(ompi_group_t); /** * Padded struct to maintain back compatibility. * See ompi/communicator/communicator.h comments with struct ompi_communicator_t * for full explanation why we chose the following padding construct for predefines. */ #define PREDEFINED_GROUP_PAD 256 struct ompi_predefined_group_t { struct ompi_group_t group; char padding[PREDEFINED_GROUP_PAD - sizeof(ompi_group_t)]; }; typedef struct ompi_predefined_group_t ompi_predefined_group_t; /* * The following include pulls in shared typedefs with debugger plugins. * For more information on why we do this see the Notice to developers * comment at the top of the ompi_msgq_dll.c file. */ #include "group_dbg.h" #define OMPI_GROUP_IS_INTRINSIC(_group) ((_group)->grp_flags&OMPI_GROUP_INTRINSIC) #define OMPI_GROUP_IS_DENSE(_group) ((_group)->grp_flags & OMPI_GROUP_DENSE) #define OMPI_GROUP_IS_SPORADIC(_group) ((_group)->grp_flags & OMPI_GROUP_SPORADIC) #define OMPI_GROUP_IS_STRIDED(_group) ((_group)->grp_flags & OMPI_GROUP_STRIDED) #define OMPI_GROUP_IS_BITMAP(_group) ((_group)->grp_flags & OMPI_GROUP_BITMAP) #define OMPI_GROUP_SET_INTRINSIC(_group) ( (_group)->grp_flags |= OMPI_GROUP_INTRINSIC) #define OMPI_GROUP_SET_DENSE(_group) ( (_group)->grp_flags |= OMPI_GROUP_DENSE) #define OMPI_GROUP_SET_SPORADIC(_group) ( (_group)->grp_flags |= OMPI_GROUP_SPORADIC) #define OMPI_GROUP_SET_STRIDED(_group) ( (_group)->grp_flags |= OMPI_GROUP_STRIDED) #define OMPI_GROUP_SET_BITMAP(_group) ( (_group)->grp_flags |= OMPI_GROUP_BITMAP) /** * Table for Fortran <-> C group handle conversion */ OMPI_DECLSPEC extern struct opal_pointer_array_t ompi_group_f_to_c_table; OMPI_DECLSPEC extern struct ompi_predefined_group_t ompi_mpi_group_null; OMPI_DECLSPEC extern struct ompi_predefined_group_t *ompi_mpi_group_null_addr; #if OPAL_ENABLE_FT_MPI /* * Global list of failed processes */ OMPI_DECLSPEC extern ompi_group_t *ompi_group_all_failed_procs; OMPI_DECLSPEC extern struct opal_mutex_t ompi_group_afp_mutex; #endif /* OPAL_ENABLE_FT_MPI */ /* * function prototypes */ /** * Allocate a new group structure. * * @param orig_group Original group * @param group_size Number of MPI processes in the group * * @return Pointer to new group structure */ OMPI_DECLSPEC ompi_group_t *ompi_group_allocate(ompi_group_t *orig_group, int group_size); ompi_group_t *ompi_group_allocate_plist_w_procs (ompi_group_t *orig_group, ompi_proc_t **procs, int group_size); ompi_group_t *ompi_group_allocate_sporadic(ompi_group_t *orig_group, int group_size); ompi_group_t *ompi_group_allocate_strided(ompi_group_t *orig_group); ompi_group_t *ompi_group_allocate_bmap(ompi_group_t *orig_group, int group_size); /** * @brief Allocate a dense group from a group * * @param[in] group group * * @returns new group pointer on success * @returns NULL on error * * This function duplicates a group. The new group will have a dense process * table. */ ompi_group_t *ompi_group_flatten (ompi_group_t *group, int max_procs); /** * Increment the reference count of the proc structures. * * @param group Pointer to ompi_group_t structute (IN) * */ OMPI_DECLSPEC void ompi_group_increment_proc_count(ompi_group_t *group); /** * Decrement the reference count of the proc structures. * * @param group Pointer to ompi_group_t structute (IN) * */ OMPI_DECLSPEC void ompi_group_decrement_proc_count(ompi_group_t *group); /** * Initialize OMPI group infrastructure. * * @return Error code */ int ompi_group_init(void); /** * Get group size. * * @param group Pointer to ompi_group_t structute (IN) * * @return Group size */ static inline int ompi_group_size(ompi_group_t *group) { return group->grp_proc_count; } /** * Get group rank * * @param group Pointer to ompi_group_t structure (IN) * * @return Group rank */ static inline int ompi_group_rank(ompi_group_t *group) { return group->grp_my_rank; } /** * Set group rank in the input group structure * * @param group Group Pointer to ompi_group_t structure (IN) * @param proc_pointer Pointer to ompi_proc_t structure for process. * MPI_PROC_NULL may be used to indicate proc not * in group * * @return Error code */ void ompi_set_group_rank(ompi_group_t *group, struct ompi_proc_t *proc_pointer); /** * Abstracting MPI_Group_translate_ranks to an ompi function for internal use */ OMPI_DECLSPEC int ompi_group_translate_ranks ( ompi_group_t *group1, int n_ranks, const int *ranks1, ompi_group_t *group2, int *ranks2); /** * Abstracting MPI_Group_compare to an ompi function for internal use */ OMPI_DECLSPEC int ompi_group_compare(ompi_group_t *group1, ompi_group_t *group2, int *result); /** * Abstracting MPI_Group_free, since it is required by some internal functions... */ int ompi_group_free (ompi_group_t **group); /** * Functions to handle process pointers for sparse group formats */ int ompi_group_translate_ranks_sporadic ( ompi_group_t *group1, int n_ranks, const int *ranks1, ompi_group_t *group2, int *ranks2); int ompi_group_translate_ranks_sporadic_reverse ( ompi_group_t *group1, int n_ranks, const int *ranks1, ompi_group_t *group2, int *ranks2); int ompi_group_translate_ranks_strided ( ompi_group_t *group1, int n_ranks, const int *ranks1, ompi_group_t *group2, int *ranks2); int ompi_group_translate_ranks_strided_reverse ( ompi_group_t *group1, int n_ranks, const int *ranks1, ompi_group_t *group2, int *ranks2); int ompi_group_translate_ranks_bmap ( ompi_group_t *group1, int n_ranks, const int *ranks1, ompi_group_t *group2, int *ranks2); int ompi_group_translate_ranks_bmap_reverse ( ompi_group_t *group1, int n_ranks, const int *ranks1, ompi_group_t *group2, int *ranks2); /** * Prototypes for the group back-end functions. Argument lists are similar to the according C MPI functions. */ int ompi_group_incl(ompi_group_t* group, int n, const int *ranks, ompi_group_t **new_group); int ompi_group_excl(ompi_group_t* group, int n, const int *ranks, ompi_group_t **new_group); int ompi_group_range_incl(ompi_group_t* group, int n_triplets, int ranges[][3],ompi_group_t **new_group); int ompi_group_range_excl(ompi_group_t* group, int n_triplets, int ranges[][3],ompi_group_t **new_group); int ompi_group_union (ompi_group_t* group1, ompi_group_t* group2, ompi_group_t **new_group); int ompi_group_intersection(ompi_group_t* group1,ompi_group_t* group2, ompi_group_t **new_group); int ompi_group_difference(ompi_group_t* group1, ompi_group_t* group2, ompi_group_t **new_group); /** * Include Functions to handle Sparse storage formats */ int ompi_group_incl_plist(ompi_group_t* group, int n, const int *ranks, ompi_group_t **new_group); int ompi_group_incl_spor(ompi_group_t* group, int n, const int *ranks, ompi_group_t **new_group); int ompi_group_incl_strided(ompi_group_t* group, int n, const int *ranks, ompi_group_t **new_group); int ompi_group_incl_bmap(ompi_group_t* group, int n, const int *ranks, ompi_group_t **new_group); /** * Functions to calculate storage spaces */ int ompi_group_calc_plist ( int n, const int *ranks ); int ompi_group_calc_strided ( int n, const int *ranks ); int ompi_group_calc_sporadic ( int n, const int *ranks ); int ompi_group_calc_bmap ( int n, int orig_size , const int *ranks ); /** * Function to return the minimum value in an array */ int ompi_group_minloc (int list[], int length); /** * @brief Helper function for retrieving the proc of a group member in a dense group * * This function exists to handle the translation of sentinel group members to real * ompi_proc_t's. If a sentinel value is found and allocate is true then this function * looks for an existing ompi_proc_t using ompi_proc_for_name which will allocate a * ompi_proc_t if one does not exist. If allocate is false then sentinel values translate * to NULL. */ static inline struct ompi_proc_t *ompi_group_dense_lookup (ompi_group_t *group, const int peer_id, const bool allocate) { ompi_proc_t *proc; #if OPAL_ENABLE_DEBUG if (peer_id >= group->grp_proc_count) { opal_output(0, "ompi_group_dense_lookup: invalid peer index (%d)", peer_id); return (struct ompi_proc_t *) NULL; } #endif proc = group->grp_proc_pointers[peer_id]; if (OPAL_UNLIKELY(ompi_proc_is_sentinel (proc))) { if (!allocate) { return NULL; } /* replace sentinel value with an actual ompi_proc_t */ ompi_proc_t *real_proc = (ompi_proc_t *) ompi_proc_for_name (ompi_proc_sentinel_to_name ((uintptr_t) proc)); if (opal_atomic_compare_exchange_strong_ptr ((opal_atomic_intptr_t *)(group->grp_proc_pointers + peer_id), (intptr_t *) &proc, (intptr_t) real_proc)) { OBJ_RETAIN(real_proc); } proc = real_proc; } return proc; } /* * This is the function that iterates through the sparse groups to the dense group * to reach the process pointer */ static inline ompi_proc_t *ompi_group_get_proc_ptr (ompi_group_t *group, int rank, const bool allocate) { #if OMPI_GROUP_SPARSE do { if (OMPI_GROUP_IS_DENSE(group)) { break; } int ranks1 = rank; ompi_group_translate_ranks (group, 1, &ranks1, group->grp_parent_group_ptr, &rank); group = group->grp_parent_group_ptr; } while (1); #endif return ompi_group_dense_lookup (group, rank, allocate); } /** * @brief Get the raw proc pointer from the group * * This function will either return a ompi_proc_t if one exists (either stored in the group * or cached in the proc hash table) or a sentinel value representing the proc. This * differs from ompi_group_get_proc_ptr() which returns the ompi_proc_t or NULL. */ static inline ompi_proc_t *ompi_group_get_proc_ptr_raw (const ompi_group_t *group, int rank) { #if OMPI_GROUP_SPARSE do { if (OMPI_GROUP_IS_DENSE(group)) { break; } int ranks1 = rank; ompi_group_translate_ranks (group, 1, &ranks1, group->grp_parent_group_ptr, &rank); group = group->grp_parent_group_ptr; } while (1); #endif return group->grp_proc_pointers[rank]; } static inline opal_process_name_t ompi_group_get_proc_name (const ompi_group_t *group, int rank) { ompi_proc_t *proc = ompi_group_get_proc_ptr_raw (group, rank); if (ompi_proc_is_sentinel (proc)) { return ompi_proc_sentinel_to_name ((intptr_t) proc); } return proc->super.proc_name; } /** * Inline function to check if sparse groups are enabled and return the direct access * to the proc pointer, otherwise the lookup function */ static inline struct ompi_proc_t* ompi_group_peer_lookup(ompi_group_t *group, int peer_id) { return ompi_group_get_proc_ptr (group, peer_id, true); } static inline struct ompi_proc_t *ompi_group_peer_lookup_existing (ompi_group_t *group, int peer_id) { return ompi_group_get_proc_ptr (group, peer_id, false); } #if OPAL_ENABLE_FT_MPI /* This function is for finding the rank of a proc in a group * return MPI_PROC_NULL if the proc is not in the group, the rank otherwise. */ static inline int ompi_group_proc_lookup_rank (ompi_group_t* group, ompi_proc_t* proc) { int i, np, v; assert( NULL != proc ); assert( !ompi_proc_is_sentinel(proc) ); np = ompi_group_size(group); if( 0 == np ) return MPI_PROC_NULL; /* heuristic: On comm_world, start the lookup from v=vpid, so that * when working on comm_world, the search is O(1); * Otherwise, wild guess: start from a proportional position * compared to comm_world position. */ v = proc->super.proc_name.vpid; v = (v<np)? v: v*ompi_proc_world_size()/np; for( i = 0; i < np; i++ ) { int rank = (i+v)%np; /* procs are lazy initialized and may be a sentinel. Handle both cases. */ ompi_proc_t* p = ompi_group_get_proc_ptr_raw(group, rank); if(OPAL_LIKELY(!ompi_proc_is_sentinel(p))) { if(p == proc) return rank; } else { opal_process_name_t name = ompi_proc_sentinel_to_name((uintptr_t)p); if( OPAL_EQUAL == ompi_rte_compare_name_fields(OMPI_RTE_CMP_ALL, &proc->super.proc_name, &name) ) return rank; } } return MPI_PROC_NULL; } #endif /* OPAL_ENABLE_FT_MPI */ /** * Return true if all processes in the group are not on the local node. */ bool ompi_group_have_remote_peers (ompi_group_t *group); /** * Count the number of processes on the local node. */ int ompi_group_count_local_peers (ompi_group_t *group); /** * @brief Check if groups overlap * * @param[in] group1 ompi group * @param[in] group2 ompi group * * @returns true if any proc in group1 is also in group2 * @returns false otherwise */ bool ompi_group_overlap (const ompi_group_t *group1, const ompi_group_t *group2); /** * Function to print the group info */ int ompi_group_dump (ompi_group_t* group); /** * Ceil Function so not to include the math.h lib */ int ompi_group_div_ceil (int num, int den); /** * Create a process name array from a group */ int ompi_group_to_proc_name_array (ompi_group_t *group, opal_process_name_t **name_array, size_t *name_array_size); /** * Return instance from a group */ static inline ompi_instance_t *ompi_group_get_instance(ompi_group_t *group) { return group->grp_instance; } END_C_DECLS #endif /* OMPI_GROUP_H */
e9c4acc0c302dc36ed3d495e0017d15efd0d7f36
cce217852fee0a222fdca9f8f6ee8897c540c663
/patch/bar_tagpreview.h
44be36d6db0259ba19725ecbc3df410280c01fc7
[ "MIT" ]
permissive
bakkeby/dwm-flexipatch
d3e920f13701714d33a5ea75a12bb52df68f54aa
7849eaa08b71d359c939b946598716539b4ba1d7
refs/heads/master
2023-08-31T22:09:22.250888
2023-08-24T16:18:03
2023-08-24T16:18:03
206,426,925
1,094
366
MIT
2023-08-24T16:18:04
2019-09-04T22:35:38
C
UTF-8
C
false
false
169
h
bar_tagpreview.h
static void createpreview(Monitor *m); static void hidetagpreview(Monitor *m); static void showtagpreview(int tag, int x, int y); static void tagpreviewswitchtag(void);
a274e52cf958905c34e59220d444665663ba4295
aabc1530cff8d7ac7f90224cfa041edbb9c35d28
/tinydixy.c
5572d9fefbbb9ba4e7f9fcb666fbea43c7ef5009
[ "Unlicense" ]
permissive
r-lyeh/tinybits
9d4e1ddb492125c140b38d98b3c0f795bdc96e40
2a735d9717c9da30fa7eb60c2cc158dee46f8d40
refs/heads/master
2023-08-29T06:01:17.399171
2022-12-26T17:10:54
2022-12-26T17:10:54
58,539,236
322
29
Unlicense
2021-01-27T19:26:12
2016-05-11T11:30:35
C
UTF-8
C
false
false
2,793
c
tinydixy.c
// tinydixy, small hierarchical config file format (subset of YAML, spec in https://github.com/kuyawa/Dixy) // - rlyeh, public domain // api, returns number of pairs found int tinydixy( const char *buffer, int (*yield)(const char *key, const char *val) ); // implementation #include <stdio.h> #include <stdlib.h> int tinydixy( const char *s, int (*yield)(const char *key, const char *val) ) { char *map = 0; int mapcap = 0, maplen = 0, num_pairs_found = 0; enum { DEL, REM, KEY, SUB, VAL } fsm = DEL; const char *cut[5] = {0}, *end[5] = {0}; while( *s ) { while( *s && (*s == '\r' || *s == '\n') ) ++s; /**/ if( *s == '#' ) cut[fsm = REM] = ++s; else if( *s == ' ' || *s == '\t' ) cut[fsm = SUB] = ++s; else if( *s == ':' ) cut[fsm = VAL] = ++s; else if( *s > ' ' && *s <= 'z' ) cut[fsm = KEY] = cut[SUB] = end[SUB] = s, free(map), map = 0, mapcap = 0, maplen = 0; else { ++s; continue; } /**/ if( fsm == REM ) { while(*s && *s != '\r'&& *s != '\n') ++s; } else if( fsm == KEY ) { while(*s && *s > ' ' && *s <= 'z' && *s != ':') ++s; end[fsm] = s; } else if( fsm == SUB ) { while(*s && *s > ' ' && *s <= 'z' && *s != ':') ++s; end[fsm] = s; } else if( fsm == VAL ) { while(*s && *s >= ' ' && *s <= 'z' && *s != '\r' && *s != '\n') ++s; end[fsm] = s; while( end[fsm][-1] == ' ' ) --end[fsm]; char buf[256] = {0}, *key = buf, *val = ""; if( end[KEY] - cut[KEY] ) key += sprintf(key, "%.*s", end[KEY] - cut[KEY], cut[KEY] ); if( end[SUB] - cut[SUB] ) key += sprintf(key, ".%.*s", end[SUB] - cut[SUB], cut[SUB] ); int reqlen = (key - buf) + 1 + (end[VAL] - cut[VAL]) + 1 + 1; if( (reqlen + maplen) >= mapcap ) map = realloc( map, mapcap += reqlen + 512 ); sprintf( map + maplen, "%.*s%c%.*s%c%c", key - buf, buf, 0, end[VAL] - cut[VAL], cut[VAL], 0, 0 ); val = map + maplen + (key - buf) + 2, key = map + maplen; if( val[0] ) { yield( key, val ); num_pairs_found++; } maplen += reqlen - 1; } } free( map ); return num_pairs_found; } // sample /* int puts2( const char *key, const char *val ) { printf("%s:'%s'\n", key, val); return 0; } int main() { const char *sample = "# Dixy 1.0\n" "\n" "name: Taylor Swift\n" "age: 27\n" "phones:\n" " 0: 555-SWIFT\n" " 1: 900-SWIFT\n" " 2: 800-TAYLOR\n" "body:\n" " height: 6 ft\n" " weight: 120 lbs\n" "pets:\n" " 0:\n" " name: Fido\n" " breed: chihuahua\n" " 1:\n" " name: Tinkerbell\n" " breed: bulldog\n"; printf("%d keys found\n", tinydixy( sample, puts2 )); } */
eef1854a620ee474fdd66d8684c44125ace3c65a
3f017c2c3a55a2ac783045a23977765862ef4b20
/modules/mp3/libmp3/xingmp3/csbt.c
df6141c36738b80bcc51170fc9ef87bfb2603f26
[]
no_license
DC-SWAT/DreamShell
8e4310087eb7f8e9bed285b8c66992e4df9c9143
f2551e18c06345fed0f5144245d6380203c20fa6
refs/heads/master
2023-07-09T16:50:05.291266
2023-06-23T05:32:37
2023-06-23T05:32:37
13,268,848
308
94
null
2023-06-23T05:04:53
2013-10-02T10:58:30
C
UTF-8
C
false
false
10,207
c
csbt.c
/*____________________________________________________________________________ FreeAmp - The Free MP3 Player MP3 Decoder originally Copyright (C) 1995-1997 Xing Technology Corp. http://www.xingtech.com Portions Copyright (C) 1998 EMusic.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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You 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. ____________________________________________________________________________*/ /**** csbt.c *************************************************** MPEG audio decoder, dct and window portable C 1/7/96 mod for Layer III ******************************************************************/ #include <float.h> #include <math.h> #include "L3.h" #include "mhead.h" void fdct32(MPEG *m, float *, float *); void fdct32_dual(MPEG *m, float *, float *); void fdct32_dual_mono(MPEG *m, float *, float *); void fdct16(MPEG *m, float *, float *); void fdct16_dual(MPEG *m, float *, float *); void fdct16_dual_mono(MPEG *m, float *, float *); void fdct8(MPEG *m, float *, float *); void fdct8_dual(MPEG *m, float *, float *); void fdct8_dual_mono(MPEG *m, float *, float *); void window(MPEG *m, float *, int , short *pcm); void window_dual(MPEG *m, float *, int , short *pcm); void window16(MPEG *m, float *, int , short *pcm); void window16_dual(MPEG *m, float *, int , short *pcm); void window8(MPEG *m, float *, int , short *pcm); void window8_dual(MPEG *m, float *, int , short *pcm); float *dct_coef_addr(MPEG *m); /*-------------------------------------------------------------------------*/ /* circular window buffers */ /*======================================================================*/ static void gencoef(MPEG *m) /* gen coef for N=32 (31 coefs) */ { int p, n, i, k; double t, pi; float *coef32; coef32 = dct_coef_addr(m); pi = 4.0 * atan(1.0); n = 16; k = 0; for (i = 0; i < 5; i++, n = n / 2) { for (p = 0; p < n; p++, k++) { t = (pi / (4 * n)) * (2 * p + 1); coef32[k] = (float) (0.50 / cos(t)); } } } /*------------------------------------------------------------*/ void sbt_init(MPEG *m) { int i; if (m->csbt.first_pass) { gencoef(m); m->csbt.first_pass = 0; } /* clear window m->csbt.vbuf */ for (i = 0; i < 512; i++) { m->csbt.vbuf[i] = 0.0F; m->csbt.vbuf2[i] = 0.0F; } m->csbt.vb2_ptr = m->csbt.vb_ptr = 0; } /*============================================================*/ /*============================================================*/ /*============================================================*/ void sbt_mono(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct32(m, sample, m->csbt.vbuf + m->csbt.vb_ptr); window(m, m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ void sbt_dual(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct32_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); fdct32_dual(m,sample + 1, m->csbt.vbuf2 + m->csbt.vb_ptr); window_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); window_dual(m,m->csbt.vbuf2, m->csbt.vb_ptr, pcm + 1); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 64; } } /*------------------------------------------------------------*/ /* convert dual to mono */ void sbt_dual_mono(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct32_dual_mono(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /* convert dual to left */ void sbt_dual_left(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct32_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /* convert dual to right */ void sbt_dual_right(MPEG *m, float *sample, short *pcm, int n) { int i; sample++; /* point to right chan */ for (i = 0; i < n; i++) { fdct32_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 32) & 511; pcm += 32; } } /*------------------------------------------------------------*/ /*---------------- 16 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ void sbt16_mono(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct16(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window16(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void sbt16_dual(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct16_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); fdct16_dual(m,sample + 1, m->csbt.vbuf2 + m->csbt.vb_ptr); window16_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); window16_dual(m,m->csbt.vbuf2, m->csbt.vb_ptr, pcm + 1); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 32; } } /*------------------------------------------------------------*/ void sbt16_dual_mono(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct16_dual_mono(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window16(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void sbt16_dual_left(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct16_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window16(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ void sbt16_dual_right(MPEG *m, float *sample, short *pcm, int n) { int i; sample++; for (i = 0; i < n; i++) { fdct16_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window16(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 16) & 255; pcm += 16; } } /*------------------------------------------------------------*/ /*---------------- 8 pt sbt's -------------------------------*/ /*------------------------------------------------------------*/ void sbt8_mono(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct8(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window8(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void sbt8_dual(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct8_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); fdct8_dual(m,sample + 1, m->csbt.vbuf2 + m->csbt.vb_ptr); window8_dual(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); window8_dual(m,m->csbt.vbuf2, m->csbt.vb_ptr, pcm + 1); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 16; } } /*------------------------------------------------------------*/ void sbt8_dual_mono(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct8_dual_mono(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window8(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void sbt8_dual_left(MPEG *m, float *sample, short *pcm, int n) { int i; for (i = 0; i < n; i++) { fdct8_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window8(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ void sbt8_dual_right(MPEG *m, float *sample, short *pcm, int n) { int i; sample++; for (i = 0; i < n; i++) { fdct8_dual(m,sample, m->csbt.vbuf + m->csbt.vb_ptr); window8(m,m->csbt.vbuf, m->csbt.vb_ptr, pcm); sample += 64; m->csbt.vb_ptr = (m->csbt.vb_ptr - 8) & 127; pcm += 8; } } /*------------------------------------------------------------*/ /*------------------------------------------------------------*/ #include "csbtb.c" /* 8 bit output */ #include "csbtL3.c" /* Layer III */ /*------------------------------------------------------------*/
fce3426e8d6b89c5ab644322a67b06f3b3411c73
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/u-boot_new/arch/blackfin/include/asm/string.h
aea4e29c9d9eb8088adc715e46d43e9eb5d788fd
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "GPL-2.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
1,747
h
string.h
/* * U-boot - string.h String functions * * Copyright (c) 2005-2007 Analog Devices Inc. * * SPDX-License-Identifier: GPL-2.0+ */ /* Changed by Lineo Inc. May 2001 */ #ifndef _BLACKFINNOMMU_STRING_H_ #define _BLACKFINNOMMU_STRING_H_ #ifdef __KERNEL__ /* only set these up for kernel code */ #define __HAVE_ARCH_STRCPY #define __HAVE_ARCH_STRNCPY #define __HAVE_ARCH_STRCMP #define __HAVE_ARCH_STRNCMP #define __HAVE_ARCH_MEMCPY #define __HAVE_ARCH_MEMCMP #define __HAVE_ARCH_MEMSET #define __HAVE_ARCH_MEMMOVE extern char *strcpy(char *dest, const char *src); extern char *strncpy(char *dest, const char *src, size_t n); extern int strcmp(const char *cs, const char *ct); extern int strncmp(const char *cs, const char *ct, size_t count); extern void *memcpy(void *dest, const void *src, size_t count); extern void *memset(void *s, int c, size_t count); extern int memcmp(const void *, const void *, size_t); extern void *memmove(void *dest, const void *src, size_t count); #else /* KERNEL */ /* * let user libraries deal with these, * IMHO the kernel has no place defining these functions for user apps */ #define __HAVE_ARCH_STRCPY 1 #define __HAVE_ARCH_STRNCPY 1 #define __HAVE_ARCH_STRCAT 1 #define __HAVE_ARCH_STRNCAT 1 #define __HAVE_ARCH_STRCMP 1 #define __HAVE_ARCH_STRNCMP 1 #define __HAVE_ARCH_STRNICMP 1 #define __HAVE_ARCH_STRCHR 1 #define __HAVE_ARCH_STRRCHR 1 #define __HAVE_ARCH_STRSTR 1 #define __HAVE_ARCH_STRLEN 1 #define __HAVE_ARCH_STRNLEN 1 #define __HAVE_ARCH_MEMSET 1 #define __HAVE_ARCH_MEMCPY 1 #define __HAVE_ARCH_MEMMOVE 1 #define __HAVE_ARCH_MEMSCAN 1 #define __HAVE_ARCH_MEMCMP 1 #define __HAVE_ARCH_MEMCHR 1 #define __HAVE_ARCH_STRTOK 1 #endif /* KERNEL */ #endif /* _BLACKFIN_STRING_H_ */
bfd3579e4e3a24ea1b8caa4dfb1ad2c6bbd48d98
4dd1db7154358f36e6aeda645180751c9fa03311
/source/agent/sip/sipIn/sip_gateway/sipua/src/sipua.c
3ef99596fc19bf4db8dacbac1b61905e904df1ee
[ "Apache-2.0" ]
permissive
open-webrtc-toolkit/owt-server
7f217c1bef38a55d92271f00ea6cbb9d1687c00b
22c1663bac5ac6c032b50b4e3da1c892fca92eb1
refs/heads/master
2023-08-21T16:38:09.515739
2023-08-10T04:58:55
2023-08-10T04:58:55
174,490,396
1,107
447
Apache-2.0
2023-08-31T02:18:29
2019-03-08T07:34:33
JavaScript
UTF-8
C
false
false
7,704
c
sipua.c
#include <pthread.h> #include <string.h> #include <unistd.h> #include <re/re.h> #include <sipua.h> #include <baresip.h> #include "core.h" #include "sipua.h" #include "sipua_actions.h" #define DEBUG_MODULE "sipua" #define DEBUG_LEVEL 7 #include <re/re_dbg.h> struct sipua_entity { /* sip ua entity */ void *ep; struct le le; /**< Linked list element */ struct mqueue *mq; struct uag *uag; pthread_t thid; }; static pthread_t dnsc_thid; /**************** sipua management ***************/ static sipua_bool sipua_prefer_ipv6 = false; static sipua_bool sipua_trans_udp = true; static sipua_bool sipua_trans_tcp = false; static sipua_bool sipua_trans_tls = false; static struct list sipual; /**< List of SIP UAs(struct ua_entity) */ struct new_sipua_th_paras{ int pfd[2]; void *ep; /*struct uag_cfg cfg;*/ char sip_server[128]; char user_name[64]; char password[64]; char disp_name[64]; }; struct new_sipua_rslt{ struct mqueue *mq; struct uag *uag; }; /**/ static int construct_uag(struct uag **uagp, void *ep, const char *sip_server, const char *user_name, const char *password, const char *disp_name) { int err; char account_str[512]={0}; sprintf(account_str, "%.128s <sip:%.128s:%.64s@%.128s>\n", disp_name, user_name, password, sip_server); err = uag_alloc(uagp, "Intel Integrated SIPUA", ep, sipua_trans_udp ? true : false, sipua_trans_tcp ? true : false, sipua_trans_tls ? true : false, sipua_prefer_ipv6 ? true : false); if (err){ *uagp = NULL; goto out; } err = ua_alloc(NULL, account_str, *uagp); if (err){ mem_deref(*uagp); *uagp = NULL; goto out; } out: return err; } static void *sipua_run(void *arg) { struct new_sipua_th_paras *params = (struct new_sipua_th_paras *)arg; struct new_sipua_rslt rslt = {NULL, NULL}; int err1 = 0, err2 = 0, n = 0; re_thread_init(); fd_setsize(8192); err1 = construct_uag(&rslt.uag, params->ep, params->sip_server, params->user_name, params->password, params->disp_name); if (err1) { warning("!!construct_uag failed.\n"); write(params->pfd[1], &rslt, sizeof(struct new_sipua_rslt)); goto out; } err2 = mqueue_alloc(&rslt.mq, sipua_cmd_handler, rslt.uag); if (err2) { warning("!!mqueue_alloc failed.\n"); write(params->pfd[1], &rslt, sizeof(struct new_sipua_rslt)); goto out; } n = write(params->pfd[1], &rslt, sizeof(struct new_sipua_rslt)); if (n < 0) { warning("!!pipeline write failed.\n"); goto out; } re_main(NULL); out: /* clean up/mem_deref all state */ if (rslt.mq) mem_deref(rslt.mq); if (rslt.uag) mem_deref(rslt.uag); re_thread_close(); return NULL; } static void sipua_destructor(void *arg) { struct sipua_entity *sipua = arg; if (sipua->mq) { mqueue_push(sipua->mq, SIPUA_TERMINATE, NULL); } list_unlink(&sipua->le); } static void *dnsc_run(void *arg) { (void)arg; re_thread_init(); fd_setsize(8192); net_reset(); re_main(NULL); re_thread_close(); return NULL; } static int dnsc_new(void) { return pthread_create(&dnsc_thid, NULL, dnsc_run, NULL); } static void dnsc_delete(void) { pthread_join(dnsc_thid, NULL); } int sipua_new(struct sipua_entity **sipuap, void *endpoint, const char *sip_server, const char * user_name, const char *password, const char *disp_name) { struct sipua_entity *sipua = NULL; pthread_t thread; int err = 0, n = 0; struct new_sipua_th_paras params = {{-1, -1}, NULL, {0}, {0}, {0}, {0}}; struct new_sipua_rslt rslt = {NULL, NULL}; if (!endpoint) { err = -1; goto out; } sipua = mem_zalloc(sizeof(struct sipua_entity), sipua_destructor); if (sipua == NULL || pipe(params.pfd) < 0){ goto out; } params.ep = endpoint; /*memcpy((void *)&params.cfg, (void *)cfg, sizeof(struct uag_cfg));*/ strncat(params.sip_server, sip_server, 127); strncat(params.user_name, user_name, 63); strncat(params.password, password, 63); strncat(params.disp_name, disp_name, 63); pthread_create(&thread, NULL, sipua_run, (void *)&params); n = read(params.pfd[0], &rslt, sizeof(struct new_sipua_rslt)); if (params.pfd[0] >= 0) { fd_close(params.pfd[0]); (void)close(params.pfd[0]); } if (params.pfd[1] >= 0) (void)close(params.pfd[1]); /*sipua->thid = thread;*/ sipua->mq = rslt.mq; sipua->uag = rslt.uag; sipua->thid = thread; out: if (n < 0 || sipua == NULL || sipua->mq == NULL || sipua->uag == NULL){ err = -1; mem_deref(sipua); }else if (sipuap){ *sipuap = sipua; list_append(&sipual, &sipua->le, sipua); } return err; } void sipua_delete(struct sipua_entity *sipua) { pthread_t thread = sipua->thid; mem_deref(sipua); pthread_join(thread, NULL); } int sipua_mod_init(void/*const char *dlpath*/) { int err = 0; (void)sys_coredump_set(true); err = libre_init(); if (err) goto out; err = conf_init(); if (err) { warning("sipua: configuration init: %m\n", err); goto out; } err = load_modules(/*dlpath*/); if (err) { warning("sipua: configuration init: %m\n", err); goto out; } list_init(&sipual); err = dnsc_new(); if (err) { warning("sipua: dnsc_new failed: %m\n", err); goto out; } log_enable_debug(true); info("sipua is ready.\n"); out: return err; } int usleep(unsigned long usec); void sipua_mod_close(void){ list_flush(&sipual); unload_modules(); dnsc_delete(); net_close(); libre_close(); usleep(40000); /* Check for memory leaks */ tmr_debug(); mem_debug(); } /******* signals *******/ void sipua_call(struct sipua_entity *sipua, sipua_bool audio, sipua_bool video, const char *calleeURI) { struct sipua_call_data *call_data = NULL; if (!sipua || !sipua->mq) { warning("sipua entity NULL!\n"); return; } call_data = mem_zalloc(sizeof(struct sipua_call_data), NULL); call_data->audio = NATURAL_BOOL(audio); call_data->video = NATURAL_BOOL(video); memset(call_data->calleeURI, 0, sizeof(call_data->calleeURI)); strncat(call_data->calleeURI, calleeURI, sizeof(call_data->calleeURI) - 1); mqueue_push(sipua->mq, SIPUA_CALL, call_data); return; } void sipua_hangup(struct sipua_entity *sipua, void* call) { if (!sipua || !sipua->mq) { warning("sipua entity NULL!\n"); return; } mqueue_push(sipua->mq, SIPUA_HANGUP, call); return; } void sipua_accept(struct sipua_entity *sipua, const char* peer) { if (!sipua || !sipua->mq) { warning("sipua entity NULL!\n"); return; } mqueue_push(sipua->mq, SIPUA_ANSWER, (void*)peer); return; } void sipua_set_call_owner(struct sipua_entity *sipua, void *call, void *callowner) { struct sipua_call_connect * data = NULL; //FIX ME, lock if (!sipua || !sipua->mq) { warning("sipua entity NULL!\n"); return; } data = mem_zalloc(sizeof(struct sipua_call_connect), NULL); data->call = call; data->owner = callowner; if (callowner) { mqueue_push(sipua->mq, SIPUA_CALL_CONNECT, data); } else { mqueue_push(sipua->mq, SIPUA_CALL_DISCONNECT, data); } return; } /******* media data *******/ /* static void tx_buf(struct sipua_entity *sipua, uint8_t *data, size_t len, enum sipua_cmd_code cmd_code) { struct sipua_tx_rtpbuf *txbuf = NULL; if (!(cmd_code == SIPUA_TX_AUD || cmd_code == SIPUA_TX_VID)) { warning("incorrect command code!\n"); return; } if (!sipua || !sipua->mq) { warning("sipua entity NULL!\n"); return; } txbuf = mem_zalloc(sizeof(struct sipua_tx_rtpbuf), NULL); txbuf->data = data; txbuf->len = len; mqueue_push(sipua->mq, cmd_code, txbuf); return; } */
9da57366b81533ac6c2291cfe55fabfc04abe6cb
f3eed0234b4d0ad2bbb2abd700cf1e2c7a0e8a1d
/AKWF-c/AKWF_0002/AKWF_0198.h
1f1466cc2afb89e250fd7f22e79ead3f94d55050
[ "CC0-1.0" ]
permissive
KristofferKarlAxelEkstrand/AKWF-FREE
b2defa1a2d389d309be6dd2e9f968923daf80d1b
cf8171df36e9fec25416b5f568b72a6e2cb69194
refs/heads/master
2023-07-23T18:22:36.939705
2023-07-10T17:14:40
2023-07-10T17:14:40
145,817,187
359
59
CC0-1.0
2023-07-10T17:14:41
2018-08-23T07:26:56
null
UTF-8
C
false
false
4,672
h
AKWF_0198.h
/* Adventure Kid Waveforms (AKWF) converted for use with Teensy Audio Library * * Adventure Kid Waveforms(AKWF) Open waveforms library * https://www.adventurekid.se/akrt/waveforms/adventure-kid-waveforms/ * * This code is in the public domain, CC0 1.0 Universal (CC0 1.0) * https://creativecommons.org/publicdomain/zero/1.0/ * * Converted by Brad Roy, https://github.com/prosper00 */ /* AKWF_0198 256 samples +-----------------------------------------------------------------------------------------------------------------+ | ***** ****** | | ***** ***** | | ***** ***** | | ***** **** | | **** **** | | **** *** | | *** *** | |** ** | | *** **| | *** *** | | **** *** | | *** **** | | *** *** | | *** *** | | **** ***** | +-----------------------------------------------------------------------------------------------------------------+ */ const uint16_t AKWF_0198 [] = { 32898, 33662, 34492, 35252, 35952, 36620, 37275, 37903, 38524, 39121, 39714, 40282, 40851, 41398, 41942, 42469, 42994, 43504, 44011, 44505, 44999, 45482, 45961, 46435, 46905, 47372, 47834, 48294, 48750, 49207, 49663, 50115, 50570, 51023, 51478, 51933, 52390, 52848, 53308, 53770, 54235, 54702, 55172, 55645, 56119, 56597, 57079, 57562, 58048, 58539, 59027, 59527, 60014, 60528, 60973, 61428, 61863, 62258, 62660, 63020, 63373, 63707, 63985, 64185, 64378, 64552, 64716, 64865, 65000, 65121, 65228, 65318, 65393, 65453, 65497, 65524, 65534, 65531, 65510, 65476, 65424, 65359, 65279, 65186, 65078, 64958, 64826, 64682, 64526, 64361, 64182, 63999, 63760, 63464, 63161, 62841, 62511, 62169, 61818, 61457, 61086, 60707, 60317, 59920, 59515, 59099, 58676, 58247, 57808, 57361, 56908, 56447, 55979, 55501, 55016, 54525, 54024, 53516, 52999, 52474, 51940, 51396, 50844, 50284, 49714, 49134, 48544, 47944, 47334, 46713, 46081, 45440, 44785, 44121, 43445, 42753, 42054, 41339, 40612, 39870, 39115, 38341, 37555, 36746, 35918, 35052, 34093, 33104, 32120, 31118, 30164, 29285, 28420, 27571, 26730, 25896, 25073, 24255, 23445, 22643, 21848, 21058, 20279, 19506, 18743, 17987, 17242, 16505, 15780, 15063, 14359, 13666, 12983, 12312, 11655, 11009, 10378, 9759, 9155, 8561, 7987, 7417, 6890, 6384, 5893, 5445, 5010, 4609, 4232, 3882, 3557, 3263, 2996, 2757, 2548, 2367, 2213, 2090, 1995, 1932, 1898, 1893, 1920, 1977, 2065, 2183, 2332, 2511, 2717, 2953, 3218, 3510, 3831, 4177, 4550, 4948, 5371, 5818, 6287, 6777, 7291, 7822, 8375, 8944, 9533, 10137, 10758, 11392, 12040, 12701, 13373, 14057, 14751, 15452, 16162, 16880, 17604, 18334, 19066, 19806, 20547, 21293, 22037, 22789, 23534, 24287, 25033, 25788, 26533, 27294, 28038, 28803, 29554, 30336, 31148, 32030, };
bd61130769aeb3ad323a40c9f38cf25ea1c30363
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/imx/imx6ull-smart/drivers/drv_usbd.c
9e7c8ad108221399070232c2155defc2a05b9c45
[ "Apache-2.0", "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC", "LicenseRef-scancode-unknown-license-reference" ]
permissive
RT-Thread/rt-thread
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
3602f891211904a27dcbd51e5ba72fefce7326b2
refs/heads/master
2023-09-01T04:10:20.295801
2023-08-31T16:20:55
2023-08-31T16:20:55
7,408,108
9,599
5,805
Apache-2.0
2023-09-14T13:37:26
2013-01-02T14:49:21
C
UTF-8
C
false
false
10,971
c
drv_usbd.c
/* * Copyright (c) 2006-2023, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2017-12-04 ZYH first implementation */ #include <usb/include/usb_device_config.h> #include <usb/include/usb.h> #include <rtthread.h> #include <usb/phy/usb_phy.h> #include <usb/device/usb_device.h> #include <usb/device/usb_device_dci.h> #include <rtdevice.h> #include <imx6ull.h> #define USB0_IRQNUM 75 /* USB PHY condfiguration */ #define BOARD_USB_PHY_D_CAL (0x0CU) #define BOARD_USB_PHY_TXCAL45DP (0x06U) #define BOARD_USB_PHY_TXCAL45DM (0x06U) #ifdef BSP_USING_USB_DEVICE static usb_device_handle ehci0_handle; static struct udcd _fsl_udc_0; static usb_status_t usb_device_callback(usb_device_handle handle, uint32_t callbackEvent, void *eventParam); static usb_status_t usb_device_endpoint_callback(usb_device_handle handle, usb_device_endpoint_callback_message_struct_t *message, void *callbackParam); static void USB_DeviceIsrEnable(uint8_t controllerId) { uint8_t irqNumber; #if defined(USB_DEVICE_CONFIG_EHCI) && (USB_DEVICE_CONFIG_EHCI > 0U) uint8_t usbDeviceEhciIrq[] = USBHS_IRQS; irqNumber = usbDeviceEhciIrq[controllerId - kUSB_ControllerEhci0]; #endif /* Install isr, set priority, and enable IRQ. */ #if defined(__GIC_PRIO_BITS) GIC_SetPriority((IRQn_Type)irqNumber, 3); #else NVIC_SetPriority((IRQn_Type)irqNumber, 3); #endif EnableIRQ((IRQn_Type)irqNumber); } /*! * @brief Initializes USB specific setting that was not set by the Clocks tool. */ static void USB_DeviceClockInit(uint8_t controllerId) { #if defined(USB_DEVICE_CONFIG_EHCI) && (USB_DEVICE_CONFIG_EHCI > 0U) usb_phy_config_struct_t phyConfig = { BOARD_USB_PHY_D_CAL, BOARD_USB_PHY_TXCAL45DP, BOARD_USB_PHY_TXCAL45DM, }; #endif #if defined(USB_DEVICE_CONFIG_EHCI) && (USB_DEVICE_CONFIG_EHCI > 0U) if (controllerId == kUSB_ControllerEhci0) { CLOCK_EnableUsbhs0PhyPllClock(kCLOCK_Usbphy480M, 480000000U); CLOCK_EnableUsbhs0Clock(kCLOCK_Usb480M, 480000000U); } else { CLOCK_EnableUsbhs1PhyPllClock(kCLOCK_Usbphy480M, 480000000U); CLOCK_EnableUsbhs1Clock(kCLOCK_Usb480M, 480000000U); } USB_EhciPhyInit(controllerId, 0, &phyConfig); #endif } static struct ep_id _ehci0_ep_pool[] = { {0x0, USB_EP_ATTR_CONTROL, USB_DIR_INOUT, 64, ID_ASSIGNED }, {0x1, USB_EP_ATTR_BULK, USB_DIR_IN, 64, ID_UNASSIGNED}, {0x1, USB_EP_ATTR_BULK, USB_DIR_OUT, 64, ID_UNASSIGNED}, {0x2, USB_EP_ATTR_INT, USB_DIR_IN, 64, ID_UNASSIGNED}, {0x2, USB_EP_ATTR_INT, USB_DIR_OUT, 64, ID_UNASSIGNED}, {0x3, USB_EP_ATTR_BULK, USB_DIR_IN, 64, ID_UNASSIGNED}, {0x3, USB_EP_ATTR_BULK, USB_DIR_OUT, 64, ID_UNASSIGNED}, {0x4, USB_EP_ATTR_INT, USB_DIR_IN, 64, ID_UNASSIGNED}, {0x4, USB_EP_ATTR_INT, USB_DIR_OUT, 64, ID_UNASSIGNED}, {0x5, USB_EP_ATTR_BULK, USB_DIR_IN, 64, ID_UNASSIGNED}, {0x5, USB_EP_ATTR_BULK, USB_DIR_OUT, 64, ID_UNASSIGNED}, {0x6, USB_EP_ATTR_INT, USB_DIR_IN, 64, ID_UNASSIGNED}, {0x6, USB_EP_ATTR_INT, USB_DIR_OUT, 64, ID_UNASSIGNED}, {0x7, USB_EP_ATTR_BULK, USB_DIR_IN, 64, ID_UNASSIGNED}, {0x7, USB_EP_ATTR_BULK, USB_DIR_OUT, 64, ID_UNASSIGNED}, {0xFF, USB_EP_ATTR_TYPE_MASK, USB_DIR_MASK, 0, ID_ASSIGNED }, }; /*! * @brief USB Interrupt service routine. * * This function serves as the USB interrupt service routine. * * @return None. */ static struct rt_workqueue *usb0_wq = NULL; static struct rt_work usb0_work; void ehci0_work(struct rt_work *work, void *work_data) { USB_DeviceEhciIsrFunction(ehci0_handle); rt_hw_interrupt_umask(USB0_IRQNUM); } void USB_OTG1_IRQHandler(int irq, void *base) { // USB_DeviceEhciIsrFunction(ehci0_handle); rt_hw_interrupt_mask(USB0_IRQNUM); rt_workqueue_dowork(usb0_wq, &usb0_work); } static rt_err_t _ehci0_ep_set_stall(rt_uint8_t address) { USB_DeviceStallEndpoint(ehci0_handle, address); return RT_EOK; } static rt_err_t _ehci0_ep_clear_stall(rt_uint8_t address) { USB_DeviceUnstallEndpoint(ehci0_handle, address); return RT_EOK; } static rt_err_t _ehci0_set_address(rt_uint8_t address) { USB_DeviceSetStatus(ehci0_handle, kUSB_DeviceStatusAddress, &address); return RT_EOK; } static rt_err_t _ehci0_set_config(rt_uint8_t address) { return RT_EOK; } static rt_err_t _ehci0_ep_enable(uep_t ep) { usb_device_endpoint_init_struct_t ep_init; usb_device_endpoint_callback_struct_t ep_callback; rt_uint32_t param = ep->ep_desc->bEndpointAddress; RT_ASSERT(ep != RT_NULL); RT_ASSERT(ep->ep_desc != RT_NULL); ep_init.maxPacketSize = ep->ep_desc->wMaxPacketSize; ep_init.endpointAddress = ep->ep_desc->bEndpointAddress; ep_init.transferType = ep->ep_desc->bmAttributes; ep_init.zlt = 0; ep_callback.callbackFn = usb_device_endpoint_callback; ep_callback.callbackParam = (void *)param; ep_callback.isBusy = 0; USB_DeviceInitEndpoint(ehci0_handle, &ep_init, &ep_callback); return RT_EOK; } static rt_err_t _ehci0_ep_disable(uep_t ep) { RT_ASSERT(ep != RT_NULL); RT_ASSERT(ep->ep_desc != RT_NULL); USB_DeviceDeinitEndpoint(ehci0_handle, ep->ep_desc->bEndpointAddress); return RT_EOK; } static rt_size_t _ehci0_ep_read(rt_uint8_t address, void *buffer) { rt_size_t size = 0; RT_ASSERT(buffer != RT_NULL); return size; } static rt_size_t _ehci0_ep_read_prepare(rt_uint8_t address, void *buffer, rt_size_t size) { USB_DeviceRecvRequest(ehci0_handle, address, buffer, size); return size; } static rt_size_t _ehci0_ep_write(rt_uint8_t address, void *buffer, rt_size_t size) { USB_DeviceSendRequest(ehci0_handle, address, buffer, size); return size; } static rt_err_t _ehci0_ep0_send_status(void) { _ehci0_ep_write(0x00, NULL, 0); return RT_EOK; } static rt_err_t _ehci0_suspend(void) { return RT_EOK; } static rt_err_t _ehci0_wakeup(void) { return RT_EOK; } const static struct udcd_ops _ehci0_udc_ops = { _ehci0_set_address, _ehci0_set_config, _ehci0_ep_set_stall, _ehci0_ep_clear_stall, _ehci0_ep_enable, _ehci0_ep_disable, _ehci0_ep_read_prepare, _ehci0_ep_read, _ehci0_ep_write, _ehci0_ep0_send_status, _ehci0_suspend, _ehci0_wakeup, }; extern void rt_hw_interrupt_umask(int vector); static rt_err_t drv_ehci0_usbd_init(rt_device_t device) { usb_status_t result; USB_DeviceClockInit(kUSB_ControllerEhci0); result = USB_DeviceInit(kUSB_ControllerEhci0, usb_device_callback, &ehci0_handle); RT_ASSERT(ehci0_handle); if(result == kStatus_USB_Success) { usb0_wq = rt_workqueue_create("u0wq", 4096, 3); rt_work_init(&usb0_work, ehci0_work, NULL); rt_hw_interrupt_install(USB0_IRQNUM, USB_OTG1_IRQHandler, (void *)ehci0_handle, "usb1_intr"); rt_hw_interrupt_umask(USB0_IRQNUM); USB_DeviceRun(ehci0_handle); } else { rt_kprintf("USB_DeviceInit ehci0 error\r\n"); return RT_ERROR; } return RT_EOK; } struct rt_device_ops imx6ull_usb_ops = { drv_ehci0_usbd_init, RT_NULL, RT_NULL, RT_NULL, RT_NULL, RT_NULL, }; static int rt_usbd_init(void) { rt_memset((void *)&_fsl_udc_0, 0, sizeof(struct udcd)); _fsl_udc_0.parent.type = RT_Device_Class_USBDevice; _fsl_udc_0.parent.ops = &imx6ull_usb_ops; _fsl_udc_0.ops = &_ehci0_udc_ops; /* Register endpoint infomation */ _fsl_udc_0.ep_pool = _ehci0_ep_pool; _fsl_udc_0.ep0.id = &_ehci0_ep_pool[0]; _fsl_udc_0.device_is_hs = RT_FALSE; rt_device_register((rt_device_t)&_fsl_udc_0, "usbd", 0); rt_usb_device_init(); return 0; } // INIT_DEVICE_EXPORT(rt_usbd_init); static usb_status_t usb_device_endpoint_callback(usb_device_handle handle, usb_device_endpoint_callback_message_struct_t *message, void *callbackParam) { rt_uint32_t ep_addr = (rt_uint32_t)callbackParam; usb_device_struct_t *deviceHandle = (usb_device_struct_t *)handle; udcd_t udcd = RT_NULL; uint8_t state; if(deviceHandle->controllerId == kUSB_ControllerEhci0) udcd = &_fsl_udc_0; if(message->isSetup) { rt_usbd_ep0_setup_handler(udcd, (struct urequest*)message->buffer); } else if(ep_addr == 0x00) { USB_DeviceGetStatus(handle, kUSB_DeviceStatusDeviceState, &state); if(state == kUSB_DeviceStateAddressing) { if (kStatus_USB_Success == USB_DeviceSetStatus(handle, kUSB_DeviceStatusAddress, NULL)) { state = kUSB_DeviceStateAddress; USB_DeviceSetStatus(handle, kUSB_DeviceStatusDeviceState, &state); } } rt_usbd_ep0_out_handler(udcd, message->length); } else if(ep_addr == 0x80) { USB_DeviceGetStatus(handle, kUSB_DeviceStatusDeviceState, &state); if(state == kUSB_DeviceStateAddressing) { if (kStatus_USB_Success == USB_DeviceSetStatus(handle, kUSB_DeviceStatusAddress, NULL)) { state = kUSB_DeviceStateAddress; USB_DeviceSetStatus(handle, kUSB_DeviceStatusDeviceState, &state); } } rt_usbd_ep0_in_handler(udcd); } else if(ep_addr & 0x80) { rt_usbd_ep_in_handler(udcd, ep_addr, message->length); } else { rt_usbd_ep_out_handler(udcd, ep_addr, message->length); } return kStatus_USB_Success; } static usb_status_t usb_device_callback(usb_device_handle handle, uint32_t callbackEvent, void *eventParam) { usb_status_t error = kStatus_USB_Error; usb_device_struct_t *deviceHandle = (usb_device_struct_t *)handle; usb_device_endpoint_init_struct_t ep0_init = { 0x40, 0x00, USB_EP_ATTR_CONTROL, 0 }; usb_device_endpoint_callback_struct_t ep0_callback = { usb_device_endpoint_callback, 0, 0 }; udcd_t udcd = RT_NULL; if(deviceHandle->controllerId == kUSB_ControllerEhci0) udcd = &_fsl_udc_0; switch (callbackEvent) { case kUSB_DeviceEventBusReset: ep0_init.endpointAddress = 0x00; ep0_callback.callbackParam = (void *)0x00; USB_DeviceInitEndpoint(deviceHandle, &ep0_init, &ep0_callback); ep0_init.endpointAddress = 0x80; ep0_callback.callbackParam = (void *)0x80; USB_DeviceInitEndpoint(deviceHandle, &ep0_init, &ep0_callback); rt_usbd_reset_handler(udcd); break; case kUSB_DeviceEventAttach: rt_usbd_connect_handler(udcd); break; case kUSB_DeviceEventDetach: rt_usbd_disconnect_handler(udcd); break; } return error; } #endif /********************* end of file ************************/
50b17805fecaba3f440d3184527c77dab725d187
f367e4b66a1ee42e85830b31df88f63723c36a47
/tests/runtime/filter_wasm.c
4cc1afcb807f86a0b0252360ae26b30904925f78
[ "Apache-2.0" ]
permissive
fluent/fluent-bit
06873e441162b92941024e9a7e9e8fc934150bf7
1a41f49dc2f3ae31a780caa9ffd6137b1d703065
refs/heads/master
2023-09-05T13:44:55.347372
2023-09-05T10:14:33
2023-09-05T10:14:33
29,933,948
4,907
1,565
Apache-2.0
2023-09-14T10:17:02
2015-01-27T20:41:52
C
UTF-8
C
false
false
12,659
c
filter_wasm.c
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Fluent Bit * ========== * Copyright (C) 2022 The Fluent Bit Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <fluent-bit.h> #include <fluent-bit/flb_time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "flb_tests_runtime.h" #define DPATH_WASM FLB_TESTS_DATA_PATH "/data/wasm" #define FLUSH_INTERVAL "1.0" #ifdef _WIN32 #define TIME_EPSILON_MS 30 #else #define TIME_EPSILON_MS 10 #endif pthread_mutex_t result_mutex = PTHREAD_MUTEX_INITIALIZER; char *output = NULL; int num_output = 0; void set_output(char *val) { pthread_mutex_lock(&result_mutex); output = val; pthread_mutex_unlock(&result_mutex); } char *get_output(void) { char *val; pthread_mutex_lock(&result_mutex); val = output; pthread_mutex_unlock(&result_mutex); return val; } static void clear_output() { pthread_mutex_lock(&result_mutex); output = NULL; pthread_mutex_unlock(&result_mutex); } static void clear_output_num() { pthread_mutex_lock(&result_mutex); num_output = 0; pthread_mutex_unlock(&result_mutex); } static int get_output_num() { int ret; pthread_mutex_lock(&result_mutex); ret = num_output; pthread_mutex_unlock(&result_mutex); return ret; } static int cb_count_msgpack_events(void *record, size_t size, void *data) { msgpack_unpacked result; size_t off = 0; if (!TEST_CHECK(data != NULL)) { flb_error("data is NULL"); } /* Iterate each item array and apply rules */ msgpack_unpacked_init(&result); while (msgpack_unpack_next(&result, record, size, &off) == MSGPACK_UNPACK_SUCCESS) { pthread_mutex_lock(&result_mutex); num_output++; pthread_mutex_unlock(&result_mutex); } msgpack_unpacked_destroy(&result); flb_free(record); return 0; } int callback_test(void* data, size_t size, void* cb_data) { if (size > 0) { flb_debug("[test_filter_wasm] received message: %s", (char*)data); set_output(data); /* success */ } return 0; } void wait_with_timeout(uint32_t timeout_ms, char **out_result) { struct flb_time start_time; struct flb_time end_time; struct flb_time diff_time; uint64_t elapsed_time_flb = 0; char *output = NULL; flb_time_get(&start_time); while (true) { output = get_output(); if (output != NULL) { *out_result = output; break; } flb_time_msleep(100); flb_time_get(&end_time); flb_time_diff(&end_time, &start_time, &diff_time); elapsed_time_flb = flb_time_to_nanosec(&diff_time) / 1000000; if (elapsed_time_flb > timeout_ms - TIME_EPSILON_MS) { flb_warn("[timeout] elapsed_time: %ld", elapsed_time_flb); // Reached timeout. break; } } } void flb_test_append_tag(void) { int ret; flb_ctx_t *ctx; int in_ffd; int out_ffd; int filter_ffd; char *output = NULL; char *input = "[0, {\"key\":\"val\"}]"; char *result; struct flb_lib_out_cb cb_data; /* clear previous output */ clear_output(); /* Create context, flush every second (some checks omitted here) */ ctx = flb_create(); flb_service_set(ctx, "flush", FLUSH_INTERVAL, "grace", "1", NULL); /* Prepare output callback context*/ cb_data.cb = callback_test; cb_data.data = NULL; /* Filter */ filter_ffd = flb_filter(ctx, (char *) "wasm", NULL); TEST_CHECK(filter_ffd >= 0); ret = flb_filter_set(ctx, filter_ffd, "Match", "*", "wasm_path", DPATH_WASM "/append_tag.wasm", "function_name", "filter_append_tag", NULL); /* Input */ in_ffd = flb_input(ctx, (char *) "lib", NULL); flb_input_set(ctx, in_ffd, "tag", "test.wasm", NULL); TEST_CHECK(in_ffd >= 0); /* Lib output */ out_ffd = flb_output(ctx, (char *) "lib", (void *)&cb_data); TEST_CHECK(out_ffd >= 0); flb_output_set(ctx, out_ffd, "match", "test.wasm", "format", "json", NULL); ret = flb_start(ctx); TEST_CHECK(ret==0); flb_lib_push(ctx, in_ffd, input, strlen(input)); wait_with_timeout(2000, &output); result = strstr(output, "\"tag\":\"test.wasm\""); TEST_CHECK(result != NULL); /* clean up */ flb_lib_free(output); flb_stop(ctx); flb_destroy(ctx); } void flb_test_helloworld(void) { int ret; flb_ctx_t *ctx; int in_ffd; int out_ffd; int filter_ffd; /* Create context, flush every second (some checks omitted here) */ ctx = flb_create(); flb_service_set(ctx, "flush", FLUSH_INTERVAL, "grace", "1", NULL); /* Filter */ filter_ffd = flb_filter(ctx, (char *) "wasm", NULL); TEST_CHECK(filter_ffd >= 0); ret = flb_filter_set(ctx, filter_ffd, "Match", "*", "wasm_path", DPATH_WASM "/say_hello.wasm", "function_name", "filter_say_hello", NULL); /* Input */ in_ffd = flb_input(ctx, (char *) "dummy", NULL); flb_input_set(ctx, in_ffd, "tag", "test", NULL); TEST_CHECK(in_ffd >= 0); /* Lib output */ out_ffd = flb_output(ctx, (char *) "stdout", NULL); TEST_CHECK(out_ffd >= 0); flb_output_set(ctx, out_ffd, "match", "test", NULL); ret = flb_start(ctx); TEST_CHECK(ret==0); flb_stop(ctx); flb_destroy(ctx); } void flb_test_numerics_records(void) { int ret; flb_ctx_t *ctx; int in_ffd; int out_ffd; int filter_ffd; char *output = NULL; char *input = "[0, {\"key\":\"val\"}]"; char *result; struct flb_lib_out_cb cb_data; /* clear previous output */ clear_output(); /* Create context, flush every second (some checks omitted here) */ ctx = flb_create(); flb_service_set(ctx, "flush", FLUSH_INTERVAL, "grace", "1", NULL); /* Prepare output callback context*/ cb_data.cb = callback_test; cb_data.data = NULL; /* Filter */ filter_ffd = flb_filter(ctx, (char *) "wasm", NULL); TEST_CHECK(filter_ffd >= 0); ret = flb_filter_set(ctx, filter_ffd, "Match", "*", "wasm_path", DPATH_WASM "/numeric_records.wasm", "function_name", "filter_numeric_records", NULL); /* Input */ in_ffd = flb_input(ctx, (char *) "lib", NULL); flb_input_set(ctx, in_ffd, "tag", "test.wasm", NULL); TEST_CHECK(in_ffd >= 0); /* Lib output */ out_ffd = flb_output(ctx, (char *) "lib", (void *)&cb_data); TEST_CHECK(out_ffd >= 0); flb_output_set(ctx, out_ffd, "match", "test.wasm", "format", "json", NULL); ret = flb_start(ctx); TEST_CHECK(ret==0); flb_lib_push(ctx, in_ffd, input, strlen(input)); wait_with_timeout(2000, &output); /* check if float (for int keys)*/ result = strstr(output, "\"wasm_int1\":10."); if (!TEST_CHECK(result == NULL)) { TEST_MSG("output:%s\n", output); } result = strstr(output, "\"wasm_int2\":100."); if (!TEST_CHECK(result == NULL)) { TEST_MSG("output:%s\n", output); } /* check if float (for float keys)*/ result = strstr(output, "\"wasm_float1\":10.5"); if (!TEST_CHECK(result != NULL)) { TEST_MSG("output:%s\n", output); } result = strstr(output, "\"wasm_float2\":100.5"); if (!TEST_CHECK(result != NULL)) { TEST_MSG("output:%s\n", output); } /* check if float (for exp style float key)*/ result = strstr(output, "\"wasm_exp_float\":0.00354"); if (!TEST_CHECK(result != NULL)) { TEST_MSG("output:%s\n", output); } /* check if float (for truncated float key)*/ result = strstr(output, "\"wasm_truncate_float\":120"); if (!TEST_CHECK(result != NULL)) { TEST_MSG("output:%s\n", output); } result = strstr(output, "\"wasm_truncate_float\":120."); if (!TEST_CHECK(result == NULL)) { TEST_MSG("output:%s\n", output); } /* clean up */ flb_lib_free(output); flb_stop(ctx); flb_destroy(ctx); } void flb_test_array_contains_null(void) { int ret; flb_ctx_t *ctx; int in_ffd; int out_ffd; int filter_ffd; char *output = NULL; char *input = "[0, {\"hello\": [1, null, \"world\"]}]"; char *result; struct flb_lib_out_cb cb_data; /* clear previous output */ clear_output(); /* Create context, flush every second (some checks omitted here) */ ctx = flb_create(); flb_service_set(ctx, "flush", FLUSH_INTERVAL, "grace", "1", NULL); /* Prepare output callback context*/ cb_data.cb = callback_test; cb_data.data = NULL; /* Filter */ filter_ffd = flb_filter(ctx, (char *) "wasm", NULL); TEST_CHECK(filter_ffd >= 0); ret = flb_filter_set(ctx, filter_ffd, "Match", "*", "wasm_path", DPATH_WASM "/modify_record.wasm", "function_name", "filter_modify_record", NULL); /* Input */ in_ffd = flb_input(ctx, (char *) "lib", NULL); flb_input_set(ctx, in_ffd, "tag", "test.wasm", NULL); TEST_CHECK(in_ffd >= 0); /* Lib output */ out_ffd = flb_output(ctx, (char *) "lib", (void *)&cb_data); TEST_CHECK(out_ffd >= 0); flb_output_set(ctx, out_ffd, "match", "test.wasm", "format", "json", NULL); ret = flb_start(ctx); TEST_CHECK(ret==0); flb_lib_push(ctx, in_ffd, input, strlen(input)); wait_with_timeout(2000, &output); result = strstr(output, "[1,null,\"world\"]"); if(!TEST_CHECK(result != NULL)) { TEST_MSG("output:%s\n", output); } result = strstr(output, "\"modify\":\"yes\""); if(!TEST_CHECK(result != NULL)) { TEST_MSG("output:%s\n", output); } /* clean up */ flb_lib_free(output); flb_stop(ctx); flb_destroy(ctx); } void flb_test_drop_all_records(void) { int ret; flb_ctx_t *ctx; int in_ffd; int out_ffd; int filter_ffd; char *output = NULL; char *input = "[0, {\"key\":\"val\"}]"; struct flb_lib_out_cb cb_data; clear_output_num(); /* Create context, flush every second (some checks omitted here) */ ctx = flb_create(); flb_service_set(ctx, "flush", FLUSH_INTERVAL, "grace", "1", NULL); /* Prepare output callback context*/ cb_data.cb = cb_count_msgpack_events; cb_data.data = NULL; /* Filter */ filter_ffd = flb_filter(ctx, (char *) "wasm", NULL); TEST_CHECK(filter_ffd >= 0); ret = flb_filter_set(ctx, filter_ffd, "Match", "*", "wasm_path", DPATH_WASM "/drop_record.wasm", "function_name", "filter_drop_record", NULL); /* Input */ in_ffd = flb_input(ctx, (char *) "lib", NULL); flb_input_set(ctx, in_ffd, "tag", "test", NULL); TEST_CHECK(in_ffd >= 0); /* Lib output */ out_ffd = flb_output(ctx, (char *) "lib", (void *)&cb_data); TEST_CHECK(out_ffd >= 0); flb_output_set(ctx, out_ffd, "match", "test", NULL); ret = flb_start(ctx); TEST_CHECK(ret==0); flb_lib_push(ctx, in_ffd, input, strlen(input)); wait_with_timeout(2000, &output); /* waiting flush */ ret = get_output_num(); if (!TEST_CHECK(ret == 0)) { TEST_MSG("error. got %d expect 0", ret); } flb_stop(ctx); flb_destroy(ctx); } TEST_LIST = { {"hello_world", flb_test_helloworld}, {"append_tag", flb_test_append_tag}, {"numeric_records", flb_test_numerics_records}, {"array_contains_null", flb_test_array_contains_null}, {"drop_all_records", flb_test_drop_all_records}, {NULL, NULL} };
23198be88bcb7a04ced032ce21a5aea7c63be8e4
bcddd00650cfaeafda4c82cef47d996419d38032
/bindings/java/wasmedge-java/wasmedge-jni/lib/VmContext.c
525752cacf11b5899c4c6d61cbf6334b0a96adb8
[ "Apache-2.0", "CC0-1.0" ]
permissive
WasmEdge/WasmEdge
d980037be14dcbddd39fdeb32801fa9539fdb440
b70f48c42922ce5ee7730054b6ac0b1615176285
refs/heads/master
2023-08-31T04:07:11.517799
2023-08-28T04:07:12
2023-08-28T04:07:12
224,908,244
5,731
703
Apache-2.0
2023-09-14T17:55:44
2019-11-29T19:00:17
C++
UTF-8
C
false
false
721
c
VmContext.c
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2019-2022 Second State INC #include "../jni/org_wasmedge_VMContext.h" #include "ConfigureContext.h" #include "StoreContext.h" #include "common.h" #include "wasmedge/wasmedge.h" JNIEXPORT void JNICALL Java_org_wasmedge_VMContext_initNative( JNIEnv *env, jobject jVmContext, jobject jConfigureContext, jobject jStoreContext) { WasmEdge_ConfigureContext *ConfigureContext = getConfigureContext(env, jConfigureContext); WasmEdge_StoreContext *StoreContext = getStoreContext(env, jStoreContext); WasmEdge_VMContext *VMContext = WasmEdge_VMCreate(ConfigureContext, StoreContext); setPointer(env, jVmContext, (jlong)VMContext); }
7b33fe1bd9d2fa8dd772d46a09f455372d2fae48
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/ffmpeg/fftools/sync_queue.c
c2b23ee4f5ab079ee41225e98939e9f95ed1a222
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "LGPL-2.1-only", "LGPL-3.0-only", "GPL-2.0-only", "LGPL-2.1-or-later", "GPL-3.0-or-later", "LGPL-3.0-or-later", "IJG", "LicenseRef-scancode-other-permissive", "GPL-2.0-or-later", "GPL-3.0-only" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C
false
false
13,420
c
sync_queue.c
/* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdint.h> #include <string.h> #include "libavutil/avassert.h" #include "libavutil/error.h" #include "libavutil/fifo.h" #include "libavutil/mathematics.h" #include "libavutil/mem.h" #include "objpool.h" #include "sync_queue.h" typedef struct SyncQueueStream { AVFifo *fifo; AVRational tb; /* stream head: largest timestamp seen */ int64_t head_ts; int limiting; /* no more frames will be sent for this stream */ int finished; uint64_t frames_sent; uint64_t frames_max; } SyncQueueStream; struct SyncQueue { enum SyncQueueType type; /* no more frames will be sent for any stream */ int finished; /* sync head: the stream with the _smallest_ head timestamp * this stream determines which frames can be output */ int head_stream; /* the finished stream with the smallest finish timestamp or -1 */ int head_finished_stream; // maximum buffering duration in microseconds int64_t buf_size_us; SyncQueueStream *streams; unsigned int nb_streams; // pool of preallocated frames to avoid constant allocations ObjPool *pool; }; static void frame_move(const SyncQueue *sq, SyncQueueFrame dst, SyncQueueFrame src) { if (sq->type == SYNC_QUEUE_PACKETS) av_packet_move_ref(dst.p, src.p); else av_frame_move_ref(dst.f, src.f); } static int64_t frame_ts(const SyncQueue *sq, SyncQueueFrame frame) { return (sq->type == SYNC_QUEUE_PACKETS) ? frame.p->pts + frame.p->duration : frame.f->pts + frame.f->duration; } static int frame_null(const SyncQueue *sq, SyncQueueFrame frame) { return (sq->type == SYNC_QUEUE_PACKETS) ? (frame.p == NULL) : (frame.f == NULL); } static void finish_stream(SyncQueue *sq, unsigned int stream_idx) { SyncQueueStream *st = &sq->streams[stream_idx]; st->finished = 1; if (st->limiting && st->head_ts != AV_NOPTS_VALUE) { /* check if this stream is the new finished head */ if (sq->head_finished_stream < 0 || av_compare_ts(st->head_ts, st->tb, sq->streams[sq->head_finished_stream].head_ts, sq->streams[sq->head_finished_stream].tb) < 0) { sq->head_finished_stream = stream_idx; } /* mark as finished all streams that should no longer receive new frames, * due to them being ahead of some finished stream */ st = &sq->streams[sq->head_finished_stream]; for (unsigned int i = 0; i < sq->nb_streams; i++) { SyncQueueStream *st1 = &sq->streams[i]; if (st != st1 && st1->head_ts != AV_NOPTS_VALUE && av_compare_ts(st->head_ts, st->tb, st1->head_ts, st1->tb) <= 0) st1->finished = 1; } } /* mark the whole queue as finished if all streams are finished */ for (unsigned int i = 0; i < sq->nb_streams; i++) { if (!sq->streams[i].finished) return; } sq->finished = 1; } static void queue_head_update(SyncQueue *sq) { if (sq->head_stream < 0) { /* wait for one timestamp in each stream before determining * the queue head */ for (unsigned int i = 0; i < sq->nb_streams; i++) { SyncQueueStream *st = &sq->streams[i]; if (st->limiting && st->head_ts == AV_NOPTS_VALUE) return; } // placeholder value, correct one will be found below sq->head_stream = 0; } for (unsigned int i = 0; i < sq->nb_streams; i++) { SyncQueueStream *st_head = &sq->streams[sq->head_stream]; SyncQueueStream *st_other = &sq->streams[i]; if (st_other->limiting && st_other->head_ts != AV_NOPTS_VALUE && av_compare_ts(st_other->head_ts, st_other->tb, st_head->head_ts, st_head->tb) < 0) sq->head_stream = i; } } /* update this stream's head timestamp */ static void stream_update_ts(SyncQueue *sq, unsigned int stream_idx, int64_t ts) { SyncQueueStream *st = &sq->streams[stream_idx]; if (ts == AV_NOPTS_VALUE || (st->head_ts != AV_NOPTS_VALUE && st->head_ts >= ts)) return; st->head_ts = ts; /* if this stream is now ahead of some finished stream, then * this stream is also finished */ if (sq->head_finished_stream >= 0 && av_compare_ts(sq->streams[sq->head_finished_stream].head_ts, sq->streams[sq->head_finished_stream].tb, ts, st->tb) <= 0) finish_stream(sq, stream_idx); /* update the overall head timestamp if it could have changed */ if (st->limiting && (sq->head_stream < 0 || sq->head_stream == stream_idx)) queue_head_update(sq); } /* If the queue for the given stream (or all streams when stream_idx=-1) * is overflowing, trigger a fake heartbeat on lagging streams. * * @return 1 if heartbeat triggered, 0 otherwise */ static int overflow_heartbeat(SyncQueue *sq, int stream_idx) { SyncQueueStream *st; SyncQueueFrame frame; int64_t tail_ts = AV_NOPTS_VALUE; /* if no stream specified, pick the one that is most ahead */ if (stream_idx < 0) { int64_t ts = AV_NOPTS_VALUE; for (int i = 0; i < sq->nb_streams; i++) { st = &sq->streams[i]; if (st->head_ts != AV_NOPTS_VALUE && (ts == AV_NOPTS_VALUE || av_compare_ts(ts, sq->streams[stream_idx].tb, st->head_ts, st->tb) < 0)) { ts = st->head_ts; stream_idx = i; } } /* no stream has a timestamp yet -> nothing to do */ if (stream_idx < 0) return 0; } st = &sq->streams[stream_idx]; /* get the chosen stream's tail timestamp */ for (size_t i = 0; tail_ts == AV_NOPTS_VALUE && av_fifo_peek(st->fifo, &frame, 1, i) >= 0; i++) tail_ts = frame_ts(sq, frame); /* overflow triggers when the tail is over specified duration behind the head */ if (tail_ts == AV_NOPTS_VALUE || tail_ts >= st->head_ts || av_rescale_q(st->head_ts - tail_ts, st->tb, AV_TIME_BASE_Q) < sq->buf_size_us) return 0; /* signal a fake timestamp for all streams that prevent tail_ts from being output */ tail_ts++; for (unsigned int i = 0; i < sq->nb_streams; i++) { SyncQueueStream *st1 = &sq->streams[i]; int64_t ts; if (st == st1 || st1->finished || (st1->head_ts != AV_NOPTS_VALUE && av_compare_ts(tail_ts, st->tb, st1->head_ts, st1->tb) <= 0)) continue; ts = av_rescale_q(tail_ts, st->tb, st1->tb); if (st1->head_ts != AV_NOPTS_VALUE) ts = FFMAX(st1->head_ts + 1, ts); stream_update_ts(sq, i, ts); } return 1; } int sq_send(SyncQueue *sq, unsigned int stream_idx, SyncQueueFrame frame) { SyncQueueStream *st; SyncQueueFrame dst; int64_t ts; int ret; av_assert0(stream_idx < sq->nb_streams); st = &sq->streams[stream_idx]; av_assert0(st->tb.num > 0 && st->tb.den > 0); if (frame_null(sq, frame)) { finish_stream(sq, stream_idx); return 0; } if (st->finished) return AVERROR_EOF; ret = objpool_get(sq->pool, (void**)&dst); if (ret < 0) return ret; frame_move(sq, dst, frame); ts = frame_ts(sq, dst); ret = av_fifo_write(st->fifo, &dst, 1); if (ret < 0) { frame_move(sq, frame, dst); objpool_release(sq->pool, (void**)&dst); return ret; } stream_update_ts(sq, stream_idx, ts); st->frames_sent++; if (st->frames_sent >= st->frames_max) finish_stream(sq, stream_idx); return 0; } static int receive_for_stream(SyncQueue *sq, unsigned int stream_idx, SyncQueueFrame frame) { SyncQueueStream *st_head = sq->head_stream >= 0 ? &sq->streams[sq->head_stream] : NULL; SyncQueueStream *st; av_assert0(stream_idx < sq->nb_streams); st = &sq->streams[stream_idx]; if (av_fifo_can_read(st->fifo)) { SyncQueueFrame peek; int64_t ts; int cmp = 1; av_fifo_peek(st->fifo, &peek, 1, 0); ts = frame_ts(sq, peek); /* check if this stream's tail timestamp does not overtake * the overall queue head */ if (ts != AV_NOPTS_VALUE && st_head) cmp = av_compare_ts(ts, st->tb, st_head->head_ts, st_head->tb); /* We can release frames that do not end after the queue head. * Frames with no timestamps are just passed through with no conditions. */ if (cmp <= 0 || ts == AV_NOPTS_VALUE) { frame_move(sq, frame, peek); objpool_release(sq->pool, (void**)&peek); av_fifo_drain2(st->fifo, 1); return 0; } } return (sq->finished || (st->finished && !av_fifo_can_read(st->fifo))) ? AVERROR_EOF : AVERROR(EAGAIN); } static int receive_internal(SyncQueue *sq, int stream_idx, SyncQueueFrame frame) { int nb_eof = 0; int ret; /* read a frame for a specific stream */ if (stream_idx >= 0) { ret = receive_for_stream(sq, stream_idx, frame); return (ret < 0) ? ret : stream_idx; } /* read a frame for any stream with available output */ for (unsigned int i = 0; i < sq->nb_streams; i++) { ret = receive_for_stream(sq, i, frame); if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) { nb_eof += (ret == AVERROR_EOF); continue; } return (ret < 0) ? ret : i; } return (nb_eof == sq->nb_streams) ? AVERROR_EOF : AVERROR(EAGAIN); } int sq_receive(SyncQueue *sq, int stream_idx, SyncQueueFrame frame) { int ret = receive_internal(sq, stream_idx, frame); /* try again if the queue overflowed and triggered a fake heartbeat * for lagging streams */ if (ret == AVERROR(EAGAIN) && overflow_heartbeat(sq, stream_idx)) ret = receive_internal(sq, stream_idx, frame); return ret; } int sq_add_stream(SyncQueue *sq, int limiting) { SyncQueueStream *tmp, *st; tmp = av_realloc_array(sq->streams, sq->nb_streams + 1, sizeof(*sq->streams)); if (!tmp) return AVERROR(ENOMEM); sq->streams = tmp; st = &sq->streams[sq->nb_streams]; memset(st, 0, sizeof(*st)); st->fifo = av_fifo_alloc2(1, sizeof(SyncQueueFrame), AV_FIFO_FLAG_AUTO_GROW); if (!st->fifo) return AVERROR(ENOMEM); /* we set a valid default, so that a pathological stream that never * receives even a real timebase (and no frames) won't stall all other * streams forever; cf. overflow_heartbeat() */ st->tb = (AVRational){ 1, 1 }; st->head_ts = AV_NOPTS_VALUE; st->frames_max = UINT64_MAX; st->limiting = limiting; return sq->nb_streams++; } void sq_set_tb(SyncQueue *sq, unsigned int stream_idx, AVRational tb) { SyncQueueStream *st; av_assert0(stream_idx < sq->nb_streams); st = &sq->streams[stream_idx]; av_assert0(!av_fifo_can_read(st->fifo)); if (st->head_ts != AV_NOPTS_VALUE) st->head_ts = av_rescale_q(st->head_ts, st->tb, tb); st->tb = tb; } void sq_limit_frames(SyncQueue *sq, unsigned int stream_idx, uint64_t frames) { SyncQueueStream *st; av_assert0(stream_idx < sq->nb_streams); st = &sq->streams[stream_idx]; st->frames_max = frames; if (st->frames_sent >= st->frames_max) finish_stream(sq, stream_idx); } SyncQueue *sq_alloc(enum SyncQueueType type, int64_t buf_size_us) { SyncQueue *sq = av_mallocz(sizeof(*sq)); if (!sq) return NULL; sq->type = type; sq->buf_size_us = buf_size_us; sq->head_stream = -1; sq->head_finished_stream = -1; sq->pool = (type == SYNC_QUEUE_PACKETS) ? objpool_alloc_packets() : objpool_alloc_frames(); if (!sq->pool) { av_freep(&sq); return NULL; } return sq; } void sq_free(SyncQueue **psq) { SyncQueue *sq = *psq; if (!sq) return; for (unsigned int i = 0; i < sq->nb_streams; i++) { SyncQueueFrame frame; while (av_fifo_read(sq->streams[i].fifo, &frame, 1) >= 0) objpool_release(sq->pool, (void**)&frame); av_fifo_freep2(&sq->streams[i].fifo); } av_freep(&sq->streams); objpool_free(&sq->pool); av_freep(psq); }
4e9f577d3d4e28ce4a1a27777c70e2e5c510a7d7
3bbf88dc48d70e4c362e15589967c271f5ce844f
/tests/projects/embed/mdk/hello/src/lib/cmsis/ARMCM3.h
44c0c23f493b56f85e0bde7a13700be0f38340e6
[ "Apache-2.0", "LicenseRef-scancode-public-domain", "Unlicense", "MIT" ]
permissive
xmake-io/xmake
ed420a84d9dddd36946893e60799bd912ffd917d
025c5e8415b456bf5f24e37322731615bd5ddea1
refs/heads/master
2023-08-31T13:40:45.719615
2023-08-31T14:33:50
2023-08-31T14:33:50
34,431,834
6,914
618
Apache-2.0
2023-09-14T09:23:40
2015-04-23T03:37:31
Lua
UTF-8
C
false
false
4,723
h
ARMCM3.h
/**************************************************************************//** * @file ARMCM3.h * @brief CMSIS Core Peripheral Access Layer Header File for * ARMCM3 Device * @version V5.3.1 * @date 09. July 2018 ******************************************************************************/ /* * Copyright (c) 2009-2018 Arm Limited. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ARMCM3_H #define ARMCM3_H #ifdef __cplusplus extern "C" { #endif /* ------------------------- Interrupt Number Definition ------------------------ */ typedef enum IRQn { /* ------------------- Processor Exceptions Numbers ----------------------------- */ NonMaskableInt_IRQn = -14, /* 2 Non Maskable Interrupt */ HardFault_IRQn = -13, /* 3 HardFault Interrupt */ MemoryManagement_IRQn = -12, /* 4 Memory Management Interrupt */ BusFault_IRQn = -11, /* 5 Bus Fault Interrupt */ UsageFault_IRQn = -10, /* 6 Usage Fault Interrupt */ SVCall_IRQn = -5, /* 11 SV Call Interrupt */ DebugMonitor_IRQn = -4, /* 12 Debug Monitor Interrupt */ PendSV_IRQn = -2, /* 14 Pend SV Interrupt */ SysTick_IRQn = -1, /* 15 System Tick Interrupt */ /* ------------------- Processor Interrupt Numbers ------------------------------ */ Interrupt0_IRQn = 0, Interrupt1_IRQn = 1, Interrupt2_IRQn = 2, Interrupt3_IRQn = 3, Interrupt4_IRQn = 4, Interrupt5_IRQn = 5, Interrupt6_IRQn = 6, Interrupt7_IRQn = 7, Interrupt8_IRQn = 8, Interrupt9_IRQn = 9 /* Interrupts 10 .. 224 are left out */ } IRQn_Type; /* ================================================================================ */ /* ================ Processor and Core Peripheral Section ================ */ /* ================================================================================ */ /* ------- Start of section using anonymous unions and disabling warnings ------- */ #if defined (__CC_ARM) #pragma push #pragma anon_unions #elif defined (__ICCARM__) #pragma language=extended #elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc11-extensions" #pragma clang diagnostic ignored "-Wreserved-id-macro" #elif defined (__GNUC__) /* anonymous unions are enabled by default */ #elif defined (__TMS470__) /* anonymous unions are enabled by default */ #elif defined (__TASKING__) #pragma warning 586 #elif defined (__CSMC__) /* anonymous unions are enabled by default */ #else #warning Not supported compiler type #endif /* -------- Configuration of Core Peripherals ----------------------------------- */ #define __CM3_REV 0x0201U /* Core revision r2p1 */ #define __MPU_PRESENT 1U /* MPU present */ #define __VTOR_PRESENT 1U /* VTOR present */ #define __NVIC_PRIO_BITS 3U /* Number of Bits used for Priority Levels */ #define __Vendor_SysTickConfig 0U /* Set to 1 if different SysTick Config is used */ #include "core_cm3.h" /* Processor and core peripherals */ #include "system_ARMCM3.h" /* System Header */ /* -------- End of section using anonymous unions and disabling warnings -------- */ #if defined (__CC_ARM) #pragma pop #elif defined (__ICCARM__) /* leave anonymous unions enabled */ #elif (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)) #pragma clang diagnostic pop #elif defined (__GNUC__) /* anonymous unions are enabled by default */ #elif defined (__TMS470__) /* anonymous unions are enabled by default */ #elif defined (__TASKING__) #pragma warning restore #elif defined (__CSMC__) /* anonymous unions are enabled by default */ #else #warning Not supported compiler type #endif #ifdef __cplusplus } #endif #endif /* ARMCM3_H */
44959273c0e421c96feae8bc33119da99c47b2f0
e72db16e9747386afd01edd1dd36d9589a3f71ef
/src/test/pmem2_granularity/pmem2_granularity.c
65e48739914f43555b8ca7a4477bda76bccf8382
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
pmem/pmdk
5e49feee8017574340db2a0f9b4e2eab99f8581c
ccadb16227bddea1bdcc518bd8f298d551b2baad
refs/heads/master
2023-08-31T02:28:06.884934
2023-08-30T14:52:25
2023-08-30T14:52:25
23,637,153
1,017
402
NOASSERTION
2023-09-07T11:52:42
2014-09-03T20:55:23
C
UTF-8
C
false
false
7,477
c
pmem2_granularity.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2019-2023, Intel Corporation */ /* * pmem2_granularity.c -- test for graunlarity functionality */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "config.h" #include "source.h" #include "unittest.h" #include "ut_pmem2_config.h" #include "ut_pmem2_utils.h" #include "out.h" static size_t Pc_capabilities; /* * parse_args -- parse args from the input */ static int parse_args(const struct test_case *tc, int argc, char *argv[], char **file) { if (argc < 1) UT_FATAL("usage: %s <file>", tc->name); *file = argv[0]; return 1; } /* * set_eadr -- set variable required for mocked functions */ static void set_eadr() { int is_eadr = atoi(os_getenv("IS_EADR")); if (is_eadr) Pc_capabilities = 3; else Pc_capabilities = 2; } /* * test_ctx -- essential parameters used by test */ struct test_ctx { int fd; enum pmem2_granularity requested_granularity; enum pmem2_granularity expected_granularity; }; /* * init_test -- initialize basic parameters for test */ static void init_test(char *file, struct test_ctx *ctx, enum pmem2_granularity granularity) { set_eadr(); ctx->fd = OPEN(file, O_RDWR); ctx->requested_granularity = granularity; int is_eadr = atoi(os_getenv("IS_EADR")); int is_pmem = atoi(os_getenv("IS_PMEM")); if (is_eadr) { if (is_pmem) ctx->expected_granularity = PMEM2_GRANULARITY_BYTE; else UT_FATAL("invalid configuration IS_EADR && !IS_PMEM"); } else if (is_pmem) { ctx->expected_granularity = PMEM2_GRANULARITY_CACHE_LINE; } else { ctx->expected_granularity = PMEM2_GRANULARITY_PAGE; } } /* * init_cfg -- initialize basic pmem2 config */ static void init_cfg(struct pmem2_config *cfg, struct pmem2_source **src, struct test_ctx *ctx) { pmem2_config_init(cfg); int ret = pmem2_source_from_fd(src, ctx->fd); UT_PMEM2_EXPECT_RETURN(ret, 0); } /* * cleanup -- cleanup the environment after test */ static void cleanup(struct pmem2_source *src, struct test_ctx *ctx) { CLOSE(ctx->fd); } /* * map_with_available_granularity -- map the range with valid granularity, * includes cleanup */ static void map_with_available_granularity(struct pmem2_config *cfg, struct pmem2_source *src, struct test_ctx *ctx) { cfg->requested_max_granularity = ctx->requested_granularity; struct pmem2_map *map; int ret = pmem2_map_new(&map, cfg, src); UT_PMEM2_EXPECT_RETURN(ret, 0); UT_ASSERTne(map, NULL); UT_ASSERTeq(ctx->expected_granularity, pmem2_map_get_store_granularity(map)); /* cleanup after the test */ pmem2_map_delete(&map); } /* * map_with_unavailable_granularity -- map the range with invalid * granularity (unsuccessful) */ static void map_with_unavailable_granularity(struct pmem2_config *cfg, struct pmem2_source *src, struct test_ctx *ctx) { cfg->requested_max_granularity = ctx->requested_granularity; struct pmem2_map *map; int ret = pmem2_map_new(&map, cfg, src); UT_PMEM2_EXPECT_RETURN(ret, PMEM2_E_GRANULARITY_NOT_SUPPORTED); UT_ERR("%s", pmem2_errormsg()); UT_ASSERTeq(map, NULL); } typedef void(*map_func)(struct pmem2_config *cfg, struct pmem2_source *src, struct test_ctx *ctx); /* * granularity_template -- template for testing granularity in pmem2 */ static int granularity_template(const struct test_case *tc, int argc, char *argv[], map_func map_do, enum pmem2_granularity granularity) { char *file = NULL; int ret = parse_args(tc, argc, argv, &file); struct test_ctx ctx = { 0 }; init_test(file, &ctx, granularity); struct pmem2_config cfg; struct pmem2_source *src; init_cfg(&cfg, &src, &ctx); map_do(&cfg, src, &ctx); cleanup(src, &ctx); pmem2_source_delete(&src); return ret; } /* * test_granularity_req_byte_avail_byte -- require byte granularity, * when byte granularity is available */ static int test_granularity_req_byte_avail_byte(const struct test_case *tc, int argc, char *argv[]) { return granularity_template(tc, argc, argv, map_with_available_granularity, PMEM2_GRANULARITY_BYTE); } /* * test_granularity_req_byte_avail_cl -- require byte granularity, * when cache line granularity is available */ static int test_granularity_req_byte_avail_cl(const struct test_case *tc, int argc, char *argv[]) { return granularity_template(tc, argc, argv, map_with_unavailable_granularity, PMEM2_GRANULARITY_BYTE); } /* * test_granularity_req_byte_avail_page -- require byte granularity, * when page granularity is available */ static int test_granularity_req_byte_avail_page(const struct test_case *tc, int argc, char *argv[]) { return granularity_template(tc, argc, argv, map_with_unavailable_granularity, PMEM2_GRANULARITY_BYTE); } /* * test_granularity_req_cl_avail_byte -- require cache line granularity, * when byte granularity is available */ static int test_granularity_req_cl_avail_byte(const struct test_case *tc, int argc, char *argv[]) { return granularity_template(tc, argc, argv, map_with_available_granularity, PMEM2_GRANULARITY_CACHE_LINE); } /* * test_granularity_req_cl_avail_cl -- require cache line granularity, * when cache line granularity is available */ static int test_granularity_req_cl_avail_cl(const struct test_case *tc, int argc, char *argv[]) { return granularity_template(tc, argc, argv, map_with_available_granularity, PMEM2_GRANULARITY_CACHE_LINE); } /* * test_granularity_req_cl_avail_page -- require cache line granularity, * when page granularity is available */ static int test_granularity_req_cl_avail_page(const struct test_case *tc, int argc, char *argv[]) { return granularity_template(tc, argc, argv, map_with_unavailable_granularity, PMEM2_GRANULARITY_CACHE_LINE); } /* * test_granularity_req_page_avail_byte -- require page granularity, * when byte granularity is available */ static int test_granularity_req_page_avail_byte(const struct test_case *tc, int argc, char *argv[]) { return granularity_template(tc, argc, argv, map_with_available_granularity, PMEM2_GRANULARITY_PAGE); } /* * test_granularity_req_page_avail_cl -- require page granularity, * when byte cache line is available */ static int test_granularity_req_page_avail_cl(const struct test_case *tc, int argc, char *argv[]) { return granularity_template(tc, argc, argv, map_with_available_granularity, PMEM2_GRANULARITY_PAGE); } /* * test_granularity_req_page_avail_page -- require page granularity, * when page granularity is available */ static int test_granularity_req_page_avail_page(const struct test_case *tc, int argc, char *argv[]) { return granularity_template(tc, argc, argv, map_with_available_granularity, PMEM2_GRANULARITY_PAGE); } /* * test_cases -- available test cases */ static struct test_case test_cases[] = { TEST_CASE(test_granularity_req_byte_avail_byte), TEST_CASE(test_granularity_req_byte_avail_cl), TEST_CASE(test_granularity_req_byte_avail_page), TEST_CASE(test_granularity_req_cl_avail_byte), TEST_CASE(test_granularity_req_cl_avail_cl), TEST_CASE(test_granularity_req_cl_avail_page), TEST_CASE(test_granularity_req_page_avail_byte), TEST_CASE(test_granularity_req_page_avail_cl), TEST_CASE(test_granularity_req_page_avail_page), }; #define NTESTS ARRAY_SIZE(test_cases) int main(int argc, char *argv[]) { START(argc, argv, "pmem2_granularity"); out_init("pmem2_granularity", "TEST_LOG_LEVEL", "TEST_LOG_FILE", 0, 0); TEST_CASE_PROCESS(argc, argv, test_cases, NTESTS); out_fini(); DONE(NULL); }
9448ba78f24eab2fdfa91814fd4c63107fb73f29
19a9f2c19bcb81c4a14ba17831d3098de7731fb5
/ni/src/lib/nfp/studentW.c
10e2cb40de3553adaa13c29253b88126a9c785f5
[ "Apache-2.0" ]
permissive
NCAR/ncl
243c30eaefce642d53373aa583b73df72eb59f22
8a96101fe14d0cf0f5ed66a5e6b1733084bc69df
refs/heads/develop
2023-03-17T07:53:18.883458
2022-05-11T16:01:03
2022-05-11T16:01:03
67,087,395
254
68
NOASSERTION
2022-10-08T07:20:06
2016-09-01T01:34:28
C
UTF-8
C
false
false
5,514
c
studentW.c
#include <stdio.h> #include "wrapper.h" extern void NGCALLF(stuprobt,STUPROBT)(double *, double *, double *, double *); NhlErrorTypes student_t_W( void ) { /* * Input variables */ /* * Argument # 0 */ void *t; double *tmp_t = NULL; int ndims_t; ng_size_t dsizes_t[NCL_MAX_DIMENSIONS]; int has_missing_t; NclScalar missing_t, missing_flt_t, missing_dbl_t; NclBasicDataTypes type_t; /* * Argument # 1 */ void *df; double *tmp_df = NULL; int ndims_df; ng_size_t dsizes_df[NCL_MAX_DIMENSIONS]; int is_scalar_df; NclBasicDataTypes type_df; /* * Return variable */ void *prob; double *tmp_prob = NULL; NclScalar missing_prob; NclBasicDataTypes type_prob; /* * Various */ ng_size_t i, size_output; /* * Retrieve parameters. * * Note any of the pointer parameters can be set to NULL, which * implies you don't care about its value. */ /* * Get argument # 0 */ t = (void*)NclGetArgValue( 0, 2, &ndims_t, dsizes_t, &missing_t, &has_missing_t, &type_t, DONT_CARE); /* * Coerce missing value to double if necessary. */ coerce_missing(type_t,has_missing_t,&missing_t, &missing_dbl_t,&missing_flt_t); /* * Get argument # 1 */ df = (void*)NclGetArgValue( 1, 2, &ndims_df, dsizes_df, NULL, NULL, &type_df, DONT_CARE); /* * Checked df's dimension sizes. It must be a scalar, or the same * size as t. */ is_scalar_df = is_scalar(ndims_df,dsizes_df); if(!is_scalar_df && ndims_df != ndims_t) { NhlPError(NhlFATAL,NhlEUNKNOWN,"student_t: df must be a scalar or an array of the same dimensionality as t"); return(NhlFATAL); } if(!is_scalar_df) { for(i = 0; i < ndims_df; i++) { if(dsizes_df[i] != dsizes_t[i]) { NhlPError(NhlFATAL,NhlEUNKNOWN,"student_t: df must be a scalar or an array of the same dimensionality as t"); return(NhlFATAL); } } } /* * Calculate size of output array. */ size_output = 1; for(i = 0; i < ndims_t; i++) size_output *= dsizes_t[i]; /* * The output type defaults to float, unless either input array is double. */ if(type_t == NCL_double || type_df == NCL_double) { type_prob = NCL_double; } else { type_prob = NCL_float; } /* * Allocate space for coercing input arrays. If any of the input * is already double, then we don't need to allocate space for * temporary arrays, because we'll just change the pointer into * the void array appropriately. * * Allocate space for tmp_t. */ if(type_t != NCL_double) { tmp_t = (double *)calloc(1,sizeof(double)); if(tmp_t == NULL) { NhlPError(NhlFATAL,NhlEUNKNOWN,"student_t: Unable to allocate memory for coercing input array to double"); return(NhlFATAL); } } /* * Allocate space for tmp_df. */ if(is_scalar_df) { tmp_df = coerce_input_double(df,type_df,1,0,NULL,NULL); } else { if(type_df != NCL_double) { tmp_df = (double *)calloc(1,sizeof(double)); if(tmp_df == NULL) { NhlPError(NhlFATAL,NhlEUNKNOWN,"student_t: Unable to allocate memory for coercing input array to double"); return(NhlFATAL); } } } /* * Allocate space for output array. */ if(type_prob != NCL_double) { prob = (void *)calloc(size_output, sizeof(float)); tmp_prob = (double *)calloc(1,sizeof(double)); if(tmp_prob == NULL) { NhlPError(NhlFATAL,NhlEUNKNOWN,"student_t: Unable to allocate memory for temporary output array"); return(NhlFATAL); } } else { prob = (void *)calloc(size_output, sizeof(double)); } if(prob == NULL) { NhlPError(NhlFATAL,NhlEUNKNOWN,"student_t: Unable to allocate memory for output array"); return(NhlFATAL); } if(has_missing_t) { if(type_prob == NCL_double) missing_prob = missing_dbl_t; else missing_prob = missing_flt_t; } /* * Loop across leftmost dimensions and call the Fortran routine for each * subsection of the input arrays. */ for(i = 0; i < size_output; i++) { /* * Coerce subsection of t (tmp_t) to double if necessary. */ if(type_t != NCL_double) { coerce_subset_input_double(t,tmp_t,i,type_t,1,0,NULL,NULL); } else { tmp_t = &((double*)t)[i]; } /* * Coerce subsection of df (tmp_df) to double if necessary. */ if(!is_scalar_df) { if(type_df != NCL_double) { coerce_subset_input_double(df,tmp_df,i,type_df,1,0,NULL,NULL); } else { tmp_df = &((double*)df)[i]; } } /* * Point temporary output array to void output array if appropriate. */ if(type_prob == NCL_double) tmp_prob = &((double*)prob)[i]; /* * Call the Fortran routine. */ NGCALLF(stuprobt,STUPROBT)(tmp_t, tmp_df, &missing_dbl_t.doubleval, tmp_prob); /* * Coerce output back to float if necessary. */ if(type_prob == NCL_float) { coerce_output_float_only(prob,tmp_prob,1,i); } } /* * Free unneeded memory. */ if(type_t != NCL_double) NclFree(tmp_t); if(type_df != NCL_double) NclFree(tmp_df); if(type_prob != NCL_double) NclFree(tmp_prob); /* * Return value back to NCL script. */ if(has_missing_t) { return(NclReturnValue(prob,ndims_t,dsizes_t,&missing_prob, type_prob,0)); } else { return(NclReturnValue(prob,ndims_t,dsizes_t,NULL,type_prob,0)); } }
25ce0b4162e832f683e34bd88b778dfdeb020138
6ff85b80c6fe1b3ad5416a304b93551a5e80de10
/C/Algorithm/RandomUniqueRepetead.c
1a7caa3f8d89cce39dcd2b8af6c996fdedd5cb12
[ "MIT" ]
permissive
maniero/SOpt
c600cc2333e0a47ce013be3516bbb8080502ff2a
5d17e1a9cbf115eaea6d30af2079d0c92ffff7a3
refs/heads/master
2023-08-10T16:48:46.058739
2023-08-10T13:42:17
2023-08-10T13:42:17
78,631,930
1,002
136
MIT
2023-01-28T12:10:01
2017-01-11T11:19:24
C#
UTF-8
C
false
false
844
c
RandomUniqueRepetead.c
#include <stdio.h> #include <time.h> #include <stdlib.h> void shuffle(int *array, int tamanho) { //sorteia grantidamente único - algoritmo Fisher-Yates for (int i = tamanho - 1; i > 0; i--) { int j = rand() % (i + 1); int tmp = array[j]; array[j] = array[i]; array[i] = tmp; } } int main() { srand(time(NULL)); int roll[8] = { 0, 1, 2, 3, 4, 5, 6, 7 }; //cria os valore permitidos shuffle(roll, 8); //embaralha int resultado[6]; for (int i = 0; i < 3; i++) { //só escolhe 3 números conforme a definição resultado[i] = roll[i]; resultado[i + 3] = roll[i]; //repete o número } shuffle(resultado, 6); //embaralha os números que estavam agrupados for (int i = 0; i < 6; i++) printf("%d ", resultado[i]); } //https://pt.stackoverflow.com/q/315483/101
5d222d343c911b25c81706fbe5026258ac421542
321d11eaee885ceb3a74db0a062f9bbdf282148c
/crypto/evp/e_bf.c
2aeda2ecf07adc77e3f0c8cfe98718144b0e78ab
[ "Apache-2.0", "OpenSSL", "LicenseRef-scancode-proprietary-license" ]
permissive
openssl/openssl
75691ebaae957793f2ff0673f77545277dfb3988
5318c012885a5382eadbf95aa9c1d35664bca819
refs/heads/master
2023-09-03T15:22:52.727123
2023-09-01T07:10:49
2023-09-02T14:30:01
7,634,677
24,148
11,569
Apache-2.0
2023-09-14T19:48:11
2013-01-15T22:34:48
C
UTF-8
C
false
false
1,398
c
e_bf.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * BF low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #ifndef OPENSSL_NO_BF # include <openssl/evp.h> # include "crypto/evp.h" # include <openssl/objects.h> # include <openssl/blowfish.h> # include "evp_local.h" static int bf_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); typedef struct { BF_KEY ks; } EVP_BF_KEY; # define data(ctx) EVP_C_DATA(EVP_BF_KEY,ctx) IMPLEMENT_BLOCK_CIPHER(bf, ks, BF, EVP_BF_KEY, NID_bf, 8, 16, 8, 64, EVP_CIPH_VARIABLE_LENGTH, bf_init_key, NULL, EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL) static int bf_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int len = EVP_CIPHER_CTX_get_key_length(ctx); if (len < 0) return 0; BF_set_key(&data(ctx)->ks, len, key); return 1; } #endif
b93392c67dc311279e67eb60b074b66f1e5112c8
a0c3679eda79919ebe06f490b799353081b2d233
/src/config.c
4e0f7db0e518d44f52286e09a4ece872d0ff7f6d
[ "BSD-2-Clause" ]
permissive
lfos/calcurse
91309ac2e1cc30b83c24199d5e0242348b489b97
95bb55f68b446e4461f27ef3a74a7d2eda950289
refs/heads/pu
2023-08-22T11:19:07.177361
2023-06-03T17:30:37
2023-06-03T17:31:59
13,078,961
970
156
BSD-2-Clause
2023-08-12T15:33:48
2013-09-24T23:06:30
C
UTF-8
C
false
false
20,429
c
config.c
/* * Calcurse - text-based organizer * * Copyright (c) 2004-2023 calcurse Development Team <misc@calcurse.org> * 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 * 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. * * Send your feedback or comments to : misc@calcurse.org * Calcurse home page : http://calcurse.org * */ #include <ctype.h> #include <unistd.h> #include <string.h> #include <strings.h> #include "calcurse.h" typedef int (*config_fn_parse_t) (void *, const char *); typedef int (*config_fn_serialize_t) (char **, void *); struct confvar { const char *key; config_fn_parse_t fn_parse; config_fn_serialize_t fn_serialize; void *target; }; static int config_parse_bool(unsigned *, const char *); static int config_serialize_bool(char **, unsigned *); static int config_parse_int(int *, const char *); static int config_serialize_int(char **, int *); static int config_parse_unsigned(unsigned *, const char *); static int config_serialize_unsigned(char **, unsigned *); static int config_parse_str(char *, const char *); static int config_serialize_str(char **, const char *); static int config_parse_calendar_view(void *, const char *); static int config_serialize_calendar_view(char **, void *); static int config_parse_todo_view(void *, const char *); static int config_serialize_todo_view(char **, void *); static int config_parse_default_panel(void *, const char *); static int config_serialize_default_panel(char **, void *); static int config_parse_first_day_of_week(void *, const char *); static int config_serialize_first_day_of_week(char **, void *); static int config_parse_color_theme(void *, const char *); static int config_serialize_color_theme(char **, void *); static int config_parse_layout(void *, const char *); static int config_serialize_layout(char **, void *); static int config_parse_sidebar_width(void *, const char *); static int config_serialize_sidebar_width(char **, void *); static int config_parse_output_datefmt(void *, const char *); static int config_serialize_output_datefmt(char **, void *); static int config_parse_input_datefmt(void *, const char *); static int config_serialize_input_datefmt(char **, void *); static int config_parse_notifyall(void *, const char *); static int config_serialize_notifyall(char **, void *); static int config_parse_heading_pos(void *, const char *); static int config_serialize_heading_pos(char **, void *); #define CONFIG_HANDLER_BOOL(var) (config_fn_parse_t) config_parse_bool, \ (config_fn_serialize_t) config_serialize_bool, &(var) #define CONFIG_HANDLER_INT(var) (config_fn_parse_t) config_parse_int, \ (config_fn_serialize_t) config_serialize_int, &(var) #define CONFIG_HANDLER_UNSIGNED(var) (config_fn_parse_t) config_parse_unsigned, \ (config_fn_serialize_t) config_serialize_unsigned, &(var) #define CONFIG_HANDLER_STR(var) (config_fn_parse_t) config_parse_str, \ (config_fn_serialize_t) config_serialize_str, &(var) static const struct confvar confmap[] = { {"appearance.calendarview", config_parse_calendar_view, config_serialize_calendar_view, NULL}, {"appearance.compactpanels", CONFIG_HANDLER_BOOL(conf.compact_panels)}, {"appearance.defaultpanel", config_parse_default_panel, config_serialize_default_panel, NULL}, {"appearance.layout", config_parse_layout, config_serialize_layout, NULL}, {"appearance.headerline", CONFIG_HANDLER_BOOL(conf.header_line)}, {"appearance.eventseparator", CONFIG_HANDLER_BOOL(conf.event_separator)}, {"appearance.dayseparator", CONFIG_HANDLER_BOOL(conf.day_separator)}, {"appearance.emptyline", CONFIG_HANDLER_BOOL(conf.empty_appt_line)}, {"appearance.emptyday", CONFIG_HANDLER_STR(conf.empty_day)}, {"appearance.notifybar", CONFIG_HANDLER_BOOL(nbar.show)}, {"appearance.sidebarwidth", config_parse_sidebar_width, config_serialize_sidebar_width, NULL}, {"appearance.theme", config_parse_color_theme, config_serialize_color_theme, NULL}, {"appearance.todoview", config_parse_todo_view, config_serialize_todo_view, NULL}, {"appearance.headingpos", config_parse_heading_pos, config_serialize_heading_pos, NULL}, {"daemon.enable", CONFIG_HANDLER_BOOL(dmon.enable)}, {"daemon.log", CONFIG_HANDLER_BOOL(dmon.log)}, {"format.inputdate", config_parse_input_datefmt, config_serialize_input_datefmt, NULL}, {"format.notifydate", CONFIG_HANDLER_STR(nbar.datefmt)}, {"format.notifytime", CONFIG_HANDLER_STR(nbar.timefmt)}, {"format.appointmenttime", CONFIG_HANDLER_STR(conf.timefmt)}, {"format.outputdate", config_parse_output_datefmt, config_serialize_output_datefmt, NULL}, {"format.dayheading", CONFIG_HANDLER_STR(conf.day_heading)}, {"general.autogc", CONFIG_HANDLER_BOOL(conf.auto_gc)}, {"general.autosave", CONFIG_HANDLER_BOOL(conf.auto_save)}, {"general.confirmdelete", CONFIG_HANDLER_BOOL(conf.confirm_delete)}, {"general.confirmquit", CONFIG_HANDLER_BOOL(conf.confirm_quit)}, {"general.firstdayofweek", config_parse_first_day_of_week, config_serialize_first_day_of_week, NULL}, {"general.multipledays", CONFIG_HANDLER_BOOL(conf.multiple_days)}, {"general.periodicsave", CONFIG_HANDLER_UNSIGNED(conf.periodic_save)}, {"general.systemevents", CONFIG_HANDLER_BOOL(conf.systemevents)}, {"notification.command", CONFIG_HANDLER_STR(nbar.cmd)}, {"notification.notifyall", config_parse_notifyall, config_serialize_notifyall, NULL}, {"notification.warning", CONFIG_HANDLER_INT(nbar.cntdwn)} }; struct config_save_status { FILE *fp; int done[ARRAY_SIZE(confmap)]; }; typedef int (*config_fn_walk_cb_t) (const char *, const char *, void *); typedef int (*config_fn_walk_junk_cb_t) (const char *, void *); static int config_parse_bool(unsigned *dest, const char *val) { if (strcmp(val, "yes") == 0) *dest = 1; else if (strcmp(val, "no") == 0) *dest = 0; else return 0; return 1; } static int config_parse_unsigned(unsigned *dest, const char *val) { if (is_all_digit(val)) *dest = atoi(val); else return 0; return 1; } static int config_parse_int(int *dest, const char *val) { char *cp = (char *)val; if (*val == '+' || *val == '-') cp++; /* Test for empty string before checking for digits only. */ if (*cp && is_all_digit(cp)) *dest = atoi(val); else return 0; return 1; } static int config_parse_str(char *dest, const char *val) { int len = strlen(val); if (len >= BUFSIZ) return 0; memcpy(dest, val, len + 1); return 1; } static int config_parse_color(int *dest, const char *val) { if (!strcmp(val, "black")) *dest = COLOR_BLACK; else if (!strcmp(val, "red")) *dest = COLOR_RED; else if (!strcmp(val, "green")) *dest = COLOR_GREEN; else if (!strcmp(val, "yellow")) *dest = COLOR_YELLOW; else if (!strcmp(val, "blue")) *dest = COLOR_BLUE; else if (!strcmp(val, "magenta")) *dest = COLOR_MAGENTA; else if (!strcmp(val, "cyan")) *dest = COLOR_CYAN; else if (!strcmp(val, "white")) *dest = COLOR_WHITE; else if (!strcmp(val, "default")) *dest = background; else return 0; return 1; } static int config_parse_color_pair(int *dest1, int *dest2, const char *val) { char s1[BUFSIZ], s2[BUFSIZ]; if (sscanf(val, "%s on %s", s1, s2) != 2) return 0; return (config_parse_color(dest1, s1) && config_parse_color(dest2, s2)); } static int config_parse_calendar_view(void *dummy, const char *val) { if (!strcmp(val, "monthly")) { ui_calendar_set_view(CAL_MONTH_VIEW); conf.cal_view = CAL_MONTH_VIEW; } else if (!strcmp(val, "weekly")) { ui_calendar_set_view(CAL_WEEK_VIEW); conf.cal_view = CAL_WEEK_VIEW; } else return 0; return 1; } static int config_parse_todo_view(void *dummy, const char *val) { if (!strcmp(val, "show-completed")) { ui_todo_set_view(TODO_SHOW_COMPLETED_VIEW); conf.todo_view = TODO_SHOW_COMPLETED_VIEW; } else if (!strcmp(val, "hide-completed")) { ui_todo_set_view(TODO_HIDE_COMPLETED_VIEW); conf.todo_view = TODO_HIDE_COMPLETED_VIEW; } else return 0; return 1; } static int config_parse_default_panel(void *dummy, const char *val) { if (!strcmp(val, "calendar")) conf.default_panel = CAL; else if (!strcmp(val, "appointments")) conf.default_panel = APP; else if (!strcmp(val, "todo")) conf.default_panel = TOD; else return 0; return 1; } static int config_parse_first_day_of_week(void *dummy, const char *val) { int i; for (i = 0; i < WEEKINDAYS; i++) { if(!strcasecmp(val, get_wday_default_string(i))) { ui_calendar_set_first_day_of_week(i); return 1; } } return 0; } static int config_parse_color_theme(void *dummy, const char *val) { int color1, color2; if (!strcmp(val, "0") || !strcmp(val, "none")) { colorize = 0; return 1; } if (!config_parse_color_pair(&color1, &color2, val)) return 0; init_pair(COLR_CUSTOM, color1, color2); custom_init_attr(); return 1; } static int config_parse_layout(void *dummy, const char *val) { wins_set_layout(atoi(val)); return 1; } static int config_parse_sidebar_width(void *dummy, const char *val) { wins_set_sbar_width(atoi(val)); return 1; } static int config_parse_output_datefmt(void *dummy, const char *val) { if (val[0] != '\0') return config_parse_str(conf.output_datefmt, val); return 1; } static int config_parse_input_datefmt(void *dummy, const char *val) { if (config_parse_int(&conf.input_datefmt, val)) { if (conf.input_datefmt <= 0 || conf.input_datefmt > DATE_FORMATS) conf.input_datefmt = 1; return 1; } else { return 0; } } static int config_parse_notifyall(void *dummy, const char *val) { if (strcmp(val, "flagged-only") == 0) nbar.notify_all = NOTIFY_FLAGGED_ONLY; else if (strcmp(val, "unflagged-only") == 0) nbar.notify_all = NOTIFY_UNFLAGGED_ONLY; else if (strcmp(val, "all") == 0) nbar.notify_all = NOTIFY_ALL; else return config_parse_bool(&nbar.notify_all, val); return 1; } static int config_parse_heading_pos(void *dummy, const char *val) { if (!strcmp(val, "left-justified")) conf.heading_pos = LEFT; else if (!strcmp(val, "centered")) conf.heading_pos = CENTER; else if (!strcmp(val, "right-justified")) conf.heading_pos = RIGHT; else return 0; return 1; } /* Set a configuration variable. */ static int config_set_conf(const char *key, const char *value) { int i; if (!key) return -1; for (i = 0; i < ARRAY_SIZE(confmap); i++) { if (!strcmp(confmap[i].key, key)) return confmap[i].fn_parse(confmap[i].target, value); } return -1; } static int config_serialize_bool(char **dest, unsigned *val) { *dest = mem_strdup(*val ? "yes" : "no"); return 1; } static int config_serialize_unsigned(char **dest, unsigned *val) { asprintf(dest, "%u", *val); return 1; } static int config_serialize_int(char **dest, int *val) { asprintf(dest, "%d", *val); return 1; } static int config_serialize_str(char **dest, const char *val) { *dest = mem_strdup(val); return 1; } /* * Return a string defining the color theme in the form: * foreground color 'on' background color * in order to dump this data in the configuration file. * Color numbers follow the ncurses library definitions. * If ncurses library was compiled with --enable-ext-funcs, * then default color is -1. */ static char *config_color_theme_name(void) { #define MAXCOLORS 8 #define NBCOLORS 2 #define DEFAULTCOLOR 255 #define DEFAULTCOLOR_EXT -1 char *theme; int i; short color[NBCOLORS]; const char *color_name[NBCOLORS]; const char *default_color = "default"; const char *name[MAXCOLORS] = { "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white" }; if (!colorize) { return mem_strdup("none"); } pair_content(COLR_CUSTOM, &color[0], &color[1]); for (i = 0; i < NBCOLORS; i++) { if ((color[i] == DEFAULTCOLOR) || (color[i] == DEFAULTCOLOR_EXT)) { color_name[i] = default_color; } else if (color[i] >= 0 && color[i] <= MAXCOLORS) { color_name[i] = name[color[i]]; } else { EXIT(_("unknown color")); /* NOTREACHED */ } } asprintf(&theme, "%s on %s", color_name[0], color_name[1]); return theme; } static int config_serialize_calendar_view(char **buf, void *dummy) { if (conf.cal_view == CAL_WEEK_VIEW) *buf = mem_strdup("weekly"); else *buf = mem_strdup("monthly"); return 1; } static int config_serialize_todo_view(char **buf, void *dummy) { if (conf.todo_view == TODO_SHOW_COMPLETED_VIEW) *buf = mem_strdup("show-completed"); else *buf = mem_strdup("hide-completed"); return 1; } static int config_serialize_default_panel(char **buf, void *dummy) { if (conf.default_panel == CAL) *buf = mem_strdup("calendar"); else if (conf.default_panel == APP) *buf = mem_strdup("appointments"); else *buf = mem_strdup("todo"); return 1; } static int config_serialize_first_day_of_week(char **buf, void *dummy) { *buf = mem_strdup(get_wday_default_string(ui_calendar_get_wday_start())); /* now stores string with uppercase first letter, changing to lower */ **buf = tolower(**buf); return 1; } static int config_serialize_color_theme(char **buf, void *dummy) { *buf = config_color_theme_name(); return 1; } static int config_serialize_layout(char **buf, void *dummy) { int tmp = wins_layout(); return config_serialize_int(buf, &tmp); } static int config_serialize_sidebar_width(char **buf, void *dummy) { int tmp = wins_sbar_wperc(); return config_serialize_int(buf, &tmp); } static int config_serialize_output_datefmt(char **buf, void *dummy) { return config_serialize_str(buf, conf.output_datefmt); } static int config_serialize_input_datefmt(char **buf, void *dummy) { return config_serialize_int(buf, &conf.input_datefmt); } static int config_serialize_notifyall(char **buf, void *dummy) { if (nbar.notify_all == NOTIFY_FLAGGED_ONLY) *buf = mem_strdup("flagged-only"); else if (nbar.notify_all == NOTIFY_UNFLAGGED_ONLY) *buf = mem_strdup("unflagged-only"); else if (nbar.notify_all == NOTIFY_ALL) *buf = mem_strdup("all"); else return 0; return 1; } static int config_serialize_heading_pos(char **buf, void *dummy) { if (conf.heading_pos == LEFT) *buf = mem_strdup("left-justified"); else if (conf.heading_pos == CENTER) *buf = mem_strdup("centered"); else *buf = mem_strdup("right-justified"); return 1; } /* Serialize the value of a configuration variable. */ static int config_serialize_conf(char **buf, const char *key, struct config_save_status *status) { int i; if (!key) return -1; for (i = 0; i < ARRAY_SIZE(confmap); i++) { if (!strcmp(confmap[i].key, key)) { if (confmap[i].fn_serialize(buf, confmap[i].target)) { if (status) status->done[i] = 1; return 1; } else { return 0; } } } return -1; } static void config_file_walk(config_fn_walk_cb_t fn_cb, config_fn_walk_junk_cb_t fn_junk_cb, void *data) { FILE *data_file; char buf[BUFSIZ], e_conf[BUFSIZ]; char *key, *value; data_file = fopen(path_conf, "r"); EXIT_IF(data_file == NULL, _("failed to open configuration file")); pthread_mutex_lock(&nbar.mutex); for (;;) { if (fgets(buf, sizeof buf, data_file) == NULL) break; io_extract_data(e_conf, buf, sizeof buf); if (*e_conf == '\0' || *e_conf == '#') { if (fn_junk_cb) fn_junk_cb(buf, data); continue; } key = e_conf; value = strchr(e_conf, '='); if (value) { *value = '\0'; value++; } else { EXIT(_("invalid configuration directive: \"%s\""), e_conf); } if (strcmp(key, "auto_save") == 0 || strcmp(key, "auto_gc") == 0 || strcmp(key, "periodic_save") == 0 || strcmp(key, "confirm_quit") == 0 || strcmp(key, "confirm_delete") == 0 || strcmp(key, "skip_system_dialogs") == 0 || strcmp(key, "skip_progress_bar") == 0 || strcmp(key, "calendar_default_view") == 0 || strcmp(key, "week_begins_on_monday") == 0 || strcmp(key, "color-theme") == 0 || strcmp(key, "layout") == 0 || strcmp(key, "side-bar_width") == 0 || strcmp(key, "notify-bar_show") == 0 || strcmp(key, "notify-bar_date") == 0 || strcmp(key, "notify-bar_clock") == 0 || strcmp(key, "notify-bar_warning") == 0 || strcmp(key, "notify-bar_command") == 0 || strcmp(key, "notify-all") == 0 || strcmp(key, "output_datefmt") == 0 || strcmp(key, "input_datefmt") == 0 || strcmp(key, "notify-daemon_enable") == 0 || strcmp(key, "notify-daemon_log") == 0) { WARN_MSG(_("Pre-3.0.0 configuration file format detected, " "please upgrade running `calcurse-upgrade`.")); } /* * Backwards compatibility for removed configuration options: * ignored on load, omitted on save. */ if (strcmp(key, "general.progressbar") == 0 || strcmp(key, "general.systemdialogs") == 0) continue; if (value && (*value == '\0' || *value == '\n')) { /* Backward compatibility mode. */ if (fgets(buf, sizeof buf, data_file) == NULL) break; io_extract_data(e_conf, buf, sizeof buf); if (*e_conf == '#') *e_conf = '\0'; value = e_conf; } fn_cb(key, value, data); } file_close(data_file, __FILE_POS__); pthread_mutex_unlock(&nbar.mutex); } static int config_load_cb(const char *key, const char *value, void *dummy) { int result = config_set_conf(key, value); if (result < 0) { WARN_MSG(_("unknown user option: \"%s\" (ignored)"), key); } else if (result == 0) { WARN_MSG(_("invalid option format: \"%s\" (ignored)"), key); } return 1; } /* Load the user configuration. */ void config_load(void) { config_file_walk(config_load_cb, NULL, NULL); } static int config_save_cb(const char *key, const char *value, void *status) { char *buf; int result = config_serialize_conf(&buf, key, (struct config_save_status *)status); if (result < 0) { WARN_MSG(_("unknown user option: \"%s\" (disabled)"), key); } else if (result == 0) { WARN_MSG(_("invalid option format: \"%s\" (disabled)"), key); } if (result <= 0) { fputc('#', ((struct config_save_status *)status)->fp); buf = mem_strdup(value); } fputs(key, ((struct config_save_status *)status)->fp); fputc('=', ((struct config_save_status *)status)->fp); fputs(buf, ((struct config_save_status *)status)->fp); fputc('\n', ((struct config_save_status *)status)->fp); mem_free(buf); return 1; } static int config_save_junk_cb(const char *data, void *status) { fputs(data, ((struct config_save_status *)status)->fp); return 1; } /* Save the user configuration. */ unsigned config_save(void) { char *tmpprefix = NULL, *tmppath = NULL; struct config_save_status status; int i; int ret = 0; if (read_only) return 1; asprintf(&tmpprefix, "%s/%s", get_tempdir(), CONF_PATH_NAME); if ((tmppath = new_tempfile(tmpprefix)) == NULL) goto cleanup; status.fp = fopen(tmppath, "w"); if (!status.fp) goto cleanup; memset(status.done, 0, sizeof(status.done)); config_file_walk(config_save_cb, config_save_junk_cb, (void *)&status); /* Set variables that were missing from the configuration file. */ for (i = 0; i < ARRAY_SIZE(confmap); i++) { if (!status.done[i]) config_save_cb(confmap[i].key, NULL, &status); } file_close(status.fp, __FILE_POS__); if (io_file_cp(tmppath, path_conf)) unlink(tmppath); ret = 1; cleanup: mem_free(tmpprefix); mem_free(tmppath); return ret; }
adf0905423e5c63a527dab31c78869e661f2c98e
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/raspberry-pico/libraries/pico-sdk/src/host/hardware_gpio/gpio.c
d5f4996f25aaa762600d6a1165d0cae1d05ea462
[ "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
RT-Thread/rt-thread
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
3602f891211904a27dcbd51e5ba72fefce7326b2
refs/heads/master
2023-09-01T04:10:20.295801
2023-08-31T16:20:55
2023-08-31T16:20:55
7,408,108
9,599
5,805
Apache-2.0
2023-09-14T13:37:26
2013-01-02T14:49:21
C
UTF-8
C
false
false
1,516
c
gpio.c
/* * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. * * SPDX-License-Identifier: BSD-3-Clause */ #include "hardware/gpio.h" // todo weak or replace? probably weak void gpio_set_function(uint gpio, enum gpio_function fn) { } void gpio_pull_up(uint gpio) { } void gpio_pull_down(uint gpio) { } void gpio_disable_pulls(uint gpio) { } void gpio_set_pulls(uint gpio, bool up, bool down) { } void gpio_set_outover(uint gpio, uint value) { } void gpio_set_inover(uint gpio, uint value) { } void gpio_set_oeover(uint gpio, uint value) { } void gpio_set_irq_enabled(uint gpio, uint32_t events, bool enable) { } void gpio_acknowledge_irq(uint gpio, uint32_t events) { } void gpio_init(uint gpio) { } PICO_WEAK_FUNCTION_DEF(gpio_get) bool PICO_WEAK_FUNCTION_IMPL_NAME(gpio_get)(uint gpio) { return 0; } uint32_t gpio_get_all() { return 0; } void gpio_set_mask(uint32_t mask) { } void gpio_clr_mask(uint32_t mask) { } void gpio_xor_mask(uint32_t mask) { } void gpio_put_masked(uint32_t mask, uint32_t value) { } void gpio_put_all(uint32_t value) { } void gpio_put(uint gpio, int value) { } void gpio_set_dir_out_masked(uint32_t mask) { } void gpio_set_dir_in_masked(uint32_t mask) { } void gpio_set_dir_masked(uint32_t mask, uint32_t value) { } void gpio_set_dir_all_bits(uint32_t value) { } void gpio_set_dir(uint gpio, bool out) { } void gpio_debug_pins_init() { } void gpio_set_input_enabled(uint gpio, bool enable) { } void gpio_init_mask(uint gpio_mask) { }
4b826144895161877785ed5e6781a2210603a71d
315f1de5835d38669c9777e8009709d80ff3d04e
/spatial/core/resources/cppgen/fringeZCU/xil_libs/xfsbl_config.h
74402d78fc4949012015e7028545426f7902956a
[ "MIT" ]
permissive
stanford-ppl/spatial-lang
751dcadfc38770f7a0b65e701f3e6aa5ef50e146
55e9a67b28f83caf3606e0c7bbead82a12cfbd2a
refs/heads/master
2023-03-08T17:55:24.007295
2018-11-14T22:07:39
2018-11-14T22:07:39
78,697,642
109
15
MIT
2018-04-12T10:44:07
2017-01-12T01:47:41
Verilog
UTF-8
C
false
false
6,637
h
xfsbl_config.h
/****************************************************************************** * * Copyright (C) 2015 - 17 Xilinx, 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, 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. * * Use of the Software is limited solely to applications: * (a) running on a Xilinx device, or * (b) that interact with a Xilinx device through a bus or interconnect. * * 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 * XILINX 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 Xilinx shall not be used * in advertising or otherwise to promote the sale, use or other dealings in * this Software without prior written authorization from Xilinx. * ******************************************************************************/ /*****************************************************************************/ /** * * @file xfsbl_config.h * * This is the header file which contains FSBL configuration * for users. * * <pre> * MODIFICATION HISTORY: * * Ver Who Date Changes * ----- ---- -------- ------------------------------------------------------- * 1.00 kc 10/21/13 Initial release * 2.0 vns 03/24/17 Removed READ_BUFFER_SIZE from configuration * Added FSBL_PL_CLEAR_EXCLUDE_VAL, FSBL_USB_EXCLUDE_VAL, * FSBL_PROT_BYPASS_EXCLUDE_VAL configurations *</pre> * * @note * ******************************************************************************/ #ifndef XFSBL_CONFIG_H #define XFSBL_CONFIG_H #ifdef __cplusplus extern "C" { #endif /***************************** Include Files *********************************/ /************************** Constant Definitions *****************************/ /* This is the address in DDR where bitstream will be copied temporarily */ #define XFSBL_DDR_TEMP_ADDRESS (0x100000U) /* This is the address in DDR where boot.bin will be copied in USB boot mode */ #define XFSBL_DDR_TEMP_BUFFER_ADDRESS (0x4000000U) /**************************** Type Definitions *******************************/ /***************** Macros (Inline Functions) Definitions *********************/ /** * @name FSBL Debug options * * FSBL supports an unconditional print * - FSBL_PRINT Used to print FSBL header and any mandatory prints * Hence FSBL_PRINT_VAL should always be 1 * Further FSBL by default doesn't have any debug prints enabled. If user * want to enable the debug prints, they can define the following * options * FSBL supports three types of debug levels. * - FSBL_DEBUG Defining this will print basic information and * error prints if any * - FSBL_DEBUG_INFO Defining this will have prints enabled with format * specifiers in addition to the basic information * - FSBL_DEBUG_DETAILED Defining this will print information with * all data exchanged. */ #define FSBL_PRINT_VAL (1U) #define FSBL_DEBUG_VAL (0U) #define FSBL_DEBUG_INFO_VAL (0U) #define FSBL_DEBUG_DETAILED_VAL (0U) /** * FSBL Debug options */ #if FSBL_PRINT_VAL #define FSBL_PRINT #endif #if FSBL_DEBUG_VAL #define FSBL_DEBUG #endif #if FSBL_DEBUG_INFO_VAL #define FSBL_DEBUG_INFO #endif #if FSBL_DEBUG_DETAILED_VAL #define FSBL_DEBUG_DETAILED #endif /** * @name FSBL code include options * * FSBL by default all the code is included. * Unwanted code can be excluded from the elf by defining here * Below blocks can be excluded from the code. * - FSBL_NAND_EXCLUDE NAND code will be excluded * - FSBL_QSPI_EXCLUDE QSPI code will be excluded * - FSBL_SD_EXCLUDE SD code will be excluded * - FSBL_SECURE_EXCLUDE Secure features * (authentication, decryption, checksum) will be excluded * - FSBL_BS_EXCLUDE PL bitstream code will be excluded * - FSBL_SHA2_EXCLUDE SHA2 code will be excluded * - FSBL_EARLY_HANDOFF_EXCLUDE Early handoff related code will be excluded * - FSBL_WDT_EXCLUDE WDT code will be excluded * - FSBL_PERF_EXCLUDE_VAL Performance prints are excluded * - FSBL_A53_TCM_ECC_EXCLUDE_VAL TCM ECC Init will be excluded for A53 * - FSBL_PL_CLEAR_EXCLUDE_VAL PL clear will be excluded unless boot.bin * contains bitstream */ #define FSBL_NAND_EXCLUDE_VAL (0U) #define FSBL_QSPI_EXCLUDE_VAL (0U) #define FSBL_SD_EXCLUDE_VAL (0U) #define FSBL_SECURE_EXCLUDE_VAL (0U) #define FSBL_BS_EXCLUDE_VAL (0U) #define FSBL_SHA2_EXCLUDE_VAL (1U) #define FSBL_EARLY_HANDOFF_EXCLUDE_VAL (1U) #define FSBL_WDT_EXCLUDE_VAL (0U) #define FSBL_PERF_EXCLUDE_VAL (1U) #define FSBL_A53_TCM_ECC_EXCLUDE_VAL (1U) #define FSBL_PL_CLEAR_EXCLUDE_VAL (1U) #define FSBL_USB_EXCLUDE_VAL (1U) #define FSBL_PROT_BYPASS_EXCLUDE_VAL (0U) #if FSBL_NAND_EXCLUDE_VAL #define FSBL_NAND_EXCLUDE #endif #if FSBL_QSPI_EXCLUDE_VAL #define FSBL_QSPI_EXCLUDE #endif #if FSBL_SD_EXCLUDE_VAL #define FSBL_SD_EXCLUDE #endif #if FSBL_SECURE_EXCLUDE_VAL #define FSBL_SECURE_EXCLUDE #endif #if FSBL_BS_EXCLUDE_VAL #define FSBL_BS_EXCLUDE #endif #if FSBL_SHA2_EXCLUDE_VAL #define FSBL_SHA2_EXCLUDE #endif #if FSBL_EARLY_HANDOFF_EXCLUDE_VAL #define FSBL_EARLY_HANDOFF_EXCLUDE #endif #if FSBL_WDT_EXCLUDE_VAL #define FSBL_WDT_EXCLUDE #endif #if FSBL_PERF_EXCLUDE_VAL #define FSBL_PERF_EXCLUDE #endif #if FSBL_A53_TCM_ECC_EXCLUDE_VAL #define FSBL_A53_TCM_ECC_EXCLUDE #endif #if FSBL_PL_CLEAR_EXCLUDE_VAL #define FSBL_PL_CLEAR_EXCLUDE #endif #if FSBL_USB_EXCLUDE_VAL #define FSBL_USB_EXCLUDE #endif #if FSBL_PROT_BYPASS_EXCLUDE_VAL #define FSBL_PROT_BYPASS_EXCLUDE #endif /************************** Function Prototypes ******************************/ /************************** Variable Definitions *****************************/ #ifdef __cplusplus } #endif #endif /* XFSBL_CONFIG_H */
07ccb47521e1bcde1b266c5429778cbf7dea765a
5ef7f5ba06b98319a5406dfa3b25c985257713d4
/skuwa/ilkf_hw_wa.c
70e7d6eb5e33a614baf18873d995eb8c0201e232
[ "MIT" ]
permissive
intel/intel-graphics-compiler
6a1ae1a84c541e967e70324492f22c941a02e38f
ea522543be6d042ec80e5db8e8878be31af68938
refs/heads/master
2023-09-03T20:31:55.215461
2023-08-29T18:31:52
2023-09-02T08:55:05
105,299,467
546
176
NOASSERTION
2023-08-23T08:57:03
2017-09-29T17:27:54
C++
UTF-8
C
false
false
1,579
c
ilkf_hw_wa.c
/*========================== begin_copyright_notice ============================ Copyright (C) 2017-2022 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ // This is an auto-generated file. Please do not edit! // If changes are needed here please reach out to the codeowners, thanks. #include "wa_def.h" #include "ilkf_rev_id.h" void InitLkfHwWaTable(PWA_TABLE pWaTable, PSKU_FEATURE_TABLE pSkuTable, PWA_INIT_PARAM pWaParam) { int iStepId_LKF = (int)pWaParam->usRevId; SI_WA_ENABLE( Wa_1406306137, "No Link Provided", "No HWSightingLink provided", PLATFORM_ALL, SI_WA_BETWEEN(iStepId_LKF, LKF_GT_REV_ID_A0, FUTURE_PROJECT)); SI_WA_ENABLE( Wa_220856683, "No Link Provided", "No HWSightingLink provided", PLATFORM_ALL, SI_WA_BETWEEN(iStepId_LKF, LKF_GT_REV_ID_A0, FUTURE_PROJECT)); SI_WA_ENABLE( Wa_2201674230, "No Link Provided", "No HWSightingLink provided", PLATFORM_ALL, SI_WA_BETWEEN(iStepId_LKF, LKF_GT_REV_ID_A0, LKF_GT_REV_ID_B0)); SI_WA_ENABLE( Wa_1406950495, "No Link Provided", "No HWSightingLink provided", PLATFORM_ALL, SI_WA_BETWEEN(iStepId_LKF, LKF_GT_REV_ID_A0, FUTURE_PROJECT)); SI_WA_ENABLE( Wa_1807084924, "No Link Provided", "No HWSightingLink provided", PLATFORM_ALL, SI_WA_BETWEEN(iStepId_LKF, LKF_GT_REV_ID_A0, FUTURE_PROJECT)); }
7bbc31aa450b5317c1c8db9a7c9dbdbc03baa4c1
0668bf74167ec645da3153c4be9d2f529ca62005
/STM32F103RCT6/STM32F10x_StdPeriph_Lib_V3.5.0/Utilities/STM32_EVAL/stm32_eval.c
9f7aa00be1c94163f29fd6f64be044d7d54040b7
[]
no_license
remotemcu/remcu_examples
eb401b343ae479d01f3be625c190d06df23ba4f9
b18752669af243770f67484e8801e5b16bfc8d87
refs/heads/master
2023-08-09T00:26:42.086987
2023-08-07T22:04:13
2023-08-07T22:04:13
198,629,084
426
12
null
2023-08-07T22:04:15
2019-07-24T12:13:21
C
UTF-8
C
false
false
3,028
c
stm32_eval.c
/** ****************************************************************************** * @file stm32_eval.c * @author MCD Application Team * @version V4.5.0 * @date 07-March-2011 * @brief STM32xx-EVAL abstraction layer. * This file should be added to the main application to use the provided * functions that manage Leds, push-buttons, COM ports and low level * HW resources initialization of the different modules available on * STM32 evaluation boards from STMicroelectronics. ****************************************************************************** * @attention * * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. * * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2> ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32_eval.h" /** @addtogroup Utilities * @{ */ /** @defgroup STM32_EVAL * @brief This file provides firmware functions to manage Leds, push-buttons, * COM ports and low level HW resources initialization of the different * modules available on STM32 Evaluation Boards from STMicroelectronics. * @{ */ /** @defgroup STM32_EVAL_Abstraction_Layer * @{ */ #ifdef USE_STM32100B_EVAL #include "stm32100b_eval/stm32100b_eval.c" #elif defined USE_STM3210B_EVAL #include "stm3210b_eval/stm3210b_eval.c" #elif defined USE_STM3210E_EVAL #include "stm3210e_eval/stm3210e_eval.c" #elif defined USE_STM3210C_EVAL #include "stm3210c_eval/stm3210c_eval.c" #elif defined USE_STM32L152_EVAL #include "stm32l152_eval/stm32l152_eval.c" #elif defined USE_STM32100E_EVAL #include "stm32100e_eval/stm32100e_eval.c" #else #error "Please select first the STM32 EVAL board to be used (in stm32_eval.h)" #endif /** @defgroup STM32_EVAL_Private_TypesDefinitions * @{ */ /** * @} */ /** @defgroup STM32_EVAL_Private_Defines * @{ */ /** * @} */ /** @defgroup STM32_EVAL_Private_Macros * @{ */ /** * @} */ /** @defgroup STM32_EVAL_Private_Variables * @{ */ /** * @} */ /** @defgroup STM32_EVAL_Private_FunctionPrototypes * @{ */ /** * @} */ /** @defgroup STM32_EVAL_Private_Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
72a79031eba14ba4ade0be44fed4776a597be4fb
da1500e0d3040497614d5327d2461a22e934b4d8
/third_party/musl/arch/x32/reloc.h
dc039adf5b455130af4a4d5af42a722943229bc0
[ "BSD-3-Clause", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-musl-exception", "MIT", "GPL-1.0-or-later", "LGPL-2.0-or-later", "Apache-2.0" ]
permissive
youtube/cobalt
34085fc93972ebe05b988b15410e99845efd1968
acefdaaadd3ef46f10f63d1acae2259e4024d383
refs/heads/main
2023-09-01T13:09:47.225174
2023-09-01T08:54:54
2023-09-01T08:54:54
50,049,789
169
80
BSD-3-Clause
2023-09-14T21:50:50
2016-01-20T18:11:34
null
UTF-8
C
false
false
1,276
h
reloc.h
#define LDSO_ARCH "x32" /* FIXME: x32 is very strange in its use of 64-bit relocation types in * a 32-bit environment. As long as the memory at reloc_addr is * zero-filled prior to relocations, just treating 64-bit relocations * as operating on 32-bit slots should be fine, but this should be * checked. In particular, R_X86_64_64, R_X86_64_DTPOFF64, and * R_X86_64_TPOFF64 may need checking. */ /* The R_X86_64_64, R_X86_64_DTPOFF32, and R_X86_64_TPOFF32 reloc types * were previously mapped in the switch table form of this file; however, * they do not seem to be used/usable for anything. If needed, new * mappings will have to be added. */ #define REL_SYMBOLIC R_X86_64_32 #define REL_OFFSET R_X86_64_PC32 #define REL_GOT R_X86_64_GLOB_DAT #define REL_PLT R_X86_64_JUMP_SLOT #define REL_RELATIVE R_X86_64_RELATIVE #define REL_COPY R_X86_64_COPY #define REL_DTPMOD R_X86_64_DTPMOD64 #define REL_DTPOFF R_X86_64_DTPOFF64 #define REL_TPOFF R_X86_64_TPOFF64 #define CRTJMP(pc,sp) __asm__ __volatile__( \ "mov %1,%%esp ; jmp *%0" : : "r"((uint64_t)(uintptr_t)pc), "r"(sp) : "memory" ) #define GETFUNCSYM(fp, sym, got) __asm__ ( \ ".hidden " #sym "\n" \ " lea " #sym "(%%rip),%0\n" \ : "=r"(*fp) : : "memory" )
34c1683b1c184ac7c320dd65864a48ed61097970
20e1c2f5cfac01f6b007124fa7792dd69751a6bb
/src/os/shared/inc/os-shared-common.h
e84249835dad2b5b694baa962cb31b95fcf865cd
[ "Apache-2.0" ]
permissive
nasa/osal
71f159b767ba4a8c39df48f238b4f296cc571ac8
99e3b4007da51031b521d90390526e123ff740b4
refs/heads/main
2023-09-01T06:33:53.932829
2023-08-18T14:27:02
2023-08-18T14:27:02
4,814,601
493
229
Apache-2.0
2023-09-13T13:57:40
2012-06-27T23:10:37
C
UTF-8
C
false
false
5,176
h
os-shared-common.h
/************************************************************************ * NASA Docket No. GSC-18,719-1, and identified as “core Flight System: Bootes” * * Copyright (c) 2020 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ************************************************************************/ /** * \file * * \ingroup shared * */ #ifndef OS_SHARED_COMMON_H #define OS_SHARED_COMMON_H #include "osapi-common.h" #include "os-shared-globaldefs.h" /* * Flag values for the "GlobalState" member the global state structure */ #define OS_INIT_MAGIC_NUMBER 0xBE57C0DE /**< Indicates that OS_API_Init() has been successfully run */ #define OS_SHUTDOWN_MAGIC_NUMBER 0xABADC0DE /**< Indicates that a system shutdown request is pending */ /* Global variables that are common between implementations */ struct OS_shared_global_vars { /* * Tracks whether OS_API_Init() has been called or if * there is a shutdown request pending. * * After boot/first startup this should have 0 (from BSS clearing) * After OS_API_Init() is called this has OS_INIT_MAGIC_NUMBER * After OS_ApplicationShutdown() this has OS_SHUTDOWN_MAGIC_NUMBER */ volatile uint32 GlobalState; /* * The console device ID used for OS_printf() calls */ osal_id_t PrintfConsoleId; /* * PrintfEnabled and GlobalState are marked "volatile" * because they are updated and read by different threads */ volatile bool PrintfEnabled; uint32 MicroSecPerTick; uint32 TicksPerSecond; /* * The event handler is an application-defined callback * that gets invoked as resources are created/configured/deleted. */ OS_EventHandler_t EventHandler; #ifdef OSAL_CONFIG_DEBUG_PRINTF uint8 DebugLevel; #endif }; /* * Shared data structure for global values */ extern OS_SharedGlobalVars_t OS_SharedGlobalVars; /*--------------------------------------------------------------------------------------- Name: OS_NotifyEvent Purpose: Notify the user application of a change in the state of an OSAL resource returns: OS_SUCCESS on success, or relevant error code ---------------------------------------------------------------------------------------*/ int32 OS_NotifyEvent(OS_Event_t event, osal_id_t object_id, void *data); /*--------------------------------------------------------------------------------------- Name: OS_API_Impl_Init Purpose: Initialize the OS-specific layer for the given object type returns: OS_SUCCESS on success, or relevant error code ---------------------------------------------------------------------------------------*/ int32 OS_API_Impl_Init(osal_objtype_t idtype); /* * This function implements the OS-specific portion * of various OSAL functions. They are defined in * OS-specific source files. */ /*---------------------------------------------------------------- Purpose: Block the "idle" thread until woken up The "IdleLoop_Impl" is called by the main thread once everything is running and there is no more work to do. It should suspend the calling thread until a wakeup event happens. ------------------------------------------------------------------*/ void OS_IdleLoop_Impl(void); /*---------------------------------------------------------------- Purpose: Wake up the idle task The "ApplicationShutdown_Impl" should wake up whatever task is currently suspended in "IdleLoop_Impl" and cause that thread to resume and return to its caller. NOTE: This should not block but it may cause the current thread to be preempted by the thread that was woken up, depending on priority levels. ------------------------------------------------------------------*/ void OS_ApplicationShutdown_Impl(void); /*---------------------------------------------------------------- Purpose: Utility function to safely find the length of a string within a fixed-size array buffer. Provides a local OSAL routine to get the functionality of the (non-C99) "strnlen()" function, via the C89/C99 standard "memchr()" function instead. ------------------------------------------------------------------*/ static inline size_t OS_strnlen(const char *s, size_t maxlen) { const char *end = (const char *)memchr(s, 0, maxlen); if (end != NULL) { /* actual length of string is difference */ maxlen = end - s; } return maxlen; } #endif /* OS_SHARED_COMMON_H */
7b76bcc0236a51569d16b6590d2929c459aebe8a
6832a9c81b16ead373325f70fb97753d6a211539
/src/wrapped/wrappedglib2_private.h
5d9b1d220646664ea4c34a0aecb6cf1e47c0c006
[ "MIT" ]
permissive
ptitSeb/box86
2d3a0c4574905ff8d9dc7b5afb5444a273832bd6
ad934455c1b40feeebe5e6bd09b9063519102859
refs/heads/master
2023-08-22T05:30:54.331500
2023-08-20T13:01:58
2023-08-20T13:01:58
164,844,546
2,877
294
MIT
2023-07-27T11:19:10
2019-01-09T10:49:32
C
UTF-8
C
false
false
49,144
h
wrappedglib2_private.h
#if !(defined(GO) && defined(GOM) && defined(GO2) && defined(DATA)) #error meh! #endif //GO(__aeabi_d2lz, //GO(__aeabi_d2ulz, //GO(_fini, GO(g_access, iFpi) GO(g_allocator_free, vFp) GO(g_allocator_new, pFpu) GO(g_array_append_vals, pFppu) GO(g_array_free, pFpi) GO(g_array_get_element_size, uFp) GO(g_array_insert_vals, pFpupu) GO(g_array_new, pFiiu) GO(g_array_prepend_vals, pFppu) GO(g_array_ref, pFp) GO(g_array_remove_index, pFpu) GO(g_array_remove_index_fast, pFpu) GO(g_array_remove_range, pFpuu) GOM(g_array_set_clear_func, vFEpp) GO(g_array_set_size, pFpu) GO(g_array_sized_new, pFiiuu) GOM(g_array_sort, vFEpp) GOM(g_array_sort_with_data, vFEppp) GO(g_array_unref, vFp) GO(g_ascii_digit_value, iFC) GO(g_ascii_dtostr, pFpid) GO(g_ascii_formatd, pFpipd) GO(g_ascii_strcasecmp, iFpp) GO(g_ascii_strdown, pFpi) GO(g_ascii_strncasecmp, iFppu) GO(g_ascii_strtod, dFpp) GO(g_ascii_strtoll, IFppu) GO(g_ascii_strtoull, UFppu) GO(g_ascii_strup, pFpi) GO(g_ascii_tolower, CFC) GO(g_ascii_toupper, CFC) GO(g_ascii_xdigit_value, iFC) GO(g_assertion_message, vFppipp) #ifdef HAVE_LD80BITS GO(g_assertion_message_cmpnum, vFppippDDC) #else GO(g_assertion_message_cmpnum, vFppippKKC) #endif GO(g_assertion_message_cmpstr, vFppippppp) GO(g_assertion_message_error, vFppipppui) GO(g_assertion_message_expr, vFppipp) GO(g_assert_warning, vFppipp) GO(g_async_queue_length, iFp) //GO(g_async_queue_length_unlocked, GO(g_async_queue_lock, vFp) GO(g_async_queue_new, pFv) //GO(g_async_queue_new_full, GO(g_async_queue_pop, pFp) //GO(g_async_queue_pop_unlocked, GO(g_async_queue_push, vFpp) //GO(g_async_queue_push_sorted, //GO(g_async_queue_push_sorted_unlocked, GO(g_async_queue_push_unlocked, vFpp) GO(g_async_queue_ref, vFp) //GO(g_async_queue_ref_unlocked, //GO(g_async_queue_sort, //GO(g_async_queue_sort_unlocked, //GO(g_async_queue_timed_pop, //GO(g_async_queue_timed_pop_unlocked, GO(g_async_queue_timeout_pop, pFpU) GO(g_async_queue_timeout_pop_unlocked, pFpU) GO(g_async_queue_try_pop, pFp) GO(g_async_queue_try_pop_unlocked, pFp) GO(g_async_queue_unlock, vFp) GO(g_async_queue_unref, vFp) GO(g_async_queue_unref_and_unlock, vFp) GO2(g_atexit, vFEp, my_atexit) //GO(g_atomic_int_add, //GO(g_atomic_int_and, //GO(g_atomic_int_compare_and_exchange, //GO(g_atomic_int_dec_and_test, //GO(g_atomic_int_exchange_and_add, //GO(g_atomic_int_get, //GO(g_atomic_int_inc, //GO(g_atomic_int_or, //GO(g_atomic_int_set, //GO(g_atomic_int_xor, //GO(g_atomic_pointer_add, //GO(g_atomic_pointer_and, //GO(g_atomic_pointer_compare_and_exchange, //GO(g_atomic_pointer_get, //GO(g_atomic_pointer_or, //GO(g_atomic_pointer_set, //GO(g_atomic_pointer_xor, GO(g_base64_decode, pFpp) GO(g_base64_decode_inplace, pFpp) GO(g_base64_decode_step, LFpLppp) GO(g_base64_encode, pFpL) GO(g_base64_encode_close, LFippp) GO(g_base64_encode_step, LFpLippp) GO(g_basename, pFp) //GO(g_bit_lock, GO(g_bit_nth_lsf, iFii) GO(g_bit_nth_msf, iFii) GO(g_bit_storage, iFi) //GO(g_bit_trylock, //GO(g_bit_unlock, //GO(g_blow_chunks, //GO(g_bookmark_file_add_application, //GO(g_bookmark_file_add_group, //GO(g_bookmark_file_error_quark, //GO(g_bookmark_file_free, //GO(g_bookmark_file_get_added, //GO(g_bookmark_file_get_app_info, //GO(g_bookmark_file_get_applications, //GO(g_bookmark_file_get_description, //GO(g_bookmark_file_get_groups, //GO(g_bookmark_file_get_icon, //GO(g_bookmark_file_get_is_private, //GO(g_bookmark_file_get_mime_type, //GO(g_bookmark_file_get_modified, //GO(g_bookmark_file_get_size, //GO(g_bookmark_file_get_title, //GO(g_bookmark_file_get_uris, //GO(g_bookmark_file_get_visited, //GO(g_bookmark_file_has_application, //GO(g_bookmark_file_has_group, //GO(g_bookmark_file_has_item, //GO(g_bookmark_file_load_from_data, //GO(g_bookmark_file_load_from_data_dirs, //GO(g_bookmark_file_load_from_file, //GO(g_bookmark_file_move_item, //GO(g_bookmark_file_new, //GO(g_bookmark_file_remove_application, //GO(g_bookmark_file_remove_group, //GO(g_bookmark_file_remove_item, //GO(g_bookmark_file_set_added, //GO(g_bookmark_file_set_app_info, //GO(g_bookmark_file_set_description, //GO(g_bookmark_file_set_groups, //GO(g_bookmark_file_set_icon, //GO(g_bookmark_file_set_is_private, //GO(g_bookmark_file_set_mime_type, //GO(g_bookmark_file_set_modified, //GO(g_bookmark_file_set_title, //GO(g_bookmark_file_set_visited, //GO(g_bookmark_file_to_data, //GO(g_bookmark_file_to_file, GOM(g_build_filename, pFEpV) GO(g_build_filenamev, pFp) GOM(g_build_path, pFEppV) // wrap using g_build_pathv GO(g_build_pathv, pFpp) GO(g_byte_array_append, pFppu) GO(g_byte_array_free, pFpi) GO(g_byte_array_free_to_bytes, pFp) GO(g_byte_array_new, pFv) GO(g_byte_array_new_take, pFpL) GO(g_byte_array_prepend, pFppu) GO(g_byte_array_ref, pFp) GO(g_byte_array_remove_index, pFpu) GO(g_byte_array_remove_index_fast, pFpu) GO(g_byte_array_remove_range, pFpuu) GO(g_byte_array_set_size, pFpu) GO(g_byte_array_sized_new, pFu) //GOM(g_byte_array_sort, vFpB) //GOM(g_byte_array_sort_with_data, vFpBp) GO(g_byte_array_unref, vFp) GO(g_bytes_compare, iFpp) GO(g_bytes_equal, iFpp) GO(g_bytes_get_data, pFpL) GO(g_bytes_get_size, LFp) GO(g_bytes_hash, uFp) GO(g_bytes_new, pFpL) GO(g_bytes_new_from_bytes, pFpLL) GO(g_bytes_new_static, pFpL) GO(g_bytes_new_take, pFpL) //GOM(g_bytes_new_with_free_func, pFppLBp) GO(g_bytes_ref, pFp) GO(g_bytes_unref, vFp) GO(g_bytes_unref_to_array, pFp) GO(g_bytes_unref_to_data, pFpp) //GO(g_cache_destroy, //GO(g_cache_insert, //GO(g_cache_key_foreach, //GO(g_cache_new, //GO(g_cache_remove, //GO(g_cache_value_foreach, GO(g_chdir, iFp) //GO(g_checksum_copy, //GO(g_checksum_free, //GO(g_checksum_get_digest, //GO(g_checksum_get_string, //GO(g_checksum_new, //GO(g_checksum_reset, //GO(g_checksum_type_get_length, //GO(g_checksum_update, GOM(g_child_watch_add, uFEipp) GOM(g_child_watch_add_full, uFEiippp) GO(g_child_watch_source_new, pFi) GO(g_chmod, iFpi) GO(g_clear_error, vFp) //GOM(g_clear_pointer, vFEpp) GO(g_close, iFip) GO(g_completion_add_items, vFpp) GO(g_completion_clear_items, vFp) GO(g_completion_complete, pFppp) GO(g_completion_complete_utf8, pFppp) GO(g_completion_free, vFp) GOM(g_completion_new, pFEp) GO(g_completion_remove_items, vFpp) GOM(g_completion_set_compare, vFEpp) //GO(g_compute_checksum_for_bytes, //GO(g_compute_checksum_for_data, //GO(g_compute_checksum_for_string, //GO(g_compute_hmac_for_data, //GO(g_compute_hmac_for_string, //GO(g_cond_broadcast, GO(g_cond_clear, vFp) GO(g_cond_free, vFp) GO(g_cond_init, vFp) GO(g_cond_new, pFv) //GO(g_cond_signal, //GO(g_cond_timed_wait, GO(g_cond_wait, vFpp) //GO(g_cond_wait_until, GO(g_convert, pFplppppp) //GO(g_convert_error_quark, GO(g_convert_with_fallback, pFplpppppp) GO(g_convert_with_iconv, pFplpppp) GO(g_creat, iFpi) GO(g_datalist_clear, vFp) //GOM(g_datalist_foreach, vFEppp) GO(g_datalist_get_data, pFpp) GO(g_datalist_get_flags, uFp) GOM(g_datalist_id_dup_data, pFEpupp) GO(g_datalist_id_get_data, pFpu) GO(g_datalist_id_remove_no_notify, pFpu) GOM(g_datalist_id_replace_data, iFEpupppp) GOM(g_datalist_id_set_data_full, vFEpupp) GO(g_datalist_init, vFp) GO(g_datalist_set_flags, vFpu) GO(g_datalist_unset_flags, vFpu) //GO(g_dataset_destroy, //GO(g_dataset_foreach, //GO(g_dataset_id_get_data, //GO(g_dataset_id_remove_no_notify, //GO(g_dataset_id_set_data_full, GO(g_date_add_days, vFpu) GO(g_date_add_months, vFpu) GO(g_date_add_years, vFpu) GO(g_date_clamp, vFppp) GO(g_date_clear, vFpu) GO(g_date_compare, iFpp) GO(g_date_days_between, iFpp) GO(g_date_free, vFp) GO(g_date_get_day, CFp) GO(g_date_get_day_of_year, uFp) GO(g_date_get_days_in_month, CFip) GO(g_date_get_iso8601_week_of_year, uFp) GO(g_date_get_julian, uFp) GO(g_date_get_monday_week_of_year, uFp) GO(g_date_get_monday_weeks_in_year, CFp) GO(g_date_get_month, iFp) GO(g_date_get_sunday_week_of_year, uFp) GO(g_date_get_sunday_weeks_in_year, CFp) GO(g_date_get_weekday, iFp) GO(g_date_get_year, WFp) GO(g_date_is_first_of_month, iFp) GO(g_date_is_last_of_month, iFp) GO(g_date_is_leap_year, iFp) GO(g_date_new, pFv) GO(g_date_new_dmy, pFCiW) GO(g_date_new_julian, pFu) GO(g_date_order, vFpp) GO(g_date_set_day, vFpC) GO(g_date_set_dmy, vFpCiW) GO(g_date_set_julian, vFpu) GO(g_date_set_month, vFpi) GO(g_date_set_parse, vFpp) GO(g_date_set_time, vFpi) //GO(g_date_set_time_t, GO(g_date_set_time_val, vFpp) GO(g_date_set_year, vFpW) GO(g_date_strftime, LFpLpp) GO(g_date_subtract_days, vFpu) GO(g_date_subtract_months, vFpu) GO(g_date_subtract_years, vFpu) //GO(g_date_time_add, //GO(g_date_time_add_days, //GO(g_date_time_add_full, //GO(g_date_time_add_hours, //GO(g_date_time_add_minutes, //GO(g_date_time_add_months, //GO(g_date_time_add_seconds, //GO(g_date_time_add_weeks, //GO(g_date_time_add_years, //GO(g_date_time_compare, //GO(g_date_time_difference, //GO(g_date_time_equal, //GO(g_date_time_format, //GO(g_date_time_get_day_of_month, //GO(g_date_time_get_day_of_week, //GO(g_date_time_get_day_of_year, //GO(g_date_time_get_hour, //GO(g_date_time_get_microsecond, //GO(g_date_time_get_minute, //GO(g_date_time_get_month, //GO(g_date_time_get_second, //GO(g_date_time_get_seconds, //GO(g_date_time_get_timezone_abbreviation, //GO(g_date_time_get_utc_offset, //GO(g_date_time_get_week_numbering_year, //GO(g_date_time_get_week_of_year, //GO(g_date_time_get_year, //GO(g_date_time_get_ymd, //GO(g_date_time_hash, //GO(g_date_time_is_daylight_savings, //GO(g_date_time_new, //GO(g_date_time_new_from_timeval_local, //GO(g_date_time_new_from_timeval_utc, //GO(g_date_time_new_from_unix_local, //GO(g_date_time_new_from_unix_utc, //GO(g_date_time_new_local, //GO(g_date_time_new_now, //GO(g_date_time_new_now_local, //GO(g_date_time_new_now_utc, //GO(g_date_time_new_utc, //GO(g_date_time_ref, //GO(g_date_time_to_local, //GO(g_date_time_to_timeval, //GO(g_date_time_to_timezone, //GO(g_date_time_to_unix, //GO(g_date_time_to_utc, //GO(g_date_time_unref, GO(g_date_to_struct_tm, vFpp) GO(g_date_valid, iFp) GO(g_date_valid_day, iFC) GO(g_date_valid_dmy, iFCiW) GO(g_date_valid_julian, iFu) GO(g_date_valid_month, iFi) GO(g_date_valid_weekday, iFi) GO(g_date_valid_year, iFW) GO(g_dcgettext, pFppi) GO(g_dgettext, pFpp) GO(g_dir_close, vFp) GO(g_direct_equal, iFpp) GO(g_direct_hash, uFp) GO(g_dir_make_tmp, pFpp) GO(g_dir_open, pFp) GO(g_dir_read_name, pFp) GO(g_dir_rewind, vFp) GO(g_dngettext, pFpppL) GO(g_double_equal, iFpp) GO(g_double_hash, uFp) GO(g_dpgettext, pFppL) GO(g_dpgettext2, pFppp) GO(g_environ_getenv, pFpp) // should wrap? GO(g_environ_setenv, pFpppi) GO(g_environ_unsetenv, pFpp) GO(g_error_copy, pFp) GO(g_error_free, vFp) GO(g_error_matches, iFppi) GO2(g_error_new, pFpipV, g_error_new_valist) GO(g_error_new_literal, pFpip) GO(g_error_new_valist, pFpipp) GO(g_file_error_from_errno, iFi) GO(g_file_error_quark, pFv) GO(g_file_get_contents, iFpppp) GO(g_filename_display_basename, pFp) GO(g_filename_display_name, pFp) GO(g_filename_from_uri, pFppp) GO(g_filename_from_utf8, pFpippp) GO(g_filename_to_uri, pFppp) GO(g_filename_to_utf8, pFpippp) GO(g_file_open_tmp, iFppp) GO(g_file_read_link, pFpp) GO(g_file_set_contents, iFppip) GO(g_file_test, iFpi) GO(g_find_program_in_path, pFp) // need wrap? GO(g_fopen, pFpp) GO(g_format_size, pFU) GO(g_format_size_for_display, pFI) GO(g_format_size_full, pFUi) GO2(g_fprintf, iFEppV, my_g_vfprintf) GO(g_free, vFp) GO(g_freopen, pFppp) GO(g_get_application_name, pFv) GO(g_get_charset, iFp) GO(g_get_codeset, pFv) GO(g_get_current_dir, pFv) GO(g_get_current_time, vFp) GO(g_getenv, pFp) // should wrap? GO(g_get_environ, pFv) GO(g_get_filename_charsets, iFp) GO(g_get_home_dir, pFv) GO(g_get_host_name, pFv) GO(g_get_language_names, pFv) GO(g_get_locale_variants, pFp) GO(g_get_monotonic_time, IFv) //GO(g_get_num_processors, GO(g_get_prgname, pFv) GO(g_get_real_name, pFv) GO(g_get_real_time, IFv) GO(g_get_system_config_dirs, pFv) GO(g_get_system_data_dirs, pFv) GO(g_get_tmp_dir, pFv) GO(g_get_user_cache_dir, pFv) GO(g_get_user_config_dir, pFv) GO(g_get_user_data_dir, pFv) GO(g_get_user_name, pFv) GO(g_get_user_runtime_dir, pFv) GO(g_get_user_special_dir, pFi) GO(g_hash_table_add, iFpp) GO(g_hash_table_contains, iFpp) GO(g_hash_table_destroy, vFp) GOM(g_hash_table_find, pFEppp) GOM(g_hash_table_foreach, vFEppp) GOM(g_hash_table_foreach_remove, uFEppp) GOM(g_hash_table_foreach_steal, uFEppp) GO(g_hash_table_get_keys, pFp) GO(g_hash_table_get_keys_as_array, pFpp) GO(g_hash_table_get_values, pFp) GO(g_hash_table_insert, iFppp) GO(g_hash_table_iter_get_hash_table, pFp) GO(g_hash_table_iter_init, vFpp) GO(g_hash_table_iter_next, iFppp) GO(g_hash_table_iter_remove, vFp) GO(g_hash_table_iter_replace, vFpp) GO(g_hash_table_iter_steal, vFp) GO(g_hash_table_lookup, pFpp) GO(g_hash_table_lookup_extended, iFpppp) GOM(g_hash_table_new, pFEpp) GOM(g_hash_table_new_full, pFEpppp) GO(g_hash_table_ref, pFp) GO(g_hash_table_remove, iFpp) GO(g_hash_table_remove_all, vFp) GO(g_hash_table_replace, iFppp) GO(g_hash_table_size, uFp) GO(g_hash_table_steal, iFpp) GO(g_hash_table_steal_all, vFp) GO(g_hash_table_unref, vFp) //GO(g_hmac_copy, //GO(g_hmac_get_digest, //GO(g_hmac_get_string, //GO(g_hmac_new, //GO(g_hmac_ref, //GO(g_hmac_unref, //GO(g_hmac_update, //GO(g_hook_alloc, //GO(g_hook_compare_ids, //GO(g_hook_destroy, //GO(g_hook_destroy_link, //GO(g_hook_find, //GO(g_hook_find_data, //GO(g_hook_find_func, //GO(g_hook_find_func_data, //GO(g_hook_first_valid, //GO(g_hook_free, //GO(g_hook_get, //GO(g_hook_insert_before, //GO(g_hook_insert_sorted, //GO(g_hook_list_clear, //GO(g_hook_list_init, //GO(g_hook_list_invoke, //GO(g_hook_list_invoke_check, //GO(g_hook_list_marshal, //GO(g_hook_list_marshal_check, //GO(g_hook_next_valid, //GO(g_hook_prepend, //GO(g_hook_ref, //GO(g_hook_unref, //GO(g_hostname_is_ascii_encoded, //GO(g_hostname_is_ip_address, //GO(g_hostname_is_non_ascii, //GO(g_hostname_to_ascii, //GO(g_hostname_to_unicode, GO(g_iconv, LFppppp) GO(g_iconv_close, iFp) GO(g_iconv_open, pFpp) GOM(g_idle_add, uFEpp) GOM(g_idle_add_full, uFEippp) GO(g_idle_remove_by_data, iFp) GO(g_idle_source_new, pFv) GO(g_int64_equal, iFpp) GO(g_int64_hash, uFp) GO(g_int_equal, iFpp) GO(g_intern_static_string, pFp) GO(g_intern_string, pFp) GO(g_int_hash, uFp) GOM(g_io_add_watch, uFEpipp) GOM(g_io_add_watch_full, uFEpiippp) GO(g_io_channel_close, vFp) GO(g_io_channel_error_from_errno, iFi) GO(g_io_channel_error_quark, pFv) GO(g_io_channel_flush, iFpp) GO(g_io_channel_get_buffer_condition, iFp) GO(g_io_channel_get_buffered, iFp) GO(g_io_channel_get_buffer_size, iFp) GO(g_io_channel_get_close_on_unref, iFp) GO(g_io_channel_get_encoding, pFp) GO(g_io_channel_get_flags, iFp) GO(g_io_channel_get_line_term, pFpp) GO(g_io_channel_init, vFp) GO(g_io_channel_new_file, pFppp) GO(g_io_channel_read, iFppLp) GO(g_io_channel_read_chars, iFpplpp) GO(g_io_channel_read_line, iFppppp) GO(g_io_channel_read_line_string, iFpppp) GO(g_io_channel_read_to_end, iFpppp) GO(g_io_channel_read_unichar, iFppp) GO(g_io_channel_ref, pFp) GO(g_io_channel_seek, iFpIi) GO(g_io_channel_seek_position, iFpIip) GO(g_io_channel_set_buffered, vFpi) GO(g_io_channel_set_buffer_size, vFpL) GO(g_io_channel_set_close_on_unref, vFpi) GO(g_io_channel_set_encoding, iFppp) GO(g_io_channel_set_flags, iFpip) GO(g_io_channel_set_line_term, vFppi) GO(g_io_channel_shutdown, iFpip) GO(g_io_channel_unix_get_fd, iFp) GO(g_io_channel_unix_new, pFi) GO(g_io_channel_unref, vFp) GO(g_io_channel_write, iFppLp) GO(g_io_channel_write_chars, iFpplpp) GO(g_io_channel_write_unichar, iFpup) GO(g_io_create_watch, pFpp) GO(g_key_file_error_quark, pFv) GO(g_key_file_free, vFp) GO(g_key_file_get_boolean, iFpppp) GO(g_key_file_get_boolean_list, pFppppp) GO(g_key_file_get_comment, pFpppp) GO(g_key_file_get_double, dFpppp) GO(g_key_file_get_double_list, pFppppp) GO(g_key_file_get_groups, pFpp) GO(g_key_file_get_int64, IFpppp) GO(g_key_file_get_integer, iFpppp) GO(g_key_file_get_integer_list, pFppppp) GO(g_key_file_get_keys, pFpppp) GO(g_key_file_get_locale_string, pFppppp) GO(g_key_file_get_locale_string_list, pFpppppp) GO(g_key_file_get_start_group, pFp) GO(g_key_file_get_string, pFpppp) GO(g_key_file_get_string_list, pFppppp) GO(g_key_file_get_uint64, UFpppp) GO(g_key_file_get_value, pFpppp) GO(g_key_file_has_group, iFpp) GO(g_key_file_has_key, iFpppp) GO(g_key_file_load_from_data, iFppLip) GO(g_key_file_load_from_data_dirs, iFpppip) GO(g_key_file_load_from_dirs, iFppppip) GO(g_key_file_load_from_file, iFppip) GO(g_key_file_new, pFv) GO(g_key_file_ref, pFp) GO(g_key_file_remove_comment, iFpppp) GO(g_key_file_remove_group, iFppp) GO(g_key_file_remove_key, iFpppp) GO(g_key_file_save_to_file, iFppp) GO(g_key_file_set_boolean, vFpppi) GO(g_key_file_set_boolean_list, vFppppL) GO(g_key_file_set_comment, iFppppp) GO(g_key_file_set_double, vFpppd) GO(g_key_file_set_double_list, vFppppL) GO(g_key_file_set_int64, vFpppI) GO(g_key_file_set_integer, vFpppi) GO(g_key_file_set_integer_list, vFppppL) GO(g_key_file_set_list_separator, vFpC) GO(g_key_file_set_locale_string, vFppppp) GO(g_key_file_set_locale_string_list, vFpppppL) GO(g_key_file_set_string, vFpppp) GO(g_key_file_set_string_list, vFppppL) GO(g_key_file_set_uint64, vFpppU) GO(g_key_file_set_value, vFpppp) GO(g_key_file_to_data, pFppp) GO(g_key_file_unref, vFp) GO(glib_check_version, pFuuu) //GO(glib_gettext, //GO(glib_pgettext, //GO(glib__private__, GO(g_list_alloc, pFv) GO(g_list_append, pFpp) GO(g_list_concat, pFpp) GO(g_list_copy, pFp) //GOM(g_list_copy_deep, pFEpBp) GO(g_list_delete_link, pFpp) GO(g_listenv, pFv) GO(g_list_find, pFpp) GOM(g_list_find_custom, pFEppp) GO(g_list_first, pFp) GOM(g_list_foreach, vFEppp) GO(g_list_free, vFp) GO(g_list_free_1, vFp) GOM(g_list_free_full, vFEpp) GO(g_list_index, iFpp) GO(g_list_insert, pFppi) GO(g_list_insert_before, pFppp) //GOM(g_list_insert_sorted, pFEppB) //GO(g_list_insert_sorted_with_data, pFEppBp) GO(g_list_last, pFp) GO(g_list_length, uFp) GO(g_list_nth, pFpu) GO(g_list_nth_data, pFpu) GO(g_list_nth_prev, pFpu) //GO(g_list_pop_allocator, GO(g_list_position, iFpp) GO(g_list_prepend, pFpp) //GO(g_list_push_allocator, GO(g_list_remove, pFpp) GO(g_list_remove_all, pFpp) GO(g_list_remove_link, pFpp) GO(g_list_reverse, pFp) GOM(g_list_sort, pFEpp) GOM(g_list_sort_with_data, pFEppp) GO(g_locale_from_utf8, pFplppp) GO(g_locale_to_utf8, pFplppp) GO2(g_log, vFpppV, g_logv) GO(g_log_default_handler, vFpipp) GO(g_log_remove_handler, vFpu) GO(g_log_set_always_fatal, iFi) GOM(g_log_set_default_handler, pFEpp) GO(g_log_set_fatal_mask, iFpi) GOM(g_log_set_handler, uFEpipp) GO(g_logv, vFpppp) // need align? GO(g_lstat, iFpp) GO(g_main_context_acquire, iFp) GO(g_main_context_add_poll, vFppi) GO(g_main_context_check, iFpipi) GO(g_main_context_default, pFv) GO(g_main_context_dispatch, vFp) //GOM(g_main_context_find_source_by_funcs_user_data, pFEppp) // 2nd is a GSourceFuncs structures with callbacks.. GO(g_main_context_find_source_by_id, pFpu) GO(g_main_context_find_source_by_user_data, pFpp) GOM(g_main_context_get_poll_func, pFEp) GO(g_main_context_get_thread_default, pFv) //GOM(g_main_context_invoke, vFppp) // 2nd is GSourceFuncs //GOM(g_main_context_invoke_full, vFpippB) // 3rd is GSourceFuncs GO(g_main_context_is_owner, iFp) GO(g_main_context_iteration, iFpi) GO(g_main_context_new, pFv) GO(g_main_context_pending, iFp) GO(g_main_context_pop_thread_default, vFp) GO(g_main_context_prepare, iFpp) GO(g_main_context_push_thread_default, vFp) GO(g_main_context_query, iFpippi) GO(g_main_context_ref, pFp) GO(g_main_context_ref_thread_default, pFv) GO(g_main_context_release, vFp) GO(g_main_context_remove_poll, vFpp) GOM(g_main_context_set_poll_func, vFEpp) GO(g_main_context_unref, vFp) GO(g_main_context_wait, iFppp) GO(g_main_context_wakeup, vFp) GO(g_main_current_source, pFv) GO(g_main_depth, iFv) GO(g_main_loop_get_context, pFp) GO(g_main_loop_is_running, iFp) GO(g_main_loop_new, pFpi) GO(g_main_loop_quit, vFp) GO(g_main_loop_ref, pFp) GO(g_main_loop_run, vFp) GO(g_main_loop_unref, vFp) GO(g_malloc, pFL) GO(g_malloc0, pFL) GO(g_malloc0_n, pFLL) GO(g_malloc_n, pFLL) GO(g_mapped_file_free, vFp) GO(g_mapped_file_get_bytes, pFp) GO(g_mapped_file_get_contents, pFp) GO(g_mapped_file_get_length, uFp) GO(g_mapped_file_new, pFppp) GO(g_mapped_file_new_from_fd, pFiip) GO(g_mapped_file_ref, pFp) GO(g_mapped_file_unref, vFp) //GO(g_markup_collect_attributes, //GO(g_markup_error_quark, GO(g_markup_escape_text, pFpl) //GO(g_markup_parse_context_end_parse, //GO(g_markup_parse_context_free, //GO(g_markup_parse_context_get_element, //GO(g_markup_parse_context_get_element_stack, //GO(g_markup_parse_context_get_position, //GO(g_markup_parse_context_get_user_data, //GO(g_markup_parse_context_new, //GO(g_markup_parse_context_parse, //GO(g_markup_parse_context_pop, //GO(g_markup_parse_context_push, //GO(g_markup_parse_context_ref, //GO(g_markup_parse_context_unref, GOM(g_markup_printf_escaped, pFEpV) GOM(g_markup_vprintf_escaped, pFEpp) GO(g_match_info_expand_references, pFppp) GO(g_match_info_fetch, pFpi) GO(g_match_info_fetch_all, pFp) GO(g_match_info_fetch_named, pFpp) GO(g_match_info_fetch_named_pos, iFpppp) GO(g_match_info_fetch_pos, iFpipp) GO(g_match_info_free, vFp) GO(g_match_info_get_match_count, iFp) GO(g_match_info_get_regex, pFp) GO(g_match_info_get_string, pFp) GO(g_match_info_is_partial_match, iFp) GO(g_match_info_matches, iFp) GO(g_match_info_next, iFpp) GO(g_match_info_ref, pFp) GO(g_match_info_unref, vFp) //GO(g_mem_chunk_alloc, //GO(g_mem_chunk_alloc0, //GO(g_mem_chunk_clean, //GO(g_mem_chunk_destroy, //GO(g_mem_chunk_free, //GO(g_mem_chunk_info, //GO(g_mem_chunk_new, //GO(g_mem_chunk_print, //GO(g_mem_chunk_reset, GO(g_memdup, pFpu) GO(g_mem_is_system_malloc, iFv) GO(g_mem_profile, vFv) //GOM(g_mem_set_vtable, vFEp) // VMemTable needs wrapping GO(g_mkdir, iFpi) GO(g_mkdir_with_parents, iFpi) GO(g_mkdtemp, pFp) GO(g_mkdtemp_full, pFpi) GO(g_mkstemp, iFp) GO(g_mkstemp_full, iFpii) GO(g_mutex_clear, vFp) GO(g_mutex_free, vFp) GO(g_mutex_init, vFp) GO(g_mutex_lock, vFp) GO(g_mutex_new, pFv) GO(g_mutex_trylock, iFp) GO(g_mutex_unlock, vFp) //GO(g_node_child_index, //GO(g_node_child_position, //GO(g_node_children_foreach, //GO(g_node_copy, //GO(g_node_copy_deep, //GO(g_node_depth, //GO(g_node_destroy, //GO(g_node_find, //GO(g_node_find_child, //GO(g_node_first_sibling, //GO(g_node_get_root, //GO(g_node_insert, //GO(g_node_insert_after, //GO(g_node_insert_before, //GO(g_node_is_ancestor, //GO(g_node_last_child, //GO(g_node_last_sibling, //GO(g_node_max_height, //GO(g_node_n_children, //GO(g_node_new, //GO(g_node_n_nodes, //GO(g_node_nth_child, //GO(g_node_pop_allocator, //GO(g_node_prepend, //GO(g_node_push_allocator, //GO(g_node_reverse_children, //GO(g_node_traverse, //GO(g_node_unlink, GO(g_nullify_pointer, vFp) //GO(g_once_impl, GO(g_once_init_enter, iFp) //GO(g_once_init_enter_impl, GO(g_once_init_leave, vFpL) GO(g_on_error_query, vFp) GO(g_on_error_stack_trace, vFp) GO(g_open, iFpii) GO(g_option_context_add_group, vFpp) GOM(g_option_context_add_main_entries, vFEppp) GO(g_option_context_free, vFp) GO(g_option_context_get_description, pFp) GO(g_option_context_get_help, pFpip) GO(g_option_context_get_help_enabled, iFp) GO(g_option_context_get_ignore_unknown_options, iFp) GO(g_option_context_get_main_group, pFp) GO(g_option_context_get_strict_posix, iFp) // 2.44+ GO(g_option_context_get_summary, pFp) GO(g_option_context_new, pFp) GO(g_option_context_parse, iFpppp) GO(g_option_context_parse_strv, iFppp) GO(g_option_context_set_description, vFpp) GO(g_option_context_set_help_enabled, vFpi) GO(g_option_context_set_ignore_unknown_options, vFpi) GO(g_option_context_set_main_group, vFpp) GO(g_option_context_set_strict_posix, vFpi) // 2.44+ GO(g_option_context_set_summary, vFpp) //GOM(g_option_context_set_translate_func, vFEpBpB) GO(g_option_context_set_translation_domain, vFpp) //GO(g_option_error_quark, GO(g_option_group_add_entries, vFpp) GO(g_option_group_free, vFp) //GOM(g_option_group_new, pFEppppB) GO(g_option_group_ref, pFp) // 2.44+ //GOM(g_option_group_set_error_hook, vFEpB) //GOM(g_option_group_set_parse_hooks, vFEpBB) //GOM(g_option_group_set_translate_func, vFEpBpB) GO(g_option_group_set_translation_domain, vFpp) GO(g_option_group_unref, vFp) // 2.44+ GO(g_parse_debug_string, uFppi) GO(g_path_get_basename, pFp) GO(g_path_get_dirname, pFp) GO(g_path_is_absolute, iFp) GO(g_path_skip_root, pFp) GO(g_pattern_match, iFpupp) GO(g_pattern_match_simple, iFpp) GO(g_pattern_match_string, iFpp) GO(g_pattern_spec_equal, iFpp) GO(g_pattern_spec_free, vFp) GO(g_pattern_spec_new, pFp) //GO(g_pointer_bit_lock, //GO(g_pointer_bit_trylock, //GO(g_pointer_bit_unlock, GO(g_poll, iFpui) GO(g_prefix_error, vFpppppppppp) //vaarg, should align? GOM(g_print, vFEpV) GOM(g_printerr, vFEpV) GO2(g_printf, iFEpV, my_g_vprintf) GOM(g_printf_string_upper_bound, uFEpp) GO(g_private_get, pFp) GOM(g_private_new, pFEp) GO(g_private_replace, vFpp) GO(g_private_set, vFpp) GO(g_propagate_error, vFpp) GO(g_propagate_prefixed_error, vFpppppppppppp) //vaarg, should align? GO(g_ptr_array_add, vFpp) GOM(g_ptr_array_foreach, vFEppp) GO(g_ptr_array_free, pFpi) GO(g_ptr_array_insert, vFpip) GO(g_ptr_array_new, pFv) GOM(g_ptr_array_new_full, pFEup) GOM(g_ptr_array_new_with_free_func, pFEp) GO(g_ptr_array_ref, pFp) GO(g_ptr_array_remove, vFpp) GO(g_ptr_array_remove_fast, iFpp) GO(g_ptr_array_remove_index, pFpu) GO(g_ptr_array_remove_index_fast, pFpu) GO(g_ptr_array_remove_range, pFpuu) GOM(g_ptr_array_set_free_func, vFEpp) GO(g_ptr_array_set_size, vFpi) GO(g_ptr_array_sized_new, pFu) GOM(g_ptr_array_sort, vFEpp) GOM(g_ptr_array_sort_with_data, vFEppp) GO(g_ptr_array_unref, vFp) GOM(g_qsort_with_data, vFEpiLpp) GO(g_quark_from_static_string, uFp) GO(g_quark_from_string, uFp) GO(g_quark_to_string, pFu) GO(g_quark_try_string, uFp) GO(g_queue_clear, vFp) //GOM(g_queue_clear_full, vFEpB) // 2.60+ GO(g_queue_copy, pFp) GO(g_queue_delete_link, vFpp) GO(g_queue_find, pFpp) GOM(g_queue_find_custom, pFEppp) //GOM(g_queue_foreach, vFEpBp) GO(g_queue_free, vFp) //GOM(g_queue_free_full, vFEpB) GO(g_queue_get_length, uFp) GO(g_queue_index, iFpp) GO(g_queue_init, vFp) GO(g_queue_insert_after, vFppp) GO(g_queue_insert_after_link, vFppp) // 2.62+ GO(g_queue_insert_before, vFppp) GO(g_queue_insert_before_link, vFppp) // 2.62+ //GOM(g_queue_insert_sorted, vFEppBp) GO(g_queue_is_empty, iFp) GO(g_queue_link_index, iFpp) GO(g_queue_new, pFv) GO(g_queue_peek_head, pFp) GO(g_queue_peek_head_link, pFp) GO(g_queue_peek_nth, pFpu) GO(g_queue_peek_nth_link, pFpu) GO(g_queue_peek_tail, pFp) GO(g_queue_peek_tail_link, pFp) GO(g_queue_pop_head, pFp) GO(g_queue_pop_head_link, pFp) GO(g_queue_pop_nth, pFpu) GO(g_queue_pop_nth_link, pFpu) GO(g_queue_pop_tail, pFp) GO(g_queue_pop_tail_link, pFp) GO(g_queue_push_head, vFpp) GO(g_queue_push_head_link, vFpp) GO(g_queue_push_nth, vFppi) GO(g_queue_push_nth_link, vFpip) GO(g_queue_push_tail, vFpp) GO(g_queue_push_tail_link, vFpp) GO(g_queue_remove, iFpp) GO(g_queue_remove_all, iFpp) GO(g_queue_reverse, pFp) //GOM(g_queue_sort, vFEpBp) GO(g_queue_unlink, vFpp) GO(g_rand_copy, pFp) GO(g_rand_double, dFv) GO(g_rand_double_range, dFdd) GO(g_rand_free, vFp) GO(g_rand_int, uFp) GO(g_rand_int_range, uFpuu) GO(g_rand_new, pFv) GO(g_rand_new_with_seed, pFu) GO(g_rand_new_with_seed_array, pFpu) GO(g_random_double, dFp) GO(g_random_double_range, dFpdd) GO(g_random_int, iFii) GO(g_random_int_range, iFii) GO(g_random_set_seed, vFu) GO(g_rand_set_seed, vFpu) GO(g_rand_set_seed_array, vFppu) GO(g_realloc, pFpL) GO(g_realloc_n, pFpLL) //GO(g_rec_mutex_clear, //GO(g_rec_mutex_init, //GO(g_rec_mutex_lock, //GO(g_rec_mutex_trylock, //GO(g_rec_mutex_unlock, GO(g_regex_check_replacement, iFppp) //GO(g_regex_error_quark, GO(g_regex_escape_nul, pFpi) GO(g_regex_escape_string, pFpi) GO(g_regex_get_capture_count, iFp) GO(g_regex_get_compile_flags, iFp) GO(g_regex_get_has_cr_or_lf, iFp) GO(g_regex_get_match_flags, iFp) GO(g_regex_get_max_backref, iFp) GO(g_regex_get_max_lookbehind, iFp) GO(g_regex_get_pattern, pFp) GO(g_regex_get_string_number, iFpp) GO(g_regex_match, iFppip) GO(g_regex_match_all, iFppip) GO(g_regex_match_all_full, iFppLiipp) GO(g_regex_match_full, iFppLiipp) GO(g_regex_match_simple, iFppii) GO(g_regex_new, pFpiip) GO(g_regex_ref, pFp) GO(g_regex_replace, pFppLipip) //GOM(g_regex_replace_eval, pFEppLiiBpp) GO(g_regex_replace_literal, pFppLipip) GO(g_regex_split, pFppi) GO(g_regex_split_full, pFppLiiip) GO(g_regex_split_simple, pFppii) GO(g_regex_unref, vFp) //GO(g_relation_count, //GO(g_relation_delete, //GO(g_relation_destroy, //GO(g_relation_exists, //GO(g_relation_index, //GO(g_relation_insert, //GO(g_relation_new, //GO(g_relation_print, //GO(g_relation_select, //GO(g_reload_user_special_dirs_cache, GO(g_remove, iFp) GO(g_rename, iFpp) GO(g_return_if_fail_warning, vFppp) GO(g_rmdir, iFp) //GO(g_rw_lock_clear, //GO(g_rw_lock_init, //GO(g_rw_lock_reader_lock, //GO(g_rw_lock_reader_trylock, //GO(g_rw_lock_reader_unlock, //GO(g_rw_lock_writer_lock, //GO(g_rw_lock_writer_trylock, //GO(g_rw_lock_writer_unlock, //GO(g_scanner_cur_line, //GO(g_scanner_cur_position, //GO(g_scanner_cur_token, //GO(g_scanner_cur_value, //GO(g_scanner_destroy, //GO(g_scanner_eof, //GO(g_scanner_error, //GO(g_scanner_get_next_token, //GO(g_scanner_input_file, //GO(g_scanner_input_text, //GO(g_scanner_lookup_symbol, //GO(g_scanner_new, //GO(g_scanner_peek_next_token, //GO(g_scanner_scope_add_symbol, //GO(g_scanner_scope_foreach_symbol, //GO(g_scanner_scope_lookup_symbol, //GO(g_scanner_scope_remove_symbol, //GO(g_scanner_set_scope, //GO(g_scanner_sync_file_offset, //GO(g_scanner_unexp_token, //GO(g_scanner_warn, //GO(g_sequence_append, //GO(g_sequence_foreach, //GO(g_sequence_foreach_range, //GO(g_sequence_free, //GO(g_sequence_get, //GO(g_sequence_get_begin_iter, //GO(g_sequence_get_end_iter, //GO(g_sequence_get_iter_at_pos, //GO(g_sequence_get_length, //GO(g_sequence_insert_before, //GO(g_sequence_insert_sorted, //GO(g_sequence_insert_sorted_iter, //GO(g_sequence_iter_compare, //GO(g_sequence_iter_get_position, //GO(g_sequence_iter_get_sequence, //GO(g_sequence_iter_is_begin, //GO(g_sequence_iter_is_end, //GO(g_sequence_iter_move, //GO(g_sequence_iter_next, //GO(g_sequence_iter_prev, //GO(g_sequence_lookup, //GO(g_sequence_lookup_iter, //GO(g_sequence_move, //GO(g_sequence_move_range, //GO(g_sequence_new, //GO(g_sequence_prepend, //GO(g_sequence_range_get_midpoint, //GO(g_sequence_remove, //GO(g_sequence_remove_range, //GO(g_sequence_search, //GO(g_sequence_search_iter, //GO(g_sequence_set, //GO(g_sequence_sort, //GO(g_sequence_sort_changed, //GO(g_sequence_sort_changed_iter, //GO(g_sequence_sort_iter, //GO(g_sequence_swap, GO(g_set_application_name, vFp) GO(g_setenv, iFppi) GOM(g_set_error, vFEppipV) GO(g_set_error_literal, vFppip) GO(g_set_prgname, vFp) GOM(g_set_printerr_handler, pFEp) GOM(g_set_print_handler, pFEp) //GO(g_shell_error_quark, GO(g_shell_parse_argv, iFpppp) GO(g_shell_quote, pFp) GO(g_shell_unquote, pFpp) GO(g_slice_alloc, pFL) GO(g_slice_alloc0, pFL) GO(g_slice_copy, pFLp) GO(g_slice_free1, vFLp) GO(g_slice_free_chain_with_offset, vFLpL) GO(g_slice_get_config, IFi) GO(g_slice_get_config_state, pFiIp) GO(g_slice_set_config, vFiI) GO(g_slist_alloc, pFv) GO(g_slist_append, pFpp) GO(g_slist_concat, pFpp) GO(g_slist_copy, pFp) //GOM(g_slist_copy_deep, pFEppp) GO(g_slist_delete_link, pFpp) GO(g_slist_find, pFpp) GOM(g_slist_find_custom, pFEppp) GOM(g_slist_foreach, pFEppp) GO(g_slist_free, vFp) GO(g_slist_free_1, vFp) //GOM(g_slist_free_full, vFEpp) GO(g_slist_index, iFpp) GO(g_slist_insert, pFppi) GO(g_slist_insert_before, pFppp) GOM(g_slist_insert_sorted, pFEppp) GOM(g_slist_insert_sorted_with_data, pFEpppp) GO(g_slist_last, pFp) GO(g_slist_length, uFp) GO(g_slist_nth, pFpu) GO(g_slist_nth_data, pFpu) //GO(g_slist_pop_allocator, GO(g_slist_position, iFpp) GO(g_slist_prepend, pFpp) //GO(g_slist_push_allocator, GO(g_slist_remove, pFpp) GO(g_slist_remove_all, pFpp) GO(g_slist_remove_link, pFpp) GO(g_slist_reverse, pFp) GOM(g_slist_sort, pFEpp) GOM(g_slist_sort_with_data, pFEppp) GO2(g_snprintf, iFEpLpV, my_g_vsnprintf) GO(g_source_add_child_source, vFpp) GO(g_source_add_poll, vFpp) GO(g_source_add_unix_fd, pFpii) GO(g_source_attach, uFpp) GO(g_source_destroy, vFp) GO(g_source_get_can_recurse, iFp) GO(g_source_get_context, pFp) GO(g_source_get_current_time, vFpp) GO(g_source_get_id, uFp) GO(g_source_get_name, pFp) GO(g_source_get_priority, iFp) GO(g_source_get_ready_time, IFp) GO(g_source_get_time, IFp) GO(g_source_is_destroyed, iFp) GO(g_source_modify_unix_fd, vFppi) GOM(g_source_new, pFEpu) GO(g_source_query_unix_fd, iFpp) GO(g_source_ref, pFp) GO(g_source_remove, iFu) GOM(g_source_remove_by_funcs_user_data, iFEpp) GO(g_source_remove_by_user_data, iFp) GO(g_source_remove_child_source, vFpp) GO(g_source_remove_poll, vFpp) GO(g_source_remove_unix_fd, vFpp) GOM(g_source_set_callback, vFEpppp) //GOM(g_source_set_callback_indirect, vFEppB) GO(g_source_set_can_recurse, vFpi) GOM(g_source_set_funcs, vFEpp) GO(g_source_set_name, vFpp) GO(g_source_set_name_by_id, vFup) GO(g_source_set_priority, vFpi) GO(g_source_set_ready_time, vFpI) GO(g_source_unref, vFp) GO(g_spaced_primes_closest, uFu) GOM(g_spawn_async, iFEpppipppp) GOM(g_spawn_async_with_pipes, iFEpppippppppp) GO(g_spawn_check_exit_status, iFip) GO(g_spawn_close_pid, vFp) GO(g_spawn_command_line_async, iFpp) GO(g_spawn_command_line_sync, iFppppp) GO(g_spawn_error_quark, pFv) GO(g_spawn_exit_error_quark, pFv) GOM(g_spawn_sync, iFEpppipppppp) GO2(g_sprintf, iFEppV, my_g_vsprintf) GO(g_stat, iFpp) GO(g_static_mutex_free, vFp) GO(g_static_mutex_get_mutex_impl, pFp) GO(g_static_mutex_init, vFp) GO(g_static_private_free, vFp) GO(g_static_private_get, pFp) GO(g_static_private_init, vFp) GOM(g_static_private_set, vFEppp) GO(g_static_rec_mutex_free, vFp) GO(g_static_rec_mutex_init, vFp) GO(g_static_rec_mutex_lock, vFp) GO(g_static_rec_mutex_lock_full, vFpu) GO(g_static_rec_mutex_trylock, iFp) GO(g_static_rec_mutex_unlock, vFp) GO(g_static_rec_mutex_unlock_full, uFp) GO(g_static_rw_lock_free, vFp) GO(g_static_rw_lock_init, vFp) GO(g_static_rw_lock_reader_lock, vFp) GO(g_static_rw_lock_reader_trylock, iFp) GO(g_static_rw_lock_reader_unlock, vFp) GO(g_static_rw_lock_writer_lock, vFp) GO(g_static_rw_lock_writer_trylock, iFp) GO(g_static_rw_lock_writer_unlock, vFp) GO(g_stpcpy, pFpp) GO(g_strcanon, pFppC) GO(g_strcasecmp, iFpp) GO(g_strchomp, pFp) GO(g_strchug, pFp) GO(g_strcmp0, iFpp) GO(g_strcompress, pFp) GO(g_strconcat, pFppppppppppppp) //vaarg, no va_list equivalent... GO(g_strdelimit, pFppC) GO(g_strdown, pFp) GO(g_strdup, pFp) GO2(g_strdup_printf, pFEpV, my_g_strdup_vprintf) GO(g_strdupv, pFp) GOM(g_strdup_vprintf, pFEpp) GO(g_str_equal, iFpp) GO(g_strerror, pFi) GO(g_strescape, pFpp) GO(g_strfreev, vFp) GO(g_str_hash, uFp) GO(g_str_has_prefix, iFpp) GO(g_str_has_suffix, iFpp) GO(g_string_append, pFpp) GO(g_string_append_c, pFpC) GO(g_string_append_len, pFppl) GO2(g_string_append_printf, vFppV, g_string_append_vprintf) // need align? GO(g_string_append_unichar, pFpu) GO(g_string_append_uri_escaped, pFpppi) GO(g_string_append_vprintf, vFppp) GO(g_string_ascii_down, pFp) GO(g_string_ascii_up, pFp) GO(g_string_assign, pFpp) GO(g_string_chunk_clear, vFp) GO(g_string_chunk_free, vFp) GO(g_string_chunk_insert, pFpp) GO(g_string_chunk_insert_const, pFpp) GO(g_string_chunk_insert_len, pFppl) GO(g_string_chunk_new, pFL) GO(g_string_down, pFp) GO(g_string_equal, iFpp) GO(g_string_erase, pFpll) GO(g_string_free, pFpi) GO(g_string_free_to_bytes, pFp) GO(g_string_hash, uFp) GO(g_string_insert, pFplp) GO(g_string_insert_c, pFplC) GO(g_string_insert_len, pFplpl) GO(g_string_insert_unichar, pFplu) GO(g_string_new, pFp) GO(g_string_new_len, pFpl) GO(g_string_overwrite, pFplp) GO(g_string_overwrite_len, pFplpl) GO(g_string_prepend, pFpp) GO(g_string_prepend_c, pFpC) GO(g_string_prepend_len, pFppl) GO(g_string_prepend_unichar, pFpu) GO2(g_string_printf, vFppV, g_string_vprintf) // need align? GO(g_string_set_size, pFpL) GO(g_string_sized_new, pFL) GO(g_string_truncate, pFpL) GO(g_string_up, pFp) GO(g_string_vprintf, vFppp) GO(g_strip_context, pFpp) GO(g_str_is_ascii, iFp) GO2(g_strjoin, pFpV, g_strjoinv) GO(g_strjoinv, pFpp) // no need to align, ony string pointers here GO(g_strlcat, uFppu) GO(g_strlcpy, uFppu) GO(g_str_match_string, iFppi) GO(g_strncasecmp, iFppu) GO(g_strndup, pFpu) GO(g_strnfill, pFuC) GO(g_strreverse, pFp) GO(g_strrstr, pFpp) GO(g_strrstr_len, pFpip) GO(g_strsignal, pFi) GO(g_strsplit, pFppi) GO(g_strsplit_set, pFppi) GO(g_strstr_len, pFpip) GO(g_str_to_ascii, pFpp) GO(g_strtod, dFpp) GO(g_str_tokenize_and_fold, pFppp) GO(g_strup, pFp) GO(g_strv_length, uFp) //GO(g_test_add_data_func, //GO(g_test_add_data_func_full, //GO(g_test_add_func, //GO(g_test_add_vtable, //GO(g_test_assert_expected_messages_internal, //GO(g_test_bug, //GO(g_test_bug_base, //GO(g_test_build_filename, //GO(g_test_create_case, //GO(g_test_create_suite, //GO(g_test_expect_message, //GO(g_test_fail, //GO(g_test_failed, //GO(g_test_get_dir, //GO(g_test_get_filename, //GO(g_test_get_root, //GO(g_test_incomplete, //GO(g_test_init, //GO(g_test_log_buffer_free, //GO(g_test_log_buffer_new, //GO(g_test_log_buffer_pop, //GO(g_test_log_buffer_push, //GO(g_test_log_msg_free, //GO(g_test_log_set_fatal_handler, //GO(g_test_log_type_name, //GO(g_test_maximized_result, //GO(g_test_message, //GO(g_test_minimized_result, //GO(g_test_queue_destroy, //GO(g_test_queue_free, //GO(g_test_rand_double, //GO(g_test_rand_double_range, //GO(g_test_rand_int, //GO(g_test_rand_int_range, //GO(g_test_run, //GO(g_test_run_suite, //GO(g_test_set_nonfatal_assertions, //GO(g_test_skip, //GO(g_test_subprocess, //GO(g_test_suite_add, //GO(g_test_suite_add_suite, //GO(g_test_timer_elapsed, //GO(g_test_timer_last, //GO(g_test_timer_start, //GO(g_test_trap_assertions, //GO(g_test_trap_fork, //GO(g_test_trap_has_passed, //GO(g_test_trap_reached_timeout, //GO(g_test_trap_subprocess, GOM(g_thread_create, pFEppip) GOM(g_thread_create_full, pFEppLiiip) //GO(g_thread_error_quark, GO(g_thread_exit, vFp) GOM(g_thread_foreach, vFEpp) GO(g_thread_get_initialized, iFv) //GO(g_thread_init_glib, GO(g_thread_join, pFp) //GO(g_thread_new, //GO(g_thread_pool_free, //GO(g_thread_pool_get_max_idle_time, //GO(g_thread_pool_get_max_threads, //GO(g_thread_pool_get_max_unused_threads, //GO(g_thread_pool_get_num_threads, //GO(g_thread_pool_get_num_unused_threads, //GO(g_thread_pool_new, //GO(g_thread_pool_push, //GO(g_thread_pool_set_max_idle_time, //GO(g_thread_pool_set_max_threads, //GO(g_thread_pool_set_max_unused_threads, //GO(g_thread_pool_set_sort_function, //GO(g_thread_pool_stop_unused_threads, //GO(g_thread_pool_unprocessed, GO(g_thread_ref, pFp) GO(g_thread_self, pFv) GO(g_thread_set_priority, vFpi) //GO(g_thread_try_new, GO(g_thread_unref, vFp) GO(g_thread_yield, vFv) GOM(g_timeout_add, uFEupp) GOM(g_timeout_add_full, uFEiuppp) GOM(g_timeout_add_seconds, uFEupp) GOM(g_timeout_add_seconds_full, uFEiuppp) GO(g_timeout_source_new, pFu) GO(g_timeout_source_new_seconds, pFu) //GO(g_timer_continue, //GO(g_timer_destroy, //GO(g_timer_elapsed, //GO(g_timer_new, //GO(g_timer_reset, //GO(g_timer_start, //GO(g_timer_stop, GO(g_time_val_add, vFpl) GO(g_time_val_from_iso8601, iFpp) GO(g_time_val_to_iso8601, pFp) //GO(g_time_zone_adjust_time, //GO(g_time_zone_find_interval, //GO(g_time_zone_get_abbreviation, //GO(g_time_zone_get_offset, //GO(g_time_zone_is_dst, //GO(g_time_zone_new, //GO(g_time_zone_new_local, //GO(g_time_zone_new_utc, //GO(g_time_zone_ref, //GO(g_time_zone_unref, GO(g_trash_stack_height, uFp) GO(g_trash_stack_peek, pFp) GO(g_trash_stack_pop, pFp) GO(g_trash_stack_push, vFpp) //GO(g_tree_destroy, //GO(g_tree_foreach, //GO(g_tree_height, //GO(g_tree_insert, //GO(g_tree_lookup, //GO(g_tree_lookup_extended, //GO(g_tree_new, //GO(g_tree_new_full, //GO(g_tree_new_with_data, //GO(g_tree_nnodes, //GO(g_tree_ref, //GO(g_tree_remove, //GO(g_tree_replace, //GO(g_tree_search, //GO(g_tree_steal, //GO(g_tree_traverse, //GO(g_tree_unref, GO(g_try_malloc, pFL) GO(g_try_malloc0, pFL) GO(g_try_malloc0_n, pFLL) GO(g_try_malloc_n, pFLL) GO(g_try_realloc, pFpL) GO(g_try_realloc_n, pFpLL) //GO(g_tuples_destroy, //GO(g_tuples_index, GO(g_ucs4_to_utf16, pFplppp) GO(g_ucs4_to_utf8, pFplppp) GO(g_unichar_break_type, iFu) GO(g_unichar_combining_class, iFu) GO(g_unichar_compose, iFuup) GO(g_unichar_decompose, iFupp) GO(g_unichar_digit_value, iFu) GO(g_unichar_fully_decompose, iFuipu) GO(g_unichar_get_mirror_char, iFup) GO(g_unichar_get_script, iFu) GO(g_unichar_isalnum, iFu) GO(g_unichar_isalpha, iFu) GO(g_unichar_iscntrl, iFu) GO(g_unichar_isdefined, iFu) GO(g_unichar_isdigit, iFu) GO(g_unichar_isgraph, iFu) GO(g_unichar_islower, iFu) GO(g_unichar_ismark, iFu) GO(g_unichar_isprint, iFu) GO(g_unichar_ispunct, iFu) GO(g_unichar_isspace, iFu) GO(g_unichar_istitle, iFu) GO(g_unichar_isupper, iFu) GO(g_unichar_iswide, iFu) GO(g_unichar_iswide_cjk, iFu) GO(g_unichar_isxdigit, iFu) GO(g_unichar_iszerowidth, iFu) GO(g_unichar_tolower, uFu) GO(g_unichar_totitle, uFu) GO(g_unichar_toupper, uFu) GO(g_unichar_to_utf8, iFup) GO(g_unichar_type, iFu) GO(g_unichar_validate, iFu) GO(g_unichar_xdigit_value, iFu) GO(g_unicode_canonical_decomposition, pFup) GO(g_unicode_canonical_ordering, vFpu) GO(g_unicode_script_from_iso15924, iFu) GO(g_unicode_script_to_iso15924, uFi) //GO(g_unix_error_quark, //GO(g_unix_fd_add, //GO(g_unix_fd_add_full, //GO(g_unix_fd_source_new, //GO(g_unix_open_pipe, //GO(g_unix_set_fd_nonblocking, //GO(g_unix_signal_add, //GO(g_unix_signal_add_full, //GO(g_unix_signal_source_new, GO(g_unlink, iFp) GO(g_unsetenv, vFp) GO(g_uri_escape_string, pFppi) GO(g_uri_list_extract_uris, pFp) GO(g_uri_parse_scheme, pFp) GO(g_uri_unescape_segment, pFppp) GO(g_uri_unescape_string, pFpp) GO(g_usleep, vFL) GO(g_utf16_to_ucs4, pFplppp) GO(g_utf16_to_utf8, pFplppp) GO(g_utf8_casefold, pFpi) GO(g_utf8_collate, iFpp) GO(g_utf8_collate_key, pFpi) GO(g_utf8_collate_key_for_filename, pFpi) GO(g_utf8_find_next_char, pFpp) GO(g_utf8_find_prev_char, pFpp) GO(g_utf8_get_char, uFp) GO(g_utf8_get_char_validated, uFpi) GO(g_utf8_normalize, pFpii) GO(g_utf8_offset_to_pointer, pFpl) GO(g_utf8_pointer_to_offset, lFpp) GO(g_utf8_prev_char, pFp) GO(g_utf8_strchr, pFpiu) GO(g_utf8_strdown, pFpi) GO(g_utf8_strlen, lFpi) GO(g_utf8_strncpy, pFppu) GO(g_utf8_strrchr, pFpiu) GO(g_utf8_strreverse, pFpi) GO(g_utf8_strup, pFpi) GO(g_utf8_substring, pFpll) GO(g_utf8_to_ucs4, pFplppp) GO(g_utf8_to_ucs4_fast, pFplp) GO(g_utf8_to_utf16, pFplppp) GO(g_utf8_validate, iFplp) GO(g_utime, iFpp) GO(g_variant_builder_add, vFppppppppppp) // vaarg GO(g_variant_builder_add_parsed, vFppppppppppp) //vaarg GO(g_variant_builder_add_value, vFpp) GO(g_variant_builder_clear, vFp) GO(g_variant_builder_close, vFp) GO(g_variant_builder_end, pFp) GO(g_variant_builder_init, vFpp) GO(g_variant_builder_new, pFp) GO(g_variant_builder_open, vFpp) GO(g_variant_builder_ref, pFp) GO(g_variant_builder_unref, vFp) GO(g_variant_byteswap, pFp) GO(g_variant_check_format_string, iFppi) GO(g_variant_classify, iFp) GO(g_variant_compare, iFpp) GO(g_variant_dict_clear, vFp) GO(g_variant_dict_contains, iFpp) GO(g_variant_dict_end, pFp) GO(g_variant_dict_init, vFpp) GO(g_variant_dict_insert, vFpppppppppppppp) //vaarg GO(g_variant_dict_insert_value, vFppp) GO(g_variant_dict_lookup, iFppppppppppppp) //vaarg GO(g_variant_dict_lookup_value, pFppp) GO(g_variant_dict_new, pFp) GO(g_variant_dict_ref, pFp) GO(g_variant_dict_remove, iFpp) GO(g_variant_dict_unref, vFp) GO(g_variant_dup_bytestring, pFpp) GO(g_variant_dup_bytestring_array, pFpp) GO(g_variant_dup_objv, pFpp) GO(g_variant_dup_string, pFpp) GO(g_variant_dup_strv, pFpp) GO(g_variant_equal, iFpp) //GO(g_variant_format_string_scan, //GO(g_variant_format_string_scan_type, GOM(g_variant_get, vFEppV) GO(g_variant_get_boolean, iFp) GO(g_variant_get_byte, CFp) GO(g_variant_get_bytestring, pFp) GO(g_variant_get_bytestring_array, pFpp) GO(g_variant_get_child, vFpuppppppppppp) //vaarg here GO(g_variant_get_child_value, pFpu) GO(g_variant_get_data, pFp) GO(g_variant_get_data_as_bytes, pFp) GO(g_variant_get_double, dFp) GO(g_variant_get_fixed_array, pFppu) GO(g_variant_get_handle, iFp) GO(g_variant_get_int16, wFp) GO(g_variant_get_int32, iFp) GO(g_variant_get_int64, IFp) GO(g_variant_get_maybe, pFp) GO(g_variant_get_normal_form, pFp) GO(g_variant_get_objv, pFpp) GO(g_variant_get_size, uFp) GO(g_variant_get_string, pFpp) GO(g_variant_get_strv, pFpp) GO(g_variant_get_type, pFp) GO(g_variant_get_type_string, pFp) GO(g_variant_get_uint16, WFp) GO(g_variant_get_uint32, uFp) GO(g_variant_get_uint64, UFp) GO(g_variant_get_va, vFpppp) // no need to GOM, it's a "scanf" type of function, so using only pointer in va_list GO(g_variant_get_variant, pFp) GO(g_variant_hash, uFp) GO(g_variant_is_container, iFp) GO(g_variant_is_floating, iFp) GO(g_variant_is_normal_form, iFp) GO(g_variant_is_object_path, iFp) GO(g_variant_is_of_type, iFpp) GO(g_variant_is_signature, iFp) GO(g_variant_iter_copy, pFp) GO(g_variant_iter_free, vFp) GO(g_variant_iter_init, uFpp) GO(g_variant_iter_loop, iFpppppppppppp) // vaarg GO(g_variant_iter_n_children, uFp) GO(g_variant_iter_new, pFp) GO(g_variant_iter_next, iFpppppppppppp) // vaarg here GO(g_variant_iter_next_value, pFp) GO(g_variant_lookup, iFpppppppppppp) // vaarg GO(g_variant_lookup_value, pFppp) GO(g_variant_n_children, uFp) GOM(g_variant_new, pFEpV) GO(g_variant_new_array, pFppu) GO(g_variant_new_boolean, pFi) GO(g_variant_new_byte, pFC) GO(g_variant_new_bytestring, pFp) GO(g_variant_new_bytestring_array, pFpi) GO(g_variant_new_dict_entry, pFpp) GO(g_variant_new_double, pFd) GO(g_variant_new_fixed_array, pFppuu) GO(g_variant_new_from_bytes, pFppi) GOM(g_variant_new_from_data, pFEppuipp) GO(g_variant_new_handle, pFi) GO(g_variant_new_int16, pFw) GO(g_variant_new_int32, pFi) GO(g_variant_new_int64, pFI) GO(g_variant_new_maybe, pFpp) GO(g_variant_new_object_path, pFp) GO(g_variant_new_objv, pFpi) GO2(g_variant_new_parsed, pFEpV, my_g_variant_new_parsed_va) GOM(g_variant_new_parsed_va, pFEpp) //GO(g_variant_new_printf, // needs alignment..... GO(g_variant_new_signature, pFp) GO(g_variant_new_string, pFp) GO(g_variant_new_strv, pFpi) GO(g_variant_new_take_string, pFp) GO(g_variant_new_tuple, pFpu) GO(g_variant_new_uint16, pFW) GO(g_variant_new_uint32, pFu) GO(g_variant_new_uint64, pFU) #ifdef NOALIGN GO(g_variant_new_va, pFppp) #else GOM(g_variant_new_va, pFEppp) #endif GO(g_variant_new_variant, pFp) GO(g_variant_parse, pFppppp) GO(g_variant_parse_error_print_context, pFpp) //GO(g_variant_parse_error_quark, //GO(g_variant_parser_get_error_quark, GO(g_variant_print, pFpi) GO(g_variant_print_string, pFppi) GO(g_variant_ref, pFp) GO(g_variant_ref_sink, pFp) //GO(g_variant_serialised_byteswap, //GO(g_variant_serialised_get_child, //GO(g_variant_serialised_is_normal, //GO(g_variant_serialised_n_children, //GO(g_variant_serialiser_is_object_path, //GO(g_variant_serialiser_is_signature, //GO(g_variant_serialiser_is_string, //GO(g_variant_serialiser_needed_size, //GO(g_variant_serialiser_serialise, GO(g_variant_store, vFp) GO(g_variant_take_ref, pFp) GO(g_variant_type_checked_, pFp) //GO(g_variant_type_copy, //GO(g_variant_type_dup_string, //GO(g_variant_type_element, //GO(g_variant_type_equal, //GO(g_variant_type_first, //GO(g_variant_type_free, //GO(g_variant_type_get_string_length, //GO(g_variant_type_hash, //GO(g_variant_type_info_assert_no_infos, //GO(g_variant_type_info_element, //GO(g_variant_type_info_get, //GO(g_variant_type_info_get_type_string, //GO(g_variant_type_info_member_info, //GO(g_variant_type_info_n_members, //GO(g_variant_type_info_query, //GO(g_variant_type_info_query_element, //GO(g_variant_type_info_ref, //GO(g_variant_type_info_unref, //GO(g_variant_type_is_array, //GO(g_variant_type_is_basic, //GO(g_variant_type_is_container, //GO(g_variant_type_is_definite, //GO(g_variant_type_is_dict_entry, //GO(g_variant_type_is_maybe, //GO(g_variant_type_is_subtype_of, //GO(g_variant_type_is_tuple, //GO(g_variant_type_is_variant, //GO(g_variant_type_key, //GO(g_variant_type_new, //GO(g_variant_type_new_array, //GO(g_variant_type_new_dict_entry, //GO(g_variant_type_new_maybe, //GO(g_variant_type_new_tuple, //GO(g_variant_type_next, //GO(g_variant_type_n_items, //GO(g_variant_type_peek_string, //GO(g_variant_type_string_is_valid, //GO(g_variant_type_string_scan, //GO(g_variant_type_value, GO(g_variant_unref, vFp) GOM(g_vasprintf, iFEppp) GOM(g_vfprintf, iFEppp) GOM(g_vprintf, iFEpp) GOM(g_vsnprintf, iFEpLpp) GOM(g_vsprintf, iFEppp) GO(g_warn_message, vFppipp) //GO(_init, DATA(g_ascii_table, 4) DATA(g_utf8_skip, 4) //GLOB(g_threads_got_initialized, 4) DATA(glib_major_version, 4) DATA(glib_minor_version, 4) DATA(glib_micro_version, 4)
8e1d5795526ff09cb4a174e79e95abbe8f90ed34
61be4a7bfc24468a1227ea797150520c83257844
/event/Demo616_0.c
9829494d6615608c6f436266fb4049c182661710
[]
no_license
MrCheeze/botw-tools
491e6a2d06191efa7fc7048aefb48b3b38a59a52
9a9e845beed87f5ec417c01e515d0fa01366366c
refs/heads/master
2022-06-26T01:34:38.353269
2022-06-20T14:52:01
2022-06-20T14:53:26
85,882,713
238
92
null
2017-05-01T22:15:30
2017-03-22T22:34:34
Python
UTF-8
C
false
false
5,261
c
Demo616_0.c
-------- EventFlow: Demo616_0 -------- Actor: EventSystemActor entrypoint: None() actions: ['Demo_ChangeScene', 'Demo_WaitFrame'] queries: ['CheckFlag', 'CheckCurrentMap'] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: Fader entrypoint: None() actions: ['Demo_FadeOut'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: GameROMPlayer entrypoint: None() actions: ['Demo_XLinkEventCreate'] queries: [] params: {'Weapon': '', 'DisableWeapon': False, 'Shield': '', 'DisableShield': False, 'Bow': '', 'DisableBow': False, 'DisableSheikPad': False, 'ArmorHead': '', 'ArmorUpper': '', 'ArmorLower': '', 'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: SceneSoundCtrlTag entrypoint: None() actions: ['Demo_SetStartProc'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: EventControllerRumble entrypoint: None() actions: ['Demo_TimeSpecRumbleMiddle'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} void Demo616_0() { SceneSoundCtrlTag.Demo_SetStartProc({'BgmCtrlType': 'Mute', 'SeCtrlType': 'WorldMute', 'IsWaitFinish': True}) call BalladOfHeroCommon.PlayerWait() if EventSystemActor.CheckCurrentMap({'MapName': 'RemainsWind'}) { if EventSystemActor.CheckFlag({'FlagName': 'BalladOfHeroRito_Finish'}) in [1, 0] { GameROMPlayer.Demo_XLinkEventCreate({'ELinkKey': 'Demo616_Fringe', 'IsWaitFinish': True, 'IsTargetDemoSLinkUser': False, 'SLinkKey': 'Demo616_Fringe'}) EventControllerRumble.Demo_TimeSpecRumbleMiddle({'Seconds': 1, 'IsWaitFinish': False, 'IsWait': False}) EventSystemActor.Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 15}) Fader.Demo_FadeOut({'Frame': 2, 'DispMode': 'NoLogo', 'IsWaitFinish': True, 'Color': 0}) call BalladOfHeroCommon.RemainsResetFlag() EventSystemActor.Demo_ChangeScene({'IsWaitFinish': True, 'FadeType': 1, 'StartType': -1, 'WarpDestMapName': 'MainField/B-3', 'WarpDestPosName': 'Clear_RemainsWind', 'EvflName': 'Demo617_0', 'EntryPointName': 'Demo617_0'}) } } else if EventSystemActor.CheckCurrentMap({'MapName': 'RemainsWater'}) { if EventSystemActor.CheckFlag({'FlagName': 'BalladOfHeroZora_Finish'}) in [1, 0] { GameROMPlayer.Demo_XLinkEventCreate({'ELinkKey': 'Demo616_Fringe', 'IsWaitFinish': True, 'IsTargetDemoSLinkUser': False, 'SLinkKey': 'Demo616_Fringe'}) EventControllerRumble.Demo_TimeSpecRumbleMiddle({'Seconds': 1, 'IsWaitFinish': False, 'IsWait': False}) EventSystemActor.Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 15}) Fader.Demo_FadeOut({'Frame': 2, 'DispMode': 'NoLogo', 'IsWaitFinish': True, 'Color': 0}) call BalladOfHeroCommon.RemainsResetFlag() EventSystemActor.Demo_ChangeScene({'IsWaitFinish': True, 'FadeType': 1, 'StartType': -1, 'WarpDestPosName': 'Clear_RemainsWater', 'WarpDestMapName': 'MainField/H-5', 'EvflName': 'Demo617_0', 'EntryPointName': 'Demo617_0Lutta'}) } } else if EventSystemActor.CheckCurrentMap({'MapName': 'RemainsFire'}) { if EventSystemActor.CheckFlag({'FlagName': 'BalladOfHeroGoron_Finish'}) in [1, 0] { GameROMPlayer.Demo_XLinkEventCreate({'ELinkKey': 'Demo616_Fringe', 'IsWaitFinish': True, 'IsTargetDemoSLinkUser': False, 'SLinkKey': 'Demo616_Fringe'}) EventControllerRumble.Demo_TimeSpecRumbleMiddle({'IsWaitFinish': False, 'Seconds': 1, 'IsWait': False}) EventSystemActor.Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 15}) Fader.Demo_FadeOut({'Frame': 2, 'DispMode': 'NoLogo', 'IsWaitFinish': True, 'Color': 0}) call BalladOfHeroCommon.RemainsResetFlag() EventSystemActor.Demo_ChangeScene({'IsWaitFinish': True, 'FadeType': 1, 'StartType': -1, 'WarpDestPosName': 'Clear_RemainsFire', 'WarpDestMapName': 'MainField/H-2', 'EntryPointName': 'Demo617_0Rudania', 'EvflName': 'Demo617_0'}) } } else if EventSystemActor.CheckFlag({'FlagName': 'BalladOfHeroGerudo_Finish'}) in [1, 0] { GameROMPlayer.Demo_XLinkEventCreate({'ELinkKey': 'Demo616_Fringe', 'IsWaitFinish': True, 'IsTargetDemoSLinkUser': False, 'SLinkKey': 'Demo616_Fringe'}) EventControllerRumble.Demo_TimeSpecRumbleMiddle({'IsWaitFinish': False, 'Seconds': 1, 'IsWait': False}) EventSystemActor.Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 15}) Fader.Demo_FadeOut({'Frame': 2, 'DispMode': 'NoLogo', 'IsWaitFinish': True, 'Color': 0}) call BalladOfHeroCommon.RemainsResetFlag() EventSystemActor.Demo_ChangeScene({'IsWaitFinish': True, 'FadeType': 1, 'StartType': -1, 'WarpDestPosName': 'Clear_RemainsElectric', 'WarpDestMapName': 'MainField/C-7', 'EvflName': 'Demo617_0', 'EntryPointName': 'Demo617_0Navoris'}) } }
5f6d964836b4b4220cec3badc8e949ab894c90a1
4e366db41b2bb755c5a1d8fa8149bf619ac7c970
/components/x11/libdga/src/dga_Xrequests.c
0c40d924c4cbfec09ab7f0d496f41a85063f9e31
[ "MIT" ]
permissive
OpenIndiana/oi-userland
0af05f09a04dc95d814fce1d56ff1d74f07fd042
a40cd6c757239bcf4e1f0d5943a65d9b57fbc3f7
refs/heads/oi/hipster
2023-09-04T04:41:58.585774
2023-09-03T18:00:28
2023-09-03T18:00:28
10,007,731
220
334
null
2023-09-14T21:48:26
2013-05-12T01:29:19
C
UTF-8
C
false
false
35,905
c
dga_Xrequests.c
/* Copyright (c) 1993, 2015, 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. */ /* * dga_Xrequests.c - the client side code for DGA X11 requests */ /* *----------------------------------------------------------------------- * * This code uses the standard extension mechanism for sending * SUN_DGA private extension requests. * *----------------------------------------------------------------------- */ #define NEED_REPLIES #define NEED_EVENTS #ifdef SERVER_DGA #include <X11/X.h> #include <X11/Xmd.h> #include "resource.h" #include "dixstruct.h" #include <stdio.h> #include "pixmapstr.h" #else #include <X11/Xlibint.h> #include <sys/resource.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/un.h> #include <netdb.h> #ifdef SVR4 #include <sys/utsname.h> #endif #endif /* SERVER_DGA */ #include "dga.h" #include "dga_Xrequests.h" #include "dga_incls.h" #include "XineramaInfo.h" #ifdef SERVER_DGA #define NEW 1 /* Flag for SHAPES to use new window grabber */ #define BadCookie 0 #endif #define X_DGA 0 /* a hack, so GetReq and GetResReq work below */ #ifndef MIN #define MIN(i,j) ((i)<(j)?(i):(j)) #endif static struct dga_extinfo **dga_extinfo_table = 0; /* No table to start with */ static int dga_extinfo_table_size = 0; static int terminate_dga_ext(); static int islocalhost(); static int dga_winlist_add(); static int dga_winlist_free(); void * _dga_is_X_window(); int dga_pixlist_add(); static int dga_pixlist_free(); void *_dga_is_X_pixmap(); extern void dgai_win_ungrab_common(); extern int _thr_main(); #ifdef SVR4 #ifdef MT mutex_t dgaGlobalMutex; mutex_t dgaGlobalPixmapMutex; int dgaThreaded; /* 1 == linked with libthread, else 0 */ int dgaMTOn; /* 1 == MT per-drawable locking is turned on, else 0 */ #endif int _dga_client_version = -1; void dga_init_version(ver) int ver; { if (ver > -1) _dga_client_version = ver; #ifdef MT dgaThreaded = (_thr_main() != -1) ? 1 : 0; dgaMTOn = 0; mutex_init(&dgaGlobalMutex, USYNC_THREAD, NULL); mutex_init(&dgaGlobalPixmapMutex, USYNC_THREAD, NULL); #endif } #endif #ifndef SERVER_DGA static struct dga_extinfo * init_dga_ext(dpy) Display *dpy; { int protmajor, protminor; XExtCodes *xecp; struct dga_extinfo *infop; #ifdef SVR4 if (_dga_client_version < 0) return 0; #endif if (dga_extinfo_table_size < (dpy->fd + 1)) { /* We've got to allocate or grow the table */ struct rlimit rl; int size; struct dga_extinfo **tblptr; size = (getrlimit(RLIMIT_NOFILE, &rl) < 0) ? dga_extinfo_table_size : rl.rlim_cur; if (size < (dpy->fd + 1)) return 0; tblptr = (struct dga_extinfo **) ((dga_extinfo_table_size) ? realloc(dga_extinfo_table, sizeof(struct dga_extinfo *) * size) : malloc(sizeof(struct dga_extinfo *) * size)); if (tblptr == NULL) return 0; dga_extinfo_table = tblptr; memset((char *) &dga_extinfo_table[dga_extinfo_table_size], (int)'\0', sizeof(struct dga_extinfo *) * (size - dga_extinfo_table_size)); dga_extinfo_table_size = size; } if (dga_extinfo_table[dpy->fd] != NULL) return dga_extinfo_table[dpy->fd]; if (!islocalhost(dpy)) return 0; if ((xecp = XInitExtension(dpy, "SUN_DGA")) != NULL) { if (XDgaQueryVersion(dpy, &protmajor, &protminor) == 0) { protmajor = 3; /* protminor = 0; let minor number pass through */ } } else return 0; if ((infop = (struct dga_extinfo *) malloc(sizeof(struct dga_extinfo))) == NULL) return 0; infop->protocol_major_version = protmajor; infop->protocol_minor_version = protminor; infop->extension = xecp->extension; infop->major_opcode = xecp->major_opcode; dga_extinfo_table[dpy->fd] = infop; XESetCloseDisplay(dpy, infop->extension, terminate_dga_ext); return infop; } static int islocalhost(dpy) Display *dpy; { char hostname[256]; char *colon; unsigned int namelen; size_t hostlen, phostlen; #ifdef IPv6 struct addrinfo *localhostaddr; struct addrinfo *otherhostaddr; struct addrinfo *i, *j; int equiv = 0; char host[NI_MAXHOST]; #else struct hostent *phost; struct hostent *h; #endif union genericaddr { struct sockaddr generic; struct sockaddr_in internet; #ifdef IPv6 struct sockaddr_in6 internetv6; struct sockaddr_storage maximumsize; #endif struct sockaddr_un nuxi; } addr; if (dpy->display_name[0] == ':') return 1; #ifdef SVR4 colon = strrchr(dpy->display_name, ':'); #else colon = rindex(dpy->display_name, ':'); #endif phostlen = strlen(dpy->display_name) - (colon ? strlen(colon) : 0); if((strncmp("unix", dpy->display_name, MIN(phostlen, 4)) == 0) || (strncmp("localhost", dpy->display_name, MIN(phostlen, 9)) == 0)) return 1; /* We're not a unix domain connection so what are we? */ namelen = sizeof addr; memset((char *) &addr, (int)'\0', sizeof addr); if(getpeername(dpy->fd, (struct sockaddr *) &addr, &namelen) < 0) return 0; hostlen = _XGetHostname(hostname, sizeof(hostname)); #ifdef IPv6 if (getaddrinfo(hostname, NULL, NULL, &localhostaddr) != 0) return 0; if (getnameinfo(&addr.generic, namelen, host, sizeof(host), NULL, 0, 0) != 0) { freeaddrinfo(localhostaddr); return 0; } if (getaddrinfo(host, NULL, NULL, &otherhostaddr) != 0) { freeaddrinfo(localhostaddr); return 0; } for (i = localhostaddr; i != NULL && equiv == 0; i = i->ai_next) { for (j = otherhostaddr; j != NULL && equiv == 0; j = j->ai_next) { if (i->ai_family == j->ai_family) { if (i->ai_family == AF_INET) { struct sockaddr_in *sinA = (struct sockaddr_in *) i->ai_addr; struct sockaddr_in *sinB = (struct sockaddr_in *) j->ai_addr; struct in_addr *A = &sinA->sin_addr; struct in_addr *B = &sinB->sin_addr; if (memcmp(A,B,sizeof(struct in_addr)) == 0) { equiv = 1; } } else if (i->ai_family == AF_INET6) { struct sockaddr_in6 *sinA = (struct sockaddr_in6 *) i->ai_addr; struct sockaddr_in6 *sinB = (struct sockaddr_in6 *) j->ai_addr; struct in6_addr *A = &sinA->sin6_addr; struct in6_addr *B = &sinB->sin6_addr; if (memcmp(A,B,sizeof(struct in6_addr)) == 0) { equiv = 1; } } } } } freeaddrinfo(localhostaddr); freeaddrinfo(otherhostaddr); return equiv; #else if ((addr.generic.sa_family != AF_INET) || ((h = gethostbyaddr((char *)&addr.internet.sin_addr, sizeof addr.internet.sin_addr, addr.internet.sin_family)) == 0)) return 0; /* Find real host name on TCPIP */ phost = gethostbyname(h->h_name); phostlen = strlen(phost->h_name); if (strncmp(hostname, phost->h_name, MIN(phostlen, hostlen))) return 0; return 1; #endif } static struct dga_extinfo * lookup_dga_ext(dpy) Display *dpy; { if (dga_extinfo_table_size < (dpy->fd + 1)) return 0; return dga_extinfo_table[dpy->fd]; } static int terminate_dga_ext(dpy, codes) Display *dpy; XExtCodes *codes; { free(dga_extinfo_table[dpy->fd]); dga_extinfo_table[dpy->fd] = NULL; dga_winlist_free(dpy, NULL); /* TODO: free pixmaps as well? */ return(1); } #endif /* SERVER_DGA */ Dga_token XDgaGrabWindow(dpy, win) Display *dpy; Window win; { #ifdef SERVER_DGA int val; WindowPtr pWin = (WindowPtr)LookupIDByType(win, RT_WINDOW); if (!pWin) return (BadCookie); if (((DrawablePtr)pWin)->type == DRAWABLE_PIXMAP) return (BadCookie); val = DgaWgGrab(pWin, NEW); if (val) { if (dga_winlist_add(val, dpy, win) == 0) { XDgaUnGrabWindow(dpy, win); return 0; } } return val; #else xResourceReq *req; xGenericReply rep; struct dga_extinfo *extinfop; if ((extinfop = init_dga_ext(dpy)) == NULL) return 0; LockDisplay(dpy); GetResReq(DGA, win, req); req->reqType = extinfop->major_opcode; req->pad = (extinfop->protocol_major_version >= 2) ? X_DgaGrabWindow : X_DgaGrabWindow_Old ; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); return 0; } UnlockDisplay(dpy); SyncHandle(); if (rep.data00) { if (dga_winlist_add(rep.data00, dpy, win) == 0) { XDgaUnGrabWindow(dpy, win); return 0; } } return rep.data00; #endif /* SERVER_DGA */ } int XDgaUnGrabWindow(dpy, win) Display *dpy; Window win; { #ifdef SERVER_DGA WindowPtr pWin = (WindowPtr)LookupIDByType(win, RT_WINDOW); int val; if (!pWin) return (BadCookie); if (((DrawablePtr)pWin)->type == DRAWABLE_PIXMAP) return (BadCookie); val = DgaWgUngrab(pWin, NEW); if (val) { if (dga_winlist_free(dpy, win) == 0) return 0; } return val; #else xResourceReq *req; xGenericReply rep; struct dga_extinfo *extinfop; if ((extinfop = lookup_dga_ext(dpy)) == NULL) return 0; LockDisplay(dpy); GetResReq(DGA, win, req); req->reqType = extinfop->major_opcode; req->pad = (extinfop->protocol_major_version >= 2) ? X_DgaUnGrabWindow : X_DgaUnGrabWindow_Old; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); return 0; } UnlockDisplay(dpy); SyncHandle(); if (rep.data00) { if (dga_winlist_free(dpy, win) == 0) return 0; } return rep.data00; /* Status */ #endif /* SERVER_DGA */ } #ifndef SERVER_DGA Dga_token XDgaGrabColormap(dpy, cmap) Display *dpy; Colormap cmap; { xResourceReq *req; xGenericReply rep; struct dga_extinfo *extinfop; #ifdef MT mutex_lock(&dgaGlobalMutex); #endif if ((extinfop = init_dga_ext(dpy)) == NULL) { #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return 0; } LockDisplay(dpy); GetResReq(DGA, cmap, req); req->reqType = extinfop->major_opcode; req->pad = (extinfop->protocol_major_version >= 3) ? X_DgaGrabColormap : X_DgaGrabColormap_Old; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return 0; } UnlockDisplay(dpy); SyncHandle(); #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return rep.data00; } int XDgaUnGrabColormap(dpy, cmap) Display *dpy; Colormap cmap; { xResourceReq *req; xGenericReply rep; struct dga_extinfo *extinfop; #ifdef MT mutex_lock(&dgaGlobalMutex); #endif if ((extinfop = lookup_dga_ext(dpy)) == NULL) { #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return 0; } LockDisplay(dpy); GetResReq(DGA, cmap, req); req->reqType = extinfop->major_opcode; req->pad = (extinfop->protocol_major_version >= 3) ? X_DgaUnGrabColormap : X_DgaUnGrabColormap_Old; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return 0; } UnlockDisplay(dpy); SyncHandle(); #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return rep.data00; /* Status */ } #endif /* SERVER_DGA */ int XDgaDrawGrabWids(dpy, drawid, nwids) Display *dpy; Drawable drawid; int nwids; { #ifdef SERVER_DGA WindowPtr pWin = (WindowPtr)LookupIDByType(drawid, RT_WINDOW); if (!pWin) return (BadCookie); if (((DrawablePtr)pWin)->type == DRAWABLE_PIXMAP) return (BadCookie); return(DgaWidGrab(pWin, nwids)); #else xDGAReq *req; xGenericReply rep; struct dga_extinfo *extinfop; #ifdef MT mutex_lock(&dgaGlobalMutex); #endif if (((extinfop = lookup_dga_ext(dpy)) == NULL) || (extinfop->protocol_major_version < 2)) { #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return 0; } LockDisplay(dpy); GetReq(DGA, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaGrabWids; req->id = drawid; req->number_objects = nwids; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return 0; } UnlockDisplay(dpy); SyncHandle(); #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return rep.data00; #endif /* SERVER_DGA */ } int XDgaGrabWids(dpy, win, nwids) Display *dpy; Window win; int nwids; { return (XDgaDrawGrabWids(dpy, (Drawable)win, nwids)); } int XDgaDrawGrabFCS(dpy, drawid, nfcs) Display *dpy; Drawable drawid; int nfcs; { #ifdef SERVER_DGA WindowPtr pWin = (WindowPtr)LookupIDByType(drawid, RT_WINDOW); if (!pWin) return (BadCookie); if (((DrawablePtr)pWin)->type == DRAWABLE_PIXMAP) return (BadCookie); /* When OWGX supports PIXMAPS, can be reomoved */ return(DgaFcsGrab(pWin, nfcs)); #else xDGAReq *req; xGenericReply rep; struct dga_extinfo *extinfop; #ifdef MT mutex_lock(&dgaGlobalMutex); #endif if (((extinfop = lookup_dga_ext(dpy)) == NULL) || (extinfop->protocol_major_version < 2)) { #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return 0; } LockDisplay(dpy); GetReq(DGA, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaGrabFCS; req->id = drawid; req->number_objects = nfcs; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return 0; } UnlockDisplay(dpy); SyncHandle(); #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return(rep.data00); #endif /* SERVER_DGA */ } int XDgaGrabFCS(dpy, win, nfcs) Display *dpy; Window win; int nfcs; { return (XDgaDrawGrabFCS(dpy, (Drawable)win, nfcs)); } int XDgaDrawGrabZbuf(dpy, drawid, nzbuftype) Display *dpy; Drawable drawid; int nzbuftype; { #ifdef SERVER_DGA WindowPtr pWin = (WindowPtr)LookupIDByType(drawid, RT_WINDOW); if (!pWin) return (BadCookie); if (((DrawablePtr)pWin)->type == DRAWABLE_PIXMAP) return (BadCookie); return(DgaZbufGrab(pWin, nzbuftype)); #else xDGAReq *req; xGenericReply rep; struct dga_extinfo *extinfop; #ifdef MT mutex_lock(&dgaGlobalMutex); #endif if (((extinfop = lookup_dga_ext(dpy)) == NULL) || (extinfop->protocol_major_version < 2)) { #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return 0; } LockDisplay(dpy); GetReq(DGA, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaGrabZbuf; req->id = drawid; req->number_objects = nzbuftype; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return 0; } UnlockDisplay(dpy); SyncHandle(); #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return(rep.data00); #endif /* SERVER_DGA */ } int XDgaGrabZbuf(dpy, win, nzbuftype) Display *dpy; Window win; int nzbuftype; { return (XDgaDrawGrabZbuf(dpy, (Drawable)win, nzbuftype)); } int XDgaDrawGrabStereo(dpy, drawid, st_mode) Display *dpy; Drawable drawid; int st_mode; { #ifdef SERVER_DGA WindowPtr pWin = (WindowPtr)LookupIDByType(drawid, RT_WINDOW); if (!pWin) return (BadCookie); if (((DrawablePtr)pWin)->type == DRAWABLE_PIXMAP) return (BadCookie); return(DgaStereoGrab(pWin, st_mode)); #else xDGAReq *req; xGenericReply rep; struct dga_extinfo *extinfop; #ifdef MT mutex_lock(&dgaGlobalMutex); #endif if (((extinfop = lookup_dga_ext(dpy)) == NULL) || (extinfop->protocol_major_version < 2)) { #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return 0; } LockDisplay(dpy); GetReq(DGA, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaGrabStereo; req->id = drawid; req->number_objects = st_mode; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return 0; } UnlockDisplay(dpy); SyncHandle(); #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return rep.data00; #endif /* SERVER_DGA */ } int XDgaGrabStereo(dpy, win, st_mode) Display *dpy; Window win; int st_mode; { return (XDgaDrawGrabStereo(dpy, (Drawable)win, st_mode)); } int XDgaGrabABuffers(dpy, win, type, buffer_site) Display *dpy; Window win; int type; int buffer_site; { #ifdef SERVER_DGA WindowPtr pWin = (WindowPtr)LookupIDByType(win, RT_WINDOW); if (!pWin) return (BadCookie); if (((DrawablePtr)pWin)->type == DRAWABLE_PIXMAP) return (BadCookie); /* Some surf prep may be needed for mpg */ return(DgaABuffersGrabInfo((DrawablePtr)pWin, type, buffer_site)); #else xDgaGrabABuffersReq *req; xGenericReply rep; struct dga_extinfo *extinfop; if ((extinfop = lookup_dga_ext(dpy)) == NULL) return 0; if (extinfop->protocol_major_version < 2) return 0; LockDisplay(dpy); GetReq(DgaGrabABuffers, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaGrabABuffers; req->id = win; req->type = type; req->buffer_site = buffer_site; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); return 0; } UnlockDisplay(dpy); SyncHandle(); return rep.data00; #endif /* SERVER_DGA */ } int XDgaUnGrabABuffers(dpy, win, type) Display *dpy; Window win; int type; { #ifdef SERVER_DGA WindowPtr pWin = (WindowPtr)LookupIDByType(win, RT_WINDOW); if (!pWin) return (BadCookie); if (((DrawablePtr)pWin)->type == DRAWABLE_PIXMAP) return (BadCookie); return(DgaABuffersUngrabInfo((DrawablePtr)pWin, type)); #else xDgaGrabABuffersReq *req; xGenericReply rep; struct dga_extinfo *extinfop; if ((extinfop = lookup_dga_ext(dpy)) == NULL) return 0; if (extinfop->protocol_major_version < 2) return 0; LockDisplay(dpy); GetReq(DgaGrabABuffers, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaUnGrabABuffers; req->id = win; req->type = type; req->buffer_site = 0; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); return 0; } UnlockDisplay(dpy); SyncHandle(); return rep.data00; #endif /* SERVER_DGA */ } int XDgaGrabBuffers(dpy, win, nbuffers) Display *dpy; Window win; int nbuffers; { #ifdef SERVER_DGA WindowPtr pWin = (WindowPtr)LookupIDByType(win, RT_WINDOW); if (!pWin) return (BadCookie); if (((DrawablePtr)pWin)->type == DRAWABLE_PIXMAP) return (BadCookie); /* Some surf prep may be needed for mpg */ return(DgaBufGrab(pWin, nbuffers)); #else xDGAReq *req; xGenericReply rep; struct dga_extinfo *extinfop; if ((extinfop = lookup_dga_ext(dpy)) == NULL) return 0; if (extinfop->protocol_major_version < 2) return 0; LockDisplay(dpy); GetReq(DGA, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaGrabBuffers; req->id = win; req->number_objects = nbuffers; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); return 0; } UnlockDisplay(dpy); SyncHandle(); return rep.data00; #endif /* SERVER_DGA */ } int XDgaUnGrabBuffers(dpy, win) Display *dpy; Window win; { #ifdef SERVER_DGA WindowPtr pWin = (WindowPtr)LookupIDByType(win, RT_WINDOW); if (!pWin) return (BadCookie); if (((DrawablePtr)pWin)->type == DRAWABLE_PIXMAP) return (BadCookie); return(DgaBufUngrab(pWin)); #else xResourceReq *req; xGenericReply rep; struct dga_extinfo *extinfop; if ((extinfop = lookup_dga_ext(dpy)) == NULL) return 0; if (extinfop->protocol_major_version < 2) return 0; LockDisplay(dpy); GetResReq(DGA, win, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaUnGrabBuffers; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); return 0; } UnlockDisplay(dpy); SyncHandle(); return rep.data00; #endif /* SERVER_DGA */ } int XDgaGrabRetainedWindow(dpy, win) Display *dpy; Window win; { #ifdef SERVER_DGA WindowPtr pWin = (WindowPtr)LookupIDByType(win, RT_WINDOW); if (!pWin) return (BadCookie); if (((DrawablePtr)pWin)->type == DRAWABLE_PIXMAP) return (BadCookie); return(DgaSharedRetained(pWin, 1, win)); #else xResourceReq *req; xGenericReply rep; struct dga_extinfo *extinfop; if ((extinfop = lookup_dga_ext(dpy)) == NULL) return 0; if (extinfop->protocol_major_version < 3) return 0; LockDisplay(dpy); GetResReq(DGA, win, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaGrabRetained; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); return 0; } UnlockDisplay(dpy); SyncHandle(); return rep.data00; #endif /* SERVER_DGA */ } int XDgaUnGrabRetainedWindow(dpy, win) Display *dpy; Window win; { #ifdef SERVER_DGA WindowPtr pWin = (WindowPtr)LookupIDByType(win, RT_WINDOW); if (!pWin) return (BadCookie); if (((DrawablePtr)pWin)->type == DRAWABLE_PIXMAP) return (BadCookie); return(DgaSharedRetained(pWin, 0, win)); #else xResourceReq *req; xGenericReply rep; struct dga_extinfo *extinfop; if ((extinfop = lookup_dga_ext(dpy)) == NULL) return 0; if (extinfop->protocol_major_version < 3) return 0; LockDisplay(dpy); GetResReq(DGA, win, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaUnGrabRetained; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); return 0; } UnlockDisplay(dpy); SyncHandle(); return rep.data00; /* Status */ #endif /* SERVER_DGA */ } int XDgaGetRetainedPath(dpy, win, path) Display *dpy; Window win; char *path; { #ifdef SERVER_DGA extern char *DgaSharedRetainedPath; if (DgaSharedRetainedPath) strcpy((char *)path, (char *)DgaSharedRetainedPath); return 1; #else xResourceReq *req; xDGARtndPathReply rep; struct dga_extinfo *extinfop; if ((extinfop = lookup_dga_ext(dpy)) == NULL) return 0; if (extinfop->protocol_major_version < 3) return 0; LockDisplay(dpy); GetResReq(DGA, win, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaGetRetainedPath; if (!_XReply(dpy, (xReply *) &rep, (SIZEOF(xDGARtndPathReply) - SIZEOF(xReply)) >> 2, xFalse)) { UnlockDisplay(dpy); SyncHandle(); return 0; } UnlockDisplay(dpy); SyncHandle(); strcpy(path, (char *) rep.path); return 1; #endif /* SERVER_DGA */ } int XDgaQueryVersion(dpy, major_versionp, minor_versionp) Display *dpy; int *major_versionp, *minor_versionp; { #ifdef SERVER_DGA *major_versionp = SUN_DGA_MAJOR_VERSION; *minor_versionp = SUN_DGA_MINOR_VERSION; return(1); #else xDgaQueryVersionReply rep; xDgaQueryVersionReq *req; int opcode, tmp; if (XQueryExtension(dpy, "SUN_DGA", &opcode, &tmp, &tmp) == 0) return 0; LockDisplay(dpy); GetReq(DgaQueryVersion, req); req->reqType = opcode; req->dgaReqType = X_DgaQueryVersion; if (!_XReply(dpy, (xReply *) & rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); return 0; } *major_versionp = rep.majorVersion; *minor_versionp = rep.minorVersion; UnlockDisplay(dpy); SyncHandle(); return 1; #endif /* SERVER_DGA */ } Dga_token XDgaGrabPixmap(dpy, d) Display *dpy; Pixmap d; { #ifdef SERVER_DGA int val; PixmapPtr pPix = (PixmapPtr)LookupIDByType(d, RT_PIXMAP); if (!pPix) return (BadCookie); if (((DrawablePtr)pPix)->type == DRAWABLE_WINDOW) return (BadCookie); val = DgaInitSharedPixmap(pPix, NEW); if (val) { if (dga_pixlist_add(val, dpy, d) == 0) { XDgaUnGrabPixmap(dpy, d); return 0; } } return val; #else xResourceReq *req; xGenericReply rep; struct dga_extinfo *extinfop; if ((extinfop = init_dga_ext(dpy)) == NULL) return 0; if (extinfop->protocol_major_version < 3) return 0; LockDisplay(dpy); GetResReq(DGA, d, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaGrabPixmap; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); return 0; } UnlockDisplay(dpy); SyncHandle(); if (rep.data00) { if (dga_pixlist_add(rep.data00, dpy, d) == 0) { XDgaUnGrabPixmap(dpy, d); return 0; } } return rep.data00; #endif /* SERVER_DGA */ } int XDgaUnGrabPixmap(dpy, d) Display *dpy; Pixmap d; { #ifdef SERVER_DGA PixmapPtr pPix = (PixmapPtr)LookupIDByType(d, RT_PIXMAP); int val; if (!pPix) return (BadCookie); if (((DrawablePtr)pPix)->type == DRAWABLE_WINDOW) return (BadCookie); val = DgaDestroySharedPixmap(pPix); if (val) { if (dga_pixlist_free(dpy, d) == 0) return 0; } return val; #else xResourceReq *req; xGenericReply rep; struct dga_extinfo *extinfop; if ((extinfop = lookup_dga_ext(dpy)) == NULL) return 0; if (extinfop->protocol_major_version < 3) return 0; LockDisplay(dpy); GetResReq(DGA, d, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaUnGrabPixmap; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); return 0; } UnlockDisplay(dpy); SyncHandle(); return rep.data00; /* Status */ #endif /* SERVER_DGA */ } static Dga_token dgai_grabDrawRequest (Display *dpy, Drawable drawid, int *drawType) { #ifdef SERVER_DGA DrawablePtr pDraw = (DrawablePtr)LookupIDByClass(drawid, RC_DRAWABLE); if (!pDraw) return(BadCookie); return(DgaDrawGrab(drawid, pDraw, NEW, drawType)); #else xResourceReq *req; xGenericReply rep; struct dga_extinfo *extinfop; if ((extinfop = init_dga_ext(dpy)) == NULL) return 0; if (extinfop->protocol_major_version < 3) return 0; LockDisplay(dpy); GetResReq(DGA, drawid, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaGrabDrawable; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); return 0; } UnlockDisplay(dpy); SyncHandle(); /* ** data00 is the opaque token identifying the drawable shared file. ** data01 is the type of the drawable: window (0) or pixmap (1), ** (Note: an attempt to grab a multibuffer drawable XID will fail) */ if (rep.data00) { *drawType = rep.data01; } return (rep.data00); #endif /* SERVER_DGA */ } static int dgai_ungrabDrawRequest (Display *dpy, Drawable drawid) { #ifdef SERVER_DGA DrawablePtr pDraw = (DrawablePtr)LookupIDByClass(drawid, RC_DRAWABLE); if (!pDraw) return(BadCookie); return(DgaDrawUngrab(drawid, pDraw, NEW)); #else xResourceReq *req; xGenericReply rep; struct dga_extinfo *extinfop; if ((extinfop = lookup_dga_ext(dpy)) == NULL) return 0; if (extinfop->protocol_major_version < 3) return 0; LockDisplay(dpy); GetResReq(DGA, drawid, req); req->reqType = extinfop->major_opcode; req->pad = X_DgaUnGrabDrawable; if (!_XReply(dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay(dpy); SyncHandle(); return 0; } UnlockDisplay(dpy); SyncHandle(); return rep.data00; /* Status */ #endif /* SERVER_DGA */ } Dga_drawable XDgaGrabDrawable(Display *dpy, Drawable drawid) { Dga_token token; int drawType; #ifdef MT mutex_lock(&dgaGlobalMutex); #endif if (!(token = dgai_grabDrawRequest(dpy, drawid, &drawType))) { #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return (NULL); } switch (drawType) { case DGA_PROTO_OVERLAY: case DGA_PROTO_WINDOW: { _Dga_window dgawin; if (!dga_winlist_add(token, dpy, (Window)drawid)) { goto Bad; } if (!(dgawin = (_Dga_window) dgai_win_grab_common(dpy, -1, token, 1))) { goto Bad; } dgawin->w_dpy = dpy; dgawin->w_id = (Window) drawid; if (dgawin->isOverlay = (drawType == DGA_PROTO_OVERLAY)) { dgawin->s_ovlstate_p = &((WXINFO *)dgawin->w_info)->w_ovlstate; dgawin->s_ovlshapevalid_p = &((WXINFO *)dgawin->w_info)->w_ovlshapevalid; dgawin->ovlStateNotifyFunc = NULL; } #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return ((Dga_drawable)dgawin); } case DGA_PROTO_PIXMAP: { _Dga_pixmap dgapix; if (!dga_pixlist_add(token, dpy, (Pixmap)drawid)) { goto Bad; } if (!(dgapix = (_Dga_pixmap) dga_pix_grab(token, (Pixmap)drawid))) { goto Bad; } dgapix->p_dpy = dpy; dgapix->p_id = (Pixmap) drawid; #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return ((Dga_drawable)dgapix); } } Bad: (void) dgai_ungrabDrawRequest(dpy, drawid); #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return (NULL); } int XDgaUnGrabDrawable(Dga_drawable dgadraw) { Drawable drawid = dga_draw_id(dgadraw); Display *dpy = dga_draw_display(dgadraw); int type = dga_draw_type(dgadraw); int status; if (dpy == NULL) return BadDrawable; #ifdef MT mutex_lock(&dgaGlobalMutex); #endif switch (type) { case DGA_DRAW_WINDOW: case DGA_DRAW_OVERLAY: dgai_win_ungrab_common((Dga_window)dgadraw, -1,1); break; case DGA_DRAW_PIXMAP: dga_pix_ungrab((Dga_pixmap)dgadraw); break; } status = dgai_ungrabDrawRequest(dpy, drawid); #ifdef MT mutex_unlock(&dgaGlobalMutex); #endif return (status); } static struct dga_xwinrec *dga_xwinlist = NULL; static int dga_winlist_add(token, dpy, win) Dga_token token; Display *dpy; Window win; { struct dga_xwinrec *recp; Display *listdpy; Window listwin; while (recp = (struct dga_xwinrec *) _dga_is_X_window(token,&listdpy,&listwin)) { if ((win == listwin) && (dpy == listdpy)) { recp->refcnt += 1; return 1; /* already in list */ } dga_winlist_free(listdpy, listwin); /* remove bogus entry from list */ } recp = (struct dga_xwinrec *) malloc(sizeof(struct dga_xwinrec)); if (recp == NULL) return 0; recp->next = dga_xwinlist; dga_xwinlist = recp; recp->token = token; recp->dpy = dpy; recp->win = win; recp->refcnt = 1; return 1; } /* * Free dga_xwinrec structure for a particular window and display. * If win is NULL free all entries on list for this display. */ static int dga_winlist_free(dpy, win) Display *dpy; Window win; { struct dga_xwinrec *recp, **prevp; int match = 0; prevp = &dga_xwinlist; recp = dga_xwinlist; while (recp) { if (recp->dpy == dpy) { if (win == NULL) { *prevp = recp->next; free(recp); match = 1; } else if (recp->win == win) { if (--recp->refcnt == 0) { *prevp = recp->next; free(recp); } return 1; } else { prevp = &recp->next; } } else { prevp = &recp->next; } recp = *prevp; } return (match); } void * _dga_is_X_window(token, dpyp, winp) Dga_token token; Display **dpyp; Window *winp; { struct dga_xwinrec *recp = dga_xwinlist; while (recp) { if (recp->token == token) { *dpyp = recp->dpy; *winp = recp->win; return ((void *) recp); } recp = recp->next; } return 0; } static struct dga_xpixrec *dga_xpixlist = NULL; /* REMIND DARYL: This routine is used to clean up "bogus" entries from * list. Shouldn't that be done in Ungrab??? */ int dga_pixlist_add(token, dpy, pix) Dga_token token; Display *dpy; Pixmap pix; { struct dga_xpixrec *recp; Display *listdpy; if (recp = (struct dga_xpixrec *) _dga_is_X_pixmap(pix, &listdpy)) { if (dpy == listdpy) { recp->refcnt += 1; return 1; /* already in list */ } dga_pixlist_free(dpy, pix); /* remove bogus entry from list */ } recp = (struct dga_xpixrec *) malloc(sizeof(struct dga_xpixrec)); if (recp == NULL) return 0; recp->next = dga_xpixlist; dga_xpixlist = recp; recp->token = token; recp->dpy = dpy; recp->pix = pix; recp->refcnt = 1; return 1; } static int dga_pixlist_free(dpy, pix) Display *dpy; Pixmap pix; { struct dga_xpixrec *recp, **prevp; int match = 0; prevp = &dga_xpixlist; recp = dga_xpixlist; while (recp) { if (recp->dpy == dpy) { if (pix == NULL) { *prevp = recp->next; free(recp); match = 1; } else if (recp->pix == pix) { if (--recp->refcnt == 0) { *prevp = recp->next; free(recp); } return 1; } else { prevp = &recp->next; } } else { prevp = &recp->next; } recp = *prevp; } return (match); } void * _dga_is_X_pixmap(pix, dpyp) Pixmap pix; Display **dpyp; { struct dga_xpixrec *recp = dga_xpixlist; while (recp) { if (recp->pix == pix) { *dpyp = recp->dpy; return ((void *) recp); } recp = recp->next; } return 0; } #ifndef SERVER_DGA /************************************ Addition to DGA for Xinerama extension. This code allows the client to mine out the window ID's that would normaly be hidden from the user in Xinerama mode. Xinerama keeps a list of WIDs that are connected to a virtual WID that the user gets to handle. **************************************/ BOOL XDgaGetXineramaInfo(dpy , VirtualWID, info ) Display *dpy; XID VirtualWID; XineramaInfo *info; { register xDgaXineramaInfoReq *req; xDgaXineramaInfoReply *rep; struct dga_extinfo *extinfop; if ((extinfop = init_dga_ext(dpy)) == NULL) return 0; rep = malloc(sizeof(xDgaXineramaInfoReply)); LockDisplay(dpy); GetReq(DgaXineramaInfo, req); req->reqType = extinfop->major_opcode; req->xdgaReqType = X_DgaXineramaInfo; req->visual = VirtualWID; if (!_XReply(dpy, (xReply *)rep, (sizeof(xDgaXineramaInfoReply)-32) >> 2, xFalse)) { UnlockDisplay(dpy); SyncHandle(); Xfree(rep); return NULL; } info->wid = VirtualWID; memcpy(&info->subs[0],&rep->subs[0],(MAXSCREEN-1) * sizeof(SubWID)); UnlockDisplay(dpy); SyncHandle(); free(rep); return 1; } #endif
545b6380f01fba4bfe18ad77e7d9cf497687a9c4
f728b4fa5156d20abc60634bc4f8b10c9226613d
/include/datoviz/transforms.h
82a012be62e69259023cd9f98ab091f7fe9c9981
[ "MIT" ]
permissive
datoviz/datoviz
802ae333b462d98468b5b7c57ed44871602b2cb8
9b934e6dc2d02b91ab60a8e3763fa565440e3ea0
refs/heads/main
2023-07-11T16:16:08.605371
2023-07-04T16:52:46
2023-07-04T16:52:46
281,501,204
476
24
MIT
2023-07-04T16:52:48
2020-07-21T20:48:09
C
UTF-8
C
false
false
9,759
h
transforms.h
/*************************************************************************************************/ /* Simple transform system for data normalization */ /*************************************************************************************************/ #ifndef DVZ_TRANSFORMS_HEADER #define DVZ_TRANSFORMS_HEADER #include "array.h" #include "common.h" /*************************************************************************************************/ /* Constants */ /*************************************************************************************************/ #define DVZ_BOX_NDC \ (DvzBox) \ { \ {-1, -1, -1}, { +1, +1, +1 } \ } #define DVZ_BOX_INF \ (DvzBox) \ { \ {+INFINITY, +INFINITY, +INFINITY}, { -INFINITY, -INFINITY, -INFINITY } \ } #define DVZ_TRANSFORM_CHAIN_MAX_SIZE 32 #define DVZ_TRANSFORM_MATRIX_VULKAN \ (dmat4) \ { \ {1, 0, 0, 0}, {0, -1, 0, 0}, {0, 0, .5, 0}, { 0, 0, .5, 1 } \ } /*************************************************************************************************/ /* Enums */ /*************************************************************************************************/ // Transformations. typedef enum { DVZ_TRANSFORM_NONE, DVZ_TRANSFORM_CARTESIAN, DVZ_TRANSFORM_POLAR, DVZ_TRANSFORM_CYLINDRICAL, DVZ_TRANSFORM_SPHERICAL, DVZ_TRANSFORM_EARTH_MERCATOR_WEB, } DvzTransformType; // Transformation flags. typedef enum { DVZ_TRANSFORM_FLAGS_NONE = 0x0000, DVZ_TRANSFORM_FLAGS_LOGX = 0x0001, DVZ_TRANSFORM_FLAGS_LOGY = 0x0002, DVZ_TRANSFORM_FLAGS_LOGLOG = 0x0003, DVZ_TRANSFORM_FLAGS_FIXED_ASPECT = 0x0008, } DvzTransformFlags; // Coordinate systems. typedef enum { DVZ_CDS_NONE, DVZ_CDS_DATA, DVZ_CDS_SCENE, DVZ_CDS_VULKAN, DVZ_CDS_FRAMEBUFFER, DVZ_CDS_WINDOW, } DvzCDS; // CDS transpose. typedef enum { DVZ_CDS_TRANSPOSE_NONE, // x right y up z front DVZ_CDS_TRANSPOSE_XFYRZU, // x front y right z up DVZ_CDS_TRANSPOSE_XBYDZL, // x back y down z left DVZ_CDS_TRANSPOSE_XLYBZD, // x left y back z down } DvzCDSTranspose; /*************************************************************************************************/ /* Typedefs */ /*************************************************************************************************/ typedef struct DvzDataCoords DvzDataCoords; typedef struct DvzBox DvzBox; typedef struct DvzTransform DvzTransform; typedef struct DvzTransformChain DvzTransformChain; // Forward declarations. typedef struct DvzPanel DvzPanel; /*************************************************************************************************/ /* Structs */ /*************************************************************************************************/ struct DvzBox { dvec3 p0, p1; }; struct DvzDataCoords { DvzBox box; // in data coordinate system DvzCDSTranspose transpose; // possible transposition of the data coordinate system DvzTransformType transform; int flags; // come from the panel // TODO: union with transform parameters? }; struct DvzTransform { DvzTransformType type; dmat4 mat; // transformation matrix for linear transforms, parameters for other transforms int flags; // come from the panel bool inverse; }; struct DvzTransformChain { uint32_t count; DvzTransform transforms[DVZ_TRANSFORM_CHAIN_MAX_SIZE]; }; /*************************************************************************************************/ /* Transposition functions */ /*************************************************************************************************/ #define MAKE_TRANSPOSE(T) \ static void _transpose_##T(DvzCDSTranspose transpose, T* src, T* dst) \ { \ ASSERT(src != NULL); \ ASSERT(dst != NULL); \ T src_ = {0}; \ memcpy(&src_, src, sizeof(T)); \ switch (transpose) \ { \ \ case DVZ_CDS_TRANSPOSE_NONE: \ memcpy(dst, src_, sizeof(T)); \ break; \ \ case DVZ_CDS_TRANSPOSE_XBYDZL: \ (*dst)[0] = -src_[2]; \ (*dst)[1] = -src_[1]; \ (*dst)[2] = -src_[0]; \ break; \ \ case DVZ_CDS_TRANSPOSE_XFYRZU: \ (*dst)[0] = -src_[1]; \ (*dst)[1] = +src_[2]; \ (*dst)[2] = +src_[0]; \ break; \ \ case DVZ_CDS_TRANSPOSE_XLYBZD: \ (*dst)[0] = -src_[0]; \ (*dst)[1] = -src_[2]; \ (*dst)[2] = -src_[1]; \ break; \ \ default: \ log_error("unknown CDS transpose %d", transpose); \ break; \ } \ } MAKE_TRANSPOSE(dvec3) MAKE_TRANSPOSE(vec3) /*************************************************************************************************/ /* Functions */ /*************************************************************************************************/ /** * Apply a CPU builtin transformation on position data. * * @param coords the data coordinate system and bounds * @param pos_in input array of dvec3 values * @param[out] pos_out output array of dvec3 values * @param inverse whether to use the inverse or forward transformation */ DVZ_EXPORT void dvz_transform_pos(DvzDataCoords coords, DvzArray* pos_in, DvzArray* pos_out, bool inverse); /** * Convert a 3D position from a coordinate system to another. * * @param panel the panel * @param source the source coordinate system * @param in the input position * @param target the target coordinate system * @param[out] out the output (transformed) position */ DVZ_EXPORT void dvz_transform(DvzPanel* panel, DvzCDS source, dvec3 pos_in, DvzCDS target, dvec3 pos_out); #endif
013ac63d2d685e119ab90144a523ca0e5c00ddf2
caa3fd7b505b9f374d67716d838fc9657135f06d
/libgo/misc/cgo/testtls/tls_unix.c
957afce90d4aedc8a79f8bfa5e447871086876b2
[ "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-google-patent-license-golang", "BSD-3-Clause" ]
permissive
golang/gofrontend
674700d5e4682daf09e3f27be4e0f2844c0e1dd2
d04b024021bb7dbaa434a6d902bd12beb08e315f
refs/heads/master
2023-08-18T00:26:59.887760
2023-07-20T18:21:13
2023-07-20T19:28:09
28,939,900
874
155
BSD-3-Clause
2023-07-26T00:00:24
2015-01-07T23:54:58
Go
UTF-8
C
false
false
272
c
tls_unix.c
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include <pthread.h> static __thread int tls; void setTLS(int v) { tls = v; } int getTLS() { return tls; }
4d0691329eeed91bb36b7a28f2db0c6213d04e1c
e08313883c08d4f41ed3dafd5394f408f309aa92
/platform/platform_glfw.c
a32ad9069b4e2aec585f5117dad22622726b4a7b
[ "CC0-1.0" ]
permissive
lieff/lvg
b48276d0e21a994baf6a2522c028509c7c20516d
753c17187e66ac4456202fdac3568467153a6c20
refs/heads/master
2022-09-10T03:48:43.768487
2022-08-16T13:51:38
2022-08-16T14:29:54
64,092,051
115
10
null
null
null
null
UTF-8
C
false
false
10,194
c
platform_glfw.c
#include <config.h> #if PLATFORM_GLFW #include <platform/platform.h> #include <stdio.h> #include <stdlib.h> #define GL_GLEXT_PROTOTYPES #ifdef EMSCRIPTEN #include <emscripten.h> #include <emscripten/html5.h> #define GLFW_INCLUDE_ES2 #endif #include <GLFW/glfw3.h> typedef void* (* GLADloadproc)(const char *name); int gladLoadGLLoader(GLADloadproc); typedef struct platform_ctx { GLFWwindow *window; platform_params *params; void (*onFrame)(void *); void *user; int winX, winY; int defWidth, defHeight; //char keys[256]; } platform_ctx; /*void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods) { platform_ctx *platform = (platform_ctx *)glfwGetWindowUserPointer(window); platform->keys[scancode & 0xff] = (action == GLFW_PRESS || action == GLFW_REPEAT) ? 1 : 0; }*/ static int glfw_init(void **ctx, platform_params *params, void (*onFrame)(void *), void *user, int audio_only) { *ctx = 0; if (!glfwInit()) { printf("error: glfw init failed\n"); return 0; } platform_ctx *platform = (platform_ctx *)calloc(1, sizeof(platform_ctx)); platform->onFrame = onFrame; platform->user = user; platform->params = params; glfwWindowHint(GLFW_RESIZABLE, 1); glfwWindowHint(GLFW_SAMPLES, 8); #ifdef EMSCRIPTEN platform->defWidth = 1024, platform->defHeight = 800; #else GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode *mode = glfwGetVideoMode(monitor); platform->defWidth = mode->width - 40; platform->defHeight = mode->height - 80; if (platform->defWidth > 1024) platform->defWidth = 1024; if (platform->defHeight > 800) platform->defHeight = 800; #endif platform->window = glfwCreateWindow(platform->defWidth, platform->defHeight, "LVG Player", NULL, NULL); if (!platform->window) { free(platform); printf("error: could not open window\n"); return 0; } #ifndef EMSCRIPTEN glfwSwapInterval(1); #endif glfwMakeContextCurrent(platform->window); glfwSetInputMode(platform->window, GLFW_STICKY_MOUSE_BUTTONS, 1); glfwSetInputMode(platform->window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); //glfwSetWindowUserPointer(platform->window, (void*)platform); //glfwSetKeyCallback(platform->window, key_callback); #ifndef EMSCRIPTEN if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { printf("error: glad init failed\n"); return 0; } #endif *ctx = platform; return 1; } static void glfw_release(void *ctx) { glfwTerminate(); } static void glfw_pull_events(void *ctx) { platform_ctx *platform = (platform_ctx *)ctx; platform_params *params = platform->params; glfwPollEvents(); glfwGetWindowSize(platform->window, &params->winWidth, &params->winHeight); glfwGetFramebufferSize(platform->window, &params->width, &params->height); glfwGetCursorPos(platform->window, &params->mx, &params->my); params->mkeys = 0; params->mkeys |= glfwGetMouseButton(platform->window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS ? MOUSE_BUTTON_LEFT : 0; params->mkeys |= glfwGetMouseButton(platform->window, GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS ? MOUSE_BUTTON_MIDDLE : 0; params->mkeys |= glfwGetMouseButton(platform->window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS ? MOUSE_BUTTON_RIGHT : 0; params->time = glfwGetTime(); } static void glfw_main_loop(void *ctx) { glfwSetTime(0); platform_ctx *platform = (platform_ctx *)ctx; #ifdef EMSCRIPTEN emscripten_set_main_loop(platform->onFrame, platform->user, 0, 1); #else while (!glfwWindowShouldClose(platform->window)) { platform->onFrame(platform->user); if (glfwGetKey(platform->window, GLFW_KEY_ESCAPE)) glfwSetWindowShouldClose(platform->window, 1); } #endif } static void glfw_swap_buffers(void *ctx) { platform_ctx *platform = (platform_ctx *)ctx; glfwSwapBuffers(platform->window); } static void glfw_fullscreen(void *ctx, int b_fullscreen) { #ifndef EMSCRIPTEN platform_ctx *platform = (platform_ctx *)ctx; platform_params *params = platform->params; GLFWmonitor *monitor = glfwGetPrimaryMonitor(); const GLFWvidmode *mode = glfwGetVideoMode(monitor); if (b_fullscreen) { glfwGetWindowPos(platform->window, &platform->winX, &platform->winY); params->winWidth = mode->width; params->winHeight = mode->height; } else { params->winWidth = platform->defWidth; params->winHeight = platform->defHeight; } glfwSetWindowMonitor(platform->window, b_fullscreen ? monitor : 0, b_fullscreen ? 0 : platform->winX, b_fullscreen ? 0 : platform->winY, params->winWidth, params->winHeight, b_fullscreen ? mode->refreshRate : 0); #endif } static double glfw_get_time(void *ctx) { return glfwGetTime(); } static int glfw_get_key(void *ctx, int key) { static const short key_lookup[] = { [KEY_A] = GLFW_KEY_A, [KEY_B] = GLFW_KEY_B, [KEY_C] = GLFW_KEY_C, [KEY_D] = GLFW_KEY_D, [KEY_E] = GLFW_KEY_E, [KEY_F] = GLFW_KEY_F, [KEY_G] = GLFW_KEY_G, [KEY_H] = GLFW_KEY_H, [KEY_I] = GLFW_KEY_I, [KEY_J] = GLFW_KEY_J, [KEY_K] = GLFW_KEY_K, [KEY_L] = GLFW_KEY_L, [KEY_M] = GLFW_KEY_M, [KEY_N] = GLFW_KEY_N, [KEY_O] = GLFW_KEY_O, [KEY_P] = GLFW_KEY_P, [KEY_Q] = GLFW_KEY_Q, [KEY_R] = GLFW_KEY_R, [KEY_S] = GLFW_KEY_S, [KEY_T] = GLFW_KEY_T, [KEY_U] = GLFW_KEY_U, [KEY_V] = GLFW_KEY_V, [KEY_W] = GLFW_KEY_W, [KEY_X] = GLFW_KEY_X, [KEY_Y] = GLFW_KEY_Y, [KEY_Z] = GLFW_KEY_Z, [KEY_1] = GLFW_KEY_1, [KEY_2] = GLFW_KEY_2, [KEY_3] = GLFW_KEY_3, [KEY_4] = GLFW_KEY_4, [KEY_5] = GLFW_KEY_5, [KEY_6] = GLFW_KEY_6, [KEY_7] = GLFW_KEY_7, [KEY_8] = GLFW_KEY_8, [KEY_9] = GLFW_KEY_9, [KEY_0] = GLFW_KEY_0, [KEY_ENTER] = GLFW_KEY_ENTER, [KEY_ESC] = GLFW_KEY_ESCAPE, [KEY_BACKSPACE] = GLFW_KEY_BACKSPACE, [KEY_TAB] = GLFW_KEY_TAB, [KEY_SPACE] = GLFW_KEY_SPACE, [KEY_MINUS] = GLFW_KEY_MINUS, [KEY_EQUAL] = GLFW_KEY_EQUAL, [KEY_LEFTBRACE] = GLFW_KEY_LEFT_BRACKET, [KEY_RIGHTBRACE] = GLFW_KEY_RIGHT_BRACKET, [KEY_BACKSLASH] = GLFW_KEY_BACKSLASH, [KEY_HASHTILDE] = GLFW_KEY_GRAVE_ACCENT, [KEY_SEMICOLON] = GLFW_KEY_SEMICOLON, [KEY_APOSTROPHE] = GLFW_KEY_APOSTROPHE, [KEY_GRAVE] = GLFW_KEY_GRAVE_ACCENT, [KEY_COMMA] = GLFW_KEY_COMMA, [KEY_DOT] = GLFW_KEY_PERIOD, [KEY_SLASH] = GLFW_KEY_SLASH, [KEY_CAPSLOCK] = GLFW_KEY_CAPS_LOCK, [KEY_F1] = GLFW_KEY_F1, [KEY_F2] = GLFW_KEY_F2, [KEY_F3] = GLFW_KEY_F3, [KEY_F4] = GLFW_KEY_F4, [KEY_F5] = GLFW_KEY_F5, [KEY_F6] = GLFW_KEY_F6, [KEY_F7] = GLFW_KEY_F7, [KEY_F8] = GLFW_KEY_F8, [KEY_F9] = GLFW_KEY_F9, [KEY_F10] = GLFW_KEY_F10, [KEY_F11] = GLFW_KEY_F11, [KEY_F12] = GLFW_KEY_F12, [KEY_SYSRQ] = GLFW_KEY_PRINT_SCREEN, [KEY_SCROLLLOCK] = GLFW_KEY_SCROLL_LOCK, [KEY_PAUSE] = GLFW_KEY_PAUSE, [KEY_INSERT] = GLFW_KEY_INSERT, [KEY_HOME] = GLFW_KEY_HOME, [KEY_PAGEUP] = GLFW_KEY_PAGE_UP, [KEY_DELETE] = GLFW_KEY_DELETE, [KEY_END] = GLFW_KEY_END, [KEY_PAGEDOWN] = GLFW_KEY_PAGE_DOWN, [KEY_RIGHT] = GLFW_KEY_RIGHT, [KEY_LEFT] = GLFW_KEY_LEFT, [KEY_DOWN] = GLFW_KEY_DOWN, [KEY_UP] = GLFW_KEY_UP, [KEY_NUMLOCK] = GLFW_KEY_NUM_LOCK, [KEY_KPSLASH] = GLFW_KEY_KP_DIVIDE, [KEY_KPASTERISK] = GLFW_KEY_KP_MULTIPLY, [KEY_KPMINUS] = GLFW_KEY_KP_SUBTRACT, [KEY_KPPLUS] = GLFW_KEY_KP_ADD, [KEY_KPENTER] = GLFW_KEY_KP_ENTER, [KEY_KP1] = GLFW_KEY_KP_1, [KEY_KP2] = GLFW_KEY_KP_2, [KEY_KP3] = GLFW_KEY_KP_3, [KEY_KP4] = GLFW_KEY_KP_4, [KEY_KP5] = GLFW_KEY_KP_5, [KEY_KP6] = GLFW_KEY_KP_6, [KEY_KP7] = GLFW_KEY_KP_7, [KEY_KP8] = GLFW_KEY_KP_8, [KEY_KP9] = GLFW_KEY_KP_9, [KEY_KP0] = GLFW_KEY_KP_0, //[KEY_KPDOT] = GLFW_KEY_KP_DECIMAL, //[KEY_102ND] = 0x64, //[KEY_COMPOSE] = 0x65, //[KEY_POWER] = 0x66, [KEY_KPEQUAL] = GLFW_KEY_KP_EQUAL, [KEY_F13] = GLFW_KEY_F13, [KEY_F14] = GLFW_KEY_F14, [KEY_F15] = GLFW_KEY_F15, [KEY_F16] = GLFW_KEY_F16, [KEY_F17] = GLFW_KEY_F17, [KEY_F18] = GLFW_KEY_F18, [KEY_F19] = GLFW_KEY_F19, [KEY_F20] = GLFW_KEY_F20, [KEY_F21] = GLFW_KEY_F21, [KEY_F22] = GLFW_KEY_F22, [KEY_F23] = GLFW_KEY_F23, [KEY_F24] = GLFW_KEY_F24, [KEY_KPCOMMA] = GLFW_KEY_KP_DECIMAL, [KEY_LEFTCTRL] = GLFW_KEY_LEFT_CONTROL, [KEY_LEFTSHIFT] = GLFW_KEY_LEFT_SHIFT, [KEY_LEFTALT] = GLFW_KEY_LEFT_ALT, [KEY_LEFTMETA] = GLFW_KEY_LEFT_SUPER, [KEY_RIGHTCTRL] = GLFW_KEY_RIGHT_CONTROL, [KEY_RIGHTSHIFT] = GLFW_KEY_RIGHT_SHIFT, [KEY_RIGHTALT] = GLFW_KEY_RIGHT_ALT, [KEY_RIGHTMETA] = GLFW_KEY_RIGHT_SUPER }; platform_ctx *platform = (platform_ctx *)ctx; if (key < 0 || key > sizeof(key_lookup)/sizeof(key_lookup[0])) return 0; return glfwGetKey(platform->window, key_lookup[key]); } static void *glfw_get_proc_address(const char *procname) { return glfwGetProcAddress(procname); } static int glfw_extension_supported(const char *ext) { return glfwExtensionSupported(ext); } const platform glfw_platform = { glfw_init, glfw_release, glfw_pull_events, glfw_main_loop, glfw_swap_buffers, glfw_fullscreen, glfw_get_time, glfw_get_key, glfw_get_proc_address, glfw_extension_supported }; #endif
0760efc7f07e901054959826b953803856427d6d
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/third_party/python/Parser/myreadline.c
1a1fe1b7b700ee11a49fc818e8258dd5a45fde28
[ "ISC", "Python-2.0", "GPL-1.0-or-later", "LicenseRef-scancode-python-cwi", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-other-copyleft" ]
permissive
jart/cosmopolitan
fb11b5658939023977060a7c6c71a74093d9cb44
0d748ad58e1063dd1f8560f18a0c75293b9415b7
refs/heads/master
2023-09-06T09:17:29.303607
2023-09-02T03:49:13
2023-09-02T03:50:18
272,457,606
11,887
435
ISC
2023-09-14T17:47:58
2020-06-15T14:16:13
C
UTF-8
C
false
false
10,989
c
myreadline.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/errno.h" #include "libc/limits.h" #include "libc/log/log.h" #include "libc/stdio/stdio.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/intrcheck.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pystate.h" /* clang-format off */ /* Readline interface for tokenizer.c and [raw_]input() in bltinmodule.c. By default, or when stdin is not a tty device, we have a super simple my_readline function using fgets. Optionally, we can use the GNU readline library. my_readline() has a different return value from GNU readline(): - NULL if an interrupt occurred or if an error occurred - a malloc'ed empty string if EOF was read - a malloc'ed string ending in \n normally */ PyThreadState* _PyOS_ReadlineTState; #ifdef WITH_THREAD #include "third_party/python/Include/pythread.h" static PyThread_type_lock _PyOS_ReadlineLock = NULL; #endif int (*PyOS_InputHook)(void) = NULL; /* This function restarts a fgets() after an EINTR error occurred except if PyOS_InterruptOccurred() returns true. */ static int my_fgets(char *buf, int len, FILE *fp) { char *p; int err; while (1) { if (PyOS_InputHook != NULL) (void)(PyOS_InputHook)(); errno = 0; clearerr(fp); p = fgets(buf, len, fp); if (p != NULL) return 0; /* No error */ err = errno; if (feof(fp)) { clearerr(fp); return -1; /* EOF */ } #ifdef EINTR if (err == EINTR) { int s; #ifdef WITH_THREAD PyEval_RestoreThread(_PyOS_ReadlineTState); #endif s = PyErr_CheckSignals(); #ifdef WITH_THREAD PyEval_SaveThread(); #endif if (s < 0) return 1; /* try again */ continue; } #endif if (PyOS_InterruptOccurred()) { return 1; /* Interrupt */ } return -2; /* Error */ } /* NOTREACHED */ } #ifdef MS_WINDOWS /* Readline implementation using ReadConsoleW */ extern char _get_console_type(HANDLE handle); char * _PyOS_WindowsConsoleReadline(HANDLE hStdIn) { static wchar_t wbuf_local[1024 * 16]; const DWORD chunk_size = 1024; DWORD n_read, total_read, wbuflen, u8len; wchar_t *wbuf; char *buf = NULL; int err = 0; n_read = (DWORD)-1; total_read = 0; wbuf = wbuf_local; wbuflen = sizeof(wbuf_local) / sizeof(wbuf_local[0]) - 1; while (1) { if (PyOS_InputHook != NULL) { (void)(PyOS_InputHook)(); } if (!ReadConsoleW(hStdIn, &wbuf[total_read], wbuflen - total_read, &n_read, NULL)) { err = GetLastError(); goto exit; } if (n_read == (DWORD)-1 && (err = GetLastError()) == ERROR_OPERATION_ABORTED) { break; } if (n_read == 0) { int s; err = GetLastError(); if (err != ERROR_OPERATION_ABORTED) goto exit; err = 0; HANDLE hInterruptEvent = _PyOS_SigintEvent(); if (WaitForSingleObjectEx(hInterruptEvent, 100, FALSE) == WAIT_OBJECT_0) { ResetEvent(hInterruptEvent); #ifdef WITH_THREAD PyEval_RestoreThread(_PyOS_ReadlineTState); #endif s = PyErr_CheckSignals(); #ifdef WITH_THREAD PyEval_SaveThread(); #endif if (s < 0) goto exit; } break; } total_read += n_read; if (total_read == 0 || wbuf[total_read - 1] == L'\n') { break; } wbuflen += chunk_size; if (wbuf == wbuf_local) { wbuf[total_read] = '\0'; wbuf = (wchar_t*)PyMem_RawMalloc(wbuflen * sizeof(wchar_t)); if (wbuf) wcscpy_s(wbuf, wbuflen, wbuf_local); else { PyErr_NoMemory(); goto exit; } } else { wchar_t *tmp = PyMem_RawRealloc(wbuf, wbuflen * sizeof(wchar_t)); if (tmp == NULL) { PyErr_NoMemory(); goto exit; } wbuf = tmp; } } if (wbuf[0] == '\x1a') { buf = PyMem_RawMalloc(1); if (buf) buf[0] = '\0'; else { PyErr_NoMemory(); } goto exit; } u8len = WideCharToMultiByte(CP_UTF8, 0, wbuf, total_read, NULL, 0, NULL, NULL); buf = PyMem_RawMalloc(u8len + 1); if (buf == NULL) { PyErr_NoMemory(); goto exit; } u8len = WideCharToMultiByte(CP_UTF8, 0, wbuf, total_read, buf, u8len, NULL, NULL); buf[u8len] = '\0'; exit: if (wbuf != wbuf_local) PyMem_RawFree(wbuf); if (err) { #ifdef WITH_THREAD PyEval_RestoreThread(_PyOS_ReadlineTState); #endif PyErr_SetFromWindowsErr(err); #ifdef WITH_THREAD PyEval_SaveThread(); #endif } return buf; } #endif /* Readline implementation using fgets() */ char * PyOS_StdioReadline(FILE *sys_stdin, FILE *sys_stdout, const char *prompt) { size_t n; char *p, *pr; #ifdef MS_WINDOWS if (!Py_LegacyWindowsStdioFlag && sys_stdin == stdin) { HANDLE hStdIn, hStdErr; _Py_BEGIN_SUPPRESS_IPH hStdIn = (HANDLE)_get_osfhandle(fileno(sys_stdin)); hStdErr = (HANDLE)_get_osfhandle(fileno(stderr)); _Py_END_SUPPRESS_IPH if (_get_console_type(hStdIn) == 'r') { fflush(sys_stdout); if (prompt) { if (_get_console_type(hStdErr) == 'w') { wchar_t *wbuf; int wlen; wlen = MultiByteToWideChar(CP_UTF8, 0, prompt, -1, NULL, 0); if (wlen) { wbuf = PyMem_RawMalloc(wlen * sizeof(wchar_t)); if (wbuf == NULL) { PyErr_NoMemory(); return NULL; } wlen = MultiByteToWideChar(CP_UTF8, 0, prompt, -1, wbuf, wlen); if (wlen) { DWORD n; fflush(stderr); /* wlen includes null terminator, so subtract 1 */ WriteConsoleW(hStdErr, wbuf, wlen - 1, &n, NULL); } PyMem_RawFree(wbuf); } } else { fprintf(stderr, "%s", prompt); fflush(stderr); } } clearerr(sys_stdin); return _PyOS_WindowsConsoleReadline(hStdIn); } } #endif n = 100; p = (char *)PyMem_RawMalloc(n); if (p == NULL) { PyErr_NoMemory(); return NULL; } fflush(sys_stdout); if (prompt) fprintf(stderr, "%s", prompt); fflush(stderr); switch (my_fgets(p, (int)n, sys_stdin)) { case 0: /* Normal case */ break; case 1: /* Interrupt */ PyMem_RawFree(p); return NULL; case -1: /* EOF */ case -2: /* Error */ default: /* Shouldn't happen */ *p = '\0'; break; } n = strlen(p); while (n > 0 && p[n-1] != '\n') { size_t incr = n+2; if (incr > INT_MAX) { PyMem_RawFree(p); PyErr_SetString(PyExc_OverflowError, "input line too long"); return NULL; } pr = (char *)PyMem_RawRealloc(p, n + incr); if (pr == NULL) { PyMem_RawFree(p); PyErr_NoMemory(); return NULL; } p = pr; if (my_fgets(p+n, (int)incr, sys_stdin) != 0) break; n += strlen(p+n); } pr = (char *)PyMem_RawRealloc(p, n+1); if (pr == NULL) { PyMem_RawFree(p); PyErr_NoMemory(); return NULL; } return pr; } /* By initializing this function pointer, systems embedding Python can override the readline function. Note: Python expects in return a buffer allocated with PyMem_Malloc. */ char *(*PyOS_ReadlineFunctionPointer)(FILE *, FILE *, const char *); /* Interface used by tokenizer.c and bltinmodule.c */ char * PyOS_Readline(FILE *sys_stdin, FILE *sys_stdout, const char *prompt) { char *rv, *res; size_t len; if (_PyOS_ReadlineTState == PyThreadState_GET()) { PyErr_SetString(PyExc_RuntimeError, "can't re-enter readline"); return NULL; } if (PyOS_ReadlineFunctionPointer == NULL) { PyOS_ReadlineFunctionPointer = PyOS_StdioReadline; } #ifdef WITH_THREAD if (_PyOS_ReadlineLock == NULL) { _PyOS_ReadlineLock = PyThread_allocate_lock(); if (_PyOS_ReadlineLock == NULL) { PyErr_SetString(PyExc_MemoryError, "can't allocate lock"); return NULL; } } #endif _PyOS_ReadlineTState = PyThreadState_GET(); Py_BEGIN_ALLOW_THREADS #ifdef WITH_THREAD PyThread_acquire_lock(_PyOS_ReadlineLock, 1); #endif /* This is needed to handle the unlikely case that the * interpreter is in interactive mode *and* stdin/out are not * a tty. This can happen, for example if python is run like * this: python -i < test1.py */ if (!isatty (fileno (sys_stdin)) || !isatty (fileno (sys_stdout))) rv = PyOS_StdioReadline (sys_stdin, sys_stdout, prompt); else rv = (*PyOS_ReadlineFunctionPointer)(sys_stdin, sys_stdout, prompt); Py_END_ALLOW_THREADS #ifdef WITH_THREAD PyThread_release_lock(_PyOS_ReadlineLock); #endif _PyOS_ReadlineTState = NULL; if (rv == NULL) return NULL; len = strlen(rv) + 1; res = PyMem_Malloc(len); if (res != NULL) { memcpy(res, rv, len); } else { PyErr_NoMemory(); } PyMem_RawFree(rv); return res; }
2384fb533191f62c8e9a4e85cbd018ae84b13991
42ab733e143d02091d13424fb4df16379d5bba0d
/third_party/libsdl2/src/video/windows/SDL_windowskeyboard.c
c7f357b5931b620fce119c8792c1038224d3d9bd
[ "Apache-2.0", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference", "Zlib" ]
permissive
google/filament
11cd37ac68790fcf8b33416b7d8d8870e48181f0
0aa0efe1599798d887fa6e33c412c09e81bea1bf
refs/heads/main
2023-08-29T17:58:22.496956
2023-08-28T17:27:38
2023-08-28T17:27:38
143,455,116
16,631
1,961
Apache-2.0
2023-09-14T16:23:39
2018-08-03T17:26:00
C++
UTF-8
C
false
false
53,027
c
SDL_windowskeyboard.c
/* Simple DirectMedia Layer Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org> 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. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_WINDOWS #include "SDL_windowsvideo.h" #include "../../events/SDL_keyboard_c.h" #include "../../events/scancodes_windows.h" #include <imm.h> #include <oleauto.h> #ifndef SDL_DISABLE_WINDOWS_IME static void IME_Init(SDL_VideoData *videodata, HWND hwnd); static void IME_Enable(SDL_VideoData *videodata, HWND hwnd); static void IME_Disable(SDL_VideoData *videodata, HWND hwnd); static void IME_Quit(SDL_VideoData *videodata); #endif /* !SDL_DISABLE_WINDOWS_IME */ #ifndef MAPVK_VK_TO_VSC #define MAPVK_VK_TO_VSC 0 #endif #ifndef MAPVK_VSC_TO_VK #define MAPVK_VSC_TO_VK 1 #endif #ifndef MAPVK_VK_TO_CHAR #define MAPVK_VK_TO_CHAR 2 #endif /* Alphabetic scancodes for PC keyboards */ void WIN_InitKeyboard(_THIS) { SDL_VideoData *data = (SDL_VideoData *) _this->driverdata; data->ime_com_initialized = SDL_FALSE; data->ime_threadmgr = 0; data->ime_initialized = SDL_FALSE; data->ime_enabled = SDL_FALSE; data->ime_available = SDL_FALSE; data->ime_hwnd_main = 0; data->ime_hwnd_current = 0; data->ime_himc = 0; data->ime_composition[0] = 0; data->ime_readingstring[0] = 0; data->ime_cursor = 0; data->ime_candlist = SDL_FALSE; SDL_memset(data->ime_candidates, 0, sizeof(data->ime_candidates)); data->ime_candcount = 0; data->ime_candref = 0; data->ime_candsel = 0; data->ime_candpgsize = 0; data->ime_candlistindexbase = 0; data->ime_candvertical = SDL_TRUE; data->ime_dirty = SDL_FALSE; SDL_memset(&data->ime_rect, 0, sizeof(data->ime_rect)); SDL_memset(&data->ime_candlistrect, 0, sizeof(data->ime_candlistrect)); data->ime_winwidth = 0; data->ime_winheight = 0; data->ime_hkl = 0; data->ime_himm32 = 0; data->GetReadingString = 0; data->ShowReadingWindow = 0; data->ImmLockIMC = 0; data->ImmUnlockIMC = 0; data->ImmLockIMCC = 0; data->ImmUnlockIMCC = 0; data->ime_uiless = SDL_FALSE; data->ime_threadmgrex = 0; data->ime_uielemsinkcookie = TF_INVALID_COOKIE; data->ime_alpnsinkcookie = TF_INVALID_COOKIE; data->ime_openmodesinkcookie = TF_INVALID_COOKIE; data->ime_convmodesinkcookie = TF_INVALID_COOKIE; data->ime_uielemsink = 0; data->ime_ippasink = 0; WIN_UpdateKeymap(); SDL_SetScancodeName(SDL_SCANCODE_APPLICATION, "Menu"); SDL_SetScancodeName(SDL_SCANCODE_LGUI, "Left Windows"); SDL_SetScancodeName(SDL_SCANCODE_RGUI, "Right Windows"); /* Are system caps/num/scroll lock active? Set our state to match. */ SDL_ToggleModState(KMOD_CAPS, (GetKeyState(VK_CAPITAL) & 0x0001) != 0); SDL_ToggleModState(KMOD_NUM, (GetKeyState(VK_NUMLOCK) & 0x0001) != 0); } void WIN_UpdateKeymap() { int i; SDL_Scancode scancode; SDL_Keycode keymap[SDL_NUM_SCANCODES]; SDL_GetDefaultKeymap(keymap); for (i = 0; i < SDL_arraysize(windows_scancode_table); i++) { int vk; /* Make sure this scancode is a valid character scancode */ scancode = windows_scancode_table[i]; if (scancode == SDL_SCANCODE_UNKNOWN ) { continue; } /* If this key is one of the non-mappable keys, ignore it */ /* Not mapping numbers fixes the French layout, giving numeric keycodes for the number keys, which is the expected behavior */ if ((keymap[scancode] & SDLK_SCANCODE_MASK) || /* scancode == SDL_SCANCODE_GRAVE || */ /* Uncomment this line to re-enable the behavior of not mapping the "`"(grave) key to the users actual keyboard layout */ (scancode >= SDL_SCANCODE_1 && scancode <= SDL_SCANCODE_0) ) { continue; } vk = MapVirtualKey(i, MAPVK_VSC_TO_VK); if ( vk ) { int ch = (MapVirtualKey( vk, MAPVK_VK_TO_CHAR ) & 0x7FFF); if ( ch ) { if ( ch >= 'A' && ch <= 'Z' ) { keymap[scancode] = SDLK_a + ( ch - 'A' ); } else { keymap[scancode] = ch; } } } } SDL_SetKeymap(0, keymap, SDL_NUM_SCANCODES); } void WIN_QuitKeyboard(_THIS) { #ifndef SDL_DISABLE_WINDOWS_IME IME_Quit((SDL_VideoData *)_this->driverdata); #endif } void WIN_ResetDeadKeys() { /* if a deadkey has been typed, but not the next character (which the deadkey might modify), this tries to undo the effect pressing the deadkey. see: http://archives.miloush.net/michkap/archive/2006/09/10/748775.html */ BYTE keyboardState[256]; WCHAR buffer[16]; int keycode, scancode, result, i; GetKeyboardState(keyboardState); keycode = VK_SPACE; scancode = MapVirtualKey(keycode, MAPVK_VK_TO_VSC); if (scancode == 0) { /* the keyboard doesn't have this key */ return; } for (i = 0; i < 5; i++) { result = ToUnicode(keycode, scancode, keyboardState, (LPWSTR)buffer, 16, 0); if (result > 0) { /* success */ return; } } } void WIN_StartTextInput(_THIS) { #ifndef SDL_DISABLE_WINDOWS_IME SDL_Window *window; #endif WIN_ResetDeadKeys(); #ifndef SDL_DISABLE_WINDOWS_IME window = SDL_GetKeyboardFocus(); if (window) { HWND hwnd = ((SDL_WindowData *) window->driverdata)->hwnd; SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; SDL_GetWindowSize(window, &videodata->ime_winwidth, &videodata->ime_winheight); IME_Init(videodata, hwnd); IME_Enable(videodata, hwnd); } #endif /* !SDL_DISABLE_WINDOWS_IME */ } void WIN_StopTextInput(_THIS) { #ifndef SDL_DISABLE_WINDOWS_IME SDL_Window *window; #endif WIN_ResetDeadKeys(); #ifndef SDL_DISABLE_WINDOWS_IME window = SDL_GetKeyboardFocus(); if (window) { HWND hwnd = ((SDL_WindowData *) window->driverdata)->hwnd; SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; IME_Init(videodata, hwnd); IME_Disable(videodata, hwnd); } #endif /* !SDL_DISABLE_WINDOWS_IME */ } void WIN_SetTextInputRect(_THIS, SDL_Rect *rect) { SDL_VideoData *videodata = (SDL_VideoData *)_this->driverdata; HIMC himc = 0; if (!rect) { SDL_InvalidParamError("rect"); return; } videodata->ime_rect = *rect; himc = ImmGetContext(videodata->ime_hwnd_current); if (himc) { COMPOSITIONFORM cf; cf.ptCurrentPos.x = videodata->ime_rect.x; cf.ptCurrentPos.y = videodata->ime_rect.y; cf.dwStyle = CFS_FORCE_POSITION; ImmSetCompositionWindow(himc, &cf); ImmReleaseContext(videodata->ime_hwnd_current, himc); } } #ifdef SDL_DISABLE_WINDOWS_IME SDL_bool IME_HandleMessage(HWND hwnd, UINT msg, WPARAM wParam, LPARAM *lParam, SDL_VideoData *videodata) { return SDL_FALSE; } void IME_Present(SDL_VideoData *videodata) { } #else #ifdef SDL_msctf_h_ #define USE_INIT_GUID #elif defined(__GNUC__) #define USE_INIT_GUID #endif #ifdef USE_INIT_GUID #undef DEFINE_GUID #define DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) static const GUID n = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} DEFINE_GUID(IID_ITfInputProcessorProfileActivationSink, 0x71C6E74E,0x0F28,0x11D8,0xA8,0x2A,0x00,0x06,0x5B,0x84,0x43,0x5C); DEFINE_GUID(IID_ITfUIElementSink, 0xEA1EA136,0x19DF,0x11D7,0xA6,0xD2,0x00,0x06,0x5B,0x84,0x43,0x5C); DEFINE_GUID(GUID_TFCAT_TIP_KEYBOARD, 0x34745C63,0xB2F0,0x4784,0x8B,0x67,0x5E,0x12,0xC8,0x70,0x1A,0x31); DEFINE_GUID(IID_ITfSource, 0x4EA48A35,0x60AE,0x446F,0x8F,0xD6,0xE6,0xA8,0xD8,0x24,0x59,0xF7); DEFINE_GUID(IID_ITfUIElementMgr, 0xEA1EA135,0x19DF,0x11D7,0xA6,0xD2,0x00,0x06,0x5B,0x84,0x43,0x5C); DEFINE_GUID(IID_ITfCandidateListUIElement, 0xEA1EA138,0x19DF,0x11D7,0xA6,0xD2,0x00,0x06,0x5B,0x84,0x43,0x5C); DEFINE_GUID(IID_ITfReadingInformationUIElement, 0xEA1EA139,0x19DF,0x11D7,0xA6,0xD2,0x00,0x06,0x5B,0x84,0x43,0x5C); DEFINE_GUID(IID_ITfThreadMgr, 0xAA80E801,0x2021,0x11D2,0x93,0xE0,0x00,0x60,0xB0,0x67,0xB8,0x6E); DEFINE_GUID(CLSID_TF_ThreadMgr, 0x529A9E6B,0x6587,0x4F23,0xAB,0x9E,0x9C,0x7D,0x68,0x3E,0x3C,0x50); DEFINE_GUID(IID_ITfThreadMgrEx, 0x3E90ADE3,0x7594,0x4CB0,0xBB,0x58,0x69,0x62,0x8F,0x5F,0x45,0x8C); #endif #define LANG_CHT MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL) #define LANG_CHS MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED) #define MAKEIMEVERSION(major,minor) ((DWORD) (((BYTE)(major) << 24) | ((BYTE)(minor) << 16) )) #define IMEID_VER(id) ((id) & 0xffff0000) #define IMEID_LANG(id) ((id) & 0x0000ffff) #define CHT_HKL_DAYI ((HKL)(UINT_PTR)0xE0060404) #define CHT_HKL_NEW_PHONETIC ((HKL)(UINT_PTR)0xE0080404) #define CHT_HKL_NEW_CHANG_JIE ((HKL)(UINT_PTR)0xE0090404) #define CHT_HKL_NEW_QUICK ((HKL)(UINT_PTR)0xE00A0404) #define CHT_HKL_HK_CANTONESE ((HKL)(UINT_PTR)0xE00B0404) #define CHT_IMEFILENAME1 "TINTLGNT.IME" #define CHT_IMEFILENAME2 "CINTLGNT.IME" #define CHT_IMEFILENAME3 "MSTCIPHA.IME" #define IMEID_CHT_VER42 (LANG_CHT | MAKEIMEVERSION(4, 2)) #define IMEID_CHT_VER43 (LANG_CHT | MAKEIMEVERSION(4, 3)) #define IMEID_CHT_VER44 (LANG_CHT | MAKEIMEVERSION(4, 4)) #define IMEID_CHT_VER50 (LANG_CHT | MAKEIMEVERSION(5, 0)) #define IMEID_CHT_VER51 (LANG_CHT | MAKEIMEVERSION(5, 1)) #define IMEID_CHT_VER52 (LANG_CHT | MAKEIMEVERSION(5, 2)) #define IMEID_CHT_VER60 (LANG_CHT | MAKEIMEVERSION(6, 0)) #define IMEID_CHT_VER_VISTA (LANG_CHT | MAKEIMEVERSION(7, 0)) #define CHS_HKL ((HKL)(UINT_PTR)0xE00E0804) #define CHS_IMEFILENAME1 "PINTLGNT.IME" #define CHS_IMEFILENAME2 "MSSCIPYA.IME" #define IMEID_CHS_VER41 (LANG_CHS | MAKEIMEVERSION(4, 1)) #define IMEID_CHS_VER42 (LANG_CHS | MAKEIMEVERSION(4, 2)) #define IMEID_CHS_VER53 (LANG_CHS | MAKEIMEVERSION(5, 3)) #define LANG() LOWORD((videodata->ime_hkl)) #define PRIMLANG() ((WORD)PRIMARYLANGID(LANG())) #define SUBLANG() SUBLANGID(LANG()) static void IME_UpdateInputLocale(SDL_VideoData *videodata); static void IME_ClearComposition(SDL_VideoData *videodata); static void IME_SetWindow(SDL_VideoData* videodata, HWND hwnd); static void IME_SetupAPI(SDL_VideoData *videodata); static DWORD IME_GetId(SDL_VideoData *videodata, UINT uIndex); static void IME_SendEditingEvent(SDL_VideoData *videodata); static void IME_DestroyTextures(SDL_VideoData *videodata); static SDL_bool UILess_SetupSinks(SDL_VideoData *videodata); static void UILess_ReleaseSinks(SDL_VideoData *videodata); static void UILess_EnableUIUpdates(SDL_VideoData *videodata); static void UILess_DisableUIUpdates(SDL_VideoData *videodata); static void IME_Init(SDL_VideoData *videodata, HWND hwnd) { if (videodata->ime_initialized) return; videodata->ime_hwnd_main = hwnd; if (SUCCEEDED(WIN_CoInitialize())) { videodata->ime_com_initialized = SDL_TRUE; CoCreateInstance(&CLSID_TF_ThreadMgr, NULL, CLSCTX_INPROC_SERVER, &IID_ITfThreadMgr, (LPVOID *)&videodata->ime_threadmgr); } videodata->ime_initialized = SDL_TRUE; videodata->ime_himm32 = SDL_LoadObject("imm32.dll"); if (!videodata->ime_himm32) { videodata->ime_available = SDL_FALSE; SDL_ClearError(); return; } videodata->ImmLockIMC = (LPINPUTCONTEXT2 (WINAPI *)(HIMC))SDL_LoadFunction(videodata->ime_himm32, "ImmLockIMC"); videodata->ImmUnlockIMC = (BOOL (WINAPI *)(HIMC))SDL_LoadFunction(videodata->ime_himm32, "ImmUnlockIMC"); videodata->ImmLockIMCC = (LPVOID (WINAPI *)(HIMCC))SDL_LoadFunction(videodata->ime_himm32, "ImmLockIMCC"); videodata->ImmUnlockIMCC = (BOOL (WINAPI *)(HIMCC))SDL_LoadFunction(videodata->ime_himm32, "ImmUnlockIMCC"); IME_SetWindow(videodata, hwnd); videodata->ime_himc = ImmGetContext(hwnd); ImmReleaseContext(hwnd, videodata->ime_himc); if (!videodata->ime_himc) { videodata->ime_available = SDL_FALSE; IME_Disable(videodata, hwnd); return; } videodata->ime_available = SDL_TRUE; IME_UpdateInputLocale(videodata); IME_SetupAPI(videodata); videodata->ime_uiless = UILess_SetupSinks(videodata); IME_UpdateInputLocale(videodata); IME_Disable(videodata, hwnd); } static void IME_Enable(SDL_VideoData *videodata, HWND hwnd) { if (!videodata->ime_initialized || !videodata->ime_hwnd_current) return; if (!videodata->ime_available) { IME_Disable(videodata, hwnd); return; } if (videodata->ime_hwnd_current == videodata->ime_hwnd_main) ImmAssociateContext(videodata->ime_hwnd_current, videodata->ime_himc); videodata->ime_enabled = SDL_TRUE; IME_UpdateInputLocale(videodata); UILess_EnableUIUpdates(videodata); } static void IME_Disable(SDL_VideoData *videodata, HWND hwnd) { if (!videodata->ime_initialized || !videodata->ime_hwnd_current) return; IME_ClearComposition(videodata); if (videodata->ime_hwnd_current == videodata->ime_hwnd_main) ImmAssociateContext(videodata->ime_hwnd_current, (HIMC)0); videodata->ime_enabled = SDL_FALSE; UILess_DisableUIUpdates(videodata); } static void IME_Quit(SDL_VideoData *videodata) { if (!videodata->ime_initialized) return; UILess_ReleaseSinks(videodata); if (videodata->ime_hwnd_main) ImmAssociateContext(videodata->ime_hwnd_main, videodata->ime_himc); videodata->ime_hwnd_main = 0; videodata->ime_himc = 0; if (videodata->ime_himm32) { SDL_UnloadObject(videodata->ime_himm32); videodata->ime_himm32 = 0; } if (videodata->ime_threadmgr) { videodata->ime_threadmgr->lpVtbl->Release(videodata->ime_threadmgr); videodata->ime_threadmgr = 0; } if (videodata->ime_com_initialized) { WIN_CoUninitialize(); videodata->ime_com_initialized = SDL_FALSE; } IME_DestroyTextures(videodata); videodata->ime_initialized = SDL_FALSE; } static void IME_GetReadingString(SDL_VideoData *videodata, HWND hwnd) { DWORD id = 0; HIMC himc = 0; WCHAR buffer[16]; WCHAR *s = buffer; DWORD len = 0; INT err = 0; BOOL vertical = FALSE; UINT maxuilen = 0; if (videodata->ime_uiless) return; videodata->ime_readingstring[0] = 0; id = IME_GetId(videodata, 0); if (!id) return; himc = ImmGetContext(hwnd); if (!himc) return; if (videodata->GetReadingString) { len = videodata->GetReadingString(himc, 0, 0, &err, &vertical, &maxuilen); if (len) { if (len > SDL_arraysize(buffer)) len = SDL_arraysize(buffer); len = videodata->GetReadingString(himc, len, s, &err, &vertical, &maxuilen); } SDL_wcslcpy(videodata->ime_readingstring, s, len); } else { LPINPUTCONTEXT2 lpimc = videodata->ImmLockIMC(himc); LPBYTE p = 0; s = 0; switch (id) { case IMEID_CHT_VER42: case IMEID_CHT_VER43: case IMEID_CHT_VER44: p = *(LPBYTE *)((LPBYTE)videodata->ImmLockIMCC(lpimc->hPrivate) + 24); if (!p) break; len = *(DWORD *)(p + 7*4 + 32*4); s = (WCHAR *)(p + 56); break; case IMEID_CHT_VER51: case IMEID_CHT_VER52: case IMEID_CHS_VER53: p = *(LPBYTE *)((LPBYTE)videodata->ImmLockIMCC(lpimc->hPrivate) + 4); if (!p) break; p = *(LPBYTE *)((LPBYTE)p + 1*4 + 5*4); if (!p) break; len = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16*2); s = (WCHAR *)(p + 1*4 + (16*2+2*4) + 5*4); break; case IMEID_CHS_VER41: { int offset = (IME_GetId(videodata, 1) >= 0x00000002) ? 8 : 7; p = *(LPBYTE *)((LPBYTE)videodata->ImmLockIMCC(lpimc->hPrivate) + offset * 4); if (!p) break; len = *(DWORD *)(p + 7*4 + 16*2*4); s = (WCHAR *)(p + 6*4 + 16*2*1); } break; case IMEID_CHS_VER42: p = *(LPBYTE *)((LPBYTE)videodata->ImmLockIMCC(lpimc->hPrivate) + 1*4 + 1*4 + 6*4); if (!p) break; len = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16*2); s = (WCHAR *)(p + 1*4 + (16*2+2*4) + 5*4); break; } if (s) { size_t size = SDL_min((size_t)(len + 1), SDL_arraysize(videodata->ime_readingstring)); SDL_wcslcpy(videodata->ime_readingstring, s, size); } videodata->ImmUnlockIMCC(lpimc->hPrivate); videodata->ImmUnlockIMC(himc); } ImmReleaseContext(hwnd, himc); IME_SendEditingEvent(videodata); } static void IME_InputLangChanged(SDL_VideoData *videodata) { UINT lang = PRIMLANG(); IME_UpdateInputLocale(videodata); if (!videodata->ime_uiless) videodata->ime_candlistindexbase = (videodata->ime_hkl == CHT_HKL_DAYI) ? 0 : 1; IME_SetupAPI(videodata); if (lang != PRIMLANG()) { IME_ClearComposition(videodata); } } static DWORD IME_GetId(SDL_VideoData *videodata, UINT uIndex) { static HKL hklprev = 0; static DWORD dwRet[2] = {0}; DWORD dwVerSize = 0; DWORD dwVerHandle = 0; LPVOID lpVerBuffer = 0; LPVOID lpVerData = 0; UINT cbVerData = 0; char szTemp[256]; HKL hkl = 0; DWORD dwLang = 0; if (uIndex >= sizeof(dwRet) / sizeof(dwRet[0])) return 0; hkl = videodata->ime_hkl; if (hklprev == hkl) return dwRet[uIndex]; hklprev = hkl; dwLang = ((DWORD_PTR)hkl & 0xffff); if (videodata->ime_uiless && LANG() == LANG_CHT) { dwRet[0] = IMEID_CHT_VER_VISTA; dwRet[1] = 0; return dwRet[0]; } if (hkl != CHT_HKL_NEW_PHONETIC && hkl != CHT_HKL_NEW_CHANG_JIE && hkl != CHT_HKL_NEW_QUICK && hkl != CHT_HKL_HK_CANTONESE && hkl != CHS_HKL) { dwRet[0] = dwRet[1] = 0; return dwRet[uIndex]; } if (ImmGetIMEFileNameA(hkl, szTemp, sizeof(szTemp) - 1) <= 0) { dwRet[0] = dwRet[1] = 0; return dwRet[uIndex]; } if (!videodata->GetReadingString) { #define LCID_INVARIANT MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT) if (CompareStringA(LCID_INVARIANT, NORM_IGNORECASE, szTemp, -1, CHT_IMEFILENAME1, -1) != 2 && CompareStringA(LCID_INVARIANT, NORM_IGNORECASE, szTemp, -1, CHT_IMEFILENAME2, -1) != 2 && CompareStringA(LCID_INVARIANT, NORM_IGNORECASE, szTemp, -1, CHT_IMEFILENAME3, -1) != 2 && CompareStringA(LCID_INVARIANT, NORM_IGNORECASE, szTemp, -1, CHS_IMEFILENAME1, -1) != 2 && CompareStringA(LCID_INVARIANT, NORM_IGNORECASE, szTemp, -1, CHS_IMEFILENAME2, -1) != 2) { dwRet[0] = dwRet[1] = 0; return dwRet[uIndex]; } #undef LCID_INVARIANT dwVerSize = GetFileVersionInfoSizeA(szTemp, &dwVerHandle); if (dwVerSize) { lpVerBuffer = SDL_malloc(dwVerSize); if (lpVerBuffer) { if (GetFileVersionInfoA(szTemp, dwVerHandle, dwVerSize, lpVerBuffer)) { if (VerQueryValueA(lpVerBuffer, "\\", &lpVerData, &cbVerData)) { #define pVerFixedInfo ((VS_FIXEDFILEINFO FAR*)lpVerData) DWORD dwVer = pVerFixedInfo->dwFileVersionMS; dwVer = (dwVer & 0x00ff0000) << 8 | (dwVer & 0x000000ff) << 16; if ((videodata->GetReadingString) || ((dwLang == LANG_CHT) && ( dwVer == MAKEIMEVERSION(4, 2) || dwVer == MAKEIMEVERSION(4, 3) || dwVer == MAKEIMEVERSION(4, 4) || dwVer == MAKEIMEVERSION(5, 0) || dwVer == MAKEIMEVERSION(5, 1) || dwVer == MAKEIMEVERSION(5, 2) || dwVer == MAKEIMEVERSION(6, 0))) || ((dwLang == LANG_CHS) && ( dwVer == MAKEIMEVERSION(4, 1) || dwVer == MAKEIMEVERSION(4, 2) || dwVer == MAKEIMEVERSION(5, 3)))) { dwRet[0] = dwVer | dwLang; dwRet[1] = pVerFixedInfo->dwFileVersionLS; SDL_free(lpVerBuffer); return dwRet[0]; } #undef pVerFixedInfo } } } SDL_free(lpVerBuffer); } } dwRet[0] = dwRet[1] = 0; return dwRet[uIndex]; } static void IME_SetupAPI(SDL_VideoData *videodata) { char ime_file[MAX_PATH + 1]; void* hime = 0; HKL hkl = 0; videodata->GetReadingString = 0; videodata->ShowReadingWindow = 0; if (videodata->ime_uiless) return; hkl = videodata->ime_hkl; if (ImmGetIMEFileNameA(hkl, ime_file, sizeof(ime_file) - 1) <= 0) return; hime = SDL_LoadObject(ime_file); if (!hime) return; videodata->GetReadingString = (UINT (WINAPI *)(HIMC, UINT, LPWSTR, PINT, BOOL*, PUINT)) SDL_LoadFunction(hime, "GetReadingString"); videodata->ShowReadingWindow = (BOOL (WINAPI *)(HIMC, BOOL)) SDL_LoadFunction(hime, "ShowReadingWindow"); if (videodata->ShowReadingWindow) { HIMC himc = ImmGetContext(videodata->ime_hwnd_current); if (himc) { videodata->ShowReadingWindow(himc, FALSE); ImmReleaseContext(videodata->ime_hwnd_current, himc); } } } static void IME_SetWindow(SDL_VideoData* videodata, HWND hwnd) { videodata->ime_hwnd_current = hwnd; if (videodata->ime_threadmgr) { struct ITfDocumentMgr *document_mgr = 0; if (SUCCEEDED(videodata->ime_threadmgr->lpVtbl->AssociateFocus(videodata->ime_threadmgr, hwnd, NULL, &document_mgr))) { if (document_mgr) document_mgr->lpVtbl->Release(document_mgr); } } } static void IME_UpdateInputLocale(SDL_VideoData *videodata) { static HKL hklprev = 0; videodata->ime_hkl = GetKeyboardLayout(0); if (hklprev == videodata->ime_hkl) return; hklprev = videodata->ime_hkl; switch (PRIMLANG()) { case LANG_CHINESE: videodata->ime_candvertical = SDL_TRUE; if (SUBLANG() == SUBLANG_CHINESE_SIMPLIFIED) videodata->ime_candvertical = SDL_FALSE; break; case LANG_JAPANESE: videodata->ime_candvertical = SDL_TRUE; break; case LANG_KOREAN: videodata->ime_candvertical = SDL_FALSE; break; } } static void IME_ClearComposition(SDL_VideoData *videodata) { HIMC himc = 0; if (!videodata->ime_initialized) return; himc = ImmGetContext(videodata->ime_hwnd_current); if (!himc) return; ImmNotifyIME(himc, NI_COMPOSITIONSTR, CPS_CANCEL, 0); if (videodata->ime_uiless) ImmSetCompositionString(himc, SCS_SETSTR, TEXT(""), sizeof(TCHAR), TEXT(""), sizeof(TCHAR)); ImmNotifyIME(himc, NI_CLOSECANDIDATE, 0, 0); ImmReleaseContext(videodata->ime_hwnd_current, himc); SDL_SendEditingText("", 0, 0); } static void IME_GetCompositionString(SDL_VideoData *videodata, HIMC himc, DWORD string) { LONG length = ImmGetCompositionStringW(himc, string, videodata->ime_composition, sizeof(videodata->ime_composition) - sizeof(videodata->ime_composition[0])); if (length < 0) length = 0; length /= sizeof(videodata->ime_composition[0]); videodata->ime_cursor = LOWORD(ImmGetCompositionStringW(himc, GCS_CURSORPOS, 0, 0)); if (videodata->ime_cursor < SDL_arraysize(videodata->ime_composition) && videodata->ime_composition[videodata->ime_cursor] == 0x3000) { int i; for (i = videodata->ime_cursor + 1; i < length; ++i) videodata->ime_composition[i - 1] = videodata->ime_composition[i]; --length; } videodata->ime_composition[length] = 0; } static void IME_SendInputEvent(SDL_VideoData *videodata) { char *s = 0; s = WIN_StringToUTF8(videodata->ime_composition); SDL_SendKeyboardText(s); SDL_free(s); videodata->ime_composition[0] = 0; videodata->ime_readingstring[0] = 0; videodata->ime_cursor = 0; } static void IME_SendEditingEvent(SDL_VideoData *videodata) { char *s = 0; WCHAR buffer[SDL_TEXTEDITINGEVENT_TEXT_SIZE]; const size_t size = SDL_arraysize(buffer); buffer[0] = 0; if (videodata->ime_readingstring[0]) { size_t len = SDL_min(SDL_wcslen(videodata->ime_composition), (size_t)videodata->ime_cursor); SDL_wcslcpy(buffer, videodata->ime_composition, len + 1); SDL_wcslcat(buffer, videodata->ime_readingstring, size); SDL_wcslcat(buffer, &videodata->ime_composition[len], size); } else { SDL_wcslcpy(buffer, videodata->ime_composition, size); } s = WIN_StringToUTF8(buffer); SDL_SendEditingText(s, videodata->ime_cursor + (int)SDL_wcslen(videodata->ime_readingstring), 0); SDL_free(s); } static void IME_AddCandidate(SDL_VideoData *videodata, UINT i, LPCWSTR candidate) { LPWSTR dst = videodata->ime_candidates[i]; *dst++ = (WCHAR)(TEXT('0') + ((i + videodata->ime_candlistindexbase) % 10)); if (videodata->ime_candvertical) *dst++ = TEXT(' '); while (*candidate && (SDL_arraysize(videodata->ime_candidates[i]) > (dst - videodata->ime_candidates[i]))) *dst++ = *candidate++; *dst = (WCHAR)'\0'; } static void IME_GetCandidateList(HIMC himc, SDL_VideoData *videodata) { LPCANDIDATELIST cand_list = 0; DWORD size = ImmGetCandidateListW(himc, 0, 0, 0); if (size) { cand_list = (LPCANDIDATELIST)SDL_malloc(size); if (cand_list) { size = ImmGetCandidateListW(himc, 0, cand_list, size); if (size) { UINT i, j; UINT page_start = 0; videodata->ime_candsel = cand_list->dwSelection; videodata->ime_candcount = cand_list->dwCount; if (LANG() == LANG_CHS && IME_GetId(videodata, 0)) { const UINT maxcandchar = 18; size_t cchars = 0; for (i = 0; i < videodata->ime_candcount; ++i) { size_t len = SDL_wcslen((LPWSTR)((DWORD_PTR)cand_list + cand_list->dwOffset[i])) + 1; if (len + cchars > maxcandchar) { if (i > cand_list->dwSelection) break; page_start = i; cchars = len; } else { cchars += len; } } videodata->ime_candpgsize = i - page_start; } else { videodata->ime_candpgsize = SDL_min(cand_list->dwPageSize, MAX_CANDLIST); if (videodata->ime_candpgsize > 0) { page_start = (cand_list->dwSelection / videodata->ime_candpgsize) * videodata->ime_candpgsize; } else { page_start = 0; } } SDL_memset(&videodata->ime_candidates, 0, sizeof(videodata->ime_candidates)); for (i = page_start, j = 0; (DWORD)i < cand_list->dwCount && j < (int)videodata->ime_candpgsize; i++, j++) { LPCWSTR candidate = (LPCWSTR)((DWORD_PTR)cand_list + cand_list->dwOffset[i]); IME_AddCandidate(videodata, j, candidate); } if (PRIMLANG() == LANG_KOREAN || (PRIMLANG() == LANG_CHT && !IME_GetId(videodata, 0))) videodata->ime_candsel = -1; } SDL_free(cand_list); } } } static void IME_ShowCandidateList(SDL_VideoData *videodata) { videodata->ime_dirty = SDL_TRUE; videodata->ime_candlist = SDL_TRUE; IME_DestroyTextures(videodata); IME_SendEditingEvent(videodata); } static void IME_HideCandidateList(SDL_VideoData *videodata) { videodata->ime_dirty = SDL_FALSE; videodata->ime_candlist = SDL_FALSE; IME_DestroyTextures(videodata); IME_SendEditingEvent(videodata); } SDL_bool IME_HandleMessage(HWND hwnd, UINT msg, WPARAM wParam, LPARAM *lParam, SDL_VideoData *videodata) { SDL_bool trap = SDL_FALSE; HIMC himc = 0; if (!videodata->ime_initialized || !videodata->ime_available || !videodata->ime_enabled) return SDL_FALSE; switch (msg) { case WM_INPUTLANGCHANGE: IME_InputLangChanged(videodata); break; case WM_IME_SETCONTEXT: *lParam = 0; break; case WM_IME_STARTCOMPOSITION: trap = SDL_TRUE; break; case WM_IME_COMPOSITION: trap = SDL_TRUE; himc = ImmGetContext(hwnd); if (*lParam & GCS_RESULTSTR) { IME_GetCompositionString(videodata, himc, GCS_RESULTSTR); IME_SendInputEvent(videodata); } if (*lParam & GCS_COMPSTR) { if (!videodata->ime_uiless) videodata->ime_readingstring[0] = 0; IME_GetCompositionString(videodata, himc, GCS_COMPSTR); IME_SendEditingEvent(videodata); } ImmReleaseContext(hwnd, himc); break; case WM_IME_ENDCOMPOSITION: videodata->ime_composition[0] = 0; videodata->ime_readingstring[0] = 0; videodata->ime_cursor = 0; SDL_SendEditingText("", 0, 0); break; case WM_IME_NOTIFY: switch (wParam) { case IMN_SETCONVERSIONMODE: case IMN_SETOPENSTATUS: IME_UpdateInputLocale(videodata); break; case IMN_OPENCANDIDATE: case IMN_CHANGECANDIDATE: if (videodata->ime_uiless) break; trap = SDL_TRUE; IME_ShowCandidateList(videodata); himc = ImmGetContext(hwnd); if (!himc) break; IME_GetCandidateList(himc, videodata); ImmReleaseContext(hwnd, himc); break; case IMN_CLOSECANDIDATE: trap = SDL_TRUE; IME_HideCandidateList(videodata); break; case IMN_PRIVATE: { DWORD dwId = IME_GetId(videodata, 0); IME_GetReadingString(videodata, hwnd); switch (dwId) { case IMEID_CHT_VER42: case IMEID_CHT_VER43: case IMEID_CHT_VER44: case IMEID_CHS_VER41: case IMEID_CHS_VER42: if (*lParam == 1 || *lParam == 2) trap = SDL_TRUE; break; case IMEID_CHT_VER50: case IMEID_CHT_VER51: case IMEID_CHT_VER52: case IMEID_CHT_VER60: case IMEID_CHS_VER53: if (*lParam == 16 || *lParam == 17 || *lParam == 26 || *lParam == 27 || *lParam == 28) trap = SDL_TRUE; break; } } break; default: trap = SDL_TRUE; break; } break; } return trap; } static void IME_CloseCandidateList(SDL_VideoData *videodata) { IME_HideCandidateList(videodata); videodata->ime_candcount = 0; SDL_memset(videodata->ime_candidates, 0, sizeof(videodata->ime_candidates)); } static void UILess_GetCandidateList(SDL_VideoData *videodata, ITfCandidateListUIElement *pcandlist) { UINT selection = 0; UINT count = 0; UINT page = 0; UINT pgcount = 0; DWORD pgstart = 0; DWORD pgsize = 0; UINT i, j; pcandlist->lpVtbl->GetSelection(pcandlist, &selection); pcandlist->lpVtbl->GetCount(pcandlist, &count); pcandlist->lpVtbl->GetCurrentPage(pcandlist, &page); videodata->ime_candsel = selection; videodata->ime_candcount = count; IME_ShowCandidateList(videodata); pcandlist->lpVtbl->GetPageIndex(pcandlist, 0, 0, &pgcount); if (pgcount > 0) { UINT *idxlist = SDL_malloc(sizeof(UINT) * pgcount); if (idxlist) { pcandlist->lpVtbl->GetPageIndex(pcandlist, idxlist, pgcount, &pgcount); pgstart = idxlist[page]; if (page < pgcount - 1) pgsize = SDL_min(count, idxlist[page + 1]) - pgstart; else pgsize = count - pgstart; SDL_free(idxlist); } } videodata->ime_candpgsize = SDL_min(pgsize, MAX_CANDLIST); videodata->ime_candsel = videodata->ime_candsel - pgstart; SDL_memset(videodata->ime_candidates, 0, sizeof(videodata->ime_candidates)); for (i = pgstart, j = 0; (DWORD)i < count && j < videodata->ime_candpgsize; i++, j++) { BSTR bstr; if (SUCCEEDED(pcandlist->lpVtbl->GetString(pcandlist, i, &bstr))) { if (bstr) { IME_AddCandidate(videodata, j, bstr); SysFreeString(bstr); } } } if (PRIMLANG() == LANG_KOREAN) videodata->ime_candsel = -1; } STDMETHODIMP_(ULONG) TSFSink_AddRef(TSFSink *sink) { return ++sink->refcount; } STDMETHODIMP_(ULONG) TSFSink_Release(TSFSink *sink) { --sink->refcount; if (sink->refcount == 0) { SDL_free(sink); return 0; } return sink->refcount; } STDMETHODIMP UIElementSink_QueryInterface(TSFSink *sink, REFIID riid, PVOID *ppv) { if (!ppv) return E_INVALIDARG; *ppv = 0; if (WIN_IsEqualIID(riid, &IID_IUnknown)) *ppv = (IUnknown *)sink; else if (WIN_IsEqualIID(riid, &IID_ITfUIElementSink)) *ppv = (ITfUIElementSink *)sink; if (*ppv) { TSFSink_AddRef(sink); return S_OK; } return E_NOINTERFACE; } ITfUIElement *UILess_GetUIElement(SDL_VideoData *videodata, DWORD dwUIElementId) { ITfUIElementMgr *puiem = 0; ITfUIElement *pelem = 0; ITfThreadMgrEx *threadmgrex = videodata->ime_threadmgrex; if (SUCCEEDED(threadmgrex->lpVtbl->QueryInterface(threadmgrex, &IID_ITfUIElementMgr, (LPVOID *)&puiem))) { puiem->lpVtbl->GetUIElement(puiem, dwUIElementId, &pelem); puiem->lpVtbl->Release(puiem); } return pelem; } STDMETHODIMP UIElementSink_BeginUIElement(TSFSink *sink, DWORD dwUIElementId, BOOL *pbShow) { ITfUIElement *element = UILess_GetUIElement((SDL_VideoData *)sink->data, dwUIElementId); ITfReadingInformationUIElement *preading = 0; ITfCandidateListUIElement *pcandlist = 0; SDL_VideoData *videodata = (SDL_VideoData *)sink->data; if (!element) return E_INVALIDARG; *pbShow = FALSE; if (SUCCEEDED(element->lpVtbl->QueryInterface(element, &IID_ITfReadingInformationUIElement, (LPVOID *)&preading))) { BSTR bstr; if (SUCCEEDED(preading->lpVtbl->GetString(preading, &bstr)) && bstr) { SysFreeString(bstr); } preading->lpVtbl->Release(preading); } else if (SUCCEEDED(element->lpVtbl->QueryInterface(element, &IID_ITfCandidateListUIElement, (LPVOID *)&pcandlist))) { videodata->ime_candref++; UILess_GetCandidateList(videodata, pcandlist); pcandlist->lpVtbl->Release(pcandlist); } return S_OK; } STDMETHODIMP UIElementSink_UpdateUIElement(TSFSink *sink, DWORD dwUIElementId) { ITfUIElement *element = UILess_GetUIElement((SDL_VideoData *)sink->data, dwUIElementId); ITfReadingInformationUIElement *preading = 0; ITfCandidateListUIElement *pcandlist = 0; SDL_VideoData *videodata = (SDL_VideoData *)sink->data; if (!element) return E_INVALIDARG; if (SUCCEEDED(element->lpVtbl->QueryInterface(element, &IID_ITfReadingInformationUIElement, (LPVOID *)&preading))) { BSTR bstr; if (SUCCEEDED(preading->lpVtbl->GetString(preading, &bstr)) && bstr) { WCHAR *s = (WCHAR *)bstr; SDL_wcslcpy(videodata->ime_readingstring, s, SDL_arraysize(videodata->ime_readingstring)); IME_SendEditingEvent(videodata); SysFreeString(bstr); } preading->lpVtbl->Release(preading); } else if (SUCCEEDED(element->lpVtbl->QueryInterface(element, &IID_ITfCandidateListUIElement, (LPVOID *)&pcandlist))) { UILess_GetCandidateList(videodata, pcandlist); pcandlist->lpVtbl->Release(pcandlist); } return S_OK; } STDMETHODIMP UIElementSink_EndUIElement(TSFSink *sink, DWORD dwUIElementId) { ITfUIElement *element = UILess_GetUIElement((SDL_VideoData *)sink->data, dwUIElementId); ITfReadingInformationUIElement *preading = 0; ITfCandidateListUIElement *pcandlist = 0; SDL_VideoData *videodata = (SDL_VideoData *)sink->data; if (!element) return E_INVALIDARG; if (SUCCEEDED(element->lpVtbl->QueryInterface(element, &IID_ITfReadingInformationUIElement, (LPVOID *)&preading))) { videodata->ime_readingstring[0] = 0; IME_SendEditingEvent(videodata); preading->lpVtbl->Release(preading); } if (SUCCEEDED(element->lpVtbl->QueryInterface(element, &IID_ITfCandidateListUIElement, (LPVOID *)&pcandlist))) { videodata->ime_candref--; if (videodata->ime_candref == 0) IME_CloseCandidateList(videodata); pcandlist->lpVtbl->Release(pcandlist); } return S_OK; } STDMETHODIMP IPPASink_QueryInterface(TSFSink *sink, REFIID riid, PVOID *ppv) { if (!ppv) return E_INVALIDARG; *ppv = 0; if (WIN_IsEqualIID(riid, &IID_IUnknown)) *ppv = (IUnknown *)sink; else if (WIN_IsEqualIID(riid, &IID_ITfInputProcessorProfileActivationSink)) *ppv = (ITfInputProcessorProfileActivationSink *)sink; if (*ppv) { TSFSink_AddRef(sink); return S_OK; } return E_NOINTERFACE; } STDMETHODIMP IPPASink_OnActivated(TSFSink *sink, DWORD dwProfileType, LANGID langid, REFCLSID clsid, REFGUID catid, REFGUID guidProfile, HKL hkl, DWORD dwFlags) { static const GUID TF_PROFILE_DAYI = { 0x037B2C25, 0x480C, 0x4D7F, { 0xB0, 0x27, 0xD6, 0xCA, 0x6B, 0x69, 0x78, 0x8A } }; SDL_VideoData *videodata = (SDL_VideoData *)sink->data; videodata->ime_candlistindexbase = WIN_IsEqualGUID(&TF_PROFILE_DAYI, guidProfile) ? 0 : 1; if (WIN_IsEqualIID(catid, &GUID_TFCAT_TIP_KEYBOARD) && (dwFlags & TF_IPSINK_FLAG_ACTIVE)) IME_InputLangChanged((SDL_VideoData *)sink->data); IME_HideCandidateList(videodata); return S_OK; } static void *vtUIElementSink[] = { (void *)(UIElementSink_QueryInterface), (void *)(TSFSink_AddRef), (void *)(TSFSink_Release), (void *)(UIElementSink_BeginUIElement), (void *)(UIElementSink_UpdateUIElement), (void *)(UIElementSink_EndUIElement) }; static void *vtIPPASink[] = { (void *)(IPPASink_QueryInterface), (void *)(TSFSink_AddRef), (void *)(TSFSink_Release), (void *)(IPPASink_OnActivated) }; static void UILess_EnableUIUpdates(SDL_VideoData *videodata) { ITfSource *source = 0; if (!videodata->ime_threadmgrex || videodata->ime_uielemsinkcookie != TF_INVALID_COOKIE) return; if (SUCCEEDED(videodata->ime_threadmgrex->lpVtbl->QueryInterface(videodata->ime_threadmgrex, &IID_ITfSource, (LPVOID *)&source))) { source->lpVtbl->AdviseSink(source, &IID_ITfUIElementSink, (IUnknown *)videodata->ime_uielemsink, &videodata->ime_uielemsinkcookie); source->lpVtbl->Release(source); } } static void UILess_DisableUIUpdates(SDL_VideoData *videodata) { ITfSource *source = 0; if (!videodata->ime_threadmgrex || videodata->ime_uielemsinkcookie == TF_INVALID_COOKIE) return; if (SUCCEEDED(videodata->ime_threadmgrex->lpVtbl->QueryInterface(videodata->ime_threadmgrex, &IID_ITfSource, (LPVOID *)&source))) { source->lpVtbl->UnadviseSink(source, videodata->ime_uielemsinkcookie); videodata->ime_uielemsinkcookie = TF_INVALID_COOKIE; source->lpVtbl->Release(source); } } static SDL_bool UILess_SetupSinks(SDL_VideoData *videodata) { TfClientId clientid = 0; SDL_bool result = SDL_FALSE; ITfSource *source = 0; if (FAILED(CoCreateInstance(&CLSID_TF_ThreadMgr, NULL, CLSCTX_INPROC_SERVER, &IID_ITfThreadMgrEx, (LPVOID *)&videodata->ime_threadmgrex))) return SDL_FALSE; if (FAILED(videodata->ime_threadmgrex->lpVtbl->ActivateEx(videodata->ime_threadmgrex, &clientid, TF_TMAE_UIELEMENTENABLEDONLY))) return SDL_FALSE; videodata->ime_uielemsink = SDL_malloc(sizeof(TSFSink)); videodata->ime_ippasink = SDL_malloc(sizeof(TSFSink)); videodata->ime_uielemsink->lpVtbl = vtUIElementSink; videodata->ime_uielemsink->refcount = 1; videodata->ime_uielemsink->data = videodata; videodata->ime_ippasink->lpVtbl = vtIPPASink; videodata->ime_ippasink->refcount = 1; videodata->ime_ippasink->data = videodata; if (SUCCEEDED(videodata->ime_threadmgrex->lpVtbl->QueryInterface(videodata->ime_threadmgrex, &IID_ITfSource, (LPVOID *)&source))) { if (SUCCEEDED(source->lpVtbl->AdviseSink(source, &IID_ITfUIElementSink, (IUnknown *)videodata->ime_uielemsink, &videodata->ime_uielemsinkcookie))) { if (SUCCEEDED(source->lpVtbl->AdviseSink(source, &IID_ITfInputProcessorProfileActivationSink, (IUnknown *)videodata->ime_ippasink, &videodata->ime_alpnsinkcookie))) { result = SDL_TRUE; } } source->lpVtbl->Release(source); } return result; } #define SAFE_RELEASE(p) \ { \ if (p) { \ (p)->lpVtbl->Release((p)); \ (p) = 0; \ } \ } static void UILess_ReleaseSinks(SDL_VideoData *videodata) { ITfSource *source = 0; if (videodata->ime_threadmgrex && SUCCEEDED(videodata->ime_threadmgrex->lpVtbl->QueryInterface(videodata->ime_threadmgrex, &IID_ITfSource, (LPVOID *)&source))) { source->lpVtbl->UnadviseSink(source, videodata->ime_uielemsinkcookie); source->lpVtbl->UnadviseSink(source, videodata->ime_alpnsinkcookie); SAFE_RELEASE(source); videodata->ime_threadmgrex->lpVtbl->Deactivate(videodata->ime_threadmgrex); SAFE_RELEASE(videodata->ime_threadmgrex); TSFSink_Release(videodata->ime_uielemsink); videodata->ime_uielemsink = 0; TSFSink_Release(videodata->ime_ippasink); videodata->ime_ippasink = 0; } } static void * StartDrawToBitmap(HDC hdc, HBITMAP *hhbm, int width, int height) { BITMAPINFO info; BITMAPINFOHEADER *infoHeader = &info.bmiHeader; BYTE *bits = NULL; if (hhbm) { SDL_zero(info); infoHeader->biSize = sizeof(BITMAPINFOHEADER); infoHeader->biWidth = width; infoHeader->biHeight = -1 * SDL_abs(height); infoHeader->biPlanes = 1; infoHeader->biBitCount = 32; infoHeader->biCompression = BI_RGB; *hhbm = CreateDIBSection(hdc, &info, DIB_RGB_COLORS, (void **)&bits, 0, 0); if (*hhbm) SelectObject(hdc, *hhbm); } return bits; } static void StopDrawToBitmap(HDC hdc, HBITMAP *hhbm) { if (hhbm && *hhbm) { DeleteObject(*hhbm); *hhbm = NULL; } } /* This draws only within the specified area and fills the entire region. */ static void DrawRect(HDC hdc, int left, int top, int right, int bottom, int pensize) { /* The case of no pen (PenSize = 0) is automatically taken care of. */ const int penadjust = (int)SDL_floor(pensize / 2.0f - 0.5f); left += pensize / 2; top += pensize / 2; right -= penadjust; bottom -= penadjust; Rectangle(hdc, left, top, right, bottom); } static void IME_DestroyTextures(SDL_VideoData *videodata) { } #define SDL_swap(a,b) { \ int c = (a); \ (a) = (b); \ (b) = c; \ } static void IME_PositionCandidateList(SDL_VideoData *videodata, SIZE size) { int left, top, right, bottom; SDL_bool ok = SDL_FALSE; int winw = videodata->ime_winwidth; int winh = videodata->ime_winheight; /* Bottom */ left = videodata->ime_rect.x; top = videodata->ime_rect.y + videodata->ime_rect.h; right = left + size.cx; bottom = top + size.cy; if (right >= winw) { left -= right - winw; right = winw; } if (bottom < winh) ok = SDL_TRUE; /* Top */ if (!ok) { left = videodata->ime_rect.x; top = videodata->ime_rect.y - size.cy; right = left + size.cx; bottom = videodata->ime_rect.y; if (right >= winw) { left -= right - winw; right = winw; } if (top >= 0) ok = SDL_TRUE; } /* Right */ if (!ok) { left = videodata->ime_rect.x + size.cx; top = 0; right = left + size.cx; bottom = size.cy; if (right < winw) ok = SDL_TRUE; } /* Left */ if (!ok) { left = videodata->ime_rect.x - size.cx; top = 0; right = videodata->ime_rect.x; bottom = size.cy; if (right >= 0) ok = SDL_TRUE; } /* Window too small, show at (0,0) */ if (!ok) { left = 0; top = 0; right = size.cx; bottom = size.cy; } videodata->ime_candlistrect.x = left; videodata->ime_candlistrect.y = top; videodata->ime_candlistrect.w = right - left; videodata->ime_candlistrect.h = bottom - top; } static void IME_RenderCandidateList(SDL_VideoData *videodata, HDC hdc) { int i, j; SIZE size = {0}; SIZE candsizes[MAX_CANDLIST]; SIZE maxcandsize = {0}; HBITMAP hbm = NULL; const int candcount = SDL_min(SDL_min(MAX_CANDLIST, videodata->ime_candcount), videodata->ime_candpgsize); SDL_bool vertical = videodata->ime_candvertical; const int listborder = 1; const int listpadding = 0; const int listbordercolor = RGB(0xB4, 0xC7, 0xAA); const int listfillcolor = RGB(255, 255, 255); const int candborder = 1; const int candpadding = 0; const int candmargin = 1; const COLORREF candbordercolor = RGB(255, 255, 255); const COLORREF candfillcolor = RGB(255, 255, 255); const COLORREF candtextcolor = RGB(0, 0, 0); const COLORREF selbordercolor = RGB(0x84, 0xAC, 0xDD); const COLORREF selfillcolor = RGB(0xD2, 0xE6, 0xFF); const COLORREF seltextcolor = RGB(0, 0, 0); const int horzcandspacing = 5; HPEN listpen = listborder != 0 ? CreatePen(PS_SOLID, listborder, listbordercolor) : (HPEN)GetStockObject(NULL_PEN); HBRUSH listbrush = CreateSolidBrush(listfillcolor); HPEN candpen = candborder != 0 ? CreatePen(PS_SOLID, candborder, candbordercolor) : (HPEN)GetStockObject(NULL_PEN); HBRUSH candbrush = CreateSolidBrush(candfillcolor); HPEN selpen = candborder != 0 ? CreatePen(PS_DOT, candborder, selbordercolor) : (HPEN)GetStockObject(NULL_PEN); HBRUSH selbrush = CreateSolidBrush(selfillcolor); HFONT font = CreateFont((int)(1 + videodata->ime_rect.h * 0.75f), 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_CHARACTER_PRECIS, CLIP_DEFAULT_PRECIS, PROOF_QUALITY, VARIABLE_PITCH | FF_SWISS, TEXT("Microsoft Sans Serif")); SetBkMode(hdc, TRANSPARENT); SelectObject(hdc, font); for (i = 0; i < candcount; ++i) { const WCHAR *s = videodata->ime_candidates[i]; if (!*s) break; GetTextExtentPoint32W(hdc, s, (int)SDL_wcslen(s), &candsizes[i]); maxcandsize.cx = SDL_max(maxcandsize.cx, candsizes[i].cx); maxcandsize.cy = SDL_max(maxcandsize.cy, candsizes[i].cy); } if (vertical) { size.cx = (listborder * 2) + (listpadding * 2) + (candmargin * 2) + (candborder * 2) + (candpadding * 2) + (maxcandsize.cx) ; size.cy = (listborder * 2) + (listpadding * 2) + ((candcount + 1) * candmargin) + (candcount * candborder * 2) + (candcount * candpadding * 2) + (candcount * maxcandsize.cy) ; } else { size.cx = (listborder * 2) + (listpadding * 2) + ((candcount + 1) * candmargin) + (candcount * candborder * 2) + (candcount * candpadding * 2) + ((candcount - 1) * horzcandspacing); ; for (i = 0; i < candcount; ++i) size.cx += candsizes[i].cx; size.cy = (listborder * 2) + (listpadding * 2) + (candmargin * 2) + (candborder * 2) + (candpadding * 2) + (maxcandsize.cy) ; } StartDrawToBitmap(hdc, &hbm, size.cx, size.cy); SelectObject(hdc, listpen); SelectObject(hdc, listbrush); DrawRect(hdc, 0, 0, size.cx, size.cy, listborder); SelectObject(hdc, candpen); SelectObject(hdc, candbrush); SetTextColor(hdc, candtextcolor); SetBkMode(hdc, TRANSPARENT); for (i = 0; i < candcount; ++i) { const WCHAR *s = videodata->ime_candidates[i]; int left, top, right, bottom; if (!*s) break; if (vertical) { left = listborder + listpadding + candmargin; top = listborder + listpadding + (i * candborder * 2) + (i * candpadding * 2) + ((i + 1) * candmargin) + (i * maxcandsize.cy); right = size.cx - listborder - listpadding - candmargin; bottom = top + maxcandsize.cy + (candpadding * 2) + (candborder * 2); } else { left = listborder + listpadding + (i * candborder * 2) + (i * candpadding * 2) + ((i + 1) * candmargin) + (i * horzcandspacing); for (j = 0; j < i; ++j) left += candsizes[j].cx; top = listborder + listpadding + candmargin; right = left + candsizes[i].cx + (candpadding * 2) + (candborder * 2); bottom = size.cy - listborder - listpadding - candmargin; } if (i == videodata->ime_candsel) { SelectObject(hdc, selpen); SelectObject(hdc, selbrush); SetTextColor(hdc, seltextcolor); } else { SelectObject(hdc, candpen); SelectObject(hdc, candbrush); SetTextColor(hdc, candtextcolor); } DrawRect(hdc, left, top, right, bottom, candborder); ExtTextOutW(hdc, left + candborder + candpadding, top + candborder + candpadding, 0, NULL, s, (int)SDL_wcslen(s), NULL); } StopDrawToBitmap(hdc, &hbm); DeleteObject(listpen); DeleteObject(listbrush); DeleteObject(candpen); DeleteObject(candbrush); DeleteObject(selpen); DeleteObject(selbrush); DeleteObject(font); IME_PositionCandidateList(videodata, size); } static void IME_Render(SDL_VideoData *videodata) { HDC hdc = CreateCompatibleDC(NULL); if (videodata->ime_candlist) IME_RenderCandidateList(videodata, hdc); DeleteDC(hdc); videodata->ime_dirty = SDL_FALSE; } void IME_Present(SDL_VideoData *videodata) { if (videodata->ime_dirty) IME_Render(videodata); /* FIXME: Need to show the IME bitmap */ } #endif /* SDL_DISABLE_WINDOWS_IME */ #endif /* SDL_VIDEO_DRIVER_WINDOWS */ /* vi: set ts=4 sw=4 expandtab: */
ddfd0dac9dc24f96486e59ab736bfcedf012ca50
42ab733e143d02091d13424fb4df16379d5bba0d
/third_party/libsdl2/Xcode-iOS/Demos/src/happy.c
658a65f01bd6707a3951986ed0cd78a043125b2b
[ "Zlib", "Apache-2.0", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
google/filament
11cd37ac68790fcf8b33416b7d8d8870e48181f0
0aa0efe1599798d887fa6e33c412c09e81bea1bf
refs/heads/main
2023-08-29T17:58:22.496956
2023-08-28T17:27:38
2023-08-28T17:27:38
143,455,116
16,631
1,961
Apache-2.0
2023-09-14T16:23:39
2018-08-03T17:26:00
C++
UTF-8
C
false
false
4,607
c
happy.c
/* * happy.c * written by Holmes Futrell * use however you want */ #include "SDL.h" #include "common.h" #define NUM_HAPPY_FACES 100 /* number of faces to draw */ #define HAPPY_FACE_SIZE 32 /* width and height of happyface */ static SDL_Texture *texture = 0; /* reference to texture holding happyface */ static struct { float x, y; /* position of happyface */ float xvel, yvel; /* velocity of happyface */ } faces[NUM_HAPPY_FACES]; /* Sets initial positions and velocities of happyfaces units of velocity are pixels per millesecond */ void initializeHappyFaces(SDL_Renderer *renderer) { int i; int w; int h; SDL_RenderGetLogicalSize(renderer, &w, &h); for (i = 0; i < NUM_HAPPY_FACES; i++) { faces[i].x = randomFloat(0.0f, w - HAPPY_FACE_SIZE); faces[i].y = randomFloat(0.0f, h - HAPPY_FACE_SIZE); faces[i].xvel = randomFloat(-60.0f, 60.0f); faces[i].yvel = randomFloat(-60.0f, 60.0f); } } void render(SDL_Renderer *renderer, double deltaTime) { int i; SDL_Rect srcRect; SDL_Rect dstRect; int w; int h; SDL_RenderGetLogicalSize(renderer, &w, &h); /* setup boundaries for happyface bouncing */ int maxx = w - HAPPY_FACE_SIZE; int maxy = h - HAPPY_FACE_SIZE; int minx = 0; int miny = 0; /* setup rects for drawing */ srcRect.x = 0; srcRect.y = 0; srcRect.w = HAPPY_FACE_SIZE; srcRect.h = HAPPY_FACE_SIZE; dstRect.w = HAPPY_FACE_SIZE; dstRect.h = HAPPY_FACE_SIZE; /* fill background in with black */ SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); /* loop through all the happy faces: - update position - update velocity (if boundary is hit) - draw */ for (i = 0; i < NUM_HAPPY_FACES; i++) { faces[i].x += faces[i].xvel * deltaTime; faces[i].y += faces[i].yvel * deltaTime; if (faces[i].x > maxx) { faces[i].x = maxx; faces[i].xvel = -faces[i].xvel; } else if (faces[i].y > maxy) { faces[i].y = maxy; faces[i].yvel = -faces[i].yvel; } if (faces[i].x < minx) { faces[i].x = minx; faces[i].xvel = -faces[i].xvel; } else if (faces[i].y < miny) { faces[i].y = miny; faces[i].yvel = -faces[i].yvel; } dstRect.x = faces[i].x; dstRect.y = faces[i].y; SDL_RenderCopy(renderer, texture, &srcRect, &dstRect); } /* update screen */ SDL_RenderPresent(renderer); } /* loads the happyface graphic into a texture */ void initializeTexture(SDL_Renderer *renderer) { SDL_Surface *bmp_surface; /* load the bmp */ bmp_surface = SDL_LoadBMP("icon.bmp"); if (bmp_surface == NULL) { fatalError("could not load bmp"); } /* set white to transparent on the happyface */ SDL_SetColorKey(bmp_surface, 1, SDL_MapRGB(bmp_surface->format, 255, 255, 255)); /* convert RGBA surface to texture */ texture = SDL_CreateTextureFromSurface(renderer, bmp_surface); if (texture == 0) { fatalError("could not create texture"); } SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND); /* free up allocated memory */ SDL_FreeSurface(bmp_surface); } int main(int argc, char *argv[]) { SDL_Window *window; SDL_Renderer *renderer; int done; int width; int height; /* initialize SDL */ if (SDL_Init(SDL_INIT_VIDEO) < 0) { fatalError("Could not initialize SDL"); } /* The specified window size doesn't matter - except for its aspect ratio, * which determines whether the window is in portrait or landscape on iOS * (if SDL_WINDOW_RESIZABLE isn't specified). */ window = SDL_CreateWindow(NULL, 0, 0, 320, 480, SDL_WINDOW_FULLSCREEN | SDL_WINDOW_ALLOW_HIGHDPI); renderer = SDL_CreateRenderer(window, -1, 0); SDL_GetWindowSize(window, &width, &height); SDL_RenderSetLogicalSize(renderer, width, height); initializeTexture(renderer); initializeHappyFaces(renderer); /* main loop */ done = 0; while (!done) { SDL_Event event; double deltaTime = updateDeltaTime(); while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { done = 1; } } render(renderer, deltaTime); SDL_Delay(1); } /* cleanup */ SDL_DestroyTexture(texture); /* shutdown SDL */ SDL_Quit(); return 0; }
c62d9a5523bed1bca5f25a8f0a635151b030a4cd
1994b15441624ad5b7f484f007083986cd846b13
/cyclone_objects/binaries/audio/typeroute.c
70329bc354015defed61403973ad0c02f7b0116b
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
porres/pd-cyclone
7e7912d5d1a7ebe00e29a643c17ebcb6f50b3747
dfb7b8ad4dddde3ff3320d8d32baefbebdff3cf9
refs/heads/master
2023-09-03T20:28:51.715146
2023-08-30T00:03:45
2023-08-30T00:03:45
51,787,562
186
26
BSD-3-Clause
2023-08-30T00:03:46
2016-02-15T21:38:34
C
UTF-8
C
false
false
1,368
c
typeroute.c
#include "m_pd.h" #include <common/api.h> typedef struct _typeroute { t_object x_obj; t_float x_input; t_outlet *x_bangout; } t_typeroute; static t_class *typeroute_class; static void typeroute_bang(t_typeroute *x) { outlet_bang(x->x_bangout); } static t_int *typeroute_perform(t_int *w) { t_typeroute *x = (t_typeroute *)(w[1]); int nblock = (int)(w[2]); t_float *in = (t_float *)(w[3]); t_float *out = (t_float *)(w[4]); while (nblock--) { *out++ = *in++; } return (w + 5); } static void typeroute_dsp(t_typeroute *x, t_signal **sp) { dsp_add(typeroute_perform, 4, x, sp[0]->s_n, sp[0]->s_vec, sp[1]->s_vec); } static void *typeroute_new(void) { t_typeroute *x = (t_typeroute *)pd_new(typeroute_class); outlet_new((t_object *)x, &s_signal); x->x_bangout = outlet_new((t_object *)x, &s_bang); return (x); } CYCLONE_OBJ_API void typeroute_tilde_setup(void) { typeroute_class = class_new(gensym("typeroute~"), (t_newmethod)typeroute_new, 0, sizeof(t_typeroute), CLASS_DEFAULT, 0); class_addmethod(typeroute_class, nullfn, gensym("signal"), 0); class_addmethod(typeroute_class, (t_method) typeroute_dsp, gensym("dsp"), A_CANT, 0); class_addbang(typeroute_class, typeroute_bang); }
61095b2be4aa8266fe77ba7bfac6dcde31a5ee0a
e72db16e9747386afd01edd1dd36d9589a3f71ef
/src/test/pmem2_badblock_mocks/mocks_other.c
29046bdf9b464a59dff9dedd9f303d4eda6698df
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
pmem/pmdk
5e49feee8017574340db2a0f9b4e2eab99f8581c
ccadb16227bddea1bdcc518bd8f298d551b2baad
refs/heads/master
2023-08-31T02:28:06.884934
2023-08-30T14:52:25
2023-08-30T14:52:25
23,637,153
1,017
402
NOASSERTION
2023-09-07T11:52:42
2014-09-03T20:55:23
C
UTF-8
C
false
false
681
c
mocks_other.c
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2020, Intel Corporation */ /* * mocks_other.c -- mocked various functions used * indirectly in pmem2_badblock_mocks.c */ #include <sys/stat.h> #include "unittest.h" #include "out.h" #include "pmem2_badblock_mocks.h" /* * fallocate -- mock fallocate */ FUNC_MOCK(fallocate, int, int fd, int mode, __off_t offset, __off_t len) FUNC_MOCK_RUN_DEFAULT { UT_OUT("fallocate(%i, %i, %lu, %lu)", fd, mode, offset, len); return 0; } FUNC_MOCK_END /* * fcntl -- mock fcntl */ FUNC_MOCK(fcntl, int, int fildes, int cmd) FUNC_MOCK_RUN_DEFAULT { UT_ASSERTeq(cmd, F_GETFL); return O_RDWR; } FUNC_MOCK_END
9f9f4ba9559a2c94d38babfd2097d840413953e9
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/JetMETCorrections/MCJet/test/DrawL3.C
c8ff9a206c64a5d3c76f80604de9823c6274d0ac
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
C
false
false
6,606
c
DrawL3.C
#include "Settings.h" void DrawL3() { gROOT->SetStyle("Plain"); gStyle->SetOptStat(0000); gStyle->SetOptFit(000); gStyle->SetPalette(1); char name[100]; int i; double x,y,e; TFile *inf = new TFile(L3OutputROOTFilename,"r"); TGraphErrors *g_Cor, *g_Resp; TF1 *CorFit, *RespFit; TMatrixD *COV_Cor, *COV_Resp; TH1F *hCorUncertainty, *hRespUncertainty, *hCorFrac, *hRespFrac; TPaveText *pave = new TPaveText(0.3,0.7,0.5,0.85,"NDC"); pave->AddText(Version); pave->AddText(Algorithm); pave->SetLineColor(0); pave->SetBorderSize(0); pave->SetFillColor(0); pave->SetBorderSize(0); /////////////////////////////////////////////////////////////// g_Cor = (TGraphErrors*)inf->Get("Correction_vs_CaloPt"); COV_Cor = (TMatrixD*)inf->Get("CovMatrix_Correction"); CorFit = (TF1*)g_Cor->GetFunction("CorFit"); CorFit->SetRange(1,5000); g_Resp = (TGraphErrors*)inf->Get("Response_vs_RefPt"); COV_Resp = (TMatrixD*)inf->Get("CovMatrix_Resp"); RespFit = (TF1*)g_Resp->GetFunction("RespFit"); RespFit->SetRange(5,5000); hCorUncertainty = new TH1F("CorrectionUncertainty","CorrectionUncertainty",5000,1,5001); hRespUncertainty = new TH1F("ResponseUncertainty","ResponseUncertainty",5000,5,5005); hCorFrac = new TH1F("FractionalCorrectionUncertainty","FractionalCorrectionUncertainty",5000,1,5001); hRespFrac = new TH1F("FractionalResponseUncertainty","FractionalResponseUncertainty",5000,5,5005); for(i=0;i<5000;i++) { x = hCorUncertainty->GetBinCenter(i+1); y = CorFit->Eval(x); e = FitUncertainty(false,CorFit,COV_Cor,x); hCorUncertainty->SetBinContent(i+1,y); hCorUncertainty->SetBinError(i+1,e); hCorFrac->SetBinContent(i+1,100*e/y); x = hRespUncertainty->GetBinCenter(i+1); y = RespFit->Eval(x); e = FitUncertainty(true,RespFit,COV_Resp,x); hRespUncertainty->SetBinContent(i+1,y); hRespUncertainty->SetBinError(i+1,e); hRespFrac->SetBinContent(i+1,100*e/y); } ////////////////////// Correction /////////////////////////////////////// TCanvas *c_Correction = new TCanvas("Correction","Correction",900,600); c_Correction->cd(); gPad->SetLogx(); hCorUncertainty->SetTitle(""); g_Cor->SetMarkerStyle(20); g_Cor->SetMarkerColor(1); g_Cor->SetLineColor(1); hCorUncertainty->SetMaximum(4); hCorUncertainty->SetMinimum(1); hCorUncertainty->GetXaxis()->SetTitle("p_{T} (GeV)"); hCorUncertainty->GetYaxis()->SetTitle("L3Correction factor"); CorFit->SetLineColor(2); CorFit->SetLineWidth(2); CorFit->SetParNames("a0","a1","a2","a3","a4"); hCorUncertainty->SetLineColor(5); hCorUncertainty->SetFillColor(5); hCorUncertainty->SetMarkerColor(5); hCorUncertainty->Draw("E3"); g_Cor->Draw("Psame"); pave->Draw(); TLegend *leg = new TLegend(0.6,0.65,0.89,0.89); leg->AddEntry(g_Cor,"measurement","LP"); leg->AddEntry(CorFit,"fit","L"); leg->AddEntry(hCorUncertainty,"fit uncertainty","F"); leg->SetFillColor(0); leg->SetLineColor(0); leg->Draw(); ////////////////////// Response /////////////////////////////////////// TCanvas *c_Response = new TCanvas("Response","Response",900,600); c_Response->cd(); gPad->SetLogx(); hRespUncertainty->SetTitle(""); g_Resp->SetMarkerStyle(20); g_Resp->SetMarkerColor(1); g_Resp->SetLineColor(1); hRespUncertainty->SetMaximum(1); hRespUncertainty->SetMinimum(0); hRespUncertainty->GetXaxis()->SetTitle("p_{T}^{gen} (GeV)"); hRespUncertainty->GetYaxis()->SetTitle("Response"); RespFit->SetLineColor(2); hRespUncertainty->SetLineColor(5); hRespUncertainty->SetFillColor(5); hRespUncertainty->SetMarkerColor(5); hRespUncertainty->Draw("E3"); g_Resp->Draw("Psame"); pave->Draw(); TLegend *leg = new TLegend(0.6,0.15,0.89,0.39); leg->AddEntry(g_Resp,"measurement","LP"); leg->AddEntry(RespFit,"fit","L"); leg->AddEntry(hRespUncertainty,"fit uncertainty","F"); leg->SetFillColor(0); leg->SetLineColor(0); leg->Draw(); ////////////////////// Correction - Response closure /////////////////////////////////////// TH1F *hClosure = new TH1F("hClosure","hClosure",1000,5,5005); for(int i=0;i<1000;i++) { double dx = 5; double x = 5+dx*i; double y = Closure(x,CorFit,RespFit); hClosure->SetBinContent(i+1,y); hClosure->SetBinError(i+1,0.); } TCanvas *can = new TCanvas("Closure","Closure",900,600); gPad->SetLogx(); hClosure->SetTitle(""); hClosure->GetXaxis()->SetTitle("p_{T}"); hClosure->GetYaxis()->SetTitle("C(p_{T})#times R(p_{T}C(p_{T}))"); hClosure->Draw(); ////////////////////// Fractional Correction Fit Uncertainty /////////////////////////////////////// TCanvas *can = new TCanvas("FracCorrUnc","FracCorrUnc",900,600); gPad->SetLogx(); hCorFrac->SetTitle(""); hCorFrac->GetXaxis()->SetTitle("p_{T} (GeV)"); hCorFrac->GetYaxis()->SetTitle("Fractional Correction Fitting Uncertainty (%)"); hCorFrac->Draw(); ////////////////////// Fractional Response Fit Uncertainty /////////////////////////////////////// TCanvas *can = new TCanvas("FracRespUnc","FracRespUnc",900,600); gPad->SetLogx(); hRespFrac->SetTitle(""); hRespFrac->GetXaxis()->SetTitle("p_{T}^{gen} (GeV)"); hRespFrac->GetYaxis()->SetTitle("Fractional Response Fit Uncertainty (%)"); hRespFrac->Draw(); } /////////////////////////////////////////////////////////////////////// double FitUncertainty(bool IsResponse, TF1* f, TMatrixD* COV, double x) { int i,j,dim,N,npar; double df,sum,y,z,x; double PartialDerivative[10],Parameter[10]; if (IsResponse) npar = 5; else npar = 4; N = f->GetNumberFreeParameters(); dim = COV->GetNrows(); if (dim != npar || N != npar) { cout<<"ERROR: wrong number of parameters !!!!"<<endl; return(-1); } for(i=0;i<npar;i++) Parameter[i] = f->GetParameter(i); z = pow(log10(x),Parameter[2]); PartialDerivative[0] = 1.; PartialDerivative[1] = 1./(z+Parameter[3]); PartialDerivative[3] = -Parameter[1]/pow(z+Parameter[3],2); PartialDerivative[2] = PartialDerivative[3]*log(log10(x))*z; if (IsResponse) { PartialDerivative[1] = -1./(z+Parameter[3]); PartialDerivative[3] = Parameter[1]/pow(z+Parameter[3],2); PartialDerivative[4] = 1./x; } sum = 0.; for(i=0;i<npar;i++) for(j=0;j<npar;j++) { y = PartialDerivative[i]*PartialDerivative[j]*COV(i,j); sum+=y; } df = sqrt(sum); return df; } double Closure(double x, TF1 *f1, TF1 *f2) { double y1,y,tmp; y1 = f1->Eval(x); y = x*y1; tmp = y1*f2->Eval(y); return tmp; }
d7557bc71f4ede690b8ffb2860c9ec7be9c6e53a
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/emips/include/endian_machdep.h
138f5b4013c0128cb1467602ef62ba6bc4b99cc8
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
138
h
endian_machdep.h
/* $NetBSD: endian_machdep.h,v 1.1 2011/01/26 01:18:51 pooka Exp $ */ #define _BYTE_ORDER _BIG_ENDIAN #include <mips/endian_machdep.h>
020b9fddd78ff8cde99725225d9d0109bdad850c
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/sound/pci/hda/hda_jack.c
9e0a95288f46fcca24fa0944fc99cd134e0d7c2e
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
14,461
c
hda_jack.c
/* * Jack-detection handling for HD-audio * * Copyright (c) 2011 Takashi Iwai <tiwai@suse.de> * * This driver is free software; you can 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. */ #include <linux/init.h> #include <linux/slab.h> #include <linux/export.h> #include <sound/core.h> #include <sound/control.h> #include <sound/jack.h> #include "hda_codec.h" #include "hda_local.h" #include "hda_auto_parser.h" #include "hda_jack.h" bool is_jack_detectable(struct hda_codec *codec, hda_nid_t nid) { if (codec->no_jack_detect) return false; if (!(snd_hda_query_pin_caps(codec, nid) & AC_PINCAP_PRES_DETECT)) return false; if (get_defcfg_misc(snd_hda_codec_get_pincfg(codec, nid)) & AC_DEFCFG_MISC_NO_PRESENCE) return false; if (!(get_wcaps(codec, nid) & AC_WCAP_UNSOL_CAP) && !codec->jackpoll_interval) return false; return true; } EXPORT_SYMBOL_HDA(is_jack_detectable); /* execute pin sense measurement */ static u32 read_pin_sense(struct hda_codec *codec, hda_nid_t nid) { u32 pincap; u32 val; if (!codec->no_trigger_sense) { pincap = snd_hda_query_pin_caps(codec, nid); if (pincap & AC_PINCAP_TRIG_REQ) /* need trigger? */ snd_hda_codec_read(codec, nid, 0, AC_VERB_SET_PIN_SENSE, 0); } val = snd_hda_codec_read(codec, nid, 0, AC_VERB_GET_PIN_SENSE, 0); if (codec->inv_jack_detect) val ^= AC_PINSENSE_PRESENCE; return val; } /** * snd_hda_jack_tbl_get - query the jack-table entry for the given NID */ struct hda_jack_tbl * snd_hda_jack_tbl_get(struct hda_codec *codec, hda_nid_t nid) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i; if (!nid || !jack) return NULL; for (i = 0; i < codec->jacktbl.used; i++, jack++) if (jack->nid == nid) return jack; return NULL; } EXPORT_SYMBOL_HDA(snd_hda_jack_tbl_get); /** * snd_hda_jack_tbl_get_from_tag - query the jack-table entry for the given tag */ struct hda_jack_tbl * snd_hda_jack_tbl_get_from_tag(struct hda_codec *codec, unsigned char tag) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i; if (!tag || !jack) return NULL; for (i = 0; i < codec->jacktbl.used; i++, jack++) if (jack->tag == tag) return jack; return NULL; } EXPORT_SYMBOL_HDA(snd_hda_jack_tbl_get_from_tag); /** * snd_hda_jack_tbl_new - create a jack-table entry for the given NID */ struct hda_jack_tbl * snd_hda_jack_tbl_new(struct hda_codec *codec, hda_nid_t nid) { struct hda_jack_tbl *jack = snd_hda_jack_tbl_get(codec, nid); if (jack) return jack; jack = snd_array_new(&codec->jacktbl); if (!jack) return NULL; jack->nid = nid; jack->jack_dirty = 1; jack->tag = codec->jacktbl.used; return jack; } EXPORT_SYMBOL_HDA(snd_hda_jack_tbl_new); void snd_hda_jack_tbl_clear(struct hda_codec *codec) { #ifdef CONFIG_SND_HDA_INPUT_JACK /* free jack instances manually when clearing/reconfiguring */ if (!codec->bus->shutdown && codec->jacktbl.list) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i; for (i = 0; i < codec->jacktbl.used; i++, jack++) { if (jack->jack) snd_device_free(codec->bus->card, jack->jack); } } #endif snd_array_free(&codec->jacktbl); } #define get_jack_plug_state(sense) !!(sense & AC_PINSENSE_PRESENCE) /* update the cached value and notification flag if needed */ static void jack_detect_update(struct hda_codec *codec, struct hda_jack_tbl *jack) { if (!jack->jack_dirty) return; if (jack->phantom_jack) jack->pin_sense = AC_PINSENSE_PRESENCE; else jack->pin_sense = read_pin_sense(codec, jack->nid); /* A gating jack indicates the jack is invalid if gating is unplugged */ if (jack->gating_jack && !snd_hda_jack_detect(codec, jack->gating_jack)) jack->pin_sense &= ~AC_PINSENSE_PRESENCE; jack->jack_dirty = 0; /* If a jack is gated by this one update it. */ if (jack->gated_jack) { struct hda_jack_tbl *gated = snd_hda_jack_tbl_get(codec, jack->gated_jack); if (gated) { gated->jack_dirty = 1; jack_detect_update(codec, gated); } } } /** * snd_hda_set_dirty_all - Mark all the cached as dirty * * This function sets the dirty flag to all entries of jack table. * It's called from the resume path in hda_codec.c. */ void snd_hda_jack_set_dirty_all(struct hda_codec *codec) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i; for (i = 0; i < codec->jacktbl.used; i++, jack++) if (jack->nid) jack->jack_dirty = 1; } EXPORT_SYMBOL_HDA(snd_hda_jack_set_dirty_all); /** * snd_hda_pin_sense - execute pin sense measurement * @codec: the CODEC to sense * @nid: the pin NID to sense * * Execute necessary pin sense measurement and return its Presence Detect, * Impedance, ELD Valid etc. status bits. */ u32 snd_hda_pin_sense(struct hda_codec *codec, hda_nid_t nid) { struct hda_jack_tbl *jack = snd_hda_jack_tbl_get(codec, nid); if (jack) { jack_detect_update(codec, jack); return jack->pin_sense; } return read_pin_sense(codec, nid); } EXPORT_SYMBOL_HDA(snd_hda_pin_sense); /** * snd_hda_jack_detect - query pin Presence Detect status * @codec: the CODEC to sense * @nid: the pin NID to sense * * Query and return the pin's Presence Detect status. */ int snd_hda_jack_detect(struct hda_codec *codec, hda_nid_t nid) { u32 sense = snd_hda_pin_sense(codec, nid); return get_jack_plug_state(sense); } EXPORT_SYMBOL_HDA(snd_hda_jack_detect); /** * snd_hda_jack_detect_enable - enable the jack-detection */ int snd_hda_jack_detect_enable_callback(struct hda_codec *codec, hda_nid_t nid, unsigned char action, hda_jack_callback cb) { struct hda_jack_tbl *jack = snd_hda_jack_tbl_new(codec, nid); if (!jack) return -ENOMEM; if (jack->jack_detect) return 0; /* already registered */ jack->jack_detect = 1; if (action) jack->action = action; if (cb) jack->callback = cb; if (codec->jackpoll_interval > 0) return 0; /* No unsol if we're polling instead */ return snd_hda_codec_write_cache(codec, nid, 0, AC_VERB_SET_UNSOLICITED_ENABLE, AC_USRSP_EN | jack->tag); } EXPORT_SYMBOL_HDA(snd_hda_jack_detect_enable_callback); int snd_hda_jack_detect_enable(struct hda_codec *codec, hda_nid_t nid, unsigned char action) { return snd_hda_jack_detect_enable_callback(codec, nid, action, NULL); } EXPORT_SYMBOL_HDA(snd_hda_jack_detect_enable); /** * snd_hda_jack_set_gating_jack - Set gating jack. * * Indicates the gated jack is only valid when the gating jack is plugged. */ int snd_hda_jack_set_gating_jack(struct hda_codec *codec, hda_nid_t gated_nid, hda_nid_t gating_nid) { struct hda_jack_tbl *gated = snd_hda_jack_tbl_get(codec, gated_nid); struct hda_jack_tbl *gating = snd_hda_jack_tbl_get(codec, gating_nid); if (!gated || !gating) return -EINVAL; gated->gating_jack = gating_nid; gating->gated_jack = gated_nid; return 0; } EXPORT_SYMBOL_HDA(snd_hda_jack_set_gating_jack); /** * snd_hda_jack_report_sync - sync the states of all jacks and report if changed */ void snd_hda_jack_report_sync(struct hda_codec *codec) { struct hda_jack_tbl *jack; int i, state; /* update all jacks at first */ jack = codec->jacktbl.list; for (i = 0; i < codec->jacktbl.used; i++, jack++) if (jack->nid) jack_detect_update(codec, jack); /* report the updated jacks; it's done after updating all jacks * to make sure that all gating jacks properly have been set */ jack = codec->jacktbl.list; for (i = 0; i < codec->jacktbl.used; i++, jack++) if (jack->nid) { if (!jack->kctl) continue; state = get_jack_plug_state(jack->pin_sense); snd_kctl_jack_report(codec->bus->card, jack->kctl, state); #ifdef CONFIG_SND_HDA_INPUT_JACK if (jack->jack) snd_jack_report(jack->jack, state ? jack->type : 0); #endif } } EXPORT_SYMBOL_HDA(snd_hda_jack_report_sync); #ifdef CONFIG_SND_HDA_INPUT_JACK /* guess the jack type from the pin-config */ static int get_input_jack_type(struct hda_codec *codec, hda_nid_t nid) { unsigned int def_conf = snd_hda_codec_get_pincfg(codec, nid); switch (get_defcfg_device(def_conf)) { case AC_JACK_LINE_OUT: case AC_JACK_SPEAKER: return SND_JACK_LINEOUT; case AC_JACK_HP_OUT: return SND_JACK_HEADPHONE; case AC_JACK_SPDIF_OUT: case AC_JACK_DIG_OTHER_OUT: return SND_JACK_AVOUT; case AC_JACK_MIC_IN: return SND_JACK_MICROPHONE; default: return SND_JACK_LINEIN; } } static void hda_free_jack_priv(struct snd_jack *jack) { struct hda_jack_tbl *jacks = jack->private_data; jacks->nid = 0; jacks->jack = NULL; } #endif /** * snd_hda_jack_add_kctl - Add a kctl for the given pin * * This assigns a jack-detection kctl to the given pin. The kcontrol * will have the given name and index. */ static int __snd_hda_jack_add_kctl(struct hda_codec *codec, hda_nid_t nid, const char *name, int idx, bool phantom_jack) { struct hda_jack_tbl *jack; struct snd_kcontrol *kctl; int err, state; jack = snd_hda_jack_tbl_new(codec, nid); if (!jack) return 0; if (jack->kctl) return 0; /* already created */ kctl = snd_kctl_jack_new(name, idx, codec); if (!kctl) return -ENOMEM; err = snd_hda_ctl_add(codec, nid, kctl); if (err < 0) return err; jack->kctl = kctl; jack->phantom_jack = !!phantom_jack; state = snd_hda_jack_detect(codec, nid); snd_kctl_jack_report(codec->bus->card, kctl, state); #ifdef CONFIG_SND_HDA_INPUT_JACK if (!phantom_jack) { jack->type = get_input_jack_type(codec, nid); err = snd_jack_new(codec->bus->card, name, jack->type, &jack->jack); if (err < 0) return err; jack->jack->private_data = jack; jack->jack->private_free = hda_free_jack_priv; snd_jack_report(jack->jack, state ? jack->type : 0); } #endif return 0; } int snd_hda_jack_add_kctl(struct hda_codec *codec, hda_nid_t nid, const char *name, int idx) { return __snd_hda_jack_add_kctl(codec, nid, name, idx, false); } EXPORT_SYMBOL_HDA(snd_hda_jack_add_kctl); /* get the unique index number for the given kctl name */ static int get_unique_index(struct hda_codec *codec, const char *name, int idx) { struct hda_jack_tbl *jack; int i, len = strlen(name); again: jack = codec->jacktbl.list; for (i = 0; i < codec->jacktbl.used; i++, jack++) { /* jack->kctl.id contains "XXX Jack" name string with index */ if (jack->kctl && !strncmp(name, jack->kctl->id.name, len) && !strcmp(" Jack", jack->kctl->id.name + len) && jack->kctl->id.index == idx) { idx++; goto again; } } return idx; } static int add_jack_kctl(struct hda_codec *codec, hda_nid_t nid, const struct auto_pin_cfg *cfg, const char *base_name) { unsigned int def_conf, conn; char name[44]; int idx, err; bool phantom_jack; if (!nid) return 0; def_conf = snd_hda_codec_get_pincfg(codec, nid); conn = get_defcfg_connect(def_conf); if (conn == AC_JACK_PORT_NONE) return 0; phantom_jack = (conn != AC_JACK_PORT_COMPLEX) || !is_jack_detectable(codec, nid); if (base_name) { strlcpy(name, base_name, sizeof(name)); idx = 0; } else snd_hda_get_pin_label(codec, nid, cfg, name, sizeof(name), &idx); if (phantom_jack) /* Example final name: "Internal Mic Phantom Jack" */ strncat(name, " Phantom", sizeof(name) - strlen(name) - 1); idx = get_unique_index(codec, name, idx); err = __snd_hda_jack_add_kctl(codec, nid, name, idx, phantom_jack); if (err < 0) return err; if (!phantom_jack) return snd_hda_jack_detect_enable(codec, nid, 0); return 0; } /** * snd_hda_jack_add_kctls - Add kctls for all pins included in the given pincfg */ int snd_hda_jack_add_kctls(struct hda_codec *codec, const struct auto_pin_cfg *cfg) { const hda_nid_t *p; int i, err; for (i = 0; i < cfg->num_inputs; i++) { /* If we have headphone mics; make sure they get the right name before grabbed by output pins */ if (cfg->inputs[i].is_headphone_mic) { if (auto_cfg_hp_outs(cfg) == 1) err = add_jack_kctl(codec, auto_cfg_hp_pins(cfg)[0], cfg, "Headphone Mic"); else err = add_jack_kctl(codec, cfg->inputs[i].pin, cfg, "Headphone Mic"); } else err = add_jack_kctl(codec, cfg->inputs[i].pin, cfg, NULL); if (err < 0) return err; } for (i = 0, p = cfg->line_out_pins; i < cfg->line_outs; i++, p++) { err = add_jack_kctl(codec, *p, cfg, NULL); if (err < 0) return err; } for (i = 0, p = cfg->hp_pins; i < cfg->hp_outs; i++, p++) { if (*p == *cfg->line_out_pins) /* might be duplicated */ break; err = add_jack_kctl(codec, *p, cfg, NULL); if (err < 0) return err; } for (i = 0, p = cfg->speaker_pins; i < cfg->speaker_outs; i++, p++) { if (*p == *cfg->line_out_pins) /* might be duplicated */ break; err = add_jack_kctl(codec, *p, cfg, NULL); if (err < 0) return err; } for (i = 0, p = cfg->dig_out_pins; i < cfg->dig_outs; i++, p++) { err = add_jack_kctl(codec, *p, cfg, NULL); if (err < 0) return err; } err = add_jack_kctl(codec, cfg->dig_in_pin, cfg, NULL); if (err < 0) return err; err = add_jack_kctl(codec, cfg->mono_out_pin, cfg, NULL); if (err < 0) return err; return 0; } EXPORT_SYMBOL_HDA(snd_hda_jack_add_kctls); static void call_jack_callback(struct hda_codec *codec, struct hda_jack_tbl *jack) { if (jack->callback) jack->callback(codec, jack); if (jack->gated_jack) { struct hda_jack_tbl *gated = snd_hda_jack_tbl_get(codec, jack->gated_jack); if (gated && gated->callback) gated->callback(codec, gated); } } void snd_hda_jack_unsol_event(struct hda_codec *codec, unsigned int res) { struct hda_jack_tbl *event; int tag = (res >> AC_UNSOL_RES_TAG_SHIFT) & 0x7f; event = snd_hda_jack_tbl_get_from_tag(codec, tag); if (!event) return; event->jack_dirty = 1; call_jack_callback(codec, event); snd_hda_jack_report_sync(codec); } EXPORT_SYMBOL_HDA(snd_hda_jack_unsol_event); void snd_hda_jack_poll_all(struct hda_codec *codec) { struct hda_jack_tbl *jack = codec->jacktbl.list; int i, changes = 0; for (i = 0; i < codec->jacktbl.used; i++, jack++) { unsigned int old_sense; if (!jack->nid || !jack->jack_dirty || jack->phantom_jack) continue; old_sense = get_jack_plug_state(jack->pin_sense); jack_detect_update(codec, jack); if (old_sense == get_jack_plug_state(jack->pin_sense)) continue; changes = 1; call_jack_callback(codec, jack); } if (changes) snd_hda_jack_report_sync(codec); } EXPORT_SYMBOL_HDA(snd_hda_jack_poll_all);
d403820d0ac67826c848c4e54a4981cb4939bbdd
fb47ab6337a71029dee71933e449cf7f6805fc0f
/external/platform/cc13xx/cc13xxware/rf_patches/rf_patch_mce_genook.h
aa2db0e97d63906337cefe851728e27f653a3ef6
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
littlekernel/lk
7e7ba50b87b1f2e0b6e2f052c59249825c91975b
30dc320054f70910e1c1ee40a6948ee99672acec
refs/heads/master
2023-09-02T00:47:52.203963
2023-06-21T22:42:35
2023-06-21T22:42:35
3,058,456
3,077
618
MIT
2023-08-30T09:41:31
2011-12-27T19:19:36
C
UTF-8
C
false
false
10,722
h
rf_patch_mce_genook.h
/****************************************************************************** * Filename: rf_patch_mce_genook.h * Revised: 2015-11-16 13:15:59 +0100 (Mon, 11 Sep 2015) * Revision: * * Description: Patch for CC13XX Generic OOK * * Copyright (c) 2015, Texas Instruments Incorporated * 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 ORGANIZATION 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 _RF_PATCH_MCE_GENOOK_H #define _RF_PATCH_MCE_GENOOK_H #include <stdint.h> #include <inc/hw_types.h> #ifndef MCE_PATCH_TYPE #define MCE_PATCH_TYPE static const uint32_t #endif #ifndef PATCH_FUN_SPEC #define PATCH_FUN_SPEC static inline #endif #ifndef RFC_MCERAM_BASE #define RFC_MCERAM_BASE 0x21008000 #endif MCE_PATCH_TYPE patchGenookMce[463] = { 0x00006030, 0x01952fcf, 0x7fff0001, 0x030c003f, 0x070c680a, 0x00010000, 0xaaaa000f, 0x00fc00aa, 0x00170003, 0x0000001f, 0x04000000, 0x0000000f, 0x00020387, 0x00434074, 0x20028000, 0x000006f0, 0x0500091e, 0x00000054, 0x50140000, 0x00000050, 0x7f30000f, 0x0000007f, 0x00000000, 0x00000000, 0x72487220, 0x73057303, 0x73047203, 0x72047306, 0x72767376, 0x8001c7c0, 0x90010001, 0x08019010, 0x720c9001, 0x720e720d, 0x7100b0c0, 0xa0c0b0f0, 0x81327218, 0x9862d030, 0x10206798, 0x1e000670, 0x1e104074, 0x1e204075, 0x3982405f, 0x163206f2, 0x14211101, 0x61826c01, 0x63186182, 0x3982632e, 0x16323942, 0x14211101, 0x60e36c01, 0x610d60e3, 0x606b1220, 0x72201210, 0x7310730f, 0x81817311, 0x91800010, 0x6044b070, 0xc101606a, 0xc470c282, 0x6f131820, 0x16116e23, 0x68791612, 0x9ab07870, 0x9ac07880, 0x9ad07890, 0x981078b0, 0xc5a0c482, 0x408e1820, 0x6e231203, 0x688b1612, 0x9ae078a0, 0x8160606a, 0x81409490, 0x2a703980, 0x16111001, 0x84448432, 0xc0f5c0f3, 0x1c01c200, 0xc10040b5, 0x40ab1c10, 0x10134cad, 0x18301803, 0x1a101a13, 0x68a83912, 0x13f360b5, 0x13f360b5, 0xc1001015, 0x1a151850, 0x39141a10, 0xb0d868b3, 0xb1087100, 0xb200a0d8, 0xb012b002, 0x22168216, 0x814640bc, 0x06f63d46, 0x81408165, 0x105106f0, 0x65570611, 0x68c53d15, 0x22f08140, 0x1a1644bf, 0x8ae14cc2, 0x9861d040, 0x13f06798, 0x40dc1c03, 0x1021c0f0, 0x65570611, 0x68d73d12, 0x1041c0f0, 0x65570611, 0x68dd3d14, 0x72207000, 0x7310730f, 0x91c0c000, 0xb0c1b0f1, 0x9760c050, 0x9780c010, 0x6491c008, 0x39838ad3, 0x06133953, 0x221081e0, 0x81a14104, 0x10170831, 0x81306557, 0x39403980, 0x45031e10, 0x0a111071, 0x60f46557, 0x65571201, 0xa0c1b204, 0xa0c3b0f1, 0x6798c050, 0x7220606a, 0x7310730f, 0x91c0c000, 0xb0c1b0f1, 0x9760c050, 0x9780c010, 0x8216b200, 0x41192216, 0xb012b002, 0xc030c008, 0x10a178ca, 0x65570611, 0x6921391a, 0x78dac0f0, 0x061110a1, 0x391a6557, 0xc0706928, 0x10a178ea, 0x65570611, 0x692f391a, 0x78fac090, 0x061110a1, 0x391a6557, 0x8ad36936, 0x39533983, 0x81e00613, 0x414c2210, 0x0831c011, 0x81a16557, 0x65576793, 0x0831c001, 0x613f6557, 0x6557c011, 0x6557c001, 0xa0c1b204, 0xa0c3b0f1, 0x6798c060, 0xc029606a, 0x455d2208, 0x41732201, 0x2201616c, 0x8aef4573, 0x416c22ff, 0x31116578, 0x39119201, 0x80fe1018, 0x456bc019, 0x6173c029, 0x7100b0f1, 0x92013111, 0x10183911, 0xb0f1c019, 0x1a197100, 0x70004573, 0x785f10f9, 0x100004f9, 0x10001000, 0x1a191000, 0x7000457b, 0xc0706750, 0x847d6798, 0x140dc010, 0x142d312d, 0x318e8ace, 0x397e311e, 0x31498ac9, 0x39493979, 0x10903129, 0x72769780, 0xa764b764, 0x9762c662, 0xb012b002, 0x986be080, 0x6798987f, 0x6699b485, 0x8ab1a182, 0x45aa22f1, 0x22f18ad1, 0x61df45aa, 0x80b77100, 0x45fd2207, 0x22b08090, 0x105441b6, 0x662d858c, 0x61aa668e, 0x22f18ab1, 0x223741c0, 0xb11341c0, 0x223080b0, 0x61ce45bb, 0x41d322e1, 0x22508090, 0xb0f541d3, 0x22108210, 0x978941aa, 0xa764b764, 0x61aab0f6, 0xb764978d, 0xb0f6a764, 0x8ad061aa, 0x42da22f0, 0x42da2237, 0xb113b075, 0x223080b0, 0xb08745d9, 0x710061aa, 0x220780b7, 0x223745fd, 0x809045fc, 0x41ee22b0, 0x858c1054, 0x668e662d, 0x8ab161df, 0x41df22e1, 0x22508090, 0xb0f541df, 0x22108210, 0x978d41df, 0xa764b764, 0x61dfb0f6, 0xb110b182, 0xb113a0e0, 0xb074a0e3, 0xa044b201, 0x986ad090, 0x10806798, 0x1c0a1610, 0x1cfa4a0e, 0x66704e0e, 0xc00ec00f, 0x80907100, 0x44442200, 0x1054858c, 0x668e662d, 0x39808130, 0x1e1006f0, 0x667a461f, 0x66646220, 0x1e008150, 0x1a104210, 0x4e101cf0, 0x62106228, 0xb0f6a0c6, 0xb0fba0cb, 0xb8846306, 0x881188c2, 0x1e010631, 0x1e21424a, 0x1e31423c, 0x10564243, 0x39161426, 0x624b1065, 0x31261056, 0x14261856, 0x10653926, 0x1056624b, 0x18563136, 0x39361426, 0x624b1065, 0x82121026, 0x1c263922, 0x18624e59, 0x1c12c101, 0x12014e57, 0x31211821, 0xcc016261, 0x18266261, 0x1c16c101, 0x10614e60, 0x62613121, 0x9581c401, 0x7000b0fb, 0x466f1c8a, 0x39208210, 0x4e6c1c04, 0x626dc001, 0x9191c011, 0x7000161f, 0x39208210, 0x4e761c04, 0x6277c001, 0x9191c011, 0x7000c01f, 0x468d1c8a, 0x31808580, 0x10013d80, 0x10171870, 0x468c1e1e, 0x39703980, 0x39818ad1, 0x08103951, 0x161f9190, 0x70000a1e, 0x10c08581, 0x22700810, 0x120a4295, 0x1cba6298, 0x161a4293, 0xb0fb7000, 0xb0f1b0f6, 0xb113b110, 0xb0f2b0f5, 0x720d720c, 0xb0cb720e, 0xb0e3b0e0, 0x22f28ab2, 0xb0c642ac, 0x62afb763, 0x22f08ad0, 0xb40542cf, 0xa428a404, 0xcaa0a429, 0xcaa13180, 0x94510001, 0x8ad39461, 0x39833183, 0x31808410, 0x31833980, 0x94100030, 0x31508400, 0x8ad33950, 0x06f33983, 0x1834c1f4, 0x31343184, 0x94000040, 0x22e2b089, 0x8aca42d9, 0x398a394a, 0x978a312a, 0xb0c6b0c5, 0x7000b763, 0xa0e0b20f, 0xa0cba0e3, 0xb764978e, 0xb0f6a764, 0xb113b110, 0x8210b0fb, 0x42e52200, 0x8002b0f5, 0xa006a004, 0x7203a001, 0xc0a07204, 0x71006798, 0xb0f6b764, 0xa20fb0c5, 0xb0f57100, 0x7820a0c5, 0x90029030, 0x90407830, 0xb0729060, 0x6699a20f, 0xa764978a, 0x61a3b0f6, 0x8180b88c, 0x392489a4, 0x00043184, 0xc0b09184, 0x73766798, 0x72487276, 0x72027206, 0x73057204, 0x606a7306, 0xc0c06750, 0xb0f86798, 0xb0fbb0cb, 0xb228b005, 0xb0fb7100, 0x22e08ad0, 0x82104328, 0x43202210, 0x8580662d, 0x0a103970, 0x63206789, 0xc0d06750, 0xb0cb6798, 0x120cb074, 0x398e881e, 0x433e1e0e, 0x30e01210, 0x71001a20, 0x6b3b662d, 0x8ad07100, 0x434522e0, 0x22108210, 0x662d4336, 0x0a113971, 0x81549191, 0x43361e04, 0x1cc4161c, 0x63364306, 0x91b01200, 0xb006b0f8, 0xb004b016, 0xb002b014, 0x8400b012, 0x04207862, 0x39838143, 0x94732a73, 0x1832c1f2, 0x10213162, 0x00123151, 0x94000020, 0x90307820, 0x78309050, 0x90609040, 0x8330c04b, 0x06303930, 0x43751e00, 0x10b8300b, 0x39181a1b, 0x108fc00a, 0xa203a204, 0x22408330, 0x165f4382, 0x6386b204, 0x43862230, 0xb203163f, 0xb072b205, 0x22007000, 0xb005478d, 0x80006392, 0x43922250, 0xa005b240, 0x82a27000, 0x06123972, 0x70000821, 0x88409850, 0x47992200, 0x7000b830 }; PATCH_FUN_SPEC void rf_patch_mce_genook(void) { #ifdef __PATCH_NO_UNROLLING uint32_t i; for (i = 0; i < 463; i++) { HWREG(RFC_MCERAM_BASE + 4 * i) = patchGenookMce[i]; } #else const uint32_t *pS = patchGenookMce; volatile unsigned long *pD = &HWREG(RFC_MCERAM_BASE); uint32_t t1, t2, t3, t4, t5, t6, t7, t8; uint32_t nIterations = 57; do { t1 = *pS++; t2 = *pS++; t3 = *pS++; t4 = *pS++; t5 = *pS++; t6 = *pS++; t7 = *pS++; t8 = *pS++; *pD++ = t1; *pD++ = t2; *pD++ = t3; *pD++ = t4; *pD++ = t5; *pD++ = t6; *pD++ = t7; *pD++ = t8; } while (--nIterations); t1 = *pS++; t2 = *pS++; t3 = *pS++; t4 = *pS++; t5 = *pS++; t6 = *pS++; t7 = *pS++; *pD++ = t1; *pD++ = t2; *pD++ = t3; *pD++ = t4; *pD++ = t5; *pD++ = t6; *pD++ = t7; #endif } #endif
38a57029098f73cbbad1b6e7f8ec4b8f21f54338
50dd46b8ece33f3cdd174284b15d1d51f89669d4
/third_party/edk2/EmulatorPkg/Include/Guid/EmuPhysicalDisk.h
8461ee714253eef140c6d21bd9d17c12036864fd
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause", "OpenSSL" ]
permissive
google/google-ctf
f99da1ee07729bbccb869fff1cbaed6a80e43bcc
df02323eaf945d15e124801c74abaadca2749dc7
refs/heads/master
2023-08-31T14:30:27.548081
2023-08-29T13:04:20
2023-08-29T13:04:20
131,317,137
4,136
607
Apache-2.0
2023-08-30T22:17:02
2018-04-27T15:56:03
Go
UTF-8
C
false
false
798
h
EmuPhysicalDisk.h
/** @file Setup Variable data structure for Emu platform. Copyright (c) 2009, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #ifndef __EMU_PHYSICAL_DISK_H__ #define __EMU_PHYSICAL_DISK_H__ #define EFI_EMU_PHYSICAL_DISK_GUID \ { 0xf2ba331a, 0x8985, 0x11db, { 0xa4, 0x06, 0x00, 0x40, 0xd0, 0x2b, 0x18, 0x35 } } extern EFI_GUID gEmuPhysicalDisksGuid; #endif
479b0b7eb9eb90b9cf93b988d86609ea14fa904d
e1d9c54e9925e30e388a255b53a93cccad0b94cb
/kubernetes/unit-test/test_v1beta3_group_subject.c
898cbbbee8cf0dfc9eab3242c91df8046f9b1dc0
[ "Apache-2.0", "curl" ]
permissive
kubernetes-client/c
dd4fd8095485c083e0f40f2b48159b1609a6141b
5ac5ff25e9809a92a48111b1f77574b6d040b711
refs/heads/master
2023-08-13T10:51:03.702497
2023-08-07T19:18:32
2023-08-07T19:18:32
247,958,425
127
47
Apache-2.0
2023-09-07T20:07:00
2020-03-17T11:59:05
C
UTF-8
C
false
false
1,734
c
test_v1beta3_group_subject.c
#ifndef v1beta3_group_subject_TEST #define v1beta3_group_subject_TEST // the following is to include only the main from the first c file #ifndef TEST_MAIN #define TEST_MAIN #define v1beta3_group_subject_MAIN #endif // TEST_MAIN #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdbool.h> #include "../external/cJSON.h" #include "../model/v1beta3_group_subject.h" v1beta3_group_subject_t* instantiate_v1beta3_group_subject(int include_optional); v1beta3_group_subject_t* instantiate_v1beta3_group_subject(int include_optional) { v1beta3_group_subject_t* v1beta3_group_subject = NULL; if (include_optional) { v1beta3_group_subject = v1beta3_group_subject_create( "0" ); } else { v1beta3_group_subject = v1beta3_group_subject_create( "0" ); } return v1beta3_group_subject; } #ifdef v1beta3_group_subject_MAIN void test_v1beta3_group_subject(int include_optional) { v1beta3_group_subject_t* v1beta3_group_subject_1 = instantiate_v1beta3_group_subject(include_optional); cJSON* jsonv1beta3_group_subject_1 = v1beta3_group_subject_convertToJSON(v1beta3_group_subject_1); printf("v1beta3_group_subject :\n%s\n", cJSON_Print(jsonv1beta3_group_subject_1)); v1beta3_group_subject_t* v1beta3_group_subject_2 = v1beta3_group_subject_parseFromJSON(jsonv1beta3_group_subject_1); cJSON* jsonv1beta3_group_subject_2 = v1beta3_group_subject_convertToJSON(v1beta3_group_subject_2); printf("repeating v1beta3_group_subject:\n%s\n", cJSON_Print(jsonv1beta3_group_subject_2)); } int main() { test_v1beta3_group_subject(1); test_v1beta3_group_subject(0); printf("Hello world \n"); return 0; } #endif // v1beta3_group_subject_MAIN #endif // v1beta3_group_subject_TEST
8955219619095cfcb15e5d046fb8b87f9476f86d
227fe1226f59d6033e20ef456a1f8288091c5312
/tests/mocksupport/server.c
d51010fc0309171942aaae815e27c2fb46398fb6
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
couchbase/libcouchbase
697ca0f621bff80e242fa1099be8d0160dd2bc55
6e411d412ba3f5039d21ea4195dca86b0f82134b
refs/heads/master
2023-08-30T23:38:38.586108
2023-08-16T13:39:57
2023-08-16T14:41:12
2,077,002
120
100
Apache-2.0
2022-09-19T12:29:14
2011-07-20T08:43:46
C
UTF-8
C
false
false
9,614
c
server.c
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2011-2020 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "check_config.h" #include "server.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <ctype.h> #ifndef _WIN32 #define DIRSEP "/" #include <pthread.h> #include <sys/wait.h> #include <arpa/inet.h> #include <netinet/tcp.h> #include <netinet/in.h> #include <signal.h> #ifdef linux #undef ntohs #undef ntohl #undef htons #undef htonl #endif #else #define DIRSEP "\\" #include <io.h> /* for access() */ #endif /* ! _WIN32 */ static int create_monitor(struct test_server_info *info) { struct addrinfo hints, *next, *ai; int error; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; info->sock = -1; error = getaddrinfo(NULL, "0", &hints, &ai); if (error != 0) { #ifdef _WIN32 if (0) { #else if (error != EAI_SYSTEM) { #endif fprintf(stderr, "getaddrinfo failed: %s\n", gai_strerror(error)); } else { perror("getaddrinfo failed:"); } return 0; } for (next = ai; next; next = next->ai_next) { int flags = 1; socklen_t len; if ((info->sock = socket(next->ai_family, next->ai_socktype, next->ai_protocol)) == -1) { continue; } setsockopt(info->sock, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); if (bind(info->sock, next->ai_addr, next->ai_addrlen) == -1) { closesocket(info->sock); info->sock = -1; continue; } else if (listen(info->sock, 10) == -1) { closesocket(info->sock); info->sock = -1; continue; } /* Ok, I've got a working socket :) */ len = sizeof(info->storage); if (getsockname(info->sock, (struct sockaddr *)&info->storage, &len) == -1) { closesocket(info->sock); info->sock = -1; continue; } if (next->ai_addr->sa_family == AF_INET) { info->port = ntohs((*(struct sockaddr_in *)&info->storage).sin_port); } else { info->port = ntohs((*(struct sockaddr_in6 *)&info->storage).sin6_port); } } freeaddrinfo(ai); return info->sock != -1; } static void wait_for_server(const char *port) { struct addrinfo hints, *next, *ai; int sock = -1; int error; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; error = getaddrinfo("localhost", port, &hints, &ai); if (error != 0) { #ifndef _WIN32 if (error != EAI_SYSTEM) { #else if (0) { #endif fprintf(stderr, "getaddrinfo failed: %s\n", gai_strerror(error)); } else { perror("getaddrinfo failed:"); } abort(); } while (1) { for (next = ai; next; next = next->ai_next) { if ((sock = socket(next->ai_family, next->ai_socktype, next->ai_protocol)) == -1) { continue; } if (connect(sock, next->ai_addr, next->ai_addrlen) == 0) { closesocket(sock); freeaddrinfo(ai); return; } closesocket(sock); } usleep(250); } } /** * Parse server parameters from environment; * format is host,bucket,username,password */ static int parse_server_conf(struct test_server_info *info, const char *param) { char *strings[10] = {NULL}; int curix = 0; char *param_copy = strdup(param); param = param_copy; while (*param && curix < 10) { const char *curfld; char *curval; size_t diff; for (curfld = param; *param && *param != ','; param++) ; diff = (param - curfld); curval = calloc(1, diff + 1); curval[diff] = '\0'; memcpy(curval, curfld, diff); strings[curix++] = curval; if (*param == ',') { param++; } } info->http = strings[0]; info->bucket = strings[1]; info->username = strings[2]; info->password = strings[3]; free(param_copy); if (!info->http) { fprintf(stderr, "Must have node entry point for real cluster test\n"); return 0; } return 1; } static int start_mock_process(struct test_server_info *info, char **argv) { char argbuf[4096] = {0}; char **arg; for (arg = argv; *arg; arg++) { strcat(argbuf, *arg); strcat(argbuf, " "); } memset(&info->process, 0, sizeof(info->process)); info->process.name = argbuf; return create_process(&info->process); } static void kill_mock_process(struct test_server_info *info) { kill_process(&info->process, 1); wait_process(&info->process, 1); cleanup_process(&info->process); } #ifndef _WIN32 #define WRAPPER_BASE "start_mock.sh" #else #define WRAPPER_BASE "start_mock.bat" #endif static void negotiate_mock_connection(struct test_server_info *info) { char buffer[1024]; lcb_ssize_t offset; lcb_ssize_t nr; int ii; /* wait until the server connects */ for (ii = 0; ii < 10; ii++) { info->client = accept(info->sock, NULL, NULL); if (info->client == -1) { /* running this in gdb on OS X, I got an EINTR a few times */ if (errno == EINTR) { fprintf(stderr, "start_mock_server: Sleeping 1 second on EINTR\n"); sleep(1); } else { perror("start_mock_server"); abort(); } } else { break; } } lcb_assert(info->client != -1); /* Get the port number of the http server */ offset = snprintf(buffer, sizeof(buffer), "localhost:"); nr = recv(info->client, buffer + offset, sizeof(buffer) - (size_t)offset - 1, 0); lcb_assert(nr > 0); buffer[nr + offset] = '\0'; info->http = strdup(buffer); wait_for_server(buffer + offset); } static int start_mock_server(struct test_server_info *info, char **cmdline) { char wrapper[1024]; char monitor[1024]; char *argv[1024]; #ifdef _WIN32 int access_mode = 00; #else int access_mode = X_OK; #endif const char *srcdir = getenv("srcdir"); if (srcdir == NULL) { srcdir = TEST_SRC_DIR; } snprintf(wrapper, sizeof(wrapper), "%s" DIRSEP "tests" DIRSEP WRAPPER_BASE, srcdir); if (access(wrapper, access_mode) == -1) { fprintf(stderr, "Failed to locate \"%s\": %s\n", wrapper, strerror(errno)); return 0; } if (!create_monitor(info)) { return 0; } { int arg = 0; argv[arg++] = (char *)wrapper; snprintf(monitor, sizeof(monitor), "--harakiri-monitor=localhost:%d", info->port); argv[arg++] = monitor; if (cmdline != NULL) { int ii = 0; while (cmdline[ii] != NULL && arg < 1022) { argv[arg++] = cmdline[ii++]; } } argv[arg++] = NULL; } start_mock_process(info, argv); negotiate_mock_connection(info); return 1; } const void *start_test_server(char **cmdline) { const char *clconf = getenv(LCB_TEST_REALCLUSTER_ENV); int server_ok = 0; struct test_server_info *info = calloc(1, sizeof(*info)); #ifdef _WIN32 /** Winsock boilerplate */ { WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) { fprintf(stderr, "WSAStartup failed. Abort\n"); abort(); } } #endif if (info == NULL) { return NULL; } if (clconf) { server_ok = parse_server_conf(info, clconf); info->is_mock = 0; } else { server_ok = start_mock_server(info, cmdline); info->is_mock = 1; } if (!server_ok) { fprintf(stderr, "Couldn't setup server!\n"); abort(); } return info; } void shutdown_mock_server(const void *handle) { struct test_server_info *info = (void *)handle; if (info != NULL) { free(info->http); free(info->bucket); free(info->username); free(info->password); if (info->is_mock) { closesocket(info->client); closesocket(info->sock); kill_mock_process(info); } free((void *)handle); } } const char *get_mock_http_server(const void *handle) { struct test_server_info *info = (void *)handle; return info->http; } void get_mock_std_creds(const void *handle, const char **userp, const char **passp) { const struct test_server_info *info = handle; if (info->is_mock) { *userp = NULL; *passp = NULL; } else { *userp = info->username; *passp = info->password; } } int is_using_real_cluster(void) { return getenv(LCB_TEST_REALCLUSTER_ENV) != NULL; }
b7fc9d38d4c48be76c795563adee011fcecb3e78
35c04ea32351dc95bc18d46e5c70dda9c1e08668
/Examples/McuLib/McuLibVersion.h
dbeac10a0634ffb7fca348febc70047028ca9cec
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
ErichStyger/mcuoneclipse
0f8e7a2056a26ed79d9d4a0afd64777ff0b2b2fe
04ad311b11860ae5f8285316010961a87fa06d0c
refs/heads/master
2023-08-28T22:54:08.501719
2023-08-25T15:11:44
2023-08-25T15:11:44
7,446,094
620
1,191
NOASSERTION
2020-10-16T03:13:28
2013-01-04T19:38:12
Batchfile
UTF-8
C
false
false
609
h
McuLibVersion.h
/** * \file * \brief Version information header file for MCU library * Copyright (c) 2020-2022, Erich Styger * SPDX-License-Identifier: BSD-3-Clause */ #ifndef SOURCES_MCULIBVERSION_H_ #define SOURCES_MCULIBVERSION_H_ /* See * https://github.com/ErichStyger/McuOnEclipseLibrary * Date: 29-Dec-2022 * Time: 08:12 */ #define McuLib_VERSION_VERSION_MAJOR (1) /*!< McuLib major version number */ #define McuLib_VERSION_VERSION_MINOR (0) /*!< McuLib minor version number */ #define McuLib_VERSION_VERSION_BUILD (9) /*!< McuLib build version number */ #endif /* SOURCES_MCULIBVERSION_H_ */
f02f9d23a55b677a1b7d8c410594e439399122f7
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/net/afpfs-ng/files/patch-include__afpfs-ng__uams_def.h
2827b63ba7b6c25559e0bad81338a2c14cbd5e0f
[ "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C
false
false
635
h
patch-include__afpfs-ng__uams_def.h
--- include/afpfs-ng/uams_def.h.orig 1970-01-01 00:00:00.000000000 +0000 +++ include/afpfs-ng/uams_def.h 2012-10-14 13:11:34.000000000 +0000 @@ -0,0 +1,16 @@ +#ifndef __UAM_DEFS_H_ +#define __UAM_DEFS_H_ + +#define UAM_NOUSERAUTHENT 0x1 +#define UAM_CLEARTXTPASSWRD 0x2 +#define UAM_RANDNUMEXCHANGE 0x4 +#define UAM_2WAYRANDNUM 0x8 +#define UAM_DHCAST128 0x10 +#define UAM_CLIENTKRB 0x20 +#define UAM_DHX2 0x40 +#define UAM_RECON1 0x80 + +int uam_string_to_bitmap(char * name); +char * uam_bitmap_to_string(unsigned int bitmap); + +#endif diff -Naur afpfs-ng-0.8.1.orig/include/afpfs-ng/utils.h afpfs-ng-0.8.1/include/afpfs-ng/utils.h
d7bb4a0042d437a126f880eba01933d1f2592861
d579699e6728aa74084f8cc4dc435007b9f523a8
/tests/regression-tests/expected-outputs/OSX/o4/condcodexform/condcodexform/condcodexform.c
f897f89326a94fd771dcdacccc0599e84106f51e
[ "BSD-3-Clause" ]
permissive
BoomerangDecompiler/boomerang
b3c6b4e88c152ac6d437f3dd3640fd9ffa157cb6
411041305f90d1d7c994f67255b5c03ea8666e60
refs/heads/develop
2023-08-31T03:50:56.112711
2020-12-28T12:11:55
2020-12-28T17:38:56
7,819,729
281
41
NOASSERTION
2020-12-27T17:59:52
2013-01-25T12:26:59
C++
UTF-8
C
false
false
2,162
c
condcodexform.c
int main(int argc, char *argv[]); __size32 global_0x00002020;// 4 bytes __size32 global_0x00002024;// 4 bytes __size32 global_0x00002028;// 4 bytes __size32 global_0x0000202c;// 4 bytes __size32 global_0x00002030;// 4 bytes __size32 global_0x00002034;// 4 bytes __size32 global_0x00002038;// 4 bytes __size32 global_0x0000203c;// 4 bytes /** address: 0x00001c20 */ int main(int argc, char *argv[]) { int CR0; // r100 int CR1; // r101 int CR2; // r102 int CR3; // r103 int CR4; // r104 int CR5; // r105 int CR6; // r106 __size32 CR7; // r107 int g0; // r0 int g0_1; // r0{24} __size32 g0_2; // r0{2} __size32 g0_3; // r0{26} __size32 g0_6; // r0{48} int g10; // r10 int g11; // r11 int g3; // r3 int g8; // r8 int g9; // r9 __size32 local0; // g0_2{2} g0 = 1; if (argc <= 1) { g0 = 0; } g0_1 = g0; if (g0_1 == 0) { g0_6 = global_0x00002038; local0 = g0_6; } else { g0_3 = global_0x0000203c; local0 = g0_3; } g0_2 = local0; if (g0_1 == 0) { g11 = global_0x00002030; } else { g11 = global_0x00002034; } if (g0_1 == 0) { g10 = global_0x00002028; } else { g10 = global_0x0000202c; } if (g0_1 == 0) { g8 = global_0x00002020; } else { g8 = global_0x00002024; } if (g0_1 <= 0) { g3 = 0; if (g0_2 == global_0x00002038 && g11 == global_0x00002030 && g10 == global_0x00002028) { g9 = global_0x00002020; bb0x1d34: g3 = 0; if (g8 == g9) { g3 = 1; } } } else { g3 = 0; if (g0_2 == global_0x0000203c && g11 == global_0x00002034 && g10 == global_0x0000202c) { g9 = global_0x00002024; goto bb0x1d34; } } if (g3 == 0) { g3 = "Failed!"; } else { g3 = "Pass"; } puts(g3); return ROTL(((CR0 << 28) + (CR1 << 24) + (CR2 << 20) + (CR3 << 16) + (CR4 << 12) + (CR5 << 8) + (CR6 << 4) + CR7), 19) & 0x1; }
3756f234e63027b64cd29b11e6495b4fcbc13ca0
19a9f2c19bcb81c4a14ba17831d3098de7731fb5
/ncarg2d/src/libncarg/support/bccom.h
dfb2a16618de03ef41cfd22f277917d5929dd243
[ "Apache-2.0" ]
permissive
NCAR/ncl
243c30eaefce642d53373aa583b73df72eb59f22
8a96101fe14d0cf0f5ed66a5e6b1733084bc69df
refs/heads/develop
2023-03-17T07:53:18.883458
2022-05-11T16:01:03
2022-05-11T16:01:03
67,087,395
254
68
NOASSERTION
2022-10-08T07:20:06
2016-09-01T01:34:28
C
UTF-8
C
false
false
378
h
bccom.h
C C $Id: bccom.h,v 1.4 2008-07-27 03:54:15 haley Exp $ C C Copyright (C) 2000 C University Corporation for Atmospheric Research C All Rights Reserved C C The use of this Software is governed by a License Agreement. C COMMON /BCCOM/FRATIO,NPPC SAVE /BCCOM/
d14097cb26c78275e583bc6f1377ffbf44e1579a
317410b28757af216145d23259d63fc96d07f613
/apps/spp_and_le/examples/multi_conn/ble_multi_central.c
79f8148487cd18f6c979d70fe9386539fa194061
[ "Apache-2.0" ]
permissive
Jieli-Tech/fw-AC63_BT_SDK
48c757dca7e8000ec763bf5466583a4cd8c4a11c
393d63758081d56f0bf0a39ac596bee32c33d493
refs/heads/master
2023-07-18T02:14:56.187266
2023-06-21T03:14:20
2023-06-21T03:14:20
272,586,610
113
76
Apache-2.0
2022-10-20T23:07:31
2020-06-16T02:02:15
C
UTF-8
C
false
false
21,220
c
ble_multi_central.c
/********************************************************************************************* * Filename : .c * Description : * Author :JM * Email : zh-jieli.com * Last modifiled : 2017-01-17 11:14 * Copyright:(c)JIELI 2011-2016 @ , All Rights Reserved. *********************************************************************************************/ #include "system/app_core.h" #include "system/includes.h" #include "app_config.h" #include "app_action.h" #include "btstack/btstack_task.h" #include "btstack/bluetooth.h" #include "user_cfg.h" #include "vm.h" #include "btcontroller_modules.h" #include "bt_common.h" #include "3th_profile_api.h" #include "le_common.h" #include "rcsp_bluetooth.h" #include "JL_rcsp_api.h" #include "custom_cfg.h" #include "btstack/btstack_event.h" #include "ble_multi.h" #include "le_client_demo.h" #include "gatt_common/le_gatt_common.h" #if CONFIG_APP_MULTI && CONFIG_BT_GATT_CLIENT_NUM #if LE_DEBUG_PRINT_EN #define log_info(x, ...) printf("[MUL-CEN]" x " ", ## __VA_ARGS__) #define log_info_hexdump put_buf #else #define log_info(...) #define log_info_hexdump(...) #endif //搜索类型 #define SET_SCAN_TYPE SCAN_ACTIVE //搜索 周期大小 #define SET_SCAN_INTERVAL ADV_SCAN_MS(24) // unit: 0.625ms //搜索 窗口大小 #define SET_SCAN_WINDOW ADV_SCAN_MS(8) // unit: 0.625ms, <= SET_SCAN_INTERVAL //连接周期 #define BASE_INTERVAL_MIN (6)//最小的interval #define SET_CONN_INTERVAL (BASE_INTERVAL_MIN*8) //(unit:1.25ms) //连接latency #define SET_CONN_LATENCY 0 //(unit:conn_interval) //连接超时 #define SET_CONN_TIMEOUT 400 //(unit:10ms) //建立连接超时 #define SET_CREAT_CONN_TIMEOUT 8000 //(unit:ms) //配对信息表 #define CLIENT_PAIR_BOND_ENABLE CONFIG_BT_SM_SUPPORT_ENABLE #define CLIENT_PAIR_BOND_TAG 0x56 struct ctl_pair_info_t { u8 head_tag; u8 match_dev_id; u8 pair_flag; u8 peer_address_info[7]; u16 conn_handle; u16 conn_interval; u16 conn_latency; u16 conn_timeout; }; /* static u8 cur_peer_addr_info[7]; //当前连接对方地址信息 */ /* static u8 client_pair_bond_info[8]; //tag + addr_type + address */ static struct ctl_pair_info_t cur_conn_info; static struct ctl_pair_info_t record_bond_info[SUPPORT_MAX_GATT_CLIENT]; static u8 multi_pair_reconnect_search_profile = 1; /*配对回连是否搜索profile*/ static u8 multi_sm_master_pair_redo; /*配对回连keymiss,是否重新执行配对*/ static int multi_client_event_packet_handler(int event, u8 *packet, u16 size, u8 *ext_param); static void multi_scan_conn_config_set(struct ctl_pair_info_t *pair_info); const gatt_client_cfg_t mul_client_init_cfg = { .event_packet_handler = multi_client_event_packet_handler, }; //--------------------------------------------------------------------------- static scan_conn_cfg_t multi_client_scan_cfg; static u16 multi_ble_client_write_handle; #define MULTI_TEST_WRITE_SEND_DATA 1 //测试发数 //--------------------------------------------------------------------------- //指定搜索uuid //指定搜索uuid static const target_uuid_t jl_multi_search_uuid_table[] = { // for uuid16 // PRIMARY_SERVICE, ae30 // CHARACTERISTIC, ae01, WRITE_WITHOUT_RESPONSE | DYNAMIC, // CHARACTERISTIC, ae02, NOTIFY, { .services_uuid16 = 0xae30, .characteristic_uuid16 = 0xae01, .opt_type = ATT_PROPERTY_WRITE_WITHOUT_RESPONSE, }, { .services_uuid16 = 0xae30, .characteristic_uuid16 = 0xae02, .opt_type = ATT_PROPERTY_NOTIFY, }, //for uuid128,sample // PRIMARY_SERVICE, 0000F530-1212-EFDE-1523-785FEABCD123 // CHARACTERISTIC, 0000F531-1212-EFDE-1523-785FEABCD123, NOTIFY, // CHARACTERISTIC, 0000F532-1212-EFDE-1523-785FEABCD123, WRITE_WITHOUT_RESPONSE | DYNAMIC, /* { .services_uuid16 = 0, .services_uuid128 = {0x00,0x00,0xF5,0x30 ,0x12,0x12 ,0xEF, 0xDE ,0x15,0x23 ,0x78,0x5F,0xEA ,0xBC,0xD1,0x23} , .characteristic_uuid16 = 0, .characteristic_uuid128 = {0x00,0x00,0xF5,0x31 ,0x12,0x12 ,0xEF, 0xDE ,0x15,0x23 ,0x78,0x5F,0xEA ,0xBC,0xD1,0x23}, .opt_type = ATT_PROPERTY_NOTIFY, }, { .services_uuid16 = 0, .services_uuid128 = {0x00,0x00,0xF5,0x30 ,0x12,0x12 ,0xEF, 0xDE ,0x15,0x23 ,0x78,0x5F,0xEA ,0xBC,0xD1,0x23} , .characteristic_uuid16 = 0, .characteristic_uuid128 = {0x00,0x00,0xF5,0x32 ,0x12,0x12 ,0xEF, 0xDE ,0x15,0x23 ,0x78,0x5F,0xEA ,0xBC,0xD1,0x23}, .opt_type = ATT_PROPERTY_WRITE_WITHOUT_RESPONSE, }, */ }; //配置多个扫描匹配设备 static const u8 cetl_test_remoter_name1[] = "AC897N_MX(BLE)";// static const client_match_cfg_t multi_match_device_table[] = { { .create_conn_mode = BIT(CLI_CREAT_BY_NAME), .compare_data_len = sizeof(cetl_test_remoter_name1) - 1, //去结束符 .compare_data = cetl_test_remoter_name1, .filter_pdu_bitmap = 0, }, }; //带绑定的设备搜索 static client_match_cfg_t *multi_bond_device_table; static u16 bond_device_table_cnt; //测试write数据操作 static void multi_client_test_write(void) { #if MULTI_TEST_WRITE_SEND_DATA static u32 count = 0; int i, ret = 0; u16 tmp_handle; count++; for (i = 0; i < SUPPORT_MAX_GATT_CLIENT; i++) { tmp_handle = ble_comm_dev_get_handle(i, GATT_ROLE_CLIENT); if (tmp_handle && multi_ble_client_write_handle) { ret = ble_comm_att_send_data(tmp_handle, multi_ble_client_write_handle, &count, 16, ATT_OP_WRITE_WITHOUT_RESPOND); log_info("test_write:%04x,%d", tmp_handle, ret); } } #endif } //配置扫描匹配连接的设备,已经连上后搜索匹配的profile uuid static const gatt_search_cfg_t multil_client_search_config = { .match_devices = multi_match_device_table, .match_devices_count = (sizeof(multi_match_device_table) / sizeof(client_match_cfg_t)), .match_rssi_enable = 0, .search_uuid_group = jl_multi_search_uuid_table, .search_uuid_count = (sizeof(jl_multi_search_uuid_table) / sizeof(target_uuid_t)), .auto_enable_ccc = 1, }; //配置扫描匹配连接绑定后的设备 static gatt_search_cfg_t multil_client_bond_config = { .match_devices = NULL, .match_devices_count = 0, .match_rssi_enable = 0, .search_uuid_group = jl_multi_search_uuid_table, .search_uuid_count = (sizeof(jl_multi_search_uuid_table) / sizeof(target_uuid_t)), .auto_enable_ccc = 1, }; /*更新连接设备的匹配配置*/ static void multi_client_reflash_bond_search_config(void) { int i; if (!multi_bond_device_table) { log_info("device tabl is null!"); return; } /*建立对应关系 配对表(匹配地址) + 默认匹配表 multi_match_device_table*/ for (i = 0; i < SUPPORT_MAX_GATT_CLIENT; i++) { multi_bond_device_table[i].create_conn_mode = BIT(CLI_CREAT_BY_ADDRESS); multi_bond_device_table[i].compare_data_len = 6; multi_bond_device_table[i].compare_data = &record_bond_info[i].peer_address_info[1]; if (CLIENT_PAIR_BOND_TAG == record_bond_info[i].head_tag) { r_printf("set bond search: %d\n", i); multi_bond_device_table[i].filter_pdu_bitmap = BIT(EVENT_ADV_SCAN_IND) | BIT(EVENT_ADV_NONCONN_IND); } else { multi_bond_device_table[i].filter_pdu_bitmap = EVENT_DEFAULT_REPORT_BITMAP; } } memcpy(&multi_bond_device_table[SUPPORT_MAX_GATT_CLIENT], multi_match_device_table, sizeof(multi_match_device_table)); multil_client_bond_config.match_devices = multi_bond_device_table; multil_client_bond_config.match_devices_count = bond_device_table_cnt; ble_gatt_client_set_search_config(&multil_client_bond_config); } //------------------------------------------------------------------------------------- //vm 绑定对方信息读写 static int multi_client_pair_vm_do(struct ctl_pair_info_t *info, u8 rw_flag) { int ret = 0; #if CLIENT_PAIR_BOND_ENABLE int i; int uint_len = sizeof(struct ctl_pair_info_t); log_info("-conn_pair_info vm_do:%d\n", rw_flag); if (rw_flag == 0) { ret = syscfg_read(CFG_BLE_BONDING_REMOTE_INFO2, (u8 *)&record_bond_info, uint_len * SUPPORT_MAX_GATT_CLIENT); if (!ret) { log_info("-null--\n"); memset((u8 *)&record_bond_info, 0xff, uint_len * SUPPORT_MAX_GATT_CLIENT); ret = 1; } /*检查合法性*/ for (i = 0; i < SUPPORT_MAX_GATT_CLIENT; i++) { if (CLIENT_PAIR_BOND_TAG != record_bond_info[i].head_tag || record_bond_info[i].pair_flag != 1) { memset((u8 *)&record_bond_info[i], 0xff, uint_len); } } } else { int fill_index = -1; if (info == NULL) { log_info("vm clear\n"); memset((u8 *)&record_bond_info, 0xff, uint_len * SUPPORT_MAX_GATT_CLIENT); } else { for (i = 0; i < SUPPORT_MAX_GATT_CLIENT; i++) { if (0 == memcmp(info, &record_bond_info[i], uint_len)) { log_info("dev in table\n"); return ret; } } put_buf((u8 *)&record_bond_info, uint_len * SUPPORT_MAX_GATT_CLIENT); put_buf((u8 *)info, uint_len); r_printf("write vm start\n"); log_info("find table\n"); /*find same*/ if (fill_index == -1) { for (i = 0; i < SUPPORT_MAX_GATT_CLIENT; i++) { if (0 == memcmp(info->peer_address_info, &record_bond_info[i].peer_address_info, 7)) { log_info("replace old\n"); fill_index = i; break; } } } /*find idle*/ if (fill_index == -1) { for (i = 0; i < SUPPORT_MAX_GATT_CLIENT; i++) { if (CLIENT_PAIR_BOND_TAG != record_bond_info[i].head_tag) { log_info("find idle\n"); fill_index = i; break; } } } /*find first*/ if (fill_index == -1) { for (i = 1; i < SUPPORT_MAX_GATT_CLIENT; i++) { memcpy(&record_bond_info[i - 1], &record_bond_info[i], uint_len); record_bond_info[i - 1].match_dev_id = i - 1; /*change id*/ } log_info("replace first\n"); fill_index = SUPPORT_MAX_GATT_CLIENT - 1; } /*连接顺序不同,handle是不一样,防止重复相同*/ for (i = 0; i < SUPPORT_MAX_GATT_CLIENT; i++) { if (info->conn_handle == record_bond_info[i].conn_handle) { record_bond_info[i].conn_handle = 0; log_info("clear repeat handle\n"); } } info->match_dev_id = fill_index;/*change id*/ memcpy(&record_bond_info[fill_index], info, uint_len); } syscfg_write(CFG_BLE_BONDING_REMOTE_INFO2, (u8 *)&record_bond_info, uint_len * SUPPORT_MAX_GATT_CLIENT); } put_buf((u8 *)&record_bond_info, uint_len * SUPPORT_MAX_GATT_CLIENT); multi_client_reflash_bond_search_config();/*配对表发生变化,更新scan设备匹配*/ #endif return ret; } //清配对信息 int multi_client_clear_pair(void) { #if CLIENT_PAIR_BOND_ENABLE ble_gatt_client_disconnect_all(); memset(&cur_conn_info, 0, sizeof(cur_conn_info)); multi_client_pair_vm_do(NULL, 1); if (BLE_ST_SCAN == ble_gatt_client_get_work_state()) { ble_gatt_client_scan_enable(0); ble_gatt_client_scan_enable(1); } #endif return 0; } //处理gatt 回调的事件,hci & gatt static int multi_client_event_packet_handler(int event, u8 *packet, u16 size, u8 *ext_param) { /* log_info("event: %02x,size= %d\n",event,size); */ switch (event) { case GATT_COMM_EVENT_GATT_DATA_REPORT: { att_data_report_t *report_data = (void *)packet; log_info("data_report:hdl=%04x,pk_type=%02x,size=%d\n", report_data->conn_handle, report_data->packet_type, report_data->blob_length); put_buf(report_data->blob, report_data->blob_length); switch (report_data->packet_type) { case GATT_EVENT_NOTIFICATION://notify break; case GATT_EVENT_INDICATION://indicate break; case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT://read break; case GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT://read long break; default: break; } } break; case GATT_COMM_EVENT_CAN_SEND_NOW: break; case GATT_COMM_EVENT_CONNECTION_COMPLETE: log_info("connection_handle:%04x\n", little_endian_read_16(packet, 0)); log_info("con_interval = %d\n", little_endian_read_16(ext_param, 14 + 0)); log_info("con_latency = %d\n", little_endian_read_16(ext_param, 14 + 2)); log_info("cnn_timeout = %d\n", little_endian_read_16(ext_param, 14 + 4)); log_info("peer_address_info:"); put_buf(&ext_param[7], 7); memcpy(cur_conn_info.peer_address_info, &ext_param[7], 7); cur_conn_info.conn_handle = little_endian_read_16(packet, 0); cur_conn_info.conn_interval = little_endian_read_16(ext_param, 14 + 0); cur_conn_info.conn_latency = little_endian_read_16(ext_param, 14 + 2); cur_conn_info.conn_timeout = little_endian_read_16(ext_param, 14 + 4); cur_conn_info.pair_flag = 0; cur_conn_info.head_tag = 0; break; case GATT_COMM_EVENT_DISCONNECT_COMPLETE: log_info("disconnect_handle:%04x,reason= %02x\n", little_endian_read_16(packet, 0), packet[2]); break; case GATT_COMM_EVENT_ENCRYPTION_CHANGE: log_info("ENCRYPTION_CHANGE:handle=%04x,state=%d,process =%d", little_endian_read_16(packet, 0), packet[2], packet[3]); if (packet[3] == LINK_ENCRYPTION_RECONNECT) { log_info("reconnect...\n"); } else { log_info("first pair...\n"); } #if CLIENT_PAIR_BOND_ENABLE cur_conn_info.head_tag = CLIENT_PAIR_BOND_TAG; cur_conn_info.pair_flag = 1; multi_client_pair_vm_do(&cur_conn_info, 1); #endif break; case GATT_COMM_EVENT_CONNECTION_UPDATE_COMPLETE: log_info("conn_param update_complete:%04x\n", little_endian_read_16(packet, 0)); log_info("update_interval = %d\n", little_endian_read_16(ext_param, 6 + 0)); log_info("update_latency = %d\n", little_endian_read_16(ext_param, 6 + 2)); log_info("update_timeout = %d\n", little_endian_read_16(ext_param, 6 + 4)); if (cur_conn_info.conn_handle == little_endian_read_16(packet, 0)) { cur_conn_info.conn_interval = little_endian_read_16(ext_param, 6 + 0); cur_conn_info.conn_latency = little_endian_read_16(ext_param, 6 + 2); cur_conn_info.conn_timeout = little_endian_read_16(ext_param, 6 + 4); } #if CLIENT_PAIR_BOND_ENABLE if (cur_conn_info.conn_handle == little_endian_read_16(packet, 0)) { if (cur_conn_info.pair_flag) { log_info("update_cur_conn\n"); multi_client_pair_vm_do(&cur_conn_info, 1); } } else { struct ctl_pair_info_t tmp_conn_info; for (int i = 0; i < SUPPORT_MAX_GATT_CLIENT; i++) { if (record_bond_info[i].pair_flag && record_bond_info[i].conn_handle == little_endian_read_16(packet, 0)) { log_info("update_record_conn\n"); memcpy(&tmp_conn_info, &record_bond_info[i], sizeof(struct ctl_pair_info_t)); tmp_conn_info.conn_interval = little_endian_read_16(ext_param, 6 + 0); tmp_conn_info.conn_latency = little_endian_read_16(ext_param, 6 + 2); tmp_conn_info.conn_timeout = little_endian_read_16(ext_param, 6 + 4); multi_client_pair_vm_do(&tmp_conn_info, 1); break; } } } #endif break; case GATT_COMM_EVENT_SCAN_DEV_MATCH: { log_info("match_dev:addr_type= %d\n", packet[0]); put_buf(&packet[1], 6); if (packet[8] == 2) { log_info("is TEST_BOX\n"); } client_match_cfg_t *match_cfg = ext_param; if (match_cfg) { log_info("match_mode: %d\n", match_cfg->create_conn_mode); if (match_cfg->compare_data_len) { put_buf(match_cfg->compare_data, match_cfg->compare_data_len); } } //update info cur_conn_info.conn_handle = 0; cur_conn_info.pair_flag = 0; cur_conn_info.match_dev_id = packet[9]; #if CLIENT_PAIR_BOND_ENABLE if (packet[9] < SUPPORT_MAX_GATT_CLIENT) { /*记录表回连,使用记录的连接参数建立*/ r_printf("match bond,reconnect\n"); multi_scan_conn_config_set(&record_bond_info[packet[9]]); if (!multi_pair_reconnect_search_profile) { multil_client_bond_config.search_uuid_count = 0;//set no search } } else { /*记录表回连,使用记录的连接参数建立*/ r_printf("match config\n"); multi_scan_conn_config_set(NULL); } #endif } break; case GATT_COMM_EVENT_GATT_SEARCH_MATCH_UUID: { opt_handle_t *opt_hdl = packet; log_info("match:server_uuid= %04x,charactc_uuid= %04x,value_handle= %04x\n", \ opt_hdl->search_uuid->services_uuid16, opt_hdl->search_uuid->characteristic_uuid16, opt_hdl->value_handle); #if MULTI_TEST_WRITE_SEND_DATA //for test if (opt_hdl->search_uuid->characteristic_uuid16 == 0xae01) { multi_ble_client_write_handle = opt_hdl->value_handle; } #endif } break; case GATT_COMM_EVENT_MTU_EXCHANGE_COMPLETE: log_info("con_handle= %02x, ATT MTU = %u\n", little_endian_read_16(packet, 0), little_endian_read_16(packet, 2)); break; case GATT_COMM_EVENT_GATT_SEARCH_PROFILE_COMPLETE: #if CLIENT_PAIR_BOND_ENABLE if (!multi_pair_reconnect_search_profile) { multil_client_bond_config.search_uuid_count = (sizeof(jl_multi_search_uuid_table) / sizeof(target_uuid_t));//recover } #endif break; case GATT_COMM_EVENT_CLIENT_STATE: log_info("client_state: handle=%02x,%02x\n", little_endian_read_16(packet, 1), packet[0]); break; default: break; } return 0; } //scan参数设置 static void multi_scan_conn_config_set(struct ctl_pair_info_t *pair_info) { multi_client_scan_cfg.scan_auto_do = 1; multi_client_scan_cfg.creat_auto_do = 1; multi_client_scan_cfg.scan_type = SET_SCAN_TYPE; multi_client_scan_cfg.scan_filter = 1; multi_client_scan_cfg.scan_interval = SET_SCAN_INTERVAL; multi_client_scan_cfg.scan_window = SET_SCAN_WINDOW; if (pair_info) { log_info("pair_to_creat:%d,%d,%d\n", pair_info->conn_interval, pair_info->conn_latency, pair_info->conn_timeout); multi_client_scan_cfg.creat_conn_interval = pair_info->conn_interval; multi_client_scan_cfg.creat_conn_latency = pair_info->conn_latency; multi_client_scan_cfg.creat_conn_super_timeout = pair_info->conn_timeout; } else { multi_client_scan_cfg.creat_conn_interval = SET_CONN_INTERVAL; multi_client_scan_cfg.creat_conn_latency = SET_CONN_LATENCY; multi_client_scan_cfg.creat_conn_super_timeout = SET_CONN_TIMEOUT; } multi_client_scan_cfg.conn_update_accept = 1; multi_client_scan_cfg.creat_state_timeout_ms = SET_CREAT_CONN_TIMEOUT; ble_gatt_client_set_scan_config(&multi_client_scan_cfg); } //multi client 初始化 void multi_client_init(void) { log_info("%s", __FUNCTION__); int i; #if CLIENT_PAIR_BOND_ENABLE if (!multi_bond_device_table) { int table_size = sizeof(multi_match_device_table) + sizeof(client_match_cfg_t) * SUPPORT_MAX_GATT_CLIENT; bond_device_table_cnt = multil_client_search_config.match_devices_count + SUPPORT_MAX_GATT_CLIENT; multi_bond_device_table = malloc(table_size); ASSERT(multi_bond_device_table != NULL, "%s,malloc fail!", __func__); memset(multi_bond_device_table, 0, table_size); } if (0 == multi_client_pair_vm_do(NULL, 0)) { log_info("client already bond dev"); } if (multi_sm_master_pair_redo) { sm_set_master_pair_redo(multi_sm_master_pair_redo); } #else ble_gatt_client_set_search_config(&multil_client_search_config); #endif multi_scan_conn_config_set(NULL); #if MULTI_TEST_WRITE_SEND_DATA sys_timer_add(0, multi_client_test_write, 500); #endif } //multi exit void multi_client_exit(void) { if (!multi_bond_device_table) { free(multi_bond_device_table); multi_bond_device_table = NULL; } } #endif
c0888957ffad908306580fc9a9ebca57fec778e3
0ba9681b235b377b3f57d52532ab7212d4d4cd8a
/intTests/test0024_llvm_assert_false/test0024.c
72a79c877ddbe27110a9891e69031896b5eea8f4
[ "BSD-3-Clause" ]
permissive
GaloisInc/saw-script
d9a3eb7b05c1bcbcc319987223cd53b903b55b5d
79ddd800bec59528958ed6d7593304e2b17b7dfb
refs/heads/master
2023-09-01T09:47:31.415255
2023-08-30T11:26:08
2023-08-30T11:26:08
34,082,065
458
82
BSD-3-Clause
2023-09-14T16:23:09
2015-04-16T21:39:32
Haskell
UTF-8
C
false
false
32
c
test0024.c
int id(int x) { return x; }
e5d63bfb2f8f9cdd61d75331a0181b73a2699d43
58fe7cb3949dd1930e709696659a0296500b64a6
/tests/unit/s2n_handshake_partial_test.c
0ec829635d83b7961b1a4049e3b3594880f0d83d
[ "Apache-2.0", "MIT" ]
permissive
aws/s2n-tls
3344638a6a69c6f20665cf6847e1bc4b85f2e558
62dc7a6d4876e5eee0dea3690d528a4c7080a1d5
refs/heads/main
2023-08-31T23:26:33.780048
2023-08-31T05:17:33
2023-08-31T05:17:33
21,287,076
513
213
Apache-2.0
2023-09-13T23:52:29
2014-06-27T19:37:59
C
UTF-8
C
false
false
9,203
c
s2n_handshake_partial_test.c
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "s2n_test.h" #include "testlib/s2n_testlib.h" #include "tls/s2n_handshake.h" #include "tls/s2n_record.h" #include "tls/s2n_tls.h" static S2N_RESULT s2n_get_test_client_and_server(struct s2n_connection **client_conn, struct s2n_connection **server_conn, struct s2n_config *config) { *client_conn = s2n_connection_new(S2N_CLIENT); RESULT_ENSURE_REF(*client_conn); *server_conn = s2n_connection_new(S2N_SERVER); RESULT_GUARD_POSIX(s2n_connection_set_blinding(*server_conn, S2N_SELF_SERVICE_BLINDING)); RESULT_ENSURE_REF(*server_conn); RESULT_GUARD_POSIX(s2n_connection_set_config(*client_conn, config)); RESULT_GUARD_POSIX(s2n_connection_set_config(*server_conn, config)); struct s2n_test_io_pair io_pair = { 0 }; RESULT_GUARD_POSIX(s2n_io_pair_init_non_blocking(&io_pair)); RESULT_GUARD_POSIX(s2n_connections_set_io_pair(*client_conn, *server_conn, &io_pair)); return S2N_RESULT_OK; } int main() { BEGIN_TEST(); if (!s2n_is_tls13_fully_supported()) { END_TEST(); } const uint8_t test_psk_data[] = "very secret"; DEFER_CLEANUP(struct s2n_psk *test_psk = s2n_external_psk_new(), s2n_psk_free); EXPECT_SUCCESS(s2n_psk_set_identity(test_psk, test_psk_data, sizeof(test_psk_data))); EXPECT_SUCCESS(s2n_psk_set_secret(test_psk, test_psk_data, sizeof(test_psk_data))); EXPECT_SUCCESS(s2n_psk_configure_early_data(test_psk, 100, 0x13, 0x01)); struct s2n_cert_chain_and_key *cert_chain = NULL; EXPECT_SUCCESS(s2n_test_cert_chain_and_key_new(&cert_chain, S2N_DEFAULT_ECDSA_TEST_CERT_CHAIN, S2N_DEFAULT_ECDSA_TEST_PRIVATE_KEY)); struct s2n_config *config = s2n_config_new(); EXPECT_SUCCESS(s2n_config_add_cert_chain_and_key_to_store(config, cert_chain)); EXPECT_SUCCESS(s2n_config_set_unsafe_for_testing(config)); EXPECT_SUCCESS(s2n_config_set_cipher_preferences(config, "default_tls13")); /* Test s2n_negotiate_until_message */ { /* Safety */ { struct s2n_connection conn = { 0 }; s2n_blocked_status blocked = 0; EXPECT_ERROR_WITH_ERRNO(s2n_negotiate_until_message(NULL, &blocked, CLIENT_HELLO), S2N_ERR_NULL); EXPECT_ERROR_WITH_ERRNO(s2n_negotiate_until_message(&conn, NULL, CLIENT_HELLO), S2N_ERR_NULL); }; /* If message is never encountered, complete the handshake */ { struct s2n_connection *client_conn = NULL, *server_conn = NULL; EXPECT_OK(s2n_get_test_client_and_server(&client_conn, &server_conn, config)); EXPECT_OK(s2n_negotiate_test_server_and_client_until_message(server_conn, client_conn, SERVER_KEY)); EXPECT_EQUAL(s2n_conn_get_current_message_type(client_conn), APPLICATION_DATA); EXPECT_EQUAL(s2n_conn_get_current_message_type(server_conn), APPLICATION_DATA); EXPECT_SUCCESS(s2n_connection_free(client_conn)); EXPECT_SUCCESS(s2n_connection_free(server_conn)); }; /* Can stop on a given message */ { struct s2n_connection *client_conn = NULL, *server_conn = NULL; EXPECT_OK(s2n_get_test_client_and_server(&client_conn, &server_conn, config)); EXPECT_OK(s2n_negotiate_test_server_and_client_until_message(server_conn, client_conn, SERVER_CERT_VERIFY)); EXPECT_EQUAL(s2n_conn_get_current_message_type(client_conn), SERVER_CERT_VERIFY); EXPECT_EQUAL(s2n_conn_get_current_message_type(server_conn), SERVER_CERT_VERIFY); EXPECT_SUCCESS(s2n_connection_free(client_conn)); EXPECT_SUCCESS(s2n_connection_free(server_conn)); }; /* Can be called repeatedly */ { struct s2n_connection *client_conn = NULL, *server_conn = NULL; EXPECT_OK(s2n_get_test_client_and_server(&client_conn, &server_conn, config)); EXPECT_OK(s2n_negotiate_test_server_and_client_until_message(server_conn, client_conn, CLIENT_HELLO)); EXPECT_EQUAL(s2n_conn_get_current_message_type(client_conn), CLIENT_HELLO); EXPECT_EQUAL(s2n_conn_get_current_message_type(server_conn), CLIENT_HELLO); EXPECT_OK(s2n_negotiate_test_server_and_client_until_message(server_conn, client_conn, CLIENT_HELLO)); EXPECT_EQUAL(s2n_conn_get_current_message_type(client_conn), CLIENT_HELLO); EXPECT_EQUAL(s2n_conn_get_current_message_type(server_conn), CLIENT_HELLO); EXPECT_OK(s2n_negotiate_test_server_and_client_until_message(server_conn, client_conn, SERVER_HELLO)); EXPECT_EQUAL(s2n_conn_get_current_message_type(client_conn), SERVER_HELLO); EXPECT_EQUAL(s2n_conn_get_current_message_type(server_conn), SERVER_HELLO); EXPECT_OK(s2n_negotiate_test_server_and_client_until_message(server_conn, client_conn, SERVER_HELLO)); EXPECT_EQUAL(s2n_conn_get_current_message_type(client_conn), SERVER_HELLO); EXPECT_EQUAL(s2n_conn_get_current_message_type(server_conn), SERVER_HELLO); EXPECT_OK(s2n_negotiate_test_server_and_client_until_message(server_conn, client_conn, APPLICATION_DATA)); EXPECT_EQUAL(s2n_conn_get_current_message_type(client_conn), APPLICATION_DATA); EXPECT_EQUAL(s2n_conn_get_current_message_type(server_conn), APPLICATION_DATA); EXPECT_OK(s2n_negotiate_test_server_and_client_until_message(server_conn, client_conn, APPLICATION_DATA)); EXPECT_EQUAL(s2n_conn_get_current_message_type(client_conn), APPLICATION_DATA); EXPECT_EQUAL(s2n_conn_get_current_message_type(server_conn), APPLICATION_DATA); EXPECT_SUCCESS(s2n_connection_free(client_conn)); EXPECT_SUCCESS(s2n_connection_free(server_conn)); }; /* Can continue as normal after stopping */ { struct s2n_connection *client_conn = NULL, *server_conn = NULL; EXPECT_OK(s2n_get_test_client_and_server(&client_conn, &server_conn, config)); EXPECT_OK(s2n_negotiate_test_server_and_client_until_message(server_conn, client_conn, CLIENT_FINISHED)); EXPECT_EQUAL(s2n_conn_get_current_message_type(client_conn), CLIENT_FINISHED); EXPECT_EQUAL(s2n_conn_get_current_message_type(server_conn), CLIENT_FINISHED); EXPECT_SUCCESS(s2n_negotiate_test_server_and_client(server_conn, client_conn)); EXPECT_EQUAL(s2n_conn_get_current_message_type(client_conn), APPLICATION_DATA); EXPECT_EQUAL(s2n_conn_get_current_message_type(server_conn), APPLICATION_DATA); EXPECT_SUCCESS(s2n_connection_free(client_conn)); EXPECT_SUCCESS(s2n_connection_free(server_conn)); }; /* Can stop on END_OF_EARLY_DATA when using early data, then continue. * (This is the non-test use case for this feature) */ { struct s2n_connection *client_conn = NULL, *server_conn = NULL; EXPECT_OK(s2n_get_test_client_and_server(&client_conn, &server_conn, config)); EXPECT_SUCCESS(s2n_connection_append_psk(client_conn, test_psk)); EXPECT_SUCCESS(s2n_connection_append_psk(server_conn, test_psk)); EXPECT_SUCCESS(s2n_connection_set_early_data_expected(client_conn)); EXPECT_SUCCESS(s2n_connection_set_early_data_expected(server_conn)); EXPECT_OK(s2n_negotiate_test_server_and_client_until_message(server_conn, client_conn, END_OF_EARLY_DATA)); EXPECT_EQUAL(s2n_conn_get_current_message_type(client_conn), END_OF_EARLY_DATA); EXPECT_EQUAL(s2n_conn_get_current_message_type(server_conn), END_OF_EARLY_DATA); EXPECT_SUCCESS(s2n_connection_set_end_of_early_data(client_conn)); EXPECT_SUCCESS(s2n_negotiate_test_server_and_client(server_conn, client_conn)); EXPECT_EQUAL(s2n_conn_get_current_message_type(client_conn), APPLICATION_DATA); EXPECT_EQUAL(s2n_conn_get_current_message_type(server_conn), APPLICATION_DATA); EXPECT_TRUE(WITH_EARLY_DATA(client_conn)); EXPECT_TRUE(WITH_EARLY_DATA(server_conn)); EXPECT_SUCCESS(s2n_connection_free(client_conn)); EXPECT_SUCCESS(s2n_connection_free(server_conn)); }; }; EXPECT_SUCCESS(s2n_config_free(config)); EXPECT_SUCCESS(s2n_cert_chain_and_key_free(cert_chain)); END_TEST(); }
0674d46e97e8c16deda08b0a90dd287224979fb5
21c92afbd7fd022a206fb31294c523aebb770104
/SuiteSparse/GraphBLAS/Test/GB_mx_mxArray_to_Semiring.c
3d4f926c67f2a233daba357a1e8b05463eb57083
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "GPL-2.0-or-later", "GPL-3.0-only", "LGPL-2.1-or-later", "LGPL-2.0-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
jlblancoc/suitesparse-metis-for-windows
70e6bcab2b525afb41758d61f823efa0618f67cf
5ee2eb4bc7bfd6d27af2f7fb027b1545cfc0fa3f
refs/heads/master
2023-08-30T21:15:39.624300
2023-03-09T10:16:48
2023-03-09T10:16:48
16,236,582
423
251
BSD-3-Clause
2023-03-09T10:18:08
2014-01-25T18:06:21
C
UTF-8
C
false
false
6,614
c
GB_mx_mxArray_to_Semiring.c
//------------------------------------------------------------------------------ // GB_mx_mxArray_to_Semiring //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2018, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // Get a semiring struct from MATLAB and convert it into a GraphBLAS semiring. // // The semiring MATLAB struct must contain the following strings: // // multiply a string with the name of the 'multiply' binary operator. // add a string with the name of the 'add' binary operator. // The operator must be commutative. // class the MATLAB class of the operators (a GrB_Type in GraphBLAS, // or just 'type' for short). A semiring in GraphBLAS can be // based on three types: z=mult(x,y), where each of x, y, and // z can be different types. The add operator is a monoid on // a single type, the same as the type of z for z=mult(x,y). // However, this MATLAB interface only supports semirings with // any of the 256 built-in operators. For those, z, x, and y // are always the same type, except for eq, ne, gt, lt, ge, le // (z is boolean and x,y are of the type given by // semiring.class) // Only built-in GraphBLAS types and operators are supported. #include "GB_mex.h" bool GB_mx_mxArray_to_Semiring // true if successful ( GrB_Semiring *handle, // the semiring const mxArray *semiring_matlab, // MATLAB version of semiring const char *name, // name of the argument const mxClassID default_class // default operator class ) { (*handle) = NULL ; const mxArray *multiply_mx = NULL, *class_mx = NULL, *add_mx = NULL ; if (semiring_matlab == NULL || mxIsEmpty (semiring_matlab)) { // semiring is not present; defaults will be used ; } else if (mxIsStruct (semiring_matlab)) { // look for semiring.multiply int fieldnumber = mxGetFieldNumber (semiring_matlab, "multiply") ; if (fieldnumber >= 0) { multiply_mx = mxGetFieldByNumber (semiring_matlab, 0, fieldnumber) ; } // look for semiring.class fieldnumber = mxGetFieldNumber (semiring_matlab, "class") ; if (fieldnumber >= 0) { class_mx = mxGetFieldByNumber (semiring_matlab, 0, fieldnumber) ; } // look for semiring.add fieldnumber = mxGetFieldNumber (semiring_matlab, "add") ; if (fieldnumber >= 0) { add_mx = mxGetFieldByNumber (semiring_matlab, 0, fieldnumber) ; } } else { mexWarnMsgIdAndTxt ("GB:warn","invalid semiring") ; return (false) ; } // find the corresponding built-in GraphBLAS multiply operator GB_Opcode multiply_opcode ; mxClassID multiply_class ; GrB_BinaryOp multiply ; if (!GB_mx_string_to_BinaryOp (&multiply, GB_TIMES_opcode, default_class, multiply_mx, class_mx, &multiply_opcode, &multiply_class, false, false) || multiply == NULL) { mexWarnMsgIdAndTxt ("GB:warn","mult missing") ; return (false) ; } bool zbool ; switch (multiply_opcode) { // 8 z=f(x,y), all x,y,z the same type case GB_FIRST_opcode : zbool = false ; break ; case GB_SECOND_opcode : zbool = false ; break ; case GB_MIN_opcode : zbool = false ; break ; case GB_MAX_opcode : zbool = false ; break ; case GB_PLUS_opcode : zbool = false ; break ; case GB_MINUS_opcode : zbool = false ; break ; case GB_TIMES_opcode : zbool = false ; break ; case GB_DIV_opcode : zbool = false ; break ; // 6 z=f(x,y), all x,y,z the same type case GB_ISEQ_opcode : zbool = false ; break ; case GB_ISNE_opcode : zbool = false ; break ; case GB_ISGT_opcode : zbool = false ; break ; case GB_ISLT_opcode : zbool = false ; break ; case GB_ISGE_opcode : zbool = false ; break ; case GB_ISLE_opcode : zbool = false ; break ; // 6 z=f(x,y), z boolean; x and y are semiring.class case GB_EQ_opcode : zbool = true ; break ; case GB_NE_opcode : zbool = true ; break ; case GB_GT_opcode : zbool = true ; break ; case GB_LT_opcode : zbool = true ; break ; case GB_GE_opcode : zbool = true ; break ; case GB_LE_opcode : zbool = true ; break ; // 3 z=f(x,y), all x,y,z the same type case GB_LOR_opcode : zbool = false ; break ; case GB_LAND_opcode : zbool = false ; break ; case GB_LXOR_opcode : zbool = false ; break ; default : mexWarnMsgIdAndTxt ("GB:warn","unsupported multiply operator") ; return (false) ; } ASSERT_OK (GB_check (multiply, "semiring multiply", GB0)) ; // find the corresponding built-in GraphBLAS add operator GB_Opcode add_opcode ; GrB_BinaryOp add ; bool ok ; if (zbool) { // class is logical, default monoid is 'or' ok = GB_mx_string_to_BinaryOp (&add, GB_LOR_opcode, mxLOGICAL_CLASS, add_mx, NULL, &add_opcode, NULL, false, false) ; } else { // class is the same as multiply->ztype, default monoid 'plus' ok = GB_mx_string_to_BinaryOp (&add, GB_PLUS_opcode, multiply_class, add_mx, NULL, &add_opcode, NULL, false, false) ; } if (!ok) { mexWarnMsgIdAndTxt ("GB:warn", "add failed") ; return (false) ; } ASSERT_OK (GB_check (add, "semiring add", GB0)) ; ASSERT_OK (GB_check (multiply, "semiring multiply", GB0)) ; // create the monoid with the add operator and its identity value GrB_Monoid monoid = GB_mx_builtin_monoid (add) ; if (monoid == NULL) { mexWarnMsgIdAndTxt ("GB:warn", "monoid failed") ; return (false) ; } // create the semiring GrB_Semiring semiring = GB_mx_builtin_semiring (monoid, multiply) ; if (semiring == NULL) { mexWarnMsgIdAndTxt ("GB:warn", "semiring failed") ; return (false) ; } ASSERT_OK (GB_check (semiring, "semiring", GB0)) ; (*handle) = semiring ; return (true) ; }
6369c2b9e8cec913afdcf73c046e2a6b8d6fa747
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
/sysutils/libirman/patches/patch-lirmand.c
92f657a80fc3e81e8552207327221e7707400f56
[]
no_license
jsonn/pkgsrc
fb34c4a6a2d350e8e415f3c4955d4989fcd86881
c1514b5f4a3726d90e30aa16b0c209adbc276d17
refs/heads/trunk
2021-01-24T09:10:01.038867
2017-07-07T15:49:43
2017-07-07T15:49:43
2,095,004
106
47
null
2016-09-19T09:26:01
2011-07-23T23:49:04
Makefile
UTF-8
C
false
false
1,498
c
patch-lirmand.c
$NetBSD: patch-lirmand.c,v 1.1 2012/10/26 20:29:15 joerg Exp $ --- lirmand.c.orig 2012-10-26 14:22:50.000000000 +0000 +++ lirmand.c @@ -63,30 +63,30 @@ char *progname = "lirmand"; int lirc = 0; /* file descriptor */ int is_daemon = 0; -FILE *log = NULL; +FILE *my_log = NULL; FILE *open_log(void) { time_t t=time(NULL); - if (!log) { - log = fopen(LIRMAND_LOGFILE, "a"); - if (log) { - fprintf(log, "%s started at %s\n", progname, ctime(&t)); + if (!my_log) { + my_log = fopen(LIRMAND_LOGFILE, "a"); + if (my_log) { + fprintf(my_log, "%s started at %s\n", progname, ctime(&t)); } } - return log; + return my_log; } void close_log(void) { time_t t = time(NULL); - if (log) { - fprintf(log, "%s stopped at %s\n", progname, ctime(&t)); - fclose(log); + if (my_log) { + fprintf(my_log, "%s stopped at %s\n", progname, ctime(&t)); + fclose(my_log); } - log = NULL; + my_log = NULL; } @@ -99,7 +99,7 @@ int debug_printf(char *format, ...) return 0; va_start(va, format); - ret = vfprintf(log, format, va); + ret = vfprintf(my_log, format, va); va_end(va); return ret; @@ -114,8 +114,8 @@ int eprintf(char *format, ...) va_start(va, format); if (open_log()) { - ret = fprintf(log, "error: "); - ret += vfprintf(log, format, va); + ret = fprintf(my_log, "error: "); + ret += vfprintf(my_log, format, va); } if (!is_daemon) { ret = fprintf(stderr, "%s: ", progname);
bafff91963f172ff3ecb850ca7ff353ba485872b
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
/filesystems/fuse-encfs/patches/patch-internal_easylogging++.h
ab68dbb8e85058ca6e5a987359c0607b7b75afa5
[]
no_license
jsonn/pkgsrc
fb34c4a6a2d350e8e415f3c4955d4989fcd86881
c1514b5f4a3726d90e30aa16b0c209adbc276d17
refs/heads/trunk
2021-01-24T09:10:01.038867
2017-07-07T15:49:43
2017-07-07T15:49:43
2,095,004
106
47
null
2016-09-19T09:26:01
2011-07-23T23:49:04
Makefile
UTF-8
C
false
false
1,022
h
patch-internal_easylogging++.h
$NetBSD: patch-internal_easylogging++.h,v 1.1 2017/06/19 18:41:39 maya Exp $ NetBSD support, it's a unixy OS. --- internal/easylogging++.h.orig 2016-09-18 20:16:04.000000000 +0000 +++ internal/easylogging++.h @@ -99,13 +99,19 @@ #else # define ELPP_OS_FREEBSD 0 #endif +#if (defined(__NetBSD__)) +# define ELPP_OS_NETBSD 1 +#else +# define ELPP_OS_NETBSD 0 +#endif + #if (defined(__sun)) # define ELPP_OS_SOLARIS 1 #else # define ELPP_OS_SOLARIS 0 #endif // Unix -#if ((ELPP_OS_LINUX || ELPP_OS_MAC || ELPP_OS_FREEBSD || ELPP_OS_SOLARIS) && (!ELPP_OS_WINDOWS)) +#if ((ELPP_OS_LINUX || ELPP_OS_MAC || ELPP_OS_FREEBSD || ELPP_OS_NETBSD || ELPP_OS_SOLARIS) && (!ELPP_OS_WINDOWS)) # define ELPP_OS_UNIX 1 #else # define ELPP_OS_UNIX 0 @@ -6692,4 +6698,4 @@ el::base::debug::CrashHandler elCrashHan #else # define START_EASYLOGGINGPP(argc, argv) el::Helpers::setArgs(argc, argv) #endif // defined(ELPP_UNICODE) -#endif // EASYLOGGINGPP_H \ No newline at end of file +#endif // EASYLOGGINGPP_H
ddf3f6b14c8a321165de17e865194f8db1e044d4
0744dcc5394cebf57ebcba343747af6871b67017
/apps/examples/connect_test/connect_test_table.h
e50638b3e3345baf2c59bfb46a9215ac43cd3919
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
Samsung/TizenRT
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
refs/heads/master
2023-08-31T08:59:33.327998
2023-08-08T06:09:20
2023-08-31T04:38:20
82,517,252
590
719
Apache-2.0
2023-09-14T06:54:49
2017-02-20T04:38:30
C
UTF-8
C
false
false
1,102
h
connect_test_table.h
/* * test_type, test_handler, test_parser, test_command */ CT_MEMBER_POOL(CT_ADD_HOSTNAME, _ct_add_hostname, _ct_parse_add_hostname, "add_hostname") CT_MEMBER_POOL(CT_CLIENT, _ct_client, _ct_parse_client, "client") CT_MEMBER_POOL(CT_SERVER, _ct_server, _ct_parse_server, "server") // Following commands are for development and testing units purpose: CT_MEMBER_POOL(CT_UDP_CLIENT, _ct_udp_client, _ct_parse_udp_client, "udp_client") CT_MEMBER_POOL(CT_TCP_CLIENT, _ct_tcp_client, _ct_parse_tcp_client, "tcp_client") CT_MEMBER_POOL(CT_DTLS_CLIENT, _ct_dtls_client, _ct_parse_dtls_client, "dtls_client") CT_MEMBER_POOL(CT_TLS_CLIENT, _ct_tls_client, _ct_parse_tls_client, "tls_client") CT_MEMBER_POOL(CT_UDP_SERVER, _ct_udp_server, _ct_parse_udp_server, "udp_server") CT_MEMBER_POOL(CT_TCP_SERVER, _ct_tcp_server, _ct_parse_tcp_server, "tcp_server") CT_MEMBER_POOL(CT_DTLS_SERVER, _ct_dtls_server, _ct_parse_dtls_server, "dtls_server") CT_MEMBER_POOL(CT_TLS_SERVER, _ct_tls_server, _ct_parse_tls_server, "tls_server") CT_MEMBER_POOL(CT_DNS_SERVICE, _ct_dns_service, _ct_parse_dns_service, "dns_service")
2331ade7ac511b57329cd8c855408750d2df1805
77fd60c4b7e7885b2ec4ca5203edf9489f6f37dc
/lib/fff/fff_glm_twolevel.c
0cdb1b400d987d6a4fa1ef00ad9ae03de645336a
[ "BSD-3-Clause" ]
permissive
nipy/nipy
156f379adbc07b259e25012662510b1f64aac4c5
7eede02471567487e454016c1e7cf637d3afac9e
refs/heads/master
2023-04-06T14:56:36.303421
2023-04-05T19:40:24
2023-04-05T19:40:24
642,344
275
115
BSD-3-Clause
2023-04-05T19:40:25
2010-05-02T10:00:33
Python
UTF-8
C
false
false
3,752
c
fff_glm_twolevel.c
#include "fff_glm_twolevel.h" #include "fff_base.h" #include "fff_blas.h" #include <stdlib.h> #include <math.h> #include <stdlib.h> /* b, s2 are initialized using the values passed to the function. The function requires the projected pseudo-inverse matrix PpiX to be pre-calculated externally. It is defined by: PpiX = P * (X'X)^-1 X' where: P = Ip - A C' (C A C')^-1 C with A = (X'X)^-1 is the appropriate projector onto the constaint space, Cb=0. P is, in fact, orthogonal for the dot product defined by X'X. PpiX is p x n. The equality PpiX*X=P is not checked. */ fff_glm_twolevel_EM* fff_glm_twolevel_EM_new(size_t n, size_t p) { fff_glm_twolevel_EM* thisone; thisone = (fff_glm_twolevel_EM*)malloc(sizeof(fff_glm_twolevel_EM)); if (thisone==NULL) return NULL; thisone->n = n; thisone->p = p; thisone->s2 = FFF_POSINF; thisone->b = fff_vector_new(p); thisone->z = fff_vector_new(n); thisone->vz = fff_vector_new(n); thisone->Qz = fff_vector_new(n); return thisone; } void fff_glm_twolevel_EM_delete(fff_glm_twolevel_EM* thisone) { if (thisone==NULL) return; fff_vector_delete(thisone->b); fff_vector_delete(thisone->z); fff_vector_delete(thisone->vz); fff_vector_delete(thisone->Qz); free(thisone); } void fff_glm_twolevel_EM_init(fff_glm_twolevel_EM* em) { fff_vector_set_all(em->b, 0.0); em->s2 = FFF_POSINF; return; } void fff_glm_twolevel_EM_run(fff_glm_twolevel_EM* em, const fff_vector* y, const fff_vector* vy, const fff_matrix* X, const fff_matrix* PpiX, unsigned int niter) { unsigned int iter = 0; size_t n=X->size1, i; double *yi, *zi, *vyi, *vzi; double w1, w2; double m = 0.0; while (iter < niter) { /*** E step ***/ /* Compute current prediction estimate: z = X*b */ fff_blas_dgemv(CblasNoTrans, 1.0, X, em->b, 0.0, em->z); /* Posterior mean and variance of each "true" effect: vz = 1/(1/vy + 1/s2) z = vz * (y/vy + X*b/s2) */ w2 = FFF_ENSURE_POSITIVE(em->s2); w2 = 1/w2; for(i=0, yi=y->data, zi=em->z->data, vyi=vy->data, vzi=em->vz->data; i<n; i++, yi+=y->stride, zi+=em->z->stride, vyi+=vy->stride, vzi+=em->vz->stride) { w1 = FFF_ENSURE_POSITIVE(*vyi); w1 = 1/w1; *vzi = 1/(w1+w2); *zi = *vzi * (w1*(*yi) + w2*(*zi)); } /*** M step ***/ /* Update effect: b = PpiX * z */ fff_blas_dgemv(CblasNoTrans, 1.0, PpiX, em->z, 0.0, em->b); /* Update variance: s2 = (1/n) [ sum((z-Xb).^2) + sum(vz) ] */ fff_vector_memcpy(em->Qz, em->z); fff_blas_dgemv(CblasNoTrans, 1.0, X, em->b, -1.0, em->Qz); /* Qz= Xb-z = Proj_X(z) - z */ em->s2 = (fff_vector_ssd(em->Qz, &m, 1) + fff_vector_sum(em->vz)) / (long double)n; /*** Increment iteration number ***/ iter ++; } return; } /* Log-likelihood computation. ri = y - Xb -2 LL = n log(2pi) + \sum_i log (s^2 + si^2) + \sum_i ri^2/(s^2 + si^2) We omit the nlog(2pi) term as it is constant. */ double fff_glm_twolevel_log_likelihood(const fff_vector* y, const fff_vector* vy, const fff_matrix* X, const fff_vector* b, double s2, fff_vector* tmp) { double LL = 0.0, w; size_t n=X->size1, i; double *ri, *vyi; /* Compute residuals: tmp = y - X b */ fff_vector_memcpy(tmp, y); fff_blas_dgemv(CblasNoTrans, -1.0, X, b, 1.0, tmp); /* Incremental computation */ for(i=0, ri=tmp->data, vyi=vy->data; i<n; i++, ri+=tmp->stride, vyi+=vy->stride) { w = *vyi + s2; w = FFF_ENSURE_POSITIVE(w); LL += log(w); LL += FFF_SQR(*ri)/w; } /* Finalize computation */ LL *= -0.5; return LL; }
a467985e6521694b55ffa0e710266c577eef38ce
aa3befea459382dc5c01c925653d54f435b3fb0f
/arch/arm64/src/a64/a64_de.c
ef3fa71e219af1343ae4635f816b8a9e5a840748
[ "MIT-open-group", "BSD-3-Clause", "HPND-sell-variant", "BSD-4-Clause-UC", "LicenseRef-scancode-warranty-disclaimer", "MIT-0", "LicenseRef-scancode-bsd-atmel", "LicenseRef-scancode-gary-s-brown", "LicenseRef-scancode-proprietary-license", "SunPro", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "LicenseRef-scancode-other-permissive", "HPND", "ISC", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "GPL-1.0-or-later", "CC-BY-2.0", "CC-BY-4.0" ]
permissive
apache/nuttx
14519a7bff4a87935d94fb8fb2b19edb501c7cec
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
refs/heads/master
2023-08-25T06:55:45.822534
2023-08-23T16:03:31
2023-08-24T21:25:47
228,103,273
407
241
Apache-2.0
2023-09-14T18:26:05
2019-12-14T23:27:55
C
UTF-8
C
false
false
29,931
c
a64_de.c
/**************************************************************************** * arch/arm64/src/a64/a64_de.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /* Reference: * * "Rendering PinePhone's Display (DE and TCON0)" * https://lupyuen.github.io/articles/de * * "NuttX RTOS for PinePhone: Render Graphics in Zig" * https://lupyuen.github.io/articles/de2 * * "A64 Page" refers to Allwinner A64 User Manual * https://lupyuen.github.io/images/Allwinner_A64_User_Manual_V1.1.pdf * * "A31 Page" refers to Allwinner A31 User Manual * https://lupyuen.github.io/images/A31_User_Manual_v1.3_20150510.pdf * * "DE Page" refers to Allwinner Display Engine 2.0 Specification * https://lupyuen.github.io/images/Allwinner_DE2.0_Spec_V1.0.pdf */ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include <string.h> #include <assert.h> #include <debug.h> #include <nuttx/arch.h> #include "hardware/a64_memorymap.h" #include "arm64_arch.h" #include "a64_de.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* Timeout for Display Engine PLL in milliseconds */ #define PLL_TIMEOUT_MS 100 /* A64 Display Engine Base Addresses ****************************************/ /* Mixer 0 (DE Page 24) */ #define A64_MIXER0_ADDR (A64_DE_ADDR + 0x100000) #define A64_MIXER0_LEN 0x6000 /* Global Registers (DE Page 90) */ #define A64_GLB_ADDR (A64_MIXER0_ADDR + 0x0000) /* Blender (DE Page 90) */ #define A64_BLD_ADDR (A64_MIXER0_ADDR + 0x1000) /* UI Overlay 1 (DE Page 102) */ #define A64_OVL_UI_CH1_ADDR (A64_MIXER0_ADDR + 0x3000) /* Video Scaler (DE Page 90) */ #define A64_VIDEO_SCALER_ADDR (A64_MIXER0_ADDR + 0x020000) /* UI Scaler 1 (DE Page 90) */ #define A64_UI_SCALER1_ADDR (A64_MIXER0_ADDR + 0x040000) /* UI Scaler 2 (DE Page 90) */ #define A64_UI_SCALER2_ADDR (A64_MIXER0_ADDR + 0x050000) /* Fresh and Contrast Enhancement (DE Page 61) */ #define A64_FCE_ADDR (A64_MIXER0_ADDR + 0x0a0000) /* Black and White Stretch (DE Page 42) */ #define A64_BWS_ADDR (A64_MIXER0_ADDR + 0x0a2000) /* Luminance Transient Improvement (DE Page 71) */ #define A64_LTI_ADDR (A64_MIXER0_ADDR + 0x0a4000) /* Luma Peaking (DE Page 80) */ #define A64_PEAKING_ADDR (A64_MIXER0_ADDR + 0x0a6000) /* Adaptive Saturation Enhancement (DE Page 40) */ #define A64_ASE_ADDR (A64_MIXER0_ADDR + 0x0a8000) /* Fancy Color Curvature Change (DE Page 56) */ #define A64_FCC_ADDR (A64_MIXER0_ADDR + 0x0aa000) /* UI Overlays 1, 2 and 3 (DE Page 102) */ #define A64_OVL_UI_ADDR(ch) (A64_OVL_UI_CH1_ADDR + ((ch) - 1) * 0x1000) /* UI Scalers 1, 2 and 3 (DE Page 90) */ #define A64_UI_SCALER_ADDR(ch) (A64_UI_SCALER1_ADDR + ((ch) - 1) * 0x10000) /* Dynamic Range Controller (DE Page 48) */ #define A64_DRC_ADDR (A64_DE_ADDR + 0x1b0000) /* A64 System Control Registers and Bit Definitions *************************/ /* SRAM Control Register 1 (A31 Page 191) */ #define SRAM_CTRL_REG1 (A64_SYSCTL_ADDR + 0x4) /* A64 CCU Registers and Bit Definitions ************************************/ /* PLL Display Engine Control Register (A64 Page 96) */ #define PLL_DE_CTRL_REG (A64_CCU_ADDR + 0x0048) #define PLL_PRE_DIV_M(n) ((n) << 0) #define PLL_FACTOR_N(n) ((n) << 8) #define PLL_MODE_SEL (1 << 24) #define PLL_LOCK (1 << 28) #define PLL_ENABLE (1 << 31) /* Bus Clock Gating Register 1 (A64 Page 102) */ #define BUS_CLK_GATING_REG1 (A64_CCU_ADDR + 0x0064) #define DE_GATING (1 << 12) /* Display Engine Clock Register (A64 Page 117) */ #define DE_CLK_REG (A64_CCU_ADDR + 0x0104) #define CLK_SRC_SEL(n) ((n) << 24) #define CLK_SRC_SEL_MASK (0b111 << 24) #define SCLK_GATING (1 << 31) #define SCLK_GATING_MASK (0b1 << 31) /* Bus Software Reset Register 1 (A64 Page 140) */ #define BUS_SOFT_RST_REG1 (A64_CCU_ADDR + 0x02c4) #define DE_RST (1 << 12) /* A64 Display Engine Registers and Bit Definitions *************************/ /* DE SCLK Gating Register (DE Page 25) */ #define SCLK_GATE (A64_DE_ADDR + 0x000) #define CORE0_SCLK_GATE (1 << 0) /* DE AHB Reset register (DE Page 25) */ #define AHB_RESET (A64_DE_ADDR + 0x008) #define CORE0_HCLK_RESET (1 << 0) /* DE HCLK Gating Register (DE Page 25) */ #define HCLK_GATE (A64_DE_ADDR + 0x004) #define CORE0_HCLK_GATE (1 << 0) /* DE2TCON MUX Register (DE Page 26) */ #define DE2TCON_MUX (A64_DE_ADDR + 0x010) #define DE2TCON_MUX_MASK (1 << 0) /* Video Scaler Control Register (DE Page 130) */ #define VS_CTRL_REG (A64_VIDEO_SCALER_ADDR + 0x00) /* 0x113 0000 is undocumented. Might be a mix-up with UI_SCALER3. */ #define UNDOC_1130000 (A64_DE_ADDR + 0x130000) /* UI Scaler 1 Control Register (DE Page 66) */ #define UIS_CTRL_REG1 (A64_UI_SCALER1_ADDR + 0x00) /* UI Scaler 2 Control Register (DE Page 66) */ #define UIS_CTRL_REG2 (A64_UI_SCALER2_ADDR + 0x00) /* Fresh and Contrast Enhancement Global Control Register (DE Page 61) */ #define GCTRL_REG_FCE (A64_FCE_ADDR + 0x00) /* Black and White Stretch Global Control Register (DE Page 42) */ #define GCTRL_REG_BWS (A64_BWS_ADDR + 0x00) /* Luminance Transient Improvement Global Control Register (DE Page 72) */ #define LTI_CTL (A64_LTI_ADDR + 0x00) /* Luma Peaking Module Control Register (DE Page 80) */ #define LP_CTRL_REG (A64_PEAKING_ADDR + 0x00) /* Adaptive Saturation Enhancement Global Control Register (DE Page 40) */ #define ASE_CTL_REG (A64_ASE_ADDR + 0x00) /* Fancy Color Curvature Change Control Register (DE Page 56) */ #define FCC_CTL_REG (A64_FCC_ADDR + 0x00) /* Dynamic Range Controller Module General Control Register (DE Page 49) */ #define GNECTL_REG (A64_DRC_ADDR + 0x00) /* Mixer 0 Global Control Register (DE Page 92) */ #define GLB_CTL (A64_MIXER0_ADDR + 0x00) #define EN_MIXER (1 << 0) /* Global Double Buffer Control (DE Page 93) */ #define GLB_DBUFFER (A64_GLB_ADDR + 0x008) #define DOUBLE_BUFFER_RDY (1 << 0) /* Global Size (DE Page 93) */ #define GLB_SIZE (A64_GLB_ADDR + 0x00c) /* Blender Fill Color Control (DE Page 106) */ #define BLD_FILL_COLOR_CTL (A64_BLD_ADDR + 0x000) #define P0_FCEN(n) ((n) << 0) #define P0_EN(n) ((n) << 8) #define P1_EN(n) ((n) << 9) #define P2_EN(n) ((n) << 10) /* Note: DE Page 91 shows incorrect offset N*0x14 for * BLD_FILL_COLOR, BLD_CH_ISIZE and BLD_CH_OFFSET. * Correct offset is N*0x10 (DE Page 108) * (N = Pipe Number, from 0 to 2 for Channels 1 to 3) */ /* Blender Fill Color (DE Page 107) */ #define BLD_FILL_COLOR(p) (A64_BLD_ADDR + 0x004 + (p) * 0x10) #define FILL_BLUE(n) ((n) << 0) #define FILL_GREEN(n) ((n) << 8) #define FILL_RED(n) ((n) << 16) #define FILL_ALPHA(n) ((n) << 24) /* Blender Input Memory Size (DE Page 108) */ #define BLD_CH_ISIZE(p) (A64_BLD_ADDR + 0x008 + (p) * 0x10) /* Blender Input Memory Offset (DE Page 108) */ #define BLD_CH_OFFSET(p) (A64_BLD_ADDR + 0x00c + (p) * 0x10) /* Blender Routing Control (DE Page 108) */ #define BLD_CH_RTCTL (A64_BLD_ADDR + 0x080) #define P0_RTCTL(n) ((n) << 0) #define P1_RTCTL(n) ((n) << 4) #define P2_RTCTL(n) ((n) << 8) /* Blender Pre-Multiply Control (DE Page 109) */ #define BLD_PREMUL_CTL (A64_BLD_ADDR + 0x084) #define P0_ALPHA_MODE(n) ((n) << 0) #define P1_ALPHA_MODE(n) ((n) << 1) #define P2_ALPHA_MODE(n) ((n) << 2) #define P3_ALPHA_MODE(n) ((n) << 3) /* Blender Background Color (DE Page 109) */ #define BLD_BK_COLOR (A64_BLD_ADDR + 0x088) #define BK_BLUE(n) ((n) << 0) #define BK_GREEN(n) ((n) << 8) #define BK_RED(n) ((n) << 16) #define BK_RESERVED (0xff << 24) /* Blender Output Size Setting (DE Page 110) */ #define BLD_SIZE (A64_BLD_ADDR + 0x08c) /* Blender Control (DE Page 110) */ #define BLD_CTL(p) (A64_BLD_ADDR + 0x090 + (p) * 4) #define BLEND_PFS(n) ((n) << 0) #define BLEND_PFD(n) ((n) << 8) #define BLEND_AFS(n) ((n) << 16) #define BLEND_AFD(n) ((n) << 24) /* UI Overlay Attribute Control (DE Page 102) */ #define OVL_UI_ATTR_CTL(ch) (A64_OVL_UI_ADDR(ch) + 0x00) #define LAY_EN (1 << 0) #define LAY_ALPHA_MODE(n) ((n) << 1) #define LAY_FBFMT(n) ((n) << 8) #define LAY_GLBALPHA(n) ((n) << 24) /* UI Overlay Memory Block Size (DE Page 104) */ #define OVL_UI_MBSIZE(ch) (A64_OVL_UI_ADDR(ch) + 0x04) /* UI Overlay Memory Block Coordinate (DE Page 104) */ #define OVL_UI_COOR(ch) (A64_OVL_UI_ADDR(ch) + 0x08) /* UI Overlay Memory Pitch (DE Page 104) */ #define OVL_UI_PITCH(ch) (A64_OVL_UI_ADDR(ch) + 0x0c) /* UI Overlay Top Field Memory Block Low Address (DE Page 104) */ #define OVL_UI_TOP_LADD(ch) (A64_OVL_UI_ADDR(ch) + 0x10) /* UI Overlay Overlay Window Size (DE Page 106) */ #define OVL_UI_SIZE(ch) (A64_OVL_UI_ADDR(ch) + 0x88) /* UI Scaler Control Register (DE Page 66) */ #define UIS_CTRL_REG(ch) (A64_UI_SCALER_ADDR(ch) + 0x00) /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: a64_wait_pll * * Description: * Wait for Display Engine PLL to be stable. * * Input Parameters: * None * * Returned Value: * Zero (OK) on success; ERROR if timeout. * ****************************************************************************/ static int a64_wait_pll(void) { int i; for (i = 0; i < PLL_TIMEOUT_MS; i++) { /* Poll on LOCK (Bit 28) of PLL Display Engine Control Register */ if ((getreg32(PLL_DE_CTRL_REG) & PLL_LOCK) != 0) { /* If LOCK is 1, then Display Engine PLL is stable */ return OK; } /* Sleep 1 millisecond and try again */ up_mdelay(1); } gerr("PLL Timeout"); return ERROR; } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: a64_de_init * * Description: * Initialize the Display Engine on the SoC. Mixer 0 will be configured * to stream pixel data to Timing Controller TCON0. Should be called * before any Display Engine operation. * * Input Parameters: * None * * Returned Value: * Zero (OK) on success; ERROR if timeout. * ****************************************************************************/ int a64_de_init(void) { int i; int ret; uint32_t pll; uint32_t clk; uint32_t clk_mask; /* Set High Speed SRAM to DMA Mode ****************************************/ ginfo("Set High Speed SRAM to DMA Mode\n"); /* SRAM Control Register 1 (A31 Page 191) * Set BIST_DMA_CTRL_SEL (Bit 31) to 0 (DMA) */ putreg32(0x0, SRAM_CTRL_REG1); /* Set Display Engine PLL to 297 MHz **************************************/ ginfo("Set Display Engine PLL to 297 MHz\n"); /* PLL Display Engine Control Register (A64 Page 96) * Set PLL_ENABLE (Bit 31) to 1 (Enable PLL) * Set PLL_MODE_SEL (Bit 24) to 1 (Integer Mode) * Set PLL_FACTOR_N (Bits 8 to 14) to 23 (N = 24) * Set PLL_PRE_DIV_M (Bits 0 to 3) to 1 (M = 2) * Actual PLL Output = 24 MHz * N / M = 288 MHz * (Slighltly below 297 MHz due to truncation) */ pll = PLL_ENABLE | PLL_MODE_SEL | PLL_FACTOR_N(23) | PLL_PRE_DIV_M(1); putreg32(pll, PLL_DE_CTRL_REG); /* Wait for Display Engine PLL to be stable *******************************/ ginfo("Wait for Display Engine PLL to be stable\n"); ret = a64_wait_pll(); if (ret < 0) { return ret; } /* Set Special Clock to Display Engine PLL ********************************/ ginfo("Set Special Clock to Display Engine PLL\n"); /* Display Engine Clock Register (A64 Page 117) * Set SCLK_GATING (Bit 31) to 1 * (Enable Special Clock) * Set CLK_SRC_SEL (Bits 24 to 26) to 1 * (Clock Source is Display Engine PLL) */ clk = SCLK_GATING | CLK_SRC_SEL(1); clk_mask = SCLK_GATING_MASK | CLK_SRC_SEL_MASK; modreg32(clk, clk_mask, DE_CLK_REG); /* Enable AHB for Display Engine: De-Assert Display Engine ****************/ ginfo("Enable AHB for Display Engine: De-Assert Display Engine\n"); /* Bus Software Reset Register 1 (A64 Page 140) * Set DE_RST (Bit 12) to 1 (De-Assert Display Engine) */ modreg32(DE_RST, DE_RST, BUS_SOFT_RST_REG1); /* Enable AHB for Display Engine: Pass Display Engine *********************/ ginfo("Enable AHB for Display Engine: Pass Display Engine\n"); /* Bus Clock Gating Register 1 (A64 Page 102) * Set DE_GATING (Bit 12) to 1 (Pass Display Engine) */ modreg32(DE_GATING, DE_GATING, BUS_CLK_GATING_REG1); /* Enable Clock for MIXER0: SCLK Clock Pass *******************************/ ginfo("Enable Clock for MIXER0: SCLK Clock Pass\n"); /* DE SCLK Gating Register (DE Page 25) * Set CORE0_SCLK_GATE (Bit 0) to 1 (Clock Pass) */ modreg32(CORE0_SCLK_GATE, CORE0_SCLK_GATE, SCLK_GATE); /* Enable Clock for MIXER0: HCLK Clock Reset Off **************************/ ginfo("Enable Clock for MIXER0: HCLK Clock Reset Off\n"); /* DE AHB Reset register (DE Page 25) * Set CORE0_HCLK_RESET (Bit 0) to 1 (Reset Off) */ modreg32(CORE0_HCLK_RESET, CORE0_HCLK_RESET, AHB_RESET); /* Enable Clock for MIXER0: HCLK Clock Pass *******************************/ ginfo("Enable Clock for MIXER0: HCLK Clock Pass\n"); /* DE HCLK Gating Register (DE Page 25) * Set CORE0_HCLK_GATE (Bit 0) to 1 (Clock Pass) */ modreg32(CORE0_HCLK_GATE, CORE0_HCLK_GATE, HCLK_GATE); /* Route MIXER0 to TCON0 **************************************************/ ginfo("Route MIXER0 to TCON0\n"); /* DE2TCON MUX Register (DE Page 26) * Set DE2TCON_MUX (Bit 0) to 0 * (Route MIXER0 to TCON0; Route MIXER1 to TCON1) */ modreg32(0, DE2TCON_MUX_MASK, DE2TCON_MUX); /* Clear MIXER0 Registers: GLB, BLD, OVL_V, OVL_UI ************************/ ginfo("Clear MIXER0 Registers: GLB, BLD, OVL_V, OVL_UI\n"); for (i = 0; i < A64_MIXER0_LEN; i += 4) { putreg32(0, A64_MIXER0_ADDR + i); } /* Disable MIXER0 VSU *****************************************************/ ginfo("Disable MIXER0 VSU\n"); /* Video Scaler Control Register (DE Page 130) * Set EN (Bit 0) to 0 (Disable Video Scaler) */ putreg32(0, VS_CTRL_REG); /* Disable MIXER0 Undocumented ********************************************/ ginfo("Disable MIXER0 Undocumented\n"); /* 0x113 0000 is undocumented. Might be a mix-up with UI_SCALER3. */ putreg32(0, UNDOC_1130000); /* Disable MIXER0 UI_SCALER1 **********************************************/ ginfo("Disable MIXER0 UI_SCALER1\n"); /* UI Scaler 1 Control Register (DE Page 66) * Set EN (Bit 0) to 0 (Disable UI Scaler) */ putreg32(0, UIS_CTRL_REG1); /* Disable MIXER0 UI_SCALER2 **********************************************/ ginfo("Disable MIXER0 UI_SCALER2\n"); /* UI Scaler 2 Control Register (DE Page 66) * Set EN (Bit 0) to 0 (Disable UI Scaler) */ putreg32(0, UIS_CTRL_REG2); /* Note: Missing UI_SCALER3(CH3) at MIXER0 Offset 0x06 0000 (DE Page 90). * Might be a mix-up with 0x113 0000 above. */ /* Disable MIXER0 FCE *****************************************************/ ginfo("Disable MIXER0 FCE\n"); /* Fresh and Contrast Enhancement Global Control Register (DE Page 61) * Set EN (Bit 0) to 0 (Disable FCE) */ putreg32(0, GCTRL_REG_FCE); /* Disable MIXER0 BWS *****************************************************/ ginfo("Disable MIXER0 BWS\n"); /* Black and White Stretch Global Control Register (DE Page 42) * Set EN (Bit 0) to 0 (Disable BWS) */ putreg32(0, GCTRL_REG_BWS); /* Disable MIXER0 LTI *****************************************************/ ginfo("Disable MIXER0 LTI\n"); /* Luminance Transient Improvement Global Control Register (DE Page 72) * Set LTI_EN (Bit 0) to 0 (Close LTI) */ putreg32(0, LTI_CTL); /* Disable MIXER0 PEAKING *************************************************/ ginfo("Disable MIXER0 PEAKING\n"); /* Luma Peaking Module Control Register (DE Page 80) * Set EN (Bit 0) to 0 (Disable PEAKING) */ putreg32(0, LP_CTRL_REG); /* Disable MIXER0 ASE *****************************************************/ ginfo("Disable MIXER0 ASE\n"); /* Adaptive Saturation Enhancement Global Control Register (DE Page 40) * Set ASE_EN (Bit 0) to 0 (Disable ASE) */ putreg32(0, ASE_CTL_REG); /* Disable MIXER0 FCC *****************************************************/ ginfo("Disable MIXER0 FCC\n"); /* Fancy Color Curvature Change Control Register (DE Page 56) * Set Enable (Bit 0) to 0 (Disable FCC) */ putreg32(0, FCC_CTL_REG); /* Disable MIXER0 DRC *****************************************************/ ginfo("Disable MIXER0 DRC\n"); /* Dynamic Range Controller Module General Control Register (DE Page 49) * Set BIST_EN (Bit 0) to 0 (Disable BIST) */ putreg32(0, GNECTL_REG); /* Enable MIXER0 **********************************************************/ ginfo("Enable MIXER0\n"); /* Mixer 0 Global Control Register (DE Page 92) * Set EN (Bit 0) to 1 (Enable Mixer) */ putreg32(EN_MIXER, GLB_CTL); return OK; } /**************************************************************************** * Name: a64_de_blender_init * * Description: * Initialize the UI Blender for Display Engine. Should be called after * a64_de_init() and before a64_de_ui_channel_init(). * * Input Parameters: * None * * Returned Value: * OK is always returned at present. * ****************************************************************************/ int a64_de_blender_init(void) { uint32_t color; uint32_t premultiply; /* Set Blender Background *************************************************/ ginfo("Set Blender Background\n"); /* Blender Background Color (DE Page 109) * Set to Black Background Color * Set RESERVED (Bits 24 to 31) to 0xFF (Undocumented) * Set RED (Bits 16 to 23) to 0 * Set GREEN (Bits 8 to 15) to 0 * Set BLUE (Bits 0 to 7) to 0 */ color = BK_RESERVED | BK_RED(0) | BK_GREEN(0) | BK_BLUE(0); putreg32(color, BLD_BK_COLOR); /* Set Blender Pre-Multiply ***********************************************/ ginfo("Set Blender Pre-Multiply\n"); /* Blender Pre-Multiply Control (DE Page 109) * Set to No Pre-Multiply for Alpha, Pipes 0 to 3 * Set P3_ALPHA_MODE (Bit 3) to 0 (Pipe 3: No Pre-Multiply) * Set P2_ALPHA_MODE (Bit 2) to 0 (Pipe 2: No Pre-Multiply) * Set P1_ALPHA_MODE (Bit 1) to 0 (Pipe 1: No Pre-Multiply) * Set P0_ALPHA_MODE (Bit 0) to 0 (Pipe 0: No Pre-Multiply) */ premultiply = P3_ALPHA_MODE(0) | P2_ALPHA_MODE(0) | P1_ALPHA_MODE(0) | P0_ALPHA_MODE(0); putreg32(premultiply, BLD_PREMUL_CTL); return OK; } /**************************************************************************** * Name: a64_de_ui_channel_init * * Description: * Initialize a UI Channel for Display Engine. Display Engine will * stream the pixel data from the Frame Buffer Memory (over DMA) to the * UI Blender. There are 3 UI Channels: Base UI Channel (Channel 1) and * 2 Overlay UI Channels (Channels 2 and 3). Should be called after * a64_de_blender_init() and before a64_de_enable(). * * Input Parameters: * channel - UI Channel Number: 1, 2 or 3 * fbmem - Start of Frame Buffer Memory (address should be 32-bit), * or NULL if this UI Channel should be disabled * fblen - Length of Frame Buffer Memory in bytes * xres - Horizontal resolution in pixel columns * yres - Vertical resolution in pixel rows * xoffset - Horizontal offset in pixel columns * yoffset - Vertical offset in pixel rows * * Returned Value: * OK is always returned at present. * ****************************************************************************/ int a64_de_ui_channel_init(uint8_t channel, const void *fbmem, size_t fblen, uint16_t xres, uint16_t yres, uint16_t xoffset, uint16_t yoffset) { uint8_t pipe; uint32_t lay_glbalpha; uint32_t lay_fbfmt; uint32_t attr; uint32_t height_width; uint32_t color; uint32_t offset; uint32_t blend; DEBUGASSERT(channel >= 1 && channel <= 3); DEBUGASSERT(fblen == xres * yres * 4); /* If UI Channel should be disabled... */ if (fbmem == NULL) { /* Disable Overlay and Pipe *******************************************/ ginfo("Channel %d: Disable Overlay and Pipe\n", channel); /* UI Overlay Attribute Control (DE Page 102) * Set LAY_EN (Bit 0) to 0 (Disable Layer) */ putreg32(0, OVL_UI_ATTR_CTL(channel)); /* Disable Scaler *****************************************************/ ginfo("Channel %d: Disable Scaler\n", channel); /* UI Scaler Control Register (DE Page 66) * Set EN (Bit 0) to 0 (Disable UI Scaler) */ putreg32(0, UIS_CTRL_REG(channel)); /* Skip to next UI Channel */ return OK; } /* Set Overlay (Assume Layer = 0) *****************************************/ ginfo("Channel %d: Set Overlay (%d x %d)\n", channel, xres, yres); /* UI Overlay Attribute Control (DE Page 102) * Set LAY_GLBALPHA (Bits 24 to 31) to 0xFF or 0x7F * (Global Alpha Value is Opaque or Semi-Transparent) * Set LAY_FBFMT (Bits 8 to 12) to 4 or 0 * (Input Data Format is XRGB 8888 or ARGB 8888) * Set LAY_ALPHA_MODE (Bits 1 to 2) to 2 * (Global Alpha is mixed with Pixel Alpha) * (Input Alpha Value = Global Alpha Value * Pixel’s Alpha Value) * Set LAY_EN (Bit 0) to 1 (Enable Layer) */ lay_glbalpha = (channel == 1) ? 0xff : /* Channel 1: Opaque */ (channel == 2) ? 0xff : /* Channel 2: Opaque */ (channel == 3) ? 0x7f : /* Channel 3: Semi-Transparent */ 0xff; /* Never comes here */ lay_fbfmt = (channel == 1) ? 4 : /* Channel 1: XRGB 8888 */ (channel == 2) ? 0 : /* Channel 2: ARGB 8888 */ (channel == 3) ? 0 : /* Channel 3: ARGB 8888 */ 0; /* Never comes here */ attr = LAY_GLBALPHA(lay_glbalpha) | LAY_FBFMT(lay_fbfmt) | LAY_ALPHA_MODE(2) | LAY_EN; putreg32(attr, OVL_UI_ATTR_CTL(channel)); /* UI Overlay Top Field Memory Block Low Address (DE Page 104) * Set to Frame Buffer Address (32 bits only) */ DEBUGASSERT((((uint64_t)fbmem) & 0xffffffff) == (uint64_t)fbmem); putreg32((uint64_t)fbmem, OVL_UI_TOP_LADD(channel)); /* UI Overlay Memory Pitch (DE Page 104) * Set to (width * 4), number of bytes per row */ putreg32(xres * 4, OVL_UI_PITCH(channel)); /* UI Overlay Memory Block Size (DE Page 104) * Set to (height-1) << 16 + (width-1) */ height_width = ((yres - 1) << 16) | (xres - 1); putreg32(height_width, OVL_UI_MBSIZE(channel)); /* UI Overlay Overlay Window Size (DE Page 106) * Set to (height-1) << 16 + (width-1) */ putreg32(height_width, OVL_UI_SIZE(channel)); /* UI Overlay Memory Block Coordinate (DE Page 104) * Set to 0 (Overlay at X=0, Y=0) */ putreg32(0, OVL_UI_COOR(channel)); /* For Channel 1: Set Blender Output */ if (channel == 1) { /* Set Blender Output *************************************************/ ginfo("Channel %d: Set Blender Output\n", channel); /* Blender Output Size Setting (DE Page 110) * Set to (height-1) << 16 + (width-1) */ putreg32(height_width, BLD_SIZE); /* Global Size (DE Page 93) * Set to (height-1) << 16 + (width-1) */ putreg32(height_width, GLB_SIZE); } /* Set Blender Input Pipe *************************************************/ pipe = channel - 1; /* Pipe Number is 0 to 2 for Channels 1 to 3 */ ginfo("Channel %d: Set Blender Input Pipe %d (%d x %d)\n", channel, pipe, xres, yres); /* Blender Input Memory Size (DE Page 108) * Set to (height-1) << 16 + (width-1) */ putreg32(height_width, BLD_CH_ISIZE(pipe)); /* Blender Fill Color (DE Page 107) * Set to Opaque Black * Set ALPHA (Bits 24 to 31) to 0xFF (Opaque) * Set RED (Bits 16 to 23) to 0 * Set GREEN (Bits 8 to 15) to 0 * Set BLUE (Bits 0 to 7) to 0 */ color = FILL_ALPHA(0xff) | FILL_RED(0) | FILL_GREEN(0) | FILL_BLUE(0); putreg32(color, BLD_FILL_COLOR(pipe)); /* Blender Input Memory Offset (DE Page 108) * Set to y_offset << 16 + x_offset */ offset = ((yoffset) << 16) | xoffset; putreg32(offset, BLD_CH_OFFSET(pipe)); /* Blender Control (DE Page 110) * Set BLEND_AFD (Bits 24 to 27) to 3 * (Coefficient for destination alpha data Q[d] is 1-A[s]) * Set BLEND_AFS (Bits 16 to 19) to 1 * (Coefficient for source alpha data Q[s] is 1) * Set BLEND_PFD (Bits 8 to 11) to 3 * (Coefficient for destination pixel data F[d] is 1-A[s]) * Set BLEND_PFS (Bits 0 to 3) to 1 * (Coefficient for source pixel data F[s] is 1) */ blend = BLEND_AFD(3) | BLEND_AFS(1) | BLEND_PFD(3) | BLEND_PFS(1); putreg32(blend, BLD_CTL(pipe)); /* Disable Scaler *********************************************************/ ginfo("Channel %d: Disable Scaler\n", channel); /* UI Scaler Control Register (DE Page 66) * Set EN (Bit 0) to 0 (Disable UI Scaler) */ putreg32(0, UIS_CTRL_REG(channel)); return OK; } /**************************************************************************** * Name: a64_de_enable * * Description: * Set the UI Blender Route, enable the Blender Pipes and enable the * Display Engine. Should be called after all 3 UI Channels have been * initialized. * * Input Parameters: * channels - Number of UI Channels to enable: 1 or 3 * * Returned Value: * OK is always returned at present. * ****************************************************************************/ int a64_de_enable(uint8_t channels) { uint32_t p2_rtctl; uint32_t p1_rtctl; uint32_t route; uint32_t p2_en; uint32_t p1_en; uint32_t fill; DEBUGASSERT(channels == 1 || channels == 3); /* Set Blender Route ******************************************************/ ginfo("Set Blender Route\n"); /* Blender Routing Control (DE Page 108) * If Rendering 1 UI Channel: * Set P0_RTCTL (Bits 0 to 3) to 1 (Pipe 0 from Channel 1) * If Rendering 3 UI Channels: * Set P2_RTCTL (Bits 8 to 11) to 3 (Pipe 2 from Channel 3) * Set P1_RTCTL (Bits 4 to 7) to 2 (Pipe 1 from Channel 2) * Set P0_RTCTL (Bits 0 to 3) to 1 (Pipe 0 from Channel 1) */ p2_rtctl = (channels == 1) ? 0 : /* Unused Pipe 2 */ (channels == 3) ? 3 : /* Select Pipe 2 from UI Channel 3 */ 0; /* Never comes here */ p1_rtctl = (channels == 1) ? 0 : /* Unused Pipe 1 */ (channels == 3) ? 2 : /* Select Pipe 1 from UI Channel 2 */ 0; /* Never comes here */ route = P2_RTCTL(p2_rtctl) | P1_RTCTL(p1_rtctl) | P0_RTCTL(1); putreg32(route, BLD_CH_RTCTL); /* Enable Blender Pipes ***************************************************/ ginfo("Enable Blender Pipes\n"); /* Blender Fill Color Control (DE Page 106) * If Rendering 1 UI Channel: * Set P0_EN (Bit 8) to 1 (Enable Pipe 0) * Set P0_FCEN (Bit 0) to 1 (Enable Pipe 0 Fill Color) * If Rendering 3 UI Channels: * Set P2_EN (Bit 10) to 1 (Enable Pipe 2) * Set P1_EN (Bit 9) to 1 (Enable Pipe 1) * Set P0_EN (Bit 8) to 1 (Enable Pipe 0) * Set P0_FCEN (Bit 0) to 1 (Enable Pipe 0 Fill Color) */ p2_en = (channels == 1) ? 0 : /* 1 UI Channel: Disable Pipe 2 */ (channels == 3) ? 1 : /* 3 UI Channels: Enable Pipe 2 */ 0; /* Never comes here */ p1_en = (channels == 1) ? 0 : /* 1 UI Channel: Disable Pipe 1 */ (channels == 3) ? 1 : /* 3 UI Channels: Enable Pipe 1 */ 0; /* Never comes here */ fill = P2_EN(p2_en) | P1_EN(p1_en) | P0_EN(1) | P0_FCEN(1); putreg32(fill, BLD_FILL_COLOR_CTL); /* Apply Settings *********************************************************/ ginfo("Apply Settings\n"); /* Global Double Buffer Control (DE Page 93) * Set DOUBLE_BUFFER_RDY (Bit 0) to 1 * (Register Value is ready for update) */ putreg32(DOUBLE_BUFFER_RDY, GLB_DBUFFER); return OK; }
7d15ba1c8bcc8c54398e8724e19376de966ab1a0
3499b1145f0827498625ec0ac71ba82bbbbda4ed
/board-package-source/cores/arduboy/wiring.c
80cc453fc29b5bb1af26ee4e7b027ef62cd1ec7d
[ "CC0-1.0" ]
permissive
MrBlinky/Arduboy-homemade-package
09120974a9c6a9ad1871ac68cbf852bb253bbd8e
3b71be313e1a4daaa745a15cdf2b58c92b101441
refs/heads/master
2023-07-22T18:36:15.664481
2023-07-15T22:08:51
2023-07-15T22:08:51
121,283,656
104
31
CC0-1.0
2023-01-02T08:24:54
2018-02-12T18:16:15
C++
UTF-8
C
false
false
26,410
c
wiring.c
/* wiring.c - Partial implementation of the Wiring API for the ATmega8. Part of Arduino - http://www.arduino.cc/ Copyright (c) 2005-2006 David A. Mellis 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "wiring_private.h" // the prescaler is set so that timer0 ticks every 64 clock cycles, and the // the overflow handler is called every 256 ticks. #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256)) // the whole number of milliseconds per timer0 overflow #define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000) // the fractional number of milliseconds per timer0 overflow. we shift right // by three to fit these numbers into a byte. (for the clock speeds we care // about - 8 and 16 MHz - this doesn't lose precision.) #define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3) #define FRACT_MAX (1000 >> 3) volatile unsigned long timer0_overflow_count = 0; volatile unsigned long timer0_millis = 0; static unsigned char timer0_fract = 0; volatile unsigned char button_ticks_hold = 0; #if defined(TIM0_OVF_vect) ISR(TIM0_OVF_vect, ISR_NAKED) #else ISR(TIMER0_OVF_vect, ISR_NAKED) #endif { /* // copy these to local variables so they can be stored in registers // (volatile variables must be read from memory on every access) unsigned long m = timer0_millis; unsigned char f = timer0_fract; m += MILLIS_INC; f += FRACT_INC; if (f >= FRACT_MAX) { f -= FRACT_MAX; m += 1; } timer0_fract = f; timer0_millis = m; timer0_overflow_count++; assembly optimisation saves 50 bytes compared to compiled C++ version (148 bytes) with 28 bytes button code and 22 bytes exit to bootloader code, we end up with the same size but a cool feature added and 3 bytes ram saved (1 byte used extra for button_ticks_hold but 4 bytes saved due to less stack pushes) */ asm volatile( // save registers and SREG before 12622 after 12576 (saving 46 bytes) " push r0 \n" " in r0, __SREG__ \n" " push r24 \n" " push r25 \n" " push r30 \n" " push r31 \n" // millis_inc = MILLIS_INC; (MILLIS_INC == 1) " lds r24, %[fract] \n" // f= timer0_fract; " subi r24, - %[fract_inc] \n" // f += FRACT_INC; " cpi r24, %[fract_max] \n" // if (f >= FRACT_MAX) " brcs 1f \n" // { " subi r24, %[fract_max] \n" // f -= FRACT_MAX; millis_inc++; (++ in the form of reverse carry) "1: \n" // } " sts %[fract], r24 \n" // timer0_fract = f; // timer0_millis += millis_inc (addition by substracting negative value) " ldi r30, lo8(%[millis]) \n" " ldi r31, hi8(%[millis]) \n" " ld r24, z \n" " sbci r24, -%[millis_inc] - 1 \n" // r24 -= 0 - MILLIS_INC - 1 + (f >= FRACT_MAX ? 0 : 1) " st z, r24 \n" " ldd r25, z+1 \n" " sbci r25, 0xFF \n" // save (uint8_t)(timer0_millis >> 8) in 25 " std z+1, r25 \n" " ldd r24, z+2 \n" " sbci r24, 0xFF \n" " std z+2, r24 \n" " ldd r24, z+3 \n" " sbci r24, 0xFF \n" " std z+3, r24 \n" // timer0_overflow_count++; " ldi r30, lo8(%[count]) \n" " ldi r31, hi8(%[count]) \n" " ld r24, z \n" " subi r24, 0xFF \n" // ++ (addition by substracting negative value) " st z, r24 \n" " ldd r24, z+1 \n" " sbci r24, 0xFF \n" " std z+1, r24 \n" " ldd r24, z+2 \n" " sbci r24, 0xFF \n" " std z+2, r24 \n" " ldd r24, z+3 \n" " sbci r24, 0xFF \n" " std z+3, r24 \n" //read Arduboy buttons #ifdef AB_DEVKIT " in r24, %[pinb] \n" // down, left, up buttons " ori r24, 0x8F \n" " sbis %[pinc], 6 \n" // skip right button not pressed " andi r24, 0xFB \n" " sbic %[pinf], 7 \n" // skip A button pressed " sbis %[pinf], 6 \n" // skip B button not pressed " clr r24 \n" " cpi r24, 0xAF \n" // test DevKit UP+DOWN for bootloader #else " in r24, %[pinf] \n" // directional buttons " ori r24, 0x0F \n" // ignore unon button bits " sbic %[pine], 6 \n" // skip A button pressed " sbis %[pinb], 4 \n" // skip B button not pressed " clr r24 \n" // A or B is pressed here, make compare fail " cpi r24, 0x6F \n" // test arduboy UP+DOWN only for bootloader #endif " brne 5f \n" // skip button combo not pressed // test button combo hold long enough "2: lds r24, %[hold] \n" " sub r25, r24 \n" // (uint8_t)(timer0_millis >> 8) - button_ticks_hold " cpi r25, 6 \n" // 1536ms >> 8 " brcs 6f \n" // skip not long enough //button combo pressed long enough: trigger bootloader mode ".global exit_to_bootloader \n" "exit_to_bootloader: \n" " ldi r30, 0x00 \n" //MAGIC KEY address (r30 is 0 from above) " ldi r31, 0x08 \n" " ldi r24, 0x77 \n" //MAGIC KEY " st Z, r24 \n" " std Z+1, r24 \n" " ldi r24, %[value1] \n" // set watchdog timer " ; ldi r31, %[value2] \n" " sts %[wdtcsr], r24 \n" " sts %[wdtcsr], r31 \n" //r31 == 08 == _BV(WDE) " rjmp .-2 \n" // infinite loop will trigger watchdog reset "5: \n" // } // reset button_ticks_hold " sts %[hold], r25 \n" // button_ticks_hold = (uint8_t)(Millis >> 8) "6: \n" //restore registers and return from interrupt " pop r31 \n" " pop r30 \n" " pop r25 \n" " pop r24 \n" " out __SREG__, r0 \n" " pop r0 \n" " reti \n" : : [millis] "" (&timer0_millis), [fract] "" (&timer0_fract), [millis_inc] "M" (MILLIS_INC), [fract_inc] "M" (FRACT_INC), [fract_max] "M" (FRACT_MAX), [count] "" (&timer0_overflow_count), [hold] "" (&button_ticks_hold), [pinf] "I" (_SFR_IO_ADDR(PINF)), [pine] "I" (_SFR_IO_ADDR(PINE)), [pinc] "I" (_SFR_IO_ADDR(PINC)), [pinb] "I" (_SFR_IO_ADDR(PINB)), [value1] "M" ((uint8_t)(_BV(WDCE) | _BV(WDE))), [value2] "M" ((uint8_t)(_BV(WDE))), [wdtcsr] "M" (_SFR_MEM_ADDR(WDTCSR)) : ); } unsigned long millis() { unsigned long m; uint8_t oldSREG = SREG; // disable interrupts while we read timer0_millis or we might get an // inconsistent value (e.g. in the middle of a write to timer0_millis) cli(); m = timer0_millis; SREG = oldSREG; return m; } unsigned long micros() { /* unsigned long m; uint8_t oldSREG = SREG, t; cli(); m = timer0_overflow_count; #if defined(TCNT0) t = TCNT0; #elif defined(TCNT0L) t = TCNT0L; #else #error TIMER 0 not defined #endif #ifdef TIFR0 if ((TIFR0 & _BV(TOV0)) && (t < 255)) m++; #else if ((TIFR & _BV(TOV0)) && (t < 255)) m++; #endif SREG = oldSREG; return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond()); */ //assembly optimalisation register unsigned long m asm("r22"); asm volatile( " in r18, %[sreg] \n" //oldSREG = SREG " cli \n" // " ld r23, x+ \n" // m = timer0_overflow_count << 8 " ld r24, x+ \n" " ld r25, x \n" " in r22, %[tcnt] \n" // (m << 8) | t " out %[sreg], r18 \n" //SREG = oldSREG " sbis %[tif], %[tov] \n" // if ((TIFR & _BV(TOV) && " rjmp 1f \n" " cpi r22, 0xFF \n" // t < 0xFF) " brcc 1f \n" " \n" " subi r23, 0xFF \n" // m++ (m+=256) " sbci r24, 0xFF \n" // " sbci r25, 0xFF \n" // "1: \n" " ldi r18,%[fm] \n" // *( 64 / clockCyclesPerMicrosecond() "2: \n" " add r22, r22 \n" " adc r23, r23 \n" " adc r24, r24 \n" " adc r25, r25 \n" " dec r18 \n" " brne 2b \n" : "=d" (m) : [sreg] "I" (_SFR_IO_ADDR(SREG)), #if defined(TCNT0) [tcnt] "I" (_SFR_IO_ADDR(TCNT0)), #elif defined(TCNT0L) [tcnt] "I" (_SFR_IO_ADDR(TCNT0L)), #else #error TIMER 0 not defined #endif #ifdef TIFR0 [tif] "I" (_SFR_IO_ADDR(TIFR0)), #else [tif] "I" (_SFR_IO_ADDR(TIFR)), #endif [tov] "M" (TOV0), #if (F_CPU == 8000000L) [fm] "M" (4), #elif (F_CPU ==16000000L) [fm] "M" (2), #else #error this version of wiring.c only supports 8MHz and 16MHz CPU clock #endif "x" (&timer0_overflow_count) : "r18" ); return m; } void delay(unsigned long ms) { /* uint32_t start = micros(); while (ms > 0) { yield(); while ( ms > 0 && (micros() - start) >= 1000) { ms--; start += 1000; } } */ //assembly optimalisation asm volatile( " movw r20, %A0 \n" //ms " movw r30, %C0 \n" " call micros \n" //endMicros = micros() "1: \n" " subi r20, 1 \n" //while (ms > 0) " sbc r21, r1 \n" " sbc r30, r1 \n" " sbc r31, r1 \n" " brcs 2f \n" " \n" " subi r22, 0x18 \n" //endMicros += 1000 " sbci r23, 0xFC \n" " sbci r24, 0xFF \n" " sbci r25, 0xFF \n" " rjmp 1b \n" "2: \n" " movw r20, r22 \n" " movw r30, r24 \n" "3: \n" " call micros \n" //while (micros() < endMicros); " cp r22, r20 \n" " cpc r23, r21 \n" " cpc r24, r30 \n" " cpc r25, r31 \n" " brcs 3b \n" : : "d" (ms), "" (micros) : "r20", "r21", "r30", "r31", /*from micros: */ "r18", "r26", "r27" ); } void delayShort(unsigned short ms) { asm volatile( " call micros \n" //endMicros = micros() "1: \n" " sbiw r30, 1 \n" //while (ms > 0) " brcs 2f \n" " \n" " subi r22, 0x18 \n" //endMicros += 1000 " sbci r23, 0xFC \n" " sbci r24, 0xFF \n" " sbci r25, 0xFF \n" " rjmp 1b \n" "2: \n" " movw r20, r22 \n" " movw r30, r24 \n" "3: \n" " call micros \n" //while (micros() < endMicros); " cp r22, r20 \n" " cpc r23, r21 \n" " cpc r24, r30 \n" " cpc r25, r31 \n" " brcs 3b \n" : : "z" (ms), "" (micros) : "r20", "r21", "r22", "r23", /*from micros: */ "r18", "r26", "r27" ); } /* Delay for the given number of microseconds. Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. */ void delayMicroseconds(unsigned int us) { // call = 4 cycles + 2 to 4 cycles to init us(2 for constant delay, 4 for variable) // calling avrlib's delay_us() function with low values (e.g. 1 or // 2 microseconds) gives delays longer than desired. //delay_us(us); #if F_CPU >= 24000000L // for the 24 MHz clock for the aventurous ones, trying to overclock // zero delay fix if (!us) return; // = 3 cycles, (4 when true) // the following loop takes a 1/6 of a microsecond (4 cycles) // per iteration, so execute it six times for each microsecond of // delay requested. us *= 6; // x6 us, = 7 cycles // account for the time taken in the preceeding commands. // we just burned 22 (24) cycles above, remove 5, (5*4=20) // us is at least 6 so we can substract 5 us -= 5; //=2 cycles #elif F_CPU >= 20000000L // for the 20 MHz clock on rare Arduino boards // for a one-microsecond delay, simply return. the overhead // of the function call takes 18 (20) cycles, which is 1us __asm__ __volatile__ ( "nop" "\n" "nop" "\n" "nop" "\n" "nop"); //just waiting 4 cycles if (us <= 1) return; // = 3 cycles, (4 when true) // the following loop takes a 1/5 of a microsecond (4 cycles) // per iteration, so execute it five times for each microsecond of // delay requested. us = (us << 2) + us; // x5 us, = 7 cycles // account for the time taken in the preceeding commands. // we just burned 26 (28) cycles above, remove 7, (7*4=28) // us is at least 10 so we can substract 7 us -= 7; // 2 cycles #elif F_CPU >= 16000000L // for the 16 MHz clock on most Arduino boards // for a one-microsecond delay, simply return. the overhead // of the function call takes 14 (16) cycles, which is 1us if (us <= 1) return; // = 3 cycles, (4 when true) // the following loop takes 1/4 of a microsecond (4 cycles) // per iteration, so execute it four times for each microsecond of // delay requested. us <<= 2; // x4 us, = 4 cycles // account for the time taken in the preceeding commands. // we just burned 19 (21) cycles above, remove 5, (5*4=20) // us is at least 8 so we can substract 5 us -= 5; // = 2 cycles, #elif F_CPU >= 12000000L // for the 12 MHz clock if somebody is working with USB // for a 1 microsecond delay, simply return. the overhead // of the function call takes 14 (16) cycles, which is 1.5us if (us <= 1) return; // = 3 cycles, (4 when true) // the following loop takes 1/3 of a microsecond (4 cycles) // per iteration, so execute it three times for each microsecond of // delay requested. us = (us << 1) + us; // x3 us, = 5 cycles // account for the time taken in the preceeding commands. // we just burned 20 (22) cycles above, remove 5, (5*4=20) // us is at least 6 so we can substract 5 us -= 5; //2 cycles #elif F_CPU >= 8000000L // for the 8 MHz internal clock // for a 1 and 2 microsecond delay, simply return. the overhead // of the function call takes 14 (16) cycles, which is 2us if (us <= 2) return; // = 3 cycles, (4 when true) // the following loop takes 1/2 of a microsecond (4 cycles) // per iteration, so execute it twice for each microsecond of // delay requested. us <<= 1; //x2 us, = 2 cycles // account for the time taken in the preceeding commands. // we just burned 17 (19) cycles above, remove 4, (4*4=16) // us is at least 6 so we can substract 4 us -= 4; // = 2 cycles #else // for the 1 MHz internal clock (default settings for common Atmega microcontrollers) // the overhead of the function calls is 14 (16) cycles if (us <= 16) return; //= 3 cycles, (4 when true) if (us <= 25) return; //= 3 cycles, (4 when true), (must be at least 25 if we want to substract 22) // compensate for the time taken by the preceeding and next commands (about 22 cycles) us -= 22; // = 2 cycles // the following loop takes 4 microseconds (4 cycles) // per iteration, so execute it us/4 times // us is at least 4, divided by 4 gives us 1 (no zero delay bug) us >>= 2; // us div 4, = 4 cycles #endif // busy wait __asm__ __volatile__ ( "1: sbiw %0,1" "\n" // 2 cycles "brne 1b" : "=w" (us) : "0" (us) // 2 cycles ); // return = 4 cycles } void init() //assembly optimized by 68 bytes { // this needs to be called before setup() or some functions won't // work there sei(); // on the ATmega168, timer 0 is also used for fast hardware pwm // (using phase-correct PWM would mean that timer 0 overflowed half as often // resulting in different millis() behavior on the ATmega8 and ATmega168) #if defined(TCCR0A) && defined(WGM01) //sbi(TCCR0A, WGM01); //sbi(TCCR0A, WGM00); asm volatile( " ldi r24, %[value] \n" " out %[tccr0a], r24 \n" : : [tccr0a] "I" (_SFR_IO_ADDR(TCCR0A)), [value] "M" (_BV(WGM01) | _BV(WGM00)) : "r24" ); #endif // set timer 0 prescale factor to 64 #if defined(__AVR_ATmega128__) // CPU specific: different values for the ATmega128 sbi(TCCR0, CS02); #elif defined(TCCR0) && defined(CS01) && defined(CS00) // this combination is for the standard atmega8 sbi(TCCR0, CS01); sbi(TCCR0, CS00); #elif defined(TCCR0B) && defined(CS01) && defined(CS00) // this combination is for the standard 168/328/1280/2560 //sbi(TCCR0B, CS01); //sbi(TCCR0B, CS00); asm volatile( " ldi r24, %[value] \n" " out %[tccr0b], r24 \n" : : [tccr0b] "I" (_SFR_IO_ADDR(TCCR0B)), [value] "M" (_BV(CS01) | _BV(CS00)) : "r24" ); #elif defined(TCCR0A) && defined(CS01) && defined(CS00) // this combination is for the __AVR_ATmega645__ series sbi(TCCR0A, CS01); sbi(TCCR0A, CS00); #else #error Timer 0 prescale factor 64 not set correctly #endif // enable timer 0 overflow interrupt #if defined(TIMSK) && defined(TOIE0) sbi(TIMSK, TOIE0); #elif defined(TIMSK0) && defined(TOIE0) TIMSK0 = _BV(TOIE0); #else #error Timer 0 overflow interrupt not set correctly #endif // timers 1 and 2 are used for phase-correct hardware pwm // this is better for motors as it ensures an even waveform // note, however, that fast pwm mode can achieve a frequency of up // 8 MHz (with a 16 MHz clock) at 50% duty cycle #if defined(TCCR1B) && defined(CS11) && defined(CS10) //TCCR1B = 0; // set timer 1 prescale factor to 64 //sbi(TCCR1B, CS11); //#if F_CPU >= 8000000L //sbi(TCCR1B, CS10); //#endif asm volatile( " ldi r30, %[tccr1b] \n" " ldi r31, 0x00 \n" " ldi r24, %[value] \n" " st z, r24 \n" : : [tccr1b] "M" (_SFR_MEM_ADDR(TCCR1B)), #if F_CPU >= 8000000L [value] "M" (_BV(CS11) | _BV(CS10)) #else [value] "M" (_BV(CS11)) #endif : "r24", "r30", "r31" ); #elif defined(TCCR1) && defined(CS11) && defined(CS10) sbi(TCCR1, CS11); #if F_CPU >= 8000000L sbi(TCCR1, CS10); #endif #endif // put timer 1 in 8-bit phase correct pwm mode #if defined(TCCR1A) && defined(WGM10) //sbi(TCCR1A, WGM10); asm volatile( " ldi r30, %[tccr1a] \n" " ldi r24, %[wgm10] \n" " st z, r24 \n" : : [tccr1a] "M" (_SFR_MEM_ADDR(TCCR1A)), [wgm10] "M" (_BV(WGM10)) : "r24", "r30", "r31" ); #endif // set timer 2 prescale factor to 64 #if defined(TCCR2) && defined(CS22) sbi(TCCR2, CS22); #elif defined(TCCR2B) && defined(CS22) sbi(TCCR2B, CS22); //#else // Timer 2 not finished (may not be present on this CPU) #endif // configure timer 2 for phase correct pwm (8-bit) #if defined(TCCR2) && defined(WGM20) sbi(TCCR2, WGM20); #elif defined(TCCR2A) && defined(WGM20) sbi(TCCR2A, WGM20); //#else // Timer 2 not finished (may not be present on this CPU) #endif #if defined(TCCR3B) && defined(CS31) && defined(WGM30) //sbi(TCCR3B, CS31); // set timer 3 prescale factor to 64 //sbi(TCCR3B, CS30); asm volatile( " ldi r30, %[tccr3b] \n" " ldi r24, %[value] \n" " st z, r24 \n" : : [tccr3b] "M" (_SFR_MEM_ADDR(TCCR3B)), [value] "M" (_BV(CS31) | _BV(CS30)) : "r24", "r30", "r31" ); //sbi(TCCR3A, WGM30); // put timer 3 in 8-bit phase correct pwm mode asm volatile( " ldi r30, %[tccr3a] \n" " ldi r24, %[wgm30] \n" " st z, r24 \n" : : [tccr3a] "M" (_SFR_MEM_ADDR(TCCR3A)), [wgm30] "M" (_BV(WGM30)) : "r24", "r30", "r31" ); #endif #if defined(TCCR4A) && defined(TCCR4B) && defined(TCCR4D) /* beginning of timer4 block for 32U4 and similar */ //sbi(TCCR4B, CS42); // set timer4 prescale factor to 64 //sbi(TCCR4B, CS41); //sbi(TCCR4B, CS40); asm volatile( " ldi r30, %[tccr4b] \n" " ldi r24, %[value] \n" " st z, r24 \n" : : [tccr4b] "M" (_SFR_MEM_ADDR(TCCR4B)), [value] "M" (_BV(CS42) | _BV(CS41) | _BV(CS40)) : "r24", "r30", "r31" ); //sbi(TCCR4D, WGM40); // put timer 4 in phase- and frequency-correct PWM mode asm volatile( " ldi r30, %[tccr4d] \n" " ldi r24, %[wgm40] \n" " st z, r24 \n" : : [tccr4d] "M" (_SFR_MEM_ADDR(TCCR4D)), [wgm40] "M" (_BV(WGM40)) : "r24", "r30", "r31" ); //sbi(TCCR4A, PWM4A); // enable PWM mode for comparator OCR4A asm volatile( " ldi r30, %[tccr4a] \n" " ldi r24, %[pwm4a] \n" " st z, r24 \n" : : [tccr4a] "M" (_SFR_MEM_ADDR(TCCR4A)), [pwm4a] "M" (_BV(PWM4A)) : "r24", "r30", "r31" ); //sbi(TCCR4C, PWM4D); // enable PWM mode for comparator OCR4D asm volatile( " ldi r30, %[tccr4c] \n" " ldi r24, %[value] \n" " st z, r24 \n" : : [tccr4c] "M" (_SFR_MEM_ADDR(TCCR4C)), [value] "M" (_BV(PWM4D)) : "r24", "r30", "r31" ); #else /* beginning of timer4 block for ATMEGA1280 and ATMEGA2560 */ #if defined(TCCR4B) && defined(CS41) && defined(WGM40) sbi(TCCR4B, CS41); // set timer 4 prescale factor to 64 sbi(TCCR4B, CS40); sbi(TCCR4A, WGM40); // put timer 4 in 8-bit phase correct pwm mode #endif #endif /* end timer4 block for ATMEGA1280/2560 and similar */ #if defined(TCCR5B) && defined(CS51) && defined(WGM50) sbi(TCCR5B, CS51); // set timer 5 prescale factor to 64 sbi(TCCR5B, CS50); sbi(TCCR5A, WGM50); // put timer 5 in 8-bit phase correct pwm mode #endif #if defined(ADCSRA) // set a2d prescaler so we are inside the desired 50-200 KHz range. #if F_CPU >= 16000000 // 16 MHz / 128 = 125 KHz //sbi(ADCSRA, ADPS2); //sbi(ADCSRA, ADPS1); //sbi(ADCSRA, ADPS0); asm volatile( " ldi r30, %[adcsra] \n" " ldi r24, %[value] \n" " st z, r24 \n" : : [adcsra] "M" (_SFR_MEM_ADDR(ADCSRA)), [value] "M" (_BV(ADPS2) |_BV(ADPS1) | _BV(ADPS0)) : "r24" ); #elif F_CPU >= 8000000 // 8 MHz / 64 = 125 KHz //sbi(ADCSRA, ADPS2); //sbi(ADCSRA, ADPS1); //cbi(ADCSRA, ADPS0); asm volatile( " ldi r30, %[adcsra] \n" " ldi r24, %[value] \n" " st z, r24 \n" : : [adcsra] "M" (_SFR_MEM_ADDR(ADCSRA)), [value] "M" (_BV(ADPS2) | _BV(ADPS1)) : "r24", "r30", "r31" ); #elif F_CPU >= 4000000 // 4 MHz / 32 = 125 KHz sbi(ADCSRA, ADPS2); cbi(ADCSRA, ADPS1); sbi(ADCSRA, ADPS0); #elif F_CPU >= 2000000 // 2 MHz / 16 = 125 KHz sbi(ADCSRA, ADPS2); cbi(ADCSRA, ADPS1); cbi(ADCSRA, ADPS0); #elif F_CPU >= 1000000 // 1 MHz / 8 = 125 KHz cbi(ADCSRA, ADPS2); sbi(ADCSRA, ADPS1); sbi(ADCSRA, ADPS0); #else // 128 kHz / 2 = 64 KHz -> This is the closest you can get, the prescaler is 2 cbi(ADCSRA, ADPS2); cbi(ADCSRA, ADPS1); sbi(ADCSRA, ADPS0); #endif // enable a2d conversions //sbi(ADCSRA, ADEN); asm volatile( " ori r24, %[aden] \n" " st z, r24 \n" : : [aden] "M" (_BV(ADEN)) : "r24", "r30", "r31" ); #endif //(below not relevant for atmega32u4) // the bootloader connects pins 0 and 1 to the USART; disconnect them // here so they can be used as normal digital i/o; they will be // reconnected in Serial.begin() #if defined(UCSRB) UCSRB = 0; #elif defined(UCSR0B) UCSR0B = 0; #endif }
3775e04d7ea516362dd711f301513d215b083ef6
aa3befea459382dc5c01c925653d54f435b3fb0f
/arch/risc-v/src/litex/hardware/litex_sdio.h
bdd8ef1e2704a5864626effb9f4a28f579283e8b
[ "MIT-open-group", "BSD-3-Clause", "HPND-sell-variant", "BSD-4-Clause-UC", "LicenseRef-scancode-warranty-disclaimer", "MIT-0", "LicenseRef-scancode-bsd-atmel", "LicenseRef-scancode-gary-s-brown", "LicenseRef-scancode-proprietary-license", "SunPro", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "LicenseRef-scancode-other-permissive", "HPND", "ISC", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "GPL-1.0-or-later", "CC-BY-2.0", "CC-BY-4.0" ]
permissive
apache/nuttx
14519a7bff4a87935d94fb8fb2b19edb501c7cec
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
refs/heads/master
2023-08-25T06:55:45.822534
2023-08-23T16:03:31
2023-08-24T21:25:47
228,103,273
407
241
Apache-2.0
2023-09-14T18:26:05
2019-12-14T23:27:55
C
UTF-8
C
false
false
5,866
h
litex_sdio.h
/**************************************************************************** * arch/risc-v/src/litex/hardware/litex_sdio.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ #ifndef __ARCH_RISCV_SRC_LITEX_HARDWARE_LITEX_SDIO_H #define __ARCH_RISCV_SRC_LITEX_HARDWARE_LITEX_SDIO_H /**************************************************************************** * Included Files ****************************************************************************/ #include "hardware/litex_memorymap.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* LITEX_SDIO register offsets **********************************************/ #define LITEX_SDBLOCK2MEM_DMA_BASE_OFFSET 0x0000 #define LITEX_SDBLOCK2MEM_DMA_LENGTH_OFFSET 0x0008 #define LITEX_SDBLOCK2MEM_DMA_ENABLE_OFFSET 0x000C #define LITEX_SDBLOCK2MEM_DMA_DONE_OFFSET 0x0010 #define LITEX_SDBLOCK2MEM_DMA_LOOP_OFFSET 0x0014 #define LITEX_SDBLOCK2MEM_DMA_OFFSET_OFFSET 0x0018 #define LITEX_SDCORE_CMD_ARGUMENT_OFFSET 0x0000 #define LITEX_SDCORE_CMD_COMMAND_OFFSET 0x0004 #define LITEX_SDCORE_CMD_SEND_OFFSET 0x0008 #define LITEX_SDCORE_CMD_RESPONSE_OFFSET 0x000C #define LITEX_SDCORE_CMD_EVENT_OFFSET 0x001C #define LITEX_SDCORE_DATA_EVENT_OFFSET 0x0020 #define LITEX_SDCORE_BLOCK_LENGTH_OFFSET 0x0024 #define LITEX_SDCORE_BLOCK_COUNT_OFFSET 0x0028 #define LITEX_SDIRQ_STATUS_OFFSET 0x0000 #define LITEX_SDIRQ_PENDING_OFFSET 0x0004 #define LITEX_SDIRQ_ENABLE_OFFSET 0x0008 #define LITEX_SDMEM2BLOCK_DMA_BASE_OFFSET 0x0000 #define LITEX_SDMEM2BLOCK_DMA_LENGTH_OFFSET 0x0008 #define LITEX_SDMEM2BLOCK_DMA_ENABLE_OFFSET 0x000C #define LITEX_SDMEM2BLOCK_DMA_DONE_OFFSET 0x0010 #define LITEX_SDMEM2BLOCK_DMA_LOOP_OFFSET 0x0014 #define LITEX_SDMEM2BLOCK_DMA_OFFSET_OFFSET 0x0018 #define LITEX_SDPHY_CARD_DETECT_OFFSET 0x0000 #define LITEX_SDPHY_CLOCKER_DIVIDER_OFFSET 0x0004 #define LITEX_SDPHY_INIT_INITIALIZE_OFFSET 0x0008 #define LITEX_SDPHY_DATAW_STATUS_OFFSET 0x000C /* LITEX_SDIO register addresses ********************************************/ #define LITEX_SDBLOCK2MEM_DMA_BASE (LITEX_SDBLOCK2MEM_BASE+LITEX_SDBLOCK2MEM_DMA_BASE_OFFSET) #define LITEX_SDBLOCK2MEM_DMA_LENGTH (LITEX_SDBLOCK2MEM_BASE+LITEX_SDBLOCK2MEM_DMA_LENGTH_OFFSET) #define LITEX_SDBLOCK2MEM_DMA_ENABLE (LITEX_SDBLOCK2MEM_BASE+LITEX_SDBLOCK2MEM_DMA_ENABLE_OFFSET) #define LITEX_SDBLOCK2MEM_DMA_DONE (LITEX_SDBLOCK2MEM_BASE+LITEX_SDBLOCK2MEM_DMA_DONE_OFFSET) #define LITEX_SDBLOCK2MEM_DMA_LOOP (LITEX_SDBLOCK2MEM_BASE+LITEX_SDBLOCK2MEM_DMA_LOOP_OFFSET) #define LITEX_SDBLOCK2MEM_DMA_OFFSET (LITEX_SDBLOCK2MEM_BASE+LITEX_SDBLOCK2MEM_DMA_OFFSET_OFFSET) #define LITEX_SDCORE_CMD_ARGUMENT (LITEX_SDCORE_BASE+LITEX_SDCORE_CMD_ARGUMENT_OFFSET) #define LITEX_SDCORE_CMD_COMMAND (LITEX_SDCORE_BASE+LITEX_SDCORE_CMD_COMMAND_OFFSET) #define LITEX_SDCORE_CMD_SEND (LITEX_SDCORE_BASE+LITEX_SDCORE_CMD_SEND_OFFSET) #define LITEX_SDCORE_CMD_RESPONSE (LITEX_SDCORE_BASE+LITEX_SDCORE_CMD_RESPONSE_OFFSET) #define LITEX_SDCORE_CMD_EVENT (LITEX_SDCORE_BASE+LITEX_SDCORE_CMD_EVENT_OFFSET) #define LITEX_SDCORE_DATA_EVENT (LITEX_SDCORE_BASE+LITEX_SDCORE_DATA_EVENT_OFFSET) #define LITEX_SDCORE_BLOCK_LENGTH (LITEX_SDCORE_BASE+LITEX_SDCORE_BLOCK_LENGTH_OFFSET) #define LITEX_SDCORE_BLOCK_COUNT (LITEX_SDCORE_BASE+LITEX_SDCORE_BLOCK_COUNT_OFFSET) #define LITEX_SDIRQ_STATUS (LITEX_SDIRQ_BASE+LITEX_SDIRQ_STATUS_OFFSET) #define LITEX_SDIRQ_PENDING (LITEX_SDIRQ_BASE+LITEX_SDIRQ_PENDING_OFFSET) #define LITEX_SDIRQ_ENABLE (LITEX_SDIRQ_BASE+LITEX_SDIRQ_ENABLE_OFFSET) #define LITEX_SDMEM2BLOCK_DMA_BASE (LITEX_SDMEM2BLOCK_BASE+LITEX_SDMEM2BLOCK_DMA_BASE_OFFSET) #define LITEX_SDMEM2BLOCK_DMA_LENGTH (LITEX_SDMEM2BLOCK_BASE+LITEX_SDMEM2BLOCK_DMA_LENGTH_OFFSET) #define LITEX_SDMEM2BLOCK_DMA_ENABLE (LITEX_SDMEM2BLOCK_BASE+LITEX_SDMEM2BLOCK_DMA_ENABLE_OFFSET) #define LITEX_SDMEM2BLOCK_DMA_DONE (LITEX_SDMEM2BLOCK_BASE+LITEX_SDMEM2BLOCK_DMA_DONE_OFFSET) #define LITEX_SDMEM2BLOCK_DMA_LOOP (LITEX_SDMEM2BLOCK_BASE+LITEX_SDMEM2BLOCK_DMA_LOOP_OFFSET) #define LITEX_SDMEM2BLOCK_DMA_OFFSET (LITEX_SDMEM2BLOCK_BASE+LITEX_SDMEM2BLOCK_DMA_OFFSET_OFFSET) #define LITEX_SDPHY_CARD_DETECT (LITEX_SDPHY_BASE+LITEX_SDPHY_CARD_DETECT_OFFSET) #define LITEX_SDPHY_CLOCKER_DIVIDER (LITEX_SDPHY_BASE+LITEX_SDPHY_CLOCKER_DIVIDER_OFFSET) #define LITEX_SDPHY_INIT_INITIALIZER (LITEX_SDPHY_BASE+LITEX_SDPHY_INIT_INITIALIZE_OFFSET) #define LITEX_SDPHY_DATAW_STATUS (LITEX_SDPHY_BASE+LITEX_SDPHY_DATAW_STATUS_OFFSET) /* LITEX_SDIO register bit definitions **************************************/ #endif /* __ARCH_RISCV_SRC_LITEX_HARDWARE_LITEX_SDIO_H */
e95261d9c3bd6d003d703a7790eb4df4533a305a
e73547787354afd9b717ea57fe8dd0695d161821
/src/world/area_kpa/kpa_13/kpa_13.h
eb1baef823ced3de731740f399ccd23238b8228c
[]
no_license
pmret/papermario
8b514b19653cef8d6145e47499b3636b8c474a37
9774b26d93f1045dd2a67e502b6efc9599fb6c31
refs/heads/main
2023-08-31T07:09:48.951514
2023-08-21T18:07:08
2023-08-21T18:07:08
287,151,133
904
139
null
2023-09-14T02:44:23
2020-08-13T01:22:57
C
UTF-8
C
false
false
380
h
kpa_13.h
/// @file kpa_13.h /// @brief Bowser's Castle - Lava Channel 2 #include "common.h" #include "message_ids.h" #include "map.h" #include "../kpa.h" #include "mapfs/kpa_13_shape.h" #include "mapfs/kpa_13_hit.h" #define NAMESPACE kpa_13 extern EvtScript N(EVS_Main); extern EvtScript N(EVS_SetupMusic); extern EvtScript N(EVS_SetupPlatforms); extern EvtScript N(EVS_MakeEntities);
e0b4b11dcc0f58a0611fa57a0f20112ac3e78b92
33e02c0f9deaaa1e5ccc2b2932ec2af281122236
/examples/xmgl/triangles.fs.c
af104b3876ad902d1135ada4dfaa3af6986ddde3
[ "WTFPL" ]
permissive
Artefact2/libxm
cb09b8f7fe5f5cfb34771a8dec6bc3f7fac715b3
bd9abb643f7b39c6c42fd8a981495a16e44e7dd9
refs/heads/master
2021-12-31T15:22:54.052727
2021-12-28T16:41:05
2021-12-28T16:41:05
10,250,877
120
19
WTFPL
2022-01-17T17:42:29
2013-05-23T18:47:33
C
UTF-8
C
false
false
1,029
c
triangles.fs.c
#version 330 core in vec2 vposition; out vec4 fragcolor; uniform vec4 xmg; /* Time, AspectRatio, unused, unused */ uniform vec4 xmci; /* Chn, NChns, Instr, NInstrs */ uniform vec4 xmdata; /* log2(Freq), Vol, SecsSinceLastTrigger, Panning */ const float sqrt3_2 = .86602540378443864676f; const float two_pi = 6.28318530717958647688f; vec3 color(float hue) { hue *= two_pi; return vec3(.5) + .5 * vec3(cos(hue), cos(hue + two_pi / 3.f), cos(hue + 2.f * two_pi / 3.f)); } void main() { if(xmdata.y < 0.01) discard; float theta = two_pi * xmdata.x / 6.f; float ct = cos(theta); float st = sin(theta); vec2 p = vec2(vposition.x - (xmdata.w - .5f) / 2.f, vposition.y) * 1.35f; p = mat2(ct, -st, st, ct) * p; p /= sqrt(xmdata.y); if(p.x < -.5) discard; if(sqrt3_2 * p.x + 1.5f * p.y > sqrt3_2) discard; if(sqrt3_2 * p.x - 1.5f * p.y > sqrt3_2) discard; float vol = smoothstep(0.0, 1.0, xmdata.y); float beat = exp(-10.0 * xmdata.z); fragcolor = vec4(mix(color(xmdata.x), vec3(1.0), .5 * beat), .1f + vol * .9f); }
f2dd7ef4a5f7b1335773b512d3a9370475ffed7e
f8cc1dd4b1378490386def2e0571561fab10b275
/src/libstddjb/sysclock_from_utc.c
c3f8df1d2cb262213b93ebd543679117c259807f
[ "ISC" ]
permissive
skarnet/skalibs
b1eb2a0e38663cbfa918ee0a7916f56227bd7c2d
1f2d5f95684e93f8523e369ef1fed7a75c444082
refs/heads/master
2023-08-23T07:33:20.996016
2023-08-08T09:39:15
2023-08-08T09:39:15
31,461,366
104
32
ISC
2021-04-11T10:10:54
2015-02-28T12:01:41
C
UTF-8
C
false
false
404
c
sysclock_from_utc.c
/* ISC license. */ #include <errno.h> #include <skalibs/config.h> #include <skalibs/uint64.h> #include <skalibs/djbtime.h> #ifdef SKALIBS_FLAG_CLOCKISTAI int sysclock_from_utc (uint64_t *u) { tai t ; if (!tai_from_utc(&t, *u)) return 0 ; if (t.x < 10) return (errno = EINVAL, 0) ; *u = t.x - 10 ; return 1 ; } #else int sysclock_from_utc (uint64_t *u) { (void)u ; return 1 ; } #endif
3ef0e71f54028e460da5d32789f39d1179c551a0
cf482a354ef3287f8d80163d12dfd6207220007a
/src/python.c
b473f36ff2d15588e5c715ea13143d6fb4b7ad9b
[ "PostgreSQL" ]
permissive
Segfault-Inc/Multicorn
f3996a9a01782dafc3ec5dbddf9c03fa40ab9a39
3b4da7f9f4ea339e71c6bb7df22d441c980b5aef
refs/heads/master
2023-07-31T04:02:13.289966
2020-08-18T13:56:06
2022-04-05T06:33:40
1,851,271
167
42
PostgreSQL
2023-09-04T18:50:12
2011-06-05T18:37:51
Python
UTF-8
C
false
false
41,565
c
python.c
#include <Python.h> #include "datetime.h" #include "postgres.h" #include "multicorn.h" #include "catalog/pg_user_mapping.h" #include "access/reloptions.h" #include "miscadmin.h" #include "utils/numeric.h" #include "utils/date.h" #include "utils/timestamp.h" #include "utils/array.h" #include "utils/catcache.h" #include "utils/memutils.h" #include "utils/resowner.h" #include "utils/rel.h" #include "utils/rel.h" #include "executor/nodeSubplan.h" #include "bytesobject.h" #include "mb/pg_wchar.h" #include "access/xact.h" #include "utils/lsyscache.h" PGDLLEXPORT List *getOptions(Oid foreigntableid); PGDLLEXPORT bool compareOptions(List *options1, List *options2); PGDLLEXPORT void getColumnsFromTable(TupleDesc desc, PyObject **p_columns, List **columns); PGDLLEXPORT bool compareColumns(List *columns1, List *columns2); PGDLLEXPORT PyObject *getClass(PyObject *className); PGDLLEXPORT PyObject *valuesToPySet(List *targetlist); PGDLLEXPORT PyObject *qualDefsToPyList(List *quallist, ConversionInfo ** cinfo); PGDLLEXPORT PyObject *pythonQual(char *operatorname, PyObject *value, ConversionInfo * cinfo, bool is_array, bool use_or, Oid typeoid); PGDLLEXPORT PyObject *getSortKey(MulticornDeparsedSortGroup *key); PGDLLEXPORT MulticornDeparsedSortGroup *getDeparsedSortGroup(PyObject *key); PGDLLEXPORT Datum pyobjectToDatum(PyObject *object, StringInfo buffer, ConversionInfo * cinfo); PGDLLEXPORT PyObject *qualdefToPython(MulticornConstQual * qualdef, ConversionInfo ** cinfo); PGDLLEXPORT PyObject *paramDefToPython(List *paramdef, ConversionInfo ** cinfos, Oid typeoid, Datum value); PGDLLEXPORT PyObject *datumNumberToPython(Datum node, ConversionInfo * cinfo); PGDLLEXPORT PyObject *datumDateToPython(Datum datum, ConversionInfo * cinfo); PGDLLEXPORT PyObject *datumStringToPython(Datum node, ConversionInfo * cinfo); PGDLLEXPORT PyObject *datumTimestampToPython(Datum datum, ConversionInfo * cinfo); PGDLLEXPORT PyObject *datumIntToPython(Datum datum, ConversionInfo * cinfo); PGDLLEXPORT PyObject *datumArrayToPython(Datum datum, Oid type, ConversionInfo * cinfo); PGDLLEXPORT PyObject *datumUnknownToPython(Datum datum, ConversionInfo * cinfo, Oid type); PGDLLEXPORT PyObject *datumByteaToPython(Datum datum, ConversionInfo * cinfo); void pythonDictToTuple(PyObject *p_value, TupleTableSlot *slot, ConversionInfo ** cinfos, StringInfo buffer); void pythonSequenceToTuple(PyObject *p_value, TupleTableSlot *slot, ConversionInfo ** cinfos, StringInfo buffer); /* Python to cstring functions */ void pyobjectToCString(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo); void pynumberToCString(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo); void pyunicodeToCString(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo); void pystringToCString(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo); void pysequenceToCString(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo); void pymappingToCString(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo); void pydateToCString(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo); void pyunknownToCstring(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo); void appendBinaryStringInfoQuote(StringInfo buffer, char *tempbuffer, Py_ssize_t strlength, bool need_quote); static void begin_remote_xact(CacheEntry * entry); /* * Get a (python) encoding name for an attribute. */ const char * getPythonEncodingName() { const char *encoding_name = GetDatabaseEncodingName(); if (strcmp(encoding_name, "SQL_ASCII") == 0) { encoding_name = "ascii"; } return encoding_name; } char * PyUnicode_AsPgString(PyObject *p_unicode) { char *message = NULL; PyObject *pTempStr; if (p_unicode == NULL) { elog(ERROR, "Received a null pointer in pyunicode_aspgstring"); } pTempStr = PyUnicode_AsEncodedString(p_unicode, getPythonEncodingName(), NULL); errorCheck(); message = strdup(PyBytes_AsString(pTempStr)); errorCheck(); Py_DECREF(pTempStr); return message; } #if PY_MAJOR_VERSION >= 3 /* * Convert a C string in the PostgreSQL server encoding to a Python * unicode object. Reference ownership is passed to the caller. */ PyObject * PyString_FromStringAndSize(const char *s, Py_ssize_t size) { char *utf8string; PyObject *o; utf8string = (char *) pg_do_encoding_conversion((unsigned char *) s, strlen(s), GetDatabaseEncoding(), PG_UTF8); if (size < 0) { o = PyUnicode_FromString(utf8string); } else { o = PyUnicode_FromStringAndSize(utf8string, size); } if (utf8string != s) pfree(utf8string); return o; } PyObject * PyString_FromString(const char *s) { return PyString_FromStringAndSize(s, -1); } char * PyString_AsString(PyObject *unicode) { char *rv; PyObject *o = PyUnicode_AsEncodedString(unicode, GetDatabaseEncodingName(), NULL); errorCheck(); rv = pstrdup(PyBytes_AsString(o)); Py_XDECREF(o); return rv; } int PyString_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length) { PyObject *o; int rv; char *tempbuffer; if (PyUnicode_Check(obj)) { o = PyUnicode_AsEncodedString(obj, GetDatabaseEncodingName(), NULL); errorCheck(); rv = PyBytes_AsStringAndSize(o, &tempbuffer, length); *buffer = pstrdup(tempbuffer); Py_XDECREF(o); return rv; } return PyBytes_AsStringAndSize(obj, buffer, length); } #endif /* PY_MAJOR_VERSION >= 3 */ /* * Utility function responsible for importing, and returning, a class by name * * Returns a new reference to the class. */ PyObject * getClass(PyObject *className) { PyObject *p_multicorn = PyImport_ImportModule("multicorn"), *p_class = PyObject_CallMethod(p_multicorn, "get_class", "(O)", className); errorCheck(); Py_DECREF(p_multicorn); return p_class; } void appendBinaryStringInfoQuote(StringInfo buffer, char *tempbuffer, Py_ssize_t strlength, bool need_quote) { if (need_quote) { char *c; int i; appendStringInfoChar(buffer, '"'); for (c = tempbuffer, i = 0; i < strlength; ++i, ++c) { if (*c == '"') { appendBinaryStringInfo(buffer, "\\\"", 2); } else if (*c == '\\') { appendBinaryStringInfo(buffer, "\\\\", 2); } else { appendStringInfoChar(buffer, *c); } } appendStringInfoChar(buffer, '"'); } else { appendBinaryStringInfo(buffer, tempbuffer, strlength); } } /* * Convert a list of Value nodes containing the column name as a string to a * pyset of python unicode strings. */ PyObject * valuesToPySet(List *targetlist) { PyObject *result = PySet_New(0); ListCell *lc; foreach(lc, targetlist) { Value *value = (Value *) lfirst(lc); PyObject *pyString = PyString_FromString(strVal(value)); PySet_Add(result, pyString); Py_DECREF(pyString); } return result; } PyObject * qualDefsToPyList(List *qual_list, ConversionInfo ** cinfos) { ListCell *lc; PyObject *p_quals = PyList_New(0); foreach(lc, qual_list) { MulticornBaseQual *qual_def = (MulticornBaseQual *) lfirst(lc); if (qual_def->right_type == T_Const) { PyObject *python_qual = qualdefToPython((MulticornConstQual *) qual_def, cinfos); if (python_qual != NULL) { PyList_Append(p_quals, python_qual); Py_DECREF(python_qual); } } } return p_quals; } /* * Same as getClass, but accepts a C-String argument instead of a python * string. * * Returns a new reference to the class. */ PyObject * getClassString(const char *className) { PyObject *p_classname = PyString_FromString(className), *p_class = getClass(p_classname); Py_DECREF(p_classname); return p_class; } List * getOptions(Oid foreigntableid) { ForeignTable *f_table; ForeignServer *f_server; UserMapping *mapping; List *options; f_table = GetForeignTable(foreigntableid); f_server = GetForeignServer(f_table->serverid); options = NIL; options = list_concat(options, f_table->options); options = list_concat(options, f_server->options); /* An error might occur if no user mapping is defined. */ /* In that case, just ignore it */ mapping = multicorn_GetUserMapping(GetUserId(), f_table->serverid); if (mapping) options = list_concat(options, mapping->options); return options; } /* * Reimplementation of GetUserMapping, which returns NULL instead of throwing an * error when the mapping is not found. */ UserMapping * multicorn_GetUserMapping(Oid userid, Oid serverid) { Datum datum; HeapTuple tp; bool isnull; UserMapping *um; tp = SearchSysCache2(USERMAPPINGUSERSERVER, ObjectIdGetDatum(userid), ObjectIdGetDatum(serverid)); if (!HeapTupleIsValid(tp)) { /* Not found for the specific user -- try PUBLIC */ tp = SearchSysCache2(USERMAPPINGUSERSERVER, ObjectIdGetDatum(InvalidOid), ObjectIdGetDatum(serverid)); } if (!HeapTupleIsValid(tp)) return NULL; um = (UserMapping *) palloc(sizeof(UserMapping)); um->userid = userid; um->serverid = serverid; /* Extract the umoptions */ datum = SysCacheGetAttr(USERMAPPINGUSERSERVER, tp, Anum_pg_user_mapping_umoptions, &isnull); if (isnull) um->options = NIL; else um->options = untransformRelOptions(datum); ReleaseSysCache(tp); return um; } /* * Collect and validate options. * Only one option is required "wrapper". * * Returns a new reference to a dictionary. * * */ PyObject * optionsListToPyDict(List *options) { ListCell *lc; PyObject *p_options_dict = PyDict_New(); foreach(lc, options) { DefElem *def = (DefElem *) lfirst(lc); PyObject *pStr = PyString_FromString((char *) defGetString(def)); PyDict_SetItemString(p_options_dict, def->defname, pStr); Py_DECREF(pStr); } return p_options_dict; } bool compareOptions(List *options1, List *options2) { ListCell *lc1, *lc2; if (list_length(options1) != list_length(options2)) { return false; } forboth(lc1, options1, lc2, options2) { DefElem *def1 = (DefElem *) lfirst(lc1); DefElem *def2 = (DefElem *) lfirst(lc2); if (def1 == NULL || def2 == NULL || strcmp(def1->defname, def2->defname) != 0) { return false; } if (strcmp(defGetString(def1), defGetString(def2)) != 0) { return false; } } return true; } void getColumnsFromTable(TupleDesc desc, PyObject **p_columns, List **columns) { PyObject *columns_dict = *p_columns; List *columns_list = *columns; if ((columns_dict != NULL) && (columns_list != NULL)) { return; } else { int i; PyObject *p_columnclass = getClassString("multicorn." "ColumnDefinition"), *p_collections = PyImport_ImportModule("collections"), *p_dictclass = PyObject_GetAttrString(p_collections, "OrderedDict"); columns_dict = PyObject_CallFunction(p_dictclass, "()"); for (i = 0; i < desc->natts; i++) { Form_pg_attribute att = TupleDescAttr(desc, i); if (!att->attisdropped) { Oid typOid = att->atttypid; char *key = NameStr(att->attname); int32 typmod = att->atttypmod; char *base_type = format_type_be(typOid); char *modded_type = format_type_with_typemod(typOid, typmod); List *options = GetForeignColumnOptions(att->attrelid, att->attnum); PyObject *p_options = optionsListToPyDict(options); PyObject *column = PyObject_CallFunction(p_columnclass, "(s,i,i,s,s,O)", key, typOid, typmod, modded_type, base_type, p_options); List *columnDef = NULL; errorCheck(); columnDef = lappend(columnDef, makeString(pstrdup(key))); columnDef = lappend(columnDef, makeConst(TYPEOID, -1, InvalidOid, 4, ObjectIdGetDatum(typOid), false, true)); columnDef = lappend(columnDef, makeConst(INT4OID, -1, InvalidOid, 4, Int32GetDatum(typmod), false, true)); columnDef = lappend(columnDef, options); columns_list = lappend(columns_list, columnDef); PyMapping_SetItemString(columns_dict, key, column); Py_DECREF(p_options); Py_DECREF(column); } } Py_DECREF(p_columnclass); Py_DECREF(p_collections); Py_DECREF(p_dictclass); errorCheck(); *p_columns = columns_dict; *columns = columns_list; } } bool compareColumns(List *columns1, List *columns2) { ListCell *lc1, *lc2; if (columns1->length != columns2->length) { return false; } forboth(lc1, columns1, lc2, columns2) { List *coldef1 = lfirst(lc1); List *coldef2 = lfirst(lc2); ListCell *cell1 = list_head(coldef1), *cell2 = list_head(coldef2); /* Compare column name */ if (strcmp(strVal(lfirst(cell1)), strVal(lfirst(cell2))) != 0) { return false; } #if PG_VERSION_NUM >= 130000 cell1 = lnext(coldef1, cell1); cell2 = lnext(coldef2, cell2); #else cell1 = lnext(cell1); cell2 = lnext(cell2); #endif /* Compare typoid */ if (((Const *) (lfirst(cell1)))->constvalue != ((Const *) lfirst(cell2))->constvalue) { return false; } #if PG_VERSION_NUM >= 130000 cell1 = lnext(coldef1, cell1); cell2 = lnext(coldef2, cell2); #else cell1 = lnext(cell1); cell2 = lnext(cell2); #endif /* Compare typmod */ if (((Const *) (lfirst(cell1)))->constvalue != ((Const *) lfirst(cell2))->constvalue) { return false; } #if PG_VERSION_NUM >= 130000 cell1 = lnext(coldef1, cell1); cell2 = lnext(coldef2, cell2); #else cell1 = lnext(cell1); cell2 = lnext(cell2); #endif /* Compare column options */ if (!compareOptions(lfirst(cell1), lfirst(cell2))) { return false; } } return true; } CacheEntry * getCacheEntry(Oid foreigntableid) { /* * create a temporary context. If we have to (re)create the python * instance, it will be promoted to a cachememorycontext. Otherwise, it * will be freed before returning the instance */ MemoryContext tempContext = AllocSetContextCreate(CurrentMemoryContext, "multicorn temporary data", ALLOCSET_SMALL_MINSIZE, ALLOCSET_SMALL_INITSIZE, ALLOCSET_SMALL_MAXSIZE), oldContext = MemoryContextSwitchTo(tempContext); CacheEntry *entry = NULL; bool found = false; List *options = getOptions(foreigntableid); List *columns = NULL; PyObject *p_columns = NULL; ForeignTable *ftable = GetForeignTable(foreigntableid); Relation rel = RelationIdGetRelation(ftable->relid); TupleDesc desc = rel->rd_att; bool needInitialization = false; entry = hash_search(InstancesHash, &foreigntableid, HASH_ENTER, &found); if (!found || entry->value == NULL) { entry->options = NULL; entry->columns = NULL; entry->cacheContext = NULL; entry->xact_depth = 0; needInitialization = true; } else { /* Even if found, we have to check several things */ if (!compareOptions(entry->options, options)) { /* Options have changed, we must purge the cache. */ Py_XDECREF(entry->value); needInitialization = true; } else { /* Options have not changed, we should look at columns. */ getColumnsFromTable(desc, &p_columns, &columns); if (!compareColumns(columns, entry->columns)) { Py_XDECREF(entry->value); needInitialization = true; } else { Py_XDECREF(p_columns); } } } if (needInitialization) { PyObject *p_options = optionsListToPyDict(options), *p_class = getClass(PyDict_GetItemString(p_options, "wrapper")), *p_instance; entry->value = NULL; getColumnsFromTable(desc, &p_columns, &columns); PyDict_DelItemString(p_options, "wrapper"); p_instance = PyObject_CallFunction(p_class, "(O,O)", p_options, p_columns); errorCheck(); /* Cleanup the old context, containing the old columns and options */ /* values */ if (entry->cacheContext != NULL) { MemoryContextDelete(entry->cacheContext); } /* Promote this tempcontext. */ MemoryContextSetParent(tempContext, CacheMemoryContext); entry->cacheContext = tempContext; entry->options = options; entry->columns = columns; entry->xact_depth = 0; Py_DECREF(p_class); Py_DECREF(p_options); Py_DECREF(p_columns); errorCheck(); entry->value = p_instance; MemoryContextSwitchTo(oldContext); } else { MemoryContextSwitchTo(oldContext); MemoryContextDelete(tempContext); } RelationClose(rel); Py_INCREF(entry->value); /* * Start a new transaction or subtransaction if needed. */ begin_remote_xact(entry); return entry; } /* * Returns the fdw_instance associated with the foreigntableid. * * For performance reasons, it is cached in hash table. */ PyObject * getInstance(Oid foreigntableid) { return getCacheEntry(foreigntableid)->value; } static void begin_remote_xact(CacheEntry * entry) { int curlevel = GetCurrentTransactionNestLevel(); PyObject *rv; /* Start main transaction if we haven't yet */ if (entry->xact_depth <= 0) { rv = PyObject_CallMethod(entry->value, "begin", "(i)", IsolationIsSerializable()); Py_XDECREF(rv); errorCheck(); entry->xact_depth = 1; } while (entry->xact_depth < curlevel) { entry->xact_depth++; rv = PyObject_CallMethod(entry->value, "sub_begin", "(i)", entry->xact_depth); Py_XDECREF(rv); errorCheck(); } } /* * Returns the relation estimated size, in term of number of rows and width. * This is done by calling the getRelSize python method. * */ void getRelSize(MulticornPlanState * state, PlannerInfo *root, double *rows, int *width) { PyObject *p_targets_set, *p_quals, *p_rows_and_width, *p_rows, *p_width, *p_startup_cost; p_targets_set = valuesToPySet(state->target_list); p_quals = qualDefsToPyList(state->qual_list, state->cinfos); p_rows_and_width = PyObject_CallMethod(state->fdw_instance, "get_rel_size", "(O,O)", p_quals, p_targets_set); errorCheck(); Py_DECREF(p_targets_set); Py_DECREF(p_quals); if ((p_rows_and_width == Py_None) || PyTuple_Size(p_rows_and_width) != 2) { Py_DECREF(p_rows_and_width); elog(ERROR, "The get_rel_size python method should return a tuple of length 2"); } p_rows = PyNumber_Long(PyTuple_GetItem(p_rows_and_width, 0)); p_width = PyNumber_Long(PyTuple_GetItem(p_rows_and_width, 1)); p_startup_cost = PyNumber_Long( PyObject_GetAttrString(state->fdw_instance, "_startup_cost")); *rows = PyLong_AsDouble(p_rows); *width = (int) PyLong_AsLong(p_width); state->startupCost = (int) PyLong_AsLong(p_startup_cost); Py_DECREF(p_rows); Py_DECREF(p_width); Py_DECREF(p_rows_and_width); } PyObject * qualdefToPython(MulticornConstQual * qualdef, ConversionInfo ** cinfos) { int arrayindex = qualdef->base.varattno - 1; char *operatorname = qualdef->base.opname; ConversionInfo *cinfo = cinfos[arrayindex]; bool is_array = qualdef->base.isArray, use_or = qualdef->base.useOr; Oid typeoid = qualdef->base.typeoid; Datum value = qualdef->value; PyObject *p_value; if (qualdef->isnull) { p_value = Py_None; Py_INCREF(Py_None); } else { if (typeoid == InvalidOid) { typeoid = cinfo->atttypoid; } p_value = datumToPython(value, typeoid, cinfo); if (p_value == NULL) { return NULL; } } if (typeoid <= 0) { typeoid = cinfo->atttypoid; } return pythonQual(operatorname, p_value, cinfo, is_array, use_or, typeoid); } PyObject * pythonQual(char *operatorname, PyObject *value, ConversionInfo * cinfo, bool is_array, bool use_or, Oid typeoid) { PyObject *qualClass = getClassString("multicorn.Qual"), *qualInstance, *p_operatorname, *operator, *columnName; p_operatorname = PyUnicode_Decode(operatorname, strlen(operatorname), getPythonEncodingName(), NULL); errorCheck(); if (is_array) { PyObject *arrayOpType; if (use_or) { arrayOpType = Py_True; } else { arrayOpType = Py_False; } operator = Py_BuildValue("(O, O)", p_operatorname, arrayOpType); Py_DECREF(p_operatorname); errorCheck(); } else { operator = p_operatorname; } columnName = PyUnicode_Decode(cinfo->attrname, strlen(cinfo->attrname), getPythonEncodingName(), NULL); qualInstance = PyObject_CallFunction(qualClass, "(O,O,O)", columnName, operator, value); errorCheck(); Py_DECREF(value); Py_DECREF(operator); Py_DECREF(qualClass); Py_DECREF(columnName); return qualInstance; } PyObject * getSortKey(MulticornDeparsedSortGroup *key) { PyObject *SortKeyClass = getClassString("multicorn.SortKey"), *SortKeyInstance, *p_attname, *p_reversed, *p_nulls_first, *p_collate; p_attname = PyUnicode_Decode(NameStr(*(key->attname)), strlen(NameStr(*(key->attname))), getPythonEncodingName(), NULL); if (key->reversed) p_reversed = Py_True; else p_reversed = Py_False; if (key->nulls_first) p_nulls_first = Py_True; else p_nulls_first = Py_False; if(key->collate == NULL){ p_collate = Py_None; Py_INCREF(p_collate); } else p_collate = PyUnicode_Decode(NameStr(*(key->collate)), strlen(NameStr(*(key->collate))), getPythonEncodingName(), NULL); SortKeyInstance = PyObject_CallFunction(SortKeyClass, "(O,i,O,O,O)", p_attname, key->attnum, p_reversed, p_nulls_first, p_collate); errorCheck(); Py_DECREF(p_attname); Py_DECREF(p_collate); Py_DECREF(SortKeyClass); return SortKeyInstance; } MulticornDeparsedSortGroup * getDeparsedSortGroup(PyObject *sortKey) { MulticornDeparsedSortGroup *md = palloc0(sizeof(MulticornDeparsedSortGroup)); PyObject * p_temp; p_temp = PyObject_GetAttrString(sortKey, "attname"); md->attname = (Name) strdup(PyUnicode_AS_DATA(p_temp)); Py_DECREF(p_temp); p_temp = PyObject_GetAttrString(sortKey, "attnum"); md->attnum = (int) PyLong_AsLong(p_temp); Py_DECREF(p_temp); p_temp = PyObject_GetAttrString(sortKey, "is_reversed"); md->reversed = PyObject_IsTrue(p_temp); Py_DECREF(p_temp); p_temp = PyObject_GetAttrString(sortKey, "nulls_first"); md->nulls_first = PyObject_IsTrue(PyObject_GetAttrString(sortKey, "nulls_first")); Py_DECREF(p_temp); p_temp = PyObject_GetAttrString(sortKey, "collate"); if(p_temp == Py_None) md->collate = 0; else md->collate = (Name) strdup(PyUnicode_AS_DATA(p_temp)); Py_DECREF(p_temp); return md; } /* * Execute the query in the python fdw, and returns an iterator. */ PyObject * execute(ForeignScanState *node, ExplainState *es) { MulticornExecState *state = node->fdw_state; PyObject *p_targets_set, *p_quals = PyList_New(0), *p_pathkeys = PyList_New(0), *p_iterable, *p_method; ListCell *lc; ExprContext *econtext = node->ss.ps.ps_ExprContext; foreach(lc, state->qual_list) { MulticornBaseQual *qual = lfirst(lc); MulticornConstQual *newqual = NULL; bool isNull; ExprState *expr_state = NULL; switch (qual->right_type) { case T_Param: expr_state = ExecInitExpr(((MulticornParamQual *) qual)->expr, (PlanState *) node); newqual = palloc0(sizeof(MulticornConstQual)); newqual->base.right_type = T_Const; newqual->base.varattno = qual->varattno; newqual->base.opname = qual->opname; newqual->base.isArray = qual->isArray; newqual->base.useOr = qual->useOr; #if PG_VERSION_NUM >= 100000 newqual->value = ExecEvalExpr(expr_state, econtext, &isNull); #else newqual->value = ExecEvalExpr(expr_state, econtext, &isNull, NULL); #endif newqual->base.typeoid = ((Param*) ((MulticornParamQual *) qual)->expr)->paramtype; newqual->isnull = isNull; break; case T_Const: newqual = (MulticornConstQual *) qual; break; default: break; } if (newqual != NULL) { PyObject *python_qual = qualdefToPython((MulticornConstQual *) newqual, state->cinfos); if (python_qual != NULL) { PyList_Append(p_quals, python_qual); Py_DECREF(python_qual); } } } /* Transform every object to a suitable python representation */ p_targets_set = valuesToPySet(state->target_list); foreach(lc, state->pathkeys) { MulticornDeparsedSortGroup *pathkey = (MulticornDeparsedSortGroup *) lfirst(lc); PyObject *python_sortkey = getSortKey(pathkey); PyList_Append(p_pathkeys, python_sortkey); Py_DECREF(python_sortkey); } { PyObject * args, * kwargs = PyDict_New(); if(PyList_Size(p_pathkeys) > 0){ PyDict_SetItemString(kwargs, "sortkeys", p_pathkeys); } if(es != NULL){ PyObject * verbose; if(es->verbose){ verbose = Py_True; } else { verbose = Py_False; } p_method = PyObject_GetAttrString(state->fdw_instance, "explain"); args = PyTuple_Pack(2, p_quals, p_targets_set); PyDict_SetItemString(kwargs, "verbose", verbose); errorCheck(); } else { p_method = PyObject_GetAttrString(state->fdw_instance, "execute"); errorCheck(); args = PyTuple_Pack(2, p_quals, p_targets_set); errorCheck(); } p_iterable = PyObject_Call(p_method, args, kwargs); errorCheck(); Py_DECREF(p_method); Py_DECREF(args); Py_DECREF(kwargs); } errorCheck(); if (p_iterable == Py_None){ state->p_iterator = p_iterable; } else { state->p_iterator = PyObject_GetIter(p_iterable); } Py_DECREF(p_quals); Py_DECREF(p_targets_set); Py_DECREF(p_pathkeys); Py_DECREF(p_iterable); errorCheck(); return state->p_iterator; } void pynumberToCString(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo) { PyObject *pTempStr; char *tempbuffer; Py_ssize_t strlength = 0; pTempStr = PyObject_Str(pyobject); PyString_AsStringAndSize(pTempStr, &tempbuffer, &strlength); appendBinaryStringInfo(buffer, tempbuffer, strlength); Py_DECREF(pTempStr); } void pyunicodeToCString(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo) { char *tempbuffer; Py_ssize_t strlength = 0; PyObject *pTempStr; pTempStr = PyUnicode_AsEncodedString(pyobject, getPythonEncodingName(), NULL); errorCheck(); PyBytes_AsStringAndSize(pTempStr, &tempbuffer, &strlength); appendBinaryStringInfoQuote(buffer, tempbuffer, strlength, cinfo->need_quote); Py_DECREF(pTempStr); } void pystringToCString(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo) { char *tempbuffer; Py_ssize_t strlength = 0; if (PyString_AsStringAndSize(pyobject, &tempbuffer, &strlength) < 0) { ereport(WARNING, (errmsg("An error occured while decoding the %s column", cinfo->attrname), errhint("You should maybe return unicode instead?"))); } appendBinaryStringInfoQuote(buffer, tempbuffer, strlength, cinfo->need_quote); } void pysequenceToCString(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo) { /* Its an array */ Py_ssize_t i, size = PySequence_Size(pyobject); PyObject *p_item; int previous_dims = cinfo->attndims, previous_needquote = cinfo->need_quote; if (cinfo->attndims == 0) { /* We are not supposed to be converted to an array. */ pyunknownToCstring(pyobject, buffer, cinfo); return; } appendStringInfoChar(buffer, '{'); /* We are an array, so we need to quote stuff */ cinfo->need_quote = true; cinfo->attndims = cinfo->attndims - 1; for (i = 0; i < size; i++) { p_item = PySequence_GetItem(pyobject, i); pyobjectToCString(p_item, buffer, cinfo); Py_DECREF(p_item); if (i != size - 1) { appendBinaryStringInfo(buffer, ", ", 2); } } appendStringInfoChar(buffer, '}'); cinfo->attndims = previous_dims; cinfo->need_quote = previous_needquote; } void pymappingToCString(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo) { PyObject *items = PyMapping_Items(pyobject); PyObject *current_tuple; Py_ssize_t i; Py_ssize_t size = PyList_Size(items); bool need_quote = cinfo->need_quote; cinfo->need_quote = true; for (i = 0; i < size; i++) { current_tuple = PySequence_GetItem(items, i); pyobjectToCString(PyTuple_GetItem(current_tuple, 0), buffer, cinfo); appendBinaryStringInfo(buffer, "=>", 2); pyobjectToCString(PyTuple_GetItem(current_tuple, 1), buffer, cinfo); if (i != size - 1) { appendBinaryStringInfo(buffer, ", ", 2); } Py_DECREF(current_tuple); } Py_DECREF(items); cinfo->need_quote = need_quote; } void pydateToCString(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo) { char *tempbuffer; Py_ssize_t strlength = 0; PyObject *formatted_date; formatted_date = PyObject_CallMethod(pyobject, "isoformat", "()"); PyString_AsStringAndSize(formatted_date, &tempbuffer, &strlength); appendBinaryStringInfo(buffer, tempbuffer, strlength); Py_DECREF(formatted_date); } void pyobjectToCString(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo) { if (pyobject == NULL || pyobject == Py_None) { return; } if (PyNumber_Check(pyobject)) { pynumberToCString(pyobject, buffer, cinfo); return; } if (PyUnicode_Check(pyobject)) { pyunicodeToCString(pyobject, buffer, cinfo); return; } if (PyBytes_Check(pyobject)) { pystringToCString(pyobject, buffer, cinfo); return; } if (PySequence_Check(pyobject)) { pysequenceToCString(pyobject, buffer, cinfo); return; } if (PyMapping_Check(pyobject)) { pymappingToCString(pyobject, buffer, cinfo); return; } PyDateTime_IMPORT; if (PyDate_Check(pyobject)) { pydateToCString(pyobject, buffer, cinfo); return; } pyunknownToCstring(pyobject, buffer, cinfo); } void pyunknownToCstring(PyObject *pyobject, StringInfo buffer, ConversionInfo * cinfo) { PyObject *pTempStr = PyObject_Str(pyobject); char *tempbuffer; Py_ssize_t strlength; PyString_AsStringAndSize(pTempStr, &tempbuffer, &strlength); errorCheck(); appendBinaryStringInfoQuote(buffer, tempbuffer, strlength, cinfo->need_quote); Py_DECREF(pTempStr); return; } void pythonDictToTuple(PyObject *p_value, TupleTableSlot *slot, ConversionInfo ** cinfos, StringInfo buffer) { int i; PyObject *p_object; Datum *values = slot->tts_values; bool *nulls = slot->tts_isnull; for (i = 0; i < slot->tts_tupleDescriptor->natts; i++) { char *key; Form_pg_attribute attr = TupleDescAttr(slot->tts_tupleDescriptor,i); AttrNumber cinfo_idx = attr->attnum - 1; if (cinfos[cinfo_idx] == NULL) { continue; } key = cinfos[cinfo_idx]->attrname; p_object = PyMapping_GetItemString(p_value, key); if (p_object != NULL && p_object != Py_None) { resetStringInfo(buffer); values[i] = pyobjectToDatum(p_object, buffer, cinfos[cinfo_idx]); if (buffer->data == NULL) { nulls[i] = true; } else { nulls[i] = false; } } else { /* "KeyError", doesnt matter. */ PyErr_Clear(); values[i] = (Datum) NULL; nulls[i] = true; } Py_XDECREF(p_object); } } void pythonSequenceToTuple(PyObject *p_value, TupleTableSlot *slot, ConversionInfo ** cinfos, StringInfo buffer) { int i, j; Datum *values = slot->tts_values; bool *nulls = slot->tts_isnull; for (i = 0, j = 0; i < slot->tts_tupleDescriptor->natts; i++) { PyObject *p_object; Form_pg_attribute attr = TupleDescAttr(slot->tts_tupleDescriptor,i); AttrNumber cinfo_idx = attr->attnum - 1; if (cinfos[cinfo_idx] == NULL) { continue; } p_object = PySequence_GetItem(p_value, j); if(p_object == NULL || p_object == Py_None){ nulls[i] = true; values[i] = 0; } else { resetStringInfo(buffer); values[i] = pyobjectToDatum(p_object, buffer, cinfos[cinfo_idx]); if (buffer->data == NULL) { nulls[i] = true; } else { nulls[i] = false; } } errorCheck(); Py_DECREF(p_object); j++; } } /* * Convert a python result (a sequence or a dictionary) to a tupletableslot. */ void pythonResultToTuple(PyObject *p_value, TupleTableSlot *slot, ConversionInfo ** cinfos, StringInfo buffer) { if (PySequence_Check(p_value)) { pythonSequenceToTuple(p_value, slot, cinfos, buffer); } else { if (PyMapping_Check(p_value)) { pythonDictToTuple(p_value, slot, cinfos, buffer); } else { elog(ERROR, "Cannot transform anything else than mappings and" "sequences to rows"); } } } Datum pyobjectToDatum(PyObject *object, StringInfo buffer, ConversionInfo * cinfo) { Datum value = 0; pyobjectToCString(object, buffer, cinfo); if (buffer->len >= 0) { if (cinfo->atttypoid == BYTEAOID || cinfo->atttypoid == TEXTOID || cinfo->atttypoid == VARCHAROID) { /* * Special case, since the value is already a byte string. */ value = PointerGetDatum(cstring_to_text_with_len(buffer->data, buffer->len)); } else { value = InputFunctionCall(cinfo->attinfunc, buffer->data, cinfo->attioparam, cinfo->atttypmod); } } return value; } PyObject * datumStringToPython(Datum datum, ConversionInfo * cinfo) { char *temp; ssize_t size; PyObject *result; temp = datum == 0 ? "?" : TextDatumGetCString(datum); size = strlen(temp); result = PyUnicode_Decode(temp, size, getPythonEncodingName(), NULL); return result; } PyObject * datumUnknownToPython(Datum datum, ConversionInfo * cinfo, Oid type) { char *temp; ssize_t size; PyObject *result; Oid outfuncoid; bool isvarlena; FmgrInfo *fmout = palloc0(sizeof(FmgrInfo)); getTypeOutputInfo(type, &outfuncoid, &isvarlena); fmgr_info(outfuncoid, fmout); temp = OutputFunctionCall(fmout, datum); size = strlen(temp); result = PyUnicode_Decode(temp, size, getPythonEncodingName(), NULL); pfree(fmout); return result; } PyObject * datumNumberToPython(Datum datum, ConversionInfo * cinfo) { ssize_t numvalue = (ssize_t) DatumGetNumeric(datum); char *tempvalue = (char *) DirectFunctionCall1(numeric_out, numvalue); PyObject *buffer = PyString_FromString(tempvalue), #if PY_MAJOR_VERSION >= 3 *value = PyFloat_FromString(buffer); #else *value = PyFloat_FromString(buffer, NULL); #endif Py_DECREF(buffer); return value; } PyObject * datumDateToPython(Datum datum, ConversionInfo * cinfo) { struct pg_tm *pg_tm_value = palloc(sizeof(struct pg_tm)); PyObject *result; fsec_t fsec; PyDateTime_IMPORT; datum = DirectFunctionCall1(date_timestamp, datum); timestamp2tm(DatumGetTimestamp(datum), NULL, pg_tm_value, &fsec, NULL, NULL); result = PyDate_FromDate(pg_tm_value->tm_year, pg_tm_value->tm_mon, pg_tm_value->tm_mday); pfree(pg_tm_value); return result; } PyObject * datumTimestampToPython(Datum datum, ConversionInfo * cinfo) { struct pg_tm *pg_tm_value = palloc(sizeof(struct pg_tm)); PyObject *result; fsec_t fsec; PyDateTime_IMPORT; timestamp2tm(DatumGetTimestamp(datum), NULL, pg_tm_value, &fsec, NULL, NULL); result = PyDateTime_FromDateAndTime(pg_tm_value->tm_year, pg_tm_value->tm_mon, pg_tm_value->tm_mday, pg_tm_value->tm_hour, pg_tm_value->tm_min, pg_tm_value->tm_sec, 0); pfree(pg_tm_value); return result; } PyObject * datumIntToPython(Datum datum, ConversionInfo * cinfo) { return PyLong_FromLong(DatumGetInt32(datum)); } PyObject * datumArrayToPython(Datum datum, Oid type, ConversionInfo * cinfo) { #if PG_VERSION_NUM >= 90500 ArrayIterator iterator = array_create_iterator(DatumGetArrayTypeP(datum), 0, NULL); # else ArrayIterator iterator = array_create_iterator(DatumGetArrayTypeP(datum), 0); # endif Datum elem = (Datum) NULL; bool isnull; PyObject *result = PyList_New(0), *pyitem; while (array_iterate(iterator, &elem, &isnull)) { if (isnull) { PyList_Append(result, Py_None); } else { HeapTuple tuple; Form_pg_type typeStruct; tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type)); if (!HeapTupleIsValid(tuple)) { elog(ERROR, "lookup failed for type %u", type); } typeStruct = (Form_pg_type) GETSTRUCT(tuple); pyitem = datumToPython(elem, typeStruct->typelem, cinfo); ReleaseSysCache(tuple); PyList_Append(result, pyitem); Py_DECREF(pyitem); } } return result; } PyObject * datumByteaToPython(Datum datum, ConversionInfo * cinfo) { text *txt = DatumGetByteaP(datum); char *str = txt == NULL ? "?" : VARDATA(txt); size_t size = VARSIZE(txt) - VARHDRSZ; #if PY_MAJOR_VERSION >= 3 return PyBytes_FromStringAndSize(str, size); #else return PyString_FromStringAndSize(str, size); #endif } PyObject * datumToPython(Datum datum, Oid type, ConversionInfo * cinfo) { HeapTuple tuple; Form_pg_type typeStruct; switch (type) { case BYTEAOID: return datumByteaToPython(datum, cinfo); case TEXTOID: case VARCHAROID: return datumStringToPython(datum, cinfo); case NUMERICOID: return datumNumberToPython(datum, cinfo); case DATEOID: return datumDateToPython(datum, cinfo); case TIMESTAMPOID: return datumTimestampToPython(datum, cinfo); case INT4OID: return datumIntToPython(datum, cinfo); default: /* Case for the array ? */ tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type)); if (!HeapTupleIsValid(tuple)) { elog(ERROR, "lookup failed for type %u", type); } typeStruct = (Form_pg_type) GETSTRUCT(tuple); ReleaseSysCache(tuple); if ((typeStruct->typelem != 0) && (typeStruct->typlen == -1)) { /* Its an array. */ return datumArrayToPython(datum, type, cinfo); } return datumUnknownToPython(datum, cinfo, type); } } /* * Call the path_keys method from the python implementation, and convert the * result to a list of "tuples" (list) of the form: * * - Bitmapset of attnums - Cost (integer) */ List * pathKeys(MulticornPlanState * state) { List *result = NULL; Py_ssize_t i; PyObject *fdw_instance = state->fdw_instance, *p_pathkeys; p_pathkeys = PyObject_CallMethod(fdw_instance, "get_path_keys", "()"); errorCheck(); for (i = 0; i < PySequence_Length(p_pathkeys); i++) { PyObject *p_item = PySequence_GetItem(p_pathkeys, i), *p_keys = PySequence_GetItem(p_item, 0), *p_cost = PySequence_GetItem(p_item, 1), *p_cost_long = PyNumber_Long(p_cost); double rows = PyLong_AsDouble(p_cost_long); ssize_t j; List *attnums = NULL; List *item = NULL; for (j = 0; j < PySequence_Length(p_keys); j++) { PyObject *p_key = PySequence_GetItem(p_keys, j); ssize_t k; /* Lookup the attribute number by its key. */ for (k = 0; k < state->numattrs; k++) { ConversionInfo *cinfo = state->cinfos[k]; if (cinfo == NULL) { continue; } if (p_key != Py_None && strcmp(cinfo->attrname, PyString_AsString(p_key)) == 0) { attnums = list_append_unique_int(attnums, cinfo->attnum); break; } } Py_DECREF(p_key); } item = lappend(item, attnums); item = lappend(item, makeConst(INT4OID, -1, InvalidOid, 4, rows, false, true)); result = lappend(result, item); Py_DECREF(p_keys); Py_DECREF(p_cost); Py_DECREF(p_cost_long); Py_DECREF(p_item); } Py_DECREF(p_pathkeys); return result; } /* * Call the can_sort method from the python implementation. We provide a deparsed * version of the requested fields to sort with all detail as needed (nulls, * collate...), and convert the result to a list of "tuples" (list) of the form: * * - Bitmapset of attnums * * representing the fields that the foreign data wrapper can be sort as * we requested. */ List * canSort(MulticornPlanState * state, List *deparsed) { List *result = NULL; ListCell *lc; Py_ssize_t i; PyObject *fdw_instance = state->fdw_instance, *p_pathkeys = PyList_New(0), *p_sortable; foreach(lc, deparsed) { MulticornDeparsedSortGroup *pathkey = (MulticornDeparsedSortGroup *) lfirst(lc); PyObject *python_sortkey = getSortKey(pathkey); PyList_Append(p_pathkeys, python_sortkey); Py_DECREF(python_sortkey); } p_sortable = PyObject_CallMethod(fdw_instance, "can_sort", "(O)", p_pathkeys); errorCheck(); for (i = 0; i < PySequence_Length(p_sortable); i++) { PyObject *p_key = PySequence_GetItem(p_sortable, i); MulticornDeparsedSortGroup *md = getDeparsedSortGroup(p_key); result = lappend(result, md); Py_DECREF(p_key); } Py_DECREF(p_pathkeys); Py_DECREF(p_sortable); return result; } PyObject * tupleTableSlotToPyObject(TupleTableSlot *slot, ConversionInfo ** cinfos) { PyObject *result = PyDict_New(); TupleDesc tupdesc = slot->tts_tupleDescriptor; int i; for (i = 0; i < tupdesc->natts; i++) { Form_pg_attribute attr = TupleDescAttr(tupdesc,i); bool isnull; Datum value; PyObject *item; AttrNumber cinfo_idx = attr->attnum - 1; if (attr->attisdropped || cinfos[cinfo_idx] == NULL) { continue; } value = slot_getattr(slot, i + 1, &isnull); if (isnull) { item = Py_None; Py_INCREF(item); } else { item = datumToPython(value, cinfos[cinfo_idx]->atttypoid, cinfos[cinfo_idx]); errorCheck(); } PyDict_SetItemString(result, cinfos[cinfo_idx]->attrname, item); Py_DECREF(item); } return result; } /* * Get the rowid column name */ char * getRowIdColumn(PyObject *fdw_instance) { PyObject *value = PyObject_GetAttrString(fdw_instance, "rowid_column"); char *result; errorCheck(); if (value == Py_None) { Py_DECREF(value); elog(ERROR, "This FDW does not support the writable API"); } result = PyString_AsString(value); Py_DECREF(value); return result; }
506ae814a15aba3119328b15851235633e2aa444
fa1a4c9c404b20cac10f537c419489ed8bb84ede
/mos-platform/nes-mmc3/bank.h
e1de7c7bc729d367bfaa42ef71bae2091a3f5df4
[ "LLVM-exception", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
llvm-mos/llvm-mos-sdk
cff8ec1780b5c79b63649ba567acb7cd271f0c32
18e0edd90648f67717b26f99559dae408eaa8b32
refs/heads/main
2023-08-31T15:47:28.907521
2023-08-29T16:40:59
2023-08-29T17:31:04
348,140,902
170
37
NOASSERTION
2023-09-14T19:46:55
2021-03-15T22:30:33
C
UTF-8
C
false
false
4,978
h
bank.h
// Copyright 2022 LLVM-MOS Project // Licensed under the Apache License, Version 2.0 with LLVM Exceptions. // See https://github.com/llvm-mos/llvm-mos-sdk/blob/main/LICENSE for license // information. // // Copyright 2019 Doug Fraker // Copyright 2018 Christopher Parker // // 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 _BANK_H_ #define _BANK_H_ #ifdef __cplusplus extern "C" { #endif // Contains functions to help with working with multiple PRG/CHR banks // For MMC3 code. // Switch to another bank and call this function. Note: Using banked_call to // call a second function from within another banked_call is safe. This function // works no matter which switchable bank the function is in. __attribute__((leaf, callback(2))) void banked_call(char bankId, void (*method)(void)); // Same as banked_call, but assumes the bank is 8000/c000. __attribute__((leaf, callback(2))) void banked_call_8000(char bankId, void (*method)(void)); // Same as banked_call, but assumes the bank is a000. __attribute__((leaf, callback(2))) void banked_call_a000(char bankId, void (*method)(void)); // Sets the bank at the address with the given high byte. __attribute__((leaf)) void set_prg_bank(char bank_id, char addr_hi); // Gets the bank at the address with the given high byte. __attribute__((leaf)) char get_prg_bank(char addr_hi); // Switch to the given bank (at $8000-9fff or $c000-dfff). Your prior bank is // not saved. // bank_id: The bank to switch to. __attribute__((leaf)) void set_prg_8000(char bank_id); // Get the current PRG bank at $8000-9fff (or $c000-dfff). // returns: The current bank. char get_prg_8000(void); // Switch to the given bank (at $a000-bfff). Your prior bank is not saved. // bank_id: The bank to switch to. __attribute__((leaf)) void set_prg_a000(char bank_id); // Get the current PRG bank at $a000-bfff. // returns: The current bank. char get_prg_a000(void); // Changes a portion of the tilesets. If interrupted, these may have no effect. // All but the low three bits of reg must be zero. __attribute__((leaf)) void set_chr_bank(char reg, char bank_id); // Same as set_chr_bank, but retries if interrupted. __attribute__((leaf)) void set_chr_bank_retry(char bank, char bank_id); // Same as the above, but hard-code the bank. void set_chr_mode_0(char chr_id); void set_chr_mode_1(char chr_id); void set_chr_mode_2(char chr_id); void set_chr_mode_3(char chr_id); void set_chr_mode_4(char chr_id); void set_chr_mode_5(char chr_id); #define MIRROR_VERTICAL 0 #define MIRROR_HORIZONTAL 1 // Set the current mirroring mode. Your options are // MIRROR_HORIZONTAL, and MIRROR_VERTICAL. __attribute__((leaf)) void set_mirroring(char mirroring); #define PRG_MODE_0 0 #define PRG_MODE_1 0x40 // Set the PRG ROM bank mode. Takes effect after the next PRG or CHR bank // switch. void set_prg_mode(char mode); #define CHR_A12_STRAIGHT 0 #define CHR_A12_INVERT 0x80 // Set whether CHR A12 is inverted. Takes effect after the next PRG or CHR bank // switch. void set_chr_a12_inversion(char mode); #define WRAM_OFF 0x40 #define WRAM_ON 0x80 #define WRAM_READ_ONLY 0xC0 // Set the WRAM mode. Your options are // WRAM_OFF, WRAM_ON, and WRAM_READ_ONLY. // May not work in some emulators. __attribute__((leaf)) void set_wram_mode(char mode); // Turns off MMC3 irqs, and changes the array pointer // to point to a default 0xff __attribute__((leaf)) void disable_irq(void); // This points an array to the IRQ system // Also turns ON the system __attribute__((leaf)) void set_irq_ptr(const void *address); // Check if it's safe to write to the irq array // returns 0xff if done, zero if not done // if the irq pointer is pointing to 0xff it is // safe to edit. __attribute__((leaf)) char is_irq_done(void); #ifdef __cplusplus } #endif #endif // _BANK_H_
668491efa7d3f725b4c75508bd4ecdc726035913
bb7a80648bf830c2fb813cdb335032142cbee06d
/mod/mpp/3559a/inc/hisisdk/mpi_avs.h
74e5c6054755b0c8fe398b0182891aa00047a8f3
[]
no_license
openhisilicon/HIVIEW
44574a29da60e3bb400c7ce97c722dfc9f2959e6
60bbfa5cb66cc82f0cdc0bba1242dbc9491b0f37
refs/heads/master
2023-09-01T01:42:19.069724
2023-08-31T09:57:39
2023-08-31T09:57:39
189,036,134
336
121
null
2023-01-07T14:10:22
2019-05-28T13:41:40
C
UTF-8
C
false
false
1,917
h
mpi_avs.h
/* * Copyright (C) Hisilicon Technologies Co., Ltd. 2016-2019. All rights reserved. * Description: * Author: Hisilicon multimedia software group * Create: 2016-11-11 */ #ifndef __MPI_AVS_H__ #define __MPI_AVS_H__ #include "hi_comm_avs.h" #ifdef __cplusplus #if __cplusplus extern "C" { #endif #endif /* __cplusplus */ HI_S32 HI_MPI_AVS_CreateGrp(AVS_GRP AVSGrp, const AVS_GRP_ATTR_S *pstGrpAttr); HI_S32 HI_MPI_AVS_DestroyGrp(AVS_GRP AVSGrp); HI_S32 HI_MPI_AVS_StartGrp(AVS_GRP AVSGrp); HI_S32 HI_MPI_AVS_StopGrp(AVS_GRP AVSGrp); HI_S32 HI_MPI_AVS_ResetGrp(AVS_GRP AVSGrp); HI_S32 HI_MPI_AVS_CloseFd(HI_VOID); HI_S32 HI_MPI_AVS_GetGrpAttr(AVS_GRP AVSGrp, AVS_GRP_ATTR_S *pstGrpAttr); HI_S32 HI_MPI_AVS_SetGrpAttr(AVS_GRP AVSGrp, const AVS_GRP_ATTR_S *pstGrpAttr); HI_S32 HI_MPI_AVS_SendPipeFrame(AVS_GRP AVSGrp, AVS_PIPE AVSPipe, const VIDEO_FRAME_INFO_S *pstVideoFrame, HI_S32 s32MilliSec); HI_S32 HI_MPI_AVS_GetPipeFrame(AVS_GRP AVSGrp, AVS_PIPE AVSPipe, VIDEO_FRAME_INFO_S *pstVideoFrame); HI_S32 HI_MPI_AVS_ReleasePipeFrame(AVS_GRP AVSGrp, AVS_PIPE AVSPipe, const VIDEO_FRAME_INFO_S *pstVideoFrame); HI_S32 HI_MPI_AVS_SetChnAttr(AVS_GRP AVSGrp, AVS_CHN AVSChn, const AVS_CHN_ATTR_S *pstChnAttr); HI_S32 HI_MPI_AVS_GetChnAttr(AVS_GRP AVSGrp, AVS_CHN AVSChn, AVS_CHN_ATTR_S *pstChnAttr); HI_S32 HI_MPI_AVS_EnableChn(AVS_GRP AVSGrp, AVS_CHN AVSChn); HI_S32 HI_MPI_AVS_DisableChn(AVS_GRP AVSGrp, AVS_CHN AVSChn); HI_S32 HI_MPI_AVS_GetChnFrame(AVS_GRP AVSGrp, AVS_CHN AVSChn, VIDEO_FRAME_INFO_S *pstVideoFrame, HI_S32 s32MilliSec); HI_S32 HI_MPI_AVS_ReleaseChnFrame(AVS_GRP AVSGrp, AVS_CHN AVSChn, const VIDEO_FRAME_INFO_S *pstVideoFrame); HI_S32 HI_MPI_AVS_GetModParam(AVS_MOD_PARAM_S *pstModParam); HI_S32 HI_MPI_AVS_SetModParam(const AVS_MOD_PARAM_S *pstModParam); #ifdef __cplusplus #if __cplusplus } #endif #endif /* __cplusplus */ #endif /* __MPI_AVS_H__ */
84a35f58d5070187cf97758c390709e6d8352da9
7be8e3636bf08ebdc6662879dc5afec548705537
/ios/Pods/Headers/Private/Flipper-Folly/folly/synchronization/AtomicUtil.h
98110d18bb8ca4c542c773a9693e450a001777a9
[ "MIT" ]
permissive
rdhox/react-native-smooth-picker
3c7384f1fed0e37f076361cce96071d01b70e209
ae9316c49512f7ed9824c5a3ad50cdf5e80fffa9
refs/heads/master
2023-01-08T16:59:40.709147
2021-07-03T14:13:21
2021-07-03T14:13:21
160,224,312
230
31
MIT
2023-01-06T01:46:04
2018-12-03T16:54:10
TypeScript
UTF-8
C
false
false
63
h
AtomicUtil.h
../../../../../Flipper-Folly/folly/synchronization/AtomicUtil.h
476a34ed8c1194dfa2ee21f67a3f4e30ab9a98d4
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/wayland-protocols/gtk/gsk/vulkan/gskvulkanrenderpass.c
a6b427a63257eb80d29d180e483d2f95937a82ae
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "LGPL-2.0-only", "LGPL-2.1-only" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C
false
false
89,867
c
gskvulkanrenderpass.c
#include "config.h" #include "gskvulkanrenderpassprivate.h" #include "gskdebugprivate.h" #include "gskprofilerprivate.h" #include "gskrendernodeprivate.h" #include "gskrenderer.h" #include "gskrendererprivate.h" #include "gskroundedrectprivate.h" #include "gsktransform.h" #include "gskvulkanblendmodepipelineprivate.h" #include "gskvulkanblurpipelineprivate.h" #include "gskvulkanborderpipelineprivate.h" #include "gskvulkanboxshadowpipelineprivate.h" #include "gskvulkanclipprivate.h" #include "gskvulkancolorpipelineprivate.h" #include "gskvulkancolortextpipelineprivate.h" #include "gskvulkancrossfadepipelineprivate.h" #include "gskvulkaneffectpipelineprivate.h" #include "gskvulkanlineargradientpipelineprivate.h" #include "gskvulkantextpipelineprivate.h" #include "gskvulkantexturepipelineprivate.h" #include "gskvulkanimageprivate.h" #include "gskvulkanpushconstantsprivate.h" #include "gskvulkanrendererprivate.h" #include "gskprivate.h" #define ORTHO_NEAR_PLANE -10000 #define ORTHO_FAR_PLANE 10000 typedef union _GskVulkanOp GskVulkanOp; typedef struct _GskVulkanOpRender GskVulkanOpRender; typedef struct _GskVulkanOpText GskVulkanOpText; typedef struct _GskVulkanOpPushConstants GskVulkanOpPushConstants; typedef enum { /* GskVulkanOpRender */ GSK_VULKAN_OP_FALLBACK, GSK_VULKAN_OP_FALLBACK_CLIP, GSK_VULKAN_OP_FALLBACK_ROUNDED_CLIP, GSK_VULKAN_OP_TEXTURE, GSK_VULKAN_OP_COLOR, GSK_VULKAN_OP_LINEAR_GRADIENT, GSK_VULKAN_OP_OPACITY, GSK_VULKAN_OP_BLUR, GSK_VULKAN_OP_COLOR_MATRIX, GSK_VULKAN_OP_BORDER, GSK_VULKAN_OP_INSET_SHADOW, GSK_VULKAN_OP_OUTSET_SHADOW, GSK_VULKAN_OP_REPEAT, GSK_VULKAN_OP_CROSS_FADE, GSK_VULKAN_OP_BLEND_MODE, /* GskVulkanOpText */ GSK_VULKAN_OP_TEXT, GSK_VULKAN_OP_COLOR_TEXT, /* GskVulkanOpPushConstants */ GSK_VULKAN_OP_PUSH_VERTEX_CONSTANTS, } GskVulkanOpType; /* render ops with 0, 1 or 2 sources */ struct _GskVulkanOpRender { GskVulkanOpType type; GskRenderNode *node; /* node that's the source of this op */ GskVulkanPipeline *pipeline; /* pipeline to use */ GskRoundedRect clip; /* clip rect (or random memory if not relevant) */ GskVulkanImage *source; /* source image to render */ GskVulkanImage *source2; /* second source image to render (if relevant) */ gsize vertex_offset; /* offset into vertex buffer */ gsize vertex_count; /* number of vertices */ gsize descriptor_set_index; /* index into descriptor sets array for the right descriptor set to bind */ gsize descriptor_set_index2; /* descriptor index for the second source (if relevant) */ graphene_rect_t source_rect; /* area that source maps to */ graphene_rect_t source2_rect; /* area that source2 maps to */ }; struct _GskVulkanOpText { GskVulkanOpType type; GskRenderNode *node; /* node that's the source of this op */ GskVulkanPipeline *pipeline; /* pipeline to use */ GskRoundedRect clip; /* clip rect (or random memory if not relevant) */ GskVulkanImage *source; /* source image to render */ gsize vertex_offset; /* offset into vertex buffer */ gsize vertex_count; /* number of vertices */ gsize descriptor_set_index; /* index into descriptor sets array for the right descriptor set to bind */ guint texture_index; /* index of the texture in the glyph cache */ guint start_glyph; /* the first glyph in nodes glyphstring that we render */ guint num_glyphs; /* number of *non-empty* glyphs (== instances) we render */ float scale; }; struct _GskVulkanOpPushConstants { GskVulkanOpType type; GskRenderNode *node; /* node that's the source of this op */ GskVulkanPushConstants constants; /* new constants to push */ }; union _GskVulkanOp { GskVulkanOpType type; GskVulkanOpRender render; GskVulkanOpText text; GskVulkanOpPushConstants constants; }; struct _GskVulkanRenderPass { GdkVulkanContext *vulkan; GArray *render_ops; GskVulkanImage *target; int scale_factor; graphene_rect_t viewport; cairo_region_t *clip; graphene_matrix_t mv; graphene_matrix_t p; VkRenderPass render_pass; VkSemaphore signal_semaphore; GArray *wait_semaphores; GskVulkanBuffer *vertex_data; GQuark fallback_pixels; GQuark texture_pixels; }; GskVulkanRenderPass * gsk_vulkan_render_pass_new (GdkVulkanContext *context, GskVulkanImage *target, int scale_factor, graphene_matrix_t *mv, graphene_rect_t *viewport, cairo_region_t *clip, VkSemaphore signal_semaphore) { GskVulkanRenderPass *self; VkImageLayout final_layout; self = g_slice_new0 (GskVulkanRenderPass); self->vulkan = g_object_ref (context); self->render_ops = g_array_new (FALSE, FALSE, sizeof (GskVulkanOp)); self->target = g_object_ref (target); self->scale_factor = scale_factor; self->clip = cairo_region_copy (clip); self->viewport = *viewport; self->mv = *mv; graphene_matrix_init_ortho (&self->p, viewport->origin.x, viewport->origin.x + viewport->size.width, viewport->origin.y, viewport->origin.y + viewport->size.height, ORTHO_NEAR_PLANE, ORTHO_FAR_PLANE); if (signal_semaphore != VK_NULL_HANDLE) // this is a dependent pass final_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; else final_layout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; GSK_VK_CHECK (vkCreateRenderPass, gdk_vulkan_context_get_device (self->vulkan), &(VkRenderPassCreateInfo) { .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, .attachmentCount = 1, .pAttachments = (VkAttachmentDescription[]) { { .format = gdk_vulkan_context_get_image_format (self->vulkan), .samples = VK_SAMPLE_COUNT_1_BIT, .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, .storeOp = VK_ATTACHMENT_STORE_OP_STORE, .initialLayout = VK_IMAGE_LAYOUT_GENERAL, .finalLayout = final_layout } }, .subpassCount = 1, .pSubpasses = (VkSubpassDescription []) { { .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, .inputAttachmentCount = 0, .colorAttachmentCount = 1, .pColorAttachments = (VkAttachmentReference []) { { .attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL } }, .pResolveAttachments = (VkAttachmentReference []) { { .attachment = VK_ATTACHMENT_UNUSED, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL } }, .pDepthStencilAttachment = NULL, } }, .dependencyCount = 0 }, NULL, &self->render_pass); self->signal_semaphore = signal_semaphore; self->wait_semaphores = g_array_new (FALSE, FALSE, sizeof (VkSemaphore)); self->vertex_data = NULL; #ifdef G_ENABLE_DEBUG self->fallback_pixels = g_quark_from_static_string ("fallback-pixels"); self->texture_pixels = g_quark_from_static_string ("texture-pixels"); #endif return self; } void gsk_vulkan_render_pass_free (GskVulkanRenderPass *self) { g_array_unref (self->render_ops); g_object_unref (self->vulkan); g_object_unref (self->target); cairo_region_destroy (self->clip); vkDestroyRenderPass (gdk_vulkan_context_get_device (self->vulkan), self->render_pass, NULL); if (self->vertex_data) gsk_vulkan_buffer_free (self->vertex_data); if (self->signal_semaphore != VK_NULL_HANDLE) vkDestroySemaphore (gdk_vulkan_context_get_device (self->vulkan), self->signal_semaphore, NULL); g_array_unref (self->wait_semaphores); g_slice_free (GskVulkanRenderPass, self); } #define FALLBACK(...) G_STMT_START { \ GSK_RENDERER_NOTE (gsk_vulkan_render_get_renderer (render), FALLBACK, g_message (__VA_ARGS__)); \ goto fallback; \ }G_STMT_END static void gsk_vulkan_render_pass_add_node (GskVulkanRenderPass *self, GskVulkanRender *render, const GskVulkanPushConstants *constants, GskRenderNode *node) { GskVulkanOp op = { .render.node = node }; GskVulkanPipelineType pipeline_type; switch (gsk_render_node_get_node_type (node)) { case GSK_NOT_A_RENDER_NODE: g_assert_not_reached (); return; case GSK_GL_SHADER_NODE: case GSK_SHADOW_NODE: case GSK_RADIAL_GRADIENT_NODE: case GSK_REPEATING_RADIAL_GRADIENT_NODE: case GSK_CONIC_GRADIENT_NODE: default: FALLBACK ("Unsupported node '%s'", g_type_name_from_instance ((GTypeInstance *) node)); case GSK_REPEAT_NODE: if (gsk_vulkan_clip_contains_rect (&constants->clip, &node->bounds)) pipeline_type = GSK_VULKAN_PIPELINE_TEXTURE; else if (constants->clip.type == GSK_VULKAN_CLIP_RECT) pipeline_type = GSK_VULKAN_PIPELINE_TEXTURE_CLIP; else if (constants->clip.type == GSK_VULKAN_CLIP_ROUNDED_CIRCULAR) pipeline_type = GSK_VULKAN_PIPELINE_TEXTURE_CLIP_ROUNDED; else FALLBACK ("Repeat nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_REPEAT; op.render.pipeline = gsk_vulkan_render_get_pipeline (render, pipeline_type); g_array_append_val (self->render_ops, op); return; case GSK_BLEND_NODE: if (gsk_vulkan_clip_contains_rect (&constants->clip, &node->bounds)) pipeline_type = GSK_VULKAN_PIPELINE_BLEND_MODE; else if (constants->clip.type == GSK_VULKAN_CLIP_RECT) pipeline_type = GSK_VULKAN_PIPELINE_BLEND_MODE_CLIP; else if (constants->clip.type == GSK_VULKAN_CLIP_ROUNDED_CIRCULAR) pipeline_type = GSK_VULKAN_PIPELINE_BLEND_MODE_CLIP_ROUNDED; else FALLBACK ("Blend nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_BLEND_MODE; op.render.pipeline = gsk_vulkan_render_get_pipeline (render, pipeline_type); g_array_append_val (self->render_ops, op); return; case GSK_CROSS_FADE_NODE: if (gsk_vulkan_clip_contains_rect (&constants->clip, &node->bounds)) pipeline_type = GSK_VULKAN_PIPELINE_CROSS_FADE; else if (constants->clip.type == GSK_VULKAN_CLIP_RECT) pipeline_type = GSK_VULKAN_PIPELINE_CROSS_FADE_CLIP; else if (constants->clip.type == GSK_VULKAN_CLIP_ROUNDED_CIRCULAR) pipeline_type = GSK_VULKAN_PIPELINE_CROSS_FADE_CLIP_ROUNDED; else FALLBACK ("Cross fade nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_CROSS_FADE; op.render.pipeline = gsk_vulkan_render_get_pipeline (render, pipeline_type); g_array_append_val (self->render_ops, op); return; case GSK_INSET_SHADOW_NODE: if (gsk_inset_shadow_node_get_blur_radius (node) > 0) FALLBACK ("Blur support not implemented for inset shadows"); else if (gsk_vulkan_clip_contains_rect (&constants->clip, &node->bounds)) pipeline_type = GSK_VULKAN_PIPELINE_INSET_SHADOW; else if (constants->clip.type == GSK_VULKAN_CLIP_RECT) pipeline_type = GSK_VULKAN_PIPELINE_INSET_SHADOW_CLIP; else if (constants->clip.type == GSK_VULKAN_CLIP_ROUNDED_CIRCULAR) pipeline_type = GSK_VULKAN_PIPELINE_INSET_SHADOW_CLIP_ROUNDED; else FALLBACK ("Inset shadow nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_INSET_SHADOW; op.render.pipeline = gsk_vulkan_render_get_pipeline (render, pipeline_type); g_array_append_val (self->render_ops, op); return; case GSK_OUTSET_SHADOW_NODE: if (gsk_outset_shadow_node_get_blur_radius (node) > 0) FALLBACK ("Blur support not implemented for outset shadows"); else if (gsk_vulkan_clip_contains_rect (&constants->clip, &node->bounds)) pipeline_type = GSK_VULKAN_PIPELINE_OUTSET_SHADOW; else if (constants->clip.type == GSK_VULKAN_CLIP_RECT) pipeline_type = GSK_VULKAN_PIPELINE_OUTSET_SHADOW_CLIP; else if (constants->clip.type == GSK_VULKAN_CLIP_ROUNDED_CIRCULAR) pipeline_type = GSK_VULKAN_PIPELINE_OUTSET_SHADOW_CLIP_ROUNDED; else FALLBACK ("Outset shadow nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_OUTSET_SHADOW; op.render.pipeline = gsk_vulkan_render_get_pipeline (render, pipeline_type); g_array_append_val (self->render_ops, op); return; case GSK_CAIRO_NODE: if (gsk_cairo_node_get_surface (node) == NULL) return; /* We're using recording surfaces, so drawing them to an image * surface and uploading them is the right thing. * But that's exactly what the fallback code does. */ goto fallback; case GSK_TEXT_NODE: { const PangoFont *font = gsk_text_node_get_font (node); const PangoGlyphInfo *glyphs = gsk_text_node_get_glyphs (node, NULL); guint num_glyphs = gsk_text_node_get_num_glyphs (node); gboolean has_color_glyphs = gsk_text_node_has_color_glyphs (node); int i; guint count; guint texture_index; int x_position; GskVulkanRenderer *renderer = GSK_VULKAN_RENDERER (gsk_vulkan_render_get_renderer (render)); if (has_color_glyphs) { if (gsk_vulkan_clip_contains_rect (&constants->clip, &node->bounds)) pipeline_type = GSK_VULKAN_PIPELINE_COLOR_TEXT; else if (constants->clip.type == GSK_VULKAN_CLIP_RECT) pipeline_type = GSK_VULKAN_PIPELINE_COLOR_TEXT_CLIP; else if (constants->clip.type == GSK_VULKAN_CLIP_ROUNDED_CIRCULAR) pipeline_type = GSK_VULKAN_PIPELINE_COLOR_TEXT_CLIP_ROUNDED; else FALLBACK ("Text nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_COLOR_TEXT; } else { if (gsk_vulkan_clip_contains_rect (&constants->clip, &node->bounds)) pipeline_type = GSK_VULKAN_PIPELINE_TEXT; else if (constants->clip.type == GSK_VULKAN_CLIP_RECT) pipeline_type = GSK_VULKAN_PIPELINE_TEXT_CLIP; else if (constants->clip.type == GSK_VULKAN_CLIP_ROUNDED_CIRCULAR) pipeline_type = GSK_VULKAN_PIPELINE_TEXT_CLIP_ROUNDED; else FALLBACK ("Text nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_TEXT; } op.text.pipeline = gsk_vulkan_render_get_pipeline (render, pipeline_type); op.text.start_glyph = 0; op.text.texture_index = G_MAXUINT; op.text.scale = self->scale_factor; x_position = 0; for (i = 0, count = 0; i < num_glyphs; i++) { const PangoGlyphInfo *gi = &glyphs[i]; texture_index = gsk_vulkan_renderer_cache_glyph (renderer, (PangoFont *)font, gi->glyph, x_position + gi->geometry.x_offset, gi->geometry.y_offset, op.text.scale); if (op.text.texture_index == G_MAXUINT) op.text.texture_index = texture_index; if (texture_index != op.text.texture_index) { op.text.num_glyphs = count; g_array_append_val (self->render_ops, op); count = 1; op.text.start_glyph = i; op.text.texture_index = texture_index; } else count++; x_position += gi->geometry.width; } if (op.text.texture_index != G_MAXUINT && count != 0) { op.text.num_glyphs = count; g_array_append_val (self->render_ops, op); } return; } case GSK_TEXTURE_NODE: if (gsk_vulkan_clip_contains_rect (&constants->clip, &node->bounds)) pipeline_type = GSK_VULKAN_PIPELINE_TEXTURE; else if (constants->clip.type == GSK_VULKAN_CLIP_RECT) pipeline_type = GSK_VULKAN_PIPELINE_TEXTURE_CLIP; else if (constants->clip.type == GSK_VULKAN_CLIP_ROUNDED_CIRCULAR) pipeline_type = GSK_VULKAN_PIPELINE_TEXTURE_CLIP_ROUNDED; else FALLBACK ("Texture nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_TEXTURE; op.render.pipeline = gsk_vulkan_render_get_pipeline (render, pipeline_type); g_array_append_val (self->render_ops, op); return; case GSK_COLOR_NODE: if (gsk_vulkan_clip_contains_rect (&constants->clip, &node->bounds)) pipeline_type = GSK_VULKAN_PIPELINE_COLOR; else if (constants->clip.type == GSK_VULKAN_CLIP_RECT) pipeline_type = GSK_VULKAN_PIPELINE_COLOR_CLIP; else if (constants->clip.type == GSK_VULKAN_CLIP_ROUNDED_CIRCULAR) pipeline_type = GSK_VULKAN_PIPELINE_COLOR_CLIP_ROUNDED; else FALLBACK ("Color nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_COLOR; op.render.pipeline = gsk_vulkan_render_get_pipeline (render, pipeline_type); g_array_append_val (self->render_ops, op); return; case GSK_LINEAR_GRADIENT_NODE: case GSK_REPEATING_LINEAR_GRADIENT_NODE: if (gsk_linear_gradient_node_get_n_color_stops (node) > GSK_VULKAN_LINEAR_GRADIENT_PIPELINE_MAX_COLOR_STOPS) FALLBACK ("Linear gradient with %zu color stops, hardcoded limit is %u", gsk_linear_gradient_node_get_n_color_stops (node), GSK_VULKAN_LINEAR_GRADIENT_PIPELINE_MAX_COLOR_STOPS); if (gsk_vulkan_clip_contains_rect (&constants->clip, &node->bounds)) pipeline_type = GSK_VULKAN_PIPELINE_LINEAR_GRADIENT; else if (constants->clip.type == GSK_VULKAN_CLIP_RECT) pipeline_type = GSK_VULKAN_PIPELINE_LINEAR_GRADIENT_CLIP; else if (constants->clip.type == GSK_VULKAN_CLIP_ROUNDED_CIRCULAR) pipeline_type = GSK_VULKAN_PIPELINE_LINEAR_GRADIENT_CLIP_ROUNDED; else FALLBACK ("Linear gradient nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_LINEAR_GRADIENT; op.render.pipeline = gsk_vulkan_render_get_pipeline (render, pipeline_type); g_array_append_val (self->render_ops, op); return; case GSK_OPACITY_NODE: if (gsk_vulkan_clip_contains_rect (&constants->clip, &node->bounds)) pipeline_type = GSK_VULKAN_PIPELINE_COLOR_MATRIX; else if (constants->clip.type == GSK_VULKAN_CLIP_RECT) pipeline_type = GSK_VULKAN_PIPELINE_COLOR_MATRIX_CLIP; else if (constants->clip.type == GSK_VULKAN_CLIP_ROUNDED_CIRCULAR) pipeline_type = GSK_VULKAN_PIPELINE_COLOR_MATRIX_CLIP_ROUNDED; else FALLBACK ("Opacity nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_OPACITY; op.render.pipeline = gsk_vulkan_render_get_pipeline (render, pipeline_type); g_array_append_val (self->render_ops, op); return; case GSK_BLUR_NODE: if (gsk_vulkan_clip_contains_rect (&constants->clip, &node->bounds)) pipeline_type = GSK_VULKAN_PIPELINE_BLUR; else if (constants->clip.type == GSK_VULKAN_CLIP_RECT) pipeline_type = GSK_VULKAN_PIPELINE_BLUR_CLIP; else if (constants->clip.type == GSK_VULKAN_CLIP_ROUNDED_CIRCULAR) pipeline_type = GSK_VULKAN_PIPELINE_BLUR_CLIP_ROUNDED; else FALLBACK ("Blur nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_BLUR; op.render.pipeline = gsk_vulkan_render_get_pipeline (render, pipeline_type); g_array_append_val (self->render_ops, op); return; case GSK_COLOR_MATRIX_NODE: if (gsk_vulkan_clip_contains_rect (&constants->clip, &node->bounds)) pipeline_type = GSK_VULKAN_PIPELINE_COLOR_MATRIX; else if (constants->clip.type == GSK_VULKAN_CLIP_RECT) pipeline_type = GSK_VULKAN_PIPELINE_COLOR_MATRIX_CLIP; else if (constants->clip.type == GSK_VULKAN_CLIP_ROUNDED_CIRCULAR) pipeline_type = GSK_VULKAN_PIPELINE_COLOR_MATRIX_CLIP_ROUNDED; else FALLBACK ("Color matrix nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_COLOR_MATRIX; op.render.pipeline = gsk_vulkan_render_get_pipeline (render, pipeline_type); g_array_append_val (self->render_ops, op); return; case GSK_BORDER_NODE: if (gsk_vulkan_clip_contains_rect (&constants->clip, &node->bounds)) pipeline_type = GSK_VULKAN_PIPELINE_BORDER; else if (constants->clip.type == GSK_VULKAN_CLIP_RECT) pipeline_type = GSK_VULKAN_PIPELINE_BORDER_CLIP; else if (constants->clip.type == GSK_VULKAN_CLIP_ROUNDED_CIRCULAR) pipeline_type = GSK_VULKAN_PIPELINE_BORDER_CLIP_ROUNDED; else FALLBACK ("Border nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_BORDER; op.render.pipeline = gsk_vulkan_render_get_pipeline (render, pipeline_type); g_array_append_val (self->render_ops, op); return; case GSK_CONTAINER_NODE: { guint i; for (i = 0; i < gsk_container_node_get_n_children (node); i++) { gsk_vulkan_render_pass_add_node (self, render, constants, gsk_container_node_get_child (node, i)); } } return; case GSK_DEBUG_NODE: gsk_vulkan_render_pass_add_node (self, render, constants, gsk_debug_node_get_child (node)); return; case GSK_TRANSFORM_NODE: { graphene_matrix_t transform, mv; GskRenderNode *child; #if 0 if (!gsk_vulkan_clip_contains_rect (clip, &node->bounds)) FALLBACK ("Transform nodes can't deal with clip type %u\n", clip->type); #endif child = gsk_transform_node_get_child (node); gsk_transform_to_matrix (gsk_transform_node_get_transform (node), &transform); graphene_matrix_init_from_matrix (&mv, &self->mv); graphene_matrix_multiply (&transform, &mv, &self->mv); if (!gsk_vulkan_push_constants_transform (&op.constants.constants, constants, gsk_transform_node_get_transform (node), &child->bounds)) FALLBACK ("Transform nodes can't deal with clip type %u", constants->clip.type); op.type = GSK_VULKAN_OP_PUSH_VERTEX_CONSTANTS; g_array_append_val (self->render_ops, op); gsk_vulkan_render_pass_add_node (self, render, &op.constants.constants, child); gsk_vulkan_push_constants_init_copy (&op.constants.constants, constants); graphene_matrix_init_from_matrix (&self->mv, &mv); g_array_append_val (self->render_ops, op); } return; case GSK_CLIP_NODE: { if (!gsk_vulkan_push_constants_intersect_rect (&op.constants.constants, constants, gsk_clip_node_get_clip (node))) FALLBACK ("Failed to find intersection between clip of type %u and rectangle", constants->clip.type); if (op.constants.constants.clip.type == GSK_VULKAN_CLIP_ALL_CLIPPED) return; op.type = GSK_VULKAN_OP_PUSH_VERTEX_CONSTANTS; g_array_append_val (self->render_ops, op); gsk_vulkan_render_pass_add_node (self, render, &op.constants.constants, gsk_clip_node_get_child (node)); gsk_vulkan_push_constants_init_copy (&op.constants.constants, constants); g_array_append_val (self->render_ops, op); } return; case GSK_ROUNDED_CLIP_NODE: { if (!gsk_vulkan_push_constants_intersect_rounded (&op.constants.constants, constants, gsk_rounded_clip_node_get_clip (node))) FALLBACK ("Failed to find intersection between clip of type %u and rounded rectangle", constants->clip.type); if (op.constants.constants.clip.type == GSK_VULKAN_CLIP_ALL_CLIPPED) return; op.type = GSK_VULKAN_OP_PUSH_VERTEX_CONSTANTS; g_array_append_val (self->render_ops, op); gsk_vulkan_render_pass_add_node (self, render, &op.constants.constants, gsk_rounded_clip_node_get_child (node)); gsk_vulkan_push_constants_init_copy (&op.constants.constants, constants); g_array_append_val (self->render_ops, op); } return; } g_assert_not_reached (); return; fallback: switch (constants->clip.type) { case GSK_VULKAN_CLIP_NONE: op.type = GSK_VULKAN_OP_FALLBACK; break; case GSK_VULKAN_CLIP_RECT: op.type = GSK_VULKAN_OP_FALLBACK_CLIP; gsk_rounded_rect_init_copy (&op.render.clip, &constants->clip.rect); break; case GSK_VULKAN_CLIP_ROUNDED_CIRCULAR: case GSK_VULKAN_CLIP_ROUNDED: op.type = GSK_VULKAN_OP_FALLBACK_ROUNDED_CLIP; gsk_rounded_rect_init_copy (&op.render.clip, &constants->clip.rect); break; case GSK_VULKAN_CLIP_ALL_CLIPPED: default: g_assert_not_reached (); return; } op.render.pipeline = gsk_vulkan_render_get_pipeline (render, GSK_VULKAN_PIPELINE_TEXTURE); g_array_append_val (self->render_ops, op); } #undef FALLBACK void gsk_vulkan_render_pass_add (GskVulkanRenderPass *self, GskVulkanRender *render, GskRenderNode *node) { GskVulkanOp op = { 0, }; graphene_matrix_t mvp; graphene_matrix_multiply (&self->mv, &self->p, &mvp); op.type = GSK_VULKAN_OP_PUSH_VERTEX_CONSTANTS; gsk_vulkan_push_constants_init (&op.constants.constants, &mvp, &self->viewport); g_array_append_val (self->render_ops, op); gsk_vulkan_render_pass_add_node (self, render, &op.constants.constants, node); } static GskVulkanImage * gsk_vulkan_render_pass_get_node_as_texture (GskVulkanRenderPass *self, GskVulkanRender *render, GskVulkanUploader *uploader, GskRenderNode *node, const graphene_rect_t *bounds, GskVulkanClip *current_clip, graphene_rect_t *tex_rect) { GskVulkanImage *result; cairo_surface_t *surface; cairo_t *cr; switch ((guint) gsk_render_node_get_node_type (node)) { case GSK_TEXTURE_NODE: if (graphene_rect_equal (bounds, &node->bounds)) { result = gsk_vulkan_renderer_ref_texture_image (GSK_VULKAN_RENDERER (gsk_vulkan_render_get_renderer (render)), gsk_texture_node_get_texture (node), uploader); gsk_vulkan_render_add_cleanup_image (render, result); *tex_rect = GRAPHENE_RECT_INIT(0, 0, 1, 1); return result; } break; case GSK_CAIRO_NODE: /* We're using recording surfaces, so drawing them to an image * surface and uploading them is the right thing. * But that's exactly what the fallback code does. */ break; default: { VkSemaphore semaphore; graphene_rect_t view; cairo_region_t *clip; GskVulkanRenderPass *pass; graphene_rect_t clipped; if (current_clip) graphene_rect_intersection (&current_clip->rect.bounds, bounds, &clipped); else clipped = *bounds; if (clipped.size.width == 0 || clipped.size.height == 0) return NULL; graphene_matrix_transform_bounds (&self->mv, &clipped, &view); view.origin.x = floor (view.origin.x); view.origin.y = floor (view.origin.y); view.size.width = ceil (view.size.width); view.size.height = ceil (view.size.height); result = gsk_vulkan_image_new_for_texture (self->vulkan, view.size.width, view.size.height); #ifdef G_ENABLE_DEBUG { GskProfiler *profiler = gsk_renderer_get_profiler (gsk_vulkan_render_get_renderer (render)); gsk_profiler_counter_add (profiler, self->texture_pixels, view.size.width * view.size.height); } #endif vkCreateSemaphore (gdk_vulkan_context_get_device (self->vulkan), &(VkSemaphoreCreateInfo) { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, NULL, 0 }, NULL, &semaphore); g_array_append_val (self->wait_semaphores, semaphore); clip = cairo_region_create_rectangle (&(cairo_rectangle_int_t) { 0, 0, gsk_vulkan_image_get_width (result), gsk_vulkan_image_get_height (result) }); pass = gsk_vulkan_render_pass_new (self->vulkan, result, self->scale_factor, &self->mv, &view, clip, semaphore); cairo_region_destroy (clip); gsk_vulkan_render_add_render_pass (render, pass); gsk_vulkan_render_pass_add (pass, render, node); gsk_vulkan_render_add_cleanup_image (render, result); /* assuming the unclipped bounds should go to texture coordinates 0..1, * calculate the coordinates for the clipped texture size */ tex_rect->origin.x = (bounds->origin.x - clipped.origin.x)/clipped.size.width; tex_rect->origin.y = (bounds->origin.y - clipped.origin.y)/clipped.size.height; tex_rect->size.width = bounds->size.width/clipped.size.width; tex_rect->size.height = bounds->size.height/clipped.size.height; return result; } } GSK_RENDERER_NOTE (gsk_vulkan_render_get_renderer (render), FALLBACK, g_message ("Node as texture not implemented for this case. Using %gx%g fallback surface", ceil (bounds->size.width), ceil (bounds->size.height))); #ifdef G_ENABLE_DEBUG { GskProfiler *profiler = gsk_renderer_get_profiler (gsk_vulkan_render_get_renderer (render)); gsk_profiler_counter_add (profiler, self->fallback_pixels, ceil (bounds->size.width) * ceil (bounds->size.height)); } #endif /* XXX: We could intersect bounds with clip bounds here */ surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, ceil (bounds->size.width), ceil (bounds->size.height)); cr = cairo_create (surface); cairo_translate (cr, -bounds->origin.x, -bounds->origin.y); gsk_render_node_draw (node, cr); cairo_destroy (cr); result = gsk_vulkan_image_new_from_data (uploader, cairo_image_surface_get_data (surface), cairo_image_surface_get_width (surface), cairo_image_surface_get_height (surface), cairo_image_surface_get_stride (surface)); cairo_surface_destroy (surface); gsk_vulkan_render_add_cleanup_image (render, result); tex_rect->origin.x = (node->bounds.origin.x - bounds->origin.x)/bounds->size.width; tex_rect->origin.y = (node->bounds.origin.y - bounds->origin.y)/bounds->size.height; tex_rect->size.width = node->bounds.size.width/bounds->size.width; tex_rect->size.height = node->bounds.size.height/bounds->size.height; return result; } static void gsk_vulkan_render_pass_upload_fallback (GskVulkanRenderPass *self, GskVulkanOpRender *op, GskVulkanRender *render, GskVulkanUploader *uploader) { GskRenderNode *node; cairo_surface_t *surface; cairo_t *cr; node = op->node; GSK_RENDERER_NOTE (gsk_vulkan_render_get_renderer (render), FALLBACK, g_message ("Upload op=%s, node %s[%p], bounds %gx%g", op->type == GSK_VULKAN_OP_FALLBACK_CLIP ? "fallback-clip" : (op->type == GSK_VULKAN_OP_FALLBACK_ROUNDED_CLIP ? "fallback-rounded-clip" : "fallback"), g_type_name_from_instance ((GTypeInstance *) node), node, ceil (node->bounds.size.width), ceil (node->bounds.size.height))); #ifdef G_ENABLE_DEBUG { GskProfiler *profiler = gsk_renderer_get_profiler (gsk_vulkan_render_get_renderer (render)); gsk_profiler_counter_add (profiler, self->fallback_pixels, ceil (node->bounds.size.width) * ceil (node->bounds.size.height)); } #endif /* XXX: We could intersect bounds with clip bounds here */ surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, ceil (node->bounds.size.width * self->scale_factor), ceil (node->bounds.size.height * self->scale_factor)); cairo_surface_set_device_scale (surface, self->scale_factor, self->scale_factor); cr = cairo_create (surface); cairo_translate (cr, -node->bounds.origin.x, -node->bounds.origin.y); if (op->type == GSK_VULKAN_OP_FALLBACK_CLIP) { cairo_rectangle (cr, op->clip.bounds.origin.x, op->clip.bounds.origin.y, op->clip.bounds.size.width, op->clip.bounds.size.height); cairo_clip (cr); } else if (op->type == GSK_VULKAN_OP_FALLBACK_ROUNDED_CLIP) { gsk_rounded_rect_path (&op->clip, cr); cairo_clip (cr); } else { g_assert (op->type == GSK_VULKAN_OP_FALLBACK); } gsk_render_node_draw (node, cr); #ifdef G_ENABLE_DEBUG if (GSK_RENDERER_DEBUG_CHECK (gsk_vulkan_render_get_renderer (render), FALLBACK)) { cairo_rectangle (cr, op->clip.bounds.origin.x, op->clip.bounds.origin.y, op->clip.bounds.size.width, op->clip.bounds.size.height); if (gsk_render_node_get_node_type (node) == GSK_CAIRO_NODE) cairo_set_source_rgba (cr, 0.3, 0, 1, 0.25); else cairo_set_source_rgba (cr, 1, 0, 0, 0.25); cairo_fill_preserve (cr); if (gsk_render_node_get_node_type (node) == GSK_CAIRO_NODE) cairo_set_source_rgba (cr, 0.3, 0, 1, 1); else cairo_set_source_rgba (cr, 1, 0, 0, 1); cairo_stroke (cr); } #endif cairo_destroy (cr); op->source = gsk_vulkan_image_new_from_data (uploader, cairo_image_surface_get_data (surface), cairo_image_surface_get_width (surface), cairo_image_surface_get_height (surface), cairo_image_surface_get_stride (surface)); op->source_rect = GRAPHENE_RECT_INIT(0, 0, 1, 1); cairo_surface_destroy (surface); gsk_vulkan_render_add_cleanup_image (render, op->source); } void gsk_vulkan_render_pass_upload (GskVulkanRenderPass *self, GskVulkanRender *render, GskVulkanUploader *uploader) { GskVulkanOp *op; guint i; GskVulkanClip *clip = NULL; for (i = 0; i < self->render_ops->len; i++) { op = &g_array_index (self->render_ops, GskVulkanOp, i); switch (op->type) { case GSK_VULKAN_OP_FALLBACK: case GSK_VULKAN_OP_FALLBACK_CLIP: case GSK_VULKAN_OP_FALLBACK_ROUNDED_CLIP: gsk_vulkan_render_pass_upload_fallback (self, &op->render, render, uploader); break; case GSK_VULKAN_OP_TEXT: case GSK_VULKAN_OP_COLOR_TEXT: { op->text.source = gsk_vulkan_renderer_ref_glyph_image (GSK_VULKAN_RENDERER (gsk_vulkan_render_get_renderer (render)), uploader, op->text.texture_index); gsk_vulkan_render_add_cleanup_image (render, op->text.source); } break; case GSK_VULKAN_OP_TEXTURE: { op->render.source = gsk_vulkan_renderer_ref_texture_image (GSK_VULKAN_RENDERER (gsk_vulkan_render_get_renderer (render)), gsk_texture_node_get_texture (op->render.node), uploader); op->render.source_rect = GRAPHENE_RECT_INIT(0, 0, 1, 1); gsk_vulkan_render_add_cleanup_image (render, op->render.source); } break; case GSK_VULKAN_OP_OPACITY: { GskRenderNode *child = gsk_opacity_node_get_child (op->render.node); op->render.source = gsk_vulkan_render_pass_get_node_as_texture (self, render, uploader, child, &child->bounds, clip, &op->render.source_rect); } break; case GSK_VULKAN_OP_REPEAT: { GskRenderNode *child = gsk_repeat_node_get_child (op->render.node); const graphene_rect_t *bounds = &op->render.node->bounds; const graphene_rect_t *child_bounds = gsk_repeat_node_get_child_bounds (op->render.node); op->render.source = gsk_vulkan_render_pass_get_node_as_texture (self, render, uploader, child, child_bounds, NULL, &op->render.source_rect); op->render.source_rect.origin.x = (bounds->origin.x - child_bounds->origin.x)/child_bounds->size.width; op->render.source_rect.origin.y = (bounds->origin.y - child_bounds->origin.y)/child_bounds->size.height; op->render.source_rect.size.width = bounds->size.width / child_bounds->size.width; op->render.source_rect.size.height = bounds->size.height / child_bounds->size.height; } break; case GSK_VULKAN_OP_BLUR: { GskRenderNode *child = gsk_blur_node_get_child (op->render.node); op->render.source = gsk_vulkan_render_pass_get_node_as_texture (self, render, uploader, child, &child->bounds, clip, &op->render.source_rect); } break; case GSK_VULKAN_OP_COLOR_MATRIX: { GskRenderNode *child = gsk_color_matrix_node_get_child (op->render.node); op->render.source = gsk_vulkan_render_pass_get_node_as_texture (self, render, uploader, child, &child->bounds, clip, &op->render.source_rect); } break; case GSK_VULKAN_OP_CROSS_FADE: { GskRenderNode *start = gsk_cross_fade_node_get_start_child (op->render.node); GskRenderNode *end = gsk_cross_fade_node_get_end_child (op->render.node); const graphene_rect_t *bounds = &op->render.node->bounds; op->render.source = gsk_vulkan_render_pass_get_node_as_texture (self, render, uploader, start, &start->bounds, clip, &op->render.source_rect); op->render.source_rect.origin.x = (bounds->origin.x - start->bounds.origin.x)/start->bounds.size.width; op->render.source_rect.origin.y = (bounds->origin.y - start->bounds.origin.y)/start->bounds.size.height; op->render.source_rect.size.width = bounds->size.width / start->bounds.size.width; op->render.source_rect.size.height = bounds->size.height / start->bounds.size.height; op->render.source2 = gsk_vulkan_render_pass_get_node_as_texture (self, render, uploader, end, &end->bounds, clip, &op->render.source2_rect); op->render.source2_rect.origin.x = (bounds->origin.x - end->bounds.origin.x)/end->bounds.size.width; op->render.source2_rect.origin.y = (bounds->origin.y - end->bounds.origin.y)/end->bounds.size.height; op->render.source2_rect.size.width = bounds->size.width / end->bounds.size.width; op->render.source2_rect.size.height = bounds->size.height / end->bounds.size.height; } break; case GSK_VULKAN_OP_BLEND_MODE: { GskRenderNode *top = gsk_blend_node_get_top_child (op->render.node); GskRenderNode *bottom = gsk_blend_node_get_bottom_child (op->render.node); const graphene_rect_t *bounds = &op->render.node->bounds; op->render.source = gsk_vulkan_render_pass_get_node_as_texture (self, render, uploader, top, &top->bounds, clip, &op->render.source_rect); op->render.source_rect.origin.x = (bounds->origin.x - top->bounds.origin.x)/top->bounds.size.width; op->render.source_rect.origin.y = (bounds->origin.y - top->bounds.origin.y)/top->bounds.size.height; op->render.source_rect.size.width = bounds->size.width / top->bounds.size.width; op->render.source_rect.size.height = bounds->size.height / top->bounds.size.height; op->render.source2 = gsk_vulkan_render_pass_get_node_as_texture (self, render, uploader, bottom, &bottom->bounds, clip, &op->render.source2_rect); op->render.source2_rect.origin.x = (bounds->origin.x - bottom->bounds.origin.x)/bottom->bounds.size.width; op->render.source2_rect.origin.y = (bounds->origin.y - bottom->bounds.origin.y)/bottom->bounds.size.height; op->render.source2_rect.size.width = bounds->size.width / bottom->bounds.size.width; op->render.source2_rect.size.height = bounds->size.height / bottom->bounds.size.height; } break; case GSK_VULKAN_OP_PUSH_VERTEX_CONSTANTS: clip = &op->constants.constants.clip; break; default: g_assert_not_reached (); case GSK_VULKAN_OP_COLOR: case GSK_VULKAN_OP_LINEAR_GRADIENT: case GSK_VULKAN_OP_BORDER: case GSK_VULKAN_OP_INSET_SHADOW: case GSK_VULKAN_OP_OUTSET_SHADOW: break; } } } static gsize gsk_vulkan_render_pass_count_vertex_data (GskVulkanRenderPass *self) { GskVulkanOp *op; gsize n_bytes; guint i; n_bytes = 0; for (i = 0; i < self->render_ops->len; i++) { op = &g_array_index (self->render_ops, GskVulkanOp, i); switch (op->type) { case GSK_VULKAN_OP_FALLBACK: case GSK_VULKAN_OP_FALLBACK_CLIP: case GSK_VULKAN_OP_FALLBACK_ROUNDED_CLIP: case GSK_VULKAN_OP_TEXTURE: case GSK_VULKAN_OP_REPEAT: op->render.vertex_count = gsk_vulkan_texture_pipeline_count_vertex_data (GSK_VULKAN_TEXTURE_PIPELINE (op->render.pipeline)); n_bytes += op->render.vertex_count; break; case GSK_VULKAN_OP_TEXT: op->text.vertex_count = gsk_vulkan_text_pipeline_count_vertex_data (GSK_VULKAN_TEXT_PIPELINE (op->text.pipeline), op->text.num_glyphs); n_bytes += op->text.vertex_count; break; case GSK_VULKAN_OP_COLOR_TEXT: op->text.vertex_count = gsk_vulkan_color_text_pipeline_count_vertex_data (GSK_VULKAN_COLOR_TEXT_PIPELINE (op->render.pipeline), op->text.num_glyphs); n_bytes += op->text.vertex_count; break; case GSK_VULKAN_OP_COLOR: op->render.vertex_count = gsk_vulkan_color_pipeline_count_vertex_data (GSK_VULKAN_COLOR_PIPELINE (op->render.pipeline)); n_bytes += op->render.vertex_count; break; case GSK_VULKAN_OP_LINEAR_GRADIENT: op->render.vertex_count = gsk_vulkan_linear_gradient_pipeline_count_vertex_data (GSK_VULKAN_LINEAR_GRADIENT_PIPELINE (op->render.pipeline)); n_bytes += op->render.vertex_count; break; case GSK_VULKAN_OP_OPACITY: case GSK_VULKAN_OP_COLOR_MATRIX: op->render.vertex_count = gsk_vulkan_effect_pipeline_count_vertex_data (GSK_VULKAN_EFFECT_PIPELINE (op->render.pipeline)); n_bytes += op->render.vertex_count; break; case GSK_VULKAN_OP_BLUR: op->render.vertex_count = gsk_vulkan_blur_pipeline_count_vertex_data (GSK_VULKAN_BLUR_PIPELINE (op->render.pipeline)); n_bytes += op->render.vertex_count; break; case GSK_VULKAN_OP_BORDER: op->render.vertex_count = gsk_vulkan_border_pipeline_count_vertex_data (GSK_VULKAN_BORDER_PIPELINE (op->render.pipeline)); n_bytes += op->render.vertex_count; break; case GSK_VULKAN_OP_INSET_SHADOW: case GSK_VULKAN_OP_OUTSET_SHADOW: op->render.vertex_count = gsk_vulkan_box_shadow_pipeline_count_vertex_data (GSK_VULKAN_BOX_SHADOW_PIPELINE (op->render.pipeline)); n_bytes += op->render.vertex_count; break; case GSK_VULKAN_OP_CROSS_FADE: op->render.vertex_count = gsk_vulkan_cross_fade_pipeline_count_vertex_data (GSK_VULKAN_CROSS_FADE_PIPELINE (op->render.pipeline)); n_bytes += op->render.vertex_count; break; case GSK_VULKAN_OP_BLEND_MODE: op->render.vertex_count = gsk_vulkan_blend_mode_pipeline_count_vertex_data (GSK_VULKAN_BLEND_MODE_PIPELINE (op->render.pipeline)); n_bytes += op->render.vertex_count; break; default: g_assert_not_reached (); case GSK_VULKAN_OP_PUSH_VERTEX_CONSTANTS: continue; } } return n_bytes; } static gsize gsk_vulkan_render_pass_collect_vertex_data (GskVulkanRenderPass *self, GskVulkanRender *render, guchar *data, gsize offset, gsize total) { GskVulkanOp *op; gsize n_bytes; guint i; n_bytes = 0; for (i = 0; i < self->render_ops->len; i++) { op = &g_array_index (self->render_ops, GskVulkanOp, i); switch (op->type) { case GSK_VULKAN_OP_FALLBACK: case GSK_VULKAN_OP_FALLBACK_CLIP: case GSK_VULKAN_OP_FALLBACK_ROUNDED_CLIP: case GSK_VULKAN_OP_TEXTURE: { op->render.vertex_offset = offset + n_bytes; gsk_vulkan_texture_pipeline_collect_vertex_data (GSK_VULKAN_TEXTURE_PIPELINE (op->render.pipeline), data + n_bytes + offset, &op->render.node->bounds, &op->render.source_rect); n_bytes += op->render.vertex_count; } break; case GSK_VULKAN_OP_REPEAT: { op->render.vertex_offset = offset + n_bytes; gsk_vulkan_texture_pipeline_collect_vertex_data (GSK_VULKAN_TEXTURE_PIPELINE (op->render.pipeline), data + n_bytes + offset, &op->render.node->bounds, &op->render.source_rect); n_bytes += op->render.vertex_count; } break; case GSK_VULKAN_OP_TEXT: { op->text.vertex_offset = offset + n_bytes; gsk_vulkan_text_pipeline_collect_vertex_data (GSK_VULKAN_TEXT_PIPELINE (op->text.pipeline), data + n_bytes + offset, GSK_VULKAN_RENDERER (gsk_vulkan_render_get_renderer (render)), &op->text.node->bounds, (PangoFont *)gsk_text_node_get_font (op->text.node), gsk_text_node_get_num_glyphs (op->text.node), gsk_text_node_get_glyphs (op->text.node, NULL), gsk_text_node_get_color (op->text.node), gsk_text_node_get_offset (op->text.node), op->text.start_glyph, op->text.num_glyphs, op->text.scale); n_bytes += op->text.vertex_count; } break; case GSK_VULKAN_OP_COLOR_TEXT: { op->text.vertex_offset = offset + n_bytes; gsk_vulkan_color_text_pipeline_collect_vertex_data (GSK_VULKAN_COLOR_TEXT_PIPELINE (op->text.pipeline), data + n_bytes + offset, GSK_VULKAN_RENDERER (gsk_vulkan_render_get_renderer (render)), &op->text.node->bounds, (PangoFont *)gsk_text_node_get_font (op->text.node), gsk_text_node_get_num_glyphs (op->text.node), gsk_text_node_get_glyphs (op->text.node, NULL), gsk_text_node_get_offset (op->text.node), op->text.start_glyph, op->text.num_glyphs, op->text.scale); n_bytes += op->text.vertex_count; } break; case GSK_VULKAN_OP_COLOR: { op->render.vertex_offset = offset + n_bytes; gsk_vulkan_color_pipeline_collect_vertex_data (GSK_VULKAN_COLOR_PIPELINE (op->render.pipeline), data + n_bytes + offset, &op->render.node->bounds, gsk_color_node_get_color (op->render.node)); n_bytes += op->render.vertex_count; } break; case GSK_VULKAN_OP_LINEAR_GRADIENT: { op->render.vertex_offset = offset + n_bytes; gsk_vulkan_linear_gradient_pipeline_collect_vertex_data (GSK_VULKAN_LINEAR_GRADIENT_PIPELINE (op->render.pipeline), data + n_bytes + offset, &op->render.node->bounds, gsk_linear_gradient_node_get_start (op->render.node), gsk_linear_gradient_node_get_end (op->render.node), gsk_render_node_get_node_type (op->render.node) == GSK_REPEATING_LINEAR_GRADIENT_NODE, gsk_linear_gradient_node_get_n_color_stops (op->render.node), gsk_linear_gradient_node_get_color_stops (op->render.node, NULL)); n_bytes += op->render.vertex_count; } break; case GSK_VULKAN_OP_OPACITY: { graphene_matrix_t color_matrix; graphene_vec4_t color_offset; graphene_matrix_init_from_float (&color_matrix, (float[16]) { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, gsk_opacity_node_get_opacity (op->render.node) }); graphene_vec4_init (&color_offset, 0.0, 0.0, 0.0, 0.0); op->render.vertex_offset = offset + n_bytes; gsk_vulkan_effect_pipeline_collect_vertex_data (GSK_VULKAN_EFFECT_PIPELINE (op->render.pipeline), data + n_bytes + offset, &op->render.node->bounds, &op->render.source_rect, &color_matrix, &color_offset); n_bytes += op->render.vertex_count; } break; case GSK_VULKAN_OP_BLUR: { op->render.vertex_offset = offset + n_bytes; gsk_vulkan_blur_pipeline_collect_vertex_data (GSK_VULKAN_BLUR_PIPELINE (op->render.pipeline), data + n_bytes + offset, &op->render.node->bounds, &op->render.source_rect, gsk_blur_node_get_radius (op->render.node)); n_bytes += op->render.vertex_count; } break; case GSK_VULKAN_OP_COLOR_MATRIX: { op->render.vertex_offset = offset + n_bytes; gsk_vulkan_effect_pipeline_collect_vertex_data (GSK_VULKAN_EFFECT_PIPELINE (op->render.pipeline), data + n_bytes + offset, &op->render.node->bounds, &op->render.source_rect, gsk_color_matrix_node_get_color_matrix (op->render.node), gsk_color_matrix_node_get_color_offset (op->render.node)); n_bytes += op->render.vertex_count; } break; case GSK_VULKAN_OP_BORDER: { op->render.vertex_offset = offset + n_bytes; gsk_vulkan_border_pipeline_collect_vertex_data (GSK_VULKAN_BORDER_PIPELINE (op->render.pipeline), data + n_bytes + offset, gsk_border_node_get_outline (op->render.node), gsk_border_node_get_widths (op->render.node), gsk_border_node_get_colors (op->render.node)); n_bytes += op->render.vertex_count; } break; case GSK_VULKAN_OP_INSET_SHADOW: { op->render.vertex_offset = offset + n_bytes; gsk_vulkan_box_shadow_pipeline_collect_vertex_data (GSK_VULKAN_BOX_SHADOW_PIPELINE (op->render.pipeline), data + n_bytes + offset, gsk_inset_shadow_node_get_outline (op->render.node), gsk_inset_shadow_node_get_color (op->render.node), gsk_inset_shadow_node_get_dx (op->render.node), gsk_inset_shadow_node_get_dy (op->render.node), gsk_inset_shadow_node_get_spread (op->render.node), gsk_inset_shadow_node_get_blur_radius (op->render.node)); n_bytes += op->render.vertex_count; } break; case GSK_VULKAN_OP_OUTSET_SHADOW: { op->render.vertex_offset = offset + n_bytes; gsk_vulkan_box_shadow_pipeline_collect_vertex_data (GSK_VULKAN_BOX_SHADOW_PIPELINE (op->render.pipeline), data + n_bytes + offset, gsk_outset_shadow_node_get_outline (op->render.node), gsk_outset_shadow_node_get_color (op->render.node), gsk_outset_shadow_node_get_dx (op->render.node), gsk_outset_shadow_node_get_dy (op->render.node), gsk_outset_shadow_node_get_spread (op->render.node), gsk_outset_shadow_node_get_blur_radius (op->render.node)); n_bytes += op->render.vertex_count; } break; case GSK_VULKAN_OP_CROSS_FADE: { op->render.vertex_offset = offset + n_bytes; gsk_vulkan_cross_fade_pipeline_collect_vertex_data (GSK_VULKAN_CROSS_FADE_PIPELINE (op->render.pipeline), data + n_bytes + offset, &op->render.node->bounds, &op->render.source_rect, &op->render.source2_rect, gsk_cross_fade_node_get_progress (op->render.node)); n_bytes += op->render.vertex_count; } break; case GSK_VULKAN_OP_BLEND_MODE: { op->render.vertex_offset = offset + n_bytes; gsk_vulkan_blend_mode_pipeline_collect_vertex_data (GSK_VULKAN_BLEND_MODE_PIPELINE (op->render.pipeline), data + n_bytes + offset, &op->render.node->bounds, &op->render.source_rect, &op->render.source2_rect, gsk_blend_node_get_blend_mode (op->render.node)); n_bytes += op->render.vertex_count; } break; default: g_assert_not_reached (); case GSK_VULKAN_OP_PUSH_VERTEX_CONSTANTS: continue; } g_assert (n_bytes + offset <= total); } return n_bytes; } static GskVulkanBuffer * gsk_vulkan_render_pass_get_vertex_data (GskVulkanRenderPass *self, GskVulkanRender *render) { if (self->vertex_data == NULL) { gsize n_bytes; guchar *data; n_bytes = gsk_vulkan_render_pass_count_vertex_data (self); self->vertex_data = gsk_vulkan_buffer_new (self->vulkan, n_bytes); data = gsk_vulkan_buffer_map (self->vertex_data); gsk_vulkan_render_pass_collect_vertex_data (self, render, data, 0, n_bytes); gsk_vulkan_buffer_unmap (self->vertex_data); } return self->vertex_data; } gsize gsk_vulkan_render_pass_get_wait_semaphores (GskVulkanRenderPass *self, VkSemaphore **semaphores) { *semaphores = (VkSemaphore *)self->wait_semaphores->data; return self->wait_semaphores->len; } gsize gsk_vulkan_render_pass_get_signal_semaphores (GskVulkanRenderPass *self, VkSemaphore **semaphores) { *semaphores = (VkSemaphore *)&self->signal_semaphore; return self->signal_semaphore != VK_NULL_HANDLE ? 1 : 0; } void gsk_vulkan_render_pass_reserve_descriptor_sets (GskVulkanRenderPass *self, GskVulkanRender *render) { GskVulkanOp *op; guint i; for (i = 0; i < self->render_ops->len; i++) { op = &g_array_index (self->render_ops, GskVulkanOp, i); switch (op->type) { case GSK_VULKAN_OP_FALLBACK: case GSK_VULKAN_OP_FALLBACK_CLIP: case GSK_VULKAN_OP_FALLBACK_ROUNDED_CLIP: case GSK_VULKAN_OP_TEXTURE: case GSK_VULKAN_OP_OPACITY: case GSK_VULKAN_OP_BLUR: case GSK_VULKAN_OP_COLOR_MATRIX: if (op->render.source) op->render.descriptor_set_index = gsk_vulkan_render_reserve_descriptor_set (render, op->render.source, FALSE); break; case GSK_VULKAN_OP_REPEAT: if (op->render.source) op->render.descriptor_set_index = gsk_vulkan_render_reserve_descriptor_set (render, op->render.source, TRUE); break; case GSK_VULKAN_OP_TEXT: case GSK_VULKAN_OP_COLOR_TEXT: op->text.descriptor_set_index = gsk_vulkan_render_reserve_descriptor_set (render, op->text.source, FALSE); break; case GSK_VULKAN_OP_CROSS_FADE: case GSK_VULKAN_OP_BLEND_MODE: if (op->render.source && op->render.source2) { op->render.descriptor_set_index = gsk_vulkan_render_reserve_descriptor_set (render, op->render.source, FALSE); op->render.descriptor_set_index2 = gsk_vulkan_render_reserve_descriptor_set (render, op->render.source2, FALSE); } break; default: g_assert_not_reached (); case GSK_VULKAN_OP_COLOR: case GSK_VULKAN_OP_LINEAR_GRADIENT: case GSK_VULKAN_OP_PUSH_VERTEX_CONSTANTS: case GSK_VULKAN_OP_BORDER: case GSK_VULKAN_OP_INSET_SHADOW: case GSK_VULKAN_OP_OUTSET_SHADOW: break; } } } static void gsk_vulkan_render_pass_draw_rect (GskVulkanRenderPass *self, GskVulkanRender *render, guint layout_count, VkPipelineLayout *pipeline_layout, VkCommandBuffer command_buffer) { GskVulkanPipeline *current_pipeline = NULL; gsize current_draw_index = 0; GskVulkanOp *op; guint i, step; GskVulkanBuffer *vertex_buffer; vertex_buffer = gsk_vulkan_render_pass_get_vertex_data (self, render); for (i = 0; i < self->render_ops->len; i += step) { op = &g_array_index (self->render_ops, GskVulkanOp, i); step = 1; switch (op->type) { case GSK_VULKAN_OP_FALLBACK: case GSK_VULKAN_OP_FALLBACK_CLIP: case GSK_VULKAN_OP_FALLBACK_ROUNDED_CLIP: case GSK_VULKAN_OP_TEXTURE: case GSK_VULKAN_OP_REPEAT: if (!op->render.source) continue; if (current_pipeline != op->render.pipeline) { current_pipeline = op->render.pipeline; vkCmdBindPipeline (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline (current_pipeline)); vkCmdBindVertexBuffers (command_buffer, 0, 1, (VkBuffer[1]) { gsk_vulkan_buffer_get_buffer (vertex_buffer) }, (VkDeviceSize[1]) { op->render.vertex_offset }); current_draw_index = 0; } vkCmdBindDescriptorSets (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline_layout (current_pipeline), 0, 1, (VkDescriptorSet[1]) { gsk_vulkan_render_get_descriptor_set (render, op->render.descriptor_set_index) }, 0, NULL); current_draw_index += gsk_vulkan_texture_pipeline_draw (GSK_VULKAN_TEXTURE_PIPELINE (current_pipeline), command_buffer, current_draw_index, 1); break; case GSK_VULKAN_OP_TEXT: if (current_pipeline != op->text.pipeline) { current_pipeline = op->text.pipeline; vkCmdBindPipeline (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline (current_pipeline)); vkCmdBindVertexBuffers (command_buffer, 0, 1, (VkBuffer[1]) { gsk_vulkan_buffer_get_buffer (vertex_buffer) }, (VkDeviceSize[1]) { op->text.vertex_offset }); current_draw_index = 0; } vkCmdBindDescriptorSets (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline_layout (current_pipeline), 0, 1, (VkDescriptorSet[1]) { gsk_vulkan_render_get_descriptor_set (render, op->text.descriptor_set_index) }, 0, NULL); current_draw_index += gsk_vulkan_text_pipeline_draw (GSK_VULKAN_TEXT_PIPELINE (current_pipeline), command_buffer, current_draw_index, op->text.num_glyphs); break; case GSK_VULKAN_OP_COLOR_TEXT: if (current_pipeline != op->text.pipeline) { current_pipeline = op->text.pipeline; vkCmdBindPipeline (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline (current_pipeline)); vkCmdBindVertexBuffers (command_buffer, 0, 1, (VkBuffer[1]) { gsk_vulkan_buffer_get_buffer (vertex_buffer) }, (VkDeviceSize[1]) { op->text.vertex_offset }); current_draw_index = 0; } vkCmdBindDescriptorSets (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline_layout (current_pipeline), 0, 1, (VkDescriptorSet[1]) { gsk_vulkan_render_get_descriptor_set (render, op->text.descriptor_set_index) }, 0, NULL); current_draw_index += gsk_vulkan_color_text_pipeline_draw (GSK_VULKAN_COLOR_TEXT_PIPELINE (current_pipeline), command_buffer, current_draw_index, op->text.num_glyphs); break; case GSK_VULKAN_OP_OPACITY: case GSK_VULKAN_OP_COLOR_MATRIX: if (!op->render.source) continue; if (current_pipeline != op->render.pipeline) { current_pipeline = op->render.pipeline; vkCmdBindPipeline (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline (current_pipeline)); vkCmdBindVertexBuffers (command_buffer, 0, 1, (VkBuffer[1]) { gsk_vulkan_buffer_get_buffer (vertex_buffer) }, (VkDeviceSize[1]) { op->render.vertex_offset }); current_draw_index = 0; } vkCmdBindDescriptorSets (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline_layout (current_pipeline), 0, 1, (VkDescriptorSet[1]) { gsk_vulkan_render_get_descriptor_set (render, op->render.descriptor_set_index) }, 0, NULL); current_draw_index += gsk_vulkan_effect_pipeline_draw (GSK_VULKAN_EFFECT_PIPELINE (current_pipeline), command_buffer, current_draw_index, 1); break; case GSK_VULKAN_OP_BLUR: if (!op->render.source) continue; if (current_pipeline != op->render.pipeline) { current_pipeline = op->render.pipeline; vkCmdBindPipeline (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline (current_pipeline)); vkCmdBindVertexBuffers (command_buffer, 0, 1, (VkBuffer[1]) { gsk_vulkan_buffer_get_buffer (vertex_buffer) }, (VkDeviceSize[1]) { op->render.vertex_offset }); current_draw_index = 0; } vkCmdBindDescriptorSets (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline_layout (current_pipeline), 0, 1, (VkDescriptorSet[1]) { gsk_vulkan_render_get_descriptor_set (render, op->render.descriptor_set_index) }, 0, NULL); current_draw_index += gsk_vulkan_blur_pipeline_draw (GSK_VULKAN_BLUR_PIPELINE (current_pipeline), command_buffer, current_draw_index, 1); break; case GSK_VULKAN_OP_COLOR: if (current_pipeline != op->render.pipeline) { current_pipeline = op->render.pipeline; vkCmdBindPipeline (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline (current_pipeline)); vkCmdBindVertexBuffers (command_buffer, 0, 1, (VkBuffer[1]) { gsk_vulkan_buffer_get_buffer (vertex_buffer) }, (VkDeviceSize[1]) { op->render.vertex_offset }); current_draw_index = 0; } for (step = 1; step + i < self->render_ops->len; step++) { GskVulkanOp *cmp = &g_array_index (self->render_ops, GskVulkanOp, i + step); if (cmp->type != GSK_VULKAN_OP_COLOR || cmp->render.pipeline != current_pipeline) break; } current_draw_index += gsk_vulkan_color_pipeline_draw (GSK_VULKAN_COLOR_PIPELINE (current_pipeline), command_buffer, current_draw_index, step); break; case GSK_VULKAN_OP_LINEAR_GRADIENT: if (current_pipeline != op->render.pipeline) { current_pipeline = op->render.pipeline; vkCmdBindPipeline (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline (current_pipeline)); vkCmdBindVertexBuffers (command_buffer, 0, 1, (VkBuffer[1]) { gsk_vulkan_buffer_get_buffer (vertex_buffer) }, (VkDeviceSize[1]) { op->render.vertex_offset }); current_draw_index = 0; } current_draw_index += gsk_vulkan_linear_gradient_pipeline_draw (GSK_VULKAN_LINEAR_GRADIENT_PIPELINE (current_pipeline), command_buffer, current_draw_index, 1); break; case GSK_VULKAN_OP_BORDER: if (current_pipeline != op->render.pipeline) { current_pipeline = op->render.pipeline; vkCmdBindPipeline (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline (current_pipeline)); vkCmdBindVertexBuffers (command_buffer, 0, 1, (VkBuffer[1]) { gsk_vulkan_buffer_get_buffer (vertex_buffer) }, (VkDeviceSize[1]) { op->render.vertex_offset }); current_draw_index = 0; } current_draw_index += gsk_vulkan_border_pipeline_draw (GSK_VULKAN_BORDER_PIPELINE (current_pipeline), command_buffer, current_draw_index, 1); break; case GSK_VULKAN_OP_INSET_SHADOW: case GSK_VULKAN_OP_OUTSET_SHADOW: if (current_pipeline != op->render.pipeline) { current_pipeline = op->render.pipeline; vkCmdBindPipeline (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline (current_pipeline)); vkCmdBindVertexBuffers (command_buffer, 0, 1, (VkBuffer[1]) { gsk_vulkan_buffer_get_buffer (vertex_buffer) }, (VkDeviceSize[1]) { op->render.vertex_offset }); current_draw_index = 0; } current_draw_index += gsk_vulkan_box_shadow_pipeline_draw (GSK_VULKAN_BOX_SHADOW_PIPELINE (current_pipeline), command_buffer, current_draw_index, 1); break; case GSK_VULKAN_OP_PUSH_VERTEX_CONSTANTS: for (int j = 0; j < layout_count; j++) gsk_vulkan_push_constants_push (&op->constants.constants, command_buffer, pipeline_layout[j]); break; case GSK_VULKAN_OP_CROSS_FADE: if (!op->render.source || !op->render.source2) continue; if (current_pipeline != op->render.pipeline) { current_pipeline = op->render.pipeline; vkCmdBindPipeline (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline (current_pipeline)); vkCmdBindVertexBuffers (command_buffer, 0, 1, (VkBuffer[1]) { gsk_vulkan_buffer_get_buffer (vertex_buffer) }, (VkDeviceSize[1]) { op->render.vertex_offset }); current_draw_index = 0; } vkCmdBindDescriptorSets (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline_layout (current_pipeline), 0, 2, (VkDescriptorSet[2]) { gsk_vulkan_render_get_descriptor_set (render, op->render.descriptor_set_index), gsk_vulkan_render_get_descriptor_set (render, op->render.descriptor_set_index2) }, 0, NULL); current_draw_index += gsk_vulkan_cross_fade_pipeline_draw (GSK_VULKAN_CROSS_FADE_PIPELINE (current_pipeline), command_buffer, current_draw_index, 1); break; case GSK_VULKAN_OP_BLEND_MODE: if (!op->render.source || !op->render.source2) continue; if (current_pipeline != op->render.pipeline) { current_pipeline = op->render.pipeline; vkCmdBindPipeline (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline (current_pipeline)); vkCmdBindVertexBuffers (command_buffer, 0, 1, (VkBuffer[1]) { gsk_vulkan_buffer_get_buffer (vertex_buffer) }, (VkDeviceSize[1]) { op->render.vertex_offset }); current_draw_index = 0; } vkCmdBindDescriptorSets (command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, gsk_vulkan_pipeline_get_pipeline_layout (current_pipeline), 0, 2, (VkDescriptorSet[2]) { gsk_vulkan_render_get_descriptor_set (render, op->render.descriptor_set_index), gsk_vulkan_render_get_descriptor_set (render, op->render.descriptor_set_index2) }, 0, NULL); current_draw_index += gsk_vulkan_blend_mode_pipeline_draw (GSK_VULKAN_BLEND_MODE_PIPELINE (current_pipeline), command_buffer, current_draw_index, 1); break; default: g_assert_not_reached (); break; } } } void gsk_vulkan_render_pass_draw (GskVulkanRenderPass *self, GskVulkanRender *render, guint layout_count, VkPipelineLayout *pipeline_layout, VkCommandBuffer command_buffer) { guint i; vkCmdSetViewport (command_buffer, 0, 1, &(VkViewport) { .x = 0, .y = 0, .width = self->viewport.size.width, .height = self->viewport.size.height, .minDepth = 0, .maxDepth = 1 }); for (i = 0; i < cairo_region_num_rectangles (self->clip); i++) { cairo_rectangle_int_t rect; cairo_region_get_rectangle (self->clip, i, &rect); vkCmdSetScissor (command_buffer, 0, 1, &(VkRect2D) { { rect.x * self->scale_factor, rect.y * self->scale_factor }, { rect.width * self->scale_factor, rect.height * self->scale_factor } }); vkCmdBeginRenderPass (command_buffer, &(VkRenderPassBeginInfo) { .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = self->render_pass, .framebuffer = gsk_vulkan_render_get_framebuffer (render, self->target), .renderArea = { { rect.x * self->scale_factor, rect.y * self->scale_factor }, { rect.width * self->scale_factor, rect.height * self->scale_factor } }, .clearValueCount = 1, .pClearValues = (VkClearValue [1]) { { .color = { .float32 = { 0.f, 0.f, 0.f, 0.f } } } } }, VK_SUBPASS_CONTENTS_INLINE); gsk_vulkan_render_pass_draw_rect (self, render, layout_count, pipeline_layout, command_buffer); vkCmdEndRenderPass (command_buffer); } }
fbf308bb5c7e198c25c590f1fb97bc2dfa58114b
4107fda8550fa34f2549e884b06b0bd2d36b9c06
/src/wayland-eglhandle.c
e0080f1b149e63aed5db95e40a71825c94d4211a
[ "MIT", "BSD-3-Clause" ]
permissive
NVIDIA/egl-wayland
08ac10ac1f8068b62834b1873133cd5c8fd51480
ea70449fd94b5f866ea6189bf4f41f7c230cccfa
refs/heads/master
2023-08-04T12:04:37.132340
2023-07-14T20:43:43
2023-07-18T18:46:06
76,882,500
253
50
MIT
2023-04-19T17:15:08
2016-12-19T17:26:25
C
UTF-8
C
false
false
7,514
c
wayland-eglhandle.c
/* * Copyright (c) 2014-2022, NVIDIA CORPORATION. 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 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. */ #include "wayland-eglhandle.h" #include "wayland-egldisplay.h" #include "wayland-eglsurface-internal.h" #include "wayland-thread.h" #include <stdlib.h> #include <errno.h> #include <assert.h> WlEglPlatformData* wlEglCreatePlatformData(int apiMajor, int apiMinor, const EGLExtDriver *driver) { const char *exts = NULL; WlEglPlatformData *res = NULL; assert((driver != NULL) && (driver->getProcAddress != NULL)); /* Allocate platform data and fetch EGL functions */ res = calloc(1, sizeof(WlEglPlatformData)); if (res == NULL) { return NULL; } wl_list_init(&res->deviceDpyList); /* Cache the EGL driver version */ #if EGL_EXTERNAL_PLATFORM_HAS(DRIVER_VERSION) if (EGL_EXTERNAL_PLATFORM_SUPPORTS(apiMajor, apiMinor, DRIVER_VERSION)) { res->egl.major = driver->major; res->egl.minor = driver->minor; } #endif /* Fetch all required driver functions */ #define GET_PROC(_FIELD_, _NAME_) \ do { \ res->egl._FIELD_ = driver->getProcAddress(#_NAME_); \ if (res->egl._FIELD_ == NULL) { \ goto fail; \ } \ } while (0) /* Core and basic stream functionality */ GET_PROC(queryString, eglQueryString); GET_PROC(queryDevices, eglQueryDevicesEXT); /* TODO: use eglGetPlatformDisplay instead of eglGetPlatformDisplayEXT if EGL 1.5 is available */ GET_PROC(getPlatformDisplay, eglGetPlatformDisplayEXT); GET_PROC(initialize, eglInitialize); GET_PROC(terminate, eglTerminate); GET_PROC(chooseConfig, eglChooseConfig); GET_PROC(getConfigAttrib, eglGetConfigAttrib); GET_PROC(querySurface, eglQuerySurface); GET_PROC(getCurrentContext, eglGetCurrentContext); GET_PROC(getCurrentSurface, eglGetCurrentSurface); GET_PROC(makeCurrent, eglMakeCurrent); GET_PROC(createStream, eglCreateStreamKHR); GET_PROC(createStreamFromFD, eglCreateStreamFromFileDescriptorKHR); GET_PROC(createStreamAttrib, eglCreateStreamAttribNV); GET_PROC(getStreamFileDescriptor, eglGetStreamFileDescriptorKHR); GET_PROC(createStreamProducerSurface, eglCreateStreamProducerSurfaceKHR); GET_PROC(createPbufferSurface, eglCreatePbufferSurface); GET_PROC(destroyStream, eglDestroyStreamKHR); GET_PROC(destroySurface, eglDestroySurface); GET_PROC(swapBuffers, eglSwapBuffers); GET_PROC(swapBuffersWithDamage, eglSwapBuffersWithDamageKHR); GET_PROC(swapInterval, eglSwapInterval); GET_PROC(getError, eglGetError); GET_PROC(releaseThread, eglReleaseThread); /* From EGL_EXT_device_query, used by the wayland-drm implementation */ GET_PROC(queryDisplayAttrib, eglQueryDisplayAttribEXT); GET_PROC(queryDeviceString, eglQueryDeviceStringEXT); #undef GET_PROC /* Fetch all optional driver functions */ #define GET_PROC(_FIELD_, _NAME_) \ res->egl._FIELD_ = driver->getProcAddress(#_NAME_) /* Used by damage thread */ GET_PROC(queryStream, eglQueryStreamKHR); GET_PROC(queryStreamu64, eglQueryStreamu64KHR); GET_PROC(createStreamSync, eglCreateStreamSyncNV); GET_PROC(clientWaitSync, eglClientWaitSyncKHR); GET_PROC(signalSync, eglSignalSyncKHR); GET_PROC(destroySync, eglDestroySyncKHR); /* Stream flush */ GET_PROC(streamFlush, eglStreamFlushNV); /* EGLImage Stream consumer and dependencies */ GET_PROC(streamImageConsumerConnect, eglStreamImageConsumerConnectNV); GET_PROC(streamAcquireImage, eglStreamAcquireImageNV); GET_PROC(streamReleaseImage, eglStreamReleaseImageNV); GET_PROC(queryStreamConsumerEvent, eglQueryStreamConsumerEventNV); GET_PROC(exportDMABUFImage, eglExportDMABUFImageMESA); GET_PROC(exportDMABUFImageQuery, eglExportDMABUFImageQueryMESA); GET_PROC(createImage, eglCreateImageKHR); GET_PROC(destroyImage, eglDestroyImageKHR); #undef GET_PROC /* Check for required EGL client extensions */ exts = res->egl.queryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); if (exts == NULL) { goto fail; } /* * Note EGL_EXT_platform_device implies support for EGL_EXT_device_base, * which is equivalent to the combination of EGL_EXT_device_query and * EGL_EXT_device_enumeration. The wayland-drm implementation assumes * EGL_EXT_device_query is supported based on this check. */ if (!wlEglFindExtension("EGL_EXT_platform_base", exts) || !wlEglFindExtension("EGL_EXT_platform_device", exts)) { goto fail; } res->supportsDisplayReference = wlEglFindExtension("EGL_KHR_display_reference", exts); /* Cache driver imports */ res->callbacks.setError = driver->setError; res->callbacks.streamSwapInterval = driver->streamSwapInterval; return res; fail: free(res); return NULL; } void wlEglDestroyPlatformData(WlEglPlatformData *data) { free(data); } void* wlEglGetInternalHandleExport(EGLDisplay dpy, EGLenum type, void *handle) { WlEglDisplay *display; if (type == EGL_OBJECT_DISPLAY_KHR) { display = wlEglAcquireDisplay(handle); if (display) { handle = (void *)display->devDpy->eglDisplay; wlEglReleaseDisplay(display); } } else if (type == EGL_OBJECT_SURFACE_KHR) { display = wlEglAcquireDisplay(dpy); if (display) { pthread_mutex_lock(&display->mutex); if (wlEglIsWlEglSurfaceForDisplay(display, (WlEglSurface *)handle)) { handle = (void *)(((WlEglSurface *)handle)->ctx.eglSurface); } pthread_mutex_unlock(&display->mutex); wlEglReleaseDisplay(dpy); } } return handle; }
ba96db6eef60552682c139c8eb6c13c682537c93
35c04ea32351dc95bc18d46e5c70dda9c1e08668
/Examples/KDS/tinyK20/LoRaMac-node/src/system/uart.c
0a27da37603b087fd49831e0bf89d754e62c9efc
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause" ]
permissive
ErichStyger/mcuoneclipse
0f8e7a2056a26ed79d9d4a0afd64777ff0b2b2fe
04ad311b11860ae5f8285316010961a87fa06d0c
refs/heads/master
2023-08-28T22:54:08.501719
2023-08-25T15:11:44
2023-08-25T15:11:44
7,446,094
620
1,191
NOASSERTION
2020-10-16T03:13:28
2013-01-04T19:38:12
Batchfile
UTF-8
C
false
false
4,507
c
uart.c
/* / _____) _ | | ( (____ _____ ____ _| |_ _____ ____| |__ \____ \| ___ | (_ _) ___ |/ ___) _ \ _____) ) ____| | | || |_| ____( (___| | | | (______/|_____)_|_|_| \__)_____)\____)_| |_| (C)2013 Semtech Description: Implements the generic UART driver License: Revised BSD License, see LICENSE.TXT file include in the project Maintainer: Miguel Luis and Gregory Cristian */ #include "board.h" #include "uart-board.h" #if defined( USE_USB_CDC ) #include "uart-usb-board.h" #endif #include "uart.h" /*! * Number of times the UartPutBuffer will try to send the buffer before * returning ERROR */ #define TX_BUFFER_RETRY_COUNT 10 void UartInit( Uart_t *obj, uint8_t uartId, PinNames tx, PinNames rx ) { if ( obj->IsInitialized == false ) { obj->IsInitialized = true; if ( uartId == UART_USB_CDC ) { #if defined( USE_USB_CDC ) UartUsbInit( obj, uartId, NC, NC ); #endif } else { UartMcuInit(obj, uartId, tx, rx); } } } void UartConfig( Uart_t *obj, UartMode_t mode, uint32_t baudrate, WordLength_t wordLength, StopBits_t stopBits, Parity_t parity, FlowCtrl_t flowCtrl ) { if ( obj->IsInitialized == false ) { // UartInit function must be called first. while ( 1 ) ; } if ( obj->UartId == UART_USB_CDC ) { #if defined( USE_USB_CDC ) UartUsbConfig( obj, mode, baudrate, wordLength, stopBits, parity, flowCtrl ); #endif } else { UartMcuConfig(obj, mode, baudrate, wordLength, stopBits, parity, flowCtrl); } } void UartDeInit( Uart_t *obj ) { obj->IsInitialized = false; if ( obj->UartId == UART_USB_CDC ) { #if defined( USE_USB_CDC ) UartUsbDeInit( obj ); #endif } else { UartMcuDeInit(obj); } } void UartEnable( Uart_t *obj ) { if ( obj->IsInitialized == false ) return; if ( obj->UartId == UART_USB_CDC ) { #if defined( USE_USB_CDC ) UartUsbEnable( obj ); #endif } else { UartMcuEnable(obj); } } void UartDisable( Uart_t *obj ) { if ( obj->IsInitialized == false ) return; if ( obj->UartId == UART_USB_CDC ) { #if defined( USE_USB_CDC ) UartUsbDisable( obj ); #endif } else { UartMcuDisable(obj); } } void UartEnableReceiver( Uart_t *obj, bool enable ) { if ( obj->IsInitialized == false ) return; if ( obj->UartId == UART_USB_CDC ) { #if defined( USE_USB_CDC ) UartUsbEnableReceiver( obj, enable ); #endif } else { UartMcuEnableReceiver(obj, enable); } } uint8_t UartPutChar( Uart_t *obj, uint8_t data ) { if ( obj->UartId == UART_USB_CDC ) { #if defined( USE_USB_CDC ) return UartUsbPutChar( obj, data ); #else return 255; // Not supported #endif } else { return UartMcuPutChar(obj, data); } } uint8_t UartGetChar( Uart_t *obj, uint8_t *data ) { if ( obj->UartId == UART_USB_CDC ) { #if defined( USE_USB_CDC ) return UartUsbGetChar( obj, data ); #else return 255; // Not supported #endif } else { return UartMcuGetChar(obj, data); } } uint8_t UartPutBuffer( Uart_t *obj, uint8_t *buffer, uint16_t size ) { if ( obj->UartId == UART_USB_CDC ) { #if defined( USE_USB_CDC ) return UartUsbPutBuffer( obj, buffer, size ); #else return 255; // Not supported #endif } else { #if defined(USE_CUSTOM_UART_HAL) return UartMcuPutBuffer(obj, buffer, size); #else uint8_t retryCount; uint16_t i; for ( i = 0; i < size; i++ ) { retryCount = 0; while ( UartPutChar(obj, buffer[i]) != 0 ) { retryCount++; // Exit if something goes terribly wrong if ( retryCount > TX_BUFFER_RETRY_COUNT ) { return 1; // Error } } } return 0; // OK #endif /* USE_CUSTOM_UART_HAL */ } } uint8_t UartGetBuffer( Uart_t *obj, uint8_t *buffer, uint16_t size, uint16_t *nbReadBytes ) { #if defined(USE_CUSTOM_UART_HAL) return UartMcuGetBuffer(obj, buffer, size); #else uint16_t localSize = 0; while ( localSize < size ) { if ( UartGetChar(obj, buffer + localSize) == 0 ) { localSize++; } else { break; } } *nbReadBytes = localSize; if ( localSize == 0 ) { return 1; // Empty } return 0; // OK #endif /* USE_CUSTOM_UART_HAL */ }
80231dde9d3408fa363ceecc4fc3074113696b50
e814383d36a10839104efaa4df277996ab220fa3
/oshmem/mca/memheap/buddy/memheap_buddy_component.h
8a4e177381ff471ac407c2c90b8f28789b9622fb
[ "mpich2", "BSD-3-Clause-Open-MPI" ]
permissive
open-mpi/ompi
a1d7483ae1d83dd8fd8ae3ee95e832e0a0ee04e3
1edfdb025c4450f694600083ad871cf06c8d45cd
refs/heads/main
2023-09-01T01:30:02.040705
2023-08-29T17:32:18
2023-08-29T17:32:18
24,107,001
2,008
973
NOASSERTION
2023-09-14T20:59:26
2014-09-16T16:08:30
C
UTF-8
C
false
false
434
h
memheap_buddy_component.h
/* * Copyright (c) 2013 Mellanox Technologies, Inc. * All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ /** * @file */ #ifndef MCA_MEMHEAP_BUDDY_COMPONENT_H #define MCA_MEMHEAP_BUDDY_COMPONENT_H BEGIN_C_DECLS /* * MEMHEAP module functions. */ OSHMEM_DECLSPEC extern mca_memheap_base_component_2_0_0_t mca_memheap_buddy_component; END_C_DECLS #endif
73c21c9b50556d1daf3c413df66b56a89c43446d
89db60818afeb3dc7c3b7abe9ceae155f074f7f2
/src/cmd/p.c
ba63dad8e14e70a21cc3365876d406d4768c3f6a
[ "bzip2-1.0.6", "LPL-1.02", "MIT" ]
permissive
9fans/plan9port
63c3d01928c6f8a8617d3ea6ecc05bac72391132
65c090346a38a8c30cb242d345aa71060116340c
refs/heads/master
2023-08-25T17:14:26.233105
2023-08-23T13:21:37
2023-08-23T18:47:08
26,095,474
1,645
468
NOASSERTION
2023-09-05T16:55:41
2014-11-02T22:40:13
C
UTF-8
C
false
false
1,494
c
p.c
#include <u.h> #include <libc.h> #include <bio.h> #define DEF 22 /* lines in chunk: 3*DEF == 66, #lines per nroff page */ Biobuf *cons; Biobuf bout; int pglen = DEF; void printfile(int); void main(int argc, char *argv[]) { int n; int f; if((cons = Bopen("/dev/tty", OREAD)) == 0) { fprint(2, "p: can't open /dev/tty\n"); exits("missing /dev/tty"); } Binit(&bout, 1, OWRITE); n = 0; while(argc > 1) { --argc; argv++; if(*argv[0] == '-'){ pglen = atoi(&argv[0][1]); if(pglen <= 0) pglen = DEF; } else { n++; f = open(argv[0], OREAD); if(f < 0){ fprint(2, "p: can't open %s\n", argv[0]); continue; } printfile(f); close(f); } } if(n == 0) printfile(0); exits(0); } void printfile(int f) { int i, j, n; char *s, *cmd; Biobuf *b; b = malloc(sizeof(Biobuf)); Binit(b, f, OREAD); for(;;){ for(i=1; i <= pglen; i++) { s = Brdline(b, '\n'); if(s == 0){ n = Blinelen(b); if(n > 0) /* line too long for Brdline */ for(j=0; j<n; j++) Bputc(&bout, Bgetc(b)); else{ /* true EOF */ free(b); return; } }else{ Bwrite(&bout, s, Blinelen(b)-1); if(i < pglen) Bwrite(&bout, "\n", 1); } } Bflush(&bout); getcmd: cmd = Brdline(cons, '\n'); if(cmd == 0 || *cmd == 'q') exits(0); cmd[Blinelen(cons)-1] = 0; if(*cmd == '!'){ if(fork() == 0){ dup(Bfildes(cons), 0); execl("/bin/rc", "rc", "-c", cmd+1, 0); } waitpid(); goto getcmd; } } }
ebbf42141b6f6cc6cf9efee3c0fe26c06bd07fe2
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/third_party/quickjs/quickjs.h
5af4890de4582ccb1b1bfbb7659cfbae95098a50
[ "MIT", "ISC" ]
permissive
jart/cosmopolitan
fb11b5658939023977060a7c6c71a74093d9cb44
0d748ad58e1063dd1f8560f18a0c75293b9415b7
refs/heads/master
2023-09-06T09:17:29.303607
2023-09-02T03:49:13
2023-09-02T03:50:18
272,457,606
11,887
435
ISC
2023-09-14T17:47:58
2020-06-15T14:16:13
C
UTF-8
C
false
false
40,171
h
quickjs.h
#ifndef COSMOPOLITAN_THIRD_PARTY_QUICKJS_QUICKJS_H_ #define COSMOPOLITAN_THIRD_PARTY_QUICKJS_QUICKJS_H_ #include "libc/intrin/likely.h" #include "libc/math.h" #include "libc/stdio/stdio.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* clang-format off */ #if (defined(__GNUC__) || defined(__clang__)) && !defined(__STRICT_ANSI__) #define __js_printf_like(f, a) __attribute__((__format__(__printf__, f, a))) #else #define __js_printf_like(a, b) #endif #define JS_BOOL int typedef struct JSRuntime JSRuntime; typedef struct JSContext JSContext; typedef struct JSObject JSObject; typedef struct JSClass JSClass; typedef uint32_t JSClassID; typedef uint32_t JSAtom; #if INTPTR_MAX >= INT64_MAX #define JS_PTR64 #define JS_PTR64_DEF(a) a #else #define JS_PTR64_DEF(a) #endif #ifndef JS_PTR64 #define JS_NAN_BOXING #endif enum { /* all tags with a reference count are negative */ JS_TAG_FIRST = -11, /* first negative tag */ JS_TAG_BIG_DECIMAL = -11, JS_TAG_BIG_INT = -10, JS_TAG_BIG_FLOAT = -9, JS_TAG_SYMBOL = -8, JS_TAG_STRING = -7, JS_TAG_MODULE = -3, /* used internally */ JS_TAG_FUNCTION_BYTECODE = -2, /* used internally */ JS_TAG_OBJECT = -1, JS_TAG_INT = 0, JS_TAG_BOOL = 1, JS_TAG_NULL = 2, JS_TAG_UNDEFINED = 3, JS_TAG_UNINITIALIZED = 4, JS_TAG_CATCH_OFFSET = 5, JS_TAG_EXCEPTION = 6, JS_TAG_FLOAT64 = 7, /* any larger tag is FLOAT64 if JS_NAN_BOXING */ }; typedef struct JSRefCountHeader { int ref_count; } JSRefCountHeader; #define JS_FLOAT64_NAN NAN #ifdef CONFIG_CHECK_JSVALUE /* JSValue consistency : it is not possible to run the code in this mode, but it is useful to detect simple reference counting errors. It would be interesting to modify a static C analyzer to handle specific annotations (clang has such annotations but only for objective C) */ typedef struct __JSValue *JSValue; typedef const struct __JSValue *JSValueConst; #define JS_VALUE_GET_TAG(v) (int)((uintptr_t)(v) & 0xf) /* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */ #define JS_VALUE_GET_NORM_TAG(v) JS_VALUE_GET_TAG(v) #define JS_VALUE_GET_INT(v) (int)((intptr_t)(v) >> 4) #define JS_VALUE_GET_BOOL(v) JS_VALUE_GET_INT(v) #define JS_VALUE_GET_FLOAT64(v) (double)JS_VALUE_GET_INT(v) #define JS_VALUE_GET_PTR(v) (void *)((intptr_t)(v) & ~0xf) #define JS_MKVAL(tag, val) (JSValue)(intptr_t)(((val) << 4) | (tag)) #define JS_MKPTR(tag, p) (JSValue)((intptr_t)(p) | (tag)) #define JS_TAG_IS_FLOAT64(tag) ((unsigned)(tag) == JS_TAG_FLOAT64) #define JS_NAN JS_MKVAL(JS_TAG_FLOAT64, 1) static inline JSValue __JS_NewFloat64(JSContext *ctx, double d) { return JS_MKVAL(JS_TAG_FLOAT64, (int)d); } static inline JS_BOOL JS_VALUE_IS_NAN(JSValue v) { return 0; } #elif defined(JS_NAN_BOXING) typedef uint64_t JSValue; #define JSValueConst JSValue #define JS_VALUE_GET_TAG(v) (int)((v) >> 32) #define JS_VALUE_GET_INT(v) (int)(v) #define JS_VALUE_GET_BOOL(v) (int)(v) #define JS_VALUE_GET_PTR(v) (void *)(intptr_t)(v) #define JS_MKVAL(tag, val) (((uint64_t)(tag) << 32) | (uint32_t)(val)) #define JS_MKPTR(tag, ptr) (((uint64_t)(tag) << 32) | (uintptr_t)(ptr)) #define JS_FLOAT64_TAG_ADDEND (0x7ff80000 - JS_TAG_FIRST + 1) /* quiet NaN encoding */ static inline double JS_VALUE_GET_FLOAT64(JSValue v) { union { JSValue v; double d; } u; u.v = v; u.v += (uint64_t)JS_FLOAT64_TAG_ADDEND << 32; return u.d; } #define JS_NAN (0x7ff8000000000000 - ((uint64_t)JS_FLOAT64_TAG_ADDEND << 32)) static inline JSValue __JS_NewFloat64(JSContext *ctx, double d) { union { double d; uint64_t u64; } u; JSValue v; u.d = d; /* normalize NaN */ if (UNLIKELY((u.u64 & 0x7fffffffffffffff) > 0x7ff0000000000000)) v = JS_NAN; else v = u.u64 - ((uint64_t)JS_FLOAT64_TAG_ADDEND << 32); return v; } #define JS_TAG_IS_FLOAT64(tag) ((unsigned)((tag) - JS_TAG_FIRST) >= (JS_TAG_FLOAT64 - JS_TAG_FIRST)) /* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */ static inline int JS_VALUE_GET_NORM_TAG(JSValue v) { uint32_t tag; tag = JS_VALUE_GET_TAG(v); if (JS_TAG_IS_FLOAT64(tag)) return JS_TAG_FLOAT64; else return tag; } static inline JS_BOOL JS_VALUE_IS_NAN(JSValue v) { uint32_t tag; tag = JS_VALUE_GET_TAG(v); return tag == (JS_NAN >> 32); } #else /* !JS_NAN_BOXING */ typedef union JSValueUnion { int32_t int32; double float64; void *ptr; } JSValueUnion; typedef struct JSValue { JSValueUnion u; int64_t tag; } JSValue; #define JSValueConst JSValue #define JS_VALUE_GET_TAG(v) ((int32_t)(v).tag) /* same as JS_VALUE_GET_TAG, but return JS_TAG_FLOAT64 with NaN boxing */ #define JS_VALUE_GET_NORM_TAG(v) JS_VALUE_GET_TAG(v) #define JS_VALUE_GET_INT(v) ((v).u.int32) #define JS_VALUE_GET_BOOL(v) ((v).u.int32) #define JS_VALUE_GET_FLOAT64(v) ((v).u.float64) #define JS_VALUE_GET_PTR(v) ((v).u.ptr) #define JS_MKVAL(tag, val) (JSValue){ (JSValueUnion){ .int32 = val }, tag } #define JS_MKPTR(tag, p) (JSValue){ (JSValueUnion){ .ptr = p }, tag } #define JS_TAG_IS_FLOAT64(tag) ((unsigned)(tag) == JS_TAG_FLOAT64) #define JS_NAN (JSValue){ .u.float64 = JS_FLOAT64_NAN, JS_TAG_FLOAT64 } static inline JSValue __JS_NewFloat64(JSContext *ctx, double d) { JSValue v; v.tag = JS_TAG_FLOAT64; v.u.float64 = d; return v; } static inline JS_BOOL JS_VALUE_IS_NAN(JSValue v) { union { double d; uint64_t u64; } u; if (v.tag != JS_TAG_FLOAT64) return 0; u.d = v.u.float64; return (u.u64 & 0x7fffffffffffffff) > 0x7ff0000000000000; } #endif /* !JS_NAN_BOXING */ #define JS_VALUE_IS_BOTH_INT(v1, v2) ((JS_VALUE_GET_TAG(v1) | JS_VALUE_GET_TAG(v2)) == 0) #define JS_VALUE_IS_BOTH_FLOAT(v1, v2) (JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(v1)) && JS_TAG_IS_FLOAT64(JS_VALUE_GET_TAG(v2))) #define JS_VALUE_GET_OBJ(v) ((JSObject *)JS_VALUE_GET_PTR(v)) #define JS_VALUE_GET_STRING(v) ((JSString *)JS_VALUE_GET_PTR(v)) #define JS_VALUE_HAS_REF_COUNT(v) ((unsigned)JS_VALUE_GET_TAG(v) >= (unsigned)JS_TAG_FIRST) /* special values */ #define JS_NULL JS_MKVAL(JS_TAG_NULL, 0) #define JS_UNDEFINED JS_MKVAL(JS_TAG_UNDEFINED, 0) #define JS_FALSE JS_MKVAL(JS_TAG_BOOL, 0) #define JS_TRUE JS_MKVAL(JS_TAG_BOOL, 1) #define JS_EXCEPTION JS_MKVAL(JS_TAG_EXCEPTION, 0) #define JS_UNINITIALIZED JS_MKVAL(JS_TAG_UNINITIALIZED, 0) /* flags for object properties */ #define JS_PROP_CONFIGURABLE (1 << 0) #define JS_PROP_WRITABLE (1 << 1) #define JS_PROP_ENUMERABLE (1 << 2) #define JS_PROP_C_W_E (JS_PROP_CONFIGURABLE | JS_PROP_WRITABLE | JS_PROP_ENUMERABLE) #define JS_PROP_LENGTH (1 << 3) /* used internally in Arrays */ #define JS_PROP_TMASK (3 << 4) /* mask for NORMAL, GETSET, VARREF, AUTOINIT */ #define JS_PROP_NORMAL (0 << 4) #define JS_PROP_GETSET (1 << 4) #define JS_PROP_VARREF (2 << 4) /* used internally */ #define JS_PROP_AUTOINIT (3 << 4) /* used internally */ /* flags for JS_DefineProperty */ #define JS_PROP_HAS_SHIFT 8 #define JS_PROP_HAS_CONFIGURABLE (1 << 8) #define JS_PROP_HAS_WRITABLE (1 << 9) #define JS_PROP_HAS_ENUMERABLE (1 << 10) #define JS_PROP_HAS_GET (1 << 11) #define JS_PROP_HAS_SET (1 << 12) #define JS_PROP_HAS_VALUE (1 << 13) /* throw an exception if false would be returned (JS_DefineProperty/JS_SetProperty) */ #define JS_PROP_THROW (1 << 14) /* throw an exception if false would be returned in strict mode (JS_SetProperty) */ #define JS_PROP_THROW_STRICT (1 << 15) #define JS_PROP_NO_ADD (1 << 16) /* internal use */ #define JS_PROP_NO_EXOTIC (1 << 17) /* internal use */ #define JS_DEFAULT_STACK_SIZE (256 * 1024) /* JS_Eval() flags */ #define JS_EVAL_TYPE_GLOBAL (0 << 0) /* global code (default) */ #define JS_EVAL_TYPE_MODULE (1 << 0) /* module code */ #define JS_EVAL_TYPE_DIRECT (2 << 0) /* direct call (internal use) */ #define JS_EVAL_TYPE_INDIRECT (3 << 0) /* indirect call (internal use) */ #define JS_EVAL_TYPE_MASK (3 << 0) #define JS_EVAL_FLAG_STRICT (1 << 3) /* force 'strict' mode */ #define JS_EVAL_FLAG_STRIP (1 << 4) /* force 'strip' mode */ /* compile but do not run. The result is an object with a JS_TAG_FUNCTION_BYTECODE or JS_TAG_MODULE tag. It can be executed with JS_EvalFunction(). */ #define JS_EVAL_FLAG_COMPILE_ONLY (1 << 5) /* don't include the stack frames before this eval in the Error() backtraces */ #define JS_EVAL_FLAG_BACKTRACE_BARRIER (1 << 6) typedef JSValue JSCFunction(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv); typedef JSValue JSCFunctionMagic(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic); typedef JSValue JSCFunctionData(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValue *func_data); typedef struct JSMallocState { size_t malloc_count; size_t malloc_size; size_t malloc_limit; void *opaque; /* user opaque */ } JSMallocState; typedef struct JSMallocFunctions { void *(*js_malloc)(JSMallocState *s, size_t size); void (*js_free)(JSMallocState *s, void *ptr); void *(*js_realloc)(JSMallocState *s, void *ptr, size_t size); size_t (*js_malloc_usable_size)(const void *ptr); } JSMallocFunctions; typedef struct JSGCObjectHeader JSGCObjectHeader; JSRuntime *JS_NewRuntime(void); /* info lifetime must exceed that of rt */ void JS_SetRuntimeInfo(JSRuntime *rt, const char *info); void JS_SetMemoryLimit(JSRuntime *rt, size_t limit); void JS_SetGCThreshold(JSRuntime *rt, size_t gc_threshold); /* use 0 to disable maximum stack size check */ void JS_SetMaxStackSize(JSRuntime *rt, size_t stack_size); /* should be called when changing thread to update the stack top value used to check stack overflow. */ void JS_UpdateStackTop(JSRuntime *rt); JSRuntime *JS_NewRuntime2(const JSMallocFunctions *mf, void *opaque); void JS_FreeRuntime(JSRuntime *rt); void *JS_GetRuntimeOpaque(JSRuntime *rt); void JS_SetRuntimeOpaque(JSRuntime *rt, void *opaque); typedef void JS_MarkFunc(JSRuntime *rt, JSGCObjectHeader *gp); void JS_MarkValue(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); void JS_RunGC(JSRuntime *rt); JS_BOOL JS_IsLiveObject(JSRuntime *rt, JSValueConst obj); JSContext *JS_NewContext(JSRuntime *rt); void JS_FreeContext(JSContext *s); JSContext *JS_DupContext(JSContext *ctx); void *JS_GetContextOpaque(JSContext *ctx); void JS_SetContextOpaque(JSContext *ctx, void *opaque); JSRuntime *JS_GetRuntime(JSContext *ctx); void JS_SetClassProto(JSContext *ctx, JSClassID class_id, JSValue obj); JSValue JS_GetClassProto(JSContext *ctx, JSClassID class_id); /* the following functions are used to select the intrinsic object to save memory */ JSContext *JS_NewContextRaw(JSRuntime *rt); void JS_AddIntrinsicBaseObjects(JSContext *ctx); void JS_AddIntrinsicDate(JSContext *ctx); void JS_AddIntrinsicEval(JSContext *ctx); void JS_AddIntrinsicStringNormalize(JSContext *ctx); void JS_AddIntrinsicRegExpCompiler(JSContext *ctx); void JS_AddIntrinsicRegExp(JSContext *ctx); void JS_AddIntrinsicJSON(JSContext *ctx); void JS_AddIntrinsicProxy(JSContext *ctx); void JS_AddIntrinsicMapSet(JSContext *ctx); void JS_AddIntrinsicTypedArrays(JSContext *ctx); void JS_AddIntrinsicPromise(JSContext *ctx); void JS_AddIntrinsicBigInt(JSContext *ctx); void JS_AddIntrinsicBigFloat(JSContext *ctx); void JS_AddIntrinsicBigDecimal(JSContext *ctx); /* enable operator overloading */ void JS_AddIntrinsicOperators(JSContext *ctx); /* enable "use math" */ void JS_EnableBignumExt(JSContext *ctx, JS_BOOL enable); JSValue js_string_codePointRange(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv); void *js_malloc_rt(JSRuntime *rt, size_t size); void js_free_rt(JSRuntime *rt, void *ptr); void *js_realloc_rt(JSRuntime *rt, void *ptr, size_t size); size_t js_malloc_usable_size_rt(JSRuntime *rt, const void *ptr); void *js_mallocz_rt(JSRuntime *rt, size_t size); void *js_malloc(JSContext *ctx, size_t size); void js_free(JSContext *ctx, void *ptr); void *js_realloc(JSContext *ctx, void *ptr, size_t size); size_t js_malloc_usable_size(JSContext *ctx, const void *ptr); void *js_realloc2(JSContext *ctx, void *ptr, size_t size, size_t *pslack); void *js_mallocz(JSContext *ctx, size_t size); char *js_strdup(JSContext *ctx, const char *str); char *js_strndup(JSContext *ctx, const char *s, size_t n); typedef struct JSMemoryUsage { int64_t malloc_size, malloc_limit, memory_used_size; int64_t malloc_count; int64_t memory_used_count; int64_t atom_count, atom_size; int64_t str_count, str_size; int64_t obj_count, obj_size; int64_t prop_count, prop_size; int64_t shape_count, shape_size; int64_t js_func_count, js_func_size, js_func_code_size; int64_t js_func_pc2line_count, js_func_pc2line_size; int64_t c_func_count, array_count; int64_t fast_array_count, fast_array_elements; int64_t binary_object_count, binary_object_size; } JSMemoryUsage; void JS_ComputeMemoryUsage(JSRuntime *rt, JSMemoryUsage *s); void JS_DumpMemoryUsage(FILE *fp, const JSMemoryUsage *s, JSRuntime *rt); /* atom support */ #define JS_ATOM_NULL 0 JSAtom JS_NewAtomLen(JSContext *ctx, const char *str, size_t len); JSAtom JS_NewAtom(JSContext *ctx, const char *str); JSAtom JS_NewAtomUInt32(JSContext *ctx, uint32_t n); JSAtom JS_DupAtom(JSContext *ctx, JSAtom v); void JS_FreeAtom(JSContext *ctx, JSAtom v); void JS_FreeAtomRT(JSRuntime *rt, JSAtom v); JSValue JS_AtomToValue(JSContext *ctx, JSAtom atom); JSValue JS_AtomToString(JSContext *ctx, JSAtom atom); const char *JS_AtomToCString(JSContext *ctx, JSAtom atom); JSAtom JS_ValueToAtom(JSContext *ctx, JSValueConst val); /* object class support */ typedef struct JSPropertyEnum { JS_BOOL is_enumerable; JSAtom atom; } JSPropertyEnum; typedef struct JSPropertyDescriptor { int flags; JSValue value; JSValue getter; JSValue setter; } JSPropertyDescriptor; typedef struct JSClassExoticMethods { /* Return -1 if exception (can only happen in case of Proxy object), FALSE if the property does not exists, TRUE if it exists. If 1 is returned, the property descriptor 'desc' is filled if != NULL. */ int (*get_own_property)(JSContext *ctx, JSPropertyDescriptor *desc, JSValueConst obj, JSAtom prop); /* '*ptab' should hold the '*plen' property keys. Return 0 if OK, -1 if exception. The 'is_enumerable' field is ignored. */ int (*get_own_property_names)(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen, JSValueConst obj); /* return < 0 if exception, or TRUE/FALSE */ int (*delete_property)(JSContext *ctx, JSValueConst obj, JSAtom prop); /* return < 0 if exception or TRUE/FALSE */ int (*define_own_property)(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValueConst val, JSValueConst getter, JSValueConst setter, int flags); /* The following methods can be emulated with the previous ones, so they are usually not needed */ /* return < 0 if exception or TRUE/FALSE */ int (*has_property)(JSContext *ctx, JSValueConst obj, JSAtom atom); JSValue (*get_property)(JSContext *ctx, JSValueConst obj, JSAtom atom, JSValueConst receiver); /* return < 0 if exception or TRUE/FALSE */ int (*set_property)(JSContext *ctx, JSValueConst obj, JSAtom atom, JSValueConst value, JSValueConst receiver, int flags); } JSClassExoticMethods; typedef void JSClassFinalizer(JSRuntime *rt, JSValue val); typedef void JSClassGCMark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func); #define JS_CALL_FLAG_CONSTRUCTOR (1 << 0) typedef JSValue JSClassCall(JSContext *ctx, JSValueConst func_obj, JSValueConst this_val, int argc, JSValueConst *argv, int flags); typedef struct JSClassDef { const char *class_name; JSClassFinalizer *finalizer; JSClassGCMark *gc_mark; /* if call != NULL, the object is a function. If (flags & JS_CALL_FLAG_CONSTRUCTOR) != 0, the function is called as a constructor. In this case, 'this_val' is new.target. A constructor call only happens if the object constructor bit is set (see JS_SetConstructorBit()). */ JSClassCall *call; /* XXX: suppress this indirection ? It is here only to save memory because only a few classes need these methods */ JSClassExoticMethods *exotic; } JSClassDef; JSClassID JS_NewClassID(JSClassID *pclass_id); int JS_NewClass(JSRuntime *rt, JSClassID class_id, const JSClassDef *class_def); int JS_IsRegisteredClass(JSRuntime *rt, JSClassID class_id); /* value handling */ forceinline JSValue JS_NewBool(JSContext *ctx, JS_BOOL val) { return JS_MKVAL(JS_TAG_BOOL, (val != 0)); } forceinline JSValue JS_NewInt32(JSContext *ctx, int32_t val) { return JS_MKVAL(JS_TAG_INT, val); } forceinline JSValue JS_NewCatchOffset(JSContext *ctx, int32_t val) { return JS_MKVAL(JS_TAG_CATCH_OFFSET, val); } forceinline JSValue JS_NewInt64(JSContext *ctx, int64_t val) { JSValue v; if (val == (int32_t)val) { v = JS_NewInt32(ctx, val); } else { v = __JS_NewFloat64(ctx, val); } return v; } forceinline JSValue JS_NewUint32(JSContext *ctx, uint32_t val) { JSValue v; if (val <= 0x7fffffff) { v = JS_NewInt32(ctx, val); } else { v = __JS_NewFloat64(ctx, val); } return v; } JSValue JS_NewBigInt64(JSContext *ctx, int64_t v); JSValue JS_NewBigUint64(JSContext *ctx, uint64_t v); forceinline JSValue JS_NewFloat64(JSContext *ctx, double d) { JSValue v; int32_t val; union { double d; uint64_t u; } u, t; u.d = d; val = (int32_t)d; t.d = val; /* -0 cannot be represented as integer, so we compare the bit representation */ if (u.u == t.u) { v = JS_MKVAL(JS_TAG_INT, val); } else { v = __JS_NewFloat64(ctx, d); } return v; } static inline JS_BOOL JS_IsNumber(JSValueConst v) { int tag = JS_VALUE_GET_TAG(v); return tag == JS_TAG_INT || JS_TAG_IS_FLOAT64(tag); } static inline JS_BOOL JS_IsBigInt(JSContext *ctx, JSValueConst v) { int tag = JS_VALUE_GET_TAG(v); return tag == JS_TAG_BIG_INT; } static inline JS_BOOL JS_IsBigFloat(JSValueConst v) { int tag = JS_VALUE_GET_TAG(v); return tag == JS_TAG_BIG_FLOAT; } static inline JS_BOOL JS_IsBigDecimal(JSValueConst v) { int tag = JS_VALUE_GET_TAG(v); return tag == JS_TAG_BIG_DECIMAL; } static inline JS_BOOL JS_IsBool(JSValueConst v) { return JS_VALUE_GET_TAG(v) == JS_TAG_BOOL; } static inline JS_BOOL JS_IsNull(JSValueConst v) { return JS_VALUE_GET_TAG(v) == JS_TAG_NULL; } static inline JS_BOOL JS_IsUndefined(JSValueConst v) { return JS_VALUE_GET_TAG(v) == JS_TAG_UNDEFINED; } static inline JS_BOOL JS_IsException(JSValueConst v) { return UNLIKELY(JS_VALUE_GET_TAG(v) == JS_TAG_EXCEPTION); } static inline JS_BOOL JS_IsUninitialized(JSValueConst v) { return UNLIKELY(JS_VALUE_GET_TAG(v) == JS_TAG_UNINITIALIZED); } static inline JS_BOOL JS_IsString(JSValueConst v) { return JS_VALUE_GET_TAG(v) == JS_TAG_STRING; } static inline JS_BOOL JS_IsSymbol(JSValueConst v) { return JS_VALUE_GET_TAG(v) == JS_TAG_SYMBOL; } static inline JS_BOOL JS_IsObject(JSValueConst v) { return JS_VALUE_GET_TAG(v) == JS_TAG_OBJECT; } JSValue JS_Throw(JSContext *ctx, JSValue obj); JSValue JS_GetException(JSContext *ctx); JS_BOOL JS_IsError(JSContext *ctx, JSValueConst val); void JS_ResetUncatchableError(JSContext *ctx); JSValue JS_NewError(JSContext *ctx); JSValue __js_printf_like(2, 3) JS_ThrowSyntaxError(JSContext *ctx, const char *fmt, ...); JSValue __js_printf_like(2, 3) JS_ThrowTypeError(JSContext *ctx, const char *fmt, ...); JSValue __js_printf_like(2, 3) JS_ThrowReferenceError(JSContext *ctx, const char *fmt, ...); JSValue __js_printf_like(2, 3) JS_ThrowRangeError(JSContext *ctx, const char *fmt, ...); JSValue __js_printf_like(2, 3) JS_ThrowInternalError(JSContext *ctx, const char *fmt, ...); JSValue JS_ThrowOutOfMemory(JSContext *ctx); void __JS_FreeValue(JSContext *ctx, JSValue v); static inline void JS_FreeValue(JSContext *ctx, JSValue v) { if (JS_VALUE_HAS_REF_COUNT(v)) { JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); if (--p->ref_count <= 0) { __JS_FreeValue(ctx, v); } } } void __JS_FreeValueRT(JSRuntime *rt, JSValue v); static inline void JS_FreeValueRT(JSRuntime *rt, JSValue v) { if (JS_VALUE_HAS_REF_COUNT(v)) { JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); if (--p->ref_count <= 0) { __JS_FreeValueRT(rt, v); } } } static inline JSValue JS_DupValue(JSContext *ctx, JSValueConst v) { if (JS_VALUE_HAS_REF_COUNT(v)) { JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); p->ref_count++; } return (JSValue)v; } static inline JSValue JS_DupValueRT(JSRuntime *rt, JSValueConst v) { if (JS_VALUE_HAS_REF_COUNT(v)) { JSRefCountHeader *p = (JSRefCountHeader *)JS_VALUE_GET_PTR(v); p->ref_count++; } return (JSValue)v; } int JS_ToBool(JSContext *ctx, JSValueConst val); /* return -1 for JS_EXCEPTION */ int JS_ToInt32(JSContext *ctx, int32_t *pres, JSValueConst val); static inline int JS_ToUint32(JSContext *ctx, uint32_t *pres, JSValueConst val) { return JS_ToInt32(ctx, (int32_t*)pres, val); } int JS_ToInt64(JSContext *ctx, int64_t *pres, JSValueConst val); int JS_ToIndex(JSContext *ctx, uint64_t *plen, JSValueConst val); int JS_ToFloat64(JSContext *ctx, double *pres, JSValueConst val); /* return an exception if 'val' is a Number */ int JS_ToBigInt64(JSContext *ctx, int64_t *pres, JSValueConst val); /* same as JS_ToInt64() but allow BigInt */ int JS_ToInt64Ext(JSContext *ctx, int64_t *pres, JSValueConst val); JSValue JS_NewStringLen(JSContext *ctx, const char *str1, size_t len1); JSValue JS_NewString(JSContext *ctx, const char *str); JSValue JS_NewAtomString(JSContext *ctx, const char *str); JSValue JS_ToString(JSContext *ctx, JSValueConst val); JSValue JS_ToPropertyKey(JSContext *ctx, JSValueConst val); const char *JS_ToCStringLen2(JSContext *ctx, size_t *plen, JSValueConst val1, JS_BOOL cesu8); static inline const char *JS_ToCStringLen(JSContext *ctx, size_t *plen, JSValueConst val1) { return JS_ToCStringLen2(ctx, plen, val1, 0); } static inline const char *JS_ToCString(JSContext *ctx, JSValueConst val1) { return JS_ToCStringLen2(ctx, NULL, val1, 0); } void JS_FreeCString(JSContext *ctx, const char *ptr); JSValue JS_NewObjectProtoClass(JSContext *ctx, JSValueConst proto, JSClassID class_id); JSValue JS_NewObjectClass(JSContext *ctx, int class_id); JSValue JS_NewObjectProto(JSContext *ctx, JSValueConst proto); JSValue JS_NewObject(JSContext *ctx); JS_BOOL JS_IsFunction(JSContext* ctx, JSValueConst val); JS_BOOL JS_IsConstructor(JSContext* ctx, JSValueConst val); JS_BOOL JS_SetConstructorBit(JSContext *ctx, JSValueConst func_obj, JS_BOOL val); JSValue JS_NewArray(JSContext *ctx); int JS_IsArray(JSContext *ctx, JSValueConst val); JSValue JS_GetPropertyInternal(JSContext *ctx, JSValueConst obj, JSAtom prop, JSValueConst receiver, JS_BOOL throw_ref_error); forceinline JSValue JS_GetProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop) { return JS_GetPropertyInternal(ctx, this_obj, prop, this_obj, 0); } JSValue JS_GetPropertyStr(JSContext *ctx, JSValueConst this_obj, const char *prop); JSValue JS_GetPropertyUint32(JSContext *ctx, JSValueConst this_obj, uint32_t idx); int JS_SetPropertyInternal(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValue val, int flags); static inline int JS_SetProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValue val) { return JS_SetPropertyInternal(ctx, this_obj, prop, val, JS_PROP_THROW); } int JS_SetPropertyUint32(JSContext *ctx, JSValueConst this_obj, uint32_t idx, JSValue val); int JS_SetPropertyInt64(JSContext *ctx, JSValueConst this_obj, int64_t idx, JSValue val); int JS_SetPropertyStr(JSContext *ctx, JSValueConst this_obj, const char *prop, JSValue val); int JS_HasProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop); int JS_IsExtensible(JSContext *ctx, JSValueConst obj); int JS_PreventExtensions(JSContext *ctx, JSValueConst obj); int JS_DeleteProperty(JSContext *ctx, JSValueConst obj, JSAtom prop, int flags); int JS_SetPrototype(JSContext *ctx, JSValueConst obj, JSValueConst proto_val); JSValue JS_GetPrototype(JSContext *ctx, JSValueConst val); #define JS_GPN_STRING_MASK (1 << 0) #define JS_GPN_SYMBOL_MASK (1 << 1) #define JS_GPN_PRIVATE_MASK (1 << 2) /* only include the enumerable properties */ #define JS_GPN_ENUM_ONLY (1 << 4) /* set theJSPropertyEnum.is_enumerable field */ #define JS_GPN_SET_ENUM (1 << 5) int JS_GetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen, JSValueConst obj, int flags); int JS_GetOwnProperty(JSContext *ctx, JSPropertyDescriptor *desc, JSValueConst obj, JSAtom prop); JSValue JS_Call(JSContext *ctx, JSValueConst func_obj, JSValueConst this_obj, int argc, JSValueConst *argv); JSValue JS_Invoke(JSContext *ctx, JSValueConst this_val, JSAtom atom, int argc, JSValueConst *argv); JSValue JS_CallConstructor(JSContext *ctx, JSValueConst func_obj, int argc, JSValueConst *argv); JSValue JS_CallConstructor2(JSContext *ctx, JSValueConst func_obj, JSValueConst new_target, int argc, JSValueConst *argv); JS_BOOL JS_DetectModule(const char *input, size_t input_len); /* 'input' must be zero terminated i.e. input[input_len] = '\0'. */ JSValue JS_Eval(JSContext *ctx, const char *input, size_t input_len, const char *filename, int eval_flags); /* same as JS_Eval() but with an explicit 'this_obj' parameter */ JSValue JS_EvalThis(JSContext *ctx, JSValueConst this_obj, const char *input, size_t input_len, const char *filename, int eval_flags); JSValue JS_GetGlobalObject(JSContext *ctx); int JS_IsInstanceOf(JSContext *ctx, JSValueConst val, JSValueConst obj); int JS_DefineProperty(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValueConst val, JSValueConst getter, JSValueConst setter, int flags); int JS_DefinePropertyValue(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValue val, int flags); int JS_DefinePropertyValueUint32(JSContext *ctx, JSValueConst this_obj, uint32_t idx, JSValue val, int flags); int JS_DefinePropertyValueStr(JSContext *ctx, JSValueConst this_obj, const char *prop, JSValue val, int flags); int JS_DefinePropertyGetSet(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValue getter, JSValue setter, int flags); void JS_SetOpaque(JSValue obj, void *opaque); void *JS_GetOpaque(JSValueConst obj, JSClassID class_id); void *JS_GetOpaque2(JSContext *ctx, JSValueConst obj, JSClassID class_id); /* 'buf' must be zero terminated i.e. buf[buf_len] = '\0'. */ JSValue JS_ParseJSON(JSContext *ctx, const char *buf, size_t buf_len, const char *filename); #define JS_PARSE_JSON_EXT (1 << 0) /* allow extended JSON */ JSValue JS_ParseJSON2(JSContext *ctx, const char *buf, size_t buf_len, const char *filename, int flags); JSValue JS_JSONStringify(JSContext *ctx, JSValueConst obj, JSValueConst replacer, JSValueConst space0); typedef void JSFreeArrayBufferDataFunc(JSRuntime *rt, void *opaque, void *ptr); JSValue JS_NewArrayBuffer(JSContext *ctx, uint8_t *buf, size_t len, JSFreeArrayBufferDataFunc *free_func, void *opaque, JS_BOOL is_shared); JSValue JS_NewArrayBufferCopy(JSContext *ctx, const uint8_t *buf, size_t len); void JS_DetachArrayBuffer(JSContext *ctx, JSValueConst obj); uint8_t *JS_GetArrayBuffer(JSContext *ctx, size_t *psize, JSValueConst obj); JSValue JS_GetTypedArrayBuffer(JSContext *ctx, JSValueConst obj, size_t *pbyte_offset, size_t *pbyte_length, size_t *pbytes_per_element); typedef struct { void *(*sab_alloc)(void *opaque, size_t size); void (*sab_free)(void *opaque, void *ptr); void (*sab_dup)(void *opaque, void *ptr); void *sab_opaque; } JSSharedArrayBufferFunctions; void JS_SetSharedArrayBufferFunctions(JSRuntime *rt, const JSSharedArrayBufferFunctions *sf); JSValue JS_NewPromiseCapability(JSContext *ctx, JSValue *resolving_funcs); /* is_handled = TRUE means that the rejection is handled */ typedef void JSHostPromiseRejectionTracker(JSContext *ctx, JSValueConst promise, JSValueConst reason, JS_BOOL is_handled, void *opaque); void JS_SetHostPromiseRejectionTracker(JSRuntime *rt, JSHostPromiseRejectionTracker *cb, void *opaque); /* return != 0 if the JS code needs to be interrupted */ typedef int JSInterruptHandler(JSRuntime *rt, void *opaque); void JS_SetInterruptHandler(JSRuntime *rt, JSInterruptHandler *cb, void *opaque); /* if can_block is TRUE, Atomics.wait() can be used */ void JS_SetCanBlock(JSRuntime *rt, JS_BOOL can_block); /* set the [IsHTMLDDA] internal slot */ void JS_SetIsHTMLDDA(JSContext *ctx, JSValueConst obj); typedef struct JSModuleDef JSModuleDef; /* return the module specifier (allocated with js_malloc()) or NULL if exception */ typedef char *JSModuleNormalizeFunc(JSContext *ctx, const char *module_base_name, const char *module_name, void *opaque); typedef JSModuleDef *JSModuleLoaderFunc(JSContext *ctx, const char *module_name, void *opaque); /* module_normalize = NULL is allowed and invokes the default module filename normalizer */ void JS_SetModuleLoaderFunc(JSRuntime *rt, JSModuleNormalizeFunc *module_normalize, JSModuleLoaderFunc *module_loader, void *opaque); /* return the import.meta object of a module */ JSValue JS_GetImportMeta(JSContext *ctx, JSModuleDef *m); JSAtom JS_GetModuleName(JSContext *ctx, JSModuleDef *m); /* JS Job support */ typedef JSValue JSJobFunc(JSContext *ctx, int argc, JSValueConst *argv); int JS_EnqueueJob(JSContext *ctx, JSJobFunc *job_func, int argc, JSValueConst *argv); JS_BOOL JS_IsJobPending(JSRuntime *rt); int JS_ExecutePendingJob(JSRuntime *rt, JSContext **pctx); /* Object Writer/Reader (currently only used to handle precompiled code) */ #define JS_WRITE_OBJ_BYTECODE (1 << 0) /* allow function/module */ #define JS_WRITE_OBJ_BSWAP (1 << 1) /* byte swapped output */ #define JS_WRITE_OBJ_SAB (1 << 2) /* allow SharedArrayBuffer */ #define JS_WRITE_OBJ_REFERENCE (1 << 3) /* allow object references to encode arbitrary object graph */ uint8_t *JS_WriteObject(JSContext *ctx, size_t *psize, JSValueConst obj, int flags); uint8_t *JS_WriteObject2(JSContext *ctx, size_t *psize, JSValueConst obj, int flags, uint8_t ***psab_tab, size_t *psab_tab_len); #define JS_READ_OBJ_BYTECODE (1 << 0) /* allow function/module */ #define JS_READ_OBJ_ROM_DATA (1 << 1) /* avoid duplicating 'buf' data */ #define JS_READ_OBJ_SAB (1 << 2) /* allow SharedArrayBuffer */ #define JS_READ_OBJ_REFERENCE (1 << 3) /* allow object references */ JSValue JS_ReadObject(JSContext *ctx, const uint8_t *buf, size_t buf_len, int flags); /* instantiate and evaluate a bytecode function. Only used when reading a script or module with JS_ReadObject() */ JSValue JS_EvalFunction(JSContext *ctx, JSValue fun_obj); /* load the dependencies of the module 'obj'. Useful when JS_ReadObject() returns a module. */ int JS_ResolveModule(JSContext *ctx, JSValueConst obj); /* only exported for os.Worker() */ JSAtom JS_GetScriptOrModuleName(JSContext *ctx, int n_stack_levels); /* only exported for os.Worker() */ JSModuleDef *JS_RunModule(JSContext *ctx, const char *basename, const char *filename); /* C function definition */ typedef enum JSCFunctionEnum { /* XXX: should rename for namespace isolation */ JS_CFUNC_generic, JS_CFUNC_generic_magic, JS_CFUNC_constructor, JS_CFUNC_constructor_magic, JS_CFUNC_constructor_or_func, JS_CFUNC_constructor_or_func_magic, JS_CFUNC_f_f, JS_CFUNC_f_f_f, JS_CFUNC_getter, JS_CFUNC_setter, JS_CFUNC_getter_magic, JS_CFUNC_setter_magic, JS_CFUNC_iterator_next, } JSCFunctionEnum; typedef union JSCFunctionType { JSCFunction *generic; JSValue (*generic_magic)(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic); JSCFunction *constructor; JSValue (*constructor_magic)(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv, int magic); JSCFunction *constructor_or_func; double (*f_f)(double); double (*f_f_f)(double, double); JSValue (*getter)(JSContext *ctx, JSValueConst this_val); JSValue (*setter)(JSContext *ctx, JSValueConst this_val, JSValueConst val); JSValue (*getter_magic)(JSContext *ctx, JSValueConst this_val, int magic); JSValue (*setter_magic)(JSContext *ctx, JSValueConst this_val, JSValueConst val, int magic); JSValue (*iterator_next)(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int *pdone, int magic); } JSCFunctionType; JSValue JS_NewCFunction2(JSContext *ctx, JSCFunction *func, const char *name, int length, JSCFunctionEnum cproto, int magic); JSValue JS_NewCFunctionData(JSContext *ctx, JSCFunctionData *func, int length, int magic, int data_len, JSValueConst *data); static inline JSValue JS_NewCFunction(JSContext *ctx, JSCFunction *func, const char *name, int length) { return JS_NewCFunction2(ctx, func, name, length, JS_CFUNC_generic, 0); } static inline JSValue JS_NewCFunctionMagic(JSContext *ctx, JSCFunctionMagic *func, const char *name, int length, JSCFunctionEnum cproto, int magic) { return JS_NewCFunction2(ctx, (JSCFunction *)func, name, length, cproto, magic); } void JS_SetConstructor(JSContext *ctx, JSValueConst func_obj, JSValueConst proto); /* C property definition */ typedef struct JSCFunctionListEntry { const char *name; uint8_t prop_flags; uint8_t def_type; int16_t magic; union { struct { uint8_t length; /* XXX: should move outside union */ uint8_t cproto; /* XXX: should move outside union */ JSCFunctionType cfunc; } func; struct { JSCFunctionType get; JSCFunctionType set; } getset; struct { const char *name; int base; } alias; struct { const struct JSCFunctionListEntry *tab; int len; } prop_list; const char *str; int32_t i32; int64_t i64; double f64; } u; } JSCFunctionListEntry; #define JS_DEF_CFUNC 0 #define JS_DEF_CGETSET 1 #define JS_DEF_CGETSET_MAGIC 2 #define JS_DEF_PROP_STRING 3 #define JS_DEF_PROP_INT32 4 #define JS_DEF_PROP_INT64 5 #define JS_DEF_PROP_DOUBLE 6 #define JS_DEF_PROP_UNDEFINED 7 #define JS_DEF_OBJECT 8 #define JS_DEF_ALIAS 9 /* Note: c++ does not like nested designators */ #define JS_CFUNC_DEF(name, length, func1) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, .u = { .func = { length, JS_CFUNC_generic, { .generic = func1 } } } } #define JS_CFUNC_MAGIC_DEF(name, length, func1, magic) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, magic, .u = { .func = { length, JS_CFUNC_generic_magic, { .generic_magic = func1 } } } } #define JS_CFUNC_SPECIAL_DEF(name, length, cproto, func1) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, 0, .u = { .func = { length, JS_CFUNC_ ## cproto, { .cproto = func1 } } } } #define JS_ITERATOR_NEXT_DEF(name, length, func1, magic) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_CFUNC, magic, .u = { .func = { length, JS_CFUNC_iterator_next, { .iterator_next = func1 } } } } #define JS_CGETSET_DEF(name, fgetter, fsetter) { name, JS_PROP_CONFIGURABLE, JS_DEF_CGETSET, 0, .u = { .getset = { .get = { .getter = fgetter }, .set = { .setter = fsetter } } } } #define JS_CGETSET_MAGIC_DEF(name, fgetter, fsetter, magic) { name, JS_PROP_CONFIGURABLE, JS_DEF_CGETSET_MAGIC, magic, .u = { .getset = { .get = { .getter_magic = fgetter }, .set = { .setter_magic = fsetter } } } } #define JS_PROP_STRING_DEF(name, cstr, prop_flags) { name, prop_flags, JS_DEF_PROP_STRING, 0, .u = { .str = cstr } } #define JS_PROP_INT32_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_INT32, 0, .u = { .i32 = val } } #define JS_PROP_INT64_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_INT64, 0, .u = { .i64 = val } } #define JS_PROP_DOUBLE_DEF(name, val, prop_flags) { name, prop_flags, JS_DEF_PROP_DOUBLE, 0, .u = { .f64 = val } } #define JS_PROP_UNDEFINED_DEF(name, prop_flags) { name, prop_flags, JS_DEF_PROP_UNDEFINED, 0, .u = { .i32 = 0 } } #define JS_OBJECT_DEF(name, tab, len, prop_flags) { name, prop_flags, JS_DEF_OBJECT, 0, .u = { .prop_list = { tab, len } } } #define JS_ALIAS_DEF(name, from) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_ALIAS, 0, .u = { .alias = { from, -1 } } } #define JS_ALIAS_BASE_DEF(name, from, base) { name, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE, JS_DEF_ALIAS, 0, .u = { .alias = { from, base } } } void JS_SetPropertyFunctionList(JSContext *ctx, JSValueConst obj, const JSCFunctionListEntry *tab, int len); /* C module definition */ typedef int JSModuleInitFunc(JSContext *ctx, JSModuleDef *m); JSModuleDef *JS_NewCModule(JSContext *ctx, const char *name_str, JSModuleInitFunc *func); /* can only be called before the module is instantiated */ int JS_AddModuleExport(JSContext *ctx, JSModuleDef *m, const char *name_str); int JS_AddModuleExportList(JSContext *ctx, JSModuleDef *m, const JSCFunctionListEntry *tab, int len); /* can only be called after the module is instantiated */ int JS_SetModuleExport(JSContext *ctx, JSModuleDef *m, const char *export_name, JSValue val); int JS_SetModuleExportList(JSContext *ctx, JSModuleDef *m, const JSCFunctionListEntry *tab, int len); /* clang-format on */ COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_QUICKJS_QUICKJS_H_ */
ec1f6b5424adbab4c8037f3df2cb783a684e5496
97c44f18459163c0baa546ab2578339b716c3238
/generic/BRGenericPrivate.h
0af60a304aab388ba59d5922b938a0442f1100d1
[ "MIT" ]
permissive
breadwallet/breadwallet-core
fe8a0ac99f3e47216860b2918c8ad14d3503b140
73566cb79f753954eccbf07d5ab25ca54741198e
refs/heads/develop
2023-08-21T22:27:45.735652
2020-02-06T18:43:51
2020-02-06T18:43:51
37,500,549
284
283
MIT
2023-03-21T09:07:32
2015-06-16T01:22:12
C
UTF-8
C
false
false
2,613
h
BRGenericPrivate.h
// // BRGenericPrivate.h // BRCore // // Created by Ed Gamble on 10/14/19. // Copyright © 2019 Breadwinner AG. All rights reserved. // // See the LICENSE file at the project root for license information. // See the CONTRIBUTORS file at the project root for a list of contributors. #ifndef BRGenericPrivate_h #define BRGenericPrivate_h #include "BRGeneric.h" #include "BRGenericHandlers.h" #if !defined(private_extern) #define private_extern extern #endif #define DECLARE_GENERIC_TYPE(name) \ struct BRGeneric##name##Record { \ const char *type; \ BRGeneric##name##Handlers handlers; \ BRGeneric##name##Ref ref; \ }; \ private_extern BRGeneric##name \ gen##name##AllocAndInit (const char *type, \ BRGeneric##name##Ref ref); #define IMPLEMENT_GENERIC_TYPE(name,field) \ private_extern BRGeneric##name \ gen##name##AllocAndInit (const char *type, \ BRGeneric##name##Ref ref) { \ BRGeneric##name __obj = calloc (1, sizeof (struct BRGeneric##name##Record)); \ __obj->type = type; \ __obj->handlers = genHandlerLookup(type)->field; \ __obj->ref = ref; \ return __obj; \ } struct BRGenericNetworkRecord { const char *type; BRGenericNetworkHandlers handlers; BRGenericNetworkRef ref; int isMainnet; }; private_extern BRGenericNetwork genNetworkAllocAndInit (const char *type, BRGenericNetworkRef ref, int isMainet); DECLARE_GENERIC_TYPE(Account) DECLARE_GENERIC_TYPE(Address) struct BRGenericTransferRecord { const char *type; char *uids; BRGenericTransferHandlers handlers; BRGenericTransferRef ref; BRGenericTransferState state; BRGenericTransferDirection direction; BRArrayOf(BRGenericTransferAttribute) attributes; }; private_extern BRGenericTransfer genTransferAllocAndInit (const char *type, BRGenericTransferRef ref); struct BRGenericWalletRecord { const char *type; BRGenericWalletHandlers handlers; BRGenericWalletRef ref; BRGenericFeeBasis defaultFeeBasis; }; private_extern BRGenericWallet genWalletAllocAndInit (const char *type, BRGenericWalletRef ref); //DECLARE_GENERIC_TYPE(Manager) #endif /* BRGenericPrivate_h */
0f924eada42956d22ad21fdb9ee7fbd678510e28
50dd46b8ece33f3cdd174284b15d1d51f89669d4
/third_party/tomcrypt/src/pk/pkcs1/pkcs_1_mgf1.c
5e17ba75abce9893b363d83db7efab8ef68a8a71
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
google/google-ctf
f99da1ee07729bbccb869fff1cbaed6a80e43bcc
df02323eaf945d15e124801c74abaadca2749dc7
refs/heads/master
2023-08-31T14:30:27.548081
2023-08-29T13:04:20
2023-08-29T13:04:20
131,317,137
4,136
607
Apache-2.0
2023-08-30T22:17:02
2018-04-27T15:56:03
Go
UTF-8
C
false
false
2,615
c
pkcs_1_mgf1.c
/* LibTomCrypt, modular cryptographic library -- Tom St Denis * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. */ #include "tomcrypt_private.h" /** @file pkcs_1_mgf1.c The Mask Generation Function (MGF1) for PKCS #1, Tom St Denis */ #ifdef LTC_PKCS_1 /** Perform PKCS #1 MGF1 (internal) @param hash_idx The index of the hash desired @param seed The seed for MGF1 @param seedlen The length of the seed @param mask [out] The destination @param masklen The length of the mask desired @return CRYPT_OK if successful */ int pkcs_1_mgf1(int hash_idx, const unsigned char *seed, unsigned long seedlen, unsigned char *mask, unsigned long masklen) { unsigned long hLen, x; ulong32 counter; int err; hash_state *md; unsigned char *buf; LTC_ARGCHK(seed != NULL); LTC_ARGCHK(mask != NULL); /* ensure valid hash */ if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) { return err; } /* get hash output size */ hLen = hash_descriptor[hash_idx].hashsize; /* allocate memory */ md = XMALLOC(sizeof(hash_state)); buf = XMALLOC(hLen); if (md == NULL || buf == NULL) { if (md != NULL) { XFREE(md); } if (buf != NULL) { XFREE(buf); } return CRYPT_MEM; } /* start counter */ counter = 0; while (masklen > 0) { /* handle counter */ STORE32H(counter, buf); ++counter; /* get hash of seed || counter */ if ((err = hash_descriptor[hash_idx].init(md)) != CRYPT_OK) { goto LBL_ERR; } if ((err = hash_descriptor[hash_idx].process(md, seed, seedlen)) != CRYPT_OK) { goto LBL_ERR; } if ((err = hash_descriptor[hash_idx].process(md, buf, 4)) != CRYPT_OK) { goto LBL_ERR; } if ((err = hash_descriptor[hash_idx].done(md, buf)) != CRYPT_OK) { goto LBL_ERR; } /* store it */ for (x = 0; x < hLen && masklen > 0; x++, masklen--) { *mask++ = buf[x]; } } err = CRYPT_OK; LBL_ERR: #ifdef LTC_CLEAN_STACK zeromem(buf, hLen); zeromem(md, sizeof(hash_state)); #endif XFREE(buf); XFREE(md); return err; } #endif /* LTC_PKCS_1 */ /* ref: HEAD -> develop */ /* git commit: 9c0d7085234bd6baba2ab8fd9eee62254599341c */ /* commit time: 2018-10-15 10:51:17 +0200 */
6be454310b65361402c21ae85ba201579de6683c
52c0949315583ba8898694cceacfaafaeab6f902
/third_party/libpg_query/src/postgres/include/catalog/pg_event_trigger.h
ca81a81dc66a3693bd525e79cc53e4cb5b809f6d
[ "MIT", "BSD-3-Clause", "PostgreSQL", "LicenseRef-scancode-unknown-license-reference" ]
permissive
cmu-db/noisepage
97093adcc9474419e063fdd97a5aa7a7ea6f3150
79276e68fe83322f1249e8a8be96bd63c583ae56
refs/heads/master
2023-08-29T05:51:04.628704
2021-11-05T14:12:08
2021-11-05T14:12:08
140,325,970
1,245
287
MIT
2022-11-08T02:06:48
2018-07-09T18:22:34
C++
UTF-8
C
false
false
1,950
h
pg_event_trigger.h
/*------------------------------------------------------------------------- * * pg_event_trigger.h * definition of the system "event trigger" relation (pg_event_trigger) * along with the relation's initial contents. * * * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/include/catalog/pg_event_trigger.h * * NOTES * the genbki.pl script reads this file and generates .bki * information from the DATA() statements. * *------------------------------------------------------------------------- */ #ifndef PG_EVENT_TRIGGER_H #define PG_EVENT_TRIGGER_H #include "catalog/genbki.h" /* ---------------- * pg_event_trigger definition. cpp turns this into * typedef struct FormData_pg_event_trigger * ---------------- */ #define EventTriggerRelationId 3466 CATALOG(pg_event_trigger,3466) { NameData evtname; /* trigger's name */ NameData evtevent; /* trigger's event */ Oid evtowner; /* trigger's owner */ Oid evtfoid; /* OID of function to be called */ char evtenabled; /* trigger's firing configuration WRT * session_replication_role */ #ifdef CATALOG_VARLEN text evttags[1]; /* command TAGs this event trigger targets */ #endif } FormData_pg_event_trigger; /* ---------------- * Form_pg_event_trigger corresponds to a pointer to a tuple with * the format of pg_event_trigger relation. * ---------------- */ typedef FormData_pg_event_trigger *Form_pg_event_trigger; /* ---------------- * compiler constants for pg_event_trigger * ---------------- */ #define Natts_pg_event_trigger 6 #define Anum_pg_event_trigger_evtname 1 #define Anum_pg_event_trigger_evtevent 2 #define Anum_pg_event_trigger_evtowner 3 #define Anum_pg_event_trigger_evtfoid 4 #define Anum_pg_event_trigger_evtenabled 5 #define Anum_pg_event_trigger_evttags 6 #endif /* PG_EVENT_TRIGGER_H */
f6500cf93eafdf45cb733ed7903ac7fe090d8fdf
010279e2ba272d09e9d2c4e903722e5faba2cf7a
/contrib/libs/zstd06/legacy/zstd_v03.h
38b1f6eb980699e139930312348a30cebec3b4ef
[ "BSD-2-Clause", "Apache-2.0" ]
permissive
catboost/catboost
854c1a1f439a96f1ae6b48e16644be20aa04dba2
f5042e35b945aded77b23470ead62d7eacefde92
refs/heads/master
2023-09-01T12:14:14.174108
2023-09-01T10:01:01
2023-09-01T10:22:12
97,556,265
8,012
1,425
Apache-2.0
2023-09-11T03:32:32
2017-07-18T05:29:04
Python
UTF-8
C
false
false
4,121
h
zstd_v03.h
#include <contrib/libs/zstd06/renames.h> /* zstd_v03 - decoder for 0.3 format Header File Copyright (C) 2015, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) 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 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. You can contact the author at : - zstd source repository : https://github.com/Cyan4973/zstd - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c */ #pragma once #if defined (__cplusplus) extern "C" { #endif /* ************************************* * Includes ***************************************/ #include <stddef.h> /* size_t */ /* ************************************* * Simple one-step function ***************************************/ /** ZSTDv03_decompress() : decompress ZSTD frames compliant with v0.3.x format compressedSize : is the exact source size maxOriginalSize : is the size of the 'dst' buffer, which must be already allocated. It must be equal or larger than originalSize, otherwise decompression will fail. return : the number of bytes decompressed into destination buffer (originalSize) or an errorCode if it fails (which can be tested using ZSTDv01_isError()) */ size_t ZSTDv03_decompress( void* dst, size_t maxOriginalSize, const void* src, size_t compressedSize); /** ZSTDv03_isError() : tells if the result of ZSTDv03_decompress() is an error */ unsigned ZSTDv03_isError(size_t code); /* ************************************* * Advanced functions ***************************************/ typedef struct ZSTDv03_Dctx_s ZSTDv03_Dctx; ZSTDv03_Dctx* ZSTDv03_createDCtx(void); size_t ZSTDv03_freeDCtx(ZSTDv03_Dctx* dctx); size_t ZSTDv03_decompressDCtx(void* ctx, void* dst, size_t maxOriginalSize, const void* src, size_t compressedSize); /* ************************************* * Streaming functions ***************************************/ size_t ZSTDv03_resetDCtx(ZSTDv03_Dctx* dctx); size_t ZSTDv03_nextSrcSizeToDecompress(ZSTDv03_Dctx* dctx); size_t ZSTDv03_decompressContinue(ZSTDv03_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize); /** Use above functions alternatively. ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue(). ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block. Result is the number of bytes regenerated within 'dst'. It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header. */ /* ************************************* * Prefix - version detection ***************************************/ #define ZSTDv03_magicNumber 0xFD2FB523 /* v0.3 */ #if defined (__cplusplus) } #endif
c4df569b6a88e88c05fe0d7697811de0a1fbac92
2753608f87a1e8fa312feced7af20917ea9cc004
/data structures/trie/c/BST.c
f03d48ce247c9838d190358acb560df350a54b9e
[ "MIT" ]
permissive
VAR-solutions/Algorithms
76faed6515367b6f27638b910dbc07f340fae56f
4ad6773e9675ef35aa858ca3969be5ddf6e3daea
refs/heads/dev
2023-08-15T11:37:26.048316
2021-08-03T07:00:28
2021-08-03T07:00:28
151,157,582
794
1,249
MIT
2023-07-29T00:28:36
2018-10-01T20:50:24
C++
UTF-8
C
false
false
2,657
c
BST.c
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *lc, *rc; }; struct node* least(struct node* root) { struct node* current = root; if(current != NULL) while(current->lc != NULL) current = current->lc; return current; } struct node* newnode(int data) { struct node* root = (struct node*)malloc(sizeof(struct node)); root->data = data; root->lc = NULL; root->rc = NULL; return root; } struct node* searchTree(struct node* root, int key) { if (key == root->data) return root; else if(key > root->data) return searchTree(root->rc, key); else return searchTree(root->lc, key); return NULL; } struct node* insertNode(struct node* root, int key) { if (root == NULL) return newnode(key); if (key < root->data) root->lc = insertNode(root->lc, key); else if(key > root->data) root->rc = insertNode(root->rc, key); //Impossible case return root; } struct node* deleteNode(struct node* root, int key) { if(root == NULL) return root; if (key < root->data) root->lc = deleteNode(root->lc, key); else if (key > root->data) root->rc = deleteNode(root->rc, key); else { if(root->lc == NULL) { struct node* temp = root->rc; free(root); return temp; } else if(root->rc == NULL) { struct node* temp = root->lc; free(root); return temp; } else { struct node* temp = root->rc; temp = least(temp); root->data = temp->data; root->rc = deleteNode(root->rc, temp->data); } } } void printInorder(struct node* node) { if (node == NULL) return; /* first recur on left child */ printInorder(node->lc); /* then print the data of node */ printf("%d ", node->data); /* now recur on right child */ printInorder(node->rc); } int main() { struct node* root = newnode(44); insertNode(root, 17); insertNode(root, 50); insertNode(root, 32); insertNode(root, 88); insertNode(root, 28); insertNode(root, 65); insertNode(root, 97); insertNode(root, 54); insertNode(root, 82); insertNode(root, 76); struct node* val = searchTree(root, 82); printf("Node found. value = %d\n", val->data); deleteNode(root, 50); printf("done first delete\n"); deleteNode(root, 65); printf("done second delete\n"); deleteNode(root, 76); printf("done third delete\n"); printInorder(root); return 0; }
afd32175e78215c65cbd6cb2326978eb5173ec01
68e115d504decf90cf8adaf1c373a220c059d8d7
/Library/PlatformMmcLib/QcomPlatformMmcLib.c
88784aa9a47f20abf2e09b3d93098770af28ea98
[ "GPL-1.0-or-later", "GPL-2.0-only", "BSD-2-Clause" ]
permissive
WOA-Project/Lumia950XLPkg
24fcad187d71488270b853d08fcdff542bbac5a2
0e7e24adb2ac80672ade1e56f9b538d99941328f
refs/heads/master
2023-08-11T09:20:00.600571
2022-09-14T09:09:51
2022-09-14T09:09:51
132,070,715
264
64
BSD-2-Clause
2022-12-18T20:27:21
2018-05-04T01:44:48
C
UTF-8
C
false
false
1,098
c
QcomPlatformMmcLib.c
#include <Base.h> #include <Library/LKEnvLib.h> #include <Library/QcomClockLib.h> #include <Library/QcomPlatformMmcLib.h> // Must come in order #include <Library/QcomPlatformMmcClockOverrideLib.h> #include <Chipset/mmc_sdhci.h> VOID LibQcomPlatformMmcClockInit(UINT32 interface) { CHAR8 clk_name[64]; INTN ret; snprintf(clk_name, sizeof(clk_name), "sdc%u_iface_clk", interface); /* enable interface clock */ ret = gClock->clk_get_set_enable(clk_name, 0, 1); if (ret) { DEBUG( (EFI_D_ERROR, "failed to set sdc%u_iface_clk ret = %d\n", interface, ret)); ASSERT(0); } } VOID LibQcomPlatformMmcClockConfig(UINT32 interface, UINT32 freq) { INTN ret = 0; CHAR8 clk_name[64]; freq = LibQcomPlatformMmcTranslateClockRate(freq); snprintf(clk_name, sizeof(clk_name), "sdc%u_core_clk", interface); ret = gClock->clk_get_set_enable(clk_name, freq, 1); if (ret) { DEBUG( (EFI_D_ERROR, "failed to set sdc%u_core_clk ret = %d\n", interface, ret)); ASSERT(0); } } VOID LibQcomPlatformMmcClockConfigCdc(UINT32 interface) {}
b31132cd68ba3cf0f3036966ee0229df9ee1c69a
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
/lib/libc/mingw/libsrc/ntddvdeo-uuid.c
740e677b7cef5fa7afddb8f5511d63e7bc68657f
[ "LGPL-2.0-or-later", "ZPL-2.1", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
ziglang/zig
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
refs/heads/master
2023-08-31T13:16:45.980913
2023-08-31T05:50:29
2023-08-31T05:50:29
40,276,274
25,560
2,399
MIT
2023-09-14T21:09:50
2015-08-06T00:51:28
Zig
UTF-8
C
false
false
188
c
ntddvdeo-uuid.c
/* from ntddvdeo.h */ #define INITGUID #include <basetyps.h> DEFINE_GUID(GUID_DEVINTERFACE_DISPLAY_ADAPTER, 0x5b45201d, 0xf2f2, 0x4f3b, 0x85, 0xbb, 0x30, 0xff, 0x1f, 0x95, 0x35, 0x99);