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
f8685a6351ad7b9c1733ee475c73f59d7d8c21aa
d61b532db0d3e08818338cfaac530a1ced1ffe3b
/util/topgen/pattern.h
863fb05570edb5fa111d17f0d9d2a4c44b2c005a
[ "LicenseRef-scancode-other-permissive" ]
permissive
davidgiven/ack
61049c7a8e95ff61a77b1edd3c22bb290720e276
db5a32c68c4a60ca26a3927a799ea662b5b2b0e5
refs/heads/default
2023-08-29T07:33:12.771205
2023-07-08T20:17:27
2023-07-08T20:17:27
37,686,316
376
74
NOASSERTION
2023-07-08T20:17:28
2015-06-18T21:33:42
C
UTF-8
C
false
false
580
h
pattern.h
/* * pattern.h * * Created on: 2018-11-25 * Author: carl */ #ifndef __PATTERN_H_INCLUDED__ #define __PATTERN_H_INCLUDED__ /* * Just add a pattern to the list. * "str" is the constraint, "l" is the line number, * "np" is the number of instructions in the pattern, * "nr" is the number of instructions in the replacement * Space is allocated in chunks of 50 */ void addpattern(char* str,int l,int np,int nr); /* * Prints the pattern_descr table and generates the routine * "check_constraint" */ void printpatterns(void); #endif /* __PATTERN_H_INCLUDED__ */
8575550e0d41b9810574fa1d6612288d37f82d11
8e56b05b32a978eb170e01409a7aaaa1fc755979
/bin/utest/fork.c
c821f2f3deb79278a91fca3563b65ddf3fccbb00
[]
permissive
cahirwpz/mimiker
d71f37c2c6efc58a0026e8e4cfcd676d85ef7445
5343231aeeeb0d16b2419f84405f52981dc51c07
refs/heads/master
2023-09-01T20:20:07.256932
2023-08-30T18:36:27
2023-08-30T18:36:27
46,346,617
278
67
BSD-3-Clause
2023-09-14T16:57:32
2015-11-17T12:46:47
C
UTF-8
C
false
false
1,311
c
fork.c
#include "utest.h" #include <sched.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> TEST_ADD(fork_wait, 0) { pid_t pid = xfork(); if (pid == 0) { debug("This is child, my pid is %d!", getpid()); exit(42); } debug("This is parent, my pid is %d, I was told child is %d!", getpid(), pid); wait_child_exited(pid, 42); return 0; } static volatile int done = 0; static void sigchld_handler(int signo) { debug("SIGCHLD handler!"); int n = 0; while ((n = waitpid(-1, NULL, WNOHANG)) > 0) { debug("Reaped a child."); done = 1; } } TEST_ADD(fork_signal, 0) { xsignal(SIGCHLD, sigchld_handler); sigset_t mask, saved; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); xsigprocmask(SIG_BLOCK, &mask, &saved); pid_t n = xfork(); if (n == 0) exit(0); /* Wait for the child to get reaped by signal handler. */ while (!done) sigsuspend(&saved); xsigprocmask(SIG_UNBLOCK, &mask, NULL); xsignal(SIGCHLD, SIG_DFL); return 0; } TEST_ADD(fork_sigchld_ignored, 0) { /* Please auto-reap my children. */ xsignal(SIGCHLD, SIG_IGN); pid_t n = xfork(); if (n == 0) exit(0); /* waitpid() should fail, since the child reaps itself. */ syscall_fail(waitpid(-1, NULL, 0), ECHILD); return 0; }
ee44c6b24f88f14d7bbc588beb804a5afa187042
f9e7d65cb784c01a0200145ba8d289afe41d4a56
/include/btle_hci2.h
0b30a0dc48824267709f0530bd53bc480a2c9dd2
[ "BSD-3-Clause" ]
permissive
FrameworkComputer/EmbeddedController
ad7086769e87d0a4179eae96a7c9ff5e383ff54e
f6d6b927eed71550d3475411cfc3e59abe5cef2a
refs/heads/hx20-hx30
2023-08-08T20:45:10.621169
2023-05-26T07:03:59
2023-05-26T07:03:59
447,021,040
846
48
BSD-3-Clause
2023-05-26T07:04:59
2022-01-12T00:11:14
C
UTF-8
C
false
false
1,501
h
btle_hci2.h
/* Copyright 2016 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* * Copied from NewBlue hci.c with permission from Dmitry Grinberg, the original * author. */ #include "btle_hci_int.h" struct hciCmdHdr { uint16_t opcode; uint8_t paramLen; } __packed; #define CMD_MAKE_OPCODE(ogf, ocf) ((((uint16_t)((ogf) & 0x3f)) << 10) | ((ocf) & 0x03ff)) #define CMD_GET_OGF(opcode) (((opcode) >> 10) & 0x3f) #define CMD_GET_OCF(opcode) ((opcode) & 0x03ff) struct hciAclHdr { uint16_t hdr; uint16_t len; } __packed; #define ACL_HDR_MASK_CONN_ID 0x0FFF #define ACL_HDR_MASK_PB 0x3000 #define ACL_HDR_MASK_BC 0xC000 #define ACL_HDR_PB_FIRST_NONAUTO 0x0000 #define ACL_HDR_PB_CONTINUED 0x1000 #define ACL_HDR_PB_FIRST_AUTO 0x2000 #define ACL_HDR_PB_COMPLETE 0x3000 struct hciScoHdr { uint16_t hdr; uint8_t len; } __packed; #define SCO_HDR_MASK_CONN_ID 0x0FFF #define SCO_HDR_MASK_STATUS 0x3000 #define SCO_STATUS_ALL_OK 0x0000 #define SCO_STATUS_UNKNOWN 0x1000 #define SCO_STATUS_NO_DATA 0x2000 #define SCO_STATUS_SOME_DATA 0x3000 struct hciEvtHdr { uint8_t code; uint8_t len; } __packed; void hci_cmd(uint8_t *hciCmdbuf); void hci_acl_to_host(uint8_t *data, uint16_t hdr, uint16_t len); void hci_acl_from_host(uint8_t *hciAclbuf); void hci_event(uint8_t event_code, uint8_t len, uint8_t *params);
10de89e1a0a9d5e81c3e9b6e0708ce7e053fd828
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/dev/i2c/am2315var.h
c248a348c7a15e26cf071e47648f642d5692d6f5
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
1,478
h
am2315var.h
/* $NetBSD: am2315var.h,v 1.2 2017/12/29 02:20:47 christos Exp $ */ /* * Copyright (c) 2017 Brad Spencer <brad@anduin.eldar.org> * * 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. * * 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 _DEV_I2C_AM2315VAR_H_ #define _DEV_I2C_AM2315VAR_H_ #include <sys/time.h> #define AM2315_NUM_SENSORS 2 #define AM2315_HUMIDITY_SENSOR 0 #define AM2315_TEMP_SENSOR 1 struct am2315_sc { int sc_am2315debug; device_t sc_dev; i2c_tag_t sc_tag; i2c_addr_t sc_addr; kmutex_t sc_mutex; kmutex_t sc_waitmutex; kcondvar_t sc_condwait; int sc_numsensors; struct sysmon_envsys *sc_sme; envsys_data_t sc_sensors[AM2315_NUM_SENSORS]; struct sysctllog *sc_am2315log; int sc_readcount; int sc_readticks; }; struct am2315_sensor { const char *desc; enum envsys_units type; }; #endif
0d89a03b981c123975a34d56b033e0a3df445636
9907672fcd81ab73ac63b2a83422a82bf31eadde
/atcoder/abc/tyama_atcoderABC015C.c
e408b930da6c437c9008b448ec9feaa40ae65034
[ "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
348
c
tyama_atcoderABC015C.c
#include <stdio.h> #include <stdbool.h> int A[5][5],N,K; bool dfs(int d,int x){ if(d&&!x)return false; if(d==N)return true; int i; for(i=0;i<K;i++)if(!dfs(d+1,x^A[d][i]))return false; return true; } int main(){ int i,j; scanf("%d%d",&N,&K); for(i=0;i<N;i++)for(j=0;j<K;j++)scanf("%d",A[i]+j); puts(dfs(0,0)?"Nothing":"Found"); return 0; }
99d64f50341310614640be33cae63abd49fe2a3f
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/staging/bcm/Macros.h
dc01e3016d4fc7e5f5db734f5ae81db324e85a96
[ "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
9,595
h
Macros.h
/************************************* * Macros.h **************************************/ #ifndef __MACROS_H__ #define __MACROS_H__ #define TX_TIMER_PERIOD 10 /*10 msec*/ #define MAX_CLASSIFIERS 100 #define MAX_TARGET_DSX_BUFFERS 24 #define MAX_CNTRL_PKTS 100 #define MAX_DATA_PKTS 200 #define MAX_ETH_SIZE 1536 #define MAX_CNTL_PKT_SIZE 2048 #define MTU_SIZE 1400 #define TX_QLEN 5 #define MAC_ADDR_REGISTER 0xbf60d000 /* Quality of Service */ #define NO_OF_QUEUES 17 #define HiPriority (NO_OF_QUEUES-1) #define LowPriority 0 #define BE 2 #define rtPS 4 #define ERTPS 5 #define UGS 6 #define BE_BUCKET_SIZE (1024*1024*100) /* 32kb */ #define rtPS_BUCKET_SIZE (1024*1024*100) /* 8kb */ #define MAX_ALLOWED_RATE (1024*1024*100) #define TX_PACKET_THRESHOLD 10 #define XSECONDS (1*HZ) #define DSC_ACTIVATE_REQUEST 248 #define QUEUE_DEPTH_OFFSET 0x1fc01000 #define MAX_DEVICE_DESC_SIZE 2040 #define MAX_CTRL_QUEUE_LEN 100 #define MAX_APP_QUEUE_LEN 200 #define MAX_LATENCY_ALLOWED 0xFFFFFFFF #define DEFAULT_UG_INTERVAL 250 #define DEFAULT_UGI_FACTOR 4 #define DEFAULT_PERSFCOUNT 60 #define MAX_CONNECTIONS 10 #define MAX_CLASS_NAME_LENGTH 32 #define ETH_LENGTH_OF_ADDRESS 6 #define MAX_MULTICAST_ADDRESSES 32 #define IP_LENGTH_OF_ADDRESS 4 #define IP_PACKET_ONLY_MODE 0 #define ETH_PACKET_TUNNELING_MODE 1 /* Link Request */ #define SET_MAC_ADDRESS_REQUEST 0 #define SYNC_UP_REQUEST 1 #define SYNCED_UP 2 #define LINK_UP_REQUEST 3 #define LINK_CONNECTED 4 #define SYNC_UP_NOTIFICATION 2 #define LINK_UP_NOTIFICATION 4 #define LINK_NET_ENTRY 0x0002 #define HMC_STATUS 0x0004 #define LINK_UP_CONTROL_REQ 0x83 #define STATS_POINTER_REQ_STATUS 0x86 #define NETWORK_ENTRY_REQ_PAYLOAD 198 #define LINK_DOWN_REQ_PAYLOAD 226 #define SYNC_UP_REQ_PAYLOAD 228 #define STATISTICS_POINTER_REQ 237 #define LINK_UP_REQ_PAYLOAD 245 #define LINK_UP_ACK 246 #define STATS_MSG_SIZE 4 #define INDEX_TO_DATA 4 #define GO_TO_IDLE_MODE_PAYLOAD 210 #define COME_UP_FROM_IDLE_MODE_PAYLOAD 211 #define IDLE_MODE_SF_UPDATE_MSG 187 #define SKB_RESERVE_ETHERNET_HEADER 16 #define SKB_RESERVE_PHS_BYTES 32 #define IP_PACKET_ONLY_MODE 0 #define ETH_PACKET_TUNNELING_MODE 1 #define ETH_CS_802_3 1 #define ETH_CS_802_1Q_VLAN 3 #define IPV4_CS 1 #define IPV6_CS 2 #define ETH_CS_MASK 0x3f /** \brief Validity bit maps for TLVs in packet classification rule */ #define PKT_CLASSIFICATION_USER_PRIORITY_VALID 0 #define PKT_CLASSIFICATION_VLANID_VALID 1 #ifndef MIN #define MIN(_a, _b) ((_a) < (_b) ? (_a) : (_b)) #endif /*Leader related terms */ #define LEADER_STATUS 0x00 #define LEADER_STATUS_TCP_ACK 0x1 #define LEADER_SIZE sizeof(struct bcm_leader) #define MAC_ADDR_REQ_SIZE sizeof(struct bcm_packettosend) #define SS_INFO_REQ_SIZE sizeof(struct bcm_packettosend) #define CM_REQUEST_SIZE (LEADER_SIZE + sizeof(stLocalSFChangeRequest)) #define IDLE_REQ_SIZE sizeof(struct bcm_packettosend) #define MAX_TRANSFER_CTRL_BYTE_USB (2*1024) #define GET_MAILBOX1_REG_REQUEST 0x87 #define GET_MAILBOX1_REG_RESPONSE 0x67 #define VCID_CONTROL_PACKET 0x00 #define TRANSMIT_NETWORK_DATA 0x00 #define RECEIVED_NETWORK_DATA 0x20 #define CM_RESPONSES 0xA0 #define STATUS_RSP 0xA1 #define LINK_CONTROL_RESP 0xA2 #define IDLE_MODE_STATUS 0xA3 #define STATS_POINTER_RESP 0xA6 #define MGMT_MSG_INFO_SW_STATUS 0xA7 #define AUTH_SS_HOST_MSG 0xA8 #define CM_DSA_ACK_PAYLOAD 247 #define CM_DSC_ACK_PAYLOAD 248 #define CM_DSD_ACK_PAYLOAD 249 #define CM_DSDEACTVATE 250 #define TOTAL_MASKED_ADDRESS_IN_BYTES 32 #define MAC_REQ 0 #define LINK_RESP 1 #define RSSI_INDICATION 2 #define SS_INFO 4 #define STATISTICS_INFO 5 #define CM_INDICATION 6 #define PARAM_RESP 7 #define BUFFER_1K 1024 #define BUFFER_2K (BUFFER_1K*2) #define BUFFER_4K (BUFFER_2K*2) #define BUFFER_8K (BUFFER_4K*2) #define BUFFER_16K (BUFFER_8K*2) #define DOWNLINK_DIR 0 #define UPLINK_DIR 1 #define BCM_SIGNATURE "BECEEM" #define GPIO_OUTPUT_REGISTER 0x0F00003C #define BCM_GPIO_OUTPUT_SET_REG 0x0F000040 #define BCM_GPIO_OUTPUT_CLR_REG 0x0F000044 #define GPIO_MODE_REGISTER 0x0F000034 #define GPIO_PIN_STATE_REGISTER 0x0F000038 struct bcm_link_state { unsigned char ucLinkStatus; unsigned char bIdleMode; unsigned char bShutdownMode; }; enum enLinkStatus { WAIT_FOR_SYNC = 1, PHY_SYNC_ACHIVED = 2, LINKUP_IN_PROGRESS = 3, LINKUP_DONE = 4, DREG_RECEIVED = 5, LINK_STATUS_RESET_RECEIVED = 6, PERIODIC_WAKE_UP_NOTIFICATION_FRM_FW = 7, LINK_SHUTDOWN_REQ_FROM_FIRMWARE = 8, COMPLETE_WAKE_UP_NOTIFICATION_FRM_FW = 9 }; enum bcm_phs_dsc_action { eAddPHSRule = 0, eSetPHSRule, eDeletePHSRule, eDeleteAllPHSRules }; #define CM_CONTROL_NEWDSX_MULTICLASSIFIER_REQ 0x89 /* Host to Mac */ #define CM_CONTROL_NEWDSX_MULTICLASSIFIER_RESP 0xA9 /* Mac to Host */ #define MASK_DISABLE_HEADER_SUPPRESSION 0x10 /* 0b000010000 */ #define MINIMUM_PENDING_DESCRIPTORS 5 #define SHUTDOWN_HOSTINITIATED_REQUESTPAYLOAD 0xCC #define SHUTDOWN_ACK_FROM_DRIVER 0x1 #define SHUTDOWN_NACK_FROM_DRIVER 0x2 #define LINK_SYNC_UP_SUBTYPE 0x0001 #define LINK_SYNC_DOWN_SUBTYPE 0x0001 #define CONT_MODE 1 #define SINGLE_DESCRIPTOR 1 #define DESCRIPTOR_LENGTH 0x30 #define FIRMWARE_DESCS_ADDRESS 0x1F100000 #define CLOCK_RESET_CNTRL_REG_1 0x0F00000C #define CLOCK_RESET_CNTRL_REG_2 0x0F000840 #define TX_DESCRIPTOR_HEAD_REGISTER 0x0F010034 #define RX_DESCRIPTOR_HEAD_REGISTER 0x0F010094 #define STATISTICS_BEGIN_ADDR 0xbf60f02c #define MAX_PENDING_CTRL_PACKET (MAX_CTRL_QUEUE_LEN-10) #define WIMAX_MAX_MTU (MTU_SIZE + ETH_HLEN) #define AUTO_LINKUP_ENABLE 0x2 #define AUTO_SYNC_DISABLE 0x1 #define AUTO_FIRM_DOWNLOAD 0x1 #define SETTLE_DOWN_TIME 50 #define HOST_BUS_SUSPEND_BIT 16 #define IDLE_MESSAGE 0x81 #define MIPS_CLOCK_133MHz 1 #define TARGET_CAN_GO_TO_IDLE_MODE 2 #define TARGET_CAN_NOT_GO_TO_IDLE_MODE 3 #define IDLE_MODE_PAYLOAD_LENGTH 8 #define IP_HEADER(Buffer) ((IPHeaderFormat *)(Buffer)) #define IPV4 4 #define IP_VERSION(byte) (((byte&0xF0)>>4)) #define SET_MAC_ADDRESS 193 #define SET_MAC_ADDRESS_RESPONSE 236 #define IDLE_MODE_WAKEUP_PATTERN 0xd0ea1d1e #define IDLE_MODE_WAKEUP_NOTIFIER_ADDRESS 0x1FC02FA8 #define IDLE_MODE_MAX_RETRY_COUNT 1000 #define CONFIG_BEGIN_ADDR 0xBF60B000 #define FIRMWARE_BEGIN_ADDR 0xBFC00000 #define INVALID_QUEUE_INDEX NO_OF_QUEUES #define INVALID_PID ((pid_t)-1) #define DDR_80_MHZ 0 #define DDR_100_MHZ 1 #define DDR_120_MHZ 2 /* Additional Frequency for T3LP */ #define DDR_133_MHZ 3 #define DDR_140_MHZ 4 /* Not Used (Reserved for future) */ #define DDR_160_MHZ 5 /* Additional Frequency for T3LP */ #define DDR_180_MHZ 6 /* Not Used (Reserved for future) */ #define DDR_200_MHZ 7 /* Not Used (Reserved for future) */ #define MIPS_200_MHZ 0 #define MIPS_160_MHZ 1 #define PLL_800_MHZ 0 #define PLL_266_MHZ 1 #define DEVICE_POWERSAVE_MODE_AS_MANUAL_CLOCK_GATING 0 #define DEVICE_POWERSAVE_MODE_AS_PMU_CLOCK_GATING 1 #define DEVICE_POWERSAVE_MODE_AS_PMU_SHUTDOWN 2 #define DEVICE_POWERSAVE_MODE_AS_RESERVED 3 #define DEVICE_POWERSAVE_MODE_AS_PROTOCOL_IDLE_MODE 4 #define EEPROM_REJECT_REG_1 0x0f003018 #define EEPROM_REJECT_REG_2 0x0f00301c #define EEPROM_REJECT_REG_3 0x0f003008 #define EEPROM_REJECT_REG_4 0x0f003020 #define EEPROM_REJECT_MASK 0x0fffffff #define VSG_MODE 0x3 /* Idle Mode Related Registers */ #define DEBUG_INTERRUPT_GENERATOR_REGISTOR 0x0F00007C #define SW_ABORT_IDLEMODE_LOC 0x0FF01FFC #define SW_ABORT_IDLEMODE_PATTERN 0xd0ea1d1e #define DEVICE_INT_OUT_EP_REG0 0x0F011870 #define DEVICE_INT_OUT_EP_REG1 0x0F011874 #define BIN_FILE "/lib/firmware/macxvi200.bin" #define CFG_FILE "/lib/firmware/macxvi.cfg" #define SF_MAX_ALLOWED_PACKETS_TO_BACKUP 128 #define MIN_VAL(x, y) ((x) < (y) ? (x) : (y)) #define MAC_ADDRESS_SIZE 6 #define EEPROM_COMMAND_Q_REG 0x0F003018 #define EEPROM_READ_DATA_Q_REG 0x0F003020 #define CHIP_ID_REG 0x0F000000 #define GPIO_MODE_REG 0x0F000034 #define GPIO_OUTPUT_REG 0x0F00003C #define WIMAX_MAX_ALLOWED_RATE (1024*1024*50) #define T3 0xbece0300 #define TARGET_SFID_TXDESC_MAP_LOC 0xBFFFF400 #define RWM_READ 0 #define RWM_WRITE 1 #define T3LPB 0xbece3300 #define BCS220_2 0xbece3311 #define BCS220_2BC 0xBECE3310 #define BCS250_BC 0xbece3301 #define BCS220_3 0xbece3321 #define HPM_CONFIG_LDO145 0x0F000D54 #define HPM_CONFIG_MSW 0x0F000D58 #define T3B 0xbece0310 enum bcm_nvm_type { NVM_AUTODETECT = 0, NVM_EEPROM, NVM_FLASH, NVM_UNKNOWN }; enum bcm_pmu_modes { HYBRID_MODE_7C = 0, INTERNAL_MODE_6 = 1, HYBRID_MODE_6 = 2 }; #define MAX_RDM_WRM_RETIRES 1 enum eAbortPattern { ABORT_SHUTDOWN_MODE = 1, ABORT_IDLE_REG = 1, ABORT_IDLE_MODE = 2, ABORT_IDLE_SYNCDOWN = 3 }; /* Offsets used by driver in skb cb variable */ #define SKB_CB_CLASSIFICATION_OFFSET 0 #define SKB_CB_LATENCY_OFFSET 1 #define SKB_CB_TCPACK_OFFSET 2 #endif /* __MACROS_H__ */
fb7a09b60020f854dcc8b7cfe97f95889e7944da
aa3befea459382dc5c01c925653d54f435b3fb0f
/arch/arm/src/s32k1xx/s32k1xx_serial.h
4b05fff5a87665b3aa203cd3b76660fa330b4975
[ "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
6,363
h
s32k1xx_serial.h
/**************************************************************************** * arch/arm/src/s32k1xx/s32k1xx_serial.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ #ifndef __ARCH_ARM_SRC_S32K1XX_S32K1XX_SERIAL_H #define __ARCH_ARM_SRC_S32K1XX_S32K1XX_SERIAL_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include "arm_internal.h" #include "s32k1xx_config.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #if defined(CONFIG_S32K1XX_LPUART0) || defined(CONFIG_S32K1XX_LPUART1) || \ defined(CONFIG_S32K1XX_LPUART2) # define HAVE_UART 1 #endif /* Assume DMA is not used on the console UART */ #undef SERIAL_HAVE_CONSOLE_RXDMA #undef SERIAL_HAVE_CONSOLE_TXDMA #if !defined(HAVE_UART) || !defined(CONFIG_ARCH_DMA) # undef CONFIG_LPUART0_RXDMA # undef CONFIG_LPUART0_TXDMA # undef CONFIG_LPUART1_RXDMA # undef CONFIG_LPUART1_TXDMA # undef CONFIG_LPUART2_RXDMA # undef CONFIG_LPUART2_TXDMA #endif /* Disable the DMA configuration on all unused LPUARTs */ #ifndef CONFIG_S32K1XX_LPUART0 # undef CONFIG_LPUART0_RXDMA # undef CONFIG_LPUART0_TXDMA #endif #ifndef CONFIG_S32K1XX_LPUART1 # undef CONFIG_LPUART1_RXDMA # undef CONFIG_LPUART1_TXDMA #endif #ifndef CONFIG_S32K1XX_LPUART2 # undef CONFIG_LPUART2_RXDMA # undef CONFIG_LPUART2_TXDMA #endif /* Is RX DMA available on any (enabled) LPUART? */ #undef SERIAL_HAVE_RXDMA #if defined(CONFIG_LPUART0_RXDMA) || defined(CONFIG_LPUART1_RXDMA) || \ defined(CONFIG_LPUART2_RXDMA) # define SERIAL_HAVE_RXDMA 1 #endif /* Is TX DMA available on any (enabled) LPUART? */ #undef SERIAL_HAVE_TXDMA #if defined(CONFIG_LPUART0_TXDMA) || defined(CONFIG_LPUART1_TXDMA) || \ defined(CONFIG_LPUART2_TXDMA) # define SERIAL_HAVE_TXDMA 1 #endif /* Is RX DMA used on all (enabled) LPUARTs */ #define SERIAL_HAVE_ONLY_RXDMA 1 #if defined(CONFIG_S32K1XX_LPUART0) && !defined(CONFIG_LPUART0_RXDMA) # undef SERIAL_HAVE_ONLY_RXDMA #elif defined(CONFIG_S32K1XX_LPUART1) && !defined(CONFIG_LPUART1_RXDMA) # undef SERIAL_HAVE_ONLY_RXDMA #elif defined(CONFIG_S32K1XX_LPUART2) && !defined(CONFIG_LPUART2_RXDMA) # undef SERIAL_HAVE_ONLY_RXDMA #endif /* Is TX DMA used on all (enabled) LPUARTs */ #define SERIAL_HAVE_ONLY_TXDMA 1 #if defined(CONFIG_S32K1XX_LPUART0) && !defined(CONFIG_LPUART0_TXDMA) # undef SERIAL_HAVE_ONLY_TXDMA #elif defined(CONFIG_S32K1XX_LPUART1) && !defined(CONFIG_LPUART1_TXDMA) # undef SERIAL_HAVE_ONLY_TXDMA #elif defined(CONFIG_S32K1XX_LPUART2) && !defined(CONFIG_LPUART2_TXDMA) # undef SERIAL_HAVE_ONLY_TXDMA #endif #undef SERIAL_HAVE_ONLY_DMA #if defined(SERIAL_HAVE_ONLY_RXDMA) && defined(SERIAL_HAVE_ONLY_TXDMA) #define SERIAL_HAVE_ONLY_DMA #endif /* Verify that DMA has been enabled and the DMA channel has been defined. */ #if defined(SERIAL_HAVE_TXDMA) || defined(SERIAL_HAVE_RXDMA) # ifndef CONFIG_S32K1XX_EDMA # error S32K1XX LPUART receive or transmit DMA requires CONFIG_S32K1XX_EDMA # endif #endif #if defined(SERIAL_HAVE_RXDMA) /* Currently RS-485 support cannot be enabled when RXDMA is in use due to * lack of testing. */ # if (defined(CONFIG_LPUART0_RXDMA) && defined(CONFIG_LPUART0_RS485)) || \ (defined(CONFIG_LPUART1_RXDMA) && defined(CONFIG_LPUART1_RS485)) || \ (defined(CONFIG_LPUART2_RXDMA) && defined(CONFIG_LPUART2_RS485)) # error "RXDMA and RS-485 cannot be enabled at the same time for the same LPUART" # endif #endif /* SERIAL_HAVE_RXDMA */ /* Currently RS-485 support cannot be enabled when TXDMA is in use due to * lack of testing. */ #if (defined(CONFIG_LPUART0_TXDMA) && defined(CONFIG_LPUART0_RS485)) || \ (defined(CONFIG_LPUART1_TXDMA) && defined(CONFIG_LPUART1_RS485)) || \ (defined(CONFIG_LPUART2_TXDMA) && defined(CONFIG_LPUART2_RS485)) # error "TXDMA and RS-485 cannot be enabled at the same time for the same LPUART" #endif /**************************************************************************** * Public Types ****************************************************************************/ /**************************************************************************** * Inline Functions ****************************************************************************/ #ifndef __ASSEMBLY__ /**************************************************************************** * Public Data ****************************************************************************/ #undef EXTERN #if defined(__cplusplus) #define EXTERN extern "C" extern "C" { #else #define EXTERN extern #endif /**************************************************************************** * Public Function Prototypes ****************************************************************************/ /**************************************************************************** * Name: s32k1xx_earlyserialinit * * Description: * Performs the low level UART initialization early in debug so that the * serial console will be available during bootup. This must be called * before arm_serialinit. * ****************************************************************************/ #ifdef USE_EARLYSERIALINIT void s32k1xx_earlyserialinit(void); #endif #undef EXTERN #if defined(__cplusplus) } #endif #endif /* __ASSEMBLY__ */ #endif /* __ARCH_ARM_SRC_S32K1XX_S32K1XX_SERIAL_H */
5a560ea80e69d515bf62fe81269427e01e146f64
e1cddfd754d952134e72dfd03522c5ea4fb6008e
/src/plugins/lldp/lldp_node.c
d4b6d529d9b2b9f463ce643c218d647de1dd6315
[ "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
8,561
c
lldp_node.c
/* * Copyright (c) 2011-2016 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. */ /** * @file * @brief LLDP nodes implementation */ #include <lldp/lldp_node.h> #include <vnet/ethernet/ethernet.h> #include <vnet/ethernet/packet.h> /* set this to 1 to turn on debug prints via clib_warning() */ #define LLDP_DEBUG (0) static vlib_node_registration_t lldp_process_node; #define F(sym, string) static char LLDP_ERR_##sym##_STR[] = string; foreach_lldp_error (F); #undef F /* * packet counter strings * Dump these counters via the "show error" CLI command */ static char *lldp_error_strings[] = { #define F(sym, string) LLDP_ERR_##sym##_STR, foreach_lldp_error (F) #undef F }; /* * We actually send all lldp pkts to the "error" node after scanning * them, so the graph node has only one next-index. The "error-drop" * node automatically bumps our per-node packet counters for us. */ typedef enum { LLDP_INPUT_NEXT_NORMAL, LLDP_INPUT_N_NEXT, } lldp_next_t; /* * Process a frame of lldp packets * Expect 1 packet / frame */ static uword lldp_node_fn (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame) { u32 n_left_from, *from; lldp_input_trace_t *t0; from = vlib_frame_vector_args (frame); /* array of buffer indices */ n_left_from = frame->n_vectors; /* number of buffer indices */ while (n_left_from > 0) { u32 bi0; vlib_buffer_t *b0; u32 next0, error0; bi0 = from[0]; b0 = vlib_get_buffer (vm, bi0); next0 = LLDP_INPUT_NEXT_NORMAL; /* scan this lldp pkt. error0 is the counter index to bump */ error0 = lldp_input (vm, b0, bi0); b0->error = node->errors[error0]; /* If this pkt is traced, snapshot the data */ if (b0->flags & VLIB_BUFFER_IS_TRACED) { int len; t0 = vlib_add_trace (vm, node, b0, sizeof (*t0)); len = (b0->current_length < sizeof (t0->data)) ? b0->current_length : sizeof (t0->data); t0->len = len; clib_memcpy_fast (t0->data, vlib_buffer_get_current (b0), len); } /* push this pkt to the next graph node, always error-drop */ vlib_set_next_frame_buffer (vm, node, next0, bi0); from += 1; n_left_from -= 1; } return frame->n_vectors; } /* * lldp input graph node declaration */ /* *INDENT-OFF* */ VLIB_REGISTER_NODE(lldp_input_node, static) = { .function = lldp_node_fn, .name = "lldp-input", .vector_size = sizeof(u32), .type = VLIB_NODE_TYPE_INTERNAL, .n_errors = LLDP_N_ERROR, .error_strings = lldp_error_strings, .format_trace = lldp_input_format_trace, .n_next_nodes = LLDP_INPUT_N_NEXT, .next_nodes = { [LLDP_INPUT_NEXT_NORMAL] = "error-drop", }, }; /* *INDENT-ON* */ /* * lldp process node function */ static uword lldp_process (vlib_main_t * vm, vlib_node_runtime_t * rt, vlib_frame_t * f) { lldp_main_t *lm = &lldp_main; f64 timeout = 0; uword event_type, *event_data = 0; /* So we can send events to the lldp process */ lm->lldp_process_node_index = lldp_process_node.index; /* with ethernet input */ ethernet_register_input_type (vm, ETHERNET_TYPE_802_1_LLDP /* LLDP */ , lldp_input_node.index); while (1) { if (vec_len (lm->intfs_timeouts)) { #if LLDP_DEBUG clib_warning ("DEBUG: wait for event with timeout %f", timeout); #endif (void) vlib_process_wait_for_event_or_clock (vm, timeout); } else { #if LLDP_DEBUG clib_warning ("DEBUG: wait for event without timeout"); #endif (void) vlib_process_wait_for_event (vm); } event_type = vlib_process_get_events (vm, &event_data); switch (event_type) { case ~0: /* no events => timeout */ /* nothing to do here */ break; case LLDP_EVENT_RESCHEDULE: /* nothing to do here - reschedule is done automatically after * each event or timeout */ break; default: clib_warning ("BUG: event type 0x%wx", event_type); break; } if (!vec_len (lm->intfs_timeouts)) { continue; } /* send packet(s) and schedule another timeout */ const f64 now = vlib_time_now (lm->vlib_main); while (1) { lldp_intf_t *n = pool_elt_at_index (lm->intfs, lm->intfs_timeouts [lm->intfs_timeouts_idx]); if (n->last_sent < 0.01 || now > n->last_sent + lm->msg_tx_interval) { #if LLDP_DEBUG clib_warning ("send packet to lldp %p, if idx %d", n, n->hw_if_index); #endif lldp_send_ethernet (lm, n, 0); ++lm->intfs_timeouts_idx; if (lm->intfs_timeouts_idx >= vec_len (lm->intfs_timeouts)) { lm->intfs_timeouts_idx = 0; } continue; } else { timeout = n->last_sent + lm->msg_tx_interval - now; break; } } #if LLDP_DEBUG clib_warning ("DEBUG: timeout set to %f", timeout); u8 *s = NULL; u32 i; vec_foreach_index (i, lm->intfs_timeouts) { if (i == lm->intfs_timeouts_idx) { s = format (s, " [%d]", lm->intfs_timeouts[i]); } else { s = format (s, " %d", lm->intfs_timeouts[i]); } } clib_warning ("DEBUG: timeout schedule: %s", s); vec_free (s); #endif if (event_data) { vec_set_len (event_data, 0); } } return 0; } /* * lldp process node declaration */ /* *INDENT-OFF* */ VLIB_REGISTER_NODE(lldp_process_node, static) = { .function = lldp_process, .type = VLIB_NODE_TYPE_PROCESS, .name = "lldp-process", }; /* *INDENT-ON* */ void lldp_schedule_intf (lldp_main_t * lm, lldp_intf_t * n) { const int idx = n - lm->intfs; u32 v; vec_foreach_index (v, lm->intfs_timeouts) { if (lm->intfs_timeouts[v] == idx) { /* already scheduled */ return; } } n->last_sent = 0; /* ensure that a packet is sent out immediately */ /* put the interface at the current position in the timeouts - it * will timeout immediately */ vec_insert (lm->intfs_timeouts, 1, lm->intfs_timeouts_idx); lm->intfs_timeouts[lm->intfs_timeouts_idx] = n - lm->intfs; vlib_process_signal_event (lm->vlib_main, lm->lldp_process_node_index, LLDP_EVENT_RESCHEDULE, 0); #if LLDP_DEBUG clib_warning ("DEBUG: schedule interface %p, if idx %d", n, n->hw_if_index); #endif } void lldp_unschedule_intf (lldp_main_t * lm, lldp_intf_t * n) { if (!n) { return; } #if LLDP_DEBUG clib_warning ("DEBUG: unschedule interface %p, if idx %d", n, n->hw_if_index); #endif const int idx = n - lm->intfs; u32 v; /* remove intf index from timeouts vector */ vec_foreach_index (v, lm->intfs_timeouts) { if (lm->intfs_timeouts[v] == idx) { vec_delete (lm->intfs_timeouts, 1, v); break; } } /* wrap current timeout index to first element if needed */ if (lm->intfs_timeouts_idx >= vec_len (lm->intfs_timeouts)) { lm->intfs_timeouts_idx = 0; } vlib_process_signal_event (lm->vlib_main, lm->lldp_process_node_index, LLDP_EVENT_RESCHEDULE, 0); } static clib_error_t * lldp_sw_interface_up_down (vnet_main_t * vnm, u32 sw_if_index, u32 flags) { lldp_main_t *lm = &lldp_main; vnet_hw_interface_t *hi = vnet_get_sup_hw_interface (vnm, sw_if_index); lldp_intf_t *n = lldp_get_intf (lm, hi->hw_if_index); if (n) { if (!(flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP)) { /* FIXME - the packet sent here isn't send properly - need to find a * way to send the packet before interface goes down */ lldp_send_ethernet (lm, n, 1); lldp_unschedule_intf (lm, n); } } return 0; } VNET_SW_INTERFACE_ADMIN_UP_DOWN_FUNCTION (lldp_sw_interface_up_down); static clib_error_t * lldp_hw_interface_up_down (vnet_main_t * vnm, u32 hw_if_index, u32 flags) { lldp_main_t *lm = &lldp_main; lldp_intf_t *n = lldp_get_intf (lm, hw_if_index); if (n) { if (flags & VNET_HW_INTERFACE_FLAG_LINK_UP) { lldp_schedule_intf (lm, n); } } return 0; } VNET_HW_INTERFACE_LINK_UP_DOWN_FUNCTION (lldp_hw_interface_up_down); /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */
0d9ba781fc008923dfa1a02938c838ef1f1871b2
7df190df28da7e4ff166e55dc8ce780f11236a9f
/src/router/lighttpd/src/mod_authn_sasl.c
ed74d1759f2b7dca48e2f13f84f52d264022be95
[ "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
10,314
c
mod_authn_sasl.c
/* * mod_authn_sasl - SASL backend for lighttpd HTTP auth * * Copyright(c) 2017 Glenn Strauss gstrauss()gluelogic.com All rights reserved * License: BSD 3-clause (same as lighttpd) */ #include "first.h" /* mod_authn_sasl * * FUTURE POTENTIAL PERFORMANCE ENHANCEMENTS: * - database response is not cached * TODO: db response caching (for limited time) to reduce load on db * (only cache successful logins to prevent cache bloat?) * (or limit number of entries (size) of cache) * (maybe have negative cache (limited size) of names not found in database) * - database query is synchronous and blocks waiting for response */ #include <sys/utsname.h> #include <stdlib.h> #include <string.h> #include <sasl/sasl.h> #include "mod_auth_api.h" #include "base.h" #include "log.h" #include "plugin.h" typedef struct { const char *service; const char *fqdn; const buffer *pwcheck_method; const buffer *sasldb_path; } plugin_config; typedef struct { PLUGIN_DATA; plugin_config defaults; plugin_config conf; int initonce; } plugin_data; static handler_t mod_authn_sasl_basic(request_st *r, void *p_d, const http_auth_require_t *require, const buffer *username, const char *pw); INIT_FUNC(mod_authn_sasl_init) { static http_auth_backend_t http_auth_backend_sasl = { "sasl", mod_authn_sasl_basic, NULL, NULL }; plugin_data *p = ck_calloc(1, sizeof(*p)); /* register http_auth_backend_sasl */ http_auth_backend_sasl.p_d = p; http_auth_backend_set(&http_auth_backend_sasl); return p; } FREE_FUNC(mod_authn_sasl_free) { plugin_data * const p = p_d; if (p->initonce) sasl_done(); if (NULL == p->cvlist) return; /* (init i to 0 if global context; to 1 to skip empty global context) */ for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) { config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0]; for (; -1 != cpv->k_id; ++cpv) { switch (cpv->k_id) { case 0: /* auth.backend.sasl.opts */ if (cpv->vtype == T_CONFIG_LOCAL) free(cpv->v.v); break; default: break; } } } } static void mod_authn_sasl_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) { switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */ case 0: /* auth.backend.sasl.opts */ if (cpv->vtype == T_CONFIG_LOCAL) memcpy(pconf, cpv->v.v, sizeof(plugin_config)); break; default:/* should not happen */ return; } } static void mod_authn_sasl_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) { do { mod_authn_sasl_merge_config_cpv(pconf, cpv); } while ((++cpv)->k_id != -1); } static void mod_authn_sasl_patch_config(request_st * const r, plugin_data * const p) { p->conf = p->defaults; /* copy small struct instead of memcpy() */ /*memcpy(&p->conf, &p->defaults, sizeof(plugin_config));*/ for (int i = 1, used = p->nconfig; i < used; ++i) { if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id)) mod_authn_sasl_merge_config(&p->conf, p->cvlist + p->cvlist[i].v.u2[0]); } } static plugin_config * mod_authn_sasl_parse_opts(server *srv, const array * const opts) { const data_string *ds; const char *service = NULL; const char *fqdn = NULL; const buffer *pwcheck_method = NULL; const buffer *sasldb_path = NULL; ds = (const data_string *) array_get_element_klen(opts, CONST_STR_LEN("service")); service = (NULL != ds) ? ds->value.ptr : "http"; ds = (const data_string *) array_get_element_klen(opts, CONST_STR_LEN("fqdn")); if (NULL != ds) fqdn = ds->value.ptr; if (NULL == fqdn) { static struct utsname uts; if (uts.nodename[0] == '\0') { if (0 != uname(&uts)) { log_perror(srv->errh, __FILE__, __LINE__, "uname()"); return NULL; } } fqdn = uts.nodename; } ds = (const data_string *) array_get_element_klen(opts, CONST_STR_LEN("pwcheck_method")); if (NULL != ds) { pwcheck_method = &ds->value; if (!buffer_is_equal_string(&ds->value, CONST_STR_LEN("saslauthd")) && !buffer_is_equal_string(&ds->value, CONST_STR_LEN("auxprop")) && !buffer_is_equal_string(&ds->value, CONST_STR_LEN("sasldb"))){ log_error(srv->errh, __FILE__, __LINE__, "sasl pwcheck_method must be one of saslauthd, " "sasldb, or auxprop, not: %s", ds->value.ptr); return NULL; } if (buffer_is_equal_string(&ds->value, CONST_STR_LEN("sasldb"))) { /* Cyrus libsasl2 expects "auxprop" instead of "sasldb" * (mod_authn_sasl_cb_getopt auxprop_plugin returns "sasldb") */ buffer *b; *(const buffer **)&b = &ds->value; buffer_copy_string_len(b, CONST_STR_LEN("auxprop")); } } else { static const buffer saslauthd = { "saslauthd", sizeof("saslauthd"), 0 }; pwcheck_method = &saslauthd; } ds = (const data_string *) array_get_element_klen(opts, CONST_STR_LEN("sasldb_path")); if (NULL != ds && !buffer_is_blank(&ds->value)) sasldb_path = &ds->value; plugin_config *pconf = ck_malloc(sizeof(plugin_config)); pconf->service = service; pconf->fqdn = fqdn; pconf->pwcheck_method = pwcheck_method; pconf->sasldb_path = sasldb_path; return pconf; } SETDEFAULTS_FUNC(mod_authn_sasl_set_defaults) { static const config_plugin_keys_t cpk[] = { { CONST_STR_LEN("auth.backend.sasl.opts"), T_CONFIG_ARRAY_KVSTRING, T_CONFIG_SCOPE_CONNECTION } ,{ NULL, 0, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET } }; plugin_data * const p = p_d; if (!config_plugin_values_init(srv, p, cpk, "mod_authn_sasl")) return HANDLER_ERROR; /* process and validate config directives * (init i to 0 if global context; to 1 to skip empty global context) */ for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) { config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0]; for (; -1 != cpv->k_id; ++cpv) { switch (cpv->k_id) { case 0: /* auth.backend.sasl.opts */ if (cpv->v.a->used) { cpv->v.v = mod_authn_sasl_parse_opts(srv, cpv->v.a); if (NULL == cpv->v.v) return HANDLER_ERROR; cpv->vtype = T_CONFIG_LOCAL; } break; default:/* should not happen */ break; } } } /* initialize p->defaults from global config context */ if (p->nconfig > 0 && p->cvlist->v.u2[1]) { const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0]; if (-1 != cpv->k_id) mod_authn_sasl_merge_config(&p->defaults, cpv); } return HANDLER_GO_ON; } static int mod_authn_sasl_cb_getopt(void *p_d, const char *plugin_name, const char *opt, const char **res, unsigned *len) { plugin_data *p = (plugin_data *)p_d; size_t sz; if (0 == strcmp(opt, "pwcheck_method")) { *res = p->conf.pwcheck_method->ptr; sz = buffer_clen(p->conf.pwcheck_method); } else if (0 == strcmp(opt, "sasldb_path") && p->conf.sasldb_path) { *res = p->conf.sasldb_path->ptr; sz = buffer_clen(p->conf.sasldb_path); } else if (0 == strcmp(opt, "auxprop_plugin")) { *res = "sasldb"; sz = sizeof("sasldb")-1; } else { UNUSED(plugin_name); return SASL_FAIL; } if (len) *len = (unsigned int)sz; return SASL_OK; } static int mod_authn_sasl_cb_log(void *vreq, int level, const char *message) { switch (level) { #if 0 case SASL_LOG_NONE: case SASL_LOG_NOTE: case SASL_LOG_DEBUG: case SASL_LOG_TRACE: case SASL_LOG_PASS: #endif default: break; case SASL_LOG_ERR: case SASL_LOG_FAIL: case SASL_LOG_WARN: /* (might omit SASL_LOG_WARN if too noisy in logs) */ log_error(((request_st *)vreq)->conf.errh, __FILE__, __LINE__, "%s", message); break; } return SASL_OK; } static handler_t mod_authn_sasl_query(request_st * const r, void *p_d, const buffer * const username, const char * const realm, const char * const pw) { plugin_data *p = (plugin_data *)p_d; sasl_conn_t *sc; sasl_callback_t const cb[] = { { SASL_CB_GETOPT, (int(*)(void))(uintptr_t)mod_authn_sasl_cb_getopt, (void *) p }, { SASL_CB_LOG, (int(*)(void))(uintptr_t)mod_authn_sasl_cb_log, (void *) r }, { SASL_CB_LIST_END, NULL, NULL } }; int rc; mod_authn_sasl_patch_config(r, p); if (!p->initonce) { /* must be done once, but after fork() if multiple lighttpd workers */ rc = sasl_server_init(cb, NULL); if (SASL_OK != rc) return HANDLER_ERROR; p->initonce = 1; } rc = sasl_server_new(p->conf.service, p->conf.fqdn, realm, NULL, NULL, cb, 0, &sc); if (SASL_OK == rc) { rc = sasl_checkpass(sc, BUF_PTR_LEN(username), pw, strlen(pw)); sasl_dispose(&sc); } return (SASL_OK == rc) ? HANDLER_GO_ON : HANDLER_ERROR; } static handler_t mod_authn_sasl_basic(request_st * const r, void *p_d, const http_auth_require_t * const require, const buffer * const username, const char * const pw) { char *realm = require->realm->ptr; handler_t rc = mod_authn_sasl_query(r, p_d, username, realm, pw); if (HANDLER_GO_ON != rc) return rc; return http_auth_match_rules(require, username->ptr, NULL, NULL) ? HANDLER_GO_ON /* access granted */ : HANDLER_ERROR; } __attribute_cold__ __declspec_dllexport__ int mod_authn_sasl_plugin_init(plugin *p); int mod_authn_sasl_plugin_init(plugin *p) { p->version = LIGHTTPD_VERSION_ID; p->name = "authn_sasl"; p->init = mod_authn_sasl_init; p->set_defaults= mod_authn_sasl_set_defaults; p->cleanup = mod_authn_sasl_free; return 0; }
b05d22d36bbf76cde414e00cafb1be7495d8dd1b
229a28fc18c13bfe1ba7fc81c38b03651ed8e93b
/sw/banshee/tests/fsqrt.c
18e57e65a8b1ab1e4658426fdaf72132b08803d6
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
pulp-platform/snitch
d3967742434fa21e8af71afa6be35ea5420166ca
d026f47843f0ea6c269244c4e6851e0e09141ec3
refs/heads/master
2023-08-24T08:42:36.230951
2023-06-19T09:34:05
2023-06-19T09:34:05
289,236,605
194
44
Apache-2.0
2023-07-11T12:46:26
2020-08-21T09:57:34
SystemVerilog
UTF-8
C
false
false
3,461
c
fsqrt.c
// Copyright 2020 ETH Zurich and University of Bologna. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include <stdint.h> int main() { int errs = 4; uint32_t i8a = 0xFFFFFF42; // 3.14 uint32_t i16a = 0xFFFF4248; // 3.14 float f32a = 3.14; double f64a = 3.14; double res = 1.7720045146669350401991125097536315250736085161629429668177719702909929723489025514725611511539091877503688586880283471705309723721012586751956463721779299361108965365785172200533307761033262439251035823876630437358544911321775625334001046371917616395365848355896213899000527657212021528895927246779480097429154300464010005952680240848463115459297328553780312231691503242208599015793499587440362444180066185238563026710308225242753943500300975957184358461499870626091843809846077091336709541509137661458088335053343825975151460070607357734811548345743955015534456467218552322095954133171880799362477308250252188131416973988993582005350715319952451457013468109231195117000461048554576068707669842993562588266797580347406917516902405285501779620381080421964911692468676654496394088290796641726097314467544452471907934937761385072173706953649409390505097456326820687124319479077069857723545275763448424743526123095082523671605076154911770441368544369157939980880039073716064343031720647930305982767909663674127659266536508742233853866486751460736968681734171024601234112111109848603356126829499008554468260892880962422318346551725814678224017826347226250095335499135772956177452621508573027889814601862343733080464610165218611014506469796480839953159053907987963746888229539303938033616475560292508959607852522732628587506900848010359146262337399502719182926411345876346411763682962300200620810946167615503832294702928298154203757353278145481441408173828749702691477702693921981501005117987820425263365883247955854902748660833891001213443228098779002847019799486769225068962106798362492845149943553231162640282955097571324701122433023245811092998880746343360680949191418953273981637109829068110425865251662526085947317016662135990699159458389649426337612397578070919724346301810733843583118526604802387577793788975059774410388320563908349065276980811546400821449562904652037828180265505648380982709553254282570388714170386081582151498563957038798648495307704883419522824305078934219573760102006376672734918202648872366047279461901050575212008546447170395166840447114506461340651090; double resf8 = 1.5; uint32_t cmp = 0; // load smallfloat data into float regfile asm volatile( "fmv.s.x ft3, %0\n" "fmv.s.x ft4, %1\n" : "+r"(i8a), "+r"(i16a)); // FSQRT.D asm volatile( "fsqrt.d ft5, %0\n" "feq.d %2, %1, ft5\n" : "+f"(f64a), "+f"(res), "+r"(cmp)); errs -= (cmp == 0x1); cmp = 0; // FSQRT.S asm volatile( "fsqrt.s ft5, %0\n" "fcvt.s.d ft6, %1\n" "feq.s %2, ft6, ft5\n" : "+f"(f32a), "+f"(res), "+r"(cmp)); errs -= (cmp == 0x1); cmp = 0; // FSQRT.H asm volatile( "fsqrt.h ft5, ft4\n" "fcvt.h.d ft6, %0\n" "feq.h %1, ft6, ft5\n" : "+f"(res), "+r"(cmp)); errs -= (cmp == 0x1); cmp = 0; // FSQRT.B asm volatile( "fsqrt.b ft5, ft3\n" "fcvt.b.d ft6, %0\n" "feq.b %1, ft6, ft5\n" : "+f"(resf8), "+r"(cmp)); errs -= (cmp == 0x1); cmp = 0; return errs; }
de7f4f201595de75b2111d15dea99ff9d0ddef24
010279e2ba272d09e9d2c4e903722e5faba2cf7a
/contrib/libs/libxml/SAX.c
292af57e97b8f82d1cd3a38b3ceabcdbe1607b93
[ "MIT", "Apache-2.0" ]
permissive
catboost/catboost
854c1a1f439a96f1ae6b48e16644be20aa04dba2
f5042e35b945aded77b23470ead62d7eacefde92
refs/heads/master
2023-09-01T12:14:14.174108
2023-09-01T10:01:01
2023-09-01T10:22:12
97,556,265
8,012
1,425
Apache-2.0
2023-09-11T03:32:32
2017-07-18T05:29:04
Python
UTF-8
C
false
false
5,531
c
SAX.c
/* * SAX.c : Old SAX v1 handlers to build a tree. * Deprecated except for compatibility * * See Copyright for the status of this software. * * Daniel Veillard <daniel@veillard.com> */ #define IN_LIBXML #include "libxml.h" #include <stdlib.h> #include <string.h> #include <libxml/xmlmemory.h> #include <libxml/tree.h> #include <libxml/parser.h> #include <libxml/parserInternals.h> #include <libxml/valid.h> #include <libxml/entities.h> #include <libxml/xmlerror.h> #include <libxml/debugXML.h> #include <libxml/xmlIO.h> #include <libxml/SAX.h> #include <libxml/uri.h> #include <libxml/valid.h> #include <libxml/HTMLtree.h> #include <libxml/globals.h> #include <libxml/SAX2.h> #ifdef LIBXML_LEGACY_ENABLED #ifdef LIBXML_SAX1_ENABLED /** * initxmlDefaultSAXHandler: * @hdlr: the SAX handler * @warning: flag if non-zero sets the handler warning procedure * * Initialize the default XML SAX version 1 handler * DEPRECATED: use xmlSAX2InitDefaultSAXHandler() for the new SAX2 blocks */ void initxmlDefaultSAXHandler(xmlSAXHandlerV1 *hdlr, int warning) { if(hdlr->initialized == 1) return; hdlr->internalSubset = xmlSAX2InternalSubset; hdlr->externalSubset = xmlSAX2ExternalSubset; hdlr->isStandalone = xmlSAX2IsStandalone; hdlr->hasInternalSubset = xmlSAX2HasInternalSubset; hdlr->hasExternalSubset = xmlSAX2HasExternalSubset; hdlr->resolveEntity = xmlSAX2ResolveEntity; hdlr->getEntity = xmlSAX2GetEntity; hdlr->getParameterEntity = xmlSAX2GetParameterEntity; hdlr->entityDecl = xmlSAX2EntityDecl; hdlr->attributeDecl = xmlSAX2AttributeDecl; hdlr->elementDecl = xmlSAX2ElementDecl; hdlr->notationDecl = xmlSAX2NotationDecl; hdlr->unparsedEntityDecl = xmlSAX2UnparsedEntityDecl; hdlr->setDocumentLocator = xmlSAX2SetDocumentLocator; hdlr->startDocument = xmlSAX2StartDocument; hdlr->endDocument = xmlSAX2EndDocument; hdlr->startElement = xmlSAX2StartElement; hdlr->endElement = xmlSAX2EndElement; hdlr->reference = xmlSAX2Reference; hdlr->characters = xmlSAX2Characters; hdlr->cdataBlock = xmlSAX2CDataBlock; hdlr->ignorableWhitespace = xmlSAX2Characters; hdlr->processingInstruction = xmlSAX2ProcessingInstruction; if (warning == 0) hdlr->warning = NULL; else hdlr->warning = xmlParserWarning; hdlr->error = xmlParserError; hdlr->fatalError = xmlParserError; hdlr->initialized = 1; } #ifdef LIBXML_HTML_ENABLED /** * inithtmlDefaultSAXHandler: * @hdlr: the SAX handler * * Initialize the default HTML SAX version 1 handler * DEPRECATED: use xmlSAX2InitHtmlDefaultSAXHandler() for the new SAX2 blocks */ void inithtmlDefaultSAXHandler(xmlSAXHandlerV1 *hdlr) { if(hdlr->initialized == 1) return; hdlr->internalSubset = xmlSAX2InternalSubset; hdlr->externalSubset = NULL; hdlr->isStandalone = NULL; hdlr->hasInternalSubset = NULL; hdlr->hasExternalSubset = NULL; hdlr->resolveEntity = NULL; hdlr->getEntity = xmlSAX2GetEntity; hdlr->getParameterEntity = NULL; hdlr->entityDecl = NULL; hdlr->attributeDecl = NULL; hdlr->elementDecl = NULL; hdlr->notationDecl = NULL; hdlr->unparsedEntityDecl = NULL; hdlr->setDocumentLocator = xmlSAX2SetDocumentLocator; hdlr->startDocument = xmlSAX2StartDocument; hdlr->endDocument = xmlSAX2EndDocument; hdlr->startElement = xmlSAX2StartElement; hdlr->endElement = xmlSAX2EndElement; hdlr->reference = NULL; hdlr->characters = xmlSAX2Characters; hdlr->cdataBlock = xmlSAX2CDataBlock; hdlr->ignorableWhitespace = xmlSAX2IgnorableWhitespace; hdlr->processingInstruction = xmlSAX2ProcessingInstruction; hdlr->comment = xmlSAX2Comment; hdlr->warning = xmlParserWarning; hdlr->error = xmlParserError; hdlr->fatalError = xmlParserError; hdlr->initialized = 1; } #endif /* LIBXML_HTML_ENABLED */ #ifdef LIBXML_DOCB_ENABLED /** * initdocbDefaultSAXHandler: * @hdlr: the SAX handler * * Initialize the default DocBook SAX version 1 handler * DEPRECATED: use xmlSAX2InitDocbDefaultSAXHandler() for the new SAX2 blocks */ void initdocbDefaultSAXHandler(xmlSAXHandlerV1 *hdlr) { if(hdlr->initialized == 1) return; hdlr->internalSubset = xmlSAX2InternalSubset; hdlr->externalSubset = NULL; hdlr->isStandalone = xmlSAX2IsStandalone; hdlr->hasInternalSubset = xmlSAX2HasInternalSubset; hdlr->hasExternalSubset = xmlSAX2HasExternalSubset; hdlr->resolveEntity = xmlSAX2ResolveEntity; hdlr->getEntity = xmlSAX2GetEntity; hdlr->getParameterEntity = NULL; hdlr->entityDecl = xmlSAX2EntityDecl; hdlr->attributeDecl = NULL; hdlr->elementDecl = NULL; hdlr->notationDecl = NULL; hdlr->unparsedEntityDecl = NULL; hdlr->setDocumentLocator = xmlSAX2SetDocumentLocator; hdlr->startDocument = xmlSAX2StartDocument; hdlr->endDocument = xmlSAX2EndDocument; hdlr->startElement = xmlSAX2StartElement; hdlr->endElement = xmlSAX2EndElement; hdlr->reference = xmlSAX2Reference; hdlr->characters = xmlSAX2Characters; hdlr->cdataBlock = NULL; hdlr->ignorableWhitespace = xmlSAX2IgnorableWhitespace; hdlr->processingInstruction = NULL; hdlr->comment = xmlSAX2Comment; hdlr->warning = xmlParserWarning; hdlr->error = xmlParserError; hdlr->fatalError = xmlParserError; hdlr->initialized = 1; } #endif /* LIBXML_DOCB_ENABLED */ #endif /* LIBXML_SAX1_ENABLED */ #define bottom_SAX #include "elfgcchack.h" #endif /* LIBXML_LEGACY_ENABLED */
24b152ef1b1b91009ddb017ad67580ee49248958
192f6a4c9d934be58bca0e610ec1a75e7777fcd1
/src/string/encoding/utf16.c
c3b6cd4e7c88222f989a05cc4d3d0eb89928f419
[ "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
15,394
c
utf16.c
/* Copyright (C) 2001-2010, Parrot Foundation. =head1 NAME src/string/encoding/utf16.c - UTF-16 encoding =head1 DESCRIPTION UTF-16 encoding =head2 Functions =over 4 =cut */ #include "parrot/parrot.h" #include "unicode.h" #include "shared.h" /* HEADERIZER HFILE: none */ /* HEADERIZER BEGIN: static */ /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ PARROT_WARN_UNUSED_RESULT static UINTVAL utf16_decode(PARROT_INTERP, ARGIN(const utf16_t *p)) __attribute__nonnull__(2); PARROT_WARN_UNUSED_RESULT PARROT_CANNOT_RETURN_NULL static utf16_t * utf16_encode(PARROT_INTERP, ARGMOD(utf16_t *ptr), UINTVAL c) __attribute__nonnull__(1) __attribute__nonnull__(2) FUNC_MODIFIES(*ptr); static UINTVAL utf16_iter_get(PARROT_INTERP, ARGIN(const STRING *str), ARGIN(const String_iter *i), INTVAL offset) __attribute__nonnull__(1) __attribute__nonnull__(2) __attribute__nonnull__(3); PARROT_WARN_UNUSED_RESULT static UINTVAL utf16_iter_get_and_advance(PARROT_INTERP, ARGIN(const STRING *str), ARGMOD(String_iter *i)) __attribute__nonnull__(1) __attribute__nonnull__(2) __attribute__nonnull__(3) FUNC_MODIFIES(*i); static void utf16_iter_set_and_advance(PARROT_INTERP, ARGMOD(STRING *str), ARGMOD(String_iter *i), UINTVAL c) __attribute__nonnull__(1) __attribute__nonnull__(2) __attribute__nonnull__(3) FUNC_MODIFIES(*str) FUNC_MODIFIES(*i); static void utf16_iter_skip(PARROT_INTERP, ARGIN(const STRING *str), ARGMOD(String_iter *i), INTVAL skip) __attribute__nonnull__(2) __attribute__nonnull__(3) FUNC_MODIFIES(*i); static UINTVAL utf16_ord(PARROT_INTERP, ARGIN(const STRING *src), INTVAL idx) __attribute__nonnull__(1) __attribute__nonnull__(2); static INTVAL utf16_partial_scan(PARROT_INTERP, ARGIN(const char *buf), ARGMOD(Parrot_String_Bounds *bounds)) __attribute__nonnull__(1) __attribute__nonnull__(2) __attribute__nonnull__(3) FUNC_MODIFIES(*bounds); static void utf16_scan(PARROT_INTERP, ARGMOD(STRING *src)) __attribute__nonnull__(1) __attribute__nonnull__(2) FUNC_MODIFIES(*src); PARROT_CANNOT_RETURN_NULL PARROT_WARN_UNUSED_RESULT static const utf16_t * utf16_skip_backward( ARGIN(const utf16_t *p), UINTVAL count) __attribute__nonnull__(1); PARROT_CANNOT_RETURN_NULL PARROT_WARN_UNUSED_RESULT static const utf16_t * utf16_skip_forward( ARGIN(const utf16_t *p), UINTVAL count) __attribute__nonnull__(1); PARROT_WARN_UNUSED_RESULT PARROT_CANNOT_RETURN_NULL static STRING * utf16_to_encoding(PARROT_INTERP, ARGIN(const STRING *src)) __attribute__nonnull__(1) __attribute__nonnull__(2); #define ASSERT_ARGS_utf16_decode __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(p)) #define ASSERT_ARGS_utf16_encode __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(ptr)) #define ASSERT_ARGS_utf16_iter_get __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(str) \ , PARROT_ASSERT_ARG(i)) #define ASSERT_ARGS_utf16_iter_get_and_advance __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(str) \ , PARROT_ASSERT_ARG(i)) #define ASSERT_ARGS_utf16_iter_set_and_advance __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(str) \ , PARROT_ASSERT_ARG(i)) #define ASSERT_ARGS_utf16_iter_skip __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(str) \ , PARROT_ASSERT_ARG(i)) #define ASSERT_ARGS_utf16_ord __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(src)) #define ASSERT_ARGS_utf16_partial_scan __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(buf) \ , PARROT_ASSERT_ARG(bounds)) #define ASSERT_ARGS_utf16_scan __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(src)) #define ASSERT_ARGS_utf16_skip_backward __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(p)) #define ASSERT_ARGS_utf16_skip_forward __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(p)) #define ASSERT_ARGS_utf16_to_encoding __attribute__unused__ int _ASSERT_ARGS_CHECK = (\ PARROT_ASSERT_ARG(interp) \ , PARROT_ASSERT_ARG(src)) /* Don't modify between HEADERIZER BEGIN / HEADERIZER END. Your changes will be lost. */ /* HEADERIZER END: static */ /* =item C<static STRING * utf16_to_encoding(PARROT_INTERP, const STRING *src)> Converts the string C<src> to this particular encoding. =cut */ PARROT_WARN_UNUSED_RESULT PARROT_CANNOT_RETURN_NULL static STRING * utf16_to_encoding(PARROT_INTERP, ARGIN(const STRING *src)) { ASSERT_ARGS(utf16_to_encoding) STRING *result; UINTVAL src_len; src_len = STRING_length(src); if (STRING_max_bytes_per_codepoint(src) == 1) { result = Parrot_gc_new_string_header(interp, 0); result->encoding = Parrot_ucs2_encoding_ptr; result->bufused = 2 * src_len; result->strlen = src_len; if (src_len) { UINTVAL i; Parrot_UInt2 *p; Parrot_gc_allocate_string_storage(interp, result, 2 * src_len); p = (Parrot_UInt2 *)result->strstart; for (i = 0; i < src_len; ++i) { p[i] = (unsigned char)src->strstart[i]; } } } else if (src->encoding == Parrot_utf16_encoding_ptr || src->encoding == Parrot_ucs2_encoding_ptr) { /* we have to use clone instead of copy because the Unicode upcase * and downcase functions assume to get an unshared buffer */ result = Parrot_str_clone(interp, src); } else { result = encoding_to_encoding(interp, src, Parrot_utf16_encoding_ptr, 2.2); /* downgrade if possible */ if (result->bufused == result->strlen << 1) result->encoding = Parrot_ucs2_encoding_ptr; } return result; } /* =item C<static void utf16_scan(PARROT_INTERP, STRING *src)> Returns the number of codepoints in string C<src> by scanning the whole string. =cut */ static void utf16_scan(PARROT_INTERP, ARGMOD(STRING *src)) { ASSERT_ARGS(utf16_scan) Parrot_String_Bounds bounds; bounds.bytes = src->bufused; bounds.chars = -1; bounds.delim = -1; utf16_partial_scan(interp, src->strstart, &bounds); if (bounds.bytes != src->bufused) Parrot_ex_throw_from_c_noargs(interp, EXCEPTION_MALFORMED_UTF16, "Unaligned end in UTF-16 string"); src->strlen = bounds.chars; } /* =item C<static INTVAL utf16_partial_scan(PARROT_INTERP, const char *buf, Parrot_String_Bounds *bounds)> Partial scan of UTF-16 string =cut */ static INTVAL utf16_partial_scan(PARROT_INTERP, ARGIN(const char *buf), ARGMOD(Parrot_String_Bounds *bounds)) { ASSERT_ARGS(utf16_partial_scan) const utf16_t * const p = (const utf16_t *)buf; UINTVAL len = bounds->bytes >> 1; INTVAL max_chars = bounds->chars; const INTVAL delim = bounds->delim; INTVAL c = -1; INTVAL chars = 0; INTVAL res = 0; UINTVAL i; if (max_chars < 0) max_chars = len; for (i = 0; i < len && chars < max_chars; ++i) { c = p[i]; if (UNICODE_IS_HIGH_SURROGATE(c)) { if (i + 1 >= len) { /* Two more bytes needed */ res = 2; break; } ++i; if (!UNICODE_IS_LOW_SURROGATE(p[i])) Parrot_ex_throw_from_c_noargs(interp, EXCEPTION_MALFORMED_UTF16, "Malformed UTF-16 string"); c = UNICODE_DECODE_SURROGATE(c, p[i]); } else { if (UNICODE_IS_LOW_SURROGATE(c)) Parrot_ex_throw_from_c_noargs(interp, EXCEPTION_MALFORMED_UTF16, "Malformed UTF-16 string"); } if (UNICODE_IS_NON_CHARACTER(c)) Parrot_ex_throw_from_c_noargs(interp, EXCEPTION_INVALID_CHARACTER, "Non-character in UTF-16 string"); ++chars; if (c == delim) { i += 1; break; } } bounds->bytes = i << 1; bounds->chars = chars; bounds->delim = c; return res; } /* =item C<static const utf16_t * utf16_skip_forward(const utf16_t *p, UINTVAL count)> Skips C<count> codepoints starting from C<p>. Returns the new pointer. =cut */ PARROT_CANNOT_RETURN_NULL PARROT_WARN_UNUSED_RESULT static const utf16_t * utf16_skip_forward(ARGIN(const utf16_t *p), UINTVAL count) { ASSERT_ARGS(utf16_skip_forward) UINTVAL i; for (i = 0; i < count; ++i) { p += UTF16SKIP(*p); } return p; } /* =item C<static const utf16_t * utf16_skip_backward(const utf16_t *p, UINTVAL count)> Skips C<count> codepoints backwards starting from C<p>. Returns the new pointer. =cut */ PARROT_CANNOT_RETURN_NULL PARROT_WARN_UNUSED_RESULT static const utf16_t * utf16_skip_backward(ARGIN(const utf16_t *p), UINTVAL count) { ASSERT_ARGS(utf16_skip_backward) UINTVAL i; for (i = 0; i < count; ++i) { --p; if (UNICODE_IS_LOW_SURROGATE(*p)) --p; } return p; } /* =item C<static UINTVAL utf16_decode(PARROT_INTERP, const utf16_t *p)> Decodes the codepoint starting at C<p>. =cut */ PARROT_WARN_UNUSED_RESULT static UINTVAL utf16_decode(SHIM_INTERP, ARGIN(const utf16_t *p)) { ASSERT_ARGS(utf16_decode) UINTVAL c = *p; if (UNICODE_IS_HIGH_SURROGATE(c)) c = UNICODE_DECODE_SURROGATE(c, p[1]); return c; } /* =item C<static utf16_t * utf16_encode(PARROT_INTERP, utf16_t *ptr, UINTVAL c)> Decodes the codepoint starting at C<p>. =cut */ PARROT_WARN_UNUSED_RESULT PARROT_CANNOT_RETURN_NULL static utf16_t * utf16_encode(PARROT_INTERP, ARGMOD(utf16_t *ptr), UINTVAL c) { ASSERT_ARGS(utf16_encode) if (c < 0xFFFE) { if (UNICODE_IS_SURROGATE(c) || (c >= 0xFDD0 && c <= 0xFDEF)) Parrot_ex_throw_from_c_noargs(interp, EXCEPTION_INVALID_CHARACTER, "Invalid character for UTF-16 encoding"); *ptr++ = c; } else { if ((c & 0xFFFE) == 0xFFFE || c > 0x10FFFF) Parrot_ex_throw_from_c_noargs(interp, EXCEPTION_INVALID_CHARACTER, "Invalid character for UTF-16 encoding"); *ptr++ = UNICODE_HIGH_SURROGATE(c); *ptr++ = UNICODE_LOW_SURROGATE(c); } return ptr; } /* =item C<static UINTVAL utf16_ord(PARROT_INTERP, const STRING *src, INTVAL idx)> Returns the codepoint in string C<src> at position C<offset>. =cut */ static UINTVAL utf16_ord(PARROT_INTERP, ARGIN(const STRING *src), INTVAL idx) { ASSERT_ARGS(utf16_ord) const UINTVAL len = STRING_length(src); const utf16_t *start; if (idx < 0) idx += len; if ((UINTVAL)idx >= len) encoding_ord_error(interp, src, idx); start = utf16_skip_forward((const utf16_t *)src->strstart, idx); return utf16_decode(interp, start); } /* =item C<static UINTVAL utf16_iter_get(PARROT_INTERP, const STRING *str, const String_iter *i, INTVAL offset)> Get the character at C<i> plus C<offset>. =cut */ static UINTVAL utf16_iter_get(PARROT_INTERP, ARGIN(const STRING *str), ARGIN(const String_iter *i), INTVAL offset) { ASSERT_ARGS(utf16_iter_get) const utf16_t *ptr = (utf16_t *)(str->strstart + i->bytepos); PARROT_ASSERT((i->charpos + offset) <= str->strlen); if (offset > 0) ptr = utf16_skip_forward(ptr, offset); else if (offset < 0) ptr = utf16_skip_backward(ptr, -offset); return utf16_decode(interp, ptr); } /* =item C<static void utf16_iter_skip(PARROT_INTERP, const STRING *str, String_iter *i, INTVAL skip)> Moves the string iterator C<i> by C<skip> characters. =cut */ static void utf16_iter_skip(SHIM_INTERP, ARGIN(const STRING *str), ARGMOD(String_iter *i), INTVAL skip) { ASSERT_ARGS(utf16_iter_skip) const utf16_t *ptr = (utf16_t *)(str->strstart + i->bytepos); i->charpos += skip; PARROT_ASSERT(i->charpos <= str->strlen); if (skip > 0) ptr = utf16_skip_forward(ptr, skip); else if (skip < 0) ptr = utf16_skip_backward(ptr, -skip); i->bytepos = (const char *)ptr - (const char *)str->strstart; PARROT_ASSERT(i->bytepos <= str->bufused); } /* =item C<static UINTVAL utf16_iter_get_and_advance(PARROT_INTERP, const STRING *str, String_iter *i)> Moves the string iterator C<i> to the next UTF-16 codepoint. =cut */ PARROT_WARN_UNUSED_RESULT static UINTVAL utf16_iter_get_and_advance(PARROT_INTERP, ARGIN(const STRING *str), ARGMOD(String_iter *i)) { ASSERT_ARGS(utf16_iter_get_and_advance) const utf16_t *ptr = (utf16_t *)(str->strstart + i->bytepos); UINTVAL c = utf16_decode(interp, ptr); i->charpos += 1; if (UNICODE_IS_HIGH_SURROGATE(*ptr)) i->bytepos += 4; else i->bytepos += 2; PARROT_ASSERT(i->bytepos <= str->bufused); return c; } /* =item C<static void utf16_iter_set_and_advance(PARROT_INTERP, STRING *str, String_iter *i, UINTVAL c)> With the string iterator C<i>, appends the codepoint C<c> and advances to the next position in the string. =cut */ static void utf16_iter_set_and_advance(PARROT_INTERP, ARGMOD(STRING *str), ARGMOD(String_iter *i), UINTVAL c) { ASSERT_ARGS(utf16_iter_set_and_advance) utf16_t * const ptr = (utf16_t *)(str->strstart + i->bytepos); utf16_t * const end = utf16_encode(interp, ptr, c); i->charpos += 1; i->bytepos += (char *)end - (char *)ptr; PARROT_ASSERT(i->bytepos <= str->bufused); } static STR_VTABLE Parrot_utf16_encoding = { -1, "utf16", NULL, 2, /* Bytes per unit */ 4, /* Max bytes per codepoint */ utf16_to_encoding, unicode_chr, encoding_equal, encoding_compare, encoding_index, encoding_rindex, encoding_hash, utf16_scan, utf16_partial_scan, utf16_ord, encoding_substr, encoding_is_cclass, encoding_find_cclass, encoding_find_not_cclass, encoding_get_graphemes, unicode_compose, encoding_decompose, unicode_upcase, unicode_downcase, unicode_titlecase, unicode_foldcase, unicode_upcase_first, unicode_downcase_first, unicode_titlecase_first, utf16_iter_get, utf16_iter_skip, utf16_iter_get_and_advance, utf16_iter_set_and_advance }; STR_VTABLE *Parrot_utf16_encoding_ptr = &Parrot_utf16_encoding; /* =back =head1 SEE ALSO F<src/string/encoding/fixed_8.c>, F<src/string/encoding/utf8.c>, F<src/string.c>, F<include/parrot/string.h>, F<docs/string.pod>. =cut */ /* * Local variables: * c-file-style: "parrot" * End: * vim: expandtab shiftwidth=4 cinoptions='\:2=2' : */
8c3026f565cd7f32ef205e069098879ff758ac06
31406f420f019a191a74b9288a6e37dcd89e8e82
/tools/node-hermes/third-party/libuv/src/unix/android-ifaddrs.c
99fb25a43b427971b96a57725268238de76a6ab3
[ "MIT", "CC-BY-4.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "ISC", "BSD-2-Clause" ]
permissive
facebook/hermes
b1bf3cb60b5946450c7c9a421ac8dad7a675e0f5
440578b31ecce46fcc5ba2ad745ffd5712d63a35
refs/heads/main
2023-09-06T04:16:02.263184
2023-09-05T20:12:54
2023-09-05T20:12:54
154,201,259
8,449
593
MIT
2023-09-14T21:25:56
2018-10-22T19:13:00
C++
UTF-8
C
false
false
20,144
c
android-ifaddrs.c
/* Copyright (c) 2013, Kenneth MacKay Copyright (c) 2014, Emergya (Cloud4all, FP7/2007-2013 grant agreement #289016) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uv/android-ifaddrs.h" #include "uv-common.h" #include <string.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <sys/socket.h> #include <net/if_arp.h> #include <netinet/in.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> typedef struct NetlinkList { struct NetlinkList *m_next; struct nlmsghdr *m_data; unsigned int m_size; } NetlinkList; static int netlink_socket(pid_t *p_pid) { struct sockaddr_nl l_addr; socklen_t l_len; int l_socket = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if(l_socket < 0) { return -1; } memset(&l_addr, 0, sizeof(l_addr)); l_addr.nl_family = AF_NETLINK; if(bind(l_socket, (struct sockaddr *)&l_addr, sizeof(l_addr)) < 0) { close(l_socket); return -1; } l_len = sizeof(l_addr); if(getsockname(l_socket, (struct sockaddr *)&l_addr, &l_len) < 0) { close(l_socket); return -1; } *p_pid = l_addr.nl_pid; return l_socket; } static int netlink_send(int p_socket, int p_request) { char l_buffer[NLMSG_ALIGN(sizeof(struct nlmsghdr)) + NLMSG_ALIGN(sizeof(struct rtgenmsg))]; struct nlmsghdr *l_hdr; struct rtgenmsg *l_msg; struct sockaddr_nl l_addr; memset(l_buffer, 0, sizeof(l_buffer)); l_hdr = (struct nlmsghdr *)l_buffer; l_msg = (struct rtgenmsg *)NLMSG_DATA(l_hdr); l_hdr->nlmsg_len = NLMSG_LENGTH(sizeof(*l_msg)); l_hdr->nlmsg_type = p_request; l_hdr->nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST; l_hdr->nlmsg_pid = 0; l_hdr->nlmsg_seq = p_socket; l_msg->rtgen_family = AF_UNSPEC; memset(&l_addr, 0, sizeof(l_addr)); l_addr.nl_family = AF_NETLINK; return (sendto(p_socket, l_hdr, l_hdr->nlmsg_len, 0, (struct sockaddr *)&l_addr, sizeof(l_addr))); } static int netlink_recv(int p_socket, void *p_buffer, size_t p_len) { struct sockaddr_nl l_addr; struct msghdr l_msg; struct iovec l_iov; l_iov.iov_base = p_buffer; l_iov.iov_len = p_len; for(;;) { int l_result; l_msg.msg_name = (void *)&l_addr; l_msg.msg_namelen = sizeof(l_addr); l_msg.msg_iov = &l_iov; l_msg.msg_iovlen = 1; l_msg.msg_control = NULL; l_msg.msg_controllen = 0; l_msg.msg_flags = 0; l_result = recvmsg(p_socket, &l_msg, 0); if(l_result < 0) { if(errno == EINTR) { continue; } return -2; } /* Buffer was too small */ if(l_msg.msg_flags & MSG_TRUNC) { return -1; } return l_result; } } static struct nlmsghdr *getNetlinkResponse(int p_socket, pid_t p_pid, int *p_size, int *p_done) { size_t l_size = 4096; void *l_buffer = NULL; for(;;) { int l_read; uv__free(l_buffer); l_buffer = uv__malloc(l_size); if (l_buffer == NULL) { return NULL; } l_read = netlink_recv(p_socket, l_buffer, l_size); *p_size = l_read; if(l_read == -2) { uv__free(l_buffer); return NULL; } if(l_read >= 0) { struct nlmsghdr *l_hdr; for(l_hdr = (struct nlmsghdr *)l_buffer; NLMSG_OK(l_hdr, (unsigned int)l_read); l_hdr = (struct nlmsghdr *)NLMSG_NEXT(l_hdr, l_read)) { if((pid_t)l_hdr->nlmsg_pid != p_pid || (int)l_hdr->nlmsg_seq != p_socket) { continue; } if(l_hdr->nlmsg_type == NLMSG_DONE) { *p_done = 1; break; } if(l_hdr->nlmsg_type == NLMSG_ERROR) { uv__free(l_buffer); return NULL; } } return l_buffer; } l_size *= 2; } } static NetlinkList *newListItem(struct nlmsghdr *p_data, unsigned int p_size) { NetlinkList *l_item = uv__malloc(sizeof(NetlinkList)); if (l_item == NULL) { return NULL; } l_item->m_next = NULL; l_item->m_data = p_data; l_item->m_size = p_size; return l_item; } static void freeResultList(NetlinkList *p_list) { NetlinkList *l_cur; while(p_list) { l_cur = p_list; p_list = p_list->m_next; uv__free(l_cur->m_data); uv__free(l_cur); } } static NetlinkList *getResultList(int p_socket, int p_request, pid_t p_pid) { int l_size; int l_done; NetlinkList *l_list; NetlinkList *l_end; if(netlink_send(p_socket, p_request) < 0) { return NULL; } l_list = NULL; l_end = NULL; l_done = 0; while(!l_done) { NetlinkList *l_item; struct nlmsghdr *l_hdr = getNetlinkResponse(p_socket, p_pid, &l_size, &l_done); /* Error */ if(!l_hdr) { freeResultList(l_list); return NULL; } l_item = newListItem(l_hdr, l_size); if (!l_item) { freeResultList(l_list); return NULL; } if(!l_list) { l_list = l_item; } else { l_end->m_next = l_item; } l_end = l_item; } return l_list; } static size_t maxSize(size_t a, size_t b) { return (a > b ? a : b); } static size_t calcAddrLen(sa_family_t p_family, int p_dataSize) { switch(p_family) { case AF_INET: return sizeof(struct sockaddr_in); case AF_INET6: return sizeof(struct sockaddr_in6); case AF_PACKET: return maxSize(sizeof(struct sockaddr_ll), offsetof(struct sockaddr_ll, sll_addr) + p_dataSize); default: return maxSize(sizeof(struct sockaddr), offsetof(struct sockaddr, sa_data) + p_dataSize); } } static void makeSockaddr(sa_family_t p_family, struct sockaddr *p_dest, void *p_data, size_t p_size) { switch(p_family) { case AF_INET: memcpy(&((struct sockaddr_in*)p_dest)->sin_addr, p_data, p_size); break; case AF_INET6: memcpy(&((struct sockaddr_in6*)p_dest)->sin6_addr, p_data, p_size); break; case AF_PACKET: memcpy(((struct sockaddr_ll*)p_dest)->sll_addr, p_data, p_size); ((struct sockaddr_ll*)p_dest)->sll_halen = p_size; break; default: memcpy(p_dest->sa_data, p_data, p_size); break; } p_dest->sa_family = p_family; } static void addToEnd(struct ifaddrs **p_resultList, struct ifaddrs *p_entry) { if(!*p_resultList) { *p_resultList = p_entry; } else { struct ifaddrs *l_cur = *p_resultList; while(l_cur->ifa_next) { l_cur = l_cur->ifa_next; } l_cur->ifa_next = p_entry; } } static int interpretLink(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList) { struct ifaddrs *l_entry; char *l_index; char *l_name; char *l_addr; char *l_data; struct ifinfomsg *l_info = (struct ifinfomsg *)NLMSG_DATA(p_hdr); size_t l_nameSize = 0; size_t l_addrSize = 0; size_t l_dataSize = 0; size_t l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifinfomsg)); struct rtattr *l_rta; for(l_rta = IFLA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize)) { size_t l_rtaDataSize = RTA_PAYLOAD(l_rta); switch(l_rta->rta_type) { case IFLA_ADDRESS: case IFLA_BROADCAST: l_addrSize += NLMSG_ALIGN(calcAddrLen(AF_PACKET, l_rtaDataSize)); break; case IFLA_IFNAME: l_nameSize += NLMSG_ALIGN(l_rtaSize + 1); break; case IFLA_STATS: l_dataSize += NLMSG_ALIGN(l_rtaSize); break; default: break; } } l_entry = uv__malloc(sizeof(struct ifaddrs) + sizeof(int) + l_nameSize + l_addrSize + l_dataSize); if (l_entry == NULL) { return -1; } memset(l_entry, 0, sizeof(struct ifaddrs)); l_entry->ifa_name = ""; l_index = ((char *)l_entry) + sizeof(struct ifaddrs); l_name = l_index + sizeof(int); l_addr = l_name + l_nameSize; l_data = l_addr + l_addrSize; /* Save the interface index so we can look it up when handling the * addresses. */ memcpy(l_index, &l_info->ifi_index, sizeof(int)); l_entry->ifa_flags = l_info->ifi_flags; l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifinfomsg)); for(l_rta = IFLA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize)) { void *l_rtaData = RTA_DATA(l_rta); size_t l_rtaDataSize = RTA_PAYLOAD(l_rta); switch(l_rta->rta_type) { case IFLA_ADDRESS: case IFLA_BROADCAST: { size_t l_addrLen = calcAddrLen(AF_PACKET, l_rtaDataSize); makeSockaddr(AF_PACKET, (struct sockaddr *)l_addr, l_rtaData, l_rtaDataSize); ((struct sockaddr_ll *)l_addr)->sll_ifindex = l_info->ifi_index; ((struct sockaddr_ll *)l_addr)->sll_hatype = l_info->ifi_type; if(l_rta->rta_type == IFLA_ADDRESS) { l_entry->ifa_addr = (struct sockaddr *)l_addr; } else { l_entry->ifa_broadaddr = (struct sockaddr *)l_addr; } l_addr += NLMSG_ALIGN(l_addrLen); break; } case IFLA_IFNAME: strncpy(l_name, l_rtaData, l_rtaDataSize); l_name[l_rtaDataSize] = '\0'; l_entry->ifa_name = l_name; break; case IFLA_STATS: memcpy(l_data, l_rtaData, l_rtaDataSize); l_entry->ifa_data = l_data; break; default: break; } } addToEnd(p_resultList, l_entry); return 0; } static struct ifaddrs *findInterface(int p_index, struct ifaddrs **p_links, int p_numLinks) { int l_num = 0; struct ifaddrs *l_cur = *p_links; while(l_cur && l_num < p_numLinks) { char *l_indexPtr = ((char *)l_cur) + sizeof(struct ifaddrs); int l_index; memcpy(&l_index, l_indexPtr, sizeof(int)); if(l_index == p_index) { return l_cur; } l_cur = l_cur->ifa_next; ++l_num; } return NULL; } static int interpretAddr(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList, int p_numLinks) { struct ifaddrmsg *l_info = (struct ifaddrmsg *)NLMSG_DATA(p_hdr); struct ifaddrs *l_interface = findInterface(l_info->ifa_index, p_resultList, p_numLinks); size_t l_nameSize = 0; size_t l_addrSize = 0; int l_addedNetmask = 0; size_t l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifaddrmsg)); struct rtattr *l_rta; struct ifaddrs *l_entry; char *l_name; char *l_addr; for(l_rta = IFA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize)) { size_t l_rtaDataSize = RTA_PAYLOAD(l_rta); if(l_info->ifa_family == AF_PACKET) { continue; } switch(l_rta->rta_type) { case IFA_ADDRESS: case IFA_LOCAL: if((l_info->ifa_family == AF_INET || l_info->ifa_family == AF_INET6) && !l_addedNetmask) { /* Make room for netmask */ l_addrSize += NLMSG_ALIGN(calcAddrLen(l_info->ifa_family, l_rtaDataSize)); l_addedNetmask = 1; } case IFA_BROADCAST: l_addrSize += NLMSG_ALIGN(calcAddrLen(l_info->ifa_family, l_rtaDataSize)); break; case IFA_LABEL: l_nameSize += NLMSG_ALIGN(l_rtaDataSize + 1); break; default: break; } } l_entry = uv__malloc(sizeof(struct ifaddrs) + l_nameSize + l_addrSize); if (l_entry == NULL) { return -1; } memset(l_entry, 0, sizeof(struct ifaddrs)); l_entry->ifa_name = (l_interface ? l_interface->ifa_name : ""); l_name = ((char *)l_entry) + sizeof(struct ifaddrs); l_addr = l_name + l_nameSize; l_entry->ifa_flags = l_info->ifa_flags; if(l_interface) { l_entry->ifa_flags |= l_interface->ifa_flags; } l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifaddrmsg)); for(l_rta = IFA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize)) { void *l_rtaData = RTA_DATA(l_rta); size_t l_rtaDataSize = RTA_PAYLOAD(l_rta); switch(l_rta->rta_type) { case IFA_ADDRESS: case IFA_BROADCAST: case IFA_LOCAL: { size_t l_addrLen = calcAddrLen(l_info->ifa_family, l_rtaDataSize); makeSockaddr(l_info->ifa_family, (struct sockaddr *)l_addr, l_rtaData, l_rtaDataSize); if(l_info->ifa_family == AF_INET6) { if(IN6_IS_ADDR_LINKLOCAL((struct in6_addr *)l_rtaData) || IN6_IS_ADDR_MC_LINKLOCAL((struct in6_addr *)l_rtaData)) { ((struct sockaddr_in6 *)l_addr)->sin6_scope_id = l_info->ifa_index; } } /* Apparently in a point-to-point network IFA_ADDRESS contains * the dest address and IFA_LOCAL contains the local address */ if(l_rta->rta_type == IFA_ADDRESS) { if(l_entry->ifa_addr) { l_entry->ifa_dstaddr = (struct sockaddr *)l_addr; } else { l_entry->ifa_addr = (struct sockaddr *)l_addr; } } else if(l_rta->rta_type == IFA_LOCAL) { if(l_entry->ifa_addr) { l_entry->ifa_dstaddr = l_entry->ifa_addr; } l_entry->ifa_addr = (struct sockaddr *)l_addr; } else { l_entry->ifa_broadaddr = (struct sockaddr *)l_addr; } l_addr += NLMSG_ALIGN(l_addrLen); break; } case IFA_LABEL: strncpy(l_name, l_rtaData, l_rtaDataSize); l_name[l_rtaDataSize] = '\0'; l_entry->ifa_name = l_name; break; default: break; } } if(l_entry->ifa_addr && (l_entry->ifa_addr->sa_family == AF_INET || l_entry->ifa_addr->sa_family == AF_INET6)) { unsigned l_maxPrefix = (l_entry->ifa_addr->sa_family == AF_INET ? 32 : 128); unsigned l_prefix = (l_info->ifa_prefixlen > l_maxPrefix ? l_maxPrefix : l_info->ifa_prefixlen); unsigned char l_mask[16] = {0}; unsigned i; for(i=0; i<(l_prefix/8); ++i) { l_mask[i] = 0xff; } if(l_prefix % 8) { l_mask[i] = 0xff << (8 - (l_prefix % 8)); } makeSockaddr(l_entry->ifa_addr->sa_family, (struct sockaddr *)l_addr, l_mask, l_maxPrefix / 8); l_entry->ifa_netmask = (struct sockaddr *)l_addr; } addToEnd(p_resultList, l_entry); return 0; } static int interpretLinks(int p_socket, pid_t p_pid, NetlinkList *p_netlinkList, struct ifaddrs **p_resultList) { int l_numLinks = 0; for(; p_netlinkList; p_netlinkList = p_netlinkList->m_next) { unsigned int l_nlsize = p_netlinkList->m_size; struct nlmsghdr *l_hdr; for(l_hdr = p_netlinkList->m_data; NLMSG_OK(l_hdr, l_nlsize); l_hdr = NLMSG_NEXT(l_hdr, l_nlsize)) { if((pid_t)l_hdr->nlmsg_pid != p_pid || (int)l_hdr->nlmsg_seq != p_socket) { continue; } if(l_hdr->nlmsg_type == NLMSG_DONE) { break; } if(l_hdr->nlmsg_type == RTM_NEWLINK) { if(interpretLink(l_hdr, p_resultList) == -1) { return -1; } ++l_numLinks; } } } return l_numLinks; } static int interpretAddrs(int p_socket, pid_t p_pid, NetlinkList *p_netlinkList, struct ifaddrs **p_resultList, int p_numLinks) { for(; p_netlinkList; p_netlinkList = p_netlinkList->m_next) { unsigned int l_nlsize = p_netlinkList->m_size; struct nlmsghdr *l_hdr; for(l_hdr = p_netlinkList->m_data; NLMSG_OK(l_hdr, l_nlsize); l_hdr = NLMSG_NEXT(l_hdr, l_nlsize)) { if((pid_t)l_hdr->nlmsg_pid != p_pid || (int)l_hdr->nlmsg_seq != p_socket) { continue; } if(l_hdr->nlmsg_type == NLMSG_DONE) { break; } if(l_hdr->nlmsg_type == RTM_NEWADDR) { if (interpretAddr(l_hdr, p_resultList, p_numLinks) == -1) { return -1; } } } } return 0; } int getifaddrs(struct ifaddrs **ifap) { int l_socket; int l_result; int l_numLinks; pid_t l_pid; NetlinkList *l_linkResults; NetlinkList *l_addrResults; if(!ifap) { return -1; } *ifap = NULL; l_socket = netlink_socket(&l_pid); if(l_socket < 0) { return -1; } l_linkResults = getResultList(l_socket, RTM_GETLINK, l_pid); if(!l_linkResults) { close(l_socket); return -1; } l_addrResults = getResultList(l_socket, RTM_GETADDR, l_pid); if(!l_addrResults) { close(l_socket); freeResultList(l_linkResults); return -1; } l_result = 0; l_numLinks = interpretLinks(l_socket, l_pid, l_linkResults, ifap); if(l_numLinks == -1 || interpretAddrs(l_socket, l_pid, l_addrResults, ifap, l_numLinks) == -1) { l_result = -1; } freeResultList(l_linkResults); freeResultList(l_addrResults); close(l_socket); return l_result; } void freeifaddrs(struct ifaddrs *ifa) { struct ifaddrs *l_cur; while(ifa) { l_cur = ifa; ifa = ifa->ifa_next; uv__free(l_cur); } }
c342a80578abfb47f5d448826fbc1b5691473d26
58fe7cb3949dd1930e709696659a0296500b64a6
/tests/unit/s2n_pq_kem_kat_kyber_r3_test.c
66e7202760808e0d53c22447b857a54d08e4ccc0
[ "Apache-2.0", "MIT" ]
permissive
aws/s2n-tls
3344638a6a69c6f20665cf6847e1bc4b85f2e558
62dc7a6d4876e5eee0dea3690d528a4c7080a1d5
refs/heads/main
2023-08-31T23:26:33.780048
2023-08-31T05:17:33
2023-08-31T05:17:33
21,287,076
513
213
Apache-2.0
2023-09-13T23:52:29
2014-06-27T19:37:59
C
UTF-8
C
false
false
1,894
c
s2n_pq_kem_kat_kyber_r3_test.c
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "pq-crypto/s2n_pq.h" #include "s2n_test.h" #include "tests/testlib/s2n_testlib.h" static const struct s2n_kem_kat_test_vector test_vectors[] = { { .kem = &s2n_kyber_512_r3, .kat_file = "kats/kyber_r3.kat", .asm_is_enabled = s2n_pq_no_asm_available, .enable_asm = s2n_pq_noop_asm, .disable_asm = s2n_pq_noop_asm, }, { .kem = &s2n_kyber_512_r3, .kat_file = "kats/kyber_r3.kat", .asm_is_enabled = s2n_kyber512r3_is_avx2_bmi2_enabled, .enable_asm = s2n_try_enable_kyber512r3_opt_avx2_bmi2, .disable_asm = s2n_disable_kyber512r3_opt_avx2_bmi2, }, }; int main() { BEGIN_TEST(); if (!s2n_pq_is_enabled() || s2n_libcrypto_supports_kyber()) { /* The KAT tests rely on the low-level PQ crypto functions; * there is nothing to test if PQ is disabled. * * In the case where we are using AWS-LC backed PQ, we rely on the * KAT tests implemented in the AWS-LC repository. Implementing these * tests within S2N is impossible due to the lack of AWS-LC interfaces * for initializing the RNG. */ END_TEST(); } EXPECT_OK(s2n_pq_kem_kat_test(test_vectors, s2n_array_len(test_vectors))); END_TEST(); }
ccfcda33fa30e0fa3593c19b3402a52ad0880aee
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
/PWGJE/EMCALJetTasks/macros/AddTaskFlowQnVectorCorrections.C
e35b85e3b59b474f436ebfbe151f5c60c2d7322d
[]
permissive
alisw/AliPhysics
91bf1bd01ab2af656a25ff10b25e618a63667d3e
5df28b2b415e78e81273b0d9bf5c1b99feda3348
refs/heads/master
2023-08-31T20:41:44.927176
2023-08-31T14:51:12
2023-08-31T14:51:12
61,661,378
129
1,150
BSD-3-Clause
2023-09-14T18:48:45
2016-06-21T19:31:29
C++
UTF-8
C
false
false
267
c
AddTaskFlowQnVectorCorrections.C
AliAnalysisTaskFlowVectorCorrections* AddTaskFlowQnVectorCorrections(const char* configFilename) { AliAnalysisTaskFlowVectorCorrections* task = PWGJE::EMCALJetTasks::AliAnalysisTaskEmcalJetHUtils::AddTaskFlowQnVectorCorrections(configFilename); return task; }
81e3afe2bac10cf19ef059b91e9013f7d342db03
035660e8cc10571ebbd0d4393fef063bb7eb98f6
/src/overlays/actors/ovl_Bg_Lotus/z_bg_lotus.c
765b58dbda2f81749781dc82d9ec66892a3dfad0
[]
no_license
zeldaret/mm
f163a5e7c4314105777369fa7671ce9c2a99922a
4ae00e909e74044f05155683b49d2561f91de7ba
refs/heads/master
2023-08-06T07:22:04.912966
2023-08-04T20:36:03
2023-08-04T20:36:03
247,875,852
915
328
null
2023-09-14T11:48:59
2020-03-17T04:03:07
C
UTF-8
C
false
false
1,223
c
z_bg_lotus.c
#include "z_bg_lotus.h" #include "objects/object_lotus/object_lotus.h" #define FLAGS 0x00000000 #define THIS ((BgLotus*)thisx) void BgLotus_Init(Actor* thisx, PlayState* play); void BgLotus_Destroy(Actor* thisx, PlayState* play); void BgLotus_Update(Actor* thisx, PlayState* play); void BgLotus_Draw(Actor* thisx, PlayState* play); /* const ActorInit Bg_Lotus_InitVars = { ACTOR_BG_LOTUS, ACTORCAT_BG, FLAGS, OBJECT_LOTUS, sizeof(BgLotus), (ActorFunc)BgLotus_Init, (ActorFunc)BgLotus_Destroy, (ActorFunc)BgLotus_Update, (ActorFunc)BgLotus_Draw }; */ #pragma GLOBAL_ASM("asm/non_matchings/overlays/ovl_Bg_Lotus/BgLotus_Init.s") #pragma GLOBAL_ASM("asm/non_matchings/overlays/ovl_Bg_Lotus/BgLotus_Destroy.s") #pragma GLOBAL_ASM("asm/non_matchings/overlays/ovl_Bg_Lotus/func_80AD6830.s") #pragma GLOBAL_ASM("asm/non_matchings/overlays/ovl_Bg_Lotus/func_80AD68DC.s") #pragma GLOBAL_ASM("asm/non_matchings/overlays/ovl_Bg_Lotus/func_80AD6A88.s") #pragma GLOBAL_ASM("asm/non_matchings/overlays/ovl_Bg_Lotus/func_80AD6B68.s") #pragma GLOBAL_ASM("asm/non_matchings/overlays/ovl_Bg_Lotus/BgLotus_Update.s") #pragma GLOBAL_ASM("asm/non_matchings/overlays/ovl_Bg_Lotus/BgLotus_Draw.s")
387b3b75706f9619648612b9bd4b5616ec368614
7c857119fe1505b1d80d6e62969661c06dc1a2f4
/NetworkPkg/DnsDxe/DnsImpl.h
fdab9c75e3f385624a33fa74b0bb71e6f851fd5d
[ "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
43,789
h
DnsImpl.h
/** @file DnsDxe support functions implementation. Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef __EFI_DNS_IMPL_H_ #define __EFI_DNS_IMPL_H_ #include <Uefi.h> // // Libraries classes // #include <Library/BaseLib.h> #include <Library/UefiLib.h> #include <Library/UefiBootServicesTableLib.h> #include <Library/UefiDriverEntryPoint.h> #include <Library/UefiRuntimeServicesTableLib.h> #include <Library/BaseMemoryLib.h> #include <Library/MemoryAllocationLib.h> #include <Library/NetLib.h> #include <Library/DebugLib.h> #include <Library/DpcLib.h> #include <Library/PrintLib.h> #include <Library/UdpIoLib.h> // // UEFI Driver Model Protocols // #include <Protocol/DriverBinding.h> #include <Protocol/ComponentName2.h> #include <Protocol/ComponentName.h> #include <Protocol/Udp4.h> #include <Protocol/Dhcp4.h> #include <Protocol/Dns4.h> #include <Protocol/Udp6.h> #include <Protocol/Dhcp6.h> #include <Protocol/Dns6.h> #include <Protocol/Ip4Config2.h> #include "DnsDriver.h" #include "DnsDhcp.h" // // Driver Version // #define DNS_VERSION 0x00000000 // // Protocol instances // extern EFI_COMPONENT_NAME_PROTOCOL gDnsComponentName; extern EFI_COMPONENT_NAME2_PROTOCOL gDnsComponentName2; extern EFI_UNICODE_STRING_TABLE *gDnsControllerNameTable; extern EFI_DRIVER_BINDING_PROTOCOL gDns4DriverBinding; extern EFI_SERVICE_BINDING_PROTOCOL mDns4ServiceBinding; extern EFI_DNS4_PROTOCOL mDns4Protocol; extern EFI_DRIVER_BINDING_PROTOCOL gDns6DriverBinding; extern EFI_SERVICE_BINDING_PROTOCOL mDns6ServiceBinding; extern EFI_DNS6_PROTOCOL mDns6Protocol; // // DNS related // #define DNS_SERVER_PORT 53 #define DNS_PROTOCOL_UDP EFI_IP_PROTO_UDP #define DNS_PROTOCOL_TCP EFI_IP_PROTO_TCP #define DNS_STATE_UNCONFIGED 0 #define DNS_STATE_CONFIGED 1 #define DNS_STATE_DESTROY 2 #define DNS_DEFAULT_TIMEOUT 2 #define DNS_TIME_TO_GETMAP 5 #pragma pack(1) typedef union _DNS_FLAGS DNS_FLAGS; typedef struct { LIST_ENTRY AllCacheLink; EFI_DNS4_CACHE_ENTRY DnsCache; } DNS4_CACHE; typedef struct { LIST_ENTRY AllCacheLink; EFI_DNS6_CACHE_ENTRY DnsCache; } DNS6_CACHE; typedef struct { LIST_ENTRY AllServerLink; EFI_IPv4_ADDRESS Dns4ServerIp; } DNS4_SERVER_IP; typedef struct { LIST_ENTRY AllServerLink; EFI_IPv6_ADDRESS Dns6ServerIp; } DNS6_SERVER_IP; typedef struct { UINT32 RetryCounting; UINT32 PacketToLive; CHAR16 *QueryHostName; EFI_IPv4_ADDRESS QueryIpAddress; BOOLEAN GeneralLookUp; EFI_DNS4_COMPLETION_TOKEN *Token; } DNS4_TOKEN_ENTRY; typedef struct { UINT32 RetryCounting; UINT32 PacketToLive; CHAR16 *QueryHostName; EFI_IPv6_ADDRESS QueryIpAddress; BOOLEAN GeneralLookUp; EFI_DNS6_COMPLETION_TOKEN *Token; } DNS6_TOKEN_ENTRY; union _DNS_FLAGS{ struct { UINT16 RCode:4; UINT16 Zero:3; UINT16 RA:1; UINT16 RD:1; UINT16 TC:1; UINT16 AA:1; UINT16 OpCode:4; UINT16 QR:1; } Bits; UINT16 Uint16; }; #define DNS_FLAGS_QR_QUERY 0 #define DNS_FLAGS_QR_RESPONSE 1 #define DNS_FLAGS_OPCODE_STANDARD 0 #define DNS_FLAGS_OPCODE_INVERSE 1 #define DNS_FLAGS_OPCODE_SERVER_STATE 2 #define DNS_FLAGS_RCODE_NO_ERROR 0 #define DNS_FLAGS_RCODE_NAME_ERROR 3 typedef struct { UINT16 Identification; DNS_FLAGS Flags; UINT16 QuestionsNum; UINT16 AnswersNum; UINT16 AuthorityNum; UINT16 AditionalNum; } DNS_HEADER; typedef struct { UINT16 Type; UINT16 Class; } DNS_QUERY_SECTION; typedef struct { UINT16 Type; UINT16 Class; UINT32 Ttl; UINT16 DataLength; } DNS_ANSWER_SECTION; #define DNS4_DOMAIN L"in-addr.arpa" #define DNS6_DOMAIN L"IP6.ARPA" #pragma pack() /** Remove TokenEntry from TokenMap. @param[in] TokenMap All DNSv4 Token entrys. @param[in] TokenEntry TokenEntry need to be removed. @retval EFI_SUCCESS Remove TokenEntry from TokenMap sucessfully. @retval EFI_NOT_FOUND TokenEntry is not found in TokenMap. **/ EFI_STATUS Dns4RemoveTokenEntry ( IN NET_MAP *TokenMap, IN DNS4_TOKEN_ENTRY *TokenEntry ); /** Remove TokenEntry from TokenMap. @param[in] TokenMap All DNSv6 Token entrys. @param[in] TokenEntry TokenEntry need to be removed. @retval EFI_SUCCESS Remove TokenEntry from TokenMap sucessfully. @retval EFI_NOT_FOUND TokenEntry is not found in TokenMap. **/ EFI_STATUS Dns6RemoveTokenEntry ( IN NET_MAP *TokenMap, IN DNS6_TOKEN_ENTRY *TokenEntry ); /** This function cancle the token specified by Arg in the Map. @param[in] Map Pointer to the NET_MAP. @param[in] Item Pointer to the NET_MAP_ITEM. @param[in] Arg Pointer to the token to be cancelled. If NULL, all the tokens in this Map will be cancelled. This parameter is optional and may be NULL. @retval EFI_SUCCESS The token is cancelled if Arg is NULL, or the token is not the same as that in the Item, if Arg is not NULL. @retval EFI_ABORTED Arg is not NULL, and the token specified by Arg is cancelled. **/ EFI_STATUS EFIAPI Dns4CancelTokens ( IN NET_MAP *Map, IN NET_MAP_ITEM *Item, IN VOID *Arg OPTIONAL ); /** This function cancle the token specified by Arg in the Map. @param[in] Map Pointer to the NET_MAP. @param[in] Item Pointer to the NET_MAP_ITEM. @param[in] Arg Pointer to the token to be cancelled. If NULL, all the tokens in this Map will be cancelled. This parameter is optional and may be NULL. @retval EFI_SUCCESS The token is cancelled if Arg is NULL, or the token is not the same as that in the Item, if Arg is not NULL. @retval EFI_ABORTED Arg is not NULL, and the token specified by Arg is cancelled. **/ EFI_STATUS EFIAPI Dns6CancelTokens ( IN NET_MAP *Map, IN NET_MAP_ITEM *Item, IN VOID *Arg OPTIONAL ); /** Get the TokenEntry from the TokensMap. @param[in] TokensMap All DNSv4 Token entrys @param[in] Token Pointer to the token to be get. @param[out] TokenEntry Pointer to TokenEntry corresponding Token. @retval EFI_SUCCESS Get the TokenEntry from the TokensMap sucessfully. @retval EFI_NOT_FOUND TokenEntry is not found in TokenMap. **/ EFI_STATUS EFIAPI GetDns4TokenEntry ( IN NET_MAP *TokensMap, IN EFI_DNS4_COMPLETION_TOKEN *Token, OUT DNS4_TOKEN_ENTRY **TokenEntry ); /** Get the TokenEntry from the TokensMap. @param[in] TokensMap All DNSv6 Token entrys @param[in] Token Pointer to the token to be get. @param[out] TokenEntry Pointer to TokenEntry corresponding Token. @retval EFI_SUCCESS Get the TokenEntry from the TokensMap sucessfully. @retval EFI_NOT_FOUND TokenEntry is not found in TokenMap. **/ EFI_STATUS EFIAPI GetDns6TokenEntry ( IN NET_MAP *TokensMap, IN EFI_DNS6_COMPLETION_TOKEN *Token, OUT DNS6_TOKEN_ENTRY **TokenEntry ); /** Cancel DNS4 tokens from the DNS4 instance. @param[in] Instance Pointer to the DNS instance context data. @param[in] Token Pointer to the token to be canceled. If NULL, all tokens in this instance will be cancelled. This parameter is optional and may be NULL. @retval EFI_SUCCESS The Token is cancelled. @retval EFI_NOT_FOUND The Token is not found. **/ EFI_STATUS Dns4InstanceCancelToken ( IN DNS_INSTANCE *Instance, IN EFI_DNS4_COMPLETION_TOKEN *Token ); /** Cancel DNS6 tokens from the DNS6 instance. @param[in] Instance Pointer to the DNS instance context data. @param[in] Token Pointer to the token to be canceled. If NULL, all tokens in this instance will be cancelled. This parameter is optional and may be NULL. @retval EFI_SUCCESS The Token is cancelled. @retval EFI_NOT_FOUND The Token is not found. **/ EFI_STATUS Dns6InstanceCancelToken ( IN DNS_INSTANCE *Instance, IN EFI_DNS6_COMPLETION_TOKEN *Token ); /** Free the resource related to the configure parameters. @param Config The DNS configure data **/ VOID Dns4CleanConfigure ( IN OUT EFI_DNS4_CONFIG_DATA *Config ); /** Free the resource related to the configure parameters. @param Config The DNS configure data **/ VOID Dns6CleanConfigure ( IN OUT EFI_DNS6_CONFIG_DATA *Config ); /** Allocate memory for configure parameter such as timeout value for Dst, then copy the configure parameter from Src to Dst. @param[out] Dst The destination DHCP configure data. @param[in] Src The source DHCP configure data. @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. @retval EFI_SUCCESS The configure is copied. **/ EFI_STATUS Dns4CopyConfigure ( OUT EFI_DNS4_CONFIG_DATA *Dst, IN EFI_DNS4_CONFIG_DATA *Src ); /** Allocate memory for configure parameter such as timeout value for Dst, then copy the configure parameter from Src to Dst. @param[out] Dst The destination DHCP configure data. @param[in] Src The source DHCP configure data. @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. @retval EFI_SUCCESS The configure is copied. **/ EFI_STATUS Dns6CopyConfigure ( OUT EFI_DNS6_CONFIG_DATA *Dst, IN EFI_DNS6_CONFIG_DATA *Src ); /** Callback of Dns packet. Does nothing. @param Arg The context. **/ VOID EFIAPI DnsDummyExtFree ( IN VOID *Arg ); /** Poll the UDP to get the IP4 default address, which may be retrieved by DHCP. The default time out value is 5 seconds. If IP has retrieved the default address, the UDP is reconfigured. @param Instance The DNS instance @param UdpIo The UDP_IO to poll @param UdpCfgData The UDP configure data to reconfigure the UDP_IO @retval TRUE The default address is retrieved and UDP is reconfigured. @retval FALSE Some error occured. **/ BOOLEAN Dns4GetMapping ( IN DNS_INSTANCE *Instance, IN UDP_IO *UdpIo, IN EFI_UDP4_CONFIG_DATA *UdpCfgData ); /** Configure the opened Udp6 instance until the corresponding Ip6 instance has been configured. @param Instance The DNS instance @param UdpIo The UDP_IO to poll @param UdpCfgData The UDP configure data to reconfigure the UDP_IO @retval TRUE Configure the Udp6 instance successfully. @retval FALSE Some error occured. **/ BOOLEAN Dns6GetMapping ( IN DNS_INSTANCE *Instance, IN UDP_IO *UdpIo, IN EFI_UDP6_CONFIG_DATA *UdpCfgData ); /** Configure the UDP. @param Instance The DNS session @param UdpIo The UDP_IO instance @retval EFI_SUCCESS The UDP is successfully configured for the session. **/ EFI_STATUS Dns4ConfigUdp ( IN DNS_INSTANCE *Instance, IN UDP_IO *UdpIo ); /** Configure the UDP. @param Instance The DNS session @param UdpIo The UDP_IO instance @retval EFI_SUCCESS The UDP is successfully configured for the session. **/ EFI_STATUS Dns6ConfigUdp ( IN DNS_INSTANCE *Instance, IN UDP_IO *UdpIo ); /** Update Dns4 cache to shared list of caches of all DNSv4 instances. @param Dns4CacheList All Dns4 cache list. @param DeleteFlag If FALSE, this function is to add one entry to the DNS Cache. If TRUE, this function will delete matching DNS Cache entry. @param Override If TRUE, the matching DNS cache entry will be overwritten with the supplied parameter. If FALSE, EFI_ACCESS_DENIED will be returned if the entry to be added is already exists. @param DnsCacheEntry Entry Pointer to DNS Cache entry. @retval EFI_SUCCESS Update Dns4 cache successfully. @retval Others Failed to update Dns4 cache. **/ EFI_STATUS EFIAPI UpdateDns4Cache ( IN LIST_ENTRY *Dns4CacheList, IN BOOLEAN DeleteFlag, IN BOOLEAN Override, IN EFI_DNS4_CACHE_ENTRY DnsCacheEntry ); /** Update Dns6 cache to shared list of caches of all DNSv6 instances. @param Dns6CacheList All Dns6 cache list. @param DeleteFlag If FALSE, this function is to add one entry to the DNS Cache. If TRUE, this function will delete matching DNS Cache entry. @param Override If TRUE, the matching DNS cache entry will be overwritten with the supplied parameter. If FALSE, EFI_ACCESS_DENIED will be returned if the entry to be added is already exists. @param DnsCacheEntry Entry Pointer to DNS Cache entry. @retval EFI_SUCCESS Update Dns6 cache successfully. @retval Others Failed to update Dns6 cache. **/ EFI_STATUS EFIAPI UpdateDns6Cache ( IN LIST_ENTRY *Dns6CacheList, IN BOOLEAN DeleteFlag, IN BOOLEAN Override, IN EFI_DNS6_CACHE_ENTRY DnsCacheEntry ); /** Add Dns4 ServerIp to common list of addresses of all configured DNSv4 server. @param Dns4ServerList Common list of addresses of all configured DNSv4 server. @param ServerIp DNS server Ip. @retval EFI_SUCCESS Add Dns4 ServerIp to common list successfully. @retval Others Failed to add Dns4 ServerIp to common list. **/ EFI_STATUS EFIAPI AddDns4ServerIp ( IN LIST_ENTRY *Dns4ServerList, IN EFI_IPv4_ADDRESS ServerIp ); /** Add Dns6 ServerIp to common list of addresses of all configured DNSv6 server. @param Dns6ServerList Common list of addresses of all configured DNSv6 server. @param ServerIp DNS server Ip. @retval EFI_SUCCESS Add Dns6 ServerIp to common list successfully. @retval Others Failed to add Dns6 ServerIp to common list. **/ EFI_STATUS EFIAPI AddDns6ServerIp ( IN LIST_ENTRY *Dns6ServerList, IN EFI_IPv6_ADDRESS ServerIp ); /** Find out whether the response is valid or invalid. @param TokensMap All DNS transmittal Tokens entry. @param Identification Identification for queried packet. @param Type Type for queried packet. @param Class Class for queried packet. @param Item Return corresponding Token entry. @retval TRUE The response is valid. @retval FALSE The response is invalid. **/ BOOLEAN IsValidDnsResponse ( IN NET_MAP *TokensMap, IN UINT16 Identification, IN UINT16 Type, IN UINT16 Class, OUT NET_MAP_ITEM **Item ); /** Parse Dns Response. @param Instance The DNS instance @param RxString Received buffer. @param Length Received buffer length. @param Completed Flag to indicate that Dns response is valid. @retval EFI_SUCCESS Parse Dns Response successfully. @retval Others Failed to parse Dns Response. **/ EFI_STATUS ParseDnsResponse ( IN OUT DNS_INSTANCE *Instance, IN UINT8 *RxString, IN UINT32 Length, OUT BOOLEAN *Completed ); /** Parse response packet. @param Packet The packets received. @param EndPoint The local/remote UDP access point @param IoStatus The status of the UDP receive @param Context The opaque parameter to the function. **/ VOID EFIAPI DnsOnPacketReceived ( NET_BUF *Packet, UDP_END_POINT *EndPoint, EFI_STATUS IoStatus, VOID *Context ); /** Release the net buffer when packet is sent. @param Packet The packets received. @param EndPoint The local/remote UDP access point @param IoStatus The status of the UDP receive @param Context The opaque parameter to the function. **/ VOID EFIAPI DnsOnPacketSent ( NET_BUF *Packet, UDP_END_POINT *EndPoint, EFI_STATUS IoStatus, VOID *Context ); /** Query request information. @param Instance The DNS instance @param Packet The packet for querying request information. @retval EFI_SUCCESS Query request information successfully. @retval Others Failed to query request information. **/ EFI_STATUS DoDnsQuery ( IN DNS_INSTANCE *Instance, IN NET_BUF *Packet ); /** Construct the Packet according query section. @param Instance The DNS instance @param QueryName Queried Name @param Type Queried Type @param Class Queried Class @param Packet The packet for query @retval EFI_SUCCESS The packet is constructed. @retval Others Failed to construct the Packet. **/ EFI_STATUS ConstructDNSQuery ( IN DNS_INSTANCE *Instance, IN CHAR8 *QueryName, IN UINT16 Type, IN UINT16 Class, OUT NET_BUF **Packet ); /** Retransmit the packet. @param Instance The DNS instance @param Packet Retransmit the packet @retval EFI_SUCCESS The packet is retransmitted. @retval Others Failed to retransmit. **/ EFI_STATUS DnsRetransmit ( IN DNS_INSTANCE *Instance, IN NET_BUF *Packet ); /** The timer ticking function for the DNS service. @param Event The ticking event @param Context The DNS service instance **/ VOID EFIAPI DnsOnTimerRetransmit ( IN EFI_EVENT Event, IN VOID *Context ); /** The timer ticking function for the DNS driver. @param Event The ticking event @param Context NULL **/ VOID EFIAPI DnsOnTimerUpdate ( IN EFI_EVENT Event, IN VOID *Context ); /** Retrieve mode data of this DNS instance. This function is used to retrieve DNS mode data for this DNS instance. @param[in] This Pointer to EFI_DNS4_PROTOCOL instance. @param[out] DnsModeData Point to the mode data. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_NOT_STARTED When DnsConfigData is queried, no configuration data is available because this instance has not been configured. @retval EFI_INVALID_PARAMETER This is NULL or DnsModeData is NULL. @retval EFI_OUT_OF_RESOURCES Failed to allocate needed resources. **/ EFI_STATUS EFIAPI Dns4GetModeData ( IN EFI_DNS4_PROTOCOL *This, OUT EFI_DNS4_MODE_DATA *DnsModeData ); /** Configure this DNS instance. This function is used to configure DNS mode data for this DNS instance. @param[in] This Pointer to EFI_DNS4_PROTOCOL instance. @param[in] DnsConfigData Point to the Configuration data. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_UNSUPPORTED The designated protocol is not supported. @retval EFI_INVALID_PARAMTER Thisis NULL. The StationIp address provided in DnsConfigData is not a valid unicast. DnsServerList is NULL while DnsServerListCount is not ZERO. DnsServerListCount is ZERO while DnsServerList is not NULL @retval EFI_OUT_OF_RESOURCES The DNS instance data or required space could not be allocated. @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. The EFI DNSv4 Protocol instance is not configured. @retval EFI_ALREADY_STARTED Second call to Configure() with DnsConfigData. To reconfigure the instance the caller must call Configure() with NULL first to return driver to unconfigured state. **/ EFI_STATUS EFIAPI Dns4Configure ( IN EFI_DNS4_PROTOCOL *This, IN EFI_DNS4_CONFIG_DATA *DnsConfigData ); /** Host name to host address translation. The HostNameToIp () function is used to translate the host name to host IP address. A type A query is used to get the one or more IP addresses for this host. @param[in] This Pointer to EFI_DNS4_PROTOCOL instance. @param[in] HostName Host name. @param[in] Token Point to the completion token to translate host name to host address. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE: This is NULL. Token is NULL. Token.Event is NULL. HostName is NULL. HostName string is unsupported format. @retval EFI_NO_MAPPING There's no source address is available for use. @retval EFI_NOT_STARTED This instance has not been started. **/ EFI_STATUS EFIAPI Dns4HostNameToIp ( IN EFI_DNS4_PROTOCOL *This, IN CHAR16 *HostName, IN EFI_DNS4_COMPLETION_TOKEN *Token ); /** IPv4 address to host name translation also known as Reverse DNS lookup. The IpToHostName() function is used to translate the host address to host name. A type PTR query is used to get the primary name of the host. Support of this function is optional. @param[in] This Pointer to EFI_DNS4_PROTOCOL instance. @param[in] IpAddress Ip Address. @param[in] Token Point to the completion token to translate host address to host name. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_UNSUPPORTED This function is not supported. @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE: This is NULL. Token is NULL. Token.Event is NULL. IpAddress is not valid IP address . @retval EFI_NO_MAPPING There's no source address is available for use. @retval EFI_ALREADY_STARTED This Token is being used in another DNS session. @retval EFI_OUT_OF_RESOURCES Failed to allocate needed resources. **/ EFI_STATUS EFIAPI Dns4IpToHostName ( IN EFI_DNS4_PROTOCOL *This, IN EFI_IPv4_ADDRESS IpAddress, IN EFI_DNS4_COMPLETION_TOKEN *Token ); /** Retrieve arbitrary information from the DNS server. This GeneralLookup() function retrieves arbitrary information from the DNS. The caller supplies a QNAME, QTYPE, and QCLASS, and all of the matching RRs are returned. All RR content (e.g., TTL) was returned. The caller need parse the returned RR to get required information. The function is optional. @param[in] This Pointer to EFI_DNS4_PROTOCOL instance. @param[in] QName Pointer to Query Name. @param[in] QType Query Type. @param[in] QClass Query Name. @param[in] Token Point to the completion token to retrieve arbitrary information. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_UNSUPPORTED This function is not supported. Or the requested QType is not supported @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE: This is NULL. Token is NULL. Token.Event is NULL. QName is NULL. @retval EFI_NO_MAPPING There's no source address is available for use. @retval EFI_ALREADY_STARTED This Token is being used in another DNS session. @retval EFI_OUT_OF_RESOURCES Failed to allocate needed resources. **/ EFI_STATUS EFIAPI Dns4GeneralLookUp ( IN EFI_DNS4_PROTOCOL *This, IN CHAR8 *QName, IN UINT16 QType, IN UINT16 QClass, IN EFI_DNS4_COMPLETION_TOKEN *Token ); /** This function is to update the DNS Cache. The UpdateDnsCache() function is used to add/delete/modify DNS cache entry. DNS cache can be normally dynamically updated after the DNS resolve succeeds. This function provided capability to manually add/delete/modify the DNS cache. @param[in] This Pointer to EFI_DNS4_PROTOCOL instance. @param[in] DeleteFlag If FALSE, this function is to add one entry to the DNS Cahce. If TRUE, this function will delete matching DNS Cache entry. @param[in] Override If TRUE, the maching DNS cache entry will be overwritten with the supplied parameter. If FALSE, EFI_ACCESS_DENIED will be returned if the entry to be added is already existed. @param[in] DnsCacheEntry Pointer to DNS Cache entry. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE: This is NULL. DnsCacheEntry.HostName is NULL. DnsCacheEntry.IpAddress is NULL. DnsCacheEntry.Timeout is zero. @retval EFI_ACCESS_DENIED The DNS cache entry already exists and Override is not TRUE. **/ EFI_STATUS EFIAPI Dns4UpdateDnsCache ( IN EFI_DNS4_PROTOCOL *This, IN BOOLEAN DeleteFlag, IN BOOLEAN Override, IN EFI_DNS4_CACHE_ENTRY DnsCacheEntry ); /** Polls for incoming data packets and processes outgoing data packets. The Poll() function can be used by network drivers and applications to increase the rate that data packets are moved between the communications device and the transmit and receive queues. In some systems, the periodic timer event in the managed network driver may not poll the underlying communications device fast enough to transmit and/or receive all data packets without missing incoming packets or dropping outgoing packets. Drivers and applications that are experiencing packet loss should try calling the Poll() function more often. @param[in] This Pointer to EFI_DNS4_PROTOCOL instance. @retval EFI_SUCCESS Incoming or outgoing data was processed. @retval EFI_NOT_STARTED This EFI DNS Protocol instance has not been started. @retval EFI_INVALID_PARAMETER This is NULL. @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. @retval EFI_TIMEOUT Data was dropped out of the transmit and/or receive queue. Consider increasing the polling rate. **/ EFI_STATUS EFIAPI Dns4Poll ( IN EFI_DNS4_PROTOCOL *This ); /** Abort an asynchronous DNS operation, including translation between IP and Host, and general look up behavior. The Cancel() function is used to abort a pending resolution request. After calling this function, Token.Status will be set to EFI_ABORTED and then Token.Event will be signaled. If the token is not in one of the queues, which usually means that the asynchronous operation has completed, this function will not signal the token and EFI_NOT_FOUND is returned. @param[in] This Pointer to EFI_DNS4_PROTOCOL instance. @param[in] Token Pointer to a token that has been issued by EFI_DNS4_PROTOCOL.HostNameToIp (), EFI_DNS4_PROTOCOL.IpToHostName() or EFI_DNS4_PROTOCOL.GeneralLookup(). If NULL, all pending tokens are aborted. @retval EFI_SUCCESS Incoming or outgoing data was processed. @retval EFI_NOT_STARTED This EFI DNS4 Protocol instance has not been started. @retval EFI_INVALID_PARAMETER This is NULL. @retval EFI_NOT_FOUND When Token is not NULL, and the asynchronous DNS operation was not found in the transmit queue. It was either completed or was not issued by HostNameToIp(), IpToHostName() or GeneralLookup(). **/ EFI_STATUS EFIAPI Dns4Cancel ( IN EFI_DNS4_PROTOCOL *This, IN EFI_DNS4_COMPLETION_TOKEN *Token ); /** Retrieve mode data of this DNS instance. This function is used to retrieve DNS mode data for this DNS instance. @param[in] This Pointer to EFI_DNS6_PROTOCOL instance. @param[out] DnsModeData Pointer to the caller-allocated storage for the EFI_DNS6_MODE_DATA data. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_NOT_STARTED When DnsConfigData is queried, no configuration data is available because this instance has not been configured. @retval EFI_INVALID_PARAMETER This is NULL or DnsModeData is NULL. @retval EFI_OUT_OF_RESOURCE Failed to allocate needed resources. **/ EFI_STATUS EFIAPI Dns6GetModeData ( IN EFI_DNS6_PROTOCOL *This, OUT EFI_DNS6_MODE_DATA *DnsModeData ); /** Configure this DNS instance. The Configure() function is used to set and change the configuration data for this EFI DNSv6 Protocol driver instance. Reset the DNS instance if DnsConfigData is NULL. @param[in] This Pointer to EFI_DNS6_PROTOCOL instance. @param[in] DnsConfigData Pointer to the configuration data structure. All associated storage to be allocated and released by caller. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_INVALID_PARAMTER This is NULL. The StationIp address provided in DnsConfigData is not zero and not a valid unicast. DnsServerList is NULL while DnsServerList Count is not ZERO. DnsServerList Count is ZERO while DnsServerList is not NULL. @retval EFI_OUT_OF_RESOURCES The DNS instance data or required space could not be allocated. @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. The EFI DNSv6 Protocol instance is not configured. @retval EFI_UNSUPPORTED The designated protocol is not supported. @retval EFI_ALREADY_STARTED Second call to Configure() with DnsConfigData. To reconfigure the instance the caller must call Configure() with NULL first to return driver to unconfigured state. **/ EFI_STATUS EFIAPI Dns6Configure ( IN EFI_DNS6_PROTOCOL *This, IN EFI_DNS6_CONFIG_DATA *DnsConfigData ); /** Host name to host address translation. The HostNameToIp () function is used to translate the host name to host IP address. A type AAAA query is used to get the one or more IPv6 addresses for this host. @param[in] This Pointer to EFI_DNS6_PROTOCOL instance. @param[in] HostName Host name. @param[in] Token Point to the completion token to translate host name to host address. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE: This is NULL. Token is NULL. Token.Event is NULL. HostName is NULL or buffer contained unsupported characters. @retval EFI_NO_MAPPING There's no source address is available for use. @retval EFI_ALREADY_STARTED This Token is being used in another DNS session. @retval EFI_NOT_STARTED This instance has not been started. @retval EFI_OUT_OF_RESOURCES Failed to allocate needed resources. **/ EFI_STATUS EFIAPI Dns6HostNameToIp ( IN EFI_DNS6_PROTOCOL *This, IN CHAR16 *HostName, IN EFI_DNS6_COMPLETION_TOKEN *Token ); /** Host address to host name translation. The IpToHostName () function is used to translate the host address to host name. A type PTR query is used to get the primary name of the host. Implementation can choose to support this function or not. @param[in] This Pointer to EFI_DNS6_PROTOCOL instance. @param[in] IpAddress Ip Address. @param[in] Token Point to the completion token to translate host address to host name. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_UNSUPPORTED This function is not supported. @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE: This is NULL. Token is NULL. Token.Event is NULL. IpAddress is not valid IP address. @retval EFI_NO_MAPPING There's no source address is available for use. @retval EFI_NOT_STARTED This instance has not been started. @retval EFI_OUT_OF_RESOURCES Failed to allocate needed resources. **/ EFI_STATUS EFIAPI Dns6IpToHostName ( IN EFI_DNS6_PROTOCOL *This, IN EFI_IPv6_ADDRESS IpAddress, IN EFI_DNS6_COMPLETION_TOKEN *Token ); /** This function provides capability to retrieve arbitrary information from the DNS server. This GeneralLookup() function retrieves arbitrary information from the DNS. The caller supplies a QNAME, QTYPE, and QCLASS, and all of the matching RRs are returned. All RR content (e.g., TTL) was returned. The caller need parse the returned RR to get required information. The function is optional. Implementation can choose to support it or not. @param[in] This Pointer to EFI_DNS6_PROTOCOL instance. @param[in] QName Pointer to Query Name. @param[in] QType Query Type. @param[in] QClass Query Name. @param[in] Token Point to the completion token to retrieve arbitrary information. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_UNSUPPORTED This function is not supported. Or the requested QType is not supported @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE: This is NULL. Token is NULL. Token.Event is NULL. QName is NULL. @retval EFI_NO_MAPPING There's no source address is available for use. @retval EFI_NOT_STARTED This instance has not been started. @retval EFI_OUT_OF_RESOURCES Failed to allocate needed resources. **/ EFI_STATUS EFIAPI Dns6GeneralLookUp ( IN EFI_DNS6_PROTOCOL *This, IN CHAR8 *QName, IN UINT16 QType, IN UINT16 QClass, IN EFI_DNS6_COMPLETION_TOKEN *Token ); /** This function is to update the DNS Cache. The UpdateDnsCache() function is used to add/delete/modify DNS cache entry. DNS cache can be normally dynamically updated after the DNS resolve succeeds. This function provided capability to manually add/delete/modify the DNS cache. @param[in] This Pointer to EFI_DNS6_PROTOCOL instance. @param[in] DeleteFlag If FALSE, this function is to add one entry to the DNS Cahce. If TRUE, this function will delete matching DNS Cache entry. @param[in] Override If TRUE, the maching DNS cache entry will be overwritten with the supplied parameter. If FALSE, EFI_ACCESS_DENIED will be returned if the entry to be added is already existed. @param[in] DnsCacheEntry Pointer to DNS Cache entry. @retval EFI_SUCCESS The operation completed successfully. @retval EFI_INVALID_PARAMETER One or more of the following conditions is TRUE: This is NULL. DnsCacheEntry.HostName is NULL. DnsCacheEntry.IpAddress is NULL. DnsCacheEntry.Timeout is zero. @retval EFI_ACCESS_DENIED The DNS cache entry already exists and Override is not TRUE. @retval EFI_OUT_OF_RESOURCE Failed to allocate needed resources. **/ EFI_STATUS EFIAPI Dns6UpdateDnsCache ( IN EFI_DNS6_PROTOCOL *This, IN BOOLEAN DeleteFlag, IN BOOLEAN Override, IN EFI_DNS6_CACHE_ENTRY DnsCacheEntry ); /** Polls for incoming data packets and processes outgoing data packets. The Poll() function can be used by network drivers and applications to increase the rate that data packets are moved between the communications device and the transmit and receive queues. In some systems, the periodic timer event in the managed network driver may not poll the underlying communications device fast enough to transmit and/or receive all data packets without missing incoming packets or dropping outgoing packets. Drivers and applications that are experiencing packet loss should try calling the Poll() function more often. @param[in] This Pointer to EFI_DNS6_PROTOCOL instance. @retval EFI_SUCCESS Incoming or outgoing data was processed. @retval EFI_NOT_STARTED This EFI DNS Protocol instance has not been started. @retval EFI_INVALID_PARAMETER This is NULL. @retval EFI_NO_MAPPING There is no source address is available for use. @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. @retval EFI_TIMEOUT Data was dropped out of the transmit and/or receive queue. Consider increasing the polling rate. **/ EFI_STATUS EFIAPI Dns6Poll ( IN EFI_DNS6_PROTOCOL *This ); /** Abort an asynchronous DNS operation, including translation between IP and Host, and general look up behavior. The Cancel() function is used to abort a pending resolution request. After calling this function, Token.Status will be set to EFI_ABORTED and then Token.Event will be signaled. If the token is not in one of the queues, which usually means that the asynchronous operation has completed, this function will not signal the token and EFI_NOT_FOUND is returned. @param[in] This Pointer to EFI_DNS6_PROTOCOL instance. @param[in] Token Pointer to a token that has been issued by EFI_DNS6_PROTOCOL.HostNameToIp (), EFI_DNS6_PROTOCOL.IpToHostName() or EFI_DNS6_PROTOCOL.GeneralLookup(). If NULL, all pending tokens are aborted. @retval EFI_SUCCESS Incoming or outgoing data was processed. @retval EFI_NOT_STARTED This EFI DNS6 Protocol instance has not been started. @retval EFI_INVALID_PARAMETER This is NULL. @retval EFI_NO_MAPPING There's no source address is available for use. @retval EFI_NOT_FOUND When Token is not NULL, and the asynchronous DNS operation was not found in the transmit queue. It was either completed or was not issued by HostNameToIp(), IpToHostName() or GeneralLookup(). **/ EFI_STATUS EFIAPI Dns6Cancel ( IN EFI_DNS6_PROTOCOL *This, IN EFI_DNS6_COMPLETION_TOKEN *Token ); #endif
7b216f7befee525f5610d837ab9ffa6338a5d6e7
581bdcc078d282e388f1b655d4cfc4e08152d117
/SystemInformer/phsvc/clapi.c
eb5ebd816d647167bf48f359aa943116a2379ab5
[ "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
36,629
c
clapi.c
/* * Copyright (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved. * * This file is part of System Informer. * * Authors: * * wj32 2011-2015 * dmex 2017-2023 * */ #include <phapp.h> #include <phsvccl.h> HANDLE PhSvcClPortHandle; PVOID PhSvcClPortHeap; HANDLE PhSvcClServerProcessId; NTSTATUS PhSvcConnectToServer( _In_ PUNICODE_STRING PortName, _In_opt_ SIZE_T PortSectionSize ) { NTSTATUS status; HANDLE sectionHandle; LARGE_INTEGER sectionSize; PORT_VIEW clientView; REMOTE_PORT_VIEW serverView; SECURITY_QUALITY_OF_SERVICE securityQos; ULONG maxMessageLength; PHSVC_API_CONNECTINFO connectInfo; ULONG connectInfoLength; if (PhSvcClPortHandle) return STATUS_ADDRESS_ALREADY_EXISTS; if (PortSectionSize == 0) PortSectionSize = UInt32x32To64(2, 1024 * 1024); // 2 MB // Create the port section and connect to the port. sectionSize.QuadPart = PortSectionSize; status = NtCreateSection( &sectionHandle, SECTION_ALL_ACCESS, NULL, &sectionSize, PAGE_READWRITE, SEC_COMMIT, NULL ); if (!NT_SUCCESS(status)) return status; clientView.Length = sizeof(PORT_VIEW); clientView.SectionHandle = sectionHandle; clientView.SectionOffset = 0; clientView.ViewSize = PortSectionSize; clientView.ViewBase = NULL; clientView.ViewRemoteBase = NULL; serverView.Length = sizeof(REMOTE_PORT_VIEW); serverView.ViewSize = 0; serverView.ViewBase = NULL; securityQos.Length = sizeof(SECURITY_QUALITY_OF_SERVICE); securityQos.ImpersonationLevel = SecurityImpersonation; securityQos.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING; securityQos.EffectiveOnly = TRUE; connectInfoLength = sizeof(PHSVC_API_CONNECTINFO); connectInfo.ServerProcessId = ULONG_MAX; status = NtConnectPort( &PhSvcClPortHandle, PortName, &securityQos, &clientView, &serverView, &maxMessageLength, &connectInfo, &connectInfoLength ); NtClose(sectionHandle); if (!NT_SUCCESS(status)) return status; PhSvcClServerProcessId = UlongToHandle(connectInfo.ServerProcessId); // Create the port heap. PhSvcClPortHeap = RtlCreateHeap( HEAP_CLASS_1, clientView.ViewBase, clientView.ViewSize, PAGE_SIZE, NULL, NULL ); if (!PhSvcClPortHeap) { NtClose(PhSvcClPortHandle); return STATUS_INSUFFICIENT_RESOURCES; } RtlSetHeapInformation( PhSvcClPortHeap, HeapCompatibilityInformation, &(ULONG){ HEAP_COMPATIBILITY_LFH }, sizeof(ULONG) ); return status; } VOID PhSvcDisconnectFromServer( VOID ) { if (PhSvcClPortHeap) { RtlDestroyHeap(PhSvcClPortHeap); PhSvcClPortHeap = NULL; } if (PhSvcClPortHandle) { NtClose(PhSvcClPortHandle); PhSvcClPortHandle = NULL; } PhSvcClServerProcessId = NULL; } _Success_(return != NULL) PVOID PhSvcpAllocateHeap( _In_ SIZE_T Size, _Out_ PULONG Offset ) { PVOID memory; if (!PhSvcClPortHeap) return NULL; memory = RtlAllocateHeap(PhSvcClPortHeap, 0, Size); if (!memory) return NULL; *Offset = PtrToUlong(PTR_SUB_OFFSET(memory, PhSvcClPortHeap)); return memory; } VOID PhSvcpFreeHeap( _In_ PVOID Memory ) { if (!PhSvcClPortHeap) return; RtlFreeHeap(PhSvcClPortHeap, 0, Memory); } _Success_(return != NULL) PVOID PhSvcpCreateString( _In_opt_ PVOID String, _In_ SIZE_T Length, _Out_ PPH_RELATIVE_STRINGREF StringRef ) { PVOID memory; SIZE_T length; ULONG offset; if (Length != SIZE_MAX) length = Length; else length = PhCountStringZ(String) * sizeof(WCHAR); if (length > ULONG_MAX) return NULL; memory = PhSvcpAllocateHeap(length, &offset); if (!memory) return NULL; if (String) memcpy(memory, String, length); StringRef->Length = (ULONG)length; StringRef->Offset = offset; return memory; } NTSTATUS PhSvcpCallServer( _Inout_ PPHSVC_API_MSG Message ) { NTSTATUS status; Message->h.u1.s1.DataLength = sizeof(PHSVC_API_MSG) - FIELD_OFFSET(PHSVC_API_MSG, p); Message->h.u1.s1.TotalLength = sizeof(PHSVC_API_MSG); Message->h.u2.ZeroInit = 0; status = NtRequestWaitReplyPort(PhSvcClPortHandle, &Message->h, &Message->h); if (!NT_SUCCESS(status)) return status; return Message->p.ReturnStatus; } NTSTATUS PhSvcCallPlugin( _In_ PPH_STRINGREF ApiId, _In_reads_bytes_opt_(InLength) PVOID InBuffer, _In_ ULONG InLength, _Out_writes_bytes_opt_(OutLength) PVOID OutBuffer, _In_ ULONG OutLength ) { NTSTATUS status; PHSVC_API_MSG m; PVOID apiId = NULL; memset(&m, 0, sizeof(PHSVC_API_MSG)); if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; if (InLength > sizeof(m.p.u.Plugin.i.Data)) return STATUS_BUFFER_OVERFLOW; m.p.ApiNumber = PhSvcPluginApiNumber; if (!(apiId = PhSvcpCreateString(ApiId->Buffer, ApiId->Length, &m.p.u.Plugin.i.ApiId))) return STATUS_NO_MEMORY; if (InLength != 0) memcpy(m.p.u.Plugin.i.Data, InBuffer, InLength); status = PhSvcpCallServer(&m); if (OutLength != 0) memcpy(OutBuffer, m.p.u.Plugin.o.Data, min(OutLength, sizeof(m.p.u.Plugin.o.Data))); if (apiId) PhSvcpFreeHeap(apiId); return status; } NTSTATUS PhSvcpCallExecuteRunAsCommand( _In_ PHSVC_API_NUMBER ApiNumber, _In_ PPH_RUNAS_SERVICE_PARAMETERS Parameters ) { NTSTATUS status; PHSVC_API_MSG m; PVOID userName = NULL; PVOID password = NULL; ULONG passwordLength = 0; PVOID currentDirectory = NULL; PVOID commandLine = NULL; PVOID fileName = NULL; PVOID desktopName = NULL; PVOID serviceName = NULL; memset(&m, 0, sizeof(PHSVC_API_MSG)); if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; m.p.ApiNumber = ApiNumber; m.p.u.ExecuteRunAsCommand.i.ProcessId = Parameters->ProcessId; m.p.u.ExecuteRunAsCommand.i.LogonType = Parameters->LogonType; m.p.u.ExecuteRunAsCommand.i.SessionId = Parameters->SessionId; m.p.u.ExecuteRunAsCommand.i.UseLinkedToken = Parameters->UseLinkedToken; m.p.u.ExecuteRunAsCommand.i.CreateSuspendedProcess = Parameters->CreateSuspendedProcess; m.p.u.ExecuteRunAsCommand.i.CreateUIAccessProcess = Parameters->CreateUIAccessProcess; status = STATUS_NO_MEMORY; if (Parameters->UserName && !(userName = PhSvcpCreateString(Parameters->UserName, SIZE_MAX, &m.p.u.ExecuteRunAsCommand.i.UserName))) goto CleanupExit; if (Parameters->Password) { if (!(password = PhSvcpCreateString(Parameters->Password, SIZE_MAX, &m.p.u.ExecuteRunAsCommand.i.Password))) goto CleanupExit; passwordLength = m.p.u.ExecuteRunAsCommand.i.Password.Length; } if (Parameters->CurrentDirectory && !(currentDirectory = PhSvcpCreateString(Parameters->CurrentDirectory, SIZE_MAX, &m.p.u.ExecuteRunAsCommand.i.CurrentDirectory))) goto CleanupExit; if (Parameters->CommandLine && !(commandLine = PhSvcpCreateString(Parameters->CommandLine, SIZE_MAX, &m.p.u.ExecuteRunAsCommand.i.CommandLine))) goto CleanupExit; if (Parameters->FileName && !(fileName = PhSvcpCreateString(Parameters->FileName, SIZE_MAX, &m.p.u.ExecuteRunAsCommand.i.FileName))) goto CleanupExit; if (Parameters->DesktopName && !(desktopName = PhSvcpCreateString(Parameters->DesktopName, SIZE_MAX, &m.p.u.ExecuteRunAsCommand.i.DesktopName))) goto CleanupExit; if (Parameters->ServiceName && !(serviceName = PhSvcpCreateString(Parameters->ServiceName, SIZE_MAX, &m.p.u.ExecuteRunAsCommand.i.ServiceName))) goto CleanupExit; status = PhSvcpCallServer(&m); CleanupExit: if (serviceName) PhSvcpFreeHeap(serviceName); if (desktopName) PhSvcpFreeHeap(desktopName); if (fileName) PhSvcpFreeHeap(fileName); if (commandLine) PhSvcpFreeHeap(commandLine); if (currentDirectory) PhSvcpFreeHeap(currentDirectory); if (password) { RtlSecureZeroMemory(password, passwordLength); PhSvcpFreeHeap(password); } if (userName) PhSvcpFreeHeap(userName); return status; } NTSTATUS PhSvcCallExecuteRunAsCommand( _In_ PPH_RUNAS_SERVICE_PARAMETERS Parameters ) { return PhSvcpCallExecuteRunAsCommand(PhSvcExecuteRunAsCommandApiNumber, Parameters); } NTSTATUS PhSvcCallUnloadDriver( _In_opt_ PVOID BaseAddress, _In_opt_ PWSTR Name ) { NTSTATUS status; PHSVC_API_MSG m; PVOID name = NULL; memset(&m, 0, sizeof(PHSVC_API_MSG)); if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; m.p.ApiNumber = PhSvcUnloadDriverApiNumber; m.p.u.UnloadDriver.i.BaseAddress = BaseAddress; if (Name) { name = PhSvcpCreateString(Name, SIZE_MAX, &m.p.u.UnloadDriver.i.Name); if (!name) return STATUS_NO_MEMORY; } status = PhSvcpCallServer(&m); if (name) PhSvcpFreeHeap(name); return status; } NTSTATUS PhSvcCallControlProcess( _In_opt_ HANDLE ProcessId, _In_ PHSVC_API_CONTROLPROCESS_COMMAND Command, _In_ ULONG Argument ) { PHSVC_API_MSG m; if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; m.p.ApiNumber = PhSvcControlProcessApiNumber; m.p.u.ControlProcess.i.ProcessId = ProcessId; m.p.u.ControlProcess.i.Command = Command; m.p.u.ControlProcess.i.Argument = Argument; return PhSvcpCallServer(&m); } NTSTATUS PhSvcCallControlService( _In_ PWSTR ServiceName, _In_ PHSVC_API_CONTROLSERVICE_COMMAND Command ) { NTSTATUS status; PHSVC_API_MSG m; PVOID serviceName; if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; m.p.ApiNumber = PhSvcControlServiceApiNumber; serviceName = PhSvcpCreateString(ServiceName, SIZE_MAX, &m.p.u.ControlService.i.ServiceName); m.p.u.ControlService.i.Command = Command; if (serviceName) { status = PhSvcpCallServer(&m); } else { status = STATUS_NO_MEMORY; } if (serviceName) PhSvcpFreeHeap(serviceName); return status; } NTSTATUS PhSvcCallCreateService( _In_ PWSTR ServiceName, _In_opt_ PWSTR DisplayName, _In_ ULONG ServiceType, _In_ ULONG StartType, _In_ ULONG ErrorControl, _In_opt_ PWSTR BinaryPathName, _In_opt_ PWSTR LoadOrderGroup, _Out_opt_ PULONG TagId, _In_opt_ PWSTR Dependencies, _In_opt_ PWSTR ServiceStartName, _In_opt_ PWSTR Password ) { NTSTATUS status; PHSVC_API_MSG m; PVOID serviceName = NULL; PVOID displayName = NULL; PVOID binaryPathName = NULL; PVOID loadOrderGroup = NULL; PVOID dependencies = NULL; PVOID serviceStartName = NULL; PVOID password = NULL; ULONG passwordLength = 0; memset(&m, 0, sizeof(PHSVC_API_MSG)); if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; m.p.ApiNumber = PhSvcCreateServiceApiNumber; m.p.u.CreateService.i.ServiceType = ServiceType; m.p.u.CreateService.i.StartType = StartType; m.p.u.CreateService.i.ErrorControl = ErrorControl; m.p.u.CreateService.i.TagIdSpecified = TagId != NULL; status = STATUS_NO_MEMORY; if (!(serviceName = PhSvcpCreateString(ServiceName, SIZE_MAX, &m.p.u.CreateService.i.ServiceName))) goto CleanupExit; if (DisplayName && !(displayName = PhSvcpCreateString(DisplayName, SIZE_MAX, &m.p.u.CreateService.i.DisplayName))) goto CleanupExit; if (BinaryPathName && !(binaryPathName = PhSvcpCreateString(BinaryPathName, SIZE_MAX, &m.p.u.CreateService.i.BinaryPathName))) goto CleanupExit; if (LoadOrderGroup && !(loadOrderGroup = PhSvcpCreateString(LoadOrderGroup, SIZE_MAX, &m.p.u.CreateService.i.LoadOrderGroup))) goto CleanupExit; if (Dependencies) { SIZE_T dependenciesLength; SIZE_T partCount; PWSTR part; dependenciesLength = sizeof(WCHAR); part = Dependencies; do { partCount = PhCountStringZ(part) + 1; part += partCount; dependenciesLength += partCount * sizeof(WCHAR); } while (partCount != 1); // stop at empty dependency part if (!(dependencies = PhSvcpCreateString(Dependencies, dependenciesLength, &m.p.u.CreateService.i.Dependencies))) goto CleanupExit; } if (ServiceStartName && !(serviceStartName = PhSvcpCreateString(ServiceStartName, SIZE_MAX, &m.p.u.CreateService.i.ServiceStartName))) goto CleanupExit; if (Password) { if (!(password = PhSvcpCreateString(Password, SIZE_MAX, &m.p.u.CreateService.i.Password))) goto CleanupExit; passwordLength = m.p.u.CreateService.i.Password.Length; } status = PhSvcpCallServer(&m); if (NT_SUCCESS(status)) { if (TagId) *TagId = m.p.u.CreateService.o.TagId; } CleanupExit: if (password) { RtlSecureZeroMemory(password, passwordLength); PhSvcpFreeHeap(password); } if (serviceStartName) PhSvcpFreeHeap(serviceStartName); if (dependencies) PhSvcpFreeHeap(dependencies); if (loadOrderGroup) PhSvcpFreeHeap(loadOrderGroup); if (binaryPathName) PhSvcpFreeHeap(binaryPathName); if (displayName) PhSvcpFreeHeap(displayName); if (serviceName) PhSvcpFreeHeap(serviceName); return status; } NTSTATUS PhSvcCallChangeServiceConfig( _In_ PWSTR ServiceName, _In_ ULONG ServiceType, _In_ ULONG StartType, _In_ ULONG ErrorControl, _In_opt_ PWSTR BinaryPathName, _In_opt_ PWSTR LoadOrderGroup, _Out_opt_ PULONG TagId, _In_opt_ PWSTR Dependencies, _In_opt_ PWSTR ServiceStartName, _In_opt_ PWSTR Password, _In_opt_ PWSTR DisplayName ) { NTSTATUS status; PHSVC_API_MSG m; PVOID serviceName = NULL; PVOID binaryPathName = NULL; PVOID loadOrderGroup = NULL; PVOID dependencies = NULL; PVOID serviceStartName = NULL; PVOID password = NULL; ULONG passwordLength = 0; PVOID displayName = NULL; memset(&m, 0, sizeof(PHSVC_API_MSG)); if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; m.p.ApiNumber = PhSvcChangeServiceConfigApiNumber; m.p.u.ChangeServiceConfig.i.ServiceType = ServiceType; m.p.u.ChangeServiceConfig.i.StartType = StartType; m.p.u.ChangeServiceConfig.i.ErrorControl = ErrorControl; m.p.u.ChangeServiceConfig.i.TagIdSpecified = TagId != NULL; status = STATUS_NO_MEMORY; if (!(serviceName = PhSvcpCreateString(ServiceName, SIZE_MAX, &m.p.u.ChangeServiceConfig.i.ServiceName))) goto CleanupExit; if (BinaryPathName && !(binaryPathName = PhSvcpCreateString(BinaryPathName, SIZE_MAX, &m.p.u.ChangeServiceConfig.i.BinaryPathName))) goto CleanupExit; if (LoadOrderGroup && !(loadOrderGroup = PhSvcpCreateString(LoadOrderGroup, SIZE_MAX, &m.p.u.ChangeServiceConfig.i.LoadOrderGroup))) goto CleanupExit; if (Dependencies) { SIZE_T dependenciesLength; SIZE_T partCount; PWSTR part; dependenciesLength = sizeof(WCHAR); part = Dependencies; do { partCount = PhCountStringZ(part) + 1; part += partCount; dependenciesLength += partCount * sizeof(WCHAR); } while (partCount != 1); // stop at empty dependency part if (!(dependencies = PhSvcpCreateString(Dependencies, dependenciesLength, &m.p.u.ChangeServiceConfig.i.Dependencies))) goto CleanupExit; } if (ServiceStartName && !(serviceStartName = PhSvcpCreateString(ServiceStartName, SIZE_MAX, &m.p.u.ChangeServiceConfig.i.ServiceStartName))) goto CleanupExit; if (Password) { if (!(password = PhSvcpCreateString(Password, SIZE_MAX, &m.p.u.ChangeServiceConfig.i.Password))) goto CleanupExit; passwordLength = m.p.u.ChangeServiceConfig.i.Password.Length; } if (DisplayName && !(displayName = PhSvcpCreateString(DisplayName, SIZE_MAX, &m.p.u.ChangeServiceConfig.i.DisplayName))) goto CleanupExit; status = PhSvcpCallServer(&m); if (NT_SUCCESS(status)) { if (TagId) *TagId = m.p.u.ChangeServiceConfig.o.TagId; } CleanupExit: if (displayName) PhSvcpFreeHeap(displayName); if (password) { RtlSecureZeroMemory(password, passwordLength); PhSvcpFreeHeap(password); } if (serviceStartName) PhSvcpFreeHeap(serviceStartName); if (dependencies) PhSvcpFreeHeap(dependencies); if (loadOrderGroup) PhSvcpFreeHeap(loadOrderGroup); if (binaryPathName) PhSvcpFreeHeap(binaryPathName); if (serviceName) PhSvcpFreeHeap(serviceName); return status; } PVOID PhSvcpPackRoot( _Inout_ PPH_BYTES_BUILDER BytesBuilder, _In_ PVOID Buffer, _In_ SIZE_T Length ) { return PhAppendBytesBuilderEx(BytesBuilder, Buffer, Length, sizeof(ULONG_PTR), NULL); } VOID PhSvcpPackBuffer_V( _Inout_ PPH_BYTES_BUILDER BytesBuilder, _Inout_ PVOID *PointerInBytesBuilder, _In_ SIZE_T Length, _In_ SIZE_T Alignment, _In_ ULONG NumberOfPointersToRebase, _In_ va_list ArgPtr ) { va_list argptr; ULONG_PTR oldBase; SIZE_T oldLength; ULONG_PTR newBase; SIZE_T offset; ULONG i; PVOID *pointer; oldBase = (ULONG_PTR)BytesBuilder->Bytes->Buffer; oldLength = BytesBuilder->Bytes->Length; assert((ULONG_PTR)PointerInBytesBuilder >= oldBase && (ULONG_PTR)PointerInBytesBuilder + sizeof(PVOID) <= oldBase + oldLength); if (!*PointerInBytesBuilder) return; PhAppendBytesBuilderEx(BytesBuilder, *PointerInBytesBuilder, Length, Alignment, &offset); newBase = (ULONG_PTR)BytesBuilder->Bytes->Buffer; PointerInBytesBuilder = (PVOID *)((ULONG_PTR)PointerInBytesBuilder - oldBase + newBase); *PointerInBytesBuilder = (PVOID)offset; argptr = ArgPtr; for (i = 0; i < NumberOfPointersToRebase; i++) { pointer = va_arg(argptr, PVOID *); assert(!*pointer || ((ULONG_PTR)*pointer >= oldBase && (ULONG_PTR)*pointer + sizeof(PVOID) <= oldBase + oldLength)); if (*pointer) *pointer = (PVOID)((ULONG_PTR)*pointer - oldBase + newBase); } } VOID PhSvcpPackBuffer( _Inout_ PPH_BYTES_BUILDER BytesBuilder, _Inout_ PVOID *PointerInBytesBuilder, _In_ SIZE_T Length, _In_ SIZE_T Alignment, _In_ ULONG NumberOfPointersToRebase, ... ) { va_list argptr; va_start(argptr, NumberOfPointersToRebase); PhSvcpPackBuffer_V(BytesBuilder, PointerInBytesBuilder, Length, Alignment, NumberOfPointersToRebase, argptr); } SIZE_T PhSvcpBufferLengthStringZ( _In_opt_ PWSTR String, _In_ BOOLEAN Multi ) { SIZE_T length = 0; if (String) { if (Multi) { PWSTR part = String; SIZE_T partCount; while (TRUE) { partCount = PhCountStringZ(part); length += (partCount + 1) * sizeof(WCHAR); if (partCount == 0) break; part += partCount + 1; } } else { length = (PhCountStringZ(String) + 1) * sizeof(WCHAR); } } return length; } NTSTATUS PhSvcCallChangeServiceConfig2( _In_ PWSTR ServiceName, _In_ ULONG InfoLevel, _In_ PVOID Info ) { NTSTATUS status; PHSVC_API_MSG m; PVOID serviceName = NULL; PVOID info = NULL; PH_BYTES_BUILDER bb; if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; m.p.ApiNumber = PhSvcChangeServiceConfig2ApiNumber; m.p.u.ChangeServiceConfig2.i.InfoLevel = InfoLevel; if (serviceName = PhSvcpCreateString(ServiceName, SIZE_MAX, &m.p.u.ChangeServiceConfig2.i.ServiceName)) { switch (InfoLevel) { case SERVICE_CONFIG_FAILURE_ACTIONS: { LPSERVICE_FAILURE_ACTIONS failureActions = Info; LPSERVICE_FAILURE_ACTIONS packedFailureActions; PhInitializeBytesBuilder(&bb, 200); packedFailureActions = PhSvcpPackRoot(&bb, failureActions, sizeof(SERVICE_FAILURE_ACTIONS)); PhSvcpPackBuffer(&bb, &packedFailureActions->lpRebootMsg, PhSvcpBufferLengthStringZ(failureActions->lpRebootMsg, FALSE), sizeof(WCHAR), 1, &packedFailureActions); PhSvcpPackBuffer(&bb, &packedFailureActions->lpCommand, PhSvcpBufferLengthStringZ(failureActions->lpCommand, FALSE), sizeof(WCHAR), 1, &packedFailureActions); if (failureActions->cActions != 0 && failureActions->lpsaActions) { PhSvcpPackBuffer(&bb, &packedFailureActions->lpsaActions, failureActions->cActions * sizeof(SC_ACTION), __alignof(SC_ACTION), 1, &packedFailureActions); } info = PhSvcpCreateString(bb.Bytes->Buffer, bb.Bytes->Length, &m.p.u.ChangeServiceConfig2.i.Info); PhDeleteBytesBuilder(&bb); } break; case SERVICE_CONFIG_DELAYED_AUTO_START_INFO: info = PhSvcpCreateString(Info, sizeof(SERVICE_DELAYED_AUTO_START_INFO), &m.p.u.ChangeServiceConfig2.i.Info); break; case SERVICE_CONFIG_FAILURE_ACTIONS_FLAG: info = PhSvcpCreateString(Info, sizeof(SERVICE_FAILURE_ACTIONS_FLAG), &m.p.u.ChangeServiceConfig2.i.Info); break; case SERVICE_CONFIG_SERVICE_SID_INFO: info = PhSvcpCreateString(Info, sizeof(SERVICE_SID_INFO), &m.p.u.ChangeServiceConfig2.i.Info); break; case SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO: { LPSERVICE_REQUIRED_PRIVILEGES_INFO requiredPrivilegesInfo = Info; LPSERVICE_REQUIRED_PRIVILEGES_INFO packedRequiredPrivilegesInfo; PhInitializeBytesBuilder(&bb, 100); packedRequiredPrivilegesInfo = PhSvcpPackRoot(&bb, requiredPrivilegesInfo, sizeof(SERVICE_REQUIRED_PRIVILEGES_INFO)); PhSvcpPackBuffer(&bb, &packedRequiredPrivilegesInfo->pmszRequiredPrivileges, PhSvcpBufferLengthStringZ(requiredPrivilegesInfo->pmszRequiredPrivileges, TRUE), sizeof(WCHAR), 1, &packedRequiredPrivilegesInfo); info = PhSvcpCreateString(bb.Bytes->Buffer, bb.Bytes->Length, &m.p.u.ChangeServiceConfig2.i.Info); PhDeleteBytesBuilder(&bb); } break; case SERVICE_CONFIG_PRESHUTDOWN_INFO: info = PhSvcpCreateString(Info, sizeof(SERVICE_PRESHUTDOWN_INFO), &m.p.u.ChangeServiceConfig2.i.Info); break; case SERVICE_CONFIG_TRIGGER_INFO: { PSERVICE_TRIGGER_INFO triggerInfo = Info; PSERVICE_TRIGGER_INFO packedTriggerInfo; ULONG i; PSERVICE_TRIGGER packedTrigger; ULONG j; PSERVICE_TRIGGER_SPECIFIC_DATA_ITEM packedDataItem; ULONG alignment; PhInitializeBytesBuilder(&bb, 400); packedTriggerInfo = PhSvcpPackRoot(&bb, triggerInfo, sizeof(SERVICE_TRIGGER_INFO)); if (triggerInfo->cTriggers != 0 && triggerInfo->pTriggers) { PhSvcpPackBuffer(&bb, &packedTriggerInfo->pTriggers, triggerInfo->cTriggers * sizeof(SERVICE_TRIGGER), __alignof(SERVICE_TRIGGER), 1, &packedTriggerInfo); for (i = 0; i < triggerInfo->cTriggers; i++) { packedTrigger = PhOffsetBytesBuilder(&bb, (SIZE_T)packedTriggerInfo->pTriggers + i * sizeof(SERVICE_TRIGGER)); PhSvcpPackBuffer(&bb, &packedTrigger->pTriggerSubtype, sizeof(GUID), __alignof(GUID), 2, &packedTriggerInfo, &packedTrigger); if (packedTrigger->cDataItems != 0 && packedTrigger->pDataItems) { PhSvcpPackBuffer(&bb, &packedTrigger->pDataItems, packedTrigger->cDataItems * sizeof(SERVICE_TRIGGER_SPECIFIC_DATA_ITEM), __alignof(SERVICE_TRIGGER_SPECIFIC_DATA_ITEM), 2, &packedTriggerInfo, &packedTrigger); for (j = 0; j < packedTrigger->cDataItems; j++) { packedDataItem = PhOffsetBytesBuilder(&bb, (SIZE_T)packedTrigger->pDataItems + j * sizeof(SERVICE_TRIGGER_SPECIFIC_DATA_ITEM)); alignment = 1; switch (packedDataItem->dwDataType) { case SERVICE_TRIGGER_DATA_TYPE_BINARY: case SERVICE_TRIGGER_DATA_TYPE_LEVEL: alignment = sizeof(CHAR); break; case SERVICE_TRIGGER_DATA_TYPE_STRING: alignment = sizeof(WCHAR); break; case SERVICE_TRIGGER_DATA_TYPE_KEYWORD_ANY: case SERVICE_TRIGGER_DATA_TYPE_KEYWORD_ALL: alignment = sizeof(ULONG64); break; } PhSvcpPackBuffer(&bb, &packedDataItem->pData, packedDataItem->cbData, alignment, 3, &packedTriggerInfo, &packedTrigger, &packedDataItem); } } } } info = PhSvcpCreateString(bb.Bytes->Buffer, bb.Bytes->Length, &m.p.u.ChangeServiceConfig2.i.Info); PhDeleteBytesBuilder(&bb); } break; case SERVICE_CONFIG_LAUNCH_PROTECTED: info = PhSvcpCreateString(Info, sizeof(SERVICE_LAUNCH_PROTECTED_INFO), &m.p.u.ChangeServiceConfig2.i.Info); break; default: status = STATUS_INVALID_PARAMETER; break; } } if (serviceName && info) { status = PhSvcpCallServer(&m); } else { status = STATUS_NO_MEMORY; } if (info) PhSvcpFreeHeap(info); if (serviceName) PhSvcpFreeHeap(serviceName); return status; } NTSTATUS PhSvcCallSetTcpEntry( _In_ PVOID TcpRow ) { PHSVC_API_MSG m; struct { ULONG dwState; ULONG dwLocalAddr; ULONG dwLocalPort; ULONG dwRemoteAddr; ULONG dwRemotePort; } *tcpRow = TcpRow; if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; m.p.ApiNumber = PhSvcSetTcpEntryApiNumber; m.p.u.SetTcpEntry.i.State = tcpRow->dwState; m.p.u.SetTcpEntry.i.LocalAddress = tcpRow->dwLocalAddr; m.p.u.SetTcpEntry.i.LocalPort = tcpRow->dwLocalPort; m.p.u.SetTcpEntry.i.RemoteAddress = tcpRow->dwRemoteAddr; m.p.u.SetTcpEntry.i.RemotePort = tcpRow->dwRemotePort; return PhSvcpCallServer(&m); } NTSTATUS PhSvcCallControlThread( _In_ HANDLE ThreadId, _In_ PHSVC_API_CONTROLTHREAD_COMMAND Command, _In_ ULONG Argument ) { PHSVC_API_MSG m; if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; m.p.ApiNumber = PhSvcControlThreadApiNumber; m.p.u.ControlThread.i.ThreadId = ThreadId; m.p.u.ControlThread.i.Command = Command; m.p.u.ControlThread.i.Argument = Argument; return PhSvcpCallServer(&m); } NTSTATUS PhSvcCallAddAccountRight( _In_ PSID AccountSid, _In_ PUNICODE_STRING UserRight ) { NTSTATUS status; PHSVC_API_MSG m; PVOID accountSid = NULL; PVOID userRight = NULL; if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; m.p.ApiNumber = PhSvcAddAccountRightApiNumber; status = STATUS_NO_MEMORY; if (!(accountSid = PhSvcpCreateString(AccountSid, PhLengthSid(AccountSid), &m.p.u.AddAccountRight.i.AccountSid))) goto CleanupExit; if (!(userRight = PhSvcpCreateString(UserRight->Buffer, UserRight->Length, &m.p.u.AddAccountRight.i.UserRight))) goto CleanupExit; status = PhSvcpCallServer(&m); CleanupExit: if (userRight) PhSvcpFreeHeap(userRight); if (accountSid) PhSvcpFreeHeap(accountSid); return status; } NTSTATUS PhSvcCallInvokeRunAsService( _In_ PPH_RUNAS_SERVICE_PARAMETERS Parameters ) { return PhSvcpCallExecuteRunAsCommand(PhSvcInvokeRunAsServiceApiNumber, Parameters); } NTSTATUS PhSvcCallIssueMemoryListCommand( _In_ SYSTEM_MEMORY_LIST_COMMAND Command ) { PHSVC_API_MSG m; if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; m.p.ApiNumber = PhSvcIssueMemoryListCommandApiNumber; m.p.u.IssueMemoryListCommand.i.Command = Command; return PhSvcpCallServer(&m); } NTSTATUS PhSvcCallPostMessage( _In_opt_ HWND hWnd, _In_ UINT Msg, _In_ WPARAM wParam, _In_ LPARAM lParam ) { PHSVC_API_MSG m; if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; m.p.ApiNumber = PhSvcPostMessageApiNumber; m.p.u.PostMessage.i.hWnd = hWnd; m.p.u.PostMessage.i.Msg = Msg; m.p.u.PostMessage.i.wParam = wParam; m.p.u.PostMessage.i.lParam = lParam; return PhSvcpCallServer(&m); } NTSTATUS PhSvcCallSendMessage( _In_opt_ HWND hWnd, _In_ UINT Msg, _In_ WPARAM wParam, _In_ LPARAM lParam ) { PHSVC_API_MSG m; if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; m.p.ApiNumber = PhSvcSendMessageApiNumber; m.p.u.PostMessage.i.hWnd = hWnd; m.p.u.PostMessage.i.Msg = Msg; m.p.u.PostMessage.i.wParam = wParam; m.p.u.PostMessage.i.lParam = lParam; return PhSvcpCallServer(&m); } NTSTATUS PhSvcCallCreateProcessIgnoreIfeoDebugger( _In_ PWSTR FileName, _In_opt_ PWSTR CommandLine ) { NTSTATUS status; PHSVC_API_MSG m; PVOID fileName = NULL; PVOID commandLine = NULL; memset(&m, 0, sizeof(PHSVC_API_MSG)); if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; m.p.ApiNumber = PhSvcCreateProcessIgnoreIfeoDebuggerApiNumber; fileName = PhSvcpCreateString(FileName, SIZE_MAX, &m.p.u.CreateProcessIgnoreIfeoDebugger.i.FileName); if (!fileName) return STATUS_NO_MEMORY; if (CommandLine) { commandLine = PhSvcpCreateString(CommandLine, SIZE_MAX, &m.p.u.CreateProcessIgnoreIfeoDebugger.i.CommandLine); if (!commandLine) return STATUS_NO_MEMORY; } status = PhSvcpCallServer(&m); if (commandLine) PhSvcpFreeHeap(commandLine); if (fileName) PhSvcpFreeHeap(fileName); return status; } _Success_(return != NULL) PSECURITY_DESCRIPTOR PhpAbsoluteToSelfRelativeSD( _In_ PSECURITY_DESCRIPTOR AbsoluteSecurityDescriptor, _Out_ PULONG BufferSize ) { NTSTATUS status; ULONG bufferSize = 0; PSECURITY_DESCRIPTOR selfRelativeSecurityDescriptor; status = RtlAbsoluteToSelfRelativeSD(AbsoluteSecurityDescriptor, NULL, &bufferSize); if (status != STATUS_BUFFER_TOO_SMALL) return NULL; selfRelativeSecurityDescriptor = PhAllocate(bufferSize); status = RtlAbsoluteToSelfRelativeSD(AbsoluteSecurityDescriptor, selfRelativeSecurityDescriptor, &bufferSize); if (!NT_SUCCESS(status)) { PhFree(selfRelativeSecurityDescriptor); return NULL; } *BufferSize = bufferSize; return selfRelativeSecurityDescriptor; } NTSTATUS PhSvcCallSetServiceSecurity( _In_ PWSTR ServiceName, _In_ SECURITY_INFORMATION SecurityInformation, _In_ PSECURITY_DESCRIPTOR SecurityDescriptor ) { NTSTATUS status; PHSVC_API_MSG m; PSECURITY_DESCRIPTOR selfRelativeSecurityDescriptor = NULL; ULONG bufferSize; PVOID serviceName = NULL; PVOID copiedSelfRelativeSecurityDescriptor = NULL; if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; selfRelativeSecurityDescriptor = PhpAbsoluteToSelfRelativeSD(SecurityDescriptor, &bufferSize); if (!selfRelativeSecurityDescriptor) { status = STATUS_BAD_DESCRIPTOR_FORMAT; goto CleanupExit; } m.p.ApiNumber = PhSvcSetServiceSecurityApiNumber; m.p.u.SetServiceSecurity.i.SecurityInformation = SecurityInformation; status = STATUS_NO_MEMORY; if (!(serviceName = PhSvcpCreateString(ServiceName, SIZE_MAX, &m.p.u.SetServiceSecurity.i.ServiceName))) goto CleanupExit; if (!(copiedSelfRelativeSecurityDescriptor = PhSvcpCreateString(selfRelativeSecurityDescriptor, bufferSize, &m.p.u.SetServiceSecurity.i.SecurityDescriptor))) goto CleanupExit; status = PhSvcpCallServer(&m); CleanupExit: if (selfRelativeSecurityDescriptor) PhFree(selfRelativeSecurityDescriptor); if (serviceName) PhSvcpFreeHeap(serviceName); if (copiedSelfRelativeSecurityDescriptor) PhSvcpFreeHeap(copiedSelfRelativeSecurityDescriptor); return status; } NTSTATUS PhSvcCallWriteMiniDumpProcess( _In_ HANDLE ProcessHandle, _In_ HANDLE ProcessId, _In_ HANDLE FileHandle, _In_ ULONG DumpType ) { NTSTATUS status; PHSVC_API_MSG m; HANDLE serverHandle = NULL; HANDLE remoteProcessHandle = NULL; HANDLE remoteFileHandle = NULL; memset(&m, 0, sizeof(PHSVC_API_MSG)); if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; // For typical uses of this function, the client has more privileges than the server. // We therefore duplicate our handles into the server's process. m.p.ApiNumber = PhSvcWriteMiniDumpProcessApiNumber; status = PhOpenProcess( &serverHandle, PROCESS_DUP_HANDLE, PhSvcClServerProcessId ); if (!NT_SUCCESS(status)) goto CleanupExit; status = NtDuplicateObject( NtCurrentProcess(), ProcessHandle, serverHandle, &remoteProcessHandle, 0, 0, DUPLICATE_SAME_ACCESS ); if (!NT_SUCCESS(status)) goto CleanupExit; status = NtDuplicateObject( NtCurrentProcess(), FileHandle, serverHandle, &remoteFileHandle, FILE_GENERIC_WRITE, 0, 0 ); if (!NT_SUCCESS(status)) goto CleanupExit; m.p.u.WriteMiniDumpProcess.i.LocalProcessHandle = HandleToUlong(remoteProcessHandle); m.p.u.WriteMiniDumpProcess.i.ProcessId = HandleToUlong(ProcessId); m.p.u.WriteMiniDumpProcess.i.LocalFileHandle = HandleToUlong(remoteFileHandle); m.p.u.WriteMiniDumpProcess.i.DumpType = DumpType; status = PhSvcpCallServer(&m); CleanupExit: if (serverHandle) { if (remoteProcessHandle) NtDuplicateObject(serverHandle, remoteProcessHandle, NULL, NULL, 0, 0, DUPLICATE_CLOSE_SOURCE); if (remoteFileHandle) NtDuplicateObject(serverHandle, remoteFileHandle, NULL, NULL, 0, 0, DUPLICATE_CLOSE_SOURCE); NtClose(serverHandle); } return status; } NTSTATUS PhSvcCallQueryProcessHeapInformation( _In_ HANDLE ProcessId, _Out_ PPH_STRING* HeapInformation ) { NTSTATUS status; PHSVC_API_MSG m; ULONG bufferSize; PVOID buffer; if (!PhSvcClPortHandle) return STATUS_PORT_DISCONNECTED; memset(&m, 0, sizeof(PHSVC_API_MSG)); m.p.ApiNumber = PhSvcQueryProcessDebugInformationApiNumber; m.p.u.QueryProcessHeap.i.ProcessId = HandleToUlong(ProcessId); bufferSize = 0x1000; if (!(buffer = PhSvcpCreateString(NULL, bufferSize, &m.p.u.QueryProcessHeap.i.Data))) return STATUS_FAIL_CHECK; status = PhSvcpCallServer(&m); if (status == STATUS_BUFFER_OVERFLOW) { PhSvcpFreeHeap(buffer); bufferSize = m.p.u.QueryProcessHeap.o.DataLength; if (!(buffer = PhSvcpCreateString(NULL, bufferSize, &m.p.u.QueryProcessHeap.i.Data))) return STATUS_FAIL_CHECK; status = PhSvcpCallServer(&m); } if (NT_SUCCESS(status)) { if (HeapInformation) *HeapInformation = PhCreateStringEx(buffer, m.p.u.QueryProcessHeap.o.DataLength); } PhSvcpFreeHeap(buffer); return status; }
dd4a90ed598cd9ef228c0c47bdf64ea34afdd1e3
f8cc1dd4b1378490386def2e0571561fab10b275
/src/libunixonacid/textmessage_receiver_hasmsginbuf.c
e41f5202c6443c9a405b9f8b6b64f125119cf67c
[ "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
488
c
textmessage_receiver_hasmsginbuf.c
/* ISC license. */ #include <stdint.h> #include <sys/uio.h> #include <skalibs/uint32.h> #include <skalibs/siovec.h> #include <skalibs/buffer.h> #include <skalibs/textmessage.h> int textmessage_receiver_hasmsginbuf (textmessage_receiver const *tr) { size_t len = buffer_len(&tr->in) ; uint32_t n ; char pack[4] ; struct iovec v[2] ; if (len < 4) return 0 ; buffer_rpeek(&tr->in, v) ; siovec_gather(v, 2, pack, 4) ; uint32_unpack_big(pack, &n) ; return len - 4 >= n ; }
8882c175f6edb45bd11ad24b5e6b08886b3f6d3e
1ecae23f22fd25334e9803f83c5f5f319a606cfe
/uc-crux-llvm/test/programs/do_strcmp.c
467d9fe5c2e5f3ff8f252fb210769288ad825499
[ "BSD-3-Clause" ]
permissive
GaloisInc/crucible
8ea77b3f45e36ee6ad38a5dff827793fd38456a4
c19fc2c53851cdd162ae1ccca14032467e3c2fd1
refs/heads/master
2023-08-29T01:28:48.974504
2023-08-22T23:31:42
2023-08-22T23:31:42
72,476,365
563
45
null
2023-08-31T22:07:29
2016-10-31T20:43:08
Rust
UTF-8
C
false
false
90
c
do_strcmp.c
#include <string.h> int do_strcmp(char *str1, char *str2) { return strcmp(str1, str2); }
d0fbe27e0b704f2f939d0b8813e26b56904a8a22
8838eb997879add5759b6dfb23f9a646464e53ca
/third-party/fuse/fuse_linux/include/sys/fcntl.h
8ea9ead62756e5a35957057dd3d7d21f2177149b
[ "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
88
h
fcntl.h
/** * @file * * @data 26.11.2015 * @author: Anton Bondarev */ #include <fcntl.h>
ee327fd6c837a48378600edcd7ce0568db193a3c
c26d7b0ed875357278e61627da2da0650da77986
/src/libm/sin.c
f08c64f9b2eb2ab574dd9bb3b9e808bb9fe00d67
[ "BSD-3-Clause" ]
permissive
RetroBSD/retrobsd
5343d9e3c424637fc3ad5b03fe720b2744490025
486f81f6abff01c7dcc207235cd2979b226a95ff
refs/heads/master
2023-09-02T23:12:05.110883
2023-07-07T18:41:40
2023-07-07T18:41:40
18,598,087
282
59
BSD-3-Clause
2023-07-18T07:35:36
2014-04-09T13:25:46
C
UTF-8
C
false
false
1,423
c
sin.c
/* * C program for floating point sin/cos. * Calls modf. * There are no error exits. * Coefficients are #3370 from Hart & Cheney (18.80D). */ #include <math.h> static double twoopi = 0.63661977236758134308; static double p0 = .1357884097877375669092680e8; static double p1 = -.4942908100902844161158627e7; static double p2 = .4401030535375266501944918e6; static double p3 = -.1384727249982452873054457e5; static double p4 = .1459688406665768722226959e3; static double q0 = .8644558652922534429915149e7; static double q1 = .4081792252343299749395779e6; static double q2 = .9463096101538208180571257e4; static double q3 = .1326534908786136358911494e3; static double sinus(arg, quad) double arg; int quad; { double modf(); double e, f; double ysq; double x,y; int k; double temp1, temp2; x = arg; if(x<0) { x = -x; quad = quad + 2; } x = x*twoopi; /*underflow?*/ if(x>32764){ y = modf(x,&e); e = e + quad; modf(0.25*e,&f); quad = e - 4*f; }else{ k = x; y = x - k; quad = (quad + k) & 03; } if (quad & 01) y = 1-y; if(quad > 1) y = -y; ysq = y*y; temp1 = ((((p4*ysq+p3)*ysq+p2)*ysq+p1)*ysq+p0)*y; temp2 = ((((ysq+q3)*ysq+q2)*ysq+q1)*ysq+q0); return(temp1/temp2); } double cos(arg) double arg; { double sinus(); if(arg<0) arg = -arg; return(sinus(arg, 1)); } double sin(arg) double arg; { double sinus(); return(sinus(arg, 0)); }
4db63a38927c0a5b1955e344a9a140e30fd96a74
3c6e1e35f38421273f92dd25055dccc6f632fd93
/app/modules/ws2812_effects.c
f55eec19f54553b6db9825ab722a98503efc0a92
[ "MIT" ]
permissive
nodemcu/nodemcu-firmware
fd907ddf01bf17fdc55dd352d6987ee91d8b95e3
f25dc56d3c6213b8ac7ce46d1293466137746eae
refs/heads/release
2023-08-22T21:46:10.995686
2021-12-30T07:46:20
2021-12-30T07:46:20
26,917,568
8,077
3,888
MIT
2023-07-25T09:20:45
2014-11-20T15:06:45
C
UTF-8
C
false
false
27,537
c
ws2812_effects.c
#include "module.h" #include "lauxlib.h" #include "lmem.h" #include "platform.h" #include <stdlib.h> #include <math.h> #include <string.h> #include "user_interface.h" #include "driver/uart.h" #include "osapi.h" #include "pm/swtimer.h" #include "pixbuf.h" #include "color_utils.h" #ifdef LUA_USE_MODULES_WS2812_EFFECTS #ifndef LUA_USE_MODULES_PIXBUF # error module pixbuf is required for ws2812_effects #endif #ifndef LUA_USE_MODULES_COLOR_UTILS # error module color_utilsf is required for ws2812_effects #endif #endif #define CANARY_VALUE 0x32372132 #define DEFAULT_MODE 0 #define DEFAULT_COLOR 0xFF0000 #define SPEED_MIN 0 #define SPEED_MAX 255 #define SPEED_DEFAULT 150 #define DELAY_DEFAULT 100 #define BRIGHTNESS_MIN 0 #define BRIGHTNESS_MAX 255 #define BRIGHTNESS_DEFAULT 100 #define EFFECT_PARAM_INVALID -10000 #define LIBRARY_NOT_INITIALIZED_ERROR_MSG "please call init() first" #define min(a,b) ((a) < (b) ? (a) : (b)) #define max(a,b) ((a) > (b) ? (a) : (b)) #define abs(a) ((a) > 0 ? (a) : (0-a)) #define min3(a,b, c) min((a), min((b), (c))) #define max3(a,b, c) max((a), max((b), (c))) #define IDX_R 1 #define IDX_G 0 #define IDX_B 2 #define IDX_W 3 typedef struct { pixbuf *buffer; int buffer_ref; uint32_t mode_delay; uint32_t counter_mode_call; uint32_t counter_mode_step; uint8_t mode_color_index; uint8_t speed; uint8_t brightness; os_timer_t os_t; uint8_t running; uint8_t effect_type; uint8_t color[4]; int effect_int_param1; struct pixbuf_shift_params shift; } ws2812_effects; enum ws2812_effects_type { WS2812_EFFECT_STATIC, WS2812_EFFECT_BLINK, WS2812_EFFECT_GRADIENT, WS2812_EFFECT_GRADIENT_RGB, WS2812_EFFECT_RANDOM_COLOR, WS2812_EFFECT_RAINBOW, WS2812_EFFECT_RAINBOW_CYCLE, WS2812_EFFECT_FLICKER, WS2812_EFFECT_FIRE_FLICKER, WS2812_EFFECT_FIRE_FLICKER_SOFT, WS2812_EFFECT_FIRE_FLICKER_INTENSE, WS2812_EFFECT_HALLOWEEN, WS2812_EFFECT_CIRCUS_COMBUSTUS, WS2812_EFFECT_LARSON_SCANNER, WS2812_EFFECT_CYCLE, WS2812_EFFECT_COLOR_WIPE, WS2812_EFFECT_RANDOM_DOT }; static ws2812_effects *state; //----------------- // UTILITY METHODS //----------------- // XXX Not exported because this module is its sole non-Lua consumer and we // should be going away soon! Deprecated, 'n all that. extern void ICACHE_RAM_ATTR ws2812_write_data( const uint8_t *pixels, uint32_t length, const uint8_t *pixels2, uint32_t length2); static int ws2812_effects_write(pixbuf* buffer) { ws2812_write_data(buffer->values, pixbuf_size(buffer), 0, 0); return 0; } // :opens_boxes -1 static void ws2812_set_pixel(int pixel, uint32_t color) { pixbuf * buffer = state->buffer; uint8_t g = ((color & 0x00FF0000) >> 16); uint8_t r = ((color & 0x0000FF00) >> 8); uint8_t b = (color & 0x000000FF); uint8_t w = pixbuf_channels(buffer) == 4 ? ((color & 0xFF000000) >> 24) : 0; int offset = pixel * pixbuf_channels(buffer); buffer->values[offset+IDX_R] = r; buffer->values[offset+IDX_G] = g; buffer->values[offset+IDX_B] = b; if (pixbuf_channels(buffer) == 4) { buffer->values[offset+IDX_W] = w; } } /* * Returns a new, random color wheel index with a minimum distance of 42 from pos. */ static uint8_t get_random_wheel_index(uint8_t pos) { uint8_t r = 0; uint8_t x = 0; uint8_t y = 0; uint8_t d = 0; while(d < 42) { r = rand() % 360; x = abs(pos - r); y = 360 - x; d = min(x, y); } return r; } //----------------- // EFFECTS LIBRARY //----------------- /** * initialized ws2812_effects with the buffer to use */ static int ws2812_effects_init(lua_State *L) { platform_print_deprecation_note("ws2812_effects", "soon; please see https://github.com/nodemcu/nodemcu-firmware/issues/3122"); pixbuf * buffer = pixbuf_from_lua_arg(L, 1); // get rid of old state if (state != NULL) { luaL_unref(L, LUA_REGISTRYINDEX, state->buffer_ref); free((void *) state); } // Allocate memory and set all to zero state = (ws2812_effects *) calloc(1,sizeof(ws2812_effects)); // initialize state->speed = SPEED_DEFAULT; state->mode_delay = DELAY_DEFAULT; state->brightness = BRIGHTNESS_DEFAULT; state->buffer = buffer; state->buffer_ref = luaL_ref(L, LUA_REGISTRYINDEX); return 0; } /* * set color for single color effects */ static int ws2812_effects_set_color(lua_State* L) { luaL_argcheck(L, state != NULL, 1, LIBRARY_NOT_INITIALIZED_ERROR_MSG); uint8_t g = luaL_checkinteger(L, 1); uint8_t r = luaL_checkinteger(L, 2); uint8_t b = luaL_checkinteger(L, 3); uint8_t w = luaL_optinteger(L, 4, 0 ); state->color[0] = g; state->color[1] = r; state->color[2] = b; state->color[3] = w; return 0; } static int ws2812_effects_get_speed(lua_State* L) { luaL_argcheck(L, state != NULL, 1, LIBRARY_NOT_INITIALIZED_ERROR_MSG); lua_pushinteger(L, state->speed); return 1; } static int ws2812_effects_set_speed(lua_State* L) { int speed = luaL_checkinteger(L, 1); luaL_argcheck(L, state != NULL, 1, LIBRARY_NOT_INITIALIZED_ERROR_MSG); luaL_argcheck(L, speed >= SPEED_MIN && speed <= SPEED_MAX, 1, "should be 0-255"); state->speed = (uint8_t)speed; state->mode_delay = 10; return 0; } static int ws2812_effects_get_delay(lua_State* L) { luaL_argcheck(L, state != NULL, 1, LIBRARY_NOT_INITIALIZED_ERROR_MSG); lua_pushinteger(L, state->mode_delay); return 1; } static int ws2812_effects_set_delay(lua_State* L) { luaL_argcheck(L, state != NULL, 1, LIBRARY_NOT_INITIALIZED_ERROR_MSG); const int delay = luaL_checkinteger(L, 1); luaL_argcheck(L, delay >= 10, 1, "must be equal / larger than 10"); state->mode_delay = delay; state->speed = 0; return 1; } static int ws2812_effects_set_brightness(lua_State* L) { int brightness = luaL_checkint(L, 1); luaL_argcheck(L, state != NULL, 1, LIBRARY_NOT_INITIALIZED_ERROR_MSG); luaL_argcheck(L, brightness >= BRIGHTNESS_MIN && brightness <= BRIGHTNESS_MAX, 1, "should be 0-255"); state->brightness = (uint8_t) brightness; return 0; } // :opens_boxes -1 static void ws2812_effects_fill_buffer(uint8_t r, uint8_t g, uint8_t b, uint8_t w) { pixbuf * buffer = state->buffer; uint8_t bright_g = g * state->brightness / BRIGHTNESS_MAX; uint8_t bright_r = r * state->brightness / BRIGHTNESS_MAX; uint8_t bright_b = b * state->brightness / BRIGHTNESS_MAX; uint8_t bright_w = w * state->brightness / BRIGHTNESS_MAX; // Fill buffer int i; uint8_t * p = &buffer->values[0]; for(i = 0; i < buffer->npix; i++) { *p++ = bright_g; *p++ = bright_r; *p++ = bright_b; if (pixbuf_channels(buffer) == 4) { *p++ = bright_w; } } } //------------------ // basic methods //------------------ /* * Cycles all LEDs at once through a rainbow. */ static int ws2812_effects_fill_color() { uint8_t g = state->color[0]; uint8_t r = state->color[1]; uint8_t b = state->color[2]; uint8_t w = state->color[3]; ws2812_effects_fill_buffer(r, g, b, w); return 0; } //----------------- // EFFECFTS //----------------- /* * blink with set color */ static int ws2812_effects_mode_blink() { if(state->counter_mode_call % 2 == 1) { // on ws2812_effects_fill_color(); } else { // off pixbuf * buffer = state->buffer; memset(&buffer->values[0], 0, pixbuf_size(buffer)); } return 0; } static int ws2812_effects_gradient(const char *gradient_spec, size_t length1) { pixbuf * buffer = state->buffer; int segments = (length1 / pixbuf_channels(buffer)) - 1; int segmentSize = buffer->npix / segments; uint8_t g1, r1, b1, g2, r2, b2; int i,j,k; g2 = *gradient_spec++; r2 = *gradient_spec++; b2 = *gradient_spec++; // skip non-rgb components for (j = 3; j < pixbuf_channels(buffer); j++) { *gradient_spec++; } // reference to buffer memory uint8_t * p = &buffer->values[0]; uint16_t h1,h2; uint8_t s,v,s1,v1,s2,v2; for (k = 0; k < segments; k++) { g1 = g2; r1 = r2; b1 = b2; uint32_t hsv1 = grb2hsv(g1, r1, b1); h1 = (hsv1 & 0xFFFF0000) >> 16; s1 = (hsv1 & 0x0000FF00) >> 8; v1 = (hsv1 & 0x000000FF); g2 = *gradient_spec++; r2 = *gradient_spec++; b2 = *gradient_spec++; for (j = 3; j < pixbuf_channels(buffer); j++) { *gradient_spec++; } uint32_t hsv2 = grb2hsv(g2, r2, b2); h2 = (hsv2 & 0xFFFF0000) >> 16; s2 = (hsv1 & 0x0000FF00) >> 8; v2 = (hsv1 & 0x000000FF); // get distance and direction to use int maxCCW = h1 > h2 ? h1 - h2 : 360 + h1 - h2; int maxCW = h1 > h2 ? 360 + h2 - h1 : h2 - h1; // Fill buffer int numPixels = segmentSize; // make sure we fill the strip correctly in case of rounding errors if (k == segments - 1) { numPixels = buffer->npix - (segmentSize * (segments - 1)); } int steps = numPixels - 1; for(i = 0; i < numPixels; i++) { // calculate HSV values //h = h1 + ((h2-h1) * i / fillSize); int h = maxCCW > maxCW ? h1 + ((maxCW * i / steps) % 360) : h1 - (maxCCW * i / steps); if (h < 0) h = h + 360; if (h > 359) h = h - 360; s = s1 + ((s2-s1) * i / steps); v = v1 + ((v2-v1) * i / steps); // convert to RGB uint32_t grb = hsv2grb(h, s, v); *p++ = ((grb & 0x00FF0000) >> 16) * state->brightness / BRIGHTNESS_MAX; *p++ = ((grb & 0x0000FF00) >> 8) * state->brightness / BRIGHTNESS_MAX; *p++ = (grb & 0x000000FF) * state->brightness / BRIGHTNESS_MAX; for (j = 3; j < pixbuf_channels(buffer); j++) { *p++ = 0; } } } return 0; } static int ws2812_effects_gradient_rgb(const char *buffer1, size_t length1) { pixbuf * buffer = state->buffer; int segments = (length1 / pixbuf_channels(buffer)) - 1; int segmentSize = buffer->npix / segments; uint8_t g1, r1, b1, g2, r2, b2; int i,j,k; g2 = *buffer1++; r2 = *buffer1++; b2 = *buffer1++; // skip non-rgb components for (j = 3; j < pixbuf_channels(buffer); j++) { *buffer1++; } // reference to buffer memory uint8_t * p = &buffer->values[0]; for (k = 0; k < segments; k++) { g1 = g2; r1 = r2; b1 = b2; g2 = *buffer1++; r2 = *buffer1++; b2 = *buffer1++; for (j = 3; j < pixbuf_channels(buffer); j++) { *buffer1++; } // Fill buffer int numPixels = segmentSize; // make sure we fill the strip correctly in case of rounding errors if (k == segments - 1) { numPixels = buffer->npix - (segmentSize * (segments - 1)); } int steps = numPixels - 1; for(i = 0; i < numPixels; i++) { *p++ = (g1 + ((g2-g1) * i / steps)) * state->brightness / BRIGHTNESS_MAX; *p++ = (r1 + ((r2-r1) * i / steps)) * state->brightness / BRIGHTNESS_MAX; *p++ = (b1 + ((b2-b1) * i / steps)) * state->brightness / BRIGHTNESS_MAX; for (j = 3; j < pixbuf_channels(buffer); j++) { *p++ = 0; } } } return 0; } /* * Lights all LEDs in one random color up. Then switches them * to the next random color. */ static int ws2812_effects_mode_random_color() { state->mode_color_index = get_random_wheel_index(state->mode_color_index); pixbuf * buffer = state->buffer; uint32_t color = color_wheel(state->mode_color_index); uint8_t r = ((color & 0x00FF0000) >> 16) * state->brightness / BRIGHTNESS_MAX; uint8_t g = ((color & 0x0000FF00) >> 8) * state->brightness / BRIGHTNESS_MAX; uint8_t b = ((color & 0x000000FF) >> 0) * state->brightness / BRIGHTNESS_MAX; // Fill buffer int i,j; uint8_t * p = &buffer->values[0]; for(i = 0; i < buffer->npix; i++) { *p++ = g; *p++ = r; *p++ = b; for (j = 3; j < pixbuf_channels(buffer); j++) { *p++ = 0; } } } /* * Cycles all LEDs at once through a rainbow. */ static int ws2812_effects_mode_rainbow() { pixbuf * buffer = state->buffer; uint32_t color = color_wheel(state->counter_mode_step); uint8_t r = (color & 0x00FF0000) >> 16; uint8_t g = (color & 0x0000FF00) >> 8; uint8_t b = (color & 0x000000FF) >> 0; // Fill buffer int i,j; uint8_t * p = &buffer->values[0]; for(i = 0; i < buffer->npix; i++) { *p++ = g * state->brightness / BRIGHTNESS_MAX; *p++ = r * state->brightness / BRIGHTNESS_MAX; *p++ = b * state->brightness / BRIGHTNESS_MAX; for (j = 3; j < pixbuf_channels(buffer); j++) { *p++ = 0; } } state->counter_mode_step = (state->counter_mode_step + 1) % 360; return 0; } /* * Cycles a rainbow over the entire string of LEDs. */ static int ws2812_effects_mode_rainbow_cycle(int repeat_count) { pixbuf * buffer = state->buffer; int i,j; uint8_t * p = &buffer->values[0]; for(i = 0; i < buffer->npix; i++) { uint16_t wheel_index = (i * 360 / buffer->npix * repeat_count) % 360; uint32_t color = color_wheel(wheel_index); uint8_t r = ((color & 0x00FF0000) >> 16) * state->brightness / BRIGHTNESS_MAX; uint8_t g = ((color & 0x0000FF00) >> 8) * state->brightness / BRIGHTNESS_MAX; uint8_t b = ((color & 0x000000FF) >> 0) * state->brightness / BRIGHTNESS_MAX; *p++ = g; *p++ = r; *p++ = b; for (j = 3; j < pixbuf_channels(buffer); j++) { *p++ = 0; } } return 0; } /* * Random flickering. */ static int ws2812_effects_mode_flicker_int(uint8_t max_flicker) { pixbuf * buffer = state->buffer; uint8_t p_g = state->color[0]; uint8_t p_r = state->color[1]; uint8_t p_b = state->color[2]; // Fill buffer int i,j; uint8_t * p = &buffer->values[0]; for(i = 0; i < buffer->npix; i++) { int flicker = rand() % (max_flicker > 0 ? max_flicker : 1); int r1 = p_r-flicker; int g1 = p_g-flicker; int b1 = p_b-flicker; if(g1<0) g1=0; if(r1<0) r1=0; if(b1<0) b1=0; *p++ = g1 * state->brightness / BRIGHTNESS_MAX; *p++ = r1 * state->brightness / BRIGHTNESS_MAX; *p++ = b1 * state->brightness / BRIGHTNESS_MAX; for (j = 3; j < pixbuf_channels(buffer); j++) { *p++ = 0; } } return 0; } /** * Halloween effect */ static int ws2812_effects_mode_halloween() { pixbuf * buffer = state->buffer; int g1 = 50 * state->brightness / BRIGHTNESS_MAX; int r1 = 255 * state->brightness / BRIGHTNESS_MAX; int b1 = 0 * state->brightness / BRIGHTNESS_MAX; int g2 = 0 * state->brightness / BRIGHTNESS_MAX; int r2 = 255 * state->brightness / BRIGHTNESS_MAX; int b2 = 130 * state->brightness / BRIGHTNESS_MAX; // Fill buffer int i,j; uint8_t * p = &buffer->values[0]; for(i = 0; i < buffer->npix; i++) { *p++ = (i % 4 < 2) ? g1 : g2; *p++ = (i % 4 < 2) ? r1 : r2; *p++ = (i % 4 < 2) ? b1 : b2; for (j = 3; j < pixbuf_channels(buffer); j++) { *p++ = 0; } } return 0; } static int ws2812_effects_mode_circus_combustus() { pixbuf * buffer = state->buffer; int g1 = 0 * state->brightness / BRIGHTNESS_MAX; int r1 = 255 * state->brightness / BRIGHTNESS_MAX; int b1 = 0 * state->brightness / BRIGHTNESS_MAX; int g2 = 255 * state->brightness / BRIGHTNESS_MAX; int r2 = 255 * state->brightness / BRIGHTNESS_MAX; int b2 = 255 * state->brightness / BRIGHTNESS_MAX; // Fill buffer int i,j; uint8_t * p = &buffer->values[0]; for(i = 0; i < buffer->npix; i++) { if (i % 6 < 2) { *p++ = g1; *p++ = r1; *p++ = b1; } else if (i % 6 < 4) { *p++ = g2; *p++ = r2; *p++ = b2; } else { *p++ = 0; *p++ = 0; *p++ = 0; } for (j = 3; j < pixbuf_channels(buffer); j++) { *p++ = 0; } } return 0; } /* * K.I.T.T. */ static int ws2812_effects_mode_larson_scanner() { pixbuf * buffer = state->buffer; int led_index = 0; for(int i=0; i < pixbuf_size(buffer); i++) { buffer->values[i] = buffer->values[i] >> 2; } uint16_t pos = 0; if(state->counter_mode_step < buffer->npix) { pos = state->counter_mode_step; } else { pos = (buffer->npix * 2) - state->counter_mode_step - 2; } pos = pos * pixbuf_channels(buffer); buffer->values[pos + 1] = state->color[1]; buffer->values[pos] = state->color[0]; buffer->values[pos + 2] = state->color[2]; state->counter_mode_step = (state->counter_mode_step + 1) % ((buffer->npix * 2) - 2); } static int ws2812_effects_mode_color_wipe() { pixbuf * buffer = state->buffer; int led_index = (state->counter_mode_step % buffer->npix) * pixbuf_channels(buffer); if (state->counter_mode_step >= buffer->npix) { buffer->values[led_index] = 0; buffer->values[led_index + 1] = 0; buffer->values[led_index + 2] = 0; } else { uint8_t px_r = state->color[1] * state->brightness / BRIGHTNESS_MAX; uint8_t px_g = state->color[0] * state->brightness / BRIGHTNESS_MAX; uint8_t px_b = state->color[2] * state->brightness / BRIGHTNESS_MAX; buffer->values[led_index] = px_g; buffer->values[led_index + 1] = px_r; buffer->values[led_index + 2] = px_b; } state->counter_mode_step = (state->counter_mode_step + 1) % (buffer->npix * 2); } static int ws2812_effects_mode_random_dot(uint8_t dots) { pixbuf * buffer = state->buffer; // fade out for(int i=0; i < pixbuf_size(buffer); i++) { buffer->values[i] = buffer->values[i] >> 1; } for(int i=0; i < dots; i++) { // pick random pixel int led_index = rand() % buffer->npix; uint32_t color = (state->color[0] << 16) | (state->color[1] << 8) | state->color[2]; if (pixbuf_channels(buffer) == 4) { color = color | (state->color[3] << 24); } ws2812_set_pixel(led_index, color); } state->counter_mode_step = (state->counter_mode_step + 1) % ((buffer->npix * 2) - 2); } static uint32_t ws2812_effects_mode_delay() { // check if delay has been set explicitly if (state->speed == 0 && state->mode_delay > 0) { return state->mode_delay; } uint32_t delay = 10; switch (state->effect_type) { case WS2812_EFFECT_BLINK: case WS2812_EFFECT_RAINBOW: case WS2812_EFFECT_RAINBOW_CYCLE: delay = 10 + ((1000 * (uint32_t)(SPEED_MAX - state->speed)) / SPEED_MAX); break; case WS2812_EFFECT_FLICKER: case WS2812_EFFECT_FIRE_FLICKER: case WS2812_EFFECT_FIRE_FLICKER_SOFT: case WS2812_EFFECT_FIRE_FLICKER_INTENSE: delay = 30 + (rand() % 100) + (200 * (SPEED_MAX - state->speed) / SPEED_MAX); break; case WS2812_EFFECT_RANDOM_COLOR: case WS2812_EFFECT_HALLOWEEN: case WS2812_EFFECT_CIRCUS_COMBUSTUS: case WS2812_EFFECT_LARSON_SCANNER: case WS2812_EFFECT_CYCLE: case WS2812_EFFECT_COLOR_WIPE: case WS2812_EFFECT_RANDOM_DOT: delay = 10 + ((1000 * (uint32_t)(SPEED_MAX - state->speed)) / SPEED_MAX); break; } return delay; } static void ws2812_effects_do_shift(void) { pixbuf_shift(state->buffer, &state->shift); ws2812_effects_write(state->buffer); } /** * run loop for the effects. */ static void ws2812_effects_loop(void* p) { if (state->effect_type == WS2812_EFFECT_BLINK) { ws2812_effects_mode_blink(); } else if (state->effect_type == WS2812_EFFECT_RAINBOW) { ws2812_effects_mode_rainbow(); } else if (state->effect_type == WS2812_EFFECT_RAINBOW_CYCLE) { // the rainbow cycle effect can be achieved by shifting the buffer ws2812_effects_do_shift(); } else if (state->effect_type == WS2812_EFFECT_FLICKER) { int flicker_value = state->effect_int_param1 != EFFECT_PARAM_INVALID ? state->effect_int_param1 : 100; if (flicker_value == 0) { flicker_value = 50; } ws2812_effects_mode_flicker_int(flicker_value); state->counter_mode_step = (state->counter_mode_step + 1) % 256; } else if (state->effect_type == WS2812_EFFECT_FIRE_FLICKER) { ws2812_effects_mode_flicker_int(110); state->counter_mode_step = (state->counter_mode_step + 1) % 256; } else if (state->effect_type == WS2812_EFFECT_FIRE_FLICKER_SOFT) { ws2812_effects_mode_flicker_int(70); state->counter_mode_step = (state->counter_mode_step + 1) % 256; } else if (state->effect_type == WS2812_EFFECT_FIRE_FLICKER_INTENSE) { ws2812_effects_mode_flicker_int(170); state->counter_mode_step = (state->counter_mode_step + 1) % 256; } else if (state->effect_type == WS2812_EFFECT_RANDOM_COLOR) { ws2812_effects_mode_random_color(); } else if (state->effect_type == WS2812_EFFECT_HALLOWEEN) { ws2812_effects_do_shift(); } else if (state->effect_type == WS2812_EFFECT_CIRCUS_COMBUSTUS) { ws2812_effects_do_shift(); } else if (state->effect_type == WS2812_EFFECT_LARSON_SCANNER) { ws2812_effects_mode_larson_scanner(); } else if (state->effect_type == WS2812_EFFECT_CYCLE) { ws2812_effects_do_shift(); } else if (state->effect_type == WS2812_EFFECT_COLOR_WIPE) { ws2812_effects_mode_color_wipe(); } else if (state->effect_type == WS2812_EFFECT_RANDOM_DOT) { uint8_t dots = state->effect_int_param1 != EFFECT_PARAM_INVALID ? state->effect_int_param1 : 1; ws2812_effects_mode_random_dot(dots); } // set the new delay for this effect state->mode_delay = ws2812_effects_mode_delay(); // call count state->counter_mode_call = (state->counter_mode_call + 1) % UINT32_MAX; // write the buffer ws2812_effects_write(state->buffer); // set the timer if (state->running == 1 && state->mode_delay >= 10) if (state->running == 1 && state->mode_delay >= 10) { os_timer_disarm(&(state->os_t)); os_timer_arm(&(state->os_t), state->mode_delay, FALSE); } } /** * Set the active effect mode */ static int ws2812_effects_set_mode(lua_State* L) { luaL_argcheck(L, state != NULL, 1, LIBRARY_NOT_INITIALIZED_ERROR_MSG); // opts must be same order as effect type enum static const char * const opts[] = {"static", "blink", "gradient", "gradient_rgb", "random_color", "rainbow", "rainbow_cycle", "flicker", "fire", "fire_soft", "fire_intense", "halloween", "circus_combustus", "larson_scanner", "cycle", "color_wipe", "random_dot", NULL}; int type = luaL_checkoption(L, 1, NULL, opts); state->effect_type = type; int effect_param = EFFECT_PARAM_INVALID; // check additional int parameter // First mandatory parameter int arg_type = lua_type(L, 2); if (arg_type == LUA_TNONE || arg_type == LUA_TNIL) { // we don't have a second parameter } else if(arg_type == LUA_TNUMBER) { effect_param = luaL_optinteger( L, 2, EFFECT_PARAM_INVALID ); } // initialize the effect state->counter_mode_step = 0; switch (state->effect_type) { case WS2812_EFFECT_STATIC: // fill with currently set color ws2812_effects_fill_color(); state->mode_delay = 250; break; case WS2812_EFFECT_BLINK: ws2812_effects_mode_blink(); break; case WS2812_EFFECT_GRADIENT: if(arg_type == LUA_TSTRING) { size_t length1; const char *buffer1 = lua_tolstring(L, 2, &length1); if ((length1 / pixbuf_channels(state->buffer) < 2) || (length1 % pixbuf_channels(state->buffer) != 0)) { luaL_argerror(L, 2, "must be at least two colors and same size as buffer colors"); } ws2812_effects_gradient(buffer1, length1); ws2812_effects_write(state->buffer); } else { luaL_argerror(L, 2, "string expected"); } break; case WS2812_EFFECT_GRADIENT_RGB: if(arg_type == LUA_TSTRING) { size_t length1; const char *buffer1 = lua_tolstring(L, 2, &length1); if ((length1 / pixbuf_channels(state->buffer) < 2) || (length1 % pixbuf_channels(state->buffer) != 0)) { luaL_argerror(L, 2, "must be at least two colors and same size as buffer colors"); } ws2812_effects_gradient_rgb(buffer1, length1); ws2812_effects_write(state->buffer); } else { luaL_argerror(L, 2, "string expected"); } break; case WS2812_EFFECT_RANDOM_COLOR: ws2812_effects_mode_random_color(); break; case WS2812_EFFECT_RAINBOW: ws2812_effects_mode_rainbow(); break; case WS2812_EFFECT_RAINBOW_CYCLE: ws2812_effects_mode_rainbow_cycle(effect_param != EFFECT_PARAM_INVALID ? effect_param : 1); pixbuf_prepare_shift(state->buffer, &state->shift, 1, PIXBUF_SHIFT_CIRCULAR, 1, -1); break; case WS2812_EFFECT_FLICKER: state->effect_int_param1 = effect_param; break; case WS2812_EFFECT_FIRE_FLICKER: case WS2812_EFFECT_FIRE_FLICKER_SOFT: case WS2812_EFFECT_FIRE_FLICKER_INTENSE: state->color[0] = 255-40; state->color[1] = 255; state->color[2] = 40; state->color[3] = 0; break; case WS2812_EFFECT_HALLOWEEN: ws2812_effects_mode_halloween(); pixbuf_prepare_shift(state->buffer, &state->shift, 1, PIXBUF_SHIFT_CIRCULAR, 1, -1); break; case WS2812_EFFECT_CIRCUS_COMBUSTUS: ws2812_effects_mode_circus_combustus(); pixbuf_prepare_shift(state->buffer, &state->shift, 1, PIXBUF_SHIFT_CIRCULAR, 1, -1); break; case WS2812_EFFECT_LARSON_SCANNER: ws2812_effects_mode_larson_scanner(); break; case WS2812_EFFECT_CYCLE: if (effect_param != EFFECT_PARAM_INVALID) { state->effect_int_param1 = effect_param; } pixbuf_prepare_shift(state->buffer, &state->shift, state->effect_int_param1, PIXBUF_SHIFT_CIRCULAR, 1, -1); break; case WS2812_EFFECT_COLOR_WIPE: // fill buffer with black. r,g,b,w = 0 ws2812_effects_fill_buffer(0, 0, 0, 0); ws2812_effects_mode_color_wipe(); break; case WS2812_EFFECT_RANDOM_DOT: // check if more than 1 dot shall be set state->effect_int_param1 = effect_param; // fill buffer with black. r,g,b,w = 0 ws2812_effects_fill_buffer(0, 0, 0, 0); break; } } /* * Start the effect execution */ static int ws2812_effects_start(lua_State* L) { //NODE_DBG("pin:%d, level:%d \n", pin, level); luaL_argcheck(L, state != NULL, 1, LIBRARY_NOT_INITIALIZED_ERROR_MSG); if (state != NULL) { os_timer_disarm(&(state->os_t)); state->running = 1; state->counter_mode_call = 0; state->counter_mode_step = 0; // set the timer os_timer_setfn(&(state->os_t), ws2812_effects_loop, NULL); os_timer_arm(&(state->os_t), state->mode_delay, FALSE); } return 0; } /* * Stop the effect execution */ static int ws2812_effects_stop(lua_State* L) { luaL_argcheck(L, state != NULL, 1, LIBRARY_NOT_INITIALIZED_ERROR_MSG); if (state != NULL) { os_timer_disarm(&(state->os_t)); state->running = 0; } return 0; } static int ws2812_effects_tostring(lua_State* L) { luaL_Buffer result; luaL_buffinit(L, &result); luaL_addchar(&result, '['); luaL_addstring(&result, "effects"); luaL_addchar(&result, ']'); luaL_pushresult(&result); return 1; } LROT_BEGIN(ws2812_effects_map, NULL, 0) LROT_FUNCENTRY( __tostring, ws2812_effects_tostring ) LROT_FUNCENTRY( init, ws2812_effects_init ) LROT_FUNCENTRY( set_brightness, ws2812_effects_set_brightness ) LROT_FUNCENTRY( set_color, ws2812_effects_set_color ) LROT_FUNCENTRY( set_speed, ws2812_effects_set_speed ) LROT_FUNCENTRY( set_delay, ws2812_effects_set_delay ) LROT_FUNCENTRY( set_mode, ws2812_effects_set_mode ) LROT_FUNCENTRY( start, ws2812_effects_start ) LROT_FUNCENTRY( stop, ws2812_effects_stop ) LROT_FUNCENTRY( get_delay, ws2812_effects_get_delay ) LROT_FUNCENTRY( get_speed, ws2812_effects_get_speed ) LROT_END(ws2812_effects_map, NULL, 0) NODEMCU_MODULE(WS2812_EFFECTS, "ws2812_effects", ws2812_effects_map, NULL);
c64c44d11a306bea5f1e15ac4120ca141958d296
e814383d36a10839104efaa4df277996ab220fa3
/opal/mca/threads/thread_usage.h
3eeca968c0691481a4064d26c7b14a80e5b7c25a
[ "mpich2", "BSD-3-Clause-Open-MPI" ]
permissive
open-mpi/ompi
a1d7483ae1d83dd8fd8ae3ee95e832e0a0ee04e3
1edfdb025c4450f694600083ad871cf06c8d45cd
refs/heads/main
2023-09-01T01:30:02.040705
2023-08-29T17:32:18
2023-08-29T17:32:18
24,107,001
2,008
973
NOASSERTION
2023-09-14T20:59:26
2014-09-16T16:08:30
C
UTF-8
C
false
false
13,256
h
thread_usage.h
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil -*- */ /* * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2007 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2006 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2007-2014 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2014-2016 Research Organization for Information Science * and Technology (RIST). All rights reserved. * Copyright (c) 2015-2018 Los Alamos National Security, LLC. All rights * reserved. * Copyright (c) 2019 Sandia National Laboratories. All rights reserved. * * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #ifndef OPAL_MCA_THREADS_THREAD_USAGE_H #define OPAL_MCA_THREADS_THREAD_USAGE_H #include "opal_config.h" #include "opal/prefetch.h" #include "opal/sys/atomic.h" OPAL_DECLSPEC extern bool opal_uses_threads; /** * Check and see if the process is using multiple threads. * * @retval true If the process may have more than one thread. * @retval false If the process only has a single thread. * * The value that this function returns is influenced by: * * - how MPI_INIT or MPI_INIT_THREAD was invoked, * - what the final MPI thread level was determined to be, * - whether the OMPI or MPI libraries are multi-threaded * * MPI_INIT and MPI_INIT_THREAD (specifically, back-end OMPI startup * functions) invoke opal_set_using_threads() to influence the value of * this function, depending on their situation. Some examples: * * - if MPI_INIT is invoked, and the ompi components in use are * single-threaded, this value will be false. * * - if MPI_INIT_THREAD is invoked with MPI_THREAD_MULTIPLE, we have * thread support, and the final thread level is determined to be * MPI_THREAD_MULTIPLE, this value will be true. * * - if the process is a single-threaded OMPI executable (e.g., mpicc), * this value will be false. * * Hence, this function will return false if there is guaranteed to * only be one thread in the process. If there is even the * possibility that we may have multiple threads, true will be * returned. */ #define opal_using_threads() opal_uses_threads /** * Set whether the process is using multiple threads or not. * * @param have Boolean indicating whether the process is using * multiple threads or not. * * @retval opal_using_threads The new return value from * opal_using_threads(). * * This function is used to influence the return value of * opal_using_threads(). If configure detected that we have thread * support, the return value of future invocations of * opal_using_threads() will be the parameter's value. If configure * detected that we have no thread support, then the return from * opal_using_threads() will always be false. */ static inline bool opal_set_using_threads(bool have) { opal_uses_threads = have; return opal_using_threads(); } /** * Use an atomic operation for increment/decrement if opal_using_threads() * indicates that threads are in use by the application or library. */ #define OPAL_THREAD_DEFINE_ATOMIC_OP(type, name, operator, suffix) \ static inline type opal_thread_##name##_fetch_##suffix(opal_atomic_##type *addr, type delta) \ { \ if (OPAL_UNLIKELY(opal_using_threads())) { \ return opal_atomic_##name##_fetch_##suffix(addr, delta); \ } \ \ *addr = *addr operator delta; \ return *addr; \ } \ \ static inline type opal_thread_fetch_##name##_##suffix(opal_atomic_##type *addr, type delta) \ { \ if (OPAL_UNLIKELY(opal_using_threads())) { \ return opal_atomic_fetch_##name##_##suffix(addr, delta); \ } \ \ type old = *addr; \ *addr = old operator delta; \ return old; \ } #define OPAL_THREAD_DEFINE_ATOMIC_COMPARE_EXCHANGE(type, addr_type, suffix) \ static inline bool opal_thread_compare_exchange_strong_##suffix(opal_atomic_##addr_type *addr, \ type *compare, type value) \ { \ if (OPAL_UNLIKELY(opal_using_threads())) { \ return opal_atomic_compare_exchange_strong_##suffix(addr, (addr_type *) compare, \ (addr_type) value); \ } \ \ if ((type) *addr == *compare) { \ ((type *) addr)[0] = value; \ return true; \ } \ \ *compare = ((type *) addr)[0]; \ \ return false; \ } #define OPAL_THREAD_DEFINE_ATOMIC_SWAP(type, addr_type, suffix) \ static inline type opal_thread_swap_##suffix(opal_atomic_##addr_type *ptr, type newvalue) \ { \ if (opal_using_threads()) { \ return (type) opal_atomic_swap_##suffix(ptr, (addr_type) newvalue); \ } \ \ type old = ((type *) ptr)[0]; \ ((type *) ptr)[0] = newvalue; \ \ return old; \ } OPAL_THREAD_DEFINE_ATOMIC_OP(int32_t, add, +, 32) OPAL_THREAD_DEFINE_ATOMIC_OP(size_t, add, +, size_t) OPAL_THREAD_DEFINE_ATOMIC_OP(int32_t, and, &, 32) OPAL_THREAD_DEFINE_ATOMIC_OP(int32_t, or, |, 32) OPAL_THREAD_DEFINE_ATOMIC_OP(int32_t, xor, ^, 32) OPAL_THREAD_DEFINE_ATOMIC_OP(int32_t, sub, -, 32) OPAL_THREAD_DEFINE_ATOMIC_OP(size_t, sub, -, size_t) OPAL_THREAD_DEFINE_ATOMIC_COMPARE_EXCHANGE(int32_t, int32_t, 32) OPAL_THREAD_DEFINE_ATOMIC_COMPARE_EXCHANGE(intptr_t, intptr_t, ptr) OPAL_THREAD_DEFINE_ATOMIC_SWAP(int32_t, int32_t, 32) OPAL_THREAD_DEFINE_ATOMIC_SWAP(intptr_t, intptr_t, ptr) #define OPAL_THREAD_ADD_FETCH32 opal_thread_add_fetch_32 #define OPAL_ATOMIC_ADD_FETCH32 opal_thread_add_fetch_32 #define OPAL_THREAD_AND_FETCH32 opal_thread_and_fetch_32 #define OPAL_ATOMIC_AND_FETCH32 opal_thread_and_fetch_32 #define OPAL_THREAD_OR_FETCH32 opal_thread_or_fetch_32 #define OPAL_ATOMIC_OR_FETCH32 opal_thread_or_fetch_32 #define OPAL_THREAD_XOR_FETCH32 opal_thread_xor_fetch_32 #define OPAL_ATOMIC_XOR_FETCH32 opal_thread_xor_fetch_32 #define OPAL_THREAD_ADD_FETCH_SIZE_T opal_thread_add_fetch_size_t #define OPAL_ATOMIC_ADD_FETCH_SIZE_T opal_thread_add_fetch_size_t #define OPAL_THREAD_SUB_FETCH_SIZE_T opal_thread_sub_fetch_size_t #define OPAL_ATOMIC_SUB_FETCH_SIZE_T opal_thread_sub_fetch_size_t #define OPAL_THREAD_FETCH_ADD32 opal_thread_fetch_add_32 #define OPAL_ATOMIC_FETCH_ADD32 opal_thread_fetch_add_32 #define OPAL_THREAD_FETCH_AND32 opal_thread_fetch_and_32 #define OPAL_ATOMIC_FETCH_AND32 opal_thread_fetch_and_32 #define OPAL_THREAD_FETCH_OR32 opal_thread_fetch_or_32 #define OPAL_ATOMIC_FETCH_OR32 opal_thread_fetch_or_32 #define OPAL_THREAD_FETCH_XOR32 opal_thread_fetch_xor_32 #define OPAL_ATOMIC_FETCH_XOR32 opal_thread_fetch_xor_32 #define OPAL_THREAD_FETCH_ADD_SIZE_T opal_thread_fetch_add_size_t #define OPAL_ATOMIC_FETCH_ADD_SIZE_T opal_thread_fetch_add_size_t #define OPAL_THREAD_FETCH_SUB_SIZE_T opal_thread_fetch_sub_size_t #define OPAL_ATOMIC_FETCH_SUB_SIZE_T opal_thread_fetch_sub_size_t #define OPAL_THREAD_COMPARE_EXCHANGE_STRONG_32 opal_thread_compare_exchange_strong_32 #define OPAL_ATOMIC_COMPARE_EXCHANGE_STRONG_32 opal_thread_compare_exchange_strong_32 #define OPAL_THREAD_COMPARE_EXCHANGE_STRONG_PTR(x, y, z) \ opal_thread_compare_exchange_strong_ptr((opal_atomic_intptr_t *) x, (intptr_t *) y, \ (intptr_t) z) #define OPAL_ATOMIC_COMPARE_EXCHANGE_STRONG_PTR OPAL_THREAD_COMPARE_EXCHANGE_STRONG_PTR #define OPAL_THREAD_SWAP_32 opal_thread_swap_32 #define OPAL_ATOMIC_SWAP_32 opal_thread_swap_32 #define OPAL_THREAD_SWAP_PTR(x, y) opal_thread_swap_ptr((opal_atomic_intptr_t *) x, (intptr_t) y) #define OPAL_ATOMIC_SWAP_PTR OPAL_THREAD_SWAP_PTR OPAL_THREAD_DEFINE_ATOMIC_OP(int64_t, add, +, 64) OPAL_THREAD_DEFINE_ATOMIC_OP(int64_t, and, &, 64) OPAL_THREAD_DEFINE_ATOMIC_OP(int64_t, or, |, 64) OPAL_THREAD_DEFINE_ATOMIC_OP(int64_t, xor, ^, 64) OPAL_THREAD_DEFINE_ATOMIC_OP(int64_t, sub, -, 64) OPAL_THREAD_DEFINE_ATOMIC_COMPARE_EXCHANGE(int64_t, int64_t, 64) OPAL_THREAD_DEFINE_ATOMIC_SWAP(int64_t, int64_t, 64) # define OPAL_THREAD_ADD_FETCH64 opal_thread_add_fetch_64 # define OPAL_ATOMIC_ADD_FETCH64 opal_thread_add_fetch_64 # define OPAL_THREAD_AND_FETCH64 opal_thread_and_fetch_64 # define OPAL_ATOMIC_AND_FETCH64 opal_thread_and_fetch_64 # define OPAL_THREAD_OR_FETCH64 opal_thread_or_fetch_64 # define OPAL_ATOMIC_OR_FETCH64 opal_thread_or_fetch_64 # define OPAL_THREAD_XOR_FETCH64 opal_thread_xor_fetch_64 # define OPAL_ATOMIC_XOR_FETCH64 opal_thread_xor_fetch_64 # define OPAL_THREAD_FETCH_ADD64 opal_thread_fetch_add_64 # define OPAL_ATOMIC_FETCH_ADD64 opal_thread_fetch_add_64 # define OPAL_THREAD_FETCH_AND64 opal_thread_fetch_and_64 # define OPAL_ATOMIC_FETCH_AND64 opal_thread_fetch_and_64 # define OPAL_THREAD_FETCH_OR64 opal_thread_fetch_or_64 # define OPAL_ATOMIC_FETCH_OR64 opal_thread_fetch_or_64 # define OPAL_THREAD_FETCH_XOR64 opal_thread_fetch_xor_64 # define OPAL_ATOMIC_FETCH_XOR64 opal_thread_fetch_xor_64 # define OPAL_THREAD_COMPARE_EXCHANGE_STRONG_64 opal_thread_compare_exchange_strong_64 # define OPAL_ATOMIC_COMPARE_EXCHANGE_STRONG_64 opal_thread_compare_exchange_strong_64 # define OPAL_THREAD_SWAP_64 opal_thread_swap_64 # define OPAL_ATOMIC_SWAP_64 opal_thread_swap_64 /* thread local storage */ #if OPAL_C_HAVE__THREAD_LOCAL # define opal_thread_local _Thread_local # define OPAL_HAVE_THREAD_LOCAL 1 #elif OPAL_C_HAVE___THREAD /* OPAL_C_HAVE__THREAD_LOCAL */ # define opal_thread_local __thread # define OPAL_HAVE_THREAD_LOCAL 1 #endif /* OPAL_C_HAVE___THREAD */ #if !defined(OPAL_HAVE_THREAD_LOCAL) # define OPAL_HAVE_THREAD_LOCAL 0 #endif /* !defined(OPAL_HAVE_THREAD_LOCAL) */ #endif /* OPAL_MCA_THREADS_THREAD_USAGE_H */
92825750d176bbb4ad8ae2375b3299467efbe062
e8b04bef9aa1ac8e2c109dd315f133c8f4d28ae6
/src/controller/c/motor.c
0314713797baadb6e0a76194d7bfb7e49437225a
[ "Apache-2.0" ]
permissive
cyberbotics/webots
f075dacf4067e8dcebbfd89e8690df8525f6d745
8aba6eaae76989facf3442305c8089d3cc366bcf
refs/heads/master
2023-08-31T09:41:13.205940
2023-08-18T10:48:30
2023-08-18T10:48:30
156,228,018
2,495
1,525
Apache-2.0
2023-08-28T16:30:33
2018-11-05T14:09:10
C++
UTF-8
C
false
false
19,762
c
motor.c
/* * Copyright 1996-2023 Cyberbotics 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 * * 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. */ // *************************************************************************** // this file contains the API interface for the Motor device // *************************************************************************** #include <stdio.h> #include <stdlib.h> #include <string.h> #include <webots/motor.h> #include <webots/nodes.h> #include "messages.h" #include "robot_private.h" typedef struct { char requests[9]; int force_feedback_sampling_period; double position; // target position double velocity; double acceleration; double force; double available_force; double control_p; double control_i; double control_d; double force_feedback; double min_position; double max_position; double max_velocity; double max_force; double previous_velocity; double previous_acceleration; double previous_available_force; double previous_control_p; double previous_control_i; double previous_control_d; double multiplier; bool configured; WbJointType type; int requested_device_type; int associated_device_tag; int couplings_size; WbDeviceTag *couplings; } Motor; static Motor *motor_create() { Motor *motor = malloc(sizeof(Motor)); int i; for (i = 0; i < sizeof(motor->requests); ++i) motor->requests[i] = 0; motor->force_feedback_sampling_period = 0; motor->position = 0.0; motor->velocity = 0.0; motor->acceleration = 0.0; motor->force = 0.0; motor->available_force = 0.0; motor->control_p = 0.0; motor->control_i = 0.0; motor->control_d = 0.0; motor->force_feedback = NAN; motor->min_position = 0.0; motor->max_position = 0.0; motor->max_velocity = 10.0; motor->max_force = 10.0; motor->multiplier = 1.0; motor->type = WB_ROTATIONAL; // To support user changes during remote control motor->previous_velocity = 10.0; motor->previous_acceleration = -1.0; motor->previous_available_force = 10.0; motor->previous_control_p = 10.0; motor->previous_control_i = 0.0; motor->previous_control_d = 0.0; // to be sure available_force is not overwritten after first configure motor->configured = false; motor->requested_device_type = 0; motor->associated_device_tag = 0; motor->couplings_size = 0; motor->couplings = NULL; return motor; } // Static functions static Motor *motor_get_struct(WbDeviceTag t) { WbDevice *d = robot_get_device_with_node(t, WB_NODE_ROTATIONAL_MOTOR, false); if (d == NULL) d = robot_get_device_with_node(t, WB_NODE_LINEAR_MOTOR, true); return d ? d->pdata : NULL; } static void motor_write_request(WbDevice *d, WbRequest *r) { Motor *m = (Motor *)d->pdata; int i; for (i = 0; i < sizeof(m->requests); ++i) { if (m->requests[i] == 0) continue; request_write_uint16(r, i); switch (i) { case C_MOTOR_SET_POSITION: request_write_double(r, m->position); break; case C_MOTOR_SET_VELOCITY: request_write_double(r, m->velocity); break; case C_MOTOR_SET_ACCELERATION: request_write_double(r, m->acceleration); break; case C_MOTOR_SET_FORCE: request_write_double(r, m->force); break; case C_MOTOR_SET_AVAILABLE_FORCE: request_write_double(r, m->available_force); break; case C_MOTOR_SET_CONTROL_PID: request_write_double(r, m->control_p); request_write_double(r, m->control_i); request_write_double(r, m->control_d); break; case C_MOTOR_FEEDBACK: request_write_uint16(r, m->force_feedback_sampling_period); break; case C_MOTOR_GET_ASSOCIATED_DEVICE: request_write_uint16(r, m->requested_device_type); break; default: break; } m->requests[i] = 0; } } static void motor_read_answer(WbDevice *d, WbRequest *r) { Motor *m = (Motor *)d->pdata; switch (request_read_uchar(r)) { case C_CONFIGURE: m->type = request_read_int32(r); m->min_position = request_read_double(r); m->max_position = request_read_double(r); m->max_velocity = request_read_double(r); if (!m->configured) { m->previous_velocity = m->max_velocity; m->velocity = m->max_velocity; } m->previous_acceleration = request_read_double(r); m->acceleration = m->previous_acceleration; m->max_force = request_read_double(r); if (!m->configured) { m->previous_available_force = m->max_force; m->available_force = m->max_force; } else { if (m->available_force == m->previous_available_force) { m->previous_available_force = m->max_force; m->available_force = m->max_force; } else { if (m->previous_available_force > m->max_force) m->previous_available_force = m->max_force; if (m->available_force > m->max_force) m->available_force = m->max_force; } } m->previous_control_p = request_read_double(r); m->previous_control_i = request_read_double(r); m->previous_control_d = request_read_double(r); m->control_p = m->previous_control_p; m->control_i = m->previous_control_i; m->control_d = m->previous_control_d; m->position = request_read_double(r); m->velocity = request_read_double(r); m->multiplier = request_read_double(r); m->couplings_size = request_read_int32(r); if (m->couplings_size > 0) { m->couplings = (WbDeviceTag *)malloc(sizeof(WbDeviceTag) * m->couplings_size); for (int i = 0; i < m->couplings_size; i++) m->couplings[i] = request_read_uint16(r); } m->configured = true; break; case C_MOTOR_FEEDBACK: m->force_feedback = request_read_double(r); break; case C_MOTOR_GET_ASSOCIATED_DEVICE: m->associated_device_tag = request_read_uint16(r); break; default: ROBOT_ASSERT(0); // should not be reached break; } } static void motor_cleanup(WbDevice *d) { Motor *m = (Motor *)d->pdata; free(m->couplings); free(m); } static void motor_toggle_remote(WbDevice *d, WbRequest *r) { Motor *m = (Motor *)d->pdata; m->requests[C_MOTOR_FEEDBACK] = 1; // setup motor if changed by user if (m->velocity != m->previous_velocity) m->requests[C_MOTOR_SET_VELOCITY] = 1; if (m->acceleration != m->previous_acceleration) m->requests[C_MOTOR_SET_ACCELERATION] = 1; if (m->available_force != m->previous_available_force) m->requests[C_MOTOR_SET_AVAILABLE_FORCE] = 1; if (m->control_p != m->previous_control_p || m->control_i != m->previous_control_i || m->control_d != m->previous_control_d) m->requests[C_MOTOR_SET_CONTROL_PID] = 1; } // Exported functions and variables const int wb_ROTATIONAL = WB_ROTATIONAL; const int wb_LINEAR = WB_LINEAR; void wb_motor_init(WbDevice *d) { d->read_answer = motor_read_answer; d->write_request = motor_write_request; d->cleanup = motor_cleanup; d->toggle_remote = motor_toggle_remote; d->pdata = motor_create(); } // Public functions (available from the user API) void wb_motor_set_position_no_mutex(WbDeviceTag tag, double pos) { Motor *m = motor_get_struct(tag); if (m) { m->requests[C_MOTOR_SET_POSITION] = 1; m->position = pos; for (int i = 0; i < m->couplings_size; ++i) { Motor *s = motor_get_struct(m->couplings[i]); if (s) s->position = isinf(pos) ? pos : pos * s->multiplier; else fprintf(stderr, "Error: %s(): invalid sibling in coupling.\n", __FUNCTION__); } } else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); } void wb_motor_set_position(WbDeviceTag tag, double position) { if (isnan(position)) { fprintf(stderr, "Error: %s() called with an invalid 'position' argument (NaN).\n", __FUNCTION__); return; } Motor *m = motor_get_struct(tag); if (!m) fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); else { robot_mutex_lock(); wb_motor_set_position_no_mutex(tag, position); robot_mutex_unlock(); } } void wb_motor_set_velocity(WbDeviceTag tag, double velocity) { if (isnan(velocity)) { fprintf(stderr, "Error: %s() called with an invalid 'velocity' argument.(NaN)\n", __FUNCTION__); return; } robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) { if (velocity < 0.0) { if (!isinf(m->position)) { fprintf(stderr, "Error: %s() called with negative 'velocity' argument in position control mode (%g).\n", __FUNCTION__, m->position); robot_mutex_unlock(); return; } } m->requests[C_MOTOR_SET_VELOCITY] = 1; m->velocity = velocity; for (int i = 0; i < m->couplings_size; ++i) { Motor *s = motor_get_struct(m->couplings[i]); if (s) s->velocity = velocity * s->multiplier; else fprintf(stderr, "Error: %s(): invalid sibling in coupling.\n", __FUNCTION__); } } else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); } double wb_motor_get_velocity(WbDeviceTag tag) { double vel = NAN; robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) vel = m->velocity; else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); return vel; } double wb_motor_get_max_velocity(WbDeviceTag tag) { double vel = NAN; robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) vel = m->max_velocity; else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); return vel; } void wb_motor_set_acceleration(WbDeviceTag tag, double acceleration) { if (acceleration < 0.0 && acceleration != -1) { fprintf(stderr, "Error: %s() called with negative 'acceleration' argument.\n", __FUNCTION__); return; } if (isnan(acceleration)) { fprintf(stderr, "Error: %s() called with an invalid 'acceleration' argument (NaN).\n", __FUNCTION__); return; } robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) { m->requests[C_MOTOR_SET_ACCELERATION] = 1; m->acceleration = acceleration; } else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); } double wb_motor_get_acceleration(WbDeviceTag tag) { double acc = NAN; robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) acc = m->acceleration; else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); return acc; } void wb_motor_set_force(WbDeviceTag tag, double force) { if (isnan(force)) { fprintf(stderr, "Error: %s() called with an invalid 'force' argument (NaN).\n", __FUNCTION__); return; } robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) { m->requests[C_MOTOR_SET_FORCE] = 1; m->force = force; for (int i = 0; i < m->couplings_size; ++i) { Motor *s = motor_get_struct(m->couplings[i]); if (s) s->force = force * s->multiplier; else fprintf(stderr, "Error: %s(): invalid sibling in coupling.\n", __FUNCTION__); } } else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); } void wb_motor_set_available_force(WbDeviceTag tag, double force) { if (isnan(force)) { fprintf(stderr, "Error: %s() called with an invalid 'force' argument (NaN).\n", __FUNCTION__); return; } if (force < 0.0) { fprintf(stderr, "Error: %s() called with negative 'force' argument.\n", __FUNCTION__); return; } robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) { m->requests[C_MOTOR_SET_AVAILABLE_FORCE] = 1; m->available_force = force; } else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); } double wb_motor_get_available_force(WbDeviceTag tag) { double force = NAN; robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) force = m->available_force; else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); return force; } double wb_motor_get_max_force(WbDeviceTag tag) { double force = NAN; robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) force = m->max_force; else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); return force; } void wb_motor_set_control_pid(WbDeviceTag tag, double p, double i, double d) { if (p <= 0.0) { fprintf(stderr, "Error: %s() called with negative or zero 'p' argument.\n", __FUNCTION__); return; } if (i < 0.0) { fprintf(stderr, "Error: %s() called with negative 'i' argument.\n", __FUNCTION__); return; } if (d < 0.0) { fprintf(stderr, "Error: %s() called with negative 'd' argument.\n", __FUNCTION__); return; } robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) { m->requests[C_MOTOR_SET_CONTROL_PID] = 1; m->control_p = p; m->control_i = i; m->control_d = d; } else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); } void wb_motor_enable_force_feedback(WbDeviceTag tag, int sampling_period) { if (sampling_period < 0) { fprintf(stderr, "Error: %s() called with negative sampling period.\n", __FUNCTION__); return; } robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) { m->requests[C_MOTOR_FEEDBACK] = 1; m->force_feedback_sampling_period = sampling_period; } else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); } void wb_motor_disable_force_feedback(WbDeviceTag tag) { Motor *m = motor_get_struct(tag); if (m) wb_motor_enable_force_feedback(tag, 0); else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); } double wb_motor_get_force_feedback(WbDeviceTag tag) { double result = NAN; robot_mutex_lock(); const Motor *m = motor_get_struct(tag); if (m) result = m->force_feedback; else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); return result; } int wb_motor_get_force_feedback_sampling_period(WbDeviceTag tag) { int sampling_period = 0; robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) sampling_period = m->force_feedback_sampling_period; else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); return sampling_period; } double wb_motor_get_min_position(WbDeviceTag tag) { double pos = NAN; robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) pos = m->min_position; else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); return pos; } double wb_motor_get_max_position(WbDeviceTag tag) { double pos = NAN; robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) pos = m->max_position; else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); return pos; } double wb_motor_get_target_position(WbDeviceTag tag) { double pos = NAN; robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) pos = m->position; else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); return pos; } WbJointType wb_motor_get_type(WbDeviceTag tag) { WbJointType type = WB_ROTATIONAL; robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) type = m->type; else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); robot_mutex_unlock(); return type; } void wbr_motor_set_force_feedback(WbDeviceTag t, double value) { Motor *m = motor_get_struct(t); if (m) m->force_feedback = value; else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); } // Aliases void wb_motor_set_available_torque(WbDeviceTag tag, double torque) { Motor *m = motor_get_struct(tag); if (m) wb_motor_set_available_force(tag, torque); else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); } double wb_motor_get_available_torque(WbDeviceTag tag) { Motor *m = motor_get_struct(tag); if (m) return wb_motor_get_available_force(tag); fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); return NAN; } double wb_motor_get_multiplier(WbDeviceTag tag) { double multiplier; robot_mutex_lock(); Motor *m = motor_get_struct(tag); if (m) multiplier = m->multiplier; else { fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); multiplier = NAN; } robot_mutex_unlock(); return multiplier; } double wb_motor_get_max_torque(WbDeviceTag tag) { Motor *m = motor_get_struct(tag); if (m) return wb_motor_get_max_force(tag); fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); return NAN; } void wb_motor_set_torque(WbDeviceTag tag, double torque) { Motor *m = motor_get_struct(tag); if (m) wb_motor_set_force(tag, torque); else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); } void wb_motor_enable_torque_feedback(WbDeviceTag tag, int sampling_period) { Motor *m = motor_get_struct(tag); if (m) wb_motor_enable_force_feedback(tag, sampling_period); else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); } void wb_motor_disable_torque_feedback(WbDeviceTag tag) { Motor *m = motor_get_struct(tag); if (m) wb_motor_disable_force_feedback(tag); else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); } int wb_motor_get_torque_feedback_sampling_period(WbDeviceTag tag) { Motor *m = motor_get_struct(tag); if (m) return wb_motor_get_force_feedback_sampling_period(tag); fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); return 0; } double wb_motor_get_torque_feedback(WbDeviceTag tag) { Motor *m = motor_get_struct(tag); if (m) return wb_motor_get_force_feedback(tag); fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); return NAN; } void wbr_motor_set_torque_feedback(WbDeviceTag t, double value) { Motor *m = motor_get_struct(t); if (m) wbr_motor_set_force_feedback(t, value); else fprintf(stderr, "Error: %s(): invalid device tag.\n", __FUNCTION__); } static WbDeviceTag motor_get_associated_device(WbDeviceTag t, int device_type, const char *function_name) { Motor *motor = motor_get_struct(t); if (!motor) { fprintf(stderr, "Error: %s(): invalid device tag.\n", function_name); return 0; } robot_mutex_lock(); motor->requests[C_MOTOR_GET_ASSOCIATED_DEVICE] = 1; motor->requested_device_type = device_type; wb_robot_flush_unlocked(function_name); WbDeviceTag tag = motor->associated_device_tag; robot_mutex_unlock(); return tag; } WbDeviceTag wb_motor_get_position_sensor(WbDeviceTag tag) { return motor_get_associated_device(tag, WB_NODE_POSITION_SENSOR, __FUNCTION__); } WbDeviceTag wb_motor_get_brake(WbDeviceTag tag) { return motor_get_associated_device(tag, WB_NODE_BRAKE, __FUNCTION__); }
cc6ae0ea1b9f60428ffaae8072a0120b25bae0b5
a91796ab826878e54d91c32249f45bb919e0c149
/3rdparty/openjpeg/openjp2/jp2.c
17572195e391028d81a57968a75990abbc463e41
[ "Apache-2.0", "IJG", "Zlib", "BSD-3-Clause", "Libpng", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
opencv/opencv
8f1c8b5a16980f78de7c6e73a4340d302d1211cc
a308dfca9856574d37abe7628b965e29861fb105
refs/heads/4.x
2023-09-01T12:37:49.132527
2023-08-30T06:53:59
2023-08-30T06:53:59
5,108,051
68,495
62,910
Apache-2.0
2023-09-14T17:37:48
2012-07-19T09:40:17
C++
UTF-8
C
false
false
117,418
c
jp2.c
/* * The copyright in this software is being made available under the 2-clauses * 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) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2010-2011, Kaori Hagihara * Copyright (c) 2008, 2011-2012, Centre National d'Etudes Spatiales (CNES), FR * Copyright (c) 2012, CS Systemes d'Information, France * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" /** @defgroup JP2 JP2 - JPEG-2000 file format reader/writer */ /*@{*/ #define OPJ_BOX_SIZE 1024 #define OPJ_UNUSED(x) (void)x /** @name Local static functions */ /*@{*/ /*static void jp2_write_url(opj_cio_t *cio, char *Idx_file);*/ /** * Reads a IHDR box - Image Header box * * @param p_image_header_data pointer to actual data (already read from file) * @param jp2 the jpeg2000 file codec. * @param p_image_header_size the size of the image header * @param p_manager the user event manager. * * @return true if the image header is valid, false else. */ static OPJ_BOOL opj_jp2_read_ihdr(opj_jp2_t *jp2, OPJ_BYTE *p_image_header_data, OPJ_UINT32 p_image_header_size, opj_event_mgr_t * p_manager); /** * Writes the Image Header box - Image Header box. * * @param jp2 jpeg2000 file codec. * @param p_nb_bytes_written pointer to store the nb of bytes written by the function. * * @return the data being copied. */ static OPJ_BYTE * opj_jp2_write_ihdr(opj_jp2_t *jp2, OPJ_UINT32 * p_nb_bytes_written); /** * Writes the Bit per Component box. * * @param jp2 jpeg2000 file codec. * @param p_nb_bytes_written pointer to store the nb of bytes written by the function. * * @return the data being copied. */ static OPJ_BYTE * opj_jp2_write_bpcc(opj_jp2_t *jp2, OPJ_UINT32 * p_nb_bytes_written); /** * Reads a Bit per Component box. * * @param p_bpc_header_data pointer to actual data (already read from file) * @param jp2 the jpeg2000 file codec. * @param p_bpc_header_size the size of the bpc header * @param p_manager the user event manager. * * @return true if the bpc header is valid, false else. */ static OPJ_BOOL opj_jp2_read_bpcc(opj_jp2_t *jp2, OPJ_BYTE * p_bpc_header_data, OPJ_UINT32 p_bpc_header_size, opj_event_mgr_t * p_manager); static OPJ_BOOL opj_jp2_read_cdef(opj_jp2_t * jp2, OPJ_BYTE * p_cdef_header_data, OPJ_UINT32 p_cdef_header_size, opj_event_mgr_t * p_manager); static void opj_jp2_apply_cdef(opj_image_t *image, opj_jp2_color_t *color, opj_event_mgr_t *); /** * Writes the Channel Definition box. * * @param jp2 jpeg2000 file codec. * @param p_nb_bytes_written pointer to store the nb of bytes written by the function. * * @return the data being copied. */ static OPJ_BYTE * opj_jp2_write_cdef(opj_jp2_t *jp2, OPJ_UINT32 * p_nb_bytes_written); /** * Writes the Colour Specification box. * * @param jp2 jpeg2000 file codec. * @param p_nb_bytes_written pointer to store the nb of bytes written by the function. * * @return the data being copied. */ static OPJ_BYTE * opj_jp2_write_colr(opj_jp2_t *jp2, OPJ_UINT32 * p_nb_bytes_written); /** * Writes a FTYP box - File type box * * @param cio the stream to write data to. * @param jp2 the jpeg2000 file codec. * @param p_manager the user event manager. * * @return true if writing was successful. */ static OPJ_BOOL opj_jp2_write_ftyp(opj_jp2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager); /** * Reads a a FTYP box - File type box * * @param p_header_data the data contained in the FTYP box. * @param jp2 the jpeg2000 file codec. * @param p_header_size the size of the data contained in the FTYP box. * @param p_manager the user event manager. * * @return true if the FTYP box is valid. */ static OPJ_BOOL opj_jp2_read_ftyp(opj_jp2_t *jp2, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); static OPJ_BOOL opj_jp2_skip_jp2c(opj_jp2_t *jp2, opj_stream_private_t *stream, opj_event_mgr_t * p_manager); /** * Reads the Jpeg2000 file Header box - JP2 Header box (warning, this is a super box). * * @param p_header_data the data contained in the file header box. * @param jp2 the jpeg2000 file codec. * @param p_header_size the size of the data contained in the file header box. * @param p_manager the user event manager. * * @return true if the JP2 Header box was successfully recognized. */ static OPJ_BOOL opj_jp2_read_jp2h(opj_jp2_t *jp2, OPJ_BYTE *p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the Jpeg2000 file Header box - JP2 Header box (warning, this is a super box). * * @param jp2 the jpeg2000 file codec. * @param stream the stream to write data to. * @param p_manager user event manager. * * @return true if writing was successful. */ static OPJ_BOOL opj_jp2_write_jp2h(opj_jp2_t *jp2, opj_stream_private_t *stream, opj_event_mgr_t * p_manager); /** * Writes the Jpeg2000 codestream Header box - JP2C Header box. This function must be called AFTER the coding has been done. * * @param cio the stream to write data to. * @param jp2 the jpeg2000 file codec. * @param p_manager user event manager. * * @return true if writing was successful. */ static OPJ_BOOL opj_jp2_write_jp2c(opj_jp2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager); #ifdef USE_JPIP /** * Write index Finder box * @param cio the stream to write to. * @param jp2 the jpeg2000 file codec. * @param p_manager user event manager. */ static OPJ_BOOL opj_jpip_write_iptr(opj_jp2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager); /** * Write index Finder box * @param cio the stream to write to. * @param jp2 the jpeg2000 file codec. * @param p_manager user event manager. */ static OPJ_BOOL opj_jpip_write_cidx(opj_jp2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager); /** * Write file Index (superbox) * @param cio the stream to write to. * @param jp2 the jpeg2000 file codec. * @param p_manager user event manager. */ static OPJ_BOOL opj_jpip_write_fidx(opj_jp2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager); #endif /* USE_JPIP */ /** * Reads a jpeg2000 file signature box. * * @param p_header_data the data contained in the signature box. * @param jp2 the jpeg2000 file codec. * @param p_header_size the size of the data contained in the signature box. * @param p_manager the user event manager. * * @return true if the file signature box is valid. */ static OPJ_BOOL opj_jp2_read_jp(opj_jp2_t *jp2, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes a jpeg2000 file signature box. * * @param cio the stream to write data to. * @param jp2 the jpeg2000 file codec. * @param p_manager the user event manager. * * @return true if writing was successful. */ static OPJ_BOOL opj_jp2_write_jp(opj_jp2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager); /** Apply collected palette data @param image Image. @param color Collector for profile, cdef and pclr data. @param p_manager the user event manager. @return true in case of success */ static OPJ_BOOL opj_jp2_apply_pclr(opj_image_t *image, opj_jp2_color_t *color, opj_event_mgr_t * p_manager); static void opj_jp2_free_pclr(opj_jp2_color_t *color); /** * Collect palette data * * @param jp2 JP2 handle * @param p_pclr_header_data FIXME DOC * @param p_pclr_header_size FIXME DOC * @param p_manager * * @return Returns true if successful, returns false otherwise */ static OPJ_BOOL opj_jp2_read_pclr(opj_jp2_t *jp2, OPJ_BYTE * p_pclr_header_data, OPJ_UINT32 p_pclr_header_size, opj_event_mgr_t * p_manager); /** * Collect component mapping data * * @param jp2 JP2 handle * @param p_cmap_header_data FIXME DOC * @param p_cmap_header_size FIXME DOC * @param p_manager FIXME DOC * * @return Returns true if successful, returns false otherwise */ static OPJ_BOOL opj_jp2_read_cmap(opj_jp2_t * jp2, OPJ_BYTE * p_cmap_header_data, OPJ_UINT32 p_cmap_header_size, opj_event_mgr_t * p_manager); /** * Reads the Color Specification box. * * @param p_colr_header_data pointer to actual data (already read from file) * @param jp2 the jpeg2000 file codec. * @param p_colr_header_size the size of the color header * @param p_manager the user event manager. * * @return true if the bpc header is valid, false else. */ static OPJ_BOOL opj_jp2_read_colr(opj_jp2_t *jp2, OPJ_BYTE * p_colr_header_data, OPJ_UINT32 p_colr_header_size, opj_event_mgr_t * p_manager); /*@}*/ /*@}*/ /** * Sets up the procedures to do on writing header after the codestream. * Developers wanting to extend the library can add their own writing procedures. */ static OPJ_BOOL opj_jp2_setup_end_header_writing(opj_jp2_t *jp2, opj_event_mgr_t * p_manager); /** * Sets up the procedures to do on reading header after the codestream. * Developers wanting to extend the library can add their own writing procedures. */ static OPJ_BOOL opj_jp2_setup_end_header_reading(opj_jp2_t *jp2, opj_event_mgr_t * p_manager); /** * Reads a jpeg2000 file header structure. * * @param jp2 the jpeg2000 file header structure. * @param stream the stream to read data from. * @param p_manager the user event manager. * * @return true if the box is valid. */ static OPJ_BOOL opj_jp2_read_header_procedure(opj_jp2_t *jp2, opj_stream_private_t *stream, opj_event_mgr_t * p_manager); /** * Executes the given procedures on the given codec. * * @param p_procedure_list the list of procedures to execute * @param jp2 the jpeg2000 file codec to execute the procedures on. * @param stream the stream to execute the procedures on. * @param p_manager the user manager. * * @return true if all the procedures were successfully executed. */ static OPJ_BOOL opj_jp2_exec(opj_jp2_t * jp2, opj_procedure_list_t * p_procedure_list, opj_stream_private_t *stream, opj_event_mgr_t * p_manager); /** * Reads a box header. The box is the way data is packed inside a jpeg2000 file structure. * * @param cio the input stream to read data from. * @param box the box structure to fill. * @param p_number_bytes_read pointer to an int that will store the number of bytes read from the stream (shoul usually be 2). * @param p_manager user event manager. * * @return true if the box is recognized, false otherwise */ static OPJ_BOOL opj_jp2_read_boxhdr(opj_jp2_box_t *box, OPJ_UINT32 * p_number_bytes_read, opj_stream_private_t *cio, opj_event_mgr_t * p_manager); /** * Sets up the validation ,i.e. adds the procedures to launch to make sure the codec parameters * are valid. Developers wanting to extend the library can add their own validation procedures. */ static OPJ_BOOL opj_jp2_setup_encoding_validation(opj_jp2_t *jp2, opj_event_mgr_t * p_manager); /** * Sets up the procedures to do on writing header. Developers wanting to extend the library can add their own writing procedures. */ static OPJ_BOOL opj_jp2_setup_header_writing(opj_jp2_t *jp2, opj_event_mgr_t * p_manager); static OPJ_BOOL opj_jp2_default_validation(opj_jp2_t * jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager); /** * Finds the image execution function related to the given box id. * * @param p_id the id of the handler to fetch. * * @return the given handler or NULL if it could not be found. */ static const opj_jp2_header_handler_t * opj_jp2_img_find_handler( OPJ_UINT32 p_id); /** * Finds the execution function related to the given box id. * * @param p_id the id of the handler to fetch. * * @return the given handler or NULL if it could not be found. */ static const opj_jp2_header_handler_t * opj_jp2_find_handler(OPJ_UINT32 p_id); static const opj_jp2_header_handler_t jp2_header [] = { {JP2_JP, opj_jp2_read_jp}, {JP2_FTYP, opj_jp2_read_ftyp}, {JP2_JP2H, opj_jp2_read_jp2h} }; static const opj_jp2_header_handler_t jp2_img_header [] = { {JP2_IHDR, opj_jp2_read_ihdr}, {JP2_COLR, opj_jp2_read_colr}, {JP2_BPCC, opj_jp2_read_bpcc}, {JP2_PCLR, opj_jp2_read_pclr}, {JP2_CMAP, opj_jp2_read_cmap}, {JP2_CDEF, opj_jp2_read_cdef} }; /** * Reads a box header. The box is the way data is packed inside a jpeg2000 file structure. Data is read from a character string * * @param box the box structure to fill. * @param p_data the character string to read data from. * @param p_number_bytes_read pointer to an int that will store the number of bytes read from the stream (shoul usually be 2). * @param p_box_max_size the maximum number of bytes in the box. * @param p_manager FIXME DOC * * @return true if the box is recognized, false otherwise */ static OPJ_BOOL opj_jp2_read_boxhdr_char(opj_jp2_box_t *box, OPJ_BYTE * p_data, OPJ_UINT32 * p_number_bytes_read, OPJ_UINT32 p_box_max_size, opj_event_mgr_t * p_manager); /** * Sets up the validation ,i.e. adds the procedures to launch to make sure the codec parameters * are valid. Developers wanting to extend the library can add their own validation procedures. */ static OPJ_BOOL opj_jp2_setup_decoding_validation(opj_jp2_t *jp2, opj_event_mgr_t * p_manager); /** * Sets up the procedures to do on reading header. * Developers wanting to extend the library can add their own writing procedures. */ static OPJ_BOOL opj_jp2_setup_header_reading(opj_jp2_t *jp2, opj_event_mgr_t * p_manager); /* ----------------------------------------------------------------------- */ static OPJ_BOOL opj_jp2_read_boxhdr(opj_jp2_box_t *box, OPJ_UINT32 * p_number_bytes_read, opj_stream_private_t *cio, opj_event_mgr_t * p_manager) { /* read header from file */ OPJ_BYTE l_data_header [8]; /* preconditions */ assert(cio != 00); assert(box != 00); assert(p_number_bytes_read != 00); assert(p_manager != 00); *p_number_bytes_read = (OPJ_UINT32)opj_stream_read_data(cio, l_data_header, 8, p_manager); if (*p_number_bytes_read != 8) { return OPJ_FALSE; } /* process read data */ opj_read_bytes(l_data_header, &(box->length), 4); opj_read_bytes(l_data_header + 4, &(box->type), 4); if (box->length == 0) { /* last box */ const OPJ_OFF_T bleft = opj_stream_get_number_byte_left(cio); if (bleft > (OPJ_OFF_T)(0xFFFFFFFFU - 8U)) { opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n"); return OPJ_FALSE; } box->length = (OPJ_UINT32)bleft + 8U; assert((OPJ_OFF_T)box->length == bleft + 8); return OPJ_TRUE; } /* do we have a "special very large box ?" */ /* read then the XLBox */ if (box->length == 1) { OPJ_UINT32 l_xl_part_size; OPJ_UINT32 l_nb_bytes_read = (OPJ_UINT32)opj_stream_read_data(cio, l_data_header, 8, p_manager); if (l_nb_bytes_read != 8) { if (l_nb_bytes_read > 0) { *p_number_bytes_read += l_nb_bytes_read; } return OPJ_FALSE; } *p_number_bytes_read = 16; opj_read_bytes(l_data_header, &l_xl_part_size, 4); if (l_xl_part_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n"); return OPJ_FALSE; } opj_read_bytes(l_data_header + 4, &(box->length), 4); } return OPJ_TRUE; } #if 0 static void jp2_write_url(opj_cio_t *cio, char *Idx_file) { OPJ_UINT32 i; opj_jp2_box_t box; box.init_pos = cio_tell(cio); cio_skip(cio, 4); cio_write(cio, JP2_URL, 4); /* DBTL */ cio_write(cio, 0, 1); /* VERS */ cio_write(cio, 0, 3); /* FLAG */ if (Idx_file) { for (i = 0; i < strlen(Idx_file); i++) { cio_write(cio, Idx_file[i], 1); } } box.length = cio_tell(cio) - box.init_pos; cio_seek(cio, box.init_pos); cio_write(cio, box.length, 4); /* L */ cio_seek(cio, box.init_pos + box.length); } #endif static OPJ_BOOL opj_jp2_read_ihdr(opj_jp2_t *jp2, OPJ_BYTE *p_image_header_data, OPJ_UINT32 p_image_header_size, opj_event_mgr_t * p_manager) { /* preconditions */ assert(p_image_header_data != 00); assert(jp2 != 00); assert(p_manager != 00); if (jp2->comps != NULL) { opj_event_msg(p_manager, EVT_WARNING, "Ignoring ihdr box. First ihdr box already read\n"); return OPJ_TRUE; } if (p_image_header_size != 14) { opj_event_msg(p_manager, EVT_ERROR, "Bad image header box (bad size)\n"); return OPJ_FALSE; } opj_read_bytes(p_image_header_data, &(jp2->h), 4); /* HEIGHT */ p_image_header_data += 4; opj_read_bytes(p_image_header_data, &(jp2->w), 4); /* WIDTH */ p_image_header_data += 4; opj_read_bytes(p_image_header_data, &(jp2->numcomps), 2); /* NC */ p_image_header_data += 2; if (jp2->h < 1 || jp2->w < 1 || jp2->numcomps < 1) { opj_event_msg(p_manager, EVT_ERROR, "Wrong values for: w(%d) h(%d) numcomps(%d) (ihdr)\n", jp2->w, jp2->h, jp2->numcomps); return OPJ_FALSE; } if ((jp2->numcomps - 1U) >= 16384U) { /* unsigned underflow is well defined: 1U <= jp2->numcomps <= 16384U */ opj_event_msg(p_manager, EVT_ERROR, "Invalid number of components (ihdr)\n"); return OPJ_FALSE; } /* allocate memory for components */ jp2->comps = (opj_jp2_comps_t*) opj_calloc(jp2->numcomps, sizeof(opj_jp2_comps_t)); if (jp2->comps == 0) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle image header (ihdr)\n"); return OPJ_FALSE; } opj_read_bytes(p_image_header_data, &(jp2->bpc), 1); /* BPC */ ++ p_image_header_data; opj_read_bytes(p_image_header_data, &(jp2->C), 1); /* C */ ++ p_image_header_data; /* Should be equal to 7 cf. chapter about image header box of the norm */ if (jp2->C != 7) { opj_event_msg(p_manager, EVT_INFO, "JP2 IHDR box: compression type indicate that the file is not a conforming JP2 file (%d) \n", jp2->C); } opj_read_bytes(p_image_header_data, &(jp2->UnkC), 1); /* UnkC */ ++ p_image_header_data; opj_read_bytes(p_image_header_data, &(jp2->IPR), 1); /* IPR */ ++ p_image_header_data; jp2->j2k->m_cp.allow_different_bit_depth_sign = (jp2->bpc == 255); jp2->j2k->ihdr_w = jp2->w; jp2->j2k->ihdr_h = jp2->h; jp2->has_ihdr = 1; return OPJ_TRUE; } static OPJ_BYTE * opj_jp2_write_ihdr(opj_jp2_t *jp2, OPJ_UINT32 * p_nb_bytes_written ) { OPJ_BYTE * l_ihdr_data, * l_current_ihdr_ptr; /* preconditions */ assert(jp2 != 00); assert(p_nb_bytes_written != 00); /* default image header is 22 bytes wide */ l_ihdr_data = (OPJ_BYTE *) opj_calloc(1, 22); if (l_ihdr_data == 00) { return 00; } l_current_ihdr_ptr = l_ihdr_data; opj_write_bytes(l_current_ihdr_ptr, 22, 4); /* write box size */ l_current_ihdr_ptr += 4; opj_write_bytes(l_current_ihdr_ptr, JP2_IHDR, 4); /* IHDR */ l_current_ihdr_ptr += 4; opj_write_bytes(l_current_ihdr_ptr, jp2->h, 4); /* HEIGHT */ l_current_ihdr_ptr += 4; opj_write_bytes(l_current_ihdr_ptr, jp2->w, 4); /* WIDTH */ l_current_ihdr_ptr += 4; opj_write_bytes(l_current_ihdr_ptr, jp2->numcomps, 2); /* NC */ l_current_ihdr_ptr += 2; opj_write_bytes(l_current_ihdr_ptr, jp2->bpc, 1); /* BPC */ ++l_current_ihdr_ptr; opj_write_bytes(l_current_ihdr_ptr, jp2->C, 1); /* C : Always 7 */ ++l_current_ihdr_ptr; opj_write_bytes(l_current_ihdr_ptr, jp2->UnkC, 1); /* UnkC, colorspace unknown */ ++l_current_ihdr_ptr; opj_write_bytes(l_current_ihdr_ptr, jp2->IPR, 1); /* IPR, no intellectual property */ ++l_current_ihdr_ptr; *p_nb_bytes_written = 22; return l_ihdr_data; } static OPJ_BYTE * opj_jp2_write_bpcc(opj_jp2_t *jp2, OPJ_UINT32 * p_nb_bytes_written ) { OPJ_UINT32 i; /* room for 8 bytes for box and 1 byte for each component */ OPJ_UINT32 l_bpcc_size; OPJ_BYTE * l_bpcc_data, * l_current_bpcc_ptr; /* preconditions */ assert(jp2 != 00); assert(p_nb_bytes_written != 00); l_bpcc_size = 8 + jp2->numcomps; l_bpcc_data = (OPJ_BYTE *) opj_calloc(1, l_bpcc_size); if (l_bpcc_data == 00) { return 00; } l_current_bpcc_ptr = l_bpcc_data; opj_write_bytes(l_current_bpcc_ptr, l_bpcc_size, 4); /* write box size */ l_current_bpcc_ptr += 4; opj_write_bytes(l_current_bpcc_ptr, JP2_BPCC, 4); /* BPCC */ l_current_bpcc_ptr += 4; for (i = 0; i < jp2->numcomps; ++i) { opj_write_bytes(l_current_bpcc_ptr, jp2->comps[i].bpcc, 1); /* write each component information */ ++l_current_bpcc_ptr; } *p_nb_bytes_written = l_bpcc_size; return l_bpcc_data; } static OPJ_BOOL opj_jp2_read_bpcc(opj_jp2_t *jp2, OPJ_BYTE * p_bpc_header_data, OPJ_UINT32 p_bpc_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 i; /* preconditions */ assert(p_bpc_header_data != 00); assert(jp2 != 00); assert(p_manager != 00); if (jp2->bpc != 255) { opj_event_msg(p_manager, EVT_WARNING, "A BPCC header box is available although BPC given by the IHDR box (%d) indicate components bit depth is constant\n", jp2->bpc); } /* and length is relevant */ if (p_bpc_header_size != jp2->numcomps) { opj_event_msg(p_manager, EVT_ERROR, "Bad BPCC header box (bad size)\n"); return OPJ_FALSE; } /* read info for each component */ for (i = 0; i < jp2->numcomps; ++i) { opj_read_bytes(p_bpc_header_data, &jp2->comps[i].bpcc, 1); /* read each BPCC component */ ++p_bpc_header_data; } return OPJ_TRUE; } static OPJ_BYTE * opj_jp2_write_cdef(opj_jp2_t *jp2, OPJ_UINT32 * p_nb_bytes_written) { /* room for 8 bytes for box, 2 for n */ OPJ_UINT32 l_cdef_size = 10; OPJ_BYTE * l_cdef_data, * l_current_cdef_ptr; OPJ_UINT32 l_value; OPJ_UINT16 i; /* preconditions */ assert(jp2 != 00); assert(p_nb_bytes_written != 00); assert(jp2->color.jp2_cdef != 00); assert(jp2->color.jp2_cdef->info != 00); assert(jp2->color.jp2_cdef->n > 0U); l_cdef_size += 6U * jp2->color.jp2_cdef->n; l_cdef_data = (OPJ_BYTE *) opj_malloc(l_cdef_size); if (l_cdef_data == 00) { return 00; } l_current_cdef_ptr = l_cdef_data; opj_write_bytes(l_current_cdef_ptr, l_cdef_size, 4); /* write box size */ l_current_cdef_ptr += 4; opj_write_bytes(l_current_cdef_ptr, JP2_CDEF, 4); /* BPCC */ l_current_cdef_ptr += 4; l_value = jp2->color.jp2_cdef->n; opj_write_bytes(l_current_cdef_ptr, l_value, 2); /* N */ l_current_cdef_ptr += 2; for (i = 0U; i < jp2->color.jp2_cdef->n; ++i) { l_value = jp2->color.jp2_cdef->info[i].cn; opj_write_bytes(l_current_cdef_ptr, l_value, 2); /* Cni */ l_current_cdef_ptr += 2; l_value = jp2->color.jp2_cdef->info[i].typ; opj_write_bytes(l_current_cdef_ptr, l_value, 2); /* Typi */ l_current_cdef_ptr += 2; l_value = jp2->color.jp2_cdef->info[i].asoc; opj_write_bytes(l_current_cdef_ptr, l_value, 2); /* Asoci */ l_current_cdef_ptr += 2; } *p_nb_bytes_written = l_cdef_size; return l_cdef_data; } static OPJ_BYTE * opj_jp2_write_colr(opj_jp2_t *jp2, OPJ_UINT32 * p_nb_bytes_written ) { /* room for 8 bytes for box 3 for common data and variable upon profile*/ OPJ_UINT32 l_colr_size = 11; OPJ_BYTE * l_colr_data, * l_current_colr_ptr; /* preconditions */ assert(jp2 != 00); assert(p_nb_bytes_written != 00); assert(jp2->meth == 1 || jp2->meth == 2); switch (jp2->meth) { case 1 : l_colr_size += 4; /* EnumCS */ break; case 2 : assert(jp2->color.icc_profile_len); /* ICC profile */ l_colr_size += jp2->color.icc_profile_len; break; default : return 00; } l_colr_data = (OPJ_BYTE *) opj_calloc(1, l_colr_size); if (l_colr_data == 00) { return 00; } l_current_colr_ptr = l_colr_data; opj_write_bytes(l_current_colr_ptr, l_colr_size, 4); /* write box size */ l_current_colr_ptr += 4; opj_write_bytes(l_current_colr_ptr, JP2_COLR, 4); /* BPCC */ l_current_colr_ptr += 4; opj_write_bytes(l_current_colr_ptr, jp2->meth, 1); /* METH */ ++l_current_colr_ptr; opj_write_bytes(l_current_colr_ptr, jp2->precedence, 1); /* PRECEDENCE */ ++l_current_colr_ptr; opj_write_bytes(l_current_colr_ptr, jp2->approx, 1); /* APPROX */ ++l_current_colr_ptr; if (jp2->meth == 1) { /* Meth value is restricted to 1 or 2 (Table I.9 of part 1) */ opj_write_bytes(l_current_colr_ptr, jp2->enumcs, 4); } /* EnumCS */ else { if (jp2->meth == 2) { /* ICC profile */ OPJ_UINT32 i; for (i = 0; i < jp2->color.icc_profile_len; ++i) { opj_write_bytes(l_current_colr_ptr, jp2->color.icc_profile_buf[i], 1); ++l_current_colr_ptr; } } } *p_nb_bytes_written = l_colr_size; return l_colr_data; } static void opj_jp2_free_pclr(opj_jp2_color_t *color) { opj_free(color->jp2_pclr->channel_sign); opj_free(color->jp2_pclr->channel_size); opj_free(color->jp2_pclr->entries); if (color->jp2_pclr->cmap) { opj_free(color->jp2_pclr->cmap); } opj_free(color->jp2_pclr); color->jp2_pclr = NULL; } static OPJ_BOOL opj_jp2_check_color(opj_image_t *image, opj_jp2_color_t *color, opj_event_mgr_t *p_manager) { OPJ_UINT16 i; /* testcase 4149.pdf.SIGSEGV.cf7.3501 */ if (color->jp2_cdef) { opj_jp2_cdef_info_t *info = color->jp2_cdef->info; OPJ_UINT16 n = color->jp2_cdef->n; OPJ_UINT32 nr_channels = image->numcomps; /* FIXME image->numcomps == jp2->numcomps before color is applied ??? */ /* cdef applies to cmap channels if any */ if (color->jp2_pclr && color->jp2_pclr->cmap) { nr_channels = (OPJ_UINT32)color->jp2_pclr->nr_channels; } for (i = 0; i < n; i++) { if (info[i].cn >= nr_channels) { opj_event_msg(p_manager, EVT_ERROR, "Invalid component index %d (>= %d).\n", info[i].cn, nr_channels); return OPJ_FALSE; } if (info[i].asoc == 65535U) { continue; } if (info[i].asoc > 0 && (OPJ_UINT32)(info[i].asoc - 1) >= nr_channels) { opj_event_msg(p_manager, EVT_ERROR, "Invalid component index %d (>= %d).\n", info[i].asoc - 1, nr_channels); return OPJ_FALSE; } } /* issue 397 */ /* ISO 15444-1 states that if cdef is present, it shall contain a complete list of channel definitions. */ while (nr_channels > 0) { for (i = 0; i < n; ++i) { if ((OPJ_UINT32)info[i].cn == (nr_channels - 1U)) { break; } } if (i == n) { opj_event_msg(p_manager, EVT_ERROR, "Incomplete channel definitions.\n"); return OPJ_FALSE; } --nr_channels; } } /* testcases 451.pdf.SIGSEGV.f4c.3723, 451.pdf.SIGSEGV.5b5.3723 and 66ea31acbb0f23a2bbc91f64d69a03f5_signal_sigsegv_13937c0_7030_5725.pdf */ if (color->jp2_pclr && color->jp2_pclr->cmap) { OPJ_UINT16 nr_channels = color->jp2_pclr->nr_channels; opj_jp2_cmap_comp_t *cmap = color->jp2_pclr->cmap; OPJ_BOOL *pcol_usage, is_sane = OPJ_TRUE; /* verify that all original components match an existing one */ for (i = 0; i < nr_channels; i++) { if (cmap[i].cmp >= image->numcomps) { opj_event_msg(p_manager, EVT_ERROR, "Invalid component index %d (>= %d).\n", cmap[i].cmp, image->numcomps); is_sane = OPJ_FALSE; } } pcol_usage = (OPJ_BOOL *) opj_calloc(nr_channels, sizeof(OPJ_BOOL)); if (!pcol_usage) { opj_event_msg(p_manager, EVT_ERROR, "Unexpected OOM.\n"); return OPJ_FALSE; } /* verify that no component is targeted more than once */ for (i = 0; i < nr_channels; i++) { OPJ_BYTE mtyp = cmap[i].mtyp; OPJ_BYTE pcol = cmap[i].pcol; /* See ISO 15444-1 Table I.14 – MTYPi field values */ if (mtyp != 0 && mtyp != 1) { opj_event_msg(p_manager, EVT_ERROR, "Invalid value for cmap[%d].mtyp = %d.\n", i, mtyp); is_sane = OPJ_FALSE; } else if (pcol >= nr_channels) { opj_event_msg(p_manager, EVT_ERROR, "Invalid component/palette index for direct mapping %d.\n", pcol); is_sane = OPJ_FALSE; } else if (pcol_usage[pcol] && mtyp == 1) { opj_event_msg(p_manager, EVT_ERROR, "Component %d is mapped twice.\n", pcol); is_sane = OPJ_FALSE; } else if (mtyp == 0 && pcol != 0) { /* I.5.3.5 PCOL: If the value of the MTYP field for this channel is 0, then * the value of this field shall be 0. */ opj_event_msg(p_manager, EVT_ERROR, "Direct use at #%d however pcol=%d.\n", i, pcol); is_sane = OPJ_FALSE; } else if (mtyp == 1 && pcol != i) { /* OpenJPEG implementation limitation. See assert(i == pcol); */ /* in opj_jp2_apply_pclr() */ opj_event_msg(p_manager, EVT_ERROR, "Implementation limitation: for palette mapping, " "pcol[%d] should be equal to %d, but is equal " "to %d.\n", i, i, pcol); is_sane = OPJ_FALSE; } else { pcol_usage[pcol] = OPJ_TRUE; } } /* verify that all components are targeted at least once */ for (i = 0; i < nr_channels; i++) { if (!pcol_usage[i] && cmap[i].mtyp != 0) { opj_event_msg(p_manager, EVT_ERROR, "Component %d doesn't have a mapping.\n", i); is_sane = OPJ_FALSE; } } /* Issue 235/447 weird cmap */ if (1 && is_sane && (image->numcomps == 1U)) { for (i = 0; i < nr_channels; i++) { if (!pcol_usage[i]) { is_sane = 0U; opj_event_msg(p_manager, EVT_WARNING, "Component mapping seems wrong. Trying to correct.\n"); break; } } if (!is_sane) { is_sane = OPJ_TRUE; for (i = 0; i < nr_channels; i++) { cmap[i].mtyp = 1U; cmap[i].pcol = (OPJ_BYTE) i; } } } opj_free(pcol_usage); if (!is_sane) { return OPJ_FALSE; } } return OPJ_TRUE; } /* file9.jp2 */ static OPJ_BOOL opj_jp2_apply_pclr(opj_image_t *image, opj_jp2_color_t *color, opj_event_mgr_t * p_manager) { opj_image_comp_t *old_comps, *new_comps; OPJ_BYTE *channel_size, *channel_sign; OPJ_UINT32 *entries; opj_jp2_cmap_comp_t *cmap; OPJ_INT32 *src, *dst; OPJ_UINT32 j, max; OPJ_UINT16 i, nr_channels, cmp, pcol; OPJ_INT32 k, top_k; channel_size = color->jp2_pclr->channel_size; channel_sign = color->jp2_pclr->channel_sign; entries = color->jp2_pclr->entries; cmap = color->jp2_pclr->cmap; nr_channels = color->jp2_pclr->nr_channels; for (i = 0; i < nr_channels; ++i) { /* Palette mapping: */ cmp = cmap[i].cmp; if (image->comps[cmp].data == NULL) { opj_event_msg(p_manager, EVT_ERROR, "image->comps[%d].data == NULL in opj_jp2_apply_pclr().\n", i); return OPJ_FALSE; } } old_comps = image->comps; new_comps = (opj_image_comp_t*) opj_malloc(nr_channels * sizeof(opj_image_comp_t)); if (!new_comps) { opj_event_msg(p_manager, EVT_ERROR, "Memory allocation failure in opj_jp2_apply_pclr().\n"); return OPJ_FALSE; } for (i = 0; i < nr_channels; ++i) { pcol = cmap[i].pcol; cmp = cmap[i].cmp; /* Direct use */ if (cmap[i].mtyp == 0) { assert(pcol == 0); new_comps[i] = old_comps[cmp]; } else { assert(i == pcol); new_comps[pcol] = old_comps[cmp]; } /* Palette mapping: */ new_comps[i].data = (OPJ_INT32*) opj_image_data_alloc(sizeof(OPJ_INT32) * old_comps[cmp].w * old_comps[cmp].h); if (!new_comps[i].data) { while (i > 0) { -- i; opj_image_data_free(new_comps[i].data); } opj_free(new_comps); opj_event_msg(p_manager, EVT_ERROR, "Memory allocation failure in opj_jp2_apply_pclr().\n"); return OPJ_FALSE; } new_comps[i].prec = channel_size[i]; new_comps[i].sgnd = channel_sign[i]; } top_k = color->jp2_pclr->nr_entries - 1; for (i = 0; i < nr_channels; ++i) { /* Palette mapping: */ cmp = cmap[i].cmp; pcol = cmap[i].pcol; src = old_comps[cmp].data; assert(src); /* verified above */ max = new_comps[pcol].w * new_comps[pcol].h; /* Direct use: */ if (cmap[i].mtyp == 0) { dst = new_comps[i].data; assert(dst); for (j = 0; j < max; ++j) { dst[j] = src[j]; } } else { assert(i == pcol); dst = new_comps[pcol].data; assert(dst); for (j = 0; j < max; ++j) { /* The index */ if ((k = src[j]) < 0) { k = 0; } else if (k > top_k) { k = top_k; } /* The colour */ dst[j] = (OPJ_INT32)entries[k * nr_channels + pcol]; } } } max = image->numcomps; for (j = 0; j < max; ++j) { if (old_comps[j].data) { opj_image_data_free(old_comps[j].data); } } opj_free(old_comps); image->comps = new_comps; image->numcomps = nr_channels; return OPJ_TRUE; }/* apply_pclr() */ static OPJ_BOOL opj_jp2_read_pclr(opj_jp2_t *jp2, OPJ_BYTE * p_pclr_header_data, OPJ_UINT32 p_pclr_header_size, opj_event_mgr_t * p_manager ) { opj_jp2_pclr_t *jp2_pclr; OPJ_BYTE *channel_size, *channel_sign; OPJ_UINT32 *entries; OPJ_UINT16 nr_entries, nr_channels; OPJ_UINT16 i, j; OPJ_UINT32 l_value; OPJ_BYTE *orig_header_data = p_pclr_header_data; /* preconditions */ assert(p_pclr_header_data != 00); assert(jp2 != 00); assert(p_manager != 00); (void)p_pclr_header_size; if (jp2->color.jp2_pclr) { return OPJ_FALSE; } if (p_pclr_header_size < 3) { return OPJ_FALSE; } opj_read_bytes(p_pclr_header_data, &l_value, 2); /* NE */ p_pclr_header_data += 2; nr_entries = (OPJ_UINT16) l_value; if ((nr_entries == 0U) || (nr_entries > 1024U)) { opj_event_msg(p_manager, EVT_ERROR, "Invalid PCLR box. Reports %d entries\n", (int)nr_entries); return OPJ_FALSE; } opj_read_bytes(p_pclr_header_data, &l_value, 1); /* NPC */ ++p_pclr_header_data; nr_channels = (OPJ_UINT16) l_value; if (nr_channels == 0U) { opj_event_msg(p_manager, EVT_ERROR, "Invalid PCLR box. Reports 0 palette columns\n"); return OPJ_FALSE; } if (p_pclr_header_size < 3 + (OPJ_UINT32)nr_channels) { return OPJ_FALSE; } entries = (OPJ_UINT32*) opj_malloc(sizeof(OPJ_UINT32) * nr_channels * nr_entries); if (!entries) { return OPJ_FALSE; } channel_size = (OPJ_BYTE*) opj_malloc(nr_channels); if (!channel_size) { opj_free(entries); return OPJ_FALSE; } channel_sign = (OPJ_BYTE*) opj_malloc(nr_channels); if (!channel_sign) { opj_free(entries); opj_free(channel_size); return OPJ_FALSE; } jp2_pclr = (opj_jp2_pclr_t*)opj_malloc(sizeof(opj_jp2_pclr_t)); if (!jp2_pclr) { opj_free(entries); opj_free(channel_size); opj_free(channel_sign); return OPJ_FALSE; } jp2_pclr->channel_sign = channel_sign; jp2_pclr->channel_size = channel_size; jp2_pclr->entries = entries; jp2_pclr->nr_entries = nr_entries; jp2_pclr->nr_channels = (OPJ_BYTE) l_value; jp2_pclr->cmap = NULL; jp2->color.jp2_pclr = jp2_pclr; for (i = 0; i < nr_channels; ++i) { opj_read_bytes(p_pclr_header_data, &l_value, 1); /* Bi */ ++p_pclr_header_data; channel_size[i] = (OPJ_BYTE)((l_value & 0x7f) + 1); channel_sign[i] = (l_value & 0x80) ? 1 : 0; } for (j = 0; j < nr_entries; ++j) { for (i = 0; i < nr_channels; ++i) { OPJ_UINT32 bytes_to_read = (OPJ_UINT32)((channel_size[i] + 7) >> 3); if (bytes_to_read > sizeof(OPJ_UINT32)) { bytes_to_read = sizeof(OPJ_UINT32); } if ((ptrdiff_t)p_pclr_header_size < (ptrdiff_t)(p_pclr_header_data - orig_header_data) + (ptrdiff_t)bytes_to_read) { return OPJ_FALSE; } opj_read_bytes(p_pclr_header_data, &l_value, bytes_to_read); /* Cji */ p_pclr_header_data += bytes_to_read; *entries = (OPJ_UINT32) l_value; entries++; } } return OPJ_TRUE; } static OPJ_BOOL opj_jp2_read_cmap(opj_jp2_t * jp2, OPJ_BYTE * p_cmap_header_data, OPJ_UINT32 p_cmap_header_size, opj_event_mgr_t * p_manager ) { opj_jp2_cmap_comp_t *cmap; OPJ_BYTE i, nr_channels; OPJ_UINT32 l_value; /* preconditions */ assert(jp2 != 00); assert(p_cmap_header_data != 00); assert(p_manager != 00); (void)p_cmap_header_size; /* Need nr_channels: */ if (jp2->color.jp2_pclr == NULL) { opj_event_msg(p_manager, EVT_ERROR, "Need to read a PCLR box before the CMAP box.\n"); return OPJ_FALSE; } /* Part 1, I.5.3.5: 'There shall be at most one Component Mapping box * inside a JP2 Header box' : */ if (jp2->color.jp2_pclr->cmap) { opj_event_msg(p_manager, EVT_ERROR, "Only one CMAP box is allowed.\n"); return OPJ_FALSE; } nr_channels = jp2->color.jp2_pclr->nr_channels; if (p_cmap_header_size < (OPJ_UINT32)nr_channels * 4) { opj_event_msg(p_manager, EVT_ERROR, "Insufficient data for CMAP box.\n"); return OPJ_FALSE; } cmap = (opj_jp2_cmap_comp_t*) opj_malloc(nr_channels * sizeof( opj_jp2_cmap_comp_t)); if (!cmap) { return OPJ_FALSE; } for (i = 0; i < nr_channels; ++i) { opj_read_bytes(p_cmap_header_data, &l_value, 2); /* CMP^i */ p_cmap_header_data += 2; cmap[i].cmp = (OPJ_UINT16) l_value; opj_read_bytes(p_cmap_header_data, &l_value, 1); /* MTYP^i */ ++p_cmap_header_data; cmap[i].mtyp = (OPJ_BYTE) l_value; opj_read_bytes(p_cmap_header_data, &l_value, 1); /* PCOL^i */ ++p_cmap_header_data; cmap[i].pcol = (OPJ_BYTE) l_value; } jp2->color.jp2_pclr->cmap = cmap; return OPJ_TRUE; } static void opj_jp2_apply_cdef(opj_image_t *image, opj_jp2_color_t *color, opj_event_mgr_t *manager) { opj_jp2_cdef_info_t *info; OPJ_UINT16 i, n, cn, asoc, acn; info = color->jp2_cdef->info; n = color->jp2_cdef->n; for (i = 0; i < n; ++i) { /* WATCH: acn = asoc - 1 ! */ asoc = info[i].asoc; cn = info[i].cn; if (cn >= image->numcomps) { opj_event_msg(manager, EVT_WARNING, "opj_jp2_apply_cdef: cn=%d, numcomps=%d\n", cn, image->numcomps); continue; } if (asoc == 0 || asoc == 65535) { image->comps[cn].alpha = info[i].typ; continue; } acn = (OPJ_UINT16)(asoc - 1); if (acn >= image->numcomps) { opj_event_msg(manager, EVT_WARNING, "opj_jp2_apply_cdef: acn=%d, numcomps=%d\n", acn, image->numcomps); continue; } /* Swap only if color channel */ if ((cn != acn) && (info[i].typ == 0)) { opj_image_comp_t saved; OPJ_UINT16 j; memcpy(&saved, &image->comps[cn], sizeof(opj_image_comp_t)); memcpy(&image->comps[cn], &image->comps[acn], sizeof(opj_image_comp_t)); memcpy(&image->comps[acn], &saved, sizeof(opj_image_comp_t)); /* Swap channels in following channel definitions, don't bother with j <= i that are already processed */ for (j = (OPJ_UINT16)(i + 1U); j < n ; ++j) { if (info[j].cn == cn) { info[j].cn = acn; } else if (info[j].cn == acn) { info[j].cn = cn; } /* asoc is related to color index. Do not update. */ } } image->comps[cn].alpha = info[i].typ; } if (color->jp2_cdef->info) { opj_free(color->jp2_cdef->info); } opj_free(color->jp2_cdef); color->jp2_cdef = NULL; }/* jp2_apply_cdef() */ static OPJ_BOOL opj_jp2_read_cdef(opj_jp2_t * jp2, OPJ_BYTE * p_cdef_header_data, OPJ_UINT32 p_cdef_header_size, opj_event_mgr_t * p_manager ) { opj_jp2_cdef_info_t *cdef_info; OPJ_UINT16 i; OPJ_UINT32 l_value; /* preconditions */ assert(jp2 != 00); assert(p_cdef_header_data != 00); assert(p_manager != 00); (void)p_cdef_header_size; /* Part 1, I.5.3.6: 'The shall be at most one Channel Definition box * inside a JP2 Header box.'*/ if (jp2->color.jp2_cdef) { return OPJ_FALSE; } if (p_cdef_header_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Insufficient data for CDEF box.\n"); return OPJ_FALSE; } opj_read_bytes(p_cdef_header_data, &l_value, 2); /* N */ p_cdef_header_data += 2; if ((OPJ_UINT16)l_value == 0) { /* szukw000: FIXME */ opj_event_msg(p_manager, EVT_ERROR, "Number of channel description is equal to zero in CDEF box.\n"); return OPJ_FALSE; } if (p_cdef_header_size < 2 + (OPJ_UINT32)(OPJ_UINT16)l_value * 6) { opj_event_msg(p_manager, EVT_ERROR, "Insufficient data for CDEF box.\n"); return OPJ_FALSE; } cdef_info = (opj_jp2_cdef_info_t*) opj_malloc(l_value * sizeof( opj_jp2_cdef_info_t)); if (!cdef_info) { return OPJ_FALSE; } jp2->color.jp2_cdef = (opj_jp2_cdef_t*)opj_malloc(sizeof(opj_jp2_cdef_t)); if (!jp2->color.jp2_cdef) { opj_free(cdef_info); return OPJ_FALSE; } jp2->color.jp2_cdef->info = cdef_info; jp2->color.jp2_cdef->n = (OPJ_UINT16) l_value; for (i = 0; i < jp2->color.jp2_cdef->n; ++i) { opj_read_bytes(p_cdef_header_data, &l_value, 2); /* Cn^i */ p_cdef_header_data += 2; cdef_info[i].cn = (OPJ_UINT16) l_value; opj_read_bytes(p_cdef_header_data, &l_value, 2); /* Typ^i */ p_cdef_header_data += 2; cdef_info[i].typ = (OPJ_UINT16) l_value; opj_read_bytes(p_cdef_header_data, &l_value, 2); /* Asoc^i */ p_cdef_header_data += 2; cdef_info[i].asoc = (OPJ_UINT16) l_value; } return OPJ_TRUE; } static OPJ_BOOL opj_jp2_read_colr(opj_jp2_t *jp2, OPJ_BYTE * p_colr_header_data, OPJ_UINT32 p_colr_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_value; /* preconditions */ assert(jp2 != 00); assert(p_colr_header_data != 00); assert(p_manager != 00); if (p_colr_header_size < 3) { opj_event_msg(p_manager, EVT_ERROR, "Bad COLR header box (bad size)\n"); return OPJ_FALSE; } /* Part 1, I.5.3.3 : 'A conforming JP2 reader shall ignore all Colour * Specification boxes after the first.' */ if (jp2->color.jp2_has_colr) { opj_event_msg(p_manager, EVT_INFO, "A conforming JP2 reader shall ignore all Colour Specification boxes after the first, so we ignore this one.\n"); p_colr_header_data += p_colr_header_size; return OPJ_TRUE; } opj_read_bytes(p_colr_header_data, &jp2->meth, 1); /* METH */ ++p_colr_header_data; opj_read_bytes(p_colr_header_data, &jp2->precedence, 1); /* PRECEDENCE */ ++p_colr_header_data; opj_read_bytes(p_colr_header_data, &jp2->approx, 1); /* APPROX */ ++p_colr_header_data; if (jp2->meth == 1) { if (p_colr_header_size < 7) { opj_event_msg(p_manager, EVT_ERROR, "Bad COLR header box (bad size: %d)\n", p_colr_header_size); return OPJ_FALSE; } if ((p_colr_header_size > 7) && (jp2->enumcs != 14)) { /* handled below for CIELab) */ /* testcase Altona_Technical_v20_x4.pdf */ opj_event_msg(p_manager, EVT_WARNING, "Bad COLR header box (bad size: %d)\n", p_colr_header_size); } opj_read_bytes(p_colr_header_data, &jp2->enumcs, 4); /* EnumCS */ p_colr_header_data += 4; if (jp2->enumcs == 14) { /* CIELab */ OPJ_UINT32 *cielab; OPJ_UINT32 rl, ol, ra, oa, rb, ob, il; cielab = (OPJ_UINT32*)opj_malloc(9 * sizeof(OPJ_UINT32)); if (cielab == NULL) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for cielab\n"); return OPJ_FALSE; } cielab[0] = 14; /* enumcs */ /* default values */ rl = ra = rb = ol = oa = ob = 0; il = 0x00443530; /* D50 */ cielab[1] = 0x44454600;/* DEF */ if (p_colr_header_size == 35) { opj_read_bytes(p_colr_header_data, &rl, 4); p_colr_header_data += 4; opj_read_bytes(p_colr_header_data, &ol, 4); p_colr_header_data += 4; opj_read_bytes(p_colr_header_data, &ra, 4); p_colr_header_data += 4; opj_read_bytes(p_colr_header_data, &oa, 4); p_colr_header_data += 4; opj_read_bytes(p_colr_header_data, &rb, 4); p_colr_header_data += 4; opj_read_bytes(p_colr_header_data, &ob, 4); p_colr_header_data += 4; opj_read_bytes(p_colr_header_data, &il, 4); p_colr_header_data += 4; cielab[1] = 0; } else if (p_colr_header_size != 7) { opj_event_msg(p_manager, EVT_WARNING, "Bad COLR header box (CIELab, bad size: %d)\n", p_colr_header_size); } cielab[2] = rl; cielab[4] = ra; cielab[6] = rb; cielab[3] = ol; cielab[5] = oa; cielab[7] = ob; cielab[8] = il; jp2->color.icc_profile_buf = (OPJ_BYTE*)cielab; jp2->color.icc_profile_len = 0; } jp2->color.jp2_has_colr = 1; } else if (jp2->meth == 2) { /* ICC profile */ OPJ_INT32 it_icc_value = 0; OPJ_INT32 icc_len = (OPJ_INT32)p_colr_header_size - 3; jp2->color.icc_profile_len = (OPJ_UINT32)icc_len; jp2->color.icc_profile_buf = (OPJ_BYTE*) opj_calloc(1, (size_t)icc_len); if (!jp2->color.icc_profile_buf) { jp2->color.icc_profile_len = 0; return OPJ_FALSE; } for (it_icc_value = 0; it_icc_value < icc_len; ++it_icc_value) { opj_read_bytes(p_colr_header_data, &l_value, 1); /* icc values */ ++p_colr_header_data; jp2->color.icc_profile_buf[it_icc_value] = (OPJ_BYTE) l_value; } jp2->color.jp2_has_colr = 1; } else if (jp2->meth > 2) { /* ISO/IEC 15444-1:2004 (E), Table I.9 Legal METH values: conforming JP2 reader shall ignore the entire Colour Specification box.*/ opj_event_msg(p_manager, EVT_INFO, "COLR BOX meth value is not a regular value (%d), " "so we will ignore the entire Colour Specification box. \n", jp2->meth); } return OPJ_TRUE; } OPJ_BOOL opj_jp2_decode(opj_jp2_t *jp2, opj_stream_private_t *p_stream, opj_image_t* p_image, opj_event_mgr_t * p_manager) { if (!p_image) { return OPJ_FALSE; } /* J2K decoding */ if (! opj_j2k_decode(jp2->j2k, p_stream, p_image, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to decode the codestream in the JP2 file\n"); return OPJ_FALSE; } if (jp2->j2k->m_specific_param.m_decoder.m_numcomps_to_decode) { /* Bypass all JP2 component transforms */ return OPJ_TRUE; } if (!jp2->ignore_pclr_cmap_cdef) { if (!opj_jp2_check_color(p_image, &(jp2->color), p_manager)) { return OPJ_FALSE; } /* Set Image Color Space */ if (jp2->enumcs == 16) { p_image->color_space = OPJ_CLRSPC_SRGB; } else if (jp2->enumcs == 17) { p_image->color_space = OPJ_CLRSPC_GRAY; } else if (jp2->enumcs == 18) { p_image->color_space = OPJ_CLRSPC_SYCC; } else if (jp2->enumcs == 24) { p_image->color_space = OPJ_CLRSPC_EYCC; } else if (jp2->enumcs == 12) { p_image->color_space = OPJ_CLRSPC_CMYK; } else { p_image->color_space = OPJ_CLRSPC_UNKNOWN; } if (jp2->color.jp2_pclr) { /* Part 1, I.5.3.4: Either both or none : */ if (!jp2->color.jp2_pclr->cmap) { opj_jp2_free_pclr(&(jp2->color)); } else { if (!opj_jp2_apply_pclr(p_image, &(jp2->color), p_manager)) { return OPJ_FALSE; } } } /* Apply the color space if needed */ if (jp2->color.jp2_cdef) { opj_jp2_apply_cdef(p_image, &(jp2->color), p_manager); } if (jp2->color.icc_profile_buf) { p_image->icc_profile_buf = jp2->color.icc_profile_buf; p_image->icc_profile_len = jp2->color.icc_profile_len; jp2->color.icc_profile_buf = NULL; } } return OPJ_TRUE; } static OPJ_BOOL opj_jp2_write_jp2h(opj_jp2_t *jp2, opj_stream_private_t *stream, opj_event_mgr_t * p_manager ) { opj_jp2_img_header_writer_handler_t l_writers [4]; opj_jp2_img_header_writer_handler_t * l_current_writer; OPJ_INT32 i, l_nb_pass; /* size of data for super box*/ OPJ_UINT32 l_jp2h_size = 8; OPJ_BOOL l_result = OPJ_TRUE; /* to store the data of the super box */ OPJ_BYTE l_jp2h_data [8]; /* preconditions */ assert(stream != 00); assert(jp2 != 00); assert(p_manager != 00); memset(l_writers, 0, sizeof(l_writers)); if (jp2->bpc == 255) { l_nb_pass = 3; l_writers[0].handler = opj_jp2_write_ihdr; l_writers[1].handler = opj_jp2_write_bpcc; l_writers[2].handler = opj_jp2_write_colr; } else { l_nb_pass = 2; l_writers[0].handler = opj_jp2_write_ihdr; l_writers[1].handler = opj_jp2_write_colr; } if (jp2->color.jp2_cdef != NULL) { l_writers[l_nb_pass].handler = opj_jp2_write_cdef; l_nb_pass++; } /* write box header */ /* write JP2H type */ opj_write_bytes(l_jp2h_data + 4, JP2_JP2H, 4); l_current_writer = l_writers; for (i = 0; i < l_nb_pass; ++i) { l_current_writer->m_data = l_current_writer->handler(jp2, &(l_current_writer->m_size)); if (l_current_writer->m_data == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to hold JP2 Header data\n"); l_result = OPJ_FALSE; break; } l_jp2h_size += l_current_writer->m_size; ++l_current_writer; } if (! l_result) { l_current_writer = l_writers; for (i = 0; i < l_nb_pass; ++i) { if (l_current_writer->m_data != 00) { opj_free(l_current_writer->m_data); } ++l_current_writer; } return OPJ_FALSE; } /* write super box size */ opj_write_bytes(l_jp2h_data, l_jp2h_size, 4); /* write super box data on stream */ if (opj_stream_write_data(stream, l_jp2h_data, 8, p_manager) != 8) { opj_event_msg(p_manager, EVT_ERROR, "Stream error while writing JP2 Header box\n"); l_result = OPJ_FALSE; } if (l_result) { l_current_writer = l_writers; for (i = 0; i < l_nb_pass; ++i) { if (opj_stream_write_data(stream, l_current_writer->m_data, l_current_writer->m_size, p_manager) != l_current_writer->m_size) { opj_event_msg(p_manager, EVT_ERROR, "Stream error while writing JP2 Header box\n"); l_result = OPJ_FALSE; break; } ++l_current_writer; } } l_current_writer = l_writers; /* cleanup */ for (i = 0; i < l_nb_pass; ++i) { if (l_current_writer->m_data != 00) { opj_free(l_current_writer->m_data); } ++l_current_writer; } return l_result; } static OPJ_BOOL opj_jp2_write_ftyp(opj_jp2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager) { OPJ_UINT32 i; OPJ_UINT32 l_ftyp_size; OPJ_BYTE * l_ftyp_data, * l_current_data_ptr; OPJ_BOOL l_result; /* preconditions */ assert(cio != 00); assert(jp2 != 00); assert(p_manager != 00); l_ftyp_size = 16 + 4 * jp2->numcl; l_ftyp_data = (OPJ_BYTE *) opj_calloc(1, l_ftyp_size); if (l_ftyp_data == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle ftyp data\n"); return OPJ_FALSE; } l_current_data_ptr = l_ftyp_data; opj_write_bytes(l_current_data_ptr, l_ftyp_size, 4); /* box size */ l_current_data_ptr += 4; opj_write_bytes(l_current_data_ptr, JP2_FTYP, 4); /* FTYP */ l_current_data_ptr += 4; opj_write_bytes(l_current_data_ptr, jp2->brand, 4); /* BR */ l_current_data_ptr += 4; opj_write_bytes(l_current_data_ptr, jp2->minversion, 4); /* MinV */ l_current_data_ptr += 4; for (i = 0; i < jp2->numcl; i++) { opj_write_bytes(l_current_data_ptr, jp2->cl[i], 4); /* CL */ } l_result = (opj_stream_write_data(cio, l_ftyp_data, l_ftyp_size, p_manager) == l_ftyp_size); if (! l_result) { opj_event_msg(p_manager, EVT_ERROR, "Error while writing ftyp data to stream\n"); } opj_free(l_ftyp_data); return l_result; } static OPJ_BOOL opj_jp2_write_jp2c(opj_jp2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager) { OPJ_OFF_T j2k_codestream_exit; OPJ_BYTE l_data_header [8]; /* preconditions */ assert(jp2 != 00); assert(cio != 00); assert(p_manager != 00); assert(opj_stream_has_seek(cio)); j2k_codestream_exit = opj_stream_tell(cio); opj_write_bytes(l_data_header, (OPJ_UINT32)(j2k_codestream_exit - jp2->j2k_codestream_offset), 4); /* size of codestream */ opj_write_bytes(l_data_header + 4, JP2_JP2C, 4); /* JP2C */ if (! opj_stream_seek(cio, jp2->j2k_codestream_offset, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n"); return OPJ_FALSE; } if (opj_stream_write_data(cio, l_data_header, 8, p_manager) != 8) { opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n"); return OPJ_FALSE; } if (! opj_stream_seek(cio, j2k_codestream_exit, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n"); return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_jp2_write_jp(opj_jp2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager) { /* 12 bytes will be read */ OPJ_BYTE l_signature_data [12]; /* preconditions */ assert(cio != 00); assert(jp2 != 00); assert(p_manager != 00); OPJ_UNUSED(jp2); /* write box length */ opj_write_bytes(l_signature_data, 12, 4); /* writes box type */ opj_write_bytes(l_signature_data + 4, JP2_JP, 4); /* writes magic number*/ opj_write_bytes(l_signature_data + 8, 0x0d0a870a, 4); if (opj_stream_write_data(cio, l_signature_data, 12, p_manager) != 12) { return OPJ_FALSE; } return OPJ_TRUE; } /* ----------------------------------------------------------------------- */ /* JP2 decoder interface */ /* ----------------------------------------------------------------------- */ void opj_jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters) { /* setup the J2K codec */ opj_j2k_setup_decoder(jp2->j2k, parameters); /* further JP2 initializations go here */ jp2->color.jp2_has_colr = 0; jp2->ignore_pclr_cmap_cdef = parameters->flags & OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG; } void opj_jp2_decoder_set_strict_mode(opj_jp2_t *jp2, OPJ_BOOL strict) { opj_j2k_decoder_set_strict_mode(jp2->j2k, strict); } OPJ_BOOL opj_jp2_set_threads(opj_jp2_t *jp2, OPJ_UINT32 num_threads) { return opj_j2k_set_threads(jp2->j2k, num_threads); } /* ----------------------------------------------------------------------- */ /* JP2 encoder interface */ /* ----------------------------------------------------------------------- */ OPJ_BOOL opj_jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_t *image, opj_event_mgr_t * p_manager) { OPJ_UINT32 i; OPJ_UINT32 depth_0; OPJ_UINT32 sign; OPJ_UINT32 alpha_count; OPJ_UINT32 color_channels = 0U; OPJ_UINT32 alpha_channel = 0U; if (!jp2 || !parameters || !image) { return OPJ_FALSE; } /* setup the J2K codec */ /* ------------------- */ /* Check if number of components respects standard */ if (image->numcomps < 1 || image->numcomps > 16384) { opj_event_msg(p_manager, EVT_ERROR, "Invalid number of components specified while setting up JP2 encoder\n"); return OPJ_FALSE; } if (opj_j2k_setup_encoder(jp2->j2k, parameters, image, p_manager) == OPJ_FALSE) { return OPJ_FALSE; } /* setup the JP2 codec */ /* ------------------- */ /* Profile box */ jp2->brand = JP2_JP2; /* BR */ jp2->minversion = 0; /* MinV */ jp2->numcl = 1; jp2->cl = (OPJ_UINT32*) opj_malloc(jp2->numcl * sizeof(OPJ_UINT32)); if (!jp2->cl) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory when setup the JP2 encoder\n"); return OPJ_FALSE; } jp2->cl[0] = JP2_JP2; /* CL0 : JP2 */ /* Image Header box */ jp2->numcomps = image->numcomps; /* NC */ jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof( opj_jp2_comps_t)); if (!jp2->comps) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory when setup the JP2 encoder\n"); /* Memory of jp2->cl will be freed by opj_jp2_destroy */ return OPJ_FALSE; } jp2->h = image->y1 - image->y0; /* HEIGHT */ jp2->w = image->x1 - image->x0; /* WIDTH */ /* BPC */ depth_0 = image->comps[0].prec - 1; sign = image->comps[0].sgnd; jp2->bpc = depth_0 + (sign << 7); for (i = 1; i < image->numcomps; i++) { OPJ_UINT32 depth = image->comps[i].prec - 1; sign = image->comps[i].sgnd; if (depth_0 != depth) { jp2->bpc = 255; } } jp2->C = 7; /* C : Always 7 */ jp2->UnkC = 0; /* UnkC, colorspace specified in colr box */ jp2->IPR = 0; /* IPR, no intellectual property */ /* BitsPerComponent box */ for (i = 0; i < image->numcomps; i++) { jp2->comps[i].bpcc = image->comps[i].prec - 1 + (image->comps[i].sgnd << 7); } /* Colour Specification box */ if (image->icc_profile_len) { jp2->meth = 2; jp2->enumcs = 0; } else { jp2->meth = 1; if (image->color_space == 1) { jp2->enumcs = 16; /* sRGB as defined by IEC 61966-2-1 */ } else if (image->color_space == 2) { jp2->enumcs = 17; /* greyscale */ } else if (image->color_space == 3) { jp2->enumcs = 18; /* YUV */ } } /* Channel Definition box */ /* FIXME not provided by parameters */ /* We try to do what we can... */ alpha_count = 0U; for (i = 0; i < image->numcomps; i++) { if (image->comps[i].alpha != 0) { alpha_count++; alpha_channel = i; } } if (alpha_count == 1U) { /* no way to deal with more than 1 alpha channel */ switch (jp2->enumcs) { case 16: case 18: color_channels = 3; break; case 17: color_channels = 1; break; default: alpha_count = 0U; break; } if (alpha_count == 0U) { opj_event_msg(p_manager, EVT_WARNING, "Alpha channel specified but unknown enumcs. No cdef box will be created.\n"); } else if (image->numcomps < (color_channels + 1)) { opj_event_msg(p_manager, EVT_WARNING, "Alpha channel specified but not enough image components for an automatic cdef box creation.\n"); alpha_count = 0U; } else if ((OPJ_UINT32)alpha_channel < color_channels) { opj_event_msg(p_manager, EVT_WARNING, "Alpha channel position conflicts with color channel. No cdef box will be created.\n"); alpha_count = 0U; } } else if (alpha_count > 1) { opj_event_msg(p_manager, EVT_WARNING, "Multiple alpha channels specified. No cdef box will be created.\n"); } if (alpha_count == 1U) { /* if here, we know what we can do */ jp2->color.jp2_cdef = (opj_jp2_cdef_t*)opj_malloc(sizeof(opj_jp2_cdef_t)); if (!jp2->color.jp2_cdef) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup the JP2 encoder\n"); return OPJ_FALSE; } /* no memset needed, all values will be overwritten except if jp2->color.jp2_cdef->info allocation fails, */ /* in which case jp2->color.jp2_cdef->info will be NULL => valid for destruction */ jp2->color.jp2_cdef->info = (opj_jp2_cdef_info_t*) opj_malloc( image->numcomps * sizeof(opj_jp2_cdef_info_t)); if (!jp2->color.jp2_cdef->info) { /* memory will be freed by opj_jp2_destroy */ opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup the JP2 encoder\n"); return OPJ_FALSE; } jp2->color.jp2_cdef->n = (OPJ_UINT16) image->numcomps; /* cast is valid : image->numcomps [1,16384] */ for (i = 0U; i < color_channels; i++) { jp2->color.jp2_cdef->info[i].cn = (OPJ_UINT16) i; /* cast is valid : image->numcomps [1,16384] */ jp2->color.jp2_cdef->info[i].typ = 0U; jp2->color.jp2_cdef->info[i].asoc = (OPJ_UINT16)(i + 1U); /* No overflow + cast is valid : image->numcomps [1,16384] */ } for (; i < image->numcomps; i++) { if (image->comps[i].alpha != 0) { /* we'll be here exactly once */ jp2->color.jp2_cdef->info[i].cn = (OPJ_UINT16) i; /* cast is valid : image->numcomps [1,16384] */ jp2->color.jp2_cdef->info[i].typ = 1U; /* Opacity channel */ jp2->color.jp2_cdef->info[i].asoc = 0U; /* Apply alpha channel to the whole image */ } else { /* Unknown channel */ jp2->color.jp2_cdef->info[i].cn = (OPJ_UINT16) i; /* cast is valid : image->numcomps [1,16384] */ jp2->color.jp2_cdef->info[i].typ = 65535U; jp2->color.jp2_cdef->info[i].asoc = 65535U; } } } jp2->precedence = 0; /* PRECEDENCE */ jp2->approx = 0; /* APPROX */ jp2->jpip_on = parameters->jpip_on; return OPJ_TRUE; } OPJ_BOOL opj_jp2_encode(opj_jp2_t *jp2, opj_stream_private_t *stream, opj_event_mgr_t * p_manager) { return opj_j2k_encode(jp2->j2k, stream, p_manager); } OPJ_BOOL opj_jp2_end_decompress(opj_jp2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(jp2 != 00); assert(cio != 00); assert(p_manager != 00); /* customization of the end encoding */ if (! opj_jp2_setup_end_header_reading(jp2, p_manager)) { return OPJ_FALSE; } /* write header */ if (! opj_jp2_exec(jp2, jp2->m_procedure_list, cio, p_manager)) { return OPJ_FALSE; } return opj_j2k_end_decompress(jp2->j2k, cio, p_manager); } OPJ_BOOL opj_jp2_end_compress(opj_jp2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(jp2 != 00); assert(cio != 00); assert(p_manager != 00); /* customization of the end encoding */ if (! opj_jp2_setup_end_header_writing(jp2, p_manager)) { return OPJ_FALSE; } if (! opj_j2k_end_compress(jp2->j2k, cio, p_manager)) { return OPJ_FALSE; } /* write header */ return opj_jp2_exec(jp2, jp2->m_procedure_list, cio, p_manager); } static OPJ_BOOL opj_jp2_setup_end_header_writing(opj_jp2_t *jp2, opj_event_mgr_t * p_manager) { /* preconditions */ assert(jp2 != 00); assert(p_manager != 00); #ifdef USE_JPIP if (jp2->jpip_on) { if (! opj_procedure_list_add_procedure(jp2->m_procedure_list, (opj_procedure)opj_jpip_write_iptr, p_manager)) { return OPJ_FALSE; } } #endif if (! opj_procedure_list_add_procedure(jp2->m_procedure_list, (opj_procedure)opj_jp2_write_jp2c, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, add your custom procedures */ #ifdef USE_JPIP if (jp2->jpip_on) { if (! opj_procedure_list_add_procedure(jp2->m_procedure_list, (opj_procedure)opj_jpip_write_cidx, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(jp2->m_procedure_list, (opj_procedure)opj_jpip_write_fidx, p_manager)) { return OPJ_FALSE; } } #endif return OPJ_TRUE; } static OPJ_BOOL opj_jp2_setup_end_header_reading(opj_jp2_t *jp2, opj_event_mgr_t * p_manager) { /* preconditions */ assert(jp2 != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(jp2->m_procedure_list, (opj_procedure)opj_jp2_read_header_procedure, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, add your custom procedures */ return OPJ_TRUE; } static OPJ_BOOL opj_jp2_default_validation(opj_jp2_t * jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager ) { OPJ_BOOL l_is_valid = OPJ_TRUE; OPJ_UINT32 i; /* preconditions */ assert(jp2 != 00); assert(cio != 00); assert(p_manager != 00); OPJ_UNUSED(p_manager); /* JPEG2000 codec validation */ /* STATE checking */ /* make sure the state is at 0 */ l_is_valid &= (jp2->jp2_state == JP2_STATE_NONE); /* make sure not reading a jp2h ???? WEIRD */ l_is_valid &= (jp2->jp2_img_state == JP2_IMG_STATE_NONE); /* POINTER validation */ /* make sure a j2k codec is present */ l_is_valid &= (jp2->j2k != 00); /* make sure a procedure list is present */ l_is_valid &= (jp2->m_procedure_list != 00); /* make sure a validation list is present */ l_is_valid &= (jp2->m_validation_list != 00); /* PARAMETER VALIDATION */ /* number of components */ l_is_valid &= (jp2->numcl > 0); /* width */ l_is_valid &= (jp2->h > 0); /* height */ l_is_valid &= (jp2->w > 0); /* precision */ for (i = 0; i < jp2->numcomps; ++i) { l_is_valid &= ((jp2->comps[i].bpcc & 0x7FU) < 38U); /* 0 is valid, ignore sign for check */ } /* METH */ l_is_valid &= ((jp2->meth > 0) && (jp2->meth < 3)); /* stream validation */ /* back and forth is needed */ l_is_valid &= opj_stream_has_seek(cio); return l_is_valid; } static OPJ_BOOL opj_jp2_read_header_procedure(opj_jp2_t *jp2, opj_stream_private_t *stream, opj_event_mgr_t * p_manager ) { opj_jp2_box_t box; OPJ_UINT32 l_nb_bytes_read; const opj_jp2_header_handler_t * l_current_handler; const opj_jp2_header_handler_t * l_current_handler_misplaced; OPJ_UINT32 l_last_data_size = OPJ_BOX_SIZE; OPJ_UINT32 l_current_data_size; OPJ_BYTE * l_current_data = 00; /* preconditions */ assert(stream != 00); assert(jp2 != 00); assert(p_manager != 00); l_current_data = (OPJ_BYTE*)opj_calloc(1, l_last_data_size); if (l_current_data == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle jpeg2000 file header\n"); return OPJ_FALSE; } while (opj_jp2_read_boxhdr(&box, &l_nb_bytes_read, stream, p_manager)) { /* is it the codestream box ? */ if (box.type == JP2_JP2C) { if (jp2->jp2_state & JP2_STATE_HEADER) { jp2->jp2_state |= JP2_STATE_CODESTREAM; opj_free(l_current_data); return OPJ_TRUE; } else { opj_event_msg(p_manager, EVT_ERROR, "bad placed jpeg codestream\n"); opj_free(l_current_data); return OPJ_FALSE; } } else if (box.length == 0) { opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n"); opj_free(l_current_data); return OPJ_FALSE; } /* testcase 1851.pdf.SIGSEGV.ce9.948 */ else if (box.length < l_nb_bytes_read) { opj_event_msg(p_manager, EVT_ERROR, "invalid box size %d (%x)\n", box.length, box.type); opj_free(l_current_data); return OPJ_FALSE; } l_current_handler = opj_jp2_find_handler(box.type); l_current_handler_misplaced = opj_jp2_img_find_handler(box.type); l_current_data_size = box.length - l_nb_bytes_read; if ((l_current_handler != 00) || (l_current_handler_misplaced != 00)) { if (l_current_handler == 00) { opj_event_msg(p_manager, EVT_WARNING, "Found a misplaced '%c%c%c%c' box outside jp2h box\n", (OPJ_BYTE)(box.type >> 24), (OPJ_BYTE)(box.type >> 16), (OPJ_BYTE)(box.type >> 8), (OPJ_BYTE)(box.type >> 0)); if (jp2->jp2_state & JP2_STATE_HEADER) { /* read anyway, we already have jp2h */ l_current_handler = l_current_handler_misplaced; } else { opj_event_msg(p_manager, EVT_WARNING, "JPEG2000 Header box not read yet, '%c%c%c%c' box will be ignored\n", (OPJ_BYTE)(box.type >> 24), (OPJ_BYTE)(box.type >> 16), (OPJ_BYTE)(box.type >> 8), (OPJ_BYTE)(box.type >> 0)); jp2->jp2_state |= JP2_STATE_UNKNOWN; if (opj_stream_skip(stream, l_current_data_size, p_manager) != l_current_data_size) { opj_event_msg(p_manager, EVT_ERROR, "Problem with skipping JPEG2000 box, stream error\n"); opj_free(l_current_data); return OPJ_FALSE; } continue; } } if ((OPJ_OFF_T)l_current_data_size > opj_stream_get_number_byte_left(stream)) { /* do not even try to malloc if we can't read */ opj_event_msg(p_manager, EVT_ERROR, "Invalid box size %d for box '%c%c%c%c'. Need %d bytes, %d bytes remaining \n", box.length, (OPJ_BYTE)(box.type >> 24), (OPJ_BYTE)(box.type >> 16), (OPJ_BYTE)(box.type >> 8), (OPJ_BYTE)(box.type >> 0), l_current_data_size, (OPJ_UINT32)opj_stream_get_number_byte_left(stream)); opj_free(l_current_data); return OPJ_FALSE; } if (l_current_data_size > l_last_data_size) { OPJ_BYTE* new_current_data = (OPJ_BYTE*)opj_realloc(l_current_data, l_current_data_size); if (!new_current_data) { opj_free(l_current_data); opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle jpeg2000 box\n"); return OPJ_FALSE; } l_current_data = new_current_data; l_last_data_size = l_current_data_size; } l_nb_bytes_read = (OPJ_UINT32)opj_stream_read_data(stream, l_current_data, l_current_data_size, p_manager); if (l_nb_bytes_read != l_current_data_size) { opj_event_msg(p_manager, EVT_ERROR, "Problem with reading JPEG2000 box, stream error\n"); opj_free(l_current_data); return OPJ_FALSE; } if (! l_current_handler->handler(jp2, l_current_data, l_current_data_size, p_manager)) { opj_free(l_current_data); return OPJ_FALSE; } } else { if (!(jp2->jp2_state & JP2_STATE_SIGNATURE)) { opj_event_msg(p_manager, EVT_ERROR, "Malformed JP2 file format: first box must be JPEG 2000 signature box\n"); opj_free(l_current_data); return OPJ_FALSE; } if (!(jp2->jp2_state & JP2_STATE_FILE_TYPE)) { opj_event_msg(p_manager, EVT_ERROR, "Malformed JP2 file format: second box must be file type box\n"); opj_free(l_current_data); return OPJ_FALSE; } jp2->jp2_state |= JP2_STATE_UNKNOWN; if (opj_stream_skip(stream, l_current_data_size, p_manager) != l_current_data_size) { if (jp2->jp2_state & JP2_STATE_CODESTREAM) { /* If we already read the codestream, do not error out */ /* Needed for data/input/nonregression/issue254.jp2 */ opj_event_msg(p_manager, EVT_WARNING, "Problem with skipping JPEG2000 box, stream error\n"); opj_free(l_current_data); return OPJ_TRUE; } else { opj_event_msg(p_manager, EVT_ERROR, "Problem with skipping JPEG2000 box, stream error\n"); opj_free(l_current_data); return OPJ_FALSE; } } } } opj_free(l_current_data); return OPJ_TRUE; } /** * Executes the given procedures on the given codec. * * @param p_procedure_list the list of procedures to execute * @param jp2 the jpeg2000 file codec to execute the procedures on. * @param stream the stream to execute the procedures on. * @param p_manager the user manager. * * @return true if all the procedures were successfully executed. */ static OPJ_BOOL opj_jp2_exec(opj_jp2_t * jp2, opj_procedure_list_t * p_procedure_list, opj_stream_private_t *stream, opj_event_mgr_t * p_manager ) { OPJ_BOOL(** l_procedure)(opj_jp2_t * jp2, opj_stream_private_t *, opj_event_mgr_t *) = 00; OPJ_BOOL l_result = OPJ_TRUE; OPJ_UINT32 l_nb_proc, i; /* preconditions */ assert(p_procedure_list != 00); assert(jp2 != 00); assert(stream != 00); assert(p_manager != 00); l_nb_proc = opj_procedure_list_get_nb_procedures(p_procedure_list); l_procedure = (OPJ_BOOL(**)(opj_jp2_t * jp2, opj_stream_private_t *, opj_event_mgr_t *)) opj_procedure_list_get_first_procedure(p_procedure_list); for (i = 0; i < l_nb_proc; ++i) { l_result = l_result && (*l_procedure)(jp2, stream, p_manager); ++l_procedure; } /* and clear the procedure list at the end. */ opj_procedure_list_clear(p_procedure_list); return l_result; } OPJ_BOOL opj_jp2_start_compress(opj_jp2_t *jp2, opj_stream_private_t *stream, opj_image_t * p_image, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(jp2 != 00); assert(stream != 00); assert(p_manager != 00); /* customization of the validation */ if (! opj_jp2_setup_encoding_validation(jp2, p_manager)) { return OPJ_FALSE; } /* validation of the parameters codec */ if (! opj_jp2_exec(jp2, jp2->m_validation_list, stream, p_manager)) { return OPJ_FALSE; } /* customization of the encoding */ if (! opj_jp2_setup_header_writing(jp2, p_manager)) { return OPJ_FALSE; } /* write header */ if (! opj_jp2_exec(jp2, jp2->m_procedure_list, stream, p_manager)) { return OPJ_FALSE; } return opj_j2k_start_compress(jp2->j2k, stream, p_image, p_manager); } static const opj_jp2_header_handler_t * opj_jp2_find_handler(OPJ_UINT32 p_id) { OPJ_UINT32 i, l_handler_size = sizeof(jp2_header) / sizeof( opj_jp2_header_handler_t); for (i = 0; i < l_handler_size; ++i) { if (jp2_header[i].id == p_id) { return &jp2_header[i]; } } return NULL; } /** * Finds the image execution function related to the given box id. * * @param p_id the id of the handler to fetch. * * @return the given handler or 00 if it could not be found. */ static const opj_jp2_header_handler_t * opj_jp2_img_find_handler( OPJ_UINT32 p_id) { OPJ_UINT32 i, l_handler_size = sizeof(jp2_img_header) / sizeof( opj_jp2_header_handler_t); for (i = 0; i < l_handler_size; ++i) { if (jp2_img_header[i].id == p_id) { return &jp2_img_header[i]; } } return NULL; } /** * Reads a jpeg2000 file signature box. * * @param p_header_data the data contained in the signature box. * @param jp2 the jpeg2000 file codec. * @param p_header_size the size of the data contained in the signature box. * @param p_manager the user event manager. * * @return true if the file signature box is valid. */ static OPJ_BOOL opj_jp2_read_jp(opj_jp2_t *jp2, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_magic_number; /* preconditions */ assert(p_header_data != 00); assert(jp2 != 00); assert(p_manager != 00); if (jp2->jp2_state != JP2_STATE_NONE) { opj_event_msg(p_manager, EVT_ERROR, "The signature box must be the first box in the file.\n"); return OPJ_FALSE; } /* assure length of data is correct (4 -> magic number) */ if (p_header_size != 4) { opj_event_msg(p_manager, EVT_ERROR, "Error with JP signature Box size\n"); return OPJ_FALSE; } /* rearrange data */ opj_read_bytes(p_header_data, &l_magic_number, 4); if (l_magic_number != 0x0d0a870a) { opj_event_msg(p_manager, EVT_ERROR, "Error with JP Signature : bad magic number\n"); return OPJ_FALSE; } jp2->jp2_state |= JP2_STATE_SIGNATURE; return OPJ_TRUE; } /** * Reads a a FTYP box - File type box * * @param p_header_data the data contained in the FTYP box. * @param jp2 the jpeg2000 file codec. * @param p_header_size the size of the data contained in the FTYP box. * @param p_manager the user event manager. * * @return true if the FTYP box is valid. */ static OPJ_BOOL opj_jp2_read_ftyp(opj_jp2_t *jp2, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 i, l_remaining_bytes; /* preconditions */ assert(p_header_data != 00); assert(jp2 != 00); assert(p_manager != 00); if (jp2->jp2_state != JP2_STATE_SIGNATURE) { opj_event_msg(p_manager, EVT_ERROR, "The ftyp box must be the second box in the file.\n"); return OPJ_FALSE; } /* assure length of data is correct */ if (p_header_size < 8) { opj_event_msg(p_manager, EVT_ERROR, "Error with FTYP signature Box size\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &jp2->brand, 4); /* BR */ p_header_data += 4; opj_read_bytes(p_header_data, &jp2->minversion, 4); /* MinV */ p_header_data += 4; l_remaining_bytes = p_header_size - 8; /* the number of remaining bytes should be a multiple of 4 */ if ((l_remaining_bytes & 0x3) != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error with FTYP signature Box size\n"); return OPJ_FALSE; } /* div by 4 */ jp2->numcl = l_remaining_bytes >> 2; if (jp2->numcl) { jp2->cl = (OPJ_UINT32 *) opj_calloc(jp2->numcl, sizeof(OPJ_UINT32)); if (jp2->cl == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory with FTYP Box\n"); return OPJ_FALSE; } } for (i = 0; i < jp2->numcl; ++i) { opj_read_bytes(p_header_data, &jp2->cl[i], 4); /* CLi */ p_header_data += 4; } jp2->jp2_state |= JP2_STATE_FILE_TYPE; return OPJ_TRUE; } static OPJ_BOOL opj_jp2_skip_jp2c(opj_jp2_t *jp2, opj_stream_private_t *stream, opj_event_mgr_t * p_manager) { /* preconditions */ assert(jp2 != 00); assert(stream != 00); assert(p_manager != 00); jp2->j2k_codestream_offset = opj_stream_tell(stream); if (opj_stream_skip(stream, 8, p_manager) != 8) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_jpip_skip_iptr(opj_jp2_t *jp2, opj_stream_private_t *stream, opj_event_mgr_t * p_manager) { /* preconditions */ assert(jp2 != 00); assert(stream != 00); assert(p_manager != 00); jp2->jpip_iptr_offset = opj_stream_tell(stream); if (opj_stream_skip(stream, 24, p_manager) != 24) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads the Jpeg2000 file Header box - JP2 Header box (warning, this is a super box). * * @param p_header_data the data contained in the file header box. * @param jp2 the jpeg2000 file codec. * @param p_header_size the size of the data contained in the file header box. * @param p_manager the user event manager. * * @return true if the JP2 Header box was successfully recognized. */ static OPJ_BOOL opj_jp2_read_jp2h(opj_jp2_t *jp2, OPJ_BYTE *p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_box_size = 0, l_current_data_size = 0; opj_jp2_box_t box; const opj_jp2_header_handler_t * l_current_handler; OPJ_BOOL l_has_ihdr = 0; /* preconditions */ assert(p_header_data != 00); assert(jp2 != 00); assert(p_manager != 00); /* make sure the box is well placed */ if ((jp2->jp2_state & JP2_STATE_FILE_TYPE) != JP2_STATE_FILE_TYPE) { opj_event_msg(p_manager, EVT_ERROR, "The box must be the first box in the file.\n"); return OPJ_FALSE; } jp2->jp2_img_state = JP2_IMG_STATE_NONE; /* iterate while remaining data */ while (p_header_size > 0) { if (! opj_jp2_read_boxhdr_char(&box, p_header_data, &l_box_size, p_header_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Stream error while reading JP2 Header box\n"); return OPJ_FALSE; } if (box.length > p_header_size) { opj_event_msg(p_manager, EVT_ERROR, "Stream error while reading JP2 Header box: box length is inconsistent.\n"); return OPJ_FALSE; } l_current_handler = opj_jp2_img_find_handler(box.type); l_current_data_size = box.length - l_box_size; p_header_data += l_box_size; if (l_current_handler != 00) { if (! l_current_handler->handler(jp2, p_header_data, l_current_data_size, p_manager)) { return OPJ_FALSE; } } else { jp2->jp2_img_state |= JP2_IMG_STATE_UNKNOWN; } if (box.type == JP2_IHDR) { l_has_ihdr = 1; } p_header_data += l_current_data_size; p_header_size -= box.length; } if (l_has_ihdr == 0) { opj_event_msg(p_manager, EVT_ERROR, "Stream error while reading JP2 Header box: no 'ihdr' box.\n"); return OPJ_FALSE; } jp2->jp2_state |= JP2_STATE_HEADER; jp2->has_jp2h = 1; return OPJ_TRUE; } static OPJ_BOOL opj_jp2_read_boxhdr_char(opj_jp2_box_t *box, OPJ_BYTE * p_data, OPJ_UINT32 * p_number_bytes_read, OPJ_UINT32 p_box_max_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_value; /* preconditions */ assert(p_data != 00); assert(box != 00); assert(p_number_bytes_read != 00); assert(p_manager != 00); if (p_box_max_size < 8) { opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box of less than 8 bytes\n"); return OPJ_FALSE; } /* process read data */ opj_read_bytes(p_data, &l_value, 4); p_data += 4; box->length = (OPJ_UINT32)(l_value); opj_read_bytes(p_data, &l_value, 4); p_data += 4; box->type = (OPJ_UINT32)(l_value); *p_number_bytes_read = 8; /* do we have a "special very large box ?" */ /* read then the XLBox */ if (box->length == 1) { OPJ_UINT32 l_xl_part_size; if (p_box_max_size < 16) { opj_event_msg(p_manager, EVT_ERROR, "Cannot handle XL box of less than 16 bytes\n"); return OPJ_FALSE; } opj_read_bytes(p_data, &l_xl_part_size, 4); p_data += 4; *p_number_bytes_read += 4; if (l_xl_part_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n"); return OPJ_FALSE; } opj_read_bytes(p_data, &l_value, 4); *p_number_bytes_read += 4; box->length = (OPJ_UINT32)(l_value); if (box->length == 0) { opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n"); return OPJ_FALSE; } } else if (box->length == 0) { opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n"); return OPJ_FALSE; } if (box->length < *p_number_bytes_read) { opj_event_msg(p_manager, EVT_ERROR, "Box length is inconsistent.\n"); return OPJ_FALSE; } return OPJ_TRUE; } OPJ_BOOL opj_jp2_read_header(opj_stream_private_t *p_stream, opj_jp2_t *jp2, opj_image_t ** p_image, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(jp2 != 00); assert(p_stream != 00); assert(p_manager != 00); /* customization of the validation */ if (! opj_jp2_setup_decoding_validation(jp2, p_manager)) { return OPJ_FALSE; } /* customization of the encoding */ if (! opj_jp2_setup_header_reading(jp2, p_manager)) { return OPJ_FALSE; } /* validation of the parameters codec */ if (! opj_jp2_exec(jp2, jp2->m_validation_list, p_stream, p_manager)) { return OPJ_FALSE; } /* read header */ if (! opj_jp2_exec(jp2, jp2->m_procedure_list, p_stream, p_manager)) { return OPJ_FALSE; } if (jp2->has_jp2h == 0) { opj_event_msg(p_manager, EVT_ERROR, "JP2H box missing. Required.\n"); return OPJ_FALSE; } if (jp2->has_ihdr == 0) { opj_event_msg(p_manager, EVT_ERROR, "IHDR box_missing. Required.\n"); return OPJ_FALSE; } return opj_j2k_read_header(p_stream, jp2->j2k, p_image, p_manager); } static OPJ_BOOL opj_jp2_setup_encoding_validation(opj_jp2_t *jp2, opj_event_mgr_t * p_manager) { /* preconditions */ assert(jp2 != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(jp2->m_validation_list, (opj_procedure)opj_jp2_default_validation, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, add your custom validation procedure */ return OPJ_TRUE; } static OPJ_BOOL opj_jp2_setup_decoding_validation(opj_jp2_t *jp2, opj_event_mgr_t * p_manager) { /* preconditions */ assert(jp2 != 00); assert(p_manager != 00); OPJ_UNUSED(jp2); OPJ_UNUSED(p_manager); /* DEVELOPER CORNER, add your custom validation procedure */ return OPJ_TRUE; } static OPJ_BOOL opj_jp2_setup_header_writing(opj_jp2_t *jp2, opj_event_mgr_t * p_manager) { /* preconditions */ assert(jp2 != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(jp2->m_procedure_list, (opj_procedure)opj_jp2_write_jp, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(jp2->m_procedure_list, (opj_procedure)opj_jp2_write_ftyp, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(jp2->m_procedure_list, (opj_procedure)opj_jp2_write_jp2h, p_manager)) { return OPJ_FALSE; } if (jp2->jpip_on) { if (! opj_procedure_list_add_procedure(jp2->m_procedure_list, (opj_procedure)opj_jpip_skip_iptr, p_manager)) { return OPJ_FALSE; } } if (! opj_procedure_list_add_procedure(jp2->m_procedure_list, (opj_procedure)opj_jp2_skip_jp2c, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, insert your custom procedures */ return OPJ_TRUE; } static OPJ_BOOL opj_jp2_setup_header_reading(opj_jp2_t *jp2, opj_event_mgr_t * p_manager) { /* preconditions */ assert(jp2 != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(jp2->m_procedure_list, (opj_procedure)opj_jp2_read_header_procedure, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, add your custom procedures */ return OPJ_TRUE; } OPJ_BOOL opj_jp2_read_tile_header(opj_jp2_t * p_jp2, OPJ_UINT32 * p_tile_index, OPJ_UINT32 * p_data_size, OPJ_INT32 * p_tile_x0, OPJ_INT32 * p_tile_y0, OPJ_INT32 * p_tile_x1, OPJ_INT32 * p_tile_y1, OPJ_UINT32 * p_nb_comps, OPJ_BOOL * p_go_on, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { return opj_j2k_read_tile_header(p_jp2->j2k, p_tile_index, p_data_size, p_tile_x0, p_tile_y0, p_tile_x1, p_tile_y1, p_nb_comps, p_go_on, p_stream, p_manager); } OPJ_BOOL opj_jp2_write_tile(opj_jp2_t *p_jp2, OPJ_UINT32 p_tile_index, OPJ_BYTE * p_data, OPJ_UINT32 p_data_size, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { return opj_j2k_write_tile(p_jp2->j2k, p_tile_index, p_data, p_data_size, p_stream, p_manager); } OPJ_BOOL opj_jp2_decode_tile(opj_jp2_t * p_jp2, OPJ_UINT32 p_tile_index, OPJ_BYTE * p_data, OPJ_UINT32 p_data_size, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { return opj_j2k_decode_tile(p_jp2->j2k, p_tile_index, p_data, p_data_size, p_stream, p_manager); } void opj_jp2_destroy(opj_jp2_t *jp2) { if (jp2) { /* destroy the J2K codec */ opj_j2k_destroy(jp2->j2k); jp2->j2k = 00; if (jp2->comps) { opj_free(jp2->comps); jp2->comps = 00; } if (jp2->cl) { opj_free(jp2->cl); jp2->cl = 00; } if (jp2->color.icc_profile_buf) { opj_free(jp2->color.icc_profile_buf); jp2->color.icc_profile_buf = 00; } if (jp2->color.jp2_cdef) { if (jp2->color.jp2_cdef->info) { opj_free(jp2->color.jp2_cdef->info); jp2->color.jp2_cdef->info = NULL; } opj_free(jp2->color.jp2_cdef); jp2->color.jp2_cdef = 00; } if (jp2->color.jp2_pclr) { if (jp2->color.jp2_pclr->cmap) { opj_free(jp2->color.jp2_pclr->cmap); jp2->color.jp2_pclr->cmap = NULL; } if (jp2->color.jp2_pclr->channel_sign) { opj_free(jp2->color.jp2_pclr->channel_sign); jp2->color.jp2_pclr->channel_sign = NULL; } if (jp2->color.jp2_pclr->channel_size) { opj_free(jp2->color.jp2_pclr->channel_size); jp2->color.jp2_pclr->channel_size = NULL; } if (jp2->color.jp2_pclr->entries) { opj_free(jp2->color.jp2_pclr->entries); jp2->color.jp2_pclr->entries = NULL; } opj_free(jp2->color.jp2_pclr); jp2->color.jp2_pclr = 00; } if (jp2->m_validation_list) { opj_procedure_list_destroy(jp2->m_validation_list); jp2->m_validation_list = 00; } if (jp2->m_procedure_list) { opj_procedure_list_destroy(jp2->m_procedure_list); jp2->m_procedure_list = 00; } opj_free(jp2); } } OPJ_BOOL opj_jp2_set_decoded_components(opj_jp2_t *p_jp2, OPJ_UINT32 numcomps, const OPJ_UINT32* comps_indices, opj_event_mgr_t * p_manager) { return opj_j2k_set_decoded_components(p_jp2->j2k, numcomps, comps_indices, p_manager); } OPJ_BOOL opj_jp2_set_decode_area(opj_jp2_t *p_jp2, opj_image_t* p_image, OPJ_INT32 p_start_x, OPJ_INT32 p_start_y, OPJ_INT32 p_end_x, OPJ_INT32 p_end_y, opj_event_mgr_t * p_manager ) { return opj_j2k_set_decode_area(p_jp2->j2k, p_image, p_start_x, p_start_y, p_end_x, p_end_y, p_manager); } OPJ_BOOL opj_jp2_get_tile(opj_jp2_t *p_jp2, opj_stream_private_t *p_stream, opj_image_t* p_image, opj_event_mgr_t * p_manager, OPJ_UINT32 tile_index ) { if (!p_image) { return OPJ_FALSE; } opj_event_msg(p_manager, EVT_WARNING, "JP2 box which are after the codestream will not be read by this function.\n"); if (! opj_j2k_get_tile(p_jp2->j2k, p_stream, p_image, p_manager, tile_index)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to decode the codestream in the JP2 file\n"); return OPJ_FALSE; } if (p_jp2->j2k->m_specific_param.m_decoder.m_numcomps_to_decode) { /* Bypass all JP2 component transforms */ return OPJ_TRUE; } if (!opj_jp2_check_color(p_image, &(p_jp2->color), p_manager)) { return OPJ_FALSE; } /* Set Image Color Space */ if (p_jp2->enumcs == 16) { p_image->color_space = OPJ_CLRSPC_SRGB; } else if (p_jp2->enumcs == 17) { p_image->color_space = OPJ_CLRSPC_GRAY; } else if (p_jp2->enumcs == 18) { p_image->color_space = OPJ_CLRSPC_SYCC; } else if (p_jp2->enumcs == 24) { p_image->color_space = OPJ_CLRSPC_EYCC; } else if (p_jp2->enumcs == 12) { p_image->color_space = OPJ_CLRSPC_CMYK; } else { p_image->color_space = OPJ_CLRSPC_UNKNOWN; } if (p_jp2->color.jp2_pclr) { /* Part 1, I.5.3.4: Either both or none : */ if (!p_jp2->color.jp2_pclr->cmap) { opj_jp2_free_pclr(&(p_jp2->color)); } else { if (!opj_jp2_apply_pclr(p_image, &(p_jp2->color), p_manager)) { return OPJ_FALSE; } } } /* Apply the color space if needed */ if (p_jp2->color.jp2_cdef) { opj_jp2_apply_cdef(p_image, &(p_jp2->color), p_manager); } if (p_jp2->color.icc_profile_buf) { p_image->icc_profile_buf = p_jp2->color.icc_profile_buf; p_image->icc_profile_len = p_jp2->color.icc_profile_len; p_jp2->color.icc_profile_buf = NULL; } return OPJ_TRUE; } /* ----------------------------------------------------------------------- */ /* JP2 encoder interface */ /* ----------------------------------------------------------------------- */ opj_jp2_t* opj_jp2_create(OPJ_BOOL p_is_decoder) { opj_jp2_t *jp2 = (opj_jp2_t*)opj_calloc(1, sizeof(opj_jp2_t)); if (jp2) { /* create the J2K codec */ if (! p_is_decoder) { jp2->j2k = opj_j2k_create_compress(); } else { jp2->j2k = opj_j2k_create_decompress(); } if (jp2->j2k == 00) { opj_jp2_destroy(jp2); return 00; } /* Color structure */ jp2->color.icc_profile_buf = NULL; jp2->color.icc_profile_len = 0; jp2->color.jp2_cdef = NULL; jp2->color.jp2_pclr = NULL; jp2->color.jp2_has_colr = 0; /* validation list creation */ jp2->m_validation_list = opj_procedure_list_create(); if (! jp2->m_validation_list) { opj_jp2_destroy(jp2); return 00; } /* execution list creation */ jp2->m_procedure_list = opj_procedure_list_create(); if (! jp2->m_procedure_list) { opj_jp2_destroy(jp2); return 00; } } return jp2; } void jp2_dump(opj_jp2_t* p_jp2, OPJ_INT32 flag, FILE* out_stream) { /* preconditions */ assert(p_jp2 != 00); j2k_dump(p_jp2->j2k, flag, out_stream); } opj_codestream_index_t* jp2_get_cstr_index(opj_jp2_t* p_jp2) { return j2k_get_cstr_index(p_jp2->j2k); } opj_codestream_info_v2_t* jp2_get_cstr_info(opj_jp2_t* p_jp2) { return j2k_get_cstr_info(p_jp2->j2k); } OPJ_BOOL opj_jp2_set_decoded_resolution_factor(opj_jp2_t *p_jp2, OPJ_UINT32 res_factor, opj_event_mgr_t * p_manager) { return opj_j2k_set_decoded_resolution_factor(p_jp2->j2k, res_factor, p_manager); } /* ----------------------------------------------------------------------- */ OPJ_BOOL opj_jp2_encoder_set_extra_options( opj_jp2_t *p_jp2, const char* const* p_options, opj_event_mgr_t * p_manager) { return opj_j2k_encoder_set_extra_options(p_jp2->j2k, p_options, p_manager); } /* ----------------------------------------------------------------------- */ /* JPIP specific */ #ifdef USE_JPIP static OPJ_BOOL opj_jpip_write_iptr(opj_jp2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager) { OPJ_OFF_T j2k_codestream_exit; OPJ_BYTE l_data_header [24]; /* preconditions */ assert(jp2 != 00); assert(cio != 00); assert(p_manager != 00); assert(opj_stream_has_seek(cio)); j2k_codestream_exit = opj_stream_tell(cio); opj_write_bytes(l_data_header, 24, 4); /* size of iptr */ opj_write_bytes(l_data_header + 4, JPIP_IPTR, 4); /* IPTR */ #if 0 opj_write_bytes(l_data_header + 4 + 4, 0, 8); /* offset */ opj_write_bytes(l_data_header + 8 + 8, 0, 8); /* length */ #else opj_write_double(l_data_header + 4 + 4, 0); /* offset */ opj_write_double(l_data_header + 8 + 8, 0); /* length */ #endif if (! opj_stream_seek(cio, jp2->jpip_iptr_offset, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n"); return OPJ_FALSE; } if (opj_stream_write_data(cio, l_data_header, 24, p_manager) != 24) { opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n"); return OPJ_FALSE; } if (! opj_stream_seek(cio, j2k_codestream_exit, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n"); return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_jpip_write_fidx(opj_jp2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager) { OPJ_OFF_T j2k_codestream_exit; OPJ_BYTE l_data_header [24]; OPJ_UNUSED(jp2); /* preconditions */ assert(jp2 != 00); assert(cio != 00); assert(p_manager != 00); assert(opj_stream_has_seek(cio)); opj_write_bytes(l_data_header, 24, 4); /* size of iptr */ opj_write_bytes(l_data_header + 4, JPIP_FIDX, 4); /* IPTR */ opj_write_double(l_data_header + 4 + 4, 0); /* offset */ opj_write_double(l_data_header + 8 + 8, 0); /* length */ if (opj_stream_write_data(cio, l_data_header, 24, p_manager) != 24) { opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n"); return OPJ_FALSE; } j2k_codestream_exit = opj_stream_tell(cio); if (! opj_stream_seek(cio, j2k_codestream_exit, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n"); return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_jpip_write_cidx(opj_jp2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager) { OPJ_OFF_T j2k_codestream_exit; OPJ_BYTE l_data_header [24]; OPJ_UNUSED(jp2); /* preconditions */ assert(jp2 != 00); assert(cio != 00); assert(p_manager != 00); assert(opj_stream_has_seek(cio)); j2k_codestream_exit = opj_stream_tell(cio); opj_write_bytes(l_data_header, 24, 4); /* size of iptr */ opj_write_bytes(l_data_header + 4, JPIP_CIDX, 4); /* IPTR */ #if 0 opj_write_bytes(l_data_header + 4 + 4, 0, 8); /* offset */ opj_write_bytes(l_data_header + 8 + 8, 0, 8); /* length */ #else opj_write_double(l_data_header + 4 + 4, 0); /* offset */ opj_write_double(l_data_header + 8 + 8, 0); /* length */ #endif if (! opj_stream_seek(cio, j2k_codestream_exit, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n"); return OPJ_FALSE; } if (opj_stream_write_data(cio, l_data_header, 24, p_manager) != 24) { opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n"); return OPJ_FALSE; } j2k_codestream_exit = opj_stream_tell(cio); if (! opj_stream_seek(cio, j2k_codestream_exit, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n"); return OPJ_FALSE; } return OPJ_TRUE; } #if 0 static void write_prxy(int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_stream_private_t *cio, opj_event_mgr_t * p_manager) { OPJ_BYTE l_data_header [8]; OPJ_OFF_T len, lenp; lenp = opj_stream_tell(cio); opj_stream_skip(cio, 4, p_manager); /* L [at the end] */ opj_write_bytes(l_data_header, JPIP_PRXY, 4); /* IPTR */ opj_stream_write_data(cio, l_data_header, 4, p_manager); opj_write_bytes(l_data_header, offset_jp2c, 8); /* OOFF */ opj_stream_write_data(cio, l_data_header, 8, p_manager); opj_write_bytes(l_data_header, length_jp2c, 4); /* OBH part 1 */ opj_write_bytes(l_data_header + 4, JP2_JP2C, 4); /* OBH part 2 */ opj_stream_write_data(cio, l_data_header, 8, p_manager); opj_write_bytes(l_data_header, 1, 1); /* NI */ opj_stream_write_data(cio, l_data_header, 1, p_manager); opj_write_bytes(l_data_header, offset_idx, 8); /* IOFF */ opj_stream_write_data(cio, l_data_header, 8, p_manager); opj_write_bytes(l_data_header, length_idx, 4); /* IBH part 1 */ opj_write_bytes(l_data_header + 4, JPIP_CIDX, 4); /* IBH part 2 */ opj_stream_write_data(cio, l_data_header, 8, p_manager); len = opj_stream_tell(cio) - lenp; opj_stream_skip(cio, lenp, p_manager); opj_write_bytes(l_data_header, len, 4); /* L */ opj_stream_write_data(cio, l_data_header, 4, p_manager); opj_stream_seek(cio, lenp + len, p_manager); } #endif #if 0 static int write_fidx(int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_stream_private_t *cio, opj_event_mgr_t * p_manager) { OPJ_BYTE l_data_header [4]; OPJ_OFF_T len, lenp; lenp = opj_stream_tell(cio); opj_stream_skip(cio, 4, p_manager); opj_write_bytes(l_data_header, JPIP_FIDX, 4); /* FIDX */ opj_stream_write_data(cio, l_data_header, 4, p_manager); write_prxy(offset_jp2c, length_jp2c, offset_idx, length_idx, cio, p_manager); len = opj_stream_tell(cio) - lenp; opj_stream_skip(cio, lenp, p_manager); opj_write_bytes(l_data_header, len, 4); /* L */ opj_stream_write_data(cio, l_data_header, 4, p_manager); opj_stream_seek(cio, lenp + len, p_manager); return len; } #endif #endif /* USE_JPIP */
997155dad94374c5c1bf55ad4e4cc7c3da5776ff
1efb2283837c9b70bc6449cec877799e4efa3268
/src/mpid/ch4/shm/posix/eager/iqueue/iqueue_noinline.h
1d232fbde554190bf5e22315e4d21e8fd98cd689
[ "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
540
h
iqueue_noinline.h
/* * Copyright (C) by Argonne National Laboratory * See COPYRIGHT in top-level directory */ #ifndef POSIX_EAGER_IQUEUE_NOINLINE_H_INCLUDED #define POSIX_EAGER_IQUEUE_NOINLINE_H_INCLUDED #include "iqueue_types.h" #include "iqueue_impl.h" int MPIDI_POSIX_iqueue_init(int rank, int size); int MPIDI_POSIX_iqueue_finalize(void); #ifdef POSIX_EAGER_INLINE #define MPIDI_POSIX_eager_init MPIDI_POSIX_iqueue_init #define MPIDI_POSIX_eager_finalize MPIDI_POSIX_iqueue_finalize #endif #endif /* POSIX_EAGER_IQUEUE_NOINLINE_H_INCLUDED */
20642fe7d554d76dffbddb81a7e2f7956597ad6f
3d144a23e67c839a4df1c073c6a2c842508f16b2
/test/Sema/Inputs/has_symbol/has_symbol_helper_clang.h
0e9f034364ae3cd3fd55a4c62fd21cfa23ce00f8
[ "Apache-2.0", "Swift-exception" ]
permissive
apple/swift
c2724e388959f6623cf6e4ad6dc1cdd875fd0592
98ada1b200a43d090311b72eb45fe8ecebc97f81
refs/heads/main
2023-08-16T10:48:25.985330
2023-08-16T09:00:42
2023-08-16T09:00:42
44,838,949
78,897
15,074
Apache-2.0
2023-09-14T21:19:23
2015-10-23T21:15:07
C++
UTF-8
C
false
false
226
h
has_symbol_helper_clang.h
// NOTE: This header is used on platforms that do not support Obj-C. extern void clangFunc(int x); extern int clangGlobalVar; struct ClangStruct { int x; }; #define CONSTANT_MACRO 42 enum ClangEnum { ClangEnumMember = 0 };
e27bb7cf6c3f4af6332f5dd8af33cce667ceacb0
7f62590ea2397fe0804e22a6d35ea00beaa111c8
/YubiKit/YubiKit/SPMHeaderLinks/YKFAccessoryDescription+Private.h
872b80793d09955be4d2854778edf585ac40440a
[ "Apache-2.0" ]
permissive
Yubico/yubikit-ios
2b3e6118bebcdf4b7f980df4b1d7e09650af8f82
02403a2384997c64b84a967c8f587e86fc1e605d
refs/heads/main
2023-05-27T06:40:44.456959
2023-05-25T13:40:34
2023-05-25T13:40:34
191,902,737
179
53
Apache-2.0
2023-05-25T13:40:36
2019-06-14T08:08:13
Objective-C
UTF-8
C
false
false
68
h
YKFAccessoryDescription+Private.h
../Connections/AccessoryConnection/YKFAccessoryDescription+Private.h
9b766b24ef377548919d4f7ebcbc5afb2ca95342
e73547787354afd9b717ea57fe8dd0695d161821
/src/battle/common/stage/area_pra/pra_03.inc.c
cc7e2c2a0ed3f3daa3c20890ba13b863967a1d58
[]
no_license
pmret/papermario
8b514b19653cef8d6145e47499b3636b8c474a37
9774b26d93f1045dd2a67e502b6efc9599fb6c31
refs/heads/main
2023-08-31T07:09:48.951514
2023-08-21T18:07:08
2023-08-21T18:07:08
287,151,133
904
139
null
2023-09-14T02:44:23
2020-08-13T01:22:57
C
UTF-8
C
false
false
491
c
pra_03.inc.c
#include "battle/battle.h" #include "mapfs/pra_bt03_shape.h" #define NAMESPACE A(pra_03) EvtScript N(EVS_PreBattle) = { EVT_CALL(SetSpriteShading, SHADING_NONE) EVT_CALL(SetCamBGColor, CAM_BATTLE, 0, 0, 0) EVT_RETURN EVT_END }; EvtScript N(EVS_PostBattle) = { EVT_RETURN EVT_END }; Stage NAMESPACE = { .texture = "pra_tex", .shape = "pra_bt03_shape", .hit = "pra_bt03_hit", .preBattle = &N(EVS_PreBattle), .postBattle = &N(EVS_PostBattle), };
f1cde166b26ac02d432d578c8fa112d4ef0950ea
9c4ec01e04f7b0a1d213e1060c6b0a008dde7cbd
/series1/usart/gpio_prs_ldma_usart/src/main_s1_gg11.c
4b5d914f78aa28cbffdcb42c4938e749eed8149c
[ "Zlib" ]
permissive
SiliconLabs/peripheral_examples
edf5ee87cd0bcb2e7ad5066e278fa1ad3b92bd35
87b252e5a1bf5b36a548c121e8ffda085d3bcbc4
refs/heads/master
2023-07-26T22:20:57.916375
2023-07-07T18:18:01
2023-07-07T18:20:16
116,865,771
326
212
NOASSERTION
2021-06-17T20:12:04
2018-01-09T20:13:39
C
UTF-8
C
false
false
7,254
c
main_s1_gg11.c
/***************************************************************************//** * @file main_s1_gg11.c * @brief This example demonstrates using LDMA with PRS where USART packet * transfers are triggered every push of Push Button 0. ******************************************************************************* * # License * <b>Copyright 2020 Silicon Laboratories Inc. www.silabs.com</b> ******************************************************************************* * * SPDX-License-Identifier: Zlib * * The licensor of this software is Silicon Laboratories Inc. * * 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. * ******************************************************************************* * # Evaluation Quality * This code has been minimally tested to ensure that it builds and is suitable * as a demonstration for evaluation purposes only. This code will be maintained * at the sole discretion of Silicon Labs. ******************************************************************************/ #include "em_device.h" #include "em_chip.h" #include "em_cmu.h" #include "em_gpio.h" #include "em_usart.h" #include "em_ldma.h" #include "em_prs.h" #include "bsp.h" #define TX_LDMA_CHANNEL 1 #define TXBUFFER_SIZE 7 volatile char TxBuffer[20] = "Hello!\n"; // Descriptor and config for the LDMA operation for sending data static LDMA_TransferCfg_t ldmaTXConfig; static LDMA_Descriptor_t descriptors[4]; /**************************************************************************//** * @brief Initialize descriptors array *****************************************************************************/ void initDescriptors(void) { // Memory to peripheral transfer, Source: TxBuffer, Destination: USART0->TXDATA, Bytes to receive: 1 descriptors[0] = (LDMA_Descriptor_t)LDMA_DESCRIPTOR_LINKREL_M2P_BYTE(TxBuffer, &(USART0->TXDATA), 1, 1); descriptors[0].xfer.doneIfs = 0; // Setting USART0 TXC flag to trigger LDMA transfers using PRS signals descriptors[1] = (LDMA_Descriptor_t)LDMA_DESCRIPTOR_LINKREL_WRITE(((PRS_CH_CTRL_SOURCESEL_USART0 & _PRS_CH_CTRL_SOURCESEL_MASK) | (PRS_CH_CTRL_SIGSEL_USART0TXC & _PRS_CH_CTRL_SIGSEL_MASK) | (uint32_t)prsEdgePos << _PRS_CH_CTRL_EDSEL_SHIFT), &PRS->CH[0].CTRL, 1); // Memory to peripheral transfer, Source: TxBuffer, Destination: USART0->TXDATA, Bytes to receive: TXBUFFER_SIZE - 1 descriptors[2] = (LDMA_Descriptor_t)LDMA_DESCRIPTOR_LINKREL_M2P_BYTE(&TxBuffer[1], &(USART0->TXDATA), TXBUFFER_SIZE-1, 0); descriptors[2].xfer.decLoopCnt = 1; // Setting GPIO pin 8 to trigger LDMA transfers using PRS signals again descriptors[3] = (LDMA_Descriptor_t)LDMA_DESCRIPTOR_LINKREL_WRITE(((PRS_CH_CTRL_SOURCESEL_GPIOH & _PRS_CH_CTRL_SOURCESEL_MASK) | (PRS_CH_CTRL_SIGSEL_GPIOPIN8 & _PRS_CH_CTRL_SIGSEL_MASK) | (uint32_t)prsEdgePos << _PRS_CH_CTRL_EDSEL_SHIFT), &PRS->CH[0].CTRL, 1); } /**************************************************************************//** * @brief Initialize USART0 *****************************************************************************/ void initUSART0 (void) { CMU_ClockEnable(cmuClock_GPIO, true); CMU_ClockEnable(cmuClock_USART0, true); // Configure GPIO mode // set pin modes for USART TX and RX pins GPIO_PinModeSet(gpioPortC, 1, gpioModeInput, 0); GPIO_PinModeSet(gpioPortC, 0, gpioModePushPull, 1); // Start with default config USART_InitAsync_TypeDef config = USART_INITASYNC_DEFAULT; // Init USART USART_InitAsync(USART0, &config); // Set USART pin locations USART0->ROUTELOC0 = USART_ROUTELOC0_RXLOC_LOC5 | USART_ROUTELOC0_TXLOC_LOC5; // Enable USART pins USART0->ROUTEPEN |= USART_ROUTEPEN_TXPEN | USART_ROUTEPEN_RXPEN; // Enable push button 0 as input GPIO_PinModeSet(BSP_GPIO_PB0_PORT, BSP_GPIO_PB0_PIN, gpioModeInputPullFilter, 1); // Enable push button 0 to generate interrupt signals so it can supply a signal to our prs // but we turn off all of it's normal interrupt modes to avoid unwanted interrupt triggers GPIO_ExtIntConfig(BSP_GPIO_PB0_PORT, BSP_GPIO_PB0_PIN, BSP_GPIO_PB0_PIN, false, false, false); // Clear pending gpio interrupts NVIC_ClearPendingIRQ(GPIO_EVEN_IRQn); GPIO_IntClear(0x00FF); // Using GPIO pin 8 to trigger LDMA transfers using PRS signals CMU_ClockEnable(cmuClock_PRS, true); PRS_SourceSignalSet(0, PRS_CH_CTRL_SOURCESEL_GPIOH, PRS_CH_CTRL_SIGSEL_GPIOPIN8, prsEdgePos); // Configuring the PRS to send the PRS signal to the LDMA Channel 0 PRS->DMAREQ0 = PRS_DMAREQ0_PRSSEL_PRSCH0; // Enable USART0 USART_Enable(USART0, usartEnable); } /**************************************************************************//** * @IRQ Handler to reset transfers *****************************************************************************/ void LDMA_IRQHandler() { LDMA_StartTransfer(TX_LDMA_CHANNEL, &ldmaTXConfig, &descriptors[0]); LDMA_IntClear(1 << TX_LDMA_CHANNEL); USART_IntClear(USART0, USART_IntGet(USART0)); } /**************************************************************************//** * @Initialize LDMA Descriptors *****************************************************************************/ void initLDMA(void) { CMU_ClockEnable(cmuClock_LDMA, true); LDMA_Init_t ldmaInit = LDMA_INIT_DEFAULT; LDMA_Init(&ldmaInit); // Initializing default LDMA settings // One byte will transfer everytime the USART TXBL flag is high ldmaTXConfig = (LDMA_TransferCfg_t)LDMA_TRANSFER_CFG_PERIPHERAL(ldmaPeripheralSignal_PRS_REQ0); // Starting both ldma transfers are different channels LDMA_StartTransfer(TX_LDMA_CHANNEL, &ldmaTXConfig, &descriptors[0]); } /**************************************************************************//** * @brief Transmitting TxBuffer *****************************************************************************/ void transmitTxBuffer(void) { for(int i = 0; i < TXBUFFER_SIZE; i++) USART_Tx(USART0, TxBuffer[i]); } /**************************************************************************//** * @brief Main function *****************************************************************************/ int main(void) { // Initialize chip CHIP_Init(); // Initialize USART0 as SPI slave initUSART0(); // Initialize descriptors initDescriptors(); // Setup LDMA channels for transfer across SPI initLDMA(); transmitTxBuffer(); while(1); }
6f7c5a13c0319bda73b81c7030f5a084377ced60
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/char/agp/frontend.c
2e044338753cb4d14cef934126ec15f472d09bb2
[ "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
24,472
c
frontend.c
/* * AGPGART driver frontend * Copyright (C) 2004 Silicon Graphics, Inc. * Copyright (C) 2002-2003 Dave Jones * Copyright (C) 1999 Jeff Hartmann * Copyright (C) 1999 Precision Insight, Inc. * Copyright (C) 1999 Xi Graphics, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * JEFF HARTMANN, OR ANY OTHER CONTRIBUTORS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include <linux/types.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/mman.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/miscdevice.h> #include <linux/agp_backend.h> #include <linux/agpgart.h> #include <linux/slab.h> #include <linux/mm.h> #include <linux/fs.h> #include <linux/sched.h> #include <asm/uaccess.h> #include <asm/pgtable.h> #include "agp.h" struct agp_front_data agp_fe; struct agp_memory *agp_find_mem_by_key(int key) { struct agp_memory *curr; if (agp_fe.current_controller == NULL) return NULL; curr = agp_fe.current_controller->pool; while (curr != NULL) { if (curr->key == key) break; curr = curr->next; } DBG("key=%d -> mem=%p", key, curr); return curr; } static void agp_remove_from_pool(struct agp_memory *temp) { struct agp_memory *prev; struct agp_memory *next; /* Check to see if this is even in the memory pool */ DBG("mem=%p", temp); if (agp_find_mem_by_key(temp->key) != NULL) { next = temp->next; prev = temp->prev; if (prev != NULL) { prev->next = next; if (next != NULL) next->prev = prev; } else { /* This is the first item on the list */ if (next != NULL) next->prev = NULL; agp_fe.current_controller->pool = next; } } } /* * Routines for managing each client's segment list - * These routines handle adding and removing segments * to each auth'ed client. */ static struct agp_segment_priv *agp_find_seg_in_client(const struct agp_client *client, unsigned long offset, int size, pgprot_t page_prot) { struct agp_segment_priv *seg; int num_segments, i; off_t pg_start; size_t pg_count; pg_start = offset / 4096; pg_count = size / 4096; seg = *(client->segments); num_segments = client->num_segments; for (i = 0; i < client->num_segments; i++) { if ((seg[i].pg_start == pg_start) && (seg[i].pg_count == pg_count) && (pgprot_val(seg[i].prot) == pgprot_val(page_prot))) { return seg + i; } } return NULL; } static void agp_remove_seg_from_client(struct agp_client *client) { DBG("client=%p", client); if (client->segments != NULL) { if (*(client->segments) != NULL) { DBG("Freeing %p from client %p", *(client->segments), client); kfree(*(client->segments)); } DBG("Freeing %p from client %p", client->segments, client); kfree(client->segments); client->segments = NULL; } } static void agp_add_seg_to_client(struct agp_client *client, struct agp_segment_priv ** seg, int num_segments) { struct agp_segment_priv **prev_seg; prev_seg = client->segments; if (prev_seg != NULL) agp_remove_seg_from_client(client); DBG("Adding seg %p (%d segments) to client %p", seg, num_segments, client); client->num_segments = num_segments; client->segments = seg; } static pgprot_t agp_convert_mmap_flags(int prot) { unsigned long prot_bits; prot_bits = calc_vm_prot_bits(prot) | VM_SHARED; return vm_get_page_prot(prot_bits); } int agp_create_segment(struct agp_client *client, struct agp_region *region) { struct agp_segment_priv **ret_seg; struct agp_segment_priv *seg; struct agp_segment *user_seg; size_t i; seg = kzalloc((sizeof(struct agp_segment_priv) * region->seg_count), GFP_KERNEL); if (seg == NULL) { kfree(region->seg_list); region->seg_list = NULL; return -ENOMEM; } user_seg = region->seg_list; for (i = 0; i < region->seg_count; i++) { seg[i].pg_start = user_seg[i].pg_start; seg[i].pg_count = user_seg[i].pg_count; seg[i].prot = agp_convert_mmap_flags(user_seg[i].prot); } kfree(region->seg_list); region->seg_list = NULL; ret_seg = kmalloc(sizeof(void *), GFP_KERNEL); if (ret_seg == NULL) { kfree(seg); return -ENOMEM; } *ret_seg = seg; agp_add_seg_to_client(client, ret_seg, region->seg_count); return 0; } /* End - Routines for managing each client's segment list */ /* This function must only be called when current_controller != NULL */ static void agp_insert_into_pool(struct agp_memory * temp) { struct agp_memory *prev; prev = agp_fe.current_controller->pool; if (prev != NULL) { prev->prev = temp; temp->next = prev; } agp_fe.current_controller->pool = temp; } /* File private list routines */ struct agp_file_private *agp_find_private(pid_t pid) { struct agp_file_private *curr; curr = agp_fe.file_priv_list; while (curr != NULL) { if (curr->my_pid == pid) return curr; curr = curr->next; } return NULL; } static void agp_insert_file_private(struct agp_file_private * priv) { struct agp_file_private *prev; prev = agp_fe.file_priv_list; if (prev != NULL) prev->prev = priv; priv->next = prev; agp_fe.file_priv_list = priv; } static void agp_remove_file_private(struct agp_file_private * priv) { struct agp_file_private *next; struct agp_file_private *prev; next = priv->next; prev = priv->prev; if (prev != NULL) { prev->next = next; if (next != NULL) next->prev = prev; } else { if (next != NULL) next->prev = NULL; agp_fe.file_priv_list = next; } } /* End - File flag list routines */ /* * Wrappers for agp_free_memory & agp_allocate_memory * These make sure that internal lists are kept updated. */ void agp_free_memory_wrap(struct agp_memory *memory) { agp_remove_from_pool(memory); agp_free_memory(memory); } struct agp_memory *agp_allocate_memory_wrap(size_t pg_count, u32 type) { struct agp_memory *memory; memory = agp_allocate_memory(agp_bridge, pg_count, type); if (memory == NULL) return NULL; agp_insert_into_pool(memory); return memory; } /* Routines for managing the list of controllers - * These routines manage the current controller, and the list of * controllers */ static struct agp_controller *agp_find_controller_by_pid(pid_t id) { struct agp_controller *controller; controller = agp_fe.controllers; while (controller != NULL) { if (controller->pid == id) return controller; controller = controller->next; } return NULL; } static struct agp_controller *agp_create_controller(pid_t id) { struct agp_controller *controller; controller = kzalloc(sizeof(struct agp_controller), GFP_KERNEL); if (controller == NULL) return NULL; controller->pid = id; return controller; } static int agp_insert_controller(struct agp_controller *controller) { struct agp_controller *prev_controller; prev_controller = agp_fe.controllers; controller->next = prev_controller; if (prev_controller != NULL) prev_controller->prev = controller; agp_fe.controllers = controller; return 0; } static void agp_remove_all_clients(struct agp_controller *controller) { struct agp_client *client; struct agp_client *temp; client = controller->clients; while (client) { struct agp_file_private *priv; temp = client; agp_remove_seg_from_client(temp); priv = agp_find_private(temp->pid); if (priv != NULL) { clear_bit(AGP_FF_IS_VALID, &priv->access_flags); clear_bit(AGP_FF_IS_CLIENT, &priv->access_flags); } client = client->next; kfree(temp); } } static void agp_remove_all_memory(struct agp_controller *controller) { struct agp_memory *memory; struct agp_memory *temp; memory = controller->pool; while (memory) { temp = memory; memory = memory->next; agp_free_memory_wrap(temp); } } static int agp_remove_controller(struct agp_controller *controller) { struct agp_controller *prev_controller; struct agp_controller *next_controller; prev_controller = controller->prev; next_controller = controller->next; if (prev_controller != NULL) { prev_controller->next = next_controller; if (next_controller != NULL) next_controller->prev = prev_controller; } else { if (next_controller != NULL) next_controller->prev = NULL; agp_fe.controllers = next_controller; } agp_remove_all_memory(controller); agp_remove_all_clients(controller); if (agp_fe.current_controller == controller) { agp_fe.current_controller = NULL; agp_fe.backend_acquired = false; agp_backend_release(agp_bridge); } kfree(controller); return 0; } static void agp_controller_make_current(struct agp_controller *controller) { struct agp_client *clients; clients = controller->clients; while (clients != NULL) { struct agp_file_private *priv; priv = agp_find_private(clients->pid); if (priv != NULL) { set_bit(AGP_FF_IS_VALID, &priv->access_flags); set_bit(AGP_FF_IS_CLIENT, &priv->access_flags); } clients = clients->next; } agp_fe.current_controller = controller; } static void agp_controller_release_current(struct agp_controller *controller, struct agp_file_private *controller_priv) { struct agp_client *clients; clear_bit(AGP_FF_IS_VALID, &controller_priv->access_flags); clients = controller->clients; while (clients != NULL) { struct agp_file_private *priv; priv = agp_find_private(clients->pid); if (priv != NULL) clear_bit(AGP_FF_IS_VALID, &priv->access_flags); clients = clients->next; } agp_fe.current_controller = NULL; agp_fe.used_by_controller = false; agp_backend_release(agp_bridge); } /* * Routines for managing client lists - * These routines are for managing the list of auth'ed clients. */ static struct agp_client *agp_find_client_in_controller(struct agp_controller *controller, pid_t id) { struct agp_client *client; if (controller == NULL) return NULL; client = controller->clients; while (client != NULL) { if (client->pid == id) return client; client = client->next; } return NULL; } static struct agp_controller *agp_find_controller_for_client(pid_t id) { struct agp_controller *controller; controller = agp_fe.controllers; while (controller != NULL) { if ((agp_find_client_in_controller(controller, id)) != NULL) return controller; controller = controller->next; } return NULL; } struct agp_client *agp_find_client_by_pid(pid_t id) { struct agp_client *temp; if (agp_fe.current_controller == NULL) return NULL; temp = agp_find_client_in_controller(agp_fe.current_controller, id); return temp; } static void agp_insert_client(struct agp_client *client) { struct agp_client *prev_client; prev_client = agp_fe.current_controller->clients; client->next = prev_client; if (prev_client != NULL) prev_client->prev = client; agp_fe.current_controller->clients = client; agp_fe.current_controller->num_clients++; } struct agp_client *agp_create_client(pid_t id) { struct agp_client *new_client; new_client = kzalloc(sizeof(struct agp_client), GFP_KERNEL); if (new_client == NULL) return NULL; new_client->pid = id; agp_insert_client(new_client); return new_client; } int agp_remove_client(pid_t id) { struct agp_client *client; struct agp_client *prev_client; struct agp_client *next_client; struct agp_controller *controller; controller = agp_find_controller_for_client(id); if (controller == NULL) return -EINVAL; client = agp_find_client_in_controller(controller, id); if (client == NULL) return -EINVAL; prev_client = client->prev; next_client = client->next; if (prev_client != NULL) { prev_client->next = next_client; if (next_client != NULL) next_client->prev = prev_client; } else { if (next_client != NULL) next_client->prev = NULL; controller->clients = next_client; } controller->num_clients--; agp_remove_seg_from_client(client); kfree(client); return 0; } /* End - Routines for managing client lists */ /* File Operations */ static int agp_mmap(struct file *file, struct vm_area_struct *vma) { unsigned int size, current_size; unsigned long offset; struct agp_client *client; struct agp_file_private *priv = file->private_data; struct agp_kern_info kerninfo; mutex_lock(&(agp_fe.agp_mutex)); if (agp_fe.backend_acquired != true) goto out_eperm; if (!(test_bit(AGP_FF_IS_VALID, &priv->access_flags))) goto out_eperm; agp_copy_info(agp_bridge, &kerninfo); size = vma->vm_end - vma->vm_start; current_size = kerninfo.aper_size; current_size = current_size * 0x100000; offset = vma->vm_pgoff << PAGE_SHIFT; DBG("%lx:%lx", offset, offset+size); if (test_bit(AGP_FF_IS_CLIENT, &priv->access_flags)) { if ((size + offset) > current_size) goto out_inval; client = agp_find_client_by_pid(current->pid); if (client == NULL) goto out_eperm; if (!agp_find_seg_in_client(client, offset, size, vma->vm_page_prot)) goto out_inval; DBG("client vm_ops=%p", kerninfo.vm_ops); if (kerninfo.vm_ops) { vma->vm_ops = kerninfo.vm_ops; } else if (io_remap_pfn_range(vma, vma->vm_start, (kerninfo.aper_base + offset) >> PAGE_SHIFT, size, vma->vm_page_prot)) { goto out_again; } mutex_unlock(&(agp_fe.agp_mutex)); return 0; } if (test_bit(AGP_FF_IS_CONTROLLER, &priv->access_flags)) { if (size != current_size) goto out_inval; DBG("controller vm_ops=%p", kerninfo.vm_ops); if (kerninfo.vm_ops) { vma->vm_ops = kerninfo.vm_ops; } else if (io_remap_pfn_range(vma, vma->vm_start, kerninfo.aper_base >> PAGE_SHIFT, size, vma->vm_page_prot)) { goto out_again; } mutex_unlock(&(agp_fe.agp_mutex)); return 0; } out_eperm: mutex_unlock(&(agp_fe.agp_mutex)); return -EPERM; out_inval: mutex_unlock(&(agp_fe.agp_mutex)); return -EINVAL; out_again: mutex_unlock(&(agp_fe.agp_mutex)); return -EAGAIN; } static int agp_release(struct inode *inode, struct file *file) { struct agp_file_private *priv = file->private_data; mutex_lock(&(agp_fe.agp_mutex)); DBG("priv=%p", priv); if (test_bit(AGP_FF_IS_CONTROLLER, &priv->access_flags)) { struct agp_controller *controller; controller = agp_find_controller_by_pid(priv->my_pid); if (controller != NULL) { if (controller == agp_fe.current_controller) agp_controller_release_current(controller, priv); agp_remove_controller(controller); controller = NULL; } } if (test_bit(AGP_FF_IS_CLIENT, &priv->access_flags)) agp_remove_client(priv->my_pid); agp_remove_file_private(priv); kfree(priv); file->private_data = NULL; mutex_unlock(&(agp_fe.agp_mutex)); return 0; } static int agp_open(struct inode *inode, struct file *file) { int minor = iminor(inode); struct agp_file_private *priv; struct agp_client *client; if (minor != AGPGART_MINOR) return -ENXIO; mutex_lock(&(agp_fe.agp_mutex)); priv = kzalloc(sizeof(struct agp_file_private), GFP_KERNEL); if (priv == NULL) { mutex_unlock(&(agp_fe.agp_mutex)); return -ENOMEM; } set_bit(AGP_FF_ALLOW_CLIENT, &priv->access_flags); priv->my_pid = current->pid; if (capable(CAP_SYS_RAWIO)) /* Root priv, can be controller */ set_bit(AGP_FF_ALLOW_CONTROLLER, &priv->access_flags); client = agp_find_client_by_pid(current->pid); if (client != NULL) { set_bit(AGP_FF_IS_CLIENT, &priv->access_flags); set_bit(AGP_FF_IS_VALID, &priv->access_flags); } file->private_data = (void *) priv; agp_insert_file_private(priv); DBG("private=%p, client=%p", priv, client); mutex_unlock(&(agp_fe.agp_mutex)); return 0; } static ssize_t agp_read(struct file *file, char __user *buf, size_t count, loff_t * ppos) { return -EINVAL; } static ssize_t agp_write(struct file *file, const char __user *buf, size_t count, loff_t * ppos) { return -EINVAL; } static int agpioc_info_wrap(struct agp_file_private *priv, void __user *arg) { struct agp_info userinfo; struct agp_kern_info kerninfo; agp_copy_info(agp_bridge, &kerninfo); userinfo.version.major = kerninfo.version.major; userinfo.version.minor = kerninfo.version.minor; userinfo.bridge_id = kerninfo.device->vendor | (kerninfo.device->device << 16); userinfo.agp_mode = kerninfo.mode; userinfo.aper_base = kerninfo.aper_base; userinfo.aper_size = kerninfo.aper_size; userinfo.pg_total = userinfo.pg_system = kerninfo.max_memory; userinfo.pg_used = kerninfo.current_memory; if (copy_to_user(arg, &userinfo, sizeof(struct agp_info))) return -EFAULT; return 0; } int agpioc_acquire_wrap(struct agp_file_private *priv) { struct agp_controller *controller; DBG(""); if (!(test_bit(AGP_FF_ALLOW_CONTROLLER, &priv->access_flags))) return -EPERM; if (agp_fe.current_controller != NULL) return -EBUSY; if (!agp_bridge) return -ENODEV; if (atomic_read(&agp_bridge->agp_in_use)) return -EBUSY; atomic_inc(&agp_bridge->agp_in_use); agp_fe.backend_acquired = true; controller = agp_find_controller_by_pid(priv->my_pid); if (controller != NULL) { agp_controller_make_current(controller); } else { controller = agp_create_controller(priv->my_pid); if (controller == NULL) { agp_fe.backend_acquired = false; agp_backend_release(agp_bridge); return -ENOMEM; } agp_insert_controller(controller); agp_controller_make_current(controller); } set_bit(AGP_FF_IS_CONTROLLER, &priv->access_flags); set_bit(AGP_FF_IS_VALID, &priv->access_flags); return 0; } int agpioc_release_wrap(struct agp_file_private *priv) { DBG(""); agp_controller_release_current(agp_fe.current_controller, priv); return 0; } int agpioc_setup_wrap(struct agp_file_private *priv, void __user *arg) { struct agp_setup mode; DBG(""); if (copy_from_user(&mode, arg, sizeof(struct agp_setup))) return -EFAULT; agp_enable(agp_bridge, mode.agp_mode); return 0; } static int agpioc_reserve_wrap(struct agp_file_private *priv, void __user *arg) { struct agp_region reserve; struct agp_client *client; struct agp_file_private *client_priv; DBG(""); if (copy_from_user(&reserve, arg, sizeof(struct agp_region))) return -EFAULT; if ((unsigned) reserve.seg_count >= ~0U/sizeof(struct agp_segment)) return -EFAULT; client = agp_find_client_by_pid(reserve.pid); if (reserve.seg_count == 0) { /* remove a client */ client_priv = agp_find_private(reserve.pid); if (client_priv != NULL) { set_bit(AGP_FF_IS_CLIENT, &client_priv->access_flags); set_bit(AGP_FF_IS_VALID, &client_priv->access_flags); } if (client == NULL) { /* client is already removed */ return 0; } return agp_remove_client(reserve.pid); } else { struct agp_segment *segment; if (reserve.seg_count >= 16384) return -EINVAL; segment = kmalloc((sizeof(struct agp_segment) * reserve.seg_count), GFP_KERNEL); if (segment == NULL) return -ENOMEM; if (copy_from_user(segment, (void __user *) reserve.seg_list, sizeof(struct agp_segment) * reserve.seg_count)) { kfree(segment); return -EFAULT; } reserve.seg_list = segment; if (client == NULL) { /* Create the client and add the segment */ client = agp_create_client(reserve.pid); if (client == NULL) { kfree(segment); return -ENOMEM; } client_priv = agp_find_private(reserve.pid); if (client_priv != NULL) { set_bit(AGP_FF_IS_CLIENT, &client_priv->access_flags); set_bit(AGP_FF_IS_VALID, &client_priv->access_flags); } } return agp_create_segment(client, &reserve); } /* Will never really happen */ return -EINVAL; } int agpioc_protect_wrap(struct agp_file_private *priv) { DBG(""); /* This function is not currently implemented */ return -EINVAL; } static int agpioc_allocate_wrap(struct agp_file_private *priv, void __user *arg) { struct agp_memory *memory; struct agp_allocate alloc; DBG(""); if (copy_from_user(&alloc, arg, sizeof(struct agp_allocate))) return -EFAULT; if (alloc.type >= AGP_USER_TYPES) return -EINVAL; memory = agp_allocate_memory_wrap(alloc.pg_count, alloc.type); if (memory == NULL) return -ENOMEM; alloc.key = memory->key; alloc.physical = memory->physical; if (copy_to_user(arg, &alloc, sizeof(struct agp_allocate))) { agp_free_memory_wrap(memory); return -EFAULT; } return 0; } int agpioc_deallocate_wrap(struct agp_file_private *priv, int arg) { struct agp_memory *memory; DBG(""); memory = agp_find_mem_by_key(arg); if (memory == NULL) return -EINVAL; agp_free_memory_wrap(memory); return 0; } static int agpioc_bind_wrap(struct agp_file_private *priv, void __user *arg) { struct agp_bind bind_info; struct agp_memory *memory; DBG(""); if (copy_from_user(&bind_info, arg, sizeof(struct agp_bind))) return -EFAULT; memory = agp_find_mem_by_key(bind_info.key); if (memory == NULL) return -EINVAL; return agp_bind_memory(memory, bind_info.pg_start); } static int agpioc_unbind_wrap(struct agp_file_private *priv, void __user *arg) { struct agp_memory *memory; struct agp_unbind unbind; DBG(""); if (copy_from_user(&unbind, arg, sizeof(struct agp_unbind))) return -EFAULT; memory = agp_find_mem_by_key(unbind.key); if (memory == NULL) return -EINVAL; return agp_unbind_memory(memory); } static long agp_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct agp_file_private *curr_priv = file->private_data; int ret_val = -ENOTTY; DBG("priv=%p, cmd=%x", curr_priv, cmd); mutex_lock(&(agp_fe.agp_mutex)); if ((agp_fe.current_controller == NULL) && (cmd != AGPIOC_ACQUIRE)) { ret_val = -EINVAL; goto ioctl_out; } if ((agp_fe.backend_acquired != true) && (cmd != AGPIOC_ACQUIRE)) { ret_val = -EBUSY; goto ioctl_out; } if (cmd != AGPIOC_ACQUIRE) { if (!(test_bit(AGP_FF_IS_CONTROLLER, &curr_priv->access_flags))) { ret_val = -EPERM; goto ioctl_out; } /* Use the original pid of the controller, * in case it's threaded */ if (agp_fe.current_controller->pid != curr_priv->my_pid) { ret_val = -EBUSY; goto ioctl_out; } } switch (cmd) { case AGPIOC_INFO: ret_val = agpioc_info_wrap(curr_priv, (void __user *) arg); break; case AGPIOC_ACQUIRE: ret_val = agpioc_acquire_wrap(curr_priv); break; case AGPIOC_RELEASE: ret_val = agpioc_release_wrap(curr_priv); break; case AGPIOC_SETUP: ret_val = agpioc_setup_wrap(curr_priv, (void __user *) arg); break; case AGPIOC_RESERVE: ret_val = agpioc_reserve_wrap(curr_priv, (void __user *) arg); break; case AGPIOC_PROTECT: ret_val = agpioc_protect_wrap(curr_priv); break; case AGPIOC_ALLOCATE: ret_val = agpioc_allocate_wrap(curr_priv, (void __user *) arg); break; case AGPIOC_DEALLOCATE: ret_val = agpioc_deallocate_wrap(curr_priv, (int) arg); break; case AGPIOC_BIND: ret_val = agpioc_bind_wrap(curr_priv, (void __user *) arg); break; case AGPIOC_UNBIND: ret_val = agpioc_unbind_wrap(curr_priv, (void __user *) arg); break; case AGPIOC_CHIPSET_FLUSH: break; } ioctl_out: DBG("ioctl returns %d\n", ret_val); mutex_unlock(&(agp_fe.agp_mutex)); return ret_val; } static const struct file_operations agp_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .read = agp_read, .write = agp_write, .unlocked_ioctl = agp_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = compat_agp_ioctl, #endif .mmap = agp_mmap, .open = agp_open, .release = agp_release, }; static struct miscdevice agp_miscdev = { .minor = AGPGART_MINOR, .name = "agpgart", .fops = &agp_fops }; int agp_frontend_initialize(void) { memset(&agp_fe, 0, sizeof(struct agp_front_data)); mutex_init(&(agp_fe.agp_mutex)); if (misc_register(&agp_miscdev)) { printk(KERN_ERR PFX "unable to get minor: %d\n", AGPGART_MINOR); return -EIO; } return 0; } void agp_frontend_cleanup(void) { misc_deregister(&agp_miscdev); }
8596cc1276349d09f7706f6069bb744b97fd291b
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
/multimedia/mediatomb/patches/patch-tombupnp_upnp_src_genlib_net_http_webserver.c
fa31e1299af511d157932e998c487f13d236780b
[]
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
610
c
patch-tombupnp_upnp_src_genlib_net_http_webserver.c
$NetBSD: patch-tombupnp_upnp_src_genlib_net_http_webserver.c,v 1.2 2012/09/25 11:45:11 ryoon Exp $ Fix building with Clang. --- tombupnp/upnp/src/genlib/net/http/webserver.c.orig 2010-03-25 14:58:12.000000000 +0000 +++ tombupnp/upnp/src/genlib/net/http/webserver.c @@ -310,7 +310,7 @@ search_extension( IN const char *extensi * 0 - On Sucess * UPNP_E_OUTOF_MEMORY - on memory allocation failures ************************************************************************/ -XINLINE int +int get_content_type( IN const char *filename, OUT DOMString * content_type ) {
986d9c1d75df5453a66f82222bd1a103dc894caf
450916eee7580beb928ed8f387db4f0a8c1aa508
/src/amuse/community/mi6/src/stellar_evolution.h
c690f358f49d5c984bb90c6863e68f4eed5364c7
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
amusecode/amuse
42095545893f5a86ea79c2a52ce54d3ce8eb204f
b57c1e2fda1457d5025307be105c2aa59b19b574
refs/heads/main
2023-08-31T04:50:48.880044
2023-08-30T12:00:20
2023-08-30T12:00:20
18,516,331
158
118
Apache-2.0
2023-08-30T12:00:22
2014-04-07T12:35:07
AMPL
UTF-8
C
false
false
4,669
h
stellar_evolution.h
#ifndef STELLAR_EVOLUTION_H #define STELLAR_EVOLUTION_H /* Tout et al MNRAS 281, 257 (1996) */ static const double L[7][5] = {{3.970417e-01, -3.2913574e-01, 3.4776688e-01, 3.7470851e-01, 9.011915e-02}, {8.527626e+00, -2.441225973e+01, 5.643597107e+01, 3.706152575e+01, 5.4562406e+00}, {2.5546e-04, -1.23461e-03, -2.3246e-04, 4.5519e-04, 1.6176e-04}, {5.432889e+00, -8.62157806e+00, 1.344202049e+01, 1.451584135e+01, 3.39793084e+00}, {5.563579e+00,-1.032345224e+01, 1.944322980e+01, 1.897361347e+01, 4.16903097e+00}, {7.8866060e-01, -2.90870942e+00, 6.54713531e+00, 4.05606657e+00, 5.3287322e-01}, {5.86685e-03, -1.704237e-02, 3.872348e-02, 2.570041e-02, 3.83376e-03}}; static const double R[9][5] = {{1.715359e+00, 6.2246212e-01, -9.2557761e-01, -1.16996966e+00, -3.0631491e-01}, {6.597788e+00, -4.2450044e-01,-1.213339427e+01,-1.073509484e+01, -2.51487077e+00}, {1.008855000e+01, -7.11727086e+00,-3.167119479e+01, -2.424848322e+01,-5.33608972e+00}, {1.012495e+00, 3.2699690e-01, -9.23418e-03, -3.876858e-02, -4.12750e-03}, {7.490166e-02, 2.410413e-02, 7.233664e-02, 3.040467e-02, 1.97741e-03}, {1.077422e-02, 0.0, 0.0, 0.0, 0.0}, {3.082234e+00, 9.447205e-01, -2.15200882e+00, -2.49219496e+00, -6.3848738e-01}, {1.784778e+01, -7.4534569e+00,-4.896066856e+01,-4.005386135e+01, -9.09331816e+00}, {2.2582e-04, -1.86899e-03, 3.88783e-03, 1.42402e-03,-7.671e-05}}; /* sloar metalicity functions double get_radius_zams0(const double &m) double get_luminosity_zams0(const double &m) */ inline double get_radius_zams0(const double &m){ double msqrt = sqrt(m); double m2 = m * m; double m2_5 = m2 * msqrt; double m4 = m2 * m2; double m6 = m4 * m2; double m6_5 = m6 * msqrt; double m8_5 = m6_5 * m2; double m11 = m8_5 * m2_5; double m18_5 = m8_5 * m6 * m4; double m19 = m18_5 * msqrt; double m19_5 = m19 * msqrt; return (R[0][0]*m2_5 + R[1][0]*m6_5 + R[2][0]*m11 + R[3][0]*m19 + R[4][0]*m19_5) / (R[5][0] + R[6][0]*m2 + R[7][0]*m8_5 + m18_5 + R[8][0]*m19_5); } inline double get_luminosity_zams0(const double &m){ double msqrt = sqrt(m); double m2 = m * m; double m3 = m * m2; double m5 = m3 * m2; double m5_5 = m5 * msqrt; double m7 = m5 * m2; double m8 = m5 * m3; double m9_5 = m5_5 * m2 * m2; double m11 = m8 * m3; return (L[0][0]*m5_5 + L[1][0]*m11) / (L[2][0] + m3 + L[3][0]*m5 + L[4][0]*m7 + L[5][0]*m8 + L[6][0]*m9_5); } /* below functions have not be checked */ inline double get_coefficient_zams(const double &z, double c[5]){ double zlog = log10(z*50); // = z / z_sun, z_sun = 0.02 return (((c[4]*zlog + c[3]) * zlog + c[2]) * zlog + c[1]) * zlog +c[0]; } inline void get_L_coef_zams_all(const double &z, double Lcoef[7]){ double zlog = log10(z*50); // = z / z_sun, z_sun = 0.02 for(int i=0; i<7; i++){ Lcoef[i] = (((L[i][4]*zlog + L[i][3]) * zlog + L[i][2]) * zlog + L[i][1]) * zlog + L[i][0]; } } inline void get_R_coef_zams_all(const double &z, double Rcoef[9]){ double zlog = log10(z*50); // = z / z_sun, z_sun = 0.02 for(int i=0; i<9; i++){ Rcoef[i] = (((R[i][4]*zlog + R[i][3]) * zlog + R[i][2]) * zlog + R[i][1]) * zlog + R[i][0]; } } inline void get_coef_zams_all(const double &z, double Lcoef[7], double Rcoef[9]){ double zlog = log10(z*50); // = z / z_sun, z_sun = 0.02 for(int i=0; i<7; i++){ Lcoef[i] = (((L[i][4]*zlog + L[i][3]) * zlog + L[i][2]) * zlog + L[i][1]) * zlog + L[i][0]; } for(int i=0; i<9; i++){ Rcoef[i] = (((R[i][4]*zlog + R[i][3]) * zlog + R[i][2]) * zlog + R[i][1]) * zlog + R[i][0]; } } inline double get_luminosity_zams(const double &m, const double Lcoef[7]){ double msqrt = sqrt(m); double m2 = m * m; double m3 = m * m2; double m5 = m3 * m2; double m5_5 = m5 * msqrt; double m7 = m5 * m2; double m8 = m5 * m3; double m9_5 = m5_5 * m2 * m2; double m11 = m3 * m8; return (Lcoef[0]*m5_5 + Lcoef[1]*m11) / (Lcoef[2] + m3 + Lcoef[3]*m5 + Lcoef[4]*m7 + Lcoef[5]*m8 + Lcoef[6]*m9_5); } inline double get_radius_zams(const double &m, const double Rcoef[9]){ double msqrt = sqrt(m); double m2 = m * m; double m2_5 = m2 * msqrt; double m4 = m2 * m2; double m6 = m4 * m2; double m6_5 = m6 * msqrt; double m8_5 = m6_5 * m2; double m11 = m8_5 * m2_5; double m18_5 = m8_5 * m6 * m4; double m19 = m18_5 * msqrt; double m19_5 = m19 * msqrt; return (Rcoef[0]*m2_5 + Rcoef[1]*m6_5 + Rcoef[2]*m11 + Rcoef[3]*m19 + Rcoef[4]*m19_5) / (Rcoef[5] + Rcoef[6]*m2 + Rcoef[7]*m8_5 + m18_5 + Rcoef[8]*m19_5); } #endif //STELLAR_EVOLUTION_H
9d3c6cff71db7bc4465838065d477435f385bfa4
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/media/usb/sn9c102/sn9c102_devtable.h
b3d2cc729657df34e57bc300033bafc1baf2bdd6
[ "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
8,451
h
sn9c102_devtable.h
/*************************************************************************** * Table of device identifiers of the SN9C1xx PC Camera Controllers * * * * Copyright (C) 2007 by Luca Risolia <luca.risolia@studio.unibo.it> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * ***************************************************************************/ #ifndef _SN9C102_DEVTABLE_H_ #define _SN9C102_DEVTABLE_H_ #include <linux/usb.h> struct sn9c102_device; /* Each SN9C1xx camera has proper PID/VID identifiers. SN9C103, SN9C105, SN9C120 support multiple interfaces, but we only have to handle the video class interface. */ #define SN9C102_USB_DEVICE(vend, prod, bridge) \ .match_flags = USB_DEVICE_ID_MATCH_DEVICE | \ USB_DEVICE_ID_MATCH_INT_CLASS, \ .idVendor = (vend), \ .idProduct = (prod), \ .bInterfaceClass = 0xff, \ .driver_info = (bridge) static const struct usb_device_id sn9c102_id_table[] = { /* SN9C101 and SN9C102 */ #if !defined CONFIG_USB_GSPCA_SONIXB && !defined CONFIG_USB_GSPCA_SONIXB_MODULE { SN9C102_USB_DEVICE(0x0c45, 0x6001, BRIDGE_SN9C102), }, { SN9C102_USB_DEVICE(0x0c45, 0x6005, BRIDGE_SN9C102), }, { SN9C102_USB_DEVICE(0x0c45, 0x6007, BRIDGE_SN9C102), }, { SN9C102_USB_DEVICE(0x0c45, 0x6009, BRIDGE_SN9C102), }, { SN9C102_USB_DEVICE(0x0c45, 0x600d, BRIDGE_SN9C102), }, /* { SN9C102_USB_DEVICE(0x0c45, 0x6011, BRIDGE_SN9C102), }, OV6650 */ { SN9C102_USB_DEVICE(0x0c45, 0x6019, BRIDGE_SN9C102), }, #endif { SN9C102_USB_DEVICE(0x0c45, 0x6024, BRIDGE_SN9C102), }, { SN9C102_USB_DEVICE(0x0c45, 0x6025, BRIDGE_SN9C102), }, #if !defined CONFIG_USB_GSPCA_SONIXB && !defined CONFIG_USB_GSPCA_SONIXB_MODULE { SN9C102_USB_DEVICE(0x0c45, 0x6028, BRIDGE_SN9C102), }, { SN9C102_USB_DEVICE(0x0c45, 0x6029, BRIDGE_SN9C102), }, { SN9C102_USB_DEVICE(0x0c45, 0x602a, BRIDGE_SN9C102), }, #endif { SN9C102_USB_DEVICE(0x0c45, 0x602b, BRIDGE_SN9C102), }, /* not in sonixb */ #if !defined CONFIG_USB_GSPCA_SONIXB && !defined CONFIG_USB_GSPCA_SONIXB_MODULE { SN9C102_USB_DEVICE(0x0c45, 0x602c, BRIDGE_SN9C102), }, /* { SN9C102_USB_DEVICE(0x0c45, 0x602d, BRIDGE_SN9C102), }, HV7131R */ { SN9C102_USB_DEVICE(0x0c45, 0x602e, BRIDGE_SN9C102), }, #endif { SN9C102_USB_DEVICE(0x0c45, 0x6030, BRIDGE_SN9C102), }, /* not in sonixb */ /* SN9C103 */ /* { SN9C102_USB_DEVICE(0x0c45, 0x6080, BRIDGE_SN9C103), }, non existent ? */ { SN9C102_USB_DEVICE(0x0c45, 0x6082, BRIDGE_SN9C103), }, /* not in sonixb */ #if !defined CONFIG_USB_GSPCA_SONIXB && !defined CONFIG_USB_GSPCA_SONIXB_MODULE /* { SN9C102_USB_DEVICE(0x0c45, 0x6083, BRIDGE_SN9C103), }, HY7131D/E */ /* { SN9C102_USB_DEVICE(0x0c45, 0x6088, BRIDGE_SN9C103), }, non existent ? */ /* { SN9C102_USB_DEVICE(0x0c45, 0x608a, BRIDGE_SN9C103), }, non existent ? */ /* { SN9C102_USB_DEVICE(0x0c45, 0x608b, BRIDGE_SN9C103), }, non existent ? */ { SN9C102_USB_DEVICE(0x0c45, 0x608c, BRIDGE_SN9C103), }, /* { SN9C102_USB_DEVICE(0x0c45, 0x608e, BRIDGE_SN9C103), }, CISVF10 */ { SN9C102_USB_DEVICE(0x0c45, 0x608f, BRIDGE_SN9C103), }, /* { SN9C102_USB_DEVICE(0x0c45, 0x60a0, BRIDGE_SN9C103), }, non existent ? */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60a2, BRIDGE_SN9C103), }, non existent ? */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60a3, BRIDGE_SN9C103), }, non existent ? */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60a8, BRIDGE_SN9C103), }, PAS106 */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60aa, BRIDGE_SN9C103), }, TAS5130 */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60ab, BRIDGE_SN9C103), }, TAS5110, non existent */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60ac, BRIDGE_SN9C103), }, non existent ? */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60ae, BRIDGE_SN9C103), }, non existent ? */ { SN9C102_USB_DEVICE(0x0c45, 0x60af, BRIDGE_SN9C103), }, { SN9C102_USB_DEVICE(0x0c45, 0x60b0, BRIDGE_SN9C103), }, /* { SN9C102_USB_DEVICE(0x0c45, 0x60b2, BRIDGE_SN9C103), }, non existent ? */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60b3, BRIDGE_SN9C103), }, non existent ? */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60b8, BRIDGE_SN9C103), }, non existent ? */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60ba, BRIDGE_SN9C103), }, non existent ? */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60bb, BRIDGE_SN9C103), }, non existent ? */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60bc, BRIDGE_SN9C103), }, non existent ? */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60be, BRIDGE_SN9C103), }, non existent ? */ #endif /* SN9C105 */ #if !defined CONFIG_USB_GSPCA_SONIXJ && !defined CONFIG_USB_GSPCA_SONIXJ_MODULE { SN9C102_USB_DEVICE(0x045e, 0x00f5, BRIDGE_SN9C105), }, { SN9C102_USB_DEVICE(0x045e, 0x00f7, BRIDGE_SN9C105), }, { SN9C102_USB_DEVICE(0x0471, 0x0327, BRIDGE_SN9C105), }, { SN9C102_USB_DEVICE(0x0471, 0x0328, BRIDGE_SN9C105), }, { SN9C102_USB_DEVICE(0x0c45, 0x60c0, BRIDGE_SN9C105), }, /* { SN9C102_USB_DEVICE(0x0c45, 0x60c2, BRIDGE_SN9C105), }, PO1030 */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60c8, BRIDGE_SN9C105), }, OM6801 */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60cc, BRIDGE_SN9C105), }, HV7131GP */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60ea, BRIDGE_SN9C105), }, non existent ? */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60ec, BRIDGE_SN9C105), }, MO4000 */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60ef, BRIDGE_SN9C105), }, ICM105C */ /* { SN9C102_USB_DEVICE(0x0c45, 0x60fa, BRIDGE_SN9C105), }, OV7648 */ { SN9C102_USB_DEVICE(0x0c45, 0x60fb, BRIDGE_SN9C105), }, { SN9C102_USB_DEVICE(0x0c45, 0x60fc, BRIDGE_SN9C105), }, { SN9C102_USB_DEVICE(0x0c45, 0x60fe, BRIDGE_SN9C105), }, /* SN9C120 */ { SN9C102_USB_DEVICE(0x0458, 0x7025, BRIDGE_SN9C120), }, /* { SN9C102_USB_DEVICE(0x0c45, 0x6102, BRIDGE_SN9C120), }, po2030 */ /* { SN9C102_USB_DEVICE(0x0c45, 0x6108, BRIDGE_SN9C120), }, om6801 */ /* { SN9C102_USB_DEVICE(0x0c45, 0x610f, BRIDGE_SN9C120), }, S5K53BEB */ { SN9C102_USB_DEVICE(0x0c45, 0x6130, BRIDGE_SN9C120), }, /* { SN9C102_USB_DEVICE(0x0c45, 0x6138, BRIDGE_SN9C120), }, MO8000 */ { SN9C102_USB_DEVICE(0x0c45, 0x613a, BRIDGE_SN9C120), }, { SN9C102_USB_DEVICE(0x0c45, 0x613b, BRIDGE_SN9C120), }, { SN9C102_USB_DEVICE(0x0c45, 0x613c, BRIDGE_SN9C120), }, { SN9C102_USB_DEVICE(0x0c45, 0x613e, BRIDGE_SN9C120), }, #endif { } }; /* Probing functions: on success, you must attach the sensor to the camera by calling sn9c102_attach_sensor(). To enable the I2C communication, you might need to perform a really basic initialization of the SN9C1XX chip. Functions must return 0 on success, the appropriate error otherwise. */ extern int sn9c102_probe_hv7131d(struct sn9c102_device* cam); extern int sn9c102_probe_hv7131r(struct sn9c102_device* cam); extern int sn9c102_probe_mi0343(struct sn9c102_device* cam); extern int sn9c102_probe_mi0360(struct sn9c102_device* cam); extern int sn9c102_probe_mt9v111(struct sn9c102_device *cam); extern int sn9c102_probe_ov7630(struct sn9c102_device* cam); extern int sn9c102_probe_ov7660(struct sn9c102_device* cam); extern int sn9c102_probe_pas106b(struct sn9c102_device* cam); extern int sn9c102_probe_pas202bcb(struct sn9c102_device* cam); extern int sn9c102_probe_tas5110c1b(struct sn9c102_device* cam); extern int sn9c102_probe_tas5110d(struct sn9c102_device* cam); extern int sn9c102_probe_tas5130d1b(struct sn9c102_device* cam); #endif /* _SN9C102_DEVTABLE_H_ */
67a6cdb213496f19ace08942dc84ee2dc7ef3e99
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
/lang/spidermonkey185/patches/patch-jsgc.h
685273590b34ca782a35461a53f9a9297f08665e
[]
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
312
h
patch-jsgc.h
$NetBSD: patch-jsgc.h,v 1.1 2016/12/18 21:54:05 joerg Exp $ --- jsgc.h.orig 2016-12-18 15:56:38.171004394 +0000 +++ jsgc.h @@ -66,7 +66,7 @@ #include "jsgcstats.h" #include "jscell.h" -struct JSCompartment; +struct JS_FRIEND_API(JSCompartment); extern "C" void js_TraceXML(JSTracer *trc, JSXML* thing);
303d1e64ce46f1046e3005dfb9bc0c8860bbf77d
eecd5e4c50d8b78a769bcc2675250576bed34066
/src/ts/tutorials/power_grid/ex5.c
733ccfeb4d9c9fa97e41d457fb47b504f2a9f604
[ "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
11,583
c
ex5.c
static char help[] = "Basic equation for an induction generator driven by a wind turbine.\n"; /*F \begin{eqnarray} T_w\frac{dv_w}{dt} & = & v_w - v_we \\ 2(H_t+H_m)\frac{ds}{dt} & = & P_w - P_e \end{eqnarray} F*/ /* - Pw is the power extracted from the wind turbine given by Pw = 0.5*\rho*cp*Ar*vw^3 - The wind speed time series is modeled using a Weibull distribution and then passed through a low pass filter (with time constant T_w). - v_we is the wind speed data calculated using Weibull distribution while v_w is the output of the filter. - P_e is assumed as constant electrical torque - This example does not work with adaptive time stepping! Reference: Power System Modeling and Scripting - F. Milano */ #include <petscts.h> #define freq 50 #define ws (2 * PETSC_PI * freq) #define MVAbase 100 typedef struct { /* Parameters for wind speed model */ PetscInt nsamples; /* Number of wind samples */ PetscReal cw; /* Scale factor for Weibull distribution */ PetscReal kw; /* Shape factor for Weibull distribution */ Vec wind_data; /* Vector to hold wind speeds */ Vec t_wind; /* Vector to hold wind speed times */ PetscReal Tw; /* Filter time constant */ /* Wind turbine parameters */ PetscScalar Rt; /* Rotor radius */ PetscScalar Ar; /* Area swept by rotor (pi*R*R) */ PetscReal nGB; /* Gear box ratio */ PetscReal Ht; /* Turbine inertia constant */ PetscReal rho; /* Atmospheric pressure */ /* Induction generator parameters */ PetscInt np; /* Number of poles */ PetscReal Xm; /* Magnetizing reactance */ PetscReal Xs; /* Stator Reactance */ PetscReal Xr; /* Rotor reactance */ PetscReal Rs; /* Stator resistance */ PetscReal Rr; /* Rotor resistance */ PetscReal Hm; /* Motor inertia constant */ PetscReal Xp; /* Xs + Xm*Xr/(Xm + Xr) */ PetscScalar Te; /* Electrical Torque */ Mat Sol; /* Solution matrix */ PetscInt stepnum; /* Column number of solution matrix */ } AppCtx; /* Initial values computed by Power flow and initialization */ PetscScalar s = -0.00011577790353; /*Pw = 0.011064344110238; %Te*wm */ PetscScalar vwa = 22.317142184449754; PetscReal tmax = 20.0; /* Saves the solution at each time to a matrix */ PetscErrorCode SaveSolution(TS ts) { AppCtx *user; Vec X; PetscScalar *mat; const PetscScalar *x; PetscInt idx; PetscReal t; PetscFunctionBegin; PetscCall(TSGetApplicationContext(ts, &user)); PetscCall(TSGetTime(ts, &t)); PetscCall(TSGetSolution(ts, &X)); idx = 3 * user->stepnum; PetscCall(MatDenseGetArray(user->Sol, &mat)); PetscCall(VecGetArrayRead(X, &x)); mat[idx] = t; PetscCall(PetscArraycpy(mat + idx + 1, x, 2)); PetscCall(MatDenseRestoreArray(user->Sol, &mat)); PetscCall(VecRestoreArrayRead(X, &x)); user->stepnum++; PetscFunctionReturn(PETSC_SUCCESS); } /* Computes the wind speed using Weibull distribution */ PetscErrorCode WindSpeeds(AppCtx *user) { PetscScalar *x, *t, avg_dev, sum; PetscInt i; PetscFunctionBegin; user->cw = 5; user->kw = 2; /* Rayleigh distribution */ user->nsamples = 2000; user->Tw = 0.2; PetscOptionsBegin(PETSC_COMM_WORLD, NULL, "Wind Speed Options", ""); { PetscCall(PetscOptionsReal("-cw", "", "", user->cw, &user->cw, NULL)); PetscCall(PetscOptionsReal("-kw", "", "", user->kw, &user->kw, NULL)); PetscCall(PetscOptionsInt("-nsamples", "", "", user->nsamples, &user->nsamples, NULL)); PetscCall(PetscOptionsReal("-Tw", "", "", user->Tw, &user->Tw, NULL)); } PetscOptionsEnd(); PetscCall(VecCreate(PETSC_COMM_WORLD, &user->wind_data)); PetscCall(VecSetSizes(user->wind_data, PETSC_DECIDE, user->nsamples)); PetscCall(VecSetFromOptions(user->wind_data)); PetscCall(VecDuplicate(user->wind_data, &user->t_wind)); PetscCall(VecGetArray(user->t_wind, &t)); for (i = 0; i < user->nsamples; i++) t[i] = (i + 1) * tmax / user->nsamples; PetscCall(VecRestoreArray(user->t_wind, &t)); /* Wind speed deviation = (-log(rand)/cw)^(1/kw) */ PetscCall(VecSetRandom(user->wind_data, NULL)); PetscCall(VecLog(user->wind_data)); PetscCall(VecScale(user->wind_data, -1 / user->cw)); PetscCall(VecGetArray(user->wind_data, &x)); for (i = 0; i < user->nsamples; i++) x[i] = PetscPowScalar(x[i], (1 / user->kw)); PetscCall(VecRestoreArray(user->wind_data, &x)); PetscCall(VecSum(user->wind_data, &sum)); avg_dev = sum / user->nsamples; /* Wind speed (t) = (1 + wind speed deviation(t) - avg_dev)*average wind speed */ PetscCall(VecShift(user->wind_data, (1 - avg_dev))); PetscCall(VecScale(user->wind_data, vwa)); PetscFunctionReturn(PETSC_SUCCESS); } /* Sets the parameters for wind turbine */ PetscErrorCode SetWindTurbineParams(AppCtx *user) { PetscFunctionBegin; user->Rt = 35; user->Ar = PETSC_PI * user->Rt * user->Rt; user->nGB = 1.0 / 89.0; user->rho = 1.225; user->Ht = 1.5; PetscFunctionReturn(PETSC_SUCCESS); } /* Sets the parameters for induction generator */ PetscErrorCode SetInductionGeneratorParams(AppCtx *user) { PetscFunctionBegin; user->np = 4; user->Xm = 3.0; user->Xs = 0.1; user->Xr = 0.08; user->Rs = 0.01; user->Rr = 0.01; user->Xp = user->Xs + user->Xm * user->Xr / (user->Xm + user->Xr); user->Hm = 1.0; user->Te = 0.011063063063251968; PetscFunctionReturn(PETSC_SUCCESS); } /* Computes the power extracted from wind */ PetscErrorCode GetWindPower(PetscScalar wm, PetscScalar vw, PetscScalar *Pw, AppCtx *user) { PetscScalar temp, lambda, lambda_i, cp; PetscFunctionBegin; temp = user->nGB * 2 * user->Rt * ws / user->np; lambda = temp * wm / vw; lambda_i = 1 / (1 / lambda + 0.002); cp = 0.44 * (125 / lambda_i - 6.94) * PetscExpScalar(-16.5 / lambda_i); *Pw = 0.5 * user->rho * cp * user->Ar * vw * vw * vw / (MVAbase * 1e6); PetscFunctionReturn(PETSC_SUCCESS); } /* Defines the ODE passed to the ODE solver */ static PetscErrorCode IFunction(TS ts, PetscReal t, Vec U, Vec Udot, Vec F, AppCtx *user) { PetscScalar *f, wm, Pw, *wd; const PetscScalar *u, *udot; PetscInt stepnum; PetscFunctionBegin; PetscCall(TSGetStepNumber(ts, &stepnum)); /* The next three lines allow us to access the entries of the vectors directly */ PetscCall(VecGetArrayRead(U, &u)); PetscCall(VecGetArrayRead(Udot, &udot)); PetscCall(VecGetArray(F, &f)); PetscCall(VecGetArray(user->wind_data, &wd)); f[0] = user->Tw * udot[0] - wd[stepnum] + u[0]; wm = 1 - u[1]; PetscCall(GetWindPower(wm, u[0], &Pw, user)); f[1] = 2.0 * (user->Ht + user->Hm) * udot[1] - Pw / wm + user->Te; PetscCall(VecRestoreArray(user->wind_data, &wd)); PetscCall(VecRestoreArrayRead(U, &u)); PetscCall(VecRestoreArrayRead(Udot, &udot)); PetscCall(VecRestoreArray(F, &f)); PetscFunctionReturn(PETSC_SUCCESS); } int main(int argc, char **argv) { TS ts; /* ODE integrator */ Vec U; /* solution will be stored here */ Mat A; /* Jacobian matrix */ PetscMPIInt size; PetscInt n = 2, idx; AppCtx user; PetscScalar *u; SNES snes; PetscScalar *mat; const PetscScalar *x, *rmat; Mat B; PetscScalar *amat; PetscViewer viewer; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Initialize program - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscFunctionBeginUser; PetscCall(PetscInitialize(&argc, &argv, (char *)0, help)); PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size)); PetscCheck(size == 1, PETSC_COMM_WORLD, PETSC_ERR_WRONG_MPI_SIZE, "Only for sequential runs"); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create necessary matrix and vectors - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(MatCreate(PETSC_COMM_WORLD, &A)); PetscCall(MatSetSizes(A, n, n, PETSC_DETERMINE, PETSC_DETERMINE)); PetscCall(MatSetFromOptions(A)); PetscCall(MatSetUp(A)); PetscCall(MatCreateVecs(A, &U, NULL)); /* Create wind speed data using Weibull distribution */ PetscCall(WindSpeeds(&user)); /* Set parameters for wind turbine and induction generator */ PetscCall(SetWindTurbineParams(&user)); PetscCall(SetInductionGeneratorParams(&user)); PetscCall(VecGetArray(U, &u)); u[0] = vwa; u[1] = s; PetscCall(VecRestoreArray(U, &u)); /* Create matrix to save solutions at each time step */ user.stepnum = 0; PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, 3, 2010, NULL, &user.Sol)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create timestepping solver context - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(TSCreate(PETSC_COMM_WORLD, &ts)); PetscCall(TSSetProblemType(ts, TS_NONLINEAR)); PetscCall(TSSetType(ts, TSBEULER)); PetscCall(TSSetIFunction(ts, NULL, (TSIFunction)IFunction, &user)); PetscCall(TSGetSNES(ts, &snes)); PetscCall(SNESSetJacobian(snes, A, A, SNESComputeJacobianDefault, NULL)); /* PetscCall(TSSetIJacobian(ts,A,A,(TSIJacobian)IJacobian,&user)); */ PetscCall(TSSetApplicationContext(ts, &user)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Set initial conditions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(TSSetSolution(ts, U)); /* Save initial solution */ idx = 3 * user.stepnum; PetscCall(MatDenseGetArray(user.Sol, &mat)); PetscCall(VecGetArrayRead(U, &x)); mat[idx] = 0.0; PetscCall(PetscArraycpy(mat + idx + 1, x, 2)); PetscCall(MatDenseRestoreArray(user.Sol, &mat)); PetscCall(VecRestoreArrayRead(U, &x)); user.stepnum++; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Set solver options - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(TSSetMaxTime(ts, 20.0)); PetscCall(TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP)); PetscCall(TSSetTimeStep(ts, .01)); PetscCall(TSSetFromOptions(ts)); PetscCall(TSSetPostStep(ts, SaveSolution)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Solve nonlinear system - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(TSSolve(ts, U)); PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, 3, user.stepnum, NULL, &B)); PetscCall(MatDenseGetArrayRead(user.Sol, &rmat)); PetscCall(MatDenseGetArray(B, &amat)); PetscCall(PetscArraycpy(amat, rmat, user.stepnum * 3)); PetscCall(MatDenseRestoreArray(B, &amat)); PetscCall(MatDenseRestoreArrayRead(user.Sol, &rmat)); PetscCall(PetscViewerBinaryOpen(PETSC_COMM_SELF, "out.bin", FILE_MODE_WRITE, &viewer)); PetscCall(MatView(B, viewer)); PetscCall(PetscViewerDestroy(&viewer)); PetscCall(MatDestroy(&user.Sol)); PetscCall(MatDestroy(&B)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Free work space. All PETSc objects should be destroyed when they are no longer needed. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(VecDestroy(&user.wind_data)); PetscCall(VecDestroy(&user.t_wind)); PetscCall(MatDestroy(&A)); PetscCall(VecDestroy(&U)); PetscCall(TSDestroy(&ts)); PetscCall(PetscFinalize()); return 0; } /*TEST build: requires: !complex test: TEST*/
926bfc4b4352f170b23774da691dbc5fe52b8a8a
e3acfc4f06840e23ef1185dcf367f40d3e3f59b4
/tests/regression/05-lval_ls/19-idxunknown_unlock_precise.c
4b62b52cffb8667349f0b70385089f3d2d37d480
[ "MIT" ]
permissive
goblint/analyzer
d62d3c610b86ed288849371b41c330c30678abc7
69ee7163eef0bfbfd6a4f3b9fda7cea5ce9ab79f
refs/heads/master
2023-08-16T21:58:53.013737
2023-08-16T08:49:18
2023-08-16T08:49:18
2,066,905
141
62
MIT
2023-09-14T18:48:34
2011-07-18T15:10:56
OCaml
UTF-8
C
false
false
955
c
19-idxunknown_unlock_precise.c
// PARAM: --enable ana.int.interval // TODO because queries don't pass lvalue index intervals extern int __VERIFIER_nondet_int(); extern void abort(void); void assume_abort_if_not(int cond) { if(!cond) {abort();} } #include <pthread.h> #include <goblint.h> int data; pthread_mutexattr_t mutexattr; pthread_mutex_t m[10]; void *t_fun(void *arg) { pthread_mutex_lock(&m[4]); data++; // TODO NORACE pthread_mutex_unlock(&m[4]); return NULL; } int main() { pthread_mutexattr_init(&mutexattr); pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_ERRORCHECK); for (int i = 0; i < 10; i++) pthread_mutex_init(&m[i], &mutexattr); int i = __VERIFIER_nondet_int(); __goblint_assume(5 <= i); __goblint_assume(i < 10); pthread_t id; pthread_create(&id, NULL, t_fun, NULL); pthread_mutex_lock(&m[4]); pthread_mutex_unlock(&m[i]); // no UB because ERRORCHECK data++; // TODO NORACE pthread_mutex_unlock(&m[4]); return 0; }
df39a4244010f2a14d7ced62c527f138e07162fb
538c0655fc1fe95e6211b0faabb24457ebb762c3
/lib/winapi/fileapi.h
f855fc4418d29867b25c397698b4a00e6a99526f
[ "BSD-3-Clause", "CC0-1.0", "MIT" ]
permissive
XboxDev/nxdk
9151adf0450915335bfd6e1aec72c4adf0f82a2a
e955705ad7e5f59cdad456d0bd6680083d03758f
refs/heads/master
2023-09-01T19:37:29.013295
2023-07-02T17:43:25
2023-07-28T13:26:17
48,426,404
311
90
null
2023-08-11T08:15:37
2015-12-22T10:43:15
C
UTF-8
C
false
false
3,440
h
fileapi.h
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: 2019-2022 Stefan Schmidt // SPDX-FileCopyrightText: 2021 Erik Abair #ifndef __FILEAPI_H__ #define __FILEAPI_H__ #include <windef.h> #include <winbase.h> #include <winnt.h> #ifdef __cplusplus extern "C" { #endif DWORD GetFileAttributesA (LPCSTR lpFileName); BOOL GetFileAttributesExA (LPCSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, LPVOID lpFileInformation); BOOL SetFileAttributesA (LPCSTR lpFileName, DWORD dwFileAttributes); BOOL GetFileTime (HANDLE hFile, LPFILETIME lpCreationTime, LPFILETIME lpLastAccessTime, LPFILETIME lpLastWriteTime); BOOL SetFileTime (HANDLE hFile, const FILETIME *lpCreationTime, const FILETIME *lpLastAccessTime, const FILETIME *lpLastWriteTime); #define CREATE_NEW 1 #define CREATE_ALWAYS 2 #define OPEN_EXISTING 3 #define OPEN_ALWAYS 4 #define TRUNCATE_EXISTING 5 HANDLE CreateFileA (LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); BOOL ReadFile (HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped); BOOL WriteFile (HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped); BOOL SetEndOfFile (HANDLE hFile); DWORD SetFilePointer (HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh, DWORD dwMoveMethod); BOOL SetFilePointerEx (HANDLE hFile, LARGE_INTEGER liDistanceToMove, PLARGE_INTEGER lpNewFilePointer, DWORD dwMoveMethod); DWORD GetFileSize (HANDLE hFile, LPDWORD lpFileSizeHigh); BOOL GetFileSizeEx (HANDLE hFile, PLARGE_INTEGER lpFileSize); HANDLE FindFirstFileA (LPCSTR lpFileName, LPWIN32_FIND_DATAA lpFindFileData); BOOL FindNextFileA (HANDLE hFindFile, LPWIN32_FIND_DATAA lpFindFileData); BOOL FindClose (HANDLE hFindFile); BOOL DeleteFileA (LPCSTR lpFileName); BOOL RemoveDirectoryA (LPCSTR lpPathName); BOOL CreateDirectoryA (LPCSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes); BOOL MoveFileA (LPCSTR lpExistingFileName, LPCSTR lpNewFileName); BOOL CopyFileA (LPCSTR lpExistingFileName, LPCSTR lpNewFileName, BOOL bFailIfExists); BOOL GetDiskFreeSpaceExA (LPCSTR lpDirectoryName, PULARGE_INTEGER lpFreeBytesAvailableToCaller, PULARGE_INTEGER lpTotalNumberOfBytes, PULARGE_INTEGER lpTotalNumberOfFreeBytes); BOOL GetDiskFreeSpaceA (LPCSTR lpRootPathName, LPDWORD lpSectorsPerCluster, LPDWORD lpBytesPerSector, LPDWORD lpNumberOfFreeClusters, LPDWORD lpTotalNumberOfClusters); DWORD GetLogicalDrives (VOID); DWORD GetLogicalDriveStringsA (DWORD nBufferLength, LPSTR lpBuffer); #ifndef UNICODE #define GetFileAttributes GetFileAttributesA #define GetFileAttributesEx GetFileAttributesExA #define SetFileAttributes SetFileAttributesA #define CreateFile CreateFileA #define FindFirstFile FindFirstFileA #define FindNextFile FindNextFileA #define DeleteFile(...) DeleteFileA(__VA_ARGS__) #define RemoveDirectory(...) RemoveDirectoryA(__VA_ARGS__) #define CreateDirectory(...) CreateDirectoryA(__VA_ARGS__) #define MoveFile(...) MoveFileA(__VA_ARGS__) #define CopyFile(...) CopyFileA(__VA_ARGS__) #define GetDiskFreeSpaceEx GetDiskFreeSpaceExA #define GetDiskFreeSpace GetDiskFreeSpaceA #define GetLogicalDriveStrings GetLogicalDriveStringsA #else #error nxdk does not support the Unicode API #endif #ifdef __cplusplus } #endif #endif
3ccb55570dceb03c2b62a4a6a92d8d3e1b0d460a
e7e2ee02a1cd3e0229346855c9aa6d931e3ca1c4
/src/storage/channel/storage_channel_iouring.h
0e0ac0737640c1e87c145ff4cc5c84cfa68ffdff
[ "BSD-3-Clause" ]
permissive
danielealbano/cachegrand
7c2dd00424596796e52b62ca2e9eb107d06e0e5b
eb2df00feab7639a0327492c11a334a22dec7e60
refs/heads/main
2023-08-19T11:04:18.418711
2023-06-11T22:44:49
2023-06-11T22:44:49
125,234,630
904
33
BSD-3-Clause
2023-06-11T22:44:51
2018-03-14T15:33:02
C
UTF-8
C
false
false
734
h
storage_channel_iouring.h
#ifndef CACHEGRAND_STORAGE_CHANNEL_IOURING_H #define CACHEGRAND_STORAGE_CHANNEL_IOURING_H #ifdef __cplusplus extern "C" { #endif typedef struct storage_channel_iouring storage_channel_iouring_t; struct storage_channel_iouring { storage_channel_t wrapped_channel; storage_io_common_fd_t mapped_fd; bool has_mapped_fd; int base_sqe_flags; storage_io_common_fd_t fd; } __attribute__((__aligned__(32))); storage_channel_iouring_t* storage_channel_iouring_new(); storage_channel_iouring_t* storage_channel_iouring_multi_new( uint32_t count); void storage_channel_iouring_free( storage_channel_iouring_t* storage_channel); #ifdef __cplusplus } #endif #endif //CACHEGRAND_STORAGE_CHANNEL_IOURING_H
3d01e18201c3a551c050b41b65506ff73ec5957d
ea8fc70c7dbf49059431fa45a940742736c68fb8
/ext/image.c
fadff61f5e2ac48496708340504930e4f3838fda
[ "BSD-3-Clause" ]
permissive
dreamsxin/cphalcon7
1bd2194a251657b48857326927db69fef617ab91
1b8c6b04b4ca237a5ead87d4752df0d2e85c7a9d
refs/heads/master
2023-03-08T04:53:08.829432
2022-07-07T07:48:59
2022-07-07T07:48:59
47,245,335
298
73
null
2021-06-22T11:53:25
2015-12-02T07:44:43
C
UTF-8
C
false
false
6,687
c
image.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez <andres@phalconphp.com> | | Eduar Carvajal <eduar@phalconphp.com> | | ZhuZongXin <dreamsxin@qq.com> | +------------------------------------------------------------------------+ */ #include "image.h" #include "image/adapter/gd.h" #include "image/adapter/imagick.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/fcall.h" #include "kernel/object.h" #include "kernel/array.h" /** * Phalcon\Image * * Image manipulation support. Allows images to be resized, cropped, etc. * *<code> * $image = Phalcon\Image::factory("upload/test.jpg"); * $image->resize(200, 200); * $image->save(); *</code> */ zend_class_entry *phalcon_image_ce; PHP_METHOD(Phalcon_Image, factory); PHP_METHOD(Phalcon_Image, splitHexColor); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_image_factory, 0, 0, 1) ZEND_ARG_INFO(0, file) ZEND_ARG_INFO(0, width) ZEND_ARG_INFO(0, height) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_image_splithexcolor, 0, 0, 1) ZEND_ARG_TYPE_INFO(0, color, IS_STRING, 0) ZEND_END_ARG_INFO() static const zend_function_entry phalcon_image_method_entry[] = { PHP_ME(Phalcon_Image, factory, arginfo_phalcon_image_factory, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_ME(Phalcon_Image, splitHexColor, arginfo_phalcon_image_splithexcolor, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) PHP_FE_END }; /** * Phalcon\Image initializer */ PHALCON_INIT_CLASS(Phalcon_Image){ PHALCON_REGISTER_CLASS(Phalcon, Image, image, phalcon_image_method_entry, ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); /* Resizing constraints */ zend_declare_class_constant_long(phalcon_image_ce, SL("NONE"), PHALCON_IMAGE_NONE); zend_declare_class_constant_long(phalcon_image_ce, SL("WIDTH"), PHALCON_IMAGE_WIDTH); zend_declare_class_constant_long(phalcon_image_ce, SL("HEIGHT"), PHALCON_IMAGE_HEIGHT); zend_declare_class_constant_long(phalcon_image_ce, SL("AUTO"), PHALCON_IMAGE_AUTO); zend_declare_class_constant_long(phalcon_image_ce, SL("INVERSE"), PHALCON_IMAGE_INVERSE); zend_declare_class_constant_long(phalcon_image_ce, SL("PRECISE"), PHALCON_IMAGE_PRECISE); zend_declare_class_constant_long(phalcon_image_ce, SL("TENSILE"), PHALCON_IMAGE_TENSILE); zend_declare_class_constant_long(phalcon_image_ce, SL("NARROW"), PHALCON_IMAGE_NARROW); /* Flipping directions */ zend_declare_class_constant_long(phalcon_image_ce, SL("HORIZONTAL"), PHALCON_IMAGE_HORIZONTAL); zend_declare_class_constant_long(phalcon_image_ce, SL("VERTICAL"), PHALCON_IMAGE_VERTICAL); /* Driver: GD, ImageMagick, etc */ zend_declare_class_constant_long(phalcon_image_ce, SL("GD"), PHALCON_IMAGE_GD); zend_declare_class_constant_long(phalcon_image_ce, SL("IMAGICK"), PHALCON_IMAGE_IMAGICK); return SUCCESS; } /** * Loads an image and prepares it for manipulation * * @return Phalcon\Image\AdapterInterface **/ PHP_METHOD(Phalcon_Image, factory) { zval *file, *width = NULL, *height = NULL; phalcon_fetch_params(0, 1, 2, &file, &width, &height); if (!width) { width = &PHALCON_GLOBAL(z_null); } if (!height) { height = &PHALCON_GLOBAL(z_null); } if (phalcon_class_str_exists(SL("imagick"), 0) != NULL) { object_init_ex(return_value, phalcon_image_adapter_imagick_ce); PHALCON_CALL_METHOD(NULL, return_value, "__construct", file, width, height); } else { object_init_ex(return_value, phalcon_image_adapter_gd_ce); PHALCON_CALL_METHOD(NULL, return_value, "__construct", file, width, height); } } void str_repeat(zval *return_value, zend_string *input_str, zend_long mult) { zend_string *result; /* Resulting string */ size_t result_len; /* Length of the resulting string */ if (mult < 0) { return; } /* Don't waste our time if it's empty */ /* ... or if the multiplier is zero */ if (ZSTR_LEN(input_str) == 0 || mult == 0) RETURN_EMPTY_STRING(); /* Initialize the result string */ result = zend_string_safe_alloc(ZSTR_LEN(input_str), mult, 0, 0); result_len = ZSTR_LEN(input_str) * mult; /* Heavy optimization for situations where input string is 1 byte long */ if (ZSTR_LEN(input_str) == 1) { memset(ZSTR_VAL(result), *ZSTR_VAL(input_str), mult); } else { char *s, *e, *ee; ptrdiff_t l=0; memcpy(ZSTR_VAL(result), ZSTR_VAL(input_str), ZSTR_LEN(input_str)); s = ZSTR_VAL(result); e = ZSTR_VAL(result) + ZSTR_LEN(input_str); ee = ZSTR_VAL(result) + result_len; while (e<ee) { l = (e-s) < (ee-e) ? (e-s) : (ee-e); memmove(e, s, l); e += l; } } ZSTR_VAL(result)[result_len] = '\0'; RETURN_NEW_STR(result); } PHP_METHOD(Phalcon_Image, splitHexColor) { zval *str, newcolor = {}; unsigned int color[4]; const char *value; int len, count; phalcon_fetch_params(0, 1, 2, &str); len = Z_STRLEN_P(str); if(len < 6) { str_repeat(&newcolor, Z_STR_P(str), 6); } else { ZVAL_COPY(&newcolor, str); } value = Z_STRVAL(newcolor); if(len == 8) { count = sscanf(value, "%02x%02x%02x%02x%n", &color[0], &color[1], &color[2], &color[3], &len); if(count < 4 || len != 8) { RETVAL_FALSE; } else { array_init(return_value); phalcon_array_append_long(return_value, color[0], 0); phalcon_array_append_long(return_value, color[1], 0); phalcon_array_append_long(return_value, color[2], 0); phalcon_array_append_long(return_value, color[3], 0); } } else { count = sscanf(value, "%02x%02x%02x%n", &color[0], &color[1], &color[2], &len); if(count < 3 || len != 6) { RETVAL_FALSE; } else { array_init(return_value); phalcon_array_append_long(return_value, color[0], 0); phalcon_array_append_long(return_value, color[1], 0); phalcon_array_append_long(return_value, color[2], 0); } } zval_ptr_dtor(&newcolor); }
c829a6036d442e02c7771113d965d5e63017026b
d2253070a3a64b14dee5ca0b3d311919178e590c
/include/mystery_event_script.h
198a07e857078c5bafaa1b355f9a955b0b725dba
[]
no_license
pret/pokeemerald
ce232eccdde78502f3c251d672b26af3e1d7e508
d67914e114c937c4c80ce128ddc5523d4dc2cd40
refs/heads/master
2023-08-31T11:23:13.877932
2023-08-27T23:40:59
2023-08-27T23:40:59
43,677,244
1,944
1,903
null
2023-09-12T22:48:06
2015-10-05T10:09:22
C
UTF-8
C
false
false
483
h
mystery_event_script.h
#ifndef GUARD_MYSTERY_EVENT_SCRIPT_H #define GUARD_MYSTERY_EVENT_SCRIPT_H enum { MEVENT_STATUS_LOAD_OK, MEVENT_STATUS_LOAD_ERROR, MEVENT_STATUS_SUCCESS, MEVENT_STATUS_FAILURE, MEVENT_STATUS_FF = 0xFF }; void InitMysteryEventScriptContext(u8 *script); bool32 RunMysteryEventScriptContextCommand(u32 *status); u32 RunMysteryEventScript(u8 *script); void SetMysteryEventScriptStatus(u32 val); u16 GetRecordMixingGift(void); #endif // GUARD_MYSTERY_EVENT_SCRIPT_H
2a77118e988eb1c35f1b3770d1e5d111047cd2fb
e1cddfd754d952134e72dfd03522c5ea4fb6008e
/src/vnet/ip/ip_path_mtu.h
96a5227237a466418f119dd76538fe159a1745bc
[ "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
3,214
h
ip_path_mtu.h
/* *------------------------------------------------------------------ * ip_path_mtu.h * * Copyright (c) 2021 Graphiant. * 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/ip/ip.h> /** * @brief * The Path MTU DPO. interposed in the forwarding chain of the host prefix. */ typedef struct ip_pmtu_dpo_t_ { /** * The protocol of packets using this DPO */ dpo_proto_t ipm_proto; u8 __pad8; /** * Configured Path Mtu */ u16 ipm_pmtu; /** * number of locks. */ u16 ipm_locks; /** * Stacked DPO */ dpo_id_t ipm_dpo; } ip_pmtu_dpo_t; /* * PMTU DPOs are accessed in the data-path so they should not straddle a cache * line. Align to a integer factor of a cacheline */ STATIC_ASSERT_SIZEOF (ip_pmtu_dpo_t, 2 * sizeof (u64)); #define foreach_ip_pmtu_flag \ _ (ATTACHED, 0, "attached") \ _ (REMOTE, 1, "remote") \ _ (STALE, 2, "stale") typedef enum ip_pmtu_flags_t_ { #define _(a, b, c) IP_PMTU_FLAG_##a = (1 << b), foreach_ip_pmtu_flag #undef _ } ip_pmtu_flags_t; /** * Remote Path MTU tracking object */ typedef struct ip_pmtu_t_ { /** linkage into the FIB graph */ fib_node_t ipt_node; /** Track fib entry */ fib_node_index_t ipt_fib_entry; u32 ipt_sibling; ip_pmtu_flags_t ipt_flags; /** Configured MTU */ u16 ipt_cfg_pmtu; /** MTU from the parent MTU */ u16 ipt_parent_pmtu; /** operational MTU; the minimum value of the cfg and parent MTU */ u16 ipt_oper_pmtu; } ip_pmtu_t; extern int ip_path_mtu_update (const ip_address_t *nh, u32 table_id, u16 pmtu); typedef walk_rc_t (*ip_path_mtu_walk_t) (index_t ipti, void *ctx); extern void ip_path_mtu_walk (ip_path_mtu_walk_t fn, void *ctx); extern int ip_path_mtu_replace_begin (void); extern int ip_path_mtu_replace_end (void); extern u32 ip_pmtu_get_table_id (const ip_pmtu_t *ipt); extern void ip_pmtu_get_ip (const ip_pmtu_t *ipt, ip_address_t *ip); extern void ip_pmtu_dpo_add_or_lock (u16 pmtu, const dpo_id_t *parent, dpo_id_t *dpo); /** * Data-plane accessor functions */ extern ip_pmtu_dpo_t *ip_pmtu_dpo_pool; static_always_inline ip_pmtu_dpo_t * ip_pmtu_dpo_get (index_t index) { return (pool_elt_at_index (ip_pmtu_dpo_pool, index)); } extern ip_pmtu_t *ip_pmtu_pool; static_always_inline ip_pmtu_t * ip_path_mtu_get (index_t index) { return (pool_elt_at_index (ip_pmtu_pool, index)); } /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */
dfdfb0478b44d71dfaf2d4b2826256bd0aff06d5
1228123ee5ab4d6b470abc766f675f99fd268e01
/psutil/arch/windows/sensors.c
fbe2c2fe9fe4e5ca95ec753fc82f6d45747c1c55
[ "BSD-3-Clause" ]
permissive
giampaolo/psutil
43874920728aa689430a069f0eefbaa05a889262
77e5b7445748d30d22c0e3b2e651414da96a88b4
refs/heads/master
2023-09-03T17:48:12.048871
2023-08-07T06:49:18
2023-08-07T06:49:18
20,101,515
9,669
1,678
BSD-3-Clause
2023-09-13T09:18:00
2014-05-23T14:01:48
Python
UTF-8
C
false
false
895
c
sensors.c
/* * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <Python.h> #include <windows.h> // Added in https://github.com/giampaolo/psutil/commit/109f873 in 2017. // Moved in here in 2023. PyObject * psutil_sensors_battery(PyObject *self, PyObject *args) { SYSTEM_POWER_STATUS sps; if (GetSystemPowerStatus(&sps) == 0) { PyErr_SetFromWindowsErr(0); return NULL; } return Py_BuildValue( "iiiI", sps.ACLineStatus, // whether AC is connected: 0=no, 1=yes, 255=unknown // status flag: // 1, 2, 4 = high, low, critical // 8 = charging // 128 = no battery sps.BatteryFlag, sps.BatteryLifePercent, // percent sps.BatteryLifeTime // remaining secs ); }
2f25541ca4e693d3aaa7c4c272bf45a291406bd0
83b8b30ebb633eecd29ca0a7a20cc43a293c9333
/shared-bindings/synthio/Biquad.h
62b6c5843b53f2d5d0ad998328fd9ce21d83e857
[ "MIT", "GPL-1.0-or-later" ]
permissive
adafruit/circuitpython
430ec895149d1eb814b505db39b4977a35ee88a7
506dca71b0cbb7af749bb51f86b01021db5483b3
refs/heads/main
2023-08-21T16:30:46.781068
2023-08-20T00:39:44
2023-08-20T00:39:44
66,166,069
3,806
1,560
MIT
2023-09-14T19:23:51
2016-08-20T20:10:40
C
UTF-8
C
false
false
326
h
Biquad.h
#pragma once #include "py/obj.h" #include "py/objnamedtuple.h" extern const mp_obj_namedtuple_type_t synthio_biquad_type_obj; mp_obj_t common_hal_synthio_new_lpf(mp_float_t w0, mp_float_t Q); mp_obj_t common_hal_synthio_new_hpf(mp_float_t w0, mp_float_t Q); mp_obj_t common_hal_synthio_new_bpf(mp_float_t w0, mp_float_t Q);
5ba842d688baccbb36f27624ed274fa4035b5442
9ceacf33fd96913cac7ef15492c126d96cae6911
/sys/dev/usb/uvscom.c
66003c7b520de43c19cfe767ae8090785ac6ae09
[]
no_license
openbsd/src
ab97ef834fd2d5a7f6729814665e9782b586c130
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
refs/heads/master
2023-09-02T18:54:56.624627
2023-09-02T15:16:12
2023-09-02T15:16:12
66,966,208
3,394
1,235
null
2023-08-08T02:42:25
2016-08-30T18:18:25
C
UTF-8
C
false
false
19,341
c
uvscom.c
/* $OpenBSD: uvscom.c,v 1.42 2022/07/02 08:50:42 visa Exp $ */ /* $NetBSD: uvscom.c,v 1.9 2003/02/12 15:36:20 ichiro Exp $ */ /*- * Copyright (c) 2001-2002, Shunsuke Akiyama <akiyama@jp.FreeBSD.org>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/sys/dev/usb/uvscom.c,v 1.1 2002/03/18 18:23:39 joe Exp $ */ /* * uvscom: SUNTAC Slipper U VS-10U driver. * Slipper U is a PC card to USB converter for data communication card * adapter. It supports DDI Pocket's Air H" C@rd, C@rd H" 64, NTT's P-in, * P-in m@ater and various data communication card adapters. */ #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/malloc.h> #include <sys/fcntl.h> #include <sys/conf.h> #include <sys/tty.h> #include <sys/ioctl.h> #include <sys/device.h> #include <dev/usb/usb.h> #include <dev/usb/usbcdc.h> #include <dev/usb/usbdi.h> #include <dev/usb/usbdi_util.h> #include <dev/usb/usbdevs.h> #include <dev/usb/ucomvar.h> #ifdef UVSCOM_DEBUG static int uvscomdebug = 1; #define DPRINTFN(n, x) do { if (uvscomdebug > (n)) printf x; } while (0) #else #define DPRINTFN(n, x) #endif #define DPRINTF(x) DPRINTFN(0, x) #define UVSCOM_IFACE_INDEX 0 #define UVSCOM_INTR_INTERVAL 100 /* mS */ #define UVSCOM_UNIT_WAIT 5 /* Request */ #define UVSCOM_SET_SPEED 0x10 #define UVSCOM_LINE_CTL 0x11 #define UVSCOM_SET_PARAM 0x12 #define UVSCOM_READ_STATUS 0xd0 #define UVSCOM_SHUTDOWN 0xe0 /* UVSCOM_SET_SPEED parameters */ #define UVSCOM_SPEED_150BPS 0x00 #define UVSCOM_SPEED_300BPS 0x01 #define UVSCOM_SPEED_600BPS 0x02 #define UVSCOM_SPEED_1200BPS 0x03 #define UVSCOM_SPEED_2400BPS 0x04 #define UVSCOM_SPEED_4800BPS 0x05 #define UVSCOM_SPEED_9600BPS 0x06 #define UVSCOM_SPEED_19200BPS 0x07 #define UVSCOM_SPEED_38400BPS 0x08 #define UVSCOM_SPEED_57600BPS 0x09 #define UVSCOM_SPEED_115200BPS 0x0a /* UVSCOM_LINE_CTL parameters */ #define UVSCOM_BREAK 0x40 #define UVSCOM_RTS 0x02 #define UVSCOM_DTR 0x01 #define UVSCOM_LINE_INIT 0x08 /* UVSCOM_SET_PARAM parameters */ #define UVSCOM_DATA_MASK 0x03 #define UVSCOM_DATA_BIT_8 0x03 #define UVSCOM_DATA_BIT_7 0x02 #define UVSCOM_DATA_BIT_6 0x01 #define UVSCOM_DATA_BIT_5 0x00 #define UVSCOM_STOP_MASK 0x04 #define UVSCOM_STOP_BIT_2 0x04 #define UVSCOM_STOP_BIT_1 0x00 #define UVSCOM_PARITY_MASK 0x18 #define UVSCOM_PARITY_EVEN 0x18 #if 0 #define UVSCOM_PARITY_UNK 0x10 #endif #define UVSCOM_PARITY_ODD 0x08 #define UVSCOM_PARITY_NONE 0x00 /* Status bits */ #define UVSCOM_TXRDY 0x04 #define UVSCOM_RXRDY 0x01 #define UVSCOM_DCD 0x08 #define UVSCOM_NOCARD 0x04 #define UVSCOM_DSR 0x02 #define UVSCOM_CTS 0x01 #define UVSCOM_USTAT_MASK (UVSCOM_NOCARD | UVSCOM_DSR | UVSCOM_CTS) struct uvscom_softc { struct device sc_dev; /* base device */ struct usbd_device *sc_udev; /* USB device */ struct usbd_interface *sc_iface; /* interface */ struct usbd_interface *sc_intr_iface; /* interrupt interface */ int sc_intr_number; /* interrupt number */ struct usbd_pipe *sc_intr_pipe; /* interrupt pipe */ u_char *sc_intr_buf; /* interrupt buffer */ int sc_isize; u_char sc_dtr; /* current DTR state */ u_char sc_rts; /* current RTS state */ u_char sc_lsr; /* Local status register */ u_char sc_msr; /* uvscom status register */ uint16_t sc_lcr; /* Line control */ u_char sc_usr; /* unit status */ struct device *sc_subdev; /* ucom device */ }; /* * These are the maximum number of bytes transferred per frame. * The output buffer size cannot be increased due to the size encoding. */ #define UVSCOMIBUFSIZE 512 #define UVSCOMOBUFSIZE 64 usbd_status uvscom_readstat(struct uvscom_softc *); usbd_status uvscom_shutdown(struct uvscom_softc *); usbd_status uvscom_reset(struct uvscom_softc *); usbd_status uvscom_set_line_coding(struct uvscom_softc *, uint16_t, uint16_t); usbd_status uvscom_set_line(struct uvscom_softc *, uint16_t); usbd_status uvscom_set_crtscts(struct uvscom_softc *); void uvscom_get_status(void *, int, u_char *, u_char *); void uvscom_dtr(struct uvscom_softc *, int); void uvscom_rts(struct uvscom_softc *, int); void uvscom_break(struct uvscom_softc *, int); void uvscom_set(void *, int, int, int); void uvscom_intr(struct usbd_xfer *, void *, usbd_status); int uvscom_param(void *, int, struct termios *); int uvscom_open(void *, int); void uvscom_close(void *, int); const struct ucom_methods uvscom_methods = { uvscom_get_status, uvscom_set, uvscom_param, NULL, /* uvscom_ioctl, TODO */ uvscom_open, uvscom_close, NULL, NULL }; static const struct usb_devno uvscom_devs [] = { /* SUNTAC U-Cable type A3 */ { USB_VENDOR_SUNTAC, USB_PRODUCT_SUNTAC_AS64LX }, /* SUNTAC U-Cable type A4 */ { USB_VENDOR_SUNTAC, USB_PRODUCT_SUNTAC_AS144L4 }, /* SUNTAC U-Cable type D2 */ { USB_VENDOR_SUNTAC, USB_PRODUCT_SUNTAC_DS96L }, /* SUNTAC U-Cable type P1 */ { USB_VENDOR_SUNTAC, USB_PRODUCT_SUNTAC_PS64P1 }, /* SUNTAC Slipper U */ { USB_VENDOR_SUNTAC, USB_PRODUCT_SUNTAC_VS10U }, /* SUNTAC Ir-Trinity */ { USB_VENDOR_SUNTAC, USB_PRODUCT_SUNTAC_IS96U }, }; int uvscom_match(struct device *, void *, void *); void uvscom_attach(struct device *, struct device *, void *); int uvscom_detach(struct device *, int); struct cfdriver uvscom_cd = { NULL, "uvscom", DV_DULL }; const struct cfattach uvscom_ca = { sizeof(struct uvscom_softc), uvscom_match, uvscom_attach, uvscom_detach }; int uvscom_match(struct device *parent, void *match, void *aux) { struct usb_attach_arg *uaa = aux; if (uaa->iface == NULL) return (UMATCH_NONE); return (usb_lookup(uvscom_devs, uaa->vendor, uaa->product) != NULL ? UMATCH_VENDOR_PRODUCT : UMATCH_NONE); } void uvscom_attach(struct device *parent, struct device *self, void *aux) { struct uvscom_softc *sc = (struct uvscom_softc *)self; struct usb_attach_arg *uaa = aux; struct usbd_device *dev = uaa->device; usb_config_descriptor_t *cdesc; usb_interface_descriptor_t *id; usb_endpoint_descriptor_t *ed; const char *devname = sc->sc_dev.dv_xname; usbd_status err; int i; struct ucom_attach_args uca; sc->sc_udev = dev; DPRINTF(("uvscom attach: sc = %p\n", sc)); /* initialize endpoints */ uca.bulkin = uca.bulkout = -1; sc->sc_intr_number = -1; sc->sc_intr_pipe = NULL; /* get the config descriptor */ cdesc = usbd_get_config_descriptor(sc->sc_udev); if (cdesc == NULL) { printf("%s: failed to get configuration descriptor\n", sc->sc_dev.dv_xname); usbd_deactivate(sc->sc_udev); return; } /* get the common interface */ err = usbd_device2interface_handle(dev, UVSCOM_IFACE_INDEX, &sc->sc_iface); if (err) { printf("%s: failed to get interface, err=%s\n", devname, usbd_errstr(err)); usbd_deactivate(sc->sc_udev); return; } id = usbd_get_interface_descriptor(sc->sc_iface); /* Find endpoints */ for (i = 0; i < id->bNumEndpoints; i++) { ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i); if (ed == NULL) { printf("%s: no endpoint descriptor for %d\n", sc->sc_dev.dv_xname, i); usbd_deactivate(sc->sc_udev); return; } if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN && UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) { uca.bulkin = ed->bEndpointAddress; } else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT && UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) { uca.bulkout = ed->bEndpointAddress; } else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN && UE_GET_XFERTYPE(ed->bmAttributes) == UE_INTERRUPT) { sc->sc_intr_number = ed->bEndpointAddress; sc->sc_isize = UGETW(ed->wMaxPacketSize); } } if (uca.bulkin == -1) { printf("%s: Could not find data bulk in\n", sc->sc_dev.dv_xname); usbd_deactivate(sc->sc_udev); return; } if (uca.bulkout == -1) { printf("%s: Could not find data bulk out\n", sc->sc_dev.dv_xname); usbd_deactivate(sc->sc_udev); return; } if (sc->sc_intr_number == -1) { printf("%s: Could not find interrupt in\n", sc->sc_dev.dv_xname); usbd_deactivate(sc->sc_udev); return; } sc->sc_dtr = sc->sc_rts = 0; sc->sc_lcr = UVSCOM_LINE_INIT; uca.portno = UCOM_UNK_PORTNO; /* bulkin, bulkout set above */ uca.ibufsize = UVSCOMIBUFSIZE; uca.obufsize = UVSCOMOBUFSIZE; uca.ibufsizepad = UVSCOMIBUFSIZE; uca.opkthdrlen = 0; uca.device = dev; uca.iface = sc->sc_iface; uca.methods = &uvscom_methods; uca.arg = sc; uca.info = NULL; err = uvscom_reset(sc); if (err) { printf("%s: reset failed, %s\n", sc->sc_dev.dv_xname, usbd_errstr(err)); usbd_deactivate(sc->sc_udev); return; } DPRINTF(("uvscom: in = 0x%x out = 0x%x intr = 0x%x\n", ucom->sc_bulkin_no, ucom->sc_bulkout_no, sc->sc_intr_number)); DPRINTF(("uplcom: in=0x%x out=0x%x intr=0x%x\n", uca.bulkin, uca.bulkout, sc->sc_intr_number )); sc->sc_subdev = config_found_sm(self, &uca, ucomprint, ucomsubmatch); } int uvscom_detach(struct device *self, int flags) { struct uvscom_softc *sc = (struct uvscom_softc *)self; int rv = 0; DPRINTF(("uvscom_detach: sc = %p\n", sc)); if (sc->sc_intr_pipe != NULL) { usbd_close_pipe(sc->sc_intr_pipe); free(sc->sc_intr_buf, M_USBDEV, sc->sc_isize); sc->sc_intr_pipe = NULL; } if (sc->sc_subdev != NULL) { rv = config_detach(sc->sc_subdev, flags); sc->sc_subdev = NULL; } return (rv); } usbd_status uvscom_readstat(struct uvscom_softc *sc) { usb_device_request_t req; usbd_status err; uint16_t r; DPRINTF(("%s: send readstat\n", sc->sc_dev.dv_xname)); req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = UVSCOM_READ_STATUS; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, 2); err = usbd_do_request(sc->sc_udev, &req, &r); if (err) { printf("%s: uvscom_readstat: %s\n", sc->sc_dev.dv_xname, usbd_errstr(err)); return (err); } DPRINTF(("%s: uvscom_readstat: r = %d\n", sc->sc_dev.dv_xname, r)); return (USBD_NORMAL_COMPLETION); } usbd_status uvscom_shutdown(struct uvscom_softc *sc) { usb_device_request_t req; usbd_status err; DPRINTF(("%s: send shutdown\n", sc->sc_dev.dv_xname)); req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = UVSCOM_SHUTDOWN; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, 0); err = usbd_do_request(sc->sc_udev, &req, NULL); if (err) { printf("%s: uvscom_shutdown: %s\n", sc->sc_dev.dv_xname, usbd_errstr(err)); return (err); } return (USBD_NORMAL_COMPLETION); } usbd_status uvscom_reset(struct uvscom_softc *sc) { DPRINTF(("%s: uvscom_reset\n", sc->sc_dev.dv_xname)); return (USBD_NORMAL_COMPLETION); } usbd_status uvscom_set_crtscts(struct uvscom_softc *sc) { DPRINTF(("%s: uvscom_set_crtscts\n", sc->sc_dev.dv_xname)); return (USBD_NORMAL_COMPLETION); } usbd_status uvscom_set_line(struct uvscom_softc *sc, uint16_t line) { usb_device_request_t req; usbd_status err; DPRINTF(("%s: uvscom_set_line: %04x\n", sc->sc_dev.dv_xname, line)); req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = UVSCOM_LINE_CTL; USETW(req.wValue, line); USETW(req.wIndex, 0); USETW(req.wLength, 0); err = usbd_do_request(sc->sc_udev, &req, NULL); if (err) { printf("%s: uvscom_set_line: %s\n", sc->sc_dev.dv_xname, usbd_errstr(err)); return (err); } return (USBD_NORMAL_COMPLETION); } usbd_status uvscom_set_line_coding(struct uvscom_softc *sc, uint16_t lsp, uint16_t ls) { usb_device_request_t req; usbd_status err; DPRINTF(("%s: uvscom_set_line_coding: %02x %02x\n", sc->sc_dev.dv_xname, lsp, ls)); req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = UVSCOM_SET_SPEED; USETW(req.wValue, lsp); USETW(req.wIndex, 0); USETW(req.wLength, 0); err = usbd_do_request(sc->sc_udev, &req, NULL); if (err) { printf("%s: uvscom_set_line_coding: %s\n", sc->sc_dev.dv_xname, usbd_errstr(err)); return (err); } req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = UVSCOM_SET_PARAM; USETW(req.wValue, ls); USETW(req.wIndex, 0); USETW(req.wLength, 0); err = usbd_do_request(sc->sc_udev, &req, NULL); if (err) { printf("%s: uvscom_set_line_coding: %s\n", sc->sc_dev.dv_xname, usbd_errstr(err)); return (err); } return (USBD_NORMAL_COMPLETION); } void uvscom_dtr(struct uvscom_softc *sc, int onoff) { DPRINTF(("%s: uvscom_dtr: onoff = %d\n", sc->sc_dev.dv_xname, onoff)); if (sc->sc_dtr == onoff) return; /* no change */ sc->sc_dtr = onoff; if (onoff) SET(sc->sc_lcr, UVSCOM_DTR); else CLR(sc->sc_lcr, UVSCOM_DTR); uvscom_set_line(sc, sc->sc_lcr); } void uvscom_rts(struct uvscom_softc *sc, int onoff) { DPRINTF(("%s: uvscom_rts: onoff = %d\n", sc->sc_dev.dv_xname, onoff)); if (sc->sc_rts == onoff) return; /* no change */ sc->sc_rts = onoff; if (onoff) SET(sc->sc_lcr, UVSCOM_RTS); else CLR(sc->sc_lcr, UVSCOM_RTS); uvscom_set_line(sc, sc->sc_lcr); } void uvscom_break(struct uvscom_softc *sc, int onoff) { DPRINTF(("%s: uvscom_break: onoff = %d\n", sc->sc_dev.dv_xname, onoff)); if (onoff) uvscom_set_line(sc, SET(sc->sc_lcr, UVSCOM_BREAK)); } void uvscom_set(void *addr, int portno, int reg, int onoff) { struct uvscom_softc *sc = addr; switch (reg) { case UCOM_SET_DTR: uvscom_dtr(sc, onoff); break; case UCOM_SET_RTS: uvscom_rts(sc, onoff); break; case UCOM_SET_BREAK: uvscom_break(sc, onoff); break; default: break; } } int uvscom_param(void *addr, int portno, struct termios *t) { struct uvscom_softc *sc = addr; usbd_status err; uint16_t lsp; uint16_t ls; DPRINTF(("%s: uvscom_param: sc = %p\n", sc->sc_dev.dv_xname, sc)); ls = 0; switch (t->c_ospeed) { case B150: lsp = UVSCOM_SPEED_150BPS; break; case B300: lsp = UVSCOM_SPEED_300BPS; break; case B600: lsp = UVSCOM_SPEED_600BPS; break; case B1200: lsp = UVSCOM_SPEED_1200BPS; break; case B2400: lsp = UVSCOM_SPEED_2400BPS; break; case B4800: lsp = UVSCOM_SPEED_4800BPS; break; case B9600: lsp = UVSCOM_SPEED_9600BPS; break; case B19200: lsp = UVSCOM_SPEED_19200BPS; break; case B38400: lsp = UVSCOM_SPEED_38400BPS; break; case B57600: lsp = UVSCOM_SPEED_57600BPS; break; case B115200: lsp = UVSCOM_SPEED_115200BPS; break; default: return (EIO); } if (ISSET(t->c_cflag, CSTOPB)) SET(ls, UVSCOM_STOP_BIT_2); else SET(ls, UVSCOM_STOP_BIT_1); if (ISSET(t->c_cflag, PARENB)) { if (ISSET(t->c_cflag, PARODD)) SET(ls, UVSCOM_PARITY_ODD); else SET(ls, UVSCOM_PARITY_EVEN); } else SET(ls, UVSCOM_PARITY_NONE); switch (ISSET(t->c_cflag, CSIZE)) { case CS5: SET(ls, UVSCOM_DATA_BIT_5); break; case CS6: SET(ls, UVSCOM_DATA_BIT_6); break; case CS7: SET(ls, UVSCOM_DATA_BIT_7); break; case CS8: SET(ls, UVSCOM_DATA_BIT_8); break; default: return (EIO); } err = uvscom_set_line_coding(sc, lsp, ls); if (err) return (EIO); if (ISSET(t->c_cflag, CRTSCTS)) { err = uvscom_set_crtscts(sc); if (err) return (EIO); } return (0); } int uvscom_open(void *addr, int portno) { struct uvscom_softc *sc = addr; int err; int i; if (usbd_is_dying(sc->sc_udev)) return (EIO); DPRINTF(("uvscom_open: sc = %p\n", sc)); if (sc->sc_intr_number != -1 && sc->sc_intr_pipe == NULL) { DPRINTF(("uvscom_open: open interrupt pipe.\n")); sc->sc_usr = 0; /* clear unit status */ err = uvscom_readstat(sc); if (err) { DPRINTF(("%s: uvscom_open: readstat failed\n", sc->sc_dev.dv_xname)); return (EIO); } sc->sc_intr_buf = malloc(sc->sc_isize, M_USBDEV, M_WAITOK); err = usbd_open_pipe_intr(sc->sc_iface, sc->sc_intr_number, USBD_SHORT_XFER_OK, &sc->sc_intr_pipe, sc, sc->sc_intr_buf, sc->sc_isize, uvscom_intr, UVSCOM_INTR_INTERVAL); if (err) { printf("%s: cannot open interrupt pipe (addr %d)\n", sc->sc_dev.dv_xname, sc->sc_intr_number); return (EIO); } } else { DPRINTF(("uvscom_open: did not open interrupt pipe.\n")); } if ((sc->sc_usr & UVSCOM_USTAT_MASK) == 0) { /* unit is not ready */ for (i = UVSCOM_UNIT_WAIT; i > 0; --i) { tsleep_nsec(&err, TTIPRI, "uvsop", SEC_TO_NSEC(1)); if (ISSET(sc->sc_usr, UVSCOM_USTAT_MASK)) break; } if (i == 0) { DPRINTF(("%s: unit is not ready\n", sc->sc_dev.dv_xname)); return (EIO); } /* check PC card was inserted */ if (ISSET(sc->sc_usr, UVSCOM_NOCARD)) { DPRINTF(("%s: no card\n", sc->sc_dev.dv_xname)); return (EIO); } } return (0); } void uvscom_close(void *addr, int portno) { struct uvscom_softc *sc = addr; int err; if (usbd_is_dying(sc->sc_udev)) return; DPRINTF(("uvscom_close: close\n")); uvscom_shutdown(sc); if (sc->sc_intr_pipe != NULL) { err = usbd_close_pipe(sc->sc_intr_pipe); if (err) printf("%s: close interrupt pipe failed: %s\n", sc->sc_dev.dv_xname, usbd_errstr(err)); free(sc->sc_intr_buf, M_USBDEV, sc->sc_isize); sc->sc_intr_pipe = NULL; } } void uvscom_intr(struct usbd_xfer *xfer, void *priv, usbd_status status) { struct uvscom_softc *sc = priv; u_char *buf = sc->sc_intr_buf; u_char pstatus; if (usbd_is_dying(sc->sc_udev)) return; if (status != USBD_NORMAL_COMPLETION) { if (status == USBD_NOT_STARTED || status == USBD_CANCELLED) return; printf("%s: uvscom_intr: abnormal status: %s\n", sc->sc_dev.dv_xname, usbd_errstr(status)); usbd_clear_endpoint_stall_async(sc->sc_intr_pipe); return; } DPRINTFN(2, ("%s: uvscom status = %02x %02x\n", sc->sc_dev.dv_xname, buf[0], buf[1])); sc->sc_lsr = sc->sc_msr = 0; sc->sc_usr = buf[1]; pstatus = buf[0]; if (ISSET(pstatus, UVSCOM_TXRDY)) SET(sc->sc_lsr, ULSR_TXRDY); if (ISSET(pstatus, UVSCOM_RXRDY)) SET(sc->sc_lsr, ULSR_RXRDY); pstatus = buf[1]; if (ISSET(pstatus, UVSCOM_CTS)) SET(sc->sc_msr, UMSR_CTS); if (ISSET(pstatus, UVSCOM_DSR)) SET(sc->sc_msr, UMSR_DSR); if (ISSET(pstatus, UVSCOM_DCD)) SET(sc->sc_msr, UMSR_DCD); ucom_status_change((struct ucom_softc *) sc->sc_subdev); } void uvscom_get_status(void *addr, int portno, u_char *lsr, u_char *msr) { struct uvscom_softc *sc = addr; if (lsr != NULL) *lsr = sc->sc_lsr; if (msr != NULL) *msr = sc->sc_msr; }
70cdacdde2498c44cf599d163796b23eab1cbbda
2d18e8571c546087151e8e92502057b2a9b0ea54
/libyara/include/yara/compiler.h
8e48e327364c048b415c5028281e3aebd738eda2
[ "BSD-3-Clause" ]
permissive
plusvic/yara
681487ae3ca333566197c037af184c131ba1dac0
ed0c4a5f0c942dc9daf7b066e40c3dbadf17515a
refs/heads/master
2020-04-06T07:05:56.368518
2020-03-13T16:44:51
2020-03-13T16:44:51
60,647,515
164
48
BSD-3-Clause
2021-02-21T11:40:38
2016-06-07T21:25:11
C
UTF-8
C
false
false
12,233
h
compiler.h
/* Copyright (c) 2013. The YARA 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: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef YR_COMPILER_H #define YR_COMPILER_H #include <stdio.h> #include <setjmp.h> #include <yara/ahocorasick.h> #include <yara/arena.h> #include <yara/hash.h> #include <yara/utils.h> #include <yara/filemap.h> #define YARA_ERROR_LEVEL_ERROR 0 #define YARA_ERROR_LEVEL_WARNING 1 // Expression type constants are powers of two because they are used as flags. #define EXPRESSION_TYPE_UNKNOWN 0 #define EXPRESSION_TYPE_BOOLEAN 1 #define EXPRESSION_TYPE_INTEGER 2 #define EXPRESSION_TYPE_STRING 4 #define EXPRESSION_TYPE_REGEXP 8 #define EXPRESSION_TYPE_OBJECT 16 #define EXPRESSION_TYPE_FLOAT 32 // The compiler uses an arena to store the data it generates during the // compilation. Each buffer in the arena is used for storing a different type // of data. The following identifiers indicate the purpose of each buffer. #define YR_NAMESPACES_TABLE 0 #define YR_RULES_TABLE 1 #define YR_METAS_TABLE 2 #define YR_STRINGS_TABLE 3 #define YR_EXTERNAL_VARIABLES_TABLE 4 #define YR_SZ_POOL 5 #define YR_CODE_SECTION 6 #define YR_RE_CODE_SECTION 7 #define YR_AC_TRANSITION_TABLE 8 #define YR_AC_STATE_MATCHES_TABLE 9 #define YR_AC_STATE_MATCHES_POOL 10 #define YR_SUMMARY_SECTION 11 // This is the number of buffers used by the compiler, should match the number // of items in the list above. #define YR_NUM_SECTIONS 12 // Number of variables used by loops. This doesn't include user defined // variables. #define YR_INTERNAL_LOOP_VARS 3 typedef struct _YR_EXPRESSION { int type; union { int64_t integer; YR_OBJECT* object; SIZED_STRING* sized_string; } value; // An expression can have an associated identifier, if "ptr" is not NULL it // points to the identifier name, if it is NULL, then "ref" holds a reference // to the identifier within YR_SZ_POOL. When the identifier is in YR_SZ_POOL // a pointer can't be used as the YR_SZ_POOL can be moved to a different // memory location. struct { const char* ptr; YR_ARENA_REF ref; } identifier ; } YR_EXPRESSION; typedef void (*YR_COMPILER_CALLBACK_FUNC)( int error_level, const char* file_name, int line_number, const YR_RULE* rule, const char* message, void* user_data); typedef const char* (*YR_COMPILER_INCLUDE_CALLBACK_FUNC)( const char* include_name, const char* calling_rule_filename, const char* calling_rule_namespace, void* user_data); typedef void (*YR_COMPILER_INCLUDE_FREE_FUNC)( const char* callback_result_ptr, void* user_data); typedef void (*YR_COMPILER_RE_AST_CALLBACK_FUNC)( const YR_RULE* rule, const char* string_identifier, const RE_AST* re_ast, void* user_data); typedef struct _YR_FIXUP { YR_ARENA_REF ref; struct _YR_FIXUP* next; } YR_FIXUP; // Each "for" loop in the condition has an associated context which holds // information about loop, like the target address for the jump instruction // that goes back to the beginning of the loop and the local variables used // by the loop. typedef struct _YR_LOOP_CONTEXT { // Reference indicating the the place in the code where the loop starts. The // loop goes back to this address on each iteration. YR_ARENA_REF start_ref; // vars_count is the number of local variables defined by the loop, and vars // is an array of expressions with the identifier and type for each of those // local variables. int vars_count; YR_EXPRESSION vars[YR_MAX_LOOP_VARS]; // vars_internal_count is the number of variables used by the loop which are // not defined by the rule itself but that are necessary for keeping the // loop's state. One example is the iteration counter. int vars_internal_count; } YR_LOOP_CONTEXT; typedef struct _YR_COMPILER { // Arena that contains the data generated by the compiled. The arena has // the following buffers: // // YR_SUMMARY_SECTION: // A YR_SUMMARY struct. // YR_RULES_TABLE: // An array of YR_RULE structures, one per each rule. // YR_STRINGS_TABLE: // An array of YR_STRING structures, one per each string. // YR_METAS_TABLE: // An array of YR_META structures, one per each meta definition. // YR_NAMESPACES_TABLE: // An array of YR_NAMESPACE structures, one per each namespace. // YR_EXTERNAL_VARIABLES_TABLE: // An array of YR_EXTERNAL_VARIABLE structures, one per each external // variable defined. // YR_SZ_POOL: // A collection of null-terminated strings. This buffer contains // identifiers, literal strings, and in general any null-terminated // string referenced by other data structures. // YR_CODE_SECTION: // The code for the condition section of all the rules. This is the // code executed by yr_execute_code. // YR_RE_CODE_SECTION: // Similar to YR_CODE_SECTION, but it contains the code for regular // expressions. This is the code executed by yr_re_exec and // yr_re_fast_exec. // YR_AC_TRANSITION_TABLE: // An array of uint32_t containing the Aho-Corasick transition table. // See comment in _yr_ac_build_transition_table for details. // YR_AC_STATE_MATCHES_TABLE: // An array of uint32_t with the same number of items than the transition // table. If entry N in the transition table corresponds to some // Aho-Corasick state, the N-th item in this array has the index within // the matches pool where the list of matches for that state begins. // YR_AC_STATE_MATCHES_POOL: // An array of YR_AC_MATCH structures. // YR_ARENA* arena; // Index of the rule being compiled in the array of YR_RULE structures // stored in YR_RULES_TABLE. If this is MAX_UINT32 the compiler is not // parsing a rule. uint32_t current_rule_idx; // uint32_t next_rule_idx; // Index of the string being compiled in the array of YR_STRING structures // stored in YR_STRINGS_TABLE. uint32_t current_string_idx; // Index of the current namespace in the array of YR_NAMESPACE structures // stored in YR_NAMESPACES_TABLE. uint32_t current_namespace_idx; // Pointer to a YR_RULES structure that represents the compiled rules. This // is what yr_compiler_get_rules returns. Once these rules are generated you // can't call any of the yr_compiler_add_xxx functions. YR_RULES* rules; int errors; int current_line; int last_error; int last_error_line; jmp_buf error_recovery; YR_AC_AUTOMATON* automaton; YR_HASH_TABLE* rules_table; YR_HASH_TABLE* objects_table; YR_HASH_TABLE* strings_table; YR_FIXUP* fixup_stack_head; int num_namespaces; YR_LOOP_CONTEXT loop[YR_MAX_LOOP_NESTING]; int loop_index; int loop_for_of_var_index; char* file_name_stack[YR_MAX_INCLUDE_DEPTH]; int file_name_stack_ptr; char last_error_extra_info[YR_MAX_COMPILER_ERROR_EXTRA_INFO]; char lex_buf[YR_LEX_BUF_SIZE]; char* lex_buf_ptr; unsigned short lex_buf_len; char include_base_dir[MAX_PATH]; void* user_data; void* incl_clbk_user_data; void* re_ast_clbk_user_data; YR_COMPILER_CALLBACK_FUNC callback; YR_COMPILER_INCLUDE_CALLBACK_FUNC include_callback; YR_COMPILER_INCLUDE_FREE_FUNC include_free; YR_COMPILER_RE_AST_CALLBACK_FUNC re_ast_callback; YR_ATOMS_CONFIG atoms_config; } YR_COMPILER; #define yr_compiler_set_error_extra_info(compiler, info) \ strlcpy( \ compiler->last_error_extra_info, \ info, \ sizeof(compiler->last_error_extra_info)); \ #define yr_compiler_set_error_extra_info_fmt(compiler, fmt, ...) \ snprintf( \ compiler->last_error_extra_info, \ sizeof(compiler->last_error_extra_info), \ fmt, __VA_ARGS__); int _yr_compiler_push_file_name( YR_COMPILER* compiler, const char* file_name); void _yr_compiler_pop_file_name( YR_COMPILER* compiler); int _yr_compiler_get_var_frame( YR_COMPILER* compiler); const char* _yr_compiler_default_include_callback( const char* include_name, const char* calling_rule_filename, const char* calling_rule_namespace, void* user_data); YR_RULE* _yr_compiler_get_rule_by_idx( YR_COMPILER* compiler, uint32_t rule_idx); YR_API int yr_compiler_create( YR_COMPILER** compiler); YR_API void yr_compiler_destroy( YR_COMPILER* compiler); YR_API void yr_compiler_set_callback( YR_COMPILER* compiler, YR_COMPILER_CALLBACK_FUNC callback, void* user_data); YR_API void yr_compiler_set_include_callback( YR_COMPILER* compiler, YR_COMPILER_INCLUDE_CALLBACK_FUNC include_callback, YR_COMPILER_INCLUDE_FREE_FUNC include_free, void* user_data); YR_API void yr_compiler_set_re_ast_callback( YR_COMPILER* compiler, YR_COMPILER_RE_AST_CALLBACK_FUNC re_ast_callback, void* user_data); YR_API void yr_compiler_set_atom_quality_table( YR_COMPILER* compiler, const void* table, int entries, unsigned char warning_threshold); YR_API int yr_compiler_load_atom_quality_table( YR_COMPILER* compiler, const char* filename, unsigned char warning_threshold); YR_API int yr_compiler_add_file( YR_COMPILER* compiler, FILE* rules_file, const char* namespace_, const char* file_name); YR_API int yr_compiler_add_fd( YR_COMPILER* compiler, YR_FILE_DESCRIPTOR rules_fd, const char* namespace_, const char* file_name); YR_API int yr_compiler_add_string( YR_COMPILER* compiler, const char* rules_string, const char* namespace_); YR_API char* yr_compiler_get_error_message( YR_COMPILER* compiler, char* buffer, int buffer_size); YR_API char* yr_compiler_get_current_file_name( YR_COMPILER* compiler); YR_API int yr_compiler_define_integer_variable( YR_COMPILER* compiler, const char* identifier, int64_t value); YR_API int yr_compiler_define_boolean_variable( YR_COMPILER* compiler, const char* identifier, int value); YR_API int yr_compiler_define_float_variable( YR_COMPILER* compiler, const char* identifier, double value); YR_API int yr_compiler_define_string_variable( YR_COMPILER* compiler, const char* identifier, const char* value); YR_API int yr_compiler_get_rules( YR_COMPILER* compiler, YR_RULES** rules); #endif
6426654c9a904b8db90cba563c6124e4ff6ffe55
06052ccd6db697947c1fcbb6ac96eba79c057fea
/lambdaLayers/SharpLayer/nodejs/node_modules/sharp/vendor/8.10.6/include/orc-0.4/orc/orc-stdint.h
599b33ae09f8d10ff27b888f9c42986f208a116b
[ "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
46
h
orc-stdint.h
/* This file is intentionally nearly empty */
c1239f9e5583b58e88f7ad2fea8299f10da56c7f
27abcab06ef2c704347eef38477b9e15b8e94cb6
/atomic.h
ea5704f0c9ea2610776e96519f73c6818f4c1368
[ "MIT" ]
permissive
travisdowns/avx-turbo
b5d439abb6dcf088b3bb62030b2b2507b9fb97f5
4a04a454feedb6402cd9d85fa6fda4d9c7ba47b4
refs/heads/master
2023-05-31T23:33:47.143323
2021-10-27T17:45:39
2021-10-27T17:45:39
145,263,040
155
19
MIT
2023-05-15T08:44:15
2018-08-19T01:01:28
C++
UTF-8
C
false
false
13,597
h
atomic.h
/* Atomic operations (v1) * Portable Snippets - https://gitub.com/nemequ/portable-snippets * Created by Evan Nemerson <evan@nemerson.com> * * To the extent possible under law, the authors have waived all * copyright and related or neighboring rights to this code. For * details, see the Creative Commons Zero 1.0 Universal license at * https://creativecommons.org/publicdomain/zero/1.0/ * * This is a small abstraction layer for some common atomic operations * (load, store, add, subtract, and compare & swap) implemented using * various compiler-specific builtins. * * There are four types, 32-bit and 64-bit integers which are both * atomic and non-atomic. The atomic versions should be used for the * atomic variable, the non-atomic variables should be used to store * values read from or written to an atomic variable. For example, a * basic CAS loop: * * void square_dest(psnip_atomic_int64* value) { * psnip_int64_t expected; * do { * expected = psnip_atomic_int64_load(&value); * } while (!psnip_atomic_int64_compare_exchange(&value, &expected, expected * expected)); * } * * Most things are implemented with the preprocessor, but if they were * functions the prototypes (the 64-bit versions, just s/64/32/ for * the 32-bit versions) would loo like: * * psnip_int64_t psnip_atomic_int64_load( * psnip_atomic_int64* object); * void psnip_atomic_int64_store( * psnip_atomic_int64* object, * psnip_int64_t desired); * _Bool psnip_atomic_int64_compare_exchange( * psnip_atomic_int64* object, * psnip_int64_t* expected, * psnip_int64_t desired); * psnip_int64_t psnip_atomic_int64_add( * psnip_atomic_int64* object, * psnip_int64_t operand); * psnip_int64_t psnip_atomic_int64_sub( * psnip_atomic_int64* object, * psnip_int64_t operand); */ #if !defined(PSNIP_ATOMIC_H) #define PSNIP_ATOMIC_H #if !defined(psnip_int64_t) || !defined(psnip_int32_t) # include "exact-int.h" #endif #if !defined(PSNIP_ATOMIC_STATIC_INLINE) # if defined(__GNUC__) # define PSNIP_ATOMIC__COMPILER_ATTRIBUTES __attribute__((__unused__)) # else # define PSNIP_ATOMIC__COMPILER_ATTRIBUTES # endif # if defined(HEDLEY_INLINE) # define PSNIP_ATOMIC__INLINE HEDLEY_INLINE # elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L # define PSNIP_ATOMIC__INLINE inline # elif defined(__GNUC_STDC_INLINE__) # define PSNIP_ATOMIC__INLINE __inline__ # elif defined(_MSC_VER) && _MSC_VER >= 1200 # define PSNIP_ATOMIC__INLINE __inline # else # define PSNIP_ATOMIC__INLINE # endif # define PSNIP_ATOMIC__FUNCTION PSNIP_ATOMIC__COMPILER_ATTRIBUTES static PSNIP_ATOMIC__INLINE #endif #if defined(__has_feature) # define PSNIP_ATOMIC_HAS_FEATURE(feature) __has_feature(feature) #else # define PSNIP_ATOMIC_HAS_FEATURE(feature) 0 #endif #define PSNIP_ATOMIC_IMPL_NONE 0 #define PSNIP_ATOMIC_IMPL_GCC 1 #define PSNIP_ATOMIC_IMPL_GCC_SYNC 2 #define PSNIP_ATOMIC_IMPL_CLANG 3 #define PSNIP_ATOMIC_IMPL_MS 4 #define PSNIP_ATOMIC_IMPL_OPENMP 5 #define PSNIP_ATOMIC_IMPL_C11 11 #if defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)) # define PSNIP_ATOMIC_IMPL PSNIP_ATOMIC_IMPL_GCC #elif !defined(__INTEL_COMPILER) && defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(__STDC_NO_ATOMICS__) /* GCC 4.7 and 4.8 sets __STDC_VERSION__ to C11 (if compiling in C11 * mode) and didn't have stdatomic.h, but failed to set * __STDC_NO_ATOMICS__. Verions prior to 4.7 didn't set * __STDC_VERSION__ to C11. */ # if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ < 9) # define PSNIP_ATOMIC_IMPL PSNIP_ATOMIC_IMPL_GCC # else # define PSNIP_ATOMIC_IMPL PSNIP_ATOMIC_IMPL_C11 # endif #elif defined(_MSC_VER) # define PSNIP_ATOMIC_IMPL PSNIP_ATOMIC_IMPL_MS #elif defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)) # define PSNIP_ATOMIC_IMPL PSNIP_ATOMIC_IMPL_GCC #elif PSNIP_ATOMIC_HAS_FEATURE(c_atomic) # define PSNIP_ATOMIC_IMPL PSNIP_ATOMIC_IMPL_CLANG #elif defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) # define PSNIP_ATOMIC_IMPL PSNIP_ATOMIC_IMPL_GCC_SYNC #elif (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x5140)) || (defined(__SUNPRO_CC) && (__SUNPRO_CC >= 0x5140)) # define PSNIP_ATOMIC_IMPL PSNIP_ATOMIC_IMPL_GCC #elif defined(_OPENMP) # define PSNIP_ATOMIC_IMPL PSNIP_ATOMIC_IMPL_OPENMP #else # define PSNIP_ATOMIC_NOT_FOUND # define PSNIP_ATOMIC_IMPL PSNIP_ATOMIC_IMPL_NONE # warning No atomic implementation found #endif #if !defined(PSNIP_ATOMIC_NOT_FOUND) #if PSNIP_ATOMIC_IMPL == PSNIP_ATOMIC_IMPL_C11 #include <stdatomic.h> typedef atomic_int_fast64_t psnip_atomic_int64; typedef atomic_int_fast32_t psnip_atomic_int32; #define PSNIP_ATOMIC_VAR_INIT(value) ATOMIC_VAR_INIT(value) #define psnip_atomic_int64_load(object) \ atomic_load(object) #define psnip_atomic_int64_store(object, desired) \ atomic_store(object, desired) #define psnip_atomic_int64_compare_exchange(object, expected, desired) \ atomic_compare_exchange_strong(object, expected, desired) #define psnip_atomic_int64_add(object, operand) \ atomic_fetch_add(object, operand) #define psnip_atomic_int64_sub(object, operand) \ atomic_fetch_sub(object, operand) #define psnip_atomic_fence() \ atomic_thread_fence(memory_order_seq_cst) #define PSNIP_ATOMIC_IS_TG #elif PSNIP_ATOMIC_IMPL == PSNIP_ATOMIC_IMPL_CLANG #include <stdint.h> typedef _Atomic psnip_int64_t psnip_atomic_int64; typedef _Atomic psnip_int32_t psnip_atomic_int32; #define psnip_atomic_int64_load(object) \ __c11_atomic_load(object, __ATOMIC_SEQ_CST) #define psnip_atomic_int64_store(object, desired) \ __c11_atomic_store(object, desired, __ATOMIC_SEQ_CST) #define psnip_atomic_int64_compare_exchange(object, expected, desired) \ __c11_atomic_compare_exchange_strong(object, expected, desired, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) #define psnip_atomic_int64_add(object, operand) \ __c11_atomic_fetch_add(object, operand, __ATOMIC_SEQ_CST) #define psnip_atomic_int64_sub(object, operand) \ __c11_atomic_fetch_sub(object, operand, __ATOMIC_SEQ_CST) #define psnip_atomic_fence() \ __c11_atomic_thread_fence(__ATOMIC_SEQ_CST) #define PSNIP_ATOMIC_IS_TG #elif PSNIP_ATOMIC_IMPL == PSNIP_ATOMIC_IMPL_GCC #include <stdint.h> #if !defined(__INTEL_COMPILER) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9)) && !defined(_OPENMP) typedef _Atomic psnip_int64_t psnip_atomic_int64; typedef _Atomic psnip_int32_t psnip_atomic_int32; #else typedef psnip_int64_t psnip_atomic_int64; typedef psnip_int32_t psnip_atomic_int32; #endif #define psnip_atomic_int64_load(object) \ __atomic_load_n(object, __ATOMIC_SEQ_CST) #define psnip_atomic_int64_store(object, desired) \ __atomic_store_n(object, desired, __ATOMIC_SEQ_CST) #define psnip_atomic_int64_compare_exchange(object, expected, desired) \ __atomic_compare_exchange_n(object, expected, desired, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) #define psnip_atomic_int64_add(object, operand) \ __atomic_add_fetch(object, operand, __ATOMIC_SEQ_CST) #define psnip_atomic_int64_sub(object, operand) \ __atomic_sub_fetch(object, operand, __ATOMIC_SEQ_CST) #define psnip_atomic_fence() \ __atomic_thread_fence(__ATOMIC_SEQ_CST) #define PSNIP_ATOMIC_IS_TG #elif PSNIP_ATOMIC_IMPL == PSNIP_ATOMIC_IMPL_GCC_SYNC #include <stdint.h> typedef psnip_int64_t psnip_atomic_int64; typedef psnip_int32_t psnip_atomic_int32; PSNIP_ATOMIC__FUNCTION psnip_int64_t psnip_atomic_int64_load(psnip_atomic_int64* object) { __sync_synchronize(); return (psnip_int64_t) *object; } PSNIP_ATOMIC__FUNCTION void psnip_atomic_int64_store(psnip_atomic_int64* object, psnip_int64_t desired) { *object = desired; __sync_synchronize(); } #define psnip_atomic_int64_compare_exchange(object, expected, desired) \ __sync_bool_compare_and_swap(object, *(expected), desired) #define psnip_atomic_int64_add(object, operand) \ __sync_fetch_and_add(object, operand) #define psnip_atomic_int64_sub(object, operand) \ __sync_fetch_and_sub(object, operand) PSNIP_ATOMIC__FUNCTION psnip_int32_t psnip_atomic_int32_load(psnip_atomic_int32* object) { __sync_synchronize(); return (psnip_int32_t) *object; } PSNIP_ATOMIC__FUNCTION void psnip_atomic_int32_store(psnip_atomic_int32* object, psnip_int32_t desired) { *object = desired; __sync_synchronize(); } #define psnip_atomic_int32_compare_exchange(object, expected, desired) \ __sync_bool_compare_and_swap(object, *(expected), desired) #define psnip_atomic_int32_add(object, operand) \ __sync_fetch_and_add(object, operand) #define psnip_atomic_int32_sub(object, operand) \ __sync_fetch_and_sub(object, operand) #define psnip_atomic_fence() \ __sync_synchronize() #elif PSNIP_ATOMIC_IMPL == PSNIP_ATOMIC_IMPL_MS #include <Windows.h> typedef long long volatile psnip_atomic_int64; typedef long volatile psnip_atomic_int32; #define psnip_atomic_int32_load(object) \ __pragma(warning(push)) \ __pragma(warning(disable:28112)) \ (*(object)) \ __pragma(warning(pop)) #define psnip_atomic_int32_store(object, desired) \ InterlockedExchange(object, desired) #define psnip_atomic_int32_compare_exchange(object, expected, desired) \ InterlockedCompareExchange(object, desired, *(expected)) #define psnip_atomic_int32_add(object, operand) \ InterlockedExchangeAdd(object, operand) #define psnip_atomic_int32_sub(object, operand) \ InterlockedExchangeAdd(object, -(operand)) #define psnip_atomic_int64_load(object) \ __pragma(warning(push)) \ __pragma(warning(disable:28112)) \ (*(object)) \ __pragma(warning(pop)) #define psnip_atomic_int64_store(object, desired) \ InterlockedExchange64(object, desired) #define psnip_atomic_int64_compare_exchange(object, expected, desired) \ InterlockedCompareExchange64(object, desired, *(expected)) #define psnip_atomic_int64_add(object, operand) \ InterlockedExchangeAdd64(object, operand) #define psnip_atomic_int64_sub(object, operand) \ InterlockedExchangeAdd64(object, -(operand)) #define psnip_atomic_fence() \ MemoryBarrier() #elif PSNIP_ATOMIC_IMPL == PSNIP_ATOMIC_IMPL_OPENMP #include <stdint.h> typedef psnip_int64_t psnip_atomic_int64; typedef psnip_int32_t psnip_atomic_int32; PSNIP_ATOMIC__FUNCTION psnip_int64_t psnip_atomic_int64_load(psnip_atomic_int64* object) { psnip_int64_t ret; #pragma omp critical(psnip_atomic) ret = *object; return ret; } PSNIP_ATOMIC__FUNCTION void psnip_atomic_int64_store(psnip_atomic_int64* object, psnip_int64_t desired) { #pragma omp critical(psnip_atomic) *object = desired; } PSNIP_ATOMIC__FUNCTION int psnip_atomic_int64_compare_exchange_(psnip_atomic_int64* object, psnip_int64_t* expected, psnip_int64_t desired) { int ret; #pragma omp critical(psnip_atomic) ret = (*object == *expected) ? ((*object = desired), 1) : 0; return ret; } #define psnip_atomic_int64_compare_exchange(object, expected, desired) \ psnip_atomic_int64_compare_exchange_(object, expected, desired) PSNIP_ATOMIC__FUNCTION psnip_int64_t psnip_atomic_int64_add(psnip_atomic_int64* object, psnip_int64_t operand) { int ret; #pragma omp critical(psnip_atomic) *object = (ret = *object) + operand; return ret; } PSNIP_ATOMIC__FUNCTION psnip_int64_t psnip_atomic_int64_sub(psnip_atomic_int64* object, psnip_int64_t operand) { int ret; #pragma omp critical(psnip_atomic) *object = (ret = *object) - operand; return ret; } PSNIP_ATOMIC__FUNCTION psnip_int32_t psnip_atomic_int32_load(psnip_atomic_int32* object) { psnip_int32_t ret; #pragma omp critical(psnip_atomic) ret = *object; return ret; } PSNIP_ATOMIC__FUNCTION void psnip_atomic_int32_store(psnip_atomic_int32* object, psnip_int32_t desired) { #pragma omp critical(psnip_atomic) *object = desired; } PSNIP_ATOMIC__FUNCTION int psnip_atomic_int32_compare_exchange_(psnip_atomic_int32* object, psnip_int32_t* expected, psnip_int32_t desired) { int ret = 1; #pragma omp critical(psnip_atomic) ret = (*object == *expected) ? ((*object = desired), 1) : 0; return ret; } #define psnip_atomic_int32_compare_exchange(object, expected, desired) \ psnip_atomic_int32_compare_exchange_(object, expected, desired) PSNIP_ATOMIC__FUNCTION psnip_int32_t psnip_atomic_int32_add(psnip_atomic_int32* object, psnip_int32_t operand) { int ret; #pragma omp critical(psnip_atomic) *object = (ret = *object) + operand; return ret; } PSNIP_ATOMIC__FUNCTION psnip_int32_t psnip_atomic_int32_sub(psnip_atomic_int32* object, psnip_int32_t operand) { int ret; #pragma omp critical(psnip_atomic) *object = (ret = *object) - operand; return ret; } PSNIP_ATOMIC__FUNCTION void psnip_atomic_fence() { #pragma omp critical(psnip_atomic) { } } #endif #if !defined(PSNIP_ATOMIC_VAR_INIT) # define PSNIP_ATOMIC_VAR_INIT(value) (value) #endif /* Most compilers have type-generic atomic implementations. */ #if defined(PSNIP_ATOMIC_IS_TG) #define psnip_atomic_int32_load(object) \ psnip_atomic_int64_load(object) #define psnip_atomic_int32_store(object, desired) \ psnip_atomic_int64_store(object, desired) #define psnip_atomic_int32_compare_exchange(object, expected, desired) \ psnip_atomic_int64_compare_exchange(object, expected, desired) #define psnip_atomic_int32_add(object, operand) \ psnip_atomic_int64_add(object, operand) #define psnip_atomic_int32_sub(object, operand) \ psnip_atomic_int64_sub(object, operand) #endif /* defined(PSNIP_ATOMIC_IS_TG) */ #endif /* !defined(PSNIP_ATOMIC_NOT_FOUND) */ #endif /* defined(PSNIP_ATOMIC_H) */
cee8a82807dea628529630f8554514ea9dc6ea0e
9ceacf33fd96913cac7ef15492c126d96cae6911
/lib/libkvm/kvm_amd64.c
72582ab1751fcff932198012bd295a30be7e14e2
[]
no_license
openbsd/src
ab97ef834fd2d5a7f6729814665e9782b586c130
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
refs/heads/master
2023-09-02T18:54:56.624627
2023-09-02T15:16:12
2023-09-02T15:16:12
66,966,208
3,394
1,235
null
2023-08-08T02:42:25
2016-08-30T18:18:25
C
UTF-8
C
false
false
5,496
c
kvm_amd64.c
/* $OpenBSD: kvm_amd64.c,v 1.16 2023/03/08 04:43:05 guenther Exp $ */ /* $NetBSD: kvm_x86_64.c,v 1.3 2002/06/05 22:01:55 fvdl Exp $ */ /*- * Copyright (c) 1989, 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software developed by the Computer Systems * Engineering group at Lawrence Berkeley Laboratory under DARPA contract * BG 91-66 and contributed to Berkeley. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * x86-64 machine dependent routines for kvm. */ #include <sys/types.h> #include <sys/signal.h> #include <sys/proc.h> #include <sys/stat.h> #include <sys/kcore.h> #include <machine/kcore.h> #include <stdlib.h> #include <unistd.h> #include <nlist.h> #include <kvm.h> #include <uvm/uvm_extern.h> #include <limits.h> #include <db.h> #include "kvm_private.h" #include <machine/pmap.h> #include <machine/pte.h> #include <machine/vmparam.h> void _kvm_freevtop(kvm_t *kd) { /* Not actually used for anything right now, but safe. */ free(kd->vmst); kd->vmst = NULL; } int _kvm_initvtop(kvm_t *kd) { return (0); } /* * Translate a kernel virtual address to a physical address. */ int _kvm_kvatop(kvm_t *kd, u_long va, paddr_t *pa) { cpu_kcore_hdr_t *cpu_kh; paddr_t pde_pa, pte_pa; u_long page_off; pd_entry_t pde; pt_entry_t pte; if (ISALIVE(kd)) { _kvm_err(kd, 0, "vatop called in live kernel!"); return (0); } page_off = va & (kd->nbpg - 1); if (va >= PMAP_DIRECT_BASE && va <= PMAP_DIRECT_END) { *pa = va - PMAP_DIRECT_BASE; return (int)(kd->nbpg - page_off); } cpu_kh = kd->cpu_data; /* * Find and read all entries to get to the pa. */ /* * Level 4. */ pde_pa = cpu_kh->ptdpaddr + (pl4_pi(va) * sizeof(pd_entry_t)); if (pread(kd->pmfd, (void *)&pde, sizeof(pde), _kvm_pa2off(kd, pde_pa)) != sizeof(pde)) { _kvm_syserr(kd, 0, "could not read PT level 4 entry"); goto lose; } if ((pde & PG_V) == 0) { _kvm_err(kd, 0, "invalid translation (invalid level 4 PDE)"); goto lose; } /* * Level 3. */ pde_pa = (pde & PG_FRAME) + (pl3_pi(va) * sizeof(pd_entry_t)); if (pread(kd->pmfd, (void *)&pde, sizeof(pde), _kvm_pa2off(kd, pde_pa)) != sizeof(pde)) { _kvm_syserr(kd, 0, "could not read PT level 3 entry"); goto lose; } if ((pde & PG_V) == 0) { _kvm_err(kd, 0, "invalid translation (invalid level 3 PDE)"); goto lose; } /* * Level 2. */ pde_pa = (pde & PG_FRAME) + (pl2_pi(va) * sizeof(pd_entry_t)); if (pread(kd->pmfd, (void *)&pde, sizeof(pde), _kvm_pa2off(kd, pde_pa)) != sizeof(pde)) { _kvm_syserr(kd, 0, "could not read PT level 2 entry"); goto lose; } if ((pde & PG_V) == 0) { _kvm_err(kd, 0, "invalid translation (invalid level 2 PDE)"); goto lose; } /* * Might be a large page. */ if ((pde & PG_PS) != 0) { page_off = va & (NBPD_L2 - 1); *pa = (pde & PG_LGFRAME) | page_off; return (int)(NBPD_L2 - page_off); } /* * Level 1. */ pte_pa = (pde & PG_FRAME) + (pl1_pi(va) * sizeof(pt_entry_t)); if (pread(kd->pmfd, (void *) &pte, sizeof(pte), _kvm_pa2off(kd, pte_pa)) != sizeof(pte)) { _kvm_syserr(kd, 0, "could not read PTE"); goto lose; } /* * Validate the PTE and return the physical address. */ if ((pte & PG_V) == 0) { _kvm_err(kd, 0, "invalid translation (invalid PTE)"); goto lose; } *pa = (pte & PG_FRAME) + page_off; return (int)(kd->nbpg - page_off); lose: *pa = (u_long)~0L; return (0); } /* * Translate a physical address to a file-offset in the crash dump. */ off_t _kvm_pa2off(kvm_t *kd, paddr_t pa) { cpu_kcore_hdr_t *cpu_kh; phys_ram_seg_t *ramsegs; off_t off; int i; cpu_kh = kd->cpu_data; ramsegs = (void *)((char *)(void *)cpu_kh + _ALIGN(sizeof *cpu_kh)); off = 0; for (i = 0; i < cpu_kh->nmemsegs; i++) { if (pa >= ramsegs[i].start && (pa - ramsegs[i].start) < ramsegs[i].size) { off += (pa - ramsegs[i].start); break; } off += ramsegs[i].size; } if (i == cpu_kh->nmemsegs) _kvm_err(kd, 0, "pa %lx not in dump", pa); return (kd->dump_off + off); }
f997c47bee6f5d263a7c409e9382f81c1bac799d
0ba524c389b02e6c3d86bf4ca0d79d1ab4e2c595
/include/dukglue/dukglue.h
1b62f7b9d4e43f1a98236bc002f6c08879fbb4f0
[ "MIT" ]
permissive
Aloshi/dukglue
87e18aefbce514a9f33a24458580a0273524df7a
c3ec2a463a03a4fa34715aa75273537d39900edb
refs/heads/master
2023-08-16T18:19:10.702139
2022-11-08T03:35:48
2022-11-08T03:35:48
48,725,685
171
37
MIT
2023-08-09T20:03:36
2015-12-29T03:34:51
C
UTF-8
C
false
false
150
h
dukglue.h
#pragma once #include "register_function.h" #include "register_class.h" #include "register_property.h" #include "public_util.h" #include "dukvalue.h"
1e3e288bfa768cc97f862d2c2e9d06db87445bee
f367e4b66a1ee42e85830b31df88f63723c36a47
/lib/wasm-micro-runtime-WAMR-1.2.2/core/iwasm/compilation/simd/simd_int_arith.c
1d0e6967b6c5401a0cefb020a677b311593b87ba
[ "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
12,574
c
simd_int_arith.c
/* * Copyright (C) 2019 Intel Corporation. All rights reserved. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ #include "simd_int_arith.h" #include "simd_common.h" #include "../aot_emit_exception.h" #include "../../aot/aot_runtime.h" static bool simd_integer_arith(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, V128Arithmetic arith_op, LLVMTypeRef vector_type) { LLVMValueRef lhs, rhs, result = NULL; if (!(rhs = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type, "rhs")) || !(lhs = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type, "lhs"))) { return false; } switch (arith_op) { case V128_ADD: result = LLVMBuildAdd(comp_ctx->builder, lhs, rhs, "sum"); break; case V128_SUB: result = LLVMBuildSub(comp_ctx->builder, lhs, rhs, "difference"); break; case V128_MUL: result = LLVMBuildMul(comp_ctx->builder, lhs, rhs, "product"); break; default: HANDLE_FAILURE("Unsupport arith_op"); break; } if (!result) { HANDLE_FAILURE("LLVMBuildAdd/LLVMBuildSub/LLVMBuildMul"); return false; } return simd_bitcast_and_push_v128(comp_ctx, func_ctx, result, "result"); } bool aot_compile_simd_i8x16_arith(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, V128Arithmetic arith_op) { return simd_integer_arith(comp_ctx, func_ctx, arith_op, V128_i8x16_TYPE); } bool aot_compile_simd_i16x8_arith(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, V128Arithmetic arith_op) { return simd_integer_arith(comp_ctx, func_ctx, arith_op, V128_i16x8_TYPE); } bool aot_compile_simd_i32x4_arith(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, V128Arithmetic arith_op) { return simd_integer_arith(comp_ctx, func_ctx, arith_op, V128_i32x4_TYPE); } bool aot_compile_simd_i64x2_arith(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, V128Arithmetic arith_op) { return simd_integer_arith(comp_ctx, func_ctx, arith_op, V128_i64x2_TYPE); } static bool simd_neg(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, LLVMTypeRef type) { LLVMValueRef vector, result; if (!(vector = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, type, "vector"))) { return false; } if (!(result = LLVMBuildNeg(comp_ctx->builder, vector, "neg"))) { HANDLE_FAILURE("LLVMBuildNeg"); return false; } return simd_bitcast_and_push_v128(comp_ctx, func_ctx, result, "result"); } bool aot_compile_simd_i8x16_neg(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { return simd_neg(comp_ctx, func_ctx, V128_i8x16_TYPE); } bool aot_compile_simd_i16x8_neg(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { return simd_neg(comp_ctx, func_ctx, V128_i16x8_TYPE); } bool aot_compile_simd_i32x4_neg(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { return simd_neg(comp_ctx, func_ctx, V128_i32x4_TYPE); } bool aot_compile_simd_i64x2_neg(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { return simd_neg(comp_ctx, func_ctx, V128_i64x2_TYPE); } bool aot_compile_simd_i8x16_popcnt(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { LLVMValueRef vector, result; if (!(vector = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, V128_i8x16_TYPE, "vector"))) { return false; } if (!(result = aot_call_llvm_intrinsic(comp_ctx, func_ctx, "llvm.ctpop.v16i8", V128_i8x16_TYPE, &V128_i8x16_TYPE, 1, vector))) { return false; } return simd_bitcast_and_push_v128(comp_ctx, func_ctx, result, "result"); } static bool simd_v128_cmp(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, LLVMTypeRef vector_type, V128Arithmetic arith_op, bool is_signed) { LLVMValueRef lhs, rhs, result; LLVMIntPredicate op; if (!(rhs = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type, "rhs")) || !(lhs = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type, "lhs"))) { return false; } if (V128_MIN == arith_op) { op = is_signed ? LLVMIntSLT : LLVMIntULT; } else { op = is_signed ? LLVMIntSGT : LLVMIntUGT; } if (!(result = LLVMBuildICmp(comp_ctx->builder, op, lhs, rhs, "cmp"))) { HANDLE_FAILURE("LLVMBuildICmp"); return false; } if (!(result = LLVMBuildSelect(comp_ctx->builder, result, lhs, rhs, "select"))) { HANDLE_FAILURE("LLVMBuildSelect"); return false; } return simd_bitcast_and_push_v128(comp_ctx, func_ctx, result, "result"); } bool aot_compile_simd_i8x16_cmp(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, V128Arithmetic arith_op, bool is_signed) { return simd_v128_cmp(comp_ctx, func_ctx, V128_i8x16_TYPE, arith_op, is_signed); } bool aot_compile_simd_i16x8_cmp(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, V128Arithmetic arith_op, bool is_signed) { return simd_v128_cmp(comp_ctx, func_ctx, V128_i16x8_TYPE, arith_op, is_signed); } bool aot_compile_simd_i32x4_cmp(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, V128Arithmetic arith_op, bool is_signed) { return simd_v128_cmp(comp_ctx, func_ctx, V128_i32x4_TYPE, arith_op, is_signed); } /* llvm.abs.* */ static bool simd_v128_abs(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, char *intrinsic, LLVMTypeRef vector_type) { LLVMValueRef vector, result; LLVMTypeRef param_types[] = { vector_type, INT1_TYPE }; if (!(vector = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type, "vec"))) { return false; } if (!(result = aot_call_llvm_intrinsic(comp_ctx, func_ctx, intrinsic, vector_type, param_types, 2, vector, /* is_int_min_poison */ LLVM_CONST(i1_zero)))) { return false; } return simd_bitcast_and_push_v128(comp_ctx, func_ctx, result, "result"); } bool aot_compile_simd_i8x16_abs(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { return simd_v128_abs(comp_ctx, func_ctx, "llvm.abs.v16i8", V128_i8x16_TYPE); } bool aot_compile_simd_i16x8_abs(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { return simd_v128_abs(comp_ctx, func_ctx, "llvm.abs.v8i16", V128_i16x8_TYPE); } bool aot_compile_simd_i32x4_abs(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { return simd_v128_abs(comp_ctx, func_ctx, "llvm.abs.v4i32", V128_i32x4_TYPE); } bool aot_compile_simd_i64x2_abs(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { return simd_v128_abs(comp_ctx, func_ctx, "llvm.abs.v2i64", V128_i64x2_TYPE); } enum integer_avgr_u { e_avgr_u_i8x16, e_avgr_u_i16x8, e_avgr_u_i32x4, }; /* TODO: try int_x86_mmx_pavg_b and int_x86_mmx_pavg_w */ /* (v1 + v2 + 1) / 2 */ static bool simd_v128_avg(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx, enum integer_avgr_u itype) { LLVMValueRef lhs, rhs, ones, result; LLVMTypeRef vector_ext_type; LLVMTypeRef vector_type[] = { V128_i8x16_TYPE, V128_i16x8_TYPE, V128_i32x4_TYPE, }; unsigned lanes[] = { 16, 8, 4 }; if (!(rhs = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type[itype], "rhs")) || !(lhs = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, vector_type[itype], "lhs"))) { return false; } if (!(vector_ext_type = LLVMVectorType(I64_TYPE, lanes[itype]))) { HANDLE_FAILURE("LLVMVectorType"); return false; } if (!(lhs = LLVMBuildZExt(comp_ctx->builder, lhs, vector_ext_type, "zext_to_i64")) || !(rhs = LLVMBuildZExt(comp_ctx->builder, rhs, vector_ext_type, "zext_to_i64"))) { HANDLE_FAILURE("LLVMBuildZExt"); return false; } /* by default, add will do signed/unsigned overflow */ if (!(result = LLVMBuildAdd(comp_ctx->builder, lhs, rhs, "l_add_r"))) { HANDLE_FAILURE("LLVMBuildAdd"); return false; } if (!(ones = simd_build_splat_const_integer_vector(comp_ctx, I64_TYPE, 1, lanes[itype]))) { return false; } if (!(result = LLVMBuildAdd(comp_ctx->builder, result, ones, "plus_1"))) { HANDLE_FAILURE("LLVMBuildAdd"); return false; } if (!(result = LLVMBuildLShr(comp_ctx->builder, result, ones, "avg"))) { HANDLE_FAILURE("LLVMBuildLShr"); return false; } if (!(result = LLVMBuildTrunc(comp_ctx->builder, result, vector_type[itype], "to_orig_type"))) { HANDLE_FAILURE("LLVMBuildTrunc"); return false; } return simd_bitcast_and_push_v128(comp_ctx, func_ctx, result, "result"); } bool aot_compile_simd_i8x16_avgr_u(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { return simd_v128_avg(comp_ctx, func_ctx, e_avgr_u_i8x16); } bool aot_compile_simd_i16x8_avgr_u(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { return simd_v128_avg(comp_ctx, func_ctx, e_avgr_u_i16x8); } bool aot_compile_simd_i32x4_avgr_u(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { return simd_v128_avg(comp_ctx, func_ctx, e_avgr_u_i32x4); } bool aot_compile_simd_i32x4_dot_i16x8(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx) { LLVMValueRef vec1, vec2, even_mask, odd_mask, zero, result; LLVMTypeRef vector_ext_type; LLVMValueRef even_element[] = { LLVM_CONST(i32_zero), LLVM_CONST(i32_two), LLVM_CONST(i32_four), LLVM_CONST(i32_six), }; LLVMValueRef odd_element[] = { LLVM_CONST(i32_one), LLVM_CONST(i32_three), LLVM_CONST(i32_five), LLVM_CONST(i32_seven), }; if (!(vec1 = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, V128_i16x8_TYPE, "vec1")) || !(vec2 = simd_pop_v128_and_bitcast(comp_ctx, func_ctx, V128_i16x8_TYPE, "vec2"))) { return false; } if (!(vector_ext_type = LLVMVectorType(I32_TYPE, 8))) { HANDLE_FAILURE("LLVMVectorType"); return false; } /* sext <v8i16> to <v8i32> */ if (!(vec1 = LLVMBuildSExt(comp_ctx->builder, vec1, vector_ext_type, "vec1_v8i32")) || !(vec2 = LLVMBuildSExt(comp_ctx->builder, vec2, vector_ext_type, "vec2_v8i32"))) { HANDLE_FAILURE("LLVMBuildSExt"); return false; } if (!(result = LLVMBuildMul(comp_ctx->builder, vec1, vec2, "product"))) { HANDLE_FAILURE("LLVMBuildMul"); return false; } /* pick elements with even indexes and odd indexes */ if (!(even_mask = LLVMConstVector(even_element, 4)) || !(odd_mask = LLVMConstVector(odd_element, 4))) { HANDLE_FAILURE("LLVMConstVector"); return false; } if (!(zero = simd_build_splat_const_integer_vector(comp_ctx, I32_TYPE, 0, 8))) { return false; } if (!(vec1 = LLVMBuildShuffleVector(comp_ctx->builder, result, zero, even_mask, "even_result")) || !(vec2 = LLVMBuildShuffleVector(comp_ctx->builder, result, zero, odd_mask, "odd_result"))) { HANDLE_FAILURE("LLVMBuildShuffleVector"); return false; } if (!(result = LLVMBuildAdd(comp_ctx->builder, vec1, vec2, "new_vec"))) { HANDLE_FAILURE("LLVMBuildAdd"); return false; } return simd_bitcast_and_push_v128(comp_ctx, func_ctx, result, "result"); }
3e961eabdcdfb25ce79bc77eb6a5e67951956b30
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/tests/usr.bin/xlint/lint1/msg_334.c
cbd3e89eb7dd738027fcf356828dcb3b65e06077
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
553
c
msg_334.c
/* $NetBSD: msg_334.c,v 1.5 2023/08/02 18:51:25 rillig Exp $ */ # 3 "msg_334.c" // Test for message: parameter %d expects '%s', gets passed '%s' [334] // // See d_c99_bool_strict.c for many more examples. /* lint1-extra-flags: -T -X 351 */ typedef _Bool bool; void test_bool(bool); void test_int(int); void caller(bool b, int i) { test_bool(b); /* expect+1: error: parameter 1 expects '_Bool', gets passed 'int' [334] */ test_bool(i); /* expect+1: error: parameter 1 expects 'int', gets passed '_Bool' [334] */ test_int(b); test_int(i); }
7329bec9185231b96802f4961120adb861fdb9ae
22dd93dfe358a2e93d0aa847c148e14f6946c035
/src/libsodium/src/libsodium/include/sodium/randombytes_internal_random.h
2b2b7d6edc11a2fef58bd731663058fe4cb7855e
[ "ISC", "Apache-2.0" ]
permissive
pyca/pynacl
a78db377529ca4aaec6987c4590f5b512a9c7f11
d35d78ef2d890906aa8312fcbe5517dfbb8002bc
refs/heads/main
2023-08-27T19:17:11.591902
2023-08-25T11:02:15
2023-08-25T11:02:15
8,350,032
896
238
Apache-2.0
2023-09-05T21:33:33
2013-02-22T03:52:39
C
UTF-8
C
false
false
427
h
randombytes_internal_random.h
#ifndef randombytes_internal_random_H #define randombytes_internal_random_H #include "export.h" #include "randombytes.h" #ifdef __cplusplus extern "C" { #endif SODIUM_EXPORT extern struct randombytes_implementation randombytes_internal_implementation; /* Backwards compatibility with libsodium < 1.0.18 */ #define randombytes_salsa20_implementation randombytes_internal_implementation #ifdef __cplusplus } #endif #endif
7afe3d9b4aab32b8e4cfc7a5e0847ebdd36a53a2
c0bfd93cd7f26a271268e504959256f1e02c6806
/examples/system/factory-test/main/main.c
4f822e8cedcdabb8a0bc2aabafaf4d0dd66cf410
[ "Apache-2.0" ]
permissive
espressif/ESP8266_RTOS_SDK
606f396e92d2675d9854f0fabd88587fbbbaf267
af0cdc36fa2600033d0a09301c754008cf1503c1
refs/heads/master
2023-08-24T22:40:15.373553
2023-05-06T02:04:24
2023-05-06T02:04:24
27,584,181
3,163
1,749
Apache-2.0
2023-08-09T10:48:13
2014-12-05T09:27:12
C
UTF-8
C
false
false
2,428
c
main.c
// Copyright 2019-2020 Espressif Systems (Shanghai) PTE 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. #include <stdio.h> #include <assert.h> #include "esp_system.h" #include "esp_rftest.h" #include "esp_log.h" #include "esp_vfs_dev.h" #include "FreeRTOS.h" #include "driver/uart.h" #include "nano_console.h" #include "esp_libc.h" #include "esp_task.h" #ifndef ESP_FACTORY_TEST_EXTRA_COMPONENTS #ifndef CONFIG_ESP_CONSOLE_UART_NUM #define CONFIG_ESP_CONSOLE_UART_NUM 0 #endif #define TAG "factory-test" static void initialize_console() { /* Disable buffering on stdin */ setvbuf(stdin, NULL, _IONBF, 0); /* Minicom, screen, idf_monitor send CR when ENTER key is pressed */ esp_vfs_dev_uart_set_rx_line_endings(ESP_LINE_ENDINGS_CR); /* Move the caret to the beginning of the next line on '\n' */ esp_vfs_dev_uart_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF); /* Configure UART. Note that REF_TICK is used so that the baud rate remains * correct while APB frequency is changing in light sleep mode. */ uart_config_t uart_config = { .baud_rate = CONFIG_ESP_CONSOLE_UART_BAUDRATE, .data_bits = UART_DATA_8_BITS, .parity = UART_PARITY_DISABLE, .stop_bits = UART_STOP_BITS_1, }; ESP_ERROR_CHECK(uart_param_config(CONFIG_ESP_CONSOLE_UART_NUM, &uart_config)); /* Install UART driver for interrupt-driven reads and writes */ ESP_ERROR_CHECK(uart_driver_install(CONFIG_ESP_CONSOLE_UART_NUM, 256, 0, 0, NULL, 0)); /* Tell VFS to use UART driver */ esp_vfs_dev_uart_use_driver(CONFIG_ESP_CONSOLE_UART_NUM); esp_console_register_rftest_command(); ESP_ERROR_CHECK(nc_init()); } void __attribute__((weak)) app_main(void) { ESP_LOGI(TAG, "SDK factory test firmware version:%s\n", esp_get_idf_version()); initialize_console(); } #endif /* ESP_FACTORY_TEST_EXTRA_COMPONENTS */
7231f661f89b5423c7351762f370fa0c0d54c766
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/third_party/opus/src/silk/tests/test_unit_LPC_inv_pred_gain.c
7ca902ad9f4d0341b12086c1578c72d94ad722d3
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license", "BSD-3-Clause-Clear", "GPL-1.0-or-later", "MIT", "LGPL-2.0-or-later", "Apache-2.0" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C
false
false
4,783
c
test_unit_LPC_inv_pred_gain.c
/*********************************************************************** Copyright (c) 2017 Google Inc., Jean-Marc Valin 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 Internet Society, IETF or IETF Trust, nor the names of specific 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. ***********************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include "celt/stack_alloc.h" #include "cpu_support.h" #include "SigProc_FIX.h" /* Computes the impulse response of the filter so we can catch filters that are definitely unstable. Some unstable filters may be classified as stable, but not the other way around. */ int check_stability(opus_int16 *A_Q12, int order) { int i; int j; int sum_a, sum_abs_a; double y[SILK_MAX_ORDER_LPC] = {0}; sum_a = sum_abs_a = 0; for( j = 0; j < order; j++ ) { sum_a += A_Q12[ j ]; sum_abs_a += silk_abs( A_Q12[ j ] ); } /* Check DC stability. */ if( sum_a >= 4096 ) { return 0; } /* If the sum of absolute values is less than 1, the filter has to be stable. */ if( sum_abs_a < 4096 ) { return 1; } y[0] = 1; for( i = 0; i < 10000; i++ ) { double sum = 0; for( j = 0; j < order; j++ ) { sum += y[ j ]*A_Q12[ j ]; } for( j = order - 1; j > 0; j-- ) { y[ j ] = y[ j - 1 ]; } y[ 0 ] = sum*(1./4096); /* If impulse response reaches +/- 10000, the filter is definitely unstable. */ if( !(y[ 0 ] < 10000 && y[ 0 ] > -10000) ) { return 0; } /* Test every 8 sample for low amplitude. */ if( ( i & 0x7 ) == 0 ) { double amp = 0; for( j = 0; j < order; j++ ) { amp += fabs(y[j]); } if( amp < 0.00001 ) { return 1; } } } return 1; } int main(void) { const int arch = opus_select_arch(); /* Set to 10000 so all branches in C function are triggered */ const int loop_num = 10000; int count = 0; ALLOC_STACK; /* FIXME: Make the seed random (with option to set it explicitly) so we get wider coverage. */ srand(0); printf("Testing silk_LPC_inverse_pred_gain() optimization ...\n"); for( count = 0; count < loop_num; count++ ) { unsigned int i; opus_int order; unsigned int shift; opus_int16 A_Q12[ SILK_MAX_ORDER_LPC ]; opus_int32 gain; for( order = 2; order <= SILK_MAX_ORDER_LPC; order += 2 ) { /* order must be even. */ for( shift = 0; shift < 16; shift++ ) { /* Different dynamic range. */ for( i = 0; i < SILK_MAX_ORDER_LPC; i++ ) { A_Q12[i] = ((opus_int16)rand()) >> shift; } gain = silk_LPC_inverse_pred_gain(A_Q12, order, arch); /* Look for filters that silk_LPC_inverse_pred_gain() thinks are stable but definitely aren't. */ if( gain != 0 && !check_stability(A_Q12, order) ) { fprintf(stderr, "**Loop %4d failed!**\n", count); return 1; } } } if( !(count % 500) ) { printf("Loop %4d passed\n", count); } } printf("silk_LPC_inverse_pred_gain() optimization passed\n"); return 0; }
14ca8258b5eee8d6c9f5cac6c2d37ab1c22f7c0d
5eff7a36d9a9917dce9111f0c3074375fe6f7656
/app/xlockmore/modes/bomb.c
b1860eae869492f40bab38d64edc9f94562a1e44
[]
no_license
openbsd/xenocara
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
a012b5de33ea0b977095d77316a521195b26cc6b
refs/heads/master
2023-08-25T12:16:58.862008
2023-08-12T16:16:25
2023-08-12T16:16:25
66,967,384
177
66
null
2023-07-22T18:12:37
2016-08-30T18:36:01
C
UTF-8
C
false
false
13,555
c
bomb.c
/* -*- Mode: C; tab-width: 4 -*- */ /* bomb --- temporary screen */ #if !defined( lint ) && !defined( SABER ) static const char sccsid[] = "@(#)bomb.c 5.00 2000/11/01 xlockmore"; #endif /*- * Copyright (c) 1994 by Dave Shield * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and that * both that copyright notice and this permission notice appear in * supporting documentation. * * This file is provided AS IS with no warranties of any kind. The author * shall have no liability with respect to the infringement of copyrights, * trade secrets or any patents by this file or any part thereof. In no * event will the author be liable for any lost revenue or profits or * other special, indirect and consequential damages. * * Revision History: * 01-Nov-2000: Allocation checks * 10-May-1997: Made more compatible with xscreensaver :) * 09-Jan-1995: Assorted defines to control various aspects of bomb mode. * Uncomment, or otherwise define the appropriate line * to obtain the relevant behaviour, thanks to Dave Shield * <D.T.Shield@csc.liv.ac.uk>. * 20-Dec-1994: Time patch for multiprocessor machines (ie. Sun10) thanks to * Nicolas Pioch <pioch@Email.ENST.Fr>. * 1994: Written. Dave Shield Liverpool Computer Science */ /*- * This mode may have limited appeal. Its good for logging yourself out * if you do not know if your going to be back. It is no longer to be used * as a way of forcing users in a lab to logout after locking the screen. */ #ifdef STANDALONE #define MODE_bomb #define USE_BOMB #define PROGCLASS "Bomb" #define HACK_INIT init_bomb #define HACK_DRAW draw_bomb #define bomb_opts xlockmore_opts #define DEFAULTS "*delay: 1000000 \n" \ "*count: 10 \n" \ "*cycles: 20 \n" \ "*ncolors: 200 \n" \ "*verbose: False \n" #define UNIFORM_COLORS #define BRIGHT_COLORS #include "xlockmore.h" /* in xscreensaver distribution */ #else /* STANDALONE */ #include "xlock.h" /* in xlockmore distribution */ #endif /* STANDALONE */ #include "iostuff.h" #ifdef MODE_bomb ModeSpecOpt bomb_opts = {0, (XrmOptionDescRec *) NULL, 0, (argtype *) NULL, (OptionStruct *) NULL}; #ifdef USE_MODULES const ModStruct bomb_description = {"bomb", "init_bomb", "draw_bomb", "release_bomb", "refresh_bomb", "change_bomb", (char *) NULL, &bomb_opts, 100000, 10, 20, 1, 64, 1.0, "", "Shows a bomb and will autologout after a time", 0, NULL}; #endif #include <signal.h> #if 0 #define SIMPLE_COUNTDOWN /* Display a simple integer countdown, */ #endif /* rather than a "MIN:SEC" format. */ #define COLOUR_CHANGE /* Display cycles through the colour wheel */ /* rather than staying red throughout. */ #ifdef USE_MB #define FULL_COUNT_FONT "-adobe-courier-bold-r-*-*-34-*-*-*-*-*-iso8859-1" #define ICON_COUNT_FONT "-misc-fixed-medium-r-normal-*-8-*-*-*-*-*-iso8859-1" #else #define FULL_COUNT_FONT "-*-*-*-*-*-*-34-*-*-*-*-*-*-*" #define ICON_COUNT_FONT "-*-*-*-*-*-*-8-*-*-*-*-*-*-*" #endif #define COUNTDOWN 600 /* No. seconds to lock for */ #define NDIGITS 4 /* Number of digits in count */ #define MAX_DELAY 1000000 /* Max delay between updates */ #define NAP_TIME 5 /* Sleep between shutdown attempts */ #define DELTA 10 /* Border around the digits */ #define RIVET_RADIUS 6 /* Size of detonator 'rivets' */ #ifdef USE_MB #define free_font(d) if (mode_font!=None){XFreeFontSet(d,mode_font); \ mode_font = None;} #else #define free_font(d) if (mode_font!=None){XFreeFont(d,mode_font); \ mode_font = None;} #endif extern XFontStruct *getFont(Display * display); typedef struct { Bool painted; int width, height; int x, y; XPoint loc; int delta; int color; time_t countdown; int startcountdown; int text_width; int text_ascent; int text_descent; int moveok; } bombstruct; static bombstruct *bombs = NULL; #ifdef USE_MB static XFontSet mode_font = None; #else static XFontStruct *mode_font = None; #endif static void rivet(ModeInfo * mi, int x, int y) { Display *display = MI_DISPLAY(mi); GC gc = MI_GC(mi); XSetForeground(display, gc, MI_BLACK_PIXEL(mi)); if (MI_NPIXELS(mi) > 2) { XDrawArc(display, MI_WINDOW(mi), gc, x, y, 2 * RIVET_RADIUS, 2 * RIVET_RADIUS, 270 * 64, 90 * 64); XSetForeground(display, gc, MI_WHITE_PIXEL(mi)); XDrawArc(display, MI_WINDOW(mi), gc, x, y, 2 * RIVET_RADIUS, 2 * RIVET_RADIUS, 70 * 64, 130 * 64); } else XDrawArc(display, MI_WINDOW(mi), gc, x, y, 2 * RIVET_RADIUS, 2 * RIVET_RADIUS, 0, 360 * 64); } static void detonator(ModeInfo * mi, int draw) { Display *display = MI_DISPLAY(mi); GC gc = MI_GC(mi); bombstruct *bp = &bombs[MI_SCREEN(mi)]; int b_width, b_height; b_width = bp->width / 2; b_height = bp->height / 3; if (draw) { #ifdef SOLARIS2 /* * if this is not done the rectangle is sometimes messed up on * Solaris2 with 24 bit TrueColor (Ultra2) */ XSetForeground(MI_DISPLAY(mi), MI_GC(mi), MI_BLACK_PIXEL(mi)); XFillRectangle(display, MI_WINDOW(mi), gc, bp->loc.x, bp->loc.y, b_width, b_height); #endif if (MI_NPIXELS(mi) > 2) XSetForeground(MI_DISPLAY(mi), MI_GC(mi), MI_PIXEL(mi, bp->color)); else XSetForeground(MI_DISPLAY(mi), MI_GC(mi), MI_WHITE_PIXEL(mi)); /*XSetForeground(display, gc, allocPixel(display, MI_COLORMAP(mi), "grey", "white")); */ XFillRectangle(display, MI_WINDOW(mi), gc, bp->loc.x, bp->loc.y, b_width, b_height); /* * If a full size screen (and colour), * 'rivet' the box to it */ if (bp->width > 160 && bp->height > 160) { rivet(mi, bp->loc.x + RIVET_RADIUS, bp->loc.y + RIVET_RADIUS); rivet(mi, bp->loc.x + RIVET_RADIUS, bp->loc.y + b_height - 3 * RIVET_RADIUS); rivet(mi, bp->loc.x + b_width - 3 * RIVET_RADIUS, bp->loc.y + RIVET_RADIUS); rivet(mi, bp->loc.x + b_width - 3 * RIVET_RADIUS, bp->loc.y + b_height - 3 * RIVET_RADIUS); } } else { XSetForeground(MI_DISPLAY(mi), MI_GC(mi), MI_BLACK_PIXEL(mi)); XFillRectangle(display, MI_WINDOW(mi), gc, bp->loc.x, bp->loc.y, b_width, b_height); } } void release_bomb(ModeInfo * mi) { if (bombs != NULL) { free(bombs); bombs = (bombstruct *) NULL; } free_font(MI_DISPLAY(mi)); } void init_bomb(ModeInfo * mi) { Display *display = MI_DISPLAY(mi); GC gc = MI_GC(mi); bombstruct *bp; char number[NDIGITS + 2]; #ifdef USE_MB char **miss, *def; int n_miss; XRectangle ink, log; #endif if (bombs == NULL) { if ((bombs = (bombstruct *) calloc(MI_NUM_SCREENS(mi), sizeof (bombstruct))) == NULL) return; } bp = &bombs[MI_SCREEN(mi)]; bp->width = MI_WIDTH(mi); bp->height = MI_HEIGHT(mi); if (mode_font != None) { #ifdef USE_MB XFreeFontSet(display, mode_font); #else XFreeFont(display, mode_font); #endif mode_font = None; } /* Set up text font */ if (bp->width > 256 && bp->height > 256) { /* Full screen */ #ifdef USE_MB mode_font = XCreateFontSet(display, FULL_COUNT_FONT, &miss, &n_miss, &def); #else mode_font = XLoadQueryFont(display, FULL_COUNT_FONT); #endif bp->delta = DELTA; } else { /* icon window */ #ifdef USE_MB mode_font = XCreateFontSet(display, ICON_COUNT_FONT, &miss, &n_miss, &def); #else mode_font = XLoadQueryFont(display, ICON_COUNT_FONT); #endif bp->delta = 2; } if (mode_font == None) { #ifdef USE_MB mode_font = XCreateFontSet(display, "-*-medium-r-normal--14-*", &miss, &n_miss, &def); #else mode_font = getFont(display); #endif } if (mode_font == None) { release_bomb(mi); return; } #ifndef USE_MB XSetFont(display, gc, mode_font->fid); #endif #ifdef SIMPLE_COUNTDOWN (void) sprintf(number, "%0*d", NDIGITS, 0); #else #ifdef USE_MB (void) sprintf(number, "%.*s:00", NDIGITS - 2, "0000000"); #else (void) sprintf(number, "%.*s:**", NDIGITS - 2, "*******"); #endif #endif /* if (mode_font == None) bp->text_width = 8; */ #ifdef USE_MB XmbTextExtents(mode_font, number, strlen(number), &ink, &log); bp->text_width = ink.width; bp->text_ascent = ink.height; bp->text_descent = 0; #else bp->text_width = XTextWidth(mode_font, number, NDIGITS + 1); bp->text_ascent = mode_font->max_bounds.ascent; bp->text_descent = mode_font->max_bounds.descent; #endif #ifndef STANDALONE if (MI_DELAY(mi) > MAX_DELAY) MI_DELAY(mi) = MAX_DELAY; /* Time cannot move slowly */ #endif /* STANDALONE */ if (MI_COUNT(mi) < 1) bp->startcountdown = 1; /* Do not want an instantaneous logout */ bp->startcountdown = MI_COUNT(mi); bp->startcountdown *= 60; #if 0 /* Stricter if uncommented but people do not have to run bomb */ if (bp->startcountdown > COUNTDOWN) bp->startcountdown = COUNTDOWN; #endif if (bp->countdown == 0) /* <--Stricter if uncommented */ bp->countdown = time((time_t *) NULL) + bp->startcountdown; /* Detonator Primed */ MI_CLEARWINDOW(mi); bp->painted = False; /* * Draw the graphics * Very simple - detonator box with countdown * * ToDo: Improve the graphics * (e.g. stick of dynamite, with burning fuse?) */ bp->loc.x = NRAND(bp->width / 2); bp->loc.y = NRAND(bp->height * 3 / 5); bp->x = bp->loc.x + bp->width / 4 - (bp->text_width / 2); bp->y = bp->loc.y + bp->height / 5; /* Central-ish */ if (MI_NPIXELS(mi) > 2) bp->color = NRAND(MI_NPIXELS(mi)); detonator(mi, 1); bp->moveok = 0; } extern void logoutUser(Display * display); #ifdef SOLARIS2 #include <signal.h> #endif #if 0 extern int kill(int, int); extern int kill(pid_t, int); #endif /* * Game Over */ static void explode(ModeInfo * mi) { bombstruct *bp = &bombs[MI_SCREEN(mi)]; char buff[NDIGITS + 2]; /* * ToDo: * Improve the graphics - some sort of explosion? * (Will need to involve the main X event loop) */ #ifdef USE_MB #ifdef SIMPLE_COUNTDOWN (void) sprintf(buff, "%.*s", NDIGITS, "000000000"); #else (void) sprintf(buff, "%.*s:00", NDIGITS - 2, "0000000"); #endif #else #ifdef SIMPLE_COUNTDOWN (void) sprintf(buff, "%.*s", NDIGITS, "*********"); #else (void) sprintf(buff, "%.*s:**", NDIGITS - 2, "*******"); #endif #endif XSetForeground(MI_DISPLAY(mi), MI_GC(mi), MI_PIXEL(mi, 1)); (void) XDrawString(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi), bp->x, bp->y, buff, NDIGITS); (void) fprintf(stderr, "BOOM!!!!\n"); #ifndef DEBUG if (MI_IS_INWINDOW(mi) || MI_IS_INROOT(mi) || MI_IS_NOLOCK(mi) || MI_IS_DEBUG(mi)) (void) kill((int) getpid(), SIGTERM); else if ((int) getuid() == 0) { /* Do not try to logout root! */ bp->countdown = 0; init_bomb(mi); } else logoutUser(MI_DISPLAY(mi)); #else (void) kill(getpid(), SIGTERM); #endif } void draw_bomb(ModeInfo * mi) { Display *display = MI_DISPLAY(mi); GC gc = MI_GC(mi); char number[NDIGITS + 2]; unsigned long crayon; int countleft; bombstruct *bp; if (bombs == NULL) return; bp = &bombs[MI_SCREEN(mi)]; if (mode_font == None) return; countleft = (int) (bp->countdown - time((time_t *) NULL)); if (countleft <= 0) explode(mi); /* Bye, bye.... */ else { bp->painted = True; #ifdef SIMPLE_COUNTDOWN (void) sprintf(number, "%0*d", NDIGITS, countleft); #else (void) sprintf(number, "%0*d:%02d", NDIGITS - 2, countleft / 60, countleft % 60); #endif /* Blank out the previous number .... */ XSetForeground(display, gc, MI_BLACK_PIXEL(mi)); XFillRectangle(display, MI_WINDOW(mi), gc, bp->x - bp->delta, (bp->y - bp->text_ascent) - bp->delta, bp->text_width + (2 * bp->delta), (bp->text_ascent + bp->text_descent) + (2 * bp->delta)); /* ... and count down */ if (MI_NPIXELS(mi) <= 2) crayon = MI_WHITE_PIXEL(mi); else #ifdef COLOUR_CHANGE /* Blue to red */ crayon = MI_PIXEL(mi, countleft * MI_NPIXELS(mi) / bp->startcountdown); #else crayon = MI_PIXEL(mi, 1); #endif if (!(countleft % 60)) { if (bp->moveok) { detonator(mi, 0); bp->loc.x = NRAND(bp->width / 2); bp->loc.y = NRAND(bp->height * 3 / 5); bp->x = bp->loc.x + bp->width / 4 - (bp->text_width / 2); bp->y = bp->loc.y + bp->height / 5; /* Central-ish */ if (MI_NPIXELS(mi) > 2) bp->color = NRAND(MI_NPIXELS(mi)); detonator(mi, 1); bp->moveok = 0; } } else { bp->moveok = 1; } XSetForeground(display, gc, crayon); #ifndef USE_MB (void) XDrawString(display, MI_WINDOW(mi), gc, bp->x, bp->y, number, strlen(number)); #else (void) XmbDrawString(display, MI_WINDOW(mi), mode_font, gc, bp->x, bp->y, number, strlen(number)); #endif } } void refresh_bomb(ModeInfo * mi) { bombstruct *bp; if (bombs == NULL) return; bp = &bombs[MI_SCREEN(mi)]; if (mode_font == None) return; if (bp->painted) { MI_CLEARWINDOW(mi); detonator(mi, 1); } } void change_bomb(ModeInfo * mi) { bombstruct *bp; if (bombs == NULL) return; bp = &bombs[MI_SCREEN(mi)]; if (mode_font == None) return; detonator(mi, 0); bp->painted = False; bp->loc.x = NRAND(bp->width / 2); bp->loc.y = NRAND(bp->height * 3 / 5); bp->x = bp->loc.x + bp->width / 4 - (bp->text_width / 2); bp->y = bp->loc.y + bp->height / 5; /* Central-ish */ if (MI_NPIXELS(mi) > 2) bp->color = NRAND(MI_NPIXELS(mi)); detonator(mi, 1); bp->moveok = 0; } #endif /* MODE_bomb */
3f9203c833745fcbe11c60d590112585cd5c5cdd
533546354c6e86f568ba936d2840c6b37a3873eb
/misc/gl2tri/main.c
0c8ad7375a1844a7781fc2850bcfa4ee0224032a
[ "MIT" ]
permissive
terryky/tflite_gles_app
4a34131cbeb677f99c0f4c04941f240748238c39
bfc2015a6d1234deebc9574798b175a6d1b2afc2
refs/heads/master
2022-05-14T11:36:51.810565
2022-04-22T14:30:50
2022-04-22T14:30:50
202,537,120
489
128
MIT
2021-03-25T07:25:58
2019-08-15T12:28:38
C
UTF-8
C
false
false
3,351
c
main.c
/* ------------------------------------------------ * * The MIT License (MIT) * Copyright (c) 2019 terryky1220@gmail.com * ------------------------------------------------ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <GLES2/gl2.h> #include "util_shader.h" #include "util_egl.h" #define UNUSED(x) (void)(x) static GLfloat s_vtx[] = { -0.5f, 0.5f, -0.5f,-0.5f, 0.5f, 0.5f, }; static GLfloat s_col[] = { 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, }; static char s_strVS[] = " \ \ attribute vec4 a_Vertex; \ attribute vec4 a_Color; \ varying vec4 v_color; \ \ void main (void) \ { \ gl_Position = a_Vertex; \ v_color = a_Color; \ } "; static char s_strFS[] = " \ \ precision mediump float; \ varying vec4 v_color; \ \ void main (void) \ { \ gl_FragColor = v_color; \ } "; int capture_to_img (char *lpFName, int nW, int nH) { FILE *fp; unsigned char *lpBuf; char strFName[ 128 ]; sprintf (strFName, "%s_RGBA8888_SIZE%dx%d.img", lpFName, nW, nH); fp = fopen (strFName, "wb"); if (fp == NULL) { fprintf (stderr, "FATAL ERROR at %s(%d)\n", __FILE__, __LINE__); return -1; } lpBuf = (unsigned char *)malloc (nW * nH * 4); if (lpBuf == NULL) { fprintf (stderr, "FATAL ERROR at %s(%d)\n", __FILE__, __LINE__); return -1; } glPixelStorei (GL_PACK_ALIGNMENT, 1); glReadPixels (0, 0, nW, nH, GL_RGBA, GL_UNSIGNED_BYTE, lpBuf); fwrite (lpBuf, 4, nW * nH, fp); free (lpBuf); fclose (fp); return 0; } /*--------------------------------------------------------------------------- * * M A I N F U N C T I O N *--------------------------------------------------------------------------- */ int main(int argc, char *argv[]) { int i; int win_w = 960; int win_h = 540; shader_obj_t sobj; UNUSED (argc); UNUSED (*argv); egl_init_with_platform_window_surface (2, 0, 0, 0, win_w, win_h); generate_shader (&sobj, s_strVS, s_strFS); for (i = 0; i < 10; i ++) { glClearColor (0.5f, 0.5f, 0.5f, 1.0f); glClear (GL_COLOR_BUFFER_BIT); glUseProgram( sobj.program ); glEnableVertexAttribArray (sobj.loc_vtx); glEnableVertexAttribArray (sobj.loc_clr); glVertexAttribPointer (sobj.loc_vtx, 2, GL_FLOAT, GL_FALSE, 0, s_vtx); glVertexAttribPointer (sobj.loc_clr, 4, GL_FLOAT, GL_FALSE, 0, s_col); glDrawArrays (GL_TRIANGLE_STRIP, 0, 3); egl_swap(); } //capture_to_img ("out", win_w, win_h); sleep (10); return 0; }
d8ec8c8697911b709aa0b6c810f6a425465842c6
83b8b30ebb633eecd29ca0a7a20cc43a293c9333
/ports/raspberrypi/boards/sparkfun_thing_plus_rp2040/mpconfigboard.h
a4a162062a70b1d938db4251c1493d05e3e02d74
[ "MIT", "GPL-1.0-or-later" ]
permissive
adafruit/circuitpython
430ec895149d1eb814b505db39b4977a35ee88a7
506dca71b0cbb7af749bb51f86b01021db5483b3
refs/heads/main
2023-08-21T16:30:46.781068
2023-08-20T00:39:44
2023-08-20T00:39:44
66,166,069
3,806
1,560
MIT
2023-09-14T19:23:51
2016-08-20T20:10:40
C
UTF-8
C
false
false
432
h
mpconfigboard.h
#define MICROPY_HW_BOARD_NAME "SparkFun Thing Plus - RP2040" #define MICROPY_HW_MCU_NAME "rp2040" #define DEFAULT_UART_BUS_TX (&pin_GPIO0) #define DEFAULT_UART_BUS_RX (&pin_GPIO1) #define DEFAULT_SPI_BUS_SCK (&pin_GPIO2) #define DEFAULT_SPI_BUS_MOSI (&pin_GPIO3) #define DEFAULT_SPI_BUS_MISO (&pin_GPIO4) #define DEFAULT_I2C_BUS_SDA (&pin_GPIO6) #define DEFAULT_I2C_BUS_SCL (&pin_GPIO7) #define MICROPY_HW_NEOPIXEL (&pin_GPIO8)
6ad8fe35db2a7248125775bdf5239eaa0ae2b60b
d79db96554e506a7be2b61bd9df178a98ac7ccf4
/src/libressl-2.4.1/tests/rc4test.c
c4d34b1a8460c1b2aa6765c2477507a97aa61664
[ "FSFAP", "OpenSSL", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
lsds/TaLoS
42edcb4ed4d76257ec3c217ba26a92f543a9ef63
9c959980de0c6d2a80582e3546747823ea3eca69
refs/heads/master
2023-09-05T04:58:07.718709
2022-01-25T05:00:19
2022-01-25T05:00:19
85,239,830
113
23
Apache-2.0
2020-11-19T08:10:08
2017-03-16T20:42:42
C
UTF-8
C
false
false
7,449
c
rc4test.c
/* crypto/rc4/rc4test.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 <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/rc4.h> #include <openssl/sha.h> static unsigned char keys[7][30]={ {8,0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}, {8,0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}, {8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, {4,0xef,0x01,0x23,0x45}, {8,0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}, {4,0xef,0x01,0x23,0x45}, }; static unsigned char data_len[7]={8,8,8,20,28,10}; static unsigned char data[7][30]={ {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xff}, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff}, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff}, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0xff}, {0x12,0x34,0x56,0x78,0x9A,0xBC,0xDE,0xF0, 0x12,0x34,0x56,0x78,0x9A,0xBC,0xDE,0xF0, 0x12,0x34,0x56,0x78,0x9A,0xBC,0xDE,0xF0, 0x12,0x34,0x56,0x78,0xff}, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff}, {0}, }; static unsigned char output[7][30]={ {0x75,0xb7,0x87,0x80,0x99,0xe0,0xc5,0x96,0x00}, {0x74,0x94,0xc2,0xe7,0x10,0x4b,0x08,0x79,0x00}, {0xde,0x18,0x89,0x41,0xa3,0x37,0x5d,0x3a,0x00}, {0xd6,0xa1,0x41,0xa7,0xec,0x3c,0x38,0xdf, 0xbd,0x61,0x5a,0x11,0x62,0xe1,0xc7,0xba, 0x36,0xb6,0x78,0x58,0x00}, {0x66,0xa0,0x94,0x9f,0x8a,0xf7,0xd6,0x89, 0x1f,0x7f,0x83,0x2b,0xa8,0x33,0xc0,0x0c, 0x89,0x2e,0xbe,0x30,0x14,0x3c,0xe2,0x87, 0x40,0x01,0x1e,0xcf,0x00}, {0xd6,0xa1,0x41,0xa7,0xec,0x3c,0x38,0xdf,0xbd,0x61,0x00}, {0}, }; int main(int argc, char *argv[]) { int i,err=0; int j; unsigned char *p; RC4_KEY key; unsigned char obuf[512]; OPENSSL_add_all_algorithms_noconf(); for (i=0; i<6; i++) { RC4_set_key(&key,keys[i][0],&(keys[i][1])); memset(obuf,0x00,sizeof(obuf)); RC4(&key,data_len[i],&(data[i][0]),obuf); if (memcmp(obuf,output[i],data_len[i]+1) != 0) { printf("error calculating RC4\n"); printf("output:"); for (j=0; j<data_len[i]+1; j++) printf(" %02x",obuf[j]); printf("\n"); printf("expect:"); p= &(output[i][0]); for (j=0; j<data_len[i]+1; j++) printf(" %02x",*(p++)); printf("\n"); err++; } else printf("test %d ok\n",i); } printf("test end processing "); for (i=0; i<data_len[3]; i++) { RC4_set_key(&key,keys[3][0],&(keys[3][1])); memset(obuf,0x00,sizeof(obuf)); RC4(&key,i,&(data[3][0]),obuf); if ((memcmp(obuf,output[3],i) != 0) || (obuf[i] != 0)) { printf("error in RC4 length processing\n"); printf("output:"); for (j=0; j<i+1; j++) printf(" %02x",obuf[j]); printf("\n"); printf("expect:"); p= &(output[3][0]); for (j=0; j<i; j++) printf(" %02x",*(p++)); printf(" 00\n"); err++; } else { printf("."); fflush(stdout); } } printf("done\n"); printf("test multi-call "); for (i=0; i<data_len[3]; i++) { RC4_set_key(&key,keys[3][0],&(keys[3][1])); memset(obuf,0x00,sizeof(obuf)); RC4(&key,i,&(data[3][0]),obuf); RC4(&key,data_len[3]-i,&(data[3][i]),&(obuf[i])); if (memcmp(obuf,output[3],data_len[3]+1) != 0) { printf("error in RC4 multi-call processing\n"); printf("output:"); for (j=0; j<data_len[3]+1; j++) printf(" %02x",obuf[j]); printf("\n"); printf("expect:"); p= &(output[3][0]); for (j=0; j<data_len[3]+1; j++) printf(" %02x",*(p++)); err++; } else { printf("."); fflush(stdout); } } printf("done\n"); printf("bulk test "); { unsigned char buf[513]; SHA_CTX c; unsigned char md[SHA_DIGEST_LENGTH]; static unsigned char expected[]={ 0xa4,0x7b,0xcc,0x00,0x3d,0xd0,0xbd,0xe1,0xac,0x5f, 0x12,0x1e,0x45,0xbc,0xfb,0x1a,0xa1,0xf2,0x7f,0xc5 }; RC4_set_key(&key,keys[0][0],&(keys[3][1])); memset(buf,'\0',sizeof(buf)); SHA1_Init(&c); for (i=0;i<2571;i++) { RC4(&key,sizeof(buf),buf,buf); SHA1_Update(&c,buf,sizeof(buf)); } SHA1_Final(md,&c); if (memcmp(md,expected,sizeof(md))) { printf("error in RC4 bulk test\n"); printf("output:"); for (j=0; j<(int)sizeof(md); j++) printf(" %02x",md[j]); printf("\n"); printf("expect:"); for (j=0; j<(int)sizeof(md); j++) printf(" %02x",expected[j]); printf("\n"); err++; } else printf("ok\n"); } exit(err); }
37dcfbc2a024468329f23d9880e2b0225530475b
d169de4c5c6b281984df35536430dcc931a957a9
/source/hal/driver/AIC/AIC8800/mmc/mmc.h
c8f2e86eba057bcb8a5081b9d718086da119f9c0
[ "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
3,796
h
mmc.h
/***************************************************************************** * Copyright(C)2009-2022 by VSF Team * * * * 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 __HAL_DRIVER_AIC8800_HW_MMC_H__ #define __HAL_DRIVER_AIC8800_HW_MMC_H__ /*============================ INCLUDES ======================================*/ #include "hal/vsf_hal_cfg.h" #if VSF_HAL_USE_MMC == ENABLED #include "../__device.h" /*============================ MACROS ========================================*/ #define VSF_MMC_CFG_REIMPLEMENT_TYPE_TRANSOP ENABLED #define VSF_MMC_CFG_REIMPLEMENT_TYPE_IRQ_MASK ENABLED #define VSF_MMC_CFG_REIMPLEMENT_TYPE_TRANSACT_STATUS ENABLED /*============================ MACROFIED FUNCTIONS ===========================*/ /*============================ TYPES =========================================*/ typedef enum vsf_mmc_transop_t { MMC_CMDOP_SINGLE_BLOCK = (1ul << 8), // MMC_CMDOP_RW MMC_CMDOP_MULTI_BLOCK = (1ul << 10) | (1ul << 16), // SDMMC_MULTI_BLOCK_MODE | SDMMC_AUTOCMD12_ENABLE MMC_CMDOP_WRITE = (1ul << 9), // SDMMC_WRITE_MODE MMC_CMDOP_RESP = (1ul << 4), // SDMMC_RESPONSE_ENABLE MMC_CMDOP_RESP_SHORT = (1ul << 5), // SDMMC_CONFIG_R3 MMC_CMDOP_RESP_SHORT_CRC = (0ul << 5), // SDMMC_CONFIG_Rx MMC_CMDOP_RESP_LONG_CRC = (2ul << 5), // SDMMC_CONFIG_R2 } vsf_mmc_transop_t; typedef enum vsf_mmc_irq_mask_t { MMC_IRQ_MASK_HOST_RESP_DONE = (0x1ul << 9), // SDMMC_RESP_DONE_FLAG MMC_IRQ_MASK_HOST_DATA_DONE = (0x1ul << 4), // SDMMC_DATA_DONE_FLAG MMC_IRQ_MASK_HOST_ALL = MMC_IRQ_MASK_HOST_RESP_DONE | MMC_IRQ_MASK_HOST_DATA_DONE, } vsf_mmc_irq_mask_t; typedef enum vsf_mmc_transact_status_t { MMC_TRANSACT_STATUS_DONE = 0, MMC_TRANSACT_STATUS_ERR_RESP_NONE = (0x1ul << 9), MMC_TRANSACT_STATUS_ERR_RESP_CRC = (0x1ul << 8), MMC_TRANSACT_STATUS_ERR_DATA_CRC = (0xFFul << 16), MMC_TRANSACT_STATUS_DATA_BUSY = (0x1ul << 2), MMC_TRANSACT_STATUS_BUSY = (0x1ul << 1), MMC_TRANSACT_STATUS_ERR_MASK = MMC_TRANSACT_STATUS_ERR_RESP_NONE | MMC_TRANSACT_STATUS_ERR_RESP_CRC | MMC_TRANSACT_STATUS_ERR_DATA_CRC, } vsf_mmc_transact_status_t; /*============================ INCLUDES ======================================*/ #endif /* VSF_HAL_USE_MMC */ #endif /* __HAL_DRIVER_AIC8800_HW_MMC_H__ */
c8e88934959c453ff76b4ffe928b0324d5e9b742
d579699e6728aa74084f8cc4dc435007b9f523a8
/data/signatures/ntifs.h
7ec644da2bd2215c094f6a74a512868d5f5704e2
[ "BSD-3-Clause" ]
permissive
BoomerangDecompiler/boomerang
b3c6b4e88c152ac6d437f3dd3640fd9ffa157cb6
411041305f90d1d7c994f67255b5c03ea8666e60
refs/heads/develop
2023-08-31T03:50:56.112711
2020-12-28T12:11:55
2020-12-28T17:38:56
7,819,729
281
41
NOASSERTION
2020-12-27T17:59:52
2013-01-25T12:26:59
C++
UTF-8
C
false
false
17,400
h
ntifs.h
void KeInitializeEvent( PRKEVENT Event, EVENT_TYPE Type, BOOLEAN State ); void KeClearEvent( PRKEVENT Event ); LONG KePulseEvent( PRKEVENT Event, KPRIORITY Increment, BOOLEAN Wait ); LONG KeReadStateEvent( PRKEVENT Event ); LONG KeResetEvent( PRKEVENT Event ); LONG KeSetEvent( PRKEVENT Event, KPRIORITY Increment, BOOLEAN Wait ); void KeInitializeMutant( PRKMUTANT Mutant, BOOLEAN InitialOwner ); LONG KeReadStateMutant( PRKMUTANT Mutant ); LONG KeReleaseMutant( PRKMUTANT Mutant, KPRIORITY Increment, BOOLEAN Abandoned, BOOLEAN Wait ); void IoRegisterFileSystem( PDEVICE_OBJECT DeviceObject ); NTSTATUS IoRegisterFsRegistrationChange( PDRIVER_OBJECT DriverObject, PDRIVER_FS_NOTIFICATION DriverNotificationRoutine ); void SeCaptureSubjectContext( PSECURITY_SUBJECT_CONTEXT SubjectContext ); void SeLockSubjectContext( PSECURITY_SUBJECT_CONTEXT SubjectContext ); void SeUnlockSubjectContext( PSECURITY_SUBJECT_CONTEXT SubjectContext ); void SeReleaseSubjectContext( PSECURITY_SUBJECT_CONTEXT SubjectContext ); NTSTATUS SeCaptureAuditPolicy( PTOKEN_AUDIT_POLICY Policy, KPROCESSOR_MODE RequestorMode, PVOID CaptureBuffer, ULONG CaptureBufferLength, POOL_TYPE PoolType, BOOLEAN ForceCapture, PTOKEN_AUDIT_POLICY *CapturedPolicy ); void SeReleaseAuditPolicy( PTOKEN_AUDIT_POLICY CapturedPolicy, KPROCESSOR_MODE RequestorMode, BOOLEAN ForceCapture ); NTSTATUS SeAssignSecurity( PSECURITY_DESCRIPTOR ParentDescriptor, PSECURITY_DESCRIPTOR ExplicitDescriptor, PSECURITY_DESCRIPTOR *NewDescriptor, BOOLEAN IsDirectoryObject, PSECURITY_SUBJECT_CONTEXT SubjectContext, PGENERIC_MAPPING GenericMapping, POOL_TYPE PoolType ); NTSTATUS SeAssignSecurityEx( PSECURITY_DESCRIPTOR ParentDescriptor, PSECURITY_DESCRIPTOR ExplicitDescriptor, PSECURITY_DESCRIPTOR *NewDescriptor, GUID *ObjectType, BOOLEAN IsDirectoryObject, ULONG AutoInheritFlags, PSECURITY_SUBJECT_CONTEXT SubjectContext, PGENERIC_MAPPING GenericMapping, POOL_TYPE PoolType ); NTSTATUS SeDeassignSecurity( PSECURITY_DESCRIPTOR *SecurityDescriptor ); BOOLEAN SeAccessCheck( PSECURITY_DESCRIPTOR SecurityDescriptor, PSECURITY_SUBJECT_CONTEXT SubjectSecurityContext, BOOLEAN SubjectContextLocked, ACCESS_MASK DesiredAccess, ACCESS_MASK PreviouslyGrantedAccess, PPRIVILEGE_SET *Privileges, PGENERIC_MAPPING GenericMapping, KPROCESSOR_MODE AccessMode, PACCESS_MASK GrantedAccess, PNTSTATUS AccessStatus ); BOOLEAN RtlValidSid( PSID Sid ); BOOLEAN RtlEqualSid( PSID Sid1, PSID Sid2 ); BOOLEAN RtlEqualPrefixSid( PSID Sid1, PSID Sid2 ); PVOID RtlFreeSid( PSID Sid ); NTSTATUS RtlAllocateAndInitializeSid( PSID_IDENTIFIER_AUTHORITY IdentifierAuthority, UCHAR SubAuthorityCount, ULONG SubAuthority0, ULONG SubAuthority1, ULONG SubAuthority2, ULONG SubAuthority3, ULONG SubAuthority4, ULONG SubAuthority5, ULONG SubAuthority6, ULONG SubAuthority7, PSID *Sid ); NTSTATUS RtlInitializeSid( PSID Sid, PSID_IDENTIFIER_AUTHORITY IdentifierAuthority, UCHAR SubAuthorityCount ); PSID_IDENTIFIER_AUTHORITY RtlIdentifierAuthoritySid( PSID Sid ); ULONG RtlLengthRequiredSid( ULONG SubAuthorityCount ); PULONG RtlSubAuthoritySid( PSID Sid, ULONG SubAuthority ); PUCHAR RtlSubAuthorityCountSid( PSID Sid ); ULONG RtlLengthSid( PSID Sid ); NTSTATUS RtlCopySid( ULONG DestinationSidLength, PSID DestinationSid, PSID SourceSid ); void RtlCopyLuid( PLUID DestinationLuid, PLUID SourceLuid ); void RtlMapGenericMask( PACCESS_MASK AccessMask, PGENERIC_MAPPING GenericMapping ); NTSTATUS RtlCreateAcl( PACL Acl, ULONG AclLength, ULONG AclRevision ); NTSTATUS RtlGetAce( PACL Acl, ULONG AceIndex, PVOID *Ace ); NTSTATUS RtlAddAccessAllowedAce( PACL Acl, ULONG AceRevision, ACCESS_MASK AccessMask, PSID Sid ); NTSTATUS PoQueueShutdownWorkItem( PWORK_QUEUE_ITEM WorkItem ); NTSTATUS ZwCreateEvent( PHANDLE EventHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, EVENT_TYPE EventType, BOOLEAN InitialState ); NTSTATUS ZwCreateFile( PHANDLE FileHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PIO_STATUS_BLOCK IoStatusBlock, PLARGE_INTEGER AllocationSize, ULONG FileAttributes, ULONG ShareAccess, ULONG CreateDisposition, ULONG CreateOptions, PVOID EaBuffer, ULONG EaLength ); NTSTATUS ZwDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes ); NTSTATUS ZwDeviceIoControlFile( HANDLE FileHandle, HANDLE Event, PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, ULONG IoControlCode, PVOID InputBuffer, ULONG InputBufferLength, PVOID OutputBuffer, ULONG OutputBufferLength ); NTSTATUS ZwOpenFile( PHANDLE FileHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PIO_STATUS_BLOCK IoStatusBlock, ULONG ShareAccess, ULONG OpenOptions ); NTSTATUS ZwQueryDirectoryFile( HANDLE FileHandle, HANDLE Event, PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, PVOID FileInformation, ULONG Length, FILE_INFORMATION_CLASS FileInformationClass, BOOLEAN ReturnSingleEntry, PUNICODE_STRING FileName, BOOLEAN RestartScan ); NTSTATUS ZwQueryInformationFile( HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID FileInformation, ULONG Length, FILE_INFORMATION_CLASS FileInformationClass ); NTSTATUS ZwSetInformationFile( HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID FileInformation, ULONG Length, FILE_INFORMATION_CLASS FileInformationClass ); NTSTATUS ZwQueryVolumeInformationFile( HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID FsInformation, ULONG Length, FS_INFORMATION_CLASS FsInformationClass ); NTSTATUS ZwSetVolumeInformationFile( HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID FsInformation, ULONG Length, FS_INFORMATION_CLASS FsInformationClass ); NTSTATUS ZwReadFile( HANDLE FileHandle, HANDLE Event, PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer, ULONG Length, PLARGE_INTEGER ByteOffset, PULONG Key ); NTSTATUS ZwWriteFile( HANDLE FileHandle, HANDLE Event, PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer, ULONG Length, PLARGE_INTEGER ByteOffset, PULONG Key ); NTSTATUS ZwFsControlFile( HANDLE FileHandle, HANDLE Event, PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, ULONG FsControlCode, PVOID InputBuffer, ULONG InputBufferLength, PVOID OutputBuffer, ULONG OutputBufferLength ); NTSTATUS ZwClose( HANDLE Handle ); NTSTATUS ZwDuplicateObject( HANDLE SourceProcessHandle, HANDLE SourceHandle, HANDLE TargetProcessHandle, PHANDLE TargetHandle, ACCESS_MASK DesiredAccess, ULONG HandleAttributes, ULONG Options ); NTSTATUS ZwCreateDirectoryObject( PHANDLE DirectoryHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes ); NTSTATUS ZwOpenDirectoryObject( PHANDLE DirectoryHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes ); NTSTATUS ZwOpenSymbolicLinkObject( PHANDLE LinkHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes ); NTSTATUS ZwQuerySymbolicLinkObject( HANDLE LinkHandle, PUNICODE_STRING LinkTarget, PULONG ReturnedLength ); NTSTATUS ZwMakeTemporaryObject( HANDLE Handle ); NTSTATUS ZwCreateKey( PHANDLE KeyHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, ULONG TitleIndex, PUNICODE_STRING Class, ULONG CreateOptions, PULONG Disposition ); NTSTATUS ZwOpenKey( PHANDLE KeyHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes ); NTSTATUS ZwDeleteKey( HANDLE KeyHandle ); NTSTATUS ZwDeleteValueKey( HANDLE KeyHandle, PUNICODE_STRING ValueName ); NTSTATUS ZwEnumerateKey( HANDLE KeyHandle, ULONG Index, KEY_INFORMATION_CLASS KeyInformationClass, PVOID KeyInformation, ULONG Length, PULONG ResultLength ); NTSTATUS ZwEnumerateValueKey( HANDLE KeyHandle, ULONG Index, KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass, PVOID KeyValueInformation, ULONG Length, PULONG ResultLength ); NTSTATUS ZwFlushKey( HANDLE KeyHandle ); NTSTATUS ZwQueryKey( HANDLE KeyHandle, KEY_INFORMATION_CLASS KeyInformationClass, PVOID KeyInformation, ULONG Length, PULONG ResultLength ); NTSTATUS ZwQueryValueKey( HANDLE KeyHandle, PUNICODE_STRING ValueName, KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass, PVOID KeyValueInformation, ULONG Length, PULONG ResultLength ); NTSTATUS ZwSetValueKey( HANDLE KeyHandle, PUNICODE_STRING ValueName, ULONG TitleIndex, ULONG Type, PVOID Data, ULONG DataSize ); NTSTATUS ZwOpenSection( PHANDLE SectionHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes ); NTSTATUS ZwMapViewOfSection( HANDLE SectionHandle, HANDLE ProcessHandle, PVOID *BaseAddress, ULONG ZeroBits, SIZE_T CommitSize, PLARGE_INTEGER SectionOffset, PSIZE_T ViewSize, SECTION_INHERIT InheritDisposition, ULONG AllocationType, ULONG Protect ); NTSTATUS ZwUnmapViewOfSection( HANDLE ProcessHandle, PVOID BaseAddress ); NTSTATUS ZwSetInformationThread( HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength ); NTSTATUS ZwCreateSection( PHANDLE SectionHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PLARGE_INTEGER MaximumSize, ULONG SectionPageProtection, ULONG AllocationAttributes, HANDLE FileHandle ); NTSTATUS ZwAllocateVirtualMemory( HANDLE ProcessHandle, PVOID *BaseAddress, ULONG ZeroBits, PSIZE_T RegionSize, ULONG AllocationType, ULONG Protect ); NTSTATUS ZwFreeVirtualMemory( HANDLE ProcessHandle, PVOID *BaseAddress, PSIZE_T RegionSize, ULONG FreeType ); NTSTATUS ZwWaitForSingleObject( HANDLE Handle, BOOLEAN Alertable, PLARGE_INTEGER TimeOPTIONAL ); NTSTATUS ZwSetEvent( HANDLE Handle, PLONG PreviousState ); NTSTATUS ZwFlushVirtualMemory( HANDLE ProcessHandle, PVOID *BaseAddress, PSIZE_T RegionSize, PIO_STATUS_BLOCK IoStatus ); NTSTATUS ZwOpenProcessTokenEx( HANDLE ProcessHandle, ACCESS_MASK DesiredAccess, ULONG HandleAttributes, PHANDLE TokenHandle ); NTSTATUS ZwOpenThreadTokenEx( HANDLE ThreadHandle, ACCESS_MASK DesiredAccess, BOOLEAN OpenAsSelf, ULONG HandleAttributes, PHANDLE TokenHandle ); NTSTATUS ZwSetInformationToken( HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, PVOID TokenInformation, ULONG TokenInformationLength ); NTSTATUS ZwQueryInformationToken( HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, PVOID TokenInformation, ULONG TokenInformationLength, PULONG ReturnLength ); NTSTATUS ZwSetSecurityObject( HANDLE Handle, SECURITY_INFORMATION SecurityInformation, PSECURITY_DESCRIPTOR SecurityDescriptor ); NTSTATUS ZwQuerySecurityObject( HANDLE Handle, SECURITY_INFORMATION SecurityInformation, PSECURITY_DESCRIPTOR SecurityDescriptor, ULONG Length, PULONG LengthNeeded ); NTSTATUS ZwLoadDriver( PUNICODE_STRING DriverServiceName ); NTSTATUS ZwUnloadDriver( PUNICODE_STRING DriverServiceName ); NTSTATUS ZwLockFile( HANDLE FileHandle, HANDLE Event, PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, PLARGE_INTEGER ByteOffset, PLARGE_INTEGER Length, ULONG Key, BOOLEAN FailImmediately, BOOLEAN ExclusiveLock ); NTSTATUS ZwUnlockFile( HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PLARGE_INTEGER ByteOffset, PLARGE_INTEGER Length, ULONG Key ); NTSTATUS ZwQueryQuotaInformationFile( HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer, ULONG Length, BOOLEAN ReturnSingleEntry, PVOID SidList, ULONG SidListLength, PSID StartSid, BOOLEAN RestartScan ); NTSTATUS ZwSetQuotaInformationFile( HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer, ULONG Length ); NTSTATUS ZwConnectPort( PHANDLE PortHandle, PUNICODE_STRING PortName, PSECURITY_QUALITY_OF_SERVICE SecurityQos, PPORT_VIEW ClientView, PREMOTE_PORT_VIEW ServerView, PULONG MaxMessageLength, PVOID ConnectionInformation, PULONG ConnectionInformationLength ); NTSTATUS ZwSecureConnectPort( PHANDLE PortHandle, PUNICODE_STRING PortName, PSECURITY_QUALITY_OF_SERVICE SecurityQos, PPORT_VIEW ClientView, PSID RequiredServerSid, PREMOTE_PORT_VIEW ServerView, PULONG MaxMessageLength, PVOID ConnectionInformation, PULONG ConnectionInformationLength ); NTSTATUS ZwRequestWaitReplyPort( HANDLE PortHandle, PPORT_MESSAGE RequestMessage, PPORT_MESSAGE ReplyMessage ); void KeInitializeSemaphore( PRKSEMAPHORE Semaphore, LONG Count, LONG Limit ); LONG KeReadStateSemaphore( PRKSEMAPHORE Semaphore ); LONG KeReleaseSemaphore( PRKSEMAPHORE Semaphore, KPRIORITY Increment, LONG Adjustment, BOOLEAN Wait ); void KeAttachProcess( PRKPROCESS Process ); void KeDetachProcess( void ); void KeStackAttachProcess( PRKPROCESS PROCESS, PRKAPC_STATE ApcState ); void KeUnstackDetachProcess( PRKAPC_STATE ApcState ); NTSTATUS KeDelayExecutionThread( KPROCESSOR_MODE WaitMode, BOOLEAN Alertable, PLARGE_INTEGER Interval ); KPRIORITY KeQueryPriorityThread( PKTHREAD Thread ); ULONG KeQueryRuntimeThread( PKTHREAD Thread, PULONG UserTime ); LONG KeSetBasePriorityThread( PKTHREAD Thread, LONG Increment ); UCHAR KeSetIdealProcessorThread( PKTHREAD Thread, UCHAR Processor ); NTSTATUS IofCallDriver( PDEVICE_OBJECT DeviceObject, PIRP Irp ); LONG_PTR ObfReferenceObject( PVOID Object ); NTSTATUS ObReferenceObjectByPointer( PVOID Object, ACCESS_MASK DesiredAccess, POBJECT_TYPE ObjectType, KPROCESSOR_MODE AccessMode ); LONG_PTR ObfDereferenceObject( PVOID Object ); NTSTATUS ObQueryNameString( PVOID Object, POBJECT_NAME_INFORMATION ObjectNameInfo, ULONG Length, PULONG ReturnLength ); NTSTATUS ObGetObjectSecurity( PVOID Object, PSECURITY_DESCRIPTOR *SecurityDescriptor, PBOOLEAN MemoryAllocated ); void ObReleaseObjectSecurity( PSECURITY_DESCRIPTOR SecurityDescriptor, BOOLEAN MemoryAllocated ); NTSTATUS ObQueryObjectAuditingByHandle( HANDLE Handle, PBOOLEAN GenerateOnClose );
ac8394bb3b072dbe73991a946cd7f00d326b7e04
15a46f79cc5edfd08ebc63a8416dd02b13a2df33
/Example28/src/main.c
43a3df756fb8a4bf5af472d2e1ceeb7d6eba4ef7
[ "Apache-2.0" ]
permissive
McNopper/OpenGL
a24a99de305f475205b00d39b4dde42d33645c6f
42fa2736e2b37db1df99c2b205279855ec6f2b1d
refs/heads/master
2022-07-16T06:44:44.845154
2022-05-21T11:47:12
2022-05-21T11:47:12
8,373,358
2,270
771
Apache-2.0
2022-05-21T11:51:12
2013-02-23T09:26:37
C
UTF-8
C
false
false
25,679
c
main.c
/** * OpenGL 4 - Example 28 * * @author Norbert Nopper norbert@nopper.tv * * Homepage: http://nopper.tv * * Copyright Norbert Nopper * * see http://john-chapman-graphics.blogspot.co.uk/2013/01/ssao-tutorial.html */ #include <stdio.h> #include "GL/glus.h" #include "wavefront.h" #define KERNEL_SIZE 32 #define SSAO_RADIUS 1.0f #define ROTATION_NOISE_SIDE_LENGTH 4 #define ROTATION_NOISE_SIZE (ROTATION_NOISE_SIDE_LENGTH*ROTATION_NOISE_SIDE_LENGTH) // static GLfloat g_viewMatrix[16]; static GLfloat g_viewProjectionMatrix[16]; static GLfloat g_inverseProjectionMatrix[16]; static GLfloat g_projectionMatrix[16]; // static GLUSprogram g_program; static GLint g_viewProjectionMatrixLocation; static GLint g_modelMatrixLocation; static GLint g_normalMatrixLocation; static GLint g_lightDirectionLocation; static GLint g_repeatLocation; static GLint g_vertexLocation; static GLint g_normalLocation; static GLint g_texCoordLocation; static GLint g_textureLocation; // static GLuint g_verticesVBO; static GLuint g_normalsVBO; static GLuint g_texCoordsVBO; static GLuint g_indicesVBO; static GLuint g_numberIndicesPlane; // static GLuint g_vao; // static GLuint g_texture; // // // static GLuint g_ssaoTexture; static GLuint g_ssaoDepthTexture; static GLuint g_ssaoNormalTexture; static GLuint g_ssaoFBO; static GLuint g_ssaoRotationNoiseTexture; // static GLuint g_blurTexture; static GLuint g_blurFBO; // // // static GLUSprogram g_ssaoProgram; static GLint g_ssaoVertexLocation; static GLint g_ssaoTexCoordLocation; static GLint g_ssaoTextureLocation; static GLint g_ssaoNormalTextureLocation; static GLint g_ssaoDepthTextureLocation; static GLint g_ssaoKernelLocation; static GLint g_ssaoRotationNoiseTextureLocation; static GLint g_ssaoRotationNoiseScaleLocation; static GLint g_ssaoInverseProjectionMatrixLocation; static GLint g_ssaoProjectionMatrixLocation; static GLint g_ssaoRadiusLocation; // static GLUSprogram g_blurProgram; static GLint g_blurVertexLocation; static GLint g_blurTexCoordLocation; static GLint g_blurColorTextureLocation; static GLint g_blurSSAOTextureLocation; static GLint g_blurTexelStepLocation; static GLint g_blurNoSSAOLocation; // static GLuint g_postprocessVerticesVBO; static GLuint g_postprocessTexCoordsVBO; static GLuint g_postprocessIndicesVBO; static GLuint g_numberIndicesPostprocessPlane; // static GLuint g_ssaoVAO; static GLuint g_blurVAO; // static struct LightProperties g_light = { { 1.0f, 1.0f, 1.0f }, { 0.3f, 0.3f, 0.3f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f }, { 1.0f, 1.0f, 1.0f, 1.0f } }; static struct CameraProperties g_camera = { { 0.0f, 15.0f, 15.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }; static GLfloat g_kernel[3 * KERNEL_SIZE]; static GLfloat g_rotationNoise[3 * ROTATION_NOISE_SIZE]; static GLfloat g_rotationNoiseScale[2]; static GLfloat g_texelStep[2]; GLUSboolean init(GLUSvoid) { GLUStextfile vertexSource; GLUStextfile fragmentSource; GLUStgaimage image; GLUSshape plane; GLint i; // glusMatrix4x4LookAtf(g_viewMatrix, g_camera.eye[0], g_camera.eye[1], g_camera.eye[2], g_camera.center[0], g_camera.center[1], g_camera.center[2], g_camera.up[0], g_camera.up[1], g_camera.up[2]); // if (!initWavefront(g_viewMatrix, &g_light)) { return GLUS_FALSE; } // glusFileLoadText("../Example28/shader/texture.vert.glsl", &vertexSource); glusFileLoadText("../Example28/shader/texture.frag.glsl", &fragmentSource); glusProgramBuildFromSource(&g_program, (const GLUSchar**)&vertexSource.text, 0, 0, 0, (const GLUSchar**)&fragmentSource.text); glusFileDestroyText(&vertexSource); glusFileDestroyText(&fragmentSource); // // Retrieve the uniform locations in the program. g_viewProjectionMatrixLocation = glGetUniformLocation(g_program.program, "u_viewProjectionMatrix"); g_modelMatrixLocation = glGetUniformLocation(g_program.program, "u_modelMatrix"); g_normalMatrixLocation = glGetUniformLocation(g_program.program, "u_normalMatrix"); g_lightDirectionLocation = glGetUniformLocation(g_program.program, "u_lightDirection"); g_repeatLocation = glGetUniformLocation(g_program.program, "u_repeat"); g_textureLocation = glGetUniformLocation(g_program.program, "u_texture"); // Retrieve the attribute locations in the program. g_vertexLocation = glGetAttribLocation(g_program.program, "a_vertex"); g_normalLocation = glGetAttribLocation(g_program.program, "a_normal"); g_texCoordLocation = glGetAttribLocation(g_program.program, "a_texCoord"); // // SSAO shader etc. // glusFileLoadText("../Example28/shader/ssao.vert.glsl", &vertexSource); glusFileLoadText("../Example28/shader/ssao.frag.glsl", &fragmentSource); glusProgramBuildFromSource(&g_ssaoProgram, (const GLUSchar**)&vertexSource.text, 0, 0, 0, (const GLUSchar**)&fragmentSource.text); glusFileDestroyText(&vertexSource); glusFileDestroyText(&fragmentSource); // // Retrieve the uniform locations in the program. g_ssaoTextureLocation = glGetUniformLocation(g_ssaoProgram.program, "u_texture"); g_ssaoNormalTextureLocation = glGetUniformLocation(g_ssaoProgram.program, "u_normalTexture"); g_ssaoDepthTextureLocation = glGetUniformLocation(g_ssaoProgram.program, "u_depthTexture"); g_ssaoKernelLocation = glGetUniformLocation(g_ssaoProgram.program, "u_kernel"); g_ssaoRotationNoiseTextureLocation = glGetUniformLocation(g_ssaoProgram.program, "u_rotationNoiseTexture"); g_ssaoRotationNoiseScaleLocation = glGetUniformLocation(g_ssaoProgram.program, "u_rotationNoiseScale"); g_ssaoInverseProjectionMatrixLocation = glGetUniformLocation(g_ssaoProgram.program, "u_inverseProjectionMatrix"); g_ssaoProjectionMatrixLocation = glGetUniformLocation(g_ssaoProgram.program, "u_projectionMatrix"); g_ssaoRadiusLocation = glGetUniformLocation(g_ssaoProgram.program, "u_radius"); // Retrieve the attribute locations in the program. g_ssaoVertexLocation = glGetAttribLocation(g_ssaoProgram.program, "a_vertex"); g_ssaoTexCoordLocation = glGetAttribLocation(g_ssaoProgram.program, "a_texCoord"); // // Blur shader etc. // glusFileLoadText("../Example28/shader/blur.vert.glsl", &vertexSource); glusFileLoadText("../Example28/shader/blur.frag.glsl", &fragmentSource); glusProgramBuildFromSource(&g_blurProgram, (const GLUSchar**)&vertexSource.text, 0, 0, 0, (const GLUSchar**)&fragmentSource.text); glusFileDestroyText(&vertexSource); glusFileDestroyText(&fragmentSource); // // Retrieve the uniform locations in the program. g_blurColorTextureLocation = glGetUniformLocation(g_blurProgram.program, "u_colorTexture"); g_blurSSAOTextureLocation = glGetUniformLocation(g_blurProgram.program, "u_ssaoTexture"); g_blurTexelStepLocation = glGetUniformLocation(g_blurProgram.program, "u_texelStep"); g_blurNoSSAOLocation = glGetUniformLocation(g_blurProgram.program, "u_noSSAO"); // Retrieve the attribute locations in the program. g_blurVertexLocation = glGetAttribLocation(g_blurProgram.program, "a_vertex"); g_blurTexCoordLocation = glGetAttribLocation(g_blurProgram.program, "a_texCoord"); // // Texture set up for the ground plane. // glusImageLoadTga("wood_texture.tga", &image); glGenTextures(1, &g_texture); glBindTexture(GL_TEXTURE_2D, g_texture); glTexImage2D(GL_TEXTURE_2D, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data); // Mipmap generation is now included in OpenGL 3 and above glGenerateMipmap(GL_TEXTURE_2D); // Trilinear filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glBindTexture(GL_TEXTURE_2D, 0); // // Setting up the SSAO frame buffer. // glGenTextures(1, &g_ssaoTexture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, g_ssaoTexture); glTexImage2D(GL_TEXTURE_2D, 0, GLUS_RGB, TEXTURE_WIDTH, TEXTURE_HEIGHT, 0, GLUS_RGB, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); // glGenTextures(1, &g_ssaoNormalTexture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, g_ssaoNormalTexture); glTexImage2D(GL_TEXTURE_2D, 0, GLUS_RGB, TEXTURE_WIDTH, TEXTURE_HEIGHT, 0, GLUS_RGB, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); // glGenTextures(1, &g_ssaoDepthTexture); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, g_ssaoDepthTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, TEXTURE_WIDTH, TEXTURE_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); // glGenFramebuffers(1, &g_ssaoFBO); glBindFramebuffer(GL_FRAMEBUFFER, g_ssaoFBO); // Attach the color buffer ... glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, g_ssaoTexture, 0); // Attach the normal buffer ... glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, g_ssaoNormalTexture, 0); // ... and the depth buffer, glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, g_ssaoDepthTexture, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { printf("GL_FRAMEBUFFER_COMPLETE error 0x%x", glCheckFramebufferStatus(GL_FRAMEBUFFER)); return GLUS_FALSE; } glBindFramebuffer(GL_FRAMEBUFFER, 0); // // Setting up the blur frame buffer // glGenTextures(1, &g_blurTexture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, g_blurTexture); glTexImage2D(GL_TEXTURE_2D, 0, GLUS_RGB, TEXTURE_WIDTH, TEXTURE_HEIGHT, 0, GLUS_RGB, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); // glGenFramebuffers(1, &g_blurFBO); glBindFramebuffer(GL_FRAMEBUFFER, g_blurFBO); // Attach the color buffer ... glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, g_blurTexture, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { printf("GL_FRAMEBUFFER_COMPLETE error 0x%x", glCheckFramebufferStatus(GL_FRAMEBUFFER)); return GLUS_FALSE; } glBindFramebuffer(GL_FRAMEBUFFER, 0); // // Ground plane setup. // glusShapeCreatePlanef(&plane, 20.0f); g_numberIndicesPlane = plane.numberIndices; glGenBuffers(1, &g_verticesVBO); glBindBuffer(GL_ARRAY_BUFFER, g_verticesVBO); glBufferData(GL_ARRAY_BUFFER, plane.numberVertices * 4 * sizeof(GLfloat), (GLfloat*)plane.vertices, GL_STATIC_DRAW); glGenBuffers(1, &g_normalsVBO); glBindBuffer(GL_ARRAY_BUFFER, g_normalsVBO); glBufferData(GL_ARRAY_BUFFER, plane.numberVertices * 3 * sizeof(GLfloat), (GLfloat*)plane.normals, GL_STATIC_DRAW); glGenBuffers(1, &g_texCoordsVBO); glBindBuffer(GL_ARRAY_BUFFER, g_texCoordsVBO); glBufferData(GL_ARRAY_BUFFER, plane.numberVertices * 2 * sizeof(GLfloat), (GLfloat*)plane.texCoords, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &g_indicesVBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesVBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, plane.numberIndices * sizeof(GLuint), (GLuint*)plane.indices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glusShapeDestroyf(&plane); // glUseProgram(g_program.program); glGenVertexArrays(1, &g_vao); glBindVertexArray(g_vao); glBindBuffer(GL_ARRAY_BUFFER, g_verticesVBO); glVertexAttribPointer(g_vertexLocation, 4, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_vertexLocation); glBindBuffer(GL_ARRAY_BUFFER, g_normalsVBO); glVertexAttribPointer(g_normalLocation, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_normalLocation); glBindBuffer(GL_ARRAY_BUFFER, g_texCoordsVBO); glVertexAttribPointer(g_texCoordLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_texCoordLocation); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesVBO); glBindVertexArray(0); // glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, g_texture); glUniform1i(g_textureLocation, 0); // How many times the surface texture is repeated. glUniform1f(g_repeatLocation, 6.0f); // // Post process plane setup. // glusShapeCreatePlanef(&plane, 1.0f); g_numberIndicesPostprocessPlane = plane.numberIndices; glGenBuffers(1, &g_postprocessVerticesVBO); glBindBuffer(GL_ARRAY_BUFFER, g_postprocessVerticesVBO); glBufferData(GL_ARRAY_BUFFER, plane.numberVertices * 4 * sizeof(GLfloat), (GLfloat*)plane.vertices, GL_STATIC_DRAW); glGenBuffers(1, &g_postprocessTexCoordsVBO); glBindBuffer(GL_ARRAY_BUFFER, g_postprocessTexCoordsVBO); glBufferData(GL_ARRAY_BUFFER, plane.numberVertices * 2 * sizeof(GLfloat), (GLfloat*)plane.texCoords, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &g_postprocessIndicesVBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_postprocessIndicesVBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, plane.numberIndices * sizeof(GLuint), (GLuint*)plane.indices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glusShapeDestroyf(&plane); // glUseProgram(g_ssaoProgram.program); glGenVertexArrays(1, &g_ssaoVAO); glBindVertexArray(g_ssaoVAO); glBindBuffer(GL_ARRAY_BUFFER, g_postprocessVerticesVBO); glVertexAttribPointer(g_ssaoVertexLocation, 4, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_ssaoVertexLocation); glBindBuffer(GL_ARRAY_BUFFER, g_postprocessTexCoordsVBO); glVertexAttribPointer(g_ssaoTexCoordLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_ssaoTexCoordLocation); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_postprocessIndicesVBO); glBindVertexArray(0); // glUniform1i(g_ssaoTextureLocation, 0); glUniform1i(g_ssaoNormalTextureLocation, 1); glUniform1i(g_ssaoDepthTextureLocation, 2); glUniform1i(g_ssaoRotationNoiseTextureLocation, 3); glUniform1f(g_ssaoRadiusLocation, SSAO_RADIUS); // // Create the Kernel for SSAO. // for (i = 0; i < KERNEL_SIZE; i++) { g_kernel[i * 3 + 0] = glusRandomUniformf(-1.0f, 1.0f); g_kernel[i * 3 + 1] = glusRandomUniformf(-1.0f, 1.0f); g_kernel[i * 3 + 2] = glusRandomUniformf(0.0f, 1.0f); // Kernel hemisphere points to positive Z-Axis. glusVector3Normalizef(&g_kernel[i * 3]); // Normalize, so included in the hemisphere. GLfloat scale = (GLfloat)i / (GLfloat)KERNEL_SIZE; // Create a scale value between [0;1[ . scale = glusMathClampf(scale * scale, 0.1f, 1.0f); // Adjust scale, that there are more values closer to the center of the g_kernel. glusVector3MultiplyScalarf(&g_kernel[i * 3], &g_kernel[i * 3], scale); } // Pass g_kernel to shader glUniform3fv(g_ssaoKernelLocation, KERNEL_SIZE, g_kernel); // // Create the rotation noise texture // for (i = 0; i < ROTATION_NOISE_SIZE; i++) { g_rotationNoise[i * 3 + 0] = glusRandomUniformf(-1.0f, 1.0f); g_rotationNoise[i * 3 + 1] = glusRandomUniformf(-1.0f, 1.0f); g_rotationNoise[i * 3 + 2] = 0.0f; // Rotate on x-y-plane, so z is zero. glusVector3Normalizef(&g_rotationNoise[i * 3]); // Normalized rotation vector. } // glGenTextures(1, &g_ssaoRotationNoiseTexture); glBindTexture(GL_TEXTURE_2D, g_ssaoRotationNoiseTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, ROTATION_NOISE_SIDE_LENGTH, ROTATION_NOISE_SIDE_LENGTH, 0, GL_RGB, GL_FLOAT, g_rotationNoise); // No filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glBindTexture(GL_TEXTURE_2D, 0); // // g_rotationNoiseScale[0] = (GLfloat)TEXTURE_WIDTH / (GLfloat)ROTATION_NOISE_SIDE_LENGTH; g_rotationNoiseScale[1] = (GLfloat)TEXTURE_HEIGHT / (GLfloat)ROTATION_NOISE_SIDE_LENGTH; // Pass the scale, as the rotation noise texture is repeated over the screen x / y times. glUniform2fv(g_ssaoRotationNoiseScaleLocation, 1, g_rotationNoiseScale); // // glUseProgram(g_blurProgram.program); glGenVertexArrays(1, &g_blurVAO); glBindVertexArray(g_blurVAO); glBindBuffer(GL_ARRAY_BUFFER, g_postprocessVerticesVBO); glVertexAttribPointer(g_blurVertexLocation, 4, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_blurVertexLocation); glBindBuffer(GL_ARRAY_BUFFER, g_postprocessTexCoordsVBO); glVertexAttribPointer(g_blurTexCoordLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_blurTexCoordLocation); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_postprocessIndicesVBO); glBindVertexArray(0); // glUniform1i(g_blurColorTextureLocation, 0); glUniform1i(g_blurSSAOTextureLocation, 1); g_texelStep[0] = 1.0f / (GLfloat)TEXTURE_WIDTH; g_texelStep[1] = 1.0f / (GLfloat)TEXTURE_HEIGHT; // Pass the value to step from one to another texel. glUniform2fv(g_blurTexelStepLocation, 1, g_texelStep); // Variable to toggle between SSAO on and off glUniform1f(g_blurNoSSAOLocation, 0.0f); // // Basic OpenGL set up. // glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); return GLUS_TRUE; } GLUSvoid reshape(GLUSint width, GLUSint height) { GLfloat modelMatrix[16]; GLfloat modelViewMatrix[16]; GLfloat normalMatrix[9]; GLfloat lightDirection[3]; reshapeWavefront(width, height); // glViewport(0, 0, width, height); glusMatrix4x4Perspectivef(g_projectionMatrix, 40.0f, (GLfloat)width / (GLfloat)height, 1.0f, 100.0f); // Calculate the inverse. Needed for the SSAO shader to get from projection to view space. glusMatrix4x4Copyf(g_inverseProjectionMatrix, g_projectionMatrix, GLUS_FALSE); glusMatrix4x4Inversef(g_inverseProjectionMatrix); glUseProgram(g_ssaoProgram.program); glUniformMatrix4fv(g_ssaoInverseProjectionMatrixLocation, 1, GL_FALSE, g_inverseProjectionMatrix); glUniformMatrix4fv(g_ssaoProjectionMatrixLocation, 1, GL_FALSE, g_projectionMatrix); // glusMatrix4x4Multiplyf(g_viewProjectionMatrix, g_projectionMatrix, g_viewMatrix); glUseProgram(g_program.program); glUniformMatrix4fv(g_viewProjectionMatrixLocation, 1, GL_FALSE, g_viewProjectionMatrix); glusMatrix4x4Identityf(modelMatrix); glusMatrix4x4RotateRxf(modelMatrix, -90.0f); glUniformMatrix4fv(g_modelMatrixLocation, 1, GL_FALSE, modelMatrix); // Calculation is in camera space glusMatrix4x4Multiplyf(modelViewMatrix, g_viewMatrix, modelMatrix); glusMatrix4x4ExtractMatrix3x3f(normalMatrix, modelViewMatrix); glUniformMatrix3fv(g_normalMatrixLocation, 1, GL_FALSE, normalMatrix); glusMatrix4x4MultiplyVector3f(lightDirection, g_viewMatrix, g_light.direction); // Direction already normalized glUniform3fv(g_lightDirectionLocation, 1, lightDirection); } GLUSvoid key(GLUSboolean pressed, GLUSint key) { static GLboolean noSSAO = GL_FALSE; if (pressed) { // w for wireframe on / off if (key == 's') { noSSAO = !noSSAO; if (noSSAO) { glUniform1f(g_blurNoSSAOLocation, 1.0f); } else { glUniform1f(g_blurNoSSAOLocation, 0.0f); } } } } GLUSboolean update(GLUSfloat time) { GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; GLfloat modelMatrix[16]; GLint i; // // Rendering scene to frame buffer. // glBindFramebuffer(GL_FRAMEBUFFER, g_ssaoFBO); glDrawBuffers(2, drawBuffers); reshape(TEXTURE_WIDTH, TEXTURE_HEIGHT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); for (i = 0; i < 3; i++) { glusMatrix4x4Identityf(modelMatrix); glusMatrix4x4Translatef(modelMatrix, (GLfloat)(i - 1) * 4.1f, 0.0f, 0.0f); glusMatrix4x4RotateRyf(modelMatrix, 45.0f); if (!updateWavefront(time, modelMatrix)) { return GLUS_FALSE; } } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, g_texture); glUseProgram(g_program.program); glBindVertexArray(g_vao); glDrawElements(GL_TRIANGLES, g_numberIndicesPlane, GL_UNSIGNED_INT, 0); // // SSAO rendering step. // glBindFramebuffer(GL_FRAMEBUFFER, g_blurFBO); glDrawBuffer(GL_COLOR_ATTACHMENT0); glClear(GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, g_ssaoTexture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, g_ssaoNormalTexture); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, g_ssaoDepthTexture); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, g_ssaoRotationNoiseTexture); glActiveTexture(GL_TEXTURE0); glUseProgram(g_ssaoProgram.program); glBindVertexArray(g_ssaoVAO); glDrawElements(GL_TRIANGLES, g_numberIndicesPostprocessPlane, GL_UNSIGNED_INT, 0); glBindTexture(GL_TEXTURE_2D, 0); // // Blur rendering step. // glBindFramebuffer(GL_FRAMEBUFFER, 0); glDrawBuffer(GL_COLOR_ATTACHMENT0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, g_ssaoTexture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, g_blurTexture); glActiveTexture(GL_TEXTURE0); glUseProgram(g_blurProgram.program); glBindVertexArray(g_blurVAO); glDrawElements(GL_TRIANGLES, g_numberIndicesPostprocessPlane, GL_UNSIGNED_INT, 0); glBindTexture(GL_TEXTURE_2D, 0); return GLUS_TRUE; } GLUSvoid terminate(GLUSvoid) { glBindBuffer(GL_ARRAY_BUFFER, 0); if (g_verticesVBO) { glDeleteBuffers(1, &g_verticesVBO); g_verticesVBO = 0; } if (g_normalsVBO) { glDeleteBuffers(1, &g_normalsVBO); g_normalsVBO = 0; } if (g_texCoordsVBO) { glDeleteBuffers(1, &g_texCoordsVBO); g_texCoordsVBO = 0; } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); if (g_indicesVBO) { glDeleteBuffers(1, &g_indicesVBO); g_indicesVBO = 0; } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); if (g_texture) { glDeleteTextures(1, &g_texture); g_texture = 0; } glBindVertexArray(0); if (g_vao) { glDeleteVertexArrays(1, &g_vao); g_vao = 0; } glUseProgram(0); glusProgramDestroy(&g_program); // if (g_postprocessVerticesVBO) { glDeleteBuffers(1, &g_postprocessVerticesVBO); g_postprocessVerticesVBO = 0; } if (g_postprocessTexCoordsVBO) { glDeleteBuffers(1, &g_postprocessTexCoordsVBO); g_postprocessTexCoordsVBO = 0; } if (g_postprocessIndicesVBO) { glDeleteBuffers(1, &g_postprocessIndicesVBO); g_postprocessIndicesVBO = 0; } if (g_ssaoVAO) { glDeleteVertexArrays(1, &g_ssaoVAO); g_ssaoVAO = 0; } if (g_blurVAO) { glDeleteVertexArrays(1, &g_blurVAO); g_blurVAO = 0; } glusProgramDestroy(&g_ssaoProgram); glusProgramDestroy(&g_blurProgram); // glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); if (g_ssaoTexture) { glDeleteTextures(1, &g_ssaoTexture); g_ssaoTexture = 0; } glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); if (g_ssaoNormalTexture) { glDeleteTextures(1, &g_ssaoNormalTexture); g_ssaoNormalTexture = 0; } glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, 0); if (g_ssaoDepthTexture) { glDeleteTextures(1, &g_ssaoDepthTexture); g_ssaoDepthTexture = 0; } glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, 0); if (g_ssaoRotationNoiseTexture) { glDeleteTextures(1, &g_ssaoRotationNoiseTexture); g_ssaoRotationNoiseTexture = 0; } glBindFramebuffer(GL_FRAMEBUFFER, 0); if (g_ssaoFBO) { glDeleteFramebuffers(1, &g_ssaoFBO); g_ssaoFBO = 0; } // if (g_blurTexture) { glDeleteTextures(1, &g_blurTexture); g_blurTexture = 0; } if (g_blurFBO) { glDeleteFramebuffers(1, &g_blurFBO); g_blurFBO = 0; } // terminateWavefront(); } int main(int argc, char* argv[]) { EGLint eglConfigAttributes[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 0, EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_NONE }; EGLint eglContextAttributes[] = { EGL_CONTEXT_MAJOR_VERSION, 4, EGL_CONTEXT_MINOR_VERSION, 1, EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE, EGL_TRUE, EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, EGL_NONE }; glusWindowSetInitFunc(init); glusWindowSetReshapeFunc(reshape); glusWindowSetKeyFunc(key); glusWindowSetUpdateFunc(update); glusWindowSetTerminateFunc(terminate); // No resizing for convenience. If resizing is allowed, dynamically resize the SSAO and Blur frame buffer as well. if (!glusWindowCreate("GLUS Example Window", TEXTURE_WIDTH, TEXTURE_HEIGHT, GLUS_FALSE, GLUS_TRUE, eglConfigAttributes, eglContextAttributes, 0)) { printf("Could not create window!\n"); return -1; } // Print out the keys printf("Keys:\n"); printf("s = Toggle SSAO on/off\n"); glusWindowRun(); return 0; }
7db2f9b4fc727a68cf9054963f9e3c4b68862381
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/stage0/stdlib/Lean/Compiler/LCNF/MonoTypes.c
a87204fc00236185cbcca1cfbb3c8d529aea0d7e
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
2023-08-30T01:57:45.786981
2023-08-29T23:14:28
2023-08-29T23:14:28
129,571,436
2,827
311
Apache-2.0
2023-09-14T18:29:16
2018-04-15T02:49:20
Lean
UTF-8
C
false
false
131,038
c
MonoTypes.c
// Lean compiler output // Module: Lean.Compiler.LCNF.MonoTypes // Imports: Init Lean.Meta.InferType Lean.Compiler.LCNF.Util Lean.Compiler.LCNF.BaseTypes Lean.Compiler.LCNF.CompilerM #include <lean/lean.h> #if defined(__clang__) #pragma clang diagnostic ignored "-Wunused-parameter" #pragma clang diagnostic ignored "-Wunused-label" #elif defined(__GNUC__) && !defined(__CLANG__) #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-label" #pragma GCC diagnostic ignored "-Wunused-but-set-variable" #endif #ifdef __cplusplus extern "C" { #endif lean_object* l_Lean_Expr_const___override(lean_object*, lean_object*); static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__16; lean_object* l___private_Init_Util_0__outOfBounds___rarg(lean_object*); lean_object* l_Lean_Name_reprPrec(lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__2; LEAN_EXPORT lean_object* l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___lambda__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Lean_Expr_withAppAux___at_Lean_Compiler_LCNF_toMonoType___spec__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__15; static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__11; LEAN_EXPORT lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____boxed(lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__24; lean_object* lean_mk_empty_array_with_capacity(lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__9; lean_object* l___private_Lean_Expr_0__Lean_Expr_getAppNumArgsAux(lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_toMonoType_visitApp(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_monoTypeExt; extern lean_object* l_Lean_Compiler_LCNF_builtinRuntimeTypes; LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__9; lean_object* l_Lean_Meta_isProp(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__30; uint8_t l_List_elem___at_Lean_NameHashSet_insert___spec__2(lean_object*, lean_object*); static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__3; lean_object* l_Lean_Core_instInhabitedCoreM___boxed(lean_object*, lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__11; LEAN_EXPORT lean_object* l_panic___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__1(lean_object*, lean_object*, lean_object*, lean_object*); lean_object* l_Lean_Expr_sort___override(lean_object*); static lean_object* l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__2___closed__1; lean_object* lean_array_push(lean_object*, lean_object*); lean_object* l_Array_toSubarray___rarg(lean_object*, lean_object*, lean_object*); lean_object* l_Lean_instBEqLocalInstance___boxed(lean_object*, lean_object*); lean_object* l_Lean_PersistentHashMap_find_x3f___at_Lean_Compiler_LCNF_getOtherDeclBaseType___spec__1(lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__26; lean_object* l_Lean_EnvExtensionInterfaceUnsafe_registerExt___rarg(lean_object*, lean_object*); lean_object* lean_mk_array(lean_object*, lean_object*); extern uint8_t l_instInhabitedBool; LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_MonoTypeExtState_mono___default; extern lean_object* l_Lean_Compiler_LCNF_erasedExpr; lean_object* lean_array_fget(lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__10; static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__14; static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__17; lean_object* l_Lean_Meta_forallTelescopeReducing___at_Lean_Meta_getParamNames___spec__2___rarg(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2(lean_object*, size_t, size_t, lean_object*, lean_object*, lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__4; static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__7; static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__21; static lean_object* l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___closed__1; static lean_object* l_Lean_Compiler_LCNF_instInhabitedTrivialStructureInfo___closed__1; extern lean_object* l_Lean_Expr_instBEqExpr; static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__4; lean_object* l_instBEqProd___rarg(lean_object*, lean_object*, lean_object*, lean_object*); static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__4; static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1___closed__1; lean_object* l_instHashableArray___rarg___boxed(lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__22; static lean_object* l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__2; lean_object* l_Lean_PersistentHashMap_insert___at_Lean_Compiler_LCNF_getOtherDeclBaseType___spec__4(lean_object*, lean_object*, lean_object*); size_t lean_usize_of_nat(lean_object*); static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__18; LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1___lambda__1___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); lean_object* lean_st_ref_take(lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_instReprTrivialStructureInfo; static lean_object* l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__3; lean_object* l_Lean_EnvExtensionInterfaceUnsafe_getState___rarg(lean_object*, lean_object*, lean_object*); lean_object* lean_nat_to_int(lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__6; LEAN_EXPORT lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468_(lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__3(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_toMonoType___closed__1; LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_instInhabitedMonoTypeExtState; LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_initFn____x40_Lean_Compiler_LCNF_MonoTypes___hyg_1970_(lean_object*); lean_object* l_Lean_Meta_isTypeFormerType(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__5; static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__7; LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_instInhabitedTrivialStructureInfo; LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__2(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__2___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); lean_object* lean_st_ref_get(lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_getOtherDeclMonoType___lambda__1(lean_object*, lean_object*, lean_object*); lean_object* lean_st_mk_ref(lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_getParamTypes(lean_object*); static lean_object* l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__1; lean_object* l_EStateM_pure___rarg(lean_object*, lean_object*); uint8_t l_Lean_Compiler_LCNF_isTypeFormerType(lean_object*); extern lean_object* l_Lean_Expr_instHashableExpr; extern lean_object* l_Lean_levelZero; static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__8; extern lean_object* l_Lean_instInhabitedExpr; LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___lambda__1___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_getParamTypes_go(lean_object*, lean_object*); lean_object* l_Lean_instHashableLocalInstance___boxed(lean_object*); lean_object* l_instHashableProd___rarg___boxed(lean_object*, lean_object*, lean_object*); uint8_t lean_name_eq(lean_object*, lean_object*); lean_object* l_Lean_Name_str___override(lean_object*, lean_object*); static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__1; LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__1___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__13; static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__19; lean_object* l___private_Init_Util_0__mkPanicMessageWithDecl(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__31; lean_object* l_Lean_Compiler_LCNF_getOtherDeclBaseType(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__2; LEAN_EXPORT lean_object* l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); uint8_t l_Lean_Expr_isErased(lean_object*); lean_object* l_Lean_EnvExtensionInterfaceUnsafe_imp___elambda__2___rarg(lean_object*, lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__15; LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_toMonoType_visitApp___lambda__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Subarray_forInUnsafe_loop___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__2___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__14; LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields(lean_object*, lean_object*, lean_object*, lean_object*); lean_object* l_Lean_Compiler_LCNF_instantiateForall_go(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__20; LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1___lambda__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Subarray_forInUnsafe_loop___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__2(lean_object*, size_t, size_t, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_toMonoType(lean_object*, lean_object*, lean_object*, lean_object*); lean_object* l_Lean_Expr_app___override(lean_object*, lean_object*); static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__10; lean_object* lean_string_length(lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__18; static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__17; uint8_t lean_nat_dec_eq(lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__23; static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__16; uint8_t lean_nat_dec_lt(lean_object*, lean_object*); static lean_object* l_panic___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__1___closed__1; static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__3; static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__25; static lean_object* l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__5; static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__12; lean_object* lean_array_set(lean_object*, lean_object*, lean_object*); lean_object* lean_panic_fn(lean_object*, lean_object*); static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__6; static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__2; lean_object* lean_nat_sub(lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__1; lean_object* l_Lean_Meta_InfoCacheKey_instHashableInfoCacheKey___boxed(lean_object*); LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_getOtherDeclMonoType(lean_object*, lean_object*, lean_object*, lean_object*); lean_object* l_Lean_mkArrow(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__19; LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_hasTrivialStructure_x3f(lean_object*, lean_object*, lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_instReprTrivialStructureInfo___closed__1; lean_object* l_Lean_PersistentHashMap_mkEmptyEntriesArray(lean_object*, lean_object*); lean_object* l_Array_ofSubarray___rarg(lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__29; lean_object* l_Lean_getConstInfo___at___private_Lean_Compiler_LCNF_Util_0__Lean_Compiler_LCNF_getCasesOnInductiveVal_x3f___spec__1(lean_object*, lean_object*, lean_object*, lean_object*); LEAN_EXPORT lean_object* l_panic___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__1(lean_object*, lean_object*, lean_object*, lean_object*); size_t lean_usize_add(size_t, size_t); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__20; lean_object* lean_array_uget(lean_object*, size_t); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__32; lean_object* lean_st_ref_set(lean_object*, lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__27; static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__5; static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__13; lean_object* l_Lean_Expr_headBeta(lean_object*); lean_object* lean_array_get_size(lean_object*); static lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__12; static lean_object* l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___closed__2; lean_object* lean_infer_type(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*); uint8_t lean_nat_dec_le(lean_object*, lean_object*); uint8_t lean_usize_dec_lt(size_t, size_t); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__8; lean_object* lean_nat_add(lean_object*, lean_object*); lean_object* l_Array_instBEqArray___rarg___boxed(lean_object*, lean_object*, lean_object*); lean_object* lean_expr_instantiate1(lean_object*, lean_object*); static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__1; lean_object* l_Nat_repr(lean_object*); static lean_object* l_Lean_Compiler_LCNF_initFn____x40_Lean_Compiler_LCNF_MonoTypes___hyg_1970____closed__1; static lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__28; static lean_object* _init_l_panic___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__1___closed__1() { _start: { lean_object* x_1; x_1 = lean_alloc_closure((void*)(l_Lean_Core_instInhabitedCoreM___boxed), 3, 1); lean_closure_set(x_1, 0, lean_box(0)); return x_1; } } LEAN_EXPORT lean_object* l_panic___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) { _start: { lean_object* x_5; lean_object* x_6; lean_object* x_7; x_5 = l_panic___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__1___closed__1; x_6 = lean_panic_fn(x_5, x_1); x_7 = lean_apply_3(x_6, x_2, x_3, x_4); return x_7; } } LEAN_EXPORT lean_object* l_Subarray_forInUnsafe_loop___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__2(lean_object* x_1, size_t x_2, size_t x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9) { _start: { uint8_t x_10; x_10 = lean_usize_dec_lt(x_3, x_2); if (x_10 == 0) { lean_object* x_11; lean_dec(x_8); lean_dec(x_7); lean_dec(x_6); lean_dec(x_5); x_11 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_11, 0, x_4); lean_ctor_set(x_11, 1, x_9); return x_11; } else { lean_object* x_12; lean_object* x_13; lean_object* x_14; lean_object* x_15; lean_object* x_21; x_12 = lean_ctor_get(x_1, 0); x_13 = lean_array_uget(x_12, x_3); lean_inc(x_8); lean_inc(x_7); lean_inc(x_6); lean_inc(x_5); x_21 = lean_infer_type(x_13, x_5, x_6, x_7, x_8, x_9); if (lean_obj_tag(x_21) == 0) { lean_object* x_22; lean_object* x_23; lean_object* x_24; x_22 = lean_ctor_get(x_21, 0); lean_inc(x_22); x_23 = lean_ctor_get(x_21, 1); lean_inc(x_23); lean_dec(x_21); lean_inc(x_8); lean_inc(x_7); lean_inc(x_6); lean_inc(x_5); lean_inc(x_22); x_24 = l_Lean_Meta_isProp(x_22, x_5, x_6, x_7, x_8, x_23); if (lean_obj_tag(x_24) == 0) { lean_object* x_25; uint8_t x_26; x_25 = lean_ctor_get(x_24, 0); lean_inc(x_25); x_26 = lean_unbox(x_25); lean_dec(x_25); if (x_26 == 0) { lean_object* x_27; lean_object* x_28; x_27 = lean_ctor_get(x_24, 1); lean_inc(x_27); lean_dec(x_24); lean_inc(x_8); lean_inc(x_7); lean_inc(x_6); lean_inc(x_5); x_28 = l_Lean_Meta_isTypeFormerType(x_22, x_5, x_6, x_7, x_8, x_27); if (lean_obj_tag(x_28) == 0) { lean_object* x_29; uint8_t x_30; x_29 = lean_ctor_get(x_28, 0); lean_inc(x_29); x_30 = lean_unbox(x_29); lean_dec(x_29); if (x_30 == 0) { lean_object* x_31; uint8_t x_32; lean_object* x_33; lean_object* x_34; lean_object* x_35; x_31 = lean_ctor_get(x_28, 1); lean_inc(x_31); lean_dec(x_28); x_32 = 1; x_33 = lean_box(x_32); x_34 = lean_array_push(x_4, x_33); x_35 = lean_alloc_ctor(1, 1, 0); lean_ctor_set(x_35, 0, x_34); x_14 = x_35; x_15 = x_31; goto block_20; } else { lean_object* x_36; uint8_t x_37; lean_object* x_38; lean_object* x_39; lean_object* x_40; x_36 = lean_ctor_get(x_28, 1); lean_inc(x_36); lean_dec(x_28); x_37 = 0; x_38 = lean_box(x_37); x_39 = lean_array_push(x_4, x_38); x_40 = lean_alloc_ctor(1, 1, 0); lean_ctor_set(x_40, 0, x_39); x_14 = x_40; x_15 = x_36; goto block_20; } } else { uint8_t x_41; lean_dec(x_8); lean_dec(x_7); lean_dec(x_6); lean_dec(x_5); lean_dec(x_4); x_41 = !lean_is_exclusive(x_28); if (x_41 == 0) { return x_28; } else { lean_object* x_42; lean_object* x_43; lean_object* x_44; x_42 = lean_ctor_get(x_28, 0); x_43 = lean_ctor_get(x_28, 1); lean_inc(x_43); lean_inc(x_42); lean_dec(x_28); x_44 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_44, 0, x_42); lean_ctor_set(x_44, 1, x_43); return x_44; } } } else { lean_object* x_45; uint8_t x_46; lean_object* x_47; lean_object* x_48; lean_object* x_49; lean_dec(x_22); x_45 = lean_ctor_get(x_24, 1); lean_inc(x_45); lean_dec(x_24); x_46 = 0; x_47 = lean_box(x_46); x_48 = lean_array_push(x_4, x_47); x_49 = lean_alloc_ctor(1, 1, 0); lean_ctor_set(x_49, 0, x_48); x_14 = x_49; x_15 = x_45; goto block_20; } } else { uint8_t x_50; lean_dec(x_22); lean_dec(x_8); lean_dec(x_7); lean_dec(x_6); lean_dec(x_5); lean_dec(x_4); x_50 = !lean_is_exclusive(x_24); if (x_50 == 0) { return x_24; } else { lean_object* x_51; lean_object* x_52; lean_object* x_53; x_51 = lean_ctor_get(x_24, 0); x_52 = lean_ctor_get(x_24, 1); lean_inc(x_52); lean_inc(x_51); lean_dec(x_24); x_53 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_53, 0, x_51); lean_ctor_set(x_53, 1, x_52); return x_53; } } } else { uint8_t x_54; lean_dec(x_8); lean_dec(x_7); lean_dec(x_6); lean_dec(x_5); lean_dec(x_4); x_54 = !lean_is_exclusive(x_21); if (x_54 == 0) { return x_21; } else { lean_object* x_55; lean_object* x_56; lean_object* x_57; x_55 = lean_ctor_get(x_21, 0); x_56 = lean_ctor_get(x_21, 1); lean_inc(x_56); lean_inc(x_55); lean_dec(x_21); x_57 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_57, 0, x_55); lean_ctor_set(x_57, 1, x_56); return x_57; } } block_20: { lean_object* x_16; size_t x_17; size_t x_18; x_16 = lean_ctor_get(x_14, 0); lean_inc(x_16); lean_dec(x_14); x_17 = 1; x_18 = lean_usize_add(x_3, x_17); x_3 = x_18; x_4 = x_16; x_9 = x_15; goto _start; } } } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1___closed__1() { _start: { lean_object* x_1; lean_object* x_2; x_1 = lean_unsigned_to_nat(0u); x_2 = lean_mk_empty_array_with_capacity(x_1); return x_2; } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8) { _start: { lean_object* x_9; lean_object* x_10; lean_object* x_11; lean_object* x_12; size_t x_13; lean_object* x_14; size_t x_15; lean_object* x_16; lean_object* x_17; x_9 = lean_ctor_get(x_1, 3); lean_inc(x_9); lean_dec(x_1); x_10 = lean_array_get_size(x_2); x_11 = l_Array_toSubarray___rarg(x_2, x_9, x_10); x_12 = lean_ctor_get(x_11, 2); lean_inc(x_12); x_13 = lean_usize_of_nat(x_12); lean_dec(x_12); x_14 = lean_ctor_get(x_11, 1); lean_inc(x_14); x_15 = lean_usize_of_nat(x_14); lean_dec(x_14); x_16 = l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1___closed__1; x_17 = l_Subarray_forInUnsafe_loop___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__2(x_11, x_13, x_15, x_16, x_4, x_5, x_6, x_7, x_8); lean_dec(x_11); if (lean_obj_tag(x_17) == 0) { uint8_t x_18; x_18 = !lean_is_exclusive(x_17); if (x_18 == 0) { return x_17; } else { lean_object* x_19; lean_object* x_20; lean_object* x_21; x_19 = lean_ctor_get(x_17, 0); x_20 = lean_ctor_get(x_17, 1); lean_inc(x_20); lean_inc(x_19); lean_dec(x_17); x_21 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_21, 0, x_19); lean_ctor_set(x_21, 1, x_20); return x_21; } } else { uint8_t x_22; x_22 = !lean_is_exclusive(x_17); if (x_22 == 0) { return x_17; } else { lean_object* x_23; lean_object* x_24; lean_object* x_25; x_23 = lean_ctor_get(x_17, 0); x_24 = lean_ctor_get(x_17, 1); lean_inc(x_24); lean_inc(x_23); lean_dec(x_17); x_25 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_25, 0, x_23); lean_ctor_set(x_25, 1, x_24); return x_25; } } } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__1() { _start: { lean_object* x_1; x_1 = lean_mk_string_from_bytes("Lean.Compiler.LCNF.MonoTypes", 28); return x_1; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__2() { _start: { lean_object* x_1; x_1 = lean_mk_string_from_bytes("Lean.Compiler.LCNF.getRelevantCtorFields", 40); return x_1; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__3() { _start: { lean_object* x_1; x_1 = lean_mk_string_from_bytes("unreachable code has been reached", 33); return x_1; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__4() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; lean_object* x_4; lean_object* x_5; lean_object* x_6; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__1; x_2 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__2; x_3 = lean_unsigned_to_nat(18u); x_4 = lean_unsigned_to_nat(47u); x_5 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__3; x_6 = l___private_Init_Util_0__mkPanicMessageWithDecl(x_1, x_2, x_3, x_4, x_5); return x_6; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__5() { _start: { uint8_t x_1; uint8_t x_2; uint8_t x_3; uint8_t x_4; lean_object* x_5; x_1 = 0; x_2 = 1; x_3 = 1; x_4 = 0; x_5 = lean_alloc_ctor(0, 0, 13); lean_ctor_set_uint8(x_5, 0, x_1); lean_ctor_set_uint8(x_5, 1, x_1); lean_ctor_set_uint8(x_5, 2, x_1); lean_ctor_set_uint8(x_5, 3, x_1); lean_ctor_set_uint8(x_5, 4, x_1); lean_ctor_set_uint8(x_5, 5, x_2); lean_ctor_set_uint8(x_5, 6, x_3); lean_ctor_set_uint8(x_5, 7, x_1); lean_ctor_set_uint8(x_5, 8, x_3); lean_ctor_set_uint8(x_5, 9, x_3); lean_ctor_set_uint8(x_5, 10, x_1); lean_ctor_set_uint8(x_5, 11, x_3); lean_ctor_set_uint8(x_5, 12, x_4); return x_5; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__6() { _start: { lean_object* x_1; x_1 = l_Lean_PersistentHashMap_mkEmptyEntriesArray(lean_box(0), lean_box(0)); return x_1; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__7() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__6; x_2 = lean_alloc_ctor(0, 1, 0); lean_ctor_set(x_2, 0, x_1); return x_2; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__8() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__7; x_2 = lean_unsigned_to_nat(0u); x_3 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_3, 0, x_1); lean_ctor_set(x_3, 1, x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__9() { _start: { lean_object* x_1; lean_object* x_2; x_1 = lean_unsigned_to_nat(32u); x_2 = lean_mk_empty_array_with_capacity(x_1); return x_2; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__10() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__9; x_2 = lean_alloc_ctor(0, 1, 0); lean_ctor_set(x_2, 0, x_1); return x_2; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__11() { _start: { size_t x_1; lean_object* x_2; lean_object* x_3; lean_object* x_4; lean_object* x_5; x_1 = 5; x_2 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__10; x_3 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__9; x_4 = lean_unsigned_to_nat(0u); x_5 = lean_alloc_ctor(0, 4, sizeof(size_t)*1); lean_ctor_set(x_5, 0, x_2); lean_ctor_set(x_5, 1, x_3); lean_ctor_set(x_5, 2, x_4); lean_ctor_set(x_5, 3, x_4); lean_ctor_set_usize(x_5, 4, x_1); return x_5; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__12() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__8; x_2 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__11; x_3 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_3, 0, x_1); lean_ctor_set(x_3, 1, x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__13() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; lean_object* x_4; lean_object* x_5; lean_object* x_6; x_1 = lean_box(0); x_2 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__5; x_3 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__12; x_4 = l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1___closed__1; x_5 = lean_unsigned_to_nat(0u); x_6 = lean_alloc_ctor(0, 6, 0); lean_ctor_set(x_6, 0, x_2); lean_ctor_set(x_6, 1, x_3); lean_ctor_set(x_6, 2, x_4); lean_ctor_set(x_6, 3, x_1); lean_ctor_set(x_6, 4, x_5); lean_ctor_set(x_6, 5, x_1); return x_6; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__14() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__7; x_2 = lean_unsigned_to_nat(0u); x_3 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_3, 0, x_1); lean_ctor_set(x_3, 1, x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__15() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__7; x_2 = lean_unsigned_to_nat(0u); x_3 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_3, 0, x_1); lean_ctor_set(x_3, 1, x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__16() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__7; x_2 = lean_unsigned_to_nat(0u); x_3 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_3, 0, x_1); lean_ctor_set(x_3, 1, x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__17() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; lean_object* x_4; lean_object* x_5; x_1 = lean_unsigned_to_nat(0u); x_2 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__14; x_3 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__15; x_4 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__16; x_5 = lean_alloc_ctor(0, 9, 0); lean_ctor_set(x_5, 0, x_1); lean_ctor_set(x_5, 1, x_1); lean_ctor_set(x_5, 2, x_1); lean_ctor_set(x_5, 3, x_2); lean_ctor_set(x_5, 4, x_3); lean_ctor_set(x_5, 5, x_4); lean_ctor_set(x_5, 6, x_2); lean_ctor_set(x_5, 7, x_3); lean_ctor_set(x_5, 8, x_3); return x_5; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__18() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__7; x_2 = lean_unsigned_to_nat(0u); x_3 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_3, 0, x_1); lean_ctor_set(x_3, 1, x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__19() { _start: { lean_object* x_1; x_1 = lean_alloc_closure((void*)(l_Lean_Meta_InfoCacheKey_instHashableInfoCacheKey___boxed), 1, 0); return x_1; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__20() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__7; x_2 = lean_unsigned_to_nat(0u); x_3 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_3, 0, x_1); lean_ctor_set(x_3, 1, x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__21() { _start: { lean_object* x_1; x_1 = lean_alloc_closure((void*)(l_Lean_instBEqLocalInstance___boxed), 2, 0); return x_1; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__22() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__21; x_2 = lean_alloc_closure((void*)(l_Array_instBEqArray___rarg___boxed), 3, 1); lean_closure_set(x_2, 0, x_1); return x_2; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__23() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__22; x_2 = l_Lean_Expr_instBEqExpr; x_3 = lean_alloc_closure((void*)(l_instBEqProd___rarg), 4, 2); lean_closure_set(x_3, 0, x_1); lean_closure_set(x_3, 1, x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__24() { _start: { lean_object* x_1; x_1 = lean_alloc_closure((void*)(l_Lean_instHashableLocalInstance___boxed), 1, 0); return x_1; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__25() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__24; x_2 = lean_alloc_closure((void*)(l_instHashableArray___rarg___boxed), 2, 1); lean_closure_set(x_2, 0, x_1); return x_2; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__26() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__25; x_2 = l_Lean_Expr_instHashableExpr; x_3 = lean_alloc_closure((void*)(l_instHashableProd___rarg___boxed), 3, 2); lean_closure_set(x_3, 0, x_1); lean_closure_set(x_3, 1, x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__27() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__7; x_2 = lean_unsigned_to_nat(0u); x_3 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_3, 0, x_1); lean_ctor_set(x_3, 1, x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__28() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l_Lean_Expr_instBEqExpr; x_2 = lean_alloc_closure((void*)(l_instBEqProd___rarg), 4, 2); lean_closure_set(x_2, 0, x_1); lean_closure_set(x_2, 1, x_1); return x_2; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__29() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l_Lean_Expr_instHashableExpr; x_2 = lean_alloc_closure((void*)(l_instHashableProd___rarg___boxed), 3, 2); lean_closure_set(x_2, 0, x_1); lean_closure_set(x_2, 1, x_1); return x_2; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__30() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__7; x_2 = lean_unsigned_to_nat(0u); x_3 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_3, 0, x_1); lean_ctor_set(x_3, 1, x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__31() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; lean_object* x_4; lean_object* x_5; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__18; x_2 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__20; x_3 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__27; x_4 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__30; x_5 = lean_alloc_ctor(0, 6, 0); lean_ctor_set(x_5, 0, x_1); lean_ctor_set(x_5, 1, x_2); lean_ctor_set(x_5, 2, x_3); lean_ctor_set(x_5, 3, x_1); lean_ctor_set(x_5, 4, x_1); lean_ctor_set(x_5, 5, x_4); return x_5; } } static lean_object* _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__32() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; lean_object* x_4; lean_object* x_5; x_1 = lean_box(0); x_2 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__17; x_3 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__31; x_4 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__11; x_5 = lean_alloc_ctor(0, 4, 0); lean_ctor_set(x_5, 0, x_2); lean_ctor_set(x_5, 1, x_3); lean_ctor_set(x_5, 2, x_1); lean_ctor_set(x_5, 3, x_4); return x_5; } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) { _start: { lean_object* x_5; x_5 = l_Lean_getConstInfo___at___private_Lean_Compiler_LCNF_Util_0__Lean_Compiler_LCNF_getCasesOnInductiveVal_x3f___spec__1(x_1, x_2, x_3, x_4); if (lean_obj_tag(x_5) == 0) { lean_object* x_6; x_6 = lean_ctor_get(x_5, 0); lean_inc(x_6); if (lean_obj_tag(x_6) == 6) { lean_object* x_7; lean_object* x_8; lean_object* x_9; lean_object* x_10; lean_object* x_11; lean_object* x_12; lean_object* x_13; lean_object* x_14; lean_object* x_15; lean_object* x_16; lean_object* x_17; x_7 = lean_ctor_get(x_5, 1); lean_inc(x_7); lean_dec(x_5); x_8 = lean_ctor_get(x_6, 0); lean_inc(x_8); lean_dec(x_6); x_9 = lean_ctor_get(x_8, 0); lean_inc(x_9); x_10 = lean_ctor_get(x_9, 2); lean_inc(x_10); lean_dec(x_9); x_11 = lean_alloc_closure((void*)(l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1___boxed), 8, 1); lean_closure_set(x_11, 0, x_8); x_12 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__32; x_13 = lean_st_mk_ref(x_12, x_7); x_14 = lean_ctor_get(x_13, 0); lean_inc(x_14); x_15 = lean_ctor_get(x_13, 1); lean_inc(x_15); lean_dec(x_13); x_16 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__13; lean_inc(x_14); x_17 = l_Lean_Meta_forallTelescopeReducing___at_Lean_Meta_getParamNames___spec__2___rarg(x_10, x_11, x_16, x_14, x_2, x_3, x_15); if (lean_obj_tag(x_17) == 0) { lean_object* x_18; lean_object* x_19; lean_object* x_20; uint8_t x_21; x_18 = lean_ctor_get(x_17, 0); lean_inc(x_18); x_19 = lean_ctor_get(x_17, 1); lean_inc(x_19); lean_dec(x_17); x_20 = lean_st_ref_get(x_14, x_19); lean_dec(x_14); x_21 = !lean_is_exclusive(x_20); if (x_21 == 0) { lean_object* x_22; x_22 = lean_ctor_get(x_20, 0); lean_dec(x_22); lean_ctor_set(x_20, 0, x_18); return x_20; } else { lean_object* x_23; lean_object* x_24; x_23 = lean_ctor_get(x_20, 1); lean_inc(x_23); lean_dec(x_20); x_24 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_24, 0, x_18); lean_ctor_set(x_24, 1, x_23); return x_24; } } else { uint8_t x_25; lean_dec(x_14); x_25 = !lean_is_exclusive(x_17); if (x_25 == 0) { return x_17; } else { lean_object* x_26; lean_object* x_27; lean_object* x_28; x_26 = lean_ctor_get(x_17, 0); x_27 = lean_ctor_get(x_17, 1); lean_inc(x_27); lean_inc(x_26); lean_dec(x_17); x_28 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_28, 0, x_26); lean_ctor_set(x_28, 1, x_27); return x_28; } } } else { lean_object* x_29; lean_object* x_30; lean_object* x_31; lean_dec(x_6); x_29 = lean_ctor_get(x_5, 1); lean_inc(x_29); lean_dec(x_5); x_30 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__4; x_31 = l_panic___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__1(x_30, x_2, x_3, x_29); return x_31; } } else { uint8_t x_32; lean_dec(x_3); lean_dec(x_2); x_32 = !lean_is_exclusive(x_5); if (x_32 == 0) { return x_5; } else { lean_object* x_33; lean_object* x_34; lean_object* x_35; x_33 = lean_ctor_get(x_5, 0); x_34 = lean_ctor_get(x_5, 1); lean_inc(x_34); lean_inc(x_33); lean_dec(x_5); x_35 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_35, 0, x_33); lean_ctor_set(x_35, 1, x_34); return x_35; } } } } LEAN_EXPORT lean_object* l_Subarray_forInUnsafe_loop___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__2___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9) { _start: { size_t x_10; size_t x_11; lean_object* x_12; x_10 = lean_unbox_usize(x_2); lean_dec(x_2); x_11 = lean_unbox_usize(x_3); lean_dec(x_3); x_12 = l_Subarray_forInUnsafe_loop___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__2(x_1, x_10, x_11, x_4, x_5, x_6, x_7, x_8, x_9); lean_dec(x_1); return x_12; } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8) { _start: { lean_object* x_9; x_9 = l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1(x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8); lean_dec(x_3); return x_9; } } static lean_object* _init_l_Lean_Compiler_LCNF_instInhabitedTrivialStructureInfo___closed__1() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = lean_box(0); x_2 = lean_unsigned_to_nat(0u); x_3 = lean_alloc_ctor(0, 3, 0); lean_ctor_set(x_3, 0, x_1); lean_ctor_set(x_3, 1, x_2); lean_ctor_set(x_3, 2, x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_instInhabitedTrivialStructureInfo() { _start: { lean_object* x_1; x_1 = l_Lean_Compiler_LCNF_instInhabitedTrivialStructureInfo___closed__1; return x_1; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__1() { _start: { lean_object* x_1; x_1 = lean_mk_string_from_bytes("ctorName", 8); return x_1; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__2() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__1; x_2 = lean_alloc_ctor(3, 1, 0); lean_ctor_set(x_2, 0, x_1); return x_2; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__3() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = lean_box(0); x_2 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__2; x_3 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_3, 0, x_1); lean_ctor_set(x_3, 1, x_2); return x_3; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__4() { _start: { lean_object* x_1; x_1 = lean_mk_string_from_bytes(" := ", 4); return x_1; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__5() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__4; x_2 = lean_alloc_ctor(3, 1, 0); lean_ctor_set(x_2, 0, x_1); return x_2; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__6() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__3; x_2 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__5; x_3 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_3, 0, x_1); lean_ctor_set(x_3, 1, x_2); return x_3; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__7() { _start: { lean_object* x_1; lean_object* x_2; x_1 = lean_unsigned_to_nat(12u); x_2 = lean_nat_to_int(x_1); return x_2; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__8() { _start: { lean_object* x_1; x_1 = lean_mk_string_from_bytes(",", 1); return x_1; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__9() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__8; x_2 = lean_alloc_ctor(3, 1, 0); lean_ctor_set(x_2, 0, x_1); return x_2; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__10() { _start: { lean_object* x_1; x_1 = lean_mk_string_from_bytes("numParams", 9); return x_1; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__11() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__10; x_2 = lean_alloc_ctor(3, 1, 0); lean_ctor_set(x_2, 0, x_1); return x_2; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__12() { _start: { lean_object* x_1; lean_object* x_2; x_1 = lean_unsigned_to_nat(13u); x_2 = lean_nat_to_int(x_1); return x_2; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__13() { _start: { lean_object* x_1; x_1 = lean_mk_string_from_bytes("fieldIdx", 8); return x_1; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__14() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__13; x_2 = lean_alloc_ctor(3, 1, 0); lean_ctor_set(x_2, 0, x_1); return x_2; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__15() { _start: { lean_object* x_1; x_1 = lean_mk_string_from_bytes("{ ", 2); return x_1; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__16() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__15; x_2 = lean_string_length(x_1); return x_2; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__17() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__16; x_2 = lean_nat_to_int(x_1); return x_2; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__18() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__15; x_2 = lean_alloc_ctor(3, 1, 0); lean_ctor_set(x_2, 0, x_1); return x_2; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__19() { _start: { lean_object* x_1; x_1 = lean_mk_string_from_bytes(" }", 2); return x_1; } } static lean_object* _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__20() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__19; x_2 = lean_alloc_ctor(3, 1, 0); lean_ctor_set(x_2, 0, x_1); return x_2; } } LEAN_EXPORT lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468_(lean_object* x_1, lean_object* x_2) { _start: { lean_object* x_3; lean_object* x_4; lean_object* x_5; lean_object* x_6; lean_object* x_7; uint8_t x_8; lean_object* x_9; lean_object* x_10; lean_object* x_11; lean_object* x_12; lean_object* x_13; lean_object* x_14; lean_object* x_15; lean_object* x_16; lean_object* x_17; lean_object* x_18; lean_object* x_19; lean_object* x_20; lean_object* x_21; lean_object* x_22; lean_object* x_23; lean_object* x_24; lean_object* x_25; lean_object* x_26; lean_object* x_27; lean_object* x_28; lean_object* x_29; lean_object* x_30; lean_object* x_31; lean_object* x_32; lean_object* x_33; lean_object* x_34; lean_object* x_35; lean_object* x_36; lean_object* x_37; lean_object* x_38; lean_object* x_39; lean_object* x_40; lean_object* x_41; lean_object* x_42; lean_object* x_43; lean_object* x_44; x_3 = lean_ctor_get(x_1, 0); lean_inc(x_3); x_4 = lean_unsigned_to_nat(0u); x_5 = l_Lean_Name_reprPrec(x_3, x_4); x_6 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__7; x_7 = lean_alloc_ctor(4, 2, 0); lean_ctor_set(x_7, 0, x_6); lean_ctor_set(x_7, 1, x_5); x_8 = 0; x_9 = lean_alloc_ctor(6, 1, 1); lean_ctor_set(x_9, 0, x_7); lean_ctor_set_uint8(x_9, sizeof(void*)*1, x_8); x_10 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__6; x_11 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_11, 0, x_10); lean_ctor_set(x_11, 1, x_9); x_12 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__9; x_13 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_13, 0, x_11); lean_ctor_set(x_13, 1, x_12); x_14 = lean_box(1); x_15 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_15, 0, x_13); lean_ctor_set(x_15, 1, x_14); x_16 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__11; x_17 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_17, 0, x_15); lean_ctor_set(x_17, 1, x_16); x_18 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__5; x_19 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_19, 0, x_17); lean_ctor_set(x_19, 1, x_18); x_20 = lean_ctor_get(x_1, 1); lean_inc(x_20); x_21 = l_Nat_repr(x_20); x_22 = lean_alloc_ctor(3, 1, 0); lean_ctor_set(x_22, 0, x_21); x_23 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__12; x_24 = lean_alloc_ctor(4, 2, 0); lean_ctor_set(x_24, 0, x_23); lean_ctor_set(x_24, 1, x_22); x_25 = lean_alloc_ctor(6, 1, 1); lean_ctor_set(x_25, 0, x_24); lean_ctor_set_uint8(x_25, sizeof(void*)*1, x_8); x_26 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_26, 0, x_19); lean_ctor_set(x_26, 1, x_25); x_27 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_27, 0, x_26); lean_ctor_set(x_27, 1, x_12); x_28 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_28, 0, x_27); lean_ctor_set(x_28, 1, x_14); x_29 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__14; x_30 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_30, 0, x_28); lean_ctor_set(x_30, 1, x_29); x_31 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_31, 0, x_30); lean_ctor_set(x_31, 1, x_18); x_32 = lean_ctor_get(x_1, 2); lean_inc(x_32); lean_dec(x_1); x_33 = l_Nat_repr(x_32); x_34 = lean_alloc_ctor(3, 1, 0); lean_ctor_set(x_34, 0, x_33); x_35 = lean_alloc_ctor(4, 2, 0); lean_ctor_set(x_35, 0, x_6); lean_ctor_set(x_35, 1, x_34); x_36 = lean_alloc_ctor(6, 1, 1); lean_ctor_set(x_36, 0, x_35); lean_ctor_set_uint8(x_36, sizeof(void*)*1, x_8); x_37 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_37, 0, x_31); lean_ctor_set(x_37, 1, x_36); x_38 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__18; x_39 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_39, 0, x_38); lean_ctor_set(x_39, 1, x_37); x_40 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__20; x_41 = lean_alloc_ctor(5, 2, 0); lean_ctor_set(x_41, 0, x_39); lean_ctor_set(x_41, 1, x_40); x_42 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__17; x_43 = lean_alloc_ctor(4, 2, 0); lean_ctor_set(x_43, 0, x_42); lean_ctor_set(x_43, 1, x_41); x_44 = lean_alloc_ctor(6, 1, 1); lean_ctor_set(x_44, 0, x_43); lean_ctor_set_uint8(x_44, sizeof(void*)*1, x_8); return x_44; } } LEAN_EXPORT lean_object* l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____boxed(lean_object* x_1, lean_object* x_2) { _start: { lean_object* x_3; x_3 = l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468_(x_1, x_2); lean_dec(x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_instReprTrivialStructureInfo___closed__1() { _start: { lean_object* x_1; x_1 = lean_alloc_closure((void*)(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____boxed), 2, 0); return x_1; } } static lean_object* _init_l_Lean_Compiler_LCNF_instReprTrivialStructureInfo() { _start: { lean_object* x_1; x_1 = l_Lean_Compiler_LCNF_instReprTrivialStructureInfo___closed__1; return x_1; } } LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1___lambda__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9) { _start: { lean_object* x_10; lean_object* x_11; lean_object* x_12; lean_object* x_13; lean_object* x_14; lean_object* x_15; x_10 = lean_ctor_get(x_1, 1); lean_inc(x_10); x_11 = lean_alloc_ctor(0, 3, 0); lean_ctor_set(x_11, 0, x_2); lean_ctor_set(x_11, 1, x_10); lean_ctor_set(x_11, 2, x_3); x_12 = lean_alloc_ctor(1, 1, 0); lean_ctor_set(x_12, 0, x_11); x_13 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_13, 0, x_4); lean_ctor_set(x_13, 1, x_12); x_14 = lean_alloc_ctor(1, 1, 0); lean_ctor_set(x_14, 0, x_13); x_15 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_15, 0, x_14); lean_ctor_set(x_15, 1, x_9); return x_15; } } LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11, lean_object* x_12, lean_object* x_13, lean_object* x_14) { _start: { uint8_t x_15; x_15 = lean_nat_dec_le(x_9, x_8); if (x_15 == 0) { lean_object* x_16; uint8_t x_17; x_16 = lean_unsigned_to_nat(0u); x_17 = lean_nat_dec_eq(x_7, x_16); if (x_17 == 0) { lean_object* x_18; lean_object* x_19; uint8_t x_20; x_18 = lean_unsigned_to_nat(1u); x_19 = lean_nat_sub(x_7, x_18); lean_dec(x_7); x_20 = !lean_is_exclusive(x_11); if (x_20 == 0) { lean_object* x_21; lean_object* x_22; uint8_t x_23; x_21 = lean_ctor_get(x_11, 1); x_22 = lean_ctor_get(x_11, 0); lean_dec(x_22); x_23 = lean_nat_dec_lt(x_8, x_5); if (x_23 == 0) { uint8_t x_24; lean_object* x_25; lean_object* x_26; uint8_t x_27; x_24 = l_instInhabitedBool; x_25 = lean_box(x_24); x_26 = l___private_Init_Util_0__outOfBounds___rarg(x_25); x_27 = lean_unbox(x_26); lean_dec(x_26); if (x_27 == 0) { lean_object* x_28; lean_inc(x_6); lean_ctor_set(x_11, 0, x_6); x_28 = lean_nat_add(x_8, x_10); lean_dec(x_8); x_7 = x_19; x_8 = x_28; goto _start; } else { if (lean_obj_tag(x_21) == 0) { lean_object* x_30; lean_object* x_31; lean_object* x_32; lean_object* x_33; lean_object* x_34; lean_object* x_35; lean_free_object(x_11); x_30 = lean_box(0); lean_inc(x_6); lean_inc(x_8); lean_inc(x_2); x_31 = l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1___lambda__1(x_1, x_2, x_8, x_6, x_21, x_30, x_12, x_13, x_14); x_32 = lean_ctor_get(x_31, 0); lean_inc(x_32); x_33 = lean_ctor_get(x_31, 1); lean_inc(x_33); lean_dec(x_31); x_34 = lean_ctor_get(x_32, 0); lean_inc(x_34); lean_dec(x_32); x_35 = lean_nat_add(x_8, x_10); lean_dec(x_8); x_7 = x_19; x_8 = x_35; x_11 = x_34; x_14 = x_33; goto _start; } else { lean_object* x_37; lean_object* x_38; lean_dec(x_19); lean_dec(x_8); lean_dec(x_6); lean_dec(x_2); x_37 = lean_alloc_ctor(1, 1, 0); lean_ctor_set(x_37, 0, x_4); lean_ctor_set(x_11, 0, x_37); x_38 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_38, 0, x_11); lean_ctor_set(x_38, 1, x_14); return x_38; } } } else { lean_object* x_39; uint8_t x_40; x_39 = lean_array_fget(x_3, x_8); x_40 = lean_unbox(x_39); lean_dec(x_39); if (x_40 == 0) { lean_object* x_41; lean_inc(x_6); lean_ctor_set(x_11, 0, x_6); x_41 = lean_nat_add(x_8, x_10); lean_dec(x_8); x_7 = x_19; x_8 = x_41; goto _start; } else { if (lean_obj_tag(x_21) == 0) { lean_object* x_43; lean_object* x_44; lean_object* x_45; lean_object* x_46; lean_object* x_47; lean_object* x_48; lean_free_object(x_11); x_43 = lean_box(0); lean_inc(x_6); lean_inc(x_8); lean_inc(x_2); x_44 = l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1___lambda__1(x_1, x_2, x_8, x_6, x_21, x_43, x_12, x_13, x_14); x_45 = lean_ctor_get(x_44, 0); lean_inc(x_45); x_46 = lean_ctor_get(x_44, 1); lean_inc(x_46); lean_dec(x_44); x_47 = lean_ctor_get(x_45, 0); lean_inc(x_47); lean_dec(x_45); x_48 = lean_nat_add(x_8, x_10); lean_dec(x_8); x_7 = x_19; x_8 = x_48; x_11 = x_47; x_14 = x_46; goto _start; } else { lean_object* x_50; lean_object* x_51; lean_dec(x_19); lean_dec(x_8); lean_dec(x_6); lean_dec(x_2); x_50 = lean_alloc_ctor(1, 1, 0); lean_ctor_set(x_50, 0, x_4); lean_ctor_set(x_11, 0, x_50); x_51 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_51, 0, x_11); lean_ctor_set(x_51, 1, x_14); return x_51; } } } } else { lean_object* x_52; uint8_t x_53; x_52 = lean_ctor_get(x_11, 1); lean_inc(x_52); lean_dec(x_11); x_53 = lean_nat_dec_lt(x_8, x_5); if (x_53 == 0) { uint8_t x_54; lean_object* x_55; lean_object* x_56; uint8_t x_57; x_54 = l_instInhabitedBool; x_55 = lean_box(x_54); x_56 = l___private_Init_Util_0__outOfBounds___rarg(x_55); x_57 = lean_unbox(x_56); lean_dec(x_56); if (x_57 == 0) { lean_object* x_58; lean_object* x_59; lean_inc(x_6); x_58 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_58, 0, x_6); lean_ctor_set(x_58, 1, x_52); x_59 = lean_nat_add(x_8, x_10); lean_dec(x_8); x_7 = x_19; x_8 = x_59; x_11 = x_58; goto _start; } else { if (lean_obj_tag(x_52) == 0) { lean_object* x_61; lean_object* x_62; lean_object* x_63; lean_object* x_64; lean_object* x_65; lean_object* x_66; x_61 = lean_box(0); lean_inc(x_6); lean_inc(x_8); lean_inc(x_2); x_62 = l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1___lambda__1(x_1, x_2, x_8, x_6, x_52, x_61, x_12, x_13, x_14); x_63 = lean_ctor_get(x_62, 0); lean_inc(x_63); x_64 = lean_ctor_get(x_62, 1); lean_inc(x_64); lean_dec(x_62); x_65 = lean_ctor_get(x_63, 0); lean_inc(x_65); lean_dec(x_63); x_66 = lean_nat_add(x_8, x_10); lean_dec(x_8); x_7 = x_19; x_8 = x_66; x_11 = x_65; x_14 = x_64; goto _start; } else { lean_object* x_68; lean_object* x_69; lean_object* x_70; lean_dec(x_19); lean_dec(x_8); lean_dec(x_6); lean_dec(x_2); x_68 = lean_alloc_ctor(1, 1, 0); lean_ctor_set(x_68, 0, x_4); x_69 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_69, 0, x_68); lean_ctor_set(x_69, 1, x_52); x_70 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_70, 0, x_69); lean_ctor_set(x_70, 1, x_14); return x_70; } } } else { lean_object* x_71; uint8_t x_72; x_71 = lean_array_fget(x_3, x_8); x_72 = lean_unbox(x_71); lean_dec(x_71); if (x_72 == 0) { lean_object* x_73; lean_object* x_74; lean_inc(x_6); x_73 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_73, 0, x_6); lean_ctor_set(x_73, 1, x_52); x_74 = lean_nat_add(x_8, x_10); lean_dec(x_8); x_7 = x_19; x_8 = x_74; x_11 = x_73; goto _start; } else { if (lean_obj_tag(x_52) == 0) { lean_object* x_76; lean_object* x_77; lean_object* x_78; lean_object* x_79; lean_object* x_80; lean_object* x_81; x_76 = lean_box(0); lean_inc(x_6); lean_inc(x_8); lean_inc(x_2); x_77 = l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1___lambda__1(x_1, x_2, x_8, x_6, x_52, x_76, x_12, x_13, x_14); x_78 = lean_ctor_get(x_77, 0); lean_inc(x_78); x_79 = lean_ctor_get(x_77, 1); lean_inc(x_79); lean_dec(x_77); x_80 = lean_ctor_get(x_78, 0); lean_inc(x_80); lean_dec(x_78); x_81 = lean_nat_add(x_8, x_10); lean_dec(x_8); x_7 = x_19; x_8 = x_81; x_11 = x_80; x_14 = x_79; goto _start; } else { lean_object* x_83; lean_object* x_84; lean_object* x_85; lean_dec(x_19); lean_dec(x_8); lean_dec(x_6); lean_dec(x_2); x_83 = lean_alloc_ctor(1, 1, 0); lean_ctor_set(x_83, 0, x_4); x_84 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_84, 0, x_83); lean_ctor_set(x_84, 1, x_52); x_85 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_85, 0, x_84); lean_ctor_set(x_85, 1, x_14); return x_85; } } } } } else { lean_object* x_86; lean_dec(x_8); lean_dec(x_7); lean_dec(x_6); lean_dec(x_4); lean_dec(x_2); x_86 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_86, 0, x_11); lean_ctor_set(x_86, 1, x_14); return x_86; } } else { lean_object* x_87; lean_dec(x_8); lean_dec(x_7); lean_dec(x_6); lean_dec(x_4); lean_dec(x_2); x_87 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_87, 0, x_11); lean_ctor_set(x_87, 1, x_14); return x_87; } } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5) { _start: { lean_object* x_6; x_6 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_6, 0, x_1); lean_ctor_set(x_6, 1, x_5); return x_6; } } static lean_object* _init_l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__2___closed__1() { _start: { lean_object* x_1; lean_object* x_2; x_1 = lean_box(0); x_2 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_2, 0, x_1); lean_ctor_set(x_2, 1, x_1); return x_2; } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__2(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5) { _start: { lean_object* x_6; x_6 = lean_ctor_get(x_1, 4); lean_inc(x_6); if (lean_obj_tag(x_6) == 0) { lean_object* x_7; lean_object* x_8; lean_dec(x_4); lean_dec(x_3); lean_dec(x_1); x_7 = lean_box(0); x_8 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_8, 0, x_7); lean_ctor_set(x_8, 1, x_5); return x_8; } else { lean_object* x_9; x_9 = lean_ctor_get(x_6, 1); lean_inc(x_9); if (lean_obj_tag(x_9) == 0) { lean_object* x_10; lean_object* x_11; x_10 = lean_ctor_get(x_6, 0); lean_inc(x_10); lean_dec(x_6); lean_inc(x_4); lean_inc(x_3); lean_inc(x_10); x_11 = l_Lean_Compiler_LCNF_getRelevantCtorFields(x_10, x_3, x_4, x_5); if (lean_obj_tag(x_11) == 0) { lean_object* x_12; lean_object* x_13; lean_object* x_14; lean_object* x_15; lean_object* x_16; lean_object* x_17; lean_object* x_18; lean_object* x_19; lean_object* x_20; lean_object* x_21; x_12 = lean_ctor_get(x_11, 0); lean_inc(x_12); x_13 = lean_ctor_get(x_11, 1); lean_inc(x_13); lean_dec(x_11); x_14 = lean_box(0); x_15 = lean_array_get_size(x_12); x_16 = lean_unsigned_to_nat(0u); x_17 = lean_unsigned_to_nat(1u); x_18 = l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__2___closed__1; lean_inc(x_15); x_19 = l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1(x_1, x_10, x_12, x_14, x_15, x_14, x_15, x_16, x_15, x_17, x_18, x_3, x_4, x_13); lean_dec(x_4); lean_dec(x_3); lean_dec(x_15); lean_dec(x_12); lean_dec(x_1); x_20 = lean_ctor_get(x_19, 0); lean_inc(x_20); x_21 = lean_ctor_get(x_20, 0); lean_inc(x_21); if (lean_obj_tag(x_21) == 0) { uint8_t x_22; x_22 = !lean_is_exclusive(x_19); if (x_22 == 0) { lean_object* x_23; lean_object* x_24; x_23 = lean_ctor_get(x_19, 0); lean_dec(x_23); x_24 = lean_ctor_get(x_20, 1); lean_inc(x_24); lean_dec(x_20); lean_ctor_set(x_19, 0, x_24); return x_19; } else { lean_object* x_25; lean_object* x_26; lean_object* x_27; x_25 = lean_ctor_get(x_19, 1); lean_inc(x_25); lean_dec(x_19); x_26 = lean_ctor_get(x_20, 1); lean_inc(x_26); lean_dec(x_20); x_27 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_27, 0, x_26); lean_ctor_set(x_27, 1, x_25); return x_27; } } else { uint8_t x_28; lean_dec(x_20); x_28 = !lean_is_exclusive(x_19); if (x_28 == 0) { lean_object* x_29; lean_object* x_30; x_29 = lean_ctor_get(x_19, 0); lean_dec(x_29); x_30 = lean_ctor_get(x_21, 0); lean_inc(x_30); lean_dec(x_21); lean_ctor_set(x_19, 0, x_30); return x_19; } else { lean_object* x_31; lean_object* x_32; lean_object* x_33; x_31 = lean_ctor_get(x_19, 1); lean_inc(x_31); lean_dec(x_19); x_32 = lean_ctor_get(x_21, 0); lean_inc(x_32); lean_dec(x_21); x_33 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_33, 0, x_32); lean_ctor_set(x_33, 1, x_31); return x_33; } } } else { uint8_t x_34; lean_dec(x_10); lean_dec(x_4); lean_dec(x_3); lean_dec(x_1); x_34 = !lean_is_exclusive(x_11); if (x_34 == 0) { return x_11; } else { lean_object* x_35; lean_object* x_36; lean_object* x_37; x_35 = lean_ctor_get(x_11, 0); x_36 = lean_ctor_get(x_11, 1); lean_inc(x_36); lean_inc(x_35); lean_dec(x_11); x_37 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_37, 0, x_35); lean_ctor_set(x_37, 1, x_36); return x_37; } } } else { lean_object* x_38; lean_object* x_39; lean_dec(x_9); lean_dec(x_6); lean_dec(x_4); lean_dec(x_3); lean_dec(x_1); x_38 = lean_box(0); x_39 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_39, 0, x_38); lean_ctor_set(x_39, 1, x_5); return x_39; } } } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__3(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5) { _start: { lean_object* x_6; lean_dec(x_2); x_6 = l_Lean_getConstInfo___at___private_Lean_Compiler_LCNF_Util_0__Lean_Compiler_LCNF_getCasesOnInductiveVal_x3f___spec__1(x_1, x_3, x_4, x_5); if (lean_obj_tag(x_6) == 0) { lean_object* x_7; x_7 = lean_ctor_get(x_6, 0); lean_inc(x_7); if (lean_obj_tag(x_7) == 5) { lean_object* x_8; uint8_t x_9; x_8 = lean_ctor_get(x_7, 0); lean_inc(x_8); lean_dec(x_7); x_9 = lean_ctor_get_uint8(x_8, sizeof(void*)*5 + 1); if (x_9 == 0) { uint8_t x_10; x_10 = lean_ctor_get_uint8(x_8, sizeof(void*)*5); if (x_10 == 0) { lean_object* x_11; lean_object* x_12; lean_object* x_13; x_11 = lean_ctor_get(x_6, 1); lean_inc(x_11); lean_dec(x_6); x_12 = lean_box(0); x_13 = l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__2(x_8, x_12, x_3, x_4, x_11); return x_13; } else { uint8_t x_14; lean_dec(x_8); lean_dec(x_4); lean_dec(x_3); x_14 = !lean_is_exclusive(x_6); if (x_14 == 0) { lean_object* x_15; lean_object* x_16; x_15 = lean_ctor_get(x_6, 0); lean_dec(x_15); x_16 = lean_box(0); lean_ctor_set(x_6, 0, x_16); return x_6; } else { lean_object* x_17; lean_object* x_18; lean_object* x_19; x_17 = lean_ctor_get(x_6, 1); lean_inc(x_17); lean_dec(x_6); x_18 = lean_box(0); x_19 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_19, 0, x_18); lean_ctor_set(x_19, 1, x_17); return x_19; } } } else { uint8_t x_20; lean_dec(x_8); lean_dec(x_4); lean_dec(x_3); x_20 = !lean_is_exclusive(x_6); if (x_20 == 0) { lean_object* x_21; lean_object* x_22; x_21 = lean_ctor_get(x_6, 0); lean_dec(x_21); x_22 = lean_box(0); lean_ctor_set(x_6, 0, x_22); return x_6; } else { lean_object* x_23; lean_object* x_24; lean_object* x_25; x_23 = lean_ctor_get(x_6, 1); lean_inc(x_23); lean_dec(x_6); x_24 = lean_box(0); x_25 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_25, 0, x_24); lean_ctor_set(x_25, 1, x_23); return x_25; } } } else { uint8_t x_26; lean_dec(x_7); lean_dec(x_4); lean_dec(x_3); x_26 = !lean_is_exclusive(x_6); if (x_26 == 0) { lean_object* x_27; lean_object* x_28; x_27 = lean_ctor_get(x_6, 0); lean_dec(x_27); x_28 = lean_box(0); lean_ctor_set(x_6, 0, x_28); return x_6; } else { lean_object* x_29; lean_object* x_30; lean_object* x_31; x_29 = lean_ctor_get(x_6, 1); lean_inc(x_29); lean_dec(x_6); x_30 = lean_box(0); x_31 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_31, 0, x_30); lean_ctor_set(x_31, 1, x_29); return x_31; } } } else { uint8_t x_32; lean_dec(x_4); lean_dec(x_3); x_32 = !lean_is_exclusive(x_6); if (x_32 == 0) { return x_6; } else { lean_object* x_33; lean_object* x_34; lean_object* x_35; x_33 = lean_ctor_get(x_6, 0); x_34 = lean_ctor_get(x_6, 1); lean_inc(x_34); lean_inc(x_33); lean_dec(x_6); x_35 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_35, 0, x_33); lean_ctor_set(x_35, 1, x_34); return x_35; } } } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_hasTrivialStructure_x3f(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) { _start: { lean_object* x_5; uint8_t x_6; x_5 = l_Lean_Compiler_LCNF_builtinRuntimeTypes; x_6 = l_List_elem___at_Lean_NameHashSet_insert___spec__2(x_1, x_5); if (x_6 == 0) { lean_object* x_7; lean_object* x_8; x_7 = lean_box(0); x_8 = l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__3(x_1, x_7, x_2, x_3, x_4); return x_8; } else { lean_object* x_9; lean_object* x_10; lean_dec(x_3); lean_dec(x_2); lean_dec(x_1); x_9 = lean_box(0); x_10 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_10, 0, x_9); lean_ctor_set(x_10, 1, x_4); return x_10; } } } LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1___lambda__1___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9) { _start: { lean_object* x_10; x_10 = l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1___lambda__1(x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8, x_9); lean_dec(x_8); lean_dec(x_7); lean_dec(x_6); lean_dec(x_5); lean_dec(x_1); return x_10; } } LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11, lean_object* x_12, lean_object* x_13, lean_object* x_14) { _start: { lean_object* x_15; x_15 = l_Std_Range_forIn_loop___at_Lean_Compiler_LCNF_hasTrivialStructure_x3f___spec__1(x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12, x_13, x_14); lean_dec(x_13); lean_dec(x_12); lean_dec(x_10); lean_dec(x_9); lean_dec(x_5); lean_dec(x_3); lean_dec(x_1); return x_15; } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__1___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5) { _start: { lean_object* x_6; x_6 = l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__1(x_1, x_2, x_3, x_4, x_5); lean_dec(x_4); lean_dec(x_3); lean_dec(x_2); return x_6; } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__2___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5) { _start: { lean_object* x_6; x_6 = l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__2(x_1, x_2, x_3, x_4, x_5); lean_dec(x_2); return x_6; } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_getParamTypes_go(lean_object* x_1, lean_object* x_2) { _start: { if (lean_obj_tag(x_1) == 7) { lean_object* x_3; lean_object* x_4; lean_object* x_5; x_3 = lean_ctor_get(x_1, 1); lean_inc(x_3); x_4 = lean_ctor_get(x_1, 2); lean_inc(x_4); lean_dec(x_1); x_5 = lean_array_push(x_2, x_3); x_1 = x_4; x_2 = x_5; goto _start; } else { lean_dec(x_1); return x_2; } } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_getParamTypes(lean_object* x_1) { _start: { lean_object* x_2; lean_object* x_3; x_2 = l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1___closed__1; x_3 = l_Lean_Compiler_LCNF_getParamTypes_go(x_1, x_2); return x_3; } } LEAN_EXPORT lean_object* l_panic___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) { _start: { lean_object* x_5; lean_object* x_6; lean_object* x_7; x_5 = l_panic___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__1___closed__1; x_6 = lean_panic_fn(x_5, x_1); x_7 = lean_apply_3(x_6, x_2, x_3, x_4); return x_7; } } LEAN_EXPORT lean_object* l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___lambda__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8) { _start: { lean_object* x_9; lean_object* x_10; lean_object* x_11; lean_object* x_12; x_9 = lean_expr_instantiate1(x_1, x_2); x_10 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_10, 0, x_3); lean_ctor_set(x_10, 1, x_9); x_11 = lean_alloc_ctor(1, 1, 0); lean_ctor_set(x_11, 0, x_10); x_12 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_12, 0, x_11); lean_ctor_set(x_12, 1, x_8); return x_12; } } static lean_object* _init_l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___closed__1() { _start: { lean_object* x_1; x_1 = lean_mk_string_from_bytes("Lean.Compiler.LCNF.toMonoType.visitApp", 38); return x_1; } } static lean_object* _init_l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___closed__2() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; lean_object* x_4; lean_object* x_5; lean_object* x_6; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__1; x_2 = l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___closed__1; x_3 = lean_unsigned_to_nat(98u); x_4 = lean_unsigned_to_nat(50u); x_5 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__3; x_6 = l___private_Init_Util_0__mkPanicMessageWithDecl(x_1, x_2, x_3, x_4, x_5); return x_6; } } LEAN_EXPORT lean_object* l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2(lean_object* x_1, size_t x_2, size_t x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7) { _start: { uint8_t x_8; x_8 = lean_usize_dec_lt(x_3, x_2); if (x_8 == 0) { lean_object* x_9; lean_dec(x_6); lean_dec(x_5); x_9 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_9, 0, x_4); lean_ctor_set(x_9, 1, x_7); return x_9; } else { lean_object* x_10; lean_object* x_11; lean_object* x_29; lean_object* x_30; lean_object* x_31; x_10 = lean_array_uget(x_1, x_3); x_29 = lean_ctor_get(x_4, 0); lean_inc(x_29); x_30 = lean_ctor_get(x_4, 1); lean_inc(x_30); lean_dec(x_4); lean_inc(x_30); x_31 = l_Lean_Expr_headBeta(x_30); if (lean_obj_tag(x_31) == 7) { lean_object* x_32; lean_object* x_33; lean_object* x_34; lean_object* x_35; uint8_t x_47; x_32 = lean_ctor_get(x_31, 1); lean_inc(x_32); x_33 = lean_ctor_get(x_31, 2); lean_inc(x_33); lean_dec(x_31); x_34 = l_Lean_Expr_headBeta(x_10); x_47 = l_Lean_Expr_isErased(x_34); if (x_47 == 0) { uint8_t x_48; x_48 = l_Lean_Expr_isErased(x_32); if (x_48 == 0) { if (lean_obj_tag(x_32) == 3) { lean_object* x_49; lean_dec(x_32); x_49 = lean_box(0); x_35 = x_49; goto block_46; } else { lean_object* x_50; lean_object* x_51; lean_object* x_52; lean_object* x_53; lean_dec(x_32); x_50 = l_Lean_Compiler_LCNF_erasedExpr; x_51 = l_Lean_Expr_app___override(x_29, x_50); x_52 = lean_box(0); x_53 = l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___lambda__1(x_33, x_34, x_51, x_30, x_52, x_5, x_6, x_7); lean_dec(x_30); lean_dec(x_34); lean_dec(x_33); x_11 = x_53; goto block_28; } } else { lean_object* x_54; lean_dec(x_32); x_54 = lean_box(0); x_35 = x_54; goto block_46; } } else { lean_object* x_55; lean_object* x_56; lean_object* x_57; lean_dec(x_32); lean_inc(x_34); x_55 = l_Lean_Expr_app___override(x_29, x_34); x_56 = lean_box(0); x_57 = l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___lambda__1(x_33, x_34, x_55, x_30, x_56, x_5, x_6, x_7); lean_dec(x_30); lean_dec(x_34); lean_dec(x_33); x_11 = x_57; goto block_28; } block_46: { lean_object* x_36; lean_dec(x_35); lean_inc(x_6); lean_inc(x_5); lean_inc(x_34); x_36 = l_Lean_Compiler_LCNF_toMonoType(x_34, x_5, x_6, x_7); if (lean_obj_tag(x_36) == 0) { lean_object* x_37; lean_object* x_38; lean_object* x_39; lean_object* x_40; lean_object* x_41; x_37 = lean_ctor_get(x_36, 0); lean_inc(x_37); x_38 = lean_ctor_get(x_36, 1); lean_inc(x_38); lean_dec(x_36); x_39 = l_Lean_Expr_app___override(x_29, x_37); x_40 = lean_box(0); x_41 = l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___lambda__1(x_33, x_34, x_39, x_30, x_40, x_5, x_6, x_38); lean_dec(x_30); lean_dec(x_34); lean_dec(x_33); x_11 = x_41; goto block_28; } else { uint8_t x_42; lean_dec(x_34); lean_dec(x_33); lean_dec(x_30); lean_dec(x_29); x_42 = !lean_is_exclusive(x_36); if (x_42 == 0) { x_11 = x_36; goto block_28; } else { lean_object* x_43; lean_object* x_44; lean_object* x_45; x_43 = lean_ctor_get(x_36, 0); x_44 = lean_ctor_get(x_36, 1); lean_inc(x_44); lean_inc(x_43); lean_dec(x_36); x_45 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_45, 0, x_43); lean_ctor_set(x_45, 1, x_44); x_11 = x_45; goto block_28; } } } } else { lean_object* x_58; lean_object* x_59; lean_dec(x_31); lean_dec(x_10); x_58 = l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___closed__2; lean_inc(x_6); lean_inc(x_5); x_59 = l_panic___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__1(x_58, x_5, x_6, x_7); if (lean_obj_tag(x_59) == 0) { uint8_t x_60; x_60 = !lean_is_exclusive(x_59); if (x_60 == 0) { lean_object* x_61; lean_object* x_62; lean_object* x_63; x_61 = lean_ctor_get(x_59, 0); lean_dec(x_61); x_62 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_62, 0, x_29); lean_ctor_set(x_62, 1, x_30); x_63 = lean_alloc_ctor(1, 1, 0); lean_ctor_set(x_63, 0, x_62); lean_ctor_set(x_59, 0, x_63); x_11 = x_59; goto block_28; } else { lean_object* x_64; lean_object* x_65; lean_object* x_66; lean_object* x_67; x_64 = lean_ctor_get(x_59, 1); lean_inc(x_64); lean_dec(x_59); x_65 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_65, 0, x_29); lean_ctor_set(x_65, 1, x_30); x_66 = lean_alloc_ctor(1, 1, 0); lean_ctor_set(x_66, 0, x_65); x_67 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_67, 0, x_66); lean_ctor_set(x_67, 1, x_64); x_11 = x_67; goto block_28; } } else { uint8_t x_68; lean_dec(x_30); lean_dec(x_29); x_68 = !lean_is_exclusive(x_59); if (x_68 == 0) { x_11 = x_59; goto block_28; } else { lean_object* x_69; lean_object* x_70; lean_object* x_71; x_69 = lean_ctor_get(x_59, 0); x_70 = lean_ctor_get(x_59, 1); lean_inc(x_70); lean_inc(x_69); lean_dec(x_59); x_71 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_71, 0, x_69); lean_ctor_set(x_71, 1, x_70); x_11 = x_71; goto block_28; } } } block_28: { if (lean_obj_tag(x_11) == 0) { lean_object* x_12; x_12 = lean_ctor_get(x_11, 0); lean_inc(x_12); if (lean_obj_tag(x_12) == 0) { uint8_t x_13; lean_dec(x_6); lean_dec(x_5); x_13 = !lean_is_exclusive(x_11); if (x_13 == 0) { lean_object* x_14; lean_object* x_15; x_14 = lean_ctor_get(x_11, 0); lean_dec(x_14); x_15 = lean_ctor_get(x_12, 0); lean_inc(x_15); lean_dec(x_12); lean_ctor_set(x_11, 0, x_15); return x_11; } else { lean_object* x_16; lean_object* x_17; lean_object* x_18; x_16 = lean_ctor_get(x_11, 1); lean_inc(x_16); lean_dec(x_11); x_17 = lean_ctor_get(x_12, 0); lean_inc(x_17); lean_dec(x_12); x_18 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_18, 0, x_17); lean_ctor_set(x_18, 1, x_16); return x_18; } } else { lean_object* x_19; lean_object* x_20; size_t x_21; size_t x_22; x_19 = lean_ctor_get(x_11, 1); lean_inc(x_19); lean_dec(x_11); x_20 = lean_ctor_get(x_12, 0); lean_inc(x_20); lean_dec(x_12); x_21 = 1; x_22 = lean_usize_add(x_3, x_21); x_3 = x_22; x_4 = x_20; x_7 = x_19; goto _start; } } else { uint8_t x_24; lean_dec(x_6); lean_dec(x_5); x_24 = !lean_is_exclusive(x_11); if (x_24 == 0) { return x_11; } else { lean_object* x_25; lean_object* x_26; lean_object* x_27; x_25 = lean_ctor_get(x_11, 0); x_26 = lean_ctor_get(x_11, 1); lean_inc(x_26); lean_inc(x_25); lean_dec(x_11); x_27 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_27, 0, x_25); lean_ctor_set(x_27, 1, x_26); return x_27; } } } } } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_toMonoType_visitApp___lambda__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7) { _start: { lean_object* x_8; lean_dec(x_4); lean_inc(x_6); lean_inc(x_5); lean_inc(x_1); x_8 = l_Lean_Compiler_LCNF_hasTrivialStructure_x3f(x_1, x_5, x_6, x_7); if (lean_obj_tag(x_8) == 0) { lean_object* x_9; x_9 = lean_ctor_get(x_8, 0); lean_inc(x_9); if (lean_obj_tag(x_9) == 0) { lean_object* x_10; lean_object* x_11; lean_object* x_12; lean_object* x_13; x_10 = lean_ctor_get(x_8, 1); lean_inc(x_10); lean_dec(x_8); x_11 = lean_box(0); lean_inc(x_1); x_12 = l_Lean_Expr_const___override(x_1, x_11); lean_inc(x_6); lean_inc(x_5); x_13 = l_Lean_Compiler_LCNF_getOtherDeclBaseType(x_1, x_2, x_5, x_6, x_10); if (lean_obj_tag(x_13) == 0) { lean_object* x_14; lean_object* x_15; lean_object* x_16; lean_object* x_17; size_t x_18; size_t x_19; lean_object* x_20; x_14 = lean_ctor_get(x_13, 0); lean_inc(x_14); x_15 = lean_ctor_get(x_13, 1); lean_inc(x_15); lean_dec(x_13); x_16 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_16, 0, x_12); lean_ctor_set(x_16, 1, x_14); x_17 = lean_array_get_size(x_3); x_18 = lean_usize_of_nat(x_17); lean_dec(x_17); x_19 = 0; x_20 = l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2(x_3, x_18, x_19, x_16, x_5, x_6, x_15); lean_dec(x_3); if (lean_obj_tag(x_20) == 0) { uint8_t x_21; x_21 = !lean_is_exclusive(x_20); if (x_21 == 0) { lean_object* x_22; lean_object* x_23; x_22 = lean_ctor_get(x_20, 0); x_23 = lean_ctor_get(x_22, 0); lean_inc(x_23); lean_dec(x_22); lean_ctor_set(x_20, 0, x_23); return x_20; } else { lean_object* x_24; lean_object* x_25; lean_object* x_26; lean_object* x_27; x_24 = lean_ctor_get(x_20, 0); x_25 = lean_ctor_get(x_20, 1); lean_inc(x_25); lean_inc(x_24); lean_dec(x_20); x_26 = lean_ctor_get(x_24, 0); lean_inc(x_26); lean_dec(x_24); x_27 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_27, 0, x_26); lean_ctor_set(x_27, 1, x_25); return x_27; } } else { uint8_t x_28; x_28 = !lean_is_exclusive(x_20); if (x_28 == 0) { return x_20; } else { lean_object* x_29; lean_object* x_30; lean_object* x_31; x_29 = lean_ctor_get(x_20, 0); x_30 = lean_ctor_get(x_20, 1); lean_inc(x_30); lean_inc(x_29); lean_dec(x_20); x_31 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_31, 0, x_29); lean_ctor_set(x_31, 1, x_30); return x_31; } } } else { uint8_t x_32; lean_dec(x_12); lean_dec(x_6); lean_dec(x_5); lean_dec(x_3); x_32 = !lean_is_exclusive(x_13); if (x_32 == 0) { return x_13; } else { lean_object* x_33; lean_object* x_34; lean_object* x_35; x_33 = lean_ctor_get(x_13, 0); x_34 = lean_ctor_get(x_13, 1); lean_inc(x_34); lean_inc(x_33); lean_dec(x_13); x_35 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_35, 0, x_33); lean_ctor_set(x_35, 1, x_34); return x_35; } } } else { lean_object* x_36; lean_object* x_37; lean_object* x_38; lean_object* x_39; lean_object* x_40; lean_dec(x_2); lean_dec(x_1); x_36 = lean_ctor_get(x_8, 1); lean_inc(x_36); lean_dec(x_8); x_37 = lean_ctor_get(x_9, 0); lean_inc(x_37); lean_dec(x_9); x_38 = lean_ctor_get(x_37, 0); lean_inc(x_38); x_39 = lean_box(0); lean_inc(x_6); lean_inc(x_5); x_40 = l_Lean_Compiler_LCNF_getOtherDeclBaseType(x_38, x_39, x_5, x_6, x_36); if (lean_obj_tag(x_40) == 0) { lean_object* x_41; lean_object* x_42; lean_object* x_43; lean_object* x_44; lean_object* x_45; lean_object* x_46; lean_object* x_47; x_41 = lean_ctor_get(x_40, 0); lean_inc(x_41); x_42 = lean_ctor_get(x_40, 1); lean_inc(x_42); lean_dec(x_40); x_43 = lean_ctor_get(x_37, 1); lean_inc(x_43); x_44 = lean_unsigned_to_nat(0u); x_45 = l_Array_toSubarray___rarg(x_3, x_44, x_43); x_46 = l_Array_ofSubarray___rarg(x_45); lean_inc(x_5); x_47 = l_Lean_Compiler_LCNF_instantiateForall_go(x_46, x_44, x_41, x_5, x_6, x_42); if (lean_obj_tag(x_47) == 0) { lean_object* x_48; lean_object* x_49; lean_object* x_50; lean_object* x_51; lean_object* x_52; uint8_t x_53; x_48 = lean_ctor_get(x_47, 0); lean_inc(x_48); x_49 = lean_ctor_get(x_47, 1); lean_inc(x_49); lean_dec(x_47); x_50 = l_Lean_Compiler_LCNF_getParamTypes(x_48); x_51 = lean_ctor_get(x_37, 2); lean_inc(x_51); lean_dec(x_37); x_52 = lean_array_get_size(x_50); x_53 = lean_nat_dec_lt(x_51, x_52); lean_dec(x_52); if (x_53 == 0) { lean_object* x_54; lean_object* x_55; lean_object* x_56; lean_dec(x_51); lean_dec(x_50); x_54 = l_Lean_instInhabitedExpr; x_55 = l___private_Init_Util_0__outOfBounds___rarg(x_54); x_56 = l_Lean_Compiler_LCNF_toMonoType(x_55, x_5, x_6, x_49); return x_56; } else { lean_object* x_57; lean_object* x_58; x_57 = lean_array_fget(x_50, x_51); lean_dec(x_51); lean_dec(x_50); x_58 = l_Lean_Compiler_LCNF_toMonoType(x_57, x_5, x_6, x_49); return x_58; } } else { uint8_t x_59; lean_dec(x_37); lean_dec(x_6); lean_dec(x_5); x_59 = !lean_is_exclusive(x_47); if (x_59 == 0) { return x_47; } else { lean_object* x_60; lean_object* x_61; lean_object* x_62; x_60 = lean_ctor_get(x_47, 0); x_61 = lean_ctor_get(x_47, 1); lean_inc(x_61); lean_inc(x_60); lean_dec(x_47); x_62 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_62, 0, x_60); lean_ctor_set(x_62, 1, x_61); return x_62; } } } else { uint8_t x_63; lean_dec(x_37); lean_dec(x_6); lean_dec(x_5); lean_dec(x_3); x_63 = !lean_is_exclusive(x_40); if (x_63 == 0) { return x_40; } else { lean_object* x_64; lean_object* x_65; lean_object* x_66; x_64 = lean_ctor_get(x_40, 0); x_65 = lean_ctor_get(x_40, 1); lean_inc(x_65); lean_inc(x_64); lean_dec(x_40); x_66 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_66, 0, x_64); lean_ctor_set(x_66, 1, x_65); return x_66; } } } } else { uint8_t x_67; lean_dec(x_6); lean_dec(x_5); lean_dec(x_3); lean_dec(x_2); lean_dec(x_1); x_67 = !lean_is_exclusive(x_8); if (x_67 == 0) { return x_8; } else { lean_object* x_68; lean_object* x_69; lean_object* x_70; x_68 = lean_ctor_get(x_8, 0); x_69 = lean_ctor_get(x_8, 1); lean_inc(x_69); lean_inc(x_68); lean_dec(x_8); x_70 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_70, 0, x_68); lean_ctor_set(x_70, 1, x_69); return x_70; } } } } static lean_object* _init_l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__1() { _start: { lean_object* x_1; x_1 = lean_mk_string_from_bytes("Decidable", 9); return x_1; } } static lean_object* _init_l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__2() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = lean_box(0); x_2 = l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__1; x_3 = l_Lean_Name_str___override(x_1, x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__3() { _start: { lean_object* x_1; x_1 = lean_mk_string_from_bytes("Bool", 4); return x_1; } } static lean_object* _init_l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__4() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = lean_box(0); x_2 = l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__3; x_3 = l_Lean_Name_str___override(x_1, x_2); return x_3; } } static lean_object* _init_l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__5() { _start: { lean_object* x_1; lean_object* x_2; lean_object* x_3; x_1 = lean_box(0); x_2 = l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__4; x_3 = l_Lean_Expr_const___override(x_2, x_1); return x_3; } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_toMonoType_visitApp(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5) { _start: { if (lean_obj_tag(x_1) == 4) { lean_object* x_6; lean_object* x_7; lean_object* x_8; uint8_t x_9; x_6 = lean_ctor_get(x_1, 0); lean_inc(x_6); x_7 = lean_ctor_get(x_1, 1); lean_inc(x_7); lean_dec(x_1); x_8 = l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__2; x_9 = lean_name_eq(x_6, x_8); if (x_9 == 0) { lean_object* x_10; lean_object* x_11; x_10 = lean_box(0); x_11 = l_Lean_Compiler_LCNF_toMonoType_visitApp___lambda__1(x_6, x_7, x_2, x_10, x_3, x_4, x_5); return x_11; } else { lean_object* x_12; lean_object* x_13; lean_dec(x_7); lean_dec(x_6); lean_dec(x_4); lean_dec(x_3); lean_dec(x_2); x_12 = l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__5; x_13 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_13, 0, x_12); lean_ctor_set(x_13, 1, x_5); return x_13; } } else { lean_object* x_14; lean_object* x_15; lean_dec(x_4); lean_dec(x_3); lean_dec(x_2); lean_dec(x_1); x_14 = l_Lean_Compiler_LCNF_erasedExpr; x_15 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_15, 0, x_14); lean_ctor_set(x_15, 1, x_5); return x_15; } } } LEAN_EXPORT lean_object* l_Lean_Expr_withAppAux___at_Lean_Compiler_LCNF_toMonoType___spec__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6) { _start: { if (lean_obj_tag(x_1) == 5) { lean_object* x_7; lean_object* x_8; lean_object* x_9; lean_object* x_10; lean_object* x_11; x_7 = lean_ctor_get(x_1, 0); lean_inc(x_7); x_8 = lean_ctor_get(x_1, 1); lean_inc(x_8); lean_dec(x_1); x_9 = lean_array_set(x_2, x_3, x_8); x_10 = lean_unsigned_to_nat(1u); x_11 = lean_nat_sub(x_3, x_10); lean_dec(x_3); x_1 = x_7; x_2 = x_9; x_3 = x_11; goto _start; } else { lean_object* x_13; lean_dec(x_3); x_13 = l_Lean_Compiler_LCNF_toMonoType_visitApp(x_1, x_2, x_4, x_5, x_6); return x_13; } } } static lean_object* _init_l_Lean_Compiler_LCNF_toMonoType___closed__1() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l_Lean_levelZero; x_2 = l_Lean_Expr_sort___override(x_1); return x_2; } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_toMonoType(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) { _start: { lean_object* x_5; uint8_t x_6; x_5 = l_Lean_Expr_headBeta(x_1); x_6 = l_Lean_Expr_isErased(x_5); if (x_6 == 0) { uint8_t x_7; lean_inc(x_5); x_7 = l_Lean_Compiler_LCNF_isTypeFormerType(x_5); if (x_7 == 0) { switch (lean_obj_tag(x_5)) { case 4: { lean_object* x_8; lean_object* x_9; x_8 = l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1___closed__1; x_9 = l_Lean_Compiler_LCNF_toMonoType_visitApp(x_5, x_8, x_2, x_3, x_4); return x_9; } case 5: { lean_object* x_10; lean_object* x_11; lean_object* x_12; lean_object* x_13; lean_object* x_14; lean_object* x_15; lean_object* x_16; x_10 = lean_unsigned_to_nat(0u); x_11 = l___private_Lean_Expr_0__Lean_Expr_getAppNumArgsAux(x_5, x_10); x_12 = l_Lean_Compiler_LCNF_toMonoType___closed__1; lean_inc(x_11); x_13 = lean_mk_array(x_11, x_12); x_14 = lean_unsigned_to_nat(1u); x_15 = lean_nat_sub(x_11, x_14); lean_dec(x_11); x_16 = l_Lean_Expr_withAppAux___at_Lean_Compiler_LCNF_toMonoType___spec__1(x_5, x_13, x_15, x_2, x_3, x_4); return x_16; } case 7: { lean_object* x_17; lean_object* x_18; lean_object* x_19; x_17 = lean_ctor_get(x_5, 1); lean_inc(x_17); x_18 = lean_ctor_get(x_5, 2); lean_inc(x_18); lean_dec(x_5); lean_inc(x_3); lean_inc(x_2); x_19 = l_Lean_Compiler_LCNF_toMonoType(x_17, x_2, x_3, x_4); if (lean_obj_tag(x_19) == 0) { lean_object* x_20; lean_object* x_21; lean_object* x_22; lean_object* x_23; lean_object* x_24; x_20 = lean_ctor_get(x_19, 0); lean_inc(x_20); x_21 = lean_ctor_get(x_19, 1); lean_inc(x_21); lean_dec(x_19); x_22 = l_Lean_Compiler_LCNF_erasedExpr; x_23 = lean_expr_instantiate1(x_18, x_22); lean_dec(x_18); lean_inc(x_3); lean_inc(x_2); x_24 = l_Lean_Compiler_LCNF_toMonoType(x_23, x_2, x_3, x_21); if (lean_obj_tag(x_24) == 0) { lean_object* x_25; lean_object* x_26; lean_object* x_27; x_25 = lean_ctor_get(x_24, 0); lean_inc(x_25); x_26 = lean_ctor_get(x_24, 1); lean_inc(x_26); lean_dec(x_24); x_27 = l_Lean_mkArrow(x_20, x_25, x_2, x_3, x_26); lean_dec(x_3); lean_dec(x_2); return x_27; } else { uint8_t x_28; lean_dec(x_20); lean_dec(x_3); lean_dec(x_2); x_28 = !lean_is_exclusive(x_24); if (x_28 == 0) { return x_24; } else { lean_object* x_29; lean_object* x_30; lean_object* x_31; x_29 = lean_ctor_get(x_24, 0); x_30 = lean_ctor_get(x_24, 1); lean_inc(x_30); lean_inc(x_29); lean_dec(x_24); x_31 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_31, 0, x_29); lean_ctor_set(x_31, 1, x_30); return x_31; } } } else { uint8_t x_32; lean_dec(x_18); lean_dec(x_3); lean_dec(x_2); x_32 = !lean_is_exclusive(x_19); if (x_32 == 0) { return x_19; } else { lean_object* x_33; lean_object* x_34; lean_object* x_35; x_33 = lean_ctor_get(x_19, 0); x_34 = lean_ctor_get(x_19, 1); lean_inc(x_34); lean_inc(x_33); lean_dec(x_19); x_35 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_35, 0, x_33); lean_ctor_set(x_35, 1, x_34); return x_35; } } } default: { lean_object* x_36; lean_object* x_37; lean_dec(x_5); lean_dec(x_3); lean_dec(x_2); x_36 = l_Lean_Compiler_LCNF_erasedExpr; x_37 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_37, 0, x_36); lean_ctor_set(x_37, 1, x_4); return x_37; } } } else { lean_object* x_38; lean_object* x_39; lean_dec(x_5); lean_dec(x_3); lean_dec(x_2); x_38 = l_Lean_Compiler_LCNF_erasedExpr; x_39 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_39, 0, x_38); lean_ctor_set(x_39, 1, x_4); return x_39; } } else { lean_object* x_40; lean_object* x_41; lean_dec(x_5); lean_dec(x_3); lean_dec(x_2); x_40 = l_Lean_Compiler_LCNF_erasedExpr; x_41 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_41, 0, x_40); lean_ctor_set(x_41, 1, x_4); return x_41; } } } LEAN_EXPORT lean_object* l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___lambda__1___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8) { _start: { lean_object* x_9; x_9 = l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___lambda__1(x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8); lean_dec(x_7); lean_dec(x_6); lean_dec(x_5); lean_dec(x_4); lean_dec(x_2); lean_dec(x_1); return x_9; } } LEAN_EXPORT lean_object* l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7) { _start: { size_t x_8; size_t x_9; lean_object* x_10; x_8 = lean_unbox_usize(x_2); lean_dec(x_2); x_9 = lean_unbox_usize(x_3); lean_dec(x_3); x_10 = l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2(x_1, x_8, x_9, x_4, x_5, x_6, x_7); lean_dec(x_1); return x_10; } } static lean_object* _init_l_Lean_Compiler_LCNF_MonoTypeExtState_mono___default() { _start: { lean_object* x_1; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__16; return x_1; } } static lean_object* _init_l_Lean_Compiler_LCNF_instInhabitedMonoTypeExtState() { _start: { lean_object* x_1; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__16; return x_1; } } static lean_object* _init_l_Lean_Compiler_LCNF_initFn____x40_Lean_Compiler_LCNF_MonoTypes___hyg_1970____closed__1() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__16; x_2 = lean_alloc_closure((void*)(l_EStateM_pure___rarg), 2, 1); lean_closure_set(x_2, 0, x_1); return x_2; } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_initFn____x40_Lean_Compiler_LCNF_MonoTypes___hyg_1970_(lean_object* x_1) { _start: { lean_object* x_2; lean_object* x_3; x_2 = l_Lean_Compiler_LCNF_initFn____x40_Lean_Compiler_LCNF_MonoTypes___hyg_1970____closed__1; x_3 = l_Lean_EnvExtensionInterfaceUnsafe_registerExt___rarg(x_2, x_1); return x_3; } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_getOtherDeclMonoType___lambda__1(lean_object* x_1, lean_object* x_2, lean_object* x_3) { _start: { lean_object* x_4; x_4 = l_Lean_PersistentHashMap_insert___at_Lean_Compiler_LCNF_getOtherDeclBaseType___spec__4(x_3, x_1, x_2); return x_4; } } static lean_object* _init_l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__1() { _start: { lean_object* x_1; x_1 = l_Lean_Compiler_LCNF_monoTypeExt; return x_1; } } static lean_object* _init_l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__2() { _start: { lean_object* x_1; lean_object* x_2; x_1 = l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__16; x_2 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_2, 0, x_1); lean_ctor_set(x_2, 1, x_1); return x_2; } } LEAN_EXPORT lean_object* l_Lean_Compiler_LCNF_getOtherDeclMonoType(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4) { _start: { lean_object* x_5; uint8_t x_6; x_5 = lean_st_ref_get(x_3, x_4); x_6 = !lean_is_exclusive(x_5); if (x_6 == 0) { lean_object* x_7; lean_object* x_8; lean_object* x_9; lean_object* x_10; lean_object* x_11; lean_object* x_12; lean_object* x_13; x_7 = lean_ctor_get(x_5, 0); x_8 = lean_ctor_get(x_5, 1); x_9 = lean_ctor_get(x_7, 0); lean_inc(x_9); lean_dec(x_7); x_10 = l_Lean_Compiler_LCNF_instInhabitedMonoTypeExtState; x_11 = l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__1; x_12 = l_Lean_EnvExtensionInterfaceUnsafe_getState___rarg(x_10, x_11, x_9); lean_dec(x_9); lean_inc(x_1); x_13 = l_Lean_PersistentHashMap_find_x3f___at_Lean_Compiler_LCNF_getOtherDeclBaseType___spec__1(x_12, x_1); if (lean_obj_tag(x_13) == 0) { lean_object* x_14; lean_object* x_15; lean_free_object(x_5); x_14 = lean_box(0); lean_inc(x_3); lean_inc(x_2); lean_inc(x_1); x_15 = l_Lean_Compiler_LCNF_getOtherDeclBaseType(x_1, x_14, x_2, x_3, x_8); if (lean_obj_tag(x_15) == 0) { lean_object* x_16; lean_object* x_17; lean_object* x_18; x_16 = lean_ctor_get(x_15, 0); lean_inc(x_16); x_17 = lean_ctor_get(x_15, 1); lean_inc(x_17); lean_dec(x_15); lean_inc(x_3); x_18 = l_Lean_Compiler_LCNF_toMonoType(x_16, x_2, x_3, x_17); if (lean_obj_tag(x_18) == 0) { lean_object* x_19; lean_object* x_20; lean_object* x_21; lean_object* x_22; lean_object* x_23; uint8_t x_24; x_19 = lean_ctor_get(x_18, 0); lean_inc(x_19); x_20 = lean_ctor_get(x_18, 1); lean_inc(x_20); lean_dec(x_18); x_21 = lean_st_ref_take(x_3, x_20); x_22 = lean_ctor_get(x_21, 0); lean_inc(x_22); x_23 = lean_ctor_get(x_21, 1); lean_inc(x_23); lean_dec(x_21); x_24 = !lean_is_exclusive(x_22); if (x_24 == 0) { lean_object* x_25; lean_object* x_26; lean_object* x_27; lean_object* x_28; lean_object* x_29; lean_object* x_30; uint8_t x_31; x_25 = lean_ctor_get(x_22, 0); x_26 = lean_ctor_get(x_22, 4); lean_dec(x_26); lean_inc(x_19); x_27 = lean_alloc_closure((void*)(l_Lean_Compiler_LCNF_getOtherDeclMonoType___lambda__1), 3, 2); lean_closure_set(x_27, 0, x_1); lean_closure_set(x_27, 1, x_19); x_28 = l_Lean_EnvExtensionInterfaceUnsafe_imp___elambda__2___rarg(x_11, x_25, x_27); x_29 = l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__2; lean_ctor_set(x_22, 4, x_29); lean_ctor_set(x_22, 0, x_28); x_30 = lean_st_ref_set(x_3, x_22, x_23); lean_dec(x_3); x_31 = !lean_is_exclusive(x_30); if (x_31 == 0) { lean_object* x_32; x_32 = lean_ctor_get(x_30, 0); lean_dec(x_32); lean_ctor_set(x_30, 0, x_19); return x_30; } else { lean_object* x_33; lean_object* x_34; x_33 = lean_ctor_get(x_30, 1); lean_inc(x_33); lean_dec(x_30); x_34 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_34, 0, x_19); lean_ctor_set(x_34, 1, x_33); return x_34; } } else { lean_object* x_35; lean_object* x_36; lean_object* x_37; lean_object* x_38; lean_object* x_39; lean_object* x_40; lean_object* x_41; lean_object* x_42; lean_object* x_43; lean_object* x_44; lean_object* x_45; lean_object* x_46; lean_object* x_47; lean_object* x_48; x_35 = lean_ctor_get(x_22, 0); x_36 = lean_ctor_get(x_22, 1); x_37 = lean_ctor_get(x_22, 2); x_38 = lean_ctor_get(x_22, 3); x_39 = lean_ctor_get(x_22, 5); x_40 = lean_ctor_get(x_22, 6); lean_inc(x_40); lean_inc(x_39); lean_inc(x_38); lean_inc(x_37); lean_inc(x_36); lean_inc(x_35); lean_dec(x_22); lean_inc(x_19); x_41 = lean_alloc_closure((void*)(l_Lean_Compiler_LCNF_getOtherDeclMonoType___lambda__1), 3, 2); lean_closure_set(x_41, 0, x_1); lean_closure_set(x_41, 1, x_19); x_42 = l_Lean_EnvExtensionInterfaceUnsafe_imp___elambda__2___rarg(x_11, x_35, x_41); x_43 = l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__2; x_44 = lean_alloc_ctor(0, 7, 0); lean_ctor_set(x_44, 0, x_42); lean_ctor_set(x_44, 1, x_36); lean_ctor_set(x_44, 2, x_37); lean_ctor_set(x_44, 3, x_38); lean_ctor_set(x_44, 4, x_43); lean_ctor_set(x_44, 5, x_39); lean_ctor_set(x_44, 6, x_40); x_45 = lean_st_ref_set(x_3, x_44, x_23); lean_dec(x_3); x_46 = lean_ctor_get(x_45, 1); lean_inc(x_46); if (lean_is_exclusive(x_45)) { lean_ctor_release(x_45, 0); lean_ctor_release(x_45, 1); x_47 = x_45; } else { lean_dec_ref(x_45); x_47 = lean_box(0); } if (lean_is_scalar(x_47)) { x_48 = lean_alloc_ctor(0, 2, 0); } else { x_48 = x_47; } lean_ctor_set(x_48, 0, x_19); lean_ctor_set(x_48, 1, x_46); return x_48; } } else { uint8_t x_49; lean_dec(x_3); lean_dec(x_1); x_49 = !lean_is_exclusive(x_18); if (x_49 == 0) { return x_18; } else { lean_object* x_50; lean_object* x_51; lean_object* x_52; x_50 = lean_ctor_get(x_18, 0); x_51 = lean_ctor_get(x_18, 1); lean_inc(x_51); lean_inc(x_50); lean_dec(x_18); x_52 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_52, 0, x_50); lean_ctor_set(x_52, 1, x_51); return x_52; } } } else { uint8_t x_53; lean_dec(x_3); lean_dec(x_2); lean_dec(x_1); x_53 = !lean_is_exclusive(x_15); if (x_53 == 0) { return x_15; } else { lean_object* x_54; lean_object* x_55; lean_object* x_56; x_54 = lean_ctor_get(x_15, 0); x_55 = lean_ctor_get(x_15, 1); lean_inc(x_55); lean_inc(x_54); lean_dec(x_15); x_56 = lean_alloc_ctor(1, 2, 0); lean_ctor_set(x_56, 0, x_54); lean_ctor_set(x_56, 1, x_55); return x_56; } } } else { lean_object* x_57; lean_dec(x_3); lean_dec(x_2); lean_dec(x_1); x_57 = lean_ctor_get(x_13, 0); lean_inc(x_57); lean_dec(x_13); lean_ctor_set(x_5, 0, x_57); return x_5; } } else { lean_object* x_58; lean_object* x_59; lean_object* x_60; lean_object* x_61; lean_object* x_62; lean_object* x_63; lean_object* x_64; x_58 = lean_ctor_get(x_5, 0); x_59 = lean_ctor_get(x_5, 1); lean_inc(x_59); lean_inc(x_58); lean_dec(x_5); x_60 = lean_ctor_get(x_58, 0); lean_inc(x_60); lean_dec(x_58); x_61 = l_Lean_Compiler_LCNF_instInhabitedMonoTypeExtState; x_62 = l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__1; x_63 = l_Lean_EnvExtensionInterfaceUnsafe_getState___rarg(x_61, x_62, x_60); lean_dec(x_60); lean_inc(x_1); x_64 = l_Lean_PersistentHashMap_find_x3f___at_Lean_Compiler_LCNF_getOtherDeclBaseType___spec__1(x_63, x_1); if (lean_obj_tag(x_64) == 0) { lean_object* x_65; lean_object* x_66; x_65 = lean_box(0); lean_inc(x_3); lean_inc(x_2); lean_inc(x_1); x_66 = l_Lean_Compiler_LCNF_getOtherDeclBaseType(x_1, x_65, x_2, x_3, x_59); if (lean_obj_tag(x_66) == 0) { lean_object* x_67; lean_object* x_68; lean_object* x_69; x_67 = lean_ctor_get(x_66, 0); lean_inc(x_67); x_68 = lean_ctor_get(x_66, 1); lean_inc(x_68); lean_dec(x_66); lean_inc(x_3); x_69 = l_Lean_Compiler_LCNF_toMonoType(x_67, x_2, x_3, x_68); if (lean_obj_tag(x_69) == 0) { lean_object* x_70; lean_object* x_71; lean_object* x_72; lean_object* x_73; lean_object* x_74; lean_object* x_75; lean_object* x_76; lean_object* x_77; lean_object* x_78; lean_object* x_79; lean_object* x_80; lean_object* x_81; lean_object* x_82; lean_object* x_83; lean_object* x_84; lean_object* x_85; lean_object* x_86; lean_object* x_87; lean_object* x_88; lean_object* x_89; x_70 = lean_ctor_get(x_69, 0); lean_inc(x_70); x_71 = lean_ctor_get(x_69, 1); lean_inc(x_71); lean_dec(x_69); x_72 = lean_st_ref_take(x_3, x_71); x_73 = lean_ctor_get(x_72, 0); lean_inc(x_73); x_74 = lean_ctor_get(x_72, 1); lean_inc(x_74); lean_dec(x_72); x_75 = lean_ctor_get(x_73, 0); lean_inc(x_75); x_76 = lean_ctor_get(x_73, 1); lean_inc(x_76); x_77 = lean_ctor_get(x_73, 2); lean_inc(x_77); x_78 = lean_ctor_get(x_73, 3); lean_inc(x_78); x_79 = lean_ctor_get(x_73, 5); lean_inc(x_79); x_80 = lean_ctor_get(x_73, 6); lean_inc(x_80); if (lean_is_exclusive(x_73)) { lean_ctor_release(x_73, 0); lean_ctor_release(x_73, 1); lean_ctor_release(x_73, 2); lean_ctor_release(x_73, 3); lean_ctor_release(x_73, 4); lean_ctor_release(x_73, 5); lean_ctor_release(x_73, 6); x_81 = x_73; } else { lean_dec_ref(x_73); x_81 = lean_box(0); } lean_inc(x_70); x_82 = lean_alloc_closure((void*)(l_Lean_Compiler_LCNF_getOtherDeclMonoType___lambda__1), 3, 2); lean_closure_set(x_82, 0, x_1); lean_closure_set(x_82, 1, x_70); x_83 = l_Lean_EnvExtensionInterfaceUnsafe_imp___elambda__2___rarg(x_62, x_75, x_82); x_84 = l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__2; if (lean_is_scalar(x_81)) { x_85 = lean_alloc_ctor(0, 7, 0); } else { x_85 = x_81; } lean_ctor_set(x_85, 0, x_83); lean_ctor_set(x_85, 1, x_76); lean_ctor_set(x_85, 2, x_77); lean_ctor_set(x_85, 3, x_78); lean_ctor_set(x_85, 4, x_84); lean_ctor_set(x_85, 5, x_79); lean_ctor_set(x_85, 6, x_80); x_86 = lean_st_ref_set(x_3, x_85, x_74); lean_dec(x_3); x_87 = lean_ctor_get(x_86, 1); lean_inc(x_87); if (lean_is_exclusive(x_86)) { lean_ctor_release(x_86, 0); lean_ctor_release(x_86, 1); x_88 = x_86; } else { lean_dec_ref(x_86); x_88 = lean_box(0); } if (lean_is_scalar(x_88)) { x_89 = lean_alloc_ctor(0, 2, 0); } else { x_89 = x_88; } lean_ctor_set(x_89, 0, x_70); lean_ctor_set(x_89, 1, x_87); return x_89; } else { lean_object* x_90; lean_object* x_91; lean_object* x_92; lean_object* x_93; lean_dec(x_3); lean_dec(x_1); x_90 = lean_ctor_get(x_69, 0); lean_inc(x_90); x_91 = lean_ctor_get(x_69, 1); lean_inc(x_91); if (lean_is_exclusive(x_69)) { lean_ctor_release(x_69, 0); lean_ctor_release(x_69, 1); x_92 = x_69; } else { lean_dec_ref(x_69); x_92 = lean_box(0); } if (lean_is_scalar(x_92)) { x_93 = lean_alloc_ctor(1, 2, 0); } else { x_93 = x_92; } lean_ctor_set(x_93, 0, x_90); lean_ctor_set(x_93, 1, x_91); return x_93; } } else { lean_object* x_94; lean_object* x_95; lean_object* x_96; lean_object* x_97; lean_dec(x_3); lean_dec(x_2); lean_dec(x_1); x_94 = lean_ctor_get(x_66, 0); lean_inc(x_94); x_95 = lean_ctor_get(x_66, 1); lean_inc(x_95); if (lean_is_exclusive(x_66)) { lean_ctor_release(x_66, 0); lean_ctor_release(x_66, 1); x_96 = x_66; } else { lean_dec_ref(x_66); x_96 = lean_box(0); } if (lean_is_scalar(x_96)) { x_97 = lean_alloc_ctor(1, 2, 0); } else { x_97 = x_96; } lean_ctor_set(x_97, 0, x_94); lean_ctor_set(x_97, 1, x_95); return x_97; } } else { lean_object* x_98; lean_object* x_99; lean_dec(x_3); lean_dec(x_2); lean_dec(x_1); x_98 = lean_ctor_get(x_64, 0); lean_inc(x_98); lean_dec(x_64); x_99 = lean_alloc_ctor(0, 2, 0); lean_ctor_set(x_99, 0, x_98); lean_ctor_set(x_99, 1, x_59); return x_99; } } } } lean_object* initialize_Init(uint8_t builtin, lean_object*); lean_object* initialize_Lean_Meta_InferType(uint8_t builtin, lean_object*); lean_object* initialize_Lean_Compiler_LCNF_Util(uint8_t builtin, lean_object*); lean_object* initialize_Lean_Compiler_LCNF_BaseTypes(uint8_t builtin, lean_object*); lean_object* initialize_Lean_Compiler_LCNF_CompilerM(uint8_t builtin, lean_object*); static bool _G_initialized = false; LEAN_EXPORT lean_object* initialize_Lean_Compiler_LCNF_MonoTypes(uint8_t builtin, lean_object* w) { lean_object * res; if (_G_initialized) return lean_io_result_mk_ok(lean_box(0)); _G_initialized = true; res = initialize_Init(builtin, lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); res = initialize_Lean_Meta_InferType(builtin, lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); res = initialize_Lean_Compiler_LCNF_Util(builtin, lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); res = initialize_Lean_Compiler_LCNF_BaseTypes(builtin, lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); res = initialize_Lean_Compiler_LCNF_CompilerM(builtin, lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; lean_dec_ref(res); l_panic___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__1___closed__1 = _init_l_panic___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__1___closed__1(); lean_mark_persistent(l_panic___at_Lean_Compiler_LCNF_getRelevantCtorFields___spec__1___closed__1); l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1___closed__1 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1___closed__1(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___lambda__1___closed__1); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__1 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__1(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__1); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__2 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__2(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__2); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__3 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__3(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__3); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__4 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__4(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__4); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__5 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__5(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__5); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__6 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__6(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__6); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__7 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__7(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__7); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__8 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__8(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__8); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__9 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__9(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__9); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__10 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__10(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__10); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__11 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__11(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__11); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__12 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__12(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__12); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__13 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__13(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__13); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__14 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__14(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__14); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__15 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__15(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__15); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__16 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__16(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__16); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__17 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__17(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__17); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__18 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__18(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__18); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__19 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__19(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__19); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__20 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__20(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__20); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__21 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__21(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__21); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__22 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__22(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__22); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__23 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__23(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__23); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__24 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__24(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__24); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__25 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__25(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__25); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__26 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__26(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__26); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__27 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__27(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__27); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__28 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__28(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__28); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__29 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__29(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__29); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__30 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__30(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__30); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__31 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__31(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__31); l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__32 = _init_l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__32(); lean_mark_persistent(l_Lean_Compiler_LCNF_getRelevantCtorFields___closed__32); l_Lean_Compiler_LCNF_instInhabitedTrivialStructureInfo___closed__1 = _init_l_Lean_Compiler_LCNF_instInhabitedTrivialStructureInfo___closed__1(); lean_mark_persistent(l_Lean_Compiler_LCNF_instInhabitedTrivialStructureInfo___closed__1); l_Lean_Compiler_LCNF_instInhabitedTrivialStructureInfo = _init_l_Lean_Compiler_LCNF_instInhabitedTrivialStructureInfo(); lean_mark_persistent(l_Lean_Compiler_LCNF_instInhabitedTrivialStructureInfo); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__1 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__1(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__1); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__2 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__2(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__2); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__3 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__3(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__3); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__4 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__4(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__4); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__5 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__5(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__5); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__6 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__6(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__6); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__7 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__7(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__7); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__8 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__8(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__8); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__9 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__9(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__9); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__10 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__10(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__10); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__11 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__11(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__11); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__12 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__12(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__12); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__13 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__13(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__13); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__14 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__14(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__14); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__15 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__15(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__15); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__16 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__16(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__16); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__17 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__17(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__17); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__18 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__18(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__18); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__19 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__19(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__19); l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__20 = _init_l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__20(); lean_mark_persistent(l___private_Lean_Compiler_LCNF_MonoTypes_0__Lean_Compiler_LCNF_reprTrivialStructureInfo____x40_Lean_Compiler_LCNF_MonoTypes___hyg_468____closed__20); l_Lean_Compiler_LCNF_instReprTrivialStructureInfo___closed__1 = _init_l_Lean_Compiler_LCNF_instReprTrivialStructureInfo___closed__1(); lean_mark_persistent(l_Lean_Compiler_LCNF_instReprTrivialStructureInfo___closed__1); l_Lean_Compiler_LCNF_instReprTrivialStructureInfo = _init_l_Lean_Compiler_LCNF_instReprTrivialStructureInfo(); lean_mark_persistent(l_Lean_Compiler_LCNF_instReprTrivialStructureInfo); l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__2___closed__1 = _init_l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__2___closed__1(); lean_mark_persistent(l_Lean_Compiler_LCNF_hasTrivialStructure_x3f___lambda__2___closed__1); l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___closed__1 = _init_l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___closed__1(); lean_mark_persistent(l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___closed__1); l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___closed__2 = _init_l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___closed__2(); lean_mark_persistent(l_Array_forInUnsafe_loop___at_Lean_Compiler_LCNF_toMonoType_visitApp___spec__2___closed__2); l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__1 = _init_l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__1(); lean_mark_persistent(l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__1); l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__2 = _init_l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__2(); lean_mark_persistent(l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__2); l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__3 = _init_l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__3(); lean_mark_persistent(l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__3); l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__4 = _init_l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__4(); lean_mark_persistent(l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__4); l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__5 = _init_l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__5(); lean_mark_persistent(l_Lean_Compiler_LCNF_toMonoType_visitApp___closed__5); l_Lean_Compiler_LCNF_toMonoType___closed__1 = _init_l_Lean_Compiler_LCNF_toMonoType___closed__1(); lean_mark_persistent(l_Lean_Compiler_LCNF_toMonoType___closed__1); l_Lean_Compiler_LCNF_MonoTypeExtState_mono___default = _init_l_Lean_Compiler_LCNF_MonoTypeExtState_mono___default(); lean_mark_persistent(l_Lean_Compiler_LCNF_MonoTypeExtState_mono___default); l_Lean_Compiler_LCNF_instInhabitedMonoTypeExtState = _init_l_Lean_Compiler_LCNF_instInhabitedMonoTypeExtState(); lean_mark_persistent(l_Lean_Compiler_LCNF_instInhabitedMonoTypeExtState); l_Lean_Compiler_LCNF_initFn____x40_Lean_Compiler_LCNF_MonoTypes___hyg_1970____closed__1 = _init_l_Lean_Compiler_LCNF_initFn____x40_Lean_Compiler_LCNF_MonoTypes___hyg_1970____closed__1(); lean_mark_persistent(l_Lean_Compiler_LCNF_initFn____x40_Lean_Compiler_LCNF_MonoTypes___hyg_1970____closed__1); if (builtin) {res = l_Lean_Compiler_LCNF_initFn____x40_Lean_Compiler_LCNF_MonoTypes___hyg_1970_(lean_io_mk_world()); if (lean_io_result_is_error(res)) return res; l_Lean_Compiler_LCNF_monoTypeExt = lean_io_result_get_value(res); lean_mark_persistent(l_Lean_Compiler_LCNF_monoTypeExt); lean_dec_ref(res); }l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__1 = _init_l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__1(); lean_mark_persistent(l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__1); l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__2 = _init_l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__2(); lean_mark_persistent(l_Lean_Compiler_LCNF_getOtherDeclMonoType___closed__2); return lean_io_result_mk_ok(lean_box(0)); } #ifdef __cplusplus } #endif
10730d2f88c695574bc866ac14c9305109303992
fbbe424559f64e9a94116a07eaaa555a01b0a7bb
/Sklearn_scipy_numpy/source/scipy/integrate/tests/_test_multivariate.c
c71affb4a200d8936c1ea08a00a49b4de67d55a3
[ "MIT" ]
permissive
ryfeus/lambda-packs
6544adb4dec19b8e71d75c24d8ed789b785b0369
cabf6e4f1970dc14302f87414f170de19944bac2
refs/heads/master
2022-12-07T16:18:52.475504
2022-11-29T13:35:35
2022-11-29T13:35:35
71,386,735
1,283
263
MIT
2022-11-26T05:02:14
2016-10-19T18:22:39
Python
UTF-8
C
false
false
1,320
c
_test_multivariate.c
#include <Python.h> /* Backwards compatibility: Python2.2 used LONG_LONG instead of PY_LONG_LONG */ #if defined(HAVE_LONG_LONG) && !defined(PY_LONG_LONG) #define PY_LONG_LONG LONG_LONG #endif #ifdef MS_WIN32 #include <windows.h> #endif #if defined(MS_WIN32) || defined(__CYGWIN__) #define EXPORT(x) __declspec(dllexport) x #else #define EXPORT(x) x #endif #include "math.h" const double PI = 3.141592653589793238462643383279502884; EXPORT(double) _multivariate_typical(int n, double *args) { return cos(args[1] * args[0] - args[2] * sin(args[0])) / PI; } EXPORT(double) _multivariate_indefinite(int n, double *args) { return -exp(-args[0]) * log(args[0]); } EXPORT(double) _multivariate_sin(int n, double *args) { return sin(args[0]); } /* This won't allow you to actually use the methods here. It just lets you load the module so you can get at the __file__ attribute. */ #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_test_multivariate", NULL, -1, NULL, /* Empty methods section */ NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit__test_multivariate(void) { return PyModule_Create(&moduledef); } #else PyMODINIT_FUNC init_test_multivariate(void) { Py_InitModule("_test_multivariate", NULL); } #endif
b80205307ef436ad80a815dd6b0d0a0ce84dda79
3d44c763f0bd72117579cdd87bbf305ffd191e8b
/src/platform/windows/win_io.c
489dc01a88f4fa7b397bb493cd34cb0d96918a47
[ "MIT" ]
permissive
nanomsg/nng
6e597e664a4126c3d8e8b16e9c22a33ac773c9c4
5ac5be5cacacdb8d6cac2fa362fce6d78e4dc389
refs/heads/master
2023-08-31T04:28:18.215853
2023-08-23T19:23:18
2023-08-28T05:58:40
76,157,774
3,407
489
MIT
2023-09-14T09:01:13
2016-12-11T06:14:28
C
UTF-8
C
false
false
3,028
c
win_io.c
// // Copyright 2020 Staysail Systems, Inc. <info@staysail.tech> // Copyright 2018 Capitar IT Group BV <info@capitar.com> // // This software is supplied under the terms of the MIT License, a // copy of which should be located in the distribution where this // file was obtained (LICENSE.txt). A copy of the license may also be // found online at https://opensource.org/licenses/MIT. // #include "core/nng_impl.h" #ifdef NNG_PLATFORM_WINDOWS #include <stdio.h> // Windows IO Completion Port support. We basically create a single // IO completion port, then start threads on it. Handles are added // to the port on an as needed basis. We use a single IO completion // port for pretty much everything. static int win_io_nthr = 0; static HANDLE win_io_h = NULL; static nni_thr *win_io_thrs; static void win_io_handler(void *arg) { NNI_ARG_UNUSED(arg); for (;;) { DWORD cnt; BOOL ok; nni_win_io *item; OVERLAPPED *olpd = NULL; ULONG_PTR key = 0; int rv; ok = GetQueuedCompletionStatus( win_io_h, &cnt, &key, &olpd, INFINITE); if (olpd == NULL) { // Completion port closed... NNI_ASSERT(ok == FALSE); break; } item = CONTAINING_RECORD(olpd, nni_win_io, olpd); rv = ok ? 0 : nni_win_error(GetLastError()); item->cb(item, rv, (size_t) cnt); } } int nni_win_io_register(HANDLE h) { if (CreateIoCompletionPort(h, win_io_h, 0, 0) == NULL) { return (nni_win_error(GetLastError())); } return (0); } int nni_win_io_init(nni_win_io *io, nni_win_io_cb cb, void *ptr) { ZeroMemory(&io->olpd, sizeof(io->olpd)); io->cb = cb; io->ptr = ptr; io->aio = NULL; io->olpd.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (io->olpd.hEvent == NULL) { return (nni_win_error(GetLastError())); } return (0); } void nni_win_io_fini(nni_win_io *io) { if (io->olpd.hEvent != NULL) { CloseHandle((HANDLE) io->olpd.hEvent); } } int nni_win_io_sysinit(void) { HANDLE h; int i; int rv; int nthr = nni_plat_ncpu() * 2; // Limits on the thread count. This is fairly arbitrary. if (nthr < 4) { nthr = 4; } if (nthr > 64) { nthr = 64; } if ((win_io_thrs = NNI_ALLOC_STRUCTS(win_io_thrs, nthr)) == NULL) { return (NNG_ENOMEM); } win_io_nthr = nthr; h = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, nthr); if (h == NULL) { return (nni_win_error(GetLastError())); } win_io_h = h; for (i = 0; i < win_io_nthr; i++) { rv = nni_thr_init(&win_io_thrs[i], win_io_handler, NULL); if (rv != 0) { goto fail; } nni_thr_set_name(&win_io_thrs[i], "nng:iocp"); } for (i = 0; i < win_io_nthr; i++) { nni_thr_run(&win_io_thrs[i]); } return (0); fail: nni_win_io_sysfini(); return (rv); } void nni_win_io_sysfini(void) { int i; HANDLE h; if ((h = win_io_h) != NULL) { CloseHandle(h); win_io_h = NULL; } for (i = 0; i < win_io_nthr; i++) { nni_thr_fini(&win_io_thrs[i]); } NNI_FREE_STRUCTS(win_io_thrs, win_io_nthr); } #endif // NNG_PLATFORM_WINDOWS
61b824d93352d9923c50bc81c6420c4fd3cb9bf0
9ceacf33fd96913cac7ef15492c126d96cae6911
/lib/libevent/min_heap.h
2b8d245ffe6eaaced6124b2e9b941162bcf9779e
[]
no_license
openbsd/src
ab97ef834fd2d5a7f6729814665e9782b586c130
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
refs/heads/master
2023-09-02T18:54:56.624627
2023-09-02T15:16:12
2023-09-02T15:16:12
66,966,208
3,394
1,235
null
2023-08-08T02:42:25
2016-08-30T18:18:25
C
UTF-8
C
false
false
5,311
h
min_heap.h
/* $OpenBSD: min_heap.h,v 1.6 2019/04/29 17:11:52 tobias Exp $ */ /* * Copyright (c) 2006 Maxim Yegorushkin <maxim.yegorushkin@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _MIN_HEAP_H_ #define _MIN_HEAP_H_ #include "event.h" typedef struct min_heap { struct event **p; size_t n, a; } min_heap_t; static inline void min_heap_ctor(min_heap_t * s); static inline void min_heap_dtor(min_heap_t * s); static inline void min_heap_elem_init(struct event * e); static inline int min_heap_elem_greater(struct event * a, struct event * b); static inline int min_heap_empty(min_heap_t * s); static inline size_t min_heap_size(min_heap_t * s); static inline struct event *min_heap_top(min_heap_t * s); static inline int min_heap_reserve(min_heap_t * s, size_t n); static inline int min_heap_push(min_heap_t * s, struct event * e); static inline struct event *min_heap_pop(min_heap_t * s); static inline int min_heap_erase(min_heap_t * s, struct event * e); static inline void min_heap_shift_up_(min_heap_t * s, size_t hole_index, struct event * e); static inline void min_heap_shift_down_(min_heap_t * s, size_t hole_index, struct event * e); int min_heap_elem_greater(struct event * a, struct event * b) { return timercmp(&a->ev_timeout, &b->ev_timeout, >); } void min_heap_ctor(min_heap_t * s) { s->p = 0; s->n = 0; s->a = 0; } void min_heap_dtor(min_heap_t * s) { if (s->p) free(s->p); } void min_heap_elem_init(struct event * e) { e->min_heap_idx = SIZE_MAX; } int min_heap_empty(min_heap_t * s) { return 0 == s->n; } size_t min_heap_size(min_heap_t * s) { return s->n; } struct event * min_heap_top(min_heap_t * s) { return s->n ? *s->p : 0; } int min_heap_push(min_heap_t * s, struct event * e) { if (min_heap_reserve(s, s->n + 1)) return -1; min_heap_shift_up_(s, s->n++, e); return 0; } struct event * min_heap_pop(min_heap_t * s) { if (s->n) { struct event *e = *s->p; min_heap_shift_down_(s, 0, s->p[--s->n]); e->min_heap_idx = SIZE_MAX; return e; } return 0; } int min_heap_erase(min_heap_t * s, struct event * e) { if (e->min_heap_idx != SIZE_MAX) { struct event *last = s->p[--s->n]; size_t parent = (e->min_heap_idx - 1) / 2; /* * we replace e with the last element in the heap. We might * need to shift it upward if it is less than its parent, or * downward if it is greater than one or both its children. * Since the children are known to be less than the parent, * it can't need to shift both up and down. */ if (e->min_heap_idx > 0 && min_heap_elem_greater(s->p[parent], last)) min_heap_shift_up_(s, e->min_heap_idx, last); else min_heap_shift_down_(s, e->min_heap_idx, last); e->min_heap_idx = SIZE_MAX; return 0; } return -1; } int min_heap_reserve(min_heap_t * s, size_t n) { if (s->a < n) { struct event **p; size_t a = s->a ? s->a * 2 : 8; if (a < n) a = n; if (!(p = recallocarray(s->p, s->a, a, sizeof *p))) return -1; s->p = p; s->a = a; } return 0; } void min_heap_shift_up_(min_heap_t * s, size_t hole_index, struct event * e) { size_t parent = (hole_index - 1) / 2; while (hole_index && min_heap_elem_greater(s->p[parent], e)) { s->p[hole_index] = s->p[parent]; s->p[hole_index]->min_heap_idx = hole_index; hole_index = parent; parent = (hole_index - 1) / 2; } e->min_heap_idx = hole_index; s->p[hole_index] = e; } void min_heap_shift_down_(min_heap_t * s, size_t hole_index, struct event * e) { size_t min_child = 2 * (hole_index + 1); while (min_child <= s->n) { if (min_child == s->n || min_heap_elem_greater(s->p[min_child], s->p[min_child - 1])) min_child -= 1; if (!(min_heap_elem_greater(e, s->p[min_child]))) break; s->p[hole_index] = s->p[min_child]; s->p[hole_index]->min_heap_idx = hole_index; hole_index = min_child; min_child = 2 * (hole_index + 1); } min_heap_shift_up_(s, hole_index, e); } #endif /* _MIN_HEAP_H_ */
250f492761e018f23ed600a107218057a5ffa389
1efb2283837c9b70bc6449cec877799e4efa3268
/src/pm/hydra/lib/tools/bootstrap/external/slurm_launch.c
15b8f55fffb2671b298f03380ffed85a9f2403dd
[ "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
5,471
c
slurm_launch.c
/* * Copyright (C) by Argonne National Laboratory * See COPYRIGHT in top-level directory */ #include "hydra.h" #include "bsci.h" #include "bscu.h" #include "topo.h" #include "slurm.h" static int fd_stdout, fd_stderr; static HYD_status proxy_list_to_node_str(struct HYD_proxy *proxy_list, int num_hosts, char **node_list_str) { int i; char *tmp[HYD_NUM_TMP_STRINGS], *foo = NULL; struct HYD_proxy *proxy; HYD_status status = HYD_SUCCESS; HYDU_FUNC_ENTER(); i = 0; for (int j = 0; j < num_hosts; j++) { proxy = proxy_list + j; tmp[i++] = MPL_strdup(proxy->node->hostname); if (proxy->node->next) tmp[i++] = MPL_strdup(","); /* If we used up more than half of the array elements, merge * what we have so far */ if (i > (HYD_NUM_TMP_STRINGS / 2)) { tmp[i++] = NULL; status = HYDU_str_alloc_and_join(tmp, &foo); HYDU_ERR_POP(status, "error joining strings\n"); i = 0; tmp[i++] = MPL_strdup(foo); MPL_free(foo); } } tmp[i++] = NULL; status = HYDU_str_alloc_and_join(tmp, &foo); HYDU_ERR_POP(status, "error joining strings\n"); *node_list_str = foo; foo = NULL; fn_exit: HYDU_free_strlist(tmp); MPL_free(foo); HYDU_FUNC_EXIT(); return status; fn_fail: goto fn_exit; } HYD_status HYDT_bscd_slurm_launch_procs(char **args, struct HYD_proxy *proxy_list, int num_hosts, int use_rmk, int *control_fd) { int idx, i; int *fd_list; char *targs[HYD_NUM_TMP_STRINGS], *node_list_str = NULL; char *path = NULL, *extra_arg_list = NULL, *extra_arg; HYD_status status = HYD_SUCCESS; HYDU_FUNC_ENTER(); /* We use the following priority order for the executable path: * (1) user-specified; (2) search in path; (3) Hard-coded * location */ if (HYDT_bsci_info.launcher_exec) path = MPL_strdup(HYDT_bsci_info.launcher_exec); if (!path) path = HYDU_find_full_path("srun"); if (!path) path = MPL_strdup("/usr/bin/srun"); if (!path) HYDU_ERR_POP(status, "error allocating memory for strdup\n"); idx = 0; targs[idx++] = MPL_strdup(path); if (use_rmk == HYD_FALSE || strcmp(HYDT_bsci_info.rmk, "slurm")) { targs[idx++] = MPL_strdup("--nodelist"); status = proxy_list_to_node_str(proxy_list, num_hosts, &node_list_str); HYDU_ERR_POP(status, "unable to build a node list string\n"); targs[idx++] = MPL_strdup(node_list_str); } targs[idx++] = MPL_strdup("-N"); targs[idx++] = HYDU_int_to_str(num_hosts); targs[idx++] = MPL_strdup("-n"); targs[idx++] = HYDU_int_to_str(num_hosts); /* Force srun to ignore stdin to avoid issues with * unexpected files open on fd 0 */ targs[idx++] = MPL_strdup("--input"); targs[idx++] = MPL_strdup("none"); if (MPL_env2str("HYDRA_LAUNCHER_EXTRA_ARGS", (const char **) &extra_arg_list)) { extra_arg = strtok(extra_arg_list, " "); while (extra_arg) { targs[idx++] = MPL_strdup(extra_arg); extra_arg = strtok(NULL, " "); } } /* Fill in the remaining arguments */ /* We do not need to create a quoted version of the string for * SLURM. It seems to be internally quoting it anyway. */ for (i = 0; args[i]; i++) targs[idx++] = MPL_strdup(args[i]); /* Increase pid list to accommodate the new pid */ HYDT_bscu_pid_list_grow(1); /* Increase fd list to accommodate these new fds */ HYDU_MALLOC_OR_JUMP(fd_list, int *, (HYD_bscu_fd_count + 3) * sizeof(int), status); for (i = 0; i < HYD_bscu_fd_count; i++) fd_list[i] = HYD_bscu_fd_list[i]; MPL_free(HYD_bscu_fd_list); HYD_bscu_fd_list = fd_list; /* append proxy ID as -1 */ targs[idx++] = HYDU_int_to_str(-1); targs[idx++] = NULL; if (HYDT_bsci_info.debug) { HYDU_dump(stdout, "Launch arguments: "); HYDU_print_strlist(targs); } /* let srun know it is being called by a launcher. It is proposed to work in later * versions of Slurm, but harmless otherwise. * We may add --external-launcher option if we know the Slurm version supports it. */ struct HYD_env *env; status = HYDU_env_create(&env, "SLURM_EXTERNAL_LAUNCHER", "1"); HYDU_ERR_POP(status, "unable to create SLURM_EXTERNAL_LAUNCHER environment\n"); int pid; status = HYDU_create_process(targs, env, NULL, &fd_stdout, &fd_stderr, &pid, -1); HYDU_ERR_POP(status, "create process returned error\n"); HYDT_bscu_pid_list_push(NULL, pid); HYDU_env_free_list(env); HYD_bscu_fd_list[HYD_bscu_fd_count++] = fd_stdout; HYD_bscu_fd_list[HYD_bscu_fd_count++] = fd_stderr; status = HYDT_dmx_register_fd(1, &fd_stdout, HYD_POLLIN, (void *) (size_t) STDOUT_FILENO, HYDT_bscu_stdio_cb); HYDU_ERR_POP(status, "demux returned error registering fd\n"); status = HYDT_dmx_register_fd(1, &fd_stderr, HYD_POLLIN, (void *) (size_t) STDERR_FILENO, HYDT_bscu_stdio_cb); HYDU_ERR_POP(status, "demux returned error registering fd\n"); fn_exit: MPL_free(node_list_str); HYDU_free_strlist(targs); MPL_free(path); HYDU_FUNC_EXIT(); return status; fn_fail: goto fn_exit; }
ad470c10ee2772043fe2412b316d0a607d1eb9ee
7d7900e1c25b729fc8c208673a449c0520ba466e
/lib/CL/clGetEventProfilingInfo.c
874f05a902c8cd7da4b29af5f0d836c6ec73e1a0
[ "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
3,033
c
clGetEventProfilingInfo.c
/* OpenCL runtime library: clGetEventProfilingInfo() Copyright (c) 2011 Erik Schnetter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "pocl_cl.h" #include <string.h> CL_API_ENTRY cl_int CL_API_CALL POname(clGetEventProfilingInfo)(cl_event event, cl_profiling_info param_name, size_t param_value_size, void *param_value, size_t *param_value_size_ret) CL_API_SUFFIX__VERSION_1_0 { size_t const value_size = sizeof(cl_ulong); POCL_RETURN_ERROR_COND ((!IS_CL_OBJECT_VALID (event)), CL_INVALID_COMMAND_QUEUE); POCL_RETURN_ERROR_ON((event->queue == NULL), CL_PROFILING_INFO_NOT_AVAILABLE, "Cannot return profiling info for user events\n"); POCL_RETURN_ERROR_ON(((event->queue->properties & CL_QUEUE_PROFILING_ENABLE) == 0), CL_PROFILING_INFO_NOT_AVAILABLE, "Cannot return profiling info when profiling " "is disabled on the queue\n"); POCL_RETURN_ERROR_ON((event->status != CL_COMPLETE), CL_PROFILING_INFO_NOT_AVAILABLE, "Cannot return profiling info on events not CL_COMPLETE yet\n"); if (param_value) { if (param_value_size < value_size) return CL_INVALID_VALUE; switch (param_name) { case CL_PROFILING_COMMAND_QUEUED: *(cl_ulong*)param_value = event->time_queue; break; case CL_PROFILING_COMMAND_SUBMIT: *(cl_ulong*)param_value = event->time_submit; break; case CL_PROFILING_COMMAND_START: *(cl_ulong*)param_value = event->time_start; break; case CL_PROFILING_COMMAND_END: *(cl_ulong*)param_value = event->time_end; break; case CL_PROFILING_COMMAND_COMPLETE: /* Child commands not supported */ *(cl_ulong *)param_value = event->time_end; break; default: return CL_INVALID_VALUE; } } if (param_value_size_ret) *param_value_size_ret = value_size; return CL_SUCCESS; } POsym(clGetEventProfilingInfo)
cf73a6134710c1678309cbe3248e0a6b52fddf6f
e0951f0c08fb24ce57d5b6fb3f364e314e94ac67
/demo/2018.03.12-understanding-unix-linux-programming/chap01/test1.c
306be10af11de1109fd5b0182e67a9920d370166
[]
no_license
chyingp/blog
1a69ddcd8acbcf20c80995d274e81450c278f32f
4fcfd719ed01f446d8f1eea721551e71db4909cf
refs/heads/master
2023-08-27T00:23:18.260234
2023-07-27T15:50:03
2023-07-27T15:50:03
9,654,619
491
279
null
2023-01-12T23:53:47
2013-04-24T18:17:08
null
UTF-8
C
false
false
200
c
test1.c
#include<stdio.h> int main() { char ch = getchar(); char ch2 = getchar(); printf("You put char is %c\n",ch); printf("You put char is %c\n",ch2); // system("pause"); return 0; }
960aeecd519e4842c20957d37cc70224e9fe8c18
badb70a0b235c98ac034cfe5b4bfafda36647831
/Include/Intel/Guid/DataHubRecords.h
6f996dca3816e74e6ae22414f613afaff3dbc953
[ "BSD-3-Clause" ]
permissive
acidanthera/OpenCorePkg
f34a7d67b22c74fb5ab559e48519e5f5855b6751
1d5b1736fe5a5ef7662b5c076c6d11aac96fd5d6
refs/heads/master
2023-08-30T21:03:02.993659
2023-08-28T23:30:43
2023-08-28T23:30:43
179,354,282
13,212
2,999
BSD-3-Clause
2023-09-10T18:29:53
2019-04-03T19:14:29
C
UTF-8
C
false
false
112,463
h
DataHubRecords.h
/** @file DataHubRecord.h includes all data hub subclass GUID definitions. This file includes all data hub sub class defitions from Cache subclass specification 0.9, DataHub SubClass specification 0.9, Memory SubClass Spec 0.9, Processor Subclass specification 0.9, and Misc SubClass specification 0.9. Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License that accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php. THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #ifndef _DATAHUB_RECORDS_GUID_H_ #define _DATAHUB_RECORDS_GUID_H_ // // The include is required to retrieve type EFI_EXP_BASE10_DATA // #include <Guid/StatusCodeDataTypeId.h> #define EFI_PROCESSOR_SUBCLASS_GUID \ { 0x26fdeb7e, 0xb8af, 0x4ccf, {0xaa, 0x97, 0x02, 0x63, 0x3c, 0xe4, 0x8c, 0xa7 } } extern EFI_GUID gEfiProcessorSubClassGuid; #define EFI_CACHE_SUBCLASS_GUID \ { 0x7f0013a7, 0xdc79, 0x4b22, {0x80, 0x99, 0x11, 0xf7, 0x5f, 0xdc, 0x82, 0x9d } } extern EFI_GUID gEfiCacheSubClassGuid; /// /// The memory subclass belongs to the data class and is identified as the memory /// subclass by the GUID. /// #define EFI_MEMORY_SUBCLASS_GUID \ {0x4E8F4EBB, 0x64B9, 0x4e05, {0x9B, 0x18, 0x4C, 0xFE, 0x49, 0x23, 0x50, 0x97} } extern EFI_GUID gEfiMemorySubClassGuid; #define EFI_MISC_SUBCLASS_GUID \ { 0x772484B2, 0x7482, 0x4b91, {0x9F, 0x9A, 0xAD, 0x43, 0xF8, 0x1C, 0x58, 0x81 } } extern EFI_GUID gEfiMiscSubClassGuid; /// /// Inconsistent with specification here: /// In ProcSubclass specification 0.9, the value is 0x0100. /// Keep it unchanged from the perspective of binary consistency. /// #define EFI_PROCESSOR_SUBCLASS_VERSION 0x00010000 #pragma pack(1) typedef struct _USB_PORT_DEVICE_PATH { ACPI_HID_DEVICE_PATH PciRootBridgeDevicePath; PCI_DEVICE_PATH PciBusDevicePath; EFI_DEVICE_PATH_PROTOCOL EndDevicePath; } USB_PORT_DEVICE_PATH; // // IDE // typedef struct _IDE_DEVICE_PATH { ACPI_HID_DEVICE_PATH PciRootBridgeDevicePath; PCI_DEVICE_PATH PciBusDevicePath; EFI_DEVICE_PATH_PROTOCOL EndDevicePath; } IDE_DEVICE_PATH; // // RMC Connector // typedef struct _RMC_CONN_DEVICE_PATH { ACPI_HID_DEVICE_PATH PciRootBridgeDevicePath; PCI_DEVICE_PATH PciBridgeDevicePath; PCI_DEVICE_PATH PciBusDevicePath; EFI_DEVICE_PATH_PROTOCOL EndDevicePath; } RMC_CONN_DEVICE_PATH; // // RIDE // typedef struct _RIDE_DEVICE_PATH { ACPI_HID_DEVICE_PATH PciRootBridgeDevicePath; PCI_DEVICE_PATH PciBridgeDevicePath; PCI_DEVICE_PATH PciBusDevicePath; EFI_DEVICE_PATH_PROTOCOL EndDevicePath; } RIDE_DEVICE_PATH; // // Gigabit NIC // typedef struct _GB_NIC_DEVICE_PATH { ACPI_HID_DEVICE_PATH PciRootBridgeDevicePath; PCI_DEVICE_PATH PciBridgeDevicePath; PCI_DEVICE_PATH PciXBridgeDevicePath; PCI_DEVICE_PATH PciXBusDevicePath; EFI_DEVICE_PATH_PROTOCOL EndDevicePath; } GB_NIC_DEVICE_PATH; // // P/S2 Connector // typedef struct _PS2_CONN_DEVICE_PATH { ACPI_HID_DEVICE_PATH PciRootBridgeDevicePath; PCI_DEVICE_PATH LpcBridgeDevicePath; ACPI_HID_DEVICE_PATH LpcBusDevicePath; EFI_DEVICE_PATH_PROTOCOL EndDevicePath; } PS2_CONN_DEVICE_PATH; // // Serial Port Connector // typedef struct _SERIAL_CONN_DEVICE_PATH { ACPI_HID_DEVICE_PATH PciRootBridgeDevicePath; PCI_DEVICE_PATH LpcBridgeDevicePath; ACPI_HID_DEVICE_PATH LpcBusDevicePath; EFI_DEVICE_PATH_PROTOCOL EndDevicePath; } SERIAL_CONN_DEVICE_PATH; // // Parallel Port Connector // typedef struct _PARALLEL_CONN_DEVICE_PATH { ACPI_HID_DEVICE_PATH PciRootBridgeDevicePath; PCI_DEVICE_PATH LpcBridgeDevicePath; ACPI_HID_DEVICE_PATH LpcBusDevicePath; EFI_DEVICE_PATH_PROTOCOL EndDevicePath; } PARALLEL_CONN_DEVICE_PATH; // // Floopy Connector // typedef struct _FLOOPY_CONN_DEVICE_PATH { ACPI_HID_DEVICE_PATH PciRootBridgeDevicePath; PCI_DEVICE_PATH LpcBridgeDevicePath; ACPI_HID_DEVICE_PATH LpcBusDevicePath; EFI_DEVICE_PATH_PROTOCOL EndDevicePath; } FLOOPY_CONN_DEVICE_PATH; /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, this data structure and corrsponding fields are NOT defined. /// It's implementation-specific to simplify the code logic. /// typedef union _EFI_MISC_PORT_DEVICE_PATH { USB_PORT_DEVICE_PATH UsbDevicePath; IDE_DEVICE_PATH IdeDevicePath; RMC_CONN_DEVICE_PATH RmcConnDevicePath; RIDE_DEVICE_PATH RideDevicePath; GB_NIC_DEVICE_PATH GbNicDevicePath; PS2_CONN_DEVICE_PATH Ps2ConnDevicePath; SERIAL_CONN_DEVICE_PATH SerialConnDevicePath; PARALLEL_CONN_DEVICE_PATH ParallelConnDevicePath; FLOOPY_CONN_DEVICE_PATH FloppyConnDevicePath; } EFI_MISC_PORT_DEVICE_PATH; #pragma pack() /// /// String Token Definition /// /// Inconsistent with specification here: /// The macro isn't defined by any specification. /// Keep it unchanged for backward compatibility. /// #define EFI_STRING_TOKEN UINT16 /// /// Each data record that is a member of some subclass starts with a standard /// header of type EFI_SUBCLASS_TYPE1_HEADER. /// This header is only a guideline and applicable only to a data /// subclass that is producing SMBIOS data records. A subclass can start with a /// different header if needed. /// typedef struct { /// /// The version of the specification to which a specific subclass data record adheres. /// UINT32 Version; /// /// The size in bytes of this data class header. /// UINT32 HeaderSize; /// /// The instance number of the subclass with the same ProducerName. This number is /// applicable in cases where multiple subclass instances that were produced by the same /// driver exist in the system. This entry is 1 based; 0 means Reserved and -1 means Not /// Applicable. All data consumer drivers should be able to handle all the possible values /// of Instance, including Not Applicable and Reserved. /// UINT16 Instance; /// /// The instance number of the RecordType for the same Instance. This number is /// applicable in cases where multiple instances of the RecordType exist for a specific /// Instance. This entry is 1 based; 0 means Reserved and -1 means Not Applicable. /// All data consumer drivers should be able to handle all the possible values of /// SubInstance, including Not Applicable and Reserved. /// UINT16 SubInstance; /// /// The record number for the data record being specified. The numbering scheme and /// definition is defined in the specific subclass specification. /// UINT32 RecordType; } EFI_SUBCLASS_TYPE1_HEADER; /// /// This structure is used to link data records in the same subclasses. A data record is /// defined as a link to another data record in the same subclass using this structure. /// typedef struct { /// /// An EFI_GUID that identifies the component that produced this data record. Type /// EFI_GUID is defined in InstallProtocolInterface() in the EFI 1.10 Specification. /// EFI_GUID ProducerName; /// /// The instance number of the subclass with the same ProducerName. This number is /// applicable in cases where multiple subclass instances that were produced by the same /// driver exist in the system. This entry is 1 based; 0 means Reserved and -1 means Not /// Applicable. All data consumer drivers should be able to handle all the possible values /// of Instance, including Not Applicable and Reserved. /// UINT16 Instance; /// The instance number of the RecordType for the same Instance. This number is /// applicable in cases where multiple instances of the RecordType exist for a specific /// Instance. This entry is 1 based; 0 means Reserved and -1 means Not Applicable. /// All data consumer drivers should be able to handle all the possible values of /// SubInstance, including Not Applicable and Reserved. UINT16 SubInstance; } EFI_INTER_LINK_DATA; // // EXP data // /// /// This macro provides a calculation for base-10 representations. Value and Exponent are each /// INT16. It is signed to cover negative values and is 16 bits wide (15 bits for data and 1 bit /// for the sign). /// typedef struct { /// /// The INT16 number by which to multiply the base-10 representation. /// UINT16 Value; /// /// The INT16 number by which to raise the base-10 calculation. /// UINT16 Exponent; } EFI_EXP_BASE2_DATA; typedef EFI_EXP_BASE10_DATA EFI_PROCESSOR_MAX_CORE_FREQUENCY_DATA; typedef EFI_EXP_BASE10_DATA EFI_PROCESSOR_MAX_FSB_FREQUENCY_DATA; typedef EFI_EXP_BASE10_DATA EFI_PROCESSOR_CORE_FREQUENCY_DATA; /// /// This data record refers to the list of frequencies that the processor core supports. The list of /// supported frequencies is determined by the firmware based on hardware capabilities--for example, /// it could be a common subset of all processors and the chipset. The unit of measurement of this data /// record is in Hertz. For asynchronous processors, the content of this data record is zero. /// The list is terminated by -1 in the Value field of the last element. A Value field of zero means /// that the processor/driver supports automatic frequency selection. /// /// Inconsistent with specification here: /// According to MiscSubclass 0.9 specification, it should be a pointer since it refers to a list of frequencies. /// typedef EFI_EXP_BASE10_DATA *EFI_PROCESSOR_CORE_FREQUENCY_LIST_DATA; /// /// This data record refers to the list of supported frequencies of the processor external bus. The list of /// supported frequencies is determined by the firmware based on hardware capabilities--for example, /// it could be a common subset of all processors and the chipset. The unit of measurement of this data /// record is in Hertz. For asynchronous processors, the content of this data record is NULL. /// The list is terminated by -1 in the Value field of the last element. A Value field of zero means /// that the processor/driver supports automatic frequency selection. /// typedef EFI_EXP_BASE10_DATA *EFI_PROCESSOR_FSB_FREQUENCY_LIST_DATA; typedef EFI_EXP_BASE10_DATA EFI_PROCESSOR_FSB_FREQUENCY_DATA; typedef STRING_REF EFI_PROCESSOR_VERSION_DATA; typedef STRING_REF EFI_PROCESSOR_MANUFACTURER_DATA; typedef STRING_REF EFI_PROCESSOR_SERIAL_NUMBER_DATA; typedef STRING_REF EFI_PROCESSOR_ASSET_TAG_DATA; typedef STRING_REF EFI_PROCESSOR_PART_NUMBER_DATA; typedef struct { UINT32 ProcessorSteppingId : 4; UINT32 ProcessorModel : 4; UINT32 ProcessorFamily : 4; UINT32 ProcessorType : 2; UINT32 ProcessorReserved1 : 2; UINT32 ProcessorXModel : 4; UINT32 ProcessorXFamily : 8; UINT32 ProcessorReserved2 : 4; } EFI_PROCESSOR_SIGNATURE; /// /// Inconsistent with specification here: /// The name of third field in ProcSubClass specification 0.9 is LogicalProcessorCount. /// Keep it unchanged for backward compatibility. /// typedef struct { UINT32 ProcessorBrandIndex : 8; UINT32 ProcessorClflush : 8; UINT32 ProcessorReserved : 8; UINT32 ProcessorDfltApicId : 8; } EFI_PROCESSOR_MISC_INFO; typedef struct { UINT32 ProcessorFpu : 1; UINT32 ProcessorVme : 1; UINT32 ProcessorDe : 1; UINT32 ProcessorPse : 1; UINT32 ProcessorTsc : 1; UINT32 ProcessorMsr : 1; UINT32 ProcessorPae : 1; UINT32 ProcessorMce : 1; UINT32 ProcessorCx8 : 1; UINT32 ProcessorApic : 1; UINT32 ProcessorReserved1 : 1; UINT32 ProcessorSep : 1; UINT32 ProcessorMtrr : 1; UINT32 ProcessorPge : 1; UINT32 ProcessorMca : 1; UINT32 ProcessorCmov : 1; UINT32 ProcessorPat : 1; UINT32 ProcessorPse36 : 1; UINT32 ProcessorPsn : 1; UINT32 ProcessorClfsh : 1; UINT32 ProcessorReserved2 : 1; UINT32 ProcessorDs : 1; UINT32 ProcessorAcpi : 1; UINT32 ProcessorMmx : 1; UINT32 ProcessorFxsr : 1; UINT32 ProcessorSse : 1; UINT32 ProcessorSse2 : 1; UINT32 ProcessorSs : 1; UINT32 ProcessorReserved3 : 1; UINT32 ProcessorTm : 1; UINT32 ProcessorReserved4 : 2; } EFI_PROCESSOR_FEATURE_FLAGS; /// /// This data record refers to the unique ID that identifies a set of processors. This data record is 16 /// bytes in length. The data in this structure is processor specific and reserved values can be defined /// for future use. The consumer of this data should not make any assumption and should use this data /// with respect to the processor family defined in the Family record number. /// typedef struct { /// /// Identifies the processor. /// EFI_PROCESSOR_SIGNATURE Signature; /// /// Provides additional processor information. /// EFI_PROCESSOR_MISC_INFO MiscInfo; /// /// Reserved for future use. /// UINT32 Reserved; /// /// Provides additional processor information. /// EFI_PROCESSOR_FEATURE_FLAGS FeatureFlags; } EFI_PROCESSOR_ID_DATA; /// /// This data record refers to the general classification of the processor. This data record is 4 bytes in /// length. /// typedef enum { EfiProcessorOther = 1, EfiProcessorUnknown = 2, EfiCentralProcessor = 3, EfiMathProcessor = 4, EfiDspProcessor = 5, EfiVideoProcessor = 6 } EFI_PROCESSOR_TYPE_DATA; /// /// This data record refers to the family of the processor as defined by the DMTF. /// This data record is 4 bytes in length. /// typedef enum { EfiProcessorFamilyOther = 0x01, EfiProcessorFamilyUnknown = 0x02, EfiProcessorFamily8086 = 0x03, EfiProcessorFamily80286 = 0x04, EfiProcessorFamilyIntel386 = 0x05, EfiProcessorFamilyIntel486 = 0x06, EfiProcessorFamily8087 = 0x07, EfiProcessorFamily80287 = 0x08, EfiProcessorFamily80387 = 0x09, EfiProcessorFamily80487 = 0x0A, EfiProcessorFamilyPentium = 0x0B, EfiProcessorFamilyPentiumPro = 0x0C, EfiProcessorFamilyPentiumII = 0x0D, EfiProcessorFamilyPentiumMMX = 0x0E, EfiProcessorFamilyCeleron = 0x0F, EfiProcessorFamilyPentiumIIXeon = 0x10, EfiProcessorFamilyPentiumIII = 0x11, EfiProcessorFamilyM1 = 0x12, EfiProcessorFamilyM2 = 0x13, EfiProcessorFamilyM1Reserved2 = 0x14, EfiProcessorFamilyM1Reserved3 = 0x15, EfiProcessorFamilyM1Reserved4 = 0x16, EfiProcessorFamilyM1Reserved5 = 0x17, EfiProcessorFamilyAmdDuron = 0x18, EfiProcessorFamilyK5 = 0x19, EfiProcessorFamilyK6 = 0x1A, EfiProcessorFamilyK6_2 = 0x1B, EfiProcessorFamilyK6_3 = 0x1C, EfiProcessorFamilyAmdAthlon = 0x1D, EfiProcessorFamilyAmd29000 = 0x1E, EfiProcessorFamilyK6_2Plus = 0x1F, EfiProcessorFamilyPowerPC = 0x20, EfiProcessorFamilyPowerPC601 = 0x21, EfiProcessorFamilyPowerPC603 = 0x22, EfiProcessorFamilyPowerPC603Plus = 0x23, EfiProcessorFamilyPowerPC604 = 0x24, EfiProcessorFamilyPowerPC620 = 0x25, EfiProcessorFamilyPowerPCx704 = 0x26, EfiProcessorFamilyPowerPC750 = 0x27, EfiProcessorFamilyAlpha3 = 0x30, EfiProcessorFamilyAlpha21064 = 0x31, EfiProcessorFamilyAlpha21066 = 0x32, EfiProcessorFamilyAlpha21164 = 0x33, EfiProcessorFamilyAlpha21164PC = 0x34, EfiProcessorFamilyAlpha21164a = 0x35, EfiProcessorFamilyAlpha21264 = 0x36, EfiProcessorFamilyAlpha21364 = 0x37, EfiProcessorFamilyMips = 0x40, EfiProcessorFamilyMIPSR4000 = 0x41, EfiProcessorFamilyMIPSR4200 = 0x42, EfiProcessorFamilyMIPSR4400 = 0x43, EfiProcessorFamilyMIPSR4600 = 0x44, EfiProcessorFamilyMIPSR10000 = 0x45, EfiProcessorFamilySparc = 0x50, EfiProcessorFamilySuperSparc = 0x51, EfiProcessorFamilymicroSparcII = 0x52, EfiProcessorFamilymicroSparcIIep = 0x53, EfiProcessorFamilyUltraSparc = 0x54, EfiProcessorFamilyUltraSparcII = 0x55, EfiProcessorFamilyUltraSparcIIi = 0x56, EfiProcessorFamilyUltraSparcIII = 0x57, /// /// Inconsistent with specification here: /// This field in ProcSubClass specification 0.9 is defined as EfiProcessorFamilyUltraSparcIIi. /// Change it to EfiProcessorFamilyUltraSparcIIIi to avoid build break. /// EfiProcessorFamilyUltraSparcIIIi = 0x58, EfiProcessorFamily68040 = 0x60, EfiProcessorFamily68xxx = 0x61, EfiProcessorFamily68000 = 0x62, EfiProcessorFamily68010 = 0x63, EfiProcessorFamily68020 = 0x64, EfiProcessorFamily68030 = 0x65, EfiProcessorFamilyHobbit = 0x70, EfiProcessorFamilyCrusoeTM5000 = 0x78, EfiProcessorFamilyCrusoeTM3000 = 0x79, EfiProcessorFamilyEfficeonTM8000 = 0x7A, EfiProcessorFamilyWeitek = 0x80, EfiProcessorFamilyItanium = 0x82, EfiProcessorFamilyAmdAthlon64 = 0x83, EfiProcessorFamilyAmdOpteron = 0x84, EfiProcessorFamilyAmdSempron = 0x85, EfiProcessorFamilyAmdTurion64Mobile = 0x86, EfiProcessorFamilyDualCoreAmdOpteron = 0x87, EfiProcessorFamilyAmdAthlon64X2DualCore = 0x88, EfiProcessorFamilyAmdTurion64X2Mobile = 0x89, EfiProcessorFamilyPARISC = 0x90, EfiProcessorFamilyPaRisc8500 = 0x91, EfiProcessorFamilyPaRisc8000 = 0x92, EfiProcessorFamilyPaRisc7300LC = 0x93, EfiProcessorFamilyPaRisc7200 = 0x94, EfiProcessorFamilyPaRisc7100LC = 0x95, EfiProcessorFamilyPaRisc7100 = 0x96, EfiProcessorFamilyV30 = 0xA0, EfiProcessorFamilyPentiumIIIXeon = 0xB0, EfiProcessorFamilyPentiumIIISpeedStep = 0xB1, EfiProcessorFamilyPentium4 = 0xB2, EfiProcessorFamilyIntelXeon = 0xB3, EfiProcessorFamilyAS400 = 0xB4, EfiProcessorFamilyIntelXeonMP = 0xB5, EfiProcessorFamilyAMDAthlonXP = 0xB6, EfiProcessorFamilyAMDAthlonMP = 0xB7, EfiProcessorFamilyIntelItanium2 = 0xB8, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyIntelPentiumM = 0xB9, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyIntelCeleronD = 0xBA, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyIntelPentiumD = 0xBB, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyIntelPentiumEx = 0xBC, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyIntelCoreSolo = 0xBD, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyReserved = 0xBE, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyIntelCore2 = 0xBF, EfiProcessorFamilyIBM390 = 0xC8, EfiProcessorFamilyG4 = 0xC9, EfiProcessorFamilyG5 = 0xCA, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyG6 = 0xCB, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyzArchitectur = 0xCC, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyViaC7M = 0xD2, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyViaC7D = 0xD3, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyViaC7 = 0xD4, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyViaEden = 0xD5, EfiProcessorFamilyi860 = 0xFA, EfiProcessorFamilyi960 = 0xFB, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyIndicatorFamily2 = 0xFE, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorFamilyReserved1 = 0xFF } EFI_PROCESSOR_FAMILY_DATA; typedef enum { EfiProcessorFamilySh3 = 0x104, EfiProcessorFamilySh4 = 0x105, EfiProcessorFamilyArm = 0x118, EfiProcessorFamilyStrongArm = 0x119, EfiProcessorFamily6x86 = 0x12C, EfiProcessorFamilyMediaGx = 0x12D, EfiProcessorFamilyMii = 0x12E, EfiProcessorFamilyWinChip = 0x140, EfiProcessorFamilyDsp = 0x15E, EfiProcessorFamilyVideo = 0x1F4 } EFI_PROCESSOR_FAMILY2_DATA; /// /// This data record refers to the core voltage of the processor being defined. The unit of measurement /// of this data record is in volts. /// typedef EFI_EXP_BASE10_DATA EFI_PROCESSOR_VOLTAGE_DATA; /// /// This data record refers to the base address of the APIC of the processor being defined. This data /// record is a physical address location. /// typedef EFI_PHYSICAL_ADDRESS EFI_PROCESSOR_APIC_BASE_ADDRESS_DATA; /// /// This data record refers to the ID of the APIC of the processor being defined. This data record is a /// 4-byte entry. /// typedef UINT32 EFI_PROCESSOR_APIC_ID_DATA; /// /// This data record refers to the version number of the APIC of the processor being defined. This data /// record is a 4-byte entry. /// typedef UINT32 EFI_PROCESSOR_APIC_VERSION_NUMBER_DATA; typedef enum { EfiProcessorIa32Microcode = 1, EfiProcessorIpfPalAMicrocode = 2, EfiProcessorIpfPalBMicrocode = 3 } EFI_PROCESSOR_MICROCODE_TYPE; /// /// This data record refers to the revision of the processor microcode that is loaded in the processor. /// This data record is a 4-byte entry. /// typedef struct { /// /// Identifies what type of microcode the data is. /// EFI_PROCESSOR_MICROCODE_TYPE ProcessorMicrocodeType; /// /// Indicates the revision number of this microcode. /// UINT32 ProcessorMicrocodeRevisionNumber; } EFI_PROCESSOR_MICROCODE_REVISION_DATA; /// /// This data record refers to the status of the processor. /// typedef struct { UINT32 CpuStatus : 3; ///< Indicates the status of the processor. UINT32 Reserved1 : 3; ///< Reserved for future use. Should be set to zero. UINT32 SocketPopulated : 1; ///< Indicates if the processor is socketed or not. UINT32 Reserved2 : 1; ///< Reserved for future use. Should be set to zero. UINT32 ApicEnable : 1; ///< Indicates if the APIC is enabled or not. UINT32 BootApplicationProcessor : 1; ///< Indicates if this processor is the boot processor. UINT32 Reserved3 : 22; ///< Reserved for future use. Should be set to zero. } EFI_PROCESSOR_STATUS_DATA; typedef enum { EfiCpuStatusUnknown = 0, EfiCpuStatusEnabled = 1, EfiCpuStatusDisabledByUser = 2, EfiCpuStatusDisabledbyBios = 3, EfiCpuStatusIdle = 4, EfiCpuStatusOther = 7 } EFI_CPU_STATUS; typedef enum { EfiProcessorSocketOther = 1, EfiProcessorSocketUnknown = 2, EfiProcessorSocketDaughterBoard = 3, EfiProcessorSocketZIF = 4, EfiProcessorSocketReplacePiggyBack = 5, EfiProcessorSocketNone = 6, EfiProcessorSocketLIF = 7, EfiProcessorSocketSlot1 = 8, EfiProcessorSocketSlot2 = 9, EfiProcessorSocket370Pin = 0xA, EfiProcessorSocketSlotA = 0xB, EfiProcessorSocketSlotM = 0xC, EfiProcessorSocket423 = 0xD, EfiProcessorSocketA462 = 0xE, EfiProcessorSocket478 = 0xF, EfiProcessorSocket754 = 0x10, EfiProcessorSocket940 = 0x11, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorSocket939 = 0x12, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorSocketmPGA604 = 0x13, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorSocketLGA771 = 0x14, /// /// Inconsistent with specification here: /// This field is NOT defined in ProcSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiProcessorSocketLGA775 = 0x15 } EFI_PROCESSOR_SOCKET_TYPE_DATA; typedef STRING_REF EFI_PROCESSOR_SOCKET_NAME_DATA; /// /// Inconsistent with specification here: /// In ProcSubclass specification 0.9, the naming is EFI_PROCESSOR_CACHE_ASSOCIATION_DATA. /// Keep it unchanged for backward compatibilty. /// typedef EFI_INTER_LINK_DATA EFI_CACHE_ASSOCIATION_DATA; /// /// This data record refers to the health status of the processor. /// /// Inconsistent with specification here: /// In ProcSubclass specification 0.9, the naming is EFI_PROCESSOR_HEALTH_STATUS_DATA. /// Keep it unchanged for backward compatibilty. /// typedef enum { EfiProcessorHealthy = 1, EfiProcessorPerfRestricted = 2, EfiProcessorFuncRestricted = 3 } EFI_PROCESSOR_HEALTH_STATUS; /// /// This data record refers to the package number of this processor. Multiple logical processors can /// exist in a system and each logical processor can be correlated to the physical processor using this /// record type. /// typedef UINTN EFI_PROCESSOR_PACKAGE_NUMBER_DATA; typedef UINT8 EFI_PROCESSOR_CORE_COUNT_DATA; typedef UINT8 EFI_PROCESSOR_ENABLED_CORE_COUNT_DATA; typedef UINT8 EFI_PROCESSOR_THREAD_COUNT_DATA; typedef struct { UINT16 Reserved : 1; UINT16 Unknown : 1; UINT16 Capable64Bit : 1; UINT16 Reserved2 : 13; } EFI_PROCESSOR_CHARACTERISTICS_DATA; /// /// Inconsistent with specification here: /// In ProcSubclass specification 0.9, the enumeration type data structure is NOT defined. /// The equivalent in specification is /// #define EFI_PROCESSOR_FREQUENCY_RECORD_NUMBER 0x00000001 /// #define EFI_PROCESSOR_BUS_FREQUENCY_RECORD_NUMBER 0x00000002 /// #define EFI_PROCESSOR_VERSION_RECORD_NUMBER 0x00000003 /// #define EFI_PROCESSOR_MANUFACTURER_RECORD_NUMBER 0x00000004 /// #define EFI_PROCESSOR_SERIAL_NUMBER_RECORD_NUMBER 0x00000005 /// #define EFI_PROCESSOR_ID_RECORD_NUMBER 0x00000006 /// #define EFI_PROCESSOR_TYPE_RECORD_NUMBER 0x00000007 /// #define EFI_PROCESSOR_FAMILY_RECORD_NUMBER 0x00000008 /// #define EFI_PROCESSOR_VOLTAGE_RECORD_NUMBER 0x00000009 /// #define EFI_PROCESSOR_APIC_BASE_ADDRESS_RECORD_NUMBER 0x0000000A /// #define EFI_PROCESSOR_APIC_ID_RECORD_NUMBER 0x0000000B /// #define EFI_PROCESSOR_APIC_VER_NUMBER_RECORD_NUMBER 0x0000000C /// #define EFI_PROCESSOR_MICROCODE_REVISION_RECORD_NUMBER 0x0000000D /// #define EFI_PROCESSOR_STATUS_RECORD_NUMBER 0x0000000E /// #define EFI_PROCESSOR_SOCKET_TYPE_RECORD_NUMBER 0x0000000F /// #define EFI_PROCESSOR_SOCKET_NAME_RECORD_NUMBER 0x00000010 /// #define EFI_PROCESSOR_CACHE_ASSOCIATION_RECORD_NUMBER 0x00000011 /// #define EFI_PROCESSOR_MAX_FREQUENCY_RECORD_NUMBER 0x00000012 /// #define EFI_PROCESSOR_ASSET_TAG_RECORD_NUMBER 0x00000013 /// #define EFI_PROCESSOR_MAX_FSB_FREQUENCY_RECORD_NUMBER 0x00000014 /// #define EFI_PROCESSOR_PACKAGE_NUMBER_RECORD_NUMBER 0x00000015 /// #define EFI_PROCESSOR_FREQUENCY_LIST_RECORD_NUMBER 0x00000016 /// #define EFI_PROCESSOR_FSB_FREQUENCY_LIST_RECORD_NUMBER 0x00000017 /// #define EFI_PROCESSOR_HEALTH_STATUS_RECORD_NUMBER 0x00000018 /// /// Keep the definition unchanged for backward compatibility. typedef enum { ProcessorCoreFrequencyRecordType = 1, ProcessorFsbFrequencyRecordType = 2, ProcessorVersionRecordType = 3, ProcessorManufacturerRecordType = 4, ProcessorSerialNumberRecordType = 5, ProcessorIdRecordType = 6, ProcessorTypeRecordType = 7, ProcessorFamilyRecordType = 8, ProcessorVoltageRecordType = 9, ProcessorApicBaseAddressRecordType = 10, ProcessorApicIdRecordType = 11, ProcessorApicVersionNumberRecordType = 12, CpuUcodeRevisionDataRecordType = 13, ProcessorStatusRecordType = 14, ProcessorSocketTypeRecordType = 15, ProcessorSocketNameRecordType = 16, CacheAssociationRecordType = 17, ProcessorMaxCoreFrequencyRecordType = 18, ProcessorAssetTagRecordType = 19, ProcessorMaxFsbFrequencyRecordType = 20, ProcessorPackageNumberRecordType = 21, ProcessorCoreFrequencyListRecordType = 22, ProcessorFsbFrequencyListRecordType = 23, ProcessorHealthStatusRecordType = 24, ProcessorCoreCountRecordType = 25, ProcessorEnabledCoreCountRecordType = 26, ProcessorThreadCountRecordType = 27, ProcessorCharacteristicsRecordType = 28, ProcessorFamily2RecordType = 29, ProcessorPartNumberRecordType = 30, } EFI_CPU_VARIABLE_RECORD_TYPE; /// /// Inconsistent with specification here: /// In ProcSubclass specification 0.9, the union type data structure is NOT defined. /// It's implementation-specific to simplify the code logic. /// typedef union { EFI_PROCESSOR_CORE_FREQUENCY_LIST_DATA ProcessorCoreFrequencyList; EFI_PROCESSOR_FSB_FREQUENCY_LIST_DATA ProcessorFsbFrequencyList; EFI_PROCESSOR_SERIAL_NUMBER_DATA ProcessorSerialNumber; EFI_PROCESSOR_CORE_FREQUENCY_DATA ProcessorCoreFrequency; EFI_PROCESSOR_FSB_FREQUENCY_DATA ProcessorFsbFrequency; EFI_PROCESSOR_MAX_CORE_FREQUENCY_DATA ProcessorMaxCoreFrequency; EFI_PROCESSOR_MAX_FSB_FREQUENCY_DATA ProcessorMaxFsbFrequency; EFI_PROCESSOR_VERSION_DATA ProcessorVersion; EFI_PROCESSOR_MANUFACTURER_DATA ProcessorManufacturer; EFI_PROCESSOR_ID_DATA ProcessorId; EFI_PROCESSOR_TYPE_DATA ProcessorType; EFI_PROCESSOR_FAMILY_DATA ProcessorFamily; EFI_PROCESSOR_VOLTAGE_DATA ProcessorVoltage; EFI_PROCESSOR_APIC_BASE_ADDRESS_DATA ProcessorApicBase; EFI_PROCESSOR_APIC_ID_DATA ProcessorApicId; EFI_PROCESSOR_APIC_VERSION_NUMBER_DATA ProcessorApicVersionNumber; EFI_PROCESSOR_MICROCODE_REVISION_DATA CpuUcodeRevisionData; EFI_PROCESSOR_STATUS_DATA ProcessorStatus; EFI_PROCESSOR_SOCKET_TYPE_DATA ProcessorSocketType; EFI_PROCESSOR_SOCKET_NAME_DATA ProcessorSocketName; EFI_PROCESSOR_ASSET_TAG_DATA ProcessorAssetTag; EFI_PROCESSOR_PART_NUMBER_DATA ProcessorPartNumber; EFI_PROCESSOR_HEALTH_STATUS ProcessorHealthStatus; EFI_PROCESSOR_PACKAGE_NUMBER_DATA ProcessorPackageNumber; EFI_PROCESSOR_CORE_COUNT_DATA ProcessorCoreCount; EFI_PROCESSOR_ENABLED_CORE_COUNT_DATA ProcessorEnabledCoreCount; EFI_PROCESSOR_THREAD_COUNT_DATA ProcessorThreadCount; EFI_PROCESSOR_CHARACTERISTICS_DATA ProcessorCharacteristics; EFI_PROCESSOR_FAMILY2_DATA ProcessorFamily2; } EFI_CPU_VARIABLE_RECORD; typedef struct { EFI_SUBCLASS_TYPE1_HEADER DataRecordHeader; EFI_CPU_VARIABLE_RECORD VariableRecord; } EFI_CPU_DATA_RECORD; #define EFI_CACHE_SUBCLASS_VERSION 0x00010000 typedef EFI_EXP_BASE2_DATA EFI_CACHE_SIZE_DATA; /// /// Inconsistent with specification here: /// In CacheSubclass specification 0.9, the naming is EFI_CACHE_MAXIMUM_SIZE_DATA. /// Keep it unchanged for backward compatibilty. /// typedef EFI_EXP_BASE2_DATA EFI_MAXIMUM_CACHE_SIZE_DATA; typedef EFI_EXP_BASE10_DATA EFI_CACHE_SPEED_DATA; typedef STRING_REF EFI_CACHE_SOCKET_DATA; typedef struct { UINT32 Other : 1; UINT32 Unknown : 1; UINT32 NonBurst : 1; UINT32 Burst : 1; UINT32 PipelineBurst : 1; /// /// Inconsistent between CacheSubclass 0.9 and SMBIOS specifications here: /// In CacheSubclass specification 0.9, the sequence of Asynchronous and Synchronous fileds /// are opposite to SMBIOS specification. /// UINT32 Asynchronous : 1; UINT32 Synchronous : 1; UINT32 Reserved : 25; } EFI_CACHE_SRAM_TYPE_DATA; typedef EFI_CACHE_SRAM_TYPE_DATA EFI_CACHE_SRAM_INSTALL_DATA; typedef enum { EfiCacheErrorOther = 1, EfiCacheErrorUnknown = 2, EfiCacheErrorNone = 3, EfiCacheErrorParity = 4, EfiCacheErrorSingleBit = 5, EfiCacheErrorMultiBit = 6 } EFI_CACHE_ERROR_TYPE_DATA; typedef enum { EfiCacheTypeOther = 1, EfiCacheTypeUnknown = 2, EfiCacheTypeInstruction = 3, EfiCacheTypeData = 4, EfiCacheTypeUnified = 5 } EFI_CACHE_TYPE_DATA; typedef enum { EfiCacheAssociativityOther = 1, EfiCacheAssociativityUnknown = 2, EfiCacheAssociativityDirectMapped = 3, EfiCacheAssociativity2Way = 4, EfiCacheAssociativity4Way = 5, EfiCacheAssociativityFully = 6, EfiCacheAssociativity8Way = 7, EfiCacheAssociativity16Way = 8 } EFI_CACHE_ASSOCIATIVITY_DATA; /// /// Inconsistent with specification here: /// In CacheSubclass 0.9 specification. It defines the field type as UINT16. /// In fact, it should be UINT32 type because it refers to a 32bit width data. /// typedef struct { UINT32 Level : 3; UINT32 Socketed : 1; UINT32 Reserved2 : 1; UINT32 Location : 2; UINT32 Enable : 1; UINT32 OperationalMode : 2; UINT32 Reserved1 : 22; } EFI_CACHE_CONFIGURATION_DATA; #define EFI_CACHE_L1 1 #define EFI_CACHE_L2 2 #define EFI_CACHE_L3 3 #define EFI_CACHE_L4 4 #define EFI_CACHE_LMAX EFI_CACHE_L4 #define EFI_CACHE_SOCKETED 1 #define EFI_CACHE_NOT_SOCKETED 0 typedef enum { EfiCacheInternal = 0, EfiCacheExternal = 1, EfiCacheReserved = 2, EfiCacheUnknown = 3 } EFI_CACHE_LOCATION; #define EFI_CACHE_ENABLED 1 #define EFI_CACHE_DISABLED 0 typedef enum { EfiCacheWriteThrough = 0, EfiCacheWriteBack = 1, EfiCacheDynamicMode = 2, EfiCacheUnknownMode = 3 } EFI_CACHE_OPERATIONAL_MODE; /// /// Inconsistent with specification here: /// In CacheSubclass specification 0.9, the enumeration type data structure is NOT defined. /// The equivalent in specification is /// #define EFI_CACHE_SIZE_RECORD_NUMBER 0x00000001 /// #define EFI_CACHE_MAXIMUM_SIZE_RECORD_NUMBER 0x00000002 /// #define EFI_CACHE_SPEED_RECORD_NUMBER 0x00000003 /// #define EFI_CACHE_SOCKET_RECORD_NUMBER 0x00000004 /// #define EFI_CACHE_SRAM_SUPPORT_RECORD_NUMBER 0x00000005 /// #define EFI_CACHE_SRAM_INSTALL_RECORD_NUMBER 0x00000006 /// #define EFI_CACHE_ERROR_SUPPORT_RECORD_NUMBER 0x00000007 /// #define EFI_CACHE_TYPE_RECORD_NUMBER 0x00000008 /// #define EFI_CACHE_ASSOCIATIVITY_RECORD_NUMBER 0x00000009 /// #define EFI_CACHE_CONFIGURATION_RECORD_NUMBER 0x0000000A /// Keep the definition unchanged for backward compatibility. /// typedef enum { CacheSizeRecordType = 1, MaximumSizeCacheRecordType = 2, CacheSpeedRecordType = 3, CacheSocketRecordType = 4, CacheSramTypeRecordType = 5, CacheInstalledSramTypeRecordType = 6, CacheErrorTypeRecordType = 7, CacheTypeRecordType = 8, CacheAssociativityRecordType = 9, CacheConfigRecordType = 10 } EFI_CACHE_VARIABLE_RECORD_TYPE; /// /// Inconsistent with specification here: /// In CacheSubclass specification 0.9, the union type data structure is NOT defined. /// It's implementation-specific to simplify the code logic. /// typedef union { EFI_CACHE_SIZE_DATA CacheSize; EFI_MAXIMUM_CACHE_SIZE_DATA MaximumCacheSize; EFI_CACHE_SPEED_DATA CacheSpeed; EFI_CACHE_SOCKET_DATA CacheSocket; EFI_CACHE_SRAM_TYPE_DATA CacheSramType; EFI_CACHE_SRAM_TYPE_DATA CacheInstalledSramType; EFI_CACHE_ERROR_TYPE_DATA CacheErrorType; EFI_CACHE_TYPE_DATA CacheType; EFI_CACHE_ASSOCIATIVITY_DATA CacheAssociativity; EFI_CACHE_CONFIGURATION_DATA CacheConfig; EFI_CACHE_ASSOCIATION_DATA CacheAssociation; } EFI_CACHE_VARIABLE_RECORD; typedef struct { EFI_SUBCLASS_TYPE1_HEADER DataRecordHeader; EFI_CACHE_VARIABLE_RECORD VariableRecord; } EFI_CACHE_DATA_RECORD; #define EFI_MEMORY_SUBCLASS_VERSION 0x0100 #define EFI_MEMORY_SIZE_RECORD_NUMBER 0x00000001 typedef enum _EFI_MEMORY_REGION_TYPE { EfiMemoryRegionMemory = 0x01, EfiMemoryRegionReserved = 0x02, EfiMemoryRegionAcpi = 0x03, EfiMemoryRegionNvs = 0x04 } EFI_MEMORY_REGION_TYPE; /// /// This data record refers to the size of a memory region. The regions that are /// described can refer to physical memory, memory-mapped I/O, or reserved BIOS memory regions. /// The unit of measurement of this data record is in bytes. /// typedef struct { /// /// A zero-based value that indicates which processor(s) can access the memory region. /// A value of 0xFFFF indicates the region is accessible by all processors. /// UINT32 ProcessorNumber; /// /// A zero-based value that indicates the starting bus that can access the memory region. /// UINT16 StartBusNumber; /// /// A zero-based value that indicates the ending bus that can access the memory region. /// A value of 0xFF for a PCI system indicates the region is accessible by all buses and /// is global in scope. An example of the EndBusNumber not being 0xFF is a system /// with two or more peer-to-host PCI bridges. /// UINT16 EndBusNumber; /// /// The type of memory region from the operating system's point of view. /// MemoryRegionType values are equivalent to the legacy INT 15 AX = E820 BIOS /// command values. /// EFI_MEMORY_REGION_TYPE MemoryRegionType; /// /// The size of the memory region in bytes. /// EFI_EXP_BASE2_DATA MemorySize; /// /// The starting physical address of the memory region. /// EFI_PHYSICAL_ADDRESS MemoryStartAddress; } EFI_MEMORY_SIZE_DATA; #define EFI_MEMORY_ARRAY_LOCATION_RECORD_NUMBER 0x00000002 typedef enum _EFI_MEMORY_ARRAY_LOCATION { EfiMemoryArrayLocationOther = 0x01, EfiMemoryArrayLocationUnknown = 0x02, EfiMemoryArrayLocationSystemBoard = 0x03, EfiMemoryArrayLocationIsaAddonCard = 0x04, EfiMemoryArrayLocationEisaAddonCard = 0x05, EfiMemoryArrayLocationPciAddonCard = 0x06, EfiMemoryArrayLocationMcaAddonCard = 0x07, EfiMemoryArrayLocationPcmciaAddonCard = 0x08, EfiMemoryArrayLocationProprietaryAddonCard = 0x09, EfiMemoryArrayLocationNuBus = 0x0A, EfiMemoryArrayLocationPc98C20AddonCard = 0xA0, EfiMemoryArrayLocationPc98C24AddonCard = 0xA1, EfiMemoryArrayLocationPc98EAddonCard = 0xA2, EfiMemoryArrayLocationPc98LocalBusAddonCard = 0xA3 } EFI_MEMORY_ARRAY_LOCATION; typedef enum _EFI_MEMORY_ARRAY_USE { EfiMemoryArrayUseOther = 0x01, EfiMemoryArrayUseUnknown = 0x02, EfiMemoryArrayUseSystemMemory = 0x03, EfiMemoryArrayUseVideoMemory = 0x04, EfiMemoryArrayUseFlashMemory = 0x05, EfiMemoryArrayUseNonVolatileRam = 0x06, EfiMemoryArrayUseCacheMemory = 0x07 } EFI_MEMORY_ARRAY_USE; typedef enum _EFI_MEMORY_ERROR_CORRECTION { EfiMemoryErrorCorrectionOther = 0x01, EfiMemoryErrorCorrectionUnknown = 0x02, EfiMemoryErrorCorrectionNone = 0x03, EfiMemoryErrorCorrectionParity = 0x04, EfiMemoryErrorCorrectionSingleBitEcc = 0x05, EfiMemoryErrorCorrectionMultiBitEcc = 0x06, EfiMemoryErrorCorrectionCrc = 0x07 } EFI_MEMORY_ERROR_CORRECTION; /// /// This data record refers to the physical memory array. This data record is a structure. /// The type definition structure for EFI_MEMORY_ARRAY_LOCATION_DATA is in SMBIOS 2.3.4: /// - Table 3.3.17.1, Type 16, Offset 0x4 /// - Table 3.3.17.2, Type 16, Offset 0x5 /// - Table 3.3.17.3, Type 16, with the following offsets: /// -- Offset 0x6 /// -- Offset 0x7 /// -- Offset 0xB /// -- Offset 0xD /// typedef struct { /// /// The physical location of the memory array. /// EFI_MEMORY_ARRAY_LOCATION MemoryArrayLocation; /// /// The memory array usage. /// EFI_MEMORY_ARRAY_USE MemoryArrayUse; /// /// The primary error correction or detection supported by this memory array. /// EFI_MEMORY_ERROR_CORRECTION MemoryErrorCorrection; /// /// The maximum memory capacity size in kilobytes. If capacity is unknown, then /// values of MaximumMemoryCapacity.Value = 0x00 and /// MaximumMemoryCapacity.Exponent = 0x8000 are used. /// EFI_EXP_BASE2_DATA MaximumMemoryCapacity; /// /// The number of memory slots or sockets that are available for memory devices /// in this array. /// UINT16 NumberMemoryDevices; } EFI_MEMORY_ARRAY_LOCATION_DATA; #define EFI_MEMORY_ARRAY_LINK_RECORD_NUMBER 0x00000003 typedef enum _EFI_MEMORY_FORM_FACTOR { EfiMemoryFormFactorOther = 0x01, EfiMemoryFormFactorUnknown = 0x02, EfiMemoryFormFactorSimm = 0x03, EfiMemoryFormFactorSip = 0x04, EfiMemoryFormFactorChip = 0x05, EfiMemoryFormFactorDip = 0x06, EfiMemoryFormFactorZip = 0x07, EfiMemoryFormFactorProprietaryCard = 0x08, EfiMemoryFormFactorDimm = 0x09, EfiMemoryFormFactorTsop = 0x0A, EfiMemoryFormFactorRowOfChips = 0x0B, EfiMemoryFormFactorRimm = 0x0C, EfiMemoryFormFactorSodimm = 0x0D, EfiMemoryFormFactorSrimm = 0x0E, /// /// Inconsistent with specification here: /// This field is NOT defined in MemSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiMemoryFormFactorFbDimm = 0x0F } EFI_MEMORY_FORM_FACTOR; typedef enum _EFI_MEMORY_ARRAY_TYPE { EfiMemoryTypeOther = 0x01, EfiMemoryTypeUnknown = 0x02, EfiMemoryTypeDram = 0x03, EfiMemoryTypeEdram = 0x04, EfiMemoryTypeVram = 0x05, EfiMemoryTypeSram = 0x06, EfiMemoryTypeRam = 0x07, EfiMemoryTypeRom = 0x08, EfiMemoryTypeFlash = 0x09, EfiMemoryTypeEeprom = 0x0A, EfiMemoryTypeFeprom = 0x0B, EfiMemoryTypeEprom = 0x0C, EfiMemoryTypeCdram = 0x0D, EfiMemoryType3Dram = 0x0E, EfiMemoryTypeSdram = 0x0F, EfiMemoryTypeSgram = 0x10, EfiMemoryTypeRdram = 0x11, EfiMemoryTypeDdr = 0x12, /// /// Inconsistent with specification here: /// This field is NOT defined in MemSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiMemoryTypeDdr2 = 0x13, /// /// Inconsistent with specification here: /// This field is NOT defined in MemSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiMemoryTypeDdr2FbDimm = 0x14 } EFI_MEMORY_ARRAY_TYPE; typedef struct { UINT32 Reserved : 1; UINT32 Other : 1; UINT32 Unknown : 1; UINT32 FastPaged : 1; UINT32 StaticColumn : 1; UINT32 PseudoStatic : 1; UINT32 Rambus : 1; UINT32 Synchronous : 1; UINT32 Cmos : 1; UINT32 Edo : 1; UINT32 WindowDram : 1; UINT32 CacheDram : 1; UINT32 Nonvolatile : 1; UINT32 Reserved1 : 19; } EFI_MEMORY_TYPE_DETAIL; typedef enum { EfiMemoryStateEnabled = 0, EfiMemoryStateUnknown = 1, EfiMemoryStateUnsupported = 2, EfiMemoryStateError = 3, EfiMemoryStateAbsent = 4, EfiMemoryStateDisabled = 5, /// /// Inconsistent with specification here: /// This field is NOT defined in MemSubClass specification 0.9. It's introduced for SMBIOS2.6 specification. /// EfiMemoryStatePartial = 6 } EFI_MEMORY_STATE; /// /// This data record describes a memory device. This data record is a structure. /// The type definition structure for EFI_MEMORY_ARRAY_LINK_DATA is in SMBIOS 2.3.4. /// typedef struct { /// /// A string that identifies the physically labeled socket or board position where the /// memory device is located. /// STRING_REF MemoryDeviceLocator; /// /// A string denoting the physically labeled bank where the memory device is located. /// STRING_REF MemoryBankLocator; /// /// A string denoting the memory manufacturer. /// STRING_REF MemoryManufacturer; /// /// A string denoting the serial number of the memory device. /// STRING_REF MemorySerialNumber; /// /// The asset tag of the memory device. /// STRING_REF MemoryAssetTag; /// /// A string denoting the part number of the memory device. /// STRING_REF MemoryPartNumber; /// /// A link to a memory array structure set. /// EFI_INTER_LINK_DATA MemoryArrayLink; /// /// A link to a memory array structure set. /// EFI_INTER_LINK_DATA MemorySubArrayLink; /// /// The total width in bits of this memory device. If there are no error correcting bits, /// then the total width equals the data width. If the width is unknown, then set the field /// to 0xFFFF. /// UINT16 MemoryTotalWidth; /// /// The data width in bits of the memory device. A data width of 0x00 and a total width /// of 0x08 indicate that the device is used solely for error correction. /// UINT16 MemoryDataWidth; /// /// The size in bytes of the memory device. A value of 0x00 denotes that no device is /// installed, while a value of all Fs denotes that the size is not known. /// EFI_EXP_BASE2_DATA MemoryDeviceSize; /// /// The form factor of the memory device. /// EFI_MEMORY_FORM_FACTOR MemoryFormFactor; /// /// A memory device set that must be populated with all devices of the same type and /// size. A value of 0x00 indicates that the device is not part of any set. A value of 0xFF /// indicates that the attribute is unknown. Any other value denotes the set number. /// UINT8 MemoryDeviceSet; /// /// The memory type in the socket. /// EFI_MEMORY_ARRAY_TYPE MemoryType; /// /// The memory type details. /// EFI_MEMORY_TYPE_DETAIL MemoryTypeDetail; /// /// The memory speed in megahertz (MHz). A value of 0x00 denotes that /// the speed is unknown. /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the naming is MemoryTypeSpeed. /// Keep it unchanged for backward compatibilty. /// EFI_EXP_BASE10_DATA MemorySpeed; /// /// The memory state. /// EFI_MEMORY_STATE MemoryState; } EFI_MEMORY_ARRAY_LINK_DATA; #define EFI_MEMORY_ARRAY_START_ADDRESS_RECORD_NUMBER 0x00000004 /// /// This data record refers to a specified physical memory array associated with /// a given memory range. /// typedef struct { /// /// The starting physical address in bytes of memory mapped to a specified physical /// memory array. /// EFI_PHYSICAL_ADDRESS MemoryArrayStartAddress; /// /// The last physical address in bytes of memory mapped to a specified physical memory /// array. /// EFI_PHYSICAL_ADDRESS MemoryArrayEndAddress; /// /// See Physical Memory Array (Type 16) for physical memory array structures. /// EFI_INTER_LINK_DATA PhysicalMemoryArrayLink; /// /// The number of memory devices that form a single row of memory for the address /// partition. /// UINT16 MemoryArrayPartitionWidth; } EFI_MEMORY_ARRAY_START_ADDRESS_DATA; #define EFI_MEMORY_DEVICE_START_ADDRESS_RECORD_NUMBER 0x00000005 /// /// This data record refers to a physical memory device that is associated with /// a given memory range. /// typedef struct { /// /// The starting physical address that is associated with the device. /// EFI_PHYSICAL_ADDRESS MemoryDeviceStartAddress; /// /// The ending physical address that is associated with the device. /// EFI_PHYSICAL_ADDRESS MemoryDeviceEndAddress; /// /// A link to the memory device data structure. /// EFI_INTER_LINK_DATA PhysicalMemoryDeviceLink; /// /// A link to the memory array data structure. /// EFI_INTER_LINK_DATA PhysicalMemoryArrayLink; /// /// The position of the memory device in a row. A value of 0x00 is reserved and a value /// of 0xFF indicates that the position is unknown. /// UINT8 MemoryDevicePartitionRowPosition; /// /// The position of the device in an interleave. /// UINT8 MemoryDeviceInterleavePosition; /// /// The maximum number of consecutive rows from the device that are accessed in a /// single interleave transfer. A value of 0x00 indicates that the device is not interleaved /// and a value of 0xFF indicates that the interleave configuration is unknown. /// UINT8 MemoryDeviceInterleaveDataDepth; } EFI_MEMORY_DEVICE_START_ADDRESS_DATA; // // Memory. Channel Device Type - SMBIOS Type 37 // #define EFI_MEMORY_CHANNEL_TYPE_RECORD_NUMBER 0x00000006 typedef enum _EFI_MEMORY_CHANNEL_TYPE { EfiMemoryChannelTypeOther = 1, EfiMemoryChannelTypeUnknown = 2, EfiMemoryChannelTypeRambus = 3, EfiMemoryChannelTypeSyncLink = 4 } EFI_MEMORY_CHANNEL_TYPE; /// /// This data record refers the type of memory that is associated with the channel. This data record is a /// structure. /// The type definition structure for EFI_MEMORY_CHANNEL_TYPE_DATA is in SMBIOS 2.3.4, /// Table 3.3.38, Type 37, with the following offsets: /// - Offset 0x4 /// - Offset 0x5 /// - Offset 0x6 /// typedef struct { /// /// The type of memory that is associated with the channel. /// EFI_MEMORY_CHANNEL_TYPE MemoryChannelType; /// /// The maximum load that is supported by the channel. /// UINT8 MemoryChannelMaximumLoad; /// /// The number of memory devices on this channel. /// UINT8 MemoryChannelDeviceCount; } EFI_MEMORY_CHANNEL_TYPE_DATA; #define EFI_MEMORY_CHANNEL_DEVICE_RECORD_NUMBER 0x00000007 /// /// This data record refers to the memory device that is associated with the memory channel. This data /// record is a structure. /// The type definition structure for EFI_MEMORY_CHANNEL_DEVICE_DATA is in SMBIOS 2.3.4, /// Table 3.3.38, Type 37, with the following offsets: /// - Offset 0x7 /// - Offset 0x8 /// typedef struct { /// /// A number between one and MemoryChannelDeviceCount plus an arbitrary base. /// UINT8 DeviceId; /// /// The Link of the associated memory device. See Memory Device (Type 17) for /// memory devices. /// EFI_INTER_LINK_DATA DeviceLink; /// /// The number of load units that this device consumes. /// UINT8 MemoryChannelDeviceLoad; } EFI_MEMORY_CHANNEL_DEVICE_DATA; // // Memory. Controller Information - SMBIOS Type 5 // /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 5. /// #define EFI_MEMORY_CONTROLLER_INFORMATION_RECORD_NUMBER 0x00000008 /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 5. /// typedef enum { EfiErrorDetectingMethodOther = 1, EfiErrorDetectingMethodUnknown = 2, EfiErrorDetectingMethodNone = 3, EfiErrorDetectingMethodParity = 4, EfiErrorDetectingMethod32Ecc = 5, EfiErrorDetectingMethod64Ecc = 6, EfiErrorDetectingMethod128Ecc = 7, EfiErrorDetectingMethodCrc = 8 } EFI_MEMORY_ERROR_DETECT_METHOD_TYPE; /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 5. /// typedef struct { UINT8 Other : 1; UINT8 Unknown : 1; UINT8 None : 1; UINT8 SingleBitErrorCorrect : 1; UINT8 DoubleBitErrorCorrect : 1; UINT8 ErrorScrubbing : 1; UINT8 Reserved : 2; } EFI_MEMORY_ERROR_CORRECT_CAPABILITY; /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 5. /// typedef enum { EfiMemoryInterleaveOther = 1, EfiMemoryInterleaveUnknown = 2, EfiMemoryInterleaveOneWay = 3, EfiMemoryInterleaveTwoWay = 4, EfiMemoryInterleaveFourWay = 5, EfiMemoryInterleaveEightWay = 6, EfiMemoryInterleaveSixteenWay = 7 } EFI_MEMORY_SUPPORT_INTERLEAVE_TYPE; /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 5. /// typedef struct { UINT16 Other : 1; UINT16 Unknown : 1; UINT16 SeventyNs : 1; UINT16 SixtyNs : 1; UINT16 FiftyNs : 1; UINT16 Reserved : 11; } EFI_MEMORY_SPEED_TYPE; /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 5. /// typedef struct { UINT16 Other : 1; UINT16 Unknown : 1; UINT16 Standard : 1; UINT16 FastPageMode : 1; UINT16 EDO : 1; UINT16 Parity : 1; UINT16 ECC : 1; UINT16 SIMM : 1; UINT16 DIMM : 1; UINT16 BurstEdo : 1; UINT16 SDRAM : 1; UINT16 Reserved : 5; } EFI_MEMORY_SUPPORTED_TYPE; /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 5. /// typedef struct { UINT8 Five : 1; UINT8 Three : 1; UINT8 Two : 1; UINT8 Reserved : 5; } EFI_MEMORY_MODULE_VOLTAGE_TYPE; /// /// EFI_MEMORY_CONTROLLER_INFORMATION is obsolete /// Use EFI_MEMORY_CONTROLLER_INFORMATION_DATA instead /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 5. /// typedef struct { EFI_MEMORY_ERROR_DETECT_METHOD_TYPE ErrorDetectingMethod; EFI_MEMORY_ERROR_CORRECT_CAPABILITY ErrorCorrectingCapability; EFI_MEMORY_SUPPORT_INTERLEAVE_TYPE MemorySupportedInterleave; EFI_MEMORY_SUPPORT_INTERLEAVE_TYPE MemoryCurrentInterleave; UINT8 MaxMemoryModuleSize; EFI_MEMORY_SPEED_TYPE MemorySpeedType; EFI_MEMORY_SUPPORTED_TYPE MemorySupportedType; EFI_MEMORY_MODULE_VOLTAGE_TYPE MemoryModuleVoltage; UINT8 NumberofMemorySlot; EFI_MEMORY_ERROR_CORRECT_CAPABILITY EnabledCorrectingCapability; UINT16 *MemoryModuleConfigHandles; } EFI_MEMORY_CONTROLLER_INFORMATION; /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 5. /// typedef struct { EFI_MEMORY_ERROR_DETECT_METHOD_TYPE ErrorDetectingMethod; EFI_MEMORY_ERROR_CORRECT_CAPABILITY ErrorCorrectingCapability; EFI_MEMORY_SUPPORT_INTERLEAVE_TYPE MemorySupportedInterleave; EFI_MEMORY_SUPPORT_INTERLEAVE_TYPE MemoryCurrentInterleave; UINT8 MaxMemoryModuleSize; EFI_MEMORY_SPEED_TYPE MemorySpeedType; EFI_MEMORY_SUPPORTED_TYPE MemorySupportedType; EFI_MEMORY_MODULE_VOLTAGE_TYPE MemoryModuleVoltage; UINT8 NumberofMemorySlot; EFI_MEMORY_ERROR_CORRECT_CAPABILITY EnabledCorrectingCapability; EFI_INTER_LINK_DATA MemoryModuleConfig[1]; } EFI_MEMORY_CONTROLLER_INFORMATION_DATA; /// /// Memory. Error Information - SMBIOS Type 18 /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 18. /// #define EFI_MEMORY_32BIT_ERROR_INFORMATION_RECORD_NUMBER 0x00000009 /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 18. /// typedef enum { EfiMemoryErrorOther = 1, EfiMemoryErrorUnknown = 2, EfiMemoryErrorOk = 3, EfiMemoryErrorBadRead = 4, EfiMemoryErrorParity = 5, EfiMemoryErrorSigleBit = 6, EfiMemoryErrorDoubleBit = 7, EfiMemoryErrorMultiBit = 8, EfiMemoryErrorNibble = 9, EfiMemoryErrorChecksum = 10, EfiMemoryErrorCrc = 11, EfiMemoryErrorCorrectSingleBit = 12, EfiMemoryErrorCorrected = 13, EfiMemoryErrorUnCorrectable = 14 } EFI_MEMORY_ERROR_TYPE; /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 18. /// typedef enum { EfiMemoryGranularityOther = 1, EfiMemoryGranularityOtherUnknown = 2, EfiMemoryGranularityDeviceLevel = 3, EfiMemoryGranularityMemPartitionLevel = 4 } EFI_MEMORY_ERROR_GRANULARITY_TYPE; /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 18. /// typedef enum { EfiMemoryErrorOperationOther = 1, EfiMemoryErrorOperationUnknown = 2, EfiMemoryErrorOperationRead = 3, EfiMemoryErrorOperationWrite = 4, EfiMemoryErrorOperationPartialWrite = 5 } EFI_MEMORY_ERROR_OPERATION_TYPE; /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 18. /// typedef struct { EFI_MEMORY_ERROR_TYPE MemoryErrorType; EFI_MEMORY_ERROR_GRANULARITY_TYPE MemoryErrorGranularity; EFI_MEMORY_ERROR_OPERATION_TYPE MemoryErrorOperation; UINT32 VendorSyndrome; UINT32 MemoryArrayErrorAddress; UINT32 DeviceErrorAddress; UINT32 DeviceErrorResolution; } EFI_MEMORY_32BIT_ERROR_INFORMATION; /// /// Memory. Error Information - SMBIOS Type 33. /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 33. /// #define EFI_MEMORY_64BIT_ERROR_INFORMATION_RECORD_NUMBER 0x0000000A /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 type 33. /// typedef struct { EFI_MEMORY_ERROR_TYPE MemoryErrorType; EFI_MEMORY_ERROR_GRANULARITY_TYPE MemoryErrorGranularity; EFI_MEMORY_ERROR_OPERATION_TYPE MemoryErrorOperation; UINT32 VendorSyndrome; UINT64 MemoryArrayErrorAddress; UINT64 DeviceErrorAddress; UINT32 DeviceErrorResolution; } EFI_MEMORY_64BIT_ERROR_INFORMATION; /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It is implementation-specific to simplify the code logic. /// typedef union _EFI_MEMORY_SUBCLASS_RECORDS { EFI_MEMORY_SIZE_DATA SizeData; EFI_MEMORY_ARRAY_LOCATION_DATA ArrayLocationData; EFI_MEMORY_ARRAY_LINK_DATA ArrayLink; EFI_MEMORY_ARRAY_START_ADDRESS_DATA ArrayStartAddress; EFI_MEMORY_DEVICE_START_ADDRESS_DATA DeviceStartAddress; EFI_MEMORY_CHANNEL_TYPE_DATA ChannelTypeData; EFI_MEMORY_CHANNEL_DEVICE_DATA ChannelDeviceData; EFI_MEMORY_CONTROLLER_INFORMATION MemoryControllerInfo; EFI_MEMORY_32BIT_ERROR_INFORMATION Memory32bitErrorInfo; EFI_MEMORY_64BIT_ERROR_INFORMATION Memory64bitErrorInfo; } EFI_MEMORY_SUBCLASS_RECORDS; typedef struct { EFI_SUBCLASS_TYPE1_HEADER Header; EFI_MEMORY_SUBCLASS_RECORDS Record; } EFI_MEMORY_SUBCLASS_DRIVER_DATA; #define EFI_MISC_SUBCLASS_VERSION 0x0100 #pragma pack(1) // // Last PCI Bus Number // #define EFI_MISC_LAST_PCI_BUS_RECORD_NUMBER 0x00000001 typedef struct { UINT8 LastPciBus; } EFI_MISC_LAST_PCI_BUS_DATA; // // Misc. BIOS Vendor - SMBIOS Type 0 // #define EFI_MISC_BIOS_VENDOR_RECORD_NUMBER 0x00000002 typedef struct { UINT64 Reserved1 : 2; UINT64 Unknown : 1; UINT64 BiosCharacteristicsNotSupported : 1; UINT64 IsaIsSupported : 1; UINT64 McaIsSupported : 1; UINT64 EisaIsSupported : 1; UINT64 PciIsSupported : 1; UINT64 PcmciaIsSupported : 1; UINT64 PlugAndPlayIsSupported : 1; UINT64 ApmIsSupported : 1; UINT64 BiosIsUpgradable : 1; UINT64 BiosShadowingAllowed : 1; UINT64 VlVesaIsSupported : 1; UINT64 EscdSupportIsAvailable : 1; UINT64 BootFromCdIsSupported : 1; UINT64 SelectableBootIsSupported : 1; UINT64 RomBiosIsSocketed : 1; UINT64 BootFromPcmciaIsSupported : 1; UINT64 EDDSpecificationIsSupported : 1; UINT64 JapaneseNecFloppyIsSupported : 1; UINT64 JapaneseToshibaFloppyIsSupported : 1; UINT64 Floppy525_360IsSupported : 1; UINT64 Floppy525_12IsSupported : 1; UINT64 Floppy35_720IsSupported : 1; UINT64 Floppy35_288IsSupported : 1; UINT64 PrintScreenIsSupported : 1; UINT64 Keyboard8042IsSupported : 1; UINT64 SerialIsSupported : 1; UINT64 PrinterIsSupported : 1; UINT64 CgaMonoIsSupported : 1; UINT64 NecPc98 : 1; UINT64 AcpiIsSupported : 1; UINT64 UsbLegacyIsSupported : 1; UINT64 AgpIsSupported : 1; UINT64 I20BootIsSupported : 1; UINT64 Ls120BootIsSupported : 1; UINT64 AtapiZipDriveBootIsSupported : 1; UINT64 Boot1394IsSupported : 1; UINT64 SmartBatteryIsSupported : 1; UINT64 BiosBootSpecIsSupported : 1; UINT64 FunctionKeyNetworkBootIsSupported : 1; UINT64 Reserved : 22; } EFI_MISC_BIOS_CHARACTERISTICS; typedef struct { UINT64 BiosReserved : 16; UINT64 SystemReserved : 16; UINT64 Reserved : 32; } EFI_MISC_BIOS_CHARACTERISTICS_EXTENSION; typedef struct { STRING_REF BiosVendor; STRING_REF BiosVersion; STRING_REF BiosReleaseDate; EFI_PHYSICAL_ADDRESS BiosStartingAddress; EFI_EXP_BASE2_DATA BiosPhysicalDeviceSize; EFI_MISC_BIOS_CHARACTERISTICS BiosCharacteristics1; EFI_MISC_BIOS_CHARACTERISTICS_EXTENSION BiosCharacteristics2; /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, this data structure and corrsponding fields are NOT defined. /// It's introduced for SmBios 2.6 specification type 0. /// UINT8 BiosMajorRelease; /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, this data structure and corrsponding fields are NOT defined. /// It's introduced for SmBios 2.6 specification type 0. /// UINT8 BiosMinorRelease; /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, this data structure and corrsponding fields are NOT defined. /// It's introduced for SmBios 2.6 specification type 0. /// UINT8 BiosEmbeddedFirmwareMajorRelease; /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, this data structure and corrsponding fields are NOT defined. /// It's introduced for SmBios 2.6 specification type 0. /// UINT8 BiosEmbeddedFirmwareMinorRelease; } EFI_MISC_BIOS_VENDOR_DATA; // // Misc. System Manufacturer - SMBIOS Type 1 // #define EFI_MISC_SYSTEM_MANUFACTURER_RECORD_NUMBER 0x00000003 typedef enum { EfiSystemWakeupTypeReserved = 0, EfiSystemWakeupTypeOther = 1, EfiSystemWakeupTypeUnknown = 2, EfiSystemWakeupTypeApmTimer = 3, EfiSystemWakeupTypeModemRing = 4, EfiSystemWakeupTypeLanRemote = 5, EfiSystemWakeupTypePowerSwitch = 6, EfiSystemWakeupTypePciPme = 7, EfiSystemWakeupTypeAcPowerRestored = 8 } EFI_MISC_SYSTEM_WAKEUP_TYPE; typedef struct { STRING_REF SystemManufacturer; STRING_REF SystemProductName; STRING_REF SystemVersion; STRING_REF SystemSerialNumber; EFI_GUID SystemUuid; EFI_MISC_SYSTEM_WAKEUP_TYPE SystemWakeupType; /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, this data structure and corrsponding fields are NOT defined. /// It's introduced for SmBios 2.6 specification type 1. /// STRING_REF SystemSKUNumber; /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, this data structure and corrsponding fields are NOT defined. /// It's introduced for SmBios 2.6 specification type 1. /// STRING_REF SystemFamily; } EFI_MISC_SYSTEM_MANUFACTURER_DATA; // // Misc. Base Board Manufacturer - SMBIOS Type 2 // #define EFI_MISC_BASE_BOARD_MANUFACTURER_RECORD_NUMBER 0x00000004 typedef struct { UINT32 Motherboard : 1; UINT32 RequiresDaughterCard : 1; UINT32 Removable : 1; UINT32 Replaceable : 1; UINT32 HotSwappable : 1; UINT32 Reserved : 27; } EFI_BASE_BOARD_FEATURE_FLAGS; typedef enum { EfiBaseBoardTypeUnknown = 1, EfiBaseBoardTypeOther = 2, EfiBaseBoardTypeServerBlade = 3, EfiBaseBoardTypeConnectivitySwitch = 4, EfiBaseBoardTypeSystemManagementModule = 5, EfiBaseBoardTypeProcessorModule = 6, EfiBaseBoardTypeIOModule = 7, EfiBaseBoardTypeMemoryModule = 8, EfiBaseBoardTypeDaughterBoard = 9, EfiBaseBoardTypeMotherBoard = 0xA, EfiBaseBoardTypeProcessorMemoryModule = 0xB, EfiBaseBoardTypeProcessorIOModule = 0xC, EfiBaseBoardTypeInterconnectBoard = 0xD } EFI_BASE_BOARD_TYPE; typedef struct { STRING_REF BaseBoardManufacturer; STRING_REF BaseBoardProductName; STRING_REF BaseBoardVersion; STRING_REF BaseBoardSerialNumber; STRING_REF BaseBoardAssetTag; STRING_REF BaseBoardChassisLocation; EFI_BASE_BOARD_FEATURE_FLAGS BaseBoardFeatureFlags; EFI_BASE_BOARD_TYPE BaseBoardType; EFI_INTER_LINK_DATA BaseBoardChassisLink; UINT32 BaseBoardNumberLinks; EFI_INTER_LINK_DATA LinkN; } EFI_MISC_BASE_BOARD_MANUFACTURER_DATA; // // Misc. System/Chassis Enclosure - SMBIOS Type 3 // #define EFI_MISC_CHASSIS_MANUFACTURER_RECORD_NUMBER 0x00000005 typedef enum { EfiMiscChassisTypeOther = 0x1, EfiMiscChassisTypeUnknown = 0x2, EfiMiscChassisTypeDeskTop = 0x3, EfiMiscChassisTypeLowProfileDesktop = 0x4, EfiMiscChassisTypePizzaBox = 0x5, EfiMiscChassisTypeMiniTower = 0x6, EfiMiscChassisTypeTower = 0x7, EfiMiscChassisTypePortable = 0x8, EfiMiscChassisTypeLapTop = 0x9, EfiMiscChassisTypeNotebook = 0xA, EfiMiscChassisTypeHandHeld = 0xB, EfiMiscChassisTypeDockingStation = 0xC, EfiMiscChassisTypeAllInOne = 0xD, EfiMiscChassisTypeSubNotebook = 0xE, EfiMiscChassisTypeSpaceSaving = 0xF, EfiMiscChassisTypeLunchBox = 0x10, EfiMiscChassisTypeMainServerChassis = 0x11, EfiMiscChassisTypeExpansionChassis = 0x12, EfiMiscChassisTypeSubChassis = 0x13, EfiMiscChassisTypeBusExpansionChassis = 0x14, EfiMiscChassisTypePeripheralChassis = 0x15, EfiMiscChassisTypeRaidChassis = 0x16, EfiMiscChassisTypeRackMountChassis = 0x17, EfiMiscChassisTypeSealedCasePc = 0x18, EfiMiscChassisMultiSystemChassis = 0x19 } EFI_MISC_CHASSIS_TYPE; typedef struct { /// /// Inconsistent with specification here: /// In MiscSubclass 0.9 specification, it has the incorrect field name "EFI_MISC_CHASSIS_TYPE". /// Change it to "ChassisType" to pass build. /// UINT32 ChassisType : 16; UINT32 ChassisLockPresent : 1; UINT32 Reserved : 15; } EFI_MISC_CHASSIS_STATUS; typedef enum { EfiChassisStateOther = 0x01, EfiChassisStateUnknown = 0x02, EfiChassisStateSafe = 0x03, EfiChassisStateWarning = 0x04, EfiChassisStateCritical = 0x05, EfiChassisStateNonRecoverable = 0x06 } EFI_MISC_CHASSIS_STATE; typedef enum { EfiChassisSecurityStatusOther = 0x01, EfiChassisSecurityStatusUnknown = 0x02, EfiChassisSecurityStatusNone = 0x03, EfiChassisSecurityStatusExternalInterfaceLockedOut = 0x04, EfiChassisSecurityStatusExternalInterfaceLockedEnabled = 0x05 } EFI_MISC_CHASSIS_SECURITY_STATE; typedef struct { UINT32 RecordType : 1; UINT32 Type : 7; UINT32 Reserved : 24; } EFI_MISC_ELEMENT_TYPE; typedef struct { EFI_MISC_ELEMENT_TYPE ChassisElementType; EFI_INTER_LINK_DATA ChassisElementStructure; EFI_BASE_BOARD_TYPE ChassisBaseBoard; UINT32 ChassisElementMinimum; UINT32 ChassisElementMaximum; } EFI_MISC_ELEMENTS; typedef struct { STRING_REF ChassisManufacturer; STRING_REF ChassisVersion; STRING_REF ChassisSerialNumber; STRING_REF ChassisAssetTag; EFI_MISC_CHASSIS_STATUS ChassisType; EFI_MISC_CHASSIS_STATE ChassisBootupState; EFI_MISC_CHASSIS_STATE ChassisPowerSupplyState; EFI_MISC_CHASSIS_STATE ChassisThermalState; EFI_MISC_CHASSIS_SECURITY_STATE ChassisSecurityState; UINT32 ChassisOemDefined; UINT32 ChassisHeight; UINT32 ChassisNumberPowerCords; UINT32 ChassisElementCount; UINT32 ChassisElementRecordLength; EFI_MISC_ELEMENTS ChassisElements; } EFI_MISC_CHASSIS_MANUFACTURER_DATA; // // Misc. Port Connector Information - SMBIOS Type 8 // #define EFI_MISC_PORT_INTERNAL_CONNECTOR_DESIGNATOR_RECORD_NUMBER 0x00000006 typedef enum { EfiPortConnectorTypeNone = 0x00, EfiPortConnectorTypeCentronics = 0x01, EfiPortConnectorTypeMiniCentronics = 0x02, EfiPortConnectorTypeProprietary = 0x03, EfiPortConnectorTypeDB25Male = 0x04, EfiPortConnectorTypeDB25Female = 0x05, EfiPortConnectorTypeDB15Male = 0x06, EfiPortConnectorTypeDB15Female = 0x07, EfiPortConnectorTypeDB9Male = 0x08, EfiPortConnectorTypeDB9Female = 0x09, EfiPortConnectorTypeRJ11 = 0x0A, EfiPortConnectorTypeRJ45 = 0x0B, EfiPortConnectorType50PinMiniScsi = 0x0C, EfiPortConnectorTypeMiniDin = 0x0D, EfiPortConnectorTypeMicriDin = 0x0E, EfiPortConnectorTypePS2 = 0x0F, EfiPortConnectorTypeInfrared = 0x10, EfiPortConnectorTypeHpHil = 0x11, EfiPortConnectorTypeUsb = 0x12, EfiPortConnectorTypeSsaScsi = 0x13, EfiPortConnectorTypeCircularDin8Male = 0x14, EfiPortConnectorTypeCircularDin8Female = 0x15, EfiPortConnectorTypeOnboardIde = 0x16, EfiPortConnectorTypeOnboardFloppy = 0x17, EfiPortConnectorType9PinDualInline = 0x18, EfiPortConnectorType25PinDualInline = 0x19, EfiPortConnectorType50PinDualInline = 0x1A, EfiPortConnectorType68PinDualInline = 0x1B, EfiPortConnectorTypeOnboardSoundInput = 0x1C, EfiPortConnectorTypeMiniCentronicsType14 = 0x1D, EfiPortConnectorTypeMiniCentronicsType26 = 0x1E, EfiPortConnectorTypeHeadPhoneMiniJack = 0x1F, EfiPortConnectorTypeBNC = 0x20, EfiPortConnectorType1394 = 0x21, EfiPortConnectorTypePC98 = 0xA0, EfiPortConnectorTypePC98Hireso = 0xA1, EfiPortConnectorTypePCH98 = 0xA2, EfiPortConnectorTypePC98Note = 0xA3, EfiPortConnectorTypePC98Full = 0xA4, EfiPortConnectorTypeOther = 0xFF } EFI_MISC_PORT_CONNECTOR_TYPE; typedef enum { EfiPortTypeNone = 0x00, EfiPortTypeParallelXtAtCompatible = 0x01, EfiPortTypeParallelPortPs2 = 0x02, EfiPortTypeParallelPortEcp = 0x03, EfiPortTypeParallelPortEpp = 0x04, EfiPortTypeParallelPortEcpEpp = 0x05, EfiPortTypeSerialXtAtCompatible = 0x06, EfiPortTypeSerial16450Compatible = 0x07, EfiPortTypeSerial16550Compatible = 0x08, EfiPortTypeSerial16550ACompatible = 0x09, EfiPortTypeScsi = 0x0A, EfiPortTypeMidi = 0x0B, EfiPortTypeJoyStick = 0x0C, EfiPortTypeKeyboard = 0x0D, EfiPortTypeMouse = 0x0E, EfiPortTypeSsaScsi = 0x0F, EfiPortTypeUsb = 0x10, EfiPortTypeFireWire = 0x11, EfiPortTypePcmciaTypeI = 0x12, EfiPortTypePcmciaTypeII = 0x13, EfiPortTypePcmciaTypeIII = 0x14, EfiPortTypeCardBus = 0x15, EfiPortTypeAccessBusPort = 0x16, EfiPortTypeScsiII = 0x17, EfiPortTypeScsiWide = 0x18, EfiPortTypePC98 = 0x19, EfiPortTypePC98Hireso = 0x1A, EfiPortTypePCH98 = 0x1B, EfiPortTypeVideoPort = 0x1C, EfiPortTypeAudioPort = 0x1D, EfiPortTypeModemPort = 0x1E, EfiPortTypeNetworkPort = 0x1F, EfiPortType8251Compatible = 0xA0, EfiPortType8251FifoCompatible = 0xA1, EfiPortTypeOther = 0xFF } EFI_MISC_PORT_TYPE; typedef struct { STRING_REF PortInternalConnectorDesignator; STRING_REF PortExternalConnectorDesignator; EFI_MISC_PORT_CONNECTOR_TYPE PortInternalConnectorType; EFI_MISC_PORT_CONNECTOR_TYPE PortExternalConnectorType; EFI_MISC_PORT_TYPE PortType; /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, this type of field is defined as EFI_DEVICE_PATH_PROTOCOL, /// which causes the implementation some complexity. Keep it unchanged for backward /// compatibility. /// EFI_MISC_PORT_DEVICE_PATH PortPath; } EFI_MISC_PORT_INTERNAL_CONNECTOR_DESIGNATOR_DATA; // // Misc. System Slots - SMBIOS Type 9 // #define EFI_MISC_SYSTEM_SLOT_DESIGNATION_RECORD_NUMBER 0x00000007 typedef enum { EfiSlotTypeOther = 0x01, EfiSlotTypeUnknown = 0x02, EfiSlotTypeIsa = 0x03, EfiSlotTypeMca = 0x04, EfiSlotTypeEisa = 0x05, EfiSlotTypePci = 0x06, EfiSlotTypePcmcia = 0x07, EfiSlotTypeVlVesa = 0x08, EfiSlotTypeProprietary = 0x09, EfiSlotTypeProcessorCardSlot = 0x0A, EfiSlotTypeProprietaryMemoryCardSlot = 0x0B, EfiSlotTypeIORiserCardSlot = 0x0C, EfiSlotTypeNuBus = 0x0D, EfiSlotTypePci66MhzCapable = 0x0E, EfiSlotTypeAgp = 0x0F, /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, its naming should be EfiSlotTypeAgp2X /// rather than EfiSlotTypeApg2X. /// EfiSlotTypeAgp2X = 0x10, EfiSlotTypeAgp4X = 0x11, EfiSlotTypePciX = 0x12, EfiSlotTypeAgp8x = 0x13, EfiSlotTypePC98C20 = 0xA0, EfiSlotTypePC98C24 = 0xA1, EfiSlotTypePC98E = 0xA2, EfiSlotTypePC98LocalBus = 0xA3, EfiSlotTypePC98Card = 0xA4, /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, these fields aren't defined. /// They're introduced for SmBios 2.6 specification type 9. /// EfiSlotTypePciExpress = 0xA5, EfiSlotTypePciExpressX1 = 0xA6, EfiSlotTypePciExpressX2 = 0xA7, EfiSlotTypePciExpressX4 = 0xA8, EfiSlotTypePciExpressX8 = 0xA9, EfiSlotTypePciExpressX16 = 0xAA } EFI_MISC_SLOT_TYPE; typedef enum { EfiSlotDataBusWidthOther = 0x01, EfiSlotDataBusWidthUnknown = 0x02, EfiSlotDataBusWidth8Bit = 0x03, EfiSlotDataBusWidth16Bit = 0x04, EfiSlotDataBusWidth32Bit = 0x05, EfiSlotDataBusWidth64Bit = 0x06, EfiSlotDataBusWidth128Bit = 0x07, /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, these fields aren't defined. /// They're introduced for SmBios 2.6 specification type 9. /// EfiSlotDataBusWidth1xOrx1 = 0x8, EfiSlotDataBusWidth2xOrx2 = 0x9, EfiSlotDataBusWidth4xOrx4 = 0xA, EfiSlotDataBusWidth8xOrx8 = 0xB, EfiSlotDataBusWidth12xOrx12 = 0xC, EfiSlotDataBusWidth16xOrx16 = 0xD, EfiSlotDataBusWidth32xOrx32 = 0xE } EFI_MISC_SLOT_DATA_BUS_WIDTH; typedef enum { EfiSlotUsageOther = 1, EfiSlotUsageUnknown = 2, EfiSlotUsageAvailable = 3, EfiSlotUsageInUse = 4 } EFI_MISC_SLOT_USAGE; typedef enum { EfiSlotLengthOther = 1, EfiSlotLengthUnknown = 2, EfiSlotLengthShort = 3, EfiSlotLengthLong = 4 } EFI_MISC_SLOT_LENGTH; typedef struct { UINT32 CharacteristicsUnknown : 1; UINT32 Provides50Volts : 1; UINT32 Provides33Volts : 1; UINT32 SharedSlot : 1; UINT32 PcCard16Supported : 1; UINT32 CardBusSupported : 1; UINT32 ZoomVideoSupported : 1; UINT32 ModemRingResumeSupported : 1; UINT32 PmeSignalSupported : 1; UINT32 HotPlugDevicesSupported : 1; UINT32 SmbusSignalSupported : 1; UINT32 Reserved : 21; } EFI_MISC_SLOT_CHARACTERISTICS; typedef struct { STRING_REF SlotDesignation; EFI_MISC_SLOT_TYPE SlotType; EFI_MISC_SLOT_DATA_BUS_WIDTH SlotDataBusWidth; EFI_MISC_SLOT_USAGE SlotUsage; EFI_MISC_SLOT_LENGTH SlotLength; UINT16 SlotId; EFI_MISC_SLOT_CHARACTERISTICS SlotCharacteristics; EFI_DEVICE_PATH_PROTOCOL SlotDevicePath; } EFI_MISC_SYSTEM_SLOT_DESIGNATION_DATA; // // Misc. Onboard Device - SMBIOS Type 10 // #define EFI_MISC_ONBOARD_DEVICE_RECORD_NUMBER 0x00000008 typedef enum { EfiOnBoardDeviceTypeOther = 1, EfiOnBoardDeviceTypeUnknown = 2, EfiOnBoardDeviceTypeVideo = 3, EfiOnBoardDeviceTypeScsiController = 4, EfiOnBoardDeviceTypeEthernet = 5, EfiOnBoardDeviceTypeTokenRing = 6, EfiOnBoardDeviceTypeSound = 7 } EFI_MISC_ONBOARD_DEVICE_TYPE; typedef struct { UINT32 DeviceType : 16; UINT32 DeviceEnabled : 1; UINT32 Reserved : 15; } EFI_MISC_ONBOARD_DEVICE_STATUS; typedef struct { STRING_REF OnBoardDeviceDescription; /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, the name is OnBoardDeviceType. /// Keep it unchanged for backward compatibilty. /// EFI_MISC_ONBOARD_DEVICE_STATUS OnBoardDeviceStatus; EFI_DEVICE_PATH_PROTOCOL OnBoardDevicePath; } EFI_MISC_ONBOARD_DEVICE_DATA; // // Misc. BIOS Language Information - SMBIOS Type 11 // #define EFI_MISC_OEM_STRING_RECORD_NUMBER 0x00000009 typedef struct { STRING_REF OemStringRef[1]; } EFI_MISC_OEM_STRING_DATA; // // Misc. System Options - SMBIOS Type 12 // typedef struct { STRING_REF SystemOptionStringRef[1]; } EFI_MISC_SYSTEM_OPTION_STRING_DATA; #define EFI_MISC_SYSTEM_OPTION_STRING_RECORD_NUMBER 0x0000000A // // Misc. Number of Installable Languages - SMBIOS Type 13 // #define EFI_MISC_NUMBER_OF_INSTALLABLE_LANGUAGES_RECORD_NUMBER 0x0000000B typedef struct { UINT32 AbbreviatedLanguageFormat : 1; UINT32 Reserved : 31; } EFI_MISC_LANGUAGE_FLAGS; typedef struct { UINT16 NumberOfInstallableLanguages; EFI_MISC_LANGUAGE_FLAGS LanguageFlags; UINT16 CurrentLanguageNumber; } EFI_MISC_NUMBER_OF_INSTALLABLE_LANGUAGES_DATA; // // Misc. System Language String // #define EFI_MISC_SYSTEM_LANGUAGE_STRING_RECORD_NUMBER 0x0000000C typedef struct { UINT16 LanguageId; STRING_REF SystemLanguageString; } EFI_MISC_SYSTEM_LANGUAGE_STRING_DATA; // // Group Associations - SMBIOS Type 14 // #define EFI_MISC_GROUP_NAME_RECORD_NUMBER 0x0000000D typedef struct { STRING_REF GroupName; UINT16 NumberGroupItems; UINT16 GroupId; } EFI_MISC_GROUP_NAME_DATA; // // Group Item Set Element // #define EFI_MISC_GROUP_ITEM_SET_RECORD_NUMBER 0x0000000E typedef struct { EFI_GUID SubClass; EFI_INTER_LINK_DATA GroupLink; UINT16 GroupId; UINT16 GroupElementId; } EFI_MISC_GROUP_ITEM_SET_DATA; // // Misc. Pointing Device Type - SMBIOS Type 21 // #define EFI_MISC_POINTING_DEVICE_TYPE_RECORD_NUMBER 0x0000000F typedef enum { EfiPointingDeviceTypeOther = 0x01, EfiPointingDeviceTypeUnknown = 0x02, EfiPointingDeviceTypeMouse = 0x03, EfiPointingDeviceTypeTrackBall = 0x04, EfiPointingDeviceTypeTrackPoint = 0x05, EfiPointingDeviceTypeGlidePoint = 0x06, EfiPointingDeviceTouchPad = 0x07, EfiPointingDeviceTouchScreen = 0x08, EfiPointingDeviceOpticalSensor = 0x09 } EFI_MISC_POINTING_DEVICE_TYPE; typedef enum { EfiPointingDeviceInterfaceOther = 0x01, EfiPointingDeviceInterfaceUnknown = 0x02, EfiPointingDeviceInterfaceSerial = 0x03, EfiPointingDeviceInterfacePs2 = 0x04, EfiPointingDeviceInterfaceInfrared = 0x05, EfiPointingDeviceInterfaceHpHil = 0x06, EfiPointingDeviceInterfaceBusMouse = 0x07, EfiPointingDeviceInterfaceADB = 0x08, EfiPointingDeviceInterfaceBusMouseDB9 = 0xA0, EfiPointingDeviceInterfaceBusMouseMicroDin = 0xA1, EfiPointingDeviceInterfaceUsb = 0xA2 } EFI_MISC_POINTING_DEVICE_INTERFACE; typedef struct { EFI_MISC_POINTING_DEVICE_TYPE PointingDeviceType; EFI_MISC_POINTING_DEVICE_INTERFACE PointingDeviceInterface; UINT16 NumberPointingDeviceButtons; EFI_DEVICE_PATH_PROTOCOL PointingDevicePath; } EFI_MISC_POINTING_DEVICE_TYPE_DATA; // // Portable Battery - SMBIOS Type 22 // /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, the name is EFI_MISC_BATTERY_LOCATION_RECORD_NUMBER. /// Keep it unchanged for backward compatibilty. /// #define EFI_MISC_PORTABLE_BATTERY_RECORD_NUMBER 0x00000010 /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, the structure name is EFI_MISC_BATTERY_DEVICE_CHEMISTRY. /// And all field namings are also different with specification. /// Keep it unchanged for backward compatibilty. /// typedef enum { EfiPortableBatteryDeviceChemistryOther = 1, EfiPortableBatteryDeviceChemistryUnknown = 2, EfiPortableBatteryDeviceChemistryLeadAcid = 3, EfiPortableBatteryDeviceChemistryNickelCadmium = 4, EfiPortableBatteryDeviceChemistryNickelMetalHydride = 5, EfiPortableBatteryDeviceChemistryLithiumIon = 6, EfiPortableBatteryDeviceChemistryZincAir = 7, EfiPortableBatteryDeviceChemistryLithiumPolymer = 8 } EFI_MISC_PORTABLE_BATTERY_DEVICE_CHEMISTRY; /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, the structure name is EFI_MISC_BATTERY_LOCATION_DATA. /// Also, the name and the order of the fields vary with specifications. /// Keep it unchanged for backward compatibilty. /// typedef struct { STRING_REF Location; STRING_REF Manufacturer; STRING_REF ManufactureDate; STRING_REF SerialNumber; STRING_REF DeviceName; EFI_MISC_PORTABLE_BATTERY_DEVICE_CHEMISTRY DeviceChemistry; UINT16 DesignCapacity; UINT16 DesignVoltage; STRING_REF SBDSVersionNumber; UINT8 MaximumError; UINT16 SBDSSerialNumber; UINT16 SBDSManufactureDate; STRING_REF SBDSDeviceChemistry; UINT8 DesignCapacityMultiplier; UINT32 OEMSpecific; UINT8 BatteryNumber; // Temporary BOOLEAN Valid; // Is entry valid - Temporary } EFI_MISC_PORTABLE_BATTERY; // // Misc. Reset Capabilities - SMBIOS Type 23 // #define EFI_MISC_RESET_CAPABILITIES_RECORD_NUMBER 0x00000011 typedef struct { UINT32 Status : 1; UINT32 BootOption : 2; UINT32 BootOptionOnLimit : 2; UINT32 WatchdogTimerPresent : 1; UINT32 Reserved : 26; } EFI_MISC_RESET_CAPABILITIES_TYPE; typedef struct { EFI_MISC_RESET_CAPABILITIES_TYPE ResetCapabilities; UINT16 ResetCount; UINT16 ResetLimit; UINT16 ResetTimerInterval; UINT16 ResetTimeout; } EFI_MISC_RESET_CAPABILITIES; typedef struct { EFI_MISC_RESET_CAPABILITIES ResetCapabilities; UINT16 ResetCount; UINT16 ResetLimit; UINT16 ResetTimerInterval; UINT16 ResetTimeout; } EFI_MISC_RESET_CAPABILITIES_DATA; // // Misc. Hardware Security - SMBIOS Type 24 // #define EFI_MISC_HARDWARE_SECURITY_SETTINGS_DATA_RECORD_NUMBER 0x00000012 /// /// Inconsistent with specification here: /// The MiscSubclass specification 0.9 only mentions the possible value of each field in /// EFI_MISC_HARDWARE_SECURITY_SETTINGS. /// It's implementation-specific in order to to simplify the code logic. /// typedef enum { EfiHardwareSecurityStatusDisabled = 0, EfiHardwareSecurityStatusEnabled = 1, EfiHardwareSecurityStatusNotImplemented = 2, EfiHardwareSecurityStatusUnknown = 3 } EFI_MISC_HARDWARE_SECURITY_STATUS; typedef struct { UINT32 FrontPanelResetStatus : 2; UINT32 AdministratorPasswordStatus : 2; UINT32 KeyboardPasswordStatus : 2; UINT32 PowerOnPasswordStatus : 2; UINT32 Reserved : 24; } EFI_MISC_HARDWARE_SECURITY_SETTINGS; typedef struct { EFI_MISC_HARDWARE_SECURITY_SETTINGS HardwareSecuritySettings; } EFI_MISC_HARDWARE_SECURITY_SETTINGS_DATA; // // System Power Controls - SMBIOS Type 25 // #define EFI_MISC_SCHEDULED_POWER_ON_MONTH_RECORD_NUMBER 0x00000013 typedef struct { UINT16 ScheduledPoweronMonth; UINT16 ScheduledPoweronDayOfMonth; UINT16 ScheduledPoweronHour; UINT16 ScheduledPoweronMinute; UINT16 ScheduledPoweronSecond; } EFI_MISC_SCHEDULED_POWER_ON_MONTH_DATA; // // Voltage Probe - SMBIOS Type 26 // #define EFI_MISC_VOLTAGE_PROBE_DESCRIPTION_RECORD_NUMBER 0x00000014 typedef struct { UINT32 VoltageProbeSite : 5; UINT32 VoltageProbeStatus : 3; UINT32 Reserved : 24; } EFI_MISC_VOLTAGE_PROBE_LOCATION; typedef struct { STRING_REF VoltageProbeDescription; EFI_MISC_VOLTAGE_PROBE_LOCATION VoltageProbeLocation; EFI_EXP_BASE10_DATA VoltageProbeMaximumValue; EFI_EXP_BASE10_DATA VoltageProbeMinimumValue; EFI_EXP_BASE10_DATA VoltageProbeResolution; EFI_EXP_BASE10_DATA VoltageProbeTolerance; EFI_EXP_BASE10_DATA VoltageProbeAccuracy; EFI_EXP_BASE10_DATA VoltageProbeNominalValue; EFI_EXP_BASE10_DATA MDLowerNoncriticalThreshold; EFI_EXP_BASE10_DATA MDUpperNoncriticalThreshold; EFI_EXP_BASE10_DATA MDLowerCriticalThreshold; EFI_EXP_BASE10_DATA MDUpperCriticalThreshold; EFI_EXP_BASE10_DATA MDLowerNonrecoverableThreshold; EFI_EXP_BASE10_DATA MDUpperNonrecoverableThreshold; UINT32 VoltageProbeOemDefined; } EFI_MISC_VOLTAGE_PROBE_DESCRIPTION_DATA; // // Cooling Device - SMBIOS Type 27 // #define EFI_MISC_COOLING_DEVICE_TEMP_LINK_RECORD_NUMBER 0x00000015 typedef struct { UINT32 CoolingDevice : 5; UINT32 CoolingDeviceStatus : 3; UINT32 Reserved : 24; } EFI_MISC_COOLING_DEVICE_TYPE; typedef struct { EFI_MISC_COOLING_DEVICE_TYPE CoolingDeviceType; EFI_INTER_LINK_DATA CoolingDeviceTemperatureLink; UINT8 CoolingDeviceUnitGroup; UINT16 CoolingDeviceNominalSpeed; UINT32 CoolingDeviceOemDefined; } EFI_MISC_COOLING_DEVICE_TEMP_LINK_DATA; // // Temperature Probe - SMBIOS Type 28 // #define EFI_MISC_TEMPERATURE_PROBE_DESCRIPTION_RECORD_NUMBER 0x00000016 typedef struct { UINT32 TemperatureProbeSite : 5; UINT32 TemperatureProbeStatus : 3; UINT32 Reserved : 24; } EFI_MISC_TEMPERATURE_PROBE_LOCATION; typedef struct { STRING_REF TemperatureProbeDescription; EFI_MISC_TEMPERATURE_PROBE_LOCATION TemperatureProbeLocation; /// /// Inconsistent with specification here: /// MiscSubclass 0.9 specification defines the fields type as EFI_EXP_BASE10_DATA. /// In fact, they should be UINT16 type because they refer to 16bit width data. /// Keeping this inconsistency for backward compatibility. /// UINT16 TemperatureProbeMaximumValue; UINT16 TemperatureProbeMinimumValue; UINT16 TemperatureProbeResolution; UINT16 TemperatureProbeTolerance; UINT16 TemperatureProbeAccuracy; UINT16 TemperatureProbeNominalValue; UINT16 MDLowerNoncriticalThreshold; UINT16 MDUpperNoncriticalThreshold; UINT16 MDLowerCriticalThreshold; UINT16 MDUpperCriticalThreshold; UINT16 MDLowerNonrecoverableThreshold; UINT16 MDUpperNonrecoverableThreshold; UINT32 TemperatureProbeOemDefined; } EFI_MISC_TEMPERATURE_PROBE_DESCRIPTION_DATA; // // Electrical Current Probe - SMBIOS Type 29 // #define EFI_MISC_ELECTRICAL_CURRENT_PROBE_DESCRIPTION_RECORD_NUMBER 0x00000017 typedef struct { UINT32 ElectricalCurrentProbeSite : 5; UINT32 ElectricalCurrentProbeStatus : 3; UINT32 Reserved : 24; } EFI_MISC_ELECTRICAL_CURRENT_PROBE_LOCATION; typedef struct { STRING_REF ElectricalCurrentProbeDescription; EFI_MISC_ELECTRICAL_CURRENT_PROBE_LOCATION ElectricalCurrentProbeLocation; EFI_EXP_BASE10_DATA ElectricalCurrentProbeMaximumValue; EFI_EXP_BASE10_DATA ElectricalCurrentProbeMinimumValue; EFI_EXP_BASE10_DATA ElectricalCurrentProbeResolution; EFI_EXP_BASE10_DATA ElectricalCurrentProbeTolerance; EFI_EXP_BASE10_DATA ElectricalCurrentProbeAccuracy; EFI_EXP_BASE10_DATA ElectricalCurrentProbeNominalValue; EFI_EXP_BASE10_DATA MDLowerNoncriticalThreshold; EFI_EXP_BASE10_DATA MDUpperNoncriticalThreshold; EFI_EXP_BASE10_DATA MDLowerCriticalThreshold; EFI_EXP_BASE10_DATA MDUpperCriticalThreshold; EFI_EXP_BASE10_DATA MDLowerNonrecoverableThreshold; EFI_EXP_BASE10_DATA MDUpperNonrecoverableThreshold; UINT32 ElectricalCurrentProbeOemDefined; } EFI_MISC_ELECTRICAL_CURRENT_PROBE_DESCRIPTION_DATA; // // Out-of-Band Remote Access - SMBIOS Type 30 // #define EFI_MISC_REMOTE_ACCESS_MANUFACTURER_DESCRIPTION_RECORD_NUMBER 0x00000018 typedef struct { UINT32 InboundConnectionEnabled : 1; UINT32 OutboundConnectionEnabled : 1; UINT32 Reserved : 30; } EFI_MISC_REMOTE_ACCESS_CONNECTIONS; typedef struct { STRING_REF RemoteAccessManufacturerNameDescription; EFI_MISC_REMOTE_ACCESS_CONNECTIONS RemoteAccessConnections; } EFI_MISC_REMOTE_ACCESS_MANUFACTURER_DESCRIPTION_DATA; // // Misc. BIS Entry Point - SMBIOS Type 31 // #define EFI_MISC_BIS_ENTRY_POINT_RECORD_NUMBER 0x00000019 typedef struct { EFI_PHYSICAL_ADDRESS BisEntryPoint; } EFI_MISC_BIS_ENTRY_POINT_DATA; // // Misc. Boot Information - SMBIOS Type 32 // #define EFI_MISC_BOOT_INFORMATION_STATUS_RECORD_NUMBER 0x0000001A /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, the structure name is EFI_MISC_BOOT_INFORMATION_STATUS_TYPE. /// Keep it unchanged for backward compatibilty. /// typedef enum { EfiBootInformationStatusNoError = 0x00, EfiBootInformationStatusNoBootableMedia = 0x01, EfiBootInformationStatusNormalOSFailedLoading = 0x02, EfiBootInformationStatusFirmwareDetectedFailure = 0x03, EfiBootInformationStatusOSDetectedFailure = 0x04, EfiBootInformationStatusUserRequestedBoot = 0x05, EfiBootInformationStatusSystemSecurityViolation = 0x06, EfiBootInformationStatusPreviousRequestedImage = 0x07, EfiBootInformationStatusWatchdogTimerExpired = 0x08, EfiBootInformationStatusStartReserved = 0x09, EfiBootInformationStatusStartOemSpecific = 0x80, EfiBootInformationStatusStartProductSpecific = 0xC0 } EFI_MISC_BOOT_INFORMATION_STATUS_DATA_TYPE; typedef struct { /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, the field name is EFI_MISC_BOOT_INFORMATION_STATUS_TYPE. /// Keep it unchanged for backward compatibilty. /// EFI_MISC_BOOT_INFORMATION_STATUS_DATA_TYPE BootInformationStatus; UINT8 BootInformationData[9]; } EFI_MISC_BOOT_INFORMATION_STATUS_DATA; // // Management Device - SMBIOS Type 34 // #define EFI_MISC_MANAGEMENT_DEVICE_DESCRIPTION_RECORD_NUMBER 0x0000001B typedef enum { EfiManagementDeviceTypeOther = 0x01, EfiManagementDeviceTypeUnknown = 0x02, EfiManagementDeviceTypeLm75 = 0x03, EfiManagementDeviceTypeLm78 = 0x04, EfiManagementDeviceTypeLm79 = 0x05, EfiManagementDeviceTypeLm80 = 0x06, EfiManagementDeviceTypeLm81 = 0x07, EfiManagementDeviceTypeAdm9240 = 0x08, EfiManagementDeviceTypeDs1780 = 0x09, EfiManagementDeviceTypeMaxim1617 = 0x0A, EfiManagementDeviceTypeGl518Sm = 0x0B, EfiManagementDeviceTypeW83781D = 0x0C, EfiManagementDeviceTypeHt82H791 = 0x0D } EFI_MISC_MANAGEMENT_DEVICE_TYPE; typedef enum { EfiManagementDeviceAddressTypeOther = 1, EfiManagementDeviceAddressTypeUnknown = 2, EfiManagementDeviceAddressTypeIOPort = 3, EfiManagementDeviceAddressTypeMemory = 4, EfiManagementDeviceAddressTypeSmbus = 5 } EFI_MISC_MANAGEMENT_DEVICE_ADDRESS_TYPE; typedef struct { STRING_REF ManagementDeviceDescription; EFI_MISC_MANAGEMENT_DEVICE_TYPE ManagementDeviceType; UINTN ManagementDeviceAddress; EFI_MISC_MANAGEMENT_DEVICE_ADDRESS_TYPE ManagementDeviceAddressType; } EFI_MISC_MANAGEMENT_DEVICE_DESCRIPTION_DATA; // // Management Device Component - SMBIOS Type 35 // #define EFI_MISC_MANAGEMENT_DEVICE_COMPONENT_DESCRIPTION_RECORD_NUMBER 0x0000001C typedef struct { STRING_REF ManagementDeviceComponentDescription; EFI_INTER_LINK_DATA ManagementDeviceLink; EFI_INTER_LINK_DATA ManagementDeviceComponentLink; /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, this field is NOT defined. /// It's introduced for SmBios 2.6 specification type 35. /// EFI_INTER_LINK_DATA ManagementDeviceThresholdLink; /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, this field is NOT defined. /// It's implementation-specific to simplify the code logic. /// UINT8 ComponentType; } EFI_MISC_MANAGEMENT_DEVICE_COMPONENT_DESCRIPTION_DATA; // // IPMI Data Record - SMBIOS Type 38 // typedef enum { EfiIpmiOther = 0, EfiIpmiKcs = 1, EfiIpmiSmic = 2, EfiIpmiBt = 3 } EFI_MISC_IPMI_INTERFACE_TYPE; typedef struct { UINT16 IpmiSpecLeastSignificantDigit : 4; UINT16 IpmiSpecMostSignificantDigit : 4; UINT16 Reserved : 8; } EFI_MISC_IPMI_SPECIFICATION_REVISION; typedef struct { EFI_MISC_IPMI_INTERFACE_TYPE IpmiInterfaceType; EFI_MISC_IPMI_SPECIFICATION_REVISION IpmiSpecificationRevision; UINT16 IpmiI2CSlaveAddress; UINT16 IpmiNvDeviceAddress; UINT64 IpmiBaseAddress; EFI_DEVICE_PATH_PROTOCOL IpmiDevicePath; } EFI_MISC_IPMI_INTERFACE_TYPE_DATA; #define EFI_MISC_IPMI_INTERFACE_TYPE_RECORD_NUMBER 0x0000001D /// /// The definition above is *NOT* defined in MiscSubclass specifications 0.9. /// It's defined for backward compatibility. /// #define EFI_MISC_IPMI_INTERFACE_TYPE_DATA_RECORD_NUMBER EFI_MISC_IPMI_INTERFACE_TYPE_RECORD_NUMBER /// /// System Power supply Record - SMBIOS Type 39 /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, the type of all fields are UINT32. /// Keep it unchanged for backward compatibilty. /// typedef struct { UINT16 PowerSupplyHotReplaceable : 1; UINT16 PowerSupplyPresent : 1; UINT16 PowerSupplyUnplugged : 1; UINT16 InputVoltageRangeSwitch : 4; UINT16 PowerSupplyStatus : 3; UINT16 PowerSupplyType : 4; UINT16 Reserved : 2; } EFI_MISC_POWER_SUPPLY_CHARACTERISTICS; /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, the structure name is EFI_MISC_POWER_SUPPLY_UNIT_GROUP_DATA. /// Keep it unchanged for backward compatibilty. /// typedef struct { UINT16 PowerUnitGroup; STRING_REF PowerSupplyLocation; STRING_REF PowerSupplyDeviceName; STRING_REF PowerSupplyManufacturer; STRING_REF PowerSupplySerialNumber; STRING_REF PowerSupplyAssetTagNumber; STRING_REF PowerSupplyModelPartNumber; STRING_REF PowerSupplyRevisionLevel; UINT16 PowerSupplyMaxPowerCapacity; EFI_MISC_POWER_SUPPLY_CHARACTERISTICS PowerSupplyCharacteristics; EFI_INTER_LINK_DATA PowerSupplyInputVoltageProbeLink; EFI_INTER_LINK_DATA PowerSupplyCoolingDeviceLink; EFI_INTER_LINK_DATA PowerSupplyInputCurrentProbeLink; } EFI_MISC_SYSTEM_POWER_SUPPLY_DATA; #define EFI_MISC_SYSTEM_POWER_SUPPLY_RECORD_NUMBER 0x0000001E /// /// OEM Data Record - SMBIOS Type 0x80-0xFF /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, the structure name is EFI_SMBIOS_STRUCTURE_HDR. /// Due to this, the structure is commonly used by vendors to construct SmBios type 0x80~0xFF table, /// Keep it unchanged for backward compatibilty. /// typedef struct { UINT8 Type; UINT8 Length; UINT16 Handle; } SMBIOS_STRUCTURE_HDR; typedef struct { /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, the field name is EFI_SMBIOS_STRUCTURE_HDR. /// Keep it unchanged for backward compatibilty. /// SMBIOS_STRUCTURE_HDR Header; UINT8 RawData[1]; } EFI_MISC_SMBIOS_STRUCT_ENCAPSULATION_DATA; #define EFI_MISC_SMBIOS_STRUCT_ENCAP_RECORD_NUMBER 0x0000001F /// /// Misc. System Event Log - SMBIOS Type 15 /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 specification type 15. /// #define EFI_MISC_SYSTEM_EVENT_LOG_RECORD_NUMBER 0x00000020 /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 specification type 15. /// typedef struct { UINT16 LogAreaLength; UINT16 LogHeaderStartOffset; UINT16 LogDataStartOffset; UINT8 AccessMethod; UINT8 LogStatus; UINT32 LogChangeToken; UINT32 AccessMethodAddress; UINT8 LogHeaderFormat; UINT8 NumberOfSupportedLogType; UINT8 LengthOfLogDescriptor; } EFI_MISC_SYSTEM_EVENT_LOG_DATA; // // Access Method. // 0x00~0x04: as following definition // 0x05~0x7f: Available for future assignment. // 0x80~0xff: BIOS Vendor/OEM-specific. // #define ACCESS_INDEXIO_1INDEX8BIT_DATA8BIT 0x00 #define ACCESS_INDEXIO_2INDEX8BIT_DATA8BIT 0X01 #define ACCESS_INDEXIO_1INDEX16BIT_DATA8BIT 0X02 #define ACCESS_MEMORY_MAPPED 0x03 #define ACCESS_GPNV 0x04 /// /// Management Device Threshold Data Record - SMBIOS Type 36 /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 specification type 36. /// #define EFI_MISC_MANAGEMENT_DEVICE_THRESHOLD_RECORD_NUMBER 0x00000021 /// /// Inconsistent with specification here: /// In MiscSubclass specification 0.9, the following data structures are NOT defined. /// It's introduced for SmBios 2.6 specification type 36. /// typedef struct { UINT16 LowerThresNonCritical; UINT16 UpperThresNonCritical; UINT16 LowerThresCritical; UINT16 UpperThresCritical; UINT16 LowerThresNonRecover; UINT16 UpperThresNonRecover; } EFI_MISC_MANAGEMENT_DEVICE_THRESHOLD; // // Declare the following strutures alias to use them more conviniently. // typedef EFI_MISC_LAST_PCI_BUS_DATA EFI_MISC_LAST_PCI_BUS; typedef EFI_MISC_BIOS_VENDOR_DATA EFI_MISC_BIOS_VENDOR; typedef EFI_MISC_SYSTEM_MANUFACTURER_DATA EFI_MISC_SYSTEM_MANUFACTURER; typedef EFI_MISC_BASE_BOARD_MANUFACTURER_DATA EFI_MISC_BASE_BOARD_MANUFACTURER; typedef EFI_MISC_CHASSIS_MANUFACTURER_DATA EFI_MISC_CHASSIS_MANUFACTURER; typedef EFI_MISC_PORT_INTERNAL_CONNECTOR_DESIGNATOR_DATA EFI_MISC_PORT_INTERNAL_CONNECTOR_DESIGNATOR; typedef EFI_MISC_SYSTEM_SLOT_DESIGNATION_DATA EFI_MISC_SYSTEM_SLOT_DESIGNATION; typedef EFI_MISC_ONBOARD_DEVICE_DATA EFI_MISC_ONBOARD_DEVICE; typedef EFI_MISC_POINTING_DEVICE_TYPE_DATA EFI_MISC_ONBOARD_DEVICE_TYPE_DATA; typedef EFI_MISC_OEM_STRING_DATA EFI_MISC_OEM_STRING; typedef EFI_MISC_SYSTEM_OPTION_STRING_DATA EFI_MISC_SYSTEM_OPTION_STRING; typedef EFI_MISC_NUMBER_OF_INSTALLABLE_LANGUAGES_DATA EFI_MISC_NUMBER_OF_INSTALLABLE_LANGUAGES; typedef EFI_MISC_SYSTEM_LANGUAGE_STRING_DATA EFI_MISC_SYSTEM_LANGUAGE_STRING; typedef EFI_MISC_SYSTEM_EVENT_LOG_DATA EFI_MISC_SYSTEM_EVENT_LOG; typedef EFI_MISC_BIS_ENTRY_POINT_DATA EFI_MISC_BIS_ENTRY_POINT; typedef EFI_MISC_BOOT_INFORMATION_STATUS_DATA EFI_MISC_BOOT_INFORMATION_STATUS; typedef EFI_MISC_SYSTEM_POWER_SUPPLY_DATA EFI_MISC_SYSTEM_POWER_SUPPLY; typedef EFI_MISC_SMBIOS_STRUCT_ENCAPSULATION_DATA EFI_MISC_SMBIOS_STRUCT_ENCAPSULATION; typedef EFI_MISC_SCHEDULED_POWER_ON_MONTH_DATA EFI_MISC_SCHEDULED_POWER_ON_MONTH; typedef EFI_MISC_VOLTAGE_PROBE_DESCRIPTION_DATA EFI_MISC_VOLTAGE_PROBE_DESCRIPTION; typedef EFI_MISC_COOLING_DEVICE_TEMP_LINK_DATA EFI_MISC_COOLING_DEVICE_TEMP_LINK; typedef EFI_MISC_TEMPERATURE_PROBE_DESCRIPTION_DATA EFI_MISC_TEMPERATURE_PROBE_DESCRIPTION; typedef EFI_MISC_REMOTE_ACCESS_MANUFACTURER_DESCRIPTION_DATA EFI_MISC_REMOTE_ACCESS_MANUFACTURER_DESCRIPTION; typedef EFI_MISC_MANAGEMENT_DEVICE_DESCRIPTION_DATA EFI_MISC_MANAGEMENT_DEVICE_DESCRIPTION; typedef EFI_MISC_ELECTRICAL_CURRENT_PROBE_DESCRIPTION_DATA EFI_MISC_ELECTRICAL_CURRENT_PROBE_DESCRIPTION; typedef EFI_MISC_MANAGEMENT_DEVICE_COMPONENT_DESCRIPTION_DATA EFI_MISC_MANAGEMENT_DEVICE_COMPONENT_DESCRIPTION; /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It is implementation-specific to simplify the code logic. /// typedef union { EFI_MISC_LAST_PCI_BUS_DATA LastPciBus; EFI_MISC_BIOS_VENDOR_DATA MiscBiosVendor; EFI_MISC_SYSTEM_MANUFACTURER_DATA MiscSystemManufacturer; EFI_MISC_BASE_BOARD_MANUFACTURER_DATA MiscBaseBoardManufacturer; EFI_MISC_CHASSIS_MANUFACTURER_DATA MiscChassisManufacturer; EFI_MISC_PORT_INTERNAL_CONNECTOR_DESIGNATOR_DATA MiscPortInternalConnectorDesignator; EFI_MISC_SYSTEM_SLOT_DESIGNATION_DATA MiscSystemSlotDesignation; EFI_MISC_ONBOARD_DEVICE_DATA MiscOnboardDevice; EFI_MISC_OEM_STRING_DATA MiscOemString; EFI_MISC_SYSTEM_OPTION_STRING_DATA MiscOptionString; EFI_MISC_NUMBER_OF_INSTALLABLE_LANGUAGES_DATA NumberOfInstallableLanguages; EFI_MISC_SYSTEM_LANGUAGE_STRING_DATA MiscSystemLanguageString; EFI_MISC_SYSTEM_EVENT_LOG_DATA MiscSystemEventLog; EFI_MISC_GROUP_NAME_DATA MiscGroupNameData; EFI_MISC_GROUP_ITEM_SET_DATA MiscGroupItemSetData; EFI_MISC_POINTING_DEVICE_TYPE_DATA MiscPointingDeviceTypeData; EFI_MISC_RESET_CAPABILITIES_DATA MiscResetCapablilitiesData; EFI_MISC_HARDWARE_SECURITY_SETTINGS_DATA MiscHardwareSecuritySettingsData; EFI_MISC_SCHEDULED_POWER_ON_MONTH_DATA MiscScheduledPowerOnMonthData; EFI_MISC_VOLTAGE_PROBE_DESCRIPTION_DATA MiscVoltagePorbeDescriptionData; EFI_MISC_COOLING_DEVICE_TEMP_LINK_DATA MiscCoolingDeviceTempLinkData; EFI_MISC_TEMPERATURE_PROBE_DESCRIPTION_DATA MiscTemperatureProbeDescriptionData; EFI_MISC_ELECTRICAL_CURRENT_PROBE_DESCRIPTION_DATA MiscElectricalCurrentProbeDescriptionData; EFI_MISC_REMOTE_ACCESS_MANUFACTURER_DESCRIPTION_DATA MiscRemoteAccessManufacturerDescriptionData; EFI_MISC_BIS_ENTRY_POINT_DATA MiscBisEntryPoint; EFI_MISC_BOOT_INFORMATION_STATUS_DATA MiscBootInformationStatus; EFI_MISC_MANAGEMENT_DEVICE_DESCRIPTION_DATA MiscMangementDeviceDescriptionData; EFI_MISC_MANAGEMENT_DEVICE_COMPONENT_DESCRIPTION_DATA MiscmangementDeviceComponentDescriptionData; EFI_MISC_IPMI_INTERFACE_TYPE_DATA MiscIpmiInterfaceTypeData; EFI_MISC_SYSTEM_POWER_SUPPLY_DATA MiscPowerSupplyInfo; EFI_MISC_SMBIOS_STRUCT_ENCAPSULATION_DATA MiscSmbiosStructEncapsulation; EFI_MISC_MANAGEMENT_DEVICE_THRESHOLD MiscManagementDeviceThreshold; } EFI_MISC_SUBCLASS_RECORDS; /// /// Inconsistent with specification here: /// In MemSubclass specification 0.9, the following data structures are NOT defined. /// It is implementation-specific to simplify the code logic. /// typedef struct { EFI_SUBCLASS_TYPE1_HEADER Header; EFI_MISC_SUBCLASS_RECORDS Record; } EFI_MISC_SUBCLASS_DRIVER_DATA; #pragma pack() /// /// Inconsistent with specification here: /// In DataHubSubclass specification 0.9 page 16, the following symbol is NOT defined. /// But value is meaningful, 0 means Reserved. /// #define EFI_SUBCLASS_INSTANCE_RESERVED 0 /// /// Inconsistent with specification here: /// In DataHubSubclass specification 0.9 page 16, the following symbol is NOT defined. /// But value is meaningful, -1 means Not Applicable. /// #define EFI_SUBCLASS_INSTANCE_NON_APPLICABLE 0xFFFF #endif
d0542cbfa998a96709fab5ef7660445eebd24dbc
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/yichip/yc3121-pos/Libraries/core/system.c
99b3f8b928a3b1bd88f4de02c75fcc779919e8d0
[ "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
6,227
c
system.c
/* File Name : system.c Author : Yichip Version : V1.0 Date : 2019/12/4 Description : none. */ #include <stdarg.h> #include "system.h" //***************************************************************************** // //! A simple MyPrintf function supporting \%c, \%d, \%p, \%s, \%u,\%x, and \%X. //! //! \param format is the format string. //! \param ... are the optional arguments, which depend on the contents of the //! \return None. // //***************************************************************************** static const int8_t *const g_pcHex1 = "0123456789abcdef"; static const int8_t *const g_pcHex2 = "0123456789ABCDEF"; void printfsend(UART_TypeDef UARTx, uint8_t *buf, int len) { uint8_t printbuf[256]; for (int i = 0; i < len; i++) { printbuf[i] = buf[i]; } UART_SendBuf(UARTx, printbuf, len); } void MyPrintf(char *format, ...) { uint32_t ulIdx, ulValue, ulPos, ulCount, ulBase, ulNeg; int8_t *pcStr, pcBuf[16], cFill; char HexFormat; va_list vaArgP; va_start(vaArgP, format); while (*format) { // Find the first non-% character, or the end of the string. for (ulIdx = 0; (format[ulIdx] != '%') && (format[ulIdx] != '\0'); ulIdx++) { } // Write this portion of the string. if (ulIdx > 0) { printfsend(UART0, (uint8_t *)format, ulIdx); } format += ulIdx; if (*format == '%') { format++; // Set the digit count to zero, and the fill character to space // (i.e. to the defaults). ulCount = 0; cFill = ' '; again: switch (*format++) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { if ((format[-1] == '0') && (ulCount == 0)) { cFill = '0'; } ulCount *= 10; ulCount += format[-1] - '0'; goto again; } case 'c': { ulValue = va_arg(vaArgP, unsigned long); printfsend(UART0, (uint8_t *)&ulValue, 1); break; } case 'd': { ulValue = va_arg(vaArgP, unsigned long); ulPos = 0; if ((long)ulValue < 0) { ulValue = -(long)ulValue; ulNeg = 1; } else { ulNeg = 0; } ulBase = 10; goto convert; } case 's': { pcStr = (int8_t *)va_arg(vaArgP, char *); for (ulIdx = 0; pcStr[ulIdx] != '\0'; ulIdx++) { } printfsend(UART0, (uint8_t *)pcStr, ulIdx); if (ulCount > ulIdx) { ulCount -= ulIdx; while (ulCount--) { printfsend(UART0, (uint8_t *)" ", 1); } } break; } case 'u': { ulValue = va_arg(vaArgP, unsigned long); ulPos = 0; ulBase = 10; ulNeg = 0; goto convert; } case 'X': { ulValue = va_arg(vaArgP, unsigned long); ulPos = 0; ulBase = 16; ulNeg = 0; HexFormat = 'X'; goto convert; } case 'x': case 'p': { ulValue = va_arg(vaArgP, unsigned long); ulPos = 0; ulBase = 16; ulNeg = 0; HexFormat = 'x'; convert: for (ulIdx = 1; (((ulIdx * ulBase) <= ulValue) && (((ulIdx * ulBase) / ulBase) == ulIdx)); ulIdx *= ulBase, ulCount--) { } if (ulNeg) { ulCount--; } if (ulNeg && (cFill == '0')) { pcBuf[ulPos++] = '-'; ulNeg = 0; } if ((ulCount > 1) && (ulCount < 16)) { for (ulCount--; ulCount; ulCount--) { pcBuf[ulPos++] = cFill; } } if (ulNeg) { pcBuf[ulPos++] = '-'; } for (; ulIdx; ulIdx /= ulBase) { if (HexFormat == 'x') pcBuf[ulPos++] = g_pcHex1[(ulValue / ulIdx) % ulBase]; //x else pcBuf[ulPos++] = g_pcHex2[(ulValue / ulIdx) % ulBase]; //X } printfsend(UART0, (uint8_t *)pcBuf, ulPos); break; } case '%': { printfsend(UART0, (uint8_t *)format - 1, 1); break; } default: { printfsend(UART0, (uint8_t *)"ERROR", 5); break; } } //switch } //if } //while va_end(vaArgP); } void printv(uint8_t *buf, uint32_t len, uint8_t *s) { uint32_t i = 0; uint32_t n = 0; MyPrintf("\r\n %s:", s); for (i = 0; i < len; i++) { if (i % 16 == 0) { MyPrintf("\r\n%08x:", n); n += 16; } MyPrintf("%02x ", buf[i]); } } void _assert_handler(const char *file, int line, const char *func) { #if defined(SDK_DEBUG) MyPrintf("Assert trigger at file: %s line:%d func: %s\n ", file, line, func); #endif while (1); }
b47e42250b00f85c666f45ad09912e2ce166502e
d169de4c5c6b281984df35536430dcc931a957a9
/source/component/usb/host/class/DL1x5/vsf_usbh_dl1x5.c
433df0e6c1463c1a251b07f89fdfabfcc457ed60
[ "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
31,558
c
vsf_usbh_dl1x5.c
/***************************************************************************** * Copyright(C)2009-2022 by VSF Team * * * * 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. * * * ****************************************************************************/ /*============================ INCLUDES ======================================*/ #include "component/usb/vsf_usb_cfg.h" #if VSF_USE_USB_HOST == ENABLED && VSF_USBH_USE_DL1X5 == ENABLED #define __VSF_EDA_CLASS_INHERIT__ #define __VSF_USBH_CLASS_IMPLEMENT_CLASS__ #if VSF_USE_UI == ENABLED && VSF_DISP_USE_DL1X5 == ENABLED # define __VSF_DISP_CLASS_INHERIT__ # define __VSF_DL1X5_USE_DISP #endif #include "../../vsf_usbh.h" #include "./vsf_usbh_dl1x5.h" // for vsf_trace #include "service/vsf_service.h" #include "kernel/vsf_kernel.h" #ifdef __VSF_DL1X5_USE_DISP // for vsf_disp # include "component/vsf_component.h" #endif /*============================ MACROS ========================================*/ #define DL1X5_PIXELS_IN_CMD 256 #if VSF_KERNEL_CFG_EDA_SUPPORT_ON_TERMINATE != ENABLED # error "VSF_KERNEL_CFG_EDA_SUPPORT_ON_TERMINATE is required" #endif #ifndef VSF_USBH_DL1X5_CFG_CLS # define VSF_USBH_DL1X5_CFG_CLS ENABLED #endif #ifndef VSF_USBH_DL1X5_CFG_READ_EDID # define VSF_USBH_DL1X5_CFG_READ_EDID ENABLED #endif #ifndef VSF_USBH_DL1X5_CFG_CMD_BUFFER_SIZE // use minimal buffer size for single maximal write_raw16 command # define VSF_USBH_DL1X5_CFG_CMD_BUFFER_SIZE (6 + 2 * DL1X5_PIXELS_IN_CMD) #endif #if VSF_USBH_DL1X5_CFG_CMD_BUFFER_SIZE < 146 # error VSF_USBH_DL1X5_CFG_CMD_BUFFER_SIZE MUST be larger than max channel seq #endif /*============================ MACROFIED FUNCTIONS ===========================*/ /*============================ TYPES =========================================*/ typedef enum dl1x5_cmd_t { DL1X5_CMD_WRITE_VREG = 0x20, DL1X5_CMD_WRITE_RAW8 = 0x60, DL1X5_CMD_WRITE_RL8 = 0x61, DL1X5_CMD_COPY8 = 0x62, DL1X5_CMD_WRITE_RAW16 = 0x68, DL1X5_CMD_WRITE_RL16 = 0x69, DL1X5_CMD_COPY16 = 0x6A, DL1X5_CMD_NULL = 0xA0, } dl1x5_cmd_t; typedef enum usb_dl1x5_req_t { USB_DL1X5_REQ_READ_EDID = 0x02, USB_DL1X5_REQ_GET_STATUS = 0x06, USB_DL1X5_REQ_SET_CHANNEL = 0x12, } usb_dl1x5_req_t; typedef struct vk_usbh_dl1x5_t { vk_usbh_t *usbh; vk_usbh_dev_t *dev; vk_usbh_ifs_t *ifs; vk_usbh_urb_t urb_out; enum { DL1X5_STATE_IDLE, DL1X5_STATE_GET_STATUS, DL1X5_STATE_READ_EDID, DL1X5_STATE_SET_STD_CHANNEL, DL1X5_STATE_SET_MODE, DL1X5_STATE_CLS, DL1X5_STATE_CLS_LAST, DL1X5_STATE_RUNNING, } state; bool is_busy; #if VSF_USBH_DL1X5_CFG_CLS == ENABLED uint32_t pixel_addr; #endif vga_timing_t timing; uint32_t cmd_pos; // add 2 more bytes for DL1X5_CMD_NULL uint8_t cmd_buf[VSF_USBH_DL1X5_CFG_CMD_BUFFER_SIZE + 2]; vk_usbh_dl1x5_callback_t callback; #if VSF_USBH_DL1X5_CFG_READ_EDID == ENABLED vsf_teda_t task; #else vsf_eda_t task; #endif #ifdef __VSF_DL1X5_USE_DISP implement(vk_disp_t) vk_disp_area_t disp_area; uint16_t *disp_buff_rgb565; uint32_t disp_pixel_pos; #endif } vk_usbh_dl1x5_t; /*============================ PROTOTYPES ====================================*/ static void *__vk_usbh_dl1x5_probe(vk_usbh_t *usbh, vk_usbh_dev_t *dev, vk_usbh_ifs_parser_t *parser_ifs); static void __vk_usbh_dl1x5_disconnect(vk_usbh_t *usbh, vk_usbh_dev_t *dev, void *param); #if VSF_USBH_DL1X5_CFG_CLS == ENABLED static bool __vk_dl1x5_cls_callback(void *dev); #endif extern void vsf_dl1x5_on_new_dev(void *dev, edid_t *edid); extern vsf_err_t vk_usbh_dl1x5_commit(void *dev); #ifdef __VSF_DL1X5_USE_DISP extern void vsf_dl1x5_on_new_disp(vk_disp_t *disp); void vk_usbh_dl1x5_set_callback(void *dev, vk_usbh_dl1x5_callback_t callback); static void __vk_disp_dl1x5_refresh_callback(void *dev, vsf_err_t err); static vsf_err_t __vk_disp_dl1x5_refresh(vk_disp_t *pthis, vk_disp_area_t *area, void *disp_buff); #else extern void vsf_dl1x5_on_dev_ready(void *dev); #endif /*============================ LOCAL VARIABLES ===============================*/ static const vk_usbh_dev_id_t __vk_usbh_dl1x5_id[] = { { VSF_USBH_MATCH_VID_PID(0x17E9, 0x019E) }, { VSF_USBH_MATCH_VID_PID(0x17E9, 0x03CD) }, }; static const uint8_t __dl1x5_std_channel_seq[] = { 0x57, 0xCD, 0xDC, 0xA7, 0x1C, 0x88, 0x5E, 0x15, 0x60, 0xFE, 0xC6, 0x97, 0x16, 0x3D, 0x47, 0xF2, }; /*============================ GLOBAL VARIABLES ==============================*/ const vk_usbh_class_drv_t vk_usbh_dl1x5_drv = { .name = "dl1x5", .dev_id_num = dimof(__vk_usbh_dl1x5_id), .dev_ids = __vk_usbh_dl1x5_id, .probe = __vk_usbh_dl1x5_probe, .disconnect = __vk_usbh_dl1x5_disconnect, }; #ifdef __VSF_DL1X5_USE_DISP static const vk_disp_drv_t __vk_disp_drv_dl1x5 = { .refresh = __vk_disp_dl1x5_refresh, }; #endif /*============================ IMPLEMENTATION ================================*/ #ifndef WEAK_VSF_DL1X5_ON_NEW_DEV WEAK(vsf_dl1x5_on_new_dev) void vsf_dl1x5_on_new_dev(void *dev, edid_t *edid) { vga_timing_t *timing = vk_usbh_dl1x5_get_timing(dev); if (!timing->pixel_clock_10khz) { // use default 800X600 @ 60Hz timing timing->pixel_clock_10khz = 4000; timing->h.active = 800; timing->h.front_porch = 40; timing->h.sync = 128; timing->h.back_porch = 88; timing->h.sync_positive = 0; timing->v.active = 600; timing->v.front_porch = 1; timing->v.sync = 4; timing->v.back_porch = 23; timing->v.sync_positive = 0; } } #endif #ifdef __VSF_DL1X5_USE_DISP # ifndef WEAK_VSF_DL1X5_ON_NEW_DISP WEAK(vsf_dl1x5_on_new_disp) void vsf_dl1x5_on_new_disp(vk_disp_t *disp) {} # endif #else # ifndef WEAK_VSF_DL1X5_ON_DEV_READY WEAK(vsf_dl1x5_on_dev_ready) void vsf_dl1x5_on_dev_ready(void *dev) {} # endif #endif static vsf_err_t __vk_usbh_dl1x5_get_status(vk_usbh_dl1x5_t *dl1x5) { VSF_USB_ASSERT((dl1x5 != NULL) && (dl1x5->usbh != NULL) && (dl1x5->dev != NULL)); struct usb_ctrlrequest_t req = { .bRequestType = USB_TYPE_VENDOR | USB_DIR_IN, .bRequest = USB_DL1X5_REQ_GET_STATUS, .wValue = 0, .wIndex = 0, .wLength = 4, }; vk_usbh_urb_set_buffer(&dl1x5->dev->ep0.urb, &dl1x5->cmd_buf, 4); return vk_usbh_control_msg(dl1x5->usbh, dl1x5->dev, &req); } #if VSF_USBH_DL1X5_CFG_READ_EDID == ENABLED static vsf_err_t __vk_usbh_dl1x5_read_edid(vk_usbh_dl1x5_t *dl1x5) { VSF_USB_ASSERT((dl1x5 != NULL) && (dl1x5->usbh != NULL) && (dl1x5->dev != NULL)); struct usb_ctrlrequest_t req = { .bRequestType = USB_TYPE_VENDOR | USB_DIR_IN, .bRequest = USB_DL1X5_REQ_READ_EDID, .wValue = 0, .wIndex = 0xA1, .wLength = 1 + 128, }; vk_usbh_urb_set_buffer(&dl1x5->dev->ep0.urb, &dl1x5->cmd_buf, 1 + 128); return vk_usbh_control_msg(dl1x5->usbh, dl1x5->dev, &req); } static bool __vga_parse_edid(edid_t *edid, vga_timing_t *timing) { const uint8_t edid_header[8] = { 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, }; uint8_t checksum = 0, *edid_buf = (uint8_t *)edid; if (memcmp(edid->header, edid_header, sizeof(edid_header))) { vsf_trace_debug("DL1X5: edid : false header" VSF_TRACE_CFG_LINEEND); return false; } for (uint_fast8_t i = 0; i < sizeof(*edid); i++) { checksum += edid_buf[i]; } if (checksum != 0) { vsf_trace_debug("DL1X5: edid : false checksum" VSF_TRACE_CFG_LINEEND); return false; } vsf_trace_debug("DL1X5: edid:" VSF_TRACE_CFG_LINEEND); vsf_trace_buffer(VSF_TRACE_DEBUG, edid, 128); vsf_trace_debug("DL1X5: edid: manufacturer = 0x%04X, product = 0x%04X, serial = 0x%08X" VSF_TRACE_CFG_LINEEND, edid->product.manufacturer, edid->product.product, edid->product.serial); vsf_trace_debug("DL1X5: edid: produced at year %d week %d" VSF_TRACE_CFG_LINEEND, 1990 + edid->product.year, edid->product.week); vsf_trace_debug("DL1X5: edid: version = %d, revision = %d" VSF_TRACE_CFG_LINEEND, edid->version.version, edid->version.revision); vsf_trace_debug("DL1X5: established_timings = 0x%08X" VSF_TRACE_CFG_LINEEND, edid->established_timings.timings + ((uint32_t)edid->established_timings.reserved_timings << 8)); struct edid_detailed_timing_t *detailed_timing = &edid->detailed_timings[0]; uint16_t blanking; if (!detailed_timing->pixel_clock_10khz) { vsf_trace_debug("DL1X5: user should provide the timings" VSF_TRACE_CFG_LINEEND); return true; } timing->pixel_clock_10khz = detailed_timing->pixel_clock_10khz; timing->h.active = detailed_timing->h_active_low + (detailed_timing->h_active_high << 8); blanking = detailed_timing->h_blanking_low + (detailed_timing->h_blanking_high << 8); timing->h.front_porch = detailed_timing->h_sync_offset_low + (detailed_timing->h_sync_offset_high << 8); timing->h.sync = detailed_timing->h_sync_width_low + (detailed_timing->h_sync_width_high << 8); timing->h.back_porch = blanking - timing->h.front_porch - timing->h.sync; if (blanking < (timing->h.front_porch + timing->h.sync)) { vsf_trace_debug("DL1X5: invalid detailed timing" VSF_TRACE_CFG_LINEEND); timing->pixel_clock_10khz = 0; return true; } timing->h.sync_positive = detailed_timing->h_sync_positive; timing->v.active = detailed_timing->v_active_low + (detailed_timing->v_active_high << 8); blanking = detailed_timing->v_blanking_low + (detailed_timing->v_blanking_high << 8); timing->v.front_porch = detailed_timing->v_sync_offset_low + (detailed_timing->v_sync_offset_high << 8); timing->v.sync = detailed_timing->v_sync_width_low + (detailed_timing->v_sync_width_high << 8); timing->v.back_porch = blanking - timing->v.front_porch - timing->v.sync; if (blanking < (timing->v.front_porch + timing->v.sync)) { vsf_trace_debug("DL1X5: invalid detailed timing" VSF_TRACE_CFG_LINEEND); timing->pixel_clock_10khz = 0; return true; } timing->v.sync_positive = detailed_timing->v_sync_positive; return true; } #endif static vsf_err_t __vk_usbh_dl1x5_set_channel(vk_usbh_dl1x5_t *dl1x5, const char *seq, uint8_t size) { VSF_USB_ASSERT((dl1x5 != NULL) && (dl1x5->usbh != NULL) && (dl1x5->dev != NULL)); struct usb_ctrlrequest_t req = { .bRequestType = USB_TYPE_VENDOR | USB_DIR_OUT, .bRequest = USB_DL1X5_REQ_SET_CHANNEL, .wValue = 0, .wIndex = 0, .wLength = size, }; memcpy(dl1x5->cmd_buf, seq, size); vk_usbh_urb_set_buffer(&dl1x5->dev->ep0.urb, &dl1x5->cmd_buf, size); return vk_usbh_control_msg(dl1x5->usbh, dl1x5->dev, &req); } static void __vk_usbh_dl1x5_on_eda_terminate(vsf_eda_t *eda) { vk_usbh_dl1x5_t *dl1x5 = container_of(eda, vk_usbh_dl1x5_t, task); vsf_usbh_free(dl1x5); } static void __dl1x5_write_vcmd(vk_usbh_dl1x5_t *dl1x5, uint_fast8_t cmd) { dl1x5->cmd_buf[dl1x5->cmd_pos++] = 0xAF; dl1x5->cmd_buf[dl1x5->cmd_pos++] = cmd; } static void __dl1x5_write_vreg(vk_usbh_dl1x5_t *dl1x5, uint_fast8_t reg, uint_fast8_t val) { __dl1x5_write_vcmd(dl1x5, DL1X5_CMD_WRITE_VREG); dl1x5->cmd_buf[dl1x5->cmd_pos++] = reg; dl1x5->cmd_buf[dl1x5->cmd_pos++] = val; } static void __dl1x5_write_vreg_be16(vk_usbh_dl1x5_t *dl1x5, uint_fast8_t reg, uint_fast16_t val) { val = cpu_to_be16(val); __dl1x5_write_vreg(dl1x5, reg, val & 0xFF); __dl1x5_write_vreg(dl1x5, reg + 1, val >> 8); } static void __dl1x5_write_vreg_le16(vk_usbh_dl1x5_t *dl1x5, uint_fast8_t reg, uint_fast16_t val) { #if __IS_COMPILER_LLVM__ # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wself-assign" #endif val = cpu_to_le16(val); #if __IS_COMPILER_LLVM__ # pragma clang diagnostic pop #endif __dl1x5_write_vreg(dl1x5, reg, val & 0xFF); __dl1x5_write_vreg(dl1x5, reg + 1, val >> 8); } static bool __dl1x5_write_rl16(vk_usbh_dl1x5_t *dl1x5, uint_fast32_t gram_addr, uint_fast16_t pixel_num, uint16_t color_rgb565) { VSF_USB_ASSERT(pixel_num <= DL1X5_PIXELS_IN_CMD); if (DL1X5_PIXELS_IN_CMD == pixel_num) { pixel_num = 0; } if (dl1x5->cmd_pos > VSF_USBH_DL1X5_CFG_CMD_BUFFER_SIZE - 9) { return false; } __dl1x5_write_vcmd(dl1x5, DL1X5_CMD_WRITE_RL16); dl1x5->cmd_buf[dl1x5->cmd_pos++] = gram_addr >> 16; dl1x5->cmd_buf[dl1x5->cmd_pos++] = gram_addr >> 8; dl1x5->cmd_buf[dl1x5->cmd_pos++] = gram_addr >> 0; dl1x5->cmd_buf[dl1x5->cmd_pos++] = pixel_num; dl1x5->cmd_buf[dl1x5->cmd_pos++] = pixel_num; dl1x5->cmd_buf[dl1x5->cmd_pos++] = color_rgb565 >> 8; dl1x5->cmd_buf[dl1x5->cmd_pos++] = color_rgb565 >> 0; return true; } static bool __dl1x5_write_raw16(vk_usbh_dl1x5_t *dl1x5, uint_fast32_t gram_addr, uint_fast16_t pixel_num, uint16_t *color_rgb565_ptr) { VSF_USB_ASSERT(pixel_num <= DL1X5_PIXELS_IN_CMD); if (dl1x5->cmd_pos > (VSF_USBH_DL1X5_CFG_CMD_BUFFER_SIZE - (6 + (pixel_num << 1)))) { return false; } __dl1x5_write_vcmd(dl1x5, DL1X5_CMD_WRITE_RAW16); dl1x5->cmd_buf[dl1x5->cmd_pos++] = gram_addr >> 16; dl1x5->cmd_buf[dl1x5->cmd_pos++] = gram_addr >> 8; dl1x5->cmd_buf[dl1x5->cmd_pos++] = gram_addr >> 0; dl1x5->cmd_buf[dl1x5->cmd_pos++] = pixel_num == DL1X5_PIXELS_IN_CMD ? 0 : pixel_num; for (uint_fast16_t i = 0; i < pixel_num; i++) { dl1x5->cmd_buf[dl1x5->cmd_pos++] = color_rgb565_ptr[i] >> 8; dl1x5->cmd_buf[dl1x5->cmd_pos++] = color_rgb565_ptr[i] >> 0; } return true; } static uint16_t __dl1x5_lfsr16(uint16_t val) { uint32_t result = 0xFFFF; while (val--) { result = ((result << 1) | (((result >> 15) ^ (result >> 4) ^ (result >> 2) ^ (result >> 1)) & 1)) & 0xFFFF; } return (uint16_t)result; } static void __vk_usbh_dl1x5_evthandler(vsf_eda_t *eda, vsf_evt_t evt) { vk_usbh_dl1x5_t *dl1x5 = container_of(eda, vk_usbh_dl1x5_t, task); vk_usbh_dev_t *dev = dl1x5->dev; switch (evt) { case VSF_EVT_INIT: if (VSF_ERR_NONE != __vsf_eda_crit_npb_enter(&dev->ep0.crit)) { break; } // fall through case VSF_EVT_SYNC: __vk_usbh_dl1x5_get_status(dl1x5); dl1x5->state = DL1X5_STATE_GET_STATUS; break; case VSF_EVT_MESSAGE: { vk_usbh_urb_t urb = { .urb_hcd = vsf_eda_get_cur_msg() }; vk_usbh_pipe_t pipe = vk_usbh_urb_get_pipe(&urb); int_fast16_t status = vk_usbh_urb_get_status(&urb); // uint_fast32_t actlen = vk_usbh_urb_get_actual_length(&urb); if (status != URB_OK) { vsf_trace_error("DL1X5: urb failed" VSF_TRACE_CFG_LINEEND); if (dl1x5->callback != NULL) { dl1x5->callback(dl1x5, VSF_ERR_FAIL); } vk_usbh_remove_interface(dl1x5->usbh, dev, dl1x5->ifs); break; } if (0 == pipe.endpoint) { switch (dl1x5->state) { case DL1X5_STATE_GET_STATUS: vsf_trace_debug("DL1X5: status = 0x%08X" VSF_TRACE_CFG_LINEEND, get_unaligned_le32(dl1x5->cmd_buf)); #if VSF_USBH_DL1X5_CFG_READ_EDID == ENABLED __vk_usbh_dl1x5_read_edid(dl1x5); dl1x5->state = DL1X5_STATE_READ_EDID; break; case DL1X5_STATE_READ_EDID: if ( (dl1x5->cmd_buf[0] != 0) || !__vga_parse_edid((edid_t *)&dl1x5->cmd_buf[1], &dl1x5->timing)) { vsf_teda_set_timer_ms(1000); break; } vsf_dl1x5_on_new_dev(dl1x5, (edid_t *)&dl1x5->cmd_buf[1]); #else vsf_dl1x5_on_new_dev(dl1x5, NULL); #endif __vk_usbh_dl1x5_set_channel(dl1x5, (const char *)__dl1x5_std_channel_seq, sizeof(__dl1x5_std_channel_seq)); dl1x5->state = DL1X5_STATE_SET_STD_CHANNEL; break; case DL1X5_STATE_SET_STD_CHANNEL: { vga_timing_t *timing = &dl1x5->timing; if (0 == timing->pixel_clock_10khz) { // invalid timing vsf_trace_error("DL1X5: invalid timing" VSF_TRACE_CFG_LINEEND); break; } uint_fast16_t h_cycles = timing->h.active + timing->h.front_porch + timing->h.sync + timing->h.back_porch; uint_fast16_t v_cycles = timing->v.active + timing->v.front_porch + timing->v.sync + timing->v.back_porch; vsf_trace_debug("DL1X5: %dx%d @ %dHz" VSF_TRACE_CFG_LINEEND, timing->h.active, timing->v.active, timing->pixel_clock_10khz * 10000 / (v_cycles * h_cycles)); __dl1x5_write_vreg(dl1x5, 0xFF, 0x00); // vreg_lock __dl1x5_write_vreg(dl1x5, 0x20, 0); // base16_16_23 __dl1x5_write_vreg(dl1x5, 0x21, 0); // base16_8_15 __dl1x5_write_vreg(dl1x5, 0x22, 0); // base16_0_7 __dl1x5_write_vreg(dl1x5, 0x26, 0); // base8_16_23 __dl1x5_write_vreg(dl1x5, 0x27, 0); // base8_8_15 __dl1x5_write_vreg(dl1x5, 0x28, 0); // base8_0_7 // counter registers with lfsr16 encoded uint16_t v_sync_start = 0; uint16_t v_sync_end = timing->v.sync; uint16_t v_display_start = v_sync_end + timing->v.back_porch; uint16_t v_display_end = v_display_start + timing->v.active; uint16_t v_end_count = v_display_end + timing->v.front_porch; uint16_t h_sync_start = 1; uint16_t h_sync_end = timing->h.sync + 1; uint16_t h_display_start = h_sync_end + timing->h.back_porch - 1; uint16_t h_display_end = h_display_start + timing->h.active; uint16_t h_end_count = h_display_end + timing->h.front_porch - 1; uint16_t h_pixels = timing->h.active; uint16_t v_pixels = timing->v.active; uint16_t pixel_clock_5khz = timing->pixel_clock_10khz << 1; if (!(timing->h.sync_positive)) { h_sync_start = h_sync_start ^ h_sync_end; h_sync_end = h_sync_start ^ h_sync_end; h_sync_start = h_sync_start ^ h_sync_end; } if (!(timing->v.sync_positive)) { v_sync_start = v_sync_start ^ v_sync_end; v_sync_end = v_sync_start ^ v_sync_end; v_sync_start = v_sync_start ^ v_sync_end; } // color depth, 0: 16, 1: 24 __dl1x5_write_vreg(dl1x5, 0x00, 0); __dl1x5_write_vreg_be16(dl1x5, 0x01, __dl1x5_lfsr16(h_display_start)); __dl1x5_write_vreg_be16(dl1x5, 0x03, __dl1x5_lfsr16(h_display_end)); __dl1x5_write_vreg_be16(dl1x5, 0x05, __dl1x5_lfsr16(v_display_start)); __dl1x5_write_vreg_be16(dl1x5, 0x07, __dl1x5_lfsr16(v_display_end)); __dl1x5_write_vreg_be16(dl1x5, 0x09, __dl1x5_lfsr16(h_end_count)); __dl1x5_write_vreg_be16(dl1x5, 0x0B, __dl1x5_lfsr16(h_sync_start)); __dl1x5_write_vreg_be16(dl1x5, 0x0D, __dl1x5_lfsr16(h_sync_end)); __dl1x5_write_vreg_be16(dl1x5, 0x0F, h_pixels); __dl1x5_write_vreg_be16(dl1x5, 0x11, __dl1x5_lfsr16(v_end_count)); __dl1x5_write_vreg_be16(dl1x5, 0x13, __dl1x5_lfsr16(v_sync_start)); __dl1x5_write_vreg_be16(dl1x5, 0x15, __dl1x5_lfsr16(v_sync_end)); __dl1x5_write_vreg_be16(dl1x5, 0x17, v_pixels); __dl1x5_write_vreg_le16(dl1x5, 0x1B, pixel_clock_5khz); // enable hsync, vsync, video __dl1x5_write_vreg(dl1x5, 0x1F, 0); // flush register __dl1x5_write_vreg(dl1x5, 0xFF, 0xFF); dl1x5->state = DL1X5_STATE_SET_MODE; vk_usbh_dl1x5_commit(dl1x5); } break; } } else { dl1x5->is_busy = false; dl1x5->cmd_pos = 0; switch (dl1x5->state) { case DL1X5_STATE_SET_MODE: #if VSF_USBH_DL1X5_CFG_CLS == ENABLED dl1x5->state = DL1X5_STATE_CLS; dl1x5->pixel_addr = 0; // fall through case DL1X5_STATE_CLS: if (__vk_dl1x5_cls_callback(dl1x5)) { if (dl1x5->cmd_pos > 0) { dl1x5->state = DL1X5_STATE_CLS_LAST; vk_usbh_dl1x5_commit(dl1x5); break; } goto __DL1X5_STATE_CLS_LAST; } break; case DL1X5_STATE_CLS_LAST: __DL1X5_STATE_CLS_LAST: #endif dl1x5->state = DL1X5_STATE_RUNNING; #ifdef __VSF_DL1X5_USE_DISP vk_usbh_dl1x5_set_callback(dl1x5, __vk_disp_dl1x5_refresh_callback); { vk_disp_param_t *param = (vk_disp_param_t *)&dl1x5->param; param->drv = &__vk_disp_drv_dl1x5; param->width = dl1x5->timing.h.active; param->height = dl1x5->timing.v.active; param->color = VSF_DISP_COLOR_RGB565; } vsf_dl1x5_on_new_disp(&dl1x5->use_as__vk_disp_t); #else vsf_dl1x5_on_dev_ready(dl1x5); #endif break; case DL1X5_STATE_RUNNING: if (dl1x5->callback != NULL) { dl1x5->callback(dl1x5, VSF_ERR_NONE); } break; } } } break; #if VSF_USBH_DL1X5_CFG_READ_EDID == ENABLED case VSF_EVT_TIMER: switch (dl1x5->state) { case DL1X5_STATE_READ_EDID: __vk_usbh_dl1x5_read_edid(dl1x5); break; } break; #endif } } static void *__vk_usbh_dl1x5_probe(vk_usbh_t *usbh, vk_usbh_dev_t *dev, vk_usbh_ifs_parser_t *parser_ifs) { vk_usbh_ifs_t *ifs = parser_ifs->ifs; vk_usbh_ifs_alt_parser_t *parser_alt = &parser_ifs->parser_alt[ifs->cur_alt]; struct usb_interface_desc_t *desc_ifs = parser_alt->desc_ifs; struct usb_endpoint_desc_t *desc_ep = parser_alt->desc_ep; vk_usbh_dl1x5_t *dl1x5 = vsf_usbh_malloc(sizeof(vk_usbh_dl1x5_t)); if (dl1x5 == NULL) { return NULL; } memset(dl1x5, 0, sizeof(vk_usbh_dl1x5_t)); for (int i = 0; i < desc_ifs->bNumEndpoints; i++) { if (desc_ep->bEndpointAddress == (USB_DIR_OUT | 1)) { vk_usbh_urb_prepare(&dl1x5->urb_out, dev, desc_ep); vk_usbh_alloc_urb(usbh, dev, &dl1x5->urb_out); break; } desc_ep = vk_usbh_get_next_ep_descriptor(desc_ep, parser_alt->desc_size - ((uintptr_t)desc_ep - (uintptr_t)desc_ifs)); } if (desc_ep->bEndpointAddress != (USB_DIR_OUT | 1)) { vsf_usbh_free(dl1x5); return NULL; } dl1x5->usbh = usbh; dl1x5->dev = dev; dl1x5->ifs = ifs; dl1x5->task.fn.evthandler = __vk_usbh_dl1x5_evthandler; dl1x5->task.on_terminate = __vk_usbh_dl1x5_on_eda_terminate; #if VSF_USBH_DL1X5_CFG_READ_EDID == ENABLED # ifdef VSF_USBH_DL1X5_CFG_PRIORITY vsf_teda_init(&dl1x5->task, VSF_USBH_DL1X5_CFG_PRIORITY); # else vsf_teda_init(&dl1x5->task); # endif #else # ifdef VSF_USBH_DL1X5_CFG_PRIORITY vsf_eda_init(&dl1x5->task, VSF_USBH_DL1X5_CFG_PRIORITY); # else vsf_eda_init(&dl1x5->task); # endif #endif #if VSF_KERNEL_CFG_TRACE == ENABLED vsf_kernel_trace_eda_info((vsf_eda_t *)&dl1x5->task, "usbh_dl1x5_task", NULL, 0); #endif return dl1x5; } static void __vk_usbh_dl1x5_disconnect(vk_usbh_t *usbh, vk_usbh_dev_t *dev, void *param) { vk_usbh_dl1x5_t *dl1x5 = (vk_usbh_dl1x5_t *)param; VSF_USB_ASSERT(dl1x5 != NULL); vk_usbh_free_urb(usbh, &dl1x5->urb_out); vsf_eda_fini((vsf_eda_t *)&dl1x5->task); } vga_timing_t * vk_usbh_dl1x5_get_timing(void *dev) { vk_usbh_dl1x5_t *dl1x5 = (vk_usbh_dl1x5_t *)dev; return &dl1x5->timing; } void vk_usbh_dl1x5_set_callback(void *dev, vk_usbh_dl1x5_callback_t callback) { vk_usbh_dl1x5_t *dl1x5 = (vk_usbh_dl1x5_t *)dev; dl1x5->callback = callback; } vsf_err_t vk_usbh_dl1x5_commit(void *dev) { vk_usbh_dl1x5_t *dl1x5 = (vk_usbh_dl1x5_t *)dev; if (!dl1x5->cmd_pos) { return VSF_ERR_NOT_READY; } dl1x5->is_busy = true; __dl1x5_write_vcmd(dl1x5, DL1X5_CMD_NULL); vk_usbh_urb_set_buffer(&dl1x5->urb_out, &dl1x5->cmd_buf, dl1x5->cmd_pos); return vk_usbh_submit_urb_ex(dl1x5->usbh, &dl1x5->urb_out, 0, (vsf_eda_t *)&dl1x5->task); } bool vk_usbh_dl1x5_fill_color(void *dev, uint_fast32_t gram_pixel_addr, uint_fast16_t pixel_num, uint16_t color_rgb565) { vk_usbh_dl1x5_t *dl1x5 = (vk_usbh_dl1x5_t *)dev; VSF_USB_ASSERT(!dl1x5->is_busy); return __dl1x5_write_rl16(dl1x5, gram_pixel_addr << 1, pixel_num, color_rgb565); } bool vk_usbh_dl1x5_fill_buf(void *dev, uint_fast32_t gram_pixel_addr, uint_fast16_t pixel_num, uint16_t *color_rgb565_ptr) { vk_usbh_dl1x5_t *dl1x5 = (vk_usbh_dl1x5_t *)dev; VSF_USB_ASSERT(!dl1x5->is_busy); return __dl1x5_write_raw16(dl1x5, gram_pixel_addr << 1, pixel_num, color_rgb565_ptr); } #if VSF_USBH_DL1X5_CFG_CLS == ENABLED static bool __vk_dl1x5_cls_callback(void *dev) { vk_usbh_dl1x5_t *dl1x5 = (vk_usbh_dl1x5_t *)dev; vga_timing_t *timing = vk_usbh_dl1x5_get_timing(dev); while (dl1x5->pixel_addr < timing->h.active * timing->v.active) { if (!vk_usbh_dl1x5_fill_color(dev, dl1x5->pixel_addr, DL1X5_PIXELS_IN_CMD, 0)) { vsf_err_t err = vk_usbh_dl1x5_commit(dev); VSF_UNUSED_PARAM(err); VSF_USB_ASSERT(VSF_ERR_NONE == err); return false; } dl1x5->pixel_addr += DL1X5_PIXELS_IN_CMD; } return true; } #endif #ifdef __VSF_DL1X5_USE_DISP static void __vk_disp_dl1x5_refresh_callback(void *dev, vsf_err_t err) { vk_usbh_dl1x5_t *dl1x5 = (vk_usbh_dl1x5_t *)dev; if (VSF_ERR_NONE != err) { return; } if (dl1x5->disp_buff_rgb565 != NULL) { vk_disp_area_t *area = &dl1x5->disp_area; uint_fast32_t pixel_remain = area->size.x * area->size.y - dl1x5->disp_pixel_pos; uint_fast32_t pixel_line_offset, pixel_line_num; uint_fast32_t pixel_addr; uint_fast16_t pixel_num; while (pixel_remain > 0) { pixel_line_num = dl1x5->disp_pixel_pos / area->size.x; pixel_line_offset = dl1x5->disp_pixel_pos % area->size.x; pixel_addr = (area->pos.y + pixel_line_num) * dl1x5->timing.h.active + area->pos.x + pixel_line_offset; if (area->size.x == dl1x5->timing.h.active) { pixel_num = vsf_min(DL1X5_PIXELS_IN_CMD, pixel_remain); } else { pixel_line_offset = area->size.x - pixel_line_offset; pixel_num = vsf_min(DL1X5_PIXELS_IN_CMD, pixel_line_offset); } if (!vk_usbh_dl1x5_fill_buf(dev, pixel_addr, pixel_num, dl1x5->disp_buff_rgb565)) { vsf_err_t err = vk_usbh_dl1x5_commit(dev); VSF_UNUSED_PARAM(err); VSF_USB_ASSERT(VSF_ERR_NONE == err); return; } dl1x5->disp_pixel_pos += pixel_num; dl1x5->disp_buff_rgb565 += pixel_num; pixel_remain -= pixel_num; } dl1x5->disp_buff_rgb565 = NULL; if (VSF_ERR_NONE == vk_usbh_dl1x5_commit(dev)) { return; } } if (NULL == dl1x5->disp_buff_rgb565) { if (dl1x5->ui_on_ready != NULL) { dl1x5->ui_on_ready(&dl1x5->use_as__vk_disp_t); } } } static vsf_err_t __vk_disp_dl1x5_refresh(vk_disp_t *pthis, vk_disp_area_t *area, void *disp_buff) { vk_usbh_dl1x5_t *dl1x5 = container_of(pthis, vk_usbh_dl1x5_t, use_as__vk_disp_t); dl1x5->disp_area = *area; dl1x5->disp_buff_rgb565 = (uint16_t *)disp_buff; dl1x5->disp_pixel_pos = 0; __vk_disp_dl1x5_refresh_callback(dl1x5, VSF_ERR_NONE); return VSF_ERR_NONE; } #endif #endif
41bea15420b8a7112ad19075f94ee51654385900
50dd46b8ece33f3cdd174284b15d1d51f89669d4
/third_party/edk2/StdLib/Include/Arm/machine/signal.h
6628eb9e9403cdfaa34f2f11b80d54b1a1fe175f
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause", "OpenSSL" ]
permissive
google/google-ctf
f99da1ee07729bbccb869fff1cbaed6a80e43bcc
df02323eaf945d15e124801c74abaadca2749dc7
refs/heads/master
2023-08-31T14:30:27.548081
2023-08-29T13:04:20
2023-08-29T13:04:20
131,317,137
4,136
607
Apache-2.0
2023-08-30T22:17:02
2018-04-27T15:56:03
Go
UTF-8
C
false
false
833
h
signal.h
/** Copyright (c) 2010, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License that accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php. THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #ifndef _MACHINE_SIGNAL_H #define _MACHINE_SIGNAL_H #include <sys/EfiCdefs.h> /** The type sig_atomic_t is the (possibly volatile-qualified) integer type of an object that can be accessed as an atomic entity, even in the presence of asynchronous interrupts. **/ typedef INTN sig_atomic_t; #endif /* _MACHINE_SIGNAL_H */
5ac8fbffcadf91920e577c8b995c1f9193c14c6a
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/audio/volumeicon/files/patch-src_oss3__backend.c
95780cd9e35321bf0f0a240fb1dae760ad6d552a
[ "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
5,042
c
patch-src_oss3__backend.c
--- src/oss3_backend.c.orig 2017-12-18 17:23:45.225185000 +0100 +++ src/oss3_backend.c 2017-12-18 17:23:57.906175000 +0100 @@ -0,0 +1,185 @@ +// +// Copyright (c) 2011 Maato <maato@softwarebakery.com> +// Copyright (c) 2017 Dmitri Goutnik <dg@syrec.org> +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer +// in this position and unchanged. +// 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(S) ``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(S) 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 OSS_HEADER +#include <sys/soundcard.h> +#include <fcntl.h> +#include <assert.h> +#include <stdlib.h> +#include <stdio.h> +#include <glib.h> + +#include "oss_backend.h" + +static const char *channel_labels[SOUND_MIXER_NRDEVICES] = SOUND_DEVICE_NAMES; +static int m_mixer_fd = -1; +static GList *m_channel_names = NULL; +static char *m_channel; +static int m_channel_dev = 0; +static char *m_device = NULL; +static GList *m_device_names = NULL; + +void +oss_setup(const gchar *card, const gchar *channel, void (*volume_changed) (int, gboolean)) +{ + // Make sure (for now) that the setup function only gets called once + static int oss_setup_called = 0; + assert(oss_setup_called == 0); + oss_setup_called++; + + g_list_free_full(m_channel_names, g_free); + m_channel_names = NULL; + g_list_free_full(m_device_names, g_free); + m_device_names = NULL; + + g_free(m_device); + m_device = g_strdup(card); + m_device_names = g_list_append(m_device_names, g_strdup(m_device)); + + // Get ahold of the mixer device + char *devmixer; + if ((devmixer = getenv("OSS_MIXERDEV")) == NULL) + devmixer = "/dev/mixer"; + if ((m_mixer_fd = open(devmixer, O_RDWR)) == -1) { + perror("Cannot open mixer"); + exit(EXIT_FAILURE); + } + + // Query mixer devices + int devmask = 0; + if (ioctl(m_mixer_fd, SOUND_MIXER_READ_DEVMASK, &devmask) == -1) { + perror("Cannot query devices"); + exit(EXIT_FAILURE); + } + + // Pupulate channel list + for (int i = 0; i < SOUND_MIXER_NRDEVICES; i++) { + if (!((1 << i) & devmask)) + continue; + m_channel_names = g_list_append(m_channel_names, g_strdup(channel_labels[i])); + } + + // Setup channel using the provided channel name + if (channel != NULL) + oss_set_channel(channel); + else if (channel == NULL && m_channel_names != NULL) + oss_set_channel((const gchar *)m_channel_names->data); +} + +const gchar * +oss_get_channel() +{ + return m_channel; +} + +void +oss_set_channel(const gchar *channel) +{ + assert(channel != NULL); + assert(m_mixer_fd != -1); + + if (g_strcmp0(channel, m_channel) == 0) + return; + + // Find channel dev index + int i; + for (i = 0; i < SOUND_MIXER_NRDEVICES; i++) + if (g_strcmp0(channel, channel_labels[i]) == 0) + break; + + if (i < SOUND_MIXER_NRDEVICES) { + g_free(m_channel); + m_channel = g_strdup(channel); + m_channel_dev = i; + } +} + +const gchar * +oss_get_device() +{ + return m_device; +} + +const GList * +oss_get_channel_names() +{ + return m_channel_names; +} + +const GList * +oss_get_device_names() +{ + return m_device_names; +} + +int +oss_get_volume() +{ + assert(m_mixer_fd != -1); + + int current_volume; + if (ioctl(m_mixer_fd, MIXER_READ(m_channel_dev), &current_volume) == -1) { + perror("Cannot read volume"); + exit(EXIT_FAILURE); + } + + // Only the left channel is returned + return current_volume & 0x7f; +} + +void +oss_set_volume(int volume) +{ + assert(m_mixer_fd != -1); + volume = (volume < 0 ? 0 : (volume > 100 ? 100 : volume)); + + volume = (volume << 8) | volume; + if (ioctl(m_mixer_fd, MIXER_WRITE(m_channel_dev), &volume) == -1) { + perror("Cannot write volume"); + exit(EXIT_FAILURE); + } +} + +gboolean +oss_get_mute() +{ + assert(m_mixer_fd != -1); + + // TODO: see if there's a way to return real mute state + return oss_get_volume() == 0; +} + +void +oss_set_mute(gboolean mute) +{ + assert(m_mixer_fd != -1); + + // TODO: see if there's a way to toggle real mute + if (mute) { + oss_set_volume(0); + } +}
4bcabc905239f53f37f4480e63f1c47e8430b16b
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/xnnpack/src/src/qs8-gemm/gen/qs8-gemm-1x8c16-minmax-rndnu-neon-mlal.c
a455c9cf4b229e2c2926b4abff4c92401eebe125
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
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
8,033
c
qs8-gemm-1x8c16-minmax-rndnu-neon-mlal.c
// Auto-generated file. Do not edit! // Template: src/qs8-gemm/c16-neon-mlal.c.in // Generator: tools/xngen // // Copyright 2021 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <assert.h> #include <arm_neon.h> #include <xnnpack/gemm.h> #include <xnnpack/math.h> void xnn_qs8_gemm_minmax_rndnu_ukernel_1x8c16__neon_mlal( size_t mr, size_t nc, size_t kc, const int8_t* restrict a, size_t a_stride, const void* restrict w, int8_t* restrict c, size_t cm_stride, size_t cn_stride, const union xnn_qs8_conv_minmax_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS { assert(mr != 0); assert(mr <= 1); assert(nc != 0); assert(kc != 0); assert(kc % sizeof(int8_t) == 0); assert(a != NULL); assert(w != NULL); assert(c != NULL); kc = round_up_po2(kc, 16 * sizeof(int8_t)); const int8_t* a0 = a; int8_t* c0 = c; do { int32x4_t vacc0x0 = vld1q_lane_s32(w, vmovq_n_s32(0), 0); w = (const void*) ((uintptr_t) w + sizeof(int32_t)); int32x4_t vacc0x1 = vld1q_lane_s32(w, vmovq_n_s32(0), 0); w = (const void*) ((uintptr_t) w + sizeof(int32_t)); int32x4_t vacc0x2 = vld1q_lane_s32(w, vmovq_n_s32(0), 0); w = (const void*) ((uintptr_t) w + sizeof(int32_t)); int32x4_t vacc0x3 = vld1q_lane_s32(w, vmovq_n_s32(0), 0); w = (const void*) ((uintptr_t) w + sizeof(int32_t)); int32x4_t vacc0x4 = vld1q_lane_s32(w, vmovq_n_s32(0), 0); w = (const void*) ((uintptr_t) w + sizeof(int32_t)); int32x4_t vacc0x5 = vld1q_lane_s32(w, vmovq_n_s32(0), 0); w = (const void*) ((uintptr_t) w + sizeof(int32_t)); int32x4_t vacc0x6 = vld1q_lane_s32(w, vmovq_n_s32(0), 0); w = (const void*) ((uintptr_t) w + sizeof(int32_t)); int32x4_t vacc0x7 = vld1q_lane_s32(w, vmovq_n_s32(0), 0); w = (const void*) ((uintptr_t) w + sizeof(int32_t)); // KC loop of 16 size_t k = kc; while (k != 0) { const int8x16_t va0 = vld1q_s8(a0); a0 += 16; const int8x16_t vb0 = vld1q_s8(w); w = (const void*) ((uintptr_t) w + 16 * sizeof(int8_t)); const int8x16_t vb1 = vld1q_s8(w); w = (const void*) ((uintptr_t) w + 16 * sizeof(int8_t)); const int8x16_t vb2 = vld1q_s8(w); w = (const void*) ((uintptr_t) w + 16 * sizeof(int8_t)); const int8x16_t vb3 = vld1q_s8(w); w = (const void*) ((uintptr_t) w + 16 * sizeof(int8_t)); const int8x16_t vb4 = vld1q_s8(w); w = (const void*) ((uintptr_t) w + 16 * sizeof(int8_t)); const int8x16_t vb5 = vld1q_s8(w); w = (const void*) ((uintptr_t) w + 16 * sizeof(int8_t)); const int8x16_t vb6 = vld1q_s8(w); w = (const void*) ((uintptr_t) w + 16 * sizeof(int8_t)); const int8x16_t vb7 = vld1q_s8(w); w = (const void*) ((uintptr_t) w + 16 * sizeof(int8_t)); int16x8_t vprod0x0 = vmull_s8(vget_low_s8(vb0), vget_low_s8(va0)); vprod0x0 = vmlal_s8(vprod0x0, vget_high_s8(vb0), vget_high_s8(va0)); vacc0x0 = vpadalq_s16(vacc0x0, vprod0x0); int16x8_t vprod0x1 = vmull_s8(vget_low_s8(vb1), vget_low_s8(va0)); vprod0x1 = vmlal_s8(vprod0x1, vget_high_s8(vb1), vget_high_s8(va0)); vacc0x1 = vpadalq_s16(vacc0x1, vprod0x1); int16x8_t vprod0x2 = vmull_s8(vget_low_s8(vb2), vget_low_s8(va0)); vprod0x2 = vmlal_s8(vprod0x2, vget_high_s8(vb2), vget_high_s8(va0)); vacc0x2 = vpadalq_s16(vacc0x2, vprod0x2); int16x8_t vprod0x3 = vmull_s8(vget_low_s8(vb3), vget_low_s8(va0)); vprod0x3 = vmlal_s8(vprod0x3, vget_high_s8(vb3), vget_high_s8(va0)); vacc0x3 = vpadalq_s16(vacc0x3, vprod0x3); int16x8_t vprod0x4 = vmull_s8(vget_low_s8(vb4), vget_low_s8(va0)); vprod0x4 = vmlal_s8(vprod0x4, vget_high_s8(vb4), vget_high_s8(va0)); vacc0x4 = vpadalq_s16(vacc0x4, vprod0x4); int16x8_t vprod0x5 = vmull_s8(vget_low_s8(vb5), vget_low_s8(va0)); vprod0x5 = vmlal_s8(vprod0x5, vget_high_s8(vb5), vget_high_s8(va0)); vacc0x5 = vpadalq_s16(vacc0x5, vprod0x5); int16x8_t vprod0x6 = vmull_s8(vget_low_s8(vb6), vget_low_s8(va0)); vprod0x6 = vmlal_s8(vprod0x6, vget_high_s8(vb6), vget_high_s8(va0)); vacc0x6 = vpadalq_s16(vacc0x6, vprod0x6); int16x8_t vprod0x7 = vmull_s8(vget_low_s8(vb7), vget_low_s8(va0)); vprod0x7 = vmlal_s8(vprod0x7, vget_high_s8(vb7), vget_high_s8(va0)); vacc0x7 = vpadalq_s16(vacc0x7, vprod0x7); k -= 16 * sizeof(int8_t); } #if XNN_ARCH_ARM64 const int32x4_t vsum0x01 = vpaddq_s32(vacc0x0, vacc0x1); const int32x4_t vsum0x23 = vpaddq_s32(vacc0x2, vacc0x3); const int32x4_t vsum0x45 = vpaddq_s32(vacc0x4, vacc0x5); const int32x4_t vsum0x67 = vpaddq_s32(vacc0x6, vacc0x7); int32x4_t vacc0x0123 = vpaddq_s32(vsum0x01, vsum0x23); int32x4_t vacc0x4567 = vpaddq_s32(vsum0x45, vsum0x67); #else const int32x2_t vpsum0x0 = vadd_s32(vget_low_s32(vacc0x0), vget_high_s32(vacc0x0)); const int32x2_t vpsum0x1 = vadd_s32(vget_low_s32(vacc0x1), vget_high_s32(vacc0x1)); const int32x2_t vpsum0x2 = vadd_s32(vget_low_s32(vacc0x2), vget_high_s32(vacc0x2)); const int32x2_t vpsum0x3 = vadd_s32(vget_low_s32(vacc0x3), vget_high_s32(vacc0x3)); const int32x2_t vsum0x01 = vpadd_s32(vpsum0x0, vpsum0x1); const int32x2_t vsum0x23 = vpadd_s32(vpsum0x2, vpsum0x3); int32x4_t vacc0x0123 = vcombine_s32(vsum0x01, vsum0x23 ); const int32x2_t vpsum0x4 = vadd_s32(vget_low_s32(vacc0x4), vget_high_s32(vacc0x4)); const int32x2_t vpsum0x5 = vadd_s32(vget_low_s32(vacc0x5), vget_high_s32(vacc0x5)); const int32x2_t vpsum0x6 = vadd_s32(vget_low_s32(vacc0x6), vget_high_s32(vacc0x6)); const int32x2_t vpsum0x7 = vadd_s32(vget_low_s32(vacc0x7), vget_high_s32(vacc0x7)); const int32x2_t vsum0x45 = vpadd_s32(vpsum0x4, vpsum0x5); const int32x2_t vsum0x67 = vpadd_s32(vpsum0x6, vpsum0x7); int32x4_t vacc0x4567 = vcombine_s32(vsum0x45, vsum0x67 ); #endif const int32x4_t vright_pre_shift = vld1q_dup_s32(&params->rndnu_neon.right_pre_shift); const int32x4_t vmultiplier = vld1q_dup_s32(&params->rndnu_neon.multiplier); const int32x4_t vright_post_shift = vld1q_dup_s32(&params->rndnu_neon.right_post_shift); vacc0x0123 = vqshlq_s32(vacc0x0123, vright_pre_shift); vacc0x4567 = vqshlq_s32(vacc0x4567, vright_pre_shift); vacc0x0123 = vqdmulhq_s32(vacc0x0123, vmultiplier); vacc0x4567 = vqdmulhq_s32(vacc0x4567, vmultiplier); vacc0x0123 = vrshlq_s32(vacc0x0123, vright_post_shift); vacc0x4567 = vrshlq_s32(vacc0x4567, vright_post_shift); const int16x8_t voutput_zero_point = vld1q_dup_s16(&params->rndnu_neon.output_zero_point); #if XNN_ARCH_ARM64 const int16x8_t vacc0x01234567 = vqaddq_s16(vqmovn_high_s32(vqmovn_s32(vacc0x0123), vacc0x4567), voutput_zero_point); int8x8_t vout0x01234567 = vqmovn_s16(vacc0x01234567); #else const int16x8_t vacc0x01234567 = vqaddq_s16(vcombine_s16(vqmovn_s32(vacc0x0123), vqmovn_s32(vacc0x4567)), voutput_zero_point); int8x8_t vout0x01234567 = vqmovn_s16(vacc0x01234567); #endif const int8x8_t voutput_min = vld1_dup_s8(&params->rndnu_neon.output_min); const int8x8_t voutput_max = vld1_dup_s8(&params->rndnu_neon.output_max); vout0x01234567 = vmax_s8(vout0x01234567, voutput_min); vout0x01234567 = vmin_s8(vout0x01234567, voutput_max); if (nc >= 8) { vst1_s8(c0 + 0, vout0x01234567); c0 = (int8_t*) ((uintptr_t) c0 + cn_stride); a0 = (const int8_t*) ((uintptr_t) a0 - kc); nc -= 8; } else { // Final case where not all of the 8 columns fit in the destination. if (nc & 4) { vst1_lane_u32((void*) c0, vreinterpret_u32_s8(vout0x01234567), 0); c0 += 4; vout0x01234567 = vext_s8(vout0x01234567, vout0x01234567, 4); } if (nc & 2) { vst1_lane_u16((void*) c0, vreinterpret_u16_s8(vout0x01234567), 0); c0 += 2; vout0x01234567 = vext_s8(vout0x01234567, vout0x01234567, 2); } if (nc & 1) { vst1_lane_s8(c0, vout0x01234567, 0); } nc = 0; } } while (nc != 0); }
30db3b74477e2fa6d7e57b5c031f5753f49afbd2
29447d279f82058a39d7d6c02ed97ad7ce937569
/Fixtures/Resources/Simple/Sources/MixedClangResource/bar.c
6a403234f4499b5fcc5fd0fb426ea8dc39a425df
[ "Apache-2.0", "BSD-3-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference", "Swift-exception" ]
permissive
apple/swift-package-manager
543a2fa53591d7441de4cb55c5580ae8881a5579
1826ef6b7d8578f13dbd6db0f631b2d7ee0ba274
refs/heads/main
2023-08-18T05:43:51.764484
2023-08-16T23:03:29
2023-08-17T22:27:58
44,840,041
10,534
1,777
Apache-2.0
2023-09-14T21:53:38
2015-10-23T21:41:12
Swift
UTF-8
C
false
false
17
c
bar.c
#include "bar.h"
47afb348a6f1ff62a062db079a96a794b9a83634
30b736259b38c916e96f8e1517f92231070f5464
/porting/nimble/include/stats/stats.h
996bcbc720bc9052463f6875a5887dc55fbedee3
[ "Apache-2.0", "LicenseRef-scancode-gary-s-brown", "BSD-3-Clause" ]
permissive
apache/mynewt-nimble
5bcc87df4482705c5a6542467bab028c8fd4e5fe
b5e107e9c55f32d18b16e5afc0a7e1720b901b68
refs/heads/master
2023-09-01T19:28:57.874159
2023-08-31T09:07:59
2023-08-31T14:46:07
113,086,218
606
354
Apache-2.0
2023-09-14T12:14:19
2017-12-04T19:34:47
C
UTF-8
C
false
false
2,089
h
stats.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 __STATS_H__ #define __STATS_H__ #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #define STATS_SECT_DECL(__name) struct stats_ ## __name #define STATS_SECT_END }; #define STATS_SECT_START(__name) STATS_SECT_DECL(__name) { #define STATS_SECT_VAR(__var) #define STATS_HDR(__sectname) NULL #define STATS_SECT_ENTRY(__var) #define STATS_SECT_ENTRY16(__var) #define STATS_SECT_ENTRY32(__var) #define STATS_SECT_ENTRY64(__var) #define STATS_RESET(__var) #define STATS_SIZE_INIT_PARMS(__sectvarname, __size) \ 0, 0 #define STATS_INC(__sectvarname, __var) #define STATS_INCN(__sectvarname, __var, __n) #define STATS_CLEAR(__sectvarname, __var) #define STATS_NAME_START(__name) #define STATS_NAME(__name, __entry) #define STATS_NAME_END(__name) #define STATS_NAME_INIT_PARMS(__name) NULL, 0 static inline int stats_init(void *a, uint8_t b, uint8_t c, void *d, uint8_t e) { /* dummy */ return 0; } static inline int stats_register(void *a, void *b) { /* dummy */ return 0; } static inline int stats_init_and_reg(void *a, uint8_t b, uint8_t c, void *d, uint8_t e, void *f) { /* dummy */ return 0; } #ifdef __cplusplus } #endif #endif /* __STATS_H__ */
1c99e8469ec54340778f169adccc8e8c4417e785
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/media/platform/sunxi-vfe/device/ar0330_mipi.c
990652baf01c4752cc6c7dff8b86f7639ca86af2
[ "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
24,862
c
ar0330_mipi.c
/* * A V4L2 driver for ar0330_mipi Raw cameras. * */ #include <linux/init.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/i2c.h> #include <linux/delay.h> #include <linux/videodev2.h> #include <linux/clk.h> #include <media/v4l2-device.h> #include <media/v4l2-chip-ident.h> #include <media/v4l2-mediabus.h> #include <linux/io.h> #include "camera.h" #include "sensor_helper.h" MODULE_AUTHOR("Chomoly"); MODULE_DESCRIPTION("A low-level driver for Aptina ar0330_mipi Raw sensors"); MODULE_LICENSE("GPL"); //for internel driver debug #define DEV_DBG_EN 0 #if(DEV_DBG_EN == 1) #define vfe_dev_dbg(x,arg...) printk("[ar0330_mipi Raw]"x,##arg) #else #define vfe_dev_dbg(x,arg...) #endif #define vfe_dev_err(x,arg...) printk("[ar0330_mipi Raw]"x,##arg) #define vfe_dev_print(x,arg...) printk("[ar0330_mipi Raw]"x,##arg) #define LOG_ERR_RET(x) { \ int ret; \ ret = x; \ if(ret < 0) {\ vfe_dev_err("error at %s\n",__func__); \ return ret; \ } \ } //define module timing #define MCLK (24*1000*1000) #define VREF_POL V4L2_MBUS_VSYNC_ACTIVE_HIGH #define HREF_POL V4L2_MBUS_HSYNC_ACTIVE_HIGH #define CLK_POL V4L2_MBUS_PCLK_SAMPLE_RISING #define V4L2_IDENT_SENSOR 0x0330 /* *Our nominal (default) frame rate. */ #define SENSOR_FRAME_RATE 30 /* * The ar0330_mipi i2c address */ #define I2C_ADDR 0x20 #define SENSOR_NAME "ar0330_mipi" //static struct delayed_work sensor_s_ae_ratio_work; static struct v4l2_subdev *glb_sd; /* * Information we maintain about a known sensor. */ struct sensor_format_struct; /* coming later */ struct cfg_array { /* coming later */ struct regval_list * regs; int size; }; static inline struct sensor_info *to_state(struct v4l2_subdev *sd) { return container_of(sd, struct sensor_info, sd); } /* * The default register settings * */ static struct regval_list sensor_default_regs[] = { {0x301a,0x0059}, //Reset Sensor {REG_DLY,0x0064}, {0x31AE,0x0202}, //Output Interface Configured to 2lane MIPI {0x301A,0x0058},//Disable Streaming {REG_DLY,0x0032}, {0x3064,0x1802}, {0x3078,0x0001}, //Marker to say that 'Defaults' have been run {0x31e0,0x0003}, //Toggle Flash on Each Frame {0x3046,0x4038}, // Enable Flash Pin {0x3048,0x8480}, // Flash Pulse Length {0x31E0,0x0203}, //OTPM V5 {0x3ED2,0x0146}, {0x3EDA,0x88BC}, {0x3EDC,0xAA63}, {0x305E,0x00A0}, //PLL_settings 588Mbps 98Mhz //STATE = Master Clock,98000000 {0x302A,0x0006}, //VT_PIX_CLK_DIV = 6 {0x302C,0x0002}, //VT_SYS_CLK_DIV = 2 {0x302E,0x0002}, //PRE_PLL_CLK_DIV = 2 {0x3030,0x0031}, //PLL_MULTIPLIER = 49 {0x3036,0x000C}, //OP_PIX_CLK_DIV = 12 {0x3038,0x0001}, //OP_SYS_CLK_DIV = 1 {0x31AC,0x0C0C}, //DATA_FORMAT_BITS //MIPI Port Timing continuous mode {0x31B0,0x002d}, {0x31B2,0x0012}, {0x31B4,0x3b44}, {0x31B6,0x314d}, {0x31B8,0x2089}, {0x31BA,0x0206}, {0x31BC,0x8005}, {0x31BE,0x2003}, //Timing_settings {0x3002, 0x0078}, //Y_ADDR_START = 120 {0x3004, 0x0006}, //X_ADDR_START = 6 {0x3006, 0x0587}, //Y_ADDR_END = 1415 {0x3008, 0x0905}, //X_ADDR_END = 2309 {0x300A, 0x051c}, //FRAME_LENGTH_LINES = 1308 {0x300C, 0x04E0}, //LINE_LENGTH_PCK = 1248 {0x3012, 0x051b}, //COARSE_INTEGRATION_TIME = 1307 {0x3014, 0x0000}, //FINE_INTEGRATION_TIME = 0 {0x30A2, 0x0001}, //X_ODD_INC = 1 {0x30A6, 0x0001}, //Y_ODD_INC = 1 {0x3040,0x0000}, //READ_MODE = 0 {0x3042,0x0000}, //EXTRA_DELAY = 0 {0x30BA,0x002C}, //DIGITAL_CTRL = 44 {0x3070,0x0000}, {0x301A,0x025C}, //Enable Streaming }; /* * Here we'll try to encapsulate the changes for just the output * video format. * */ static struct regval_list sensor_fmt_raw[] = { //{REG_TERM,VAL_TERM}, }; /* * Code for dealing with controls. * fill with different sensor module * different sensor module has different settings here * if not support the follow function ,retrun -EINVAL */ static int sensor_g_exp(struct v4l2_subdev *sd, __s32 *value) { struct sensor_info *info = to_state(sd); *value = info->exp; vfe_dev_dbg("sensor_get_exposure = %d\n", info->exp); return 0; } static int sensor_s_exp(struct v4l2_subdev *sd, unsigned int exp_val) { struct sensor_info *info = to_state(sd); vfe_dev_dbg("sensor_set_exposure = %d\n", exp_val); if(exp_val>0xffffff) exp_val=0xfffff0; if(exp_val<16) exp_val=16; exp_val=(exp_val)>>4;//rounding to 1 sensor_write(sd, 0x3012,exp_val);//coarse integration time info->exp = exp_val; return 0; } static int sensor_g_gain(struct v4l2_subdev *sd, __s32 *value) { struct sensor_info *info = to_state(sd); *value = info->gain; vfe_dev_dbg("sensor_get_gain = %d\n", info->gain); return 0; } static int sensor_s_gain(struct v4l2_subdev *sd, int gain_val) { struct sensor_info *info = to_state(sd); unsigned short dig_gain = 0x80; // 1 times digital gain if (gain_val < 16) gain_val = 16; if (16<= gain_val*100 && gain_val*100 < (103*16) ) sensor_write(sd,0x3060,0x0000); else if ((103*16) <= gain_val*100 && gain_val*100 < (107*16)) sensor_write(sd,0x3060,0x0001); else if ((107*16) <= gain_val*100 && gain_val*100 < (110*16)) sensor_write(sd,0x3060,0x0002); else if ((110*16) <= gain_val*100 && gain_val*100 < (114*16)) sensor_write(sd,0x3060,0x0003); else if ((114*16) <= gain_val*100 && gain_val*100 < (119*16)) sensor_write(sd,0x3060,0x0004); else if ((119*16) <= gain_val*100 && gain_val*100 < (123*16)) sensor_write(sd,0x3060,0x0005); else if ((123*16) <= gain_val*100 && gain_val*100 < (128*16)) sensor_write(sd,0x3060,0x0006); else if ((128*16) <= gain_val*100 && gain_val*100 < (133*16)) sensor_write(sd,0x3060,0x0007); else if ((133*16) <= gain_val*100 && gain_val*100 < (139*16)) sensor_write(sd,0x3060,0x0008); else if ((139*16) <= gain_val*100 && gain_val*100 < (145*16)) sensor_write(sd,0x3060,0x0009); else if ((145*16) <= gain_val*100 && gain_val*100 < (152*16)) sensor_write(sd,0x3060,0x000a); else if ((152*16) <= gain_val*100 && gain_val*100 < (160*16)) sensor_write(sd,0x3060,0x000b); else if ((160*16) <= gain_val*100 && gain_val*100 < (168*16)) sensor_write(sd,0x3060,0x000c); else if ((168*16) <= gain_val*100 && gain_val*100 < (178*16)) sensor_write(sd,0x3060,0x000d); else if ((178*16) <= gain_val*100 && gain_val*100 < (188*16)) sensor_write(sd,0x3060,0x000e); else if ((188*16) <= gain_val*100 && gain_val*100 < (200*16)) sensor_write(sd,0x3060,0x000f); else if ((200*16) <= gain_val*100 && gain_val*100 < (213*16)) { sensor_write(sd,0x3060,0x0010); dig_gain = gain_val*12800/(200*16); } else if ((213*16) <= gain_val*100 && gain_val*100 < (229*16)) { sensor_write(sd,0x3060,0x0012); dig_gain = gain_val*12800/(213*16); } else if ((229*16) <= gain_val*100 && gain_val*100 < (246*16)) { sensor_write(sd,0x3060,0x0014); dig_gain = gain_val*12800/(229*16); } else if ((246*16) <= gain_val*100 && gain_val*100 < (267*16)) { sensor_write(sd,0x3060,0x0016); dig_gain = gain_val*12800/(246*16); } else if ((267*16) <= gain_val*100 && gain_val*100 < (291*16)) { sensor_write(sd,0x3060,0x0018); dig_gain = gain_val*12800/(267*16); } else if ((291*16) <= gain_val*100 && gain_val*100 < (320*16)) { sensor_write(sd,0x3060,0x001a); dig_gain = gain_val*12800/(291*16); } else if ((320*16) <= gain_val*100 && gain_val*100 < (356*16)) { sensor_write(sd,0x3060,0x001c); dig_gain = gain_val*12800/(320*16); } else if ((356*16) <= gain_val*100 && gain_val*100 < (400*16)) { sensor_write(sd,0x3060,0x001e); dig_gain = gain_val*12800/(356*16); } else if ((400*16) <= gain_val*100 && gain_val*100 < (457*16)) { sensor_write(sd,0x3060,0x0020); dig_gain = gain_val*12800/(400*16); } else if ((457*16) <= gain_val*100 && gain_val*100 < (533*16)) { sensor_write(sd,0x3060,0x0024); dig_gain = gain_val*12800/(457*16); } else if ((533*16) <= gain_val*100 && gain_val*100 < (640*16)) { sensor_write(sd,0x3060,0x0028); dig_gain = gain_val*12800/(533*16); } else if ((640*16) <= gain_val*100 && gain_val*100 < (800*16)) { sensor_write(sd,0x3060,0x002c); dig_gain = gain_val*12800/(640*16); } else if ((800*16) <= gain_val*100 ) { sensor_write(sd,0x3060,0x0030); dig_gain = gain_val*12800/(800*16); } sensor_write(sd, 0x305e, dig_gain); info->gain = gain_val; return 0; } static int ar0330_sensor_vts; static int sensor_s_exp_gain(struct v4l2_subdev *sd, struct sensor_exp_gain *exp_gain) { int exp_val, gain_val,shutter,frame_length; struct sensor_info *info = to_state(sd); exp_val = exp_gain->exp_val; gain_val = exp_gain->gain_val; if(gain_val<1*16) gain_val=16; if(gain_val>64*16-1) gain_val=64*16-1; if(exp_val>0xfffff) exp_val=0xfffff; shutter = exp_val/16; if(shutter > ar0330_sensor_vts - 4) frame_length = shutter + 4; else frame_length = ar0330_sensor_vts; printk("norm exp_val = %d,gain_val = %d\n",exp_val,gain_val); sensor_s_exp(sd,exp_val); sensor_s_gain(sd,gain_val); info->exp = exp_val; info->gain = gain_val; return 0; } static int sensor_s_sw_stby(struct v4l2_subdev *sd, int on_off) { int ret ; data_type rdtmp; ret = sensor_read(sd,0x301a,&rdtmp); if (ret!=0) return ret; if (on_off == 1) sensor_write(sd,0x301a,(rdtmp & 0xfff8)); else sensor_write(sd,0x301a,rdtmp ); return ret; } /* * Stuff that knows about the sensor. */ static int sensor_power(struct v4l2_subdev *sd, int on) { int ret; ret = 0; switch(on) { case CSI_SUBDEV_STBY_ON: vfe_dev_dbg("CSI_SUBDEV_STBY_ON!\n"); ret = sensor_s_sw_stby(sd, CSI_GPIO_HIGH); if(ret < 0) vfe_dev_err("soft stby falied!\n"); usleep_range(10000,12000); cci_lock(sd); vfe_gpio_write(sd,PWDN,CSI_GPIO_HIGH); cci_unlock(sd); vfe_set_mclk(sd,OFF); break; case CSI_SUBDEV_STBY_OFF: vfe_dev_dbg("CSI_SUBDEV_STBY_OFF!\n"); cci_lock(sd); vfe_set_mclk_freq(sd,MCLK); vfe_set_mclk(sd,ON); usleep_range(10000,12000); vfe_gpio_write(sd,PWDN,CSI_GPIO_LOW); usleep_range(10000,12000); ret = sensor_s_sw_stby(sd, CSI_GPIO_LOW); if(ret < 0) vfe_dev_err("soft stby off falied!\n"); cci_unlock(sd); break; case CSI_SUBDEV_PWR_ON: vfe_dev_dbg("CSI_SUBDEV_PWR_ON!\n"); cci_lock(sd); vfe_gpio_set_status(sd,PWDN,1);//set the gpio to output vfe_gpio_set_status(sd,RESET,1);//set the gpio to output vfe_gpio_set_status(sd,POWER_EN,1);//set the gpio to output vfe_gpio_write(sd,RESET,CSI_GPIO_HIGH); vfe_gpio_write(sd,PWDN,CSI_GPIO_HIGH); vfe_gpio_write(sd,POWER_EN,CSI_GPIO_LOW); usleep_range(1000,1200); vfe_set_pmu_channel(sd,AVDD,ON); vfe_gpio_write(sd,POWER_EN,CSI_GPIO_HIGH); vfe_set_pmu_channel(sd,DVDD,ON); vfe_set_pmu_channel(sd,AFVDD,ON); usleep_range(1000,1200); vfe_set_pmu_channel(sd,IOVDD,ON); vfe_set_mclk_freq(sd,MCLK); vfe_set_mclk(sd,ON); usleep_range(10000,12000); vfe_gpio_write(sd,PWDN,CSI_GPIO_LOW); usleep_range(10000,12000); vfe_gpio_write(sd,RESET,CSI_GPIO_LOW); usleep_range(20000,22000); vfe_gpio_write(sd,RESET,CSI_GPIO_HIGH); cci_lock(sd); vfe_set_mclk_freq(sd,MCLK); vfe_set_mclk(sd,ON); usleep_range(10000,12000); vfe_gpio_write(sd,PWDN,CSI_GPIO_LOW); usleep_range(10000,12000); ret = sensor_s_sw_stby(sd, CSI_GPIO_LOW); if(ret < 0) vfe_dev_err("soft stby off falied!\n"); cci_unlock(sd); break; case CSI_SUBDEV_PWR_OFF: vfe_dev_dbg("CSI_SUBDEV_PWR_OFF!\n"); cci_lock(sd); vfe_gpio_set_status(sd,PWDN,1);//set the gpio to output vfe_gpio_set_status(sd,RESET,1);//set the gpio to output vfe_gpio_write(sd,RESET,CSI_GPIO_LOW); vfe_gpio_write(sd,PWDN,CSI_GPIO_HIGH); vfe_set_mclk(sd,OFF); vfe_set_pmu_channel(sd,AFVDD,OFF); vfe_set_pmu_channel(sd,DVDD,OFF); vfe_gpio_write(sd,POWER_EN,CSI_GPIO_LOW); vfe_set_pmu_channel(sd,AVDD,OFF); vfe_set_pmu_channel(sd,IOVDD,OFF); vfe_gpio_set_status(sd,RESET,0);//set the gpio to input vfe_gpio_set_status(sd,PWDN,0);//set the gpio to input vfe_gpio_set_status(sd,POWER_EN,0);//set the gpio to input cci_unlock(sd); break; default: return -EINVAL; } return 0; } static int sensor_reset(struct v4l2_subdev *sd, u32 val) { switch(val) { case 0: vfe_gpio_write(sd,RESET,CSI_GPIO_HIGH); usleep_range(10000,12000); break; case 1: vfe_gpio_write(sd,RESET,CSI_GPIO_LOW); usleep_range(10000,12000); break; default: return -EINVAL; } return 0; } static int sensor_detect(struct v4l2_subdev *sd) { unsigned short rdval = 0; LOG_ERR_RET(sensor_read(sd, 0x3000, &rdval)) if(rdval != 0x2604) { printk(KERN_DEBUG"*********sensor error,read id is %x.\n",rdval); return -ENODEV; } else { printk(KERN_DEBUG"*********find ar0330_mipi raw data camera sensor now.\n"); return 0; } } static int sensor_init(struct v4l2_subdev *sd, u32 val) { int ret; struct sensor_info *info = to_state(sd); vfe_dev_dbg("sensor_init\n"); /*Make sure it is a target sensor*/ ret = sensor_detect(sd); if (ret) { vfe_dev_err("chip found is not an target chip.\n"); return ret; } vfe_get_standby_mode(sd,&info->stby_mode); if((info->stby_mode == HW_STBY || info->stby_mode == SW_STBY) \ && info->init_first_flag == 0) { vfe_dev_print("stby_mode and init_first_flag = 0\n"); return 0; } info->focus_status = 0; info->low_speed = 0; info->width = HD1080_WIDTH; info->height = HD1080_HEIGHT; info->hflip = 0; info->vflip = 0; info->gain = 0; info->tpf.numerator = 1; info->tpf.denominator = 30; /* 30fps */ ret = sensor_write_array(sd, sensor_default_regs, ARRAY_SIZE(sensor_default_regs)); if(ret < 0) { vfe_dev_err("write sensor_default_regs error\n"); return ret; } if(info->stby_mode == 0) info->init_first_flag = 0; info->preview_first_flag = 1; return 0; } static long sensor_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg) { int ret=0; struct sensor_info *info = to_state(sd); switch(cmd) { case GET_CURRENT_WIN_CFG: if(info->current_wins != NULL) { memcpy( arg, info->current_wins, sizeof(struct sensor_win_size) ); ret=0; } else { vfe_dev_err("empty wins!\n"); ret=-1; } break; case SET_FPS: break; case ISP_SET_EXP_GAIN: ret = sensor_s_exp_gain(sd, (struct sensor_exp_gain *)arg); break; default: return -EINVAL; } return ret; } /* * Store information about the video data format. */ static struct sensor_format_struct { __u8 *desc; //__u32 pixelformat; enum v4l2_mbus_pixelcode mbus_code; struct regval_list *regs; int regs_size; int bpp; /* Bytes per pixel */ }sensor_formats[] = { { .desc = "Raw RGB Bayer", .mbus_code = V4L2_MBUS_FMT_SGRBG12_12X1, .regs = sensor_fmt_raw, .regs_size = ARRAY_SIZE(sensor_fmt_raw), .bpp = 1 }, }; #define N_FMTS ARRAY_SIZE(sensor_formats) /* * Then there is the issue of window sizes. Try to capture the info here. */ static struct sensor_win_size sensor_win_sizes[] = { /* qsxga: 2304*1296 */ { .width = 2304, .height = 1296, .hoffset = 0, .voffset = 0, .hts = 1248, .vts = 1308, .pclk = 49*1000*1000, .mipi_bps = (588*1000*1000), .fps_fixed = 1, .bin_factor = 1, .intg_min = 1<<4, .intg_max = 1308<<4,// .gain_min = 1<<4, .gain_max = 64<<4, .regs = sensor_default_regs, .regs_size = ARRAY_SIZE(sensor_default_regs), .set_size = NULL, }, /* 1080P */ { .width = HD1080_WIDTH, .height = HD1080_HEIGHT, .hoffset = 0, .voffset = 0, .hts = 1248, .vts = 1308, .pclk = 49*1000*1000, .mipi_bps = (588*1000*1000)/1, .fps_fixed = 1, .bin_factor = 1, .intg_min = 1<<4, .intg_max = 1308<<4,// .gain_min = 1<<4, .gain_max = 64<<4, .width_input = 2304, .height_input = 1296, .regs = sensor_default_regs, .regs_size = ARRAY_SIZE(sensor_default_regs), .set_size = NULL, }, }; #define N_WIN_SIZES (ARRAY_SIZE(sensor_win_sizes)) static int sensor_enum_fmt(struct v4l2_subdev *sd, unsigned index, enum v4l2_mbus_pixelcode *code) { if (index >= N_FMTS) return -EINVAL; *code = sensor_formats[index].mbus_code; return 0; } static int sensor_enum_size(struct v4l2_subdev *sd, struct v4l2_frmsizeenum *fsize) { if(fsize->index > N_WIN_SIZES-1) return -EINVAL; fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE; fsize->discrete.width = sensor_win_sizes[fsize->index].width; fsize->discrete.height = sensor_win_sizes[fsize->index].height; return 0; } static int sensor_try_fmt_internal(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *fmt, struct sensor_format_struct **ret_fmt, struct sensor_win_size **ret_wsize) { int index; struct sensor_win_size *wsize; struct sensor_info *info = to_state(sd); for (index = 0; index < N_FMTS; index++) if (sensor_formats[index].mbus_code == fmt->code) break; if (index >= N_FMTS) return -EINVAL; if (ret_fmt != NULL) *ret_fmt = sensor_formats + index; /* * Fields: the sensor devices claim to be progressive. */ fmt->field = V4L2_FIELD_NONE; /* * Round requested image size down to the nearest * we support, but not below the smallest. */ for (wsize = sensor_win_sizes; wsize < sensor_win_sizes + N_WIN_SIZES; wsize++) if (fmt->width >= wsize->width && fmt->height >= wsize->height) break; if (wsize >= sensor_win_sizes + N_WIN_SIZES) wsize--; /* Take the smallest one */ if (ret_wsize != NULL) *ret_wsize = wsize; /* * Note the size we'll actually handle. */ fmt->width = wsize->width; fmt->height = wsize->height; info->current_wins = wsize; return 0; } static int sensor_try_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *fmt) { return sensor_try_fmt_internal(sd, fmt, NULL, NULL); } static int sensor_g_mbus_config(struct v4l2_subdev *sd, struct v4l2_mbus_config *cfg) { cfg->type = V4L2_MBUS_CSI2; cfg->flags = 0|V4L2_MBUS_CSI2_2_LANE|V4L2_MBUS_CSI2_CHANNEL_0; return 0; } /* * Set a format. */ static int sensor_s_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *fmt) { int ret; struct sensor_format_struct *sensor_fmt; struct sensor_win_size *wsize; struct sensor_info *info = to_state(sd); vfe_dev_dbg("sensor_s_fmt\n"); ret = sensor_try_fmt_internal(sd, fmt, &sensor_fmt, &wsize); if (ret) return ret; if(info->capture_mode == V4L2_MODE_VIDEO) { //video } else if(info->capture_mode == V4L2_MODE_IMAGE) { //image } LOG_ERR_RET(sensor_write_array(sd, sensor_fmt->regs, sensor_fmt->regs_size)) ret = 0; if (wsize->regs) LOG_ERR_RET(sensor_write_array(sd, wsize->regs, wsize->regs_size)) if (wsize->set_size) LOG_ERR_RET(wsize->set_size(sd)) info->fmt = sensor_fmt; info->width = wsize->width; info->height = wsize->height; ar0330_sensor_vts = wsize->vts; // show_regs_array(sd,sensor_1080p_regs); vfe_dev_print("s_fmt set width = %d, height = %d\n",wsize->width,wsize->height); if(info->capture_mode == V4L2_MODE_VIDEO) { //video } else { //capture image } //sensor_write_array(sd, sensor_oe_enable_regs, ARRAY_SIZE(sensor_oe_enable_regs)); return 0; } /* * Implement G/S_PARM. There is a "high quality" mode we could try * to do someday; for now, we just do the frame rate tweak. */ static int sensor_g_parm(struct v4l2_subdev *sd, struct v4l2_streamparm *parms) { struct v4l2_captureparm *cp = &parms->parm.capture; struct sensor_info *info = to_state(sd); if (parms->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) return -EINVAL; memset(cp, 0, sizeof(struct v4l2_captureparm)); cp->capability = V4L2_CAP_TIMEPERFRAME; cp->capturemode = info->capture_mode; return 0; } static int sensor_s_parm(struct v4l2_subdev *sd, struct v4l2_streamparm *parms) { struct v4l2_captureparm *cp = &parms->parm.capture; struct sensor_info *info = to_state(sd); vfe_dev_dbg("sensor_s_parm\n"); if (parms->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) return -EINVAL; if (info->tpf.numerator == 0) return -EINVAL; info->capture_mode = cp->capturemode; return 0; } static int sensor_queryctrl(struct v4l2_subdev *sd, struct v4l2_queryctrl *qc) { /* Fill in min, max, step and default value for these controls. */ /* see include/linux/videodev2.h for details */ switch (qc->id) { case V4L2_CID_GAIN: return v4l2_ctrl_query_fill(qc, 1*16, 16*9-1, 1, 16); case V4L2_CID_EXPOSURE: return v4l2_ctrl_query_fill(qc, 1, 65536*16, 1, 1); case V4L2_CID_FRAME_RATE: return v4l2_ctrl_query_fill(qc, 15, 120, 1, 30); } return -EINVAL; } static int sensor_g_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl) { switch (ctrl->id) { case V4L2_CID_GAIN: return sensor_g_gain(sd, &ctrl->value); case V4L2_CID_EXPOSURE: return sensor_g_exp(sd, &ctrl->value); } return -EINVAL; } static int sensor_s_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl) { struct v4l2_queryctrl qc; int ret; qc.id = ctrl->id; ret = sensor_queryctrl(sd, &qc); if (ret < 0) { return ret; } if (ctrl->value < qc.minimum || ctrl->value > qc.maximum) { vfe_dev_err("max gain qurery is %d,min gain qurey is %d\n",qc.maximum,qc.minimum); return -ERANGE; } switch (ctrl->id) { case V4L2_CID_GAIN: return sensor_s_gain(sd, ctrl->value); case V4L2_CID_EXPOSURE: return sensor_s_exp(sd, ctrl->value); } return -EINVAL; } static int sensor_g_chip_ident(struct v4l2_subdev *sd, struct v4l2_dbg_chip_ident *chip) { struct i2c_client *client = v4l2_get_subdevdata(sd); return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_SENSOR, 0); } /* ----------------------------------------------------------------------- */ static const struct v4l2_subdev_core_ops sensor_core_ops = { .g_chip_ident = sensor_g_chip_ident, .g_ctrl = sensor_g_ctrl, .s_ctrl = sensor_s_ctrl, .queryctrl = sensor_queryctrl, .reset = sensor_reset, .init = sensor_init, .s_power = sensor_power, .ioctl = sensor_ioctl, }; static const struct v4l2_subdev_video_ops sensor_video_ops = { .enum_mbus_fmt = sensor_enum_fmt, .enum_framesizes = sensor_enum_size, .try_mbus_fmt = sensor_try_fmt, .s_mbus_fmt = sensor_s_fmt, .s_parm = sensor_s_parm, .g_parm = sensor_g_parm, .g_mbus_config = sensor_g_mbus_config, }; static const struct v4l2_subdev_ops sensor_ops = { .core = &sensor_core_ops, .video = &sensor_video_ops, }; /* ----------------------------------------------------------------------- */ static struct cci_driver cci_drv = { .name = SENSOR_NAME, .addr_width = CCI_BITS_16, .data_width = CCI_BITS_16, }; static int sensor_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct v4l2_subdev *sd; struct sensor_info *info; info = kzalloc(sizeof(struct sensor_info), GFP_KERNEL); if (info == NULL) return -ENOMEM; sd = &info->sd; glb_sd = sd; cci_dev_probe_helper(sd, client, &sensor_ops, &cci_drv); info->fmt = &sensor_formats[0]; info->af_first_flag = 1; info->init_first_flag = 1; return 0; } static int sensor_remove(struct i2c_client *client) { struct v4l2_subdev *sd; sd = cci_dev_remove_helper(client, &cci_drv); kfree(to_state(sd)); return 0; } static const struct i2c_device_id sensor_id[] = { {SENSOR_NAME, 0 }, { } }; MODULE_DEVICE_TABLE(i2c, sensor_id); static struct i2c_driver sensor_driver = { .driver = { .owner = THIS_MODULE, .name = SENSOR_NAME, }, .probe = sensor_probe, .remove = sensor_remove, .id_table = sensor_id, }; static __init int init_sensor(void) { return cci_dev_init_helper(&sensor_driver); } static __exit void exit_sensor(void) { cci_dev_exit_helper(&sensor_driver); } module_init(init_sensor); module_exit(exit_sensor);
1b732bb0e11a5709bdbeaafe729686fdbb7d4489
8838eb997879add5759b6dfb23f9a646464e53ca
/src/include/defines/null.h
6bdbcbd1b1356837fb9e3307c93496aa87680d19
[ "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
264
h
null.h
/** * @file * * @date Aug 29, 2013 * @author: Anton Bondarev */ #ifndef NULL_DEF_H_ #define NULL_DEF_H_ #undef NULL #ifndef __cplusplus #define NULL ((void *)0) #else /* __cplusplus */ #define NULL 0 #endif /* ! __cplusplus */ #endif /* NULL_DEF_H_ */
5c358aeddeb10ee2354ff0a402270bc373e71708
0a8b224bd47a65dfd87bb02902e7c01e3e71d8f5
/android/library/maply/jni/include/generated/com_mousebird_maply_View.h
35cca19fd40b0f7c8e089dd4629a8fd2c0ed25b4
[ "Apache-2.0" ]
permissive
mousebird-consulting-inc/WhirlyGlobe
72ea7ffc7b82006d44d2df8e471238f06e93daeb
07a710bf6deffda8222a7a7864eb855e95aa73b3
refs/heads/main
2023-08-31T07:13:46.124930
2022-05-05T17:08:18
2022-05-05T17:08:18
3,139,032
106
36
NOASSERTION
2023-08-22T20:54:16
2012-01-09T18:51:52
C++
UTF-8
C
false
true
1,335
h
com_mousebird_maply_View.h
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_mousebird_maply_View */ #ifndef _Included_com_mousebird_maply_View #define _Included_com_mousebird_maply_View #ifdef __cplusplus extern "C" { #endif /* * Class: com_mousebird_maply_View * Method: calcModelViewMatrix * Signature: ()Lcom/mousebird/maply/Matrix4d; */ JNIEXPORT jobject JNICALL Java_com_mousebird_maply_View_calcModelViewMatrix (JNIEnv *, jobject); /* * Class: com_mousebird_maply_View * Method: heightForMapScale * Signature: (DDD)D */ JNIEXPORT jdouble JNICALL Java_com_mousebird_maply_View_heightForMapScale (JNIEnv *, jobject, jdouble, jdouble, jdouble); /* * Class: com_mousebird_maply_View * Method: currentMapZoom * Signature: (DDD)D */ JNIEXPORT jdouble JNICALL Java_com_mousebird_maply_View_currentMapZoom (JNIEnv *, jobject, jdouble, jdouble, jdouble); /* * Class: com_mousebird_maply_View * Method: currentMapScale * Signature: (DD)D */ JNIEXPORT jdouble JNICALL Java_com_mousebird_maply_View_currentMapScale (JNIEnv *, jobject, jdouble, jdouble); /* * Class: com_mousebird_maply_View * Method: nativeInit * Signature: ()V */ JNIEXPORT void JNICALL Java_com_mousebird_maply_View_nativeInit (JNIEnv *, jclass); #ifdef __cplusplus } #endif #endif
8ea981401772a4f383ee2dffae40014286050c9f
f3eed0234b4d0ad2bbb2abd700cf1e2c7a0e8a1d
/AKWF-c/AKWF_fmsynth/AKWF_fmsynth_0005.h
dea97dcea41059c7b1d007e372243bce4884376e
[ "CC0-1.0" ]
permissive
KristofferKarlAxelEkstrand/AKWF-FREE
b2defa1a2d389d309be6dd2e9f968923daf80d1b
cf8171df36e9fec25416b5f568b72a6e2cb69194
refs/heads/master
2023-07-23T18:22:36.939705
2023-07-10T17:14:40
2023-07-10T17:14:40
145,817,187
359
59
CC0-1.0
2023-07-10T17:14:41
2018-08-23T07:26:56
null
UTF-8
C
false
false
4,688
h
AKWF_fmsynth_0005.h
/* Adventure Kid Waveforms (AKWF) converted for use with Teensy Audio Library * * Adventure Kid Waveforms(AKWF) Open waveforms library * https://www.adventurekid.se/akrt/waveforms/adventure-kid-waveforms/ * * This code is in the public domain, CC0 1.0 Universal (CC0 1.0) * https://creativecommons.org/publicdomain/zero/1.0/ * * Converted by Brad Roy, https://github.com/prosper00 */ /* AKWF_fmsynth_0005 256 samples +-----------------------------------------------------------------------------------------------------------------+ | ** *** *** *** ** ** ** ** * * * * | | ** ** *** * ** * ** * ** * ** ** | |** ** *** ** * ** * ** * ** * * | |* *** **** ** ** ** * * * * * * | |* **** * * ** ** * * * ** * | | ** ** ** ** ** * * * * | | * * ** ** * * * * * *| | ** * ** ** * * * * * *| | * * ******* ** * * * * *| | ** * * * * * * * * | | * ** * * * * * * | | ** * ** * * * * ** | | * * * ** * * * * | | ** * * * * * ** ** | | ** ** **** *** * ** | +-----------------------------------------------------------------------------------------------------------------+ */ const uint16_t AKWF_fmsynth_0005 [] = { 33749, 36745, 39389, 41899, 44106, 46092, 47798, 49254, 50450, 51392, 52106, 52579, 52859, 52925, 52835, 52567, 52181, 51654, 51044, 50332, 49569, 48742, 47894, 47010, 46131, 45249, 44387, 43546, 42742, 41976, 41261, 40598, 39992, 39451, 38973, 38567, 38228, 37967, 37773, 37661, 37620, 37660, 37772, 37963, 38227, 38569, 38979, 39463, 40013, 40629, 41305, 42037, 42819, 43643, 44503, 45385, 46282, 47181, 48069, 48929, 49748, 50505, 51188, 51772, 52242, 52577, 52756, 52762, 52579, 52187, 51572, 50723, 49629, 48286, 46691, 44844, 42754, 40433, 37895, 35165, 32272, 29248, 26130, 22965, 19797, 16683, 13672, 10824, 8195, 5843, 3823, 2184, 975, 237, 0, 284, 1100, 2449, 4312, 6657, 9436, 12583, 16019, 19640, 23333, 26974, 30604, 34220, 37688, 40922, 43838, 46387, 48525, 50232, 51501, 52338, 52753, 52773, 52428, 51754, 50789, 49573, 48151, 46562, 44848, 43044, 41192, 39321, 37459, 35633, 33869, 32182, 30590, 29104, 27735, 26492, 25381, 24402, 23562, 22863, 22301, 21882, 21607, 21474, 21484, 21641, 21943, 22395, 22999, 23752, 24661, 25723, 26938, 28306, 29820, 31471, 33250, 35138, 37118, 39162, 41235, 43300, 45308, 47208, 48939, 50435, 51620, 52429, 52782, 52610, 51845, 50441, 48359, 45596, 42172, 38163, 33686, 28949, 24134, 19187, 14312, 9818, 5954, 2938, 933, 66, 387, 1908, 4572, 8278, 12860, 18128, 23829, 29704, 35460, 40810, 45458, 49148, 51640, 52761, 52389, 50498, 47141, 42500, 36861, 30668, 24414, 18174, 12290, 7284, 3454, 1032, 88, 634, 2568, 5747, 9953, 14951, 20466, 26225, 31947, 37372, 42260, 46394, 49607, 51759, 52780, 52618, 51315, 48916, 45576, 41432, 36744, 31736, 26761, 21853, 17052, 12603, 8703, 5468, 2982, 1272, 335, 147, 648, 1795, 3482, 5671, 8222, 11127, 14206, 17512, 20803, 24235, 27409, 30777, };
9a61646ba4bf4757fdd01124fea4326621e88dce
fef5296397f9b950a11455e880a919537390aea0
/nbi/engine/native/launcher/windows/src/Main.c
5a819eed05805139a89d43a82ef8afc148448faf
[ "Apache-2.0" ]
permissive
apache/netbeans
5a4d6fa9e4f230b33e44519a479d66e47a381289
28d308b400bbe439ac0ac84b64d823ce0b69272e
refs/heads/master
2023-08-29T15:32:41.838270
2023-08-29T09:48:59
2023-08-29T09:48:59
102,083,576
1,692
718
Apache-2.0
2023-09-14T19:41:05
2017-09-01T07:00:11
Java
UTF-8
C
false
false
21,819
c
Main.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <commctrl.h> #include "Launcher.h" #include "FileUtils.h" #include "StringUtils.h" #include "SystemUtils.h" #include "ExtractUtils.h" #include "Main.h" #define HAVE_WCHAR_H 1 char mainClassName[80] = "Main NBI Window Class"; char mainTitle [80] = "NBI Launcher"; char showMessageTitle [] = "\n<ShowMessage>\n"; HWND hwndPB = NULL; HWND hwndMain = NULL; HWND hwndErrorDetail = NULL; HWND hwndErrorTitle = NULL; HWND hwndButton = NULL; HWND hwndProgressTitle = NULL; HINSTANCE globalInstance = NULL; int64t * totalProgressSize = NULL; int64t * currentProgressSize = NULL; long steps = 1000; long lastCheckedStep = 0; int iCmdShowGlobal = 0; HANDLE initializationSuccess = NULL; HANDLE initializationFailed = NULL; HANDLE closingWindowsRequired = NULL; HANDLE closingWindowsConfirmed = NULL; HANDLE buttonPressed = NULL; #define BTN_EXIT 254 LRESULT CALLBACK WndProc(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam) { switch (umsg) { case WM_CLOSE: SetEvent(closingWindowsRequired); DestroyWindow(hwndPB); DestroyWindow(hwndProgressTitle); DestroyWindow(hwndErrorDetail); DestroyWindow(hwndErrorTitle); DestroyWindow(hwndButton); DestroyWindow(hwnd); return 0; case WM_DESTROY: UnregisterClass(mainClassName, globalInstance); PostQuitMessage(0); return 0; case WM_COMMAND: if(LOWORD(wParam)==BTN_EXIT) { SetEvent(buttonPressed); return 0; } } return DefWindowProc(hwnd, umsg, wParam, lParam); } void initMainWindow(LauncherProperties * props, HINSTANCE hInstance) { if(!isSilent(props)) { int systemWidth = GetSystemMetrics(SM_CXSCREEN); int systemHeight = GetSystemMetrics(SM_CYSCREEN); int w = 460; int h = 200; int x = (systemWidth - w)/2; int y = (systemHeight - h)/2; InitCommonControls(); hwndMain = CreateWindow(mainClassName, mainTitle, //WS_OVERLAPPED | WS_EX_TOOLWINDOW, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_BORDER | WS_DLGFRAME | WS_SYSMENU | WS_MINIMIZEBOX /* | WS_THICKFRAME | WS_MAXIMIZEBOX*/ , x, y, w, h, NULL, NULL, hInstance, NULL); } } void initErrorTitleWindow(LauncherProperties *props, HINSTANCE hInstance) { if(!isSilent(props)) { RECT rcClient; int cyVScroll; cyVScroll = GetSystemMetrics(SM_CYVSCROLL); GetClientRect(hwndMain, &rcClient); hwndErrorTitle = CreateWindowExW(0, WC_STATICW, WC_STATICW, WS_CHILD, rcClient.left + 10, 15, rcClient.right - 20, 20, hwndMain, NULL, hInstance, NULL); if (hwndErrorTitle) { HFONT hFont = (HFONT) GetStockObject(DEFAULT_GUI_FONT); LOGFONT lfTitle; HFONT titleFont; GetObject(hFont, sizeof(lfTitle), &lfTitle); lfTitle.lfWeight = FW_ULTRABOLD;//OLD; lfTitle.lfHeight = lfTitle.lfHeight + 2 ; lfTitle.lfWidth = 0; titleFont = CreateFontIndirect(&lfTitle); SendMessage(hwndErrorTitle, WM_SETFONT, (WPARAM) titleFont , FALSE); //DeleteObject(titleFont ); setErrorTitleString(props, NULL); } } } void initErrorDetailWindow(LauncherProperties *props, HINSTANCE hInstance) { if(!isSilent(props)) { RECT rcClient; int cyVScroll; cyVScroll = GetSystemMetrics(SM_CYVSCROLL); GetClientRect(hwndMain, &rcClient); hwndErrorDetail = CreateWindowExW(0, WC_STATICW, WC_STATICW, WS_CHILD , rcClient.left + 10, 40, rcClient.right - 20, 80, hwndMain, NULL, hInstance, NULL); if (hwndErrorDetail) { LOGFONT lfDetail; HFONT detailFont; HFONT hFont = (HFONT) GetStockObject(DEFAULT_GUI_FONT); GetObject(hFont, sizeof(lfDetail), &lfDetail); lfDetail.lfHeight = lfDetail.lfHeight + 2; lfDetail.lfWidth = 0; detailFont = CreateFontIndirect(&lfDetail); SendMessage(hwndErrorDetail, WM_SETFONT, (WPARAM) detailFont, FALSE); //DeleteObject(detailFont); setErrorDetailString(props, NULL); } } } void initProgressTitleWindow(LauncherProperties *props, HINSTANCE hInstance) { if(!isSilent(props)) { RECT rcClient; int cyVScroll; int height = 20; cyVScroll = GetSystemMetrics(SM_CYVSCROLL); GetClientRect(hwndMain, &rcClient); hwndProgressTitle = CreateWindowExW(0, WC_STATICW, WC_STATICW, WS_CHILD | WS_VISIBLE , rcClient.left + 10, (rcClient.bottom - cyVScroll)/2 - height, rcClient.right - 20, height, hwndMain, NULL, hInstance, NULL); if (hwndProgressTitle) { LOGFONT lfTitle; HFONT progressTitleFont; HFONT hFont = (HFONT) GetStockObject(DEFAULT_GUI_FONT); GetObject(hFont, sizeof(lfTitle), &lfTitle); lfTitle.lfHeight = lfTitle.lfHeight + 2; lfTitle.lfWidth = 0; progressTitleFont = CreateFontIndirect(&lfTitle); SendMessage(hwndProgressTitle, WM_SETFONT, (WPARAM) progressTitleFont, FALSE); //DeleteObject(detailFont); setProgressTitleString(props, NULL); } } } void initProgressWindow(LauncherProperties * props, HINSTANCE hInstance) { if(!isSilent(props)) { RECT rcClient; int cyVScroll; cyVScroll = GetSystemMetrics(SM_CYVSCROLL); GetClientRect(hwndMain, &rcClient); hwndPB = CreateWindowExW(0, PROGRESS_CLASSW, NULL, WS_CHILD | WS_VISIBLE | PBS_SMOOTH, rcClient.left + 10, (rcClient.bottom - cyVScroll)/2 , rcClient.right - 20, cyVScroll, hwndMain, NULL, hInstance, NULL); totalProgressSize->Low = 100; totalProgressSize->High = 0; } } void initExitButton(LauncherProperties * props, HINSTANCE hInstance) { if(!isSilent(props)) { RECT rcClient; //int cyVScroll = GetSystemMetrics(SM_CYVSCROLL); int buttonWidth = 180; int buttonHeight = 25; GetClientRect(hwndMain, &rcClient); hwndButton = CreateWindowExW(0, WC_BUTTONW, NULL, WS_CHILD | BS_DEFPUSHBUTTON | WS_TABSTOP | BS_PUSHBUTTON , rcClient.right - 20 - buttonWidth, rcClient.bottom - 10 - buttonHeight, buttonWidth, buttonHeight, hwndMain, (HMENU)BTN_EXIT, hInstance, 0); if (hwndButton) { LOGFONT lfButton; HFONT buttonFont; HFONT hFont = (HFONT) GetStockObject(DEFAULT_GUI_FONT); GetObject(hFont, sizeof(lfButton), &lfButton); lfButton.lfHeight = lfButton.lfHeight + 2; lfButton.lfWidth = 0; buttonFont = CreateFontIndirect(&lfButton); SendMessage(hwndButton, WM_SETFONT, (WPARAM) buttonFont, FALSE); SetFocus(hwndButton); //DeleteObject(detailFont); setButtonString(props, NULL); UpdateWindow(hwndButton); } } } void showErrorW(LauncherProperties * props, const char * error, const DWORD varArgsNumber, ...) { WCHAR * errorTitle = NULL; WCHAR * errorMessage = NULL; DWORD totalLength = 0; DWORD counter=0; WCHAR * result = NULL; va_list ap; getI18nPropertyTitleDetail(props, error, & errorTitle, &errorMessage); totalLength=getLengthW(errorMessage); va_start(ap, varArgsNumber); while((counter++)<varArgsNumber) { WCHAR * arg = va_arg( ap, WCHAR * ); totalLength+=getLengthW(arg); } va_end(ap); result = newpWCHAR(totalLength + 1); va_start(ap, varArgsNumber); if(errorMessage!=NULL) { wvsprintfW(result, errorMessage, ap); } va_end(ap); if(!isSilent(props)) { HANDLE * events = (HANDLE *) LocalAlloc(LPTR, sizeof(HANDLE)*2); hide(props, hwndProgressTitle); hide(props, hwndPB); setErrorDetailString(props, result); setErrorTitleString(props, errorTitle); setButtonString(props, getI18nProperty(props, EXIT_BUTTON_PROP)); show(props, hwndErrorDetail); show(props, hwndErrorTitle); show(props, hwndButton); events[0] = buttonPressed; events[1] = closingWindowsRequired; WaitForMultipleObjects(2, events, FALSE, INFINITE); FREE(events); } FREE(result); FREE(errorTitle); FREE(errorMessage); } BOOL InitInstance(LauncherProperties * props, HINSTANCE hInstance, int iCmdShow, HWND * MainWindowHandle) { if(isSilent(props)) return TRUE; iCmdShowGlobal = iCmdShow; initMainWindow(props, hInstance); if(!hwndMain) return FALSE; initErrorTitleWindow(props, hInstance); if(!hwndErrorTitle) return FALSE; initErrorDetailWindow(props, hInstance); if(!hwndErrorDetail) return FALSE; initProgressWindow(props, hInstance); if (! hwndPB) return FALSE; initProgressTitleWindow(props, hInstance); if (! hwndPB) return FALSE; initExitButton(props, hInstance); if (! hwndButton) return FALSE; UpdateWindow(hwndMain); * MainWindowHandle = hwndMain; return TRUE; } void messageLoop(LauncherProperties * props){ if(!isSilent(props)) { MSG message; while(GetMessage(&message, NULL, 0, 0) > 0) { if(!IsDialogMessage(hwndMain, & message)) { TranslateMessage(&message); DispatchMessage(&message); } } } } BOOL InitApplication(LauncherProperties * props, HINSTANCE hInstance) { if(isSilent(props)) { return TRUE; } else { WNDCLASSEX wndclass; wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = (WNDPROC)WndProc; wndclass.cbSize = sizeof(WNDCLASSEX); wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(100)); wndclass.hIconSm = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(100), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR); wndclass.hInstance = hInstance; wndclass.hCursor = LoadCursor( 0, IDC_ARROW ); wndclass.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); wndclass.lpszMenuName = NULL; wndclass.lpszClassName = mainClassName; return RegisterClassEx(&wndclass); } } DWORD isTerminated(LauncherProperties * props) { if(props->status == ERROR_USER_TERMINATED) { writeMessageA(props, OUTPUT_LEVEL_DEBUG, 0, "... already terminated", 1); return 1; } if (WAIT_OBJECT_0 == WaitForSingleObject(closingWindowsRequired, 0)) { writeMessageA(props, OUTPUT_LEVEL_DEBUG, 0, "... terminate signal!", 1); props->status = ERROR_USER_TERMINATED; return 1; } return 0; } void addProgressPosition(LauncherProperties * props, DWORD add) { if(isSilent(props)) return; if ( add > 0 ) { int64t *mult1 = NULL; int64t *mult2 = NULL; int64t *currMult = NULL; int comp1 = 0; int comp2 = 0; int goout = 0; plus(currentProgressSize, add); do { multiply(mult1 = newint64_t(totalProgressSize->Low, totalProgressSize->High), lastCheckedStep); multiply(mult2 = newint64_t(totalProgressSize->Low, totalProgressSize->High), lastCheckedStep + 1); multiply(currMult = newint64_t(currentProgressSize->Low, currentProgressSize->High), steps); comp1 = compareInt64t(currMult, mult1); if (comp1 == 0) { goout = 1; } else { comp2 = compareInt64t(currMult, mult2); if (comp2 == 0) { lastCheckedStep++; goout = 1; } else if (comp1 > 0 && comp2 < 0) { goout = 1; } else { lastCheckedStep++; } } FREE(mult1); FREE(mult2); FREE(currMult); if(lastCheckedStep >= steps) { lastCheckedStep = steps; goout = 1; } } while (!goout); SendMessage(hwndPB, PBM_SETPOS, lastCheckedStep, 0); } } void setProgressRange(LauncherProperties * props, int64t * range) { if(isSilent(props)) return; totalProgressSize->Low = range->Low; totalProgressSize->High = range->High; currentProgressSize->Low = 0; currentProgressSize->High = 0; lastCheckedStep = 0; SendMessage(hwndPB, PBM_SETRANGE, 0, MAKELPARAM(0, steps)); SendMessage(hwndPB, PBM_SETSTEP, 1, 0); } void hide(LauncherProperties * props, HWND hwnd) { if(!isSilent(props) && hwndMain != NULL && hwnd!=NULL ) { ShowWindow(hwnd, SW_HIDE); UpdateWindow(hwnd); } } void show(LauncherProperties * props, HWND hwnd) { if(!isSilent(props) && hwndMain != NULL && hwnd!=NULL ) { ShowWindow(hwnd, iCmdShowGlobal); UpdateWindow(hwnd); } } void setProgressTitleString(LauncherProperties * props, const WCHAR * message) { if(isSilent(props)) return; SetWindowTextW(hwndProgressTitle, message); UpdateWindow(hwndProgressTitle); UpdateWindow(hwndMain); } void setErrorTitleString(LauncherProperties * props, const WCHAR * message) { if(isSilent(props)) return; SetWindowTextW(hwndErrorTitle, message); UpdateWindow(hwndErrorTitle); UpdateWindow(hwndMain); } void setErrorDetailString(LauncherProperties * props, const WCHAR * message) { if(isSilent(props)) return; SetWindowTextW(hwndErrorDetail, message); UpdateWindow(hwndErrorDetail); UpdateWindow(hwndMain); } void setButtonString(LauncherProperties * props, const WCHAR * message) { if(isSilent(props)) return; SetWindowTextW(hwndButton, message); UpdateWindow(hwndButton); UpdateWindow(hwndMain); } void setMainWindowTitle(LauncherProperties * props, const WCHAR * message) { if(isSilent(props)) return; SetWindowTextW(hwndMain, message); UpdateWindow(hwndMain); } void closeLauncherWindows(LauncherProperties * props) { if(isSilent(props)) return; SendMessage(hwndMain, WM_CLOSE, 0, 0); } void hideLauncherWindows(LauncherProperties * props) { if(isSilent(props)) return; if(hwndMain != NULL) { ShowWindow(hwndMain, HIDE_WINDOW); UpdateWindow(hwndMain); } } void showLauncherWindows(LauncherProperties * props) { if(isSilent(props)) return; ShowWindow(hwndMain, iCmdShowGlobal); SetForegroundWindow(hwndMain); UpdateWindow(hwndMain); } void showMessageW(LauncherProperties * props, const WCHAR* message, const DWORD varArgsNumber, ...) { DWORD totalLength = getLengthW(message); va_list ap; DWORD counter=0; WCHAR * result = NULL; writeMessageA(props, OUTPUT_LEVEL_DEBUG, 0, showMessageTitle, 0); va_start(ap, varArgsNumber); while((counter++)<varArgsNumber) { WCHAR * arg = va_arg( ap, WCHAR * ); totalLength+=getLengthW(arg); } va_end(ap); result = newpWCHAR(totalLength + 1); va_start(ap, varArgsNumber); wvsprintfW(result, message, ap); va_end(ap); writeMessageW(props, OUTPUT_LEVEL_DEBUG, 0, result, 1); if(!isSilent(props)) { hideLauncherWindows(props); MessageBoxW(hwndMain, result, getI18nProperty(props, MSG_MESSAGEBOX_TITLE), MB_OK); } } /* void showMessageA(LauncherProperties * props, const char* message, const DWORD varArgsNumber, ...) { DWORD totalLength = getLengthA(message); va_list ap; DWORD counter=0; char * result = NULL; writeMessageA(props, OUTPUT_LEVEL_DEBUG, 0, showMessageTitle, 0); va_start(ap, varArgsNumber); while((counter++)<varArgsNumber) { char * arg = va_arg( ap, char * ); totalLength+=getLengthA(arg); } va_end(ap); result = newpChar(totalLength + 1); va_start(ap, varArgsNumber); vsprintf(result, message, ap); va_end(ap); writeMessageA(props, OUTPUT_LEVEL_DEBUG, 0, result, 1); if(!isSilent(props)) { char * prop = toChar(getI18nProperty(props, MSG_MESSAGEBOX_TITLE)); MessageBoxA(hwndMain, result, prop, MB_OK); FREE(prop); } } */ /* * WCHAR* GetStringFromStringTable( UINT uStringID ) { * WCHAR *pwchMem, *pwchCur; * UINT idRsrcBlk = uStringID / 16 + 1; * int strIndex = uStringID % 16; * HINSTANCE hModule = NULL; * HRSRC hResource = NULL; * int i=0; * LANGID lang = LANGIDFROMLCID(GetUserDefaultLCID()); * * hResource = FindResourceExW( GetModuleHandleW(NULL), (LPWSTR)RT_STRING, * MAKEINTRESOURCEW(idRsrcBlk), lang); * * if( hResource != NULL ) { * pwchMem = (WCHAR *)LoadResource( hModule, hResource ); * * if( pwchMem != NULL ) { * pwchCur = pwchMem; * for(i = 0; i<16; i++ ) { * if( *pwchCur ) { * int cchString = *pwchCur; // String size in characters. * pwchCur++; * if( i == strIndex ) { * WCHAR * tmp = appendStringNW(NULL, 0, pwchCur, cchString); * return tmp; * } * pwchCur += cchString; * } * else * pwchCur++; * } * } * } * return NULL; * * }*/ DWORD WINAPI launcherThread(void * ptr) { HANDLE * events = (HANDLE *) LocalAlloc(LPTR, sizeof(HANDLE)*2); DWORD result; events[0] = initializationSuccess; events[1] = initializationFailed; result = WaitForMultipleObjects(2, events, FALSE, INFINITE); FREE(events); if (result == WAIT_OBJECT_0) { LauncherProperties * props = (LauncherProperties*) ptr; processLauncher(props); SetEvent(closingWindowsConfirmed); closeLauncherWindows(props); } return 0; } void createLauncherThread(LauncherProperties *props) { DWORD threadId; if(CreateThread( NULL, 0, &launcherThread, (LPVOID) props, 0, &threadId )==NULL) { SetEvent(closingWindowsConfirmed); } } DWORD createGui(LauncherProperties* props, HINSTANCE hInstance, HINSTANCE hi, int nCmdShow) { if (!InitApplication(props, hInstance)) { SetEvent(initializationFailed); return 0; } else if (!InitInstance(props, hInstance, nCmdShow, & hwndMain)) { SetEvent(initializationFailed); return 0; } else { SetEvent(initializationSuccess); } return 1; } DWORD createEvents() { initializationSuccess = CreateEventW(NULL, TRUE, FALSE, NULL); if(initializationSuccess==NULL) { return 0; } initializationFailed = CreateEventW(NULL, TRUE, FALSE, NULL); if(initializationFailed==NULL) { return 0; } buttonPressed = CreateEventW(NULL, TRUE, FALSE, NULL); if(buttonPressed ==NULL) { return 0; } closingWindowsRequired = CreateEventW(NULL, TRUE, FALSE, NULL); if(closingWindowsRequired ==NULL) { return 0; } closingWindowsConfirmed = CreateEventW(NULL, TRUE, FALSE, NULL); if(closingWindowsConfirmed ==NULL) { return 0; } return 1; } int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hi, LPSTR lpCmdLine, int nCmdShow) { DWORD exitCode = 1; DWORD status = ERROR_OK; totalProgressSize = newint64_t(0,0); currentProgressSize = newint64_t(0,0); globalInstance = hInstance; UNREFERENCED_PARAMETER(lpCmdLine); initWow64(); if(is9x()) { MessageBoxA(0, "Windows 9X platform is not supported", "Message", MB_OK); status = EXIT_CODE_SYSTEM_ERROR; } else { if(!createEvents()) { status = EXIT_CODE_EVENTS_INITIALIZATION_ERROR; } else { LauncherProperties * props = createLauncherProperties(); createLauncherThread(props); if(!createGui(props, hInstance, hi, nCmdShow)) { status = EXIT_CODE_GUI_INITIALIZATION_ERROR; } else { messageLoop(props); WaitForSingleObject(closingWindowsConfirmed, INFINITE); } status = props->status; exitCode = props->exitCode; printStatus(props); freeLauncherProperties(&props); } } FREE(currentProgressSize); FREE(totalProgressSize); return (status==ERROR_OK) ? exitCode : status; } int WINAPI MyMain(void) { int exitCode; STARTUPINFO StartupInfo; StartupInfo.dwFlags = 0; GetStartupInfo( &StartupInfo ); exitCode = WinMain(GetModuleHandle(NULL), NULL, NULL, StartupInfo.dwFlags & STARTF_USESHOWWINDOW ? StartupInfo.wShowWindow : SW_SHOWDEFAULT); ExitProcess(exitCode); return exitCode; }
48cde13b5b1fef103eb2e3a563eb764bb927f9fe
cc13bdb0f445b8acf6bec24946fcfb5e854989b6
/Pods/BoringSSL-GRPC/src/crypto/bio/hexdump.c
e3c45f068ad133b409a07256bb32ebb060b1940c
[ "ISC", "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "MIT" ]
permissive
devMEremenko/XcodeBenchmark
59eaf0f7d6cdaead6338511431489d9d2bf0bbb5
3aaaa6aa4400a20513dd4b6fdb372c48b8c9e772
refs/heads/master
2023-09-04T08:37:51.014081
2023-07-25T23:37:37
2023-07-25T23:37:37
288,524,849
2,335
346
MIT
2023-09-08T16:52:16
2020-08-18T17:47:47
Swift
UTF-8
C
false
false
6,378
c
hexdump.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_grpc/bio.h> #include <limits.h> #include <string.h> #include "../internal.h" // hexdump_ctx contains the state of a hexdump. struct hexdump_ctx { BIO *bio; char right_chars[18]; // the contents of the right-hand side, ASCII dump. unsigned used; // number of bytes in the current line. size_t n; // number of bytes total. unsigned indent; }; static void hexbyte(char *out, uint8_t b) { static const char hextable[] = "0123456789abcdef"; out[0] = hextable[b>>4]; out[1] = hextable[b&0x0f]; } static char to_char(uint8_t b) { if (b < 32 || b > 126) { return '.'; } return b; } // hexdump_write adds |len| bytes of |data| to the current hex dump described by // |ctx|. static int hexdump_write(struct hexdump_ctx *ctx, const uint8_t *data, size_t len) { char buf[10]; unsigned l; // Output lines look like: // 00000010 2e 2f 30 31 32 33 34 35 36 37 38 ... 3c 3d // |./0123456789:;<=| // ^ offset ^ extra space ^ ASCII of line for (size_t i = 0; i < len; i++) { if (ctx->used == 0) { // The beginning of a line. BIO_indent(ctx->bio, ctx->indent, UINT_MAX); hexbyte(&buf[0], ctx->n >> 24); hexbyte(&buf[2], ctx->n >> 16); hexbyte(&buf[4], ctx->n >> 8); hexbyte(&buf[6], ctx->n); buf[8] = buf[9] = ' '; if (BIO_write(ctx->bio, buf, 10) < 0) { return 0; } } hexbyte(buf, data[i]); buf[2] = ' '; l = 3; if (ctx->used == 7) { // There's an additional space after the 8th byte. buf[3] = ' '; l = 4; } else if (ctx->used == 15) { // At the end of the line there's an extra space and the bar for the // right column. buf[3] = ' '; buf[4] = '|'; l = 5; } if (BIO_write(ctx->bio, buf, l) < 0) { return 0; } ctx->right_chars[ctx->used] = to_char(data[i]); ctx->used++; ctx->n++; if (ctx->used == 16) { ctx->right_chars[16] = '|'; ctx->right_chars[17] = '\n'; if (BIO_write(ctx->bio, ctx->right_chars, sizeof(ctx->right_chars)) < 0) { return 0; } ctx->used = 0; } } return 1; } // finish flushes any buffered data in |ctx|. static int finish(struct hexdump_ctx *ctx) { // See the comments in |hexdump| for the details of this format. const unsigned n_bytes = ctx->used; unsigned l; char buf[5]; if (n_bytes == 0) { return 1; } OPENSSL_memset(buf, ' ', 4); buf[4] = '|'; for (; ctx->used < 16; ctx->used++) { l = 3; if (ctx->used == 7) { l = 4; } else if (ctx->used == 15) { l = 5; } if (BIO_write(ctx->bio, buf, l) < 0) { return 0; } } ctx->right_chars[n_bytes] = '|'; ctx->right_chars[n_bytes + 1] = '\n'; if (BIO_write(ctx->bio, ctx->right_chars, n_bytes + 2) < 0) { return 0; } return 1; } int BIO_hexdump(BIO *bio, const uint8_t *data, size_t len, unsigned indent) { struct hexdump_ctx ctx; OPENSSL_memset(&ctx, 0, sizeof(ctx)); ctx.bio = bio; ctx.indent = indent; if (!hexdump_write(&ctx, data, len) || !finish(&ctx)) { return 0; } return 1; }
8a6a46a9147330de133faef609a10c5b9ff58ea7
8126d163872d9c2e56c6628f41e259d88168fc9f
/src/camera.h
524124a739320b03357265f1d772978b3fbca8bc
[ "BSD-2-Clause-Views", "BSD-2-Clause" ]
permissive
XProger/OpenLara
8c16a7cafdcd44c74356e0c6b7a1d0ab38c20191
d2e363db886b0aa2b666aa5d44a1beef321665d7
refs/heads/master
2023-08-31T14:13:08.805461
2023-06-28T22:54:59
2023-06-28T22:54:59
65,638,810
4,515
466
BSD-2-Clause
2023-09-10T18:01:09
2016-08-13T22:06:58
C
UTF-8
C
false
false
24,513
h
camera.h
#ifndef H_CAMERA #define H_CAMERA #include "core.h" #include "frustum.h" #include "controller.h" #include "character.h" #define CAM_SPEED_FOLLOW 12 #define CAM_SPEED_COMBAT 8 #define CAM_EYE_SEPARATION 16.0f #ifdef _OS_3DS #define CAM_FOCAL_LENGTH 512.0f #else #define CAM_FOCAL_LENGTH 1536.0f #endif #define CAM_OFFSET_FOLLOW (1024.0f + 512.0f) #ifdef _OS_BITTBOY #define CAM_OFFSET_COMBAT CAM_OFFSET_FOLLOW #else #define CAM_OFFSET_COMBAT (CAM_OFFSET_FOLLOW + 512.0f) #endif #define CAM_OFFSET_LOOK (512.0f) #define CAM_FOLLOW_ANGLE 0.0f #define CAM_LOOK_ANGLE_XMAX ( 55.0f * DEG2RAD) #define CAM_LOOK_ANGLE_XMIN (-75.0f * DEG2RAD) #define CAM_LOOK_ANGLE_Y ( 80.0f * DEG2RAD) #define SPECTATOR_TIMER 1.0f #define SPECTATOR_POS_SPEED 4096.0f #define SPECTATOR_ROT_SPEED PI #define SPECTATOR_SMOOTH 4.0f struct Camera : ICamera { IGame *game; TR::Level *level; Character *owner; Frustum *frustum; float fov, aspect, znear, zfar; vec3 lookAngle, targetAngle, viewAngle; mat4 mViewInv; float timer; int viewIndex; int viewIndexLast; Controller* viewTarget; Controller* viewTargetLast; Basis fpHead; int speed; bool smooth; bool spectator; vec3 specPos, specPosSmooth; vec3 specRot, specRotSmooth; float specTimer; int16 specRoom; Camera(IGame *game, Character *owner) : ICamera(), game(game), level(game->getLevel()), frustum(new Frustum()), timer(-1.0f), viewIndex(-1), viewIndexLast(-1), viewTarget(NULL) { this->owner = owner; reset(); spectator = false; specTimer = 0.0f; targetAngle = vec3(0.0f); } void reset() { Sound::listener[cameraIndex].matrix.identity(); Sound::listener[cameraIndex].matrix.translate(vec3(float(0x7FFFFFFF))); lookAngle = vec3(0.0f); changeView(false); if (level->isCutsceneLevel()) { mode = MODE_CUTSCENE; // room = level->entities[level->cutEntity].room; timer = 0.0f; } else mode = MODE_FOLLOW; eye.pos = owner->pos; eye.room = owner->getRoomIndex(); target.pos = owner->pos; target.room = eye.room; target.pos.y -= 1024; eye.pos.z -= 100; speed = CAM_SPEED_FOLLOW; smooth = false; } virtual ~Camera() { delete frustum; } virtual Controller* getOwner() { return owner; } virtual int getRoomIndex() const { return spectator ? specRoom : eye.room; } void updateListener(const mat4 &matrix) { Sound::flipped = level->state.flags.flipped; Sound::listener[cameraIndex].matrix = matrix; if (cameraIndex == 0) { // reverb effect only for main player TR::Room &r = level->rooms[getRoomIndex()]; float h = (r.info.yBottom - r.info.yTop) / 1024.0f; Sound::reverb.setRoomSize(vec3(float(r.xSectors), h, float(r.zSectors)) * 2.419f); // convert cells size into meters } } bool isUnderwater() { return level->rooms[getRoomIndex()].flags.water; } vec3 getViewPoint(bool useBounds = true) { Box box = owner->getBoundingBox(); vec3 pos = owner->pos; if (!useBounds) { if (owner->getEntity().type == TR::Entity::LARA && owner->stand != Character::STAND_UNDERWATER && owner->stand != Character::STAND_ONWATER) { pos.y -= 512.0f; } return pos; } vec3 center = box.center(); if (centerView) { pos.x = center.x; pos.z = center.z; } if (owner->getEntity().type == TR::Entity::LARA) { if (mode == MODE_LOOK) { Basis b = owner->getJoint(owner->jointHead); b.translate(vec3(0, -128, 0)); pos = b.pos; } else { if (mode != MODE_STATIC) pos.y = box.max.y + (box.min.y - box.max.y) * (3.0f / 4.0f); else pos.y = center.y; if (owner->stand != Character::STAND_UNDERWATER) pos.y -= 256; } } else { pos.y = center.y; } return pos; } virtual void doCutscene(const vec3 &pos, float rotation) { mode = Camera::MODE_CUTSCENE; level->cutMatrix.identity(); level->cutMatrix.rotateY(rotation); level->cutMatrix.setPos(pos); owner->animation.overrideMask = 0; timer = 0.0f; } bool updateFirstPerson() { Basis &joint = owner->getJoint(owner->jointHead); if (mode != MODE_CUTSCENE && !owner->useHeadAnimation()) { targetAngle.x += PI; targetAngle.z = -targetAngle.z; vec3 pos = joint.pos - joint.rot * vec3(0, 48, -24); quat rot = rotYXZ(targetAngle); fpHead.pos = pos; fpHead.rot = fpHead.rot.lerp(rot, smooth ? Core::deltaTime * 10.0f : 1.0f); } else { fpHead = joint; fpHead.rot = fpHead.rot * quat(vec3(1, 0, 0), PI); fpHead.pos -= joint.rot * vec3(0, 48, -24); } if (Core::settings.detail.stereo == Core::Settings::STEREO_VR) { fpHead.rot = quat(vec3(1, 0, 0), PI); } mViewInv.identity(); mViewInv.setRot(fpHead.rot); mViewInv.setPos(fpHead.pos); eye.pos = mViewInv.getPos(); eye.room = owner->getRoomIndex(); return true; } void clipSlide(float offset, float *toX, float *toZ, float targetX, float targetZ, const TR::Box &box) { TR::Box sqBox; sqBox.minZ = SQR(int(targetZ) - box.minZ); sqBox.maxZ = SQR(int(targetZ) - box.maxZ); sqBox.minX = SQR(int(targetX) - box.minX); sqBox.maxX = 0; // unused offset *= offset; int32 h = sqBox.minX + sqBox.minZ; if (h > 256 * 256) { *toX = float(box.minX); if (offset > h || offset < sqBox.minX) *toZ = float(box.minZ); else *toZ = targetZ + sqrtf(offset - sqBox.minX) * sign(box.minZ - box.maxZ); return; } h = sqBox.minX + sqBox.maxZ; if (h > 256 * 256) { *toX = float(box.minX); if (offset > h || offset < sqBox.minX) *toZ = float(box.maxZ); else *toZ = targetZ - sqrtf(offset - sqBox.minX) * sign(box.minZ - box.maxZ); return; } h = sqBox.maxX + sqBox.minZ; *toZ = float(box.minZ); if (offset > h || offset < sqBox.minZ) *toX = float(box.maxX); else *toX = targetX - sqrtf(offset - sqBox.minZ) * sign(box.minX - box.maxX); } void traceClip(float offset, TR::Location &to) { owner->trace(target, to); uint16 ownerBoxIndex = level->getSector(target.room, target.pos)->boxIndex; uint16 cameraBoxIndex = level->getSector(to.room, to.pos)->boxIndex; if (ownerBoxIndex == TR::NO_BOX) return; TR::Box cBox = level->boxes[ownerBoxIndex]; if (cameraBoxIndex != TR::NO_BOX && !level->boxes[ownerBoxIndex].contains(int(to.pos.x), int(to.pos.z))) cBox = level->boxes[cameraBoxIndex]; clipBox(to.room, to.pos, cBox); cBox.expand(-256); // transform coord system by clipping direction float *toX = &to.pos.x, *toZ = &to.pos.z, targetX = target.pos.x, targetZ = target.pos.z; if (to.pos.z < cBox.minZ || to.pos.z > cBox.maxZ) { swap(toX, toZ); swap(targetX, targetZ); swap(cBox.minX, cBox.minZ); swap(cBox.maxX, cBox.maxZ); } if (*toX >= cBox.minX && *toX <= cBox.maxX) return; if (*toX > cBox.maxX) swap(cBox.minX, cBox.maxX); if (*toZ > targetZ) swap(cBox.minZ, cBox.maxZ); clipSlide(offset, toX, toZ, targetX, targetZ, cBox); level->getSector(to.room, to.pos); } void clipBox(int16 roomIndex, const vec3 &pos, TR::Box &box) { const TR::Room &room = level->rooms[roomIndex]; int dx = int(pos.x) / 1024 * 1024; int dz = int(pos.z) / 1024 * 1024; TR::Box border; border.minX = dx - 1; border.minZ = dz - 1; border.maxX = dx + 1024; border.maxZ = dz + 1024; for (int i = 0; i < 4; i++) { vec3 p = pos; if (i / 2) p.x = float(border.sides[i]); else p.z = float(border.sides[i]); int16 index = roomIndex; if (level->isBlocked(index, p)) { box.sides[i] = border.sides[i]; continue; } int sx = clamp((int(p.x) - room.info.x) / 1024, 0, room.xSectors - 1); int sz = clamp((int(p.z) - room.info.z) / 1024, 0, room.zSectors - 1); int boxIndex = room.sectors[sz + sx * room.zSectors].boxIndex; if (boxIndex != TR::NO_BOX) { if (i % 2) box.sides[i] = max(box.sides[i], level->boxes[boxIndex].sides[i]); else box.sides[i] = min(box.sides[i], level->boxes[boxIndex].sides[i]); } } } void move(const TR::Location &to) { float t = (smooth && speed) ? (30.0f / speed * Core::deltaTime) : 1.0f; if (mode == MODE_LOOK) t = 20.0f * Core::deltaTime; eye.pos = eye.pos.lerp(to.pos, t); eye.room = to.room; TR::Room::Sector *sector = level->getSector(eye.room, eye.pos); float floor = level->getFloor(sector, eye.pos) - 256; if (to.pos.y >= floor && eye.pos.y >= floor) { owner->trace(target, eye); sector = level->getSector(eye.room, eye.pos); floor = level->getFloor(sector, eye.pos) - 256; } float ceiling = level->getCeiling(sector, eye.pos) + 256; if (floor < ceiling) floor = ceiling = (floor + ceiling) * 0.5f; if (eye.pos.y > floor) eye.pos.y = floor; if (eye.pos.y < ceiling) eye.pos.y = ceiling; } virtual void update() { if (shake > 0.0f) { shake = max(0.0f, shake - Core::deltaTime); Input::setJoyVibration(cameraIndex, clamp(shake, 0.0f, 1.0f), 0); } if (mode == MODE_FOLLOW) { speed = CAM_SPEED_FOLLOW; } if (mode == MODE_COMBAT) { speed = CAM_SPEED_COMBAT; } viewAngle = vec3(0.0f); if (mode == MODE_CUTSCENE) { ASSERT(level->cameraFramesCount && level->cameraFrames); timer += Core::deltaTime * 30.0f; float t = timer - int(timer); int indexA = min(int(timer), level->cameraFramesCount - 3); int indexB = min((indexA + 1), level->cameraFramesCount - 3); if (indexA == level->cameraFramesCount - 3) { if (level->isCutsceneLevel()) game->loadNextLevel(); else { Character *lara = (Character*)owner; if (lara->health > 0.0f) { mode = MODE_FOLLOW; return; } } } if (!spectator) { if (!firstPerson) { TR::CameraFrame *frameA = &level->cameraFrames[indexA]; TR::CameraFrame *frameB = &level->cameraFrames[indexB]; const float maxDelta = 512 * 512; float dp = (vec3(frameA->pos) - vec3(frameB->pos)).length2(); float dt = (vec3(frameA->target) - vec3(frameB->target)).length2(); if (dp > maxDelta || dt > maxDelta) { eye.pos = frameA->pos; target.pos = frameA->target; fov = frameA->fov / 32767.0f * 120.0f; } else { eye.pos = vec3(frameA->pos).lerp(frameB->pos, t); target.pos = vec3(frameA->target).lerp(frameB->target, t); fov = lerp(frameA->fov / 32767.0f * 120.0f, frameB->fov / 32767.0f * 120.0f, t); } eye.pos = level->cutMatrix * eye.pos; target.pos = level->cutMatrix * target.pos; mViewInv = mat4(eye.pos, target.pos, vec3(0, -1, 0)); } else updateFirstPerson(); } } else { if (Core::settings.detail.stereo == Core::Settings::STEREO_VR) { lookAngle = vec3(0.0f); } else { if (mode == MODE_LOOK) { float d = 3.0f * Core::deltaTime; vec2 L = Input::joy[Core::settings.controls[cameraIndex].joyIndex].L; L = L.normal() * max(0.0f, L.length() - INPUT_JOY_DZ_STICK) / (1.0f - INPUT_JOY_DZ_STICK); lookAngle.x += L.y * d; lookAngle.y += L.x * d; if (Input::state[cameraIndex][cUp]) lookAngle.x -= d; if (Input::state[cameraIndex][cDown]) lookAngle.x += d; if (Input::state[cameraIndex][cLeft]) lookAngle.y -= d; if (Input::state[cameraIndex][cRight]) lookAngle.y += d; lookAngle.x = clamp(lookAngle.x, CAM_LOOK_ANGLE_XMIN, CAM_LOOK_ANGLE_XMAX); lookAngle.y = clamp(lookAngle.y, -CAM_LOOK_ANGLE_Y, CAM_LOOK_ANGLE_Y); } else { if (lookAngle.x != CAM_FOLLOW_ANGLE || lookAngle.y != 0.0f) { float t = 10.0f * Core::deltaTime; lookAngle.x = lerp(clampAngle(lookAngle.x), CAM_FOLLOW_ANGLE, t); lookAngle.y = lerp(clampAngle(lookAngle.y), 0.0f, t); if (fabsf(lookAngle.x - CAM_FOLLOW_ANGLE) < EPS) lookAngle.x = CAM_FOLLOW_ANGLE; if (lookAngle.y < EPS) lookAngle.y = 0.0f; } if (!spectator) { vec2 R = Input::joy[Core::settings.controls[cameraIndex].joyIndex].R; R.x = sign(R.x) * max(0.0f, (fabsf(R.x) - INPUT_JOY_DZ_STICK) / (1.0f - INPUT_JOY_DZ_STICK)); R.y = sign(R.y) * max(0.0f, (fabsf(R.y) - INPUT_JOY_DZ_STICK) / (1.0f - INPUT_JOY_DZ_STICK)); viewAngle.x = -R.y * PI * 0.375f; viewAngle.y = R.x * PI * 0.5f; viewAngle.z = 0.0f; } } } targetAngle = owner->angle + lookAngle + viewAngle; targetAngle.x = clampAngle(targetAngle.x); targetAngle.y = clampAngle(targetAngle.y); targetAngle.x = clamp(targetAngle.x, -85 * DEG2RAD, +85 * DEG2RAD); Controller *lookAt = NULL; if (mode != MODE_STATIC) { if (!owner->viewTarget) { if (viewTarget && !viewTarget->flags.invisible) { vec3 targetVec = (viewTarget->pos - owner->pos).normal(); if (targetVec.dot(owner->getDir()) > 0.1f) { lookAt = viewTarget; } } } else { lookAt = owner->viewTarget; } owner->lookAt(lookAt); } else { lookAt = viewTarget; owner->lookAt(NULL); } if (!firstPerson && (mode == MODE_FOLLOW || mode == MODE_COMBAT)) { targetAngle += angle; } bool isStatic = (mode == MODE_STATIC || mode == MODE_HEAVY) && viewTarget; if (!firstPerson || isStatic) { TR::Location to; target.box = TR::NO_BOX; if (mode == MODE_STATIC && viewIndex > -1) { TR::Camera &cam = level->cameras[viewIndex]; to.room = cam.room; to.pos = vec3(float(cam.x), float(cam.y), float(cam.z)); if (lookAt) { target.room = lookAt->getRoomIndex(); target.pos = lookAt->getBoundingBox().center(); } else { target.room = owner->getRoomIndex(); target.pos = getViewPoint(false); } } else { vec3 p = getViewPoint(); target.room = owner->getRoomIndex(); target.pos.x = p.x; target.pos.z = p.z; if (smooth) target.pos.y += (p.y - target.pos.y) * Core::deltaTime * 5.0f; else target.pos.y = p.y; float offset; if (mode == MODE_LOOK) offset = CAM_OFFSET_LOOK; else offset = (mode == MODE_COMBAT ? CAM_OFFSET_COMBAT : CAM_OFFSET_FOLLOW); vec3 dir = vec3(targetAngle.x, targetAngle.y) * offset; to.pos = target.pos - dir; to.room = target.room; traceClip(offset, to); } move(to); mViewInv = mat4(eye.pos, target.pos, vec3(0, -1, 0)); } else updateFirstPerson(); } level->getSector(eye.room, eye.pos); smooth = true; viewIndexLast = viewIndex; if ((mode == MODE_STATIC || mode == MODE_HEAVY) && timer != 0.0f) { timer -= Core::deltaTime; if (timer <= 0.0f) { timer = -1.0f; smooth = false; } } if (mode != MODE_CUTSCENE && (mode != MODE_HEAVY || timer == -1.0f)) { mode = MODE_FOLLOW; viewIndex = -1; viewTargetLast = viewTarget; viewTarget = NULL; } Input::Joystick &specJoy = Input::joy[Core::settings.controls[cameraIndex].joyIndex]; if (specJoy.down[jkL] && specJoy.down[jkR]) { specTimer += Core::deltaTime; if (specTimer > SPECTATOR_TIMER) { firstPerson = false; spectator = !spectator; specTimer = 0.0f; specPos = eye.pos; specRot = targetAngle; specRot.z = PI; specRot.y += PI; specPosSmooth = specPos; specRotSmooth = specRot; specRoom = eye.room; } } else { specTimer = 0.0f; } if (spectator) { vec2 L = specJoy.L; vec2 R = specJoy.R; float U = specJoy.RT; float D = specJoy.LT; L = L.normal() * max(0.0f, L.length() - INPUT_JOY_DZ_STICK) / (1.0f - INPUT_JOY_DZ_STICK); R = R.normal() * max(0.0f, R.length() - INPUT_JOY_DZ_STICK) / (1.0f - INPUT_JOY_DZ_STICK); U = max(0.0f, U - INPUT_JOY_DZ_TRIGGER) / (1.0f - INPUT_JOY_DZ_TRIGGER); D = max(0.0f, D - INPUT_JOY_DZ_TRIGGER) / (1.0f - INPUT_JOY_DZ_TRIGGER); // apply dead zone if (L.length() < 0.05f) L = vec2(0.0f); if (R.length() < 0.05f) R = vec2(0.0f); if (U < 0.05) U = 0.0f; if (D < 0.05) D = 0.0f; vec3 dir = vec3(L.x, D - U, L.y) * (SPECTATOR_POS_SPEED * Core::deltaTime); vec2 rot = R * (SPECTATOR_ROT_SPEED * Core::deltaTime); vec3 d = vec3(specRot.x, specRot.y); vec3 r = d.cross(vec3(0.0f, 1.0f, 0.0f)).normal(); specPos += r * dir.x + vec3(0.0f, dir.y, 0.0f) + d * dir.z; specRot.x += rot.y; specRot.y += rot.x; specRot.x = clamp(specRot.x, -PIH, +PIH); specPosSmooth = specPosSmooth.lerp(specPos, SPECTATOR_SMOOTH * Core::deltaTime); specRotSmooth = specRotSmooth.lerp(specRot, SPECTATOR_SMOOTH * Core::deltaTime); mViewInv.identity(); mViewInv.translate(specPosSmooth); mViewInv.rotateY(specRotSmooth.y); mViewInv.rotateX(specRotSmooth.x); mViewInv.rotateZ(specRotSmooth.z); for (int i = 0; i < level->roomsCount; i++) { TR::Room &room = level->rooms[i]; if (room.contains(specPos)) { specRoom = i; break; } } level->getSector(specRoom, specPos); } if (Core::settings.detail.stereo == Core::Settings::STEREO_VR) updateListener(mViewInv * Input::hmd.head); else updateListener(mViewInv); } virtual void setup(bool calcMatrices) { if (calcMatrices) { Core::mViewInv = mViewInv; if (Core::settings.detail.stereo == Core::Settings::STEREO_VR) Core::mViewInv = Core::mViewInv * Input::hmd.eye[Core::eye == -1.0f ? 0 : 1]; if (shake > 0.0f) Core::mViewInv.setPos(Core::mViewInv.getPos() + vec3(0.0f, sinf(shake * PI * 7) * shake * 48.0f, 0.0f)); if (Core::settings.detail.stereo == Core::Settings::STEREO_SBS || Core::settings.detail.stereo == Core::Settings::STEREO_ANAGLYPH) { float separation = Core::eye * CAM_EYE_SEPARATION; #ifdef _OS_3DS if (firstPerson) { separation *= 0.125; } #endif Core::mViewInv.setPos(Core::mViewInv.getPos() + Core::mViewInv.right().xyz() * separation); } if (reflectPlane) { Core::mViewInv = mat4(*reflectPlane) * Core::mViewInv; Core::mViewInv.scale(vec3(1.0f, -1.0f, 1.0f)); } Core::mView = Core::mViewInv.inverseOrtho(); if (Core::settings.detail.stereo == Core::Settings::STEREO_VR) { Core::mProj = Input::hmd.proj[Core::eye == -1.0f ? 0 : 1]; } else { float eyeSep = (Core::eye * CAM_EYE_SEPARATION) * znear / CAM_FOCAL_LENGTH; Core::mProj = GAPI::perspective(fov, aspect, znear, zfar, eyeSep); } if (reflectPlane) { setOblique(*reflectPlane); } } Core::setViewProj(Core::mView, Core::mProj); Core::viewPos = Core::mViewInv.getPos(); // update room for eye (with HMD offset) if (Core::settings.detail.isStereo()) level->getSector(eye.room, Core::viewPos.xyz()); frustum->pos = Core::viewPos.xyz(); frustum->calcPlanes(Core::mViewProj); } void setOblique(const vec4 &clipPlane) { // http://www.terathon.com/code/oblique.html #ifdef _OS_WP8 Core::mProj.unrot90(); #endif vec4 p = Core::mViewInv.transpose() * clipPlane; vec4 q; q.x = (sign(p.x) + Core::mProj.e02) / Core::mProj.e00; q.y = (sign(p.y) + Core::mProj.e12) / Core::mProj.e11; q.z = -1.0f; q.w = (1.0f + Core::mProj.e22) / Core::mProj.e23; float f = GAPI::getProjRange() == mat4::PROJ_NEG_POS ? 2.0f : 1.0f; vec4 c = p * (f / p.dot(q)); Core::mProj.e20 = c.x; Core::mProj.e21 = c.y; Core::mProj.e22 = c.z + (f - 1.0f); Core::mProj.e23 = c.w; #ifdef _OS_WP8 Core::mProj.rot90(); #endif } void changeView(bool firstPerson) { this->firstPerson = firstPerson; if (firstPerson) smooth = false; fov = firstPerson ? 90.0f : 65.0f; znear = firstPerson ? 16.0f : 32.0f; zfar = 45.0f * 1024.0f; #ifdef _OS_PSP znear = 256.0f; #endif } }; #endif
2fe55d43f8f68a92cdd8eed89b8c7bbad96a3586
035660e8cc10571ebbd0d4393fef063bb7eb98f6
/src/boot_O2_g3/CIC6105.c
b45b193135881c2609f5976abdc7e45b0f83af60
[]
no_license
zeldaret/mm
f163a5e7c4314105777369fa7671ce9c2a99922a
4ae00e909e74044f05155683b49d2561f91de7ba
refs/heads/master
2023-08-06T07:22:04.912966
2023-08-04T20:36:03
2023-08-04T20:36:03
247,875,852
915
328
null
2023-09-14T11:48:59
2020-03-17T04:03:07
C
UTF-8
C
false
false
756
c
CIC6105.c
#include "global.h" #include "fault.h" UNK_TYPE4 D_8009BE30; UNK_TYPE4 D_8009BE34; FaultClient romInfoFaultClient; void CIC6105_Nop80081820(void) { } void CIC6105_Nop80081828(void) { } void CIC6105_PrintRomInfo(void) { FaultDrawer_DrawText(80, 200, "SP_STATUS %08x", HW_REG(SP_STATUS_REG, u32)); FaultDrawer_DrawText(40, 184, "ROM_F [Creator:%s]", gBuildTeam); FaultDrawer_DrawText(56, 192, "[Date:%s]", gBuildDate); } void CIC6105_AddRomInfoFaultPage(void) { Fault_AddClient(&romInfoFaultClient, (void*)CIC6105_PrintRomInfo, NULL, NULL); } void CIC6105_RemoveRomInfoFaultPage(void) { Fault_RemoveClient(&romInfoFaultClient); } void func_800818F4(void) { D_8009BE30 = *(u32*)0xA02FB1F4; D_8009BE34 = *(u32*)0xA02FE1C0; }
84ab89c615473e84fde7b579042ed3155b8ba352
76f7459a09acb9be2d52407132f5ff8955627da2
/frame/thread/bli_thread.h
9a6c3d1b5d9b18f2f8ab97c6eb95daedf3521ce7
[ "BSD-3-Clause" ]
permissive
flame/blis
448bc0ad139b726188129c5627c304274b41c3c1
6dcf7666eff14348e82fbc2750be4b199321e1b9
refs/heads/master
2023-09-01T14:56:11.920485
2023-08-27T19:18:57
2023-08-27T19:18:57
16,143,904
1,696
361
NOASSERTION
2023-08-27T19:18:58
2014-01-22T15:58:24
C
UTF-8
C
false
false
4,746
h
bli_thread.h
/* BLIS An object-based framework for developing high-performance BLAS-like libraries. Copyright (C) 2014, The University of Texas at Austin Copyright (C) 2016, Hewlett Packard Enterprise Development LP Copyright (C) 2018 - 2019, Advanced Micro Devices, Inc. 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(s) of the copyright holder(s) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef BLIS_THREAD_H #define BLIS_THREAD_H // Include thread communicator (thrcomm_t) object definitions and prototypes. #include "bli_thrcomm.h" // Include thread info (thrinfo_t) object definitions and prototypes. #include "bli_thrinfo.h" // Thread lanuch prototypes. Must go before including implementation headers. typedef void (*thread_func_t)( thrcomm_t* gl_comm, dim_t tid, const void* params ); // Include threading implementations. #include "bli_thread_openmp.h" #include "bli_thread_pthreads.h" #include "bli_thread_hpx.h" #include "bli_thread_single.h" // Initialization-related prototypes. int bli_thread_init( void ); int bli_thread_finalize( void ); // ----------------------------------------------------------------------------- BLIS_EXPORT_BLIS void bli_thread_launch ( timpl_t ti, dim_t nt, thread_func_t func, const void* params ); // ----------------------------------------------------------------------------- // Factorization and partitioning prototypes typedef struct { dim_t n; dim_t sqrt_n; dim_t f; } bli_prime_factors_t; void bli_prime_factorization( dim_t n, bli_prime_factors_t* factors ); dim_t bli_next_prime_factor( bli_prime_factors_t* factors ); bool bli_is_prime( dim_t n ); void bli_thread_partition_2x2 ( dim_t n_thread, dim_t work1, dim_t work2, dim_t* restrict nt1, dim_t* restrict nt2 ); void bli_thread_partition_2x2_slow ( dim_t n_thread, dim_t work1, dim_t work2, dim_t* restrict nt1, dim_t* restrict nt2 ); void bli_thread_partition_2x2_fast ( dim_t n_thread, dim_t work1, dim_t work2, dim_t* restrict nt1, dim_t* restrict nt2 ); // ----------------------------------------------------------------------------- dim_t bli_gcd( dim_t x, dim_t y ); dim_t bli_lcm( dim_t x, dim_t y ); dim_t bli_ipow( dim_t base, dim_t power ); // ----------------------------------------------------------------------------- BLIS_EXPORT_BLIS dim_t bli_thread_get_jc_nt( void ); BLIS_EXPORT_BLIS dim_t bli_thread_get_pc_nt( void ); BLIS_EXPORT_BLIS dim_t bli_thread_get_ic_nt( void ); BLIS_EXPORT_BLIS dim_t bli_thread_get_jr_nt( void ); BLIS_EXPORT_BLIS dim_t bli_thread_get_ir_nt( void ); BLIS_EXPORT_BLIS dim_t bli_thread_get_num_threads( void ); BLIS_EXPORT_BLIS timpl_t bli_thread_get_thread_impl( void ); BLIS_EXPORT_BLIS const char* bli_thread_get_thread_impl_str( timpl_t ti ); BLIS_EXPORT_BLIS void bli_thread_set_ways( dim_t jc, dim_t pc, dim_t ic, dim_t jr, dim_t ir ); BLIS_EXPORT_BLIS void bli_thread_set_num_threads( dim_t value ); BLIS_EXPORT_BLIS void bli_thread_set_thread_impl( timpl_t ti ); BLIS_EXPORT_BLIS void bli_thread_reset( void ); #endif
3c91c44f915e1a4b1a60dea1f20f4db91ec10e73
9ceacf33fd96913cac7ef15492c126d96cae6911
/sys/dev/pci/cs4280.c
837a15f658919b5a0cfa8766e11b7040ef961280
[]
no_license
openbsd/src
ab97ef834fd2d5a7f6729814665e9782b586c130
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
refs/heads/master
2023-09-02T18:54:56.624627
2023-09-02T15:16:12
2023-09-02T15:16:12
66,966,208
3,394
1,235
null
2023-08-08T02:42:25
2016-08-30T18:18:25
C
UTF-8
C
false
false
42,342
c
cs4280.c
/* $OpenBSD: cs4280.c,v 1.60 2022/10/26 20:19:08 kn Exp $ */ /* $NetBSD: cs4280.c,v 1.5 2000/06/26 04:56:23 simonb Exp $ */ /* * Copyright (c) 1999, 2000 Tatoku Ogaito. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Tatoku Ogaito * for the NetBSD Project. * 4. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Cirrus Logic CS4280 (and maybe CS461x) driver. * Data sheets can be found * http://www.cirrus.com/ftp/pubs/4280.pdf * http://www.cirrus.com/ftp/pubs/4297.pdf * ftp://ftp.alsa-project.org/pub/manuals/cirrus/embedded_audio_spec.pdf * ftp://ftp.alsa-project.org/pub/manuals/cirrus/embedded_audio_spec.doc */ /* * TODO * Implement MIDI * Joystick support */ #ifdef CS4280_DEBUG #ifndef MIDI_READY #define MIDI_READY #endif /* ! MIDI_READY */ #endif #ifdef MIDI_READY #include "midi.h" #endif #if defined(CS4280_DEBUG) #define DPRINTF(x) if (cs4280debug) printf x #define DPRINTFN(n,x) if (cs4280debug>(n)) printf x int cs4280debug = 0; #else #define DPRINTF(x) #define DPRINTFN(n,x) #endif #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/fcntl.h> #include <sys/malloc.h> #include <sys/device.h> #include <dev/pci/pcidevs.h> #include <dev/pci/pcivar.h> #include <dev/pci/cs4280reg.h> #include <sys/audioio.h> #include <dev/audio_if.h> #include <dev/ic/ac97.h> #include <machine/bus.h> #define CSCC_PCI_BA0 0x10 #define CSCC_PCI_BA1 0x14 struct cs4280_dma { bus_dmamap_t map; caddr_t addr; /* real dma buffer */ caddr_t dum; /* dummy buffer for audio driver */ bus_dma_segment_t segs[1]; int nsegs; size_t size; struct cs4280_dma *next; }; #define DMAADDR(p) ((p)->map->dm_segs[0].ds_addr) #define BUFADDR(p) ((void *)((p)->dum)) #define KERNADDR(p) ((void *)((p)->addr)) /* * Software state */ struct cs4280_softc { struct device sc_dev; pci_intr_handle_t * sc_ih; /* I/O (BA0) */ bus_space_tag_t ba0t; bus_space_handle_t ba0h; /* BA1 */ bus_space_tag_t ba1t; bus_space_handle_t ba1h; /* DMA */ bus_dma_tag_t sc_dmatag; struct cs4280_dma *sc_dmas; void (*sc_pintr)(void *); /* dma completion intr handler */ void *sc_parg; /* arg for sc_intr() */ char *sc_ps, *sc_pe, *sc_pn; int sc_pcount; int sc_pi; struct cs4280_dma *sc_pdma; char *sc_pbuf; #ifdef DIAGNOSTIC char sc_prun; #endif void (*sc_rintr)(void *); /* dma completion intr handler */ void *sc_rarg; /* arg for sc_intr() */ char *sc_rs, *sc_re, *sc_rn; int sc_rcount; int sc_ri; struct cs4280_dma *sc_rdma; char *sc_rbuf; int sc_rparam; /* record format */ #ifdef DIAGNOSTIC char sc_rrun; #endif #if NMIDI > 0 void (*sc_iintr)(void *, int); /* midi input ready handler */ void (*sc_ointr)(void *); /* midi output ready handler */ void *sc_arg; #endif u_int32_t pctl; u_int32_t cctl; struct ac97_codec_if *codec_if; struct ac97_host_if host_if; u_int16_t ac97_reg[CS4280_SAVE_REG_MAX + 1]; /* Save ac97 registers */ }; #define BA0READ4(sc, r) bus_space_read_4((sc)->ba0t, (sc)->ba0h, (r)) #define BA0WRITE4(sc, r, x) bus_space_write_4((sc)->ba0t, (sc)->ba0h, (r), (x)) #define BA1READ4(sc, r) bus_space_read_4((sc)->ba1t, (sc)->ba1h, (r)) #define BA1WRITE4(sc, r, x) bus_space_write_4((sc)->ba1t, (sc)->ba1h, (r), (x)) int cs4280_match(struct device *, void *, void *); void cs4280_attach(struct device *, struct device *, void *); int cs4280_activate(struct device *, int); void cs4280_attachhook(struct device *); int cs4280_intr(void *); void cs4280_reset(void *); int cs4280_download_image(struct cs4280_softc *); int cs4280_download(struct cs4280_softc *, const u_int32_t *, u_int32_t, u_int32_t); int cs4280_allocmem(struct cs4280_softc *, size_t, size_t, struct cs4280_dma *); int cs4280_freemem(struct cs4280_softc *, struct cs4280_dma *); #ifdef CS4280_DEBUG int cs4280_check_images(struct cs4280_softc *); int cs4280_checkimage(struct cs4280_softc *, u_int32_t *, u_int32_t, u_int32_t); #endif struct cfdriver clcs_cd = { NULL, "clcs", DV_DULL }; const struct cfattach clcs_ca = { sizeof(struct cs4280_softc), cs4280_match, cs4280_attach, NULL, cs4280_activate }; int cs4280_init(struct cs4280_softc *, int); int cs4280_init2(struct cs4280_softc *, int); int cs4280_open(void *, int); void cs4280_close(void *); int cs4280_set_params(void *, int, int, struct audio_params *, struct audio_params *); int cs4280_round_blocksize(void *, int); int cs4280_halt_output(void *); int cs4280_halt_input(void *); int cs4280_mixer_set_port(void *, mixer_ctrl_t *); int cs4280_mixer_get_port(void *, mixer_ctrl_t *); int cs4280_query_devinfo(void *addr, mixer_devinfo_t *dip); void *cs4280_malloc(void *, int, size_t, int, int); void cs4280_free(void *, void *, int); int cs4280_trigger_output(void *, void *, void *, int, void (*)(void *), void *, struct audio_params *); int cs4280_trigger_input(void *, void *, void *, int, void (*)(void *), void *, struct audio_params *); void cs4280_set_dac_rate(struct cs4280_softc *, int ); void cs4280_set_adc_rate(struct cs4280_softc *, int ); int cs4280_get_portnum_by_name(struct cs4280_softc *, char *, char *, char *); int cs4280_src_wait(struct cs4280_softc *); int cs4280_attach_codec(void *sc, struct ac97_codec_if *); int cs4280_read_codec(void *sc, u_int8_t a, u_int16_t *d); int cs4280_write_codec(void *sc, u_int8_t a, u_int16_t d); void cs4280_reset_codec(void *sc); void cs4280_clear_fifos(struct cs4280_softc *); #if NMIDI > 0 void cs4280_midi_close(void *); void cs4280_midi_getinfo(void *, struct midi_info *); int cs4280_midi_open(void *, int, void (*)(void *, int), void (*)(void *), void *); int cs4280_midi_output(void *, int); #endif const struct audio_hw_if cs4280_hw_if = { .open = cs4280_open, .close = cs4280_close, .set_params = cs4280_set_params, .round_blocksize = cs4280_round_blocksize, .halt_output = cs4280_halt_output, .halt_input = cs4280_halt_input, .set_port = cs4280_mixer_set_port, .get_port = cs4280_mixer_get_port, .query_devinfo = cs4280_query_devinfo, .allocm = cs4280_malloc, .freem = cs4280_free, .trigger_output = cs4280_trigger_output, .trigger_input = cs4280_trigger_input, }; #if NMIDI > 0 const struct midi_hw_if cs4280_midi_hw_if = { cs4280_midi_open, cs4280_midi_close, cs4280_midi_output, 0, /* flush */ cs4280_midi_getinfo, 0, /* ioctl */ }; #endif const struct pci_matchid cs4280_devices[] = { { PCI_VENDOR_CIRRUS, PCI_PRODUCT_CIRRUS_CS4280 }, { PCI_VENDOR_CIRRUS, PCI_PRODUCT_CIRRUS_CS4610 }, { PCI_VENDOR_CIRRUS, PCI_PRODUCT_CIRRUS_CS4615 }, }; int cs4280_match(struct device *parent, void *ma, void *aux) { return (pci_matchbyid((struct pci_attach_args *)aux, cs4280_devices, nitems(cs4280_devices))); } int cs4280_read_codec(void *sc_, u_int8_t add, u_int16_t *data) { struct cs4280_softc *sc = sc_; int n; DPRINTFN(5,("read_codec: add=0x%02x ", add)); /* * Make sure that there is not data sitting around from a previous * uncompleted access. */ BA0READ4(sc, CS4280_ACSDA); /* Set up AC97 control registers. */ BA0WRITE4(sc, CS4280_ACCAD, add); BA0WRITE4(sc, CS4280_ACCDA, 0); BA0WRITE4(sc, CS4280_ACCTL, ACCTL_RSTN | ACCTL_ESYN | ACCTL_VFRM | ACCTL_CRW | ACCTL_DCV ); if (cs4280_src_wait(sc) < 0) { printf("%s: AC97 read prob. (DCV!=0) for add=0x%02x\n", sc->sc_dev.dv_xname, add); return (1); } /* wait for valid status bit is active */ n = 0; while (!(BA0READ4(sc, CS4280_ACSTS) & ACSTS_VSTS)) { delay(1); while (++n > 1000) { printf("%s: AC97 read fail (VSTS==0) for add=0x%02x\n", sc->sc_dev.dv_xname, add); return (1); } } *data = BA0READ4(sc, CS4280_ACSDA); DPRINTFN(5,("data=0x%04x\n", *data)); return (0); } int cs4280_write_codec(void *sc_, u_int8_t add, u_int16_t data) { struct cs4280_softc *sc = sc_; DPRINTFN(5,("write_codec: add=0x%02x data=0x%04x\n", add, data)); BA0WRITE4(sc, CS4280_ACCAD, add); BA0WRITE4(sc, CS4280_ACCDA, data); BA0WRITE4(sc, CS4280_ACCTL, ACCTL_RSTN | ACCTL_ESYN | ACCTL_VFRM | ACCTL_DCV ); if (cs4280_src_wait(sc) < 0) { printf("%s: AC97 write fail (DCV!=0) for add=0x%02x data=" "0x%04x\n", sc->sc_dev.dv_xname, add, data); return (1); } return (0); } int cs4280_src_wait(struct cs4280_softc *sc) { int n; n = 0; while ((BA0READ4(sc, CS4280_ACCTL) & ACCTL_DCV)) { delay(1000); if (++n > 1000) return (-1); } return (0); } void cs4280_set_adc_rate(struct cs4280_softc *sc, int rate) { /* calculate capture rate: * * capture_coefficient_increment = -round(rate*128*65536/48000; * capture_phase_increment = floor(48000*65536*1024/rate); * cx = round(48000*65536*1024 - capture_phase_increment*rate); * cy = floor(cx/200); * capture_sample_rate_correction = cx - 200*cy; * capture_delay = ceil(24*48000/rate); * capture_num_triplets = floor(65536*rate/24000); * capture_group_length = 24000/GCD(rate, 24000); * where GCD means "Greatest Common Divisor". * * capture_coefficient_increment, capture_phase_increment and * capture_num_triplets are 32-bit signed quantities. * capture_sample_rate_correction and capture_group_length are * 16-bit signed quantities. * capture_delay is a 14-bit unsigned quantity. */ u_int32_t cci,cpi,cnt,cx,cy, tmp1; u_int16_t csrc, cgl, cdlay; /* XXX * Even though, embedded_audio_spec says capture rate range 11025 to * 48000, dhwiface.cpp says, * * "We can only decimate by up to a factor of 1/9th the hardware rate. * Return an error if an attempt is made to stray outside that limit." * * so assume range as 48000/9 to 48000 */ if (rate < 8000) rate = 8000; if (rate > 48000) rate = 48000; cx = rate << 16; cci = cx / 48000; cx -= cci * 48000; cx <<= 7; cci <<= 7; cci += cx / 48000; cci = - cci; cx = 48000 << 16; cpi = cx / rate; cx -= cpi * rate; cx <<= 10; cpi <<= 10; cy = cx / rate; cpi += cy; cx -= cy * rate; cy = cx / 200; csrc = cx - 200*cy; cdlay = ((48000 * 24) + rate - 1) / rate; #if 0 cdlay &= 0x3fff; /* make sure cdlay is 14-bit */ #endif cnt = rate << 16; cnt /= 24000; cgl = 1; for (tmp1 = 2; tmp1 <= 64; tmp1 *= 2) { if (((rate / tmp1) * tmp1) != rate) cgl *= 2; } if (((rate / 3) * 3) != rate) cgl *= 3; for (tmp1 = 5; tmp1 <= 125; tmp1 *= 5) { if (((rate / tmp1) * tmp1) != rate) cgl *= 5; } #if 0 /* XXX what manual says */ tmp1 = BA1READ4(sc, CS4280_CSRC) & ~CSRC_MASK; tmp1 |= csrc<<16; BA1WRITE4(sc, CS4280_CSRC, tmp1); #else /* suggested by cs461x.c (ALSA driver) */ BA1WRITE4(sc, CS4280_CSRC, CS4280_MK_CSRC(csrc, cy)); #endif #if 0 /* I am confused. The sample rate calculation section says * cci *is* 32-bit signed quantity but in the parameter description * section, CCI only assigned 16bit. * I believe size of the variable. */ tmp1 = BA1READ4(sc, CS4280_CCI) & ~CCI_MASK; tmp1 |= cci<<16; BA1WRITE4(sc, CS4280_CCI, tmp1); #else BA1WRITE4(sc, CS4280_CCI, cci); #endif tmp1 = BA1READ4(sc, CS4280_CD) & ~CD_MASK; tmp1 |= cdlay <<18; BA1WRITE4(sc, CS4280_CD, tmp1); BA1WRITE4(sc, CS4280_CPI, cpi); tmp1 = BA1READ4(sc, CS4280_CGL) & ~CGL_MASK; tmp1 |= cgl; BA1WRITE4(sc, CS4280_CGL, tmp1); BA1WRITE4(sc, CS4280_CNT, cnt); tmp1 = BA1READ4(sc, CS4280_CGC) & ~CGC_MASK; tmp1 |= cgl; BA1WRITE4(sc, CS4280_CGC, tmp1); } void cs4280_set_dac_rate(struct cs4280_softc *sc, int rate) { /* * playback rate may range from 8000Hz to 48000Hz * * play_phase_increment = floor(rate*65536*1024/48000) * px = round(rate*65536*1024 - play_phase_incremnt*48000) * py=floor(px/200) * play_sample_rate_correction = px - 200*py * * play_phase_increment is a 32bit signed quantity. * play_sample_rate_correction is a 16bit signed quantity. */ int32_t ppi; int16_t psrc; u_int32_t px, py; if (rate < 8000) rate = 8000; if (rate > 48000) rate = 48000; px = rate << 16; ppi = px/48000; px -= ppi*48000; ppi <<= 10; px <<= 10; py = px / 48000; ppi += py; px -= py*48000; py = px/200; px -= py*200; psrc = px; #if 0 /* what manual says */ px = BA1READ4(sc, CS4280_PSRC) & ~PSRC_MASK; BA1WRITE4(sc, CS4280_PSRC, ( ((psrc<<16) & PSRC_MASK) | px )); #else /* suggested by cs461x.c (ALSA driver) */ BA1WRITE4(sc, CS4280_PSRC, CS4280_MK_PSRC(psrc,py)); #endif BA1WRITE4(sc, CS4280_PPI, ppi); } void cs4280_attachhook(struct device *self) { struct cs4280_softc *sc = (struct cs4280_softc *)self; mixer_ctrl_t ctl; /* Initialization */ if (cs4280_init2(sc, 1) != 0) return; printf("%s: firmware loaded\n", sc->sc_dev.dv_xname); /* Turn mute off of DAC, CD and master volumes by default */ ctl.type = AUDIO_MIXER_ENUM; ctl.un.ord = 0; /* off */ ctl.dev = cs4280_get_portnum_by_name(sc, AudioCoutputs, AudioNmaster, AudioNmute); cs4280_mixer_set_port(sc, &ctl); ctl.dev = cs4280_get_portnum_by_name(sc, AudioCinputs, AudioNdac, AudioNmute); cs4280_mixer_set_port(sc, &ctl); ctl.dev = cs4280_get_portnum_by_name(sc, AudioCinputs, AudioNcd, AudioNmute); cs4280_mixer_set_port(sc, &ctl); audio_attach_mi(&cs4280_hw_if, sc, NULL, &sc->sc_dev); #if NMIDI > 0 midi_attach_mi(&cs4280_midi_hw_if, sc, &sc->sc_dev); #endif } void cs4280_attach(struct device *parent, struct device *self, void *aux) { struct cs4280_softc *sc = (struct cs4280_softc *) self; struct pci_attach_args *pa = (struct pci_attach_args *) aux; pci_chipset_tag_t pc = pa->pa_pc; char const *intrstr; pci_intr_handle_t ih; u_int32_t mem; /* Map I/O register */ if (pci_mapreg_map(pa, CSCC_PCI_BA0, PCI_MAPREG_TYPE_MEM | PCI_MAPREG_MEM_TYPE_32BIT, 0, &sc->ba0t, &sc->ba0h, NULL, NULL, 0)) { printf(": can't map BA0 space\n"); return; } if (pci_mapreg_map(pa, CSCC_PCI_BA1, PCI_MAPREG_TYPE_MEM | PCI_MAPREG_MEM_TYPE_32BIT, 0, &sc->ba1t, &sc->ba1h, NULL, NULL, 0)) { printf(": can't map BA1 space\n"); return; } sc->sc_dmatag = pa->pa_dmat; /* Get out of power save mode if needed. */ pci_set_powerstate(pc, pa->pa_tag, PCI_PMCSR_STATE_D0); /* LATENCY_TIMER setting */ mem = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_BHLC_REG); if ( PCI_LATTIMER(mem) < 32 ) { mem &= 0xffff00ff; mem |= 0x00002000; pci_conf_write(pa->pa_pc, pa->pa_tag, PCI_BHLC_REG, mem); } /* Map and establish the interrupt. */ if (pci_intr_map(pa, &ih)) { printf(": couldn't map interrupt\n"); return; } intrstr = pci_intr_string(pc, ih); sc->sc_ih = pci_intr_establish(pc, ih, IPL_AUDIO | IPL_MPSAFE, cs4280_intr, sc, sc->sc_dev.dv_xname); if (sc->sc_ih == NULL) { printf(": couldn't establish interrupt"); if (intrstr != NULL) printf(" at %s", intrstr); printf("\n"); return; } printf(": %s\n", intrstr); /* Initialization */ if (cs4280_init(sc, 1) != 0) return; config_mountroot(self, cs4280_attachhook); /* AC 97 attachment */ sc->host_if.arg = sc; sc->host_if.attach = cs4280_attach_codec; sc->host_if.read = cs4280_read_codec; sc->host_if.write = cs4280_write_codec; sc->host_if.reset = cs4280_reset_codec; if (ac97_attach(&sc->host_if) != 0) { printf("%s: ac97_attach failed\n", sc->sc_dev.dv_xname); return; } } int cs4280_intr(void *p) { /* * XXX * * Since CS4280 has only 4kB dma buffer and * interrupt occurs every 2kB block, I create dummy buffer * which returns to audio driver and actual dma buffer * using in DMA transfer. * * * ring buffer in audio.c is pointed by BUFADDR * <------ ring buffer size == 64kB ------> * <-----> blksize == 2048*(sc->sc_[pr]count) kB * |= = = =|= = = =|= = = =|= = = =|= = = =| * | | | | | | <- call audio_intp every * sc->sc_[pr]_count time. * * actual dma buffer is pointed by KERNADDR * <-> dma buffer size = 4kB * |= =| * * */ struct cs4280_softc *sc = p; u_int32_t intr, mem; char * empty_dma; int handled = 0; mtx_enter(&audio_lock); /* grab interrupt register then clear it */ intr = BA0READ4(sc, CS4280_HISR); BA0WRITE4(sc, CS4280_HICR, HICR_CHGM | HICR_IEV); /* Playback Interrupt */ if (intr & HISR_PINT) { handled = 1; mem = BA1READ4(sc, CS4280_PFIE); BA1WRITE4(sc, CS4280_PFIE, (mem & ~PFIE_PI_MASK) | PFIE_PI_DISABLE); if (sc->sc_pintr) { if ((sc->sc_pi%sc->sc_pcount) == 0) sc->sc_pintr(sc->sc_parg); } else { printf("unexpected play intr\n"); } /* copy buffer */ ++sc->sc_pi; empty_dma = sc->sc_pdma->addr; if (sc->sc_pi&1) empty_dma += CS4280_ICHUNK; memcpy(empty_dma, sc->sc_pn, CS4280_ICHUNK); sc->sc_pn += CS4280_ICHUNK; if (sc->sc_pn >= sc->sc_pe) sc->sc_pn = sc->sc_ps; BA1WRITE4(sc, CS4280_PFIE, mem); } /* Capture Interrupt */ if (intr & HISR_CINT) { int i; int16_t rdata; handled = 1; mem = BA1READ4(sc, CS4280_CIE); BA1WRITE4(sc, CS4280_CIE, (mem & ~CIE_CI_MASK) | CIE_CI_DISABLE); ++sc->sc_ri; empty_dma = sc->sc_rdma->addr; if ((sc->sc_ri&1) == 0) empty_dma += CS4280_ICHUNK; /* * XXX * I think this audio data conversion should be * happened in upper layer, but I put this here * since there is no conversion function available. */ switch(sc->sc_rparam) { case CF_16BIT_STEREO: /* just copy it */ memcpy(sc->sc_rn, empty_dma, CS4280_ICHUNK); sc->sc_rn += CS4280_ICHUNK; break; case CF_16BIT_MONO: for (i = 0; i < 512; i++) { rdata = *((int16_t *)empty_dma)>>1; empty_dma += 2; rdata += *((int16_t *)empty_dma)>>1; empty_dma += 2; *((int16_t *)sc->sc_rn) = rdata; sc->sc_rn += 2; } break; case CF_8BIT_STEREO: for (i = 0; i < 512; i++) { rdata = *((int16_t*)empty_dma); empty_dma += 2; *sc->sc_rn++ = rdata >> 8; rdata = *((int16_t*)empty_dma); empty_dma += 2; *sc->sc_rn++ = rdata >> 8; } break; case CF_8BIT_MONO: for (i = 0; i < 512; i++) { rdata = *((int16_t*)empty_dma) >>1; empty_dma += 2; rdata += *((int16_t*)empty_dma) >>1; empty_dma += 2; *sc->sc_rn++ = rdata >>8; } break; default: /* Should not reach here */ printf("unknown sc->sc_rparam: %d\n", sc->sc_rparam); } if (sc->sc_rn >= sc->sc_re) sc->sc_rn = sc->sc_rs; BA1WRITE4(sc, CS4280_CIE, mem); if (sc->sc_rintr) { if ((sc->sc_ri%(sc->sc_rcount)) == 0) sc->sc_rintr(sc->sc_rarg); } else { printf("unexpected record intr\n"); } } #if NMIDI > 0 /* Midi port Interrupt */ if (intr & HISR_MIDI) { int data; handled = 1; DPRINTF(("i: %d: ", BA0READ4(sc, CS4280_MIDSR))); /* Read the received data */ while ((sc->sc_iintr != NULL) && ((BA0READ4(sc, CS4280_MIDSR) & MIDSR_RBE) == 0)) { data = BA0READ4(sc, CS4280_MIDRP) & MIDRP_MASK; DPRINTF(("r:%x\n",data)); sc->sc_iintr(sc->sc_arg, data); } /* Write the data */ #if 1 /* XXX: * It seems "Transmit Buffer Full" never activate until EOI * is delivered. Shall I throw EOI top of this routine ? */ if ((BA0READ4(sc, CS4280_MIDSR) & MIDSR_TBF) == 0) { DPRINTF(("w: ")); if (sc->sc_ointr != NULL) sc->sc_ointr(sc->sc_arg); } #else while ((sc->sc_ointr != NULL) && ((BA0READ4(sc, CS4280_MIDSR) & MIDSR_TBF) == 0)) { DPRINTF(("w: ")); sc->sc_ointr(sc->sc_arg); } #endif DPRINTF(("\n")); } #endif mtx_leave(&audio_lock); return handled; } /* Download Processor Code and Data image */ int cs4280_download(struct cs4280_softc *sc, const u_int32_t *src, u_int32_t offset, u_int32_t len) { u_int32_t ctr; #ifdef CS4280_DEBUG u_int32_t con, data; u_int8_t c0,c1,c2,c3; #endif if ((offset&3) || (len&3)) return (-1); len /= sizeof(u_int32_t); for (ctr = 0; ctr < len; ctr++) { /* XXX: * I cannot confirm this is the right thing or not * on BIG-ENDIAN machines. */ BA1WRITE4(sc, offset+ctr*4, htole32(*(src+ctr))); #ifdef CS4280_DEBUG data = htole32(*(src+ctr)); c0 = bus_space_read_1(sc->ba1t, sc->ba1h, offset+ctr*4+0); c1 = bus_space_read_1(sc->ba1t, sc->ba1h, offset+ctr*4+1); c2 = bus_space_read_1(sc->ba1t, sc->ba1h, offset+ctr*4+2); c3 = bus_space_read_1(sc->ba1t, sc->ba1h, offset+ctr*4+3); con = ( (c3<<24) | (c2<<16) | (c1<<8) | c0 ); if (data != con ) { printf("0x%06x: write=0x%08x read=0x%08x\n", offset+ctr*4, data, con); return (-1); } #endif } return (0); } struct BA1struct *BA1Struct; int cs4280_download_image(struct cs4280_softc *sc) { int idx, err = 0; u_int32_t offset = 0; static u_char *cs4280_firmware; static size_t cs4280_firmwarelen; if (cs4280_firmware == NULL) { err = loadfirmware("cs4280", &cs4280_firmware, &cs4280_firmwarelen); if (err) return (err); } BA1Struct = (struct BA1struct *)cs4280_firmware; for (idx = 0; idx < BA1_MEMORY_COUNT; ++idx) { err = cs4280_download(sc, &BA1Struct->map[offset], BA1Struct->memory[idx].offset, BA1Struct->memory[idx].size); if (err != 0) { printf("%s: load_image failed at %d\n", sc->sc_dev.dv_xname, idx); return (-1); } offset += BA1Struct->memory[idx].size / sizeof(u_int32_t); } return (err); } #ifdef CS4280_DEBUG int cs4280_checkimage(struct cs4280_softc *sc, u_int32_t *src, u_int32_t offset, u_int32_t len) { u_int32_t ctr, data; int err = 0; if ((offset&3) || (len&3)) return -1; len /= sizeof(u_int32_t); for (ctr = 0; ctr < len; ctr++) { /* I cannot confirm this is the right thing * on BIG-ENDIAN machines */ data = BA1READ4(sc, offset+ctr*4); if (data != htole32(*(src+ctr))) { printf("0x%06x: 0x%08x(0x%08x)\n", offset+ctr*4, data, *(src+ctr)); *(src+ctr) = data; ++err; } } return (err); } int cs4280_check_images(struct cs4280_softc *sc) { int idx, err; u_int32_t offset = 0; err = 0; /*for (idx=0; idx < BA1_MEMORY_COUNT; ++idx) { */ for (idx = 0; idx < 1; ++idx) { err = cs4280_checkimage(sc, &BA1Struct->map[offset], BA1Struct->memory[idx].offset, BA1Struct->memory[idx].size); if (err != 0) { printf("%s: check_image failed at %d\n", sc->sc_dev.dv_xname, idx); } offset += BA1Struct->memory[idx].size / sizeof(u_int32_t); } return (err); } #endif int cs4280_attach_codec(void *sc_, struct ac97_codec_if *codec_if) { struct cs4280_softc *sc = sc_; sc->codec_if = codec_if; return (0); } void cs4280_reset_codec(void *sc_) { struct cs4280_softc *sc = sc_; int n; /* Reset codec */ BA0WRITE4(sc, CS4280_ACCTL, 0); delay(100); /* delay 100us */ BA0WRITE4(sc, CS4280_ACCTL, ACCTL_RSTN); /* * It looks like we do the following procedure, too */ /* Enable AC-link sync generation */ BA0WRITE4(sc, CS4280_ACCTL, ACCTL_ESYN | ACCTL_RSTN); delay(50*1000); /* XXX delay 50ms */ /* Assert valid frame signal */ BA0WRITE4(sc, CS4280_ACCTL, ACCTL_VFRM | ACCTL_ESYN | ACCTL_RSTN); /* Wait for valid AC97 input slot */ n = 0; while (BA0READ4(sc, CS4280_ACISV) != (ACISV_ISV3 | ACISV_ISV4)) { delay(1000); if (++n > 1000) { printf("reset_codec: AC97 inputs slot ready timeout\n"); return; } } } /* Processor Soft Reset */ void cs4280_reset(void *sc_) { struct cs4280_softc *sc = sc_; /* Set RSTSP bit in SPCR (also clear RUN, RUNFR, and DRQEN) */ BA1WRITE4(sc, CS4280_SPCR, SPCR_RSTSP); delay(100); /* Clear RSTSP bit in SPCR */ BA1WRITE4(sc, CS4280_SPCR, 0); /* enable DMA request */ BA1WRITE4(sc, CS4280_SPCR, SPCR_DRQEN); } int cs4280_open(void *addr, int flags) { return (0); } void cs4280_close(void *addr) { struct cs4280_softc *sc = addr; /* XXX: already called in audio_close() */ cs4280_halt_output(sc); cs4280_halt_input(sc); sc->sc_pintr = 0; sc->sc_rintr = 0; } int cs4280_set_params(void *addr, int setmode, int usemode, struct audio_params *play, struct audio_params *rec) { struct cs4280_softc *sc = addr; struct audio_params *p; int mode; for (mode = AUMODE_RECORD; mode != -1; mode = mode == AUMODE_RECORD ? AUMODE_PLAY : -1 ) { if ((setmode & mode) == 0) continue; p = mode == AUMODE_PLAY ? play : rec; if (p == play) { DPRINTFN(5,("play: sample=%ld precision=%d channels=%d\n", p->sample_rate, p->precision, p->channels)); } else { DPRINTFN(5,("rec: sample=%ld precision=%d channels=%d\n", p->sample_rate, p->precision, p->channels)); } /* play back data format may be 8- or 16-bit and * either stereo or mono. * playback rate may range from 8000Hz to 48000Hz * * capture data format must be 16bit stereo * and sample rate range from 11025Hz to 48000Hz. * * XXX: it looks like to work with 8000Hz, * although data sheets say lower limit is * 11025 Hz. */ if (p->sample_rate < 8000) p->sample_rate = 8000; if (p->sample_rate > 48000) p->sample_rate = 48000; if (p->precision > 16) p->precision = 16; if (p->channels > 2) p->channels = 2; /* capturing data is slinear */ switch (p->encoding) { case AUDIO_ENCODING_SLINEAR_LE: break; default: return (EINVAL); } p->bps = AUDIO_BPS(p->precision); p->msb = 1; } /* set sample rate */ cs4280_set_dac_rate(sc, play->sample_rate); cs4280_set_adc_rate(sc, rec->sample_rate); return (0); } int cs4280_round_blocksize(void *hdl, int blk) { return (blk < CS4280_ICHUNK ? CS4280_ICHUNK : blk & -CS4280_ICHUNK); } int cs4280_mixer_get_port(void *addr, mixer_ctrl_t *cp) { struct cs4280_softc *sc = addr; return (sc->codec_if->vtbl->mixer_get_port(sc->codec_if, cp)); } int cs4280_query_devinfo(void *addr, mixer_devinfo_t *dip) { struct cs4280_softc *sc = addr; return (sc->codec_if->vtbl->query_devinfo(sc->codec_if, dip)); } int cs4280_get_portnum_by_name(struct cs4280_softc *sc, char *class, char *device, char *qualifier) { return (sc->codec_if->vtbl->get_portnum_by_name(sc->codec_if, class, device, qualifier)); } int cs4280_halt_output(void *addr) { struct cs4280_softc *sc = addr; u_int32_t mem; mtx_enter(&audio_lock); mem = BA1READ4(sc, CS4280_PCTL); BA1WRITE4(sc, CS4280_PCTL, mem & ~PCTL_MASK); #ifdef DIAGNOSTIC sc->sc_prun = 0; #endif mtx_leave(&audio_lock); return (0); } int cs4280_halt_input(void *addr) { struct cs4280_softc *sc = addr; u_int32_t mem; mtx_enter(&audio_lock); mem = BA1READ4(sc, CS4280_CCTL); BA1WRITE4(sc, CS4280_CCTL, mem & ~CCTL_MASK); #ifdef DIAGNOSTIC sc->sc_rrun = 0; #endif mtx_leave(&audio_lock); return (0); } int cs4280_mixer_set_port(void *addr, mixer_ctrl_t *cp) { struct cs4280_softc *sc = addr; int val; val = sc->codec_if->vtbl->mixer_set_port(sc->codec_if, cp); DPRINTFN(3,("mixer_set_port: val=%d\n", val)); return (val); } int cs4280_freemem(struct cs4280_softc *sc, struct cs4280_dma *p) { bus_dmamap_unload(sc->sc_dmatag, p->map); bus_dmamap_destroy(sc->sc_dmatag, p->map); bus_dmamem_unmap(sc->sc_dmatag, p->addr, p->size); bus_dmamem_free(sc->sc_dmatag, p->segs, p->nsegs); return (0); } int cs4280_allocmem(struct cs4280_softc *sc, size_t size, size_t align, struct cs4280_dma *p) { int error; /* XXX */ p->size = size; error = bus_dmamem_alloc(sc->sc_dmatag, p->size, align, 0, p->segs, sizeof(p->segs)/sizeof(p->segs[0]), &p->nsegs, BUS_DMA_NOWAIT); if (error) { printf("%s: unable to allocate dma, error=%d\n", sc->sc_dev.dv_xname, error); return (error); } error = bus_dmamem_map(sc->sc_dmatag, p->segs, p->nsegs, p->size, &p->addr, BUS_DMA_NOWAIT|BUS_DMA_COHERENT); if (error) { printf("%s: unable to map dma, error=%d\n", sc->sc_dev.dv_xname, error); goto free; } error = bus_dmamap_create(sc->sc_dmatag, p->size, 1, p->size, 0, BUS_DMA_NOWAIT, &p->map); if (error) { printf("%s: unable to create dma map, error=%d\n", sc->sc_dev.dv_xname, error); goto unmap; } error = bus_dmamap_load(sc->sc_dmatag, p->map, p->addr, p->size, NULL, BUS_DMA_NOWAIT); if (error) { printf("%s: unable to load dma map, error=%d\n", sc->sc_dev.dv_xname, error); goto destroy; } return (0); destroy: bus_dmamap_destroy(sc->sc_dmatag, p->map); unmap: bus_dmamem_unmap(sc->sc_dmatag, p->addr, p->size); free: bus_dmamem_free(sc->sc_dmatag, p->segs, p->nsegs); return (error); } void * cs4280_malloc(void *addr, int direction, size_t size, int pool, int flags) { struct cs4280_softc *sc = addr; struct cs4280_dma *p; caddr_t q; int error; DPRINTFN(5,("cs4280_malloc: size=%d pool=%d flags=%d\n", size, pool, flags)); q = malloc(size, pool, flags); if (!q) return (0); p = malloc(sizeof(*p), pool, flags); if (!p) { free(q,pool, 0); return (0); } /* * cs4280 has fixed 4kB buffer */ error = cs4280_allocmem(sc, CS4280_DCHUNK, CS4280_DALIGN, p); if (error) { free(q, pool, 0); free(p, pool, 0); return (0); } p->next = sc->sc_dmas; sc->sc_dmas = p; p->dum = q; /* return to audio driver */ return (p->dum); } void cs4280_free(void *addr, void *ptr, int pool) { struct cs4280_softc *sc = addr; struct cs4280_dma **pp, *p; for (pp = &sc->sc_dmas; (p = *pp) != NULL; pp = &p->next) { if (BUFADDR(p) == ptr) { cs4280_freemem(sc, p); *pp = p->next; free(p->dum, pool, 0); free(p, pool, 0); return; } } } int cs4280_trigger_output(void *addr, void *start, void *end, int blksize, void (*intr)(void *), void *arg, struct audio_params *param) { struct cs4280_softc *sc = addr; u_int32_t pfie, pctl, mem, pdtc; struct cs4280_dma *p; #ifdef DIAGNOSTIC if (sc->sc_prun) printf("cs4280_trigger_output: already running\n"); sc->sc_prun = 1; #endif DPRINTF(("cs4280_trigger_output: sc=%p start=%p end=%p " "blksize=%d intr=%p(%p)\n", addr, start, end, blksize, intr, arg)); sc->sc_pintr = intr; sc->sc_parg = arg; /* stop playback DMA */ mem = BA1READ4(sc, CS4280_PCTL); BA1WRITE4(sc, CS4280_PCTL, mem & ~PCTL_MASK); /* setup PDTC */ pdtc = BA1READ4(sc, CS4280_PDTC); pdtc &= ~PDTC_MASK; pdtc |= CS4280_MK_PDTC(param->precision * param->channels); BA1WRITE4(sc, CS4280_PDTC, pdtc); DPRINTF(("param: precision=%d channels=%d encoding=%d\n", param->precision, param->channels, param->encoding)); for (p = sc->sc_dmas; p != NULL && BUFADDR(p) != start; p = p->next) ; if (p == NULL) { printf("cs4280_trigger_output: bad addr %p\n", start); return (EINVAL); } if (DMAADDR(p) % CS4280_DALIGN != 0 ) { printf("cs4280_trigger_output: DMAADDR(p)=0x%lx does not start" "4kB align\n", DMAADDR(p)); return (EINVAL); } sc->sc_pcount = blksize / CS4280_ICHUNK; /* CS4280_ICHUNK is fixed hardware blksize*/ sc->sc_ps = (char *)start; sc->sc_pe = (char *)end; sc->sc_pdma = p; sc->sc_pbuf = KERNADDR(p); sc->sc_pi = 0; sc->sc_pn = sc->sc_ps; if (blksize >= CS4280_DCHUNK) { sc->sc_pn = sc->sc_ps + CS4280_DCHUNK; memcpy(sc->sc_pbuf, start, CS4280_DCHUNK); ++sc->sc_pi; } else { sc->sc_pn = sc->sc_ps + CS4280_ICHUNK; memcpy(sc->sc_pbuf, start, CS4280_ICHUNK); } /* initiate playback dma */ mtx_enter(&audio_lock); BA1WRITE4(sc, CS4280_PBA, DMAADDR(p)); /* set PFIE */ pfie = BA1READ4(sc, CS4280_PFIE) & ~PFIE_MASK; if (param->precision == 8) pfie |= PFIE_8BIT; if (param->channels == 1) pfie |= PFIE_MONO; if (param->encoding == AUDIO_ENCODING_ULINEAR_BE || param->encoding == AUDIO_ENCODING_SLINEAR_BE) pfie |= PFIE_SWAPPED; if (param->encoding == AUDIO_ENCODING_ULINEAR_BE || param->encoding == AUDIO_ENCODING_ULINEAR_LE) pfie |= PFIE_UNSIGNED; BA1WRITE4(sc, CS4280_PFIE, pfie | PFIE_PI_ENABLE); cs4280_set_dac_rate(sc, param->sample_rate); pctl = BA1READ4(sc, CS4280_PCTL) & ~PCTL_MASK; pctl |= sc->pctl; BA1WRITE4(sc, CS4280_PCTL, pctl); mtx_leave(&audio_lock); return (0); } int cs4280_trigger_input(void *addr, void *start, void *end, int blksize, void (*intr)(void *), void *arg, struct audio_params *param) { struct cs4280_softc *sc = addr; u_int32_t cctl, cie; struct cs4280_dma *p; #ifdef DIAGNOSTIC if (sc->sc_rrun) printf("cs4280_trigger_input: already running\n"); sc->sc_rrun = 1; #endif DPRINTF(("cs4280_trigger_input: sc=%p start=%p end=%p " "blksize=%d intr=%p(%p)\n", addr, start, end, blksize, intr, arg)); sc->sc_rintr = intr; sc->sc_rarg = arg; sc->sc_ri = 0; sc->sc_rcount = blksize / CS4280_ICHUNK; /* CS4280_ICHUNK is fixed hardware blksize*/ sc->sc_rs = (char *)start; sc->sc_re = (char *)end; sc->sc_rn = sc->sc_rs; /* setup format information for internal converter */ sc->sc_rparam = 0; if (param->precision == 8) { sc->sc_rparam += CF_8BIT; sc->sc_rcount <<= 1; } if (param->channels == 1) { sc->sc_rparam += CF_MONO; sc->sc_rcount <<= 1; } /* stop capture DMA */ cctl = BA1READ4(sc, CS4280_CCTL) & ~CCTL_MASK; BA1WRITE4(sc, CS4280_CCTL, cctl); for (p = sc->sc_dmas; p && BUFADDR(p) != start; p = p->next) ; if (!p) { printf("cs4280_trigger_input: bad addr %p\n", start); return (EINVAL); } if (DMAADDR(p) % CS4280_DALIGN != 0) { printf("cs4280_trigger_input: DMAADDR(p)=0x%lx does not start" "4kB align\n", DMAADDR(p)); return (EINVAL); } sc->sc_rdma = p; sc->sc_rbuf = KERNADDR(p); /* initiate capture dma */ mtx_enter(&audio_lock); BA1WRITE4(sc, CS4280_CBA, DMAADDR(p)); /* set CIE */ cie = BA1READ4(sc, CS4280_CIE) & ~CIE_CI_MASK; BA1WRITE4(sc, CS4280_CIE, cie | CIE_CI_ENABLE); cs4280_set_adc_rate(sc, param->sample_rate); cctl = BA1READ4(sc, CS4280_CCTL) & ~CCTL_MASK; cctl |= sc->cctl; BA1WRITE4(sc, CS4280_CCTL, cctl); mtx_leave(&audio_lock); return (0); } int cs4280_init(struct cs4280_softc *sc, int init) { int n; u_int32_t mem; /* Start PLL out in known state */ BA0WRITE4(sc, CS4280_CLKCR1, 0); /* Start serial ports out in known state */ BA0WRITE4(sc, CS4280_SERMC1, 0); /* Specify type of CODEC */ /* XXX should no be here */ #define SERACC_CODEC_TYPE_1_03 #ifdef SERACC_CODEC_TYPE_1_03 BA0WRITE4(sc, CS4280_SERACC, SERACC_HSP | SERACC_CTYPE_1_03); /* AC 97 1.03 */ #else BA0WRITE4(sc, CS4280_SERACC, SERACC_HSP | SERACC_CTYPE_2_0); /* AC 97 2.0 */ #endif /* Reset codec */ BA0WRITE4(sc, CS4280_ACCTL, 0); delay(100); /* delay 100us */ BA0WRITE4(sc, CS4280_ACCTL, ACCTL_RSTN); /* Enable AC-link sync generation */ BA0WRITE4(sc, CS4280_ACCTL, ACCTL_ESYN | ACCTL_RSTN); delay(50*1000); /* delay 50ms */ /* Set the serial port timing configuration */ BA0WRITE4(sc, CS4280_SERMC1, SERMC1_PTC_AC97); /* Setup clock control */ BA0WRITE4(sc, CS4280_PLLCC, PLLCC_CDR_STATE|PLLCC_LPF_STATE); BA0WRITE4(sc, CS4280_PLLM, PLLM_STATE); BA0WRITE4(sc, CS4280_CLKCR2, CLKCR2_PDIVS_8); /* Power up the PLL */ BA0WRITE4(sc, CS4280_CLKCR1, CLKCR1_PLLP); delay(50*1000); /* delay 50ms */ /* Turn on clock */ mem = BA0READ4(sc, CS4280_CLKCR1) | CLKCR1_SWCE; BA0WRITE4(sc, CS4280_CLKCR1, mem); /* Set the serial port FIFO pointer to the * first sample in FIFO. (not documented) */ cs4280_clear_fifos(sc); #if 0 /* Set the serial port FIFO pointer to the first sample in the FIFO */ BA0WRITE4(sc, CS4280_SERBSP, 0); #endif /* Configure the serial port */ BA0WRITE4(sc, CS4280_SERC1, SERC1_SO1EN | SERC1_SO1F_AC97); BA0WRITE4(sc, CS4280_SERC2, SERC2_SI1EN | SERC2_SI1F_AC97); BA0WRITE4(sc, CS4280_SERMC1, SERMC1_MSPE | SERMC1_PTC_AC97); /* Wait for CODEC ready */ n = 0; while ((BA0READ4(sc, CS4280_ACSTS) & ACSTS_CRDY) == 0) { delay(125); if (++n > 1000) { printf("%s: codec ready timeout\n", sc->sc_dev.dv_xname); return(1); } } /* Assert valid frame signal */ BA0WRITE4(sc, CS4280_ACCTL, ACCTL_VFRM | ACCTL_ESYN | ACCTL_RSTN); /* Wait for valid AC97 input slot */ n = 0; while ((BA0READ4(sc, CS4280_ACISV) & (ACISV_ISV3 | ACISV_ISV4)) != (ACISV_ISV3 | ACISV_ISV4)) { delay(1000); if (++n > 1000) { printf("AC97 inputs slot ready timeout\n"); return(1); } } /* Set AC97 output slot valid signals */ BA0WRITE4(sc, CS4280_ACOSV, ACOSV_SLV3 | ACOSV_SLV4); /* reset the processor */ cs4280_reset(sc); return (0); } int cs4280_init2(struct cs4280_softc *sc, int init) { int n; u_int32_t mem; /* Download the image to the processor */ if (cs4280_download_image(sc) != 0) { printf("%s: image download error\n", sc->sc_dev.dv_xname); return(1); } /* Save playback parameter and then write zero. * this ensures that DMA doesn't immediately occur upon * starting the processor core */ mem = BA1READ4(sc, CS4280_PCTL); sc->pctl = mem & PCTL_MASK; /* save startup value */ cs4280_halt_output(sc); /* Save capture parameter and then write zero. * this ensures that DMA doesn't immediately occur upon * starting the processor core */ mem = BA1READ4(sc, CS4280_CCTL); sc->cctl = mem & CCTL_MASK; /* save startup value */ cs4280_halt_input(sc); /* MSH: need to power up ADC and DAC? */ /* Processor Startup Procedure */ BA1WRITE4(sc, CS4280_FRMT, FRMT_FTV); BA1WRITE4(sc, CS4280_SPCR, SPCR_RUN | SPCR_RUNFR | SPCR_DRQEN); /* Monitor RUNFR bit in SPCR for 1 to 0 transition */ n = 0; while (BA1READ4(sc, CS4280_SPCR) & SPCR_RUNFR) { delay(10); if (++n > 1000) { printf("SPCR 1->0 transition timeout\n"); return(1); } } n = 0; while (!(BA1READ4(sc, CS4280_SPCS) & SPCS_SPRUN)) { delay(10); if (++n > 1000) { printf("SPCS 0->1 transition timeout\n"); return(1); } } /* Processor is now running !!! */ /* Setup volume */ BA1WRITE4(sc, CS4280_PVOL, 0x80008000); BA1WRITE4(sc, CS4280_CVOL, 0x80008000); /* Interrupt enable */ BA0WRITE4(sc, CS4280_HICR, HICR_IEV|HICR_CHGM); /* playback interrupt enable */ mem = BA1READ4(sc, CS4280_PFIE) & ~PFIE_PI_MASK; mem |= PFIE_PI_ENABLE; BA1WRITE4(sc, CS4280_PFIE, mem); /* capture interrupt enable */ mem = BA1READ4(sc, CS4280_CIE) & ~CIE_CI_MASK; mem |= CIE_CI_ENABLE; BA1WRITE4(sc, CS4280_CIE, mem); #if NMIDI > 0 /* Reset midi port */ mem = BA0READ4(sc, CS4280_MIDCR) & ~MIDCR_MASK; BA0WRITE4(sc, CS4280_MIDCR, mem | MIDCR_MRST); DPRINTF(("midi reset: 0x%x\n", BA0READ4(sc, CS4280_MIDCR))); /* midi interrupt enable */ mem |= MIDCR_TXE | MIDCR_RXE | MIDCR_RIE | MIDCR_TIE; BA0WRITE4(sc, CS4280_MIDCR, mem); #endif return(0); } int cs4280_activate(struct device *self, int act) { struct cs4280_softc *sc = (struct cs4280_softc *)self; int rv = 0; switch (act) { case DVACT_SUSPEND: /* should I powerdown here ? */ cs4280_write_codec(sc, AC97_REG_POWER, CS4280_POWER_DOWN_ALL); break; case DVACT_RESUME: cs4280_close(sc); cs4280_init(sc, 0); cs4280_init2(sc, 0); ac97_resume(&sc->host_if, sc->codec_if); rv = config_activate_children(self, act); break; default: rv = config_activate_children(self, act); break; } return (rv); } void cs4280_clear_fifos(struct cs4280_softc *sc) { int pd = 0, cnt, n; u_int32_t mem; /* * If device power down, power up the device and keep power down * state. */ mem = BA0READ4(sc, CS4280_CLKCR1); if (!(mem & CLKCR1_SWCE)) { printf("cs4280_clear_fifo: power down found.\n"); BA0WRITE4(sc, CS4280_CLKCR1, mem | CLKCR1_SWCE); pd = 1; } BA0WRITE4(sc, CS4280_SERBWP, 0); for (cnt = 0; cnt < 256; cnt++) { n = 0; while (BA0READ4(sc, CS4280_SERBST) & SERBST_WBSY) { delay(1000); if (++n > 1000) { printf("clear_fifo: fist timeout cnt=%d\n", cnt); break; } } BA0WRITE4(sc, CS4280_SERBAD, cnt); BA0WRITE4(sc, CS4280_SERBCM, SERBCM_WRC); } if (pd) BA0WRITE4(sc, CS4280_CLKCR1, mem); } #if NMIDI > 0 int cs4280_midi_open(void *addr, int flags, void (*iintr)(void, int), void (*ointr)(void *), void *arg) { struct cs4280_softc *sc = addr; u_int32_t mem; DPRINTF(("midi_open\n")); sc->sc_iintr = iintr; sc->sc_ointr = ointr; sc->sc_arg = arg; /* midi interrupt enable */ mem = BA0READ4(sc, CS4280_MIDCR) & ~MIDCR_MASK; mem |= MIDCR_TXE | MIDCR_RXE | MIDCR_RIE | MIDCR_TIE | MIDCR_MLB; BA0WRITE4(sc, CS4280_MIDCR, mem); #ifdef CS4280_DEBUG if (mem != BA0READ4(sc, CS4280_MIDCR)) { DPRINTF(("midi_open: MIDCR=%d\n", BA0READ4(sc, CS4280_MIDCR))); return(EINVAL); } DPRINTF(("MIDCR=0x%x\n", BA0READ4(sc, CS4280_MIDCR))); #endif return (0); } void cs4280_midi_close(void *addr) { struct cs4280_softc *sc = addr; u_int32_t mem; DPRINTF(("midi_close\n")); mem = BA0READ4(sc, CS4280_MIDCR); mem &= ~MIDCR_MASK; BA0WRITE4(sc, CS4280_MIDCR, mem); sc->sc_iintr = 0; sc->sc_ointr = 0; } int cs4280_midi_output(void *addr, int d) { struct cs4280_softc *sc = addr; u_int32_t mem; int x; for (x = 0; x != MIDI_BUSY_WAIT; x++) { if ((BA0READ4(sc, CS4280_MIDSR) & MIDSR_TBF) == 0) { mem = BA0READ4(sc, CS4280_MIDWP) & ~MIDWP_MASK; mem |= d & MIDWP_MASK; DPRINTFN(5,("midi_output d=0x%08x",d)); BA0WRITE4(sc, CS4280_MIDWP, mem); if (mem != BA0READ4(sc, CS4280_MIDWP)) { DPRINTF(("Bad write data: %d %d", mem, BA0READ4(sc, CS4280_MIDWP))); return(EIO); } return (0); } delay(MIDI_BUSY_DELAY); } return (EIO); } void cs4280_midi_getinfo(void *addr, struct midi_info *mi) { mi->name = "CS4280 MIDI UART"; mi->props = MIDI_PROP_CAN_INPUT | MIDI_PROP_OUT_INTR; } #endif
ee15f2552745d2492181c3532334950871b029db
d388e61cca43f163fb33b8c464d0ce679b5eabe6
/STM32CubeExpansion_USBPD_F0/Middlewares/ST/STM32_USBPD_Library/Core/inc/usbpd_trace.h
6dad250b4985492c5a61a62815251171aef9c29b
[]
no_license
st-one/X-CUBE-USB-PD
2cffc6b5b443eec159c1eab96a486696b7e1eade
5d2c7752fcdda8f21f8a1b96ab8b74712e5baa76
refs/heads/master
2022-05-02T01:12:44.270608
2022-04-05T23:25:42
2022-04-05T23:25:42
64,798,120
104
36
null
null
null
null
UTF-8
C
false
false
5,096
h
usbpd_trace.h
/** ****************************************************************************** * @file usbpd_trace.h * @author MCD Application Team * @brief This file contains the headers of usbpd_cad.h for Cable Attach-Detach * controls. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics International N.V. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS 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 __USBPD_TRACE_H_ #define __USBPD_TRACE_H_ #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ /** @addtogroup STM32_USBPD_LIBRARY * @{ */ /** @addtogroup USBPD_CORE * @{ */ /** @addtogroup USBPD_CORE_TRACE * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup USBPD_CORE_TRACE_Exported_Types USBPD CORE TRACE Exported Types * @{ */ typedef enum { USBPD_TRACE_FORMAT_TLV = 0, USBPD_TRACE_MESSAGE_IN = 1, USBPD_TRACE_MESSAGE_OUT = 2, USBPD_TRACE_CADEVENT = 3, USBPD_TRACE_PE_STATE = 4, USBPD_TRACE_CAD_LOW = 5, USBPD_TRACE_DEBUG = 6, USBPD_TRACE_SRC = 7, USBPD_TRACE_SNK = 8, USBPD_TRACE_NOTIF = 9, USBPD_TRACE_POWER =10 } TRACE_EVENT; typedef void (*TRACE_ENTRY_POINT)(TRACE_EVENT type, uint8_t port, uint8_t sop, uint8_t *ptr, uint32_t size); /** * @} */ /* Exported define -----------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported variables --------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @defgroup USBPD_CORE_TRACE_Exported_Functions USBPD TRACE Exported Functions * @{ */ /** * @brief Initialize the TRACE module * @retval None */ void USBPD_TRACE_Init(void); /** * @brief Add information in debug trace buffer * @param Type Trace Type based on @ref TRACE_EVENT * @param PortNum Port number value * @param Sop SOP type * @param Ptr Pointer on the data to send * @param Size Size of the data to send * @retval None. */ void USBPD_TRACE_Add(TRACE_EVENT Type, uint8_t PortNum, uint8_t Sop, uint8_t *Ptr, uint32_t Size); /** * @brief Main Trace TX process to push data on the media. * @retval Timing */ uint32_t USBPD_TRACE_TX_Process(void); /** * @} */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __USBPD_CAD_H_ */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
b7061638204ec7dea2edc1c5586e008a298c6936
c59784458e4dcb34eadd6941bc4297c28c1a7e53
/Compilers/glcc/gigatron/libc/pow.c
c592e55365d88fcccf4ca248d1627d0681ffda00
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license", "GPL-1.0-or-later", "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
660
c
pow.c
#include <gigatron/libc.h> #include <errno.h> #include <math.h> static double _ipow(double x, double ye) { register long i = ye; register double r = 1.0; while (i) { if (i & 1) r *= x; x *= x; i >>= 1; } return r; } double pow(double x, double y) { double s = +1; double yf; double ye; int yi; if (y == 0.0 || x == 1.0) return 1.0; if (y < 0) { y = -y; x = 1.0 / x; } yf = modf(y, &ye); if (x <= 0) { if (x == 0) return 0; if (yf != 0) { errno = EDOM; return _fexception(0); } if ((int)ye & 1) { s = -1; } x = -x; } if (yf == 0 && ye < 1000) return s * _ipow(x, ye); return s * exp(y * log(x)); }
5892fbc4ca7dd3cf28ab23749798fb8a79384e2c
e0eb89846beb33f454bf288342389daacfc4d8a6
/preg.c
8a0792cd7dde36452d27325c7046cfc3d75326d8
[ "MIT", "BSD-3-Clause" ]
permissive
mysqludf/lib_mysqludf_preg
827ba14d17571c45b5e3ce67bd5ba0726d968f24
6395901adaf987a9f9e4e1b859daad4f2d665eff
refs/heads/testing
2022-08-23T06:43:20.353505
2022-08-17T03:07:05
2022-08-17T03:07:05
4,137,763
101
19
NOASSERTION
2022-08-17T03:07:06
2012-04-25T14:59:15
Shell
UTF-8
C
false
false
16,565
c
preg.c
/* * Copyright (C) 2007-2013 Rich Waters <raw@goodhumans.net> * * This file is part of lib_mysqludf_preg. * * 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 preg.c * * @brief Provides some functions that are shared by the various * preg udf functions. */ #include "ghmysql.h" #include "preg.h" /* For pthreads */ #include <pthread.h> /* * Public Functions: */ /** * @fn pcre *pregCompileRegexArg( UDF_ARGS *args , char *msg , int msglen ) * * @brief compile the regex (arg[0]) * * @param args - the args supplied by mysql udf api (ultimately, the user) * @param msg - buffer where error messages can be placed * @param msglen - size of the error message buffer above * * @return - if successful - the compiled regular expression * @return - if failure - NULL * * @details * This function compiles the pcre regular expression passed in as * the first argument. The argument passed * as args->args[0] is a pattern that needs to include delimiters and * may include modifiers. (ie. /([a-z0-9]*?)(.*)/i ). This function * is necessary because compileRegex (from_php.c) requires a string * argument. This function null terminates the first argument and * calls compileRegex. * * @note * make sure to call pcre_free to free up the returned result (if not null) * */ pcre *pregCompileRegexArg( UDF_ARGS *args , char *msg , int msglen ) { pcre *re ; /* the compiled pattern */ char *val ; /* The pattern to compile */ *msg ='\0'; val = ghargdup( args , 0 ) ; if( !val ) { if( args->lengths[0] && args->args[0] ) { strncpy( msg , "Out of memory" , msglen ) ; } else { strncpy( msg , "Empty pattern" , msglen ) ; } return NULL ; } re = compileRegex( val , args->lengths[0], msg, msglen ) ; free( val ) ; return re ; } /** * @fn int initPtrInfo( struct preg_s *ptr ,UDF_ARGS *args,char *message ) * * @brief initialize contents of initid->ptr * * @param ptr - the pointer to initialize the info in * @param args - the args supplied by mysql udf api (ultimately, the user) * @param message - put error message in here if error * * @return 0 - on success * @return 1 - on error * * @details * Compile the regex and save it in ptr->re. This function should * normally only be called if the first argument is a constant. * * @note * make sure to call destroyPtrInfo when done */ int initPtrInfo( struct preg_s *ptr ,UDF_ARGS *args,char *message ) { // 128 is a safe size for mysql, which reccomends 80 chars or less messages ptr->re = pregCompileRegexArg( args, message,128 ); if( !ptr->re ) { return 1; } return 0 ; } /** * @fn int *pregCreateOffsetsVector( pcre *re , pcre_extra *extra , int *count, * char *msg , int msglen ) * * @brief allocate a memory area that can be used for holding the offset vector * used by the pcre library. * * @param re - compiled regular expression * @param extra - NULL or extra info about re as returned by pcre_study * @param count - pointer to integer to place number of captures into * @param msg - put error messages here * @param msglen - length of msg buffer * * @return pointer to new offets vector - on success * @return NULL if out of memory or error from pcre * * @details The ovector is used by the pcre for capturing the offsets of * the parenthesized sub-expressions of a pcre expression. This function * uses pcre_fullinfo to retrieve the number of capture groups in the * expression, and then it allocates a vector of that size+1 and * sets the passed in count to that size as well. */ int *pregCreateOffsetsVector( pcre *re , pcre_extra *extra , int *count , char *msg , int msglen ) { int *ovec ; /* vector to return */ int oveccount ; /* number of capture groups found */ *count = 0 ; if( pcre_fullinfo(re, extra , PCRE_INFO_CAPTURECOUNT, &oveccount ) < 0 ) { strncpy(msg,"preg: error retrieving information about pattern",msglen); return NULL ; } ++oveccount ; // for 0 oveccount *= 3 ; // 2 for offset info , 1 for pcre internals ovec = malloc( sizeof( int ) * oveccount ) ; if( !ovec ) { strncpy( msg , "preg: out of memory" , msglen ) ; return NULL ; } *count = oveccount ; return ovec ; } /** * @fn int pregGetGroupNum( pcre *re , UDF_ARGS *args , int argnum ) * * @brief gets the string number of a capture group from a pcre * * @param re - compiled regular expression * @param args - the args to the mysql UDF * @param argnum - the index of the args that specifies the group number to get * * @return int >= 0 string number that can be passed to pcre_get_substring * @return -1 if group number not found or other error * * @details This function extract the desired group number from the * given arguments. If it is a named capture group, it is converted * to a number using pcre_get_stringnumber. This number is then returned. */ int pregGetGroupNum( pcre *re , UDF_ARGS *args , int argnum ) { char *group ; /* named group - args[argnum] */ int groupnum ; /* string number of capture group */ // The groupnum was specified as an optional parameter if( argnum >= args->arg_count ) groupnum = 0 ; else if( args->arg_type[argnum] == INT_RESULT ) { // numeric capture group groupnum = (int)(*(longlong *)args->args[2]) ; } else { // This is a named group. The numeric groupnum must be found group = ghargdup( args , 2 ) ; if( !group ) { fprintf(stderr,"pregGetGroupNum: error accessing capture group\n"); return -1 ; } groupnum =pcre_get_stringnumber(re , group); free( group ) ; } return groupnum ; } /** * @fn int pregSkipToOccurence( pcre *re , char *subject , int subject_len , * int *ovector , int oveccount , int occurence, * int *rc) * * @brief return a pointer to the nth occurence of a pcre in a string * * @param re - compiled regular expression * @param subject - the string on which to perform matching * @param subject_len - length of the subject string * @param ovector - vector used by pcre to capture offets of matches * @param oveccount - size of ovector * @param occurence - match occurence to find * @param rc - put result of last pcre_exec call here * * @return char * - portion of string which starts with pcre occurence requested * @return -1 if group number not found or other error * * @details This function extract the desired group number from the * given arguments. If it is a named capture group, it is converted * to a number using pcre_get_stringnumber. This number is then returned. */ char *pregSkipToOccurence( pcre *re , char *subject , int subject_len , int *ovector , int oveccount , int occurence, int *rc) { char *ex_subject ; /* position of last match */ int subject_offset = 0 ; /* offset of next match from last one */ char *ret = NULL ; /* return value from this function */ pcre_extra extra; ex_subject = subject ; memset(&extra, 0, sizeof(extra)); pregSetLimits(&extra); // Skip over the 1st N occurences while( occurence-- && subject_offset <= subject_len ) { // Run the regex and find the groupnum if possible *rc = pcre_exec(re, &extra, subject + subject_offset , subject_len - subject_offset, 0,0, ovector, oveccount); if( *rc <= 0 ) break ; ex_subject = subject + subject_offset ; subject_offset += ovector[1] ; } if( rc > 0 ) ret = ex_subject ; return ret ; } /** * @fn void destroyPtrInfo( struct preg_s *ptr ) * * @brief free up the memory used by ptr and alloced in initPtrInfo * * @param ptr - free members of this struct */ void destroyPtrInfo( struct preg_s *ptr ) { if( ptr->re ) { pcre_free( ptr->re ) ; ptr->re = NULL ; } if( ptr->return_buffer ) { free( ptr->return_buffer ) ; ptr->return_buffer = NULL ; } } /** * @fn void pregDeInit(UDF_INIT *initid) * * @brief shared _deinit routines used by preg. * * @param initid - various info supplied by mysql api - read more at * http://dev.mysql.com/doc/refman/5.0/en/adding-udf.html * * @details - frees the ptr members and then frees the ptr itself. It * can usually be the only thing called by the _deinit functions of the * preg routeines. */ void pregDeInit(UDF_INIT *initid) { struct preg_s *ptr ; /* to avoid casting */ if (initid->ptr) { ptr = (struct preg_s *)initid->ptr ; destroyPtrInfo( ptr ) ; free( ptr ) ; initid->ptr = NULL ; } } /** * @fn bool pregInit(UDF_INIT *initid, UDF_ARGS *args, char *message) * * @brief * Perform the init stuff common to all preg routines * * @param initid - various info supplied by mysql api - read more at * http://dev.mysql.com/doc/refman/5.0/en/adding-udf.html * * @param args - array of information about arguments from the SQL call * See file documentation for the description of the SQL arguments * * @param message - for error messages. Should be <80 but can be 255. * * @return 0 - on success * @return 1 - on error * * @details This function is called from the _init routines for the preg * functions. It performs the initializations common to all or most of * those routines. This includes converting the 1st 2 args to strings, * and compiling the first argument (the pattern) if it * is a constant. */ bool pregInit(UDF_INIT *initid, UDF_ARGS *args, char *message) { struct preg_s *ptr; /* temp holder of initid->ptr */ int i ; // use calloc so deInit can check for NULL's before freeing initid->ptr = (char *)calloc( 1,sizeof( struct preg_s ) ) ; ptr = (struct preg_s *)initid->ptr ; if( !ptr ) { strcpy(message,"not enough memory"); return 1; } if( ghargIsNullConstant( args , 0 ) ) { ptr->constant_pattern = 1 ; #ifdef GH_1_0_NULL_HANDLING strcpy( message, "NULL pattern" ) ; return 1 ; #endif } // Convert first 2 args (pattern & subject) to strings. for (i=0 ; i < 2; i++) args->arg_type[i]=STRING_RESULT; if(args->arg_count && args->args[0] ) { if( initPtrInfo( ptr , args , message ) ) { return 1; } /** * If the pattern is constant, compile it once to improve perfomance. * Set the constant_pattern member to inform main function. */ ptr->constant_pattern = 1 ; } else { ptr->constant_pattern = 0 ; } if( ((int)initid->max_length) > 0 ) { ptr->return_buffer_size = initid->max_length + 1 ; } else { // If there is no limit on max_length. Start at a fairly big // size. Re-allocations will occur if necessary. ptr->return_buffer_size = 1024000 ; } ptr->return_buffer = malloc( ptr->return_buffer_size ) ; return 0 ; } /** * int pregCopyToReturnBuffer( struct preg_s *ptr , char *s , int l ) * * @brief * safely copies data into ptr->return_buffer * * @param ptr - the info stored in initid->ptr * @param s - data to be copied * @param l - length of data to be copied * * @return the number of bytes copied - on success * @return -1 - on error * * @details This function checks to see if ptr->return_buffer is big * enough to hold the given data. If it isn't, reallocs occur. * Then the data is copied. * * @note * The return buffer is null-terminated, as well. This shouldn't be * necessary, but it can help to prevent potential crashes. */ int pregCopyToReturnBuffer( struct preg_s *ptr , char *s , int l ) { char *newbuf ; if( (l+1) > ptr->return_buffer_size ) { newbuf = malloc( l + 1 ) ; if( !newbuf ) { fprintf( stderr , "preg: out of memory reallocing return buffer\n" ) ; return -1 ; } free( ptr->return_buffer ) ; ptr->return_buffer = newbuf ; ptr->return_buffer_size = l + 1 ; } memcpy( ptr->return_buffer , s , l ) ; ptr->return_buffer[ l ] = 0 ; return l ; } /** * @fn char *pregMoveToReturnValues( UDF_INIT *initid , * unsigned long *length , * char *is_null , char *error , * char *s , int s_len ) * * @brief * set the appropriate UDF return values to the given data for UDF's * that return strings, and frees passed in data pointer. * * @param initid - various info supplied by mysql api - read more at * http://dev.mysql.com/doc/refman/5.0/en/adding-udf.html * * @param length - put the length of the returned string here. * @param is_null - set this if return value is null and NULL is allowed * @param error - set if an error occurs * @param s - string to copy into return buffer * @param s_len - length of string to copy into return buffer * * @return - pointer to the string to return (ptr->return_buffer) * @return - NULL - if error occured and NULL's are allowed * * @details This function checks the given length and data for * negatives and NULL, respectively. This function should usually * be called using the results from a pcre function call, and it * prints the appropriate error message is the given length is <0. * Otherwise, it checks for non-NULL data uses pregCopyToReturnBuffer * to copy given data into ptr->return_buffer. If this copy is * successful, it frees the passed in string. * * @note. This function frees the passed in string after copying it. Careful! */ char *pregMoveToReturnValues( UDF_INIT *initid , unsigned long *length , char *is_null , char *error , char *s , int s_len ) { struct preg_s *ptr ; /* local holder of initid->ptr */ int l ; /* bytes copied into return_buffer */ ptr = (struct preg_s *)initid->ptr ; // Set default return info. *error = 1 ; *length = 0 ; *ptr->return_buffer = '\0'; if( initid->maybe_null ) { *is_null = 1 ; } if( s_len >= 0 ) { if( s ) { // normal case -- copy data & free it l = pregCopyToReturnBuffer( ptr , s , s_len ) ; if( l >= 0 ) { *is_null = 0 ; *error = 0 ; *length = l ; } free( s ) ; } else { // Empty string is not error? *is_null = 0 ; *error = 0 ; } } else { ghlogprintf("ERROR preg: pcre_exec rturned error %d (%s)\n" , s_len, pregExecErrorString(s_len) ) ; } if( *is_null ) { return NULL ; } else { return ptr->return_buffer ; } }
9d0e75f46d92f7bb25761f171ab6cd4541cfd527
76ce519e33fe1828b292db9a9e463d557a3b7764
/csrc/pf_win32.h
c383c82ab1cf66fce8a7a014b6b291977a91b215
[ "0BSD" ]
permissive
philburk/pforth
59a9effe826d1c9552b3acf2516292209c7980ed
8da2f097a6a4b856e659e08556ff938ac612d8ed
refs/heads/master
2023-08-29T00:14:06.130545
2023-02-11T20:24:43
2023-02-11T20:24:43
28,118,577
588
126
0BSD
2023-03-01T09:51:10
2014-12-17T03:05:04
C
UTF-8
C
false
false
1,385
h
pf_win32.h
/* @(#) pf_win32.h 98/01/26 1.2 */ #ifndef _pf_win32_h #define _pf_win32_h #include <conio.h> /*************************************************************** ** WIN32 dependant include file for PForth, a Forth based on 'C' ** ** Author: Phil Burk ** Copyright 1994 3DO, Phil Burk, Larry Polansky, David Rosenboom ** ** Permission to use, copy, modify, and/or distribute this ** software for any purpose with or without fee is hereby granted. ** ** 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. ** ***************************************************************/ /* Include as PF_USER_INC2 for PCs */ /* Modify some existing defines. */ /* ** The PC will insert LF characters into the dictionary files unless ** we use "b" mode! */ #undef PF_FAM_CREATE #define PF_FAM_CREATE ("wb+") #undef PF_FAM_OPEN_RO #define PF_FAM_OPEN_RO ("rb") #undef PF_FAM_OPEN_RW #define PF_FAM_OPEN_RW ("rb+") #endif /* _pf_win32_h */
499a5216c0bd78cad5587e3198867be5bd8f2107
a5a7c59b04a1a64fe34653c7970c3cf173f9c1df
/numerics/src/FrictionContact/FrictionContactProblem.h
0d035179987a83d74fd9b6c01b0a0882a720a34d
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
siconos/siconos
a7afdba41a2bc1192ad8dcd93ac7266fa281f4cf
82a8d1338bfc1be0d36b5e8a9f40c1ad5384a641
refs/heads/master
2023-08-21T22:22:55.625941
2023-07-17T13:07:32
2023-07-17T13:07:32
37,709,357
166
33
Apache-2.0
2023-07-17T12:31:16
2015-06-19T07:55:53
C
UTF-8
C
false
false
5,223
h
FrictionContactProblem.h
/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2022 INRIA. * * 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 FRICTIONCONTACTPROBLEM_H #define FRICTIONCONTACTPROBLEM_H /*!\file FrictionContactProblem.h Definition of a structure to handle friction-contact (2D or 3D) problems. */ #include "NumericsFwd.h" // for FrictionContactProblem, NumericsMatrix #include "NumericsMatrix.h" // for RawNumericsMatrix #include "SiconosConfig.h" // for BUILD_AS_CPP // IWYU pragma: keep #include <stdio.h> // for FILE /** The structure that defines a (reduced or dual) Friction-Contact (3D or 2D) problem. */ struct FrictionContactProblem { /** dimension of the contact space (3D or 2D ) */ int dimension; /** the number of contacts \f$ n_c \f$ */ int numberOfContacts; /** \f$ {M} \in {{\mathrm{I\!R}}}^{n \times n} \f$, a matrix with \f$ n = d n_c \f$ stored in NumericsMatrix structure */ RawNumericsMatrix *M; /** \f$ {q} \in {{\mathrm{I\!R}}}^{n} \f$ */ double *q; /** \f$ {\mu} \in {{\mathrm{I\!R}}}^{n_c} \f$, vector of friction coefficients (\f$ n_c = \f$ numberOfContacts) */ double *mu; }; struct SplittedFrictionContactProblem { FrictionContactProblem *fc3d; NumericsMatrix *M_nn; NumericsMatrix *M_tn; NumericsMatrix *M_nt; NumericsMatrix *M_tt; double *q_n; double *q_t; }; #if defined(__cplusplus) && !defined(BUILD_AS_CPP) extern "C" { #endif /* create an empty FrictionContactProblem * \return an empty fcp */ FrictionContactProblem *frictionContactProblem_new(void); /** new FrictionContactProblem from minimal set of data * * \param[in] dim the problem dimension * \param[in] nc the number of contact * \param[in] M the NumericsMatrix * \param[in] q the q vector * \param[in] mu the mu vector * \return a pointer to a FrictionContactProblem structure */ FrictionContactProblem *frictionContactProblem_new_with_data(int dim, int nc, NumericsMatrix *M, double *q, double *mu); /** free a FrictionContactProblem * * \param problem the problem to free */ void frictionContactProblem_free(FrictionContactProblem *problem); /** display a FrictionContactProblem * * \param problem the problem to display */ void frictionContact_display(FrictionContactProblem *problem); /** print a FrictionContactProblem in a file (numerics .dat format) * * \param problem the problem to print out * \param file the dest file * \return 0 if successfull */ int frictionContact_printInFile(FrictionContactProblem *problem, FILE *file); /** print a FrictionContactProblem in a file (numerics dat format) * * \param problem the problem to print out * \param filename the dest file * \return 0 if successfull */ int frictionContact_printInFilename(FrictionContactProblem *problem, char *filename); /** read a FrictionContactProblem from a file descriptor * * \param file descriptor * \return problem the problem to read */ FrictionContactProblem *frictionContact_newFromFile(FILE *file); /** read a FrictionContactProblem from a file (.dat or hdf5 if fclib is on) from * its filename * * \param filename the name of the input file * \return problem the problem to read */ FrictionContactProblem *frictionContact_new_from_filename(const char *filename); void createSplittedFrictionContactProblem( FrictionContactProblem *problem, SplittedFrictionContactProblem *splitted_problem); void frictionContactProblem_compute_statistics(FrictionContactProblem *problem, double *reaction, double *velocity, double tol, int do_print); /** Creates a new FrictionContact problem and initialize its content by copying an existing problem. \param problem the source problem to be copied \return a pointer to a new FrictionContactProblem */ FrictionContactProblem *frictionContact_copy(FrictionContactProblem *problem); /** Rescales M matrix and q vector of a given FrictionContactProblem. \f[ :math:`M = \alpha\gamma^2 M, q=\alpha\gamma q` \f] \param problem to be rescaled \param alpha rescaling factor \param gamma rescaling factor */ void frictionContact_rescaling(FrictionContactProblem *problem, double alpha, double gamma); #if defined(__cplusplus) && !defined(BUILD_AS_CPP) } #endif #endif
cd42f7f354d157e849f81fe0d6bac58c9eb924a7
59864cbd213b5da6f50d6255b0a021564b3d5bd4
/challenges/Childs_Game/pov_1/printf.c
c9523fc60bb83b7793fa9381592f38e0cf76bc55
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-unknown", "BSD-2-Clause" ]
permissive
trailofbits/cb-multios
8af96a4fbc3b34644367faa135347f88e0e0d0a3
810d7b24b1f62f56ef49b148fe155b0d0629cad2
refs/heads/master
2023-09-05T03:56:20.229403
2022-12-27T15:47:54
2022-12-27T15:47:54
41,688,943
522
133
MIT
2023-06-29T02:47:13
2015-08-31T17:04:31
C
UTF-8
C
false
false
6,451
c
printf.c
#include "libpov.h" #include "cgc_stdarg.h" #include "cgc_stdint.h" #include "cgc_stdio_private.h" /* * This library can be customized using preprocessor defines: * PRINTF_CHAR specifies the character to use instead of % * PRINTF_N_CHAR specifies the character to use for %n, otherwise disabled */ #ifndef PRINTF_CHAR #define PRINTF_CHAR '%' #endif static void cgc__convert_unsigned(char *buf, unsigned x, int base, int upper) { const char *numbers; char *tmp = buf + 20; if (upper) numbers = "0123456789ABCDEF"; else numbers = "0123456789abcdef"; /* NUL terminate */ *(--tmp) = 0; if (x == 0) *(--tmp) = numbers[0]; else { while (x) { *(--tmp) = numbers[x % base]; x = x / base; } } /* move to beginning of buf */ cgc_memmove(buf, tmp, 20 - (buf - tmp)); } static void cgc__convert_signed(char *buf, int x, int base, int upper) { if (x < 0) { *buf++ = '-'; x = -x; } cgc__convert_unsigned(buf, x, base, upper); } static int cgc__vsfprintf(const char *fmt, va_list ap, FILE *stream, char *buf, cgc_size_t buf_size) { char ch; unsigned int num_size, field_size; cgc_size_t count = 0; char numbuf[64]; cgc_size_t numbuflen; #define OUTPUT_CHAR(_ch) \ do { \ if (count >= buf_size) { \ if (count++ == SIZE_MAX) cgc__terminate(1); \ break; \ } \ char __ch = _ch; \ if (stream) cgc_fwrite(&__ch, 1, stream); \ if (buf) buf[count] = __ch; \ count++; \ } while (0) #define OUTPUT_STRING(str, _sz) \ do { \ cgc_size_t sz = _sz; \ if (count >= buf_size) { \ if ((cgc_size_t)(count + sz) < (count)) cgc__terminate(1); \ count += sz; break; \ } \ cgc_size_t cnt = buf_size - count; \ if (cnt > sz) cnt = sz; \ if (stream) cgc_fwrite(str, cnt, stream); \ if (buf) cgc_memcpy(buf + count, str, cnt); \ if ((cgc_size_t)(count + sz) < (count)) cgc__terminate(1); \ count += sz; \ } while (0) while ((ch = *fmt++)) { char pad_char = ' '; const char *tmp, *strarg; unsigned int uintarg; int intarg; /* output non-format characters */ while (ch != PRINTF_CHAR) { OUTPUT_CHAR(ch); if (!(ch = *fmt++)) goto done; } tmp = fmt; num_size = 4; field_size = 0; /* field flags */ switch ((ch = *fmt++)) { case 0: /* NUL */ goto done; case ' ': pad_char = ' '; break; case '0': pad_char = '0'; break; default: fmt--; break; } /* field width */ if (*fmt >= '0' && *fmt <= '9') field_size = cgc_strtoul(fmt, (char **)&fmt, 10); /* modifiers */ switch ((ch = *fmt++)) { case 0: /* NUL */ goto done; case 'h': if (*fmt == 'h') { fmt++; num_size = 1; } else { num_size = 2; } break; case 'l': if (*fmt == 'l') { fmt++; num_size = 8; /* BUG: long long NOT supported */ } else { num_size = 4; } break; default: fmt--; break; } /* conversion */ switch ((ch = *fmt++)) { case 0: /* NUL */ OUTPUT_STRING(tmp, fmt - tmp); goto done; default: /* unrecognized format character */ OUTPUT_STRING(tmp, fmt - tmp); break; case 'd': case 'u': case 'x': case 'X': if (ch == 'd') { if (num_size <= 4) intarg = va_arg(ap, int); else goto done; cgc__convert_signed(numbuf, intarg, 10, 0); } else { if (num_size <= 4) uintarg = va_arg(ap, unsigned int); else goto done; cgc__convert_unsigned(numbuf, uintarg, ch == 'u' ? 10 : 16, ch == 'X'); } numbuflen = cgc_strlen(numbuf); if (numbuflen < field_size) { field_size -= numbuflen; do { OUTPUT_CHAR(pad_char); field_size--; } while (field_size > 0); } OUTPUT_STRING(numbuf, numbuflen); break; case 'c': ch = va_arg(ap, int); OUTPUT_CHAR(ch); break; case 's': strarg = va_arg(ap, const char *); OUTPUT_STRING(strarg, cgc_strlen(strarg)); break; #ifdef PRINTF_N_CHAR case PRINTF_N_CHAR: if (num_size == 1) *va_arg(ap, unsigned char *) = count; else if (num_size == 2) *va_arg(ap, unsigned short *) = count; else if (num_size == 4) *va_arg(ap, unsigned int *) = count; else goto done; #endif } } done: /* append NUL byte to buf, but not to the stream */ stream = NULL; OUTPUT_CHAR('\0'); return (int)count; } int cgc_printf(const char *fmt, ...) { int ret; va_list ap; va_start(ap, fmt); ret = cgc_vprintf(fmt, ap); va_end(ap); return ret; } int cgc_fprintf(FILE *stream, const char *fmt, ...) { int ret; va_list ap; va_start(ap, fmt); ret = cgc_vfprintf(stream, fmt, ap); va_end(ap); return ret; } int cgc_sprintf(char *str, const char *fmt, ...) { int ret; va_list ap; va_start(ap, fmt); ret = cgc_vsprintf(str, fmt, ap); va_end(ap); return ret; } int cgc_vprintf(const char *fmt, va_list ap) { return cgc_vfprintf(cgc_stdout, fmt, ap); } int cgc_vfprintf(FILE *stream, const char *fmt, va_list ap) { return cgc__vsfprintf(fmt, ap, stream, NULL, INT_MAX); } int cgc_vsprintf(char *str, const char *fmt, va_list ap) { return cgc__vsfprintf(fmt, ap, NULL, str, INT_MAX); }
2e0611bd72d4f969a52d7ee1f750e23fcc2a0c9f
78dc9f153549b281be709227bc9897931b06260d
/generation/WinSDK/RecompiledIdlHeaders/shared/sensorsutils.h
9be1bb69d30c441a3ee877332e7071dcc387f7d0
[ "MIT" ]
permissive
microsoft/win32metadata
dff35b4fe904d556162cee5133294c4498f1a79a
5bf233f04d45f7a697e112e9639722551103eb07
refs/heads/main
2023-09-01T19:51:22.972899
2023-08-30T21:39:44
2023-08-30T21:39:44
270,838,404
1,240
107
NOASSERTION
2023-09-14T18:49:44
2020-06-08T21:52:10
C++
UTF-8
C
false
false
8,763
h
sensorsutils.h
/*++ Copyright (c) Microsoft Corporation. All rights reserved. Module Name: SensorsUtils.h Abstract: This file contains utility functions for V2 Sensors --*/ #if _MSC_VER > 1000 #pragma once #endif #include <SensorsStructures.h> #ifdef __cplusplus extern "C" { #endif #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) /////////////////////////////////////////////////////////////////////////////// // // // TimeStamp Helpers // // // /////////////////////////////////////////////////////////////////////////////// NTSTATUS GetPerformanceTime( _Out_ PULONG TimeMs ); #define MILLISECONDS_TO_100NANOSECONDS(durationMs) ((durationMs) * 1000 * 10) #define MILLISECONDS_FROM_100NANOSECONDS(durationNanoS) ((durationNanoS) / (1000 * 10)) /////////////////////////////////////////////////////////////////////////////// // // // PropVariant Helper // // // /////////////////////////////////////////////////////////////////////////////// HRESULT InitPropVariantFromFloat( _In_ FLOAT fltVal, _Out_ PROPVARIANT *ppropvar ); NTSTATUS PropKeyFindKeyGetPropVariant( _In_ const SENSOR_COLLECTION_LIST *pList, _In_ const PROPERTYKEY *pKey, _In_ BOOLEAN TypeCheck, _Inout_ PROPVARIANT *pValue ); _At_(pList->AllocatedSizeInBytes, _Const_) _At_(pList->Count, _Const_) NTSTATUS PropKeyFindKeySetPropVariant( _Inout_ SENSOR_COLLECTION_LIST *pList, _In_ const PROPERTYKEY *pKey, _In_ BOOLEAN TypeCheck, _In_ PROPVARIANT *pValue ); NTSTATUS PropKeyFindKeyGetFileTime( _In_ const SENSOR_COLLECTION_LIST *pList, _In_ const PROPERTYKEY *pKey, _Out_ FILETIME *pRetValue); NTSTATUS PropKeyFindKeyGetGuid( _In_ const SENSOR_COLLECTION_LIST *pList, _In_ const PROPERTYKEY *pKey, _Out_ GUID *pRetValue ); NTSTATUS PropKeyFindKeyGetBool( _In_ const SENSOR_COLLECTION_LIST *pList, _In_ const PROPERTYKEY *pKey, _Out_ BOOL *pRetValue ); NTSTATUS PropKeyFindKeyGetUlong( _In_ const SENSOR_COLLECTION_LIST *pList, _In_ const PROPERTYKEY *pKey, _Out_ ULONG *pRetValue ); NTSTATUS PropKeyFindKeyGetUshort( _In_ const SENSOR_COLLECTION_LIST *pList, _In_ const PROPERTYKEY *pKey, _Out_ USHORT *pRetValue ); NTSTATUS PropKeyFindKeyGetFloat( _In_ const SENSOR_COLLECTION_LIST *pList, _In_ const PROPERTYKEY *pKey, _Out_ FLOAT *pRetValue ); NTSTATUS PropKeyFindKeyGetDouble( _In_ const SENSOR_COLLECTION_LIST *pList, _In_ const PROPERTYKEY *pKey, _Out_ double *pRetValue ); NTSTATUS PropKeyFindKeyGetInt32( _In_ const SENSOR_COLLECTION_LIST *pList, _In_ const PROPERTYKEY *pKey, _Out_ INT32 *pRetValue ); NTSTATUS PropKeyFindKeyGetInt64( _In_ const SENSOR_COLLECTION_LIST *pList, _In_ const PROPERTYKEY *pKey, _Out_ INT64 *pRetValue ); NTSTATUS PropKeyFindKeyGetNthUlong( _In_ const SENSOR_COLLECTION_LIST *pList, _In_ const PROPERTYKEY *pKey, _In_ const UINT32 Occurrence, _Out_ ULONG *pRetValue ); NTSTATUS PropKeyFindKeyGetNthUshort( _In_ const SENSOR_COLLECTION_LIST *pList, _In_ const PROPERTYKEY *pKey, _In_ const UINT32 Occurrence, _Out_ USHORT *pRetValue ); NTSTATUS PropKeyFindKeyGetNthInt64( _In_ const SENSOR_COLLECTION_LIST *pList, _In_ const PROPERTYKEY *pKey, _In_ const UINT32 Occurrence, _Out_ INT64 *pRetValue ); BOOLEAN IsKeyPresentInPropertyList( _In_ PSENSOR_PROPERTY_LIST pList, _In_ const PROPERTYKEY *pKey ); BOOLEAN IsKeyPresentInCollectionList( _In_ PSENSOR_COLLECTION_LIST pList, _In_ const PROPERTYKEY *pKey ); BOOLEAN IsCollectionListSame( _In_ const PSENSOR_COLLECTION_LIST ListA, _In_ const PSENSOR_COLLECTION_LIST ListB ); NTSTATUS PropVariantGetInformation( _In_ const PROPVARIANT *PropVariantValue, _Out_opt_ ULONG *PropVariantOffset, _Out_opt_ ULONG *PropVariantSize, _Outptr_opt_result_bytebuffer_maybenull_(*PropVariantSize) PVOID *PropVariantPointer, _Out_opt_ DEVPROPTYPE *RemappedType ); NTSTATUS PropertiesListCopy( _Inout_ PSENSOR_PROPERTY_LIST Target, _In_ const PSENSOR_PROPERTY_LIST Source ); ULONG PropertiesListGetFillableCount( _In_ ULONG BufferSizeBytes ); /////////////////////////////////////////////////////////////////////////////// // // // Collection List Marshaling Legacy Helpers // // Architecture-specific - Avoid using for data across process boundaries // // // /////////////////////////////////////////////////////////////////////////////// ULONG CollectionsListGetMarshalledSize( _In_ const PSENSOR_COLLECTION_LIST Collection ); NTSTATUS CollectionsListCopyAndMarshall( _Inout_ PSENSOR_COLLECTION_LIST Target, _In_ const PSENSOR_COLLECTION_LIST Source ); NTSTATUS CollectionsListMarshall( _Inout_ PSENSOR_COLLECTION_LIST Target ); ULONG CollectionsListGetMarshalledSizeWithoutSerialization( _In_ const PSENSOR_COLLECTION_LIST Collection ); NTSTATUS CollectionsListUpdateMarshalledPointer( _Inout_ PSENSOR_COLLECTION_LIST Collection ); /////////////////////////////////////////////////////////////////////////////// // // // Collection List Serialization Helpers // // Architecture-independent - Safe to use for data across process boundaries // // (for example, during DeviceIoControl) // // // /////////////////////////////////////////////////////////////////////////////// NTSTATUS SerializationBufferAllocate( _In_ ULONG SizeInBytes, _Outptr_result_bytebuffer_(SizeInBytes) BYTE** pBuffer ); VOID SerializationBufferFree( _In_opt_ BYTE* Buffer ); ULONG CollectionsListGetSerializedSize( _In_ const PSENSOR_COLLECTION_LIST Collection ); NTSTATUS CollectionsListSerializeToBuffer( _In_ const PSENSOR_COLLECTION_LIST SourceCollection, _In_ ULONG TargetBufferSizeInBytes, _Out_writes_bytes_(TargetBufferSizeInBytes) BYTE* TargetBuffer ); NTSTATUS CollectionsListAllocateBufferAndSerialize( _In_ const PSENSOR_COLLECTION_LIST SourceCollection, _Out_ ULONG* pTargetBufferSizeInBytes, _Outptr_result_bytebuffer_(*pTargetBufferSizeInBytes) BYTE** pTargetBuffer ); NTSTATUS CollectionsListDeserializeFromBuffer( _In_ ULONG SourceBufferSizeInBytes, _In_reads_bytes_(SourceBufferSizeInBytes) const BYTE* SourceBuffer, _Inout_ PSENSOR_COLLECTION_LIST TargetCollection ); /////////////////////////////////////////////////////////////////////////////// // // // Collection List Helper // // // /////////////////////////////////////////////////////////////////////////////// NTSTATUS SensorCollectionGetAt( _In_ UINT32 Index, _In_ PSENSOR_COLLECTION_LIST pSensorsList, _Out_opt_ PROPERTYKEY* pKey, _Out_opt_ PROPVARIANT* pValue ); ULONG CollectionsListGetFillableCount( _In_ ULONG BufferSizeBytes ); BOOLEAN EvaluateActivityThresholds( _In_ PSENSOR_COLLECTION_LIST newSample, _In_ PSENSOR_COLLECTION_LIST oldSample, _In_ PSENSOR_COLLECTION_LIST thresholds ); NTSTATUS CollectionsListSortSubscribedActivitiesByConfidence( _In_ PSENSOR_COLLECTION_LIST thresholds, _Inout_updates_bytes_(pCollection->AllocatedSizeInBytes) PSENSOR_COLLECTION_LIST pCollection ); HRESULT InitPropVariantFromCLSIDArray( _In_reads_(size) GUID *members, _In_ ULONG size, _Out_ PROPVARIANT *ppropvar ); BOOLEAN IsSensorSubscribed( _In_ PSENSOR_COLLECTION_LIST subscriptionList, _In_ GUID currentType ); BOOLEAN IsGUIDPresentInList( _In_reads_(arrayLength) const GUID *guidArray, _In_ const ULONG arrayLength, _In_ const GUID *guidElem ); #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */ #ifdef __cplusplus } #endif
5718f94aaaae9719c05f29b2968f1d7b5531aa81
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/thermal/sunxi_gpu_cooling.h
786200bdba3153e6a7c8a9709352431ee6beee66
[ "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
425
h
sunxi_gpu_cooling.h
#ifndef SUNXI_GPU_COOLING_H #define SUNXI_GPU_COOLING_H #include <linux/thermal.h> #define GPU_FREQ_TABLE_MAX (10) struct sunxi_gpu_cooling_device { struct device *dev; struct thermal_cooling_device *cool_dev; int (*cool) (int); u32 cooling_state; u32 state_num; u32 gpu_freq_limit; u32 gpu_freq_roof; u32 gpu_freq_floor; u32 freq_table[GPU_FREQ_TABLE_MAX]; spinlock_t lock; }; #endif /* SUNXI_GPU_COOLING_H */
ddca167ad06bc6cf69f7a231cd3085c14eb0b2f0
b41843c7eb48e897d9195bb2b239071b6a42721a
/libraries/base/include/CTypes.h
92084c78b4a0fd260f7ca254b05b7256cc679f08
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ghc/ghc
f19b08125f1f9ecf4df31e55fb90c32d18099071
ac29787c92551682ec89fcd71ac939becf69f051
refs/heads/master
2023-09-03T21:06:18.699382
2023-09-01T07:16:20
2023-09-01T18:30:02
1,560,597
2,927
791
NOASSERTION
2023-07-08T14:10:40
2011-04-02T19:39:34
Haskell
UTF-8
C
false
false
1,520
h
CTypes.h
{- -------------------------------------------------------------------------- // Dirty CPP hackery for CTypes/CTypesISO // // (c) The FFI task force, 2000 // -------------------------------------------------------------------------- -} #pragma once {- // As long as there is no automatic derivation of classes for newtypes we resort // to extremely dirty cpp-hackery. :-P Some care has to be taken when the // macros below are modified, otherwise the layout rule will bite you. -} -- // GHC can derive any class for a newtype, so we make use of that here... #define ARITHMETIC_CLASSES Eq,Ord,Num,Enum,Storable,Real #define INTEGRAL_CLASSES Bounded,Integral,Bits,FiniteBits #define FLOATING_CLASSES Fractional,Floating,RealFrac,RealFloat #define OPAQUE_CLASSES Eq,Ord,Storable #define ARITHMETIC_TYPE(T,THE_CTYPE,B) \ newtype {-# CTYPE THE_CTYPE #-} T = T B deriving newtype (Read, Show, ARITHMETIC_CLASSES); #define INTEGRAL_TYPE(T,THE_CTYPE,B) \ newtype {-# CTYPE THE_CTYPE #-} T = T B \ deriving newtype (Read, Show, ARITHMETIC_CLASSES, INTEGRAL_CLASSES, Ix); #define FLOATING_TYPE(T,THE_CTYPE,B) \ newtype {-# CTYPE THE_CTYPE #-} T = T B deriving newtype (Read, Show, ARITHMETIC_CLASSES, FLOATING_CLASSES); #define FLOATING_TYPE_WITH_CTYPE(T,THE_CTYPE,B) \ newtype {-# CTYPE THE_CTYPE #-} T = T B \ deriving newtype (Read, Show, ARITHMETIC_CLASSES, FLOATING_CLASSES); #define OPAQUE_TYPE(T,THE_CTYPE,B) \ newtype {-# CTYPE THE_CTYPE #-} T = T (B) \ deriving newtype (Show, OPAQUE_CLASSES);
d080196b0db51f6439b858d93c4131223c37b9ac
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/third_party/musl/crypt_r.c
b272d0fb8b41ca79da9e13345f00c265d14793d1
[ "ISC" ]
permissive
jart/cosmopolitan
fb11b5658939023977060a7c6c71a74093d9cb44
0d748ad58e1063dd1f8560f18a0c75293b9415b7
refs/heads/master
2023-09-06T09:17:29.303607
2023-09-02T03:49:13
2023-09-02T03:50:18
272,457,606
11,887
435
ISC
2023-09-14T17:47:58
2020-06-15T14:16:13
C
UTF-8
C
false
false
3,933
c
crypt_r.c
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-β”‚ β”‚vi: set et ft=c ts=8 tw=8 fenc=utf-8 :viβ”‚ β•šβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β• β”‚ β”‚ β”‚ Musl Libc β”‚ β”‚ Copyright Β© 2005-2014 Rich Felker, et al. β”‚ β”‚ β”‚ β”‚ Permission is hereby granted, free of charge, to any person obtaining β”‚ β”‚ a copy of this software and associated documentation files (the β”‚ β”‚ "Software"), to deal in the Software without restriction, including β”‚ β”‚ without limitation the rights to use, copy, modify, merge, publish, β”‚ β”‚ distribute, sublicense, and/or sell copies of the Software, and to β”‚ β”‚ permit persons to whom the Software is furnished to do so, subject to β”‚ β”‚ the following conditions: β”‚ β”‚ β”‚ β”‚ The above copyright notice and this permission notice shall be β”‚ β”‚ included in all copies or substantial portions of the Software. β”‚ β”‚ β”‚ β”‚ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, β”‚ β”‚ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF β”‚ β”‚ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. β”‚ β”‚ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY β”‚ β”‚ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, β”‚ β”‚ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE β”‚ β”‚ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. β”‚ β”‚ β”‚ β•šβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€*/ #include "third_party/musl/crypt.h" #include "third_party/musl/crypt.internal.h" asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /** * Encrypts password the old fashioned way. * * The method of encryption depends on the first three chars of salt: * * - `$1$` is MD5 * - `$2$` is Blowfish * - `$5$` is SHA-256 * - `$6$` is SHA-512 * - Otherwise DES * * @return static memory with encrypted password * @see third_party/argon2/ */ char *crypt_r(const char *key, const char *salt, struct crypt_data *data) { /* Per the crypt_r API, the caller has provided a pointer to * struct crypt_data; however, this implementation does not * use the structure to store any internal state, and treats * it purely as a char buffer for storing the result. */ char *output = (char *)data; if (salt[0] == '$' && salt[1] && salt[2]) { if (salt[1] == '1' && salt[2] == '$') return __crypt_md5(key, salt, output); if (salt[1] == '2' && salt[3] == '$') return __crypt_blowfish(key, salt, output); if (salt[1] == '5' && salt[2] == '$') return __crypt_sha256(key, salt, output); if (salt[1] == '6' && salt[2] == '$') return __crypt_sha512(key, salt, output); } return __crypt_des(key, salt, output); }
098215ccc4d48f8c8a81497c048161ed5498e24b
fb0f9abad373cd635c2635bbdf491ea0f32da5ff
/src/native/public/mono/metadata/details/mono-gc-functions.h
6208110d1c789c82613d3e77dd1f4d91fd83d429
[ "MIT" ]
permissive
dotnet/runtime
f6fd23936752e202f8e4d6d94f3a4f3b0e77f58f
47bb554d298e1e34c4e3895d7731e18ad1c47d02
refs/heads/main
2023-09-03T15:35:46.493337
2023-09-03T08:13:23
2023-09-03T08:13:23
210,716,005
13,765
5,179
MIT
2023-09-14T21:58:52
2019-09-24T23:36:39
C#
UTF-8
C
false
false
1,282
h
mono-gc-functions.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // This file does not have ifdef guards, it is meant to be included multiple times with different definitions of MONO_API_FUNCTION #ifndef MONO_API_FUNCTION #error "MONO_API_FUNCTION(ret,name,args) macro not defined before including function declaration header" #endif MONO_API_FUNCTION(void, mono_gc_collect, (int generation)) MONO_API_FUNCTION(int, mono_gc_max_generation, (void)) MONO_API_FUNCTION(int, mono_gc_get_generation, (MonoObject *object)) MONO_API_FUNCTION(int, mono_gc_collection_count, (int generation)) MONO_API_FUNCTION(int64_t, mono_gc_get_generation_size, (int generation)) MONO_API_FUNCTION(int64_t, mono_gc_get_used_size, (void)) MONO_API_FUNCTION(int64_t, mono_gc_get_heap_size, (void)) MONO_API_FUNCTION(MonoBoolean, mono_gc_pending_finalizers, (void)) MONO_API_FUNCTION(void, mono_gc_finalize_notify, (void)) MONO_API_FUNCTION(int, mono_gc_invoke_finalizers, (void)) /* heap walking is only valid in the pre-stop-world event callback */ MONO_API_FUNCTION(int, mono_gc_walk_heap, (int flags, MonoGCReferences callback, void *data)) MONO_API_FUNCTION(MONO_RT_EXTERNAL_ONLY void, mono_gc_init_finalizer_thread, (void))
a23ac3d36f51e670b53b4bd29eb7a4c150d7ce98
aa3befea459382dc5c01c925653d54f435b3fb0f
/arch/arm/src/sam34/hardware/sam4s_pio.h
42d1c631f90475550b56460e3d0c00854a6e42ec
[ "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
25,413
h
sam4s_pio.h
/**************************************************************************** * arch/arm/src/sam34/hardware/sam4s_pio.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ #ifndef __ARCH_ARM_SRC_SAM34_HARDWARE_SAM4S_PIO_H #define __ARCH_ARM_SRC_SAM34_HARDWARE_SAM4S_PIO_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include "chip.h" #include "hardware/sam_memorymap.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* PIO register offsets *****************************************************/ #define SAM_PIO_PER_OFFSET 0x0000 /* PIO Enable Register */ #define SAM_PIO_PDR_OFFSET 0x0004 /* PIO Disable Register */ #define SAM_PIO_PSR_OFFSET 0x0008 /* PIO Status Register */ /* 0x000c: Reserved */ #define SAM_PIO_OER_OFFSET 0x0010 /* Output Enable Register */ #define SAM_PIO_ODR_OFFSET 0x0014 /* Output Disable Register */ #define SAM_PIO_OSR_OFFSET 0x0018 /* Output Status Register */ /* 0x001c: Reserved */ #define SAM_PIO_IFER_OFFSET 0x0020 /* Glitch Input Filter Enable Register */ #define SAM_PIO_IFDR_OFFSET 0x0024 /* Glitch Input Filter Disable Register */ #define SAM_PIO_IFSR_OFFSET 0x0028 /* Glitch Input Filter Status Register */ /* 0x002c: Reserved */ #define SAM_PIO_SODR_OFFSET 0x0030 /* Set Output Data Register */ #define SAM_PIO_CODR_OFFSET 0x0034 /* Clear Output Data Register */ #define SAM_PIO_ODSR_OFFSET 0x0038 /* Output Data Status Register */ #define SAM_PIO_PDSR_OFFSET 0x003c /* Pin Data Status Register */ #define SAM_PIO_IER_OFFSET 0x0040 /* Interrupt Enable Register */ #define SAM_PIO_IDR_OFFSET 0x0044 /* Interrupt Disable Register */ #define SAM_PIO_IMR_OFFSET 0x0048 /* Interrupt Mask Register */ #define SAM_PIO_ISR_OFFSET 0x004c /* Interrupt Status Register */ #define SAM_PIO_MDER_OFFSET 0x0050 /* Multi-driver Enable Register */ #define SAM_PIO_MDDR_OFFSET 0x0054 /* Multi-driver Disable Register */ #define SAM_PIO_MDSR_OFFSET 0x0058 /* Multi-driver Status Register */ /* 0x005c: Reserved */ #define SAM_PIO_PUDR_OFFSET 0x0060 /* Pull-up Disable Register */ #define SAM_PIO_PUER_OFFSET 0x0064 /* Pull-up Enable Register */ #define SAM_PIO_PUSR_OFFSET 0x0068 /* Pad Pull-up Status Register */ /* 0x006c: Reserved */ #define SAM_PIO_ABCDSR1_OFFSET 0x0070 /* Peripheral Select Register 1 */ #define SAM_PIO_ABCDSR2_OFFSET 0x0074 /* Peripheral Select Register 2 */ /* 0x0078-0x007c: Reserved */ #define SAM_PIO_IFSCDR_OFFSET 0x0080 /* Input Filter Slow Clock Disable Register */ #define SAM_PIO_IFSCER_OFFSET 0x0084 /* Input Filter Slow Clock Enable Register */ #define SAM_PIO_IFSCSR_OFFSET 0x0088 /* Input Filter Slow Clock Status Register */ #define SAM_PIO_SCDR_OFFSET 0x008c /* Slow Clock Divider Debouncing Register */ #define SAM_PIO_PPDDR_OFFSET 0x0090 /* Pad Pull Down Disable Register */ #define SAM_PIO_PPDER_OFFSET 0x0094 /* PIO Pad Pull Down Enable Register */ #define SAM_PIO_PPDSR_OFFSET 0x0098 /* PIO Pad Pull Down Status Register */ /* 0x009c: Reserved */ #define SAM_PIO_OWER_OFFSET 0x00a0 /* Output Write Enable */ #define SAM_PIO_OWDR_OFFSET 0x00a4 /* Output Write Disable */ #define SAM_PIO_OWSR_OFFSET 0x00a8 /* Output Write Status Register */ /* 0x00ac: Reserved */ #define SAM_PIO_AIMER_OFFSET 0x00b0 /* Additional Interrupt Modes Enable Register */ #define SAM_PIO_AIMDR_OFFSET 0x00b4 /* Additional Interrupt Modes Disables Register */ #define SAM_PIO_AIMMR_OFFSET 0x00b8 /* Additional Interrupt Modes Mask Register */ /* 0x00bc: Reserved */ #define SAM_PIO_ESR_OFFSET 0x00c0 /* Edge Select Register */ #define SAM_PIO_LSR_OFFSET 0x00c4 /* Level Select Register */ #define SAM_PIO_ELSR_OFFSET 0x00c8 /* Edge/Level Status Register */ /* 0x00cc: Reserved */ #define SAM_PIO_FELLSR_OFFSET 0x00d0 /* Falling Edge/Low Level Select Register */ #define SAM_PIO_REHLSR_OFFSET 0x00d4 /* Rising Edge/ High Level Select Register */ #define SAM_PIO_FRLHSR_OFFSET 0x00d8 /* Fall/Rise - Low/High Status Register */ /* 0x00dc: Reserved */ #define SAM_PIO_LOCKSR_OFFSET 0x00e0 /* Lock Status */ #define SAM_PIO_WPMR_OFFSET 0x00e4 /* Write Protect Mode Register */ #define SAM_PIO_WPSR_OFFSET 0x00e8 /* Write Protect Status Register */ /* 0x00ec-0x00f8: Reserved */ #define SAM_PIO_SCHMITT_OFFSET 0x0100 /* Schmitt Trigger Register */ /* 0x0104-0x14c: Reserved */ #define SAM_PIO_PCMR_OFFSET 0x0150 /* Parallel Capture Mode Register */ #define SAM_PIO_PCIER_OFFSET 0x0154 /* Parallel Capture Interrupt Enable Register */ #define SAM_PIO_PCIDR_OFFSET 0x0158 /* Parallel Capture Interrupt Disable Register */ #define SAM_PIO_PCIMR_OFFSET 0x015c /* Parallel Capture Interrupt Mask Register */ #define SAM_PIO_PCISR_OFFSET 0x0160 /* Parallel Capture Interrupt Status Register */ #define SAM_PIO_PCRHR_OFFSET 0x0164 /* Parallel Capture Reception Holding Register */ /* 0x0168-0x018c: Reserved for PDC registers */ /* PIO register addresses ***************************************************/ #define PIOA (0) #define PIOB (1) #define PIOC (2) #define NPIO (3) #define SAM_PIO_PER(n) (SAM_PIO_BASE(n)+SAM_PIO_PER_OFFSET) #define SAM_PIO_PDR(n) (SAM_PIO_BASE(n)+SAM_PIO_PDR_OFFSET) #define SAM_PIO_PSR(n) (SAM_PIO_BASE(n)+SAM_PIO_PSR_OFFSET) #define SAM_PIO_OER(n) (SAM_PIO_BASE(n)+SAM_PIO_OER_OFFSET) #define SAM_PIO_ODR(n) (SAM_PIO_BASE(n)+SAM_PIO_ODR_OFFSET) #define SAM_PIO_OSR(n) (SAM_PIO_BASE(n)+SAM_PIO_OSR_OFFSET) #define SAM_PIO_IFER(n) (SAM_PIO_BASE(n)+SAM_PIO_IFER_OFFSET) #define SAM_PIO_IFDR(n) (SAM_PIO_BASE(n)+SAM_PIO_IFDR_OFFSET) #define SAM_PIO_IFSR(n) (SAM_PIO_BASE(n)+SAM_PIO_IFSR_OFFSET) #define SAM_PIO_SODR(n) (SAM_PIO_BASE(n)+SAM_PIO_SODR_OFFSET) #define SAM_PIO_CODR(n) (SAM_PIO_BASE(n)+SAM_PIO_CODR_OFFSET) #define SAM_PIO_ODSR(n) (SAM_PIO_BASE(n)+SAM_PIO_ODSR_OFFSET) #define SAM_PIO_PDSR(n) (SAM_PIO_BASE(n)+SAM_PIO_PDSR_OFFSET) #define SAM_PIO_IER(n) (SAM_PIO_BASE(n)+SAM_PIO_IER_OFFSET) #define SAM_PIO_IDR(n) (SAM_PIO_BASE(n)+SAM_PIO_IDR_OFFSET) #define SAM_PIO_IMR(n) (SAM_PIO_BASE(n)+SAM_PIO_IMR_OFFSET) #define SAM_PIO_ISR(n) (SAM_PIO_BASE(n)+SAM_PIO_ISR_OFFSET) #define SAM_PIO_MDER(n) (SAM_PIO_BASE(n)+SAM_PIO_MDER_OFFSET) #define SAM_PIO_MDDR(n) (SAM_PIO_BASE(n)+SAM_PIO_MDDR_OFFSET) #define SAM_PIO_MDSR(n) (SAM_PIO_BASE(n)+SAM_PIO_MDSR_OFFSET) #define SAM_PIO_PUDR(n) (SAM_PIO_BASE(n)+SAM_PIO_PUDR_OFFSET) #define SAM_PIO_PUER(n) (SAM_PIO_BASE(n)+SAM_PIO_PUER_OFFSET) #define SAM_PIO_PUSR(n) (SAM_PIO_BASE(n)+SAM_PIO_PUSR_OFFSET) #define SAM_PIO_ABCDSR1(n) (SAM_PIO_BASE(n)+SAM_PIO_ABCDSR1_OFFSET) #define SAM_PIO_ABCDSR2(n) (SAM_PIO_BASE(n)+SAM_PIO_ABCDSR2_OFFSET) #define SAM_PIO_IFSCDR(n) (SAM_PIO_BASE(n)+SAM_PIO_IFSCDR_OFFSET) #define SAM_PIO_IFSCER(n) (SAM_PIO_BASE(n)+SAM_PIO_IFSCER_OFFSET) #define SAM_PIO_IFSCSR(n) (SAM_PIO_BASE(n)+SAM_PIO_IFSCSR_OFFSET) #define SAM_PIO_SCDR(n) (SAM_PIO_BASE(n)+SAM_PIO_SCDR_OFFSET) #define SAM_PIO_PPDDR(n) (SAM_PIO_BASE(n)+SAM_PIO_PPDDR_OFFSET) #define SAM_PIO_PPDER(n) (SAM_PIO_BASE(n)+SAM_PIO_PPDER_OFFSET) #define SAM_PIO_PPDSR(n) (SAM_PIO_BASE(n)+SAM_PIO_PPDSR_OFFSET) #define SAM_PIO_OWER(n) (SAM_PIO_BASE(n)+SAM_PIO_OWER_OFFSET) #define SAM_PIO_OWDR(n) (SAM_PIO_BASE(n)+SAM_PIO_OWDR_OFFSET) #define SAM_PIO_OWSR(n) (SAM_PIO_BASE(n)+SAM_PIO_OWSR_OFFSET) #define SAM_PIO_AIMER(n) (SAM_PIO_BASE(n)+SAM_PIO_AIMER_OFFSET) #define SAM_PIO_AIMDR(n) (SAM_PIO_BASE(n)+SAM_PIO_AIMDR_OFFSET) #define SAM_PIO_AIMMR(n) (SAM_PIO_BASE(n)+SAM_PIO_AIMMR_OFFSET) #define SAM_PIO_ESR(n) (SAM_PIO_BASE(n)+SAM_PIO_ESR_OFFSET) #define SAM_PIO_LSR(n) (SAM_PIO_BASE(n)+SAM_PIO_LSR_OFFSET) #define SAM_PIO_ELSR(n) (SAM_PIO_BASE(n)+SAM_PIO_ELSR_OFFSET) #define SAM_PIO_FELLSR(n) (SAM_PIO_BASE(n)+SAM_PIO_FELLSR_OFFSET) #define SAM_PIO_REHLSR(n) (SAM_PIO_BASE(n)+SAM_PIO_REHLSR_OFFSET) #define SAM_PIO_FRLHSR(n) (SAM_PIO_BASE(n)+SAM_PIO_FRLHSR_OFFSET) #define SAM_PIO_LOCKSR(n) (SAM_PIO_BASE(n)+SAM_PIO_LOCKSR_OFFSET) #define SAM_PIO_WPMR(n) (SAM_PIO_BASE(n)+SAM_PIO_WPMR_OFFSET) #define SAM_PIO_WPSR(n) (SAM_PIO_BASE(n)+SAM_PIO_WPSR_OFFSET) #define SAM_PIO_SCHMITT(n) (SAM_PIO_BASE(n)+SAM_PIO_SCHMITT_OFFSET) #define SAM_PIO_PCMR(n) (SAM_PIO_BASE(n)+SAM_PIO_PCMR_OFFSET) #define SAM_PIO_PCIER(n) (SAM_PIO_BASE(n)+SAM_PIO_PCIER_OFFSET) #define SAM_PIO_PCIDR(n) (SAM_PIO_BASE(n)+SAM_PIO_PCIDR_OFFSET) #define SAM_PIO_PCIMR(n) (SAM_PIO_BASE(n)+SAM_PIO_PCIMR_OFFSET) #define SAM_PIO_PCISR(n) (SAM_PIO_BASE(n)+SAM_PIO_PCISR_OFFSET) #define SAM_PIO_PCRHR(n) (SAM_PIO_BASE(n)+SAM_PIO_PCRHR_OFFSET #define SAM_PIOA_PER (SAM_PIOA_BASE+SAM_PIO_PER_OFFSET) #define SAM_PIOA_PDR (SAM_PIOA_BASE+SAM_PIO_PDR_OFFSET) #define SAM_PIOA_PSR (SAM_PIOA_BASE+SAM_PIO_PSR_OFFSET) #define SAM_PIOA_OER (SAM_PIOA_BASE+SAM_PIO_OER_OFFSET) #define SAM_PIOA_ODR (SAM_PIOA_BASE+SAM_PIO_ODR_OFFSET) #define SAM_PIOA_OSR (SAM_PIOA_BASE+SAM_PIO_OSR_OFFSET) #define SAM_PIOA_IFER (SAM_PIOA_BASE+SAM_PIO_IFER_OFFSET) #define SAM_PIOA_IFDR (SAM_PIOA_BASE+SAM_PIO_IFDR_OFFSET) #define SAM_PIOA_IFSR (SAM_PIOA_BASE+SAM_PIO_IFSR_OFFSET) #define SAM_PIOA_SODR (SAM_PIOA_BASE+SAM_PIO_SODR_OFFSET) #define SAM_PIOA_CODR (SAM_PIOA_BASE+SAM_PIO_CODR_OFFSET) #define SAM_PIOA_ODSR (SAM_PIOA_BASE+SAM_PIO_ODSR_OFFSET) #define SAM_PIOA_PDSR (SAM_PIOA_BASE+SAM_PIO_PDSR_OFFSET) #define SAM_PIOA_IER (SAM_PIOA_BASE+SAM_PIO_IER_OFFSET) #define SAM_PIOA_IDR (SAM_PIOA_BASE+SAM_PIO_IDR_OFFSET) #define SAM_PIOA_IMR (SAM_PIOA_BASE+SAM_PIO_IMR_OFFSET) #define SAM_PIOA_ISR (SAM_PIOA_BASE+SAM_PIO_ISR_OFFSET) #define SAM_PIOA_MDER (SAM_PIOA_BASE+SAM_PIO_MDER_OFFSET) #define SAM_PIOA_MDDR (SAM_PIOA_BASE+SAM_PIO_MDDR_OFFSET) #define SAM_PIOA_MDSR (SAM_PIOA_BASE+SAM_PIO_MDSR_OFFSET) #define SAM_PIOA_PUDR (SAM_PIOA_BASE+SAM_PIO_PUDR_OFFSET) #define SAM_PIOA_PUER (SAM_PIOA_BASE+SAM_PIO_PUER_OFFSET) #define SAM_PIOA_PUSR (SAM_PIOA_BASE+SAM_PIO_PUSR_OFFSET) #define SAM_PIOA_ABCDSR1 (SAM_PIOA_BASE+SAM_PIO_ABCDSR1_OFFSET) #define SAM_PIOA_ABCDSR2 (SAM_PIOA_BASE+SAM_PIO_ABCDSR2_OFFSET) #define SAM_PIOA_IFSCDR (SAM_PIOA_BASE+SAM_PIO_IFSCDR_OFFSET) #define SAM_PIOA_IFSCER (SAM_PIOA_BASE+SAM_PIO_IFSCER_OFFSET) #define SAM_PIOA_IFSCSR (SAM_PIOA_BASE+SAM_PIO_IFSCSR_OFFSET) #define SAM_PIOA_SCDR (SAM_PIOA_BASE+SAM_PIO_SCDR_OFFSET) #define SAM_PIOA_PPDDR (SAM_PIOA_BASE+SAM_PIO_PPDDR_OFFSET) #define SAM_PIOA_PPDER (SAM_PIOA_BASE+SAM_PIO_PPDER_OFFSET) #define SAM_PIOA_PPDSR (SAM_PIOA_BASE+SAM_PIO_PPDSR_OFFSET) #define SAM_PIOA_OWER (SAM_PIOA_BASE+SAM_PIO_OWER_OFFSET) #define SAM_PIOA_OWDR (SAM_PIOA_BASE+SAM_PIO_OWDR_OFFSET) #define SAM_PIOA_OWSR (SAM_PIOA_BASE+SAM_PIO_OWSR_OFFSET) #define SAM_PIOA_AIMER (SAM_PIOA_BASE+SAM_PIO_AIMER_OFFSET) #define SAM_PIOA_AIMDR (SAM_PIOA_BASE+SAM_PIO_AIMDR_OFFSET) #define SAM_PIOA_AIMMR (SAM_PIOA_BASE+SAM_PIO_AIMMR_OFFSET) #define SAM_PIOA_ESR (SAM_PIOA_BASE+SAM_PIO_ESR_OFFSET) #define SAM_PIOA_LSR (SAM_PIOA_BASE+SAM_PIO_LSR_OFFSET) #define SAM_PIOA_ELSR (SAM_PIOA_BASE+SAM_PIO_ELSR_OFFSET) #define SAM_PIOA_FELLSR (SAM_PIOA_BASE+SAM_PIO_FELLSR_OFFSET) #define SAM_PIOA_REHLSR (SAM_PIOA_BASE+SAM_PIO_REHLSR_OFFSET) #define SAM_PIOA_FRLHSR (SAM_PIOA_BASE+SAM_PIO_FRLHSR_OFFSET) #define SAM_PIOA_LOCKSR (SAM_PIOA_BASE+SAM_PIO_LOCKSR_OFFSET) #define SAM_PIOA_WPMR (SAM_PIOA_BASE+SAM_PIO_WPMR_OFFSET) #define SAM_PIOA_WPSR (SAM_PIOA_BASE+SAM_PIO_WPSR_OFFSET) #define SAM_PIOA_SCHMITT (SAM_PIOA_BASE+SAM_PIO_SCHMITT_OFFSET) #define SAM_PIOA_PCMR (SAM_PIOA_BASE+SAM_PIO_PCMR_OFFSET) #define SAM_PIOA_PCIER (SAM_PIOA_BASE+SAM_PIO_PCIER_OFFSET) #define SAM_PIOA_PCIDR (SAM_PIOA_BASE+SAM_PIO_PCIDR_OFFSET) #define SAM_PIOA_PCIMR (SAM_PIOA_BASE+SAM_PIO_PCIMR_OFFSET) #define SAM_PIOA_PCISR (SAM_PIOA_BASE+SAM_PIO_PCISR_OFFSET) #define SAM_PIOA_PCRHR (SAM_PIOA_BASE+SAM_PIO_PCRHR_OFFSET #define SAM_PIOB_PER (SAM_PIOB_BASE+SAM_PIO_PER_OFFSET) #define SAM_PIOB_PDR (SAM_PIOB_BASE+SAM_PIO_PDR_OFFSET) #define SAM_PIOB_PSR (SAM_PIOB_BASE+SAM_PIO_PSR_OFFSET) #define SAM_PIOB_OER (SAM_PIOB_BASE+SAM_PIO_OER_OFFSET) #define SAM_PIOB_ODR (SAM_PIOB_BASE+SAM_PIO_ODR_OFFSET) #define SAM_PIOB_OSR (SAM_PIOB_BASE+SAM_PIO_OSR_OFFSET) #define SAM_PIOB_IFER (SAM_PIOB_BASE+SAM_PIO_IFER_OFFSET) #define SAM_PIOB_IFDR (SAM_PIOB_BASE+SAM_PIO_IFDR_OFFSET) #define SAM_PIOB_IFSR (SAM_PIOB_BASE+SAM_PIO_IFSR_OFFSET) #define SAM_PIOB_SODR (SAM_PIOB_BASE+SAM_PIO_SODR_OFFSET) #define SAM_PIOB_CODR (SAM_PIOB_BASE+SAM_PIO_CODR_OFFSET) #define SAM_PIOB_ODSR (SAM_PIOB_BASE+SAM_PIO_ODSR_OFFSET) #define SAM_PIOB_PDSR (SAM_PIOB_BASE+SAM_PIO_PDSR_OFFSET) #define SAM_PIOB_IER (SAM_PIOB_BASE+SAM_PIO_IER_OFFSET) #define SAM_PIOB_IDR (SAM_PIOB_BASE+SAM_PIO_IDR_OFFSET) #define SAM_PIOB_IMR (SAM_PIOB_BASE+SAM_PIO_IMR_OFFSET) #define SAM_PIOB_ISR (SAM_PIOB_BASE+SAM_PIO_ISR_OFFSET) #define SAM_PIOB_MDER (SAM_PIOB_BASE+SAM_PIO_MDER_OFFSET) #define SAM_PIOB_MDDR (SAM_PIOB_BASE+SAM_PIO_MDDR_OFFSET) #define SAM_PIOB_MDSR (SAM_PIOB_BASE+SAM_PIO_MDSR_OFFSET) #define SAM_PIOB_PUDR (SAM_PIOB_BASE+SAM_PIO_PUDR_OFFSET) #define SAM_PIOB_PUER (SAM_PIOB_BASE+SAM_PIO_PUER_OFFSET) #define SAM_PIOB_PUSR (SAM_PIOB_BASE+SAM_PIO_PUSR_OFFSET) #define SAM_PIOB_ABCDSR1 (SAM_PIOB_BASE+SAM_PIO_ABCDSR1_OFFSET) #define SAM_PIOB_ABCDSR2 (SAM_PIOB_BASE+SAM_PIO_ABCDSR2_OFFSET) #define SAM_PIOB_IFSCDR (SAM_PIOB_BASE+SAM_PIO_IFSCDR_OFFSET) #define SAM_PIOB_IFSCER (SAM_PIOB_BASE+SAM_PIO_IFSCER_OFFSET) #define SAM_PIOB_IFSCSR (SAM_PIOB_BASE+SAM_PIO_IFSCSR_OFFSET) #define SAM_PIOB_SCDR (SAM_PIOB_BASE+SAM_PIO_SCDR_OFFSET) #define SAM_PIOB_PPDDR (SAM_PIOB_BASE+SAM_PIO_PPDDR_OFFSET) #define SAM_PIOB_PPDER (SAM_PIOB_BASE+SAM_PIO_PPDER_OFFSET) #define SAM_PIOB_PPDSR (SAM_PIOB_BASE+SAM_PIO_PPDSR_OFFSET) #define SAM_PIOB_OWER (SAM_PIOB_BASE+SAM_PIO_OWER_OFFSET) #define SAM_PIOB_OWDR (SAM_PIOB_BASE+SAM_PIO_OWDR_OFFSET) #define SAM_PIOB_OWSR (SAM_PIOB_BASE+SAM_PIO_OWSR_OFFSET) #define SAM_PIOB_AIMER (SAM_PIOB_BASE+SAM_PIO_AIMER_OFFSET) #define SAM_PIOB_AIMDR (SAM_PIOB_BASE+SAM_PIO_AIMDR_OFFSET) #define SAM_PIOB_AIMMR (SAM_PIOB_BASE+SAM_PIO_AIMMR_OFFSET) #define SAM_PIOB_ESR (SAM_PIOB_BASE+SAM_PIO_ESR_OFFSET) #define SAM_PIOB_LSR (SAM_PIOB_BASE+SAM_PIO_LSR_OFFSET) #define SAM_PIOB_ELSR (SAM_PIOB_BASE+SAM_PIO_ELSR_OFFSET) #define SAM_PIOB_FELLSR (SAM_PIOB_BASE+SAM_PIO_FELLSR_OFFSET) #define SAM_PIOB_REHLSR (SAM_PIOB_BASE+SAM_PIO_REHLSR_OFFSET) #define SAM_PIOB_FRLHSR (SAM_PIOB_BASE+SAM_PIO_FRLHSR_OFFSET) #define SAM_PIOB_LOCKSR (SAM_PIOB_BASE+SAM_PIO_LOCKSR_OFFSET) #define SAM_PIOB_WPMR (SAM_PIOB_BASE+SAM_PIO_WPMR_OFFSET) #define SAM_PIOB_WPSR (SAM_PIOB_BASE+SAM_PIO_WPSR_OFFSET) #define SAM_PIOB_SCHMITT (SAM_PIOB_BASE+SAM_PIO_SCHMITT_OFFSET) #define SAM_PIOB_PCMR (SAM_PIOB_BASE+SAM_PIO_PCMR_OFFSET) #define SAM_PIOB_PCIER (SAM_PIOB_BASE+SAM_PIO_PCIER_OFFSET) #define SAM_PIOB_PCIDR (SAM_PIOB_BASE+SAM_PIO_PCIDR_OFFSET) #define SAM_PIOB_PCIMR (SAM_PIOB_BASE+SAM_PIO_PCIMR_OFFSET) #define SAM_PIOB_PCISR (SAM_PIOB_BASE+SAM_PIO_PCISR_OFFSET) #define SAM_PIOB_PCRHR (SAM_PIOB_BASE+SAM_PIO_PCRHR_OFFSET #define SAM_PIOC_PER (SAM_PIOC_BASE+SAM_PIO_PER_OFFSET) #define SAM_PIOC_PDR (SAM_PIOC_BASE+SAM_PIO_PDR_OFFSET) #define SAM_PIOC_PSR (SAM_PIOC_BASE+SAM_PIO_PSR_OFFSET) #define SAM_PIOC_OER (SAM_PIOC_BASE+SAM_PIO_OER_OFFSET) #define SAM_PIOC_ODR (SAM_PIOC_BASE+SAM_PIO_ODR_OFFSET) #define SAM_PIOC_OSR (SAM_PIOC_BASE+SAM_PIO_OSR_OFFSET) #define SAM_PIOC_IFER (SAM_PIOC_BASE+SAM_PIO_IFER_OFFSET) #define SAM_PIOC_IFDR (SAM_PIOC_BASE+SAM_PIO_IFDR_OFFSET) #define SAM_PIOC_IFSR (SAM_PIOC_BASE+SAM_PIO_IFSR_OFFSET) #define SAM_PIOC_SODR (SAM_PIOC_BASE+SAM_PIO_SODR_OFFSET) #define SAM_PIOC_CODR (SAM_PIOC_BASE+SAM_PIO_CODR_OFFSET) #define SAM_PIOC_ODSR (SAM_PIOC_BASE+SAM_PIO_ODSR_OFFSET) #define SAM_PIOC_PDSR (SAM_PIOC_BASE+SAM_PIO_PDSR_OFFSET) #define SAM_PIOC_IER (SAM_PIOC_BASE+SAM_PIO_IER_OFFSET) #define SAM_PIOC_IDR (SAM_PIOC_BASE+SAM_PIO_IDR_OFFSET) #define SAM_PIOC_IMR (SAM_PIOC_BASE+SAM_PIO_IMR_OFFSET) #define SAM_PIOC_ISR (SAM_PIOC_BASE+SAM_PIO_ISR_OFFSET) #define SAM_PIOC_MDER (SAM_PIOC_BASE+SAM_PIO_MDER_OFFSET) #define SAM_PIOC_MDDR (SAM_PIOC_BASE+SAM_PIO_MDDR_OFFSET) #define SAM_PIOC_MDSR (SAM_PIOC_BASE+SAM_PIO_MDSR_OFFSET) #define SAM_PIOC_PUDR (SAM_PIOC_BASE+SAM_PIO_PUDR_OFFSET) #define SAM_PIOC_PUER (SAM_PIOC_BASE+SAM_PIO_PUER_OFFSET) #define SAM_PIOC_PUSR (SAM_PIOC_BASE+SAM_PIO_PUSR_OFFSET) #define SAM_PIOC_ABCDSR1 (SAM_PIOC_BASE+SAM_PIO_ABCDSR1_OFFSET) #define SAM_PIOC_ABCDSR2 (SAM_PIOC_BASE+SAM_PIO_ABCDSR2_OFFSET) #define SAM_PIOC_IFSCDR (SAM_PIOC_BASE+SAM_PIO_IFSCDR_OFFSET) #define SAM_PIOC_IFSCER (SAM_PIOC_BASE+SAM_PIO_IFSCER_OFFSET) #define SAM_PIOC_IFSCSR (SAM_PIOC_BASE+SAM_PIO_IFSCSR_OFFSET) #define SAM_PIOC_SCDR (SAM_PIOC_BASE+SAM_PIO_SCDR_OFFSET) #define SAM_PIOC_PPDDR (SAM_PIOC_BASE+SAM_PIO_PPDDR_OFFSET) #define SAM_PIOC_PPDER (SAM_PIOC_BASE+SAM_PIO_PPDER_OFFSET) #define SAM_PIOC_PPDSR (SAM_PIOC_BASE+SAM_PIO_PPDSR_OFFSET) #define SAM_PIOC_OWER (SAM_PIOC_BASE+SAM_PIO_OWER_OFFSET) #define SAM_PIOC_OWDR (SAM_PIOC_BASE+SAM_PIO_OWDR_OFFSET) #define SAM_PIOC_OWSR (SAM_PIOC_BASE+SAM_PIO_OWSR_OFFSET) #define SAM_PIOC_AIMER (SAM_PIOC_BASE+SAM_PIO_AIMER_OFFSET) #define SAM_PIOC_AIMDR (SAM_PIOC_BASE+SAM_PIO_AIMDR_OFFSET) #define SAM_PIOC_AIMMR (SAM_PIOC_BASE+SAM_PIO_AIMMR_OFFSET) #define SAM_PIOC_ESR (SAM_PIOC_BASE+SAM_PIO_ESR_OFFSET) #define SAM_PIOC_LSR (SAM_PIOC_BASE+SAM_PIO_LSR_OFFSET) #define SAM_PIOC_ELSR (SAM_PIOC_BASE+SAM_PIO_ELSR_OFFSET) #define SAM_PIOC_FELLSR (SAM_PIOC_BASE+SAM_PIO_FELLSR_OFFSET) #define SAM_PIOC_REHLSR (SAM_PIOC_BASE+SAM_PIO_REHLSR_OFFSET) #define SAM_PIOC_FRLHSR (SAM_PIOC_BASE+SAM_PIO_FRLHSR_OFFSET) #define SAM_PIOC_LOCKSR (SAM_PIOC_BASE+SAM_PIO_LOCKSR_OFFSET) #define SAM_PIOC_WPMR (SAM_PIOC_BASE+SAM_PIO_WPMR_OFFSET) #define SAM_PIOC_WPSR (SAM_PIOC_BASE+SAM_PIO_WPSR_OFFSET) #define SAM_PIOC_SCHMITT (SAM_PIOC_BASE+SAM_PIO_SCHMITT_OFFSET) #define SAM_PIOC_PCMR (SAM_PIOC_BASE+SAM_PIO_PCMR_OFFSET) #define SAM_PIOC_PCIER (SAM_PIOC_BASE+SAM_PIO_PCIER_OFFSET) #define SAM_PIOC_PCIDR (SAM_PIOC_BASE+SAM_PIO_PCIDR_OFFSET) #define SAM_PIOC_PCIMR (SAM_PIOC_BASE+SAM_PIO_PCIMR_OFFSET) #define SAM_PIOC_PCISR (SAM_PIOC_BASE+SAM_PIO_PCISR_OFFSET) #define SAM_PIOC_PCRHR (SAM_PIOC_BASE+SAM_PIO_PCRHR_OFFSET /* PIO register bit definitions *********************************************/ /* Common bit definitions for ALMOST all IO registers (exceptions follow) */ #define PIO(n) (1 << (n)) /* Bit n: PIO n */ /* PIO Write Protect Mode Register */ #define PIO_WPMR_WPEN (1 << 0) /* Bit 0: Write Protect Enable */ #define PIO_WPMR_WPKEY_SHIFT (8) /* Bits 8-31: Write Protect KEY */ #define PIO_WPMR_WPKEY_MASK (0xffffff << PIO_WPMR_WPKEY_SHIFT) # define PIO_WPMR_WPKEY (0x50494f << PIO_WPMR_WPKEY_SHIFT) /* PIO Write Protect Status Register */ #define PIO_WPSR_WPVS (1 << 0) /* Bit 0: Write Protect Violation Status */ #define PIO_WPSR_WPVSRC_SHIFT (8) /* Bits 8-23: Write Protect Violation Source */ #define PIO_WPSR_WPVSRC_MASK (0xffff << PIO_WPSR_WPVSRC_SHIFT) /* PIO Parallel Capture Mode Register */ #define PIO_PCMR_PCEN (1 << 0) /* Bit 0: Parallel Capture Mode Enable */ #define PIO_PCMR_DSIZE_SHIFT (4) /* Bits 4-5: Parallel Capture Mode Data Size */ #define PIO_PCMR_DSIZE_MASK (3 << PIO_PCMR_DSIZE_SHIFT) # define PIO_PCMR_DSIZE_BYTE (0 << PIO_PCMR_DSIZE_SHIFT) /* 8-bit data in PIO_PCRHR */ # define PIO_PCMR_DSIZE_HWORD (1 << PIO_PCMR_DSIZE_SHIFT) /* 16-bit data in PIO_PCRHR */ # define PIO_PCMR_DSIZE_WORD (2 << PIO_PCMR_DSIZE_SHIFT) /* 32-bit data in PIO_PCRHR */ #define PIO_PCMR_ALWYS (1 << 9) /* Bit 9: Parallel Capture Mode Always Sampling */ #define PIO_PCMR_HALFS (1 << 10) /* Bit 10: Parallel Capture Mode Half Sampling */ #define PIO_PCMR_FRSTS (1 << 11) /* Bit 11: Parallel Capture Mode First Sample */ /* PIO Parallel Capture Interrupt Enable, Disable, Mask, * and Status Registers */ #define PIOC_PCINT_DRDY (1 << 0) /* Bit 0: Parallel Capture Mode Data Ready Interrupt Enable */ #define PIOC_PCINT_OVRE (1 << 1) /* Bit 1: Parallel Capture Mode Overrun Error Interrupt Enable */ #define PIOC_PCINT_ENDRX (1 << 2) /* Bit 2: End of Reception Transfer Interrupt Enable */ #define PIOC_PCINT_RXBUFF (1 << 3) /* Bit 3: Reception Buffer Full Interrupt Enable */ /**************************************************************************** * Public Types ****************************************************************************/ /**************************************************************************** * Public Data ****************************************************************************/ /**************************************************************************** * Public Functions Prototypes ****************************************************************************/ #endif /* __ARCH_ARM_SRC_SAM34_HARDWARE_SAM4S_PIO_H */