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
c55e1179b0479c2a0b6cb76796b0a6d16dca61a3
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/renesas/ra4m2-eco/ra/fsp/src/bsp/mcu/all/bsp_tfu.h
3ead89c369712ec7fdf6469ae0b624fb336c3435
[ "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,268
h
bsp_tfu.h
/*********************************************************************************************************************** * Copyright [2020-2022] Renesas Electronics Corporation and/or its affiliates. All Rights Reserved. * * This software and documentation are supplied by Renesas Electronics America Inc. and may only be used with products * of Renesas Electronics Corp. and its affiliates ("Renesas"). No other uses are authorized. Renesas products are * sold pursuant to Renesas terms and conditions of sale. Purchasers are solely responsible for the selection and use * of Renesas products and Renesas assumes no liability. No license, express or implied, to any intellectual property * right is granted by Renesas. This software is protected under all applicable laws, including copyright laws. Renesas * reserves the right to change or discontinue this software and/or this documentation. THE SOFTWARE AND DOCUMENTATION * IS DELIVERED TO YOU "AS IS," AND RENESAS MAKES NO REPRESENTATIONS OR WARRANTIES, AND TO THE FULLEST EXTENT * PERMISSIBLE UNDER APPLICABLE LAW, DISCLAIMS ALL WARRANTIES, WHETHER EXPLICITLY OR IMPLICITLY, INCLUDING WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT, WITH RESPECT TO THE SOFTWARE OR * DOCUMENTATION. RENESAS SHALL HAVE NO LIABILITY ARISING OUT OF ANY SECURITY VULNERABILITY OR BREACH. TO THE MAXIMUM * EXTENT PERMITTED BY LAW, IN NO EVENT WILL RENESAS BE LIABLE TO YOU IN CONNECTION WITH THE SOFTWARE OR DOCUMENTATION * (OR ANY PERSON OR ENTITY CLAIMING RIGHTS DERIVED FROM YOU) FOR ANY LOSS, DAMAGES, OR CLAIMS WHATSOEVER, INCLUDING, * WITHOUT LIMITATION, ANY DIRECT, CONSEQUENTIAL, SPECIAL, INDIRECT, PUNITIVE, OR INCIDENTAL DAMAGES; ANY LOST PROFITS, * OTHER ECONOMIC DAMAGE, PROPERTY DAMAGE, OR PERSONAL INJURY; AND EVEN IF RENESAS HAS BEEN ADVISED OF THE POSSIBILITY * OF SUCH LOSS, DAMAGES, CLAIMS OR COSTS. **********************************************************************************************************************/ #ifndef RENESAS_TFU #define RENESAS_TFU /*********************************************************************************************************************** * Includes <System Includes> , "Project Includes" **********************************************************************************************************************/ /* Mathematical Functions includes. */ #ifdef __cplusplus #include <cmath> #else #include <math.h> #endif /** Common macro for FSP header files. There is also a corresponding FSP_FOOTER macro at the end of this file. */ FSP_HEADER /*******************************************************************************************************************//** * @addtogroup BSP_MCU * @{ **********************************************************************************************************************/ /*********************************************************************************************************************** * Macro definitions **********************************************************************************************************************/ #define R_TFU_HYPOT_SCALING_FACTOR 0.607252935f #ifdef __GNUC__ /* and (arm)clang */ #if (__STDC_VERSION__ < 199901L) && defined(__STRICT_ANSI__) && !defined(__cplusplus) /* No form of inline is available, it happens only when -std=c89, gnu89 and * above are OK */ #warning \ "-std=c89 doesn't support type checking on TFU. Please use -std=gnu89 or higher for example -std=c99" #else #ifdef __GNUC_GNU_INLINE__ /* gnu89 semantics of inline and extern inline are essentially the exact * opposite of those in C99 */ #define BSP_TFU_INLINE extern inline __attribute__((always_inline)) #else /* __GNUC_STDC_INLINE__ */ #define BSP_TFU_INLINE static inline __attribute__((always_inline)) #endif #endif #elif __ICCARM__ #define BSP_TFU_INLINE #else #error "Compiler not supported!" #endif /*********************************************************************************************************************** * Typedef definitions **********************************************************************************************************************/ /*********************************************************************************************************************** * Exported global variables **********************************************************************************************************************/ /*********************************************************************************************************************** * Inline Functions **********************************************************************************************************************/ /*******************************************************************************************************************//** * Calculates sine of the given angle. * @param[in] angle The value of an angle in radian. * * @retval Sine value of an angle. **********************************************************************************************************************/ #if __ICCARM__ #pragma inline = forced #endif BSP_TFU_INLINE float __sinf (float angle) { /* Set the angle to R_TFU->SCDT1 */ R_TFU->SCDT1 = angle; /* Read sin from R_TFU->SCDT1 */ return R_TFU->SCDT1; } /*******************************************************************************************************************//** * Calculates cosine of the given angle. * @param[in] angle The value of an angle in radian. * * @retval Cosine value of an angle. **********************************************************************************************************************/ #if __ICCARM__ #pragma inline = forced #endif BSP_TFU_INLINE float __cosf (float angle) { /* Set the angle to R_TFU->SCDT1 */ R_TFU->SCDT1 = angle; /* Read cos from R_TFU->SCDT1 */ return R_TFU->SCDT0; } /*******************************************************************************************************************//** * Calculates sine and cosine of the given angle. * @param[in] angle The value of an angle in radian. * @param[out] sin Sine value of an angle. * @param[out] cos Cosine value of an angle. **********************************************************************************************************************/ #if __ICCARM__ #pragma inline = forced #endif BSP_TFU_INLINE void __sincosf (float angle, float * sin, float * cos) { /* Set the angle to R_TFU->SCDT1 */ R_TFU->SCDT1 = angle; /* Read sin from R_TFU->SCDT1 */ *sin = R_TFU->SCDT1; /* Read sin from R_TFU->SCDT1 */ *cos = R_TFU->SCDT0; } /*******************************************************************************************************************//** * Calculates the arc tangent based on given X-cordinate and Y-cordinate values. * @param[in] y_cord Y-Axis cordinate value. * @param[in] x_cord X-Axis cordinate value. * * @retval Arc tangent for given values. **********************************************************************************************************************/ #if __ICCARM__ #pragma inline = forced #endif BSP_TFU_INLINE float __atan2f (float y_cord, float x_cord) { /* Set X-cordinate to R_TFU->ATDT0 */ R_TFU->ATDT0 = x_cord; /* set Y-cordinate to R_TFU->ATDT1 */ R_TFU->ATDT1 = y_cord; /* Read arctan(y/x) from R_TFU->ATDT1 */ return R_TFU->ATDT1; } /*******************************************************************************************************************//** * Calculates the hypotenuse based on given X-cordinate and Y-cordinate values. * @param[in] y_cord Y-cordinate value. * @param[in] x_cord X-cordinate value. * * @retval Hypotenuse for given values. **********************************************************************************************************************/ #if __ICCARM__ #pragma inline = forced #endif BSP_TFU_INLINE float __hypotf (float x_cord, float y_cord) { /* Set X-coordinate to R_TFU->ATDT0 */ R_TFU->ATDT0 = x_cord; /* set Y-coordinate to R_TFU->ATDT1 */ R_TFU->ATDT1 = y_cord; /* Read sqrt (x_cord2 + y_cord2) from R_TFU->ATDT0 */ return R_TFU->ATDT0 * R_TFU_HYPOT_SCALING_FACTOR; } /*******************************************************************************************************************//** * Calculates the arc tangent and hypotenuse based on given X-cordinate and Y-cordinate values. * @param[in] y_cord Y-cordinate value. * @param[in] x_cord X-cordinate value. * @param[out] atan2 Arc tangent for given values. * @param[out] hypot Hypotenuse for given values. **********************************************************************************************************************/ #if __ICCARM__ #pragma inline = forced #endif BSP_TFU_INLINE void __atan2hypotf (float y_cord, float x_cord, float * atan2, float * hypot) { /* Set X-coordinate to R_TFU->ATDT0 */ R_TFU->ATDT0 = x_cord; /* set Y-coordinate to R_TFU->ATDT1 */ R_TFU->ATDT1 = y_cord; /* Read arctan(y/x) from R_TFU->ATDT1 */ *atan2 = R_TFU->ATDT1; /* Read sqrt (x_cord2 + y_cord2) from R_TFU->ATDT0 */ *hypot = R_TFU->ATDT0 * R_TFU_HYPOT_SCALING_FACTOR; } #if BSP_CFG_USE_TFU_MATHLIB #define sinf(x) __sinf(x) #define cosf(x) __cosf(x) #define atan2f(y, x) __atan2f(y, x) #define hypotf(x, y) __hypotf(x, y) #define atan2hypotf(y, x, a, h) __atan2hypotf(y, x, a, h) #define sincosf(a, s, c) __sincosf(a, s, c) #endif /*********************************************************************************************************************** * Exported global functions (to be accessed by other files) **********************************************************************************************************************/ /** @} (end addtogroup BSP_MCU) */ /** Common macro for FSP header files. There is also a corresponding FSP_HEADER macro at the top of this file. */ FSP_FOOTER #endif /* RENESAS_TFU */
b98d9060416de9ec743de4f457ae5563725c3296
331640994b1b6f66c1639278571ddbdc6c8c0751
/src/nxt_port_hash.c
b23acfb2847c79a74f3fffe6dcb6787e86557e31
[ "Apache-2.0" ]
permissive
nginx/unit
eabcd067eaa60f4bdcf0cfaffe7d9932add2c66a
9b22b6957bc87b3df002d0bc691fdae6a20abdac
refs/heads/master
2023-09-04T02:02:13.581700
2023-08-30T16:07:24
2023-08-30T16:07:24
102,627,638
4,649
452
Apache-2.0
2023-09-12T01:28:22
2017-09-06T15:45:30
C
UTF-8
C
false
false
2,967
c
nxt_port_hash.c
/* * Copyright (C) Max Romanov * Copyright (C) NGINX, Inc. */ #include <nxt_port_hash.h> // Explicitly using 32 bit types to avoid possible alignment. typedef struct { int32_t pid; uint32_t port_id; } nxt_pid_port_id_t; static nxt_int_t nxt_port_hash_test(nxt_lvlhsh_query_t *lhq, void *data) { nxt_port_t *port; nxt_pid_port_id_t *pid_port_id; port = data; pid_port_id = (nxt_pid_port_id_t *) lhq->key.start; if (lhq->key.length == sizeof(nxt_pid_port_id_t) && pid_port_id->pid == port->pid && pid_port_id->port_id == port->id) { return NXT_OK; } return NXT_DECLINED; } static const nxt_lvlhsh_proto_t lvlhsh_ports_proto nxt_aligned(64) = { NXT_LVLHSH_DEFAULT, nxt_port_hash_test, nxt_lvlhsh_alloc, nxt_lvlhsh_free, }; nxt_port_t * nxt_port_hash_retrieve(nxt_lvlhsh_t *port_hash) { return nxt_lvlhsh_retrieve(port_hash, &lvlhsh_ports_proto, NULL); } nxt_inline void nxt_port_hash_lhq(nxt_lvlhsh_query_t *lhq, nxt_pid_port_id_t *pid_port) { lhq->key_hash = nxt_murmur_hash2(pid_port, sizeof(nxt_pid_port_id_t)); lhq->key.length = sizeof(nxt_pid_port_id_t); lhq->key.start = (u_char *) pid_port; lhq->proto = &lvlhsh_ports_proto; lhq->pool = NULL; } nxt_int_t nxt_port_hash_add(nxt_lvlhsh_t *port_hash, nxt_port_t *port) { nxt_int_t res; nxt_pid_port_id_t pid_port; nxt_lvlhsh_query_t lhq; pid_port.pid = port->pid; pid_port.port_id = port->id; nxt_port_hash_lhq(&lhq, &pid_port); lhq.replace = 0; lhq.value = port; res = nxt_lvlhsh_insert(port_hash, &lhq); switch (res) { case NXT_OK: break; default: nxt_thread_log_error(NXT_LOG_WARN, "port #%d for pid %PI add failed", port->id, port->pid); break; } return res; } nxt_int_t nxt_port_hash_remove(nxt_lvlhsh_t *port_hash, nxt_port_t *port) { nxt_int_t res; nxt_pid_port_id_t pid_port; nxt_lvlhsh_query_t lhq; pid_port.pid = port->pid; pid_port.port_id = port->id; nxt_port_hash_lhq(&lhq, &pid_port); res = nxt_lvlhsh_delete(port_hash, &lhq); switch (res) { case NXT_OK: break; default: nxt_thread_log_error(NXT_LOG_WARN, "port #%d for pid %PI remove failed", port->id, port->pid); break; } return res; } nxt_port_t * nxt_port_hash_find(nxt_lvlhsh_t *port_hash, nxt_pid_t pid, nxt_port_id_t port_id) { nxt_pid_port_id_t pid_port; nxt_lvlhsh_query_t lhq; pid_port.pid = pid; pid_port.port_id = port_id; nxt_port_hash_lhq(&lhq, &pid_port); if (nxt_lvlhsh_find(port_hash, &lhq) == NXT_OK) { nxt_thread_log_debug("process port (%PI, %d) found", pid, port_id); return lhq.value; } nxt_thread_log_debug("process port (%PI, %d) not found", pid, port_id); return NULL; }
08c25c9c6866cb857c342e52174a65972ef6aa09
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/math/readstat/files/patch-src_readstat__variable.c
4bc2fe0c7ad8a06b1d414bebe7bfed7125e0bde5
[ "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
538
c
patch-src_readstat__variable.c
--- src/readstat_variable.c.orig 2020-08-25 16:29:50 UTC +++ src/readstat_variable.c @@ -2,10 +2,10 @@ #include <stdlib.h> #include "readstat.h" -static readstat_value_t make_blank_value(); +static readstat_value_t make_blank_value(void); static readstat_value_t make_double_value(double dval); -static readstat_value_t make_blank_value() { +static readstat_value_t make_blank_value(void) { readstat_value_t value = { .is_system_missing = 1, .v = { .double_value = NAN }, .type = READSTAT_TYPE_DOUBLE }; return value; }
86bec3f6d99eb53ff097b3af5db087158fd409c7
af92a18fc8396a47c6140c7cc16c8a761d1afd5a
/homeworks/1-bootloader/bootloader/pi-side/bootloader.c
0c22257bd6bca85ddd1e2c668b0d15737774832a
[]
no_license
dddrrreee/cs140e-win19
2cd1c67b66cf2a2dd8900144d67b41b1bc8466ba
5ace9ace5fd13de5c83e6f24b1d0cb158c9a6879
refs/heads/master
2020-04-15T13:51:30.165435
2020-01-29T06:26:34
2020-01-29T06:26:34
164,733,325
165
58
null
2019-01-10T06:48:44
2019-01-08T21:10:36
Python
UTF-8
C
false
false
1,588
c
bootloader.c
/* * very simple bootloader. more robust than xmodem. (that code seems to * have bugs in terms of recovery with inopportune timeouts.) */ #define __SIMPLE_IMPL__ #include "../shared-code/simple-boot.h" #include "libpi.small/rpi.h" static void send_byte(unsigned char uc) { uart_putc(uc); } static unsigned char get_byte(void) { return uart_getc(); } static unsigned get_uint(void) { unsigned u = get_byte(); u |= get_byte() << 8; u |= get_byte() << 16; u |= get_byte() << 24; return u; } static void put_uint(unsigned u) { send_byte((u >> 0) & 0xff); send_byte((u >> 8) & 0xff); send_byte((u >> 16) & 0xff); send_byte((u >> 24) & 0xff); } static void die(int code) { put_uint(code); reboot(); } // bootloader: // 1. wait for SOH, size, cksum from unix side. // 2. echo SOH, checksum(size), cksum back. // 3. wait for ACK. // 4. read the bytes, one at a time, copy them to ARMBASE. // 5. verify checksum. // 6. send ACK back. // 7. wait 500ms // 8. jump to ARMBASE. // void notmain(void) { uart_init(); // XXX: cs107e has this delay; doesn't seem to be required if // you drain the uart. delay_ms(500); /* XXX put your bootloader implementation here XXX */ // XXX: appears we need these delays or the unix side gets confused. // I believe it's b/c the code we call re-initializes the uart; could // disable that to make it a bit more clean. delay_ms(500); // run what client sent. BRANCHTO(ARMBASE); // should not get back here, but just in case. reboot(); }
535b1917db6c86b72281e8da9d4cd326b35587ff
8838eb997879add5759b6dfb23f9a646464e53ca
/src/tests/kernel/task/signal.c
0c5d62db2dce360c00fa77f7c0bbd71360741143
[ "BSD-2-Clause" ]
permissive
embox/embox
d6aacec876978522f01cdc4b8de37a668c6f4c80
98e3c06e33f3fdac10a29c069c20775568e0a6d1
refs/heads/master
2023-09-04T03:02:20.165042
2023-09-02T14:55:31
2023-09-02T14:55:31
33,078,138
1,087
325
BSD-2-Clause
2023-09-14T16:58:34
2015-03-29T15:27:48
C
UTF-8
C
false
false
1,423
c
signal.c
/** * @file * * @brief * * @date 07.12.2011 * @author Anton Bondarev */ #include <embox/test.h> #include <signal.h> #include <stdint.h> #include <unistd.h> #include <pthread.h> #include <kernel/task.h> #include <kernel/time/ktime.h> EMBOX_TEST_SUITE("test for task API"); static volatile char flag = 0; static volatile char flag2 = 0; static void sig_hnd(int sig) { flag = 1; task_exit(NULL); } static void *task_hnd(void *arg) { signal(9, sig_hnd); while(1) sleep(0); return NULL; } TEST_CASE("create task and send signal") { int tid = new_task("", task_hnd, NULL); ksleep(100); kill(tid, 9); ksleep(100); test_assert(flag != 0); } static void sig_hnd2(int sig) { if (sig == 9) { task_exit(NULL); } else { flag2 ++; } } static void *task_hnd2(void *arg) { signal(9, sig_hnd2); signal(1, sig_hnd2); while(1) sleep(0); return NULL; } TEST_CASE("create task and send him signal 3 times") { int tid = new_task("", task_hnd2, NULL); flag2 = 0; ksleep(100); kill(tid, 1); ksleep(100); kill(tid, 1); ksleep(100); kill(tid, 9); test_assert(flag2 == 2); } static void *thread_hnd(void *arg) { ksleep(1000); task_exit(NULL); return NULL; } static void *task_hnd_thread(void *arg) { struct thread *thd; pthread_create(&thd, 0, thread_hnd, NULL); return NULL; } TEST_CASE("create a task with 2 threads, kill it") { new_task("", task_hnd_thread, NULL); }
9784916cec817bb7e34daa66cd0e1999ffeda5dc
c741ef13c3fbdbba8416b835dc4314ca774cae48
/src/rr.h
04818dbfe3661b41d33bea0d4f4ed12f1386a4d9
[ "ISC", "LicenseRef-scancode-public-domain" ]
permissive
troglobit/watchdogd
708c1e29c1b699386d201b8e634f71998365cb2a
1d0acd1e16b96dc83c45f184e63dfd17687dd097
refs/heads/master
2022-06-22T04:20:58.037351
2022-06-20T19:20:18
2022-06-20T19:20:18
797,135
171
37
ISC
2022-06-20T19:20:19
2010-07-25T21:18:48
C
UTF-8
C
false
false
1,225
h
rr.h
/* Reset reason API for backend store * * Copyright (C) 2017-2020 Joachim Wiberg <troglobit@gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef RR_H_ #define RR_H_ extern int reset_reason_init (int enabled, char *file); extern int reset_reason_set (wdog_reason_t *reason, pid_t pid); extern int reset_reason_get (wdog_reason_t *reason, pid_t *pid); extern int reset_reason_clear (wdog_reason_t *reason); #endif /* RR_H_ */ /** * Local Variables: * c-file-style: "linux" * indent-tabs-mode: t * End: */
d126b1edbae8ecfb40168c3e73ec2875c2f9a6db
cff4428975e403e4ef02d75498b78cd1a610a01a
/src/box/sql/pragma.h
f319272d4bd3f055588d6d65fc9006e8e4bfbfd4
[ "BSD-2-Clause" ]
permissive
tarantool/tarantool
c1f252b642d223af62485dc21165c7f7c3354e7e
f58cc96f2798ddc5f492223897d0b77e4f902128
refs/heads/master
2023-09-03T15:16:29.144171
2023-08-31T11:39:28
2023-09-01T12:39:29
911,980
3,205
490
NOASSERTION
2023-09-14T17:58:17
2010-09-15T07:59:26
Lua
UTF-8
C
false
false
2,360
h
pragma.h
/** List of ID of pragmas. */ enum { PRAGMA_COLLATION_LIST = 0, PRAGMA_FOREIGN_KEY_LIST, PRAGMA_INDEX_INFO, PRAGMA_INDEX_LIST, PRAGMA_STATS, PRAGMA_TABLE_INFO, }; /** * Column names and types for pragmas. The type of the column is * the following value after its name. */ static const char *const pragCName[] = { /* Used by: table_info */ /* 0 */ "cid", /* 1 */ "integer", /* 2 */ "name", /* 3 */ "text", /* 4 */ "type", /* 3 */ "text", /* 6 */ "notnull", /* 1 */ "integer", /* 8 */ "dflt_value", /* 9 */ "text", /* 10 */ "pk", /* 11 */ "integer", /* Used by: stats */ /* 12 */ "table", /* 13 */ "text", /* 14 */ "index", /* 15 */ "text", /* 16 */ "width", /* 17 */ "integer", /* 18 */ "height", /* 19 */ "integer", /* Used by: index_info */ /* 20 */ "seqno", /* 21 */ "integer", /* 22 */ "cid", /* 23 */ "integer", /* 24 */ "name", /* 25 */ "text", /* 26 */ "desc", /* 27 */ "integer", /* 28 */ "coll", /* 29 */ "text", /* 30 */ "type", /* 31 */ "text", /* Used by: index_list */ /* 32 */ "seq", /* 33 */ "integer", /* 34 */ "name", /* 35 */ "text", /* 36 */ "unique", /* 37 */ "integer", /* Used by: collation_list */ /* 38 */ "seq", /* 39 */ "integer", /* 40 */ "name", /* 41 */ "text", /* Used by: foreign_key_list */ /* 42 */ "id", /* 43 */ "integer", /* 44 */ "seq", /* 45 */ "integer", /* 46 */ "table", /* 47 */ "text", /* 48 */ "from", /* 49 */ "text", /* 50 */ "to", /* 51 */ "text", /* 52 */ "on_update", /* 53 */ "text", /* 54 */ "on_delete", /* 55 */ "text", /* 56 */ "match", /* 57 */ "text", }; /** Definitions of all built-in pragmas */ struct PragmaName { /** Name of pragma. */ const char *const zName; /** Id of pragma. */ u8 ePragTyp; /** Start of column names in pragCName[] */ u8 iPragCName; /** Number of column names. */ u8 nPragCName; }; /** * The order of pragmas in this array is important: it has * to be sorted. For more info see pragma_locate function. */ static const struct PragmaName aPragmaName[] = { {"collation_list", PRAGMA_COLLATION_LIST, 38, 2}, {"foreign_key_list", PRAGMA_FOREIGN_KEY_LIST, 42, 8}, {"index_info", PRAGMA_INDEX_INFO, 20, 6}, {"index_list", PRAGMA_INDEX_LIST, 32, 3}, {"stats", PRAGMA_STATS, 12, 4}, {"table_info", PRAGMA_TABLE_INFO, 0, 6}, };
a1b2f6a4ff9051f29a12d9b27ca4421634e0ea6a
c2634ebec1d4448e372d174f459c3cbc03fd1edc
/lib/node_modules/@stdlib/math/base/ops/cmulf/src/main.c
2daefc4fa0f0a9a00eef78347e9a03ceb31fa333
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT", "SunPro", "BSD-3-Clause", "BSL-1.0", "LicenseRef-scancode-public-domain" ]
permissive
stdlib-js/stdlib
ede11aee78f08e4f78a0bb939cb0bc244850b55b
f10c6e7db1a2b15cdd2b6237dd0927466ebd7278
refs/heads/develop
2023-09-05T03:29:36.368208
2023-09-03T22:42:11
2023-09-03T22:42:11
54,614,238
4,163
230
Apache-2.0
2023-09-13T21:26:07
2016-03-24T04:19:52
JavaScript
UTF-8
C
false
false
1,634
c
main.c
/** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib 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 "stdlib/math/base/ops/cmulf.h" #include "stdlib/complex/float32.h" #include "stdlib/complex/reimf.h" /** * Multiplies two single-precision complex floating-point numbers. * * @param z1 input value * @param z2 input value * @return result * * @example * #include "stdlib/complex/float32.h" * #include "stdlib/complex/realf.h" * #include "stdlib/complex/imagf.h" * * stdlib_complex64_t z1 = stdlib_complex64( 5.0f, 3.0f ); * stdlib_complex64_t z2 = stdlib_complex64( -2.0f, 1.0f ); * * stdlib_complex64_t out = stdlib_base_cmulf( z1, z2 ); * * float re = stdlib_realf( out ); * // returns -13.0f * * float im = stdlib_imagf( out ); * // returns -1.0f */ stdlib_complex64_t stdlib_base_cmulf( const stdlib_complex64_t z1, const stdlib_complex64_t z2 ) { float re1; float re2; float im1; float im2; float re; float im; stdlib_reimf( z1, &re1, &im1 ); stdlib_reimf( z2, &re2, &im2 ); re = (re1*re2) - (im1*im2); im = (re1*im2) + (im1*re2); return stdlib_complex64( re, im ); }
e09f63563e81fae423333927ca60da2f1b3bd1b4
64c2e443aaeb703ea09656056ea07bfd99910971
/pocs/linux/cve-2023-2163/include/kernel_helpers.h
9d306c442458e4de23a376c15f0395b382ab4a85
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
google/security-research
cc117b0b1ddb357a9a03fc3f2aae63b181d68501
ab605f29076b1f809a977a48531d9a2fe9f4f82a
refs/heads/master
2023-08-13T20:46:32.879967
2023-08-09T16:57:42
2023-08-09T16:57:42
272,394,704
2,432
337
Apache-2.0
2023-09-13T07:54:55
2020-06-15T09:19:51
C
UTF-8
C
false
false
3,303
h
kernel_helpers.h
#ifndef _KERNEL_HELPERS_ #define _KERNEL_HELPERS_ #include "exploit_prims.h" #define XA_CHUNK_SHIFT 0x6 #define XA_CHUNK_SIZE 0x40 #define XA_RETRY_ENTRY xa_mk_internal(256) #define RADIX_TREE_RETRY XA_RETRY_ENTRY #define RADIX_TREE_MAP_SHIFT XA_CHUNK_SHIFT #define RADIX_TREE_MAP_SIZE (1UL << RADIX_TREE_MAP_SHIFT) #define RADIX_TREE_MAP_MASK (RADIX_TREE_MAP_SIZE-1) /* * The bottom two bits of the slot determine how the remaining bits in the * slot are interpreted: * * 00 - data pointer * 10 - internal entry * x1 - value entry * * The internal entry may be a pointer to the next level in the tree, a * sibling entry, or an indicator that the entry in this slot has been moved * to another location in the tree and the lookup should be restarted. While * NULL fits the 'data pointer' pattern, it means that there is no entry in * the tree for this index (no matter what level of the tree it is found at). * This means that storing a NULL entry in the tree is the same as deleting * the entry from the tree. */ #define RADIX_TREE_ENTRY_MASK 3UL #define RADIX_TREE_INTERNAL_NODE 2UL /** * struct xarray - The anchor of the XArray. * @xa_lock: Lock that protects the contents of the XArray. * * To use the xarray, define it statically or embed it in your data structure. * It is a very small data structure, so it does not usually make sense to * allocate it separately and keep a pointer to it in your data structure. * * You may use the xa_lock to protect your own data structures as well. */ /* * If all of the entries in the array are NULL, @xa_head is a NULL pointer. * If the only non-NULL entry in the array is at index 0, @xa_head is that * entry. If any other entry in the array is non-NULL, @xa_head points * to an @xa_node. */ struct xarray { int32_t xa_lock; int32_t xa_flags; void *xa_head; }; /* * xa_mk_internal() - Create an internal entry. * @v: Value to turn into an internal entry. * * Internal entries are used for a number of purposes. Entries 0-255 are * used for sibling entries (only 0-62 are used by the current code). 256 * is used for the retry entry. 257 is used for the reserved / zero entry. * Negative internal entries are used to represent errnos. Node pointers * are also tagged as internal entries in some situations. * * Context: Any context. * Return: An XArray internal entry corresponding to this value. */ static inline void *xa_mk_internal(unsigned long v) { return (void *)((v << 2) | 2); } #define radix_tree_root xarray #define radix_tree_node xa_node struct xa_node { unsigned char shift; /* Bits remaining in each slot */ unsigned char offset; /* Slot offset in parent */ unsigned char count; /* Total entry count */ unsigned char nr_values; /* Value entry count */ struct xa_node *parent; /* NULL at top of tree */ struct xarray *array; /* The array we belong to */ char filler[0x10]; void *slots[XA_CHUNK_SIZE]; }; struct idr { struct radix_tree_root idr_rt; unsigned int idr_base; unsigned int idr_next; }; struct pid_namespace { struct idr idr; }; struct pid *find_pid_ns(context *ctx, int process_id); #endif
899f3bbd9801fa347265c1785f582953a68ea557
08b91813241c91239b55cce7711ae307bec66eb5
/src/gui/widget_diff.h
0a53d59932e488ad96268a8985ba540350d32d6e
[ "MIT", "FSFUL" ]
permissive
lc-soft/LCUI
8711344e37237763033a9eca5353f99ad0c262d6
051bb7a4d5c5cb7f6d71a0d6e54d4063b268db9c
refs/heads/develop
2023-07-30T07:41:49.610626
2022-04-10T06:32:11
2022-04-10T06:51:34
5,293,802
4,353
405
MIT
2023-04-30T08:55:37
2012-08-04T07:09:40
C
UTF-8
C
false
false
2,707
h
widget_diff.h
/* * widget_diff.h -- Comparison of differences in component styles and layouts * * Copyright (c) 2020, Liu chao <lc-soft@live.cn> All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of LCUI nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** for check widget difference */ typedef struct LCUI_WidgetStyleDiffRec_ { int z_index; int display; float left; float right; float top; float bottom; float width; float height; float opacity; LCUI_BOOL visible; LCUI_Rect2F margin; LCUI_Rect2F padding; LCUI_StyleValue position; LCUI_BorderStyle border; LCUI_BoxShadowStyle shadow; LCUI_BackgroundStyle background; LCUI_WidgetBoxModelRec box; LCUI_FlexBoxLayoutStyle flex; LCUI_BOOL should_add_invalid_area; } LCUI_WidgetStyleDiffRec, *LCUI_WidgetStyleDiff; typedef struct LCUI_WidgetLayoutDiffRec_ { LCUI_BOOL should_add_invalid_area; LCUI_WidgetBoxModelRec box; } LCUI_WidgetLayoutDiffRec, *LCUI_WidgetLayoutDiff; void Widget_InitStyleDiff(LCUI_Widget w, LCUI_WidgetStyleDiff diff); void Widget_BeginStyleDiff(LCUI_Widget w, LCUI_WidgetStyleDiff diff); int Widget_EndStyleDiff(LCUI_Widget w, LCUI_WidgetStyleDiff diff); void Widget_BeginLayoutDiff(LCUI_Widget w, LCUI_WidgetLayoutDiff diff); int Widget_EndLayoutDiff(LCUI_Widget w, LCUI_WidgetLayoutDiff diff);
8f5bad3b77405181bb65f2b3ba5f7d5fa156d475
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
/games/py-renpy/patches/patch-module_subpixel.c
7afc24a59b5073a02354c9f3de0d1c82643e8c54
[]
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
337
c
patch-module_subpixel.c
$NetBSD: patch-module_subpixel.c,v 1.1 2017/06/24 19:39:47 adam Exp $ Fix for duplicate symbol PyGAME_C_API. --- module/subpixel.c.orig 2017-06-24 17:57:56.000000000 +0000 +++ module/subpixel.c @@ -7,7 +7,7 @@ */ #include "renpy.h" -#include <pygame/pygame.h> +#include <pygame/_pygame.h> #include <stdio.h> #include <math.h>
a12f28d44a8a80528d993c4bcef77b1fb0730221
c9bc99866cfab223c777cfb741083be3e9439d81
/product/synquacer/scp_ramfw/config_mhu.c
d1f28674dc2921deff8cae46eb66743f1474368c
[ "BSD-3-Clause" ]
permissive
ARM-software/SCP-firmware
4738ca86ce42d82588ddafc2226a1f353ff2c797
f6bcca436768359ffeadd84d65e8ea0c3efc7ef1
refs/heads/master
2023-09-01T16:13:36.962036
2023-08-17T13:00:20
2023-08-31T07:43:37
134,399,880
211
165
NOASSERTION
2023-09-13T14:27:10
2018-05-22T10:35:56
C
UTF-8
C
false
false
1,257
c
config_mhu.c
/* * Arm SCP/MCP Software * Copyright (c) 2018-2021, Arm Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include "config_mhu.h" #include "synquacer_mmap.h" #include <mod_mhu.h> #include <fwk_element.h> #include <fwk_id.h> #include <fwk_module.h> #include <fmw_cmsis.h> static const struct fwk_element mhu_element_table[] = { [SCP_SYNQUACER_MHU_DEVICE_IDX_SCP_AP_S] = { .name = "MHU_SCP_AP_S", .sub_element_count = 1, .data = &((struct mod_mhu_device_config) { .irq = MHU_SEC_SCP_AP_IRQn, .in = MHU_AP_TO_SCP_S(0), .out = MHU_SCP_TO_AP_S(0), }) }, [SCP_SYNQUACER_MHU_DEVICE_IDX_SCP_AP_NS] = { .name = "MHU_SCP_AP_NS", .sub_element_count = 1, .data = &((struct mod_mhu_device_config) { .irq = MHU_NON_SEC_SCP_AP_IRQn, .in = MHU_AP_TO_SCP_NS(0), .out = MHU_SCP_TO_AP_NS(0), }) }, [SCP_SYNQUACER_MHU_DEVICE_IDX_COUNT] = { 0 }, }; static const struct fwk_element *mhu_get_element_table(fwk_id_t module_id) { return mhu_element_table; } const struct fwk_module_config config_mhu = { .elements = FWK_MODULE_DYNAMIC_ELEMENTS(mhu_get_element_table), };
138685bbae2d2b9503cf40e18c39c61504910aa1
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
/lib/libc/wasi/libc-top-half/musl/src/internal/libc.h
355c3a4e2398d9b6c8ea2805d9a010ffc489ebc9
[ "BSD-3-Clause", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-musl-exception", "MIT", "LLVM-exception", "Apache-2.0", "NCSA" ]
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
1,859
h
libc.h
#ifndef LIBC_H #define LIBC_H #include <stdlib.h> #include <stdio.h> #include <limits.h> struct __locale_map; struct __locale_struct { const struct __locale_map *cat[6]; }; struct tls_module { struct tls_module *next; void *image; size_t len, size, align, offset; }; struct __libc { #ifdef __wasilibc_unmodified_upstream char can_do_threads; #endif #if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT) char threaded; #endif #ifdef __wasilibc_unmodified_upstream // WASI doesn't currently use any code that needs "secure" mode char secure; #endif #if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT) volatile signed char need_locks; int threads_minus_1; #endif #ifdef __wasilibc_unmodified_upstream // WASI has no auxv size_t *auxv; #endif #ifdef __wasilibc_unmodified_upstream // WASI use different TLS implement struct tls_module *tls_head; size_t tls_size, tls_align, tls_cnt; #endif #ifdef __wasilibc_unmodified_upstream // WASI doesn't get the page size from auxv size_t page_size; #endif struct __locale_struct global_locale; #if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT) #else struct __locale_struct *current_locale; #endif }; #ifndef PAGE_SIZE #define PAGE_SIZE libc.page_size #endif extern hidden struct __libc __libc; #define libc __libc hidden void __init_libc(char **, char *); hidden void __init_tls(size_t *); hidden void __init_ssp(void *); hidden void __libc_start_init(void); hidden void __funcs_on_exit(void); hidden void __funcs_on_quick_exit(void); hidden void __libc_exit_fini(void); hidden void __fork_handler(int); extern hidden size_t __hwcap; extern hidden size_t __sysinfo; extern char *__progname, *__progname_full; extern hidden const char __libc_version[]; hidden void __synccall(void (*)(void *), void *); hidden int __setxid(int, int, int, int); #endif
c7ed03de4b13378999febcff364111d7b1f6aafd
7744859512f027ef0da8b1bde0f8518e631b98eb
/soh/src/code/padmgr.c
4735a259ce3c6b43f061091cb099b803d00349f7
[]
no_license
HarbourMasters/Shipwright
7f70b9470e4f9a117f3fe2d6e4deb776b8742182
0e7c6585239c0d7ea2c039b8b8cb7eaedf8928a9
refs/heads/develop
2023-08-31T20:50:56.253521
2023-08-30T17:34:06
2023-08-30T17:34:06
472,575,717
2,104
459
null
2023-09-14T20:29:01
2022-03-22T01:42:52
C
UTF-8
C
false
false
17,159
c
padmgr.c
#include "global.h" #include "vt.h" #include <string.h> #include "soh/Enhancements/game-interactor/GameInteractor.h" s32 D_8012D280 = 1; void OTRControllerCallback(uint8_t rumble); OSMesgQueue* PadMgr_LockSerialMesgQueue(PadMgr* padMgr) { OSMesgQueue* ctrlrQ = NULL; if (D_8012D280 > 2) { // "serialMsgQ Waiting for lock" osSyncPrintf("%2d %d serialMsgQロック待ち %08x %08x %08x\n", osGetThreadId(NULL), padMgr->serialMsgQ.validCount, padMgr, &padMgr->serialMsgQ, &ctrlrQ); } osRecvMesg(&padMgr->serialMsgQ, (OSMesg*)&ctrlrQ, OS_MESG_BLOCK); if (D_8012D280 > 2) { // "serialMsgQ Locked" osSyncPrintf("%2d %d serialMsgQをロックしました %08x\n", osGetThreadId(NULL), padMgr->serialMsgQ.validCount, ctrlrQ); } return ctrlrQ; } void PadMgr_UnlockSerialMesgQueue(PadMgr* padMgr, OSMesgQueue* ctrlrQ) { if (D_8012D280 > 2) { // "serialMsgQ Unlock" osSyncPrintf("%2d %d serialMsgQロック解除します %08x %08x %08x\n", osGetThreadId(NULL), padMgr->serialMsgQ.validCount, padMgr, &padMgr->serialMsgQ, ctrlrQ); } osSendMesgPtr(&padMgr->serialMsgQ, ctrlrQ, OS_MESG_BLOCK); if (D_8012D280 > 2) { // "serialMsgQ Unlocked" osSyncPrintf("%2d %d serialMsgQロック解除しました %08x %08x %08x\n", osGetThreadId(NULL), padMgr->serialMsgQ.validCount, padMgr, &padMgr->serialMsgQ, ctrlrQ); } } void PadMgr_LockPadData(PadMgr* padMgr) { osRecvMesg(&padMgr->lockMsgQ, NULL, OS_MESG_BLOCK); } void PadMgr_UnlockPadData(PadMgr* padMgr) { osSendMesgPtr(&padMgr->lockMsgQ, NULL, OS_MESG_BLOCK); } void PadMgr_RumbleControl(PadMgr* padMgr) { static u32 errcnt = 0; static u32 frame; s32 temp = 1; s32 triedRumbleComm; OSMesgQueue* ctrlrQ = PadMgr_LockSerialMesgQueue(padMgr); s32 var4; s32 i; triedRumbleComm = 0; for (i = 0; i < 4; i++) { if (padMgr->ctrlrIsConnected[i]) { if (padMgr->padStatus[i].status & 1) { if (padMgr->pakType[i] == temp) { if (padMgr->rumbleEnable[i] != 0) { if (padMgr->rumbleCounter[i] < 3) { // clang-format off osSyncPrintf(VT_FGCOL(YELLOW)); // clang-format on // "Vibration pack jumble jumble"? osSyncPrintf("padmgr: %dコン: %s\n", i + 1, "振動パック ぶるぶるぶるぶる"); osSyncPrintf(VT_RST); if (__osMotorAccess(&padMgr->pfs[i], temp) != 0) { padMgr->pakType[i] = 0; osSyncPrintf(VT_FGCOL(YELLOW)); // "A communication error has occurred with the vibration pack" osSyncPrintf("padmgr: %dコン: %s\n", i + 1, "振動パックで通信エラーが発生しました"); osSyncPrintf(VT_RST); } else { padMgr->rumbleCounter[i] = 3; } triedRumbleComm = 1; } } else { if (padMgr->rumbleCounter[i] != 0) { // clang-format off osSyncPrintf(VT_FGCOL(YELLOW)); // clang-format on // "Stop vibration pack" osSyncPrintf("padmgr: %dコン: %s\n", i + 1, "振動パック 停止"); osSyncPrintf(VT_RST); if (osMotorStop(&padMgr->pfs[i]) != 0) { padMgr->pakType[i] = 0; osSyncPrintf(VT_FGCOL(YELLOW)); // "A communication error has occurred with the vibration pack" osSyncPrintf("padmgr: %dコン: %s\n", i + 1, "振動パックで通信エラーが発生しました"); osSyncPrintf(VT_RST); } else { padMgr->rumbleCounter[i]--; } triedRumbleComm = 1; } } } } else { if (padMgr->pakType[i] != 0) { if (padMgr->pakType[i] == 1) { osSyncPrintf(VT_FGCOL(YELLOW)); // "It seems that a vibration pack was pulled out" osSyncPrintf("padmgr: %dコン: %s\n", i + 1, "振動パックが抜かれたようです"); osSyncPrintf(VT_RST); padMgr->pakType[i] = 0; } else { osSyncPrintf(VT_FGCOL(YELLOW)); // "It seems that a controller pack that is not a vibration pack was pulled out" osSyncPrintf("padmgr: %dコン: %s\n", i + 1, "振動パックではないコントローラパックが抜かれたようです"); osSyncPrintf(VT_RST); padMgr->pakType[i] = 0; } } } } } if (!triedRumbleComm) { i = frame % 4; if (padMgr->ctrlrIsConnected[i] && (padMgr->padStatus[i].status & 1) && (padMgr->pakType[i] != 1)) { var4 = osMotorInit(ctrlrQ, &padMgr->pfs[i], i); if (var4 == 0) { padMgr->pakType[i] = 1; osMotorStart(&padMgr->pfs[i]); osMotorStop(&padMgr->pfs[i]); osSyncPrintf(VT_FGCOL(YELLOW)); // "Recognized vibration pack" osSyncPrintf("padmgr: %dコン: %s\n", i + 1, "振動パックを認識しました"); osSyncPrintf(VT_RST); } else if (var4 == 11) { padMgr->pakType[i] = 2; } else if (var4 == 4) { LOG_NUM("++errcnt", ++errcnt); osSyncPrintf(VT_FGCOL(YELLOW)); // "Controller pack communication error" osSyncPrintf("padmgr: %dコン: %s\n", i + 1, "コントローラパックの通信エラー"); osSyncPrintf(VT_RST); } } } frame++; PadMgr_UnlockSerialMesgQueue(padMgr, ctrlrQ); } void PadMgr_RumbleStop(PadMgr* padMgr) { s32 i; OSMesgQueue* ctrlrQ = PadMgr_LockSerialMesgQueue(padMgr); for (i = 0; i < 4; i++) { if (osMotorInit(ctrlrQ, &padMgr->pfs[i], i) == 0) { #if 0 if ((gFaultStruct.msgId == 0) && (padMgr->rumbleOnFrames != 0)) { osSyncPrintf(VT_FGCOL(YELLOW)); // "Stop vibration pack" osSyncPrintf("padmgr: %dコン: %s\n", i + 1, "振動パック 停止"); osSyncPrintf(VT_RST); } #endif osMotorStop(&padMgr->pfs[i]); } } PadMgr_UnlockSerialMesgQueue(padMgr, ctrlrQ); } void PadMgr_RumbleReset(PadMgr* padMgr) { padMgr->rumbleOffFrames = 3; } void PadMgr_RumbleSetSingle(PadMgr* padMgr, u32 ctrlr, u32 rumble) { padMgr->rumbleEnable[ctrlr] = rumble; padMgr->rumbleOnFrames = 240; } void PadMgr_RumbleSet(PadMgr* padMgr, u8* ctrlrRumbles) { s32 i; for (i = 0; i < 4; i++) { padMgr->rumbleEnable[i] = ctrlrRumbles[i]; } padMgr->rumbleOnFrames = 240; } #define PAUSE_BUFFER_INPUT_BLOCK_ID 0 void PadMgr_ProcessInputs(PadMgr* padMgr) { s32 i; Input* input; OSContPad* padnow1; // original name s32 buttonDiff; PadMgr_LockPadData(padMgr); input = &padMgr->inputs[0]; padnow1 = &padMgr->pads[0]; for (i = 0; i < padMgr->nControllers; i++, input++, padnow1++) { input->prev = input->cur; switch (padnow1->err_no) { case 0: input->cur = *padnow1; if (GameInteractor_DisableZTargetingActive()) { input->cur.button &= ~(BTN_Z); } uint32_t emulatedButtons = GameInteractor_GetEmulatedButtons(); if (emulatedButtons) { input->cur.button |= emulatedButtons; GameInteractor_SetEmulatedButtons(0); } if (GameInteractor_ReverseControlsActive()) { if (input->cur.stick_x == -128) { input->cur.stick_x = 127; } else { input->cur.stick_x *= -1; } if (input->cur.stick_y == -128) { input->cur.stick_y = 127; } else { input->cur.stick_y *= -1; } } if (!padMgr->ctrlrIsConnected[i]) { padMgr->ctrlrIsConnected[i] = true; osSyncPrintf(VT_FGCOL(YELLOW)); osSyncPrintf("padmgr: %dコン: %s\n", i + 1, "認識しました"); // "Recognized" osSyncPrintf(VT_RST); } break; case 4: input->cur = input->prev; LOG_NUM("this->Key_switch[i]", padMgr->ctrlrIsConnected[i]); osSyncPrintf(VT_FGCOL(YELLOW)); // "Overrun error occurred" osSyncPrintf("padmgr: %dコン: %s\n", i + 1, "オーバーランエラーが発生"); osSyncPrintf(VT_RST); break; case 8: input->cur.button = 0; input->cur.stick_x = 0; input->cur.stick_y = 0; input->cur.err_no = padnow1->err_no; if (padMgr->ctrlrIsConnected[i]) { padMgr->ctrlrIsConnected[i] = false; padMgr->pakType[i] = 0; padMgr->rumbleCounter[i] = 0xFF; osSyncPrintf(VT_FGCOL(YELLOW)); // "Do not respond"? osSyncPrintf("padmgr: %dコン: %s\n", i + 1, "応答しません"); osSyncPrintf(VT_RST); } break; default: LOG_HEX("padnow1->errno", padnow1->err_no); Fault_AddHungupAndCrash(__FILE__, __LINE__); } // When 3 frames are left on easy pause buffer, re-apply the last held inputs to the prev inputs // to compute the pressed difference. This makes it so previously held inputs are continued as "held", // but new inputs when unpausing are "pressed" out of the pause menu. if (CVarGetInteger("gCheatEasyPauseBufferTimer", 0) == 3) { input->prev.button = CVarGetInteger("gCheatEasyPauseBufferLastInputs", 0); } buttonDiff = input->prev.button ^ input->cur.button; input->press.button |= (u16)(buttonDiff & input->cur.button); input->rel.button |= (u16)(buttonDiff & input->prev.button); PadUtils_UpdateRelXY(input); input->press.stick_x += (s8)(input->cur.stick_x - input->prev.stick_x); input->press.stick_y += (s8)(input->cur.stick_y - input->prev.stick_y); } uint8_t rumble = (padMgr->rumbleEnable[0] > 0); OTRControllerCallback(rumble); PadMgr_UnlockPadData(padMgr); } void PadMgr_HandleRetraceMsg(PadMgr* padMgr) { s32 i; OSMesgQueue* queue = PadMgr_LockSerialMesgQueue(padMgr); u32 mask; osContStartReadData(queue); if (padMgr->retraceCallback) { padMgr->retraceCallback(padMgr, padMgr->retraceCallbackValue); } osRecvMesg(queue, NULL, OS_MESG_BLOCK); osContGetReadData(padMgr->pads); for (i = 0; i < __osMaxControllers; i++) { padMgr->padStatus[i].status = Controller_ShouldRumble(i); } if (padMgr->preNMIShutdown) { memset(padMgr->pads, 0, sizeof(padMgr->pads)); } PadMgr_ProcessInputs(padMgr); osContStartQuery(queue); osRecvMesg(queue, NULL, OS_MESG_BLOCK); osContGetQuery(padMgr->padStatus); PadMgr_UnlockSerialMesgQueue(padMgr, queue); mask = 0; for (i = 0; i < 4; i++) { if (padMgr->padStatus[i].err_no == 0) { if (padMgr->padStatus[i].type == CONT_TYPE_NORMAL) { mask |= 1 << i; } else { //LOG_HEX("this->pad_status[i].type", padMgr->padStatus[i].type); // "An unknown type of controller is connected" //osSyncPrintf("知らない種類のコントローラが接続されています\n"); } } } padMgr->validCtrlrsMask = mask; /* if (gFaultStruct.msgId) { PadMgr_RumbleStop(padMgr); } else */ if (padMgr->rumbleOffFrames > 0) { --padMgr->rumbleOffFrames; PadMgr_RumbleStop(padMgr); } else if (padMgr->rumbleOnFrames == 0) { PadMgr_RumbleStop(padMgr); } else if (!padMgr->preNMIShutdown) { PadMgr_RumbleControl(padMgr); --padMgr->rumbleOnFrames; } } void PadMgr_HandlePreNMI(PadMgr* padMgr) { osSyncPrintf("padmgr_HandlePreNMI()\n"); padMgr->preNMIShutdown = true; PadMgr_RumbleReset(padMgr); } void PadMgr_RequestPadData(PadMgr* padMgr, Input* inputs, s32 mode) { s32 i; Input* ogInput; Input* newInput; s32 buttonDiff; PadMgr_LockPadData(padMgr); ogInput = &padMgr->inputs[0]; newInput = &inputs[0]; for (i = 0; i < 4; i++) { if (mode != 0) { *newInput = *ogInput; ogInput->press.button = 0; ogInput->press.stick_x = 0; ogInput->press.stick_y = 0; ogInput->rel.button = 0; } else { newInput->prev = newInput->cur; newInput->cur = ogInput->cur; buttonDiff = newInput->prev.button ^ newInput->cur.button; newInput->press.button = newInput->cur.button & buttonDiff; newInput->rel.button = newInput->prev.button & buttonDiff; PadUtils_UpdateRelXY(newInput); newInput->press.stick_x += (s8)(newInput->cur.stick_x - newInput->prev.stick_x); newInput->press.stick_y += (s8)(newInput->cur.stick_y - newInput->prev.stick_y); } ogInput++; newInput++; } PadMgr_UnlockPadData(padMgr); } void PadMgr_ThreadEntry(PadMgr* padMgr) { s16* mesg = NULL; s32 exit; //osSyncPrintf("コントローラスレッド実行開始\n"); // "Controller thread execution start" exit = false; while (!exit) { if ((D_8012D280 > 2) && (padMgr->interruptMsgQ.validCount == 0)) { // "Waiting for controller thread event" osSyncPrintf("コントローラスレッドイベント待ち %lld\n", OS_CYCLES_TO_USEC(osGetTime())); } osRecvMesg(&padMgr->interruptMsgQ, (OSMesg*)&mesg, OS_MESG_BLOCK); //LOG_CHECK_NULL_POINTER("msg", mesg); PadMgr_HandleRetraceMsg(padMgr); break; #if 0 switch (*mesg) { case OS_SC_RETRACE_MSG: if (D_8012D280 > 2) { osSyncPrintf("padmgr_HandleRetraceMsg START %lld\n", OS_CYCLES_TO_USEC(osGetTime())); } PadMgr_HandleRetraceMsg(padMgr); if (D_8012D280 > 2) { osSyncPrintf("padmgr_HandleRetraceMsg END %lld\n", OS_CYCLES_TO_USEC(osGetTime())); } break; case OS_SC_PRE_NMI_MSG: PadMgr_HandlePreNMI(padMgr); break; case OS_SC_NMI_MSG: exit = true; break; } #endif } // OTRTODO: Removed due to crash //IrqMgr_RemoveClient(padMgr->irqMgr, &padMgr->irqClient); //osSyncPrintf("コントローラスレッド実行終了\n"); // "Controller thread execution end" } void PadMgr_Init(PadMgr* padMgr, OSMesgQueue* siIntMsgQ, IrqMgr* irqMgr, OSId id, OSPri priority, void* stack) { osSyncPrintf("パッドマネージャ作成 padmgr_Create()\n"); // "Pad Manager creation" memset(padMgr, 0, sizeof(PadMgr)); padMgr->irqMgr = irqMgr; osCreateMesgQueue(&padMgr->interruptMsgQ, padMgr->interruptMsgBuf, 4); // OTRTODO: Removed due to crash //IrqMgr_AddClient(padMgr->irqMgr, &padMgr->irqClient, &padMgr->interruptMsgQ); osCreateMesgQueue(&padMgr->serialMsgQ, padMgr->serialMsgBuf, 1); PadMgr_UnlockSerialMesgQueue(padMgr, siIntMsgQ); osCreateMesgQueue(&padMgr->lockMsgQ, padMgr->lockMsgBuf, 1); PadMgr_UnlockPadData(padMgr); PadSetup_Init(siIntMsgQ, (u8*)&padMgr->validCtrlrsMask, padMgr->padStatus); padMgr->nControllers = 4; osContSetCh(padMgr->nControllers); osCreateThread(&padMgr->thread, id, (void (*)(void*))PadMgr_ThreadEntry, padMgr, stack, priority); osStartThread(&padMgr->thread); }
8f8c9d55e6f87089d9b29c333386df077bec2830
309f9b2a66a89c2edcc300129359e8a79c37ceee
/mm/mmap.c
d15834313150439373fc596a33fab6fa93aa3da5
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
mikaku/Fiwix
47df5c58aaf9879e2bad6cf6b88d4ed9dfa57392
8a1352db07c843e3c53c3aa7f72f518acdab7d7b
refs/heads/master
2023-09-03T18:38:02.823376
2023-09-01T09:43:56
2023-09-01T09:43:56
129,542,762
195
18
MIT
2023-08-16T10:39:20
2018-04-14T18:15:22
C
UTF-8
C
false
false
11,606
c
mmap.c
/* * fiwix/mm/mmap.c * * Copyright 2018-2022, Jordi Sanfeliu. All rights reserved. * Distributed under the terms of the Fiwix License. */ #include <fiwix/asm.h> #include <fiwix/mm.h> #include <fiwix/fs.h> #include <fiwix/fcntl.h> #include <fiwix/stat.h> #include <fiwix/process.h> #include <fiwix/mman.h> #include <fiwix/errno.h> #include <fiwix/stdio.h> #include <fiwix/string.h> #include <fiwix/shm.h> void merge_vma_regions(struct vma *, struct vma *); void show_vma_regions(struct proc *p) { __ino_t inode; int major, minor; char *section; char r, w, x, f; struct vma *vma; unsigned int n; int count; vma = p->vma_table; n = 0; printk("num address range flag offset dev inode mod section cnt\n"); printk("---- --------------------- ---- ---------- ----- ---------- --- ------- ----\n"); while(vma) { r = vma->prot & PROT_READ ? 'r' : '-'; w = vma->prot & PROT_WRITE ? 'w' : '-'; x = vma->prot & PROT_EXEC ? 'x' : '-'; if(vma->flags & MAP_SHARED) { f = 's'; } else if(vma->flags & MAP_PRIVATE) { f = 'p'; } else { f = '-'; } switch(vma->s_type) { case P_TEXT: section = "text "; break; case P_DATA: section = "data "; break; case P_BSS: section = "bss "; break; case P_HEAP: section = "heap "; break; case P_STACK: section = "stack"; break; case P_MMAP: section = "mmap "; break; #ifdef CONFIG_SYSVIPC case P_SHM: section = "shm "; break; #endif /* CONFIG_SYSVIPC */ default: section = NULL; break; } inode = major = minor = count = 0; if(vma->inode) { inode = vma->inode->inode; major = MAJOR(vma->inode->dev); minor = MINOR(vma->inode->dev); count = vma->inode->count; } printk("[%02d] 0x%08x-0x%08x %c%c%c%c 0x%08x %02d:%02d %- 10u <%d> [%s] (%d)\n", n, vma->start, vma->end, r, w, x, f, vma->offset, major, minor, inode, vma->o_mode, section, count); vma = vma->next; n++; } if(!n) { printk("[no vma regions]\n"); } } /* insert a vma structure into vma_table sorted by address */ static void insert_vma_region(struct vma *vma) { struct vma *vmat; vmat = current->vma_table; while(vmat) { if(vmat->start > vma->start) { break; } vmat = vmat->next; } if(!vmat) { /* append */ vma->prev = current->vma_table->prev; current->vma_table->prev->next = vma; current->vma_table->prev = vma; } else { /* insert */ vma->prev = vmat->prev; vma->next = vmat; if(vmat == current->vma_table) { /* insert in the head */ current->vma_table = vma; } else { /* insert in the middle */ vmat->prev->next = vma; } vmat->prev = vma; } if(vma != vma->prev && vma->start >= vma->prev->start && vma->start <= vma->prev->end) { merge_vma_regions(vma->prev, vma); } } static void add_vma_region(struct vma *vma) { unsigned int flags; SAVE_FLAGS(flags); CLI(); if(!current->vma_table) { current->vma_table = vma; current->vma_table->prev = vma; } else { insert_vma_region(vma); } RESTORE_FLAGS(flags); } static void del_vma_region(struct vma *vma) { unsigned int flags; struct vma *tmp; tmp = vma; if(!vma->next && !vma->prev) { printk("WARNING: %s(): trying to delete an unexistent vma region (%x).\n", __FUNCTION__, vma->start); return; } SAVE_FLAGS(flags); CLI(); if(vma->next) { vma->next->prev = vma->prev; } if(vma->prev) { if(vma != current->vma_table) { vma->prev->next = vma->next; } } if(!vma->next) { current->vma_table->prev = vma->prev; } if(vma == current->vma_table) { current->vma_table = vma->next; } RESTORE_FLAGS(flags); kfree((unsigned int)tmp); } static int can_be_merged(struct vma *a, struct vma *b) { if((a->end == b->start) && (a->prot == b->prot) && (a->flags == b->flags) && (a->offset == b->offset) && (a->s_type == b->s_type) && #ifdef CONFIG_SYSVIPC (a->s_type != P_SHM) && #endif /* CONFIG_SYSVIPC */ (a->inode == b->inode)) { return 1; } return 0; } static int free_vma_region(struct vma *vma, unsigned int start, __ssize_t length) { struct vma *new; if(start + length < vma->end) { if(!(new = (struct vma *)kmalloc(sizeof(struct vma)))) { return -ENOMEM; } memset_b(new, 0, sizeof(struct vma)); new->start = start + length; new->end = vma->end; new->prot = vma->prot; new->flags = vma->flags; new->offset = vma->offset; new->s_type = vma->s_type; new->inode = vma->inode; new->o_mode = vma->o_mode; } else { new = NULL; } if(vma->start == start) { if(vma->inode) { iput(vma->inode); } del_vma_region(vma); } else { vma->end = start; } if(new) { add_vma_region(new); } return 0; } /* this assumes that vma_table is sorted by address */ void merge_vma_regions(struct vma *a, struct vma *b) { struct vma *new; if(b->start == a->end) { if(can_be_merged(a, b)) { a->end = b->end; del_vma_region(b); return; } } if((b->start < a->end)) { if(!(new = (struct vma *)kmalloc(sizeof(struct vma)))) { return; } new->start = b->end; new->end = a->end; new->prot = a->prot; new->flags = a->flags; new->offset = a->offset; new->s_type = a->s_type; new->inode = a->inode; new->o_mode = a->o_mode; free_vma_pages(a, b->start, b->end - b->start); invalidate_tlb(); a->end = b->start; if(a->start == a->end) { del_vma_region(a); } if(new->start >= new->end) { kfree((unsigned int)new); } else { insert_vma_region(new); } } } void free_vma_pages(struct vma *vma, unsigned int start, __size_t length) { unsigned int n, offset; unsigned int *pgdir, *pgtbl; unsigned int pde, pte; struct page *pg; int page; pgdir = (unsigned int *)P2V(current->tss.cr3); pgtbl = NULL; for(n = 0; n < (length / PAGE_SIZE); n++) { pde = GET_PGDIR(start + (n * PAGE_SIZE)); pte = GET_PGTBL(start + (n * PAGE_SIZE)); if(pgdir[pde] & PAGE_PRESENT) { pgtbl = (unsigned int *)P2V((pgdir[pde] & PAGE_MASK)); if(pgtbl[pte] & PAGE_PRESENT) { /* make sure to not free reserved pages */ page = pgtbl[pte] >> PAGE_SHIFT; pg = &page_table[page]; if(pg->flags & PAGE_RESERVED) { continue; } if(vma->prot & PROT_WRITE && vma->flags & MAP_SHARED) { offset = start - vma->start + vma->offset + n * PAGE_SIZE; write_page(pg, vma->inode, offset, PAGE_SIZE); } kfree(P2V(pgtbl[pte]) & PAGE_MASK); current->rss--; #ifdef CONFIG_SYSVIPC if(vma->object) { shm_rss--; } #endif /* CONFIG_SYSVIPC */ pgtbl[pte] = 0; /* check if a page table can be freed */ for(pte = 0; pte < PT_ENTRIES; pte++) { if(pgtbl[pte] & PAGE_MASK) { break; } } if(pte == PT_ENTRIES) { kfree((unsigned int)pgtbl & PAGE_MASK); current->rss--; pgdir[pde] = 0; } } } } } void release_binary(void) { struct vma *vma, *tmp; vma = current->vma_table; while(vma) { tmp = vma->next; free_vma_pages(vma, vma->start, vma->end - vma->start); free_vma_region(vma, vma->start, vma->end - vma->start); vma = tmp; } invalidate_tlb(); } struct vma *find_vma_region(unsigned int addr) { struct vma *vma; if(!addr) { return NULL; } addr &= PAGE_MASK; vma = current->vma_table; while(vma) { if((addr >= vma->start) && (addr < vma->end)) { return vma; } vma = vma->next; } return NULL; } struct vma *find_vma_intersection(unsigned int start, unsigned int end) { struct vma *vma; vma = current->vma_table; while(vma) { if(end <= vma->start) { break; } if(start < vma->end) { return vma; } vma = vma->next; } return NULL; } int expand_heap(unsigned int new) { struct vma *vma, *heap; vma = current->vma_table; heap = NULL; while(vma) { /* make sure the new heap won't overlap the next region */ if(heap && new < vma->start) { heap->end = new; return 0; } else { heap = NULL; /* was a bad candidate */ } if(!heap && vma->s_type == P_HEAP) { heap = vma; /* possible candidate */ } vma = vma->next; } /* out of memory! */ return 1; } /* return the first free address that matches with the size of length */ unsigned int get_unmapped_vma_region(unsigned int length) { unsigned int addr; struct vma *vma; if(!length) { return 0; } addr = MMAP_START; vma = current->vma_table; while(vma) { if(vma->start < MMAP_START) { vma = vma->next; continue; } if(vma->start - addr >= length) { return PAGE_ALIGN(addr); } addr = PAGE_ALIGN(vma->end); vma = vma->next; } return 0; } int do_mmap(struct inode *i, unsigned int start, unsigned int length, unsigned int prot, unsigned int flags, unsigned int offset, char type, char mode, void *object) { struct vma *vma; int errno; if(!(length = PAGE_ALIGN(length))) { return start; } if(start > PAGE_OFFSET || start + length > PAGE_OFFSET) { return -EINVAL; } /* file mapping */ if(i) { if(!S_ISREG(i->i_mode) && !S_ISCHR(i->i_mode)) { return -ENODEV; } /* * The file shall have been opened with read permission, * regardless of the protection options specified. * IEEE Std 1003.1, 2004 Edition. */ if(mode == O_WRONLY) { return -EACCES; } switch(flags & MAP_TYPE) { case MAP_SHARED: if(prot & PROT_WRITE) { if(!(mode & (O_WRONLY | O_RDWR))) { return -EACCES; } } break; case MAP_PRIVATE: break; default: return -EINVAL; } i->count++; /* anonymous mapping */ } else { if((flags & MAP_TYPE) != MAP_PRIVATE) { return -EINVAL; } /* anonymous objects must be filled with zeros */ flags |= ZERO_PAGE; #ifdef CONFIG_SYSVIPC /* ... except for SHM regions */ if(type == P_SHM) { flags &= ~ZERO_PAGE; } #endif /* CONFIG_SYSVIPC */ } if(flags & MAP_FIXED) { if(start & ~PAGE_MASK) { return -EINVAL; } } else { start = get_unmapped_vma_region(length); if(!start) { printk("WARNING: %s(): unable to get an unmapped vma region.\n", __FUNCTION__); return -ENOMEM; } } if(!(vma = (struct vma *)kmalloc(sizeof(struct vma)))) { return -ENOMEM; } memset_b(vma, 0, sizeof(struct vma)); vma->start = start; vma->end = start + length; vma->prot = prot; vma->flags = flags; vma->offset = offset; vma->s_type = type; vma->inode = i; vma->o_mode = mode; #ifdef CONFIG_SYSVIPC vma->object = (struct shmid_ds *)object; #endif /* CONFIG_SYSVIPC */ if(i && i->fsop->mmap) { if((errno = i->fsop->mmap(i, vma))) { int errno2; if((errno2 = free_vma_region(vma, start, length))) { kfree((unsigned int)vma); return errno2; } kfree((unsigned int)vma); return errno; } } add_vma_region(vma); return start; } int do_munmap(unsigned int addr, __size_t length) { struct vma *vma; unsigned int size; if(addr & ~PAGE_MASK) { return -EINVAL; } length = PAGE_ALIGN(length); while(length) { if((vma = find_vma_region(addr))) { if((addr + length) > vma->end) { size = vma->end - addr; } else { size = length; } free_vma_pages(vma, addr, size); invalidate_tlb(); free_vma_region(vma, addr, size); length -= size; addr += size; } } return 0; } int do_mprotect(struct vma *vma, unsigned int addr, __size_t length, int prot) { struct vma *new; if(!(new = (struct vma *)kmalloc(sizeof(struct vma)))) { return -ENOMEM; } memset_b(new, 0, sizeof(struct vma)); new->start = addr; new->end = addr + length; new->prot = prot; new->flags = vma->flags; new->offset = vma->offset; new->s_type = vma->s_type; new->inode = vma->inode; new->o_mode = vma->o_mode; add_vma_region(new); return 0; }
9281c90502276a14dfa8f6a9f609eadd5a99eadb
6832a9c81b16ead373325f70fb97753d6a211539
/src/wrapped/wrappedsdl2net_private.h
6986d4da27661765395f6c388ce44d4070170c6f
[ "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
1,220
h
wrappedsdl2net_private.h
#if !(defined(GO) && defined(GOM) && defined(GO2) && defined(DATA)) #error Meh! #endif GO(SDLNet_AddSocket, iFpp) GO(SDLNet_AllocPacket, pFi) GO(SDLNet_AllocPacketV, pFii) GO(SDLNet_AllocSocketSet, pFi) GO(SDLNet_CheckSockets, iFpu) GO(SDLNet_DelSocket, iFpp) GO(SDLNet_FreePacket, vFp) GO(SDLNet_FreePacketV, vFp) GO(SDLNet_FreeSocketSet, vFp) GO(SDLNet_GetError, pFv) //GO(SDLNet_GetLastError, GO(SDLNet_GetLocalAddresses, iFpi) GO(SDLNet_Init, iFv) GO(SDLNet_Linked_Version, pFv) GO(SDLNet_Quit, vFv) GO(SDLNet_Read16, WFp) GO(SDLNet_Read32, uFp) GO(SDLNet_ResizePacket, iFpi) GO(SDLNet_ResolveHost, iFppW) GO(SDLNet_ResolveIP, pFp) //GOM(SDLNet_SetError, vFEpV) //GO(SDLNet_SetLastError, GO(SDLNet_TCP_Accept, pFp) GO(SDLNet_TCP_Close, vFp) GO(SDLNet_TCP_GetPeerAddress, pFp) GO(SDLNet_TCP_Open, pFp) GO(SDLNet_TCP_Recv, iFppi) GO(SDLNet_TCP_Send, iFppi) GO(SDLNet_UDP_Bind, iFpip) GO(SDLNet_UDP_Close, vFp) GO(SDLNet_UDP_GetPeerAddress, pFpi) GO(SDLNet_UDP_Open, pFW) GO(SDLNet_UDP_Recv, iFpp) GO(SDLNet_UDP_RecvV, iFpp) GO(SDLNet_UDP_Send, iFpip) GO(SDLNet_UDP_SendV, iFppi) GO(SDLNet_UDP_SetPacketLoss, vFpi) GO(SDLNet_UDP_Unbind, vFpi) GO(SDLNet_Write16, vFWp) GO(SDLNet_Write32, vFup) GO(SDLNet_version, pFv)
8901208daad3a539596fbd0e92062fc7d7e6fa2b
97c44f18459163c0baa546ab2578339b716c3238
/vendor/ed25519/ge.c
44fa2599f53f83c238d52f2b0c301c1900f3ed39
[ "Zlib", "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
11,262
c
ge.c
/* Copyright (c) 2015 Orson Peters <orsonpeters@gmail.com> 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 "ge.h" #include "precomp_data.h" /* r = p + q */ void ge_add(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) { fe t0; fe_add(r->X, p->Y, p->X); fe_sub(r->Y, p->Y, p->X); fe_mul(r->Z, r->X, q->YplusX); fe_mul(r->Y, r->Y, q->YminusX); fe_mul(r->T, q->T2d, p->T); fe_mul(r->X, p->Z, q->Z); fe_add(t0, r->X, r->X); fe_sub(r->X, r->Z, r->Y); fe_add(r->Y, r->Z, r->Y); fe_add(r->Z, t0, r->T); fe_sub(r->T, t0, r->T); } static void slide(signed char *r, const unsigned char *a) { int i; int b; int k; for (i = 0; i < 256; ++i) { r[i] = 1 & (a[i >> 3] >> (i & 7)); } for (i = 0; i < 256; ++i) if (r[i]) { for (b = 1; b <= 6 && i + b < 256; ++b) { if (r[i + b]) { if (r[i] + (r[i + b] << b) <= 15) { r[i] += r[i + b] << b; r[i + b] = 0; } else if (r[i] - (r[i + b] << b) >= -15) { r[i] -= r[i + b] << b; for (k = i + b; k < 256; ++k) { if (!r[k]) { r[k] = 1; break; } r[k] = 0; } } else { break; } } } } } /* r = a * A + b * B where a = a[0]+256*a[1]+...+256^31 a[31]. and b = b[0]+256*b[1]+...+256^31 b[31]. B is the Ed25519 base point (x,4/5) with x positive. */ void ge_double_scalarmult_vartime(ge_p2 *r, const unsigned char *a, const ge_p3 *A, const unsigned char *b) { signed char aslide[256]; signed char bslide[256]; ge_cached Ai[8]; /* A,3A,5A,7A,9A,11A,13A,15A */ ge_p1p1 t; ge_p3 u; ge_p3 A2; int i; slide(aslide, a); slide(bslide, b); ge_p3_to_cached(&Ai[0], A); ge_p3_dbl(&t, A); ge_p1p1_to_p3(&A2, &t); ge_add(&t, &A2, &Ai[0]); ge_p1p1_to_p3(&u, &t); ge_p3_to_cached(&Ai[1], &u); ge_add(&t, &A2, &Ai[1]); ge_p1p1_to_p3(&u, &t); ge_p3_to_cached(&Ai[2], &u); ge_add(&t, &A2, &Ai[2]); ge_p1p1_to_p3(&u, &t); ge_p3_to_cached(&Ai[3], &u); ge_add(&t, &A2, &Ai[3]); ge_p1p1_to_p3(&u, &t); ge_p3_to_cached(&Ai[4], &u); ge_add(&t, &A2, &Ai[4]); ge_p1p1_to_p3(&u, &t); ge_p3_to_cached(&Ai[5], &u); ge_add(&t, &A2, &Ai[5]); ge_p1p1_to_p3(&u, &t); ge_p3_to_cached(&Ai[6], &u); ge_add(&t, &A2, &Ai[6]); ge_p1p1_to_p3(&u, &t); ge_p3_to_cached(&Ai[7], &u); ge_p2_0(r); for (i = 255; i >= 0; --i) { if (aslide[i] || bslide[i]) { break; } } for (; i >= 0; --i) { ge_p2_dbl(&t, r); if (aslide[i] > 0) { ge_p1p1_to_p3(&u, &t); ge_add(&t, &u, &Ai[aslide[i] / 2]); } else if (aslide[i] < 0) { ge_p1p1_to_p3(&u, &t); ge_sub(&t, &u, &Ai[(-aslide[i]) / 2]); } if (bslide[i] > 0) { ge_p1p1_to_p3(&u, &t); ge_madd(&t, &u, &Bi[bslide[i] / 2]); } else if (bslide[i] < 0) { ge_p1p1_to_p3(&u, &t); ge_msub(&t, &u, &Bi[(-bslide[i]) / 2]); } ge_p1p1_to_p2(r, &t); } } static const fe d = { -10913610, 13857413, -15372611, 6949391, 114729, -8787816, -6275908, -3247719, -18696448, -12055116 }; static const fe sqrtm1 = { -32595792, -7943725, 9377950, 3500415, 12389472, -272473, -25146209, -2005654, 326686, 11406482 }; int ge_frombytes_negate_vartime(ge_p3 *h, const unsigned char *s) { fe u; fe v; fe v3; fe vxx; fe check; fe_frombytes(h->Y, s); fe_1(h->Z); fe_sq(u, h->Y); fe_mul(v, u, d); fe_sub(u, u, h->Z); /* u = y^2-1 */ fe_add(v, v, h->Z); /* v = dy^2+1 */ fe_sq(v3, v); fe_mul(v3, v3, v); /* v3 = v^3 */ fe_sq(h->X, v3); fe_mul(h->X, h->X, v); fe_mul(h->X, h->X, u); /* x = uv^7 */ fe_pow22523(h->X, h->X); /* x = (uv^7)^((q-5)/8) */ fe_mul(h->X, h->X, v3); fe_mul(h->X, h->X, u); /* x = uv^3(uv^7)^((q-5)/8) */ fe_sq(vxx, h->X); fe_mul(vxx, vxx, v); fe_sub(check, vxx, u); /* vx^2-u */ if (fe_isnonzero(check)) { fe_add(check, vxx, u); /* vx^2+u */ if (fe_isnonzero(check)) { return -1; } fe_mul(h->X, h->X, sqrtm1); } if (fe_isnegative(h->X) == (s[31] >> 7)) { fe_neg(h->X, h->X); } fe_mul(h->T, h->X, h->Y); return 0; } /* r = p + q */ void ge_madd(ge_p1p1 *r, const ge_p3 *p, const ge_precomp *q) { fe t0; fe_add(r->X, p->Y, p->X); fe_sub(r->Y, p->Y, p->X); fe_mul(r->Z, r->X, q->yplusx); fe_mul(r->Y, r->Y, q->yminusx); fe_mul(r->T, q->xy2d, p->T); fe_add(t0, p->Z, p->Z); fe_sub(r->X, r->Z, r->Y); fe_add(r->Y, r->Z, r->Y); fe_add(r->Z, t0, r->T); fe_sub(r->T, t0, r->T); } /* r = p - q */ void ge_msub(ge_p1p1 *r, const ge_p3 *p, const ge_precomp *q) { fe t0; fe_add(r->X, p->Y, p->X); fe_sub(r->Y, p->Y, p->X); fe_mul(r->Z, r->X, q->yminusx); fe_mul(r->Y, r->Y, q->yplusx); fe_mul(r->T, q->xy2d, p->T); fe_add(t0, p->Z, p->Z); fe_sub(r->X, r->Z, r->Y); fe_add(r->Y, r->Z, r->Y); fe_sub(r->Z, t0, r->T); fe_add(r->T, t0, r->T); } /* r = p */ void ge_p1p1_to_p2(ge_p2 *r, const ge_p1p1 *p) { fe_mul(r->X, p->X, p->T); fe_mul(r->Y, p->Y, p->Z); fe_mul(r->Z, p->Z, p->T); } /* r = p */ void ge_p1p1_to_p3(ge_p3 *r, const ge_p1p1 *p) { fe_mul(r->X, p->X, p->T); fe_mul(r->Y, p->Y, p->Z); fe_mul(r->Z, p->Z, p->T); fe_mul(r->T, p->X, p->Y); } void ge_p2_0(ge_p2 *h) { fe_0(h->X); fe_1(h->Y); fe_1(h->Z); } /* r = 2 * p */ void ge_p2_dbl(ge_p1p1 *r, const ge_p2 *p) { fe t0; fe_sq(r->X, p->X); fe_sq(r->Z, p->Y); fe_sq2(r->T, p->Z); fe_add(r->Y, p->X, p->Y); fe_sq(t0, r->Y); fe_add(r->Y, r->Z, r->X); fe_sub(r->Z, r->Z, r->X); fe_sub(r->X, t0, r->Y); fe_sub(r->T, r->T, r->Z); } void ge_p3_0(ge_p3 *h) { fe_0(h->X); fe_1(h->Y); fe_1(h->Z); fe_0(h->T); } /* r = 2 * p */ void ge_p3_dbl(ge_p1p1 *r, const ge_p3 *p) { ge_p2 q; ge_p3_to_p2(&q, p); ge_p2_dbl(r, &q); } /* r = p */ static const fe d2 = { -21827239, -5839606, -30745221, 13898782, 229458, 15978800, -12551817, -6495438, 29715968, 9444199 }; void ge_p3_to_cached(ge_cached *r, const ge_p3 *p) { fe_add(r->YplusX, p->Y, p->X); fe_sub(r->YminusX, p->Y, p->X); fe_copy(r->Z, p->Z); fe_mul(r->T2d, p->T, d2); } /* r = p */ void ge_p3_to_p2(ge_p2 *r, const ge_p3 *p) { fe_copy(r->X, p->X); fe_copy(r->Y, p->Y); fe_copy(r->Z, p->Z); } void ge_p3_tobytes(unsigned char *s, const ge_p3 *h) { fe recip; fe x; fe y; fe_invert(recip, h->Z); fe_mul(x, h->X, recip); fe_mul(y, h->Y, recip); fe_tobytes(s, y); s[31] ^= fe_isnegative(x) << 7; } static unsigned char equal(signed char b, signed char c) { unsigned char ub = b; unsigned char uc = c; unsigned char x = ub ^ uc; /* 0: yes; 1..255: no */ uint64_t y = x; /* 0: yes; 1..255: no */ y -= 1; /* large: yes; 0..254: no */ y >>= 63; /* 1: yes; 0: no */ return (unsigned char) y; } static unsigned char negative(signed char b) { uint64_t x = b; /* 18446744073709551361..18446744073709551615: yes; 0..255: no */ x >>= 63; /* 1: yes; 0: no */ return (unsigned char) x; } static void cmov(ge_precomp *t, const ge_precomp *u, unsigned char b) { fe_cmov(t->yplusx, u->yplusx, b); fe_cmov(t->yminusx, u->yminusx, b); fe_cmov(t->xy2d, u->xy2d, b); } static void select(ge_precomp *t, int pos, signed char b) { ge_precomp minust; unsigned char bnegative = negative(b); unsigned char babs = b - (((-bnegative) & b) << 1); fe_1(t->yplusx); fe_1(t->yminusx); fe_0(t->xy2d); cmov(t, &base[pos][0], equal(babs, 1)); cmov(t, &base[pos][1], equal(babs, 2)); cmov(t, &base[pos][2], equal(babs, 3)); cmov(t, &base[pos][3], equal(babs, 4)); cmov(t, &base[pos][4], equal(babs, 5)); cmov(t, &base[pos][5], equal(babs, 6)); cmov(t, &base[pos][6], equal(babs, 7)); cmov(t, &base[pos][7], equal(babs, 8)); fe_copy(minust.yplusx, t->yminusx); fe_copy(minust.yminusx, t->yplusx); fe_neg(minust.xy2d, t->xy2d); cmov(t, &minust, bnegative); } /* h = a * B where a = a[0]+256*a[1]+...+256^31 a[31] B is the Ed25519 base point (x,4/5) with x positive. Preconditions: a[31] <= 127 */ void ge_scalarmult_base(ge_p3 *h, const unsigned char *a) { signed char e[64]; signed char carry; ge_p1p1 r; ge_p2 s; ge_precomp t; int i; for (i = 0; i < 32; ++i) { e[2 * i + 0] = (a[i] >> 0) & 15; e[2 * i + 1] = (a[i] >> 4) & 15; } /* each e[i] is between 0 and 15 */ /* e[63] is between 0 and 7 */ carry = 0; for (i = 0; i < 63; ++i) { e[i] += carry; carry = e[i] + 8; carry >>= 4; e[i] -= carry << 4; } e[63] += carry; /* each e[i] is between -8 and 8 */ ge_p3_0(h); for (i = 1; i < 64; i += 2) { select(&t, i / 2, e[i]); ge_madd(&r, h, &t); ge_p1p1_to_p3(h, &r); } ge_p3_dbl(&r, h); ge_p1p1_to_p2(&s, &r); ge_p2_dbl(&r, &s); ge_p1p1_to_p2(&s, &r); ge_p2_dbl(&r, &s); ge_p1p1_to_p2(&s, &r); ge_p2_dbl(&r, &s); ge_p1p1_to_p3(h, &r); for (i = 0; i < 64; i += 2) { select(&t, i / 2, e[i]); ge_madd(&r, h, &t); ge_p1p1_to_p3(h, &r); } } /* r = p - q */ void ge_sub(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) { fe t0; fe_add(r->X, p->Y, p->X); fe_sub(r->Y, p->Y, p->X); fe_mul(r->Z, r->X, q->YminusX); fe_mul(r->Y, r->Y, q->YplusX); fe_mul(r->T, q->T2d, p->T); fe_mul(r->X, p->Z, q->Z); fe_add(t0, r->X, r->X); fe_sub(r->X, r->Z, r->Y); fe_add(r->Y, r->Z, r->Y); fe_sub(r->Z, t0, r->T); fe_add(r->T, t0, r->T); } void ge_tobytes(unsigned char *s, const ge_p2 *h) { fe recip; fe x; fe y; fe_invert(recip, h->Z); fe_mul(x, h->X, recip); fe_mul(y, h->Y, recip); fe_tobytes(s, y); s[31] ^= fe_isnegative(x) << 7; }
638588ea97af2aad18ab4150d2e076f059bbb275
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/u-boot_new/drivers/input/i8042.c
35fa0bb5043d0c0321d49c8e674063cad5e41d22
[ "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
23,048
c
i8042.c
/* * (C) Copyright 2002 ELTEC Elektronik AG * Frank Gottschling <fgottschling@eltec.de> * * SPDX-License-Identifier: GPL-2.0+ */ /* i8042.c - Intel 8042 keyboard driver routines */ /* includes */ #include <common.h> #include <linux/compiler.h> #ifdef CONFIG_USE_CPCIDVI extern u8 gt_cpcidvi_in8(u32 offset); extern void gt_cpcidvi_out8(u32 offset, u8 data); #define in8(a) gt_cpcidvi_in8(a) #define out8(a, b) gt_cpcidvi_out8(a, b) #endif #include <i8042.h> /* defines */ #ifdef CONFIG_CONSOLE_CURSOR extern void console_cursor(int state); static int blinkCount = CONFIG_SYS_CONSOLE_BLINK_COUNT; static int cursor_state; #endif /* locals */ static int kbd_input = -1; /* no input yet */ static int kbd_mapping = KBD_US; /* default US keyboard */ static int kbd_flags = NORMAL; /* after reset */ static int kbd_state; /* unshift code */ static void kbd_conv_char(unsigned char scan_code); static void kbd_led_set(void); static void kbd_normal(unsigned char scan_code); static void kbd_shift(unsigned char scan_code); static void kbd_ctrl(unsigned char scan_code); static void kbd_num(unsigned char scan_code); static void kbd_caps(unsigned char scan_code); static void kbd_scroll(unsigned char scan_code); static void kbd_alt(unsigned char scan_code); static int kbd_input_empty(void); static int kbd_reset(void); static unsigned char kbd_fct_map[144] = { /* kbd_fct_map table for scan code */ 0, AS, AS, AS, AS, AS, AS, AS, /* scan 0- 7 */ AS, AS, AS, AS, AS, AS, AS, AS, /* scan 8- F */ AS, AS, AS, AS, AS, AS, AS, AS, /* scan 10-17 */ AS, AS, AS, AS, AS, CN, AS, AS, /* scan 18-1F */ AS, AS, AS, AS, AS, AS, AS, AS, /* scan 20-27 */ AS, AS, SH, AS, AS, AS, AS, AS, /* scan 28-2F */ AS, AS, AS, AS, AS, AS, SH, AS, /* scan 30-37 */ AS, AS, CP, 0, 0, 0, 0, 0, /* scan 38-3F */ 0, 0, 0, 0, 0, NM, ST, ES, /* scan 40-47 */ ES, ES, ES, ES, ES, ES, ES, ES, /* scan 48-4F */ ES, ES, ES, ES, 0, 0, AS, 0, /* scan 50-57 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 58-5F */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 60-67 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 68-6F */ AS, 0, 0, AS, 0, 0, AS, 0, /* scan 70-77 */ 0, AS, 0, 0, 0, AS, 0, 0, /* scan 78-7F */ AS, CN, AS, AS, AK, ST, EX, EX, /* enhanced */ AS, EX, EX, AS, EX, AS, EX, EX /* enhanced */ }; static unsigned char kbd_key_map[2][5][144] = { { /* US keyboard */ { /* unshift code */ 0, 0x1b, '1', '2', '3', '4', '5', '6', /* scan 0- 7 */ '7', '8', '9', '0', '-', '=', 0x08, '\t', /* scan 8- F */ 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', /* scan 10-17 */ 'o', 'p', '[', ']', '\r', CN, 'a', 's', /* scan 18-1F */ 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', /* scan 20-27 */ '\'', '`', SH, '\\', 'z', 'x', 'c', 'v', /* scan 28-2F */ 'b', 'n', 'm', ',', '.', '/', SH, '*', /* scan 30-37 */ ' ', ' ', CP, 0, 0, 0, 0, 0, /* scan 38-3F */ 0, 0, 0, 0, 0, NM, ST, '7', /* scan 40-47 */ '8', '9', '-', '4', '5', '6', '+', '1', /* scan 48-4F */ '2', '3', '0', '.', 0, 0, 0, 0, /* scan 50-57 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 58-5F */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 60-67 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 68-6F */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 70-77 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 78-7F */ '\r', CN, '/', '*', ' ', ST, 'F', 'A', /* extended */ 0, 'D', 'C', 0, 'B', 0, '@', 'P' /* extended */ }, { /* shift code */ 0, 0x1b, '!', '@', '#', '$', '%', '^', /* scan 0- 7 */ '&', '*', '(', ')', '_', '+', 0x08, '\t', /* scan 8- F */ 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', /* scan 10-17 */ 'O', 'P', '{', '}', '\r', CN, 'A', 'S', /* scan 18-1F */ 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', /* scan 20-27 */ '"', '~', SH, '|', 'Z', 'X', 'C', 'V', /* scan 28-2F */ 'B', 'N', 'M', '<', '>', '?', SH, '*', /* scan 30-37 */ ' ', ' ', CP, 0, 0, 0, 0, 0, /* scan 38-3F */ 0, 0, 0, 0, 0, NM, ST, '7', /* scan 40-47 */ '8', '9', '-', '4', '5', '6', '+', '1', /* scan 48-4F */ '2', '3', '0', '.', 0, 0, 0, 0, /* scan 50-57 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 58-5F */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 60-67 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 68-6F */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 70-77 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 78-7F */ '\r', CN, '/', '*', ' ', ST, 'F', 'A', /* extended */ 0, 'D', 'C', 0, 'B', 0, '@', 'P' /* extended */ }, { /* control code */ 0xff, 0x1b, 0xff, 0x00, 0xff, 0xff, 0xff, 0xff, /* scan 0- 7 */ 0x1e, 0xff, 0xff, 0xff, 0x1f, 0xff, 0xff, '\t', /* scan 8- F */ 0x11, 0x17, 0x05, 0x12, 0x14, 0x19, 0x15, 0x09, /* scan 10-17 */ 0x0f, 0x10, 0x1b, 0x1d, '\r', CN, 0x01, 0x13, /* scan 18-1F */ 0x04, 0x06, 0x07, 0x08, 0x0a, 0x0b, 0x0c, 0xff, /* scan 20-27 */ 0xff, 0x1c, SH, 0xff, 0x1a, 0x18, 0x03, 0x16, /* scan 28-2F */ 0x02, 0x0e, 0x0d, 0xff, 0xff, 0xff, SH, 0xff, /* scan 30-37 */ 0xff, 0xff, CP, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 38-3F */ 0xff, 0xff, 0xff, 0xff, 0xff, NM, ST, 0xff, /* scan 40-47 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 48-4F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 50-57 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 58-5F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 60-67 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 68-6F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 70-77 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 78-7F */ '\r', CN, '/', '*', ' ', ST, 0xff, 0xff, /* extended */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff /* extended */ }, { /* non numeric code */ 0, 0x1b, '1', '2', '3', '4', '5', '6', /* scan 0- 7 */ '7', '8', '9', '0', '-', '=', 0x08, '\t', /* scan 8- F */ 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', /* scan 10-17 */ 'o', 'p', '[', ']', '\r', CN, 'a', 's', /* scan 18-1F */ 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', /* scan 20-27 */ '\'', '`', SH, '\\', 'z', 'x', 'c', 'v', /* scan 28-2F */ 'b', 'n', 'm', ',', '.', '/', SH, '*', /* scan 30-37 */ ' ', ' ', CP, 0, 0, 0, 0, 0, /* scan 38-3F */ 0, 0, 0, 0, 0, NM, ST, 'w', /* scan 40-47 */ 'x', 'y', 'l', 't', 'u', 'v', 'm', 'q', /* scan 48-4F */ 'r', 's', 'p', 'n', 0, 0, 0, 0, /* scan 50-57 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 58-5F */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 60-67 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 68-6F */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 70-77 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 78-7F */ '\r', CN, '/', '*', ' ', ST, 'F', 'A', /* extended */ 0, 'D', 'C', 0, 'B', 0, '@', 'P' /* extended */ }, { /* right alt mode - not used in US keyboard */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 0 - 7 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 8 - F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 10 -17 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 18 -1F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 20 -27 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 28 -2F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 30 -37 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 38 -3F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 40 -47 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 48 -4F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 50 -57 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 58 -5F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 60 -67 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 68 -6F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 70 -77 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 78 -7F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* extended */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff /* extended */ } }, { /* german keyboard */ { /* unshift code */ 0, 0x1b, '1', '2', '3', '4', '5', '6', /* scan 0- 7 */ '7', '8', '9', '0', 0xe1, '\'', 0x08, '\t', /* scan 8- F */ 'q', 'w', 'e', 'r', 't', 'z', 'u', 'i', /* scan 10-17 */ 'o', 'p', 0x81, '+', '\r', CN, 'a', 's', /* scan 18-1F */ 'd', 'f', 'g', 'h', 'j', 'k', 'l', 0x94, /* scan 20-27 */ 0x84, '^', SH, '#', 'y', 'x', 'c', 'v', /* scan 28-2F */ 'b', 'n', 'm', ',', '.', '-', SH, '*', /* scan 30-37 */ ' ', ' ', CP, 0, 0, 0, 0, 0, /* scan 38-3F */ 0, 0, 0, 0, 0, NM, ST, '7', /* scan 40-47 */ '8', '9', '-', '4', '5', '6', '+', '1', /* scan 48-4F */ '2', '3', '0', ',', 0, 0, '<', 0, /* scan 50-57 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 58-5F */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 60-67 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 68-6F */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 70-77 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 78-7F */ '\r', CN, '/', '*', ' ', ST, 'F', 'A', /* extended */ 0, 'D', 'C', 0, 'B', 0, '@', 'P' /* extended */ }, { /* shift code */ 0, 0x1b, '!', '"', 0x15, '$', '%', '&', /* scan 0- 7 */ '/', '(', ')', '=', '?', '`', 0x08, '\t', /* scan 8- F */ 'Q', 'W', 'E', 'R', 'T', 'Z', 'U', 'I', /* scan 10-17 */ 'O', 'P', 0x9a, '*', '\r', CN, 'A', 'S', /* scan 18-1F */ 'D', 'F', 'G', 'H', 'J', 'K', 'L', 0x99, /* scan 20-27 */ 0x8e, 0xf8, SH, '\'', 'Y', 'X', 'C', 'V', /* scan 28-2F */ 'B', 'N', 'M', ';', ':', '_', SH, '*', /* scan 30-37 */ ' ', ' ', CP, 0, 0, 0, 0, 0, /* scan 38-3F */ 0, 0, 0, 0, 0, NM, ST, '7', /* scan 40-47 */ '8', '9', '-', '4', '5', '6', '+', '1', /* scan 48-4F */ '2', '3', '0', ',', 0, 0, '>', 0, /* scan 50-57 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 58-5F */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 60-67 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 68-6F */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 70-77 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 78-7F */ '\r', CN, '/', '*', ' ', ST, 'F', 'A', /* extended */ 0, 'D', 'C', 0, 'B', 0, '@', 'P' /* extended */ }, { /* control code */ 0xff, 0x1b, 0xff, 0x00, 0xff, 0xff, 0xff, 0xff, /* scan 0- 7 */ 0x1e, 0xff, 0xff, 0xff, 0x1f, 0xff, 0xff, '\t', /* scan 8- F */ 0x11, 0x17, 0x05, 0x12, 0x14, 0x19, 0x15, 0x09, /* scan 10-17 */ 0x0f, 0x10, 0x1b, 0x1d, '\r', CN, 0x01, 0x13, /* scan 18-1F */ 0x04, 0x06, 0x07, 0x08, 0x0a, 0x0b, 0x0c, 0xff, /* scan 20-27 */ 0xff, 0x1c, SH, 0xff, 0x1a, 0x18, 0x03, 0x16, /* scan 28-2F */ 0x02, 0x0e, 0x0d, 0xff, 0xff, 0xff, SH, 0xff, /* scan 30-37 */ 0xff, 0xff, CP, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 38-3F */ 0xff, 0xff, 0xff, 0xff, 0xff, NM, ST, 0xff, /* scan 40-47 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 48-4F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 50-57 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 58-5F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 60-67 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 68-6F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 70-77 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 78-7F */ '\r', CN, '/', '*', ' ', ST, 0xff, 0xff, /* extended */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff /* extended */ }, { /* non numeric code */ 0, 0x1b, '1', '2', '3', '4', '5', '6', /* scan 0- 7 */ '7', '8', '9', '0', 0xe1, '\'', 0x08, '\t', /* scan 8- F */ 'q', 'w', 'e', 'r', 't', 'z', 'u', 'i', /* scan 10-17 */ 'o', 'p', 0x81, '+', '\r', CN, 'a', 's', /* scan 18-1F */ 'd', 'f', 'g', 'h', 'j', 'k', 'l', 0x94, /* scan 20-27 */ 0x84, '^', SH, 0, 'y', 'x', 'c', 'v', /* scan 28-2F */ 'b', 'n', 'm', ',', '.', '-', SH, '*', /* scan 30-37 */ ' ', ' ', CP, 0, 0, 0, 0, 0, /* scan 38-3F */ 0, 0, 0, 0, 0, NM, ST, 'w', /* scan 40-47 */ 'x', 'y', 'l', 't', 'u', 'v', 'm', 'q', /* scan 48-4F */ 'r', 's', 'p', 'n', 0, 0, '<', 0, /* scan 50-57 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 58-5F */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 60-67 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 68-6F */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 70-77 */ 0, 0, 0, 0, 0, 0, 0, 0, /* scan 78-7F */ '\r', CN, '/', '*', ' ', ST, 'F', 'A', /* extended */ 0, 'D', 'C', 0, 'B', 0, '@', 'P' /* extended */ }, { /* Right alt mode - is used in German keyboard */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 0 - 7 */ '{', '[', ']', '}', '\\', 0xff, 0xff, 0xff, /* scan 8 - F */ '@', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 10 -17 */ 0xff, 0xff, 0xff, '~', 0xff, 0xff, 0xff, 0xff, /* scan 18 -1F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 20 -27 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 28 -2F */ 0xff, 0xff, 0xe6, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 30 -37 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 38 -3F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 40 -47 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 48 -4F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, '|', 0xff, /* scan 50 -57 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 58 -5F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 60 -67 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 68 -6F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 70 -77 */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* scan 78 -7F */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* extended */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff /* extended */ } } }; static unsigned char ext_key_map[] = { 0x1c, /* keypad enter */ 0x1d, /* right control */ 0x35, /* keypad slash */ 0x37, /* print screen */ 0x38, /* right alt */ 0x46, /* break */ 0x47, /* editpad home */ 0x48, /* editpad up */ 0x49, /* editpad pgup */ 0x4b, /* editpad left */ 0x4d, /* editpad right */ 0x4f, /* editpad end */ 0x50, /* editpad dn */ 0x51, /* editpad pgdn */ 0x52, /* editpad ins */ 0x53, /* editpad del */ 0x00 /* map end */ }; /******************************************************************************/ static int kbd_controller_present(void) { return in8(I8042_STATUS_REG) != 0xff; } /* * Implement a weak default function for boards that optionally * need to skip the i8042 initialization. */ int __weak board_i8042_skip(void) { /* As default, don't skip */ return 0; } void i8042_flush(void) { int timeout; /* * The delay is to give the keyboard controller some time to fill the * next byte. */ while (1) { timeout = 100; /* wait for no longer than 100us */ while (timeout > 0 && !(in8(I8042_STATUS_REG) & 0x01)) { udelay(1); timeout--; } /* Try to pull next byte if not timeout. */ if (in8(I8042_STATUS_REG) & 0x01) in8(I8042_DATA_REG); else break; } } int i8042_disable(void) { if (kbd_input_empty() == 0) return -1; /* Disable keyboard */ out8(I8042_COMMAND_REG, 0xad); if (kbd_input_empty() == 0) return -1; return 0; } /******************************************************************************* * * i8042_kbd_init - reset keyboard and init state flags */ int i8042_kbd_init(void) { int keymap, try; char *penv; if (!kbd_controller_present() || board_i8042_skip()) return -1; #ifdef CONFIG_USE_CPCIDVI penv = getenv("console"); if (penv != NULL) { if (strncmp(penv, "serial", 7) == 0) return -1; } #endif /* Init keyboard device (default US layout) */ keymap = KBD_US; penv = getenv("keymap"); if (penv != NULL) { if (strncmp(penv, "de", 3) == 0) keymap = KBD_GER; } for (try = 0; try < KBD_RESET_TRIES; try++) { if (kbd_reset() == 0) { kbd_mapping = keymap; kbd_flags = NORMAL; kbd_state = 0; kbd_led_set(); return 0; } } return -1; } /******************************************************************************* * * i8042_tstc - test if keyboard input is available * option: cursor blinking if called in a loop */ int i8042_tstc(void) { unsigned char scan_code = 0; #ifdef CONFIG_CONSOLE_CURSOR if (--blinkCount == 0) { cursor_state ^= 1; console_cursor(cursor_state); blinkCount = CONFIG_SYS_CONSOLE_BLINK_COUNT; udelay(10); } #endif if ((in8(I8042_STATUS_REG) & 0x01) == 0) { return 0; } else { scan_code = in8(I8042_DATA_REG); if (scan_code == 0xfa) return 0; kbd_conv_char(scan_code); if (kbd_input != -1) return 1; } return 0; } /******************************************************************************* * * i8042_getc - wait till keyboard input is available * option: turn on/off cursor while waiting */ int i8042_getc(void) { int ret_chr; unsigned char scan_code; while (kbd_input == -1) { while ((in8(I8042_STATUS_REG) & 0x01) == 0) { #ifdef CONFIG_CONSOLE_CURSOR if (--blinkCount == 0) { cursor_state ^= 1; console_cursor(cursor_state); blinkCount = CONFIG_SYS_CONSOLE_BLINK_COUNT; } udelay(10); #endif } scan_code = in8(I8042_DATA_REG); if (scan_code != 0xfa) kbd_conv_char (scan_code); } ret_chr = kbd_input; kbd_input = -1; return ret_chr; } /******************************************************************************/ static void kbd_conv_char(unsigned char scan_code) { if (scan_code == 0xe0) { kbd_flags |= EXT; return; } /* if high bit of scan_code, set break flag */ if (scan_code & 0x80) kbd_flags |= BRK; else kbd_flags &= ~BRK; if ((scan_code == 0xe1) || (kbd_flags & E1)) { if (scan_code == 0xe1) { kbd_flags ^= BRK; /* reset the break flag */ kbd_flags ^= E1; /* bitwise EXOR with E1 flag */ } return; } scan_code &= 0x7f; if (kbd_flags & EXT) { int i; kbd_flags ^= EXT; for (i = 0; ext_key_map[i]; i++) { if (ext_key_map[i] == scan_code) { scan_code = 0x80 + i; break; } } /* not found ? */ if (!ext_key_map[i]) return; } switch (kbd_fct_map[scan_code]) { case AS: kbd_normal(scan_code); break; case SH: kbd_shift(scan_code); break; case CN: kbd_ctrl(scan_code); break; case NM: kbd_num(scan_code); break; case CP: kbd_caps(scan_code); break; case ST: kbd_scroll(scan_code); break; case AK: kbd_alt(scan_code); break; } return; } /******************************************************************************/ static void kbd_normal(unsigned char scan_code) { unsigned char chr; if ((kbd_flags & BRK) == NORMAL) { chr = kbd_key_map[kbd_mapping][kbd_state][scan_code]; if ((chr == 0xff) || (chr == 0x00)) return; /* if caps lock convert upper to lower */ if (((kbd_flags & CAPS) == CAPS) && (chr >= 'a' && chr <= 'z')) { chr -= 'a' - 'A'; } kbd_input = chr; } } /******************************************************************************/ static void kbd_shift(unsigned char scan_code) { if ((kbd_flags & BRK) == BRK) { kbd_state = AS; kbd_flags &= (~SHIFT); } else { kbd_state = SH; kbd_flags |= SHIFT; } } /******************************************************************************/ static void kbd_ctrl(unsigned char scan_code) { if ((kbd_flags & BRK) == BRK) { kbd_state = AS; kbd_flags &= (~CTRL); } else { kbd_state = CN; kbd_flags |= CTRL; } } /******************************************************************************/ static void kbd_caps(unsigned char scan_code) { if ((kbd_flags & BRK) == NORMAL) { kbd_flags ^= CAPS; kbd_led_set(); /* update keyboard LED */ } } /******************************************************************************/ static void kbd_num(unsigned char scan_code) { if ((kbd_flags & BRK) == NORMAL) { kbd_flags ^= NUM; kbd_state = (kbd_flags & NUM) ? AS : NM; kbd_led_set(); /* update keyboard LED */ } } /******************************************************************************/ static void kbd_scroll(unsigned char scan_code) { if ((kbd_flags & BRK) == NORMAL) { kbd_flags ^= STP; kbd_led_set(); /* update keyboard LED */ if (kbd_flags & STP) kbd_input = 0x13; else kbd_input = 0x11; } } /******************************************************************************/ static void kbd_alt(unsigned char scan_code) { if ((kbd_flags & BRK) == BRK) { kbd_state = AS; kbd_flags &= (~ALT); } else { kbd_state = AK; kbd_flags &= ALT; } } /******************************************************************************/ static void kbd_led_set(void) { kbd_input_empty(); out8(I8042_DATA_REG, 0xed); /* SET LED command */ kbd_input_empty(); out8(I8042_DATA_REG, (kbd_flags & 0x7)); /* LED bits only */ } /******************************************************************************/ static int kbd_input_empty(void) { int kbdTimeout = KBD_TIMEOUT * 1000; while ((in8(I8042_STATUS_REG) & I8042_STATUS_IN_DATA) && kbdTimeout--) udelay(1); return kbdTimeout != -1; } /******************************************************************************/ static int wait_until_kbd_output_full(void) { int kbdTimeout = KBD_TIMEOUT * 1000; while (((in8(I8042_STATUS_REG) & 0x01) == 0) && kbdTimeout--) udelay(1); return kbdTimeout != -1; } /******************************************************************************/ static int kbd_reset(void) { /* KB Reset */ if (kbd_input_empty() == 0) return -1; out8(I8042_DATA_REG, 0xff); if (wait_until_kbd_output_full() == 0) return -1; if (in8(I8042_DATA_REG) != 0xfa) /* ACK */ return -1; if (wait_until_kbd_output_full() == 0) return -1; if (in8(I8042_DATA_REG) != 0xaa) /* Test Pass*/ return -1; if (kbd_input_empty() == 0) return -1; /* Set KBC mode */ out8(I8042_COMMAND_REG, 0x60); if (kbd_input_empty() == 0) return -1; out8(I8042_DATA_REG, 0x45); if (kbd_input_empty() == 0) return -1; /* Enable Keyboard */ out8(I8042_COMMAND_REG, 0xae); if (kbd_input_empty() == 0) return -1; return 0; }
c80106f20b4fcf48bd9eec734e72444ccdec6110
aa3befea459382dc5c01c925653d54f435b3fb0f
/include/err.h
fec7f2729fcff442134c6aaede70ce818108dad1
[ "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
2,803
h
err.h
/**************************************************************************** * include/err.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 __INCLUDE_ERR_H #define __INCLUDE_ERR_H /**************************************************************************** * Included Files ****************************************************************************/ #include <stdarg.h> #include <nuttx/compiler.h> /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #ifdef __cplusplus #define EXTERN extern "C" extern "C" { #else #define EXTERN extern #endif /* Append _func suffix to avoid the penitential symbol collision */ #define warn warn_func #define vwarn vwarn_func #define warnx warnx_func #define vwarnx vwarnx_func #define err err_func #define verr verr_func #define errx errx_func #define verrx verrx_func /**************************************************************************** * Public Function Prototypes ****************************************************************************/ /* Print "pid: ", FORMAT, ": ", the standard error string for errno, * and a newline, on stderr. */ void warn(FAR const char *fmt, ...) printf_like(1, 2); void vwarn(FAR const char *fmt, va_list ap) printf_like(1, 0); /* Likewise, but without ": " and the standard error string. */ void warnx(FAR const char *fmt, ...) printf_like(1, 2); void vwarnx(FAR const char *fmt, va_list ap) printf_like(1, 0); /* Likewise, and then exit with STATUS. */ void err(int status, FAR const char *fmt, ...) printf_like(2, 3); void verr(int status, FAR const char *fmt, va_list ap) printf_like(2, 0); void errx(int status, FAR const char *fmt, ...) printf_like(2, 3); void verrx(int status, FAR const char *fmt, va_list ap) printf_like(2, 0); #ifdef __cplusplus #undef EXTERN } #endif #endif /* __INCLUDE_ERR_H */
fa45dd11cced7a465b648a257054e6714b9a4c0c
765f7b8c2caf2d50da8f431f1332207456ba33ee
/libc/unistd/chdir.c
ce60140d581cb6eb9bc05f042b05dcef3c7932ff
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-commercial-license", "AGPL-3.0-or-later", "GPL-1.0-or-later", "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
klange/toaruos
a840f8d46993dc7a8850f82b6d04ba0c2af276a9
4a31a09ba27904b42ee35e8fb1a3c7f87669a2ef
refs/heads/master
2023-09-01T02:00:53.151334
2023-08-28T00:59:18
2023-08-28T00:59:18
1,259,258
5,557
613
NCSA
2023-02-04T08:24:11
2011-01-16T00:59:27
C
UTF-8
C
false
false
205
c
chdir.c
#include <unistd.h> #include <syscall.h> #include <syscall_nums.h> #include <errno.h> DEFN_SYSCALL1(chdir, SYS_CHDIR, char *); int chdir(const char *path) { __sets_errno(syscall_chdir((char*)path)); }
2d9c310dd19b8cea816dd9d5c94b62f86c77d49c
d169de4c5c6b281984df35536430dcc931a957a9
/source/shell/sys/linux/include/linux/i2c-dev.h
6541ea7a4c32420adf8e24b5aa53536fe2375531
[ "LGPL-2.1-only", "Apache-2.0" ]
permissive
vsfteam/vsf
2ba968ba2ef53b036668019c6c6746149a63c38a
522a52ff2ee4ed149b52789a5bd366f80c08c458
refs/heads/master
2023-08-27T07:32:08.339123
2023-08-26T17:46:07
2023-08-26T17:46:07
181,911,464
273
83
Apache-2.0
2023-08-29T03:08:36
2019-04-17T14:43:42
C
UTF-8
C
false
false
845
h
i2c-dev.h
#ifndef __VSF_LINUX_I2C_DEV_H__ #define __VSF_LINUX_I2C_DEV_H__ #include <linux/types.h> #ifdef __cplusplus extern "C" { #endif // for ioctrl #define I2C_SLAVE (('i' << 8) | 0) #define I2C_SLAVE_FORCE I2C_SLAVE #define I2C_TENBIT (('i' << 8) | 1) #define I2C_FUNCS (('i' << 8) | 2) #define I2C_RDWR (('i' << 8) | 3) #define I2C_SMBUS (('i' << 8) | 4) #define I2C_PEC (('i' << 8) | 5) struct i2c_smbus_ioctl_data { __u8 read_write; __u8 command; __u32 size; union i2c_smbus_data *data; }; struct i2c_rdwr_ioctl_data { struct i2c_msg *msgs; __u32 nmsgs; }; #define I2C_RDWR_IOCTL_MAX_MSGS 42 #define I2C_RDRW_IOCTL_MAX_MSGS I2C_RDWR_IOCTL_MAX_MSGS #ifdef __cplusplus } #endif #endif
ab5672b3d0ff16d34b0bf7321dc06c3af1c6a210
88ae8695987ada722184307301e221e1ba3cc2fa
/native_client/tests/longjmp/longjmp_stackslots_test.c
7bb19a34db034573ee0267cf0d9656c50bfcf1c2
[ "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
3,525
c
longjmp_stackslots_test.c
/* * Copyright (c) 2014 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. */ #include <setjmp.h> #include <stdio.h> #include <stdlib.h> /* * This is a regression test for a bug in PNaCl's setjmp() implementation. * The PNaCl translator was reusing stack slots in cases where use of * setjmp() should disable that. See: * https://code.google.com/p/nativeclient/issues/detail?id=3733 * * To test for the bug, this must be compiled with optimisation, in order * to run mem2reg and use spill slots. However, get_next() and * check_equals() must not be inlined. */ static int g_counter = 0; __attribute__((noinline)) int get_next(void) { return ++g_counter; } __attribute__((noinline)) void check_equals(int actual, int expected) { if (actual == expected) { printf("OK: got %i\n", actual); } else { printf("ERROR: got %i but expected %i\n", actual, expected); exit(1); } } int main(void) { /* * Keep enough variables live across the setjmp() call that they don't * all fit in registers, so that the compiler spills some of them to * spill slots on the stack. * * There need to be >8 variables here to catch the bug on ARM (without * NaCl SFI), because ARM's calling conventions use 8 callee-saved * registers (r4-r11), not counting the stack pointer. */ int a1 = get_next(); int a2 = get_next(); int a3 = get_next(); int a4 = get_next(); int a5 = get_next(); int a6 = get_next(); int a7 = get_next(); int a8 = get_next(); int a9 = get_next(); int a10 = get_next(); int a11 = get_next(); int a12 = get_next(); int a13 = get_next(); int a14 = get_next(); int a15 = get_next(); int a16 = get_next(); jmp_buf buf; if (setjmp(buf)) { check_equals(a1, 1); check_equals(a2, 2); check_equals(a3, 3); check_equals(a4, 4); check_equals(a5, 5); check_equals(a6, 6); check_equals(a7, 7); check_equals(a8, 8); check_equals(a9, 9); check_equals(a10, 10); check_equals(a11, 11); check_equals(a12, 12); check_equals(a13, 13); check_equals(a14, 14); check_equals(a15, 15); check_equals(a16, 16); return 0; } /* * Again, keep enough variables live that some of them will need spill * slots. A correct compiler will realise that a1...aN are still live * (via setjmp()+longjmp()), and so not reuse the earlier spill slots. * An incorrect compiler will think that a1..aN are dead here and wrongly * reuse the earlier spill slots. */ int b1 = get_next(); int b2 = get_next(); int b3 = get_next(); int b4 = get_next(); int b5 = get_next(); int b6 = get_next(); int b7 = get_next(); int b8 = get_next(); int b9 = get_next(); int b10 = get_next(); int b11 = get_next(); int b12 = get_next(); int b13 = get_next(); int b14 = get_next(); int b15 = get_next(); int b16 = get_next(); int start = 16; check_equals(b1, start + 1); check_equals(b2, start + 2); check_equals(b3, start + 3); check_equals(b4, start + 4); check_equals(b5, start + 5); check_equals(b6, start + 6); check_equals(b7, start + 7); check_equals(b8, start + 8); check_equals(b9, start + 9); check_equals(b10, start + 10); check_equals(b11, start + 11); check_equals(b12, start + 12); check_equals(b13, start + 13); check_equals(b14, start + 14); check_equals(b15, start + 15); check_equals(b16, start + 16); longjmp(buf, 1); }
205a94fe63b9c3a4436314c88f9233884fe1e0be
2898fa4f2ad766afa0495a837f59fe95daa081a7
/tests/unit-pass/composite-fun.c
f70c4add99594e355b6b5d946ed4f95d87f218f0
[ "NCSA" ]
permissive
kframework/c-semantics
12fcc1b1bf1f7792636d1c37f6f7bb1b89a392b5
e6879d14455771aa0cb3e3d201131d4d763a73a2
refs/heads/master
2023-07-31T23:57:03.316456
2022-02-01T17:50:31
2022-02-01T17:50:31
11,747,541
312
52
NOASSERTION
2022-02-01T17:50:33
2013-07-29T19:13:25
C
UTF-8
C
false
false
100
c
composite-fun.c
void foo(int x) {} void bar(int y) {} int main() { void (*baz)(int) = 0 ? foo : bar; baz(0); }
2f60c715c98de948b30a793f0306d14b780df96a
adecc0c46666e54b6242a0df4e2fa74d4d9d2784
/ovc4/firmware/lpc_fw/component/spi/flexcomm_spi_adapter.c
d593625fb5ba98ff3d13b23db0d552e72cafbdca
[ "CC-BY-4.0", "Apache-2.0", "CERN-OHL-P-2.0" ]
permissive
osrf/ovc
180f0cea2d588e2377dc8e10c0af2a73c1489416
88c1077f226477ac807aa9ecdf3ab58a07da1fb8
refs/heads/master
2023-05-03T09:34:10.443008
2022-03-31T02:28:39
2022-03-31T02:28:39
122,394,447
199
53
Apache-2.0
2023-04-12T06:04:50
2018-02-21T21:14:24
C
UTF-8
C
false
false
10,250
c
flexcomm_spi_adapter.c
/* * Copyright 2018 NXP * All rights reserved. * * * SPDX-License-Identifier: BSD-3-Clause */ #include "fsl_common.h" #include "fsl_spi.h" #include "spi.h" /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief hal_spi master state structure. */ typedef struct _hal_spi_master { hal_spi_master_transfer_callback_t callback; void *callbackParam; spi_master_handle_t hardwareHandle; uint8_t instance; } hal_spi_master_t; /*! @brief hal_spi slave state structure. */ typedef struct _hal_spi_slave { hal_spi_slave_transfer_callback_t callback; void *callbackParam; spi_slave_handle_t hardwareHandle; uint8_t instance; } hal_spi_slave_t; /******************************************************************************* * Prototypes ******************************************************************************/ /******************************************************************************* * Variables ******************************************************************************/ /*! @brief Array to map SPI instance number to base address. */ static const SPI_Type *s_spiBases[] = SPI_BASE_PTRS; /******************************************************************************* * Code ******************************************************************************/ hal_spi_status_t HAL_SpiGetStatus(status_t status) { hal_spi_status_t returnStatus; switch (status) { case kStatus_Success: { returnStatus = kStatus_HAL_SpiSuccess; break; } case kStatus_SPI_Busy: { returnStatus = kStatus_HAL_SpiBusy; break; } case kStatus_SPI_Idle: { returnStatus = kStatus_HAL_SpiIdle; break; } default: { returnStatus = kStatus_HAL_SpiError; break; } } return returnStatus; } static void HAL_SpiMasterCallback(SPI_Type *base, spi_master_handle_t *handle, status_t status, void *callbackParam) { hal_spi_master_t *spiMasterHandle; assert(callbackParam); spiMasterHandle = (hal_spi_master_t *)callbackParam; if (spiMasterHandle->callback) { spiMasterHandle->callback(spiMasterHandle, HAL_SpiGetStatus(status), spiMasterHandle->callbackParam); } } static void HAL_SpiSlaveCallback(SPI_Type *base, spi_slave_handle_t *handle, status_t status, void *callbackParam) { hal_spi_slave_t *spiSlaveHandle; assert(callbackParam); spiSlaveHandle = (hal_spi_slave_t *)callbackParam; if (spiSlaveHandle->callback) { spiSlaveHandle->callback(spiSlaveHandle, HAL_SpiGetStatus(status), spiSlaveHandle->callbackParam); } } hal_spi_status_t HAL_SpiMasterInit(hal_spi_master_handle_t handle, const hal_spi_master_config_t *config) { hal_spi_master_t *masterHandle; spi_master_config_t spiConfig; assert(handle); assert(config); if (HAL_SPI_MASTER_HANDLE_SIZE < sizeof(hal_spi_master_t)) { return kStatus_HAL_SpiError; } masterHandle = (hal_spi_master_t *)handle; SPI_MasterGetDefaultConfig(&spiConfig); spiConfig.polarity = (kHAL_SpiClockPolarityActiveHigh == config->polarity) ? kSPI_ClockPolarityActiveHigh : kSPI_ClockPolarityActiveLow; spiConfig.phase = (kHAL_SpiClockPhaseFirstEdge == config->phase) ? kSPI_ClockPhaseFirstEdge : kSPI_ClockPhaseSecondEdge; spiConfig.direction = (kHAL_SpiMsbFirst == config->direction) ? kSPI_MsbFirst : kSPI_LsbFirst; spiConfig.baudRate_Bps = config->baudRate_Bps; spiConfig.enableMaster = config->enableMaster; masterHandle->instance = config->instance; SPI_MasterInit((SPI_Type *)s_spiBases[masterHandle->instance], &spiConfig, config->srcClock_Hz); return kStatus_HAL_SpiSuccess; } hal_spi_status_t HAL_SpiSlaveInit(hal_spi_slave_handle_t handle, const hal_spi_slave_config_t *config) { hal_spi_slave_t *slaveHandle; spi_slave_config_t spiConfig; assert(handle); assert(config); if (HAL_SPI_SLAVE_HANDLE_SIZE < sizeof(hal_spi_slave_t)) { return kStatus_HAL_SpiError; } slaveHandle = (hal_spi_slave_t *)handle; SPI_SlaveGetDefaultConfig(&spiConfig); spiConfig.polarity = (kHAL_SpiClockPolarityActiveHigh == config->polarity) ? kSPI_ClockPolarityActiveHigh : kSPI_ClockPolarityActiveLow; spiConfig.phase = (kHAL_SpiClockPhaseFirstEdge == config->phase) ? kSPI_ClockPhaseFirstEdge : kSPI_ClockPhaseSecondEdge; spiConfig.direction = (kHAL_SpiMsbFirst == config->direction) ? kSPI_MsbFirst : kSPI_LsbFirst; slaveHandle->instance = config->instance; SPI_SlaveInit((SPI_Type *)s_spiBases[slaveHandle->instance], &spiConfig); return kStatus_HAL_SpiSuccess; } hal_spi_status_t HAL_SpiMasterDeinit(hal_spi_master_handle_t handle) { hal_spi_master_t *masterHandle; assert(handle); masterHandle = (hal_spi_master_t *)handle; SPI_Deinit((SPI_Type *)s_spiBases[masterHandle->instance]); return kStatus_HAL_SpiSuccess; } hal_spi_status_t HAL_SpiSlaveDeinit(hal_spi_slave_handle_t handle) { hal_spi_slave_t *slaveHandle; assert(handle); slaveHandle = (hal_spi_slave_t *)handle; SPI_Deinit((SPI_Type *)s_spiBases[slaveHandle->instance]); return kStatus_HAL_SpiSuccess; } hal_spi_status_t HAL_SpiMasterTransferInstallCallback(hal_spi_master_handle_t handle, hal_spi_master_transfer_callback_t callback, void *callbackParam) { hal_spi_master_t *masterHandle; assert(handle); masterHandle = (hal_spi_master_t *)handle; masterHandle->callback = callback; masterHandle->callbackParam = callbackParam; SPI_MasterTransferCreateHandle((SPI_Type *)s_spiBases[masterHandle->instance], &masterHandle->hardwareHandle, HAL_SpiMasterCallback, masterHandle); return kStatus_HAL_SpiSuccess; } hal_spi_status_t HAL_SpiMasterTransferBlocking(hal_spi_master_handle_t handle, hal_spi_transfer_t *xfer) { hal_spi_master_t *masterHandle; spi_transfer_t transfer; assert(handle); assert(xfer); masterHandle = (hal_spi_master_t *)handle; transfer.txData = xfer->txData; transfer.rxData = xfer->rxData; transfer.dataSize = xfer->dataSize; transfer.configFlags = xfer->flags; return HAL_SpiGetStatus(SPI_MasterTransferBlocking((SPI_Type *)s_spiBases[masterHandle->instance], &transfer)); } hal_spi_status_t HAL_SpiMasterTransferNonBlocking(hal_spi_master_handle_t handle, hal_spi_transfer_t *xfer) { hal_spi_master_t *masterHandle; spi_transfer_t transfer; assert(handle); assert(xfer); masterHandle = (hal_spi_master_t *)handle; transfer.txData = xfer->txData; transfer.rxData = xfer->rxData; transfer.dataSize = xfer->dataSize; transfer.configFlags = xfer->flags; return HAL_SpiGetStatus(SPI_MasterTransferNonBlocking((SPI_Type *)s_spiBases[masterHandle->instance], &masterHandle->hardwareHandle, &transfer)); } hal_spi_status_t HAL_SpiMasterTransferGetCount(hal_spi_master_handle_t handle, size_t *count) { hal_spi_master_t *masterHandle; assert(handle); assert(count); masterHandle = (hal_spi_master_t *)handle; return HAL_SpiGetStatus(SPI_MasterTransferGetCount((SPI_Type *)s_spiBases[masterHandle->instance], &masterHandle->hardwareHandle, count)); } hal_spi_status_t HAL_SpiMasterTransferAbort(hal_spi_master_handle_t handle) { hal_spi_master_t *masterHandle; assert(handle); masterHandle = (hal_spi_master_t *)handle; SPI_MasterTransferAbort((SPI_Type *)s_spiBases[masterHandle->instance], &masterHandle->hardwareHandle); return kStatus_HAL_SpiSuccess; } hal_spi_status_t HAL_SpiSlaveTransferInstallCallback(hal_spi_slave_handle_t handle, hal_spi_slave_transfer_callback_t callback, void *callbackParam) { hal_spi_slave_t *slaveHandle; assert(handle); slaveHandle = (hal_spi_slave_t *)handle; slaveHandle->callback = callback; slaveHandle->callbackParam = callbackParam; SPI_SlaveTransferCreateHandle((SPI_Type *)s_spiBases[slaveHandle->instance], &slaveHandle->hardwareHandle, HAL_SpiSlaveCallback, slaveHandle); return kStatus_HAL_SpiSuccess; } hal_spi_status_t HAL_SpiSlaveTransferNonBlocking(hal_spi_slave_handle_t handle, hal_spi_transfer_t *xfer) { hal_spi_slave_t *slaveHandle; spi_transfer_t transfer; assert(handle); assert(xfer); slaveHandle = (hal_spi_slave_t *)handle; transfer.txData = xfer->txData; transfer.rxData = xfer->rxData; transfer.dataSize = xfer->dataSize; transfer.configFlags = xfer->flags; return HAL_SpiGetStatus(SPI_SlaveTransferNonBlocking((SPI_Type *)s_spiBases[slaveHandle->instance], &slaveHandle->hardwareHandle, &transfer)); } hal_spi_status_t HAL_SpiSlaveTransferGetCount(hal_spi_slave_handle_t handle, size_t *count) { hal_spi_slave_t *slaveHandle; assert(handle); assert(count); slaveHandle = (hal_spi_slave_t *)handle; return HAL_SpiGetStatus( SPI_SlaveTransferGetCount((SPI_Type *)s_spiBases[slaveHandle->instance], &slaveHandle->hardwareHandle, count)); } hal_spi_status_t HAL_SpiSlaveTransferAbort(hal_spi_slave_handle_t handle) { hal_spi_slave_t *slaveHandle; assert(handle); slaveHandle = (hal_spi_slave_t *)handle; SPI_SlaveTransferAbort((SPI_Type *)s_spiBases[slaveHandle->instance], &slaveHandle->hardwareHandle); return kStatus_HAL_SpiSuccess; }
5e1c3db7835b1798ed2661d05435f1b0ce39b62a
ec6a71b57ebe88538269197fd16bede6bc2062ae
/erts/include/internal/sparc32/rwlock.h
1cc516cdad0c56711099573974971a564e649eb3
[ "Apache-2.0" ]
permissive
erlang/otp
7c6e88ca955bd6a3ede1530154c80e8ce449a370
334589af62a8db25a81afba2ecc50f33ff69ddb8
refs/heads/master
2023-08-30T23:37:28.061328
2023-08-30T04:20:48
2023-08-30T04:20:48
374,927
9,920
3,018
Apache-2.0
2023-09-14T10:37:26
2009-11-16T17:17:57
Erlang
UTF-8
C
false
false
3,398
h
rwlock.h
/* * %CopyrightBegin% * * Copyright Ericsson AB 2005-2016. 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. * * %CopyrightEnd% */ /* * Native ethread rwlocks on SPARC V9. * Author: Mikael Pettersson. */ #ifndef ETHREAD_SPARC32_RWLOCK_H #define ETHREAD_SPARC32_RWLOCK_H #define ETHR_HAVE_NATIVE_RWSPINLOCKS 1 #define ETHR_NATIVE_RWSPINLOCK_IMPL "ethread" /* Unlocked if zero, read-locked if positive, write-locked if -1. */ typedef struct { volatile int lock; } ethr_native_rwlock_t; #if defined(ETHR_TRY_INLINE_FUNCS) || defined(ETHR_AUX_IMPL__) static ETHR_INLINE void ethr_native_rwlock_init(ethr_native_rwlock_t *lock) { lock->lock = 0; } static ETHR_INLINE void ethr_native_read_unlock(ethr_native_rwlock_t *lock) { unsigned int old, new; ETHR_MEMBAR(ETHR_LoadLoad|ETHR_StoreLoad); do { old = lock->lock; new = old-1; __asm__ __volatile__( "cas [%2], %1, %0" : "=&r"(new) : "r"(old), "r"(&lock->lock), "0"(new) : "memory"); } while (__builtin_expect(old != new, 0)); } static ETHR_INLINE int ethr_native_read_trylock(ethr_native_rwlock_t *lock) { int old, new; do { old = lock->lock; if (__builtin_expect(old < 0, 0)) return 0; new = old+1; __asm__ __volatile__( "cas [%2], %1, %0" : "=&r"(new) : "r"(old), "r"(&lock->lock), "0"(new) : "memory"); } while (__builtin_expect(old != new, 0)); ETHR_MEMBAR(ETHR_StoreLoad|ETHR_StoreStore); return 1; } static ETHR_INLINE int ethr_native_read_is_locked(ethr_native_rwlock_t *lock) { return lock->lock < 0; } static ETHR_INLINE void ethr_native_read_lock(ethr_native_rwlock_t *lock) { for(;;) { if (__builtin_expect(ethr_native_read_trylock(lock) != 0, 1)) break; do { ETHR_MEMBAR(ETHR_LoadLoad); } while (ethr_native_read_is_locked(lock)); } } static ETHR_INLINE void ethr_native_write_unlock(ethr_native_rwlock_t *lock) { ETHR_MEMBAR(ETHR_LoadStore|ETHR_StoreStore); lock->lock = 0; } static ETHR_INLINE int ethr_native_write_trylock(ethr_native_rwlock_t *lock) { unsigned int old, new; do { old = lock->lock; if (__builtin_expect(old != 0, 0)) return 0; new = -1; __asm__ __volatile__( "cas [%2], %1, %0" : "=&r"(new) : "r"(old), "r"(&lock->lock), "0"(new) : "memory"); } while (__builtin_expect(old != new, 0)); ETHR_MEMBAR(ETHR_StoreLoad|ETHR_StoreStore); return 1; } static ETHR_INLINE int ethr_native_write_is_locked(ethr_native_rwlock_t *lock) { return lock->lock != 0; } static ETHR_INLINE void ethr_native_write_lock(ethr_native_rwlock_t *lock) { for(;;) { if (__builtin_expect(ethr_native_write_trylock(lock) != 0, 1)) break; do { ETHR_MEMBAR(ETHR_LoadLoad); } while (ethr_native_write_is_locked(lock)); } } #endif /* ETHR_TRY_INLINE_FUNCS */ #endif /* ETHREAD_SPARC32_RWLOCK_H */
45a5a55fda484ffb1d7dcbf9a444519c59fcb8f7
b57c00ee9d73e157e772fbb2397c37e33b164ca3
/OpenDingTalkHelperForiOS/Pods/Headers/Private/BRPickerView/BRResultModel.h
f95bb15101676b8cf1706d15538f10a8248b2a2a
[ "MIT" ]
permissive
SmileZXLee/OpenDingTalkHelperForiOS
4b84b24479894ea9384a2f414422b636f6578cec
a83c2680a91b6072403c07cfaed8b12e83bdc028
refs/heads/master
2023-05-28T17:59:32.974595
2023-05-23T10:33:43
2023-05-23T10:33:43
216,163,695
246
41
null
null
null
null
UTF-8
C
false
false
67
h
BRResultModel.h
../../../BRPickerView/BRPickerView/StringPickerView/BRResultModel.h
28e69635fc90cc6e9447f4449a3cb05ebe846aa1
33377c4d113cf9ea1338077af6bd645f3c5796b3
/extensions/android/ringlibsdl/project/jni/flac-1.2.1/src/metaflac/operations.c
54774bf69b0d61d501b9e6d3444733380f92a103
[ "BSD-3-Clause", "GPL-2.0-only", "LGPL-2.1-only", "GFDL-1.2-only", "LGPL-2.0-or-later", "GPL-1.0-or-later", "GPL-2.0-or-later", "GFDL-1.1-or-later", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
ring-lang/ring
56f55111f751b0274d4f588871f806a8c2734dea
2081d2efb41c9dacd49b7a6944b9ca332638ba64
refs/heads/master
2023-09-04T16:54:44.309452
2023-09-03T10:28:57
2023-09-03T10:28:57
54,633,811
1,360
555
MIT
2023-08-03T01:48:24
2016-03-24T10:29:27
C
UTF-8
C
false
false
26,180
c
operations.c
/* metaflac - Command-line FLAC metadata editor * Copyright (C) 2001,2002,2003,2004,2005,2006,2007 Josh Coalson * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #if HAVE_CONFIG_H # include <config.h> #endif #include "operations.h" #include "usage.h" #include "utils.h" #include "FLAC/assert.h" #include "FLAC/metadata.h" #include "share/alloc.h" #include "share/grabbag.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "operations_shorthand.h" static void show_version(void); static FLAC__bool do_major_operation(const CommandLineOptions *options); static FLAC__bool do_major_operation_on_file(const char *filename, const CommandLineOptions *options); static FLAC__bool do_major_operation__list(const char *filename, FLAC__Metadata_Chain *chain, const CommandLineOptions *options); static FLAC__bool do_major_operation__append(FLAC__Metadata_Chain *chain, const CommandLineOptions *options); static FLAC__bool do_major_operation__remove(FLAC__Metadata_Chain *chain, const CommandLineOptions *options); static FLAC__bool do_major_operation__remove_all(FLAC__Metadata_Chain *chain, const CommandLineOptions *options); static FLAC__bool do_shorthand_operations(const CommandLineOptions *options); static FLAC__bool do_shorthand_operations_on_file(const char *filename, const CommandLineOptions *options); static FLAC__bool do_shorthand_operation(const char *filename, FLAC__bool prefix_with_filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write, FLAC__bool utf8_convert); static FLAC__bool do_shorthand_operation__add_replay_gain(char **filenames, unsigned num_files, FLAC__bool preserve_modtime); static FLAC__bool do_shorthand_operation__add_padding(const char *filename, FLAC__Metadata_Chain *chain, unsigned length, FLAC__bool *needs_write); static FLAC__bool passes_filter(const CommandLineOptions *options, const FLAC__StreamMetadata *block, unsigned block_number); static void write_metadata(const char *filename, FLAC__StreamMetadata *block, unsigned block_number, FLAC__bool raw, FLAC__bool hexdump_application); /* from operations_shorthand_seektable.c */ extern FLAC__bool do_shorthand_operation__add_seekpoints(const char *filename, FLAC__Metadata_Chain *chain, const char *specification, FLAC__bool *needs_write); /* from operations_shorthand_streaminfo.c */ extern FLAC__bool do_shorthand_operation__streaminfo(const char *filename, FLAC__bool prefix_with_filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write); /* from operations_shorthand_vorbiscomment.c */ extern FLAC__bool do_shorthand_operation__vorbis_comment(const char *filename, FLAC__bool prefix_with_filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write, FLAC__bool raw); /* from operations_shorthand_cuesheet.c */ extern FLAC__bool do_shorthand_operation__cuesheet(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write); /* from operations_shorthand_picture.c */ extern FLAC__bool do_shorthand_operation__picture(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write); FLAC__bool do_operations(const CommandLineOptions *options) { FLAC__bool ok = true; if(options->show_long_help) { long_usage(0); } if(options->show_version) { show_version(); } else if(options->args.checks.num_major_ops > 0) { FLAC__ASSERT(options->args.checks.num_shorthand_ops == 0); FLAC__ASSERT(options->args.checks.num_major_ops == 1); FLAC__ASSERT(options->args.checks.num_major_ops == options->ops.num_operations); ok = do_major_operation(options); } else if(options->args.checks.num_shorthand_ops > 0) { FLAC__ASSERT(options->args.checks.num_shorthand_ops == options->ops.num_operations); ok = do_shorthand_operations(options); } return ok; } /* * local routines */ void show_version(void) { printf("metaflac %s\n", FLAC__VERSION_STRING); } FLAC__bool do_major_operation(const CommandLineOptions *options) { unsigned i; FLAC__bool ok = true; /* to die after first error, v--- add '&& ok' here */ for(i = 0; i < options->num_files; i++) ok &= do_major_operation_on_file(options->filenames[i], options); return ok; } FLAC__bool do_major_operation_on_file(const char *filename, const CommandLineOptions *options) { FLAC__bool ok = true, needs_write = false, is_ogg = false; FLAC__Metadata_Chain *chain = FLAC__metadata_chain_new(); if(0 == chain) die("out of memory allocating chain"); /*@@@@ lame way of guessing the file type */ if(strlen(filename) >= 4 && (0 == strcmp(filename+strlen(filename)-4, ".oga") || 0 == strcmp(filename+strlen(filename)-4, ".ogg"))) is_ogg = true; if(! (is_ogg? FLAC__metadata_chain_read_ogg(chain, filename) : FLAC__metadata_chain_read(chain, filename)) ) { print_error_with_chain_status(chain, "%s: ERROR: reading metadata", filename); FLAC__metadata_chain_delete(chain); return false; } switch(options->ops.operations[0].type) { case OP__LIST: ok = do_major_operation__list(options->prefix_with_filename? filename : 0, chain, options); break; case OP__APPEND: ok = do_major_operation__append(chain, options); needs_write = true; break; case OP__REMOVE: ok = do_major_operation__remove(chain, options); needs_write = true; break; case OP__REMOVE_ALL: ok = do_major_operation__remove_all(chain, options); needs_write = true; break; case OP__MERGE_PADDING: FLAC__metadata_chain_merge_padding(chain); needs_write = true; break; case OP__SORT_PADDING: FLAC__metadata_chain_sort_padding(chain); needs_write = true; break; default: FLAC__ASSERT(0); return false; } if(ok && needs_write) { if(options->use_padding) FLAC__metadata_chain_sort_padding(chain); ok = FLAC__metadata_chain_write(chain, options->use_padding, options->preserve_modtime); if(!ok) print_error_with_chain_status(chain, "%s: ERROR: writing FLAC file", filename); } FLAC__metadata_chain_delete(chain); return ok; } FLAC__bool do_major_operation__list(const char *filename, FLAC__Metadata_Chain *chain, const CommandLineOptions *options) { FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new(); FLAC__StreamMetadata *block; FLAC__bool ok = true; unsigned block_number; if(0 == iterator) die("out of memory allocating iterator"); FLAC__metadata_iterator_init(iterator, chain); block_number = 0; do { block = FLAC__metadata_iterator_get_block(iterator); ok &= (0 != block); if(!ok) fprintf(stderr, "%s: ERROR: couldn't get block from chain\n", filename); else if(passes_filter(options, FLAC__metadata_iterator_get_block(iterator), block_number)) write_metadata(filename, block, block_number, !options->utf8_convert, options->application_data_format_is_hexdump); block_number++; } while(ok && FLAC__metadata_iterator_next(iterator)); FLAC__metadata_iterator_delete(iterator); return ok; } FLAC__bool do_major_operation__append(FLAC__Metadata_Chain *chain, const CommandLineOptions *options) { (void) chain, (void) options; fprintf(stderr, "ERROR: --append not implemented yet\n"); return false; } FLAC__bool do_major_operation__remove(FLAC__Metadata_Chain *chain, const CommandLineOptions *options) { FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new(); FLAC__bool ok = true; unsigned block_number; if(0 == iterator) die("out of memory allocating iterator"); FLAC__metadata_iterator_init(iterator, chain); block_number = 0; while(ok && FLAC__metadata_iterator_next(iterator)) { block_number++; if(passes_filter(options, FLAC__metadata_iterator_get_block(iterator), block_number)) { ok &= FLAC__metadata_iterator_delete_block(iterator, options->use_padding); if(options->use_padding) ok &= FLAC__metadata_iterator_next(iterator); } } FLAC__metadata_iterator_delete(iterator); return ok; } FLAC__bool do_major_operation__remove_all(FLAC__Metadata_Chain *chain, const CommandLineOptions *options) { FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new(); FLAC__bool ok = true; if(0 == iterator) die("out of memory allocating iterator"); FLAC__metadata_iterator_init(iterator, chain); while(ok && FLAC__metadata_iterator_next(iterator)) { ok &= FLAC__metadata_iterator_delete_block(iterator, options->use_padding); if(options->use_padding) ok &= FLAC__metadata_iterator_next(iterator); } FLAC__metadata_iterator_delete(iterator); return ok; } FLAC__bool do_shorthand_operations(const CommandLineOptions *options) { unsigned i; FLAC__bool ok = true; /* to die after first error, v--- add '&& ok' here */ for(i = 0; i < options->num_files; i++) ok &= do_shorthand_operations_on_file(options->filenames[i], options); /* check if OP__ADD_REPLAY_GAIN requested */ if(ok && options->num_files > 0) { for(i = 0; i < options->ops.num_operations; i++) { if(options->ops.operations[i].type == OP__ADD_REPLAY_GAIN) ok = do_shorthand_operation__add_replay_gain(options->filenames, options->num_files, options->preserve_modtime); } } return ok; } FLAC__bool do_shorthand_operations_on_file(const char *filename, const CommandLineOptions *options) { unsigned i; FLAC__bool ok = true, needs_write = false, use_padding = options->use_padding; FLAC__Metadata_Chain *chain = FLAC__metadata_chain_new(); if(0 == chain) die("out of memory allocating chain"); if(!FLAC__metadata_chain_read(chain, filename)) { print_error_with_chain_status(chain, "%s: ERROR: reading metadata", filename); return false; } for(i = 0; i < options->ops.num_operations && ok; i++) { /* * Do OP__ADD_SEEKPOINT last to avoid decoding twice if both * --add-seekpoint and --import-cuesheet-from are used. */ if(options->ops.operations[i].type != OP__ADD_SEEKPOINT) ok &= do_shorthand_operation(filename, options->prefix_with_filename, chain, &options->ops.operations[i], &needs_write, options->utf8_convert); /* The following seems counterintuitive but the meaning * of 'use_padding' is 'try to keep the overall metadata * to its original size, adding or truncating extra * padding if necessary' which is why we need to turn it * off in this case. If we don't, the extra padding block * will just be truncated. */ if(options->ops.operations[i].type == OP__ADD_PADDING) use_padding = false; } /* * Do OP__ADD_SEEKPOINT last to avoid decoding twice if both * --add-seekpoint and --import-cuesheet-from are used. */ for(i = 0; i < options->ops.num_operations && ok; i++) { if(options->ops.operations[i].type == OP__ADD_SEEKPOINT) ok &= do_shorthand_operation(filename, options->prefix_with_filename, chain, &options->ops.operations[i], &needs_write, options->utf8_convert); } if(ok && needs_write) { if(use_padding) FLAC__metadata_chain_sort_padding(chain); ok = FLAC__metadata_chain_write(chain, use_padding, options->preserve_modtime); if(!ok) print_error_with_chain_status(chain, "%s: ERROR: writing FLAC file", filename); } FLAC__metadata_chain_delete(chain); return ok; } FLAC__bool do_shorthand_operation(const char *filename, FLAC__bool prefix_with_filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write, FLAC__bool utf8_convert) { FLAC__bool ok = true; switch(operation->type) { case OP__SHOW_MD5SUM: case OP__SHOW_MIN_BLOCKSIZE: case OP__SHOW_MAX_BLOCKSIZE: case OP__SHOW_MIN_FRAMESIZE: case OP__SHOW_MAX_FRAMESIZE: case OP__SHOW_SAMPLE_RATE: case OP__SHOW_CHANNELS: case OP__SHOW_BPS: case OP__SHOW_TOTAL_SAMPLES: case OP__SET_MD5SUM: case OP__SET_MIN_BLOCKSIZE: case OP__SET_MAX_BLOCKSIZE: case OP__SET_MIN_FRAMESIZE: case OP__SET_MAX_FRAMESIZE: case OP__SET_SAMPLE_RATE: case OP__SET_CHANNELS: case OP__SET_BPS: case OP__SET_TOTAL_SAMPLES: ok = do_shorthand_operation__streaminfo(filename, prefix_with_filename, chain, operation, needs_write); break; case OP__SHOW_VC_VENDOR: case OP__SHOW_VC_FIELD: case OP__REMOVE_VC_ALL: case OP__REMOVE_VC_FIELD: case OP__REMOVE_VC_FIRSTFIELD: case OP__SET_VC_FIELD: case OP__IMPORT_VC_FROM: case OP__EXPORT_VC_TO: ok = do_shorthand_operation__vorbis_comment(filename, prefix_with_filename, chain, operation, needs_write, !utf8_convert); break; case OP__IMPORT_CUESHEET_FROM: case OP__EXPORT_CUESHEET_TO: ok = do_shorthand_operation__cuesheet(filename, chain, operation, needs_write); break; case OP__IMPORT_PICTURE_FROM: case OP__EXPORT_PICTURE_TO: ok = do_shorthand_operation__picture(filename, chain, operation, needs_write); break; case OP__ADD_SEEKPOINT: ok = do_shorthand_operation__add_seekpoints(filename, chain, operation->argument.add_seekpoint.specification, needs_write); break; case OP__ADD_REPLAY_GAIN: /* this command is always executed last */ ok = true; break; case OP__ADD_PADDING: ok = do_shorthand_operation__add_padding(filename, chain, operation->argument.add_padding.length, needs_write); break; default: ok = false; FLAC__ASSERT(0); break; }; return ok; } FLAC__bool do_shorthand_operation__add_replay_gain(char **filenames, unsigned num_files, FLAC__bool preserve_modtime) { FLAC__StreamMetadata streaminfo; float *title_gains = 0, *title_peaks = 0; float album_gain, album_peak; unsigned sample_rate = 0; unsigned bits_per_sample = 0; unsigned channels = 0; unsigned i; const char *error; FLAC__bool first = true; FLAC__ASSERT(num_files > 0); for(i = 0; i < num_files; i++) { FLAC__ASSERT(0 != filenames[i]); if(!FLAC__metadata_get_streaminfo(filenames[i], &streaminfo)) { fprintf(stderr, "%s: ERROR: can't open file or get STREAMINFO block\n", filenames[i]); return false; } if(first) { first = false; sample_rate = streaminfo.data.stream_info.sample_rate; bits_per_sample = streaminfo.data.stream_info.bits_per_sample; channels = streaminfo.data.stream_info.channels; } else { if(sample_rate != streaminfo.data.stream_info.sample_rate) { fprintf(stderr, "%s: ERROR: sample rate of %u Hz does not match previous files' %u Hz\n", filenames[i], streaminfo.data.stream_info.sample_rate, sample_rate); return false; } if(bits_per_sample != streaminfo.data.stream_info.bits_per_sample) { fprintf(stderr, "%s: ERROR: resolution of %u bps does not match previous files' %u bps\n", filenames[i], streaminfo.data.stream_info.bits_per_sample, bits_per_sample); return false; } if(channels != streaminfo.data.stream_info.channels) { fprintf(stderr, "%s: ERROR: # channels (%u) does not match previous files' (%u)\n", filenames[i], streaminfo.data.stream_info.channels, channels); return false; } } if(!grabbag__replaygain_is_valid_sample_frequency(sample_rate)) { fprintf(stderr, "%s: ERROR: sample rate of %u Hz is not supported\n", filenames[i], sample_rate); return false; } if(channels != 1 && channels != 2) { fprintf(stderr, "%s: ERROR: # of channels (%u) is not supported, must be 1 or 2\n", filenames[i], channels); return false; } } FLAC__ASSERT(bits_per_sample >= FLAC__MIN_BITS_PER_SAMPLE && bits_per_sample <= FLAC__MAX_BITS_PER_SAMPLE); if(!grabbag__replaygain_init(sample_rate)) { FLAC__ASSERT(0); /* double protection */ fprintf(stderr, "internal error\n"); return false; } if( 0 == (title_gains = (float*)safe_malloc_mul_2op_(sizeof(float), /*times*/num_files)) || 0 == (title_peaks = (float*)safe_malloc_mul_2op_(sizeof(float), /*times*/num_files)) ) die("out of memory allocating space for title gains/peaks"); for(i = 0; i < num_files; i++) { if(0 != (error = grabbag__replaygain_analyze_file(filenames[i], title_gains+i, title_peaks+i))) { fprintf(stderr, "%s: ERROR: during analysis (%s)\n", filenames[i], error); free(title_gains); free(title_peaks); return false; } } grabbag__replaygain_get_album(&album_gain, &album_peak); for(i = 0; i < num_files; i++) { if(0 != (error = grabbag__replaygain_store_to_file(filenames[i], album_gain, album_peak, title_gains[i], title_peaks[i], preserve_modtime))) { fprintf(stderr, "%s: ERROR: writing tags (%s)\n", filenames[i], error); free(title_gains); free(title_peaks); return false; } } free(title_gains); free(title_peaks); return true; } FLAC__bool do_shorthand_operation__add_padding(const char *filename, FLAC__Metadata_Chain *chain, unsigned length, FLAC__bool *needs_write) { FLAC__StreamMetadata *padding = 0; FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new(); if(0 == iterator) die("out of memory allocating iterator"); FLAC__metadata_iterator_init(iterator, chain); while(FLAC__metadata_iterator_next(iterator)) ; padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING); if(0 == padding) die("out of memory allocating PADDING block"); padding->length = length; if(!FLAC__metadata_iterator_insert_block_after(iterator, padding)) { print_error_with_chain_status(chain, "%s: ERROR: adding new PADDING block to metadata", filename); FLAC__metadata_object_delete(padding); FLAC__metadata_iterator_delete(iterator); return false; } FLAC__metadata_iterator_delete(iterator); *needs_write = true; return true; } FLAC__bool passes_filter(const CommandLineOptions *options, const FLAC__StreamMetadata *block, unsigned block_number) { unsigned i, j; FLAC__bool matches_number = false, matches_type = false; FLAC__bool has_block_number_arg = false; for(i = 0; i < options->args.num_arguments; i++) { if(options->args.arguments[i].type == ARG__BLOCK_TYPE || options->args.arguments[i].type == ARG__EXCEPT_BLOCK_TYPE) { for(j = 0; j < options->args.arguments[i].value.block_type.num_entries; j++) { if(options->args.arguments[i].value.block_type.entries[j].type == block->type) { if(block->type != FLAC__METADATA_TYPE_APPLICATION || !options->args.arguments[i].value.block_type.entries[j].filter_application_by_id || 0 == memcmp(options->args.arguments[i].value.block_type.entries[j].application_id, block->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)) matches_type = true; } } } else if(options->args.arguments[i].type == ARG__BLOCK_NUMBER) { has_block_number_arg = true; for(j = 0; j < options->args.arguments[i].value.block_number.num_entries; j++) { if(options->args.arguments[i].value.block_number.entries[j] == block_number) matches_number = true; } } } if(!has_block_number_arg) matches_number = true; if(options->args.checks.has_block_type) { FLAC__ASSERT(!options->args.checks.has_except_block_type); } else if(options->args.checks.has_except_block_type) matches_type = !matches_type; else matches_type = true; return matches_number && matches_type; } void write_metadata(const char *filename, FLAC__StreamMetadata *block, unsigned block_number, FLAC__bool raw, FLAC__bool hexdump_application) { unsigned i, j; /*@@@ yuck, should do this with a varargs function or something: */ #define PPR if(filename)printf("%s:",filename); PPR; printf("METADATA block #%u\n", block_number); PPR; printf(" type: %u (%s)\n", (unsigned)block->type, block->type < FLAC__METADATA_TYPE_UNDEFINED? FLAC__MetadataTypeString[block->type] : "UNKNOWN"); PPR; printf(" is last: %s\n", block->is_last? "true":"false"); PPR; printf(" length: %u\n", block->length); switch(block->type) { case FLAC__METADATA_TYPE_STREAMINFO: PPR; printf(" minimum blocksize: %u samples\n", block->data.stream_info.min_blocksize); PPR; printf(" maximum blocksize: %u samples\n", block->data.stream_info.max_blocksize); PPR; printf(" minimum framesize: %u bytes\n", block->data.stream_info.min_framesize); PPR; printf(" maximum framesize: %u bytes\n", block->data.stream_info.max_framesize); PPR; printf(" sample_rate: %u Hz\n", block->data.stream_info.sample_rate); PPR; printf(" channels: %u\n", block->data.stream_info.channels); PPR; printf(" bits-per-sample: %u\n", block->data.stream_info.bits_per_sample); #ifdef _MSC_VER PPR; printf(" total samples: %I64u\n", block->data.stream_info.total_samples); #else PPR; printf(" total samples: %llu\n", (unsigned long long)block->data.stream_info.total_samples); #endif PPR; printf(" MD5 signature: "); for(i = 0; i < 16; i++) { printf("%02x", (unsigned)block->data.stream_info.md5sum[i]); } printf("\n"); break; case FLAC__METADATA_TYPE_PADDING: /* nothing to print */ break; case FLAC__METADATA_TYPE_APPLICATION: PPR; printf(" application ID: "); for(i = 0; i < 4; i++) printf("%02x", block->data.application.id[i]); printf("\n"); PPR; printf(" data contents:\n"); if(0 != block->data.application.data) { if(hexdump_application) hexdump(filename, block->data.application.data, block->length - FLAC__STREAM_METADATA_HEADER_LENGTH, " "); else (void) local_fwrite(block->data.application.data, 1, block->length - FLAC__STREAM_METADATA_HEADER_LENGTH, stdout); } break; case FLAC__METADATA_TYPE_SEEKTABLE: PPR; printf(" seek points: %u\n", block->data.seek_table.num_points); for(i = 0; i < block->data.seek_table.num_points; i++) { if(block->data.seek_table.points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) { #ifdef _MSC_VER PPR; printf(" point %u: sample_number=%I64u, stream_offset=%I64u, frame_samples=%u\n", i, block->data.seek_table.points[i].sample_number, block->data.seek_table.points[i].stream_offset, block->data.seek_table.points[i].frame_samples); #else PPR; printf(" point %u: sample_number=%llu, stream_offset=%llu, frame_samples=%u\n", i, (unsigned long long)block->data.seek_table.points[i].sample_number, (unsigned long long)block->data.seek_table.points[i].stream_offset, block->data.seek_table.points[i].frame_samples); #endif } else { PPR; printf(" point %u: PLACEHOLDER\n", i); } } break; case FLAC__METADATA_TYPE_VORBIS_COMMENT: PPR; printf(" vendor string: "); write_vc_field(0, &block->data.vorbis_comment.vendor_string, raw, stdout); PPR; printf(" comments: %u\n", block->data.vorbis_comment.num_comments); for(i = 0; i < block->data.vorbis_comment.num_comments; i++) { PPR; printf(" comment[%u]: ", i); write_vc_field(0, &block->data.vorbis_comment.comments[i], raw, stdout); } break; case FLAC__METADATA_TYPE_CUESHEET: PPR; printf(" media catalog number: %s\n", block->data.cue_sheet.media_catalog_number); #ifdef _MSC_VER PPR; printf(" lead-in: %I64u\n", block->data.cue_sheet.lead_in); #else PPR; printf(" lead-in: %llu\n", (unsigned long long)block->data.cue_sheet.lead_in); #endif PPR; printf(" is CD: %s\n", block->data.cue_sheet.is_cd? "true":"false"); PPR; printf(" number of tracks: %u\n", block->data.cue_sheet.num_tracks); for(i = 0; i < block->data.cue_sheet.num_tracks; i++) { const FLAC__StreamMetadata_CueSheet_Track *track = block->data.cue_sheet.tracks+i; const FLAC__bool is_last = (i == block->data.cue_sheet.num_tracks-1); const FLAC__bool is_leadout = is_last && track->num_indices == 0; PPR; printf(" track[%u]\n", i); #ifdef _MSC_VER PPR; printf(" offset: %I64u\n", track->offset); #else PPR; printf(" offset: %llu\n", (unsigned long long)track->offset); #endif if(is_last) { PPR; printf(" number: %u (%s)\n", (unsigned)track->number, is_leadout? "LEAD-OUT" : "INVALID"); } else { PPR; printf(" number: %u\n", (unsigned)track->number); } if(!is_leadout) { PPR; printf(" ISRC: %s\n", track->isrc); PPR; printf(" type: %s\n", track->type == 1? "DATA" : "AUDIO"); PPR; printf(" pre-emphasis: %s\n", track->pre_emphasis? "true":"false"); PPR; printf(" number of index points: %u\n", track->num_indices); for(j = 0; j < track->num_indices; j++) { const FLAC__StreamMetadata_CueSheet_Index *index = track->indices+j; PPR; printf(" index[%u]\n", j); #ifdef _MSC_VER PPR; printf(" offset: %I64u\n", index->offset); #else PPR; printf(" offset: %llu\n", (unsigned long long)index->offset); #endif PPR; printf(" number: %u\n", (unsigned)index->number); } } } break; case FLAC__METADATA_TYPE_PICTURE: PPR; printf(" type: %u (%s)\n", block->data.picture.type, block->data.picture.type < FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED? FLAC__StreamMetadata_Picture_TypeString[block->data.picture.type] : "UNDEFINED"); PPR; printf(" MIME type: %s\n", block->data.picture.mime_type); PPR; printf(" description: %s\n", block->data.picture.description); PPR; printf(" width: %u\n", (unsigned)block->data.picture.width); PPR; printf(" height: %u\n", (unsigned)block->data.picture.height); PPR; printf(" depth: %u\n", (unsigned)block->data.picture.depth); PPR; printf(" colors: %u%s\n", (unsigned)block->data.picture.colors, block->data.picture.colors? "" : " (unindexed)"); PPR; printf(" data length: %u\n", (unsigned)block->data.picture.data_length); PPR; printf(" data:\n"); if(0 != block->data.picture.data) hexdump(filename, block->data.picture.data, block->data.picture.data_length, " "); break; default: PPR; printf(" data contents:\n"); if(0 != block->data.unknown.data) hexdump(filename, block->data.unknown.data, block->length, " "); break; } #undef PPR }
f5df08807398156d254e9e5875c2fa47e76f48ff
930e24019ec42ad7633eebfa974a05773167f210
/limbo/thirdparty/lefdef/5.8/def/cdef/defMsgTable.h
34eb53411f012821e5681a150f63e440c1d8c15a
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
limbo018/Limbo
ab3d75ff13d57042acb5b14e3f97c643bbd7f0c9
f66d910cc1ce589185bad3da1d26a10710036302
refs/heads/master
2023-08-21T16:20:39.651170
2023-07-21T08:36:24
2023-07-21T08:36:24
106,957,057
116
48
MIT
2023-07-21T08:36:25
2017-10-14T19:35:04
C++
UTF-8
C
false
false
22,462
h
defMsgTable.h
/* * emsMkError: */ #include <stdio.h> #include "ems.h" #ifdef TSIZE #undef TSIZE #define TSIZE 2048 #endif emsError_t DEFEmsMsgTable[] = { {5000 , EMS_NONE, "The 'defrRead' function has been called before the 'defrInit' function.\nThe 'defrInit' function should be called prior to the 'defrRead' function.", -1, 0}, {5001 , EMS_NONE, "DEF statement found in the def file with no callback set.", -1, 0}, {6000 , EMS_NONE, "The syntax for an ALIAS statement is \"&ALIAS aliasName = aliasDefinition &ENDALIAS\". '=' is missing after the aliasName.", -1, 0}, {6001 , EMS_NONE, "End of file is reached while parsing in the middle of an ALIAS statement.\nReview you def file and add '&ENDALIAS' in the ALIAS statement.", -1, 0}, {6002 , EMS_NONE, "The def file is incomplete.", -1, 0}, {6003 , EMS_NONE, "The BEGINEXT tag is missing in the DEF file. Include the tag and then try again.", -1, 0}, {6004 , EMS_NONE, "The BEGINEXT tag is empty. Specify a value for the tag and try again.", -1, 0}, {6005 , EMS_NONE, "The '\"' is missing within the tag. Specify the '\"' in the tag and then try again.", -1, 0}, {6006 , EMS_NONE, "The ending '\"' is missing in the tag. Specify the ending '\"' in the tag and then try again.", -1, 0}, {6007 , EMS_NONE, "The ENDEXT statement is missing in the DEF file. Include the statement and then try again.", -1, 0}, {6008 , EMS_NONE, "Invalid characters found in \'%s\'.\nThese characters might be using the character types other than English.\nCreate characters by specifying valid characters types.", -1, 0}, {6010 , EMS_NONE, "An error has been reported in callback.", -1, 0}, {6011 , EMS_NONE, "Too many syntax errors have been reported.", -1, 0}, {6030 , EMS_NONE, "Invalid direction specified with FPC name. The valid direction is either 'H' or 'V'. Specify a valid vale and then try again.", -1, 0}, {6060 , EMS_NONE, "Invalid value specified for IOTIMING rise/fall. The valid value for rise is 'R' and for fall is 'F'. Specify a valid value and then try again.", -1, 0}, {6080 , EMS_NONE, "An internal error has occurred. The index number for the SUBNET wires array is less then or equal to 0.\nContact Cadence Customer Support with this error information.", -1, 0}, {6081 , EMS_NONE, "An internal error has occurred. The index number for the NET PATH wires array is less then or equal to 0.\nContact Cadence Customer Support with this error information.", -1, 0}, {6082 , EMS_NONE, "An internal error has occurred. The index number for the NET SHIELDPATH wires array is less then or equal to 0.\nContact Cadence Customer Support with this error information.", -1, 0}, {6083 , EMS_NONE, "The index number %d specified for the NET INSTANCE is invalid.\nValid index is from 0 to %d. Specify a valid index number and then try again.", -1, 0}, {6084 , EMS_NONE, "The index number %d specified for the NET PIN is invalid.\nValid index is from 0 to %d. Specify a valid index number and then try again.", -1, 0}, {6085 , EMS_NONE, "The index number %d specified for the NET POLYGON is invalid.\nValid index is from 0 to %d. Specify a valid index number and then try again.", -1, 0}, {6086 , EMS_NONE, "The index number %d specified for the NET RECTANGLE is invalid.\nValid index is from 0 to %d. Specify a valid index number and then try again.", -1, 0}, {6090 , EMS_NONE, "The index number %d specified for the NONDEFAULT LAYER is invalid.\nValid index is from 0 to %d. Specify a valid index number and then try again.", -1, 0}, {6091 , EMS_NONE, "The index number %d specified for the NONDEFAULT PROPERTY is invalid.\nValid index is from 0 to %d. Specify a valid index number and then try again.", -1, 0}, {6100 , EMS_NONE, "The value spefified for PARTITION SETUP is invalid. The valid value for SETUP is 'R' or 'F'. Specify a valid value for SETUP and then try again.", -1, 0}, {6101 , EMS_NONE, "The value spefified for PARTITION HOLD is invalid. The valid value for HOLD is 'R' or 'F'. Specify a valid value for HOLD and then try again.", -1, 0}, {6120 , EMS_NONE, "The index number %d specified for the PIN PROPERTY is invalide.\nValid index number is from 0 to %d. Specify a valid index number and then try again.", -1, 0}, {6130 , EMS_NONE, "The index number %d specified for the REGION PROPERTY is invalide.\nValid index number is from 0 to %d. Specify a valid index number and then try again.", -1, 0}, {6131 , EMS_NONE, "The index number %d specified for the REGION RECTANGLE is invalide.\nValid index number is from 0 to %d. Specify a valid index number and then try again.", -1, 0}, {6140 , EMS_NONE, "The index number %d specified for the VIA LAYER RECTANGLE is invalide.\nValid index number is from 0 to %d. Specify a valid index number and then try again.", -1, 0}, {6150 , EMS_NONE, "The START statement in the SCANCHAINS has defined more than one time in the SCANCHAINS statement.\nUpdate the DEF file to only one START statement and then try again.", -1, 0}, {6151 , EMS_NONE, "The STOP statment in the SCANCHAINS has defined more than one time in the SCANCHAINS statement.\nUpdate the DEF file to only one STOP statement and then try again.", -1, 0}, {6160 , EMS_NONE, "The index number %d specified for the SLOT RECTANGLE is invalid.\nValid index number is from 0 to %d. Specify a valid index number and then try again.", -1, 0}, {6170 , EMS_NONE, "The TimingDisable type is invalid. The valid types are FROMPIN, & THRUPIN. Specify the valid type and then try again.", -1, 0}, {6180 , EMS_NONE, "The index number %d specified for the VIA POLYGON is invalid.\nValid index is from 0 to %d. Specify a valid index number and then try again", -1, 0}, {6200 , EMS_NONE, "The ASSERTION statement is invalid because it has an invalid operand rule.\nValid operand rule is either NET or PATH. Specify a valid operand and then try again.", -1, 0}, {6201 , EMS_NONE, "Unable to process the DEF file. Both WIREDLOGIC and DELAY statements are defined in constraint/assertion.\nUpdate the DEF file to define either a WIREDLOGIC or DELAY statement only.", -1, 0}, {6202 , EMS_NONE, "Unable to process the DEF file. Both SUM and DIFF statements are defined in constraint/assertion.\nUpdate the DEF file to define either a SUM or DIFF statement only.", -1, 0}, {6501 , EMS_NONE, "An error has been found while processing the DEF file '%s'\nUnit %d is a 5.6 or later syntax. Define the DEF file as 5.6 and then try again.", -1, 0}, {6502 , EMS_NONE, "The value %d defined for DEF UNITS DISTANCE MICRON is invalid\n. The valid values are 100, 200, 1000, 2000, 10000, or 20000. Specify a valid value and then try again.", -1, 0}, {6503 , EMS_NONE, "The execution has been stopped because the DEF parser 5.7 does not support DEF file with version %s.\nUpdate your DEF file to version 5.7 or earlier.", -1, 0}, {6504 , EMS_NONE, "Def parser version 5.7 and later does not support NAMESCASESENSITIVE OFF.\nEither remove this optional construct or set it to ON.", -1, 0}, {6505 , EMS_NONE, "The NONDEFAULTRULE statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6506 , EMS_NONE, "The NETEXPR statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6507 , EMS_NONE, "The SUPPLYSENSITIVITY statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6508 , EMS_NONE, "The GROUNDSENSITIVITY statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6509 , EMS_NONE, "The POLYGON statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6510 , EMS_NONE, "The ANTENNAPINPARTIALMETALAREA statement is available in version 5.4 and later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6511 , EMS_NONE, "The ANTENNAPINPARTIALMETALSIDEAREA statement is available in version 5.4 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6512 , EMS_NONE, "The ANTENNAPINGATEAREA statement is available in version 5.4 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6513 , EMS_NONE, "The ANTENNAPINDIFFAREA statement is available in version 5.4 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6514 , EMS_NONE, "The ANTENNAPINMAXAREACAR statement is available in version 5.4 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6515 , EMS_NONE, "The ANTENNAPINMAXSIDEAREACAR statement is available in version 5.4 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6516 , EMS_NONE, "The ANTENNAPINPARTIALCUTAREA statement is available in version 5.4 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6517 , EMS_NONE, "The ANTENNAPINMAXCUTCAR statement is available in version 5.4 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6518 , EMS_NONE, "The ANTENNAMODEL statement is available in version 5.5 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6519 , EMS_NONE, "The SPACING statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6520 , EMS_NONE, "The DESIGNRULEWIDTH statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6523 , EMS_NONE, "Invalid ROW statement defined in the DEF file. The DO statement which is required in the ROW statement is not defined.\nUpdate your DEF file with a DO statement.", -1, 0}, {6524 , EMS_NONE, "Invalid syntax specified. The valid syntax is either \"DO 1 BY num or DO num BY 1\". Specify the valid syntax and try again.", -1, 0}, {6525 , EMS_NONE, "The DO number %g in TRACK is invalid.\nThe number value has to be greater than 0. Specify the valid syntax and try again.", -1, 0}, {6526 , EMS_NONE, "The STEP number %g in TRACK is invalid.\nThe number value has to be greater than 0. Specify the valid syntax and try again.", -1, 0}, {6527 , EMS_NONE, "The DO number %g in GCELLGRID is invalid.\nThe number value has to be greater than 0. Specify the valid syntax and try again.", -1, 0}, {6528 , EMS_NONE, "The STEP number %g in GCELLGRID is invalid.\nThe number value has to be greater than 0. Specify the valid syntax and try again.", -1, 0}, {6529 , EMS_NONE, "The HALO statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6530 , EMS_NONE, "The FIXEDBUMP statement is available in version 5.5 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6531 , EMS_NONE, "The layerName which is required in path is missing. Include the layerName in the path and then try again.", -1, 0}, {6532 , EMS_NONE, "The VIA DO statement is available in version 5.5 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6533 , EMS_NONE, "Either the numX or numY in the VIA DO statement has invalid value. The value specified is 0.\nUpdate your DEF file with the correct value and then try again.", -1, 0}, {6534 , EMS_NONE, "The STYLE statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6535 , EMS_NONE, "The POLYGON statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6536 , EMS_NONE, "The RECT statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6537 , EMS_NONE, "The value %s for statement VOLTAGE is invalid. The value can only be integer.\nSpecify a valid value in units of millivolts", -1, 0}, {6538 , EMS_NONE, "The PARTITION statement is available in version 5.5 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6539 , EMS_NONE, "Invalid BLOCKAGE statement defined in the DEF file. The BLOCKAGE statment has both the LAYER and the PLACEMENT statements defined.\nUpdate your DEF file to have either BLOCKAGE or PLACEMENT statement only.", -1, 0}, {6540 , EMS_NONE, "The SPACING statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6541 , EMS_NONE, "The SPACING statement is defined in the LAYER statement,\nbut there is already either a SPACING statement or DESIGNRULEWIDTH statement has defined in the LAYER statement.\nUpdate your DEF file to have either SPACING statement or a DESIGNRULEWIDTH statement.", -1, 0}, {6542 , EMS_NONE, "The defined BLOCKAGES COMPONENT statement has either COMPONENT, SLOTS, FILLS, PUSHDOWN or EXCEPTPGNET defined.\nOnly one of these statements is allowed per LAYER. Updated the DEF file to define a valid BLOCKAGES COMPONENT statement per layer.", -1, 0}, {6543 , EMS_NONE, "The defined BLOCKAGES PLACEMENT statement has either COMPONENT, PUSHDOWN, SOFT or PARTIAL defined.\nOnly one of these statements is allowed per LAYER. Updated the DEF file to define a valid BLOCKAGES PLACEMENT statement.", -1, 0}, {6544 , EMS_NONE, "A POLYGON statement is defined in the BLOCKAGE statement,\nbut it is not defined in the BLOCKAGE LAYER statement.\nUpdate your DEF file to either remove the POLYGON statement from the BLOCKAGE statement or\ndefine the POLYGON statement in a BLOCKAGE LAYER statement.", -1, 0}, {6545 , EMS_NONE, "The NONDEFAULTRULE statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6546 , EMS_NONE, "The STYLES statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6547 , EMS_NONE, "The PLACEMENT SOFT is available in version 5.7 or later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6548 , EMS_NONE, "The PARTIAL is available in version 5.7 or later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6549 , EMS_NONE, "The EXCEPTPGNET is available in version 5.7 or later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6550 , EMS_NONE, "The HALO SOFT is available in version 5.7 or later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6551 , EMS_NONE, "The ROUTEHALO is available in version 5.7 or later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6552 , EMS_NONE, "The FILLWIREOPC is available in version 5.7 or later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6553 , EMS_NONE, "The LAYER OPC is available in version 5.7 or later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6554 , EMS_NONE, "The VIA OPC is available in version 5.7 or later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6555 , EMS_NONE, "The PORT in PINS is available in version 5.7 or later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6556 , EMS_NONE, "The PIN VIA statement is available in version 5.7 and later.\nHowever, your DEF file is defined with version %g.", -1, 0}, {6557 , EMS_NONE, "The VIARULE statement is available in version 5.6 and later.\nHowever, your DEF file is defined with version %g,", -1, 0}, {6558 , EMS_NONE, "The FREQUENCY statement is available in version 5.5 and later.\nHowever, your DEF file is defined with version %g", -1, 0}, {6559 , EMS_NONE, "The ROWCOL statement is missing from the VIARULE statement. Ensure that it exists in the VIARULE statement.", -1, 0}, {6560 , EMS_NONE, "The ORIGIN statement is missing from the VIARULE statement. Ensure that it exists in the VIARULE statement.", -1, 0}, {6561 , EMS_NONE, " The OFFSET statement is missing from the VIARULE statement. Ensure that it exists in the VIARULE statement.", -1, 0}, {6562 , EMS_NONE, "The PATTERN statement is missing from the VIARULE statement. Ensure that it exists in the VIARULE statement.", -1, 0}, {6563 , EMS_NONE, "The TYPE statement already exists. It has been defined in the REGION statement.", -1, 0}, {6564 , EMS_NONE, "POLYGON statement in FILLS LAYER is a version 5.6 and later syntax.\nYour def file is defined with version %g,", -1, 0}, {7000 , EMS_NONE, "The specified string has exceeded 4096 characters. The extra characters will be truncated. Specify a string less than or equal to 4096 characters.", -1, 0}, {7010 , EMS_NONE, "The PropName %s is not defined for %s.", -1, 0}, {7011 , EMS_NONE, "The NAMESCASESENSITIVE statement is obsolete in version 5.6 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7012 , EMS_NONE, "The DEF file is invalid because the VERSION statement is not defined in it.\nThe VERSION statement is required in DEF file. Define this statement by refering to the LEF/DEF Language Reference manual.", -1, 0}, {7013 , EMS_NONE, "The DEF file is invalid if NAMESCASESENSITIVE is undefined.\nNAMESCASESENSITIVE is a mandatory statement in the DEF file with version 5.6 and earlier.\nTo define the NAMESCASESENSITIVE statement, refer to the LEF/DEF 5.5 and earlier Language Reference manual.", -1, 0}, {7014 , EMS_NONE, "The DEF file is invalid if BUSBITCHARS is undefined.\nBUSBITCHARS is a mandatory statement in the DEF file with version 5.6 and earlier.\nTo define the BUSBITCHARS statement, refer to the LEF/DEF 5.5 and earlier Language Reference manual.", -1, 0}, {7015 , EMS_NONE, "The DEF file is invalid if DIVIDERCHAR is undefined.\nDIVIDERCHAR is a mandatory statement in the DEF file with version 5.6 and earlier.\nTo define the DIVIDERCHAR statement, refer to the LEF/DEF 5.5 and earlier Language Reference manual.", -1, 0}, {7016 , EMS_NONE, "DESIGN is a mandatory statement in the DEF file. Ensure that it exists in the file.", -1, 0}, {7017 , EMS_NONE, "The DEFAULTCAP statement is obsolete in version 5.4 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7018 , EMS_NONE, "The DO statement in the ROW statement with the name %s has invalid syntax.\nThe valid syntax is \"DO numX BY 1 STEP spaceX 0 | DO 1 BY numY STEP 0 spaceY\".\nSpecify the valid syntax and try again.", -1, 0}, {7019 , EMS_NONE, "The PATTERNNAME statement is obsolete in version 5.6 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7020 , EMS_NONE, "The REGION pt pt statement is obsolete in version 5.5 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7021 , EMS_NONE, "The FOREIGN statement is obsolete in version 5.6 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7022 , EMS_NONE, "In the COMPONENT UNPLACED statement, the point and orient are invalid in version 5.4 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7023 , EMS_NONE, "The SPECIAL NET statement, with type %s, does not have any net statement defined.\nThe DEF parser will ignore this statement.", -1, 0}, {7024 , EMS_NONE, "The ESTCAP statement is obsolete in version 5.5 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7025 , EMS_NONE, "The SPECIAL NET SHIELD statement, does not have any shield net statement defined.\nThe DEF parser will ignore this statement.", -1, 0}, {7026 , EMS_NONE, "The WIDTH statement is obsolete in version 5.5 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7027 , EMS_NONE, "The GROUP REGION pt pt statement is obsolete in version 5.5 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7028 , EMS_NONE, "The GROUP SOFT MAXX statement is obsolete in version 5.5 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7029 , EMS_NONE, "The GROUP SOFT MAXY statement is obsolete in version 5.5 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7030 , EMS_NONE, "The GROUP SOFT MAXHALFPERIMETER statement is obsolete in version 5.5 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7031 , EMS_NONE, "The ASSERTIONS statement is obsolete in version 5.4 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7032 , EMS_NONE, "The CONSTRAINTS statement is obsolete in version 5.4 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7035 , EMS_NONE, "The IOTIMINGS statement is obsolete in version 5.4 and later.\nThe DEF parser will ignore this statement.", -1, 0}, {7500 , EMS_NONE, "Unable to open the file defRWarning.log in %s.\nWarning messages will not be written out in the log file.\nCheck if you have write permission on the directory.", -1, 0}, {8000 , EMS_NONE, "The data still exists after the END DESIGN statement. The DEF parser will ignore this data.", -1, 0}, {8500 , EMS_NONE, "Unable to open the file defRWarning.log in %s.\nInfo messages will not be written out in the log file.\nCheck if you have write permission on the directory.", -1, 0}, {9000 , EMS_NONE, "The DEF writer has detected that the function defwInitCbk has already been called and you are trying to call defwInit.\nOnly defwInitCbk or defwInit can be called but not both.\nUpdate your program and then try again.", -1, 0}, {9001 , EMS_NONE, "The DEF writer has detected that the function defwInit has already been called and you are trying to call defwInitCbk.\nOnly defwInitCbk or defwInit can be called but not both.\nUpdate your program and then try again.", -1, 0}, {9010 , EMS_NONE, "The function defwWrite is called before the function defwInitCbk.\nYou need to call defwInitCbk before calling any other functions.\nUpdate your program and then try again.", -1, 0}, {9011 , EMS_NONE, "You program has called the function defwInit to initialize the writer.\nIf you want to use the callback option you need to use the function defwInitCbk.", -1, 0}, {9012 , EMS_NONE, "You are calling the function defwPrintUnusedCallbacks but you did call the function defwSetRegisterUnusedCallbacks which is required before you can call defwPrintUnusedCallbacks.", -1, 0}, {-1 , EMS_NONE, "", -1, 0} }; /* * End machine generated table. */
71c55bd64bf80544ea9a6f004964bc1bffb1f93f
5ed4f58304033044e3a259f2a678328de4696692
/src/re_search.c
b2dc24ed233592206b7ff92c8dbd67a0b59ab7db
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
troglobit/mg
a971a04a1610f93d57636f1253760684ea7b29a9
46dca121b1d67758ee06809d8eb72d0b9d6def65
refs/heads/master
2023-08-21T22:52:12.135823
2023-08-13T15:31:28
2023-08-13T15:31:28
58,325,928
333
39
Unlicense
2023-08-09T23:59:32
2016-05-08T18:41:56
C
UTF-8
C
false
false
15,063
c
re_search.c
/* $OpenBSD: re_search.c,v 1.36 2021/04/22 19:50:55 lum Exp $ */ /* This file is in the public domain. */ /* * regular expression search commands for Mg * * This file contains functions to implement several of gnuemacs's regular * expression functions for Mg. Several of the routines below are just minor * re-arrangements of Mg's non-regular expression search functions. Some of * them are similar in structure to the original MicroEMACS, others are * modifications of Rich Ellison's code. Peter Newton re-wrote about half of * them from scratch. */ #include <sys/types.h> #include <regex.h> #include <signal.h> #include <stdio.h> #include <string.h> #include "def.h" #include "macro.h" #define SRCH_BEGIN (0) /* search sub-codes */ #define SRCH_FORW (-1) #define SRCH_BACK (-2) #define SRCH_NOPR (-3) #define SRCH_ACCM (-4) #define SRCH_MARK (-5) #define RE_NMATCH 10 /* max number of matches */ #define REPLEN 256 /* max length of replacement string */ #ifndef REG_STARTEND #define REG_STARTEND 4 #endif char re_pat[NPAT]; /* regex pattern */ int re_srch_lastdir = SRCH_NOPR; /* last search flags */ int casefoldsearch = TRUE; /* does search ignore case? */ static int re_doreplace(RSIZE, char *); static int re_forwsrch(void); static int re_backsrch(void); static int re_readpattern(char *); static int killmatches(int); static int countmatches(int); /* * Search forward. * Get a search string from the user and search for it starting at ".". If * found, move "." to just after the matched characters. display does all * the hard stuff. If not found, it just prints a message. */ int re_forwsearch(int f, int n) { int s; if ((s = re_readpattern("RE Search")) != TRUE) return (s); if (re_forwsrch() == FALSE) { dobeep(); ewprintf("Search failed: \"%s\"", re_pat); return (FALSE); } re_srch_lastdir = SRCH_FORW; return (TRUE); } /* * Reverse search. * Get a search string from the user, and search, starting at "." * and proceeding toward the front of the buffer. If found "." is left * pointing at the first character of the pattern [the last character that * was matched]. */ int re_backsearch(int f, int n) { int s; if ((s = re_readpattern("RE Search backward")) != TRUE) return (s); if (re_backsrch() == FALSE) { dobeep(); ewprintf("Search failed: \"%s\"", re_pat); return (FALSE); } re_srch_lastdir = SRCH_BACK; return (TRUE); } /* * Search again, using the same search string and direction as the last search * command. The direction has been saved in "srch_lastdir", so you know which * way to go. * * XXX: This code has problems -- some incompatibility(?) with extend.c causes * match to fail when it should not. */ int re_searchagain(int f, int n) { if (re_srch_lastdir == SRCH_NOPR) { dobeep(); ewprintf("No last search"); return (FALSE); } if (re_srch_lastdir == SRCH_FORW) { if (re_forwsrch() == FALSE) { dobeep(); ewprintf("Search failed: \"%s\"", re_pat); return (FALSE); } return (TRUE); } if (re_srch_lastdir == SRCH_BACK) if (re_backsrch() == FALSE) { dobeep(); ewprintf("Search failed: \"%s\"", re_pat); return (FALSE); } return (TRUE); } /* Compiled regex goes here-- changed only when new pattern read */ static regex_t regex_buff; static regmatch_t regex_match[RE_NMATCH]; /* * Re-Query Replace. * Replace strings selectively. Does a search and replace operation. */ int re_queryrepl(int f, int n) { int rcnt = 0; /* replacements made so far */ int plen, s; /* length of found string */ char news[NPAT]; /* replacement string */ if ((s = re_readpattern("RE Query replace")) != TRUE) return (s); if (eread("Query replace %s with: ", news, NPAT, EFNUL | EFNEW | EFCR, re_pat) == NULL) return (ABORT); ewprintf("Query replacing %s with %s:", re_pat, news); /* * Search forward repeatedly, checking each time whether to insert * or not. The "!" case makes the check always true, so it gets put * into a tighter loop for efficiency. */ while (re_forwsrch() == TRUE) { retry: update(CMODE); switch (getkey(FALSE)) { case ' ': plen = regex_match[0].rm_eo - regex_match[0].rm_so; if (re_doreplace((RSIZE)plen, news) == FALSE) return (FALSE); rcnt++; break; case '.': plen = regex_match[0].rm_eo - regex_match[0].rm_so; if (re_doreplace((RSIZE)plen, news) == FALSE) return (FALSE); rcnt++; goto stopsearch; case CCHR('G'): /* ^G */ (void)ctrlg(FFRAND, 0); goto stopsearch; case CCHR('['): /* ESC */ case '`': goto stopsearch; case '!': do { plen = regex_match[0].rm_eo - regex_match[0].rm_so; if (re_doreplace((RSIZE)plen, news) == FALSE) return (FALSE); rcnt++; } while (re_forwsrch() == TRUE); goto stopsearch; case CCHR('?'): /* To not replace */ break; default: ewprintf("<SP> replace, [.] rep-end, <DEL> don't, [!] repl rest <ESC> quit"); goto retry; } } stopsearch: curwp->w_rflag |= WFFULL; update(CMODE); if (!inmacro) { if (rcnt == 0) ewprintf("(No replacements done)"); else if (rcnt == 1) ewprintf("(1 replacement done)"); else ewprintf("(%d replacements done)", rcnt); } return (TRUE); } int re_repl(int f, int n) { int rcnt = 0; /* replacements made so far */ int plen, s; /* length of found string */ char news[NPAT]; /* replacement string */ if ((s = re_readpattern("RE Replace")) != TRUE) return (s); if (eread("Replace %s with: ", news, NPAT, EFNUL | EFNEW | EFCR, re_pat) == NULL) return (ABORT); while (re_forwsrch() == TRUE) { plen = regex_match[0].rm_eo - regex_match[0].rm_so; if (re_doreplace((RSIZE)plen, news) == FALSE) return (FALSE); rcnt++; } curwp->w_rflag |= WFFULL; update(CMODE); if (!inmacro) ewprintf("(%d replacement(s) done)", rcnt); return(TRUE); } /* * Routine re_doreplace calls lreplace to make replacements needed by * re_query replace. Its reason for existence is to deal with \1, \2. etc. * plen: length to remove * st: replacement string */ static int re_doreplace(RSIZE plen, char *st) { int j, k, s, more, num, state; struct line *clp; char repstr[REPLEN]; clp = curwp->w_dotp; more = TRUE; j = 0; state = 0; num = 0; /* The following FSA parses the replacement string */ while (more) { switch (state) { case 0: if (*st == '\\') { st++; state = 1; } else if (*st == '\0') more = FALSE; else { repstr[j] = *st; j++; if (j >= REPLEN) return (FALSE); st++; } break; case 1: if (*st >= '0' && *st <= '9') { num = *st - '0'; st++; state = 2; } else if (*st == '\0') more = FALSE; else { repstr[j] = *st; j++; if (j >= REPLEN) return (FALSE); st++; state = 0; } break; case 2: if (*st >= '0' && *st <= '9') { num = 10 * num + *st - '0'; st++; } else { if (num >= RE_NMATCH) return (FALSE); k = regex_match[num].rm_eo - regex_match[num].rm_so; if (j + k >= REPLEN) return (FALSE); bcopy(&(clp->l_text[regex_match[num].rm_so]), &repstr[j], k); j += k; if (*st == '\0') more = FALSE; if (*st == '\\') { st++; state = 1; } else { repstr[j] = *st; j++; if (j >= REPLEN) return (FALSE); st++; state = 0; } } break; } /* switch (state) */ } /* while (more) */ repstr[j] = '\0'; s = lreplace(plen, repstr); return (s); } /* * This routine does the real work of a forward search. The pattern is * sitting in the external variable "pat". If found, dot is updated, the * window system is notified of the change, and TRUE is returned. If the * string isn't found, FALSE is returned. */ static int re_forwsrch(void) { int re_flags, tbo, tdotline, error; struct line *clp; clp = curwp->w_dotp; tbo = curwp->w_doto; tdotline = curwp->w_dotline; if (tbo == clp->l_used) /* * Don't start matching past end of line -- must move to * beginning of next line, unless line is empty or at * end of file. */ if (clp != curbp->b_headp && llength(clp) != 0) { clp = lforw(clp); tdotline++; tbo = 0; } /* * Note this loop does not process the last line, but this editor * always makes the last line empty so this is good. */ while (clp != (curbp->b_headp)) { re_flags = REG_STARTEND; if (tbo != 0) re_flags |= REG_NOTBOL; regex_match[0].rm_so = tbo; regex_match[0].rm_eo = llength(clp); error = regexec(&regex_buff, ltext(clp) ? ltext(clp) : "", RE_NMATCH, regex_match, re_flags); if (error != 0) { clp = lforw(clp); tdotline++; tbo = 0; } else { curwp->w_doto = regex_match[0].rm_eo; curwp->w_dotp = clp; curwp->w_dotline = tdotline; curwp->w_rflag |= WFMOVE; return (TRUE); } } return (FALSE); } /* * This routine does the real work of a backward search. The pattern is sitting * in the external variable "re_pat". If found, dot is updated, the window * system is notified of the change, and TRUE is returned. If the string isn't * found, FALSE is returned. */ static int re_backsrch(void) { struct line *clp; int tbo, tdotline; regmatch_t lastmatch; clp = curwp->w_dotp; tbo = curwp->w_doto; tdotline = curwp->w_dotline; /* Start search one position to the left of dot */ tbo = tbo - 1; if (tbo < 0) { /* must move up one line */ clp = lback(clp); tdotline--; tbo = llength(clp); } /* * Note this loop does not process the last line, but this editor * always makes the last line empty so this is good. */ while (clp != (curbp->b_headp)) { regex_match[0].rm_so = 0; regex_match[0].rm_eo = llength(clp); lastmatch.rm_so = -1; /* * Keep searching until we don't match any longer. Assumes a * non-match does not modify the regex_match array. We have to * do this character-by-character after the first match since * POSIX regexps don't give you a way to do reverse matches. */ while (!regexec(&regex_buff, ltext(clp) ? ltext(clp) : "", RE_NMATCH, regex_match, REG_STARTEND) && regex_match[0].rm_so <= tbo) { memcpy(&lastmatch, &regex_match[0], sizeof(regmatch_t)); regex_match[0].rm_so++; regex_match[0].rm_eo = llength(clp); } if (lastmatch.rm_so == -1) { clp = lback(clp); tdotline--; tbo = llength(clp); } else { memcpy(&regex_match[0], &lastmatch, sizeof(regmatch_t)); curwp->w_doto = regex_match[0].rm_so; curwp->w_dotp = clp; curwp->w_dotline = tdotline; curwp->w_rflag |= WFMOVE; return (TRUE); } } return (FALSE); } /* * Read a pattern. * Stash it in the external variable "re_pat". The "pat" is * not updated if the user types in an empty line. If the user typed * an empty line, and there is no old pattern, it is an error. * Display the old pattern, in the style of Jeff Lomicka. There is * some do-it-yourself control expansion. */ static int re_readpattern(char *re_prompt) { static int dofree = 0; int flags, error, s; char tpat[NPAT], *rep; if (re_pat[0] == '\0') rep = eread("%s: ", tpat, NPAT, EFNEW | EFCR, re_prompt); else rep = eread("%s (default %s): ", tpat, NPAT, EFNUL | EFNEW | EFCR, re_prompt, re_pat); if (rep == NULL) return (ABORT); if (rep[0] != '\0') { /* New pattern given */ (void)strlcpy(re_pat, tpat, sizeof(re_pat)); if (casefoldsearch) flags = REG_EXTENDED | REG_ICASE; else flags = REG_EXTENDED; if (dofree) regfree(&regex_buff); error = regcomp(&regex_buff, re_pat, flags); if (error != 0) { char message[256]; regerror(error, &regex_buff, message, sizeof(message)); dobeep(); ewprintf("Regex Error: %s", message); re_pat[0] = '\0'; return (FALSE); } dofree = 1; s = TRUE; } else if (rep[0] == '\0' && re_pat[0] != '\0') /* Just using old pattern */ s = TRUE; else s = FALSE; return (s); } /* * Cause case to not matter in searches. This is the default. If called * with argument cause case to matter. */ /* ARGSUSED*/ int setcasefold(int f, int n) { if (f & FFARG) { casefoldsearch = FALSE; ewprintf("Case-fold-search unset"); } else { casefoldsearch = TRUE; ewprintf("Case-fold-search set"); } /* * Invalidate the regular expression pattern since I'm too lazy to * recompile it. */ re_pat[0] = '\0'; return (TRUE); } /* * Delete all lines after dot that contain a string matching regex. */ int delmatchlines(int f, int n) { int s; if ((s = re_readpattern("Flush lines (containing match for regexp)")) != TRUE) return (s); s = killmatches(TRUE); return (s); } /* * Delete all lines after dot that don't contain a string matching regex. */ int delnonmatchlines(int f, int n) { int s; if ((s = re_readpattern("Keep lines (containing match for regexp)")) != TRUE) return (s); s = killmatches(FALSE); return (s); } /* * This function does the work of deleting matching lines. */ static int killmatches(int cond) { int s, error; int count = 0; struct line *clp; clp = curwp->w_dotp; if (curwp->w_doto == llength(clp)) /* Consider dot on next line */ clp = lforw(clp); while (clp != (curbp->b_headp)) { /* see if line matches */ regex_match[0].rm_so = 0; regex_match[0].rm_eo = llength(clp); error = regexec(&regex_buff, ltext(clp) ? ltext(clp) : "", RE_NMATCH, regex_match, REG_STARTEND); /* Delete line when appropriate */ if ((cond == FALSE && error) || (cond == TRUE && !error)) { curwp->w_doto = 0; curwp->w_dotp = clp; count++; s = ldelete(llength(clp) + 1, KNONE); clp = curwp->w_dotp; curwp->w_rflag |= WFMOVE; if (s == FALSE) return (FALSE); } else clp = lforw(clp); } ewprintf("%d line(s) deleted", count); if (count > 0) curwp->w_rflag |= WFMOVE; return (TRUE); } /* * Count lines matching regex. */ int cntmatchlines(int f, int n) { int s; if ((s = re_readpattern("Count lines (matching regexp)")) != TRUE) return (s); s = countmatches(TRUE); return (s); } /* * Count lines that fail to match regex. */ int cntnonmatchlines(int f, int n) { int s; if ((s = re_readpattern("Count lines (not matching regexp)")) != TRUE) return (s); s = countmatches(FALSE); return (s); } /* * This function does the work of counting matching lines. */ int countmatches(int cond) { int error; int count = 0; struct line *clp; clp = curwp->w_dotp; if (curwp->w_doto == llength(clp)) /* Consider dot on next line */ clp = lforw(clp); while (clp != (curbp->b_headp)) { /* see if line matches */ regex_match[0].rm_so = 0; regex_match[0].rm_eo = llength(clp); error = regexec(&regex_buff, ltext(clp) ? ltext(clp) : "", RE_NMATCH, regex_match, REG_STARTEND); /* Count line when appropriate */ if ((cond == FALSE && error) || (cond == TRUE && !error)) count++; clp = lforw(clp); } if (cond) ewprintf("Number of lines matching: %d", count); else ewprintf("Number of lines not matching: %d", count); return (TRUE); }
908901e17d0301b9ec3d238976463540a99245e4
e1cddfd754d952134e72dfd03522c5ea4fb6008e
/src/vnet/mpls/mpls_tunnel.c
5f7bf8c3b257a1323088063ba979ee6ca963b06f
[ "Apache-2.0" ]
permissive
FDio/vpp
0ad30fa1bec2975ffa6b66b45c9f4f32163123b6
f234b0d4626d7e686422cc9dfd25958584f4931e
refs/heads/master
2023-08-31T16:09:04.068646
2022-03-14T09:49:15
2023-08-31T09:50:00
96,556,718
1,048
630
Apache-2.0
2023-06-21T05:39:17
2017-07-07T16:29:40
C
UTF-8
C
false
false
30,966
c
mpls_tunnel.c
/* * mpls_tunnel.c: MPLS tunnel interfaces (i.e. for RSVP-TE) * * Copyright (c) 2012 Cisco and/or its affiliates. * 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 <vnet/vnet.h> #include <vnet/mpls/mpls_tunnel.h> #include <vnet/mpls/mpls_types.h> #include <vnet/ip/ip.h> #include <vnet/fib/fib_path_list.h> #include <vnet/adj/adj_midchain.h> #include <vnet/adj/adj_mcast.h> #include <vnet/dpo/replicate_dpo.h> #include <vnet/fib/mpls_fib.h> /** * @brief pool of tunnel instances */ static mpls_tunnel_t *mpls_tunnel_pool; /** * @brief DB of SW index to tunnel index */ static u32 *mpls_tunnel_db; /** * @brief MPLS tunnel flags strings */ static const char *mpls_tunnel_attribute_names[] = MPLS_TUNNEL_ATTRIBUTES; /** * @brief Packet trace structure */ typedef struct mpls_tunnel_trace_t_ { /** * Tunnel-id / index in tunnel vector */ u32 tunnel_id; } mpls_tunnel_trace_t; static u8 * format_mpls_tunnel_tx_trace (u8 * s, va_list * args) { CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *); CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *); mpls_tunnel_trace_t * t = va_arg (*args, mpls_tunnel_trace_t *); s = format (s, "MPLS: tunnel %d", t->tunnel_id); return s; } typedef enum { MPLS_TUNNEL_ENCAP_NEXT_L2_MIDCHAIN, MPLS_TUNNEL_ENCAP_N_NEXT, } mpls_tunnel_encap_next_t; /** * @brief TX function. Only called L2. L3 traffic uses the adj-midchains */ VLIB_NODE_FN (mpls_tunnel_tx) (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame) { u32 *from = vlib_frame_vector_args (frame); vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b; u16 nexts[VLIB_FRAME_SIZE], *next; u32 n_left; n_left = frame->n_vectors; b = bufs; next = nexts; vlib_get_buffers (vm, from, bufs, n_left); while (n_left > 2) { const mpls_tunnel_t *mt0, *mt1; u32 sw_if_index0, sw_if_index1; sw_if_index0 = vnet_buffer(b[0])->sw_if_index[VLIB_TX]; sw_if_index1 = vnet_buffer(b[1])->sw_if_index[VLIB_TX]; mt0 = pool_elt_at_index(mpls_tunnel_pool, mpls_tunnel_db[sw_if_index0]); mt1 = pool_elt_at_index(mpls_tunnel_pool, mpls_tunnel_db[sw_if_index1]); vnet_buffer(b[0])->ip.adj_index[VLIB_TX] = mt0->mt_l2_lb.dpoi_index; vnet_buffer(b[1])->ip.adj_index[VLIB_TX] = mt1->mt_l2_lb.dpoi_index; next[0] = mt0->mt_l2_lb.dpoi_next_node; next[1] = mt1->mt_l2_lb.dpoi_next_node; /* since we are coming out of the L2 world, where the vlib_buffer * union is used for other things, make sure it is clean for * MPLS from now on. */ vnet_buffer(b[0])->mpls.first = 0; vnet_buffer(b[1])->mpls.first = 0; if (PREDICT_FALSE(b[0]->flags & VLIB_BUFFER_IS_TRACED)) { mpls_tunnel_trace_t *tr = vlib_add_trace (vm, node, b[0], sizeof (*tr)); tr->tunnel_id = mpls_tunnel_db[sw_if_index0]; } if (PREDICT_FALSE(b[1]->flags & VLIB_BUFFER_IS_TRACED)) { mpls_tunnel_trace_t *tr = vlib_add_trace (vm, node, b[1], sizeof (*tr)); tr->tunnel_id = mpls_tunnel_db[sw_if_index1]; } b += 2; n_left -= 2; next += 2; } while (n_left) { const mpls_tunnel_t *mt0; u32 sw_if_index0; sw_if_index0 = vnet_buffer(b[0])->sw_if_index[VLIB_TX]; mt0 = pool_elt_at_index(mpls_tunnel_pool, mpls_tunnel_db[sw_if_index0]); vnet_buffer(b[0])->ip.adj_index[VLIB_TX] = mt0->mt_l2_lb.dpoi_index; next[0] = mt0->mt_l2_lb.dpoi_next_node; /* since we are coming out of the L2 world, where the vlib_buffer * union is used for other things, make sure it is clean for * MPLS from now on. */ vnet_buffer(b[0])->mpls.first = 0; if (PREDICT_FALSE(b[0]->flags & VLIB_BUFFER_IS_TRACED)) { mpls_tunnel_trace_t *tr = vlib_add_trace (vm, node, b[0], sizeof (*tr)); tr->tunnel_id = mpls_tunnel_db[sw_if_index0]; } b += 1; n_left -= 1; next += 1; } vlib_buffer_enqueue_to_next (vm, node, from, nexts, frame->n_vectors); return frame->n_vectors; } VLIB_REGISTER_NODE (mpls_tunnel_tx) = { .name = "mpls-tunnel-tx", .vector_size = sizeof (u32), .format_trace = format_mpls_tunnel_tx_trace, .type = VLIB_NODE_TYPE_INTERNAL, .n_errors = 0, .n_next_nodes = 0, /* MPLS_TUNNEL_ENCAP_N_NEXT, */ /* .next_nodes = { */ /* [MPLS_TUNNEL_ENCAP_NEXT_L2_MIDCHAIN] = "mpls-load-balance", */ /* }, */ }; /** * @brief Get a tunnel object from a SW interface index */ static mpls_tunnel_t* mpls_tunnel_get_from_sw_if_index (u32 sw_if_index) { if ((vec_len(mpls_tunnel_db) <= sw_if_index) || (~0 == mpls_tunnel_db[sw_if_index])) return (NULL); return (pool_elt_at_index(mpls_tunnel_pool, mpls_tunnel_db[sw_if_index])); } /** * @brief Build a rewrite string for the MPLS tunnel. */ static u8* mpls_tunnel_build_rewrite_i (void) { /* * passing the adj code a NULL rewrite means 'i don't have one cos * t'other end is unresolved'. That's not the case here. For the mpls * tunnel there are just no bytes of encap to apply in the adj. We'll impose * the label stack once we choose a path. So return a zero length rewrite. */ u8 *rewrite = NULL; vec_validate(rewrite, 0); vec_reset_length(rewrite); return (rewrite); } /** * @brief Build a rewrite string for the MPLS tunnel. */ static u8* mpls_tunnel_build_rewrite (vnet_main_t * vnm, u32 sw_if_index, vnet_link_t link_type, const void *dst_address) { return (mpls_tunnel_build_rewrite_i()); } typedef struct mpls_tunnel_collect_forwarding_ctx_t_ { load_balance_path_t * next_hops; const mpls_tunnel_t *mt; fib_forward_chain_type_t fct; } mpls_tunnel_collect_forwarding_ctx_t; static fib_path_list_walk_rc_t mpls_tunnel_collect_forwarding (fib_node_index_t pl_index, fib_node_index_t path_index, void *arg) { mpls_tunnel_collect_forwarding_ctx_t *ctx; fib_path_ext_t *path_ext; ctx = arg; /* * if the path is not resolved, don't include it. */ if (!fib_path_is_resolved(path_index)) { return (FIB_PATH_LIST_WALK_CONTINUE); } /* * get the matching path-extension for the path being visited. */ path_ext = fib_path_ext_list_find_by_path_index(&ctx->mt->mt_path_exts, path_index); /* * we don't want IP TTL decrements for packets hitting the MPLS labels * we stack on, since the IP TTL decrement is done by the adj */ path_ext->fpe_mpls_flags |= FIB_PATH_EXT_MPLS_FLAG_NO_IP_TTL_DECR; /* * found a matching extension. stack it to obtain the forwarding * info for this path. */ ctx->next_hops = fib_path_ext_stack (path_ext, DPO_PROTO_MPLS, ctx->fct, ctx->next_hops); return (FIB_PATH_LIST_WALK_CONTINUE); } static void mpls_tunnel_mk_lb (mpls_tunnel_t *mt, vnet_link_t linkt, fib_forward_chain_type_t fct, dpo_id_t *dpo_lb) { dpo_proto_t lb_proto; /* * If the entry has path extensions then we construct a load-balance * by stacking the extensions on the forwarding chains of the paths. * Otherwise we use the load-balance of the path-list */ mpls_tunnel_collect_forwarding_ctx_t ctx = { .mt = mt, .next_hops = NULL, .fct = fct, }; /* * As an optimisation we allocate the vector of next-hops to be sized * equal to the maximum nuber of paths we will need, which is also the * most likely number we will need, since in most cases the paths are 'up'. */ vec_validate(ctx.next_hops, fib_path_list_get_n_paths(mt->mt_path_list)); vec_reset_length(ctx.next_hops); lb_proto = fib_forw_chain_type_to_dpo_proto(fct); if (FIB_NODE_INDEX_INVALID != mt->mt_path_list) { fib_path_list_walk(mt->mt_path_list, mpls_tunnel_collect_forwarding, &ctx); } if (!dpo_id_is_valid(dpo_lb)) { /* * first time create */ if (mt->mt_flags & MPLS_TUNNEL_FLAG_MCAST) { dpo_set(dpo_lb, DPO_REPLICATE, lb_proto, replicate_create(0, lb_proto)); } else { flow_hash_config_t fhc; switch (linkt) { case VNET_LINK_MPLS: fhc = MPLS_FLOW_HASH_DEFAULT; break; case VNET_LINK_IP4: case VNET_LINK_IP6: fhc = IP_FLOW_HASH_DEFAULT; break; default: fhc = 0; break; } dpo_set(dpo_lb, DPO_LOAD_BALANCE, lb_proto, load_balance_create(0, lb_proto, fhc)); } } if (mt->mt_flags & MPLS_TUNNEL_FLAG_MCAST) { /* * MPLS multicast */ replicate_multipath_update(dpo_lb, ctx.next_hops); } else { load_balance_multipath_update(dpo_lb, ctx.next_hops, LOAD_BALANCE_FLAG_NONE); vec_free(ctx.next_hops); } } /** * mpls_tunnel_stack * * 'stack' (resolve the recursion for) the tunnel's midchain adjacency */ static void mpls_tunnel_stack (adj_index_t ai) { ip_adjacency_t *adj; mpls_tunnel_t *mt; u32 sw_if_index; adj = adj_get(ai); sw_if_index = adj->rewrite_header.sw_if_index; mt = mpls_tunnel_get_from_sw_if_index(sw_if_index); if (NULL == mt || FIB_NODE_INDEX_INVALID == mt->mt_path_list) return; if (FIB_NODE_INDEX_INVALID == mt->mt_path_list) { adj_nbr_midchain_unstack(ai); return; } /* * while we're stacking the adj, remove the tunnel from the child list * of the path list. this breaks a circular dependency of walk updates * where the create of adjacencies in the children can lead to walks * that get back here. */ fib_path_list_lock(mt->mt_path_list); fib_path_list_child_remove(mt->mt_path_list, mt->mt_sibling_index); /* * Construct the DPO (load-balance or replicate) that we can stack * the tunnel's midchain on */ if (vnet_hw_interface_get_flags(vnet_get_main(), mt->mt_hw_if_index) & VNET_HW_INTERFACE_FLAG_LINK_UP) { dpo_id_t dpo = DPO_INVALID; mpls_tunnel_mk_lb(mt, adj->ia_link, fib_forw_chain_type_from_link_type( adj_get_link_type(ai)), &dpo); adj_nbr_midchain_stack(ai, &dpo); dpo_reset(&dpo); } else { adj_nbr_midchain_unstack(ai); } mt->mt_sibling_index = fib_path_list_child_add(mt->mt_path_list, FIB_NODE_TYPE_MPLS_TUNNEL, mt - mpls_tunnel_pool); fib_path_list_unlock(mt->mt_path_list); } /** * @brief Call back when restacking all adjacencies on a MPLS interface */ static adj_walk_rc_t mpls_adj_walk_cb (adj_index_t ai, void *ctx) { mpls_tunnel_stack(ai); return (ADJ_WALK_RC_CONTINUE); } static void mpls_tunnel_restack (mpls_tunnel_t *mt) { fib_protocol_t proto; /* * walk all the adjacencies on the MPLS interface and restack them */ if (mt->mt_flags & MPLS_TUNNEL_FLAG_L2) { /* * Stack a load-balance that drops, whilst we have no paths */ dpo_id_t dpo = DPO_INVALID; mpls_tunnel_mk_lb(mt, VNET_LINK_MPLS, FIB_FORW_CHAIN_TYPE_ETHERNET, &dpo); dpo_stack_from_node(mpls_tunnel_tx.index, &mt->mt_l2_lb, &dpo); dpo_reset(&dpo); } else { FOR_EACH_FIB_IP_PROTOCOL(proto) { adj_nbr_walk(mt->mt_sw_if_index, proto, mpls_adj_walk_cb, NULL); } } } static clib_error_t * mpls_tunnel_admin_up_down (vnet_main_t * vnm, u32 hw_if_index, u32 flags) { vnet_hw_interface_t * hi; mpls_tunnel_t *mt; hi = vnet_get_hw_interface (vnm, hw_if_index); mt = mpls_tunnel_get_from_sw_if_index(hi->sw_if_index); if (NULL == mt) return (NULL); if (flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP) vnet_hw_interface_set_flags (vnm, hw_if_index, VNET_HW_INTERFACE_FLAG_LINK_UP); else vnet_hw_interface_set_flags (vnm, hw_if_index, 0 /* down */); mpls_tunnel_restack(mt); return (NULL); } /** * @brief Fixup the adj rewrite post encap. This is a no-op since the * rewrite is a stack of labels. */ static void mpls_tunnel_fixup (vlib_main_t *vm, const ip_adjacency_t *adj, vlib_buffer_t *b0, const void*data) { /* * A no-op w.r.t. the header. but reset the 'have we pushed any * MPLS labels onto the packet' flag. That way when we enter the * tunnel we'll get a TTL set to 255 */ vnet_buffer(b0)->mpls.first = 0; } static void mpls_tunnel_update_adj (vnet_main_t * vnm, u32 sw_if_index, adj_index_t ai) { ip_adjacency_t *adj; ASSERT(ADJ_INDEX_INVALID != ai); adj = adj_get(ai); switch (adj->lookup_next_index) { case IP_LOOKUP_NEXT_ARP: case IP_LOOKUP_NEXT_GLEAN: case IP_LOOKUP_NEXT_BCAST: adj_nbr_midchain_update_rewrite(ai, mpls_tunnel_fixup, NULL, ADJ_FLAG_NONE, mpls_tunnel_build_rewrite_i()); break; case IP_LOOKUP_NEXT_MCAST: /* * Construct a partial rewrite from the known ethernet mcast dest MAC * There's no MAC fixup, so the last 2 parameters are 0 */ adj_mcast_midchain_update_rewrite(ai, mpls_tunnel_fixup, NULL, ADJ_FLAG_NONE, mpls_tunnel_build_rewrite_i(), 0, 0); break; case IP_LOOKUP_NEXT_DROP: case IP_LOOKUP_NEXT_PUNT: case IP_LOOKUP_NEXT_LOCAL: case IP_LOOKUP_NEXT_REWRITE: case IP_LOOKUP_NEXT_MIDCHAIN: case IP_LOOKUP_NEXT_MCAST_MIDCHAIN: case IP_LOOKUP_NEXT_ICMP_ERROR: case IP_LOOKUP_N_NEXT: ASSERT (0); break; } mpls_tunnel_stack(ai); } static u8 * format_mpls_tunnel_name (u8 * s, va_list * args) { u32 dev_instance = va_arg (*args, u32); return format (s, "mpls-tunnel%d", dev_instance); } static u8 * format_mpls_tunnel_device (u8 * s, va_list * args) { u32 dev_instance = va_arg (*args, u32); CLIB_UNUSED (int verbose) = va_arg (*args, int); return (format (s, "MPLS-tunnel: id %d\n", dev_instance)); } VNET_DEVICE_CLASS (mpls_tunnel_class) = { .name = "MPLS tunnel device", .format_device_name = format_mpls_tunnel_name, .format_device = format_mpls_tunnel_device, .format_tx_trace = format_mpls_tunnel_tx_trace, .admin_up_down_function = mpls_tunnel_admin_up_down, }; VNET_HW_INTERFACE_CLASS (mpls_tunnel_hw_interface_class) = { .name = "MPLS-Tunnel", .update_adjacency = mpls_tunnel_update_adj, .build_rewrite = mpls_tunnel_build_rewrite, .flags = VNET_HW_INTERFACE_CLASS_FLAG_P2P, }; const mpls_tunnel_t * mpls_tunnel_get (u32 mti) { return (pool_elt_at_index(mpls_tunnel_pool, mti)); } /** * @brief Walk all the MPLS tunnels */ void mpls_tunnel_walk (mpls_tunnel_walk_cb_t cb, void *ctx) { u32 mti; pool_foreach_index (mti, mpls_tunnel_pool) { cb(mti, ctx); } } void vnet_mpls_tunnel_del (u32 sw_if_index) { mpls_tunnel_t *mt; mt = mpls_tunnel_get_from_sw_if_index(sw_if_index); if (NULL == mt) return; if (FIB_NODE_INDEX_INVALID != mt->mt_path_list) fib_path_list_child_remove(mt->mt_path_list, mt->mt_sibling_index); dpo_reset(&mt->mt_l2_lb); vnet_reset_interface_l3_output_node (vlib_get_main (), mt->mt_sw_if_index); vnet_delete_hw_interface (vnet_get_main(), mt->mt_hw_if_index); pool_put(mpls_tunnel_pool, mt); mpls_tunnel_db[sw_if_index] = ~0; } u32 vnet_mpls_tunnel_create (u8 l2_only, u8 is_multicast, u8 *tag) { vnet_hw_interface_t * hi; mpls_tunnel_t *mt; vnet_main_t * vnm; u32 mti; vnm = vnet_get_main(); pool_get(mpls_tunnel_pool, mt); clib_memset (mt, 0, sizeof (*mt)); mti = mt - mpls_tunnel_pool; fib_node_init(&mt->mt_node, FIB_NODE_TYPE_MPLS_TUNNEL); mt->mt_path_list = FIB_NODE_INDEX_INVALID; mt->mt_sibling_index = FIB_NODE_INDEX_INVALID; if (is_multicast) mt->mt_flags |= MPLS_TUNNEL_FLAG_MCAST; if (l2_only) mt->mt_flags |= MPLS_TUNNEL_FLAG_L2; if (tag) memcpy(mt->mt_tag, tag, sizeof(mt->mt_tag)); else mt->mt_tag[0] = '\0'; /* * Create a new tunnel HW interface */ mt->mt_hw_if_index = vnet_register_interface( vnm, mpls_tunnel_class.index, mti, mpls_tunnel_hw_interface_class.index, mti); hi = vnet_get_hw_interface (vnm, mt->mt_hw_if_index); if (mt->mt_flags & MPLS_TUNNEL_FLAG_L2) vnet_set_interface_output_node (vnm, mt->mt_hw_if_index, mpls_tunnel_tx.index); else vnet_set_interface_l3_output_node (vnm->vlib_main, hi->sw_if_index, (u8 *) "tunnel-output"); /* Standard default MPLS tunnel MTU. */ vnet_sw_interface_set_mtu (vnm, hi->sw_if_index, 9000); /* * Add the new tunnel to the tunnel DB - key:SW if index */ mt->mt_sw_if_index = hi->sw_if_index; vec_validate_init_empty(mpls_tunnel_db, mt->mt_sw_if_index, ~0); mpls_tunnel_db[mt->mt_sw_if_index] = mti; return (mt->mt_sw_if_index); } void vnet_mpls_tunnel_path_add (u32 sw_if_index, fib_route_path_t *rpaths) { fib_route_path_t *rpath; mpls_tunnel_t *mt; u32 mti; mt = mpls_tunnel_get_from_sw_if_index(sw_if_index); if (NULL == mt) return; mti = mt - mpls_tunnel_pool; /* * construct a path-list from the path provided */ if (FIB_NODE_INDEX_INVALID == mt->mt_path_list) { mt->mt_path_list = fib_path_list_create(FIB_PATH_LIST_FLAG_SHARED, rpaths); mt->mt_sibling_index = fib_path_list_child_add(mt->mt_path_list, FIB_NODE_TYPE_MPLS_TUNNEL, mti); } else { fib_node_index_t old_pl_index; old_pl_index = mt->mt_path_list; mt->mt_path_list = fib_path_list_copy_and_path_add(old_pl_index, FIB_PATH_LIST_FLAG_SHARED, rpaths); fib_path_list_child_remove(old_pl_index, mt->mt_sibling_index); mt->mt_sibling_index = fib_path_list_child_add(mt->mt_path_list, FIB_NODE_TYPE_MPLS_TUNNEL, mti); /* * re-resolve all the path-extensions with the new path-list */ fib_path_ext_list_resolve(&mt->mt_path_exts, mt->mt_path_list); } vec_foreach(rpath, rpaths) { fib_path_ext_list_insert(&mt->mt_path_exts, mt->mt_path_list, FIB_PATH_EXT_MPLS, rpath); } mpls_tunnel_restack(mt); } int vnet_mpls_tunnel_path_remove (u32 sw_if_index, fib_route_path_t *rpaths) { mpls_tunnel_t *mt; u32 mti; mt = mpls_tunnel_get_from_sw_if_index(sw_if_index); if (NULL == mt) return (0); mti = mt - mpls_tunnel_pool; /* * construct a path-list from the path provided */ if (FIB_NODE_INDEX_INVALID == mt->mt_path_list) { /* can't remove a path if we have onoe */ return (0); } else { fib_node_index_t old_pl_index; old_pl_index = mt->mt_path_list; fib_path_list_lock(old_pl_index); mt->mt_path_list = fib_path_list_copy_and_path_remove(old_pl_index, FIB_PATH_LIST_FLAG_SHARED, rpaths); fib_path_list_child_remove(old_pl_index, mt->mt_sibling_index); if (FIB_NODE_INDEX_INVALID == mt->mt_path_list) { /* no paths left */ fib_path_list_unlock(old_pl_index); return (0); } else { mt->mt_sibling_index = fib_path_list_child_add(mt->mt_path_list, FIB_NODE_TYPE_MPLS_TUNNEL, mti); } /* * find the matching path extension and remove it */ fib_path_ext_list_remove(&mt->mt_path_exts, FIB_PATH_EXT_MPLS, rpaths); /* * re-resolve all the path-extensions with the new path-list */ fib_path_ext_list_resolve(&mt->mt_path_exts, mt->mt_path_list); mpls_tunnel_restack(mt); fib_path_list_unlock(old_pl_index); } return (fib_path_list_get_n_paths(mt->mt_path_list)); } int vnet_mpls_tunnel_get_index (u32 sw_if_index) { mpls_tunnel_t *mt; mt = mpls_tunnel_get_from_sw_if_index(sw_if_index); if (NULL == mt) return (~0); return (mt - mpls_tunnel_pool); } static clib_error_t * vnet_create_mpls_tunnel_command_fn (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { unformat_input_t _line_input, * line_input = &_line_input; vnet_main_t * vnm = vnet_get_main(); u8 is_del = 0, l2_only = 0, is_multicast =0; fib_route_path_t rpath, *rpaths = NULL; u32 sw_if_index = ~0, payload_proto; clib_error_t *error = NULL; clib_memset(&rpath, 0, sizeof(rpath)); payload_proto = DPO_PROTO_MPLS; /* Get a line of input. */ if (! unformat_user (input, unformat_line_input, line_input)) return 0; while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT) { if (unformat (line_input, "del %U", unformat_vnet_sw_interface, vnm, &sw_if_index)) is_del = 1; else if (unformat (line_input, "add %U", unformat_vnet_sw_interface, vnm, &sw_if_index)) is_del = 0; else if (unformat (line_input, "add")) is_del = 0; else if (unformat (line_input, "l2-only")) l2_only = 1; else if (unformat (line_input, "multicast")) is_multicast = 1; else if (unformat (line_input, "via %U", unformat_fib_route_path, &rpath, &payload_proto)) vec_add1(rpaths, rpath); else { error = clib_error_return (0, "unknown input '%U'", format_unformat_error, line_input); goto done; } } if (is_del) { if (NULL == rpaths) { vnet_mpls_tunnel_del(sw_if_index); } else if (!vnet_mpls_tunnel_path_remove(sw_if_index, rpaths)) { vnet_mpls_tunnel_del(sw_if_index); } } else { if (0 == vec_len(rpath.frp_label_stack)) { error = clib_error_return (0, "No Output Labels '%U'", format_unformat_error, line_input); goto done; } if (~0 == sw_if_index) { sw_if_index = vnet_mpls_tunnel_create(l2_only, is_multicast, NULL); } vnet_mpls_tunnel_path_add(sw_if_index, rpaths); } done: vec_free(rpaths); unformat_free (line_input); return error; } /*? * This command create a uni-directional MPLS tunnel * * @cliexpar * @cliexstart{create mpls tunnel} * create mpls tunnel via 10.0.0.1 GigEthernet0/8/0 out-label 33 out-label 34 * @cliexend ?*/ VLIB_CLI_COMMAND (create_mpls_tunnel_command, static) = { .path = "mpls tunnel", .short_help = "mpls tunnel [multicast] [l2-only] via [next-hop-address] [next-hop-interface] [next-hop-table <value>] [weight <value>] [preference <value>] [udp-encap-id <value>] [ip4-lookup-in-table <value>] [ip6-lookup-in-table <value>] [mpls-lookup-in-table <value>] [resolve-via-host] [resolve-via-connected] [rx-ip4 <interface>] [out-labels <value value value>]", .function = vnet_create_mpls_tunnel_command_fn, }; static u8 * format_mpls_tunnel (u8 * s, va_list * args) { mpls_tunnel_t *mt = va_arg (*args, mpls_tunnel_t *); mpls_tunnel_attribute_t attr; s = format(s, "mpls-tunnel%d: sw_if_index:%d hw_if_index:%d", mt - mpls_tunnel_pool, mt->mt_sw_if_index, mt->mt_hw_if_index); if (MPLS_TUNNEL_FLAG_NONE != mt->mt_flags) { s = format(s, " \n flags:"); FOR_EACH_MPLS_TUNNEL_ATTRIBUTE(attr) { if ((1<<attr) & mt->mt_flags) { s = format (s, "%s,", mpls_tunnel_attribute_names[attr]); } } } s = format(s, "\n via:\n"); s = fib_path_list_format(mt->mt_path_list, s); s = format(s, "%U", format_fib_path_ext_list, &mt->mt_path_exts); s = format(s, "\n"); if (mt->mt_flags & MPLS_TUNNEL_FLAG_L2) { s = format(s, " forwarding: %U\n", format_fib_forw_chain_type, FIB_FORW_CHAIN_TYPE_ETHERNET); s = format(s, " %U\n", format_dpo_id, &mt->mt_l2_lb, 2); } return (s); } static clib_error_t * show_mpls_tunnel_command_fn (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { mpls_tunnel_t * mt; u32 mti = ~0; if (pool_elts (mpls_tunnel_pool) == 0) vlib_cli_output (vm, "No MPLS tunnels configured..."); while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) { if (unformat (input, "%d", &mti)) ; else break; } if (~0 == mti) { pool_foreach (mt, mpls_tunnel_pool) { vlib_cli_output (vm, "[@%d] %U", mt - mpls_tunnel_pool, format_mpls_tunnel, mt); } } else { if (pool_is_free_index(mpls_tunnel_pool, mti)) return clib_error_return (0, "Not a tunnel index %d", mti); mt = pool_elt_at_index(mpls_tunnel_pool, mti); vlib_cli_output (vm, "[@%d] %U", mt - mpls_tunnel_pool, format_mpls_tunnel, mt); } return 0; } /*? * This command to show MPLS tunnels * * @cliexpar * @cliexstart{sh mpls tunnel 2} * [@2] mpls_tunnel2: sw_if_index:5 hw_if_index:5 * label-stack: * 3, * via: * index:26 locks:1 proto:ipv4 uPRF-list:26 len:1 itfs:[2, ] * index:26 pl-index:26 ipv4 weight=1 attached-nexthop: oper-flags:resolved, * 10.0.0.2 loop0 * [@0]: ipv4 via 10.0.0.2 loop0: IP4: de:ad:00:00:00:00 -> 00:00:11:aa:bb:cc * @cliexend ?*/ VLIB_CLI_COMMAND (show_mpls_tunnel_command, static) = { .path = "show mpls tunnel", .function = show_mpls_tunnel_command_fn, }; static mpls_tunnel_t * mpls_tunnel_from_fib_node (fib_node_t *node) { ASSERT(FIB_NODE_TYPE_MPLS_TUNNEL == node->fn_type); return ((mpls_tunnel_t*) (((char*)node) - STRUCT_OFFSET_OF(mpls_tunnel_t, mt_node))); } /** * Function definition to backwalk a FIB node */ static fib_node_back_walk_rc_t mpls_tunnel_back_walk (fib_node_t *node, fib_node_back_walk_ctx_t *ctx) { mpls_tunnel_restack(mpls_tunnel_from_fib_node(node)); return (FIB_NODE_BACK_WALK_CONTINUE); } /** * Function definition to get a FIB node from its index */ static fib_node_t* mpls_tunnel_fib_node_get (fib_node_index_t index) { mpls_tunnel_t * mt; mt = pool_elt_at_index(mpls_tunnel_pool, index); return (&mt->mt_node); } /** * Function definition to inform the FIB node that its last lock has gone. */ static void mpls_tunnel_last_lock_gone (fib_node_t *node) { /* * The MPLS MPLS tunnel is a root of the graph. As such * it never has children and thus is never locked. */ ASSERT(0); } /* * Virtual function table registered by MPLS MPLS tunnels * for participation in the FIB object graph. */ const static fib_node_vft_t mpls_vft = { .fnv_get = mpls_tunnel_fib_node_get, .fnv_last_lock = mpls_tunnel_last_lock_gone, .fnv_back_walk = mpls_tunnel_back_walk, }; static clib_error_t * mpls_tunnel_init (vlib_main_t *vm) { fib_node_register_type(FIB_NODE_TYPE_MPLS_TUNNEL, &mpls_vft); return 0; } VLIB_INIT_FUNCTION(mpls_tunnel_init);
f12e631ef0e671b20171fc3698aa2072da31af7d
581bdcc078d282e388f1b655d4cfc4e08152d117
/plugins/OnlineChecks/db.c
2d1c00cc7280e273a0f8dcf8c4ae8c7a6e491b5d
[ "MIT", "BSD-3-Clause", "LGPL-2.0-or-later", "Zlib", "LGPL-2.1-or-later", "GPL-2.0-only", "LicenseRef-scancode-public-domain" ]
permissive
winsiderss/systeminformer
774928be871f0055263ac5e62ae0a598b098486b
5a6b442acd45d681f699a133d476a3211d072871
refs/heads/master
2023-08-28T15:43:41.074679
2023-08-27T20:59:20
2023-08-27T20:59:20
50,824,485
2,137
292
MIT
2023-09-10T22:35:12
2016-02-01T08:10:21
C
UTF-8
C
false
false
3,146
c
db.c
/* * Copyright (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved. * * This file is part of System Informer. * * Authors: * * dmex 2016-2023 * */ #include "onlnchk.h" PPH_HASHTABLE ProcessObjectDb; PH_QUEUED_LOCK ProcessObjectDbLock = PH_QUEUED_LOCK_INIT; PH_STRINGREF ProcessObjectDbHash = PH_STRINGREF_INIT(L"386f3b6b3f6c35346c69346c6b343d69396b6b3468386b683d383d356b3e383e38356b343f69393b683d3b3a39386b3c6b3a3a3e696835696e686f6b38683e6e"); PH_STRINGREF ServiceObjectDbHash = PH_STRINGREF_INIT(L"39666e39663d6e66356e3935666a66626e6e627e6e35623d6a3d6a3d6e6e6e6a6a6a35396a6a3d6e7a357e7e7a35626a663d6e7a3d6a3d6e7a397e3d3d6e6e7e"); PH_STRINGREF NetworkObjectDbHash = PH_STRINGREF_INIT(L"6e61653c676065676b6b7a393d6a66357a396a6e6e66397a35"); BOOLEAN NTAPI ProcessObjectDbEqualFunction( _In_ PVOID Entry1, _In_ PVOID Entry2 ) { PPROCESS_DB_OBJECT object1 = *(PPROCESS_DB_OBJECT *)Entry1; PPROCESS_DB_OBJECT object2 = *(PPROCESS_DB_OBJECT *)Entry2; return PhEqualStringRef(&object1->FileName, &object2->FileName, FALSE); } ULONG NTAPI ProcessObjectDbHashFunction( _In_ PVOID Entry ) { PPROCESS_DB_OBJECT object = *(PPROCESS_DB_OBJECT *)Entry; return PhHashStringRefEx(&object->FileName, FALSE, PH_STRING_HASH_X65599); } VOID InitializeProcessDb( VOID ) { ProcessObjectDb = PhCreateHashtable( sizeof(PPROCESS_DB_OBJECT), ProcessObjectDbEqualFunction, ProcessObjectDbHashFunction, 64 ); } VOID CleanupProcessDb( VOID ) { PhDereferenceObject(ProcessObjectDb); } ULONG GetNumberOfProcessDbObjects( VOID ) { return ProcessObjectDb->Count; } VOID LockProcessDb( VOID ) { PhAcquireQueuedLockExclusive(&ProcessObjectDbLock); } VOID UnlockProcessDb( VOID ) { PhReleaseQueuedLockExclusive(&ProcessObjectDbLock); } PPROCESS_DB_OBJECT FindProcessDbObject( _In_ PPH_STRINGREF FileName ) { PROCESS_DB_OBJECT lookupObject; PPROCESS_DB_OBJECT lookupObjectPtr; PPROCESS_DB_OBJECT *objectPtr; lookupObject.FileName = *FileName; lookupObjectPtr = &lookupObject; objectPtr = PhFindEntryHashtable(ProcessObjectDb, &lookupObjectPtr); if (objectPtr) return *objectPtr; else return NULL; } PPROCESS_DB_OBJECT CreateProcessDbObject( _In_ PPH_STRING FileName, _In_opt_ INT64 Positives, _In_opt_ INT64 Total, _In_opt_ PPH_STRING Hash ) { PPROCESS_DB_OBJECT object; BOOLEAN added; PPROCESS_DB_OBJECT *realObject; PH_FORMAT format[3]; PhReferenceObject(FileName); object = PhAllocateZero(sizeof(PROCESS_DB_OBJECT)); object->FileName = PhGetStringRef(FileName); object->Positives = Positives; object->Hash = FileName; // %lu | %lu PhInitFormatU(&format[0], (ULONG)Positives); PhInitFormatS(&format[1], L" | "); PhInitFormatU(&format[2], (ULONG)Total); object->Result = PhFormat(format, RTL_NUMBER_OF(format), 0); realObject = PhAddEntryHashtableEx(ProcessObjectDb, &object, &added); if (added) return object; else return NULL; }
be1b855f51f85dcf9c5e9eeb53977f4b94794eaa
0744dcc5394cebf57ebcba343747af6871b67017
/os/fs/inode/inode.h
045a4aecfca23cfdddafd8647b64d3abbd56ba57
[ "GPL-1.0-or-later", "BSD-3-Clause", "ISC", "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", "Apache-2.0" ]
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
14,392
h
inode.h
/**************************************************************************** * * Copyright 2016 Samsung Electronics 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. * ****************************************************************************/ /**************************************************************************** * fs/inode/inode.h * * Copyright (C) 2007, 2009, 2012, 2014 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * 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 NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __FS_INODE_H #define __FS_INODE_H /**************************************************************************** * Included Files ****************************************************************************/ #include <tinyara/config.h> #include <sys/types.h> #include <stdint.h> #include <dirent.h> #include <tinyara/fs/fs.h> #include <tinyara/compiler.h> /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* Inode i_flag values */ #define FSNODEFLAG_TYPE_MASK 0x00000007 /* Isolates type field */ #define FSNODEFLAG_TYPE_DRIVER 0x00000000 /* Character driver */ #define FSNODEFLAG_TYPE_BLOCK 0x00000001 /* Block driver */ #define FSNODEFLAG_TYPE_MOUNTPT 0x00000002 /* Mount point */ #define FSNODEFLAG_TYPE_SPECIAL 0x00000004 /* Special OS type */ #define FSNODEFLAG_TYPE_NAMEDSEM 0x00000004 /* Named semaphore */ #define FSNODEFLAG_TYPE_MQUEUE 0x00000005 /* Message Queue */ #define FSNODEFLAG_TYPE_SHM 0x00000006 /* Shared memory region */ #define FSNODEFLAG_DELETED 0x00000008 /* Unlinked */ #define INODE_IS_TYPE(i, t) \ (((i)->i_flags & FSNODEFLAG_TYPE_MASK) == (t)) #define INODE_IS_SPECIAL(i) \ (((i)->i_flags & FSNODEFLAG_TYPE_SPECIAL) != 0) #define INODE_IS_DRIVER(i) INODE_IS_TYPE(i, FSNODEFLAG_TYPE_DRIVER) #define INODE_IS_BLOCK(i) INODE_IS_TYPE(i, FSNODEFLAG_TYPE_BLOCK) #define INODE_IS_MOUNTPT(i) INODE_IS_TYPE(i, FSNODEFLAG_TYPE_MOUNTPT) #define INODE_IS_NAMEDSEM(i) INODE_IS_TYPE(i, FSNODEFLAG_TYPE_NAMEDSEM) #define INODE_IS_MQUEUE(i) INODE_IS_TYPE(i, FSNODEFLAG_TYPE_MQUEUE) #define INODE_IS_SHM(i) INODE_IS_TYPE(i, FSNODEFLAG_TYPE_SHM) #define INODE_GET_TYPE(i) ((i)->i_flags & FSNODEFLAG_TYPE_MASK) #define INODE_SET_TYPE(i, t) \ do { \ (i)->i_flags = ((i)->i_flags & ~FSNODEFLAG_TYPE_MASK) | (t); \ } while (0) #define INODE_SET_DRIVER(i) INODE_SET_TYPE(i, FSNODEFLAG_TYPE_DRIVER) #define INODE_SET_BLOCK(i) INODE_SET_TYPE(i, FSNODEFLAG_TYPE_BLOCK) #define INODE_SET_MOUNTPT(i) INODE_SET_TYPE(i, FSNODEFLAG_TYPE_MOUNTPT) #define INODE_SET_NAMEDSEM(i) INODE_SET_TYPE(i, FSNODEFLAG_TYPE_NAMEDSEM) #define INODE_SET_MQUEUE(i) INODE_SET_TYPE(i, FSNODEFLAG_TYPE_MQUEUE) #define INODE_SET_SHM(i) INODE_SET_TYPE(i, FSNODEFLAG_TYPE_SHM) /* Mountpoint fd_flags values */ #define DIRENTFLAGS_PSEUDONODE 1 #define DIRENT_SETPSEUDONODE(f) do { (f) |= DIRENTFLAGS_PSEUDONODE; } while (0) #define DIRENT_ISPSEUDONODE(f) (((f) & DIRENTFLAGS_PSEUDONODE) != 0) /**************************************************************************** * Public Types ****************************************************************************/ /* Callback used by foreach_inode to traverse all inodes in the pseudo- * file system. */ typedef int (*foreach_inode_t)(FAR struct inode *node, FAR char dirpath[PATH_MAX], FAR void *arg); /**************************************************************************** * Global Variables ****************************************************************************/ #undef EXTERN #if defined(__cplusplus) #define EXTERN extern "C" extern "C" { #else #define EXTERN extern #endif EXTERN FAR struct inode *root_inode; /**************************************************************************** * Public Function Prototypes ****************************************************************************/ /* fs_inode.c ***************************************************************/ /**************************************************************************** * Name: inode_initialize * * Description: * This is called from the OS initialization logic to configure the file * system. * ****************************************************************************/ void inode_initialize(void); /**************************************************************************** * Name: inode_semtake * * Description: * Get exclusive access to the in-memory inode tree (tree_sem). * ****************************************************************************/ void inode_semtake(void); /**************************************************************************** * Name: inode_semgive * * Description: * Relinquish exclusive access to the in-memory inode tree (tree_sem). * ****************************************************************************/ void inode_semgive(void); /**************************************************************************** * Name: inode_search * * Description: * Find the inode associated with 'path' returning the inode references * and references to its companion nodes. * * Assumptions: * The caller holds the tree_sem * ****************************************************************************/ FAR struct inode *inode_search(FAR const char **path, FAR struct inode **peer, FAR struct inode **parent, FAR const char **relpath); /**************************************************************************** * Name: inode_stat * * Description: * The inode_stat() function will obtain information about an 'inode' in * the pseudo file system and will write it to the area pointed to by 'buf'. * * The 'buf' argument is a pointer to a stat structure, as defined in * <sys/stat.h>, into which information is placed concerning the file. * * Input Parameters: * inode - The inode of interest * buf - The caller provide location in which to return information about * the inode. * * Returned Value: * Zero (OK) returned on success. Otherwise, a negated errno value is * returned to indicate the nature of the failure. * ****************************************************************************/ struct stat; /* Forward reference */ int inode_stat(FAR struct inode *inode, FAR struct stat *buf); /**************************************************************************** * Name: inode_free * * Description: * Free resources used by an inode * ****************************************************************************/ void inode_free(FAR struct inode *node); /**************************************************************************** * Name: inode_nextname * * Description: * Given a path with node names separated by '/', return the next node * name. * ****************************************************************************/ const char *inode_nextname(FAR const char *name); /* fs_inodereserver.c *******************************************************/ /**************************************************************************** * Name: inode_reserve * * Description: * Reserve an (initialized) inode the pseudo file system. * * NOTE: Caller must hold the inode semaphore * * Input parameters: * path - The path to the inode to create * inode - The location to return the inode pointer * * Returned Value: * Zero on success (with the inode point in 'inode'); A negated errno * value is returned on failure: * * EINVAL - 'path' is invalid for this operation * EEXIST - An inode already exists at 'path' * ENOMEM - Failed to allocate in-memory resources for the operation * ****************************************************************************/ int inode_reserve(FAR const char *path, FAR struct inode **inode); /* fs_inoderemove.c *********************************************************/ /**************************************************************************** * Name: inode_unlink * * Description: * Given a path, remove a the node from the in-memory, inode tree that the * path refers to. This is normally done in preparation to removing or * moving an inode. * * Assumptions/Limitations: * The caller must hold the inode semaphore * ****************************************************************************/ FAR struct inode *inode_unlink(FAR const char *path); /**************************************************************************** * Name: inode_remove * * Description: * Given a path, remove a the node from the in-memory, inode tree that the * path refers to and free all resources related to the inode. If the * inode is in-use, then it will be unlinked, but will not be freed until * the last reference to the inode is released. * * Assumptions/Limitations: * The caller must hold the inode semaphore * ****************************************************************************/ int inode_remove(FAR const char *path); /* fs_inodefind.c ***********************************************************/ /**************************************************************************** * Name: inode_find * * Description: * This is called from the open() logic to get a reference to the inode * associated with a path. * ****************************************************************************/ FAR struct inode *inode_find(FAR const char *path, const char **relpath); /* fs_inodeaddref.c *********************************************************/ void inode_addref(FAR struct inode *inode); /* fs_inoderelease.c ********************************************************/ void inode_release(FAR struct inode *inode); /* fs_foreachinode.c ********************************************************/ /**************************************************************************** * Name: foreach_inode * * Description: * Visit each inode in the pseudo-file system. The traversal is terminated * when the callback 'handler' returns a non-zero value, or when all of * the inodes have been visited. * * NOTE 1: Use with caution... The pseudo-file system is locked throughout * the traversal. * NOTE 2: The search algorithm is recursive and could, in principle, use * an indeterminant amount of stack space. This will not usually be a * real work issue. * ****************************************************************************/ int foreach_inode(foreach_inode_t handler, FAR void *arg); /* fs_files.c ***************************************************************/ /**************************************************************************** * Name: files_initialize * * Description: * This is called from the FS initialization logic to configure the files. * ****************************************************************************/ void weak_function files_initialize(void); /**************************************************************************** * Name: files_allocate * * Description: * Allocate a struct files instance and associate it with an inode instance. * Returns the file descriptor == index into the files array. * ****************************************************************************/ int files_allocate(FAR struct inode *inode, int oflags, off_t pos, int minfd); /**************************************************************************** * Name: files_close * * Description: * Close an inode (if open) * * Assumuptions: * Caller holds the list semaphore because the file descriptor will be freed. * ****************************************************************************/ int files_close(int fd); /**************************************************************************** * Name: files_release * * Assumuptions: * Similar to files_close(). Called only from open() logic on error * conditions. * ****************************************************************************/ void files_release(int fd); #undef EXTERN #if defined(__cplusplus) } #endif #endif /* __FS_INODE_H */
e4fa87767c2b5756a93f8a60e39c4e2c1d8ed7d3
9f01cf4f599af5ef184b0a0c5ddc9a5ae6e249bf
/engine/wii/control.c
d4b568cfd7b2e059daa11c27497f8761389e7650
[]
permissive
DCurrent/openbor
89f348ce7a93519f420ac6602d1fea615703f4ca
7f6f17507078848be625e6d1c1b4f41823151387
refs/heads/master
2023-09-03T12:41:21.059545
2022-04-22T20:39:58
2022-04-22T20:39:58
86,879,076
817
127
BSD-3-Clause
2023-09-13T11:47:20
2017-04-01T03:06:14
C
UTF-8
C
false
false
16,779
c
control.c
/* * OpenBOR - http://www.chronocrash.com * ----------------------------------------------------------------------- * All rights reserved, see LICENSE in OpenBOR root for details. * * Copyright (c) 2004 - 2019 OpenBOR Team */ // Generic control stuff (keyboard+joystick) #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <ogc/lwp_watchdog.h> #include <wiiuse/wpad.h> #include <ogc/pad.h> #include <ogc/system.h> #include "globals.h" #include "control.h" #include "openbor.h" #include "List.h" /*#define NUNCHUK_STICK_UP (0x0004 << 16) #define NUNCHUK_STICK_DOWN (0x0008 << 16) #define NUNCHUK_STICK_LEFT (0x0010 << 16) #define NUNCHUK_STICK_RIGHT (0x0020 << 16)*/ #define LEFT_STICK_UP -1 #define LEFT_STICK_DOWN -2 #define LEFT_STICK_LEFT -3 #define LEFT_STICK_RIGHT -4 typedef enum { DEVICE_TYPE_NONE, DEVICE_TYPE_WII_REMOTE, DEVICE_TYPE_WIIMOTE_NUNCHUK, DEVICE_TYPE_CLASSIC_CONTROLLER, DEVICE_TYPE_PRO_CONTROLLER, DEVICE_TYPE_GAMECUBE_CONTROLLER, } DeviceType; typedef struct { DeviceType deviceType; char name[CONTROL_DEVICE_NAME_SIZE]; int mappings[SDID_COUNT]; int port; // TODO: rumble } InputDevice; static InputDevice devices[MAX_DEVICES]; static bool controlInited = false; static int wiimoteIDs[4] = {-1, -1, -1, -1}; // if non-null, device is being remapped in the input settings menu static InputDevice *remapDevice = NULL; static int remapKeycode = -1; // each list member is an array of SDID_COUNT ints, dynamically allocated static List savedMappings; static bool savedMappingsInited = false; static const char *deviceTypeNames[] = { "None", "Wii Remote", "Remote+Nunchuk", "Classic Controller", "Wii U Pro Controller", "GameCube Controller", }; static void handle_events(); // update the mappings for a device in the save data static void update_saved_mapping(int deviceID) { InputDevice *device = &devices[deviceID]; if (device->deviceType == DEVICE_TYPE_NONE) return; if (List_FindByName(&savedMappings, device->name)) { memcpy(List_Retrieve(&savedMappings), device->mappings, SDID_COUNT * sizeof(int)); } else { int *mappings = malloc(SDID_COUNT * sizeof(int)); memcpy(mappings, device->mappings, SDID_COUNT * sizeof(int)); List_InsertAfter(&savedMappings, mappings, device->name); } } // set the mappings for a device to the saved settings static void load_from_saved_mapping(int deviceID) { InputDevice *device = &devices[deviceID]; if (device->deviceType == DEVICE_TYPE_NONE) return; if (List_FindByName(&savedMappings, device->name)) { memcpy(device->mappings, List_Retrieve(&savedMappings), SDID_COUNT * sizeof(int)); } else { control_resetmappings(deviceID); } } static void clear_saved_mappings() { if (!savedMappingsInited) { List_Init(&savedMappings); savedMappingsInited = true; } int numMappings = List_GetSize(&savedMappings); List_Reset(&savedMappings); for (int i = 0; i < numMappings; i++) { free(List_Retrieve(&savedMappings)); List_GotoNext(&savedMappings); } List_Clear(&savedMappings); } static void setup_device(int deviceID, DeviceType type, const char *name, int port) { devices[deviceID].deviceType = type; devices[deviceID].port = port; snprintf(devices[deviceID].name, sizeof(devices[deviceID].name), "%s #%i", name, port+1); load_from_saved_mapping(deviceID); printf("Set up device: %s\n", devices[deviceID].name); } void control_init() { if (controlInited) return; if (!savedMappingsInited) { List_Init(&savedMappings); savedMappingsInited = true; } // initialize all devices to DEVICE_TYPE_NONE and all device IDs to -1 memset(devices, 0, sizeof(devices)); memset(wiimoteIDs, 0xff, sizeof(wiimoteIDs)); //PAD_Init(); //WUPC_Init(); WPAD_Init(); handle_events(); controlInited = true; } void control_exit() { if (!controlInited) return; clear_saved_mappings(); for (int i = 0; i < MAX_DEVICES; i++) { InputDevice *device = &devices[i]; device->deviceType = DEVICE_TYPE_NONE; } remapDevice = NULL; remapKeycode = -1; controlInited = false; } static void set_default_wiimote_mappings(InputDevice *device) { // up/down/left/right are rotated because the remote is held sideways device->mappings[SDID_MOVEUP] = WPAD_BUTTON_RIGHT; device->mappings[SDID_MOVEDOWN] = WPAD_BUTTON_LEFT; device->mappings[SDID_MOVELEFT] = WPAD_BUTTON_UP; device->mappings[SDID_MOVERIGHT] = WPAD_BUTTON_DOWN; device->mappings[SDID_ATTACK] = WPAD_BUTTON_1; device->mappings[SDID_ATTACK2] = WPAD_BUTTON_A; device->mappings[SDID_ATTACK3] = WPAD_BUTTON_HOME; device->mappings[SDID_ATTACK4] = 0; device->mappings[SDID_JUMP] = WPAD_BUTTON_2; device->mappings[SDID_SPECIAL] = WPAD_BUTTON_B; device->mappings[SDID_START] = WPAD_BUTTON_PLUS; device->mappings[SDID_SCREENSHOT] = WPAD_BUTTON_MINUS; device->mappings[SDID_ESC] = WPAD_BUTTON_1; } static void set_default_wiimote_nunchuk_mappings(InputDevice *device) { device->mappings[SDID_MOVEUP] = LEFT_STICK_UP; device->mappings[SDID_MOVEDOWN] = LEFT_STICK_DOWN; device->mappings[SDID_MOVELEFT] = LEFT_STICK_LEFT; device->mappings[SDID_MOVERIGHT] = LEFT_STICK_RIGHT; device->mappings[SDID_ATTACK] = WPAD_BUTTON_A; device->mappings[SDID_ATTACK2] = WPAD_NUNCHUK_BUTTON_C; device->mappings[SDID_ATTACK3] = WPAD_BUTTON_1; device->mappings[SDID_ATTACK4] = WPAD_BUTTON_2; device->mappings[SDID_JUMP] = WPAD_BUTTON_B; device->mappings[SDID_SPECIAL] = WPAD_NUNCHUK_BUTTON_Z; device->mappings[SDID_START] = WPAD_BUTTON_PLUS; device->mappings[SDID_SCREENSHOT] = WPAD_BUTTON_MINUS; device->mappings[SDID_ESC] = WPAD_BUTTON_B; } static void set_default_classic_controller_mappings(InputDevice *device) { device->mappings[SDID_MOVEUP] = WPAD_CLASSIC_BUTTON_UP; device->mappings[SDID_MOVEDOWN] = WPAD_CLASSIC_BUTTON_DOWN; device->mappings[SDID_MOVELEFT] = WPAD_CLASSIC_BUTTON_LEFT; device->mappings[SDID_MOVERIGHT] = WPAD_CLASSIC_BUTTON_RIGHT; device->mappings[SDID_ATTACK] = WPAD_CLASSIC_BUTTON_A; device->mappings[SDID_ATTACK2] = WPAD_CLASSIC_BUTTON_Y; device->mappings[SDID_ATTACK3] = WPAD_CLASSIC_BUTTON_FULL_R; device->mappings[SDID_ATTACK4] = WPAD_CLASSIC_BUTTON_FULL_L; device->mappings[SDID_JUMP] = WPAD_CLASSIC_BUTTON_B; device->mappings[SDID_SPECIAL] = WPAD_CLASSIC_BUTTON_X; device->mappings[SDID_START] = WPAD_CLASSIC_BUTTON_PLUS; device->mappings[SDID_SCREENSHOT] = WPAD_CLASSIC_BUTTON_MINUS; device->mappings[SDID_ESC] = WPAD_CLASSIC_BUTTON_B; } void control_resetmappings(int deviceID) { if (deviceID < 0) return; InputDevice *device = &devices[deviceID]; switch (device->deviceType) { case DEVICE_TYPE_WII_REMOTE: set_default_wiimote_mappings(device); break; case DEVICE_TYPE_WIIMOTE_NUNCHUK: set_default_wiimote_nunchuk_mappings(device); break; case DEVICE_TYPE_CLASSIC_CONTROLLER: set_default_classic_controller_mappings(device); break; default: memset(device->mappings, 0, sizeof(device->mappings)); break; } } static DeviceType device_type_for_expansion_type(int expansion) { switch (expansion) { case WPAD_EXP_NUNCHUK: return DEVICE_TYPE_WIIMOTE_NUNCHUK; case WPAD_EXP_CLASSIC: return DEVICE_TYPE_CLASSIC_CONTROLLER; case WPAD_EXP_NONE: default: return DEVICE_TYPE_WII_REMOTE; } } // handle controller connected/disconnected or Wiimote expansion plugged/unplugged static void handle_events() { WPAD_ScanPads(); for (size_t port = 0; port < 4; port++) { u32 type; if (WPAD_Probe(port, &type) == WPAD_ERR_NO_CONTROLLER) // wiimote disconnected { if (devices[port].deviceType != DEVICE_TYPE_NONE) if (wiimoteIDs[port] != -1) { printf("%s disconnected\n", devices[port].name); devices[wiimoteIDs[port]].deviceType = DEVICE_TYPE_NONE; wiimoteIDs[port] = -1; } } else { WPADData *wpad = WPAD_Data(port); DeviceType newType = device_type_for_expansion_type(wpad->exp.type); if (wiimoteIDs[port] == -1) // wiimote connected { for (size_t i = 0; i < MAX_DEVICES; i++) { if (devices[i].deviceType == DEVICE_TYPE_NONE) { wiimoteIDs[port] = i; break; } } // MAX_DEVICES is 32 and there are a maximum of 12 devices supported, so this should be safe assert(wiimoteIDs[port] != -1); } if (newType != devices[wiimoteIDs[port]].deviceType) // wiimote connected or expansion type changed { setup_device(wiimoteIDs[port], newType, deviceTypeNames[newType], port); } } } } // Returns 1 if key is pressed, 0 if not static unsigned int is_key_pressed(InputDevice *device, int keycode) { if (device->deviceType == DEVICE_TYPE_WII_REMOTE) { WPADData *wpad = WPAD_Data(device->port); return !!(wpad->btns_h & keycode); } else if (device->deviceType == DEVICE_TYPE_WIIMOTE_NUNCHUK) { WPADData *wpad = WPAD_Data(device->port); switch (keycode) { case LEFT_STICK_UP: return (wpad->exp.nunchuk.js.pos.y >= 0xB0); case LEFT_STICK_DOWN: return (wpad->exp.nunchuk.js.pos.y <= 0x40); case LEFT_STICK_LEFT: return (wpad->exp.nunchuk.js.pos.x <= 0x40); case LEFT_STICK_RIGHT: return (wpad->exp.nunchuk.js.pos.x >= 0xB0); default: return !!(wpad->btns_h & keycode); } } else if (device->deviceType == DEVICE_TYPE_CLASSIC_CONTROLLER) { // TODO: analog sticks WPADData *wpad = WPAD_Data(device->port); return !!(wpad->btns_h & keycode); } return 0; } void control_update_player(s_playercontrols *playerControls) { uint32_t keyflags = 0; InputDevice *device = &devices[playerControls->deviceID]; for (unsigned int i = 0; i < SDID_COUNT; i++) { keyflags |= (is_key_pressed(device, device->mappings[i]) << i); } playerControls->newkeyflags = keyflags & (~playerControls->keyflags); playerControls->keyflags = keyflags; } void control_update(s_playercontrols **playerControls, int numPlayers) { handle_events(); for (int i = 0; i < numPlayers; i++) { control_update_player(playerControls[i]); } } void control_remapdevice(int deviceID) { if (deviceID < 0) { // done remapping; reset globals to default values remapDevice = NULL; remapKeycode = -1; } else { assert(devices[deviceID].deviceType != DEVICE_TYPE_NONE); remapDevice = &devices[deviceID]; remapKeycode = -1; } } int control_getremappedkey() { return remapKeycode; } int *control_getmappings(int deviceID) { return devices[deviceID].mappings; } const char *control_getkeyname(int deviceID, int keycode) { if (deviceID < 0) return "None"; if (devices[deviceID].deviceType == DEVICE_TYPE_WII_REMOTE) { const char *buttonNames[] = { "2", "1", "B", "A", "-", "???", "???", "Home", "Down", "Up", "Left", "Right", "+", }; for (size_t i = 0; i < sizeof(buttonNames) / sizeof(buttonNames[0]); i++) { if (keycode == (1 << i)) { return buttonNames[i]; } } } else if (devices[deviceID].deviceType == DEVICE_TYPE_WIIMOTE_NUNCHUK) { const char *buttonNames[] = { "2", "1", "B", "A", "-", "Home", "D-Pad Left", "D-Pad Right", "D-Pad Down", "D-Pad Up", "+", "???", "???", "???", "Z", "C", }; for (size_t i = 0; i < sizeof(buttonNames) / sizeof(buttonNames[0]); i++) { if (keycode == (1 << i)) { return buttonNames[i]; } } // if it's not a button, it's an analog stick direction switch (keycode) { case LEFT_STICK_UP: return "Analog Stick Up"; case LEFT_STICK_DOWN: return "Analog Stick Down"; case LEFT_STICK_LEFT: return "Analog Stick Left"; case LEFT_STICK_RIGHT: return "Analog Stick Right"; } } else if (devices[deviceID].deviceType == DEVICE_TYPE_CLASSIC_CONTROLLER) { const char *buttonNames[] = { "D-Pad Up", "D-Pad Left", "ZR", "X", "A", "Y", "B", "ZL", "R", "+", "Home", "-", "L", "Down", "Right", }; for (size_t i = 0; i < sizeof(buttonNames) / sizeof(buttonNames[0]); i++) { if (keycode == (0x10000 << i)) { return buttonNames[i]; } } } return "None"; } bool control_isvaliddevice(int deviceID) { return deviceID >= 0 && devices[deviceID].deviceType != DEVICE_TYPE_NONE; } const char *control_getdevicename(int deviceID) { return devices[deviceID].deviceType == DEVICE_TYPE_NONE ? "None" : devices[deviceID].name; } void control_rumble(int deviceID, int ratio, int msec) { // TODO } #define MAPPINGS_FILE_SENTINEL 0x9cf232d4 bool control_loadmappings(const char *filename) { FILE *fp = fopen(filename, "rb"); if (!fp) { return false; } clear_saved_mappings(); while (!feof(fp) && !ferror(fp)) { char name[CONTROL_DEVICE_NAME_SIZE]; int *mapping = malloc(SDID_COUNT * sizeof(int)); int sentinel; if (fread(name, 1, sizeof(name), fp) != sizeof(name) || fread(mapping, sizeof(int), SDID_COUNT, fp) != SDID_COUNT || fread(&sentinel, sizeof(int), 1, fp) != 1) { free(mapping); break; } else if (sentinel != MAPPINGS_FILE_SENTINEL) { free(mapping); fclose(fp); return false; } name[sizeof(name)-1] = '\0'; // just in case printf("Loaded mapping for %s\n", name); List_InsertAfter(&savedMappings, mapping, name); } fclose(fp); // update all current device mappings with the newly loaded mappings for (int i = 0; i < MAX_DEVICES; i++) { if (devices[i].deviceType != DEVICE_TYPE_NONE) { load_from_saved_mapping(i); } } return true; } bool control_savemappings(const char *filename) { // update savedMappings with all current device mappings for (int i = 0; i < MAX_DEVICES; i++) { if (devices[i].deviceType != DEVICE_TYPE_NONE) { update_saved_mapping(i); } } FILE *fp = fopen(filename, "wb"); if (!fp) { return false; } int numMappings = List_GetSize(&savedMappings); List_Reset(&savedMappings); for (int i = 0; i < numMappings; i++) { char name[CONTROL_DEVICE_NAME_SIZE]; snprintf(name, sizeof(name), "%s", List_GetName(&savedMappings)); int *mapping = List_Retrieve(&savedMappings); const int sentinel = MAPPINGS_FILE_SENTINEL; if (fwrite(name, 1, sizeof(name), fp) != sizeof(name) || fwrite(mapping, sizeof(int), SDID_COUNT, fp) != SDID_COUNT || fwrite(&sentinel, sizeof(int), 1, fp) != 1) { fclose(fp); return false; } List_GotoNext(&savedMappings); } fclose(fp); return true; } void control_clearmappings() { clear_saved_mappings(); for (int i = 0; i < MAX_DEVICES; i++) { if (devices[i].deviceType != DEVICE_TYPE_NONE) { control_resetmappings(i); } } }
c9f8e917d42f42acd7888c4935ccc6905e3b7742
149354d7985afe98a4e895adf3b87cc21a1c5d8d
/Kanan/metrics_gui/perf_timer.h
ea9a410d792884a66974798e7b8550a1d785b79c
[ "Unlicense" ]
permissive
cursey/kanan-new
5c8bde2bc51c985f116c889ba731ca77224baa90
4b1bb49cd8838e21263196c72ba0024394d7ef49
refs/heads/master
2023-09-01T02:46:48.031030
2023-08-26T01:01:19
2023-08-26T01:01:19
108,602,829
146
98
Unlicense
2023-09-08T02:25:48
2017-10-27T22:53:39
C++
UTF-8
C
false
false
1,990
h
perf_timer.h
/* Copyright 2017-2018 Intel Corporation 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. */ #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <stdint.h> #include <windows.h> struct PerfTimerFrequency { uint64_t Numerator; enum { Denominator = 1 }; }; inline uint64_t GetPerfTimerCount() { LARGE_INTEGER t; QueryPerformanceCounter(&t); return t.QuadPart; } inline PerfTimerFrequency GetPerfTimerFrequency() { PerfTimerFrequency f; QueryPerformanceFrequency((LARGE_INTEGER*) &f.Numerator); return f; } #else // ifdef _WIN32 #include <mach/mach_time.h> #include <stdint.h> struct PerfTimerFrequency { uint64_t Numerator; uint32_t Denominator; }; inline uint64_t GetPerfTimerCount() { return mach_absolute_time(); } inline PerfTimerFrequency GetPerfTimerFrequency() { mach_timebase_info_data_t i; mach_timebase_info(&i); PerfTimerFrequency f; f.Numerator = 1000000000ull * i.denom; f.Denominator = i.numer; return f; } #endif // ifdef _WIN32
3ce1e157d031e1023067a8faee3010014159521e
eecd5e4c50d8b78a769bcc2675250576bed34066
/include/petsc/private/glvisviewerimpl.h
4102fc517f9c54d145f16c8f6deac6090f9922dc
[ "BSD-2-Clause" ]
permissive
petsc/petsc
3b1a04fea71858e0292f9fd4d04ea11618c50969
9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9
refs/heads/main
2023-08-17T20:51:16.507070
2023-08-17T16:08:06
2023-08-17T16:08:06
8,691,401
341
169
NOASSERTION
2023-03-29T11:02:58
2013-03-10T20:55:21
C
UTF-8
C
false
false
2,416
h
glvisviewerimpl.h
#ifndef _GLVISIMPL_H #define _GLVISIMPL_H #include <petscviewer.h> #include <petscsys.h> struct _n_PetscViewerGLVisVecInfo { char *fec_type; /* the output of FiniteElementCollection::Name() */ }; typedef struct _n_PetscViewerGLVisVecInfo *PetscViewerGLVisVecInfo; struct _n_PetscViewerGLVisInfo { PetscBool enabled; /* whether or not to visualize data from the process (it works, but it currently misses a public API) */ PetscBool init; /* whether or not the popup window has been initialized (must be done after having sent the data the first time) */ PetscInt size[2]; /* window sizes */ PetscReal pause; /* pause argument */ char *fmt; /* format */ }; typedef struct _n_PetscViewerGLVisInfo *PetscViewerGLVisInfo; typedef enum { PETSCVIEWERGLVIS_DISCONNECTED, PETSCVIEWERGLVIS_CONNECTED, PETSCVIEWERGLVIS_DISABLED } PetscViewerGLVisStatus; PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscViewerGLVisPause_Internal(PetscViewer); PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscViewerGLVisSetDM_Internal(PetscViewer, PetscObject); PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscViewerGLVisGetDM_Internal(PetscViewer, PetscObject *); PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscViewerGLVisInitWindow_Internal(PetscViewer, PetscBool, PetscInt, const char *); PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscViewerGLVisGetStatus_Internal(PetscViewer, PetscViewerGLVisStatus *); PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscViewerGLVisGetType_Internal(PetscViewer, PetscViewerGLVisType *); PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscViewerGLVisGetWindow_Internal(PetscViewer, PetscInt, PetscViewer *); PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscViewerGLVisRestoreWindow_Internal(PetscViewer, PetscInt, PetscViewer *); PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscViewerGLVisGetFields_Internal(PetscViewer, PetscInt *, const char **[], PetscInt *[], PetscErrorCode (**)(PetscObject, PetscInt, PetscObject[], void *), PetscObject *[], void **); PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscViewerGLVisGetDMWindow_Internal(PetscViewer, PetscViewer *); PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscViewerGLVisRestoreDMWindow_Internal(PetscViewer, PetscViewer *); PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscGLVisCollectiveBegin(MPI_Comm, PetscViewer *); PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscGLVisCollectiveEnd(MPI_Comm, PetscViewer *); #endif
dffd95f37a4639be60ee0403fcddea80f9915b36
8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a
/3rdParty/V8/v7.9.317/third_party/icu/source/i18n/unicode/usearch.h
3a7c311ce953a8464ffbf4eb0113ed5df45185a0
[ "LicenseRef-scancode-unicode", "ICU", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "NAIST-2003", "MIT", "bzip2-1.0.6", "Apache-2.0", "SunPro", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "GPL-2.0-only", "CC0-1.0", "BSL-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "JSON", "Unlicense", "BSD-4-Clause", "Python-2.0", "LGPL-2.1-or-later" ]
permissive
arangodb/arangodb
0980625e76c56a2449d90dcb8d8f2c485e28a83b
43c40535cee37fc7349a21793dc33b1833735af5
refs/heads/devel
2023-08-31T09:34:47.451950
2023-08-31T07:25:02
2023-08-31T07:25:02
2,649,214
13,385
982
Apache-2.0
2023-09-14T17:02:16
2011-10-26T06:42:00
C++
UTF-8
C
false
false
39,038
h
usearch.h
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ********************************************************************** * Copyright (C) 2001-2011,2014 IBM and others. All rights reserved. ********************************************************************** * Date Name Description * 06/28/2001 synwee Creation. ********************************************************************** */ #ifndef USEARCH_H #define USEARCH_H #include "unicode/utypes.h" #if !UCONFIG_NO_COLLATION && !UCONFIG_NO_BREAK_ITERATION #include "unicode/localpointer.h" #include "unicode/ucol.h" #include "unicode/ucoleitr.h" #include "unicode/ubrk.h" /** * \file * \brief C API: StringSearch * * C Apis for an engine that provides language-sensitive text searching based * on the comparison rules defined in a <tt>UCollator</tt> data struct, * see <tt>ucol.h</tt>. This ensures that language eccentricity can be * handled, e.g. for the German collator, characters &szlig; and SS will be matched * if case is chosen to be ignored. * See the <a href="http://source.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm"> * "ICU Collation Design Document"</a> for more information. * <p> * The implementation may use a linear search or a modified form of the Boyer-Moore * search; for more information on the latter see * <a href="http://icu-project.org/docs/papers/efficient_text_searching_in_java.html"> * "Efficient Text Searching in Java"</a>, published in <i>Java Report</i> * in February, 1999. * <p> * There are 2 match options for selection:<br> * Let S' be the sub-string of a text string S between the offsets start and * end <start, end>. * <br> * A pattern string P matches a text string S at the offsets <start, end> * if * <pre> * option 1. Some canonical equivalent of P matches some canonical equivalent * of S' * option 2. P matches S' and if P starts or ends with a combining mark, * there exists no non-ignorable combining mark before or after S' * in S respectively. * </pre> * Option 2. will be the default. * <p> * This search has APIs similar to that of other text iteration mechanisms * such as the break iterators in <tt>ubrk.h</tt>. Using these * APIs, it is easy to scan through text looking for all occurances of * a given pattern. This search iterator allows changing of direction by * calling a <tt>reset</tt> followed by a <tt>next</tt> or <tt>previous</tt>. * Though a direction change can occur without calling <tt>reset</tt> first, * this operation comes with some speed penalty. * Generally, match results in the forward direction will match the result * matches in the backwards direction in the reverse order * <p> * <tt>usearch.h</tt> provides APIs to specify the starting position * within the text string to be searched, e.g. <tt>usearch_setOffset</tt>, * <tt>usearch_preceding</tt> and <tt>usearch_following</tt>. Since the * starting position will be set as it is specified, please take note that * there are some dangerous positions which the search may render incorrect * results: * <ul> * <li> The midst of a substring that requires normalization. * <li> If the following match is to be found, the position should not be the * second character which requires to be swapped with the preceding * character. Vice versa, if the preceding match is to be found, * position to search from should not be the first character which * requires to be swapped with the next character. E.g certain Thai and * Lao characters require swapping. * <li> If a following pattern match is to be found, any position within a * contracting sequence except the first will fail. Vice versa if a * preceding pattern match is to be found, a invalid starting point * would be any character within a contracting sequence except the last. * </ul> * <p> * A breakiterator can be used if only matches at logical breaks are desired. * Using a breakiterator will only give you results that exactly matches the * boundaries given by the breakiterator. For instance the pattern "e" will * not be found in the string "\u00e9" if a character break iterator is used. * <p> * Options are provided to handle overlapping matches. * E.g. In English, overlapping matches produces the result 0 and 2 * for the pattern "abab" in the text "ababab", where else mutually * exclusive matches only produce the result of 0. * <p> * Options are also provided to implement "asymmetric search" as described in * <a href="http://www.unicode.org/reports/tr10/#Asymmetric_Search"> * UTS #10 Unicode Collation Algorithm</a>, specifically the USearchAttribute * USEARCH_ELEMENT_COMPARISON and its values. * <p> * Though collator attributes will be taken into consideration while * performing matches, there are no APIs here for setting and getting the * attributes. These attributes can be set by getting the collator * from <tt>usearch_getCollator</tt> and using the APIs in <tt>ucol.h</tt>. * Lastly to update String Search to the new collator attributes, * usearch_reset() has to be called. * <p> * Restriction: <br> * Currently there are no composite characters that consists of a * character with combining class > 0 before a character with combining * class == 0. However, if such a character exists in the future, the * search mechanism does not guarantee the results for option 1. * * <p> * Example of use:<br> * <pre><code> * char *tgtstr = "The quick brown fox jumped over the lazy fox"; * char *patstr = "fox"; * UChar target[64]; * UChar pattern[16]; * UErrorCode status = U_ZERO_ERROR; * u_uastrcpy(target, tgtstr); * u_uastrcpy(pattern, patstr); * * UStringSearch *search = usearch_open(pattern, -1, target, -1, "en_US", * NULL, &status); * if (U_SUCCESS(status)) { * for (int pos = usearch_first(search, &status); * pos != USEARCH_DONE; * pos = usearch_next(search, &status)) * { * printf("Found match at %d pos, length is %d\n", pos, * usearch_getMatchLength(search)); * } * } * * usearch_close(search); * </code></pre> * @stable ICU 2.4 */ /** * DONE is returned by previous() and next() after all valid matches have * been returned, and by first() and last() if there are no matches at all. * @stable ICU 2.4 */ #define USEARCH_DONE -1 /** * Data structure for searching * @stable ICU 2.4 */ struct UStringSearch; /** * Data structure for searching * @stable ICU 2.4 */ typedef struct UStringSearch UStringSearch; /** * @stable ICU 2.4 */ typedef enum { /** * Option for overlapping matches * @stable ICU 2.4 */ USEARCH_OVERLAP = 0, #ifndef U_HIDE_DEPRECATED_API /** * Option for canonical matches; option 1 in header documentation. * The default value will be USEARCH_OFF. * Note: Setting this option to USEARCH_ON currently has no effect on * search behavior, and this option is deprecated. Instead, to control * canonical match behavior, you must set UCOL_NORMALIZATION_MODE * appropriately (to UCOL_OFF or UCOL_ON) in the UCollator used by * the UStringSearch object. * @see usearch_openFromCollator * @see usearch_getCollator * @see usearch_setCollator * @see ucol_getAttribute * @deprecated ICU 53 */ USEARCH_CANONICAL_MATCH = 1, #endif /* U_HIDE_DEPRECATED_API */ /** * Option to control how collation elements are compared. * The default value will be USEARCH_STANDARD_ELEMENT_COMPARISON. * @stable ICU 4.4 */ USEARCH_ELEMENT_COMPARISON = 2, #ifndef U_HIDE_DEPRECATED_API /** * One more than the highest normal USearchAttribute value. * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. */ USEARCH_ATTRIBUTE_COUNT = 3 #endif /* U_HIDE_DEPRECATED_API */ } USearchAttribute; /** * @stable ICU 2.4 */ typedef enum { /** * Default value for any USearchAttribute * @stable ICU 2.4 */ USEARCH_DEFAULT = -1, /** * Value for USEARCH_OVERLAP and USEARCH_CANONICAL_MATCH * @stable ICU 2.4 */ USEARCH_OFF, /** * Value for USEARCH_OVERLAP and USEARCH_CANONICAL_MATCH * @stable ICU 2.4 */ USEARCH_ON, /** * Value (default) for USEARCH_ELEMENT_COMPARISON; * standard collation element comparison at the specified collator * strength. * @stable ICU 4.4 */ USEARCH_STANDARD_ELEMENT_COMPARISON, /** * Value for USEARCH_ELEMENT_COMPARISON; * collation element comparison is modified to effectively provide * behavior between the specified strength and strength - 1. Collation * elements in the pattern that have the base weight for the specified * strength are treated as "wildcards" that match an element with any * other weight at that collation level in the searched text. For * example, with a secondary-strength English collator, a plain 'e' in * the pattern will match a plain e or an e with any diacritic in the * searched text, but an e with diacritic in the pattern will only * match an e with the same diacritic in the searched text. * * This supports "asymmetric search" as described in * <a href="http://www.unicode.org/reports/tr10/#Asymmetric_Search"> * UTS #10 Unicode Collation Algorithm</a>. * * @stable ICU 4.4 */ USEARCH_PATTERN_BASE_WEIGHT_IS_WILDCARD, /** * Value for USEARCH_ELEMENT_COMPARISON. * collation element comparison is modified to effectively provide * behavior between the specified strength and strength - 1. Collation * elements in either the pattern or the searched text that have the * base weight for the specified strength are treated as "wildcards" * that match an element with any other weight at that collation level. * For example, with a secondary-strength English collator, a plain 'e' * in the pattern will match a plain e or an e with any diacritic in the * searched text, but an e with diacritic in the pattern will only * match an e with the same diacritic or a plain e in the searched text. * * This option is similar to "asymmetric search" as described in * [UTS #10 Unicode Collation Algorithm](http://www.unicode.org/reports/tr10/#Asymmetric_Search), * but also allows unmarked characters in the searched text to match * marked or unmarked versions of that character in the pattern. * * @stable ICU 4.4 */ USEARCH_ANY_BASE_WEIGHT_IS_WILDCARD, #ifndef U_HIDE_DEPRECATED_API /** * One more than the highest normal USearchAttributeValue value. * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. */ USEARCH_ATTRIBUTE_VALUE_COUNT #endif /* U_HIDE_DEPRECATED_API */ } USearchAttributeValue; /* open and close ------------------------------------------------------ */ /** * Creating a search iterator data struct using the argument locale language * rule set. A collator will be created in the process, which will be owned by * this search and will be deleted in <tt>usearch_close</tt>. * @param pattern for matching * @param patternlength length of the pattern, -1 for null-termination * @param text text string * @param textlength length of the text string, -1 for null-termination * @param locale name of locale for the rules to be used * @param breakiter A BreakIterator that will be used to restrict the points * at which matches are detected. If a match is found, but * the match's start or end index is not a boundary as * determined by the <tt>BreakIterator</tt>, the match will * be rejected and another will be searched for. * If this parameter is <tt>NULL</tt>, no break detection is * attempted. * @param status for errors if it occurs. If pattern or text is NULL, or if * patternlength or textlength is 0 then an * U_ILLEGAL_ARGUMENT_ERROR is returned. * @return search iterator data structure, or NULL if there is an error. * @stable ICU 2.4 */ U_STABLE UStringSearch * U_EXPORT2 usearch_open(const UChar *pattern, int32_t patternlength, const UChar *text, int32_t textlength, const char *locale, UBreakIterator *breakiter, UErrorCode *status); /** * Creating a search iterator data struct using the argument collator language * rule set. Note, user retains the ownership of this collator, thus the * responsibility of deletion lies with the user. * NOTE: string search cannot be instantiated from a collator that has * collate digits as numbers (CODAN) turned on. * @param pattern for matching * @param patternlength length of the pattern, -1 for null-termination * @param text text string * @param textlength length of the text string, -1 for null-termination * @param collator used for the language rules * @param breakiter A BreakIterator that will be used to restrict the points * at which matches are detected. If a match is found, but * the match's start or end index is not a boundary as * determined by the <tt>BreakIterator</tt>, the match will * be rejected and another will be searched for. * If this parameter is <tt>NULL</tt>, no break detection is * attempted. * @param status for errors if it occurs. If collator, pattern or text is NULL, * or if patternlength or textlength is 0 then an * U_ILLEGAL_ARGUMENT_ERROR is returned. * @return search iterator data structure, or NULL if there is an error. * @stable ICU 2.4 */ U_STABLE UStringSearch * U_EXPORT2 usearch_openFromCollator( const UChar *pattern, int32_t patternlength, const UChar *text, int32_t textlength, const UCollator *collator, UBreakIterator *breakiter, UErrorCode *status); /** * Destroying and cleaning up the search iterator data struct. * If a collator is created in <tt>usearch_open</tt>, it will be destroyed here. * @param searchiter data struct to clean up * @stable ICU 2.4 */ U_STABLE void U_EXPORT2 usearch_close(UStringSearch *searchiter); #if U_SHOW_CPLUSPLUS_API U_NAMESPACE_BEGIN /** * \class LocalUStringSearchPointer * "Smart pointer" class, closes a UStringSearch via usearch_close(). * For most methods see the LocalPointerBase base class. * * @see LocalPointerBase * @see LocalPointer * @stable ICU 4.4 */ U_DEFINE_LOCAL_OPEN_POINTER(LocalUStringSearchPointer, UStringSearch, usearch_close); U_NAMESPACE_END #endif /* get and set methods -------------------------------------------------- */ /** * Sets the current position in the text string which the next search will * start from. Clears previous states. * This method takes the argument index and sets the position in the text * string accordingly without checking if the index is pointing to a * valid starting point to begin searching. * Search positions that may render incorrect results are highlighted in the * header comments * @param strsrch search iterator data struct * @param position position to start next search from. If position is less * than or greater than the text range for searching, * an U_INDEX_OUTOFBOUNDS_ERROR will be returned * @param status error status if any. * @stable ICU 2.4 */ U_STABLE void U_EXPORT2 usearch_setOffset(UStringSearch *strsrch, int32_t position, UErrorCode *status); /** * Return the current index in the string text being searched. * If the iteration has gone past the end of the text (or past the beginning * for a backwards search), <tt>USEARCH_DONE</tt> is returned. * @param strsrch search iterator data struct * @see #USEARCH_DONE * @stable ICU 2.4 */ U_STABLE int32_t U_EXPORT2 usearch_getOffset(const UStringSearch *strsrch); /** * Sets the text searching attributes located in the enum USearchAttribute * with values from the enum USearchAttributeValue. * <tt>USEARCH_DEFAULT</tt> can be used for all attributes for resetting. * @param strsrch search iterator data struct * @param attribute text attribute to be set * @param value text attribute value * @param status for errors if it occurs * @see #usearch_getAttribute * @stable ICU 2.4 */ U_STABLE void U_EXPORT2 usearch_setAttribute(UStringSearch *strsrch, USearchAttribute attribute, USearchAttributeValue value, UErrorCode *status); /** * Gets the text searching attributes. * @param strsrch search iterator data struct * @param attribute text attribute to be retrieve * @return text attribute value * @see #usearch_setAttribute * @stable ICU 2.4 */ U_STABLE USearchAttributeValue U_EXPORT2 usearch_getAttribute( const UStringSearch *strsrch, USearchAttribute attribute); /** * Returns the index to the match in the text string that was searched. * This call returns a valid result only after a successful call to * <tt>usearch_first</tt>, <tt>usearch_next</tt>, <tt>usearch_previous</tt>, * or <tt>usearch_last</tt>. * Just after construction, or after a searching method returns * <tt>USEARCH_DONE</tt>, this method will return <tt>USEARCH_DONE</tt>. * <p> * Use <tt>usearch_getMatchedLength</tt> to get the matched string length. * @param strsrch search iterator data struct * @return index to a substring within the text string that is being * searched. * @see #usearch_first * @see #usearch_next * @see #usearch_previous * @see #usearch_last * @see #USEARCH_DONE * @stable ICU 2.4 */ U_STABLE int32_t U_EXPORT2 usearch_getMatchedStart( const UStringSearch *strsrch); /** * Returns the length of text in the string which matches the search pattern. * This call returns a valid result only after a successful call to * <tt>usearch_first</tt>, <tt>usearch_next</tt>, <tt>usearch_previous</tt>, * or <tt>usearch_last</tt>. * Just after construction, or after a searching method returns * <tt>USEARCH_DONE</tt>, this method will return 0. * @param strsrch search iterator data struct * @return The length of the match in the string text, or 0 if there is no * match currently. * @see #usearch_first * @see #usearch_next * @see #usearch_previous * @see #usearch_last * @see #USEARCH_DONE * @stable ICU 2.4 */ U_STABLE int32_t U_EXPORT2 usearch_getMatchedLength( const UStringSearch *strsrch); /** * Returns the text that was matched by the most recent call to * <tt>usearch_first</tt>, <tt>usearch_next</tt>, <tt>usearch_previous</tt>, * or <tt>usearch_last</tt>. * If the iterator is not pointing at a valid match (e.g. just after * construction or after <tt>USEARCH_DONE</tt> has been returned, returns * an empty string. If result is not large enough to store the matched text, * result will be filled with the partial text and an U_BUFFER_OVERFLOW_ERROR * will be returned in status. result will be null-terminated whenever * possible. If the buffer fits the matched text exactly, a null-termination * is not possible, then a U_STRING_NOT_TERMINATED_ERROR set in status. * Pre-flighting can be either done with length = 0 or the API * <tt>usearch_getMatchLength</tt>. * @param strsrch search iterator data struct * @param result UChar buffer to store the matched string * @param resultCapacity length of the result buffer * @param status error returned if result is not large enough * @return exact length of the matched text, not counting the null-termination * @see #usearch_first * @see #usearch_next * @see #usearch_previous * @see #usearch_last * @see #USEARCH_DONE * @stable ICU 2.4 */ U_STABLE int32_t U_EXPORT2 usearch_getMatchedText(const UStringSearch *strsrch, UChar *result, int32_t resultCapacity, UErrorCode *status); #if !UCONFIG_NO_BREAK_ITERATION /** * Set the BreakIterator that will be used to restrict the points at which * matches are detected. * @param strsrch search iterator data struct * @param breakiter A BreakIterator that will be used to restrict the points * at which matches are detected. If a match is found, but * the match's start or end index is not a boundary as * determined by the <tt>BreakIterator</tt>, the match will * be rejected and another will be searched for. * If this parameter is <tt>NULL</tt>, no break detection is * attempted. * @param status for errors if it occurs * @see #usearch_getBreakIterator * @stable ICU 2.4 */ U_STABLE void U_EXPORT2 usearch_setBreakIterator(UStringSearch *strsrch, UBreakIterator *breakiter, UErrorCode *status); /** * Returns the BreakIterator that is used to restrict the points at which * matches are detected. This will be the same object that was passed to the * constructor or to <tt>usearch_setBreakIterator</tt>. Note that * <tt>NULL</tt> * is a legal value; it means that break detection should not be attempted. * @param strsrch search iterator data struct * @return break iterator used * @see #usearch_setBreakIterator * @stable ICU 2.4 */ U_STABLE const UBreakIterator * U_EXPORT2 usearch_getBreakIterator( const UStringSearch *strsrch); #endif /** * Set the string text to be searched. Text iteration will hence begin at the * start of the text string. This method is useful if you want to re-use an * iterator to search for the same pattern within a different body of text. * @param strsrch search iterator data struct * @param text new string to look for match * @param textlength length of the new string, -1 for null-termination * @param status for errors if it occurs. If text is NULL, or textlength is 0 * then an U_ILLEGAL_ARGUMENT_ERROR is returned with no change * done to strsrch. * @see #usearch_getText * @stable ICU 2.4 */ U_STABLE void U_EXPORT2 usearch_setText( UStringSearch *strsrch, const UChar *text, int32_t textlength, UErrorCode *status); /** * Return the string text to be searched. * @param strsrch search iterator data struct * @param length returned string text length * @return string text * @see #usearch_setText * @stable ICU 2.4 */ U_STABLE const UChar * U_EXPORT2 usearch_getText(const UStringSearch *strsrch, int32_t *length); /** * Gets the collator used for the language rules. * <p> * Deleting the returned <tt>UCollator</tt> before calling * <tt>usearch_close</tt> would cause the string search to fail. * <tt>usearch_close</tt> will delete the collator if this search owns it. * @param strsrch search iterator data struct * @return collator * @stable ICU 2.4 */ U_STABLE UCollator * U_EXPORT2 usearch_getCollator( const UStringSearch *strsrch); /** * Sets the collator used for the language rules. User retains the ownership * of this collator, thus the responsibility of deletion lies with the user. * This method causes internal data such as Boyer-Moore shift tables to * be recalculated, but the iterator's position is unchanged. * @param strsrch search iterator data struct * @param collator to be used * @param status for errors if it occurs * @stable ICU 2.4 */ U_STABLE void U_EXPORT2 usearch_setCollator( UStringSearch *strsrch, const UCollator *collator, UErrorCode *status); /** * Sets the pattern used for matching. * Internal data like the Boyer Moore table will be recalculated, but the * iterator's position is unchanged. * @param strsrch search iterator data struct * @param pattern string * @param patternlength pattern length, -1 for null-terminated string * @param status for errors if it occurs. If text is NULL, or textlength is 0 * then an U_ILLEGAL_ARGUMENT_ERROR is returned with no change * done to strsrch. * @stable ICU 2.4 */ U_STABLE void U_EXPORT2 usearch_setPattern( UStringSearch *strsrch, const UChar *pattern, int32_t patternlength, UErrorCode *status); /** * Gets the search pattern * @param strsrch search iterator data struct * @param length return length of the pattern, -1 indicates that the pattern * is null-terminated * @return pattern string * @stable ICU 2.4 */ U_STABLE const UChar * U_EXPORT2 usearch_getPattern( const UStringSearch *strsrch, int32_t *length); /* methods ------------------------------------------------------------- */ /** * Returns the first index at which the string text matches the search * pattern. * The iterator is adjusted so that its current index (as returned by * <tt>usearch_getOffset</tt>) is the match position if one was found. * If a match is not found, <tt>USEARCH_DONE</tt> will be returned and * the iterator will be adjusted to the index <tt>USEARCH_DONE</tt>. * @param strsrch search iterator data struct * @param status for errors if it occurs * @return The character index of the first match, or * <tt>USEARCH_DONE</tt> if there are no matches. * @see #usearch_getOffset * @see #USEARCH_DONE * @stable ICU 2.4 */ U_STABLE int32_t U_EXPORT2 usearch_first(UStringSearch *strsrch, UErrorCode *status); /** * Returns the first index equal or greater than <tt>position</tt> at which * the string text * matches the search pattern. The iterator is adjusted so that its current * index (as returned by <tt>usearch_getOffset</tt>) is the match position if * one was found. * If a match is not found, <tt>USEARCH_DONE</tt> will be returned and * the iterator will be adjusted to the index <tt>USEARCH_DONE</tt> * <p> * Search positions that may render incorrect results are highlighted in the * header comments. If position is less than or greater than the text range * for searching, an U_INDEX_OUTOFBOUNDS_ERROR will be returned * @param strsrch search iterator data struct * @param position to start the search at * @param status for errors if it occurs * @return The character index of the first match following <tt>pos</tt>, * or <tt>USEARCH_DONE</tt> if there are no matches. * @see #usearch_getOffset * @see #USEARCH_DONE * @stable ICU 2.4 */ U_STABLE int32_t U_EXPORT2 usearch_following(UStringSearch *strsrch, int32_t position, UErrorCode *status); /** * Returns the last index in the target text at which it matches the search * pattern. The iterator is adjusted so that its current * index (as returned by <tt>usearch_getOffset</tt>) is the match position if * one was found. * If a match is not found, <tt>USEARCH_DONE</tt> will be returned and * the iterator will be adjusted to the index <tt>USEARCH_DONE</tt>. * @param strsrch search iterator data struct * @param status for errors if it occurs * @return The index of the first match, or <tt>USEARCH_DONE</tt> if there * are no matches. * @see #usearch_getOffset * @see #USEARCH_DONE * @stable ICU 2.4 */ U_STABLE int32_t U_EXPORT2 usearch_last(UStringSearch *strsrch, UErrorCode *status); /** * Returns the first index less than <tt>position</tt> at which the string text * matches the search pattern. The iterator is adjusted so that its current * index (as returned by <tt>usearch_getOffset</tt>) is the match position if * one was found. * If a match is not found, <tt>USEARCH_DONE</tt> will be returned and * the iterator will be adjusted to the index <tt>USEARCH_DONE</tt> * <p> * Search positions that may render incorrect results are highlighted in the * header comments. If position is less than or greater than the text range * for searching, an U_INDEX_OUTOFBOUNDS_ERROR will be returned. * <p> * When <tt>USEARCH_OVERLAP</tt> option is off, the last index of the * result match is always less than <tt>position</tt>. * When <tt>USERARCH_OVERLAP</tt> is on, the result match may span across * <tt>position</tt>. * @param strsrch search iterator data struct * @param position index position the search is to begin at * @param status for errors if it occurs * @return The character index of the first match preceding <tt>pos</tt>, * or <tt>USEARCH_DONE</tt> if there are no matches. * @see #usearch_getOffset * @see #USEARCH_DONE * @stable ICU 2.4 */ U_STABLE int32_t U_EXPORT2 usearch_preceding(UStringSearch *strsrch, int32_t position, UErrorCode *status); /** * Returns the index of the next point at which the string text matches the * search pattern, starting from the current position. * The iterator is adjusted so that its current * index (as returned by <tt>usearch_getOffset</tt>) is the match position if * one was found. * If a match is not found, <tt>USEARCH_DONE</tt> will be returned and * the iterator will be adjusted to the index <tt>USEARCH_DONE</tt> * @param strsrch search iterator data struct * @param status for errors if it occurs * @return The index of the next match after the current position, or * <tt>USEARCH_DONE</tt> if there are no more matches. * @see #usearch_first * @see #usearch_getOffset * @see #USEARCH_DONE * @stable ICU 2.4 */ U_STABLE int32_t U_EXPORT2 usearch_next(UStringSearch *strsrch, UErrorCode *status); /** * Returns the index of the previous point at which the string text matches * the search pattern, starting at the current position. * The iterator is adjusted so that its current * index (as returned by <tt>usearch_getOffset</tt>) is the match position if * one was found. * If a match is not found, <tt>USEARCH_DONE</tt> will be returned and * the iterator will be adjusted to the index <tt>USEARCH_DONE</tt> * @param strsrch search iterator data struct * @param status for errors if it occurs * @return The index of the previous match before the current position, * or <tt>USEARCH_DONE</tt> if there are no more matches. * @see #usearch_last * @see #usearch_getOffset * @see #USEARCH_DONE * @stable ICU 2.4 */ U_STABLE int32_t U_EXPORT2 usearch_previous(UStringSearch *strsrch, UErrorCode *status); /** * Reset the iteration. * Search will begin at the start of the text string if a forward iteration * is initiated before a backwards iteration. Otherwise if a backwards * iteration is initiated before a forwards iteration, the search will begin * at the end of the text string. * @param strsrch search iterator data struct * @see #usearch_first * @stable ICU 2.4 */ U_STABLE void U_EXPORT2 usearch_reset(UStringSearch *strsrch); #ifndef U_HIDE_INTERNAL_API /** * Simple forward search for the pattern, starting at a specified index, * and using using a default set search options. * * This is an experimental function, and is not an official part of the * ICU API. * * The collator options, such as UCOL_STRENGTH and UCOL_NORMALIZTION, are honored. * * The UStringSearch options USEARCH_CANONICAL_MATCH, USEARCH_OVERLAP and * any Break Iterator are ignored. * * Matches obey the following constraints: * * Characters at the start or end positions of a match that are ignorable * for collation are not included as part of the match, unless they * are part of a combining sequence, as described below. * * A match will not include a partial combining sequence. Combining * character sequences are considered to be inseperable units, * and either match the pattern completely, or are considered to not match * at all. Thus, for example, an A followed a combining accent mark will * not be found when searching for a plain (unaccented) A. (unless * the collation strength has been set to ignore all accents). * * When beginning a search, the initial starting position, startIdx, * is assumed to be an acceptable match boundary with respect to * combining characters. A combining sequence that spans across the * starting point will not supress a match beginning at startIdx. * * Characters that expand to multiple collation elements * (German sharp-S becoming 'ss', or the composed forms of accented * characters, for example) also must match completely. * Searching for a single 's' in a string containing only a sharp-s will * find no match. * * * @param strsrch the UStringSearch struct, which references both * the text to be searched and the pattern being sought. * @param startIdx The index into the text to begin the search. * @param matchStart An out parameter, the starting index of the matched text. * This parameter may be NULL. * A value of -1 will be returned if no match was found. * @param matchLimit Out parameter, the index of the first position following the matched text. * The matchLimit will be at a suitable position for beginning a subsequent search * in the input text. * This parameter may be NULL. * A value of -1 will be returned if no match was found. * * @param status Report any errors. Note that no match found is not an error. * @return TRUE if a match was found, FALSE otherwise. * * @internal */ U_INTERNAL UBool U_EXPORT2 usearch_search(UStringSearch *strsrch, int32_t startIdx, int32_t *matchStart, int32_t *matchLimit, UErrorCode *status); /** * Simple backwards search for the pattern, starting at a specified index, * and using using a default set search options. * * This is an experimental function, and is not an official part of the * ICU API. * * The collator options, such as UCOL_STRENGTH and UCOL_NORMALIZTION, are honored. * * The UStringSearch options USEARCH_CANONICAL_MATCH, USEARCH_OVERLAP and * any Break Iterator are ignored. * * Matches obey the following constraints: * * Characters at the start or end positions of a match that are ignorable * for collation are not included as part of the match, unless they * are part of a combining sequence, as described below. * * A match will not include a partial combining sequence. Combining * character sequences are considered to be inseperable units, * and either match the pattern completely, or are considered to not match * at all. Thus, for example, an A followed a combining accent mark will * not be found when searching for a plain (unaccented) A. (unless * the collation strength has been set to ignore all accents). * * When beginning a search, the initial starting position, startIdx, * is assumed to be an acceptable match boundary with respect to * combining characters. A combining sequence that spans across the * starting point will not supress a match beginning at startIdx. * * Characters that expand to multiple collation elements * (German sharp-S becoming 'ss', or the composed forms of accented * characters, for example) also must match completely. * Searching for a single 's' in a string containing only a sharp-s will * find no match. * * * @param strsrch the UStringSearch struct, which references both * the text to be searched and the pattern being sought. * @param startIdx The index into the text to begin the search. * @param matchStart An out parameter, the starting index of the matched text. * This parameter may be NULL. * A value of -1 will be returned if no match was found. * @param matchLimit Out parameter, the index of the first position following the matched text. * The matchLimit will be at a suitable position for beginning a subsequent search * in the input text. * This parameter may be NULL. * A value of -1 will be returned if no match was found. * * @param status Report any errors. Note that no match found is not an error. * @return TRUE if a match was found, FALSE otherwise. * * @internal */ U_INTERNAL UBool U_EXPORT2 usearch_searchBackwards(UStringSearch *strsrch, int32_t startIdx, int32_t *matchStart, int32_t *matchLimit, UErrorCode *status); #endif /* U_HIDE_INTERNAL_API */ #endif /* #if !UCONFIG_NO_COLLATION && !UCONFIG_NO_BREAK_ITERATION */ #endif
92c158b003976d6cb78e2e49cad3212fe5ec1d6d
bb157fd805d63dc4cb6d6bfb7cd120f519bc17c1
/src/libserver/fuzzy_backend/fuzzy_backend_sqlite.h
766f7c9d2e2def6db6381489b6acb09549a5a8c3
[ "Apache-2.0" ]
permissive
rspamd/rspamd
faffd25f1c084400839589e576a911db1d7d6089
c4e54b4daa77bee29862a00900bede165ea16b52
refs/heads/master
2023-08-30T23:40:52.860552
2023-08-29T18:20:25
2023-08-29T18:20:25
9,549,081
1,039
291
NOASSERTION
2023-09-13T10:17:46
2013-04-19T16:00:18
C
UTF-8
C
false
false
2,976
h
fuzzy_backend_sqlite.h
/*- * Copyright 2016 Vsevolod Stakhov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FUZZY_BACKEND_H_ #define FUZZY_BACKEND_H_ #include "config.h" #include "fuzzy_wire.h" #ifdef __cplusplus extern "C" { #endif struct rspamd_fuzzy_backend_sqlite; /** * Open fuzzy backend * @param path file to open (legacy file will be converted automatically) * @param err error pointer * @return backend structure or NULL */ struct rspamd_fuzzy_backend_sqlite *rspamd_fuzzy_backend_sqlite_open(const gchar *path, gboolean vacuum, GError **err); /** * Check specified fuzzy in the backend * @param backend * @param cmd * @return reply with probability and weight */ struct rspamd_fuzzy_reply rspamd_fuzzy_backend_sqlite_check( struct rspamd_fuzzy_backend_sqlite *backend, const struct rspamd_fuzzy_cmd *cmd, gint64 expire); /** * Prepare storage for updates (by starting transaction) */ gboolean rspamd_fuzzy_backend_sqlite_prepare_update(struct rspamd_fuzzy_backend_sqlite *backend, const gchar *source); /** * Add digest to the database * @param backend * @param cmd * @return */ gboolean rspamd_fuzzy_backend_sqlite_add(struct rspamd_fuzzy_backend_sqlite *backend, const struct rspamd_fuzzy_cmd *cmd); /** * Delete digest from the database * @param backend * @param cmd * @return */ gboolean rspamd_fuzzy_backend_sqlite_del( struct rspamd_fuzzy_backend_sqlite *backend, const struct rspamd_fuzzy_cmd *cmd); /** * Commit updates to storage */ gboolean rspamd_fuzzy_backend_sqlite_finish_update(struct rspamd_fuzzy_backend_sqlite *backend, const gchar *source, gboolean version_bump); /** * Sync storage * @param backend * @return */ gboolean rspamd_fuzzy_backend_sqlite_sync(struct rspamd_fuzzy_backend_sqlite *backend, gint64 expire, gboolean clean_orphaned); /** * Close storage * @param backend */ void rspamd_fuzzy_backend_sqlite_close(struct rspamd_fuzzy_backend_sqlite *backend); gsize rspamd_fuzzy_backend_sqlite_count(struct rspamd_fuzzy_backend_sqlite *backend); gint rspamd_fuzzy_backend_sqlite_version(struct rspamd_fuzzy_backend_sqlite *backend, const gchar *source); gsize rspamd_fuzzy_backend_sqlite_expired(struct rspamd_fuzzy_backend_sqlite *backend); const gchar *rspamd_fuzzy_sqlite_backend_id(struct rspamd_fuzzy_backend_sqlite *backend); #ifdef __cplusplus } #endif #endif /* FUZZY_BACKEND_H_ */
c725a09a34c0e60eaa3a6085f17a802bf9bb6d37
b0f08154e3eebc7d8465efc57597e52d08d69c18
/src/broker/cas_function.h
8ff5dd92f0951f589eb293f28d9781dd89db6cf4
[ "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
CUBRID/cubrid
8f71a0010243b72e43ba887d229210650f4e901e
3b952af33230839a1b561a78ecd4b773374b66f8
refs/heads/develop
2023-08-18T19:16:30.987583
2023-08-18T08:18:05
2023-08-18T08:18:05
52,080,367
287
294
NOASSERTION
2023-09-14T21:29:09
2016-02-19T10:25:32
C
UTF-8
C
false
false
6,876
h
cas_function.h
/* * Copyright 2008 Search Solution Corporation * Copyright 2016 CUBRID 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. * */ /* * cas_function.h - */ #ifndef _CAS_FUNCTION_H_ #define _CAS_FUNCTION_H_ #ident "$Id$" #include "cas_net_buf.h" typedef enum { FN_KEEP_CONN = 0, FN_CLOSE_CONN = -1, FN_KEEP_SESS = -2, FN_GRACEFUL_DOWN = -3 } FN_RETURN; typedef FN_RETURN (*T_SERVER_FUNC) (SOCKET, int, void **, T_NET_BUF *, T_REQ_INFO *); extern FN_RETURN fn_end_tran (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); #if !defined(CAS_FOR_ORACLE) && !defined(CAS_FOR_MYSQL) && !defined(CAS_FOR_CGW) extern FN_RETURN fn_end_session (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_get_row_count (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_get_last_insert_id (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); #endif /* !CAS_FOR_ORACLE && !CAS_FOR_MYSQL && !CAS_FOR_CGW */ extern FN_RETURN fn_prepare (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_execute (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); #if !defined(CAS_FOR_ORACLE) && !defined(CAS_FOR_MYSQL) && !defined(CAS_FOR_CGW) extern FN_RETURN fn_get_db_parameter (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_set_db_parameter (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_set_cas_change_mode (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); #endif /* !CAS_FOR_ORACLE && !CAS_FOR_MYSQL && !CAS_FOR_CGW */ extern FN_RETURN fn_close_req_handle (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_cursor (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_fetch (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); #if !defined(CAS_FOR_ORACLE) && !defined(CAS_FOR_MYSQL) && !defined(CAS_FOR_CGW) extern FN_RETURN fn_schema_info (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); #endif /* !CAS_FOR_ORACLE && !CAS_FOR_MYSQL && !CAS_FOR_CGW */ extern FN_RETURN fn_get_db_version (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_next_result (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_execute_batch (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_execute_array (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_get_attr_type_str (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_xa_prepare (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_xa_recover (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_xa_end_tran (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_con_close (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_check_cas (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_make_out_rs (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_get_generated_keys (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); #if !defined(CAS_FOR_ORACLE) && !defined(CAS_FOR_MYSQL) && !defined(CAS_FOR_CGW) extern FN_RETURN fn_oid_get (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_oid_put (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_get_class_num_objs (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_oid (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_collection (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); #endif /* !CAS_FOR_ORACLE && !CAS_FOR_MYSQL && !CAS_FOR_CGW */ #if !defined(CAS_FOR_ORACLE) && !defined(CAS_FOR_MYSQL) extern FN_RETURN fn_cursor_close (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); #endif /* !CAS_FOR_ORACLE && !CAS_FOR_MYSQL */ extern FN_RETURN fn_cursor_update (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_get_query_info (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); #if !defined(CAS_FOR_ORACLE) && !defined(CAS_FOR_MYSQL) && !defined(CAS_FOR_CGW) extern FN_RETURN fn_savepoint (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_parameter_info (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); #endif /* !CAS_FOR_ORACLE && !CAS_FOR_MYSQL && !CAS_FOR_CGW */ extern FN_RETURN fn_not_supported (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); #if !defined(CAS_FOR_ORACLE) && !defined(CAS_FOR_MYSQL) && !defined(CAS_FOR_CGW) extern FN_RETURN fn_lob_new (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_lob_write (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_lob_read (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_deprecated (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); extern FN_RETURN fn_prepare_and_execute (SOCKET sock_fd, int argc, void **argv, T_NET_BUF * net_buf, T_REQ_INFO * req_info); #endif /* !CAS_FOR_ORACLE && !CAS_FOR_MYSQL && !CAS_FOR_CGW */ #endif /* _CAS_FUNCTION_H_ */
8bc1f00635ffb721b70b7f71992ec5b1fa686f02
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/mips/oprofile/backtrace.c
83a1dfd8f0e3c34d02cbe24448f5c5407852f942
[ "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
4,534
c
backtrace.c
#include <linux/oprofile.h> #include <linux/sched.h> #include <linux/mm.h> #include <linux/uaccess.h> #include <asm/ptrace.h> #include <asm/stacktrace.h> #include <linux/stacktrace.h> #include <linux/kernel.h> #include <asm/sections.h> #include <asm/inst.h> struct stackframe { unsigned long sp; unsigned long pc; unsigned long ra; }; static inline int get_mem(unsigned long addr, unsigned long *result) { unsigned long *address = (unsigned long *) addr; if (!access_ok(VERIFY_READ, addr, sizeof(unsigned long))) return -1; if (__copy_from_user_inatomic(result, address, sizeof(unsigned long))) return -3; return 0; } /* * These two instruction helpers were taken from process.c */ static inline int is_ra_save_ins(union mips_instruction *ip) { /* sw / sd $ra, offset($sp) */ return (ip->i_format.opcode == sw_op || ip->i_format.opcode == sd_op) && ip->i_format.rs == 29 && ip->i_format.rt == 31; } static inline int is_sp_move_ins(union mips_instruction *ip) { /* addiu/daddiu sp,sp,-imm */ if (ip->i_format.rs != 29 || ip->i_format.rt != 29) return 0; if (ip->i_format.opcode == addiu_op || ip->i_format.opcode == daddiu_op) return 1; return 0; } /* * Looks for specific instructions that mark the end of a function. * This usually means we ran into the code area of the previous function. */ static inline int is_end_of_function_marker(union mips_instruction *ip) { /* jr ra */ if (ip->r_format.func == jr_op && ip->r_format.rs == 31) return 1; /* lui gp */ if (ip->i_format.opcode == lui_op && ip->i_format.rt == 28) return 1; return 0; } /* * TODO for userspace stack unwinding: * - handle cases where the stack is adjusted inside a function * (generally doesn't happen) * - find optimal value for max_instr_check * - try to find a way to handle leaf functions */ static inline int unwind_user_frame(struct stackframe *old_frame, const unsigned int max_instr_check) { struct stackframe new_frame = *old_frame; off_t ra_offset = 0; size_t stack_size = 0; unsigned long addr; if (old_frame->pc == 0 || old_frame->sp == 0 || old_frame->ra == 0) return -9; for (addr = new_frame.pc; (addr + max_instr_check > new_frame.pc) && (!ra_offset || !stack_size); --addr) { union mips_instruction ip; if (get_mem(addr, (unsigned long *) &ip)) return -11; if (is_sp_move_ins(&ip)) { int stack_adjustment = ip.i_format.simmediate; if (stack_adjustment > 0) /* This marks the end of the previous function, which means we overran. */ break; stack_size = (unsigned long) stack_adjustment; } else if (is_ra_save_ins(&ip)) { int ra_slot = ip.i_format.simmediate; if (ra_slot < 0) /* This shouldn't happen. */ break; ra_offset = ra_slot; } else if (is_end_of_function_marker(&ip)) break; } if (!ra_offset || !stack_size) return -1; if (ra_offset) { new_frame.ra = old_frame->sp + ra_offset; if (get_mem(new_frame.ra, &(new_frame.ra))) return -13; } if (stack_size) { new_frame.sp = old_frame->sp + stack_size; if (get_mem(new_frame.sp, &(new_frame.sp))) return -14; } if (new_frame.sp > old_frame->sp) return -2; new_frame.pc = old_frame->ra; *old_frame = new_frame; return 0; } static inline void do_user_backtrace(unsigned long low_addr, struct stackframe *frame, unsigned int depth) { const unsigned int max_instr_check = 512; const unsigned long high_addr = low_addr + THREAD_SIZE; while (depth-- && !unwind_user_frame(frame, max_instr_check)) { oprofile_add_trace(frame->ra); if (frame->sp < low_addr || frame->sp > high_addr) break; } } #ifndef CONFIG_KALLSYMS static inline void do_kernel_backtrace(unsigned long low_addr, struct stackframe *frame, unsigned int depth) { } #else static inline void do_kernel_backtrace(unsigned long low_addr, struct stackframe *frame, unsigned int depth) { while (depth-- && frame->pc) { frame->pc = unwind_stack_by_address(low_addr, &(frame->sp), frame->pc, &(frame->ra)); oprofile_add_trace(frame->ra); } } #endif void notrace op_mips_backtrace(struct pt_regs *const regs, unsigned int depth) { struct stackframe frame = { .sp = regs->regs[29], .pc = regs->cp0_epc, .ra = regs->regs[31] }; const int userspace = user_mode(regs); const unsigned long low_addr = ALIGN(frame.sp, THREAD_SIZE); if (userspace) do_user_backtrace(low_addr, &frame, depth); else do_kernel_backtrace(low_addr, &frame, depth); }
acc90d3461ad244d1868f899895af66d1ea92d53
7f6c235b0598353549959c18f69eefd20b766907
/support/p2000/stripcas.c
c7ecc6c1c1ae8fd36d6760ccca6ade4a7df79ef1
[ "ClArtistic" ]
permissive
z88dk/z88dk
46dfd4905f36d99333173cadd0a660839befc9f0
8b07f37cc43c5d9ffe69b563c80763491d8faff7
refs/heads/master
2023-09-04T19:29:49.254958
2023-09-03T20:51:24
2023-09-03T20:51:24
54,035,569
820
263
NOASSERTION
2023-09-05T11:09:04
2016-03-16T13:48:16
Assembly
UTF-8
C
false
false
1,305
c
stripcas.c
/* * Philips P2000 emulator CASsette format strip tool * * Usage: stripcas [casfile] [dstfile] * * Stefano Bodrato, Apr 2014 * * * $Id: stripcas.c,v 1.1 2014-04-16 20:21:40 stefano Exp $ */ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *fpin, *fpout; int c; int i; int tmp, count, found; if (argc != 3) { fprintf(stdout,"Usage: %s [CAS file] [dst BIN file]\n",argv[0]); exit(1); } if ( (fpin=fopen(argv[1],"rb") ) == NULL ) { printf("Can't open input file\n"); exit(1); } if ( (fpout=fopen(argv[2],"wb") ) == NULL ) { printf("Can't open output file\n"); exit(1); } i=0; count=1; found=0; while (((c=getc(fpin)) != EOF) && (count >0)) { if (i==0x36) printf(" %u Program name: ",count); if ((i>=0x36)&&(i<0x41)) printf("%c",c); if (i==0x3d) printf(" ."); if (i==0x41) printf("\n"); if ((i==0x32)||(i==0x34)||(i==0x1A)||(i==0x42)) tmp=c; if ((i==0x33)||(i==0x35)||(i==0x1B)||(i==0x43) { if (!found && ((c*256+tmp)!=0)) { count=c*256+tmp; found = 1; } printf("Sz@%x:%u\n",i-1,c*256+tmp); } if (i==0x4f) printf("Block countdown order number:%u\n",c); if (i>0xff) { fputc(c,fpout); count--; } if (++i >= 0x500) i=0; } fclose(fpin); fclose(fpout); }
c5af4ab1b9ae7a9e57309d5219f021845bfcaa16
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/microchip/same70/bsp/same70b/include/instance/supc.h
845066b653a9a67b4c8e09a3f3c512aa265b87e0
[ "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
2,590
h
supc.h
/** * \file * * \brief Instance description for SUPC * * Copyright (c) 2019 Microchip Technology Inc. * * \license_start * * \page License * * 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 * * 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. * * \license_stop * */ /* file generated from device description version 2019-01-18T21:19:59Z */ #ifndef _SAME70_SUPC_INSTANCE_H_ #define _SAME70_SUPC_INSTANCE_H_ /* ========== Register definition for SUPC peripheral ========== */ #if (defined(__ASSEMBLER__) || defined(__IAR_SYSTEMS_ASM__)) #define REG_SUPC_CR (0x400E1810) /**< (SUPC) Supply Controller Control Register */ #define REG_SUPC_SMMR (0x400E1814) /**< (SUPC) Supply Controller Supply Monitor Mode Register */ #define REG_SUPC_MR (0x400E1818) /**< (SUPC) Supply Controller Mode Register */ #define REG_SUPC_WUMR (0x400E181C) /**< (SUPC) Supply Controller Wake-up Mode Register */ #define REG_SUPC_WUIR (0x400E1820) /**< (SUPC) Supply Controller Wake-up Inputs Register */ #define REG_SUPC_SR (0x400E1824) /**< (SUPC) Supply Controller Status Register */ #else #define REG_SUPC_CR (*(__O uint32_t*)0x400E1810U) /**< (SUPC) Supply Controller Control Register */ #define REG_SUPC_SMMR (*(__IO uint32_t*)0x400E1814U) /**< (SUPC) Supply Controller Supply Monitor Mode Register */ #define REG_SUPC_MR (*(__IO uint32_t*)0x400E1818U) /**< (SUPC) Supply Controller Mode Register */ #define REG_SUPC_WUMR (*(__IO uint32_t*)0x400E181CU) /**< (SUPC) Supply Controller Wake-up Mode Register */ #define REG_SUPC_WUIR (*(__IO uint32_t*)0x400E1820U) /**< (SUPC) Supply Controller Wake-up Inputs Register */ #define REG_SUPC_SR (*(__I uint32_t*)0x400E1824U) /**< (SUPC) Supply Controller Status Register */ #endif /* (defined(__ASSEMBLER__) || defined(__IAR_SYSTEMS_ASM__)) */ /* ========== Instance Parameter definitions for SUPC peripheral ========== */ #define SUPC_INSTANCE_ID 0 #endif /* _SAME70_SUPC_INSTANCE_ */
a8bc7cb4240088c764d01827f82af935d73c536d
971b2cea2d1c3001aadc8ca1a48110b7db1ed5f2
/deps/abc/src/map/mpm/mpmPre.c
a1462342a81eb668e43ca5e1f933de14938459dd
[ "MIT-Modern-Variant", "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
emsec/hal
70ad2921739967d914dd458984bd7d6d497d3b0a
e4fae37bec9168a61100eacfda37a1f291b4d0be
refs/heads/master
2023-09-02T20:27:32.909426
2023-09-01T13:03:24
2023-09-01T13:03:24
169,076,171
510
72
MIT
2023-09-01T13:03:26
2019-02-04T12:37:20
C++
UTF-8
C
false
false
33,785
c
mpmPre.c
/**CFile**************************************************************** FileName [mpmPre.c] SystemName [ABC: Logic synthesis and verification system.] PackageName [Configurable technology mapper.] Synopsis [DSD-related precomputations.] Author [Alan Mishchenko] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - June 1, 2013.] Revision [$Id: mpmPre.c,v 1.00 2013/06/01 00:00:00 alanmi Exp $] ***********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "misc/vec/vec.h" #include "misc/vec/vecHsh.h" #include "misc/extra/extra.h" #include "bool/kit/kit.h" #include "misc/util/utilTruth.h" ABC_NAMESPACE_IMPL_START //////////////////////////////////////////////////////////////////////// /// DECLARATIONS /// //////////////////////////////////////////////////////////////////////// typedef struct Ifd_Obj_t_ Ifd_Obj_t; struct Ifd_Obj_t_ { unsigned nFreq : 18; // frequency unsigned nAnds : 6; // number of AND gates unsigned nSupp : 5; // support size unsigned Type : 2; // type unsigned fWay : 1; // transparent edge unsigned pFans[3]; // fanins }; typedef struct Ifd_Man_t_ Ifd_Man_t; struct Ifd_Man_t_ { Ifd_Obj_t * pObjs; int nObjs; int nObjsAlloc; // hashing operations Vec_Int_t * vArgs; // iDsd1 op iDsdC Vec_Int_t * vRes; // result of operation Hsh_IntMan_t * vHash; // hash table Vec_Int_t * vMarks; // marks where given N begins Vec_Wrd_t * vTruths; // truth tables Vec_Int_t * vClauses; // truth tables // other data Vec_Int_t * vSuper; }; static inline int Ifd_ObjIsVar( Ifd_Obj_t * p ) { return p->Type == 0; } static inline int Ifd_ObjIsAnd( Ifd_Obj_t * p ) { return p->Type == 1; } static inline int Ifd_ObjIsXor( Ifd_Obj_t * p ) { return p->Type == 2; } static inline int Ifd_ObjIsMux( Ifd_Obj_t * p ) { return p->Type == 3; } static inline Ifd_Obj_t * Ifd_ManObj( Ifd_Man_t * p, int i ) { assert( i >= 0 && i < p->nObjs ); return p->pObjs + i; } static inline Ifd_Obj_t * Ifd_ManObjFromLit( Ifd_Man_t * p, int iLit ) { return Ifd_ManObj( p, Abc_Lit2Var(iLit) ); } static inline int Ifd_ObjId( Ifd_Man_t * p, Ifd_Obj_t * pObj ) { assert( pObj - p->pObjs >= 0 && pObj - p->pObjs < p->nObjs ); return pObj - p->pObjs; } static inline int Ifd_LitSuppSize( Ifd_Man_t * p, int iLit ) { return iLit > 0 ? Ifd_ManObjFromLit(p, iLit)->nSupp : 0; } static inline int Ifd_LitNumAnds( Ifd_Man_t * p, int iLit ) { return iLit > 0 ? Ifd_ManObjFromLit(p, iLit)->nAnds : 0; } #define Ifd_ManForEachNodeWithSupp( p, nVars, pLeaf, i ) \ for ( i = Vec_IntEntry(p->vMarks, nVars); (i < Vec_IntEntry(p->vMarks, nVars+1)) && (pLeaf = Ifd_ManObj(p, i)); i++ ) //////////////////////////////////////////////////////////////////////// /// FUNCTION DEFINITIONS /// //////////////////////////////////////////////////////////////////////// /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Ifd_Man_t * Ifd_ManStart() { Ifd_Man_t * p; p = ABC_CALLOC( Ifd_Man_t, 1 ); p->nObjsAlloc = Abc_PrimeCudd( 50000000 ); p->nObjs = 2; p->pObjs = ABC_CALLOC( Ifd_Obj_t, p->nObjsAlloc ); memset( p->pObjs, 0xFF, sizeof(Ifd_Obj_t) ); // const node (p->pObjs + 1)->nSupp = 1; // variable (p->pObjs + 1)->fWay = 1; // variable // hashing operations p->vArgs = Vec_IntAlloc( 4000 ); p->vRes = Vec_IntAlloc( 1000 ); p->vHash = Hsh_IntManStart( p->vArgs, 4, 1000 ); p->vMarks = Vec_IntAlloc( 100 ); Vec_IntPush( p->vMarks, 0 ); Vec_IntPush( p->vMarks, 1 ); Vec_IntPush( p->vMarks, p->nObjs ); // other data p->vSuper = Vec_IntAlloc( 1000 ); p->vTruths = Vec_WrdAlloc( 1000 ); p->vClauses = Vec_IntAlloc( 1000 ); return p; } void Ifd_ManStop( Ifd_Man_t * p ) { int i, This, Prev = 0; Vec_IntForEachEntryStart( p->vMarks, This, i, 1 ) { printf( "%d(%d:%d) ", i-1, This, This - Prev ); Prev = This; } printf( "\n" ); Vec_IntFreeP( &p->vArgs ); Vec_IntFreeP( &p->vRes ); Vec_WrdFreeP( &p->vTruths ); Vec_IntFreeP( &p->vClauses ); Vec_IntFreeP( &p->vMarks ); Hsh_IntManStop( p->vHash ); Vec_IntFreeP( &p->vSuper ); ABC_FREE( p->pObjs ); ABC_FREE( p ); } /**Function************************************************************* Synopsis [Printing structures.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Ifd_ObjPrint_rec( Ifd_Man_t * p, int iLit, int * pCounter, int DiffType ) { char Symb[2][4] = { {'?','(','[','<'}, {'?',')',']','>'} }; Ifd_Obj_t * pDsd; if ( Abc_LitIsCompl(iLit) ) printf( "!" ), iLit = Abc_LitNot(iLit); if ( iLit == 2 ) { printf( "%c", 'a' + (*pCounter)++ ); return; } pDsd = Ifd_ManObjFromLit( p, iLit ); if ( DiffType ) printf( "%c", Symb[0][pDsd->Type] ); Ifd_ObjPrint_rec( p, pDsd->pFans[0], pCounter, pDsd->Type == 3 || Abc_LitIsCompl(pDsd->pFans[0]) || pDsd->Type != Ifd_ManObjFromLit(p, pDsd->pFans[0])->Type ); Ifd_ObjPrint_rec( p, pDsd->pFans[1], pCounter, pDsd->Type == 3 || Abc_LitIsCompl(pDsd->pFans[1]) || pDsd->Type != Ifd_ManObjFromLit(p, pDsd->pFans[1])->Type ); if ( pDsd->pFans[2] != -1 ) Ifd_ObjPrint_rec( p, pDsd->pFans[2], pCounter, pDsd->Type == 3 || Abc_LitIsCompl(pDsd->pFans[2]) || pDsd->Type != Ifd_ManObjFromLit(p, pDsd->pFans[2])->Type ); if ( DiffType ) printf( "%c", Symb[1][pDsd->Type] ); } void Ifd_ObjPrint( Ifd_Man_t * p, int iLit ) { int Counter = 0; if ( iLit == 0 ) { printf( "0" ); return; } if ( iLit == 1 ) { printf( "1" ); return; } Ifd_ObjPrint_rec( p, iLit, &Counter, 1 ); } void Ifd_ManPrint2( Ifd_Man_t * p ) { int i; for ( i = 0; i < p->nObjs; i++ ) { printf( "%4d : ", i ); Ifd_ObjPrint( p, Abc_Var2Lit( i, 0 ) ); printf( "\n" ); } } void Ifd_ManPrint( Ifd_Man_t * p ) { int i; for ( i = 0; i < p->nObjs; i++ ) { word Fun = Vec_WrdEntry( p->vTruths, i ); printf( " { " ); printf( "%d, ", Extra_TruthSupportSize((unsigned *)&Fun, 6) ); printf( "%2d, ", Ifd_LitNumAnds(p, Abc_Var2Lit(i, 0)) ); printf( "%2d, ", Vec_IntEntry(p->vClauses, i) ); printf( "ABC_CONST(" ); Extra_PrintHex( stdout, (unsigned *)&Fun, 6 ); printf( "), \"" ); Ifd_ObjPrint( p, Abc_Var2Lit( i, 0 ) ); printf( "\" }, // %4d \n", i ); } } /**Function************************************************************* Synopsis [Computing truth tables.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ word Ifd_ObjTruth_rec( Ifd_Man_t * p, int iLit, int * pCounter ) { static word s_Truths6[6] = { ABC_CONST(0xAAAAAAAAAAAAAAAA), ABC_CONST(0xCCCCCCCCCCCCCCCC), ABC_CONST(0xF0F0F0F0F0F0F0F0), ABC_CONST(0xFF00FF00FF00FF00), ABC_CONST(0xFFFF0000FFFF0000), ABC_CONST(0xFFFFFFFF00000000) }; Ifd_Obj_t * pDsd; word Fun0, Fun1, Fun2 = 0; assert( !Abc_LitIsCompl(iLit) ); if ( iLit == 2 ) return s_Truths6[(*pCounter)++]; pDsd = Ifd_ManObjFromLit( p, iLit ); Fun0 = Ifd_ObjTruth_rec( p, Abc_LitRegular(pDsd->pFans[0]), pCounter ); Fun1 = Ifd_ObjTruth_rec( p, Abc_LitRegular(pDsd->pFans[1]), pCounter ); if ( pDsd->pFans[2] != -1 ) Fun2 = Ifd_ObjTruth_rec( p, Abc_LitRegular(pDsd->pFans[2]), pCounter ); Fun0 = Abc_LitIsCompl(pDsd->pFans[0]) ? ~Fun0 : Fun0; Fun1 = Abc_LitIsCompl(pDsd->pFans[1]) ? ~Fun1 : Fun1; if ( pDsd->pFans[2] != -1 ) Fun2 = Abc_LitIsCompl(pDsd->pFans[2]) ? ~Fun2 : Fun2; if ( pDsd->Type == 1 ) return Fun0 & Fun1; if ( pDsd->Type == 2 ) return Fun0 ^ Fun1; if ( pDsd->Type == 3 ) return (Fun2 & Fun1) | (~Fun2 & Fun0); assert( 0 ); return -1; } word Ifd_ObjTruth( Ifd_Man_t * p, int iLit ) { word Fun; int Counter = 0; if ( iLit == 0 ) return 0; if ( iLit == 1 ) return ~(word)0; Fun = Ifd_ObjTruth_rec( p, Abc_LitRegular(iLit), &Counter ); return Abc_LitIsCompl(iLit) ? ~Fun : Fun; } void Ifd_ManTruthAll( Ifd_Man_t * p ) { word Fun; int i; assert( Vec_WrdSize(p->vTruths) == 0 ); for ( i = 0; i < p->nObjs; i++ ) { Fun = Ifd_ObjTruth( p, Abc_Var2Lit( i, 0 ) ); Vec_WrdPush( p->vTruths, Fun ); // Extra_PrintHex( stdout, (unsigned *)&Fun, 6 ); printf( " " ); // Kit_DsdPrintFromTruth( (unsigned *)&Fun, 6 ); printf( "\n" ); } } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Mpm_ComputeCnfSizeOne( word Truth, int nVars, Vec_Int_t * vCover, Vec_Str_t * vCnf ) { Vec_StrClear( vCnf ); if ( Truth == 0 || ~Truth == 0 ) { // assert( nVars == 0 ); Vec_StrPush( vCnf, (char)(Truth == 0) ); Vec_StrPush( vCnf, (char)-1 ); return 1; } else { int i, k, c, RetValue, Literal, Cube, nCubes = 0; assert( nVars > 0 ); for ( c = 0; c < 2; c ++ ) { Truth = c ? ~Truth : Truth; RetValue = Kit_TruthIsop( (unsigned *)&Truth, nVars, vCover, 0 ); assert( RetValue == 0 ); nCubes += Vec_IntSize( vCover ); Vec_IntForEachEntry( vCover, Cube, i ) { for ( k = 0; k < nVars; k++ ) { Literal = 3 & (Cube >> (k << 1)); if ( Literal == 1 ) // '0' -> pos lit Vec_StrPush( vCnf, (char)Abc_Var2Lit(k, 0) ); else if ( Literal == 2 ) // '1' -> neg lit Vec_StrPush( vCnf, (char)Abc_Var2Lit(k, 1) ); else if ( Literal != 0 ) assert( 0 ); } Vec_StrPush( vCnf, (char)Abc_Var2Lit(nVars, c) ); Vec_StrPush( vCnf, (char)-1 ); } } return nCubes; } } void Mpm_ComputeCnfSizeAll( Ifd_Man_t * p ) { Vec_Int_t * vCover = Vec_IntAlloc( 1 << 16 ); Vec_Str_t * vCnf = Vec_StrAlloc( 1000 ); word Truth; int i; assert( Vec_IntSize(p->vClauses) == 0 ); Vec_WrdForEachEntry( p->vTruths, Truth, i ) Vec_IntPush( p->vClauses, Mpm_ComputeCnfSizeOne(Truth, 6, vCover, vCnf) ); Vec_IntFree( vCover ); Vec_StrFree( vCnf ); } /**Function************************************************************* Synopsis [Canonicizing DSD structures.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Ifd_ManHashLookup( Ifd_Man_t * p, int iDsd0, int iDsd1, int iDsdC, int Type ) { int pData[4]; assert( iDsdC != -1 || iDsd0 >= iDsd1 ); assert( iDsdC == -1 || !Abc_LitIsCompl(iDsd1) ); pData[0] = iDsd0; pData[1] = iDsd1; pData[2] = iDsdC; pData[3] = Type; return *Hsh_IntManLookup( p->vHash, (unsigned *)pData ); } void Ifd_ManHashInsert( Ifd_Man_t * p, int iDsd0, int iDsd1, int iDsdC, int Type, int Res ) { int iObj; assert( iDsdC != -1 || iDsd0 >= iDsd1 ); assert( iDsdC == -1 || !Abc_LitIsCompl(iDsd1) ); Vec_IntPush( p->vArgs, iDsd0 ); Vec_IntPush( p->vArgs, iDsd1 ); Vec_IntPush( p->vArgs, iDsdC ); Vec_IntPush( p->vArgs, Type ); iObj = Hsh_IntManAdd( p->vHash, Vec_IntSize(p->vRes) ); assert( iObj == Vec_IntSize(p->vRes) ); Vec_IntPush( p->vRes, Res ); assert( 4 * Vec_IntSize(p->vRes) == Vec_IntSize(p->vArgs) ); } int Ifd_ManHashFindOrAdd( Ifd_Man_t * p, int iDsd0, int iDsd1, int iDsdC, int Type ) { Ifd_Obj_t * pObj; int iObj, Value; assert( iDsdC != -1 || iDsd0 >= iDsd1 ); assert( iDsdC == -1 || !Abc_LitIsCompl(iDsd1) ); Vec_IntPush( p->vArgs, iDsd0 ); Vec_IntPush( p->vArgs, iDsd1 ); Vec_IntPush( p->vArgs, iDsdC ); Vec_IntPush( p->vArgs, Type ); Value = Hsh_IntManAdd( p->vHash, Vec_IntSize(p->vRes) ); if ( Value < Vec_IntSize(p->vRes) ) { iObj = Vec_IntEntry(p->vRes, Value); Vec_IntShrink( p->vArgs, Vec_IntSize(p->vArgs) - 4 ); pObj = Ifd_ManObj( p, iObj ); // pObj->nFreq++; assert( (int)pObj->Type == Type ); assert( (int)pObj->nSupp == Ifd_LitSuppSize(p, iDsd0) + Ifd_LitSuppSize(p, iDsd1) + Ifd_LitSuppSize(p, iDsdC) ); } else { if ( p->nObjs == p->nObjsAlloc ) printf( "The number of nodes is more than %d\n", p->nObjs ); assert( p->nObjs < p->nObjsAlloc ); iObj = p->nObjs; pObj = Ifd_ManObj( p, p->nObjs++ ); // pObj->nFreq = 1; pObj->nSupp = Ifd_LitSuppSize(p, iDsd0) + Ifd_LitSuppSize(p, iDsd1) + Ifd_LitSuppSize(p, iDsdC); pObj->nAnds = Ifd_LitNumAnds(p, iDsd0) + Ifd_LitNumAnds(p, iDsd1) + Ifd_LitNumAnds(p, iDsdC) + ((Type == 1) ? 1 : 3); pObj->Type = Type; if ( Type == 1 ) pObj->fWay = 0; else if ( Type == 2 ) pObj->fWay = Ifd_ManObjFromLit(p, iDsd0)->fWay || Ifd_ManObjFromLit(p, iDsd1)->fWay; else if ( Type == 3 ) // pObj->fWay = (Ifd_ManObjFromLit(p, iDsd0)->fWay && Ifd_ManObjFromLit(p, iDsd1)->fWay) || (Abc_Lit2Var(iDsd0) == Abc_Lit2Var(iDsd1) && Ifd_ManObjFromLit(p, iDsdC)->fWay); pObj->fWay = (Ifd_ManObjFromLit(p, iDsd0)->fWay && Ifd_ManObjFromLit(p, iDsd1)->fWay) || (iDsd0 == Abc_LitNot(iDsd1) && Ifd_ManObjFromLit(p, iDsdC)->fWay); else assert( 0 ); pObj->pFans[0] = iDsd0; pObj->pFans[1] = iDsd1; pObj->pFans[2] = iDsdC; Vec_IntPush( p->vRes, iObj ); } assert( 4 * Vec_IntSize(p->vRes) == Vec_IntSize(p->vArgs) ); return iObj; } void Ifd_ManOperSuper_rec( Ifd_Man_t * p, int iLit, int Type, Vec_Int_t * vObjs ) { Ifd_Obj_t * pDsd = Ifd_ManObjFromLit( p, iLit ); if ( Abc_LitIsCompl(iLit) || (int)pDsd->Type != Type ) Vec_IntPush( vObjs, iLit ); else { Ifd_ManOperSuper_rec( p, pDsd->pFans[0], Type, vObjs ); Ifd_ManOperSuper_rec( p, pDsd->pFans[1], Type, vObjs ); } } int Ifd_ManOper( Ifd_Man_t * p, int iDsd0, int iDsd1, int iDsdC, int Type ) { int i, iLit0, iLit1, iThis, fCompl = 0; if ( Type == 1 ) // AND { if ( iDsd0 == 0 || iDsd1 == 0 ) return 0; if ( iDsd0 == 1 || iDsd1 == 1 ) return (iDsd0 == 1) ? iDsd1 : iDsd0; } else if ( Type == 2 ) // XOR { if ( iDsd0 < 2 ) return Abc_LitNotCond( iDsd1, iDsd0 ); if ( iDsd1 < 2 ) return Abc_LitNotCond( iDsd0, iDsd1 ); if ( Abc_LitIsCompl(iDsd0) ) fCompl ^= 1, iDsd0 = Abc_LitNot(iDsd0); if ( Abc_LitIsCompl(iDsd1) ) fCompl ^= 1, iDsd1 = Abc_LitNot(iDsd1); } else if ( Type == 3 ) { if ( Abc_LitIsCompl(iDsdC) ) { ABC_SWAP( int, iDsd0, iDsd1 ); iDsdC = Abc_LitNot(iDsdC); } if ( Abc_LitIsCompl(iDsd1) ) fCompl ^= 1, iDsd0 = Abc_LitNot(iDsd0), iDsd1 = Abc_LitNot(iDsd1); } assert( iDsd0 > 1 && iDsd1 > 1 && Type >= 1 && Type <= 3 ); /* // check cache iThis = Ifd_ManHashLookup( p, iDsd0, iDsd1, iDsdC, Type ); if ( iThis != -1 ) return Abc_Var2Lit( iThis, fCompl ); */ // create new entry if ( Type == 3 ) { iThis = Ifd_ManHashFindOrAdd( p, iDsd0, iDsd1, iDsdC, Type ); return Abc_Var2Lit( iThis, fCompl ); } assert( iDsdC == -1 ); Vec_IntClear( p->vSuper ); Ifd_ManOperSuper_rec( p, iDsd0, Type, p->vSuper ); Ifd_ManOperSuper_rec( p, iDsd1, Type, p->vSuper ); Vec_IntSort( p->vSuper, 1 ); iLit0 = Vec_IntEntry( p->vSuper, 0 ); Vec_IntForEachEntryStart( p->vSuper, iLit1, i, 1 ) iLit0 = Abc_Var2Lit( Ifd_ManHashFindOrAdd(p, iLit0, iLit1, -1, Type), 0 ); assert( !Abc_LitIsCompl(iLit0) ); // insert into cache // if ( Vec_IntSize(p->vSuper) > 2 ) // Ifd_ManHashInsert( p, iDsd0, iDsd1, iDsdC, Type, iLit0 ); return Abc_LitNotCond( iLit0, fCompl ); } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Ifd_ManFindDsd_rec( Ifd_Man_t * pMan, char * pStr, char ** p, int * pMatches ) { int fCompl = 0; if ( **p == '!' ) (*p)++, fCompl = 1; if ( **p >= 'a' && **p <= 'f' ) // var { assert( **p - 'a' >= 0 && **p - 'a' < 6 ); return Abc_Var2Lit( 1, fCompl ); } if ( **p == '(' ) // and/or { char * q = pStr + pMatches[ *p - pStr ]; int Lit, Res = 1; assert( **p == '(' && *q == ')' ); for ( (*p)++; *p < q; (*p)++ ) { Lit = Ifd_ManFindDsd_rec( pMan, pStr, p, pMatches ); Res = Ifd_ManOper( pMan, Res, Lit, 0, 1 ); } assert( *p == q ); return Abc_LitNotCond( Res, fCompl ); } if ( **p == '[' ) // xor { char * q = pStr + pMatches[ *p - pStr ]; int Lit, Res = 0; assert( **p == '[' && *q == ']' ); for ( (*p)++; *p < q; (*p)++ ) { Lit = Ifd_ManFindDsd_rec( pMan, pStr, p, pMatches ); Res = Ifd_ManOper( pMan, Res, Lit, 0, 2 ); } assert( *p == q ); return Abc_LitNotCond( Res, fCompl ); } if ( **p == '<' ) // mux { int Temp[3], * pTemp = Temp, Res; char * q = pStr + pMatches[ *p - pStr ]; assert( **p == '<' && *q == '>' ); // derive MAX components for ( (*p)++; *p < q; (*p)++ ) *pTemp++ = Ifd_ManFindDsd_rec( pMan, pStr, p, pMatches ); assert( pTemp == Temp + 3 ); assert( *p == q ); // Res = (Temp[0] & Temp[1]) | (~Temp[0] & Temp[2]); Res = Ifd_ManOper( pMan, Temp[2], Temp[1], Temp[0], 3 ); return Abc_LitNotCond( Res, fCompl ); } assert( 0 ); return 0; } #define IFM_MAX_STR 100 #define IFM_MAX_VAR 16 int * Ifd_ManComputeMatches( char * p ) { static int pMatches[IFM_MAX_STR]; int pNested[IFM_MAX_VAR]; int v, nNested = 0; for ( v = 0; p[v]; v++ ) { assert( v < IFM_MAX_STR ); pMatches[v] = 0; if ( p[v] == '(' || p[v] == '[' || p[v] == '<' || p[v] == '{' ) pNested[nNested++] = v; else if ( p[v] == ')' || p[v] == ']' || p[v] == '>' || p[v] == '}' ) pMatches[pNested[--nNested]] = v; assert( nNested < IFM_MAX_VAR ); } assert( nNested == 0 ); return pMatches; } int Ifd_ManFindDsd( Ifd_Man_t * pMan, char * p ) { int Res; if ( *p == '0' && *(p+1) == 0 ) Res = 0; else if ( *p == '1' && *(p+1) == 0 ) Res = 1; else Res = Ifd_ManFindDsd_rec( pMan, p, &p, Ifd_ManComputeMatches(p) ); assert( *++p == 0 ); return Res; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Ifd_ManDsdTest2() { char * p = "(abc)"; // char * q = "(a[bc])"; // char * r = "[<abc>(def)]"; Ifd_Man_t * pMan = Ifd_ManStart(); int iLit = Ifd_ManFindDsd( pMan, p ); Ifd_ObjPrint( pMan, iLit ); Ifd_ManStop( pMan ); printf( "\n" ); } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Vec_Wrd_t * Ifd_ManDsdTruths( int nVars ) { int fUseMux = 1; Vec_Wrd_t * vTruths; Ifd_Man_t * pMan = Ifd_ManStart(); Ifd_Obj_t * pLeaf0, * pLeaf1, * pLeaf2; int v, i, j, k, c0, c1, c2; for ( v = 2; v <= nVars; v++ ) { // create ANDs/XORs for ( i = 1; i < v; i++ ) for ( j = 1; j < v; j++ ) if ( i + j == v ) { Ifd_ManForEachNodeWithSupp( pMan, i, pLeaf0, c0 ) Ifd_ManForEachNodeWithSupp( pMan, j, pLeaf1, c1 ) { assert( (int)pLeaf0->nSupp == i ); assert( (int)pLeaf1->nSupp == j ); Ifd_ManOper( pMan, Abc_Var2Lit(c0, 0), Abc_Var2Lit(c1, 0), -1, 1 ); if ( !pLeaf1->fWay ) Ifd_ManOper( pMan, Abc_Var2Lit(c0, 0), Abc_Var2Lit(c1, 1), -1, 1 ); if ( !pLeaf0->fWay ) Ifd_ManOper( pMan, Abc_Var2Lit(c0, 1), Abc_Var2Lit(c1, 0), -1, 1 ); if ( !pLeaf0->fWay && !pLeaf1->fWay ) Ifd_ManOper( pMan, Abc_Var2Lit(c0, 1), Abc_Var2Lit(c1, 1), -1, 1 ); Ifd_ManOper( pMan, Abc_Var2Lit(c0, 0), Abc_Var2Lit(c1, 0), -1, 2 ); } } // create MUX if ( fUseMux ) for ( i = 1; i < v-1; i++ ) for ( j = 1; j < v-1; j++ ) for ( k = 1; k < v-1; k++ ) if ( i + j + k == v ) { Ifd_ManForEachNodeWithSupp( pMan, i, pLeaf0, c0 ) Ifd_ManForEachNodeWithSupp( pMan, j, pLeaf1, c1 ) Ifd_ManForEachNodeWithSupp( pMan, k, pLeaf2, c2 ) { assert( (int)pLeaf0->nSupp == i ); assert( (int)pLeaf1->nSupp == j ); assert( (int)pLeaf2->nSupp == k ); //printf( "%d %d %d ", i, j, k ); //printf( "%d %d %d\n", Ifd_ObjId(pMan, pLeaf0), Ifd_ObjId(pMan, pLeaf1), Ifd_ObjId(pMan, pLeaf2) ); if ( pLeaf2->fWay && c0 < c1 ) continue; Ifd_ManOper( pMan, Abc_Var2Lit(c0, 0), Abc_Var2Lit(c1, 0), Abc_Var2Lit(c2, 0), 3 ); if ( !pLeaf0->fWay && !pLeaf1->fWay ) Ifd_ManOper( pMan, Abc_Var2Lit(c0, 1), Abc_Var2Lit(c1, 0), Abc_Var2Lit(c2, 0), 3 ); } } // bookmark Vec_IntPush( pMan->vMarks, pMan->nObjs ); } Ifd_ManTruthAll( pMan ); Mpm_ComputeCnfSizeAll( pMan ); // Ifd_ManPrint( pMan ); vTruths = pMan->vTruths; pMan->vTruths = NULL; Ifd_ManStop( pMan ); return vTruths; } /**Function************************************************************* Synopsis [Generating the guided array for minimal permutations.] Description [http://icodesnip.com/search/johnson%20trotter/] SideEffects [] SeeAlso [] ***********************************************************************/ void Ifd_ManDsdPermPrint( int * perm, int size ) { int i; for ( i = 0; i < size; i++ ) printf( "%d", perm[i] ); printf( "\n" ); } Vec_Int_t * Ifd_ManDsdPermJT( int n ) { Vec_Int_t * vGuide = Vec_IntAlloc( 100 ); int *array, *dir, tmp, tmp2, i, max; array = (int*)malloc(sizeof(int) * n); dir = (int*)calloc(n, sizeof(int)); for (i = 0; i < n; i++) array[i] = i; max = n - 1; if (n != 1) do { // Ifd_ManDsdPermPrint(array, n); tmp = array[max]; tmp2 = dir[max]; i = !dir[max] ? max - 1 : max + 1; array[max] = array[i]; array[i] = tmp; Vec_IntPush( vGuide, Abc_MinInt(max, i) ); dir[max] = dir[i]; dir[i] = tmp2; for (i = 0; i < n; i++) if (array[i] > tmp) dir[i] = !dir[i]; max = n; for (i = 0; i < n; i++) if (((!dir[i] && i != 0 && array[i] > array[i-1]) || (dir[i] && i != n-1 && array[i] > array[i+1])) && (array[i] > array[max] || max == n)) max = i; } while (max < n); // Ifd_ManDsdPermPrint(array,n); Vec_IntPush( vGuide, 0 ); free(dir); free(array); return vGuide; } int Ifd_ManDsdTest4() { int pPerm[6] = { 0, 1, 2, 3, 4, 5 }; Vec_Int_t * vGuide = Ifd_ManDsdPermJT( 6 ); int i, Entry; Vec_IntForEachEntry( vGuide, Entry, i ) { ABC_SWAP( int, pPerm[Entry], pPerm[Entry+1] ); Ifd_ManDsdPermPrint( pPerm, 6 ); } Vec_IntFree( vGuide ); return 1; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ static inline word Extra_Truth6SwapAdjacent( word t, int iVar ) { // variable swapping code static word PMasks[5][3] = { { ABC_CONST(0x9999999999999999), ABC_CONST(0x2222222222222222), ABC_CONST(0x4444444444444444) }, { ABC_CONST(0xC3C3C3C3C3C3C3C3), ABC_CONST(0x0C0C0C0C0C0C0C0C), ABC_CONST(0x3030303030303030) }, { ABC_CONST(0xF00FF00FF00FF00F), ABC_CONST(0x00F000F000F000F0), ABC_CONST(0x0F000F000F000F00) }, { ABC_CONST(0xFF0000FFFF0000FF), ABC_CONST(0x0000FF000000FF00), ABC_CONST(0x00FF000000FF0000) }, { ABC_CONST(0xFFFF00000000FFFF), ABC_CONST(0x00000000FFFF0000), ABC_CONST(0x0000FFFF00000000) } }; assert( iVar < 5 ); return (t & PMasks[iVar][0]) | ((t & PMasks[iVar][1]) << (1 << iVar)) | ((t & PMasks[iVar][2]) >> (1 << iVar)); } static inline word Extra_Truth6ChangePhase( word t, int iVar) { // elementary truth tables static word Truth6[6] = { ABC_CONST(0xAAAAAAAAAAAAAAAA), ABC_CONST(0xCCCCCCCCCCCCCCCC), ABC_CONST(0xF0F0F0F0F0F0F0F0), ABC_CONST(0xFF00FF00FF00FF00), ABC_CONST(0xFFFF0000FFFF0000), ABC_CONST(0xFFFFFFFF00000000) }; assert( iVar < 6 ); return ((t & ~Truth6[iVar]) << (1 << iVar)) | ((t & Truth6[iVar]) >> (1 << iVar)); } Vec_Wrd_t * Extra_Truth6AllConfigs2( word t, int * pComp, int * pPerm, int nVars ) { int nPerms = Extra_Factorial( nVars ); int nSwaps = (1 << nVars); Vec_Wrd_t * vTruths = Vec_WrdStart( nPerms * (1 << (nVars+1)) ); word tCur, tTemp1, tTemp2; int i, p, c; for ( i = 0; i < 2; i++ ) { tCur = i ? t : ~t; tTemp1 = tCur; for ( p = 0; p < nPerms; p++ ) { tTemp2 = tCur; for ( c = 0; c < nSwaps; c++ ) { Vec_WrdWriteEntry( vTruths, (p << (nVars+1))|(i << nVars)|c, tCur ); tCur = Extra_Truth6ChangePhase( tCur, pComp[c] ); } assert( tTemp2 == tCur ); tCur = Extra_Truth6SwapAdjacent( tCur, pPerm[p] ); } assert( tTemp1 == tCur ); } if ( t ) { int i; word Truth; Vec_WrdForEachEntry( vTruths, Truth, i ) assert( Truth ); } return vTruths; } Vec_Wrd_t * Extra_Truth6AllConfigs( word t, int * pComp, int * pPerm, int nVars ) { int nPerms = Extra_Factorial( nVars ); int nSwaps = (1 << nVars); Vec_Wrd_t * vTruths = Vec_WrdStart( nPerms * nSwaps ); word tCur = t, tTemp1, tTemp2; int p, c, Config; tTemp1 = tCur; for ( p = 0; p < nPerms; p++ ) { tCur = Extra_Truth6SwapAdjacent( tCur, pPerm[p] ); Config = 0; tTemp2 = tCur; for ( c = 0; c < nSwaps; c++ ) { Vec_WrdWriteEntry( vTruths, (p << nVars)|Config, tCur ); tCur = Extra_Truth6ChangePhase( tCur, pComp[c] ); Config ^= (1 << pComp[c]); } assert( Config == 0 ); assert( tTemp2 == tCur ); } assert( tTemp1 == tCur ); if ( t ) { int i; word Truth; Vec_WrdForEachEntry( vTruths, Truth, i ) assert( Truth ); } return vTruths; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Ifd_ComputeSignature( word uTruth, int pCounts[6] ) { int v, Pos, Neg, Xor; for ( v = 0; v < 6; v++ ) { Neg = Abc_TtCountOnes( Abc_Tt6Cofactor0(uTruth, v) ) / 2; Pos = Abc_TtCountOnes( Abc_Tt6Cofactor1(uTruth, v) ) / 2; Xor = Abc_TtCountOnes( Abc_Tt6Cofactor0(uTruth, v) ^ Abc_Tt6Cofactor1(uTruth, v) ) / 2; if ( Pos <= Neg ) pCounts[v] = (Pos << 20) | (Neg << 10) | Xor; else pCounts[v] = (Neg << 20) | (Pos << 10) | Xor; } Vec_IntSelectSort( pCounts, 6 ); } int Ifd_ManDsdTest33() { int nVars = 6; Vec_Wrd_t * vTruths = Ifd_ManDsdTruths( nVars ); int i, v, pCounts[6]; word uTruth; Vec_WrdForEachEntry( vTruths, uTruth, i ) { Ifd_ComputeSignature( uTruth, pCounts ); // print printf( "%5d : ", i ); for ( v = 0; v < 6; v++ ) printf( "%2d %2d %2d ", (pCounts[v] >> 20) & 0xFF, (pCounts[v] >> 10) & 0xFF, (pCounts[v] >> 0) & 0xFF ); printf( " " ); Kit_DsdPrintFromTruth( (unsigned *)&uTruth, nVars ); printf( "\n" ); } Vec_WrdFree( vTruths ); return 1; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Ifd_ManDsdTest() { int nVars = 6; FILE * pFile; char pFileName[32]; Vec_Wrd_t * vTruths = Ifd_ManDsdTruths( nVars ); Vec_Wrd_t * vVariants; Vec_Int_t * vUniques; Vec_Int_t * vCompls; Vec_Wrd_t * vTruthRes = Vec_WrdAlloc( 4000000 ); Vec_Int_t * vConfgRes = Vec_IntAlloc( 4000000 ); int * pComp, * pPerm; word Truth, Variant; int i, k, Uniq, Runner, Counter = 0; assert( nVars >= 3 && nVars <= 6 ); assert( Vec_WrdSize(vTruths) < (1<<10) ); vCompls = Vec_IntAlloc( 720 * 64 ); pComp = Extra_GreyCodeSchedule( nVars ); pPerm = Extra_PermSchedule( nVars ); Vec_WrdForEachEntry( vTruths, Truth, i ) { vVariants = Extra_Truth6AllConfigs( Truth, pComp, pPerm, nVars ); // save compl bits Vec_IntClear( vCompls ); Vec_WrdForEachEntry( vVariants, Variant, k ) { Vec_IntPush( vCompls, (int)(Variant & 1) ); Vec_WrdWriteEntry( vVariants, k, Variant & 1 ? ~Variant : Variant ); } // uniqify vUniques = Hsh_WrdManHashArray( vVariants, 1 ); Runner = 0; Vec_IntForEachEntry( vUniques, Uniq, k ) if ( Runner == Uniq ) { Variant = Vec_WrdEntry(vVariants, k); assert( (Variant & 1) == 0 ); Vec_WrdPush( vTruthRes, Variant ); Vec_IntPush( vConfgRes, (i << 17)|(Vec_IntEntry(vCompls, k) << 16)|k ); Runner++; } Vec_IntUniqify( vUniques ); assert( Runner == Vec_IntSize(vUniques) ); Counter += Vec_IntSize(vUniques); //printf( "%5d : ", i ); Kit_DsdPrintFromTruth( &Truth, nVars ), printf( " " ), Vec_IntPrint( vUniques ), printf( "\n" ); Vec_IntFree( vUniques ); Vec_WrdFree( vVariants ); } Vec_IntFree( vCompls ); Vec_WrdFree( vTruths ); ABC_FREE( pPerm ); ABC_FREE( pComp ); printf( "Total = %d.\n", Counter ); assert( Vec_WrdSize(vTruthRes) == Counter ); // write the data into a file sprintf( pFileName, "dsdfuncs%d.dat", nVars ); pFile = fopen( pFileName, "wb" ); fwrite( Vec_WrdArray(vTruthRes), sizeof(word), Vec_WrdSize(vTruthRes), pFile ); fwrite( Vec_IntArray(vConfgRes), sizeof(int), Vec_IntSize(vConfgRes), pFile ); fclose( pFile ); printf( "File \"%s\" with %d 6-input functions has been written out.\n", pFileName, Vec_IntSize(vConfgRes) ); Vec_WrdFree( vTruthRes ); Vec_IntFree( vConfgRes ); return 1; } int Ifd_ManDsdTest55() { abctime clk = Abc_Clock(); FILE * pFile; char * pFileName = "dsdfuncs6.dat"; int RetValue, size = Extra_FileSize( pFileName ) / 12; // 2866420 Vec_Wrd_t * vTruthRes = Vec_WrdAlloc( size + 1 ); Vec_Int_t * vConfgRes = Vec_IntAlloc( size ); Hsh_IntMan_t * pHash; pFile = fopen( pFileName, "rb" ); RetValue = fread( Vec_WrdArray(vTruthRes), sizeof(word), size, pFile ); RetValue = fread( Vec_IntArray(vConfgRes), sizeof(int), size, pFile ); vTruthRes->nSize = size; vConfgRes->nSize = size; // create hash table pHash = Hsh_WrdManHashArrayStart( vTruthRes, 1 ); // experiment with functions // cleanup Hsh_IntManStop( pHash ); Vec_WrdFree( vTruthRes ); Vec_IntFree( vConfgRes ); Abc_PrintTime( 1, "Reading file", Abc_Clock() - clk ); return 1; } //////////////////////////////////////////////////////////////////////// /// END OF FILE /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_IMPL_END
a84a173bf061c7137620d9573f10c9aed679fb31
3eb3c4046b17e265930aaf89fa93f41896f243cb
/neural_modelling/src/neuron/structural_plasticity/synaptogenesis/sp_structs.h
ec31f79d6c37995c1470def7175fc6b2c198ef8e
[ "Apache-2.0" ]
permissive
SpiNNakerManchester/sPyNNaker
b177613a114cfc7e7687ec36c1f72a2f07f66977
891cfb3046f66185fd8df52d270380fa94c32eab
refs/heads/master
2023-09-01T11:28:21.252266
2023-08-17T08:07:43
2023-08-17T08:07:43
20,801,613
101
53
Apache-2.0
2023-09-14T18:39:29
2014-06-13T11:07:19
Python
UTF-8
C
false
false
11,658
h
sp_structs.h
/* * Copyright (c) 2017 The University of Manchester * * 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 * * https://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. */ //! \dir //! \brief Structural plasticity through formation and elimination of synapses //! \file //! \brief Miscellaneous structures #ifndef _SP_STRUCTS_H_ #define _SP_STRUCTS_H_ #include <neuron/plasticity/synapse_dynamics.h> #include <neuron/synapse_row.h> #include <debug.h> #include <random.h> // Define the formation and elimination params struct elimination_params; struct formation_params; //! Flag: Is connection lateral? #define IS_CONNECTION_LAT 1 #ifndef SOMETIMES_UNUSED #define SOMETIMES_UNUSED __attribute__((unused)) #endif // !SOMETIMES_UNUSED //! Entry of map from post-connection to pre-connection neural indices typedef struct post_to_pre_entry { uint8_t pop_index; uint8_t sub_pop_index; uint16_t neuron_index; } post_to_pre_entry; //! information per atom typedef struct { uint32_t key; uint32_t mask; uint32_t n_colour_bits; uint32_t n_atoms; uint32_t lo_atom; uint32_t m_pop_index; } key_atom_info_t; //! individual pre-synaptic sub-population information typedef struct { uint16_t no_pre_vertices; uint16_t sp_control; uint16_t delay_lo; uint16_t delay_hi; uint32_t weight; uint32_t connection_type; uint32_t total_no_atoms; key_atom_info_t key_atom_info[]; } pre_info_t; //! table of individual pre-synaptic information typedef struct { uint32_t no_pre_pops; pre_info_t **prepop_info; } pre_pop_info_table_t; //! parameters of the synaptic rewiring model typedef struct { uint32_t fast; uint32_t p_rew; uint32_t s_max; uint32_t app_no_atoms; uint32_t machine_no_atoms; uint32_t low_atom; uint32_t high_atom; uint32_t with_replacement; // the 2 seeds that are used: shared for sync, local for everything else mars_kiss64_seed_t shared_seed; mars_kiss64_seed_t local_seed; uint32_t no_pre_pops; } rewiring_data_t; //! struct representing the current state of rewiring typedef struct { //! Seed referenced from rewiring data mars_kiss64_seed_t *local_seed; //! Low atom copied from rewiring data uint32_t post_low_atom; // with_replacement copied from rewiring data uint32_t with_replacement; // what are the currently selecting pre- and post-synaptic neurons uint32_t pre_syn_id; uint32_t post_syn_id; //! does the connection already exist uint32_t element_exists; // information extracted from the post to pre table post_to_pre_entry *post_to_pre_table_entry; pre_info_t *pre_population_info; key_atom_info_t *key_atom_info; post_to_pre_entry post_to_pre; //! offset in synaptic row (if exists) uint32_t offset; //! current delay (if exists) uint16_t delay; //! current weight (if exists) uint16_t weight; //! synapse type uint32_t synapse_type; } current_state_t; //! Get a random unsigned integer up to (but not including) a given maximum //! \param[in] max The maximum value allowed //! \param[in] seed The random seed to use //! \return The generated value static inline uint32_t rand_int(uint32_t max, mars_kiss64_seed_t seed) { return muliulr(max, ulrbits(mars_kiss64_seed(seed))); } //! \brief unpack the spike into key and identifying information for the //! neuron; Identify pop, sub-population and low and high atoms //! \param[in] pre_pop_info_table: The prepopulation information table //! \param[in] spike: The spike to look up the information from //! \param[out] neuron_id: The ID of the neuron within its population //! \param[out] population_id: The population ID //! \param[out] sub_population_id: The ID of the sub-population //! \param[out] m_pop_index: The master population table index //! \return True if the information was found. static inline bool sp_structs_find_by_spike( const pre_pop_info_table_t *pre_pop_info_table, spike_t spike, uint32_t *restrict neuron_id, uint32_t *restrict population_id, uint32_t *restrict sub_population_id, uint32_t *restrict m_pop_index) { // Amazing linear search inc. // Loop over all populations for (uint32_t i = 0; i < pre_pop_info_table->no_pre_pops; i++) { const pre_info_t *pre_pop_info = pre_pop_info_table->prepop_info[i]; // Loop over all sub-populations and check if the KEY matches // (with neuron ID masked out) for (int j = 0; j < pre_pop_info->no_pre_vertices; j++) { const key_atom_info_t *kai = &pre_pop_info->key_atom_info[j]; if ((spike & kai->mask) == kai->key) { *population_id = i; *sub_population_id = j; *neuron_id = (spike & ~kai->mask) >> kai->n_colour_bits; *m_pop_index = kai->m_pop_index; return true; } } } return false; } //! \brief Get the sub-population id and sub-population-based neuron id given //! the population id and the population-based neuron id //! \param[in] pre_pop_info_table: The prepopulation information table //! \param[in] population_id: The population ID //! \param[in] pop_neuron_id: The ID of the neuron within the population //! \param[out] sub_population_id: The ID of the sub-population //! \param[out] sub_pop_neuron_id: //! The ID of the neuron within the sub-population //! \param[out] spike: The spike associated with communication from that neuron //! \return True if the information was found. static inline bool sp_structs_get_sub_pop_info( const pre_pop_info_table_t *pre_pop_info_table, uint32_t population_id, uint32_t pop_neuron_id, uint32_t *restrict sub_population_id, uint32_t *restrict sub_pop_neuron_id, uint32_t *restrict spike) { const pre_info_t *app_pop_info = pre_pop_info_table->prepop_info[population_id]; uint32_t neuron_id = pop_neuron_id; for (uint32_t i = 0; i < app_pop_info->no_pre_vertices; i++) { const key_atom_info_t *kai = &app_pop_info->key_atom_info[i]; uint32_t n_atoms = kai->n_atoms; if (neuron_id < n_atoms) { *sub_population_id = i; *sub_pop_neuron_id = neuron_id; *spike = kai->key | (neuron_id << kai->n_colour_bits); return true; } neuron_id -= n_atoms; } return false; } //! \brief Removes a synapse from the relevant structures //! \param[in,out] current_state: Describes what is to be done //! \param[in,out] row: The row of the synaptic matrix to be updated //! \return True if the synapse was removed static inline bool sp_structs_remove_synapse( current_state_t *restrict current_state, synaptic_row_t restrict row) { if (!synapse_dynamics_remove_neuron(current_state->offset, row)) { return false; } current_state->post_to_pre_table_entry->neuron_index = 0xFFFF; return true; } //! \brief Adds a synapse to the relevant structures //! \param[in,out] current_state: Describes what is to be done //! \param[in,out] row: The row of the synaptic matrix to be updated //! \return True if the synapse was added static inline bool sp_structs_add_synapse( current_state_t *restrict current_state, synaptic_row_t restrict row) { uint32_t appr_scaled_weight = current_state->pre_population_info->weight; uint32_t actual_delay; uint32_t offset = current_state->pre_population_info->delay_hi - current_state->pre_population_info->delay_lo; actual_delay = rand_int(offset, *(current_state->local_seed)) + current_state->pre_population_info->delay_lo; if (!synapse_dynamics_add_neuron( current_state->post_syn_id, row, appr_scaled_weight, actual_delay, current_state->pre_population_info->connection_type)) { return false; } // Critical: tell the compiler that this pointer is aligned so it doesn't // internally convert the assignment to a memcpy(), which is a saving of // hundreds of bytes... post_to_pre_entry *ppentry = __builtin_assume_aligned( current_state->post_to_pre_table_entry, 4); *ppentry = current_state->post_to_pre; return true; } //! \brief Common code for structural plasticity initialisation. //! \param[in] sdram_sp_address: Address of the configuration region. //! \param[in,out] rewiring_data: //! Address of the rewiring information structure to fill out. //! \param[in,out] pre_info: //! The pre-population information structure to fill out. //! \param[out] post_to_pre_table: Variable to receive the address of the //! post-population-to-pre-population mapping table that this function //! discovers in the configuration region. //! \return pointer to the next piece of memory after the common section of the //! configuration region. static inline uint8_t *sp_structs_read_in_common( address_t sdram_sp_address, rewiring_data_t *rewiring_data, pre_pop_info_table_t *pre_info, post_to_pre_entry **post_to_pre_table) { uint8_t *data = (uint8_t *) sdram_sp_address; spin1_memcpy(rewiring_data, data, sizeof(rewiring_data_t)); data += sizeof(rewiring_data_t); pre_info->no_pre_pops = rewiring_data->no_pre_pops; pre_info->prepop_info = spin1_malloc( rewiring_data->no_pre_pops * sizeof(pre_info_t *)); if (pre_info->prepop_info == NULL) { log_error("Could not initialise pre population info"); rt_error(RTE_SWERR); } for (uint32_t i = 0; i < rewiring_data->no_pre_pops; i++) { pre_info->prepop_info[i] = (pre_info_t *) data; uint32_t pre_size = (pre_info->prepop_info[i]->no_pre_vertices * sizeof(key_atom_info_t)) + sizeof(pre_info_t); pre_info->prepop_info[i] = spin1_malloc(pre_size); if (pre_info->prepop_info[i] == NULL) { log_error("Could not initialise pre population info %d", i); rt_error(RTE_SWERR); } spin1_memcpy(pre_info->prepop_info[i], data, pre_size); log_debug("no_pre = %u, sp_control %u, " "delay lo %u, delay hi %u, weight %d", pre_info->prepop_info[i]->no_pre_vertices, pre_info->prepop_info[i]->sp_control, pre_info->prepop_info[i]->delay_lo, pre_info->prepop_info[i]->delay_hi, pre_info->prepop_info[i]->weight); log_debug("connection_type = %d, total_no_atoms=%d", pre_info->prepop_info[i]->connection_type, pre_info->prepop_info[i]->total_no_atoms); data += pre_size; } *post_to_pre_table = (post_to_pre_entry *) data; uint32_t n_elements = rewiring_data->s_max * rewiring_data->machine_no_atoms; for (uint32_t i=0; i < n_elements; i++){ log_debug("index %d, pop index %d, sub pop index %d, neuron_index %d", i, (*post_to_pre_table)[i].pop_index, (*post_to_pre_table)[i].sub_pop_index, (*post_to_pre_table)[i].neuron_index); } data += n_elements * sizeof(post_to_pre_entry); return (uint8_t *) data; } #endif // _SP_STRUCTS_H_
a84ac0eea0c5aef4f7c4dbc4f5667f34a7887b0e
cff4428975e403e4ef02d75498b78cd1a610a01a
/src/lib/core/mp_datetime.h
b28bb512c7b81c573d0e61e6fd3cfbd8a6256e4f
[ "BSD-2-Clause" ]
permissive
tarantool/tarantool
c1f252b642d223af62485dc21165c7f7c3354e7e
f58cc96f2798ddc5f492223897d0b77e4f902128
refs/heads/master
2023-09-03T15:16:29.144171
2023-08-31T11:39:28
2023-09-01T12:39:29
911,980
3,205
490
NOASSERTION
2023-09-14T17:58:17
2010-09-15T07:59:26
Lua
UTF-8
C
false
false
1,623
h
mp_datetime.h
#pragma once /* * SPDX-License-Identifier: BSD-2-Clause * * Copyright 2021, Tarantool AUTHORS, please see AUTHORS file. */ #include <stdio.h> #include "datetime.h" #if defined(__cplusplus) extern "C" { #endif /* defined(__cplusplus) */ /** * Unpack datetime data from MessagePack buffer. * @sa datetime_pack */ struct datetime * datetime_unpack(const char **data, uint32_t len, struct datetime *date); /** * Pack datetime data to MessagePack buffer. * @sa datetime_unpack */ char * datetime_pack(char *data, const struct datetime *date); /** * Calculate size of MessagePack buffer for datetime data. */ uint32_t mp_sizeof_datetime(const struct datetime *date); /** * Decode data from MessagePack buffer to datetime structure. */ struct datetime * mp_decode_datetime(const char **data, struct datetime *date); /** * Encode datetime structure to the MessagePack buffer. */ char * mp_encode_datetime(char *data, const struct datetime *date); /** * Print datetime's string representation into a given buffer. * @sa mp_snprint_decimal */ int mp_snprint_datetime(char *buf, int size, const char **data, uint32_t len); /** * Print datetime's string representation into a stream. * @sa mp_fprint_decimal */ int mp_fprint_datetime(FILE *file, const char **data, uint32_t len); /** * Check that the buffer contains a valid packed datetime. * @sa mp_validate_decimal */ static inline int mp_validate_datetime(const char *data, uint32_t len) { struct datetime date; return datetime_unpack(&data, len, &date) == NULL; } #if defined(__cplusplus) } /* extern "C" */ #endif /* defined(__cplusplus) */
886854974a7daff98b292c0c5426704beab5c8e7
75b0d3e42c36d73afeea24326b61fc43b591140e
/openssldl.h
aafcbd45bd8cf963c68cd82c06ff8a21aaf62156
[ "MIT" ]
permissive
dosgo/ngrok-c
0c0462ddb912d51584a448b34033b253b804dacc
34b7346ba368c23057503073e7250e88f8e4e1f7
refs/heads/master
2023-07-13T16:12:59.277312
2022-11-24T15:41:18
2022-11-24T15:41:18
31,640,501
607
270
MIT
2021-09-01T01:20:06
2015-03-04T05:51:22
C
UTF-8
C
false
false
4,819
h
openssldl.h
#ifndef OPENSSLDL_H #define OPENSSLDL_H #include <openssl/ssl.h> //---------------------------------------------------------------------------- // Constantes #define SSL_ERROR_NONE 0 #define SSL_ERROR_SSL 1 #define SSL_ERROR_WANT_READ 2 #define SSL_ERROR_WANT_WRITE 3 #define SSL_ERROR_WANT_X509_LOOKUP 4 #define SSL_ERROR_SYSCALL 5 #define SSL_ERROR_ZERO_RETURN 6 #define SSL_ERROR_WANT_CONNECT 7 #define SSL_ERROR_WANT_ACCEPT 8 #define X509_FILETYPE_PEM 1 #define SSL_FILETYPE_PEM X509_FILETYPE_PEM //---------------------------------------------------------------------------- // Variáveis //struct SSL; //struct SSL_CTX; //struct SSL_METHOD; //struct X509; //struct X509_STORE_CTX; //---------------------------------------------------------------------------- // Tipos typedef int (*TSslGetError)(const SSL *s,int ret_code); typedef int (*TSslLibraryInit)(void ); typedef int (*TOpensslInitSsl)(unsigned long long opts, void* v); typedef void (*TSslLoadErrorStrings)(void); typedef SSL_CTX * (*TSslCtxNew)(SSL_METHOD *meth); typedef void (*TSslCtxFree)(SSL_CTX *); typedef int (*TSslSetFd)(SSL *s, int fd); typedef SSL_METHOD *(*TSslMethodV2)(void); typedef SSL_METHOD *(*TSslMethodV3)(void); typedef SSL_METHOD *(*TSslMethodTLSV1)(void); typedef SSL_METHOD *(*TSslMethodV23)(void); typedef SSL_METHOD *(*TtlsMethod)(void); typedef SSL * (*TSslNew)(SSL_CTX *ctx); typedef void (*TSslFree)(SSL *ssl); typedef int (*TSslAccept)(SSL *ssl); typedef int (*TSslConnect)(SSL *ssl); typedef int (*TSslShutdown)(SSL *s); typedef int (*TSslRead)(SSL *ssl,void *buf,int num); typedef int (*TSslPeek)(SSL *ssl,void *buf,int num); typedef int (*TSslWrite)(SSL *ssl,const void *buf,int num); typedef int (*TSslPending)(const SSL *s); typedef int (*TSslPrivateKeyFile)(SSL_CTX *ctx, const char *file, int type); typedef int (*TSslCertificateFile)(SSL_CTX *ctx, const char *file, int type); typedef void (*TOPENSSLaddallalgorithms)(void); typedef X509 * (*TSslGetPeerCertificate)(const SSL *ssl); typedef void (*TSslX509free)(X509 *x); typedef X509 * (*TSslX509d2i)(X509 **px, const unsigned char **in, int len); typedef int (*TSslX509i2d)(X509 *x, unsigned char **out); typedef void (*TSslSetConnectState)(SSL *ssl);//SSL_set_connect_state dosgo typedef int (*TSslDoHandshake)(SSL *ssl);//SSL_do_handshake dosgo typedef SSL_SESSION * (*TSsLGetSession)(const SSL *ssl);//SSL_get_session dosgo typedef int (*TSsLSetSession)(SSL *to, SSL_SESSION *session);//SSL_set_session dosgo typedef long (*TSslCtxCtrl)(SSL_CTX *ctx,int cmd, long larg, void *parg);//SSL_CTX_ctrl dosgo typedef SSL_SESSION *(*TSsLGet1Session)(SSL *ssl);//SSL_get1_session dosgo //---------------------------------------------------------------------------- // Ponteiros de funções extern TSslGetError SslGetError; extern TSslLibraryInit SslLibraryInit; extern TOpensslInitSsl OpensslInitSsl; //openssl 1.1 use extern TSslLoadErrorStrings SslLoadErrorStrings; extern TSslCtxNew SslCtxNew; extern TSslCtxFree SslCtxFree; extern TSslSetFd SslSetFd; extern TSslMethodV2 SslMethodV2; extern TSslMethodV3 SslMethodV3; extern TSslMethodTLSV1 SslMethodTLSV1; extern TSslMethodV23 SslMethodV23; extern TtlsMethod TlsMethod; //openssl 1.1 use extern TSslNew SslNew; extern TSslFree SslFree; extern TSslAccept SslAccept; extern TSslConnect SslConnect; extern TSslShutdown SslShutdown; extern TSslRead SslRead; extern TSslPeek SslPeek; extern TSslWrite SslWrite; extern TSslPending SslPending; extern TSslPrivateKeyFile SslPrivateKeyFile; extern TSslCertificateFile SslCertificateFile; extern TOPENSSLaddallalgorithms OPENSSLaddallalgorithms; extern TSslGetPeerCertificate SslGetPeerCertificate; extern TSslX509free SslX509free; extern TSslX509d2i SslX509d2i; extern TSslX509i2d SslX509i2d; extern TSslSetConnectState SslSetConnectState; //dosgo extern TSslDoHandshake SslDoHandshake; //dosgo extern TSsLSetSession SsLSetSession; //dosgo extern TSsLGetSession SsLGetSession; //dosgo extern TSslCtxCtrl SslCtxCtrl; //dosgo extern TSsLGet1Session SsLGet1Session; //dosgo //---------------------------------------------------------------------------- /// Fecha biblioteca SSL void FechaSSL(); /// Abre biblioteca SSL /** @return 0 se sucesso ou a mensagem de erro */ const char * AbreSSL(); //---------------------------------------------------------------------------- #endif
a860bec84811e58ceaac8e7bd0681c0dc58b4304
a6e90e48ced58e5fdd162d9c111679fcaac57b06
/picohttp/quicperf.h
f3134c7849e8e48cebefceedfbff2499a4e23c4b
[ "MIT" ]
permissive
private-octopus/picoquic
0355964aa79e4292178d57a57bec084d6e3e99da
1e2979e8db0957c8ee798940091c4d0ef13bf8af
refs/heads/master
2023-08-20T08:18:46.538002
2023-08-16T03:41:36
2023-08-16T03:41:36
95,480,304
466
142
MIT
2023-09-06T16:56:25
2017-06-26T19:08:37
C
UTF-8
C
false
false
3,469
h
quicperf.h
/* * Author: Christian Huitema * Copyright (c) 2019, Private Octopus, Inc. * All rights reserved. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * 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 Private Octopus, Inc. 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 QUICPERF_H #define QUICPERF_H #define QUICPERF_ALPN "perf" #define QUICPERF_ALPN_LEN 4 #define QUICPERF_NO_ERROR 0 #define QUICPERF_ERROR_NOT_IMPLEMENTED 1 #define QUICPERF_ERROR_INTERNAL_ERROR 2 #define QUICPERF_ERROR_NOT_ENOUGH_DATA_SENT 3 #define QUICPERF_ERROR_TOO_MUCH_DATA_SENT 4 #define QUICPERF_STREAM_ID_INITIAL UINT64_MAX #ifdef __cplusplus extern "C" { #endif typedef struct st_quicperf_stream_desc_t { uint64_t repeat_count; uint64_t stream_id; /* if -, use default */ uint64_t previous_stream_id; /* if -, use default */ uint64_t post_size; /* Mandatory */ uint64_t response_size; /* If infinite, client will ask stop sending at this size */ int is_infinite; /* Set if the response size was set to "-xxx" */ } quicperf_stream_desc_t; typedef struct st_quicperf_stream_ctx { picosplay_node_t quicperf_stream_node; uint64_t stream_id; uint8_t length_header[8]; uint64_t post_size; /* Unknown on server, from scenario on client */ uint64_t nb_post_bytes; /* Sent on client, received on server */ uint64_t response_size; /* From data on server, from scenario on client */ uint64_t nb_response_bytes; /* Received on client, sent on server */ uint64_t post_time; /* Time stream open (client) or first byte received (server) */ uint64_t post_fin_time; /* Time last byte sent (client) or received (server) */ uint64_t response_time; /* Time first byte sent (server) or received (client) */ uint64_t response_fin_time; /* Time last byte sent (server) or received (client) */ int stop_for_fin; int is_stopped; int is_closed; } quicperf_stream_ctx_t; typedef struct st_quicperf_ctx_t { int is_client; int progress_observed; size_t nb_scenarios; size_t nb_open_streams; uint64_t last_interaction_time; quicperf_stream_desc_t* scenarios; picosplay_tree_t quicperf_stream_tree; /* Statistics gathered on client */ uint64_t data_sent; uint64_t data_received; uint64_t nb_streams; } quicperf_ctx_t; quicperf_ctx_t* quicperf_create_ctx(const char* scenario_text); void quicperf_delete_ctx(quicperf_ctx_t* ctx); int quicperf_callback(picoquic_cnx_t* cnx, uint64_t stream_id, uint8_t* bytes, size_t length, picoquic_call_back_event_t fin_or_event, void* callback_ctx, void* v_stream_ctx); #ifdef __cplusplus } #endif #endif /* QUICPERF_H */
e0df0eb3862b967a5f7fc903b35d89d9e4e734a5
7df190df28da7e4ff166e55dc8ce780f11236a9f
/src/router/ipsec/isakmpd/sysdep/openbsd/keynote_compat.c
ce3f1003feaf364e2025d4d84336ab81218a4817
[ "BSD-3-Clause" ]
permissive
mirror/dd-wrt
25416946e6132aa54b35809de61834a1825a9a36
8f2934a5a2adfbb59b471375aa3a38de5d036531
refs/heads/master
2023-08-31T14:54:47.496685
2023-08-30T17:40:54
2023-08-30T17:40:54
7,470,282
520
281
null
2023-05-29T20:56:24
2013-01-06T17:21:29
null
UTF-8
C
false
false
2,955
c
keynote_compat.c
/* $OpenBSD: keynote_compat.c,v 1.5 2003/06/03 14:53:11 ho Exp $ */ /* $EOM: keynote_compat.c,v 1.1 2000/10/15 19:18:26 niklas Exp $ */ /* * Copyright (c) 2000 Niklas Hallqvist. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * By mistake these functions were introduced into libkeynote without * updating some kind of version preprocessor symbol we can test. * Provide weak functions that can be used if the libkeynote version * we link against miss them. */ #pragma weak kn_get_string=_kn_get_string #pragma weak kn_free_key=_kn_free_key /* * The author of this code is Angelos D. Keromytis (angelos@dsl.cis.upenn.edu) * * This code was written by Angelos D. Keromytis in Philadelphia, PA, USA, * in April-May 1998 * * Copyright (C) 1998, 1999 by Angelos D. Keromytis. * * Permission to use, copy, and modify this software without fee * is hereby granted, provided that this entire notice is included in * all copies of any software which is or includes a copy or * modification of this software. * * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR * IMPLIED WARRANTY. IN PARTICULAR, THE AUTHORS MAKES NO * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR * PURPOSE. */ #include <sys/types.h> #include <regex.h> #include <keynote.h> extern void keynote_free_key(void *, int); extern char *keynote_get_private_key (char *); /* * Exportable front-end to keynote_get_private_key(). */ char * _kn_get_string (char *buf) { return keynote_get_private_key (buf); } /* * Free a key. */ void _kn_free_key (struct keynote_deckey *dc) { if (dc) keynote_free_key (dc->dec_key, dc->dec_algorithm); }
b233555d27514982445d726e2f77ac05544da2b2
88dea29c69d1b003e188a9a7819931eb1fbd17d8
/testing/fuzzing/snmp_transport_fuzzer.c
bc961a65bb1e209ea7712eb3159915ab723d5e4d
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive", "BSD-3-Clause", "MIT", "MIT-CMU" ]
permissive
net-snmp/net-snmp
388733e7094495d25d052834e36691bcfc8b5bad
9ff837bfae4d985e40c8eaf3734a377898d8753a
refs/heads/master
2023-09-01T09:19:14.133409
2023-08-31T02:54:49
2023-08-31T15:11:53
128,822,274
241
236
NOASSERTION
2023-09-11T18:00:01
2018-04-09T19:19:27
C
UTF-8
C
false
false
4,361
c
snmp_transport_fuzzer.c
/* * Copyright (c) 2021, Net-snmp authors * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <net-snmp/net-snmp-config.h> #include <net-snmp/net-snmp-includes.h> #include "../../snmplib/transports/snmpIPBaseDomain.h" #include <net-snmp/library/snmpUDPIPv6Domain.h> #include <net-snmp/library/snmpIPXDomain.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include "ada_fuzz_header.h" int LLVMFuzzerInitialize(int *argc, char ***argv) { if (getenv("NETSNMP_DEBUGGING") != NULL) { /* * Turn on all debugging, to help understand what * bits of the parser are running. */ snmp_enable_stderrlog(); snmp_set_do_debugging(1); debug_register_tokens(""); } return 0; } int LLVMFuzzerTestOneInput(const uint8_t * data, size_t size) { /* * Force the fuzzer to create larger strings as we use * a lot of the data. */ if (size < 550) { return 0; } af_gb_init(); const uint8_t *data2 = data; size_t size2 = size; netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_APPTYPE, "testprog"); init_snmp_transport(); netsnmp_tdomain_init(); /* * Main fuzzing logic */ char *prefix = af_gb_get_null_terminated(&data2, &size2); char *fmt_data = af_gb_get_null_terminated(&data2, &size2); netsnmp_transport *t2 = NULL; if (prefix && fmt_data) { free(netsnmp_ipv6_fmtaddr(prefix, t2, fmt_data, strlen(fmt_data))); struct sockaddr_in6 addr; if (!netsnmp_sockaddr_in6(&addr, prefix, 5123)) goto cleanup; } /* * Security parsing routines. */ char *udp6_token = af_gb_get_null_terminated(&data2, &size2); char *udp6_param = af_gb_get_null_terminated(&data2, &size2); if (udp6_token && udp6_param) { netsnmp_udp6_parse_security(udp6_token, udp6_param); } char *udp_token = af_gb_get_null_terminated(&data2, &size2); char *udp_param = af_gb_get_null_terminated(&data2, &size2); if (udp_token && udp_param) { netsnmp_udp_parse_security(udp_token, udp_param); } struct netsnmp_ep_str ep_str = { }; char *endpoint = af_gb_get_null_terminated(&data2, &size2); if (endpoint && !netsnmp_parse_ep_str(&ep_str, endpoint)) goto cleanup; char *unix_token = af_gb_get_null_terminated(&data2, &size2); char *unix_param = af_gb_get_null_terminated(&data2, &size2); if (unix_token && unix_param) { netsnmp_unix_parse_security(unix_token, unix_param); } /* * Cleanup */ free(ep_str.addr); cleanup: netsnmp_clear_tdomain_list(); shutdown_snmp_transport(); af_gb_cleanup(); return 0; }
b84298c2fc425bd42cdc78c29e8511f623d3a3d0
810237086aae7600b9ef87a610aec4777b1bf156
/Example/Pods/Headers/Private/SJMediaCacheServer/MCSUtils.h
fb7a3132e39cb4a637e098e4986ea1ff7f512eea
[ "MIT" ]
permissive
changsanjiang/SJVideoPlayer
f63f3156d5ad07ec107b0feb481110222dd45a85
bff75e1f7f033edc05e07c333ce3557cb289c95c
refs/heads/master
2022-12-20T22:47:04.095976
2022-12-10T08:57:46
2022-12-10T08:57:46
100,693,284
2,680
513
MIT
2022-11-02T11:04:42
2017-08-18T08:56:30
Objective-C
UTF-8
C
false
false
69
h
MCSUtils.h
../../../SJMediaCacheServer/SJMediaCacheServer/Core/Common/MCSUtils.h
93bad7b4edd2af001c9d9f952ec126ac33f1b295
ea401c3e792a50364fe11f7cea0f35f99e8f4bde
/released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/tz_pixel_array.c
ae6dffdc2089ee14d294d9d2fa524b07918c37f6
[ "MIT", "BSD-2-Clause", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only" ]
permissive
Vaa3D/vaa3d_tools
edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9
e6974d5223ae70474efaa85e1253f5df1814fae8
refs/heads/master
2023-08-03T06:12:01.013752
2023-08-02T07:26:01
2023-08-02T07:26:01
50,527,925
107
86
MIT
2023-05-22T23:43:48
2016-01-27T18:19:17
C++
UTF-8
C
false
false
4,080
c
tz_pixel_array.c
/* tz_pixel_array.c * * 30-Nov-2007 Initial write: Ting Zhao */ #include <image_lib.h> #include <utilities.h> #include "tz_error.h" #include "tz_objdef.h" #include "tz_image_lib.h" #include "tz_pixel_array.h" #include "tz_u8array.h" #include "tz_u16array.h" #include "tz_farray.h" #include "tz_darray.h" INIT_EXCEPTION static inline int pixel_array_asize(const Pixel_Array *pa) { return pa->size * pa->kind; } void Default_Pixel_Array(Pixel_Array *pa) { if (pa->array == NULL) { return; } pa->size = 0; pa->kind = 1; } DEFINE_OBJECT_MANAGEMENT(Pixel_Array, array, asize, pixel_array) Pixel_Array *Make_Pixel_Array(int kind, int size) { Pixel_Array *pa = NULL; pa = new_pixel_array(size * kind, "Make_Pixel_Array"); pa->kind = kind; pa->size = size; return pa; } static size_t pixel_array_fread_attribute(Pixel_Array *pa, FILE *stream) { size_t read_size = 0; read_size += fread(&(pa->kind), sizeof(int), 1, stream); read_size += fread(&(pa->size), sizeof(int), 1, stream); return read_size; } size_t Pixel_Array_Fread(Pixel_Array *pa, FILE *stream) { size_t read_size = 0; read_size += pixel_array_fread_attribute(pa, stream); read_size += fread(pa->array, pixel_array_asize(pa), 1, stream); return read_size; } size_t Pixel_Array_Fwrite(const Pixel_Array *pa, FILE *stream) { size_t written_size = 0; written_size += fwrite(&(pa->kind), sizeof(int), 1, stream); written_size += fwrite(&(pa->size), sizeof(int), 1, stream); written_size += fwrite(pa->array, pixel_array_asize(pa), 1, stream); return written_size; } Pixel_Array* Pixel_Array_Read(const char *file_path) { Pixel_Array tmp_array; FILE *fp = Guarded_Fopen((char *) file_path, "rb", "Pixel_Array_Read"); pixel_array_fread_attribute(&tmp_array, fp); Pixel_Array *pa = Make_Pixel_Array(tmp_array.kind, tmp_array.size); fread(pa->array, pixel_array_asize(pa), 1, fp); fclose (fp); return pa; } void Pixel_Array_Write(const char *file_path, const Pixel_Array *pa) { FILE *fp = Guarded_Fopen((char *) file_path, "wb", "Pixel_Array_Write"); Pixel_Array_Fwrite(pa, fp); fclose(fp); } /* Print_Pixel_Array(): Print pixel array. */ void Print_Pixel_Array(const Pixel_Array *pa) { int i; DEFINE_ARRAY_ALL(array, pa); printf("Pixel array: kind - %d, size - %d\n", pa->kind, pa->size); switch (pa->kind) { case GREY: for (i = 0; i < pa->size; i++) { printf("%u\n", array_grey[i]); } break; case GREY16: for (i = 0; i < pa->size; i++) { printf("%u\n", array_grey16[i]); } break; case COLOR: for (i = 0; i < pa->size; i++) { printf("%u, %u, %u\n", array_color[i][0], array_color[i][1], array_color[i][2]); } break; case FLOAT32: for (i = 0; i < pa->size; i++) { printf("%g\n", array_float32[i]); } break; case FLOAT64: for (i = 0; i < pa->size; i++) { printf("%g\n", array_float64[i]); } break; default: THROW(ERROR_DATA_TYPE); } } void Pixel_Array_Export(const char *file_path, const Pixel_Array *pa) { switch (pa->kind) { case GREY: u8array_write(file_path, (const tz_uint8*)pa->array, pa->size); break; case GREY16: u16array_write(file_path, (const tz_uint16*)pa->array, pa->size); break; case FLOAT32: farray_write(file_path, (const float*)pa->array, pa->size); break; case FLOAT64: darray_write(file_path, (const double*)pa->array, pa->size); break; default: TZ_ERROR(ERROR_DATA_TYPE); } } double Pixel_Array_Value(const Pixel_Array *pa, int index) { switch (pa->kind) { case GREY: return ((uint8 *) pa->array)[index]; case GREY16: return ((uint16 *) pa->array)[index]; case FLOAT32: return ((float *) pa->array)[index]; case FLOAT64: return ((double *) pa->array)[index]; default: TZ_ERROR(ERROR_DATA_TYPE); } return 0.0; }
b54403f4057044e60bb8475f98bfd4a98d1c51f2
83372fce92c9088ee5c1e1c13bc67385a3b02a36
/test/ref/charset.c
8bd1675c8838f28b8d6f3dc4a33bdff9cc0ae0ea
[ "Zlib", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
permissive
cc65/cc65
2cd1b20b61ddd0691cd4601b4da37a9200a50afb
16e90187e8e80c6e2fcfcc04f068ac865d2290e5
refs/heads/master
2023-09-03T17:16:46.027934
2023-09-02T22:30:44
2023-09-02T22:30:44
8,932,489
2,103
526
Zlib
2023-09-13T06:19:01
2013-03-21T15:56:48
C
UTF-8
C
false
false
3,523
c
charset.c
/* !!DESCRIPTION!! basic ASCII character test !!ORIGIN!! testsuite !!LICENCE!! Public Domain !!AUTHOR!! Groepaz/Hitmen */ #include <stdio.h> #if 0 /* this kind of line-continuation for strings doesnt work properly for cc65 */ const unsigned char characters[]={ /*0123456789abcdef0123456789abcdef*/ /* iso646-us control-characters */ " " /* 00-1f */ /* iso646-us printable characters */ " !\"#$%&'()*+,-./" /* 20-2f !"#$%&'()*+,-./ */ "0123456789" /* 30-39 0123456789 */ ":;<=>?@" /* 3a-40 :;<=>?@ */ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* 41-5a A-Z */ "[\\]^_`" /* 5b-60 [\]^_` */ "abcdefghijklmnopqrstuvwxyz" /* 61-7a a-z */ "{|}~ " /* 7b-7f {|}~ */ /* iso8859-15 extended characters */ }; #endif const unsigned char characters[]={ /*0123456789abcdef0123456789abcdef*/ /* iso646-us control-characters */ /* 00-1f */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* iso646-us printable characters */ /* 20-2f !"#$%&'()*+,-./ */ ' ','!','"','#','$','%','&','\'','(',')','*','+',',','-','.','/', /* 30-39 0123456789 */ '0','1','2','3','4','5','6','7','8','9', /* 3a-40 :;<=>?@ */ ':',';','<','=','>','?','@', /* 41-5a A-Z */ 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', /* 5b-60 [\]^_` */ '[','\\',']','^','_','`', /* 61-7a a-z */ 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', /* 7b-7f {|}~ */ '{','|','}','~',' ' /* iso8859-15 extended characters */ }; void printchars(unsigned char a,unsigned char b){ for(b++;a!=b;a++) /* printf("%02x ",a); */ /* printf("%02x ",characters[a]); */ printf("%c",characters[a]); printf("\n"); } int main(void) { printf("characters:\n\n"); printchars(0x61,0x7a); printchars(0x41,0x5a); printf("numbers:\n\n"); printchars(0x30,0x39); printf("other:\n\n"); printchars(0x20,0x2f); /*printchars(0x3a,0x40);*/ printchars(0x3a,0x3f); /*printchars(0x5b,0x60);*/ /*printchars(0x7b,0x7f);*/ printf("\n\n"); printf("slash: '%c'\n",'/'); printf("backslash: '%c'\n",'\\'); printf("curly braces open: '%c'\n",'{'); printf("curly braces close: '%c'\n",'}'); printf("square braces open: '%c'\n",'['); printf("square braces close: '%c'\n",']'); printf("underscore: '%c'\n",'_'); printf("tilde: '%c'\n",'~'); printf("pipe: '%c'\n",'|'); printf("apostroph: '%c'\n",'\''); printf("single quote '%c'\n",'`'); printf("xor '%c'\n",'^'); printf("at '%c'\n",'@'); return 0; }
72a2f3d726f88d5a1f07da1fa2d7880dda9c2101
dd595acb70010b3c5ccddca44de372ea07b7e8c3
/test/jpg_test.h
d72865a00c467f9b2780bee4e14dbc3f003c8eb8
[ "MIT" ]
permissive
brackeen/ok-file-formats
ab485f46dd84b8f46e95a88153482d1287ae771d
8d68dad9c9f220058e86dc7f3d05acca6b9aedf5
refs/heads/master
2021-12-12T13:13:08.861427
2021-09-11T17:34:05
2021-09-11T17:34:05
20,731,408
111
17
null
null
null
null
UTF-8
C
false
false
224
h
jpg_test.h
#ifndef JPG_TEST_H #define JPG_TEST_H #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif int jpg_test(const char *path_to_jpgs, const char *path_to_rgba_files, bool verbose); #ifdef __cplusplus } #endif #endif
b2b7acbe2e1ce13e4a71d933d3ac76d4a19be6ae
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/wch/arm/Libraries/ch32_drivers/drv_hwtimer_ch32f20x.c
5bb45e7b363cf5bfeaadf77b5966dc93ca938d25
[ "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
15,748
c
drv_hwtimer_ch32f20x.c
/* * Copyright (c) 2006-2023, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2022-01-21 charlown first version */ #include <rtthread.h> #include <rtdevice.h> #include <board.h> #ifdef BSP_USING_HWTIMER #define LOG_TAG "drv.hwtimer" #include <drv_log.h> struct hwtimer_device { struct rt_hwtimer_device parent; TIM_TypeDef *periph; IRQn_Type irqn; char *name; }; #ifdef BSP_USING_TIM1_HWTIMER struct hwtimer_device hwtimer_device1 = { .periph = TIM1, .irqn = TIM1_UP_IRQn, .name = "timer1"}; #endif #ifdef BSP_USING_TIM2_HWTIMER struct hwtimer_device hwtimer_device2 = { .periph = TIM2, .irqn = TIM2_IRQn, .name = "timer2"}; #endif #ifdef BSP_USING_TIM3_HWTIMER struct hwtimer_device hwtimer_device3 = { .periph = TIM3, .irqn = TIM3_IRQn, .name = "timer3"}; #endif #ifdef BSP_USING_TIM4_HWTIMER struct hwtimer_device hwtimer_device4 = { .periph = TIM4, .irqn = TIM4_IRQn, .name = "timer4"}; #endif #ifdef BSP_USING_TIM5_HWTIMER struct hwtimer_device hwtimer_device5 = { .periph = TIM5, .irqn = TIM5_IRQn, .name = "timer5"}; #endif #ifdef BSP_USING_TIM6_HWTIMER struct hwtimer_device hwtimer_device6 = { .periph = TIM6, .irqn = TIM6_IRQn, .name = "timer6"}; #endif #ifdef BSP_USING_TIM7_HWTIMER struct hwtimer_device hwtimer_device7 = { .periph = TIM7, .irqn = TIM7_IRQn, .name = "timer7"}; #endif #ifdef BSP_USING_TIM8_HWTIMER struct hwtimer_device hwtimer_device8 = { .periph = TIM8, .irqn = TIM8_UP_IRQn, .name = "timer8"}; #endif #ifdef BSP_USING_TIM9_HWTIMER struct hwtimer_device hwtimer_device9 = { .periph = TIM9, .irqn = TIM9_UP_IRQn, .name = "timer9"}; #endif #ifdef BSP_USING_TIM10_HWTIMER struct hwtimer_device hwtimer_device10 = { .periph = TIM10, .irqn = TIM10_UP_IRQn, .name = "timer10"}; #endif static void ch32f2_hwtimer_init(struct rt_hwtimer_device *device, rt_uint32_t state) { struct hwtimer_device *hwtimer_dev; struct rt_hwtimer_info *hwtimer_info; rt_uint32_t clk = 0; rt_uint16_t prescaler_value = 0; TIM_TimeBaseInitTypeDef TIM_TimeBaseInitType; NVIC_InitTypeDef NVIC_InitStructure; RT_ASSERT(device != RT_NULL); hwtimer_dev = (struct hwtimer_device *)device; if (state) { ch32f2_tim_clock_init(hwtimer_dev->periph); hwtimer_info = ch32f2_hwtimer_info_config_get(hwtimer_dev->periph); clk = ch32f2_tim_clock_get(hwtimer_dev->periph); prescaler_value = (rt_uint16_t)(clk / hwtimer_info->minfreq) - 1; /* * (1 / freq) = (cnt + 1) * (1 / (clk/(prescaler_value + 1) ) ) */ TIM_TimeBaseInitType.TIM_Period = hwtimer_info->maxcnt - 1; TIM_TimeBaseInitType.TIM_Prescaler = prescaler_value; TIM_TimeBaseInitType.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInitType.TIM_RepetitionCounter = 0; if (hwtimer_info == RT_NULL) { TIM_TimeBaseInitType.TIM_CounterMode = TIM_CounterMode_Up; } else { if (hwtimer_info->cntmode == HWTIMER_CNTMODE_UP) { TIM_TimeBaseInitType.TIM_CounterMode = TIM_CounterMode_Up; } else { TIM_TimeBaseInitType.TIM_CounterMode = TIM_CounterMode_Down; } } TIM_TimeBaseInit(hwtimer_dev->periph, &TIM_TimeBaseInitType); NVIC_InitStructure.NVIC_IRQChannel = hwtimer_dev->irqn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); TIM_ITConfig(hwtimer_dev->periph, TIM_IT_Update, ENABLE); TIM_ClearITPendingBit(hwtimer_dev->periph, TIM_IT_Update); LOG_D("%s init success", hwtimer_dev->name); } } static rt_err_t ch32f2_hwtimer_start(struct rt_hwtimer_device *device, rt_uint32_t cnt, rt_hwtimer_mode_t mode) { struct hwtimer_device *hwtimer_dev; RT_ASSERT(device != RT_NULL); hwtimer_dev = (struct hwtimer_device *)device; /* * (1 / freq) = (cnt + 1) * (1 / (clk/(prescaler_value + 1) ) ) */ TIM_SetCounter(hwtimer_dev->periph, 0); TIM_SetAutoreload(hwtimer_dev->periph, cnt - 1); if (mode == HWTIMER_MODE_ONESHOT) { TIM_SelectOnePulseMode(hwtimer_dev->periph, TIM_OPMode_Single); } else { TIM_SelectOnePulseMode(hwtimer_dev->periph, TIM_OPMode_Repetitive); } TIM_Cmd(hwtimer_dev->periph, ENABLE); LOG_D("%s start, cnt = %d", hwtimer_dev->name, cnt); return RT_EOK; } static void ch32f2_hwtimer_stop(struct rt_hwtimer_device *device) { struct hwtimer_device *hwtimer_dev; RT_ASSERT(device != RT_NULL); hwtimer_dev = (struct hwtimer_device *)device; TIM_Cmd(hwtimer_dev->periph, DISABLE); TIM_SetCounter(hwtimer_dev->periph, 0); } static rt_uint32_t ch32f2_hwtimer_counter_get(struct rt_hwtimer_device *device) { struct hwtimer_device *hwtimer_dev; RT_ASSERT(device != RT_NULL); hwtimer_dev = (struct hwtimer_device *)device; return hwtimer_dev->periph->CNT; } static rt_err_t ch32f2_hwtimer_control(struct rt_hwtimer_device *device, rt_uint32_t cmd, void *arg) { struct hwtimer_device *hwtimer_dev; rt_err_t result = RT_EOK; RT_ASSERT(device != RT_NULL); hwtimer_dev = (struct hwtimer_device *)device; switch (cmd) { case HWTIMER_CTRL_FREQ_SET: { rt_uint32_t freq = 0; rt_uint32_t clk = 0; rt_uint16_t prescaler_value = 0; /* * (1 / freq) = (cnt + 1) * (1 / (clk/(prescaler_value + 1) ) ) */ if (arg != RT_NULL) { freq = *((rt_uint32_t *)arg); clk = ch32f2_tim_clock_get(hwtimer_dev->periph); prescaler_value = (rt_uint16_t)(clk / freq) - 1; TIM_PrescalerConfig(hwtimer_dev->periph, prescaler_value, TIM_PSCReloadMode_Immediate); } else { result = -RT_EINVAL; } } break; default: result = -RT_ENOSYS; break; } return result; } static const struct rt_hwtimer_ops hwtimer_ops = { .init = ch32f2_hwtimer_init, .start = ch32f2_hwtimer_start, .stop = ch32f2_hwtimer_stop, .count_get = ch32f2_hwtimer_counter_get, .control = ch32f2_hwtimer_control, }; static int rt_hw_hwtimer_init(void) { rt_err_t ret; struct rt_hwtimer_info *hwtimer_info; #ifdef BSP_USING_TIM1_HWTIMER hwtimer_info = ch32f2_hwtimer_info_config_get(hwtimer_device1.periph); hwtimer_device1.parent.info = hwtimer_info; hwtimer_device1.parent.ops = &hwtimer_ops; ret = rt_device_hwtimer_register(&hwtimer_device1.parent, hwtimer_device1.name, RT_NULL); if (ret == RT_EOK) { LOG_D("hwtimer: %s register success.", hwtimer_device1.name); } else { LOG_D("hwtimer: %s register failed.", hwtimer_device1.name); } #endif #ifdef BSP_USING_TIM2_HWTIMER hwtimer_info = ch32f2_hwtimer_info_config_get(hwtimer_device2.periph); hwtimer_device2.parent.info = hwtimer_info; hwtimer_device2.parent.ops = &hwtimer_ops; ret = rt_device_hwtimer_register(&hwtimer_device2.parent, hwtimer_device2.name, RT_NULL); if (ret == RT_EOK) { LOG_D("hwtimer: %s register success.", hwtimer_device2.name); } else { LOG_D("hwtimer: %s register failed.", hwtimer_device2.name); } #endif #ifdef BSP_USING_TIM3_HWTIMER hwtimer_info = ch32f2_hwtimer_info_config_get(hwtimer_device3.periph); hwtimer_device3.parent.info = hwtimer_info; hwtimer_device3.parent.ops = &hwtimer_ops; ret = rt_device_hwtimer_register(&hwtimer_device3.parent, hwtimer_device3.name, RT_NULL); if (ret == RT_EOK) { LOG_D("hwtimer: %s register success.", hwtimer_device3.name); } else { LOG_D("hwtimer: %s register failed.", hwtimer_device3.name); } #endif #ifdef BSP_USING_TIM4_HWTIMER hwtimer_info = ch32f2_hwtimer_info_config_get(hwtimer_device4.periph); hwtimer_device4.parent.info = hwtimer_info; hwtimer_device4.parent.ops = &hwtimer_ops; ret = rt_device_hwtimer_register(&hwtimer_device4.parent, hwtimer_device4.name, RT_NULL); if (ret == RT_EOK) { LOG_D("hwtimer: %s register success.", hwtimer_device4.name); } else { LOG_D("hwtimer: %s register failed.", hwtimer_device4.name); } #endif #ifdef BSP_USING_TIM5_HWTIMER hwtimer_info = ch32f2_hwtimer_info_config_get(hwtimer_device5.periph); hwtimer_device5.parent.info = hwtimer_info; hwtimer_device5.parent.ops = &hwtimer_ops; ret = rt_device_hwtimer_register(&hwtimer_device5.parent, hwtimer_device5.name, RT_NULL); if (ret == RT_EOK) { LOG_D("hwtimer: %s register success.", hwtimer_device5.name); } else { LOG_D("hwtimer: %s register failed.", hwtimer_device5.name); } #endif #ifdef BSP_USING_TIM6_HWTIMER hwtimer_info = ch32f2_hwtimer_info_config_get(hwtimer_device6.periph); hwtimer_device6.parent.info = hwtimer_info; hwtimer_device6.parent.ops = &hwtimer_ops; ret = rt_device_hwtimer_register(&hwtimer_device6.parent, hwtimer_device6.name, RT_NULL); if (ret == RT_EOK) { LOG_D("hwtimer: %s register success.", hwtimer_device6.name); } else { LOG_D("hwtimer: %s register failed.", hwtimer_device6.name); } #endif #ifdef BSP_USING_TIM7_HWTIMER hwtimer_info = ch32f2_hwtimer_info_config_get(hwtimer_device7.periph); hwtimer_device7.parent.info = hwtimer_info; hwtimer_device7.parent.ops = &hwtimer_ops; ret = rt_device_hwtimer_register(&hwtimer_device7.parent, hwtimer_device7.name, RT_NULL); if (ret == RT_EOK) { LOG_D("hwtimer: %s register success.", hwtimer_device7.name); } else { LOG_D("hwtimer: %s register failed.", hwtimer_device7.name); } #endif #ifdef BSP_USING_TIM8_HWTIMER hwtimer_info = ch32f2_hwtimer_info_config_get(hwtimer_device8.periph); hwtimer_device8.parent.info = hwtimer_info; hwtimer_device8.parent.ops = &hwtimer_ops; ret = rt_device_hwtimer_register(&hwtimer_device8.parent, hwtimer_device8.name, RT_NULL); if (ret == RT_EOK) { LOG_D("hwtimer: %s register success.", hwtimer_device8.name); } else { LOG_D("hwtimer: %s register failed.", hwtimer_device8.name); } #endif #ifdef BSP_USING_TIM9_HWTIMER hwtimer_info = ch32f2_hwtimer_info_config_get(hwtimer_device9.periph); hwtimer_device9.parent.info = hwtimer_info; hwtimer_device9.parent.ops = &hwtimer_ops; ret = rt_device_hwtimer_register(&hwtimer_device9.parent, hwtimer_device9.name, RT_NULL); if (ret == RT_EOK) { LOG_D("hwtimer: %s register success.", hwtimer_device9.name); } else { LOG_D("hwtimer: %s register failed.", hwtimer_device9.name); } #endif #ifdef BSP_USING_TIM10_HWTIMER hwtimer_info = ch32f2_hwtimer_info_config_get(hwtimer_device10.periph); hwtimer_device10.parent.info = hwtimer_info; hwtimer_device10.parent.ops = &hwtimer_ops; ret = rt_device_hwtimer_register(&hwtimer_device10.parent, hwtimer_device10.name, RT_NULL); if (ret == RT_EOK) { LOG_D("hwtimer: %s register success.", hwtimer_device10.name); } else { LOG_D("hwtimer: %s register failed.", hwtimer_device10.name); } #endif return RT_EOK; } INIT_DEVICE_EXPORT(rt_hw_hwtimer_init); #ifdef BSP_USING_TIM1_HWTIMER void TIM1_UP_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); if (TIM_GetITStatus(hwtimer_device1.periph, TIM_IT_Update) == SET) { TIM_ClearITPendingBit(hwtimer_device1.periph, TIM_IT_Update); rt_device_hwtimer_isr(&hwtimer_device1.parent); } /* leave interrupt */ rt_interrupt_leave(); } #endif #ifdef BSP_USING_TIM2_HWTIMER void TIM2_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); if (TIM_GetITStatus(hwtimer_device2.periph, TIM_IT_Update) == SET) { TIM_ClearITPendingBit(hwtimer_device2.periph, TIM_IT_Update); rt_device_hwtimer_isr(&hwtimer_device2.parent); } /* leave interrupt */ rt_interrupt_leave(); } #endif #ifdef BSP_USING_TIM3_HWTIMER void TIM3_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); if (TIM_GetITStatus(hwtimer_device3.periph, TIM_IT_Update) == SET) { TIM_ClearITPendingBit(hwtimer_device3.periph, TIM_IT_Update); rt_device_hwtimer_isr(&hwtimer_device3.parent); } /* leave interrupt */ rt_interrupt_leave(); } #endif #ifdef BSP_USING_TIM4_HWTIMER void TIM4_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); if (TIM_GetITStatus(hwtimer_device4.periph, TIM_IT_Update) == SET) { TIM_ClearITPendingBit(hwtimer_device4.periph, TIM_IT_Update); rt_device_hwtimer_isr(&hwtimer_device4.parent); } /* leave interrupt */ rt_interrupt_leave(); } #endif #ifdef BSP_USING_TIM5_HWTIMER void TIM5_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); if (TIM_GetITStatus(hwtimer_device5.periph, TIM_IT_Update) == SET) { TIM_ClearITPendingBit(hwtimer_device5.periph, TIM_IT_Update); rt_device_hwtimer_isr(&hwtimer_device5.parent); } /* leave interrupt */ rt_interrupt_leave(); } #endif #ifdef BSP_USING_TIM6_HWTIMER void TIM6_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); if (TIM_GetITStatus(hwtimer_device6.periph, TIM_IT_Update) == SET) { TIM_ClearITPendingBit(hwtimer_device6.periph, TIM_IT_Update); rt_device_hwtimer_isr(&hwtimer_device6.parent); } /* leave interrupt */ rt_interrupt_leave(); } #endif #ifdef BSP_USING_TIM7_HWTIMER void TIM7_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); if (TIM_GetITStatus(hwtimer_device7.periph, TIM_IT_Update) == SET) { TIM_ClearITPendingBit(hwtimer_device7.periph, TIM_IT_Update); rt_device_hwtimer_isr(&hwtimer_device7.parent); } /* leave interrupt */ rt_interrupt_leave(); } #endif #ifdef BSP_USING_TIM8_HWTIMER void TIM8_UP_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); if (TIM_GetITStatus(hwtimer_device8.periph, TIM_IT_Update) == SET) { TIM_ClearITPendingBit(hwtimer_device8.periph, TIM_IT_Update); rt_device_hwtimer_isr(&hwtimer_device8.parent); } /* leave interrupt */ rt_interrupt_leave(); } #endif #ifdef BSP_USING_TIM9_HWTIMER void TIM9_UP_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); if (TIM_GetITStatus(hwtimer_device9.periph, TIM_IT_Update) == SET) { TIM_ClearITPendingBit(hwtimer_device9.periph, TIM_IT_Update); rt_device_hwtimer_isr(&hwtimer_device9.parent); } /* leave interrupt */ rt_interrupt_leave(); } #endif #ifdef BSP_USING_TIM10_HWTIMER void TIM10_UP_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); if (TIM_GetITStatus(hwtimer_device10.periph, TIM_IT_Update) == SET) { TIM_ClearITPendingBit(hwtimer_device10.periph, TIM_IT_Update); rt_device_hwtimer_isr(&hwtimer_device10.parent); } /* leave interrupt */ rt_interrupt_leave(); } #endif #endif /* BSP_USING_HWTIMER */
42a61f01385591bfda34399c5089eb09fd56b25d
50dd46b8ece33f3cdd174284b15d1d51f89669d4
/2020/quals/pwn-gatekey/attachments/gatekey/gatekey/gatekey_setup.c
37719dd04bc8b8c0183e01b2ed1f15fa90d17879
[ "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
8,526
c
gatekey_setup.c
/* * Copyright 2020 Google LLC * * 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. */ #define _GNU_SOURCE #include <fcntl.h> #include <unistd.h> #include <err.h> #include <assert.h> #include <stdint.h> #include <unistd.h> #include <limits.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <stddef.h> #include <stdlib.h> #include <sys/prctl.h> #include <sys/mman.h> #include <sys/syscall.h> #include <linux/audit.h> #include <linux/seccomp.h> #include <linux/filter.h> #include "internal.h" #include "gatekey_api.h" struct seccomp_data_patched { int nr; __u32 arch; __u64 instruction_pointer; __u64 args[6]; __u64 pkeys; }; #define SECCOMP_LOAD(NAME, OFFSET) \ { .code = BPF_LD | BPF_W | BPF_ABS, .k = offsetof(struct seccomp_data_patched, NAME) + OFFSET } #define SECCOMP_ASSERT(CMP, VALUE) \ { .code = BPF_JMP|CMP|BPF_K, .k = (VALUE), .jf = (uint8_t)-2 } #define SECCOMP_ACCEPT_IF(CMP, VALUE) \ { .code = BPF_JMP|CMP|BPF_K, .k = (VALUE), .jt = (uint8_t)-1 } extern struct open_how permitted_open_how[2]; extern void *(*__morecore)(unsigned long); /* from glibc */ /* __morecore hook to prevent any use of brk() */ static void *morecore_reject(unsigned long increment) { return NULL; } /* If you have unaligned WRPKRU/XRSTOR anywhere, this is gonna let you have a * really bad time. But at least the glibc I'm testing with doesn't have any of * those... * Also, this breaks lazy symbol resolution. */ static void clobber_insn_unless_known_safe(unsigned char *p) { extern unsigned char safe_wrpkru_trusted[]; extern unsigned char safe_wrpkru_normal[]; if (p == safe_wrpkru_trusted || p == safe_wrpkru_normal) { printf(" known safe\n"); return; } printf(" clobbering\n"); int fd = open("/proc/self/mem", O_WRONLY); if (fd == -1) err(1, "open mem"); unsigned char clobber[] = {0xcc, 0xcc, 0xcc}; if (pwrite(fd, clobber, sizeof(clobber), (unsigned long)p) != sizeof(clobber)) err(1, "clobbering instruction failed"); close(fd); } static void ensure_no_bad_insns_in_range(unsigned long start, unsigned long end) { printf("ensure_no_bad_insns_in_range(%lx-%lx)\n", start, end); for (unsigned char *p = (unsigned char *)start; p + 3 <= (unsigned char*)end; p++) { if (p[0] != 0x0f) continue; if (p[1] == 0x01 && p[2] == 0xef) { printf("WRPKRU at %p\n", p); clobber_insn_unless_known_safe(p); } if (p[1] == 0xae && (p[2] & 0x38) == 0x28 && (p[2] >> 6) != 3/*register-direct==LFENCE*/) { printf("XRSTOR at %p\n", p); clobber_insn_unless_known_safe(p); } } } static void ensure_no_bad_insns(void) { int maps_fd = open("/proc/self/maps", O_RDONLY); char maps[100000]; int maps_len = 0; while (1) { int len = read(maps_fd, maps+maps_len, sizeof(maps)-1-maps_len); if (len < 0) err(1, "unable to read from maps"); if (len == 0) break; maps_len += len; } maps[maps_len] = '\0'; char *line = maps; unsigned long exec_start = 0, exec_end = 0; while (1) { char *next_line = strchr(line, '\n'); if (next_line) { *next_line = '\0'; next_line++; } unsigned long start, end; char flags[100]; if (sscanf(line, "%lx-%lx %s", &start, &end, flags) != 3) errx(1, "cannot parse line '%s'", line); printf("got mapping: %s\n", line); assert(end > start); assert(flags[2] == '-' || flags[2] == 'x'); assert(flags[1] == '-' || flags[2] == '-'); // W^X if (flags[2] == 'x' && start == exec_end) { exec_end = end; } else if (flags[2] == 'x') { ensure_no_bad_insns_in_range(exec_start, exec_end); exec_start = start; exec_end = end; } line = next_line; if (line == NULL || line[0] == '\0') break; } ensure_no_bad_insns_in_range(exec_start, exec_end); close(maps_fd); } void gatekey_setup(void) { __morecore = morecore_reject; ensure_no_bad_insns(); /* Prevent exploitable recursion. */ if (mprotect(key_gate_stack, 0x1000, PROT_NONE)) err(1, "mprotect key_gate_stack guard page"); #ifndef INSECURE /* Set up trusted/normal pkey states. */ int gatekey_idx = pkey_alloc(0, 0); if (gatekey_idx == -1) err(1, "pkey_alloc failed; please make sure your machine supports pkeys"); gatekey_trusted_key_state = __builtin_ia32_rdpkru(); unsigned int gatekey_write_mask = (0x2 << (2 * gatekey_idx)); gatekey_normal_key_state = gatekey_trusted_key_state | gatekey_write_mask; /* Protect gatekey regions with our shiny new pkey. */ if (pkey_mprotect(_gatekey_data_begin, _gatekey_data_end - _gatekey_data_begin, PROT_READ|PROT_WRITE, gatekey_idx)) err(1, "protect our .data with the gatekey: pkey_mprotect(%p, 0x%lx, READ|WRITE, 0x%lx)", _gatekey_data_begin, _gatekey_data_end - _gatekey_data_begin, gatekey_idx); if (pkey_mprotect(_gatekey_bss_begin, _gatekey_bss_end - _gatekey_bss_begin, PROT_READ|PROT_WRITE, gatekey_idx)) err(1, "protect our .bss with the gatekey"); printf("trusted pkeys state: 0x%x\n", gatekey_trusted_key_state); printf("restricted pkeys state: 0x%x\n", gatekey_normal_key_state); printf("gatekey index: %d\n", gatekey_idx); #else printf("INSECURE MODE ACTIVE, NOT FOR PRODUCTION USE\n"); #endif /* * Create a seccomp policy to protect gatekey stuff. */ unsigned long mmap_protected_end = (unsigned long)&_end; assert(mmap_protected_end <= UINT_MAX); struct sock_filter filter[] = { /* must be x86-64 ABI */ SECCOMP_LOAD(arch, 0), SECCOMP_ASSERT(BPF_JEQ, AUDIT_ARCH_X86_64), SECCOMP_LOAD(nr, 0), /* unconditionally acceptable syscalls */ SECCOMP_ACCEPT_IF(BPF_JEQ, __NR_read), SECCOMP_ACCEPT_IF(BPF_JEQ, __NR_pread64), SECCOMP_ACCEPT_IF(BPF_JEQ, __NR_write), SECCOMP_ACCEPT_IF(BPF_JEQ, __NR_pwrite64), SECCOMP_ACCEPT_IF(BPF_JEQ, __NR_close), SECCOMP_ACCEPT_IF(BPF_JEQ, __NR_exit_group), SECCOMP_ACCEPT_IF(BPF_JEQ, __NR_getrandom), /* mmap: only non-fixed, non-executable */ { .code = BPF_JMP|BPF_JEQ|BPF_K, .k = __NR_mmap, .jf = 4 }, SECCOMP_LOAD(args[2], 0), SECCOMP_ASSERT(BPF_JEQ, PROT_READ|PROT_WRITE), SECCOMP_LOAD(args[3], 0), SECCOMP_ACCEPT_IF(BPF_JEQ, MAP_PRIVATE|MAP_ANONYMOUS), /* munmap: only past the end of our program mapping */ { .code = BPF_JMP|BPF_JEQ|BPF_K, .k = __NR_munmap, .jf = 4 }, SECCOMP_LOAD(args[0], 4), SECCOMP_ACCEPT_IF(BPF_JGT, 0), SECCOMP_LOAD(args[0], 0), SECCOMP_ACCEPT_IF(BPF_JGE, (uint32_t)mmap_protected_end), #ifndef INSECURE /* anything else requires having the privileged key... */ SECCOMP_LOAD(pkeys, 0), SECCOMP_ASSERT(BPF_JEQ, gatekey_trusted_key_state), #endif /* privileged code still can't do whatever it wants, but we permit opening * files below cwd and open fds */ SECCOMP_LOAD(nr, 0), SECCOMP_ASSERT(BPF_JEQ, __NR_openat2), SECCOMP_LOAD(args[2], 4), SECCOMP_ASSERT(BPF_JEQ, ((unsigned long)&permitted_open_how)>>32), SECCOMP_LOAD(args[2], 0), SECCOMP_ACCEPT_IF(BPF_JEQ, (uint32_t)(unsigned long)permitted_open_how), SECCOMP_ACCEPT_IF(BPF_JEQ, (uint32_t)(unsigned long)(permitted_open_how+1)), BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL), BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW) }; int filter_len = sizeof(filter)/sizeof(filter[0]); /* interpret negative jumps as end-of-program-relative */ for (int i=0; i<filter_len; i++) { if (filter[i].jf >= (uint8_t)-8) filter[i].jf = filter_len + (int8_t)filter[i].jf - (i + 1); if (filter[i].jt >= (uint8_t)-8) filter[i].jt = filter_len + (int8_t)filter[i].jt - (i + 1); } struct sock_fprog prog = { .filter = filter, .len = sizeof(filter)/sizeof(filter[0]) }; /* turn on seccomp filter */ if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) err(1, "set NNP"); if (syscall(__NR_seccomp, SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_LOG, &prog)) err(1, "engage seccomp filter"); /* switch to untrusted protection keys state */ gatekey_exit_trusted(0); }
13e52d6e5828be8794b597b2999f1ba3373e9ada
9907672fcd81ab73ac63b2a83422a82bf31eadde
/codeforces/tyama_codeforces281A.c
80a7790f76e428efd482d5fdc75686ddb91d37b2
[ "0BSD" ]
permissive
cielavenir/procon
bbe1974b9bddb51b76d58722a0686a5b477c4456
746e1a91f574f20647e8aaaac0d9e6173f741176
refs/heads/master
2023-06-21T23:11:24.562546
2023-06-11T13:15:15
2023-06-11T13:15:15
7,557,464
137
136
null
2020-10-20T09:35:52
2013-01-11T09:40:26
C++
UTF-8
C
false
false
77
c
tyama_codeforces281A.c
main(c){putchar(toupper(getchar()));for(;~(c=getchar());)putchar(c);exit(0);}
a7178c0aebe5c21cfa83c55f13dc61c91be6b024
060c02561085a494df306deb2f3a8fddb984c73a
/src/gcrcell.c
17040c75aa3199351bb5e53fb4f48e0d8e737dd8
[ "MIT" ]
permissive
Interlisp/maiko
48631ae6abc9d98d5c3eeb5f5eb736adf400ea8f
7fce08f92c221bcb98e5f6d560aa50cb942e95b3
refs/heads/master
2023-09-03T12:23:43.081470
2023-08-09T21:04:51
2023-08-09T21:04:51
279,184,900
110
33
MIT
2023-09-13T14:49:28
2020-07-13T02:00:09
C
UTF-8
C
false
false
13,074
c
gcrcell.c
/* $Id: gcrcell.c,v 1.3 1999/05/31 23:35:32 sybalsky Exp $ (C) Copyright Venue, All Rights Reserved */ /************************************************************************/ /* */ /* (C) Copyright 1989-95 Venue. All Rights Reserved. */ /* Manufactured in the United States of America. */ /* */ /************************************************************************/ #include "version.h" /*************************************************************************/ /* */ /* File Name : gcrcell.c */ /* */ /*************************************************************************/ /* */ /* Creation Date : July-7-1987 */ /* Written by Tomoru Teruuchi */ /* */ /*************************************************************************/ /* */ /* Functions : */ /* gcreccell(cell); */ /* freelistcell(cell); */ /* */ /* */ /*************************************************************************/ /* Description : */ /* */ /* The functions "gcreccell" and "freelistcell" are the translated */ /* functions from the Lisp functions "\GCRECLAIMCELL" that is the UFN */ /* function of the opcode "RECLAIMCELL", and "\FREELISTCELL". */ /* These functions may have the following characteristics : */ /* */ /* gcreccell(cell) LispPTR cell */ /* This function may always return NIL(= 0), as the Lisp */ /* macro .RECLAIMCELLLP. in more upper level may use this */ /* return value as the further Garbage's pointer.(The Opcode*/ /* "RECLAIMCELL"'s function is specified as this, but its */ /* UFN function is not. The gcreccell function's */ /* behavior is same as the UFN function for speed and */ /* simplicity,this is, this function is closed in this level*/ /* ) */ /* This function may reclaim the data of all types that is */ /* Garbage.Especially, the data whose types are ARRAYBLOCK */ /* (= 0), STACKP(= 8),VMEMPAGEP(= 10) and CODEBLOCK(= 54,55,*/ /* 56,57,58,59,60,61,62,63) may be reclaimed by each special*/ /* processes that are specified and invoked by this function*/ /* .The data whose type is LISTP is the main data type */ /* processed in this function actually and only then the */ /* function "freelistcell" may be called for making linkage */ /* of free list. */ /* */ /* freelistcell(cell) LispPTR cell */ /* This function may make the linkage of free list of the */ /* cons cell.The header of this linkage is DTD->NEXTPAGE of */ /* LISTP and each cons page has its internal linkage of free*/ /* cells.This return value is not considered as not used. */ /* */ /*************************************************************************/ /* \Tomtom */ /*************************************************************************/ #include <stdio.h> // for printf #include "address.h" // for POINTER_PAGE #include "adr68k.h" // for NativeAligned4FromLAddr, NativeAligned4FromLPage #include "car-cdrdefs.h" // for car, cdr #include "cell.h" // for conspage, freecons, FREECONS, CDR_INDIRECT #include "commondefs.h" // for error #include "gccodedefs.h" // for reclaimcodeblock #include "gcdata.h" // for DELREF, REC_GCLOOKUPV, ADDREF, REC_GCLOOKUP #include "gcfinaldefs.h" // for reclaimarrayblock, reclaimstackp, releasing... #include "gcrcelldefs.h" // for freelistcell, gcreccell #include "lispemul.h" // for LispPTR, ConsCell, NIL, POINTERMASK, DLword #include "lspglob.h" // for ListpDTD #include "lsptypes.h" // for dtd, GetDTD, GetTypeNumber, TYPE_ARRAYBLOCK #ifdef DTDDEBUG #include "testtooldefs.h" #endif #ifdef NEWCDRCODING #undef CONSPAGE_LAST #define CONSPAGE_LAST 0x0ffffffff #else #undef CONSPAGE_LAST #define CONSPAGE_LAST 0x0ffff #endif /* NEWCDRCODING */ #define TODO_LIMIT 1000 #define ADD_TO_DO(ptr, offset) \ do { \ if (do_count < TODO_LIMIT) { \ if ((ptr) & 0xF0000000) error("illegal ptr in addtodo"); \ to_do[do_count] = (ptr); \ to_do_offset[do_count] = offset; \ todo_uses++; \ /*REC_GCLOOKUP((ptr), ADDREF);*/ \ do_count++; \ } else { /* error("GC missing some to-do's"); */ \ todo_misses++; \ } \ } while (0) static unsigned todo_uses = 0; static unsigned todo_misses = 0; static unsigned todo_reads = 0; /************************************************************************/ /* */ /* g c r e c c e l l */ /* */ /* Reclaim a cell, doing necessary finalization &c. */ /* */ /************************************************************************/ LispPTR gcreccell(LispPTR cell) { ConsCell *ptr; struct dtd *typdtd; DLword typ; LispPTR tmpptr, donext, tmpcell, val; LispPTR ptrfield, carfield; int index, code; LispPTR *field; #ifdef NEWCDRCODING LispPTR to_do[TODO_LIMIT]; /* table of pointers to follow, since Cdr coding lost */ short to_do_offset[TODO_LIMIT]; /* offset in datatype */ unsigned do_count = 0; /* counter of entries in to_do table */ #endif /* NEWCDRCODING */ val = NIL; tmpptr = cell; index = -1; donext = NIL; lp: ptr = (ConsCell *)NativeAligned4FromLAddr(tmpptr & -2); /* # ifdef CHECK if (refcnt(tmpptr) != 1) error("reclaiming cell w/refcnt not 1"); # endif */ #ifdef DEBUG if (tmpptr & 1) error("Reclaiming cell pointer with low bit 1."); #else tmpptr &= -2; /* turn off low bit of pointer, so we never reclaim odd'ns */ #endif if ((tmpptr & 0x0FFF0000) == 0x60000) error("freeing an old atom??"); typ = GetTypeNumber(tmpptr); #ifdef DEBUG if (typ == 6) printf("Reclaiming array ptr 0x%x.\n", tmpptr); #endif switch (typ) { case TYPE_LISTP: { if ((code = ptr->cdr_code) == CDR_INDIRECT) /* indirect */ { tmpcell = ptr->car_field; /* Monitor */ freelistcell(tmpptr); ptr = (ConsCell *)NativeAligned4FromLAddr(tmpcell); tmpptr = tmpcell; code = ptr->cdr_code; } if (index != -1) /* car part */ index = -1; else { REC_GCLOOKUPV(car(tmpptr), DELREF, val); if (val != NIL) { ptr->car_field = donext; ptr->cdr_code = code; donext = tmpptr; goto doval; } } REC_GCLOOKUPV(cdr(tmpptr), DELREF, val); if (code <= CDR_MAXINDIRECT) { #ifdef NEWCDRCODING tmpcell = tmpptr + ((code - CDR_INDIRECT) << 1); #else tmpcell = POINTER_PAGEBASE(tmpptr) + ((code - CDR_INDIRECT) << 1); #endif /* NEWCDRCODING */ freelistcell(tmpcell); } freelistcell(tmpptr); goto doval; } case TYPE_ARRAYBLOCK: if ((index == -1) && reclaimarrayblock(tmpptr)) goto trynext; else break; case TYPE_STACKP: if ((index == -1) && reclaimstackp(tmpptr)) goto trynext; break; case TYPE_VMEMPAGEP: if ((index == -1) && releasingvmempage(tmpptr)) { goto trynext; } else break; case TYPE_CODEHUNK1: case TYPE_CODEHUNK2: case TYPE_CODEHUNK3: case TYPE_CODEHUNK4: case TYPE_CODEHUNK5: case TYPE_CODEHUNK6: case TYPE_CODEHUNK7: case TYPE_CODEHUNK8: case TYPE_CODEHUNK9: case TYPE_CODEHUNK10: if ((index == -1) && reclaimcodeblock(tmpptr)) goto trynext; else break; default:; } normal: typdtd = (struct dtd *)GetDTD(typ); ptrfield = typdtd->dtd_ptrs; if (index != -1) { index = (index << 1); ptrfield = cdr(ptrfield); while ((car(ptrfield) & 0x0ffff) != index) ptrfield = cdr(ptrfield); index = -1; } while (ptrfield != NIL) { carfield = car(ptrfield); ptrfield = cdr(ptrfield); carfield &= 0x0ffff; REC_GCLOOKUPV((POINTERMASK & *(LispPTR *)NativeAligned4FromLAddr(tmpptr + carfield)), DELREF, val); #ifndef NEWCDRCODING if (val != NIL) { if (ptrfield != NIL) { ptr = (ConsCell *)NativeAligned4FromLAddr(tmpptr); ptr->car_field = donext; ptr->cdr_code = ((car(ptrfield) & 0x0ffff) >> 1); donext = tmpptr; goto doval; } else goto addtofreelist; } #else if (val != NIL) { if (ptrfield != NIL) { if ((carfield = car(ptrfield) & 0x0ffff) >> 1 < 15) { ptr = (ConsCell *)NativeAligned4FromLAddr(tmpptr); ptr->car_field = donext; ptr->cdr_code = ((car(ptrfield) & 0x0ffff) >> 1); donext = tmpptr; goto doval; } else { ADD_TO_DO(tmpptr, (car(ptrfield) & 0xffff) >> 1); goto doval; } } else goto addtofreelist; } #endif /* NEWCDRCODING */ } addtofreelist: field = (LispPTR *)NativeAligned4FromLAddr(tmpptr); *field = typdtd->dtd_free; typdtd->dtd_free = tmpptr & POINTERMASK; #ifdef DTDDEBUG check_dtd_chain(GetTypeNumber(tmpptr & POINTERMASK)); #endif /******************************/ /* */ /* Freeing one cell made another cell's refcnt = 0. */ /* ADDREF the second cell (to remove it from the GC table) */ /* and reclaim it. */ /************************************************************/ doval: if (val != NIL) { tmpptr = val; REC_GCLOOKUP(tmpptr, ADDREF); /* GCLOOKUP(0x8000, ADDREF,tmpptr); */ val = NIL; goto lp; } /***************************************************************/ /* */ /* Finished freeing the main cell, but we may have saved other */ /* cells whose refcnt's went to 0 along the way. This is */ /* where we work down the list of saved items to free. */ /* */ /****************************************************************/ trynext: if (donext != NIL) { tmpptr = donext; ptr = (ConsCell *)NativeAligned4FromLAddr(tmpptr); donext = (LispPTR)ptr->car_field; index = ptr->cdr_code; goto lp; } #ifdef NEWCDRCODING if (do_count) /* If there are other cells to collect */ { do_count--; tmpptr = to_do[do_count]; index = to_do_offset[do_count]; todo_reads++; /*REC_GCLOOKUP(tmpptr, ADDREF); */ goto lp; } #endif /*NEWCDRCODING */ return (NIL); } /************************************************************************/ /* */ /* f r e e l i s t c e l l */ /* */ /* */ /* */ /************************************************************************/ void freelistcell(LispPTR cell) { struct conspage *pbase; ConsCell *cell68k; unsigned int offset, prior, celloffset; cell68k = (ConsCell *)NativeAligned4FromLAddr(cell); pbase = (struct conspage *)NativeAligned4FromLPage(POINTER_PAGE(cell)); celloffset = (LispPTR)cell & 0xFF; #ifdef NEWCDRCODING if (celloffset < 8) error("freeing CONS cell that's really freelist ptr"); #endif /* NEWCDRCODING */ if (pbase->count) /* There are free cells on the page already */ { prior = 0; for (offset = pbase->next_cell; offset; offset = FREECONS(pbase, offset)->next_free) { #ifdef NEWCDRCODING if ((6 ^ offset) < (6 ^ celloffset)) #else if (offset < celloffset) #endif /* NEWCDRCODING */ { break; } prior = offset; } if (prior) FREECONS(pbase, prior)->next_free = celloffset; else pbase->next_cell = celloffset; ((freecons *)cell68k)->next_free = offset; } else /* NO FREE CELLS. Just replace next_free. */ { pbase->next_cell = celloffset; FREECONS(pbase, celloffset)->next_free = 0; /* And this is end of the chain */ } if ((++pbase->count > 32) && (pbase->next_page == CONSPAGE_LAST)) { pbase->next_page = ListpDTD->dtd_nextpage; ListpDTD->dtd_nextpage = POINTER_PAGE(cell); } }
88a17cbee8d342158c0e4d15bd420a8e05c64aeb
192f6a4c9d934be58bca0e610ec1a75e7777fcd1
/src/gc/gc_private.h
c31188cffdcee1e806f88d3c5d3dca8070bba516
[ "Artistic-2.0" ]
permissive
parrot/parrot
39a74fbb015829cef901211d6d173b71eea475ea
f89a111c06ad0367817c52fda6ff5c24165c005b
refs/heads/master
2023-07-20T07:41:40.386067
2021-08-25T17:59:15
2021-08-25T17:59:15
1,071,734
450
134
null
2016-11-09T10:57:41
2010-11-11T15:14:10
C
UTF-8
C
false
false
35,175
h
gc_private.h
/* Copyright (C) 2001-2015, Parrot Foundation. =head1 NAME src/gc/gc_private.h - private header file for the GC subsystem =head1 DESCRIPTION This is a private header file for the GC subsystem. It contains definitions that are only for use in the GC and don't need to be included in the rest of Parrot. =head2 Private Functions =over 4 =cut */ #ifndef PARROT_GC_PRIVATE_H_GUARD #define PARROT_GC_PRIVATE_H_GUARD #include "parrot/settings.h" #include "variable_size_pool.h" #if ! DISABLE_GC_DEBUG /* Set when walking the system stack. Defined in src/gc/system.c */ extern int CONSERVATIVE_POINTER_CHASING; #endif #ifndef MEMORY_DEBUG # define MEMORY_DEBUG_DETAIL_2(s, a1, a2) # define MEMORY_DEBUG_DETAIL_3(s, a1, a2, a3) # define GC_DEBUG_DETAIL(s) # define GC_DEBUG_DETAIL_FLAGS(s, pmc) # define GC_DEBUG_DETAIL_STR(s, str) # define GC_DEBUG_DETAIL_1_FLAGS(s, a1, pmc) # define GC_DEBUG_DETAIL_1(s, a1) # define GC_DEBUG_DETAIL_2(s, a1, a2) # define GC_DEBUG_DETAIL_3(s, a1, a2, a3) # define MEMORY_DEBUG_UNUSED(interp) UNUSED(interp) #else # define MEMORY_DEBUG_UNUSED(interp) # define MEMORY_DEBUG_DETAIL_2(s, a1, a2) \ if (Interp_debug_TEST(interp, \ PARROT_MEM_STAT_DEBUG_FLAG | PARROT_MEM_DETAIL_DEBUG_FLAG)) \ fprintf(stderr, (s), (a1), (a2)) # define MEMORY_DEBUG_DETAIL_3(s, a1, a2, a3) \ if (Interp_debug_TEST(interp, \ PARROT_MEM_STAT_DEBUG_FLAG | PARROT_MEM_DETAIL_DEBUG_FLAG)) \ fprintf(stderr, (s), (a1), (a2), (a3)) # define GC_DEBUG_DETAIL(s) \ if (Interp_debug_TEST(interp, \ PARROT_MEM_STAT_DEBUG_FLAG | PARROT_GC_DETAIL_DEBUG_FLAG)) \ fprintf(stderr, (s)) # define GC_DEBUG_DETAIL_FLAGS(s, pmc) \ if (Interp_debug_TEST(interp, \ PARROT_MEM_STAT_DEBUG_FLAG | PARROT_GC_DETAIL_DEBUG_FLAG)) { \ fprintf(stderr, (s)); trace_pmc_dump(interp, (pmc)); fprintf(stderr, "\n"); } # define GC_DEBUG_DETAIL_STR(s, str) \ if (Interp_debug_TEST(interp, \ PARROT_MEM_STAT_DEBUG_FLAG | PARROT_GC_DETAIL_DEBUG_FLAG)) { \ fprintf(stderr, (s)); trace_str_dump(interp, (str)); fprintf(stderr, "\n"); } # define GC_DEBUG_DETAIL_1_FLAGS(s, a1, pmc) \ if (Interp_debug_TEST(interp, \ PARROT_MEM_STAT_DEBUG_FLAG | PARROT_GC_DETAIL_DEBUG_FLAG)) { \ fprintf(stderr, (s), (a1)); trace_pmc_dump(interp, (pmc)); fprintf(stderr, "\n"); } # define GC_DEBUG_DETAIL_1(s, a1) \ if (Interp_debug_TEST(interp, \ PARROT_MEM_STAT_DEBUG_FLAG | PARROT_GC_DETAIL_DEBUG_FLAG)) \ fprintf(stderr, (s), (a1)) # define GC_DEBUG_DETAIL_2(s, a1, a2) \ if (Interp_debug_TEST(interp, \ PARROT_MEM_STAT_DEBUG_FLAG | PARROT_GC_DETAIL_DEBUG_FLAG)) \ fprintf(stderr, (s), (a1), (a2)) # define GC_DEBUG_DETAIL_3(s, a1, a2, a3) \ if (Interp_debug_TEST(interp, \ PARROT_MEM_STAT_DEBUG_FLAG | PARROT_GC_DETAIL_DEBUG_FLAG)) \ fprintf(stderr, (s), (a1), (a2), (a3)) #endif #define PANIC_OUT_OF_MEM(size) panic_failed_allocation(__LINE__, (size)) /* =item C<static void panic_failed_allocation(unsigned int line, size_t size)> Print an error message and die. =cut */ PARROT_DOES_NOT_RETURN static void panic_failed_allocation(unsigned int line, size_t size) { fprintf(stderr, "Failed allocation of "SIZE_FMT" bytes\n", size); Parrot_x_panic_and_exit(NULL, "Out of mem", __FILE__, line); } #ifdef __ia64__ # include <ucontext.h> extern void *flush_reg_store(void); # define BACKING_STORE_BASE 0x80000fff80000000 # ifdef __hpux # include <sys/pstat.h> # include <ia64/sys/inline.h> # endif /* __hpux */ #endif /* __ia64__ */ /* the percent of used Arena items at which to trace next time through */ #define GC_DEBUG_REPLENISH_LEVEL_FACTOR 0.0 #define GC_DEBUG_UNITS_PER_ALLOC_GROWTH_FACTOR 1 #define REPLENISH_LEVEL_FACTOR 0.5 /* this factor is totally arbitrary, but gives good timings for stress.pasm */ #define UNITS_PER_ALLOC_GROWTH_FACTOR 1.75 #define POOL_MAX_BYTES (65536 * 128) #define GC_SIZE_THRESHOLD (1024 * 1024) #define GC_DEFAULT_DYNAMIC_THRESHOLD 75 #define GC_DEFAULT_MIN_THRESHOLD (4 * 1024 * 1024) /* promills of system memory */ #define GC_DEFAULT_NURSERY_SIZE 2 #define PMC_HEADERS_PER_ALLOC (4096 * 10 / sizeof (PMC)) #define BUFFER_HEADERS_PER_ALLOC (4096 / sizeof (Parrot_Buffer)) #define STRING_HEADERS_PER_ALLOC (4096 * 20 / sizeof (STRING)) #define CONSTANT_PMC_HEADERS_PER_ALLOC (4096 / sizeof (PMC)) #define GET_SIZED_POOL_IDX(x) ((x) / sizeof (void *)) #define GC_NUM_INITIAL_FIXED_SIZE_POOLS 128 /* these values are used for the attribute allocator */ #define GC_ATTRIB_POOLS_HEADROOM 8 #define GC_FIXED_SIZE_POOL_SIZE 4096 /* Set to 1 if we want to use the fixed-size allocator. Set to 0 if we want to allocate these things using mem_sys_allocate instead */ #define GC_USE_FIXED_SIZE_ALLOCATOR 1 /* We're using this here to add an additional pointer to a PObj without having to actually add an entire pointer to every PObj-alike structure in Parrot. Astute observers may notice that if the PObj is comprised of only an INTVAL, then there are some systems where sizeof(PObj*) can be larger then sizeof(PObj), thus creating overflow. However PObjs are never used by themselves, things like PMCs and STRINGs are cast to PObj in the GC, so we should have plenty of space. */ typedef struct GC_MS_PObj_Wrapper { size_t flags; struct GC_MS_PObj_Wrapper * next_ptr; } GC_MS_PObj_Wrapper; /* how often to skip a full GC when this pool has nothing free */ typedef enum _gc_skip_type_enum { GC_NO_SKIP = 0, GC_ONE_SKIP, /* unused */ GC_ALWAYS_SKIP, GC_NEVER_SKIP /* unused */ } gc_skip_type_enum; /** statistics for GC **/ typedef struct GC_Statistics { size_t gc_mark_runs; /* Number of times we've done a mark run */ size_t gc_lazy_mark_runs; /* Number of successful lazy mark runs */ size_t gc_collect_runs; /* Number of times we've done a memory compaction, currently for strings only. */ size_t mem_allocs_since_last_collect; /* The number of memory * allocations from the * system since the last * compaction run. * UNUSED, ALWAYS 0 */ size_t header_allocs_since_last_collect; /* The size of header * blocks allocated from * the system since the last * GC run. * UNUSED, ALWAYS 0 */ size_t memory_allocated; /* The total amount of memory allocated * in fixed and variable size pools. * Doesn't count memory for internal * structures */ size_t memory_used; /* The total amount of memory used * in fixed and variable size * pools. Also includes memory in * variable size pools that has been * freed but can only be reclaimed * by a GC run */ size_t mem_used_last_collect; /* The total amount of * memory used after * the last GC run */ UINTVAL memory_collected; /* Total amount of memory copied during collection */ } GC_Statistics; /* Callback for live string. Use Parrot_Buffer for now... */ typedef void (*string_iterator_callback)(PARROT_INTERP, Parrot_Buffer *str, void *data); typedef struct GC_Subsystem { /* Which GC subsystem are we using? See PARROT_GC_DEFAULT_TYPE in * include/parrot/settings.h for possible values */ gc_sys_type_enum sys_type; /** Function hooks that each subsystem MUST provide */ void (*finalize_gc_system) (PARROT_INTERP); void (*destroy_child_interp)(ARGMOD(Interp *dest_interp), ARGIN(Interp *child_interp)); void (*maybe_gc_mark)(PARROT_INTERP, UINTVAL flags); void (*do_gc_mark)(PARROT_INTERP, UINTVAL flags); void (*compact_string_pool)(PARROT_INTERP); void (*mark_special)(PARROT_INTERP, ARGMOD(PMC *pmc)); void (*pmc_needs_early_collection)(PARROT_INTERP, ARGMOD(PMC *)); void (*init_pool)(PARROT_INTERP, ARGMOD(struct Fixed_Size_Pool *)); PMC* (*allocate_pmc_header)(PARROT_INTERP, UINTVAL flags); void (*free_pmc_header)(PARROT_INTERP, ARGFREE(PMC *)); STRING* (*allocate_string_header)(PARROT_INTERP, UINTVAL flags); void (*free_string_header)(PARROT_INTERP, ARGFREE(STRING *)); Parrot_Buffer* (*allocate_bufferlike_header)(PARROT_INTERP, size_t size); void (*free_bufferlike_header)(PARROT_INTERP, ARGFREE(Parrot_Buffer *), size_t size); int (*is_pmc_ptr)(PARROT_INTERP, ARGIN_NULLOK(void *)); int (*is_string_ptr)(PARROT_INTERP, ARGIN_NULLOK(void *)); void (*mark_str_header)(PARROT_INTERP, ARGMOD(STRING *)); void (*mark_pmc_header)(PARROT_INTERP, ARGMOD(PMC *)); void* (*allocate_pmc_attributes)(PARROT_INTERP, ARGMOD(PMC *)); void (*free_pmc_attributes)(PARROT_INTERP, ARGFREE(PMC *)); void (*allocate_string_storage)(PARROT_INTERP, ARGMOD(STRING *str), size_t size); void (*reallocate_string_storage)(PARROT_INTERP, ARGMOD(STRING *str), size_t size); void (*allocate_buffer_storage)(PARROT_INTERP, ARGMOD(Parrot_Buffer *buffer), size_t nsize); void (*reallocate_buffer_storage)(PARROT_INTERP, ARGMOD(Parrot_Buffer *buffer), size_t newsize); void* (*allocate_fixed_size_storage)(PARROT_INTERP, size_t size); void (*free_fixed_size_storage)(PARROT_INTERP, size_t size, ARGFREE(void *)); void* (*allocate_memory_chunk)(PARROT_INTERP, size_t size); void* (*reallocate_memory_chunk)(PARROT_INTERP, ARGFREE(void *data), size_t newsize); void* (*allocate_memory_chunk_with_interior_pointers)(PARROT_INTERP, size_t size); void* (*reallocate_memory_chunk_with_interior_pointers)(PARROT_INTERP, ARGFREE(void *data), size_t oldsize, size_t newsize); void (*free_memory_chunk)(PARROT_INTERP, ARGFREE(void *data)); /* locks and semaphores for the 3 phases or threaded access */ void (*block_mark)(PARROT_INTERP); void (*unblock_mark)(PARROT_INTERP); unsigned int (*is_blocked_mark)(PARROT_INTERP); void (*block_mark_locked)(PARROT_INTERP); void (*unblock_mark_locked)(PARROT_INTERP); void (*block_sweep)(PARROT_INTERP); void (*unblock_sweep)(PARROT_INTERP); unsigned int (*is_blocked_sweep)(PARROT_INTERP); void (*block_move)(PARROT_INTERP); void (*unblock_move)(PARROT_INTERP); unsigned int (*is_blocked_move)(PARROT_INTERP); /* Introspection. Each GC must provide this function. Even with fake data */ /* Return by value to simplify memory management */ size_t (*get_gc_info)(PARROT_INTERP, Interpinfo_enum); /* Get boundaries of allocated memory. Used during scanning of C stack */ void* (*get_low_str_ptr)(PARROT_INTERP); void* (*get_high_str_ptr)(PARROT_INTERP); void* (*get_low_pmc_ptr)(PARROT_INTERP); void* (*get_high_pmc_ptr)(PARROT_INTERP); /* Iterate over _live_ strings. Used for string pool compacting */ void (*iterate_live_strings)(PARROT_INTERP, string_iterator_callback callback, void *data); /* Write barrier */ void (*write_barrier)(PARROT_INTERP, ARGMOD(PMC *)); /* Statistic for GC */ struct GC_Statistics stats; /* Holds system-specific data structures */ void * gc_private; } GC_Subsystem; /* This header structure describes an arena: a block of memory that is part of a fixed-sized pool. The arena has enough memory for 'total_objects' objects of a particular size specified in the pool. */ typedef struct Fixed_Size_Arena { size_t used; /* Number of objects slots used. */ size_t total_objects; /* Total number of object slots. */ struct Fixed_Size_Arena *prev; /* Pointer to previous arena. */ struct Fixed_Size_Arena *next; /* Pointer to next arena. */ void *start_objects; /* Pointer to arena memory. */ } Fixed_Size_Arena; /* This simple header structure describes a free PMC attribute object. A list of them hang off the PMC attribute pool. */ typedef struct PMC_Attribute_Free_List { struct PMC_Attribute_Free_List * next; /* Pointer to next free object. */ } PMC_Attribute_Free_List; /* This header structure describes a PMC attribute arena: A block of memory that is part of a PMC attribute pool. The allocatable memory follows this header. */ typedef struct PMC_Attribute_Arena { struct PMC_Attribute_Arena * next; /* Pointer to next arena. */ struct PMC_Attribute_Arena * prev; /* Pointer to previous arena. */ } PMC_Attribute_Arena; /* This structure describes a PMC attribute pool. A vector of them hang off the Memory_Pools root structure. */ typedef struct PMC_Attribute_Pool { size_t attr_size; /* Size of attribute object. */ size_t total_objects; /* Total objects in the pool. */ size_t objects_per_alloc; /* Number of object slots to allocate. */ size_t num_free_objects; /* Number of objects on the free list. */ PMC_Attribute_Free_List * free_list; /* List of free object slots, or NULL. */ PMC_Attribute_Arena * top_arena; /* Pointer to most recent arena. */ PMC_Attribute_Free_List * newfree; /* Pointer to next object slot in latest arena, or NULL (slots weren't put on free list). */ PMC_Attribute_Free_List * newlast; /* High water mark in arena. */ } PMC_Attribute_Pool; /* This structure describes a fixed-size memory pool. Various such pools hang off the Memory_Pools root structure. */ typedef struct Fixed_Size_Pool { size_t object_size; /* Size in bytes of an individual pool object. This size may include a GC system-specific GC header. */ size_t start_arena_memory; /* Address of the lowest arena. */ size_t end_arena_memory; /* And the highest one. */ Fixed_Size_Arena *last_Arena; /* Pointer to most recent arena. */ GC_MS_PObj_Wrapper * free_list; /* List of free object slots, or NULL. */ size_t num_free_objects; /* Number of objects on the free list. */ size_t total_objects; /* Total objects in the pool. */ PARROT_OBSERVER const char *name; /* Name of pool. */ size_t objects_per_alloc; /* Number of object slots to allocate. */ int skip; /* How often to skip full GC (see gc_skip_type_enum). */ size_t replenish_level; /* Replenish pool when free object slots goes below this level. */ add_free_object_fn_type add_free_object; /* Adds a free object to the pool's free list */ get_free_object_fn_type get_free_object; /* Gets and removes a free object from the pool's free list. */ alloc_objects_fn_type alloc_objects; /* Allocates an arena for objects. */ alloc_objects_fn_type more_objects; /* Obtain more free objects. */ gc_object_fn_type gc_object; /* GCs object during sweep. */ /* Contains GC system-specific data structures ... unused at the moment, * but this is where it should go when we need it ... union { } gc_private; */ void *newfree; /* Pointer to next object slot in latest arena, or NULL (slots weren't put on free list). */ void *newlast; /* High water mark in arena. */ } Fixed_Size_Pool; /* String GC subsystem data */ typedef struct String_GC { Variable_Size_Pool *memory_pool; /* General memory pool. */ Variable_Size_Pool *constant_string_pool; /* Constant string pool (not compacted */ } String_GC; typedef struct Memory_Pools { String_GC string_gc; Fixed_Size_Pool *string_header_pool; Fixed_Size_Pool *pmc_pool; Fixed_Size_Pool *constant_pmc_pool; Fixed_Size_Pool *constant_string_header_pool; Fixed_Size_Pool **sized_header_pools; PMC_Attribute_Pool **attrib_pools; size_t num_sized; size_t num_attribs; /* GC blocking */ UINTVAL gc_mark_block_level:8; /* Num of outstanding GC block requests */ UINTVAL gc_sweep_block_level:8; /* Num of outstanding GC block requests */ UINTVAL gc_move_block_level:8; /* for the compacting/move phase */ PMC *gc_mark_start; /* first PMC marked during a GC run */ PMC *gc_mark_ptr; /* last PMC marked during a GC run */ PMC *gc_trace_ptr; /* last PMC trace_children was called on */ int lazy_gc; /* flag that indicates whether we should stop when we've seen all impatient PMCs */ UINTVAL num_early_gc_PMCs; /* how many PMCs want immediate destruction */ UINTVAL num_early_PMCs_seen; /* how many such PMCs has GC seen */ /* private data for the GC subsystem */ void *gc_private; /* GC subsystem data */ } Memory_Pools; /* HEADERIZER BEGIN: src/gc/system.c */ /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ void trace_system_areas(PARROT_INTERP, ARGIN_NULLOK(const Memory_Pools *mem_pools)) __attribute__nonnull__(1); #define ASSERT_ARGS_trace_system_areas __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp)) /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ /* HEADERIZER END: src/gc/system.c */ /* HEADERIZER BEGIN: src/gc/mark_sweep.c */ /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ PARROT_WARN_UNUSED_RESULT INTVAL contained_in_pool( ARGIN(const Fixed_Size_Pool *pool), ARGIN(const void *ptr)) __attribute__nonnull__(1) __attribute__nonnull__(2); PARROT_CANNOT_RETURN_NULL Fixed_Size_Pool * get_bufferlike_pool(PARROT_INTERP, ARGMOD(Memory_Pools *mem_pools), size_t buffer_size) __attribute__nonnull__(1) __attribute__nonnull__(2) FUNC_MODIFIES(*mem_pools); PARROT_IGNORABLE_RESULT int /*@alt void@*/ header_pools_iterate_callback(PARROT_INTERP, ARGMOD(Memory_Pools *mem_pools), int flag, ARGIN_NULLOK(void *arg), NOTNULL(const pool_iter_fn func)) __attribute__nonnull__(1) __attribute__nonnull__(2) __attribute__nonnull__(5) FUNC_MODIFIES(*mem_pools); void initialize_fixed_size_pools(PARROT_INTERP, ARGMOD(Memory_Pools *mem_pools)) __attribute__nonnull__(1) __attribute__nonnull__(2) FUNC_MODIFIES(*mem_pools); void mark_special(PARROT_INTERP, Memory_Pools *mem_pools, ARGIN(PMC *obj)) __attribute__nonnull__(1) __attribute__nonnull__(3); void Parrot_add_to_free_list(PARROT_INTERP, ARGMOD(Fixed_Size_Pool *pool), ARGMOD(Fixed_Size_Arena *arena)) __attribute__nonnull__(2) __attribute__nonnull__(3) FUNC_MODIFIES(*pool) FUNC_MODIFIES(*arena); void Parrot_append_arena_in_pool(PARROT_INTERP, Memory_Pools *mem_pools, ARGMOD(Fixed_Size_Pool *pool), ARGMOD(Fixed_Size_Arena *new_arena), size_t size) __attribute__nonnull__(1) __attribute__nonnull__(3) __attribute__nonnull__(4) FUNC_MODIFIES(*pool) FUNC_MODIFIES(*new_arena); void Parrot_gc_clear_live_bits(PARROT_INTERP, ARGIN(const Fixed_Size_Pool *pool)) __attribute__nonnull__(2); void Parrot_gc_run_init(PARROT_INTERP, ARGMOD(Memory_Pools *mem_pools)) __attribute__nonnull__(2) FUNC_MODIFIES(*mem_pools); void Parrot_gc_sweep_pool(PARROT_INTERP, ARGMOD(Memory_Pools *mem_pools), ARGMOD(Fixed_Size_Pool *pool)) __attribute__nonnull__(1) __attribute__nonnull__(2) __attribute__nonnull__(3) FUNC_MODIFIES(*mem_pools) FUNC_MODIFIES(*pool); int Parrot_gc_trace_root(PARROT_INTERP, ARGMOD_NULLOK(Memory_Pools *mem_pools), Parrot_gc_trace_type trace) __attribute__nonnull__(1) FUNC_MODIFIES(*mem_pools); #define ASSERT_ARGS_contained_in_pool __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(pool) \ , PARROT_ASSERT_ARG(ptr)) #define ASSERT_ARGS_get_bufferlike_pool __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(mem_pools)) #define ASSERT_ARGS_header_pools_iterate_callback __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(mem_pools) \ , PARROT_ASSERT_ARG(func)) #define ASSERT_ARGS_initialize_fixed_size_pools __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(mem_pools)) #define ASSERT_ARGS_mark_special __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(obj)) #define ASSERT_ARGS_Parrot_add_to_free_list __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(pool) \ , PARROT_ASSERT_ARG(arena)) #define ASSERT_ARGS_Parrot_append_arena_in_pool __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(pool) \ , PARROT_ASSERT_ARG(new_arena)) #define ASSERT_ARGS_Parrot_gc_clear_live_bits __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(pool)) #define ASSERT_ARGS_Parrot_gc_run_init __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(mem_pools)) #define ASSERT_ARGS_Parrot_gc_sweep_pool __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(mem_pools) \ , PARROT_ASSERT_ARG(pool)) #define ASSERT_ARGS_Parrot_gc_trace_root __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp)) /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ /* HEADERIZER END: src/gc/mark_sweep.c */ /* HEADERIZER BEGIN: src/gc/alloc_resources.c */ /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ void check_buffer_ptr( ARGMOD(Parrot_Buffer * pobj), ARGMOD(Variable_Size_Pool * pool)) __attribute__nonnull__(1) __attribute__nonnull__(2) FUNC_MODIFIES(* pobj) FUNC_MODIFIES(* pool); void merge_pools( ARGMOD(Variable_Size_Pool *dest), ARGMOD(Variable_Size_Pool *source)) __attribute__nonnull__(1) __attribute__nonnull__(2) FUNC_MODIFIES(*dest) FUNC_MODIFIES(*source); void Parrot_gc_destroy_header_pools(PARROT_INTERP, ARGMOD(Memory_Pools *mem_pools)) __attribute__nonnull__(1) __attribute__nonnull__(2) FUNC_MODIFIES(*mem_pools); void Parrot_gc_merge_memory_pools( ARGMOD(Interp *dest_interp), ARGMOD(Memory_Pools *dest_arena), ARGIN(const Memory_Pools *source_arena)) __attribute__nonnull__(1) __attribute__nonnull__(2) __attribute__nonnull__(3) FUNC_MODIFIES(*dest_interp) FUNC_MODIFIES(*dest_arena); #define ASSERT_ARGS_check_buffer_ptr __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(pobj) \ , PARROT_ASSERT_ARG(pool)) #define ASSERT_ARGS_merge_pools __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(dest) \ , PARROT_ASSERT_ARG(source)) #define ASSERT_ARGS_Parrot_gc_destroy_header_pools \ __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(mem_pools)) #define ASSERT_ARGS_Parrot_gc_merge_memory_pools __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(dest_interp) \ , PARROT_ASSERT_ARG(dest_arena) \ , PARROT_ASSERT_ARG(source_arena)) /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ /* HEADERIZER END: src/gc/alloc_resources.c */ /* GC subsystem init functions */ /* HEADERIZER BEGIN: src/gc/gc_ms.c */ /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ void gc_ms_allocate_buffer_storage(PARROT_INTERP, ARGIN(Parrot_Buffer *str), size_t size) __attribute__nonnull__(1) __attribute__nonnull__(2); PARROT_CANNOT_RETURN_NULL void * gc_ms_allocate_fixed_size_storage(PARROT_INTERP, size_t size) __attribute__nonnull__(1); void gc_ms_allocate_string_storage(PARROT_INTERP, ARGIN(STRING *str), size_t size) __attribute__nonnull__(1) __attribute__nonnull__(2); void gc_ms_compact_memory_pool(PARROT_INTERP) __attribute__nonnull__(1); void gc_ms_free_fixed_size_storage(PARROT_INTERP, size_t size, ARGFREE_NOTNULL(void *data)) __attribute__nonnull__(1) __attribute__nonnull__(3); void gc_ms_free_pmc_attributes(PARROT_INTERP, ARGMOD(PMC *pmc)) __attribute__nonnull__(1) __attribute__nonnull__(2) FUNC_MODIFIES(*pmc); void gc_ms_mark_pmc_header(PARROT_INTERP, ARGMOD_NULLOK(PMC *obj)) __attribute__nonnull__(1) FUNC_MODIFIES(*obj); void gc_ms_pmc_needs_early_collection(PARROT_INTERP, ARGMOD(PMC *pmc)) __attribute__nonnull__(1) __attribute__nonnull__(2) FUNC_MODIFIES(*pmc); void gc_ms_reallocate_buffer_storage(PARROT_INTERP, ARGIN(Parrot_Buffer *str), size_t size) __attribute__nonnull__(1) __attribute__nonnull__(2); void gc_ms_reallocate_string_storage(PARROT_INTERP, ARGIN(STRING *str), size_t size) __attribute__nonnull__(1) __attribute__nonnull__(2); PARROT_WARN_UNUSED_RESULT PARROT_PURE_FUNCTION size_t Parrot_gc_get_info(PARROT_INTERP, Interpinfo_enum which, ARGIN(GC_Statistics *stats)) __attribute__nonnull__(3); void Parrot_gc_ms_init(PARROT_INTERP, Parrot_GC_Init_Args *args) __attribute__nonnull__(1); PARROT_WARN_UNUSED_RESULT PARROT_PURE_FUNCTION int Parrot_gc_ms_needed(PARROT_INTERP) __attribute__nonnull__(1); #define ASSERT_ARGS_gc_ms_allocate_buffer_storage __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(str)) #define ASSERT_ARGS_gc_ms_allocate_fixed_size_storage \ __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp)) #define ASSERT_ARGS_gc_ms_allocate_string_storage __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(str)) #define ASSERT_ARGS_gc_ms_compact_memory_pool __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp)) #define ASSERT_ARGS_gc_ms_free_fixed_size_storage __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(data)) #define ASSERT_ARGS_gc_ms_free_pmc_attributes __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(pmc)) #define ASSERT_ARGS_gc_ms_mark_pmc_header __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp)) #define ASSERT_ARGS_gc_ms_pmc_needs_early_collection \ __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(pmc)) #define ASSERT_ARGS_gc_ms_reallocate_buffer_storage \ __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(str)) #define ASSERT_ARGS_gc_ms_reallocate_string_storage \ __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(str)) #define ASSERT_ARGS_Parrot_gc_get_info __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(stats)) #define ASSERT_ARGS_Parrot_gc_ms_init __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp)) #define ASSERT_ARGS_Parrot_gc_ms_needed __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp)) /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ /* HEADERIZER END: src/gc/gc_ms.c */ /* HEADERIZER BEGIN: src/gc/gc_inf.c */ /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ void Parrot_gc_inf_init(PARROT_INTERP, Parrot_GC_Init_Args *args) __attribute__nonnull__(1); #define ASSERT_ARGS_Parrot_gc_inf_init __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp)) /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ /* HEADERIZER END: src/gc/gc_inf.c */ /* HEADERIZER BEGIN: src/gc/gc_ms2.c */ /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ void gc_ms2_print_stats_always(PARROT_INTERP, ARGIN(const char* header)) __attribute__nonnull__(1) __attribute__nonnull__(2); void Parrot_gc_ms2_init(PARROT_INTERP, ARGIN(Parrot_GC_Init_Args *args)) __attribute__nonnull__(1) __attribute__nonnull__(2); #define ASSERT_ARGS_gc_ms2_print_stats_always __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(header)) #define ASSERT_ARGS_Parrot_gc_ms2_init __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(args)) /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ /* HEADERIZER END: src/gc/gc_ms2.c */ /* HEADERIZER BEGIN: src/gc/gc_gms.c */ /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ void gc_gms_print_stats_always(PARROT_INTERP, ARGIN(const char* header)) __attribute__nonnull__(1) __attribute__nonnull__(2); void Parrot_gc_gms_init(PARROT_INTERP, ARGIN(Parrot_GC_Init_Args *args)) __attribute__nonnull__(1) __attribute__nonnull__(2); int pobj2gen(ARGIN(PObj *pmc)) __attribute__nonnull__(1); #define ASSERT_ARGS_gc_gms_print_stats_always __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(header)) #define ASSERT_ARGS_Parrot_gc_gms_init __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(args)) #define ASSERT_ARGS_pobj2gen __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(pmc)) /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ /* HEADERIZER END: src/gc/gc_gms.c */ /* HEADERIZER BEGIN: src/gc/string_gc.c */ /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ void Parrot_gc_str_allocate_buffer_storage(PARROT_INTERP, ARGIN(String_GC *gc), ARGOUT(Parrot_Buffer *buffer), size_t size) __attribute__nonnull__(1) __attribute__nonnull__(2) __attribute__nonnull__(3) FUNC_MODIFIES(*buffer); void Parrot_gc_str_allocate_string_storage(PARROT_INTERP, ARGIN(String_GC *gc), ARGMOD(STRING *str), size_t size) __attribute__nonnull__(1) __attribute__nonnull__(2) __attribute__nonnull__(3) FUNC_MODIFIES(*str); void Parrot_gc_str_compact_pool(PARROT_INTERP, ARGIN(String_GC *gc)) __attribute__nonnull__(1) __attribute__nonnull__(2); void Parrot_gc_str_finalize(PARROT_INTERP, ARGMOD(String_GC *gc)) __attribute__nonnull__(2) FUNC_MODIFIES(*gc); void Parrot_gc_str_free_buffer_storage(PARROT_INTERP, ARGIN(String_GC *gc), ARGMOD(Parrot_Buffer *b)) __attribute__nonnull__(2) __attribute__nonnull__(3) FUNC_MODIFIES(*b); void Parrot_gc_str_initialize(PARROT_INTERP, ARGMOD(String_GC *gc)) __attribute__nonnull__(1) __attribute__nonnull__(2) FUNC_MODIFIES(*gc); void Parrot_gc_str_reallocate_buffer_storage(PARROT_INTERP, ARGIN(String_GC *gc), ARGMOD(Parrot_Buffer *buffer), size_t newsize) __attribute__nonnull__(1) __attribute__nonnull__(2) __attribute__nonnull__(3) FUNC_MODIFIES(*buffer); void Parrot_gc_str_reallocate_string_storage(PARROT_INTERP, ARGIN(String_GC *gc), ARGMOD(STRING *str), size_t newsize) __attribute__nonnull__(1) __attribute__nonnull__(2) __attribute__nonnull__(3) FUNC_MODIFIES(*str); #define ASSERT_ARGS_Parrot_gc_str_allocate_buffer_storage \ __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(gc) \ , PARROT_ASSERT_ARG(buffer)) #define ASSERT_ARGS_Parrot_gc_str_allocate_string_storage \ __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(gc) \ , PARROT_ASSERT_ARG(str)) #define ASSERT_ARGS_Parrot_gc_str_compact_pool __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(gc)) #define ASSERT_ARGS_Parrot_gc_str_finalize __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(gc)) #define ASSERT_ARGS_Parrot_gc_str_free_buffer_storage \ __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(gc) \ , PARROT_ASSERT_ARG(b)) #define ASSERT_ARGS_Parrot_gc_str_initialize __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(gc)) #define ASSERT_ARGS_Parrot_gc_str_reallocate_buffer_storage \ __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(gc) \ , PARROT_ASSERT_ARG(buffer)) #define ASSERT_ARGS_Parrot_gc_str_reallocate_string_storage \ __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(gc) \ , PARROT_ASSERT_ARG(str)) /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ /* HEADERIZER END: src/gc/string_gc.c */ #endif /* PARROT_GC_PRIVATE_H_GUARD */ /* =back =cut */ /* * Local variables: * c-file-style: "parrot" * End: * vim: expandtab shiftwidth=4 cinoptions='\:2=2' : */
25a112319ba24f6d6f9630d387586c3be60c3f8c
693bd39eb66eade67997bc608fe84e76e66eeec2
/osal/inc/mpp_debug.h
5ed55c2ec9b88f95b6407233271777cffbab8077
[]
permissive
HermanChen/mpp
6a1751777b120b764f86e0f34975231054a3c262
0af9b5becc76c4685831214808e124e65543297b
refs/heads/develop
2023-08-17T07:17:49.489974
2023-07-31T08:26:14
2023-08-11T07:38:17
71,088,248
139
79
Apache-2.0
2023-03-08T09:44:01
2016-10-17T01:13:37
C
UTF-8
C
false
false
3,573
h
mpp_debug.h
/* * Copyright 2022 Rockchip Electronics Co. LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __MPP_DEBUG_H__ #define __MPP_DEBUG_H__ #include <stdlib.h> #include "rk_type.h" #include "mpp_err.h" #include "mpp_log.h" #define MPP_DBG_TIMING (0x00000001) #define MPP_DBG_PTS (0x00000002) #define MPP_DBG_INFO (0x00000004) #define MPP_DBG_PLATFORM (0x00000010) #define MPP_DBG_DUMP_LOG (0x00000100) #define MPP_DBG_DUMP_IN (0x00000200) #define MPP_DBG_DUMP_OUT (0x00000400) #define MPP_DBG_DUMP_CFG (0x00000800) #define _mpp_dbg(debug, flag, fmt, ...) mpp_log_c((debug) & (flag), fmt, ## __VA_ARGS__) #define _mpp_dbg_f(debug, flag, fmt, ...) mpp_log_cf((debug) & (flag), fmt, ## __VA_ARGS__) #define mpp_dbg(flag, fmt, ...) _mpp_dbg(mpp_debug, flag, fmt, ## __VA_ARGS__) #define mpp_dbg_f(flag, fmt, ...) _mpp_dbg_f(mpp_debug, flag, fmt, ## __VA_ARGS__) #define mpp_dbg_pts(fmt, ...) mpp_dbg(MPP_DBG_PTS, fmt, ## __VA_ARGS__) #define mpp_dbg_info(fmt, ...) mpp_dbg(MPP_DBG_INFO, fmt, ## __VA_ARGS__) #define mpp_dbg_platform(fmt, ...) mpp_dbg(MPP_DBG_PLATFORM, fmt, ## __VA_ARGS__) #define MPP_ABORT (0x10000000) /* * mpp_dbg usage: * * in h264d module define module debug flag variable like: h265d_debug * then define h265d_dbg macro as follow : * * extern RK_U32 h265d_debug; * * #define H265D_DBG_FUNCTION (0x00000001) * #define H265D_DBG_VPS (0x00000002) * #define H265D_DBG_SPS (0x00000004) * #define H265D_DBG_PPS (0x00000008) * #define H265D_DBG_SLICE_HDR (0x00000010) * * #define h265d_dbg(flag, fmt, ...) mpp_dbg(h265d_debug, flag, fmt, ## __VA_ARGS__) * * finally use environment control the debug flag * * mpp_get_env_u32("h264d_debug", &h265d_debug, 0) * */ /* * sub-module debug flag usage example: * +------+-------------------+ * | 8bit | 24bit | * +------+-------------------+ * 0~15 bit: software debug print * 16~23 bit: hardware debug print * 24~31 bit: information print format */ #define mpp_abort() do { \ if (mpp_debug & MPP_ABORT) { \ abort(); \ } \ } while (0) #define MPP_STRINGS(x) MPP_TO_STRING(x) #define MPP_TO_STRING(x) #x #define mpp_assert(cond) do { \ if (!(cond)) { \ mpp_err("Assertion %s failed at %s:%d\n", \ MPP_STRINGS(cond), __FUNCTION__, __LINE__); \ mpp_abort(); \ } \ } while (0) #ifdef __cplusplus extern "C" { #endif extern RK_U32 mpp_debug; #ifdef __cplusplus } #endif #endif /*__MPP_DEBUG_H__*/
8f96851a3d8936fc6669557920f8eb685390a3f9
1efb2283837c9b70bc6449cec877799e4efa3268
/test/mpi/comm/dup_with_info.c
3d5c9436275b34af80bd80f96612a89b6355b8c7
[ "mpich2" ]
permissive
pmodels/mpich
d2392e8e30536cad3e500c16aa1e71211101d83f
2d265f9f5f93ebdd07ad547423bc6212868262a4
refs/heads/main
2023-09-04T05:50:15.041823
2023-09-01T23:07:33
2023-09-01T23:07:33
70,918,679
506
313
NOASSERTION
2023-09-14T14:38:36
2016-10-14T14:39:42
C
UTF-8
C
false
false
2,981
c
dup_with_info.c
/* * Copyright (C) by Argonne National Laboratory * See COPYRIGHT in top-level directory */ #include "mpi.h" #include <stdio.h> #include "mpitest.h" static int run_tests(MPI_Comm comm) { int rank, size, wrank, wsize, dest, a, b, errs = 0; MPI_Status status; /* Check basic properties */ MPI_Comm_size(MPI_COMM_WORLD, &wsize); MPI_Comm_rank(MPI_COMM_WORLD, &wrank); MPI_Comm_size(comm, &size); MPI_Comm_rank(comm, &rank); if (size != wsize || rank != wrank) { errs++; fprintf(stderr, "Size (%d) or rank (%d) wrong\n", size, rank); fflush(stderr); } MPI_Barrier(comm); /* Can we communicate with this new communicator? */ dest = MPI_PROC_NULL; if (rank == 0) { dest = size - 1; a = rank; b = -1; MPI_Sendrecv(&a, 1, MPI_INT, dest, 0, &b, 1, MPI_INT, dest, 0, comm, &status); if (b != dest) { errs++; fprintf(stderr, "Received %d expected %d on %d\n", b, dest, rank); fflush(stderr); } if (status.MPI_SOURCE != dest) { errs++; fprintf(stderr, "Source not set correctly in status on %d\n", rank); fflush(stderr); } } else if (rank == size - 1) { dest = 0; a = rank; b = -1; MPI_Sendrecv(&a, 1, MPI_INT, dest, 0, &b, 1, MPI_INT, dest, 0, comm, &status); if (b != dest) { errs++; fprintf(stderr, "Received %d expected %d on %d\n", b, dest, rank); fflush(stderr); } if (status.MPI_SOURCE != dest) { errs++; fprintf(stderr, "Source not set correctly in status on %d\n", rank); fflush(stderr); } } MPI_Barrier(comm); return errs; } int main(int argc, char **argv) { int errs = 0; MPI_Comm newcomm; MPI_Info info; MTest_Init(&argc, &argv); /* Dup with no info */ MPI_Comm_dup_with_info(MPI_COMM_WORLD, MPI_INFO_NULL, &newcomm); errs += run_tests(newcomm); MPI_Comm_free(&newcomm); /* Dup with info keys */ MPI_Info_create(&info); MPI_Info_set(info, (char *) "host", (char *) "myhost.myorg.org"); MPI_Info_set(info, (char *) "file", (char *) "runfile.txt"); MPI_Info_set(info, (char *) "soft", (char *) "2:1000:4,3:1000:7"); MPI_Comm_dup_with_info(MPI_COMM_WORLD, info, &newcomm); errs += run_tests(newcomm); MPI_Info_free(&info); MPI_Comm_free(&newcomm); /* Dup with deleted info keys */ MPI_Info_create(&info); MPI_Info_set(info, (char *) "host", (char *) "myhost.myorg.org"); MPI_Info_set(info, (char *) "file", (char *) "runfile.txt"); MPI_Info_set(info, (char *) "soft", (char *) "2:1000:4,3:1000:7"); MPI_Comm_dup_with_info(MPI_COMM_WORLD, info, &newcomm); MPI_Info_free(&info); errs += run_tests(newcomm); MPI_Comm_free(&newcomm); MTest_Finalize(errs); return MTestReturnValue(errs); }
4703854a253a6c7b725e287062e682bea70991bd
8395e6351ce613e17b3d948590eaa356fcf13526
/test/mock/xiaomi-redmi-2a.h
1e8af3fcd6bb2d25923065d56d34bd31accd53da
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-free-unknown" ]
permissive
pytorch/cpuinfo
68e18c869e660ff2aab126d3ff56832f3a065bf7
959002f82d7962a473d8bf301845f2af720e0aa4
refs/heads/main
2023-08-30T17:40:05.341466
2023-08-16T22:30:44
2023-08-16T22:37:13
83,772,175
723
280
BSD-2-Clause
2023-08-17T19:51:33
2017-03-03T07:46:54
C
UTF-8
C
false
false
36,788
h
xiaomi-redmi-2a.h
struct cpuinfo_mock_file filesystem[] = { { .path = "/proc/cpuinfo", .size = 1225, .content = "processor\t: 0\n" "model name\t: ARMv7 Processor rev 5 (v7l)\n" "Processor\t: ARMv7 Processor rev 5 (v7l)\n" "BogoMIPS\t: 2609.15\n" "Features\t: swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt \n" "CPU implementer\t: 0x41\n" "CPU architecture: 7\n" "CPU variant\t: 0x0\n" "CPU part\t: 0xc07\n" "CPU revision\t: 5\n" "\n" "processor\t: 1\n" "model name\t: ARMv7 Processor rev 5 (v7l)\n" "Processor\t: ARMv7 Processor rev 5 (v7l)\n" "BogoMIPS\t: 2609.15\n" "Features\t: swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt \n" "CPU implementer\t: 0x41\n" "CPU architecture: 7\n" "CPU variant\t: 0x0\n" "CPU part\t: 0xc07\n" "CPU revision\t: 5\n" "\n" "processor\t: 2\n" "model name\t: ARMv7 Processor rev 5 (v7l)\n" "Processor\t: ARMv7 Processor rev 5 (v7l)\n" "BogoMIPS\t: 2609.15\n" "Features\t: swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt \n" "CPU implementer\t: 0x41\n" "CPU architecture: 7\n" "CPU variant\t: 0x0\n" "CPU part\t: 0xc07\n" "CPU revision\t: 5\n" "\n" "processor\t: 3\n" "model name\t: ARMv7 Processor rev 5 (v7l)\n" "Processor\t: ARMv7 Processor rev 5 (v7l)\n" "BogoMIPS\t: 2609.15\n" "Features\t: swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt \n" "CPU implementer\t: 0x41\n" "CPU architecture: 7\n" "CPU variant\t: 0x0\n" "CPU part\t: 0xc07\n" "CPU revision\t: 5\n" "\n" "Hardware\t: Leadcore Innopower\n" "Revision\t: 0000\n" "Serial\t\t: 0000000000000000\n", }, { .path = "/system/build.prop", .size = 4346, .content = "# begin build properties\n" "# autogenerated by buildinfo.sh\n" "ro.build.id=KTU84Q\n" "ro.build.version.incremental=V8.0.1.0.KHLCNDG\n" "ro.build.version.sdk=19\n" "ro.build.version.codename=REL\n" "ro.build.version.release=4.4.4\n" "ro.build.version.security_patch=2016-08-01\n" "ro.build.version.base_os=\n" "ro.build.date=Sat Aug 13 16:53:18 CST 2016\n" "ro.build.date.utc=1471078398\n" "ro.build.type=user\n" "ro.build.user=builder\n" "ro.build.host=c3-miui-ota-bd21.bj\n" "ro.build.tags=release-keys\n" "ro.product.brand=Xiaomi\n" "ro.product.mod_device=lte26007\n" "ro.product.hardware.version=Ver0606\n" "ro.product.cpu.abi=armeabi-v7a\n" "ro.product.cpu.abi2=armeabi\n" "ro.product.locale.language=zh\n" "ro.product.locale.region=CN\n" "ro.wifi.channels=\n" "ro.board.platform=lc1860\n" "# ro.build.product is obsolete; use ro.product.device\n" "# Do not try to parse ro.build.description or .fingerprint\n" "ro.build.description=full_lte26007-user 4.4.4 KTU84Q V8.0.1.0.KHLCNDG release-keys\n" "ro.build.fingerprint=Xiaomi/full_lte26007/lte26007:4.4.4/KTU84Q/V8.0.1.0.KHLCNDG:user/release-keys\n" "ro.build.characteristics=default\n" "# end build properties\n" "\n" "#\n" "# ADDITIONAL_BUILD_PROPERTIES\n" "#\n" "ro.miui.version.code_time=1469635200\n" "ro.miui.ui.version.code=6\n" "ro.miui.ui.version.name=V8\n" "persist.power.useautobrightadj=true\n" "persist.sys.mcd_config_file=/system/etc/mcd_default.conf\n" "ro.com.android.dateformat=MM-dd-yyyy\n" "ro.carrier=unknown\n" "ro.build.mass.production=true\n" "persist.sys.install.lc.log=/data/local/log,I1,0,0,I2,0,0,I3,0,0,I4,0,0,I5,0,0,I6,0,0\n" "persist.sys.install.max.lc.log=/data/local/log,I1,10,8192,I2,10,8192,I3,10,51200,I4,100,8192,I5,10,8192,I6,10,8192\n" "persist.sys.lc.msms=221\n" "persist.sys.lc.standby.rat=7,3\n" "persist.sys.lc.dual2single=1\n" "persist.sys.lc.dynamic.rat=1\n" "persist.sys.lc.master.card=10\n" "persist.sys.lc.def.cs=0\n" "persist.sys.lc.def.ps=0\n" "persist.sys.lc.def.sms=0\n" "persist.sys.lc.network.model=3\n" "persist.sys.lc.check.imei=1\n" "persist.sys.lc.network.select.mode=1\n" "persist.sys.lc.preferred.network.mode=1\n" "ro.build.display.lc.id=L1860_1.00.10.R57_20151110\n" "ro.build.factory.mode=0\n" "ro.build.display.factory.id=FACTORY-02\n" "persist.sys.timezone=Asia/Shanghai\n" "debug.hwc.fakevsync=0\n" "debug.hwc.logvsync=0\n" "debug.sf.gpuoverlay=0\n" "debug.sf.sa_enable=1\n" "debug.sf.sa_log=0\n" "debug.hwc.asyncdisp=1\n" "debug.power.loghint=0\n" "persist.radio.elog.path=1\n" "persist.sys.lc.amt.mmi.station=18\n" "ro.installed.fm=1\n" "ro.fm.devicename=bcm4343_b2\n" "wifi.interface=wlan0\n" "ro.opengles.version=196608\n" "persist.sys.display_prefer=2\n" "persist.sys.display_ce=11\n" "sys.haptic.long.weak=0,1,20,21\n" "sys.haptic.long.normal=0,14,20,32\n" "sys.haptic.long.strong=0,24,20,45\n" "sys.haptic.down.weak=0,1,20,21\n" "sys.haptic.down.normal=0,12,24,32\n" "sys.haptic.down.strong=0,24,20,46\n" "sys.haptic.up.weak=0,1,25,26\n" "sys.haptic.up.normal=0,10,25,35\n" "sys.haptic.up.strong=0,20,25,46\n" "sys.haptic.tap.weak=0,8,25,28\n" "sys.haptic.tap.normal=0,15,30,40\n" "sys.haptic.tap.strong=0,24,32,48\n" "ro.config.low_ram=false\n" "ro.config.max_starting_bg=8\n" "ro.audio.flinger_standbytime_ms=1000\n" "dalvik.vm.heapstartsize=8m\n" "dalvik.vm.heapgrowthlimit=96m\n" "dalvik.vm.heapsize=256m\n" "dalvik.vm.heaptargetutilization=0.75\n" "dalvik.vm.heapminfree=2m\n" "dalvik.vm.heapmaxfree=8m\n" "persist.sys.dalvik.vm.lib=libdvm.so\n" "net.bt.name=Android\n" "dalvik.vm.stack-trace-file=/data/anr/traces.txt\n" "ro.miui.has_real_blur=1\n" "ro.miui.has_handy_mode_sf=1\n" "ro.product.mod_device=lte26007\n" "ro.config.sms_received_sound=FadeIn.ogg\n" "ro.config.sms_delivered_sound=MessageComplete.ogg\n" "ro.com.android.mobiledata=false\n" "ro.product.manufacturer=Xiaomi\n" "ro.config.elder-ringtone=Angel.mp3\n" "keyguard.no_require_sim=true\n" "ro.com.android.dataroaming=false\n" "persist.sys.mitalk.enable=true\n" "ro.config.ringtone=Ring_Synth_04.ogg\n" "ro.config.notification_sound=pixiedust.ogg\n" "ro.config.alarm_alert=Alarm_Classic.ogg\n" "ro.product.cuptsm=XIAOMI|ESE|02|01\n" "ro.product.name=full_lte26007\n" "ro.build.display.id=KTU84P\n" "ro.product.device=lte26007\n" "ro.product.board=2014502\n" "ro.build.customer=XIAOMI\n" "ro.build.product=HM2014502\n" "ro.product.model=HM 2A\n" "ro.product.real_model=2014502\n" "ro.build.display.wtid=SW_S26007A2_V001_M10_XM_USER\n" "ro.com.google.clientidbase=android-xiaomi\n" "ro.sf.lcd_density=320\n" "persist.radio.multisim.config=dsds\n" "ro.telephony.default_network=101\n" "ro.ril.auto.plmn=0\n" "ro.telephony.call_ring.multiple=false\n" "ro.ril.resend.sms.full=1\n" "ro.ril.modem.pb=0\n" "persist.sys.lc.dcrm.config=0\n" "persist.sys.button_jack_profile=volume\n" "persist.sys.button_jack_switch=0\n" "persist.sys.miui_feature_config=/system/etc/miui_feature/lite.conf\n" "\n", }, { .path = "/sys/devices/system/cpu/kernel_max", .size = 2, .content = "4\n", }, { .path = "/sys/devices/system/cpu/possible", .size = 4, .content = "0-4\n", }, { .path = "/sys/devices/system/cpu/present", .size = 4, .content = "0-4\n", }, { .path = "/sys/devices/system/cpu/online", .size = 4, .content = "0-3\n", }, { .path = "/sys/devices/system/cpu/offline", .size = 2, .content = "4\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/affected_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", .size = 8, .content = "1495000\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq", .size = 7, .content = "624000\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_transition_latency", .size = 7, .content = "300000\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/related_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies", .size = 84, .content = "1495000 1401563 1308125 1214688 1121250 1027813 934375 840938 747500 654063 624000 \n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors", .size = 67, .content = "conservative ondemand userspace powersave interactive performance \n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq", .size = 7, .content = "747500\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_driver", .size = 15, .content = "arm-big-little\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor", .size = 12, .content = "interactive\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq", .size = 8, .content = "1495000\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq", .size = 7, .content = "624000\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state", .size = 114, .content = "1495000 450\n" "1401563 20\n" "1308125 12\n" "1214688 0\n" "1121250 9\n" "1027813 2\n" "934375 18\n" "840938 33\n" "747500 213\n" "654063 14\n" "624000 0\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/stats/total_trans", .size = 3, .content = "63\n", }, { .path = "/sys/devices/system/cpu/cpu0/cpufreq/stats/trans_table", .size = 1481, .content = " From : To\n" " : 1495000 1401563 1308125 1214688 1121250 1027813 934375 840938 747500 654063 624000 \n" " 1495000: 0 2 2 0 2 0 2 2 13 0 0 \n" " 1401563: 1 0 0 0 1 0 0 0 0 0 0 \n" " 1308125: 3 0 0 0 0 0 0 0 0 0 0 \n" " 1214688: 0 0 0 0 0 0 0 0 0 0 0 \n" " 1121250: 2 0 1 0 0 0 0 0 0 0 0 \n" " 1027813: 1 0 0 0 0 0 0 0 0 0 0 \n" " 934375: 0 0 0 0 0 1 0 0 2 0 0 \n" " 840938: 3 0 0 0 0 0 1 0 3 0 0 \n" " 747500: 12 0 0 0 0 0 0 5 0 2 0 \n" " 654063: 0 0 0 0 0 0 0 0 2 0 0 \n" " 624000: 0 0 0 0 0 0 0 0 0 0 0 \n", }, { .path = "/sys/devices/system/cpu/cpu0/topology/physical_package_id", .size = 2, .content = "1\n", }, { .path = "/sys/devices/system/cpu/cpu0/topology/core_siblings_list", .size = 4, .content = "0-3\n", }, { .path = "/sys/devices/system/cpu/cpu0/topology/core_siblings", .size = 3, .content = "0f\n", }, { .path = "/sys/devices/system/cpu/cpu0/topology/core_id", .size = 2, .content = "0\n", }, { .path = "/sys/devices/system/cpu/cpu0/topology/thread_siblings_list", .size = 2, .content = "0\n", }, { .path = "/sys/devices/system/cpu/cpu0/topology/thread_siblings", .size = 3, .content = "01\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/affected_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_max_freq", .size = 8, .content = "1495000\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_min_freq", .size = 7, .content = "624000\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/cpuinfo_transition_latency", .size = 7, .content = "300000\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/related_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/scaling_available_frequencies", .size = 84, .content = "1495000 1401563 1308125 1214688 1121250 1027813 934375 840938 747500 654063 624000 \n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/scaling_available_governors", .size = 67, .content = "conservative ondemand userspace powersave interactive performance \n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/scaling_cur_freq", .size = 8, .content = "1495000\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/scaling_driver", .size = 15, .content = "arm-big-little\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/scaling_governor", .size = 12, .content = "interactive\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq", .size = 8, .content = "1495000\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq", .size = 7, .content = "624000\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/stats/time_in_state", .size = 116, .content = "1495000 595\n" "1401563 24\n" "1308125 12\n" "1214688 4\n" "1121250 17\n" "1027813 10\n" "934375 30\n" "840938 49\n" "747500 233\n" "654063 14\n" "624000 0\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/stats/total_trans", .size = 3, .content = "84\n", }, { .path = "/sys/devices/system/cpu/cpu1/cpufreq/stats/trans_table", .size = 1481, .content = " From : To\n" " : 1495000 1401563 1308125 1214688 1121250 1027813 934375 840938 747500 654063 624000 \n" " 1495000: 0 2 2 0 2 0 2 3 16 0 0 \n" " 1401563: 2 0 0 0 1 0 0 0 0 0 0 \n" " 1308125: 3 0 0 0 0 0 0 0 0 0 0 \n" " 1214688: 0 1 0 0 0 0 0 0 0 0 0 \n" " 1121250: 3 0 1 1 0 0 0 0 0 0 0 \n" " 1027813: 1 0 0 0 2 0 0 0 0 0 0 \n" " 934375: 1 0 0 0 0 3 0 0 2 0 0 \n" " 840938: 4 0 0 0 0 0 4 0 3 0 0 \n" " 747500: 13 0 0 0 0 0 0 8 0 2 0 \n" " 654063: 0 0 0 0 0 0 0 0 2 0 0 \n" " 624000: 0 0 0 0 0 0 0 0 0 0 0 \n", }, { .path = "/sys/devices/system/cpu/cpu1/topology/physical_package_id", .size = 2, .content = "1\n", }, { .path = "/sys/devices/system/cpu/cpu1/topology/core_siblings_list", .size = 4, .content = "0-3\n", }, { .path = "/sys/devices/system/cpu/cpu1/topology/core_siblings", .size = 3, .content = "0f\n", }, { .path = "/sys/devices/system/cpu/cpu1/topology/core_id", .size = 2, .content = "1\n", }, { .path = "/sys/devices/system/cpu/cpu1/topology/thread_siblings_list", .size = 2, .content = "1\n", }, { .path = "/sys/devices/system/cpu/cpu1/topology/thread_siblings", .size = 3, .content = "02\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/affected_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_max_freq", .size = 8, .content = "1495000\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_min_freq", .size = 7, .content = "624000\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/cpuinfo_transition_latency", .size = 7, .content = "300000\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/related_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/scaling_available_frequencies", .size = 84, .content = "1495000 1401563 1308125 1214688 1121250 1027813 934375 840938 747500 654063 624000 \n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/scaling_available_governors", .size = 67, .content = "conservative ondemand userspace powersave interactive performance \n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/scaling_cur_freq", .size = 8, .content = "1495000\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/scaling_driver", .size = 15, .content = "arm-big-little\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/scaling_governor", .size = 12, .content = "interactive\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq", .size = 8, .content = "1495000\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq", .size = 7, .content = "624000\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/stats/time_in_state", .size = 116, .content = "1495000 763\n" "1401563 24\n" "1308125 28\n" "1214688 4\n" "1121250 29\n" "1027813 10\n" "934375 30\n" "840938 49\n" "747500 258\n" "654063 18\n" "624000 0\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/stats/total_trans", .size = 3, .content = "98\n", }, { .path = "/sys/devices/system/cpu/cpu2/cpufreq/stats/trans_table", .size = 1481, .content = " From : To\n" " : 1495000 1401563 1308125 1214688 1121250 1027813 934375 840938 747500 654063 624000 \n" " 1495000: 0 2 2 0 2 0 2 3 19 0 0 \n" " 1401563: 2 0 0 0 1 0 0 0 0 0 0 \n" " 1308125: 5 0 0 0 1 0 0 0 0 0 0 \n" " 1214688: 0 1 0 0 0 0 0 0 0 0 0 \n" " 1121250: 3 0 4 1 0 0 0 0 0 0 0 \n" " 1027813: 1 0 0 0 2 0 0 0 0 0 0 \n" " 934375: 1 0 0 0 0 3 0 0 2 0 0 \n" " 840938: 4 0 0 0 0 0 4 0 3 0 0 \n" " 747500: 14 0 0 0 2 0 0 8 0 3 0 \n" " 654063: 0 0 0 0 0 0 0 0 3 0 0 \n" " 624000: 0 0 0 0 0 0 0 0 0 0 0 \n", }, { .path = "/sys/devices/system/cpu/cpu2/topology/physical_package_id", .size = 2, .content = "1\n", }, { .path = "/sys/devices/system/cpu/cpu2/topology/core_siblings_list", .size = 4, .content = "0-3\n", }, { .path = "/sys/devices/system/cpu/cpu2/topology/core_siblings", .size = 3, .content = "0f\n", }, { .path = "/sys/devices/system/cpu/cpu2/topology/core_id", .size = 2, .content = "2\n", }, { .path = "/sys/devices/system/cpu/cpu2/topology/thread_siblings_list", .size = 2, .content = "2\n", }, { .path = "/sys/devices/system/cpu/cpu2/topology/thread_siblings", .size = 3, .content = "04\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/affected_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_max_freq", .size = 8, .content = "1495000\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_min_freq", .size = 7, .content = "624000\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/cpuinfo_transition_latency", .size = 7, .content = "300000\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/related_cpus", .size = 8, .content = "0 1 2 3\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/scaling_available_frequencies", .size = 84, .content = "1495000 1401563 1308125 1214688 1121250 1027813 934375 840938 747500 654063 624000 \n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/scaling_available_governors", .size = 67, .content = "conservative ondemand userspace powersave interactive performance \n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/scaling_cur_freq", .size = 8, .content = "1495000\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/scaling_driver", .size = 15, .content = "arm-big-little\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/scaling_governor", .size = 12, .content = "interactive\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq", .size = 8, .content = "1495000\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq", .size = 7, .content = "624000\n", }, { .path = "/sys/devices/system/cpu/cpu3/cpufreq/stats/time_in_state", .size = 116, .content = "1495000 956\n" "1401563 24\n" "1308125 40\n" "1214688 4\n" "1121250 49\n" "1027813 10\n" "934375 30\n" "840938 49\n" "747500 264\n" "654063 18\n" "624000 0\n", }, { NULL }, }; #ifdef __ANDROID__ struct cpuinfo_mock_property properties[] = { { .key = "dalvik.vm.heapgrowthlimit", .value = "96m", }, { .key = "dalvik.vm.heapmaxfree", .value = "8m", }, { .key = "dalvik.vm.heapminfree", .value = "2m", }, { .key = "dalvik.vm.heapsize", .value = "256m", }, { .key = "dalvik.vm.heapstartsize", .value = "8m", }, { .key = "dalvik.vm.heaptargetutilization", .value = "0.75", }, { .key = "dalvik.vm.stack-trace-file", .value = "/data/anr/traces.txt", }, { .key = "debug.hwc.asyncdisp", .value = "1", }, { .key = "debug.hwc.fakevsync", .value = "0", }, { .key = "debug.hwc.logvsync", .value = "0", }, { .key = "debug.power.loghint", .value = "0", }, { .key = "debug.sf.gpuoverlay", .value = "0", }, { .key = "debug.sf.sa_enable", .value = "1", }, { .key = "debug.sf.sa_log", .value = "0", }, { .key = "init.svc.AcdApiDaemon", .value = "stopped", }, { .key = "init.svc.adbd", .value = "running", }, { .key = "init.svc.akmd09911", .value = "running", }, { .key = "init.svc.bootanim", .value = "running", }, { .key = "init.svc.checkpath", .value = "stopped", }, { .key = "init.svc.checksdkpath", .value = "stopped", }, { .key = "init.svc.debuggerd", .value = "running", }, { .key = "init.svc.drm", .value = "running", }, { .key = "init.svc.emsd", .value = "running", }, { .key = "init.svc.fdpp", .value = "running", }, { .key = "init.svc.flash_recovery", .value = "stopped", }, { .key = "init.svc.fuse_sdcard", .value = "running", }, { .key = "init.svc.fuse_usbotg", .value = "running", }, { .key = "init.svc.gps-daemon", .value = "running", }, { .key = "init.svc.gps_config_init", .value = "stopped", }, { .key = "init.svc.healthd", .value = "running", }, { .key = "init.svc.installd", .value = "running", }, { .key = "init.svc.invn_cal_accel", .value = "stopped", }, { .key = "init.svc.invn_cal_gyro", .value = "stopped", }, { .key = "init.svc.keystore", .value = "running", }, { .key = "init.svc.lc-elog_powerup", .value = "stopped", }, { .key = "init.svc.lc-oms-amt", .value = "running", }, { .key = "init.svc.lc-oms-sa", .value = "running", }, { .key = "init.svc.lc_boot_mode", .value = "stopped", }, { .key = "init.svc.mcd_init", .value = "stopped", }, { .key = "init.svc.mdbd", .value = "running", }, { .key = "init.svc.media", .value = "running", }, { .key = "init.svc.memsicd", .value = "stopped", }, { .key = "init.svc.middle_perf", .value = "stopped", }, { .key = "init.svc.netd", .value = "running", }, { .key = "init.svc.otad", .value = "running", }, { .key = "init.svc.radio_config", .value = "running", }, { .key = "init.svc.sdcard", .value = "running", }, { .key = "init.svc.servicemanager", .value = "running", }, { .key = "init.svc.setlockstate", .value = "stopped", }, { .key = "init.svc.shelld", .value = "running", }, { .key = "init.svc.surfaceflinger", .value = "running", }, { .key = "init.svc.thermal", .value = "running", }, { .key = "init.svc.ueventd", .value = "running", }, { .key = "init.svc.vold", .value = "running", }, { .key = "init.svc.zygote", .value = "running", }, { .key = "keyguard.no_require_sim", .value = "true", }, { .key = "net.bt.name", .value = "Android", }, { .key = "net.change", .value = "net.tcp.buffersize.evdo", }, { .key = "net.tcp.buffersize.default", .value = "4096,87380,110208,4096,16384,110208", }, { .key = "net.tcp.buffersize.edge", .value = "4093,26280,35040,4096,16384,35040", }, { .key = "net.tcp.buffersize.evdo", .value = "4094,87380,262144,4096,16384,262144", }, { .key = "net.tcp.buffersize.gprs", .value = "4092,8760,11680,4096,8760,11680", }, { .key = "net.tcp.buffersize.hsdpa", .value = "4094,87380,262144,4096,16384,262144", }, { .key = "net.tcp.buffersize.hspa", .value = "4094,87380,262144,4096,16384,262144", }, { .key = "net.tcp.buffersize.hspap", .value = "4094,87380,1220608,4096,16384,1220608", }, { .key = "net.tcp.buffersize.hsupa", .value = "4094,87380,262144,4096,16384,262144", }, { .key = "net.tcp.buffersize.lte", .value = "524288,1048576,2097152,262144,524288,1048576", }, { .key = "net.tcp.buffersize.umts", .value = "4094,87380,110208,4096,16384,110208", }, { .key = "net.tcp.buffersize.wifi", .value = "524288,1048576,2097152,262144,524288,1048576", }, { .key = "persist.mass_storage.enable", .value = "false", }, { .key = "persist.power.useautobrightadj", .value = "true", }, { .key = "persist.radio.default.data", .value = "0", }, { .key = "persist.radio.elog.path", .value = "1", }, { .key = "persist.radio.lc.master.card", .value = "10", }, { .key = "persist.radio.multisim.config", .value = "dsds", }, { .key = "persist.sys.adb.backroot", .value = "0", }, { .key = "persist.sys.aries.power_profile", .value = "middle", }, { .key = "persist.sys.button_jack_profile", .value = "volume", }, { .key = "persist.sys.button_jack_switch", .value = "0", }, { .key = "persist.sys.country", .value = "US", }, { .key = "persist.sys.dalvik.vm.lib", .value = "libdvm.so", }, { .key = "persist.sys.display_cabc", .value = "0", }, { .key = "persist.sys.display_ce", .value = "11", }, { .key = "persist.sys.display_prefer", .value = "2", }, { .key = "persist.sys.gamut_mode", .value = "0", }, { .key = "persist.sys.install.lc.log", .value = "/data/local/log,I1,0,0,I2,0,0,I3,0,0,I4,0,0,I5,0,0,I6,0,0", }, { .key = "persist.sys.install.max.lc.log", .value = "/data/local/log,I1,10,8192,I2,10,8192,I3,10,51200,I4,100,8192,I5,10,8192,I6,10,8192", }, { .key = "persist.sys.klo.rec_start", .value = "1409500940", }, { .key = "persist.sys.klo", .value = "on", }, { .key = "persist.sys.language", .value = "en", }, { .key = "persist.sys.lc.actual.rat", .value = "7,1", }, { .key = "persist.sys.lc.amt.mmi.station", .value = "18", }, { .key = "persist.sys.lc.check.imei", .value = "0", }, { .key = "persist.sys.lc.dcrm.config", .value = "0", }, { .key = "persist.sys.lc.def.cs", .value = "0", }, { .key = "persist.sys.lc.def.ps", .value = "0", }, { .key = "persist.sys.lc.def.sms", .value = "0", }, { .key = "persist.sys.lc.dual2single", .value = "1", }, { .key = "persist.sys.lc.dynamic.rat", .value = "1", }, { .key = "persist.sys.lc.master.card", .value = "10", }, { .key = "persist.sys.lc.msms", .value = "221", }, { .key = "persist.sys.lc.network.model", .value = "3", }, { .key = "persist.sys.lc.standby.rat", .value = "7,3", }, { .key = "persist.sys.localevar", .value = "", }, { .key = "persist.sys.ltm_enable", .value = "false", }, { .key = "persist.sys.mcd_config_file", .value = "/system/etc/mcd_default.conf", }, { .key = "persist.sys.memctrl", .value = "on", }, { .key = "persist.sys.mitalk.enable", .value = "true", }, { .key = "persist.sys.miui_feature_config", .value = "/system/etc/miui_feature/lite.conf", }, { .key = "persist.sys.modem.reset", .value = "1", }, { .key = "persist.sys.profiler_ms", .value = "0", }, { .key = "persist.sys.released", .value = "true", }, { .key = "persist.sys.screenshot_mode", .value = "0", }, { .key = "persist.sys.silent", .value = "0", }, { .key = "persist.sys.smartcover_enabled", .value = "false", }, { .key = "persist.sys.smartcover_mode", .value = "1", }, { .key = "persist.sys.timezone", .value = "Asia/Shanghai", }, { .key = "persist.sys.usb.config", .value = "mtp,adb", }, { .key = "persist.sys.vold.primary", .value = "0", }, { .key = "ro.adb.secure", .value = "1", }, { .key = "ro.allow.mock.location", .value = "0", }, { .key = "ro.audio.flinger_standbytime_ms", .value = "1000", }, { .key = "ro.baseband", .value = "unknown", }, { .key = "ro.board.platform", .value = "lc1860", }, { .key = "ro.bootloader", .value = "unknown", }, { .key = "ro.bootmode", .value = "unknown", }, { .key = "ro.bt.bdaddr_path", .value = "/amt/BT/BT_Address.txt", }, { .key = "ro.build.characteristics", .value = "default", }, { .key = "ro.build.customer", .value = "XIAOMI", }, { .key = "ro.build.date.utc", .value = "1471078398", }, { .key = "ro.build.date", .value = "Sat Aug 13 16:53:18 CST 2016", }, { .key = "ro.build.description", .value = "full_lte26007-user 4.4.4 KTU84Q V8.0.1.0.KHLCNDG release-keys", }, { .key = "ro.build.display.factory.id", .value = "FACTORY-02", }, { .key = "ro.build.display.id", .value = "KTU84P", }, { .key = "ro.build.display.lc.id", .value = "L1860_1.00.10.R57_20151110", }, { .key = "ro.build.display.wtid", .value = "SW_S26007A2_V001_M10_XM_USER", }, { .key = "ro.build.factory.mode", .value = "0", }, { .key = "ro.build.fingerprint", .value = "Xiaomi/full_lte26007/lte26007:4.4.4/KTU84Q/V8.0.1.0.KHLCNDG:user/release-keys", }, { .key = "ro.build.host", .value = "c3-miui-ota-bd21.bj", }, { .key = "ro.build.id", .value = "KTU84Q", }, { .key = "ro.build.mass.production", .value = "true", }, { .key = "ro.build.product", .value = "HM2014502", }, { .key = "ro.build.tags", .value = "release-keys", }, { .key = "ro.build.type", .value = "user", }, { .key = "ro.build.user", .value = "builder", }, { .key = "ro.build.version.base_os", .value = "", }, { .key = "ro.build.version.codename", .value = "REL", }, { .key = "ro.build.version.incremental", .value = "V8.0.1.0.KHLCNDG", }, { .key = "ro.build.version.release", .value = "4.4.4", }, { .key = "ro.build.version.sdk", .value = "19", }, { .key = "ro.build.version.security_patch", .value = "2016-08-01", }, { .key = "ro.carrier", .value = "unknown", }, { .key = "ro.com.android.dataroaming", .value = "false", }, { .key = "ro.com.android.dateformat", .value = "MM-dd-yyyy", }, { .key = "ro.com.android.mobiledata", .value = "false", }, { .key = "ro.com.google.clientidbase", .value = "android-xiaomi", }, { .key = "ro.config.alarm_alert", .value = "Alarm_Classic.ogg", }, { .key = "ro.config.elder-ringtone", .value = "Angel.mp3", }, { .key = "ro.config.low_ram", .value = "false", }, { .key = "ro.config.max_starting_bg", .value = "8", }, { .key = "ro.config.notification_sound", .value = "pixiedust.ogg", }, { .key = "ro.config.ringtone", .value = "Ring_Synth_04.ogg", }, { .key = "ro.config.sms_delivered_sound", .value = "MessageComplete.ogg", }, { .key = "ro.config.sms_received_sound", .value = "FadeIn.ogg", }, { .key = "ro.crypto.fuse_sdcard", .value = "true", }, { .key = "ro.crypto.state", .value = "unencrypted", }, { .key = "ro.debuggable", .value = "0", }, { .key = "ro.factorytest", .value = "0", }, { .key = "ro.fm.devicename", .value = "bcm4343_b2", }, { .key = "ro.hardware", .value = "leadcoreinnopower", }, { .key = "ro.installed.fm", .value = "1", }, { .key = "ro.lc.dual2single", .value = "1", }, { .key = "ro.lc.dynamic.rat", .value = "1", }, { .key = "ro.lc.msms", .value = "221", }, { .key = "ro.miui.cust_variant", .value = "cn", }, { .key = "ro.miui.has_handy_mode_sf", .value = "1", }, { .key = "ro.miui.has_real_blur", .value = "1", }, { .key = "ro.miui.mcc", .value = "9460", }, { .key = "ro.miui.mnc", .value = "9999", }, { .key = "ro.miui.region", .value = "CN", }, { .key = "ro.miui.ui.version.code", .value = "6", }, { .key = "ro.miui.ui.version.name", .value = "V8", }, { .key = "ro.miui.version.code_time", .value = "1469635200", }, { .key = "ro.opengles.version", .value = "196608", }, { .key = "ro.product.board", .value = "2014502", }, { .key = "ro.product.brand", .value = "Xiaomi", }, { .key = "ro.product.cpu.abi2", .value = "armeabi", }, { .key = "ro.product.cpu.abi", .value = "armeabi-v7a", }, { .key = "ro.product.cuptsm", .value = "XIAOMI|ESE|02|01", }, { .key = "ro.product.device", .value = "lte26007", }, { .key = "ro.product.hardware.version", .value = "Ver0606", }, { .key = "ro.product.locale.language", .value = "zh", }, { .key = "ro.product.locale.region", .value = "CN", }, { .key = "ro.product.manufacturer", .value = "Xiaomi", }, { .key = "ro.product.mod_device", .value = "lte26007", }, { .key = "ro.product.model", .value = "HM 2A", }, { .key = "ro.product.name", .value = "full_lte26007", }, { .key = "ro.product.real_model", .value = "2014502", }, { .key = "ro.revision", .value = "0", }, { .key = "ro.ril.auto.plmn", .value = "0", }, { .key = "ro.ril.modem.pb", .value = "0", }, { .key = "ro.ril.resend.sms.full", .value = "1", }, { .key = "ro.secure", .value = "1", }, { .key = "ro.serialno", .value = "1L521W028325", }, { .key = "ro.sf.lcd_density", .value = "320", }, { .key = "ro.telephony.call_ring.multiple", .value = "false", }, { .key = "ro.telephony.default_network", .value = "101", }, { .key = "ro.wifi.channels", .value = "", }, { .key = "sys.alarmboot.mode", .value = "0", }, { .key = "sys.chargeonly.mode", .value = "0", }, { .key = "sys.haptic.down.normal", .value = "0,12,24,32", }, { .key = "sys.haptic.down.strong", .value = "0,24,20,46", }, { .key = "sys.haptic.down.weak", .value = "0,1,20,21", }, { .key = "sys.haptic.long.normal", .value = "0,14,20,32", }, { .key = "sys.haptic.long.strong", .value = "0,24,20,45", }, { .key = "sys.haptic.long.weak", .value = "0,1,20,21", }, { .key = "sys.haptic.tap.normal", .value = "0,15,30,40", }, { .key = "sys.haptic.tap.strong", .value = "0,24,32,48", }, { .key = "sys.haptic.tap.weak", .value = "0,8,25,28", }, { .key = "sys.haptic.up.normal", .value = "0,10,25,35", }, { .key = "sys.haptic.up.strong", .value = "0,20,25,46", }, { .key = "sys.haptic.up.weak", .value = "0,1,25,26", }, { .key = "sys.usb.config", .value = "mtp,adb", }, { .key = "sys.usb.state", .value = "mtp,adb", }, { .key = "tcmd.suspend", .value = "0", }, { .key = "vold.post_fs_data_done", .value = "1", }, { .key = "wifi.interface", .value = "wlan0", }, { NULL }, }; #endif /* __ANDROID__ */
b8760e7671a0cc810ac75de7fe47259c8dc40bdd
7c857119fe1505b1d80d6e62969661c06dc1a2f4
/Library/OpensslLib/openssl-1.0.1e/crypto/rc4/rc4_enc.c
8c4fc6c7a3da38451da27f8b429ef340d2684a40
[ "BSD-2-Clause" ]
permissive
CloverHackyColor/CloverBootloader
7042ca7dd6b513d22be591a295e49071ae1482ee
2711170df4f60b2ae5aa20add3e00f35cf57b7e5
refs/heads/master
2023-08-30T22:14:34.590134
2023-08-27T19:14:02
2023-08-27T19:14:02
205,810,121
4,734
770
BSD-2-Clause
2023-09-03T12:41:33
2019-09-02T08:22:14
C
UTF-8
C
false
false
10,536
c
rc4_enc.c
/* crypto/rc4/rc4_enc.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <openssl/rc4.h> #include "rc4_locl.h" /* RC4 as implemented from a posting from * Newsgroups: sci.crypt * From: sterndark@netcom.com (David Sterndark) * Subject: RC4 Algorithm revealed. * Message-ID: <sternCvKL4B.Hyy@netcom.com> * Date: Wed, 14 Sep 1994 06:35:31 GMT */ void RC4(RC4_KEY *key, size_t len, const unsigned char *indata, unsigned char *outdata) { register RC4_INT *d; register RC4_INT x,y,tx,ty; size_t i; x=key->x; y=key->y; d=key->data; #if defined(RC4_CHUNK) /* * The original reason for implementing this(*) was the fact that * pre-21164a Alpha CPUs don't have byte load/store instructions * and e.g. a byte store has to be done with 64-bit load, shift, * and, or and finally 64-bit store. Peaking data and operating * at natural word size made it possible to reduce amount of * instructions as well as to perform early read-ahead without * suffering from RAW (read-after-write) hazard. This resulted * in ~40%(**) performance improvement on 21064 box with gcc. * But it's not only Alpha users who win here:-) Thanks to the * early-n-wide read-ahead this implementation also exhibits * >40% speed-up on SPARC and 20-30% on 64-bit MIPS (depending * on sizeof(RC4_INT)). * * (*) "this" means code which recognizes the case when input * and output pointers appear to be aligned at natural CPU * word boundary * (**) i.e. according to 'apps/openssl speed rc4' benchmark, * crypto/rc4/rc4speed.c exhibits almost 70% speed-up... * * Cavets. * * - RC4_CHUNK="unsigned long long" should be a #1 choice for * UltraSPARC. Unfortunately gcc generates very slow code * (2.5-3 times slower than one generated by Sun's WorkShop * C) and therefore gcc (at least 2.95 and earlier) should * always be told that RC4_CHUNK="unsigned long". * * <appro@fy.chalmers.se> */ # define RC4_STEP ( \ x=(x+1) &0xff, \ tx=d[x], \ y=(tx+y)&0xff, \ ty=d[y], \ d[y]=tx, \ d[x]=ty, \ (RC4_CHUNK)d[(tx+ty)&0xff]\ ) if ( ( ((size_t)indata & (sizeof(RC4_CHUNK)-1)) | ((size_t)outdata & (sizeof(RC4_CHUNK)-1)) ) == 0 ) { RC4_CHUNK ichunk,otp; const union { long one; char little; } is_endian = {1}; /* * I reckon we can afford to implement both endian * cases and to decide which way to take at run-time * because the machine code appears to be very compact * and redundant 1-2KB is perfectly tolerable (i.e. * in case the compiler fails to eliminate it:-). By * suggestion from Terrel Larson <terr@terralogic.net> * who also stands for the is_endian union:-) * * Special notes. * * - is_endian is declared automatic as doing otherwise * (declaring static) prevents gcc from eliminating * the redundant code; * - compilers (those I've tried) don't seem to have * problems eliminating either the operators guarded * by "if (sizeof(RC4_CHUNK)==8)" or the condition * expressions themselves so I've got 'em to replace * corresponding #ifdefs from the previous version; * - I chose to let the redundant switch cases when * sizeof(RC4_CHUNK)!=8 be (were also #ifdefed * before); * - in case you wonder "&(sizeof(RC4_CHUNK)*8-1)" in * [LB]ESHFT guards against "shift is out of range" * warnings when sizeof(RC4_CHUNK)!=8 * * <appro@fy.chalmers.se> */ if (!is_endian.little) { /* BIG-ENDIAN CASE */ # define BESHFT(c) (((sizeof(RC4_CHUNK)-(c)-1)*8)&(sizeof(RC4_CHUNK)*8-1)) for (;len&(0-sizeof(RC4_CHUNK));len-=sizeof(RC4_CHUNK)) { ichunk = *(RC4_CHUNK *)indata; otp = RC4_STEP<<BESHFT(0); otp |= RC4_STEP<<BESHFT(1); otp |= RC4_STEP<<BESHFT(2); otp |= RC4_STEP<<BESHFT(3); if (sizeof(RC4_CHUNK)==8) { otp |= RC4_STEP<<BESHFT(4); otp |= RC4_STEP<<BESHFT(5); otp |= RC4_STEP<<BESHFT(6); otp |= RC4_STEP<<BESHFT(7); } *(RC4_CHUNK *)outdata = otp^ichunk; indata += sizeof(RC4_CHUNK); outdata += sizeof(RC4_CHUNK); } if (len) { RC4_CHUNK mask=(RC4_CHUNK)-1, ochunk; ichunk = *(RC4_CHUNK *)indata; ochunk = *(RC4_CHUNK *)outdata; otp = 0; i = BESHFT(0); mask <<= (sizeof(RC4_CHUNK)-len)<<3; switch (len&(sizeof(RC4_CHUNK)-1)) { case 7: otp = RC4_STEP<<i, i-=8; case 6: otp |= RC4_STEP<<i, i-=8; case 5: otp |= RC4_STEP<<i, i-=8; case 4: otp |= RC4_STEP<<i, i-=8; case 3: otp |= RC4_STEP<<i, i-=8; case 2: otp |= RC4_STEP<<i, i-=8; case 1: otp |= RC4_STEP<<i, i-=8; case 0: ; /* * it's never the case, * but it has to be here * for ultrix? */ } ochunk &= ~mask; ochunk |= (otp^ichunk) & mask; *(RC4_CHUNK *)outdata = ochunk; } key->x=x; key->y=y; return; } else { /* LITTLE-ENDIAN CASE */ # define LESHFT(c) (((c)*8)&(sizeof(RC4_CHUNK)*8-1)) for (;len&(0-sizeof(RC4_CHUNK));len-=sizeof(RC4_CHUNK)) { ichunk = *(RC4_CHUNK *)indata; otp = RC4_STEP; otp |= RC4_STEP<<8; otp |= RC4_STEP<<16; otp |= RC4_STEP<<24; if (sizeof(RC4_CHUNK)==8) { otp |= RC4_STEP<<LESHFT(4); otp |= RC4_STEP<<LESHFT(5); otp |= RC4_STEP<<LESHFT(6); otp |= RC4_STEP<<LESHFT(7); } *(RC4_CHUNK *)outdata = otp^ichunk; indata += sizeof(RC4_CHUNK); outdata += sizeof(RC4_CHUNK); } if (len) { RC4_CHUNK mask=(RC4_CHUNK)-1, ochunk; ichunk = *(RC4_CHUNK *)indata; ochunk = *(RC4_CHUNK *)outdata; otp = 0; i = 0; mask >>= (sizeof(RC4_CHUNK)-len)<<3; switch (len&(sizeof(RC4_CHUNK)-1)) { case 7: otp = RC4_STEP, i+=8; case 6: otp |= RC4_STEP<<i, i+=8; case 5: otp |= RC4_STEP<<i, i+=8; case 4: otp |= RC4_STEP<<i, i+=8; case 3: otp |= RC4_STEP<<i, i+=8; case 2: otp |= RC4_STEP<<i, i+=8; case 1: otp |= RC4_STEP<<i, i+=8; case 0: ; /* * it's never the case, * but it has to be here * for ultrix? */ } ochunk &= ~mask; ochunk |= (otp^ichunk) & mask; *(RC4_CHUNK *)outdata = ochunk; } key->x=x; key->y=y; return; } } #endif #define LOOP(in,out) \ x=((x+1)&0xff); \ tx=d[x]; \ y=(tx+y)&0xff; \ d[x]=ty=d[y]; \ d[y]=tx; \ (out) = d[(tx+ty)&0xff]^ (in); #ifndef RC4_INDEX #define RC4_LOOP(a,b,i) LOOP(*((a)++),*((b)++)) #else #define RC4_LOOP(a,b,i) LOOP(a[i],b[i]) #endif i=len>>3; if (i) { for (;;) { RC4_LOOP(indata,outdata,0); RC4_LOOP(indata,outdata,1); RC4_LOOP(indata,outdata,2); RC4_LOOP(indata,outdata,3); RC4_LOOP(indata,outdata,4); RC4_LOOP(indata,outdata,5); RC4_LOOP(indata,outdata,6); RC4_LOOP(indata,outdata,7); #ifdef RC4_INDEX indata+=8; outdata+=8; #endif if (--i == 0) break; } } i=len&0x07; if (i) { for (;;) { RC4_LOOP(indata,outdata,0); if (--i == 0) break; RC4_LOOP(indata,outdata,1); if (--i == 0) break; RC4_LOOP(indata,outdata,2); if (--i == 0) break; RC4_LOOP(indata,outdata,3); if (--i == 0) break; RC4_LOOP(indata,outdata,4); if (--i == 0) break; RC4_LOOP(indata,outdata,5); if (--i == 0) break; RC4_LOOP(indata,outdata,6); if (--i == 0) break; } } key->x=x; key->y=y; }
25e778543d45a6ddd7644997e3e1af1260346df6
b23de605446429b92ed1cd1facc402b025a488e8
/include/aws/io/tls_channel_handler.h
5c630de834b014d82382c99cbaabeff5531f0a49
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
permissive
awslabs/aws-c-io
64e56224e43fce0a7c02e555cfeba39c58b8bb5f
b4aa873e16db0824ad381ae78764d445ae62ee32
refs/heads/main
2023-09-04T05:20:05.302131
2023-08-28T17:28:58
2023-08-28T17:28:58
123,649,788
103
66
Apache-2.0
2023-09-06T16:52:56
2018-03-03T01:50:50
C
UTF-8
C
false
false
33,967
h
tls_channel_handler.h
#ifndef AWS_IO_TLS_CHANNEL_HANDLER_H #define AWS_IO_TLS_CHANNEL_HANDLER_H /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/common/byte_buf.h> #include <aws/common/ref_count.h> #include <aws/io/io.h> AWS_PUSH_SANE_WARNING_LEVEL #define AWS_TLS_NEGOTIATED_PROTOCOL_MESSAGE 0x01 struct aws_channel_slot; struct aws_channel_handler; struct aws_pkcs11_session; struct aws_string; enum aws_tls_versions { AWS_IO_SSLv3, AWS_IO_TLSv1, AWS_IO_TLSv1_1, AWS_IO_TLSv1_2, AWS_IO_TLSv1_3, AWS_IO_TLS_VER_SYS_DEFAULTS = 128, }; enum aws_tls_cipher_pref { AWS_IO_TLS_CIPHER_PREF_SYSTEM_DEFAULT = 0, /* Deprecated */ AWS_IO_TLS_CIPHER_PREF_KMS_PQ_TLSv1_0_2019_06 = 1, /* Deprecated */ AWS_IO_TLS_CIPHER_PREF_KMS_PQ_SIKE_TLSv1_0_2019_11 = 2, /* Deprecated */ AWS_IO_TLS_CIPHER_PREF_KMS_PQ_TLSv1_0_2020_02 = 3, /* Deprecated */ AWS_IO_TLS_CIPHER_PREF_KMS_PQ_SIKE_TLSv1_0_2020_02 = 4, /* Deprecated */ AWS_IO_TLS_CIPHER_PREF_KMS_PQ_TLSv1_0_2020_07 = 5, /* * This TLS cipher preference list contains post-quantum key exchange algorithms that have been submitted to NIST * for potential future standardization. Support for this preference list, or PQ algorithms present in it, may be * removed at any time in the future. PQ algorithms in this preference list will be used in hybrid mode, and always * combined with a classical ECDHE key exchange. */ AWS_IO_TLS_CIPHER_PREF_PQ_TLSv1_0_2021_05 = 6, AWS_IO_TLS_CIPHER_PREF_END_RANGE = 0xFFFF }; /** * The hash algorithm of a TLS private key operation. Any custom private key operation handlers are expected to perform * operations on the input TLS data using the correct hash algorithm or fail the operation. */ enum aws_tls_hash_algorithm { AWS_TLS_HASH_UNKNOWN, AWS_TLS_HASH_SHA1, AWS_TLS_HASH_SHA224, AWS_TLS_HASH_SHA256, AWS_TLS_HASH_SHA384, AWS_TLS_HASH_SHA512, }; /** * The signature of a TLS private key operation. Any custom private key operation handlers are expected to perform * operations on the input TLS data using the correct signature algorithm or fail the operation. */ enum aws_tls_signature_algorithm { AWS_TLS_SIGNATURE_UNKNOWN, AWS_TLS_SIGNATURE_RSA, AWS_TLS_SIGNATURE_ECDSA, }; /** * The TLS private key operation that needs to be performed by a custom private key operation handler when making * a connection using mutual TLS. */ enum aws_tls_key_operation_type { AWS_TLS_KEY_OPERATION_UNKNOWN, AWS_TLS_KEY_OPERATION_SIGN, AWS_TLS_KEY_OPERATION_DECRYPT, }; struct aws_tls_ctx { struct aws_allocator *alloc; void *impl; struct aws_ref_count ref_count; }; /** * Invoked upon completion of the TLS handshake. If successful error_code will be AWS_OP_SUCCESS, otherwise * the negotiation failed and immediately after this function is invoked, the channel will be shutting down. */ typedef void(aws_tls_on_negotiation_result_fn)( struct aws_channel_handler *handler, struct aws_channel_slot *slot, int error_code, void *user_data); /** * Only used if the TLS handler is the last handler in the channel. This allows you to read any data that * was read and decrypted by the handler. If you have application protocol channel handlers, this function * is not necessary and certainly not recommended. */ typedef void(aws_tls_on_data_read_fn)( struct aws_channel_handler *handler, struct aws_channel_slot *slot, struct aws_byte_buf *buffer, void *user_data); /** * Invoked when an error occurs in the TLS state machine AFTER the handshake has completed. This function should only * be used in conjunction with the rules of aws_tls_on_data_read_fn. */ typedef void(aws_tls_on_error_fn)( struct aws_channel_handler *handler, struct aws_channel_slot *slot, int err, const char *message, void *user_data); struct aws_tls_connection_options { /** semi-colon delimited list of protocols. Example: * h2;http/1.1 */ struct aws_string *alpn_list; /** * Serves two purposes. If SNI is supported (hint... it is), * this sets the SNI extension. * * For X.509 validation this also sets the name that will be used * for verifying the subj alt name and common name of the peer's certificate. */ struct aws_string *server_name; aws_tls_on_negotiation_result_fn *on_negotiation_result; aws_tls_on_data_read_fn *on_data_read; aws_tls_on_error_fn *on_error; void *user_data; struct aws_tls_ctx *ctx; bool advertise_alpn_message; uint32_t timeout_ms; }; /** * A struct containing all of the data needed for a private key operation when * making a mutual TLS connection. This struct contains the data that needs * to be operated on, like performing a sign operation or a decrypt operation. */ struct aws_tls_key_operation; struct aws_tls_ctx_options { struct aws_allocator *allocator; /** * minimum tls version to use. If you just want us to use the * system defaults, you can set: AWS_IO_TLS_VER_SYS_DEFAULTS. This * has the added benefit of automatically picking up new TLS versions * as your OS or distribution adds support. */ enum aws_tls_versions minimum_tls_version; /** * The Cipher Preference List to use */ enum aws_tls_cipher_pref cipher_pref; /** * A PEM armored PKCS#7 collection of CAs you want to trust as a string. * Only use this if it's a CA not currently installed on your system. */ struct aws_byte_buf ca_file; /** * Only used on Unix systems using an openssl style trust API. * this is typically something like /etc/pki/tls/certs/" */ struct aws_string *ca_path; /** * Sets ctx wide alpn string. This is most useful for servers. * This is a semi-colon delimited list. example: * h2;http/1.1 */ struct aws_string *alpn_list; /** * A PEM armored PKCS#7 certificate as a string. * It is supported on every operating system. */ struct aws_byte_buf certificate; #ifdef _WIN32 /** The path to a system * installed certficate/private key pair. Example: * CurrentUser\\MY\\<thumprint> */ const char *system_certificate_path; #endif /** * A PEM armored PKCS#7 private key as a string. * * On windows, this field should be NULL only if you are * using a system installed certficate. */ struct aws_byte_buf private_key; #ifdef __APPLE__ /** * Apple Only! * * On Apple OS you can also use a pkcs#12 for your certificate * and private key. This is the contents the certificate. */ struct aws_byte_buf pkcs12; /** * Password for the pkcs12 data in pkcs12. */ struct aws_byte_buf pkcs12_password; # if !defined(AWS_OS_IOS) /** * On Apple OS you can also use a custom keychain instead of * the default keychain of the account. */ struct aws_string *keychain_path; # endif #endif /** max tls fragment size. Default is the value of g_aws_channel_max_fragment_size. */ size_t max_fragment_size; /** * default is true for clients and false for servers. * You should not change this default for clients unless * you're testing and don't want to fool around with CA trust stores. * Before you release to production, you'll want to turn this back on * and add your custom CA to the aws_tls_ctx_options. * * If you set this in server mode, it enforces client authentication. */ bool verify_peer; /** * For use when adding BYO_CRYPTO implementations. You can set extra data in here for use with your TLS * implementation. */ void *ctx_options_extension; /** * Set if using custom private key operations. * See aws_custom_key_op_handler for more details * * Note: Custom key operations (and PKCS#11 integration) hasn't been tested with TLS 1.3, so don't use * cipher preferences that allow TLS 1.3. If this is set, we will always use non TLS 1.3 preferences. */ struct aws_custom_key_op_handler *custom_key_op_handler; }; struct aws_tls_negotiated_protocol_message { struct aws_byte_buf protocol; }; typedef struct aws_channel_handler *( *aws_tls_on_protocol_negotiated)(struct aws_channel_slot *new_slot, struct aws_byte_buf *protocol, void *user_data); /** * An enum for the current state of tls negotiation within a tls channel handler */ enum aws_tls_negotiation_status { AWS_TLS_NEGOTIATION_STATUS_NONE, AWS_TLS_NEGOTIATION_STATUS_ONGOING, AWS_TLS_NEGOTIATION_STATUS_SUCCESS, AWS_TLS_NEGOTIATION_STATUS_FAILURE }; #ifdef BYO_CRYPTO /** * Callback for creating a TLS handler. If you're using this you're using BYO_CRYPTO. This function should return * a fully implemented aws_channel_handler instance for TLS. Note: the aws_tls_options passed to your * aws_tls_handler_new_fn contains multiple callbacks. Namely: aws_tls_on_negotiation_result_fn. You are responsible for * invoking this function when TLs session negotiation has completed. */ typedef struct aws_channel_handler *(aws_tls_handler_new_fn)( struct aws_allocator *allocator, struct aws_tls_connection_options *options, struct aws_channel_slot *slot, void *user_data); /** * Invoked when it's time to start TLS negotiation. Note: the aws_tls_options passed to your aws_tls_handler_new_fn * contains multiple callbacks. Namely: aws_tls_on_negotiation_result_fn. You are responsible for invoking this function * when TLS session negotiation has completed. */ typedef int(aws_tls_client_handler_start_negotiation_fn)(struct aws_channel_handler *handler, void *user_data); struct aws_tls_byo_crypto_setup_options { aws_tls_handler_new_fn *new_handler_fn; /* ignored for server implementations, required for clients. */ aws_tls_client_handler_start_negotiation_fn *start_negotiation_fn; void *user_data; }; #endif /* BYO_CRYPTO */ AWS_EXTERN_C_BEGIN /******************************** tls options init stuff ***********************/ /** * Initializes options with default client options */ AWS_IO_API void aws_tls_ctx_options_init_default_client( struct aws_tls_ctx_options *options, struct aws_allocator *allocator); /** * Cleans up resources allocated by init_* functions */ AWS_IO_API void aws_tls_ctx_options_clean_up(struct aws_tls_ctx_options *options); /** * Initializes options for use with mutual tls in client mode. * cert_path and pkey_path are paths to files on disk. cert_path * and pkey_path are treated as PKCS#7 PEM armored. They are loaded * from disk and stored in buffers internally. * * NOTE: This is unsupported on iOS. */ AWS_IO_API int aws_tls_ctx_options_init_client_mtls_from_path( struct aws_tls_ctx_options *options, struct aws_allocator *allocator, const char *cert_path, const char *pkey_path); /** * Initializes options for use with mutual tls in client mode. * cert and pkey are copied. cert and pkey are treated as PKCS#7 PEM * armored. * * NOTE: This is unsupported on iOS. */ AWS_IO_API int aws_tls_ctx_options_init_client_mtls( struct aws_tls_ctx_options *options, struct aws_allocator *allocator, const struct aws_byte_cursor *cert, const struct aws_byte_cursor *pkey); /** * vtable for aws_custom_key_op_handler. */ struct aws_custom_key_op_handler_vtable { /** * Called when the a TLS handshake has an operation it needs the custom key operation handler to perform. * NOTE: You must call aws_tls_key_operation_complete() or aws_tls_key_operation_complete_with_error() * otherwise the TLS handshake will stall the TLS connection indefinitely and leak memory. */ void (*on_key_operation)(struct aws_custom_key_op_handler *key_op_handler, struct aws_tls_key_operation *operation); }; /** * The custom key operation that is used when performing a mutual TLS handshake. This can * be extended to provide custom private key operations, like PKCS11 or similar. */ struct aws_custom_key_op_handler { /** * A void* intended to be populated with a reference to whatever class is extending this class. For example, * if you have extended aws_custom_key_op_handler with a custom struct, you would put a pointer to this struct * to *impl so you can retrieve it back in the vtable functions. */ void *impl; /** * A vtable containing all of the functions the aws_custom_key_op_handler implements. Is intended to be extended. * NOTE: Use "aws_custom_key_op_handler_<func>" to access vtable functions. */ const struct aws_custom_key_op_handler_vtable *vtable; /** * A reference count for handling memory usage. * Use aws_custom_key_op_handler_acquire and aws_custom_key_op_handler_release to increase/decrease count. */ struct aws_ref_count ref_count; }; /** * Increases the reference count for the passed-in aws_custom_key_op_handler and returns it. */ AWS_IO_API struct aws_custom_key_op_handler *aws_custom_key_op_handler_acquire( struct aws_custom_key_op_handler *key_op_handler); /** * Decreases the reference count for the passed-in aws_custom_key_op_handler and returns NULL. */ AWS_IO_API struct aws_custom_key_op_handler *aws_custom_key_op_handler_release( struct aws_custom_key_op_handler *key_op_handler); /** * Calls the on_key_operation vtable function. See aws_custom_key_op_handler_vtable for function details. */ AWS_IO_API void aws_custom_key_op_handler_perform_operation( struct aws_custom_key_op_handler *key_op_handler, struct aws_tls_key_operation *operation); /** * Initializes options for use with mutual TLS in client mode, * where private key operations are handled by custom code. * * Note: cert_file_contents will be copied into a new buffer after this * function is called, so you do not need to keep that data alive * after calling this function. * * @param options aws_tls_ctx_options to be initialized. * @param allocator Allocator to use. * @param custom Options for custom key operations. * @param cert_file_contents The contents of a certificate file. */ AWS_IO_API int aws_tls_ctx_options_init_client_mtls_with_custom_key_operations( struct aws_tls_ctx_options *options, struct aws_allocator *allocator, struct aws_custom_key_op_handler *custom, const struct aws_byte_cursor *cert_file_contents); /** * This struct exists as a graceful way to pass many arguments when * calling init-with-pkcs11 functions on aws_tls_ctx_options (this also makes * it easy to introduce optional arguments in the future). * Instances of this struct should only exist briefly on the stack. * * Instructions for binding this to high-level languages: * - Python: The members of this struct should be the keyword args to the init-with-pkcs11 functions. * - JavaScript: This should be an options map passed to init-with-pkcs11 functions. * - Java: This should be an options class passed to init-with-pkcs11 functions. * - C++: Same as Java * * Notes on integer types: * PKCS#11 uses `unsigned long` for IDs, handles, etc but we expose them as `uint64_t` in public APIs. * We do this because sizeof(long) is inconsistent across platform/arch/language * (ex: always 64bit in Java, always 32bit in C on Windows, matches CPU in C on Linux and Apple). * By using uint64_t in our public API, we can keep the careful bounds-checking all in one * place, instead of expecting each high-level language binding to get it just right. */ struct aws_tls_ctx_pkcs11_options { /** * The PKCS#11 library to use. * This field is required. */ struct aws_pkcs11_lib *pkcs11_lib; /** * User PIN, for logging into the PKCS#11 token (UTF-8). * Zero out to log into a token with a "protected authentication path". */ struct aws_byte_cursor user_pin; /** * ID of slot containing PKCS#11 token. * If set to NULL, the token will be chosen based on other criteria * (such as token label). */ const uint64_t *slot_id; /** * Label of PKCS#11 token to use. * If zeroed out, the token will be chosen based on other criteria * (such as slot ID). */ struct aws_byte_cursor token_label; /** * Label of private key object on PKCS#11 token (UTF-8). * If zeroed out, the private key will be chosen based on other criteria * (such as being the only available private key on the token). */ struct aws_byte_cursor private_key_object_label; /** * Certificate's file path on disk (UTF-8). * The certificate must be PEM formatted and UTF-8 encoded. * Zero out if passing in certificate by some other means (such as file contents). */ struct aws_byte_cursor cert_file_path; /** * Certificate's file contents (UTF-8). * The certificate must be PEM formatted and UTF-8 encoded. * Zero out if passing in certificate by some other means (such as file path). */ struct aws_byte_cursor cert_file_contents; }; /** * Initializes options for use with mutual TLS in client mode, * where a PKCS#11 library provides access to the private key. * * NOTE: This only works on Unix devices. * * @param options aws_tls_ctx_options to be initialized. * @param allocator Allocator to use. * @param pkcs11_options Options for using PKCS#11 (contents are copied) */ AWS_IO_API int aws_tls_ctx_options_init_client_mtls_with_pkcs11( struct aws_tls_ctx_options *options, struct aws_allocator *allocator, const struct aws_tls_ctx_pkcs11_options *pkcs11_options); /** * @Deprecated * * Sets a custom keychain path for storing the cert and pkey with mutual tls in client mode. * * NOTE: This only works on MacOS. */ AWS_IO_API int aws_tls_ctx_options_set_keychain_path( struct aws_tls_ctx_options *options, struct aws_byte_cursor *keychain_path_cursor); /** * Initializes options for use with in server mode. * cert_path and pkey_path are paths to files on disk. cert_path * and pkey_path are treated as PKCS#7 PEM armored. They are loaded * from disk and stored in buffers internally. */ AWS_IO_API int aws_tls_ctx_options_init_default_server_from_path( struct aws_tls_ctx_options *options, struct aws_allocator *allocator, const char *cert_path, const char *pkey_path); /** * Initializes options for use with in server mode. * cert and pkey are copied. cert and pkey are treated as PKCS#7 PEM * armored. */ AWS_IO_API int aws_tls_ctx_options_init_default_server( struct aws_tls_ctx_options *options, struct aws_allocator *allocator, struct aws_byte_cursor *cert, struct aws_byte_cursor *pkey); /** * Initializes options for use with mutual tls in client mode. * cert_reg_path is the path to a system * installed certficate/private key pair. Example: * CurrentUser\\MY\\<thumprint> * * NOTE: This only works on Windows. */ AWS_IO_API int aws_tls_ctx_options_init_client_mtls_from_system_path( struct aws_tls_ctx_options *options, struct aws_allocator *allocator, const char *cert_reg_path); /** * Initializes options for use with server mode. * cert_reg_path is the path to a system * installed certficate/private key pair. Example: * CurrentUser\\MY\\<thumprint> * * NOTE: This only works on Windows. */ AWS_IO_API int aws_tls_ctx_options_init_default_server_from_system_path( struct aws_tls_ctx_options *options, struct aws_allocator *allocator, const char *cert_reg_path); /** * Initializes options for use with mutual tls in client mode. * pkcs12_path is a path to a file on disk containing a pkcs#12 file. The file is loaded * into an internal buffer. pkcs_pwd is the corresponding password for the pkcs#12 file; it is copied. * * NOTE: This only works on Apple devices. */ AWS_IO_API int aws_tls_ctx_options_init_client_mtls_pkcs12_from_path( struct aws_tls_ctx_options *options, struct aws_allocator *allocator, const char *pkcs12_path, const struct aws_byte_cursor *pkcs_pwd); /** * Initializes options for use with mutual tls in client mode. * pkcs12 is a buffer containing a pkcs#12 certificate and private key; it is copied. * pkcs_pwd is the corresponding password for the pkcs#12 buffer; it is copied. * * NOTE: This only works on Apple devices. */ AWS_IO_API int aws_tls_ctx_options_init_client_mtls_pkcs12( struct aws_tls_ctx_options *options, struct aws_allocator *allocator, struct aws_byte_cursor *pkcs12, struct aws_byte_cursor *pkcs_pwd); /** * Initializes options for use in server mode. * pkcs12_path is a path to a file on disk containing a pkcs#12 file. The file is loaded * into an internal buffer. pkcs_pwd is the corresponding password for the pkcs#12 file; it is copied. * * NOTE: This only works on Apple devices. */ AWS_IO_API int aws_tls_ctx_options_init_server_pkcs12_from_path( struct aws_tls_ctx_options *options, struct aws_allocator *allocator, const char *pkcs12_path, struct aws_byte_cursor *pkcs_password); /** * Initializes options for use in server mode. * pkcs12 is a buffer containing a pkcs#12 certificate and private key; it is copied. * pkcs_pwd is the corresponding password for the pkcs#12 buffer; it is copied. * * NOTE: This only works on Apple devices. */ AWS_IO_API int aws_tls_ctx_options_init_server_pkcs12( struct aws_tls_ctx_options *options, struct aws_allocator *allocator, struct aws_byte_cursor *pkcs12, struct aws_byte_cursor *pkcs_password); /** * Sets alpn list in the form <protocol1;protocol2;...>. A maximum of 4 protocols are supported. * alpn_list is copied. */ AWS_IO_API int aws_tls_ctx_options_set_alpn_list(struct aws_tls_ctx_options *options, const char *alpn_list); /** * Enables or disables x.509 validation. Disable this only for testing. To enable mutual TLS in server mode, * set verify_peer to true. */ AWS_IO_API void aws_tls_ctx_options_set_verify_peer(struct aws_tls_ctx_options *options, bool verify_peer); /** * Sets preferred TLS Cipher List */ AWS_IO_API void aws_tls_ctx_options_set_tls_cipher_preference( struct aws_tls_ctx_options *options, enum aws_tls_cipher_pref cipher_pref); /** * Sets the minimum TLS version to allow. */ AWS_IO_API void aws_tls_ctx_options_set_minimum_tls_version( struct aws_tls_ctx_options *options, enum aws_tls_versions minimum_tls_version); /** * Override the default trust store. ca_file is a buffer containing a PEM armored chain of trusted CA certificates. * ca_file is copied. */ AWS_IO_API int aws_tls_ctx_options_override_default_trust_store( struct aws_tls_ctx_options *options, const struct aws_byte_cursor *ca_file); /** * Override the default trust store. ca_path is a path to a directory on disk containing trusted certificates. This is * only supported on Unix systems (otherwise this parameter is ignored). ca_file is a path to a file on disk containing * trusted certificates. ca_file is loaded from disk and stored in an internal buffer. */ AWS_IO_API int aws_tls_ctx_options_override_default_trust_store_from_path( struct aws_tls_ctx_options *options, const char *ca_path, const char *ca_file); /** * When implementing BYO_CRYPTO, if you need extra data to pass to your tls implementation, set it here. The lifetime of * extension_data must outlive the options object and be cleaned up after options is cleaned up. */ AWS_IO_API void aws_tls_ctx_options_set_extension_data(struct aws_tls_ctx_options *options, void *extension_data); /** * Initializes default connection options from an instance ot aws_tls_ctx. */ AWS_IO_API void aws_tls_connection_options_init_from_ctx( struct aws_tls_connection_options *conn_options, struct aws_tls_ctx *ctx); /** * Cleans up resources in aws_tls_connection_options. This can be called immediately after initializing * a tls handler, or if using the bootstrap api, immediately after asking for a channel. */ AWS_IO_API void aws_tls_connection_options_clean_up(struct aws_tls_connection_options *connection_options); /** * Copies 'from' to 'to' */ AWS_IO_API int aws_tls_connection_options_copy( struct aws_tls_connection_options *to, const struct aws_tls_connection_options *from); /** * Sets callbacks for use with a tls connection. */ AWS_IO_API void aws_tls_connection_options_set_callbacks( struct aws_tls_connection_options *conn_options, aws_tls_on_negotiation_result_fn *on_negotiation_result, aws_tls_on_data_read_fn *on_data_read, aws_tls_on_error_fn *on_error, void *user_data); /** * Sets server name to use for the SNI extension (supported everywhere), as well as x.509 validation. If you don't * set this, your x.509 validation will likely fail. */ AWS_IO_API int aws_tls_connection_options_set_server_name( struct aws_tls_connection_options *conn_options, struct aws_allocator *allocator, const struct aws_byte_cursor *server_name); /** * Sets alpn list in the form <protocol1;protocol2;...>. A maximum of 4 protocols are supported. * alpn_list is copied. This value is already inherited from aws_tls_ctx, but the aws_tls_ctx is expensive, * and should be used across as many connections as possible. If you want to set this per connection, set it here. */ AWS_IO_API int aws_tls_connection_options_set_alpn_list( struct aws_tls_connection_options *conn_options, struct aws_allocator *allocator, const char *alpn_list); /********************************* TLS context and state management *********************************/ /** * Returns true if alpn is available in the underlying tls implementation. * This function should always be called before setting an alpn list. */ AWS_IO_API bool aws_tls_is_alpn_available(void); /** * Returns true if this Cipher Preference is available in the underlying TLS implementation. * This function should always be called before setting a Cipher Preference */ AWS_IO_API bool aws_tls_is_cipher_pref_supported(enum aws_tls_cipher_pref cipher_pref); /** * Creates a new tls channel handler in client mode. Options will be copied. * You must call aws_tls_client_handler_start_negotiation and wait on the * aws_tls_on_negotiation_result_fn callback before the handler can begin processing * application data. */ AWS_IO_API struct aws_channel_handler *aws_tls_client_handler_new( struct aws_allocator *allocator, struct aws_tls_connection_options *options, struct aws_channel_slot *slot); /** * Creates a new tls channel handler in server mode. Options will be copied. * You must wait on the aws_tls_on_negotiation_result_fn callback before the handler can begin processing * application data. */ AWS_IO_API struct aws_channel_handler *aws_tls_server_handler_new( struct aws_allocator *allocator, struct aws_tls_connection_options *options, struct aws_channel_slot *slot); #ifdef BYO_CRYPTO /** * If using BYO_CRYPTO, you need to call this function prior to creating any client channels in the application. */ AWS_IO_API void aws_tls_byo_crypto_set_client_setup_options(const struct aws_tls_byo_crypto_setup_options *options); /** * If using BYO_CRYPTO, you need to call this function prior to creating any server channels in the application. */ AWS_IO_API void aws_tls_byo_crypto_set_server_setup_options(const struct aws_tls_byo_crypto_setup_options *options); #endif /* BYO_CRYPTO */ /** * Creates a channel handler, for client or server mode, that handles alpn. This isn't necessarily required * since you can always call aws_tls_handler_protocol in the aws_tls_on_negotiation_result_fn callback, but * this makes channel bootstrap easier to handle. */ AWS_IO_API struct aws_channel_handler *aws_tls_alpn_handler_new( struct aws_allocator *allocator, aws_tls_on_protocol_negotiated on_protocol_negotiated, void *user_data); /** * Kicks off the negotiation process. This function must be called when in client mode to initiate the * TLS handshake. Once the handshake has completed the aws_tls_on_negotiation_result_fn will be invoked. */ AWS_IO_API int aws_tls_client_handler_start_negotiation(struct aws_channel_handler *handler); #ifndef BYO_CRYPTO /** * Creates a new server ctx. This ctx can be used for the lifetime of the application assuming you want the same * options for every incoming connection. Options will be copied. */ AWS_IO_API struct aws_tls_ctx *aws_tls_server_ctx_new( struct aws_allocator *alloc, const struct aws_tls_ctx_options *options); /** * Creates a new client ctx. This ctx can be used for the lifetime of the application assuming you want the same * options for every outgoing connection. Options will be copied. */ AWS_IO_API struct aws_tls_ctx *aws_tls_client_ctx_new( struct aws_allocator *alloc, const struct aws_tls_ctx_options *options); #endif /* BYO_CRYPTO */ /** * Increments the reference count on the tls context, allowing the caller to take a reference to it. * * Returns the same tls context passed in. */ AWS_IO_API struct aws_tls_ctx *aws_tls_ctx_acquire(struct aws_tls_ctx *ctx); /** * Decrements a tls context's ref count. When the ref count drops to zero, the object will be destroyed. */ AWS_IO_API void aws_tls_ctx_release(struct aws_tls_ctx *ctx); /** * Not necessary if you are installing more handlers into the channel, but if you just want to have TLS for arbitrary * data and use the channel handler directly, this function allows you to write data to the channel and have it * encrypted. */ AWS_IO_API int aws_tls_handler_write( struct aws_channel_handler *handler, struct aws_channel_slot *slot, struct aws_byte_buf *buf, aws_channel_on_message_write_completed_fn *on_write_completed, void *completion_user_data); /** * Returns a byte buffer by copy of the negotiated protocols. If there is no agreed upon protocol, len will be 0 and * buffer will be NULL. */ AWS_IO_API struct aws_byte_buf aws_tls_handler_protocol(struct aws_channel_handler *handler); /** * Client mode only. This is the server name that was used for SNI and host name validation. */ AWS_IO_API struct aws_byte_buf aws_tls_handler_server_name(struct aws_channel_handler *handler); /**************************** TLS KEY OPERATION *******************************/ /* Note: Currently this assumes the user knows what key is being used for key/cert pairs but s2n supports multiple cert/key pairs. This functionality is not used in the CRT currently, but in the future, we may need to implement this */ /** * Complete a successful TLS private key operation by providing its output. * The output is copied into the TLS connection. * The operation is freed by this call. * * You MUST call this or aws_tls_key_operation_complete_with_error(). * Failure to do so will stall the TLS connection indefinitely and leak memory. */ AWS_IO_API void aws_tls_key_operation_complete(struct aws_tls_key_operation *operation, struct aws_byte_cursor output); /** * Complete an failed TLS private key operation. * The TLS connection will fail. * The operation is freed by this call. * * You MUST call this or aws_tls_key_operation_complete(). * Failure to do so will stall the TLS connection indefinitely and leak memory. */ AWS_IO_API void aws_tls_key_operation_complete_with_error(struct aws_tls_key_operation *operation, int error_code); /** * Returns the input data that needs to be operated on by the custom key operation. */ AWS_IO_API struct aws_byte_cursor aws_tls_key_operation_get_input(const struct aws_tls_key_operation *operation); /** * Returns the type of operation that needs to be performed by the custom key operation. * If the implementation cannot perform the operation, * use aws_tls_key_operation_complete_with_error() to preventing stalling the TLS connection. */ AWS_IO_API enum aws_tls_key_operation_type aws_tls_key_operation_get_type(const struct aws_tls_key_operation *operation); /** * Returns the algorithm the operation is expected to be operated with. * If the implementation does not support the signature algorithm, * use aws_tls_key_operation_complete_with_error() to preventing stalling the TLS connection. */ AWS_IO_API enum aws_tls_signature_algorithm aws_tls_key_operation_get_signature_algorithm( const struct aws_tls_key_operation *operation); /** * Returns the algorithm the operation digest is signed with. * If the implementation does not support the digest algorithm, * use aws_tls_key_operation_complete_with_error() to preventing stalling the TLS connection. */ AWS_IO_API enum aws_tls_hash_algorithm aws_tls_key_operation_get_digest_algorithm(const struct aws_tls_key_operation *operation); /********************************* Misc TLS related *********************************/ /* * Injects a tls handler/slot into a channel and begins tls negotiation. * If desired, ALPN must be handled separately * * right_of_slot must be an existing slot in a channel */ AWS_IO_API int aws_channel_setup_client_tls( struct aws_channel_slot *right_of_slot, struct aws_tls_connection_options *tls_options); /** * Given enum, return string like: AWS_TLS_HASH_SHA256 -> "SHA256" */ AWS_IO_API const char *aws_tls_hash_algorithm_str(enum aws_tls_hash_algorithm hash); /** * Given enum, return string like: AWS_TLS_SIGNATURE_RSA -> "RSA" */ AWS_IO_API const char *aws_tls_signature_algorithm_str(enum aws_tls_signature_algorithm signature); /** * Given enum, return string like: AWS_TLS_SIGNATURE_RSA -> "RSA" */ AWS_IO_API const char *aws_tls_key_operation_type_str(enum aws_tls_key_operation_type operation_type); AWS_EXTERN_C_END AWS_POP_SANE_WARNING_LEVEL #endif /* AWS_IO_TLS_CHANNEL_HANDLER_H */
e17510b0f3e01c39e5d8deb7e7aa4fe7c73893b3
5e4c0bdc2a28c0daf27cd208a4055e9b6e445a12
/pappl/job-filter.c
6160f6be619d4dab84ceba4f9dfac0afc63c781d
[ "LicenseRef-scancode-generic-exception", "Apache-2.0", "GPL-2.0-only", "LGPL-2.0-only" ]
permissive
michaelrsweet/pappl
c332313616020d7b5b9f96b6cedffc73a35b3223
793b41adbc38e0bd74c06fbf52568e4eac4957be
refs/heads/master
2023-08-29T00:56:45.739440
2023-08-02T13:26:32
2023-08-02T13:26:32
243,025,018
319
46
Apache-2.0
2023-09-05T07:56:12
2020-02-25T14:50:23
C
UTF-8
C
false
false
28,730
c
job-filter.c
// // Job MIME filter functions for the Printer Application Framework // // Copyright © 2019-2020 by Michael R Sweet. // // Licensed under Apache License v2.0. See the file "LICENSE" for more // information. // // // Include necessary headers... // #include "pappl.h" #include "job-private.h" #include "system-private.h" #ifdef HAVE_LIBJPEG # include <setjmp.h> # include <jpeglib.h> #endif // HAVE_LIBJPEG #ifdef HAVE_LIBPNG # include <png.h> #endif // HAVE_LIBPNG // // Local types... // #ifdef HAVE_LIBJPEG typedef struct _pappl_jpeg_err_s // JPEG error manager extension { struct jpeg_error_mgr jerr; // JPEG error manager information jmp_buf retbuf; // setjmp() return buffer char message[JMSG_LENGTH_MAX]; // Last error message } _pappl_jpeg_err_t; #endif // HAVE_LIBJPEG // // Local functions... // #ifdef HAVE_LIBJPEG static void jpeg_error_handler(j_common_ptr p) _PAPPL_NORETURN; #endif // HAVE_LIBJPEG #ifdef HAVE_LIBPNG static void png_error_func(png_structp pp, png_const_charp message); static void png_warning_func(png_structp pp, png_const_charp message); #endif // HAVE_LIBPNG // // 'papplJobFilterImage()' - Filter an image in memory. // // This function will print a grayscale or sRGB image using the printer's raster // driver interface, scaling and positioning the image as necessary based on // the job options, and printing as many copies as requested. // // The image data is an array of grayscale ("depth" = `1`) or sRGB // ("depth" = `3`) pixels starting at the top-left corner of the image. // // The image resolution ("ppi") is expressed in pixels per inch and is used for // some "print-scaling" modes. Pass `0` if the image has no explicit resolution // information. // bool // O - `true` on success, `false` otherwise papplJobFilterImage( pappl_job_t *job, // I - Job pappl_device_t *device, // I - Device pappl_pr_options_t *options, // I - Print options const unsigned char *pixels, // I - Pointer to the top-left corner of the image data int width, // I - Width in columns int height, // I - Height in lines int depth, // I - Bytes per pixel (`1` for grayscale or `3` for sRGB) int ppi, // I - Pixels per inch (`0` for unknown) bool smoothing) // I - `true` to smooth/interpolate the image, `false` for nearest-neighbor sampling { bool started = false;// Have we started the job? pappl_pr_driver_data_t driver_data; // Printer driver data const unsigned char *dither; // Dither line int ileft, // Imageable left margin itop, // Imageable top margin iwidth, // Imageable width iheight; // Imageable length/height unsigned char white, // White color *line = NULL, // Output line *lineptr, // Pointer in line byte, // Byte in line bit; // Current bit const unsigned char *pixbase, // Pointer to first pixel *pixline, // Pointer to start of current line *pixptr, // Pointer into image *pixend; // End of image int pixel0, // Temporary pixel value pixel1, // ... img_width, // Rotated image width img_height, // Rotated image height x, // X position xsize, // Scaled width xstart, // X start position xend, // X end position y, // Y position ysize, // Scaled height ystart, // Y start position yend; // Y end position int xdir, // X direction xerr, // X error accumulator xmod, // X modulus xstep, // X step yerr, // Y error accumulator ymod, // Y modulus ystep, // Y step ydir; // Y direction // Images contain a single page/impression... papplJobSetImpressions(job, 1); if (options->print_scaling == PAPPL_SCALING_FILL) { // Scale to fill the entire media area... ileft = 0; itop = 0; iwidth = (int)options->header.cupsWidth; iheight = (int)options->header.cupsHeight; } else { // Scale/center within the margins... ileft = options->media.left_margin * options->printer_resolution[0] / 2540; itop = options->media.top_margin * options->printer_resolution[1] / 2540; iwidth = (int)options->header.cupsWidth - (options->media.left_margin + options->media.right_margin) * options->printer_resolution[0] / 2540; iheight = (int)options->header.cupsHeight - (options->media.bottom_margin + options->media.top_margin) * options->printer_resolution[1] / 2540; } papplLogJob(job, PAPPL_LOGLEVEL_DEBUG, "ileft=%d, itop=%d, iwidth=%d, iheight=%d", ileft, itop, iwidth, iheight); if (iwidth <= 0 || iheight <= 0) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Invalid media size"); return (false); } // Figure out the scaling and rotation of the image... if (options->orientation_requested == IPP_ORIENT_NONE) { if (width > height && options->header.cupsWidth < options->header.cupsHeight) { options->orientation_requested = IPP_ORIENT_LANDSCAPE; papplLogJob(job, PAPPL_LOGLEVEL_INFO, "Auto-orientation: landscape"); } else { options->orientation_requested = IPP_ORIENT_PORTRAIT; papplLogJob(job, PAPPL_LOGLEVEL_INFO, "Auto-orientation: portrait"); } } if (options->print_scaling == PAPPL_SCALING_AUTO || options->print_scaling == PAPPL_SCALING_AUTO_FIT) { if (ppi <= 0) { // No resolution information, so just force scaling the image to fit/fill xsize = iwidth + 1; ysize = iheight + 1; } else if (options->orientation_requested == IPP_ORIENT_PORTRAIT || options->orientation_requested == IPP_ORIENT_REVERSE_PORTRAIT) { xsize = width * options->printer_resolution[0] / ppi; ysize = height * options->printer_resolution[1] / ppi; } else { xsize = height * options->printer_resolution[0] / ppi; ysize = width * options->printer_resolution[1] / ppi; } if (xsize > iwidth || ysize > iheight) { // Scale to fit/fill based on "print-scaling" and margins... if (options->print_scaling == PAPPL_SCALING_AUTO && options->media.bottom_margin == 0 && options->media.left_margin == 0 && options->media.right_margin == 0 && options->media.top_margin == 0) options->print_scaling = PAPPL_SCALING_FILL; else options->print_scaling = PAPPL_SCALING_FIT; } else { // Do no scaling... options->print_scaling = PAPPL_SCALING_NONE; } } else if (options->print_scaling == PAPPL_SCALING_NONE && ppi <= 0) { // Force a default PPI value of 200, which fits a typical 1080p sized // screenshot on a standard letter/A4 page. ppi = 200; } switch (options->orientation_requested) { default : case IPP_ORIENT_PORTRAIT : pixbase = pixels; img_width = width; img_height = height; xdir = (int)depth; ydir = (int)depth * (int)width; if (options->print_scaling == PAPPL_SCALING_NONE) { // No scaling xsize = img_width * options->printer_resolution[0] / ppi; ysize = img_height * options->printer_resolution[1] / ppi; } else { // Fit/fill xsize = iwidth; ysize = xsize * height / width; if ((ysize > iheight && options->print_scaling == PAPPL_SCALING_FIT) || (ysize < iheight && options->print_scaling == PAPPL_SCALING_FILL)) { ysize = iheight; xsize = ysize * width / height; } } break; case IPP_ORIENT_REVERSE_PORTRAIT : pixbase = pixels + depth * width * height - depth; img_width = width; img_height = height; xdir = -(int)depth; ydir = -(int)depth * (int)width; if (options->print_scaling == PAPPL_SCALING_NONE) { // No scaling xsize = img_width * options->printer_resolution[0] / ppi; ysize = img_height * options->printer_resolution[1] / ppi; } else { // Fit/fill xsize = iwidth; ysize = xsize * height / width; if ((ysize > iheight && options->print_scaling == PAPPL_SCALING_FIT) || (ysize < iheight && options->print_scaling == PAPPL_SCALING_FILL)) { ysize = iheight; xsize = ysize * width / height; } } break; case IPP_ORIENT_LANDSCAPE : // 90 counter-clockwise pixbase = pixels + depth * width - depth; img_width = height; img_height = width; xdir = (int)depth * (int)width; ydir = -(int)depth; if (options->print_scaling == PAPPL_SCALING_NONE) { // No scaling xsize = img_width * options->printer_resolution[0] / ppi; ysize = img_height * options->printer_resolution[1] / ppi; } else { // Fit/fill xsize = iwidth; ysize = xsize * width / height; if ((ysize > iheight && options->print_scaling == PAPPL_SCALING_FIT) || (ysize < iheight && options->print_scaling == PAPPL_SCALING_FILL)) { ysize = iheight; xsize = ysize * height / width; } } break; case IPP_ORIENT_REVERSE_LANDSCAPE : // 90 clockwise pixbase = pixels + depth * (height - 1) * width; img_width = height; img_height = width; xdir = -(int)depth * (int)width; ydir = (int)depth; if (options->print_scaling == PAPPL_SCALING_NONE) { // No scaling xsize = img_width * options->printer_resolution[0] / ppi; ysize = img_height * options->printer_resolution[1] / ppi; } else { // Fit/fill xsize = iwidth; ysize = xsize * width / height; if ((ysize > iheight && options->print_scaling == PAPPL_SCALING_FIT) || (ysize < iheight && options->print_scaling == PAPPL_SCALING_FILL)) { ysize = iheight; xsize = ysize * height / width; } } break; } // Don't rotate in the driver... options->orientation_requested = IPP_ORIENT_PORTRAIT; xstart = ileft + (iwidth - xsize) / 2; xend = xstart + xsize; ystart = itop + (iheight - ysize) / 2; yend = ystart + ysize; xmod = (int)(img_width % xsize); xstep = (int)(img_width / xsize) * xdir; ymod = (int)(img_height % ysize); ystep = (int)(img_height / ysize) * ydir; if (xend > (int)options->header.cupsWidth) xend = (int)options->header.cupsWidth; if (yend > (int)options->header.cupsHeight) yend = (int)options->header.cupsHeight; papplLogJob(job, PAPPL_LOGLEVEL_DEBUG, "xsize=%d, xstart=%d, xend=%d, xdir=%d, xmod=%d, xstep=%d", xsize, xstart, xend, xdir, xmod, xstep); papplLogJob(job, PAPPL_LOGLEVEL_DEBUG, "ysize=%d, ystart=%d, yend=%d, ydir=%d, ymod=%d, ystep=%d", ysize, ystart, yend, ydir, ymod, ystep); papplPrinterGetDriverData(papplJobGetPrinter(job), &driver_data); if ((line = malloc(options->header.cupsBytesPerLine)) == NULL) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to allocate memory for raster line."); goto abort_job; } // Start the job... if (!(driver_data.rstartjob_cb)(job, options, device)) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to start raster job."); goto abort_job; } started = true; if (options->header.cupsColorSpace == CUPS_CSPACE_K || options->header.cupsColorSpace == CUPS_CSPACE_CMYK) white = 0x00; else white = 0xff; pixend = pixels + width * height * depth; // Print every copy... while (papplJobGetCopiesCompleted(job) < papplJobGetCopies(job)) { if (papplJobGetState(job) != IPP_JSTATE_PROCESSING || papplJobIsCanceled(job)) break; if (!(driver_data.rstartpage_cb)(job, options, device, 1)) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to start raster page."); goto abort_job; } // Leading blank space... memset(line, white, options->header.cupsBytesPerLine); for (y = 0; y < ystart; y ++) { if (!(driver_data.rwriteline_cb)(job, options, device, (unsigned)y, line)) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to write raster line %u.", y); goto abort_job; } } if (ystart < 0) { pixline = pixbase - (ystart * ymod / ysize) * ydir; yerr = -ymod / 2 - (ystart * ymod) % ysize; } else { pixline = pixbase; yerr = -ymod / 2; } // Now RIP the image... for (; y < yend && !job->is_canceled; y ++) { pixptr = pixline; if (xstart < 0) { pixptr -= (xstart * xmod / xsize) * xdir; x = 0; xerr = -xmod / 2 - (xstart * xmod) % xsize; } else { x = xstart; xerr = -xmod / 2; } if (options->header.cupsBitsPerPixel == 1) { // Need to dither the image to 1-bit black... dither = options->dither[y & 15]; for (lineptr = line + x / 8, bit = 128 >> (x & 7), byte = 0; x < xend; x ++) { // Dither the current pixel... if (*pixptr <= dither[x & 15]) byte |= bit; // Advance to the next pixel... pixptr += xstep; xerr += xmod; if (xerr >= (int)xsize) { // Accumulated error has overflowed, advance another pixel... xerr -= xsize; pixptr += xdir; } // and the next bit if (bit == 1) { // Current byte is "full", save it... *lineptr++ = byte; byte = 0; bit = 128; } else bit /= 2; } if (bit < 128) *lineptr = byte; } else if (options->header.cupsColorSpace == CUPS_CSPACE_K) { // Need to invert the image... for (lineptr = line + x; x < xend; x ++) { // Copy an inverted grayscale pixel... if (smoothing && yerr >= 0 && xerr >= 0) { const unsigned char *rt = pixptr + xdir, *dn = pixptr + ydir, *dnrt = pixptr + xdir + ydir; // Pointers to adjacent pixels if (rt < pixels || rt >= pixend) rt = pixptr; if (dn < pixels || dn >= pixend) dn = pixptr; if (dnrt < pixels || dnrt >= pixend) dnrt = pixptr; pixel0 = ((xsize - xerr) * *pixptr + xerr * *rt) / xsize; pixel1 = ((xsize - xerr) * *dn + xerr * *dnrt) / xsize; *lineptr++ = (unsigned char)(255 - ((ysize - yerr) * pixel0 + yerr * pixel1) / ysize); } else { *lineptr++ = ~*pixptr; } // Advance to the next pixel... pixptr += xstep; xerr += xmod; if (xerr >= (int)xsize) { // Accumulated error has overflowed, advance another pixel... xerr -= xsize; pixptr += xdir; } } } else { // Need to copy the image... int bpp = (int)options->header.cupsBitsPerPixel / 8; for (lineptr = line + x * bpp; x < xend; x ++) { // Copy a grayscale or RGB pixel... if (smoothing && yerr >= 0 && xerr >= 0) { int j; // Looping var const unsigned char *rt = pixptr + xdir, *dn = pixptr + ydir, *dnrt = pixptr + xdir + ydir; // Pointers to adjacent pixels if (rt < pixels || rt >= pixend) rt = pixptr; if (dn < pixels || dn >= pixend) dn = pixptr; if (dnrt < pixels || dnrt >= pixend) dnrt = pixptr; for (j = 0; j < bpp; j ++) { pixel0 = ((xsize - xerr) * pixptr[j] + xerr * rt[j]) / xsize; pixel1 = ((xsize - xerr) * dn[j] + xerr * dnrt[j]) / xsize; *lineptr++ = (unsigned char)(((ysize - yerr) * pixel0 + yerr * pixel1) / ysize); } } else { memcpy(lineptr, pixptr, (unsigned)bpp); lineptr += bpp; } // Advance to the next pixel... pixptr += xstep; xerr += xmod; if (xerr >= (int)xsize) { // Accumulated error has overflowed, advance another pixel... xerr -= xsize; pixptr += xdir; } } } if (!(driver_data.rwriteline_cb)(job, options, device, (unsigned)y, line)) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to write raster line %u.", y); goto abort_job; } pixline += ystep; yerr += ymod; if (yerr >= ysize) { pixline += ydir; yerr -= ysize; } } // Trailing blank space... memset(line, white, options->header.cupsBytesPerLine); for (; y < (int)options->header.cupsHeight; y ++) { if (!(driver_data.rwriteline_cb)(job, options, device, (unsigned)y, line)) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to write raster line %u.", y); goto abort_job; } } // End the page... if (!(driver_data.rendpage_cb)(job, options, device, 1)) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to end raster page."); goto abort_job; } papplJobSetImpressionsCompleted(job, 1); papplJobSetCopiesCompleted(job, 1); } // End the job... if (!(driver_data.rendjob_cb)(job, options, device)) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to end raster job."); goto abort_job; } // Free memory and return... free(line); return (true); // Abort the job... abort_job: if (started) (driver_data.rendjob_cb)(job, options, device); free(line); return (false); } // // '_papplJobFilterJPEG()' - Filter a JPEG image file. // #ifdef HAVE_LIBJPEG bool _papplJobFilterJPEG( pappl_job_t *job, // I - Job pappl_device_t *device, // I - Device void *data) // I - Filter data (unused) { const char *filename; // JPEG filename FILE *fp; // JPEG file pappl_pr_options_t *options = NULL;// Job options struct jpeg_decompress_struct dinfo; // Decompressor info int xdpi, // X pixels per inch ydpi; // Y pixels per inch _pappl_jpeg_err_t jerr; // Error handler info unsigned char *pixels = NULL; // Image pixels JSAMPROW row; // Sample row pointer bool ret = false; // Return value (void)data; // Open the JPEG file... filename = papplJobGetFilename(job); if ((fp = fopen(filename, "rb")) == NULL) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to open JPEG file '%s': %s", filename, strerror(errno)); return (false); } // Read the image header... jpeg_std_error(&jerr.jerr); jerr.jerr.error_exit = jpeg_error_handler; if (setjmp(jerr.retbuf)) { // JPEG library errors are directed to this point... papplJobSetReasons(job, PAPPL_JREASON_DOCUMENT_FORMAT_ERROR, PAPPL_JREASON_NONE); papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to open JPEG file '%s': %s", filename, jerr.message); ret = false; goto finish_jpeg; } dinfo.err = (struct jpeg_error_mgr *)&jerr; jpeg_create_decompress(&dinfo); jpeg_stdio_src(&dinfo, fp); jpeg_read_header(&dinfo, TRUE); // Get job options and request the image data in the format we need... options = papplJobCreatePrintOptions(job, 1, dinfo.num_components > 1); dinfo.quantize_colors = FALSE; if (options->header.cupsNumColors == 1) { dinfo.out_color_space = JCS_GRAYSCALE; dinfo.out_color_components = 1; dinfo.output_components = 1; } else { dinfo.out_color_space = JCS_RGB; dinfo.out_color_components = 3; dinfo.output_components = 3; } jpeg_calc_output_dimensions(&dinfo); papplLogJob(job, PAPPL_LOGLEVEL_INFO, "JPEG image dimensions are %ux%ux%d", dinfo.output_width, dinfo.output_height, dinfo.output_components); if (dinfo.output_width < 1 || dinfo.output_width > (JDIMENSION)job->system->max_image_width || dinfo.output_height < 1 || dinfo.output_height > (JDIMENSION)job->system->max_image_height || ((size_t)dinfo.output_width * (size_t)dinfo.output_height * (size_t)dinfo.output_components) > job->system->max_image_size) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "JPEG image is too large to print."); papplJobSetReasons(job, PAPPL_JREASON_DOCUMENT_UNPRINTABLE_ERROR, PAPPL_JREASON_NONE); goto finish_jpeg; } if ((pixels = (unsigned char *)malloc((size_t)dinfo.output_width * (size_t)dinfo.output_height * (size_t)dinfo.output_components)) == NULL) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to allocate memory for %ux%ux%d JPEG image.", dinfo.output_width, dinfo.output_height, dinfo.output_components); papplJobSetReasons(job, PAPPL_JREASON_ERRORS_DETECTED, PAPPL_JREASON_NONE); goto finish_jpeg; } jpeg_start_decompress(&dinfo); while (dinfo.output_scanline < dinfo.output_height) { row = (JSAMPROW)(pixels + (size_t)dinfo.output_scanline * (size_t)dinfo.output_width * (size_t)dinfo.output_components); jpeg_read_scanlines(&dinfo, &row, 1); } switch (dinfo.density_unit) { default : case 0 : // Unknown units xdpi = ydpi = 0; break; case 1 : // Dots-per-inch xdpi = dinfo.X_density; ydpi = dinfo.Y_density; break; case 2 : // Dots-per-centimeter xdpi = dinfo.X_density * 254 / 100; ydpi = dinfo.Y_density * 254 / 100; break; } papplLogJob(job, PAPPL_LOGLEVEL_INFO, "JPEG image resolution is %dx%ddpi", xdpi, ydpi); if (xdpi != ydpi) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "JPEG image has non-square aspect ratio - not currently supported."); papplJobSetReasons(job, PAPPL_JREASON_DOCUMENT_UNPRINTABLE_ERROR, PAPPL_JREASON_NONE); goto finish_jpeg; } ret = papplJobFilterImage(job, device, options, pixels, (int)dinfo.output_width, (int)dinfo.output_height, dinfo.output_components, xdpi, true); jpeg_finish_decompress(&dinfo); finish_jpeg: papplJobDeletePrintOptions(options); free(pixels); jpeg_destroy_decompress(&dinfo); fclose(fp); return (ret); } #endif // HAVE_LIBJPEG // // 'process_png()' - Process a PNG image file. // #ifdef HAVE_LIBPNG bool // O - `true` on success and `false` otherwise _papplJobFilterPNG( pappl_job_t *job, // I - Job pappl_device_t *device, // I - Device void *data) // I - Filter data (unused) { const char *filename; // Job filename FILE *fp; // PNG file pappl_pr_options_t *options = NULL;// Job options png_structp pp = NULL; // PNG read pointer png_infop info = NULL; // PNG info pointers png_bytep *rows = NULL; // PNG row pointers png_color_16 bg; // Background color int i, // Looping var color_type, // PNG color mode width, // Width in columns height, // Height in lines depth, // Bytes per pixel xdpi, // X resolution ydpi; // Y resolution unsigned char *pixels = NULL; // Image pixels bool ret = false; // Return value // Open the PNG file... (void)data; filename = papplJobGetFilename(job); if ((fp = fopen(filename, "rb")) == NULL) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to open PNG file '%s': %s", filename, strerror(errno)); return (false); } // Setup PNG data structures... if ((pp = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp)job, png_error_func, png_warning_func)) == NULL) { papplJobSetReasons(job, PAPPL_JREASON_DOCUMENT_FORMAT_ERROR, PAPPL_JREASON_NONE); papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to allocate memory for PNG file '%s': %s", job->filename, strerror(errno)); goto finish_png; } if ((info = png_create_info_struct(pp)) == NULL) { papplJobSetReasons(job, PAPPL_JREASON_DOCUMENT_FORMAT_ERROR, PAPPL_JREASON_NONE); papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to allocate memory for PNG file '%s': %s", job->filename, strerror(errno)); goto finish_png; } if (setjmp(png_jmpbuf(pp))) { // If we get here, PNG loading failed and any errors/warnings were logged // via the corresponding callback functions... papplJobSetReasons(job, PAPPL_JREASON_DOCUMENT_FORMAT_ERROR, PAPPL_JREASON_NONE); goto finish_png; } // Start reading... png_init_io(pp, fp); # if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) // Don't throw errors with "invalid" sRGB profiles produced by Adobe apps. png_set_option(pp, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); # endif // PNG_SKIP_sRGB_CHECK_PROFILE && PNG_SET_OPTION_SUPPORTED // Get the image dimensions and depth... png_read_info(pp, info); width = (int)png_get_image_width(pp, info); height = (int)png_get_image_height(pp, info); color_type = png_get_color_type(pp, info); if (color_type & PNG_COLOR_MASK_COLOR) depth = 3; else depth = 1; papplLogJob(job, PAPPL_LOGLEVEL_INFO, "PNG image dimensions are %dx%dx%d", width, height, depth); if (width < 1 || width > job->system->max_image_width || height < 1 || height > job->system->max_image_height || (size_t)(width * height * depth) > job->system->max_image_size) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "PNG image is too large to print."); papplJobSetReasons(job, PAPPL_JREASON_DOCUMENT_UNPRINTABLE_ERROR, PAPPL_JREASON_NONE); goto finish_png; } xdpi = (int)png_get_x_pixels_per_inch(pp, info); ydpi = (int)png_get_y_pixels_per_inch(pp, info); papplLogJob(job, PAPPL_LOGLEVEL_INFO, "PNG image resolution is %dx%ddpi", xdpi, ydpi); if (xdpi != ydpi) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "PNG image has non-square aspect ratio - not currently supported."); papplJobSetReasons(job, PAPPL_JREASON_DOCUMENT_UNPRINTABLE_ERROR, PAPPL_JREASON_NONE); goto finish_png; } // Set decoding options... if (png_get_valid(pp, info, PNG_INFO_tRNS)) { // Map transparency to alpha png_set_tRNS_to_alpha(pp); color_type |= PNG_COLOR_MASK_ALPHA; } #ifdef PNG_TRANSFORM_SCALE_16 if (png_get_bit_depth(pp, info) > 8) { // Scale 16-bit values to 8-bit gamma-corrected ones png_set_scale_16(pp); papplLogJob(job, PAPPL_LOGLEVEL_DEBUG, "Scaling 16-bit PNG data to 8-bits."); } #else if (png_get_bit_depth(pp, info) > 8) { // Strip the bottom bits of 16-bit values png_set_strip_16(pp); papplLogJob(job, PAPPL_LOGLEVEL_DEBUG, "Stripping 16-bit PNG data to 8-bits."); } #endif // PNG_TRANSFORM_SCALE_16 if (png_get_bit_depth(pp, info) < 8) { // Expand 1, 2, and 4-bit values to 8 bits if (depth == 1) png_set_expand_gray_1_2_4_to_8(pp); else png_set_packing(pp); } if (color_type & PNG_COLOR_MASK_PALETTE) { // Convert indexed images to RGB... png_set_palette_to_rgb(pp); } // Remove alpha by compositing over white... bg.red = bg.green = bg.blue = 65535; png_set_background(pp, &bg, PNG_BACKGROUND_GAMMA_SCREEN, 0, 1); // Allocate memory for the image... if ((pixels = (unsigned char *)calloc(1, (size_t)(width * height * depth))) == NULL) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to allocate memory for PNG image: %s", strerror(errno)); papplJobSetReasons(job, PAPPL_JREASON_DOCUMENT_UNPRINTABLE_ERROR, PAPPL_JREASON_NONE); goto finish_png; } if ((rows = (png_bytep *)calloc((size_t)height, sizeof(png_bytep))) == NULL) { papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "Unable to allocate memory for PNG image: %s", strerror(errno)); papplJobSetReasons(job, PAPPL_JREASON_DOCUMENT_UNPRINTABLE_ERROR, PAPPL_JREASON_NONE); goto finish_png; } for (i = 0; i < height; i ++) rows[i] = pixels + i * width * depth; // Read the image... for (i = png_set_interlace_handling(pp); i > 0; i --) png_read_rows(pp, rows, NULL, (png_uint_32)height); // Prepare options... options = papplJobCreatePrintOptions(job, 1, depth == 3); // Print the image... ret = papplJobFilterImage(job, device, options, pixels, width, height, depth, (int)png_get_x_pixels_per_inch(pp, info), false); // Finish up... finish_png: if (pp && info) { png_read_end(pp, info); png_destroy_read_struct(&pp, &info, NULL); pp = NULL; info = NULL; } fclose(fp); fp = NULL; papplJobDeletePrintOptions(options); options = NULL; free(pixels); pixels = NULL; free(rows); rows = NULL; return (ret); } #endif // HAVE_LIBPNG #ifdef HAVE_LIBJPEG // // 'jpeg_error_handler()' - Handle JPEG errors by not exiting. // static void jpeg_error_handler(j_common_ptr p) // I - JPEG data { _pappl_jpeg_err_t *jerr = (_pappl_jpeg_err_t *)p->err; // JPEG error handler // Save the error message in the string buffer... (jerr->jerr.format_message)(p, jerr->message); // Return to the point we called setjmp()... longjmp(jerr->retbuf, 1); } #endif // HAVE_LIBJPEG #ifdef HAVE_LIBPNG // // 'png_error_func()' - PNG error message function. // static void png_error_func( png_structp pp, // I - PNG pointer png_const_charp message) // I - Error message { pappl_job_t *job = (pappl_job_t *)png_get_error_ptr(pp); // Job papplLogJob(job, PAPPL_LOGLEVEL_ERROR, "PNG: %s", message); } // // 'png_warning_func()' - PNG warning message function. // static void png_warning_func( png_structp pp, // I - PNG pointer png_const_charp message) // I - Error message { pappl_job_t *job = (pappl_job_t *)png_get_error_ptr(pp); // Job papplLogJob(job, PAPPL_LOGLEVEL_WARN, "PNG: %s", message); } #endif // HAVE_LIBPNG
9a1c53c94b0c131b47a10bdb42d6321273459245
03b2c80dbc41e904b167d504666e27d798da5447
/src/typedef_thread.h
d679f1c07d63640e412048944d6243a6291cbdf3
[ "Unlicense" ]
permissive
nptcl/npt
7c1570b497cdce0b8971cb445fbc04cb500232d3
aa714a2370ac9fa5348c2fc96159b40b9de3de07
refs/heads/master
2023-03-20T09:13:54.669118
2022-07-02T11:17:44
2022-07-02T11:17:44
171,985,905
160
12
Unlicense
2023-03-11T01:36:37
2019-02-22T03:11:34
C
UTF-8
C
false
false
1,151
h
typedef_thread.h
#ifndef __TYPEDEF_THREAD_HEADER__ #define __TYPEDEF_THREAD_HEADER__ #include "define.h" /* single thread mode */ #ifdef LISP_THREAD_DISABLE typedef int threadhandle; typedef int mutexlite; typedef int rwlocklite; struct threadlocal_single { const void *value; }; typedef struct threadlocal_single *threadlocal; typedef int condlite; typedef int binsem; #endif /* pthread mode */ #ifdef LISP_THREAD_UNIX #include <pthread.h> #include <semaphore.h> #include <errno.h> typedef pthread_t threadhandle; typedef pthread_mutex_t mutexlite; typedef pthread_rwlock_t rwlocklite; typedef pthread_key_t threadlocal; typedef sem_t semunix; typedef semunix binsem; typedef pthread_cond_t condlite; #endif /* Windows mode */ #ifdef LISP_THREAD_WINDOWS #include <windows.h> typedef HANDLE threadhandle; typedef DWORD threadid; typedef CRITICAL_SECTION mutexlite; /* required Vista */ typedef SRWLOCK rwlocklite; typedef DWORD threadlocal; typedef CONDITION_VARIABLE condlite; typedef HANDLE semwindows; struct binsemlite_tag { mutexlite mutex; condlite cond; int value; }; typedef struct binsemlite_tag binsemlite; typedef binsemlite binsem; #endif #endif
7153bcd7affa8fab391878348967ae7a6dfe6b6e
487c8455b34e2b312da42bf8a43162aa5c5027df
/Target/Demo/TRICORE_TC3_TC375_Lite_Kit_ADS/Prog/Libraries/iLLD/TC37A/Tricore/Gtm/Std/IfxGtm_Tim.c
48ad435613d1901b866d613ba56973aab61f764e
[]
no_license
feaser/openblt
bf3a72e7beb998cb635a67db85fa68100d048bb8
57b517eabeb37d945606e18736e106bde34010bc
refs/heads/master
2023-08-31T23:54:09.030534
2023-07-07T10:29:56
2023-07-07T10:29:56
102,110,352
534
236
null
2023-09-14T11:11:56
2017-09-01T12:26:08
C
UTF-8
C
false
false
6,948
c
IfxGtm_Tim.c
/** * \file IfxGtm_Tim.c * \brief GTM basic functionality * * \version iLLD_1_0_1_12_0_1 * \copyright Copyright (c) 2018 Infineon Technologies AG. All rights reserved. * * * IMPORTANT NOTICE * * Use of this file is subject to the terms of use agreed between (i) you or * the company in which ordinary course of business you are acting and (ii) * Infineon Technologies AG or its licensees. If and as long as no such terms * of use are agreed, use of this file is subject to following: * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, must * be included in all copies of the Software, in whole or in part, and all * derivative works of the Software, unless such copies or derivative works are * solely in the form of machine-executable object code generated by a source * language processor. * * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /******************************************************************************/ /*----------------------------------Includes----------------------------------*/ /******************************************************************************/ #include "IfxGtm_Tim.h" /******************************************************************************/ /*-------------------------Function Implementations---------------------------*/ /******************************************************************************/ float32 IfxGtm_Tim_Ch_getCaptureClockFrequency(Ifx_GTM *gtm, Ifx_GTM_TIM_CH *channel) { IfxGtm_Cmu_Clk clock; clock = IfxGtm_Tim_Ch_getCaptureClockSource(channel); return IfxGtm_Cmu_getClkFrequency(gtm, clock, TRUE); } IfxGtm_Cmu_Clk IfxGtm_Tim_Ch_getCaptureClockSource(Ifx_GTM_TIM_CH *channel) { return (IfxGtm_Cmu_Clk)channel->CTRL.B.CLK_SEL; } float32 IfxGtm_Tim_Ch_getFilterClockFrequency(Ifx_GTM *gtm, Ifx_GTM_TIM_CH *channel) { IfxGtm_Cmu_Tim_Filter_Clk filterClock; IfxGtm_Cmu_Clk clock; filterClock = IfxGtm_Tim_Ch_getFilterClockSource(channel); switch (filterClock) { case IfxGtm_Cmu_Tim_Filter_Clk_0: clock = IfxGtm_Cmu_Clk_0; break; case IfxGtm_Cmu_Tim_Filter_Clk_1: clock = IfxGtm_Cmu_Clk_1; break; case IfxGtm_Cmu_Tim_Filter_Clk_6: clock = IfxGtm_Cmu_Clk_6; break; case IfxGtm_Cmu_Tim_Filter_Clk_7: clock = IfxGtm_Cmu_Clk_7; break; default: clock = IfxGtm_Cmu_Clk_0; // This case never occurs break; } return IfxGtm_Cmu_getClkFrequency(gtm, clock, TRUE); } IfxGtm_Cmu_Tim_Filter_Clk IfxGtm_Tim_Ch_getFilterClockSource(Ifx_GTM_TIM_CH *channel) { return (IfxGtm_Cmu_Tim_Filter_Clk)channel->CTRL.B.FLT_CNT_FRQ; } float32 IfxGtm_Tim_Ch_getTimeoutClockFrequency(Ifx_GTM *gtm, Ifx_GTM_TIM_CH *channel) { IfxGtm_Cmu_Clk clock; clock = IfxGtm_Tim_Ch_getTimeoutClockSource(channel); return IfxGtm_Cmu_getClkFrequency(gtm, clock, TRUE); } IfxGtm_Cmu_Clk IfxGtm_Tim_Ch_getTimeoutClockSource(Ifx_GTM_TIM_CH *channel) { return (IfxGtm_Cmu_Clk)channel->TDUV.B.TCS; } void IfxGtm_Tim_Ch_setChannelNotification(Ifx_GTM_TIM_CH *channel, boolean irqOnNewVal, boolean irqOnCntOverflow, boolean irqOnEcntOverflow, boolean irqOnDatalost) { Ifx_GTM_TIM_CH_IRQ_EN en; en.U = channel->IRQ.EN.U; en.B.NEWVAL_IRQ_EN = irqOnNewVal ? 1 : 0; en.B.CNTOFL_IRQ_EN = irqOnCntOverflow ? 1 : 0; en.B.ECNTOFL_IRQ_EN = irqOnEcntOverflow ? 1 : 0; en.B.GPROFL_IRQ_EN = irqOnDatalost ? 1 : 0; channel->IRQ.EN.U = en.U; } void IfxGtm_Tim_Ch_setClockSource(Ifx_GTM_TIM_CH *channel, IfxGtm_Cmu_Clk clock) { channel->CTRL.B.CLK_SEL = clock; } void IfxGtm_Tim_Ch_setControl(Ifx_GTM_TIM_CH *channel, IfxGtm_Tim_ChannelControl control) { Ifx_GTM_TIM_CH_CTRL ctrl; ctrl.U = channel->CTRL.U; ctrl.B.TIM_EN = control.enable; ctrl.B.TIM_MODE = control.mode; ctrl.B.OSM = control.enableOneShotMode; ctrl.B.ARU_EN = control.enableAruRouting; ctrl.B.CICTRL = control.channelInputControl; ctrl.B.GPR0_SEL = control.gpr0Sel; ctrl.B.GPR1_SEL = control.gpr1Sel; ctrl.B.CNTS_SEL = control.cntsSel; ctrl.B.DSL = control.signalLevelControl; ctrl.B.ISL = control.ignoreSignalLevel; ctrl.B.ECNT_RESET = control.enableCounterReset; ctrl.B.FLT_EN = control.enableFilter; ctrl.B.FLT_CNT_FRQ = control.filterCounterFrequency; ctrl.B.EXT_CAP_EN = control.enableExternalCaptureMode; ctrl.B.FLT_MODE_RE = control.filterModeRisingEdge; ctrl.B.FLT_CTR_RE = control.filterCounterModeRisingEdge; ctrl.B.FLT_MODE_FE = control.filterModeFallingEdge; ctrl.B.FLT_CTR_FE = control.filterCounterModeFallingEdge; ctrl.B.CLK_SEL = control.clkSel; ctrl.B.FR_ECNT_OFL = control.extendEdgeCounterOverflow; ctrl.B.EGPR0_SEL = control.egpr0Sel; ctrl.B.EGPR1_SEL = control.egpr1Sel; ctrl.B.TOCTRL = control.timeoutControl; channel->CTRL.U = ctrl.U; } void IfxGtm_Tim_Ch_setFilterNotification(Ifx_GTM_TIM_CH *channel, boolean irqOnGlitch) { Ifx_GTM_TIM_CH_IRQ_EN en; en.U = channel->IRQ.EN.U; en.B.GLITCHDET_IRQ_EN = irqOnGlitch ? 1 : 0; channel->IRQ.EN.U = en.U; } void IfxGtm_Tim_Ch_setNotificationMode(Ifx_GTM_TIM_CH *channel, IfxGtm_IrqMode mode) { Ifx_GTM_TIM_CH_IRQ_EN en; en.U = channel->IRQ.EN.U; /* Disable all interrupts of the interrupt set to change mode */ channel->IRQ.EN.U = 0; channel->IRQ.MODE.B.IRQ_MODE = mode; channel->IRQ.EN.U = en.U; /* Set the values back */ } void IfxGtm_Tim_Ch_setTimeoutNotification(Ifx_GTM_TIM_CH *channel, boolean irqOnTimeout) { Ifx_GTM_TIM_CH_IRQ_EN en; en.U = channel->IRQ.EN.U; en.B.TODET_IRQ_EN = irqOnTimeout ? 1 : 0; channel->IRQ.EN.U = en.U; }
5706c8e71d3fcd17c2a5e6ab54f5fd9a8d5da1da
6fb39aaadfb3c2306920066448e0f927461633e2
/simulator/ms-tpm-20-ref/TPMCmd/tpm/src/X509/TpmASN1.c
f275c580153e2b99e871707f0f2936f6b7df549b
[ "BSD-2-Clause", "LicenseRef-scancode-proprietary-license", "Apache-2.0", "BSD-3-Clause" ]
permissive
google/go-tpm-tools
f6d9db521c4a1e823679d5312298419643affdc7
9e1f35d66b888ca2021fe0cb721b7ce5daf9eaef
refs/heads/master
2023-08-28T00:38:37.132933
2023-08-16T18:50:59
2023-08-16T18:50:59
161,976,966
181
57
Apache-2.0
2023-09-14T21:55:06
2018-12-16T07:10:09
C
UTF-8
C
false
false
17,313
c
TpmASN1.c
/* Microsoft Reference Implementation for TPM 2.0 * * The copyright in this software is being made available under the BSD License, * included below. This software may be subject to other third party and * contributor rights, including patent rights, and no such rights are granted * under this license. * * Copyright (c) Microsoft Corporation * * All rights reserved. * * BSD License * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //** Includes #include "Tpm.h" #define _OIDS_ #include "OIDs.h" #include "TpmASN1.h" #include "TpmASN1_fp.h" //** Unmarshaling Functions //*** ASN1UnmarshalContextInitialize() // Function does standard initialization of a context. // Return Type: BOOL // TRUE(1) success // FALSE(0) failure BOOL ASN1UnmarshalContextInitialize( ASN1UnmarshalContext *ctx, INT16 size, BYTE *buffer ) { VERIFY(buffer != NULL); VERIFY(size > 0); ctx->buffer = buffer; ctx->size = size; ctx->offset = 0; ctx->tag = 0xFF; return TRUE; Error: return FALSE; } //***ASN1DecodeLength() // This function extracts the length of an element from 'buffer' starting at 'offset'. // Return Type: UINT16 // >=0 the extracted length // <0 an error INT16 ASN1DecodeLength( ASN1UnmarshalContext *ctx ) { BYTE first; // Next octet in buffer INT16 value; // VERIFY(ctx->offset < ctx->size); first = NEXT_OCTET(ctx); // If the number of octets of the entity is larger than 127, then the first octet // is the number of octets in the length specifier. if(first >= 0x80) { // Make sure that this length field is contained with the structure being // parsed CHECK_SIZE(ctx, (first & 0x7F)); if(first == 0x82) { // Two octets of size // get the next value value = (INT16)NEXT_OCTET(ctx); // Make sure that the result will fit in an INT16 VERIFY(value < 0x0080); // Shift up and add next octet value = (value << 8) + NEXT_OCTET(ctx); } else if(first == 0x81) value = NEXT_OCTET(ctx); // Sizes larger than will fit in a INT16 are an error else goto Error; } else value = first; // Make sure that the size defined something within the current context CHECK_SIZE(ctx, value); return value; Error: ctx->size = -1; // Makes everything fail from now on. return -1; } //***ASN1NextTag() // This function extracts the next type from 'buffer' starting at 'offset'. // It advances 'offset' as it parses the type and the length of the type. It returns // the length of the type. On return, the 'length' octets starting at 'offset' are the // octets of the type. // Return Type: UINT // >=0 the number of octets in 'type' // <0 an error INT16 ASN1NextTag( ASN1UnmarshalContext *ctx ) { // A tag to get? VERIFY(ctx->offset < ctx->size); // Get it ctx->tag = NEXT_OCTET(ctx); // Make sure that it is not an extended tag VERIFY((ctx->tag & 0x1F) != 0x1F); // Get the length field and return that return ASN1DecodeLength(ctx); Error: // Attempt to read beyond the end of the context or an illegal tag ctx->size = -1; // Persistent failure ctx->tag = 0xFF; return -1; } //*** ASN1GetBitStringValue() // Try to parse a bit string of up to 32 bits from a value that is expected to be // a bit string. // If there is a general parsing error, the context->size is set to -1. // Return Type: BOOL // TRUE(1) success // FALSE(0) failure BOOL ASN1GetBitStringValue( ASN1UnmarshalContext *ctx, UINT32 *val ) { int shift; INT16 length; UINT32 value = 0; // VERIFY((length = ASN1NextTag(ctx)) >= 1); VERIFY(ctx->tag == ASN1_BITSTRING); // Get the shift value for the bit field (how many bits to loop off of the end) shift = NEXT_OCTET(ctx); length--; // the shift count has to make sense VERIFY((shift < 8) && ((length > 0) || (shift == 0))); // if there are any bytes left for(; length > 0; length--) { if(length > 1) { // for all but the last octet, just shift and add the new octet VERIFY((value & 0xFF000000) == 0); // can't loose significant bits value = (value << 8) + NEXT_OCTET(ctx); } else { // for the last octet, just shift the accumulated value enough to // accept the significant bits in the last octet and shift the last // octet down VERIFY(((value & (0xFF000000 << (8 - shift)))) == 0); value = (value << (8 - shift)) + (NEXT_OCTET(ctx) >> shift); } } *val = value; return TRUE; Error: ctx->size = -1; return FALSE; } //******************************************************************* //** Marshaling Functions //******************************************************************* //*** Introduction // Marshaling of an ASN.1 structure is accomplished from the bottom up. That is, // the things that will be at the end of the structure are added last. To manage the // collecting of the relative sizes, start a context for the outermost container, if // there is one, and then placing items in from the bottom up. If the bottom-most // item is also within a structure, create a nested context by calling // ASN1StartMarshalingContext(). // // The context control structure contains a 'buffer' pointer, an 'offset', an 'end' // and a stack. 'offset' is the offset from the start of the buffer of the last added // byte. When 'offset' reaches 0, the buffer is full. 'offset' is a signed value so // that, when it becomes negative, there is an overflow. Only two functions are // allowed to move bytes into the buffer: ASN1PushByte() and ASN1PushBytes(). These // functions make sure that no data is written beyond the end of the buffer. // // When a new context is started, the current value of 'end' is pushed // on the stack and 'end' is set to 'offset. As bytes are added, offset gets smaller. // At any time, the count of bytes in the current context is simply 'end' - 'offset'. // // Since starting a new context involves setting 'end' = 'offset', the number of bytes // in the context starts at 0. The nominal way of ending a context is to use // 'end' - 'offset' to set the length value, and then a tag is added to the buffer. // Then the previous 'end' value is popped meaning that the context just ended // becomes a member of the now current context. // // The nominal strategy for building a completed ASN.1 structure is to push everything // into the buffer and then move everything to the start of the buffer. The move is // simple as the size of the move is the initial 'end' value minus the final 'offset' // value. The destination is 'buffer' and the source is 'buffer' + 'offset'. As Skippy // would say "Easy peasy, Joe." // // It is not necessary to provide a buffer into which the data is placed. If no buffer // is provided, then the marshaling process will return values needed for marshaling. // On strategy for filling the buffer would be to execute the process for building // the structure without using a buffer. This would return the overall size of the // structure. Then that amount of data could be allocated for the buffer and the fill // process executed again with the data going into the buffer. At the end, the data // would be in its final resting place. //*** ASN1InitialializeMarshalContext() // This creates a structure for handling marshaling of an ASN.1 formatted data // structure. void ASN1InitialializeMarshalContext( ASN1MarshalContext *ctx, INT16 length, BYTE *buffer ) { ctx->buffer = buffer; if(buffer) ctx->offset = length; else ctx->offset = INT16_MAX; ctx->end = ctx->offset; ctx->depth = -1; } //*** ASN1StartMarshalContext() // This starts a new constructed element. It is constructed on 'top' of the value // that was previously placed in the structure. void ASN1StartMarshalContext( ASN1MarshalContext *ctx ) { pAssert((ctx->depth + 1) < MAX_DEPTH); ctx->depth++; ctx->ends[ctx->depth] = ctx->end; ctx->end = ctx->offset; } //*** ASN1EndMarshalContext() // This function restores the end pointer for an encapsulating structure. // Return Type: INT16 // > 0 the size of the encapsulated structure that was just ended // <= 0 an error INT16 ASN1EndMarshalContext( ASN1MarshalContext *ctx ) { INT16 length; pAssert(ctx->depth >= 0); length = ctx->end - ctx->offset; ctx->end = ctx->ends[ctx->depth--]; if((ctx->depth == -1) && (ctx->buffer)) { MemoryCopy(ctx->buffer, ctx->buffer + ctx->offset, ctx->end - ctx->offset); } return length; } //***ASN1EndEncapsulation() // This function puts a tag and length in the buffer. In this function, an embedded // BIT_STRING is assumed to be a collection of octets. To indicate that all bits // are used, a byte of zero is prepended. If a raw bit-string is needed, a new // function like ASN1PushInteger() would be needed. // Return Type: INT16 // > 0 number of octets in the encapsulation // == 0 failure UINT16 ASN1EndEncapsulation( ASN1MarshalContext *ctx, BYTE tag ) { // only add a leading zero for an encapsulated BIT STRING if (tag == ASN1_BITSTRING) ASN1PushByte(ctx, 0); ASN1PushTagAndLength(ctx, tag, ctx->end - ctx->offset); return ASN1EndMarshalContext(ctx); } //*** ASN1PushByte() BOOL ASN1PushByte( ASN1MarshalContext *ctx, BYTE b ) { if(ctx->offset > 0) { ctx->offset -= 1; if(ctx->buffer) ctx->buffer[ctx->offset] = b; return TRUE; } ctx->offset = -1; return FALSE; } //*** ASN1PushBytes() // Push some raw bytes onto the buffer. 'count' cannot be zero. // Return Type: IN16 // > 0 count bytes // == 0 failure unless count was zero INT16 ASN1PushBytes( ASN1MarshalContext *ctx, INT16 count, const BYTE *buffer ) { // make sure that count is not negative which would mess up the math; and that // if there is a count, there is a buffer VERIFY((count >= 0) && ((buffer != NULL) || (count == 0))); // back up the offset to determine where the new octets will get pushed ctx->offset -= count; // can't go negative VERIFY(ctx->offset >= 0); // if there are buffers, move the data, otherwise, assume that this is just a // test. if(count && buffer && ctx->buffer) MemoryCopy(&ctx->buffer[ctx->offset], buffer, count); return count; Error: ctx->offset = -1; return 0; } //*** ASN1PushNull() // Return Type: IN16 // > 0 count bytes // == 0 failure unless count was zero INT16 ASN1PushNull( ASN1MarshalContext *ctx ) { ASN1PushByte(ctx, 0); ASN1PushByte(ctx, ASN1_NULL); return (ctx->offset >= 0) ? 2 : 0; } //*** ASN1PushLength() // Push a length value. This will only handle length values that fit in an INT16. // Return Type: UINT16 // > 0 number of bytes added // == 0 failure INT16 ASN1PushLength( ASN1MarshalContext *ctx, INT16 len ) { UINT16 start = ctx->offset; VERIFY(len >= 0); if(len <= 127) ASN1PushByte(ctx, (BYTE)len); else { ASN1PushByte(ctx, (BYTE)(len & 0xFF)); len >>= 8; if(len == 0) ASN1PushByte(ctx, 0x81); else { ASN1PushByte(ctx, (BYTE)(len)); ASN1PushByte(ctx, 0x82); } } goto Exit; Error: ctx->offset = -1; Exit: return (ctx->offset > 0) ? start - ctx->offset : 0; } //*** ASN1PushTagAndLength() // Return Type: INT16 // > 0 number of bytes added // == 0 failure INT16 ASN1PushTagAndLength( ASN1MarshalContext *ctx, BYTE tag, INT16 length ) { INT16 bytes; bytes = ASN1PushLength(ctx, length); bytes += (INT16)ASN1PushByte(ctx, tag); return (ctx->offset < 0) ? 0 : bytes; } //*** ASN1PushTaggedOctetString() // This function will push a random octet string. // Return Type: INT16 // > 0 number of bytes added // == 0 failure INT16 ASN1PushTaggedOctetString( ASN1MarshalContext *ctx, INT16 size, const BYTE *string, BYTE tag ) { ASN1PushBytes(ctx, size, string); // PushTagAndLenght just tells how many octets it added so the total size of this // element is the sum of those octets and input size. size += ASN1PushTagAndLength(ctx, tag, size); return size; } //*** ASN1PushUINT() // This function pushes an native-endian integer value. This just changes a // native-endian integer into a big-endian byte string and calls ASN1PushInteger(). // That function will remove leading zeros and make sure that the number is positive. // Return Type: IN16 // > 0 count bytes // == 0 failure unless count was zero INT16 ASN1PushUINT( ASN1MarshalContext *ctx, UINT32 integer ) { BYTE marshaled[4]; UINT32_TO_BYTE_ARRAY(integer, marshaled); return ASN1PushInteger(ctx, 4, marshaled); } //*** ASN1PushInteger // Push a big-endian integer on the end of the buffer // Return Type: UINT16 // > 0 the number of bytes marshaled for the integer // == 0 failure INT16 ASN1PushInteger( ASN1MarshalContext *ctx, // IN/OUT: buffer context INT16 iLen, // IN: octets of the integer BYTE *integer // IN: big-endian integer ) { // no leading 0's while((*integer == 0) && (--iLen > 0)) integer++; // Move the bytes to the buffer ASN1PushBytes(ctx, iLen, integer); // if needed, add a leading byte of 0 to make the number positive if(*integer & 0x80) iLen += (INT16)ASN1PushByte(ctx, 0); // PushTagAndLenght just tells how many octets it added so the total size of this // element is the sum of those octets and the adjusted input size. iLen += ASN1PushTagAndLength(ctx, ASN1_INTEGER, iLen); return iLen; } //*** ASN1PushOID() // This function is used to add an OID. An OID is 0x06 followed by a byte of size // followed by size bytes. This is used to avoid having to do anything special in the // definition of an OID. // Return Type: UINT16 // > 0 the number of bytes marshaled for the integer // == 0 failure INT16 ASN1PushOID( ASN1MarshalContext *ctx, const BYTE *OID ) { if((*OID == ASN1_OBJECT_IDENTIFIER) && ((OID[1] & 0x80) == 0)) { return ASN1PushBytes(ctx, OID[1] + 2, OID); } ctx->offset = -1; return 0; }
c28e0257ac6a0cd958a872a6e9a20ebc7bc120af
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
/print/qpdfview/patches/patch-sources_model.h
aa641a766414a5ad7909c107e812807d83f4fec6
[]
no_license
NetBSD/pkgsrc
a0732c023519650ef821ab89c23ab6ab59e25bdb
d042034ec4896cc5b47ed6f2e5b8802d9bc5c556
refs/heads/trunk
2023-09-01T07:40:12.138283
2023-09-01T05:25:19
2023-09-01T05:25:19
88,439,572
321
138
null
2023-07-12T22:34:14
2017-04-16T20:04:15
null
UTF-8
C
false
false
361
h
patch-sources_model.h
$NetBSD: patch-sources_model.h,v 1.1 2020/06/28 14:55:17 nia Exp $ Fix Qt 5.15 fallout. --- sources/model.h.orig 2019-07-24 19:18:33.000000000 +0000 +++ sources/model.h @@ -24,6 +24,7 @@ along with qpdfview. If not, see <http: #define DOCUMENTMODEL_H #include <QList> +#include <QPainterPath> #include <QtPlugin> #include <QWidget> #include <QVector>
377966108905a28ef64ba47b3a61ab84d884acde
e08313883c08d4f41ed3dafd5394f408f309aa92
/render/render.h
d3e65e72792c15fd6464b0844b3e4047efa187be
[ "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
2,464
h
render.h
#pragma once #define NANOSVG_ALL_COLOR_KEYWORDS #include "../nanovg/nanosvg.h" #include "../nanovg/nanovg.h" #include "lvg_header.h" #include <platform/platform.h> #define IMAGE_REPEAT 1 #define GRADIENT_SAMPLES_L 256 #define GRADIENT_SAMPLES_R 256 #define BLEND_REPLACE 0 #define BLEND_LAYER 1 #define BLEND_MULTIPLY 2 #define BLEND_SCREEN 3 #define BLEND_LIGHTEN 4 #define BLEND_DARKEN 5 #define BLEND_DIFFERENCE 6 #define BLEND_ADD 7 #define BLEND_SUBTRACT 8 #define BLEND_INVERT 9 #define BLEND_ALPHA 10 #define BLEND_ERASE 11 #define BLEND_OVERLAY 12 #define BLEND_HARDLIGHT 13 typedef struct render { int (*init)(void **render, const platform *platform); void (*release)(void *render); void (*begin_frame)(void *render, int viewportWidth, int viewportHeight, int winWidth, int winHeight, int width, int height); void (*end_frame)(void *render); int (*cache_shape)(void *render, NSVGshape *shape); int (*cache_image)(void *render, int width, int height, int flags, const void *rgba); int (*cache_gradient)(void *render, NSVGpaint *fill); void (*free_image)(void *render, int image); void (*update_image)(void *render, int image, const void *rgba); void (*render_shape)(void *render, LVGShapeCollection *shapecol, LVGColorTransform *cxform, float ratio, int blend_mode); void (*render_image)(void *render, int image); void (*set_transform)(void *render, float *t, int reset); void (*get_transform)(void *render, float *t); int (*inside_shape)(void *render, NSVGshape *shape, float x, float y); } render; NVGcolor nvgColorU32(uint32_t c); NVGcolor transformColor(NVGcolor color, LVGColorTransform *x); int LinearGradientStops(const render *render, void *render_obj, NSVGgradient *gradient, LVGColorTransform *x); int RadialGradientStops(const render *render, void *render_obj, NSVGgradient *gradient, LVGColorTransform *x); void gl_free_image(void *render, int image); typedef float Transform3x2[2][3]; void identity(Transform3x2 dst); void mul(Transform3x2 dst, Transform3x2 a, Transform3x2 b); void translate(Transform3x2 dst, float x, float y); void scale(Transform3x2 dst, float x, float y); void rotate(Transform3x2 dst, float angle); void xform(float dst[2], Transform3x2 a, const float v[2]); void inverse(Transform3x2 dst, Transform3x2 data); void to_transform3x2(Transform3x2 tr, float *t); void from_transform3x2(float *t, Transform3x2 tr);
39d71af3e345c4717113c045dfff113ad3157b46
06052ccd6db697947c1fcbb6ac96eba79c057fea
/lambdaLayers/SharpLayer/nodejs/node_modules/sharp/vendor/8.10.6/include/libgsf-1/gsf/gsf-infile-msole.h
f2aaa8fd4e2d14290bfc365e11d10b2b7bf16cce
[ "Apache-2.0", "MIT" ]
permissive
venveo/serverless-sharp
89e673e8ab727a00a5bb3cf2c8b9b3876caec8db
1f64468784763bbf40c32497c35de69406765335
refs/heads/master
2023-04-15T01:45:01.990626
2022-06-29T12:30:07
2022-06-29T12:30:07
198,690,918
165
39
MIT
2023-03-04T04:28:54
2019-07-24T18:38:47
JavaScript
UTF-8
C
false
false
1,658
h
gsf-infile-msole.h
/* vim: set sw=8: -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /* * gsf-infile-msole.h: * * Copyright (C) 2002-2006 Jody Goldberg (jody@gnome.org) * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2.1 of the GNU Lesser General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ #ifndef GSF_INFILE_MSOLE_H #define GSF_INFILE_MSOLE_H #include <gsf/gsf-fwd.h> #include <gsf/gsf-infile.h> G_BEGIN_DECLS typedef struct _GsfInfileMSOle GsfInfileMSOle; #define GSF_INFILE_MSOLE_TYPE (gsf_infile_msole_get_type ()) #define GSF_INFILE_MSOLE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GSF_INFILE_MSOLE_TYPE, GsfInfileMSOle)) #define GSF_IS_INFILE_MSOLE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GSF_INFILE_MSOLE_TYPE)) GType gsf_infile_msole_get_type (void); /* void gsf_infile_msole_register_type (GTypeModule *module); glib dynamic types are not thread safe */ GsfInfile *gsf_infile_msole_new (GsfInput *source, GError **err); gboolean gsf_infile_msole_get_class_id (GsfInfileMSOle const *ole, guint8 *res); G_END_DECLS #endif /* GSF_INFILE_MSOLE_H */
0d555ade19ca9b89a324015add1f13d99f56766e
f367e4b66a1ee42e85830b31df88f63723c36a47
/lib/wasm-micro-runtime-WAMR-1.2.2/samples/socket-api/wasm-src/socket_opts.c
890cc0cc5c513148217037679a47bd8ebfe881fb
[ "Apache-2.0", "LLVM-exception" ]
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
10,010
c
socket_opts.c
/* * Copyright (C) 2022 Amazon.com Inc. or its affiliates. All rights reserved. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ #include <arpa/inet.h> #include <errno.h> #include <netinet/tcp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/time.h> #include <unistd.h> #ifdef __wasi__ #include <wasi_socket_ext.h> #endif #define MULTICAST_ADDR 16777440 #define OPTION_ASSERT(A, B, OPTION) \ if (A == B) { \ printf("%s is expected\n", OPTION); \ } \ else { \ printf("%s is unexpected\n", OPTION); \ perror("assertion failed"); \ return EXIT_FAILURE; \ } static struct timeval to_timeval(time_t tv_sec, suseconds_t tv_usec) { struct timeval tv = { tv_sec, tv_usec }; return tv; } static int set_and_get_bool_opt(int socket_fd, int level, int optname, int val) { int bool_opt = val; int ret = -1; socklen_t opt_len = sizeof(bool_opt); ret = setsockopt(socket_fd, level, optname, &bool_opt, sizeof(bool_opt)); if (ret != 0) return !val; bool_opt = !bool_opt; ret = getsockopt(socket_fd, level, optname, &bool_opt, &opt_len); if (ret != 0) return !val; return bool_opt; } int main(int argc, char *argv[]) { int tcp_socket_fd = 0; int udp_socket_fd = 0; int udp_ipv6_socket_fd = 0; struct timeval tv; socklen_t opt_len; int buf_len; int result; struct linger linger_opt; uint32_t time_s; int ttl; printf("[Client] Create TCP socket\n"); tcp_socket_fd = socket(AF_INET, SOCK_STREAM, 0); if (tcp_socket_fd == -1) { perror("Create socket failed"); return EXIT_FAILURE; } printf("[Client] Create UDP socket\n"); udp_socket_fd = socket(AF_INET, SOCK_DGRAM, 0); if (udp_socket_fd == -1) { perror("Create socket failed"); return EXIT_FAILURE; } printf("[Client] Create UDP IPv6 socket\n"); udp_ipv6_socket_fd = socket(AF_INET6, SOCK_DGRAM, 0); if (udp_ipv6_socket_fd == -1) { perror("Create socket failed"); return EXIT_FAILURE; } // SO_RCVTIMEO tv = to_timeval(123, 1000); result = setsockopt(tcp_socket_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); OPTION_ASSERT(result, 0, "setsockopt SO_RCVTIMEO result") tv = to_timeval(0, 0); opt_len = sizeof(tv); result = getsockopt(tcp_socket_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, &opt_len); OPTION_ASSERT(result, 0, "getsockopt SO_RCVTIMEO result") OPTION_ASSERT(tv.tv_sec, 123, "SO_RCVTIMEO tv_sec"); // OPTION_ASSERT(tv.tv_usec, 1000, "SO_RCVTIMEO tv_usec"); // SO_SNDTIMEO tv = to_timeval(456, 2000); result = setsockopt(tcp_socket_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); OPTION_ASSERT(result, 0, "setsockopt SO_SNDTIMEO result") tv = to_timeval(0, 0); opt_len = sizeof(tv); result = getsockopt(tcp_socket_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, &opt_len); OPTION_ASSERT(result, 0, "getsockopt SO_SNDTIMEO result") OPTION_ASSERT(tv.tv_sec, 456, "SO_SNDTIMEO tv_sec"); // OPTION_ASSERT(tv.tv_usec, 2000, "SO_SNDTIMEO tv_usec"); // SO_SNDBUF buf_len = 8192; result = setsockopt(tcp_socket_fd, SOL_SOCKET, SO_SNDBUF, &buf_len, sizeof(buf_len)); OPTION_ASSERT(result, 0, "setsockopt SO_SNDBUF result") buf_len = 0; opt_len = sizeof(buf_len); result = getsockopt(tcp_socket_fd, SOL_SOCKET, SO_SNDBUF, &buf_len, &opt_len); OPTION_ASSERT(result, 0, "getsockopt SO_SNDBUF result") OPTION_ASSERT((buf_len == 16384 || buf_len == 8192), 1, "SO_SNDBUF buf_len"); // SO_RCVBUF buf_len = 4096; result = setsockopt(tcp_socket_fd, SOL_SOCKET, SO_RCVBUF, &buf_len, sizeof(buf_len)); OPTION_ASSERT(result, 0, "setsockopt SO_RCVBUF result") buf_len = 0; opt_len = sizeof(buf_len); result = getsockopt(tcp_socket_fd, SOL_SOCKET, SO_RCVBUF, &buf_len, &opt_len); OPTION_ASSERT(result, 0, "getsockopt SO_RCVBUF result") OPTION_ASSERT((buf_len == 8192 || buf_len == 4096), 1, "SO_SNDBUF buf_len"); // SO_KEEPALIVE OPTION_ASSERT( set_and_get_bool_opt(tcp_socket_fd, SOL_SOCKET, SO_KEEPALIVE, 1), 1, "SO_KEEPALIVE enabled"); OPTION_ASSERT( set_and_get_bool_opt(tcp_socket_fd, SOL_SOCKET, SO_KEEPALIVE, 0), 0, "SO_KEEPALIVE disabled"); // SO_REUSEADDR OPTION_ASSERT( set_and_get_bool_opt(tcp_socket_fd, SOL_SOCKET, SO_REUSEADDR, 1), 1, "SO_REUSEADDR enabled"); OPTION_ASSERT( set_and_get_bool_opt(tcp_socket_fd, SOL_SOCKET, SO_REUSEADDR, 0), 0, "SO_REUSEADDR disabled"); // SO_REUSEPORT OPTION_ASSERT( set_and_get_bool_opt(tcp_socket_fd, SOL_SOCKET, SO_REUSEPORT, 1), 1, "SO_REUSEPORT enabled"); OPTION_ASSERT( set_and_get_bool_opt(tcp_socket_fd, SOL_SOCKET, SO_REUSEPORT, 0), 0, "SO_REUSEPORT disabled"); // SO_LINGER linger_opt.l_onoff = 1; linger_opt.l_linger = 10; result = setsockopt(tcp_socket_fd, SOL_SOCKET, SO_LINGER, &linger_opt, sizeof(linger_opt)); OPTION_ASSERT(result, 0, "setsockopt SO_LINGER result") linger_opt.l_onoff = 0; linger_opt.l_linger = 0; opt_len = sizeof(linger_opt); result = getsockopt(tcp_socket_fd, SOL_SOCKET, SO_LINGER, &linger_opt, &opt_len); OPTION_ASSERT(result, 0, "getsockopt SO_LINGER result") OPTION_ASSERT(linger_opt.l_onoff, 1, "SO_LINGER l_onoff"); OPTION_ASSERT(linger_opt.l_linger, 10, "SO_LINGER l_linger"); // SO_BROADCAST OPTION_ASSERT( set_and_get_bool_opt(udp_socket_fd, SOL_SOCKET, SO_BROADCAST, 1), 1, "SO_BROADCAST enabled"); OPTION_ASSERT( set_and_get_bool_opt(udp_socket_fd, SOL_SOCKET, SO_BROADCAST, 0), 0, "SO_BROADCAST disabled"); // TCP_KEEPIDLE #ifdef TCP_KEEPIDLE time_s = 16; result = setsockopt(tcp_socket_fd, IPPROTO_TCP, TCP_KEEPIDLE, &time_s, sizeof(time_s)); OPTION_ASSERT(result, 0, "setsockopt TCP_KEEPIDLE result") time_s = 0; opt_len = sizeof(time_s); result = getsockopt(tcp_socket_fd, IPPROTO_TCP, TCP_KEEPIDLE, &time_s, &opt_len); OPTION_ASSERT(result, 0, "getsockopt TCP_KEEPIDLE result") OPTION_ASSERT(time_s, 16, "TCP_KEEPIDLE"); #endif // TCP_KEEPINTVL time_s = 8; result = setsockopt(tcp_socket_fd, IPPROTO_TCP, TCP_KEEPINTVL, &time_s, sizeof(time_s)); OPTION_ASSERT(result, 0, "setsockopt TCP_KEEPINTVL result") time_s = 0; opt_len = sizeof(time_s); result = getsockopt(tcp_socket_fd, IPPROTO_TCP, TCP_KEEPINTVL, &time_s, &opt_len); OPTION_ASSERT(result, 0, "getsockopt TCP_KEEPINTVL result") OPTION_ASSERT(time_s, 8, "TCP_KEEPINTVL"); // TCP_FASTOPEN_CONNECT #ifdef TCP_FASTOPEN_CONNECT OPTION_ASSERT(set_and_get_bool_opt(tcp_socket_fd, IPPROTO_TCP, TCP_FASTOPEN_CONNECT, 1), 1, "TCP_FASTOPEN_CONNECT enabled"); OPTION_ASSERT(set_and_get_bool_opt(tcp_socket_fd, IPPROTO_TCP, TCP_FASTOPEN_CONNECT, 0), 0, "TCP_FASTOPEN_CONNECT disabled"); #endif // TCP_NODELAY OPTION_ASSERT( set_and_get_bool_opt(tcp_socket_fd, IPPROTO_TCP, TCP_NODELAY, 1), 1, "TCP_NODELAY enabled"); OPTION_ASSERT( set_and_get_bool_opt(tcp_socket_fd, IPPROTO_TCP, TCP_NODELAY, 0), 0, "TCP_NODELAY disabled"); // TCP_QUICKACK #ifdef TCP_QUICKACK OPTION_ASSERT( set_and_get_bool_opt(tcp_socket_fd, IPPROTO_TCP, TCP_QUICKACK, 1), 1, "TCP_QUICKACK enabled"); OPTION_ASSERT( set_and_get_bool_opt(tcp_socket_fd, IPPROTO_TCP, TCP_QUICKACK, 0), 0, "TCP_QUICKACK disabled"); #endif // IP_TTL ttl = 8; result = setsockopt(tcp_socket_fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl)); OPTION_ASSERT(result, 0, "IP_TIL"); ttl = 0; opt_len = sizeof(ttl); result = getsockopt(tcp_socket_fd, IPPROTO_IP, IP_TTL, &ttl, &opt_len); OPTION_ASSERT(ttl, 8, "IP_TTL"); OPTION_ASSERT(result, 0, "IP_TIL"); // IPV6_V6ONLY OPTION_ASSERT( set_and_get_bool_opt(udp_ipv6_socket_fd, IPPROTO_IPV6, IPV6_V6ONLY, 1), 1, "IPV6_V6ONLY enabled"); OPTION_ASSERT( set_and_get_bool_opt(udp_ipv6_socket_fd, IPPROTO_IPV6, IPV6_V6ONLY, 0), 0, "IPV6_V6ONLY disabled"); // IP_MULTICAST_LOOP OPTION_ASSERT( set_and_get_bool_opt(udp_socket_fd, IPPROTO_IP, IP_MULTICAST_LOOP, 1), 1, "IP_MULTICAST_LOOP enabled"); OPTION_ASSERT( set_and_get_bool_opt(udp_socket_fd, IPPROTO_IP, IP_MULTICAST_LOOP, 0), 0, "IP_MULTICAST_LOOP disabled"); // IP_MULTICAST_TTL ttl = 8; result = setsockopt(udp_socket_fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); OPTION_ASSERT(result, 0, "IP_MULTICAST_TTL"); ttl = 0; opt_len = sizeof(ttl); result = getsockopt(udp_socket_fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, &opt_len); OPTION_ASSERT(ttl, 8, "IP_MULTICAST_TTL"); OPTION_ASSERT(result, 0, "IP_MULTICAST_TTL"); // IPV6_MULTICAST_LOOP OPTION_ASSERT(set_and_get_bool_opt(udp_ipv6_socket_fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, 1), 1, "IPV6_MULTICAST_LOOP enabled"); OPTION_ASSERT(set_and_get_bool_opt(udp_ipv6_socket_fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, 0), 0, "IPV6_MULTICAST_LOOP disabled"); printf("[Client] Close sockets\n"); close(tcp_socket_fd); close(udp_socket_fd); close(udp_ipv6_socket_fd); return EXIT_SUCCESS; }
a96ec761a500802ecc242a96ad1f91c8ea04c319
50e95229b9a1161ac294137120aaba94c9eb06bc
/sources/ippcp/pcpbnarithgcd.c
d35dbc4cc840817d45280c820069ece306ee2f4f
[ "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
9,542
c
pcpbnarithgcd.c
/******************************************************************************* * Copyright (C) 2002 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. * *******************************************************************************/ /* // Intel(R) Integrated Performance Primitives // Cryptographic Primitives (ippcp) // // Contents: // ippsGcd_BN() // */ #include "owndefs.h" #include "owncp.h" #include "pcpbn.h" #include "pcptool.h" /*F* // Name: ippsGcd_BN // // Purpose: compute GCD value. // // Returns: Reason: // ippStsNullPtrErr pA == NULL // pB == NULL // pGCD == NULL // ippStsContextMatchErr !BN_VALID_ID(pA) // !BN_VALID_ID(pB) // !BN_VALID_ID(pGCD) // ippStsBadArgErr A==B==0 // ippStsOutOfRangeErr pGCD can not hold result // ippStsNoErr no errors // // Parameters: // pA source BigNum // pB source BigNum // pGCD GCD value // *F*/ IPPFUN(IppStatus, ippsGcd_BN, (IppsBigNumState* pA, IppsBigNumState* pB, IppsBigNumState* pGCD)) { IPP_BAD_PTR3_RET(pA, pB, pGCD); IPP_BADARG_RET(!BN_VALID_ID(pA), ippStsContextMatchErr); IPP_BADARG_RET(!BN_VALID_ID(pB), ippStsContextMatchErr); IPP_BADARG_RET(!BN_VALID_ID(pGCD), ippStsContextMatchErr); IPP_BADARG_RET(BN_ROOM(pGCD) < IPP_MIN(BN_SIZE(pA), BN_SIZE(pB)), ippStsOutOfRangeErr); { IppsBigNumState* x = pA; IppsBigNumState* y = pB; IppsBigNumState* g = pGCD; int aIsZero = BN_SIZE(pA)==1 && BN_NUMBER(pA)[0]==0; int bIsZero = BN_SIZE(pB)==1 && BN_NUMBER(pB)[0]==0; if(aIsZero && bIsZero) return ippStsBadArgErr; if(aIsZero && !bIsZero) { COPY_BNU(BN_NUMBER(g), BN_NUMBER(pB), BN_SIZE(pB)); BN_SIZE(g) = BN_SIZE(pB); BN_SIGN(g) = ippBigNumPOS; return ippStsNoErr; } if(bIsZero && !aIsZero) { COPY_BNU(BN_NUMBER(g), BN_NUMBER(pA), BN_SIZE(pA)); BN_SIZE(g) = BN_SIZE(pA); BN_SIGN(g) = ippBigNumPOS; return ippStsNoErr; } /* // Lehmer's algorithm requres that first number must be greater than second // x is the first, y is the second */ { int cmpRes = cpCmp_BNU(BN_NUMBER(x), BN_SIZE(x), BN_NUMBER(y), BN_SIZE(y)); if(0>cmpRes) SWAP_PTR(IppsBigNumState, x, y); if(0==cmpRes) { COPY_BNU(BN_NUMBER(g), BN_NUMBER(x), BN_SIZE(x)); BN_SIGN(g) = ippBigNumPOS; BN_SIZE(g) = BN_SIZE(x); return ippStsNoErr; } if(BN_SIZE(x)==1) { BNU_CHUNK_T gcd = cpGcd_BNU(BN_NUMBER(x)[0], BN_NUMBER(y)[0]); BN_NUMBER(g)[0] = gcd; BN_SIZE(g) = 1; return ippStsNoErr; } } { Ipp32u* xBuffer = (Ipp32u*)BN_BUFFER(x); Ipp32u* yBuffer = (Ipp32u*)BN_BUFFER(y); Ipp32u* gBuffer = (Ipp32u*)BN_BUFFER(g); Ipp32u* xData = (Ipp32u*)BN_NUMBER(x); Ipp32u* yData = (Ipp32u*)BN_NUMBER(y); Ipp32u* gData = (Ipp32u*)BN_NUMBER(g); cpSize nsXmax = BN_ROOM(x)*((Ipp32s)(sizeof(BNU_CHUNK_T)/sizeof(Ipp32u))); cpSize nsYmax = BN_ROOM(y)*((Ipp32s)(sizeof(BNU_CHUNK_T)/sizeof(Ipp32u))); cpSize nsGmax = BN_ROOM(g)*((Ipp32s)(sizeof(BNU_CHUNK_T)/sizeof(Ipp32u))); cpSize nsX = BN_SIZE(x)*((Ipp32s)(sizeof(BNU_CHUNK_T)/sizeof(Ipp32u))); cpSize nsY = BN_SIZE(y)*((Ipp32s)(sizeof(BNU_CHUNK_T)/sizeof(Ipp32u))); Ipp32u* T; Ipp32u* u; FIX_BNU32(xData, nsX); FIX_BNU32(yData, nsY); /* init buffers */ ZEXPAND_COPY_BNU(xBuffer, nsXmax, xData, nsX); ZEXPAND_COPY_BNU(yBuffer, nsYmax, yData, nsY); T = gBuffer; u = gData; ZEXPAND_BNU(T, 0, nsGmax); ZEXPAND_BNU(u, 0, nsGmax); while(nsX > (cpSize)(sizeof(BNU_CHUNK_T)/sizeof(Ipp32u))) { /* xx and yy is the high-order digits of x and y (yy could be 0) */ Ipp64u xx = (Ipp64u)(xBuffer[nsX-1]); Ipp64u yy = (nsY < nsX)? 0 : (Ipp64u)(yBuffer[nsY-1]); Ipp64s AA = 1; Ipp64s BB = 0; Ipp64s CC = 0; Ipp64s DD = 1; Ipp64s t; while((yy+(Ipp64u)CC)!=0 && (yy+(Ipp64u)DD)!=0) { Ipp64u q = ( xx + (Ipp64u)AA ) / ( yy + (Ipp64u)CC ); Ipp64u q1 = ( xx + (Ipp64u)BB ) / ( yy + (Ipp64u)DD ); if(q!=q1) break; t = AA - (Ipp64s)q*CC; AA = CC; CC = t; t = BB - (Ipp64s)q*DD; BB = DD; DD = t; t = (Ipp64s)(xx - q*yy); xx = yy; yy = (Ipp64u)t; } if(BB == 0) { /* T = x mod y */ cpSize nsT = cpMod_BNU32(xBuffer, nsX, yBuffer, nsY); ZEXPAND_BNU(T, 0, nsGmax); COPY_BNU(T, xBuffer, nsT); /* a = b; b = T; */ ZEXPAND_BNU(xBuffer, 0, nsXmax); COPY_BNU(xBuffer, yBuffer, nsY); ZEXPAND_BNU(yBuffer, 0, nsYmax); COPY_BNU(yBuffer, T, nsY); } else { Ipp32u carry; /* // T = AA*x + BB*y; // u = CC*x + DD*y; // b = u; a = T; */ if((AA <= 0)&&(BB>=0)) { Ipp32u a1 = (Ipp32u)(-AA); carry = cpMulDgt_BNU32(T, yBuffer, nsY, (Ipp32u)BB); carry = cpMulDgt_BNU32(u, xBuffer, nsY, a1); /* T = BB*y - AA*x; */ carry = cpSub_BNU32(T, T, u, nsY); } else { if((AA >= 0)&&(BB<=0)) { Ipp32u b1 = (Ipp32u)(-BB); carry = cpMulDgt_BNU32(T, xBuffer, nsY, (Ipp32u)AA); carry = cpMulDgt_BNU32(u, yBuffer, nsY, b1); /* T = AA*x - BB*y; */ carry = cpSub_BNU32(T, T, u, nsY); } else { /*AA*BB>=0 */ carry = cpMulDgt_BNU32(T, xBuffer, nsY, (Ipp32u)AA); carry = cpMulDgt_BNU32(u, yBuffer, nsY, (Ipp32u)BB); /* T = AA*x + BB*y; */ carry = cpAdd_BNU32(T, T, u, nsY); } } /* Now T is reserved. We use only u for intermediate results. */ if((CC <= 0)&&(DD>=0)){ Ipp32u c1 = (Ipp32u)(-CC); /* u = x*CC; x = u; */ carry = cpMulDgt_BNU32(u, xBuffer, nsY, c1); COPY_BNU(xBuffer, u, nsY); /* u = y*DD; */ carry = cpMulDgt_BNU32(u, yBuffer, nsY, (Ipp32u)DD); /* u = DD*y - CC*x; */ carry = cpSub_BNU32(u, u, xBuffer, nsY); } else { if((CC >= 0)&&(DD<=0)){ Ipp32u d1 = (Ipp32u)(-DD); /* u = y*DD; y = u */ carry = cpMulDgt_BNU32(u, yBuffer, nsY, d1); COPY_BNU(yBuffer, u, nsY); /* u = CC*x; */ carry = cpMulDgt_BNU32(u, xBuffer, nsY, (Ipp32u)CC); /* u = CC*x - DD*y; */ carry = cpSub_BNU32(u, u, yBuffer, nsY); } else { /*CC*DD>=0 */ /* y = y*DD */ carry = cpMulDgt_BNU32(u, yBuffer, nsY, (Ipp32u)DD); COPY_BNU(yBuffer, u, nsY); /* u = x*CC */ carry = cpMulDgt_BNU32(u, xBuffer, nsY, (Ipp32u)CC); /* u = x*CC + y*DD */ carry = cpAdd_BNU32(u, u, yBuffer, nsY); } } IPP_UNREFERENCED_PARAMETER(carry); /* y = u; x = T; */ COPY_BNU(yBuffer, u, nsY); COPY_BNU(xBuffer, T, nsY); } FIX_BNU32(xBuffer, nsX); FIX_BNU32(yBuffer, nsY); if (nsY > nsX) { SWAP_PTR(IppsBigNumState, x, y); SWAP(nsX, nsY); } if (nsY==1 && yBuffer[nsY-1]==0) { /* End evaluation */ ZEXPAND_BNU(gData, 0, nsGmax); COPY_BNU(gData, xBuffer, nsX); BN_SIZE(g) = INTERNAL_BNU_LENGTH(nsX); BN_SIGN(g) = ippBigNumPOS; return ippStsNoErr; } } BN_NUMBER(g)[0] = cpGcd_BNU(((BNU_CHUNK_T*)xBuffer)[0], ((BNU_CHUNK_T*)yBuffer)[0]); BN_SIZE(g) = 1; BN_SIGN(g) = ippBigNumPOS; return ippStsNoErr; } } }
33fa1284c1d4a222c298786b6bb805c72e3d2061
7c857119fe1505b1d80d6e62969661c06dc1a2f4
/FileSystems/GrubFS/src/driver.c
4217958baf7d8ff6b2333dbe1e37e34085ab22ea
[ "BSD-2-Clause", "GPL-3.0-only" ]
permissive
CloverHackyColor/CloverBootloader
7042ca7dd6b513d22be591a295e49071ae1482ee
2711170df4f60b2ae5aa20add3e00f35cf57b7e5
refs/heads/master
2023-08-30T22:14:34.590134
2023-08-27T19:14:02
2023-08-27T19:14:02
205,810,121
4,734
770
BSD-2-Clause
2023-09-03T12:41:33
2019-09-02T08:22:14
C
UTF-8
C
false
false
15,135
c
driver.c
/* driver.c - Wrapper for standalone EFI filesystem drivers */ /* * Copyright © 2014 Pete Batard <pete@akeo.ie> * Based on iPXE's efi_driver.c and efi_file.c: * Copyright © 2011,2013 Michael Brown <mbrown@fensystems.co.uk>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <Protocol/DriverBinding.h> #include <Protocol/ComponentName.h> #include <Protocol/ComponentName2.h> #include "driver.h" /* We'll try to instantiate a custom protocol as a mutex, so we need a GUID */ EFI_GUID *MutexGUID = NULL; /* Keep a global copy of our ImageHanle */ EFI_HANDLE EfiImageHandle = NULL; /* Handle for our custom protocol/mutex instance */ static EFI_HANDLE MutexHandle = NULL; /* Custom protocol/mutex definition */ typedef struct { INTN Unused; } EFI_MUTEX_PROTOCOL; static EFI_MUTEX_PROTOCOL MutexProtocol = { 0 }; /* Return the driver name */ static EFI_STATUS EFIAPI FSGetDriverName(EFI_COMPONENT_NAME_PROTOCOL *This, CHAR8 *Language, CHAR16 **DriverName) { *DriverName = DriverNameString; return EFI_SUCCESS; } static EFI_STATUS EFIAPI FSGetDriverName2(EFI_COMPONENT_NAME2_PROTOCOL *This, CHAR8 *Language, CHAR16 **DriverName) { *DriverName = DriverNameString; return EFI_SUCCESS; } /* Return the controller name (unsupported for a filesystem) */ static EFI_STATUS EFIAPI FSGetControllerName(EFI_COMPONENT_NAME_PROTOCOL *This, EFI_HANDLE ControllerHandle, EFI_HANDLE ChildHandle, CHAR8 *Language, CHAR16 **ControllerName) { return EFI_UNSUPPORTED; } static EFI_STATUS EFIAPI FSGetControllerName2(EFI_COMPONENT_NAME2_PROTOCOL *This, EFI_HANDLE ControllerHandle, EFI_HANDLE ChildHandle, CHAR8 *Language, CHAR16 **ControllerName) { return EFI_UNSUPPORTED; } static VOID FreeFsInstance(EFI_FS *Instance) { if (Instance->DevicePathString != NULL) { FreePool(Instance->DevicePathString); Instance->DevicePathString = NULL; } if (Instance->RootFile != NULL) { FreePool(Instance->RootFile); Instance->RootFile = NULL; } if (Instance != NULL) { FreePool(Instance); Instance = NULL; } } /* * http://sourceforge.net/p/tianocore/edk2-MdeModulePkg/ci/master/tree/Universal/Disk/DiskIoDxe/DiskIo.c * To check if your driver has a chance to apply to the controllers sent during * the supported detection phase, try to open the child protocols they are meant * to consume in exclusive access (here EFI_DISK_IO). */ static EFI_STATUS EFIAPI FSBindingSupported(EFI_DRIVER_BINDING_PROTOCOL *This, EFI_HANDLE ControllerHandle, EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath) { EFI_STATUS Status; EFI_DISK_IO_PROTOCOL *DiskIo; EFI_DISK_IO2_PROTOCOL *DiskIo2; /* Don't handle this unless we can get exclusive access to DiskIO through it */ Status = BS->OpenProtocol(ControllerHandle, &gEfiDiskIo2ProtocolGuid, (VOID **) &DiskIo2, This->DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_BY_DRIVER); if (EFI_ERROR(Status)) { DiskIo2 = NULL; } Status = BS->OpenProtocol(ControllerHandle, &gEfiDiskIoProtocolGuid, (VOID **) &DiskIo, This->DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_BY_DRIVER); if (EFI_ERROR(Status)) return Status; PrintDebug(L"FSBindingSupported\n"); /* The whole concept of BindingSupported is to hint at what we may * actually support, but not check if the target is valid or * initialize anything, so we must close all protocols we opened. */ BS->CloseProtocol(ControllerHandle, &gEfiDiskIo2ProtocolGuid, This->DriverBindingHandle, ControllerHandle); BS->CloseProtocol(ControllerHandle, &gEfiDiskIoProtocolGuid, This->DriverBindingHandle, ControllerHandle); return EFI_SUCCESS; } static EFI_STATUS EFIAPI FSBindingStart(EFI_DRIVER_BINDING_PROTOCOL *This, EFI_HANDLE ControllerHandle, EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath) { EFI_STATUS Status; EFI_FS *Instance; EFI_DEVICE_PATH *DevicePath; PrintDebug(L"FSBindingStart\n"); /* Allocate a new instance of a filesystem */ Instance = AllocateZeroPool(sizeof(EFI_FS)); if (Instance == NULL) { Status = EFI_OUT_OF_RESOURCES; PrintStatusError(Status, L"Could not allocate a new file system instance"); return Status; } Instance->FileIoInterface.Revision = EFI_FILE_IO_INTERFACE_REVISION; Instance->FileIoInterface.OpenVolume = FileOpenVolume, /* Fill the device path for our instance */ DevicePath = DevicePathFromHandle(ControllerHandle); if (DevicePath == NULL) { Status = EFI_NO_MAPPING; PrintStatusError(Status, L"Could not get Device Path"); goto error; } Instance->DevicePathString = ConvertDevicePathToText(DevicePath, FALSE, FALSE); if (Instance->DevicePathString == NULL) { Status = EFI_OUT_OF_RESOURCES; PrintStatusError(Status, L"Could not allocate Device Path string"); goto error; } /* Get access to the Block IO protocol for this controller */ Status = BS->OpenProtocol(ControllerHandle, &gEfiBlockIo2ProtocolGuid, (VOID **) &Instance->BlockIo2, This->DriverBindingHandle, ControllerHandle, /* http://wiki.phoenix.com/wiki/index.php/EFI_BOOT_SERVICES#OpenProtocol.28.29 * EFI_OPEN_PROTOCOL_BY_DRIVER returns Access Denied here, most likely * because the disk driver has that protocol already open. So we use * EFI_OPEN_PROTOCOL_GET_PROTOCOL (which doesn't require us to close it) */ EFI_OPEN_PROTOCOL_GET_PROTOCOL); if (EFI_ERROR(Status)) { Instance->BlockIo2 = NULL; } Status = BS->OpenProtocol(ControllerHandle, &gEfiBlockIoProtocolGuid, (VOID **) &Instance->BlockIo, This->DriverBindingHandle, ControllerHandle, /* http://wiki.phoenix.com/wiki/index.php/EFI_BOOT_SERVICES#OpenProtocol.28.29 * EFI_OPEN_PROTOCOL_BY_DRIVER returns Access Denied here, most likely * because the disk driver has that protocol already open. So we use * EFI_OPEN_PROTOCOL_GET_PROTOCOL (which doesn't require us to close it) */ EFI_OPEN_PROTOCOL_GET_PROTOCOL); if (EFI_ERROR(Status)) { PrintStatusError(Status, L"Could not access BlockIO protocol"); goto error; } /* Get exclusive access to the Disk IO protocol */ Status = BS->OpenProtocol(ControllerHandle, &gEfiDiskIo2ProtocolGuid, (VOID**) &Instance->DiskIo2, This->DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_BY_DRIVER); if (EFI_ERROR(Status)) { Instance->DiskIo2 = NULL; } Status = BS->OpenProtocol(ControllerHandle, &gEfiDiskIoProtocolGuid, (VOID**) &Instance->DiskIo, This->DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_BY_DRIVER); if (EFI_ERROR(Status)) { PrintStatusError(Status, L"Could not access the DiskIo protocol"); goto error; } /* Go through GRUB target init */ Status = GrubDeviceInit(Instance); if (EFI_ERROR(Status)) { PrintStatusError(Status, L"Could not init grub device"); goto error; } Status = FSInstall(Instance, ControllerHandle); /* Unless we close the DiskIO protocol in case of error, no other * FS driver will be able to access this partition. */ if (EFI_ERROR(Status)) { GrubDeviceExit(Instance); BS->CloseProtocol(ControllerHandle, &gEfiDiskIo2ProtocolGuid, This->DriverBindingHandle, ControllerHandle); BS->CloseProtocol(ControllerHandle, &gEfiDiskIoProtocolGuid, This->DriverBindingHandle, ControllerHandle); } error: if (EFI_ERROR(Status)) FreeFsInstance(Instance); return Status; } static EFI_STATUS EFIAPI FSBindingStop(EFI_DRIVER_BINDING_PROTOCOL *This, EFI_HANDLE ControllerHandle, UINTN NumberOfChildren, EFI_HANDLE *ChildHandleBuffer) { EFI_STATUS Status; EFI_FS *Instance; EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *FileIoInterface; PrintDebug(L"FSBindingStop\n"); /* Get a pointer back to our FS instance through its installed protocol */ Status = BS->OpenProtocol(ControllerHandle, &gEfiSimpleFileSystemProtocolGuid, (VOID **) &FileIoInterface, This->DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL); if (EFI_ERROR(Status)) { PrintStatusError(Status, L"Could not locate our instance"); return Status; } Instance = _CR(FileIoInterface, EFI_FS, FileIoInterface); FSUninstall(Instance, ControllerHandle); Status = GrubDeviceExit(Instance); if (EFI_ERROR(Status)) { PrintStatusError(Status, L"Could not destroy grub device"); } BS->CloseProtocol(ControllerHandle, &gEfiDiskIo2ProtocolGuid, This->DriverBindingHandle, ControllerHandle); BS->CloseProtocol(ControllerHandle, &gEfiDiskIoProtocolGuid, This->DriverBindingHandle, ControllerHandle); FreeFsInstance(Instance); return EFI_SUCCESS; } /* * The platform determines whether it will support the older Component * Name Protocol or the current Component Name2 Protocol, or both. * Because of this, it is strongly recommended that you implement both * protocols in your driver. * * NB: From what I could see, the only difference between Name and Name2 * is that Name uses ISO-639-2 ("eng") whereas Name2 uses RFC 4646 ("en") * See: http://www.loc.gov/standards/iso639-2/faq.html#6 */ static EFI_COMPONENT_NAME_PROTOCOL FSComponentName = { .GetDriverName = FSGetDriverName, .GetControllerName = FSGetControllerName, .SupportedLanguages = (CHAR8 *) "eng" }; static EFI_COMPONENT_NAME2_PROTOCOL FSComponentName2 = { .GetDriverName = FSGetDriverName2, .GetControllerName = FSGetControllerName2, .SupportedLanguages = (CHAR8 *) "en" }; static EFI_DRIVER_BINDING_PROTOCOL FSDriverBinding = { .Supported = FSBindingSupported, .Start = FSBindingStart, .Stop = FSBindingStop, /* This field is used by the EFI boot service ConnectController() to determine the order * that driver's Supported() service will be used when a controller needs to be started. * EFI Driver Binding Protocol instances with higher Version values will be used before * ones with lower Version values. The Version values of 0x0-0x0f and * 0xfffffff0-0xffffffff are reserved for platform/OEM specific drivers. The Version * values of 0x10-0xffffffef are reserved for IHV-developed drivers. */ .Version = 0x10, .ImageHandle = NULL, .DriverBindingHandle = NULL }; /** * Uninstall EFI driver * * @v ImageHandle Handle identifying the loaded image * @ret Status EFI status code to return on exit */ EFI_STATUS EFIAPI FSDriverUninstall(EFI_HANDLE ImageHandle) { EFI_STATUS Status; UINTN NumHandles; EFI_HANDLE *Handles; UINTN i; /* Enumerate all handles */ Status = BS->LocateHandleBuffer(AllHandles, NULL, NULL, &NumHandles, &Handles); /* Disconnect controllers linked to our driver. This action will trigger a call to BindingStop */ if (Status == EFI_SUCCESS) { for (i=0; i<NumHandles; i++) { /* Make sure to filter on DriverBindingHandle, else EVERYTHING gets disconnected! */ Status = BS->DisconnectController(Handles[i], FSDriverBinding.DriverBindingHandle, NULL); if (Status == EFI_SUCCESS) PrintDebug(L"DisconnectController[%d]\n", i); } } else { PrintStatusError(Status, L"Unable to enumerate handles"); } if (Handles != NULL) { BS->FreePool(Handles); Handles = NULL; } /* Now that all controllers are disconnected, we can safely remove our protocols */ BS->UninstallMultipleProtocolInterfaces(ImageHandle, &gEfiDriverBindingProtocolGuid, &FSDriverBinding, &gEfiComponentNameProtocolGuid, &FSComponentName, &gEfiComponentName2ProtocolGuid, &FSComponentName2, NULL); /* Release the relevant GRUB fs module(s) */ GrubDriverExit(); /* Uninstall our mutex (we're the only instance that can run this code) */ BS->UninstallMultipleProtocolInterfaces(MutexHandle, MutexGUID, &MutexProtocol, NULL); PrintDebug(L"FS driver uninstalled.\n"); return EFI_SUCCESS; } /** * Install EFI driver - Will be the entrypoint for our driver executable * http://wiki.phoenix.com/wiki/index.php/EFI_IMAGE_ENTRY_POINT * * @v ImageHandle Handle identifying the loaded image * @v SystemTable Pointers to EFI system calls * @ret Status EFI status code to return on exit */ EFI_STATUS EFIAPI FSDriverInstall(EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE* SystemTable) { EFI_STATUS Status; EFI_LOADED_IMAGE_PROTOCOL *LoadedImage = NULL; VOID *Interface; //InitializeLib(ImageHandle, SystemTable); SetLogging(); EfiImageHandle = ImageHandle; /* Prevent the driver from being loaded twice by detecting and trying to * instantiate a custom protocol, which we use as a global mutex. */ MutexGUID = GetFSGuid(); Status = BS->LocateProtocol(MutexGUID, NULL, &Interface); if (Status == EFI_SUCCESS) { PrintError(L"This driver has already been installed\n"); return EFI_LOAD_ERROR; } /* The only valid status we expect is NOT FOUND here */ if (Status != EFI_NOT_FOUND) { PrintStatusError(Status, L"Could not locate global mutex"); return Status; } Status = BS->InstallMultipleProtocolInterfaces(&MutexHandle, MutexGUID, &MutexProtocol, NULL); if (EFI_ERROR(Status)) { PrintStatusError(Status, L"Could not install global mutex"); return Status; } /* Grab a handle to this image, so that we can add an unload to our driver */ Status = BS->OpenProtocol(ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **) &LoadedImage, ImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL); if (EFI_ERROR(Status)) { PrintStatusError(Status, L"Could not open loaded image protocol"); return Status; } /* Configure driver binding protocol */ FSDriverBinding.ImageHandle = ImageHandle; FSDriverBinding.DriverBindingHandle = ImageHandle; /* Install driver */ Status = BS->InstallMultipleProtocolInterfaces(&FSDriverBinding.DriverBindingHandle, &gEfiDriverBindingProtocolGuid, &FSDriverBinding, &gEfiComponentNameProtocolGuid, &FSComponentName, &gEfiComponentName2ProtocolGuid, &FSComponentName2, NULL); if (EFI_ERROR(Status)) { PrintStatusError(Status, L"Could not bind driver"); return Status; } /* Register the uninstall callback */ LoadedImage->Unload = FSDriverUninstall; /* Initialize the relevant GRUB fs module(s) */ GrubDriverInit(); PrintDebug(L"FS driver installed.\n"); return EFI_SUCCESS; }
d78b75b34621e69728e74e94b309612caf61c8f2
12650661d6bd77a562cfc5dd8414bfb3388ebad3
/Led-green/Led-green.c
67fe2d010fcd2118751936c08752bfb4a7a7793e
[ "Apache-2.0" ]
permissive
varghes/Raspberry-QNX
da08ae9b9805888df4177eaffbefabc545e5f327
043582a94ac94e8311ff7c845beb450a9a718f04
refs/heads/master
2022-08-15T03:31:59.433490
2022-07-30T16:45:46
2022-07-30T16:45:46
66,693,885
112
59
null
2018-03-14T14:42:09
2016-08-27T03:32:17
C
UTF-8
C
false
false
1,357
c
Led-green.c
#include <stdlib.h> #include <stdio.h> #include <hw/inout.h> #include <sys/mman.h> #include <sys/neutrino.h> #include <stdint.h> #include <assert.h> #include <errno.h> #include <pthread.h> #include <unistd.h> #include <string.h> #include <sys/mman.h> #include <sys/neutrino.h> #include <hw/inout.h> #include <sys/slog.h> #include <sys/slogcodes.h> //#define BCM2835_DEBUG_LED #define GPIO_BASE 0x20200000 #define GPIO_REG_SIZE 0x30 #define LED_GPFSEL_GREEN 0x10 #define LED_GPFSEL_RED 0x0C #define LED_GPFBIT_GREEN 21 #define LED_GPFBIT_RED 15 #define LED_GPSET 0x20 #define LED_GPCLR 0x2c #define LED_GPIO_BIT_GREEN 15 #define LED_GPIO_BIT_RED 3 uintptr_t gpio; int main(int argc, char *argv[]) { uintptr_t gpio_base; unsigned int val; printf("LED Test-Green\n"); ThreadCtl (_NTO_TCTL_IO,NULL); gpio_base = mmap_device_io(GPIO_REG_SIZE, GPIO_BASE); if(gpio_base == MAP_DEVICE_FAILED) { perror("Can't map device I/O"); return 0; } val=in32(gpio_base+LED_GPFSEL_GREEN); val&=~(7<<LED_GPFBIT_GREEN); val|=1 << LED_GPFBIT_GREEN; out32(gpio_base+LED_GPFSEL_GREEN,val); while(1) { delay(1000); out32(gpio_base+LED_GPCLR,1<<LED_GPIO_BIT_GREEN); delay(1000); out32(gpio_base+LED_GPSET,1 << LED_GPIO_BIT_GREEN); } munmap_device_io(gpio_base, GPIO_REG_SIZE); return EXIT_SUCCESS; }
ddab9622ad93219bcc7da77890836f6ca2f18af9
f8cc1dd4b1378490386def2e0571561fab10b275
/src/libunixonacid/openwritenclose_at.c
c901952f61fea98ec38712b1dae1493611009cba
[ "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
392
c
openwritenclose_at.c
/* ISC license. */ #include <unistd.h> #include <skalibs/allreadwrite.h> #include <skalibs/djbunix.h> #include <skalibs/unix-transactional.h> size_t openwritenclose_at (int dirfd, char const *file, char const *s, size_t n) { size_t r ; int fd = openc_truncatb(dirfd, file) ; if (fd < 0) return 0 ; r = allwrite(fd, s, n) ; if (r >= n) fsync(fd) ; fd_close(fd) ; return r ; }
6e0d5178647de06100c13a268c44e16caec9d960
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Plugins/Experimental/AlembicImporter/Source/ThirdParty/Alembic/hdf5/src/H5Smpio.c
2187f0e95f1a2736377425b75d053586b105c5f5
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C
false
false
45,789
c
H5Smpio.c
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the files COPYING and Copyright.html. COPYING can be found at the root * * of the source code distribution tree; Copyright.html can be found at the * * root level of an installed copy of the electronic HDF5 document set and * * is linked from the top-level documents page. It can also be found at * * http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have * * access to either file, you may request a copy from help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Programmer: rky 980813 * * Purpose: Functions to read/write directly between app buffer and file. * * Beware of the ifdef'ed print statements. * I didn't make them portable. */ #define H5S_PACKAGE /*suppress error about including H5Spkg */ #include "H5private.h" /* Generic Functions */ #include "H5Dprivate.h" /* Datasets */ #include "H5Eprivate.h" /* Error handling */ #include "H5Fprivate.h" /* File access */ #include "H5FDprivate.h" /* File drivers */ #include "H5Iprivate.h" /* IDs */ #include "H5MMprivate.h" /* Memory management */ #include "H5Oprivate.h" /* Object headers */ #include "H5Pprivate.h" /* Property lists */ #include "H5Spkg.h" /* Dataspaces */ #include "H5VMprivate.h" /* Vector and array functions */ #ifdef H5_HAVE_PARALLEL static herr_t H5S_mpio_all_type(const H5S_t *space, size_t elmt_size, MPI_Datatype *new_type, int *count, hbool_t *is_derived_type); static herr_t H5S_mpio_none_type(MPI_Datatype *new_type, int *count, hbool_t *is_derived_type); static herr_t H5S_mpio_create_point_datatype(size_t elmt_size, hsize_t num_points, MPI_Aint *disp, MPI_Datatype *new_type); static herr_t H5S_mpio_point_type(const H5S_t *space, size_t elmt_size, MPI_Datatype *new_type, int *count, hbool_t *is_derived_type, hbool_t do_permute, hsize_t **permute_map, hbool_t *is_permuted); static herr_t H5S_mpio_permute_type(const H5S_t *space, size_t elmt_size, hsize_t **permute_map, MPI_Datatype *new_type, int *count, hbool_t *is_derived_type); static herr_t H5S_mpio_hyper_type(const H5S_t *space, size_t elmt_size, MPI_Datatype *new_type, int *count, hbool_t *is_derived_type); static herr_t H5S_mpio_span_hyper_type(const H5S_t *space, size_t elmt_size, MPI_Datatype *new_type, int *count, hbool_t *is_derived_type); static herr_t H5S_obtain_datatype(const hsize_t down[], H5S_hyper_span_t* span, const MPI_Datatype *elmt_type, MPI_Datatype *span_type, size_t elmt_size); #define H5S_MPIO_INITIAL_ALLOC_COUNT 256 /*------------------------------------------------------------------------- * Function: H5S_mpio_all_type * * Purpose: Translate an HDF5 "all" selection into an MPI type. * * Return: non-negative on success, negative on failure. * * Outputs: *new_type the MPI type corresponding to the selection * *count how many objects of the new_type in selection * (useful if this is the buffer type for xfer) * *is_derived_type 0 if MPI primitive type, 1 if derived * * Programmer: rky 980813 * *------------------------------------------------------------------------- */ static herr_t H5S_mpio_all_type(const H5S_t *space, size_t elmt_size, MPI_Datatype *new_type, int *count, hbool_t *is_derived_type) { hsize_t total_bytes; hssize_t snelmts; /* Total number of elmts (signed) */ hsize_t nelmts; /* Total number of elmts */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI_NOINIT /* Check args */ HDassert(space); /* Just treat the entire extent as a block of bytes */ if((snelmts = (hssize_t)H5S_GET_EXTENT_NPOINTS(space)) < 0) HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, FAIL, "src dataspace has invalid selection") H5_CHECKED_ASSIGN(nelmts, hsize_t, snelmts, hssize_t); total_bytes = (hsize_t)elmt_size * nelmts; /* fill in the return values */ *new_type = MPI_BYTE; H5_CHECKED_ASSIGN(*count, int, total_bytes, hsize_t); *is_derived_type = FALSE; done: FUNC_LEAVE_NOAPI(ret_value) } /* H5S_mpio_all_type() */ /*------------------------------------------------------------------------- * Function: H5S_mpio_none_type * * Purpose: Translate an HDF5 "none" selection into an MPI type. * * Return: non-negative on success, negative on failure. * * Outputs: *new_type the MPI type corresponding to the selection * *count how many objects of the new_type in selection * (useful if this is the buffer type for xfer) * *is_derived_type 0 if MPI primitive type, 1 if derived * * Programmer: Quincey Koziol, October 29, 2002 * *------------------------------------------------------------------------- */ static herr_t H5S_mpio_none_type(MPI_Datatype *new_type, int *count, hbool_t *is_derived_type) { FUNC_ENTER_NOAPI_NOINIT_NOERR /* fill in the return values */ *new_type = MPI_BYTE; *count = 0; *is_derived_type = FALSE; FUNC_LEAVE_NOAPI(SUCCEED) } /* H5S_mpio_none_type() */ /*------------------------------------------------------------------------- * Function: H5S_mpio_create_point_datatype * * Purpose: Create a derived datatype for point selections. * * Return: non-negative on success, negative on failure. * * Outputs: *new_type the MPI type corresponding to the selection * * Programmer: Mohamad Chaarawi * *------------------------------------------------------------------------- */ static herr_t H5S_mpio_create_point_datatype (size_t elmt_size, hsize_t num_points, MPI_Aint *disp, MPI_Datatype *new_type) { MPI_Datatype elmt_type; /* MPI datatype for individual element */ hbool_t elmt_type_created = FALSE; /* Whether the element MPI datatype was created */ int mpi_code; /* MPI error code */ int *blocks = NULL; /* Array of block sizes for MPI hindexed create call */ hsize_t u; /* Local index variable */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI_NOINIT /* Create an MPI datatype for an element */ if(MPI_SUCCESS != (mpi_code = MPI_Type_contiguous((int)elmt_size, MPI_BYTE, &elmt_type))) HMPI_GOTO_ERROR(FAIL, "MPI_Type_contiguous failed", mpi_code) elmt_type_created = TRUE; /* Allocate block sizes for MPI datatype call */ if(NULL == (blocks = (int *)H5MM_malloc(sizeof(int) * num_points))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate array of blocks") /* Would be nice to have Create_Hindexed_block to avoid this array of all ones */ for(u = 0; u < num_points; u++) blocks[u] = 1; /* Create an MPI datatype for the whole point selection */ if(MPI_SUCCESS != (mpi_code = MPI_Type_create_hindexed((int)num_points, blocks, disp, elmt_type, new_type))) HMPI_GOTO_ERROR(FAIL, "MPI_Type_create_indexed_block failed", mpi_code) /* Commit MPI datatype for later use */ if(MPI_SUCCESS != (mpi_code = MPI_Type_commit(new_type))) HMPI_GOTO_ERROR(FAIL, "MPI_Type_commit failed", mpi_code) done: if(elmt_type_created) MPI_Type_free(&elmt_type); if(blocks) H5MM_free(blocks); FUNC_LEAVE_NOAPI(ret_value) } /* H5S_mpio_create_point_datatype() */ /*------------------------------------------------------------------------- * Function: H5S_mpio_point_type * * Purpose: Translate an HDF5 "point" selection into an MPI type. * Create a permutation array to handle out-of-order point selections. * * Return: non-negative on success, negative on failure. * * Outputs: *new_type the MPI type corresponding to the selection * *count how many objects of the new_type in selection * (useful if this is the buffer type for xfer) * *is_derived_type 0 if MPI primitive type, 1 if derived * *permute_map the permutation of the displacements to create * the MPI_Datatype * *is_permuted 0 if the displacements are permuted, 1 if not * * Programmer: Mohamad Chaarawi * *------------------------------------------------------------------------- */ static herr_t H5S_mpio_point_type(const H5S_t *space, size_t elmt_size, MPI_Datatype *new_type, int *count, hbool_t *is_derived_type, hbool_t do_permute, hsize_t **permute, hbool_t *is_permuted) { MPI_Aint *disp = NULL; /* Datatype displacement for each point*/ H5S_pnt_node_t *curr = NULL; /* Current point being operated on in from the selection */ hssize_t snum_points; /* Signed number of elements in selection */ hsize_t num_points; /* Sumber of points in the selection */ hsize_t u; /* Local index variable */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI_NOINIT /* Check args */ HDassert(space); /* Get the total number of points selected */ if((snum_points = (hssize_t)H5S_GET_SELECT_NPOINTS(space)) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOUNT, FAIL, "can't get number of elements selected") num_points = (hsize_t)snum_points; /* Allocate array for element displacements */ if(NULL == (disp = (MPI_Aint *)H5MM_malloc(sizeof(MPI_Aint) * num_points))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate array of displacements") /* Allocate array for element permutation - returned to caller */ if(do_permute) if(NULL == (*permute = (hsize_t *)H5MM_malloc(sizeof(hsize_t) * num_points))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate permutation array") /* Iterate through list of elements */ curr = space->select.sel_info.pnt_lst->head; for(u = 0 ; u < num_points ; u++) { /* calculate the displacement of the current point */ disp[u] = H5VM_array_offset(space->extent.rank, space->extent.size, curr->pnt); disp[u] *= elmt_size; /* This is a File Space used to set the file view, so adjust the displacements * to have them monotonically non-decreasing. * Generate the permutation array by indicating at each point being selected, * the position it will shifted in the new displacement. Example: * Suppose 4 points with corresponding are selected * Pt 1: disp=6 ; Pt 2: disp=3 ; Pt 3: disp=0 ; Pt 4: disp=4 * The permute map to sort the displacements in order will be: * point 1: map[0] = L, indicating that this point is not moved (1st point selected) * point 2: map[1] = 0, indicating that this point is moved to the first position, * since disp_pt1(6) > disp_pt2(3) * point 3: map[2] = 0, move to position 0, bec it has the lowest disp between * the points selected so far. * point 4: map[3] = 2, move the 2nd position since point 1 has a higher disp, * but points 2 and 3 have lower displacements. */ if(do_permute) { if(u > 0 && disp[u] < disp[u - 1]) { unsigned s = 0, l = u, m = u / 2; *is_permuted = TRUE; do { if(disp[u] > disp[m]) s = m + 1; else if(disp[u] < disp[m]) l = m; else break; m = s + ((l - s) / 2); } while(s < l); if(m < u) { MPI_Aint temp; temp = disp[u]; HDmemmove(disp + m + 1, disp + m, (u - m) * sizeof(MPI_Aint)); disp[m] = temp; } /* end if */ (*permute)[u] = m; } /* end if */ else (*permute)[u] = num_points; } /* end if */ /* this is a memory space, and no permutation is necessary to create the derived datatype */ else { ;/* do nothing */ } /* end else */ /* get the next point */ curr = curr->next; } /* end for */ /* Create the MPI datatype for the set of element displacements */ if(H5S_mpio_create_point_datatype(elmt_size, num_points, disp, new_type) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_BADTYPE, FAIL, "couldn't create an MPI Datatype from point selection") /* Set values about MPI datatype created */ *count = 1; *is_derived_type = TRUE; done: if(NULL != disp) H5MM_free(disp); /* Release the permutation buffer, if it wasn't used */ if(!(*is_permuted) && (*permute)) { H5MM_free(*permute); *permute = NULL; } /* end if */ FUNC_LEAVE_NOAPI(ret_value) } /* H5S_mpio_point_type() */ /*------------------------------------------------------------------------- * Function: H5S_mpio_permute_type * * Purpose: Translate an HDF5 "all/hyper/point" selection into an MPI type, * while applying the permutation map. This function is called if * the file space selection is permuted due to out-of-order point * selection and so the memory datatype has to be permuted using the * permutation map created by the file selection. * * Note: This routine is called from H5S_mpio_space_type(), which is * called first for the file dataspace and creates * * Return: non-negative on success, negative on failure. * * Outputs: *new_type the MPI type corresponding to the selection * *count how many objects of the new_type in selection * (useful if this is the buffer type for xfer) * *is_derived_type 0 if MPI primitive type, 1 if derived * * Programmer: Mohamad Chaarawi * *------------------------------------------------------------------------- */ static herr_t H5S_mpio_permute_type(const H5S_t *space, size_t elmt_size, hsize_t **permute, MPI_Datatype *new_type, int *count, hbool_t *is_derived_type) { MPI_Aint *disp = NULL; /* Datatype displacement for each point*/ H5S_sel_iter_t sel_iter; /* Selection iteration info */ hbool_t sel_iter_init = FALSE; /* Selection iteration info has been initialized */ hsize_t off[H5D_IO_VECTOR_SIZE]; /* Array to store sequence offsets */ size_t len[H5D_IO_VECTOR_SIZE]; /* Array to store sequence lengths */ hssize_t snum_points; /* Signed number of elements in selection */ hsize_t num_points; /* Number of points in the selection */ size_t max_elem; /* Maximum number of elements allowed in sequences */ hsize_t u; /* Local index variable */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI_NOINIT /* Check args */ HDassert(space); /* Get the total number of points selected */ if((snum_points = (hssize_t)H5S_GET_SELECT_NPOINTS(space)) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOUNT, FAIL, "can't get number of elements selected") num_points = (hsize_t)snum_points; /* Allocate array to store point displacements */ if(NULL == (disp = (MPI_Aint *)H5MM_malloc(sizeof(MPI_Aint) * num_points))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate array of displacements") /* Initialize selection iterator */ if(H5S_select_iter_init(&sel_iter, space, elmt_size) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "unable to initialize selection iterator") sel_iter_init = TRUE; /* Selection iteration info has been initialized */ /* Set the number of elements to iterate over */ H5_CHECKED_ASSIGN(max_elem, size_t, num_points, hsize_t); /* Loop, while elements left in selection */ u = 0; while(max_elem > 0) { hsize_t off[H5D_IO_VECTOR_SIZE]; /* Array to store sequence offsets */ size_t len[H5D_IO_VECTOR_SIZE]; /* Array to store sequence lengths */ size_t nelem; /* Number of elements used in sequences */ size_t nseq; /* Number of sequences generated */ size_t curr_seq; /* Current sequence being worked on */ /* Get the sequences of bytes */ if(H5S_SELECT_GET_SEQ_LIST(space, 0, &sel_iter, (size_t)H5D_IO_VECTOR_SIZE, max_elem, &nseq, &nelem, off, len) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "sequence length generation failed") /* Loop, while sequences left to process */ for(curr_seq = 0; curr_seq < nseq; curr_seq++) { hsize_t curr_off; /* Current offset within sequence */ size_t curr_len; /* Length of bytes left to process in sequence */ /* Get the current offset */ curr_off = off[curr_seq]; /* Get the number of bytes in sequence */ curr_len = len[curr_seq]; /* Loop, while bytes left in sequence */ while(curr_len > 0) { /* Set the displacement of the current point */ disp[u] = curr_off; /* This is a memory displacement, so for each point selected, * apply the map that was generated by the file selection */ if((*permute)[u] != num_points) { MPI_Aint temp = disp[u]; HDmemmove(disp + (*permute)[u] + 1, disp + (*permute)[u], (u - (*permute)[u]) * sizeof(MPI_Aint)); disp[(*permute)[u]] = temp; } /* end if */ /* Advance to next element */ u++; /* Increment offset in dataspace */ curr_off += elmt_size; /* Decrement number of bytes left in sequence */ curr_len -= elmt_size; } /* end while */ } /* end for */ /* Decrement number of elements left to process */ max_elem -= nelem; } /* end while */ /* Create the MPI datatype for the set of element displacements */ if(H5S_mpio_create_point_datatype(elmt_size, num_points, disp, new_type) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_BADTYPE, FAIL, "couldn't create an MPI Datatype from point selection") /* Set values about MPI datatype created */ *count = 1; *is_derived_type = TRUE; done: /* Release selection iterator */ if(sel_iter_init) if(H5S_SELECT_ITER_RELEASE(&sel_iter) < 0) HDONE_ERROR(H5E_DATASPACE, H5E_CANTRELEASE, FAIL, "unable to release selection iterator") /* Free memory */ if(disp) H5MM_free(disp); if(*permute) { H5MM_free(*permute); *permute = NULL; } /* end if */ FUNC_LEAVE_NOAPI(ret_value) } /* H5S_mpio_permute_type() */ /*------------------------------------------------------------------------- * Function: H5S_mpio_hyper_type * * Purpose: Translate an HDF5 hyperslab selection into an MPI type. * * Return: non-negative on success, negative on failure. * * Outputs: *new_type the MPI type corresponding to the selection * *count how many objects of the new_type in selection * (useful if this is the buffer type for xfer) * *is_derived_type 0 if MPI primitive type, 1 if derived * * Programmer: rky 980813 * *------------------------------------------------------------------------- */ static herr_t H5S_mpio_hyper_type(const H5S_t *space, size_t elmt_size, MPI_Datatype *new_type, int *count, hbool_t *is_derived_type) { H5S_sel_iter_t sel_iter; /* Selection iteration info */ hbool_t sel_iter_init = FALSE; /* Selection iteration info has been initialized */ struct dim { /* less hassle than malloc/free & ilk */ hssize_t start; hsize_t strid; hsize_t block; hsize_t xtent; hsize_t count; } d[H5S_MAX_RANK]; hsize_t offset[H5S_MAX_RANK]; hsize_t max_xtent[H5S_MAX_RANK]; H5S_hyper_dim_t *diminfo; /* [rank] */ unsigned rank; MPI_Datatype inner_type, outer_type; MPI_Aint extent_len, start_disp, new_extent; MPI_Aint lb; /* Needed as an argument for MPI_Type_get_extent */ unsigned u; /* Local index variable */ int i; /* Local index variable */ int mpi_code; /* MPI return code */ herr_t ret_value = SUCCEED; FUNC_ENTER_NOAPI_NOINIT /* Check args */ HDassert(space); HDassert(sizeof(MPI_Aint) >= sizeof(elmt_size)); /* Initialize selection iterator */ if(H5S_select_iter_init(&sel_iter, space, elmt_size) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "unable to initialize selection iterator") sel_iter_init = TRUE; /* Selection iteration info has been initialized */ /* Abbreviate args */ diminfo = sel_iter.u.hyp.diminfo; HDassert(diminfo); /* make a local copy of the dimension info so we can operate with them */ /* Check if this is a "flattened" regular hyperslab selection */ if(sel_iter.u.hyp.iter_rank != 0 && sel_iter.u.hyp.iter_rank < space->extent.rank) { /* Flattened selection */ rank = sel_iter.u.hyp.iter_rank; HDassert(rank <= H5S_MAX_RANK); /* within array bounds */ #ifdef H5S_DEBUG if(H5DEBUG(S)) HDfprintf(H5DEBUG(S), "%s: Flattened selection\n",FUNC); #endif for(u = 0; u < rank; ++u) { H5_CHECK_OVERFLOW(diminfo[u].start, hsize_t, hssize_t) d[u].start = (hssize_t)diminfo[u].start + sel_iter.u.hyp.sel_off[u]; d[u].strid = diminfo[u].stride; d[u].block = diminfo[u].block; d[u].count = diminfo[u].count; d[u].xtent = sel_iter.u.hyp.size[u]; #ifdef H5S_DEBUG if(H5DEBUG(S)){ HDfprintf(H5DEBUG(S), "%s: start=%Hd stride=%Hu count=%Hu block=%Hu xtent=%Hu", FUNC, d[u].start, d[u].strid, d[u].count, d[u].block, d[u].xtent ); if (u==0) HDfprintf(H5DEBUG(S), " rank=%u\n", rank ); else HDfprintf(H5DEBUG(S), "\n" ); } #endif if(0 == d[u].block) goto empty; if(0 == d[u].count) goto empty; if(0 == d[u].xtent) goto empty; } /* end for */ } /* end if */ else { /* Non-flattened selection */ rank = space->extent.rank; HDassert(rank <= H5S_MAX_RANK); /* within array bounds */ if(0 == rank) goto empty; #ifdef H5S_DEBUG if(H5DEBUG(S)) HDfprintf(H5DEBUG(S),"%s: Non-flattened selection\n",FUNC); #endif for(u = 0; u < rank; ++u) { H5_CHECK_OVERFLOW(diminfo[u].start, hsize_t, hssize_t) d[u].start = (hssize_t)diminfo[u].start + space->select.offset[u]; d[u].strid = diminfo[u].stride; d[u].block = diminfo[u].block; d[u].count = diminfo[u].count; d[u].xtent = space->extent.size[u]; #ifdef H5S_DEBUG if(H5DEBUG(S)){ HDfprintf(H5DEBUG(S), "%s: start=%Hd stride=%Hu count=%Hu block=%Hu xtent=%Hu", FUNC, d[u].start, d[u].strid, d[u].count, d[u].block, d[u].xtent ); if (u==0) HDfprintf(H5DEBUG(S), " rank=%u\n", rank ); else HDfprintf(H5DEBUG(S), "\n" ); } #endif if(0 == d[u].block) goto empty; if(0 == d[u].count) goto empty; if(0 == d[u].xtent) goto empty; } /* end for */ } /* end else */ /********************************************************************** Compute array "offset[rank]" which gives the offsets for a multi- dimensional array with dimensions "d[i].xtent" (i=0,1,...,rank-1). **********************************************************************/ offset[rank - 1] = 1; max_xtent[rank - 1] = d[rank - 1].xtent; #ifdef H5S_DEBUG if(H5DEBUG(S)) { i = ((int)rank) - 1; HDfprintf(H5DEBUG(S), " offset[%2d]=%Hu; max_xtent[%2d]=%Hu\n", i, offset[i], i, max_xtent[i]); } #endif for(i = ((int)rank) - 2; i >= 0; --i) { offset[i] = offset[i + 1] * d[i + 1].xtent; max_xtent[i] = max_xtent[i + 1] * d[i].xtent; #ifdef H5S_DEBUG if(H5DEBUG(S)) HDfprintf(H5DEBUG(S), " offset[%2d]=%Hu; max_xtent[%2d]=%Hu\n", i, offset[i], i, max_xtent[i]); #endif } /* end for */ /* Create a type covering the selected hyperslab. * Multidimensional dataspaces are stored in row-major order. * The type is built from the inside out, going from the * fastest-changing (i.e., inner) dimension * to the slowest (outer). */ /******************************************************* * Construct contig type for inner contig dims: *******************************************************/ #ifdef H5S_DEBUG if(H5DEBUG(S)) { HDfprintf(H5DEBUG(S), "%s: Making contig type %Zu MPI_BYTEs\n", FUNC, elmt_size); for(i = ((int)rank) - 1; i >= 0; --i) HDfprintf(H5DEBUG(S), "d[%d].xtent=%Hu \n", i, d[i].xtent); } #endif if(MPI_SUCCESS != (mpi_code = MPI_Type_contiguous((int)elmt_size, MPI_BYTE, &inner_type))) HMPI_GOTO_ERROR(FAIL, "MPI_Type_contiguous failed", mpi_code) /******************************************************* * Construct the type by walking the hyperslab dims * from the inside out: *******************************************************/ for(i = ((int)rank) - 1; i >= 0; --i) { #ifdef H5S_DEBUG if(H5DEBUG(S)) HDfprintf(H5DEBUG(S), "%s: Dimension i=%d \n" "start=%Hd count=%Hu block=%Hu stride=%Hu, xtent=%Hu max_xtent=%d\n", FUNC, i, d[i].start, d[i].count, d[i].block, d[i].strid, d[i].xtent, max_xtent[i]); #endif #ifdef H5S_DEBUG if(H5DEBUG(S)) HDfprintf(H5DEBUG(S), "%s: i=%d Making vector-type \n", FUNC,i); #endif /**************************************** * Build vector type of the selection. ****************************************/ mpi_code = MPI_Type_vector((int)(d[i].count), /* count */ (int)(d[i].block), /* blocklength */ (int)(d[i].strid), /* stride */ inner_type, /* old type */ &outer_type); /* new type */ MPI_Type_free(&inner_type); if(mpi_code != MPI_SUCCESS) HMPI_GOTO_ERROR(FAIL, "couldn't create MPI vector type", mpi_code) /**************************************** * Then build the dimension type as (start, vector type, xtent). ****************************************/ /* calculate start and extent values of this dimension */ start_disp = d[i].start * offset[i] * elmt_size; new_extent = (MPI_Aint)elmt_size * max_xtent[i]; if(MPI_SUCCESS != (mpi_code = MPI_Type_get_extent(outer_type, &lb, &extent_len))) HMPI_GOTO_ERROR(FAIL, "MPI_Type_get_extent failed", mpi_code) /************************************************* * Restructure this datatype ("outer_type") * so that it still starts at 0, but its extent * is the full extent in this dimension. *************************************************/ if(start_disp > 0 || extent_len < new_extent) { MPI_Datatype interm_type; int block_len = 1; HDassert(0 == lb); mpi_code = MPI_Type_create_hindexed(1, &block_len, &start_disp, outer_type, &interm_type); MPI_Type_free(&outer_type); if(mpi_code != MPI_SUCCESS) HMPI_GOTO_ERROR(FAIL, "MPI_Type_create_hindexed failed", mpi_code) mpi_code = MPI_Type_create_resized(interm_type, lb, new_extent, &inner_type); MPI_Type_free(&interm_type); if(mpi_code != MPI_SUCCESS) HMPI_GOTO_ERROR(FAIL, "couldn't resize MPI vector type", mpi_code) } /* end if */ else inner_type = outer_type; } /* end for */ /*************************** * End of loop, walking * thru dimensions. ***************************/ /* At this point inner_type is actually the outermost type, even for 0-trip loop */ *new_type = inner_type; if(MPI_SUCCESS != (mpi_code = MPI_Type_commit(new_type))) HMPI_GOTO_ERROR(FAIL, "MPI_Type_commit failed", mpi_code) /* fill in the remaining return values */ *count = 1; /* only have to move one of these suckers! */ *is_derived_type = TRUE; HGOTO_DONE(SUCCEED); empty: /* special case: empty hyperslab */ *new_type = MPI_BYTE; *count = 0; *is_derived_type = FALSE; done: /* Release selection iterator */ if(sel_iter_init) if(H5S_SELECT_ITER_RELEASE(&sel_iter) < 0) HDONE_ERROR(H5E_DATASPACE, H5E_CANTRELEASE, FAIL, "unable to release selection iterator") #ifdef H5S_DEBUG if(H5DEBUG(S)) HDfprintf(H5DEBUG(S), "Leave %s, count=%ld is_derived_type=%t\n", FUNC, *count, *is_derived_type ); #endif FUNC_LEAVE_NOAPI(ret_value) } /* end H5S_mpio_hyper_type() */ /*------------------------------------------------------------------------- * Function: H5S_mpio_span_hyper_type * * Purpose: Translate an HDF5 irregular hyperslab selection into an MPI type. * * Return: non-negative on success, negative on failure. * * Outputs: *new_type the MPI type corresponding to the selection * *count how many objects of the new_type in selection * (useful if this is the buffer type for xfer) * *is_derived_type 0 if MPI primitive type, 1 if derived * * Programmer: kyang * *------------------------------------------------------------------------- */ static herr_t H5S_mpio_span_hyper_type(const H5S_t *space, size_t elmt_size, MPI_Datatype *new_type, int *count, hbool_t *is_derived_type) { MPI_Datatype elmt_type; /* MPI datatype for an element */ hbool_t elmt_type_is_derived = FALSE; /* Whether the element type has been created */ MPI_Datatype span_type; /* MPI datatype for overall span tree */ hsize_t down[H5S_MAX_RANK]; /* 'down' sizes for each dimension */ int mpi_code; /* MPI return code */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI_NOINIT /* Check args */ HDassert(space); HDassert(space->extent.size); HDassert(space->select.sel_info.hslab->span_lst); HDassert(space->select.sel_info.hslab->span_lst->head); /* Create the base type for an element */ if(MPI_SUCCESS != (mpi_code = MPI_Type_contiguous((int)elmt_size, MPI_BYTE, &elmt_type))) HMPI_GOTO_ERROR(FAIL, "MPI_Type_contiguous failed", mpi_code) elmt_type_is_derived = TRUE; /* Compute 'down' sizes for each dimension */ if(H5VM_array_down(space->extent.rank, space->extent.size, down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTGETSIZE, FAIL, "couldn't compute 'down' dimension sizes") /* Obtain derived data type */ if(H5S_obtain_datatype(down, space->select.sel_info.hslab->span_lst->head, &elmt_type, &span_type, elmt_size) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_BADTYPE, FAIL, "couldn't obtain MPI derived data type") if(MPI_SUCCESS != (mpi_code = MPI_Type_commit(&span_type))) HMPI_GOTO_ERROR(FAIL, "MPI_Type_commit failed", mpi_code) *new_type = span_type; /* fill in the remaining return values */ *count = 1; *is_derived_type = TRUE; done: /* Release resources */ if(elmt_type_is_derived) if(MPI_SUCCESS != (mpi_code = MPI_Type_free(&elmt_type))) HMPI_DONE_ERROR(FAIL, "MPI_Type_free failed", mpi_code) FUNC_LEAVE_NOAPI(ret_value) } /* end H5S_mpio_span_hyper_type() */ /*------------------------------------------------------------------------- * Function: H5S_obtain_datatype * * Purpose: Obtain an MPI derived datatype based on span-tree * implementation * * Return: non-negative on success, negative on failure. * * Outputs: *span_type the MPI type corresponding to the selection * * Programmer: kyang * *------------------------------------------------------------------------- */ static herr_t H5S_obtain_datatype(const hsize_t *down, H5S_hyper_span_t *span, const MPI_Datatype *elmt_type, MPI_Datatype *span_type, size_t elmt_size) { size_t alloc_count; /* Number of span tree nodes allocated at this level */ size_t outercount; /* Number of span tree nodes at this level */ MPI_Datatype *inner_type = NULL; hbool_t inner_types_freed = FALSE; /* Whether the inner_type MPI datatypes have been freed */ hbool_t span_type_valid = FALSE; /* Whether the span_type MPI datatypes is valid */ int *blocklen = NULL; MPI_Aint *disp = NULL; H5S_hyper_span_t *tspan; /* Temporary pointer to span tree node */ int mpi_code; /* MPI return status code */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI_NOINIT /* Sanity check */ HDassert(span); /* Allocate the initial displacement & block length buffers */ alloc_count = H5S_MPIO_INITIAL_ALLOC_COUNT; if(NULL == (disp = (MPI_Aint *)H5MM_malloc(alloc_count * sizeof(MPI_Aint)))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate array of displacements") if(NULL == (blocklen = (int *)H5MM_malloc(alloc_count * sizeof(int)))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate array of block lengths") /* if this is the fastest changing dimension, it is the base case for derived datatype. */ if(NULL == span->down) { tspan = span; outercount = 0; while(tspan) { /* Check if we need to increase the size of the buffers */ if(outercount >= alloc_count) { MPI_Aint *tmp_disp; /* Temporary pointer to new displacement buffer */ int *tmp_blocklen; /* Temporary pointer to new block length buffer */ /* Double the allocation count */ alloc_count *= 2; /* Re-allocate the buffers */ if(NULL == (tmp_disp = (MPI_Aint *)H5MM_realloc(disp, alloc_count * sizeof(MPI_Aint)))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate array of displacements") disp = tmp_disp; if(NULL == (tmp_blocklen = (int *)H5MM_realloc(blocklen, alloc_count * sizeof(int)))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate array of block lengths") blocklen = tmp_blocklen; } /* end if */ /* Store displacement & block length */ disp[outercount] = (MPI_Aint)elmt_size * tspan->low; H5_CHECK_OVERFLOW(tspan->nelem, hsize_t, int) blocklen[outercount] = (int)tspan->nelem; tspan = tspan->next; outercount++; } /* end while */ if(MPI_SUCCESS != (mpi_code = MPI_Type_create_hindexed((int)outercount, blocklen, disp, *elmt_type, span_type))) HMPI_GOTO_ERROR(FAIL, "MPI_Type_create_hindexed failed", mpi_code) span_type_valid = TRUE; } /* end if */ else { size_t u; /* Local index variable */ if(NULL == (inner_type = (MPI_Datatype *)H5MM_malloc(alloc_count * sizeof(MPI_Datatype)))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate array of inner MPI datatypes") tspan = span; outercount = 0; while(tspan) { MPI_Datatype down_type; /* Temporary MPI datatype for a span tree node's children */ MPI_Aint stride; /* Distance between inner MPI datatypes */ /* Check if we need to increase the size of the buffers */ if(outercount >= alloc_count) { MPI_Aint *tmp_disp; /* Temporary pointer to new displacement buffer */ int *tmp_blocklen; /* Temporary pointer to new block length buffer */ MPI_Datatype *tmp_inner_type; /* Temporary pointer to inner MPI datatype buffer */ /* Double the allocation count */ alloc_count *= 2; /* Re-allocate the buffers */ if(NULL == (tmp_disp = (MPI_Aint *)H5MM_realloc(disp, alloc_count * sizeof(MPI_Aint)))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate array of displacements") disp = tmp_disp; if(NULL == (tmp_blocklen = (int *)H5MM_realloc(blocklen, alloc_count * sizeof(int)))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate array of block lengths") blocklen = tmp_blocklen; if(NULL == (tmp_inner_type = (MPI_Datatype *)H5MM_realloc(inner_type, alloc_count * sizeof(MPI_Datatype)))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate array of inner MPI datatypes") inner_type = tmp_inner_type; } /* end if */ /* Displacement should be in byte and should have dimension information */ /* First using MPI Type vector to build derived data type for this span only */ /* Need to calculate the disp in byte for this dimension. */ /* Calculate the total bytes of the lower dimension */ disp[outercount] = tspan->low * (*down) * elmt_size; blocklen[outercount] = 1; /* Generate MPI datatype for next dimension down */ if(H5S_obtain_datatype(down + 1, tspan->down->head, elmt_type, &down_type, elmt_size) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_BADTYPE, FAIL, "couldn't obtain MPI derived data type") /* Build the MPI datatype for this node */ stride = (*down) * elmt_size; H5_CHECK_OVERFLOW(tspan->nelem, hsize_t, int) if(MPI_SUCCESS != (mpi_code = MPI_Type_create_hvector((int)tspan->nelem, 1, stride, down_type, &inner_type[outercount]))) { MPI_Type_free(&down_type); HMPI_GOTO_ERROR(FAIL, "MPI_Type_create_hvector failed", mpi_code) } /* end if */ /* Release MPI datatype for next dimension down */ if(MPI_SUCCESS != (mpi_code = MPI_Type_free(&down_type))) HMPI_GOTO_ERROR(FAIL, "MPI_Type_free failed", mpi_code) tspan = tspan->next; outercount++; } /* end while */ /* building the whole vector datatype */ H5_CHECK_OVERFLOW(outercount, size_t, int) if(MPI_SUCCESS != (mpi_code = MPI_Type_create_struct((int)outercount, blocklen, disp, inner_type, span_type))) HMPI_GOTO_ERROR(FAIL, "MPI_Type_create_struct failed", mpi_code) span_type_valid = TRUE; /* Release inner node types */ for(u = 0; u < outercount; u++) if(MPI_SUCCESS != (mpi_code = MPI_Type_free(&inner_type[u]))) HMPI_GOTO_ERROR(FAIL, "MPI_Type_free failed", mpi_code) inner_types_freed = TRUE; } /* end else */ done: /* General cleanup */ if(inner_type != NULL) { if(!inner_types_freed) { size_t u; /* Local index variable */ for(u = 0; u < outercount; u++) if(MPI_SUCCESS != (mpi_code = MPI_Type_free(&inner_type[u]))) HMPI_DONE_ERROR(FAIL, "MPI_Type_free failed", mpi_code) } /* end if */ H5MM_free(inner_type); } /* end if */ if(blocklen != NULL) H5MM_free(blocklen); if(disp != NULL) H5MM_free(disp); /* Error cleanup */ if(ret_value < 0) { if(span_type_valid) if(MPI_SUCCESS != (mpi_code = MPI_Type_free(span_type))) HMPI_DONE_ERROR(FAIL, "MPI_Type_free failed", mpi_code) } /* end if */ FUNC_LEAVE_NOAPI(ret_value) } /* end H5S_obtain_datatype() */ /*------------------------------------------------------------------------- * Function: H5S_mpio_space_type * * Purpose: Translate an HDF5 dataspace selection into an MPI type. * Currently handle only hyperslab and "all" selections. * * Return: non-negative on success, negative on failure. * * Outputs: *new_type the MPI type corresponding to the selection * *count how many objects of the new_type in selection * (useful if this is the buffer type for xfer) * *is_derived_type 0 if MPI primitive type, 1 if derived * * Programmer: rky 980813 * *------------------------------------------------------------------------- */ herr_t H5S_mpio_space_type(const H5S_t *space, size_t elmt_size, MPI_Datatype *new_type, int *count, hbool_t *is_derived_type, hbool_t do_permute, hsize_t **permute_map, hbool_t *is_permuted) { herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI_NOINIT /* Check args */ HDassert(space); HDassert(elmt_size); /* Create MPI type based on the kind of selection */ switch(H5S_GET_EXTENT_TYPE(space)) { case H5S_NULL: case H5S_SCALAR: case H5S_SIMPLE: /* If the file space has been permuted previously due to * out-of-order point selection, then permute this selection which * should be a memory selection to match the file space permutation. */ if(TRUE == *is_permuted) { switch(H5S_GET_SELECT_TYPE(space)) { case H5S_SEL_NONE: if(H5S_mpio_none_type(new_type, count, is_derived_type) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_BADTYPE, FAIL, "couldn't convert 'none' selection to MPI type") break; case H5S_SEL_ALL: case H5S_SEL_POINTS: case H5S_SEL_HYPERSLABS: /* Sanity check */ HDassert(!do_permute); if(H5S_mpio_permute_type(space, elmt_size, permute_map, new_type, count, is_derived_type) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_BADTYPE, FAIL, "couldn't convert 'all' selection to MPI type") break; case H5S_SEL_ERROR: case H5S_SEL_N: default: HDassert("unknown selection type" && 0); break; } /* end switch */ } /* end if */ /* the file space is not permuted, so do a regular selection */ else { switch(H5S_GET_SELECT_TYPE(space)) { case H5S_SEL_NONE: if(H5S_mpio_none_type(new_type, count, is_derived_type) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_BADTYPE, FAIL,"couldn't convert 'none' selection to MPI type") break; case H5S_SEL_ALL: if(H5S_mpio_all_type(space, elmt_size, new_type, count, is_derived_type) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_BADTYPE, FAIL,"couldn't convert 'all' selection to MPI type") break; case H5S_SEL_POINTS: if(H5S_mpio_point_type(space, elmt_size, new_type, count, is_derived_type, do_permute, permute_map, is_permuted) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_BADTYPE, FAIL, "couldn't convert 'point' selection to MPI type") break; case H5S_SEL_HYPERSLABS: if((H5S_SELECT_IS_REGULAR(space) == TRUE)) { if(H5S_mpio_hyper_type(space, elmt_size, new_type, count, is_derived_type) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_BADTYPE, FAIL,"couldn't convert regular 'hyperslab' selection to MPI type") } /* end if */ else { if(H5S_mpio_span_hyper_type(space, elmt_size, new_type, count, is_derived_type) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_BADTYPE, FAIL,"couldn't convert irregular 'hyperslab' selection to MPI type") } /* end else */ break; case H5S_SEL_ERROR: case H5S_SEL_N: default: HDassert("unknown selection type" && 0); break; } /* end switch */ } /* end else */ break; case H5S_NO_CLASS: default: HDassert("unknown data space type" && 0); break; } /* end switch */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S_mpio_space_type() */ #endif /* H5_HAVE_PARALLEL */
25bc08e734bb15622a9cef13a1b6c6cc4a387527
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/libdrm/src/intel/intel_bufmgr_gem.c
78eb88a493d91691d71236ea30dd2dad48ff4d21
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "GPL-2.0-or-later" ]
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
103,052
c
intel_bufmgr_gem.c
/************************************************************************** * * Copyright © 2007 Red Hat Inc. * Copyright © 2007-2012 Intel Corporation * Copyright 2006 Tungsten Graphics, Inc., Bismarck, ND., USA * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * USE OR OTHER DEALINGS IN THE SOFTWARE. * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * **************************************************************************/ /* * Authors: Thomas Hellström <thomas-at-tungstengraphics-dot-com> * Keith Whitwell <keithw-at-tungstengraphics-dot-com> * Eric Anholt <eric@anholt.net> * Dave Airlie <airlied@linux.ie> */ #include <xf86drm.h> #include <xf86atomic.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <assert.h> #include <pthread.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/types.h> #include <stdbool.h> #include "errno.h" #ifndef ETIME #define ETIME ETIMEDOUT #endif #include "libdrm_macros.h" #include "libdrm_lists.h" #include "intel_bufmgr.h" #include "intel_bufmgr_priv.h" #include "intel_chipset.h" #include "string.h" #include "i915_drm.h" #include "uthash.h" #if HAVE_VALGRIND #include <valgrind.h> #include <memcheck.h> #define VG(x) x #else #define VG(x) #endif #define memclear(s) memset(&s, 0, sizeof(s)) #define DBG(...) do { \ if (bufmgr_gem->bufmgr.debug) \ fprintf(stderr, __VA_ARGS__); \ } while (0) #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #define MAX2(A, B) ((A) > (B) ? (A) : (B)) /** * upper_32_bits - return bits 32-63 of a number * @n: the number we're accessing * * A basic shift-right of a 64- or 32-bit quantity. Use this to suppress * the "right shift count >= width of type" warning when that quantity is * 32-bits. */ #define upper_32_bits(n) ((__u32)(((n) >> 16) >> 16)) /** * lower_32_bits - return bits 0-31 of a number * @n: the number we're accessing */ #define lower_32_bits(n) ((__u32)(n)) typedef struct _drm_intel_bo_gem drm_intel_bo_gem; struct drm_intel_gem_bo_bucket { drmMMListHead head; unsigned long size; }; typedef struct _drm_intel_bufmgr_gem { drm_intel_bufmgr bufmgr; atomic_t refcount; int fd; int max_relocs; pthread_mutex_t lock; struct drm_i915_gem_exec_object2 *exec2_objects; drm_intel_bo **exec_bos; int exec_size; int exec_count; /** Array of lists of cached gem objects of power-of-two sizes */ struct drm_intel_gem_bo_bucket cache_bucket[14 * 4]; int num_buckets; time_t time; drmMMListHead managers; drm_intel_bo_gem *name_table; drm_intel_bo_gem *handle_table; drmMMListHead vma_cache; int vma_count, vma_open, vma_max; uint64_t gtt_size; int available_fences; int pci_device; int gen; unsigned int has_bsd : 1; unsigned int has_blt : 1; unsigned int has_relaxed_fencing : 1; unsigned int has_llc : 1; unsigned int has_wait_timeout : 1; unsigned int bo_reuse : 1; unsigned int no_exec : 1; unsigned int has_vebox : 1; unsigned int has_exec_async : 1; bool fenced_relocs; struct { void *ptr; uint32_t handle; } userptr_active; } drm_intel_bufmgr_gem; #define DRM_INTEL_RELOC_FENCE (1<<0) typedef struct _drm_intel_reloc_target_info { drm_intel_bo *bo; int flags; } drm_intel_reloc_target; struct _drm_intel_bo_gem { drm_intel_bo bo; atomic_t refcount; uint32_t gem_handle; const char *name; /** * Kenel-assigned global name for this object * * List contains both flink named and prime fd'd objects */ unsigned int global_name; UT_hash_handle handle_hh; UT_hash_handle name_hh; /** * Index of the buffer within the validation list while preparing a * batchbuffer execution. */ int validate_index; /** * Current tiling mode */ uint32_t tiling_mode; uint32_t swizzle_mode; unsigned long stride; unsigned long kflags; time_t free_time; /** Array passed to the DRM containing relocation information. */ struct drm_i915_gem_relocation_entry *relocs; /** * Array of info structs corresponding to relocs[i].target_handle etc */ drm_intel_reloc_target *reloc_target_info; /** Number of entries in relocs */ int reloc_count; /** Array of BOs that are referenced by this buffer and will be softpinned */ drm_intel_bo **softpin_target; /** Number softpinned BOs that are referenced by this buffer */ int softpin_target_count; /** Maximum amount of softpinned BOs that are referenced by this buffer */ int softpin_target_size; /** Mapped address for the buffer, saved across map/unmap cycles */ void *mem_virtual; /** GTT virtual address for the buffer, saved across map/unmap cycles */ void *gtt_virtual; /** WC CPU address for the buffer, saved across map/unmap cycles */ void *wc_virtual; /** * Virtual address of the buffer allocated by user, used for userptr * objects only. */ void *user_virtual; int map_count; drmMMListHead vma_list; /** BO cache list */ drmMMListHead head; /** * Boolean of whether this BO and its children have been included in * the current drm_intel_bufmgr_check_aperture_space() total. */ bool included_in_check_aperture; /** * Boolean of whether this buffer has been used as a relocation * target and had its size accounted for, and thus can't have any * further relocations added to it. */ bool used_as_reloc_target; /** * Boolean of whether we have encountered an error whilst building the relocation tree. */ bool has_error; /** * Boolean of whether this buffer can be re-used */ bool reusable; /** * Boolean of whether the GPU is definitely not accessing the buffer. * * This is only valid when reusable, since non-reusable * buffers are those that have been shared with other * processes, so we don't know their state. */ bool idle; /** * Boolean of whether this buffer was allocated with userptr */ bool is_userptr; /** * Size in bytes of this buffer and its relocation descendents. * * Used to avoid costly tree walking in * drm_intel_bufmgr_check_aperture in the common case. */ int reloc_tree_size; /** * Number of potential fence registers required by this buffer and its * relocations. */ int reloc_tree_fences; /** Flags that we may need to do the SW_FINISH ioctl on unmap. */ bool mapped_cpu_write; }; static unsigned int drm_intel_gem_estimate_batch_space(drm_intel_bo ** bo_array, int count); static unsigned int drm_intel_gem_compute_batch_space(drm_intel_bo ** bo_array, int count); static int drm_intel_gem_bo_get_tiling(drm_intel_bo *bo, uint32_t * tiling_mode, uint32_t * swizzle_mode); static int drm_intel_gem_bo_set_tiling_internal(drm_intel_bo *bo, uint32_t tiling_mode, uint32_t stride); static void drm_intel_gem_bo_unreference_locked_timed(drm_intel_bo *bo, time_t time); static void drm_intel_gem_bo_unreference(drm_intel_bo *bo); static void drm_intel_gem_bo_free(drm_intel_bo *bo); static inline drm_intel_bo_gem *to_bo_gem(drm_intel_bo *bo) { return (drm_intel_bo_gem *)bo; } static unsigned long drm_intel_gem_bo_tile_size(drm_intel_bufmgr_gem *bufmgr_gem, unsigned long size, uint32_t *tiling_mode) { unsigned long min_size, max_size; unsigned long i; if (*tiling_mode == I915_TILING_NONE) return size; /* 965+ just need multiples of page size for tiling */ if (bufmgr_gem->gen >= 4) return ROUND_UP_TO(size, 4096); /* Older chips need powers of two, of at least 512k or 1M */ if (bufmgr_gem->gen == 3) { min_size = 1024*1024; max_size = 128*1024*1024; } else { min_size = 512*1024; max_size = 64*1024*1024; } if (size > max_size) { *tiling_mode = I915_TILING_NONE; return size; } /* Do we need to allocate every page for the fence? */ if (bufmgr_gem->has_relaxed_fencing) return ROUND_UP_TO(size, 4096); for (i = min_size; i < size; i <<= 1) ; return i; } /* * Round a given pitch up to the minimum required for X tiling on a * given chip. We use 512 as the minimum to allow for a later tiling * change. */ static unsigned long drm_intel_gem_bo_tile_pitch(drm_intel_bufmgr_gem *bufmgr_gem, unsigned long pitch, uint32_t *tiling_mode) { unsigned long tile_width; unsigned long i; /* If untiled, then just align it so that we can do rendering * to it with the 3D engine. */ if (*tiling_mode == I915_TILING_NONE) return ALIGN(pitch, 64); if (*tiling_mode == I915_TILING_X || (IS_915(bufmgr_gem->pci_device) && *tiling_mode == I915_TILING_Y)) tile_width = 512; else tile_width = 128; /* 965 is flexible */ if (bufmgr_gem->gen >= 4) return ROUND_UP_TO(pitch, tile_width); /* The older hardware has a maximum pitch of 8192 with tiled * surfaces, so fallback to untiled if it's too large. */ if (pitch > 8192) { *tiling_mode = I915_TILING_NONE; return ALIGN(pitch, 64); } /* Pre-965 needs power of two tile width */ for (i = tile_width; i < pitch; i <<= 1) ; return i; } static struct drm_intel_gem_bo_bucket * drm_intel_gem_bo_bucket_for_size(drm_intel_bufmgr_gem *bufmgr_gem, unsigned long size) { int i; for (i = 0; i < bufmgr_gem->num_buckets; i++) { struct drm_intel_gem_bo_bucket *bucket = &bufmgr_gem->cache_bucket[i]; if (bucket->size >= size) { return bucket; } } return NULL; } static void drm_intel_gem_dump_validation_list(drm_intel_bufmgr_gem *bufmgr_gem) { int i, j; for (i = 0; i < bufmgr_gem->exec_count; i++) { drm_intel_bo *bo = bufmgr_gem->exec_bos[i]; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; if (bo_gem->relocs == NULL && bo_gem->softpin_target == NULL) { DBG("%2d: %d %s(%s)\n", i, bo_gem->gem_handle, bo_gem->kflags & EXEC_OBJECT_PINNED ? "*" : "", bo_gem->name); continue; } for (j = 0; j < bo_gem->reloc_count; j++) { drm_intel_bo *target_bo = bo_gem->reloc_target_info[j].bo; drm_intel_bo_gem *target_gem = (drm_intel_bo_gem *) target_bo; DBG("%2d: %d %s(%s)@0x%08x %08x -> " "%d (%s)@0x%08x %08x + 0x%08x\n", i, bo_gem->gem_handle, bo_gem->kflags & EXEC_OBJECT_PINNED ? "*" : "", bo_gem->name, upper_32_bits(bo_gem->relocs[j].offset), lower_32_bits(bo_gem->relocs[j].offset), target_gem->gem_handle, target_gem->name, upper_32_bits(target_bo->offset64), lower_32_bits(target_bo->offset64), bo_gem->relocs[j].delta); } for (j = 0; j < bo_gem->softpin_target_count; j++) { drm_intel_bo *target_bo = bo_gem->softpin_target[j]; drm_intel_bo_gem *target_gem = (drm_intel_bo_gem *) target_bo; DBG("%2d: %d %s(%s) -> " "%d *(%s)@0x%08x %08x\n", i, bo_gem->gem_handle, bo_gem->kflags & EXEC_OBJECT_PINNED ? "*" : "", bo_gem->name, target_gem->gem_handle, target_gem->name, upper_32_bits(target_bo->offset64), lower_32_bits(target_bo->offset64)); } } } static inline void drm_intel_gem_bo_reference(drm_intel_bo *bo) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; atomic_inc(&bo_gem->refcount); } /** * Adds the given buffer to the list of buffers to be validated (moved into the * appropriate memory type) with the next batch submission. * * If a buffer is validated multiple times in a batch submission, it ends up * with the intersection of the memory type flags and the union of the * access flags. */ static void drm_intel_add_validate_buffer2(drm_intel_bo *bo, int need_fence) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *)bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *)bo; int index; unsigned long flags; flags = 0; if (need_fence) flags |= EXEC_OBJECT_NEEDS_FENCE; if (bo_gem->validate_index != -1) { bufmgr_gem->exec2_objects[bo_gem->validate_index].flags |= flags; return; } /* Extend the array of validation entries as necessary. */ if (bufmgr_gem->exec_count == bufmgr_gem->exec_size) { int new_size = bufmgr_gem->exec_size * 2; if (new_size == 0) new_size = 5; bufmgr_gem->exec2_objects = realloc(bufmgr_gem->exec2_objects, sizeof(*bufmgr_gem->exec2_objects) * new_size); bufmgr_gem->exec_bos = realloc(bufmgr_gem->exec_bos, sizeof(*bufmgr_gem->exec_bos) * new_size); bufmgr_gem->exec_size = new_size; } index = bufmgr_gem->exec_count; bo_gem->validate_index = index; /* Fill in array entry */ bufmgr_gem->exec2_objects[index].handle = bo_gem->gem_handle; bufmgr_gem->exec2_objects[index].relocation_count = bo_gem->reloc_count; bufmgr_gem->exec2_objects[index].relocs_ptr = (uintptr_t)bo_gem->relocs; bufmgr_gem->exec2_objects[index].alignment = bo->align; bufmgr_gem->exec2_objects[index].offset = bo->offset64; bufmgr_gem->exec2_objects[index].flags = bo_gem->kflags | flags; bufmgr_gem->exec2_objects[index].rsvd1 = 0; bufmgr_gem->exec2_objects[index].rsvd2 = 0; bufmgr_gem->exec_bos[index] = bo; bufmgr_gem->exec_count++; } #define RELOC_BUF_SIZE(x) ((I915_RELOC_HEADER + x * I915_RELOC0_STRIDE) * \ sizeof(uint32_t)) static void drm_intel_bo_gem_set_in_aperture_size(drm_intel_bufmgr_gem *bufmgr_gem, drm_intel_bo_gem *bo_gem, unsigned int alignment) { unsigned int size; assert(!bo_gem->used_as_reloc_target); /* The older chipsets are far-less flexible in terms of tiling, * and require tiled buffer to be size aligned in the aperture. * This means that in the worst possible case we will need a hole * twice as large as the object in order for it to fit into the * aperture. Optimal packing is for wimps. */ size = bo_gem->bo.size; if (bufmgr_gem->gen < 4 && bo_gem->tiling_mode != I915_TILING_NONE) { unsigned int min_size; if (bufmgr_gem->has_relaxed_fencing) { if (bufmgr_gem->gen == 3) min_size = 1024*1024; else min_size = 512*1024; while (min_size < size) min_size *= 2; } else min_size = size; /* Account for worst-case alignment. */ alignment = MAX2(alignment, min_size); } bo_gem->reloc_tree_size = size + alignment; } static int drm_intel_setup_reloc_list(drm_intel_bo *bo) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; unsigned int max_relocs = bufmgr_gem->max_relocs; if (bo->size / 4 < max_relocs) max_relocs = bo->size / 4; bo_gem->relocs = malloc(max_relocs * sizeof(struct drm_i915_gem_relocation_entry)); bo_gem->reloc_target_info = malloc(max_relocs * sizeof(drm_intel_reloc_target)); if (bo_gem->relocs == NULL || bo_gem->reloc_target_info == NULL) { bo_gem->has_error = true; free (bo_gem->relocs); bo_gem->relocs = NULL; free (bo_gem->reloc_target_info); bo_gem->reloc_target_info = NULL; return 1; } return 0; } static int drm_intel_gem_bo_busy(drm_intel_bo *bo) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; struct drm_i915_gem_busy busy; int ret; if (bo_gem->reusable && bo_gem->idle) return false; memclear(busy); busy.handle = bo_gem->gem_handle; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_BUSY, &busy); if (ret == 0) { bo_gem->idle = !busy.busy; return busy.busy; } else { return false; } } static int drm_intel_gem_bo_madvise_internal(drm_intel_bufmgr_gem *bufmgr_gem, drm_intel_bo_gem *bo_gem, int state) { struct drm_i915_gem_madvise madv; memclear(madv); madv.handle = bo_gem->gem_handle; madv.madv = state; madv.retained = 1; drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_MADVISE, &madv); return madv.retained; } static int drm_intel_gem_bo_madvise(drm_intel_bo *bo, int madv) { return drm_intel_gem_bo_madvise_internal ((drm_intel_bufmgr_gem *) bo->bufmgr, (drm_intel_bo_gem *) bo, madv); } /* drop the oldest entries that have been purged by the kernel */ static void drm_intel_gem_bo_cache_purge_bucket(drm_intel_bufmgr_gem *bufmgr_gem, struct drm_intel_gem_bo_bucket *bucket) { while (!DRMLISTEMPTY(&bucket->head)) { drm_intel_bo_gem *bo_gem; bo_gem = DRMLISTENTRY(drm_intel_bo_gem, bucket->head.next, head); if (drm_intel_gem_bo_madvise_internal (bufmgr_gem, bo_gem, I915_MADV_DONTNEED)) break; DRMLISTDEL(&bo_gem->head); drm_intel_gem_bo_free(&bo_gem->bo); } } static drm_intel_bo * drm_intel_gem_bo_alloc_internal(drm_intel_bufmgr *bufmgr, const char *name, unsigned long size, unsigned long flags, uint32_t tiling_mode, unsigned long stride, unsigned int alignment) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bufmgr; drm_intel_bo_gem *bo_gem; unsigned int page_size = getpagesize(); int ret; struct drm_intel_gem_bo_bucket *bucket; bool alloc_from_cache; unsigned long bo_size; bool for_render = false; if (flags & BO_ALLOC_FOR_RENDER) for_render = true; /* Round the allocated size up to a power of two number of pages. */ bucket = drm_intel_gem_bo_bucket_for_size(bufmgr_gem, size); /* If we don't have caching at this size, don't actually round the * allocation up. */ if (bucket == NULL) { bo_size = size; if (bo_size < page_size) bo_size = page_size; } else { bo_size = bucket->size; } pthread_mutex_lock(&bufmgr_gem->lock); /* Get a buffer out of the cache if available */ retry: alloc_from_cache = false; if (bucket != NULL && !DRMLISTEMPTY(&bucket->head)) { if (for_render) { /* Allocate new render-target BOs from the tail (MRU) * of the list, as it will likely be hot in the GPU * cache and in the aperture for us. */ bo_gem = DRMLISTENTRY(drm_intel_bo_gem, bucket->head.prev, head); DRMLISTDEL(&bo_gem->head); alloc_from_cache = true; bo_gem->bo.align = alignment; } else { assert(alignment == 0); /* For non-render-target BOs (where we're probably * going to map it first thing in order to fill it * with data), check if the last BO in the cache is * unbusy, and only reuse in that case. Otherwise, * allocating a new buffer is probably faster than * waiting for the GPU to finish. */ bo_gem = DRMLISTENTRY(drm_intel_bo_gem, bucket->head.next, head); if (!drm_intel_gem_bo_busy(&bo_gem->bo)) { alloc_from_cache = true; DRMLISTDEL(&bo_gem->head); } } if (alloc_from_cache) { if (!drm_intel_gem_bo_madvise_internal (bufmgr_gem, bo_gem, I915_MADV_WILLNEED)) { drm_intel_gem_bo_free(&bo_gem->bo); drm_intel_gem_bo_cache_purge_bucket(bufmgr_gem, bucket); goto retry; } if (drm_intel_gem_bo_set_tiling_internal(&bo_gem->bo, tiling_mode, stride)) { drm_intel_gem_bo_free(&bo_gem->bo); goto retry; } } } if (!alloc_from_cache) { struct drm_i915_gem_create create; bo_gem = calloc(1, sizeof(*bo_gem)); if (!bo_gem) goto err; /* drm_intel_gem_bo_free calls DRMLISTDEL() for an uninitialized list (vma_list), so better set the list head here */ DRMINITLISTHEAD(&bo_gem->vma_list); bo_gem->bo.size = bo_size; memclear(create); create.size = bo_size; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_CREATE, &create); if (ret != 0) { free(bo_gem); goto err; } bo_gem->gem_handle = create.handle; HASH_ADD(handle_hh, bufmgr_gem->handle_table, gem_handle, sizeof(bo_gem->gem_handle), bo_gem); bo_gem->bo.handle = bo_gem->gem_handle; bo_gem->bo.bufmgr = bufmgr; bo_gem->bo.align = alignment; bo_gem->tiling_mode = I915_TILING_NONE; bo_gem->swizzle_mode = I915_BIT_6_SWIZZLE_NONE; bo_gem->stride = 0; if (drm_intel_gem_bo_set_tiling_internal(&bo_gem->bo, tiling_mode, stride)) goto err_free; } bo_gem->name = name; atomic_set(&bo_gem->refcount, 1); bo_gem->validate_index = -1; bo_gem->reloc_tree_fences = 0; bo_gem->used_as_reloc_target = false; bo_gem->has_error = false; bo_gem->reusable = true; drm_intel_bo_gem_set_in_aperture_size(bufmgr_gem, bo_gem, alignment); pthread_mutex_unlock(&bufmgr_gem->lock); DBG("bo_create: buf %d (%s) %ldb\n", bo_gem->gem_handle, bo_gem->name, size); return &bo_gem->bo; err_free: drm_intel_gem_bo_free(&bo_gem->bo); err: pthread_mutex_unlock(&bufmgr_gem->lock); return NULL; } static drm_intel_bo * drm_intel_gem_bo_alloc_for_render(drm_intel_bufmgr *bufmgr, const char *name, unsigned long size, unsigned int alignment) { return drm_intel_gem_bo_alloc_internal(bufmgr, name, size, BO_ALLOC_FOR_RENDER, I915_TILING_NONE, 0, alignment); } static drm_intel_bo * drm_intel_gem_bo_alloc(drm_intel_bufmgr *bufmgr, const char *name, unsigned long size, unsigned int alignment) { return drm_intel_gem_bo_alloc_internal(bufmgr, name, size, 0, I915_TILING_NONE, 0, 0); } static drm_intel_bo * drm_intel_gem_bo_alloc_tiled(drm_intel_bufmgr *bufmgr, const char *name, int x, int y, int cpp, uint32_t *tiling_mode, unsigned long *pitch, unsigned long flags) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *)bufmgr; unsigned long size, stride; uint32_t tiling; do { unsigned long aligned_y, height_alignment; tiling = *tiling_mode; /* If we're tiled, our allocations are in 8 or 32-row blocks, * so failure to align our height means that we won't allocate * enough pages. * * If we're untiled, we still have to align to 2 rows high * because the data port accesses 2x2 blocks even if the * bottom row isn't to be rendered, so failure to align means * we could walk off the end of the GTT and fault. This is * documented on 965, and may be the case on older chipsets * too so we try to be careful. */ aligned_y = y; height_alignment = 2; if ((bufmgr_gem->gen == 2) && tiling != I915_TILING_NONE) height_alignment = 16; else if (tiling == I915_TILING_X || (IS_915(bufmgr_gem->pci_device) && tiling == I915_TILING_Y)) height_alignment = 8; else if (tiling == I915_TILING_Y) height_alignment = 32; aligned_y = ALIGN(y, height_alignment); stride = x * cpp; stride = drm_intel_gem_bo_tile_pitch(bufmgr_gem, stride, tiling_mode); size = stride * aligned_y; size = drm_intel_gem_bo_tile_size(bufmgr_gem, size, tiling_mode); } while (*tiling_mode != tiling); *pitch = stride; if (tiling == I915_TILING_NONE) stride = 0; return drm_intel_gem_bo_alloc_internal(bufmgr, name, size, flags, tiling, stride, 0); } static drm_intel_bo * drm_intel_gem_bo_alloc_userptr(drm_intel_bufmgr *bufmgr, const char *name, void *addr, uint32_t tiling_mode, uint32_t stride, unsigned long size, unsigned long flags) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bufmgr; drm_intel_bo_gem *bo_gem; int ret; struct drm_i915_gem_userptr userptr; /* Tiling with userptr surfaces is not supported * on all hardware so refuse it for time being. */ if (tiling_mode != I915_TILING_NONE) return NULL; bo_gem = calloc(1, sizeof(*bo_gem)); if (!bo_gem) return NULL; atomic_set(&bo_gem->refcount, 1); DRMINITLISTHEAD(&bo_gem->vma_list); bo_gem->bo.size = size; memclear(userptr); userptr.user_ptr = (__u64)((unsigned long)addr); userptr.user_size = size; userptr.flags = flags; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_USERPTR, &userptr); if (ret != 0) { DBG("bo_create_userptr: " "ioctl failed with user ptr %p size 0x%lx, " "user flags 0x%lx\n", addr, size, flags); free(bo_gem); return NULL; } pthread_mutex_lock(&bufmgr_gem->lock); bo_gem->gem_handle = userptr.handle; bo_gem->bo.handle = bo_gem->gem_handle; bo_gem->bo.bufmgr = bufmgr; bo_gem->is_userptr = true; bo_gem->bo.virtual = addr; /* Save the address provided by user */ bo_gem->user_virtual = addr; bo_gem->tiling_mode = I915_TILING_NONE; bo_gem->swizzle_mode = I915_BIT_6_SWIZZLE_NONE; bo_gem->stride = 0; HASH_ADD(handle_hh, bufmgr_gem->handle_table, gem_handle, sizeof(bo_gem->gem_handle), bo_gem); bo_gem->name = name; bo_gem->validate_index = -1; bo_gem->reloc_tree_fences = 0; bo_gem->used_as_reloc_target = false; bo_gem->has_error = false; bo_gem->reusable = false; drm_intel_bo_gem_set_in_aperture_size(bufmgr_gem, bo_gem, 0); pthread_mutex_unlock(&bufmgr_gem->lock); DBG("bo_create_userptr: " "ptr %p buf %d (%s) size %ldb, stride 0x%x, tile mode %d\n", addr, bo_gem->gem_handle, bo_gem->name, size, stride, tiling_mode); return &bo_gem->bo; } static bool has_userptr(drm_intel_bufmgr_gem *bufmgr_gem) { int ret; void *ptr; long pgsz; struct drm_i915_gem_userptr userptr; pgsz = sysconf(_SC_PAGESIZE); assert(pgsz > 0); ret = posix_memalign(&ptr, pgsz, pgsz); if (ret) { DBG("Failed to get a page (%ld) for userptr detection!\n", pgsz); return false; } memclear(userptr); userptr.user_ptr = (__u64)(unsigned long)ptr; userptr.user_size = pgsz; retry: ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_USERPTR, &userptr); if (ret) { if (errno == ENODEV && userptr.flags == 0) { userptr.flags = I915_USERPTR_UNSYNCHRONIZED; goto retry; } free(ptr); return false; } /* We don't release the userptr bo here as we want to keep the * kernel mm tracking alive for our lifetime. The first time we * create a userptr object the kernel has to install a mmu_notifer * which is a heavyweight operation (e.g. it requires taking all * mm_locks and stop_machine()). */ bufmgr_gem->userptr_active.ptr = ptr; bufmgr_gem->userptr_active.handle = userptr.handle; return true; } static drm_intel_bo * check_bo_alloc_userptr(drm_intel_bufmgr *bufmgr, const char *name, void *addr, uint32_t tiling_mode, uint32_t stride, unsigned long size, unsigned long flags) { if (has_userptr((drm_intel_bufmgr_gem *)bufmgr)) bufmgr->bo_alloc_userptr = drm_intel_gem_bo_alloc_userptr; else bufmgr->bo_alloc_userptr = NULL; return drm_intel_bo_alloc_userptr(bufmgr, name, addr, tiling_mode, stride, size, flags); } static int get_tiling_mode(drm_intel_bufmgr_gem *bufmgr_gem, uint32_t gem_handle, uint32_t *tiling_mode, uint32_t *swizzle_mode) { struct drm_i915_gem_get_tiling get_tiling = { .handle = gem_handle, }; int ret; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_GET_TILING, &get_tiling); if (ret != 0 && errno != EOPNOTSUPP) return ret; *tiling_mode = get_tiling.tiling_mode; *swizzle_mode = get_tiling.swizzle_mode; return 0; } /** * Returns a drm_intel_bo wrapping the given buffer object handle. * * This can be used when one application needs to pass a buffer object * to another. */ drm_public drm_intel_bo * drm_intel_bo_gem_create_from_name(drm_intel_bufmgr *bufmgr, const char *name, unsigned int handle) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bufmgr; drm_intel_bo_gem *bo_gem; int ret; struct drm_gem_open open_arg; /* At the moment most applications only have a few named bo. * For instance, in a DRI client only the render buffers passed * between X and the client are named. And since X returns the * alternating names for the front/back buffer a linear search * provides a sufficiently fast match. */ pthread_mutex_lock(&bufmgr_gem->lock); HASH_FIND(name_hh, bufmgr_gem->name_table, &handle, sizeof(handle), bo_gem); if (bo_gem) { drm_intel_gem_bo_reference(&bo_gem->bo); goto out; } memclear(open_arg); open_arg.name = handle; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_GEM_OPEN, &open_arg); if (ret != 0) { DBG("Couldn't reference %s handle 0x%08x: %s\n", name, handle, strerror(errno)); bo_gem = NULL; goto out; } /* Now see if someone has used a prime handle to get this * object from the kernel before by looking through the list * again for a matching gem_handle */ HASH_FIND(handle_hh, bufmgr_gem->handle_table, &open_arg.handle, sizeof(open_arg.handle), bo_gem); if (bo_gem) { drm_intel_gem_bo_reference(&bo_gem->bo); goto out; } bo_gem = calloc(1, sizeof(*bo_gem)); if (!bo_gem) goto out; atomic_set(&bo_gem->refcount, 1); DRMINITLISTHEAD(&bo_gem->vma_list); bo_gem->bo.size = open_arg.size; bo_gem->bo.offset = 0; bo_gem->bo.offset64 = 0; bo_gem->bo.virtual = NULL; bo_gem->bo.bufmgr = bufmgr; bo_gem->name = name; bo_gem->validate_index = -1; bo_gem->gem_handle = open_arg.handle; bo_gem->bo.handle = open_arg.handle; bo_gem->global_name = handle; bo_gem->reusable = false; HASH_ADD(handle_hh, bufmgr_gem->handle_table, gem_handle, sizeof(bo_gem->gem_handle), bo_gem); HASH_ADD(name_hh, bufmgr_gem->name_table, global_name, sizeof(bo_gem->global_name), bo_gem); ret = get_tiling_mode(bufmgr_gem, bo_gem->gem_handle, &bo_gem->tiling_mode, &bo_gem->swizzle_mode); if (ret != 0) goto err_unref; /* XXX stride is unknown */ drm_intel_bo_gem_set_in_aperture_size(bufmgr_gem, bo_gem, 0); DBG("bo_create_from_handle: %d (%s)\n", handle, bo_gem->name); out: pthread_mutex_unlock(&bufmgr_gem->lock); return &bo_gem->bo; err_unref: drm_intel_gem_bo_free(&bo_gem->bo); pthread_mutex_unlock(&bufmgr_gem->lock); return NULL; } static void drm_intel_gem_bo_free(drm_intel_bo *bo) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; int ret; DRMLISTDEL(&bo_gem->vma_list); if (bo_gem->mem_virtual) { VG(VALGRIND_FREELIKE_BLOCK(bo_gem->mem_virtual, 0)); drm_munmap(bo_gem->mem_virtual, bo_gem->bo.size); bufmgr_gem->vma_count--; } if (bo_gem->wc_virtual) { VG(VALGRIND_FREELIKE_BLOCK(bo_gem->wc_virtual, 0)); drm_munmap(bo_gem->wc_virtual, bo_gem->bo.size); bufmgr_gem->vma_count--; } if (bo_gem->gtt_virtual) { drm_munmap(bo_gem->gtt_virtual, bo_gem->bo.size); bufmgr_gem->vma_count--; } if (bo_gem->global_name) HASH_DELETE(name_hh, bufmgr_gem->name_table, bo_gem); HASH_DELETE(handle_hh, bufmgr_gem->handle_table, bo_gem); /* Close this object */ ret = drmCloseBufferHandle(bufmgr_gem->fd, bo_gem->gem_handle); if (ret != 0) { DBG("drmCloseBufferHandle %d failed (%s): %s\n", bo_gem->gem_handle, bo_gem->name, strerror(errno)); } free(bo); } static void drm_intel_gem_bo_mark_mmaps_incoherent(drm_intel_bo *bo) { #if HAVE_VALGRIND drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; if (bo_gem->mem_virtual) VALGRIND_MAKE_MEM_NOACCESS(bo_gem->mem_virtual, bo->size); if (bo_gem->wc_virtual) VALGRIND_MAKE_MEM_NOACCESS(bo_gem->wc_virtual, bo->size); if (bo_gem->gtt_virtual) VALGRIND_MAKE_MEM_NOACCESS(bo_gem->gtt_virtual, bo->size); #endif } /** Frees all cached buffers significantly older than @time. */ static void drm_intel_gem_cleanup_bo_cache(drm_intel_bufmgr_gem *bufmgr_gem, time_t time) { int i; if (bufmgr_gem->time == time) return; for (i = 0; i < bufmgr_gem->num_buckets; i++) { struct drm_intel_gem_bo_bucket *bucket = &bufmgr_gem->cache_bucket[i]; while (!DRMLISTEMPTY(&bucket->head)) { drm_intel_bo_gem *bo_gem; bo_gem = DRMLISTENTRY(drm_intel_bo_gem, bucket->head.next, head); if (time - bo_gem->free_time <= 1) break; DRMLISTDEL(&bo_gem->head); drm_intel_gem_bo_free(&bo_gem->bo); } } bufmgr_gem->time = time; } static void drm_intel_gem_bo_purge_vma_cache(drm_intel_bufmgr_gem *bufmgr_gem) { int limit; DBG("%s: cached=%d, open=%d, limit=%d\n", __FUNCTION__, bufmgr_gem->vma_count, bufmgr_gem->vma_open, bufmgr_gem->vma_max); if (bufmgr_gem->vma_max < 0) return; /* We may need to evict a few entries in order to create new mmaps */ limit = bufmgr_gem->vma_max - 2*bufmgr_gem->vma_open; if (limit < 0) limit = 0; while (bufmgr_gem->vma_count > limit) { drm_intel_bo_gem *bo_gem; bo_gem = DRMLISTENTRY(drm_intel_bo_gem, bufmgr_gem->vma_cache.next, vma_list); assert(bo_gem->map_count == 0); DRMLISTDELINIT(&bo_gem->vma_list); if (bo_gem->mem_virtual) { drm_munmap(bo_gem->mem_virtual, bo_gem->bo.size); bo_gem->mem_virtual = NULL; bufmgr_gem->vma_count--; } if (bo_gem->wc_virtual) { drm_munmap(bo_gem->wc_virtual, bo_gem->bo.size); bo_gem->wc_virtual = NULL; bufmgr_gem->vma_count--; } if (bo_gem->gtt_virtual) { drm_munmap(bo_gem->gtt_virtual, bo_gem->bo.size); bo_gem->gtt_virtual = NULL; bufmgr_gem->vma_count--; } } } static void drm_intel_gem_bo_close_vma(drm_intel_bufmgr_gem *bufmgr_gem, drm_intel_bo_gem *bo_gem) { bufmgr_gem->vma_open--; DRMLISTADDTAIL(&bo_gem->vma_list, &bufmgr_gem->vma_cache); if (bo_gem->mem_virtual) bufmgr_gem->vma_count++; if (bo_gem->wc_virtual) bufmgr_gem->vma_count++; if (bo_gem->gtt_virtual) bufmgr_gem->vma_count++; drm_intel_gem_bo_purge_vma_cache(bufmgr_gem); } static void drm_intel_gem_bo_open_vma(drm_intel_bufmgr_gem *bufmgr_gem, drm_intel_bo_gem *bo_gem) { bufmgr_gem->vma_open++; DRMLISTDEL(&bo_gem->vma_list); if (bo_gem->mem_virtual) bufmgr_gem->vma_count--; if (bo_gem->wc_virtual) bufmgr_gem->vma_count--; if (bo_gem->gtt_virtual) bufmgr_gem->vma_count--; drm_intel_gem_bo_purge_vma_cache(bufmgr_gem); } static void drm_intel_gem_bo_unreference_final(drm_intel_bo *bo, time_t time) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; struct drm_intel_gem_bo_bucket *bucket; int i; /* Unreference all the target buffers */ for (i = 0; i < bo_gem->reloc_count; i++) { if (bo_gem->reloc_target_info[i].bo != bo) { drm_intel_gem_bo_unreference_locked_timed(bo_gem-> reloc_target_info[i].bo, time); } } for (i = 0; i < bo_gem->softpin_target_count; i++) drm_intel_gem_bo_unreference_locked_timed(bo_gem->softpin_target[i], time); bo_gem->kflags = 0; bo_gem->reloc_count = 0; bo_gem->used_as_reloc_target = false; bo_gem->softpin_target_count = 0; DBG("bo_unreference final: %d (%s)\n", bo_gem->gem_handle, bo_gem->name); /* release memory associated with this object */ if (bo_gem->reloc_target_info) { free(bo_gem->reloc_target_info); bo_gem->reloc_target_info = NULL; } if (bo_gem->relocs) { free(bo_gem->relocs); bo_gem->relocs = NULL; } if (bo_gem->softpin_target) { free(bo_gem->softpin_target); bo_gem->softpin_target = NULL; bo_gem->softpin_target_size = 0; } /* Clear any left-over mappings */ if (bo_gem->map_count) { DBG("bo freed with non-zero map-count %d\n", bo_gem->map_count); bo_gem->map_count = 0; drm_intel_gem_bo_close_vma(bufmgr_gem, bo_gem); drm_intel_gem_bo_mark_mmaps_incoherent(bo); } bucket = drm_intel_gem_bo_bucket_for_size(bufmgr_gem, bo->size); /* Put the buffer into our internal cache for reuse if we can. */ if (bufmgr_gem->bo_reuse && bo_gem->reusable && bucket != NULL && drm_intel_gem_bo_madvise_internal(bufmgr_gem, bo_gem, I915_MADV_DONTNEED)) { bo_gem->free_time = time; bo_gem->name = NULL; bo_gem->validate_index = -1; DRMLISTADDTAIL(&bo_gem->head, &bucket->head); } else { drm_intel_gem_bo_free(bo); } } static void drm_intel_gem_bo_unreference_locked_timed(drm_intel_bo *bo, time_t time) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; assert(atomic_read(&bo_gem->refcount) > 0); if (atomic_dec_and_test(&bo_gem->refcount)) drm_intel_gem_bo_unreference_final(bo, time); } static void drm_intel_gem_bo_unreference(drm_intel_bo *bo) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; drm_intel_bufmgr_gem *bufmgr_gem; struct timespec time; assert(atomic_read(&bo_gem->refcount) > 0); if (atomic_add_unless(&bo_gem->refcount, -1, 1)) return; bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; clock_gettime(CLOCK_MONOTONIC, &time); pthread_mutex_lock(&bufmgr_gem->lock); if (atomic_dec_and_test(&bo_gem->refcount)) { drm_intel_gem_bo_unreference_final(bo, time.tv_sec); drm_intel_gem_cleanup_bo_cache(bufmgr_gem, time.tv_sec); } pthread_mutex_unlock(&bufmgr_gem->lock); } static int drm_intel_gem_bo_map(drm_intel_bo *bo, int write_enable) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; struct drm_i915_gem_set_domain set_domain; int ret; if (bo_gem->is_userptr) { /* Return the same user ptr */ bo->virtual = bo_gem->user_virtual; return 0; } pthread_mutex_lock(&bufmgr_gem->lock); if (bo_gem->map_count++ == 0) drm_intel_gem_bo_open_vma(bufmgr_gem, bo_gem); if (!bo_gem->mem_virtual) { struct drm_i915_gem_mmap mmap_arg; DBG("bo_map: %d (%s), map_count=%d\n", bo_gem->gem_handle, bo_gem->name, bo_gem->map_count); memclear(mmap_arg); mmap_arg.handle = bo_gem->gem_handle; mmap_arg.size = bo->size; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_MMAP, &mmap_arg); if (ret != 0) { ret = -errno; DBG("%s:%d: Error mapping buffer %d (%s): %s .\n", __FILE__, __LINE__, bo_gem->gem_handle, bo_gem->name, strerror(errno)); if (--bo_gem->map_count == 0) drm_intel_gem_bo_close_vma(bufmgr_gem, bo_gem); pthread_mutex_unlock(&bufmgr_gem->lock); return ret; } VG(VALGRIND_MALLOCLIKE_BLOCK(mmap_arg.addr_ptr, mmap_arg.size, 0, 1)); bo_gem->mem_virtual = (void *)(uintptr_t) mmap_arg.addr_ptr; } DBG("bo_map: %d (%s) -> %p\n", bo_gem->gem_handle, bo_gem->name, bo_gem->mem_virtual); bo->virtual = bo_gem->mem_virtual; memclear(set_domain); set_domain.handle = bo_gem->gem_handle; set_domain.read_domains = I915_GEM_DOMAIN_CPU; if (write_enable) set_domain.write_domain = I915_GEM_DOMAIN_CPU; else set_domain.write_domain = 0; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &set_domain); if (ret != 0) { DBG("%s:%d: Error setting to CPU domain %d: %s\n", __FILE__, __LINE__, bo_gem->gem_handle, strerror(errno)); } if (write_enable) bo_gem->mapped_cpu_write = true; drm_intel_gem_bo_mark_mmaps_incoherent(bo); VG(VALGRIND_MAKE_MEM_DEFINED(bo_gem->mem_virtual, bo->size)); pthread_mutex_unlock(&bufmgr_gem->lock); return 0; } static int map_gtt(drm_intel_bo *bo) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; int ret; if (bo_gem->is_userptr) return -EINVAL; if (bo_gem->map_count++ == 0) drm_intel_gem_bo_open_vma(bufmgr_gem, bo_gem); /* Get a mapping of the buffer if we haven't before. */ if (bo_gem->gtt_virtual == NULL) { struct drm_i915_gem_mmap_gtt mmap_arg; DBG("bo_map_gtt: mmap %d (%s), map_count=%d\n", bo_gem->gem_handle, bo_gem->name, bo_gem->map_count); memclear(mmap_arg); mmap_arg.handle = bo_gem->gem_handle; /* Get the fake offset back... */ ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_MMAP_GTT, &mmap_arg); if (ret != 0) { ret = -errno; DBG("%s:%d: Error preparing buffer map %d (%s): %s .\n", __FILE__, __LINE__, bo_gem->gem_handle, bo_gem->name, strerror(errno)); if (--bo_gem->map_count == 0) drm_intel_gem_bo_close_vma(bufmgr_gem, bo_gem); return ret; } /* and mmap it */ bo_gem->gtt_virtual = drm_mmap(0, bo->size, PROT_READ | PROT_WRITE, MAP_SHARED, bufmgr_gem->fd, mmap_arg.offset); if (bo_gem->gtt_virtual == MAP_FAILED) { bo_gem->gtt_virtual = NULL; ret = -errno; DBG("%s:%d: Error mapping buffer %d (%s): %s .\n", __FILE__, __LINE__, bo_gem->gem_handle, bo_gem->name, strerror(errno)); if (--bo_gem->map_count == 0) drm_intel_gem_bo_close_vma(bufmgr_gem, bo_gem); return ret; } } bo->virtual = bo_gem->gtt_virtual; DBG("bo_map_gtt: %d (%s) -> %p\n", bo_gem->gem_handle, bo_gem->name, bo_gem->gtt_virtual); return 0; } drm_public int drm_intel_gem_bo_map_gtt(drm_intel_bo *bo) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; struct drm_i915_gem_set_domain set_domain; int ret; pthread_mutex_lock(&bufmgr_gem->lock); ret = map_gtt(bo); if (ret) { pthread_mutex_unlock(&bufmgr_gem->lock); return ret; } /* Now move it to the GTT domain so that the GPU and CPU * caches are flushed and the GPU isn't actively using the * buffer. * * The pagefault handler does this domain change for us when * it has unbound the BO from the GTT, but it's up to us to * tell it when we're about to use things if we had done * rendering and it still happens to be bound to the GTT. */ memclear(set_domain); set_domain.handle = bo_gem->gem_handle; set_domain.read_domains = I915_GEM_DOMAIN_GTT; set_domain.write_domain = I915_GEM_DOMAIN_GTT; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &set_domain); if (ret != 0) { DBG("%s:%d: Error setting domain %d: %s\n", __FILE__, __LINE__, bo_gem->gem_handle, strerror(errno)); } drm_intel_gem_bo_mark_mmaps_incoherent(bo); VG(VALGRIND_MAKE_MEM_DEFINED(bo_gem->gtt_virtual, bo->size)); pthread_mutex_unlock(&bufmgr_gem->lock); return 0; } /** * Performs a mapping of the buffer object like the normal GTT * mapping, but avoids waiting for the GPU to be done reading from or * rendering to the buffer. * * This is used in the implementation of GL_ARB_map_buffer_range: The * user asks to create a buffer, then does a mapping, fills some * space, runs a drawing command, then asks to map it again without * synchronizing because it guarantees that it won't write over the * data that the GPU is busy using (or, more specifically, that if it * does write over the data, it acknowledges that rendering is * undefined). */ drm_public int drm_intel_gem_bo_map_unsynchronized(drm_intel_bo *bo) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; #if HAVE_VALGRIND drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; #endif int ret; /* If the CPU cache isn't coherent with the GTT, then use a * regular synchronized mapping. The problem is that we don't * track where the buffer was last used on the CPU side in * terms of drm_intel_bo_map vs drm_intel_gem_bo_map_gtt, so * we would potentially corrupt the buffer even when the user * does reasonable things. */ if (!bufmgr_gem->has_llc) return drm_intel_gem_bo_map_gtt(bo); pthread_mutex_lock(&bufmgr_gem->lock); ret = map_gtt(bo); if (ret == 0) { drm_intel_gem_bo_mark_mmaps_incoherent(bo); VG(VALGRIND_MAKE_MEM_DEFINED(bo_gem->gtt_virtual, bo->size)); } pthread_mutex_unlock(&bufmgr_gem->lock); return ret; } static int drm_intel_gem_bo_unmap(drm_intel_bo *bo) { drm_intel_bufmgr_gem *bufmgr_gem; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; int ret = 0; if (bo == NULL) return 0; if (bo_gem->is_userptr) return 0; bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; pthread_mutex_lock(&bufmgr_gem->lock); if (bo_gem->map_count <= 0) { DBG("attempted to unmap an unmapped bo\n"); pthread_mutex_unlock(&bufmgr_gem->lock); /* Preserve the old behaviour of just treating this as a * no-op rather than reporting the error. */ return 0; } if (bo_gem->mapped_cpu_write) { struct drm_i915_gem_sw_finish sw_finish; /* Cause a flush to happen if the buffer's pinned for * scanout, so the results show up in a timely manner. * Unlike GTT set domains, this only does work if the * buffer should be scanout-related. */ memclear(sw_finish); sw_finish.handle = bo_gem->gem_handle; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_SW_FINISH, &sw_finish); ret = ret == -1 ? -errno : 0; bo_gem->mapped_cpu_write = false; } /* We need to unmap after every innovation as we cannot track * an open vma for every bo as that will exhaust the system * limits and cause later failures. */ if (--bo_gem->map_count == 0) { drm_intel_gem_bo_close_vma(bufmgr_gem, bo_gem); drm_intel_gem_bo_mark_mmaps_incoherent(bo); bo->virtual = NULL; } pthread_mutex_unlock(&bufmgr_gem->lock); return ret; } drm_public int drm_intel_gem_bo_unmap_gtt(drm_intel_bo *bo) { return drm_intel_gem_bo_unmap(bo); } static bool is_cache_coherent(drm_intel_bo *bo) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; struct drm_i915_gem_caching arg = {}; arg.handle = bo_gem->gem_handle; if (drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_GET_CACHING, &arg)) assert(false); return arg.caching != I915_CACHING_NONE; } static void set_domain(drm_intel_bo *bo, uint32_t read, uint32_t write) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; struct drm_i915_gem_set_domain arg = {}; arg.handle = bo_gem->gem_handle; arg.read_domains = read; arg.write_domain = write; if (drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &arg)) assert(false); } static int mmap_write(drm_intel_bo *bo, unsigned long offset, unsigned long length, const void *buf) { void *map = NULL; if (!length) return 0; if (is_cache_coherent(bo)) { map = drm_intel_gem_bo_map__cpu(bo); if (map) set_domain(bo, I915_GEM_DOMAIN_CPU, I915_GEM_DOMAIN_CPU); } if (!map) { map = drm_intel_gem_bo_map__wc(bo); if (map) set_domain(bo, I915_GEM_DOMAIN_WC, I915_GEM_DOMAIN_WC); } assert(map); memcpy((char *)map + offset, buf, length); drm_intel_gem_bo_unmap(bo); return 0; } static int mmap_read(drm_intel_bo *bo, unsigned long offset, unsigned long length, void *buf) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; void *map = NULL; if (!length) return 0; if (bufmgr_gem->has_llc || is_cache_coherent(bo)) { map = drm_intel_gem_bo_map__cpu(bo); if (map) set_domain(bo, I915_GEM_DOMAIN_CPU, 0); } if (!map) { map = drm_intel_gem_bo_map__wc(bo); if (map) set_domain(bo, I915_GEM_DOMAIN_WC, 0); } assert(map); memcpy(buf, (char *)map + offset, length); drm_intel_gem_bo_unmap(bo); return 0; } static int drm_intel_gem_bo_subdata(drm_intel_bo *bo, unsigned long offset, unsigned long size, const void *data) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; struct drm_i915_gem_pwrite pwrite; int ret; if (bo_gem->is_userptr) return -EINVAL; memclear(pwrite); pwrite.handle = bo_gem->gem_handle; pwrite.offset = offset; pwrite.size = size; pwrite.data_ptr = (uint64_t) (uintptr_t) data; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_PWRITE, &pwrite); if (ret) ret = -errno; if (ret != 0 && ret != -EOPNOTSUPP) { DBG("%s:%d: Error writing data to buffer %d: (%d %d) %s .\n", __FILE__, __LINE__, bo_gem->gem_handle, (int)offset, (int)size, strerror(errno)); return ret; } if (ret == -EOPNOTSUPP) mmap_write(bo, offset, size, data); return 0; } static int drm_intel_gem_get_pipe_from_crtc_id(drm_intel_bufmgr *bufmgr, int crtc_id) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bufmgr; struct drm_i915_get_pipe_from_crtc_id get_pipe_from_crtc_id; int ret; memclear(get_pipe_from_crtc_id); get_pipe_from_crtc_id.crtc_id = crtc_id; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GET_PIPE_FROM_CRTC_ID, &get_pipe_from_crtc_id); if (ret != 0) { /* We return -1 here to signal that we don't * know which pipe is associated with this crtc. * This lets the caller know that this information * isn't available; using the wrong pipe for * vblank waiting can cause the chipset to lock up */ return -1; } return get_pipe_from_crtc_id.pipe; } static int drm_intel_gem_bo_get_subdata(drm_intel_bo *bo, unsigned long offset, unsigned long size, void *data) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; struct drm_i915_gem_pread pread; int ret; if (bo_gem->is_userptr) return -EINVAL; memclear(pread); pread.handle = bo_gem->gem_handle; pread.offset = offset; pread.size = size; pread.data_ptr = (uint64_t) (uintptr_t) data; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_PREAD, &pread); if (ret) ret = -errno; if (ret != 0 && ret != -EOPNOTSUPP) { DBG("%s:%d: Error reading data from buffer %d: (%d %d) %s .\n", __FILE__, __LINE__, bo_gem->gem_handle, (int)offset, (int)size, strerror(errno)); return ret; } if (ret == -EOPNOTSUPP) mmap_read(bo, offset, size, data); return 0; } /** Waits for all GPU rendering with the object to have completed. */ static void drm_intel_gem_bo_wait_rendering(drm_intel_bo *bo) { drm_intel_gem_bo_start_gtt_access(bo, 1); } /** * Waits on a BO for the given amount of time. * * @bo: buffer object to wait for * @timeout_ns: amount of time to wait in nanoseconds. * If value is less than 0, an infinite wait will occur. * * Returns 0 if the wait was successful ie. the last batch referencing the * object has completed within the allotted time. Otherwise some negative return * value describes the error. Of particular interest is -ETIME when the wait has * failed to yield the desired result. * * Similar to drm_intel_gem_bo_wait_rendering except a timeout parameter allows * the operation to give up after a certain amount of time. Another subtle * difference is the internal locking semantics are different (this variant does * not hold the lock for the duration of the wait). This makes the wait subject * to a larger userspace race window. * * The implementation shall wait until the object is no longer actively * referenced within a batch buffer at the time of the call. The wait will * not guarantee that the buffer is re-issued via another thread, or an flinked * handle. Userspace must make sure this race does not occur if such precision * is important. * * Note that some kernels have broken the inifite wait for negative values * promise, upgrade to latest stable kernels if this is the case. */ drm_public int drm_intel_gem_bo_wait(drm_intel_bo *bo, int64_t timeout_ns) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; struct drm_i915_gem_wait wait; int ret; if (!bufmgr_gem->has_wait_timeout) { DBG("%s:%d: Timed wait is not supported. Falling back to " "infinite wait\n", __FILE__, __LINE__); if (timeout_ns) { drm_intel_gem_bo_wait_rendering(bo); return 0; } else { return drm_intel_gem_bo_busy(bo) ? -ETIME : 0; } } memclear(wait); wait.bo_handle = bo_gem->gem_handle; wait.timeout_ns = timeout_ns; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_WAIT, &wait); if (ret == -1) return -errno; return ret; } /** * Sets the object to the GTT read and possibly write domain, used by the X * 2D driver in the absence of kernel support to do drm_intel_gem_bo_map_gtt(). * * In combination with drm_intel_gem_bo_pin() and manual fence management, we * can do tiled pixmaps this way. */ drm_public void drm_intel_gem_bo_start_gtt_access(drm_intel_bo *bo, int write_enable) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; struct drm_i915_gem_set_domain set_domain; int ret; memclear(set_domain); set_domain.handle = bo_gem->gem_handle; set_domain.read_domains = I915_GEM_DOMAIN_GTT; set_domain.write_domain = write_enable ? I915_GEM_DOMAIN_GTT : 0; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_SET_DOMAIN, &set_domain); if (ret != 0) { DBG("%s:%d: Error setting memory domains %d (%08x %08x): %s .\n", __FILE__, __LINE__, bo_gem->gem_handle, set_domain.read_domains, set_domain.write_domain, strerror(errno)); } } static void drm_intel_bufmgr_gem_destroy(drm_intel_bufmgr *bufmgr) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bufmgr; int i, ret; free(bufmgr_gem->exec2_objects); free(bufmgr_gem->exec_bos); pthread_mutex_destroy(&bufmgr_gem->lock); /* Free any cached buffer objects we were going to reuse */ for (i = 0; i < bufmgr_gem->num_buckets; i++) { struct drm_intel_gem_bo_bucket *bucket = &bufmgr_gem->cache_bucket[i]; drm_intel_bo_gem *bo_gem; while (!DRMLISTEMPTY(&bucket->head)) { bo_gem = DRMLISTENTRY(drm_intel_bo_gem, bucket->head.next, head); DRMLISTDEL(&bo_gem->head); drm_intel_gem_bo_free(&bo_gem->bo); } } /* Release userptr bo kept hanging around for optimisation. */ if (bufmgr_gem->userptr_active.ptr) { ret = drmCloseBufferHandle(bufmgr_gem->fd, bufmgr_gem->userptr_active.handle); free(bufmgr_gem->userptr_active.ptr); if (ret) fprintf(stderr, "Failed to release test userptr object! (%d) " "i915 kernel driver may not be sane!\n", errno); } free(bufmgr); } /** * Adds the target buffer to the validation list and adds the relocation * to the reloc_buffer's relocation list. * * The relocation entry at the given offset must already contain the * precomputed relocation value, because the kernel will optimize out * the relocation entry write when the buffer hasn't moved from the * last known offset in target_bo. */ static int do_bo_emit_reloc(drm_intel_bo *bo, uint32_t offset, drm_intel_bo *target_bo, uint32_t target_offset, uint32_t read_domains, uint32_t write_domain, bool need_fence) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; drm_intel_bo_gem *target_bo_gem = (drm_intel_bo_gem *) target_bo; bool fenced_command; if (bo_gem->has_error) return -ENOMEM; if (target_bo_gem->has_error) { bo_gem->has_error = true; return -ENOMEM; } /* We never use HW fences for rendering on 965+ */ if (bufmgr_gem->gen >= 4) need_fence = false; fenced_command = need_fence; if (target_bo_gem->tiling_mode == I915_TILING_NONE) need_fence = false; /* Create a new relocation list if needed */ if (bo_gem->relocs == NULL && drm_intel_setup_reloc_list(bo)) return -ENOMEM; /* Check overflow */ assert(bo_gem->reloc_count < bufmgr_gem->max_relocs); /* Check args */ assert(offset <= bo->size - 4); assert((write_domain & (write_domain - 1)) == 0); /* An object needing a fence is a tiled buffer, so it won't have * relocs to other buffers. */ if (need_fence) { assert(target_bo_gem->reloc_count == 0); target_bo_gem->reloc_tree_fences = 1; } /* Make sure that we're not adding a reloc to something whose size has * already been accounted for. */ assert(!bo_gem->used_as_reloc_target); if (target_bo_gem != bo_gem) { target_bo_gem->used_as_reloc_target = true; bo_gem->reloc_tree_size += target_bo_gem->reloc_tree_size; bo_gem->reloc_tree_fences += target_bo_gem->reloc_tree_fences; } bo_gem->reloc_target_info[bo_gem->reloc_count].bo = target_bo; if (target_bo != bo) drm_intel_gem_bo_reference(target_bo); if (fenced_command) bo_gem->reloc_target_info[bo_gem->reloc_count].flags = DRM_INTEL_RELOC_FENCE; else bo_gem->reloc_target_info[bo_gem->reloc_count].flags = 0; bo_gem->relocs[bo_gem->reloc_count].offset = offset; bo_gem->relocs[bo_gem->reloc_count].delta = target_offset; bo_gem->relocs[bo_gem->reloc_count].target_handle = target_bo_gem->gem_handle; bo_gem->relocs[bo_gem->reloc_count].read_domains = read_domains; bo_gem->relocs[bo_gem->reloc_count].write_domain = write_domain; bo_gem->relocs[bo_gem->reloc_count].presumed_offset = target_bo->offset64; bo_gem->reloc_count++; return 0; } static void drm_intel_gem_bo_use_48b_address_range(drm_intel_bo *bo, uint32_t enable) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; if (enable) bo_gem->kflags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS; else bo_gem->kflags &= ~EXEC_OBJECT_SUPPORTS_48B_ADDRESS; } static int drm_intel_gem_bo_add_softpin_target(drm_intel_bo *bo, drm_intel_bo *target_bo) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; drm_intel_bo_gem *target_bo_gem = (drm_intel_bo_gem *) target_bo; if (bo_gem->has_error) return -ENOMEM; if (target_bo_gem->has_error) { bo_gem->has_error = true; return -ENOMEM; } if (!(target_bo_gem->kflags & EXEC_OBJECT_PINNED)) return -EINVAL; if (target_bo_gem == bo_gem) return -EINVAL; if (bo_gem->softpin_target_count == bo_gem->softpin_target_size) { int new_size = bo_gem->softpin_target_size * 2; if (new_size == 0) new_size = bufmgr_gem->max_relocs; bo_gem->softpin_target = realloc(bo_gem->softpin_target, new_size * sizeof(drm_intel_bo *)); if (!bo_gem->softpin_target) return -ENOMEM; bo_gem->softpin_target_size = new_size; } bo_gem->softpin_target[bo_gem->softpin_target_count] = target_bo; drm_intel_gem_bo_reference(target_bo); bo_gem->softpin_target_count++; return 0; } static int drm_intel_gem_bo_emit_reloc(drm_intel_bo *bo, uint32_t offset, drm_intel_bo *target_bo, uint32_t target_offset, uint32_t read_domains, uint32_t write_domain) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *)bo->bufmgr; drm_intel_bo_gem *target_bo_gem = (drm_intel_bo_gem *)target_bo; if (target_bo_gem->kflags & EXEC_OBJECT_PINNED) return drm_intel_gem_bo_add_softpin_target(bo, target_bo); else return do_bo_emit_reloc(bo, offset, target_bo, target_offset, read_domains, write_domain, !bufmgr_gem->fenced_relocs); } static int drm_intel_gem_bo_emit_reloc_fence(drm_intel_bo *bo, uint32_t offset, drm_intel_bo *target_bo, uint32_t target_offset, uint32_t read_domains, uint32_t write_domain) { return do_bo_emit_reloc(bo, offset, target_bo, target_offset, read_domains, write_domain, true); } drm_public int drm_intel_gem_bo_get_reloc_count(drm_intel_bo *bo) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; return bo_gem->reloc_count; } /** * Removes existing relocation entries in the BO after "start". * * This allows a user to avoid a two-step process for state setup with * counting up all the buffer objects and doing a * drm_intel_bufmgr_check_aperture_space() before emitting any of the * relocations for the state setup. Instead, save the state of the * batchbuffer including drm_intel_gem_get_reloc_count(), emit all the * state, and then check if it still fits in the aperture. * * Any further drm_intel_bufmgr_check_aperture_space() queries * involving this buffer in the tree are undefined after this call. * * This also removes all softpinned targets being referenced by the BO. */ drm_public void drm_intel_gem_bo_clear_relocs(drm_intel_bo *bo, int start) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; int i; struct timespec time; clock_gettime(CLOCK_MONOTONIC, &time); assert(bo_gem->reloc_count >= start); /* Unreference the cleared target buffers */ pthread_mutex_lock(&bufmgr_gem->lock); for (i = start; i < bo_gem->reloc_count; i++) { drm_intel_bo_gem *target_bo_gem = (drm_intel_bo_gem *) bo_gem->reloc_target_info[i].bo; if (&target_bo_gem->bo != bo) { bo_gem->reloc_tree_fences -= target_bo_gem->reloc_tree_fences; drm_intel_gem_bo_unreference_locked_timed(&target_bo_gem->bo, time.tv_sec); } } bo_gem->reloc_count = start; for (i = 0; i < bo_gem->softpin_target_count; i++) { drm_intel_bo_gem *target_bo_gem = (drm_intel_bo_gem *) bo_gem->softpin_target[i]; drm_intel_gem_bo_unreference_locked_timed(&target_bo_gem->bo, time.tv_sec); } bo_gem->softpin_target_count = 0; pthread_mutex_unlock(&bufmgr_gem->lock); } /** * Walk the tree of relocations rooted at BO and accumulate the list of * validations to be performed and update the relocation buffers with * index values into the validation list. */ static void drm_intel_gem_bo_process_reloc2(drm_intel_bo *bo) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *)bo; int i; if (bo_gem->relocs == NULL && bo_gem->softpin_target == NULL) return; for (i = 0; i < bo_gem->reloc_count; i++) { drm_intel_bo *target_bo = bo_gem->reloc_target_info[i].bo; int need_fence; if (target_bo == bo) continue; drm_intel_gem_bo_mark_mmaps_incoherent(bo); /* Continue walking the tree depth-first. */ drm_intel_gem_bo_process_reloc2(target_bo); need_fence = (bo_gem->reloc_target_info[i].flags & DRM_INTEL_RELOC_FENCE); /* Add the target to the validate list */ drm_intel_add_validate_buffer2(target_bo, need_fence); } for (i = 0; i < bo_gem->softpin_target_count; i++) { drm_intel_bo *target_bo = bo_gem->softpin_target[i]; if (target_bo == bo) continue; drm_intel_gem_bo_mark_mmaps_incoherent(bo); drm_intel_gem_bo_process_reloc2(target_bo); drm_intel_add_validate_buffer2(target_bo, false); } } static void drm_intel_update_buffer_offsets2 (drm_intel_bufmgr_gem *bufmgr_gem) { int i; for (i = 0; i < bufmgr_gem->exec_count; i++) { drm_intel_bo *bo = bufmgr_gem->exec_bos[i]; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *)bo; /* Update the buffer offset */ if (bufmgr_gem->exec2_objects[i].offset != bo->offset64) { /* If we're seeing softpinned object here it means that the kernel * has relocated our object... Indicating a programming error */ assert(!(bo_gem->kflags & EXEC_OBJECT_PINNED)); DBG("BO %d (%s) migrated: 0x%08x %08x -> 0x%08x %08x\n", bo_gem->gem_handle, bo_gem->name, upper_32_bits(bo->offset64), lower_32_bits(bo->offset64), upper_32_bits(bufmgr_gem->exec2_objects[i].offset), lower_32_bits(bufmgr_gem->exec2_objects[i].offset)); bo->offset64 = bufmgr_gem->exec2_objects[i].offset; bo->offset = bufmgr_gem->exec2_objects[i].offset; } } } drm_public void drm_intel_gem_bo_aub_dump_bmp(drm_intel_bo *bo, int x1, int y1, int width, int height, enum aub_dump_bmp_format format, int pitch, int offset) { } static int do_exec2(drm_intel_bo *bo, int used, drm_intel_context *ctx, drm_clip_rect_t *cliprects, int num_cliprects, int DR4, int in_fence, int *out_fence, unsigned int flags) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *)bo->bufmgr; struct drm_i915_gem_execbuffer2 execbuf; int ret = 0; int i; if (to_bo_gem(bo)->has_error) return -ENOMEM; switch (flags & 0x7) { default: return -EINVAL; case I915_EXEC_BLT: if (!bufmgr_gem->has_blt) return -EINVAL; break; case I915_EXEC_BSD: if (!bufmgr_gem->has_bsd) return -EINVAL; break; case I915_EXEC_VEBOX: if (!bufmgr_gem->has_vebox) return -EINVAL; break; case I915_EXEC_RENDER: case I915_EXEC_DEFAULT: break; } pthread_mutex_lock(&bufmgr_gem->lock); /* Update indices and set up the validate list. */ drm_intel_gem_bo_process_reloc2(bo); /* Add the batch buffer to the validation list. There are no relocations * pointing to it. */ drm_intel_add_validate_buffer2(bo, 0); memclear(execbuf); execbuf.buffers_ptr = (uintptr_t)bufmgr_gem->exec2_objects; execbuf.buffer_count = bufmgr_gem->exec_count; execbuf.batch_start_offset = 0; execbuf.batch_len = used; execbuf.cliprects_ptr = (uintptr_t)cliprects; execbuf.num_cliprects = num_cliprects; execbuf.DR1 = 0; execbuf.DR4 = DR4; execbuf.flags = flags; if (ctx == NULL) i915_execbuffer2_set_context_id(execbuf, 0); else i915_execbuffer2_set_context_id(execbuf, ctx->ctx_id); execbuf.rsvd2 = 0; if (in_fence != -1) { execbuf.rsvd2 = in_fence; execbuf.flags |= I915_EXEC_FENCE_IN; } if (out_fence != NULL) { *out_fence = -1; execbuf.flags |= I915_EXEC_FENCE_OUT; } if (bufmgr_gem->no_exec) goto skip_execution; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_EXECBUFFER2_WR, &execbuf); if (ret != 0) { ret = -errno; if (ret == -ENOSPC) { DBG("Execbuffer fails to pin. " "Estimate: %u. Actual: %u. Available: %u\n", drm_intel_gem_estimate_batch_space(bufmgr_gem->exec_bos, bufmgr_gem->exec_count), drm_intel_gem_compute_batch_space(bufmgr_gem->exec_bos, bufmgr_gem->exec_count), (unsigned int) bufmgr_gem->gtt_size); } } drm_intel_update_buffer_offsets2(bufmgr_gem); if (ret == 0 && out_fence != NULL) *out_fence = execbuf.rsvd2 >> 32; skip_execution: if (bufmgr_gem->bufmgr.debug) drm_intel_gem_dump_validation_list(bufmgr_gem); for (i = 0; i < bufmgr_gem->exec_count; i++) { drm_intel_bo_gem *bo_gem = to_bo_gem(bufmgr_gem->exec_bos[i]); bo_gem->idle = false; /* Disconnect the buffer from the validate list */ bo_gem->validate_index = -1; bufmgr_gem->exec_bos[i] = NULL; } bufmgr_gem->exec_count = 0; pthread_mutex_unlock(&bufmgr_gem->lock); return ret; } static int drm_intel_gem_bo_exec2(drm_intel_bo *bo, int used, drm_clip_rect_t *cliprects, int num_cliprects, int DR4) { return do_exec2(bo, used, NULL, cliprects, num_cliprects, DR4, -1, NULL, I915_EXEC_RENDER); } static int drm_intel_gem_bo_mrb_exec2(drm_intel_bo *bo, int used, drm_clip_rect_t *cliprects, int num_cliprects, int DR4, unsigned int flags) { return do_exec2(bo, used, NULL, cliprects, num_cliprects, DR4, -1, NULL, flags); } drm_public int drm_intel_gem_bo_context_exec(drm_intel_bo *bo, drm_intel_context *ctx, int used, unsigned int flags) { return do_exec2(bo, used, ctx, NULL, 0, 0, -1, NULL, flags); } drm_public int drm_intel_gem_bo_fence_exec(drm_intel_bo *bo, drm_intel_context *ctx, int used, int in_fence, int *out_fence, unsigned int flags) { return do_exec2(bo, used, ctx, NULL, 0, 0, in_fence, out_fence, flags); } static int drm_intel_gem_bo_pin(drm_intel_bo *bo, uint32_t alignment) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; struct drm_i915_gem_pin pin; int ret; memclear(pin); pin.handle = bo_gem->gem_handle; pin.alignment = alignment; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_PIN, &pin); if (ret != 0) return -errno; bo->offset64 = pin.offset; bo->offset = pin.offset; return 0; } static int drm_intel_gem_bo_unpin(drm_intel_bo *bo) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; struct drm_i915_gem_unpin unpin; int ret; memclear(unpin); unpin.handle = bo_gem->gem_handle; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_UNPIN, &unpin); if (ret != 0) return -errno; return 0; } static int drm_intel_gem_bo_set_tiling_internal(drm_intel_bo *bo, uint32_t tiling_mode, uint32_t stride) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; struct drm_i915_gem_set_tiling set_tiling; int ret; if (bo_gem->global_name == 0 && tiling_mode == bo_gem->tiling_mode && stride == bo_gem->stride) return 0; memset(&set_tiling, 0, sizeof(set_tiling)); do { /* set_tiling is slightly broken and overwrites the * input on the error path, so we have to open code * rmIoctl. */ set_tiling.handle = bo_gem->gem_handle; set_tiling.tiling_mode = tiling_mode; set_tiling.stride = stride; ret = ioctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_SET_TILING, &set_tiling); } while (ret == -1 && (errno == EINTR || errno == EAGAIN)); if (ret == -1) return -errno; bo_gem->tiling_mode = set_tiling.tiling_mode; bo_gem->swizzle_mode = set_tiling.swizzle_mode; bo_gem->stride = set_tiling.stride; return 0; } static int drm_intel_gem_bo_set_tiling(drm_intel_bo *bo, uint32_t * tiling_mode, uint32_t stride) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; int ret; /* Tiling with userptr surfaces is not supported * on all hardware so refuse it for time being. */ if (bo_gem->is_userptr) return -EINVAL; /* Linear buffers have no stride. By ensuring that we only ever use * stride 0 with linear buffers, we simplify our code. */ if (*tiling_mode == I915_TILING_NONE) stride = 0; ret = drm_intel_gem_bo_set_tiling_internal(bo, *tiling_mode, stride); if (ret == 0) drm_intel_bo_gem_set_in_aperture_size(bufmgr_gem, bo_gem, 0); *tiling_mode = bo_gem->tiling_mode; return ret; } static int drm_intel_gem_bo_get_tiling(drm_intel_bo *bo, uint32_t * tiling_mode, uint32_t * swizzle_mode) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; *tiling_mode = bo_gem->tiling_mode; *swizzle_mode = bo_gem->swizzle_mode; return 0; } static int drm_intel_gem_bo_set_softpin_offset(drm_intel_bo *bo, uint64_t offset) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; bo->offset64 = offset; bo->offset = offset; bo_gem->kflags |= EXEC_OBJECT_PINNED; return 0; } drm_public drm_intel_bo * drm_intel_bo_gem_create_from_prime(drm_intel_bufmgr *bufmgr, int prime_fd, int size) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bufmgr; int ret; uint32_t handle; drm_intel_bo_gem *bo_gem; pthread_mutex_lock(&bufmgr_gem->lock); ret = drmPrimeFDToHandle(bufmgr_gem->fd, prime_fd, &handle); if (ret) { DBG("create_from_prime: failed to obtain handle from fd: %s\n", strerror(errno)); pthread_mutex_unlock(&bufmgr_gem->lock); return NULL; } /* * See if the kernel has already returned this buffer to us. Just as * for named buffers, we must not create two bo's pointing at the same * kernel object */ HASH_FIND(handle_hh, bufmgr_gem->handle_table, &handle, sizeof(handle), bo_gem); if (bo_gem) { drm_intel_gem_bo_reference(&bo_gem->bo); goto out; } bo_gem = calloc(1, sizeof(*bo_gem)); if (!bo_gem) goto out; atomic_set(&bo_gem->refcount, 1); DRMINITLISTHEAD(&bo_gem->vma_list); /* Determine size of bo. The fd-to-handle ioctl really should * return the size, but it doesn't. If we have kernel 3.12 or * later, we can lseek on the prime fd to get the size. Older * kernels will just fail, in which case we fall back to the * provided (estimated or guess size). */ ret = lseek(prime_fd, 0, SEEK_END); if (ret != -1) bo_gem->bo.size = ret; else bo_gem->bo.size = size; bo_gem->bo.handle = handle; bo_gem->bo.bufmgr = bufmgr; bo_gem->gem_handle = handle; HASH_ADD(handle_hh, bufmgr_gem->handle_table, gem_handle, sizeof(bo_gem->gem_handle), bo_gem); bo_gem->name = "prime"; bo_gem->validate_index = -1; bo_gem->reloc_tree_fences = 0; bo_gem->used_as_reloc_target = false; bo_gem->has_error = false; bo_gem->reusable = false; ret = get_tiling_mode(bufmgr_gem, handle, &bo_gem->tiling_mode, &bo_gem->swizzle_mode); if (ret) goto err; /* XXX stride is unknown */ drm_intel_bo_gem_set_in_aperture_size(bufmgr_gem, bo_gem, 0); out: pthread_mutex_unlock(&bufmgr_gem->lock); return &bo_gem->bo; err: drm_intel_gem_bo_free(&bo_gem->bo); pthread_mutex_unlock(&bufmgr_gem->lock); return NULL; } drm_public int drm_intel_bo_gem_export_to_prime(drm_intel_bo *bo, int *prime_fd) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; if (drmPrimeHandleToFD(bufmgr_gem->fd, bo_gem->gem_handle, DRM_CLOEXEC | DRM_RDWR, prime_fd) != 0) return -errno; bo_gem->reusable = false; return 0; } static int drm_intel_gem_bo_flink(drm_intel_bo *bo, uint32_t * name) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; if (!bo_gem->global_name) { struct drm_gem_flink flink; memclear(flink); flink.handle = bo_gem->gem_handle; if (drmIoctl(bufmgr_gem->fd, DRM_IOCTL_GEM_FLINK, &flink)) return -errno; pthread_mutex_lock(&bufmgr_gem->lock); if (!bo_gem->global_name) { bo_gem->global_name = flink.name; bo_gem->reusable = false; HASH_ADD(name_hh, bufmgr_gem->name_table, global_name, sizeof(bo_gem->global_name), bo_gem); } pthread_mutex_unlock(&bufmgr_gem->lock); } *name = bo_gem->global_name; return 0; } /** * Enables unlimited caching of buffer objects for reuse. * * This is potentially very memory expensive, as the cache at each bucket * size is only bounded by how many buffers of that size we've managed to have * in flight at once. */ drm_public void drm_intel_bufmgr_gem_enable_reuse(drm_intel_bufmgr *bufmgr) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bufmgr; bufmgr_gem->bo_reuse = true; } /** * Disables implicit synchronisation before executing the bo * * This will cause rendering corruption unless you correctly manage explicit * fences for all rendering involving this buffer - including use by others. * Disabling the implicit serialisation is only required if that serialisation * is too coarse (for example, you have split the buffer into many * non-overlapping regions and are sharing the whole buffer between concurrent * independent command streams). * * Note the kernel must advertise support via I915_PARAM_HAS_EXEC_ASYNC, * which can be checked using drm_intel_bufmgr_can_disable_implicit_sync, * or subsequent execbufs involving the bo will generate EINVAL. */ drm_public void drm_intel_gem_bo_disable_implicit_sync(drm_intel_bo *bo) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; bo_gem->kflags |= EXEC_OBJECT_ASYNC; } /** * Enables implicit synchronisation before executing the bo * * This is the default behaviour of the kernel, to wait upon prior writes * completing on the object before rendering with it, or to wait for prior * reads to complete before writing into the object. * drm_intel_gem_bo_disable_implicit_sync() can stop this behaviour, telling * the kernel never to insert a stall before using the object. Then this * function can be used to restore the implicit sync before subsequent * rendering. */ drm_public void drm_intel_gem_bo_enable_implicit_sync(drm_intel_bo *bo) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; bo_gem->kflags &= ~EXEC_OBJECT_ASYNC; } /** * Query whether the kernel supports disabling of its implicit synchronisation * before execbuf. See drm_intel_gem_bo_disable_implicit_sync() */ drm_public int drm_intel_bufmgr_gem_can_disable_implicit_sync(drm_intel_bufmgr *bufmgr) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bufmgr; return bufmgr_gem->has_exec_async; } /** * Enable use of fenced reloc type. * * New code should enable this to avoid unnecessary fence register * allocation. If this option is not enabled, all relocs will have fence * register allocated. */ drm_public void drm_intel_bufmgr_gem_enable_fenced_relocs(drm_intel_bufmgr *bufmgr) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *)bufmgr; bufmgr_gem->fenced_relocs = true; } /** * Return the additional aperture space required by the tree of buffer objects * rooted at bo. */ static int drm_intel_gem_bo_get_aperture_space(drm_intel_bo *bo) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; int i; int total = 0; if (bo == NULL || bo_gem->included_in_check_aperture) return 0; total += bo->size; bo_gem->included_in_check_aperture = true; for (i = 0; i < bo_gem->reloc_count; i++) total += drm_intel_gem_bo_get_aperture_space(bo_gem-> reloc_target_info[i].bo); return total; } /** * Count the number of buffers in this list that need a fence reg * * If the count is greater than the number of available regs, we'll have * to ask the caller to resubmit a batch with fewer tiled buffers. * * This function over-counts if the same buffer is used multiple times. */ static unsigned int drm_intel_gem_total_fences(drm_intel_bo ** bo_array, int count) { int i; unsigned int total = 0; for (i = 0; i < count; i++) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo_array[i]; if (bo_gem == NULL) continue; total += bo_gem->reloc_tree_fences; } return total; } /** * Clear the flag set by drm_intel_gem_bo_get_aperture_space() so we're ready * for the next drm_intel_bufmgr_check_aperture_space() call. */ static void drm_intel_gem_bo_clear_aperture_space_flag(drm_intel_bo *bo) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; int i; if (bo == NULL || !bo_gem->included_in_check_aperture) return; bo_gem->included_in_check_aperture = false; for (i = 0; i < bo_gem->reloc_count; i++) drm_intel_gem_bo_clear_aperture_space_flag(bo_gem-> reloc_target_info[i].bo); } /** * Return a conservative estimate for the amount of aperture required * for a collection of buffers. This may double-count some buffers. */ static unsigned int drm_intel_gem_estimate_batch_space(drm_intel_bo **bo_array, int count) { int i; unsigned int total = 0; for (i = 0; i < count; i++) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo_array[i]; if (bo_gem != NULL) total += bo_gem->reloc_tree_size; } return total; } /** * Return the amount of aperture needed for a collection of buffers. * This avoids double counting any buffers, at the cost of looking * at every buffer in the set. */ static unsigned int drm_intel_gem_compute_batch_space(drm_intel_bo **bo_array, int count) { int i; unsigned int total = 0; for (i = 0; i < count; i++) { total += drm_intel_gem_bo_get_aperture_space(bo_array[i]); /* For the first buffer object in the array, we get an * accurate count back for its reloc_tree size (since nothing * had been flagged as being counted yet). We can save that * value out as a more conservative reloc_tree_size that * avoids double-counting target buffers. Since the first * buffer happens to usually be the batch buffer in our * callers, this can pull us back from doing the tree * walk on every new batch emit. */ if (i == 0) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo_array[i]; bo_gem->reloc_tree_size = total; } } for (i = 0; i < count; i++) drm_intel_gem_bo_clear_aperture_space_flag(bo_array[i]); return total; } /** * Return -1 if the batchbuffer should be flushed before attempting to * emit rendering referencing the buffers pointed to by bo_array. * * This is required because if we try to emit a batchbuffer with relocations * to a tree of buffers that won't simultaneously fit in the aperture, * the rendering will return an error at a point where the software is not * prepared to recover from it. * * However, we also want to emit the batchbuffer significantly before we reach * the limit, as a series of batchbuffers each of which references buffers * covering almost all of the aperture means that at each emit we end up * waiting to evict a buffer from the last rendering, and we get synchronous * performance. By emitting smaller batchbuffers, we eat some CPU overhead to * get better parallelism. */ static int drm_intel_gem_check_aperture_space(drm_intel_bo **bo_array, int count) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo_array[0]->bufmgr; unsigned int total = 0; unsigned int threshold = bufmgr_gem->gtt_size * 3 / 4; int total_fences; /* Check for fence reg constraints if necessary */ if (bufmgr_gem->available_fences) { total_fences = drm_intel_gem_total_fences(bo_array, count); if (total_fences > bufmgr_gem->available_fences) return -ENOSPC; } total = drm_intel_gem_estimate_batch_space(bo_array, count); if (total > threshold) total = drm_intel_gem_compute_batch_space(bo_array, count); if (total > threshold) { DBG("check_space: overflowed available aperture, " "%dkb vs %dkb\n", total / 1024, (int)bufmgr_gem->gtt_size / 1024); return -ENOSPC; } else { DBG("drm_check_space: total %dkb vs bufgr %dkb\n", total / 1024, (int)bufmgr_gem->gtt_size / 1024); return 0; } } /* * Disable buffer reuse for objects which are shared with the kernel * as scanout buffers */ static int drm_intel_gem_bo_disable_reuse(drm_intel_bo *bo) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; bo_gem->reusable = false; return 0; } static int drm_intel_gem_bo_is_reusable(drm_intel_bo *bo) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; return bo_gem->reusable; } static int _drm_intel_gem_bo_references(drm_intel_bo *bo, drm_intel_bo *target_bo) { drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; int i; for (i = 0; i < bo_gem->reloc_count; i++) { if (bo_gem->reloc_target_info[i].bo == target_bo) return 1; if (bo == bo_gem->reloc_target_info[i].bo) continue; if (_drm_intel_gem_bo_references(bo_gem->reloc_target_info[i].bo, target_bo)) return 1; } for (i = 0; i< bo_gem->softpin_target_count; i++) { if (bo_gem->softpin_target[i] == target_bo) return 1; if (_drm_intel_gem_bo_references(bo_gem->softpin_target[i], target_bo)) return 1; } return 0; } /** Return true if target_bo is referenced by bo's relocation tree. */ static int drm_intel_gem_bo_references(drm_intel_bo *bo, drm_intel_bo *target_bo) { drm_intel_bo_gem *target_bo_gem = (drm_intel_bo_gem *) target_bo; if (bo == NULL || target_bo == NULL) return 0; if (target_bo_gem->used_as_reloc_target) return _drm_intel_gem_bo_references(bo, target_bo); return 0; } static void add_bucket(drm_intel_bufmgr_gem *bufmgr_gem, int size) { unsigned int i = bufmgr_gem->num_buckets; assert(i < ARRAY_SIZE(bufmgr_gem->cache_bucket)); DRMINITLISTHEAD(&bufmgr_gem->cache_bucket[i].head); bufmgr_gem->cache_bucket[i].size = size; bufmgr_gem->num_buckets++; } static void init_cache_buckets(drm_intel_bufmgr_gem *bufmgr_gem) { unsigned long size, cache_max_size = 64 * 1024 * 1024; /* OK, so power of two buckets was too wasteful of memory. * Give 3 other sizes between each power of two, to hopefully * cover things accurately enough. (The alternative is * probably to just go for exact matching of sizes, and assume * that for things like composited window resize the tiled * width/height alignment and rounding of sizes to pages will * get us useful cache hit rates anyway) */ add_bucket(bufmgr_gem, 4096); add_bucket(bufmgr_gem, 4096 * 2); add_bucket(bufmgr_gem, 4096 * 3); /* Initialize the linked lists for BO reuse cache. */ for (size = 4 * 4096; size <= cache_max_size; size *= 2) { add_bucket(bufmgr_gem, size); add_bucket(bufmgr_gem, size + size * 1 / 4); add_bucket(bufmgr_gem, size + size * 2 / 4); add_bucket(bufmgr_gem, size + size * 3 / 4); } } drm_public void drm_intel_bufmgr_gem_set_vma_cache_size(drm_intel_bufmgr *bufmgr, int limit) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *)bufmgr; bufmgr_gem->vma_max = limit; drm_intel_gem_bo_purge_vma_cache(bufmgr_gem); } static int parse_devid_override(const char *devid_override) { static const struct { const char *name; int pci_id; } name_map[] = { { "brw", PCI_CHIP_I965_GM }, { "g4x", PCI_CHIP_GM45_GM }, { "ilk", PCI_CHIP_ILD_G }, { "snb", PCI_CHIP_SANDYBRIDGE_M_GT2_PLUS }, { "ivb", PCI_CHIP_IVYBRIDGE_S_GT2 }, { "hsw", PCI_CHIP_HASWELL_CRW_E_GT3 }, { "byt", PCI_CHIP_VALLEYVIEW_3 }, { "bdw", 0x1620 | BDW_ULX }, { "skl", PCI_CHIP_SKYLAKE_DT_GT2 }, { "kbl", PCI_CHIP_KABYLAKE_DT_GT2 }, }; unsigned int i; for (i = 0; i < ARRAY_SIZE(name_map); i++) { if (!strcmp(name_map[i].name, devid_override)) return name_map[i].pci_id; } return strtod(devid_override, NULL); } /** * Get the PCI ID for the device. This can be overridden by setting the * INTEL_DEVID_OVERRIDE environment variable to the desired ID. */ static int get_pci_device_id(drm_intel_bufmgr_gem *bufmgr_gem) { char *devid_override; int devid = 0; int ret; drm_i915_getparam_t gp; if (geteuid() == getuid()) { devid_override = getenv("INTEL_DEVID_OVERRIDE"); if (devid_override) { bufmgr_gem->no_exec = true; return parse_devid_override(devid_override); } } memclear(gp); gp.param = I915_PARAM_CHIPSET_ID; gp.value = &devid; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GETPARAM, &gp); if (ret) { fprintf(stderr, "get chip id failed: %d [%d]\n", ret, errno); fprintf(stderr, "param: %d, val: %d\n", gp.param, *gp.value); } return devid; } drm_public int drm_intel_bufmgr_gem_get_devid(drm_intel_bufmgr *bufmgr) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *)bufmgr; return bufmgr_gem->pci_device; } /** * Sets the AUB filename. * * This function has to be called before drm_intel_bufmgr_gem_set_aub_dump() * for it to have any effect. */ drm_public void drm_intel_bufmgr_gem_set_aub_filename(drm_intel_bufmgr *bufmgr, const char *filename) { } /** * Sets up AUB dumping. * * This is a trace file format that can be used with the simulator. * Packets are emitted in a format somewhat like GPU command packets. * You can set up a GTT and upload your objects into the referenced * space, then send off batchbuffers and get BMPs out the other end. */ drm_public void drm_intel_bufmgr_gem_set_aub_dump(drm_intel_bufmgr *bufmgr, int enable) { fprintf(stderr, "libdrm aub dumping is deprecated.\n\n" "Use intel_aubdump from intel-gpu-tools instead. Install intel-gpu-tools,\n" "then run (for example)\n\n" "\t$ intel_aubdump --output=trace.aub glxgears -geometry 500x500\n\n" "See the intel_aubdump man page for more details.\n"); } drm_public drm_intel_context * drm_intel_gem_context_create(drm_intel_bufmgr *bufmgr) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *)bufmgr; struct drm_i915_gem_context_create create; drm_intel_context *context = NULL; int ret; context = calloc(1, sizeof(*context)); if (!context) return NULL; memclear(create); ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_CONTEXT_CREATE, &create); if (ret != 0) { DBG("DRM_IOCTL_I915_GEM_CONTEXT_CREATE failed: %s\n", strerror(errno)); free(context); return NULL; } context->ctx_id = create.ctx_id; context->bufmgr = bufmgr; return context; } drm_public int drm_intel_gem_context_get_id(drm_intel_context *ctx, uint32_t *ctx_id) { if (ctx == NULL) return -EINVAL; *ctx_id = ctx->ctx_id; return 0; } drm_public void drm_intel_gem_context_destroy(drm_intel_context *ctx) { drm_intel_bufmgr_gem *bufmgr_gem; struct drm_i915_gem_context_destroy destroy; int ret; if (ctx == NULL) return; memclear(destroy); bufmgr_gem = (drm_intel_bufmgr_gem *)ctx->bufmgr; destroy.ctx_id = ctx->ctx_id; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_CONTEXT_DESTROY, &destroy); if (ret != 0) fprintf(stderr, "DRM_IOCTL_I915_GEM_CONTEXT_DESTROY failed: %s\n", strerror(errno)); free(ctx); } drm_public int drm_intel_get_reset_stats(drm_intel_context *ctx, uint32_t *reset_count, uint32_t *active, uint32_t *pending) { drm_intel_bufmgr_gem *bufmgr_gem; struct drm_i915_reset_stats stats; int ret; if (ctx == NULL) return -EINVAL; memclear(stats); bufmgr_gem = (drm_intel_bufmgr_gem *)ctx->bufmgr; stats.ctx_id = ctx->ctx_id; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GET_RESET_STATS, &stats); if (ret == 0) { if (reset_count != NULL) *reset_count = stats.reset_count; if (active != NULL) *active = stats.batch_active; if (pending != NULL) *pending = stats.batch_pending; } return ret; } drm_public int drm_intel_reg_read(drm_intel_bufmgr *bufmgr, uint32_t offset, uint64_t *result) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *)bufmgr; struct drm_i915_reg_read reg_read; int ret; memclear(reg_read); reg_read.offset = offset; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_REG_READ, &reg_read); *result = reg_read.val; return ret; } drm_public int drm_intel_get_subslice_total(int fd, unsigned int *subslice_total) { drm_i915_getparam_t gp; int ret; memclear(gp); gp.value = (int*)subslice_total; gp.param = I915_PARAM_SUBSLICE_TOTAL; ret = drmIoctl(fd, DRM_IOCTL_I915_GETPARAM, &gp); if (ret) return -errno; return 0; } drm_public int drm_intel_get_eu_total(int fd, unsigned int *eu_total) { drm_i915_getparam_t gp; int ret; memclear(gp); gp.value = (int*)eu_total; gp.param = I915_PARAM_EU_TOTAL; ret = drmIoctl(fd, DRM_IOCTL_I915_GETPARAM, &gp); if (ret) return -errno; return 0; } drm_public int drm_intel_get_pooled_eu(int fd) { drm_i915_getparam_t gp; int ret = -1; memclear(gp); gp.param = I915_PARAM_HAS_POOLED_EU; gp.value = &ret; if (drmIoctl(fd, DRM_IOCTL_I915_GETPARAM, &gp)) return -errno; return ret; } drm_public int drm_intel_get_min_eu_in_pool(int fd) { drm_i915_getparam_t gp; int ret = -1; memclear(gp); gp.param = I915_PARAM_MIN_EU_IN_POOL; gp.value = &ret; if (drmIoctl(fd, DRM_IOCTL_I915_GETPARAM, &gp)) return -errno; return ret; } /** * Annotate the given bo for use in aub dumping. * * \param annotations is an array of drm_intel_aub_annotation objects * describing the type of data in various sections of the bo. Each * element of the array specifies the type and subtype of a section of * the bo, and the past-the-end offset of that section. The elements * of \c annotations must be sorted so that ending_offset is * increasing. * * \param count is the number of elements in the \c annotations array. * If \c count is zero, then \c annotations will not be dereferenced. * * Annotations are copied into a private data structure, so caller may * re-use the memory pointed to by \c annotations after the call * returns. * * Annotations are stored for the lifetime of the bo; to reset to the * default state (no annotations), call this function with a \c count * of zero. */ drm_public void drm_intel_bufmgr_gem_set_aub_annotations(drm_intel_bo *bo, drm_intel_aub_annotation *annotations, unsigned count) { } static pthread_mutex_t bufmgr_list_mutex = PTHREAD_MUTEX_INITIALIZER; static drmMMListHead bufmgr_list = { &bufmgr_list, &bufmgr_list }; static drm_intel_bufmgr_gem * drm_intel_bufmgr_gem_find(int fd) { drm_intel_bufmgr_gem *bufmgr_gem; DRMLISTFOREACHENTRY(bufmgr_gem, &bufmgr_list, managers) { if (bufmgr_gem->fd == fd) { atomic_inc(&bufmgr_gem->refcount); return bufmgr_gem; } } return NULL; } static void drm_intel_bufmgr_gem_unref(drm_intel_bufmgr *bufmgr) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *)bufmgr; if (atomic_add_unless(&bufmgr_gem->refcount, -1, 1)) return; pthread_mutex_lock(&bufmgr_list_mutex); if (atomic_dec_and_test(&bufmgr_gem->refcount)) { DRMLISTDEL(&bufmgr_gem->managers); drm_intel_bufmgr_gem_destroy(bufmgr); } pthread_mutex_unlock(&bufmgr_list_mutex); } drm_public void *drm_intel_gem_bo_map__gtt(drm_intel_bo *bo) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; if (bo_gem->gtt_virtual) return bo_gem->gtt_virtual; if (bo_gem->is_userptr) return NULL; pthread_mutex_lock(&bufmgr_gem->lock); if (bo_gem->gtt_virtual == NULL) { struct drm_i915_gem_mmap_gtt mmap_arg; void *ptr; DBG("bo_map_gtt: mmap %d (%s), map_count=%d\n", bo_gem->gem_handle, bo_gem->name, bo_gem->map_count); if (bo_gem->map_count++ == 0) drm_intel_gem_bo_open_vma(bufmgr_gem, bo_gem); memclear(mmap_arg); mmap_arg.handle = bo_gem->gem_handle; /* Get the fake offset back... */ ptr = MAP_FAILED; if (drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_MMAP_GTT, &mmap_arg) == 0) { /* and mmap it */ ptr = drm_mmap(0, bo->size, PROT_READ | PROT_WRITE, MAP_SHARED, bufmgr_gem->fd, mmap_arg.offset); } if (ptr == MAP_FAILED) { if (--bo_gem->map_count == 0) drm_intel_gem_bo_close_vma(bufmgr_gem, bo_gem); ptr = NULL; } bo_gem->gtt_virtual = ptr; } pthread_mutex_unlock(&bufmgr_gem->lock); return bo_gem->gtt_virtual; } drm_public void *drm_intel_gem_bo_map__cpu(drm_intel_bo *bo) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; if (bo_gem->mem_virtual) return bo_gem->mem_virtual; if (bo_gem->is_userptr) { /* Return the same user ptr */ return bo_gem->user_virtual; } pthread_mutex_lock(&bufmgr_gem->lock); if (!bo_gem->mem_virtual) { struct drm_i915_gem_mmap mmap_arg; if (bo_gem->map_count++ == 0) drm_intel_gem_bo_open_vma(bufmgr_gem, bo_gem); DBG("bo_map: %d (%s), map_count=%d\n", bo_gem->gem_handle, bo_gem->name, bo_gem->map_count); memclear(mmap_arg); mmap_arg.handle = bo_gem->gem_handle; mmap_arg.size = bo->size; if (drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_MMAP, &mmap_arg)) { DBG("%s:%d: Error mapping buffer %d (%s): %s .\n", __FILE__, __LINE__, bo_gem->gem_handle, bo_gem->name, strerror(errno)); if (--bo_gem->map_count == 0) drm_intel_gem_bo_close_vma(bufmgr_gem, bo_gem); } else { VG(VALGRIND_MALLOCLIKE_BLOCK(mmap_arg.addr_ptr, mmap_arg.size, 0, 1)); bo_gem->mem_virtual = (void *)(uintptr_t) mmap_arg.addr_ptr; } } pthread_mutex_unlock(&bufmgr_gem->lock); return bo_gem->mem_virtual; } drm_public void *drm_intel_gem_bo_map__wc(drm_intel_bo *bo) { drm_intel_bufmgr_gem *bufmgr_gem = (drm_intel_bufmgr_gem *) bo->bufmgr; drm_intel_bo_gem *bo_gem = (drm_intel_bo_gem *) bo; if (bo_gem->wc_virtual) return bo_gem->wc_virtual; if (bo_gem->is_userptr) return NULL; pthread_mutex_lock(&bufmgr_gem->lock); if (!bo_gem->wc_virtual) { struct drm_i915_gem_mmap mmap_arg; if (bo_gem->map_count++ == 0) drm_intel_gem_bo_open_vma(bufmgr_gem, bo_gem); DBG("bo_map: %d (%s), map_count=%d\n", bo_gem->gem_handle, bo_gem->name, bo_gem->map_count); memclear(mmap_arg); mmap_arg.handle = bo_gem->gem_handle; mmap_arg.size = bo->size; mmap_arg.flags = I915_MMAP_WC; if (drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_MMAP, &mmap_arg)) { DBG("%s:%d: Error mapping buffer %d (%s): %s .\n", __FILE__, __LINE__, bo_gem->gem_handle, bo_gem->name, strerror(errno)); if (--bo_gem->map_count == 0) drm_intel_gem_bo_close_vma(bufmgr_gem, bo_gem); } else { VG(VALGRIND_MALLOCLIKE_BLOCK(mmap_arg.addr_ptr, mmap_arg.size, 0, 1)); bo_gem->wc_virtual = (void *)(uintptr_t) mmap_arg.addr_ptr; } } pthread_mutex_unlock(&bufmgr_gem->lock); return bo_gem->wc_virtual; } /** * Initializes the GEM buffer manager, which uses the kernel to allocate, map, * and manage map buffer objections. * * \param fd File descriptor of the opened DRM device. */ drm_public drm_intel_bufmgr * drm_intel_bufmgr_gem_init(int fd, int batch_size) { drm_intel_bufmgr_gem *bufmgr_gem; struct drm_i915_gem_get_aperture aperture; drm_i915_getparam_t gp; int ret, tmp; pthread_mutex_lock(&bufmgr_list_mutex); bufmgr_gem = drm_intel_bufmgr_gem_find(fd); if (bufmgr_gem) goto exit; bufmgr_gem = calloc(1, sizeof(*bufmgr_gem)); if (bufmgr_gem == NULL) goto exit; bufmgr_gem->fd = fd; atomic_set(&bufmgr_gem->refcount, 1); if (pthread_mutex_init(&bufmgr_gem->lock, NULL) != 0) { free(bufmgr_gem); bufmgr_gem = NULL; goto exit; } memclear(aperture); ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GEM_GET_APERTURE, &aperture); if (ret == 0) bufmgr_gem->gtt_size = aperture.aper_available_size; else { fprintf(stderr, "DRM_IOCTL_I915_GEM_APERTURE failed: %s\n", strerror(errno)); bufmgr_gem->gtt_size = 128 * 1024 * 1024; fprintf(stderr, "Assuming %dkB available aperture size.\n" "May lead to reduced performance or incorrect " "rendering.\n", (int)bufmgr_gem->gtt_size / 1024); } bufmgr_gem->pci_device = get_pci_device_id(bufmgr_gem); if (IS_GEN2(bufmgr_gem->pci_device)) bufmgr_gem->gen = 2; else if (IS_GEN3(bufmgr_gem->pci_device)) bufmgr_gem->gen = 3; else if (IS_GEN4(bufmgr_gem->pci_device)) bufmgr_gem->gen = 4; else if (IS_GEN5(bufmgr_gem->pci_device)) bufmgr_gem->gen = 5; else if (IS_GEN6(bufmgr_gem->pci_device)) bufmgr_gem->gen = 6; else if (IS_GEN7(bufmgr_gem->pci_device)) bufmgr_gem->gen = 7; else if (IS_GEN8(bufmgr_gem->pci_device)) bufmgr_gem->gen = 8; else if (!intel_get_genx(bufmgr_gem->pci_device, &bufmgr_gem->gen)) { free(bufmgr_gem); bufmgr_gem = NULL; goto exit; } if (IS_GEN3(bufmgr_gem->pci_device) && bufmgr_gem->gtt_size > 256*1024*1024) { /* The unmappable part of gtt on gen 3 (i.e. above 256MB) can't * be used for tiled blits. To simplify the accounting, just * subtract the unmappable part (fixed to 256MB on all known * gen3 devices) if the kernel advertises it. */ bufmgr_gem->gtt_size -= 256*1024*1024; } memclear(gp); gp.value = &tmp; gp.param = I915_PARAM_HAS_EXECBUF2; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GETPARAM, &gp); if (ret) { fprintf(stderr, "i915 does not support EXECBUFER2\n"); free(bufmgr_gem); bufmgr_gem = NULL; goto exit; } gp.param = I915_PARAM_HAS_BSD; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GETPARAM, &gp); bufmgr_gem->has_bsd = ret == 0; gp.param = I915_PARAM_HAS_BLT; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GETPARAM, &gp); bufmgr_gem->has_blt = ret == 0; gp.param = I915_PARAM_HAS_RELAXED_FENCING; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GETPARAM, &gp); bufmgr_gem->has_relaxed_fencing = ret == 0; gp.param = I915_PARAM_HAS_EXEC_ASYNC; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GETPARAM, &gp); bufmgr_gem->has_exec_async = ret == 0; bufmgr_gem->bufmgr.bo_alloc_userptr = check_bo_alloc_userptr; gp.param = I915_PARAM_HAS_WAIT_TIMEOUT; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GETPARAM, &gp); bufmgr_gem->has_wait_timeout = ret == 0; gp.param = I915_PARAM_HAS_LLC; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GETPARAM, &gp); if (ret != 0) { /* Kernel does not supports HAS_LLC query, fallback to GPU * generation detection and assume that we have LLC on GEN6/7 */ bufmgr_gem->has_llc = (IS_GEN6(bufmgr_gem->pci_device) | IS_GEN7(bufmgr_gem->pci_device)); } else bufmgr_gem->has_llc = *gp.value; gp.param = I915_PARAM_HAS_VEBOX; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GETPARAM, &gp); bufmgr_gem->has_vebox = (ret == 0) & (*gp.value > 0); gp.param = I915_PARAM_HAS_EXEC_SOFTPIN; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GETPARAM, &gp); if (ret == 0 && *gp.value > 0) bufmgr_gem->bufmgr.bo_set_softpin_offset = drm_intel_gem_bo_set_softpin_offset; if (bufmgr_gem->gen < 4) { gp.param = I915_PARAM_NUM_FENCES_AVAIL; gp.value = &bufmgr_gem->available_fences; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GETPARAM, &gp); if (ret) { fprintf(stderr, "get fences failed: %d [%d]\n", ret, errno); fprintf(stderr, "param: %d, val: %d\n", gp.param, *gp.value); bufmgr_gem->available_fences = 0; } else { /* XXX The kernel reports the total number of fences, * including any that may be pinned. * * We presume that there will be at least one pinned * fence for the scanout buffer, but there may be more * than one scanout and the user may be manually * pinning buffers. Let's move to execbuffer2 and * thereby forget the insanity of using fences... */ bufmgr_gem->available_fences -= 2; if (bufmgr_gem->available_fences < 0) bufmgr_gem->available_fences = 0; } } if (bufmgr_gem->gen >= 8) { gp.param = I915_PARAM_HAS_ALIASING_PPGTT; ret = drmIoctl(bufmgr_gem->fd, DRM_IOCTL_I915_GETPARAM, &gp); if (ret == 0 && *gp.value == 3) bufmgr_gem->bufmgr.bo_use_48b_address_range = drm_intel_gem_bo_use_48b_address_range; } /* Let's go with one relocation per every 2 dwords (but round down a bit * since a power of two will mean an extra page allocation for the reloc * buffer). * * Every 4 was too few for the blender benchmark. */ bufmgr_gem->max_relocs = batch_size / sizeof(uint32_t) / 2 - 2; bufmgr_gem->bufmgr.bo_alloc = drm_intel_gem_bo_alloc; bufmgr_gem->bufmgr.bo_alloc_for_render = drm_intel_gem_bo_alloc_for_render; bufmgr_gem->bufmgr.bo_alloc_tiled = drm_intel_gem_bo_alloc_tiled; bufmgr_gem->bufmgr.bo_reference = drm_intel_gem_bo_reference; bufmgr_gem->bufmgr.bo_unreference = drm_intel_gem_bo_unreference; bufmgr_gem->bufmgr.bo_map = drm_intel_gem_bo_map; bufmgr_gem->bufmgr.bo_unmap = drm_intel_gem_bo_unmap; bufmgr_gem->bufmgr.bo_subdata = drm_intel_gem_bo_subdata; bufmgr_gem->bufmgr.bo_get_subdata = drm_intel_gem_bo_get_subdata; bufmgr_gem->bufmgr.bo_wait_rendering = drm_intel_gem_bo_wait_rendering; bufmgr_gem->bufmgr.bo_emit_reloc = drm_intel_gem_bo_emit_reloc; bufmgr_gem->bufmgr.bo_emit_reloc_fence = drm_intel_gem_bo_emit_reloc_fence; bufmgr_gem->bufmgr.bo_pin = drm_intel_gem_bo_pin; bufmgr_gem->bufmgr.bo_unpin = drm_intel_gem_bo_unpin; bufmgr_gem->bufmgr.bo_get_tiling = drm_intel_gem_bo_get_tiling; bufmgr_gem->bufmgr.bo_set_tiling = drm_intel_gem_bo_set_tiling; bufmgr_gem->bufmgr.bo_flink = drm_intel_gem_bo_flink; bufmgr_gem->bufmgr.bo_exec = drm_intel_gem_bo_exec2; bufmgr_gem->bufmgr.bo_mrb_exec = drm_intel_gem_bo_mrb_exec2; bufmgr_gem->bufmgr.bo_busy = drm_intel_gem_bo_busy; bufmgr_gem->bufmgr.bo_madvise = drm_intel_gem_bo_madvise; bufmgr_gem->bufmgr.destroy = drm_intel_bufmgr_gem_unref; bufmgr_gem->bufmgr.debug = 0; bufmgr_gem->bufmgr.check_aperture_space = drm_intel_gem_check_aperture_space; bufmgr_gem->bufmgr.bo_disable_reuse = drm_intel_gem_bo_disable_reuse; bufmgr_gem->bufmgr.bo_is_reusable = drm_intel_gem_bo_is_reusable; bufmgr_gem->bufmgr.get_pipe_from_crtc_id = drm_intel_gem_get_pipe_from_crtc_id; bufmgr_gem->bufmgr.bo_references = drm_intel_gem_bo_references; init_cache_buckets(bufmgr_gem); DRMINITLISTHEAD(&bufmgr_gem->vma_cache); bufmgr_gem->vma_max = -1; /* unlimited by default */ DRMLISTADD(&bufmgr_gem->managers, &bufmgr_list); exit: pthread_mutex_unlock(&bufmgr_list_mutex); return bufmgr_gem != NULL ? &bufmgr_gem->bufmgr : NULL; }
14bd6fab2c5e0df34e850e1031264798c287cda6
19cf5c5a22fad2e5a3ae222134f4a30812ffbbf7
/src/golf/golf.h
f42f03ff29e0350442f713001097d09bcf35b06a
[ "MIT" ]
permissive
mgerdes/Open-Golf
6805e5a8b0378167259869e0087913ef0f77e94c
b9029f1e80c3110ae3d4fc9300854bdaeef96508
refs/heads/master
2023-08-20T13:58:13.657077
2022-03-25T13:55:33
2022-03-25T13:55:33
298,134,035
1,319
68
MIT
2022-07-21T22:26:46
2020-09-24T01:09:14
C
UTF-8
C
false
false
840
h
golf.h
#ifndef _GOLF_GOLF_H #define _GOLF_GOLF_H #include "common/data.h" #include "common/file.h" #include "common/level.h" typedef enum golf_state { GOLF_STATE_TITLE_SCREEN, GOLF_STATE_MAIN_MENU, GOLF_STATE_LOADING_LEVEL, GOLF_STATE_IN_GAME, } golf_state_t; typedef struct golf { golf_state_t state; union { struct { float t; } title_screen; struct { float t; } main_menu; struct { float t; } loading_level; struct { float t; } in_game; }; int level_num; char level_loading_path[GOLF_FILE_MAX_PATH]; golf_level_t *level; } golf_t; void golf_init(void); void golf_update(float dt); golf_t *golf_get(void); void golf_start_level(int level_num); void golf_goto_main_menu(void); #endif
456a822353348163c0d93c04793a04dca1cbdabf
ae5e2ee11aa213d50515dab995380ff18f1031e9
/GleeBug/ntdll.h
5064065bf836afac732c4f7db6baf8d8ac3c475c
[ "MIT" ]
permissive
x64dbg/GleeBug
21f9475d02c4701d8402ea4280c0da8aff35701c
37b6606d5892f8e9a3dead97aa6e45e2a9b072ff
refs/heads/vs2015
2023-07-26T20:40:12.373298
2023-07-08T12:37:23
2023-07-08T12:37:23
48,104,657
1,100
39
MIT
2022-07-20T19:49:19
2015-12-16T10:49:32
C
UTF-8
C
false
false
237,583
h
ntdll.h
#ifndef _NTDLL_H #define _NTDLL_H #pragma once #ifdef __cplusplus extern "C" { #endif #ifndef WIN32_NO_STATUS #define WIN32_NO_STATUS #endif #include <Windows.h> #undef WIN32_NO_STATUS #include <ntstatus.h> #include <intrin.h> #define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0) #define NT_ERROR(Status) ((((ULONG)(Status)) >> 30) == 3) #define FASTCALL __fastcall #ifndef _Reserved_ #define _Reserved_ #endif #define ALIGN_DOWN(length, type) \ ((ULONG)(length) & ~(sizeof(type) - 1)) #define ALIGN_UP(length, type) \ (ALIGN_DOWN(((ULONG)(length) + sizeof(type) - 1), type)) #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #define MAX(a,b) (((a) > (b)) ? (a) : (b)) typedef LONG NTSTATUS, *PNTSTATUS; typedef LONG KPRIORITY, *PKPRIORITY; typedef ULONG LOGICAL, *PLOGICAL; typedef struct _CLIENT_ID { HANDLE UniqueProcess; HANDLE UniqueThread; } CLIENT_ID, *PCLIENT_ID; enum KPROCESSOR_MODE { KernelMode, UserMode }; typedef enum _KTHREAD_STATE { Initialized, Ready, Running, Standby, Terminated, Waiting, Transition, DeferredReady, GateWaitObsolete, WaitingForProcessInSwap, MaximumThreadState } KTHREAD_STATE, *PKTHREAD_STATE; typedef enum _KWAIT_REASON { Executive, FreePage, PageIn, PoolAllocation, DelayExecution, Suspended, UserRequest, WrExecutive, WrFreePage, WrPageIn, WrPoolAllocation, WrDelayExecution, WrSuspended, WrUserRequest, WrEventPair, WrQueue, WrLpcReceive, WrLpcReply, WrVirtualMemory, WrPageOut, WrRendezvous, WrKeyedEvent, WrTerminated, WrProcessInSwap, WrCpuRateControl, WrCalloutStack, WrKernel, WrResource, WrPushLock, WrMutex, WrQuantumEnd, WrDispatchInt, WrPreempted, WrYieldExecution, WrFastMutex, WrGuardedMutex, WrRundown, WrAlertByThreadId, WrDeferredPreempt, MaximumWaitReason } KWAIT_REASON; typedef enum _EVENT_TYPE { NotificationEvent, SynchronizationEvent } EVENT_TYPE; typedef enum _TIMER_TYPE { NotificationTimer, SynchronizationTimer } TIMER_TYPE; typedef enum _WAIT_TYPE { WaitAll, WaitAny, WaitNotification, WaitDequeue } WAIT_TYPE; typedef enum _SECTION_INHERIT { ViewShare = 1, ViewUnmap = 2 } SECTION_INHERIT; #define HARDERROR_OVERRIDE_ERRORMODE 0x10000000 typedef enum _HARDERROR_RESPONSE_OPTION { OptionAbortRetryIgnore, OptionOk, OptionOkCancel, OptionRetryCancel, OptionYesNo, OptionYesNoCancel, OptionShutdownSystem, OptionOkNoWait, OptionCancelTryContinue } HARDERROR_RESPONSE_OPTION, *PHARDERROR_RESPONSE_OPTION; typedef enum _HARDERROR_RESPONSE { ResponseReturnToCaller, ResponseNotHandled, ResponseAbort, ResponseCancel, ResponseIgnore, ResponseNo, ResponseOk, ResponseRetry, ResponseYes, ResponseTryAgain, ResponseContinue } HARDERROR_RESPONSE, *PHARDERROR_RESPONSE; typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING, *PUNICODE_STRING; typedef const UNICODE_STRING* PCUNICODE_STRING; #define DECLARE_UNICODE_STRING_SIZE(_var, _size) \ WCHAR _var ## _buffer[_size]; \ __pragma(warning(push)) \ __pragma(warning(disable:4221)) __pragma(warning(disable:4204)) \ UNICODE_STRING _var = { 0, (_size) * sizeof(WCHAR) , _var ## _buffer } \ __pragma(warning(pop)) #define DECLARE_STATIC_UNICODE_STRING_SIZE(_var, _size) \ WCHAR _var ## _buffer[_size]; \ __pragma(warning(push)) \ __pragma(warning(disable:4221)) __pragma(warning(disable:4204)) \ static UNICODE_STRING _var = { 0, (_size) * sizeof(WCHAR) , _var ## _buffer } \ __pragma(warning(pop)) #if defined(__clang__) #define RTL_CONSTANT_STRING(s) \ __pragma(clang diagnostic push) \ __pragma(clang diagnostic ignored "-Wwritable-strings") \ { sizeof(s) - sizeof((s)[0]), sizeof(s), s } \ __pragma(clang diagnostic pop) #else #define RTL_CONSTANT_STRING(s) { sizeof(s) - sizeof((s)[0]), sizeof(s), (PWSTR)s } #define RTL_CONSTANT_ANSI_STRING(s) { sizeof(s) - sizeof((s)[0]), sizeof(s), (PSTR)s } #endif FORCEINLINE VOID RtlInitEmptyUnicodeString( _Out_ PUNICODE_STRING UnicodeString, _In_ PWCHAR Buffer, _In_ USHORT BufferSize) { UnicodeString->Length = 0; UnicodeString->MaximumLength = BufferSize; UnicodeString->Buffer = Buffer; } typedef struct _STRING { USHORT Length; USHORT MaximumLength; PCHAR Buffer; } ANSI_STRING, *PANSI_STRING; typedef struct _SYSTEM_SESSION_PROCESS_INFORMATION { ULONG SessionId; ULONG SizeOfBuf; PVOID Buffer; } SYSTEM_SESSION_PROCESS_INFORMATION, *PSYSTEM_SESSION_PROCESS_INFORMATION; typedef struct _SYSTEM_KERNEL_DEBUGGER_INFORMATION { BOOLEAN KernelDebuggerEnabled; BOOLEAN KernelDebuggerNotPresent; } SYSTEM_KERNEL_DEBUGGER_INFORMATION, *PSYSTEM_KERNEL_DEBUGGER_INFORMATION; typedef struct _SYSTEM_KERNEL_DEBUGGER_INFORMATION_EX { BOOLEAN DebuggerAllowed; BOOLEAN DebuggerEnabled; BOOLEAN DebuggerPresent; } SYSTEM_KERNEL_DEBUGGER_INFORMATION_EX, *PSYSTEM_KERNEL_DEBUGGER_INFORMATION_EX; typedef struct _LDT_INFORMATION { ULONG Start; ULONG Length; LDT_ENTRY LdtEntries[1]; } PROCESS_LDT_INFORMATION, *PPROCESS_LDT_INFORMATION; typedef struct _KERNEL_USER_TIMES { LARGE_INTEGER CreateTime; LARGE_INTEGER ExitTime; LARGE_INTEGER KernelTime; LARGE_INTEGER UserTime; } KERNEL_USER_TIMES, *PKERNEL_USER_TIMES; typedef struct _SYSTEM_THREAD_INFORMATION { LARGE_INTEGER KernelTime; LARGE_INTEGER UserTime; LARGE_INTEGER CreateTime; ULONG WaitTime; PVOID StartAddress; CLIENT_ID ClientId; KPRIORITY Priority; LONG BasePriority; ULONG ContextSwitches; ULONG ThreadState; KWAIT_REASON WaitReason; } SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION; typedef struct _SYSTEM_PROCESS_INFORMATION { ULONG NextEntryOffset; ULONG NumberOfThreads; LARGE_INTEGER WorkingSetPrivateSize; // Since Vista ULONG HardFaultCount; // Since Windows 7 ULONG NumberOfThreadsHighWatermark; // Since Windows 7 ULONGLONG CycleTime; // Since Windows 7 LARGE_INTEGER CreateTime; LARGE_INTEGER UserTime; LARGE_INTEGER KernelTime; UNICODE_STRING ImageName; KPRIORITY BasePriority; HANDLE UniqueProcessId; HANDLE InheritedFromUniqueProcessId; ULONG HandleCount; ULONG SessionId; ULONG_PTR UniqueProcessKey; // Since Vista (requires SystemExtendedProcessInformation) SIZE_T PeakVirtualSize; SIZE_T VirtualSize; ULONG PageFaultCount; SIZE_T PeakWorkingSetSize; SIZE_T WorkingSetSize; SIZE_T QuotaPeakPagedPoolUsage; SIZE_T QuotaPagedPoolUsage; SIZE_T QuotaPeakNonPagedPoolUsage; SIZE_T QuotaNonPagedPoolUsage; SIZE_T PagefileUsage; SIZE_T PeakPagefileUsage; SIZE_T PrivatePageCount; LARGE_INTEGER ReadOperationCount; LARGE_INTEGER WriteOperationCount; LARGE_INTEGER OtherOperationCount; LARGE_INTEGER ReadTransferCount; LARGE_INTEGER WriteTransferCount; LARGE_INTEGER OtherTransferCount; SYSTEM_THREAD_INFORMATION Threads[1]; } SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION; typedef struct _PROCESS_SESSION_INFORMATION { ULONG SessionId; } PROCESS_SESSION_INFORMATION, *PPROCESS_SESSION_INFORMATION; // File attribute values #define FILE_ATTRIBUTE_READONLY 0x00000001 #define FILE_ATTRIBUTE_HIDDEN 0x00000002 #define FILE_ATTRIBUTE_SYSTEM 0x00000004 #define FILE_ATTRIBUTE_DIRECTORY 0x00000010 #define FILE_ATTRIBUTE_ARCHIVE 0x00000020 #define FILE_ATTRIBUTE_DEVICE 0x00000040 #define FILE_ATTRIBUTE_NORMAL 0x00000080 #define FILE_ATTRIBUTE_TEMPORARY 0x00000100 #define FILE_ATTRIBUTE_SPARSE_FILE 0x00000200 #define FILE_ATTRIBUTE_REPARSE_POINT 0x00000400 #define FILE_ATTRIBUTE_COMPRESSED 0x00000800 #define FILE_ATTRIBUTE_OFFLINE 0x00001000 #define FILE_ATTRIBUTE_NOT_CONTENT_INDEXED 0x00002000 #define FILE_ATTRIBUTE_ENCRYPTED 0x00004000 #define FILE_ATTRIBUTE_INTEGRITY_STREAM 0x00008000 #define FILE_ATTRIBUTE_VIRTUAL 0x00010000 #define FILE_ATTRIBUTE_NO_SCRUB_DATA 0x00020000 #define FILE_ATTRIBUTE_EA 0x00040000 #define FILE_ATTRIBUTE_PINNED 0x00080000 #define FILE_ATTRIBUTE_UNPINNED 0x00100000 #define FILE_ATTRIBUTE_RECALL_ON_OPEN 0x00040000 #define FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS 0x00400000 #if NTDDI_VERSION < NTDDI_WIN8 #define FILE_ATTRIBUTE_VALID_FLAGS 0x00007fb7 #define FILE_ATTRIBUTE_VALID_SET_FLAGS 0x000031a7 #elif NTDDI_VERSION < NTDDI_WIN10_RS2 #define FILE_ATTRIBUTE_VALID_FLAGS 0x0002ffb7 #define FILE_ATTRIBUTE_VALID_SET_FLAGS 0x000231a7 #else #define FILE_ATTRIBUTE_VALID_FLAGS 0x005affb7 #define FILE_ATTRIBUTE_VALID_SET_FLAGS 0x001a31a7 #endif // File create disposition values #define FILE_SUPERSEDE 0x00000000 #define FILE_OPEN 0x00000001 #define FILE_CREATE 0x00000002 #define FILE_OPEN_IF 0x00000003 #define FILE_OVERWRITE 0x00000004 #define FILE_OVERWRITE_IF 0x00000005 #define FILE_MAXIMUM_DISPOSITION 0x00000005 // File create/open option flags #define FILE_DIRECTORY_FILE 0x00000001 #define FILE_WRITE_THROUGH 0x00000002 #define FILE_SEQUENTIAL_ONLY 0x00000004 #define FILE_NO_INTERMEDIATE_BUFFERING 0x00000008 #define FILE_SYNCHRONOUS_IO_ALERT 0x00000010 #define FILE_SYNCHRONOUS_IO_NONALERT 0x00000020 #define FILE_NON_DIRECTORY_FILE 0x00000040 #define FILE_CREATE_TREE_CONNECTION 0x00000080 #define FILE_COMPLETE_IF_OPLOCKED 0x00000100 #define FILE_NO_EA_KNOWLEDGE 0x00000200 #define FILE_OPEN_FOR_RECOVERY 0x00000400 #define FILE_RANDOM_ACCESS 0x00000800 #define FILE_DELETE_ON_CLOSE 0x00001000 #define FILE_OPEN_BY_FILE_ID 0x00002000 #define FILE_OPEN_FOR_BACKUP_INTENT 0x00004000 #define FILE_NO_COMPRESSION 0x00008000 #if NTDDI_VERSION >= NTDDI_WIN7 #define FILE_OPEN_REQUIRING_OPLOCK 0x00010000 #define FILE_DISALLOW_EXCLUSIVE 0x00020000 #endif #if NTDDI_VERSION >= NTDDI_WIN8 #define FILE_SESSION_AWARE 0x00040000 #endif #define FILE_RESERVE_OPFILTER 0x00100000 #define FILE_OPEN_REPARSE_POINT 0x00200000 #define FILE_OPEN_NO_RECALL 0x00400000 #define FILE_OPEN_FOR_FREE_SPACE_QUERY 0x00800000 #define FILE_VALID_OPTION_FLAGS 0x00ffffff #define FILE_VALID_PIPE_OPTION_FLAGS 0x00000032 #define FILE_VALID_MAILSLOT_OPTION_FLAGS 0x00000032 #define FILE_VALID_SET_FLAGS 0x00000036 // Named pipe type flags #define FILE_PIPE_BYTE_STREAM_TYPE 0x00000000 #define FILE_PIPE_MESSAGE_TYPE 0x00000001 #define FILE_PIPE_ACCEPT_REMOTE_CLIENTS 0x00000000 #define FILE_PIPE_REJECT_REMOTE_CLIENTS 0x00000002 #define FILE_PIPE_TYPE_VALID_MASK 0x00000003 // Named pipe completion mode flags #define FILE_PIPE_QUEUE_OPERATION 0x00000000 #define FILE_PIPE_COMPLETE_OPERATION 0x00000001 // Named pipe read mode flags #define FILE_PIPE_BYTE_STREAM_MODE 0x00000000 #define FILE_PIPE_MESSAGE_MODE 0x00000001 // NamedPipeConfiguration flags #define FILE_PIPE_INBOUND 0x00000000 #define FILE_PIPE_OUTBOUND 0x00000001 #define FILE_PIPE_FULL_DUPLEX 0x00000002 // NamedPipeState flags #define FILE_PIPE_DISCONNECTED_STATE 0x00000001 #define FILE_PIPE_LISTENING_STATE 0x00000002 #define FILE_PIPE_CONNECTED_STATE 0x00000003 #define FILE_PIPE_CLOSING_STATE 0x00000004 // NamedPipeEnd flags #define FILE_PIPE_CLIENT_END 0x00000000 #define FILE_PIPE_SERVER_END 0x00000001 typedef struct _FILE_BASIC_INFORMATION { LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; ULONG FileAttributes; } FILE_BASIC_INFORMATION, *PFILE_BASIC_INFORMATION; typedef struct _FILE_STANDARD_INFORMATION { LARGE_INTEGER AllocationSize; LARGE_INTEGER EndOfFile; ULONG NumberOfLinks; BOOLEAN DeletePending; BOOLEAN Directory; } FILE_STANDARD_INFORMATION, *PFILE_STANDARD_INFORMATION; typedef struct _FILE_POSITION_INFORMATION { LARGE_INTEGER CurrentByteOffset; } FILE_POSITION_INFORMATION, *PFILE_POSITION_INFORMATION; typedef struct _THREAD_BASIC_INFORMATION { NTSTATUS ExitStatus; PVOID TebBaseAddress; CLIENT_ID ClientId; ULONG_PTR AffinityMask; KPRIORITY Priority; LONG BasePriority; } THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION; typedef struct _MEMORY_REGION_INFORMATION { PVOID AllocationBase; ULONG AllocationProtect; union { ULONG RegionType; struct { ULONG Private : 1; ULONG MappedDataFile : 1; ULONG MappedImage : 1; ULONG MappedPageFile : 1; ULONG MappedPhysical : 1; ULONG DirectMapped : 1; ULONG Reserved : 26; } s; } u; SIZE_T RegionSize; SIZE_T CommitSize; } MEMORY_REGION_INFORMATION, *PMEMORY_REGION_INFORMATION; typedef struct _SECTION_BASIC_INFORMATION { PVOID BaseAddress; ULONG AllocationAttributes; LARGE_INTEGER MaximumSize; } SECTION_BASIC_INFORMATION, *PSECTION_BASIC_INFORMATION; typedef struct _SECTION_IMAGE_INFORMATION { PVOID TransferAddress; // Entry point ULONG ZeroBits; SIZE_T MaximumStackSize; SIZE_T CommittedStackSize; ULONG SubSystemType; union { struct { USHORT SubSystemMinorVersion; USHORT SubSystemMajorVersion; } s1; ULONG SubSystemVersion; } u1; union { struct { USHORT MajorOperatingSystemVersion; USHORT MinorOperatingSystemVersion; } s2; ULONG OperatingSystemVersion; } u2; USHORT ImageCharacteristics; USHORT DllCharacteristics; USHORT Machine; BOOLEAN ImageContainsCode; union { UCHAR ImageFlags; struct { UCHAR ComPlusNativeReady : 1; UCHAR ComPlusILOnly : 1; UCHAR ImageDynamicallyRelocated : 1; UCHAR ImageMappedFlat : 1; UCHAR BaseBelow4gb : 1; UCHAR ComPlusPrefer32bit : 1; UCHAR Reserved : 2; } s3; } u3; ULONG LoaderFlags; ULONG ImageFileSize; ULONG CheckSum; } SECTION_IMAGE_INFORMATION, *PSECTION_IMAGE_INFORMATION; typedef struct _SECTION_INTERNAL_IMAGE_INFORMATION { SECTION_IMAGE_INFORMATION SectionInformation; union { ULONG ExtendedFlags; struct { ULONG ImageReturnFlowGuardEnabled : 1; ULONG ImageReturnFlowGuardStrict : 1; ULONG ImageExportSuppressionEnabled : 1; ULONG Reserved : 29; } s; } u; } SECTION_INTERNAL_IMAGE_INFORMATION, *PSECTION_INTERNAL_IMAGE_INFORMATION; typedef struct _OBJECT_ATTRIBUTES { ULONG Length; HANDLE RootDirectory; PUNICODE_STRING ObjectName; ULONG Attributes; PVOID SecurityDescriptor; PVOID SecurityQualityOfService; } OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES; // https://stackoverflow.com/questions/36961152/detect-windows-kit-8-0-and-windows-kit-8-1-sdks #if defined(WINAPI_PARTITION_APP) #if defined(WINAPI_FAMILY_SYSTEM) #define USING_WINDOWS_10_SDK #elif (WINAPI_PARTITION_APP == 0x00000002) || (WINAPI_PARTITION_APP == 1) #define USING_WINDOWS_8_x_SDK #endif #endif // This struct was included in winnt.h starting in the Windows 8.0 SDK #if !(defined(USING_WINDOWS_8_x_SDK) || defined(USING_WINDOWS_10_SDK)) typedef struct _EXCEPTION_REGISTRATION_RECORD { _EXCEPTION_REGISTRATION_RECORD* Next; _EXCEPTION_DISPOSITION Handler; } EXCEPTION_REGISTRATION_RECORD, *PEXCEPTION_REGISTRATION_RECORD; #endif #define LDR_GET_DLL_HANDLE_EX_UNCHANGED_REFCOUNT 0x00000001 #define LDR_GET_DLL_HANDLE_EX_PIN 0x00000002 #define LDR_GET_PROCEDURE_ADDRESS_EX_DONT_RECORD_FORWARDER 0x00000001 #define LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS 0x00000001 #define LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY 0x00000002 #define LDR_LOCK_LOADER_LOCK_DISPOSITION_INVALID 0 #define LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED 1 #define LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_NOT_ACQUIRED 2 #define LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS 0x00000001 typedef struct _LDR_RESOURCE_INFO { ULONG_PTR Type; ULONG_PTR Name; ULONG_PTR Language; } LDR_RESOURCE_INFO, *PLDR_RESOURCE_INFO; typedef struct _LDR_ENUM_RESOURCE_INFO { ULONG_PTR Type; ULONG_PTR Name; ULONG_PTR Language; PVOID Data; SIZE_T Size; ULONG_PTR Reserved; } LDR_ENUM_RESOURCE_INFO, *PLDR_ENUM_RESOURCE_INFO; #define LDR_FIND_RESOURCE_LANGUAGE_CAN_FALLBACK 0x00000000 #define LDR_FIND_RESOURCE_LANGUAGE_EXACT 0x00000004 #define LDR_FIND_RESOURCE_LANGUAGE_REDIRECT_VERSION 0x00000008 typedef struct _RTL_PROCESS_MODULE_INFORMATION { HANDLE Section; PVOID MappedBase; PVOID ImageBase; ULONG ImageSize; ULONG Flags; USHORT LoadOrderIndex; USHORT InitOrderIndex; USHORT LoadCount; USHORT OffsetToFileName; UCHAR FullPathName[256]; } RTL_PROCESS_MODULE_INFORMATION, *PRTL_PROCESS_MODULE_INFORMATION; typedef struct _RTL_PROCESS_MODULES { ULONG NumberOfModules; RTL_PROCESS_MODULE_INFORMATION Modules[1]; } RTL_PROCESS_MODULES, *PRTL_PROCESS_MODULES; typedef struct _RTL_PROCESS_MODULE_INFORMATION_EX { USHORT NextOffset; RTL_PROCESS_MODULE_INFORMATION BaseInfo; ULONG ImageChecksum; ULONG TimeDateStamp; PVOID DefaultBase; } RTL_PROCESS_MODULE_INFORMATION_EX, *PRTL_PROCESS_MODULE_INFORMATION_EX; typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO { USHORT UniqueProcessId; USHORT CreatorBackTraceIndex; UCHAR ObjectTypeIndex; UCHAR HandleAttributes; USHORT HandleValue; PVOID Object; ULONG GrantedAccess; } SYSTEM_HANDLE_TABLE_ENTRY_INFO, *PSYSTEM_HANDLE_TABLE_ENTRY_INFO; typedef struct _SYSTEM_HANDLE_INFORMATION { ULONG NumberOfHandles; SYSTEM_HANDLE_TABLE_ENTRY_INFO Handles[1]; } SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION; typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX { PVOID Object; ULONG_PTR UniqueProcessId; ULONG_PTR HandleValue; ULONG GrantedAccess; USHORT CreatorBackTraceIndex; USHORT ObjectTypeIndex; ULONG HandleAttributes; ULONG Reserved; } SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX, *PSYSTEM_HANDLE_TABLE_ENTRY_INFO_EX; typedef struct _SYSTEM_HANDLE_INFORMATION_EX { ULONG_PTR NumberOfHandles; ULONG_PTR Reserved; SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles[1]; } SYSTEM_HANDLE_INFORMATION_EX, *PSYSTEM_HANDLE_INFORMATION_EX; typedef struct _OBJECT_BASIC_INFORMATION { ULONG Attributes; ACCESS_MASK GrantedAccess; ULONG HandleCount; ULONG PointerCount; ULONG PagedPoolCharge; ULONG NonPagedPoolCharge; ULONG Reserved[ 3 ]; ULONG NameInfoSize; ULONG TypeInfoSize; ULONG SecurityDescriptorSize; LARGE_INTEGER CreationTime; } OBJECT_BASIC_INFORMATION, *POBJECT_BASIC_INFORMATION; typedef struct _OBJECT_NAME_INFORMATION { UNICODE_STRING Name; } OBJECT_NAME_INFORMATION, *POBJECT_NAME_INFORMATION; typedef struct _OBJECT_TYPE_INFORMATION { UNICODE_STRING TypeName; ULONG TotalNumberOfObjects; ULONG TotalNumberOfHandles; ULONG TotalPagedPoolUsage; ULONG TotalNonPagedPoolUsage; ULONG TotalNamePoolUsage; ULONG TotalHandleTableUsage; ULONG HighWaterNumberOfObjects; ULONG HighWaterNumberOfHandles; ULONG HighWaterPagedPoolUsage; ULONG HighWaterNonPagedPoolUsage; ULONG HighWaterNamePoolUsage; ULONG HighWaterHandleTableUsage; ULONG InvalidAttributes; GENERIC_MAPPING GenericMapping; ULONG ValidAccessMask; BOOLEAN SecurityRequired; BOOLEAN MaintainHandleCount; UCHAR TypeIndex; // Since Windows 8.1 CHAR ReservedByte; ULONG PoolType; ULONG DefaultPagedPoolCharge; ULONG DefaultNonPagedPoolCharge; } OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION; typedef struct _OBJECT_TYPES_INFORMATION { ULONG NumberOfTypes; OBJECT_TYPE_INFORMATION TypeInformation[1]; } OBJECT_TYPES_INFORMATION, *POBJECT_TYPES_INFORMATION; typedef struct _OBJECT_HANDLE_FLAG_INFORMATION { BOOLEAN Inherit; BOOLEAN ProtectFromClose; } OBJECT_HANDLE_FLAG_INFORMATION, *POBJECT_HANDLE_FLAG_INFORMATION; typedef struct _DBGKM_EXCEPTION { EXCEPTION_RECORD ExceptionRecord; ULONG FirstChance; } DBGKM_EXCEPTION, *PDBGKM_EXCEPTION; typedef struct _DBGKM_CREATE_THREAD { ULONG SubSystemKey; PVOID StartAddress; } DBGKM_CREATE_THREAD, *PDBGKM_CREATE_THREAD; typedef struct _DBGKM_CREATE_PROCESS { ULONG SubSystemKey; HANDLE FileHandle; PVOID BaseOfImage; ULONG DebugInfoFileOffset; ULONG DebugInfoSize; DBGKM_CREATE_THREAD InitialThread; } DBGKM_CREATE_PROCESS, *PDBGKM_CREATE_PROCESS; typedef struct _DBGKM_EXIT_THREAD { NTSTATUS ExitStatus; } DBGKM_EXIT_THREAD, *PDBGKM_EXIT_THREAD; typedef struct _DBGKM_EXIT_PROCESS { NTSTATUS ExitStatus; } DBGKM_EXIT_PROCESS, *PDBGKM_EXIT_PROCESS; typedef struct _DBGKM_LOAD_DLL { HANDLE FileHandle; PVOID BaseOfDll; ULONG DebugInfoFileOffset; ULONG DebugInfoSize; PVOID NamePointer; } DBGKM_LOAD_DLL, *PDBGKM_LOAD_DLL; typedef struct _DBGKM_UNLOAD_DLL { PVOID BaseAddress; } DBGKM_UNLOAD_DLL, *PDBGKM_UNLOAD_DLL; typedef enum _DBG_STATE { DbgIdle, DbgReplyPending, DbgCreateThreadStateChange, DbgCreateProcessStateChange, DbgExitThreadStateChange, DbgExitProcessStateChange, DbgExceptionStateChange, DbgBreakpointStateChange, DbgSingleStepStateChange, DbgLoadDllStateChange, DbgUnloadDllStateChange } DBG_STATE, *PDBG_STATE; typedef struct _DBGUI_CREATE_THREAD { HANDLE HandleToThread; DBGKM_CREATE_THREAD NewThread; } DBGUI_CREATE_THREAD, *PDBGUI_CREATE_THREAD; typedef struct _DBGUI_CREATE_PROCESS { HANDLE HandleToProcess; HANDLE HandleToThread; DBGKM_CREATE_PROCESS NewProcess; } DBGUI_CREATE_PROCESS, *PDBGUI_CREATE_PROCESS; typedef struct _DBGUI_WAIT_STATE_CHANGE { DBG_STATE NewState; CLIENT_ID AppClientId; union { DBGKM_EXCEPTION Exception; DBGUI_CREATE_THREAD CreateThread; DBGUI_CREATE_PROCESS CreateProcessInfo; DBGKM_EXIT_THREAD ExitThread; DBGKM_EXIT_PROCESS ExitProcess; DBGKM_LOAD_DLL LoadDll; DBGKM_UNLOAD_DLL UnloadDll; } StateInfo; } DBGUI_WAIT_STATE_CHANGE, *PDBGUI_WAIT_STATE_CHANGE; typedef struct _DBGSS_THREAD_DATA { struct _DBGSS_THREAD_DATA* Next; HANDLE ThreadHandle; HANDLE ProcessHandle; ULONG ProcessId; ULONG ThreadId; BOOLEAN HandleMarked; } DBGSS_THREAD_DATA, *PDBGSS_THREAD_DATA; #define DbgSsSetThreadData(d) \ NtCurrentTeb()->DbgSsReserved[0] = d #define DbgSsGetThreadData() \ ((PDBGSS_THREAD_DATA)NtCurrentTeb()->DbgSsReserved[0]) typedef USHORT RTL_ATOM, *PRTL_ATOM; typedef long SECURITY_STATUS; typedef struct _RTL_SPLAY_LINKS { struct _RTL_SPLAY_LINKS* Parent; struct _RTL_SPLAY_LINKS* LeftChild; struct _RTL_SPLAY_LINKS* RightChild; } RTL_SPLAY_LINKS, *PRTL_SPLAY_LINKS; #define RtlInitializeSplayLinks(Links) \ { \ PRTL_SPLAY_LINKS _SplayLinks; \ _SplayLinks = (PRTL_SPLAY_LINKS)(Links); \ _SplayLinks->Parent = _SplayLinks; \ _SplayLinks->LeftChild = NULL; \ _SplayLinks->RightChild = NULL; \ } typedef struct _PREFIX_TABLE_ENTRY { SHORT NodeTypeCode; SHORT NameLength; struct _PREFIX_TABLE_ENTRY* NextPrefixTree; RTL_SPLAY_LINKS Links; PANSI_STRING Prefix; } PREFIX_TABLE_ENTRY, *PPREFIX_TABLE_ENTRY; typedef struct _PREFIX_TABLE { SHORT NodeTypeCode; SHORT NameLength; PPREFIX_TABLE_ENTRY NextPrefixTree; } PREFIX_TABLE, *PPREFIX_TABLE; typedef struct _RTL_BITMAP { ULONG SizeOfBitMap; PULONG Buffer; } RTL_BITMAP, *PRTL_BITMAP; typedef struct _RTL_BITMAP_RUN { ULONG StartingIndex; ULONG NumberOfBits; } RTL_BITMAP_RUN, *PRTL_BITMAP_RUN; typedef enum { RtlBsdItemVersionNumber = 0x00, RtlBsdItemProductType, RtlBsdItemAabEnabled, RtlBsdItemAabTimeout, RtlBsdItemBootGood, RtlBsdItemBootShutdown, RtlBsdItemMax } RTL_BSD_ITEM_TYPE, *PRTL_BSD_ITEM_TYPE; #define DUPLICATE_CLOSE_SOURCE 0x00000001 #define DUPLICATE_SAME_ACCESS 0x00000002 #define DUPLICATE_SAME_ATTRIBUTES 0x00000004 #define RTL_WALK_MAX_STACK_DEPTH 128 // These cannot be ORed together #define RTL_WALK_KERNEL_MODE_STACK 0x00000000 // Kernel mode callers only #define RTL_WALK_USER_MODE_STACK 0x00000001 #define RTL_WALK_TRACE_HANDLES 0x00000300 typedef struct _RTL_PROCESS_VERIFIER_OPTIONS { ULONG SizeStruct; ULONG Option; UCHAR OptionData[1]; } RTL_PROCESS_VERIFIER_OPTIONS, *PRTL_PROCESS_VERIFIER_OPTIONS; typedef struct _RTL_DEBUG_INFORMATION { HANDLE SectionHandleClient; PVOID ViewBaseClient; PVOID ViewBaseTarget; ULONG_PTR ViewBaseDelta; HANDLE EventPairClient; HANDLE EventPairTarget; HANDLE TargetProcessId; HANDLE TargetThreadHandle; ULONG Flags; SIZE_T OffsetFree; SIZE_T CommitSize; SIZE_T ViewSize; union { PRTL_PROCESS_MODULES Modules; PRTL_PROCESS_MODULE_INFORMATION_EX ModulesEx; }; struct _RTL_PROCESS_BACKTRACES* BackTraces; struct _RTL_PROCESS_HEAPS* Heaps; struct _RTL_PROCESS_LOCKS* Locks; PVOID SpecificHeap; HANDLE TargetProcessHandle; PRTL_PROCESS_VERIFIER_OPTIONS VerifierOptions; PVOID ProcessHeap; HANDLE CriticalSectionHandle; HANDLE CriticalSectionOwnerThread; PVOID Reserved[4]; } RTL_DEBUG_INFORMATION, *PRTL_DEBUG_INFORMATION; typedef VOID (*PPS_APC_ROUTINE)( _In_opt_ PVOID ApcArgument1, _In_opt_ PVOID ApcArgument2, _In_opt_ PVOID ApcArgument3 ); typedef struct _RTLP_CURDIR_REF* PRTLP_CURDIR_REF; typedef struct _RTL_RELATIVE_NAME_U { UNICODE_STRING RelativeName; HANDLE ContainingDirectory; PRTLP_CURDIR_REF CurDirRef; } RTL_RELATIVE_NAME_U, *PRTL_RELATIVE_NAME_U; typedef enum _RTL_PATH_TYPE { RtlPathTypeUnknown, RtlPathTypeUncAbsolute, RtlPathTypeDriveAbsolute, RtlPathTypeDriveRelative, RtlPathTypeRooted, RtlPathTypeRelative, RtlPathTypeLocalDevice, RtlPathTypeRootLocalDevice, } RTL_PATH_TYPE; #define DOS_MAX_COMPONENT_LENGTH 255 #define DOS_MAX_PATH_LENGTH (DOS_MAX_COMPONENT_LENGTH + 5) typedef struct _CURDIR { UNICODE_STRING DosPath; HANDLE Handle; } CURDIR, *PCURDIR; #define RTL_USER_PROC_CURDIR_CLOSE 0x00000002 #define RTL_USER_PROC_CURDIR_INHERIT 0x00000003 typedef struct _RTL_DRIVE_LETTER_CURDIR { USHORT Flags; USHORT Length; ULONG TimeStamp; UNICODE_STRING DosPath; } RTL_DRIVE_LETTER_CURDIR, *PRTL_DRIVE_LETTER_CURDIR; #define RTL_MAX_DRIVE_LETTERS 32 #define RTL_DRIVE_LETTER_VALID (USHORT)0x0001 typedef struct _LDR_SERVICE_TAG_RECORD { struct _LDR_SERVICE_TAG_RECORD* Next; ULONG ServiceTag; } LDR_SERVICE_TAG_RECORD, *PLDR_SERVICE_TAG_RECORD; typedef struct _LDRP_CSLIST { PSINGLE_LIST_ENTRY Tail; } LDRP_CSLIST, *PLDRP_CSLIST; typedef enum _LDR_DDAG_STATE { LdrModulesMerged = -5, LdrModulesInitError = -4, LdrModulesSnapError = -3, LdrModulesUnloaded = -2, LdrModulesUnloading = -1, LdrModulesPlaceHolder = 0, LdrModulesMapping = 1, LdrModulesMapped = 2, LdrModulesWaitingForDependencies = 3, LdrModulesSnapping = 4, LdrModulesSnapped = 5, LdrModulesCondensed = 6, LdrModulesReadyToInit = 7, LdrModulesInitializing = 8, LdrModulesReadyToRun = 9 } LDR_DDAG_STATE; typedef struct _LDR_DDAG_NODE { LIST_ENTRY Modules; PLDR_SERVICE_TAG_RECORD ServiceTagList; ULONG LoadCount; ULONG LoadWhileUnloadingCount; ULONG LowestLink; union { LDRP_CSLIST Dependencies; SINGLE_LIST_ENTRY RemovalLink; }; LDRP_CSLIST IncomingDependencies; LDR_DDAG_STATE State; SINGLE_LIST_ENTRY CondenseLink; ULONG PreorderNumber; } LDR_DDAG_NODE, *PLDR_DDAG_NODE; typedef struct _LDR_DEPENDENCY_RECORD { SINGLE_LIST_ENTRY DependencyLink; PLDR_DDAG_NODE DependencyNode; SINGLE_LIST_ENTRY IncomingDependencyLink; PLDR_DDAG_NODE IncomingDependencyNode; } LDR_DEPENDENCY_RECORD, *PLDR_DEPENDENCY_RECORD; typedef enum _LDR_DLL_LOAD_REASON { LoadReasonStaticDependency, LoadReasonStaticForwarderDependency, LoadReasonDynamicForwarderDependency, LoadReasonDelayloadDependency, LoadReasonDynamicLoad, LoadReasonAsImageLoad, LoadReasonAsDataLoad, LoadReasonUnknown = -1 } LDR_DLL_LOAD_REASON, *PLDR_DLL_LOAD_REASON; #define LDRP_PACKAGED_BINARY 0x00000001 #define LDRP_IMAGE_DLL 0x00000004 #define LDRP_LOAD_IN_PROGRESS 0x00001000 #define LDRP_ENTRY_PROCESSED 0x00004000 #define LDRP_DONT_CALL_FOR_THREADS 0x00040000 #define LDRP_PROCESS_ATTACH_CALLED 0x00080000 #define LDRP_PROCESS_ATTACH_FAILED 0x00100000 #define LDRP_IMAGE_NOT_AT_BASE 0x00200000 // Vista and below #define LDRP_COR_IMAGE 0x00400000 #define LDRP_DONT_RELOCATE 0x00800000 #define LDRP_REDIRECTED 0x10000000 #define LDRP_COMPAT_DATABASE_PROCESSED 0x80000000 #define LDR_DATA_TABLE_ENTRY_SIZE_WINXP FIELD_OFFSET(LDR_DATA_TABLE_ENTRY, DdagNode) #define LDR_DATA_TABLE_ENTRY_SIZE_WIN7 FIELD_OFFSET(LDR_DATA_TABLE_ENTRY, BaseNameHashValue) #define LDR_DATA_TABLE_ENTRY_SIZE_WIN8 FIELD_OFFSET(LDR_DATA_TABLE_ENTRY, ImplicitPathOptions) #define RTL_BALANCED_NODE_RESERVED_PARENT_MASK 3 typedef struct _RTL_BALANCED_NODE { union { struct _RTL_BALANCED_NODE* Children[2]; struct { struct _RTL_BALANCED_NODE* Left; struct _RTL_BALANCED_NODE* Right; } s; }; union { UCHAR Red : 1; UCHAR Balance : 2; ULONG_PTR ParentValue; } u; } RTL_BALANCED_NODE, *PRTL_BALANCED_NODE; typedef struct _LDR_DATA_TABLE_ENTRY { LIST_ENTRY InLoadOrderLinks; LIST_ENTRY InMemoryOrderLinks; union { LIST_ENTRY InInitializationOrderLinks; LIST_ENTRY InProgressLinks; }; PVOID DllBase; PVOID EntryPoint; ULONG SizeOfImage; UNICODE_STRING FullDllName; UNICODE_STRING BaseDllName; union { UCHAR FlagGroup[4]; ULONG Flags; struct { ULONG PackagedBinary : 1; ULONG MarkedForRemoval : 1; ULONG ImageDll : 1; ULONG LoadNotificationsSent : 1; ULONG TelemetryEntryProcessed : 1; ULONG ProcessStaticImport : 1; ULONG InLegacyLists : 1; ULONG InIndexes : 1; ULONG ShimDll : 1; ULONG InExceptionTable : 1; ULONG ReservedFlags1 : 2; ULONG LoadInProgress : 1; ULONG LoadConfigProcessed : 1; ULONG EntryProcessed : 1; ULONG ProtectDelayLoad : 1; ULONG ReservedFlags3 : 2; ULONG DontCallForThreads : 1; ULONG ProcessAttachCalled : 1; ULONG ProcessAttachFailed : 1; ULONG CorDeferredValidate : 1; ULONG CorImage : 1; ULONG DontRelocate : 1; ULONG CorILOnly : 1; ULONG ReservedFlags5 : 3; ULONG Redirected : 1; ULONG ReservedFlags6 : 2; ULONG CompatDatabaseProcessed : 1; } s; } u; USHORT ObsoleteLoadCount; USHORT TlsIndex; LIST_ENTRY HashLinks; ULONG TimeDateStamp; struct _ACTIVATION_CONTEXT* EntryPointActivationContext; PVOID Lock; PLDR_DDAG_NODE DdagNode; LIST_ENTRY NodeModuleLink; struct _LDRP_LOAD_CONTEXT* LoadContext; PVOID ParentDllBase; PVOID SwitchBackContext; RTL_BALANCED_NODE BaseAddressIndexNode; RTL_BALANCED_NODE MappingInfoIndexNode; ULONG_PTR OriginalBase; LARGE_INTEGER LoadTime; ULONG BaseNameHashValue; LDR_DLL_LOAD_REASON LoadReason; ULONG ImplicitPathOptions; ULONG ReferenceCount; ULONG DependentLoadFlags; UCHAR SigningLevel; // Since Windows 10 RS2 } LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY; typedef struct _INITIAL_TEB { struct { PVOID OldStackBase; PVOID OldStackLimit; } OldInitialTeb; PVOID StackBase; PVOID StackLimit; PVOID StackAllocationBase; } INITIAL_TEB, *PINITIAL_TEB; typedef struct _IO_STATUS_BLOCK { union { NTSTATUS Status; PVOID Pointer; }; ULONG_PTR Information; } IO_STATUS_BLOCK, *PIO_STATUS_BLOCK; typedef VOID (NTAPI* PIO_APC_ROUTINE)( _In_ PVOID ApcContext, _In_ PIO_STATUS_BLOCK IoStatusBlock, _In_ ULONG Reserved ); typedef struct _FILE_IO_COMPLETION_INFORMATION { PVOID KeyContext; PVOID ApcContext; IO_STATUS_BLOCK IoStatusBlock; } FILE_IO_COMPLETION_INFORMATION, *PFILE_IO_COMPLETION_INFORMATION; typedef struct _FILE_COMPLETION_INFORMATION { HANDLE Port; PVOID Key; } FILE_COMPLETION_INFORMATION, *PFILE_COMPLETION_INFORMATION; #ifdef __cplusplus typedef enum _PRIORITY_CLASS : UCHAR { Undefined, Idle, Normal, High, Realtime, BelowNormal, AboveNormal } PRIORITY_CLASS; #else typedef UCHAR PRIORITY_CLASS; #endif typedef struct _PROCESS_PRIORITY_CLASS { BOOLEAN Foreground; PRIORITY_CLASS PriorityClass; } PROCESS_PRIORITY_CLASS, *PPROCESS_PRIORITY_CLASS; typedef struct _PS_ATTRIBUTE { ULONG_PTR Attribute; // PROC_THREAD_ATTRIBUTE_XXX | PROC_THREAD_ATTRIBUTE_XXX modifiers, see ProcThreadAttributeValue macro and Windows Internals 6 (372) SIZE_T Size; // Size of Value or *ValuePtr union { ULONG_PTR Value; // Reserve 8 bytes for data (such as a Handle or a data pointer) PVOID ValuePtr; // data pointer }; PSIZE_T ReturnLength; // Either 0 or specifies size of data returned to caller via "ValuePtr" } PS_ATTRIBUTE, *PPS_ATTRIBUTE; typedef struct _PS_ATTRIBUTE_LIST { SIZE_T TotalLength; // sizeof(PS_ATTRIBUTE_LIST) PS_ATTRIBUTE Attributes[2]; // Depends on how many attribute entries should be supplied to NtCreateUserProcess } PS_ATTRIBUTE_LIST, *PPS_ATTRIBUTE_LIST; typedef struct _PS_MEMORY_RESERVE { PVOID ReserveAddress; SIZE_T ReserveSize; } PS_MEMORY_RESERVE, *PPS_MEMORY_RESERVE; #define PS_ATTRIBUTE_NUMBER_MASK 0x0000ffff #define PS_ATTRIBUTE_THREAD 0x00010000 // Attribute may be used with thread creation #define PS_ATTRIBUTE_INPUT 0x00020000 // Attribute is input only #define PS_ATTRIBUTE_ADDITIVE 0x00040000 // Attribute may be "accumulated", e.g. bitmasks, counters, etc. typedef enum _PS_ATTRIBUTE_NUM { PsAttributeParentProcess, // in HANDLE PsAttributeDebugPort, // in HANDLE PsAttributeToken, // in HANDLE PsAttributeClientId, // out PCLIENT_ID PsAttributeTebAddress, // out PTEB PsAttributeImageName, // in PWSTR PsAttributeImageInfo, // out PSECTION_IMAGE_INFORMATION PsAttributeMemoryReserve, // in PPS_MEMORY_RESERVE PsAttributePriorityClass, // in UCHAR PsAttributeErrorMode, // in ULONG PsAttributeStdHandleInfo, // in PPS_STD_HANDLE_INFO PsAttributeHandleList, // in PHANDLE PsAttributeGroupAffinity, // in PGROUP_AFFINITY PsAttributePreferredNode, // in PUSHORT PsAttributeIdealProcessor, // in PPROCESSOR_NUMBER PsAttributeUmsThread, // see MSDN UpdateProceThreadAttributeList (CreateProcessW) - in PUMS_CREATE_THREAD_ATTRIBUTES PsAttributeMitigationOptions, // in UCHAR PsAttributeProtectionLevel, // in ULONG PsAttributeSecureProcess, // since THRESHOLD (Virtual Secure Mode, Device Guard) PsAttributeJobList, PsAttributeChildProcessPolicy, // since THRESHOLD2 PsAttributeAllApplicationPackagesPolicy, // since REDSTONE PsAttributeWin32kFilter, PsAttributeSafeOpenPromptOriginClaim, PsAttributeBnoIsolation, PsAttributeDesktopAppPolicy, PsAttributeMax } PS_ATTRIBUTE_NUM; #define PsAttributeValue(Number, Thread, Input, Additive) \ (((Number) & PS_ATTRIBUTE_NUMBER_MASK) | \ ((Thread) ? PS_ATTRIBUTE_THREAD : 0) | \ ((Input) ? PS_ATTRIBUTE_INPUT : 0) | \ ((Additive) ? PS_ATTRIBUTE_ADDITIVE : 0)) #define PS_ATTRIBUTE_PARENT_PROCESS \ PsAttributeValue(PsAttributeParentProcess, FALSE, TRUE, TRUE) // 0x60000 #define PS_ATTRIBUTE_DEBUG_PORT \ PsAttributeValue(PsAttributeDebugPort, FALSE, TRUE, TRUE) // 0x60001 #define PS_ATTRIBUTE_TOKEN \ PsAttributeValue(PsAttributeToken, FALSE, TRUE, TRUE) // 0x60002 #define PS_ATTRIBUTE_CLIENT_ID \ PsAttributeValue(PsAttributeClientId, TRUE, FALSE, FALSE) // 0x10003 #define PS_ATTRIBUTE_TEB_ADDRESS \ PsAttributeValue(PsAttributeTebAddress, TRUE, FALSE, FALSE) // 0x10004 #define PS_ATTRIBUTE_IMAGE_NAME \ PsAttributeValue(PsAttributeImageName, FALSE, TRUE, FALSE) // 0x20005 #define PS_ATTRIBUTE_IMAGE_INFO \ PsAttributeValue(PsAttributeImageInfo, FALSE, FALSE, FALSE) // 0x6 #define PS_ATTRIBUTE_MEMORY_RESERVE \ PsAttributeValue(PsAttributeMemoryReserve, FALSE, TRUE, FALSE) // 0x20007 #define PS_ATTRIBUTE_PRIORITY_CLASS \ PsAttributeValue(PsAttributePriorityClass, FALSE, TRUE, FALSE) // 0x20008 #define PS_ATTRIBUTE_ERROR_MODE \ PsAttributeValue(PsAttributeErrorMode, FALSE, TRUE, FALSE) // 0x20009 #define PS_ATTRIBUTE_STD_HANDLE_INFO \ PsAttributeValue(PsAttributeStdHandleInfo, FALSE, TRUE, FALSE) // 0x2000A #define PS_ATTRIBUTE_HANDLE_LIST \ PsAttributeValue(PsAttributeHandleList, FALSE, TRUE, FALSE) // 0x2000B #define PS_ATTRIBUTE_GROUP_AFFINITY \ PsAttributeValue(PsAttributeGroupAffinity, TRUE, TRUE, FALSE) // 0x2000C #define PS_ATTRIBUTE_PREFERRED_NODE \ PsAttributeValue(PsAttributePreferredNode, FALSE, TRUE, FALSE) // 0x2000D #define PS_ATTRIBUTE_IDEAL_PROCESSOR \ PsAttributeValue(PsAttributeIdealProcessor, TRUE, TRUE, FALSE) // 0x2000E #define PS_ATTRIBUTE_MITIGATION_OPTIONS \ PsAttributeValue(PsAttributeMitigationOptions, FALSE, TRUE, TRUE) // 0x60010 #define PS_ATTRIBUTE_PROTECTION_LEVEL \ PsAttributeValue(PsAttributeProtectionLevel, FALSE, TRUE, FALSE) // 0x20011 typedef enum _PS_STD_HANDLE_STATE { PsNeverDuplicate, PsRequestDuplicate, // Duplicate standard handles specified by PseudoHandleMask, and only if StdHandleSubsystemType matches the image subsystem PsAlwaysDuplicate, // Always duplicate standard handles PsMaxStdHandleStates } PS_STD_HANDLE_STATE; #define HANDLE_DETACHED_PROCESS ((HANDLE)-1) #define HANDLE_CREATE_NEW_CONSOLE ((HANDLE)-2) #define HANDLE_CREATE_NO_WINDOW ((HANDLE)-3) #define PS_STD_INPUT_HANDLE 0x1 #define PS_STD_OUTPUT_HANDLE 0x2 #define PS_STD_ERROR_HANDLE 0x4 typedef struct _PS_STD_HANDLE_INFO { union { ULONG Flags; struct { ULONG StdHandleState : 2; // PS_STD_HANDLE_STATE ULONG PseudoHandleMask : 3; // PS_STD_* } s; }; ULONG StdHandleSubsystemType; } PS_STD_HANDLE_INFO, *PPS_STD_HANDLE_INFO; typedef struct _PS_BNO_ISOLATION_PARAMETERS { UNICODE_STRING IsolationPrefix; ULONG HandleCount; PVOID* Handles; BOOLEAN IsolationEnabled; } PS_BNO_ISOLATION_PARAMETERS, *PPS_BNO_ISOLATION_PARAMETERS; typedef enum _PS_MITIGATION_OPTION { PS_MITIGATION_OPTION_NX, PS_MITIGATION_OPTION_SEHOP, PS_MITIGATION_OPTION_FORCE_RELOCATE_IMAGES, PS_MITIGATION_OPTION_HEAP_TERMINATE, PS_MITIGATION_OPTION_BOTTOM_UP_ASLR, PS_MITIGATION_OPTION_HIGH_ENTROPY_ASLR, PS_MITIGATION_OPTION_STRICT_HANDLE_CHECKS, PS_MITIGATION_OPTION_WIN32K_SYSTEM_CALL_DISABLE, PS_MITIGATION_OPTION_EXTENSION_POINT_DISABLE, PS_MITIGATION_OPTION_PROHIBIT_DYNAMIC_CODE, PS_MITIGATION_OPTION_CONTROL_FLOW_GUARD, PS_MITIGATION_OPTION_BLOCK_NON_MICROSOFT_BINARIES, PS_MITIGATION_OPTION_FONT_DISABLE, PS_MITIGATION_OPTION_IMAGE_LOAD_NO_REMOTE, PS_MITIGATION_OPTION_IMAGE_LOAD_NO_LOW_LABEL, PS_MITIGATION_OPTION_IMAGE_LOAD_PREFER_SYSTEM32, PS_MITIGATION_OPTION_RETURN_FLOW_GUARD, PS_MITIGATION_OPTION_LOADER_INTEGRITY_CONTINUITY, PS_MITIGATION_OPTION_STRICT_CONTROL_FLOW_GUARD, PS_MITIGATION_OPTION_RESTRICT_SET_THREAD_CONTEXT } PS_MITIGATION_OPTION; typedef enum _PS_CREATE_STATE { PsCreateInitialState, PsCreateFailOnFileOpen, PsCreateFailOnSectionCreate, PsCreateFailExeFormat, PsCreateFailMachineMismatch, PsCreateFailExeName, // Debugger specified PsCreateSuccess, PsCreateMaximumStates } PS_CREATE_STATE; typedef struct _PS_CREATE_INFO { SIZE_T Size; PS_CREATE_STATE State; union { // PsCreateInitialState struct { union { ULONG InitFlags; struct { UCHAR WriteOutputOnExit : 1; UCHAR DetectManifest : 1; UCHAR IFEOSkipDebugger : 1; UCHAR IFEODoNotPropagateKeyState : 1; UCHAR SpareBits1 : 4; UCHAR SpareBits2 : 8; USHORT ProhibitedImageCharacteristics : 16; } s1; } u1; ACCESS_MASK AdditionalFileAccess; } InitState; // PsCreateFailOnSectionCreate struct { HANDLE FileHandle; } FailSection; // PsCreateFailExeFormat struct { USHORT DllCharacteristics; } ExeFormat; // PsCreateFailExeName struct { HANDLE IFEOKey; } ExeName; // PsCreateSuccess struct { union { ULONG OutputFlags; struct { UCHAR ProtectedProcess : 1; UCHAR AddressSpaceOverride : 1; UCHAR DevOverrideEnabled : 1; // From Image File Execution Options UCHAR ManifestDetected : 1; UCHAR ProtectedProcessLight : 1; UCHAR SpareBits1 : 3; UCHAR SpareBits2 : 8; USHORT SpareBits3 : 16; } s2; } u2; HANDLE FileHandle; HANDLE SectionHandle; ULONGLONG UserProcessParametersNative; ULONG UserProcessParametersWow64; ULONG CurrentParameterFlags; ULONGLONG PebAddressNative; ULONG PebAddressWow64; ULONGLONG ManifestAddress; ULONG ManifestSize; } SuccessState; }; } PS_CREATE_INFO, *PPS_CREATE_INFO; #define PROCESS_CREATE_FLAGS_BREAKAWAY 0x00000001 #define PROCESS_CREATE_FLAGS_NO_DEBUG_INHERIT 0x00000002 #define PROCESS_CREATE_FLAGS_INHERIT_HANDLES 0x00000004 #define PROCESS_CREATE_FLAGS_OVERRIDE_ADDRESS_SPACE 0x00000008 #define PROCESS_CREATE_FLAGS_LARGE_PAGES 0x00000010 // Only usable with NtCreateUserProcess (Vista+): #define PROCESS_CREATE_FLAGS_LARGE_PAGE_SYSTEM_DLL 0x00000020 #define PROCESS_CREATE_FLAGS_PROTECTED_PROCESS 0x00000040 // Only allowed if the calling process is itself protected #define PROCESS_CREATE_FLAGS_CREATE_SESSION 0x00000080 #define PROCESS_CREATE_FLAGS_INHERIT_FROM_PARENT 0x00000100 typedef enum _MEMORY_RESERVE_TYPE { MemoryReserveUserApc, MemoryReserveIoCompletion, MemoryReserveTypeMax } MEMORY_RESERVE_TYPE; typedef struct _PROCESS_HANDLE_TRACING_ENABLE { ULONG Flags; } PROCESS_HANDLE_TRACING_ENABLE, *PPROCESS_HANDLE_TRACING_ENABLE; #define PROCESS_HANDLE_TRACING_MAX_SLOTS 0x20000 typedef struct _PROCESS_HANDLE_TRACING_ENABLE_EX { ULONG Flags; ULONG TotalSlots; } PROCESS_HANDLE_TRACING_ENABLE_EX, *PPROCESS_HANDLE_TRACING_ENABLE_EX; // Source: http://processhacker.sourceforge.net typedef enum _PROCESSINFOCLASS { ProcessBasicInformation, // q: PROCESS_BASIC_INFORMATION, PROCESS_EXTENDED_BASIC_INFORMATION ProcessQuotaLimits, // qs: QUOTA_LIMITS, QUOTA_LIMITS_EX ProcessIoCounters, // q: IO_COUNTERS ProcessVmCounters, // q: VM_COUNTERS, VM_COUNTERS_EX, VM_COUNTERS_EX2 ProcessTimes, // q: KERNEL_USER_TIMES ProcessBasePriority, // s: KPRIORITY ProcessRaisePriority, // s: ULONG ProcessDebugPort, // q: HANDLE ProcessExceptionPort, // s: HANDLE ProcessAccessToken, // s: PROCESS_ACCESS_TOKEN ProcessLdtInformation, // qs: PROCESS_LDT_INFORMATION // 10 ProcessLdtSize, // s: PROCESS_LDT_SIZE ProcessDefaultHardErrorMode, // qs: ULONG ProcessIoPortHandlers, // (kernel-mode only) ProcessPooledUsageAndLimits, // q: POOLED_USAGE_AND_LIMITS ProcessWorkingSetWatch, // q: PROCESS_WS_WATCH_INFORMATION[]; s: void ProcessUserModeIOPL, ProcessEnableAlignmentFaultFixup, // s: BOOLEAN ProcessPriorityClass, // qs: PROCESS_PRIORITY_CLASS ProcessWx86Information, ProcessHandleCount, // q: ULONG, PROCESS_HANDLE_INFORMATION // 20 ProcessAffinityMask, // s: KAFFINITY ProcessPriorityBoost, // qs: ULONG ProcessDeviceMap, // qs: PROCESS_DEVICEMAP_INFORMATION, PROCESS_DEVICEMAP_INFORMATION_EX ProcessSessionInformation, // q: PROCESS_SESSION_INFORMATION ProcessForegroundInformation, // s: PROCESS_FOREGROUND_BACKGROUND ProcessWow64Information, // q: ULONG_PTR ProcessImageFileName, // q: UNICODE_STRING ProcessLUIDDeviceMapsEnabled, // q: ULONG ProcessBreakOnTermination, // qs: ULONG ProcessDebugObjectHandle, // q: HANDLE // 30 ProcessDebugFlags, // qs: ULONG ProcessHandleTracing, // q: PROCESS_HANDLE_TRACING_QUERY; s: size 0 disables, otherwise enables ProcessIoPriority, // qs: IO_PRIORITY_HINT ProcessExecuteFlags, // qs: ULONG ProcessResourceManagement, ProcessCookie, // q: ULONG ProcessImageInformation, // q: SECTION_IMAGE_INFORMATION ProcessCycleTime, // q: PROCESS_CYCLE_TIME_INFORMATION // since VISTA ProcessPagePriority, // q: ULONG ProcessInstrumentationCallback, // 40 ProcessThreadStackAllocation, // s: PROCESS_STACK_ALLOCATION_INFORMATION, PROCESS_STACK_ALLOCATION_INFORMATION_EX ProcessWorkingSetWatchEx, // q: PROCESS_WS_WATCH_INFORMATION_EX[] ProcessImageFileNameWin32, // q: UNICODE_STRING ProcessImageFileMapping, // q: HANDLE (input) ProcessAffinityUpdateMode, // qs: PROCESS_AFFINITY_UPDATE_MODE ProcessMemoryAllocationMode, // qs: PROCESS_MEMORY_ALLOCATION_MODE ProcessGroupInformation, // q: USHORT[] ProcessTokenVirtualizationEnabled, // s: ULONG ProcessConsoleHostProcess, // q: ULONG_PTR ProcessWindowInformation, // q: PROCESS_WINDOW_INFORMATION // 50 ProcessHandleInformation, // q: PROCESS_HANDLE_SNAPSHOT_INFORMATION // since WIN8 ProcessMitigationPolicy, // s: PROCESS_MITIGATION_POLICY_INFORMATION ProcessDynamicFunctionTableInformation, ProcessHandleCheckingMode, ProcessKeepAliveCount, // q: PROCESS_KEEPALIVE_COUNT_INFORMATION ProcessRevokeFileHandles, // s: PROCESS_REVOKE_FILE_HANDLES_INFORMATION ProcessWorkingSetControl, // s: PROCESS_WORKING_SET_CONTROL ProcessHandleTable, // since WINBLUE ProcessCheckStackExtentsMode, ProcessCommandLineInformation, // q: UNICODE_STRING // 60 ProcessProtectionInformation, // q: PS_PROTECTION ProcessMemoryExhaustion, // PROCESS_MEMORY_EXHAUSTION_INFO // since THRESHOLD ProcessFaultInformation, // PROCESS_FAULT_INFORMATION ProcessTelemetryIdInformation, // PROCESS_TELEMETRY_ID_INFORMATION ProcessCommitReleaseInformation, // PROCESS_COMMIT_RELEASE_INFORMATION ProcessDefaultCpuSetsInformation, ProcessAllowedCpuSetsInformation, ProcessSubsystemProcess, ProcessJobMemoryInformation, // PROCESS_JOB_MEMORY_INFO ProcessInPrivate, // since THRESHOLD2 // 70 ProcessRaiseUMExceptionOnInvalidHandleClose, ProcessIumChallengeResponse, ProcessChildProcessInformation, // PROCESS_CHILD_PROCESS_INFORMATION ProcessHighGraphicsPriorityInformation, ProcessSubsystemInformation, // q: SUBSYSTEM_INFORMATION_TYPE // since REDSTONE2 ProcessEnergyValues, // PROCESS_ENERGY_VALUES, PROCESS_EXTENDED_ENERGY_VALUES ProcessActivityThrottleState, // PROCESS_ACTIVITY_THROTTLE_STATE ProcessActivityThrottlePolicy, // PROCESS_ACTIVITY_THROTTLE_POLICY ProcessWin32kSyscallFilterInformation, ProcessDisableSystemAllowedCpuSets, ProcessWakeInformation, // PROCESS_WAKE_INFORMATION ProcessEnergyTrackingState, // PROCESS_ENERGY_TRACKING_STATE MaxProcessInfoClass } PROCESSINFOCLASS; // Source: http://processhacker.sourceforge.net typedef enum _SYSTEM_INFORMATION_CLASS { SystemBasicInformation, // q: SYSTEM_BASIC_INFORMATION SystemProcessorInformation, // q: SYSTEM_PROCESSOR_INFORMATION SystemPerformanceInformation, // q: SYSTEM_PERFORMANCE_INFORMATION SystemTimeOfDayInformation, // q: SYSTEM_TIMEOFDAY_INFORMATION SystemPathInformation, // not implemented SystemProcessInformation, // q: SYSTEM_PROCESS_INFORMATION SystemCallCountInformation, // q: SYSTEM_CALL_COUNT_INFORMATION SystemDeviceInformation, // q: SYSTEM_DEVICE_INFORMATION SystemProcessorPerformanceInformation, // q: SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION SystemFlagsInformation, // q: SYSTEM_FLAGS_INFORMATION SystemCallTimeInformation, // not implemented // SYSTEM_CALL_TIME_INFORMATION // 10 SystemModuleInformation, // q: RTL_PROCESS_MODULES SystemLocksInformation, // q: RTL_PROCESS_LOCKS SystemStackTraceInformation, // q: RTL_PROCESS_BACKTRACES SystemPagedPoolInformation, // not implemented SystemNonPagedPoolInformation, // not implemented SystemHandleInformation, // q: SYSTEM_HANDLE_INFORMATION SystemObjectInformation, // q: SYSTEM_OBJECTTYPE_INFORMATION mixed with SYSTEM_OBJECT_INFORMATION SystemPageFileInformation, // q: SYSTEM_PAGEFILE_INFORMATION SystemVdmInstemulInformation, // q SystemVdmBopInformation, // not implemented // 20 SystemFileCacheInformation, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (info for WorkingSetTypeSystemCache) SystemPoolTagInformation, // q: SYSTEM_POOLTAG_INFORMATION SystemInterruptInformation, // q: SYSTEM_INTERRUPT_INFORMATION SystemDpcBehaviorInformation, // q: SYSTEM_DPC_BEHAVIOR_INFORMATION; s: SYSTEM_DPC_BEHAVIOR_INFORMATION (requires SeLoadDriverPrivilege) SystemFullMemoryInformation, // not implemented SystemLoadGdiDriverInformation, // s (kernel-mode only) SystemUnloadGdiDriverInformation, // s (kernel-mode only) SystemTimeAdjustmentInformation, // q: SYSTEM_QUERY_TIME_ADJUST_INFORMATION; s: SYSTEM_SET_TIME_ADJUST_INFORMATION (requires SeSystemtimePrivilege) SystemSummaryMemoryInformation, // not implemented SystemMirrorMemoryInformation, // s (requires license value "Kernel-MemoryMirroringSupported") (requires SeShutdownPrivilege) // 30 SystemPerformanceTraceInformation, // q; s: (type depends on EVENT_TRACE_INFORMATION_CLASS) SystemObsolete0, // not implemented SystemExceptionInformation, // q: SYSTEM_EXCEPTION_INFORMATION SystemCrashDumpStateInformation, // s (requires SeDebugPrivilege) SystemKernelDebuggerInformation, // q: SYSTEM_KERNEL_DEBUGGER_INFORMATION SystemContextSwitchInformation, // q: SYSTEM_CONTEXT_SWITCH_INFORMATION SystemRegistryQuotaInformation, // q: SYSTEM_REGISTRY_QUOTA_INFORMATION; s (requires SeIncreaseQuotaPrivilege) SystemExtendServiceTableInformation, // s (requires SeLoadDriverPrivilege) // loads win32k only SystemPrioritySeperation, // s (requires SeTcbPrivilege) SystemVerifierAddDriverInformation, // s (requires SeDebugPrivilege) // 40 SystemVerifierRemoveDriverInformation, // s (requires SeDebugPrivilege) SystemProcessorIdleInformation, // q: SYSTEM_PROCESSOR_IDLE_INFORMATION SystemLegacyDriverInformation, // q: SYSTEM_LEGACY_DRIVER_INFORMATION SystemCurrentTimeZoneInformation, // q SystemLookasideInformation, // q: SYSTEM_LOOKASIDE_INFORMATION SystemTimeSlipNotification, // s (requires SeSystemtimePrivilege) SystemSessionCreate, // not implemented SystemSessionDetach, // not implemented SystemSessionInformation, // not implemented SystemRangeStartInformation, // q: SYSTEM_RANGE_START_INFORMATION // 50 SystemVerifierInformation, // q: SYSTEM_VERIFIER_INFORMATION; s (requires SeDebugPrivilege) SystemVerifierThunkExtend, // s (kernel-mode only) SystemSessionProcessInformation, // q: SYSTEM_SESSION_PROCESS_INFORMATION SystemLoadGdiDriverInSystemSpace, // s (kernel-mode only) (same as SystemLoadGdiDriverInformation) SystemNumaProcessorMap, // q SystemPrefetcherInformation, // q: PREFETCHER_INFORMATION; s: PREFETCHER_INFORMATION // PfSnQueryPrefetcherInformation SystemExtendedProcessInformation, // q: SYSTEM_PROCESS_INFORMATION SystemRecommendedSharedDataAlignment, // q SystemComPlusPackage, // q; s SystemNumaAvailableMemory, // 60 SystemProcessorPowerInformation, // q: SYSTEM_PROCESSOR_POWER_INFORMATION SystemEmulationBasicInformation, // q SystemEmulationProcessorInformation, SystemExtendedHandleInformation, // q: SYSTEM_HANDLE_INFORMATION_EX SystemLostDelayedWriteInformation, // q: ULONG SystemBigPoolInformation, // q: SYSTEM_BIGPOOL_INFORMATION SystemSessionPoolTagInformation, // q: SYSTEM_SESSION_POOLTAG_INFORMATION SystemSessionMappedViewInformation, // q: SYSTEM_SESSION_MAPPED_VIEW_INFORMATION SystemHotpatchInformation, // q; s SystemObjectSecurityMode, // q // 70 SystemWatchdogTimerHandler, // s (kernel-mode only) SystemWatchdogTimerInformation, // q (kernel-mode only); s (kernel-mode only) SystemLogicalProcessorInformation, // q: SYSTEM_LOGICAL_PROCESSOR_INFORMATION SystemWow64SharedInformationObsolete, // not implemented SystemRegisterFirmwareTableInformationHandler, // s (kernel-mode only) SystemFirmwareTableInformation, // SYSTEM_FIRMWARE_TABLE_INFORMATION SystemModuleInformationEx, // q: RTL_PROCESS_MODULE_INFORMATION_EX SystemVerifierTriageInformation, // not implemented SystemSuperfetchInformation, // q; s: SUPERFETCH_INFORMATION // PfQuerySuperfetchInformation SystemMemoryListInformation, // q: SYSTEM_MEMORY_LIST_INFORMATION; s: SYSTEM_MEMORY_LIST_COMMAND (requires SeProfileSingleProcessPrivilege) // 80 SystemFileCacheInformationEx, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (same as SystemFileCacheInformation) SystemThreadPriorityClientIdInformation, // s: SYSTEM_THREAD_CID_PRIORITY_INFORMATION (requires SeIncreaseBasePriorityPrivilege) SystemProcessorIdleCycleTimeInformation, // q: SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION[] SystemVerifierCancellationInformation, // not implemented // name:wow64:whNT32QuerySystemVerifierCancellationInformation SystemProcessorPowerInformationEx, // not implemented SystemRefTraceInformation, // q; s: SYSTEM_REF_TRACE_INFORMATION // ObQueryRefTraceInformation SystemSpecialPoolInformation, // q; s (requires SeDebugPrivilege) // MmSpecialPoolTag, then MmSpecialPoolCatchOverruns != 0 SystemProcessIdInformation, // q: SYSTEM_PROCESS_ID_INFORMATION SystemErrorPortInformation, // s (requires SeTcbPrivilege) SystemBootEnvironmentInformation, // q: SYSTEM_BOOT_ENVIRONMENT_INFORMATION // 90 SystemHypervisorInformation, // q; s (kernel-mode only) SystemVerifierInformationEx, // q; s: SYSTEM_VERIFIER_INFORMATION_EX SystemTimeZoneInformation, // s (requires SeTimeZonePrivilege) SystemImageFileExecutionOptionsInformation, // s: SYSTEM_IMAGE_FILE_EXECUTION_OPTIONS_INFORMATION (requires SeTcbPrivilege) SystemCoverageInformation, // q; s // name:wow64:whNT32QuerySystemCoverageInformation; ExpCovQueryInformation SystemPrefetchPatchInformation, // not implemented SystemVerifierFaultsInformation, // s (requires SeDebugPrivilege) SystemSystemPartitionInformation, // q: SYSTEM_SYSTEM_PARTITION_INFORMATION SystemSystemDiskInformation, // q: SYSTEM_SYSTEM_DISK_INFORMATION SystemProcessorPerformanceDistribution, // q: SYSTEM_PROCESSOR_PERFORMANCE_DISTRIBUTION // 100 SystemNumaProximityNodeInformation, // q SystemDynamicTimeZoneInformation, // q; s (requires SeTimeZonePrivilege) SystemCodeIntegrityInformation, // q: SYSTEM_CODEINTEGRITY_INFORMATION // SeCodeIntegrityQueryInformation SystemProcessorMicrocodeUpdateInformation, // s SystemProcessorBrandString, // q // HaliQuerySystemInformation -> HalpGetProcessorBrandString, info class 23 SystemVirtualAddressInformation, // q: SYSTEM_VA_LIST_INFORMATION[]; s: SYSTEM_VA_LIST_INFORMATION[] (requires SeIncreaseQuotaPrivilege) // MmQuerySystemVaInformation SystemLogicalProcessorAndGroupInformation, // q: SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX // since WIN7 // KeQueryLogicalProcessorRelationship SystemProcessorCycleTimeInformation, // q: SYSTEM_PROCESSOR_CYCLE_TIME_INFORMATION[] SystemStoreInformation, // q; s // SmQueryStoreInformation SystemRegistryAppendString, // s: SYSTEM_REGISTRY_APPEND_STRING_PARAMETERS // 110 SystemAitSamplingValue, // s: ULONG (requires SeProfileSingleProcessPrivilege) SystemVhdBootInformation, // q: SYSTEM_VHD_BOOT_INFORMATION SystemCpuQuotaInformation, // q; s // PsQueryCpuQuotaInformation SystemNativeBasicInformation, // not implemented SystemSpare1, // not implemented SystemLowPriorityIoInformation, // q: SYSTEM_LOW_PRIORITY_IO_INFORMATION SystemTpmBootEntropyInformation, // q: TPM_BOOT_ENTROPY_NT_RESULT // ExQueryTpmBootEntropyInformation SystemVerifierCountersInformation, // q: SYSTEM_VERIFIER_COUNTERS_INFORMATION SystemPagedPoolInformationEx, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (info for WorkingSetTypePagedPool) SystemSystemPtesInformationEx, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (info for WorkingSetTypeSystemPtes) // 120 SystemNodeDistanceInformation, // q SystemAcpiAuditInformation, // q: SYSTEM_ACPI_AUDIT_INFORMATION // HaliQuerySystemInformation -> HalpAuditQueryResults, info class 26 SystemBasicPerformanceInformation, // q: SYSTEM_BASIC_PERFORMANCE_INFORMATION // name:wow64:whNtQuerySystemInformation_SystemBasicPerformanceInformation SystemQueryPerformanceCounterInformation, // q: SYSTEM_QUERY_PERFORMANCE_COUNTER_INFORMATION // since WIN7 SP1 SystemSessionBigPoolInformation, // q: SYSTEM_SESSION_POOLTAG_INFORMATION // since WIN8 SystemBootGraphicsInformation, // q; s: SYSTEM_BOOT_GRAPHICS_INFORMATION (kernel-mode only) SystemScrubPhysicalMemoryInformation, // q; s: MEMORY_SCRUB_INFORMATION SystemBadPageInformation, SystemProcessorProfileControlArea, // q; s: SYSTEM_PROCESSOR_PROFILE_CONTROL_AREA SystemCombinePhysicalMemoryInformation, // s: MEMORY_COMBINE_INFORMATION, MEMORY_COMBINE_INFORMATION_EX, MEMORY_COMBINE_INFORMATION_EX2 // 130 SystemEntropyInterruptTimingCallback, SystemConsoleInformation, // q: SYSTEM_CONSOLE_INFORMATION SystemPlatformBinaryInformation, // q: SYSTEM_PLATFORM_BINARY_INFORMATION SystemThrottleNotificationInformation, SystemHypervisorProcessorCountInformation, // q: SYSTEM_HYPERVISOR_PROCESSOR_COUNT_INFORMATION SystemDeviceDataInformation, // q: SYSTEM_DEVICE_DATA_INFORMATION SystemDeviceDataEnumerationInformation, SystemMemoryTopologyInformation, // q: SYSTEM_MEMORY_TOPOLOGY_INFORMATION SystemMemoryChannelInformation, // q: SYSTEM_MEMORY_CHANNEL_INFORMATION SystemBootLogoInformation, // q: SYSTEM_BOOT_LOGO_INFORMATION // 140 SystemProcessorPerformanceInformationEx, // q: SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION_EX // since WINBLUE SystemSpare0, SystemSecureBootPolicyInformation, // q: SYSTEM_SECUREBOOT_POLICY_INFORMATION SystemPageFileInformationEx, // q: SYSTEM_PAGEFILE_INFORMATION_EX SystemSecureBootInformation, // q: SYSTEM_SECUREBOOT_INFORMATION SystemEntropyInterruptTimingRawInformation, SystemPortableWorkspaceEfiLauncherInformation, // q: SYSTEM_PORTABLE_WORKSPACE_EFI_LAUNCHER_INFORMATION SystemFullProcessInformation, // q: SYSTEM_PROCESS_INFORMATION with SYSTEM_PROCESS_INFORMATION_EXTENSION (requires admin) SystemKernelDebuggerInformationEx, // q: SYSTEM_KERNEL_DEBUGGER_INFORMATION_EX SystemBootMetadataInformation, // 150 SystemSoftRebootInformation, SystemElamCertificateInformation, // s: SYSTEM_ELAM_CERTIFICATE_INFORMATION SystemOfflineDumpConfigInformation, SystemProcessorFeaturesInformation, // q: SYSTEM_PROCESSOR_FEATURES_INFORMATION SystemRegistryReconciliationInformation, SystemEdidInformation, SystemManufacturingInformation, // q: SYSTEM_MANUFACTURING_INFORMATION // since THRESHOLD SystemEnergyEstimationConfigInformation, // q: SYSTEM_ENERGY_ESTIMATION_CONFIG_INFORMATION SystemHypervisorDetailInformation, // q: SYSTEM_HYPERVISOR_DETAIL_INFORMATION SystemProcessorCycleStatsInformation, // q: SYSTEM_PROCESSOR_CYCLE_STATS_INFORMATION // 160 SystemVmGenerationCountInformation, SystemTrustedPlatformModuleInformation, // q: SYSTEM_TPM_INFORMATION SystemKernelDebuggerFlags, SystemCodeIntegrityPolicyInformation, // q: SYSTEM_CODEINTEGRITYPOLICY_INFORMATION SystemIsolatedUserModeInformation, // q: SYSTEM_ISOLATED_USER_MODE_INFORMATION SystemHardwareSecurityTestInterfaceResultsInformation, SystemSingleModuleInformation, // q: SYSTEM_SINGLE_MODULE_INFORMATION SystemAllowedCpuSetsInformation, SystemDmaProtectionInformation, // q: SYSTEM_DMA_PROTECTION_INFORMATION SystemInterruptCpuSetsInformation, // q: SYSTEM_INTERRUPT_CPU_SET_INFORMATION // 170 SystemSecureBootPolicyFullInformation, // q: SYSTEM_SECUREBOOT_POLICY_FULL_INFORMATION SystemCodeIntegrityPolicyFullInformation, SystemAffinitizedInterruptProcessorInformation, SystemRootSiloInformation, // q: SYSTEM_ROOT_SILO_INFORMATION SystemCpuSetInformation, // q: SYSTEM_CPU_SET_INFORMATION // since THRESHOLD2 SystemCpuSetTagInformation, // q: SYSTEM_CPU_SET_TAG_INFORMATION SystemWin32WerStartCallout, SystemSecureKernelProfileInformation, // q: SYSTEM_SECURE_KERNEL_HYPERGUARD_PROFILE_INFORMATION SystemCodeIntegrityPlatformManifestInformation, // q: SYSTEM_SECUREBOOT_PLATFORM_MANIFEST_INFORMATION // since REDSTONE SystemInterruptSteeringInformation, // 180 SystemSupportedProcessorArchitectures, SystemMemoryUsageInformation, // q: SYSTEM_MEMORY_USAGE_INFORMATION SystemCodeIntegrityCertificateInformation, // q: SYSTEM_CODEINTEGRITY_CERTIFICATE_INFORMATION SystemPhysicalMemoryInformation, // q: SYSTEM_PHYSICAL_MEMORY_INFORMATION // since REDSTONE2 SystemControlFlowTransition, SystemKernelDebuggingAllowed, SystemActivityModerationExeState, // SYSTEM_ACTIVITY_MODERATION_EXE_STATE SystemActivityModerationUserSettings, // SYSTEM_ACTIVITY_MODERATION_USER_SETTINGS SystemCodeIntegrityPoliciesFullInformation, SystemCodeIntegrityUnlockInformation, // SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION // 190 SystemIntegrityQuotaInformation, SystemFlushInformation, // q: SYSTEM_FLUSH_INFORMATION MaxSystemInfoClass } SYSTEM_INFORMATION_CLASS; typedef enum _OBJECT_INFORMATION_CLASS { ObjectBasicInformation, // OBJECT_BASIC_INFORMATION ObjectNameInformation, // OBJECT_NAME_INFORMATION ObjectTypeInformation, // OBJECT_TYPE_INFORMATION ObjectTypesInformation, // OBJECT_TYPES_INFORMATION ObjectHandleFlagInformation, // OBJECT_HANDLE_FLAG_INFORMATION ObjectSessionInformation, ObjectSessionObjectInformation, MaxObjectInfoClass } OBJECT_INFORMATION_CLASS; //Source: http://processhacker.sourceforge.net typedef enum _THREADINFOCLASS { ThreadBasicInformation, // q: THREAD_BASIC_INFORMATION ThreadTimes, // q: KERNEL_USER_TIMES ThreadPriority, // s: KPRIORITY ThreadBasePriority, // s: LONG ThreadAffinityMask, // s: KAFFINITY ThreadImpersonationToken, // s: HANDLE ThreadDescriptorTableEntry, // q: DESCRIPTOR_TABLE_ENTRY (or WOW64_DESCRIPTOR_TABLE_ENTRY) ThreadEnableAlignmentFaultFixup, // s: BOOLEAN ThreadEventPair, ThreadQuerySetWin32StartAddress, // q: PVOID ThreadZeroTlsCell, // 10 ThreadPerformanceCount, // q: LARGE_INTEGER ThreadAmILastThread, // q: ULONG ThreadIdealProcessor, // s: ULONG ThreadPriorityBoost, // qs: ULONG ThreadSetTlsArrayAddress, ThreadIsIoPending, // q: ULONG ThreadHideFromDebugger, // s: void ThreadBreakOnTermination, // qs: ULONG ThreadSwitchLegacyState, ThreadIsTerminated, // q: ULONG // 20 ThreadLastSystemCall, // q: THREAD_LAST_SYSCALL_INFORMATION ThreadIoPriority, // qs: IO_PRIORITY_HINT ThreadCycleTime, // q: THREAD_CYCLE_TIME_INFORMATION ThreadPagePriority, // q: ULONG ThreadActualBasePriority, ThreadTebInformation, // q: THREAD_TEB_INFORMATION (requires THREAD_GET_CONTEXT + THREAD_SET_CONTEXT) ThreadCSwitchMon, ThreadCSwitchPmu, ThreadWow64Context, // q: WOW64_CONTEXT ThreadGroupInformation, // q: GROUP_AFFINITY // 30 ThreadUmsInformation, // q: THREAD_UMS_INFORMATION ThreadCounterProfiling, ThreadIdealProcessorEx, // q: PROCESSOR_NUMBER ThreadCpuAccountingInformation, // since WIN8 ThreadSuspendCount, // since WINBLUE ThreadHeterogeneousCpuPolicy, // q: KHETERO_CPU_POLICY // since THRESHOLD ThreadContainerId, // q: GUID ThreadNameInformation, // qs: THREAD_NAME_INFORMATION ThreadSelectedCpuSets, ThreadSystemThreadInformation, // q: SYSTEM_THREAD_INFORMATION // 40 ThreadActualGroupAffinity, // since THRESHOLD2 ThreadDynamicCodePolicyInfo, ThreadExplicitCaseSensitivity, ThreadWorkOnBehalfTicket, ThreadSubsystemInformation, // q: SUBSYSTEM_INFORMATION_TYPE // since REDSTONE2 ThreadDbgkWerReportActive, ThreadAttachContainer, MaxThreadInfoClass } THREADINFOCLASS; typedef enum _FSINFOCLASS { FileFsVolumeInformation = 1, // FILE_FS_VOLUME_INFORMATION FileFsLabelInformation = 2, // FILE_FS_LABEL_INFORMATION FileFsSizeInformation = 3, // FILE_FS_SIZE_INFORMATION FileFsDeviceInformation = 4, // FILE_FS_DEVICE_INFORMATION FileFsAttributeInformation = 5, // FILE_FS_ATTRIBUTE_INFORMATION FileFsControlInformation = 6, // FILE_FS_CONTROL_INFORMATION FileFsFullSizeInformation = 7, // FILE_FS_FULL_SIZE_INFORMATION FileFsObjectIdInformation = 8, // FILE_FS_OBJECTID_INFORMATION FileFsDriverPathInformation = 9, // FILE_FS_DRIVER_PATH_INFORMATION FileFsVolumeFlagsInformation = 10, // FILE_FS_VOLUME_FLAGS_INFORMATION FileFsSectorSizeInformation = 11, // FILE_FS_SECTOR_SIZE_INFORMATION // since WIN8 FileFsDataCopyInformation = 12, // FILE_FS_DATA_COPY_INFORMATION FileFsMetadataSizeInformation = 13, // FILE_FS_METADATA_SIZE_INFORMATION // since THRESHOLD FileFsMaximumInformation } FS_INFORMATION_CLASS, *PFS_INFORMATION_CLASS; typedef enum _MEMORY_INFORMATION_CLASS { MemoryBasicInformation, // MEMORY_BASIC_INFORMATION MemoryWorkingSetInformation, // MEMORY_WORKING_SET_INFORMATION MemoryMappedFilenameInformation, // UNICODE_STRING MemoryRegionInformation, // MEMORY_REGION_INFORMATION MemoryWorkingSetExInformation, // MEMORY_WORKING_SET_EX_INFORMATION MemorySharedCommitInformation, // MEMORY_SHARED_COMMIT_INFORMATION MemoryImageInformation, // MEMORY_IMAGE_INFORMATION MemoryRegionInformationEx, MemoryPrivilegedBasicInformation } MEMORY_INFORMATION_CLASS; typedef enum _SECTION_INFORMATION_CLASS { SectionBasicInformation, SectionImageInformation, SectionRelocationInformation, // name:wow64:whNtQuerySection_SectionRelocationInformation SectionOriginalBaseInformation, // PVOID BaseAddress SectionInternalImageInformation, // SECTION_INTERNAL_IMAGE_INFORMATION // since REDSTONE2 MaxSectionInfoClass } SECTION_INFORMATION_CLASS; // Boot condition flags (NtInitializeRegistry) #define REG_INIT_BOOT_SM 0x0000 #define REG_INIT_BOOT_SETUP 0x0001 #define REG_INIT_BOOT_ACCEPTED_BASE 0x0002 #define REG_INIT_BOOT_ACCEPTED_MAX REG_INIT_BOOT_ACCEPTED_BASE + 999 #define REG_MAX_KEY_VALUE_NAME_LENGTH 32767 #define REG_MAX_KEY_NAME_LENGTH 512 typedef enum _KEY_INFORMATION_CLASS { KeyBasicInformation, // KEY_BASIC_INFORMATION KeyNodeInformation, // KEY_NODE_INFORMATION KeyFullInformation, // KEY_FULL_INFORMATION KeyNameInformation, // KEY_NAME_INFORMATION KeyCachedInformation, // KEY_CACHED_INFORMATION KeyFlagsInformation, // KEY_FLAGS_INFORMATION KeyVirtualizationInformation, // KEY_VIRTUALIZATION_INFORMATION KeyHandleTagsInformation, // KEY_HANDLE_TAGS_INFORMATION KeyTrustInformation, // KEY_TRUST_INFORMATION KeyLayerInformation, // KEY_LAYER_INFORMATION MaxKeyInfoClass } KEY_INFORMATION_CLASS; typedef struct _KEY_BASIC_INFORMATION { LARGE_INTEGER LastWriteTime; ULONG TitleIndex; ULONG NameLength; WCHAR Name[1]; } KEY_BASIC_INFORMATION, *PKEY_BASIC_INFORMATION; typedef struct _KEY_NODE_INFORMATION { LARGE_INTEGER LastWriteTime; ULONG TitleIndex; ULONG ClassOffset; ULONG ClassLength; ULONG NameLength; WCHAR Name[1]; // ... // WCHAR Class[1]; } KEY_NODE_INFORMATION, *PKEY_NODE_INFORMATION; typedef struct _KEY_FULL_INFORMATION { LARGE_INTEGER LastWriteTime; ULONG TitleIndex; ULONG ClassOffset; ULONG ClassLength; ULONG SubKeys; ULONG MaxNameLen; ULONG MaxClassLen; ULONG Values; ULONG MaxValueNameLen; ULONG MaxValueDataLen; WCHAR Class[1]; } KEY_FULL_INFORMATION, *PKEY_FULL_INFORMATION; typedef struct _KEY_NAME_INFORMATION { ULONG NameLength; WCHAR Name[1]; } KEY_NAME_INFORMATION, *PKEY_NAME_INFORMATION; typedef struct _KEY_CACHED_INFORMATION { LARGE_INTEGER LastWriteTime; ULONG TitleIndex; ULONG SubKeys; ULONG MaxNameLen; ULONG Values; ULONG MaxValueNameLen; ULONG MaxValueDataLen; ULONG NameLength; WCHAR Name[1]; } KEY_CACHED_INFORMATION, *PKEY_CACHED_INFORMATION; typedef struct _KEY_FLAGS_INFORMATION { ULONG UserFlags; } KEY_FLAGS_INFORMATION, *PKEY_FLAGS_INFORMATION; typedef struct _KEY_VIRTUALIZATION_INFORMATION { ULONG VirtualizationCandidate : 1; // Tells whether the key is part of the virtualization namespace scope (only HKLM\Software for now). ULONG VirtualizationEnabled : 1; // Tells whether virtualization is enabled on this key. Can be 1 only if above flag is 1. ULONG VirtualTarget : 1; // Tells if the key is a virtual key. Can be 1 only if above 2 are 0. Valid only on the virtual store key handles. ULONG VirtualStore : 1; // Tells if the key is a part of the virtual store path. Valid only on the virtual store key handles. ULONG VirtualSource : 1; // Tells if the key has ever been virtualized, can be 1 only if VirtualizationCandidate is 1. ULONG Reserved : 27; } KEY_VIRTUALIZATION_INFORMATION, *PKEY_VIRTUALIZATION_INFORMATION; // private typedef struct _KEY_TRUST_INFORMATION { ULONG TrustedKey : 1; ULONG Reserved : 31; } KEY_TRUST_INFORMATION, *PKEY_TRUST_INFORMATION; // private typedef struct _KEY_LAYER_INFORMATION { ULONG IsTombstone; ULONG IsSupersedeLocal; ULONG IsSupersedeTree; ULONG ClassIsInherited; ULONG Reserved; } KEY_LAYER_INFORMATION, *PKEY_LAYER_INFORMATION; typedef enum _KEY_SET_INFORMATION_CLASS { KeyWriteTimeInformation, // KEY_WRITE_TIME_INFORMATION KeyWow64FlagsInformation, // KEY_WOW64_FLAGS_INFORMATION KeyControlFlagsInformation, // KEY_CONTROL_FLAGS_INFORMATION KeySetVirtualizationInformation, // KEY_SET_VIRTUALIZATION_INFORMATION KeySetDebugInformation, KeySetHandleTagsInformation, // KEY_HANDLE_TAGS_INFORMATION MaxKeySetInfoClass } KEY_SET_INFORMATION_CLASS; typedef struct _KEY_WRITE_TIME_INFORMATION { LARGE_INTEGER LastWriteTime; } KEY_WRITE_TIME_INFORMATION, *PKEY_WRITE_TIME_INFORMATION; typedef struct _KEY_WOW64_FLAGS_INFORMATION { ULONG UserFlags; } KEY_WOW64_FLAGS_INFORMATION, *PKEY_WOW64_FLAGS_INFORMATION; typedef struct _KEY_HANDLE_TAGS_INFORMATION { ULONG HandleTags; } KEY_HANDLE_TAGS_INFORMATION, *PKEY_HANDLE_TAGS_INFORMATION; typedef struct _KEY_CONTROL_FLAGS_INFORMATION { ULONG ControlFlags; } KEY_CONTROL_FLAGS_INFORMATION, *PKEY_CONTROL_FLAGS_INFORMATION; typedef struct _KEY_SET_VIRTUALIZATION_INFORMATION { ULONG VirtualTarget : 1; ULONG VirtualStore : 1; ULONG VirtualSource : 1; // true if key has been virtualized at least once ULONG Reserved : 29; } KEY_SET_VIRTUALIZATION_INFORMATION, *PKEY_SET_VIRTUALIZATION_INFORMATION; typedef enum _KEY_VALUE_INFORMATION_CLASS { KeyValueBasicInformation, // KEY_VALUE_BASIC_INFORMATION KeyValueFullInformation, // KEY_VALUE_FULL_INFORMATION KeyValuePartialInformation, // KEY_VALUE_PARTIAL_INFORMATION KeyValueFullInformationAlign64, KeyValuePartialInformationAlign64, // KEY_VALUE_PARTIAL_INFORMATION_ALIGN64 KeyValueLayerInformation, // KEY_VALUE_LAYER_INFORMATION MaxKeyValueInfoClass } KEY_VALUE_INFORMATION_CLASS; typedef struct _KEY_VALUE_BASIC_INFORMATION { ULONG TitleIndex; ULONG Type; ULONG NameLength; WCHAR Name[1]; } KEY_VALUE_BASIC_INFORMATION, *PKEY_VALUE_BASIC_INFORMATION; typedef struct _KEY_VALUE_FULL_INFORMATION { ULONG TitleIndex; ULONG Type; ULONG DataOffset; ULONG DataLength; ULONG NameLength; WCHAR Name[1]; // ... // UCHAR Data[1]; } KEY_VALUE_FULL_INFORMATION, *PKEY_VALUE_FULL_INFORMATION; typedef struct _KEY_VALUE_PARTIAL_INFORMATION { ULONG TitleIndex; ULONG Type; ULONG DataLength; UCHAR Data[1]; } KEY_VALUE_PARTIAL_INFORMATION, *PKEY_VALUE_PARTIAL_INFORMATION; typedef struct _KEY_VALUE_PARTIAL_INFORMATION_ALIGN64 { ULONG Type; ULONG DataLength; UCHAR Data[1]; } KEY_VALUE_PARTIAL_INFORMATION_ALIGN64, *PKEY_VALUE_PARTIAL_INFORMATION_ALIGN64; // private typedef struct _KEY_VALUE_LAYER_INFORMATION { ULONG IsTombstone; ULONG Reserved; } KEY_VALUE_LAYER_INFORMATION, *PKEY_VALUE_LAYER_INFORMATION; typedef struct _KEY_VALUE_ENTRY { PUNICODE_STRING ValueName; ULONG DataLength; ULONG DataOffset; ULONG Type; } KEY_VALUE_ENTRY, *PKEY_VALUE_ENTRY; typedef enum _REG_ACTION { KeyAdded, KeyRemoved, KeyModified } REG_ACTION; typedef struct _REG_NOTIFY_INFORMATION { ULONG NextEntryOffset; REG_ACTION Action; ULONG KeyLength; WCHAR Key[1]; } REG_NOTIFY_INFORMATION, *PREG_NOTIFY_INFORMATION; typedef struct _KEY_PID_ARRAY { HANDLE PID; UNICODE_STRING KeyName; } KEY_PID_ARRAY, *PKEY_PID_ARRAY; typedef struct _KEY_OPEN_SUBKEYS_INFORMATION { ULONG Count; KEY_PID_ARRAY KeyArray[1]; } KEY_OPEN_SUBKEYS_INFORMATION, *PKEY_OPEN_SUBKEYS_INFORMATION; typedef enum _SYSDBG_COMMAND { SysDbgQueryModuleInformation, SysDbgQueryTraceInformation, SysDbgSetTracepoint, SysDbgSetSpecialCall, SysDbgClearSpecialCalls, SysDbgQuerySpecialCalls, SysDbgBreakPoint, SysDbgQueryVersion, SysDbgReadVirtual, SysDbgWriteVirtual, SysDbgReadPhysical, SysDbgWritePhysical, SysDbgReadControlSpace, SysDbgWriteControlSpace, SysDbgReadIoSpace, SysDbgWriteIoSpace, SysDbgReadMsr, SysDbgWriteMsr, SysDbgReadBusData, SysDbgWriteBusData, SysDbgCheckLowMemory, SysDbgEnableKernelDebugger, SysDbgDisableKernelDebugger, SysDbgGetAutoKdEnable, SysDbgSetAutoKdEnable, SysDbgGetPrintBufferSize, SysDbgSetPrintBufferSize, SysDbgGetKdUmExceptionEnable, SysDbgSetKdUmExceptionEnable, SysDbgGetTriageDump, SysDbgGetKdBlockEnable, SysDbgSetKdBlockEnable, SysDbgRegisterForUmBreakInfo, SysDbgGetUmBreakPid, SysDbgClearUmBreakPid, SysDbgGetUmAttachPid, SysDbgClearUmAttachPid, SysDbgGetLiveKernelDump } SYSDBG_COMMAND, *PSYSDBG_COMMAND; typedef enum _DEBUGOBJECTINFOCLASS { DebugObjectFlags = 1, MaxDebugObjectInfoClass } DEBUGOBJECTINFOCLASS, *PDEBUGOBJECTINFOCLASS; //Source: http://processhacker.sourceforge.net typedef enum _FILE_INFORMATION_CLASS { FileDirectoryInformation = 1, // FILE_DIRECTORY_INFORMATION FileFullDirectoryInformation, // FILE_FULL_DIR_INFORMATION FileBothDirectoryInformation, // FILE_BOTH_DIR_INFORMATION FileBasicInformation, // FILE_BASIC_INFORMATION FileStandardInformation, // FILE_STANDARD_INFORMATION FileInternalInformation, // FILE_INTERNAL_INFORMATION FileEaInformation, // FILE_EA_INFORMATION FileAccessInformation, // FILE_ACCESS_INFORMATION FileNameInformation, // FILE_NAME_INFORMATION FileRenameInformation, // FILE_RENAME_INFORMATION // 10 FileLinkInformation, // FILE_LINK_INFORMATION FileNamesInformation, // FILE_NAMES_INFORMATION FileDispositionInformation, // FILE_DISPOSITION_INFORMATION FilePositionInformation, // FILE_POSITION_INFORMATION FileFullEaInformation, // FILE_FULL_EA_INFORMATION FileModeInformation, // FILE_MODE_INFORMATION FileAlignmentInformation, // FILE_ALIGNMENT_INFORMATION FileAllInformation, // FILE_ALL_INFORMATION FileAllocationInformation, // FILE_ALLOCATION_INFORMATION FileEndOfFileInformation, // FILE_END_OF_FILE_INFORMATION // 20 FileAlternateNameInformation, // FILE_NAME_INFORMATION FileStreamInformation, // FILE_STREAM_INFORMATION FilePipeInformation, // FILE_PIPE_INFORMATION FilePipeLocalInformation, // FILE_PIPE_LOCAL_INFORMATION FilePipeRemoteInformation, // FILE_PIPE_REMOTE_INFORMATION FileMailslotQueryInformation, // FILE_MAILSLOT_QUERY_INFORMATION FileMailslotSetInformation, // FILE_MAILSLOT_SET_INFORMATION FileCompressionInformation, // FILE_COMPRESSION_INFORMATION FileObjectIdInformation, // FILE_OBJECTID_INFORMATION FileCompletionInformation, // FILE_COMPLETION_INFORMATION // 30 FileMoveClusterInformation, // FILE_MOVE_CLUSTER_INFORMATION FileQuotaInformation, // FILE_QUOTA_INFORMATION FileReparsePointInformation, // FILE_REPARSE_POINT_INFORMATION FileNetworkOpenInformation, // FILE_NETWORK_OPEN_INFORMATION FileAttributeTagInformation, // FILE_ATTRIBUTE_TAG_INFORMATION FileTrackingInformation, // FILE_TRACKING_INFORMATION FileIdBothDirectoryInformation, // FILE_ID_BOTH_DIR_INFORMATION FileIdFullDirectoryInformation, // FILE_ID_FULL_DIR_INFORMATION FileValidDataLengthInformation, // FILE_VALID_DATA_LENGTH_INFORMATION FileShortNameInformation, // FILE_NAME_INFORMATION // 40 FileIoCompletionNotificationInformation, // FILE_IO_COMPLETION_NOTIFICATION_INFORMATION // since VISTA FileIoStatusBlockRangeInformation, // FILE_IOSTATUSBLOCK_RANGE_INFORMATION FileIoPriorityHintInformation, // FILE_IO_PRIORITY_HINT_INFORMATION FileSfioReserveInformation, // FILE_SFIO_RESERVE_INFORMATION FileSfioVolumeInformation, // FILE_SFIO_VOLUME_INFORMATION FileHardLinkInformation, // FILE_LINKS_INFORMATION FileProcessIdsUsingFileInformation, // FILE_PROCESS_IDS_USING_FILE_INFORMATION FileNormalizedNameInformation, // FILE_NAME_INFORMATION FileNetworkPhysicalNameInformation, // FILE_NETWORK_PHYSICAL_NAME_INFORMATION FileIdGlobalTxDirectoryInformation, // FILE_ID_GLOBAL_TX_DIR_INFORMATION // since WIN7 // 50 FileIsRemoteDeviceInformation, // FILE_IS_REMOTE_DEVICE_INFORMATION FileUnusedInformation, FileNumaNodeInformation, // FILE_NUMA_NODE_INFORMATION FileStandardLinkInformation, // FILE_STANDARD_LINK_INFORMATION FileRemoteProtocolInformation, // FILE_REMOTE_PROTOCOL_INFORMATION FileRenameInformationBypassAccessCheck, // (kernel-mode only); FILE_RENAME_INFORMATION // since WIN8 FileLinkInformationBypassAccessCheck, // (kernel-mode only); FILE_LINK_INFORMATION FileVolumeNameInformation, // FILE_VOLUME_NAME_INFORMATION FileIdInformation, // FILE_ID_INFORMATION FileIdExtdDirectoryInformation, // FILE_ID_EXTD_DIR_INFORMATION FileReplaceCompletionInformation, // FILE_COMPLETION_INFORMATION // since WINBLUE FileHardLinkFullIdInformation, // FILE_LINK_ENTRY_FULL_ID_INFORMATION FileIdExtdBothDirectoryInformation, // FILE_ID_EXTD_BOTH_DIR_INFORMATION // since THRESHOLD FileDispositionInformationEx, // FILE_DISPOSITION_INFO_EX // since REDSTONE FileRenameInformationEx, FileRenameInformationExBypassAccessCheck, FileDesiredStorageClassInformation, // FILE_DESIRED_STORAGE_CLASS_INFORMATION // since REDSTONE2 FileStatInformation, // FILE_STAT_INFORMATION FileMaximumInformation } FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS; typedef struct _SYSTEM_BASIC_INFORMATION { ULONG Reserved; ULONG TimerResolution; ULONG PageSize; ULONG NumberOfPhysicalPages; ULONG LowestPhysicalPageNumber; ULONG HighestPhysicalPageNumber; ULONG AllocationGranularity; ULONG_PTR MinimumUserModeAddress; ULONG_PTR MaximumUserModeAddress; ULONG_PTR ActiveProcessorsAffinityMask; CCHAR NumberOfProcessors; } SYSTEM_BASIC_INFORMATION, *PSYSTEM_BASIC_INFORMATION; typedef struct _FILE_PIPE_PEEK_BUFFER { ULONG NamedPipeState; ULONG ReadDataAvailable; ULONG NumberOfMessages; ULONG MessageLength; CHAR Data[1]; } FILE_PIPE_PEEK_BUFFER, *PFILE_PIPE_PEEK_BUFFER; typedef struct _NAMED_PIPE_CREATE_PARAMETERS { ULONG NamedPipeType; ULONG ReadMode; ULONG CompletionMode; ULONG MaximumInstances; ULONG InboundQuota; ULONG OutboundQuota; LARGE_INTEGER DefaultTimeout; BOOLEAN TimeoutSpecified; } NAMED_PIPE_CREATE_PARAMETERS, *PNAMED_PIPE_CREATE_PARAMETERS; typedef struct _FILE_NETWORK_OPEN_INFORMATION { LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; LARGE_INTEGER AllocationSize; LARGE_INTEGER EndOfFile; ULONG FileAttributes; } FILE_NETWORK_OPEN_INFORMATION, *PFILE_NETWORK_OPEN_INFORMATION; typedef struct _SYSTEM_TIMEOFDAY_INFORMATION { LARGE_INTEGER BootTime; LARGE_INTEGER CurrentTime; LARGE_INTEGER TimeZoneBias; ULONG TimeZoneId; ULONG Reserved; ULONGLONG BootTimeBias; ULONGLONG SleepTimeBias; } SYSTEM_TIMEOFDAY_INFORMATION, *PSYSTEM_TIMEOFDAY_INFORMATION; typedef struct _SYSTEM_CONSOLE_INFORMATION { ULONG DriverLoaded : 1; ULONG Spare : 31; } SYSTEM_CONSOLE_INFORMATION, *PSYSTEM_CONSOLE_INFORMATION; typedef struct _KSYSTEM_TIME { ULONG LowPart; LONG High1Time; LONG High2Time; } KSYSTEM_TIME, *PKSYSTEM_TIME; typedef struct _PROCESS_ACCESS_TOKEN { HANDLE Token; // Needs TOKEN_ASSIGN_PRIMARY access HANDLE Thread; // Handle to initial/only thread; needs THREAD_QUERY_INFORMATION access } PROCESS_ACCESS_TOKEN, *PPROCESS_ACCESS_TOKEN; #ifdef __cplusplus typedef enum _PS_PROTECTED_TYPE : UCHAR { PsProtectedTypeNone, PsProtectedTypeProtectedLight, PsProtectedTypeProtected, PsProtectedTypeMax } PS_PROTECTED_TYPE; #else typedef UCHAR PS_PROTECTED_TYPE; #endif #ifdef __cplusplus typedef enum _PS_PROTECTED_SIGNER : UCHAR { PsProtectedSignerNone, PsProtectedSignerAuthenticode, PsProtectedSignerCodeGen, PsProtectedSignerAntimalware, PsProtectedSignerLsa, PsProtectedSignerWindows, PsProtectedSignerWinTcb, PsProtectedSignerWinSystem, PsProtectedSignerApp, PsProtectedSignerMax } PS_PROTECTED_SIGNER; #else typedef UCHAR PS_PROTECTED_SIGNER; #endif typedef struct _PS_PROTECTION { union { struct { PS_PROTECTED_TYPE Type : 3; BOOLEAN Audit : 1; PS_PROTECTED_SIGNER Signer : 4; } s; UCHAR Level; }; } PS_PROTECTION, *PPS_PROTECTION; #define RTL_CREATE_ENVIRONMENT_TRANSLATE 0x1 // Translate from multi-byte to Unicode #define RTL_CREATE_ENVIRONMENT_TRANSLATE_FROM_OEM 0x2 // Translate from OEM to Unicode (Translate flag must also be set) #define RTL_CREATE_ENVIRONMENT_EMPTY 0x4 // Create empty environment block typedef struct _RTL_BUFFER { PUCHAR Buffer; PUCHAR StaticBuffer; SIZE_T Size; SIZE_T StaticSize; SIZE_T ReservedForAllocatedSize; // for future doubling PVOID ReservedForIMalloc; // for future pluggable growth } RTL_BUFFER, *PRTL_BUFFER; typedef struct _RTL_UNICODE_STRING_BUFFER { UNICODE_STRING String; RTL_BUFFER ByteBuffer; UCHAR MinimumStaticBufferForTerminalNul[sizeof(WCHAR)]; } RTL_UNICODE_STRING_BUFFER, *PRTL_UNICODE_STRING_BUFFER; typedef struct _RTL_USER_PROCESS_PARAMETERS { ULONG MaximumLength; ULONG Length; ULONG Flags; ULONG DebugFlags; HANDLE ConsoleHandle; ULONG ConsoleFlags; HANDLE StandardInput; HANDLE StandardOutput; HANDLE StandardError; CURDIR CurrentDirectory; UNICODE_STRING DllPath; UNICODE_STRING ImagePathName; UNICODE_STRING CommandLine; PWCHAR Environment; ULONG StartingX; ULONG StartingY; ULONG CountX; ULONG CountY; ULONG CountCharsX; ULONG CountCharsY; ULONG FillAttribute; ULONG WindowFlags; ULONG ShowWindowFlags; UNICODE_STRING WindowTitle; UNICODE_STRING DesktopInfo; UNICODE_STRING ShellInfo; UNICODE_STRING RuntimeData; RTL_DRIVE_LETTER_CURDIR CurrentDirectories[RTL_MAX_DRIVE_LETTERS]; ULONG_PTR EnvironmentSize; ULONG_PTR EnvironmentVersion; PVOID PackageDependencyData; ULONG ProcessGroupId; ULONG LoaderThreads; } RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS; #define RTL_USER_PROCESS_PARAMETERS_NORMALIZED 0x01 #define RTL_USER_PROCESS_PARAMETERS_PROFILE_USER 0x02 #define RTL_USER_PROCESS_PARAMETERS_PROFILE_KERNEL 0x04 #define RTL_USER_PROCESS_PARAMETERS_PROFILE_SERVER 0x08 #define RTL_USER_PROCESS_PARAMETERS_RESERVE_1MB 0x20 #define RTL_USER_PROCESS_PARAMETERS_RESERVE_16MB 0x40 #define RTL_USER_PROCESS_PARAMETERS_CASE_SENSITIVE 0x80 #define RTL_USER_PROCESS_PARAMETERS_DISABLE_HEAP_DECOMMIT 0x100 #define RTL_USER_PROCESS_PARAMETERS_DLL_REDIRECTION_LOCAL 0x1000 #define RTL_USER_PROCESS_PARAMETERS_APP_MANIFEST_PRESENT 0x2000 #define RTL_USER_PROCESS_PARAMETERS_IMAGE_KEY_MISSING 0x4000 #define RTL_USER_PROCESS_PARAMETERS_NX_OPTIN 0x20000 typedef struct _RTL_USER_PROCESS_INFORMATION { ULONG Length; HANDLE Process; HANDLE Thread; CLIENT_ID ClientId; SECTION_IMAGE_INFORMATION ImageInformation; } RTL_USER_PROCESS_INFORMATION, *PRTL_USER_PROCESS_INFORMATION; // Handle tag bits for PEB stdio file handles #define PEB_STDIO_HANDLE_NATIVE 0 #define PEB_STDIO_HANDLE_SUBSYS 1 #define PEB_STDIO_HANDLE_PM 2 #define PEB_STDIO_HANDLE_RESERVED 3 #define GDI_HANDLE_BUFFER_SIZE32 34 #define GDI_HANDLE_BUFFER_SIZE64 60 #ifndef _WIN64 #define GDI_HANDLE_BUFFER_SIZE GDI_HANDLE_BUFFER_SIZE32 #else #define GDI_HANDLE_BUFFER_SIZE GDI_HANDLE_BUFFER_SIZE64 #endif typedef ULONG GDI_HANDLE_BUFFER32[GDI_HANDLE_BUFFER_SIZE32]; typedef ULONG GDI_HANDLE_BUFFER64[GDI_HANDLE_BUFFER_SIZE64]; typedef ULONG GDI_HANDLE_BUFFER[GDI_HANDLE_BUFFER_SIZE]; #define FLS_MAXIMUM_AVAILABLE 128 #define TLS_MINIMUM_AVAILABLE 64 #define TLS_EXPANSION_SLOTS 1024 typedef struct _PEB_LDR_DATA { ULONG Length; BOOLEAN Initialized; HANDLE SsHandle; LIST_ENTRY InLoadOrderModuleList; LIST_ENTRY InMemoryOrderModuleList; LIST_ENTRY InInitializationOrderModuleList; PVOID EntryInProgress; BOOLEAN ShutdownInProgress; HANDLE ShutdownThreadId; } PEB_LDR_DATA, *PPEB_LDR_DATA; typedef struct _ACTIVATION_CONTEXT_STACK { struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME* ActiveFrame; LIST_ENTRY FrameListCache; ULONG Flags; ULONG NextCookieSequenceNumber; ULONG StackId; } ACTIVATION_CONTEXT_STACK, *PACTIVATION_CONTEXT_STACK; typedef struct _PEB { BOOLEAN InheritedAddressSpace; BOOLEAN ReadImageFileExecOptions; BOOLEAN BeingDebugged; union { BOOLEAN BitField; struct { BOOLEAN ImageUsesLargePages : 1; BOOLEAN IsProtectedProcess : 1; BOOLEAN IsImageDynamicallyRelocated : 1; BOOLEAN SkipPatchingUser32Forwarders : 1; BOOLEAN IsPackagedProcess : 1; BOOLEAN IsAppContainer : 1; BOOLEAN IsProtectedProcessLight : 1; BOOLEAN IsLongPathAwareProcess : 1; } s1; } u1; HANDLE Mutant; PVOID ImageBaseAddress; PPEB_LDR_DATA Ldr; PRTL_USER_PROCESS_PARAMETERS ProcessParameters; PVOID SubSystemData; PVOID ProcessHeap; PRTL_CRITICAL_SECTION FastPebLock; PVOID AtlThunkSListPtr; PVOID IFEOKey; union { ULONG CrossProcessFlags; struct { ULONG ProcessInJob : 1; ULONG ProcessInitializing : 1; ULONG ProcessUsingVEH : 1; ULONG ProcessUsingVCH : 1; ULONG ProcessUsingFTH : 1; ULONG ProcessPreviouslyThrottled : 1; ULONG ProcessCurrentlyThrottled : 1; ULONG ReservedBits0 : 25; } s2; } u2; union { PVOID KernelCallbackTable; PVOID UserSharedInfoPtr; } u3; ULONG SystemReserved[1]; ULONG AtlThunkSListPtr32; PVOID ApiSetMap; ULONG TlsExpansionCounter; PVOID TlsBitmap; ULONG TlsBitmapBits[2]; PVOID ReadOnlySharedMemoryBase; PVOID SharedData; // HotpatchInformation PVOID* ReadOnlyStaticServerData; PVOID AnsiCodePageData; // PCPTABLEINFO PVOID OemCodePageData; // PCPTABLEINFO PVOID UnicodeCaseTableData; // PNLSTABLEINFO ULONG NumberOfProcessors; ULONG NtGlobalFlag; LARGE_INTEGER CriticalSectionTimeout; SIZE_T HeapSegmentReserve; SIZE_T HeapSegmentCommit; SIZE_T HeapDeCommitTotalFreeThreshold; SIZE_T HeapDeCommitFreeBlockThreshold; ULONG NumberOfHeaps; ULONG MaximumNumberOfHeaps; PVOID* ProcessHeaps; // PHEAP PVOID GdiSharedHandleTable; PVOID ProcessStarterHelper; ULONG GdiDCAttributeList; PRTL_CRITICAL_SECTION LoaderLock; ULONG OSMajorVersion; ULONG OSMinorVersion; USHORT OSBuildNumber; USHORT OSCSDVersion; ULONG OSPlatformId; ULONG ImageSubsystem; ULONG ImageSubsystemMajorVersion; ULONG ImageSubsystemMinorVersion; ULONG_PTR ActiveProcessAffinityMask; GDI_HANDLE_BUFFER GdiHandleBuffer; PVOID PostProcessInitRoutine; PVOID TlsExpansionBitmap; ULONG TlsExpansionBitmapBits[32]; ULONG SessionId; ULARGE_INTEGER AppCompatFlags; ULARGE_INTEGER AppCompatFlagsUser; PVOID pShimData; PVOID AppCompatInfo; // APPCOMPAT_EXE_DATA UNICODE_STRING CSDVersion; PVOID ActivationContextData; // ACTIVATION_CONTEXT_DATA PVOID ProcessAssemblyStorageMap; // ASSEMBLY_STORAGE_MAP PVOID SystemDefaultActivationContextData; // ACTIVATION_CONTEXT_DATA PVOID SystemAssemblyStorageMap; // ASSEMBLY_STORAGE_MAP SIZE_T MinimumStackCommit; PVOID* FlsCallback; LIST_ENTRY FlsListHead; PVOID FlsBitmap; ULONG FlsBitmapBits[FLS_MAXIMUM_AVAILABLE / (sizeof(ULONG) * 8)]; ULONG FlsHighIndex; PVOID WerRegistrationData; PVOID WerShipAssertPtr; PVOID pUnused; // pContextData PVOID pImageHeaderHash; union { ULONG TracingFlags; struct { ULONG HeapTracingEnabled : 1; ULONG CritSecTracingEnabled : 1; ULONG LibLoaderTracingEnabled : 1; ULONG SpareTracingBits : 29; } s3; } u4; ULONGLONG CsrServerReadOnlySharedMemoryBase; PVOID TppWorkerpListLock; LIST_ENTRY TppWorkerpList; PVOID WaitOnAddressHashTable[128]; PVOID TelemetryCoverageHeader; // REDSTONE3 ULONG CloudFileFlags; } PEB, *PPEB; #define GDI_BATCH_BUFFER_SIZE 310 typedef struct _GDI_TEB_BATCH { ULONG Offset; ULONG_PTR HDC; ULONG Buffer[GDI_BATCH_BUFFER_SIZE]; } GDI_TEB_BATCH, *PGDI_TEB_BATCH; typedef struct _TEB_ACTIVE_FRAME_CONTEXT { ULONG Flags; PSTR FrameName; } TEB_ACTIVE_FRAME_CONTEXT, *PTEB_ACTIVE_FRAME_CONTEXT; typedef struct _TEB_ACTIVE_FRAME { ULONG Flags; struct _TEB_ACTIVE_FRAME* Previous; PTEB_ACTIVE_FRAME_CONTEXT Context; } TEB_ACTIVE_FRAME, *PTEB_ACTIVE_FRAME; typedef struct _TEB { NT_TIB NtTib; PVOID EnvironmentPointer; CLIENT_ID ClientId; PVOID ActiveRpcHandle; PVOID ThreadLocalStoragePointer; PPEB ProcessEnvironmentBlock; ULONG LastErrorValue; ULONG CountOfOwnedCriticalSections; PVOID CsrClientThread; PVOID Win32ThreadInfo; ULONG User32Reserved[26]; ULONG UserReserved[5]; PVOID WOW32Reserved; LCID CurrentLocale; ULONG FpSoftwareStatusRegister; PVOID ReservedForDebuggerInstrumentation[16]; #ifdef _WIN64 PVOID SystemReserved1[30]; #else PVOID SystemReserved1[26]; #endif CHAR PlaceholderCompatibilityMode; CHAR PlaceholderReserved[11]; ULONG ProxiedProcessId; ACTIVATION_CONTEXT_STACK ActivationStack; UCHAR WorkingOnBehalfTicket[8]; NTSTATUS ExceptionCode; PACTIVATION_CONTEXT_STACK ActivationContextStackPointer; ULONG_PTR InstrumentationCallbackSp; ULONG_PTR InstrumentationCallbackPreviousPc; ULONG_PTR InstrumentationCallbackPreviousSp; #ifdef _WIN64 ULONG TxFsContext; #endif BOOLEAN InstrumentationCallbackDisabled; #ifndef _WIN64 UCHAR SpareBytes[23]; ULONG TxFsContext; #endif GDI_TEB_BATCH GdiTebBatch; CLIENT_ID RealClientId; HANDLE GdiCachedProcessHandle; ULONG GdiClientPID; ULONG GdiClientTID; PVOID GdiThreadLocalInfo; ULONG_PTR Win32ClientInfo[62]; PVOID glDispatchTable[233]; ULONG_PTR glReserved1[29]; PVOID glReserved2; PVOID glSectionInfo; PVOID glSection; PVOID glTable; PVOID glCurrentRC; PVOID glContext; NTSTATUS LastStatusValue; UNICODE_STRING StaticUnicodeString; WCHAR StaticUnicodeBuffer[261]; PVOID DeallocationStack; PVOID TlsSlots[64]; LIST_ENTRY TlsLinks; PVOID Vdm; PVOID ReservedForNtRpc; PVOID DbgSsReserved[2]; ULONG HardErrorMode; #ifdef _WIN64 PVOID Instrumentation[11]; #else PVOID Instrumentation[9]; #endif GUID ActivityId; PVOID SubProcessTag; PVOID PerflibData; PVOID EtwTraceData; PVOID WinSockData; ULONG GdiBatchCount; union { PROCESSOR_NUMBER CurrentIdealProcessor; ULONG IdealProcessorValue; struct { UCHAR ReservedPad0; UCHAR ReservedPad1; UCHAR ReservedPad2; UCHAR IdealProcessor; } s1; } u1; ULONG GuaranteedStackBytes; PVOID ReservedForPerf; PVOID ReservedForOle; ULONG WaitingOnLoaderLock; PVOID SavedPriorityState; ULONG_PTR ReservedForCodeCoverage; PVOID ThreadPoolData; PVOID* TlsExpansionSlots; #ifdef _WIN64 PVOID DeallocationBStore; PVOID BStoreLimit; #endif ULONG MuiGeneration; ULONG IsImpersonating; PVOID NlsCache; PVOID pShimData; USHORT HeapVirtualAffinity; USHORT LowFragHeapDataSlot; HANDLE CurrentTransactionHandle; PTEB_ACTIVE_FRAME ActiveFrame; PVOID FlsData; PVOID PreferredLanguages; PVOID UserPrefLanguages; PVOID MergedPrefLanguages; ULONG MuiImpersonation; union { USHORT CrossTebFlags; USHORT SpareCrossTebBits : 16; } u2; union { USHORT SameTebFlags; struct { USHORT SafeThunkCall : 1; USHORT InDebugPrint : 1; USHORT HasFiberData : 1; USHORT SkipThreadAttach : 1; USHORT WerInShipAssertCode : 1; USHORT RanProcessInit : 1; USHORT ClonedThread : 1; USHORT SuppressDebugMsg : 1; USHORT DisableUserStackWalk : 1; USHORT RtlExceptionAttached : 1; USHORT InitialThread : 1; USHORT SessionAware : 1; USHORT LoadOwner : 1; USHORT LoaderWorker : 1; USHORT SkipLoaderInit : 1; USHORT SpareSameTebBits : 1; } s2; } u3; PVOID TxnScopeEnterCallback; PVOID TxnScopeExitCallback; PVOID TxnScopeContext; ULONG LockCount; LONG WowTebOffset; PVOID ResourceRetValue; PVOID ReservedForWdf; ULONGLONG ReservedForCrt; GUID EffectiveContainerId; } TEB, *PTEB; typedef enum _ALTERNATIVE_ARCHITECTURE_TYPE { StandardDesign, NEC98x86, EndAlternatives } ALTERNATIVE_ARCHITECTURE_TYPE; #define PROCESSOR_FEATURE_MAX 64 #define MAX_WOW64_SHARED_ENTRIES 16 #define NX_SUPPORT_POLICY_ALWAYSOFF 0 #define NX_SUPPORT_POLICY_ALWAYSON 1 #define NX_SUPPORT_POLICY_OPTIN 2 #define NX_SUPPORT_POLICY_OPTOUT 3 #pragma pack(push, 4) typedef struct _KUSER_SHARED_DATA { ULONG TickCountLowDeprecated; ULONG TickCountMultiplier; volatile KSYSTEM_TIME InterruptTime; volatile KSYSTEM_TIME SystemTime; volatile KSYSTEM_TIME TimeZoneBias; USHORT ImageNumberLow; USHORT ImageNumberHigh; WCHAR NtSystemRoot[260]; ULONG MaxStackTraceDepth; ULONG CryptoExponent; ULONG TimeZoneId; ULONG LargePageMinimum; ULONG AitSamplingValue; ULONG AppCompatFlag; ULONGLONG RNGSeedVersion; ULONG GlobalValidationRunlevel; LONG TimeZoneBiasStamp; ULONG NtBuildNumber; ULONG NtProductType; BOOLEAN ProductTypeIsValid; UCHAR Reserved0[1]; USHORT NativeProcessorArchitecture; ULONG NtMajorVersion; ULONG NtMinorVersion; BOOLEAN ProcessorFeatures[PROCESSOR_FEATURE_MAX]; ULONG Reserved1; ULONG Reserved3; volatile ULONG TimeSlip; ALTERNATIVE_ARCHITECTURE_TYPE AlternativeArchitecture; ULONG BootId; LARGE_INTEGER SystemExpirationDate; ULONG SuiteMask; BOOLEAN KdDebuggerEnabled; union { UCHAR MitigationPolicies; struct { UCHAR NXSupportPolicy : 2; UCHAR SEHValidationPolicy : 2; UCHAR CurDirDevicesSkippedForDlls : 2; UCHAR Reserved : 2; } s1; } u1; UCHAR Reserved6[2]; volatile ULONG ActiveConsoleId; volatile ULONG DismountCount; ULONG ComPlusPackage; ULONG LastSystemRITEventTickCount; ULONG NumberOfPhysicalPages; BOOLEAN SafeBootMode; UCHAR VirtualizationFlags; UCHAR Reserved12[2]; union { ULONG SharedDataFlags; struct { ULONG DbgErrorPortPresent : 1; ULONG DbgElevationEnabled : 1; ULONG DbgVirtEnabled : 1; ULONG DbgInstallerDetectEnabled : 1; ULONG DbgLkgEnabled : 1; ULONG DbgDynProcessorEnabled : 1; ULONG DbgConsoleBrokerEnabled : 1; ULONG DbgSecureBootEnabled : 1; ULONG DbgMultiSessionSku : 1; ULONG DbgMultiUsersInSessionSku : 1; ULONG SpareBits : 22; } s2; } u2; ULONG DataFlagsPad[1]; ULONGLONG TestRetInstruction; LONGLONG QpcFrequency; ULONG SystemCall; ULONG SystemCallPad0; ULONGLONG SystemCallPad[2]; union { volatile KSYSTEM_TIME TickCount; volatile ULONG64 TickCountQuad; ULONG ReservedTickCountOverlay[3]; }; ULONG TickCountPad[1]; ULONG Cookie; ULONG CookiePad[1]; LONGLONG ConsoleSessionForegroundProcessId; ULONGLONG TimeUpdateLock; ULONGLONG BaselineSystemTimeQpc; ULONGLONG BaselineInterruptTimeQpc; ULONGLONG QpcSystemTimeIncrement; ULONGLONG QpcInterruptTimeIncrement; UCHAR QpcSystemTimeIncrementShift; UCHAR QpcInterruptTimeIncrementShift; USHORT UnparkedProcessorCount; ULONG EnclaveFeatureMask[4]; ULONG Reserved8; USHORT UserModeGlobalLogger[16]; ULONG ImageFileExecutionOptions; ULONG LangGenerationCount; ULONGLONG Reserved4; volatile ULONG64 InterruptTimeBias; volatile ULONG64 QpcBias; ULONG ActiveProcessorCount; volatile UCHAR ActiveGroupCount; UCHAR Reserved9; union { USHORT QpcData; struct { UCHAR QpcBypassEnabled : 1; UCHAR QpcShift : 1; } s3; } u3; LARGE_INTEGER TimeZoneBiasEffectiveStart; LARGE_INTEGER TimeZoneBiasEffectiveEnd; XSTATE_CONFIGURATION XState; } KUSER_SHARED_DATA, *PKUSER_SHARED_DATA; #pragma pack(pop) #ifdef __cplusplus static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TickCountMultiplier) == 0x4, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, InterruptTime) == 0x8, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, SystemTime) == 0x14, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TimeZoneBias) == 0x20, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ImageNumberLow) == 0x2c, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ImageNumberHigh) == 0x2e, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, NtSystemRoot) == 0x30, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, MaxStackTraceDepth) == 0x238, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, CryptoExponent) == 0x23c, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TimeZoneId) == 0x240, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, LargePageMinimum) == 0x244, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, NtProductType) == 0x264, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ProductTypeIsValid) == 0x268, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, NtMajorVersion) == 0x26c, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, NtMinorVersion) == 0x270, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ProcessorFeatures) == 0x274, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved1) == 0x2b4, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved3) == 0x2b8, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TimeSlip) == 0x2bc, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, AlternativeArchitecture) == 0x2c0, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, SystemExpirationDate) == 0x2c8, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, SuiteMask) == 0x2d0, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, KdDebuggerEnabled) == 0x2d4, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ActiveConsoleId) == 0x2d8, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, DismountCount) == 0x2dc, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ComPlusPackage) == 0x2e0, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, LastSystemRITEventTickCount) == 0x2e4, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, NumberOfPhysicalPages) == 0x2e8, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, SafeBootMode) == 0x2ec, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TestRetInstruction) == 0x2f8, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, SystemCallPad) == 0x310, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TickCount) == 0x320, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TickCountQuad) == 0x320, "Offset check"); static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, XState) == 0x3d8, "Offset check"); #endif #if !defined(_KERNEL_MODE) && !defined(KERNELMODE) #define USER_SHARED_DATA 0x7FFE0000 #define SharedUserData ((KUSER_SHARED_DATA * const)USER_SHARED_DATA) #else #if defined(_M_IX86) #define KI_USER_SHARED_DATA 0xFFDF0000 #elif defined (_M_AMD64) #define KI_USER_SHARED_DATA 0xFFFFF78000000000Ui64 #elif defined (_M_ARM) #define KI_USER_SHARED_DATA 0xFFFF9000 #elif defined(M_ARM64) #define KI_USER_SHARED_DATA 0xFFFFF78000000000Ui64 #endif #define SharedUserData ((KUSER_SHARED_DATA * const)KI_USER_SHARED_DATA) #endif typedef struct _PROCESS_BASIC_INFORMATION { NTSTATUS ExitStatus; PPEB PebBaseAddress; ULONG_PTR AffinityMask; KPRIORITY BasePriority; HANDLE UniqueProcessId; HANDLE InheritedFromUniqueProcessId; } PROCESS_BASIC_INFORMATION, *PPROCESS_BASIC_INFORMATION; typedef struct _PROCESS_EXTENDED_BASIC_INFORMATION { SIZE_T Size; // Set to sizeof structure on input PROCESS_BASIC_INFORMATION BasicInfo; union { ULONG Flags; struct { ULONG IsProtectedProcess : 1; ULONG IsWow64Process : 1; ULONG IsProcessDeleting : 1; ULONG IsCrossSessionCreate : 1; ULONG IsFrozen : 1; ULONG IsBackground : 1; ULONG IsStronglyNamed : 1; ULONG IsSecureProcess : 1; ULONG IsSubsystemProcess : 1; ULONG SpareBits : 23; } s; } u; } PROCESS_EXTENDED_BASIC_INFORMATION, *PPROCESS_EXTENDED_BASIC_INFORMATION; typedef struct _SYSTEM_EXTENDED_THREAD_INFORMATION { SYSTEM_THREAD_INFORMATION ThreadInfo; PVOID StackBase; PVOID StackLimit; PVOID Win32StartAddress; PTEB TebBase; // Since Vista ULONG_PTR Reserved2; ULONG_PTR Reserved3; ULONG_PTR Reserved4; } SYSTEM_EXTENDED_THREAD_INFORMATION, *PSYSTEM_EXTENDED_THREAD_INFORMATION; #ifndef FIELD_OFFSET #if !defined(__clang__) #define FIELD_OFFSET(type, field) ((LONG)(LONG_PTR)&(((type *)0)->field)) #else #define FIELD_OFFSET(type, field) ((LONG)__builtin_offsetof(type, field)) #endif #endif #ifndef UFIELD_OFFSET #if !defined(__clang__) #define UFIELD_OFFSET(type, field) ((ULONG)(LONG_PTR)&(((type *)0)->field)) #else #define UFIELD_OFFSET(type, field) ((ULONG)__builtin_offsetof(type, field)) #endif #endif #define PTR_ADD_OFFSET(Pointer, Offset) ((PVOID)((ULONG_PTR)(Pointer) + (ULONG_PTR)(Offset))) #define PTR_SUB_OFFSET(Pointer, Offset) ((PVOID)((ULONG_PTR)(Pointer) - (ULONG_PTR)(Offset))) #define ALIGN_DOWN_BY(Address, Align) ((ULONG_PTR)(Address) & ~(Align - 1)) #define ALIGN_DOWN_POINTER_BY(Pointer, Align) ((PVOID)ALIGN_DOWN_BY(Pointer, Align)) #define ALIGN_DOWN_POINTER(Pointer, Type) ((PVOID)ALIGN_DOWN(Pointer, Type)) #define ALIGN_UP_BY(Address, Align) (((ULONG_PTR)(Address) + (Align) - 1) & ~((Align) - 1)) #define ALIGN_UP_POINTER_BY(Pointer, Align) ((PVOID)ALIGN_UP_BY(Pointer, Align)) #define ALIGN_UP_POINTER(Pointer, Type) ((PVOID)ALIGN_UP(Pointer, Type)) #define InitializeObjectAttributes( p, n, a, r, s ) { \ (p)->Length = sizeof( OBJECT_ATTRIBUTES ); \ (p)->RootDirectory = r; \ (p)->Attributes = a; \ (p)->ObjectName = n; \ (p)->SecurityDescriptor = s; \ (p)->SecurityQualityOfService = NULL; \ } #define OBJ_INHERIT 0x00000002L #define OBJ_PERMANENT 0x00000010L #define OBJ_EXCLUSIVE 0x00000020L #define OBJ_CASE_INSENSITIVE 0x00000040L #define OBJ_OPENIF 0x00000080L #define OBJ_OPENLINK 0x00000100L #define OBJ_KERNEL_HANDLE 0x00000200L #define OBJ_FORCE_ACCESS_CHECK 0x00000400L #define OBJ_IGNORE_IMPERSONATED_DEVICEMAP 0x00000800 #define OBJ_DONT_REPARSE 0x00001000 #define OBJ_VALID_ATTRIBUTES 0x00001FF2 #if NTDDI_VERSION >= NTDDI_VISTA #define THREAD_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \ 0xFFFF) #else #define THREAD_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \ 0x3FF) #endif #define THREAD_CREATE_FLAGS_CREATE_SUSPENDED 0x00000001 #define THREAD_CREATE_FLAGS_SUPPRESS_DLLMAINS 0x00000002 #define THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER 0x00000004 #define THREAD_CREATE_FLAGS_HAS_SECURITY_DESCRIPTOR 0x00000010 // ? #define THREAD_CREATE_FLAGS_ACCESS_CHECK_IN_TARGET 0x00000020 // ? #define THREAD_CREATE_FLAGS_INITIAL_THREAD 0x00000080 #define DEBUG_READ_EVENT 0x0001 #define DEBUG_PROCESS_ASSIGN 0x0002 #define DEBUG_SET_INFORMATION 0x0004 #define DEBUG_QUERY_INFORMATION 0x0008 #define DEBUG_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \ DEBUG_READ_EVENT | DEBUG_PROCESS_ASSIGN | DEBUG_SET_INFORMATION | \ DEBUG_QUERY_INFORMATION) #define DEBUG_KILL_ON_CLOSE 0x1 #ifndef IO_COMPLETION_QUERY_STATE #define IO_COMPLETION_QUERY_STATE 0x0001 #endif #ifndef IO_COMPLETION_MODIFY_STATE #define IO_COMPLETION_MODIFY_STATE 0x0002 #endif #ifndef IO_COMPLETION_ALL_ACCESS #define IO_COMPLETION_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \ IO_COMPLETION_QUERY_STATE | IO_COMPLETION_MODIFY_STATE) #endif #ifndef SEMAPHORE_ALL_ACCESS #define SEMAPHORE_QUERY_STATE 0x0001 #define SEMAPHORE_MODIFY_STATE 0x0002 #define SEMAPHORE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \ SEMAPHORE_QUERY_STATE | SEMAPHORE_MODIFY_STATE) #endif #ifndef MUTANT_ALL_ACCESS #define MUTANT_QUERY_STATE 0x0001 #define MUTANT_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \ MUTANT_QUERY_STATE) #endif #ifndef EVENT_ALL_ACCESS #define EVENT_QUERY_STATE 0x0001 #define EVENT_MODIFY_STATE 0x0002 #define EVENT_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \ EVENT_QUERY_STATE | EVENT_MODIFY_STATE) #endif #define KEYEDEVENT_WAIT 0x0001 #define KEYEDEVENT_WAKE 0x0002 #define KEYEDEVENT_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \ KEYEDEVENT_WAIT | KEYEDEVENT_WAKE) #define DIRECTORY_QUERY 0x0001 #define DIRECTORY_TRAVERSE 0x0002 #define DIRECTORY_CREATE_OBJECT 0x0004 #define DIRECTORY_CREATE_SUBDIRECTORY 0x0008 #define DIRECTORY_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \ DIRECTORY_QUERY | DIRECTORY_TRAVERSE | \ DIRECTORY_CREATE_OBJECT | DIRECTORY_CREATE_SUBDIRECTORY) #define SYMBOLIC_LINK_QUERY 0x0001 #define SYMBOLIC_LINK_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \ SYMBOLIC_LINK_QUERY) #ifndef TOKEN_ALL_ACCESS #define TOKEN_ASSIGN_PRIMARY 0x0001 #define TOKEN_DUPLICATE 0x0002 #define TOKEN_IMPERSONATE 0x0004 #define TOKEN_QUERY 0x0008 #define TOKEN_QUERY_SOURCE 0x0010 #define TOKEN_ADJUST_PRIVILEGES 0x0020 #define TOKEN_ADJUST_GROUPS 0x0040 #define TOKEN_ADJUST_DEFAULT 0x0080 #define TOKEN_ADJUST_SESSIONID 0x0100 #define TOKEN_ALL_ACCESS_P (STANDARD_RIGHTS_REQUIRED | \ TOKEN_ASSIGN_PRIMARY | \ TOKEN_DUPLICATE | \ TOKEN_IMPERSONATE | \ TOKEN_QUERY | \ TOKEN_QUERY_SOURCE | \ TOKEN_ADJUST_PRIVILEGES | \ TOKEN_ADJUST_GROUPS | \ TOKEN_ADJUST_DEFAULT) #define TOKEN_ALL_ACCESS (TOKEN_ALL_ACCESS_P | \ TOKEN_ADJUST_SESSIONID) #endif #define WORKER_FACTORY_RELEASE_WORKER 0x0001 #define WORKER_FACTORY_WAIT 0x0002 #define WORKER_FACTORY_SET_INFORMATION 0x0004 #define WORKER_FACTORY_QUERY_INFORMATION 0x0008 #define WORKER_FACTORY_READY_WORKER 0x0010 #define WORKER_FACTORY_SHUTDOWN 0x0020 #define WORKER_FACTORY_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \ WORKER_FACTORY_RELEASE_WORKER | \ WORKER_FACTORY_WAIT | \ WORKER_FACTORY_SET_INFORMATION | \ WORKER_FACTORY_QUERY_INFORMATION | \ WORKER_FACTORY_READY_WORKER | \ WORKER_FACTORY_SHUTDOWN) #define NtCurrentProcess ((HANDLE)(LONG_PTR)-1) #define NtCurrentThread ((HANDLE)(LONG_PTR)-2) #define NtCurrentPeb() (NtCurrentTeb()->ProcessEnvironmentBlock) #define NtCurrentProcessId() (NtCurrentTeb()->ClientId.UniqueProcess) #define NtCurrentThreadId() (NtCurrentTeb()->ClientId.UniqueThread) #define RtlProcessHeap() (NtCurrentPeb()->ProcessHeap) typedef struct _RTL_HEAP_ENTRY { SIZE_T Size; USHORT Flags; USHORT AllocatorBackTraceIndex; union { struct { SIZE_T Settable; ULONG Tag; } s1; struct { SIZE_T CommittedSize; PVOID FirstBlock; } s2; } u; } RTL_HEAP_ENTRY, *PRTL_HEAP_ENTRY; #define RTL_HEAP_BUSY (USHORT)0x0001 #define RTL_HEAP_SEGMENT (USHORT)0x0002 #define RTL_HEAP_SETTABLE_VALUE (USHORT)0x0010 #define RTL_HEAP_SETTABLE_FLAG1 (USHORT)0x0020 #define RTL_HEAP_SETTABLE_FLAG2 (USHORT)0x0040 #define RTL_HEAP_SETTABLE_FLAG3 (USHORT)0x0080 #define RTL_HEAP_SETTABLE_FLAGS (USHORT)0x00e0 #define RTL_HEAP_UNCOMMITTED_RANGE (USHORT)0x0100 #define RTL_HEAP_PROTECTED_ENTRY (USHORT)0x0200 typedef struct _RTL_HEAP_TAG { ULONG NumberOfAllocations; ULONG NumberOfFrees; SIZE_T BytesAllocated; USHORT TagIndex; USHORT CreatorBackTraceIndex; WCHAR TagName[24]; } RTL_HEAP_TAG, *PRTL_HEAP_TAG; typedef struct _RTL_HEAP_INFORMATION { PVOID BaseAddress; ULONG Flags; USHORT EntryOverhead; USHORT CreatorBackTraceIndex; SIZE_T BytesAllocated; SIZE_T BytesCommitted; ULONG NumberOfTags; ULONG NumberOfEntries; ULONG NumberOfPseudoTags; ULONG PseudoTagGranularity; ULONG Reserved[5]; PRTL_HEAP_TAG Tags; PRTL_HEAP_ENTRY Entries; } RTL_HEAP_INFORMATION, *PRTL_HEAP_INFORMATION; typedef struct _RTL_PROCESS_HEAPS { ULONG NumberOfHeaps; RTL_HEAP_INFORMATION Heaps[1]; } RTL_PROCESS_HEAPS, *PRTL_PROCESS_HEAPS; typedef NTSTATUS (NTAPI* PRTL_HEAP_COMMIT_ROUTINE)( _In_ PVOID Base, _Inout_ PVOID* CommitAddress, _Inout_ PSIZE_T CommitSize ); typedef struct _RTL_HEAP_PARAMETERS { ULONG Length; SIZE_T SegmentReserve; SIZE_T SegmentCommit; SIZE_T DeCommitFreeBlockThreshold; SIZE_T DeCommitTotalFreeThreshold; SIZE_T MaximumAllocationSize; SIZE_T VirtualMemoryThreshold; SIZE_T InitialCommit; SIZE_T InitialReserve; PRTL_HEAP_COMMIT_ROUTINE CommitRoutine; SIZE_T Reserved[2]; } RTL_HEAP_PARAMETERS, *PRTL_HEAP_PARAMETERS; #define HEAP_SETTABLE_USER_VALUE 0x00000100 #define HEAP_SETTABLE_USER_FLAG1 0x00000200 #define HEAP_SETTABLE_USER_FLAG2 0x00000400 #define HEAP_SETTABLE_USER_FLAG3 0x00000800 #define HEAP_SETTABLE_USER_FLAGS 0x00000e00 #define HEAP_CLASS_0 0x00000000 // Process heap #define HEAP_CLASS_1 0x00001000 // Private heap #define HEAP_CLASS_2 0x00002000 // Kernel heap #define HEAP_CLASS_3 0x00003000 // GDI heap #define HEAP_CLASS_4 0x00004000 // User heap #define HEAP_CLASS_5 0x00005000 // Console heap #define HEAP_CLASS_6 0x00006000 // User desktop heap #define HEAP_CLASS_7 0x00007000 // CSR shared heap #define HEAP_CLASS_8 0x00008000 // CSR port heap #define HEAP_CLASS_MASK 0x0000f000 typedef struct _RTL_HEAP_TAG_INFO { ULONG NumberOfAllocations; ULONG NumberOfFrees; SIZE_T BytesAllocated; } RTL_HEAP_TAG_INFO, *PRTL_HEAP_TAG_INFO; #define RTL_HEAP_MAKE_TAG HEAP_MAKE_TAG_FLAGS typedef struct _RTL_HEAP_WALK_ENTRY { PVOID DataAddress; SIZE_T DataSize; UCHAR OverheadBytes; UCHAR SegmentIndex; USHORT Flags; union { struct { SIZE_T Settable; USHORT TagIndex; USHORT AllocatorBackTraceIndex; ULONG Reserved[2]; } Block; struct { ULONG CommittedSize; ULONG UnCommittedSize; PVOID FirstEntry; PVOID LastEntry; } Segment; }; } RTL_HEAP_WALK_ENTRY, *PRTL_HEAP_WALK_ENTRY; // HEAP_INFORMATION_CLASS. winnt.h is incomplete #define HeapCompatibilityInformation 0x0 // q; s: ULONG #define HeapEnableTerminationOnCorruption 0x1 // q; s: NULL #define HeapExtendedInformation 0x2 // q; s: HEAP_EXTENDED_INFORMATION #define HeapOptimizeResources 0x3 // q; s: HEAP_OPTIMIZE_RESOURCES_INFORMATION #define HeapTaggingInformation 0x4 #define HeapStackDatabase 0x5 #define HeapDetailedFailureInformation 0x80000001 #define HeapSetDebuggingInformation 0x80000002 // q; s: HEAP_DEBUGGING_INFORMATION typedef struct _PROCESS_HEAP_INFORMATION { ULONG_PTR ReserveSize; ULONG_PTR CommitSize; ULONG NumberOfHeaps; ULONG_PTR FirstHeapInformationOffset; } PROCESS_HEAP_INFORMATION, *PPROCESS_HEAP_INFORMATION; typedef struct _HEAP_INFORMATION { ULONG_PTR Address; ULONG Mode; ULONG_PTR ReserveSize; ULONG_PTR CommitSize; ULONG_PTR FirstRegionInformationOffset; ULONG_PTR NextHeapInformationOffset; } HEAP_INFORMATION, *PHEAP_INFORMATION; typedef struct _HEAP_EXTENDED_INFORMATION { HANDLE Process; ULONG_PTR Heap; ULONG Level; PVOID CallbackRoutine; PVOID CallbackContext; PROCESS_HEAP_INFORMATION ProcessHeapInformation; HEAP_INFORMATION HeapInformation; } HEAP_EXTENDED_INFORMATION, *PHEAP_EXTENDED_INFORMATION; typedef NTSTATUS (NTAPI* PRTL_HEAP_LEAK_ENUMERATION_ROUTINE)( _In_ LONG Reserved, _In_ PVOID HeapHandle, _In_ PVOID BaseAddress, _In_ SIZE_T BlockSize, _In_ ULONG StackTraceDepth, _In_ PVOID* StackTrace ); typedef struct _HEAP_DEBUGGING_INFORMATION { PVOID InterceptorFunction; USHORT InterceptorValue; ULONG ExtendedOptions; ULONG StackTraceDepth; SIZE_T MinTotalBlockSize; SIZE_T MaxTotalBlockSize; PRTL_HEAP_LEAK_ENUMERATION_ROUTINE HeapLeakEnumerationRoutine; } HEAP_DEBUGGING_INFORMATION, *PHEAP_DEBUGGING_INFORMATION; typedef NTSTATUS (NTAPI* PRTL_ENUM_HEAPS_ROUTINE)( _In_ PVOID HeapHandle, _In_ PVOID Parameter ); typedef NTSTATUS (NTAPI* PUSER_THREAD_START_ROUTINE)( _In_ PVOID ThreadParameter ); #define LDR_FORMAT_MESSAGE_FROM_SYSTEM_MESSAGE_TABLE 11 #define RTL_ERRORMODE_NOGPFAULTERRORBOX 0x0020 #define RTL_ERRORMODE_NOOPENFILEERRORBOX 0x0040 #define RTL_ACQUIRE_PRIVILEGE_REVERT 0x00000001 #define RTL_ACQUIRE_PRIVILEGE_PROCESS 0x00000002 typedef VOID (NTAPI* PLDR_IMPORT_MODULE_CALLBACK)( _In_ PVOID Parameter, _In_ PSTR ModuleName ); typedef struct _LDR_IMPORT_CALLBACK_INFO { PLDR_IMPORT_MODULE_CALLBACK ImportCallbackRoutine; PVOID ImportCallbackParameter; } LDR_IMPORT_CALLBACK_INFO, *PLDR_IMPORT_CALLBACK_INFO; typedef struct _LDR_SECTION_INFO { HANDLE SectionHandle; ACCESS_MASK DesiredAccess; POBJECT_ATTRIBUTES ObjectAttributes; ULONG SectionPageProtection; ULONG AllocationAttributes; } LDR_SECTION_INFO, *PLDR_SECTION_INFO; typedef struct _LDR_VERIFY_IMAGE_INFO { ULONG Size; ULONG Flags; LDR_IMPORT_CALLBACK_INFO CallbackInfo; LDR_SECTION_INFO SectionInfo; USHORT ImageCharacteristics; } LDR_VERIFY_IMAGE_INFO, *PLDR_VERIFY_IMAGE_INFO; typedef enum _SEMAPHORE_INFORMATION_CLASS { SemaphoreBasicInformation } SEMAPHORE_INFORMATION_CLASS; typedef struct _SEMAPHORE_BASIC_INFORMATION { LONG CurrentCount; LONG MaximumCount; } SEMAPHORE_BASIC_INFORMATION, *PSEMAPHORE_BASIC_INFORMATION; typedef enum _TIMER_INFORMATION_CLASS { TimerBasicInformation } TIMER_INFORMATION_CLASS; typedef struct _TIMER_BASIC_INFORMATION { LARGE_INTEGER RemainingTime; BOOLEAN TimerState; } TIMER_BASIC_INFORMATION, *PTIMER_BASIC_INFORMATION; typedef VOID (NTAPI* PTIMER_APC_ROUTINE)( _In_ PVOID TimerContext, _In_ ULONG TimerLowValue, _In_ LONG TimerHighValue ); typedef enum _TIMER_SET_INFORMATION_CLASS { TimerSetCoalescableTimer, MaxTimerInfoClass } TIMER_SET_INFORMATION_CLASS; typedef struct _TIMER_SET_COALESCABLE_TIMER_INFO { _In_ LARGE_INTEGER DueTime; _In_opt_ PTIMER_APC_ROUTINE TimerApcRoutine; _In_opt_ PVOID TimerContext; _In_opt_ struct _COUNTED_REASON_CONTEXT* WakeContext; _In_opt_ ULONG Period; _In_ ULONG TolerableDelay; _Out_opt_ PBOOLEAN PreviousState; } TIMER_SET_COALESCABLE_TIMER_INFO, *PTIMER_SET_COALESCABLE_TIMER_INFO; typedef struct _TOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE { ULONG64 Version; UNICODE_STRING Name; } TOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE, *PTOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE; typedef struct _TOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE { PVOID pValue; ULONG ValueLength; } TOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE, *PTOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE; typedef struct _TOKEN_SECURITY_ATTRIBUTE_V1 { UNICODE_STRING Name; USHORT ValueType; USHORT Reserved; ULONG Flags; ULONG ValueCount; union { PLONG64 pInt64; PULONG64 pUint64; PUNICODE_STRING pString; PTOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE pFqbn; PTOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE pOctetString; } Values; } TOKEN_SECURITY_ATTRIBUTE_V1, *PTOKEN_SECURITY_ATTRIBUTE_V1; #define TOKEN_SECURITY_ATTRIBUTES_INFORMATION_VERSION_V1 1 #define TOKEN_SECURITY_ATTRIBUTES_INFORMATION_VERSION TOKEN_SECURITY_ATTRIBUTES_INFORMATION_VERSION_V1 typedef struct _TOKEN_SECURITY_ATTRIBUTES_INFORMATION { USHORT Version; USHORT Reserved; ULONG AttributeCount; union { PTOKEN_SECURITY_ATTRIBUTE_V1 pAttributeV1; } Attribute; } TOKEN_SECURITY_ATTRIBUTES_INFORMATION, *PTOKEN_SECURITY_ATTRIBUTES_INFORMATION; typedef enum _FILTER_BOOT_OPTION_OPERATION { FilterBootOptionOperationOpenSystemStore, FilterBootOptionOperationSetElement, FilterBootOptionOperationDeleteElement, FilterBootOptionOperationMax } FILTER_BOOT_OPTION_OPERATION; typedef enum _IO_SESSION_EVENT { IoSessionEventIgnore, IoSessionEventCreated, IoSessionEventTerminated, IoSessionEventConnected, IoSessionEventDisconnected, IoSessionEventLogon, IoSessionEventLogoff, IoSessionEventMax } IO_SESSION_EVENT; typedef enum _IO_SESSION_STATE { IoSessionStateCreated, IoSessionStateInitialized, IoSessionStateConnected, IoSessionStateDisconnected, IoSessionStateDisconnectedLoggedOn, IoSessionStateLoggedOn, IoSessionStateLoggedOff, IoSessionStateTerminated, IoSessionStateMax } IO_SESSION_STATE; typedef struct _PORT_MESSAGE PORT_MESSAGE, *PPORT_MESSAGE; typedef struct _TP_ALPC TP_ALPC, *PTP_ALPC; typedef VOID (NTAPI* PTP_ALPC_CALLBACK)( _Inout_ PTP_CALLBACK_INSTANCE Instance, _Inout_opt_ PVOID Context, _In_ PTP_ALPC Alpc ); typedef VOID (NTAPI* PTP_ALPC_CALLBACK_EX)( _Inout_ PTP_CALLBACK_INSTANCE Instance, _Inout_opt_ PVOID Context, _In_ PTP_ALPC Alpc, _In_ PVOID ApcContext ); typedef VOID (NTAPI* PTP_IO_CALLBACK)( _Inout_ PTP_CALLBACK_INSTANCE Instance, _Inout_opt_ PVOID Context, _In_ PVOID ApcContext, _In_ PIO_STATUS_BLOCK IoSB, _In_ PTP_IO Io ); typedef enum _IO_COMPLETION_INFORMATION_CLASS { IoCompletionBasicInformation } IO_COMPLETION_INFORMATION_CLASS; typedef struct _IO_COMPLETION_BASIC_INFORMATION { LONG Depth; } IO_COMPLETION_BASIC_INFORMATION, *PIO_COMPLETION_BASIC_INFORMATION; typedef enum _WORKERFACTORYINFOCLASS { WorkerFactoryTimeout, WorkerFactoryRetryTimeout, WorkerFactoryIdleTimeout, WorkerFactoryBindingCount, WorkerFactoryThreadMinimum, WorkerFactoryThreadMaximum, WorkerFactoryPaused, WorkerFactoryBasicInformation, WorkerFactoryAdjustThreadGoal, WorkerFactoryCallbackType, WorkerFactoryStackInformation, // 10 WorkerFactoryThreadBasePriority, WorkerFactoryTimeoutWaiters, // since THRESHOLD WorkerFactoryFlags, WorkerFactoryThreadSoftMaximum, MaxWorkerFactoryInfoClass } WORKERFACTORYINFOCLASS, *PWORKERFACTORYINFOCLASS; typedef struct _WORKER_FACTORY_BASIC_INFORMATION { LARGE_INTEGER Timeout; LARGE_INTEGER RetryTimeout; LARGE_INTEGER IdleTimeout; BOOLEAN Paused; BOOLEAN TimerSet; BOOLEAN QueuedToExWorker; BOOLEAN MayCreate; BOOLEAN CreateInProgress; BOOLEAN InsertedIntoQueue; BOOLEAN Shutdown; ULONG BindingCount; ULONG ThreadMinimum; ULONG ThreadMaximum; ULONG PendingWorkerCount; ULONG WaitingWorkerCount; ULONG TotalWorkerCount; ULONG ReleaseCount; LONGLONG InfiniteWaitGoal; PVOID StartRoutine; PVOID StartParameter; HANDLE ProcessId; SIZE_T StackReserve; SIZE_T StackCommit; NTSTATUS LastThreadCreationStatus; } WORKER_FACTORY_BASIC_INFORMATION, *PWORKER_FACTORY_BASIC_INFORMATION; typedef struct _BOOT_ENTRY { ULONG Version; ULONG Length; ULONG Id; ULONG Attributes; ULONG FriendlyNameOffset; ULONG BootFilePathOffset; ULONG OsOptionsLength; UCHAR OsOptions[1]; } BOOT_ENTRY, *PBOOT_ENTRY; typedef struct _BOOT_ENTRY_LIST { ULONG NextEntryOffset; BOOT_ENTRY BootEntry; } BOOT_ENTRY_LIST, *PBOOT_ENTRY_LIST; typedef struct _BOOT_OPTIONS { ULONG Version; ULONG Length; ULONG Timeout; ULONG CurrentBootEntryId; ULONG NextBootEntryId; WCHAR HeadlessRedirection[1]; } BOOT_OPTIONS, *PBOOT_OPTIONS; typedef struct _FILE_PATH { ULONG Version; ULONG Length; ULONG Type; UCHAR FilePath[1]; } FILE_PATH, *PFILE_PATH; typedef struct _EFI_DRIVER_ENTRY { ULONG Version; ULONG Length; ULONG Id; ULONG FriendlyNameOffset; ULONG DriverFilePathOffset; } EFI_DRIVER_ENTRY, *PEFI_DRIVER_ENTRY; typedef struct _EFI_DRIVER_ENTRY_LIST { ULONG NextEntryOffset; EFI_DRIVER_ENTRY DriverEntry; } EFI_DRIVER_ENTRY_LIST, *PEFI_DRIVER_ENTRY_LIST; FORCEINLINE VOID InitializeListHead( _Out_ PLIST_ENTRY ListHead ) { ListHead->Flink = ListHead->Blink = ListHead; } FORCEINLINE BOOLEAN IsListEmpty( _In_ PLIST_ENTRY ListHead ) { return ListHead->Flink == ListHead; } FORCEINLINE BOOLEAN RemoveEntryList( _In_ PLIST_ENTRY Entry ) { PLIST_ENTRY Flink = Entry->Flink; PLIST_ENTRY Blink = Entry->Blink; Blink->Flink = Flink; Flink->Blink = Blink; return Flink == Blink; } FORCEINLINE PLIST_ENTRY RemoveHeadList( _Inout_ PLIST_ENTRY ListHead ) { PLIST_ENTRY Entry = ListHead->Flink; PLIST_ENTRY Flink = Entry->Flink; ListHead->Flink = Flink; Flink->Blink = ListHead; return Entry; } FORCEINLINE PLIST_ENTRY RemoveTailList( _Inout_ PLIST_ENTRY ListHead ) { PLIST_ENTRY Entry = ListHead->Blink; PLIST_ENTRY Blink = Entry->Blink; ListHead->Blink = Blink; Blink->Flink = ListHead; return Entry; } FORCEINLINE VOID InsertTailList( _Inout_ PLIST_ENTRY ListHead, _Inout_ PLIST_ENTRY Entry ) { PLIST_ENTRY Blink = ListHead->Blink; Entry->Flink = ListHead; Entry->Blink = Blink; Blink->Flink = Entry; ListHead->Blink = Entry; } FORCEINLINE VOID InsertHeadList( _Inout_ PLIST_ENTRY ListHead, _Inout_ PLIST_ENTRY Entry ) { PLIST_ENTRY Flink = ListHead->Flink; Entry->Flink = Flink; Entry->Blink = ListHead; Flink->Blink = Entry; ListHead->Flink = Entry; } FORCEINLINE VOID AppendTailList( _Inout_ PLIST_ENTRY ListHead, _Inout_ PLIST_ENTRY ListToAppend ) { PLIST_ENTRY ListEnd = ListHead->Blink; ListHead->Blink->Flink = ListToAppend; ListHead->Blink = ListToAppend->Blink; ListToAppend->Blink->Flink = ListHead; ListToAppend->Blink = ListEnd; } FORCEINLINE PSINGLE_LIST_ENTRY PopEntryList( _Inout_ PSINGLE_LIST_ENTRY ListHead ) { PSINGLE_LIST_ENTRY FirstEntry = ListHead->Next; if(FirstEntry) ListHead->Next = FirstEntry->Next; return FirstEntry; } FORCEINLINE VOID PushEntryList( _Inout_ PSINGLE_LIST_ENTRY ListHead, _Inout_ PSINGLE_LIST_ENTRY Entry ) { Entry->Next = ListHead->Next; ListHead->Next = Entry; } NTSYSCALLAPI NTSTATUS NTAPI NtCreateProcess( _Out_ PHANDLE ProcessHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ HANDLE ParentProcess, _In_ BOOLEAN InheritObjectTable, _In_opt_ HANDLE SectionHandle, _In_opt_ HANDLE DebugPort, _In_opt_ HANDLE ExceptionPort ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateProcessEx( _Out_ PHANDLE ProcessHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ HANDLE ParentProcess, _In_ ULONG Flags, _In_opt_ HANDLE SectionHandle, _In_opt_ HANDLE DebugPort, _In_opt_ HANDLE ExceptionPort, _In_ BOOLEAN InJob ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSCALLAPI NTSTATUS NTAPI NtCreateUserProcess( _Out_ PHANDLE ProcessHandle, _Out_ PHANDLE ThreadHandle, _In_ ACCESS_MASK ProcessDesiredAccess, _In_ ACCESS_MASK ThreadDesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ProcessObjectAttributes, _In_opt_ POBJECT_ATTRIBUTES ThreadObjectAttributes, _In_ ULONG ProcessFlags, _In_ ULONG ThreadFlags, _In_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters, _Inout_ PPS_CREATE_INFO CreateInfo, _In_ PPS_ATTRIBUTE_LIST AttributeList ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtSetInformationProcess( _In_ HANDLE ProcessHandle, _In_ PROCESSINFOCLASS ProcessInformationClass, _In_ PVOID ProcessInformation, _In_ ULONG ProcessInformationLength ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryInformationProcess( _In_ HANDLE ProcessHandle, _In_ PROCESSINFOCLASS ProcessInformationClass, _Out_ PVOID ProcessInformation, _In_ ULONG ProcessInformationLength, _Out_opt_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryObject( _In_ HANDLE Handle, _In_ OBJECT_INFORMATION_CLASS ObjectInformationClass, _Out_opt_ PVOID ObjectInformation, _In_ ULONG ObjectInformationLength, _Out_opt_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtQuerySystemInformation( _In_ SYSTEM_INFORMATION_CLASS SystemInformationClass, _Out_opt_ PVOID SystemInformation, _In_ ULONG SystemInformationLength, _Out_opt_ PULONG ReturnLength ); #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSCALLAPI NTSTATUS NTAPI NtQuerySystemInformationEx( _In_ SYSTEM_INFORMATION_CLASS SystemInformationClass, _In_ PVOID InputBuffer, _In_ ULONG InputBufferLength, _Out_ PVOID SystemInformation, _In_ ULONG SystemInformationLength, _Out_opt_ PULONG ReturnLength ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtSetSystemInformation( _In_ SYSTEM_INFORMATION_CLASS SystemInformationClass, _In_opt_ PVOID SystemInformation, _In_ ULONG SystemInformationLength ); NTSYSCALLAPI NTSTATUS NTAPI NtSetInformationThread( _In_ HANDLE ThreadHandle, _In_ THREADINFOCLASS ThreadInformationClass, _In_ PVOID ThreadInformation, _In_ ULONG ThreadInformationLength ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryInformationThread( _In_ HANDLE ThreadHandle, _In_ THREADINFOCLASS ThreadInformationClass, _Out_ PVOID ThreadInformation, _In_ ULONG ThreadInformationLength, _Out_opt_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtUnmapViewOfSection( _In_ HANDLE ProcessHandle, _In_ PVOID BaseAddress ); NTSYSCALLAPI NTSTATUS NTAPI NtExtendSection( _In_ HANDLE SectionHandle, _Inout_ PLARGE_INTEGER NewSectionSize ); NTSYSCALLAPI NTSTATUS NTAPI NtSuspendThread( _In_ HANDLE ThreadHandle, _Out_opt_ PULONG PreviousSuspendCount ); NTSYSCALLAPI NTSTATUS NTAPI NtResumeThread( _In_ HANDLE ThreadHandle, _Out_opt_ PULONG PreviousSuspendCount ); NTSYSCALLAPI NTSTATUS NTAPI NtSuspendProcess( _In_ HANDLE ProcessHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtResumeProcess( _In_ HANDLE ProcessHandle ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSCALLAPI ULONG NTAPI NtGetCurrentProcessorNumber( ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtSignalAndWaitForSingleObject( _In_ HANDLE SignalHandle, _In_ HANDLE WaitHandle, _In_ BOOLEAN Alertable, _In_opt_ PLARGE_INTEGER Timeout ); NTSYSCALLAPI NTSTATUS NTAPI NtWaitForSingleObject( _In_ HANDLE Handle, _In_ BOOLEAN Alertable, _In_opt_ PLARGE_INTEGER Timeout ); NTSYSCALLAPI NTSTATUS NTAPI NtWaitForMultipleObjects( _In_ ULONG Count, _In_ PHANDLE Handles, _In_ WAIT_TYPE WaitType, _In_ BOOLEAN Alertable, _In_opt_ PLARGE_INTEGER Timeout ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSCALLAPI NTSTATUS NTAPI NtWaitForMultipleObjects32( _In_ ULONG Count, _In_ PHANDLE Handles, _In_ WAIT_TYPE WaitType, _In_ BOOLEAN Alertable, _In_opt_ PLARGE_INTEGER Timeout ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtSetSecurityObject( _In_ HANDLE Handle, _In_ SECURITY_INFORMATION SecurityInformation, _In_ PSECURITY_DESCRIPTOR SecurityDescriptor ); NTSYSCALLAPI NTSTATUS NTAPI NtQuerySecurityObject( _In_ HANDLE Handle, _In_ SECURITY_INFORMATION SecurityInformation, _Out_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_ ULONG Length, _Out_ PULONG LengthNeeded ); NTSYSCALLAPI NTSTATUS NTAPI NtQueueApcThread( _In_ HANDLE ThreadHandle, _In_ PPS_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcArgument1, _In_opt_ PVOID ApcArgument2, _In_opt_ PVOID ApcArgument3 ); #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSCALLAPI NTSTATUS NTAPI NtQueueApcThreadEx( _In_ HANDLE ThreadHandle, _In_opt_ HANDLE UserApcReserveHandle, _In_ PPS_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcArgument1, _In_opt_ PVOID ApcArgument2, _In_opt_ PVOID ApcArgument3 ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtProtectVirtualMemory( _In_ HANDLE ProcessHandle, _Inout_ PVOID* BaseAddress, _Inout_ PSIZE_T RegionSize, _In_ ULONG NewProtect, _Out_ PULONG OldProtect ); NTSYSCALLAPI NTSTATUS NTAPI NtFlushBuffersFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock ); NTSYSCALLAPI NTSTATUS NTAPI NtFlushInstructionCache( _In_ HANDLE ProcessHandle, _In_opt_ PVOID BaseAddress, _In_ SIZE_T Length ); NTSYSCALLAPI NTSTATUS NTAPI NtFlushWriteBuffer( ); NTSYSCALLAPI NTSTATUS NTAPI NtFsControlFile( _In_ HANDLE FileHandle, _In_opt_ HANDLE Event, _In_opt_ PIO_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcContext, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ ULONG FsControlCode, _In_opt_ PVOID InputBuffer, _In_ ULONG InputBufferLength, _Out_opt_ PVOID OutputBuffer, _In_ ULONG OutputBufferLength ); NTSYSCALLAPI NTSTATUS NTAPI NtLockFile( _In_ HANDLE FileHandle, _In_opt_ HANDLE Event, _In_opt_ PIO_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcContext, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ PLARGE_INTEGER ByteOffset, _In_ PLARGE_INTEGER Length, _In_ ULONG Key, _In_ BOOLEAN FailImmediately, _In_ BOOLEAN ExclusiveLock ); NTSYSCALLAPI NTSTATUS NTAPI NtUnlockFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ PLARGE_INTEGER ByteOffset, _In_ PLARGE_INTEGER Length, _In_ ULONG Key ); NTSYSCALLAPI NTSTATUS NTAPI NtFlushVirtualMemory( _In_ HANDLE ProcessHandle, _Inout_ PVOID* BaseAddress, _Inout_ PSIZE_T RegionSize, _Out_ PIO_STATUS_BLOCK IoStatus ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryVirtualMemory( _In_ HANDLE ProcessHandle, _In_ PVOID BaseAddress, _In_ MEMORY_INFORMATION_CLASS MemoryInformationClass, _Out_ PVOID MemoryInformation, _In_ SIZE_T MemoryInformationLength, _Out_opt_ PSIZE_T ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtLockVirtualMemory( _In_ HANDLE ProcessHandle, _Inout_ PVOID* BaseAddress, _Inout_ PSIZE_T RegionSize, _In_ ULONG MapType ); NTSYSCALLAPI NTSTATUS NTAPI NtUnlockVirtualMemory( _In_ HANDLE ProcessHandle, _Inout_ PVOID* BaseAddress, _Inout_ PSIZE_T RegionSize, _In_ ULONG MapType ); NTSYSCALLAPI NTSTATUS NTAPI NtSystemDebugControl( _In_ SYSDBG_COMMAND Command, _Inout_opt_ PVOID InputBuffer, _In_ ULONG InputBufferLength, _Out_opt_ PVOID OutputBuffer, _In_ ULONG OutputBufferLength, _Out_opt_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtYieldExecution( ); NTSYSCALLAPI NTSTATUS NTAPI NtClose( _In_ HANDLE Handle ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryAttributesFile( _In_ POBJECT_ATTRIBUTES ObjectAttributes, _Out_ PFILE_BASIC_INFORMATION FileInformation ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryFullAttributesFile( _In_ POBJECT_ATTRIBUTES ObjectAttributes, _Out_ PFILE_NETWORK_OPEN_INFORMATION FileInformation ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryInformationFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _Out_ PVOID FileInformation, _In_ ULONG Length, _In_ FILE_INFORMATION_CLASS FileInformationClass ); NTSYSCALLAPI NTSTATUS NTAPI NtSetInformationFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ PVOID FileInformation, _In_ ULONG Length, _In_ FILE_INFORMATION_CLASS FileInformationClass ); NTSYSCALLAPI NTSTATUS NTAPI NtSetQuotaInformationFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ PVOID Buffer, _In_ ULONG Length ); NTSYSCALLAPI NTSTATUS NTAPI NtSetVolumeInformationFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ PVOID FsInformation, _In_ ULONG Length, _In_ FS_INFORMATION_CLASS FsInformationClass ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateFile( _Out_ PHANDLE FileHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_opt_ PLARGE_INTEGER AllocationSize, _In_ ULONG FileAttributes, _In_ ULONG ShareAccess, _In_ ULONG CreateDisposition, _In_ ULONG CreateOptions, _In_opt_ PVOID EaBuffer, _In_ ULONG EaLength ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateNamedPipeFile( _Out_ PHANDLE FileHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ ULONG ShareAccess, _In_ ULONG CreateDisposition, _In_ ULONG CreateOptions, _In_ ULONG NamedPipeType, _In_ ULONG ReadMode, _In_ ULONG CompletionMode, _In_ ULONG MaximumInstances, _In_ ULONG InboundQuota, _In_ ULONG OutboundQuota, _In_opt_ PLARGE_INTEGER DefaultTimeout ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateMailslotFile( _Out_ PHANDLE FileHandle, _In_ ULONG DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ ULONG CreateOptions, _In_ ULONG MailslotQuota, _In_ ULONG MaximumMessageSize, _In_ PLARGE_INTEGER ReadTimeout ); NTSYSCALLAPI NTSTATUS NTAPI NtCancelIoFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSCALLAPI NTSTATUS NTAPI NtCancelIoFileEx( _In_ HANDLE FileHandle, _In_opt_ PIO_STATUS_BLOCK IoRequestToCancel, _Out_ PIO_STATUS_BLOCK IoStatusBlock ); NTSYSCALLAPI NTSTATUS NTAPI NtCancelSynchronousIoFile( _In_ HANDLE ThreadHandle, _In_opt_ PIO_STATUS_BLOCK IoRequestToCancel, _Out_ PIO_STATUS_BLOCK IoStatusBlock ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtCreateSymbolicLinkObject( _Out_ PHANDLE LinkHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ PUNICODE_STRING LinkTarget ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenSymbolicLinkObject( _Out_ PHANDLE LinkHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI NTSTATUS NTAPI NtQuerySymbolicLinkObject( _In_ HANDLE LinkHandle, _Inout_ PUNICODE_STRING LinkTarget, _Out_opt_ PULONG ReturnedLength ); NTSYSCALLAPI NTSTATUS NTAPI NtGetContextThread( _In_ HANDLE ThreadHandle, _Inout_ PCONTEXT ThreadContext ); NTSYSCALLAPI NTSTATUS NTAPI NtSetContextThread( _In_ HANDLE ThreadHandle, _In_ PCONTEXT ThreadContext ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenProcess( _Out_ PHANDLE ProcessHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ PCLIENT_ID ClientId ); NTSYSCALLAPI NTSTATUS NTAPI NtTerminateProcess( _In_opt_ HANDLE ProcessHandle, _In_ NTSTATUS ExitStatus ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSCALLAPI NTSTATUS NTAPI NtGetNextProcess( _In_ HANDLE ProcessHandle, _In_ ACCESS_MASK DesiredAccess, _In_ ULONG HandleAttributes, _In_ ULONG Flags, _Out_ PHANDLE NewProcessHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtGetNextThread( _In_ HANDLE ProcessHandle, _In_ HANDLE ThreadHandle, _In_ ACCESS_MASK DesiredAccess, _In_ ULONG HandleAttributes, _In_ ULONG Flags, _Out_ PHANDLE NewThreadHandle ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtCreateDebugObject( _Out_ PHANDLE DebugObjectHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ ULONG Flags ); NTSYSCALLAPI NTSTATUS NTAPI NtDebugActiveProcess( _In_ HANDLE ProcessHandle, _In_ HANDLE DebugObjectHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtContinue( _In_ PCONTEXT ContextRecord, _In_ BOOLEAN TestAlert ); NTSYSCALLAPI NTSTATUS NTAPI NtRaiseException( _In_ PEXCEPTION_RECORD ExceptionRecord, _In_ PCONTEXT ContextRecord, _In_ BOOLEAN FirstChance ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateThread( _Out_ PHANDLE ThreadHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ HANDLE ProcessHandle, _Out_ PCLIENT_ID ClientId, _In_ PCONTEXT ThreadContext, _In_ PINITIAL_TEB InitialTeb, _In_ BOOLEAN CreateSuspended ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSCALLAPI NTSTATUS NTAPI NtCreateThreadEx( _Out_ PHANDLE ThreadHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ HANDLE ProcessHandle, _In_ PUSER_THREAD_START_ROUTINE StartRoutine, _In_opt_ PVOID Argument, _In_ ULONG CreateFlags, _In_opt_ ULONG_PTR ZeroBits, _In_opt_ SIZE_T StackSize, _In_opt_ SIZE_T MaximumStackSize, _In_opt_ PPS_ATTRIBUTE_LIST AttributeList ); #endif #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSCALLAPI NTSTATUS NTAPI NtAllocateReserveObject( _Out_ PHANDLE MemoryReserveHandle, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ MEMORY_RESERVE_TYPE Type ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtRegisterThreadTerminatePort( _In_ HANDLE PortHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtRaiseHardError( _In_ NTSTATUS ErrorStatus, _In_ ULONG NumberOfParameters, _In_opt_ ULONG UnicodeStringParameterMask, _In_ PULONG_PTR Parameters, _In_ HARDERROR_RESPONSE_OPTION ResponseOption, _Out_ PHARDERROR_RESPONSE Response ); NTSYSCALLAPI NTSTATUS NTAPI NtAllocateVirtualMemory( _In_ HANDLE ProcessHandle, _Inout_ PVOID* BaseAddress, _In_ ULONG_PTR ZeroBits, _Inout_ PSIZE_T RegionSize, _In_ ULONG AllocationType, _In_ ULONG Protect ); NTSYSCALLAPI NTSTATUS NTAPI NtFreeVirtualMemory( _In_ HANDLE ProcessHandle, _Inout_ PVOID* BaseAddress, _Inout_ PSIZE_T RegionSize, _In_ ULONG FreeType ); NTSYSCALLAPI NTSTATUS NTAPI NtReadVirtualMemory( _In_ HANDLE ProcessHandle, _In_opt_ PVOID BaseAddress, _Out_ PVOID Buffer, _In_ SIZE_T BufferSize, _Out_opt_ PSIZE_T NumberOfBytesRead ); NTSYSCALLAPI NTSTATUS NTAPI NtWriteVirtualMemory( _In_ HANDLE ProcessHandle, _In_opt_ PVOID BaseAddress, _In_ CONST VOID* Buffer, _In_ SIZE_T BufferSize, _Out_opt_ PSIZE_T NumberOfBytesWritten ); NTSYSCALLAPI NTSTATUS NTAPI NtAllocateUserPhysicalPages( _In_ HANDLE ProcessHandle, _Inout_ PULONG_PTR NumberOfPages, _Out_ PULONG_PTR UserPfnArray ); NTSYSCALLAPI NTSTATUS NTAPI NtMapUserPhysicalPages( _In_ PVOID VirtualAddress, _In_ ULONG_PTR NumberOfPages, _In_ PULONG_PTR UserPfnArray ); NTSYSCALLAPI NTSTATUS NTAPI NtMapUserPhysicalPagesScatter( _In_ PVOID* VirtualAddresses, _In_ ULONG_PTR NumberOfPages, _In_ PULONG_PTR UserPfnArray ); NTSYSCALLAPI NTSTATUS NTAPI NtFreeUserPhysicalPages( _In_ HANDLE ProcessHandle, _Inout_ PULONG_PTR NumberOfPages, _In_ PULONG_PTR UserPfnArray ); NTSYSCALLAPI NTSTATUS NTAPI NtQuerySection( _In_ HANDLE SectionHandle, _In_ SECTION_INFORMATION_CLASS SectionInformationClass, _Out_ PVOID SectionInformation, _In_ SIZE_T SectionInformationLength, _Out_opt_ PSIZE_T ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtAreMappedFilesTheSame( _In_ PVOID File1MappedAsAnImage, _In_ PVOID File2MappedAsFile ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateSection( _Out_ PHANDLE SectionHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ PLARGE_INTEGER MaximumSize, _In_ ULONG SectionPageProtection, _In_ ULONG AllocationAttributes, _In_opt_ HANDLE FileHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenSection( _Out_ PHANDLE SectionHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI NTSTATUS NTAPI NtMapViewOfSection( _In_ HANDLE SectionHandle, _In_ HANDLE ProcessHandle, _Inout_ PVOID* BaseAddress, _In_ ULONG_PTR ZeroBits, _In_ SIZE_T CommitSize, _Inout_opt_ PLARGE_INTEGER SectionOffset, _Inout_ PSIZE_T ViewSize, _In_ SECTION_INHERIT InheritDisposition, _In_ ULONG AllocationType, _In_ ULONG Win32Protect ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSCALLAPI NTSTATUS NTAPI NtOpenSession( _Out_ PHANDLE SessionHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtNotifyChangeDirectoryFile( _In_ HANDLE FileHandle, _In_opt_ HANDLE Event, _In_opt_ PIO_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcContext, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _Out_ FILE_NOTIFY_INFORMATION Buffer, _In_ ULONG Length, _In_ ULONG CompletionFilter, _In_ BOOLEAN WatchTree ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenFile( _Out_ PHANDLE FileHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ ULONG ShareAccess, _In_ ULONG OpenOptions ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryDirectoryFile( _In_ HANDLE FileHandle, _In_opt_ HANDLE Event, _In_opt_ PIO_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcContext, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _Out_ PVOID FileInformation, _In_ ULONG Length, _In_ FILE_INFORMATION_CLASS FileInformationClass, _In_ BOOLEAN ReturnSingleEntry, _In_opt_ PUNICODE_STRING FileName, _In_ BOOLEAN RestartScan ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryEaFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _Out_ PVOID Buffer, _In_ ULONG Length, _In_ BOOLEAN ReturnSingleEntry, _In_ PVOID EaList, _In_ ULONG EaListLength, _In_opt_ PULONG EaIndex, _In_ BOOLEAN RestartScan ); NTSYSCALLAPI NTSTATUS NTAPI NtSetEaFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ PVOID Buffer, _In_ ULONG Length ); NTSYSCALLAPI NTSTATUS NTAPI NtLoadDriver( _In_ PUNICODE_STRING DriverServiceName ); NTSYSCALLAPI NTSTATUS NTAPI NtUnloadDriver( _In_ PUNICODE_STRING DriverServiceName ); NTSYSCALLAPI NTSTATUS NTAPI NtReadFile( _In_ HANDLE FileHandle, _In_opt_ HANDLE Event, _In_opt_ PIO_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcContext, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _Out_ PVOID Buffer, _In_ ULONG Length, _In_opt_ PLARGE_INTEGER ByteOffset, _In_opt_ PULONG Key ); NTSYSCALLAPI NTSTATUS NTAPI NtReadFileScatter( _In_ HANDLE FileHandle, _In_opt_ HANDLE Event, _In_opt_ PIO_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcContext, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ PFILE_SEGMENT_ELEMENT SegmentArray, _In_ ULONG Length, _In_opt_ PLARGE_INTEGER ByteOffset, _In_opt_ PULONG Key ); NTSYSCALLAPI NTSTATUS NTAPI NtWriteFileGather( _In_ HANDLE FileHandle, _In_opt_ HANDLE Event, _In_opt_ PIO_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcContext, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ PFILE_SEGMENT_ELEMENT SegmentArray, _In_ ULONG Length, _In_opt_ PLARGE_INTEGER ByteOffset, _In_opt_ PULONG Key ); NTSYSCALLAPI NTSTATUS NTAPI NtDeleteFile( _In_ POBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI NTSTATUS NTAPI NtWriteFile( _In_ HANDLE FileHandle, _In_opt_ HANDLE Event, _In_opt_ PIO_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcContext, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ PVOID Buffer, _In_ ULONG Length, _In_opt_ PLARGE_INTEGER ByteOffset, _In_opt_ PULONG Key ); NTSYSCALLAPI NTSTATUS NTAPI NtDeviceIoControlFile( _In_ HANDLE FileHandle, _In_opt_ HANDLE Event, _In_opt_ PIO_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcContext, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ ULONG IoControlCode, _In_opt_ PVOID InputBuffer, _In_ ULONG InputBufferLength, _Out_opt_ PVOID OutputBuffer, _In_ ULONG OutputBufferLength ); NTSYSCALLAPI NTSTATUS NTAPI NtSetInformationObject( _In_ HANDLE Handle, _In_ OBJECT_INFORMATION_CLASS ObjectInformationClass, _In_ PVOID ObjectInformation, _In_ ULONG ObjectInformationLength ); NTSYSCALLAPI NTSTATUS NTAPI NtDuplicateObject( _In_ HANDLE SourceProcessHandle, _In_ HANDLE SourceHandle, _In_opt_ HANDLE TargetProcessHandle, _Out_opt_ PHANDLE TargetHandle, _In_ ACCESS_MASK DesiredAccess, _In_ ULONG HandleAttributes, _In_ ULONG Options ); NTSYSCALLAPI NTSTATUS NTAPI NtMakePermanentObject( _In_ HANDLE Object ); NTSYSCALLAPI NTSTATUS NTAPI NtMakeTemporaryObject( _In_ HANDLE Handle ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateDirectoryObject( _Out_ PHANDLE DirectoryHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenDirectoryObject( _Out_ PHANDLE DirectoryHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryDirectoryObject( _In_ HANDLE DirectoryHandle, _Out_ PVOID Buffer, _In_ ULONG BufferLength, _In_ BOOLEAN ReturnSingleEntry, _In_ BOOLEAN RestartScan, _Inout_ PULONG Context, _Out_opt_ PULONG ReturnLength ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSCALLAPI NTSTATUS NTAPI NtCreatePrivateNamespace( _Out_ PHANDLE NamespaceHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ PVOID BoundaryDescriptor ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenPrivateNamespace( _Out_ PHANDLE NamespaceHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ PVOID BoundaryDescriptor ); NTSYSCALLAPI NTSTATUS NTAPI NtDeletePrivateNamespace( _In_ HANDLE NamespaceHandle ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtOpenThread( _Out_ PHANDLE ThreadHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ PCLIENT_ID ClientId ); NTSYSCALLAPI NTSTATUS NTAPI NtTerminateThread( _In_opt_ HANDLE ThreadHandle, _In_ NTSTATUS ExitStatus ); NTSYSCALLAPI NTSTATUS NTAPI NtQuerySystemTime( _Out_ PLARGE_INTEGER SystemTime ); NTSYSCALLAPI NTSTATUS NTAPI NtSetSystemTime( _In_opt_ PLARGE_INTEGER SystemTime, _Out_opt_ PLARGE_INTEGER PreviousTime ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryTimerResolution( _Out_ PULONG MaximumTime, _Out_ PULONG MinimumTime, _Out_ PULONG CurrentTime ); NTSYSCALLAPI NTSTATUS NTAPI NtSetTimerResolution( _In_ ULONG DesiredTime, _In_ BOOLEAN SetResolution, _Out_ PULONG ActualTime ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryPerformanceCounter( _Out_ PLARGE_INTEGER PerformanceCounter, _Out_opt_ PLARGE_INTEGER PerformanceFrequency ); NTSYSCALLAPI NTSTATUS NTAPI NtAllocateLocallyUniqueId( _Out_ PLUID Luid ); NTSYSCALLAPI NTSTATUS NTAPI NtSetUuidSeed( _In_ PCHAR Seed ); NTSYSCALLAPI NTSTATUS NTAPI NtAllocateUuids( _Out_ PULARGE_INTEGER Time, _Out_ PULONG Range, _Out_ PULONG Sequence, _Out_ PCHAR Seed ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateEvent( _Out_ PHANDLE EventHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ EVENT_TYPE EventType, _In_ BOOLEAN InitialState ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenEvent( _Out_ PHANDLE EventHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI NTSTATUS NTAPI NtSetEvent( _In_ HANDLE EventHandle, _Out_opt_ PLONG PreviousState ); NTSYSCALLAPI NTSTATUS NTAPI NtResetEvent( _In_ HANDLE EventHandle, _Out_opt_ PLONG PreviousState ); NTSYSCALLAPI NTSTATUS NTAPI NtClearEvent( _In_ HANDLE EventHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryQuotaInformationFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _Out_ PVOID Buffer, _In_ ULONG Length, _In_ BOOLEAN ReturnSingleEntry, _In_opt_ PVOID SidList, _In_ ULONG SidListLength, _In_opt_ PSID StartSid, _In_ BOOLEAN RestartScan ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryVolumeInformationFile( _In_ HANDLE FileHandle, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _Out_ PVOID FsInformation, _In_ ULONG Length, _In_ FS_INFORMATION_CLASS FsInformationClass ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateKey( _Out_ PHANDLE KeyHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _Reserved_ ULONG TitleIndex, _In_opt_ PUNICODE_STRING Class, _In_ ULONG CreateOptions, _Out_opt_ PULONG Disposition ); #if NTDDI_VERSION >= PNTDDI_VISTA NTSYSCALLAPI NTSTATUS NTAPI NtCreateKeyTransacted( _Out_ PHANDLE KeyHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _Reserved_ ULONG TitleIndex, _In_opt_ PUNICODE_STRING Class, _In_ ULONG CreateOptions, _In_ HANDLE TransactionHandle, _Out_opt_ PULONG Disposition ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtOpenKey( _Out_ PHANDLE KeyHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes ); #if NTDDI_VERSION >= PNTDDI_VISTA NTSYSCALLAPI NTSTATUS NTAPI NtOpenKeyTransacted( _Out_ PHANDLE KeyHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ HANDLE TransactionHandle ); #endif #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSCALLAPI NTSTATUS NTAPI NtOpenKeyEx( _Out_ PHANDLE KeyHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ ULONG OpenOptions ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenKeyTransactedEx( _Out_ PHANDLE KeyHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ ULONG OpenOptions, _In_ HANDLE TransactionHandle ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtDeleteKey( _In_ HANDLE KeyHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtRenameKey( _In_ HANDLE KeyHandle, _In_ PUNICODE_STRING NewName ); NTSYSCALLAPI NTSTATUS NTAPI NtDeleteValueKey( _In_ HANDLE KeyHandle, _In_ PUNICODE_STRING ValueName ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryKey( _In_ HANDLE KeyHandle, _In_ KEY_INFORMATION_CLASS KeyInformationClass, _Out_ PVOID KeyInformation, _In_ ULONG Length, _Out_ PULONG ResultLength ); NTSYSCALLAPI NTSTATUS NTAPI NtSetInformationKey( _In_ HANDLE KeyHandle, _In_ KEY_SET_INFORMATION_CLASS KeySetInformationClass, _In_ PVOID KeySetInformation, _In_ ULONG KeySetInformationLength ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryValueKey( _In_ HANDLE KeyHandle, _In_ PUNICODE_STRING ValueName, _In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass, _Out_ PVOID KeyValueInformation, _In_ ULONG Length, _Out_ PULONG ResultLength ); NTSYSCALLAPI NTSTATUS NTAPI NtSetValueKey( _In_ HANDLE KeyHandle, _In_ PUNICODE_STRING ValueName, _In_opt_ ULONG TitleIndex, _In_ ULONG Type, _In_ PVOID Data, _In_ ULONG DataSize ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryMultipleValueKey( _In_ HANDLE KeyHandle, _Inout_ PKEY_VALUE_ENTRY ValueEntries, _In_ ULONG EntryCount, _Out_ PVOID ValueBuffer, _Inout_ PULONG BufferLength, _Out_opt_ PULONG RequiredBufferLength ); NTSYSCALLAPI NTSTATUS NTAPI NtEnumerateKey( _In_ HANDLE KeyHandle, _In_ ULONG Index, _In_ KEY_INFORMATION_CLASS KeyInformationClass, _Out_ PVOID KeyInformation, _In_ ULONG Length, _Out_ PULONG ResultLength ); NTSYSCALLAPI NTSTATUS NTAPI NtEnumerateValueKey( _In_ HANDLE KeyHandle, _In_ ULONG Index, _In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass, _Out_ PVOID KeyValueInformation, _In_ ULONG Length, _Out_ PULONG ResultLength ); NTSYSCALLAPI NTSTATUS NTAPI NtFlushKey( _In_ HANDLE KeyHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtCompactKeys( _In_ ULONG Count, _In_ PHANDLE KeyArray ); NTSYSCALLAPI NTSTATUS NTAPI NtCompressKey( _In_ HANDLE Key ); NTSYSCALLAPI NTSTATUS NTAPI NtLoadKey( _In_ POBJECT_ATTRIBUTES TargetKey, _In_ POBJECT_ATTRIBUTES SourceFile ); NTSYSCALLAPI NTSTATUS NTAPI NtLoadKey2( _In_ POBJECT_ATTRIBUTES TargetKey, _In_ POBJECT_ATTRIBUTES SourceFile, _In_ ULONG Flags ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSCALLAPI NTSTATUS NTAPI NtLoadKeyEx( _In_ POBJECT_ATTRIBUTES TargetKey, _In_ POBJECT_ATTRIBUTES SourceFile, _In_ ULONG Flags, _In_opt_ HANDLE TrustClassKey, _In_opt_ HANDLE Event, _In_opt_ ACCESS_MASK DesiredAccess, _Out_opt_ PHANDLE RootHandle, _Out_opt_ PIO_STATUS_BLOCK IoStatus ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtReplaceKey( _In_ POBJECT_ATTRIBUTES NewFile, _In_ HANDLE TargetHandle, _In_ POBJECT_ATTRIBUTES OldFile ); NTSYSCALLAPI NTSTATUS NTAPI NtSaveKey( _In_ HANDLE KeyHandle, _In_ HANDLE FileHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtSaveKeyEx( _In_ HANDLE KeyHandle, _In_ HANDLE FileHandle, _In_ ULONG Format ); NTSYSCALLAPI NTSTATUS NTAPI NtSaveMergedKeys( _In_ HANDLE HighPrecedenceKeyHandle, _In_ HANDLE LowPrecedenceKeyHandle, _In_ HANDLE FileHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtRestoreKey( _In_ HANDLE KeyHandle, _In_ HANDLE FileHandle, _In_ ULONG Flags ); NTSYSCALLAPI NTSTATUS NTAPI NtUnloadKey( _In_ POBJECT_ATTRIBUTES TargetKey ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSCALLAPI NTSTATUS NTAPI NtUnloadKey2( _In_ POBJECT_ATTRIBUTES TargetKey, _In_ ULONG Flags ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtUnloadKeyEx( _In_ POBJECT_ATTRIBUTES TargetKey, _In_opt_ HANDLE Event ); NTSYSCALLAPI NTSTATUS NTAPI NtNotifyChangeKey( _In_ HANDLE KeyHandle, _In_opt_ HANDLE Event, _In_opt_ PIO_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcContext, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ ULONG CompletionFilter, _In_ BOOLEAN WatchTree, _Out_ PVOID Buffer, _In_ ULONG BufferSize, _In_ BOOLEAN Asynchronous ); NTSYSCALLAPI NTSTATUS NTAPI NtNotifyChangeMultipleKeys( _In_ HANDLE MasterKeyHandle, _In_opt_ ULONG Count, _In_ POBJECT_ATTRIBUTES SubordinateObjects, _In_opt_ HANDLE Event, _In_opt_ PIO_APC_ROUTINE ApcRoutine, _In_opt_ PVOID ApcContext, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ ULONG CompletionFilter, _In_ BOOLEAN WatchTree, _Out_ PVOID Buffer, _In_ ULONG BufferSize, _In_ BOOLEAN Asynchronous ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryOpenSubKeys( _In_ POBJECT_ATTRIBUTES TargetKey, _Out_ PULONG HandleCount ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSCALLAPI NTSTATUS NTAPI NtQueryOpenSubKeysEx( _In_ POBJECT_ATTRIBUTES TargetKey, _In_ ULONG BufferLength, _Out_ PVOID Buffer, _Out_ PULONG RequiredSize ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtInitializeRegistry( _In_ USHORT BootCondition ); NTSYSCALLAPI NTSTATUS NTAPI NtLockRegistryKey( _In_ HANDLE KeyHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtLockProductActivationKeys( _Inout_opt_ ULONG* pPrivateVer, _Out_opt_ ULONG* pSafeMode ); #if NTDDI_VERSION >= PNTDDI_VISTA NTSYSCALLAPI NTSTATUS NTAPI NtFreezeRegistry( _In_ ULONG TimeOutInSeconds ); NTSYSCALLAPI NTSTATUS NTAPI NtThawRegistry( ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtDelayExecution( _In_ BOOLEAN Alertable, _In_ PLARGE_INTEGER DelayInterval ); NTSYSCALLAPI NTSTATUS NTAPI NtCallbackReturn( _In_ PVOID OutputBuffer, _In_ ULONG OutputLength, _In_ NTSTATUS Status ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSCALLAPI VOID NTAPI NtFlushProcessWriteBuffers( ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtQueryDebugFilterState( _In_ ULONG ComponentId, _In_ ULONG Level ); NTSYSCALLAPI NTSTATUS NTAPI NtSetDebugFilterState( _In_ ULONG ComponentId, _In_ ULONG Level, _In_ BOOLEAN State ); NTSYSCALLAPI NTSTATUS NTAPI NtRemoveProcessDebug( _In_ HANDLE ProcessHandle, _In_ HANDLE DebugObjectHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtWaitForDebugEvent( _In_ HANDLE DebugObjectHandle, _In_ BOOLEAN Alertable, _In_opt_ PLARGE_INTEGER Timeout, _Out_ PDBGUI_WAIT_STATE_CHANGE WaitStateChange ); NTSYSCALLAPI NTSTATUS NTAPI NtDebugContinue( _In_ HANDLE DebugObjectHandle, _In_ PCLIENT_ID ClientId, _In_ NTSTATUS ContinueStatus ); NTSYSCALLAPI NTSTATUS NTAPI NtSetInformationDebugObject( _In_ HANDLE DebugObjectHandle, _In_ DEBUGOBJECTINFOCLASS DebugObjectInformationClass, _In_ PVOID DebugInformation, _In_ ULONG DebugInformationLength, _Out_opt_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenProcessToken( _In_ HANDLE ProcessHandle, _In_ ACCESS_MASK DesiredAccess, _Out_ PHANDLE TokenHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenProcessTokenEx( _In_ HANDLE ProcessHandle, _In_ ACCESS_MASK DesiredAccess, _In_ ULONG HandleAttributes, _Out_ PHANDLE TokenHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenThreadToken( _In_ HANDLE ThreadHandle, _In_ ACCESS_MASK DesiredAccess, _In_ BOOLEAN OpenAsSelf, _Out_ PHANDLE TokenHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenThreadTokenEx( _In_ HANDLE ThreadHandle, _In_ ACCESS_MASK DesiredAccess, _In_ BOOLEAN OpenAsSelf, _In_ ULONG HandleAttributes, _Out_ PHANDLE TokenHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateToken( _Out_ PHANDLE TokenHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ TOKEN_TYPE TokenType, _In_ PLUID AuthenticationId, _In_ PLARGE_INTEGER ExpirationTime, _In_ PTOKEN_USER User, _In_ PTOKEN_GROUPS Groups, _In_ PTOKEN_PRIVILEGES Privileges, _In_opt_ PTOKEN_OWNER Owner, _In_ PTOKEN_PRIMARY_GROUP PrimaryGroup, _In_opt_ PTOKEN_DEFAULT_DACL DefaultDacl, _In_ PTOKEN_SOURCE TokenSource ); NTSYSCALLAPI NTSTATUS NTAPI NtDuplicateToken( _In_ HANDLE ExistingTokenHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ BOOLEAN EffectiveOnly, _In_ TOKEN_TYPE TokenType, _Out_ PHANDLE NewTokenHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtAdjustPrivilegesToken( _In_ HANDLE TokenHandle, _In_ BOOLEAN DisableAllPrivileges, _In_opt_ PTOKEN_PRIVILEGES NewState, _In_ ULONG BufferLength, _Out_opt_ PTOKEN_PRIVILEGES PreviousState, _Out_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtAdjustGroupsToken( _In_ HANDLE TokenHandle, _In_ BOOLEAN ResetToDefault, _In_opt_ PTOKEN_GROUPS NewState, _In_opt_ ULONG BufferLength, _Out_ PTOKEN_GROUPS PreviousState, _Out_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtFilterToken( _In_ HANDLE ExistingTokenHandle, _In_ ULONG Flags, _In_opt_ PTOKEN_GROUPS SidsToDisable, _In_opt_ PTOKEN_PRIVILEGES PrivilegesToDelete, _In_opt_ PTOKEN_GROUPS RestrictedSids, _Out_ PHANDLE NewTokenHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtSetInformationToken( _In_ HANDLE TokenHandle, _In_ TOKEN_INFORMATION_CLASS TokenInformationClass, _In_ PVOID TokenInformation, _In_ ULONG TokenInformationLength ); NTSYSCALLAPI NTSTATUS NTAPI NtCompareTokens( _In_ HANDLE FirstTokenHandle, _In_ HANDLE SecondTokenHandle, _Out_ PBOOLEAN Equal ); NTSYSCALLAPI NTSTATUS NTAPI NtPrivilegeCheck( _In_ HANDLE ClientToken, _Inout_ PPRIVILEGE_SET RequiredPrivileges, _Out_ PBOOLEAN Result ); NTSYSCALLAPI NTSTATUS NTAPI NtImpersonateAnonymousToken( _In_ HANDLE ThreadHandle ); #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSCALLAPI NTSTATUS NTAPI NtQuerySecurityAttributesToken( _In_ HANDLE TokenHandle, _In_reads_opt_(NumberOfAttributes) PUNICODE_STRING Attributes, _In_ ULONG NumberOfAttributes, _Out_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION Buffer, _In_ ULONG Length, _Out_ PULONG ReturnLength ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtAccessCheck( _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_ HANDLE ClientToken, _In_ ACCESS_MASK DesiredAccess, _In_ PGENERIC_MAPPING GenericMapping, _Out_ PPRIVILEGE_SET PrivilegeSet, _Inout_ PULONG PrivilegeSetLength, _Out_ PACCESS_MASK GrantedAccess, _Out_ PNTSTATUS AccessStatus ); NTSYSCALLAPI NTSTATUS NTAPI NtAccessCheckByType( _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_opt_ PSID PrincipalSelfSid, _In_ HANDLE ClientToken, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_TYPE_LIST ObjectTypeList, _In_ ULONG ObjectTypeListLength, _In_ PGENERIC_MAPPING GenericMapping, _Out_ PPRIVILEGE_SET PrivilegeSet, _Inout_ PULONG PrivilegeSetLength, _Out_ PACCESS_MASK GrantedAccess, _Out_ PNTSTATUS AccessStatus ); NTSYSCALLAPI NTSTATUS NTAPI NtAccessCheckByTypeResultList( _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_opt_ PSID PrincipalSelfSid, _In_ HANDLE ClientToken, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_TYPE_LIST ObjectTypeList, _In_ ULONG ObjectTypeListLength, _In_ PGENERIC_MAPPING GenericMapping, _Out_ PPRIVILEGE_SET PrivilegeSet, _Inout_ PULONG PrivilegeSetLength, _Out_ PACCESS_MASK GrantedAccess, _Out_ PNTSTATUS AccessStatus ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateIoCompletion( _Out_ PHANDLE IoCompletionHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ ULONG Count ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenIoCompletion( _Out_ PHANDLE IoCompletionHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryIoCompletion( _In_ HANDLE IoCompletionHandle, _In_ IO_COMPLETION_INFORMATION_CLASS IoCompletionInformationClass, _Out_ PVOID IoCompletionInformation, _In_ ULONG IoCompletionInformationLength, _Out_opt_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtSetIoCompletion( _In_ HANDLE IoCompletionHandle, _In_opt_ PVOID KeyContext, _In_opt_ PVOID ApcContext, _In_ NTSTATUS IoStatus, _In_ ULONG_PTR IoStatusInformation ); #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSCALLAPI NTSTATUS NTAPI NtSetIoCompletionEx( _In_ HANDLE IoCompletionHandle, _In_ HANDLE IoCompletionPacketHandle, _In_opt_ PVOID KeyContext, _In_opt_ PVOID ApcContext, _In_ NTSTATUS IoStatus, _In_ ULONG_PTR IoStatusInformation ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtRemoveIoCompletion( _In_ HANDLE IoCompletionHandle, _Out_ PVOID* KeyContext, _Out_ PVOID* ApcContext, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_opt_ PLARGE_INTEGER Timeout ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSCALLAPI NTSTATUS NTAPI NtRemoveIoCompletionEx( _In_ HANDLE IoCompletionHandle, _Out_ PFILE_IO_COMPLETION_INFORMATION IoCompletionInformation, _In_ ULONG Count, _Out_ PULONG NumEntriesRemoved, _In_opt_ PLARGE_INTEGER Timeout, _In_ BOOLEAN Alertable ); #endif #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSCALLAPI NTSTATUS NTAPI NtNotifyChangeSession( _In_ HANDLE SessionHandle, _In_ ULONG ChangeSequenceNumber, _In_ PLARGE_INTEGER ChangeTimeStamp, _In_ IO_SESSION_EVENT Event, _In_ IO_SESSION_STATE NewState, _In_ IO_SESSION_STATE PreviousState, _In_ PVOID Payload, _In_ ULONG PayloadSize ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtCreateMutant( _Out_ PHANDLE MutantHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ BOOLEAN InitialOwner ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenMutant( _Out_ PHANDLE MutantHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI NTSTATUS NTAPI NtReleaseMutant( _In_ HANDLE MutantHandle, _Out_opt_ PLONG PreviousCount ); NTSYSCALLAPI NTSTATUS NTAPI NtAlertThread( _In_ HANDLE ThreadHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtAlertResumeThread( _In_ HANDLE ThreadHandle, _Out_opt_ PULONG PreviousSuspendCount ); NTSYSCALLAPI NTSTATUS NTAPI NtTestAlert( ); NTSYSCALLAPI NTSTATUS NTAPI NtImpersonateThread( _In_ HANDLE ServerThreadHandle, _In_ HANDLE ClientThreadHandle, _In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateSemaphore( _Out_ PHANDLE SemaphoreHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ LONG InitialCount, _In_ LONG MaximumCount ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenSemaphore( _Out_ PHANDLE SemaphoreHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI NTSTATUS NTAPI NtReleaseSemaphore( _In_ HANDLE SemaphoreHandle, _In_ LONG ReleaseCount, _Out_opt_ PLONG PreviousCount ); NTSYSCALLAPI NTSTATUS NTAPI NtQuerySemaphore( _In_ HANDLE SemaphoreHandle, _In_ SEMAPHORE_INFORMATION_CLASS SemaphoreInformationClass, _Out_ PVOID SemaphoreInformation, _In_ ULONG SemaphoreInformationLength, _Out_opt_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateTimer( _Out_ PHANDLE TimerHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ TIMER_TYPE TimerType ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenTimer( _Out_ PHANDLE TimerHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI NTSTATUS NTAPI NtSetTimer( _In_ HANDLE TimerHandle, _In_ PLARGE_INTEGER DueTime, _In_opt_ PTIMER_APC_ROUTINE TimerApcRoutine, _In_opt_ PVOID TimerContext, _In_ BOOLEAN ResumeTimer, _In_opt_ LONG Period, _Out_opt_ PBOOLEAN PreviousState ); #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSCALLAPI NTSTATUS NTAPI NtSetTimerEx( _In_ HANDLE TimerHandle, _In_ TIMER_SET_INFORMATION_CLASS TimerSetInformationClass, _Inout_ PVOID TimerSetInformation, _In_ ULONG TimerSetInformationLength ); #endif NTSYSCALLAPI NTSTATUS NTAPI NtCancelTimer( _In_ HANDLE TimerHandle, _Out_opt_ PBOOLEAN CurrentState ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryTimer( _In_ HANDLE TimerHandle, _In_ TIMER_INFORMATION_CLASS TimerInformationClass, _Out_ PVOID TimerInformation, _In_ ULONG TimerInformationLength, _Out_opt_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateKeyedEvent( _Out_ PHANDLE KeyedEventHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ ULONG Flags ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenKeyedEvent( _Out_ PHANDLE KeyedEventHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI NTSTATUS NTAPI NtReleaseKeyedEvent( _In_ HANDLE KeyedEventHandle, _In_ PVOID KeyValue, _In_ BOOLEAN Alertable, _In_opt_ PLARGE_INTEGER Timeout ); NTSYSCALLAPI NTSTATUS NTAPI NtWaitForKeyedEvent( _In_ HANDLE KeyedEventHandle, _In_ PVOID KeyValue, _In_ BOOLEAN Alertable, _In_opt_ PLARGE_INTEGER Timeout ); #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSCALLAPI NTSTATUS NTAPI NtUmsThreadYield( _In_ PVOID SchedulerParam ); #endif #if NTDDI_VERSION >= NTDDI_VISTA NTSYSCALLAPI NTSTATUS NTAPI NtCreateTransactionManager( _Out_ PHANDLE TmHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ PUNICODE_STRING LogFileName, _In_opt_ ULONG CreateOptions, _In_opt_ ULONG CommitStrength ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenTransactionManager( _Out_ PHANDLE TmHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ PUNICODE_STRING LogFileName, _In_opt_ LPGUID TmIdentity, _In_opt_ ULONG OpenOptions ); NTSYSCALLAPI NTSTATUS NTAPI NtRenameTransactionManager( _In_ PUNICODE_STRING LogFileName, _In_ LPGUID ExistingTransactionManagerGuid ); NTSYSCALLAPI NTSTATUS NTAPI NtRollforwardTransactionManager( _In_ HANDLE TransactionManagerHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); NTSYSCALLAPI NTSTATUS NTAPI NtRecoverTransactionManager( _In_ HANDLE TransactionManagerHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryInformationTransactionManager( _In_ HANDLE TransactionManagerHandle, _In_ TRANSACTIONMANAGER_INFORMATION_CLASS TransactionManagerInformationClass, _Out_ PVOID TransactionManagerInformation, _In_ ULONG TransactionManagerInformationLength, _Out_opt_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtSetInformationTransactionManager( _In_opt_ HANDLE TmHandle, _In_ TRANSACTIONMANAGER_INFORMATION_CLASS TransactionManagerInformationClass, _In_ PVOID TransactionManagerInformation, _In_ ULONG TransactionManagerInformationLength ); NTSYSCALLAPI NTSTATUS NTAPI NtEnumerateTransactionObject( _In_opt_ HANDLE RootObjectHandle, _In_ KTMOBJECT_TYPE QueryType, _Inout_updates_bytes_(ObjectCursorLength) PKTMOBJECT_CURSOR ObjectCursor, _In_ ULONG ObjectCursorLength, _Out_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateTransaction( _Out_ PHANDLE TransactionHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ LPGUID Uow, _In_opt_ HANDLE TmHandle, _In_opt_ ULONG CreateOptions, _In_opt_ ULONG IsolationLevel, _In_opt_ ULONG IsolationFlags, _In_opt_ PLARGE_INTEGER Timeout, _In_opt_ PUNICODE_STRING Description ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenTransaction( _Out_ PHANDLE TransactionHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ LPGUID Uow, _In_opt_ HANDLE TmHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryInformationTransaction( _In_ HANDLE TransactionHandle, _In_ TRANSACTION_INFORMATION_CLASS TransactionInformationClass, _Out_ PVOID TransactionInformation, _In_ ULONG TransactionInformationLength, _Out_opt_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtSetInformationTransaction( _In_ HANDLE TransactionHandle, _In_ TRANSACTION_INFORMATION_CLASS TransactionInformationClass, _In_ PVOID TransactionInformation, _In_ ULONG TransactionInformationLength ); NTSYSCALLAPI NTSTATUS NTAPI NtCommitTransaction( _In_ HANDLE TransactionHandle, _In_ BOOLEAN Wait ); NTSYSCALLAPI NTSTATUS NTAPI NtRollbackTransaction( _In_ HANDLE TransactionHandle, _In_ BOOLEAN Wait ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateEnlistment( _Out_ PHANDLE EnlistmentHandle, _In_ ACCESS_MASK DesiredAccess, _In_ HANDLE ResourceManagerHandle, _In_ HANDLE TransactionHandle, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ ULONG CreateOptions, _In_ NOTIFICATION_MASK NotificationMask, _In_opt_ PVOID EnlistmentKey ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenEnlistment( _Out_ PHANDLE EnlistmentHandle, _In_ ACCESS_MASK DesiredAccess, _In_ HANDLE ResourceManagerHandle, _In_ LPGUID EnlistmentGuid, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryInformationEnlistment( _In_ HANDLE EnlistmentHandle, _In_ ENLISTMENT_INFORMATION_CLASS EnlistmentInformationClass, _Out_ PVOID EnlistmentInformation, _In_ ULONG EnlistmentInformationLength, _Out_opt_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtSetInformationEnlistment( _In_opt_ HANDLE EnlistmentHandle, _In_ ENLISTMENT_INFORMATION_CLASS EnlistmentInformationClass, _In_ PVOID EnlistmentInformation, _In_ ULONG EnlistmentInformationLength ); NTSYSCALLAPI NTSTATUS NTAPI NtRecoverEnlistment( _In_ HANDLE EnlistmentHandle, _In_opt_ PVOID EnlistmentKey ); NTSYSCALLAPI NTSTATUS NTAPI NtPrePrepareEnlistment( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); NTSYSCALLAPI NTSTATUS NTAPI NtPrepareEnlistment( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); NTSYSCALLAPI NTSTATUS NTAPI NtCommitEnlistment( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); NTSYSCALLAPI NTSTATUS NTAPI NtRollbackEnlistment( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); NTSYSCALLAPI NTSTATUS NTAPI NtPrePrepareComplete( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); NTSYSCALLAPI NTSTATUS NTAPI NtPrepareComplete( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); NTSYSCALLAPI NTSTATUS NTAPI NtCommitComplete( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); NTSYSCALLAPI NTSTATUS NTAPI NtReadOnlyEnlistment( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); NTSYSCALLAPI NTSTATUS NTAPI NtRollbackComplete( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); NTSYSCALLAPI NTSTATUS NTAPI NtSinglePhaseReject( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); NTSYSCALLAPI NTSTATUS NTAPI NtCreateResourceManager( _Out_ PHANDLE ResourceManagerHandle, _In_ ACCESS_MASK DesiredAccess, _In_ HANDLE TmHandle, _In_ LPGUID RmGuid, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ ULONG CreateOptions, _In_opt_ PUNICODE_STRING Description ); NTSYSCALLAPI NTSTATUS NTAPI NtOpenResourceManager( _Out_ PHANDLE ResourceManagerHandle, _In_ ACCESS_MASK DesiredAccess, _In_ HANDLE TmHandle, _In_opt_ LPGUID ResourceManagerGuid, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI NTSTATUS NTAPI NtRecoverResourceManager( _In_ HANDLE ResourceManagerHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtGetNotificationResourceManager( _In_ HANDLE ResourceManagerHandle, _Out_ PTRANSACTION_NOTIFICATION TransactionNotification, _In_ ULONG NotificationLength, _In_opt_ PLARGE_INTEGER Timeout, _Out_opt_ PULONG ReturnLength, _In_ ULONG Asynchronous, _In_opt_ ULONG_PTR AsynchronousContext ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryInformationResourceManager( _In_ HANDLE ResourceManagerHandle, _In_ RESOURCEMANAGER_INFORMATION_CLASS ResourceManagerInformationClass, _Out_ PVOID ResourceManagerInformation, _In_ ULONG ResourceManagerInformationLength, _Out_opt_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtSetInformationResourceManager( _In_ HANDLE ResourceManagerHandle, _In_ RESOURCEMANAGER_INFORMATION_CLASS ResourceManagerInformationClass, _In_ PVOID ResourceManagerInformation, _In_ ULONG ResourceManagerInformationLength ); NTSYSCALLAPI NTSTATUS NTAPI NtRegisterProtocolAddressInformation( _In_ HANDLE ResourceManager, _In_ PCRM_PROTOCOL_ID ProtocolId, _In_ ULONG ProtocolInformationSize, _In_ PVOID ProtocolInformation, _In_opt_ ULONG CreateOptions ); NTSYSCALLAPI NTSTATUS NTAPI NtPropagationComplete( _In_ HANDLE ResourceManagerHandle, _In_ ULONG RequestCookie, _In_ ULONG BufferLength, _In_ PVOID Buffer ); NTSYSCALLAPI NTSTATUS NTAPI NtPropagationFailed( _In_ HANDLE ResourceManagerHandle, _In_ ULONG RequestCookie, _In_ NTSTATUS PropStatus ); NTSYSCALLAPI NTSTATUS NTAPI NtFreezeTransactions( _In_ PLARGE_INTEGER FreezeTimeout, _In_ PLARGE_INTEGER ThawTimeout ); NTSYSCALLAPI NTSTATUS NTAPI NtThawTransactions( ); #endif #if NTDDI_VERSION >= NTDDI_VISTA NTSYSCALLAPI NTSTATUS NTAPI NtCreateWorkerFactory( _Out_ PHANDLE WorkerFactoryHandleReturn, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ HANDLE CompletionPortHandle, _In_ HANDLE WorkerProcessHandle, _In_ PUSER_THREAD_START_ROUTINE StartRoutine, _In_opt_ PVOID StartParameter, _In_opt_ ULONG MaxThreadCount, _In_opt_ SIZE_T StackReserve, _In_opt_ SIZE_T StackCommit ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryInformationWorkerFactory( _In_ HANDLE WorkerFactoryHandle, _In_ WORKERFACTORYINFOCLASS WorkerFactoryInformationClass, _Out_ PVOID WorkerFactoryInformation, _In_ ULONG WorkerFactoryInformationLength, _Out_opt_ PULONG ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtSetInformationWorkerFactory( _In_ HANDLE WorkerFactoryHandle, _In_ WORKERFACTORYINFOCLASS WorkerFactoryInformationClass, _In_ PVOID WorkerFactoryInformation, _In_ ULONG WorkerFactoryInformationLength ); NTSYSCALLAPI NTSTATUS NTAPI NtShutdownWorkerFactory( _In_ HANDLE WorkerFactoryHandle, _Inout_ volatile LONG* PendingWorkerCount ); NTSYSCALLAPI NTSTATUS NTAPI NtReleaseWorkerFactoryWorker( _In_ HANDLE WorkerFactoryHandle ); NTSYSCALLAPI NTSTATUS NTAPI NtWorkerFactoryWorkerReady( _In_ HANDLE WorkerFactoryHandle ); #endif #if NTDDI_VERSION >= NTDDI_VISTA #if NTDDI_VERSION >= NTDDI_WIN8 || defined(_WIN64) // Windows 8+ declaration, but can be used on any x64 Windows Vista+ NTSYSCALLAPI NTSTATUS NTAPI NtWaitForWorkViaWorkerFactory( _In_ HANDLE WorkerFactoryHandle, _Out_ PFILE_IO_COMPLETION_INFORMATION MiniPacket, _In_ ULONG Count, _Out_ PULONG NumEntriesRemoved, _In_ PLARGE_INTEGER Unknown // Wrong type (but works) ); #else // Windows Vista/7 x86 NTSYSCALLAPI NTSTATUS NTAPI NtWaitForWorkViaWorkerFactory( _In_ HANDLE WorkerFactoryHandle, _Out_ PFILE_IO_COMPLETION_INFORMATION MiniPacket ); #endif #endif NTSYSCALLAPI NTSTATUS NTAPI NtQuerySystemEnvironmentValue( _In_ PUNICODE_STRING VariableName, _Out_ PWSTR VariableValue, _In_ USHORT ValueLength, _Out_opt_ PUSHORT ReturnLength ); NTSYSCALLAPI NTSTATUS NTAPI NtSetSystemEnvironmentValue( _In_ PUNICODE_STRING VariableName, _In_ PUNICODE_STRING VariableValue ); NTSYSCALLAPI NTSTATUS NTAPI NtQuerySystemEnvironmentValueEx( _In_ PUNICODE_STRING VariableName, _In_ LPGUID VendorGuid, _Out_ PVOID Value, _Inout_ PULONG ValueLength, _Out_opt_ PULONG Attributes ); NTSYSCALLAPI NTSTATUS NTAPI NtSetSystemEnvironmentValueEx( _In_ PUNICODE_STRING VariableName, _In_ LPGUID VendorGuid, _In_ PVOID Value, _In_ ULONG ValueLength, _In_ ULONG Attributes ); NTSYSCALLAPI NTSTATUS NTAPI NtEnumerateSystemEnvironmentValuesEx( _In_ ULONG InformationClass, _Out_ PVOID Buffer, _Inout_ PULONG BufferLength ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSCALLAPI NTSTATUS NTAPI NtAddBootEntry( _In_ PBOOT_ENTRY BootEntry, _Out_opt_ PULONG Id ); NTSYSCALLAPI NTSTATUS NTAPI NtDeleteBootEntry( _In_ ULONG Id ); NTSYSCALLAPI NTSTATUS NTAPI NtModifyBootEntry( _In_ PBOOT_ENTRY BootEntry ); NTSYSCALLAPI NTSTATUS NTAPI NtEnumerateBootEntries( _Out_writes_bytes_opt_(*BufferLength) PVOID Buffer, _Inout_ PULONG BufferLength ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryBootEntryOrder( _Out_writes_opt_(*Count) PULONG Ids, _Inout_ PULONG Count ); NTSYSCALLAPI NTSTATUS NTAPI NtSetBootEntryOrder( _In_reads_(Count) PULONG Ids, _In_ ULONG Count ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryBootOptions( _Out_writes_bytes_opt_(*BootOptionsLength) PBOOT_OPTIONS BootOptions, _Inout_ PULONG BootOptionsLength ); NTSYSCALLAPI NTSTATUS NTAPI NtSetBootOptions( _In_ PBOOT_OPTIONS BootOptions, _In_ ULONG FieldsToChange ); NTSYSCALLAPI NTSTATUS NTAPI NtTranslateFilePath( _In_ PFILE_PATH InputFilePath, _In_ ULONG OutputType, _Out_writes_bytes_opt_(*OutputFilePathLength) PFILE_PATH OutputFilePath, _Inout_opt_ PULONG OutputFilePathLength ); NTSYSCALLAPI NTSTATUS NTAPI NtAddDriverEntry( _In_ PEFI_DRIVER_ENTRY DriverEntry, _Out_opt_ PULONG Id ); NTSYSCALLAPI NTSTATUS NTAPI NtDeleteDriverEntry( _In_ ULONG Id ); NTSYSCALLAPI NTSTATUS NTAPI NtModifyDriverEntry( _In_ PEFI_DRIVER_ENTRY DriverEntry ); NTSYSCALLAPI NTSTATUS NTAPI NtEnumerateDriverEntries( _Out_writes_bytes_opt_(*BufferLength) PVOID Buffer, _Inout_ PULONG BufferLength ); NTSYSCALLAPI NTSTATUS NTAPI NtQueryDriverEntryOrder( _Out_writes_opt_(*Count) PULONG Ids, _Inout_ PULONG Count ); NTSYSCALLAPI NTSTATUS NTAPI NtSetDriverEntryOrder( _In_reads_(Count) PULONG Ids, _In_ ULONG Count ); #endif #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSCALLAPI NTSTATUS NTAPI NtSerializeBoot( ); NTSYSCALLAPI NTSTATUS NTAPI NtEnableLastKnownGood( ); NTSYSCALLAPI NTSTATUS NTAPI NtDisableLastKnownGood( ); #endif NTSYSAPI ULONG __cdecl DbgPrint( _In_ PCH Format, ... ); NTSYSAPI ULONG __cdecl DbgPrintEx( _In_ ULONG ComponentId, _In_ ULONG Level, _In_ PCSTR Format, ... ); NTSYSAPI VOID NTAPI DbgBreakPoint( ); NTSYSAPI NTSTATUS NTAPI DbgUiConnectToDbg( ); NTSYSAPI HANDLE NTAPI DbgUiGetThreadDebugObject( ); NTSYSAPI VOID NTAPI DbgUiSetThreadDebugObject( _In_ HANDLE DebugObject ); NTSYSAPI NTSTATUS NTAPI DbgUiWaitStateChange( _Out_ PDBGUI_WAIT_STATE_CHANGE StateChange, _In_opt_ PLARGE_INTEGER Timeout ); NTSYSAPI NTSTATUS NTAPI DbgUiContinue( _In_ PCLIENT_ID AppClientId, _In_ NTSTATUS ContinueStatus ); NTSYSAPI NTSTATUS NTAPI DbgUiStopDebugging( _In_ HANDLE Process ); NTSYSAPI NTSTATUS NTAPI DbgUiDebugActiveProcess( _In_ HANDLE Process ); NTSYSAPI VOID NTAPI DbgUiRemoteBreakin( _In_ PVOID Context ); NTSYSAPI NTSTATUS NTAPI DbgUiIssueRemoteBreakin( _In_ HANDLE Process ); NTSYSAPI NTSTATUS NTAPI DbgUiConvertStateChangeStructure( _In_ PDBGUI_WAIT_STATE_CHANGE StateChange, _Out_ DEBUG_EVENT* DebugEvent ); NTSYSAPI NTSTATUS NTAPI LdrLoadDll( _In_opt_ PCWSTR DllPath, _In_opt_ PULONG DllCharacteristics, _In_ PUNICODE_STRING DllName, _Out_ PVOID* DllHandle ); NTSYSAPI NTSTATUS NTAPI LdrGetDllHandle( _In_opt_ PCWSTR DllPath, _In_opt_ PULONG DllCharacteristics, _In_ PUNICODE_STRING DllName, _Out_ PVOID* DllHandle ); NTSYSAPI NTSTATUS NTAPI LdrGetDllHandleEx( _In_ ULONG Flags, _In_opt_ PCWSTR DllPath, _In_opt_ PULONG DllCharacteristics, _In_ PUNICODE_STRING DllName, _Out_opt_ PVOID* DllHandle ); #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSAPI NTSTATUS NTAPI LdrGetDllHandleByMapping( _In_ PVOID Base, _Out_ PVOID* DllHandle ); NTSYSAPI NTSTATUS NTAPI LdrGetDllHandleByName( _In_opt_ PUNICODE_STRING BaseDllName, _In_opt_ PUNICODE_STRING FullDllName, _Out_ PVOID* DllHandle ); #endif NTSYSAPI NTSTATUS NTAPI LdrGetProcedureAddress( _In_ PVOID DllHandle, _In_opt_ CONST PANSI_STRING ProcedureName, _In_opt_ ULONG ProcedureNumber, _Out_ PVOID* ProcedureAddress ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSAPI NTSTATUS NTAPI LdrGetProcedureAddressEx( _In_ PVOID DllHandle, _In_opt_ PANSI_STRING ProcedureName, _In_opt_ ULONG ProcedureNumber, _Out_ PVOID* ProcedureAddress, _In_ ULONG Flags ); #endif NTSYSAPI NTSTATUS NTAPI LdrLockLoaderLock( _In_ ULONG Flags, _Out_opt_ ULONG* Disposition, _Out_ PVOID* Cookie ); NTSYSAPI NTSTATUS NTAPI LdrUnlockLoaderLock( _In_ ULONG Flags, _Inout_ PVOID Cookie ); NTSYSAPI PIMAGE_BASE_RELOCATION NTAPI LdrProcessRelocationBlock( _In_ ULONG_PTR VA, _In_ ULONG SizeOfBlock, _In_ PUSHORT NextOffset, _In_ LONG_PTR Diff ); NTSYSAPI NTSTATUS NTAPI LdrUnloadDll( _In_ PVOID DllHandle ); NTSYSAPI NTSTATUS NTAPI LdrDisableThreadCalloutsForDll( _In_ PVOID DllHandle ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSAPI NTSTATUS NTAPI LdrOpenImageFileOptionsKey( _In_ PUNICODE_STRING SubKey, _In_ BOOLEAN Wow64, _Out_ PHANDLE NewKeyHandle ); NTSYSAPI NTSTATUS NTAPI LdrQueryImageFileKeyOption( _In_ HANDLE KeyHandle, _In_ PCWSTR ValueName, _In_ ULONG Type, _Out_ PVOID Buffer, _In_ ULONG BufferSize, _Out_opt_ PULONG ReturnedLength ); #endif NTSYSAPI NTSTATUS NTAPI LdrVerifyImageMatchesChecksum( _In_ HANDLE ImageFileHandle, _In_opt_ PLDR_IMPORT_MODULE_CALLBACK ImportCallbackRoutine, _In_ PVOID ImportCallbackParameter, _Out_opt_ PUSHORT ImageCharacteristics ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSAPI NTSTATUS NTAPI LdrVerifyImageMatchesChecksumEx( _In_ HANDLE ImageFileHandle, _Inout_ PLDR_VERIFY_IMAGE_INFO VerifyInfo ); #endif NTSYSAPI NTSTATUS NTAPI LdrFindResourceDirectory_U( _In_ PVOID DllHandle, _In_ CONST LDR_RESOURCE_INFO* ResourceIdPath, _In_ ULONG ResourceIdPathLength, _Out_ PIMAGE_RESOURCE_DIRECTORY* ResourceDirectory ); NTSYSAPI NTSTATUS NTAPI LdrFindResource_U( _In_ PVOID DllHandle, _In_ CONST LDR_RESOURCE_INFO* ResourceIdPath, _In_ ULONG ResourceIdPathLength, _Out_ PIMAGE_RESOURCE_DATA_ENTRY* ResourceDataEntry ); NTSYSAPI NTSTATUS NTAPI LdrFindResourceEx_U( _In_opt_ ULONG Flags, _In_ PVOID DllHandle, _In_ CONST LDR_RESOURCE_INFO* ResourceIdPath, _In_ ULONG ResourceIdPathLength, _Out_ PIMAGE_RESOURCE_DATA_ENTRY* ResourceDataEntry ); NTSYSAPI VOID NTAPI RtlAssert( _In_ PVOID VoidFailedAssertion, _In_ PVOID VoidFileName, _In_ ULONG LineNumber, _In_opt_ PSTR MutableMessage ); NTSYSAPI DECLSPEC_NORETURN VOID NTAPI RtlRaiseStatus( _In_ NTSTATUS Status ); NTSYSAPI VOID NTAPI RtlRaiseException( _In_ PEXCEPTION_RECORD ExceptionRecord ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSAPI NTSTATUS NTAPI RtlConnectToSm( _In_ PUNICODE_STRING ApiPortName, _In_ HANDLE ApiPortHandle, _In_ DWORD ProcessImageType, _Out_ PHANDLE SmssConnection ); NTSYSAPI NTSTATUS NTAPI RtlSendMsgToSm( _In_ HANDLE ApiPortHandle, _In_ PPORT_MESSAGE MessageData ); NTSYSAPI NTSTATUS NTAPI RtlRegisterThreadWithCsrss( ); #endif NTSYSAPI NTSTATUS NTAPI RtlEnterCriticalSection( _Inout_ PRTL_CRITICAL_SECTION CriticalSection ); NTSYSAPI NTSTATUS NTAPI RtlLeaveCriticalSection( _Inout_ PRTL_CRITICAL_SECTION CriticalSection ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSAPI LOGICAL NTAPI RtlIsCriticalSectionLocked( _In_ PRTL_CRITICAL_SECTION CriticalSection ); NTSYSAPI LOGICAL NTAPI RtlIsCriticalSectionLockedByThread( _In_ PRTL_CRITICAL_SECTION CriticalSection ); NTSYSAPI ULONG NTAPI RtlGetCriticalSectionRecursionCount( _In_ PRTL_CRITICAL_SECTION CriticalSection ); #endif NTSYSAPI LOGICAL NTAPI RtlTryEnterCriticalSection( _Inout_ PRTL_CRITICAL_SECTION CriticalSection ); NTSYSAPI NTSTATUS NTAPI RtlInitializeCriticalSection( _Out_ PRTL_CRITICAL_SECTION CriticalSection ); NTSYSAPI VOID NTAPI RtlEnableEarlyCriticalSectionEventCreation( ); NTSYSAPI NTSTATUS NTAPI RtlInitializeCriticalSectionAndSpinCount( _Out_ PRTL_CRITICAL_SECTION CriticalSection, _In_ ULONG SpinCount ); NTSYSAPI ULONG NTAPI RtlSetCriticalSectionSpinCount( _Inout_ PRTL_CRITICAL_SECTION CriticalSection, _In_ ULONG SpinCount ); NTSYSAPI NTSTATUS NTAPI RtlDeleteCriticalSection( _Inout_ PRTL_CRITICAL_SECTION CriticalSection ); #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSAPI BOOL NTAPI RtlQueryPerformanceFrequency( _Out_ PLARGE_INTEGER Frequency ); #else FORCEINLINE BOOL NTAPI RtlQueryPerformanceFrequency( _Out_ PLARGE_INTEGER Frequency ) { LARGE_INTEGER _; return NT_SUCCESS(NtQueryPerformanceCounter(&_, Frequency)); } #endif #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSAPI BOOL NTAPI RtlQueryPerformanceCounter( _Out_ PLARGE_INTEGER PerformanceCount ); #else FORCEINLINE BOOL NTAPI RtlQueryPerformanceCounter( _Out_ PLARGE_INTEGER PerformanceCount ) { return NT_SUCCESS(NtQueryPerformanceCounter(PerformanceCount, NULL)); } #endif NTSYSAPI NTSTATUS NTAPI RtlGetCompressionWorkSpaceSize( _In_ USHORT CompressionFormatAndEngine, _Out_ PULONG CompressBufferWorkSpaceSize, _Out_ PULONG CompressFragmentWorkSpaceSize ); NTSYSAPI NTSTATUS NTAPI RtlCompressBuffer( _In_ USHORT CompressionFormatAndEngine, _In_ PUCHAR UncompressedBuffer, _In_ ULONG UncompressedBufferSize, _Out_ PUCHAR CompressedBuffer, _In_ ULONG CompressedBufferSize, _In_ ULONG UncompressedChunkSize, _Out_ PULONG FinalCompressedSize, _In_ PVOID WorkSpace ); NTSYSAPI NTSTATUS NTAPI RtlDecompressBuffer( _In_ USHORT CompressionFormat, _Out_ PUCHAR UncompressedBuffer, _In_ ULONG UncompressedBufferSize, _In_ PUCHAR CompressedBuffer, _In_ ULONG CompressedBufferSize, _Out_ PULONG FinalUncompressedSize ); NTSYSAPI PVOID NTAPI RtlCreateHeap( _In_ ULONG Flags, _In_opt_ PVOID HeapBase, _In_opt_ SIZE_T ReserveSize, _In_opt_ SIZE_T CommitSize, _In_opt_ PVOID Lock, _In_opt_ PRTL_HEAP_PARAMETERS Parameters ); NTSYSAPI PVOID NTAPI RtlDestroyHeap( _Inout_ PVOID HeapHandle ); NTSYSAPI PVOID NTAPI RtlAllocateHeap( _In_ PVOID HeapHandle, _In_opt_ ULONG Flags, _In_ SIZE_T Size ); NTSYSAPI BOOLEAN NTAPI RtlFreeHeap( _In_ PVOID HeapHandle, _In_opt_ ULONG Flags, _Inout_opt_ PVOID BaseAddress ); NTSYSAPI NTSTATUS NTAPI RtlWalkHeap( _In_ PVOID HeapHandle, _Inout_ PRTL_HEAP_WALK_ENTRY Entry ); NTSYSAPI NTSTATUS NTAPI RtlQueryHeapInformation( _In_ PVOID HeapHandle, _In_ HEAP_INFORMATION_CLASS HeapInformationClass, _Out_opt_ PVOID HeapInformation, _In_opt_ SIZE_T HeapInformationLength, _Out_opt_ PSIZE_T ReturnLength ); NTSYSAPI NTSTATUS NTAPI RtlSetHeapInformation( _In_ PVOID HeapHandle, _In_ HEAP_INFORMATION_CLASS HeapInformationClass, _In_opt_ PVOID HeapInformation, _In_opt_ SIZE_T HeapInformationLength ); NTSYSAPI SIZE_T NTAPI RtlSizeHeap( _In_ PVOID HeapHandle, _In_ ULONG Flags, _In_ PVOID BaseAddress ); NTSYSAPI NTSTATUS NTAPI RtlZeroHeap( _In_ PVOID HeapHandle, _In_ ULONG Flags ); NTSYSAPI VOID NTAPI RtlProtectHeap( _In_ PVOID HeapHandle, _In_ BOOLEAN MakeReadOnly ); NTSYSAPI BOOLEAN NTAPI RtlLockHeap( _In_ PVOID HeapHandle ); NTSYSAPI BOOLEAN NTAPI RtlUnlockHeap( _In_ PVOID HeapHandle ); NTSYSAPI PVOID NTAPI RtlReAllocateHeap( _In_ PVOID HeapHandle, _In_ ULONG Flags, _Inout_opt_ PVOID BaseAddress, _In_ SIZE_T Size ); NTSYSAPI BOOLEAN NTAPI RtlGetUserInfoHeap( _In_ PVOID HeapHandle, _In_ ULONG Flags, _In_ PVOID BaseAddress, _Out_opt_ PVOID* UserValue, _Out_opt_ PULONG UserFlags ); NTSYSAPI BOOLEAN NTAPI RtlSetUserValueHeap( _In_ PVOID HeapHandle, _In_ ULONG Flags, _In_ PVOID BaseAddress, _In_ PVOID UserValue ); NTSYSAPI BOOLEAN NTAPI RtlSetUserFlagsHeap( _In_ PVOID HeapHandle, _In_ ULONG Flags, _In_ PVOID BaseAddress, _In_ ULONG UserFlagsReset, _In_ ULONG UserFlagsSet ); NTSYSAPI ULONG NTAPI RtlCreateTagHeap( _In_ PVOID HeapHandle, _In_ ULONG Flags, _In_opt_ PWSTR TagPrefix, _In_ PWSTR TagNames ); NTSYSAPI PWSTR NTAPI RtlQueryTagHeap( _In_ PVOID HeapHandle, _In_ ULONG Flags, _In_ USHORT TagIndex, _In_ BOOLEAN ResetCounters, _Out_opt_ PRTL_HEAP_TAG_INFO TagInfo ); NTSYSAPI SIZE_T NTAPI RtlCompactHeap( _In_ PVOID HeapHandle, _In_ ULONG Flags ); NTSYSAPI BOOLEAN NTAPI RtlValidateHeap( _In_ PVOID HeapHandle, _In_ ULONG Flags, _In_ PVOID BaseAddress ); NTSYSAPI BOOLEAN NTAPI RtlValidateProcessHeaps( ); NTSYSAPI ULONG NTAPI RtlGetProcessHeaps( _In_ ULONG NumberOfHeaps, _Out_ PVOID* ProcessHeaps ); NTSYSAPI NTSTATUS NTAPI RtlEnumProcessHeaps( _In_ PRTL_ENUM_HEAPS_ROUTINE EnumRoutine, _In_ PVOID Parameter ); NTSYSAPI ULONG NTAPI RtlUniform( _Inout_ PULONG Seed ); NTSYSAPI ULONG NTAPI RtlRandom( _Inout_ PULONG Seed ); NTSYSAPI ULONG NTAPI RtlRandomEx( _Inout_ PULONG Seed ); NTSYSAPI NTSTATUS NTAPI RtlFindMessage( _In_ PVOID DllHandle, _In_ ULONG MessageTableId, _In_ ULONG MessageLanguageId, _In_ ULONG MessageId, _Out_ PMESSAGE_RESOURCE_ENTRY* MessageEntry ); NTSYSAPI NTSTATUS NTAPI RtlFormatMessage( _In_ PCWSTR MessageFormat, _In_ ULONG MaximumWidth, _In_ BOOLEAN IgnoreInserts, _In_ BOOLEAN ArgumentsAreAnsi, _In_ BOOLEAN ArgumentsAreAnArray, _In_ va_list* Arguments, _Out_ PWSTR Buffer, _In_ ULONG Length, _Out_opt_ PULONG ReturnLength ); NTSYSAPI ULONG NTAPI RtlNtStatusToDosError( _In_ NTSTATUS Status ); NTSYSAPI ULONG NTAPI RtlNtStatusToDosErrorNoTeb( _In_ NTSTATUS Status ); NTSYSAPI NTSTATUS NTAPI RtlGetLastNtStatus( ); NTSYSAPI LONG NTAPI RtlGetLastWin32Error( ); NTSYSAPI VOID NTAPI RtlSetLastWin32ErrorAndNtStatusFromNtStatus( _In_ NTSTATUS Status ); NTSYSAPI VOID NTAPI RtlSetLastWin32Error( _In_ LONG Win32Error ); NTSYSAPI VOID NTAPI RtlRestoreLastWin32Error( _In_ LONG Win32Error ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSAPI ULONG NTAPI RtlGetThreadErrorMode( ); NTSYSAPI NTSTATUS NTAPI RtlSetThreadErrorMode( _In_ ULONG NewMode, _Out_opt_ PULONG OldMode ); #endif NTSYSAPI NTSTATUS NTAPI RtlUpcaseUnicodeString( _Out_ PUNICODE_STRING DestinationString, _In_ PCUNICODE_STRING SourceString, _In_ BOOLEAN AllocateDestinationString ); NTSYSAPI VOID NTAPI RtlInitUnicodeString( _Out_ PUNICODE_STRING DestinationString, _In_opt_ PWSTR SourceString ); NTSYSAPI VOID NTAPI RtlInitAnsiString( _Out_ PANSI_STRING DestinationString, _In_opt_ PSTR SourceString ); NTSYSAPI VOID NTAPI RtlCopyUnicodeString( _Out_ PUNICODE_STRING DestinationString, _In_ PCUNICODE_STRING SourceString ); NTSYSAPI NTSTATUS NTAPI RtlAppendUnicodeToString( _In_ PUNICODE_STRING Destination, _In_opt_ PCWSTR Source ); NTSYSAPI NTSTATUS NTAPI RtlAnsiStringToUnicodeString( _Inout_ PUNICODE_STRING DestinationString, _In_ PANSI_STRING SourceString, _In_ BOOLEAN AllocateDestinationString ); NTSYSAPI NTSTATUS NTAPI RtlUnicodeStringToAnsiString( _Inout_ PANSI_STRING DestinationString, _In_ PUNICODE_STRING SourceString, _In_ BOOLEAN AllocateDestinationString ); NTSYSAPI VOID NTAPI RtlFreeAnsiString( _Inout_ PANSI_STRING AnsiString ); NTSYSAPI NTSTATUS NTAPI RtlDefaultNpAcl( _Out_ PACL* Dacl ); NTSYSAPI NTSTATUS NTAPI RtlCreateEnvironment( _In_ BOOLEAN CloneCurrentEnvironment, _Out_ PVOID* Environment ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSAPI NTSTATUS NTAPI RtlCreateEnvironmentEx( _In_ PVOID SourceEnv, _Out_ PVOID* Environment, _In_ ULONG Flags ); #endif NTSYSAPI NTSTATUS NTAPI RtlDestroyEnvironment( _In_ PVOID Environment ); NTSYSAPI NTSTATUS NTAPI RtlSetCurrentEnvironment( _In_ PVOID Environment, _Out_opt_ PVOID* PreviousEnvironment ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSAPI NTSTATUS NTAPI RtlSetEnvironmentVar( _In_opt_ PWSTR* Environment, _In_ PWSTR Name, _In_ SIZE_T NameLength, _In_ PWSTR Value, _In_ SIZE_T ValueLength ); #endif NTSYSAPI NTSTATUS NTAPI RtlSetEnvironmentVariable( _In_opt_ PVOID* Environment, _In_ PUNICODE_STRING Name, _In_ PUNICODE_STRING Value ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSAPI NTSTATUS NTAPI RtlQueryEnvironmentVariable( _In_opt_ PVOID Environment, _In_ PWSTR Name, _In_ SIZE_T NameLength, _Out_ PWSTR Value, _In_ SIZE_T ValueLength, _Out_ PSIZE_T ReturnLength ); #endif NTSYSAPI NTSTATUS NTAPI RtlQueryEnvironmentVariable_U( _In_opt_ PVOID Environment, _In_ PUNICODE_STRING Name, _Out_ PUNICODE_STRING Value ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSAPI NTSTATUS NTAPI RtlExpandEnvironmentStrings( _In_opt_ PVOID Environment, _In_ PWSTR Src, _In_ SIZE_T SrcLength, _Out_ PWSTR Dst, _In_ SIZE_T DstLength, _Out_opt_ PSIZE_T ReturnLength ); #endif NTSYSAPI NTSTATUS NTAPI RtlExpandEnvironmentStrings_U( _In_opt_ PVOID Environment, _In_ PUNICODE_STRING Source, _Out_ PUNICODE_STRING Destination, _Out_opt_ PULONG ReturnedLength ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSAPI NTSTATUS NTAPI RtlSetEnvironmentStrings( _In_ PWCHAR NewEnvironment, _In_ SIZE_T NewEnvironmentSize ); #endif NTSYSAPI NTSTATUS NTAPI RtlCreateProcessParameters( _Out_ PRTL_USER_PROCESS_PARAMETERS* pProcessParameters, _In_ PUNICODE_STRING ImagePathName, _In_opt_ PUNICODE_STRING DllPath, _In_opt_ PUNICODE_STRING CurrentDirectory, _In_opt_ PUNICODE_STRING CommandLine, _In_opt_ PVOID Environment, _In_opt_ PUNICODE_STRING WindowTitle, _In_opt_ PUNICODE_STRING DesktopInfo, _In_opt_ PUNICODE_STRING ShellInfo, _In_opt_ PUNICODE_STRING RuntimeData ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSAPI NTSTATUS NTAPI RtlCreateProcessParametersEx( _Out_ PRTL_USER_PROCESS_PARAMETERS* pProcessParameters, _In_ PUNICODE_STRING ImagePathName, _In_opt_ PUNICODE_STRING DllPath, _In_opt_ PUNICODE_STRING CurrentDirectory, _In_opt_ PUNICODE_STRING CommandLine, _In_opt_ PVOID Environment, _In_opt_ PUNICODE_STRING WindowTitle, _In_opt_ PUNICODE_STRING DesktopInfo, _In_opt_ PUNICODE_STRING ShellInfo, _In_opt_ PUNICODE_STRING RuntimeData, _In_ ULONG Flags // Pass RTL_USER_PROCESS_PARAMETERS_NORMALIZED to keep parameters normalized ); #endif NTSYSAPI NTSTATUS NTAPI RtlDestroyProcessParameters( _In_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters ); NTSYSAPI PRTL_USER_PROCESS_PARAMETERS NTAPI RtlNormalizeProcessParams( _Inout_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters ); NTSYSAPI PRTL_USER_PROCESS_PARAMETERS NTAPI RtlDeNormalizeProcessParams( _Inout_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters ); NTSYSAPI NTSTATUS NTAPI RtlCreateUserProcess( _In_ PUNICODE_STRING NtImagePathName, _In_ ULONG AttributesDeprecated, _In_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters, _In_opt_ PSECURITY_DESCRIPTOR ProcessSecurityDescriptor, _In_opt_ PSECURITY_DESCRIPTOR ThreadSecurityDescriptor, _In_opt_ HANDLE ParentProcess, _In_ BOOLEAN InheritHandles, _In_opt_ HANDLE DebugPort, _In_opt_ HANDLE TokenHandle, // used to be ExceptionPort _Out_ PRTL_USER_PROCESS_INFORMATION ProcessInformation ); NTSYSAPI NTSTATUS NTAPI RtlCreateUserThread( _In_ HANDLE Process, _In_opt_ PSECURITY_DESCRIPTOR ThreadSecurityDescriptor, _In_ BOOLEAN CreateSuspended, _In_opt_ ULONG ZeroBits, _In_opt_ SIZE_T MaximumStackSize, _In_opt_ SIZE_T CommittedStackSize, _In_ PUSER_THREAD_START_ROUTINE StartAddress, _In_opt_ PVOID Parameter, _Out_opt_ PHANDLE Thread, _Out_opt_ PCLIENT_ID ClientId ); NTSYSAPI NTSTATUS NTAPI RtlDosApplyFileIsolationRedirection_Ustr( _In_ ULONG Flags, _In_ PUNICODE_STRING OriginalName, _In_ PUNICODE_STRING Extension, _Inout_ PUNICODE_STRING StaticString, _Inout_ PUNICODE_STRING DynamicString, _Inout_ PUNICODE_STRING* NewName, _In_ PULONG NewFlags, _In_ PSIZE_T FileNameSize, _In_ PSIZE_T RequiredLength ); NTSYSAPI PIMAGE_NT_HEADERS NTAPI RtlImageNtHeader( _In_ PVOID ImageBase ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSAPI NTSTATUS NTAPI RtlImageNtHeaderEx( _In_opt_ ULONG Flags, _In_ PVOID Base, _In_ ULONG64 Size, _Out_ PIMAGE_NT_HEADERS* OutHeaders ); #endif NTSYSAPI PVOID NTAPI RtlImageDirectoryEntryToData( _In_ PVOID ImageBase, _In_ BOOLEAN MappedAsImage, _In_ USHORT DirectoryEntry, _Out_ PULONG Size ); NTSYSAPI PVOID NTAPI RtlPcToFileHeader( _In_ PVOID PcValue, _Out_ PVOID* BaseOfImage ); NTSYSAPI PVOID NTAPI RtlAddressInSectionTable( _In_ PIMAGE_NT_HEADERS NtHeaders, _In_ PVOID BaseOfImage, _In_ ULONG VirtualAddress ); NTSYSAPI PIMAGE_SECTION_HEADER NTAPI RtlImageRvaToSection( _In_ PIMAGE_NT_HEADERS NtHeaders, _In_ PVOID Base, _In_ ULONG Rva ); NTSYSAPI PVOID NTAPI RtlImageRvaToVa( _In_ PIMAGE_NT_HEADERS NtHeaders, _In_ PVOID Base, _In_ ULONG Rva, _Inout_opt_ PIMAGE_SECTION_HEADER* LastRvaSection ); NTSYSAPI NTSTATUS NTAPI RtlQueryProcessHeapInformation( _Inout_ PRTL_DEBUG_INFORMATION Buffer ); NTSYSAPI PRTL_DEBUG_INFORMATION NTAPI RtlCreateQueryDebugBuffer( _In_opt_ ULONG MaximumCommit, _In_ BOOLEAN UseEventPair ); NTSYSAPI NTSTATUS NTAPI RtlQueryProcessDebugInformation( _In_ HANDLE UniqueProcessId, _In_ ULONG Flags, _Inout_ PRTL_DEBUG_INFORMATION Buffer ); #ifdef _WIN64 NTSYSAPI VOID WINAPI RtlRestoreContext( _In_ PCONTEXT ContextRecord, _In_opt_ PEXCEPTION_RECORD ExceptionRecord ); #endif NTSYSAPI NTSTATUS NTAPI RtlAdjustPrivilege( _In_ ULONG Privilege, _In_ BOOLEAN Enable, _In_ BOOLEAN Client, _Out_ PBOOLEAN WasEnabled ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSAPI NTSTATUS NTAPI RtlAcquirePrivilege( _In_ PULONG Privilege, _In_ ULONG NumPriv, _In_ ULONG Flags, _Out_ PVOID* ReturnedState ); NTSYSAPI VOID NTAPI RtlReleasePrivilege( _In_ PVOID StatePointer ); #endif NTSYSAPI ULONG NTAPI RtlGetFullPathName_U( _In_ PWSTR FileName, _In_ ULONG BufferLength, _Out_ PWSTR Buffer, _Out_opt_ PWSTR* FilePart ); NTSYSAPI BOOLEAN NTAPI RtlDosPathNameToNtPathName_U( _In_ PCWSTR DosFileName, _Out_ PUNICODE_STRING NtFileName, _Out_opt_ PWSTR* FilePart, _Reserved_ PVOID Reserved ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSAPI BOOLEAN NTAPI RtlDosPathNameToRelativeNtPathName_U( _In_ PCWSTR DosFileName, _Out_ PUNICODE_STRING NtFileName, _Out_opt_ PWSTR* FilePart, _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName ); NTSYSAPI NTSTATUS NTAPI RtlDosPathNameToRelativeNtPathName_U_WithStatus( _In_ PWSTR DosFileName, _Out_ PUNICODE_STRING NtFileName, _Out_opt_ PWSTR* FilePart, _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName ); #endif NTSYSAPI RTL_PATH_TYPE NTAPI RtlDetermineDosPathNameType_U( _In_ PCWSTR Path ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSAPI NTSTATUS NTAPI RtlGetFullPathName_UstrEx( _In_ PUNICODE_STRING FileName, _In_opt_ PUNICODE_STRING StaticString, _In_opt_ PUNICODE_STRING DynamicString, _Out_opt_ PUNICODE_STRING* StringUsed, _Out_opt_ PSIZE_T FilePartSize, _Out_opt_ PBOOLEAN NameInvalid, _Out_ RTL_PATH_TYPE* PathType, _Out_opt_ PSIZE_T LengthNeeded ); #endif NTSYSAPI NTSTATUS NTAPI RtlSetCurrentDirectory_U( _In_ PUNICODE_STRING PathName ); #if NTDDI_VERSION >= NTDDI_WS03 NTSYSAPI VOID NTAPI RtlReleaseRelativeName( _In_ PRTL_RELATIVE_NAME_U RelativeName ); #endif NTSYSAPI NTSTATUS NTAPI RtlNtPathNameToDosPathName( _In_ ULONG Flags, _Inout_ PRTL_UNICODE_STRING_BUFFER Path, _Out_opt_ PULONG Disposition, _Inout_opt_ PWSTR* FilePart ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSAPI VOID NTAPI RtlInitializeSRWLock( _Out_ PRTL_SRWLOCK SRWLock ); NTSYSAPI VOID NTAPI RtlAcquireSRWLockExclusive( _Inout_ PRTL_SRWLOCK SRWLock ); NTSYSAPI VOID NTAPI RtlAcquireSRWLockShared( _Inout_ PRTL_SRWLOCK SRWLock ); NTSYSAPI VOID NTAPI RtlReleaseSRWLockExclusive( _Inout_ PRTL_SRWLOCK SRWLock ); NTSYSAPI VOID NTAPI RtlReleaseSRWLockShared( _Inout_ PRTL_SRWLOCK SRWLock ); #endif #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSAPI BOOLEAN NTAPI RtlTryAcquireSRWLockExclusive( _Inout_ PRTL_SRWLOCK SRWLock ); NTSYSAPI BOOLEAN NTAPI RtlTryAcquireSRWLockShared( _Inout_ PRTL_SRWLOCK SRWLock ); NTSYSAPI VOID NTAPI RtlAcquireReleaseSRWLockExclusive( _Inout_ PRTL_SRWLOCK SRWLock ); #endif NTSYSAPI ULONG NTAPI RtlWalkFrameChain( _Out_ PVOID* Callers, _In_ ULONG Count, _In_ ULONG Flags ); NTSYSAPI PPREFIX_TABLE_ENTRY NTAPI PfxFindPrefix( _In_ PPREFIX_TABLE PrefixTable, _In_ PANSI_STRING FullName ); NTSYSAPI VOID NTAPI PfxInitialize( _Out_ PPREFIX_TABLE PrefixTable ); NTSYSAPI BOOLEAN NTAPI PfxInsertPrefix( _In_ PPREFIX_TABLE PrefixTable, _In_ PANSI_STRING Prefix, _Out_ PPREFIX_TABLE_ENTRY PrefixTableEntry ); NTSYSAPI VOID NTAPI PfxRemovePrefix( _In_ PPREFIX_TABLE PrefixTable, _In_ PPREFIX_TABLE_ENTRY PrefixTableEntry ); NTSYSAPI NTSTATUS NTAPI RtlAbsoluteToSelfRelativeSD( _In_ PSECURITY_DESCRIPTOR AbsoluteSecurityDescriptor, _Out_ PSECURITY_DESCRIPTOR SelfRelativeSecurityDescriptor, _Inout_ PULONG BufferLength ); NTSYSAPI NTSTATUS NTAPI RtlAddAccessAllowedAce( _Inout_ PACL Acl, _In_ ULONG AceRevision, _In_ ACCESS_MASK AccessMask, _In_ PSID Sid ); NTSYSAPI NTSTATUS NTAPI RtlAddAccessAllowedAceEx( _Inout_ PACL Acl, _In_ ULONG AceRevision, _In_ ULONG AceFlags, _In_ ACCESS_MASK AccessMask, _In_ PSID Sid ); NTSYSAPI NTSTATUS NTAPI RtlAddAce( _Inout_ PACL Acl, _In_ ULONG AceRevision, _In_ ULONG StartingAceIndex, _In_ PVOID AceList, _In_ ULONG AceListLength ); NTSYSAPI NTSTATUS NTAPI RtlAddAtomToAtomTable( _In_ PVOID AtomTableHandle, _In_ PWSTR AtomName, _Inout_opt_ PRTL_ATOM Atom ); NTSYSAPI NTSTATUS NTAPI RtlAppendUnicodeStringToString( PUNICODE_STRING Destination, PCUNICODE_STRING Source ); NTSYSAPI BOOLEAN NTAPI RtlAreAllAccessesGranted( _In_ ACCESS_MASK GrantedAccess, _In_ ACCESS_MASK DesiredAccess ); NTSYSAPI BOOLEAN NTAPI RtlAreAnyAccessesGranted( _In_ ACCESS_MASK GrantedAccess, _In_ ACCESS_MASK DesiredAccess ); NTSYSAPI BOOLEAN NTAPI RtlAreBitsClear( _In_ PRTL_BITMAP BitMapHeader, _In_ ULONG StartingIndex, _In_ ULONG Length ); NTSYSAPI BOOLEAN NTAPI RtlAreBitsSet( _In_ PRTL_BITMAP BitMapHeader, _In_ ULONG StartingIndex, _In_ ULONG Length ); NTSYSAPI VOID NTAPI RtlCaptureContext( _Out_ PCONTEXT ContextRecord ); NTSYSAPI USHORT NTAPI RtlCaptureStackBackTrace( _In_ ULONG FramesToSkip, _In_ ULONG FramesToCapture, _Out_ PVOID* BackTrace, _Out_opt_ PULONG BackTraceHash ); NTSYSAPI VOID NTAPI RtlClearAllBits( _In_ PRTL_BITMAP BitMapHeader ); NTSYSAPI VOID NTAPI RtlClearBits( _In_ PRTL_BITMAP BitMapHeader, _In_ ULONG StartingIndex, _In_ ULONG NumberToClear ); NTSYSAPI NTSTATUS NTAPI RtlCreateSystemVolumeInformationFolder( _In_ PCUNICODE_STRING VolumeRootPath ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSAPI LONG NTAPI RtlCompareAltitudes( _In_ PCUNICODE_STRING Altitude1, _In_ PCUNICODE_STRING Altitude2 ); #endif NTSYSAPI LONG NTAPI RtlCompareUnicodeString( _In_ PCUNICODE_STRING String1, _In_ PCUNICODE_STRING String2, _In_ BOOLEAN CaseInSensitive ); NTSYSAPI ULONG32 NTAPI RtlComputeCrc32( _In_ ULONG32 PartialCrc, _In_ PVOID Buffer, _In_ ULONG Length ); NTSYSAPI NTSTATUS NTAPI RtlConvertSidToUnicodeString( _Inout_ PUNICODE_STRING UnicodeString, _In_ PSID Sid, _In_ BOOLEAN AllocateDestinationString ); NTSYSAPI VOID NTAPI RtlCopyLuid( _Out_ PLUID DestinationLuid, _In_ PLUID SourceLuid ); NTSYSAPI NTSTATUS NTAPI RtlCopySid( _In_ ULONG DestinationSidLength, _Out_ PSID DestinationSid, _In_ PSID SourceSid ); NTSYSAPI NTSTATUS NTAPI RtlCreateAcl( _Out_ PACL Acl, _In_ ULONG AclLength, _In_ ULONG AclRevision ); NTSYSAPI NTSTATUS NTAPI RtlCreateAtomTable( _In_ ULONG NumberOfBuckets, _Out_ PVOID* AtomTableHandle ); NTSYSAPI NTSTATUS NTAPI RtlDecompressFragment( _In_ USHORT CompressionFormat, _Out_ PUCHAR UncompressedFragment, _In_ ULONG UncompressedFragmentSize, _In_ PUCHAR CompressedBuffer, _In_ ULONG CompressedBufferSize, _In_ ULONG FragmentOffset, _Out_ PULONG FinalUncompressedSize, _In_ PVOID WorkSpace ); NTSYSAPI PRTL_SPLAY_LINKS NTAPI RtlDelete( _In_ PRTL_SPLAY_LINKS Links ); NTSYSAPI NTSTATUS NTAPI RtlDeleteAce( _Inout_ PACL Acl, _In_ ULONG AceIndex ); NTSYSAPI NTSTATUS NTAPI RtlDeleteAtomFromAtomTable( _In_ PVOID AtomTableHandle, _In_ RTL_ATOM Atom ); NTSYSAPI VOID NTAPI RtlDeleteNoSplay( _In_ PRTL_SPLAY_LINKS Links, _Inout_ PRTL_SPLAY_LINKS* Root ); NTSYSAPI NTSTATUS NTAPI RtlDowncaseUnicodeString( _Out_ PUNICODE_STRING DestinationString, _In_ PCUNICODE_STRING SourceString, _In_ BOOLEAN AllocateDestinationString ); NTSYSAPI NTSTATUS NTAPI RtlDuplicateUnicodeString( _In_ ULONG Flags, _In_ UNICODE_STRING* StringIn, _Out_ UNICODE_STRING* StringOut ); NTSYSAPI NTSTATUS NTAPI RtlEmptyAtomTable( _In_ PVOID AtomTableHandle, _In_ BOOLEAN IncludePinnedAtoms ); NTSYSAPI BOOLEAN NTAPI RtlEqualSid( _In_ PSID Sid1, _In_ PSID Sid2 ); NTSYSAPI BOOLEAN NTAPI RtlEqualString( _In_ PANSI_STRING String1, _In_ PANSI_STRING String2, _In_ BOOLEAN CaseInSensitive ); NTSYSAPI BOOLEAN NTAPI RtlEqualUnicodeString( _In_ PCUNICODE_STRING String1, _In_ PCUNICODE_STRING String2, _In_ BOOLEAN CaseInSensitive ); NTSYSAPI ULONG NTAPI RtlFindClearBits( _In_ PRTL_BITMAP BitMapHeader, _In_ ULONG NumberToFind, _In_ ULONG HintIndex ); NTSYSAPI ULONG NTAPI RtlFindClearBitsAndSet( _In_ PRTL_BITMAP BitMapHeader, _In_ ULONG NumberToFind, _In_ ULONG HintIndex ); NTSYSAPI ULONG NTAPI RtlFindClearRuns( _In_ PRTL_BITMAP BitMapHeader, _Out_ PRTL_BITMAP_RUN RunArray, _In_ ULONG SizeOfRunArray, _In_ BOOLEAN LocateLongestRuns ); NTSYSAPI ULONG NTAPI RtlFindLastBackwardRunClear( _In_ PRTL_BITMAP BitMapHeader, _In_ ULONG FromIndex, _In_ PULONG StartingRunIndex ); NTSYSAPI CCHAR NTAPI RtlFindLeastSignificantBit( _In_ ULONGLONG Set ); NTSYSAPI ULONG NTAPI RtlFindLongestRunClear( _In_ PRTL_BITMAP BitMapHeader, _In_ PULONG StartingIndex ); NTSYSAPI CCHAR NTAPI RtlFindMostSignificantBit( _In_ ULONGLONG Set ); NTSYSAPI ULONG NTAPI RtlFindNextForwardRunClear( _In_ PRTL_BITMAP BitMapHeader, _In_ ULONG FromIndex, _In_ PULONG StartingRunIndex ); NTSYSAPI ULONG NTAPI RtlFindSetBits( _In_ PRTL_BITMAP BitMapHeader, _In_ ULONG NumberToFind, _In_ ULONG HintIndex ); NTSYSAPI ULONG NTAPI RtlFindSetBitsAndClear( _In_ PRTL_BITMAP BitMapHeader, _In_ ULONG NumberToFind, _In_ ULONG HintIndex ); NTSYSAPI VOID NTAPI RtlGetCallersAddress( _Out_ PVOID* CallersAddress, _Out_ PVOID* CallersCaller ); NTSYSAPI NTSTATUS NTAPI RtlGetDaclSecurityDescriptor( _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _Out_ PBOOLEAN DaclPresent, _Out_ PACL* Dacl, _Out_ PBOOLEAN DaclDefaulted ); NTSYSAPI NTSTATUS NTAPI RtlGetGroupSecurityDescriptor( _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _Out_ PSID* Group, _Out_ PBOOLEAN GroupDefaulted ); NTSYSAPI NTSTATUS NTAPI RtlGetOwnerSecurityDescriptor( _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _Out_ PSID* Owner, _Out_ PBOOLEAN OwnerDefaulted ); NTSYSAPI NTSTATUS NTAPI RtlGetSaclSecurityDescriptor( _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _Out_ PBOOLEAN SaclPresent, _Out_ PACL* Sacl, _Out_ PBOOLEAN SaclDefaulted ); NTSYSAPI NTSTATUS NTAPI RtlGetSetBootStatusData( _In_ HANDLE Handle, _In_ BOOLEAN Get, _In_ RTL_BSD_ITEM_TYPE DataItem, _In_ PVOID DataBuffer, _In_ ULONG DataBufferLength, _Out_opt_ PULONG ByteRead ); NTSYSAPI NTSTATUS NTAPI RtlCreateBootStatusDataFile( ); NTSYSAPI NTSTATUS NTAPI RtlGetVersion( _Out_ PRTL_OSVERSIONINFOW lpVersionInformation ); NTSYSAPI NTSTATUS NTAPI RtlGUIDFromString( _In_ PUNICODE_STRING GuidString, _Out_ GUID* Guid ); NTSYSAPI NTSTATUS NTAPI RtlHashUnicodeString( _In_ UNICODE_STRING* String, _In_ BOOLEAN CaseInSensitive, _In_ ULONG HashAlgorithm, _Out_ PULONG HashValue ); NTSYSAPI NTSTATUS NTAPI RtlInitializeSid( _Out_ PSID Sid, _In_ PSID_IDENTIFIER_AUTHORITY IdentifierAuthority, _In_ UCHAR SubAuthorityCount ); NTSYSAPI ULONG NTAPI RtlLengthRequiredSid( _In_ ULONG SubAuthorityCount ); NTSYSAPI ULONG NTAPI RtlLengthSecurityDescriptor( _In_ PSECURITY_DESCRIPTOR SecurityDescriptor ); NTSYSAPI ULONG NTAPI RtlLengthSid( _In_ PSID Sid ); NTSYSAPI NTSTATUS NTAPI RtlLockBootStatusData( _Out_ PHANDLE BootStatusDataHandle ); NTSYSAPI NTSTATUS NTAPI RtlLookupAtomInAtomTable( _In_ PVOID AtomTableHandle, _In_ PWSTR AtomName, _Out_opt_ PRTL_ATOM Atom ); NTSYSAPI NTSTATUS NTAPI RtlMapSecurityErrorToNtStatus( _In_ SECURITY_STATUS Error ); NTSYSAPI NTSTATUS NTAPI RtlMultiByteToUnicodeN( _Out_ PWCH UnicodeString, _In_ ULONG MaxBytesInUnicodeString, _Out_opt_ PULONG BytesInUnicodeString, _In_ PCSTR MultiByteString, _In_ ULONG BytesInMultiByteString ); NTSYSAPI NTSTATUS NTAPI RtlMultiByteToUnicodeSize( _Out_ PULONG BytesInUnicodeString, _In_ PCSTR MultiByteString, _In_ ULONG BytesInMultiByteString ); NTSYSAPI ULONG NTAPI RtlNumberOfClearBits( _In_ PRTL_BITMAP BitMapHeader ); NTSYSAPI ULONG NTAPI RtlNumberOfSetBits( _In_ PRTL_BITMAP BitMapHeader ); NTSYSAPI NTSTATUS NTAPI RtlQueryAtomInAtomTable( _In_ PVOID AtomTableHandle, _In_ RTL_ATOM Atom, _Out_opt_ PULONG AtomUsage, _Out_opt_ PULONG AtomFlags, _Inout_opt_ PWSTR AtomName, _Inout_opt_ PULONG AtomNameLength ); NTSYSAPI PRTL_SPLAY_LINKS NTAPI RtlRealPredecessor( _In_ PRTL_SPLAY_LINKS Links ); NTSYSAPI PRTL_SPLAY_LINKS NTAPI RtlRealSuccessor( _In_ PRTL_SPLAY_LINKS Links ); NTSYSAPI VOID NTAPI RtlRunDecodeUnicodeString( _In_ UCHAR Seed, _Inout_ PUNICODE_STRING String ); NTSYSAPI VOID NTAPI RtlRunEncodeUnicodeString( _In_opt_ PUCHAR Seed, _Inout_ PUNICODE_STRING String ); NTSYSAPI NTSTATUS NTAPI RtlSelfRelativeToAbsoluteSD( _In_ PSECURITY_DESCRIPTOR SelfRelativeSecurityDescriptor, _Out_ PSECURITY_DESCRIPTOR AbsoluteSecurityDescriptor, _Inout_ PULONG AbsoluteSecurityDescriptorSize, _Out_ PACL Dacl, _Inout_ PULONG DaclSize, _Out_ PACL Sacl, _Inout_ PULONG SaclSize, _Out_opt_ PSID Owner, _Inout_ PULONG OwnerSize, _Out_opt_ PSID PrimaryGroup, _Inout_ PULONG PrimaryGroupSize ); NTSYSAPI NTSTATUS NTAPI RtlSelfRelativeToAbsoluteSD2( _Inout_ PSECURITY_DESCRIPTOR pSelfRelativeSecurityDescriptor, _Inout_ PULONG pBufferSize ); NTSYSAPI VOID NTAPI RtlSetAllBits( _In_ PRTL_BITMAP BitMapHeader ); NTSYSAPI VOID NTAPI RtlSetBits( _In_ PRTL_BITMAP BitMapHeader, _In_ ULONG StartingIndex, _In_ ULONG NumberToSet ); NTSYSAPI NTSTATUS NTAPI RtlSetDaclSecurityDescriptor( _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_ BOOLEAN DaclPresent, _In_opt_ PACL Dacl, _In_ BOOLEAN DaclDefaulted ); NTSYSAPI NTSTATUS NTAPI RtlSetGroupSecurityDescriptor( _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_opt_ PSID Group, _In_opt_ BOOLEAN GroupDefaulted ); NTSYSAPI NTSTATUS NTAPI RtlSetOwnerSecurityDescriptor( _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_opt_ PSID Owner, _In_ BOOLEAN OwnerDefaulted ); NTSYSAPI NTSTATUS NTAPI RtlSetSaclSecurityDescriptor( _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_ BOOLEAN SaclPresent, _In_opt_ PACL Sacl, _In_opt_ BOOLEAN SaclDefaulted ); NTSYSAPI PRTL_SPLAY_LINKS NTAPI RtlSplay( _Inout_ PRTL_SPLAY_LINKS Links ); NTSYSAPI NTSTATUS NTAPI RtlStringFromGUID( _In_ REFGUID Guid, _Out_ PUNICODE_STRING GuidString ); NTSYSAPI PUCHAR NTAPI RtlSubAuthorityCountSid( _In_ PSID Sid ); NTSYSAPI PULONG NTAPI RtlSubAuthoritySid( _In_ PSID Sid, _In_ ULONG SubAuthority ); NTSYSAPI PRTL_SPLAY_LINKS NTAPI RtlSubtreePredecessor( _In_ PRTL_SPLAY_LINKS Links ); NTSYSAPI PRTL_SPLAY_LINKS NTAPI RtlSubtreeSuccessor( _In_ PRTL_SPLAY_LINKS Links ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSAPI BOOLEAN NTAPI RtlTestBit( _In_ PRTL_BITMAP BitMapHeader, _In_ ULONG BitNumber ); #endif NTSYSAPI VOID NTAPI RtlUnlockBootStatusData( _In_ HANDLE BootStatusDataHandle ); NTSYSAPI NTSTATUS NTAPI RtlCreateSecurityDescriptor( _Out_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_ ULONG Revision ); NTSYSAPI BOOLEAN NTAPI RtlValidRelativeSecurityDescriptor( _In_ PSECURITY_DESCRIPTOR SecurityDescriptorInput, _In_ ULONG SecurityDescriptorLength, _In_ SECURITY_INFORMATION RequiredInformation ); NTSYSAPI BOOLEAN NTAPI RtlValidSecurityDescriptor( _In_ PSECURITY_DESCRIPTOR SecurityDescriptor ); NTSYSAPI BOOLEAN NTAPI RtlValidSid( _In_ PSID Sid ); NTSYSAPI NTSTATUS NTAPI RtlVerifyVersionInfo( _In_ RTL_OSVERSIONINFOEXW VersionInfo, _In_ ULONG TypeMask, _In_ ULONGLONG ConditionMask ); NTSYSAPI ULONGLONG NTAPI VerSetConditionMask( _In_ ULONGLONG ConditionMask, _In_ ULONG TypeMask, _In_ UCHAR Condition ); #if NTDDI_VERSION >= NTDDI_VISTA NTSYSAPI NTSTATUS NTAPI TpAllocPool( _Out_ PTP_POOL* PoolReturn, _Reserved_ PVOID Reserved ); #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSAPI NTSTATUS NTAPI TpDisablePoolCallbackChecks( _Inout_ PTP_POOL Pool ); #endif NTSYSAPI VOID NTAPI TpReleasePool( _Inout_ PTP_POOL Pool ); NTSYSAPI VOID NTAPI TpSetPoolMaxThreads( _Inout_ PTP_POOL Pool, _In_ LONG MaxThreads ); NTSYSAPI NTSTATUS NTAPI TpSetPoolMinThreads( _Inout_ PTP_POOL Pool, _In_ LONG MinThreads ); #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSAPI NTSTATUS NTAPI TpQueryPoolStackInformation( _In_ PTP_POOL Pool, _Out_ PTP_POOL_STACK_INFORMATION PoolStackInformation ); NTSYSAPI NTSTATUS NTAPI TpSetPoolStackInformation( _Inout_ PTP_POOL Pool, _In_ PTP_POOL_STACK_INFORMATION PoolStackInformation ); #endif NTSYSAPI NTSTATUS NTAPI TpAllocCleanupGroup( _Out_ PTP_CLEANUP_GROUP* CleanupGroupReturn ); NTSYSAPI VOID NTAPI TpReleaseCleanupGroup( _Inout_ PTP_CLEANUP_GROUP CleanupGroup ); NTSYSAPI VOID NTAPI TpReleaseCleanupGroupMembers( _Inout_ PTP_CLEANUP_GROUP CleanupGroup, _In_ LOGICAL CancelPendingCallbacks, _Inout_opt_ PVOID CleanupParameter ); NTSYSAPI NTSTATUS NTAPI TpSimpleTryPost( _In_ PTP_SIMPLE_CALLBACK Callback, _Inout_opt_ PVOID Context, _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron ); NTSYSAPI NTSTATUS NTAPI TpAllocWork( _Out_ PTP_WORK* WorkReturn, _In_ PTP_WORK_CALLBACK Callback, _Inout_opt_ PVOID Context, _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron ); NTSYSAPI VOID NTAPI TpReleaseWork( _Inout_ PTP_WORK Work ); NTSYSAPI VOID NTAPI TpPostWork( _Inout_ PTP_WORK Work ); NTSYSAPI VOID NTAPI TpWaitForWork( _Inout_ PTP_WORK Work, _In_ LOGICAL CancelPendingCallbacks ); NTSYSAPI NTSTATUS NTAPI TpAllocTimer( _Out_ PTP_TIMER* Timer, _In_ PTP_TIMER_CALLBACK Callback, _Inout_opt_ PVOID Context, _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron ); NTSYSAPI VOID NTAPI TpReleaseTimer( _Inout_ PTP_TIMER Timer ); NTSYSAPI VOID NTAPI TpSetTimer( _Inout_ PTP_TIMER Timer, _In_opt_ PLARGE_INTEGER DueTime, _In_ LONG Period, _In_opt_ LONG WindowLength ); NTSYSAPI LOGICAL NTAPI TpIsTimerSet( _In_ PTP_TIMER Timer ); NTSYSAPI VOID NTAPI TpWaitForTimer( _Inout_ PTP_TIMER Timer, _In_ LOGICAL CancelPendingCallbacks ); NTSYSAPI NTSTATUS NTAPI TpAllocWait( _Out_ PTP_WAIT* WaitReturn, _In_ PTP_WAIT_CALLBACK Callback, _Inout_opt_ PVOID Context, _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron ); NTSYSAPI VOID NTAPI TpReleaseWait( _Inout_ PTP_WAIT Wait ); NTSYSAPI VOID NTAPI TpSetWait( _Inout_ PTP_WAIT Wait, _In_opt_ HANDLE Handle, _In_opt_ PLARGE_INTEGER Timeout ); NTSYSAPI NTSTATUS NTAPI TpAllocIoCompletion( _Out_ PTP_IO* IoReturn, _In_ HANDLE File, _In_ PTP_IO_CALLBACK Callback, _Inout_opt_ PVOID Context, _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron ); NTSYSAPI VOID NTAPI TpWaitForIoCompletion( _Inout_ PTP_IO Io, _In_ LOGICAL CancelPendingCallbacks ); NTSYSAPI NTSTATUS NTAPI TpAllocAlpcCompletion( _Out_ PTP_ALPC* AlpcReturn, _In_ HANDLE AlpcPort, _In_ PTP_ALPC_CALLBACK Callback, _Inout_opt_ PVOID Context, _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron ); #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSAPI NTSTATUS NTAPI TpAllocAlpcCompletionEx( _Out_ PTP_ALPC* AlpcReturn, _In_ HANDLE AlpcPort, _In_ PTP_ALPC_CALLBACK_EX Callback, _Inout_opt_ PVOID Context, _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron ); #endif NTSYSAPI VOID NTAPI TpReleaseAlpcCompletion( _Inout_ PTP_ALPC Alpc ); NTSYSAPI VOID NTAPI TpWaitForAlpcCompletion( _Inout_ PTP_ALPC Alpc ); #endif #if NTDDI_VERSION >= NTDDI_WIN7 NTSYSAPI NTSTATUS NTAPI TpAlpcRegisterCompletionList( _Inout_ PTP_ALPC Alpc ); NTSYSAPI NTSTATUS NTAPI TpAlpcUnregisterCompletionList( _Inout_ PTP_ALPC Alpc ); #endif #ifdef __cplusplus }; #endif #endif // _NTDLL_H
515f6d2802556641621eaec4572b1ed48d9232dc
08f08fd3d91c053c9f272a423b8f8940d178f35a
/lib/directory.c
490f677ea925b9bf0227d7fe0ef56426738895f5
[ "MIT", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference" ]
permissive
twogood/unshield
f1235d67353a2206e93eebc86777ec7ac58ad9e6
67bca739edfdb5468412a073b08541dc4c19747c
refs/heads/main
2023-05-25T09:04:13.674526
2023-03-23T20:22:48
2023-03-23T20:22:48
3,277,724
282
78
MIT
2023-09-13T16:59:21
2012-01-26T21:40:49
C
UTF-8
C
false
false
787
c
directory.c
#include "internal.h" #include "log.h" int unshield_directory_count(Unshield* unshield) { if (unshield) { /* XXX: multi-volume support... */ Header* header = unshield->header_list; return header->cab.directory_count; } else return -1; } const char* unshield_directory_name(Unshield* unshield, int index) { if (unshield && index >= 0) { /* XXX: multi-volume support... */ Header* header = unshield->header_list; if (index < (int)header->cab.directory_count) return unshield_get_utf8_string(header, header->data + header->common.cab_descriptor_offset + header->cab.file_table_offset + header->file_table[index]); } unshield_warning("Failed to get directory name %i", index); return NULL; }
85d716870f412d7ad25c329de418d4aa2e8ece68
fbe68d84e97262d6d26dd65c704a7b50af2b3943
/third_party/virtualbox/src/bldprogs/test-gccplugin-2.c
13cf8ee2ecc99ee5cc7ae956103502ef7ce08218
[ "MIT", "GPL-2.0-only", "LicenseRef-scancode-unknown-license-reference", "CDDL-1.0", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "LGPL-2.1-or-later", "GPL-2.0-or-later", "MPL-1.0", "LicenseRef-scancode-generic-exception", "Apache-2.0", "OpenSSL" ]
permissive
thalium/icebox
c4e6573f2b4f0973b6c7bb0bf068fe9e795fdcfb
6f78952d58da52ea4f0e55b2ab297f28e80c1160
refs/heads/master
2022-08-14T00:19:36.984579
2022-02-22T13:10:31
2022-02-22T13:10:31
190,019,914
585
109
MIT
2022-01-13T20:58:15
2019-06-03T14:18:12
C++
UTF-8
C
false
false
1,421
c
test-gccplugin-2.c
/* $Id: test-gccplugin-2.c $ */ /** @file * Compiler plugin testcase \#2. */ /* * Copyright (C) 2010-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /* Only valid stuff in this one. */ extern void MyIprtPrintf(const char *pszFormat, ...) __attribute__((__iprt_format__(1,2))); extern void foo(void); extern unsigned long long g_ull; typedef unsigned long long RTGCPHYS; extern RTGCPHYS g_GCPhys; typedef RTGCPHYS *PRTGCPHYS; extern PRTGCPHYS g_pGCPhys; #include <stdarg.h> void foo(const char *pszFormat, ...) { MyIprtPrintf("%s %RX64 %RGp %p %RGp", "foobar", g_ull, g_GCPhys, g_pGCPhys, *g_pGCPhys); MyIprtPrintf("%RX32 %d %s\n", 10, 42, "string"); MyIprtPrintf("%u %.8Rhxs %d\n", 10, &g_ull, 42); MyIprtPrintf("%u %.8RhxD %d\n", 10, &g_ull, 42); { va_list va; int iValue; va_start(va, pszFormat); iValue = va_arg(va, int); va_end(va); MyIprtPrintf("%u\n", iValue); } }
cc6c7bdaeb62bf17b60b2f4221c06d4d2699098f
c59784458e4dcb34eadd6941bc4297c28c1a7e53
/Archive/lcc/Utils/lcc/src/bind.c
9a26c88785bb65a36925d52b820eb790d85284d0
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license", "BSD-2-Clause" ]
permissive
kervinck/gigatron-rom
42af9ce548d34d64ee667f662337ea7aa6d331e8
5d24889a661793ef0a9fb8d714bab9127307ee30
refs/heads/master
2023-07-30T02:11:24.748356
2023-07-07T06:27:20
2023-07-07T06:27:20
106,879,621
216
85
BSD-2-Clause
2023-08-08T09:40:32
2017-10-13T22:40:14
C
UTF-8
C
false
false
533
c
bind.c
#include "c.h" #undef yy #define yy \ xx(alpha/osf, alphaIR) \ xx(mips/irix, mipsebIR) \ xx(sparc/sun, sparcIR) \ xx(sparc/solaris,solarisIR) \ xx(x86/win32, x86IR) \ xx(x86/linux, x86linuxIR) \ xx(gt1, gt1IR) \ xx(symbolic/osf, symbolic64IR) \ xx(symbolic/irix,symbolicIR) \ xx(symbolic, symbolicIR) \ xx(bytecode, bytecodeIR) \ xx(null, nullIR) #undef xx #define xx(a,b) extern Interface b; yy Binding bindings[] = { #undef xx #define xx(a,b) #a, &b, yy NULL, NULL }; #undef yy #undef xx
d5e4841757ada6104e752f419cdaa30e2e1a4140
baa9fffc817a2a993d4ecc774d3f277783308c20
/test/apps/test_tcmalloc.c
d28883cb17b8b560be1695fcba2deac685358867
[ "BSD-3-Clause" ]
permissive
openucx/ucx
9a0f2205295afbdf3cff14b5d24af781b123f5ea
73a48700badb7cbace64d94b82f408e2a26fca32
refs/heads/master
2023-09-01T16:51:26.913950
2023-09-01T13:02:25
2023-09-01T13:02:25
25,379,390
966
420
NOASSERTION
2023-09-14T12:29:35
2014-10-17T22:17:24
C
UTF-8
C
false
false
606
c
test_tcmalloc.c
/** * Copyright (c) NVIDIA CORPORATION & AFFILIATES, 2001-2018. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #include <ucp/api/ucp.h> #include <dlfcn.h> #include <stdio.h> int main(int argc, char **argv) { ucp_params_t params; ucs_status_t status; ucp_context_h context; params.field_mask = UCP_PARAM_FIELD_FEATURES; params.features = UCP_FEATURE_TAG; status = ucp_init(&params, NULL, &context); if (status != UCS_OK) { return -1; } dlopen("libselinux.so", RTLD_LAZY); ucp_cleanup(context); printf("SUCCESS\n"); return 0; }
16c0dfe2bc1dbd972c458907c69a14655c639fd8
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/mips/kernel/csrc-sb1250.c
6ecb77d820631972a8bf3494ffa7b9a56098b610
[ "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
2,151
c
csrc-sb1250.c
/* * Copyright (C) 2000, 2001 Broadcom Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <linux/clocksource.h> #include <asm/addrspace.h> #include <asm/io.h> #include <asm/time.h> #include <asm/sibyte/sb1250.h> #include <asm/sibyte/sb1250_regs.h> #include <asm/sibyte/sb1250_int.h> #include <asm/sibyte/sb1250_scd.h> #define SB1250_HPT_NUM 3 #define SB1250_HPT_VALUE M_SCD_TIMER_CNT /* max value */ /* * The HPT is free running from SB1250_HPT_VALUE down to 0 then starts over * again. */ static cycle_t sb1250_hpt_read(struct clocksource *cs) { unsigned int count; count = G_SCD_TIMER_CNT(__raw_readq(IOADDR(A_SCD_TIMER_REGISTER(SB1250_HPT_NUM, R_SCD_TIMER_CNT)))); return SB1250_HPT_VALUE - count; } struct clocksource bcm1250_clocksource = { .name = "bcm1250-counter-3", .rating = 200, .read = sb1250_hpt_read, .mask = CLOCKSOURCE_MASK(23), .flags = CLOCK_SOURCE_IS_CONTINUOUS, }; void __init sb1250_clocksource_init(void) { struct clocksource *cs = &bcm1250_clocksource; /* Setup hpt using timer #3 but do not enable irq for it */ __raw_writeq(0, IOADDR(A_SCD_TIMER_REGISTER(SB1250_HPT_NUM, R_SCD_TIMER_CFG))); __raw_writeq(SB1250_HPT_VALUE, IOADDR(A_SCD_TIMER_REGISTER(SB1250_HPT_NUM, R_SCD_TIMER_INIT))); __raw_writeq(M_SCD_TIMER_ENABLE | M_SCD_TIMER_MODE_CONTINUOUS, IOADDR(A_SCD_TIMER_REGISTER(SB1250_HPT_NUM, R_SCD_TIMER_CFG))); clocksource_register_hz(cs, V_SCD_TIMER_FREQ); }
be0407a8b1994cc7755262e4359753b9e4d1f10e
515a17dfa8acffb7dbc076dca5be7ef3ddc2952f
/tools/external/sra-dump/factory.h
dd9d105ebab683553352f20f8846d76fb4b77536
[ "LicenseRef-scancode-ncbi", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-us-govt-public-domain" ]
permissive
ncbi/sra-tools
d54d2fe00214d9471b6dbd0b90c2fe0062f87cdd
1bb9cd2f317a232eb8f1e1d33cfc3582c71b3eec
refs/heads/master
2023-09-01T11:46:59.189830
2023-08-29T16:34:24
2023-08-29T16:34:24
23,203,598
991
271
NOASSERTION
2023-09-14T19:43:38
2014-08-21T21:25:38
C
UTF-8
C
false
false
8,557
h
factory.h
/*=========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * */ #ifndef _h_tools_dump_factory #define _h_tools_dump_factory #include <klib/rc.h> #include <kfs/file.h> #include <klib/data-buffer.h> #include <sra/sradb.h> #define DATABUFFER_INC_SZ 4096 /* KDataBuffer is used as byte buffer-only here! */ #define IF_BUF(expr, buf, writ) \ while( (rc = (expr)) != 0 && \ (GetRCObject(rc) == rcMemory || GetRCObject(rc) == ( enum RCObject )rcBuffer) && \ (GetRCState(rc) == rcInsufficient || GetRCState(rc) == rcExhausted) ) { \ SRA_DUMP_DBG(10, ("\n%s grow buffer from %u to %u\n", __func__, buf->elem_count, writ + DATABUFFER_INC_SZ)); \ if( (rc = KDataBufferResize(buf, writ + DATABUFFER_INC_SZ)) != 0 ) { \ break; \ } \ } \ if( rc == 0 ) typedef enum { eSplitterSpot = 1, eSplitterRead, eSplitterFormat /* in splitters chain this type must be the last instance and must write to file(s) */ } ESRASplitterTypes; typedef struct SRASplitter SRASplitter; #define NREADS_MAX (8*1024) typedef uint8_t readmask_t; extern uint32_t nreads_max; /* new hack to realize changed requirement for quality-filter */ #define DEF_QUAL_N_LIMIT 10 extern uint32_t quality_N_limit; extern bool g_legacy_report; #define make_readmask(m) readmask_t m[NREADS_MAX] #define copy_readmask(src,dst) (memmove(dst, src, sizeof(readmask_t) * nreads_max)) #define reset_readmask(m) (memset(m, ~0, sizeof(readmask_t) * nreads_max)) #define clear_readmask(m) (memset(m, 0, sizeof(readmask_t) * nreads_max)) #define set_readmask(m,id) (id < nreads_max ? (m)[id] = 1 : 0) #define unset_readmask(m,id) (id < nreads_max ? (m)[id] = 0 : 0) #define get_readmask(m,id) (id < nreads_max ? ((m)[id]) : 0) #define isset_readmask(m,id) (id < nreads_max ? (m)[id] != 0 : false) typedef struct SRASplitter_Keys_struct { const char* key; make_readmask(readmask); } SRASplitter_Keys; /* for eSpot splitter: returns pointer to key and (optionally) modified readmask, based on spotid and readmask key == NULL stops further processing of the spot, char* key alloc and dealloc must be handled by splitter itself */ typedef rc_t (SRASplitter_GetKey_Func)(const SRASplitter* self, const char** key, spotid_t spot, readmask_t* readmask); /* for eRead splitter: returns array of keys and readmasks used array portion count in keys, based on spotid and readmask, on return keys shows number of array key[] elements used, keys == 0 stops further processing of the spot, elements with key.key == NULL OR key.readmask == 0 are skipped key alloc and dealloc must be handled by splitter itself */ typedef rc_t (SRASplitter_GetKeySet_Func)(const SRASplitter* self, const SRASplitter_Keys** key, uint32_t* keys, spotid_t spot, const readmask_t* readmask); /* writes data to file(s) using SRASplitter_File* functions, based on spot and readmask do NOT open or create any files directly here, use SRASplitter_FileXXX functions only! */ typedef rc_t (SRASplitter_Dump_Func)(const SRASplitter* self, spotid_t spot, const readmask_t* readmask); /* optional method to free splitter resources, object distruction is handled automatically, do NOT free self! */ typedef rc_t (SRASplitter_Release_Func)(const SRASplitter* self); /** * Base type constructor, must be called when constructing custom splitter type */ rc_t SRASplitter_Make(const SRASplitter** self, size_t type_size, /* sizeof(derived object) */ /* mandatory only for eSpot splitter, must be NULL for other types */ SRASplitter_GetKey_Func*, /* mandatory only for eRead splitter, must be NULL for other types */ SRASplitter_GetKeySet_Func*, /* mandatory only for eFormat splitter, must be NULL for other types */ SRASplitter_Dump_Func*, /* optional destructor, do NOT free self! */ SRASplitter_Release_Func* release); /** * Base type destructor */ rc_t SRASplitter_Release(const SRASplitter* self); /** * Add spot to processing chain */ rc_t SRASplitter_AddSpot(const SRASplitter* self, spotid_t spot, readmask_t* readmask); /** * File access routines */ /* key [IN] - usually file type extension: .sff, .fastq, _nse.txt, etc */ rc_t SRASplitter_FileActivate(const SRASplitter* self, const char* key); /* CAREFULL!!! these operates on last active file spot can be zero to indicate file header/footer which no considered as actual data and file treated as empty if no actual spots is written */ rc_t SRASplitter_FileWrite( const SRASplitter* cself, spotid_t spot, const void* buf, size_t size ); rc_t SRASplitter_FileWritePos( const SRASplitter* cself, spotid_t spot, uint64_t pos, const void* buf, size_t size ); typedef struct SRASplitterFactory SRASplitterFactory; typedef rc_t (SRASplitterFactory_Init_Func)(const SRASplitterFactory* self); typedef rc_t (SRASplitterFactory_NewObj_Func)(const SRASplitterFactory* self, const SRASplitter** splitter); typedef void (SRASplitterFactory_Release_Func)(const SRASplitterFactory* self); /** * Initialize factories file handler object. * Must be called BEFORE 1st call to SRASplitterFactory_Init * * key_as_dir [IN] - if true, subdirs created for each splitting level: SPOT_GROUP/1/prefix.fastq * if false, single file is used in split chain: prefix_SPOT_GROUP_1.fastq * prefix [IN] - file name prefix, usually run id (accession) * path, ... [IN] - path to directory where file will reside */ rc_t SRASplitterFactory_FilerInit(bool to_stdout, bool gzip, bool bzip2, bool key_as_dir, bool keep_empty, const char* path, ...); /* this only works correctly on top of the splitter tree !! */ rc_t SRASplitterFactory_FilerPrefix(const char* prefix); void SRASplitterFactory_FilerReport(uint64_t* total, uint64_t* biggest_file); void SRASplitterFiler_Release(void); /** * Create factory object */ rc_t SRASplitterFactory_Make(const SRASplitterFactory** self, ESRASplitterTypes type, size_t type_size, /* optional method to initialize self */ SRASplitterFactory_Init_Func* init, /* mandatory method to spawn new SRASplitter object */ SRASplitterFactory_NewObj_Func* newObj, /* optional destructor, should NOT free self!!! */ SRASplitterFactory_Release_Func* release); /** * Releases Factory and all chained factories */ void SRASplitterFactory_Release(const SRASplitterFactory* self); /** * Get Factory type */ ESRASplitterTypes SRASplitterFactory_GetType(const SRASplitterFactory* self); /** * Chain "next" factory after "self", releases old chain if present */ rc_t SRASplitterFactory_AddNext(const SRASplitterFactory* self, const SRASplitterFactory* next); /** * Initialize a chain of factories. Factories must be chaind properly before init. * Type chain must look like (eSpot|eRead)*, eFormat. */ rc_t SRASplitterFactory_Init(const SRASplitterFactory* self); /** * Create new instance of factory kind, point splitter to next factory in chain */ rc_t SRASplitterFactory_NewObj(const SRASplitterFactory* self, const SRASplitter** splitter); #endif /* _h_tools_dump_factory */
2aa4ad1f116f56d133a28d6c231d5e8eeae98355
cce217852fee0a222fdca9f8f6ee8897c540c663
/patch/layout_horizgrid.c
beb8e0bafc06e7964c30b6e15f7ff37cf4386725
[ "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
2,390
c
layout_horizgrid.c
void horizgrid(Monitor *m) { Client *c; unsigned int n, i; int mx = 0, my = 0, mh = 0, mw = 0; int sx = 0, sy = 0, sh = 0, sw = 0; int ntop; float mfacts = 0, sfacts = 0; int mrest, srest, mtotal = 0, stotal = 0; #if VANITYGAPS_PATCH int oh, ov, ih, iv; getgaps(m, &oh, &ov, &ih, &iv, &n); #else for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++); #endif // VANITYGAPS_PATCH if (n == 0) return; if (n <= 2) ntop = n; else { ntop = n / 2; } #if VANITYGAPS_PATCH sx = mx = m->wx + ov; sy = my = m->wy + oh; sh = mh = m->wh - 2*oh; sw = mw = m->ww - 2*ov; if (n > ntop) { sh = (mh - ih) / 2; mh = mh - ih - sh; sy = my + mh + ih; mw = m->ww - 2*ov - iv * (ntop - 1); sw = m->ww - 2*ov - iv * (n - ntop - 1); } #else sx = mx = m->wx; sy = my = m->wy; sh = mh = m->wh; sw = mw = m->ww; if (n > ntop) { sh = mh / 2; mh = mh - sh; sy = my + mh; } #endif // VANITYGAPS_PATCH /* calculate facts */ #if CFACTS_PATCH for (i = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++) if (i < ntop) mfacts += c->cfact; else sfacts += c->cfact; for (i = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++) if (i < ntop) mtotal += mh * (c->cfact / mfacts); else stotal += sw * (c->cfact / sfacts); #else mfacts = ntop; sfacts = n - ntop; for (i = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++) if (i < ntop) mtotal += mh / mfacts; else stotal += sw / sfacts; #endif // CFACTS_PATCH mrest = mh - mtotal; srest = sw - stotal; for (i = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++) if (i < ntop) { #if CFACTS_PATCH resize(c, mx, my, mw * (c->cfact / mfacts) + (i < mrest ? 1 : 0) - (2*c->bw), mh - (2*c->bw), 0); #else resize(c, mx, my, mw / mfacts + (i < mrest ? 1 : 0) - (2*c->bw), mh - (2*c->bw), 0); #endif // CFACTS_PATCH #if VANITYGAPS_PATCH mx += WIDTH(c) + iv; #else mx += WIDTH(c); #endif // VANITYGAPS_PATCH } else { #if CFACTS_PATCH resize(c, sx, sy, sw * (c->cfact / sfacts) + ((i - ntop) < srest ? 1 : 0) - (2*c->bw), sh - (2*c->bw), 0); #else resize(c, sx, sy, sw / sfacts + ((i - ntop) < srest ? 1 : 0) - (2*c->bw), sh - (2*c->bw), 0); #endif // CFACTS_PATCH #if VANITYGAPS_PATCH sx += WIDTH(c) + iv; #else sx += WIDTH(c); #endif // VANITYGAPS_PATCH } }
36b464254a26021aeb04d7acbf51d3831c3386e2
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/acm32/acm32f4xx-nucleo/libraries/HAL_Driver/Inc/HAL_ADC.h
48e6e6e1af918f4f38cc0b20b2eaed894652d95a
[ "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
39,084
h
HAL_ADC.h
/* ****************************************************************************** * @file HAL_ADC.h * @version V1.0.0 * @date 2020 * @brief Header file of ADC HAL module. ****************************************************************************** */ #ifndef __HAL_ADC_H__ #define __HAL_ADC_H__ #include "ACM32Fxx_HAL.h" /**************** Total definition for ADC **************************/ #define ADC_CH_MASK (BIT4|BIT3|BIT2|BIT1|BIT0) /**************** Bit definition for ADC_SR register **************************/ #define ADC_SR_AWD (BIT5) #define ADC_SR_OVERF (BIT4) #define ADC_SR_EOG (BIT3) #define ADC_SR_JEOC (BIT2) #define ADC_SR_EOC (BIT1) #define ADC_SR_ADRDY (BIT0) /**************** Bit definition for ADC_IE register **************************/ #define ADC_IE_AWDIE (BIT5) #define ADC_IE_OVERFIE (BIT4) #define ADC_IE_EOGIE (BIT3) #define ADC_IE_JEOCIE (BIT2) #define ADC_IE_EOCIE (BIT1) /**************** Bit definition for ADC_CR1 register **************************/ #define ADC_CR1_AWDJCH_POS (27U) #define ADC_CR1_AWDJCH_MASK (BIT31|BIT30|BIT29|BIT28|BIT27) #define ADC_CR1_DISCNUM_POS (23U) #define ADC_CR1_DISCNUM_MASK (BIT26|BIT25|BIT24|BIT23) #define ADC_CR1_DISCEN BIT22 #define ADC_CR1_CONT BIT21 #define ADC_CR1_SWSTART BIT20 #define ADC_CR1_JSWSTART BIT19 #define ADC_CR1_EXTSEL_POS (16U) #define ADC_CR1_EXTSEL_MASK (BIT18|BIT17|BIT16) #define ADC_CR1_JEXTSEL_POS (13U) #define ADC_CR1_JEXTSEL_MASK (BIT15|BIT14|BIT13) #define ADC_CR1_DMA BIT12 #define ADC_CR1_AWDEN BIT11 #define ADC_CR1_JAWDEN BIT10 #define ADC_CR1_JEN BIT9 #define ADC_CR1_AWDSGL BIT8 #define ADC_CR1_AWDCH_POS (0U) #define ADC_CR1_AWDCH_MASK (BIT4|BIT3|BIT2|BIT1|BIT0) /**************** Bit definition for ADC_CR2 register **************************/ #define ADC_CR2_FASTMOD BIT27 #define ADC_CR2_AFE_RSTN BIT26 #define ADC_CR2_JOVSE BIT25 #define ADC_CR2_JTOVS BIT24 #define ADC_CR2_OVSS_POS (20U) #define ADC_CR2_OVSS_MASK (BIT23|BIT22|BIT21|BIT20) #define ADC_CR2_OVSR_POS (17U) #define ADC_CR2_OVSR_MASK (BIT19|BIT18|BIT17) #define ADC_CR2_OVSE BIT16 #define ADC_CR2_BUF_STIME_POS (8U) #define ADC_CR2_BUF_STIME_MASK (BIT15|BIT14|BIT13|BIT12|BIT11|BIT10|BIT9|BIT8) #define ADC_CR2_EN_BUF BIT7 #define ADC_CR2_DIV_POS (3U) #define ADC_CR2_DIV_MASK (BIT6|BIT5|BIT4|BIT3) #define ADC_CR2_ADC_STP BIT2 #define ADC_CR2_OVRMOD BIT1 #define ADC_CR2_ADC_EN BIT0 /**************** Bit definition for ADC_SMPR1 register **************************/ #define ADC_SMPR_CH_MASK (BIT3|BIT2|BIT1|BIT0) /**************** Bit definition for ADC_DIFF register **************************/ #define ADC_DIFF_DIFF7_F BIT7 #define ADC_DIFF_DIFF6_E BIT6 #define ADC_DIFF_DIFF5_D BIT5 #define ADC_DIFF_DIFF4_C BIT4 #define ADC_DIFF_DIFF3_B BIT3 #define ADC_DIFF_DIFF2_A BIT2 #define ADC_DIFF_DIFF1_9 BIT1 #define ADC_DIFF_DIFF0_8 BIT0 /**************** Bit definition for ADC_HTR register ***********************/ #define ADC_HTR_DHT (BIT27|BIT26|BIT25|BIT24|BIT23|BIT22|BIT21|BIT20|BIT19|BIT18|BIT17|BIT16) #define ADC_HTR_HT (BIT11|BIT10|BIT9|BIT8|BIT7|BIT6|BIT5|BIT4|BIT3|BIT2|BIT1|BIT0) /**************** Bit definition for ADC_LTR register ***********************/ #define ADC_LTR_DLT (BIT27|BIT26|BIT25|BIT24|BIT23|BIT22|BIT21|BIT20|BIT19|BIT18|BIT17|BIT16) #define ADC_LTR_LT (BIT11|BIT10|BIT9|BIT8|BIT7|BIT6|BIT5|BIT4|BIT3|BIT2|BIT1|BIT0) /**************** Bit definition for ADC_SQR1 register ***********************/ #define ADC_SQR1_L (BIT3|BIT2|BIT1|BIT0) /**************** Bit definition for ADC_JSQR register ***********************/ #define ADC_JSQR_JSQ (BIT4|BIT3|BIT2|BIT1|BIT0) /**************** Bit definition for ADC_JDR register ***********************/ #define ADC_JDR_JCH (BIT20|BIT19|BIT18|BIT17|BIT16) /**************** Bit definition for ADC_DR register ***********************/ #define ADC_DR_CH (BIT20|BIT19|BIT18|BIT17|BIT16) /**************** Bit definition for ADC_SIGN register ***********************/ #define ADC_SIGN_SIGN7_F BIT7 #define ADC_SIGN_SIGN6_E BIT6 #define ADC_SIGN_SIGN5_D BIT5 #define ADC_SIGN_SIGN4_C BIT4 #define ADC_SIGN_SIGN3_B BIT3 #define ADC_SIGN_SIGN2_A BIT2 #define ADC_SIGN_SIGN1_9 BIT1 #define ADC_SIGN_SIGN0_8 BIT0 /**************** Bit definition for ADC_TSREF register ***********************/ #define ADC_TSREF_HIZ_EN BIT27 #define ADC_TSREF_VREFBI_SEL_POS (25U) #define ADC_TSREF_VREFBI_SEL_MASK (BIT26|BIT25) #define ADC_TSREF_VREFBI_EN BIT24 #define ADC_TSREF_VTRIM_POS (19U) #define ADC_TSREF_VTRIM_MASK (BIT23|BIT22|BIT21|BIT20|BIT19) #define ADC_TSREF_TTRIM_POS (15U) #define ADC_TSREF_TTRIM_MASK (BIT18|BIT17|BIT16|BIT15) #define ADC_TSREF_ALG_MEAN_POS (9U) #define ADC_TSREF_ALG_MEAN_MASK (BIT10|BIT9) #define ADC_TSREF_ADJ_TD_OS_POS (5U) #define ADC_TSREF_ADJ_TD_OS_MASK (BIT8|BIT7|BIT6|BIT5) #define ADC_TSREF_ADJ_TD_GA_POS (1U) #define ADC_TSREF_ADJ_TD_GA_MASK (BIT4|BIT3|BIT2|BIT1) #define ADC_TSREF_EN_TS BIT0 /**************** Macro definition for register operation **************************/ /**************** Enable the specified ADC. **************************/ #define __HAL_ADC_ENABLE(__HANDLE__) \ (SET_BIT((__HANDLE__)->Instance->CR2, (ADC_CR2_ADC_EN))) /**************** Disable the specified ADC. **************************/ #define __HAL_ADC_DISABLE(__HANDLE__) \ (CLEAR_BIT((__HANDLE__)->Instance->CR2, (ADC_CR2_ADC_EN))) /**************** Enable the specified ADC interrupt source. **************************/ #define __HAL_ADC_ENABLE_IT(__HANDLE__, __INTERRUPT__) \ (SET_BIT((__HANDLE__)->Instance->IE, (__INTERRUPT__))) /**************** Disable the specified ADC interrupt source. **************************/ #define __HAL_ADC_DISABLE_IT(__HANDLE__, __INTERRUPT__) \ (CLEAR_BIT((__HANDLE__)->Instance->IE, (__INTERRUPT__))) /**************** Checks if the specified ADC interrupt source is enabled or disabled. **************************/ #define __HAL_ADC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) \ (((__HANDLE__)->Instance->IE & (__INTERRUPT__)) == (__INTERRUPT__)) /**************** Get the selected ADC's flag status. **************************/ #define __HAL_ADC_GET_FLAG(__HANDLE__, __FLAG__) \ ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) /**************** Clear the selected ADC's flag status. **************************/ #define __HAL_ADC_CLEAR_FLAG(__HANDLE__, __FLAG__) \ (SET_BIT((__HANDLE__)->Instance->SR, (__FLAG__))) /**************** Checks if the ADC regular group trig source is the specified source. **************************/ #define __HAL_ADC_CHECK_TRIG_REGULAR(__HANDLE__, __TRIGSOURCE__) \ ((((__HANDLE__)->Instance->CR1 & ADC_CR1_EXTSEL_MASK) >> ADC_CR1_EXTSEL_POS) == (__TRIGSOURCE__)) /**************** Checks if the ADC injected channel trig source is the specified source. **************************/ #define __HAL_ADC_CHECK_TRIG_INJECTED(__HANDLE__, __TRIGSOURCE__) \ ((((__HANDLE__)->Instance->CR1 & ADC_CR1_JEXTSEL_MASK) >> ADC_CR1_JEXTSEL_POS) == (__TRIGSOURCE__)) /**************** Bit definition for ADC_SMPR3 register **************************/ #define ADC_SMPR3_CONV_PLUS_POS (20U) #define ADC_SMPR3_CONV_PLUS_MASK (BIT21|BIT20) /** * @brief ADC ExTigger structure definition */ typedef struct { uint32_t ExTrigSel; /*!< Configures the regular channel trig mode. */ uint32_t JExTrigSel; /*!< Configures the inject channel trig mode. */ }ADC_ExTrigTypeDef; /** * @brief ADC group regular oversampling structure definition */ typedef struct { uint32_t Ratio; /*!< Configures the oversampling ratio. This parameter can be a value of @ref ADC_CR2_OVSR_2X*/ uint32_t RightBitShift; /*!< Configures the division coefficient for the Oversampler. This parameter can be a value of @ref ADC_CR2_OVSS_0 */ uint32_t TriggeredMode; /*!< Selects the regular triggered oversampling mode. This parameter can be a value of 0 : trig 1 time; other: trig N times, N refer to the oversampling Ratio*/ }ADC_OversamplingTypeDef; /******************************** ADC Init mode define *******************************/ /******************************** ConConvMode define *******************************/ #define ADC_CONCONVMODE_DISABLE (0) #define ADC_CONCONVMODE_ENABLE (1) /******************************** JChannelMode define *******************************/ #define ADC_JCHANNELMODE_DISABLE (0) #define ADC_JCHANNELMODE_ENABLE (1) /******************************** DiffMode define *******************************/ #define ADC_DIFFMODE_DISABLE (0) #define ADC_DIFFMODE_ENABLE (1) /******************************** DMAMode define *******************************/ #define ADC_DMAMODE_DISABLE (0) #define ADC_DMAMODE_ENABLE (1) /******************************** OverMode define *******************************/ #define ADC_OVERMODE_DISABLE (0) #define ADC_OVERMODE_ENABLE (1) /******************************** OverSampMode define *******************************/ #define ADC_OVERSAMPMODE_DISABLE (0) #define ADC_OVERSAMPMODE_ENABLE (1) /******************************** AnalogWDGEn define *******************************/ #define ADC_ANALOGWDGEN_DISABLE (0) #define ADC_ANALOGWDGEN_ENABLE (1) /** * @brief ADC Configuration Structure definition */ typedef struct { uint32_t ClockDiv; /*!< Specify the ADC clock div from the PCLK. This parameter can be set to ADC_CLOCK_DIV1 | ADC_CLOCK_DIV2 |... ADC_CLOCK_DIV16 */ uint32_t ConConvMode; /*!< Specify whether the conversion is performed in single mode (one conversion) or continuous mode for ADC group regular, after the first ADC conversion start trigger occurred (software start or external trigger). This parameter can be set to ADC_CONCONVMODE_DISABLE or ADC_CONCONVMODE_ENABLE. */ uint32_t JChannelMode; /*!< Specify if support inject channel. This parameter can be set to ADC_JCHANNELMODE_DISABLE or ADC_JCHANNELMODE_ENABLE*/ uint32_t DiffMode; /*!< Specify the differential parameters. ADC_DIFFMODE_DISABLE:single end mode, ADC_DIFFMODE_ENABLE:differential end mode */ uint32_t ChannelEn; /*!< Specify the enable ADC channels. This parameter can be set to ADC_CHANNEL_0_EN | ADC_CHANNEL_1_EN |... ADC_CHANNEL_15_EN*/ ADC_ExTrigTypeDef ExTrigMode; /*!< ADC ExTigger structure, config the regular and inject channel trig mode */ uint32_t DMAMode; /*!< Specify whether the DMA requests are performed in one shot mode (DMA transfer stops when number of conversions is reached) or in continuous mode (DMA transfer unlimited, whatever number of conversions). This parameter can be set to ADC_DMAMODE_ENABLE or ADC_DMAMODE_DISABLE. Note: In continuous mode, DMA must be configured in circular mode. Otherwise an overrun will be triggered when DMA buffer maximum pointer is reached. */ uint32_t OverMode; /*!< ADC_OVERMODE_DISABLE,ADC_OVERMODE_ENABLE*/ uint32_t OverSampMode; /*!< Specify whether the oversampling feature is enabled or disabled. This parameter can be set to ADC_OVERSAMPMODE_ENABLE or ADC_OVERSAMPMODE_DISABLE. Note: This parameter can be modified only if there is no conversion is ongoing on ADC group regular. */ ADC_OversamplingTypeDef Oversampling; /*!< Specify ADC group regular oversampling structure. */ uint32_t AnalogWDGEn; }ADC_InitTypeDef; typedef struct { uint32_t RjMode; /*!< Specify the channel mode, 0:regular, Other:inject*/ uint32_t Channel; /*!< Specify the channel to configure into ADC regular group. This parameter can be a value of @ref ADC_CHANNEL_0 Note: Depending on devices and ADC instances, some channels may not be available on device package pins. Refer to device datasheet for channels availability. */ uint32_t Sq; /*!< Add or remove the channel from ADC regular group sequencer and specify its conversion rank. This parameter is dependent on ScanConvMode: - sequencer configured to fully configurable: Channels ordering into each rank of scan sequence: whatever channel can be placed into whatever rank. - sequencer configured to not fully configurable: rank of each channel is fixed by channel HW number. (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...). Despite the channel rank is fixed, this parameter allow an additional possibility: to remove the selected rank (selected channel) from sequencer. This parameter can be a value of @ref ADC_SEQUENCE_SQ1 */ uint32_t Smp; /*!< Sampling time value to be set for the selected channel. Unit: ADC clock cycles This parameter can be a value of @ref ADC_SMP_CLOCK_3 */ }ADC_ChannelConfTypeDef; typedef struct { uint32_t WatchdogMode; /*!< Configure the ADC analog watchdog mode: single/all/none channels. For Analog Watchdog 1: Configure the ADC analog watchdog mode: single channel or all channels, ADC group regular. For Analog Watchdog 2 and 3: Several channels can be monitored by applying successively the AWD init structure. This parameter can be a value of @ref ADC_ANALOGWATCHDOG_RCH_ALL. */ uint32_t Channel; /*!< Select which ADC channel to monitor by analog watchdog. For Analog Watchdog 1: this parameter has an effect only if parameter 'WatchdogMode' is configured on single channel (only 1 channel can be monitored). For Analog Watchdog 2 and 3: Several channels can be monitored. To use this feature, call successively the function HAL_ADC_AnalogWDGConfig() for each channel to be added (or removed with value 'ADC_ANALOGWATCHDOG_NONE'). This parameter can be a value of @ref ADC_CHANNEL_0. */ uint32_t ITMode; /*!< Specify whether the analog watchdog is configured in interrupt or polling mode. This parameter can be set to ENABLE or DISABLE */ uint32_t HighThreshold; /*!< Configure the ADC analog watchdog High threshold value. */ uint32_t LowThreshold; /*!< Configures the ADC analog watchdog Low threshold value. */ }ADC_AnalogWDGConfTypeDef; /******************************** ADC Over Sample Shift define *******************************/ #define ADC_CR2_OVSS_0 (0U) #define ADC_CR2_OVSS_1 (1U) #define ADC_CR2_OVSS_2 (2U) #define ADC_CR2_OVSS_3 (3U) #define ADC_CR2_OVSS_4 (4U) #define ADC_CR2_OVSS_5 (5U) #define ADC_CR2_OVSS_6 (6U) #define ADC_CR2_OVSS_7 (7U) #define ADC_CR2_OVSS_8 (8U) /******************************** ADC Over Sample Rate define *******************************/ #define ADC_CR2_OVSR_2X (0U) #define ADC_CR2_OVSR_4X (1U) #define ADC_CR2_OVSR_8X (2U) #define ADC_CR2_OVSR_16X (3U) #define ADC_CR2_OVSR_32X (4U) #define ADC_CR2_OVSR_64X (5U) #define ADC_CR2_OVSR_128X (6U) #define ADC_CR2_OVSR_256X (7U) /******************************** ADC Sample period define *******************************/ #define ADC_SMP_CLOCK_3 (0U) #define ADC_SMP_CLOCK_5 (1U) #define ADC_SMP_CLOCK_7 (2U) #define ADC_SMP_CLOCK_10 (3U) #define ADC_SMP_CLOCK_13 (4U) #define ADC_SMP_CLOCK_16 (5U) #define ADC_SMP_CLOCK_20 (6U) #define ADC_SMP_CLOCK_30 (7U) #define ADC_SMP_CLOCK_60 (8U) #define ADC_SMP_CLOCK_80 (9U) #define ADC_SMP_CLOCK_100 (10U) #define ADC_SMP_CLOCK_120 (11U) #define ADC_SMP_CLOCK_160 (12U) #define ADC_SMP_CLOCK_320 (13U) #define ADC_SMP_CLOCK_480 (14U) #define ADC_SMP_CLOCK_640 (15U) /******************************** ADC ClockPrescale define *******************************/ #define ADC_CLOCK_DIV1 (0U) #define ADC_CLOCK_DIV2 (1U) #define ADC_CLOCK_DIV3 (2U) #define ADC_CLOCK_DIV4 (3U) #define ADC_CLOCK_DIV5 (4U) #define ADC_CLOCK_DIV6 (5U) #define ADC_CLOCK_DIV7 (6U) #define ADC_CLOCK_DIV8 (7U) #define ADC_CLOCK_DIV9 (8U) #define ADC_CLOCK_DIV10 (9U) #define ADC_CLOCK_DIV11 (10U) #define ADC_CLOCK_DIV12 (11U) #define ADC_CLOCK_DIV13 (12U) #define ADC_CLOCK_DIV14 (13U) #define ADC_CLOCK_DIV15 (14U) #define ADC_CLOCK_DIV16 (15U) /************************ADC_AnalogWDGConfTypeDef->WatchdogMode define********************/ #define ADC_ANALOGWATCHDOG_RCH_ALL (1U) //All regular channels #define ADC_ANALOGWATCHDOG_JCH_ALL (2U) //All inject channels #define ADC_ANALOGWATCHDOG_RCH_AND_JCH_ALL (3U) //All regular and inject channels #define ADC_ANALOGWATCHDOG_RCH_SINGLE (4U) //Single regular channel #define ADC_ANALOGWATCHDOG_JCH_SINGLE (5U) //Single Inject channel #define ADC_ANALOGWATCHDOG_RCH_OR_JCH_SINGLE (6U) //Regular or inject channel /******************************** ADC sequence number define *******************************/ #define ADC_SEQUENCE_SQ1 (1U) #define ADC_SEQUENCE_SQ2 (2U) #define ADC_SEQUENCE_SQ3 (3U) #define ADC_SEQUENCE_SQ4 (4U) #define ADC_SEQUENCE_SQ5 (5U) #define ADC_SEQUENCE_SQ6 (6U) #define ADC_SEQUENCE_SQ7 (7U) #define ADC_SEQUENCE_SQ8 (8U) #define ADC_SEQUENCE_SQ9 (9U) #define ADC_SEQUENCE_SQ10 (10U) #define ADC_SEQUENCE_SQ11 (11U) #define ADC_SEQUENCE_SQ12 (12U) #define ADC_SEQUENCE_SQ13 (13U) #define ADC_SEQUENCE_SQ14 (14U) #define ADC_SEQUENCE_SQ15 (15U) #define ADC_SEQUENCE_SQ16 (16U) /******************************** ADC channel number define *******************************/ #define ADC_CHANNEL_0 (0U) #define ADC_CHANNEL_1 (1U) #define ADC_CHANNEL_2 (2U) #define ADC_CHANNEL_3 (3U) #define ADC_CHANNEL_4 (4U) #define ADC_CHANNEL_5 (5U) #define ADC_CHANNEL_6 (6U) #define ADC_CHANNEL_7 (7U) #define ADC_CHANNEL_8 (8U) #define ADC_CHANNEL_9 (9U) #define ADC_CHANNEL_10 (10U) #define ADC_CHANNEL_11 (11U) #define ADC_CHANNEL_12 (12U) #define ADC_CHANNEL_13 (13U) #define ADC_CHANNEL_14 (14U) #define ADC_CHANNEL_15 (15U) #define ADC_CHANNEL_TEMP (16U) #define ADC_CHANNEL_VBAT (17U) #define ADC_CHANNEL_VBGR (18U) #define ADC_CHANNEL_EXT2 (19U) #define ADC_CHANNEL_EXT3 (20U) /******************************** ADC channel enable define *******************************/ #define ADC_CHANNEL_0_EN (BIT0) #define ADC_CHANNEL_1_EN (BIT1) #define ADC_CHANNEL_2_EN (BIT2) #define ADC_CHANNEL_3_EN (BIT3) #define ADC_CHANNEL_4_EN (BIT4) #define ADC_CHANNEL_5_EN (BIT5) #define ADC_CHANNEL_6_EN (BIT6) #define ADC_CHANNEL_7_EN (BIT7) #define ADC_CHANNEL_8_EN (BIT8) #define ADC_CHANNEL_9_EN (BIT9) #define ADC_CHANNEL_10_EN (BIT10) #define ADC_CHANNEL_11_EN (BIT11) #define ADC_CHANNEL_12_EN (BIT12) #define ADC_CHANNEL_13_EN (BIT13) #define ADC_CHANNEL_14_EN (BIT14) #define ADC_CHANNEL_15_EN (BIT15) #define ADC_CHANNEL_TEMP_EN (BIT16) #define ADC_CHANNEL_VBAT_EN (BIT17) #define ADC_CHANNEL_VBGR_EN (BIT18) #define ADC_CHANNEL_EXT2_EN (BIT19) #define ADC_CHANNEL_EXT3_EN (BIT20) /******************************** ADC Trig source define******************************* * | Trig Source | ACM32FXXX/FPXXX | ACM32F0X0 | * * | ADC_SOFTWARE_START | SWSTART/JSWSTART | SWSTART/JSWSTART | * * | ADC_EXTERNAL_TIG1 | TIM1_TRGO | TIM1_TRGO | * * | ADC_EXTERNAL_TIG2 | TIM1_CC4 | TIM1_CC4 | * * | ADC_EXTERNAL_TIG3 | TIM2_TRGO | RSV | * * | ADC_EXTERNAL_TIG4 | TIM3_TRGO | TIM3_TRGO | * * | ADC_EXTERNAL_TIG5 | TIM4_TRGO | TIM15_TRGO | * * | ADC_EXTERNAL_TIG6 | TIM6_TRGO | TIM6_TRGO | * * | ADC_EXTERNAL_TIG7 | EXTi Line 11 | EXTi Line 11 | */ #define ADC_SOFTWARE_START (0U) #define ADC_EXTERNAL_TIG1 (1U) #define ADC_EXTERNAL_TIG2 (2U) #define ADC_EXTERNAL_TIG3 (3U) #define ADC_EXTERNAL_TIG4 (4U) #define ADC_EXTERNAL_TIG5 (5U) #define ADC_EXTERNAL_TIG6 (6U) #define ADC_EXTERNAL_TIG7 (7U) /******************************** ADC results flag define for HAL level*******************************/ #define HAL_ADC_EOC_FLAG 0x80000000 #define HAL_ADC_JEOC_FLAG 0x40000000 #define HAL_ADC_AWD_FLAG 0x20000000 /** * @brief ADC handle Structure definition */ typedef struct __ADC_HandleTypeDef { ADC_TypeDef *Instance; /*!< Register base address */ ADC_InitTypeDef Init; /*!< ADC initialization parameters and regular conversions setting */ DMA_HandleTypeDef *DMA_Handle; /*!< Pointer DMA Handler */ uint32_t ChannelNum; /*!< Total enable regular group channel number*/ uint32_t *AdcResults; /*!< Point to the convert results*/ void (*ConvCpltCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC conversion complete callback */ void (*GroupCpltCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC regular group conversion complete callback */ void (*InjectedConvCpltCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC injected conversion complete callback */ void (*LevelOutOfWindowCallback)(struct __ADC_HandleTypeDef *hadc); /*!< ADC analog watchdog callback */ }ADC_HandleTypeDef; /******************************** ADC Instances *******************************/ #define IS_ADC_ALL_INSTANCE(INSTANCE) ((INSTANCE) == ADC) #define IS_ADC_ALL_CONCONVMODE(CONCONVMODE) (((CONCONVMODE) == ADC_CONCONVMODE_DISABLE) || \ ((CONCONVMODE) == ADC_CONCONVMODE_ENABLE)) #define IS_ADC_ALL_JCHANNELMODE(JCHANNELMODE) (((JCHANNELMODE) == ADC_JCHANNELMODE_DISABLE) || \ ((JCHANNELMODE) == ADC_JCHANNELMODE_ENABLE)) #define IS_ADC_ALL_DIFFMODE(DIFFMODE) (((DIFFMODE) == ADC_DIFFMODE_DISABLE) || \ ((DIFFMODE) == ADC_DIFFMODE_ENABLE)) #define IS_ADC_ALL_DMAMODE(DMAMODE) (((DMAMODE) == ADC_DMAMODE_DISABLE) || \ ((DMAMODE) == ADC_DMAMODE_ENABLE)) #define IS_ADC_ALL_OVERMODE(OVERMODE) (((OVERMODE) == ADC_OVERMODE_DISABLE) || \ ((OVERMODE) == ADC_OVERMODE_ENABLE)) #define IS_ADC_ALL_OVERSAMPMODE(OVERSAMPMODE) (((OVERSAMPMODE) == ADC_OVERSAMPMODE_DISABLE) || \ ((OVERSAMPMODE) == ADC_OVERSAMPMODE_ENABLE)) #define IS_ADC_ALL_OVSS(_OVSS) (((_OVSS) == ADC_CR2_OVSS_0) || \ ((_OVSS) == ADC_CR2_OVSS_1) || \ ((_OVSS) == ADC_CR2_OVSS_2) || \ ((_OVSS) == ADC_CR2_OVSS_3) || \ ((_OVSS) == ADC_CR2_OVSS_4) || \ ((_OVSS) == ADC_CR2_OVSS_5) || \ ((_OVSS) == ADC_CR2_OVSS_6) || \ ((_OVSS) == ADC_CR2_OVSS_7) || \ ((_OVSS) == ADC_CR2_OVSS_8)) #define IS_ADC_ALL_OVSR(_OVSR) (((_OVSR) == ADC_CR2_OVSR_2X) || \ ((_OVSR) == ADC_CR2_OVSR_4X) || \ ((_OVSR) == ADC_CR2_OVSR_8X) || \ ((_OVSR) == ADC_CR2_OVSR_16X) || \ ((_OVSR) == ADC_CR2_OVSR_32X) || \ ((_OVSR) == ADC_CR2_OVSR_64X) || \ ((_OVSR) == ADC_CR2_OVSR_128X) || \ ((_OVSR) == ADC_CR2_OVSR_256X)) #define IS_ADC_ALL_ANALOGWDGEN(ANALOGWDGEN) (((ANALOGWDGEN) == ADC_ANALOGWDGEN_DISABLE) || \ ((ANALOGWDGEN) == ADC_ANALOGWDGEN_ENABLE)) #define IS_ADC_ALL_CLOCKDIV(CLOCKDIV) (((CLOCKDIV) == ADC_CLOCK_DIV1) || \ ((CLOCKDIV) == ADC_CLOCK_DIV2) || \ ((CLOCKDIV) == ADC_CLOCK_DIV3) || \ ((CLOCKDIV) == ADC_CLOCK_DIV4) || \ ((CLOCKDIV) == ADC_CLOCK_DIV5) || \ ((CLOCKDIV) == ADC_CLOCK_DIV6) || \ ((CLOCKDIV) == ADC_CLOCK_DIV7) || \ ((CLOCKDIV) == ADC_CLOCK_DIV8) || \ ((CLOCKDIV) == ADC_CLOCK_DIV9) || \ ((CLOCKDIV) == ADC_CLOCK_DIV10) || \ ((CLOCKDIV) == ADC_CLOCK_DIV11) || \ ((CLOCKDIV) == ADC_CLOCK_DIV12) || \ ((CLOCKDIV) == ADC_CLOCK_DIV13) || \ ((CLOCKDIV) == ADC_CLOCK_DIV14) || \ ((CLOCKDIV) == ADC_CLOCK_DIV15) || \ ((CLOCKDIV) == ADC_CLOCK_DIV16)) #define IS_ADC_ALL_SEQUENCE(SEQUENCE) (((SEQUENCE) == ADC_SEQUENCE_SQ1) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ2) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ3) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ4) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ5) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ6) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ7) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ8) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ9) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ10) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ11) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ12) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ13) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ14) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ15) || \ ((SEQUENCE) == ADC_SEQUENCE_SQ16)) #define IS_ADC_ALL_CHANNEL(CHANNEL) (((CHANNEL) == ADC_CHANNEL_0) || \ ((CHANNEL) == ADC_CHANNEL_1) || \ ((CHANNEL) == ADC_CHANNEL_2) || \ ((CHANNEL) == ADC_CHANNEL_3) || \ ((CHANNEL) == ADC_CHANNEL_4) || \ ((CHANNEL) == ADC_CHANNEL_5) || \ ((CHANNEL) == ADC_CHANNEL_6) || \ ((CHANNEL) == ADC_CHANNEL_7) || \ ((CHANNEL) == ADC_CHANNEL_8) || \ ((CHANNEL) == ADC_CHANNEL_9) || \ ((CHANNEL) == ADC_CHANNEL_10) || \ ((CHANNEL) == ADC_CHANNEL_11) || \ ((CHANNEL) == ADC_CHANNEL_12) || \ ((CHANNEL) == ADC_CHANNEL_13) || \ ((CHANNEL) == ADC_CHANNEL_14) || \ ((CHANNEL) == ADC_CHANNEL_15) || \ ((CHANNEL) == ADC_CHANNEL_TEMP) || \ ((CHANNEL) == ADC_CHANNEL_VBAT) || \ ((CHANNEL) == ADC_CHANNEL_VBGR) || \ ((CHANNEL) == ADC_CHANNEL_EXT2) || \ ((CHANNEL) == ADC_CHANNEL_EXT3)) #define IS_ADC_ALL_CHANNELEN(CHANNELEN) ((CHANNELEN) <= 0x1FFFFF) #define IS_ADC_ALL_SMPCLOCK(SMPCLOCK) (((SMPCLOCK) == ADC_SMP_CLOCK_3) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_5) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_7) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_10) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_13) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_16) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_20) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_30) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_60) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_80) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_100) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_120) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_160) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_320) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_480) || \ ((SMPCLOCK) == ADC_SMP_CLOCK_640)) #define IS_ADC_ALL_TRIG(_TRIG) (((_TRIG) == ADC_SOFTWARE_START) || \ ((_TRIG) == ADC_EXTERNAL_TIG1) || \ ((_TRIG) == ADC_EXTERNAL_TIG2) || \ ((_TRIG) == ADC_EXTERNAL_TIG3) || \ ((_TRIG) == ADC_EXTERNAL_TIG4) || \ ((_TRIG) == ADC_EXTERNAL_TIG5) || \ ((_TRIG) == ADC_EXTERNAL_TIG6) || \ ((_TRIG) == ADC_EXTERNAL_TIG7)) #define IS_ADC_EVENT_TYPE(_EVENT) (((_EVENT) == ADC_SR_AWD) || \ ((_EVENT) == ADC_SR_OVERF) || \ ((_EVENT) == ADC_SR_EOG) || \ ((_EVENT) == ADC_SR_JEOC) || \ ((_EVENT) == ADC_SR_EOC)) /* Function : HAL_ADC_IRQHandler */ void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc); void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc); void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig); HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig); HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length); HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc); uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef *hadc); HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef *hadc, uint32_t EventType, uint32_t Timeout); HAL_StatusTypeDef HAL_ADC_InjectedStart_IT(ADC_HandleTypeDef* hadc); HAL_StatusTypeDef HAL_ADC_InjectedStop_IT(ADC_HandleTypeDef* hadc); uint32_t HAL_ADC_InjectedGetValue(ADC_HandleTypeDef *hadc); HAL_StatusTypeDef HAL_ADC_Polling(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length, uint32_t Timeout); #endif
e80b8c66ed5a8bf70a67bcfdaf00528539528df1
eda03521b87da8bdbef6339b5b252472a5be8d23
/Kernel/API/VirGL.h
2d7a848459dc42e28ab4e2f7adb4c4e37130eb85
[ "BSD-2-Clause" ]
permissive
SerenityOS/serenity
6ba3ffb242ed76c9f335bd2c3b9a928329cd7d98
ef9b6c25fafcf4ef0b44a562ee07f6412aeb8561
refs/heads/master
2023-09-01T13:04:30.262106
2023-09-01T08:06:28
2023-09-01T10:45:38
160,083,795
27,256
3,929
BSD-2-Clause
2023-09-14T21:00:04
2018-12-02T19:28:41
C++
UTF-8
C
false
false
658
h
VirGL.h
/* * Copyright (c) 2022, Sahan Fernando <sahan.h.fernando@gmail.com> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/Types.h> struct VirGL3DResourceSpec { u32 target; u32 format; u32 bind; u32 width; u32 height; u32 depth; u32 array_size; u32 last_level; u32 nr_samples; u32 flags; u32 created_resource_id; }; struct VirGLCommandBuffer { u32 const* data; u32 num_elems; }; #define VIRGL_DATA_DIR_GUEST_TO_HOST 1 #define VIRGL_DATA_DIR_HOST_TO_GUEST 2 struct VirGLTransferDescriptor { void* data; size_t offset_in_region; size_t num_bytes; int direction; };
84b5ffd178362d7dd16d759745b1dcabe3054dd0
0a3363c1d3d5867f1340de49b84eab84defa3fb8
/arch/am335x/hal/sys/close.c
e6d873deae392c3066654bec590fa9dabcc80ae0
[ "MIT" ]
permissive
odevices/er-301
b09bc53f1b11ff1bba2be8a51220ebfe932dd935
3a7b592fe5d223d5a96b2d8e90b578b23bbdabe5
refs/heads/develop
2023-02-17T16:31:01.764589
2023-02-14T06:55:32
2023-02-14T06:55:32
343,000,824
124
26
MIT
2023-02-14T06:55:34
2021-02-28T02:06:10
C
UTF-8
C
false
false
1,027
c
close.c
#include "resource.h" #include <unistd.h> #include <errno.h> #include "warning.h" #include <hal/log.h> static int card_close(int fd) { FRESULT res; file_t *fp = lookupCardFileDescriptor(fd); if (fp == NULL) { logWarn("Bad file descriptor."); errno = EBADF; return -1; } res = f_sync(&fp->fil); if (res != FR_OK) { logWarn("f_sync failed. (res = %d)", res); errno = EIO; return -1; } res = f_close(&fp->fil); destroyCardFileDescriptor(fd); if (res != FR_OK) { logWarn("f_close failed. (res = %d)", res); errno = EIO; return -1; } return 0; } static int ramdisk_close(int fd) { RamFile *fp = lookupRamFileDescriptor(fd); if (fp == NULL) { errno = EBADF; return -1; } destroyRamFileDescriptor(fd); return 0; } int _close(int fd) { if (isCardFileDescriptor(fd)) { return card_close(fd); } else if (isRamFileDescriptor(fd)) { return ramdisk_close(fd); } else { errno = EBADF; return -1; } }
1c4e457065ae87a3f626fcdff74eb71b508f1de8
3f97df4f7e06c653be69c547c7e2efb7a9b5aad0
/CMSIS/RTOS2/RTX/Source/rtx_mutex.c
6667188b6bb83894b6a3308963ea6e255e3fc7f5
[ "Apache-2.0" ]
permissive
ARM-software/CMSIS_5
ef832c23aa9af025718f5aa3c780b4870d2ff060
a75f01746df18bb5b929dfb8dc6c9407fac3a0f3
refs/heads/develop
2023-09-06T02:49:34.281196
2023-06-21T12:52:04
2023-06-21T12:52:04
51,990,771
2,872
1,356
Apache-2.0
2023-08-22T09:43:24
2016-02-18T08:04:18
C
UTF-8
C
false
false
21,440
c
rtx_mutex.c
/* * Copyright (c) 2013-2023 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. * * ----------------------------------------------------------------------------- * * Project: CMSIS-RTOS RTX * Title: Mutex functions * * ----------------------------------------------------------------------------- */ #include "rtx_lib.h" // OS Runtime Object Memory Usage #ifdef RTX_OBJ_MEM_USAGE osRtxObjectMemUsage_t osRtxMutexMemUsage \ __attribute__((section(".data.os.mutex.obj"))) = { 0U, 0U, 0U }; #endif // ==== Helper functions ==== /// Verify that Mutex object pointer is valid. /// \param[in] mutex mutex object. /// \return true - valid, false - invalid. static bool_t IsMutexPtrValid (const os_mutex_t *mutex) { #ifdef RTX_OBJ_PTR_CHECK //lint --e{923} --e{9078} "cast from pointer to unsigned int" [MISRA Note 7] uint32_t cb_start = (uint32_t)&__os_mutex_cb_start__; uint32_t cb_length = (uint32_t)&__os_mutex_cb_length__; // Check the section boundaries if (((uint32_t)mutex - cb_start) >= cb_length) { //lint -e{904} "Return statement before end of function" [MISRA Note 1] return FALSE; } // Check the object alignment if ((((uint32_t)mutex - cb_start) % sizeof(os_mutex_t)) != 0U) { //lint -e{904} "Return statement before end of function" [MISRA Note 1] return FALSE; } #else // Check NULL pointer if (mutex == NULL) { //lint -e{904} "Return statement before end of function" [MISRA Note 1] return FALSE; } #endif return TRUE; } // ==== Library functions ==== /// Release Mutex list when owner Thread terminates. /// \param[in] mutex_list mutex list. void osRtxMutexOwnerRelease (os_mutex_t *mutex_list) { os_mutex_t *mutex; os_mutex_t *mutex_next; os_thread_t *thread; mutex = mutex_list; while (mutex != NULL) { mutex_next = mutex->owner_next; // Check if Mutex is Robust if ((mutex->attr & osMutexRobust) != 0U) { // Clear Lock counter mutex->lock = 0U; EvrRtxMutexReleased(mutex, 0U); // Check if Thread is waiting for a Mutex if (mutex->thread_list != NULL) { // Wakeup waiting Thread with highest Priority thread = osRtxThreadListGet(osRtxObject(mutex)); osRtxThreadWaitExit(thread, (uint32_t)osOK, FALSE); // Thread is the new Mutex owner mutex->owner_thread = thread; mutex->owner_prev = NULL; mutex->owner_next = thread->mutex_list; if (thread->mutex_list != NULL) { thread->mutex_list->owner_prev = mutex; } thread->mutex_list = mutex; mutex->lock = 1U; EvrRtxMutexAcquired(mutex, 1U); } } mutex = mutex_next; } } /// Restore Mutex owner Thread priority. /// \param[in] mutex mutex object. /// \param[in] thread_wakeup thread wakeup object. void osRtxMutexOwnerRestore (const os_mutex_t *mutex, const os_thread_t *thread_wakeup) { const os_mutex_t *mutex0; os_thread_t *thread; const os_thread_t *thread0; int8_t priority; // Restore owner Thread priority if ((mutex->attr & osMutexPrioInherit) != 0U) { thread = mutex->owner_thread; priority = thread->priority_base; mutex0 = thread->mutex_list; // Check Mutexes owned by Thread do { if ((mutex0->attr & osMutexPrioInherit) != 0U) { // Check Threads waiting for Mutex thread0 = mutex0->thread_list; if (thread0 == thread_wakeup) { // Skip thread that is waken-up thread0 = thread0->thread_next; } if ((thread0 != NULL) && (thread0->priority > priority)) { // Higher priority Thread is waiting for Mutex priority = thread0->priority; } } mutex0 = mutex0->owner_next; } while (mutex0 != NULL); if (thread->priority != priority) { thread->priority = priority; osRtxThreadListSort(thread); } } } /// Unlock Mutex owner when mutex is deleted. /// \param[in] mutex mutex object. /// \return true - successful, false - not locked. static bool_t osRtxMutexOwnerUnlock (os_mutex_t *mutex) { const os_mutex_t *mutex0; os_thread_t *thread; int8_t priority; // Check if Mutex is locked if (mutex->lock == 0U) { //lint -e{904} "Return statement before end of function" [MISRA Note 1] return FALSE; } thread = mutex->owner_thread; // Remove Mutex from Thread owner list if (mutex->owner_next != NULL) { mutex->owner_next->owner_prev = mutex->owner_prev; } if (mutex->owner_prev != NULL) { mutex->owner_prev->owner_next = mutex->owner_next; } else { thread->mutex_list = mutex->owner_next; } // Restore owner Thread priority priority = thread->priority_base; mutex0 = thread->mutex_list; // Check Mutexes owned by Thread while (mutex0 != NULL) { if ((mutex0->attr & osMutexPrioInherit) != 0U) { if ((mutex0->thread_list != NULL) && (mutex0->thread_list->priority > priority)) { // Higher priority Thread is waiting for Mutex priority = mutex0->thread_list->priority; } } mutex0 = mutex0->owner_next; } if (thread->priority != priority) { thread->priority = priority; osRtxThreadListSort(thread); } // Unblock waiting threads while (mutex->thread_list != NULL) { thread = osRtxThreadListGet(osRtxObject(mutex)); osRtxThreadWaitExit(thread, (uint32_t)osErrorResource, FALSE); } mutex->lock = 0U; return TRUE; } /// Destroy a Mutex object. /// \param[in] mutex mutex object. static void osRtxMutexDestroy (os_mutex_t *mutex) { // Mark object as invalid mutex->id = osRtxIdInvalid; // Free object memory if ((mutex->flags & osRtxFlagSystemObject) != 0U) { #ifdef RTX_OBJ_PTR_CHECK (void)osRtxMemoryPoolFree(osRtxInfo.mpi.mutex, mutex); #else if (osRtxInfo.mpi.mutex != NULL) { (void)osRtxMemoryPoolFree(osRtxInfo.mpi.mutex, mutex); } else { (void)osRtxMemoryFree(osRtxInfo.mem.common, mutex); } #endif #ifdef RTX_OBJ_MEM_USAGE osRtxMutexMemUsage.cnt_free++; #endif } EvrRtxMutexDestroyed(mutex); } #ifdef RTX_SAFETY_CLASS /// Delete a Mutex safety class. /// \param[in] safety_class safety class. /// \param[in] mode safety mode. void osRtxMutexDeleteClass (uint32_t safety_class, uint32_t mode) { os_mutex_t *mutex; uint32_t length; //lint --e{923} --e{9078} "cast from pointer to unsigned int" [MISRA Note 7] mutex = (os_mutex_t *)(uint32_t)&__os_mutex_cb_start__; length = (uint32_t)&__os_mutex_cb_length__; while (length >= sizeof(os_mutex_t)) { if ( (mutex->id == osRtxIdMutex) && ((((mode & osSafetyWithSameClass) != 0U) && ((mutex->attr >> osRtxAttrClass_Pos) == (uint8_t)safety_class)) || (((mode & osSafetyWithLowerClass) != 0U) && ((mutex->attr >> osRtxAttrClass_Pos) < (uint8_t)safety_class)))) { (void)osRtxMutexOwnerUnlock(mutex); osRtxMutexDestroy(mutex); } length -= sizeof(os_mutex_t); mutex++; } } #endif // ==== Service Calls ==== /// Create and Initialize a Mutex object. /// \note API identical to osMutexNew static osMutexId_t svcRtxMutexNew (const osMutexAttr_t *attr) { os_mutex_t *mutex; #ifdef RTX_SAFETY_CLASS const os_thread_t *thread = osRtxThreadGetRunning(); #endif uint32_t attr_bits; uint8_t flags; const char *name; // Process attributes if (attr != NULL) { name = attr->name; attr_bits = attr->attr_bits; //lint -e{9079} "conversion from pointer to void to pointer to other type" [MISRA Note 6] mutex = attr->cb_mem; #ifdef RTX_SAFETY_CLASS if ((attr_bits & osSafetyClass_Valid) != 0U) { if ((thread != NULL) && ((thread->attr >> osRtxAttrClass_Pos) < (uint8_t)((attr_bits & osSafetyClass_Msk) >> osSafetyClass_Pos))) { EvrRtxMutexError(NULL, (int32_t)osErrorSafetyClass); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return NULL; } } #endif if (mutex != NULL) { if (!IsMutexPtrValid(mutex) || (attr->cb_size != sizeof(os_mutex_t))) { EvrRtxMutexError(NULL, osRtxErrorInvalidControlBlock); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return NULL; } } else { if (attr->cb_size != 0U) { EvrRtxMutexError(NULL, osRtxErrorInvalidControlBlock); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return NULL; } } } else { name = NULL; attr_bits = 0U; mutex = NULL; } // Allocate object memory if not provided if (mutex == NULL) { if (osRtxInfo.mpi.mutex != NULL) { //lint -e{9079} "conversion from pointer to void to pointer to other type" [MISRA Note 5] mutex = osRtxMemoryPoolAlloc(osRtxInfo.mpi.mutex); #ifndef RTX_OBJ_PTR_CHECK } else { //lint -e{9079} "conversion from pointer to void to pointer to other type" [MISRA Note 5] mutex = osRtxMemoryAlloc(osRtxInfo.mem.common, sizeof(os_mutex_t), 1U); #endif } #ifdef RTX_OBJ_MEM_USAGE if (mutex != NULL) { uint32_t used; osRtxMutexMemUsage.cnt_alloc++; used = osRtxMutexMemUsage.cnt_alloc - osRtxMutexMemUsage.cnt_free; if (osRtxMutexMemUsage.max_used < used) { osRtxMutexMemUsage.max_used = used; } } #endif flags = osRtxFlagSystemObject; } else { flags = 0U; } if (mutex != NULL) { // Initialize control block mutex->id = osRtxIdMutex; mutex->flags = flags; mutex->attr = (uint8_t)(attr_bits & ~osRtxAttrClass_Msk); mutex->name = name; mutex->thread_list = NULL; mutex->owner_thread = NULL; mutex->owner_prev = NULL; mutex->owner_next = NULL; mutex->lock = 0U; #ifdef RTX_SAFETY_CLASS if ((attr_bits & osSafetyClass_Valid) != 0U) { mutex->attr |= (uint8_t)((attr_bits & osSafetyClass_Msk) >> (osSafetyClass_Pos - osRtxAttrClass_Pos)); } else { // Inherit safety class from the running thread if (thread != NULL) { mutex->attr |= (uint8_t)(thread->attr & osRtxAttrClass_Msk); } } #endif EvrRtxMutexCreated(mutex, mutex->name); } else { EvrRtxMutexError(NULL, (int32_t)osErrorNoMemory); } return mutex; } /// Get name of a Mutex object. /// \note API identical to osMutexGetName static const char *svcRtxMutexGetName (osMutexId_t mutex_id) { os_mutex_t *mutex = osRtxMutexId(mutex_id); // Check parameters if (!IsMutexPtrValid(mutex) || (mutex->id != osRtxIdMutex)) { EvrRtxMutexGetName(mutex, NULL); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return NULL; } EvrRtxMutexGetName(mutex, mutex->name); return mutex->name; } /// Acquire a Mutex or timeout if it is locked. /// \note API identical to osMutexAcquire static osStatus_t svcRtxMutexAcquire (osMutexId_t mutex_id, uint32_t timeout) { os_mutex_t *mutex = osRtxMutexId(mutex_id); os_thread_t *thread; osStatus_t status; // Check running thread thread = osRtxThreadGetRunning(); if (thread == NULL) { EvrRtxMutexError(mutex, osRtxErrorKernelNotRunning); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return osError; } // Check parameters if (!IsMutexPtrValid(mutex) || (mutex->id != osRtxIdMutex)) { EvrRtxMutexError(mutex, (int32_t)osErrorParameter); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return osErrorParameter; } #ifdef RTX_SAFETY_CLASS // Check running thread safety class if ((thread->attr >> osRtxAttrClass_Pos) < (mutex->attr >> osRtxAttrClass_Pos)) { EvrRtxMutexError(mutex, (int32_t)osErrorSafetyClass); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return osErrorSafetyClass; } #endif // Check if Mutex is not locked if (mutex->lock == 0U) { // Acquire Mutex mutex->owner_thread = thread; mutex->owner_prev = NULL; mutex->owner_next = thread->mutex_list; if (thread->mutex_list != NULL) { thread->mutex_list->owner_prev = mutex; } thread->mutex_list = mutex; mutex->lock = 1U; EvrRtxMutexAcquired(mutex, mutex->lock); status = osOK; } else { // Check if Mutex is recursive and running Thread is the owner if (((mutex->attr & osMutexRecursive) != 0U) && (mutex->owner_thread == thread)) { // Try to increment lock counter if (mutex->lock == osRtxMutexLockLimit) { EvrRtxMutexError(mutex, osRtxErrorMutexLockLimit); status = osErrorResource; } else { mutex->lock++; EvrRtxMutexAcquired(mutex, mutex->lock); status = osOK; } } else { // Check if timeout is specified if (timeout != 0U) { // Check if Priority inheritance protocol is enabled if ((mutex->attr & osMutexPrioInherit) != 0U) { // Raise priority of owner Thread if lower than priority of running Thread if (mutex->owner_thread->priority < thread->priority) { mutex->owner_thread->priority = thread->priority; osRtxThreadListSort(mutex->owner_thread); } } EvrRtxMutexAcquirePending(mutex, timeout); // Suspend current Thread if (osRtxThreadWaitEnter(osRtxThreadWaitingMutex, timeout)) { osRtxThreadListPut(osRtxObject(mutex), thread); } else { EvrRtxMutexAcquireTimeout(mutex); } status = osErrorTimeout; } else { EvrRtxMutexNotAcquired(mutex); status = osErrorResource; } } } return status; } /// Release a Mutex that was acquired by osMutexAcquire. /// \note API identical to osMutexRelease static osStatus_t svcRtxMutexRelease (osMutexId_t mutex_id) { os_mutex_t *mutex = osRtxMutexId(mutex_id); const os_mutex_t *mutex0; os_thread_t *thread; int8_t priority; // Check running thread thread = osRtxThreadGetRunning(); if (thread == NULL) { EvrRtxMutexError(mutex, osRtxErrorKernelNotRunning); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return osError; } // Check parameters if (!IsMutexPtrValid(mutex) || (mutex->id != osRtxIdMutex)) { EvrRtxMutexError(mutex, (int32_t)osErrorParameter); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return osErrorParameter; } // Check if Mutex is not locked if (mutex->lock == 0U) { EvrRtxMutexError(mutex, osRtxErrorMutexNotLocked); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return osErrorResource; } // Check if running Thread is not the owner if (mutex->owner_thread != thread) { EvrRtxMutexError(mutex, osRtxErrorMutexNotOwned); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return osErrorResource; } // Decrement Lock counter mutex->lock--; EvrRtxMutexReleased(mutex, mutex->lock); // Check Lock counter if (mutex->lock == 0U) { // Remove Mutex from Thread owner list if (mutex->owner_next != NULL) { mutex->owner_next->owner_prev = mutex->owner_prev; } if (mutex->owner_prev != NULL) { mutex->owner_prev->owner_next = mutex->owner_next; } else { thread->mutex_list = mutex->owner_next; } // Restore running Thread priority priority = thread->priority_base; mutex0 = thread->mutex_list; // Check mutexes owned by running Thread while (mutex0 != NULL) { if ((mutex0->attr & osMutexPrioInherit) != 0U) { if ((mutex0->thread_list != NULL) && (mutex0->thread_list->priority > priority)) { // Higher priority Thread is waiting for Mutex priority = mutex0->thread_list->priority; } } mutex0 = mutex0->owner_next; } thread->priority = priority; // Check if Thread is waiting for a Mutex if (mutex->thread_list != NULL) { // Wakeup waiting Thread with highest Priority thread = osRtxThreadListGet(osRtxObject(mutex)); osRtxThreadWaitExit(thread, (uint32_t)osOK, FALSE); // Thread is the new Mutex owner mutex->owner_thread = thread; mutex->owner_prev = NULL; mutex->owner_next = thread->mutex_list; if (thread->mutex_list != NULL) { thread->mutex_list->owner_prev = mutex; } thread->mutex_list = mutex; mutex->lock = 1U; EvrRtxMutexAcquired(mutex, 1U); } osRtxThreadDispatch(NULL); } return osOK; } /// Get Thread which owns a Mutex object. /// \note API identical to osMutexGetOwner static osThreadId_t svcRtxMutexGetOwner (osMutexId_t mutex_id) { os_mutex_t *mutex = osRtxMutexId(mutex_id); // Check parameters if (!IsMutexPtrValid(mutex) || (mutex->id != osRtxIdMutex)) { EvrRtxMutexGetOwner(mutex, NULL); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return NULL; } // Check if Mutex is not locked if (mutex->lock == 0U) { EvrRtxMutexGetOwner(mutex, NULL); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return NULL; } EvrRtxMutexGetOwner(mutex, mutex->owner_thread); return mutex->owner_thread; } /// Delete a Mutex object. /// \note API identical to osMutexDelete static osStatus_t svcRtxMutexDelete (osMutexId_t mutex_id) { os_mutex_t *mutex = osRtxMutexId(mutex_id); #ifdef RTX_SAFETY_CLASS const os_thread_t *thread; #endif // Check parameters if (!IsMutexPtrValid(mutex) || (mutex->id != osRtxIdMutex)) { EvrRtxMutexError(mutex, (int32_t)osErrorParameter); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return osErrorParameter; } #ifdef RTX_SAFETY_CLASS // Check running thread safety class thread = osRtxThreadGetRunning(); if ((thread != NULL) && ((thread->attr >> osRtxAttrClass_Pos) < (mutex->attr >> osRtxAttrClass_Pos))) { EvrRtxMutexError(mutex, (int32_t)osErrorSafetyClass); //lint -e{904} "Return statement before end of function" [MISRA Note 1] return osErrorSafetyClass; } #endif // Unlock the mutex owner if (osRtxMutexOwnerUnlock(mutex)) { osRtxThreadDispatch(NULL); } osRtxMutexDestroy(mutex); return osOK; } // Service Calls definitions //lint ++flb "Library Begin" [MISRA Note 11] SVC0_1(MutexNew, osMutexId_t, const osMutexAttr_t *) SVC0_1(MutexGetName, const char *, osMutexId_t) SVC0_2(MutexAcquire, osStatus_t, osMutexId_t, uint32_t) SVC0_1(MutexRelease, osStatus_t, osMutexId_t) SVC0_1(MutexGetOwner, osThreadId_t, osMutexId_t) SVC0_1(MutexDelete, osStatus_t, osMutexId_t) //lint --flb "Library End" // ==== Public API ==== /// Create and Initialize a Mutex object. osMutexId_t osMutexNew (const osMutexAttr_t *attr) { osMutexId_t mutex_id; EvrRtxMutexNew(attr); if (IsException() || IsIrqMasked()) { EvrRtxMutexError(NULL, (int32_t)osErrorISR); mutex_id = NULL; } else { mutex_id = __svcMutexNew(attr); } return mutex_id; } /// Get name of a Mutex object. const char *osMutexGetName (osMutexId_t mutex_id) { const char *name; if (IsException() || IsIrqMasked()) { name = svcRtxMutexGetName(mutex_id); } else { name = __svcMutexGetName(mutex_id); } return name; } /// Acquire a Mutex or timeout if it is locked. osStatus_t osMutexAcquire (osMutexId_t mutex_id, uint32_t timeout) { osStatus_t status; EvrRtxMutexAcquire(mutex_id, timeout); if (IsException() || IsIrqMasked()) { EvrRtxMutexError(mutex_id, (int32_t)osErrorISR); status = osErrorISR; } else { status = __svcMutexAcquire(mutex_id, timeout); } return status; } /// Release a Mutex that was acquired by \ref osMutexAcquire. osStatus_t osMutexRelease (osMutexId_t mutex_id) { osStatus_t status; EvrRtxMutexRelease(mutex_id); if (IsException() || IsIrqMasked()) { EvrRtxMutexError(mutex_id, (int32_t)osErrorISR); status = osErrorISR; } else { status = __svcMutexRelease(mutex_id); } return status; } /// Get Thread which owns a Mutex object. osThreadId_t osMutexGetOwner (osMutexId_t mutex_id) { osThreadId_t thread; if (IsException() || IsIrqMasked()) { EvrRtxMutexGetOwner(mutex_id, NULL); thread = NULL; } else { thread = __svcMutexGetOwner(mutex_id); } return thread; } /// Delete a Mutex object. osStatus_t osMutexDelete (osMutexId_t mutex_id) { osStatus_t status; EvrRtxMutexDelete(mutex_id); if (IsException() || IsIrqMasked()) { EvrRtxMutexError(mutex_id, (int32_t)osErrorISR); status = osErrorISR; } else { status = __svcMutexDelete(mutex_id); } return status; }
4b5e9f8ec5c338262f0fb7536fc9be0e80c99978
fb47ab6337a71029dee71933e449cf7f6805fc0f
/arch/arm64/include/arch/aspace.h
abb22ff2c2eae915689250ae4dcf62020d8a001c
[ "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
519
h
aspace.h
/* * Copyright (c) 2015-2016 Travis Geiselbrecht * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT */ #pragma once #include <lk/compiler.h> #include <lk/list.h> #include <arch/arm64/mmu.h> __BEGIN_CDECLS struct arch_aspace { /* pointer to the translation table */ paddr_t tt_phys; pte_t *tt_virt; uint flags; /* range of address space */ vaddr_t base; size_t size; }; __END_CDECLS
4dba4fd42fe5e80ab5310a7e9893c739d42f8c95
7df190df28da7e4ff166e55dc8ce780f11236a9f
/src/router/open-plc-utils/plc/int6kid.c
69ce8b16366bc131fd2d9ac8d7400de60b8d0355
[ "BSD-3-Clause-Clear" ]
permissive
mirror/dd-wrt
25416946e6132aa54b35809de61834a1825a9a36
8f2934a5a2adfbb59b471375aa3a38de5d036531
refs/heads/master
2023-08-31T14:54:47.496685
2023-08-30T17:40:54
2023-08-30T17:40:54
7,470,282
520
281
null
2023-05-29T20:56:24
2013-01-06T17:21:29
null
UTF-8
C
false
false
10,269
c
int6kid.c
/*====================================================================* * * Copyright (c) 2013 Qualcomm Atheros, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted (subject to the limitations * in the disclaimer below) provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of Qualcomm Atheros nor the names of * its contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE * COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *--------------------------------------------------------------------*/ /*====================================================================* * * int6kid.c - Atheros Powerline Device Identity * * * Contributor(s): * Charles Maier <cmaier@qca.qualcomm.com> * Matthieu Poullet <m.poullet@avm.de> * *--------------------------------------------------------------------*/ /*====================================================================*" * system header files; *--------------------------------------------------------------------*/ #include <unistd.h> #include <stdlib.h> #include <limits.h> #include <string.h> #include <ctype.h> /*====================================================================* * custom header files; *--------------------------------------------------------------------*/ #include "../tools/getoptv.h" #include "../tools/putoptv.h" #include "../tools/memory.h" #include "../tools/number.h" #include "../tools/symbol.h" #include "../tools/types.h" #include "../tools/flags.h" #include "../tools/files.h" #include "../tools/error.h" #include "../plc/plc.h" #include "../ram/nvram.h" #include "../ram/sdram.h" #include "../nvm/nvm.h" #include "../pib/pib.h" #include "../mme/mme.h" /*====================================================================* * custom source files; *--------------------------------------------------------------------*/ #ifndef MAKEFILE #include "../tools/getoptv.c" #include "../tools/putoptv.c" #include "../tools/version.c" #include "../tools/uintspec.c" #include "../tools/hexencode.c" #include "../tools/hexdecode.c" #include "../tools/todigit.c" #include "../tools/hexdump.c" #include "../tools/hexout.c" #include "../tools/error.c" #include "../tools/synonym.c" #endif #ifndef MAKEFILE #include "../mme/EthernetHeader.c" #include "../mme/QualcommHeader.c" #include "../mme/UnwantedMessage.c" #include "../plc/Display.c" #include "../plc/Devices.c" #endif #ifndef MAKEFILE #include "../ether/openchannel.c" #include "../ether/closechannel.c" #include "../ether/readpacket.c" #include "../ether/sendpacket.c" #include "../ether/channel.c" #endif #ifndef MAKEFILE #include "../mme/MMECode.c" #endif /*====================================================================* * program constants; *--------------------------------------------------------------------*/ #define INT6KID_VERBOSE (1 << 0) #define INT6KID_SILENCE (1 << 1) #define INT6KID_NEWLINE (1 << 2) #define INT6KID_DAK 0 #define INT6KID_NMK 1 #define INT6KID_MAC 2 #define INT6KID_MFG 3 #define INT6KID_USR 4 #define INT6KID_NET 5 /*====================================================================* * * void ReadKey1 (struct channel * channel, unsigned c, int key); * * read the first block of the PIB from a device then echo one of * several parameters on stdout as a string; program output can be * used in scripts to define variables or compare strings; * * this function is an abridged version of ReadParameters(); it reads only * the first 1024 bytes of the PIB then stops; most parameters of * general interest occur in that block; * * *--------------------------------------------------------------------*/ static void ReadKey1 (struct channel * channel, unsigned c, int key) { struct message message; static signed count = 0; signed packetsize; #ifndef __GNUC__ #pragma pack (push,1) #endif struct __packed vs_rd_mod_request { struct ethernet_hdr ethernet; struct qualcomm_hdr qualcomm; uint8_t MODULEID; uint8_t RESERVED; uint16_t MLENGTH; uint32_t MOFFSET; uint8_t DAK [16]; } * request = (struct vs_rd_mod_request *)(&message); struct __packed vs_rd_mod_confirm { struct ethernet_hdr ethernet; struct qualcomm_hdr qualcomm; uint8_t MSTATUS; uint8_t RESERVED1 [3]; uint8_t MODULEID; uint8_t RESERVED2; uint16_t MLENGTH; uint32_t MOFFSET; uint32_t MCHKSUM; struct simple_pib pib; } * confirm = (struct vs_rd_mod_confirm *)(&message); #ifndef __GNUC__ #pragma pack (pop) #endif memset (&message, 0, sizeof (message)); EthernetHeader (&request->ethernet, channel->peer, channel->host, channel->type); QualcommHeader (&request->qualcomm, 0, (VS_RD_MOD | MMTYPE_REQ)); request->MODULEID = VS_MODULE_PIB; request->MLENGTH = HTOLE16 (PLC_RECORD_SIZE); request->MOFFSET = HTOLE32 (0); if (sendpacket (channel, &message, (ETHER_MIN_LEN - ETHER_CRC_LEN)) < 0) { error (1, errno, CHANNEL_CANTSEND); } while ((packetsize = readpacket (channel, &message, sizeof (message))) > 0) { if (UnwantedMessage (&message, packetsize, 0, (VS_RD_MOD | MMTYPE_CNF))) { continue; } if (confirm->MSTATUS) { error (0, 0, "%s (%0X): ", MMECode (confirm->qualcomm.MMTYPE, confirm->MSTATUS), confirm->MSTATUS); continue; } if (count++ > 0) { putc (c, stdout); } if (key == INT6KID_MAC) { hexout (confirm->pib.MAC, sizeof (confirm->pib.MAC), HEX_EXTENDER, 0, stdout); continue; } if (key == INT6KID_DAK) { hexout (confirm->pib.DAK, sizeof (confirm->pib.DAK), HEX_EXTENDER, 0, stdout); continue; } if (key == INT6KID_NMK) { hexout (confirm->pib.NMK, sizeof (confirm->pib.NMK), HEX_EXTENDER, 0, stdout); continue; } if (key == INT6KID_MFG) { confirm->pib.MFG [PIB_HFID_LEN - 1] = (char)(0); printf ("%s", confirm->pib.MFG); continue; } if (key == INT6KID_USR) { confirm->pib.USR [PIB_HFID_LEN - 1] = (char)(0); printf ("%s", confirm->pib.USR); continue; } if (key == INT6KID_NET) { confirm->pib.NET [PIB_HFID_LEN - 1] = (char)(0); printf ("%s", confirm->pib.NET); continue; } } if (packetsize < 0) { error (1, errno, CHANNEL_CANTREAD); } return; } /*====================================================================* * * int main (int argc, char const * argv []); * * * *--------------------------------------------------------------------*/ int main (int argc, char const * argv []) { extern struct channel channel; static char const * optv [] = { "Ac:Dei:MnNqSUv", "device", "Qualcomm Atheros Powerline Device Identity", "A\tEthernet address (MAC)", "c c\tcharacter delimiter is (c)", "D\tDevice Access Key (DAK)", "e\tredirect stderr to stdout", #if defined (WINPCAP) || defined (LIBPCAP) "i n\thost interface is (n) [" LITERAL (CHANNEL_ETHNUMBER) "]", #else "i s\thost interface is (s) [" LITERAL (CHANNEL_ETHDEVICE) "]", #endif "M\tNetwork Membership Key (NMK)", "n\tappend newline on output", "N\tnetwork HFID", "q\tquiet mode", "S\tmanufacturer HFID", "U\tuser HFID", "v\tverbose mode", (char const *) (0) }; signed newline = '\n'; signed key = INT6KID_DAK; flag_t flags = (flag_t)(0); signed c; if (getenv (PLCDEVICE)) { #if defined (WINPCAP) || defined (LIBPCAP) channel.ifindex = atoi (getenv (PLCDEVICE)); #else channel.ifname = strdup (getenv (PLCDEVICE)); #endif } optind = 1; while ((c = getoptv (argc, argv, optv)) != -1) { switch (c) { case 'A': key = INT6KID_MAC; break; case 'c': newline = * optarg; break; case 'D': key = INT6KID_DAK; break; case 'e': dup2 (STDOUT_FILENO, STDERR_FILENO); break; case 'i': #if defined (WINPCAP) || defined (LIBPCAP) channel.ifindex = atoi (optarg); #else channel.ifname = optarg; #endif break; case 'M': key = INT6KID_NMK; break; case 'n': _setbits (flags, INT6KID_NEWLINE); break; case 'N': key = INT6KID_NET; break; case 'q': _setbits (channel.flags, CHANNEL_SILENCE); _setbits (flags, PLC_SILENCE); break; case 'S': key = INT6KID_MFG; break; case 'U': key = INT6KID_USR; break; case 'v': _setbits (channel.flags, CHANNEL_VERBOSE); _setbits (flags, PLC_VERBOSE); break; default: break; } } argc -= optind; argv += optind; openchannel (&channel); if (!argc) { ReadKey1 (&channel, newline, key); if (_anyset (flags, INT6KID_NEWLINE)) { putc (newline, stdout); } } while ((argc) && (* argv)) { if (!hexencode (channel.peer, sizeof (channel.peer), synonym (* argv, devices, SIZEOF (devices)))) { error (1, errno, PLC_BAD_MAC, * argv); } ReadKey1 (&channel, newline, key); if (_anyset (flags, INT6KID_NEWLINE)) { putc (newline, stdout); } argv++; argc--; } closechannel (&channel); return (0); }
0f385fe3cae16835ce16db828eb3b52fedf2bd12
810237086aae7600b9ef87a610aec4777b1bf156
/Example/Pods/Headers/Public/SJBaseVideoPlayer/SJRotationManager.h
6d0c09ff882e792d62ffd0c4b6060cc14b8fff26
[ "MIT" ]
permissive
changsanjiang/SJVideoPlayer
f63f3156d5ad07ec107b0feb481110222dd45a85
bff75e1f7f033edc05e07c333ce3557cb289c95c
refs/heads/master
2022-12-20T22:47:04.095976
2022-12-10T08:57:46
2022-12-10T08:57:46
100,693,284
2,680
513
MIT
2022-11-02T11:04:42
2017-08-18T08:56:30
Objective-C
UTF-8
C
false
false
82
h
SJRotationManager.h
../../../SJBaseVideoPlayer/SJBaseVideoPlayer/Common/Implements/SJRotationManager.h
9027eb37fc90930b9dd9551fa333899834b30b38
7d7900e1c25b729fc8c208673a449c0520ba466e
/poclu/bswap.c
fd58edae5cfd3133584203810bf75094c0bc03b1
[ "MIT", "BSD-2-Clause" ]
permissive
pocl/pocl
384091e15c8f6abf29fd2c6deace34a7de5a6ac6
5a99e12d0bb78427ad948ac368589135507f1b59
refs/heads/main
2023-09-02T14:16:21.381680
2023-08-21T12:13:47
2023-08-21T12:13:47
12,292,999
775
250
MIT
2023-09-14T06:50:34
2013-08-22T09:26:12
C
UTF-8
C
false
false
4,341
c
bswap.c
/** * \brief byte swap functions Copyright (c) 2012 Pekka Jääskeläinen / Tampere University of Technology 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. \file */ #include "pocl_opencl.h" /** * \brief inplace endian byte swap macro * \param __DTYPE [in] word datatype * \param __WORD [in/out] data to be swapped in place */ #define GENERIC_BYTESWAP(__DTYPE, __WORD) \ do { \ unsigned __i; \ union _word_union \ { \ __DTYPE full_word; \ unsigned char bytes[sizeof(__DTYPE)]; \ } __old, __neww; \ \ __old.full_word = __WORD; \ for (__i = 0; __i < sizeof(__DTYPE); ++__i) \ __neww.bytes[__i] = __old.bytes[sizeof(__DTYPE) - __i - 1]; \ __WORD = __neww.full_word; \ } while(0) /** * \brief internal function to compare device- to host-endianness. * @param device [in] device in question * @return 1 if endianness is not the same. */ static int needs_swap(cl_device_id device) { cl_bool deviceLittle; clGetDeviceInfo (device, CL_DEVICE_ENDIAN_LITTLE, sizeof(cl_bool), &deviceLittle, NULL); #if defined(WORDS_BIGENDIAN) && WORDS_BIGENDIAN == 1 return deviceLittle; #else return !deviceLittle; #endif } cl_int poclu_bswap_cl_int(cl_device_id device, cl_int original) { if (!needs_swap (device)) return original; GENERIC_BYTESWAP (cl_int, original); return original; } cl_half poclu_bswap_cl_half(cl_device_id device, cl_half original) { if (!needs_swap (device)) return original; GENERIC_BYTESWAP (cl_half, original); return original; } cl_float poclu_bswap_cl_float(cl_device_id device, cl_float original) { if (!needs_swap (device)) return original; GENERIC_BYTESWAP (cl_float, original); return original; } void poclu_bswap_cl_int_array(cl_device_id device, cl_int* array, size_t num_elements) { size_t i; if (!needs_swap (device)) return; for (i = 0; i < num_elements; ++i) { GENERIC_BYTESWAP (cl_int, array[i]); } } void poclu_bswap_cl_half_array(cl_device_id device, cl_half* array, size_t num_elements) { size_t i; if (!needs_swap (device)) return; for (i = 0; i < num_elements; ++i) { GENERIC_BYTESWAP (cl_half, array[i]); } } void poclu_bswap_cl_float_array(cl_device_id device, cl_float* array, size_t num_elements) { size_t i; if (!needs_swap (device)) return; for (i = 0; i < num_elements; ++i) { GENERIC_BYTESWAP (cl_float, array[i]); } } void poclu_bswap_cl_float2_array(cl_device_id device, cl_float2* array, size_t num_elements) { size_t i; if (!needs_swap (device)) return; for (i = 0; i < num_elements; ++i) { GENERIC_BYTESWAP (cl_float, array[i].s[0]); GENERIC_BYTESWAP (cl_float, array[i].s[1]); } }
c5a0b1416ca5f70b406cb1df0df3a9d804d93db3
35c04ea32351dc95bc18d46e5c70dda9c1e08668
/Examples/MCUXpresso/tinyK22/tinyK22_FreeRTOS_ASAN/source/asan_test.h
abe3be6266fd9825485683cd0e9afb6da994dd18
[ "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
180
h
asan_test.h
/* * Copyright (c) 2020, Erich Styger * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef ASAN_TEST_H_ #define ASAN_TEST_H_ void ASAN_Test(void); #endif /* ASAN_TEST_H_ */
26ce84e47a4bc3077dd3032884d3b9910647a04f
aa5c1a530f95d629e686ac9124caf1a49a9f23e9
/runtime/src/iree/hal/drivers/local_sync/sync_event.c
117f83f93deb920bf60d08e996d4008a11c69169
[ "Apache-2.0", "LLVM-exception", "LicenseRef-scancode-unknown-license-reference" ]
permissive
openxla/iree
eacf5b239559e1d3b40c38039ac4c26315b523f7
13ef677e556d0a1d154e45b052fe016256057f65
refs/heads/main
2023-09-06T01:19:49.598662
2023-09-04T07:01:30
2023-09-04T07:01:30
208,145,128
387
110
Apache-2.0
2023-09-14T20:48:00
2019-09-12T20:57:39
C++
UTF-8
C
false
false
1,753
c
sync_event.c
// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/hal/drivers/local_sync/sync_event.h" #include <stddef.h> typedef struct iree_hal_sync_event_t { iree_hal_resource_t resource; iree_allocator_t host_allocator; } iree_hal_sync_event_t; static const iree_hal_event_vtable_t iree_hal_sync_event_vtable; static iree_hal_sync_event_t* iree_hal_sync_event_cast( iree_hal_event_t* base_value) { IREE_HAL_ASSERT_TYPE(base_value, &iree_hal_sync_event_vtable); return (iree_hal_sync_event_t*)base_value; } iree_status_t iree_hal_sync_event_create(iree_allocator_t host_allocator, iree_hal_event_t** out_event) { IREE_ASSERT_ARGUMENT(out_event); *out_event = NULL; IREE_TRACE_ZONE_BEGIN(z0); iree_hal_sync_event_t* event = NULL; iree_status_t status = iree_allocator_malloc(host_allocator, sizeof(*event), (void**)&event); if (iree_status_is_ok(status)) { iree_hal_resource_initialize(&iree_hal_sync_event_vtable, &event->resource); event->host_allocator = host_allocator; *out_event = (iree_hal_event_t*)event; } IREE_TRACE_ZONE_END(z0); return status; } static void iree_hal_sync_event_destroy(iree_hal_event_t* base_event) { iree_hal_sync_event_t* event = iree_hal_sync_event_cast(base_event); iree_allocator_t host_allocator = event->host_allocator; IREE_TRACE_ZONE_BEGIN(z0); iree_allocator_free(host_allocator, event); IREE_TRACE_ZONE_END(z0); } static const iree_hal_event_vtable_t iree_hal_sync_event_vtable = { .destroy = iree_hal_sync_event_destroy, };
a1aef2e4df5747ca5ff710e2d70209aa4c5b67ed
83e7dc1281874779c46dfadcc15b2bb66d8e599c
/demos/music/assets/img_lv_demo_music_icon_3_large.c
d359e07ddc37eb064a445190f82ae130814bf20f
[ "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
60,177
c
img_lv_demo_music_icon_3_large.c
#include "../lv_demo_music.h" #if LV_USE_DEMO_MUSIC && LV_DEMO_MUSIC_LARGE #ifndef LV_ATTRIBUTE_MEM_ALIGN #define LV_ATTRIBUTE_MEM_ALIGN #endif #ifndef LV_ATTRIBUTE_IMG_IMG_LV_DEMO_MUSIC_ICN_DOWNLOAD #define LV_ATTRIBUTE_IMG_IMG_LV_DEMO_MUSIC_ICN_DOWNLOAD #endif const LV_ATTRIBUTE_MEM_ALIGN LV_ATTRIBUTE_LARGE_CONST LV_ATTRIBUTE_IMG_IMG_LV_DEMO_MUSIC_ICN_DOWNLOAD uint8_t img_lv_demo_music_icon_3_map[] = { #if LV_COLOR_DEPTH == 1 || LV_COLOR_DEPTH == 8 /*Pixel format: Blue: 2 bit, Green: 3 bit, Red: 3 bit, Alpha 8 bit */ 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x08, 0x21, 0xcb, 0x21, 0xef, 0x21, 0x37, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x28, 0x21, 0xff, 0x21, 0xff, 0x21, 0x87, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x27, 0x21, 0xff, 0x21, 0xff, 0x21, 0x7b, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x27, 0x21, 0xff, 0x21, 0xff, 0x21, 0x78, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x27, 0x21, 0xff, 0x21, 0xff, 0x21, 0x78, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x27, 0x21, 0xff, 0x21, 0xff, 0x21, 0x78, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x27, 0x21, 0xff, 0x21, 0xff, 0x21, 0x78, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x27, 0x21, 0xff, 0x21, 0xff, 0x21, 0x78, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x25, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x48, 0x21, 0x9b, 0x21, 0xc8, 0x21, 0xdc, 0x21, 0xe0, 0x21, 0xd0, 0x21, 0x44, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x27, 0x21, 0xff, 0x21, 0xff, 0x21, 0x78, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x14, 0x21, 0xb4, 0x21, 0xdf, 0x21, 0xdf, 0x21, 0xd3, 0x21, 0xab, 0x21, 0x67, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x04, 0x21, 0xb0, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0x9f, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x27, 0x21, 0xff, 0x21, 0xff, 0x21, 0x78, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x37, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xdb, 0x21, 0x33, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0xcf, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xc7, 0x21, 0xa7, 0x21, 0xa3, 0x21, 0x93, 0x21, 0x18, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x27, 0x21, 0xff, 0x21, 0xff, 0x21, 0x78, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x25, 0x00, 0x21, 0x00, 0x21, 0x73, 0x21, 0xa3, 0x21, 0xa3, 0x21, 0xb8, 0x21, 0xf3, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0x38, 0x25, 0x00, 0x21, 0x00, 0x21, 0xb3, 0x21, 0xff, 0x21, 0xff, 0x21, 0xb8, 0x21, 0x2c, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x27, 0x21, 0xff, 0x21, 0xff, 0x21, 0x78, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x25, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x13, 0x21, 0x87, 0x21, 0xff, 0x21, 0xff, 0x21, 0xf7, 0x21, 0x08, 0x21, 0x34, 0x21, 0xff, 0x21, 0xff, 0x21, 0xc3, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x27, 0x21, 0xff, 0x21, 0xff, 0x21, 0x78, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x70, 0x21, 0xff, 0x21, 0xff, 0x21, 0x87, 0x21, 0x94, 0x21, 0xff, 0x21, 0xfc, 0x21, 0x14, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x27, 0x21, 0xff, 0x21, 0xff, 0x21, 0x78, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0xdb, 0x21, 0xff, 0x21, 0xeb, 0x21, 0xd7, 0x21, 0xff, 0x21, 0xc7, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x25, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x27, 0x21, 0xff, 0x21, 0xff, 0x21, 0x78, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x73, 0x21, 0xff, 0x21, 0xfb, 0x21, 0xf0, 0x21, 0xff, 0x21, 0xa8, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x48, 0x21, 0x6b, 0x21, 0x00, 0x21, 0x00, 0x21, 0x2b, 0x21, 0xff, 0x21, 0xff, 0x21, 0x7b, 0x21, 0x00, 0x21, 0x00, 0x21, 0x50, 0x21, 0x68, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x53, 0x21, 0xff, 0x21, 0xf4, 0x21, 0xec, 0x21, 0xff, 0x21, 0xac, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x18, 0x21, 0xff, 0x21, 0xff, 0x21, 0x9c, 0x21, 0x00, 0x21, 0x10, 0x21, 0xff, 0x21, 0xff, 0x21, 0x73, 0x21, 0x00, 0x21, 0x57, 0x21, 0xff, 0x21, 0xff, 0x21, 0x5f, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x25, 0x00, 0x25, 0x00, 0x25, 0x00, 0x21, 0x58, 0x21, 0xff, 0x21, 0xf4, 0x21, 0xeb, 0x21, 0xff, 0x21, 0xac, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x0f, 0x21, 0xe0, 0x21, 0xff, 0x21, 0xff, 0x21, 0x8c, 0x21, 0x00, 0x21, 0xf3, 0x21, 0xff, 0x21, 0x48, 0x21, 0x38, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0x3b, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x25, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x5b, 0x21, 0xff, 0x21, 0xf4, 0x21, 0xeb, 0x21, 0xff, 0x21, 0xac, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x25, 0x00, 0x25, 0x00, 0x25, 0x00, 0x21, 0x0f, 0x21, 0xdc, 0x21, 0xff, 0x21, 0xff, 0x21, 0xc3, 0x21, 0xe8, 0x21, 0xff, 0x21, 0xc3, 0x21, 0xfb, 0x21, 0xff, 0x21, 0xff, 0x21, 0x4c, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x5b, 0x21, 0xff, 0x21, 0xf4, 0x21, 0xeb, 0x21, 0xff, 0x21, 0xac, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x25, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x10, 0x21, 0xe4, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0x50, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x25, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x5b, 0x21, 0xff, 0x21, 0xf4, 0x21, 0xeb, 0x21, 0xff, 0x21, 0xac, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x25, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x13, 0x21, 0xd8, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0x50, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x5b, 0x21, 0xff, 0x21, 0xf4, 0x21, 0xeb, 0x21, 0xff, 0x21, 0xac, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x0f, 0x21, 0xe7, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0x4c, 0x25, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x5b, 0x21, 0xff, 0x21, 0xf4, 0x21, 0xeb, 0x21, 0xff, 0x21, 0xac, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x25, 0x00, 0x25, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x18, 0x21, 0xdc, 0x21, 0xf8, 0x21, 0x5b, 0x21, 0x00, 0x25, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x5b, 0x21, 0xff, 0x21, 0xf4, 0x21, 0xef, 0x21, 0xff, 0x21, 0xa8, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x03, 0x21, 0x14, 0x21, 0x00, 0x21, 0x00, 0x25, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x57, 0x21, 0xff, 0x21, 0xf4, 0x21, 0xeb, 0x21, 0xff, 0x21, 0xaf, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x25, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x25, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x57, 0x21, 0xff, 0x21, 0xf7, 0x21, 0xc0, 0x21, 0xff, 0x21, 0xdf, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x94, 0x21, 0xff, 0x21, 0xfb, 0x21, 0x6c, 0x21, 0xff, 0x21, 0xff, 0x21, 0x58, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x0b, 0x21, 0xf8, 0x21, 0xff, 0x21, 0xcf, 0x21, 0x0f, 0x21, 0xff, 0x21, 0xff, 0x21, 0xfb, 0x21, 0x38, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x04, 0x21, 0xc3, 0x21, 0xff, 0x21, 0xff, 0x21, 0x4c, 0x21, 0x00, 0x21, 0x60, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0x80, 0x21, 0x3b, 0x21, 0x1f, 0x21, 0x1b, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x1c, 0x21, 0x2c, 0x21, 0x63, 0x21, 0xdc, 0x21, 0xff, 0x21, 0xff, 0x21, 0xb7, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x73, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xb7, 0x21, 0x00, 0x25, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x4c, 0x21, 0xcf, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xff, 0x21, 0xef, 0x21, 0x7f, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x07, 0x21, 0x58, 0x21, 0x84, 0x21, 0x94, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x97, 0x21, 0x8c, 0x21, 0x6b, 0x21, 0x20, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, #endif #if LV_COLOR_DEPTH == 16 /*Pixel format: Blue: 5 bit, Green: 6 bit, Red: 5 bit, Alpha 8 bit*/ 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x08, 0x66, 0x20, 0xcb, 0x66, 0x20, 0xef, 0x66, 0x20, 0x37, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x28, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x86, 0x20, 0x87, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x27, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x7b, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x27, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x78, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x46, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x27, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x78, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x46, 0x20, 0x00, 0x46, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x27, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x78, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x46, 0x20, 0x00, 0x46, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x27, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x78, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x46, 0x20, 0x00, 0x26, 0x20, 0x00, 0x46, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x27, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x78, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x48, 0x66, 0x20, 0x9b, 0x66, 0x20, 0xc8, 0x66, 0x20, 0xdc, 0x66, 0x20, 0xe0, 0x66, 0x20, 0xd0, 0x66, 0x20, 0x44, 0x46, 0x20, 0x00, 0x46, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x27, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x78, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x14, 0x66, 0x20, 0xb4, 0x66, 0x20, 0xdf, 0x66, 0x20, 0xdf, 0x66, 0x20, 0xd3, 0x66, 0x20, 0xab, 0x66, 0x20, 0x67, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x04, 0x66, 0x20, 0xb0, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x9f, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x27, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x78, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x37, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xdb, 0x66, 0x20, 0x33, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0xcf, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xc7, 0x66, 0x20, 0xa7, 0x66, 0x20, 0xa3, 0x66, 0x20, 0x93, 0x46, 0x20, 0x18, 0x46, 0x20, 0x00, 0x46, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x27, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x78, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x73, 0x66, 0x20, 0xa3, 0x66, 0x20, 0xa3, 0x66, 0x20, 0xb8, 0x66, 0x20, 0xf3, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x38, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0xb3, 0x66, 0x20, 0xff, 0x86, 0x20, 0xff, 0x66, 0x20, 0xb8, 0x66, 0x20, 0x2c, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x46, 0x20, 0x00, 0x26, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x27, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x78, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x13, 0x66, 0x20, 0x87, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xf7, 0x66, 0x20, 0x08, 0x66, 0x20, 0x34, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xc3, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x46, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x27, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x78, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x70, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x87, 0x66, 0x20, 0x94, 0x66, 0x20, 0xff, 0x66, 0x20, 0xfc, 0x46, 0x20, 0x14, 0x46, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x27, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x78, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x46, 0x20, 0x00, 0x46, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0xdb, 0x66, 0x20, 0xff, 0x66, 0x20, 0xeb, 0x66, 0x20, 0xd7, 0x66, 0x20, 0xff, 0x66, 0x20, 0xc7, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x27, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x78, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x46, 0x20, 0x00, 0x26, 0x20, 0x00, 0x46, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x73, 0x66, 0x20, 0xff, 0x66, 0x20, 0xfb, 0x66, 0x20, 0xf0, 0x66, 0x20, 0xff, 0x66, 0x20, 0xa8, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x48, 0x66, 0x20, 0x6b, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x2b, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x7b, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x50, 0x66, 0x20, 0x68, 0x46, 0x20, 0x00, 0x46, 0x20, 0x00, 0x46, 0x20, 0x00, 0x46, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x53, 0x66, 0x20, 0xff, 0x66, 0x20, 0xf4, 0x66, 0x20, 0xec, 0x66, 0x20, 0xff, 0x66, 0x20, 0xac, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x18, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x9c, 0x66, 0x20, 0x00, 0x66, 0x20, 0x10, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x73, 0x66, 0x20, 0x00, 0x66, 0x20, 0x57, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x5f, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x58, 0x66, 0x20, 0xff, 0x66, 0x20, 0xf4, 0x66, 0x20, 0xeb, 0x66, 0x20, 0xff, 0x66, 0x20, 0xac, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x0f, 0x66, 0x20, 0xe0, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x8c, 0x66, 0x20, 0x00, 0x66, 0x20, 0xf3, 0x66, 0x20, 0xff, 0x66, 0x20, 0x48, 0x66, 0x20, 0x38, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x46, 0x20, 0x3b, 0x46, 0x20, 0x00, 0x46, 0x20, 0x00, 0x46, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x5b, 0x66, 0x20, 0xff, 0x66, 0x20, 0xf4, 0x66, 0x20, 0xeb, 0x66, 0x20, 0xff, 0x66, 0x20, 0xac, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x0f, 0x66, 0x20, 0xdc, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xc3, 0x66, 0x20, 0xe8, 0x66, 0x20, 0xff, 0x66, 0x20, 0xc3, 0x66, 0x20, 0xfb, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x4c, 0x46, 0x20, 0x00, 0x46, 0x20, 0x00, 0x46, 0x20, 0x00, 0x46, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x5b, 0x66, 0x20, 0xff, 0x66, 0x20, 0xf4, 0x66, 0x20, 0xeb, 0x66, 0x20, 0xff, 0x66, 0x20, 0xac, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x10, 0x66, 0x20, 0xe4, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x86, 0x20, 0x50, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x5b, 0x66, 0x20, 0xff, 0x66, 0x20, 0xf4, 0x66, 0x20, 0xeb, 0x66, 0x20, 0xff, 0x66, 0x20, 0xac, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x13, 0x66, 0x20, 0xd8, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x86, 0x20, 0xff, 0x86, 0x20, 0x50, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x5b, 0x66, 0x20, 0xff, 0x66, 0x20, 0xf4, 0x66, 0x20, 0xeb, 0x66, 0x20, 0xff, 0x66, 0x20, 0xac, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x0f, 0x66, 0x20, 0xe7, 0x66, 0x20, 0xff, 0x86, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x4c, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x5b, 0x66, 0x20, 0xff, 0x66, 0x20, 0xf4, 0x66, 0x20, 0xeb, 0x66, 0x20, 0xff, 0x66, 0x20, 0xac, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x18, 0x66, 0x20, 0xdc, 0x66, 0x20, 0xf8, 0x46, 0x20, 0x5b, 0x46, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x5b, 0x66, 0x20, 0xff, 0x66, 0x20, 0xf4, 0x66, 0x20, 0xef, 0x66, 0x20, 0xff, 0x66, 0x20, 0xa8, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x03, 0x66, 0x20, 0x14, 0x26, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x57, 0x66, 0x20, 0xff, 0x66, 0x20, 0xf4, 0x66, 0x20, 0xeb, 0x66, 0x20, 0xff, 0x66, 0x20, 0xaf, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x26, 0x20, 0x00, 0x46, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x57, 0x66, 0x20, 0xff, 0x66, 0x20, 0xf7, 0x66, 0x20, 0xc0, 0x66, 0x20, 0xff, 0x66, 0x20, 0xdf, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x46, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x94, 0x66, 0x20, 0xff, 0x66, 0x20, 0xfb, 0x66, 0x20, 0x6c, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x58, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x0b, 0x66, 0x20, 0xf8, 0x66, 0x20, 0xff, 0x66, 0x20, 0xcf, 0x86, 0x20, 0x0f, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xfb, 0x66, 0x20, 0x38, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x04, 0x86, 0x20, 0xc3, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x46, 0x20, 0x4c, 0x86, 0x20, 0x00, 0x86, 0x20, 0x60, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0x80, 0x66, 0x20, 0x3b, 0x66, 0x20, 0x1f, 0x66, 0x20, 0x1b, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x1c, 0x66, 0x20, 0x2c, 0x66, 0x20, 0x63, 0x66, 0x20, 0xdc, 0x66, 0x20, 0xff, 0x86, 0x20, 0xff, 0x66, 0x20, 0xb7, 0x46, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x73, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xb7, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x4c, 0x66, 0x20, 0xcf, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xff, 0x66, 0x20, 0xef, 0x66, 0x20, 0x7f, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x86, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x07, 0x66, 0x20, 0x58, 0x66, 0x20, 0x84, 0x66, 0x20, 0x94, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x97, 0x66, 0x20, 0x8c, 0x66, 0x20, 0x6b, 0x66, 0x20, 0x20, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x66, 0x20, 0x00, 0x86, 0x20, 0x00, #endif #if LV_COLOR_DEPTH == 32 /*Pixel format: Blue: 8 bit, Green: 8 bit, Red: 8 bit, Alpha: 8 bit*/ 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x32, 0x0c, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x08, 0x32, 0x0e, 0x20, 0xcb, 0x32, 0x0e, 0x20, 0xef, 0x30, 0x0b, 0x20, 0x37, 0x30, 0x0b, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0b, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0b, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0c, 0x20, 0x00, 0x32, 0x0c, 0x20, 0x00, 0x32, 0x0c, 0x20, 0x00, 0x32, 0x0c, 0x20, 0x00, 0x32, 0x0c, 0x20, 0x00, 0x32, 0x0c, 0x20, 0x00, 0x32, 0x0c, 0x20, 0x28, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0f, 0x20, 0x87, 0x32, 0x0f, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0f, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0b, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x27, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x7b, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0b, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0b, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x27, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x78, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0b, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x30, 0x09, 0x20, 0x00, 0x32, 0x0c, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x27, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x78, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0b, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x30, 0x09, 0x20, 0x00, 0x31, 0x09, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x27, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x78, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0b, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x30, 0x09, 0x20, 0x00, 0x30, 0x07, 0x20, 0x00, 0x32, 0x0c, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x27, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x78, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0b, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x30, 0x09, 0x20, 0x00, 0x2f, 0x05, 0x20, 0x00, 0x31, 0x09, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x27, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x78, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0b, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x48, 0x32, 0x0e, 0x20, 0x9b, 0x32, 0x0e, 0x20, 0xc8, 0x32, 0x0e, 0x20, 0xdc, 0x32, 0x0e, 0x20, 0xe0, 0x32, 0x0e, 0x20, 0xd0, 0x31, 0x0c, 0x20, 0x44, 0x30, 0x0a, 0x20, 0x00, 0x30, 0x0a, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x27, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x78, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x14, 0x32, 0x0e, 0x20, 0xb4, 0x32, 0x0e, 0x20, 0xdf, 0x32, 0x0e, 0x20, 0xdf, 0x32, 0x0e, 0x20, 0xd3, 0x32, 0x0e, 0x20, 0xab, 0x31, 0x0c, 0x20, 0x67, 0x31, 0x0b, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x04, 0x32, 0x0e, 0x20, 0xb0, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x9f, 0x30, 0x0e, 0x20, 0x00, 0x30, 0x0d, 0x20, 0x00, 0x32, 0x0c, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x27, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x78, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x37, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xdb, 0x32, 0x0c, 0x20, 0x33, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x32, 0x0e, 0x20, 0xcf, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xc7, 0x31, 0x0e, 0x20, 0xa7, 0x31, 0x0e, 0x20, 0xa3, 0x31, 0x0e, 0x20, 0x93, 0x30, 0x09, 0x20, 0x18, 0x30, 0x07, 0x20, 0x00, 0x30, 0x08, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x27, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x78, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x73, 0x31, 0x0e, 0x20, 0xa3, 0x31, 0x0e, 0x20, 0xa3, 0x32, 0x0e, 0x20, 0xb8, 0x32, 0x0e, 0x20, 0xf3, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0e, 0x20, 0x38, 0x30, 0x11, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x31, 0x0e, 0x20, 0xb3, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0f, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xb8, 0x30, 0x0e, 0x20, 0x2c, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x30, 0x0d, 0x20, 0x00, 0x30, 0x0d, 0x20, 0x00, 0x30, 0x08, 0x20, 0x00, 0x30, 0x06, 0x20, 0x00, 0x31, 0x0b, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x27, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x78, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x30, 0x0d, 0x20, 0x00, 0x30, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x13, 0x32, 0x0e, 0x20, 0x87, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xf7, 0x30, 0x0e, 0x20, 0x08, 0x30, 0x0d, 0x20, 0x34, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0d, 0x20, 0xc3, 0x30, 0x0b, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x30, 0x0d, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x08, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x27, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x78, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x30, 0x0b, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x30, 0x0d, 0x20, 0x00, 0x30, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x70, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0c, 0x20, 0x87, 0x31, 0x0e, 0x20, 0x94, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xfc, 0x30, 0x09, 0x20, 0x14, 0x30, 0x07, 0x20, 0x00, 0x30, 0x0b, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x31, 0x10, 0x20, 0x00, 0x32, 0x0c, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x27, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x78, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0a, 0x20, 0x00, 0x30, 0x08, 0x20, 0x00, 0x30, 0x0d, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x32, 0x0e, 0x20, 0xdb, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xeb, 0x32, 0x0e, 0x20, 0xd7, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xc7, 0x30, 0x0d, 0x20, 0x00, 0x30, 0x0d, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x00, 0x32, 0x0c, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x27, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x78, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0b, 0x20, 0x00, 0x30, 0x07, 0x20, 0x00, 0x30, 0x06, 0x20, 0x00, 0x30, 0x0a, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x73, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xfb, 0x32, 0x0e, 0x20, 0xf0, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0d, 0x20, 0xa8, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x48, 0x32, 0x0d, 0x20, 0x6b, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x2b, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0d, 0x20, 0x7b, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x50, 0x31, 0x0c, 0x20, 0x68, 0x30, 0x09, 0x20, 0x00, 0x30, 0x08, 0x20, 0x00, 0x30, 0x07, 0x20, 0x00, 0x30, 0x08, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x53, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xf4, 0x32, 0x0e, 0x20, 0xec, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0d, 0x20, 0xac, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0b, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x18, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x9c, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x10, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0d, 0x20, 0x73, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x57, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0e, 0x20, 0x5f, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x58, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xf4, 0x32, 0x0e, 0x20, 0xeb, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0d, 0x20, 0xac, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x0f, 0x32, 0x0e, 0x20, 0xe0, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x8c, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0e, 0x20, 0xf3, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0x48, 0x32, 0x0e, 0x20, 0x38, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0a, 0x20, 0x3b, 0x30, 0x08, 0x20, 0x00, 0x30, 0x09, 0x20, 0x00, 0x30, 0x08, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x5b, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xf4, 0x32, 0x0e, 0x20, 0xeb, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0d, 0x20, 0xac, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0b, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x30, 0x12, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x0f, 0x32, 0x0e, 0x20, 0xdc, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xc3, 0x32, 0x0e, 0x20, 0xe8, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xc3, 0x32, 0x0e, 0x20, 0xfb, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0e, 0x20, 0x4c, 0x30, 0x09, 0x20, 0x00, 0x30, 0x08, 0x20, 0x00, 0x30, 0x08, 0x20, 0x00, 0x30, 0x09, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x5b, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xf4, 0x32, 0x0e, 0x20, 0xeb, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0d, 0x20, 0xac, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0b, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x10, 0x32, 0x0e, 0x20, 0xe4, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x30, 0x0f, 0x20, 0x50, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x5b, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xf4, 0x32, 0x0e, 0x20, 0xeb, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0d, 0x20, 0xac, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0b, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x13, 0x32, 0x0e, 0x20, 0xd8, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0f, 0x20, 0xff, 0x30, 0x0f, 0x20, 0x50, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x5b, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xf4, 0x32, 0x0e, 0x20, 0xeb, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0d, 0x20, 0xac, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0b, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x0f, 0x32, 0x0e, 0x20, 0xe7, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0f, 0x20, 0xff, 0x32, 0x0d, 0x20, 0xff, 0x30, 0x0c, 0x20, 0x4c, 0x30, 0x11, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x5b, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xf4, 0x32, 0x0e, 0x20, 0xeb, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0d, 0x20, 0xac, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x2f, 0x11, 0x20, 0x00, 0x2f, 0x11, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x18, 0x32, 0x0e, 0x20, 0xdc, 0x32, 0x0e, 0x20, 0xf8, 0x31, 0x08, 0x20, 0x5b, 0x30, 0x0a, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x5b, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xf4, 0x32, 0x0e, 0x20, 0xef, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0d, 0x20, 0xa8, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x30, 0x0c, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x33, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x03, 0x31, 0x0c, 0x20, 0x14, 0x30, 0x06, 0x20, 0x00, 0x30, 0x0b, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x57, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xf4, 0x32, 0x0e, 0x20, 0xeb, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0d, 0x20, 0xaf, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x30, 0x06, 0x20, 0x00, 0x30, 0x0a, 0x20, 0x00, 0x31, 0x11, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x57, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xf7, 0x31, 0x0e, 0x20, 0xc0, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xdf, 0x30, 0x0d, 0x20, 0x00, 0x30, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x31, 0x0c, 0x20, 0x00, 0x31, 0x0a, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x94, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xfb, 0x31, 0x0e, 0x20, 0x6c, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x30, 0x0c, 0x20, 0x58, 0x30, 0x0b, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0f, 0x20, 0x00, 0x32, 0x0f, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x30, 0x10, 0x20, 0x0b, 0x32, 0x0e, 0x20, 0xf8, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0d, 0x20, 0xcf, 0x30, 0x10, 0x20, 0x0f, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0d, 0x20, 0xfb, 0x31, 0x0b, 0x20, 0x38, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x32, 0x0e, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x04, 0x32, 0x0f, 0x20, 0xc3, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x30, 0x0a, 0x20, 0x4c, 0x30, 0x10, 0x20, 0x00, 0x31, 0x0f, 0x20, 0x60, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x31, 0x0d, 0x20, 0x80, 0x31, 0x0d, 0x20, 0x3b, 0x32, 0x0e, 0x20, 0x1f, 0x32, 0x0e, 0x20, 0x1b, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x32, 0x0e, 0x20, 0x1c, 0x31, 0x0d, 0x20, 0x2c, 0x31, 0x0e, 0x20, 0x63, 0x32, 0x0e, 0x20, 0xdc, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0f, 0x20, 0xff, 0x31, 0x0d, 0x20, 0xb7, 0x30, 0x0a, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x31, 0x0d, 0x20, 0x73, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xb7, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x11, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x4c, 0x32, 0x0e, 0x20, 0xcf, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xff, 0x32, 0x0e, 0x20, 0xef, 0x31, 0x0d, 0x20, 0x7f, 0x31, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, 0x30, 0x0f, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x30, 0x0e, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x07, 0x31, 0x0e, 0x20, 0x58, 0x31, 0x0e, 0x20, 0x84, 0x32, 0x0e, 0x20, 0x94, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x97, 0x32, 0x0e, 0x20, 0x8c, 0x31, 0x0e, 0x20, 0x6b, 0x31, 0x0d, 0x20, 0x20, 0x31, 0x0d, 0x20, 0x00, 0x32, 0x0d, 0x20, 0x00, 0x31, 0x0e, 0x20, 0x00, 0x30, 0x10, 0x20, 0x00, #endif }; const lv_img_dsc_t img_lv_demo_music_icon_3 = { .header.always_zero = 0, .header.w = 34, .header.h = 32, .data_size = 1088 * LV_COLOR_FORMAT_NATIVE_ALPHA_SIZE, .header.cf = LV_COLOR_FORMAT_NATIVE_ALPHA, .data = img_lv_demo_music_icon_3_map, }; #endif
f6646ab3ff7197bcac0cadeae29c9500b94532ba
423b65b4ad72a4601ae49202ed87284bcce54bab
/lib/verifier/klee-mainstream/__VERIFIER_nondet_double_named.c
d14544b6809f9e56a8088ff392aa350cbf4f31b8
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "NCSA" ]
permissive
staticafi/symbiotic
aed81e44ba6faca51d4c0e7769882afef2c5f1bf
7ba60a1e715ef0d5f261c9b2f032a00d96b4d053
refs/heads/main
2023-05-11T07:37:04.709107
2022-12-21T10:33:28
2023-03-14T09:17:19
28,639,394
281
54
MIT
2023-04-30T14:32:10
2014-12-30T17:33:06
Python
UTF-8
C
false
false
373
c
__VERIFIER_nondet_double_named.c
#include "symbiotic-size_t.h" extern void klee_make_symbolic(void *, size_t, const char *); double __VERIFIER_nondet_double_named(const char *name) { _Bool nan_choice; klee_make_symbolic(&nan_choice, sizeof(_Bool), "nondet_double_is_nan"); if (nan_choice) { return ((double)0.0)/0.0; } else { double x; klee_make_symbolic(&x, sizeof(x), name); return x; } }
37924bb7b2e74304f9183f00b118be2f53434cb6
d6d6893f488941edfc5d244221583c63572d9d5f
/code/graphics/opengl/gropengldraw.h
5ca9d59c677bd0132d76886118dd1c403fd84729
[ "Unlicense" ]
permissive
scp-fs2open/fs2open.github.com
4170cc58b92577b41308a9e6343dd3fc3fb7a074
865f7e725c7a4d9c0b209a49ed0cbd8dc45e8ae7
refs/heads/master
2023-08-29T11:29:27.822804
2023-08-27T20:33:28
2023-08-27T20:33:28
7,700,081
382
311
NOASSERTION
2023-09-14T15:49:22
2013-01-19T06:10:53
C++
UTF-8
C
false
false
4,976
h
gropengldraw.h
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ #ifndef GR_OPENGLDRAW_H #define GR_OPENGLDRAW_H #include "graphics/2d.h" #include "gropenglstate.h" #include "gropenglshader.h" #include "graphics/shadows.h" #include <glad/glad.h> extern GLuint Scene_framebuffer; extern GLuint Scene_framebuffer_ms; extern GLuint Scene_ldr_texture; extern GLuint Scene_color_texture; extern GLuint Scene_position_texture; extern GLuint Scene_normal_texture; extern GLuint Scene_specular_texture; extern GLuint Scene_emissive_texture; extern GLuint Scene_color_texture_ms; extern GLuint Scene_position_texture_ms; extern GLuint Scene_normal_texture_ms; extern GLuint Scene_specular_texture_ms; extern GLuint Scene_emissive_texture_ms; extern GLuint Scene_luminance_texture; extern GLuint Scene_effect_texture; extern GLuint Scene_composite_texture; extern GLuint Scene_depth_texture; extern GLuint Scene_depth_texture_ms; extern GLuint Cockpit_depth_texture; extern GLuint Scene_stencil_buffer; void gr_opengl_update_distortion(); void gr_opengl_sphere(material *material_def, float rad); void gr_opengl_shadow_map_start(matrix4 *shadow_view_matrix, const matrix *light_orient, vec3d* eye_pos); void gr_opengl_shadow_map_end(); void gr_opengl_render_shield_impact(shield_material* material_info, primitive_type prim_type, vertex_layout* layout, gr_buffer_handle buffer_handle, int n_verts); void opengl_setup_scene_textures(); void opengl_scene_texture_shutdown(); void gr_opengl_scene_texture_begin(); void gr_opengl_scene_texture_end(); void gr_opengl_copy_effect_texture(); void opengl_render_primitives(primitive_type prim_type, vertex_layout* layout, int n_verts, gr_buffer_handle buffer_handle, size_t vert_offset, size_t byte_offset); void opengl_render_primitives_immediate(primitive_type prim_type, vertex_layout* layout, int n_verts, void* data, int size); void gr_opengl_render_primitives(material* material_info, primitive_type prim_type, vertex_layout* layout, int offset, int n_verts, gr_buffer_handle buffer_handle, size_t buffer_offset); void gr_opengl_render_primitives_particle(particle_material* material_info, primitive_type prim_type, vertex_layout* layout, int offset, int n_verts, gr_buffer_handle buffer_handle); void gr_opengl_render_primitives_batched(batched_bitmap_material* material_info, primitive_type prim_type, vertex_layout* layout, int offset, int n_verts, gr_buffer_handle buffer_handle); void gr_opengl_render_primitives_distortion(distortion_material* material_info, primitive_type prim_type, vertex_layout* layout, int offset, int n_verts, gr_buffer_handle buffer_handle); void gr_opengl_render_movie(movie_material* material_info, primitive_type prim_type, vertex_layout* layout, int n_verts, gr_buffer_handle buffer, size_t buffer_offset); void gr_opengl_render_nanovg(nanovg_material* material_info, primitive_type prim_type, vertex_layout* layout, int offset, int n_verts, gr_buffer_handle buffer_handle); void gr_opengl_render_decals(decal_material* material_info, primitive_type prim_type, vertex_layout* layout, int num_elements, const indexed_vertex_source& binding); void gr_opengl_render_rocket_primitives(interface_material* material_info, primitive_type prim_type, vertex_layout* layout, int n_indices, gr_buffer_handle vertex_buffer, gr_buffer_handle index_buffer); void opengl_draw_textured_quad(GLfloat x1, GLfloat y1, GLfloat u1, GLfloat v1, GLfloat x2, GLfloat y2, GLfloat u2, GLfloat v2); /** * @brief Draw "something" so that the entire screen is covered and the corners use the UV values that are provided. * * @details This actually draws a a single oversized triangle that covers the screen in such a way so that the provided * UV values are generated by the GPU in the corners of the screen. This is better than drawing two triangles since then * the diagonal would be shaded differently for the two triangles causing visual differences. * * @param u1 The U value of the lower left corner. * @param v1 The V value of the lower left corner. * @param u2 The U value of the upper right corner. * @param v2 The V value of the upper right corner. */ void opengl_draw_full_screen_textured(GLfloat u1, GLfloat v1, GLfloat u2, GLfloat v2); inline GLenum opengl_primitive_type(primitive_type prim_type); void gr_opengl_start_decal_pass(); void gr_opengl_stop_decal_pass(); void gr_opengl_calculate_irrmap(); extern int Scene_texture_initialized; extern GLuint Scene_color_texture; extern GLuint Scene_ldr_texture; extern GLuint Scene_luminance_texture; extern GLuint Scene_effect_texture; extern int Scene_texture_width; extern int Scene_texture_height; extern float Scene_texture_u_scale; extern float Scene_texture_v_scale; #endif // !GR_OPENGLDRAW_H
f38eb45373cf58200bbe1b05893753db328ed7cb
8ac9de6e6f9619eac09d8998ca5251f57a808012
/runtime/gen/runtime/type.h
e972ef8ffe11f678d41fbd9f310107d729557428
[ "AFL-3.0" ]
permissive
fanx-dev/fanx
1e1f04c4d9f967e34638e8abd88b74d767adf8bf
506dcc0f793e655a0a1e3f846bf8803301b17e96
refs/heads/master
2023-01-30T04:35:11.607402
2023-01-14T07:55:02
2023-01-14T07:55:02
131,579,289
172
12
null
null
null
null
UTF-8
C
false
false
807
h
type.h
// // Type.h // fcode // // Created by yangjiandong on 15/8/2. // Copyright (c) 2015年 yangjiandong. All rights reserved. // #ifndef __fcode__Type__ #define __fcode__Type__ #include <inttypes.h> #include "util/miss.h" #include "fni_ext.h" #ifdef __cplusplus extern "C" { #endif //void fr_VTable_init(fr_Env env, fr_Type type); bool fr_isClass(fr_Env env, fr_Obj obj, fr_Type type); fr_Type fr_getClass(fr_Env env, fr_Obj obj); void **fr_getInterfaceVTable(fr_Env env, fr_Obj obj, fr_Type itype); void fr_registerClass(fr_Env env, const char *pod, const char *clz, fr_Type type); //fr_Type fr_findClass(fr_Env env, const char *pod, const char *clz); void fr_registerPod(fr_Env env, struct fr_Pod_ *pod); #ifdef __cplusplus }//extern "C" { #endif #endif /* defined(__fcode__Type__) */
65ec54b7006a29fec8dc5571146e3338e7a81da8
342983ac4a4ddc27ffa33d48eae37bdd6237c618
/common/scan.c
177cdb8cc951bb37796c864d01280e34dfcc0559
[ "MIT" ]
permissive
chenhaiq/mt7610u_wifi_sta_v3002_dpo_20130916
9bbba99ecc921ce54e79038495a79b2df848956b
092d218723b8d50816b3bfb377675f5658a8ac4a
refs/heads/master
2022-08-10T15:47:25.607687
2017-08-18T16:37:02
2021-01-05T05:29:30
30,166,779
156
87
MIT
2022-07-27T03:52:36
2015-02-02T01:50:46
C
UTF-8
C
false
false
15,819
c
scan.c
/* ************************************************************************* * Ralink Tech Inc. * 5F., No.36, Taiyuan St., Jhubei City, * Hsinchu County 302, * Taiwan, R.O.C. * * (c) Copyright 2002-2010, Ralink Technology, Inc. * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * *************************************************************************/ #include "rt_config.h" #ifdef SCAN_SUPPORT static INT scan_ch_restore(RTMP_ADAPTER *pAd, UCHAR OpMode) { #ifdef CONFIG_STA_SUPPORT USHORT Status; #endif /* CONFIG_STA_SUPPORT */ INT bw, ch; //printk("pAd->hw_cfg.bbp_bw = %d\n", pAd->hw_cfg.bbp_bw); if (pAd->CommonCfg.BBPCurrentBW != pAd->hw_cfg.bbp_bw) { rtmp_bbp_set_bw(pAd, pAd->hw_cfg.bbp_bw); AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE); AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel); ch = pAd->CommonCfg.CentralChannel; } else { AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE); AsicLockChannel(pAd, pAd->CommonCfg.Channel); ch = pAd->CommonCfg.Channel; } switch(pAd->CommonCfg.BBPCurrentBW) { case BW_80: bw = 80; break; case BW_40: bw = 40; break; case BW_10: bw = 10; break; case BW_20: default: bw =20; break; } DBGPRINT(RT_DEBUG_TRACE, ("SYNC - End of SCAN, restore to %dMHz channel %d, Total BSS[%02d]\n", bw, ch, pAd->ScanTab.BssNr)); #ifdef CONFIG_STA_SUPPORT if (OpMode == OPMODE_STA) { /* If all peer Ad-hoc clients leave, driver would do LinkDown and LinkUp. In LinkUp, CommonCfg.Ssid would copy SSID from MlmeAux. To prevent SSID is zero or wrong in Beacon, need to recover MlmeAux.SSID here. */ if (ADHOC_ON(pAd)) { NdisZeroMemory(pAd->MlmeAux.Ssid, MAX_LEN_OF_SSID); pAd->MlmeAux.SsidLen = pAd->CommonCfg.SsidLen; NdisMoveMemory(pAd->MlmeAux.Ssid, pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen); } /* To prevent data lost. Send an NULL data with turned PSM bit on to current associated AP before SCAN progress. Now, we need to send an NULL data with turned PSM bit off to AP, when scan progress done */ if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) && (INFRA_ON(pAd))) { RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) ? TRUE:FALSE), pAd->CommonCfg.bAPSDForcePowerSave ? PWR_SAVE : pAd->StaCfg.Psm); DBGPRINT(RT_DEBUG_TRACE, ("%s -- Send null frame\n", __FUNCTION__)); } /* keep the latest scan channel, could be 0 for scan complete, or other channel*/ pAd->StaCfg.LastScanChannel = pAd->MlmeAux.Channel; pAd->StaCfg.ScanChannelCnt = 0; /* Suspend scanning and Resume TxData for Fast Scanning*/ if ((pAd->MlmeAux.Channel != 0) && (pAd->StaCfg.bImprovedScan)) /* it is scan pending*/ { pAd->Mlme.SyncMachine.CurrState = SCAN_PENDING; Status = MLME_SUCCESS; DBGPRINT(RT_DEBUG_WARN, ("bFastRoamingScan ~~~ Get back to send data ~~~\n")); RTMPResumeMsduTransmission(pAd); } else { pAd->StaCfg.BssNr = pAd->ScanTab.BssNr; pAd->StaCfg.bImprovedScan = FALSE; pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE; Status = MLME_SUCCESS; MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status, 0); RTMP_MLME_HANDLER(pAd); } #ifdef LINUX #ifdef RT_CFG80211_SUPPORT RTEnqueueInternalCmd(pAd, CMDTHREAD_SCAN_END, NULL, 0); #endif /* RT_CFG80211_SUPPORT */ #endif /* LINUX */ } #endif /* CONFIG_STA_SUPPORT */ return TRUE; } static INT scan_active(RTMP_ADAPTER *pAd, UCHAR OpMode, UCHAR ScanType) { UCHAR *frm_buf = NULL; HEADER_802_11 Hdr80211; ULONG FrameLen = 0; UCHAR SsidLen = 0; #ifdef CONFIG_STA_SUPPORT USHORT Status; #endif /* CONFIG_STA_SUPPORT */ if (MlmeAllocateMemory(pAd, &frm_buf) != NDIS_STATUS_SUCCESS) { DBGPRINT(RT_DEBUG_TRACE, ("SYNC - ScanNextChannel() allocate memory fail\n")); #ifdef CONFIG_STA_SUPPORT if (OpMode == OPMODE_STA) { pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE; Status = MLME_FAIL_NO_RESOURCE; MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status, 0); } #endif /* CONFIG_STA_SUPPORT */ return FALSE; } #ifdef DOT11_N_SUPPORT #ifdef DOT11N_DRAFT3 if (ScanType == SCAN_2040_BSS_COEXIST) { DBGPRINT(RT_DEBUG_INFO, ("SYNC - SCAN_2040_BSS_COEXIST !! Prepare to send Probe Request\n")); } #endif /* DOT11N_DRAFT3 */ #endif /* DOT11_N_SUPPORT */ /* There is no need to send broadcast probe request if active scan is in effect.*/ SsidLen = 0; if ((ScanType == SCAN_ACTIVE) || (ScanType == FAST_SCAN_ACTIVE) ) SsidLen = pAd->MlmeAux.SsidLen; { #ifdef CONFIG_STA_SUPPORT /*IF_DEV_CONFIG_OPMODE_ON_STA(pAd) */ if (OpMode == OPMODE_STA) { MgtMacHeaderInit(pAd, &Hdr80211, SUBTYPE_PROBE_REQ, 0, BROADCAST_ADDR, BROADCAST_ADDR); } #endif /* CONFIG_STA_SUPPORT */ MakeOutgoingFrame(frm_buf, &FrameLen, sizeof(HEADER_802_11), &Hdr80211, 1, &SsidIe, 1, &SsidLen, SsidLen, pAd->MlmeAux.Ssid, 1, &SupRateIe, 1, &pAd->CommonCfg.SupRateLen, pAd->CommonCfg.SupRateLen, pAd->CommonCfg.SupRate, END_OF_ARGS); if (pAd->CommonCfg.ExtRateLen) { ULONG Tmp; MakeOutgoingFrame(frm_buf + FrameLen, &Tmp, 1, &ExtRateIe, 1, &pAd->CommonCfg.ExtRateLen, pAd->CommonCfg.ExtRateLen, pAd->CommonCfg.ExtRate, END_OF_ARGS); FrameLen += Tmp; } } #ifdef DOT11_N_SUPPORT if (WMODE_CAP_N(pAd->CommonCfg.PhyMode)) { ULONG Tmp; UCHAR HtLen; UCHAR BROADCOM[4] = {0x0, 0x90, 0x4c, 0x33}; #ifdef RT_BIG_ENDIAN HT_CAPABILITY_IE HtCapabilityTmp; #endif if (pAd->bBroadComHT == TRUE) { HtLen = pAd->MlmeAux.HtCapabilityLen + 4; #ifdef RT_BIG_ENDIAN NdisMoveMemory(&HtCapabilityTmp, &pAd->MlmeAux.HtCapability, SIZE_HT_CAP_IE); *(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo)); #ifdef UNALIGNMENT_SUPPORT { EXT_HT_CAP_INFO extHtCapInfo; NdisMoveMemory((PUCHAR)(&extHtCapInfo), (PUCHAR)(&HtCapabilityTmp.ExtHtCapInfo), sizeof(EXT_HT_CAP_INFO)); *(USHORT *)(&extHtCapInfo) = cpu2le16(*(USHORT *)(&extHtCapInfo)); NdisMoveMemory((PUCHAR)(&HtCapabilityTmp.ExtHtCapInfo), (PUCHAR)(&extHtCapInfo), sizeof(EXT_HT_CAP_INFO)); } #else *(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = cpu2le16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo)); #endif /* UNALIGNMENT_SUPPORT */ MakeOutgoingFrame(frm_buf + FrameLen, &Tmp, 1, &WpaIe, 1, &HtLen, 4, &BROADCOM[0], pAd->MlmeAux.HtCapabilityLen, &HtCapabilityTmp, END_OF_ARGS); #else MakeOutgoingFrame(frm_buf + FrameLen, &Tmp, 1, &WpaIe, 1, &HtLen, 4, &BROADCOM[0], pAd->MlmeAux.HtCapabilityLen, &pAd->MlmeAux.HtCapability, END_OF_ARGS); #endif /* RT_BIG_ENDIAN */ } else { HtLen = sizeof(HT_CAPABILITY_IE); #ifdef RT_BIG_ENDIAN NdisMoveMemory(&HtCapabilityTmp, &pAd->CommonCfg.HtCapability, SIZE_HT_CAP_IE); *(USHORT *)(&HtCapabilityTmp.HtCapInfo) = SWAP16(*(USHORT *)(&HtCapabilityTmp.HtCapInfo)); #ifdef UNALIGNMENT_SUPPORT { EXT_HT_CAP_INFO extHtCapInfo; NdisMoveMemory((PUCHAR)(&extHtCapInfo), (PUCHAR)(&HtCapabilityTmp.ExtHtCapInfo), sizeof(EXT_HT_CAP_INFO)); *(USHORT *)(&extHtCapInfo) = cpu2le16(*(USHORT *)(&extHtCapInfo)); NdisMoveMemory((PUCHAR)(&HtCapabilityTmp.ExtHtCapInfo), (PUCHAR)(&extHtCapInfo), sizeof(EXT_HT_CAP_INFO)); } #else *(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo) = cpu2le16(*(USHORT *)(&HtCapabilityTmp.ExtHtCapInfo)); #endif /* UNALIGNMENT_SUPPORT */ MakeOutgoingFrame(frm_buf + FrameLen, &Tmp, 1, &HtCapIe, 1, &HtLen, HtLen, &HtCapabilityTmp, END_OF_ARGS); #else MakeOutgoingFrame(frm_buf + FrameLen, &Tmp, 1, &HtCapIe, 1, &HtLen, HtLen, &pAd->CommonCfg.HtCapability, END_OF_ARGS); #endif /* RT_BIG_ENDIAN */ } FrameLen += Tmp; #ifdef DOT11N_DRAFT3 if ((pAd->MlmeAux.Channel <= 14) && (pAd->CommonCfg.bBssCoexEnable == TRUE)) { ULONG Tmp; HtLen = 1; MakeOutgoingFrame(frm_buf + FrameLen, &Tmp, 1, &ExtHtCapIe, 1, &HtLen, 1, &pAd->CommonCfg.BSSCoexist2040.word, END_OF_ARGS); FrameLen += Tmp; } #endif /* DOT11N_DRAFT3 */ } #endif /* DOT11_N_SUPPORT */ #ifdef DOT11_VHT_AC if (WMODE_CAP_AC(pAd->CommonCfg.PhyMode) && (pAd->MlmeAux.Channel > 14)) { FrameLen += build_vht_ies(pAd, (UCHAR *)(frm_buf + FrameLen), SUBTYPE_PROBE_REQ); } #endif /* DOT11_VHT_AC */ #ifdef WPA_SUPPLICANT_SUPPORT if ((OpMode == OPMODE_STA) && (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE) && (pAd->StaCfg.WpsProbeReqIeLen != 0)) { ULONG WpsTmpLen = 0; MakeOutgoingFrame(frm_buf + FrameLen, &WpsTmpLen, pAd->StaCfg.WpsProbeReqIeLen, pAd->StaCfg.pWpsProbeReqIe, END_OF_ARGS); FrameLen += WpsTmpLen; } #endif /* WPA_SUPPLICANT_SUPPORT */ MiniportMMRequest(pAd, 0, frm_buf, FrameLen); #ifdef CONFIG_STA_SUPPORT if (OpMode == OPMODE_STA) { /* To prevent data lost. Send an NULL data with turned PSM bit on to current associated AP when SCAN in the channel where associated AP located. */ if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) && (INFRA_ON(pAd)) && (pAd->CommonCfg.Channel == pAd->MlmeAux.Channel)) { RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) ? TRUE:FALSE), PWR_SAVE); DBGPRINT(RT_DEBUG_TRACE, ("ScanNextChannel():Send PWA NullData frame to notify the associated AP!\n")); } } #endif /* CONFIG_STA_SUPPORT */ MlmeFreeMemory(pAd, frm_buf); return TRUE; } /* ========================================================================== Description: Scan next channel ========================================================================== */ VOID ScanNextChannel( IN PRTMP_ADAPTER pAd, IN UCHAR OpMode) { UCHAR ScanType = pAd->MlmeAux.ScanType; UINT ScanTimeIn5gChannel = SHORT_CHANNEL_TIME; BOOLEAN ScanPending = FALSE; RALINK_TIMER_STRUCT *sc_timer; UINT stay_time = 0; UCHAR ImprovedScan_MaxScanChannelCnt; #ifdef RALINK_ATE /* Nothing to do in ATE mode. */ if (ATE_ON(pAd)) return; #endif /* RALINK_ATE */ #ifdef CONFIG_STA_SUPPORT IF_DEV_CONFIG_OPMODE_ON_STA(pAd) { if (MONITOR_ON(pAd)) return; } #ifdef WIFI_P2P_CONCURRENT_FAST_SCAN ImprovedScan_MaxScanChannelCnt = 3; #else ImprovedScan_MaxScanChannelCnt = 7; #endif /* WIFI_P2P_CONCURRENT_FAST_SCAN */ ScanPending = ((pAd->StaCfg.bImprovedScan) && (pAd->StaCfg.ScanChannelCnt>=ImprovedScan_MaxScanChannelCnt)); #endif /* CONFIG_STA_SUPPORT */ if ((pAd->MlmeAux.Channel == 0) || ScanPending) { scan_ch_restore(pAd, OpMode); } #ifdef RTMP_MAC_USB #ifdef CONFIG_STA_SUPPORT else if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST) && (OpMode == OPMODE_STA)) { pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE; MlmeCntlConfirm(pAd, MT2_SCAN_CONF, MLME_FAIL_NO_RESOURCE); } #endif /* CONFIG_STA_SUPPORT */ #endif /* RTMP_MAC_USB */ else { #ifdef CONFIG_STA_SUPPORT if (OpMode == OPMODE_STA) { /* BBP and RF are not accessible in PS mode, we has to wake them up first*/ if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE)) AsicForceWakeup(pAd, TRUE); /* leave PSM during scanning. otherwise we may lost ProbeRsp & BEACON*/ if (pAd->StaCfg.Psm == PWR_SAVE) RTMP_SET_PSM_BIT(pAd, PWR_ACTIVE); } #endif /* CONFIG_STA_SUPPORT */ AsicSwitchChannel(pAd, pAd->MlmeAux.Channel, TRUE); AsicLockChannel(pAd, pAd->MlmeAux.Channel); #ifdef CONFIG_STA_SUPPORT if (OpMode == OPMODE_STA) { BOOLEAN bScanPassive = FALSE; if (pAd->MlmeAux.Channel > 14) { if ((pAd->CommonCfg.bIEEE80211H == 1) && RadarChannelCheck(pAd, pAd->MlmeAux.Channel)) bScanPassive = TRUE; } #ifdef CARRIER_DETECTION_SUPPORT if (pAd->CommonCfg.CarrierDetect.Enable == TRUE) bScanPassive = TRUE; #endif /* CARRIER_DETECTION_SUPPORT */ if (bScanPassive) { ScanType = SCAN_PASSIVE; ScanTimeIn5gChannel = MIN_CHANNEL_TIME; } } #endif /* CONFIG_STA_SUPPORT */ /* Check if channel if passive scan under current regulatory domain */ if (CHAN_PropertyCheck(pAd, pAd->MlmeAux.Channel, CHANNEL_PASSIVE_SCAN) == TRUE) ScanType = SCAN_PASSIVE; if (OpMode == OPMODE_AP) sc_timer = &pAd->MlmeAux.APScanTimer; else sc_timer = &pAd->MlmeAux.ScanTimer; /* We need to shorten active scan time in order for WZC connect issue */ /* Chnage the channel scan time for CISCO stuff based on its IAPP announcement */ if (ScanType == FAST_SCAN_ACTIVE) stay_time = FAST_ACTIVE_SCAN_TIME; else /* must be SCAN_PASSIVE or SCAN_ACTIVE*/ { #ifdef CONFIG_STA_SUPPORT pAd->StaCfg.ScanChannelCnt++; #endif /* CONFIG_STA_SUPPORT */ if (WMODE_CAP_2G(pAd->CommonCfg.PhyMode) && WMODE_CAP_5G(pAd->CommonCfg.PhyMode)) { if (pAd->MlmeAux.Channel > 14) stay_time = ScanTimeIn5gChannel; else stay_time = MIN_CHANNEL_TIME; } #ifdef WIFI_P2P_CONCURRENT_FAST_SCAN /* If this is not PASSIVE scan && Fast scan is enabled, we shorten the chanenl dwell time */ else if (ScanType != SCAN_PASSIVE && pAd->StaCfg.bImprovedScan) stay_time = FAST_ACTIVE_SCAN_TIME; #endif /* WIFI_P2P_CONCURRENT_FAST_SCAN */ else stay_time = MAX_CHANNEL_TIME; } RTMPSetTimer(sc_timer, stay_time); if (SCAN_MODE_ACT(ScanType)) { if (scan_active(pAd, OpMode, ScanType) == FALSE) return; } /* For SCAN_CISCO_PASSIVE, do nothing and silently wait for beacon or other probe reponse*/ #ifdef CONFIG_STA_SUPPORT if (OpMode == OPMODE_STA) pAd->Mlme.SyncMachine.CurrState = SCAN_LISTEN; #endif /* CONFIG_STA_SUPPORT */ } } BOOLEAN ScanRunning( IN PRTMP_ADAPTER pAd) { BOOLEAN rv = FALSE; #ifdef CONFIG_STA_SUPPORT IF_DEV_CONFIG_OPMODE_ON_STA(pAd) { if ((pAd->Mlme.SyncMachine.CurrState == SCAN_LISTEN) || (pAd->Mlme.SyncMachine.CurrState == SCAN_PENDING)) rv = TRUE; } #endif /* CONFIG_STA_SUPPORT */ return rv; } #endif /* SCAN_SUPPORT */