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
693989e2ee2a7712f46b602af7cca6f46f98c05c
76db964c1e74ba457a40f5407a74982d3d5d6f22
/core/interpreter/data.c
eb4408ab25af85fef2ffb1a2b02e33dba2d4770b
[ "Zlib" ]
permissive
timoinutilis/lowres-nx
dd2fd8eb103925e7fc2f66ce5c631d9a373b3e45
10a48e309ac5284724010eea56372fbc72b9f975
refs/heads/master
2023-04-08T22:05:33.039947
2023-03-23T15:02:02
2023-03-23T15:02:02
75,659,563
158
26
Zlib
2023-03-23T15:02:04
2016-12-05T19:38:19
JavaScript
UTF-8
C
false
false
2,214
c
data.c
// // Copyright 2017 Timo Kloss // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #include "data.h" #include "interpreter.h" void dat_nextData(struct Interpreter *interpreter) { interpreter->currentDataValueToken++; if (interpreter->currentDataValueToken->type == TokenComma) { // value follows interpreter->currentDataValueToken++; } else { // next DATA line interpreter->currentDataToken = interpreter->currentDataToken->jumpToken; if (interpreter->currentDataToken) { interpreter->currentDataValueToken = interpreter->currentDataToken + 1; // after DATA } else { interpreter->currentDataValueToken = NULL; } } } void dat_restoreData(struct Interpreter *interpreter, struct Token *jumpToken) { if (jumpToken) { struct Token *dataToken = interpreter->firstData; while (dataToken && dataToken < jumpToken) { dataToken = dataToken->jumpToken; } interpreter->currentDataToken = dataToken; } else { interpreter->currentDataToken = interpreter->firstData; } if (interpreter->currentDataToken) { interpreter->currentDataValueToken = interpreter->currentDataToken + 1; // after DATA } else { interpreter->currentDataValueToken = NULL; } }
85bb527af31e0467c02433a73d058ab9ea7d638c
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
/lib/libc/include/any-windows-any/ntddscsi.h
9466f359d3869687aa09b495e1edea1f3f3298cc
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
ziglang/zig
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
refs/heads/master
2023-08-31T13:16:45.980913
2023-08-31T05:50:29
2023-08-31T05:50:29
40,276,274
25,560
2,399
MIT
2023-09-14T21:09:50
2015-08-06T00:51:28
Zig
UTF-8
C
false
false
7,153
h
ntddscsi.h
/** * This file has no copyright assigned and is placed in the Public Domain. * This file is part of the mingw-w64 runtime package. * No warranty is given; refer to the file DISCLAIMER.PD within this package. */ #ifdef DEFINE_GUID #ifndef FAR #define FAR #endif DEFINE_GUID(ScsiRawInterfaceGuid,0x53f56309,0xb6bf,0x11d0,0x94,0xf2,0x00,0xa0,0xc9,0x1e,0xfb,0x8b); DEFINE_GUID(WmiScsiAddressGuid,0x53f5630f,0xb6bf,0x11d0,0x94,0xf2,0x00,0xa0,0xc9,0x1e,0xfb,0x8b); #endif /* DEFINE_GUID */ #ifndef _NTDDSCSIH_ #define _NTDDSCSIH_ #ifdef __cplusplus extern "C" { #endif #define IOCTL_SCSI_BASE FILE_DEVICE_CONTROLLER #define DD_SCSI_DEVICE_NAME "\\Device\\ScsiPort" #define DD_SCSI_DEVICE_NAME_U L"\\Device\\ScsiPort" #define IOCTL_SCSI_PASS_THROUGH CTL_CODE(IOCTL_SCSI_BASE,0x0401,METHOD_BUFFERED,FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_SCSI_MINIPORT CTL_CODE(IOCTL_SCSI_BASE,0x0402,METHOD_BUFFERED,FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_SCSI_GET_INQUIRY_DATA CTL_CODE(IOCTL_SCSI_BASE,0x0403,METHOD_BUFFERED,FILE_ANY_ACCESS) #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE(IOCTL_SCSI_BASE,0x0404,METHOD_BUFFERED,FILE_ANY_ACCESS) #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE(IOCTL_SCSI_BASE,0x0405,METHOD_BUFFERED,FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_SCSI_GET_ADDRESS CTL_CODE(IOCTL_SCSI_BASE,0x0406,METHOD_BUFFERED,FILE_ANY_ACCESS) #define IOCTL_SCSI_RESCAN_BUS CTL_CODE(IOCTL_SCSI_BASE,0x0407,METHOD_BUFFERED,FILE_ANY_ACCESS) #define IOCTL_SCSI_GET_DUMP_POINTERS CTL_CODE(IOCTL_SCSI_BASE,0x0408,METHOD_BUFFERED,FILE_ANY_ACCESS) #define IOCTL_SCSI_FREE_DUMP_POINTERS CTL_CODE(IOCTL_SCSI_BASE,0x0409,METHOD_BUFFERED,FILE_ANY_ACCESS) #define IOCTL_IDE_PASS_THROUGH CTL_CODE(IOCTL_SCSI_BASE,0x040a,METHOD_BUFFERED,FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_ATA_PASS_THROUGH CTL_CODE(IOCTL_SCSI_BASE,0x040b,METHOD_BUFFERED,FILE_READ_ACCESS | FILE_WRITE_ACCESS) #define IOCTL_ATA_PASS_THROUGH_DIRECT CTL_CODE(IOCTL_SCSI_BASE,0x040c,METHOD_BUFFERED,FILE_READ_ACCESS | FILE_WRITE_ACCESS) typedef struct _SCSI_PASS_THROUGH { USHORT Length; UCHAR ScsiStatus; UCHAR PathId; UCHAR TargetId; UCHAR Lun; UCHAR CdbLength; UCHAR SenseInfoLength; UCHAR DataIn; ULONG DataTransferLength; ULONG TimeOutValue; ULONG_PTR DataBufferOffset; ULONG SenseInfoOffset; UCHAR Cdb[16]; }SCSI_PASS_THROUGH,*PSCSI_PASS_THROUGH; typedef struct _SCSI_PASS_THROUGH_DIRECT { USHORT Length; UCHAR ScsiStatus; UCHAR PathId; UCHAR TargetId; UCHAR Lun; UCHAR CdbLength; UCHAR SenseInfoLength; UCHAR DataIn; ULONG DataTransferLength; ULONG TimeOutValue; PVOID DataBuffer; ULONG SenseInfoOffset; UCHAR Cdb[16]; }SCSI_PASS_THROUGH_DIRECT,*PSCSI_PASS_THROUGH_DIRECT; #if defined(_WIN64) typedef struct _SCSI_PASS_THROUGH32 { USHORT Length; UCHAR ScsiStatus; UCHAR PathId; UCHAR TargetId; UCHAR Lun; UCHAR CdbLength; UCHAR SenseInfoLength; UCHAR DataIn; ULONG DataTransferLength; ULONG TimeOutValue; ULONG32 DataBufferOffset; ULONG SenseInfoOffset; UCHAR Cdb[16]; } SCSI_PASS_THROUGH32,*PSCSI_PASS_THROUGH32; typedef struct _SCSI_PASS_THROUGH_DIRECT32 { USHORT Length; UCHAR ScsiStatus; UCHAR PathId; UCHAR TargetId; UCHAR Lun; UCHAR CdbLength; UCHAR SenseInfoLength; UCHAR DataIn; ULONG DataTransferLength; ULONG TimeOutValue; VOID *DataBuffer; ULONG SenseInfoOffset; UCHAR Cdb[16]; } SCSI_PASS_THROUGH_DIRECT32,*PSCSI_PASS_THROUGH_DIRECT32; #endif /* _WIN64 */ typedef struct _ATA_PASS_THROUGH_EX { USHORT Length; USHORT AtaFlags; UCHAR PathId; UCHAR TargetId; UCHAR Lun; UCHAR ReservedAsUchar; ULONG DataTransferLength; ULONG TimeOutValue; ULONG ReservedAsUlong; ULONG_PTR DataBufferOffset; UCHAR PreviousTaskFile[8]; UCHAR CurrentTaskFile[8]; } ATA_PASS_THROUGH_EX,*PATA_PASS_THROUGH_EX; typedef struct _ATA_PASS_THROUGH_DIRECT { USHORT Length; USHORT AtaFlags; UCHAR PathId; UCHAR TargetId; UCHAR Lun; UCHAR ReservedAsUchar; ULONG DataTransferLength; ULONG TimeOutValue; ULONG ReservedAsUlong; PVOID DataBuffer; UCHAR PreviousTaskFile[8]; UCHAR CurrentTaskFile[8]; } ATA_PASS_THROUGH_DIRECT,*PATA_PASS_THROUGH_DIRECT; #if defined(_WIN64) typedef struct _ATA_PASS_THROUGH_EX32 { USHORT Length; USHORT AtaFlags; UCHAR PathId; UCHAR TargetId; UCHAR Lun; UCHAR ReservedAsUchar; ULONG DataTransferLength; ULONG TimeOutValue; ULONG ReservedAsUlong; ULONG32 DataBufferOffset; UCHAR PreviousTaskFile[8]; UCHAR CurrentTaskFile[8]; } ATA_PASS_THROUGH_EX32,*PATA_PASS_THROUGH_EX32; typedef struct _ATA_PASS_THROUGH_DIRECT32 { USHORT Length; USHORT AtaFlags; UCHAR PathId; UCHAR TargetId; UCHAR Lun; UCHAR ReservedAsUchar; ULONG DataTransferLength; ULONG TimeOutValue; ULONG ReservedAsUlong; VOID *DataBuffer; UCHAR PreviousTaskFile[8]; UCHAR CurrentTaskFile[8]; } ATA_PASS_THROUGH_DIRECT32,*PATA_PASS_THROUGH_DIRECT32; #endif /* _WIN64 */ #define ATA_FLAGS_DRDY_REQUIRED (1 << 0) #define ATA_FLAGS_DATA_IN (1 << 1) #define ATA_FLAGS_DATA_OUT (1 << 2) #define ATA_FLAGS_48BIT_COMMAND (1 << 3) #define ATA_FLAGS_USE_DMA (1 << 4) typedef struct _SCSI_BUS_DATA { UCHAR NumberOfLogicalUnits; UCHAR InitiatorBusId; ULONG InquiryDataOffset; }SCSI_BUS_DATA,*PSCSI_BUS_DATA; typedef struct _SCSI_ADAPTER_BUS_INFO { UCHAR NumberOfBuses; SCSI_BUS_DATA BusData[1]; } SCSI_ADAPTER_BUS_INFO,*PSCSI_ADAPTER_BUS_INFO; typedef struct _SCSI_INQUIRY_DATA { UCHAR PathId; UCHAR TargetId; UCHAR Lun; BOOLEAN DeviceClaimed; ULONG InquiryDataLength; ULONG NextInquiryDataOffset; UCHAR InquiryData[1]; }SCSI_INQUIRY_DATA,*PSCSI_INQUIRY_DATA; typedef struct _SRB_IO_CONTROL { ULONG HeaderLength; UCHAR Signature[8]; ULONG Timeout; ULONG ControlCode; ULONG ReturnCode; ULONG Length; } SRB_IO_CONTROL,*PSRB_IO_CONTROL; typedef struct _IO_SCSI_CAPABILITIES { ULONG Length; ULONG MaximumTransferLength; ULONG MaximumPhysicalPages; ULONG SupportedAsynchronousEvents; ULONG AlignmentMask; BOOLEAN TaggedQueuing; BOOLEAN AdapterScansDown; BOOLEAN AdapterUsesPio; } IO_SCSI_CAPABILITIES,*PIO_SCSI_CAPABILITIES; typedef struct _SCSI_ADDRESS { ULONG Length; UCHAR PortNumber; UCHAR PathId; UCHAR TargetId; UCHAR Lun; } SCSI_ADDRESS,*PSCSI_ADDRESS; struct _ADAPTER_OBJECT; typedef struct _DUMP_POINTERS { struct _ADAPTER_OBJECT *AdapterObject; PVOID MappedRegisterBase; PVOID DumpData; PVOID CommonBufferVa; LARGE_INTEGER CommonBufferPa; ULONG CommonBufferSize; BOOLEAN AllocateCommonBuffers; BOOLEAN UseDiskDump; UCHAR Spare1[2]; PVOID DeviceObject; } DUMP_POINTERS,*PDUMP_POINTERS; #define SCSI_IOCTL_DATA_OUT 0 #define SCSI_IOCTL_DATA_IN 1 #define SCSI_IOCTL_DATA_UNSPECIFIED 2 #ifdef __cplusplus } #endif #endif /* _NTDDSCSIH_ */
1998cdea55470a5e2a87e945120e185833c5b350
5ab69c8644a936a3d9dec1669a86c7369c911bf8
/arch/cpu/simplelink-cc13xx-cc26xx/dev/spi-arch.c
f4c6114e8ab422e6f9ce5af9c4879ac4b394aefb
[ "BSD-3-Clause" ]
permissive
contiki-ng/contiki-ng
393d36f68b98f5ee3544ea32502cf662ffb2fe9f
31fcaadf7a0dc8ceea07f438cd69db73174879e6
refs/heads/develop
2023-09-01T20:10:30.000765
2023-09-01T14:37:12
2023-09-01T14:37:12
91,191,972
1,242
788
BSD-3-Clause
2023-09-14T19:08:35
2017-05-13T17:37:59
C
UTF-8
C
false
false
7,569
c
spi-arch.c
/* * Copyright (c) 2018, Texas Instruments Incorporated - http://www.ti.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. 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. */ /** * \addtogroup cc13xx-cc26xx-cpu * @{ * * \defgroup cc13xx-cc26xx-spi CC13xx/CC26xx SPI HAL * * @{ * \file * Implementation of the SPI HAL driver for CC13xx/CC26xx. * \author * Edvard Pettersen <e.pettersen@ti.com> */ /*---------------------------------------------------------------------------*/ #include "contiki.h" #include "sys/cc.h" #include "dev/spi.h" /*---------------------------------------------------------------------------*/ #include <ti/drivers/SPI.h> #include <ti/drivers/dpl/HwiP.h> #include <ti/drivers/pin/PINCC26XX.h> /*---------------------------------------------------------------------------*/ #include <stdbool.h> #include <stddef.h> #include <stdint.h> /*---------------------------------------------------------------------------*/ typedef struct { SPI_Handle handle; const spi_device_t *owner; } spi_arch_t; /*---------------------------------------------------------------------------*/ #if (SPI_CONTROLLER_COUNT > 0) static spi_arch_t spi_arches[SPI_CONTROLLER_COUNT]; #else static spi_arch_t *spi_arches = NULL; #endif /*---------------------------------------------------------------------------*/ static inline spi_arch_t * get_handle(uint8_t spi_controller) { if(spi_controller < SPI_CONTROLLER_COUNT) { return &spi_arches[spi_controller]; } else { return NULL; } } /*---------------------------------------------------------------------------*/ static SPI_FrameFormat convert_frame_format(uint8_t pol, uint8_t pha) { pol = (pol) ? 1 : 0; pha = (pha) ? 1 : 0; /* * Convert pol/pha to a single byte on the following format: * xxxA xxxB * where A is the polarity bit and B is the phase bit. * Note that any other value deviating from this format will * default to the SPI_POL1_PHA1 format. */ uint8_t pol_pha = (pol << 4) | (pha << 0); switch(pol_pha) { case 0x00: return SPI_POL0_PHA0; case 0x01: return SPI_POL0_PHA1; case 0x10: return SPI_POL1_PHA0; default: /* fallthrough */ case 0x11: return SPI_POL1_PHA1; } } /*---------------------------------------------------------------------------*/ bool spi_arch_has_lock(const spi_device_t *dev) { /* * The SPI device is the owner if the SPI controller returns a valid * SPI arch object and the SPI device is owner of that object. */ spi_arch_t *spi_arch = get_handle(dev->spi_controller); return (spi_arch != NULL) && (spi_arch->owner == dev); } /*---------------------------------------------------------------------------*/ bool spi_arch_is_bus_locked(const spi_device_t *dev) { /* * The SPI controller is locked by any device if the SPI controller returns * a valid SPI arch object and the SPI handle of that object is valid. */ spi_arch_t *spi_arch = get_handle(dev->spi_controller); return (spi_arch != NULL) && (spi_arch->handle != NULL); } /*---------------------------------------------------------------------------*/ spi_status_t spi_arch_lock_and_open(const spi_device_t *dev) { uint_least8_t spi_index; spi_arch_t *spi_arch; SPI_Params spi_params; const uintptr_t hwi_key = HwiP_disable(); spi_index = dev->spi_controller; spi_arch = get_handle(spi_index); /* Ensure the provided SPI index is valid. */ if(spi_arch == NULL) { HwiP_restore(hwi_key); return SPI_DEV_STATUS_EINVAL; } /* Ensure the corresponding SPI interface is not already locked. */ if(spi_arch_is_bus_locked(dev)) { HwiP_restore(hwi_key); return SPI_DEV_STATUS_BUS_LOCKED; } SPI_Params_init(&spi_params); spi_params.transferMode = SPI_MODE_BLOCKING; spi_params.mode = SPI_MASTER; spi_params.bitRate = dev->spi_bit_rate; spi_params.dataSize = 8; spi_params.frameFormat = convert_frame_format(dev->spi_pol, dev->spi_pha); /* * Try to open the SPI driver. Accessing the SPI driver also ensures * atomic access to the SPI interface. */ spi_arch->handle = SPI_open(spi_index, &spi_params); if(spi_arch->handle == NULL) { HwiP_restore(hwi_key); return SPI_DEV_STATUS_BUS_LOCKED; } spi_arch->owner = dev; HwiP_restore(hwi_key); return SPI_DEV_STATUS_OK; } /*---------------------------------------------------------------------------*/ spi_status_t spi_arch_close_and_unlock(const spi_device_t *dev) { spi_arch_t *spi_arch; const uintptr_t hwi_key = HwiP_disable(); /* Ensure the provided SPI index is valid. */ spi_arch = get_handle(dev->spi_controller); if(spi_arch == NULL) { HwiP_restore(hwi_key); return SPI_DEV_STATUS_EINVAL; } /* Ensure the corresponding SPI device owns the SPI controller. */ if(!spi_arch_has_lock(dev)) { HwiP_restore(hwi_key); return SPI_DEV_STATUS_BUS_NOT_OWNED; } SPI_close(spi_arch->handle); spi_arch->handle = NULL; spi_arch->owner = NULL; HwiP_restore(hwi_key); return SPI_DEV_STATUS_OK; } /*---------------------------------------------------------------------------*/ spi_status_t spi_arch_transfer(const spi_device_t *dev, const uint8_t *write_buf, int wlen, uint8_t *inbuf, int rlen, int ignore_len) { spi_arch_t *spi_arch; size_t totlen; SPI_Transaction spi_transaction; bool transfer_ok; /* Ensure the provided SPI index is valid. */ spi_arch = get_handle(dev->spi_controller); if(spi_arch == NULL) { return SPI_DEV_STATUS_EINVAL; } if(!spi_arch_has_lock(dev)) { return SPI_DEV_STATUS_BUS_NOT_OWNED; } totlen = MAX((size_t)(rlen + ignore_len), (size_t)wlen); if(totlen == 0) { /* Nothing to do */ return SPI_DEV_STATUS_OK; } spi_transaction.count = totlen; spi_transaction.txBuf = (void *)write_buf; spi_transaction.rxBuf = (void *)inbuf; transfer_ok = SPI_transfer(spi_arch->handle, &spi_transaction); if(!transfer_ok) { return SPI_DEV_STATUS_TRANSFER_ERR; } return SPI_DEV_STATUS_OK; } /*---------------------------------------------------------------------------*/ /** * @} * @} */
124c232d82559b7ada58a0eaf38ceceff7389205
ee73efbbdacd0e2b2a2646fcdf4b20e357bd7e0e
/src/chain/tx_blacklist.h
492bb1220cbed05b4f1df4cf3c99815122c0c5bb
[ "MIT" ]
permissive
particl/particl-core
fb94d509fe45aef0facaa4fe89dff0d68a3ead68
bcdcec20cdfe4e1dc4b7a463c6b155455e24fd22
refs/heads/master
2023-09-01T17:54:51.251810
2023-08-17T15:04:29
2023-08-17T15:04:29
97,465,672
150
88
MIT
2021-03-26T15:47:55
2017-07-17T10:45:54
C++
UTF-8
C
false
false
12,244
h
tx_blacklist.h
// Copyright (c) 2021 tecnovert // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #ifndef PARTICL_CHAIN_TX_BLACKLIST_H #define PARTICL_CHAIN_TX_BLACKLIST_H int64_t anon_index_blacklist[] = { 5735, // Outputs from A -> P txns to Pjc3TqX23Mb23iw8RS2YuXjNX5s8fgficZ 2221,2239,2266,2270,2280,2299,2358,2466,2601,2889,2892,3366,3529,3554, 3593,3657,3688,3692,3734,3757,3941,3942,3991,4208,5149,5181,5324,5430, 5571,5579,5679,5735,5796,5818,6004,6203,6463,6857,7315,7334,7424,7429, 7472,7602,7608,7645,7679,7685,7740,7799,7805,7806,7807,7810,7811,7812, 7816,7817,7818,7819,7820,7823,7828,7831,7832,7833,7839,7842,7845,7847, 7848,7849,7850,7851,7852,7853,7854,7855,7856,7859,7862,7863,7864,7865, 7866,7870,7871,7876,7878,7879,7883,7884,7885,7886,7887,7888,7889,7890, 7891,7894,7897,7899,7906,7908,7909,7910,7911,7912,7913,7914,7924,7934, 7935,7936,7937,7938,7944,7948,7949,7950,7951,7955,7956,7957,7958,7959, 7960,7961,7962,7965,7968,7969,7970,7971,7972,7973,7974,7975,7976,7977, 7978,7981,7984,7987,7988,7989,7992,7995,7996,8000,8004,8005,8006,8007, 8008,8009,8010,8011,8015,8019,8024,8025,8028,8031,8032,8033,8034,8035, 8036,8038,8039,8040,8041,8046,8050,8054,8057,8060,8065,8070,8073,8076, 8077,8080,8083,8085,8086,8087,8088,8091,8096,8097,8098,8099,8104,8107, 8108,8111,8112,8113,8117,8126,8127,8129,8130,8131,8132,8133,8134,8137, 8140,8147,8148,8149,8150,8151,8154,8155,8158,8161,8162,8163,8168,8169, 8170,8171,8172,8173,8174,8175,8176,8179,8180,8181,8182,8183,8184,8185, 8186,8187,8188,8191,8194,8195,8196,8200,8201,8202,8203,8204,8205,8207, 8208,8212,8213,8221,8223,8225,8226,8227,8235,8236,8242,8245,8246,8247, 8248,8249,8250,8253,8254,8257,8260,8264,8267,8270,8271,8274,8275,8276, 8278,8279,8282,8285,8286,8287,8290,8298,8299,8300,8302,8303,8304,8305, 8306,8309,8312,8317,8330,8331,8346,8347,8348,8349,8353,8354,8355,8360, 8364,8367,8370,8376,8381,8382,8383,8387,8390,8399,8401,8402,8403,8404, 8406,8407,8408,8409,8410,8411,8415,8416,8417,8418,8421,8424,8426,8427, 8433,8438,8439,8443,8448,8449,8452,8453,8456,8459,8460,8461,8462,8467, 8472,8477,8478,8482,8483,8484,8485,8486,8487,8491,8493,8494,8495,8497, 8498,8499,8500,8505,8508,8509,8518,8520,8522,8525,8526,8529,8530,8531, 8532,8533,8536,8537,8538,8540,8541,8542,8544,8545,8546,8547,8550,8553, 8554,8558,8559,8560,8561,8562,8563,8564,8565,8568,8570,8573,8574,8577, 8581,8594,8600,8601,8603,8613,8623,8625,8631,8633,8634,8637,8647,8651, 8657,8659,8665,8679,8686,8696,8703,8705,8708,8711,8715,8719,8720,8721, 8722,8725,8726,8729,8740,8741,8744,8748,8753,8754,8773,8774,8775,8776, 8777,8781,8782,8785,8790,8793,8794,8799,8802,8805,8821,8826,8829,8831, 8832,8835,8836,8839,8840,8841,8842,8843,8847,8848,8851,8854,8855,8856, 8857,8858,8859,8860,8861,8862,8863,8864,8865,8872,8875,8879,8881,8882, 8883,8884,8885,8886,8887,8888,8889,8890,8891,8893,8897,8898,8901,8903, 8904,8907,8930,8940,8943,8946,8947,8948,8951,8952,8957,8965,8968,8969, 8970,8976,8983,8987,8992,8999,9005,9009,9013,9015,9016,9019,9030,9039, 9042,9043,9045,9046,9047,9048,9049,9050,9051,9052,9053,9056,9059,9060, 9063,9066,9069,9070,9073,9076,9079,9080,9083,9084,9088,9098,9109,9110, 9113,9116,9119,9123,9124,9125,9126,9127,9128,9130,9131,9132,9133,9135, 9136,9137,9138,9139,9140,9143,9145,9146,9147,9149,9154,9155,9158,9161, 9162,9163,9164,9165,9166,9169,9172,9173,9174,9179,9181,9186,9189,9190, 9191,9192,9193,9196,9197,9198,9201,9202,9203,9204,9205,9214,9222,9223, 9224,9226,9227,9229,9230,9231,9233,9234,9235,9237,9238,9241,9242,9243, 9244,9246,9253,9254,9255,9256,9257,9258,9259,9262,9264,9267,9270,9275, 9278,9279,9280,9281,9282,9284,9285,9286,9288,9290,9291,9292,9295,9297, 9300,9302,9304,9305,9312,9314,9319,9320,9324,9327,9328,9329,9330,9332, 9333,9334,9337,9338,9339,9340,9341,9342,9350,9351,9352,9353,9354,9355, 9356,9357,9358,9359,9360,9361,9362,9363,9366,9369,9373,9380,9381,9382, 9385,9401,9410,9411,9412,9413,9414,9415,9418,9419,9422,9423,9424,9427, 9430,9431,9432,9435,9439,9442,9445,9448,9453,9458,9460,9467,9470,9474, 9479,9492,9498,9501,9502,9503,9505,9506,9508,9509,9510,9511,9512,9513, 9517,9562,9564,9574,9578,9582,9585,9588,9589,9595,9598,9599,9600,9603, 9606,9611,9615,9625,9630,9633,9634,9642,9647,9652,9655,9656,9657,9659, 9661,9666,9677,9683,9687,9690,9700,9709,9715,9720,9722,9723,9724,9725, 9728,9729,9732,9733,9734,9736,9737,9738,9739,9742,9745,9746,9747,9748, 9749,9750,9755,9758,9759,9760,9761,9762,9763,9765,9766,9775,9776,9777, 9778,9781,9782,9785,9786,9789,9790,9795,9802,9806,9810,9811,9814,9815, 9818,9827,9830,9835,9837,9838,9839,9840,9841,9842,9843,9846,9849,9850, 9851,9854,9857,9860,9862,9865,9877,9878,9879,9880,9883,9888,9895,9896, 9897,9898,9901,9902,9903,9904,9905,9906,9908,9913,9915,9916,9917,9918, 9919,9920,9923,9926,9931,9933,9935,9940,9941,9942,9943,9944,9945,9948, 9951,9952,9953,9958,9959,9960,9965,9968,9971,9972,9973,9974,9975,9976, 9977,9978,9979,9980,9981,9984,9987,9988,9989,9990,9991,9995,9996,9997, 9998,10001,10003,10004,10006,10009,10011,10012,10013,10014,10015,10018, 10021,10026,10030,10033,10039,10042,10043,10046,10049,10051,10052,10055, 10058,10063,10064,10065,10066,10067,10068,10072,10076,10077,10078,10082, 10085,10086,10087,10090,10091,10094,10095,10097,10115,10116,10117,10118, 10119,10120,10121,10122,10123,10124,10125,10130,10131,10132,10133,10134, 10135,10138,10142,10148,10151,10154,10155,10158,10161,10165,10166,10167, 10168,10171,10172,10173,10174,10175,10176,10177,10178,10181,10187,10188, 10189,10190,10191,10192,10193,10194,10195,10196,10197,10198,10199,10202, 10205,10208,10209,10210,10211,10212,10215,10216,10219,10222,10223,10230, 10234,10239,10240,10243,10246,10247,10248,10249,10250,10251,10252,10253, 10254,10255,10256,10257,10258,10259,10260,10261,10262,10263,10264,10268, 10273,10274,10279,10282,10283,10284,10287,10290,10291,10292,10293,10297, 10300,10301,10302,10303,10304,10306,10382,10398,10399,10400,10401,10402, 10407,10410,10413,10414,10416,10418,10419,10420,10423,10425,10426,10427, 10433,10439,10440,10447,10453,10454,10456,10457,10458,10467,10475,10479, 10480,10481,10484,10488,10497,10499,10500,10511,10512,10513,10518,10519, 10524,10531,10535,10539,10541,10545,10548,10551,10553,10558,10559,10560, 10567,10572,10577,10579,10584,10585,10586,10587,10588,10589,10590,10601, 10602,10603,10615,10619,10622,10623,10626,10627,10630,10631,10634,10637, 10640,10641,10642,10644,10647,10650,10651,10655,10656,10663,10665,10666, 10668,10669,10670,10671,10672,10673,10674,10675,10676,10677,10678,10681, 10686,10687,10690,10695,10696,10699,10701,10702,10705,10706,10708,10713, 10714,10717,10720,10721,10727,10728,10733,10737,10740,10743,10744,10745, 10752,10757,10764,10767,10768,10769,10770,10771,10772,10775,10778,10779, 10780,10781,10782,10783,10784,10785,10788,10790,10792,10793,10794,10799, 10802,10805,10806,10807,10808,10809,10810,10811,10812,10813,10814,10815, 10816,10819,10820,10821,10822,10823,10836,10837,10840,10843,10846,10847, 10852,10856,10857,10860,10863,10864,10867,10869,10870,10871,10872,10873, 10875,10876,10877,10878,10879,10880,10881,10882,10883,10886,10889,10892, 10895,10898,10901,10902,10903,10906,10907,10908,10916,10919,10924,10925, 10926,10927,10930,10935,10943,10944,10947,10950,10953,10957,10958,10961, 10964,10965,10967,10968,10969,10970,10973,10976,10977,10978,10979,10980, 10981,10982,10983,10984,10986,10987,10988,10989,10990,10991,10993,10994, 10995,10998,11001,11004,11005,11006,11007,11008,11015,11021,11023,11036, 11039,11043,11071,11091,11103,11112,11119,11122,11124,11131,11137,11140, 11141,11144,11149,11153,11154,11155,11156,11157,11158,11159,11160,11164, 11167,11168,11169,11170,11171,11172,11173,11183,11187,11188,11189,11190, 11195,11198,11201,11202,11205,11210,11211,11214,11216,11218,11219,11220, 11221,11225,11228,11230,11234,11236,11238,11244,11246,11249,11252,11253, 11254,11257,11261,11265,11268,11269,11273,11279,11280,11281,11286,11291, 11292,11295,11297,11300,11306,11310,11313,11320,11326,11328,11330,11335, 11336,11340,11347,11356,11360,11361,11362,11363,11365,11366,11369,11370, 11371,11374,11376,11377,11380,11383,11384,11385,11386,11387,11388,11389, 11390,11391,11394,11400,11403,11408,11411,11414,11415,11418,11421,11422, 11423,11424,11427,11430,11431,11432,11437,11438,11439,11440,11441,11442, 11443,11448,11453,11457,11460,11461,11464,11470,11471,11473,11479,11481, 11483,11484,11485,11486,11487,11490,11497,11501,11504,11507,11510,11513, 11514,11515,11518,11521,11522,11524,11527,11530,11531,11536,11549,11554, 11557,11558,11559,11560,11561,11562,11563,11566,11569,11570,11571,11580, 11583,11584,11587,11588,11591,11592,11595,11597,11608,11609,11610,11613, 11620,11621,11625,11628,11633,11640,11642,11643,11648,11649,11652,11656, 11660,11665,11666,11667,11668,11669,11670,11671,11672,11673,11676,11678, 11680,11681,11686,11691,11695,11696,11697,11698,11699,11700,11703,11705, 11706,11709,11712,11714,11717,11721,11724,11725,11726,11727,11730,11733, 11734,11735,11736,11737,11738,11739,11740,11741,11742,11743,11746,11748, 11749,11750,11751,11752,11755,11757,11760,11761,11764,11767,11770,11775, 11776,11777,11780,11782,11783,11784,11785,11786,11787,11789,11791,11794, 11799,11803,11805,11806,11808,11809,11810,11811,11812,11813,11814,11815, 11816,11817,11818,11819,11820,11821,11822,11825,11831,11832,11833,11834, 11837,11838,11840,11841,11842,11843,11846,11851,11855,11858,11863,11866, 11876,11877,11878,11879,11880,11881,11885,11888,11890,11894,11901,11903, 11908,11909,11910,11911,11912,11913,11914,11915,11916,11917,11918,11919, 11920,11922,11923,11926,11930,11937,11940,11941,11942,11945,11948,11960, 11962,11966,11969,11970,11973,11979,11982,11983,11987,11988,11989,11992, 11994,11995,11996,11997,11998,12004,12005,12011,12014,12017,12018,12019, 12020,12021,12022,12023,12027,12028,12029,12030,12031,12032,12033,12034, 12035,12036,12037,12038,12043,12047,12050,12053,12054,12055,12062,12069, 12074,12077,12078,12079,12082,12084,12085,12090,12091,12094,12096,12100, 12103,12106,12107,12110,12113,12114,12116,12117,12118,12121,12122,12125, 12126,12130,12131,12132,12133,12134,12135,12142,12145,12150,12152,12156, 12165,12168,12171,12177,12178,12180,12187,12191,12196,12202,12203,12207, 12210,12211,12212,12215,12218,12219,12220,12221,12226,12227,12228,12229, 12232,12235,12236,12239,12241,12247,12253,12255,12256,12257,12258,12259, 12260,12261,12262,12275,12276,12277,12279,12280,12288,12291,12296,12300, 12305,12307,12308,12309,12310,12314,12316,12317,12318,12319,12321,12322, 12326,12335,12337,12338,12339,12344,15668,16006,16016,16430,16472,16600, 16677,16925,16928,16987,17014,17035,17057,17108,17123,17141,17171,17213, 17235,17284,17303,17319,17331,17353,17369,17383,17398,17409,17427,17437, 17450,17495,17560,17576,17586,17607,17620,17635,17652,17664,17678,17695, 17711,17718,17731,17748,17763,17771,17787,17804,17815,17823,17840,17851, 17871,17887,17904,17923,17931,17949,17956,17978,17996,18008,18011,18021, 18030,18038,18048,18060,18070,18082,18094,18103,18117,18123,18132,18140, 18148,18163,18166,18172,18191,18206,18243,18259,18284,18301,18316,18336, 18355,18393,18407,18421,18445,18469,18525,18534,18558,18579,18597,18606, 18619,18632,18651,18661,18675,18689,18699,18706,18715,18729,18742,18761, 18780,18831,18858,18864,18878,18880,18894,18916,18937,18954,18967,18984, 18996,19006,19022,19029,19039,19052,19057,19063,19068,19084,19094,19105, 19115,19134,19154,19171,19184,19198,19228,19233,19246,19261,19282,19301, 19310,19320,19336,19347,19356,19366,19377,19396,19407,19413,19426,19437, 19458,19472,19483,19506,19524,19547,19550,19561,19575,19577,19589,19605, 19617,19625,19663,19680,19684,19705,19720,19735,19750,19766,19776,19793, 19811,19823,19835,19853,19860,19867,19889,19907,19934,19983,19996,20004, 20009,20016,20028,20045,20059,20080,20094,20099,20112,20127,20149,20167, 20194,20213,20228,20244,20257,20265,20283,20301,20317,20324,20335,20343, 20359,20369,20379,20385,20403,20413,20423,20434,20448,20465,20526,20586, 20605,20617,20629,20633,20643,20662,20673,20749,20761,20786,20805,20823, 20830,20842,20858,20862,20869,20872,20880,20889,20903,20915,20932,21070, 21100,21125,21262,21287,21305,21321,21332,21370,21470,21480 }; size_t anon_index_blacklist_size = sizeof(anon_index_blacklist) / sizeof(int64_t); #endif // PARTICL_CHAIN_TX_BLACKLIST_H
d69600e20c8bfa15c1e7e4e7e7ee6b3be5bef483
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/nuvoton/libraries/m2354/rtt_port/drv_epwm_capture.c
053bb260c78f52b5f6099af46102161e3aaf15a4
[ "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
16,421
c
drv_epwm_capture.c
/**************************************************************************//** * * @copyright (C) 2020 Nuvoton Technology Corp. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2020-8-20 Philo First version * ******************************************************************************/ #include <rtconfig.h> #if defined(BSP_USING_EPWM_CAPTURE) #if ((BSP_USING_EPWM0_CAPTURE_CHMSK+BSP_USING_EPWM1_CAPTURE_CHMSK)!=0) #include <rtdevice.h> #include "NuMicro.h" #define EPWM_CH0CH1_POS (0) #define EPWM_CH2CH3_POS (2) #define EPWM_CH4CH5_POS (4) /* Private typedef --------------------------------------------------------------*/ typedef struct nu_capture { struct rt_inputcapture_device parent; EPWM_T *epwm; uint8_t u8Channel; IRQn_Type irq; uint32_t u32CurrentRisingCnt; uint32_t u32CurrentFallingCnt; rt_bool_t input_data_level; } nu_capture_t; /* Private functions ------------------------------------------------------------*/ static rt_err_t nu_capture_init(struct rt_inputcapture_device *inputcapture); static rt_err_t nu_capture_open(struct rt_inputcapture_device *inputcapture); static rt_err_t nu_capture_close(struct rt_inputcapture_device *inputcapture); static rt_err_t nu_capture_get_pulsewidth(struct rt_inputcapture_device *inputcapture, rt_uint32_t *pulsewidth_us); /* Public functions -------------------------------------------------------------*/ /* Private variables ------------------------------------------------------------*/ #if (BSP_USING_EPWM0_CAPTURE_CHMSK!=0) static const char *nu_epwm0_device_name[EPWM_CHANNEL_NUM] = { "epwm0i0", "epwm0i1", "epwm0i2", "epwm0i3", "epwm0i4", "epwm0i5"}; static const IRQn_Type nu_epwm0_irq[EPWM_CHANNEL_NUM / 2] = { EPWM0_P0_IRQn, EPWM0_P1_IRQn, EPWM0_P2_IRQn}; static nu_capture_t nu_epwm0_capture[EPWM_CHANNEL_NUM] = {0}; #endif #if (BSP_USING_EPWM1_CAPTURE_CHMSK!=0) static const char *nu_epwm1_device_name[EPWM_CHANNEL_NUM] = {"epwm1i0", "epwm1i1", "epwm1i2", "epwm1i3", "epwm1i4", "epwm1i5", }; static const IRQn_Type nu_epwm1_irq[EPWM_CHANNEL_NUM / 2] = {EPWM1_P0_IRQn, EPWM1_P1_IRQn, EPWM1_P2_IRQn }; static nu_capture_t nu_epwm1_capture[EPWM_CHANNEL_NUM] = {0}; #endif static struct rt_inputcapture_ops nu_capture_ops = { .init = nu_capture_init, .open = nu_capture_open, .close = nu_capture_close, .get_pulsewidth = nu_capture_get_pulsewidth, }; /* Functions define ------------------------------------------------------------*/ static rt_err_t CalPulseWidth(nu_capture_t *nu_capture) { rt_bool_t bWrapAroundFlag = RT_FALSE; /* Check rising/falling capture counter is overflow or not */ if (EPWM_GetWrapAroundFlag(nu_capture->epwm, nu_capture->u8Channel)) { EPWM_ClearWrapAroundFlag(nu_capture->epwm, nu_capture->u8Channel); bWrapAroundFlag = RT_TRUE; } /* Read the capture counter value if falling/rising edge */ if (EPWM_GetCaptureIntFlag(nu_capture->epwm, nu_capture->u8Channel) == 1)//Rising edge { EPWM_ClearCaptureIntFlag(nu_capture->epwm, nu_capture->u8Channel, EPWM_CAPTURE_INT_RISING_LATCH); if (bWrapAroundFlag) { nu_capture->u32CurrentRisingCnt = 0x10000; } nu_capture->u32CurrentRisingCnt += EPWM_GET_CAPTURE_RISING_DATA(nu_capture->epwm, nu_capture->u8Channel); } else if (EPWM_GetCaptureIntFlag(nu_capture->epwm, nu_capture->u8Channel) == 2)//Falling edge { EPWM_ClearCaptureIntFlag(nu_capture->epwm, nu_capture->u8Channel, EPWM_CAPTURE_INT_FALLING_LATCH); if (bWrapAroundFlag) { nu_capture->u32CurrentFallingCnt = 0x10000; } nu_capture->u32CurrentFallingCnt += EPWM_GET_CAPTURE_FALLING_DATA(nu_capture->epwm, nu_capture->u8Channel); } else { EPWM_ClearCaptureIntFlag(nu_capture->epwm, nu_capture->u8Channel, EPWM_CAPTURE_INT_RISING_LATCH); EPWM_ClearCaptureIntFlag(nu_capture->epwm, nu_capture->u8Channel, EPWM_CAPTURE_INT_FALLING_LATCH); return -(RT_ERROR); } return RT_EOK; } #if (BSP_USING_EPWM0_CAPTURE_CHMSK&(0x3<<EPWM_CH0CH1_POS)) void EPWM0_P0_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); /* Avoid excessive iteration by monitoring enabled channels */ #if (BSP_USING_EPWM0_CAPTURE_CHMSK&(0x1<<EPWM_CH0CH1_POS)) uint8_t const start = 0 + EPWM_CH0CH1_POS; #else /* Only channel 1 */ uint8_t const start = 1 + EPWM_CH0CH1_POS; #endif #if (BSP_USING_EPWM0_CAPTURE_CHMSK&(0x2<<EPWM_CH0CH1_POS)) uint8_t const end = 2 + EPWM_CH0CH1_POS; #else /* Only channel 0 */ uint8_t const end = 1 + EPWM_CH0CH1_POS; #endif /* 2 channel using same irq */ for (uint8_t i = start; i < end ; i++) { if (EPWM_GetCaptureIntFlag(nu_epwm0_capture[i].epwm, nu_epwm0_capture[i].u8Channel) != 0) { /* Calculate pulse width */ if (CalPulseWidth(&nu_epwm0_capture[i]) == RT_EOK) { rt_hw_inputcapture_isr(&nu_epwm0_capture[i].parent, nu_epwm0_capture[i].input_data_level); } } } /* leave interrupt */ rt_interrupt_leave(); } #endif #if (BSP_USING_EPWM0_CAPTURE_CHMSK&(0x3<<EPWM_CH2CH3_POS)) void EPWM0_P1_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); /* Avoid excessive iteration by monitoring enabled channels */ #if (BSP_USING_EPWM0_CAPTURE_CHMSK&(0x1<<EPWM_CH2CH3_POS)) uint8_t const start = 0 + EPWM_CH2CH3_POS; #else /* Only channel 3 */ uint8_t const start = 1 + EPWM_CH2CH3_POS; #endif #if (BSP_USING_EPWM0_CAPTURE_CHMSK&(0x2<<EPWM_CH2CH3_POS)) uint8_t const end = 2 + EPWM_CH2CH3_POS; #else /* Only channel 2 */ uint8_t const end = 1 + EPWM_CH2CH3_POS; #endif /* 2 channel using same irq */ for (uint8_t i = start; i < end ; i++) { if (EPWM_GetCaptureIntFlag(nu_epwm0_capture[i].epwm, nu_epwm0_capture[i].u8Channel) != 0) { /* Calculate pulse width */ if (CalPulseWidth(&nu_epwm0_capture[i]) == RT_EOK) { rt_hw_inputcapture_isr(&nu_epwm0_capture[i].parent, nu_epwm0_capture[i].input_data_level); } } } /* leave interrupt */ rt_interrupt_leave(); } #endif #if (BSP_USING_EPWM0_CAPTURE_CHMSK&(0x3<<EPWM_CH4CH5_POS)) void EPWM0_P2_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); /* Avoid excessive iteration by monitoring enabled channels */ #if (BSP_USING_EPWM0_CAPTURE_CHMSK&(0x1<<EPWM_CH4CH5_POS)) uint8_t const start = 0 + EPWM_CH4CH5_POS; #else /* Only channel 5 */ uint8_t const start = 1 + EPWM_CH4CH5_POS; #endif #if (BSP_USING_EPWM0_CAPTURE_CHMSK&(0x2<<EPWM_CH4CH5_POS)) uint8_t const end = 2 + EPWM_CH4CH5_POS; #else /* Only channel 4 */ uint8_t const end = 1 + EPWM_CH4CH5_POS; #endif /* 2 channel using same irq */ for (uint8_t i = start; i < end ; i++) { if (EPWM_GetCaptureIntFlag(nu_epwm0_capture[i].epwm, nu_epwm0_capture[i].u8Channel) != 0) { /* Calculate pulse width */ if (CalPulseWidth(&nu_epwm0_capture[i]) == RT_EOK) { rt_hw_inputcapture_isr(&nu_epwm0_capture[i].parent, nu_epwm0_capture[i].input_data_level); } } } /* leave interrupt */ rt_interrupt_leave(); } #endif #if (BSP_USING_EPWM1_CAPTURE_CHMSK&(0x3<<EPWM_CH0CH1_POS)) void EPWM1_P0_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); /* Avoid excessive iteration by monitoring enabled channels */ #if (BSP_USING_EPWM1_CAPTURE_CHMSK&(0x1<<EPWM_CH0CH1_POS)) uint8_t const start = 0 + EPWM_CH0CH1_POS; #else /* Only channel 1 */ uint8_t const start = 1 + EPWM_CH0CH1_POS; #endif #if (BSP_USING_EPWM1_CAPTURE_CHMSK&(0x2<<EPWM_CH0CH1_POS)) uint8_t const end = 2 + EPWM_CH0CH1_POS; #else /* Only channel 0 */ uint8_t const end = 1 + EPWM_CH0CH1_POS; #endif /* 2 channel using same irq */ for (uint8_t i = start; i < end ; i++) { if (EPWM_GetCaptureIntFlag(nu_epwm1_capture[i].epwm, nu_epwm1_capture[i].u8Channel) != 0) { /* Calculate pulse width */ if (CalPulseWidth(&nu_epwm1_capture[i]) == RT_EOK) { rt_hw_inputcapture_isr(&nu_epwm1_capture[i].parent, nu_epwm1_capture[i].input_data_level); } } } /* leave interrupt */ rt_interrupt_leave(); } #endif #if (BSP_USING_EPWM1_CAPTURE_CHMSK&(0x3<<EPWM_CH2CH3_POS)) void EPWM1_P1_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); /* Avoid excessive iteration by monitoring enabled channels */ #if (BSP_USING_EPWM1_CAPTURE_CHMSK&(0x1<<EPWM_CH2CH3_POS)) uint8_t const start = 0 + EPWM_CH2CH3_POS; #else /* Only channel 3 */ uint8_t const start = 1 + EPWM_CH2CH3_POS; #endif #if (BSP_USING_EPWM1_CAPTURE_CHMSK&(0x2<<EPWM_CH2CH3_POS)) uint8_t const end = 2 + EPWM_CH2CH3_POS; #else /* Only channel 2 */ uint8_t const end = 1 + EPWM_CH2CH3_POS; #endif /* 2 channel using same irq */ for (uint8_t i = start; i < end ; i++) { if (EPWM_GetCaptureIntFlag(nu_epwm1_capture[i].epwm, nu_epwm1_capture[i].u8Channel) != 0) { /* Calculate pulse width */ if (CalPulseWidth(&nu_epwm1_capture[i]) == RT_EOK) { rt_hw_inputcapture_isr(&nu_epwm1_capture[i].parent, nu_epwm1_capture[i].input_data_level); } } } /* leave interrupt */ rt_interrupt_leave(); } #endif #if (BSP_USING_EPWM1_CAPTURE_CHMSK&(0x3<<EPWM_CH4CH5_POS)) void EPWM1_P2_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); /* Avoid excessive iteration by monitoring enabled channels */ #if (BSP_USING_EPWM1_CAPTURE_CHMSK&(0x1<<EPWM_CH4CH5_POS)) uint8_t const start = 0 + EPWM_CH4CH5_POS; #else /* Only channel 5 */ uint8_t const start = 1 + EPWM_CH4CH5_POS; #endif #if (BSP_USING_EPWM1_CAPTURE_CHMSK&(0x2<<EPWM_CH4CH5_POS)) uint8_t const end = 2 + EPWM_CH4CH5_POS; #else /* Only channel 4 */ uint8_t const end = 1 + EPWM_CH4CH5_POS; #endif /* 2 channel using same irq */ for (uint8_t i = start; i < end ; i++) { if (EPWM_GetCaptureIntFlag(nu_epwm1_capture[i].epwm, nu_epwm1_capture[i].u8Channel) != 0) { /* Calculate pulse width */ if (CalPulseWidth(&nu_epwm1_capture[i]) == RT_EOK) { rt_hw_inputcapture_isr(&nu_epwm1_capture[i].parent, nu_epwm1_capture[i].input_data_level); } } } /* leave interrupt */ rt_interrupt_leave(); } #endif static rt_err_t nu_capture_get_pulsewidth(struct rt_inputcapture_device *inputcapture, rt_uint32_t *pulsewidth_us) { rt_err_t ret = RT_EOK; nu_capture_t *nu_capture; nu_capture = (nu_capture_t *)inputcapture; if (nu_capture->u32CurrentFallingCnt) { *pulsewidth_us = nu_capture->u32CurrentFallingCnt; nu_capture->input_data_level = RT_FALSE; nu_capture->u32CurrentFallingCnt = 0; } else if (nu_capture->u32CurrentRisingCnt) { *pulsewidth_us = nu_capture->u32CurrentRisingCnt; nu_capture->input_data_level = RT_TRUE; nu_capture->u32CurrentRisingCnt = 0; } else { ret = -RT_ERROR; } return -(ret); } static rt_err_t nu_epwm_init(nu_capture_t *nu_capture) { rt_err_t ret = -RT_ERROR; static rt_bool_t bEPWM0Inited = RT_FALSE; static rt_bool_t bEPWM1Inited = RT_FALSE; if (nu_capture->epwm == EPWM0) { if (bEPWM0Inited == RT_FALSE) { /* Enable EPWM0 clock */ SYS_UnlockReg(); CLK_EnableModuleClock(EPWM0_MODULE); CLK_SetModuleClock(EPWM0_MODULE, CLK_CLKSEL2_EPWM0SEL_PCLK0, 0); SYS_LockReg(); bEPWM0Inited = RT_TRUE; } ret = RT_EOK; } else if (nu_capture->epwm == EPWM1) { if (bEPWM1Inited == RT_FALSE) { /* Enable EPWM1 clock */ SYS_UnlockReg(); CLK_EnableModuleClock(EPWM1_MODULE); CLK_SetModuleClock(EPWM1_MODULE, CLK_CLKSEL2_EPWM1SEL_PCLK1, 0); SYS_LockReg(); bEPWM1Inited = RT_TRUE; } ret = RT_EOK; } return -(ret); } static rt_err_t nu_capture_init(struct rt_inputcapture_device *inputcapture) { rt_err_t ret = RT_EOK; nu_capture_t *nu_capture; RT_ASSERT(inputcapture != RT_NULL); nu_capture = (nu_capture_t *) inputcapture; if (nu_epwm_init(nu_capture) != RT_EOK) { rt_kprintf("Failed to initialize EPWM%d.\n", nu_capture->epwm); ret = -RT_ERROR; } return -(ret); } static rt_err_t nu_capture_open(struct rt_inputcapture_device *inputcapture) { rt_err_t ret = RT_EOK; nu_capture_t *nu_capture; RT_ASSERT(inputcapture != RT_NULL); nu_capture = (nu_capture_t *) inputcapture; /* Set capture time as 1000 nanosecond */ EPWM_ConfigCaptureChannel(nu_capture->epwm, nu_capture->u8Channel, 1000, 0); /* Enable capture rising/falling edge interrupt */ EPWM_EnableCaptureInt(nu_capture->epwm, nu_capture->u8Channel, EPWM_CAPTURE_INT_FALLING_LATCH | EPWM_CAPTURE_INT_RISING_LATCH); /* Enable EPWM NVIC interrupt */ NVIC_EnableIRQ(nu_capture->irq); /* Enable Capture Function for EPWM */ EPWM_EnableCapture(nu_capture->epwm, 0x1 << nu_capture->u8Channel); /* Enable rising/falling capture reload */ nu_capture->epwm->CAPCTL |= (0x1 << (EPWM_CAPCTL_RCRLDEN0_Pos + nu_capture->u8Channel)) | (0x1 << (EPWM_CAPCTL_FCRLDEN0_Pos + nu_capture->u8Channel)); /* Set counter type as down count */ EPWM_SET_ALIGNED_TYPE(nu_capture->epwm, 0x1 << nu_capture->u8Channel, EPWM_UP_COUNTER); /* Enable EPWM Timer */ EPWM_Start(nu_capture->epwm, 0x1 << nu_capture->u8Channel); return ret; } static rt_err_t nu_capture_close(struct rt_inputcapture_device *inputcapture) { rt_err_t ret = RT_EOK; nu_capture_t *nu_capture; RT_ASSERT(inputcapture != RT_NULL); nu_capture = (nu_capture_t *) inputcapture; /* Disable capture rising/falling edge interrupt */ EPWM_DisableCaptureInt(nu_capture->epwm, nu_capture->u8Channel, EPWM_CAPTURE_INT_FALLING_LATCH | EPWM_CAPTURE_INT_RISING_LATCH); /* Disable EPWM NVIC interrupt */ NVIC_DisableIRQ(nu_capture->irq); /* Enable EPWM Timer */ EPWM_Stop(nu_capture->epwm, 0x1 << nu_capture->u8Channel); return ret; } /* Init and register epwm capture */ int nu_epwm_capture_device_init(void) { /* Init EPWM0 6 channel and EPWM1 6 channel */ #if (BSP_USING_EPWM0_CAPTURE_CHMSK!=0) for (int i = 0; i < EPWM_CHANNEL_NUM; i++) { if (BSP_USING_EPWM0_CAPTURE_CHMSK & (0x1 << i)) { nu_epwm0_capture[i].epwm = EPWM0; nu_epwm0_capture[i].u8Channel = i; nu_epwm0_capture[i].irq = nu_epwm0_irq[i / 2]; nu_epwm0_capture[i].u32CurrentRisingCnt = 0; nu_epwm0_capture[i].u32CurrentFallingCnt = 0; nu_epwm0_capture[i].parent.ops = &nu_capture_ops; /* register inputcapture device */ rt_device_inputcapture_register(&nu_epwm0_capture[i].parent, nu_epwm0_device_name[i], &nu_epwm0_capture[i]); } } #endif //#if (BSP_USING_EPWM0_CAPTURE_CHMSK!=0) #if (BSP_USING_EPWM1_CAPTURE_CHMSK!=0) for (int i = 0; i < EPWM_CHANNEL_NUM; i++) { if (BSP_USING_EPWM1_CAPTURE_CHMSK & (0x1 << i)) { nu_epwm1_capture[i].epwm = EPWM1; nu_epwm1_capture[i].u8Channel = i; nu_epwm1_capture[i].irq = nu_epwm1_irq[i / 2]; nu_epwm1_capture[i].u32CurrentRisingCnt = 0; nu_epwm1_capture[i].u32CurrentFallingCnt = 0; nu_epwm1_capture[i].parent.ops = &nu_capture_ops; /* register inputcapture device */ rt_device_inputcapture_register(&nu_epwm1_capture[i].parent, nu_epwm1_device_name[i], &nu_epwm1_capture[i]); } } #endif //#if (BSP_USING_EPWM1_CAPTURE_CHMSK!=0) return 0; } INIT_DEVICE_EXPORT(nu_epwm_capture_device_init); #endif //#if ((BSP_USING_EPWM0_CAPTURE_CHMSK+BSP_USING_EPWM1_CAPTURE_CHMSK)!=0) #endif //#if defined(BSP_USING_EPWM_CAPTURE)
00b4db11d9fd2169978c5cb5772f5b4d846aeb40
1885ce333f6980ab6aad764b3f8caf42094d9f7d
/test/e2e/test_input/ObjectArxHeaders/AdHostableUi.h
2801548cd8a5975e1eec67d82a3a4d0b6a5aa535
[ "MIT" ]
permissive
satya-das/cppparser
1dbccdeed4287c36c61edc30190c82de447e415b
f9a4cfac1a3af7286332056d7c661d86b6c35eb3
refs/heads/master
2023-07-06T00:55:23.382303
2022-10-03T19:40:05
2022-10-03T19:40:05
16,642,636
194
26
MIT
2023-06-26T13:44:32
2014-02-08T12:20:01
C++
UTF-8
C
false
false
654
h
AdHostableUi.h
////////////////////////////////////////////////////////////////////////////// // // Copyright 2018 by Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// #pragma once #ifndef ADHOSTABLEUI_H #define ADHOSTABLEUI_H #include "adesk.h" #ifdef ADHOSTABLE_API #define ADHOSTABLE_PORT __declspec(dllexport) #else #define ADHOSTABLE_PORT #endif #endif
0c368a1a2f9358f9a7f024c82140c0f99e37e5f4
8b98cd47f934d2a4a8d0b2842d3277b01f3fb7fa
/applications/obsolete/starbench/slatest/pm.c
c955b1afa163a4068b94d75ffa971ca7f6a92611
[]
no_license
Starlink/starlink
1cc03b85eb78330a3622003b26b69c1733df50fe
2c374b3e97c9cebcc8f3bd2f8b4bb326eefe061a
refs/heads/master
2023-07-26T09:32:27.987319
2023-07-05T23:56:27
2023-07-05T23:56:27
5,169,323
139
45
null
2022-11-18T13:29:32
2012-07-24T18:15:25
Fortran
UTF-8
C
false
false
680
c
pm.c
/* ** Copyright (C) 2005 P.T.Wallace. ** Use for profit prohibited - enquiries to ptw@tpsoft.demon.co.uk. */ #include "sbmlib.h" #include "sbmmac.h" void sbmpm(double qfoo,double qbar,double qbaz,double Q0, double qfobar,double q1,double q2,double qfoobar,double*Q3, double*q4){static double qfOBAz=(365.25*86400.0/149597870.0) *DAS2R;int qfoobaz;double QQUUX,Q5[3],QFRED,p[3];sbmdcs2c( qfoo,qbar,p);QQUUX=qfOBAz*q1*qfobar;Q5[0]=-qbaz*p[1]-Q0*cos( qfoo)*sin(qbar)+QQUUX*p[0];Q5[1]=qbaz*p[0]-Q0*sin(qfoo)*sin( qbar)+QQUUX*p[1];Q5[2]=Q0*cos(qbar)+QQUUX*p[2];QFRED=qfoobar -q2;for(qfoobaz=0;qfoobaz<3;qfoobaz++){p[qfoobaz]+=QFRED*Q5[ qfoobaz];}sbmdcc2s(p,Q3,q4);*Q3=sbmdranrm(*Q3);}
d982bff1050e1d9060cd8879e9ff652ff0483c74
c500fb774ff2ace0bcebc19368ad956fe461a2a7
/code/apps/query-performance.c
b6f630711eb3161329e6affcdaed9cce01c0d2f8
[ "BSD-3-Clause" ]
permissive
zpl-c/librg
33481fd88f9e4d72b5a3312a712fa74da231ef8f
17f18c93c6b614bbdbb423213b8b3d5f2b9d8593
refs/heads/master
2023-09-02T02:05:54.046572
2023-08-19T12:29:22
2023-08-19T12:29:22
96,756,516
548
26
BSD-3-Clause
2020-10-06T10:52:57
2017-07-10T08:52:14
C
UTF-8
C
false
false
1,951
c
query-performance.c
#define LIBRG_IMPL // #define LIBRG_ENTITY_MAXCHUNKS 1 #include "librg.h" #define MAX_ENTITY 1000 #define QUERY_ATTEMPTS 1000 int main() { librg_world *world = librg_world_create(); /* create our world configuration */ librg_config_chunksize_set(world, 16, 16, 0); librg_config_chunkamount_set(world, 64, 64, 0); librg_config_chunkoffset_set(world, LIBRG_OFFSET_BEG, LIBRG_OFFSET_BEG, LIBRG_OFFSET_BEG); zpl_f64 tstart = zpl_time_rel_ms(); /* create set of testing entities */ for (int i = 0; i < MAX_ENTITY; ++i) { int chx = rand() % 64; int chy = rand() % 64; librg_entity_track(world, i); librg_chunk chid = librg_chunk_from_chunkpos(world, chx, chy, 0); librg_entity_chunk_set(world, i, chid); } zpl_printf("[test] tracked %d entities in (%.3f ms)\n", librg_world_entities_tracked(world), zpl_time_rel_ms() - tstart); /* set owner to a single entity */ int ownerid = 1; librg_entity_owner_set(world, 0, ownerid); /* fetch entities via query */ int64_t entities[1000] = {0}; size_t entity_amount = 1000; int query_radius = 16; tstart = zpl_time_rel(); for (int i = 0; i < QUERY_ATTEMPTS; ++i) { size_t entity_limit = 1000; librg_world_query(world, ownerid, query_radius, entities, &entity_limit); entity_amount = entity_limit; } zpl_printf("[test] found %d entities in (%.3f ms)\n", entity_amount, zpl_time_rel_ms() - tstart); /* results */ // // before switch to internal memory // [test] found 171 entities in (7800.685 ms) // [test] found 171 entities in (7789.673 ms) // [test] found 171 entities in (7804.661 ms) // // after switch to internal memory // [test] found 171 entities in (4308.592 ms) // [test] found 171 entities in (4234.625 ms) // [test] found 171 entities in (4221.636 ms) librg_world_destroy(world); return 0; }
423dbb097f9850b94519d75a124dc0849ed43af3
331640994b1b6f66c1639278571ddbdc6c8c0751
/src/nxt_port_rpc.h
c07683fb08b053d0120553bd825170458e15d4bc
[ "Apache-2.0" ]
permissive
nginx/unit
eabcd067eaa60f4bdcf0cfaffe7d9932add2c66a
9b22b6957bc87b3df002d0bc691fdae6a20abdac
refs/heads/master
2023-09-04T02:02:13.581700
2023-08-30T16:07:24
2023-08-30T16:07:24
102,627,638
4,649
452
Apache-2.0
2023-09-12T01:28:22
2017-09-06T15:45:30
C
UTF-8
C
false
false
1,120
h
nxt_port_rpc.h
/* * Copyright (C) Max Romanov * Copyright (C) NGINX, Inc. */ #ifndef _NXT_PORT_RPC_H_INCLUDED_ #define _NXT_PORT_RPC_H_INCLUDED_ typedef void (*nxt_port_rpc_handler_t)(nxt_task_t *task, nxt_port_recv_msg_t *msg, void *data); nxt_int_t nxt_port_rpc_init(void); uint32_t nxt_port_rpc_register_handler(nxt_task_t *task, nxt_port_t *port, nxt_port_rpc_handler_t ready_handler, nxt_port_rpc_handler_t error_handler, nxt_pid_t peer, void *data); void *nxt_port_rpc_register_handler_ex(nxt_task_t *task, nxt_port_t *port, nxt_port_rpc_handler_t ready_handler, nxt_port_rpc_handler_t error_handler, size_t ex_size); uint32_t nxt_port_rpc_ex_stream(void *ex); void nxt_port_rpc_ex_set_peer(nxt_task_t *task, nxt_port_t *port, void *ex, nxt_pid_t peer); void nxt_port_rpc_handler(nxt_task_t *task, nxt_port_recv_msg_t *msg); void nxt_port_rpc_remove_peer(nxt_task_t *task, nxt_port_t *port, nxt_pid_t peer); void nxt_port_rpc_cancel(nxt_task_t *task, nxt_port_t *port, uint32_t stream); void nxt_port_rpc_close(nxt_task_t *task, nxt_port_t *port); #endif /* _NXT_PORT_RPC_H_INCLUDED_ */
cf5a37042d508be49008bf6f03a0fac5a9e75e61
e1ba6e7d2c51c2527158664ae4d8fbed2cb5572f
/test/recc.c
dbff4e39ed7c8662363c6de617e31392d0b2dae7
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
RobertElderSoftware/recc
1bc30b975bb736e7733da78653aa2b0efb2d80eb
a3e773d35f1ceda81f1e5ed2d1dfef5b10fd3848
refs/heads/master
2023-07-30T21:35:31.956235
2020-01-24T20:03:46
2020-01-24T20:03:46
28,613,742
264
22
Apache-2.0
2017-12-04T01:39:56
2014-12-30T01:57:05
C
UTF-8
C
false
false
53,349
c
recc.c
/* Copyright 2016 Robert Elder Software Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "../recc-implementation/compiler_interface_phase_3.h" void register_test_objects(struct build_state *); void register_test_objects(struct build_state * state){ /* Some required functions for tests */ register_entity(state, "test/extras/random.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/extras/random.c", "terminal", "true"); register_entity(state, "test/extras/extern_test.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/extras/extern_test.c", "terminal", "true"); register_entity(state, "test/extras/main_argv_indirect.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/extras/main_argv_indirect.c", "terminal", "true"); register_entity(state, "test/extras/main_div_zero_test.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/extras/main_div_zero_test.c", "terminal", "true"); register_entity(state, "test/extras/random.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/extras/extern_test.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/extras/main_argv_indirect.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/extras/main_div_zero_test.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/extras/random.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/extras/extern_test.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/extras/main_argv_indirect.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/extras/main_div_zero_test.l2", ENTITY_TYPE_L2_FILE); register_dependency(state, "test/extras/random.i", "test/extras/random.c"); register_dependency(state, "test/extras/extern_test.i", "test/extras/extern_test.c"); register_dependency(state, "test/extras/main_argv_indirect.i", "test/extras/main_argv_indirect.c"); register_dependency(state, "test/extras/main_div_zero_test.i", "test/extras/main_div_zero_test.c"); register_dependency(state, "test/extras/random.l2", "test/extras/random.i"); register_dependency(state, "test/extras/extern_test.l2", "test/extras/extern_test.i"); register_dependency(state, "test/extras/main_argv_indirect.l2", "test/extras/main_argv_indirect.i"); register_dependency(state, "test/extras/main_div_zero_test.l2", "test/extras/main_div_zero_test.i"); register_entity(state, "test/extras/l2/mainstub_div_zero_test.l2", ENTITY_TYPE_L2_FILE); add_entity_attribute(state, "test/extras/l2/mainstub_div_zero_test.l2", "terminal", "true"); register_entity(state, "test/extras/l2/mainstub_argv_indirect.l2", ENTITY_TYPE_L2_FILE); add_entity_attribute(state, "test/extras/l2/mainstub_argv_indirect.l2", "terminal", "true"); /* Test cases */ register_entity(state, "test/c89/basic-operations.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/basic-operations.c", "terminal", "true"); register_entity(state, "test/c89/basic-putchar-aa.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/basic-putchar-aa.c", "terminal", "true"); register_entity(state, "test/c89/div-zero.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/div-zero.c", "terminal", "true"); register_entity(state, "test/c89/preprocessor_test.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/preprocessor_test.c", "terminal", "true"); register_entity(state, "test/c89/filesystem.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/filesystem.c", "terminal", "true"); register_entity(state, "test/c89/basic-putchar-a.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/basic-putchar-a.c", "terminal", "true"); register_entity(state, "test/c89/basic-putchar-b.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/basic-putchar-b.c", "terminal", "true"); register_entity(state, "test/c89/empty-main-return-zero.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/empty-main-return-zero.c", "terminal", "true"); register_entity(state, "test/c89/for-loop.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/for-loop.c", "terminal", "true"); register_entity(state, "test/c89/ignore-local.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/ignore-local.c", "terminal", "true"); register_entity(state, "test/c89/many-types.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/many-types.c", "terminal", "true"); register_entity(state, "test/c89/nested-putchar-a.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/nested-putchar-a.c", "terminal", "true"); register_entity(state, "test/c89/nested-putchar-a-param-ignored.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/nested-putchar-a-param-ignored.c", "terminal", "true"); register_entity(state, "test/c89/nested-putchar-a-param-used.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/nested-putchar-a-param-used.c", "terminal", "true"); register_entity(state, "test/c89/print.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/print.c", "terminal", "true"); register_entity(state, "test/c89/putchar-return.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/putchar-return.c", "terminal", "true"); register_entity(state, "test/c89/string-literal.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/string-literal.c", "terminal", "true"); register_entity(state, "test/c89/use-array.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/use-array.c", "terminal", "true"); register_entity(state, "test/c89/use-local.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/use-local.c", "terminal", "true"); register_entity(state, "test/c89/use-reference.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/use-reference.c", "terminal", "true"); register_entity(state, "test/c89/va_list_call.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/va_list_call.c", "terminal", "true"); register_entity(state, "test/c89/while-loop.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/while-loop.c", "terminal", "true"); register_entity(state, "test/c89/typedef.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/typedef.c", "terminal", "true"); register_entity(state, "test/c89/exotic-declarators.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/exotic-declarators.c", "terminal", "true"); register_entity(state, "test/c89/constants.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/constants.c", "terminal", "true"); register_entity(state, "test/c89/malloc-test.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/malloc-test.c", "terminal", "true"); register_entity(state, "test/c89/main_with_parameters.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/main_with_parameters.c", "terminal", "true"); register_entity(state, "test/c89/regex_engine_unit_tests.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c89/regex_engine_unit_tests.c", "terminal", "true"); register_entity(state, "test/c89/basic-operations.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/basic-putchar-aa.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/div-zero.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/preprocessor_test.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/filesystem.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/basic-putchar-a.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/basic-putchar-b.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/empty-main-return-zero.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/for-loop.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/ignore-local.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/many-types.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/nested-putchar-a.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/nested-putchar-a-param-ignored.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/nested-putchar-a-param-used.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/print.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/putchar-return.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/string-literal.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/use-array.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/use-local.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/use-reference.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/va_list_call.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/while-loop.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/typedef.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/exotic-declarators.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/constants.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/malloc-test.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/main_with_parameters.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c89/regex_engine_unit_tests.i", ENTITY_TYPE_PREPROCESSED_FILE); register_dependency(state, "test/c89/basic-operations.i", "test/c89/basic-operations.c"); register_dependency(state, "test/c89/basic-putchar-aa.i", "test/c89/basic-putchar-aa.c"); register_dependency(state, "test/c89/div-zero.i", "test/c89/div-zero.c"); register_dependency(state, "test/c89/preprocessor_test.i", "test/c89/preprocessor_test.c"); register_dependency(state, "test/c89/filesystem.i", "test/c89/filesystem.c"); register_dependency(state, "test/c89/basic-putchar-a.i", "test/c89/basic-putchar-a.c"); register_dependency(state, "test/c89/basic-putchar-b.i", "test/c89/basic-putchar-b.c"); register_dependency(state, "test/c89/empty-main-return-zero.i", "test/c89/empty-main-return-zero.c"); register_dependency(state, "test/c89/for-loop.i", "test/c89/for-loop.c"); register_dependency(state, "test/c89/ignore-local.i", "test/c89/ignore-local.c"); register_dependency(state, "test/c89/many-types.i", "test/c89/many-types.c"); register_dependency(state, "test/c89/nested-putchar-a.i", "test/c89/nested-putchar-a.c"); register_dependency(state, "test/c89/nested-putchar-a-param-ignored.i", "test/c89/nested-putchar-a-param-ignored.c"); register_dependency(state, "test/c89/nested-putchar-a-param-used.i", "test/c89/nested-putchar-a-param-used.c"); register_dependency(state, "test/c89/print.i", "test/c89/print.c"); register_dependency(state, "test/c89/putchar-return.i", "test/c89/putchar-return.c"); register_dependency(state, "test/c89/string-literal.i", "test/c89/string-literal.c"); register_dependency(state, "test/c89/use-array.i", "test/c89/use-array.c"); register_dependency(state, "test/c89/use-local.i", "test/c89/use-local.c"); register_dependency(state, "test/c89/use-reference.i", "test/c89/use-reference.c"); register_dependency(state, "test/c89/va_list_call.i", "test/c89/va_list_call.c"); register_dependency(state, "test/c89/while-loop.i", "test/c89/while-loop.c"); register_dependency(state, "test/c89/typedef.i", "test/c89/typedef.c"); register_dependency(state, "test/c89/exotic-declarators.i", "test/c89/exotic-declarators.c"); register_dependency(state, "test/c89/constants.i", "test/c89/constants.c"); register_dependency(state, "test/c89/malloc-test.i", "test/c89/malloc-test.c"); register_dependency(state, "test/c89/main_with_parameters.i", "test/c89/main_with_parameters.c"); register_dependency(state, "test/c89/regex_engine_unit_tests.i", "test/c89/regex_engine_unit_tests.c"); register_entity(state, "test/c89/basic-operations.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/basic-putchar-aa.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/div-zero.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/preprocessor_test.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/filesystem.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/basic-putchar-a.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/basic-putchar-b.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/empty-main-return-zero.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/for-loop.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/ignore-local.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/many-types.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/nested-putchar-a.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/nested-putchar-a-param-ignored.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/nested-putchar-a-param-used.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/print.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/putchar-return.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/string-literal.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/use-array.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/use-local.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/use-reference.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/va_list_call.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/while-loop.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/typedef.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/exotic-declarators.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/constants.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/malloc-test.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/main_with_parameters.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c89/regex_engine_unit_tests.l2", ENTITY_TYPE_L2_FILE); register_dependency(state, "test/c89/basic-operations.l2", "test/c89/basic-operations.i"); register_dependency(state, "test/c89/basic-putchar-aa.l2", "test/c89/basic-putchar-aa.i"); register_dependency(state, "test/c89/div-zero.l2", "test/c89/div-zero.i"); register_dependency(state, "test/c89/preprocessor_test.l2", "test/c89/preprocessor_test.i"); register_dependency(state, "test/c89/filesystem.l2", "test/c89/filesystem.i"); register_dependency(state, "test/c89/basic-putchar-a.l2", "test/c89/basic-putchar-a.i"); register_dependency(state, "test/c89/basic-putchar-b.l2", "test/c89/basic-putchar-b.i"); register_dependency(state, "test/c89/empty-main-return-zero.l2", "test/c89/empty-main-return-zero.i"); register_dependency(state, "test/c89/for-loop.l2", "test/c89/for-loop.i"); register_dependency(state, "test/c89/ignore-local.l2", "test/c89/ignore-local.i"); register_dependency(state, "test/c89/many-types.l2", "test/c89/many-types.i"); register_dependency(state, "test/c89/nested-putchar-a.l2", "test/c89/nested-putchar-a.i"); register_dependency(state, "test/c89/nested-putchar-a-param-ignored.l2", "test/c89/nested-putchar-a-param-ignored.i"); register_dependency(state, "test/c89/nested-putchar-a-param-used.l2", "test/c89/nested-putchar-a-param-used.i"); register_dependency(state, "test/c89/print.l2", "test/c89/print.i"); register_dependency(state, "test/c89/putchar-return.l2", "test/c89/putchar-return.i"); register_dependency(state, "test/c89/string-literal.l2", "test/c89/string-literal.i"); register_dependency(state, "test/c89/use-array.l2", "test/c89/use-array.i"); register_dependency(state, "test/c89/use-local.l2", "test/c89/use-local.i"); register_dependency(state, "test/c89/use-reference.l2", "test/c89/use-reference.i"); register_dependency(state, "test/c89/va_list_call.l2", "test/c89/va_list_call.i"); register_dependency(state, "test/c89/while-loop.l2", "test/c89/while-loop.i"); register_dependency(state, "test/c89/typedef.l2", "test/c89/typedef.i"); register_dependency(state, "test/c89/exotic-declarators.l2", "test/c89/exotic-declarators.i"); register_dependency(state, "test/c89/constants.l2", "test/c89/constants.i"); register_dependency(state, "test/c89/malloc-test.l2", "test/c89/malloc-test.i"); register_dependency(state, "test/c89/main_with_parameters.l2", "test/c89/main_with_parameters.i"); register_dependency(state, "test/c89/regex_engine_unit_tests.l2", "test/c89/regex_engine_unit_tests.i"); register_entity(state, "test/c89/basic-operations.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/basic-putchar-aa.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/div-zero.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/preprocessor_test.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/filesystem.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/basic-putchar-a.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/basic-putchar-b.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/empty-main-return-zero.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/for-loop.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/ignore-local.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/many-types.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/nested-putchar-a.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/nested-putchar-a-param-ignored.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/nested-putchar-a-param-used.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/print.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/putchar-return.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/string-literal.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/use-array.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/use-local.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/use-reference.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/va_list_call.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/while-loop.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/typedef.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/exotic-declarators.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/constants.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/malloc-test.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/main_with_parameters.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c89/regex_engine_unit_tests.l1", ENTITY_TYPE_L1_FILE); register_dependency(state, "test/c89/basic-operations.l1", "test/c89/basic-operations.l2"); register_dependency(state, "test/c89/basic-putchar-aa.l1", "test/c89/basic-putchar-aa.l2"); register_dependency(state, "test/c89/div-zero.l1", "test/c89/div-zero.l2"); register_dependency(state, "test/c89/preprocessor_test.l1", "test/c89/preprocessor_test.l2"); register_dependency(state, "test/c89/filesystem.l1", "test/c89/filesystem.l2"); register_dependency(state, "test/c89/basic-putchar-a.l1", "test/c89/basic-putchar-a.l2"); register_dependency(state, "test/c89/basic-putchar-b.l1", "test/c89/basic-putchar-b.l2"); register_dependency(state, "test/c89/empty-main-return-zero.l1", "test/c89/empty-main-return-zero.l2"); register_dependency(state, "test/c89/for-loop.l1", "test/c89/for-loop.l2"); register_dependency(state, "test/c89/ignore-local.l1", "test/c89/ignore-local.l2"); register_dependency(state, "test/c89/many-types.l1", "test/c89/many-types.l2"); register_dependency(state, "test/c89/nested-putchar-a.l1", "test/c89/nested-putchar-a.l2"); register_dependency(state, "test/c89/nested-putchar-a-param-ignored.l1", "test/c89/nested-putchar-a-param-ignored.l2"); register_dependency(state, "test/c89/nested-putchar-a-param-used.l1", "test/c89/nested-putchar-a-param-used.l2"); register_dependency(state, "test/c89/print.l1", "test/c89/print.l2"); register_dependency(state, "test/c89/putchar-return.l1", "test/c89/putchar-return.l2"); register_dependency(state, "test/c89/string-literal.l1", "test/c89/string-literal.l2"); register_dependency(state, "test/c89/use-array.l1", "test/c89/use-array.l2"); register_dependency(state, "test/c89/use-local.l1", "test/c89/use-local.l2"); register_dependency(state, "test/c89/use-reference.l1", "test/c89/use-reference.l2"); register_dependency(state, "test/c89/va_list_call.l1", "test/c89/va_list_call.l2"); register_dependency(state, "test/c89/while-loop.l1", "test/c89/while-loop.l2"); register_dependency(state, "test/c89/typedef.l1", "test/c89/typedef.l2"); register_dependency(state, "test/c89/exotic-declarators.l1", "test/c89/exotic-declarators.l2"); register_dependency(state, "test/c89/constants.l1", "test/c89/constants.l2"); register_dependency(state, "test/c89/malloc-test.l1", "test/c89/malloc-test.l2"); register_dependency(state, "test/c89/main_with_parameters.l1", "test/c89/main_with_parameters.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "test/c89/regex_engine_unit_tests.l2"); register_entity(state, "test/c99/preprocessor_test.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c99/preprocessor_test.c", "terminal", "true"); register_entity(state, "test/c99/snprintf_test.c", ENTITY_TYPE_C_FILE); add_entity_attribute(state, "test/c99/snprintf_test.c", "terminal", "true"); register_entity(state, "test/c99/preprocessor_test.i", ENTITY_TYPE_PREPROCESSED_FILE); register_entity(state, "test/c99/snprintf_test.i", ENTITY_TYPE_PREPROCESSED_FILE); register_dependency(state, "test/c99/preprocessor_test.i", "test/c99/preprocessor_test.c"); register_dependency(state, "test/c99/snprintf_test.i", "test/c99/snprintf_test.c"); register_entity(state, "test/c99/preprocessor_test.l2", ENTITY_TYPE_L2_FILE); register_entity(state, "test/c99/snprintf_test.l2", ENTITY_TYPE_L2_FILE); register_dependency(state, "test/c99/preprocessor_test.l2", "test/c99/preprocessor_test.i"); register_dependency(state, "test/c99/snprintf_test.l2", "test/c99/snprintf_test.i"); register_entity(state, "test/c99/preprocessor_test.l1", ENTITY_TYPE_L1_FILE); register_entity(state, "test/c99/snprintf_test.l1", ENTITY_TYPE_L1_FILE); register_dependency(state, "test/c99/preprocessor_test.l1", "test/c99/preprocessor_test.l2"); register_dependency(state, "test/c99/snprintf_test.l1", "test/c99/snprintf_test.l2"); register_entity(state, "test/c89/basic-operations.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/basic-operations.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/basic-operations.l0.js", "language", "jsonp"); register_entity(state, "test/c89/basic-putchar-aa.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/basic-putchar-aa.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/basic-putchar-aa.l0.js", "language", "jsonp"); register_entity(state, "test/c89/div-zero.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/div-zero.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/div-zero.l0.js", "language", "jsonp"); register_entity(state, "test/c89/preprocessor_test.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/preprocessor_test.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/preprocessor_test.l0.js", "language", "jsonp"); register_entity(state, "test/c89/filesystem.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/filesystem.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/filesystem.l0.js", "language", "jsonp"); register_entity(state, "test/c89/basic-putchar-a.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/basic-putchar-a.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/basic-putchar-a.l0.js", "language", "jsonp"); register_entity(state, "test/c89/basic-putchar-b.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/basic-putchar-b.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/basic-putchar-b.l0.js", "language", "jsonp"); register_entity(state, "test/c89/empty-main-return-zero.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/empty-main-return-zero.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/empty-main-return-zero.l0.js", "language", "jsonp"); register_entity(state, "test/c89/for-loop.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/for-loop.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/for-loop.l0.js", "language", "jsonp"); register_entity(state, "test/c89/ignore-local.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/ignore-local.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/ignore-local.l0.js", "language", "jsonp"); register_entity(state, "test/c89/many-types.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/many-types.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/many-types.l0.js", "language", "jsonp"); register_entity(state, "test/c89/nested-putchar-a.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/nested-putchar-a.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/nested-putchar-a.l0.js", "language", "jsonp"); register_entity(state, "test/c89/nested-putchar-a-param-ignored.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/nested-putchar-a-param-ignored.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/nested-putchar-a-param-ignored.l0.js", "language", "jsonp"); register_entity(state, "test/c89/nested-putchar-a-param-used.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/nested-putchar-a-param-used.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/nested-putchar-a-param-used.l0.js", "language", "jsonp"); register_entity(state, "test/c89/print.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/print.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/print.l0.js", "language", "jsonp"); register_entity(state, "test/c89/putchar-return.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/putchar-return.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/putchar-return.l0.js", "language", "jsonp"); register_entity(state, "test/c89/string-literal.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/string-literal.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/string-literal.l0.js", "language", "jsonp"); register_entity(state, "test/c89/use-array.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/use-array.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/use-array.l0.js", "language", "jsonp"); register_entity(state, "test/c89/use-local.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/use-local.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/use-local.l0.js", "language", "jsonp"); register_entity(state, "test/c89/use-reference.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/use-reference.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/use-reference.l0.js", "language", "jsonp"); register_entity(state, "test/c89/va_list_call.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/va_list_call.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/va_list_call.l0.js", "language", "jsonp"); register_entity(state, "test/c89/while-loop.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/while-loop.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/while-loop.l0.js", "language", "jsonp"); register_entity(state, "test/c89/typedef.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/typedef.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/typedef.l0.js", "language", "jsonp"); register_entity(state, "test/c89/exotic-declarators.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/exotic-declarators.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/exotic-declarators.l0.js", "language", "jsonp"); register_entity(state, "test/c89/constants.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/constants.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/constants.l0.js", "language", "jsonp"); register_entity(state, "test/c89/malloc-test.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/malloc-test.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/malloc-test.l0.js", "language", "jsonp"); register_entity(state, "test/c89/main_with_parameters.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/main_with_parameters.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/main_with_parameters.l0.js", "language", "jsonp"); register_entity(state, "test/c89/regex_engine_unit_tests.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c89/regex_engine_unit_tests.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c89/regex_engine_unit_tests.l0.js", "language", "jsonp"); register_entity(state, "test/c99/preprocessor_test.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c99/preprocessor_test.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c99/preprocessor_test.l0.js", "language", "jsonp"); register_entity(state, "test/c99/snprintf_test.l0.js", ENTITY_TYPE_L0_FILE); add_entity_attribute(state, "test/c99/snprintf_test.l0.js", "variable_name", "jsonpCallback"); add_entity_attribute(state, "test/c99/snprintf_test.l0.js", "language", "jsonp"); register_dependency(state, "test/c89/basic-operations.l0.js", "test/c89/basic-operations.l1"); register_dependency(state, "test/c89/basic-putchar-aa.l0.js", "test/c89/basic-putchar-aa.l1"); register_dependency(state, "test/c89/div-zero.l0.js", "test/c89/div-zero.l1"); register_dependency(state, "test/c89/preprocessor_test.l0.js", "test/c89/preprocessor_test.l1"); register_dependency(state, "test/c89/filesystem.l0.js", "test/c89/filesystem.l1"); register_dependency(state, "test/c89/basic-putchar-a.l0.js", "test/c89/basic-putchar-a.l1"); register_dependency(state, "test/c89/basic-putchar-b.l0.js", "test/c89/basic-putchar-b.l1"); register_dependency(state, "test/c89/empty-main-return-zero.l0.js", "test/c89/empty-main-return-zero.l1"); register_dependency(state, "test/c89/for-loop.l0.js", "test/c89/for-loop.l1"); register_dependency(state, "test/c89/ignore-local.l0.js", "test/c89/ignore-local.l1"); register_dependency(state, "test/c89/many-types.l0.js", "test/c89/many-types.l1"); register_dependency(state, "test/c89/nested-putchar-a.l0.js", "test/c89/nested-putchar-a.l1"); register_dependency(state, "test/c89/nested-putchar-a-param-ignored.l0.js", "test/c89/nested-putchar-a-param-ignored.l1"); register_dependency(state, "test/c89/nested-putchar-a-param-used.l0.js", "test/c89/nested-putchar-a-param-used.l1"); register_dependency(state, "test/c89/print.l0.js", "test/c89/print.l1"); register_dependency(state, "test/c89/putchar-return.l0.js", "test/c89/putchar-return.l1"); register_dependency(state, "test/c89/string-literal.l0.js", "test/c89/string-literal.l1"); register_dependency(state, "test/c89/use-array.l0.js", "test/c89/use-array.l1"); register_dependency(state, "test/c89/use-local.l0.js", "test/c89/use-local.l1"); register_dependency(state, "test/c89/use-reference.l0.js", "test/c89/use-reference.l1"); register_dependency(state, "test/c89/va_list_call.l0.js", "test/c89/va_list_call.l1"); register_dependency(state, "test/c89/while-loop.l0.js", "test/c89/while-loop.l1"); register_dependency(state, "test/c89/typedef.l0.js", "test/c89/typedef.l1"); register_dependency(state, "test/c89/exotic-declarators.l0.js", "test/c89/exotic-declarators.l1"); register_dependency(state, "test/c89/constants.l0.js", "test/c89/constants.l1"); register_dependency(state, "test/c89/malloc-test.l0.js", "test/c89/malloc-test.l1"); register_dependency(state, "test/c89/main_with_parameters.l0.js", "test/c89/main_with_parameters.l1"); register_dependency(state, "test/c89/regex_engine_unit_tests.l0.js", "test/c89/regex_engine_unit_tests.l1"); register_dependency(state, "test/c99/preprocessor_test.l0.js", "test/c99/preprocessor_test.l1"); register_dependency(state, "test/c99/snprintf_test.l0.js", "test/c99/snprintf_test.l1"); /* Link final l1 files */ register_dependency(state, "test/c89/filesystem.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/filesystem.l1", "recc-implementation/libdata-structures.l2"); register_dependency(state, "test/c89/filesystem.l1", "builtin/libbuiltin.l2"); register_dependency(state, "test/c89/filesystem.l1", "recc-implementation/binary_exponential_buffer.l2"); register_dependency(state, "test/c89/filesystem.l1", "recc-implementation/memory_pool_collection.l2"); register_dependency(state, "test/c89/filesystem.l1", "recc-implementation/code_generator.l2"); register_dependency(state, "test/c89/filesystem.l1", "recc-implementation/preprocessor.l2"); register_dependency(state, "test/c89/filesystem.l1", "recc-implementation/parser.l2"); register_dependency(state, "test/c89/filesystem.l1", "recc-implementation/lexer.l2"); register_dependency(state, "test/c89/filesystem.l1", "recc-implementation/io.l2"); register_dependency(state, "test/c89/filesystem.l1", "recc-implementation/regex_engine.l2"); register_dependency(state, "test/c89/filesystem.l1", "recc-implementation/type_engine.l2"); register_dependency(state, "test/c89/filesystem.l1", "libc/libc.l2"); register_dependency(state, "test/c89/filesystem.l1", "recc-implementation/filesystem_impl.l2"); register_dependency(state, "test/c89/filesystem.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/filesystem.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "recc-implementation/libdata-structures.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "builtin/libbuiltin.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "recc-implementation/binary_exponential_buffer.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "recc-implementation/memory_pool_collection.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "recc-implementation/code_generator.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "recc-implementation/preprocessor.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "recc-implementation/parser.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "recc-implementation/lexer.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "recc-implementation/io.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "recc-implementation/regex_engine.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "recc-implementation/type_engine.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "libc/libc.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "recc-implementation/filesystem_impl.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/regex_engine_unit_tests.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/basic-operations.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/basic-operations.l1", "builtin/libbuiltin.l2"); register_dependency(state, "test/c89/basic-operations.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/basic-operations.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/basic-operations.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/basic-operations.l1", "libc/printf.l2"); register_dependency(state, "test/c89/basic-putchar-aa.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/basic-putchar-aa.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/basic-putchar-aa.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/basic-putchar-aa.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/basic-putchar-aa.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/div-zero.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/div-zero.l1", "builtin/libbuiltin.l2"); register_dependency(state, "test/c89/div-zero.l1", "libc/assert.l2"); register_dependency(state, "test/c89/div-zero.l1", "libc/printf.l2"); register_dependency(state, "test/c89/div-zero.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/div-zero.l1", "test/extras/main_div_zero_test.l2"); register_dependency(state, "test/c89/div-zero.l1", "test/extras/l2/mainstub_div_zero_test.l2"); register_dependency(state, "test/c89/div-zero.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/preprocessor_test.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/preprocessor_test.l1", "builtin/libbuiltin.l2"); register_dependency(state, "test/c89/preprocessor_test.l1", "libc/assert.l2"); register_dependency(state, "test/c89/preprocessor_test.l1", "libc/printf.l2"); register_dependency(state, "test/c89/preprocessor_test.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/preprocessor_test.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/preprocessor_test.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/basic-putchar-a.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/basic-putchar-a.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/basic-putchar-a.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/basic-putchar-a.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/basic-putchar-a.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/basic-putchar-b.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/basic-putchar-b.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/basic-putchar-b.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/basic-putchar-b.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/basic-putchar-b.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/empty-main-return-zero.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/empty-main-return-zero.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/empty-main-return-zero.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/empty-main-return-zero.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/empty-main-return-zero.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/for-loop.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/for-loop.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/for-loop.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/for-loop.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/for-loop.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/ignore-local.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/ignore-local.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/ignore-local.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/ignore-local.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/ignore-local.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/many-types.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/many-types.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/many-types.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/many-types.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/many-types.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/nested-putchar-a.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/nested-putchar-a.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/nested-putchar-a.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/nested-putchar-a.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/nested-putchar-a.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/nested-putchar-a-param-ignored.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/nested-putchar-a-param-ignored.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/nested-putchar-a-param-ignored.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/nested-putchar-a-param-ignored.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/nested-putchar-a-param-ignored.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/nested-putchar-a-param-used.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/nested-putchar-a-param-used.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/nested-putchar-a-param-used.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/nested-putchar-a-param-used.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/nested-putchar-a-param-used.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/print.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/print.l1", "generated/unsigned_int_binary_search.l2"); register_dependency(state, "test/c89/print.l1", "libc/malloc.l2"); register_dependency(state, "test/c89/print.l1", "generated/unsigned_int_merge_sort.l2"); register_dependency(state, "test/c89/print.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/print.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/print.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/print.l1", "builtin/libbuiltin.l2"); register_dependency(state, "test/c89/print.l1", "libc/assert.l2"); register_dependency(state, "test/c89/print.l1", "libc/printf.l2"); register_dependency(state, "test/c89/print.l1", "test/extras/extern_test.l2"); register_dependency(state, "test/c89/print.l1", "test/extras/random.l2"); register_dependency(state, "test/c89/putchar-return.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/putchar-return.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/putchar-return.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/putchar-return.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/putchar-return.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/string-literal.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/string-literal.l1", "builtin/libbuiltin.l2"); register_dependency(state, "test/c89/string-literal.l1", "libc/assert.l2"); register_dependency(state, "test/c89/string-literal.l1", "libc/printf.l2"); register_dependency(state, "test/c89/string-literal.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/string-literal.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/string-literal.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/use-array.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/use-array.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/use-array.l1", "libc/assert.l2"); register_dependency(state, "test/c89/use-array.l1", "libc/printf.l2"); register_dependency(state, "test/c89/use-array.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/use-array.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/use-array.l1", "builtin/libbuiltin.l2"); register_dependency(state, "test/c89/use-local.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/use-local.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/use-local.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/use-local.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/use-local.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/use-reference.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/use-reference.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/use-reference.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/use-reference.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/use-reference.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/va_list_call.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/va_list_call.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/va_list_call.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/va_list_call.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/va_list_call.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/while-loop.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/while-loop.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/while-loop.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/while-loop.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/while-loop.l1", "builtin/signed_less_than.l2"); register_dependency(state, "test/c89/while-loop.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/typedef.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/typedef.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/typedef.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/typedef.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/typedef.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/exotic-declarators.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/exotic-declarators.l1", "builtin/stack.l2"); register_dependency(state, "test/c89/exotic-declarators.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/exotic-declarators.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/exotic-declarators.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/constants.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/constants.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/constants.l1", "builtin/libbuiltin.l2"); register_dependency(state, "test/c89/constants.l1", "libc/assert.l2"); register_dependency(state, "test/c89/constants.l1", "libc/printf.l2"); register_dependency(state, "test/c89/constants.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/constants.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/malloc-test.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/malloc-test.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/malloc-test.l1", "builtin/libbuiltin.l2"); register_dependency(state, "test/c89/malloc-test.l1", "libc/assert.l2"); register_dependency(state, "test/c89/malloc-test.l1", "libc/printf.l2"); register_dependency(state, "test/c89/malloc-test.l1", "libc/malloc.l2"); register_dependency(state, "test/c89/malloc-test.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/malloc-test.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c89/malloc-test.l1", "test/extras/random.l2"); register_dependency(state, "test/c89/main_with_parameters.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c89/main_with_parameters.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c89/main_with_parameters.l1", "test/extras/main_argv_indirect.l2"); register_dependency(state, "test/c89/main_with_parameters.l1", "test/extras/l2/mainstub_argv_indirect.l2"); register_dependency(state, "test/c89/main_with_parameters.l1", "libc/putchar.l2"); register_dependency(state, "test/c89/main_with_parameters.l1", "builtin/libbuiltin.l2"); register_dependency(state, "test/c89/main_with_parameters.l1", "libc/assert.l2"); register_dependency(state, "test/c89/main_with_parameters.l1", "libc/printf.l2"); register_dependency(state, "test/c99/preprocessor_test.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c99/preprocessor_test.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c99/preprocessor_test.l1", "builtin/libbuiltin.l2"); register_dependency(state, "test/c99/preprocessor_test.l1", "libc/assert.l2"); register_dependency(state, "test/c99/preprocessor_test.l1", "libc/printf.l2"); register_dependency(state, "test/c99/preprocessor_test.l1", "libc/malloc.l2"); register_dependency(state, "test/c99/preprocessor_test.l1", "libc/putchar.l2"); register_dependency(state, "test/c99/preprocessor_test.l1", "builtin/l2/mainstub.l2"); register_dependency(state, "test/c99/snprintf_test.l1", "kernel/l2/putchar_busy.l2"); register_dependency(state, "test/c99/snprintf_test.l1", "builtin/l2/memory_mapped_registers.l2"); register_dependency(state, "test/c99/snprintf_test.l1", "builtin/libbuiltin.l2"); register_dependency(state, "test/c99/snprintf_test.l1", "libc/assert.l2"); register_dependency(state, "test/c99/snprintf_test.l1", "libc/printf.l2"); register_dependency(state, "test/c99/snprintf_test.l1", "libc/malloc.l2"); register_dependency(state, "test/c99/snprintf_test.l1", "libc/putchar.l2"); register_dependency(state, "test/c99/snprintf_test.l1", "builtin/l2/mainstub.l2"); }
f03720d3e8e783248a8a36e5381cf62ffcafaf51
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/wayland-protocols/gtk/gtk/gtkliststore.c
8485586221bcbf34d3a360dda529bc6bf558f289
[ "BSD-3-Clause", "MIT", "LGPL-2.0-or-later", "LGPL-2.0-only", "LGPL-2.1-only", "Apache-2.0", "GPL-1.0-or-later" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C
false
false
78,225
c
gtkliststore.c
/* gtkliststore.c * Copyright (C) 2000 Red Hat, Inc., Jonathan Blandford <jrb@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <errno.h> #include <stdlib.h> #include <string.h> #include <gobject/gvaluecollector.h> #include "gtktreemodel.h" #include "gtkliststore.h" #include "gtktreedatalist.h" #include "gtktreednd.h" #include "gtkintl.h" #include "gtkbuildable.h" #include "gtkbuilderprivate.h" /** * GtkListStore: * * A list-like data structure that can be used with the GtkTreeView * * The #GtkListStore object is a list model for use with a #GtkTreeView * widget. It implements the #GtkTreeModel interface, and consequentialy, * can use all of the methods available there. It also implements the * #GtkTreeSortable interface so it can be sorted by the view. * Finally, it also implements the tree * [drag and drop][gtk4-GtkTreeView-drag-and-drop] * interfaces. * * The #GtkListStore can accept most GObject types as a column type, though * it can’t accept all custom types. Internally, it will keep a copy of * data passed in (such as a string or a boxed pointer). Columns that * accept #GObjects are handled a little differently. The * #GtkListStore will keep a reference to the object instead of copying the * value. As a result, if the object is modified, it is up to the * application writer to call gtk_tree_model_row_changed() to emit the * #GtkTreeModel::row_changed signal. This most commonly affects lists with * #GdkTextures stored. * * An example for creating a simple list store: * |[<!-- language="C" --> * enum { * COLUMN_STRING, * COLUMN_INT, * COLUMN_BOOLEAN, * N_COLUMNS * }; * * { * GtkListStore *list_store; * GtkTreePath *path; * GtkTreeIter iter; * int i; * * list_store = gtk_list_store_new (N_COLUMNS, * G_TYPE_STRING, * G_TYPE_INT, * G_TYPE_BOOLEAN); * * for (i = 0; i < 10; i++) * { * char *some_data; * * some_data = get_some_data (i); * * // Add a new row to the model * gtk_list_store_append (list_store, &iter); * gtk_list_store_set (list_store, &iter, * COLUMN_STRING, some_data, * COLUMN_INT, i, * COLUMN_BOOLEAN, FALSE, * -1); * * // As the store will keep a copy of the string internally, * // we free some_data. * g_free (some_data); * } * * // Modify a particular row * path = gtk_tree_path_new_from_string ("4"); * gtk_tree_model_get_iter (GTK_TREE_MODEL (list_store), * &iter, * path); * gtk_tree_path_free (path); * gtk_list_store_set (list_store, &iter, * COLUMN_BOOLEAN, TRUE, * -1); * } * ]| * * # Performance Considerations * * Internally, the #GtkListStore was originally implemented with a linked list * with a tail pointer. As a result, it was fast at data insertion and deletion, * and not fast at random data access. The #GtkListStore sets the * #GTK_TREE_MODEL_ITERS_PERSIST flag, which means that #GtkTreeIters can be * cached while the row exists. Thus, if access to a particular row is needed * often and your code is expected to run on older versions of GTK, it is worth * keeping the iter around. * * # Atomic Operations * * It is important to note that only the methods * gtk_list_store_insert_with_values() and gtk_list_store_insert_with_valuesv() * are atomic, in the sense that the row is being appended to the store and the * values filled in in a single operation with regard to #GtkTreeModel signaling. * In contrast, using e.g. gtk_list_store_append() and then gtk_list_store_set() * will first create a row, which triggers the #GtkTreeModel::row-inserted signal * on #GtkListStore. The row, however, is still empty, and any signal handler * connecting to #GtkTreeModel::row-inserted on this particular store should be prepared * for the situation that the row might be empty. This is especially important * if you are wrapping the #GtkListStore inside a #GtkTreeModelFilter and are * using a #GtkTreeModelFilterVisibleFunc. Using any of the non-atomic operations * to append rows to the #GtkListStore will cause the * #GtkTreeModelFilterVisibleFunc to be visited with an empty row first; the * function must be prepared for that. * * # GtkListStore as GtkBuildable * * The GtkListStore implementation of the GtkBuildable interface allows * to specify the model columns with a <columns> element that may contain * multiple <column> elements, each specifying one model column. The “type” * attribute specifies the data type for the column. * * Additionally, it is possible to specify content for the list store * in the UI definition, with the <data> element. It can contain multiple * <row> elements, each specifying to content for one row of the list model. * Inside a <row>, the <col> elements specify the content for individual cells. * * Note that it is probably more common to define your models in the code, * and one might consider it a layering violation to specify the content of * a list store in a UI definition, data, not presentation, and common wisdom * is to separate the two, as far as possible. * * An example of a UI Definition fragment for a list store: * |[<!-- language="C" --> * <object class="GtkListStore"> * <columns> * <column type="gchararray"/> * <column type="gchararray"/> * <column type="gint"/> * </columns> * <data> * <row> * <col id="0">John</col> * <col id="1">Doe</col> * <col id="2">25</col> * </row> * <row> * <col id="0">Johan</col> * <col id="1">Dahlin</col> * <col id="2">50</col> * </row> * </data> * </object> * ]| */ struct _GtkListStorePrivate { GtkTreeIterCompareFunc default_sort_func; GDestroyNotify default_sort_destroy; GList *sort_list; GType *column_headers; int stamp; int n_columns; int sort_column_id; int length; GtkSortType order; guint columns_dirty : 1; gpointer default_sort_data; gpointer seq; /* head of the list */ }; #define GTK_LIST_STORE_IS_SORTED(list) (((GtkListStore*)(list))->priv->sort_column_id != GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID) static void gtk_list_store_tree_model_init (GtkTreeModelIface *iface); static void gtk_list_store_drag_source_init(GtkTreeDragSourceIface *iface); static void gtk_list_store_drag_dest_init (GtkTreeDragDestIface *iface); static void gtk_list_store_sortable_init (GtkTreeSortableIface *iface); static void gtk_list_store_buildable_init (GtkBuildableIface *iface); static void gtk_list_store_finalize (GObject *object); static GtkTreeModelFlags gtk_list_store_get_flags (GtkTreeModel *tree_model); static int gtk_list_store_get_n_columns (GtkTreeModel *tree_model); static GType gtk_list_store_get_column_type (GtkTreeModel *tree_model, int index); static gboolean gtk_list_store_get_iter (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreePath *path); static GtkTreePath *gtk_list_store_get_path (GtkTreeModel *tree_model, GtkTreeIter *iter); static void gtk_list_store_get_value (GtkTreeModel *tree_model, GtkTreeIter *iter, int column, GValue *value); static gboolean gtk_list_store_iter_next (GtkTreeModel *tree_model, GtkTreeIter *iter); static gboolean gtk_list_store_iter_previous (GtkTreeModel *tree_model, GtkTreeIter *iter); static gboolean gtk_list_store_iter_children (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *parent); static gboolean gtk_list_store_iter_has_child (GtkTreeModel *tree_model, GtkTreeIter *iter); static int gtk_list_store_iter_n_children (GtkTreeModel *tree_model, GtkTreeIter *iter); static gboolean gtk_list_store_iter_nth_child (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *parent, int n); static gboolean gtk_list_store_iter_parent (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *child); static void gtk_list_store_set_n_columns (GtkListStore *list_store, int n_columns); static void gtk_list_store_set_column_type (GtkListStore *list_store, int column, GType type); static void gtk_list_store_increment_stamp (GtkListStore *list_store); /* Drag and Drop */ static gboolean real_gtk_list_store_row_draggable (GtkTreeDragSource *drag_source, GtkTreePath *path); static gboolean gtk_list_store_drag_data_delete (GtkTreeDragSource *drag_source, GtkTreePath *path); static GdkContentProvider * gtk_list_store_drag_data_get (GtkTreeDragSource *drag_source, GtkTreePath *path); static gboolean gtk_list_store_drag_data_received (GtkTreeDragDest *drag_dest, GtkTreePath *dest, const GValue *value); static gboolean gtk_list_store_row_drop_possible (GtkTreeDragDest *drag_dest, GtkTreePath *dest_path, const GValue *value); /* sortable */ static void gtk_list_store_sort (GtkListStore *list_store); static void gtk_list_store_sort_iter_changed (GtkListStore *list_store, GtkTreeIter *iter, int column); static gboolean gtk_list_store_get_sort_column_id (GtkTreeSortable *sortable, int *sort_column_id, GtkSortType *order); static void gtk_list_store_set_sort_column_id (GtkTreeSortable *sortable, int sort_column_id, GtkSortType order); static void gtk_list_store_set_sort_func (GtkTreeSortable *sortable, int sort_column_id, GtkTreeIterCompareFunc func, gpointer data, GDestroyNotify destroy); static void gtk_list_store_set_default_sort_func (GtkTreeSortable *sortable, GtkTreeIterCompareFunc func, gpointer data, GDestroyNotify destroy); static gboolean gtk_list_store_has_default_sort_func (GtkTreeSortable *sortable); /* buildable */ static gboolean gtk_list_store_buildable_custom_tag_start (GtkBuildable *buildable, GtkBuilder *builder, GObject *child, const char *tagname, GtkBuildableParser *parser, gpointer *data); static void gtk_list_store_buildable_custom_tag_end (GtkBuildable *buildable, GtkBuilder *builder, GObject *child, const char *tagname, gpointer data); G_DEFINE_TYPE_WITH_CODE (GtkListStore, gtk_list_store, G_TYPE_OBJECT, G_ADD_PRIVATE (GtkListStore) G_IMPLEMENT_INTERFACE (GTK_TYPE_TREE_MODEL, gtk_list_store_tree_model_init) G_IMPLEMENT_INTERFACE (GTK_TYPE_TREE_DRAG_SOURCE, gtk_list_store_drag_source_init) G_IMPLEMENT_INTERFACE (GTK_TYPE_TREE_DRAG_DEST, gtk_list_store_drag_dest_init) G_IMPLEMENT_INTERFACE (GTK_TYPE_TREE_SORTABLE, gtk_list_store_sortable_init) G_IMPLEMENT_INTERFACE (GTK_TYPE_BUILDABLE, gtk_list_store_buildable_init)) static void gtk_list_store_class_init (GtkListStoreClass *class) { GObjectClass *object_class; object_class = (GObjectClass*) class; object_class->finalize = gtk_list_store_finalize; } static void gtk_list_store_tree_model_init (GtkTreeModelIface *iface) { iface->get_flags = gtk_list_store_get_flags; iface->get_n_columns = gtk_list_store_get_n_columns; iface->get_column_type = gtk_list_store_get_column_type; iface->get_iter = gtk_list_store_get_iter; iface->get_path = gtk_list_store_get_path; iface->get_value = gtk_list_store_get_value; iface->iter_next = gtk_list_store_iter_next; iface->iter_previous = gtk_list_store_iter_previous; iface->iter_children = gtk_list_store_iter_children; iface->iter_has_child = gtk_list_store_iter_has_child; iface->iter_n_children = gtk_list_store_iter_n_children; iface->iter_nth_child = gtk_list_store_iter_nth_child; iface->iter_parent = gtk_list_store_iter_parent; } static void gtk_list_store_drag_source_init (GtkTreeDragSourceIface *iface) { iface->row_draggable = real_gtk_list_store_row_draggable; iface->drag_data_delete = gtk_list_store_drag_data_delete; iface->drag_data_get = gtk_list_store_drag_data_get; } static void gtk_list_store_drag_dest_init (GtkTreeDragDestIface *iface) { iface->drag_data_received = gtk_list_store_drag_data_received; iface->row_drop_possible = gtk_list_store_row_drop_possible; } static void gtk_list_store_sortable_init (GtkTreeSortableIface *iface) { iface->get_sort_column_id = gtk_list_store_get_sort_column_id; iface->set_sort_column_id = gtk_list_store_set_sort_column_id; iface->set_sort_func = gtk_list_store_set_sort_func; iface->set_default_sort_func = gtk_list_store_set_default_sort_func; iface->has_default_sort_func = gtk_list_store_has_default_sort_func; } void gtk_list_store_buildable_init (GtkBuildableIface *iface) { iface->custom_tag_start = gtk_list_store_buildable_custom_tag_start; iface->custom_tag_end = gtk_list_store_buildable_custom_tag_end; } static void gtk_list_store_init (GtkListStore *list_store) { GtkListStorePrivate *priv; list_store->priv = gtk_list_store_get_instance_private (list_store); priv = list_store->priv; priv->seq = g_sequence_new (NULL); priv->sort_list = NULL; priv->stamp = g_random_int (); priv->sort_column_id = GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID; priv->columns_dirty = FALSE; priv->length = 0; } static gboolean iter_is_valid (GtkTreeIter *iter, GtkListStore *list_store) { return iter != NULL && iter->user_data != NULL && list_store->priv->stamp == iter->stamp && !g_sequence_iter_is_end (iter->user_data) && g_sequence_iter_get_sequence (iter->user_data) == list_store->priv->seq; } /** * gtk_list_store_new: * @n_columns: number of columns in the list store * @...: all #GType types for the columns, from first to last * * Creates a new list store as with @n_columns columns each of the types passed * in. Note that only types derived from standard GObject fundamental types * are supported. * * As an example, `gtk_list_store_new (3, G_TYPE_INT, G_TYPE_STRING, * GDK_TYPE_TEXTURE);` will create a new #GtkListStore with three columns, of type * int, string and #GdkTexture, respectively. * * Returns: a new #GtkListStore */ GtkListStore * gtk_list_store_new (int n_columns, ...) { GtkListStore *retval; va_list args; int i; g_return_val_if_fail (n_columns > 0, NULL); retval = g_object_new (GTK_TYPE_LIST_STORE, NULL); gtk_list_store_set_n_columns (retval, n_columns); va_start (args, n_columns); for (i = 0; i < n_columns; i++) { GType type = va_arg (args, GType); if (! _gtk_tree_data_list_check_type (type)) { g_warning ("%s: Invalid type %s", G_STRLOC, g_type_name (type)); g_object_unref (retval); va_end (args); return NULL; } gtk_list_store_set_column_type (retval, i, type); } va_end (args); return retval; } /** * gtk_list_store_newv: (rename-to gtk_list_store_new) * @n_columns: number of columns in the list store * @types: (array length=n_columns): an array of #GType types for the columns, from first to last * * Non-vararg creation function. Used primarily by language bindings. * * Returns: (transfer full): a new #GtkListStore **/ GtkListStore * gtk_list_store_newv (int n_columns, GType *types) { GtkListStore *retval; int i; g_return_val_if_fail (n_columns > 0, NULL); retval = g_object_new (GTK_TYPE_LIST_STORE, NULL); gtk_list_store_set_n_columns (retval, n_columns); for (i = 0; i < n_columns; i++) { if (! _gtk_tree_data_list_check_type (types[i])) { g_warning ("%s: Invalid type %s", G_STRLOC, g_type_name (types[i])); g_object_unref (retval); return NULL; } gtk_list_store_set_column_type (retval, i, types[i]); } return retval; } /** * gtk_list_store_set_column_types: * @list_store: A #GtkListStore * @n_columns: Number of columns for the list store * @types: (array length=n_columns): An array length n of #GTypes * * This function is meant primarily for #GObjects that inherit from #GtkListStore, * and should only be used when constructing a new #GtkListStore. It will not * function after a row has been added, or a method on the #GtkTreeModel * interface is called. **/ void gtk_list_store_set_column_types (GtkListStore *list_store, int n_columns, GType *types) { GtkListStorePrivate *priv; int i; g_return_if_fail (GTK_IS_LIST_STORE (list_store)); priv = list_store->priv; g_return_if_fail (priv->columns_dirty == 0); gtk_list_store_set_n_columns (list_store, n_columns); for (i = 0; i < n_columns; i++) { if (! _gtk_tree_data_list_check_type (types[i])) { g_warning ("%s: Invalid type %s", G_STRLOC, g_type_name (types[i])); continue; } gtk_list_store_set_column_type (list_store, i, types[i]); } } static void gtk_list_store_set_n_columns (GtkListStore *list_store, int n_columns) { GtkListStorePrivate *priv = list_store->priv; int i; if (priv->n_columns == n_columns) return; priv->column_headers = g_renew (GType, priv->column_headers, n_columns); for (i = priv->n_columns; i < n_columns; i++) priv->column_headers[i] = G_TYPE_INVALID; priv->n_columns = n_columns; if (priv->sort_list) _gtk_tree_data_list_header_free (priv->sort_list); priv->sort_list = _gtk_tree_data_list_header_new (n_columns, priv->column_headers); } static void gtk_list_store_set_column_type (GtkListStore *list_store, int column, GType type) { GtkListStorePrivate *priv = list_store->priv; if (!_gtk_tree_data_list_check_type (type)) { g_warning ("%s: Invalid type %s", G_STRLOC, g_type_name (type)); return; } priv->column_headers[column] = type; } static void gtk_list_store_finalize (GObject *object) { GtkListStore *list_store = GTK_LIST_STORE (object); GtkListStorePrivate *priv = list_store->priv; g_sequence_foreach (priv->seq, (GFunc) _gtk_tree_data_list_free, priv->column_headers); g_sequence_free (priv->seq); _gtk_tree_data_list_header_free (priv->sort_list); g_free (priv->column_headers); if (priv->default_sort_destroy) { GDestroyNotify d = priv->default_sort_destroy; priv->default_sort_destroy = NULL; d (priv->default_sort_data); priv->default_sort_data = NULL; } G_OBJECT_CLASS (gtk_list_store_parent_class)->finalize (object); } /* Fulfill the GtkTreeModel requirements */ static GtkTreeModelFlags gtk_list_store_get_flags (GtkTreeModel *tree_model) { return GTK_TREE_MODEL_ITERS_PERSIST | GTK_TREE_MODEL_LIST_ONLY; } static int gtk_list_store_get_n_columns (GtkTreeModel *tree_model) { GtkListStore *list_store = GTK_LIST_STORE (tree_model); GtkListStorePrivate *priv = list_store->priv; priv->columns_dirty = TRUE; return priv->n_columns; } static GType gtk_list_store_get_column_type (GtkTreeModel *tree_model, int index) { GtkListStore *list_store = GTK_LIST_STORE (tree_model); GtkListStorePrivate *priv = list_store->priv; g_return_val_if_fail (index < priv->n_columns, G_TYPE_INVALID); priv->columns_dirty = TRUE; return priv->column_headers[index]; } static gboolean gtk_list_store_get_iter (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreePath *path) { GtkListStore *list_store = GTK_LIST_STORE (tree_model); GtkListStorePrivate *priv = list_store->priv; GSequence *seq; int i; priv->columns_dirty = TRUE; seq = priv->seq; i = gtk_tree_path_get_indices (path)[0]; if (i >= g_sequence_get_length (seq)) { iter->stamp = 0; return FALSE; } iter->stamp = priv->stamp; iter->user_data = g_sequence_get_iter_at_pos (seq, i); return TRUE; } static GtkTreePath * gtk_list_store_get_path (GtkTreeModel *tree_model, GtkTreeIter *iter) { GtkListStore *list_store = GTK_LIST_STORE (tree_model); GtkListStorePrivate *priv = list_store->priv; GtkTreePath *path; g_return_val_if_fail (iter->stamp == priv->stamp, NULL); if (g_sequence_iter_is_end (iter->user_data)) return NULL; path = gtk_tree_path_new (); gtk_tree_path_append_index (path, g_sequence_iter_get_position (iter->user_data)); return path; } static void gtk_list_store_get_value (GtkTreeModel *tree_model, GtkTreeIter *iter, int column, GValue *value) { GtkListStore *list_store = GTK_LIST_STORE (tree_model); GtkListStorePrivate *priv = list_store->priv; GtkTreeDataList *list; int tmp_column = column; g_return_if_fail (column < priv->n_columns); g_return_if_fail (iter_is_valid (iter, list_store)); list = g_sequence_get (iter->user_data); while (tmp_column-- > 0 && list) list = list->next; if (list == NULL) g_value_init (value, priv->column_headers[column]); else _gtk_tree_data_list_node_to_value (list, priv->column_headers[column], value); } static gboolean gtk_list_store_iter_next (GtkTreeModel *tree_model, GtkTreeIter *iter) { GtkListStore *list_store = GTK_LIST_STORE (tree_model); GtkListStorePrivate *priv = list_store->priv; gboolean retval; g_return_val_if_fail (priv->stamp == iter->stamp, FALSE); iter->user_data = g_sequence_iter_next (iter->user_data); retval = g_sequence_iter_is_end (iter->user_data); if (retval) iter->stamp = 0; return !retval; } static gboolean gtk_list_store_iter_previous (GtkTreeModel *tree_model, GtkTreeIter *iter) { GtkListStore *list_store = GTK_LIST_STORE (tree_model); GtkListStorePrivate *priv = list_store->priv; g_return_val_if_fail (priv->stamp == iter->stamp, FALSE); if (g_sequence_iter_is_begin (iter->user_data)) { iter->stamp = 0; return FALSE; } iter->user_data = g_sequence_iter_prev (iter->user_data); return TRUE; } static gboolean gtk_list_store_iter_children (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *parent) { GtkListStore *list_store = (GtkListStore *) tree_model; GtkListStorePrivate *priv = list_store->priv; /* this is a list, nodes have no children */ if (parent) { iter->stamp = 0; return FALSE; } if (g_sequence_get_length (priv->seq) > 0) { iter->stamp = priv->stamp; iter->user_data = g_sequence_get_begin_iter (priv->seq); return TRUE; } else { iter->stamp = 0; return FALSE; } } static gboolean gtk_list_store_iter_has_child (GtkTreeModel *tree_model, GtkTreeIter *iter) { return FALSE; } static int gtk_list_store_iter_n_children (GtkTreeModel *tree_model, GtkTreeIter *iter) { GtkListStore *list_store = GTK_LIST_STORE (tree_model); GtkListStorePrivate *priv = list_store->priv; if (iter == NULL) return g_sequence_get_length (priv->seq); g_return_val_if_fail (priv->stamp == iter->stamp, -1); return 0; } static gboolean gtk_list_store_iter_nth_child (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *parent, int n) { GtkListStore *list_store = GTK_LIST_STORE (tree_model); GtkListStorePrivate *priv = list_store->priv; GSequenceIter *child; iter->stamp = 0; if (parent) return FALSE; child = g_sequence_get_iter_at_pos (priv->seq, n); if (g_sequence_iter_is_end (child)) return FALSE; iter->stamp = priv->stamp; iter->user_data = child; return TRUE; } static gboolean gtk_list_store_iter_parent (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *child) { iter->stamp = 0; return FALSE; } static gboolean gtk_list_store_real_set_value (GtkListStore *list_store, GtkTreeIter *iter, int column, GValue *value, gboolean sort) { GtkListStorePrivate *priv = list_store->priv; GtkTreeDataList *list; GtkTreeDataList *prev; int old_column = column; GValue real_value = G_VALUE_INIT; gboolean converted = FALSE; gboolean retval = FALSE; if (! g_type_is_a (G_VALUE_TYPE (value), priv->column_headers[column])) { if (! (g_value_type_transformable (G_VALUE_TYPE (value), priv->column_headers[column]))) { g_warning ("%s: Unable to convert from %s to %s", G_STRLOC, g_type_name (G_VALUE_TYPE (value)), g_type_name (priv->column_headers[column])); return retval; } g_value_init (&real_value, priv->column_headers[column]); if (!g_value_transform (value, &real_value)) { g_warning ("%s: Unable to make conversion from %s to %s", G_STRLOC, g_type_name (G_VALUE_TYPE (value)), g_type_name (priv->column_headers[column])); g_value_unset (&real_value); return retval; } converted = TRUE; } prev = list = g_sequence_get (iter->user_data); while (list != NULL) { if (column == 0) { if (converted) _gtk_tree_data_list_value_to_node (list, &real_value); else _gtk_tree_data_list_value_to_node (list, value); retval = TRUE; if (converted) g_value_unset (&real_value); if (sort && GTK_LIST_STORE_IS_SORTED (list_store)) gtk_list_store_sort_iter_changed (list_store, iter, old_column); return retval; } column--; prev = list; list = list->next; } if (g_sequence_get (iter->user_data) == NULL) { list = _gtk_tree_data_list_alloc(); g_sequence_set (iter->user_data, list); list->next = NULL; } else { list = prev->next = _gtk_tree_data_list_alloc (); list->next = NULL; } while (column != 0) { list->next = _gtk_tree_data_list_alloc (); list = list->next; list->next = NULL; column --; } if (converted) _gtk_tree_data_list_value_to_node (list, &real_value); else _gtk_tree_data_list_value_to_node (list, value); retval = TRUE; if (converted) g_value_unset (&real_value); if (sort && GTK_LIST_STORE_IS_SORTED (list_store)) gtk_list_store_sort_iter_changed (list_store, iter, old_column); return retval; } /** * gtk_list_store_set_value: * @list_store: A #GtkListStore * @iter: A valid #GtkTreeIter for the row being modified * @column: column number to modify * @value: new value for the cell * * Sets the data in the cell specified by @iter and @column. * The type of @value must be convertible to the type of the * column. * **/ void gtk_list_store_set_value (GtkListStore *list_store, GtkTreeIter *iter, int column, GValue *value) { GtkListStorePrivate *priv; g_return_if_fail (GTK_IS_LIST_STORE (list_store)); g_return_if_fail (iter_is_valid (iter, list_store)); g_return_if_fail (G_IS_VALUE (value)); priv = list_store->priv; g_return_if_fail (column >= 0 && column < priv->n_columns); if (gtk_list_store_real_set_value (list_store, iter, column, value, TRUE)) { GtkTreePath *path; path = gtk_list_store_get_path (GTK_TREE_MODEL (list_store), iter); gtk_tree_model_row_changed (GTK_TREE_MODEL (list_store), path, iter); gtk_tree_path_free (path); } } static GtkTreeIterCompareFunc gtk_list_store_get_compare_func (GtkListStore *list_store) { GtkListStorePrivate *priv = list_store->priv; GtkTreeIterCompareFunc func = NULL; if (GTK_LIST_STORE_IS_SORTED (list_store)) { if (priv->sort_column_id != -1) { GtkTreeDataSortHeader *header; header = _gtk_tree_data_list_get_header (priv->sort_list, priv->sort_column_id); g_return_val_if_fail (header != NULL, NULL); g_return_val_if_fail (header->func != NULL, NULL); func = header->func; } else { func = priv->default_sort_func; } } return func; } static void gtk_list_store_set_vector_internal (GtkListStore *list_store, GtkTreeIter *iter, gboolean *emit_signal, gboolean *maybe_need_sort, int *columns, GValue *values, int n_values) { GtkListStorePrivate *priv = list_store->priv; int i; GtkTreeIterCompareFunc func = NULL; func = gtk_list_store_get_compare_func (list_store); if (func != _gtk_tree_data_list_compare_func) *maybe_need_sort = TRUE; for (i = 0; i < n_values; i++) { *emit_signal = gtk_list_store_real_set_value (list_store, iter, columns[i], &values[i], FALSE) || *emit_signal; if (func == _gtk_tree_data_list_compare_func && columns[i] == priv->sort_column_id) *maybe_need_sort = TRUE; } } static void gtk_list_store_set_valist_internal (GtkListStore *list_store, GtkTreeIter *iter, gboolean *emit_signal, gboolean *maybe_need_sort, va_list var_args) { GtkListStorePrivate *priv = list_store->priv; int column; GtkTreeIterCompareFunc func = NULL; column = va_arg (var_args, int); func = gtk_list_store_get_compare_func (list_store); if (func != _gtk_tree_data_list_compare_func) *maybe_need_sort = TRUE; while (column != -1) { GValue value = G_VALUE_INIT; char *error = NULL; if (column < 0 || column >= priv->n_columns) { g_warning ("%s: Invalid column number %d added to iter (remember to end your list of columns with a -1)", G_STRLOC, column); break; } G_VALUE_COLLECT_INIT (&value, priv->column_headers[column], var_args, 0, &error); if (error) { g_warning ("%s: %s", G_STRLOC, error); g_free (error); /* we purposely leak the value here, it might not be * in a sane state if an error condition occurred */ break; } /* FIXME: instead of calling this n times, refactor with above */ *emit_signal = gtk_list_store_real_set_value (list_store, iter, column, &value, FALSE) || *emit_signal; if (func == _gtk_tree_data_list_compare_func && column == priv->sort_column_id) *maybe_need_sort = TRUE; g_value_unset (&value); column = va_arg (var_args, int); } } /** * gtk_list_store_set_valuesv: (rename-to gtk_list_store_set) * @list_store: A #GtkListStore * @iter: A valid #GtkTreeIter for the row being modified * @columns: (array length=n_values): an array of column numbers * @values: (array length=n_values): an array of GValues * @n_values: the length of the @columns and @values arrays * * A variant of gtk_list_store_set_valist() which * takes the columns and values as two arrays, instead of * varargs. This function is mainly intended for * language-bindings and in case the number of columns to * change is not known until run-time. */ void gtk_list_store_set_valuesv (GtkListStore *list_store, GtkTreeIter *iter, int *columns, GValue *values, int n_values) { GtkListStorePrivate *priv; gboolean emit_signal = FALSE; gboolean maybe_need_sort = FALSE; g_return_if_fail (GTK_IS_LIST_STORE (list_store)); g_return_if_fail (iter_is_valid (iter, list_store)); priv = list_store->priv; gtk_list_store_set_vector_internal (list_store, iter, &emit_signal, &maybe_need_sort, columns, values, n_values); if (maybe_need_sort && GTK_LIST_STORE_IS_SORTED (list_store)) gtk_list_store_sort_iter_changed (list_store, iter, priv->sort_column_id); if (emit_signal) { GtkTreePath *path; path = gtk_list_store_get_path (GTK_TREE_MODEL (list_store), iter); gtk_tree_model_row_changed (GTK_TREE_MODEL (list_store), path, iter); gtk_tree_path_free (path); } } /** * gtk_list_store_set_valist: * @list_store: A #GtkListStore * @iter: A valid #GtkTreeIter for the row being modified * @var_args: va_list of column/value pairs * * See gtk_list_store_set(); this version takes a va_list for use by language * bindings. * **/ void gtk_list_store_set_valist (GtkListStore *list_store, GtkTreeIter *iter, va_list var_args) { GtkListStorePrivate *priv; gboolean emit_signal = FALSE; gboolean maybe_need_sort = FALSE; g_return_if_fail (GTK_IS_LIST_STORE (list_store)); g_return_if_fail (iter_is_valid (iter, list_store)); priv = list_store->priv; gtk_list_store_set_valist_internal (list_store, iter, &emit_signal, &maybe_need_sort, var_args); if (maybe_need_sort && GTK_LIST_STORE_IS_SORTED (list_store)) gtk_list_store_sort_iter_changed (list_store, iter, priv->sort_column_id); if (emit_signal) { GtkTreePath *path; path = gtk_list_store_get_path (GTK_TREE_MODEL (list_store), iter); gtk_tree_model_row_changed (GTK_TREE_MODEL (list_store), path, iter); gtk_tree_path_free (path); } } /** * gtk_list_store_set: * @list_store: a #GtkListStore * @iter: row iterator * @...: pairs of column number and value, terminated with -1 * * Sets the value of one or more cells in the row referenced by @iter. * The variable argument list should contain integer column numbers, * each column number followed by the value to be set. * The list is terminated by a -1. For example, to set column 0 with type * %G_TYPE_STRING to “Foo”, you would write `gtk_list_store_set (store, iter, * 0, "Foo", -1)`. * * The value will be referenced by the store if it is a %G_TYPE_OBJECT, and it * will be copied if it is a %G_TYPE_STRING or %G_TYPE_BOXED. */ void gtk_list_store_set (GtkListStore *list_store, GtkTreeIter *iter, ...) { va_list var_args; va_start (var_args, iter); gtk_list_store_set_valist (list_store, iter, var_args); va_end (var_args); } /** * gtk_list_store_remove: * @list_store: A #GtkListStore * @iter: A valid #GtkTreeIter * * Removes the given row from the list store. After being removed, * @iter is set to be the next valid row, or invalidated if it pointed * to the last row in @list_store. * * Returns: %TRUE if @iter is valid, %FALSE if not. **/ gboolean gtk_list_store_remove (GtkListStore *list_store, GtkTreeIter *iter) { GtkListStorePrivate *priv; GtkTreePath *path; GSequenceIter *ptr, *next; g_return_val_if_fail (GTK_IS_LIST_STORE (list_store), FALSE); g_return_val_if_fail (iter_is_valid (iter, list_store), FALSE); priv = list_store->priv; path = gtk_list_store_get_path (GTK_TREE_MODEL (list_store), iter); ptr = iter->user_data; next = g_sequence_iter_next (ptr); _gtk_tree_data_list_free (g_sequence_get (ptr), priv->column_headers); g_sequence_remove (iter->user_data); priv->length--; gtk_tree_model_row_deleted (GTK_TREE_MODEL (list_store), path); gtk_tree_path_free (path); if (g_sequence_iter_is_end (next)) { iter->stamp = 0; return FALSE; } else { iter->stamp = priv->stamp; iter->user_data = next; return TRUE; } } /** * gtk_list_store_insert: * @list_store: A #GtkListStore * @iter: (out): An unset #GtkTreeIter to set to the new row * @position: position to insert the new row, or -1 for last * * Creates a new row at @position. @iter will be changed to point to this new * row. If @position is -1 or is larger than the number of rows on the list, * then the new row will be appended to the list. The row will be empty after * this function is called. To fill in values, you need to call * gtk_list_store_set() or gtk_list_store_set_value(). * **/ void gtk_list_store_insert (GtkListStore *list_store, GtkTreeIter *iter, int position) { GtkListStorePrivate *priv; GtkTreePath *path; GSequence *seq; GSequenceIter *ptr; int length; g_return_if_fail (GTK_IS_LIST_STORE (list_store)); g_return_if_fail (iter != NULL); priv = list_store->priv; priv->columns_dirty = TRUE; seq = priv->seq; length = g_sequence_get_length (seq); if (position > length || position < 0) position = length; ptr = g_sequence_get_iter_at_pos (seq, position); ptr = g_sequence_insert_before (ptr, NULL); iter->stamp = priv->stamp; iter->user_data = ptr; g_assert (iter_is_valid (iter, list_store)); priv->length++; path = gtk_tree_path_new (); gtk_tree_path_append_index (path, position); gtk_tree_model_row_inserted (GTK_TREE_MODEL (list_store), path, iter); gtk_tree_path_free (path); } /** * gtk_list_store_insert_before: * @list_store: A #GtkListStore * @iter: (out): An unset #GtkTreeIter to set to the new row * @sibling: (allow-none): A valid #GtkTreeIter, or %NULL * * Inserts a new row before @sibling. If @sibling is %NULL, then the row will * be appended to the end of the list. @iter will be changed to point to this * new row. The row will be empty after this function is called. To fill in * values, you need to call gtk_list_store_set() or gtk_list_store_set_value(). * **/ void gtk_list_store_insert_before (GtkListStore *list_store, GtkTreeIter *iter, GtkTreeIter *sibling) { GtkListStorePrivate *priv; GSequenceIter *after; g_return_if_fail (GTK_IS_LIST_STORE (list_store)); g_return_if_fail (iter != NULL); priv = list_store->priv; if (sibling) g_return_if_fail (iter_is_valid (sibling, list_store)); if (!sibling) after = g_sequence_get_end_iter (priv->seq); else after = sibling->user_data; gtk_list_store_insert (list_store, iter, g_sequence_iter_get_position (after)); } /** * gtk_list_store_insert_after: * @list_store: A #GtkListStore * @iter: (out): An unset #GtkTreeIter to set to the new row * @sibling: (allow-none): A valid #GtkTreeIter, or %NULL * * Inserts a new row after @sibling. If @sibling is %NULL, then the row will be * prepended to the beginning of the list. @iter will be changed to point to * this new row. The row will be empty after this function is called. To fill * in values, you need to call gtk_list_store_set() or gtk_list_store_set_value(). * **/ void gtk_list_store_insert_after (GtkListStore *list_store, GtkTreeIter *iter, GtkTreeIter *sibling) { GtkListStorePrivate *priv; GSequenceIter *after; g_return_if_fail (GTK_IS_LIST_STORE (list_store)); g_return_if_fail (iter != NULL); priv = list_store->priv; if (sibling) g_return_if_fail (iter_is_valid (sibling, list_store)); if (!sibling) after = g_sequence_get_begin_iter (priv->seq); else after = g_sequence_iter_next (sibling->user_data); gtk_list_store_insert (list_store, iter, g_sequence_iter_get_position (after)); } /** * gtk_list_store_prepend: * @list_store: A #GtkListStore * @iter: (out): An unset #GtkTreeIter to set to the prepend row * * Prepends a new row to @list_store. @iter will be changed to point to this new * row. The row will be empty after this function is called. To fill in * values, you need to call gtk_list_store_set() or gtk_list_store_set_value(). * **/ void gtk_list_store_prepend (GtkListStore *list_store, GtkTreeIter *iter) { g_return_if_fail (GTK_IS_LIST_STORE (list_store)); g_return_if_fail (iter != NULL); gtk_list_store_insert (list_store, iter, 0); } /** * gtk_list_store_append: * @list_store: A #GtkListStore * @iter: (out): An unset #GtkTreeIter to set to the appended row * * Appends a new row to @list_store. @iter will be changed to point to this new * row. The row will be empty after this function is called. To fill in * values, you need to call gtk_list_store_set() or gtk_list_store_set_value(). * **/ void gtk_list_store_append (GtkListStore *list_store, GtkTreeIter *iter) { g_return_if_fail (GTK_IS_LIST_STORE (list_store)); g_return_if_fail (iter != NULL); gtk_list_store_insert (list_store, iter, -1); } static void gtk_list_store_increment_stamp (GtkListStore *list_store) { GtkListStorePrivate *priv = list_store->priv; do { priv->stamp++; } while (priv->stamp == 0); } /** * gtk_list_store_clear: * @list_store: a #GtkListStore. * * Removes all rows from the list store. * **/ void gtk_list_store_clear (GtkListStore *list_store) { GtkListStorePrivate *priv; GtkTreeIter iter; g_return_if_fail (GTK_IS_LIST_STORE (list_store)); priv = list_store->priv; while (g_sequence_get_length (priv->seq) > 0) { iter.stamp = priv->stamp; iter.user_data = g_sequence_get_begin_iter (priv->seq); gtk_list_store_remove (list_store, &iter); } gtk_list_store_increment_stamp (list_store); } /** * gtk_list_store_iter_is_valid: * @list_store: A #GtkListStore. * @iter: A #GtkTreeIter. * * > This function is slow. Only use it for debugging and/or testing * > purposes. * * Checks if the given iter is a valid iter for this #GtkListStore. * * Returns: %TRUE if the iter is valid, %FALSE if the iter is invalid. **/ gboolean gtk_list_store_iter_is_valid (GtkListStore *list_store, GtkTreeIter *iter) { GtkListStorePrivate *priv; GSequenceIter *seq_iter; g_return_val_if_fail (GTK_IS_LIST_STORE (list_store), FALSE); g_return_val_if_fail (iter != NULL, FALSE); /* can't use iter_is_valid() here, because iter might point * to random memory. * * We MUST NOT dereference it. */ priv = list_store->priv; if (iter == NULL || iter->user_data == NULL || priv->stamp != iter->stamp) return FALSE; for (seq_iter = g_sequence_get_begin_iter (priv->seq); !g_sequence_iter_is_end (seq_iter); seq_iter = g_sequence_iter_next (seq_iter)) { if (seq_iter == iter->user_data) return TRUE; } return FALSE; } static gboolean real_gtk_list_store_row_draggable (GtkTreeDragSource *drag_source, GtkTreePath *path) { return TRUE; } static gboolean gtk_list_store_drag_data_delete (GtkTreeDragSource *drag_source, GtkTreePath *path) { GtkTreeIter iter; if (gtk_list_store_get_iter (GTK_TREE_MODEL (drag_source), &iter, path)) { gtk_list_store_remove (GTK_LIST_STORE (drag_source), &iter); return TRUE; } return FALSE; } static GdkContentProvider * gtk_list_store_drag_data_get (GtkTreeDragSource *drag_source, GtkTreePath *path) { /* Note that we don't need to handle the GTK_TREE_MODEL_ROW * target, because the default handler does it for us, but * we do anyway for the convenience of someone maybe overriding the * default handler. */ return gtk_tree_create_row_drag_content (GTK_TREE_MODEL (drag_source), path); } static gboolean gtk_list_store_drag_data_received (GtkTreeDragDest *drag_dest, GtkTreePath *dest, const GValue *value) { GtkTreeModel *tree_model = GTK_TREE_MODEL (drag_dest); GtkListStore *list_store = GTK_LIST_STORE (tree_model); GtkListStorePrivate *priv = list_store->priv; GtkTreeModel *src_model = NULL; GtkTreePath *src_path = NULL; gboolean retval = FALSE; if (gtk_tree_get_row_drag_data (value, &src_model, &src_path) && src_model == tree_model) { /* Copy the given row to a new position */ GtkTreeIter src_iter; GtkTreeIter dest_iter; GtkTreePath *prev; if (!gtk_list_store_get_iter (src_model, &src_iter, src_path)) { goto out; } /* Get the path to insert _after_ (dest is the path to insert _before_) */ prev = gtk_tree_path_copy (dest); if (!gtk_tree_path_prev (prev)) { /* dest was the first spot in the list; which means we are supposed * to prepend. */ gtk_list_store_prepend (list_store, &dest_iter); retval = TRUE; } else { if (gtk_list_store_get_iter (tree_model, &dest_iter, prev)) { GtkTreeIter tmp_iter = dest_iter; gtk_list_store_insert_after (list_store, &dest_iter, &tmp_iter); retval = TRUE; } } gtk_tree_path_free (prev); /* If we succeeded in creating dest_iter, copy data from src */ if (retval) { GtkTreeDataList *dl = g_sequence_get (src_iter.user_data); GtkTreeDataList *copy_head = NULL; GtkTreeDataList *copy_prev = NULL; GtkTreeDataList *copy_iter = NULL; GtkTreePath *path; int col; col = 0; while (dl) { copy_iter = _gtk_tree_data_list_node_copy (dl, priv->column_headers[col]); if (copy_head == NULL) copy_head = copy_iter; if (copy_prev) copy_prev->next = copy_iter; copy_prev = copy_iter; dl = dl->next; ++col; } dest_iter.stamp = priv->stamp; g_sequence_set (dest_iter.user_data, copy_head); path = gtk_list_store_get_path (tree_model, &dest_iter); gtk_tree_model_row_changed (tree_model, path, &dest_iter); gtk_tree_path_free (path); } } else { /* FIXME maybe add some data targets eventually, or handle text * targets in the simple case. */ } out: if (src_path) gtk_tree_path_free (src_path); return retval; } static gboolean gtk_list_store_row_drop_possible (GtkTreeDragDest *drag_dest, GtkTreePath *dest_path, const GValue *value) { int *indices; GtkTreeModel *src_model = NULL; GtkTreePath *src_path = NULL; gboolean retval = FALSE; /* don't accept drops if the list has been sorted */ if (GTK_LIST_STORE_IS_SORTED (drag_dest)) return FALSE; if (!gtk_tree_get_row_drag_data (value, &src_model, &src_path)) goto out; if (src_model != GTK_TREE_MODEL (drag_dest)) goto out; if (gtk_tree_path_get_depth (dest_path) != 1) goto out; /* can drop before any existing node, or before one past any existing. */ indices = gtk_tree_path_get_indices (dest_path); if (indices[0] <= g_sequence_get_length (GTK_LIST_STORE (drag_dest)->priv->seq)) retval = TRUE; out: if (src_path) gtk_tree_path_free (src_path); return retval; } /* Sorting and reordering */ /* Reordering */ static int gtk_list_store_reorder_func (GSequenceIter *a, GSequenceIter *b, gpointer user_data) { GHashTable *new_positions = user_data; int apos = GPOINTER_TO_INT (g_hash_table_lookup (new_positions, a)); int bpos = GPOINTER_TO_INT (g_hash_table_lookup (new_positions, b)); if (apos < bpos) return -1; if (apos > bpos) return 1; return 0; } /** * gtk_list_store_reorder: * @store: A #GtkListStore. * @new_order: (array zero-terminated=1): an array of integers mapping the new * position of each child to its old position before the re-ordering, * i.e. @new_order`[newpos] = oldpos`. It must have * exactly as many items as the list store’s length. * * Reorders @store to follow the order indicated by @new_order. Note that * this function only works with unsorted stores. **/ void gtk_list_store_reorder (GtkListStore *store, int *new_order) { GtkListStorePrivate *priv; int i; GtkTreePath *path; GHashTable *new_positions; GSequenceIter *ptr; int *order; g_return_if_fail (GTK_IS_LIST_STORE (store)); g_return_if_fail (!GTK_LIST_STORE_IS_SORTED (store)); g_return_if_fail (new_order != NULL); priv = store->priv; order = g_new (int, g_sequence_get_length (priv->seq)); for (i = 0; i < g_sequence_get_length (priv->seq); i++) order[new_order[i]] = i; new_positions = g_hash_table_new (g_direct_hash, g_direct_equal); ptr = g_sequence_get_begin_iter (priv->seq); i = 0; while (!g_sequence_iter_is_end (ptr)) { g_hash_table_insert (new_positions, ptr, GINT_TO_POINTER (order[i++])); ptr = g_sequence_iter_next (ptr); } g_free (order); g_sequence_sort_iter (priv->seq, gtk_list_store_reorder_func, new_positions); g_hash_table_destroy (new_positions); /* emit signal */ path = gtk_tree_path_new (); gtk_tree_model_rows_reordered (GTK_TREE_MODEL (store), path, NULL, new_order); gtk_tree_path_free (path); } static GHashTable * save_positions (GSequence *seq) { GHashTable *positions = g_hash_table_new (g_direct_hash, g_direct_equal); GSequenceIter *ptr; ptr = g_sequence_get_begin_iter (seq); while (!g_sequence_iter_is_end (ptr)) { g_hash_table_insert (positions, ptr, GINT_TO_POINTER (g_sequence_iter_get_position (ptr))); ptr = g_sequence_iter_next (ptr); } return positions; } static int * generate_order (GSequence *seq, GHashTable *old_positions) { GSequenceIter *ptr; int *order = g_new (int, g_sequence_get_length (seq)); int i; i = 0; ptr = g_sequence_get_begin_iter (seq); while (!g_sequence_iter_is_end (ptr)) { int old_pos = GPOINTER_TO_INT (g_hash_table_lookup (old_positions, ptr)); order[i++] = old_pos; ptr = g_sequence_iter_next (ptr); } g_hash_table_destroy (old_positions); return order; } /** * gtk_list_store_swap: * @store: A #GtkListStore. * @a: A #GtkTreeIter. * @b: Another #GtkTreeIter. * * Swaps @a and @b in @store. Note that this function only works with * unsorted stores. **/ void gtk_list_store_swap (GtkListStore *store, GtkTreeIter *a, GtkTreeIter *b) { GtkListStorePrivate *priv; GHashTable *old_positions; int *order; GtkTreePath *path; g_return_if_fail (GTK_IS_LIST_STORE (store)); g_return_if_fail (!GTK_LIST_STORE_IS_SORTED (store)); g_return_if_fail (iter_is_valid (a, store)); g_return_if_fail (iter_is_valid (b, store)); priv = store->priv; if (a->user_data == b->user_data) return; old_positions = save_positions (priv->seq); g_sequence_swap (a->user_data, b->user_data); order = generate_order (priv->seq, old_positions); path = gtk_tree_path_new (); gtk_tree_model_rows_reordered (GTK_TREE_MODEL (store), path, NULL, order); gtk_tree_path_free (path); g_free (order); } static void gtk_list_store_move_to (GtkListStore *store, GtkTreeIter *iter, int new_pos) { GtkListStorePrivate *priv = store->priv; GHashTable *old_positions; GtkTreePath *path; int *order; old_positions = save_positions (priv->seq); g_sequence_move (iter->user_data, g_sequence_get_iter_at_pos (priv->seq, new_pos)); order = generate_order (priv->seq, old_positions); path = gtk_tree_path_new (); gtk_tree_model_rows_reordered (GTK_TREE_MODEL (store), path, NULL, order); gtk_tree_path_free (path); g_free (order); } /** * gtk_list_store_move_before: * @store: A #GtkListStore. * @iter: A #GtkTreeIter. * @position: (allow-none): A #GtkTreeIter, or %NULL. * * Moves @iter in @store to the position before @position. Note that this * function only works with unsorted stores. If @position is %NULL, @iter * will be moved to the end of the list. **/ void gtk_list_store_move_before (GtkListStore *store, GtkTreeIter *iter, GtkTreeIter *position) { int pos; g_return_if_fail (GTK_IS_LIST_STORE (store)); g_return_if_fail (!GTK_LIST_STORE_IS_SORTED (store)); g_return_if_fail (iter_is_valid (iter, store)); if (position) g_return_if_fail (iter_is_valid (position, store)); if (position) pos = g_sequence_iter_get_position (position->user_data); else pos = -1; gtk_list_store_move_to (store, iter, pos); } /** * gtk_list_store_move_after: * @store: A #GtkListStore. * @iter: A #GtkTreeIter. * @position: (allow-none): A #GtkTreeIter or %NULL. * * Moves @iter in @store to the position after @position. Note that this * function only works with unsorted stores. If @position is %NULL, @iter * will be moved to the start of the list. **/ void gtk_list_store_move_after (GtkListStore *store, GtkTreeIter *iter, GtkTreeIter *position) { int pos; g_return_if_fail (GTK_IS_LIST_STORE (store)); g_return_if_fail (!GTK_LIST_STORE_IS_SORTED (store)); g_return_if_fail (iter_is_valid (iter, store)); if (position) g_return_if_fail (iter_is_valid (position, store)); if (position) pos = g_sequence_iter_get_position (position->user_data) + 1; else pos = 0; gtk_list_store_move_to (store, iter, pos); } /* Sorting */ static int gtk_list_store_compare_func (GSequenceIter *a, GSequenceIter *b, gpointer user_data) { GtkListStore *list_store = user_data; GtkListStorePrivate *priv = list_store->priv; GtkTreeIter iter_a; GtkTreeIter iter_b; int retval; GtkTreeIterCompareFunc func; gpointer data; if (priv->sort_column_id != -1) { GtkTreeDataSortHeader *header; header = _gtk_tree_data_list_get_header (priv->sort_list, priv->sort_column_id); g_return_val_if_fail (header != NULL, 0); g_return_val_if_fail (header->func != NULL, 0); func = header->func; data = header->data; } else { g_return_val_if_fail (priv->default_sort_func != NULL, 0); func = priv->default_sort_func; data = priv->default_sort_data; } iter_a.stamp = priv->stamp; iter_a.user_data = (gpointer)a; iter_b.stamp = priv->stamp; iter_b.user_data = (gpointer)b; g_assert (iter_is_valid (&iter_a, list_store)); g_assert (iter_is_valid (&iter_b, list_store)); retval = (* func) (GTK_TREE_MODEL (list_store), &iter_a, &iter_b, data); if (priv->order == GTK_SORT_DESCENDING) { if (retval > 0) retval = -1; else if (retval < 0) retval = 1; } return retval; } static void gtk_list_store_sort (GtkListStore *list_store) { GtkListStorePrivate *priv = list_store->priv; int *new_order; GtkTreePath *path; GHashTable *old_positions; if (!GTK_LIST_STORE_IS_SORTED (list_store) || g_sequence_get_length (priv->seq) <= 1) return; old_positions = save_positions (priv->seq); g_sequence_sort_iter (priv->seq, gtk_list_store_compare_func, list_store); /* Let the world know about our new order */ new_order = generate_order (priv->seq, old_positions); path = gtk_tree_path_new (); gtk_tree_model_rows_reordered (GTK_TREE_MODEL (list_store), path, NULL, new_order); gtk_tree_path_free (path); g_free (new_order); } static gboolean iter_is_sorted (GtkListStore *list_store, GtkTreeIter *iter) { GSequenceIter *cmp; if (!g_sequence_iter_is_begin (iter->user_data)) { cmp = g_sequence_iter_prev (iter->user_data); if (gtk_list_store_compare_func (cmp, iter->user_data, list_store) > 0) return FALSE; } cmp = g_sequence_iter_next (iter->user_data); if (!g_sequence_iter_is_end (cmp)) { if (gtk_list_store_compare_func (iter->user_data, cmp, list_store) > 0) return FALSE; } return TRUE; } static void gtk_list_store_sort_iter_changed (GtkListStore *list_store, GtkTreeIter *iter, int column) { GtkListStorePrivate *priv = list_store->priv; GtkTreePath *path; path = gtk_list_store_get_path (GTK_TREE_MODEL (list_store), iter); gtk_tree_model_row_changed (GTK_TREE_MODEL (list_store), path, iter); gtk_tree_path_free (path); if (!iter_is_sorted (list_store, iter)) { GHashTable *old_positions; int *order; old_positions = save_positions (priv->seq); g_sequence_sort_changed_iter (iter->user_data, gtk_list_store_compare_func, list_store); order = generate_order (priv->seq, old_positions); path = gtk_tree_path_new (); gtk_tree_model_rows_reordered (GTK_TREE_MODEL (list_store), path, NULL, order); gtk_tree_path_free (path); g_free (order); } } static gboolean gtk_list_store_get_sort_column_id (GtkTreeSortable *sortable, int *sort_column_id, GtkSortType *order) { GtkListStore *list_store = GTK_LIST_STORE (sortable); GtkListStorePrivate *priv = list_store->priv; if (sort_column_id) * sort_column_id = priv->sort_column_id; if (order) * order = priv->order; if (priv->sort_column_id == GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID || priv->sort_column_id == GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID) return FALSE; return TRUE; } static void gtk_list_store_set_sort_column_id (GtkTreeSortable *sortable, int sort_column_id, GtkSortType order) { GtkListStore *list_store = GTK_LIST_STORE (sortable); GtkListStorePrivate *priv = list_store->priv; if ((priv->sort_column_id == sort_column_id) && (priv->order == order)) return; if (sort_column_id != GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID) { if (sort_column_id != GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID) { GtkTreeDataSortHeader *header = NULL; header = _gtk_tree_data_list_get_header (priv->sort_list, sort_column_id); /* We want to make sure that we have a function */ g_return_if_fail (header != NULL); g_return_if_fail (header->func != NULL); } else { g_return_if_fail (priv->default_sort_func != NULL); } } priv->sort_column_id = sort_column_id; priv->order = order; gtk_tree_sortable_sort_column_changed (sortable); gtk_list_store_sort (list_store); } static void gtk_list_store_set_sort_func (GtkTreeSortable *sortable, int sort_column_id, GtkTreeIterCompareFunc func, gpointer data, GDestroyNotify destroy) { GtkListStore *list_store = GTK_LIST_STORE (sortable); GtkListStorePrivate *priv = list_store->priv; priv->sort_list = _gtk_tree_data_list_set_header (priv->sort_list, sort_column_id, func, data, destroy); if (priv->sort_column_id == sort_column_id) gtk_list_store_sort (list_store); } static void gtk_list_store_set_default_sort_func (GtkTreeSortable *sortable, GtkTreeIterCompareFunc func, gpointer data, GDestroyNotify destroy) { GtkListStore *list_store = GTK_LIST_STORE (sortable); GtkListStorePrivate *priv = list_store->priv; if (priv->default_sort_destroy) { GDestroyNotify d = priv->default_sort_destroy; priv->default_sort_destroy = NULL; d (priv->default_sort_data); } priv->default_sort_func = func; priv->default_sort_data = data; priv->default_sort_destroy = destroy; if (priv->sort_column_id == GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID) gtk_list_store_sort (list_store); } static gboolean gtk_list_store_has_default_sort_func (GtkTreeSortable *sortable) { GtkListStore *list_store = GTK_LIST_STORE (sortable); GtkListStorePrivate *priv = list_store->priv; return (priv->default_sort_func != NULL); } /** * gtk_list_store_insert_with_values: * @list_store: A #GtkListStore * @iter: (out) (optional): An unset #GtkTreeIter to set to the new row * @position: position to insert the new row, or -1 to append after existing * rows * @...: pairs of column number and value, terminated with -1 * * Creates a new row at @position. @iter will be changed to point to this new * row. If @position is -1, or larger than the number of rows in the list, then * the new row will be appended to the list. The row will be filled with the * values given to this function. * * Calling * `gtk_list_store_insert_with_values (list_store, iter, position...)` * has the same effect as calling: * * |[<!-- language="C" --> * static void * insert_value (GtkListStore *list_store, * GtkTreeIter *iter, * int position) * { * gtk_list_store_insert (list_store, iter, position); * gtk_list_store_set (list_store, * iter * // ... * ); * } * ]| * * with the difference that the former will only emit #GtkTreeModel::row-inserted * once, while the latter will emit #GtkTreeModel::row-inserted, * #GtkTreeModel::row-changed and, if the list store is sorted, * #GtkTreeModel::rows-reordered for every inserted value. * * Since emitting the #GtkTreeModel::rows-reordered signal repeatedly can * affect the performance of the program, gtk_list_store_insert_with_values() * should generally be preferred when inserting rows in a sorted list store. */ void gtk_list_store_insert_with_values (GtkListStore *list_store, GtkTreeIter *iter, int position, ...) { GtkListStorePrivate *priv; GtkTreePath *path; GSequence *seq; GSequenceIter *ptr; GtkTreeIter tmp_iter; int length; gboolean changed = FALSE; gboolean maybe_need_sort = FALSE; va_list var_args; /* FIXME: refactor to reduce overlap with gtk_list_store_set() */ g_return_if_fail (GTK_IS_LIST_STORE (list_store)); priv = list_store->priv; if (!iter) iter = &tmp_iter; priv->columns_dirty = TRUE; seq = priv->seq; length = g_sequence_get_length (seq); if (position > length || position < 0) position = length; ptr = g_sequence_get_iter_at_pos (seq, position); ptr = g_sequence_insert_before (ptr, NULL); iter->stamp = priv->stamp; iter->user_data = ptr; g_assert (iter_is_valid (iter, list_store)); priv->length++; va_start (var_args, position); gtk_list_store_set_valist_internal (list_store, iter, &changed, &maybe_need_sort, var_args); va_end (var_args); /* Don't emit rows_reordered here */ if (maybe_need_sort && GTK_LIST_STORE_IS_SORTED (list_store)) g_sequence_sort_changed_iter (iter->user_data, gtk_list_store_compare_func, list_store); /* Just emit row_inserted */ path = gtk_list_store_get_path (GTK_TREE_MODEL (list_store), iter); gtk_tree_model_row_inserted (GTK_TREE_MODEL (list_store), path, iter); gtk_tree_path_free (path); } /** * gtk_list_store_insert_with_valuesv: (rename-to gtk_list_store_insert_with_values) * @list_store: A #GtkListStore * @iter: (out) (optional): An unset #GtkTreeIter to set to the new row * @position: position to insert the new row, or -1 for last * @columns: (array length=n_values): an array of column numbers * @values: (array length=n_values): an array of GValues * @n_values: the length of the @columns and @values arrays * * A variant of gtk_list_store_insert_with_values() which * takes the columns and values as two arrays, instead of * varargs. * * This function is mainly intended for language-bindings. */ void gtk_list_store_insert_with_valuesv (GtkListStore *list_store, GtkTreeIter *iter, int position, int *columns, GValue *values, int n_values) { GtkListStorePrivate *priv; GtkTreePath *path; GSequence *seq; GSequenceIter *ptr; GtkTreeIter tmp_iter; int length; gboolean changed = FALSE; gboolean maybe_need_sort = FALSE; /* FIXME refactor to reduce overlap with * gtk_list_store_insert_with_values() */ g_return_if_fail (GTK_IS_LIST_STORE (list_store)); priv = list_store->priv; if (!iter) iter = &tmp_iter; priv->columns_dirty = TRUE; seq = priv->seq; length = g_sequence_get_length (seq); if (position > length || position < 0) position = length; ptr = g_sequence_get_iter_at_pos (seq, position); ptr = g_sequence_insert_before (ptr, NULL); iter->stamp = priv->stamp; iter->user_data = ptr; g_assert (iter_is_valid (iter, list_store)); priv->length++; gtk_list_store_set_vector_internal (list_store, iter, &changed, &maybe_need_sort, columns, values, n_values); /* Don't emit rows_reordered here */ if (maybe_need_sort && GTK_LIST_STORE_IS_SORTED (list_store)) g_sequence_sort_changed_iter (iter->user_data, gtk_list_store_compare_func, list_store); /* Just emit row_inserted */ path = gtk_list_store_get_path (GTK_TREE_MODEL (list_store), iter); gtk_tree_model_row_inserted (GTK_TREE_MODEL (list_store), path, iter); gtk_tree_path_free (path); } /* GtkBuildable custom tag implementation * * <columns> * <column type="..."/> * <column type="..."/> * </columns> */ typedef struct { gboolean translatable; char *context; int id; } ColInfo; typedef struct { GtkBuilder *builder; GObject *object; GSList *column_type_names; GType *column_types; GValue *values; int *colids; ColInfo **columns; int last_row; int n_columns; int row_column; gboolean is_data; const char *domain; } SubParserData; static void list_store_start_element (GtkBuildableParseContext *context, const char *element_name, const char **names, const char **values, gpointer user_data, GError **error) { SubParserData *data = (SubParserData*)user_data; if (strcmp (element_name, "col") == 0) { int id = -1; const char *id_str; const char *msg_context = NULL; gboolean translatable = FALSE; ColInfo *info; GValue val = G_VALUE_INIT; if (!_gtk_builder_check_parent (data->builder, context, "row", error)) return; if (data->row_column >= data->n_columns) { g_set_error (error, GTK_BUILDER_ERROR, GTK_BUILDER_ERROR_INVALID_VALUE, "Too many columns, maximum is %d", data->n_columns - 1); _gtk_builder_prefix_error (data->builder, context, error); return; } if (!g_markup_collect_attributes (element_name, names, values, error, G_MARKUP_COLLECT_STRING, "id", &id_str, G_MARKUP_COLLECT_BOOLEAN|G_MARKUP_COLLECT_OPTIONAL, "translatable", &translatable, G_MARKUP_COLLECT_STRING|G_MARKUP_COLLECT_OPTIONAL, "comments", NULL, G_MARKUP_COLLECT_STRING|G_MARKUP_COLLECT_OPTIONAL, "context", &msg_context, G_MARKUP_COLLECT_INVALID)) { _gtk_builder_prefix_error (data->builder, context, error); return; } if (!gtk_builder_value_from_string_type (data->builder, G_TYPE_INT, id_str, &val, error)) { _gtk_builder_prefix_error (data->builder, context, error); return; } id = g_value_get_int (&val); if (id < 0 || id >= data->n_columns) { g_set_error (error, GTK_BUILDER_ERROR, GTK_BUILDER_ERROR_INVALID_VALUE, "id value %d out of range", id); _gtk_builder_prefix_error (data->builder, context, error); return; } info = g_slice_new0 (ColInfo); info->translatable = translatable; info->context = g_strdup (msg_context); info->id = id; data->colids[data->row_column] = id; data->columns[data->row_column] = info; data->row_column++; data->is_data = TRUE; } else if (strcmp (element_name, "row") == 0) { if (!_gtk_builder_check_parent (data->builder, context, "data", error)) return; if (!g_markup_collect_attributes (element_name, names, values, error, G_MARKUP_COLLECT_INVALID, NULL, NULL, G_MARKUP_COLLECT_INVALID)) _gtk_builder_prefix_error (data->builder, context, error); } else if (strcmp (element_name, "columns") == 0 || strcmp (element_name, "data") == 0) { if (!_gtk_builder_check_parent (data->builder, context, "object", error)) return; if (!g_markup_collect_attributes (element_name, names, values, error, G_MARKUP_COLLECT_INVALID, NULL, NULL, G_MARKUP_COLLECT_INVALID)) _gtk_builder_prefix_error (data->builder, context, error); } else if (strcmp (element_name, "column") == 0) { const char *type; if (!_gtk_builder_check_parent (data->builder, context, "columns", error)) return; if (!g_markup_collect_attributes (element_name, names, values, error, G_MARKUP_COLLECT_STRING, "type", &type, G_MARKUP_COLLECT_INVALID)) { _gtk_builder_prefix_error (data->builder, context, error); return; } data->column_type_names = g_slist_prepend (data->column_type_names, g_strdup (type)); } else { _gtk_builder_error_unhandled_tag (data->builder, context, "GtkListStore", element_name, error); } } static void list_store_end_element (GtkBuildableParseContext *context, const char *element_name, gpointer user_data, GError **error) { SubParserData *data = (SubParserData*)user_data; g_assert (data->builder); if (strcmp (element_name, "row") == 0) { GtkTreeIter iter; int i; gtk_list_store_insert_with_valuesv (GTK_LIST_STORE (data->object), &iter, data->last_row, data->colids, data->values, data->row_column); for (i = 0; i < data->row_column; i++) { ColInfo *info = data->columns[i]; g_free (info->context); g_slice_free (ColInfo, info); data->columns[i] = NULL; g_value_unset (&data->values[i]); } g_free (data->values); data->values = g_new0 (GValue, data->n_columns); data->last_row++; data->row_column = 0; } else if (strcmp (element_name, "columns") == 0) { GType *column_types; GSList *l; int i; GType type; data->column_type_names = g_slist_reverse (data->column_type_names); column_types = g_new0 (GType, g_slist_length (data->column_type_names)); for (l = data->column_type_names, i = 0; l; l = l->next, i++) { type = gtk_builder_get_type_from_name (data->builder, l->data); if (type == G_TYPE_INVALID) { g_warning ("Unknown type %s specified in treemodel %s", (const char *)l->data, gtk_buildable_get_buildable_id (GTK_BUILDABLE (data->object))); continue; } column_types[i] = type; g_free (l->data); } gtk_list_store_set_column_types (GTK_LIST_STORE (data->object), i, column_types); g_free (column_types); } else if (strcmp (element_name, "col") == 0) { data->is_data = FALSE; } } static void list_store_text (GtkBuildableParseContext *context, const char *text, gsize text_len, gpointer user_data, GError **error) { SubParserData *data = (SubParserData*)user_data; int i; char *string; ColInfo *info; if (!data->is_data) return; i = data->row_column - 1; info = data->columns[i]; string = g_strndup (text, text_len); if (info->translatable && text_len) { char *translated; /* FIXME: This will not use the domain set in the .ui file, * since the parser is not telling the builder about the domain. * However, it will work for gtk_builder_set_translation_domain() calls. */ translated = g_strdup (_gtk_builder_parser_translate (data->domain, info->context, string)); g_free (string); string = translated; } if (!gtk_builder_value_from_string_type (data->builder, data->column_types[info->id], string, &data->values[i], error)) { _gtk_builder_prefix_error (data->builder, context, error); } g_free (string); } static const GtkBuildableParser list_store_parser = { list_store_start_element, list_store_end_element, list_store_text }; static gboolean gtk_list_store_buildable_custom_tag_start (GtkBuildable *buildable, GtkBuilder *builder, GObject *child, const char *tagname, GtkBuildableParser *parser, gpointer *parser_data) { SubParserData *data; if (child) return FALSE; if (strcmp (tagname, "columns") == 0) { data = g_slice_new0 (SubParserData); data->builder = builder; data->object = G_OBJECT (buildable); data->column_type_names = NULL; *parser = list_store_parser; *parser_data = data; return TRUE; } else if (strcmp (tagname, "data") == 0) { int n_columns = gtk_list_store_get_n_columns (GTK_TREE_MODEL (buildable)); if (n_columns == 0) g_error ("Cannot append data to an empty model"); data = g_slice_new0 (SubParserData); data->builder = builder; data->object = G_OBJECT (buildable); data->values = g_new0 (GValue, n_columns); data->colids = g_new0 (int, n_columns); data->columns = g_new0 (ColInfo*, n_columns); data->column_types = GTK_LIST_STORE (buildable)->priv->column_headers; data->n_columns = n_columns; data->last_row = 0; data->domain = gtk_builder_get_translation_domain (builder); *parser = list_store_parser; *parser_data = data; return TRUE; } return FALSE; } static void gtk_list_store_buildable_custom_tag_end (GtkBuildable *buildable, GtkBuilder *builder, GObject *child, const char *tagname, gpointer parser_data) { SubParserData *data = (SubParserData*)parser_data; if (strcmp (tagname, "columns") == 0) { g_slist_free (data->column_type_names); g_slice_free (SubParserData, data); } else if (strcmp (tagname, "data") == 0) { int i; for (i = 0; i < data->n_columns; i++) { ColInfo *info = data->columns[i]; if (info) { g_free (info->context); g_slice_free (ColInfo, info); } } g_free (data->colids); g_free (data->columns); g_free (data->values); g_slice_free (SubParserData, data); } }
030c1eac9df6902c3091cbb8079b0a92ec56b2b5
693bd39eb66eade67997bc608fe84e76e66eeec2
/mpp/hal/rkdec/avs2d/hal_avs2d_vdpu382.h
0cddfc2a7bfcba06b8d60f11771bf269beac3bb7
[]
permissive
HermanChen/mpp
6a1751777b120b764f86e0f34975231054a3c262
0af9b5becc76c4685831214808e124e65543297b
refs/heads/develop
2023-08-17T07:17:49.489974
2023-07-31T08:26:14
2023-08-11T07:38:17
71,088,248
139
79
Apache-2.0
2023-03-08T09:44:01
2016-10-17T01:13:37
C
UTF-8
C
false
false
1,283
h
hal_avs2d_vdpu382.h
/* * Copyright 2022 Rockchip Electronics Co. LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __HAL_AVS2D_VDPU382_H__ #define __HAL_AVS2D_VDPU382_H__ #include "mpp_device.h" #include "parser_api.h" #include "hal_avs2d_api.h" #include "hal_avs2d_global.h" #include "avs2d_syntax.h" #include "vdpu382.h" #define AVS2D_REGISTERS (278) #ifdef __cplusplus extern "C" { #endif MPP_RET hal_avs2d_vdpu382_init (void *hal, MppHalCfg *cfg); MPP_RET hal_avs2d_vdpu382_deinit (void *hal); MPP_RET hal_avs2d_vdpu382_gen_regs(void *hal, HalTaskInfo *task); MPP_RET hal_avs2d_vdpu382_start (void *hal, HalTaskInfo *task); MPP_RET hal_avs2d_vdpu382_wait (void *hal, HalTaskInfo *task); #ifdef __cplusplus } #endif #endif /*__HAL_AVS2D_VDPU382_H__*/
a0c7ae0780337f1438632ecbc571ebdc2d948314
01bcef56ade123623725ca78d233ac8653a91ece
/engine/broadcast.h
edcaf903699fb172848966b75f343a236b77fda4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
SwagSoftware/Kisak-Strike
1085ba3c6003e622dac5ebc0c9424cb16ef58467
4c2fdc31432b4f5b911546c8c0d499a9cff68a85
refs/heads/master
2023-09-01T02:06:59.187775
2022-09-05T00:51:46
2022-09-05T00:51:46
266,676,410
921
123
null
2022-10-01T16:26:41
2020-05-25T03:41:35
C++
WINDOWS-1252
C
false
false
758
h
broadcast.h
//========= Copyright © Valve Corporation, All rights reserved. ============// #ifndef ENGINE_BROADCAST_HDR #define ENGINE_BROADCAST_HDR enum BroadcastChunkEnum { BROADCAST_FULLFRAME, // a single keyframe message BROADCAST_SIGNON, BROADCAST_NETWORK_DATA_TABLES, BROADCAST_STRING_TABLES, BROADCAST_FRAMES, // a number of incremental frames (384 frames for a 3-second pack on a 128-tick server) BROADCAST_DELTAFRAME, BROADCAST_CONSOLE_COMMAND, BROADCAST_STOP, BROADCAST_TOC, BROADCAST_TOC_SIZE }; struct BroadcastChunk_t { uint32 nChunkId; uint32 nChunkSize; // size in bytes of the chunk that follows; 0 means it's empty }; struct BroadcastTocKeyframe_t { uint32 nKeyframeTick; uint32 nBroadcastIndex; }; #endif // ENGINE_BROADCAST_HDR
819b09c4898269e827694081d9c356ce13622252
ecce427678ecff2a93a47f3b1b664202c7d27617
/levels/jrb/areas/2/collision.inc.c
31d002a0b99ed7a0c741a7b0c4adc2e14b682b55
[]
no_license
sm64pc/sm64ex
ecf37f31b3f7426c4874254660d856030d789714
54cd27ccee45a2403b45f07a00d6043c51149969
refs/heads/nightly
2023-08-11T12:14:34.424168
2023-07-01T11:45:50
2023-07-01T11:45:50
262,091,731
795
238
null
2023-07-01T11:45:51
2020-05-07T15:43:27
C
UTF-8
C
false
false
17,005
c
collision.inc.c
// 0x070105B8 - 0x07011370 const Collision jrb_seg7_area_2_collision[] = { COL_INIT(), COL_VERTEX_INIT(0xC6), COL_VERTEX(-435, -74, 621), COL_VERTEX(-72, -74, 904), COL_VERTEX(-82, -74, 736), COL_VERTEX(-232, -74, 576), COL_VERTEX(-479, -74, 721), COL_VERTEX(259, -202, 610), COL_VERTEX(628, -202, 616), COL_VERTEX(442, -202, 561), COL_VERTEX(235, -202, 827), COL_VERTEX(495, -202, 944), COL_VERTEX(758, -202, 808), COL_VERTEX(886, -35, 839), COL_VERTEX(847, -35, 1084), COL_VERTEX(906, -35, 1054), COL_VERTEX(979, -35, 846), COL_VERTEX(801, -35, 945), COL_VERTEX(128, -4, 1013), COL_VERTEX(168, 322, 1458), COL_VERTEX(523, 95, 1273), COL_VERTEX(710, 430, 1647), COL_VERTEX(275, 558, 1980), COL_VERTEX(-407, 445, 1450), COL_VERTEX(-417, 694, 1769), COL_VERTEX(414, 943, 2667), COL_VERTEX(-167, 1258, 2584), COL_VERTEX(-472, 287, 1330), COL_VERTEX(545, 11, 1249), COL_VERTEX(-475, -351, 184), COL_VERTEX(-705, -289, 184), COL_VERTEX(784, 583, 2313), COL_VERTEX(70, -4, 1085), COL_VERTEX(313, -4, 1193), COL_VERTEX(290, -4, 1038), COL_VERTEX(239, -4, 980), COL_VERTEX(418, 322, 1606), COL_VERTEX(312, 322, 1474), COL_VERTEX(477, 322, 1814), COL_VERTEX(33, 322, 1615), COL_VERTEX(841, 95, 1342), COL_VERTEX(761, 95, 1210), COL_VERTEX(575, 95, 1479), COL_VERTEX(496, 95, 1444), COL_VERTEX(628, 95, 1151), COL_VERTEX(696, 430, 2063), COL_VERTEX(1031, 430, 1890), COL_VERTEX(661, 430, 1790), COL_VERTEX(1087, 430, 1732), COL_VERTEX(961, 430, 1625), COL_VERTEX(513, 558, 2044), COL_VERTEX(428, 558, 1927), COL_VERTEX(517, 558, 2227), COL_VERTEX(193, 558, 2081), COL_VERTEX(-102, 445, 1567), COL_VERTEX(-189, 445, 1466), COL_VERTEX(-98, 445, 1762), COL_VERTEX(-429, 445, 1614), COL_VERTEX(-480, 445, 1541), COL_VERTEX(-363, 694, 2060), COL_VERTEX(-27, 694, 2210), COL_VERTEX(-500, 694, 1865), COL_VERTEX(-36, 694, 1879), COL_VERTEX(-248, 694, 1740), COL_VERTEX(1027, 943, 2507), COL_VERTEX(751, 943, 2357), COL_VERTEX(1128, 941, 2827), COL_VERTEX(802, 943, 3000), COL_VERTEX(401, 943, 2819), COL_VERTEX(-350, 1258, 2875), COL_VERTEX(-211, 1258, 3072), COL_VERTEX(126, 1258, 3224), COL_VERTEX(388, 1258, 3273), COL_VERTEX(362, 1258, 2944), COL_VERTEX(193, 1258, 2628), COL_VERTEX(523, 18, 1273), COL_VERTEX(-546, 303, 1249), COL_VERTEX(514, 22, 1330), COL_VERTEX(-463, -351, 265), COL_VERTEX(-631, -306, 265), COL_VERTEX(-387, 897, 2313), COL_VERTEX(-313, 880, 2394), COL_VERTEX(712, 605, 2394), COL_VERTEX(-54, 1673, 3483), COL_VERTEX(-189, 1343, 3224), COL_VERTEX(885, 1421, 3483), COL_VERTEX(384, 1189, 3224), COL_VERTEX(836, 1068, 3224), COL_VERTEX(1217, 1125, 3135), COL_VERTEX(362, 1028, 2944), COL_VERTEX(593, -351, 606), COL_VERTEX(628, -336, 616), COL_VERTEX(822, -351, 488), COL_VERTEX(876, -148, 851), COL_VERTEX(801, -120, 945), COL_VERTEX(628, -59, 1151), COL_VERTEX(239, -112, 980), COL_VERTEX(290, -91, 1038), COL_VERTEX(-490, 217, 1205), COL_VERTEX(761, 6, 1210), COL_VERTEX(710, 218, 1647), COL_VERTEX(961, 274, 1625), COL_VERTEX(661, 279, 1790), COL_VERTEX(693, 536, 2270), COL_VERTEX(418, 213, 1606), COL_VERTEX(513, 450, 2044), COL_VERTEX(1027, 748, 2507), COL_VERTEX(193, 884, 2628), COL_VERTEX(275, 475, 1980), COL_VERTEX(-36, 499, 1879), COL_VERTEX(168, 192, 1458), COL_VERTEX(-189, 292, 1466), COL_VERTEX(312, 163, 1474), COL_VERTEX(-82, -171, 736), COL_VERTEX(-232, -227, 576), COL_VERTEX(534, -56, 1205), COL_VERTEX(568, -39, 1221), COL_VERTEX(996, 299, 1655), COL_VERTEX(-331, 811, 2270), COL_VERTEX(751, 597, 2358), COL_VERTEX(428, 402, 1927), COL_VERTEX(414, 848, 2667), COL_VERTEX(-167, 955, 2584), COL_VERTEX(-262, 1070, 2735), COL_VERTEX(-248, 472, 1740), COL_VERTEX(-406, 531, 1767), COL_VERTEX(-102, 330, 1567), COL_VERTEX(-407, 341, 1450), COL_VERTEX(-446, 381, 1499), COL_VERTEX(259, -338, 610), COL_VERTEX(128, -62, 1013), COL_VERTEX(288, -351, 602), COL_VERTEX(-435, -146, 621), COL_VERTEX(442, -351, 561), COL_VERTEX(1110, -351, -333), COL_VERTEX(886, -142, 839), COL_VERTEX(-1009, -351, -332), COL_VERTEX(-864, 191, -2190), COL_VERTEX(-1071, -351, -1741), COL_VERTEX(-560, -42, -2445), COL_VERTEX(759, -351, -2188), COL_VERTEX(822, -351, -2139), COL_VERTEX(1188, -351, -1513), COL_VERTEX(886, -351, -2029), COL_VERTEX(1263, -72, -1679), COL_VERTEX(1188, -351, -556), COL_VERTEX(-665, -351, 154), COL_VERTEX(1695, 1539, 2833), COL_VERTEX(-36, 2599, 3522), COL_VERTEX(-491, 1583, 3135), COL_VERTEX(1653, 1382, -1187), COL_VERTEX(-739, 2023, -1187), COL_VERTEX(1188, -351, -2194), COL_VERTEX(-950, 1237, -860), COL_VERTEX(-993, 1078, -765), COL_VERTEX(482, 2801, 3605), COL_VERTEX(226, 2211, 3699), COL_VERTEX(1180, 2762, 3522), COL_VERTEX(1478, 2782, 3194), COL_VERTEX(1331, 2232, 3522), COL_VERTEX(359, 2982, 3522), COL_VERTEX(415, 3189, 3398), COL_VERTEX(111, 3148, 3194), COL_VERTEX(1162, -351, -2190), COL_VERTEX(-515, 2858, 2428), COL_VERTEX(1876, 2217, 2428), COL_VERTEX(1235, 2969, 3398), COL_VERTEX(-1228, -351, -1152), COL_VERTEX(-697, 2180, 2833), COL_VERTEX(-1205, 283, -2190), COL_VERTEX(-262, -351, -2828), COL_VERTEX(464, -317, -2445), COL_VERTEX(455, -351, -2936), COL_VERTEX(-940, -93, -2701), COL_VERTEX(-703, 792, -3230), COL_VERTEX(-380, 629, -3358), COL_VERTEX(-968, 1168, -2719), COL_VERTEX(1005, 334, -3230), COL_VERTEX(645, 354, -3358), COL_VERTEX(822, -351, -2820), COL_VERTEX(1424, 527, -2719), COL_VERTEX(-417, 543, 1769), COL_VERTEX(-1009, -351, -1865), COL_VERTEX(-1311, -110, -1274), COL_VERTEX(-716, -351, -2182), COL_VERTEX(-643, -351, -2261), COL_VERTEX(455, -351, -2425), COL_VERTEX(-1054, -351, -502), COL_VERTEX(-1129, 568, -1679), COL_VERTEX(844, -266, -2190), COL_VERTEX(-617, -255, -2828), COL_VERTEX(910, 2028, 3699), COL_VERTEX(-934, 1297, -753), COL_VERTEX(1458, 656, -753), COL_VERTEX(1415, 496, -658), COL_VERTEX(-976, 1137, -658), COL_VERTEX(1188, -351, -2178), COL_VERTEX(1442, 596, -860), COL_VERTEX(1399, 436, -765), COL_VERTEX(983, 2666, 3605), COL_TRI_INIT(SURFACE_DEFAULT, 236), COL_TRI(10, 89, 6), COL_TRI(6, 88, 7), COL_TRI(6, 89, 88), COL_TRI(88, 131, 7), COL_TRI(131, 88, 90), COL_TRI(7, 129, 5), COL_TRI(7, 131, 129), COL_TRI(76, 129, 131), COL_TRI(131, 90, 132), COL_TRI(76, 131, 132), COL_TRI(129, 127, 5), COL_TRI(5, 127, 8), COL_TRI(16, 128, 30), COL_TRI(0, 130, 4), COL_TRI(3, 130, 0), COL_TRI(3, 112, 130), COL_TRI(2, 112, 3), COL_TRI(2, 111, 112), COL_TRI(1, 111, 2), COL_TRI(33, 128, 16), COL_TRI(33, 94, 128), COL_TRI(32, 94, 33), COL_TRI(32, 95, 94), COL_TRI(31, 95, 32), COL_TRI(11, 92, 15), COL_TRI(15, 92, 12), COL_TRI(14, 133, 11), COL_TRI(90, 91, 133), COL_TRI(132, 133, 14), COL_TRI(132, 90, 133), COL_TRI(11, 91, 92), COL_TRI(11, 133, 91), COL_TRI(38, 97, 39), COL_TRI(39, 93, 42), COL_TRI(39, 97, 93), COL_TRI(42, 93, 114), COL_TRI(42, 26, 73), COL_TRI(42, 114, 26), COL_TRI(73, 18, 42), COL_TRI(36, 102, 34), COL_TRI(34, 102, 110), COL_TRI(34, 110, 35), COL_TRI(35, 110, 108), COL_TRI(115, 99, 47), COL_TRI(14, 46, 132), COL_TRI(14, 115, 46), COL_TRI(14, 13, 115), COL_TRI(35, 108, 17), COL_TRI(17, 108, 37), COL_TRI(46, 115, 47), COL_TRI(132, 46, 86), COL_TRI(46, 44, 86), COL_TRI(47, 98, 19), COL_TRI(47, 99, 98), COL_TRI(19, 98, 100), COL_TRI(19, 100, 45), COL_TRI(45, 100, 43), COL_TRI(20, 106, 51), COL_TRI(49, 106, 20), COL_TRI(49, 118, 106), COL_TRI(56, 126, 74), COL_TRI(48, 118, 49), COL_TRI(48, 103, 118), COL_TRI(50, 103, 48), COL_TRI(21, 126, 56), COL_TRI(21, 125, 126), COL_TRI(53, 109, 21), COL_TRI(109, 125, 21), COL_TRI(126, 25, 74), COL_TRI(59, 56, 74), COL_TRI(55, 56, 59), COL_TRI(52, 109, 53), COL_TRI(52, 124, 109), COL_TRI(54, 124, 52), COL_TRI(22, 179, 59), COL_TRI(61, 123, 22), COL_TRI(123, 179, 22), COL_TRI(59, 179, 55), COL_TRI(55, 179, 123), COL_TRI(134, 67, 59), COL_TRI(74, 134, 59), COL_TRI(59, 67, 78), COL_TRI(59, 116, 57), COL_TRI(59, 78, 116), COL_TRI(61, 122, 123), COL_TRI(60, 107, 61), COL_TRI(107, 122, 61), COL_TRI(63, 117, 80), COL_TRI(58, 107, 60), COL_TRI(62, 104, 63), COL_TRI(64, 104, 62), COL_TRI(104, 117, 63), COL_TRI(63, 119, 23), COL_TRI(63, 80, 119), COL_TRI(29, 80, 117), COL_TRI(23, 119, 66), COL_TRI(71, 87, 105), COL_TRI(70, 84, 71), COL_TRI(84, 87, 71), COL_TRI(71, 105, 72), COL_TRI(135, 136, 180), COL_TRI(72, 105, 120), COL_TRI(72, 120, 24), COL_TRI(24, 120, 121), COL_TRI(24, 121, 67), COL_TRI(79, 78, 121), COL_TRI(67, 121, 78), COL_TRI(134, 147, 67), COL_TRI(68, 67, 147), COL_TRI(136, 182, 180), COL_TRI(136, 183, 182), COL_TRI(136, 138, 184), COL_TRI(136, 184, 183), COL_TRI(136, 141, 139), COL_TRI(137, 135, 182), COL_TRI(137, 182, 183), COL_TRI(135, 180, 182), COL_TRI(137, 183, 184), COL_TRI(137, 184, 169), COL_TRI(138, 187, 169), COL_TRI(138, 169, 184), COL_TRI(139, 187, 138), COL_TRI(136, 139, 138), COL_TRI(136, 143, 140), COL_TRI(136, 144, 27), COL_TRI(136, 27, 143), COL_TRI(140, 187, 141), COL_TRI(141, 187, 139), COL_TRI(136, 140, 141), COL_TRI(142, 140, 143), COL_TRI(142, 143, 145), COL_TRI(143, 27, 132), COL_TRI(144, 28, 27), COL_TRI(27, 76, 132), COL_TRI(140, 142, 187), COL_TRI(101, 78, 29), COL_TRI(136, 181, 165), COL_TRI(136, 134, 144), COL_TRI(134, 28, 144), COL_TRI(28, 134, 74), COL_TRI(136, 165, 134), COL_TRI(145, 132, 86), COL_TRI(83, 157, 86), COL_TRI(86, 157, 145), COL_TRI(147, 185, 166), COL_TRI(77, 28, 96), COL_TRI(28, 74, 96), COL_TRI(96, 114, 113), COL_TRI(96, 26, 114), COL_TRI(96, 74, 26), COL_TRI(101, 116, 78), COL_TRI(146, 147, 166), COL_TRI(147, 134, 185), COL_TRI(81, 82, 147), COL_TRI(68, 147, 82), COL_TRI(18, 73, 75), COL_TRI(18, 75, 41), COL_TRI(148, 190, 149), COL_TRI(148, 191, 190), COL_TRI(149, 174, 148), COL_TRI(150, 192, 148), COL_TRI(151, 190, 191), COL_TRI(149, 193, 167), COL_TRI(149, 167, 174), COL_TRI(151, 191, 195), COL_TRI(152, 151, 196), COL_TRI(151, 195, 196), COL_TRI(83, 189, 157), COL_TRI(81, 189, 83), COL_TRI(153, 155, 197), COL_TRI(153, 197, 189), COL_TRI(154, 153, 189), COL_TRI(155, 157, 189), COL_TRI(155, 189, 197), COL_TRI(81, 154, 189), COL_TRI(156, 157, 155), COL_TRI(157, 156, 163), COL_TRI(157, 163, 145), COL_TRI(145, 143, 132), COL_TRI(142, 145, 163), COL_TRI(153, 154, 146), COL_TRI(154, 81, 146), COL_TRI(146, 81, 147), COL_TRI(158, 153, 146), COL_TRI(159, 146, 160), COL_TRI(160, 146, 166), COL_TRI(159, 158, 146), COL_TRI(161, 187, 142), COL_TRI(162, 163, 160), COL_TRI(163, 156, 160), COL_TRI(153, 158, 159), COL_TRI(160, 166, 162), COL_TRI(167, 186, 135), COL_TRI(156, 164, 160), COL_TRI(156, 155, 164), COL_TRI(153, 164, 155), COL_TRI(153, 159, 164), COL_TRI(164, 159, 160), COL_TRI(165, 166, 185), COL_TRI(165, 181, 166), COL_TRI(166, 181, 186), COL_TRI(162, 166, 186), COL_TRI(135, 186, 181), COL_TRI(161, 142, 194), COL_TRI(135, 181, 136), COL_TRI(168, 169, 161), COL_TRI(168, 137, 169), COL_TRI(169, 187, 161), COL_TRI(170, 168, 161), COL_TRI(170, 161, 194), COL_TRI(170, 194, 150), COL_TRI(171, 167, 135), COL_TRI(137, 171, 135), COL_TRI(137, 188, 171), COL_TRI(168, 188, 137), COL_TRI(172, 188, 173), COL_TRI(173, 188, 168), COL_TRI(172, 171, 188), COL_TRI(174, 178, 148), COL_TRI(173, 168, 170), COL_TRI(174, 171, 172), COL_TRI(170, 150, 177), COL_TRI(150, 194, 192), COL_TRI(150, 148, 178), COL_TRI(175, 177, 178), COL_TRI(176, 177, 175), COL_TRI(177, 150, 178), COL_TRI(173, 170, 176), COL_TRI(176, 170, 177), COL_TRI(174, 167, 171), COL_TRI(163, 162, 196), COL_TRI(162, 152, 196), COL_TRI(178, 174, 172), COL_TRI(175, 178, 172), COL_TRI(176, 175, 172), COL_TRI(173, 176, 172), COL_TRI_INIT(SURFACE_SLIPPERY, 92), COL_TRI(70, 69, 81), COL_TRI(69, 82, 81), COL_TRI(68, 82, 69), COL_TRI(70, 81, 83), COL_TRI(84, 70, 83), COL_TRI(85, 84, 83), COL_TRI(83, 86, 85), COL_TRI(87, 84, 85), COL_TRI(65, 85, 64), COL_TRI(86, 64, 85), COL_TRI(87, 85, 65), COL_TRI(88, 89, 90), COL_TRI(95, 113, 9), COL_TRI(90, 89, 10), COL_TRI(91, 90, 10), COL_TRI(92, 10, 9), COL_TRI(91, 10, 92), COL_TRI(12, 92, 97), COL_TRI(93, 97, 92), COL_TRI(9, 93, 92), COL_TRI(9, 113, 93), COL_TRI(8, 94, 9), COL_TRI(94, 95, 9), COL_TRI(93, 113, 114), COL_TRI(31, 113, 95), COL_TRI(96, 113, 31), COL_TRI(97, 38, 12), COL_TRI(12, 38, 13), COL_TRI(38, 99, 13), COL_TRI(98, 99, 38), COL_TRI(40, 98, 38), COL_TRI(103, 50, 101), COL_TRI(99, 115, 13), COL_TRI(100, 98, 40), COL_TRI(101, 100, 40), COL_TRI(40, 36, 101), COL_TRI(102, 36, 40), COL_TRI(40, 41, 102), COL_TRI(100, 101, 43), COL_TRI(43, 101, 44), COL_TRI(101, 29, 44), COL_TRI(36, 103, 101), COL_TRI(79, 105, 119), COL_TRI(104, 44, 29), COL_TRI(64, 86, 44), COL_TRI(44, 104, 64), COL_TRI(29, 117, 104), COL_TRI(66, 87, 65), COL_TRI(105, 87, 66), COL_TRI(105, 66, 119), COL_TRI(79, 120, 105), COL_TRI(79, 119, 80), COL_TRI(79, 121, 120), COL_TRI(50, 51, 58), COL_TRI(106, 107, 51), COL_TRI(51, 107, 58), COL_TRI(107, 54, 122), COL_TRI(54, 107, 106), COL_TRI(57, 116, 58), COL_TRI(101, 50, 58), COL_TRI(58, 116, 101), COL_TRI(108, 110, 41), COL_TRI(55, 123, 122), COL_TRI(55, 122, 54), COL_TRI(106, 37, 54), COL_TRI(37, 124, 54), COL_TRI(37, 106, 118), COL_TRI(37, 118, 36), COL_TRI(108, 124, 37), COL_TRI(109, 124, 108), COL_TRI(36, 118, 103), COL_TRI(110, 102, 41), COL_TRI(111, 1, 94), COL_TRI(25, 108, 41), COL_TRI(25, 41, 75), COL_TRI(25, 109, 108), COL_TRI(25, 125, 109), COL_TRI(25, 126, 125), COL_TRI(111, 8, 127), COL_TRI(111, 94, 8), COL_TRI(1, 128, 94), COL_TRI(77, 4, 130), COL_TRI(31, 30, 96), COL_TRI(1, 96, 128), COL_TRI(96, 30, 128), COL_TRI(77, 96, 4), COL_TRI(4, 96, 1), COL_TRI(112, 111, 127), COL_TRI(76, 112, 127), COL_TRI(76, 127, 129), COL_TRI(76, 77, 112), COL_TRI(77, 130, 112), COL_TRI_INIT(SURFACE_NOT_SLIPPERY, 51), COL_TRI(11, 13, 14), COL_TRI(0, 1, 2), COL_TRI(0, 2, 3), COL_TRI(0, 4, 1), COL_TRI(5, 6, 7), COL_TRI(5, 8, 9), COL_TRI(5, 9, 10), COL_TRI(5, 10, 6), COL_TRI(11, 12, 13), COL_TRI(17, 37, 36), COL_TRI(11, 15, 12), COL_TRI(16, 30, 31), COL_TRI(16, 32, 33), COL_TRI(16, 31, 32), COL_TRI(17, 34, 35), COL_TRI(17, 36, 34), COL_TRI(20, 48, 49), COL_TRI(18, 38, 39), COL_TRI(18, 40, 38), COL_TRI(18, 41, 40), COL_TRI(18, 39, 42), COL_TRI(19, 43, 44), COL_TRI(19, 45, 43), COL_TRI(19, 44, 46), COL_TRI(19, 46, 47), COL_TRI(22, 58, 60), COL_TRI(20, 50, 48), COL_TRI(20, 51, 50), COL_TRI(21, 52, 53), COL_TRI(21, 54, 52), COL_TRI(21, 55, 54), COL_TRI(21, 56, 55), COL_TRI(22, 57, 58), COL_TRI(22, 59, 57), COL_TRI(24, 68, 69), COL_TRI(22, 60, 61), COL_TRI(23, 62, 63), COL_TRI(23, 64, 62), COL_TRI(23, 65, 64), COL_TRI(23, 66, 65), COL_TRI(24, 67, 68), COL_TRI(24, 69, 70), COL_TRI(24, 70, 71), COL_TRI(29, 78, 79), COL_TRI(24, 71, 72), COL_TRI(25, 73, 26), COL_TRI(26, 74, 25), COL_TRI(25, 75, 73), COL_TRI(27, 28, 76), COL_TRI(28, 77, 76), COL_TRI(29, 79, 80), COL_TRI_STOP(), COL_SPECIAL_INIT(1), SPECIAL_OBJECT_WITH_YAW(/*preset*/ special_null_start, /*pos*/ 866, 798, -1248, /*yaw*/ 128), // unused, probably an early way to set intial position COL_WATER_BOX_INIT(1), COL_WATER_BOX(0, -4095, -4095, 4096, 4096, 2765), COL_END(), };
6a453c4c67c1700c6f9eff2c526901c83ad98732
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sbin/nvmectl/bn.h
5bbda3b8d79e570c1b046c179402482e26fc791e
[]
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
5,556
h
bn.h
/* $NetBSD: bn.h,v 1.1 2017/02/13 11:16:46 nonaka Exp $ */ /*- * Copyright (c) 2012 Alistair Crooks <agc@NetBSD.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 ``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 FAUXBN_H_ #define FAUXBN_H_ 20100108 #include <sys/types.h> #include <inttypes.h> #include <stdio.h> #ifndef __BEGIN_DECLS # if defined(__cplusplus) # define __BEGIN_DECLS extern "C" { # define __END_DECLS } # else # define __BEGIN_DECLS # define __END_DECLS # endif #endif __BEGIN_DECLS /* should be 32bit on ILP32, 64bit on LP64 */ typedef unsigned long mp_digit; typedef uint64_t mp_word; /* multi-precision integer */ typedef struct mp_int { mp_digit *dp; /* array of digits */ int used; /* # of digits used */ int alloc; /* # of digits allocated */ int sign; /* non-zero if negative */ } mp_int; #define BIGNUM mp_int #define BN_ULONG mp_digit /* a "context" of mp integers - never really used */ typedef struct bn_ctx_t { size_t count; size_t arraysize; BIGNUM **v; } BN_CTX; #define MP_LT -1 #define MP_EQ 0 #define MP_GT 1 #define MP_ZPOS 0 #define MP_NEG 1 #define MP_OKAY 0 #define MP_MEM -2 #define MP_VAL -3 #define MP_RANGE MP_VAL /*********************************/ #define BN_is_negative(x) ((x)->sign == MP_NEG) #define BN_is_zero(a) (((a)->used == 0) ? 1 : 0) #define BN_is_odd(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 1)) ? 1 : 0) #define BN_is_even(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 0)) ? 1 : 0) BIGNUM *BN_new(void); BIGNUM *BN_dup(const BIGNUM */*a*/); int BN_copy(BIGNUM */*b*/, const BIGNUM */*a*/); void BN_init(BIGNUM */*a*/); void BN_free(BIGNUM */*a*/); void BN_clear(BIGNUM */*a*/); void BN_clear_free(BIGNUM */*a*/); int BN_cmp(BIGNUM */*a*/, BIGNUM */*b*/); BIGNUM *BN_bin2bn(const uint8_t */*buf*/, int /*size*/, BIGNUM */*bn*/); int BN_bn2bin(const BIGNUM */*a*/, unsigned char */*b*/); char *BN_bn2hex(const BIGNUM */*a*/); char *BN_bn2dec(const BIGNUM */*a*/); char *BN_bn2radix(const BIGNUM */*a*/, unsigned /*radix*/); int BN_hex2bn(BIGNUM **/*a*/, const char */*str*/); int BN_dec2bn(BIGNUM **/*a*/, const char */*str*/); int BN_radix2bn(BIGNUM **/*a*/, const char */*str*/, unsigned /*radix*/); int BN_print_fp(FILE */*fp*/, const BIGNUM */*a*/); int BN_add(BIGNUM */*r*/, const BIGNUM */*a*/, const BIGNUM */*b*/); int BN_sub(BIGNUM */*r*/, const BIGNUM */*a*/, const BIGNUM */*b*/); int BN_mul(BIGNUM */*r*/, const BIGNUM */*a*/, const BIGNUM */*b*/, BN_CTX */*ctx*/); int BN_div(BIGNUM */*q*/, BIGNUM */*r*/, const BIGNUM */*a*/, const BIGNUM */*b*/, BN_CTX */*ctx*/); void BN_swap(BIGNUM */*a*/, BIGNUM */*b*/); int BN_bitop(BIGNUM */*r*/, const BIGNUM */*a*/, char /*op*/, const BIGNUM */*b*/); int BN_lshift(BIGNUM */*r*/, const BIGNUM */*a*/, int /*n*/); int BN_lshift1(BIGNUM */*r*/, BIGNUM */*a*/); int BN_rshift(BIGNUM */*r*/, const BIGNUM */*a*/, int /*n*/); int BN_rshift1(BIGNUM */*r*/, BIGNUM */*a*/); int BN_set_word(BIGNUM */*a*/, BN_ULONG /*w*/); void BN_set_negative(BIGNUM */*a*/, int /*n*/); int BN_num_bytes(const BIGNUM */*a*/); int BN_num_bits(const BIGNUM */*a*/); int BN_mod_exp(BIGNUM */*r*/, BIGNUM */*a*/, BIGNUM */*p*/, BIGNUM */*m*/, BN_CTX */*ctx*/); BIGNUM *BN_mod_inverse(BIGNUM */*ret*/, BIGNUM */*a*/, const BIGNUM */*n*/, BN_CTX */*ctx*/); int BN_mod_mul(BIGNUM */*ret*/, BIGNUM */*a*/, BIGNUM */*b*/, const BIGNUM */*m*/, BN_CTX */*ctx*/); int BN_mod_sub(BIGNUM */*r*/, BIGNUM */*a*/, BIGNUM */*b*/, const BIGNUM */*m*/, BN_CTX */*ctx*/); int BN_raise(BIGNUM */*res*/, BIGNUM */*a*/, BIGNUM */*b*/); int BN_factorial(BIGNUM */*fact*/, BIGNUM */*f*/); BN_CTX *BN_CTX_new(void); BIGNUM *BN_CTX_get(BN_CTX */*ctx*/); void BN_CTX_start(BN_CTX */*ctx*/); void BN_CTX_end(BN_CTX */*ctx*/); void BN_CTX_init(BN_CTX */*c*/); void BN_CTX_free(BN_CTX */*c*/); int BN_rand(BIGNUM */*rnd*/, int /*bits*/, int /*top*/, int /*bottom*/); int BN_rand_range(BIGNUM */*rnd*/, BIGNUM */*range*/); int BN_is_prime(const BIGNUM */*a*/, int /*checks*/, void (*callback)(int, int, void *), BN_CTX */*ctx*/, void */*cb_arg*/); const BIGNUM *BN_value_one(void); int BN_is_bit_set(const BIGNUM */*a*/, int /*n*/); int BN_gcd(BIGNUM */*r*/, BIGNUM */*a*/, BIGNUM */*b*/, BN_CTX */*ctx*/); /* utilities */ int humanize_bignum(char *, size_t, const BIGNUM *, const char *, int, int); __END_DECLS #endif
a4d89ea430fe0efd3044147b44ca30f86efe6a0d
963cb6c161842ef207ae0526a166e4bb1603397a
/ugui/widgets/menu_widget.h
8bd5012cb53beb5f9d11ab8b9618fc441a5c568d
[ "MIT", "LGPL-2.0-or-later", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ryankurte/micro-gui
9417e81ccc0bb1e4e1a311ce2394dbf0cfa6f45e
2f30aff2d4bcb63b10eee770d898171298c08602
refs/heads/master
2023-06-09T09:33:57.161058
2023-06-06T06:29:39
2023-06-06T06:29:39
45,529,092
171
36
MIT
2023-06-06T06:29:41
2015-11-04T09:39:23
C
UTF-8
C
false
false
1,930
h
menu_widget.h
#ifndef MENU_WIDGET_H #define MENU_WIDGET_H #include <stdint.h> #include "ugui/ugui.h" typedef struct ugui_menu_index_s { uint32_t x; uint32_t y; } ugui_menu_index_t; typedef uint32_t menu_get_num_callback(void *menu_widget, void* data); typedef uint32_t menu_get_height_callback(void *menu_widget, uint16_t section, void* data); typedef void menu_get_header_callback(void* menu_widget, char* header); typedef void menu_get_data_callback(void* menu_widget, uint16_t index, char* title, char* data); typedef void menu_select_callback(void *menu_widget, uint16_t index, void *callback_context); typedef void header_draw_callback(ugui_graphics_t *graphics_ctx, ugui_rect_t *bounds, char* title); typedef void menu_draw_callback(ugui_graphics_t *graphics_ctx, ugui_rect_t *bounds, char* title, char* data); typedef struct ugui_menu_widget_data_callbacks_s { menu_get_num_callback *get_num_sections; menu_get_num_callback *get_num_rows; menu_get_header_callback *get_header; menu_get_data_callback *get_data; menu_select_callback *select; } ugui_menu_widget_data_callbacks_t; typedef struct ugui_menu_widget_draw_callbacks_s { menu_get_num_callback *get_header_height; menu_get_num_callback *get_cell_height; header_draw_callback *draw_header; menu_draw_callback *draw_row; } ugui_menu_widget_draw_callbacks_t; typedef struct ugui_menu_widget_s ugui_menu_widget_t; ugui_menu_widget_t *ugui_menu_widget_create(ugui_rect_t frame); void ugui_menu_widget_set_callbacks(ugui_menu_widget_t* menu_widget, ugui_menu_widget_data_callbacks_t* callbacks); void ugui_menu_widget_set_draw(ugui_menu_widget_t* menu_widget, ugui_menu_widget_draw_callbacks_t* callbacks); ugui_layer_t* ugui_menu_widget_get_layer(ugui_menu_widget_t* menu_widget); void ugui_menu_widget_attach_to_window(ugui_menu_widget_t* menu_widget, ugui_window_t* window); void ugui_menu_widget_destroy(ugui_menu_widget_t* menu_widget); #endif
e21090ec9a607c0ba0a99e6fe08973befaffb246
9746c6821b6c13e9089f1eeee1b53efcafb4a84f
/testmodule_win/sys/sioctl.h
36a891f706b0e521e3949edec55ca9ec4ee5e026
[ "MS-PL", "MIT" ]
permissive
intel/kernel-fuzzer-for-xen-project
3c953d3e2ff8d497435b3eddd2b3bcce570f705c
3458cf6ecdddf4aa3d85484915eb4fa7d2f378e4
refs/heads/master
2023-08-20T22:14:24.086023
2023-05-26T18:56:48
2023-05-26T18:56:48
261,611,628
457
80
MIT
2023-05-26T18:56:49
2020-05-06T00:14:07
C
UTF-8
C
false
false
1,155
h
sioctl.h
/*++ Copyright (c) 1997 Microsoft Corporation Module Name: SIOCTL.H Abstract: Defines the IOCTL codes that will be used by this driver. The IOCTL code contains a command identifier, plus other information about the device, the type of access with which the file must have been opened, and the type of buffering. Environment: Kernel mode only. --*/ // // Device type -- in the "User Defined" range." // #define SIOCTL_TYPE 40000 // // The IOCTL function codes from 0x800 to 0xFFF are for customer use. // #define IOCTL_SIOCTL_METHOD_IN_DIRECT \ CTL_CODE( SIOCTL_TYPE, 0x900, METHOD_IN_DIRECT, FILE_ANY_ACCESS ) #define IOCTL_SIOCTL_METHOD_OUT_DIRECT \ CTL_CODE( SIOCTL_TYPE, 0x901, METHOD_OUT_DIRECT , FILE_ANY_ACCESS ) #define IOCTL_SIOCTL_METHOD_BUFFERED \ CTL_CODE( SIOCTL_TYPE, 0x902, METHOD_BUFFERED, FILE_ANY_ACCESS ) #define IOCTL_SIOCTL_METHOD_NEITHER \ CTL_CODE( SIOCTL_TYPE, 0x903, METHOD_NEITHER , FILE_ANY_ACCESS ) #define DRIVER_FUNC_INSTALL 0x01 #define DRIVER_FUNC_REMOVE 0x02 #define DRIVER_NAME "SIoctl"
0ac99ac0ed82e9f693050d399483598215112feb
07327b5e8b2831b12352bf7c6426bfda60129da7
/Include/10.0.10240.0/um/spellcheck_i.c
4b7425e73987f3be2832aeca77c48fb70b965058
[]
no_license
tpn/winsdk-10
ca279df0fce03f92036e90fb04196d6282a264b7
9b69fd26ac0c7d0b83d378dba01080e93349c2ed
refs/heads/master
2021-01-10T01:56:18.586459
2018-02-19T21:26:31
2018-02-19T21:29:50
44,352,845
218
432
null
null
null
null
UTF-8
C
false
false
2,334
c
spellcheck_i.c
/* this ALWAYS GENERATED file contains the IIDs and CLSIDs */ /* link this file in with the server and any clients */ /* File created by MIDL compiler version 8.00.0613 */ /* @@MIDL_FILE_HEADING( ) */ #ifdef __cplusplus extern "C"{ #endif #include <rpc.h> #include <rpcndr.h> #ifdef _MIDL_USE_GUIDDEF_ #ifndef INITGUID #define INITGUID #include <guiddef.h> #undef INITGUID #else #include <guiddef.h> #endif #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ DEFINE_GUID(name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) #else // !_MIDL_USE_GUIDDEF_ #ifndef __IID_DEFINED__ #define __IID_DEFINED__ typedef struct _IID { unsigned long x; unsigned short s1; unsigned short s2; unsigned char c[8]; } IID; #endif // __IID_DEFINED__ #ifndef CLSID_DEFINED #define CLSID_DEFINED typedef IID CLSID; #endif // CLSID_DEFINED #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ const type name = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} #endif !_MIDL_USE_GUIDDEF_ MIDL_DEFINE_GUID(IID, IID_ISpellingError,0xB7C82D61,0xFBE8,0x4B47,0x9B,0x27,0x6C,0x0D,0x2E,0x0D,0xE0,0xA3); MIDL_DEFINE_GUID(IID, IID_IEnumSpellingError,0x803E3BD4,0x2828,0x4410,0x82,0x90,0x41,0x8D,0x1D,0x73,0xC7,0x62); MIDL_DEFINE_GUID(IID, IID_IOptionDescription,0x432E5F85,0x35CF,0x4606,0xA8,0x01,0x6F,0x70,0x27,0x7E,0x1D,0x7A); MIDL_DEFINE_GUID(IID, IID_ISpellCheckerChangedEventHandler,0x0B83A5B0,0x792F,0x4EAB,0x97,0x99,0xAC,0xF5,0x2C,0x5E,0xD0,0x8A); MIDL_DEFINE_GUID(IID, IID_ISpellChecker,0xB6FD0B71,0xE2BC,0x4653,0x8D,0x05,0xF1,0x97,0xE4,0x12,0x77,0x0B); MIDL_DEFINE_GUID(IID, IID_ISpellChecker2,0xE7ED1C71,0x87F7,0x4378,0xA8,0x40,0xC9,0x20,0x0D,0xAC,0xEE,0x47); MIDL_DEFINE_GUID(IID, IID_ISpellCheckerFactory,0x8E018A9D,0x2415,0x4677,0xBF,0x08,0x79,0x4E,0xA6,0x1F,0x94,0xBB); MIDL_DEFINE_GUID(IID, IID_IUserDictionariesRegistrar,0xAA176B85,0x0E12,0x4844,0x8E,0x1A,0xEE,0xF1,0xDA,0x77,0xF5,0x86); MIDL_DEFINE_GUID(IID, LIBID_MsSpellCheckLib,0x4A250E01,0x61EA,0x400B,0xA2,0x7D,0xBF,0x37,0x44,0xBC,0xC9,0xF5); MIDL_DEFINE_GUID(CLSID, CLSID_SpellCheckerFactory,0x7AB36653,0x1796,0x484B,0xBD,0xFA,0xE7,0x4F,0x1D,0xB7,0xC1,0xDC); #undef MIDL_DEFINE_GUID #ifdef __cplusplus } #endif
a462fe3580bb7ec2bc69c5ab840826b4060a8861
1885ce333f6980ab6aad764b3f8caf42094d9f7d
/test/e2e/test_master/ObjectArxHeaders/clipdata.h
b278a2f3f8dab5cd5d6dab31bbb3f6a3232f8833
[ "MIT" ]
permissive
satya-das/cppparser
1dbccdeed4287c36c61edc30190c82de447e415b
f9a4cfac1a3af7286332056d7c661d86b6c35eb3
refs/heads/master
2023-07-06T00:55:23.382303
2022-10-03T19:40:05
2022-10-03T19:40:05
16,642,636
194
26
MIT
2023-06-26T13:44:32
2014-02-08T12:20:01
C++
UTF-8
C
false
false
2,106
h
clipdata.h
// ////////////////////////////////////////////////////////////////////////////// // // Copyright 2018 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// // // Name: ClipData.h // // Remarks: Supports Clipboard and Drag and Drop Geometry from AutoCAD // ////////////////////////////////////////////////////////////////////////////// #ifndef _CLIPDATA_H # define _CLIPDATA_H # pragma pack (push, 8) # include "accoredefs.h" # include "AdAChar.h" enum eClipInfoFlags { kbDragGeometry = 0x01, }; enum eXrefType { kXrefTypeAttach = 1, kXrefTypeOverlay = 2 }; enum eExpandedClipDataTypes { kDcPlotStyles = 1, kDcXrefs = 2, kDcLayouts = 3, kDcBlocks = 4, kDcLayers = 5, kDcDrawings = 6, kDcLinetypes = 7, kDcTextStyles = 8, kDcDimStyles = 9, kDcBlocksWithAttdef = 10, //#ifdef ADCHATCH kDcHatches = 11, //#endif kTpXrefs = 12, kTpImages = 13, kTpTable = 14, kDcTableStyles = 15, kDcMultileaderStyles = 16, kDcVisualStyles = 17, kDcSectionViewStyles = 18, kDcDetailViewStyles = 19, }; const int nBlockFileSize = 260; const int nSignatureSize = 4; // Clipboard and drag and drop information stored in the format // CAcadDoc::m_cfPrivate ("AutoCAD.r15"). // typedef struct tagClipboardInfo { ACHAR szTempFile[nBlockFileSize]; ACHAR szSourceFile[nBlockFileSize]; ACHAR szSignature[nSignatureSize]; int nFlags; AcGePoint3d dptInsert; RECT rectGDI; void* mpView; DWORD m_dwThreadId; int nLen; int nType; ACHAR chData[1]; } ClipboardInfo; # define szClipSignature ACRX_T(/*MSG0*/"R15") ACCORE_PORT const ACHAR* acedClipFormatName(); # pragma pack (pop) #endif
ab7d8a93bfadd056d25701a285d511bed7b83e2c
676acab8ff535019faff7da3afb8eecc3fa127f5
/src/lib/micro-xrce-dds-client/src/c/profile/transport/ip/udp/udp_transport_windows.c
022a498a6369f62ee6f6afae8977e726f74a5520
[ "Apache-2.0" ]
permissive
Firmament-Autopilot/FMT-Firmware
f8c324577245bd7e91af436954b4ce9421acbb41
0212fe89820376bfbedaded519552f6b011a7b8a
refs/heads/master
2023-09-01T11:37:46.194145
2023-08-29T06:33:10
2023-08-29T06:33:10
402,557,689
351
143
Apache-2.0
2023-09-12T05:28:39
2021-09-02T20:42:56
C
UTF-8
C
false
false
2,658
c
udp_transport_windows.c
#include "udp_transport_internal.h" #include <uxr/client/profile/transport/ip/udp/udp_transport_windows.h> #include <ws2tcpip.h> bool uxr_init_udp_platform( uxrUDPPlatform* platform, uxrIpProtocol ip_protocol, const char* ip, const char* port) { bool rv = false; WSADATA wsa_data; if (0 != WSAStartup(MAKEWORD(2, 2), &wsa_data)) { return false; } switch (ip_protocol) { case UXR_IPv4: platform->poll_fd.fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); break; case UXR_IPv6: platform->poll_fd.fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); break; } if (INVALID_SOCKET != platform->poll_fd.fd) { struct addrinfo hints; struct addrinfo* result; struct addrinfo* ptr; ZeroMemory(&hints, sizeof(hints)); switch (ip_protocol) { case UXR_IPv4: hints.ai_family = AF_INET; break; case UXR_IPv6: hints.ai_family = AF_INET6; break; } hints.ai_socktype = SOCK_DGRAM; if (0 == getaddrinfo(ip, port, &hints, &result)) { for (ptr = result; ptr != NULL; ptr = ptr->ai_next) { if (0 == connect(platform->poll_fd.fd, ptr->ai_addr, (int)ptr->ai_addrlen)) { platform->poll_fd.events = POLLIN; rv = true; break; } } } freeaddrinfo(result); } return rv; } bool uxr_close_udp_platform( uxrUDPPlatform* platform) { bool rv = (INVALID_SOCKET == platform->poll_fd.fd) ? true : (0 == closesocket(platform->poll_fd.fd)); return (0 == WSACleanup()) && rv; } size_t uxr_write_udp_data_platform( uxrUDPPlatform* platform, const uint8_t* buf, size_t len, uint8_t* errcode) { size_t rv = 0; int bytes_sent = send(platform->poll_fd.fd, (const char*)buf, (int)len, 0); if (SOCKET_ERROR != bytes_sent) { rv = (size_t)bytes_sent; *errcode = 0; } else { *errcode = 1; } return rv; } size_t uxr_read_udp_data_platform( uxrUDPPlatform* platform, uint8_t* buf, size_t len, int timeout, uint8_t* errcode) { size_t rv = 0; int poll_rv = WSAPoll(&platform->poll_fd, 1, timeout); if (0 < poll_rv) { int bytes_received = recv(platform->poll_fd.fd, (char*)buf, (int)len, 0); if (SOCKET_ERROR != bytes_received) { rv = (size_t)bytes_received; *errcode = 0; } else { *errcode = 1; } } else { *errcode = (0 == poll_rv) ? 0 : 1; } return rv; }
5fa7b33601622ef7738feadc767fcbcb2d45b016
07327b5e8b2831b12352bf7c6426bfda60129da7
/Include/10.0.16299.0/um/WebEvnts.h
f9e500d3dc2e5ac9749b6bf180cfd2b162fe5dc0
[]
no_license
tpn/winsdk-10
ca279df0fce03f92036e90fb04196d6282a264b7
9b69fd26ac0c7d0b83d378dba01080e93349c2ed
refs/heads/master
2021-01-10T01:56:18.586459
2018-02-19T21:26:31
2018-02-19T21:29:50
44,352,845
218
432
null
null
null
null
UTF-8
C
false
false
10,461
h
WebEvnts.h
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 8.01.0622 */ /* @@MIDL_FILE_HEADING( ) */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 500 #endif /* verify that the <rpcsal.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCSAL_H_VERSION__ #define __REQUIRED_RPCSAL_H_VERSION__ 100 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif /* __RPCNDR_H_VERSION__ */ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __webevnts_h__ #define __webevnts_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IWebBrowserEventsService_FWD_DEFINED__ #define __IWebBrowserEventsService_FWD_DEFINED__ typedef interface IWebBrowserEventsService IWebBrowserEventsService; #endif /* __IWebBrowserEventsService_FWD_DEFINED__ */ #ifndef __IWebBrowserEventsUrlService_FWD_DEFINED__ #define __IWebBrowserEventsUrlService_FWD_DEFINED__ typedef interface IWebBrowserEventsUrlService IWebBrowserEventsUrlService; #endif /* __IWebBrowserEventsUrlService_FWD_DEFINED__ */ /* header files for imported files */ #include "objidl.h" #include "oleidl.h" #ifdef __cplusplus extern "C"{ #endif /* interface __MIDL_itf_webevnts_0000_0000 */ /* [local] */ //=--------------------------------------------------------------------------= // webevnts.h //=--------------------------------------------------------------------------= // (C) Copyright Microsoft Corporation. All Rights Reserved. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. //=--------------------------------------------------------------------------= #include <winapifamily.h> #pragma region Desktop Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #pragma comment(lib,"uuid.lib") //---------------------------------------------------------------------------= // IWebBrowserEventsService and IWebBrowserUrlForEvents Interfaces. #ifndef _LPWEBEVNTS_DEFINED #define _LPWEBEVNTS_DEFINED extern RPC_IF_HANDLE __MIDL_itf_webevnts_0000_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_webevnts_0000_0000_v0_0_s_ifspec; #ifndef __IWebBrowserEventsService_INTERFACE_DEFINED__ #define __IWebBrowserEventsService_INTERFACE_DEFINED__ /* interface IWebBrowserEventsService */ /* [object][hidden][helpcontext][helpstring][uuid] */ EXTERN_C const IID IID_IWebBrowserEventsService; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("54A8F188-9EBD-4795-AD16-9B4945119636") IWebBrowserEventsService : public IUnknown { public: virtual /* [helpcontext][helpstring] */ HRESULT STDMETHODCALLTYPE FireBeforeNavigate2Event( /* [retval][out] */ __RPC__out VARIANT_BOOL *pfCancel) = 0; virtual /* [helpcontext][helpstring] */ HRESULT STDMETHODCALLTYPE FireNavigateComplete2Event( void) = 0; virtual /* [helpcontext][helpstring] */ HRESULT STDMETHODCALLTYPE FireDownloadBeginEvent( void) = 0; virtual /* [helpcontext][helpstring] */ HRESULT STDMETHODCALLTYPE FireDownloadCompleteEvent( void) = 0; virtual /* [helpcontext][helpstring] */ HRESULT STDMETHODCALLTYPE FireDocumentCompleteEvent( void) = 0; }; #else /* C style interface */ typedef struct IWebBrowserEventsServiceVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IWebBrowserEventsService * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IWebBrowserEventsService * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IWebBrowserEventsService * This); /* [helpcontext][helpstring] */ HRESULT ( STDMETHODCALLTYPE *FireBeforeNavigate2Event )( __RPC__in IWebBrowserEventsService * This, /* [retval][out] */ __RPC__out VARIANT_BOOL *pfCancel); /* [helpcontext][helpstring] */ HRESULT ( STDMETHODCALLTYPE *FireNavigateComplete2Event )( __RPC__in IWebBrowserEventsService * This); /* [helpcontext][helpstring] */ HRESULT ( STDMETHODCALLTYPE *FireDownloadBeginEvent )( __RPC__in IWebBrowserEventsService * This); /* [helpcontext][helpstring] */ HRESULT ( STDMETHODCALLTYPE *FireDownloadCompleteEvent )( __RPC__in IWebBrowserEventsService * This); /* [helpcontext][helpstring] */ HRESULT ( STDMETHODCALLTYPE *FireDocumentCompleteEvent )( __RPC__in IWebBrowserEventsService * This); END_INTERFACE } IWebBrowserEventsServiceVtbl; interface IWebBrowserEventsService { CONST_VTBL struct IWebBrowserEventsServiceVtbl *lpVtbl; }; #ifdef COBJMACROS #define IWebBrowserEventsService_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IWebBrowserEventsService_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IWebBrowserEventsService_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IWebBrowserEventsService_FireBeforeNavigate2Event(This,pfCancel) \ ( (This)->lpVtbl -> FireBeforeNavigate2Event(This,pfCancel) ) #define IWebBrowserEventsService_FireNavigateComplete2Event(This) \ ( (This)->lpVtbl -> FireNavigateComplete2Event(This) ) #define IWebBrowserEventsService_FireDownloadBeginEvent(This) \ ( (This)->lpVtbl -> FireDownloadBeginEvent(This) ) #define IWebBrowserEventsService_FireDownloadCompleteEvent(This) \ ( (This)->lpVtbl -> FireDownloadCompleteEvent(This) ) #define IWebBrowserEventsService_FireDocumentCompleteEvent(This) \ ( (This)->lpVtbl -> FireDocumentCompleteEvent(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IWebBrowserEventsService_INTERFACE_DEFINED__ */ #ifndef __IWebBrowserEventsUrlService_INTERFACE_DEFINED__ #define __IWebBrowserEventsUrlService_INTERFACE_DEFINED__ /* interface IWebBrowserEventsUrlService */ /* [object][hidden][helpcontext][helpstring][uuid] */ EXTERN_C const IID IID_IWebBrowserEventsUrlService; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("87CC5D04-EAFA-4833-9820-8F986530CC00") IWebBrowserEventsUrlService : public IUnknown { public: virtual /* [helpcontext][helpstring] */ HRESULT STDMETHODCALLTYPE GetUrlForEvents( /* [retval][out] */ __RPC__deref_out_opt BSTR *pUrl) = 0; }; #else /* C style interface */ typedef struct IWebBrowserEventsUrlServiceVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IWebBrowserEventsUrlService * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IWebBrowserEventsUrlService * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IWebBrowserEventsUrlService * This); /* [helpcontext][helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetUrlForEvents )( __RPC__in IWebBrowserEventsUrlService * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pUrl); END_INTERFACE } IWebBrowserEventsUrlServiceVtbl; interface IWebBrowserEventsUrlService { CONST_VTBL struct IWebBrowserEventsUrlServiceVtbl *lpVtbl; }; #ifdef COBJMACROS #define IWebBrowserEventsUrlService_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IWebBrowserEventsUrlService_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IWebBrowserEventsUrlService_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IWebBrowserEventsUrlService_GetUrlForEvents(This,pUrl) \ ( (This)->lpVtbl -> GetUrlForEvents(This,pUrl) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IWebBrowserEventsUrlService_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_webevnts_0000_0002 */ /* [local] */ #endif #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */ #pragma endregion extern RPC_IF_HANDLE __MIDL_itf_webevnts_0000_0002_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_webevnts_0000_0002_v0_0_s_ifspec; /* Additional Prototypes for ALL interfaces */ unsigned long __RPC_USER BSTR_UserSize( __RPC__in unsigned long *, unsigned long , __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out BSTR * ); void __RPC_USER BSTR_UserFree( __RPC__in unsigned long *, __RPC__in BSTR * ); unsigned long __RPC_USER BSTR_UserSize64( __RPC__in unsigned long *, unsigned long , __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal64( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal64(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out BSTR * ); void __RPC_USER BSTR_UserFree64( __RPC__in unsigned long *, __RPC__in BSTR * ); /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
1d82b58302d91426d3bc69f577b38c18398ecf21
340cc5d8ba77fbbafefb8a1755ae4dacbfb6953e
/src/inline/applybits_inline.c
012de88bf3fc6dd470bcbfd411cae610b7d9fb1f
[ "BSD-3-Clause" ]
permissive
phaag/nfdump
1899c1b376c62040acdc994892949310cf85b32a
584453e6e3b4d6f23cf6c83cd2a7298cf0b5c44a
refs/heads/master
2023-08-31T06:53:13.565444
2023-08-20T12:22:46
2023-08-20T12:22:46
40,435,192
703
200
NOASSERTION
2023-08-20T18:40:33
2015-08-09T12:12:03
C
UTF-8
C
false
false
5,165
c
applybits_inline.c
/* * Copyright (c) 2009-2021, Peter Haag * Copyright (c) 2004-2008, SWITCH - Teleinformatikdienste fuer Lehre und Forschung * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * */ static inline void ApplyNetMaskBits(master_record_t *flow_record, int apply_netbits); static inline void ApplyNetMaskBits(master_record_t *flow_record, int apply_netbits) { if ((flow_record->mflags & V3_FLAG_IPV6_ADDR) != 0) { // IPv6 if (apply_netbits & 1) { uint64_t mask; uint32_t mask_bits = flow_record->src_mask; if (mask_bits > 64) { mask = 0xffffffffffffffffLL << (128 - mask_bits); flow_record->V6.srcaddr[1] &= mask; } else { mask = 0xffffffffffffffffLL << (64 - mask_bits); flow_record->V6.srcaddr[0] &= mask; flow_record->V6.srcaddr[1] = 0; } } if (apply_netbits & 2) { uint64_t mask; uint32_t mask_bits = flow_record->dst_mask; if (mask_bits > 64) { mask = 0xffffffffffffffffLL << (128 - mask_bits); flow_record->V6.dstaddr[1] &= mask; } else { mask = 0xffffffffffffffffLL << (64 - mask_bits); flow_record->V6.dstaddr[0] &= mask; flow_record->V6.dstaddr[1] = 0; } } } else { // IPv4 if (apply_netbits & 1) { uint32_t srcmask = 0xffffffff << (32 - flow_record->src_mask); flow_record->V4.srcaddr &= srcmask; } if (apply_netbits & 2) { uint32_t dstmask = 0xffffffff << (32 - flow_record->dst_mask); flow_record->V4.dstaddr &= dstmask; } } } // End of ApplyNetMaskBits static inline void SetNetMaskBits(EXipv4Flow_t *EXipv4Flow, EXipv6Flow_t *EXipv6Flow, EXflowMisc_t *EXflowMisc, int apply_netbits); static inline void SetNetMaskBits(EXipv4Flow_t *EXipv4Flow, EXipv6Flow_t *EXipv6Flow, EXflowMisc_t *EXflowMisc, int apply_netbits) { if (EXipv6Flow) { // IPv6 if (apply_netbits & 1) { uint64_t mask; uint32_t mask_bits = EXflowMisc->srcMask; if (mask_bits > 64) { mask = 0xffffffffffffffffLL << (128 - mask_bits); EXipv6Flow->srcAddr[1] &= mask; } else { mask = 0xffffffffffffffffLL << (64 - mask_bits); EXipv6Flow->srcAddr[0] &= mask; EXipv6Flow->srcAddr[1] = 0; } } if (apply_netbits & 2) { uint64_t mask; uint32_t mask_bits = EXflowMisc->dstMask; if (mask_bits > 64) { mask = 0xffffffffffffffffLL << (128 - mask_bits); EXipv6Flow->dstAddr[1] &= mask; } else { mask = 0xffffffffffffffffLL << (64 - mask_bits); EXipv6Flow->dstAddr[0] &= mask; EXipv6Flow->dstAddr[1] = 0; } } } else if (EXipv4Flow) { // IPv4 if (apply_netbits & 1) { uint32_t srcmask = 0xffffffff << (32 - EXflowMisc->srcMask); EXipv4Flow->srcAddr &= srcmask; } if (apply_netbits & 2) { uint32_t dstmask = 0xffffffff << (32 - EXflowMisc->dstMask); EXipv4Flow->dstAddr &= dstmask; } } } // End of SetNetMaskBits static inline void ApplyAggrMask(master_record_t *record, master_record_t *mask) { uint64_t *r = (uint64_t *)record; uint64_t *m = (uint64_t *)mask; for (int i = INDEX_BASE; i < Offset_MR_LAST; i++) { r[i] &= m[i]; } } // End of ApplyAggrMask
15cc1961d2dc20958f56424e239f1687ce8402ce
fef5296397f9b950a11455e880a919537390aea0
/ide/dlight.nativeexecution/tools/killall/src/linux/pfind.c
69bf424a68d177f45b35f94e21f6d836ccac8013
[ "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
2,440
c
pfind.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 <stdio.h> #include <stdlib.h> #include <limits.h> #include <dirent.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include "../pfind.h" #define MAX_LEN 4048 static char *procdir = "/proc"; pid_t* pfind(const char* magicenv) { pid_t *result = NULL; char fname[PATH_MAX]; char buffer[MAX_LEN]; DIR *dirp; struct dirent *dentp; int fd, res = 0, ressize = 0; if ((dirp = opendir(procdir)) == NULL) { return NULL; } while (dentp = readdir(dirp)) { if (dentp->d_name[0] < '0' || dentp->d_name[0] > '9') { continue; } char* pid = dentp->d_name; snprintf(fname, PATH_MAX, "%s/%s/environ", procdir, pid); if ((fd = open(fname, O_RDONLY)) == -1) { continue; // iterate over /proc } int size; if ((size = read(fd, buffer, MAX_LEN)) == -1) { goto next; } char* p = buffer; while (p < buffer + size) { if (strcmp(magicenv, p) == 0) { if (res >= ressize) { ressize += 10; result = realloc(result, ressize * sizeof (pid_t)); } result[res++] = (pid_t) atol(pid); break; } p += strlen(p) + 1; } next: (void) close(fd); } if (dirp != NULL) { (void) closedir(dirp); } if (res >= ressize) { ressize++; result = realloc(result, ressize * sizeof (pid_t)); } result[res] = 0; return result; }
79c7f73b6a61b35b42c522b09237f30b4c4628b7
2898fa4f2ad766afa0495a837f59fe95daa081a7
/tests/unit-pass/inc-ref-link1.c
58a22b94182811147e006d3e1fd9415c3ac4e12a
[ "NCSA" ]
permissive
kframework/c-semantics
12fcc1b1bf1f7792636d1c37f6f7bb1b89a392b5
e6879d14455771aa0cb3e3d201131d4d763a73a2
refs/heads/master
2023-07-31T23:57:03.316456
2022-02-01T17:50:31
2022-02-01T17:50:31
11,747,541
312
52
NOASSERTION
2022-02-01T17:50:33
2013-07-29T19:13:25
C
UTF-8
C
false
false
129
c
inc-ref-link1.c
extern struct foo x; void bar(struct foo *x); struct foo *p = &x; int main() { struct foo *p2 = &x; bar(p); return 0; }
62258981f394648c594359aa9794bcae5104c3c7
6f57761c60582c546423a2a08c769f18236fd153
/include/ccl_eh.h
3972b91aa94dc4627f48d24422fef74efefa87c8
[ "BSD-3-Clause", "LGPL-2.0-or-later", "BSD-2-Clause" ]
permissive
LSSTDESC/CCL
30644922fead0b017c1056e628bec23cf6bc4dfb
29d46978445678d86a4bee485cb29d30246ff64a
refs/heads/master
2023-09-03T17:03:17.012019
2023-08-08T11:01:33
2023-08-08T11:01:33
57,389,367
118
68
BSD-3-Clause
2023-08-30T13:25:25
2016-04-29T14:08:38
C
UTF-8
C
false
false
851
h
ccl_eh.h
/** @file */ #ifndef __CCL_EH98_H_INCLUDED__ #define __CCL_EH98_H_INCLUDED__ CCL_BEGIN_DECLS typedef struct eh_struct { double rsound; double zeq; double keq; double zdrag; double kSilk; double rsound_approx; double th2p7; double alphac; double alphab; double betac; double betab; double bnode; int wiggled; } eh_struct; /* * Allocate a new struct for storing EH98 data * @param params Cosmological parameters * @param int, include BAO wiggles if not 0, smooth otherwise */ eh_struct* ccl_eh_struct_new(ccl_parameters *params, int wiggled); /* * Compute the Eisenstein & Hu (1998) unnormalize power spectrum * @param params Cosmological parameters * @param eh, an eh_struct instance * @param k, wavenumber in Mpc^-1 */ double ccl_eh_power(ccl_parameters *params, eh_struct* eh, double k); CCL_END_DECLS #endif
03553c7a0de9e02e44e1c524d419b70551892fd6
fd4cfb3cf9eca142cca63ae4a754fcacf0948a08
/ttydraw/charset.c
32313a87a6addcbb0782b805e06823baf45839e5
[ "WTFPL" ]
permissive
taviso/123elf
6e9394c11d9f2656ddc7f54f63dacbcf5557909c
df948ddd3e2d4e8ce10bfb9b34a3f82e7571eae0
refs/heads/main
2023-08-13T02:18:34.921398
2023-05-26T13:49:24
2023-05-26T13:49:24
494,666,336
1,002
62
null
2023-04-09T01:53:22
2022-05-21T03:06:48
C
UTF-8
C
false
false
12,590
c
charset.c
/* * libcaca Colour ASCII-Art library * Copyright © 2002—2018 Sam Hocevar <sam@hocevar.net> * 2007 Ben Wiley Sittler <bsittler@gmail.com> * All Rights Reserved * * This library is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What the Fuck You Want * to Public License, Version 2, as published by Sam Hocevar. See * http://www.wtfpl.net/ for more details. */ /* * This file contains functions for converting characters between * various character sets. */ #include <curses.h> #include "config.h" #if !defined(__KERNEL__) # include <string.h> #endif #include "ttydraw.h" #include "ttyint.h" /* * UTF-8 handling */ static uint8_t const trailing[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 }; static uint32_t const offsets[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; /* * CP437 handling */ static uint32_t const cp437_lookup1[] = { /* 0x01 - 0x0f: ☺ ☻ ♥ ♦ ♣ ♠ • ◘ ○ ◙ ♂ ♀ ♪ ♫ ☼ */ 0x263a, 0x263b, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25d8, 0x25cb, 0x25d9, 0x2642, 0x2640, 0x266a, 0x266b, 0x263c, /* 0x10 - 0x1f: ► ◄ ↕ ‼ ¶ § ▬ ↨ ↑ ↓ → ← ∟ ↔ ▲ ▼ */ 0x25ba, 0x25c4, 0x2195, 0x203c, 0xb6, 0xa7, 0x25ac, 0x21a8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221f, 0x2194, 0x25b2, 0x25bc }; static uint32_t const cp437_lookup2[] = { /* 0x7f: ⌂ */ 0x2302, /* 0x80 - 0x8f: Ç ü é â ä à å ç ê ë è ï î ì Ä Å */ 0xc7, 0xfc, 0xe9, 0xe2, 0xe4, 0xe0, 0xe5, 0xe7, 0xea, 0xeb, 0xe8, 0xef, 0xee, 0xec, 0xc4, 0xc5, /* 0x90 - 0x9f: É æ Æ ô ö ò û ù ÿ Ö Ü ¢ £ ¥ ₧ ƒ */ 0xc9, 0xe6, 0xc6, 0xf4, 0xf6, 0xf2, 0xfb, 0xf9, 0xff, 0xd6, 0xdc, 0xa2, 0xa3, 0xa5, 0x20a7, 0x192, /* 0xa0 - 0xaf: á í ó ú ñ Ñ ª º ¿ ⌐ ¬ ½ ¼ ¡ « » */ 0xe1, 0xed, 0xf3, 0xfa, 0xf1, 0xd1, 0xaa, 0xba, 0xbf, 0x2310, 0xac, 0xbd, 0xbc, 0xa1, 0xab, 0xbb, /* 0xb0 - 0xbf: ░ ▒ ▓ │ ┤ ╡ ╢ ╖ ╕ ╣ ║ ╗ ╝ ╜ ╛ ┐ */ 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255d, 0x255c, 0x255b, 0x2510, /* 0xc0 - 0xcf: └ ┴ ┬ ├ ─ ┼ ╞ ╟ ╚ ╔ ╩ ╦ ╠ ═ ╬ ╧ */ 0x2514, 0x2534, 0x252c, 0x251c, 0x2500, 0x253c, 0x255e, 0x255f, 0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256c, 0x2567, /* 0xd0 - 0xdf: ╨ ╤ ╥ ╙ ╘ ╒ ╓ ╫ ╪ ┘ ┌ █ ▄ ▌ ▐ ▀ */ 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256b, 0x256a, 0x2518, 0x250c, 0x2588, 0x2584, 0x258c, 0x2590, 0x2580, /* 0xe0 - 0xef: α ß Γ π Σ σ µ τ Φ Θ Ω δ ∞ φ ε ∩ */ 0x3b1, 0xdf, 0x393, 0x3c0, 0x3a3, 0x3c3, 0xb5, 0x3c4, 0x3a6, 0x398, 0x3a9, 0x3b4, 0x221e, 0x3c6, 0x3b5, 0x2229, /* 0xf0 - 0xff: ≡ ± ≥ ≤ ⌠ ⌡ ÷ ≈ ° ∙ · √ ⁿ ² ■ <nbsp> */ 0x2261, 0xb1, 0x2265, 0x2264, 0x2320, 0x2321, 0xf7, 0x2248, 0xb0, 0x2219, 0xb7, 0x221a, 0x207f, 0xb2, 0x25a0, 0xa0 }; /** \brief Convert a UTF-8 character to UTF-32. * * Convert a UTF-8 character read from a string and return its value in * the UTF-32 character set. If the second argument is not null, the total * number of read bytes is written in it. * * If a null byte was reached before the expected end of the UTF-8 sequence, * this function returns zero and the number of read bytes is set to zero. * * This function never fails, but its behaviour with illegal UTF-8 sequences * is undefined. * * \param s A string containing the UTF-8 character. * \param bytes A pointer to a size_t to store the number of bytes in the * character, or NULL. * \return The corresponding UTF-32 character, or zero if the character * is incomplete. */ uint32_t caca_utf8_to_utf32(char const *s, size_t *bytes) { int todo = trailing[(int)(unsigned char)*s]; int i = 0; uint32_t ret = 0; for(;;) { if(!*s) { if(bytes) *bytes = 0; return 0; } ret += ((uint32_t)(unsigned char)*s++) << (6 * (todo - i)); if(todo == i++) { if(bytes) *bytes = i; return ret - offsets[todo]; } } } /** \brief Convert a UTF-32 character to UTF-8. * * Convert a UTF-32 character read from a string and write its value in * the UTF-8 character set into the given buffer. * * This function never fails, but its behaviour with illegal UTF-32 characters * is undefined. * * \param buf A pointer to a character buffer where the UTF-8 sequence will * be written. * \param ch The UTF-32 character. * \return The number of bytes written. */ size_t caca_utf32_to_utf8(char *buf, uint32_t ch) { static const uint8_t mark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; char *parser = buf; size_t bytes; if(ch < 0x80) { *parser++ = ch; return 1; } bytes = (ch < 0x800) ? 2 : (ch < 0x10000) ? 3 : 4; parser += bytes; switch(bytes) { case 4: *--parser = (ch | 0x80) & 0xbf; ch >>= 6; case 3: *--parser = (ch | 0x80) & 0xbf; ch >>= 6; case 2: *--parser = (ch | 0x80) & 0xbf; ch >>= 6; } *--parser = ch | mark[bytes]; return bytes; } /** \brief Convert a UTF-32 character to CP437. * * Convert a UTF-32 character read from a string and return its value in * the CP437 character set, or "?" if the character has no equivalent. * * This function never fails. * * \param ch The UTF-32 character. * \return The corresponding CP437 character, or "?" if not representable. */ uint8_t caca_utf32_to_cp437(uint32_t ch) { unsigned int i; if(ch < 0x00000020) return '?'; if(ch < 0x00000080) return ch; for(i = 0; i < sizeof(cp437_lookup1) / sizeof(*cp437_lookup1); i++) if(cp437_lookup1[i] == ch) return 0x01 + i; for(i = 0; i < sizeof(cp437_lookup2) / sizeof(*cp437_lookup2); i++) if(cp437_lookup2[i] == ch) return 0x7f + i; return '?'; } /** \brief Convert a CP437 character to UTF-32. * * Convert a CP437 character read from a string and return its value in * the UTF-32 character set, or zero if the character is a CP437 control * character. * * This function never fails. * * \param ch The CP437 character. * \return The corresponding UTF-32 character, or zero if not representable. */ uint32_t caca_cp437_to_utf32(uint8_t ch) { if(ch > 0x7f) return cp437_lookup2[ch - 0x7f]; if(ch >= 0x20) return (uint32_t)ch; if(ch > 0) return cp437_lookup1[ch - 0x01]; return 0x00000000; } /** \brief Convert a UTF-32 character to ASCII. * * Convert a UTF-32 character into an ASCII character. When no equivalent * exists, a graphically close equivalent is sought. * * This function never fails, but its behaviour with illegal UTF-32 characters * is undefined. * * \param ch The UTF-32 character. * \return The corresponding ASCII character, or a graphically close * equivalent if found, or "?" if not representable. */ char caca_utf32_to_ascii(uint32_t ch) { /* Standard ASCII */ if(ch < 0x80) return ch; /* Fullwidth Forms */ if(ch > 0x0000ff00 && ch < 0x0000ff5f) return ' ' + (ch - 0x0000ff00); switch (ch) { case 0x000000a0: /*   (nbsp) */ case 0x00003000: /*   (ideographic space) */ return ' '; case 0x000000a3: /* £ */ return 'f'; case 0x000000b0: /* ° */ return '\''; case 0x000000b1: /* ± */ return '#'; case 0x000000b7: /* · */ case 0x00002219: /* ∙ */ case 0x000030fb: /* ・ */ return '.'; case 0x000003c0: /* π */ return '*'; case 0x00002018: /* ‘ */ case 0x00002019: /* ’ */ return '\''; case 0x0000201c: /* “ */ case 0x0000201d: /* ” */ return '"'; case 0x00002190: /* ← */ return '<'; case 0x00002191: /* ↑ */ return '^'; case 0x00002192: /* → */ return '>'; case 0x00002193: /* ↓ */ return 'v'; case 0x00002260: /* ≠ */ return '!'; case 0x00002261: /* ≡ */ return '='; case 0x00002264: /* ≤ */ return '<'; case 0x00002265: /* ≥ */ return '>'; case 0x000023ba: /* ⎺ */ case 0x000023bb: /* ⎻ */ case 0x000023bc: /* ⎼ */ case 0x000023bd: /* ⎽ */ case 0x00002500: /* ─ */ case 0x00002550: /* ═ */ return '-'; case 0x00002502: /* │ */ case 0x00002551: /* ║ */ return '|'; case 0x0000250c: /* ┌ */ case 0x00002552: /* ╒ */ case 0x00002553: /* ╓ */ case 0x00002554: /* ╔ */ case 0x00002514: /* └ */ case 0x00002558: /* ╘ */ case 0x00002559: /* ╙ */ case 0x0000255a: /* ╚ */ case 0x0000251c: /* ├ */ case 0x0000255e: /* ╞ */ case 0x0000255f: /* ╟ */ case 0x00002560: /* ╠ */ case 0x0000252c: /* ┬ */ case 0x00002564: /* ╤ */ case 0x00002565: /* ╥ */ case 0x00002566: /* ╦ */ case 0x00002534: /* ┴ */ case 0x00002567: /* ╧ */ case 0x00002568: /* ╨ */ case 0x00002569: /* ╩ */ case 0x0000253c: /* ┼ */ case 0x0000256a: /* ╪ */ case 0x0000256b: /* ╫ */ case 0x0000256c: /* ╬ */ return '+'; case 0x00002510: /* ┐ */ case 0x00002555: /* ╕ */ case 0x00002556: /* ╖ */ case 0x00002557: /* ╗ */ case 0x00002518: /* ┘ */ case 0x0000255b: /* ╛ */ case 0x0000255c: /* ╜ */ case 0x0000255d: /* ╝ */ case 0x00002524: /* ┤ */ case 0x00002561: /* ╡ */ case 0x00002562: /* ╢ */ case 0x00002563: /* ╣ */ return '+'; case 0x00002591: /* ░ */ case 0x00002592: /* ▒ */ case 0x00002593: /* ▓ */ case 0x00002588: /* █ */ case 0x0000258c: /* ▌ */ case 0x00002590: /* ▐ */ case 0x000025a0: /* ■ */ case 0x000025ac: /* ▬ */ case 0x000025ae: /* ▮ */ return '#'; case 0x00002580: /* ▀ */ return '"'; case 0x00002584: /* ▄ */ return ','; case 0x000025c6: /* ◆ */ case 0x00002666: /* ♦ */ return '+'; case 0x00002022: /* • */ case 0x000025cb: /* ○ */ case 0x000025cf: /* ● */ case 0x00002603: /* ☃ */ case 0x0000263c: /* ☼ */ return 'o'; case 0x0000301c: /* 〜 */ return '~'; } return '?'; } /** \brief Tell whether a UTF-32 character is fullwidth. * * Check whether the given UTF-32 character should be printed at twice * the normal width (fullwidth characters). If the character is unknown * or if its status cannot be decided, it is treated as a standard-width * character. * * This function never fails. * * \param ch The UTF-32 character. * \return 1 if the character is fullwidth, 0 otherwise. */ int caca_utf32_is_fullwidth(uint32_t ch) { if(ch < 0x2e80) /* Standard stuff */ return 0; if(ch < 0xa700) /* Japanese, Korean, CJK, Yi... */ return 1; if(ch < 0xac00) /* Modified Tone Letters, Syloti Nagri */ return 0; if(ch < 0xd800) /* Hangul Syllables */ return 1; if(ch < 0xf900) /* Misc crap */ return 0; if(ch < 0xfb00) /* More CJK */ return 1; if(ch < 0xfe20) /* Misc crap */ return 0; if(ch < 0xfe70) /* More CJK */ return 1; if(ch < 0xff00) /* Misc crap */ return 0; if(ch < 0xff61) /* Fullwidth forms */ return 1; if(ch < 0xffe0) /* Halfwidth forms */ return 0; if(ch < 0xffe8) /* More fullwidth forms */ return 1; if(ch < 0x20000) /* Misc crap */ return 0; if(ch < 0xe0000) /* More CJK */ return 1; return 0; }
f560862aa821b5b423f228ad5524735385b515c7
baf824f8819f90928e11480d0eae89efb60341a1
/ports/nxp_lpc546/sdk22/middleware/usb_1.7.0/host/class/usb_host_cdc.h
7e2ffcc80bd063bdd519d635714cb8f95840293b
[ "MIT" ]
permissive
RockySong/micropython-rocky
549770723ba92cb311c468880ead0ffdd4fa8fe5
2d728f414bf8d041ca609e00448850759aade3cd
refs/heads/omv_initial_integrate
2021-05-12T12:20:18.404341
2021-01-15T01:15:48
2021-01-15T01:15:48
117,408,452
198
90
MIT
2020-08-25T03:31:32
2018-01-14T06:40:36
C
UTF-8
C
false
false
28,682
h
usb_host_cdc.h
/* * Copyright (c) 2015 - 2016, Freescale Semiconductor, Inc. * Copyright 2016 NXP * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o 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. * * o 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 __USB_HOST_CDC_H__ #define __USB_HOST_CDC_H__ /*! * @addtogroup usb_host_cdc_drv * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ /* Class-specific request */ /* CDC 1.2 */ /*! @brief CDC class-specific request (SEND_ENCAPSULATED_COMMAND) */ #define USB_HOST_CDC_SEND_ENCAPSULATED_COMMAND 0x00U /*! @brief CDC class-specific request (GET_ENCAPSULATED_RESPONSE) */ #define USB_HOST_CDC_GET_ENCAPSULATED_RESPONSE 0x01U /* PSTN */ /*! @brief CDC class-specific request (SET_LINE_CODING) */ #define USB_HOST_CDC_SET_LINE_CODING 0x20U /*! @brief CDC class-specific request (GET_LINE_CODING) */ #define USB_HOST_CDC_GET_LINE_CODING 0x21U /*! @brief CDC class-specific request (SET_CONTROL_LINE_STATE) */ #define USB_HOST_CDC_SET_CONTROL_LINE_STATE 0x22U /*! @brief CDC class-specific notifications(SerialState) bitmap*/ #define USB_HOST_ACM_UART_STATE_BITMAP_BTXCARRITER 0x01U /*! @brief CDC class-specific notifications(SerialState) bitmap*/ #define USB_HOST_ACM_UART_STATE_BITMAP_BRXCARRITER 0x02U /*! @brief CDC class-specific notifications(SerialState) bitmap*/ #define USB_HOST_ACM_UART_STATE_BITMAP_BBREAK 0x04U /*! @brief CDC class-specific notifications(SerialState) bitmap*/ #define USB_HOST_ACM_UART_STATE_BITMAP_BBRINGSIGNAL 0x10U /*! @brief CDC class-specific request (SET_CONTROL_LINE_STATE) bitmap*/ #define USB_HOST_CDC_CONTROL_LINE_STATE_DTR 0x01U /*! @brief CDC class-specific request (SET_CONTROL_LINE_STATE) bitmap*/ #define USB_HOST_CDC_CONTROL_LINE_STATE_RTS 0x02U /*CDC SPEC*/ /*! @brief CDC class-specific bDescriptor SubType in functional descriptors*/ #define USB_HOST_DESC_SUBTYPE_HEADER 0x00U /*! @brief CDC class-specific bDescriptor SubType in functional descriptors*/ #define USB_HOST_DESC_SUBTYPE_CM 0x01U /*! @brief CDC class-specific bDescriptor SubType in functional descriptors*/ #define USB_HOST_DESC_SUBTYPE_ACM 0x02U /*! @brief CDC class-specific bDescriptor SubType in functional descriptors*/ #define USB_HOST_DESC_SUBTYPE_DLM 0x03U /*! @brief CDC class-specific bDescriptor SubType in functional descriptors*/ #define USB_HOST_DESC_SUBTYPE_TR 0x04U /*! @brief CDC class-specific bDescriptor SubType in functional descriptors*/ #define USB_HOST_DESC_SUBTYPE_TC_LSR 0x05U /*! @brief CDC class-specific bDescriptor SubType in functional descriptors*/ #define USB_HOST_DESC_SUBTYPE_UNION 0x06U /*! @brief CDC class-specific bDescriptor SubType in functional descriptors*/ #define USB_HOST_DESC_SUBTYPE_CS 0x07U /*! @brief CDC class-specific bDescriptor SubType in functional descriptors*/ #define USB_HOST_DESC_SUBTYPE_TOM 0x08U /*See the CDC specification page20*/ /*! @brief CDC class-specific code, Communications Interface Class Code*/ #define USB_HOST_CDC_COMMUNICATIONS_CLASS_CODE 0x02U /*! @brief CDC class-specific code,Communications Class Subclass Codes*/ #define USB_HOST_CDC_SUBCLASS_ACM_CODE 0x02U /*No class specific protocol required. See the CDC specification page22*/ #define USB_HOST_CDC_PROTOCOL_CODE 0x00U /*! @brief CDC class-specific code,Data Class Interface Codes*/ #define USB_HOST_CDC_DATA_CLASS_CODE 0x0AU /* This field is unused for Data Class interfaces and should have a value of 00h.*/ #define USB_HOST_CDC_DATA_SUBCLASS_CODE 0x00U /*No class-specific protocol required. See the CDC specification page22*/ #define USB_HOST_CDC_DATA_PROTOCOL_CODE 0x00U /*! @brief CDC GetLineCoding structure according to the 6.3 in PSTN specification */ typedef struct _usb_host_cdc_line_coding_struct { uint32_t dwDTERate; /*!< Data terminal rate, in bits per second*/ uint8_t bCharFormat; /*!< Stop bits*/ uint8_t bParityType; /*!< Parity*/ uint8_t bDataBits; /*!< Data bits (5, 6, 7, 8 or 16).*/ } usb_host_cdc_line_coding_struct_t; /*! @brief CDC GetLineCoding structure according to the 6.3 in PSTN specification */ typedef struct _usb_host_cdc_control_line_state_struct { uint16_t line_state; /*!< D1, This signal corresponds to V.24 signal 105 and RS-232 signal RTS*/ /*!< D0, This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR*/ } usb_host_cdc_control_line_state_struct_t; /*! @brief CDC SerialState structure according to the 6.5.4 in PSTN specification */ typedef struct _usb_host_cdc_acm_state_struct { uint8_t reserved[8]; /*!< Notify response by the device, this is used as notification header which is return by the device */ uint8_t bmstate; /*!< UART State Bitmap Values*/ uint8_t reserved1[1]; /*!< Fix 4B align issue*/ uint8_t reserved2[2]; /*!< Fix 4B align issue*/ } usb_host_cdc_acm_state_struct_t; /*! @brief CDC Header Functional Descriptor structure according to the 5.2.3 in CDC specification */ typedef struct _usb_host_cdc_head_function_desc_struct { uint8_t bFunctionLength; /*!<Size of this descriptor in bytes.*/ uint8_t bDescriptorType; /*!<CS_INTERFACE descriptor type.*/ uint8_t bDescriptorSubtype; /*!<Header functional descriptor subtype.*/ uint8_t bcdCDC[2]; /*!<USB Class Definitions for Communications Devices Specification release number in binary-coded decimal.*/ } usb_host_cdc_head_function_desc_struct_t; /*! @brief CDC Call Management Functional Descriptor structure according to the 5.3.1 in PSTN specification */ typedef struct _usb_host_cdc_call_manage_desc_struct { uint8_t bFunctionLength; /*!<Size of this descriptor in bytes.*/ uint8_t bDescriptorType; /*!<CS_INTERFACE.*/ uint8_t bDescriptorSubtype; /*!<Call Management functional descriptor subtype.*/ uint8_t bmCapabilities; /*!<The capabilities that this configuration supports.*/ uint8_t bDataInterface; /*!<Interface number of Data Class interface optionally used for call management.*/ } usb_host_cdc_call_manage_desc_struct_t; /*! @brief CDC Abstract Control Management Functional Descriptor structure according to the 5.3.2 in PSTN specification */ typedef struct _usb_host_cdc_abstract_control_desc_struct { uint8_t bFunctionLength; /*!<Size of this descriptor in bytes.*/ uint8_t bDescriptorType; /*!<CS_INTERFACE.*/ uint8_t bDescriptorSubtype; /*!<Abstract Control Management functional descriptor subtype.*/ uint8_t bmCapabilities; /*!<The capabilities that this configuration supports.*/ } usb_host_cdc_abstract_control_desc_struct_t; /*! @brief CDC Direct Line Management Functional Descriptor structure according to the 5.3.3 in PSTN specification */ typedef struct _usb_host_cdc_direct_line_desc_struct { uint8_t bFunctionLength; /*!<Size of this descriptor in bytes.*/ uint8_t bDescriptorType; /*!<CS_INTERFACE.*/ uint8_t bDescriptorSubtype; /*!<Direct Line Management functional descriptor subtype,.*/ uint8_t bmCapabilities; /*!<The capabilities that this configuration supports.*/ } usb_host_cdc_direct_line_desc_struct_t; /*! @brief CDC Telephone Ringer Functional Descriptor structure according to the 5.3.4 in PSTN specification */ typedef struct _usb_host_cdc_telephone_ringer_desc_struct { uint8_t bFunctionLength; /*!<Size of this descriptor in bytes.*/ uint8_t bDescriptorType; /*!<CS_INTERFACE.*/ uint8_t bDescriptorSubtype; /*!<Telephone Ringer functional descriptor subtype*/ uint8_t bRingerVolSteps; /*!<Number of discrete steps in volume supported by the ringer,.*/ uint8_t bNumRingerPatterns; /*!<Number of ringer patterns supported.*/ } usb_host_cdc_telephone_ringer_desc_struct_t; /*! @brief CDC Telephone Call and Line State Reporting Capabilities Descriptor structure according to the 5.3.6 in PSTN * specification */ typedef struct _usb_host_cdc_tcLsr_desc_struct { uint8_t bFunctionLength; /*!<Size of this descriptor in bytes.*/ uint8_t bDescriptorType; /*!<CS_INTERFACE.*/ uint8_t bDescriptorSubtype; /*!<Telephone Call State Reporting Capabilities descriptor subtype.*/ uint8_t bmCapabilities[4]; /*!<Call and line state reporting capabilities of the device.*/ } usb_host_cdc_tcLsr_desc_struct_t; /*! @brief CDC Header Functional Descriptor structure according to the 5.2.3 in CDC specification */ typedef struct _usb_host_cdc_union_interface_desc_struct { uint8_t bFunctionLength; /*!<Size of this descriptor in bytes.*/ uint8_t bDescriptorType; /*!<CS_INTERFACE descriptor type.*/ uint8_t bDescriptorSubtype; /*!<Union Functional Descriptor SubType.*/ uint8_t bControlInterface; /*!<USB Class Definitions for Communications Devices Specification release number in binary-coded decimal.*/ } usb_host_cdc_union_interface_desc_struct_t; /*! @brief CDC Telephone Operational Modes Functional Descriptor structure according to the 5.3.5 in PSTN specification */ typedef struct _usb_host_cdc_tom_desc_struct { uint8_t bFunctionLength; /*!<Size of this descriptor in bytes.*/ uint8_t bDescriptorType; /*!<CS_INTERFACE.*/ uint8_t bDescriptorSubtype; /*!<Telephone Operational Modes functional descriptor subtype.*/ uint8_t bmCapabilities; /*!<Operational modes:.*/ } usb_host_cdc_tom_desc_struct_t; /*! @brief CDC common Functional Descriptor structure */ typedef struct _usb_host_cdc_common_desc_struct { uint8_t bFunctionLength; /*!<Size of this descriptor in bytes.*/ uint8_t bDescriptorType; /*!<CS_INTERFACE descriptor type.*/ uint8_t bDescriptorSubtype; /*!<Header functional descriptor subtype.*/ } usb_host_cdc_common_desc_struct_t; /*! @brief CDC union Functional Descriptor structure for analyze a class-specific descriptor */ typedef union _usb_cdc_func_desc_struct { usb_host_cdc_common_desc_struct_t common; usb_host_cdc_head_function_desc_struct_t head; usb_host_cdc_union_interface_desc_struct_t unionDesc; usb_host_cdc_call_manage_desc_struct_t callManage; usb_host_cdc_abstract_control_desc_struct_t acm; usb_host_cdc_direct_line_desc_struct_t dl; usb_host_cdc_telephone_ringer_desc_struct_t tr; usb_host_cdc_tom_desc_struct_t tom; usb_host_cdc_tcLsr_desc_struct_t tcLsr; } usb_cdc_func_desc_struct_t; typedef struct _usb_host_cdc_instance_struct { usb_host_handle hostHandle; /*!< The handle of the USB host. */ usb_device_handle deviceHandle; /*!< The handle of the USB device structure. */ usb_host_interface_handle controlInterfaceHandle; /*!< The handle of the CDC device control interface. */ usb_host_interface_handle dataInterfaceHandle; /*!< The handle of the CDC device data interface. */ usb_host_pipe_handle interruptPipe; /*!< Interrupt pipe for the CDC device data interface. */ usb_host_pipe_handle controlPipe; /*!< Control pipe*/ usb_host_pipe_handle inPipe; /*!< CDC bulk in pipe*/ usb_host_pipe_handle outPipe; /*!< CDC bulk out pipe*/ usb_host_cdc_head_function_desc_struct_t *headDesc; /*!< CDC class-specific head function descriptor*/ usb_host_cdc_call_manage_desc_struct_t *callManageDesc; /*!< cdCDCc class-specific call manage descriptor*/ usb_host_cdc_abstract_control_desc_struct_t *abstractControlDesc; /*!< CDC class-specific abstract control descriptor*/ usb_host_cdc_union_interface_desc_struct_t *unionInterfaceDesc; /*!< CDC class-specific union function descriptor*/ void *interruptCallbackParam; /*!< CDC interrupt in transfer callback parameter*/ void *controlCallbackParam; /*!< CDC control transfer callback parameter*/ void *inCallbackParam; /*!< CDC bulk in transfer callback parameter*/ void *outCallbackParam; /*!< CDC bulk out transfer callback parameter*/ usb_host_transfer_t *controlTransfer; /*!< Ongoing control transfer*/ transfer_callback_t controlCallbackFn; /*!< CDC control transfer callback function pointer*/ transfer_callback_t interruptCallbackFn; /*!< CDC interrupt transfer callback function pointer*/ transfer_callback_t outCallbackFn; /*!< CDC bulk out transfer callback function pointer*/ transfer_callback_t inCallbackFn; /*!< CDC bulk in transfer callback function pointer*/ #if ((defined USB_HOST_CONFIG_CLASS_AUTO_CLEAR_STALL) && USB_HOST_CONFIG_CLASS_AUTO_CLEAR_STALL) uint8_t *stallDataBuffer; /*!< Keep the data buffer for stall transfer's data*/ uint32_t stallDataLength; /*!< Keep the data length for stall transfer's data*/ #endif uint16_t packetSize; /*!< CDC control pipe maximum packet size*/ uint16_t bulkOutPacketSize; /*!< CDC bulk out maximum packet size*/ uint16_t bulkInPacketSize; /*!< CDC bulk in maximum packet size*/ } usb_host_cdc_instance_struct_t; #ifdef __cplusplus extern "C" { #endif /******************************************************************************* * API ******************************************************************************/ /*! * @name USB CDC host class driver * @{ */ /*! * @brief Initializes the CDC instance. * * This function allocates the resource for the CDC instance. * * @param deviceHandle The device handle. * @param classHandle Returns class handle. * * @retval kStatus_USB_Success The device is initialized successfully. * @retval kStatus_USB_AllocFail Allocate memory fail. */ extern usb_status_t USB_HostCdcInit(usb_device_handle deviceHandle, usb_host_class_handle *classHandle); /*! * @brief CDC set data interface callback and opens pipes. * * @param[in] classHandle The class handle. * @param[in] interfaceHandle The interface handle. * @param[in] alternateSetting The alternate setting value. * @param[in] callbackFn This callback is called after this function completes. * @param[in] callbackParam The first parameter in the callback function. * * @retval kStatus_USB_Success The device is initialized successfully. * @retval kStatus_USB_InvalidHandle The classHandle is NULL pointer. * @retval kStatus_USB_Busy There is no idle transfer. * @retval kStatus_USB_Error Send transfer fail. See the USB_HostSendSetup. * @retval kStatus_USB_Busy Callback return status, there is no idle pipe. * @retval kStatus_USB_TransferStall Callback return status, the transfer is stalled by the device. * @retval kStatus_USB_Error Callback return status, open pipe fail. See the USB_HostOpenPipe. */ extern usb_status_t USB_HostCdcSetDataInterface(usb_host_class_handle classHandle, usb_host_interface_handle interfaceHandle, uint8_t alternateSetting, transfer_callback_t callbackFn, void *callbackParam); /*! * @brief CDC set control interface callback and opens pipes. * * @param[in] classHandle The class handle. * @param[in] interfaceHandle The interface handle. * @param[in] alternateSetting The alternate setting value. * @param[in] callbackFn This callback is called after this function completes. * @param[in] callbackParam The first parameter in the callback function. * * @retval kStatus_USB_Success The device is initialized successfully. * @retval kStatus_USB_InvalidHandle The classHandle is NULL pointer. * @retval kStatus_USB_Busy There is no idle transfer. * @retval kStatus_USB_Error Send transfer fail. See the USB_HostSendSetup. * @retval kStatus_USB_Busy Callback return status, there is no idle pipe. * @retval kStatus_USB_TransferStall Callback return status, the transfer is stalled by the device. * @retval kStatus_USB_Error Callback return status, open pipe fail. See the USB_HostOpenPipe. */ extern usb_status_t USB_HostCdcSetControlInterface(usb_host_class_handle classHandle, usb_host_interface_handle interfaceHandle, uint8_t alternateSetting, transfer_callback_t callbackFn, void *callbackParam); /*! * @brief Deinitializes the CDC instance. * * This function frees the resource for the CDC instance. * * @param deviceHandle The device handle. * @param classHandle The class handle. * * @retval kStatus_USB_Success The device is de-initialized successfully. */ extern usb_status_t USB_HostCdcDeinit(usb_device_handle deviceHandle, usb_host_class_handle classHandle); /*! * @brief Gets the pipe maximum packet size. * * @param[in] classHandle The class handle. * @param[in] pipeType Its value is USB_ENDPOINT_CONTROL, USB_ENDPOINT_ISOCHRONOUS, USB_ENDPOINT_BULK or * USB_ENDPOINT_INTERRUPT. * See the usb_spec.h * @param[in] direction Pipe direction. * * @retval 0 The classHandle is NULL. * @retval max Packet size. */ extern uint16_t USB_HostCdcGetPacketsize(usb_host_class_handle classHandle, uint8_t pipeType, uint8_t direction); /*! * @brief Receives data. * * This function implements the CDC receiving data. * * @param classHandle The class handle. * @param buffer The buffer pointer. * @param bufferLength The buffer length. * @param callbackFn This callback is called after this function completes. * @param callbackParam The first parameter in the callback function. * * @retval kStatus_USB_Success Receive request successfully. * @retval kStatus_USB_InvalidHandle The classHandle is NULL pointer. * @retval kStatus_USB_Busy There is no idle transfer. * @retval kStatus_USB_Error Pipe is not initialized. * Or, send transfer fail. See the USB_HostRecv. */ extern usb_status_t USB_HostCdcDataRecv(usb_host_class_handle classHandle, uint8_t *buffer, uint32_t bufferLength, transfer_callback_t callbackFn, void *callbackParam); /*! * @brief Sends data. * * This function implements the CDC sending data. * * @param classHandle The class handle. * @param buffer The buffer pointer. * @param bufferLength The buffer length. * @param callbackFn This callback is called after this function completes. * @param callbackParam The first parameter in the callback function. * * @retval kStatus_USB_Success Receive request successfully. * @retval kStatus_USB_InvalidHandle The classHandle is NULL pointer. * @retval kStatus_USB_Busy There is no idle transfer. * @retval kStatus_USB_Error Pipe is not initialized. * Or, send transfer fail. See the USB_HostSend. */ extern usb_status_t USB_HostCdcDataSend(usb_host_class_handle classHandle, uint8_t *buffer, uint32_t bufferLength, transfer_callback_t callbackFn, void *callbackParam); /*! * @brief Interrupts the receive data. * * This function implements the interrupt receiving data. * * @param classHandle The class handle. * @param buffer The buffer pointer. * @param bufferLength The buffer length. * @param callbackFn This callback is called after this function completes. * @param callbackParam The first parameter in the callback function. * * @retval kStatus_USB_Success Receive request successfully. * @retval kStatus_USB_InvalidHandle The classHandle is NULL pointer. * @retval kStatus_USB_Busy There is no idle transfer. * @retval kStatus_USB_Error Pipe is not initialized. * Or, send transfer fail. See the USB_HostRecv. */ extern usb_status_t USB_HostCdcInterruptRecv(usb_host_class_handle classHandle, uint8_t *buffer, uint32_t bufferLength, transfer_callback_t callbackFn, void *callbackParam); /*! * @brief CDC get line coding. * * This function implements the CDC GetLineCoding request. See the PSTN specification. * * @param classHandle The class handle. * @param uartLineCoding The line coding pointer. * @param callbackFn This callback is called after this function completes. * @param callbackParam The first parameter in the callback function. * * @retval kStatus_USB_Success Request successful. * @retval kStatus_USB_InvalidHandle The classHandle is NULL pointer. * @retval kStatus_USB_Busy There is no idle transfer. * @retval kStatus_USB_Error Send transfer fail. See the USB_HostSendSetup. */ extern usb_status_t USB_HostCdcGetAcmLineCoding(usb_host_class_handle classHandle, usb_host_cdc_line_coding_struct_t *uartLineCoding, transfer_callback_t callbackFn, void *callbackParam); /*! * @brief CDC setControlLineState. * * This function implements the CDC etControlLineState request. See PSTN specification. * * @param classHandle The class handle. * @param dtr The DRS value. * @param rts The RTS value. * @param callbackFn This callback is called after this function completes. * @param callbackParam The first parameter in the callback function. * * @retval kStatus_USB_Success Request successful. * @retval kStatus_USB_InvalidHandle The classHandle is NULL pointer. * @retval kStatus_USB_Busy There is no idle transfer. * @retval kStatus_USB_Error Send transfer fail. See the USB_HostSendSetup. */ extern usb_status_t USB_HostCdcSetAcmCtrlState( usb_host_class_handle classHandle, uint8_t dtr, uint8_t rts, transfer_callback_t callbackFn, void *callbackParam); /*! * @brief cdc send encapsulated command. * * This function implements cdc SEND_ENCAPSULATED_COMMAND request.refer to cdc 1.2 spec. * * @param classHandle the class handle. * @param buffer the buffer pointer. * @param bufferLength the buffer length. * @param callbackFn this callback is called after this function completes. * @param callbackParam the first parameter in the callback function. * * @retval kStatus_USB_Success request successfully. * @retval kStatus_USB_InvalidHandle The classHandle is NULL pointer. * @retval kStatus_USB_Busy There is no idle transfer. * @retval kStatus_USB_Error send transfer fail, please reference to USB_HostSendSetup. */ usb_status_t USB_HostCdcSendEncapsulatedCommand(usb_host_class_handle classHandle, uint8_t *buffer, uint16_t bufferLength, transfer_callback_t callbackFn, void *callbackParam); /*! * @brief cdc get encapsulated response. * * This function implements cdc GET_ENCAPSULATED_RESPONSE request.refer to cdc 1.2 spec. * * @param classHandle the class handle. * @param buffer the buffer pointer. * @param bufferLength the buffer length. * @param callbackFn this callback is called after this function completes. * @param callbackParam the first parameter in the callback function. * * @retval kStatus_USB_Success request successfully. * @retval kStatus_USB_InvalidHandle The classHandle is NULL pointer. * @retval kStatus_USB_Busy There is no idle transfer. * @retval kStatus_USB_Error send transfer fail, please reference to USB_HostSendSetup. */ usb_status_t USB_HostCdcGetEncapsulatedResponse(usb_host_class_handle classHandle, uint8_t *buffer, uint16_t bufferLength, transfer_callback_t callbackFn, void *callbackParam); /*! * @brief CDC gets the ACM descriptor. * * This function is hunting for the class-specific ACM descriptor in the configuration and gets the corresponding * descriptor. * * @param classHandle The class handle. * @param headDesc The head function descriptor pointer. * @param callManageDesc The call management functional descriptor pointer. * @param abstractControlDesc The abstract control management functional pointer. * @param unionInterfaceDesc The union functional descriptor pointer. * * @retval kStatus_USB_Error Analyse descriptor error. */ extern usb_status_t USB_HostCdcGetAcmDescriptor(usb_host_class_handle classHandle, usb_host_cdc_head_function_desc_struct_t **headDesc, usb_host_cdc_call_manage_desc_struct_t **callManageDesc, usb_host_cdc_abstract_control_desc_struct_t **abstractControlDesc, usb_host_cdc_union_interface_desc_struct_t **unionInterfaceDesc); /*! * @brief CDC send control transfer common code. * * @param classHandle The class handle. * @param request_type Set up the packet request type. * @param request Set up the packet request value. * @param wvalue_l Set up the packet wvalue low byte. * @param wvalue_h Set up the packet wvalue high byte. * @param wlength Set up the packet wlength value. * @param data Data buffer pointer * @param callbackFn This callback is called after this function completes. * @param callbackParam The first parameter in the callback function. * * @return An error code or kStatus_USB_Success. */ extern usb_status_t USB_HostCdcControl(usb_host_class_handle classHandle, uint8_t request_type, uint8_t request, uint8_t wvalue_l, uint8_t wvalue_h, uint16_t wlength, uint8_t *data, transfer_callback_t callbackFn, void *callbackParam); /*@}*/ #ifdef __cplusplus } #endif /*@}*/ #endif /*__USB_HOST_CDC_H__*/
e1ce7b23c43091ed349b747c5cdd6a32ec4be0db
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
/x11/modular-xorg-server112/patches/patch-glx_rensize.c
b14f242cd119953184ca19111107e9d791a2e6e0
[]
no_license
jsonn/pkgsrc
fb34c4a6a2d350e8e415f3c4955d4989fcd86881
c1514b5f4a3726d90e30aa16b0c209adbc276d17
refs/heads/trunk
2021-01-24T09:10:01.038867
2017-07-07T15:49:43
2017-07-07T15:49:43
2,095,004
106
47
null
2016-09-19T09:26:01
2011-07-23T23:49:04
Makefile
UTF-8
C
false
false
2,950
c
patch-glx_rensize.c
$NetBSD: patch-glx_rensize.c,v 1.1 2015/04/03 09:46:18 tnn Exp $ X.Org Security Advisory: Dec. 9, 2014 Protocol handling issues in X Window System servers --- glx/rensize.c.orig 2012-05-17 17:09:02.000000000 +0000 +++ glx/rensize.c @@ -52,7 +52,7 @@ Map1Size(GLint k, GLint order) } int -__glXMap1dReqSize(const GLbyte * pc, Bool swap) +__glXMap1dReqSize(const GLbyte * pc, Bool swap, int reqlen) { GLenum target; GLint order, k; @@ -68,7 +68,7 @@ __glXMap1dReqSize(const GLbyte * pc, Boo } int -__glXMap1fReqSize(const GLbyte * pc, Bool swap) +__glXMap1fReqSize(const GLbyte * pc, Bool swap, int reqlen) { GLenum target; GLint order, k; @@ -92,7 +92,7 @@ Map2Size(int k, int majorOrder, int mino } int -__glXMap2dReqSize(const GLbyte * pc, Bool swap) +__glXMap2dReqSize(const GLbyte * pc, Bool swap, int reqlen) { GLenum target; GLint uorder, vorder, k; @@ -110,7 +110,7 @@ __glXMap2dReqSize(const GLbyte * pc, Boo } int -__glXMap2fReqSize(const GLbyte * pc, Bool swap) +__glXMap2fReqSize(const GLbyte * pc, Bool swap, int reqlen) { GLenum target; GLint uorder, vorder, k; @@ -342,13 +342,14 @@ __glXTypeSize(GLenum enm) } int -__glXDrawArraysReqSize(const GLbyte * pc, Bool swap) +__glXDrawArraysReqSize(const GLbyte * pc, Bool swap, int reqlen) { __GLXdispatchDrawArraysHeader *hdr = (__GLXdispatchDrawArraysHeader *) pc; __GLXdispatchDrawArraysComponentHeader *compHeader; GLint numVertexes = hdr->numVertexes; GLint numComponents = hdr->numComponents; GLint arrayElementSize = 0; + GLint x, size; int i; if (swap) { @@ -357,6 +358,13 @@ __glXDrawArraysReqSize(const GLbyte * pc } pc += sizeof(__GLXdispatchDrawArraysHeader); + reqlen -= sizeof(__GLXdispatchDrawArraysHeader); + + size = safe_mul(sizeof(__GLXdispatchDrawArraysComponentHeader), + numComponents); + if (size < 0 || reqlen < 0 || reqlen < size) + return -1; + compHeader = (__GLXdispatchDrawArraysComponentHeader *) pc; for (i = 0; i < numComponents; i++) { @@ -400,17 +408,18 @@ __glXDrawArraysReqSize(const GLbyte * pc return -1; } - arrayElementSize += __GLX_PAD(numVals * __glXTypeSize(datatype)); + x = safe_pad(safe_mul(numVals, __glXTypeSize(datatype))); + if ((arrayElementSize = safe_add(arrayElementSize, x)) < 0) + return -1; pc += sizeof(__GLXdispatchDrawArraysComponentHeader); } - return ((numComponents * sizeof(__GLXdispatchDrawArraysComponentHeader)) + - (numVertexes * arrayElementSize)); + return safe_add(size, safe_mul(numVertexes, arrayElementSize)); } int -__glXSeparableFilter2DReqSize(const GLbyte * pc, Bool swap) +__glXSeparableFilter2DReqSize(const GLbyte * pc, Bool swap, int reqlen) { __GLXdispatchConvolutionFilterHeader *hdr = (__GLXdispatchConvolutionFilterHeader *) pc;
91e41bba071391486113563a8b78819c98533aaa
bc010403013ffe60d43950224c1921982d83cbc1
/inc/tpg_trace.h
f2071577e84f73c0619cdf56ece766b42ea91ed8
[ "BSD-3-Clause" ]
permissive
Juniper/warp17
69f11fbd1a9b8c7aa9c2eb9291a8e0e108193a6e
f51cc6b8f1da7ca9703c7fbb951a638ae4a0e9dc
refs/heads/dev/common
2023-09-04T12:59:33.140329
2020-09-28T10:49:23
2020-09-28T10:49:23
59,734,760
412
88
BSD-3-Clause
2022-10-02T04:27:14
2016-05-26T08:47:40
C
UTF-8
C
false
false
10,497
h
tpg_trace.h
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * Copyright (c) 2016, Juniper Networks, Inc. All rights reserved. * * * The contents of this file are subject to the terms of the BSD 3 clause * License (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at * https://github.com/Juniper/warp17/blob/master/LICENSE. * * 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. * * File name: * tpg_trace.h * * Description: * In memory tracing module interface. * * Author: * Dumitru Ceara, Eelco Chaudron * * Initial Created: * 05/19/2015 * * Notes: * */ /***************************************************************************** * Multiple include protection ****************************************************************************/ #ifndef _H_TPG_TRACE_ #define _H_TPG_TRACE_ /***************************************************************************** * Trace buffer component definition ****************************************************************************/ typedef char * (*trace_printer_fmt_cb_t)(const char *data, uint32_t len); /***************************************************************************** * Trace buffer definition (one circular buffer per component per core) ****************************************************************************/ typedef struct trace_buffer_s { /* Bit field for trace_buf_flags: */ uint32_t tb_enabled :1; uint32_t tb_filled :1; uint32_t tb_size; uint32_t tb_start; uint32_t tb_end; uint32_t tb_lvl; char *tb_buf; } __rte_cache_aligned trace_buffer_t; typedef struct trace_comp_s { uint32_t tc_comp_id; trace_buffer_t *tc_buffers; trace_printer_fmt_cb_t tc_fmt; uint32_t tc_disabled :1; } __rte_cache_aligned trace_comp_t; typedef enum trace_level_s { TRACE_LVL_CRIT, TRACE_LVL_ERROR, TRACE_LVL_INFO, TRACE_LVL_LOG, TRACE_LVL_DEBUG, TRACE_LVL_MAX } trace_level_t; /***************************************************************************** * Trace helper macros. ****************************************************************************/ #define TRACE_BUF_GET_LEVEL(tb) ((tb)->tb_lvl) #define TRACE_BUF_SET_LEVEL(tb, lvl) \ do { \ assert((lvl) < TRACE_LVL_MAX); \ (tb)->tb_lvl = (lvl); \ } while (0) /***************************************************************************** * Trace external variables. ****************************************************************************/ extern bool trace_disabled; extern trace_comp_t trace_components[TRACE_MAX]; /***************************************************************************** * Trace inline functions. ***************************************************************************** * trace_level_str() ****************************************************************************/ static inline __attribute__((always_inline)) const char *trace_level_str(trace_level_t lvl) { switch (lvl) { case TRACE_LVL_CRIT: return "CRI"; case TRACE_LVL_ERROR: return "ERR"; case TRACE_LVL_LOG: return "LOG"; case TRACE_LVL_INFO: return "INF"; case TRACE_LVL_DEBUG: return "DBG"; default: return "Unknown"; } return "Unknown"; } /***************************************************************************** * trace_get_comp_pointer() ****************************************************************************/ static inline __attribute__((always_inline)) trace_comp_t *trace_get_comp_pointer(uint32_t id) { if (unlikely(id >= TRACE_MAX)) return NULL; return &trace_components[id]; } /***************************************************************************** * trace_get_pointer_from_comp() ****************************************************************************/ static inline __attribute__((always_inline)) trace_buffer_t *trace_get_pointer_from_comp(const trace_comp_t *tc, int lcore_idx) { if (unlikely(tc == NULL)) return NULL; return &tc->tc_buffers[lcore_idx]; } /***************************************************************************** * trace_get_pointer() ****************************************************************************/ static inline __attribute__((always_inline)) trace_buffer_t *trace_get_pointer(uint32_t id, int lcore_idx) { return trace_get_pointer_from_comp(trace_get_comp_pointer(id), lcore_idx); } /***************************************************************************** * trace_allowed() ****************************************************************************/ static inline __attribute__((always_inline)) bool trace_allowed(int lcore_idx, uint32_t trace_buf_id, trace_level_t level) { trace_comp_t *tc; trace_buffer_t *tb; if (likely(trace_disabled)) return false; tc = trace_get_comp_pointer(trace_buf_id); if (unlikely(!tc)) return false; if (likely(tc->tc_disabled)) return false; tb = trace_get_pointer_from_comp(tc, lcore_idx); if (likely(!tb->tb_enabled)) return false; if (likely(level > TRACE_BUF_GET_LEVEL(tb))) return false; return true; } /***************************************************************************** * Tracing API ****************************************************************************/ extern bool trace_init(void); extern uint32_t trace_get_component_cnt(void); extern trace_comp_t *trace_get_comp_pointer_by_name(const char *name); /* Configuration */ extern void trace_set_core_level(const trace_comp_t *tc, int lcore, const char *lvl); extern const char *trace_get_core_level(const trace_comp_t *tc, int lcore); extern void trace_set_core_bufsize(const trace_comp_t *tc, int lcore, uint32_t bufsize); extern uint32_t trace_get_core_bufsize(const trace_comp_t *tc, int lcore); extern bool trace_get_core_enabled(const trace_comp_t *tc, int lcore); /* Adding traces. */ extern int trace_add_raw(int lcore_idx, uint32_t trace_buf_id, trace_level_t level, const void *data, uint32_t datalen); extern int trace_add_formatted(int lcore_idx, uint32_t trace_buf_id, trace_level_t level, const char *fmt, ...) __attribute__ ((format (printf, 4, 5))); typedef void (*trace_printer_cb_t)(void *arg, trace_level_t lvl, const char *comp_name, const char *data, uint32_t len); /* Dumping traces from raw buffers. */ extern void trace_entry_dump(trace_printer_cb_t printer, void *printer_arg, trace_printer_fmt_cb_t fmt, const char *comp_name, const char *buffer, uint32_t bufsize, uint32_t *start_id, uint32_t *start_pos, uint32_t end_pos); /* Trace component iterator stuff. */ typedef void (*trace_comp_it_cb_t)(const trace_comp_t *tc, void *data); /* Iterates through trace components. Most definitely the callback shouldn't * try to change the trace_comp_t elements. Also it shouldn't be called in fast * path! */ extern void trace_comp_iterate(trace_comp_it_cb_t cb, void *data); /* Actual tracing is done only if support is compiled in. */ #if defined(TPG_DBG_TRACE) #define TRACE(comp, lvl, data, datalen) \ (unlikely(trace_allowed(rte_lcore_index(-1), TRACE_ ## comp, \ TRACE_LVL_ ## lvl)) ? \ trace_add_raw(rte_lcore_index(-1), TRACE_ ## comp, \ TRACE_LVL_ ## lvl, (data), (datalen)) : \ 0) #define TRACE_FMT(comp, lvl, fmt, ...) \ (unlikely(trace_allowed(rte_lcore_index(-1), TRACE_ ## comp, \ TRACE_LVL_ ## lvl)) ? \ trace_add_formatted(rte_lcore_index(-1), TRACE_ ## comp, \ TRACE_LVL_ ## lvl, (fmt), __VA_ARGS__) : \ 0) #else /* defined(TPG_DBG_TRACE) */ #define TRACE(comp, lvl, data, datalen) \ do { \ RTE_SET_USED(data); \ RTE_SET_USED(datalen); \ } while (0) #define TRACE_FMT(comp, lvl, fmt, ...) \ RTE_SET_USED(fmt) #endif /* defined(TPG_DBG_TRACE) */ #endif /* _H_TPG_TRACE_ */
1bb97db6fbd74410284bd42ef9990126fd8455db
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
/PWG/EMCAL/macros/AddTaskEmcalAodTrackFilter.C
b71721b05c44918b518f2d6a8661aa99ff1cd4d1
[]
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
627
c
AddTaskEmcalAodTrackFilter.C
static AliEmcalAodTrackFilterTask* AddTaskEmcalAodTrackFilter( const char *name = "FilterTracks", const char *inname = "tracks", const char *runperiod = "", const char *taskName = "AliEmcalAodTrackFilterTask", const char *suffix = "" ){ return AliEmcalAodTrackFilterTask::AddTaskEmcalAodTrackFilter(name,inname,runperiod,taskName,suffix); }
6da7968d15ba263e962c87470ea79f963c47c636
552b4df0d31a97cad18dbb8b1a3437e80b6f6dad
/src/bbccon.c
00c9756277b838d12d55fab3c531169ba4bc4e9b
[ "Zlib" ]
permissive
rtrussell/BBCSDL
65477d503f14dc7af1727ef8dce13ce80fc4c849
ae588d80bc303897b5da5e108863e0c07fdb30d8
refs/heads/master
2023-08-25T20:17:25.350123
2023-08-12T10:44:45
2023-08-12T10:44:45
163,871,226
145
31
Zlib
2023-03-23T23:22:44
2019-01-02T17:44:35
C
UTF-8
C
false
false
42,979
c
bbccon.c
/******************************************************************\ * BBC BASIC Minimal Console Version * * Copyright (C) R. T. Russell, 2021-2023 * * * * bbccon.c Main program, Initialisation, Keyboard handling * * Version 0.44a, 25-Jul-2023 * \******************************************************************/ #define _GNU_SOURCE #define __USE_GNU #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <unistd.h> #include <string.h> #include <time.h> #include <math.h> #include "bbccon.h" #define HISTORY 100 // Number of items in command history #define ESCTIME 200 // Milliseconds to wait for escape sequence #define QRYTIME 1000 // Milliseconds to wait for cursor query response #define QSIZE 32 // Twice longest expected escape sequence #ifdef _WIN32 #include <windows.h> #include <conio.h> typedef int timer_t ; #undef WM_APP #define myftell _ftelli64 #define myfseek _fseeki64 #define PLATFORM "Win32" #define realpath(N,R) _fullpath((R),(N),_MAX_PATH) #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4 #define DISABLE_NEWLINE_AUTO_RETURN 0x8 #define ENABLE_VIRTUAL_TERMINAL_INPUT 0x200 BOOL WINAPI K32EnumProcessModules (HANDLE, HMODULE*, DWORD, LPDWORD) ; #else #include <termios.h> #include <signal.h> #include <pthread.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/ioctl.h> #include "dlfcn.h" #define myftell ftell #define myfseek fseek #define PLATFORM "Linux" #define WM_TIMER 275 #endif #ifdef __WIN64__ #undef PLATFORM #define PLATFORM "Win64" #endif #ifdef __APPLE__ #include <dispatch/dispatch.h> #include <mach-o/dyld.h> typedef dispatch_source_t timer_t ; dispatch_queue_t timerqueue ; #undef PLATFORM #define PLATFORM "MacOS" #endif #undef MAX_PATH #define MAX(X,Y) (((X) > (Y)) ? (X) : (Y)) // Program constants: #define SCREEN_WIDTH 640 #define SCREEN_HEIGHT 500 #define MAX_PATH 260 #define AUDIOLEN 441 * 4 // Global variables (external linkage): void *userRAM = NULL ; void *progRAM = NULL ; void *userTOP = NULL ; const int bLowercase = 0 ; // Dummy const char szVersion[] = "BBC BASIC for "PLATFORM" Console "VERSION ; const char szNotice[] = "(C) Copyright R. T. Russell, "YEAR ; char *szLoadDir ; char *szLibrary ; char *szUserDir ; char *szTempDir ; char *szCmdLine ; int MaximumRAM = MAXIMUM_RAM ; timer_t UserTimerID ; unsigned int palette[256] ; // Array of VDU command lengths: static int vdulen[] = { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 5, 0, 0, 1, 9, 8, 5, 0, 1, 4, 4, 0, 2 } ; // Keycode translation table: static unsigned char xkey[64] = { 0, 139, 138, 137, 136, 0, 131, 0, 130, 0, 0, 0, 0, 0, 0, 0, 145, 146, 147, 148, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 134, 135, 0, 132, 133, 0, 0, 0, 0, 0, 0, 0, 0, 149, 0, 150, 151, 152, 153, 154, 0, 155, 156, 0, 0, 0, 0, 0, 0, 0 } ; // Declared in bbcans.c: void oscli (char *) ; void xeqvdu (int, int, int) ; char *setup (char *, char *, char *, char, unsigned char *) ; // Declared in bbmain.c: void error (int, const char *) ; void text (const char *) ; // Output NUL-terminated string void crlf (void) ; // Output a newline // Declared in bbeval.c: unsigned int rnd (void) ; // Return a pseudo-random number // Interpreter entry point: int basic (void *, void *, void *) ; // Forward references: unsigned char osbget (void*, int*) ; void osbput (void*, unsigned char) ; void quiet (void) ; // Dummy functions: void gfxPrimitivesSetFont(void) { } ; void gfxPrimitivesGetFont(void) { } ; // File scope variables: static unsigned char inputq[QSIZE] ; static volatile int inpqr = 0, inpqw = 0 ; // Put to STDIN queue: static int putinp (unsigned char inp) { unsigned char bl = inpqw ; unsigned char al = (bl + 1) % QSIZE ; if (al != inpqr) { inputq[bl] = inp ; inpqw = al ; return 1 ; } return 0 ; } // Get from STDIN queue: static int getinp (unsigned char *pinp) { unsigned char bl = inpqr ; if (bl != inpqw) { *pinp = inputq[bl] ; inpqr = (bl + 1) % QSIZE ; return 1 ; } return 0 ; } #ifdef _WIN32 #define RTLD_DEFAULT (void *)(-1) static void *dlsym (void *handle, const char *symbol) { void *procaddr ; HMODULE modules[100] ; long unsigned int i, needed ; K32EnumProcessModules ((HANDLE)-1, modules, sizeof (modules), &needed) ; for (i = 0; i < needed / sizeof (HMODULE); i++) { procaddr = GetProcAddress (modules[i], symbol) ; if (procaddr != NULL) break ; } return procaddr ; } static DWORD WINAPI myThread (void *parm) { int ch ; long unsigned int nread ; while (ReadFile (GetStdHandle(STD_INPUT_HANDLE), &ch, 1, &nread, NULL)) { if (nread) while (putinp (ch) == 0) sleep (0) ; else sleep (0) ; } return 0 ; } #else void *myThread (void *parm) { int ch ; size_t nread ; do { nread = read (STDIN_FILENO, &ch, 1) ; if (nread) while (putinp (ch) == 0) usleep (1) ; else usleep (1) ; } while (nread >= 0) ; return 0 ; } #endif #ifdef __linux__ static void *mymap (unsigned int size) { FILE *fp ; char line[256] ; void *start, *finish, *base = (void *) 0x400000 ; fp = fopen ("/proc/self/maps", "r") ; if (fp == NULL) return NULL ; while (NULL != fgets (line, 256, fp)) { sscanf (line, "%p-%p", &start, &finish) ; start = (void *)((size_t)start & -0x1000) ; // page align (GCC extension) if (start >= (base + size)) return base ; if (finish > (void *)0xFFFFF000) return NULL ; base = (void *)(((size_t)finish + 0xFFF) & -0x1000) ; // page align if (base > ((void *)0xFFFFFFFF - size)) return NULL ; } return base ; } #endif // Put event into event queue, unless full: int putevt (heapptr handler, int msg, int wparam, int lparam) { unsigned char bl = evtqw ; unsigned char al = bl + 8 ; int index = bl >> 2 ; if ((al == evtqr) || (eventq == NULL)) return 0 ; eventq[index] = lparam ; eventq[index + 1] = msg ; eventq[index + 64] = wparam ; eventq[index + 65] = handler ; evtqw = al ; return 1 ; } // Get event from event queue, unless empty: static heapptr getevt (void) { heapptr handler ; unsigned char al = evtqr ; int index = al >> 2 ; flags &= ~ALERT ; if ((al == evtqw) || (eventq == NULL)) return 0 ; lParam = eventq[index] ; iMsg = eventq[index + 1] ; wParam = eventq[index + 64] ; handler = eventq[index + 65] ; al += 8 ; evtqr = al ; if (al != evtqw) flags |= ALERT ; return handler ; } // Put keycode to keyboard queue: static int putkey (char key) { unsigned char bl = kbdqw ; unsigned char al = bl + 1 ; if ((key == 0x1B) && !(flags & ESCDIS)) { flags |= ESCFLG ; return 0 ; } if (al != kbdqr) { keybdq[(int) bl] = key ; kbdqw = al ; return 1 ; } return 0 ; } // Get keycode (if any) from keyboard queue: int getkey (unsigned char *pkey) { unsigned char bl = kbdqr ; if (bl != kbdqw) { *pkey = keybdq[(int) bl] ; kbdqr = bl + 1 ; return 1 ; } return 0 ; } // Get millisecond tick count: unsigned int GetTicks (void) { #ifdef _WIN32 return timeGetTime () ; #else struct timespec ts ; if (clock_gettime (CLOCK_MONOTONIC, &ts)) clock_gettime (CLOCK_REALTIME, &ts) ; return (ts.tv_sec * 1000) + (ts.tv_nsec / 1000000) ; #endif } static int kbchk (void) { return (inpqr != inpqw) ; } static unsigned char kbget (void) { unsigned char ch = 0 ; getinp (&ch) ; return ch ; } static int kwait (unsigned int timeout) { int ready ; timeout += GetTicks () ; while (!(ready = kbchk ()) && (GetTicks() < timeout)) usleep (1) ; return ready ; } // Returns 1 if the cursor position was read successfully or 0 if it was aborted // (in which case *px and *py will be unchanged) or if px and py are both NULL. int stdin_handler (int *px, int *py) { int wait = (px != NULL) || (py != NULL) ; static char report[16] ; static char *p = report, *q = report ; unsigned char ch ; if (wait) { printf ("\033[6n") ; fflush (stdout) ; } do { if (kbchk ()) { ch = kbget () ; if (ch == 0x1B) { if (p != report) q = p ; *p++ = 0x1B ; } else if (p != report) { if (p < report + sizeof(report)) *p++ = ch ; if ((ch >= 'A') && (ch <= '~') && (ch != '[') && (ch != 'O') && ((*(q + 1) == '[') || (*(q + 1) == 'O'))) { p = q ; q = report ; if (ch == 'R') { int row = 0, col = 0 ; if (sscanf (p, "\033[%d;%dR", &row, &col) == 2) { if (px) *px = col - 1 ; if (py) *py = row - 1 ; return 1 ; } } if (ch == '~') { int key ; if (sscanf (p, "\033[%d~", &key)) putkey (xkey[key + 32]) ; } else putkey (xkey[ch - 64]) ; } } else { putkey (ch) ; if (((kbdqr - kbdqw - 1) & 0xFF) < 50) { p = report ; q = report ; wait = 0 ; // abort } } } if ((wait || (p != report)) && !kwait (wait ? QRYTIME : ESCTIME)) { q = report ; while (q < p) putkey (*q++) ; p = report ; q = report ; wait = 0 ; // abort } } while (wait || (p != report)) ; return 0 ; } // Get text cursor (caret) coordinates: void getcsr(int *px, int *py) { if (!stdin_handler (px, py)) { if (px != NULL) *px = -1 ; // Flag unable to read if (py != NULL) *py = -1 ; } } // SOUND Channel,Amplitude,Pitch,Duration void sound (short chan, signed char ampl, unsigned char pitch, unsigned char duration) { } // ENVELOPE N,T,PI1,PI2,PI3,PN1,PN2,PN3,AA,AD,AS,AR,ALA,ALD void envel (signed char *env) { } // Disable sound generation: void quiet (void) { } // Get pixel RGB colour: int vtint (int x, int y) { error (255, "Sorry, not implemented") ; return -1 ; } // Get nearest palette index: int vpoint (int x, int y) { error (255, "Sorry, not implemented") ; return -1 ; } int vgetc (int x, int y) { error (255, "Sorry, not implemented") ; return -1 ; } int osbyte (int al, int xy) { error (255, "Sorry, not implemented") ; return -1 ; } void osword (int al, void *xy) { error (255, "Sorry, not implemented") ; return ; } // Get string width in graphics units: int widths (unsigned char *s, int l) { error (255, "Sorry, not implemented") ; return -1 ; } // ADVAL(n) int adval (int n) { if (n == -1) return (kbdqr - kbdqw - 1) & 0xFF ; error (255, "Sorry, not implemented") ; return -1 ; } // APICALL #ifdef __llvm__ long long apicall_ (long long (*APIfunc) (size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, double, double, double, double, double, double, double, double), PARM *p) { return APIfunc (p->i[0], p->i[1], p->i[2], p->i[3], p->i[4], p->i[5], p->i[6], p->i[7], p->i[8], p->i[9], p->i[10], p->i[11], p->f[0], p->f[1], p->f[2], p->f[3], p->f[4], p->f[5], p->f[6], p->f[7]) ; } double fltcall_ (double (*APIfunc) (size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, double, double, double, double, double, double, double, double), PARM *p) { return APIfunc (p->i[0], p->i[1], p->i[2], p->i[3], p->i[4], p->i[5], p->i[6], p->i[7], p->i[8], p->i[9], p->i[10], p->i[11], p->f[0], p->f[1], p->f[2], p->f[3], p->f[4], p->f[5], p->f[6], p->f[7]) ; } #else #pragma GCC optimize ("O0") long long apicall_ (long long (*APIfunc) (size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t), PARM *p) { #ifdef ARMHF if (p->f[0] == 0.0) memcpy (&p->f[0], &p->i[0], 48) ; #endif long long wrapper (volatile double a, volatile double b, volatile double c, volatile double d, volatile double e, volatile double f, volatile double g, volatile double h) { long long result ; #ifdef _WIN32 static void* savesp ; asm ("mov %%esp,%0" : "=m" (savesp)) ; #endif result = APIfunc (p->i[0], p->i[1], p->i[2], p->i[3], p->i[4], p->i[5], p->i[6], p->i[7], p->i[8], p->i[9], p->i[10], p->i[11]) ; #ifdef _WIN32 asm ("mov %0,%%esp" : : "m" (savesp)) ; #endif return result ; } return wrapper (p->f[0], p->f[1], p->f[2], p->f[3], p->f[4], p->f[5], p->f[6], p->f[7]) ; } double fltcall_ (double (*APIfunc) (size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t, size_t), PARM *p) { #ifdef ARMHF if (p->f[0] == 0.0) memcpy (&p->f[0], &p->i[0], 48) ; #endif double wrapper (volatile double a, volatile double b, volatile double c, volatile double d, volatile double e, volatile double f, volatile double g, volatile double h) { double result ; #ifdef _WIN32 static void* savesp ; asm ("mov %%esp,%0" : "=m" (savesp)) ; #endif result = APIfunc (p->i[0], p->i[1], p->i[2], p->i[3], p->i[4], p->i[5], p->i[6], p->i[7], p->i[8], p->i[9], p->i[10], p->i[11]) ; #ifdef _WIN32 asm ("mov %0,%%esp" : : "m" (savesp)) ; #endif return result ; } return wrapper (p->f[0], p->f[1], p->f[2], p->f[3], p->f[4], p->f[5], p->f[6], p->f[7]) ; } #pragma GCC reset_options #endif // Call a function in the context of the GUI thread: size_t guicall (void *func, PARM *parm) { return apicall_ (func, parm) ; } // Check for Escape (if enabled) and kill: void trap (void) { stdin_handler (NULL, NULL) ; if (flags & KILL) error (-1, NULL) ; // Quit if (flags & ESCFLG) { flags &= ~ESCFLG ; kbdqr = kbdqw ; quiet () ; if (exchan) { fclose (exchan) ; exchan = NULL ; } error (17, NULL) ; // 'Escape' } } // Test for escape, kill, pause, single-step, flash and alert: heapptr xtrap (void) { trap () ; if (flags & ALERT) return getevt () ; return 0 ; } // Report a 'fatal' error: void faterr (const char *msg) { error (512, "") ; } // Read keyboard or F-key expansion: static int rdkey (unsigned char *pkey) { if (keyptr) { *pkey = *keyptr++ ; if (*keyptr == 0) keyptr = NULL ; return 1 ; } while (getkey (pkey)) { int keyno = 0 ; if ((*pkey >= 128) && (*pkey < 156)) keyno = *pkey ^ 144 ; if (keyno >= 24) keyno -= 12 ; if (*pkey == 127) { *pkey = 8 ; keyno = 24 ; } if (keyno) { keyptr = *((unsigned char **)keystr + keyno) ; if (keyptr) { *pkey = *keyptr++ ; if (*keyptr == 0) keyptr = NULL ; } } return 1 ; } return 0 ; } // Wait a maximum period for a keypress, or test key asynchronously: int oskey (int wait) { if (wait >= 0) { unsigned int start = GetTicks () ; while (1) { unsigned char key ; trap () ; if (rdkey (&key)) return (int) key ; if ((unsigned int)(GetTicks () - start) >= wait * 10) return -1 ; usleep (5000) ; } } if (wait == -256) return 's' ; return 0 ; } // Wait for keypress: unsigned char osrdch (void) { unsigned char key ; if (exchan) { if (fread (&key, 1, 1, exchan)) return key ; fclose (exchan) ; exchan = NULL ; } if (optval >> 4) return osbget ((void *)(size_t)(optval >> 4), NULL) ; while (!rdkey (&key)) { usleep (5000) ; trap () ; } return key ; } // Output byte to VDU stream: void oswrch (unsigned char vdu) { unsigned char *pqueue = vduq ; if (optval & 0x0F) { osbput ((void *)(size_t)(optval & 0x0F), vdu) ; return ; } if (spchan) { if (0 == fwrite (&vdu, 1, 1, spchan)) { fclose (spchan) ; spchan = NULL ; } } if (vduq[10] != 0) // Filling queue ? { vduq[9 - vduq[10]] = vdu ; vduq[10] -- ; if (vduq[10] != 0) return ; vdu = vduq[9] ; if (vdu >= 0x80) { xeqvdu (vdu << 8, 0, 0) ; int ecx = (vdu >> 4) & 3 ; if (ecx == 0) ecx++ ; pqueue -= ecx - 9 ; for ( ; ecx > 0 ; ecx--) xeqvdu (*pqueue++ << 8, 0, 0) ; fflush (stdout) ; return ; } } else if (vdu >= 0x20) { if ((vdu >= 0x80) && (vflags & UTF8)) { char ah = (vdu >> 4) & 3 ; if (ah == 0) ah++ ; vduq[10] = ah ; // No. of bytes to follow vduq[9] = vdu ; return ; } xeqvdu (vdu << 8, 0, 0) ; fflush (stdout) ; return ; } else { vduq[10] = vdulen[(int) vdu] ; vduq[9] = vdu ; if (vduq[10] != 0) return ; } // Mapping of VDU queue to UserEvent parameters, // VDU 23 (defchr) has the most parameter bytes: // // 0 ^ // status-> 0 | ev.user.code // V | // h v // g ^ // f | ev.user.data1 // e | // d v // c ^ // b | ev.user.data2 // a | // vduq-> n v xeqvdu (*(int*)(pqueue + 8) & 0xFFFF, *(int*)(pqueue + 4), *(int*)pqueue) ; } // Prepare for outputting an error message: void reset (void) { vduq[10] = 0 ; // Flush VDU queue keyptr = NULL ; // Cancel *KEY expansion optval = 0 ; // Cancel I/O redirection reflag = 0 ; // *REFRESH ON } // Input and edit a string : void osline (char *buffer) { static char *history[HISTORY] = {NULL} ; static int empty = 0 ; int current = empty ; char *eol = buffer ; char *p = buffer ; *buffer = 0x0D ; int n ; while (1) { unsigned char key ; key = osrdch () ; switch (key) { case 0x0A: case 0x0D: n = (char *) memchr (buffer, 0x0D, 256) - buffer ; if (n == 0) return ; if ((current == (empty + HISTORY - 1) % HISTORY) && (0 == memcmp (buffer, history[current], n))) return ; history[empty] = malloc (n + 1) ; memcpy (history[empty], buffer, n + 1) ; empty = (empty + 1) % HISTORY ; if (history[empty]) { free (history[empty]) ; history[empty] = NULL ; } return ; case 8: case 127: if (p > buffer) { char *q = p ; do p-- ; while ((vflags & UTF8) && (*(signed char*)p < -64)) ; oswrch (8) ; memmove (p, q, buffer + 256 - q) ; } break ; case 21: while (p > buffer) { char *q = p ; do p-- ; while ((vflags & UTF8) && (*(signed char*)p < -64)) ; oswrch (8) ; memmove (p, q, buffer + 256 - q) ; } break ; case 130: while (p > buffer) { oswrch (8) ; do p-- ; while ((vflags & UTF8) && (*(signed char*)p < -64)) ; } break ; case 131: while (*p != 0x0D) { oswrch (9) ; do p++ ; while ((vflags & UTF8) && (*(signed char*)p < -64)) ; } break ; case 134: vflags ^= IOFLAG ; if (vflags & IOFLAG) printf ("\033[1 q") ; else printf ("\033[3 q\033[7 q") ; break ; case 135: if (*p != 0x0D) { char *q = p ; do q++ ; while ((vflags & UTF8) && (*(signed char*)q < -64)) ; memmove (p, q, buffer + 256 - q) ; } break ; case 136: if (p > buffer) { oswrch (8) ; do p-- ; while ((vflags & UTF8) && (*(signed char*)p < -64)) ; } break ; case 137: if (*p != 0x0D) { oswrch (9) ; do p++ ; while ((vflags & UTF8) && (*(signed char*)p < -64)) ; } break ; case 138: case 139: if (key == 138) n = (current + 1) % HISTORY ; else n = (current + HISTORY - 1) % HISTORY ; if (history[n]) { char *s = history[n] ; while (*p != 0x0D) { oswrch (9) ; do p++ ; while ((vflags & UTF8) && (*(signed char*)p < -64)) ; } while (p > buffer) { oswrch (127) ; do p-- ; while ((vflags & UTF8) && (*(signed char*)p < -64)) ; } while ((*s != 0x0D) && (p < (buffer + 255))) { oswrch (*s) ; *p++ = *s++ ; } *p = 0x0D ; current = n ; } break ; case 9: case 132: case 133: case 140: case 141: break ; default: if (p < (buffer + 255)) { if (key != 0x0A) { oswrch (key) ; } if (key >= 32) { memmove (p + 1, p, buffer + 255 - p) ; *p++ = key ; *(buffer + 255) = 0x0D ; if ((*p != 0x0D) && (vflags & IOFLAG)) { char *q = p ; do q++ ; while ((vflags & UTF8) && (*(signed char*)q < -64)) ; memmove (p, q, buffer + 256 - q) ; } } } } if (*p != 0x0D) { oswrch (23) ; oswrch (1) ; for (n = 8 ; n != 0 ; n--) oswrch (0) ; } n = 0 ; while (*p != 0x0D) { oswrch (*p++) ; n++ ; } for (int i = 0; i < (eol - p); i++) oswrch (32) ; for (int i = 0; i < (eol - p); i++) oswrch (8) ; eol = p ; while (n) { if (!(vflags & UTF8) || (*(signed char*)p >= -64)) oswrch (8) ; p-- ; n-- ; } if (*p != 0x0D) { oswrch (23) ; oswrch (1) ; oswrch (1) ; for (n = 7 ; n != 0 ; n--) oswrch (0) ; } } } // Get TIME int getime (void) { unsigned int n = GetTicks () ; if (n < lastick) timoff += 0x19999999 ; lastick = n ; return n / 10 + timoff ; } int getims (void) { char *at ; time_t tt ; time (&tt) ; at = ctime (&tt) ; *(int *)(accs + 0) = *(int *)(at + 0) ; // Day-of-week *(int *)(accs + 4) = *(int *)(at + 8) ; // Day-of-month *(int *)(accs + 7) = *(int *)(at + 4) ; // Month *(int *)(accs + 11) = *(int *)(at + 20) ; // Year if (*(accs + 4) == ' ') *(accs + 4) = '0' ; memcpy (accs + 16, at + 11, 8) ; // Time accs[3] = '.' ; accs[15] = ',' ; return 24 ; } // Put TIME void putime (int n) { lastick = GetTicks () ; timoff = n - lastick / 10 ; } // Wait for a specified number of centiseconds: // On some platforms specifying a negative value causes a task switch void oswait (int cs) { unsigned int start = GetTicks () ; if (cs < 0) { sleep (0) ; return ; } cs *= 10 ; do { trap () ; usleep (1000) ; } while ((unsigned int)(GetTicks () - start) < cs) ; } // MOUSE x%, y%, b% void mouse (int *px, int *py, int *pb) { if (px) *px = 0 ; if (py) *py = 0 ; if (pb) *pb = 0 ; } // MOUSE ON [type] void mouseon (int type) { } // MOUSE OFF void mouseoff (void) { } // MOUSE TO x%, y% void mouseto (int x, int y) { } // Get address of an API function: void *sysadr (char *name) { void *addr = NULL ; if (addr != NULL) return addr ; return dlsym (RTLD_DEFAULT, name) ; } // Call an emulated OS subroutine (if CALL or USR to an address < 0x10000) int oscall (int addr) { int al = stavar[1] ; void *xy = (void *) ((size_t)stavar[24] | ((size_t)stavar[25] << 8)) ; switch (addr) { case 0xFFE0: // OSRDCH return (int) osrdch () ; case 0xFFE3: // OSASCI if (al != 0x0D) { oswrch (al) ; return 0 ; } case 0xFFE7: // OSNEWL crlf () ; return 0 ; case 0xFFEE: // OSWRCH oswrch (al) ; return 0 ; case 0xFFF1: // OSWORD memcpy (xy + 1, &bbcfont[*(unsigned char*)(xy) << 3], 8) ; return 0 ; case 0xFFF4: // OSBYTE return (vgetc (0x80000000, 0x80000000) << 8) ; case 0xFFF7: // OSCLI oscli (xy) ; return 0 ; default: error (8, NULL) ; // 'Address out of range' } return 0 ; } // Request memory allocation above HIMEM: heapptr oshwm (void *addr, int settop) { #ifdef _WIN32 if ((addr < userRAM) || (addr > (userRAM + MaximumRAM)) || (NULL == VirtualAlloc (userRAM, addr - userRAM, MEM_COMMIT, PAGE_EXECUTE_READWRITE))) return 0 ; #else if ((addr < userRAM) || (addr > (userRAM + MaximumRAM))) return 0 ; #endif else { if (settop && (addr > userTOP)) userTOP = addr ; return (size_t) addr ; } } // Get a file context from a channel number: static FILE *lookup (void *chan) { FILE *file = NULL ; if ((chan >= (void *)1) && (chan <= (void *)(MAX_PORTS + MAX_FILES))) file = (FILE*) filbuf[(size_t)chan] ; else file = (FILE*) chan ; if (file == NULL) error (222, "Invalid channel") ; return file ; } // Load a file into memory: void osload (char *p, void *addr, int max) { int n ; FILE *file ; if (NULL == setup (path, p, ".bbc", '\0', NULL)) error (253, "Bad string") ; file = fopen (path, "rb") ; if (file == NULL) error (214, "File or path not found") ; n = fread (addr, 1, max, file) ; fclose (file) ; if (n == 0) error (189, "Couldn't read from file") ; } // Save a file from memory: void ossave (char *p, void *addr, int len) { int n ; FILE *file ; if (NULL == setup (path, p, ".bbc", '\0', NULL)) error (253, "Bad string") ; file = fopen (path, "w+b") ; if (file == NULL) error (214, "Couldn't create file") ; n = fwrite (addr, 1, len, file) ; fclose (file) ; if (n < len) error (189, "Couldn't write to file") ; } // Open a file: void *osopen (int type, char *p) { int chan, first, last ; FILE *file ; if (setup (path, p, ".bbc", '\0', NULL) == NULL) return 0 ; if (type == 0) file = fopen (path, "rb") ; else if (type == 1) file = fopen (path, "w+b") ; else file = fopen (path, "r+b") ; if (file == NULL) return NULL ; #ifdef _WIN32 if (strchr (path+3, ':')) #else if (0 == memcmp (path, "/dev", 4)) #endif { first = 1 ; last = MAX_PORTS ; } else { first = MAX_PORTS + 1 ; last = MAX_PORTS + MAX_FILES ; } for (chan = first; chan <= last; chan++) { if (filbuf[chan] == 0) { filbuf[chan] = file ; if (chan > MAX_PORTS) *(int *)&fcbtab[chan - MAX_PORTS - 1] = 0 ; return (void *)(size_t)chan ; } } fclose (file) ; error (192, "Too many open files") ; return NULL ; // never happens } // Read file to 256-byte buffer: static void readb (FILE *context, unsigned char *buffer, FCB *pfcb) { int amount ; if (context == NULL) error (222, "Invalid channel") ; // if (pfcb->p != pfcb->o) Windows requires fseek to be called ALWAYS myfseek (context, (pfcb->p - pfcb->o) & 0xFF, SEEK_CUR) ; #ifdef _WIN32 long long ptr = myftell (context) ; #endif amount = fread (buffer, 1, 256, context) ; #ifdef _WIN32 myfseek (context, ptr + amount, SEEK_SET) ; // filetest.bbc fix (32-bit) #endif pfcb->p = 0 ; pfcb->o = amount & 0xFF ; pfcb->w = 0 ; pfcb->f = (amount != 0) ; while (amount < 256) buffer[amount++] = 0 ; return ; } // Write 256-byte buffer to file: static int writeb (FILE *context, unsigned char *buffer, FCB *pfcb) { int amount ; if (pfcb->f >= 0) { pfcb->f = 0 ; return 0 ; } if (context == NULL) error (222, "Invalid channel") ; if (pfcb->f & 1) myfseek (context, pfcb->o ? -pfcb->o : -256, SEEK_CUR) ; #ifdef _WIN32 long long ptr = myftell (context) ; #endif amount = fwrite (buffer, 1, pfcb->w ? pfcb->w : 256, context) ; #ifdef _WIN32 myfseek (context, ptr + amount, SEEK_SET) ; // assemble.bbc asmtst64.bba fix #endif pfcb->o = amount & 0xFF ; pfcb->w = 0 ; pfcb->f = 1 ; return (amount == 0) ; } // Close a single file: static int closeb (void *chan) { int result ; if ((chan > (void *)MAX_PORTS) && (chan <= (void *)(MAX_PORTS+MAX_FILES))) { int index = (size_t) chan - MAX_PORTS - 1 ; unsigned char *buffer = (unsigned char *) filbuf[0] + index * 0x100 ; FCB *pfcb = &fcbtab[index] ; FILE *handle = (FILE *) filbuf[(size_t) chan] ; if (writeb (handle, buffer, pfcb)) return 1 ; } result = fclose (lookup (chan)) ; if ((chan >= (void *)1) && (chan <= (void *)(MAX_PORTS + MAX_FILES))) filbuf[(size_t)chan] = 0 ; return result ; } // Read a byte: unsigned char osbget (void *chan, int *peof) { unsigned char byte = 0 ; if (peof != NULL) *peof = 0 ; if (chan <= (void *)MAX_PORTS) { #ifdef _WIN32 intptr_t file = _get_osfhandle (fileno (lookup (chan))) ; ReadFile ((HANDLE) file, &byte, 1, NULL, NULL) ; #else read (fileno (lookup (chan)), &byte, 1) ; #endif return byte ; } if ((chan > (void *)MAX_PORTS) && (chan <= (void *)(MAX_PORTS+MAX_FILES))) { int index = (size_t) chan - MAX_PORTS - 1 ; unsigned char *buffer = (unsigned char *) filbuf[0] + index * 0x100 ; FCB *pfcb = &fcbtab[index] ; if (pfcb->p == pfcb->o) { FILE *handle = (FILE *) filbuf[(size_t) chan] ; if (writeb (handle, buffer, pfcb)) error (189, "Couldn't write to file") ; readb (handle, buffer, pfcb) ; if ((pfcb->f & 1) == 0) { if (peof != NULL) *peof = 1 ; return 0 ; } } return buffer[pfcb->p++] ; } if ((0 == fread (&byte, 1, 1, lookup (chan))) && (peof != NULL)) *peof = 1 ; return byte ; } // Write a byte: void osbput (void *chan, unsigned char byte) { if (chan <= (void *) MAX_PORTS) { #ifdef _WIN32 intptr_t file = _get_osfhandle (fileno (lookup (chan))) ; WriteFile ((HANDLE) file, &byte, 1, NULL, NULL) ; #else write (fileno (lookup (chan)), &byte, 1) ; #endif return ; } if ((chan > (void *)MAX_PORTS) && (chan <= (void *)(MAX_PORTS+MAX_FILES))) { int index = (size_t) chan - MAX_PORTS - 1 ; unsigned char *buffer = (unsigned char *) filbuf[0] + index * 0x100 ; FCB *pfcb = &fcbtab[index] ; if (pfcb->p == pfcb->o) { FILE *handle = (FILE *) filbuf[(size_t) chan] ; if (writeb (handle, buffer, pfcb)) error (189, "Couldn't write to file") ; readb (handle, buffer, pfcb) ; } buffer[pfcb->p++] = byte ; pfcb->w = pfcb->p ; pfcb->f |= 0x80 ; return ; } if (0 == fwrite (&byte, 1, 1, lookup (chan))) error (189, "Couldn't write to file") ; } // Get file pointer: long long getptr (void *chan) { myfseek (lookup (chan), 0, SEEK_CUR) ; long long ptr = myftell (lookup (chan)) ; if (ptr == -1) error (189, "Couldn't read file pointer") ; if ((chan > (void *)MAX_PORTS) && (chan <= (void *)(MAX_PORTS+MAX_FILES))) { FCB *pfcb = &fcbtab[(size_t) chan - MAX_PORTS - 1] ; if (pfcb->o) ptr -= pfcb->o ; else if (pfcb->f & 1) ptr -= 256 ; if (pfcb->p) ptr += pfcb->p ; else if (pfcb->f & 0x81) ptr += 256 ; } return ptr ; } // Set file pointer: void setptr (void *chan, long long ptr) { if ((chan > (void *)MAX_PORTS) && (chan <= (void *)(MAX_PORTS+MAX_FILES))) { int index = (size_t) chan - MAX_PORTS - 1 ; unsigned char *buffer = (unsigned char *) filbuf[0] + index * 0x100 ; FCB *pfcb = &fcbtab[index] ; FILE *handle = (FILE *) filbuf[(size_t) chan] ; if (writeb (handle, buffer, pfcb)) error (189, "Couldn't write to file") ; *(int *)pfcb = 0 ; } if (-1 == myfseek (lookup (chan), ptr, SEEK_SET)) error (189, "Couldn't set file pointer") ; } // Get file size: long long getext (void *chan) { FILE *file = lookup (chan) ; if (chan <= (void *)MAX_PORTS) { #ifdef _WIN32 COMSTAT cs = {0} ; ClearCommError ((HANDLE) _get_osfhandle (fileno (file)), NULL, &cs) ; return cs.cbInQue ; #elif defined(__linux__) || defined(__APPLE__) int waiting = 0 ; ioctl (fileno (file), FIONREAD, &waiting) ; return waiting ; #else return 0 ; #endif } long long newptr = getptr (chan) ; myfseek (file, 0, SEEK_CUR) ; long long ptr = myftell (file) ; myfseek (file, 0, SEEK_END) ; long long size = myftell (file) ; if ((ptr == -1) || (size == -1)) error (189, "Couldn't set file pointer") ; myfseek (file, ptr, SEEK_SET) ; if (newptr > size) return newptr ; return size ; } // Get EOF status: long long geteof (void *chan) { if ((chan > (void *)MAX_PORTS) && (chan <= (void *)(MAX_PORTS+MAX_FILES))) { FCB *pfcb = &fcbtab[(size_t) chan - MAX_PORTS - 1] ; if ((pfcb->p != 0) && (pfcb->o == 0) && ((pfcb->f) & 1)) return 0 ; } return -(getptr (chan) >= getext (chan)) ; } // Close file (if chan = 0 all open files closed and errors ignored): void osshut (void *chan) { if (chan == NULL) { int chan ; for (chan = MAX_PORTS + MAX_FILES; chan > 0; chan--) { if (filbuf[chan]) closeb ((void *)(size_t)chan) ; // ignore errors } return ; } if (closeb (chan)) error (189, "Couldn't close file") ; } // Start interpreter: int entry (void *immediate) { accs = (char*) userRAM ; // String accumulator buff = (char*) accs + ACCSLEN ; // Temporary string buffer path = (char*) buff + 0x100 ; // File path keystr = (char**) (path + 0x100) ; // *KEY strings keybdq = (char*) keystr + 0x100 ; // Keyboard queue eventq = (void*) keybdq + 0x100 ; // Event queue filbuf[0] = (eventq + 0x200 / 4) ; // File buffers n.b. pointer arithmetic!! farray = 1 ; // @hfile%() number of dimensions fasize = MAX_PORTS + MAX_FILES + 4 ; // @hfile%() number of elements #ifndef _WIN32 vflags = UTF8 ; // Not |= (fails on Linux build) #endif prand.l = (unsigned int) GetTicks () ; /// Seed PRNG prand.h = (prand.l == 0) ; rnd () ; // Randomise ! memset (keystr, 0, 256) ; xeqvdu (0x1700, 0, 0x1F) ; // initialise VDU drivers spchan = NULL ; exchan = NULL ; if (immediate == (void *) 1) { text (szVersion) ; crlf () ; text (szNotice) ; crlf () ; } return basic (progRAM, userTOP, immediate) ; } #ifdef _WIN32 static void UserTimerProc (UINT uUserTimerID, UINT uMsg, void *dwUser, void *dw1, void *dw2) { if (timtrp) putevt (timtrp, WM_TIMER, 0, 0) ; flags |= ALERT ; // Always, for periodic ESCape detection return ; } timer_t StartTimer (int period) { return timeSetEvent (period, 0, (LPTIMECALLBACK) UserTimerProc, 0, TIME_PERIODIC) ; } void StopTimer (timer_t timerid) { timeKillEvent (timerid) ; } void SystemIO (int flag) { if (!flag) SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE), ENABLE_VIRTUAL_TERMINAL_INPUT) ; } #endif #ifdef __linux__ static void UserTimerProc (int sig, siginfo_t *si, void *uc) { if (timtrp) putevt (timtrp, WM_TIMER, 0, 0) ; flags |= ALERT ; // Always, for periodic ESCape detection } timer_t StartTimer (int period) { timer_t timerid ; struct sigevent evp = {0} ; struct sigaction sig ; struct itimerspec tm ; tm.it_interval.tv_nsec = (period % 1000) * 1000000 ; tm.it_interval.tv_sec = (period / 1000) ; tm.it_value = tm.it_interval ; sig.sa_handler = (void *) &UserTimerProc ; sigemptyset (&sig.sa_mask) ; sig.sa_flags = 0 ; evp.sigev_value.sival_ptr = &timerid ; evp.sigev_notify = SIGEV_SIGNAL ; evp.sigev_signo = SIGALRM ; timer_create (CLOCK_MONOTONIC, &evp, &timerid) ; timer_settime (timerid, 0, &tm, NULL) ; sigaction (SIGALRM, &sig, NULL) ; return timerid ; } void StopTimer (timer_t timerid) { timer_delete (timerid) ; } void SystemIO (int flag) { struct termios tmp ; tcgetattr (STDIN_FILENO, &tmp) ; if (flag) { tmp.c_lflag |= ISIG ; tmp.c_oflag |= OPOST ; } else { tmp.c_lflag &= ~ISIG ; tmp.c_oflag &= ~OPOST ; } tcsetattr (STDIN_FILENO, TCSAFLUSH, &tmp) ; } #endif #ifdef __APPLE__ static void UserTimerProc (dispatch_source_t timerid) { if (timtrp) putevt (timtrp, WM_TIMER, 0, 0) ; flags |= ALERT ; // Always, for periodic ESCape detection } timer_t StartTimer (int period) { dispatch_source_t timerid ; dispatch_time_t start ; timerid = dispatch_source_create (DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timerqueue) ; dispatch_source_set_event_handler (timerid, ^{UserTimerProc(timerid);}) ; start = dispatch_time (DISPATCH_TIME_NOW, period * 1000000) ; dispatch_source_set_timer (timerid, start, period * 1000000, 0) ; dispatch_resume (timerid) ; return timerid ; } void StopTimer (timer_t timerid) { dispatch_source_cancel (timerid) ; } void SystemIO (int flag) { struct termios tmp ; tcgetattr (STDIN_FILENO, &tmp) ; if (flag) { tmp.c_lflag |= ISIG ; tmp.c_oflag |= OPOST ; } else { tmp.c_lflag &= ~ISIG ; tmp.c_oflag &= ~OPOST ; } tcsetattr (STDIN_FILENO, TCSAFLUSH, &tmp) ; } #endif static void SetLoadDir (char *path) { char temp[MAX_PATH] ; char *p ; strcpy (temp, path) ; p = strrchr (temp, '/') ; if (p == NULL) p = strrchr (temp, '\\') ; if (p) { *p = '\0' ; realpath (temp, szLoadDir) ; } else { getcwd (szLoadDir, MAX_PATH) ; } #ifdef _WIN32 strcat (szLoadDir, "\\") ; #else strcat (szLoadDir, "/") ; #endif } int main (int argc, char* argv[]) { int i ; char *env, *p, *q ; int exitcode = 0 ; void *immediate = NULL ; FILE *ProgFile, *TestFile ; char szAutoRun[MAX_PATH + 1] ; #ifdef _WIN32 int orig_stdout = -1 ; int orig_stdin = -1 ; HANDLE hThread = NULL ; platform = 0 ; // Allocate the program buffer // First reserve the maximum amount: char *pstrVirtual = NULL ; while ((MaximumRAM >= DEFAULT_RAM) && (NULL == (pstrVirtual = (char*) VirtualAlloc (NULL, MaximumRAM, MEM_RESERVE, PAGE_EXECUTE_READWRITE)))) MaximumRAM /= 2 ; // Now commit the initial amount to physical RAM: if (pstrVirtual != NULL) userRAM = (char*) VirtualAlloc (pstrVirtual, DEFAULT_RAM, MEM_COMMIT, PAGE_EXECUTE_READWRITE) ; #endif #ifdef __linux__ static struct termios orig_termios ; pthread_t hThread = 0 ; platform = 1 ; void *base = NULL ; while ((MaximumRAM >= MINIMUM_RAM) && (NULL == (base = mymap (MaximumRAM)))) MaximumRAM /= 2 ; // Now commit the initial amount to physical RAM: if (base != NULL) userRAM = mmap (base, MaximumRAM, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | MAP_ANON, -1, 0) ; #endif #ifdef __APPLE__ static struct termios orig_termios ; pthread_t hThread = NULL ; platform = 2 ; while ((MaximumRAM >= MINIMUM_RAM) && ((void*)-1 == (userRAM = mmap ((void *)0x10000000, MaximumRAM, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0))) && ((void*)-1 == (userRAM = mmap ((void *)0x10000000, MaximumRAM, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0)))) MaximumRAM /= 2 ; #endif if ((userRAM == NULL) || (userRAM == (void *)-1)) { fprintf(stderr, "Couldn't allocate memory\r\n") ; return 9 ; } #if defined __x86_64__ || defined __aarch64__ platform |= 0x40 ; #endif if (MaximumRAM > DEFAULT_RAM) userTOP = userRAM + DEFAULT_RAM ; else userTOP = userRAM + MaximumRAM ; progRAM = userRAM + PAGE_OFFSET ; // Will be raised if @cmd$ exceeds 255 bytes szCmdLine = progRAM - 0x100 ; // Must be immediately below default progRAM szTempDir = szCmdLine - 0x100 ; // Strings must be allocated on BASIC's heap szUserDir = szTempDir - 0x100 ; szLibrary = szUserDir - 0x100 ; szLoadDir = szLibrary - 0x100 ; // Get path to executable: #ifdef _WIN32 if (GetModuleFileName(NULL, szLibrary, 256) == 0) #endif #ifdef __linux__ i = readlink ("/proc/self/exe", szLibrary, 255) ; if (i > 0) szLibrary[i] = '\0' ; else #endif #ifdef __APPLE__ i = 256 ; if (_NSGetExecutablePath(szLibrary, (unsigned int *)&i)) #endif { p = realpath (argv[0], NULL) ; if (p) { strncpy (szLibrary, p, 256) ; free (p) ; } } for (i = 1; i < argc; i++) { if (NULL != strstr(argv[i], "-quit")) immediate = (void *) -1 ; if (NULL != strstr(argv[i], "-load")) immediate = (void *) 1 ; if (NULL != strstr(argv[i], "-help")) immediate = (void *) 2 ; if (immediate) { argc-- ; while (i++ < argc) argv[i - 1] = argv[i] ; break ; } } if (immediate == (void *) 2) { printf ("%s %s\n\n", szVersion, szNotice) ; printf ("The command syntax is: bbcbasic [option] [bbcfile]\n\n") ; printf ("where <option> is one of:\n") ; printf (" -help Display this message.\n") ; printf (" -load Load BASIC program <bbcfile> but don't run it.\n") ; printf (" -quit Run BASIC program <bbcfile> and quit when it ends.\n") ; printf ("otherwise run <bbcfile> (if any) and stay in the interpreter.\n") ; return 0 ; } strcpy (szAutoRun, szLibrary) ; q = strrchr (szAutoRun, '/') ; if (q == NULL) q = strrchr (szAutoRun, '\\') ; p = strrchr (szAutoRun, '.') ; if (p > q) *p = '\0' ; strcat (szAutoRun, ".bbc") ; TestFile = fopen (szAutoRun, "rb") ; if (TestFile != NULL) fclose (TestFile) ; else if ((argc >= 2) && (*argv[1] != '-')) strcpy (szAutoRun, argv[1]) ; strcpy (szCmdLine, szAutoRun) ; if (argc >= 2) { *szCmdLine = 0 ; for (i = 1; i < argc; i++) { if (i > 1) strcat (szCmdLine, " ") ; strcat (szCmdLine, argv[i]) ; } progRAM = (void *)(((intptr_t) szCmdLine + strlen(szCmdLine) + 256) & -256) ; } if (*szAutoRun && (NULL != (ProgFile = fopen (szAutoRun, "rb")))) { fread (progRAM, 1, userTOP - progRAM, ProgFile) ; fclose (ProgFile) ; } else { immediate = (void *) 1 ; *szAutoRun = '\0' ; } env = getenv ("TMPDIR") ; if (!env) env = getenv ("TMP") ; if (!env) env = getenv ("TEMP") ; if (env) strcpy (szTempDir, env) ; else strcpy (szTempDir, "/tmp") ; env = getenv ("HOME") ; if (!env) env = getenv ("APPDATA") ; if (!env) env = getenv ("HOMEPATH") ; if (env) strcpy (szUserDir, env) ; p = strrchr (szLibrary, '/') ; if (p == NULL) p = strrchr (szLibrary, '\\') ; if (p) *p = '\0' ; #ifdef _WIN32 strcat (szTempDir, "\\") ; strcat (szLibrary, "\\lib\\") ; strcat (szUserDir, "\\bbcbasic\\") ; mkdir (szUserDir) ; #else strcat (szTempDir, "/") ; strcat (szLibrary, "/lib/") ; strcat (szUserDir, "/bbcbasic/") ; mkdir (szUserDir, 0777) ; #endif SetLoadDir (szAutoRun) ; if (argc < 2) *szCmdLine = 0 ; else if (TestFile == NULL) chdir (szLoadDir) ; // Set console for raw input and ANSI output: #ifdef _WIN32 // n.b. Description of DISABLE_NEWLINE_AUTO_RETURN at MSDN is completely wrong! // What it actually does is to disable converting LF into CRLF, not wrap action. if (GetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), (LPDWORD) &orig_stdout)) SetConsoleMode (GetStdHandle(STD_OUTPUT_HANDLE), orig_stdout | ENABLE_WRAP_AT_EOL_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN) ; if (GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), (LPDWORD) &orig_stdin)) SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE), ENABLE_VIRTUAL_TERMINAL_INPUT) ; hThread = CreateThread (NULL, 0, myThread, 0, 0, NULL) ; #else tcgetattr (STDIN_FILENO, &orig_termios) ; struct termios raw = orig_termios ; raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON) ; raw.c_oflag &= ~OPOST ; raw.c_cflag |= CS8 ; raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG) ; raw.c_cc[VMIN] = 0 ; raw.c_cc[VTIME] = 1 ; tcsetattr (STDIN_FILENO, TCSAFLUSH, &raw) ; pthread_create(&hThread, NULL, &myThread, NULL); #endif #ifdef __APPLE__ timerqueue = dispatch_queue_create ("timerQueue", 0) ; #endif UserTimerID = StartTimer (250) ; flags = 0 ; exitcode = entry (immediate) ; if (UserTimerID) StopTimer (UserTimerID) ; #ifdef __APPLE__ dispatch_release (timerqueue) ; #endif #ifdef _WIN32 if (_isatty (_fileno (stdout))) printf ("\033[0m\033[!p") ; CloseHandle (hThread) ; if (orig_stdout != -1) SetConsoleMode (GetStdHandle(STD_OUTPUT_HANDLE), orig_stdout) ; if (orig_stdin != -1) SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE), orig_stdin) ; #else if (isatty (STDOUT_FILENO)) printf ("\033[0m\033[!p") ; tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios) ; #endif exit (exitcode) ; }
c9a5a0c1ec280d011b68af47b9da997bb8f4215f
b1fcecfa2d9b42db62ba22f4635b3e845bf4ab56
/nginx/src/http/ngx_http_upstream.h
95471deb18f24883b309932074ad372484a446cf
[ "BSD-2-Clause" ]
permissive
chronolaw/annotated_nginx
606b5ae08b8173daa01fcac353b089b17deff08d
60b0e2a15d4c7c51313bd117bab026046c3da01b
refs/heads/master
2023-06-29T09:15:23.066046
2023-06-17T08:35:25
2023-06-17T08:35:25
51,183,743
573
206
null
null
null
null
UTF-8
C
false
false
18,345
h
ngx_http_upstream.h
// annotated by chrono since 2016 // // * ngx_http_upstream_conf_t // * ngx_http_upstream_s // * ngx_http_upstream_srv_conf_s /* * Copyright (C) Igor Sysoev * Copyright (C) Nginx, Inc. */ #ifndef _NGX_HTTP_UPSTREAM_H_INCLUDED_ #define _NGX_HTTP_UPSTREAM_H_INCLUDED_ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_event.h> #include <ngx_event_connect.h> #include <ngx_event_pipe.h> #include <ngx_http.h> #define NGX_HTTP_UPSTREAM_FT_ERROR 0x00000002 #define NGX_HTTP_UPSTREAM_FT_TIMEOUT 0x00000004 #define NGX_HTTP_UPSTREAM_FT_INVALID_HEADER 0x00000008 #define NGX_HTTP_UPSTREAM_FT_HTTP_500 0x00000010 #define NGX_HTTP_UPSTREAM_FT_HTTP_502 0x00000020 #define NGX_HTTP_UPSTREAM_FT_HTTP_503 0x00000040 #define NGX_HTTP_UPSTREAM_FT_HTTP_504 0x00000080 #define NGX_HTTP_UPSTREAM_FT_HTTP_403 0x00000100 #define NGX_HTTP_UPSTREAM_FT_HTTP_404 0x00000200 #define NGX_HTTP_UPSTREAM_FT_HTTP_429 0x00000400 #define NGX_HTTP_UPSTREAM_FT_UPDATING 0x00000800 #define NGX_HTTP_UPSTREAM_FT_BUSY_LOCK 0x00001000 #define NGX_HTTP_UPSTREAM_FT_MAX_WAITING 0x00002000 #define NGX_HTTP_UPSTREAM_FT_NON_IDEMPOTENT 0x00004000 #define NGX_HTTP_UPSTREAM_FT_NOLIVE 0x40000000 #define NGX_HTTP_UPSTREAM_FT_OFF 0x80000000 #define NGX_HTTP_UPSTREAM_FT_STATUS (NGX_HTTP_UPSTREAM_FT_HTTP_500 \ |NGX_HTTP_UPSTREAM_FT_HTTP_502 \ |NGX_HTTP_UPSTREAM_FT_HTTP_503 \ |NGX_HTTP_UPSTREAM_FT_HTTP_504 \ |NGX_HTTP_UPSTREAM_FT_HTTP_403 \ |NGX_HTTP_UPSTREAM_FT_HTTP_404 \ |NGX_HTTP_UPSTREAM_FT_HTTP_429) #define NGX_HTTP_UPSTREAM_INVALID_HEADER 40 #define NGX_HTTP_UPSTREAM_IGN_XA_REDIRECT 0x00000002 #define NGX_HTTP_UPSTREAM_IGN_XA_EXPIRES 0x00000004 #define NGX_HTTP_UPSTREAM_IGN_EXPIRES 0x00000008 #define NGX_HTTP_UPSTREAM_IGN_CACHE_CONTROL 0x00000010 #define NGX_HTTP_UPSTREAM_IGN_SET_COOKIE 0x00000020 #define NGX_HTTP_UPSTREAM_IGN_XA_LIMIT_RATE 0x00000040 #define NGX_HTTP_UPSTREAM_IGN_XA_BUFFERING 0x00000080 #define NGX_HTTP_UPSTREAM_IGN_XA_CHARSET 0x00000100 #define NGX_HTTP_UPSTREAM_IGN_VARY 0x00000200 // 上游的收发状态 typedef struct { ngx_uint_t status; ngx_msec_t response_time; ngx_msec_t connect_time; ngx_msec_t header_time; ngx_msec_t queue_time; off_t response_length; // 收到的字节数 // ngx_http_upstream_process_header里增加 off_t bytes_received; // 发送到后端的字节数 // 1.15.8新增 off_t bytes_sent; ngx_str_t *peer; } ngx_http_upstream_state_t; // upstream模块的主配置,存储所有的upstream{}配置 typedef struct { ngx_hash_t headers_in_hash; // 里面的元素是ngx_http_upstream_srv_conf_t ngx_array_t upstreams; /* ngx_http_upstream_srv_conf_t */ } ngx_http_upstream_main_conf_t; typedef struct ngx_http_upstream_srv_conf_s ngx_http_upstream_srv_conf_t; // 给load balance模块用初始化函数指针 typedef ngx_int_t (*ngx_http_upstream_init_pt)(ngx_conf_t *cf, ngx_http_upstream_srv_conf_t *us); typedef ngx_int_t (*ngx_http_upstream_init_peer_pt)(ngx_http_request_t *r, ngx_http_upstream_srv_conf_t *us); // 给load balance模块用初始化结构体 // 定义了load-balance模块的入口,有两个回调函数,用来初始化load-balance模块 typedef struct { ngx_http_upstream_init_pt init_upstream; ngx_http_upstream_init_peer_pt init; // 指向ngx_http_upstream_rr_peers_t // backup/非backup服务器IP列表 void *data; } ngx_http_upstream_peer_t; // 在upstream{}里的每个server指令相关的信息 // 包括地址/权重/超时等等 typedef struct { // 服务器的名字 ngx_str_t name; // 服务器对应的地址数组,可能有多个ip地址 ngx_addr_t *addrs; // 服务器地址数组的长度,即个数 ngx_uint_t naddrs; // 权重 ngx_uint_t weight; // 允许的最大连接数 ngx_uint_t max_conns; // 允许的最大失败次数 ngx_uint_t max_fails; // 失败的时间区间 time_t fail_timeout; // 服务器的恢复时间 ngx_msec_t slow_start; // 是否下线 ngx_uint_t down; // 1.11.5新增slow_start、max_conns // 是否是备用服务器 unsigned backup:1; NGX_COMPAT_BEGIN(6) NGX_COMPAT_END } ngx_http_upstream_server_t; #define NGX_HTTP_UPSTREAM_CREATE 0x0001 #define NGX_HTTP_UPSTREAM_WEIGHT 0x0002 #define NGX_HTTP_UPSTREAM_MAX_FAILS 0x0004 #define NGX_HTTP_UPSTREAM_FAIL_TIMEOUT 0x0008 #define NGX_HTTP_UPSTREAM_DOWN 0x0010 #define NGX_HTTP_UPSTREAM_BACKUP 0x0020 #define NGX_HTTP_UPSTREAM_MAX_CONNS 0x0100 // ngx_http_upstream_srv_conf_t // 每个upstream{}块的配置结构体,存储server信息 struct ngx_http_upstream_srv_conf_s { // 初始化结构体 // 给load balance模块用初始化结构体 // 定义了load-balance模块的入口,有两个回调函数,用来初始化load-balance模块 ngx_http_upstream_peer_t peer; // 数组,存储模块的配置结构体 // 使用宏ngx_http_conf_upstream_srv_conf void **srv_conf; // 存储ngx_http_upstream_server_t的数组 ngx_array_t *servers; /* ngx_http_upstream_server_t */ ngx_uint_t flags; // upstream{}块的名字 ngx_str_t host; // 在配置文件里的位置 u_char *file_name; ngx_uint_t line; in_port_t port; // 通常来说upstream块名字里是没有端口号的 ngx_uint_t no_port; /* unsigned no_port:1 */ // 使用的共享内存指针 #if (NGX_HTTP_UPSTREAM_ZONE) ngx_shm_zone_t *shm_zone; #endif }; typedef struct { ngx_addr_t *addr; ngx_http_complex_value_t *value; #if (NGX_HAVE_TRANSPARENT_PROXY) ngx_uint_t transparent; /* unsigned transparent:1; */ #endif } ngx_http_upstream_local_t; // ngx_http_upstream_conf_t; // 需要设置超时时间、缓冲、限速等必要的参数,才能正确地连接上游服务器 typedef struct { ngx_http_upstream_srv_conf_t *upstream; ngx_msec_t connect_timeout; ngx_msec_t send_timeout; ngx_msec_t read_timeout; ngx_msec_t next_upstream_timeout; size_t send_lowat; size_t buffer_size; size_t limit_rate; size_t busy_buffers_size; size_t max_temp_file_size; size_t temp_file_write_size; size_t busy_buffers_size_conf; size_t max_temp_file_size_conf; size_t temp_file_write_size_conf; ngx_bufs_t bufs; ngx_uint_t ignore_headers; ngx_uint_t next_upstream; ngx_uint_t store_access; ngx_uint_t next_upstream_tries; ngx_flag_t buffering; ngx_flag_t request_buffering; ngx_flag_t pass_request_headers; ngx_flag_t pass_request_body; ngx_flag_t ignore_client_abort; ngx_flag_t intercept_errors; ngx_flag_t cyclic_temp_file; ngx_flag_t force_ranges; ngx_path_t *temp_path; ngx_hash_t hide_headers_hash; ngx_array_t *hide_headers; ngx_array_t *pass_headers; ngx_http_upstream_local_t *local; ngx_flag_t socket_keepalive; #if (NGX_HTTP_CACHE) ngx_shm_zone_t *cache_zone; ngx_http_complex_value_t *cache_value; ngx_uint_t cache_min_uses; ngx_uint_t cache_use_stale; ngx_uint_t cache_methods; off_t cache_max_range_offset; ngx_flag_t cache_lock; ngx_msec_t cache_lock_timeout; ngx_msec_t cache_lock_age; ngx_flag_t cache_revalidate; ngx_flag_t cache_convert_head; ngx_flag_t cache_background_update; ngx_array_t *cache_valid; ngx_array_t *cache_bypass; ngx_array_t *cache_purge; ngx_array_t *no_cache; #endif ngx_array_t *store_lengths; ngx_array_t *store_values; #if (NGX_HTTP_CACHE) signed cache:2; #endif signed store:2; unsigned intercept_404:1; unsigned change_buffering:1; unsigned pass_trailers:1; unsigned preserve_output:1; #if (NGX_HTTP_SSL || NGX_COMPAT) ngx_ssl_t *ssl; ngx_flag_t ssl_session_reuse; ngx_http_complex_value_t *ssl_name; ngx_flag_t ssl_server_name; ngx_flag_t ssl_verify; ngx_http_complex_value_t *ssl_certificate; ngx_http_complex_value_t *ssl_certificate_key; ngx_array_t *ssl_passwords; #endif ngx_str_t module; NGX_COMPAT_BEGIN(2) NGX_COMPAT_END } ngx_http_upstream_conf_t; typedef struct { ngx_str_t name; ngx_http_header_handler_pt handler; ngx_uint_t offset; ngx_http_header_handler_pt copy_handler; ngx_uint_t conf; ngx_uint_t redirect; /* unsigned redirect:1; */ } ngx_http_upstream_header_t; // 上游的响应头,同样也有快速查找常用头字段 typedef struct { ngx_list_t headers; ngx_list_t trailers; ngx_uint_t status_n; ngx_str_t status_line; ngx_table_elt_t *status; ngx_table_elt_t *date; ngx_table_elt_t *server; ngx_table_elt_t *connection; ngx_table_elt_t *expires; ngx_table_elt_t *etag; ngx_table_elt_t *x_accel_expires; ngx_table_elt_t *x_accel_redirect; ngx_table_elt_t *x_accel_limit_rate; ngx_table_elt_t *content_type; ngx_table_elt_t *content_length; ngx_table_elt_t *last_modified; ngx_table_elt_t *location; ngx_table_elt_t *refresh; ngx_table_elt_t *www_authenticate; ngx_table_elt_t *transfer_encoding; ngx_table_elt_t *vary; ngx_table_elt_t *cache_control; ngx_table_elt_t *set_cookie; off_t content_length_n; time_t last_modified_time; unsigned connection_close:1; unsigned chunked:1; unsigned no_cache:1; unsigned expired:1; } ngx_http_upstream_headers_in_t; typedef struct { ngx_str_t host; in_port_t port; ngx_uint_t no_port; /* unsigned no_port:1 */ ngx_uint_t naddrs; ngx_resolver_addr_t *addrs; struct sockaddr *sockaddr; socklen_t socklen; ngx_str_t name; ngx_resolver_ctx_t *ctx; } ngx_http_upstream_resolved_t; typedef void (*ngx_http_upstream_handler_pt)(ngx_http_request_t *r, ngx_http_upstream_t *u); // ngx_http_upstream_t // 定义了upstream机制需要的所有信息 struct ngx_http_upstream_s { ngx_http_upstream_handler_pt read_event_handler; ngx_http_upstream_handler_pt write_event_handler; // 连接结构体 ngx_peer_connection_t peer; ngx_event_pipe_t *pipe; // 发送的请求数据 // u->request_bufs = r->request_body->bufs; ngx_chain_t *request_bufs; ngx_output_chain_ctx_t output; ngx_chain_writer_ctx_t writer; // 上游的连接参数设置 ngx_http_upstream_conf_t *conf; ngx_http_upstream_srv_conf_t *upstream; #if (NGX_HTTP_CACHE) ngx_array_t *caches; #endif // 上游的响应头 ngx_http_upstream_headers_in_t headers_in; // 上游服务器的地址 ngx_http_upstream_resolved_t *resolved; ngx_buf_t from_client; // 数据缓冲区 ngx_buf_t buffer; // 缓冲数据的长度 off_t length; // 从上游接收到的数据 ngx_chain_t *out_bufs; ngx_chain_t *busy_bufs; ngx_chain_t *free_bufs; // 处理上游服务器响应数据的回调函数 ngx_int_t (*input_filter_init)(void *data); ngx_int_t (*input_filter)(void *data, ssize_t bytes); void *input_filter_ctx; #if (NGX_HTTP_CACHE) ngx_int_t (*create_key)(ngx_http_request_t *r); #endif // 发送接收请求的回调函数,9个 ngx_int_t (*create_request)(ngx_http_request_t *r); ngx_int_t (*reinit_request)(ngx_http_request_t *r); ngx_int_t (*process_header)(ngx_http_request_t *r); void (*abort_request)(ngx_http_request_t *r); void (*finalize_request)(ngx_http_request_t *r, ngx_int_t rc); ngx_int_t (*rewrite_redirect)(ngx_http_request_t *r, ngx_table_elt_t *h, size_t prefix); ngx_int_t (*rewrite_cookie)(ngx_http_request_t *r, ngx_table_elt_t *h); ngx_msec_t start_time; // 处理的状态信息 ngx_http_upstream_state_t *state; ngx_str_t method; ngx_str_t schema; ngx_str_t uri; #if (NGX_HTTP_SSL || NGX_COMPAT) ngx_str_t ssl_name; #endif ngx_http_cleanup_pt *cleanup; unsigned store:1; unsigned cacheable:1; unsigned accel:1; unsigned ssl:1; #if (NGX_HTTP_CACHE) unsigned cache_status:3; #endif // 是否使用更多的缓冲区来接收上游的数据 unsigned buffering:1; unsigned keepalive:1; unsigned upgrade:1; unsigned error:1; // 是否已经发送请求 unsigned request_sent:1; // 是否已经发送请求体数据 unsigned request_body_sent:1; unsigned request_body_blocked:1; // 是否已经发送响应头 unsigned header_sent:1; }; typedef struct { ngx_uint_t status; ngx_uint_t mask; } ngx_http_upstream_next_t; typedef struct { ngx_str_t key; ngx_str_t value; ngx_uint_t skip_empty; } ngx_http_upstream_param_t; ngx_int_t ngx_http_upstream_create(ngx_http_request_t *r); void ngx_http_upstream_init(ngx_http_request_t *r); ngx_int_t ngx_http_upstream_non_buffered_filter_init(void *data); ngx_int_t ngx_http_upstream_non_buffered_filter(void *data, ssize_t bytes); ngx_http_upstream_srv_conf_t *ngx_http_upstream_add(ngx_conf_t *cf, ngx_url_t *u, ngx_uint_t flags); char *ngx_http_upstream_bind_set_slot(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); char *ngx_http_upstream_param_set_slot(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); ngx_int_t ngx_http_upstream_hide_headers_hash(ngx_conf_t *cf, ngx_http_upstream_conf_t *conf, ngx_http_upstream_conf_t *prev, ngx_str_t *default_hide_headers, ngx_hash_init_t *hash); #define ngx_http_conf_upstream_srv_conf(uscf, module) \ uscf->srv_conf[module.ctx_index] extern ngx_module_t ngx_http_upstream_module; extern ngx_conf_bitmask_t ngx_http_upstream_cache_method_mask[]; extern ngx_conf_bitmask_t ngx_http_upstream_ignore_headers_masks[]; #endif /* _NGX_HTTP_UPSTREAM_H_INCLUDED_ */
f02e83916e59534646effc9d49bdd370295b20c4
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/libc/time/asctime.c
a5350228bfc561486bc09c084f9234790c79e6e6
[ "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
4,173
c
asctime.c
#include "libc/fmt/fmt.h" #include "libc/str/str.h" #include "libc/time/struct/tm.h" #include "libc/time/time.h" #include "libc/time/tz.internal.h" #include "third_party/python/Include/object.h" // clang-format off /* asctime and asctime_r a la POSIX and ISO C, except pad years before 1000. */ /* ** This file is in the public domain, so clarified as of ** 1996-06-05 by Arthur David Olson. */ /* ** Avoid the temptation to punt entirely to strftime; ** the output of strftime is supposed to be locale specific ** whereas the output of asctime is supposed to be constant. */ /* ** Some systems only handle "%.2d"; others only handle "%02d"; ** "%02.2d" makes (most) everybody happy. ** At least some versions of gcc warn about the %02.2d; ** we conditionalize below to avoid the warning. */ /* ** All years associated with 32-bit time_t values are exactly four digits long; ** some years associated with 64-bit time_t values are not. ** Vintage programs are coded for years that are always four digits long ** and may assume that the newline always lands in the same place. ** For years that are less than four digits, we pad the output with ** leading zeroes to get the newline in the traditional place. ** The -4 ensures that we get four characters of output even if ** we call a strftime variant that produces fewer characters for some years. ** The ISO C and POSIX standards prohibit padding the year, ** but many implementations pad anyway; most likely the standards are buggy. */ #ifdef __GNUC__ #define ASCTIME_FMT "%s %s%3d %2.2d:%2.2d:%2.2d %-4s\n" #else /* !defined __GNUC__ */ #define ASCTIME_FMT "%s %s%3d %02.2d:%02.2d:%02.2d %-4s\n" #endif /* !defined __GNUC__ */ /* ** For years that are more than four digits we put extra spaces before the year ** so that code trying to overwrite the newline won't end up overwriting ** a digit within a year and truncating the year (operating on the assumption ** that no output is better than wrong output). */ #ifdef __GNUC__ #define ASCTIME_FMT_B "%s %s%3d %2.2d:%2.2d:%2.2d %s\n" #else /* !defined __GNUC__ */ #define ASCTIME_FMT_B "%s %s%3d %02.2d:%02.2d:%02.2d %s\n" #endif /* !defined __GNUC__ */ #define STD_ASCTIME_BUF_SIZE 26 /* ** Big enough for something such as ** ??? ???-2147483648 -2147483648:-2147483648:-2147483648 -2147483648\n ** (two three-character abbreviations, five strings denoting integers, ** seven explicit spaces, two explicit colons, a newline, ** and a trailing NUL byte). ** The values above are for systems where an int is 32 bits and are provided ** as an example; the define below calculates the maximum for the system at ** hand. */ #define MAX_ASCTIME_BUF_SIZE (2*3+5*INT_STRLEN_MAXIMUM(int)+7+2+1+1) static char buf_asctime[MAX_ASCTIME_BUF_SIZE]; char * asctime_r(register const struct tm *timeptr, char buf[hasatleast 26]) { register const char * wn; register const char * mn; char year[INT_STRLEN_MAXIMUM(int) + 2]; char result[MAX_ASCTIME_BUF_SIZE]; if (timeptr == NULL) { errno = EINVAL; return strcpy(buf, "??? ??? ?? ??:??:?? ????\n"); } if (timeptr->tm_wday < 0 || timeptr->tm_wday >= DAYSPERWEEK) wn = "???"; else wn = kWeekdayNameShort[timeptr->tm_wday]; if (timeptr->tm_mon < 0 || timeptr->tm_mon >= MONSPERYEAR) mn = "???"; else mn = kMonthNameShort[timeptr->tm_mon]; /* ** Use strftime's %Y to generate the year, to avoid overflow problems ** when computing timeptr->tm_year + TM_YEAR_BASE. ** Assume that strftime is unaffected by other out-of-range members ** (e.g., timeptr->tm_mday) when processing "%Y". */ strftime(year, sizeof year, "%Y", timeptr); /* ** We avoid using snprintf since it's not available on all systems. */ (sprintf)(result, ((strlen(year) <= 4) ? ASCTIME_FMT : ASCTIME_FMT_B), wn, mn, timeptr->tm_mday, timeptr->tm_hour, timeptr->tm_min, timeptr->tm_sec, year); if (strlen(result) < STD_ASCTIME_BUF_SIZE || buf == buf_asctime) return strcpy(buf, result); else { errno = EOVERFLOW; return NULL; } } char * asctime(register const struct tm *timeptr) { return asctime_r(timeptr, buf_asctime); }
3cf4cadbfae07b296a70872cc7778609bde50029
010279e2ba272d09e9d2c4e903722e5faba2cf7a
/contrib/tools/f2c/src/version.c
b2606b299877ed9d99a52b59d177a778a25bec45
[ "LicenseRef-scancode-other-permissive", "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
107
c
version.c
char F2C_version[] = "20200916"; char xxxvers[] = "\n@(#) FORTRAN 77 to C Translator, VERSION 20200916\n";
4576a86c4f7f866709772e13b87d351193304755
61be4a7bfc24468a1227ea797150520c83257844
/event/Demo602_0.c
06317e4c22d1e3d0025141886060294b4cf64d63
[]
no_license
MrCheeze/botw-tools
491e6a2d06191efa7fc7048aefb48b3b38a59a52
9a9e845beed87f5ec417c01e515d0fa01366366c
refs/heads/master
2022-06-26T01:34:38.353269
2022-06-20T14:52:01
2022-06-20T14:53:26
85,882,713
238
92
null
2017-05-01T22:15:30
2017-03-22T22:34:34
Python
UTF-8
C
false
false
25,525
c
Demo602_0.c
-------- EventFlow: Demo602_0 -------- Actor: DgnObj_EntranceElevatorSP entrypoint: None() actions: ['Demo_PlayASForDemoPreMove', 'Demo_PlayASForDemo'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: DgnObj_EntranceShutterSP entrypoint: None() actions: ['Demo_PlayASForDemoPreMove', 'Demo_PlayASForDemo'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: DgnObj_WarpPointSP entrypoint: None() actions: ['Demo_PlayASForDemoPreMove', 'Demo_PlayASForDemo', 'Demo_TrigNullASPlay'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: DgnObj_EntranceTerminalSP entrypoint: None() actions: ['Demo_PlayASForDemoPreMove', 'Demo_PlayASForDemo', 'Demo_TrigNullASPlay'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: Starter entrypoint: None() actions: ['Demo_SendSignal'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: EventSystemActor entrypoint: None() actions: ['Demo_WaitFrame', 'Demo_FlagOFF'] queries: ['CheckFlag', 'CheckPlayerRideHorse', 'CheckPlayerState'] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: SoundTriggerTag entrypoint: None() actions: ['Demo_SoundTrigger'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: GameROMPlayer entrypoint: None() actions: ['Demo_PlayerHide', 'Demo_PlayerShow', 'Demo_StopInAir', 'Demo_VisibleOff', 'Demo_PlayerWait', 'Demo_TurnAndLookToObjectNow', 'Demo_PlayerTurnAndLookToObject'] queries: [] params: {'Weapon': '', 'DisableWeapon': False, 'Shield': '', 'DisableShield': False, 'Bow': '', 'DisableBow': False, 'DisableSheikPad': False, 'ArmorHead': '', 'ArmorUpper': '', 'ArmorLower': '', 'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: EventMessageTransmitter1 entrypoint: None() actions: ['Demo_Msg2CameraResetNoConnect'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: GameRomCamera entrypoint: None() actions: ['Demo_GameCamera', 'Demo_CameraAnimFlow', 'Demo_MovePosFlow'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: Obj_SweepCollision entrypoint: None() actions: ['Demo_Sweep'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: EventControllerRumble entrypoint: None() actions: ['Demo_TimeSpecRumbleMiddle', 'Demo_RumbleLarge', 'Demo_RumbleMiddle'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: DgnObj_DLC_ChampionsDungeonEntrance_A_01 entrypoint: None() actions: ['Demo_PlayASForDemo', 'Demo_XLinkEventCreate', 'Demo_TrigNullASPlay', 'Demo_OnMUAssignSaveForUsed', 'Demo_PlayASForDemoPreMove'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: SceneSoundCtrlTag entrypoint: None() actions: ['Demo_Ctrl'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: FldObj_DLC_WaterShrineGround_A_01 entrypoint: None() actions: ['Demo_PlayASForDemoPreMove', 'Demo_PlayASForDemo'] queries: [] params: {'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0, 'CreateMode': 2} Actor: EventSystemActor[PlayerController] entrypoint: None() actions: ['Demo_WaitFrame'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} Actor: EventSystemActor[Shake] entrypoint: None() actions: ['Demo_WaitFrame'] queries: [] params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0} void DungeonArrival_DLC() { EventMessageTransmitter1.Demo_Msg2CameraResetNoConnect({'IsWaitFinish': True}) if EventSystemActor.CheckPlayerRideHorse() { Event100: Starter.Demo_SendSignal({'SignalType': 0, 'Value': True, 'IsWaitFinish': False}) GameROMPlayer.Demo_PlayerHide({'IsWaitFinish': False}) fork { if EventSystemActor.CheckPlayerState({'PlayerState': 4}) && !EventSystemActor.CheckFlag({'FlagName': 'BalladOfHeroGoron_Dungeon01_ForDemo602_0'}) { EventSystemActor[PlayerController].Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 1}) GameROMPlayer.Demo_PlayerTurnAndLookToObject({'IsWaitFinish': False, 'ObjectId': 3, 'FaceId': 1, 'IsValid': False, 'ActorName': '', 'UniqueName': '', 'PosOffset': [0.0, 0.0, 0.0], 'TurnPosition': [0.0, 0.0, 0.0], 'TurnDirection': 0.0, 'IsUseSlowTurn': False, 'IsTurnToLookAtPos': False}) GameROMPlayer.Demo_PlayerHide({'IsWaitFinish': False}) } } { call Demo602_0_Cam_Gerudo02() } EventSystemActor.Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 5}) DgnObj_DLC_ChampionsDungeonEntrance_A_01.Demo_OnMUAssignSaveForUsed({'IsWaitFinish': True}) EventSystemActor.Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 10}) SoundTriggerTag.Demo_SoundTrigger({'IsWaitFinish': False, 'SoundDelay': 0, 'SLinkInst': '', 'Sound': 'ReadRiddle'}) EventSystemActor.Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 20}) if EventSystemActor.CheckFlag({'FlagName': 'NotBack_Demo016Camera'}) { GameROMPlayer.Demo_PlayerShow({'IsWaitFinish': False}) GameROMPlayer.Demo_PlayerWait({'IsWaitFinish': False}) EventSystemActor.Demo_FlagOFF({'FlagName': 'NotBack_Demo016Camera', 'IsWaitFinish': True}) } else { GameROMPlayer.Demo_PlayerShow({'IsWaitFinish': False}) GameROMPlayer.Demo_PlayerWait({'IsWaitFinish': False}) GameRomCamera.Demo_GameCamera({'IsWaitFinish': True}) } } else if EventSystemActor.CheckPlayerState({'PlayerState': 4}) { GameROMPlayer.Demo_VisibleOff({'IsWaitFinish': False}) } else { GameROMPlayer.Demo_StopInAir({'NoFixed': True, 'IsWaitFinish': False}) } goto Event100 } void Demo602_0() { call InitTalk.InitTalk({'Arg_Turn': 0, 'Arg_Greeting': 'FollowAISchedule'}) } void Demo602_0_Camera() { fork { EventSystemActor.Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 60}) SceneSoundCtrlTag.Demo_Ctrl({'BgmCtrlType': 'Mute', 'IsWaitFinish': True, 'SeCtrlType': 'None'}) } { call Demo602_0_CDungeonAnm() } { GameRomCamera.Demo_CameraAnimFlow({'CameraName': '', 'StartFrame': 0.0, 'EndFrame': -1.0, 'DOFUse': False, 'DOFStartFrame': 0.0, 'FocalLength': 0.0, 'Aperture': 0.0, 'DOFBlurStart': 2.0, 'DOFEndFrame': 0.0, 'FocalLengthEnd': 0.0, 'ApertureEnd': 0.0, 'DOFBlurEnd': 2.0, 'InterpolateCount': 0.0, 'UniqueName': '', 'Accept1FrameDelay': False, 'TargetActor': 3, 'IsWaitFinish': True, 'SceneName': 'C01_0', 'BgCheck': False, 'TargetActorPosReferenceMode': 0, 'TargetActorDirReferenceMode': 0, 'OverwriteAtDist': 1.0, 'OverwriteAt': True, 'ActorName': 'DgnObj_DLC_ChampionsDungeonEntrance_A_01'}) GameRomCamera.Demo_CameraAnimFlow({'CameraName': '', 'StartFrame': 0.0, 'EndFrame': -1.0, 'DOFUse': False, 'DOFStartFrame': 0.0, 'FocalLength': 0.0, 'Aperture': 0.0, 'DOFBlurStart': 2.0, 'DOFEndFrame': 0.0, 'FocalLengthEnd': 0.0, 'ApertureEnd': 0.0, 'DOFBlurEnd': 2.0, 'InterpolateCount': 0.0, 'UniqueName': '', 'Accept1FrameDelay': False, 'TargetActor': 3, 'SceneName': 'C01_1', 'IsWaitFinish': True, 'BgCheck': False, 'TargetActorPosReferenceMode': 0, 'TargetActorDirReferenceMode': 0, 'OverwriteAtDist': 1.0, 'OverwriteAt': True, 'ActorName': 'DgnObj_DLC_ChampionsDungeonEntrance_A_01'}) GameRomCamera.Demo_CameraAnimFlow({'CameraName': '', 'StartFrame': 0.0, 'EndFrame': -1.0, 'DOFUse': False, 'DOFStartFrame': 0.0, 'FocalLength': 0.0, 'Aperture': 0.0, 'DOFBlurStart': 2.0, 'DOFEndFrame': 0.0, 'FocalLengthEnd': 0.0, 'ApertureEnd': 0.0, 'DOFBlurEnd': 2.0, 'InterpolateCount': 0.0, 'UniqueName': '', 'Accept1FrameDelay': False, 'TargetActor': 3, 'IsWaitFinish': True, 'SceneName': 'C01_3', 'BgCheck': False, 'TargetActorPosReferenceMode': 0, 'TargetActorDirReferenceMode': 0, 'OverwriteAtDist': 1.0, 'OverwriteAt': True, 'ActorName': 'DgnObj_DLC_ChampionsDungeonEntrance_A_01'}) } } void Demo602_0_Cam_Gerudo03() { if EventSystemActor.CheckFlag({'FlagName': 'BalladOfHeroGerudo_Dungeon03_ForDemo602_0'}) { fork { call Demo602_0_CDungeonAnm() } { GameRomCamera.Demo_MovePosFlow({'Pattern1PosX': -3455.690673828125, 'Pattern1PosY': 460.1050109863281, 'Pattern1PosZ': 1325.4197998046875, 'Pattern1AtX': -3451.1748046875, 'Pattern1AtY': 455.77423095703125, 'Pattern1AtZ': 1327.1416015625, 'Pattern1Fovy': 50.00001907348633, 'IsWaitFinish': True, 'TargetActor1': -1, 'ActorName1': '', 'UniqueName1': '', 'TargetActor2': -1, 'ActorName2': '', 'UniqueName2': '', 'PosAppendMode': 1, 'GameDataVec3fCameraPos': '', 'AtAppendMode': 1, 'GameDataVec3fCameraAt': '', 'FovyAppendMode': 1, 'StartCalcOnly': False, 'MotionMode': 0, 'Count': 0.0, 'Cushion': 0.0, 'CollisionInterpolateSkip': True, 'Accept1FrameDelay': False, 'LatShiftRange': 0.0, 'LngShiftRange': 0.0, 'ActorIgnoringCollision': -1, 'ReviseModeEnd': 2}) GameRomCamera.Demo_MovePosFlow({'Pattern1PosX': -0.2556149959564209, 'Pattern1PosY': 25.50946044921875, 'Pattern1PosZ': 22.61328125, 'Pattern1AtX': -0.25, 'Pattern1AtY': 25.476318359375, 'Pattern1AtZ': 21.613525390625, 'Pattern1Fovy': 33.39850997924805, 'TargetActor1': 3, 'AtAppendMode': 2, 'PosAppendMode': 2, 'ActorName1': 'DgnObj_DLC_ChampionsDungeonEntrance_A_01', 'Count': 30.0, 'IsWaitFinish': True, 'UniqueName1': '', 'TargetActor2': -1, 'ActorName2': '', 'UniqueName2': '', 'GameDataVec3fCameraPos': '', 'GameDataVec3fCameraAt': '', 'FovyAppendMode': 1, 'StartCalcOnly': False, 'MotionMode': 0, 'Cushion': 0.0, 'CollisionInterpolateSkip': True, 'Accept1FrameDelay': False, 'LatShiftRange': 0.0, 'LngShiftRange': 0.0, 'ActorIgnoringCollision': -1, 'ReviseModeEnd': 2}) GameRomCamera.Demo_CameraAnimFlow({'CameraName': '', 'StartFrame': 0.0, 'EndFrame': -1.0, 'DOFUse': False, 'DOFStartFrame': 0.0, 'FocalLength': 0.0, 'Aperture': 0.0, 'DOFBlurStart': 2.0, 'DOFEndFrame': 0.0, 'FocalLengthEnd': 0.0, 'ApertureEnd': 0.0, 'DOFBlurEnd': 2.0, 'InterpolateCount': 0.0, 'UniqueName': '', 'Accept1FrameDelay': False, 'TargetActor': 3, 'IsWaitFinish': True, 'BgCheck': False, 'TargetActorPosReferenceMode': 0, 'TargetActorDirReferenceMode': 0, 'OverwriteAtDist': 1.0, 'OverwriteAt': True, 'ActorName': 'DgnObj_DLC_ChampionsDungeonEntrance_A_01', 'SceneName': 'C02_0'}) GameRomCamera.Demo_CameraAnimFlow({'CameraName': '', 'StartFrame': 0.0, 'EndFrame': -1.0, 'DOFUse': False, 'DOFStartFrame': 0.0, 'FocalLength': 0.0, 'Aperture': 0.0, 'DOFBlurStart': 2.0, 'DOFEndFrame': 0.0, 'FocalLengthEnd': 0.0, 'ApertureEnd': 0.0, 'DOFBlurEnd': 2.0, 'InterpolateCount': 0.0, 'UniqueName': '', 'Accept1FrameDelay': False, 'TargetActor': 3, 'SceneName': 'C01_1', 'IsWaitFinish': True, 'BgCheck': False, 'TargetActorPosReferenceMode': 0, 'TargetActorDirReferenceMode': 0, 'OverwriteAtDist': 1.0, 'OverwriteAt': True, 'ActorName': 'DgnObj_DLC_ChampionsDungeonEntrance_A_01'}) GameRomCamera.Demo_CameraAnimFlow({'CameraName': '', 'StartFrame': 0.0, 'EndFrame': -1.0, 'DOFUse': False, 'DOFStartFrame': 0.0, 'FocalLength': 0.0, 'Aperture': 0.0, 'DOFBlurStart': 2.0, 'DOFEndFrame': 0.0, 'FocalLengthEnd': 0.0, 'ApertureEnd': 0.0, 'DOFBlurEnd': 2.0, 'InterpolateCount': 0.0, 'UniqueName': '', 'Accept1FrameDelay': False, 'TargetActor': 3, 'IsWaitFinish': True, 'SceneName': 'C01_3', 'BgCheck': False, 'TargetActorPosReferenceMode': 0, 'TargetActorDirReferenceMode': 0, 'OverwriteAtDist': 1.0, 'OverwriteAt': True, 'ActorName': 'DgnObj_DLC_ChampionsDungeonEntrance_A_01'}) } EventSystemActor.Demo_FlagOFF({'IsWaitFinish': True, 'FlagName': 'BalladOfHeroGerudo_Dungeon03_ForDemo602_0'}) } else { call Demo602_0_Cam_OneHit01() } } void Demo602_0_Cam_Gerudo02() { if EventSystemActor.CheckFlag({'FlagName': 'BalladOfHeroGerudo_Dungeon02_ForDemo602_0'}) { fork { call Demo602_0_CDungeonAnm() } { GameRomCamera.Demo_CameraAnimFlow({'CameraName': '', 'StartFrame': 0.0, 'EndFrame': -1.0, 'DOFUse': False, 'DOFStartFrame': 0.0, 'FocalLength': 0.0, 'Aperture': 0.0, 'DOFBlurStart': 2.0, 'DOFEndFrame': 0.0, 'FocalLengthEnd': 0.0, 'ApertureEnd': 0.0, 'DOFBlurEnd': 2.0, 'InterpolateCount': 0.0, 'UniqueName': '', 'Accept1FrameDelay': False, 'TargetActor': 3, 'IsWaitFinish': True, 'BgCheck': False, 'TargetActorPosReferenceMode': 0, 'TargetActorDirReferenceMode': 0, 'OverwriteAtDist': 1.0, 'OverwriteAt': True, 'ActorName': 'DgnObj_DLC_ChampionsDungeonEntrance_A_01', 'SceneName': 'C03_0'}) GameRomCamera.Demo_CameraAnimFlow({'CameraName': '', 'StartFrame': 0.0, 'EndFrame': -1.0, 'DOFUse': False, 'DOFStartFrame': 0.0, 'FocalLength': 0.0, 'Aperture': 0.0, 'DOFBlurStart': 2.0, 'DOFEndFrame': 0.0, 'FocalLengthEnd': 0.0, 'ApertureEnd': 0.0, 'DOFBlurEnd': 2.0, 'InterpolateCount': 0.0, 'UniqueName': '', 'Accept1FrameDelay': False, 'TargetActor': 3, 'IsWaitFinish': True, 'BgCheck': False, 'TargetActorPosReferenceMode': 0, 'TargetActorDirReferenceMode': 0, 'OverwriteAtDist': 1.0, 'OverwriteAt': True, 'ActorName': 'DgnObj_DLC_ChampionsDungeonEntrance_A_01', 'SceneName': 'C03_1'}) GameRomCamera.Demo_CameraAnimFlow({'CameraName': '', 'StartFrame': 0.0, 'EndFrame': -1.0, 'DOFUse': False, 'DOFStartFrame': 0.0, 'FocalLength': 0.0, 'Aperture': 0.0, 'DOFBlurStart': 2.0, 'DOFEndFrame': 0.0, 'FocalLengthEnd': 0.0, 'ApertureEnd': 0.0, 'DOFBlurEnd': 2.0, 'InterpolateCount': 0.0, 'UniqueName': '', 'Accept1FrameDelay': False, 'TargetActor': 3, 'IsWaitFinish': True, 'BgCheck': False, 'TargetActorPosReferenceMode': 0, 'TargetActorDirReferenceMode': 0, 'OverwriteAtDist': 1.0, 'OverwriteAt': True, 'ActorName': 'DgnObj_DLC_ChampionsDungeonEntrance_A_01', 'SceneName': 'C03_3'}) } EventSystemActor.Demo_FlagOFF({'IsWaitFinish': True, 'FlagName': 'BalladOfHeroGerudo_Dungeon02_ForDemo602_0'}) } else { call Demo602_0_Cam_Gerudo03() } } void Demo602_0_Cam_Water() { fork { call Demo602_0_Camera() } { FldObj_DLC_WaterShrineGround_A_01.Demo_PlayASForDemoPreMove({'IsWaitFinish': True, 'TargetIndex': -1, 'SeqBank': 0, 'IsIgnoreSame': False, 'IsEnabledAnimeDriven': -1, 'ClothWarpMode': -2, 'MorphingFrame': -1.0, 'ASName': 'Rising'}) FldObj_DLC_WaterShrineGround_A_01.Demo_PlayASForDemo({'IsWaitFinish': True, 'TargetIndex': -1, 'SeqBank': 0, 'IsIgnoreSame': False, 'IsEnabledAnimeDriven': -1, 'ClothWarpMode': -2, 'MorphingFrame': -1.0, 'ASName': 'Rising'}) } if EventSystemActor.CheckFlag({'FlagName': 'BalladOfHeroRito_Dungeon01_ForDemo602_0'}) { EventSystemActor.Demo_FlagOFF({'IsWaitFinish': True, 'FlagName': 'BalladOfHeroRito_TargetEffect'}) EventSystemActor.Demo_FlagOFF({'IsWaitFinish': True, 'FlagName': 'BalladOfHeroRito_Dungeon01_ForDemo602_0'}) } } void Demo602_0_CDungeonAnm() { fork { DgnObj_DLC_ChampionsDungeonEntrance_A_01.Demo_TrigNullASPlay({'IsWaitFinish': True, 'ASName': 'Close', 'IsIgnoreSame': True, 'ASSlot': 0, 'SequenceBank': 0}) DgnObj_DLC_ChampionsDungeonEntrance_A_01.Demo_PlayASForDemoPreMove({'IsWaitFinish': True, 'ASName': 'Rising', 'IsEnabledAnimeDriven': 1, 'SeqBank': 0, 'IsIgnoreSame': False, 'ClothWarpMode': 0, 'MorphingFrame': 0.0, 'TargetIndex': 1}) } { DgnObj_EntranceElevatorSP.Demo_PlayASForDemoPreMove({'IsWaitFinish': True, 'ASName': 'Rising', 'IsEnabledAnimeDriven': 1, 'TargetIndex': 1, 'SeqBank': 0, 'IsIgnoreSame': False, 'ClothWarpMode': 0, 'MorphingFrame': 0.0}) } { DgnObj_EntranceShutterSP.Demo_PlayASForDemoPreMove({'IsWaitFinish': True, 'IsEnabledAnimeDriven': 1, 'TargetIndex': 0, 'SeqBank': 0, 'IsIgnoreSame': False, 'ClothWarpMode': 0, 'MorphingFrame': 0.0, 'ASName': 'Rising'}) } { Obj_SweepCollision.Demo_Sweep({'DynScalingTime': 90.0, 'IsWaitFinish': True}) } { DgnObj_WarpPointSP.Demo_TrigNullASPlay({'IsWaitFinish': True, 'ASName': 'OffWait', 'ASSlot': 0, 'IsIgnoreSame': True, 'SequenceBank': 0}) DgnObj_WarpPointSP.Demo_PlayASForDemoPreMove({'IsWaitFinish': True, 'ASName': 'Rising', 'TargetIndex': 1, 'IsEnabledAnimeDriven': 1, 'SeqBank': 0, 'IsIgnoreSame': False, 'ClothWarpMode': 0, 'MorphingFrame': 0.0}) } { DgnObj_EntranceTerminalSP.Demo_TrigNullASPlay({'IsWaitFinish': True, 'ASName': 'OffWait', 'ASSlot': 0, 'IsIgnoreSame': True, 'SequenceBank': 0}) DgnObj_EntranceTerminalSP.Demo_PlayASForDemoPreMove({'IsWaitFinish': True, 'ASName': 'Rising', 'TargetIndex': 1, 'IsEnabledAnimeDriven': 1, 'SeqBank': 0, 'IsIgnoreSame': False, 'ClothWarpMode': 0, 'MorphingFrame': 0.0}) } fork { DgnObj_DLC_ChampionsDungeonEntrance_A_01.Demo_PlayASForDemo({'IsWaitFinish': True, 'ASName': 'Rising', 'IsEnabledAnimeDriven': 1, 'SeqBank': 0, 'IsIgnoreSame': False, 'ClothWarpMode': 0, 'MorphingFrame': 0.0, 'TargetIndex': 1}) } { DgnObj_EntranceElevatorSP.Demo_PlayASForDemo({'IsWaitFinish': True, 'ASName': 'Rising', 'IsEnabledAnimeDriven': 1, 'TargetIndex': 1, 'SeqBank': 0, 'IsIgnoreSame': False, 'ClothWarpMode': 0, 'MorphingFrame': 0.0}) } { DgnObj_EntranceShutterSP.Demo_PlayASForDemo({'IsWaitFinish': True, 'ASName': 'Rising', 'IsEnabledAnimeDriven': 1, 'TargetIndex': 0, 'SeqBank': 0, 'IsIgnoreSame': False, 'ClothWarpMode': 0, 'MorphingFrame': 0.0}) } { DgnObj_WarpPointSP.Demo_PlayASForDemo({'IsWaitFinish': True, 'ASName': 'Rising', 'TargetIndex': 1, 'IsEnabledAnimeDriven': 1, 'SeqBank': 0, 'IsIgnoreSame': False, 'ClothWarpMode': 0, 'MorphingFrame': 0.0}) } { DgnObj_EntranceTerminalSP.Demo_PlayASForDemo({'IsWaitFinish': True, 'ASName': 'Rising', 'TargetIndex': 1, 'IsEnabledAnimeDriven': 1, 'SeqBank': 0, 'IsIgnoreSame': False, 'ClothWarpMode': 0, 'MorphingFrame': 0.0}) } { SoundTriggerTag.Demo_SoundTrigger({'Sound': 'Demo602_0_DungeonAppearanceTrigger', 'SoundDelay': 0, 'SLinkInst': '', 'IsWaitFinish': False}) } { if EventSystemActor.CheckFlag({'FlagName': 'Demo602_0_DungeonArrival_Snow'}) { DgnObj_DLC_ChampionsDungeonEntrance_A_01.Demo_XLinkEventCreate({'IsWaitFinish': True, 'IsTargetDemoSLinkUser': False, 'ELinkKey': 'Demo602_0_DungeonArrival_Snow', 'SLinkKey': 'Demo602_0_DungeonArrival_Snow'}) EventSystemActor.Demo_FlagOFF({'IsWaitFinish': True, 'FlagName': 'Demo602_0_DungeonArrival_Snow'}) } else if EventSystemActor.CheckFlag({'FlagName': 'Demo602_0_DungeonArrival_Water'}) { DgnObj_DLC_ChampionsDungeonEntrance_A_01.Demo_XLinkEventCreate({'IsWaitFinish': True, 'IsTargetDemoSLinkUser': False, 'ELinkKey': 'Demo602_0_DungeonArrival_Water', 'SLinkKey': 'Demo602_0_DungeonArrival_Water'}) EventSystemActor.Demo_FlagOFF({'IsWaitFinish': True, 'FlagName': 'Demo602_0_DungeonArrival_Water'}) } else { DgnObj_DLC_ChampionsDungeonEntrance_A_01.Demo_XLinkEventCreate({'IsWaitFinish': True, 'IsTargetDemoSLinkUser': False, 'ELinkKey': 'Demo602_0_DungeonArrival_Normal', 'SLinkKey': 'Demo602_0_DungeonArrival_Normal'}) } } { EventSystemActor[Shake].Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 15}) EventControllerRumble.Demo_RumbleMiddle({'Count': 1, 'IsWaitFinish': False}) EventSystemActor[Shake].Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 45}) EventControllerRumble.Demo_TimeSpecRumbleMiddle({'IsWaitFinish': True, 'IsWait': True, 'Seconds': 14}) EventControllerRumble.Demo_RumbleLarge({'IsWaitFinish': True, 'Count': 1}) } } void DungeonArrival_DLC_Water() { EventMessageTransmitter1.Demo_Msg2CameraResetNoConnect({'IsWaitFinish': True}) if EventSystemActor.CheckPlayerRideHorse() { Event420: Starter.Demo_SendSignal({'SignalType': 0, 'Value': True, 'IsWaitFinish': False}) GameROMPlayer.Demo_PlayerHide({'IsWaitFinish': False}) fork { if EventSystemActor.CheckPlayerState({'PlayerState': 4}) && !EventSystemActor.CheckFlag({'FlagName': 'BalladOfHeroZora_Dungeon02_ForDemo602_0'}) { EventSystemActor[PlayerController].Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 1}) GameROMPlayer.Demo_TurnAndLookToObjectNow({'IsWaitFinish': False, 'ObjectId': 3, 'FaceId': 1, 'IsValid': False, 'ActorName': '', 'UniqueName': '', 'PosOffset': [0.0, 0.0, 0.0], 'TurnPosition': [0.0, 0.0, 0.0], 'TurnDirection': 0.0}) GameROMPlayer.Demo_PlayerHide({'IsWaitFinish': False}) } } { call Demo602_0_Cam_Water() } EventSystemActor.Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 5}) DgnObj_DLC_ChampionsDungeonEntrance_A_01.Demo_OnMUAssignSaveForUsed({'IsWaitFinish': True}) EventSystemActor.Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 10}) SoundTriggerTag.Demo_SoundTrigger({'IsWaitFinish': False, 'SoundDelay': 0, 'SLinkInst': '', 'Sound': 'ReadRiddle'}) EventSystemActor.Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 20}) if EventSystemActor.CheckFlag({'FlagName': 'NotBack_Demo016Camera'}) { GameROMPlayer.Demo_PlayerShow({'IsWaitFinish': False}) GameROMPlayer.Demo_PlayerWait({'IsWaitFinish': False}) EventSystemActor.Demo_FlagOFF({'FlagName': 'NotBack_Demo016Camera', 'IsWaitFinish': True}) } else { GameROMPlayer.Demo_PlayerShow({'IsWaitFinish': False}) GameROMPlayer.Demo_PlayerWait({'IsWaitFinish': False}) GameRomCamera.Demo_GameCamera({'IsWaitFinish': True}) } } else if EventSystemActor.CheckPlayerState({'PlayerState': 4}) { GameROMPlayer.Demo_VisibleOff({'IsWaitFinish': False}) } else { GameROMPlayer.Demo_StopInAir({'NoFixed': True, 'IsWaitFinish': False}) } goto Event420 } void Demo602_0_Cam_OneHit01() { if EventSystemActor.CheckFlag({'FlagName': 'OneHitDungeon000_ForDemo602_0'}) { fork { EventSystemActor.Demo_WaitFrame({'IsWaitFinish': True, 'Frame': 60}) SceneSoundCtrlTag.Demo_Ctrl({'BgmCtrlType': 'Mute', 'IsWaitFinish': True, 'SeCtrlType': 'None'}) } { call Demo602_0_CDungeonAnm() } { GameRomCamera.Demo_CameraAnimFlow({'CameraName': '', 'StartFrame': 0.0, 'EndFrame': -1.0, 'DOFUse': False, 'DOFStartFrame': 0.0, 'FocalLength': 0.0, 'Aperture': 0.0, 'DOFBlurStart': 2.0, 'DOFEndFrame': 0.0, 'FocalLengthEnd': 0.0, 'ApertureEnd': 0.0, 'DOFBlurEnd': 2.0, 'InterpolateCount': 0.0, 'UniqueName': '', 'Accept1FrameDelay': False, 'TargetActor': 3, 'IsWaitFinish': True, 'BgCheck': False, 'TargetActorPosReferenceMode': 0, 'TargetActorDirReferenceMode': 0, 'OverwriteAtDist': 1.0, 'OverwriteAt': True, 'ActorName': 'DgnObj_DLC_ChampionsDungeonEntrance_A_01', 'SceneName': 'C04_0'}) GameRomCamera.Demo_CameraAnimFlow({'CameraName': '', 'StartFrame': 0.0, 'EndFrame': -1.0, 'DOFUse': False, 'DOFStartFrame': 0.0, 'FocalLength': 0.0, 'Aperture': 0.0, 'DOFBlurStart': 2.0, 'DOFEndFrame': 0.0, 'FocalLengthEnd': 0.0, 'ApertureEnd': 0.0, 'DOFBlurEnd': 2.0, 'InterpolateCount': 0.0, 'UniqueName': '', 'Accept1FrameDelay': False, 'TargetActor': 3, 'IsWaitFinish': True, 'BgCheck': False, 'TargetActorPosReferenceMode': 0, 'TargetActorDirReferenceMode': 0, 'OverwriteAtDist': 1.0, 'OverwriteAt': True, 'ActorName': 'DgnObj_DLC_ChampionsDungeonEntrance_A_01', 'SceneName': 'C04_1'}) GameRomCamera.Demo_CameraAnimFlow({'CameraName': '', 'StartFrame': 0.0, 'EndFrame': -1.0, 'DOFUse': False, 'DOFStartFrame': 0.0, 'FocalLength': 0.0, 'Aperture': 0.0, 'DOFBlurStart': 2.0, 'DOFEndFrame': 0.0, 'FocalLengthEnd': 0.0, 'ApertureEnd': 0.0, 'DOFBlurEnd': 2.0, 'InterpolateCount': 0.0, 'UniqueName': '', 'Accept1FrameDelay': False, 'TargetActor': 3, 'IsWaitFinish': True, 'BgCheck': False, 'TargetActorPosReferenceMode': 0, 'TargetActorDirReferenceMode': 0, 'OverwriteAtDist': 1.0, 'OverwriteAt': True, 'ActorName': 'DgnObj_DLC_ChampionsDungeonEntrance_A_01', 'SceneName': 'C04_3'}) } EventSystemActor.Demo_FlagOFF({'IsWaitFinish': True, 'FlagName': 'OneHitDungeon000_ForDemo602_0'}) } else { call Demo602_0_Camera() } }
33c3d690eba1127f97a6cebf99f6fd10a0d23599
0744dcc5394cebf57ebcba343747af6871b67017
/external/iotjs/deps/jerry/jerry-core/jrt/jrt-bit-fields.h
c5aaf373fb8f811fbd480aa08c1fa3e9a709dd7c
[ "LicenseRef-scancode-dco-1.1", "Apache-2.0", "MIT" ]
permissive
Samsung/TizenRT
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
refs/heads/master
2023-08-31T08:59:33.327998
2023-08-08T06:09:20
2023-08-31T04:38:20
82,517,252
590
719
Apache-2.0
2023-09-14T06:54:49
2017-02-20T04:38:30
C
UTF-8
C
false
false
1,620
h
jrt-bit-fields.h
/* Copyright JS Foundation and other contributors, http://js.foundation * * 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 JRT_BIT_FIELDS_H #define JRT_BIT_FIELDS_H /** * Extract a bit-field. * * @param type type of container * @param container container to extract bit-field from * @param lsb least significant bit of the value to be extracted * @param width width of the bit-field to be extracted * @return bit-field's value */ #define JRT_EXTRACT_BIT_FIELD(type, container, lsb, width) \ (((container) >> lsb) & ((((type) 1) << (width)) - 1)) /** * Set a bit-field. * * @param type type of container * @param container container to insert bit-field to * @param new_bit_field_value value of bit-field to insert * @param lsb least significant bit of the value to be inserted * @param width width of the bit-field to be inserted * @return bit-field's value */ #define JRT_SET_BIT_FIELD_VALUE(type, container, new_bit_field_value, lsb, width) \ (((container) & ~(((((type) 1) << (width)) - 1) << (lsb))) | (((type) new_bit_field_value) << (lsb))) #endif /* !JRT_BIT_FIELDS_H */
1264b27fbe16d8d2fe2f8d0f12b27a14124c4390
4cd1537b92864ee108def7886aafc0f924f97c0f
/ext/engine_hooks.h
4fc82d78fd19d2aaa63bd64d294eafbacf8f0d69
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
DataDog/dd-trace-php
68f08674208ef9ec1c874e3eabd7b88f1d6dd5dd
014989e42bfa5919f451cee3ae2b57cc35bdee9b
refs/heads/master
2023-09-01T15:36:22.838634
2023-09-01T13:17:02
2023-09-01T13:17:02
119,990,860
363
166
NOASSERTION
2023-09-13T16:09:22
2018-02-02T14:21:54
PHP
UTF-8
C
false
false
3,435
h
engine_hooks.h
#ifndef DD_ENGINE_HOOKS_H #define DD_ENGINE_HOOKS_H #include <Zend/zend.h> #include <Zend/zend_exceptions.h> #if PHP_VERSION_ID >= 80000 #include <Zend/zend_observer.h> #endif #include <php.h> #include <stdint.h> #include "compatibility.h" #include "ddtrace.h" #include "ddtrace_string.h" ZEND_EXTERN_MODULE_GLOBALS(ddtrace) void ddtrace_engine_hooks_minit(void); void ddtrace_fetch_profiling_symbols(void); void ddtrace_engine_hooks_mshutdown(void); void ddtrace_compile_time_reset(void); int64_t ddtrace_compile_time_get(void); struct ddtrace_error_handling { int type; int lineno; #if PHP_VERSION_ID < 80000 char *message; #else zend_string *message; #endif #if PHP_VERSION_ID < 80100 char *file; #else zend_string *file; #endif int error_reporting; zend_error_handling error_handling; }; typedef struct ddtrace_error_handling ddtrace_error_handling; struct ddtrace_sandbox_backup { ddtrace_error_handling eh; zend_object *exception, *prev_exception; }; typedef struct ddtrace_sandbox_backup ddtrace_sandbox_backup; inline void ddtrace_backup_error_handling(ddtrace_error_handling *eh, zend_error_handling_t mode) { eh->type = PG(last_error_type); eh->lineno = PG(last_error_lineno); eh->message = PG(last_error_message); eh->file = PG(last_error_file); // Need to null these so that if another error comes along that they don't get double-freed PG(last_error_message) = NULL; PG(last_error_file) = NULL; eh->error_reporting = EG(error_reporting); EG(error_reporting) = 0; zend_replace_error_handling(mode, NULL, &eh->error_handling); } void ddtrace_restore_error_handling(ddtrace_error_handling *eh); inline void ddtrace_maybe_clear_exception(void) { if (EG(exception)) { zend_clear_exception(); } } inline ddtrace_sandbox_backup ddtrace_sandbox_begin(void) { ddtrace_sandbox_backup backup = {.exception = NULL, .prev_exception = NULL}; if (EG(exception)) { backup.exception = EG(exception); backup.prev_exception = EG(prev_exception); EG(exception) = NULL; EG(prev_exception) = NULL; } ddtrace_backup_error_handling(&backup.eh, EH_THROW); return backup; } inline void ddtrace_sandbox_end(ddtrace_sandbox_backup *backup) { ddtrace_restore_error_handling(&backup->eh); ddtrace_maybe_clear_exception(); if (backup->exception) { EG(exception) = backup->exception; EG(prev_exception) = backup->prev_exception; zend_throw_exception_internal(NULL); } } #if PHP_VERSION_ID < 80000 PHP_FUNCTION(ddtrace_internal_function_handler); #define DDTRACE_ERROR_CB_PARAMETERS \ int orig_type, const char *error_filename, const uint error_lineno, const char *format, va_list args #define DDTRACE_ERROR_CB_PARAM_PASSTHRU orig_type, error_filename, error_lineno, format, args #else #if PHP_VERSION_ID < 80100 #define DDTRACE_ERROR_CB_PARAMETERS \ int orig_type, const char *error_filename, const uint32_t error_lineno, zend_string *message #else #define DDTRACE_ERROR_CB_PARAMETERS \ int orig_type, zend_string *error_filename, const uint32_t error_lineno, zend_string *message #endif #define DDTRACE_ERROR_CB_PARAM_PASSTHRU orig_type, error_filename, error_lineno, message #endif extern void (*ddtrace_prev_error_cb)(DDTRACE_ERROR_CB_PARAMETERS); void ddtrace_error_cb(DDTRACE_ERROR_CB_PARAMETERS); #endif // DD_ENGINE_HOOKS_H
6bc427c79399b55f062a81f003c9f2dec5d154b7
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/hc32/libraries/hc32f460_ddl/midwares/hc32/usb/usb_device_lib/device_core/usb_dev_int.c
fa53d985491542a03d7f0ca8dd1cd3eaafca9d01
[ "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
RT-Thread/rt-thread
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
3602f891211904a27dcbd51e5ba72fefce7326b2
refs/heads/master
2023-09-01T04:10:20.295801
2023-08-31T16:20:55
2023-08-31T16:20:55
7,408,108
9,599
5,805
Apache-2.0
2023-09-14T13:37:26
2013-01-02T14:49:21
C
UTF-8
C
false
false
15,436
c
usb_dev_int.c
/** ******************************************************************************* * @file usb_dev_int.c * @brief Peripheral Device interrupt subroutines. @verbatim Change Logs: Date Author Notes 2022-03-31 CDT First version @endverbatim ******************************************************************************* * Copyright (C) 2022, Xiaohua Semiconductor Co., Ltd. All rights reserved. * * This software component is licensed by XHSC under BSD 3-Clause license * (the "License"); You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ******************************************************************************* */ /******************************************************************************* * Include files ******************************************************************************/ #include "usb_dev_int.h" /** * @addtogroup LL_USB_LIB * @{ */ /** * @addtogroup LL_USB_DEV_CORE * @{ */ /******************************************************************************* * Function implementation - global ('extern') and local ('static') ******************************************************************************/ /** * @brief read the endpoint flags * @param [in] pdev device instance * @param [in] epnum endpoint number * @retval status */ static uint32_t usb_rddevinep(usb_core_instance *pdev, uint8_t epnum) { uint32_t u32diepmsk; uint32_t u32diepempmsk; u32diepmsk = READ_REG32(pdev->regs.DREGS->DIEPMSK); u32diepempmsk = READ_REG32(pdev->regs.DREGS->DIEPEMPMSK); u32diepmsk |= (((u32diepempmsk >> epnum) & 0x1UL) << 7U); return (READ_REG32(pdev->regs.INEP_REGS[epnum]->DIEPINT) & u32diepmsk); } /** * @brief check FIFO for the next packet to be loaded * @param [in] pdev device instance * @param [in] epnum endpoint number * @retval None */ static void usb_wrblanktxfifo(usb_core_instance *pdev, uint32_t epnum) { USB_DEV_EP *ep; uint32_t u32Len; uint32_t u32Len32b; uint16_t u16spclen; uint32_t u32diepempmsk; ep = &pdev->dev.in_ep[epnum]; u32Len = ep->xfer_len - ep->xfer_count; if (u32Len > ep->maxpacket) { u32Len = ep->maxpacket; } u32Len32b = (u32Len + 3UL) >> 2; u16spclen = usb_rdineptxfspcavail(pdev, epnum); while ((u16spclen >= u32Len32b) && (ep->xfer_count < ep->xfer_len)) { u32Len = ep->xfer_len - ep->xfer_count; if (u32Len > ep->maxpacket) { u32Len = ep->maxpacket; } u32Len32b = (u32Len + 3UL) >> 2; usb_wrpkt(&pdev->regs, ep->xfer_buff, (uint8_t)epnum, (uint16_t)u32Len, pdev->basic_cfgs.dmaen); ep->xfer_buff += u32Len; ep->xfer_count += u32Len; u16spclen = usb_rdineptxfspcavail(pdev, epnum); } if (u32Len == 0UL) { u32diepempmsk = 0x01UL << epnum; CLR_REG32_BIT(pdev->regs.DREGS->DIEPEMPMSK, u32diepempmsk); } } #ifdef VBUS_SENSING_ENABLED /** * @brief Indicates that the USB_OTG controller has detected a connection * @param [in] pdev device instance * @retval None */ static void usb_sessionrequest_isr(usb_core_instance *pdev) { dev_int_cbkpr->devctrlconnect(pdev, 1U); WRITE_REG32(pdev->regs.GREGS->GINTSTS, USBFS_GINTSTS_VBUSVINT); if (0U != pdev->basic_cfgs.low_power) { CLR_REG32_BIT(*pdev->regs.GCCTL, USBFS_GCCTL_STPPCLK | USBFS_GCCTL_GATEHCLK); } } #endif /** * @brief Indicates that the controller has detected a resume or remote Wake-up sequence * @param [in] pdev device instance * @retval None */ static void usb_resume_isr(usb_core_instance *pdev) { if (0U != pdev->basic_cfgs.low_power) { CLR_REG32_BIT(*pdev->regs.GCCTL, USBFS_GCCTL_STPPCLK | USBFS_GCCTL_GATEHCLK); } CLR_REG32_BIT(pdev->regs.DREGS->DCTL, USBFS_DCTL_RWUSIG); dev_int_cbkpr->Resume(pdev); WRITE_REG32(pdev->regs.GREGS->GINTSTS, USBFS_GINTSTS_WKUINT); } /** * @brief Indicates that SUSPEND state has been detected on the USB * @param [in] pdev device instance * @retval None */ static void usb_susp_isr(usb_core_instance *pdev) { uint32_t u32dsts; uint8_t u8PrevStatus; dev_int_cbkpr->Suspend(pdev); u32dsts = READ_REG32(pdev->regs.DREGS->DSTS); WRITE_REG32(pdev->regs.GREGS->GINTSTS, USBFS_GINTSTS_USBSUSP); u8PrevStatus = pdev->dev.device_cur_status; if ((u8PrevStatus == USB_DEV_CONFIGURED) && (0U != pdev->basic_cfgs.low_power) && ((u32dsts & 1UL) != 0UL) && (pdev->dev.connection_status == 1U)) { SET_REG32_BIT(*pdev->regs.GCCTL, USBFS_GCCTL_STPPCLK); SET_REG32_BIT(*pdev->regs.GCCTL, USBFS_GCCTL_GATEHCLK); } } /** * @brief Indicates that at leadt one IN EP has a pending interrupt * @param [in] pdev device instance * @retval None */ static void usb_inep_isr(usb_core_instance *pdev) { uint32_t u32diepint; uint32_t u32EpIntr; uint8_t u8epnum; uint32_t u32diepempmsk; u32EpIntr = usb_getalliepintr(&pdev->regs); u8epnum = 0U; while ((0U != u32EpIntr) && (u8epnum <= USB_MAX_TX_FIFOS)) { if ((u32EpIntr & 0x1UL) != 0UL) { u32diepint = usb_rddevinep(pdev, u8epnum); if ((u32diepint & XFER_COMPL) != 0UL) { u32diepempmsk = 1UL << u8epnum; CLR_REG32_BIT(pdev->regs.DREGS->DIEPEMPMSK, u32diepempmsk); WRITE_REG32(pdev->regs.INEP_REGS[u8epnum]->DIEPINT, XFER_COMPL); dev_int_cbkpr->DataInStage(pdev, u8epnum); if (pdev->basic_cfgs.dmaen == 1U) { if ((u8epnum == 0U) && (pdev->dev.device_state == USB_EP0_STATUS_IN)) { pdev->dev.out_ep[0].xfer_len = 64U; pdev->dev.out_ep[0].rem_data_len = 64U; pdev->dev.out_ep[0].total_data_len = 64U; usb_ep0revcfg(&pdev->regs, pdev->basic_cfgs.dmaen, pdev->dev.setup_pkt_buf); pdev->dev.device_state = USB_EP0_IDLE; } } } if ((u32diepint & EPDISABLED) != 0UL) { WRITE_REG32(pdev->regs.INEP_REGS[u8epnum]->DIEPINT, EPDISABLED); } if ((u32diepint & TIME_OUT) != 0UL) { WRITE_REG32(pdev->regs.INEP_REGS[u8epnum]->DIEPINT, TIME_OUT); } if ((u32diepint & INTKNTXFEMP) != 0UL) { WRITE_REG32(pdev->regs.INEP_REGS[u8epnum]->DIEPINT, INTKNTXFEMP); } if ((u32diepint & INEPNAKEFF) != 0UL) { WRITE_REG32(pdev->regs.INEP_REGS[u8epnum]->DIEPINT, INEPNAKEFF); } if ((u32diepint & TXFEMP) != 0UL) { usb_wrblanktxfifo(pdev, u8epnum); WRITE_REG32(pdev->regs.INEP_REGS[u8epnum]->DIEPINT, TXFEMP); } } u8epnum++; u32EpIntr >>= 1U; } } /** * @brief Indicates that an OUT EP has a pending Interrupt * @param [in] pdev device instance * @retval None */ static void usb_outep_isr(usb_core_instance *pdev) { uint32_t u32EpIntr; uint32_t u32doepint; uint8_t u8epnum = 0U; uint32_t u8Xfer; uint32_t u32ReadEpSize; u32EpIntr = usb_getalloepintr(&pdev->regs); while ((u32EpIntr != 0UL) && (u8epnum <= USB_MAX_TX_FIFOS)) { if ((u32EpIntr & 0x1UL) != 0UL) { u32doepint = usb_getoepintbit(&pdev->regs, u8epnum); if ((u32doepint & XFER_COMPL) != 0UL) { WRITE_REG32(pdev->regs.OUTEP_REGS[u8epnum]->DOEPINT, XFER_COMPL); if (pdev->basic_cfgs.dmaen == 1U) { u32ReadEpSize = (READ_REG32(pdev->regs.OUTEP_REGS[u8epnum]->DOEPTSIZ) & USBFS_DOEPTSIZ_XFRSIZ); u8Xfer = LL_MIN(pdev->dev.out_ep[u8epnum].maxpacket, pdev->dev.out_ep[u8epnum].xfer_len); pdev->dev.out_ep[u8epnum].xfer_count = u8Xfer - u32ReadEpSize; if (u8epnum != 0U) { pdev->dev.out_ep[u8epnum].xfer_count = pdev->dev.out_ep[u8epnum].xfer_len - u32ReadEpSize; } } dev_int_cbkpr->DataOutStage(pdev, u8epnum); if (pdev->basic_cfgs.dmaen == 1U) { if ((u8epnum == 0U) && (pdev->dev.device_state == USB_EP0_STATUS_OUT)) { pdev->dev.out_ep[0].xfer_len = 64U; pdev->dev.out_ep[0].rem_data_len = 64U; pdev->dev.out_ep[0].total_data_len = 64U; usb_ep0revcfg(&pdev->regs, pdev->basic_cfgs.dmaen, pdev->dev.setup_pkt_buf); pdev->dev.device_state = USB_EP0_IDLE; } } } if ((u32doepint & EPDISABLED) != 0UL) { WRITE_REG32(pdev->regs.OUTEP_REGS[u8epnum]->DOEPINT, EPDISABLED); } if (u8epnum == 0U) { u32doepint = usb_getoepintbit(&pdev->regs, u8epnum); if ((u32doepint & SETUP_BIT) != 0UL) { dev_int_cbkpr->SetupStage(pdev); WRITE_REG32(pdev->regs.OUTEP_REGS[u8epnum]->DOEPINT, SETUP_BIT); } } } u8epnum++; u32EpIntr >>= 1U; } } /** * @brief Handles the SOF Interrupts * @param [in] pdev device instance * @retval None */ static void usb_sof_isr(usb_core_instance *pdev) { dev_int_cbkpr->SOF(pdev); WRITE_REG32(pdev->regs.GREGS->GINTSTS, USBFS_GINTSTS_SOF); } /** * @brief Handles the Rx Status Queue Level Interrupt * @param [in] pdev device instance * @retval status */ static void usb_rxstsqlvl_isr(usb_core_instance *pdev) { uint32_t u32grxsts; USB_DEV_EP *ep; uint8_t u8epnum; uint8_t u8PktStatus; uint16_t u16ByteCnt; CLR_REG32_BIT(pdev->regs.GREGS->GINTMSK, USBFS_GINTMSK_RXFNEM); u32grxsts = READ_REG32(pdev->regs.GREGS->GRXSTSP); u8epnum = (uint8_t)(u32grxsts & USBFS_GRXSTSP_CHNUM_EPNUM); u8PktStatus = (uint8_t)((u32grxsts & USBFS_GRXSTSP_PKTSTS) >> USBFS_GRXSTSP_PKTSTS_POS); u16ByteCnt = (uint16_t)((u32grxsts & USBFS_GRXSTSP_BCNT) >> USBFS_GRXSTSP_BCNT_POS); ep = &pdev->dev.out_ep[u8epnum]; switch (u8PktStatus) { case STS_DATA_UPDT: if (0U != u16ByteCnt) { usb_rdpkt(&pdev->regs, ep->xfer_buff, u16ByteCnt); ep->xfer_buff += u16ByteCnt; ep->xfer_count += u16ByteCnt; } else { ; } break; case STS_SETUP_UPDT: /* Copy the setup packet received in FIFO into the setup buffer in RAM */ usb_rdpkt(&pdev->regs, pdev->dev.setup_pkt_buf, 8U); ep->xfer_count += u16ByteCnt; break; case STS_GOUT_NAK: case STS_XFER_COMP: case STS_SETUP_COMP: break; default: break; } SET_REG32_BIT(pdev->regs.GREGS->GINTMSK, USBFS_GINTMSK_RXFNEM); } /** * @brief This interrupt occurs when a USB Reset is detected * @param [in] pdev device instance * @retval None */ static void usb_reset_isr(usb_core_instance *pdev) { uint32_t i; CLR_REG32_BIT(pdev->regs.DREGS->DCTL, USBFS_DCTL_RWUSIG); usb_txfifoflush(&pdev->regs, 0UL); for (i = 0UL; i < pdev->basic_cfgs.dev_epnum ; i++) { WRITE_REG32(pdev->regs.INEP_REGS[i]->DIEPINT, 0xFFUL); WRITE_REG32(pdev->regs.OUTEP_REGS[i]->DOEPINT, 0xFFUL); } WRITE_REG32(pdev->regs.DREGS->DAINT, 0xFFFFFFFFUL); WRITE_REG32(pdev->regs.DREGS->DAINTMSK, 1UL | (1UL << USBFS_DAINTMSK_OEPINTM_POS)); //todo: bit5 if need be set? WRITE_REG32(pdev->regs.DREGS->DOEPMSK, USBFS_DOEPMSK_STUPM | USBFS_DOEPMSK_XFRCM | USBFS_DOEPMSK_EPDM); #ifdef USB_OTG_HS_DEDICATED_EP1_ENABLED WRITE_REG32(pdev->regs.DREGS->DOUTEP1MSK, USBFS_DOEPMSK_STUPM | USBFS_DOEPMSK_XFRCM | USBFS_DOEPMSK_EPDM); #endif WRITE_REG32(pdev->regs.DREGS->DIEPMSK, USBFS_DIEPMSK_XFRCM | USBFS_DIEPMSK_TOM | USBFS_DIEPMSK_EPDM); #ifdef USB_OTG_HS_DEDICATED_EP1_ENABLED WRITE_REG32(pdev->regs.DREGS->DINEP1MSK, USBFS_DIEPMSK_XFRCM | USBFS_DIEPMSK_TOM | USBFS_DIEPMSK_EPDM); #endif CLR_REG32_BIT(pdev->regs.DREGS->DCFG, USBFS_DCFG_DAD); pdev->dev.out_ep[0].xfer_len = 64U; pdev->dev.out_ep[0].rem_data_len = 64U; pdev->dev.out_ep[0].total_data_len = 64U; usb_ep0revcfg(&pdev->regs, pdev->basic_cfgs.dmaen, pdev->dev.setup_pkt_buf); WRITE_REG32(pdev->regs.GREGS->GINTSTS, USBFS_GINTSTS_USBRST); dev_int_cbkpr->Reset(pdev); } /** * @brief Read the device status register and set the device speed * @param [in] pdev device instance * @retval None */ static void usb_enumfinish_isr(usb_core_instance *pdev) { usb_ep0activate(&pdev->regs); usb_setaroundtim(pdev); WRITE_REG32(pdev->regs.GREGS->GINTSTS, USBFS_GINTSTS_ENUMDNE); } /** * @brief handle the ISO IN incomplete interrupt * @param [in] pdev device instance * @retval None */ static void usb_isoinincomplt_isr(usb_core_instance *pdev) { dev_int_cbkpr->IsoINIncomplete(pdev); WRITE_REG32(pdev->regs.GREGS->GINTSTS, USBFS_GINTSTS_IISOIXFR); } /** * @brief handle the ISO OUT incomplete interrupt * @param [in] pdev device instance * @retval None */ static void usb_isooutincomplt_isr(usb_core_instance *pdev) { dev_int_cbkpr->IsoOUTIncomplete(pdev); WRITE_REG32(pdev->regs.GREGS->GINTSTS, USBFS_GINTSTS_IPXFR_INCOMPISOOUT); } /** * @brief handles all USB Interrupts * @param [in] pdev device instance * @retval None */ void usb_isr_handler(usb_core_instance *pdev) { uint32_t u32gintsts; if (0U == usb_getcurmod(&pdev->regs)) { u32gintsts = usb_getcoreintr(&pdev->regs); if (u32gintsts == 0UL) { return; } if ((u32gintsts & OUTEP_INT) != 0UL) { usb_outep_isr(pdev); } if ((u32gintsts & INEP_INT) != 0UL) { usb_inep_isr(pdev); } if ((u32gintsts & MODEMIS_INT) != 0UL) { WRITE_REG32(pdev->regs.GREGS->GINTSTS, MODEMIS_INT); } if ((u32gintsts & WAKEUP_INT) != 0UL) { usb_resume_isr(pdev); } if ((u32gintsts & USBSUSP_INT) != 0UL) { usb_susp_isr(pdev); } if ((u32gintsts & SOF_INT) != 0UL) { usb_sof_isr(pdev); } if ((u32gintsts & RXFLVL_INT) != 0UL) { usb_rxstsqlvl_isr(pdev); } if ((u32gintsts & USBRST_INT) != 0UL) { usb_reset_isr(pdev); } if ((u32gintsts & ENUMDONE_INT) != 0UL) { usb_enumfinish_isr(pdev); } if ((u32gintsts & INCOMPLSOIN) != 0UL) { usb_isoinincomplt_isr(pdev); } if ((u32gintsts & INCOMPLSOOUT) != 0UL) { usb_isooutincomplt_isr(pdev); } #ifdef VBUS_SENSING_ENABLED if ((u32gintsts & VBUSV_INT) != 0UL) { usb_sessionrequest_isr(pdev); } #endif } } /** * @} */ /** * @} */ /****************************************************************************** * EOF (not truncated) *****************************************************************************/
ba4decdb5ed5a8deb169c0d79a58ccaf82b70ab1
f3eed0234b4d0ad2bbb2abd700cf1e2c7a0e8a1d
/AKWF-c/AKWF_stereo/AKWF_stereo_0072.h
7684ad51a86f2c164616314812faf316353d5000
[ "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
6,478
h
AKWF_stereo_0072.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_stereo_0072 256 samples +-----------------------------------------------------------------------------------------------------------------+ | *************** * | | ****************** * | |************* * * | | * * * **************| | * ** *********************** | | * ********* ***** *** | | *** ************ ** | | ** * ** | | ** * | | ** * | | * | | * | | * | | * | | * | +-----------------------------------------------------------------------------------------------------------------+ */ const uint16_t AKWF_stereo_0072 [] = { 33415, 34217, 34148, 35985, 34292, 36242, 34304, 36405, 34194, 35883, 33851, 35645, 33579, 35346, 33617, 35388, 33763, 35483, 34070, 35773, 34215, 36066, 34455, 36366, 34566, 36601, 34710, 36798, 34789, 36956, 34886, 37085, 34957, 37229, 35037, 37366, 35130, 37537, 35206, 37690, 35299, 37884, 35383, 38048, 35470, 38232, 35539, 38394, 35630, 38582, 35702, 38733, 35774, 38910, 35847, 39066, 35917, 39245, 35992, 39395, 36050, 39578, 36137, 39738, 36185, 39907, 36274, 40068, 36315, 40247, 36411, 40400, 36440, 40567, 36542, 40733, 36578, 40903, 36678, 41060, 36708, 41230, 36815, 41398, 36854, 41559, 36943, 41723, 37000, 41893, 37085, 42059, 37153, 42214, 37213, 42388, 37320, 42549, 37329, 42713, 37467, 42868, 37465, 43050, 37664, 43197, 37605, 43368, 37855, 43523, 37743, 43707, 38059, 43843, 37856, 44034, 38287, 44170, 37948, 44370, 38570, 44473, 37831, 44741, 36044, 45196, 36215, 45308, 36402, 45494, 37919, 45417, 38133, 45576, 38774, 45636, 38965, 45808, 39229, 45920, 39381, 46076, 39502, 46243, 39634, 46379, 39676, 46560, 39799, 46683, 39831, 46907, 39914, 46979, 39956, 47233, 40028, 47295, 40093, 47575, 40118, 47589, 40226, 47912, 40223, 47907, 40349, 48235, 40320, 48212, 40487, 48570, 40429, 48529, 40603, 48870, 40553, 48859, 40724, 49179, 40670, 49177, 40829, 49462, 40829, 49540, 40925, 49730, 40982, 49889, 41018, 49994, 41158, 50262, 41087, 50222, 41361, 50660, 41161, 50456, 41555, 51042, 41222, 50673, 41781, 51456, 41268, 50875, 41999, 51839, 41270, 51114, 42075, 52253, 41303, 51333, 42317, 52623, 41502, 51582, 42527, 52939, 41670, 51871, 42682, 53218, 41893, 52257, 42685, 53325, 42319, 52912, 42262, 52906, 44032, 55196, 26133, 32645, 20450, 24779, 15786, 15925, 21478, 17504, 24513, 14736, 25215, 10732, 27442, 11920, 26355, 11636, 27792, 15286, 26661, 14577, 28152, 15486, 27423, 12687, 28706, 12882, 27896, 11777, 28517, 13760, 27603, 14206, 27906, 15707, 27224, 15049, 27399, 14913, 26920, 13961, 26830, 14104, 26355, 14343, 26040, 15104, 25687, 15590, 25311, 15678, 25142, 15621, 24772, 15286, 24667, 15430, 24230, 15462, 24174, 16067, 23769, 16174, 23778, 16582, 23494, 16386, 23599, 16610, 23401, 16442, 23512, 16835, 23424, 16920, 23537, 17356, 23571, 17391, 23702, 17666, 23906, 17640, 23970, 17863, 24372, 17943, 24134, 18296, 23782, 18566, 24071, 18781, 24458, 18938, 25221, 19007, 25510, 19166, 25997, 19296, 26288, 19530, 26609, 19684, 26882, 19913, 27137, 20058, 27392, 20256, 27575, 20380, 27814, 20593, 27960, 20751, 28134, 20958, 28252, 21126, 28395, 21322, 28470, 21462, 28562, 21645, 28634, 21805, 28664, 21980, 28708, 22138, 28701, 22323, 28744, 22478, 28686, 22642, 28726, 22797, 28651, 22970, 28680, 23118, 28577, 23290, 28622, 23452, 28518, 23621, 28543, 23767, 28462, 23943, 28493, 24097, 28429, 24262, 28444, 24422, 28442, 24590, 28428, 24755, 28485, 24913, 28450, 25092, 28595, 25247, 28493, 25427, 28744, 25577, 28560, 25786, 28895, 25922, 28673, 26134, 29159, 26257, 28872, 26484, 29445, 26591, 29070, 26836, 29765, 26931, 29278, 27195, 30093, 27269, 29508, 27560, 30430, 27610, 29791, 27909, 24090, 28936, 24266, 29123, 24245, 29300, 28187, 28939, 29174, 28968, 30503, 28990, 31293, 29037, 31661, 29203, 32248, 29273, 32230, 29498, 32696, 29587, 32517, 29827, 32910, 29924, 32675, 30171, 32993, 30282, 32759, 30515, 33030, 30643, 32820, 30859, 33037, 31007, 32866, 31196, 33034, 31369, 32897, 31525, 33036, 31734, 32937, 31855, 33042, 32102, 32976, 32180, 33065, 32468, 33018, 32502, 33099, 32838, 33070, 32817, 33161, 33218, 33120, 33125, 33244, 33603, 33182, 33401, 33374, 34051, 33172, 33487, 32446, 31920, 33017, 33174, };
dd15d490e080c9560a4f1be05066f596dace93c1
1885ce333f6980ab6aad764b3f8caf42094d9f7d
/test/e2e/test_master/skia/include/core/SkYUVAIndex.h
e9b7acb573e36aaa8f3f5893b74b67c39e524d15
[ "MIT" ]
permissive
satya-das/cppparser
1dbccdeed4287c36c61edc30190c82de447e415b
f9a4cfac1a3af7286332056d7c661d86b6c35eb3
refs/heads/master
2023-07-06T00:55:23.382303
2022-10-03T19:40:05
2022-10-03T19:40:05
16,642,636
194
26
MIT
2023-06-26T13:44:32
2014-02-08T12:20:01
C++
UTF-8
C
false
false
2,573
h
SkYUVAIndex.h
/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkYUVAIndex_DEFINED # define SkYUVAIndex_DEFINED # include "include/core/SkColor.h" # include "include/core/SkTypes.h" /** \struct SkYUVAIndex Describes from which image source and which channel to read each individual YUVA plane. SkYUVAIndex contains a index for which image source to read from and a enum for which channel to read from. */ struct SK_API SkYUVAIndex { bool operator==(const SkYUVAIndex& that) const { return this->fIndex == that.fIndex && this->fChannel == that.fChannel; } bool operator!=(const SkYUVAIndex& that) const { return !(*this == that); } // Index in the array of SkYUVAIndex // TODO: rename as Component enum Index { kY_Index = 0, kU_Index = 1, kV_Index = 2, kA_Index = 3, kLast_Index = kA_Index }; static constexpr int kIndexCount = kLast_Index + 1; /** The index is a number between -1..3 which defines which image source to read from, where -1 * means the image source doesn't exist. The assumption is we will always have image sources for * each of YUV planes, but optionally have image source for A plane. */ int fIndex; /** The channel describes from which channel to read the info from. Currently we only deal with * YUV and NV12 and channel info is ignored. */ SkColorChannel fChannel; static bool AreValidIndices(const SkYUVAIndex yuvaIndices[4], int* numPlanes) { // Note that 'numPlanes' is always filled in even if the indices are not valid. // This means it can always be used to process the backing resources (but be careful // of empty intervening slots). int maxSlotUsed = -1; bool used[4] = {false, false, false, false}; bool valid = true; for (int i = 0; i < 4; ++i) { if (yuvaIndices[i].fIndex < 0) { if (SkYUVAIndex::kA_Index != i) { valid = false; } } else { if (yuvaIndices[i].fIndex > 3) { valid = false; } else { maxSlotUsed = SkTMax(yuvaIndices[i].fIndex, maxSlotUsed); used[i] = true; } } } // All the used slots should be packed starting at 0 with no gaps for (int i = 0; i <= maxSlotUsed; ++i) { if (!used[i]) { valid = false; } } *numPlanes = maxSlotUsed + 1; return valid; } }; #endif
b3c53786dc3aae9ac2d9829601908dad1fd5c6be
89ac799bd004042f913c9205abd22feaf847f5be
/src/linker.h
02a29b6c80276b7c012c88f9ea7a2fc92ae9ff72
[]
no_license
FoxdieTeam/mgs_reversing
de0b501e9a6318bf817e0d0f03af34c836a2f0b6
d057e3eb8bebeb645ca23db6ce690577268f59d5
refs/heads/master
2023-07-21T02:31:57.827478
2023-07-17T10:50:39
2023-07-17T10:50:39
223,033,157
270
35
null
2023-09-14T21:49:31
2019-11-20T21:44:13
C
UTF-8
C
false
false
964
h
linker.h
#ifndef LINKER_H_ #define LINKER_H_ #define SECTION(x) __attribute__((section(x))) #define COUNTOF(x) sizeof(x) / sizeof(x[0]) #define CTASTR2(pre, post) pre##post #define CTASTR(pre, post) CTASTR2(pre, post) #define STATIC_ASSERT(cond, msg, line) \ typedef struct \ { \ int CTASTR(static_assertion_failed_, msg) : !!(cond); \ } CTASTR(static_assertion_failed_, line) #ifdef NO_ASSERT_SIZE // set in everything.h #define STATIC_ASSERT_SIZE(struct, size) #else #define STATIC_ASSERT_SIZE(struct, size) STATIC_ASSERT(sizeof(struct) == size, wrong_size, __LINE__) #endif #endif // LINKER_H_
91ad2f865848ecb216d16328dd81bdbed47955db
549f66608f0cb4e50cee2e51c53206e798ab82cd
/runtime/POSIX/fd_64.c
aea9ebacef58e049c3f793b3d1bd6f9ee0328bce
[ "NCSA" ]
permissive
klee/klee
c8da2f9668ee199af47cd2c784cea979017d7704
7082eafd05b4f268132ab94772c0243dbebf5087
refs/heads/master
2023-08-04T08:10:38.619540
2023-06-23T21:34:12
2023-07-21T09:00:02
11,568,417
2,339
679
NOASSERTION
2023-09-11T10:23:26
2013-07-21T22:03:03
C++
UTF-8
C
false
false
3,150
c
fd_64.c
//===-- fd_64.c -----------------------------------------------------------===// // // The KLEE Symbolic Virtual Machine // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #if __GNUC__ #if __x86_64__ || __ppc64__ #define ENV64 #else #define ENV32 #endif #endif #define INSIDE_FD_64 #define _LARGEFILE64_SOURCE #define _FILE_OFFSET_BITS 64 #include "fd.h" #include "klee/Config/Version.h" #include "klee/klee.h" #include <assert.h> #include <errno.h> #include <fcntl.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #ifndef __FreeBSD__ #include <sys/vfs.h> #endif #include <dirent.h> #include <sys/ioctl.h> #include <sys/mtio.h> #include <sys/select.h> #include <termios.h> #include <unistd.h> /*** Forward to actual implementations ***/ int open(const char *pathname, int flags, ...) { mode_t mode = 0; if (flags & O_CREAT) { /* get mode */ va_list ap; va_start(ap, flags); mode = va_arg(ap, int); va_end(ap); } return __fd_open(pathname, flags, mode); } int openat(int fd, const char *pathname, int flags, ...) { mode_t mode = 0; if (flags & O_CREAT) { /* get mode */ va_list ap; va_start(ap, flags); mode = va_arg(ap, int); va_end(ap); } return __fd_openat(fd, pathname, flags, mode); } /* removed in glibc 2.33 */ #ifdef __REDIRECT_NTH extern int __REDIRECT_NTH(__fxstat, (int __ver, int __fildes, struct stat *__stat_buf), __fxstat64); extern int __REDIRECT_NTH(__xstat, (int __ver, const char *__filename, struct stat *__stat_buf), __xstat64); extern int __REDIRECT_NTH(__lxstat, (int __ver, const char *__filename, struct stat *__stat_buf), __lxstat64); #endif off64_t lseek(int fd, off64_t offset, int whence) { return __fd_lseek(fd, offset, whence); } int __xstat(int vers, const char *path, struct stat *buf) { return __fd_stat(path, (struct stat64*) buf); } int stat(const char *path, struct stat *buf) { return __fd_stat(path, (struct stat64*) buf); } int __lxstat(int vers, const char *path, struct stat *buf) { return __fd_lstat(path, (struct stat64*) buf); } int lstat(const char *path, struct stat *buf) { return __fd_lstat(path, (struct stat64*) buf); } int __fxstat(int vers, int fd, struct stat *buf) { return __fd_fstat(fd, (struct stat64*) buf); } int fstat(int fd, struct stat *buf) { return __fd_fstat(fd, (struct stat64*) buf); } int ftruncate64(int fd, off64_t length) { return __fd_ftruncate(fd, length); } int statfs(const char *path, struct statfs *buf) __attribute__((weak)); int statfs(const char *path, struct statfs *buf) { return __fd_statfs(path, buf); } ssize_t getdents64(int fd, void *dirp, size_t count) { return __fd_getdents(fd, (struct dirent64*) dirp, count); } ssize_t __getdents64(int fd, void *dirp, size_t count) __attribute__((alias("getdents64")));
ade8e4fd9170a309bf8639233ffa722c93cd494e
de21f9075f55640514c29ef0f1fe3f0690845764
/src/goto-instrument/wmm/wmm.h
9e1fd088e34a673654a229dc437d63c5018c1e7d
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-4-Clause" ]
permissive
diffblue/cbmc
975a074ac445febb3b5715f8792beb545522dc18
decd2839c2f51a54b2ad0f3e89fdc1b4bf78cd16
refs/heads/develop
2023-08-31T05:52:05.342195
2023-08-30T13:31:51
2023-08-30T13:31:51
51,877,056
589
309
NOASSERTION
2023-09-14T18:49:17
2016-02-16T23:03:52
C++
UTF-8
C
false
false
644
h
wmm.h
/*******************************************************************\ Module: memory models Author: Vincent Nimal Date: 2012 \*******************************************************************/ /// \file /// memory models #ifndef CPROVER_GOTO_INSTRUMENT_WMM_WMM_H #define CPROVER_GOTO_INSTRUMENT_WMM_WMM_H enum memory_modelt { Unknown=-1, TSO=0, PSO=1, RMO=2, Power=3 }; enum instrumentation_strategyt { all=0, min_interference=1, read_first=2, write_first=3, my_events=4, one_event_per_cycle=5 }; enum loop_strategyt { arrays_only=0, all_loops=1, no_loop=2 }; #endif // CPROVER_GOTO_INSTRUMENT_WMM_WMM_H
37f0d9cecd817e204b5e0e58836cd5787d330f0a
e90671c6b1cb69eaf57bd0ab4bbd1bd92ba9aea9
/android/vendored/sdk47/@shopify/react-native-skia/cpp/skia/include/private/SkHalf.h
d9518913109148f02f09effc02e0fff567d834f1
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
expo/expo
72fc802e3b6806789225bdd856031a8d150dd6f5
40f087fc0c0ab22270cfef2673bced44af170c34
refs/heads/main
2023-08-17T01:38:28.442098
2023-08-16T21:43:11
2023-08-16T21:43:11
65,750,241
23,742
5,421
MIT
2023-09-14T21:37:37
2016-08-15T17:14:25
TypeScript
UTF-8
C
false
false
3,224
h
SkHalf.h
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkHalf_DEFINED #define SkHalf_DEFINED #include "include/core/SkTypes.h" #include "include/private/SkNx.h" // 16-bit floating point value // format is 1 bit sign, 5 bits exponent, 10 bits mantissa // only used for storage typedef uint16_t SkHalf; static constexpr uint16_t SK_HalfMin = 0x0400; // 2^-14 (minimum positive normal value) static constexpr uint16_t SK_HalfMax = 0x7bff; // 65504 static constexpr uint16_t SK_HalfEpsilon = 0x1400; // 2^-10 static constexpr uint16_t SK_Half1 = 0x3C00; // 1 // convert between half and single precision floating point float SkHalfToFloat(SkHalf h); SkHalf SkFloatToHalf(float f); // Convert between half and single precision floating point, // assuming inputs and outputs are both finite, and may // flush values which would be denormal half floats to zero. static inline Sk4f SkHalfToFloat_finite_ftz(uint64_t); static inline Sk4h SkFloatToHalf_finite_ftz(const Sk4f&); // ~~~~~~~~~~~ impl ~~~~~~~~~~~~~~ // // Like the serial versions in SkHalf.cpp, these are based on // https://fgiesen.wordpress.com/2012/03/28/half-to-float-done-quic/ // GCC 4.9 lacks the intrinsics to use ARMv8 f16<->f32 instructions, so we use inline assembly. static inline Sk4f SkHalfToFloat_finite_ftz(uint64_t rgba) { Sk4h hs = Sk4h::Load(&rgba); #if !defined(SKNX_NO_SIMD) && defined(SK_CPU_ARM64) float32x4_t fs; asm ("fcvtl %[fs].4s, %[hs].4h \n" // vcvt_f32_f16(...) : [fs] "=w" (fs) // =w: write-only NEON register : [hs] "w" (hs.fVec)); // w: read-only NEON register return fs; #else Sk4i bits = SkNx_cast<int>(hs), // Expand to 32 bit. sign = bits & 0x00008000, // Save the sign bit for later... positive = bits ^ sign, // ...but strip it off for now. is_norm = 0x03ff < positive; // Exponent > 0? // For normal half floats, extend the mantissa by 13 zero bits, // then adjust the exponent from 15 bias to 127 bias. Sk4i norm = (positive << 13) + ((127 - 15) << 23); Sk4i merged = (sign << 16) | (norm & is_norm); return Sk4f::Load(&merged); #endif } static inline Sk4h SkFloatToHalf_finite_ftz(const Sk4f& fs) { #if !defined(SKNX_NO_SIMD) && defined(SK_CPU_ARM64) float32x4_t vec = fs.fVec; asm ("fcvtn %[vec].4h, %[vec].4s \n" // vcvt_f16_f32(vec) : [vec] "+w" (vec)); // +w: read-write NEON register return vreinterpret_u16_f32(vget_low_f32(vec)); #else Sk4i bits = Sk4i::Load(&fs), sign = bits & 0x80000000, // Save the sign bit for later... positive = bits ^ sign, // ...but strip it off for now. will_be_norm = 0x387fdfff < positive; // greater than largest denorm half? // For normal half floats, adjust the exponent from 127 bias to 15 bias, // then drop the bottom 13 mantissa bits. Sk4i norm = (positive - ((127 - 15) << 23)) >> 13; Sk4i merged = (sign >> 16) | (will_be_norm & norm); return SkNx_cast<uint16_t>(merged); #endif } #endif
dfecb8407657ae57dda9807bb24a8b1eb526292a
e1cddfd754d952134e72dfd03522c5ea4fb6008e
/src/vppinfra/pcap.c
bdaa861db3fe31d375ac773ab6153783ed668be8
[ "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
6,609
c
pcap.c
/* * Copyright (c) 2015 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. */ /* * pcap.c: libpcap packet capture format * * Copyright (c) 2008 Eliot Dresselhaus * * 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 <fcntl.h> #include <vppinfra/pcap.h> /** * @file * @brief PCAP function. * * Usage: * * <code><pre> * \#include <vppinfra/pcap.h> * * static pcap_main_t pcap = { * .file_name = "/tmp/ip4", * .n_packets_to_capture = 2, * .packet_type = PCAP_PACKET_TYPE_ip, * }; * </pre></code> * * To add a buffer: * * <code><pre>pcap_add_buffer (&pcap, vm, pi0, 128);</pre></code> * * File will be written after @c n_packets_to_capture or call to pcap_write (&amp;pcap). * */ /** * @brief Close PCAP file * * @return rc - clib_error_t * */ __clib_export clib_error_t * pcap_close (pcap_main_t * pm) { close (pm->file_descriptor); pm->flags &= ~PCAP_MAIN_INIT_DONE; pm->file_descriptor = -1; return 0; } /** * @brief Write PCAP file * * @return rc - clib_error_t * */ __clib_export clib_error_t * pcap_write (pcap_main_t * pm) { clib_error_t *error = 0; if (!(pm->flags & PCAP_MAIN_INIT_DONE)) { pcap_file_header_t fh; int n; if (!pm->file_name) pm->file_name = "/tmp/vnet.pcap"; pm->file_descriptor = open (pm->file_name, O_CREAT | O_TRUNC | O_WRONLY, 0664); if (pm->file_descriptor < 0) { error = clib_error_return_unix (0, "failed to open `%s'", pm->file_name); goto done; } pm->flags |= PCAP_MAIN_INIT_DONE; pm->n_packets_captured = 0; pm->n_pcap_data_written = 0; clib_spinlock_init (&pm->lock); /* Write file header. */ clib_memset (&fh, 0, sizeof (fh)); fh.magic = 0xa1b2c3d4; fh.major_version = 2; fh.minor_version = 4; fh.time_zone = 0; fh.max_packet_size_in_bytes = 1 << 16; fh.packet_type = pm->packet_type; n = write (pm->file_descriptor, &fh, sizeof (fh)); if (n != sizeof (fh)) { if (n < 0) error = clib_error_return_unix (0, "write file header `%s'", pm->file_name); else error = clib_error_return (0, "short write of file header `%s'", pm->file_name); goto done; } } while (vec_len (pm->pcap_data) > pm->n_pcap_data_written) { i64 n = vec_len (pm->pcap_data) - pm->n_pcap_data_written; n = write (pm->file_descriptor, vec_elt_at_index (pm->pcap_data, pm->n_pcap_data_written), n); if (n < 0 && unix_error_is_fatal (errno)) { error = clib_error_return_unix (0, "write `%s'", pm->file_name); goto done; } pm->n_pcap_data_written += n; } if (pm->n_pcap_data_written >= vec_len (pm->pcap_data)) { vec_reset_length (pm->pcap_data); pm->n_pcap_data_written = 0; } done: if (error) { if (pm->file_descriptor >= 0) close (pm->file_descriptor); } return error; } /** * @brief Read PCAP file * * @return rc - clib_error_t * */ __clib_export clib_error_t * pcap_read (pcap_main_t * pm) { clib_error_t *error = 0; int fd, need_swap, n; pcap_file_header_t fh; pcap_packet_header_t ph; fd = open (pm->file_name, O_RDONLY); if (fd < 0) { error = clib_error_return_unix (0, "open `%s'", pm->file_name); goto done; } if (read (fd, &fh, sizeof (fh)) != sizeof (fh)) { error = clib_error_return_unix (0, "read file header `%s'", pm->file_name); goto done; } need_swap = 0; if (fh.magic == 0xd4c3b2a1) { need_swap = 1; #define _(t,f) fh.f = clib_byte_swap_##t (fh.f); foreach_pcap_file_header; #undef _ } if (fh.magic != 0xa1b2c3d4) { error = clib_error_return (0, "bad magic `%s'", pm->file_name); goto done; } pm->min_packet_bytes = 0; pm->max_packet_bytes = 0; while ((n = read (fd, &ph, sizeof (ph))) != 0) { u8 *data; u64 timestamp; u32 timestamp_sec; u32 timestamp_usec; if (need_swap) { #define _(t,f) ph.f = clib_byte_swap_##t (ph.f); foreach_pcap_packet_header; #undef _ } data = vec_new (u8, ph.n_bytes_in_packet); if (read (fd, data, ph.n_packet_bytes_stored_in_file) != ph.n_packet_bytes_stored_in_file) { error = clib_error_return (0, "short read `%s'", pm->file_name); goto done; } if (vec_len (pm->packets_read) == 0) pm->min_packet_bytes = pm->max_packet_bytes = ph.n_bytes_in_packet; else { pm->min_packet_bytes = clib_min (pm->min_packet_bytes, ph.n_bytes_in_packet); pm->max_packet_bytes = clib_max (pm->max_packet_bytes, ph.n_bytes_in_packet); } timestamp_sec = ph.time_in_sec; timestamp_usec = ph.time_in_usec; timestamp = ((u64) timestamp_sec) * 1000000 + (u64) timestamp_usec; vec_add1 (pm->packets_read, data); vec_add1 (pm->timestamps, timestamp); } done: if (fd >= 0) close (fd); return error; } /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */
dc1e0c1db18794a0d9f830147e670e4109653589
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/sun2/include/frame.h
64f1523413257b219a36c01f3c41fa9d80934950
[]
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
89
h
frame.h
/* $NetBSD: frame.h,v 1.1 2001/04/06 13:13:03 fredette Exp $ */ #include <m68k/frame.h>
facaa88f13aa6b842e3c49a4fe2f42912972676c
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/third_party/libsecret/libsecret/secret-types.h
708c53f82a856f83ca659d955b1d4b6bc4d6aa86
[ "LGPL-2.1-only", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "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
1,112
h
secret-types.h
/* libsecret - GLib wrapper for Secret Service * * Copyright 2011 Collabora Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the licence or (at * your option) any later version. * * See the included COPYING file for more information. * * Author: Stef Walter <stefw@gnome.org> */ #if !defined (__SECRET_INSIDE_HEADER__) && !defined (SECRET_COMPILATION) #error "Only <libsecret/secret.h> can be included directly." #endif #ifndef __SECRET_TYPES_H__ #define __SECRET_TYPES_H__ #include <glib.h> G_BEGIN_DECLS #define SECRET_ERROR (secret_error_get_quark ()) GQuark secret_error_get_quark (void) G_GNUC_CONST; typedef enum { SECRET_ERROR_PROTOCOL = 1, SECRET_ERROR_IS_LOCKED = 2, SECRET_ERROR_NO_SUCH_OBJECT = 3, SECRET_ERROR_ALREADY_EXISTS = 4, } SecretError; #define SECRET_COLLECTION_DEFAULT "default" #define SECRET_COLLECTION_SESSION "session" G_END_DECLS #endif /* __G_SERVICE_H___ */
8b63f6b21dc59a93b55ddf3210b9cefc78390025
1efd2de8bf77ec00eb2fcaf5749278495946d920
/src/vos/vos_ts.c
9e47d1000978db5f04ef6113308e8b33901413b8
[ "BSD-2-Clause", "BSD-2-Clause-Patent" ]
permissive
daos-stack/daos
6f55bf3061fd830d5b8d28506e1295e2d3a27c38
ed5eed5df43a68571afe123132a743824c02637a
refs/heads/master
2023-08-31T21:43:37.606145
2023-08-31T16:38:00
2023-08-31T16:38:00
69,390,670
631
300
NOASSERTION
2023-09-14T18:55:15
2016-09-27T19:21:29
C
UTF-8
C
false
false
10,394
c
vos_ts.c
/** * (C) Copyright 2020-2023 Intel Corporation. * * SPDX-License-Identifier: BSD-2-Clause-Patent */ /** * Record timestamp table * vos/vos_ts.c * * Author: Jeff Olivier <jeffrey.v.olivier@intel.com> */ #define D_LOGFAC DD_FAC(vos) #include "vos_internal.h" #define DEFINE_TS_STR(type, desc, count) desc, /** Strings corresponding to timestamp types */ static const char * const type_strs[] = { D_FOREACH_TS_TYPE(DEFINE_TS_STR) }; #define DEFINE_TS_COUNT(type, desc, count) count, static const uint32_t type_counts[] = { D_FOREACH_TS_TYPE(DEFINE_TS_COUNT) }; #define OBJ_MISS_SIZE (1 << 16) #define DKEY_MISS_SIZE (1 << 16) #define AKEY_MISS_SIZE (1 << 16) #define TS_TRACE(action, entry, idx, type) \ D_DEBUG(DB_TRACE, "%s %s at idx %d(%p), read.hi="DF_U64 \ " read.lo="DF_U64"\n", action, type_strs[type], idx, \ (entry)->te_record_ptr, (entry)->te_ts.tp_ts_rh, \ (entry)->te_ts.tp_ts_rl) /** The entry is being evicted either because there is no space in the cache or * the item it represents has been removed. In either case, update the * corresponding negative entry. */ static bool ts_update_on_evict(struct vos_ts_table *ts_table, struct vos_ts_entry *entry) { struct vos_wts_cache *wcache; struct vos_wts_cache *dest; if (entry->te_record_ptr == NULL) return false; wcache = &entry->te_w_cache; if (entry->te_negative == NULL) { /* No negative entry. This is likely the container level, so * just update the global entries */ dest = &ts_table->tt_w_cache; if (entry->te_ts.tp_ts_rl > ts_table->tt_ts_rl) { vos_ts_copy(&ts_table->tt_ts_rl, &ts_table->tt_tx_rl, entry->te_ts.tp_ts_rl, &entry->te_ts.tp_tx_rl); } if (entry->te_ts.tp_ts_rh > ts_table->tt_ts_rh) { vos_ts_copy(&ts_table->tt_ts_rh, &ts_table->tt_tx_rh, entry->te_ts.tp_ts_rh, &entry->te_ts.tp_tx_rh); } goto update_w_cache; } dest = &entry->te_negative->te_w_cache; vos_ts_rl_update(entry->te_negative, entry->te_ts.tp_ts_rl, &entry->te_ts.tp_tx_rl); vos_ts_rh_update(entry->te_negative, entry->te_ts.tp_ts_rh, &entry->te_ts.tp_tx_rh); update_w_cache: vos_ts_update_wcache(dest, wcache->wc_ts_w[0]); vos_ts_update_wcache(dest, wcache->wc_ts_w[1]); return true; } static void evict_entry(void *payload, uint32_t idx, void *arg) { struct vos_ts_info *info = arg; struct vos_ts_entry *entry = payload; if (ts_update_on_evict(info->ti_table, entry)) { TS_TRACE("Evicted", entry, idx, info->ti_type); entry->te_record_ptr = NULL; } } static void init_entry(void *payload, uint32_t idx, void *arg) { struct vos_ts_info *info = arg; struct vos_ts_entry *entry = payload; entry->te_info = info; } static const struct lru_callbacks lru_cbs = { .lru_on_evict = evict_entry, .lru_on_init = init_entry, }; int vos_ts_table_alloc(struct vos_ts_table **ts_tablep) { struct vos_ts_entry *entry; struct vos_ts_table *ts_table; struct vos_ts_info *info; struct vos_ts_entry *miss_cursor; int rc; uint32_t i; int j; uint32_t miss_size; *ts_tablep = NULL; D_ALLOC_PTR(ts_table); if (ts_table == NULL) return -DER_NOMEM; D_ALLOC_ARRAY(ts_table->tt_misses, OBJ_MISS_SIZE + DKEY_MISS_SIZE + AKEY_MISS_SIZE); if (ts_table->tt_misses == NULL) { rc = -DER_NOMEM; goto free_table; } ts_table->tt_ts_rl = vos_start_epoch; ts_table->tt_ts_rh = vos_start_epoch; uuid_clear(ts_table->tt_tx_rl.dti_uuid); uuid_clear(ts_table->tt_tx_rh.dti_uuid); miss_cursor = ts_table->tt_misses; for (i = 0; i < VOS_TS_TYPE_COUNT; i++) { info = &ts_table->tt_type_info[i]; info->ti_type = i; info->ti_count = type_counts[i]; info->ti_table = ts_table; switch (i) { case VOS_TS_TYPE_OBJ: miss_size = OBJ_MISS_SIZE; break; case VOS_TS_TYPE_DKEY: miss_size = DKEY_MISS_SIZE; break; case VOS_TS_TYPE_AKEY: miss_size = AKEY_MISS_SIZE; break; case VOS_TS_TYPE_CONT: default: miss_size = 0; break; } if (miss_size) { info->ti_cache_mask = miss_size - 1; info->ti_misses = miss_cursor; miss_cursor += miss_size; /* Negative entries are global. Each object/key chain * will hash to an index. There will be some false * sharing but it should be fairly minimal. Start each * negative entry with global settings. */ for (j = 0; j < miss_size; j++) { entry = &info->ti_misses[j]; entry->te_info = info; vos_ts_copy(&entry->te_ts.tp_ts_rl, &entry->te_ts.tp_tx_rl, ts_table->tt_ts_rl, &ts_table->tt_tx_rl); vos_ts_copy(&entry->te_ts.tp_ts_rh, &entry->te_ts.tp_tx_rh, ts_table->tt_ts_rh, &ts_table->tt_tx_rh); } } rc = lrua_array_alloc(&info->ti_array, info->ti_count, 1, sizeof(struct vos_ts_entry), 0, &lru_cbs, info); if (rc != 0) goto cleanup; } *ts_tablep = ts_table; return 0; cleanup: for (i = 0; i < VOS_TS_TYPE_COUNT; i++) lrua_array_free(ts_table->tt_type_info[i].ti_array); D_FREE(ts_table->tt_misses); free_table: D_FREE(ts_table); return rc; } void vos_ts_table_free(struct vos_ts_table **ts_tablep) { struct vos_ts_table *ts_table = *ts_tablep; int i; for (i = 0; i < VOS_TS_TYPE_COUNT; i++) lrua_array_free(ts_table->tt_type_info[i].ti_array); D_FREE(ts_table->tt_misses); D_FREE(ts_table); *ts_tablep = NULL; } void vos_ts_evict_lru(struct vos_ts_table *ts_table, struct vos_ts_entry **entryp, uint32_t *idx, uint32_t hash_idx, uint32_t type) { struct vos_ts_entry *entry; struct vos_ts_entry *neg_entry = NULL; struct vos_ts_info *info = &ts_table->tt_type_info[type]; int rc; rc = lrua_alloc(ts_table->tt_type_info[type].ti_array, idx, &entry); D_ASSERT(rc == 0); /** autoeviction and no allocation */ if (info->ti_cache_mask) neg_entry = &info->ti_misses[hash_idx]; entry->te_negative = neg_entry; if (neg_entry == NULL) { /** Use global timestamps for the type to initialize it */ vos_ts_copy(&entry->te_ts.tp_ts_rl, &entry->te_ts.tp_tx_rl, ts_table->tt_ts_rl, &ts_table->tt_tx_rl); vos_ts_copy(&entry->te_ts.tp_ts_rh, &entry->te_ts.tp_tx_rh, ts_table->tt_ts_rh, &ts_table->tt_tx_rh); entry->te_w_cache = ts_table->tt_w_cache; } else { vos_ts_copy(&entry->te_ts.tp_ts_rh, &entry->te_ts.tp_tx_rh, neg_entry->te_ts.tp_ts_rh, &neg_entry->te_ts.tp_tx_rh); vos_ts_copy(&entry->te_ts.tp_ts_rl, &entry->te_ts.tp_tx_rl, neg_entry->te_ts.tp_ts_rl, &neg_entry->te_ts.tp_tx_rl); entry->te_w_cache = neg_entry->te_w_cache; } /** Set the lower bounds for the entry */ entry->te_record_ptr = idx; TS_TRACE("Allocated", entry, *idx, type); D_ASSERT(type == info->ti_type); *entryp = entry; } int vos_ts_set_allocate(struct vos_ts_set **ts_set, uint64_t flags, uint16_t cflags, uint32_t akey_nr, const struct dtx_handle *dth, bool standalone) { const struct dtx_id *tx_id = NULL; uint32_t size; uint64_t array_size; uint64_t cond_mask = VOS_COND_FETCH_MASK | VOS_COND_UPDATE_MASK | VOS_OF_COND_PER_AKEY; vos_kh_clear(standalone); *ts_set = NULL; if (!dtx_is_valid_handle(dth)) { if ((flags & cond_mask) == 0) return 0; } else { tx_id = &dth->dth_xid; } size = VOS_TS_TYPE_AKEY + akey_nr; array_size = size * sizeof((*ts_set)->ts_entries[0]); D_ALLOC(*ts_set, sizeof(**ts_set) + array_size); if (*ts_set == NULL) return -DER_NOMEM; (*ts_set)->ts_flags = flags; (*ts_set)->ts_set_size = size; if (tx_id != NULL) { (*ts_set)->ts_in_tx = true; uuid_copy((*ts_set)->ts_tx_id.dti_uuid, tx_id->dti_uuid); (*ts_set)->ts_tx_id.dti_hlc = tx_id->dti_hlc; } /* ts_in_tx is false by default */ vos_ts_set_append_cflags(*ts_set, cflags); return 0; } void vos_ts_set_upgrade(struct vos_ts_set *ts_set) { struct vos_ts_set_entry *set_entry; struct vos_ts_entry *entry; struct vos_ts_table *ts_table; struct vos_ts_info *info; uint32_t hash_idx; int i; if (!vos_ts_in_tx(ts_set)) return; ts_table = vos_ts_table_get(false); for (i = 0; i < ts_set->ts_init_count; i++) { set_entry = &ts_set->ts_entries[i]; entry = set_entry->se_entry; info = entry->te_info; D_ASSERT(entry != NULL); if (entry->te_negative != NULL || info->ti_misses == NULL) continue; D_ASSERT(i != 0); /** no negative lookup on container */ D_ASSERT(set_entry->se_create_idx != NULL); hash_idx = entry - info->ti_misses; vos_ts_evict_lru(ts_table, &entry, set_entry->se_create_idx, hash_idx, info->ti_type); set_entry->se_entry = entry; } } static inline bool vos_ts_check_conflict(daos_epoch_t read_time, const struct dtx_id *read_id, daos_epoch_t write_time, const struct dtx_id *write_id) { if (write_time > read_time) return false; if (write_time != read_time) return true; if (read_id->dti_hlc != write_id->dti_hlc) return true; return uuid_compare(read_id->dti_uuid, write_id->dti_uuid) != 0; } bool vos_ts_check_read_conflict(struct vos_ts_set *ts_set, int idx, daos_epoch_t write_time) { struct vos_ts_set_entry *se; struct vos_ts_entry *entry; int write_level; bool conflict; D_ASSERT(ts_set != NULL); se = &ts_set->ts_entries[idx]; entry = se->se_entry; if (ts_set->ts_wr_level > ts_set->ts_max_type) write_level = ts_set->ts_max_type; else write_level = ts_set->ts_wr_level; if (se->se_etype > write_level) return false; /** Check is redundant */ /** NB: If there is a negative entry, we should also check it. Otherwise, we can miss * timestamp updates associated with conditional operations where the tree exists but * we don't load it */ if (se->se_etype < write_level) { /* check the low time */ conflict = vos_ts_check_conflict(entry->te_ts.tp_ts_rl, &entry->te_ts.tp_tx_rl, write_time, &ts_set->ts_tx_id); if (conflict || entry->te_negative == NULL) return conflict; return vos_ts_check_conflict(entry->te_negative->te_ts.tp_ts_rl, &entry->te_negative->te_ts.tp_tx_rl, write_time, &ts_set->ts_tx_id); } /* check the high time */ conflict = vos_ts_check_conflict(entry->te_ts.tp_ts_rh, &entry->te_ts.tp_tx_rh, write_time, &ts_set->ts_tx_id); if (conflict || entry->te_negative == NULL) return conflict; return vos_ts_check_conflict(entry->te_negative->te_ts.tp_ts_rh, &entry->te_negative->te_ts.tp_tx_rh, write_time, &ts_set->ts_tx_id); }
7c747d25792e6c3ec204d11d7e4f54f59a2e4ecc
fbe68d84e97262d6d26dd65c704a7b50af2b3943
/third_party/virtualbox/src/VBox/Additions/x11/x11include/xorg-server-1.1.0/Pcl.h
bb1f52b2c5ea24a226922eae9dee6474e8213bc3
[ "MIT", "GPL-2.0-only", "LicenseRef-scancode-unknown-license-reference", "CDDL-1.0", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "LGPL-2.1-or-later", "GPL-2.0-or-later", "MPL-1.0", "LicenseRef-scancode-generic-exception", "Apache-2.0", "OpenSSL" ]
permissive
thalium/icebox
c4e6573f2b4f0973b6c7bb0bf068fe9e795fdcfb
6f78952d58da52ea4f0e55b2ab297f28e80c1160
refs/heads/master
2022-08-14T00:19:36.984579
2022-02-22T13:10:31
2022-02-22T13:10:31
190,019,914
585
109
MIT
2022-01-13T20:58:15
2019-06-03T14:18:12
C++
UTF-8
C
false
false
14,890
h
Pcl.h
/* $Xorg: Pcl.h,v 1.3 2000/08/17 19:48:07 cpqbld Exp $ */ /******************************************************************* ** ** ********************************************************* ** * ** * File: Pcl.h ** * ** * Contents: defines and includes for the Pcl driver ** * for a printing X server. ** * ** * Created: 1/30/95 ** * ** ********************************************************* ** ********************************************************************/ /* (c) Copyright 1996 Hewlett-Packard Company (c) Copyright 1996 International Business Machines Corp. (c) Copyright 1996 Sun Microsystems, Inc. (c) Copyright 1996 Novell, Inc. (c) Copyright 1996 Digital Equipment Corp. (c) Copyright 1996 Fujitsu Limited (c) Copyright 1996 Hitachi, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the names of the copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from said copyright holders. */ /* $XFree86: xc/programs/Xserver/Xprint/pcl/Pcl.h,v 1.12 2001/12/21 21:02:05 dawes Exp $ */ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> #endif #ifndef _PCL_H_ #define _PCL_H_ #include <stdio.h> #include "scrnintstr.h" #include "PclDef.h" #include "Pclmap.h" #include "PclSFonts.h" #include <X11/extensions/Print.h> #include <X11/extensions/Printstr.h> #include "regionstr.h" #include <X11/fonts/fontstruct.h> #include "dixfontstr.h" #include "gcstruct.h" /* * Some sleazes to force the XrmDB stuff into the server */ #ifndef HAVE_XPointer typedef char *XPointer; #endif #define Status int #define True 1 #define False 0 #include "misc.h" #include <X11/Xfuncproto.h> #include <X11/Xresource.h> #include "attributes.h" /****** * externally visible variables from PclInit.c ******/ extern int PclScreenPrivateIndex, PclWindowPrivateIndex; extern int PclContextPrivateIndex; extern int PclPixmapPrivateIndex; extern int PclGCPrivateIndex; /****** * externally visible variables from PclAttVal.c ******/ extern XpValidatePoolsRec PclValidatePoolsRec; /* * This structure defines a mapping from an X colormap ID to a list of * print contexts which use the colormap. */ typedef struct _pclcontextlist { XpContextPtr context; struct _pclcontextlist *next; } PclContextList, *PclContextListPtr; typedef struct _pclcmaptocontexts { long colormapId; PclContextListPtr contexts; struct _pclcmaptocontexts *next; } PclCmapToContexts; typedef struct { PclCmapToContexts *colormaps; CloseScreenProcPtr CloseScreen; } PclScreenPrivRec, *PclScreenPrivPtr; /* * This structure defines a mapping from an X colormap ID to a PCL * palette ID. */ typedef struct _palettemap { long colormapId; int paletteId; int downloaded; struct _palettemap *next; } PclPaletteMap, *PclPaletteMapPtr; typedef struct { char *jobFileName; FILE *pJobFile; char *pageFileName; FILE *pPageFile; GC lastGC; unsigned char *dash; int validGC; ClientPtr getDocClient; int getDocBufSize; PclSoftFontInfoPtr pSoftFontInfo; PclPaletteMapPtr palettes; int currentPalette; int nextPaletteId; PclPaletteMap staticGrayPalette; PclPaletteMap trueColorPalette; PclPaletteMap specialTrueColorPalette; unsigned char *ctbl; int ctbldim; int isRaw; #ifdef XP_PCL_LJ3 unsigned int fcount; unsigned int fcount_max; char *figures; #endif /* XP_PCL_LJ3 */ } PclContextPrivRec, *PclContextPrivPtr; typedef struct { int validContext; XpContextPtr context; } PclWindowPrivRec, *PclWindowPrivPtr; typedef struct { unsigned long stippleFg, stippleBg; } PclGCPrivRec, *PclGCPrivPtr; typedef struct { XpContextPtr context; char *tempFileName; FILE *tempFile; GC lastGC; int validGC; } PclPixmapPrivRec, *PclPixmapPrivPtr; /****** * Defined functions ******/ #define SEND_PCL(f,c) fwrite( c, sizeof( char ), strlen( c ), f ) #define SEND_PCL_COUNT(f,c,n) fwrite( c, sizeof( char ), n, f ) #ifndef XP_PCL_LJ3 #define SAVE_PCL(f,p,c) SEND_PCL(f,c) #define SAVE_PCL_COUNT(f,p,c,n) SEND_PCL_COUNT(f,c,n) #define MACRO_START(f,p) SEND_PCL(f, "\033&f1Y\033&f0X") #define MACRO_END(f) SEND_PCL(f, "\033&f1X") #else #define SAVE_PCL(f,p,c) PclSpoolFigs(p, c, strlen(c)) #define SAVE_PCL_COUNT(f,p,c,n) PclSpoolFigs(p, c, n) #define MACRO_START(f,p) p->fcount = 0 #define MACRO_END(f) /* do nothing */ #endif /* XP_PCL_LJ3 */ #define MIN(a,b) (((a)<(b))?(a):(b)) #ifndef MAX #define MAX(a,b) (((a)>(b))?(a):(b)) #endif /****** * Functions in PclArc.c ******/ extern void PclPolyArc( DrawablePtr pDrawable, GCPtr pGC, int nArcs, xArc *pArcs); extern void PclPolyFillArc( DrawablePtr pDrawable, GCPtr pGC, int nArcs, xArc *pArcs); /****** * Functions in PclArea.c ******/ extern void PclPutImage( DrawablePtr pDrawable, GCPtr pGC, int depth, int x, int y, int w, int h, int leftPad, int format, char *pImage); extern RegionPtr PclCopyArea( DrawablePtr pSrc, DrawablePtr pDst, GCPtr pGC, int srcx, int srcy, int width, int height, int dstx, int dsty); RegionPtr PclCopyPlane( DrawablePtr pSrc, DrawablePtr pDst, GCPtr pGC, int srcx, int srcy, int width, int height, int dstx, int dsty, unsigned long plane); /****** * Functions in PclAttr.c ******/ extern char *PclGetAttributes( XpContextPtr pCon, XPAttributes pool ); extern char *PclGetOneAttribute( XpContextPtr pCon, XPAttributes pool, char *attr ); extern int PclAugmentAttributes( XpContextPtr pCon, XPAttributes pool, char *attrs ); extern int PclSetAttributes( XpContextPtr pCon, XPAttributes pool, char *attrs ); /****** * Functions in PclColor.c ******/ extern Bool PclCreateDefColormap(ScreenPtr pScreen); extern Bool PclCreateColormap(ColormapPtr pColor); extern void PclDestroyColormap(ColormapPtr pColor); extern void PclInstallColormap(ColormapPtr pColor); extern void PclUninstallColormap(ColormapPtr pColor); extern int PclListInstalledColormaps(ScreenPtr pScreen, XID *pCmapList); extern void PclStoreColors(ColormapPtr pColor, int ndef, xColorItem *pdefs); extern void PclResolveColor(unsigned short *pRed, unsigned short *pGreen, unsigned short *pBlue, VisualPtr pVisual); extern int PclUpdateColormap(DrawablePtr pDrawable, XpContextPtr pCon, GCPtr gc, FILE *outFile); extern void PclLookUp(ColormapPtr cmap, PclContextPrivPtr cPriv, unsigned short *r, unsigned short *g, unsigned short *b); extern PclPaletteMapPtr PclFindPaletteMap(PclContextPrivPtr cPriv, ColormapPtr cmap, GCPtr gc); extern unsigned char *PclReadMap(char *, int *); /****** * Functions in PclCursor.c ******/ extern void PclConstrainCursor( ScreenPtr pScreen, BoxPtr pBox); extern void PclCursorLimits( ScreenPtr pScreen, CursorPtr pCursor, BoxPtr pHotBox, BoxPtr pTopLeftbox); extern Bool PclDisplayCursor( ScreenPtr pScreen, CursorPtr pCursor); extern Bool PclRealizeCursor( ScreenPtr pScreen, CursorPtr pCursor); extern Bool PclUnrealizeCursor( ScreenPtr pScreen, CursorPtr pCursor); extern void PclRecolorCursor( ScreenPtr pScreen, CursorPtr pCursor, Bool displayed); extern Bool PclSetCursorPosition( ScreenPtr pScreen, int x, int y, Bool generateEvent); /****** * Functions in PclSFonts.c ******/ extern void PclDownloadSoftFont8( FILE *fp, PclSoftFontInfoPtr pSoftFontInfo, PclFontHead8Ptr pfh, PclCharDataPtr pcd, unsigned char *code); extern void PclDownloadSoftFont16( FILE *fp, PclSoftFontInfoPtr pSoftFontInfo, PclFontHead16Ptr pfh, PclCharDataPtr pcd, unsigned char row, unsigned char col); extern PclSoftFontInfoPtr PclCreateSoftFontInfo(void); extern void PclDestroySoftFontInfo( PclSoftFontInfoPtr pSoftFontInfo ); /****** * Functions in PclGC.c ******/ extern Bool PclCreateGC(GCPtr pGC); extern void PclDestroyGC(GCPtr pGC); extern int PclUpdateDrawableGC( GCPtr pGC, DrawablePtr pDrawable, FILE **outFile); extern void PclValidateGC( GCPtr pGC, unsigned long changes, DrawablePtr pDrawable); extern void PclSetDrawablePrivateStuff( DrawablePtr pDrawable, GC gc ); extern int PclGetDrawablePrivateStuff( DrawablePtr pDrawable, GC *gc, unsigned long *valid, FILE **file ); extern void PclSetDrawablePrivateGC( DrawablePtr pDrawable, GC gc); extern void PclComputeCompositeClip( GCPtr pGC, DrawablePtr pDrawable); /****** * Functions in PclInit.c ******/ extern Bool PclCloseScreen( int index, ScreenPtr pScreen); extern Bool InitializeColorPclDriver( int ndx, ScreenPtr pScreen, int argc, char **argv); extern Bool InitializeMonoPclDriver( int ndx, ScreenPtr pScreen, int argc, char **argv); extern Bool InitializeLj3PclDriver( int ndx, ScreenPtr pScreen, int argc, char **argv); extern XpContextPtr PclGetContextFromWindow( WindowPtr win ); /****** * Functions in PclLine.c ******/ extern void PclPolyLine( DrawablePtr pDrawable, GCPtr pGC, int mode, int nPoints, xPoint *pPoints); extern void PclPolySegment( DrawablePtr pDrawable, GCPtr pGC, int nSegments, xSegment *pSegments); /****** * Functions in PclMisc.c ******/ extern void PclQueryBestSize( int class, short *pwidth, short *pheight, ScreenPtr pScreen); extern char *GetPropString(WindowPtr pWin, char *propName); extern int SystemCmd(char *cmdStr); extern int PclGetMediumDimensions( XpContextPtr pCon, CARD16 *pWidth, CARD16 *pHeight); extern int PclGetReproducibleArea( XpContextPtr pCon, xRectangle *pRect); extern void PclSendData( FILE *outFile, PclContextPrivPtr pConPriv, BoxPtr pbox, int nbox, double ratio); /****** * Functions in PclPixel.c ******/ extern void PclPolyPoint( DrawablePtr pDrawable, GCPtr pGC, int mode, int nPoints, xPoint *pPoints); extern void PclPushPixels( GCPtr pGC, PixmapPtr pBitmap, DrawablePtr pDrawable, int width, int height, int x, int y); /****** * Functions in PclPixmap.c ******/ extern PixmapPtr PclCreatePixmap( ScreenPtr pScreen, int width, int height, int depth); extern Bool PclDestroyPixmap(PixmapPtr pPixmap); /****** * Functions in PclPolygon.c ******/ extern void PclPolyRectangle( DrawablePtr pDrawable, GCPtr pGC, int nRects, xRectangle *pRects); extern void PclFillPolygon( DrawablePtr pDrawable, GCPtr pGC, int shape, int mode, int nPoints, DDXPointPtr pPoints); extern void PclPolyFillRect( DrawablePtr pDrawable, GCPtr pGC, int nRects, xRectangle *pRects); /****** * Functions in PclSpans.c ******/ extern void PclFillSpans( DrawablePtr pDrawable, GCPtr pGC, int nSpans, DDXPointPtr pPoints, int *pWidths, int fSorted); extern void PclSetSpans( DrawablePtr pDrawable, GCPtr pGC, char *pSrc, DDXPointPtr pPoints, int *pWidths, int nSpans, int fSorted); /****** * Functions in PclText.c ******/ extern int PclPolyText8( DrawablePtr pDrawable, GCPtr pGC, int x, int y, int count, char *string); extern int PclPolyText16( DrawablePtr pDrawable, GCPtr pGC, int x, int y, int count, unsigned short *string); extern void PclImageText8( DrawablePtr pDrawable, GCPtr pGC, int x, int y, int count, char *string); extern void PclImageText16( DrawablePtr pDrawable, GCPtr pGC, int x, int y, int count, unsigned short *string); extern void PclImageGlyphBlt( DrawablePtr pDrawable, GCPtr pGC, int x, int y, unsigned int nGlyphs, CharInfoPtr *pCharInfo, pointer pGlyphBase); extern void PclPolyGlyphBlt( DrawablePtr pDrawable, GCPtr pGC, int x, int y, unsigned int nGlyphs, CharInfoPtr *pCharInfo, pointer pGlyphBase); /****** * Functions in PclWindow.c ******/ extern Bool PclCreateWindow(register WindowPtr pWin); extern Bool PclDestroyWindow(WindowPtr pWin); extern Bool PclMapWindow(WindowPtr pWindow); extern Bool PclPositionWindow( register WindowPtr pWin, int x, int y); extern Bool PclUnmapWindow(WindowPtr pWindow); extern void PclCopyWindow( WindowPtr pWin, DDXPointRec ptOldOrg, RegionPtr prgnSrc); extern Bool PclChangeWindowAttributes( register WindowPtr pWin, register unsigned long mask); extern void PclPaintWindow( WindowPtr pWin, RegionPtr pRegion, int what); /****** * Functions in PclFonts.c ******/ extern Bool PclRealizeFont( ScreenPtr pscr, FontPtr pFont); extern Bool PclUnrealizeFont( ScreenPtr pscr, FontPtr pFont); /****** * Functions in PclPrint.c ******/ extern int PclStartJob( XpContextPtr pCon, Bool sendClientData, ClientPtr client); extern int PclEndJob( XpContextPtr pCon, Bool cancel); extern int PclStartPage( XpContextPtr pCon, WindowPtr pWin); extern int PclEndPage( XpContextPtr pCon, WindowPtr pWin); extern int PclStartDoc(XpContextPtr pCon, XPDocumentType type); extern int PclEndDoc( XpContextPtr pCon, Bool cancel); extern int PclDocumentData( XpContextPtr pCon, DrawablePtr pDraw, char *pData, int len_data, char *pFmt, int len_fmt, char *pOpt, int len_opt, ClientPtr client); extern int PclGetDocumentData( XpContextPtr pCon, ClientPtr client, int maxBufferSize); #endif /* _PCL_H_ */
d83e7f339e69199363f7a63f1034f746654cd5c8
4692f28f86ee84a76abfac8cc8a0dd41fcd402e4
/pkg/security/ebpf/c/include/constants/offsets/netns.h
e3eaac0e2f744d3c84b9823c69d6b3d8339e53e8
[ "GPL-2.0-only", "CC0-1.0", "BSD-3-Clause", "Apache-2.0", "GPL-1.0-or-later", "MIT", "0BSD", "Unlicense", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "BSD-2-Clause-Views", "MPL-2.0" ]
permissive
DataDog/datadog-agent
cc4b89839d6031903bf23aa12eccc2a3f3c7f213
d960cdb7de8fa5d1c7138cfe58e754af80cb796a
refs/heads/main
2023-09-04T10:45:08.138748
2023-09-04T09:13:43
2023-09-04T09:13:43
49,970,739
2,388
1,288
Apache-2.0
2023-09-14T20:06:34
2016-01-19T17:40:41
Go
UTF-8
C
false
false
2,203
h
netns.h
#ifndef _CONSTANTS_OFFSETS_NETNS_H_ #define _CONSTANTS_OFFSETS_NETNS_H_ #include "constants/macros.h" __attribute__((always_inline)) u32 get_ifindex_from_net_device(struct net_device *device) { u64 net_device_ifindex_offset; LOAD_CONSTANT("net_device_ifindex_offset", net_device_ifindex_offset); u32 ifindex; bpf_probe_read(&ifindex, sizeof(ifindex), (void*)device + net_device_ifindex_offset); return ifindex; } #define NET_STRUCT_HAS_PROC_INUM 0 #define NET_STRUCT_HAS_NS 1 __attribute__((always_inline)) u32 get_netns_from_net(struct net *net) { u64 net_struct_type; LOAD_CONSTANT("net_struct_type", net_struct_type); u64 net_proc_inum_offset; LOAD_CONSTANT("net_proc_inum_offset", net_proc_inum_offset); u64 net_ns_offset; LOAD_CONSTANT("net_ns_offset", net_ns_offset); if (net_struct_type == NET_STRUCT_HAS_PROC_INUM) { u32 inum = 0; bpf_probe_read(&inum, sizeof(inum), (void*)net + net_proc_inum_offset); return inum; } #ifndef DO_NOT_USE_TC struct ns_common ns; bpf_probe_read(&ns, sizeof(ns), (void*)net + net_ns_offset); return ns.inum; #else return 0; #endif } __attribute__((always_inline)) u32 get_netns_from_sock(struct sock *sk) { u64 sock_common_skc_net_offset; LOAD_CONSTANT("sock_common_skc_net_offset", sock_common_skc_net_offset); struct sock_common *common = (void *)sk; struct net *net = NULL; bpf_probe_read(&net, sizeof(net), (void *)common + sock_common_skc_net_offset); return get_netns_from_net(net); } __attribute__((always_inline)) u32 get_netns_from_socket(struct socket *socket) { u64 socket_sock_offset; LOAD_CONSTANT("socket_sock_offset", socket_sock_offset); struct sock *sk = NULL; bpf_probe_read(&sk, sizeof(sk), (void *)socket + socket_sock_offset); return get_netns_from_sock(sk); } __attribute__((always_inline)) u32 get_netns_from_nf_conn(struct nf_conn *ct) { u64 nf_conn_ct_net_offset; LOAD_CONSTANT("nf_conn_ct_net_offset", nf_conn_ct_net_offset); struct net *net = NULL; bpf_probe_read(&net, sizeof(net), (void *)ct + nf_conn_ct_net_offset); return get_netns_from_net(net); } #endif
071c16e0fe1f93bf846ec1bc6add0d1ebb7fca69
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/tkm32F499/Libraries/Hal_lib/inc/HAL_adc.h
b93cb48d89e9b82ef2639103032e862b425298d3
[ "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
13,921
h
HAL_adc.h
/** ****************************************************************************** * @file HAL_adc.h * @author IC Applications Department * @version V0.8 * @date 2019_08_02 * @brief This file contains all the functions prototypes for the ADC firmware * library. ****************************************************************************** * @copy * * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE * TIME. AS A RESULT, HOLOCENE SHALL NOT BE HELD LIABLE FOR ANY * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. * * <h2><center>&copy; COPYRIGHT 2016 HOLOCENE</center></h2> */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __HAL_ADC_H #define __HAL_ADC_H /* Includes ------------------------------------------------------------------*/ #include "HAL_device.h" /** @addtogroup StdPeriph_Driver * @{ */ /** @addtogroup ADC * @{ */ /** @defgroup ADC_Exported_Types * @{ */ /** * @brief ADC Init structure definition */ /* typedef struct { uint32_t ADC_Mode; FunctionalState ADC_ScanConvMode; FunctionalState ADC_ContinuousConvMode; uint32_t ADC_ExternalTrigConv; uint32_t ADC_DataAlign; uint8_t ADC_NbrOfChannel; }ADC_InitTypeDef; */ typedef struct { uint32_t ADC_Resolution; uint32_t ADC_PRESCARE; uint32_t ADC_Mode; FunctionalState ADC_ContinuousConvMode; uint32_t ADC_TRGEN; uint32_t ADC_ExternalTrigConv; uint32_t ADC_DataAlign; }ADC_InitTypeDef; /** * @} */ /** @defgroup ADC_Exported_Constants * @{ */ #define IS_ADC_ALL_PERIPH(PERIPH) (((*(uint32_t*)&(PERIPH)) == ADC1_BASE) || \ ((*(uint32_t*)&(PERIPH)) == ADC2_BASE)) #define IS_ADC_DMA_PERIPH(PERIPH) (((*(uint32_t*)&(PERIPH)) == ADC1_BASE) || \ ((*(uint32_t*)&(PERIPH)) == ADC2_BASE)) /** @defgroup ADC_Resolution * @{ */ #define ADC_Resolution_12b ((uint32_t)0x00000000) #define ADC_Resolution_11b ((uint32_t)0x00000080) #define ADC_Resolution_10b ((uint32_t)0x00000100) #define ADC_Resolution_9b ((uint32_t)0x00000180) #define ADC_Resolution_8b ((uint32_t)0x00000200) #define IS_ADC_RESOLUTION(RESOLUTION) (((RESOLUTION) == ADC_Resolution_12b) || \ ((RESOLUTION) == ADC_Resolution_10b) || \ ((RESOLUTION) == ADC_Resolution_8b) || \ ((RESOLUTION) == ADC_Resolution_6b)) /** * @brief for ADC1, ADC2 */ #define ADC_PCLK2_PRESCARE_2 ((uint32_t)0x00000000) #define ADC_PCLK2_PRESCARE_4 ((uint32_t)0x00000010) #define ADC_PCLK2_PRESCARE_6 ((uint32_t)0x00000020) #define ADC_PCLK2_PRESCARE_8 ((uint32_t)0x00000030) #define ADC_PCLK2_PRESCARE_10 ((uint32_t)0x00000040) #define ADC_PCLK2_PRESCARE_12 ((uint32_t)0x00000050) #define ADC_PCLK2_PRESCARE_14 ((uint32_t)0x00000060) #define ADC_PCLK2_PRESCARE_16 ((uint32_t)0x00000070) /** @defgroup ADC_dual_mode * @{ */ #define ADC_Mode_Single ((uint32_t)0x00000000) #define ADC_Mode_Single_Period ((uint32_t)0x00000200) #define ADC_Mode_Continuous_Scan ((uint32_t)0x00000400) #define IS_ADC_MODE(MODE) (((MODE) == ADC_Mode_Single) || \ ((MODE) == ADC_Mode_Single_Period) || \ ((MODE) == ADC_Mode_Continuous_Scan)) /** * @} */ #define ADC_TRG_Disable ((uint32_t)0xfffffffB) #define ADC_TRG_Enable ((uint32_t)0x00000004) /** @defgroup ADC_extrenal_trigger_sources_for_regular_channels_conversion * @{ */ /** * @brief for ADC1 */ #define ADC_ExternalTrigConv_T1_CC1 ((uint32_t)0x00000000) #define ADC_ExternalTrigConv_T1_CC2 ((uint32_t)0x00000010) #define ADC_ExternalTrigConv_T1_CC3 ((uint32_t)0x00000020) #define ADC_ExternalTrigConv_T2_CC2 ((uint32_t)0x00000030) #define ADC_ExternalTrigConv_T3_TRGO ((uint32_t)0x00000040) #define ADC_ExternalTrigConv_T4_CC4 ((uint32_t)0x00000050) #define ADC_ExternalTrigConv_T3_CC1 ((uint32_t)0x00000060) #define ADC_ExternalTrigConv_EXTI_11 ((uint32_t)0x00000070) /** * @brief for ADC2 */ #define ADC_ExternalTrigConv_T1_TRGO ((uint32_t)0x00000000) #define ADC_ExternalTrigConv_T1_CC4 ((uint32_t)0x00000010) #define ADC_ExternalTrigConv_T2_TRGO ((uint32_t)0x00000020) #define ADC_ExternalTrigConv_T2_CC1 ((uint32_t)0x00000030) #define ADC_ExternalTrigConv_T3_CC4 ((uint32_t)0x00000040) #define ADC_ExternalTrigConv_T4_TRGO ((uint32_t)0x00000050) #define ADC_ExternalTrigConv_T3_CC1 ((uint32_t)0x00000060) #define ADC_ExternalTrigConv_EXTI_15 ((uint32_t)0x00000070) #define IS_ADC_EXT_TRIG(REGTRIG) (((REGTRIG) == ADC_ExternalTrigConv_T1_CC1) || \ ((REGTRIG) == ADC_ExternalTrigConv_T1_CC2) || \ ((REGTRIG) == ADC_ExternalTrigConv_T1_CC3) || \ ((REGTRIG) == ADC_ExternalTrigConv_T2_CC2) || \ ((REGTRIG) == ADC_ExternalTrigConv_T3_TRGO) || \ ((REGTRIG) == ADC_ExternalTrigConv_T4_CC4) || \ ((REGTRIG) == ADC_ExternalTrigConv_T3_CC1) || \ ((REGTRIG) == ADC_ExternalTrigConv_EXTI_11) || \ ((REGTRIG) == ADC_ExternalTrigConv_T1_TRGO) || \ ((REGTRIG) == ADC_ExternalTrigConv_T1_CC4) || \ ((REGTRIG) == ADC_ExternalTrigConv_T2_TRGO) || \ ((REGTRIG) == ADC_ExternalTrigConv_T2_CC1) || \ ((REGTRIG) == ADC_ExternalTrigConv_T3_CC4) || \ ((REGTRIG) == ADC_ExternalTrigConv_T4_TRGO) || \ ((REGTRIG) == ADC_ExternalTrigConv_T3_CC1) || \ ((REGTRIG) == ADC_ExternalTrigConv_EXTI_15)) /** * @} */ /** @defgroup ADC_data_align * @{ */ #define ADC_DataAlign_Right ((uint32_t)0x00000000) #define ADC_DataAlign_Left ((uint32_t)0x00000800) #define IS_ADC_DATA_ALIGN(ALIGN) (((ALIGN) == ADC_DataAlign_Right) || \ ((ALIGN) == ADC_DataAlign_Left)) /** * @} */ /** @defgroup ADC_channels * @{ */ #define ADC_Channel_0 ((uint8_t)0x00) #define ADC_Channel_1 ((uint8_t)0x01) #define ADC_Channel_2 ((uint8_t)0x02) #define ADC_Channel_3 ((uint8_t)0x03) #define ADC_Channel_4 ((uint8_t)0x04) #define ADC_Channel_5 ((uint8_t)0x05) #define ADC_Channel_6 ((uint8_t)0x06) #define ADC_Channel_7 ((uint8_t)0x07) #define ADC_Channel_8 ((uint8_t)0x08) #define ADC_Channel_All ((uint8_t)0x0f) #define IS_ADC_CHANNEL(CHANNEL) (((CHANNEL) == ADC_Channel_0) || ((CHANNEL) == ADC_Channel_1) || \ ((CHANNEL) == ADC_Channel_2) || ((CHANNEL) == ADC_Channel_3) || \ ((CHANNEL) == ADC_Channel_4) || ((CHANNEL) == ADC_Channel_5) || \ ((CHANNEL) == ADC_Channel_6) || ((CHANNEL) == ADC_Channel_7) || \ ((CHANNEL) == ADC_Channel_8) || ((CHANNEL) == ADC_Channel_All)) /** * @} */ /** * @} */ #define ADC_SMPR_SMP ((uint32_t)0x00000007) /*!< SMP[2:0] bits (Sampling time selection) */ #define ADC_SMPR_SMP_0 ((uint32_t)0x00000001) /*!< Bit 0 */ #define ADC_SMPR_SMP_1 ((uint32_t)0x00000002) /*!< Bit 1 */ #define ADC_SMPR_SMP_2 ((uint32_t)0x00000004) /*!< Bit 2 */ /** @defgroup ADC_sampling_times * @{ */ #define ADC_SampleTime_1_5Cycles ((uint32_t)0x00000000) #define ADC_SampleTime_7_5Cycles ((uint32_t)0x00000001) #define ADC_SampleTime_13_5Cycles ((uint32_t)0x00000002) #define ADC_SampleTime_28_5Cycles ((uint32_t)0x00000003) #define ADC_SampleTime_41_5Cycles ((uint32_t)0x00000004) #define ADC_SampleTime_55_5Cycles ((uint32_t)0x00000005) #define ADC_SampleTime_71_5Cycles ((uint32_t)0x00000006) #define ADC_SampleTime_239_5Cycles ((uint32_t)0x00000007) #define IS_ADC_SAMPLE_TIME(TIME) (((TIME) == ADC_SampleTime_1_5Cycles) || \ ((TIME) == ADC_SampleTime_7_5Cycles) || \ ((TIME) == ADC_SampleTime_13_5Cycles) || \ ((TIME) == ADC_SampleTime_28_5Cycles) || \ ((TIME) == ADC_SampleTime_41_5Cycles) || \ ((TIME) == ADC_SampleTime_55_5Cycles) || \ ((TIME) == ADC_SampleTime_71_5Cycles) || \ ((TIME) == ADC_SampleTime_239_5Cycles)) /** @defgroup ADC_injected_channel_selection * @{ */ #define ADC_InjectedChannel_0 ((uint8_t)0x18) #define ADC_InjectedChannel_1 ((uint8_t)0x1C) #define ADC_InjectedChannel_2 ((uint8_t)0x20) #define ADC_InjectedChannel_3 ((uint8_t)0x24) #define ADC_InjectedChannel_4 ((uint8_t)0x28) #define ADC_InjectedChannel_5 ((uint8_t)0x2C) #define ADC_InjectedChannel_6 ((uint8_t)0x30) #define ADC_InjectedChannel_7 ((uint8_t)0x34) #define ADC_InjectedChannel_8 ((uint8_t)0x38) #define IS_ADC_INJECTED_CHANNEL(CHANNEL) (((CHANNEL) == ADC_InjectedChannel_1) || \ ((CHANNEL) == ADC_InjectedChannel_2) || \ ((CHANNEL) == ADC_InjectedChannel_3) || \ ((CHANNEL) == ADC_InjectedChannel_4) || \ ((CHANNEL) == ADC_InjectedChannel_5) || \ ((CHANNEL) == ADC_InjectedChannel_6) || \ ((CHANNEL) == ADC_InjectedChannel_7) || \ ((CHANNEL) == ADC_InjectedChannel_8)) /** * @} */ /** @defgroup ADC_analog_watchdog_selection * @{ */ #define ADC_AnalogWatchdog_SingleRegEnable ((uint32_t)0x00000002) #define ADC_AnalogWatchdog_None ((uint32_t)0x00000000) #define IS_ADC_ANALOG_WATCHDOG(WATCHDOG) (((WATCHDOG) == ADC_AnalogWatchdog_SingleRegEnable) || \ ((WATCHDOG) == ADC_AnalogWatchdog_None)) /** * @} */ /** @defgroup ADC_interrupts_definition * @{ */ #define ADC_IT_EOC ((uint16_t)0x0001) #define ADC_IT_AWD ((uint16_t)0x0002) #define IS_ADC_IT(IT) ((((IT) & (uint16_t)0xFFFC) == 0x00) && ((IT) != 0x00)) #define IS_ADC_GET_IT(IT) (((IT) == ADC_IT_EOC) || ((IT) == ADC_IT_AWD)) /** * @} */ /** @defgroup ADC_flags_definition * @{ */ #define ADC_FLAG_AWD ((uint8_t)0x02) //ADWIF 比较标志位 #define ADC_FLAG_EOC ((uint8_t)0x01) //ADIF 转换结束标志位 #define IS_ADC_CLEAR_FLAG(FLAG) ((((FLAG) & (uint8_t)0xF0) == 0x00) && ((FLAG) != 0x00)) #define IS_ADC_GET_FLAG(FLAG) (((FLAG) == ADC_FLAG_AWD) || ((FLAG) == ADC_FLAG_EOC)) /** * @} */ /** @defgroup ADC_thresholds * @{ */ #define IS_ADC_THRESHOLD(THRESHOLD) ((THRESHOLD) <= 0xFFF) /** * @} */ /** @defgroup ADC_injected_offset * @{ */ #define IS_ADC_OFFSET(OFFSET) ((OFFSET) <= 0xFFF) /** * @} */ /** @defgroup ADC_injected_length * @{ */ #define IS_ADC_INJECTED_LENGTH(LENGTH) (((LENGTH) >= 0x1) && ((LENGTH) <= 0x4)) /** * @} */ /** @defgroup ADC_injected_rank * @{ */ #define IS_ADC_INJECTED_RANK(RANK) (((RANK) >= 0x1) && ((RANK) <= 0x4)) /** * @} */ /** @defgroup ADC_regular_length * @{ */ #define IS_ADC_REGULAR_LENGTH(LENGTH) (((LENGTH) >= 0x1) && ((LENGTH) <= 0x10)) /** * @} */ /** @defgroup ADC_regular_rank * @{ */ #define IS_ADC_REGULAR_RANK(RANK) (((RANK) >= 0x1) && ((RANK) <= 0x10)) /** * @} */ /** @defgroup ADC_regular_discontinuous_mode_number * @{ */ #define IS_ADC_REGULAR_DISC_NUMBER(NUMBER) (((NUMBER) >= 0x1) && ((NUMBER) <= 0x8)) /** * @} */ /** * @} */ /** @defgroup ADC_Exported_Macros * @{ */ /** * @} */ /** @defgroup ADC_Exported_Functions * @{ */ void ADC_DeInit(ADC_TypeDef* ADCx); void ADC_Init(ADC_TypeDef* ADCx, ADC_InitTypeDef* ADC_InitStruct); void ADC_StructInit(ADC_InitTypeDef* ADC_InitStruct); void ADC_Cmd(ADC_TypeDef* ADCx, FunctionalState NewState); void ADC_DMACmd(ADC_TypeDef* ADCx, FunctionalState NewState); void ADC_ITConfig(ADC_TypeDef* ADCx, uint16_t ADC_IT, FunctionalState NewState); void ADC_SoftwareStartConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState); FlagStatus ADC_GetSoftwareStartConvStatus(ADC_TypeDef* ADCx); void ADC_RegularChannelConfig(ADC_TypeDef* ADCx, uint8_t ADC_Channel, uint8_t Rank, uint8_t ADC_SampleTime); void ADC_ExternalTrigConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState); uint16_t ADC_GetConversionValue(ADC_TypeDef* ADCx); void ADC_ExternalTrigInjectedConvConfig(ADC_TypeDef* ADCx, uint32_t ADC_ExternalTrigInjecConv); void ADC_ExternalTrigInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState); void ADC_SoftwareStartInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState); void ADC_AnalogWatchdogCmd(ADC_TypeDef* ADCx, uint32_t ADC_AnalogWatchdog); void ADC_AnalogWatchdogThresholdsConfig(ADC_TypeDef* ADCx, uint16_t HighThreshold, uint16_t LowThreshold); void ADC_AnalogWatchdogSingleChannelConfig(ADC_TypeDef* ADCx, uint8_t ADC_Channel); void ADC_TempSensorVrefintCmd(FunctionalState NewState); FlagStatus ADC_GetFlagStatus(ADC_TypeDef* ADCx, uint8_t ADC_FLAG); void ADC_ClearFlag(ADC_TypeDef* ADCx, uint8_t ADC_FLAG); ITStatus ADC_GetITStatus(ADC_TypeDef* ADCx, uint16_t ADC_IT); void ADC_ClearITPendingBit(ADC_TypeDef* ADCx, uint16_t ADC_IT); #endif /*__HAL_ADC_H */ /** * @} */ /** * @} */ /** * @} */ /*-------------------------(C) COPYRIGHT 2016 HOLOCENE ----------------------*/
7830dbc009778313864fa7adb067663c0fcdbde3
86dc6d2dd56d5962cb8a35afae05ca3447d70185
/src/www/shaders/extrudeShader.c
3f3dcb5353d3db4c3c39caa9967d8112a8c538fb
[ "MIT", "CC-BY-3.0" ]
permissive
gavanw/vqisosmall
229eb629c9ea3b5ebdeb0db4532f8d2360b1e0dc
0e1dcd52999c7a797b5087ae5e04e25b41e619a3
refs/heads/master
2020-04-02T06:50:24.035821
2016-08-16T22:24:46
2016-08-16T22:24:46
64,972,688
325
57
null
2016-08-16T22:24:47
2016-08-04T23:03:15
JavaScript
UTF-8
C
false
false
621
c
extrudeShader.c
uniform sampler2D u_Texture0; uniform sampler2D u_Texture1; uniform sampler2D u_Texture2; uniform sampler2D u_Texture3; uniform float u_Time; uniform float u_Zoom; uniform vec2 u_Resolution; varying vec2 v_TexCoords; varying vec3 v_Position; $ $ void main() { vec2 a_TexCoords = uv.xy; v_TexCoords = uv.xy; v_Position = position.xyz; gl_Position = vec4( position.xyz, 1.0 ); } $ void main() { vec4 baseval = texture2D( u_Texture0, v_TexCoords ); vec2 newCoords = v_TexCoords; newCoords.y -= baseval.b*255.0/u_Resolution.y; vec4 idval = texture2D( u_Texture1, newCoords ); gl_FragColor = idval; }
3b2dd9329be3f3b505840bd991c53355e81629e6
0744dcc5394cebf57ebcba343747af6871b67017
/os/arch/xtensa/include/esp32/sens_struct.h
8e8ae25f94f89adb1aab2cb30a3866423c8a0f5f
[ "GPL-1.0-or-later", "BSD-3-Clause", "ISC", "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", "Apache-2.0" ]
permissive
Samsung/TizenRT
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
refs/heads/master
2023-08-31T08:59:33.327998
2023-08-08T06:09:20
2023-08-31T04:38:20
82,517,252
590
719
Apache-2.0
2023-09-14T06:54:49
2017-02-20T04:38:30
C
UTF-8
C
false
false
9,309
h
sens_struct.h
/****************************************************************** * * Copyright 2019 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************/ // Copyright 2015-2016 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. #ifndef _SOC_SENS_STRUCT_H_ #define _SOC_SENS_STRUCT_H_ #ifdef __cplusplus extern "C" { #endif typedef volatile struct { union { struct { uint32_t sar1_clk_div :8; uint32_t sar1_sample_cycle :8; uint32_t sar1_sample_bit :2; uint32_t sar1_clk_gated :1; uint32_t sar1_sample_num :8; uint32_t sar1_dig_force :1; /*1 : ADC1 is controlled by the digital controller 0 : RTC controller */ uint32_t sar1_data_inv :1; uint32_t reserved29 :3; }; uint32_t val; } sar_read_ctrl; uint32_t sar_read_status1; union { struct { uint32_t sar_amp_wait1 :16; uint32_t sar_amp_wait2 :16; }; uint32_t val; } sar_meas_wait1; union { struct { uint32_t sar_amp_wait3 :16; uint32_t force_xpd_amp :2; uint32_t force_xpd_sar :2; uint32_t sar2_rstb_wait :8; uint32_t reserved28 :4; }; uint32_t val; } sar_meas_wait2; union { struct { uint32_t xpd_sar_amp_fsm :4; uint32_t amp_rst_fb_fsm :4; uint32_t amp_short_ref_fsm :4; uint32_t amp_short_ref_gnd_fsm :4; uint32_t xpd_sar_fsm :4; uint32_t sar_rstb_fsm :4; uint32_t sar2_xpd_wait :8; }; uint32_t val; } sar_meas_ctrl; uint32_t sar_read_status2; uint32_t ulp_cp_sleep_cyc0; uint32_t ulp_cp_sleep_cyc1; uint32_t ulp_cp_sleep_cyc2; uint32_t ulp_cp_sleep_cyc3; uint32_t ulp_cp_sleep_cyc4; union { struct { uint32_t sar1_bit_width :2; uint32_t sar2_bit_width :2; uint32_t sar2_en_test :1; uint32_t sar2_pwdet_cct :3; uint32_t ulp_cp_force_start_top :1; uint32_t ulp_cp_start_top :1; uint32_t sarclk_en :1; uint32_t pc_init :11; uint32_t sar2_stop :1; uint32_t sar1_stop :1; uint32_t sar2_pwdet_en :1; uint32_t reserved25 :7; }; uint32_t val; } sar_start_force; union { struct { uint32_t mem_wr_addr_init :11; uint32_t mem_wr_addr_size :11; uint32_t rtc_mem_wr_offst_clr :1; uint32_t reserved23 :9; }; uint32_t val; } sar_mem_wr_ctrl; uint32_t sar_atten1; uint32_t sar_atten2; union { struct { uint32_t i2c_slave_addr1 :11; uint32_t i2c_slave_addr0 :11; uint32_t meas_status :8; uint32_t reserved30 :2; }; uint32_t val; } sar_slave_addr1; union { struct { uint32_t i2c_slave_addr3 :11; uint32_t i2c_slave_addr2 :11; uint32_t reserved22 :10; }; uint32_t val; } sar_slave_addr2; union { struct { uint32_t i2c_slave_addr5 :11; uint32_t i2c_slave_addr4 :11; uint32_t tsens_out :8; uint32_t tsens_rdy_out :1; uint32_t reserved31 :1; }; uint32_t val; } sar_slave_addr3; union { struct { uint32_t i2c_slave_addr7 :11; uint32_t i2c_slave_addr6 :11; uint32_t i2c_rdata :8; uint32_t i2c_done :1; uint32_t reserved31 :1; }; uint32_t val; } sar_slave_addr4; union { struct { uint32_t tsens_xpd_wait :12; uint32_t tsens_xpd_force :1; uint32_t tsens_clk_inv :1; uint32_t tsens_clk_gated :1; uint32_t tsens_in_inv :1; uint32_t tsens_clk_div :8; uint32_t tsens_power_up :1; uint32_t tsens_power_up_force :1; uint32_t tsens_dump_out :1; uint32_t reserved27 :5; }; uint32_t val; } sar_tctrl; union { struct { uint32_t sar_i2c_ctrl :28; uint32_t sar_i2c_start :1; uint32_t sar_i2c_start_force :1; uint32_t reserved30 :2; }; uint32_t val; } sar_i2c_ctrl; union { struct { uint32_t meas1_data_sar :16; uint32_t meas1_done_sar :1; uint32_t meas1_start_sar :1; uint32_t meas1_start_force :1; /*1 : ADC1 is controlled by the digital or RTC controller 0 : Ulp coprocessor */ uint32_t sar1_en_pad :12; uint32_t sar1_en_pad_force :1; /*1 : Data ports are controlled by the digital or RTC controller 0 : Ulp coprocessor */ }; uint32_t val; } sar_meas_start1; union { struct { uint32_t touch_meas_delay :16; uint32_t touch_xpd_wait :8; uint32_t touch_out_sel :1; uint32_t touch_out_1en :1; uint32_t xpd_hall_force :1; /*1 : Power of hall sensor is controlled by the digital or RTC controller 0 : Ulp coprocessor */ uint32_t hall_phase_force :1; /*1 : Phase of hall sensor is controlled by the digital or RTC controller 0 : Ulp coprocessor */ uint32_t reserved28 :4; }; uint32_t val; } sar_touch_ctrl1; union { struct { uint32_t l_thresh :16; uint32_t h_thresh :16; }; uint32_t val; } touch_thresh[5]; union { struct { uint32_t l_val :16; uint32_t h_val :16; }; uint32_t val; } touch_meas[5]; union { struct { uint32_t touch_meas_en :10; uint32_t touch_meas_done :1; uint32_t touch_start_fsm_en :1; uint32_t touch_start_en :1; uint32_t touch_start_force :1; uint32_t touch_sleep_cycles :16; uint32_t touch_meas_en_clr :1; uint32_t reserved31 :1; }; uint32_t val; } sar_touch_ctrl2; uint32_t reserved_88; union { struct { uint32_t touch_pad_worken :10; uint32_t touch_pad_outen2 :10; uint32_t touch_pad_outen1 :10; uint32_t reserved30 :2; }; uint32_t val; } sar_touch_enable; union { struct { uint32_t sar2_clk_div :8; uint32_t sar2_sample_cycle :8; uint32_t sar2_sample_bit :2; uint32_t sar2_clk_gated :1; uint32_t sar2_sample_num :8; uint32_t sar2_pwdet_force :1; /*1 : ADC2 is controlled by PWDET 0 : digital or RTC controller */ uint32_t sar2_dig_force :1; /*1 : ADC2 is controlled by the digital controller 0 : RTC controller */ uint32_t sar2_data_inv :1; uint32_t reserved30 :2; }; uint32_t val; } sar_read_ctrl2; union { struct { uint32_t meas2_data_sar :16; uint32_t meas2_done_sar :1; uint32_t meas2_start_sar :1; uint32_t meas2_start_force :1; /*1 : ADC2 is controlled by the digital or RTC controller 0 : Ulp coprocessor */ uint32_t sar2_en_pad :12; uint32_t sar2_en_pad_force :1; /*1 : Data ports are controlled by the digital or RTC controller 0 : Ulp coprocessor */ }; uint32_t val; } sar_meas_start2; union { struct { uint32_t sw_fstep :16; uint32_t sw_tone_en :1; uint32_t debug_bit_sel :5; uint32_t dac_dig_force :1; uint32_t dac_clk_force_low :1; uint32_t dac_clk_force_high :1; uint32_t dac_clk_inv :1; uint32_t reserved26 :6; }; uint32_t val; } sar_dac_ctrl1; union { struct { uint32_t dac_dc1 :8; uint32_t dac_dc2 :8; uint32_t dac_scale1 :2; uint32_t dac_scale2 :2; uint32_t dac_inv1 :2; uint32_t dac_inv2 :2; uint32_t dac_cw_en1 :1; uint32_t dac_cw_en2 :1; uint32_t reserved26 :6; }; uint32_t val; } sar_dac_ctrl2; union { struct { uint32_t sar1_dac_xpd_fsm :4; uint32_t sar1_dac_xpd_fsm_idle :1; uint32_t xpd_sar_amp_fsm_idle :1; uint32_t amp_rst_fb_fsm_idle :1; uint32_t amp_short_ref_fsm_idle :1; uint32_t amp_short_ref_gnd_fsm_idle :1; uint32_t xpd_sar_fsm_idle :1; uint32_t sar_rstb_fsm_idle :1; uint32_t sar2_rstb_force :2; uint32_t amp_rst_fb_force :2; uint32_t amp_short_ref_force :2; uint32_t amp_short_ref_gnd_force :2; uint32_t reserved19 :13; }; uint32_t val; } sar_meas_ctrl2; uint32_t reserved_a4; uint32_t reserved_a8; uint32_t reserved_ac; uint32_t reserved_b0; uint32_t reserved_b4; uint32_t reserved_b8; uint32_t reserved_bc; uint32_t reserved_c0; uint32_t reserved_c4; uint32_t reserved_c8; uint32_t reserved_cc; uint32_t reserved_d0; uint32_t reserved_d4; uint32_t reserved_d8; uint32_t reserved_dc; uint32_t reserved_e0; uint32_t reserved_e4; uint32_t reserved_e8; uint32_t reserved_ec; uint32_t reserved_f0; uint32_t reserved_f4; uint32_t sar_nouse; union { struct { uint32_t sar_date :28; uint32_t reserved28 :4; }; uint32_t val; } sardate; } sens_dev_t; extern sens_dev_t SENS; #ifdef __cplusplus } #endif #endif /* _SOC_SENS_STRUCT_H_ */
62890b440621765468ccb1b193669fa828ffbd15
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/editors/ted/files/patch-textEncoding-sioIconv.c
aeeea7be218fc24b50253ebfab1094fe76405a11
[ "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
365
c
patch-textEncoding-sioIconv.c
--- textEncoding/sioIconv.c.orig 2013-02-01 12:11:08 UTC +++ textEncoding/sioIconv.c @@ -61,11 +61,7 @@ static int sioInIconvReadBytes( void * /* 1 */ while( ! tooBig ) { -# if defined(__GNUC__) && ! defined(iconv) char * inbuf= (char *)iis->iisInBuf; -# else - const char * inbuf= (const char *)iis->iisInBuf; -# endif int got; /* 2 */
6869a321d9bf88744edf89c2662b3bae6235ca9a
d0889089b86bc407b154879cb294e703f9303989
/Lumos/External/OpenAL/Alc/fpu_modes.h
750252fc4c78d79cec5779b15e82bbe1942e30ac
[ "MIT", "LicenseRef-scancode-public-domain", "LGPL-2.0-or-later", "LGPL-2.0-only" ]
permissive
jmorton06/Lumos
9ab96420c619d9baac07e4561d0a7e83645d54c8
e5f0ebfa9049d3515caaad056fda082a1e9d74ae
refs/heads/main
2023-09-01T02:48:00.496623
2023-07-06T07:31:44
2023-07-06T07:31:44
164,933,352
1,052
126
MIT
2023-09-06T08:08:18
2019-01-09T20:32:10
C++
UTF-8
C
false
false
854
h
fpu_modes.h
#ifndef FPU_MODES_H #define FPU_MODES_H #ifdef HAVE_FENV_H #include <fenv.h> #endif typedef struct FPUCtl { #ifdef HAVE_FENV_H fenv_t flt_env; #ifdef _WIN32 int round_mode; #endif #else int state; #endif #ifdef HAVE_SSE int sse_state; #endif } FPUCtl; void SetMixerFPUMode(FPUCtl *ctl); void RestoreFPUMode(const FPUCtl *ctl); #ifdef __GNUC__ /* Use an alternate macro set with GCC to avoid accidental continue or break * statements within the mixer mode. */ #define START_MIXER_MODE() __extension__({ FPUCtl _oldMode; SetMixerFPUMode(&_oldMode) #define END_MIXER_MODE() RestoreFPUMode(&_oldMode); }) #else #define START_MIXER_MODE() do { FPUCtl _oldMode; SetMixerFPUMode(&_oldMode) #define END_MIXER_MODE() RestoreFPUMode(&_oldMode); } while(0) #endif #define LEAVE_MIXER_MODE() RestoreFPUMode(&_oldMode) #endif /* FPU_MODES_H */
30a73afd0b8fbf2b404a68913c4c418349606997
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/weston/src/tests/input-timestamps-helper.c
05cafec44e820f73f0a6ae40826a2ff5898fa866
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LGPL-2.0-or-later", "GPL-1.0-or-later", "BSD-3-Clause" ]
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
4,940
c
input-timestamps-helper.c
/* * Copyright © 2017 Collabora, Ltd. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "config.h" #include <assert.h> #include <stdio.h> #include <string.h> #include <time.h> #include "input-timestamps-helper.h" #include "input-timestamps-unstable-v1-client-protocol.h" #include "shared/timespec-util.h" #include <libweston/zalloc.h> #include "weston-test-client-helper.h" struct input_timestamps { struct zwp_input_timestamps_v1 *proxy; }; static struct zwp_input_timestamps_manager_v1 * get_input_timestamps_manager(struct client *client) { struct global *g; struct global *global_ts = NULL; struct zwp_input_timestamps_manager_v1 *ts = NULL; wl_list_for_each(g, &client->global_list, link) { if (strcmp(g->interface, zwp_input_timestamps_manager_v1_interface.name)) continue; if (global_ts) assert(!"Multiple input timestamp managers"); global_ts = g; } assert(global_ts); assert(global_ts->version == 1); ts = wl_registry_bind(client->wl_registry, global_ts->name, &zwp_input_timestamps_manager_v1_interface, 1); assert(ts); return ts; } static void input_timestamp(void *data, struct zwp_input_timestamps_v1 *zwp_input_timestamps_v1, uint32_t tv_sec_hi, uint32_t tv_sec_lo, uint32_t tv_nsec) { struct timespec *timestamp = data; timespec_from_proto(timestamp, tv_sec_hi, tv_sec_lo, tv_nsec); testlog("test-client: got input timestamp %ld.%ld\n", timestamp->tv_sec, timestamp->tv_nsec); } static const struct zwp_input_timestamps_v1_listener input_timestamps_listener = { .timestamp = input_timestamp, }; struct input_timestamps * input_timestamps_create_for_keyboard(struct client *client) { struct zwp_input_timestamps_manager_v1 *manager = get_input_timestamps_manager(client); struct timespec *timestamp= &client->input->keyboard->input_timestamp; struct input_timestamps *input_ts; input_ts = zalloc(sizeof *input_ts); assert(input_ts); input_ts->proxy = zwp_input_timestamps_manager_v1_get_keyboard_timestamps( manager, client->input->keyboard->wl_keyboard); assert(input_ts->proxy); zwp_input_timestamps_v1_add_listener(input_ts->proxy, &input_timestamps_listener, timestamp); zwp_input_timestamps_manager_v1_destroy(manager); client_roundtrip(client); return input_ts; } struct input_timestamps * input_timestamps_create_for_pointer(struct client *client) { struct zwp_input_timestamps_manager_v1 *manager = get_input_timestamps_manager(client); struct timespec *timestamp= &client->input->pointer->input_timestamp; struct input_timestamps *input_ts; input_ts = zalloc(sizeof *input_ts); assert(input_ts); input_ts->proxy = zwp_input_timestamps_manager_v1_get_pointer_timestamps( manager, client->input->pointer->wl_pointer); assert(input_ts->proxy); zwp_input_timestamps_v1_add_listener(input_ts->proxy, &input_timestamps_listener, timestamp); zwp_input_timestamps_manager_v1_destroy(manager); client_roundtrip(client); return input_ts; } struct input_timestamps * input_timestamps_create_for_touch(struct client *client) { struct zwp_input_timestamps_manager_v1 *manager = get_input_timestamps_manager(client); struct timespec *timestamp= &client->input->touch->input_timestamp; struct input_timestamps *input_ts; input_ts = zalloc(sizeof *input_ts); assert(input_ts); input_ts->proxy = zwp_input_timestamps_manager_v1_get_touch_timestamps( manager, client->input->touch->wl_touch); assert(input_ts->proxy); zwp_input_timestamps_v1_add_listener(input_ts->proxy, &input_timestamps_listener, timestamp); zwp_input_timestamps_manager_v1_destroy(manager); client_roundtrip(client); return input_ts; } void input_timestamps_destroy(struct input_timestamps *input_ts) { zwp_input_timestamps_v1_destroy(input_ts->proxy); free(input_ts); }
d23ce8a5e375f0896a16291c88c1ce0de8b94513
1e21bfcd7a1a01e609be8ff4ecf959d3e7b048cb
/src/severity.c
174011446610f8b480c9f69f1a33a34dde45ea8a
[ "Apache-2.0" ]
permissive
goatshriek/stumpless
f3720221824fad9e4b185d6304d82c1530e5317b
111796d0afbb75645058a5afe5313cf1a59ba44d
refs/heads/latest
2023-08-18T05:08:33.694065
2023-08-09T01:08:27
2023-08-09T01:08:27
20,359,440
428
394
Apache-2.0
2023-09-04T02:22:31
2014-05-31T16:06:34
C
UTF-8
C
false
false
1,644
c
severity.c
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2018-2022 Joel E. Anderson * * 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 <stddef.h> #include <string.h> #include <stumpless/severity.h> #include "private/severity.h" #include "private/strhelper.h" static char *severity_enum_to_string[] = { STUMPLESS_FOREACH_SEVERITY( GENERATE_STRING ) }; const char * stumpless_get_severity_string( enum stumpless_severity severity ) { if ( !severity_is_invalid( severity ) ) { return severity_enum_to_string[severity]; } return "NO_SUCH_SEVERITY"; } enum stumpless_severity stumpless_get_severity_enum( const char *severity_string ) { size_t severity_bound; size_t i; severity_bound = sizeof( severity_enum_to_string ) / sizeof( severity_enum_to_string[0] ); for( i = 0; i < severity_bound; i++ ) { if( strcmp( severity_string, severity_enum_to_string[i] ) == 0 ) { return i; } } return -1; } /* private functions */ int get_severity( int prival ) { return prival & 0x7; } int severity_is_invalid( int severity ) { return severity < 0 || severity > 7; }
d20576c7f16f0c4bad86dc5888fa584a04093545
5f86fc385c7dcfcb5b166cdea7c8b13057b8bb5f
/host/optee/linux/enclave.c
a537fc2765f23646c123d201fb324610497833ef
[ "MIT" ]
permissive
openenclave/openenclave
54a38e12d9aa73357d9f438a07cd8c07ffe5e6df
cdeb95c1ec163117de409295333b6b2702013e08
refs/heads/master
2023-08-14T16:43:32.049533
2023-07-21T15:58:54
2023-07-21T15:58:54
101,804,230
800
372
MIT
2023-09-12T20:26:02
2017-08-29T20:31:38
C
UTF-8
C
false
false
16,368
c
enclave.c
// Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. #include <openenclave/bits/defs.h> #include <openenclave/edger8r/host.h> #include <openenclave/internal/calls.h> #include <openenclave/internal/defs.h> #include <openenclave/internal/raise.h> #include <openenclave/internal/safemath.h> #include "../../calls.h" #include "../../ocalls/ocalls.h" #include "enclave.h" // clang-format off /** * TEE Parameter Types used when invoking functions inside the TA. * * Each invocation includes four TEEC_Parameter structures, used for the * following purposes, by index, then by component: * * 0: Platform-specific data * Unused. * * 1: Open Enclave-specific data * Tmpref: Arguments marshaling structure, if any. * Note: This parameter is not used for built-in ECALLs. * * 2: Input parameter * Tmpref: The input parameters buffer, if any. * * 3: Output parameter * Tmpref: The output parameters buffer, if any. * * A similar pattern is used when the enclave calls into the host via an OCALL. * There is no reason why the pattern is similar, other than for consistency. * * See enclave/core/optee/gp.c. */ #define PT_BUILTIN_CALL_IN_OUT \ (TEEC_PARAM_TYPES( \ TEEC_NONE, \ TEEC_NONE, \ TEEC_MEMREF_TEMP_INPUT, \ TEEC_MEMREF_TEMP_OUTPUT)) #define PT_ENCLAVE_CALL_IN_OUT \ (TEEC_PARAM_TYPES( \ TEEC_NONE, \ TEEC_MEMREF_TEMP_INOUT, \ TEEC_MEMREF_TEMP_INPUT, \ TEEC_MEMREF_TEMP_OUTPUT)) #define PT_ENCLAVE_CALL_IN_NO_OUT \ (TEEC_PARAM_TYPES( \ TEEC_NONE, \ TEEC_MEMREF_TEMP_INOUT, \ TEEC_MEMREF_TEMP_INPUT, \ TEEC_NONE)) #define PT_ENCLAVE_CALL_NO_IN_OUT \ (TEEC_PARAM_TYPES( \ TEEC_NONE, \ TEEC_MEMREF_TEMP_INOUT, \ TEEC_NONE, \ TEEC_MEMREF_TEMP_OUTPUT)) #define PT_ENCLAVE_CALL_NO_IN_NO_OUT \ (TEEC_PARAM_TYPES( \ TEEC_NONE, \ TEEC_MEMREF_TEMP_INOUT, \ TEEC_NONE, \ TEEC_NONE)) // clang-format on /* This value is defined in the TEE Client API headers. At the time of this * writing, the value is four (4). If the header were to ever change to a lower * value, it would cause trouble for all TEE clients. As a result, it's highly * unlikely it will ever change. Nevertheless, it doesn't hurt to ensure that * the value is indeed at least as large as we assume it to be. */ OE_STATIC_ASSERT(TEEC_CONFIG_PAYLOAD_REF_COUNT >= 4); static oe_result_t _handle_call_host_function( void* inout_buffer, size_t inout_buffer_size, void* input_buffer, size_t input_buffer_size, void* output_buffer, size_t output_buffer_size, oe_enclave_t* enclave) { oe_result_t result = OE_OK; oe_call_host_function_args_t* args_ptr; oe_ocall_func_t func; ocall_table_t ocall_table; size_t buffer_size; /* Check parameters */ if (!inout_buffer || inout_buffer_size != sizeof(oe_call_host_function_args_t)) OE_RAISE(OE_INVALID_PARAMETER); /* The in/out buffer contains the OCALL parameters structure */ args_ptr = (oe_call_host_function_args_t*)inout_buffer; if (args_ptr == NULL) OE_RAISE(OE_INVALID_PARAMETER); ocall_table.ocalls = enclave->ocalls; ocall_table.num_ocalls = enclave->num_ocalls; /* Fetch matching function */ if (args_ptr->function_id >= ocall_table.num_ocalls) OE_RAISE(OE_NOT_FOUND); func = ocall_table.ocalls[args_ptr->function_id]; if (func == NULL) { result = OE_NOT_FOUND; goto done; } /* TODO: Is due to limits imposed by the ECALL/ERET mechanism and therefore * SGX-specific? */ OE_CHECK( oe_safe_add_u64(input_buffer_size, output_buffer_size, &buffer_size)); /* Buffer sizes must be pointer aligned */ if ((input_buffer_size % OE_EDGER8R_BUFFER_ALIGNMENT) != 0) OE_RAISE(OE_INVALID_PARAMETER); if ((output_buffer_size % OE_EDGER8R_BUFFER_ALIGNMENT) != 0) OE_RAISE(OE_INVALID_PARAMETER); /* Call the function */ func( input_buffer, input_buffer_size, output_buffer, output_buffer_size, &args_ptr->output_bytes_written); /* The ocall succeeded */ args_ptr->result = OE_OK; result = OE_OK; done: return result; } static TEEC_Result _handle_generic_rpc( int func, void* inout_buffer, size_t inout_buffer_size, void* input_buffer, size_t input_buffer_size, void* output_buffer, size_t output_buffer_size, void* context) { oe_enclave_t* enclave = (oe_enclave_t*)context; switch ((oe_func_t)func) { case OE_OCALL_CALL_HOST_FUNCTION: _handle_call_host_function( inout_buffer, inout_buffer_size, input_buffer, input_buffer_size, output_buffer, output_buffer_size, enclave); break; case OE_OCALL_MALLOC: HandleMalloc(*(uint64_t*)input_buffer, (uint64_t*)output_buffer); break; case OE_OCALL_FREE: HandleFree(*(uint64_t*)input_buffer); break; case OE_OCALL_THREAD_WAIT: return TEEC_ERROR_NOT_SUPPORTED; case OE_OCALL_THREAD_WAKE: return TEEC_ERROR_NOT_SUPPORTED; case OE_OCALL_GET_TIME: oe_handle_get_time( *(uint64_t*)input_buffer, (uint64_t*)output_buffer); break; default: { /* No function found with the number */ return TEEC_ERROR_ITEM_NOT_FOUND; } } return TEEC_SUCCESS; } static void* _grpc_thread_proc(void* param) { TEEC_Result res; oe_enclave_t* enclave = (oe_enclave_t*)param; /* This function only returns when the TA is terminated */ res = TEEC_ReceiveReplyGenericRpc( &enclave->session, _handle_generic_rpc, enclave); return (void*)(uintptr_t)res; } static oe_result_t _handle_call_builtin_function( oe_enclave_t* enclave, uint16_t func, uint64_t arg_in, uint64_t* arg_out) { oe_result_t result = OE_UNEXPECTED; TEEC_Result res; TEEC_Operation op; uint32_t err_origin; /* Host OS-specific data (only used on Windows) */ memset(&op.params[0], 0, sizeof(op.params[0])); /* Unused */ memset(&op.params[1], 0, sizeof(op.params[1])); /* Input buffer */ op.params[2].tmpref.buffer = &arg_in; op.params[2].tmpref.size = sizeof(arg_in); /* Output buffer */ op.params[3].tmpref.buffer = (void*)arg_out; op.params[3].tmpref.size = sizeof(*arg_out); /* Fill in parameter types */ op.paramTypes = PT_BUILTIN_CALL_IN_OUT; /* Perform the ECALL */ res = TEEC_InvokeCommand(&enclave->session, func, &op, &err_origin); /* Check the result */ if (res != TEEC_SUCCESS) OE_RAISE_MSG( OE_UNEXPECTED, "TEEC_InvokeCommand failed with 0x%x and error origin 0x%x", res, err_origin); result = OE_OK; done: return result; } static oe_result_t _handle_call_enclave_function( oe_enclave_t* enclave, oe_call_enclave_function_args_t* args) { oe_result_t result = OE_UNEXPECTED; TEEC_Result res; TEEC_Operation op; uint32_t err_origin; /* Host OS-specific data (only used on Windows) */ memset(&op.params[0], 0, sizeof(op.params[0])); /* Open Enclave-specific data */ op.params[1].tmpref.buffer = args; op.params[1].tmpref.size = sizeof(*args); /* Input buffer */ if (args->input_buffer) { op.params[2].tmpref.buffer = (void*)args->input_buffer; op.params[2].tmpref.size = args->input_buffer_size; } /* Output buffer */ if (args->output_buffer) { op.params[3].tmpref.buffer = (void*)args->output_buffer; op.params[3].tmpref.size = args->output_buffer_size; } /* Fill in parameter types */ if (args->input_buffer && args->output_buffer) op.paramTypes = PT_ENCLAVE_CALL_IN_OUT; else if (args->input_buffer) op.paramTypes = PT_ENCLAVE_CALL_IN_NO_OUT; else if (args->output_buffer) op.paramTypes = PT_ENCLAVE_CALL_NO_IN_OUT; else op.paramTypes = PT_ENCLAVE_CALL_NO_IN_NO_OUT; /* Perform the ECALL */ res = TEEC_InvokeCommand( &enclave->session, OE_ECALL_CALL_ENCLAVE_FUNCTION, &op, &err_origin); /* Check the result */ if (res != TEEC_SUCCESS) OE_RAISE_MSG( OE_UNEXPECTED, "TEEC_InvokeCommand failed with 0x%x and error origin 0x%x", res, err_origin); /* Extract the result */ result = *(oe_result_t*)args->output_buffer; done: return result; } static oe_result_t _uuid_from_string(const char* uuid_str, TEEC_UUID* uuid) { int i; uint64_t uuid_parts[5]; char* id_copy; const char* current_token; id_copy = strdup(uuid_str); /* Remove ".ta" extension, if one is present */ size_t len = strlen(id_copy); if ((len > 3) && (strcmp(&id_copy[len - 3], ".ta") == 0)) { id_copy[len - 3] = 0; } if (strlen(id_copy) != 36) return OE_FAILURE; i = 5; current_token = strtok(id_copy, "-"); while (current_token != NULL && i >= 0) { uuid_parts[--i] = strtoull(current_token, NULL, 16); current_token = strtok(NULL, "-"); } free(id_copy); if (i != 0) return OE_FAILURE; uuid->timeLow = (uint32_t)uuid_parts[4]; uuid->timeMid = (uint16_t)uuid_parts[3]; uuid->timeHiAndVersion = (uint16_t)uuid_parts[2]; uuid->clockSeqAndNode[0] = (uint8_t)(uuid_parts[1] >> (8 * 1)); uuid->clockSeqAndNode[1] = (uint8_t)(uuid_parts[1] >> (8 * 0)); uuid->clockSeqAndNode[2] = (uint8_t)(uuid_parts[0] >> (8 * 5)); uuid->clockSeqAndNode[3] = (uint8_t)(uuid_parts[0] >> (8 * 4)); uuid->clockSeqAndNode[4] = (uint8_t)(uuid_parts[0] >> (8 * 3)); uuid->clockSeqAndNode[5] = (uint8_t)(uuid_parts[0] >> (8 * 2)); uuid->clockSeqAndNode[6] = (uint8_t)(uuid_parts[0] >> (8 * 1)); uuid->clockSeqAndNode[7] = (uint8_t)(uuid_parts[0] >> (8 * 0)); return OE_OK; } oe_result_t oe_get_ecall_id_table( oe_enclave_t* enclave, oe_ecall_id_t** ecall_id_table, uint64_t* ecall_id_table_size) { oe_result_t result = OE_UNEXPECTED; if (!enclave || !ecall_id_table || !ecall_id_table_size) OE_RAISE(OE_INVALID_PARAMETER); *ecall_id_table = enclave->ecall_id_table; *ecall_id_table_size = enclave->ecall_id_table_size; result = OE_OK; done: return result; } oe_result_t oe_set_ecall_id_table( oe_enclave_t* enclave, oe_ecall_id_t* ecall_id_table, uint64_t ecall_id_table_size) { oe_result_t result = OE_UNEXPECTED; if (!enclave || !ecall_id_table || !ecall_id_table_size) OE_RAISE(OE_INVALID_PARAMETER); enclave->ecall_id_table = ecall_id_table; enclave->ecall_id_table_size = ecall_id_table_size; result = OE_OK; done: return result; } oe_result_t oe_create_enclave( const char* enclave_path, oe_enclave_type_t enclave_type, uint32_t flags, const oe_enclave_setting_t* settings, uint32_t setting_count, const oe_ocall_func_t* ocall_table, uint32_t ocall_count, const oe_ecall_info_t* ecall_name_table, uint32_t ecall_count, oe_enclave_t** enclave_out) { oe_result_t result = OE_UNEXPECTED; oe_enclave_t* enclave = NULL; TEEC_UUID teec_uuid; TEEC_Result teec_res; uint32_t teec_err_origin; bool have_mutex = false; bool have_context = false; bool have_session = false; if (enclave_out) *enclave_out = NULL; /* Check parameters */ if (!enclave_path || !enclave_out || ((enclave_type != OE_ENCLAVE_TYPE_OPTEE) && (enclave_type != OE_ENCLAVE_TYPE_AUTO)) || (setting_count > 0 && settings == NULL) || (setting_count == 0 && settings != NULL) || (flags & OE_ENCLAVE_FLAG_RESERVED) || (!(flags & OE_ENCLAVE_FLAG_SIMULATE) && (flags & OE_ENCLAVE_FLAG_DEBUG))) OE_RAISE(OE_INVALID_PARAMETER); /* Convert the path into a TEE UUID. */ OE_CHECK(_uuid_from_string(enclave_path, &teec_uuid)); /* Allocate and zero-fill the enclave structure */ if (!(enclave = (oe_enclave_t*)calloc(1, sizeof(oe_enclave_t)))) OE_RAISE(OE_OUT_OF_MEMORY); /* Initialize the mutex used to ensure that no two threads ever try to * enter an OP-TEE enclave at once. */ if (pthread_mutex_init(&enclave->mutex, NULL)) OE_RAISE(OE_FAILURE, "pthread_mutex_init failed", NULL); have_mutex = true; /* Open a context against OP-TEE. */ if ((teec_res = TEEC_InitializeContext(NULL, &enclave->ctx)) != TEEC_SUCCESS) OE_RAISE( OE_FAILURE, "TEEC_InitializeContext failed with %x", teec_res, NULL); have_context = true; /* Open a session against the TA being requested. */ if ((teec_res = TEEC_OpenSession( &enclave->ctx, &enclave->session, &teec_uuid, TEEC_LOGIN_PUBLIC, NULL, NULL, &teec_err_origin)) != TEEC_SUCCESS) OE_RAISE( OE_FAILURE, "TEEC_OpenSession failed with %x and error origin %x", teec_res, teec_err_origin, NULL); have_session = true; /* Create a thread to process Generic RPCs (OCALLs). */ if (pthread_create(&enclave->grpc_thread, NULL, _grpc_thread_proc, enclave)) OE_RAISE(OE_FAILURE, "pthread_create failed", NULL); /* Fill out the rest of the enclave structure. */ enclave->magic = ENCLAVE_MAGIC; enclave->uuid = teec_uuid; enclave->path = strndup( enclave_path, 38); // 37 + 1 = length of a UUID + NULL terminator enclave->ocalls = (const oe_ocall_func_t*)ocall_table; enclave->num_ocalls = ocall_count; /* Register ecalls */ enclave->num_ecalls = ecall_count; oe_register_ecalls(enclave, ecall_name_table, ecall_count); *enclave_out = enclave; result = OE_OK; done: if (result != OE_OK) { if (have_session) TEEC_CloseSession(&enclave->session); if (have_context) TEEC_FinalizeContext(&enclave->ctx); if (have_mutex) pthread_mutex_destroy(&enclave->mutex); if (enclave) free(enclave); } return result; } oe_result_t oe_ecall( oe_enclave_t* enclave, uint16_t func, uint64_t arg_in, uint64_t* arg_out) { oe_result_t result; /* Reject invalid parameters */ if (!enclave) OE_RAISE(OE_INVALID_PARAMETER); /* Dispatch ECALL based on function */ if (func == OE_ECALL_CALL_ENCLAVE_FUNCTION) { result = _handle_call_enclave_function( enclave, (oe_call_enclave_function_args_t*)arg_in); } else { result = _handle_call_builtin_function(enclave, func, arg_in, arg_out); } done: return result; } oe_result_t oe_terminate_enclave(oe_enclave_t* enclave) { oe_result_t result = OE_UNEXPECTED; /* Check parameters */ if (!enclave || enclave->magic != ENCLAVE_MAGIC) OE_RAISE(OE_INVALID_PARAMETER); /* Clear the magic number */ enclave->magic = 0; /* Close the session with the TA */ TEEC_CloseSession(&enclave->session); /* Finalize the context against OP-TEE */ TEEC_FinalizeContext(&enclave->ctx); /* Destroy the ecall id table */ if (enclave->ecall_id_table) free(enclave->ecall_id_table); /* Destroy the concurrency mutex */ pthread_mutex_destroy(&enclave->mutex); /* Clear the contents of the enclave structure */ memset(enclave, 0, sizeof(oe_enclave_t)); /* Free the enclave structure */ free(enclave); result = OE_OK; done: return result; }
8ba2aeaa0baf0a70ce613c348bfacd56925dfd56
e47e2263ca0b60d0c8327f74b4d4078deadea430
/tess-two/jni/com_googlecode_leptonica_android/src/src/colorcontent.c
1ce76203d3c9a18a3223fe15d500b800d98ac061
[ "Apache-2.0", "BSD-2-Clause", "CC-BY-2.5" ]
permissive
rmtheis/tess-two
43ed1bdcceee88df696efdee7c3965572ff2121f
ab4cab1bd9794aacb74162aff339daa921a68c3f
refs/heads/master
2023-03-10T08:27:42.539055
2022-03-17T11:21:24
2022-03-17T11:21:24
2,581,357
3,632
1,331
Apache-2.0
2019-10-20T00:51:50
2011-10-15T11:14:00
C
UTF-8
C
false
false
61,221
c
colorcontent.c
/*====================================================================* - Copyright (C) 2001 Leptonica. 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 ANY - 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. *====================================================================*/ /*! * \file colorcontent.c * <pre> * * Builds an image of the color content, on a per-pixel basis, * as a measure of the amount of divergence of each color * component (R,G,B) from gray. * l_int32 pixColorContent() * * Finds the 'amount' of color in an image, on a per-pixel basis, * as a measure of the difference of the pixel color from gray. * PIX *pixColorMagnitude() * * Generates a mask over pixels that have sufficient color and * are not too close to gray pixels. * PIX *pixMaskOverColorPixels() * * Generates mask over pixels within a prescribed cube in RGB space * PIX *pixMaskOverColorRange() * * Finds the fraction of pixels with "color" that are not close to black * l_int32 pixColorFraction() * * Finds the number of perceptually significant gray intensities * in a grayscale image. * l_int32 pixNumSignificantGrayColors() * * Identifies images where color quantization will cause posterization * due to the existence of many colors in low-gradient regions. * l_int32 pixColorsForQuantization() * * Finds the number of unique colors in an image * l_int32 pixNumColors() * * Find the most "populated" colors in the image (and quantize) * l_int32 pixGetMostPopulatedColors() * PIX *pixSimpleColorQuantize() * * Constructs a color histogram based on rgb indices * NUMA *pixGetRGBHistogram() * l_int32 makeRGBIndexTables() * l_int32 getRGBFromIndex() * * Identify images that have highlight (red) color * l_int32 pixHasHighlightRed() * * Color is tricky. If we consider gray (r = g = b) to have no color * content, how should we define the color content in each component * of an arbitrary pixel, as well as the overall color magnitude? * * I can think of three ways to define the color content in each component: * * (1) Linear. For each component, take the difference from the average * of all three. * (2) Linear. For each component, take the difference from the average * of the other two. * (3) Nonlinear. For each component, take the minimum of the differences * from the other two. * * How might one choose from among these? Consider two different situations: * (a) r = g = 0, b = 255 {255} /255/ * (b) r = 0, g = 127, b = 255 {191} /128/ * How much g is in each of these? The three methods above give: * (a) 1: 85 2: 127 3: 0 [85] * (b) 1: 0 2: 0 3: 127 [0] * How much b is in each of these? * (a) 1: 170 2: 255 3: 255 [255] * (b) 1: 127 2: 191 3: 127 [191] * The number I'd "like" to give is in []. (Please don't ask why, it's * just a feeling. * * So my preferences seem to be somewhere between (1) and (2). * (3) is just too "decisive!" Let's pick (2). * * We also allow compensation for white imbalance. For each * component, we do a linear TRC (gamma = 1.0), where the black * point remains at 0 and the white point is given by the input * parameter. This is equivalent to doing a global remapping, * as with pixGlobalNormRGB(), followed by color content (or magnitude) * computation, but without the overhead of first creating the * white point normalized image. * * Another useful property is the overall color magnitude in the pixel. * For this there are again several choices, such as: * (a) rms deviation from the mean * (b) the average L1 deviation from the mean * (c) the maximum (over components) of one of the color * content measures given above. * * For now, we will choose two of the methods in (c): * L_MAX_DIFF_FROM_AVERAGE_2 * Define the color magnitude as the maximum over components * of the difference between the component value and the * average of the other two. It is easy to show that * this is equivalent to selecting the two component values * that are closest to each other, averaging them, and * using the distance from that average to the third component. * For (a) and (b) above, this value is in {..}. * L_MAX_MIN_DIFF_FROM_2 * Define the color magnitude as the maximum over components * of the minimum difference between the component value and the * other two values. It is easy to show that this is equivalent * to selecting the intermediate value of the three differences * between the three components. For (a) and (b) above, * this value is in /../. * </pre> */ #include "allheaders.h" /* ----------------------------------------------------------------------- * * Builds an image of the color content, on a per-pixel basis, * * as a measure of the amount of divergence of each color * * component (R,G,B) from gray. * * ----------------------------------------------------------------------- */ /*! * \brief pixColorContent() * * \param[in] pixs 32 bpp rgb or 8 bpp colormapped * \param[in] rwhite, gwhite, bwhite color value associated with white point * \param[in] mingray min gray value for which color is measured * \param[out] ppixr [optional] 8 bpp red 'content' * \param[out] ppixg [optional] 8 bpp green 'content' * \param[out] ppixb [optional] 8 bpp blue 'content' * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This returns the color content in each component, which is * a measure of the deviation from gray, and is defined * as the difference between the component and the average of * the other two components. See the discussion at the * top of this file. * (2) The three numbers (rwhite, gwhite and bwhite) can be thought * of as the values in the image corresponding to white. * They are used to compensate for an unbalanced color white point. * They must either be all 0 or all non-zero. To turn this * off, set them all to 0. * (3) If the maximum component after white point correction, * max(r,g,b), is less than mingray, all color components * for that pixel are set to zero. * Use mingray = 0 to turn off this filtering of dark pixels. * (4) Therefore, use 0 for all four input parameters if the color * magnitude is to be calculated without either white balance * correction or dark filtering. * </pre> */ l_int32 pixColorContent(PIX *pixs, l_int32 rwhite, l_int32 gwhite, l_int32 bwhite, l_int32 mingray, PIX **ppixr, PIX **ppixg, PIX **ppixb) { l_int32 w, h, d, i, j, wplc, wplr, wplg, wplb; l_int32 rval, gval, bval, rgdiff, rbdiff, gbdiff, maxval, colorval; l_int32 *rtab, *gtab, *btab; l_uint32 pixel; l_uint32 *datac, *datar, *datag, *datab, *linec, *liner, *lineg, *lineb; NUMA *nar, *nag, *nab; PIX *pixc; /* rgb */ PIX *pixr, *pixg, *pixb; /* 8 bpp grayscale */ PIXCMAP *cmap; PROCNAME("pixColorContent"); if (!ppixr && !ppixg && !ppixb) return ERROR_INT("no return val requested", procName, 1); if (ppixr) *ppixr = NULL; if (ppixg) *ppixg = NULL; if (ppixb) *ppixb = NULL; if (!pixs) return ERROR_INT("pixs not defined", procName, 1); if (mingray < 0) mingray = 0; pixGetDimensions(pixs, &w, &h, &d); if (mingray > 255) return ERROR_INT("mingray > 255", procName, 1); if (rwhite < 0 || gwhite < 0 || bwhite < 0) return ERROR_INT("some white vals are negative", procName, 1); if ((rwhite || gwhite || bwhite) && (rwhite * gwhite * bwhite == 0)) return ERROR_INT("white vals not all zero or all nonzero", procName, 1); cmap = pixGetColormap(pixs); if (!cmap && d != 32) return ERROR_INT("pixs neither cmapped nor 32 bpp", procName, 1); if (cmap) pixc = pixRemoveColormap(pixs, REMOVE_CMAP_TO_FULL_COLOR); else pixc = pixClone(pixs); pixr = pixg = pixb = NULL; pixGetDimensions(pixc, &w, &h, NULL); if (ppixr) { pixr = pixCreate(w, h, 8); datar = pixGetData(pixr); wplr = pixGetWpl(pixr); *ppixr = pixr; } if (ppixg) { pixg = pixCreate(w, h, 8); datag = pixGetData(pixg); wplg = pixGetWpl(pixg); *ppixg = pixg; } if (ppixb) { pixb = pixCreate(w, h, 8); datab = pixGetData(pixb); wplb = pixGetWpl(pixb); *ppixb = pixb; } datac = pixGetData(pixc); wplc = pixGetWpl(pixc); if (rwhite) { /* all white pt vals are nonzero */ nar = numaGammaTRC(1.0, 0, rwhite); rtab = numaGetIArray(nar); nag = numaGammaTRC(1.0, 0, gwhite); gtab = numaGetIArray(nag); nab = numaGammaTRC(1.0, 0, bwhite); btab = numaGetIArray(nab); } for (i = 0; i < h; i++) { linec = datac + i * wplc; if (pixr) liner = datar + i * wplr; if (pixg) lineg = datag + i * wplg; if (pixb) lineb = datab + i * wplb; for (j = 0; j < w; j++) { pixel = linec[j]; extractRGBValues(pixel, &rval, &gval, &bval); if (rwhite) { /* color correct for white point */ rval = rtab[rval]; gval = gtab[gval]; bval = btab[bval]; } if (mingray > 0) { /* dark pixels have no color value */ maxval = L_MAX(rval, gval); maxval = L_MAX(maxval, bval); if (maxval < mingray) continue; /* colorval = 0 for each component */ } rgdiff = L_ABS(rval - gval); rbdiff = L_ABS(rval - bval); gbdiff = L_ABS(gval - bval); if (pixr) { colorval = (rgdiff + rbdiff) / 2; SET_DATA_BYTE(liner, j, colorval); } if (pixg) { colorval = (rgdiff + gbdiff) / 2; SET_DATA_BYTE(lineg, j, colorval); } if (pixb) { colorval = (rbdiff + gbdiff) / 2; SET_DATA_BYTE(lineb, j, colorval); } } } if (rwhite) { numaDestroy(&nar); numaDestroy(&nag); numaDestroy(&nab); LEPT_FREE(rtab); LEPT_FREE(gtab); LEPT_FREE(btab); } pixDestroy(&pixc); return 0; } /* ----------------------------------------------------------------------- * * Finds the 'amount' of color in an image, on a per-pixel basis, * * as a measure of the difference of the pixel color from gray. * * ----------------------------------------------------------------------- */ /*! * \brief pixColorMagnitude() * * \param[in] pixs 32 bpp rgb or 8 bpp colormapped * \param[in] rwhite, gwhite, bwhite color value associated with white point * \param[in] type chooses the method for calculating the color magnitude: * L_MAX_DIFF_FROM_AVERAGE_2, L_MAX_MIN_DIFF_FROM_2, * L_MAX_DIFF * \return pixd 8 bpp, amount of color in each source pixel, * or NULL on error * * <pre> * Notes: * (1) For an RGB image, a gray pixel is one where all three components * are equal. We define the amount of color in an RGB pixel as * a function depending on the absolute value of the differences * between the three color components. Consider the two largest * of these differences. The pixel component in common to these * two differences is the color farthest from the other two. * The color magnitude in an RGB pixel can be taken as one * of these three definitions: * (a) The average of these two differences. This is the * average distance from the two components that are * nearest to each other to the third component. * (b) The minimum value of these two differences. This is * the intermediate value of the three distances between * component values. Stated otherwise, it is the * maximum over all components of the minimum distance * from that component to the other two components. * (c) The maximum difference between component values. * (2) As an example, suppose that R and G are the closest in * magnitude. Then the color is determined as either: * (a) The average distance of B from these two: * (|B - R| + |B - G|) / 2 * (b) The minimum distance of B from these two: * min(|B - R|, |B - G|). * (c) The maximum distance of B from these two: * max(|B - R|, |B - G|) * (3) The three methods for choosing the color magnitude from * the components are selected with these flags: * (a) L_MAX_DIFF_FROM_AVERAGE_2 * (b) L_MAX_MIN_DIFF_FROM_2 * (c) L_MAX_DIFF * (4) The three numbers (rwhite, gwhite and bwhite) can be thought * of as the values in the image corresponding to white. * They are used to compensate for an unbalanced color white point. * They must either be all 0 or all non-zero. To turn this * off, set them all to 0. * </pre> */ PIX * pixColorMagnitude(PIX *pixs, l_int32 rwhite, l_int32 gwhite, l_int32 bwhite, l_int32 type) { l_int32 w, h, d, i, j, wplc, wpld; l_int32 rval, gval, bval, rdist, gdist, bdist, colorval; l_int32 rgdist, rbdist, gbdist, mindist, maxdist, minval, maxval; l_int32 *rtab, *gtab, *btab; l_uint32 pixel; l_uint32 *datac, *datad, *linec, *lined; NUMA *nar, *nag, *nab; PIX *pixc, *pixd; PIXCMAP *cmap; PROCNAME("pixColorMagnitude"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, NULL); pixGetDimensions(pixs, &w, &h, &d); if (type != L_MAX_DIFF_FROM_AVERAGE_2 && type != L_MAX_MIN_DIFF_FROM_2 && type != L_MAX_DIFF) return (PIX *)ERROR_PTR("invalid type", procName, NULL); if (rwhite < 0 || gwhite < 0 || bwhite < 0) return (PIX *)ERROR_PTR("some white vals are negative", procName, NULL); if ((rwhite || gwhite || bwhite) && (rwhite * gwhite * bwhite == 0)) return (PIX *)ERROR_PTR("white vals not all zero or all nonzero", procName, NULL); cmap = pixGetColormap(pixs); if (!cmap && d != 32) return (PIX *)ERROR_PTR("pixs not cmapped or 32 bpp", procName, NULL); if (cmap) pixc = pixRemoveColormap(pixs, REMOVE_CMAP_TO_FULL_COLOR); else pixc = pixClone(pixs); pixd = pixCreate(w, h, 8); datad = pixGetData(pixd); wpld = pixGetWpl(pixd); datac = pixGetData(pixc); wplc = pixGetWpl(pixc); if (rwhite) { /* all white pt vals are nonzero */ nar = numaGammaTRC(1.0, 0, rwhite); rtab = numaGetIArray(nar); nag = numaGammaTRC(1.0, 0, gwhite); gtab = numaGetIArray(nag); nab = numaGammaTRC(1.0, 0, bwhite); btab = numaGetIArray(nab); } for (i = 0; i < h; i++) { linec = datac + i * wplc; lined = datad + i * wpld; for (j = 0; j < w; j++) { pixel = linec[j]; extractRGBValues(pixel, &rval, &gval, &bval); if (rwhite) { /* color correct for white point */ rval = rtab[rval]; gval = gtab[gval]; bval = btab[bval]; } if (type == L_MAX_DIFF_FROM_AVERAGE_2) { rdist = ((gval + bval ) / 2 - rval); rdist = L_ABS(rdist); gdist = ((rval + bval ) / 2 - gval); gdist = L_ABS(gdist); bdist = ((rval + gval ) / 2 - bval); bdist = L_ABS(bdist); colorval = L_MAX(rdist, gdist); colorval = L_MAX(colorval, bdist); } else if (type == L_MAX_MIN_DIFF_FROM_2) { /* intermediate dist */ rgdist = L_ABS(rval - gval); rbdist = L_ABS(rval - bval); gbdist = L_ABS(gval - bval); maxdist = L_MAX(rgdist, rbdist); if (gbdist >= maxdist) { colorval = maxdist; } else { /* gbdist is smallest or intermediate */ mindist = L_MIN(rgdist, rbdist); colorval = L_MAX(mindist, gbdist); } } else { /* type == L_MAX_DIFF */ minval = L_MIN(rval, gval); minval = L_MIN(minval, bval); maxval = L_MAX(rval, gval); maxval = L_MAX(maxval, bval); colorval = maxval - minval; } SET_DATA_BYTE(lined, j, colorval); } } if (rwhite) { numaDestroy(&nar); numaDestroy(&nag); numaDestroy(&nab); LEPT_FREE(rtab); LEPT_FREE(gtab); LEPT_FREE(btab); } pixDestroy(&pixc); return pixd; } /* ----------------------------------------------------------------------- * * Generates a mask over pixels that have sufficient color and * * are not too close to gray pixels. * * ----------------------------------------------------------------------- */ /*! * \brief pixMaskOverColorPixels() * * \param[in] pixs 32 bpp rgb or 8 bpp colormapped * \param[in] threshdiff threshold for minimum of the max difference * between components * \param[in] mindist minimum allowed distance from nearest non-color pixel * \return pixd 1 bpp, mask over color pixels, or NULL on error * * <pre> * Notes: * (1) The generated mask identifies each pixel as either color or * non-color. For a pixel to be color, it must satisfy two * constraints: * (a) The max difference between the r,g and b components must * equal or exceed a threshold %threshdiff. * (b) It must be at least %mindist (in an 8-connected way) * from the nearest non-color pixel. * (2) The distance constraint (b) is only applied if %mindist \> 1. * For example, if %mindist == 2, the color pixels identified * by (a) are eroded by a 3x3 Sel. In general, the Sel size * for erosion is 2 * (%mindist - 1) + 1. * Why have this constraint? In scanned images that are * essentially gray, color artifacts are typically introduced * in transition regions near sharp edges that go from dark * to light, so this allows these transition regions to be removed. * </pre> */ PIX * pixMaskOverColorPixels(PIX *pixs, l_int32 threshdiff, l_int32 mindist) { l_int32 w, h, d, i, j, wpls, wpld, size; l_int32 rval, gval, bval, minval, maxval; l_uint32 *datas, *datad, *lines, *lined; PIX *pixc, *pixd; PIXCMAP *cmap; PROCNAME("pixMaskOverColorPixels"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, NULL); pixGetDimensions(pixs, &w, &h, &d); cmap = pixGetColormap(pixs); if (!cmap && d != 32) return (PIX *)ERROR_PTR("pixs not cmapped or 32 bpp", procName, NULL); if (cmap) pixc = pixRemoveColormap(pixs, REMOVE_CMAP_TO_FULL_COLOR); else pixc = pixClone(pixs); pixd = pixCreate(w, h, 1); datad = pixGetData(pixd); wpld = pixGetWpl(pixd); datas = pixGetData(pixc); wpls = pixGetWpl(pixc); for (i = 0; i < h; i++) { lines = datas + i * wpls; lined = datad + i * wpld; for (j = 0; j < w; j++) { extractRGBValues(lines[j], &rval, &gval, &bval); minval = L_MIN(rval, gval); minval = L_MIN(minval, bval); maxval = L_MAX(rval, gval); maxval = L_MAX(maxval, bval); if (maxval - minval >= threshdiff) SET_DATA_BIT(lined, j); } } if (mindist > 1) { size = 2 * (mindist - 1) + 1; pixErodeBrick(pixd, pixd, size, size); } pixDestroy(&pixc); return pixd; } /* ----------------------------------------------------------------------- * * Generates a mask over pixels that have RGB color components * * within the prescribed range (a cube in RGB color space) * * ----------------------------------------------------------------------- */ /*! * \brief pixMaskOverColorRange() * * \param[in] pixs 32 bpp rgb or 8 bpp colormapped * \param[in] rmin, rmax min and max allowed values for red component * \param[in] gmin, gmax * \param[in] bmin, bmax * \return pixd 1 bpp, mask over color pixels, or NULL on error */ PIX * pixMaskOverColorRange(PIX *pixs, l_int32 rmin, l_int32 rmax, l_int32 gmin, l_int32 gmax, l_int32 bmin, l_int32 bmax) { l_int32 w, h, d, i, j, wpls, wpld; l_int32 rval, gval, bval; l_uint32 *datas, *datad, *lines, *lined; PIX *pixc, *pixd; PIXCMAP *cmap; PROCNAME("pixMaskOverColorRange"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, NULL); pixGetDimensions(pixs, &w, &h, &d); cmap = pixGetColormap(pixs); if (!cmap && d != 32) return (PIX *)ERROR_PTR("pixs not cmapped or 32 bpp", procName, NULL); if (cmap) pixc = pixRemoveColormap(pixs, REMOVE_CMAP_TO_FULL_COLOR); else pixc = pixClone(pixs); pixd = pixCreate(w, h, 1); datad = pixGetData(pixd); wpld = pixGetWpl(pixd); datas = pixGetData(pixc); wpls = pixGetWpl(pixc); for (i = 0; i < h; i++) { lines = datas + i * wpls; lined = datad + i * wpld; for (j = 0; j < w; j++) { extractRGBValues(lines[j], &rval, &gval, &bval); if (rval < rmin || rval > rmax) continue; if (gval < gmin || gval > gmax) continue; if (bval < bmin || bval > bmax) continue; SET_DATA_BIT(lined, j); } } pixDestroy(&pixc); return pixd; } /* ----------------------------------------------------------------------- * * Finds the fraction of pixels with "color" that are not close to black * * ----------------------------------------------------------------------- */ /*! * \brief pixColorFraction() * * \param[in] pixs 32 bpp rgb * \param[in] darkthresh threshold near black; if the lightest component * is below this, the pixel is not considered in * the statistics; typ. 20 * \param[in] lightthresh threshold near white; if the darkest component * is above this, the pixel is not considered in * the statistics; typ. 244 * \param[in] diffthresh thresh for the maximum difference between * component value; below this the pixel is not * considered to have sufficient color * \param[in] factor subsampling factor * \param[out] ppixfract fraction of pixels in intermediate * brightness range that were considered * for color content * \param[out] pcolorfract fraction of pixels that meet the * criterion for sufficient color; 0.0 on error * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This function is asking the question: to what extent does the * image appear to have color? The amount of color a pixel * appears to have depends on both the deviation of the * individual components from their average and on the average * intensity itself. For example, the color will be much more * obvious with a small deviation from white than the same * deviation from black. * (2) Any pixel that meets these three tests is considered a * colorful pixel: * (a) the lightest component must equal or exceed %darkthresh * (b) the darkest component must not exceed %lightthresh * (c) the max difference between components must equal or * exceed %diffthresh. * (3) The dark pixels are removed from consideration because * they don't appear to have color. * (4) The very lightest pixels are removed because if an image * has a lot of "white", the color fraction will be artificially * low, even if all the other pixels are colorful. * (5) If pixfract is very small, there are few pixels that are neither * black nor white. If colorfract is very small, the pixels * that are neither black nor white have very little color * content. The product 'pixfract * colorfract' gives the * fraction of pixels with significant color content. * (6) One use of this function is as a preprocessing step for median * cut quantization (colorquant2.c), which does a very poor job * splitting the color space into rectangular volume elements when * all the pixels are near the diagonal of the color cube. For * octree quantization of an image with only gray values, the * 2^(level) octcubes on the diagonal are the only ones * that can be occupied. * </pre> */ l_int32 pixColorFraction(PIX *pixs, l_int32 darkthresh, l_int32 lightthresh, l_int32 diffthresh, l_int32 factor, l_float32 *ppixfract, l_float32 *pcolorfract) { l_int32 i, j, w, h, wpl, rval, gval, bval, minval, maxval; l_int32 total, npix, ncolor; l_uint32 pixel; l_uint32 *data, *line; PROCNAME("pixColorFraction"); if (ppixfract) *ppixfract = 0.0; if (pcolorfract) *pcolorfract = 0.0; if (!ppixfract || !pcolorfract) return ERROR_INT("&pixfract and &colorfract not defined", procName, 1); if (!pixs || pixGetDepth(pixs) != 32) return ERROR_INT("pixs not defined or not 32 bpp", procName, 1); pixGetDimensions(pixs, &w, &h, NULL); data = pixGetData(pixs); wpl = pixGetWpl(pixs); npix = ncolor = total = 0; for (i = 0; i < h; i += factor) { line = data + i * wpl; for (j = 0; j < w; j += factor) { total++; pixel = line[j]; extractRGBValues(pixel, &rval, &gval, &bval); minval = L_MIN(rval, gval); minval = L_MIN(minval, bval); if (minval > lightthresh) /* near white */ continue; maxval = L_MAX(rval, gval); maxval = L_MAX(maxval, bval); if (maxval < darkthresh) /* near black */ continue; npix++; if (maxval - minval >= diffthresh) ncolor++; } } if (npix == 0) { L_WARNING("No pixels found for consideration\n", procName); return 0; } *ppixfract = (l_float32)npix / (l_float32)total; *pcolorfract = (l_float32)ncolor / (l_float32)npix; return 0; } /* ----------------------------------------------------------------------- * * Finds the number of perceptually significant gray intensities * * in a grayscale image. * * ----------------------------------------------------------------------- */ /*! * \brief pixNumSignificantGrayColors() * * \param[in] pixs 8 bpp gray * \param[in] darkthresh dark threshold for minimum intensity to be * considered; typ. 20 * \param[in] lightthresh threshold near white, for maximum intensity * to be considered; typ. 236 * \param[in] minfract minimum fraction of all pixels to include a level * as significant; typ. 0.0001; should be < 0.001 * \param[in] factor subsample factor; integer >= 1 * \param[out] pncolors number of significant colors; 0 on error * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This function is asking the question: how many perceptually * significant gray color levels is in this pix? * A color level must meet 3 criteria to be significant: * ~ it can't be too close to black * ~ it can't be too close to white * ~ it must have at least some minimum fractional population * (2) Use -1 for default values for darkthresh, lightthresh and minfract. * (3) Choose default of darkthresh = 20, because variations in very * dark pixels are not visually significant. * (4) Choose default of lightthresh = 236, because document images * that have been jpeg'd typically have near-white pixels in the * 8x8 jpeg blocks, and these should not be counted. It is desirable * to obtain a clean image by quantizing this noise away. * </pre> */ l_int32 pixNumSignificantGrayColors(PIX *pixs, l_int32 darkthresh, l_int32 lightthresh, l_float32 minfract, l_int32 factor, l_int32 *pncolors) { l_int32 i, w, h, count, mincount, ncolors; NUMA *na; PROCNAME("pixNumSignificantGrayColors"); if (!pncolors) return ERROR_INT("&ncolors not defined", procName, 1); *pncolors = 0; if (!pixs || pixGetDepth(pixs) != 8) return ERROR_INT("pixs not defined or not 8 bpp", procName, 1); if (darkthresh < 0) darkthresh = 20; /* defaults */ if (lightthresh < 0) lightthresh = 236; if (minfract < 0.0) minfract = 0.0001; if (minfract > 1.0) return ERROR_INT("minfract > 1.0", procName, 1); if (minfract >= 0.001) L_WARNING("minfract too big; likely to underestimate ncolors\n", procName); if (lightthresh > 255 || darkthresh >= lightthresh) return ERROR_INT("invalid thresholds", procName, 1); if (factor < 1) factor = 1; pixGetDimensions(pixs, &w, &h, NULL); mincount = (l_int32)(minfract * w * h * factor * factor); if ((na = pixGetGrayHistogram(pixs, factor)) == NULL) return ERROR_INT("na not made", procName, 1); ncolors = 2; /* add in black and white */ for (i = darkthresh; i <= lightthresh; i++) { numaGetIValue(na, i, &count); if (count >= mincount) ncolors++; } *pncolors = ncolors; numaDestroy(&na); return 0; } /* ----------------------------------------------------------------------- * * Identifies images where color quantization will cause posterization * * due to the existence of many colors in low-gradient regions. * * ----------------------------------------------------------------------- */ /*! * \brief pixColorsForQuantization() * \param[in] pixs 8 bpp gray or 32 bpp rgb; with or without colormap * \param[in] thresh binary threshold on edge gradient; 0 for default * \param[out] pncolors the number of colors found * \param[out] piscolor [optional] 1 if significant color is found; * 0 otherwise. If pixs is 8 bpp, and does not have * a colormap with color entries, this is 0 * \param[in] debug 1 to output masked image that is tested for colors; * 0 otherwise * \return 0 if OK, 1 on error. * * <pre> * Notes: * (1) This function finds a measure of the number of colors that are * found in low-gradient regions of an image. By its * magnitude relative to some threshold (not specified in * this function), it gives a good indication of whether * quantization will generate posterization. This number * is larger for images with regions of slowly varying * intensity (if 8 bpp) or color (if rgb). Such images, if * quantized, may require dithering to avoid posterization, * and lossless compression is then expected to be poor. * (2) If pixs has a colormap, the number of colors returned is * the number in the colormap. * (3) It is recommended that document images be reduced to a width * of 800 pixels before applying this function. Then it can * be expected that color detection will be fairly accurate * and the number of colors will reflect both the content and * the type of compression to be used. For less than 15 colors, * there is unlikely to be a halftone image, and lossless * quantization should give both a good visual result and * better compression. * (4) When using the default threshold on the gradient (15), * images (both gray and rgb) where ncolors is greater than * about 15 will compress poorly with either lossless * compression or dithered quantization, and they may be * posterized with non-dithered quantization. * (5) For grayscale images, or images without significant color, * this returns the number of significant gray levels in * the low-gradient regions. The actual number of gray levels * can be large due to jpeg compression noise in the background. * (6) Similarly, for color images, the actual number of different * (r,g,b) colors in the low-gradient regions (rather than the * number of occupied level 4 octcubes) can be quite large, e.g., * due to jpeg compression noise, even for regions that appear * to be of a single color. By quantizing to level 4 octcubes, * most of these superfluous colors are removed from the counting. * (7) The image is tested for color. If there is very little color, * it is thresholded to gray and the number of gray levels in * the low gradient regions is found. If the image has color, * the number of occupied level 4 octcubes is found. * (8) The number of colors in the low-gradient regions increases * monotonically with the threshold %thresh on the edge gradient. * (9) Background: grayscale and color quantization is often useful * to achieve highly compressed images with little visible * distortion. However, gray or color washes (regions of * low gradient) can defeat this approach to high compression. * How can one determine if an image is expected to compress * well using gray or color quantization? We use the fact that * * gray washes, when quantized with less than 50 intensities, * have posterization (visible boundaries between regions * of uniform 'color') and poor lossless compression * * color washes, when quantized with level 4 octcubes, * typically result in both posterization and the occupancy * of many level 4 octcubes. * Images can have colors either intrinsically or as jpeg * compression artifacts. This function reduces but does not * completely eliminate measurement of jpeg quantization noise * in the white background of grayscale or color images. * </pre> */ l_int32 pixColorsForQuantization(PIX *pixs, l_int32 thresh, l_int32 *pncolors, l_int32 *piscolor, l_int32 debug) { l_int32 w, h, d, minside, factor; l_float32 pixfract, colorfract; PIX *pixt, *pixsc, *pixg, *pixe, *pixb, *pixm; PIXCMAP *cmap; PROCNAME("pixColorsForQuantization"); if (piscolor) *piscolor = 0; if (!pncolors) return ERROR_INT("&ncolors not defined", procName, 1); *pncolors = 0; if (!pixs) return ERROR_INT("pixs not defined", procName, 1); if ((cmap = pixGetColormap(pixs)) != NULL) { *pncolors = pixcmapGetCount(cmap); if (piscolor) pixcmapHasColor(cmap, piscolor); return 0; } pixGetDimensions(pixs, &w, &h, &d); if (d != 8 && d != 32) return ERROR_INT("pixs not 8 or 32 bpp", procName, 1); if (thresh <= 0) thresh = 15; /* First test if 32 bpp has any significant color; if not, * convert it to gray. Colors whose average values are within * 20 of black or 8 of white are ignored because they're not * very 'colorful'. If less than 2.5/10000 of the pixels have * significant color, consider the image to be gray. */ minside = L_MIN(w, h); if (d == 8) { pixt = pixClone(pixs); } else { /* d == 32 */ factor = L_MAX(1, minside / 400); pixColorFraction(pixs, 20, 248, 30, factor, &pixfract, &colorfract); if (pixfract * colorfract < 0.00025) { pixt = pixGetRGBComponent(pixs, COLOR_RED); d = 8; } else { /* d == 32 */ pixt = pixClone(pixs); if (piscolor) *piscolor = 1; } } /* If the smallest side is less than 1000, do not downscale. * If it is in [1000 ... 2000), downscale by 2x. If it is >= 2000, * downscale by 4x. Factors of 2 are chosen for speed. The * actual resolution at which subsequent calculations take place * is not strongly dependent on downscaling. */ factor = L_MAX(1, minside / 500); if (factor == 1) pixsc = pixCopy(NULL, pixt); /* to be sure pixs is unchanged */ else if (factor == 2 || factor == 3) pixsc = pixScaleAreaMap2(pixt); else pixsc = pixScaleAreaMap(pixt, 0.25, 0.25); /* Basic edge mask generation procedure: * ~ work on a grayscale image * ~ get a 1 bpp edge mask by using an edge filter and * thresholding to get fg pixels at the edges * ~ for gray, dilate with a 3x3 brick Sel to get mask over * all pixels within a distance of 1 pixel from the nearest * edge pixel * ~ for color, dilate with a 7x7 brick Sel to get mask over * all pixels within a distance of 3 pixels from the nearest * edge pixel */ if (d == 8) pixg = pixClone(pixsc); else /* d == 32 */ pixg = pixConvertRGBToLuminance(pixsc); pixe = pixSobelEdgeFilter(pixg, L_ALL_EDGES); pixb = pixThresholdToBinary(pixe, thresh); pixInvert(pixb, pixb); if (d == 8) pixm = pixMorphSequence(pixb, "d3.3", 0); else pixm = pixMorphSequence(pixb, "d7.7", 0); /* Mask the near-edge pixels to white, and count the colors. * If grayscale, don't count colors within 20 levels of * black or white, and only count colors with a fraction * of at least 1/10000 of the image pixels. * If color, count the number of level 4 octcubes that * contain at least 20 pixels. These magic numbers are guesses * as to what might work, based on a small data set. Results * should not be overly sensitive to their actual values. */ if (d == 8) { pixSetMasked(pixg, pixm, 0xff); if (debug) pixWrite("junkpix8.png", pixg, IFF_PNG); pixNumSignificantGrayColors(pixg, 20, 236, 0.0001, 1, pncolors); } else { /* d == 32 */ pixSetMasked(pixsc, pixm, 0xffffffff); if (debug) pixWrite("junkpix32.png", pixsc, IFF_PNG); pixNumberOccupiedOctcubes(pixsc, 4, 20, -1, pncolors); } pixDestroy(&pixt); pixDestroy(&pixsc); pixDestroy(&pixg); pixDestroy(&pixe); pixDestroy(&pixb); pixDestroy(&pixm); return 0; } /* ----------------------------------------------------------------------- * * Finds the number of unique colors in an image * * ----------------------------------------------------------------------- */ /*! * \brief pixNumColors() * \param[in] pixs 2, 4, 8, 32 bpp * \param[in] factor subsampling factor; integer * \param[out] pncolors the number of colors found, or 0 if * there are more than 256 * \return 0 if OK, 1 on error. * * <pre> * Notes: * (1) This returns the actual number of colors found in the image, * even if there is a colormap. If %factor == 1 and the * number of colors differs from the number of entries * in the colormap, a warning is issued. * (2) Use %factor == 1 to find the actual number of colors. * Use %factor \> 1 to quickly find the approximate number of colors. * (3) For d = 2, 4 or 8 bpp grayscale, this returns the number * of colors found in the image in 'ncolors'. * (4) For d = 32 bpp (rgb), if the number of colors is * greater than 256, this returns 0 in 'ncolors'. * </pre> */ l_int32 pixNumColors(PIX *pixs, l_int32 factor, l_int32 *pncolors) { l_int32 w, h, d, i, j, wpl, hashsize, sum, count; l_int32 rval, gval, bval, val; l_int32 *inta; l_uint32 pixel; l_uint32 *data, *line; PIXCMAP *cmap; PROCNAME("pixNumColors"); if (!pncolors) return ERROR_INT("&ncolors not defined", procName, 1); *pncolors = 0; if (!pixs) return ERROR_INT("pixs not defined", procName, 1); pixGetDimensions(pixs, &w, &h, &d); if (d != 2 && d != 4 && d != 8 && d != 32) return ERROR_INT("d not in {2, 4, 8, 32}", procName, 1); if (factor < 1) factor = 1; data = pixGetData(pixs); wpl = pixGetWpl(pixs); sum = 0; if (d != 32) { /* grayscale */ inta = (l_int32 *)LEPT_CALLOC(256, sizeof(l_int32)); for (i = 0; i < h; i += factor) { line = data + i * wpl; for (j = 0; j < w; j += factor) { if (d == 8) val = GET_DATA_BYTE(line, j); else if (d == 4) val = GET_DATA_QBIT(line, j); else /* d == 2 */ val = GET_DATA_DIBIT(line, j); inta[val] = 1; } } for (i = 0; i < 256; i++) if (inta[i]) sum++; *pncolors = sum; LEPT_FREE(inta); cmap = pixGetColormap(pixs); if (cmap && factor == 1) { count = pixcmapGetCount(cmap); if (sum != count) L_WARNING("colormap size %d differs from actual colors\n", procName, count); } return 0; } /* 32 bpp rgb; quit if we get above 256 colors */ hashsize = 5507; /* big and prime; collisions are not likely */ inta = (l_int32 *)LEPT_CALLOC(hashsize, sizeof(l_int32)); for (i = 0; i < h; i += factor) { line = data + i * wpl; for (j = 0; j < w; j += factor) { pixel = line[j]; extractRGBValues(pixel, &rval, &gval, &bval); val = (137 * rval + 269 * gval + 353 * bval) % hashsize; if (inta[val] == 0) { inta[val] = 1; sum++; if (sum > 256) { LEPT_FREE(inta); return 0; } } } } *pncolors = sum; LEPT_FREE(inta); return 0; } /* ----------------------------------------------------------------------- * * Find the most "populated" colors in the image (and quantize) * * ----------------------------------------------------------------------- */ /*! * \brief pixGetMostPopulatedColors() * \param[in] pixs 32 bpp rgb * \param[in] sigbits 2-6, significant bits retained in the quantizer * for each component of the input image * \param[in] factor subsampling factor; use 1 for no subsampling * \param[in] ncolors the number of most populated colors to select * \param[out] parray [optional] array of colors, each as 0xrrggbb00 * \param[out] pcmap [optional] colormap of the colors * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This finds the %ncolors most populated cubes in rgb colorspace, * where the cube size depends on %sigbits as * cube side = (256 \>\> sigbits) * (2) The rgb color components are found at the center of the cube. * (3) The output array of colors can be displayed using * pixDisplayColorArray(array, ncolors, ...); * </pre> */ l_int32 pixGetMostPopulatedColors(PIX *pixs, l_int32 sigbits, l_int32 factor, l_int32 ncolors, l_uint32 **parray, PIXCMAP **pcmap) { l_int32 n, i, rgbindex, rval, gval, bval; NUMA *nahisto, *naindex; PROCNAME("pixGetMostPopulatedColors"); if (!parray && !pcmap) return ERROR_INT("no return val requested", procName, 1); if (parray) *parray = NULL; if (pcmap) *pcmap = NULL; if (!pixs || pixGetDepth(pixs) != 32) return ERROR_INT("pixs not defined", procName, 1); if (sigbits < 2 || sigbits > 6) return ERROR_INT("sigbits not in [2 ... 6]", procName, 1); if (factor < 1 || ncolors < 1) return ERROR_INT("factor < 1 or ncolors < 1", procName, 1); if ((nahisto = pixGetRGBHistogram(pixs, sigbits, factor)) == NULL) return ERROR_INT("nahisto not made", procName, 1); /* naindex contains the index into nahisto, which is the rgbindex */ naindex = numaSortIndexAutoSelect(nahisto, L_SORT_DECREASING); numaDestroy(&nahisto); if (!naindex) return ERROR_INT("naindex not made", procName, 1); n = numaGetCount(naindex); ncolors = L_MIN(n, ncolors); if (parray) *parray = (l_uint32 *)LEPT_CALLOC(ncolors, sizeof(l_uint32)); if (pcmap) *pcmap = pixcmapCreate(8); for (i = 0; i < ncolors; i++) { numaGetIValue(naindex, i, &rgbindex); /* rgb index */ getRGBFromIndex(rgbindex, sigbits, &rval, &gval, &bval); if (parray) composeRGBPixel(rval, gval, bval, *parray + i); if (pcmap) pixcmapAddColor(*pcmap, rval, gval, bval); } numaDestroy(&naindex); return 0; } /*! * \brief pixSimpleColorQuantize() * \param[in] pixs 32 bpp rgb * \param[in] sigbits 2-4, significant bits retained in the quantizer * for each component of the input image * \param[in] factor subsampling factor; use 1 for no subsampling * \param[in] ncolors the number of most populated colors to select * \return pixd 8 bpp cmapped or NULL on error * * <pre> * Notes: * (1) If you want to do color quantization for real, use octcube * or modified median cut. This function shows that it is * easy to make a simple quantizer based solely on the population * in cells of a given size in rgb color space. * (2) The %ncolors most populated cells at the %sigbits level form * the colormap for quantizing, and this uses octcube indexing * under the covers to assign each pixel to the nearest color. * (3) %sigbits is restricted to 2, 3 and 4. At the low end, the * color discrimination is very crude; at the upper end, a set of * similar colors can dominate the result. Interesting results * are generally found for %sigbits = 3 and ncolors ~ 20. * (4) See also pixColorSegment() for a method of quantizing the * colors to generate regions of similar color. * </pre> */ PIX * pixSimpleColorQuantize(PIX *pixs, l_int32 sigbits, l_int32 factor, l_int32 ncolors) { l_int32 w, h; PIX *pixd; PIXCMAP *cmap; PROCNAME("pixSimpleColorQuantize"); if (!pixs || pixGetDepth(pixs) != 32) return (PIX *)ERROR_PTR("pixs not defined", procName, NULL); if (sigbits < 2 || sigbits > 4) return (PIX *)ERROR_PTR("sigbits not in {2,3,4}", procName, NULL); pixGetMostPopulatedColors(pixs, sigbits, factor, ncolors, NULL, &cmap); pixGetDimensions(pixs, &w, &h, NULL); pixd = pixCreate(w, h, 8); pixSetColormap(pixd, cmap); pixAssignToNearestColor(pixd, pixs, NULL, 4, NULL); return pixd; } /* ----------------------------------------------------------------------- * * Constructs a color histogram based on rgb indices * * ----------------------------------------------------------------------- */ /*! * \brief pixGetRGBHistogram() * \param[in] pixs 32 bpp rgb * \param[in] sigbits 2-6, significant bits retained in the quantizer * for each component of the input image * \param[in] factor subsampling factor; use 1 for no subsampling * \return numa histogram of colors, indexed by RGB * components, or NULL on error * * <pre> * Notes: * (1) This uses a simple, fast method of indexing into an rgb image. * (2) The output is a 1D histogram of count vs. rgb-index, which * uses red sigbits as the most significant and blue as the least. * (3) This function produces the same result as pixMedianCutHisto(). * </pre> */ NUMA * pixGetRGBHistogram(PIX *pixs, l_int32 sigbits, l_int32 factor) { l_int32 w, h, i, j, size, wpl, rval, gval, bval, npts; l_uint32 val32, rgbindex; l_float32 *array; l_uint32 *data, *line, *rtab, *gtab, *btab; NUMA *na; PROCNAME("pixGetRGBHistogram"); if (!pixs || pixGetDepth(pixs) != 32) return (NUMA *)ERROR_PTR("pixs not defined", procName, NULL); if (sigbits < 2 || sigbits > 6) return (NUMA *)ERROR_PTR("sigbits not in [2 ... 6]", procName, NULL); if (factor < 1) return (NUMA *)ERROR_PTR("factor < 1", procName, NULL); /* Get histogram size: 2^(3 * sigbits) */ size = 1 << (3 * sigbits); /* 64, 512, 4096, 32768, 262144 */ na = numaMakeConstant(0, size); /* init to all 0 */ array = numaGetFArray(na, L_NOCOPY); makeRGBIndexTables(&rtab, &gtab, &btab, sigbits); /* Check the number of sampled pixels */ pixGetDimensions(pixs, &w, &h, NULL); npts = ((w + factor - 1) / factor) * ((h + factor - 1) / factor); if (npts < 1000) L_WARNING("only sampling %d pixels\n", procName, npts); wpl = pixGetWpl(pixs); data = pixGetData(pixs); for (i = 0; i < h; i += factor) { line = data + i * wpl; for (j = 0; j < w; j += factor) { val32 = *(line + j); extractRGBValues(val32, &rval, &gval, &bval); rgbindex = rtab[rval] | gtab[gval] | btab[bval]; array[rgbindex]++; } } LEPT_FREE(rtab); LEPT_FREE(gtab); LEPT_FREE(btab); return na; } /*! * \brief makeRGBIndexTables() * * \param[out] prtab, pgtab, pbtab 256-entry index tables * \param[in] sigbits 2-6, significant bits retained in the quantizer * for each component of the input image * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) These tables are used to map from rgb sample values to * an rgb index, using * rgbindex = rtab[rval] | gtab[gval] | btab[bval] * where, e.g., if sigbits = 3, the index is a 9 bit integer: * r7 r6 r5 g7 g6 g5 b7 b6 b5 * </pre> */ l_int32 makeRGBIndexTables(l_uint32 **prtab, l_uint32 **pgtab, l_uint32 **pbtab, l_int32 sigbits) { l_int32 i; l_uint32 *rtab, *gtab, *btab; PROCNAME("makeRGBIndexTables"); if (prtab) *prtab = NULL; if (pgtab) *pgtab = NULL; if (pbtab) *pbtab = NULL; if (!prtab || !pgtab || !pbtab) return ERROR_INT("not all table ptrs defined", procName, 1); if (sigbits < 2 || sigbits > 6) return ERROR_INT("sigbits not in [2 ... 6]", procName, 1); rtab = (l_uint32 *)LEPT_CALLOC(256, sizeof(l_uint32)); gtab = (l_uint32 *)LEPT_CALLOC(256, sizeof(l_uint32)); btab = (l_uint32 *)LEPT_CALLOC(256, sizeof(l_uint32)); *prtab = rtab; *pgtab = gtab; *pbtab = btab; switch (sigbits) { case 2: for (i = 0; i < 256; i++) { rtab[i] = (i & 0xc0) >> 2; gtab[i] = (i & 0xc0) >> 4; btab[i] = (i & 0xc0) >> 6; } break; case 3: for (i = 0; i < 256; i++) { rtab[i] = (i & 0xe0) << 1; gtab[i] = (i & 0xe0) >> 2; btab[i] = (i & 0xe0) >> 5; } break; case 4: for (i = 0; i < 256; i++) { rtab[i] = (i & 0xf0) << 4; gtab[i] = (i & 0xf0); btab[i] = (i & 0xf0) >> 4; } break; case 5: for (i = 0; i < 256; i++) { rtab[i] = (i & 0xf8) << 7; gtab[i] = (i & 0xf8) << 2; btab[i] = (i & 0xf8) >> 3; } break; case 6: for (i = 0; i < 256; i++) { rtab[i] = (i & 0xfc) << 10; gtab[i] = (i & 0xfc) << 4; btab[i] = (i & 0xfc) >> 2; } break; default: L_ERROR("Illegal sigbits = %d\n", procName, sigbits); return ERROR_INT("sigbits not in [2 ... 6]", procName, 1); } return 0; } /*! * \brief getRGBFromIndex() * * \param[in] index rgbindex * \param[in] sigbits 2-6, significant bits retained in the quantizer * for each component of the input image * \param[out] prval, pgval, pbval rgb values * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) The %index is expressed in bits, based on the the * %sigbits of the r, g and b components, as * r7 r6 ... g7 g6 ... b7 b6 ... * (2) The computed rgb values are in the center of the quantized cube. * The extra bit that is OR'd accomplishes this. * </pre> */ l_int32 getRGBFromIndex(l_uint32 index, l_int32 sigbits, l_int32 *prval, l_int32 *pgval, l_int32 *pbval) { PROCNAME("getRGBFromIndex"); if (prval) *prval = 0; if (pgval) *pgval = 0; if (pbval) *pbval = 0; if (!prval || !pgval || !pbval) return ERROR_INT("not all component ptrs defined", procName, 1); if (sigbits < 2 || sigbits > 6) return ERROR_INT("sigbits not in [2 ... 6]", procName, 1); switch (sigbits) { case 2: *prval = ((index << 2) & 0xc0) | 0x20; *pgval = ((index << 4) & 0xc0) | 0x20; *pbval = ((index << 6) & 0xc0) | 0x20; break; case 3: *prval = ((index >> 1) & 0xe0) | 0x10; *pgval = ((index << 2) & 0xe0) | 0x10; *pbval = ((index << 5) & 0xe0) | 0x10; break; case 4: *prval = ((index >> 4) & 0xf0) | 0x08; *pgval = (index & 0xf0) | 0x08; *pbval = ((index << 4) & 0xf0) | 0x08; break; case 5: *prval = ((index >> 7) & 0xf8) | 0x04; *pgval = ((index >> 2) & 0xf8) | 0x04; *pbval = ((index << 3) & 0xf8) | 0x04; break; case 6: *prval = ((index >> 10) & 0xfc) | 0x02; *pgval = ((index >> 4) & 0xfc) | 0x02; *pbval = ((index << 2) & 0xfc) | 0x02; break; default: L_ERROR("Illegal sigbits = %d\n", procName, sigbits); return ERROR_INT("sigbits not in [2 ... 6]", procName, 1); } return 0; } /* ----------------------------------------------------------------------- * * Identify images that have highlight (red) color * * ----------------------------------------------------------------------- */ /*! * \brief pixHasHighlightRed() * * \param[in] pixs 32 bpp rgb * \param[in] factor subsampling; an integer >= 1; use 1 for all pixels * \param[in] fract threshold fraction of all image pixels * \param[in] fthresh threshold on a function of the components; typ. ~2.5 * \param[out] phasred 1 if red pixels are above threshold * \param[out] pratio [optional] normalized fraction of threshold * red pixels that is actually observed * \param[out] ppixdb [optional] seed pixel mask * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) Pixels are identified as red if they satisfy two conditions: * (a) The components satisfy (R-B)/B \> %fthresh (red or dark fg) * (b) The red component satisfied R \> 128 (red or light bg) * Masks are generated for (a) and (b), and the intersection * gives the pixels that are red but not either light bg or * dark fg. * (2) A typical value for fract = 0.0001, which gives sensitivity * to an image where a small fraction of the pixels are printed * in red. * (3) A typical value for fthresh = 2.5. Higher values give less * sensitivity to red, and fewer false positives. * </pre> */ l_int32 pixHasHighlightRed(PIX *pixs, l_int32 factor, l_float32 fract, l_float32 fthresh, l_int32 *phasred, l_float32 *pratio, PIX **ppixdb) { l_int32 w, h, count; l_float32 ratio; PIX *pix1, *pix2, *pix3, *pix4; FPIX *fpix; PROCNAME("pixHasHighlightRed"); if (pratio) *pratio = 0.0; if (ppixdb) *ppixdb = NULL; if (phasred) *phasred = 0; if (!pratio && !ppixdb) return ERROR_INT("no return val requested", procName, 1); if (!phasred) return ERROR_INT("&hasred not defined", procName, 1); if (!pixs || pixGetDepth(pixs) != 32) return ERROR_INT("pixs not defined or not 32 bpp", procName, 1); if (fthresh < 1.5 || fthresh > 3.5) L_WARNING("fthresh = %f is out of normal bounds\n", procName, fthresh); if (factor > 1) pix1 = pixScaleByIntSampling(pixs, factor); else pix1 = pixClone(pixs); /* Identify pixels that are either red or dark foreground */ fpix = pixComponentFunction(pix1, 1.0, 0.0, -1.0, 0.0, 0.0, 1.0); pix2 = fpixThresholdToPix(fpix, fthresh); pixInvert(pix2, pix2); /* Identify pixels that are either red or light background */ pix3 = pixGetRGBComponent(pix1, COLOR_RED); pix4 = pixThresholdToBinary(pix3, 130); pixInvert(pix4, pix4); pixAnd(pix4, pix4, pix2); pixCountPixels(pix4, &count, NULL); pixGetDimensions(pix4, &w, &h, NULL); L_INFO("count = %d, thresh = %d\n", procName, count, (l_int32)(fract * w * h)); ratio = (l_float32)count / (fract * w * h); if (pratio) *pratio = ratio; if (ratio >= 1.0) *phasred = 1; if (ppixdb) *ppixdb = pix4; else pixDestroy(&pix4); pixDestroy(&pix1); pixDestroy(&pix2); pixDestroy(&pix3); fpixDestroy(&fpix); return 0; }
847d57649e8e7b78a31ab4888fc02c3d61b003ef
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/include/linux/in6.h
34edf1f6c9a3c42acf94e6055952eb3c3ad66ad6
[ "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
1,893
h
in6.h
/* * Types and definitions for AF_INET6 * Linux INET6 implementation * * Authors: * Pedro Roque <roque@di.fc.ul.pt> * * Sources: * IPv6 Program Interfaces for BSD Systems * <draft-ietf-ipngwg-bsd-api-05.txt> * * Advanced Sockets API for IPv6 * <draft-stevens-advanced-api-00.txt> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IN6_H #define _LINUX_IN6_H #include <uapi/linux/in6.h> /* IPv6 Wildcard Address (::) and Loopback Address (::1) defined in RFC2553 * NOTE: Be aware the IN6ADDR_* constants and in6addr_* externals are defined * in network byte order, not in host byte order as are the IPv4 equivalents */ extern const struct in6_addr in6addr_any; #define IN6ADDR_ANY_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } } extern const struct in6_addr in6addr_loopback; #define IN6ADDR_LOOPBACK_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } } extern const struct in6_addr in6addr_linklocal_allnodes; #define IN6ADDR_LINKLOCAL_ALLNODES_INIT \ { { { 0xff,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } } extern const struct in6_addr in6addr_linklocal_allrouters; #define IN6ADDR_LINKLOCAL_ALLROUTERS_INIT \ { { { 0xff,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2 } } } extern const struct in6_addr in6addr_interfacelocal_allnodes; #define IN6ADDR_INTERFACELOCAL_ALLNODES_INIT \ { { { 0xff,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } } extern const struct in6_addr in6addr_interfacelocal_allrouters; #define IN6ADDR_INTERFACELOCAL_ALLROUTERS_INIT \ { { { 0xff,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2 } } } extern const struct in6_addr in6addr_sitelocal_allrouters; #define IN6ADDR_SITELOCAL_ALLROUTERS_INIT \ { { { 0xff,5,0,0,0,0,0,0,0,0,0,0,0,0,0,2 } } } #endif
9ae0e545927054d00496b9fb8c0ea7f900886d90
ec34c10de6b7cde45b12fa40e036120633069996
/cameras/ShoestringLXUSB_DLL.h
ff5b401db0e2a759478f0c59fc66ecdf5767f5c0
[ "BSD-3-Clause" ]
permissive
OpenPHDGuiding/phd2
7640bba3e9a20501ac99d0504fecc5be73d53633
9ff645f1fd5861722497221ecc4d000136b66e28
refs/heads/master
2023-09-01T18:13:37.555796
2023-08-27T23:53:18
2023-08-27T23:53:18
38,025,807
239
115
BSD-3-Clause
2023-09-11T02:33:21
2015-06-25T03:31:41
C++
UTF-8
C
false
false
4,274
h
ShoestringLXUSB_DLL.h
// ShoestringLXUSB_DLL.h // Copyright 2005 Shoestring Astronomy // www.ShoestringAstronomy.com // These are possible return values for the shutter status in LXUSB_Frame1Status and LXUSB_Status // They are also the possible input values for the frame1 parameter of LXUSB_SetAll const int LXUSB_FRAME1_ASSERTED = 2; const int LXUSB_FRAME1_DEASSERTED = 1; // These are possible return values for the shutter status in LXUSB_Frame2Status and LXUSB_Status // They are also the possible input values for the frame2 parameter of LXUSB_SetAll const int LXUSB_FRAME2_ASSERTED = 2; const int LXUSB_FRAME2_DEASSERTED = 1; // These are possible return values for the shutter status in LXUSB_ShutterStatus and LXUSB_Status // They are also the possible input values for the shutter parameter of LXUSB_SetAll const int LXUSB_SHUTTER_ASSERTED = 2; const int LXUSB_SHUTTER_DEASSERTED = 1; // These are possible return values for the shutter status in LXUSB_CCDAmpStatus and LXUSB_Status // They are also the possible input values for the ccdamp parameter of LXUSB_SetAll const int LXUSB_CCDAMP_ASSERTED = 2; const int LXUSB_CCDAMP_DEASSERTED = 1; // These are possible return values for the LED status in LXUSB_LEDStatus and LXUSB_Status // They are also the possible input values for the led parameter of LXUSB_SetAll const int LXUSB_LED_ON_RED = 4; const int LXUSB_LED_ON_GREEN = 3; const int LXUSB_LED_OFF_RED = 2; const int LXUSB_LED_OFF_GREEN = 1; __declspec(dllimport) bool __stdcall LXUSB_Open( void ); // Opens the LXUSB and prepares it for use __declspec(dllimport) void __stdcall LXUSB_Close( void ); // Closes the LXUSB after use is complete __declspec(dllimport) bool __stdcall LXUSB_Reset( void ); // Resets the state of the LXUSB to its power-up default __declspec(dllimport) bool __stdcall LXUSB_Frame1Assert( void ); // Asserts the Frame 1 Transfer signal __declspec(dllimport) bool __stdcall LXUSB_Frame1Deassert( void ); // Deasserts the Frame 1 Transfer signal __declspec(dllimport) bool __stdcall LXUSB_Frame2Assert( void ); // Asserts the Frame 2 Transfer signal __declspec(dllimport) bool __stdcall LXUSB_Frame2Deassert( void ); // Deasserts the Frame 2 Transfer signal __declspec(dllimport) bool __stdcall LXUSB_ShutterAssert( void ); // Asserts the Shutter signal __declspec(dllimport) bool __stdcall LXUSB_ShutterDeassert( void ); // Deasserts the Shutter signal __declspec(dllimport) bool __stdcall LXUSB_CCDAmpAssert( void ); // Asserts the CCDAmp signal __declspec(dllimport) bool __stdcall LXUSB_CCDAmpDeassert( void ); // Deasserts the CCDAmp signal __declspec(dllimport) bool __stdcall LXUSB_AllControlDeassert( void ); // Deasserts all four control signals __declspec(dllimport) bool __stdcall LXUSB_LEDOn( void ); // Turns the front panel LED on __declspec(dllimport) bool __stdcall LXUSB_LEDOff( void ); // Turns the front panel LED off __declspec(dllimport) bool __stdcall LXUSB_LEDRed( void ); // Sets the current LED color to red __declspec(dllimport) bool __stdcall LXUSB_LEDGreen( void ); // Sets the current LED color to green __declspec(dllimport) bool __stdcall LXUSB_SetAll(int frame1, int frame2, int shutter, int ccdamp, int led); // Allows Frame 1 Transfer, Frame 2 Transfer, Shutter, CCDAmp, and LED states to all be set simulataneously __declspec(dllimport) bool __stdcall LXUSB_Frame1Status(int *status); // Checks the status of the Frame 1 Transfer signal __declspec(dllimport) bool __stdcall LXUSB_Frame2Status(int *status); // Checks the status of the Frame 2 Transfer signal __declspec(dllimport) bool __stdcall LXUSB_ShutterStatus(int *status); // Checks the status of the Shutter signal __declspec(dllimport) bool __stdcall LXUSB_CCDAmpStatus(int *status); // Checks the status of the CCDAmp signal __declspec(dllimport) bool __stdcall LXUSB_LEDStatus(int *status); // Checks the status of the front panel LED __declspec(dllimport) bool __stdcall LXUSB_Status(int *frame1_status, int *frame2_status, int *shutter_status, int *ccdamp_status, int *led_status ); // Checks the status of Frame 1 Transfer, Frame 2 Transfer, Shutter, CCDAmp, and LED simulataneously
73ef29f755670d667ea71b4efa68720a47f3a465
eed5357a3992cc351c09eca34b211d224cc0ad05
/src/main.c
84b6ae12a962d28f01fa19f5833d36264aeee35a
[]
no_license
pjreddie/uwimg
830c0758b1be28231b87db784c215ec23fd2f7b7
8511a7f95192267ca0404d2c7c794c2ed90e8e0a
refs/heads/main
2023-03-21T04:13:09.616898
2023-02-22T21:52:49
2023-02-22T21:52:49
212,867,363
250
82
null
2020-05-01T12:39:51
2019-10-04T17:20:28
C
UTF-8
C
false
false
594
c
main.c
#include <math.h> #include <string.h> #include "image.h" #include "test.h" #include "args.h" int main(int argc, char **argv) { if(argc < 3){ printf("usage: %s test <hw0 | hw1...>\n", argv[0]); } else if (0 == strcmp(argv[1], "test")){ if (0 == strcmp(argv[2], "hw0")) test_hw0(); if (0 == strcmp(argv[2], "hw1")) test_hw1(); if (0 == strcmp(argv[2], "hw2")) test_hw2(); if (0 == strcmp(argv[2], "hw3")) test_hw3(); if (0 == strcmp(argv[2], "hw4")) test_hw4(); if (0 == strcmp(argv[2], "hw5")) test_hw5(); } return 0; }
b3fdf195371f0b70ad1dae7e8330c17487361035
b39c7f759fa9ff31ca0eb561379cba859329060c
/lib/fec.h
a793ed3351536a95b7c35edf568a4f22c8653fe3
[ "MIT" ]
permissive
wangyu-/UDPspeeder
c15d10225623cba6e9681e30720961db5fa2c025
17694ecaa9681b04498709ba7526c8a8f022b512
refs/heads/branch_libev
2023-07-31T13:16:48.856709
2023-07-22T22:16:33
2023-07-22T22:16:33
99,672,281
4,785
929
MIT
2023-06-29T15:53:38
2017-08-08T08:57:18
C++
UTF-8
C
false
false
2,338
h
fec.h
/* * fec.c -- forward error correction based on Vandermonde matrices * 980614 * (C) 1997-98 Luigi Rizzo (luigi@iet.unipi.it) * * Portions derived from code by Phil Karn (karn@ka9q.ampr.org), * Robert Morelos-Zaragoza (robert@spectra.eng.hawaii.edu) and Hari * Thirumoorthy (harit@spectra.eng.hawaii.edu), Aug 1995 * * 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 AUTHORS ``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 AUTHORS * 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 following parameter defines how many bits are used for * field elements. The code supports any value from 2 to 16 * but fastest operation is achieved with 8 bit elements * This is the only parameter you may want to change. */ #ifndef GF_BITS #define GF_BITS 8 /* code over GF(2**GF_BITS) - change to suit */ #endif #define GF_SIZE ((1 << GF_BITS) - 1) /* powers of \alpha */ void fec_free(void *p) ; void * fec_new(int k, int n) ;//n>=k void init_fec() ; //if you never called this,it will be automatically called in fec_new() void fec_encode(void *code, void *src[], void *dst, int index, int sz) ; int fec_decode(void *code, void *pkt[], int index[], int sz) ; int get_k(void *code); int get_n(void *code); /* end of file */
0119030dc5d8bfe1f9df62df3eb774e316ca8a9c
31f5cddb9885fc03b5c05fba5f9727b2f775cf47
/thirdparty/google/tensorflow/lite/c/c_test.c
2e9ca30ee43f8c08c74030700f248d46af3084df
[ "MIT" ]
permissive
timi-liuliang/echo
2935a34b80b598eeb2c2039d686a15d42907d6f7
d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24
refs/heads/master
2023-08-17T05:35:08.104918
2023-08-11T18:10:35
2023-08-11T18:10:35
124,620,874
822
102
MIT
2021-06-11T14:29:03
2018-03-10T04:07:35
C++
UTF-8
C
false
false
5,176
c
c_test.c
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/c/c_api.h" #include "tensorflow/lite/c/c_api_experimental.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/c/builtin_op_data.h" // This file exists just to verify that the above header files above can build, // link, and run as "C" code. #ifdef __cplusplus #error "This file should be compiled as C code, not as C++." #endif #include <stdio.h> #include <stdlib.h> #include <string.h> static void CheckFailed(const char *expression, const char *filename, int line_number) { fprintf(stderr, "ERROR: CHECK failed: %s:%d: %s\n", filename, line_number, expression); fflush(stderr); abort(); } // We use an extra level of macro indirection here to ensure that the // macro arguments get evaluated, so that in a call to CHECK(foo), // the call to STRINGIZE(condition) in the definition of the CHECK // macro results in the string "foo" rather than the string "condition". #define STRINGIZE(expression) STRINGIZE2(expression) #define STRINGIZE2(expression) #expression // Like assert(), but not dependent on NDEBUG. #define CHECK(condition) \ ((condition) ? (void)0 \ : CheckFailed(STRINGIZE(condition), __FILE__, __LINE__)) #define ASSERT_EQ(expected, actual) CHECK((expected) == (actual)) #define ASSERT_NE(expected, actual) CHECK((expected) != (actual)) #define ASSERT_STREQ(expected, actual) \ ASSERT_EQ(0, strcmp((expected), (actual))) // Test the TfLiteVersion function. static void TestVersion(void) { const char *version = TfLiteVersion(); printf("Version = %s\n", version); CHECK(version[0] != '\0'); } static void TestSmokeTest(void) { TfLiteModel* model = TfLiteModelCreateFromFile("tensorflow/lite/testdata/add.bin"); ASSERT_NE(model, NULL); TfLiteInterpreterOptions* options = TfLiteInterpreterOptionsCreate(); ASSERT_NE(options, NULL); TfLiteInterpreterOptionsSetNumThreads(options, 2); TfLiteInterpreter* interpreter = TfLiteInterpreterCreate(model, options); ASSERT_NE(interpreter, NULL); // The options/model can be deleted immediately after interpreter creation. TfLiteInterpreterOptionsDelete(options); TfLiteModelDelete(model); ASSERT_EQ(TfLiteInterpreterAllocateTensors(interpreter), kTfLiteOk); ASSERT_EQ(TfLiteInterpreterGetInputTensorCount(interpreter), 1); ASSERT_EQ(TfLiteInterpreterGetOutputTensorCount(interpreter), 1); int input_dims[1] = {2}; ASSERT_EQ(TfLiteInterpreterResizeInputTensor( interpreter, 0, input_dims, 1), kTfLiteOk); ASSERT_EQ(TfLiteInterpreterAllocateTensors(interpreter), kTfLiteOk); TfLiteTensor* input_tensor = TfLiteInterpreterGetInputTensor(interpreter, 0); ASSERT_NE(input_tensor, NULL); ASSERT_EQ(TfLiteTensorType(input_tensor), kTfLiteFloat32); ASSERT_EQ(TfLiteTensorNumDims(input_tensor), 1); ASSERT_EQ(TfLiteTensorDim(input_tensor, 0), 2); ASSERT_EQ(TfLiteTensorByteSize(input_tensor), sizeof(float) * 2); ASSERT_NE(TfLiteTensorData(input_tensor), NULL); ASSERT_STREQ(TfLiteTensorName(input_tensor), "input"); TfLiteQuantizationParams input_params = TfLiteTensorQuantizationParams(input_tensor); ASSERT_EQ(input_params.scale, 0.f); ASSERT_EQ(input_params.zero_point, 0); float input[2] = {1.f, 3.f}; ASSERT_EQ(TfLiteTensorCopyFromBuffer(input_tensor, input, 2 * sizeof(float)), kTfLiteOk); ASSERT_EQ(TfLiteInterpreterInvoke(interpreter), kTfLiteOk); const TfLiteTensor* output_tensor = TfLiteInterpreterGetOutputTensor(interpreter, 0); ASSERT_NE(output_tensor, NULL); ASSERT_EQ(TfLiteTensorType(output_tensor), kTfLiteFloat32); ASSERT_EQ(TfLiteTensorNumDims(output_tensor), 1); ASSERT_EQ(TfLiteTensorDim(output_tensor, 0), 2); ASSERT_EQ(TfLiteTensorByteSize(output_tensor), sizeof(float) * 2); ASSERT_NE(TfLiteTensorData(output_tensor), NULL); ASSERT_STREQ(TfLiteTensorName(output_tensor), "output"); TfLiteQuantizationParams output_params = TfLiteTensorQuantizationParams(output_tensor); ASSERT_EQ(output_params.scale, 0.f); ASSERT_EQ(output_params.zero_point, 0); float output[2]; ASSERT_EQ(TfLiteTensorCopyToBuffer(output_tensor, output, 2 * sizeof(float)), kTfLiteOk); ASSERT_EQ(output[0], 3.f); ASSERT_EQ(output[1], 9.f); TfLiteInterpreterDelete(interpreter); } static void RunTests(void) { TestVersion(); TestSmokeTest(); } int main(void) { RunTests(); return 0; }
649f56263bb48e7c01bf5f67bb95c633aea7f24c
2dfc2beac0ad497f8fc59201921097a412f0df7f
/trunk/3rdparty/openssl-1.1-fit/crypto/evp/evp_enc.c
e3c165d48e082dc4c46f72fd1296de0494720040
[ "OpenSSL", "JSON", "Apache-2.0", "LicenseRef-scancode-mulanpsl-2.0-en", "MIT", "MulanPSL-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ossrs/srs
cf9442478fedcd32ef2817f8d53f405a6fa2c7d1
7138edd318d30b545e73e80500adda771817f8d1
refs/heads/develop
2023-09-01T03:38:35.057515
2023-08-31T01:45:25
2023-08-31T01:49:36
34,777,562
23,557
5,046
MIT
2023-09-09T00:57:42
2015-04-29T06:59:32
C++
UTF-8
C
false
false
21,428
c
evp_enc.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <limits.h> #include <assert.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/rand_drbg.h> #include <openssl/engine.h> #include "crypto/evp.h" #include "evp_local.h" int EVP_CIPHER_CTX_reset(EVP_CIPHER_CTX *c) { if (c == NULL) return 1; if (c->cipher != NULL) { if (c->cipher->cleanup && !c->cipher->cleanup(c)) return 0; /* Cleanse cipher context data */ if (c->cipher_data && c->cipher->ctx_size) OPENSSL_cleanse(c->cipher_data, c->cipher->ctx_size); } OPENSSL_free(c->cipher_data); #ifndef OPENSSL_NO_ENGINE ENGINE_finish(c->engine); #endif memset(c, 0, sizeof(*c)); return 1; } EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void) { return OPENSSL_zalloc(sizeof(EVP_CIPHER_CTX)); } void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx) { EVP_CIPHER_CTX_reset(ctx); OPENSSL_free(ctx); } int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const unsigned char *key, const unsigned char *iv, int enc) { if (cipher != NULL) EVP_CIPHER_CTX_reset(ctx); return EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, enc); } int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl, const unsigned char *key, const unsigned char *iv, int enc) { if (enc == -1) enc = ctx->encrypt; else { if (enc) enc = 1; ctx->encrypt = enc; } #ifndef OPENSSL_NO_ENGINE /* * Whether it's nice or not, "Inits" can be used on "Final"'d contexts so * this context may already have an ENGINE! Try to avoid releasing the * previous handle, re-querying for an ENGINE, and having a * reinitialisation, when it may all be unnecessary. */ if (ctx->engine && ctx->cipher && (cipher == NULL || cipher->nid == ctx->cipher->nid)) goto skip_to_init; #endif if (cipher) { /* * Ensure a context left lying around from last time is cleared (the * previous check attempted to avoid this if the same ENGINE and * EVP_CIPHER could be used). */ if (ctx->cipher) { unsigned long flags = ctx->flags; EVP_CIPHER_CTX_reset(ctx); /* Restore encrypt and flags */ ctx->encrypt = enc; ctx->flags = flags; } #ifndef OPENSSL_NO_ENGINE if (impl) { if (!ENGINE_init(impl)) { EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR); return 0; } } else /* Ask if an ENGINE is reserved for this job */ impl = ENGINE_get_cipher_engine(cipher->nid); if (impl) { /* There's an ENGINE for this job ... (apparently) */ const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid); if (!c) { /* * One positive side-effect of US's export control history, * is that we should at least be able to avoid using US * misspellings of "initialisation"? */ EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR); return 0; } /* We'll use the ENGINE's private cipher definition */ cipher = c; /* * Store the ENGINE functional reference so we know 'cipher' came * from an ENGINE and we need to release it when done. */ ctx->engine = impl; } else ctx->engine = NULL; #endif ctx->cipher = cipher; if (ctx->cipher->ctx_size) { ctx->cipher_data = OPENSSL_zalloc(ctx->cipher->ctx_size); if (ctx->cipher_data == NULL) { ctx->cipher = NULL; EVPerr(EVP_F_EVP_CIPHERINIT_EX, ERR_R_MALLOC_FAILURE); return 0; } } else { ctx->cipher_data = NULL; } ctx->key_len = cipher->key_len; /* Preserve wrap enable flag, zero everything else */ ctx->flags &= EVP_CIPHER_CTX_FLAG_WRAP_ALLOW; if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) { if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) { ctx->cipher = NULL; EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR); return 0; } } } else if (!ctx->cipher) { EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_NO_CIPHER_SET); return 0; } #ifndef OPENSSL_NO_ENGINE skip_to_init: #endif /* we assume block size is a power of 2 in *cryptUpdate */ OPENSSL_assert(ctx->cipher->block_size == 1 || ctx->cipher->block_size == 8 || ctx->cipher->block_size == 16); if (!(ctx->flags & EVP_CIPHER_CTX_FLAG_WRAP_ALLOW) && EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_WRAP_MODE) { EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_WRAP_MODE_NOT_ALLOWED); return 0; } if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_CUSTOM_IV)) { switch (EVP_CIPHER_CTX_mode(ctx)) { case EVP_CIPH_STREAM_CIPHER: case EVP_CIPH_ECB_MODE: break; case EVP_CIPH_CFB_MODE: case EVP_CIPH_OFB_MODE: ctx->num = 0; /* fall-through */ case EVP_CIPH_CBC_MODE: OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) <= (int)sizeof(ctx->iv)); if (iv) memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx)); memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx)); break; case EVP_CIPH_CTR_MODE: ctx->num = 0; /* Don't reuse IV for CTR mode */ if (iv) memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx)); break; default: return 0; } } if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) { if (!ctx->cipher->init(ctx, key, iv, enc)) return 0; } ctx->buf_len = 0; ctx->final_used = 0; ctx->block_mask = ctx->cipher->block_size - 1; return 1; } int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { if (ctx->encrypt) return EVP_EncryptUpdate(ctx, out, outl, in, inl); else return EVP_DecryptUpdate(ctx, out, outl, in, inl); } int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { if (ctx->encrypt) return EVP_EncryptFinal_ex(ctx, out, outl); else return EVP_DecryptFinal_ex(ctx, out, outl); } int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { if (ctx->encrypt) return EVP_EncryptFinal(ctx, out, outl); else return EVP_DecryptFinal(ctx, out, outl); } int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const unsigned char *key, const unsigned char *iv) { return EVP_CipherInit(ctx, cipher, key, iv, 1); } int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl, const unsigned char *key, const unsigned char *iv) { return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1); } int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const unsigned char *key, const unsigned char *iv) { return EVP_CipherInit(ctx, cipher, key, iv, 0); } int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl, const unsigned char *key, const unsigned char *iv) { return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0); } /* * According to the letter of standard difference between pointers * is specified to be valid only within same object. This makes * it formally challenging to determine if input and output buffers * are not partially overlapping with standard pointer arithmetic. */ #ifdef PTRDIFF_T # undef PTRDIFF_T #endif #if defined(OPENSSL_SYS_VMS) && __INITIAL_POINTER_SIZE==64 /* * Then we have VMS that distinguishes itself by adhering to * sizeof(size_t)==4 even in 64-bit builds, which means that * difference between two pointers might be truncated to 32 bits. * In the context one can even wonder how comparison for * equality is implemented. To be on the safe side we adhere to * PTRDIFF_T even for comparison for equality. */ # define PTRDIFF_T uint64_t #else # define PTRDIFF_T size_t #endif int is_partially_overlapping(const void *ptr1, const void *ptr2, int len) { PTRDIFF_T diff = (PTRDIFF_T)ptr1-(PTRDIFF_T)ptr2; /* * Check for partially overlapping buffers. [Binary logical * operations are used instead of boolean to minimize number * of conditional branches.] */ int overlapped = (len > 0) & (diff != 0) & ((diff < (PTRDIFF_T)len) | (diff > (0 - (PTRDIFF_T)len))); return overlapped; } static int evp_EncryptDecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int i, j, bl, cmpl = inl; if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS)) cmpl = (cmpl + 7) / 8; bl = ctx->cipher->block_size; /* * CCM mode needs to know about the case where inl == 0 && in == NULL - it * means the plaintext/ciphertext length is 0 */ if (inl < 0 || (inl == 0 && EVP_CIPHER_mode(ctx->cipher) != EVP_CIPH_CCM_MODE)) { *outl = 0; return inl == 0; } if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { /* If block size > 1 then the cipher will have to do this check */ if (bl == 1 && is_partially_overlapping(out, in, cmpl)) { EVPerr(EVP_F_EVP_ENCRYPTDECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING); return 0; } i = ctx->cipher->do_cipher(ctx, out, in, inl); if (i < 0) return 0; else *outl = i; return 1; } if (is_partially_overlapping(out + ctx->buf_len, in, cmpl)) { EVPerr(EVP_F_EVP_ENCRYPTDECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING); return 0; } if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) { if (ctx->cipher->do_cipher(ctx, out, in, inl)) { *outl = inl; return 1; } else { *outl = 0; return 0; } } i = ctx->buf_len; OPENSSL_assert(bl <= (int)sizeof(ctx->buf)); if (i != 0) { if (bl - i > inl) { memcpy(&(ctx->buf[i]), in, inl); ctx->buf_len += inl; *outl = 0; return 1; } else { j = bl - i; /* * Once we've processed the first j bytes from in, the amount of * data left that is a multiple of the block length is: * (inl - j) & ~(bl - 1) * We must ensure that this amount of data, plus the one block that * we process from ctx->buf does not exceed INT_MAX */ if (((inl - j) & ~(bl - 1)) > INT_MAX - bl) { EVPerr(EVP_F_EVP_ENCRYPTDECRYPTUPDATE, EVP_R_OUTPUT_WOULD_OVERFLOW); return 0; } memcpy(&(ctx->buf[i]), in, j); inl -= j; in += j; if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl)) return 0; out += bl; *outl = bl; } } else *outl = 0; i = inl & (bl - 1); inl -= i; if (inl > 0) { if (!ctx->cipher->do_cipher(ctx, out, in, inl)) return 0; *outl += inl; } if (i != 0) memcpy(ctx->buf, &(in[inl]), i); ctx->buf_len = i; return 1; } int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { /* Prevent accidental use of decryption context when encrypting */ if (!ctx->encrypt) { EVPerr(EVP_F_EVP_ENCRYPTUPDATE, EVP_R_INVALID_OPERATION); return 0; } return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl); } int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { int ret; ret = EVP_EncryptFinal_ex(ctx, out, outl); return ret; } int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { int n, ret; unsigned int i, b, bl; /* Prevent accidental use of decryption context when encrypting */ if (!ctx->encrypt) { EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX, EVP_R_INVALID_OPERATION); return 0; } if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { ret = ctx->cipher->do_cipher(ctx, out, NULL, 0); if (ret < 0) return 0; else *outl = ret; return 1; } b = ctx->cipher->block_size; OPENSSL_assert(b <= sizeof(ctx->buf)); if (b == 1) { *outl = 0; return 1; } bl = ctx->buf_len; if (ctx->flags & EVP_CIPH_NO_PADDING) { if (bl) { EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX, EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH); return 0; } *outl = 0; return 1; } n = b - bl; for (i = bl; i < b; i++) ctx->buf[i] = n; ret = ctx->cipher->do_cipher(ctx, out, ctx->buf, b); if (ret) *outl = b; return ret; } int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int fix_len, cmpl = inl; unsigned int b; /* Prevent accidental use of encryption context when decrypting */ if (ctx->encrypt) { EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_INVALID_OPERATION); return 0; } b = ctx->cipher->block_size; if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS)) cmpl = (cmpl + 7) / 8; /* * CCM mode needs to know about the case where inl == 0 - it means the * plaintext/ciphertext length is 0 */ if (inl < 0 || (inl == 0 && EVP_CIPHER_mode(ctx->cipher) != EVP_CIPH_CCM_MODE)) { *outl = 0; return inl == 0; } if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { if (b == 1 && is_partially_overlapping(out, in, cmpl)) { EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING); return 0; } fix_len = ctx->cipher->do_cipher(ctx, out, in, inl); if (fix_len < 0) { *outl = 0; return 0; } else *outl = fix_len; return 1; } if (ctx->flags & EVP_CIPH_NO_PADDING) return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl); OPENSSL_assert(b <= sizeof(ctx->final)); if (ctx->final_used) { /* see comment about PTRDIFF_T comparison above */ if (((PTRDIFF_T)out == (PTRDIFF_T)in) || is_partially_overlapping(out, in, b)) { EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING); return 0; } /* * final_used is only ever set if buf_len is 0. Therefore the maximum * length output we will ever see from evp_EncryptDecryptUpdate is * the maximum multiple of the block length that is <= inl, or just: * inl & ~(b - 1) * Since final_used has been set then the final output length is: * (inl & ~(b - 1)) + b * This must never exceed INT_MAX */ if ((inl & ~(b - 1)) > INT_MAX - b) { EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_OUTPUT_WOULD_OVERFLOW); return 0; } memcpy(out, ctx->final, b); out += b; fix_len = 1; } else fix_len = 0; if (!evp_EncryptDecryptUpdate(ctx, out, outl, in, inl)) return 0; /* * if we have 'decrypted' a multiple of block size, make sure we have a * copy of this last block */ if (b > 1 && !ctx->buf_len) { *outl -= b; ctx->final_used = 1; memcpy(ctx->final, &out[*outl], b); } else ctx->final_used = 0; if (fix_len) *outl += b; return 1; } int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { int ret; ret = EVP_DecryptFinal_ex(ctx, out, outl); return ret; } int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { int i, n; unsigned int b; /* Prevent accidental use of encryption context when decrypting */ if (ctx->encrypt) { EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_INVALID_OPERATION); return 0; } *outl = 0; if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { i = ctx->cipher->do_cipher(ctx, out, NULL, 0); if (i < 0) return 0; else *outl = i; return 1; } b = ctx->cipher->block_size; if (ctx->flags & EVP_CIPH_NO_PADDING) { if (ctx->buf_len) { EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH); return 0; } *outl = 0; return 1; } if (b > 1) { if (ctx->buf_len || !ctx->final_used) { EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_WRONG_FINAL_BLOCK_LENGTH); return 0; } OPENSSL_assert(b <= sizeof(ctx->final)); /* * The following assumes that the ciphertext has been authenticated. * Otherwise it provides a padding oracle. */ n = ctx->final[b - 1]; if (n == 0 || n > (int)b) { EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT); return 0; } for (i = 0; i < n; i++) { if (ctx->final[--b] != n) { EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT); return 0; } } n = ctx->cipher->block_size - n; for (i = 0; i < n; i++) out[i] = ctx->final[i]; *outl = n; } else *outl = 0; return 1; } int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen) { if (c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH) return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL); if (c->key_len == keylen) return 1; if ((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) { c->key_len = keylen; return 1; } EVPerr(EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH, EVP_R_INVALID_KEY_LENGTH); return 0; } int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad) { if (pad) ctx->flags &= ~EVP_CIPH_NO_PADDING; else ctx->flags |= EVP_CIPH_NO_PADDING; return 1; } int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { int ret; if (!ctx->cipher) { EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_NO_CIPHER_SET); return 0; } if (!ctx->cipher->ctrl) { EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_NOT_IMPLEMENTED); return 0; } ret = ctx->cipher->ctrl(ctx, type, arg, ptr); if (ret == -1) { EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED); return 0; } return ret; } int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key) { if (ctx->cipher->flags & EVP_CIPH_RAND_KEY) return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key); if (RAND_priv_bytes(key, ctx->key_len) <= 0) return 0; return 1; } int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in) { if ((in == NULL) || (in->cipher == NULL)) { EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INPUT_NOT_INITIALIZED); return 0; } #ifndef OPENSSL_NO_ENGINE /* Make sure it's safe to copy a cipher context using an ENGINE */ if (in->engine && !ENGINE_init(in->engine)) { EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_ENGINE_LIB); return 0; } #endif EVP_CIPHER_CTX_reset(out); memcpy(out, in, sizeof(*out)); if (in->cipher_data && in->cipher->ctx_size) { out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size); if (out->cipher_data == NULL) { out->cipher = NULL; EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_MALLOC_FAILURE); return 0; } memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size); } if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY) if (!in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out)) { out->cipher = NULL; EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INITIALIZATION_ERROR); return 0; } return 1; }
f36862e0131c6cbce0696efa30479784d914e1c5
8838eb997879add5759b6dfb23f9a646464e53ca
/src/drivers/usb/hc/usb_dwc/usb_dwc.h
50ba5553c45061ffb70d33d361b1144de3c51d08
[ "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
34,144
h
usb_dwc.h
/** * @file usb_dwc_regs.h * * Registers of the DesignWare Hi-Speed USB 2.0 On-The-Go Controller. */ /* Embedded Xinu, Copyright (C) 2013. All rights reserved. */ /* Copyright (c) 2008, Douglas Comer and Dennis Brylow * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted for use in any lawful way, 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 names of the authors nor their contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS AND 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 _USB_DWC_REGS_H_ #define _USB_DWC_REGS_H_ // #include <usb_util.h> #include <assert.h> #include <kernel/thread/types.h> #include <kernel/thread/sync/semaphore.h> /** * Number of DWC host channels, each of which can be used for an independent * USB transfer. On the BCM2835 (Raspberry Pi), 8 are available. This is * documented on page 201 of the BCM2835 ARM Peripherals document. */ #define DWC_NUM_CHANNELS 8 /** * Layout of the registers of the DesignWare Hi-Speed USB 2.0 On-The-Go * Controller. There is no official documentation for these; however, the * register locations (and to some extent the meanings) can be found in other * code, such as the Linux driver for this hardware that Synopsys contributed. * * We do not explicitly define every bit in the registers because the majority * are not used by our driver and would complicate this file. For example, we * do not attempt to document any features that are specific to suspend, * hibernation, the OTG protocol, or to the core acting in device mode rather * than host mode. * * The bits and fields we do use in our driver we have tried to completely * document based on our understanding of what they do. We cannot guarantee * that all the information is correct, as we do not have access to any official * documentation. */ struct dwc_regs { /* 0x000 : OTG Control */ uint32_t otg_control; /* 0x004 : OTG Interrupt */ uint32_t otg_interrupt; /** * 0x008 : AHB Configuration Register. * * This register configures some of the interactions the DWC has with the * rest of the system. */ uint32_t ahb_configuration; /** Enable interrupts from the USB controller. Disabled by default. */ #define DWC_AHB_INTERRUPT_ENABLE (1 << 0) /** * Bits [4:1] of the AHB Configuration register were redefined by Broadcom for * the BCM2835; hence this flag is only valid on the BCM2835. * * This bit is documented as: * * 1 = Wait for all outstanding AXI writes to complete before signalling * (internally) that DMA is done. * 0 = don't wait. * * We set this bit because the Linux driver does, although we did not observe a * difference in behavior. */ #define BCM_DWC_AHB_AXI_WAIT (1 << 4) /** * Writing 1 to this bit in the AHB Configuration Register allows the USB * controller to perform DMA (Direct Memory Access). Disabled by default. */ #define DWC_AHB_DMA_ENABLE (1 << 5) /* 0x01c : Core USB configuration */ uint32_t core_usb_configuration; /** * 0x010 : Core Reset Register. * * Software can use this register to cause the DWC to reset itself. */ uint32_t core_reset; /** * TODO */ #define DWC_AHB_MASTER_IDLE (1u << 31) /** * Write 1 to this location in the Core Reset Register to start a soft * reset. This bit will then be cleared by the hardware when the reset is * complete. */ #define DWC_SOFT_RESET (1 << 0) /** * 0x014 : Core Interrupt Register. * * This register contains the state of pending top-level DWC interrupts. 1 * means interrupt pending while 0 means no interrupt pending. * * Note that at least for port_intr and host_channel_intr, software must * clear the interrupt somewhere else rather than by writing to this * register. */ union dwc_core_interrupts { uint32_t val; struct { uint32_t stuff : 3; /** * Start of Frame. TODO */ uint32_t sof_intr : 1; uint32_t morestuff : 20; /** * Host port status changed. Software must examine the Host Port * Control and Status Register to determine the current status of * the host port and clear any flags in it that indicate a status * change. */ uint32_t port_intr : 1; /* Bit 24 */ /** * Channel interrupt occurred. Software must examine the Host All * Channels Interrupt Register to determine which channel(s) have * pending interrupts, then handle and clear the interrupts for * these channels. */ uint32_t host_channel_intr : 1; /* Bit 25 */ uint32_t evenmorestuff : 6; }; } core_interrupts; /** * 0x018 : Core Interrupt Mask Register. * * This register has the same format as the Core Interrupt Register and * configures whether the corresponding interrupt is enabled (1) or disabled * (0). Initial state after reset is all 0's. */ union dwc_core_interrupts core_interrupt_mask; /* 0x01c : Receive Status Queue Read */ uint32_t receive_status; /* 0x020 : Receive Status Queue Read & Pop */ uint32_t receive_status_pop; /** * 0x024 : Receive FIFO Size Register. * * This register contains the size of the Receive FIFO, in 4-byte words. * * This register must be set by software before using the controller; see * the note in the documentation for the hwcfg3 register about configuring * the dynamic FIFOs. */ uint32_t rx_fifo_size; /** * 0x028 : Non Periodic Transmit FIFO Size Register. * * The low 16 bits of this register contain the offset of the Nonperiodic * Transmit FIFO, in 4-byte words, from the start of the memory reserved by * the controller for dynamic FIFOs. The high 16 bits of this register * contain its size, in 4-byte words. * * This register must be set by software before using the controller; see * the note in the documentation for the hwcfg3 register about configuring * the dynamic FIFOs. */ uint32_t nonperiodic_tx_fifo_size; /* 0x02c : Non Periodic Transmit FIFO/Queue Status Register */ uint32_t nonperiodic_tx_fifo_status; /* 0x030 */ uint32_t i2c_control; /* 0x034 */ uint32_t phy_vendor_control; /* 0x038 */ uint32_t gpio; /* 0x03c */ uint32_t user_id; /* 0x040 */ uint32_t vendor_id; /* 0x044 */ uint32_t hwcfg1; /* 0x048 */ uint32_t hwcfg2; /** * 0x04c : Hardware Configuration 3 Register. * * The high 16 bits of this read-only register contain the maximum total * size, in words, of the dynamic FIFOs (Rx, Nonperiodic Tx, and Periodic * Tx). Software must set up these three dynamic FIFOs in the rx_fifo_size, * nonperiodic_tx_fifo_size, and host_periodic_tx_fifo_size registers such * that their total size does not exceed this maximum total size and no * FIFOs overlap. * * Note: Software must explicitly configure the dynamic FIFOs even if the * controller is operating in DMA mode, since the default values for the * FIFO sizes and offsets may be invalid. For example, in Broadcom's * instantiation of this controller for the BCM2835, only 4080 words are * available for dynamic FIFOs, but the dynamic FIFO sizes are set to 4096, * 32, and 0, which are invalid as they add up to more than 4080. <b>IF YOU * DO NOT DO THIS YOU WILL GET SILENT MEMORY CORRUPTION</b>. * * The low 16 bits of this register contain various flags that are not * documented here as we don't use any in our driver. */ uint32_t hwcfg3; /* 0x050 */ uint32_t hwcfg4; /* 0x054 */ uint32_t core_lpm_configuration; /* 0x058 */ uint32_t global_powerDn; /* 0x05c */ uint32_t global_fifo_config; /* 0x060 */ uint32_t adp_control; /* 0x064 */ uint32_t reserved_0x64[39]; /** * 0x100 : Host Periodic Transmit FIFO Size Register. * * The low 16 bits of this register configure the offset of the Periodic * Transmit FIFO, in 4-byte words, from the start of the memory reserved by * the controller for dynamic FIFOs. The high 16 bits of this register * configure its size, in 4-byte words. * * This register should be set by software before using the controller; see * the note in the documentation for the hwcfg3 register about configuring * the dynamic FIFOs. */ uint32_t host_periodic_tx_fifo_size; /* TODO */ uint32_t stuff[191]; /** * @name Host registers * * The registers beginning at this point are considered to be the "Host" * registers. These are used for the "Host" half of the OTG (On-The-Go) * protocol, which allows this hardware to act as either a USB host or a USB * device. This is the only half we are concerned with in this driver and * we do not declare the corresponding Device registers. */ /**@{*/ /* 0x400 */ uint32_t host_configuration; /* 0x404 */ uint32_t host_frame_interval; /* 0x408 */ uint32_t host_frame_number; /* 0x40c */ uint32_t host_reserved_0x40c; /* 0x410 */ uint32_t host_fifo_status; /** * 0x414 : Host All Channels Interrupt Register. * * This register contains a bit for each host channel that indicates whether * an interrupt has occurred on that host channel. You cannot clear the * interrupts by writing to this register; use the channel-specific * interrupt registers instead. */ uint32_t host_channels_interrupt; /** * 0x418 : Host All Channels Interrupt Mask Register. * * Same format as the Host All Channels Interrupt Register, but a 1 in this * register indicates that the corresponding host channel interrupt is * enabled. Software can change this register. Defaults to all 0's after a * reset. */ uint32_t host_channels_interrupt_mask; /* 0x41c */ uint32_t host_frame_list; /* 0x420 */ uint32_t host_reserved_0x420[8]; /** * 0x440 : Host Port Control and Status Register. * * This register provides the information needed to respond to status * queries about the "host port", which is the port that is logically * attached to the root hub. * * When changing this register, software must read its value, then clear the * enabled, connected_changed, enabled_changed, and overcurrent_changed * members to avoid changing them, as those particular bits are cleared by * writing 1. */ union dwc_host_port_ctrlstatus { uint32_t val; struct { /** * 1: a device is connected to this port. * 0: no device is connected to this port. * * Changed by hardware only. */ uint32_t connected : 1; /* Bit 0 */ /** * Set by hardware when connected bit changes. Software can write * 1 to acknowledge and clear. The setting of this bit by hardware * generates an interrupt that can be enabled by setting port_intr * in the core_interrupt_mask register. */ uint32_t connected_changed : 1; /* Bit 1 */ /** * 1: port is enabled. * 0: port is disabled. * * Note: the host port is enabled by default after it is reset. * * Note: Writing 1 here appears to disable the port. */ uint32_t enabled : 1; /* Bit 2 */ /** * Set by hardware when enabled bit changes. Software can write 1 * to acknowledge and clear. The setting of this bit by hardware * generates an interrupt that can be enabled by setting port_intr * in the core_interrupt_mask register. */ uint32_t enabled_changed : 1; /* Bit 3 */ /** * 1: overcurrent condition active on this port * 0: no overcurrent condition active on this port * * Changed by hardware only. */ uint32_t overcurrent : 1; /* Bit 4 */ /** * Set by hardware when the overcurrent bit changes. The software * can write 1 to acknowledge and clear. The setting of this bit by * hardware generates the interrupt that can be enabled by setting * port_intr in the core_interrupt_mask register. */ uint32_t overcurrent_changed : 1; /* Bit 5 */ /** * Set by software to set resume signalling. */ uint32_t resume : 1; /* Bit 6 */ /** * Set by software to suspend the port. */ uint32_t suspended : 1; /* Bit 7 */ /** * Software can set this to start a reset on this port. Software * must clear this after waiting 60 milliseconds for the reset is * complete. */ uint32_t reset : 1; /* Bit 8 */ uint32_t reserved : 1; /* Bit 9 */ /** * Current logic of data lines (10: logic of D+; 11: logic of D-). * * Changed by hardware only. */ uint32_t line_status : 2; /* Bits 10-11*/ /** * 1: port is powered. * 0: port is not powered. * * Software can change this bit to power on (1) or power off (0) * the port. */ uint32_t powered : 1; /* Bit 12 */ uint32_t test_control : 4; /* Bits 13-16 */ /** * Speed of attached device (if any). This should only be * considered meaningful if the connected bit is set. * * 00: high speed; 01: full speed; 10: low speed * * Changed by hardware only. */ uint32_t speed : 2; /* Bits 17-18 */ uint32_t reserved2 : 13; /* Bits 19-32 */ }; } host_port_ctrlstatus; uint32_t host_reserved_0x444[47]; /** * 0x500 : Array of host channels. Each host channel can be used to * execute an independent USB transfer or transaction simultaneously. A USB * transfer may consist of multiple transactions, or packets. To avoid * having to re-program the channel, it may be useful to use one channel for * all transactions of a transfer before allowing other transfers to be * scheduled on it. */ struct dwc_host_channel { /** * Channel Characteristics Register - * * Contains various fields that must be set to prepare this channel for * a transfer to or from a particular endpoint on a particular USB * device. * * This register only needs to be programmed one time when doing a * transfer, regardless of how many packets it consists of, unless the * channel is re-programmed for a different transfer or the transfer is * moved to a different channel. */ union dwc_host_channel_characteristics { uint32_t val; struct { /** * Maximum packet size the endpoint is capable of sending or * receiving. Must be programmed by software before starting * the transfer. */ uint32_t max_packet_size : 11; /* Bits 0-10 */ /** * Endpoint number (low 4 bits of bEndpointAddress). Must be * programmed by software before starting the transfer. */ uint32_t endpoint_number : 4; /* Bits 11-14 */ /** * Endpoint direction (high bit of bEndpointAddress). Must be * programmed by software before starting the transfer. */ uint32_t endpoint_direction : 1; /* Bit 15 */ uint32_t reserved : 1; /* Bit 16 */ /** * 1 when the device being communicated with is attached at low * speed; 0 otherwise. Must be programmed by software before * starting the transfer. */ uint32_t low_speed : 1; /* Bit 17 */ /** * Endpoint type (low 2 bits of bmAttributes). Must be * programmed by software before starting the transfer. */ uint32_t endpoint_type : 2; /* Bits 18-19 */ /** * Maximum number of transactions that can be executed per * microframe as part of this transfer. Normally 1, but should * be set to 1 + (bits 11 and 12 of wMaxPacketSize) for * high-speed interrupt and isochronous endpoints. Must be * programmed by software before starting the transfer. */ uint32_t packets_per_frame : 2; /* Bits 20-21 */ /** * USB device address of the device on which the endpoint is * located. Must be programmed by software before starting the * transfer. */ uint32_t device_address : 7; /* Bits 22-28 */ /** * Just before enabling the channel (for all transactions), * software needs to set this to the opposite of the low bit of * the host_frame_number register. Otherwise the hardware will * issue frame overrun errors on some transactions. TODO: what * exactly does this do? */ uint32_t odd_frame : 1; /* Bit 29 */ /** * Software can set this to 1 to halt the channel. Not needed * during normal operation as the channel halts automatically * when a transaction completes or an error occurs. */ uint32_t channel_disable : 1; /* Bit 30 */ /** * Software can set this to 1 to enable the channel, thereby * actually starting the transaction on the USB. This must only * be done after the characteristics, split_control, and * transfer registers, and possibly other registers (depending * on the transfer) have been programmed. */ uint32_t channel_enable : 1; /* Bit 31 */ }; } characteristics; /** * Channel Split Control Register - * * This register is used to set up Split Transactions for communicating * with low or full-speed devices attached to a high-speed hub. When * doing so, set split_enable to 1 and the other fields as documented. * Otherwise, software must clear this register before starting the * transfer. * * Like the Channel Characteristics register, this register only * needs to be programmed one time if the channel is enabled multiple * times to send all the packets of a single transfer. */ union dwc_host_channel_split_control { uint32_t val; struct { /** * 0-based index of the port on the high-speed hub on which the * low or full-speed device is attached. */ uint32_t port_address : 7; /* Bits 0-6 */ /** * USB device address of the high-speed hub that acts as the * Transaction Translator for this low or full-speed device. * This is not necessarily the hub the device is physically * connected to, since that could be a full-speed or low-speed * hub. Instead, software must walk up the USB device tree * (towards the root hub) until a high-speed hub is found and * use its device address here. */ uint32_t hub_address : 7; /* Bits 7-13 */ /** * TODO: what exactly does this do? */ uint32_t transaction_position : 2; /* Bits 14-15 */ /** * 0: Do a Start Split transaction * 1: Do a Complete Split transaction. * * When split transactions are enabled, this must be programmed * by software before enabling the channel. Note that you must * begin with a Start Split transaction and alternate this bit * for each transaction until the transfer is complete. */ uint32_t complete_split : 1; /* Bit 16 */ uint32_t reserved : 14; /* Bits 17-30 */ /** * Set to 1 to enable Split Transactions. */ uint32_t split_enable : 1; /* Bit 31 */ }; } split_control; /** * Channel Interrupts Register - * * Bitmask of status conditions that have occurred on this channel. * * These bits can be used with or without "real" interrupts. To have * the CPU get a real interrupt when one of these bits gets set, set the * appropriate bit in the interrupt_mask, and also ensure that * interrupts from the channel are enabled in the * host_channels_interrupt_mask register, channel interrupts overall are * enabled in the core_interrupt_mask register, and interrupts from the * DWC hardware overall are enabled in the ahb_configuration register * and by any system-specific interrupt controller. */ union dwc_host_channel_interrupts { uint32_t val; struct { /** * The requested USB transfer has successfully completed. * * Exceptions and caveats: * * - When doing split transactions, this bit will be set after a * Complete Split transaction has finished, even though the * overall transfer may not actually be complete. * * - The transfer will only be complete up to the extent that * data was programmed into the channel. For example, control * transfers have 3 phases, each of which must be programmed * into the channel separately. This flag will be set after * each of these phases has successfully completed. * * - An OUT transfer is otherwise considered complete when * exactly the requested number of bytes of data have been * successfully transferred, while an IN transfer is otherwise * considered complete when exactly the requested number of * bytes of data have been successfully transferred or a * shorter-than-expected packet was received. */ uint32_t transfer_completed : 1; /* Bit 0 */ /** * The channel has halted. After this bit has been set, the * channel sits idle and nothing else will happen until software * takes action. * * Channels may halt for several reasons. From our experience * these cover all possible situations in which software needs * to take action, so this is the only channel interrupt that * actually needs to be enabled. At least in DMA mode, the * controller to some extent will act autonomously to complete * transfers and only issue this interrupt when software needs * to take action. * * Situations in which a channel will halt include but probably * are not limited to: * * - The transfer has completed, thereby setting the * transfer_completed flag as documented above. * * - A Start Split or Complete Split transaction has finished. * * - The hub sent a NYET packet when trying to execute a * Complete Split transaction, thereby signalling that the * Split transaction is not yet complete. * * - The device sent a NAK packet, thereby signalling it had no * data to send at the time, when trying to execute an IN * interrupt transfer. * * - One of several errors has occurred, such as an AHB error, * data toggle error, tranasction error, stall condition, or * frame overrun error. */ uint32_t channel_halted : 1; /* Bit 1 */ /** * An error occurred on the ARM Advanced High-Performance Bus * (AHB). */ uint32_t ahb_error : 1; /* Bit 2 */ /** * The device issued a STALL handshake packet (endpoint is * halted or control pipe request is not supported). */ uint32_t stall_response_received : 1; /* Bit 3 */ /** * The device issued a NAK handshake packet (receiving device * cannot accept data or transmitting device cannot send data). * * The channel will halt with this bit set when performing an IN * transfer from an interrupt endpoint that has no data to send. * As this requires software intervention to restart the * channel, this means that polling of interrupt endpoints (e.g. * on hubs and HID devices) must be done in software, even if * the actual transactions themselves are interrupt-driven. */ uint32_t nak_response_received : 1; /* Bit 4 */ /** * The device issued an ACK handshake packet (receiving device * acknowledged error-free packet). */ uint32_t ack_response_received : 1; /* Bit 5 */ /** * The device issued a NYET handshake packet. */ uint32_t nyet_response_received : 1; /* Bit 6 */ /** * From our experience this seems to usually indicate that * software programmed the channel incorrectly. */ uint32_t transaction_error : 1; /* Bit 7 */ /** * Unexpected bus activity occurred. */ uint32_t babble_error : 1; /* Bit 8 */ /** * TODO */ uint32_t frame_overrun : 1; /* Bit 9 */ /** * When issuing a series of DATA transactions to an endpoint, * the correct DATA0 or DATA1 packet ID was not specified in the * packet_id member of the transfer register. */ uint32_t data_toggle_error : 1; /* Bit 10 */ uint32_t buffer_not_available : 1; /* Bit 11 */ uint32_t excess_transaction_error : 1; /* Bit 12 */ uint32_t frame_list_rollover : 1; /* Bit 13 */ uint32_t reserved : 18; /* Bits 14-31 */ }; } interrupts; /** * Channel Interrupts Mask Register - * * This has the same format as the Channel Interrupts Register, but * software uses this to enable (1) or disable (0) the corresponding * interrupt. Defaults to all 0's after a reset. */ union dwc_host_channel_interrupts interrupt_mask; /** * Channel Transfer Register: * * Used to store additional information about the transfer. This must * be programmed before beginning the transfer. */ union dwc_host_channel_transfer { uint32_t val; struct { /** * Size of the data to send or receive, in bytes. Software must * program this before beginning the transfer. This can be * greater than the maximum packet length. * * For IN transfers, the hardware decrements this field for each * packet received by the number of bytes received. For split * transactions, the decrement happens after the Complete Split * rather than the Start Split. Software can subtract this * field from the original transfer size in order to determine * the number of bytes received at any given point, including * when the transfer has encountered an error or has completed * with either the full size or a short size. * * For OUT transfers, the hardware does not update this field as * expected. It will not be decremented when data is * transmitted, at least not in every case; hence, software * cannot rely on its value to indicate how many bytes of data * have been transmitted so far. Instead, software must inspect * the packet_count field and assume that all data was * transmitted if packet_count is 0, or that the amount of data * transmitted is equal to the endpoint's maximum packet size * times [the original packet count minus packet_count] if * packet_count is nonzero. */ uint32_t size : 19; /* Bits 0-18 */ /** * Number of packets left to transmit or maximum number of * packets left to receive. Software must program this before * beginning the transfer. The packet count is calculated as * the size divided by the maximum packet size, rounded up to * the nearest whole packet. As a special case, if the transfer * size is 0 bytes, the packet count must be set to 1. * * The hardware will decrement this register when a packet is * successfully sent or received. In the case of split * transactions, this happens after the Complete Split rather * than after the Start Split. If the final received packet of * an IN transfer is short, it is still counted. */ uint32_t packet_count : 10; /* Bits 19-28 */ /** * High 2 bits of the Packet ID used in the USB protocol. * * When performing the SETUP phase of a control transfer, * specify 0x3 here to generate the needed SETUP token. * * When performing the DATA phase of a control transfer, * initially specify 0x2 here to begin the DATA packets with the * needed DATA1 Packet ID. * * When performing the STATUS phase of a control transfer, * specify 0x2 here to generate the neeed DATA1 Packet ID. * * When starting a bulk, isochronous, or interrupt transfer, * specify 0x0 here to generate the needed DATA0 Packet ID. * * In the case of a transfer consisting of multiple DATA * packets, the hardware will update this field with the Packet * ID to use for the next packet. This field therefore only * needs to be re-programmed if the transfer is moved to a * different channel or the channel is re-used before the * transfer is complete. When doing so, software must save this * field so that it can be re-programmed correctly. */ uint32_t packet_id : 2; /* Bits 29-30 */ /** * TODO */ uint32_t do_ping : 1; /* Bit 31 */ }; } transfer; /** * Channel DMA Address Register - * * Word-aligned address at which the hardware will read or write data * using Direct Memory Access. This must be programmed before beginning * the transfer, unless the size of the data to send or receive is 0. * The hardware will increment this address by the number of bytes * successfully received or sent, which will correspond to the size * decrease in transfer.size. * * Note: DMA must be enabled in the AHB Configuration Register before * this register can be used. Otherwise, the hardware is considered to * be in Slave mode and must be controlled a different way, which we do * not use in our driver and do not attempt to document. * * BCM2835-specific note: Theoretically, addresses written to this * register must be bus addresses, not ARM physical addresses. However, * in our experience the behavior is the same when simply using ARM * physical addresses. */ uint32_t dma_address; uint32_t reserved_1; uint32_t reserved_2; } host_channels[DWC_NUM_CHANNELS]; uint32_t host_reserved_after_channels[(0x800 - 0x500 - (DWC_NUM_CHANNELS * sizeof(struct dwc_host_channel))) / sizeof(uint32_t)]; /**@}*/ /* 0x800 */ uint32_t reserved_0x800[(0xe00 - 0x800) / sizeof(uint32_t)]; /* 0xe00 : Power and Clock Gating Control Register */ uint32_t power; }; /* Make sure the registers are declared correctly. This is dummy code that will * be compiled into nothing. */ static inline void _dwc_check_regs(void) { static_assert(offsetof(struct dwc_regs, vendor_id) == 0x40, ""); static_assert(offsetof(struct dwc_regs, host_periodic_tx_fifo_size) == 0x100, ""); static_assert(offsetof(struct dwc_regs, host_configuration) == 0x400, ""); static_assert(offsetof(struct dwc_regs, host_port_ctrlstatus) == 0x440, ""); static_assert(offsetof(struct dwc_regs, reserved_0x800) == 0x800, ""); static_assert(offsetof(struct dwc_regs, power) == 0xe00, ""); } /** * @ingroup usbcore * * Specification of an asynchronous (interrupt-driven) USB transfer request. * This can be a control, bulk, or interrupt request. To get one of these * structures, either call usb_alloc_xfer_request(), or allocate memory manually * in another way and call usb_init_xfer_request(). Submit to to the USB core * using usb_submit_xfer_request() after filling in the * @ref usb_xfer_request::dev "dev", * @ref usb_xfer_request::endpoint_desc "endpoint_desc", * @ref usb_xfer_request::sendbuf "sendbuf" or * @ref usb_xfer_request::recvbuf "recvbuf", * @ref usb_xfer_request::size "size", * and * @ref usb_xfer_request::completion_cb_func "completion_cb_func" members, * and optionally the * @ref usb_xfer_request::private "private" and * @ref usb_xfer_request::setup_data "setup_data" members. */ struct usb_dwc_request { /********************* * Input variables * *********************/ /** USB device to communicate with. */ struct usb_device *dev; /** Setup data for the USB control request. Must be filled in for control * transfers; ignored otherwise. Note: consider using usb_control_msg() for * control transfers instead. */ // struct usb_control_setup_data setup_data; /** Callback function that will be called when this USB transfer has been * successfully completed or has failed. */ //usb_xfer_completed_t completion_cb_func; /********************* * Output variables * *********************/ /** Actual size of the data transferred. This should be tested after a * successful device-to-host (IN) transfer, since it is valid for such a * transfer to complete with less than the number of bytes requested if for * whatever reason the device was unable to provide the full size. */ uint32_t actual_size; /***************************************************************** * Private variables (mainly for Host Controller Drivers; do not * * touch from device drivers). TODO: a better design might * * allow HCDs to customize the variables they can use, perhaps * * by embedding the usb_xfer_request in another struct. * *****************************************************************/ void *cur_data_ptr; uint8_t complete_split : 1; uint8_t short_attempt : 1; uint8_t need_sof : 1; uint8_t control_phase : 2; uint8_t next_data_pid : 2; uint32_t attempted_size; uint32_t attempted_packets_remaining; uint32_t attempted_bytes_remaining; uint32_t csplit_retries; struct thread *deferer_thread; struct sem deferer_thread_sema; }; #endif /* _USB_DWC_REGS_H_ */
d3c57815d067e5720d4d92c8e2af605b72dfca2b
baf824f8819f90928e11480d0eae89efb60341a1
/ports/nxp_rt1050_60/ay_imu/core/madgwick_fusion.h
63b492d14eb14ae3643e56506636213a444eb3b3
[ "GPL-1.0-or-later", "MIT" ]
permissive
RockySong/micropython-rocky
549770723ba92cb311c468880ead0ffdd4fa8fe5
2d728f414bf8d041ca609e00448850759aade3cd
refs/heads/omv_initial_integrate
2021-05-12T12:20:18.404341
2021-01-15T01:15:48
2021-01-15T01:15:48
117,408,452
198
90
MIT
2020-08-25T03:31:32
2018-01-14T06:40:36
C
UTF-8
C
false
false
163
h
madgwick_fusion.h
#ifndef __MADGWICK_FUSION_H__ #define __MADGWICK_FUSION_H__ #include "vector.h" void madgwick_ahrs_update(q_t *q, v3_t g, v3_t a, v3_t m, float deltaT); #endif
3b2279d11b87ca392223eeb3f2a83b63ede68e88
1240fb278fecfad54ef6a586e1e59f7f36b38912
/src/tpm2-tss-engine-ecc.c
9e72c851a610e41dac8fc9334459a72e4d37cf1c
[ "BSD-3-Clause" ]
permissive
tpm2-software/tpm2-tss-engine
5ba2ba465ad2edcc305ce81f11932d4f49ca454e
af8b26e7ffe69837197fb841e9a31230ae01c9cc
refs/heads/master
2023-08-13T17:54:12.359140
2023-05-22T12:06:41
2023-05-23T07:07:10
136,935,379
134
104
BSD-3-Clause
2023-05-23T07:07:11
2018-06-11T14:09:00
C
UTF-8
C
false
false
26,182
c
tpm2-tss-engine-ecc.c
/******************************************************************************* * Copyright 2017-2018, Fraunhofer SIT sponsored by Infineon Technologies AG * 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 tpm2-tss-engine nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include <string.h> #include <openssl/engine.h> #include <openssl/ec.h> #include <openssl/ecdsa.h> #include <tss2/tss2_mu.h> #include <tss2/tss2_esys.h> #include "tpm2-tss-engine.h" #include "tpm2-tss-engine-common.h" static int ec_key_app_data = -1; #if OPENSSL_VERSION_NUMBER < 0x10100000 const ECDSA_METHOD *ecc_method_default = NULL; ECDSA_METHOD *ecc_methods = NULL; #else /* OPENSSL_VERSION_NUMBER < 0x10100000 */ const EC_KEY_METHOD *ecc_method_default = NULL; EC_KEY_METHOD *ecc_methods = NULL; #endif /* OPENSSL_VERSION_NUMBER < 0x10100000 */ #ifdef HAVE_OPENSSL_DIGEST_SIGN static int (*ecdsa_pkey_orig_copy)(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src); static void (*ecdsa_pkey_orig_cleanup)(EVP_PKEY_CTX *ctx); #endif /* HAVE_OPENSSL_DIGEST_SIGN */ static TPM2B_DATA allOutsideInfo = { .size = 0, }; static TPML_PCR_SELECTION allCreationPCR = { .count = 0, }; static TPM2B_PUBLIC keyEcTemplate = { .publicArea = { .type = TPM2_ALG_ECC, .nameAlg = ENGINE_HASH_ALG, .objectAttributes = (TPMA_OBJECT_USERWITHAUTH | TPMA_OBJECT_SIGN_ENCRYPT | TPMA_OBJECT_FIXEDTPM | TPMA_OBJECT_FIXEDPARENT | TPMA_OBJECT_SENSITIVEDATAORIGIN | TPMA_OBJECT_NODA), .parameters.eccDetail = { .curveID = 0, /* To be filled out later */ .symmetric = { .algorithm = TPM2_ALG_NULL, .keyBits.aes = 0, .mode.aes = 0, }, .scheme = { .scheme = TPM2_ALG_NULL, .details = {} }, .kdf = { .scheme = TPM2_ALG_NULL, .details = {} }, }, .unique.ecc = { .x.size = 0, .y.size = 0 } } }; #if OPENSSL_VERSION_NUMBER < 0x10100000 static int EC_GROUP_order_bits(const EC_GROUP *group) { if (!group) return 0; BIGNUM *order = BN_new(); if (order == NULL) { ERR_clear_error(); return 0; } int ret = 0; if (!EC_GROUP_get_order(group, order, NULL)) { ERR_clear_error(); BN_free(order); return 0; } ret = BN_num_bits(order); BN_free(order); return ret; } #else /* OPENSSL_VERSION_NUMBER < 0x10100000 */ /** * Initialize a TPM2B_ECC_POINT from an OpenSSL EC_POINT. * * @param point Pointer to output tpm point * @param pub_key OpenSSL public key to convert * @param group Curve group * @retval 0 on failure */ static int init_tpm_public_point(TPM2B_ECC_POINT *point, const EC_POINT *ec_point, const EC_GROUP *ec_group) { unsigned char buffer[1 + sizeof(point->point.x.buffer) + sizeof(point->point.y.buffer)] = {0}; BN_CTX *ctx = BN_CTX_new(); if (!ctx) return 0; BN_CTX_start(ctx); size_t len = 0; // first, check for actual buffer size required if ((len = EC_POINT_point2oct(ec_group, ec_point, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, ctx)) <= sizeof(buffer)) { len = EC_POINT_point2oct(ec_group, ec_point, POINT_CONVERSION_UNCOMPRESSED, buffer, sizeof(buffer), ctx); } BN_CTX_end(ctx); BN_CTX_free(ctx); if (len == 0 || len > sizeof(buffer)) return 0; len = (len - 1) / 2; point->point.x.size = len; point->point.y.size = len; memcpy(point->point.x.buffer, &buffer[1], len); memcpy(point->point.y.buffer, &buffer[1 + len], len); return 1; } /** * Generate a shared secret using a TPM key * * @param psec Pointer to output buffer holding shared secret * @param pseclen Size of the psec buffer * @param pub_key The peer's public key * @param ecdh The ECC key object for the host private key * @retval 0 on failure */ static int ecdh_compute_key(unsigned char **psec, size_t *pseclen, const EC_POINT *pub_key, const EC_KEY *eckey) { /* * If this is not a TPM2 key, bail out since fall through to software * functions requires a non-const EC_KEY, yet the ECDH prototype only * provides it as const. */ TPM2_DATA *tpm2Data = tpm2tss_ecc_getappdata(eckey); if (tpm2Data == NULL) return 0; TPM2B_ECC_POINT inPoint; TPM2B_ECC_POINT *outPoint = NULL; const EC_GROUP *group = EC_KEY_get0_group(eckey); int ret = init_tpm_public_point(&inPoint, pub_key, group); if (!ret) return 0; ESYS_CONTEXT *esys_ctx = NULL; ESYS_TR keyHandle = ESYS_TR_NONE; TSS2_RC r = init_tpm_key(&esys_ctx, &keyHandle, tpm2Data); ERRchktss(ecdh_compute_key, r, goto error); r = Esys_ECDH_ZGen(esys_ctx, keyHandle, ESYS_TR_PASSWORD, ESYS_TR_NONE, ESYS_TR_NONE, &inPoint, &outPoint); ERRchktss(ecdh_compute_key, r, goto error); *pseclen = outPoint->point.x.size; *psec = OPENSSL_malloc(*pseclen); if (!*psec) goto error; memcpy(*psec, outPoint->point.x.buffer, *pseclen); ret = 1; goto out; error: ret = 0; out: if (keyHandle != ESYS_TR_NONE) { if (tpm2Data->privatetype == KEY_TYPE_HANDLE) { Esys_TR_Close(esys_ctx, &keyHandle); } else { Esys_FlushContext(esys_ctx, keyHandle); } } Esys_Free(outPoint); esys_ctx_free(&esys_ctx); return ret; } #endif /* OPENSSL_VERSION_NUMBER < 0x10100000 */ static ECDSA_SIG * ecdsa_sign(ESYS_CONTEXT *esys_ctx, ESYS_TR key_handle, TPM2B_DIGEST *digest, TPMT_TK_HASHCHECK *validation, TPM2_ALG_ID hash_alg) { TPMT_SIG_SCHEME inScheme = { .scheme = TPM2_ALG_ECDSA, .details.ecdsa.hashAlg = hash_alg, }; BIGNUM *bns = NULL, *bnr = NULL; ECDSA_SIG *ret = NULL; TPMT_SIGNATURE *sig = NULL; TSS2_RC r; r = Esys_Sign(esys_ctx, key_handle, ESYS_TR_PASSWORD, ESYS_TR_NONE, ESYS_TR_NONE, digest, &inScheme, validation, &sig); ERRchktss(ecdsa_sign, r, goto error); ret = ECDSA_SIG_new(); if (ret == NULL) { ERR(ecdsa_sign, ERR_R_MALLOC_FAILURE); goto error; } bns = BN_bin2bn(&sig->signature.ecdsa.signatureS.buffer[0], sig->signature.ecdsa.signatureS.size, NULL); bnr = BN_bin2bn(&sig->signature.ecdsa.signatureR.buffer[0], sig->signature.ecdsa.signatureR.size, NULL); if (!bns || !bnr) { ERR(ecdsa_sign, ERR_R_MALLOC_FAILURE); goto error; } #if OPENSSL_VERSION_NUMBER < 0x10100000 ret->s = bns; ret->r = bnr; #else /* OPENSSL_VERSION_NUMBER < 0x10100000 */ ECDSA_SIG_set0(ret, bnr, bns); #endif /* OPENSSL_VERSION_NUMBER < 0x10100000 */ goto out; error: if (bns) BN_free(bns); if (bnr) BN_free(bnr); if (ret) ECDSA_SIG_free(ret); ret = NULL; out: Esys_Free(sig); return ret; } /** Sign data using a TPM key * * This function performs the sign function using the private key in ECDSA. * This operation is usually used to perform signature and authentication * operations. * @param dgst The data to be signed. * @param dgst_len Length of the from buffer. * @param inv Ignored * @param rp Ignored * @param eckey The ECC key object. * @retval 0 on failure * @retval size Size of the returned signature */ static ECDSA_SIG * ecdsa_ec_key_sign(const unsigned char *dgst, int dgst_len, const BIGNUM *inv, const BIGNUM *rp, EC_KEY *eckey) { ECDSA_SIG *ret = NULL; TPM2_DATA *tpm2Data = tpm2tss_ecc_getappdata(eckey); TPM2_ALG_ID hash_alg; /* If this is not a TPM2 key, fall through to software functions */ if (tpm2Data == NULL) { #if OPENSSL_VERSION_NUMBER < 0x10100000 ECDSA_set_method(eckey, ecc_method_default); ret = ECDSA_do_sign_ex(dgst, dgst_len, inv, rp, eckey); ECDSA_set_method(eckey, ecc_methods); return ret; #else /* OPENSSL_VERSION_NUMBER < 0x10100000 */ EC_KEY_set_method(eckey, ecc_method_default); ret = ECDSA_do_sign_ex(dgst, dgst_len, inv, rp, eckey); EC_KEY_set_method(eckey, ecc_methods); return ret; #endif /* OPENSSL_VERSION_NUMBER < 0x10100000 */ } DBG("ecdsa_sign called for input data(size=%i):\n", dgst_len); DBGBUF(dgst, dgst_len); TSS2_RC r; ESYS_CONTEXT *esys_ctx = NULL; ESYS_TR keyHandle = ESYS_TR_NONE; TPMT_TK_HASHCHECK validation = { .tag = TPM2_ST_HASHCHECK, .hierarchy = TPM2_RH_NULL, .digest.size = 0 }; /* * ECDSA signatures truncate the incoming hash to fit the curve, * and the signature mechanism is the same regardless of the * hash being used. * * The TPM bizarrely wants to be told the hash algorithm, and * either it or the TSS will validate that the digest length * matches the hash that it's told, despite it having no business * caring about such things. * * So, we can truncate the digest any pretend it's any smaller * digest that the TPM actually does support, as long as that * digest is larger than the size of the curve. */ int curve_len = (EC_GROUP_order_bits(EC_KEY_get0_group(eckey)) + 7) / 8; /* If we couldn't work it out, don't truncate */ if (!curve_len) curve_len = dgst_len; if (dgst_len == SHA_DIGEST_LENGTH || (curve_len <= SHA_DIGEST_LENGTH && dgst_len > SHA_DIGEST_LENGTH)) { hash_alg = TPM2_ALG_SHA1; dgst_len = SHA_DIGEST_LENGTH; } else if (dgst_len == SHA256_DIGEST_LENGTH || (curve_len <= SHA256_DIGEST_LENGTH && dgst_len > SHA256_DIGEST_LENGTH)) { hash_alg = TPM2_ALG_SHA256; dgst_len = SHA256_DIGEST_LENGTH; } else if (dgst_len == SHA384_DIGEST_LENGTH || (curve_len <= SHA384_DIGEST_LENGTH && dgst_len > SHA384_DIGEST_LENGTH)) { hash_alg = TPM2_ALG_SHA384; dgst_len = SHA384_DIGEST_LENGTH; } else if (dgst_len == SHA512_DIGEST_LENGTH || (curve_len <= SHA512_DIGEST_LENGTH && dgst_len > SHA512_DIGEST_LENGTH)) { hash_alg = TPM2_ALG_SHA512; dgst_len = SHA512_DIGEST_LENGTH; } else { ERR(ecdsa_sign, TPM2TSS_R_PADDING_UNKNOWN); goto error; } TPM2B_DIGEST digest = { .size = dgst_len }; if (digest.size > sizeof(digest.buffer)) { ERR(ecdsa_sign, TPM2TSS_R_DIGEST_TOO_LARGE); goto error; } memcpy(&digest.buffer[0], dgst, digest.size); r = init_tpm_key(&esys_ctx, &keyHandle, tpm2Data); ERRchktss(ecdsa_sign, r, goto error); ret = ecdsa_sign(esys_ctx, keyHandle, &digest, &validation, hash_alg); goto out; error: r = -1; out: if (keyHandle != ESYS_TR_NONE) { if (tpm2Data->privatetype == KEY_TYPE_HANDLE) { Esys_TR_Close(esys_ctx, &keyHandle); } else { Esys_FlushContext(esys_ctx, keyHandle); } } esys_ctx_free(&esys_ctx); return (r == TSS2_RC_SUCCESS) ? ret : NULL; } #ifdef HAVE_OPENSSL_DIGEST_SIGN static int ecdsa_pkey_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { if (ecdsa_pkey_orig_copy && !ecdsa_pkey_orig_copy(dst, src)) return 0; return digest_sign_copy(dst, src); } static void ecdsa_pkey_cleanup(EVP_PKEY_CTX *ctx) { digest_sign_cleanup(ctx); if (ecdsa_pkey_orig_cleanup) ecdsa_pkey_orig_cleanup(ctx); } /* called for digest & sign init, after message digest algorithm set */ static int ecdsa_digest_custom(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx) { EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(ctx); EC_KEY *eckey = EVP_PKEY_get0_EC_KEY(pkey); TPM2_DATA *tpm2data = tpm2tss_ecc_getappdata(eckey); DBG("ecdsa_digest_custom %p %p\n", ctx, mctx); return digest_sign_init(ctx, mctx, tpm2data, ECDSA_size(eckey)); } static int ecdsa_signctx(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, EVP_MD_CTX *mctx) { TPM2_SIG_DATA *sig_data = EVP_PKEY_CTX_get_app_data(ctx); TSS2_RC r = TSS2_RC_SUCCESS; TPMT_TK_HASHCHECK *validation_ptr = NULL; TPM2B_DIGEST *digest_ptr = NULL; ECDSA_SIG *ecdsa_s = NULL; DBG("ecdsa_signctx %p %p sig_data %p\n", ctx, mctx, sig_data); if (!sig) { /* caller just wants to know the size */ *siglen = sig_data->sig_size; return 1; } if (!sig_data) { /* handle non-TPM key */ unsigned char md[EVP_MAX_MD_SIZE]; unsigned int md_len = 0; if (!EVP_DigestFinal_ex(mctx, md, &md_len)) return 0; if (EVP_PKEY_sign(ctx, sig, siglen, md, md_len) <= 0) return 0; return 1; } if (!digest_finish(sig_data, &digest_ptr, &validation_ptr)) return 0; ecdsa_s = ecdsa_sign(sig_data->key->esys_ctx, sig_data->key->key_handle, digest_ptr, validation_ptr, sig_data->hash_alg); if (!ecdsa_s) goto error; *siglen = i2d_ECDSA_SIG(ecdsa_s, &sig); r = 1; goto out; error: r = 0; out: ECDSA_SIG_free(ecdsa_s); Esys_Free(digest_ptr); Esys_Free(validation_ptr); return r; } #endif /* HAVE_OPENSSL_DIGEST_SIGN */ /** Helper to populate the ECC key object. * * In order to use an ECC key object in a typical manner, all fields of the * OpenSSL's corresponding object bust be filled. This function fills the public * values correctly. * @param key The key object to fill. * @retval 0 on failure * @retval 1 on success */ static int populate_ecc(EC_KEY *key) { EC_GROUP *ecgroup = NULL; int nid; BIGNUM *x = NULL, *y = NULL; TPM2_DATA *tpm2Data = tpm2tss_ecc_getappdata(key); if (tpm2Data == NULL) return 0; switch (tpm2Data->pub.publicArea.parameters.eccDetail.curveID) { case TPM2_ECC_NIST_P256: nid = EC_curve_nist2nid("P-256"); break; case TPM2_ECC_NIST_P384: nid = EC_curve_nist2nid("P-384"); break; default: nid = -1; } if (nid < 0) { ERR(populate_ecc, TPM2TSS_R_UNKNOWN_CURVE); return 0; } ecgroup = EC_GROUP_new_by_curve_name(nid); if (ecgroup == NULL) { ERR(populate_ecc, TPM2TSS_R_UNKNOWN_CURVE); return 0; } if (!EC_KEY_set_group(key, ecgroup)) { ERR(populate_ecc, TPM2TSS_R_GENERAL_FAILURE); EC_GROUP_free(ecgroup); return 0; } EC_KEY_set_asn1_flag(key, OPENSSL_EC_NAMED_CURVE); EC_GROUP_free(ecgroup); x = BN_bin2bn(tpm2Data->pub.publicArea.unique.ecc.x.buffer, tpm2Data->pub.publicArea.unique.ecc.x.size, NULL); y = BN_bin2bn(tpm2Data->pub.publicArea.unique.ecc.y.buffer, tpm2Data->pub.publicArea.unique.ecc.y.size, NULL); if (!x || !y) { ERR(populate_ecc, ERR_R_MALLOC_FAILURE); return 0; } if (!EC_KEY_set_public_key_affine_coordinates(key, x, y)) { ERR(populate_ecc, TPM2TSS_R_GENERAL_FAILURE); BN_free(y); BN_free(x); return 0; } BN_free(y); BN_free(x); return 1; } /** Helper to load an ECC key from a tpm2Data * * This function creates a key object given a TPM2_DATA object. The resulting * key object can then be used for signing with the tpm2tss engine. Ownership * of the TPM2_DATA object is taken on success. * @param tpm2Data The key data to use. Must have been allocated using * OPENSSL_malloc. * @retval key The key object * @retval NULL on failure. */ EVP_PKEY * tpm2tss_ecc_makekey(TPM2_DATA *tpm2Data) { DBG("Creating ECC key object.\n"); EVP_PKEY *pkey; EC_KEY *eckey; /* create the new objects to return */ if ((pkey = EVP_PKEY_new()) == NULL) { ERR(tpm2tss_ecc_makekey, ERR_R_MALLOC_FAILURE); return NULL; } if ((eckey = EC_KEY_new()) == NULL) { ERR(tpm2tss_ecc_makekey, ERR_R_MALLOC_FAILURE); EVP_PKEY_free(pkey); return NULL; } #if OPENSSL_VERSION_NUMBER < 0x10100000 if (!ECDSA_set_method(eckey, ecc_methods)) { #else /* OPENSSL_VERSION_NUMBER < 0x10100000 */ if (!EC_KEY_set_method(eckey, ecc_methods)) { #endif /* OPENSSL_VERSION_NUMBER < 0x10100000 */ ERR(tpm2tss_ecc_makekey, TPM2TSS_R_GENERAL_FAILURE); EC_KEY_free(eckey); goto error; } if (!EVP_PKEY_assign_EC_KEY(pkey, eckey)) { ERR(tpm2tss_ecc_makekey, TPM2TSS_R_GENERAL_FAILURE); EC_KEY_free(eckey); goto error; } if (!tpm2tss_ecc_setappdata(eckey, tpm2Data)) { ERR(tpm2tss_ecc_makekey, TPM2TSS_R_GENERAL_FAILURE); goto error; } if (!populate_ecc(eckey)) goto error; DBG("Created ECC key object.\n"); return pkey; error: EVP_PKEY_free(pkey); return NULL; } /** Retrieve app data * * Since the ECC api (opposed to the RSA api) does not provide a standardized * way to retrieve app data between the library and an application, this helper * is defined * @param key The key object * @retval tpm2Data The corresponding TPM data * @retval NULL on failure. */ TPM2_DATA * #if OPENSSL_VERSION_NUMBER < 0x10100000 tpm2tss_ecc_getappdata(EC_KEY *key) #else /* OPENSSL_VERSION_NUMBER < 0x10100000 */ tpm2tss_ecc_getappdata(const EC_KEY *key) #endif /* OPENSSL_VERSION_NUMBER < 0x10100000 */ { if (ec_key_app_data == -1) { DBG("Module uninitialized\n"); return NULL; } #if OPENSSL_VERSION_NUMBER < 0x10100000 return ECDSA_get_ex_data(key, ec_key_app_data); #else /* OPENSSL_VERSION_NUMBER < 0x10100000 */ return EC_KEY_get_ex_data(key, ec_key_app_data); #endif /* OPENSSL_VERSION_NUMBER < 0x10100000 */ } /** Set app data * * Since the ECC api (opposed to the RSA api) does not provide a standardized * way to set app data between the library and an application, this helper * is defined * @param key The key object * @param tpm2Data The corresponding TPM data * @retval 1 on success * @retval 0 on failure */ int tpm2tss_ecc_setappdata(EC_KEY *key, TPM2_DATA *tpm2Data) { if (ec_key_app_data == -1) { DBG("Module uninitialized\n"); return 0; } #if OPENSSL_VERSION_NUMBER < 0x10100000 return ECDSA_set_ex_data(key, ec_key_app_data, tpm2Data); #else /* OPENSSL_VERSION_NUMBER < 0x10100000 */ return EC_KEY_set_ex_data(key, ec_key_app_data, tpm2Data); #endif /* OPENSSL_VERSION_NUMBER < 0x10100000 */ } static void free_ecc_appdata(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp) { TPM2_DATA *tpm2Data = ptr; (void)parent; (void)ad; (void)idx; (void)argl; (void)argp; if (!ptr) return; OPENSSL_free(tpm2Data); } /** Generate a tpm2tss ecc key object. * * This function creates a new TPM ECC key. The TPM data is stored inside the * object*s app data and can be retrieved using tpm2tss_ecc_getappdata(). * @param key The key object for the TPM ECC key to be created * @param curve The curve to be used for the key * @param password The Password to be set for the new key * @retval 1 on success * @retval 0 on failure */ int tpm2tss_ecc_genkey(EC_KEY *key, TPMI_ECC_CURVE curve, const char *password, TPM2_HANDLE parentHandle) { DBG("GenKey for ecdsa.\n"); TSS2_RC r; ESYS_CONTEXT *esys_ctx = NULL; ESYS_TR parent = ESYS_TR_NONE; TPM2B_PUBLIC *keyPublic = NULL; TPM2B_PRIVATE *keyPrivate = NULL; TPM2_DATA *tpm2Data = NULL; TPM2B_PUBLIC inPublic = keyEcTemplate; TPM2B_SENSITIVE_CREATE inSensitive = { .sensitive = { .userAuth = { .size = 0, }, .data = { .size = 0, } } }; tpm2Data = OPENSSL_malloc(sizeof(*tpm2Data)); if (tpm2Data == NULL) { ERR(tpm2tss_ecc_genkey, ERR_R_MALLOC_FAILURE); goto error; } memset(tpm2Data, 0, sizeof(*tpm2Data)); inPublic.publicArea.parameters.eccDetail.curveID = curve; if (password) { DBG("Setting a password for the created key.\n"); if (strlen(password) > sizeof(tpm2Data->userauth.buffer) - 1 || strlen(password) > sizeof(inSensitive.sensitive.userAuth.buffer) - 1) { goto error; } tpm2Data->userauth.size = strlen(password); memcpy(&tpm2Data->userauth.buffer[0], password, tpm2Data->userauth.size); inSensitive.sensitive.userAuth.size = strlen(password); memcpy(&inSensitive.sensitive.userAuth.buffer[0], password, strlen(password)); } else tpm2Data->emptyAuth = 1; r = init_tpm_parent(&esys_ctx, parentHandle, &parent); ERRchktss(tpm2tss_ecc_genkey, r, goto error); tpm2Data->parent = parentHandle; DBG("Generating the ECC key inside the TPM.\n"); r = Esys_Create(esys_ctx, parent, ESYS_TR_PASSWORD, ESYS_TR_NONE, ESYS_TR_NONE, &inSensitive, &inPublic, &allOutsideInfo, &allCreationPCR, &keyPrivate, &keyPublic, NULL, NULL, NULL); ERRchktss(tpm2tss_ecc_genkey, r, goto error); DBG("Generated the ECC key inside the TPM.\n"); tpm2Data->pub = *keyPublic; tpm2Data->priv = *keyPrivate; if (!tpm2tss_ecc_setappdata(key, tpm2Data)) { ERR(tpm2tss_ecc_genkey, TPM2TSS_R_GENERAL_FAILURE); goto error; } if (!populate_ecc(key)) { goto error; } goto end; error: r = -1; tpm2tss_ecc_setappdata(key, NULL); if (tpm2Data) OPENSSL_free(tpm2Data); end: Esys_Free(keyPrivate); Esys_Free(keyPublic); if (parent != ESYS_TR_NONE && !parentHandle) Esys_FlushContext(esys_ctx, parent); esys_ctx_free(&esys_ctx); return (r == TSS2_RC_SUCCESS); } /** Initialize the tpm2tss engine's ecc submodule * * Initialize the tpm2tss engine's submodule by setting function pointer. * @param e The engine context. * @retval 1 on success * @retval 0 on failure */ int init_ecc(ENGINE *e) { (void)(e); #if OPENSSL_VERSION_NUMBER < 0x10100000 ecc_method_default = ECDSA_OpenSSL(); if (ecc_method_default == NULL) return 0; ecc_methods = ECDSA_METHOD_new(ecc_method_default); if (ecc_methods == NULL) return 0; ECDSA_METHOD_set_sign(ecc_methods, ecdsa_ec_key_sign); if (ec_key_app_data == -1) ec_key_app_data = ECDSA_get_ex_new_index(0, NULL, NULL, NULL, free_ecc_appdata); #else /* OPENSSL_VERSION_NUMBER < 0x10100000 */ ecc_method_default = EC_KEY_OpenSSL(); if (ecc_method_default == NULL) return 0; ecc_methods = EC_KEY_METHOD_new(ecc_method_default); if (ecc_methods == NULL) return 0; int (*orig_sign) (int, const unsigned char *, int, unsigned char *, unsigned int *, const BIGNUM *, const BIGNUM *, EC_KEY *) = NULL; EC_KEY_METHOD_get_sign(ecc_methods, &orig_sign, NULL, NULL); EC_KEY_METHOD_set_sign(ecc_methods, orig_sign, NULL, ecdsa_ec_key_sign); EC_KEY_METHOD_set_compute_key(ecc_methods, ecdh_compute_key); if (ec_key_app_data == -1) ec_key_app_data = EC_KEY_get_ex_new_index(0, NULL, NULL, NULL, free_ecc_appdata); #endif /* OPENSSL_VERSION_NUMBER < 0x10100000 */ #if HAVE_OPENSSL_DIGEST_SIGN /* digest and sign support */ EVP_PKEY_METHOD *pkey_ecc_methods; pkey_ecc_methods = EVP_PKEY_meth_new(EVP_PKEY_EC, 0); if (pkey_ecc_methods == NULL) return 0; const EVP_PKEY_METHOD *pkey_orig_ecc_methods = EVP_PKEY_meth_find(EVP_PKEY_EC); if (pkey_orig_ecc_methods == NULL) return 0; EVP_PKEY_meth_copy(pkey_ecc_methods, pkey_orig_ecc_methods); /* * save originals since we only override some of the pkey * functionality, rather than reimplementing all of it */ EVP_PKEY_meth_get_copy(pkey_ecc_methods, &ecdsa_pkey_orig_copy); EVP_PKEY_meth_get_cleanup(pkey_ecc_methods, &ecdsa_pkey_orig_cleanup); EVP_PKEY_meth_set_copy(pkey_ecc_methods, ecdsa_pkey_copy); EVP_PKEY_meth_set_cleanup(pkey_ecc_methods, ecdsa_pkey_cleanup); EVP_PKEY_meth_set_signctx(pkey_ecc_methods, NULL, ecdsa_signctx); EVP_PKEY_meth_set_digest_custom(pkey_ecc_methods, ecdsa_digest_custom); EVP_PKEY_meth_add0(pkey_ecc_methods); #endif /* HAVE_OPENSSL_DIGEST_SIGN */ return 1; }
e8cfc0cc8f5d46eb0e7cf19d075386c6ea734439
f3eed0234b4d0ad2bbb2abd700cf1e2c7a0e8a1d
/AKWF-c/AKWF_vgame/AKWF_vgame_0123.h
a8d793fe444a07ddbcfa062236d7cd376813da0d
[ "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,684
h
AKWF_vgame_0123.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_vgame_0123 256 samples +-----------------------------------------------------------------------------------------------------------------+ | * * | | * * | | ********** * | | * * * | | * * | | * * * * | |**************** * ************************ | | * * * | | * * * * | | * ***************** ************************| | * * | | * * | | * *********** | | * * | | * * | +-----------------------------------------------------------------------------------------------------------------+ */ const uint16_t AKWF_vgame_0123 [] = { 37129, 39848, 38957, 39520, 39106, 39432, 39169, 39381, 39214, 39342, 39248, 39307, 39278, 39276, 39304, 39246, 39329, 39222, 39348, 39200, 39362, 39183, 39370, 39173, 39371, 39171, 39363, 39178, 39343, 39198, 39311, 39233, 39256, 39301, 39154, 39460, 38842, 49344, 52614, 51409, 52171, 51594, 52060, 51651, 52016, 51665, 52002, 51650, 52011, 51616, 52039, 51562, 52084, 51494, 52143, 51410, 52220, 51274, 52677, 62715, 65289, 63561, 65164, 63558, 65170, 63525, 65171, 63511, 65138, 63541, 65051, 63626, 64976, 62655, 9492, 0, 3063, 0, 2453, 177, 2141, 449, 1890, 703, 1634, 994, 1300, 1474, 421, 7584, 15255, 13092, 14401, 13513, 14151, 13708, 14022, 13825, 13950, 13896, 13914, 13936, 13906, 13956, 13916, 13958, 13938, 13954, 13963, 13949, 13988, 13933, 14213, 25136, 27083, 26275, 26871, 26368, 26833, 26405, 26815, 26436, 26797, 26467, 26774, 26504, 26746, 26545, 26715, 26588, 26679, 26633, 26642, 26678, 26606, 26723, 26569, 26766, 26537, 26805, 26506, 26840, 26478, 26876, 26451, 26916, 26407, 26996, 26227, 27894, 38715, 39517, 39105, 39465, 39127, 39453, 39139, 39439, 39154, 39424, 39169, 39404, 39186, 39386, 39201, 39366, 39216, 39350, 39227, 39334, 39237, 39319, 39247, 39306, 39254, 39294, 39261, 39281, 39268, 39268, 39275, 39252, 39286, 39234, 39299, 39213, 39316, 39188, 39337, 39159, 39361, 39124, 39393, 39083, 39430, 39030, 39485, 38954, 39586, 38775, 39966, 37003, 26485, 26692, 26621, 26582, 26688, 26540, 26715, 26518, 26728, 26515, 26728, 26518, 26723, 26528, 26715, 26543, 26701, 26561, 26687, 26580, 26673, 26599, 26658, 26618, 26645, 26636, 26634, 26653, 26624, 26667, 26616, 26679, 26610, 26690, 26607, 26698, 26606, 26704, 26607, 26708, 26613, 26707, 26621, 26702, 26635, 26692, 26654, 26673, 26687, 26638, 26744, 26559, 26891, 26223, };
f07e9ec59410dde4973d58022fc56691e0ed6917
0744dcc5394cebf57ebcba343747af6871b67017
/os/board/rtl8730e/src/component/os/tizenrt/ethernetif_tizenrt.h
2e46be5809983363d55d64e5f317a7acb3aa138b
[ "GPL-1.0-or-later", "BSD-3-Clause", "ISC", "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", "Apache-2.0" ]
permissive
Samsung/TizenRT
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
refs/heads/master
2023-08-31T08:59:33.327998
2023-08-08T06:09:20
2023-08-31T04:38:20
82,517,252
590
719
Apache-2.0
2023-09-14T06:54:49
2017-02-20T04:38:30
C
UTF-8
C
false
false
1,435
h
ethernetif_tizenrt.h
/****************************************************************************** * Copyright (c) 2013-2016 Realtek Semiconductor Corp. * * 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 __ETHERNETIF_H__ #define __ETHERNETIF_H__ #include "lwip/err.h" #include "lwip/netif.h" //----- ------------------------------------------------------------------ // Ethernet Buffer //----- ------------------------------------------------------------------ struct eth_drv_sg { unsigned int buf; unsigned int len; }; #define MAX_ETH_DRV_SG 32 #define MAX_ETH_MSG 1540 void ethernetif_recv(struct netif *netif, int total_len); err_t ethernetif_init_rtk(struct netif *netif); err_t ethernetif_mii_init(struct netif *netif); void lwip_PRE_SLEEP_PROCESSING(void); void lwip_POST_SLEEP_PROCESSING(void); #endif
d10555448ad116bc46063716f9153b1bf3675c65
96a330b0069bf008457d7a9201fc8eba83ff86c6
/src/services/pcn-loadbalancer-rp/src/Lbrp_dp.c
b37353cd5dee2559c934e968bda652f3a2c99a21
[ "Apache-2.0" ]
permissive
polycube-network/polycube
0ef845cb7043a47c37f2f2073d5aaf818da6da46
a143e3c0325400dad7b9ff3406848f5a953ed3d1
refs/heads/master
2023-03-20T01:08:32.534908
2022-06-30T12:45:40
2022-06-30T12:45:40
161,432,392
463
107
Apache-2.0
2023-03-07T01:11:30
2018-12-12T04:23:33
C++
UTF-8
C
false
false
23,832
c
Lbrp_dp.c
/* * Copyright 2018 The Polycube Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <linux/jhash.h> #include <uapi/linux/bpf.h> #include <uapi/linux/filter.h> #include <uapi/linux/icmp.h> #include <uapi/linux/if_arp.h> #include <uapi/linux/if_ether.h> #include <uapi/linux/if_packet.h> #include <uapi/linux/in.h> #include <uapi/linux/ip.h> #include <uapi/linux/pkt_cls.h> #include <uapi/linux/tcp.h> #include <uapi/linux/udp.h> /* * * This load balancer implements the following behavior: * * - Load Balance (by looking up in the services map the VIP, to make load * balancing)(from vip to backend) * - Reverse Proxy (from backend to vip) * * IF (DADDR IS VIP) * LOAD BALANCE * REDIRECT TO BACKEND_PORT * * ELSE IF(PKT FROM BACKEND_PORT) * REV_PROXY -> (SADDR = VIP) * REDIRECT TO FRONTEND_PORT * ELSE IF(PKT FROM FRONTEND_PORT) * REDIRECT TO BACKEND_PORT * */ #define MAX_SERVICES 1024 #define MAX_SESSIONS 65536 #define MAX_FRONTENDS 1024 #define IP_CSUM_OFFSET (sizeof(struct eth_hdr) + offsetof(struct iphdr, check)) #define TCP_CSUM_OFFSET \ (sizeof(struct eth_hdr) + sizeof(struct iphdr) + \ offsetof(struct tcphdr, check)) #define UDP_CSUM_OFFSET \ (sizeof(struct eth_hdr) + sizeof(struct iphdr) + \ offsetof(struct udphdr, check)) #define ICMP_CSUM_OFFSET \ (sizeof(struct eth_hdr) + sizeof(struct iphdr) + \ offsetof(struct icmphdr, checksum)) #define IS_PSEUDO 0x10 #ifndef SINGLE_PORT_MODE #define SINGLE_PORT_MODE 0 #endif #ifndef BACKEND_PORT #define BACKEND_PORT 0 #endif #ifndef FRONTEND_PORT #define FRONTEND_PORT 1 #endif #define REASON_ARP_REPLY 0x0 #define REASON_FLOODING 0x1 struct eth_hdr { __be64 dst : 48; __be64 src : 48; __be16 proto; } __attribute__((packed)); struct arp_hdr { __be16 ar_hrd; /* format of hardware address */ __be16 ar_pro; /* format of protocol address */ unsigned char ar_hln; /* length of hardware address */ unsigned char ar_pln; /* length of protocol address */ __be16 ar_op; /* ARP opcode (command) */ __be64 ar_sha : 48; /* sender hardware address */ __be32 ar_sip; /* sender IP address */ __be64 ar_tha : 48; /* target hardware address */ __be32 ar_tip; /* target IP address */ } __attribute__((packed)); // This struct keeps the session ID of the traffic that has currently been // handled by the load balancer. // This is needed in order to perform the reverse proxy algorithm to the return // traffic struct sessions { __be32 ip_src; __be32 ip_dst; __be16 port_src; __be16 port_dst; __be16 proto; } __attribute__((packed)); struct vip { __be32 ip; __be16 port; __be16 proto; __be16 index; // refers to backend's index for that Service(vip) } __attribute__((packed)); struct backend { __be32 ip; __be16 port; __be16 proto; } __attribute__((packed)); /* * This table contains multiple entries for each virtual service (i.e., virtual * IP / protocol / port). * When 'index' = 0, the value in the hash map is actually not a couple * IP address / port but the number of backends (also called 'pool size') * associated to that virtual service. * Then, for following entries (i.e., when 'index' > 0), the * 'struct backend' keeps the actual data (IP/port) for that backend. * * Example: * VIP 1, index 0 -> Number of backends: 4 * VIP 1, index 1 -> Backend 2 * VIP 1, index 2 -> Backend 1 * VIP 1, index 3 -> Backend 2 * VIP 1, index 4 -> Backend 1 * * VIP 2, index 0 -> Number of backends: 2 * VIP 2, index 1 -> Backend 1 * VIP 2, index 2 -> Backend 1 * * where VIP 1 has 4 backends and VIP2 has 2 backend. * * The number of backend in this table may be different from the number of * actual servers in order to keep session affinity when a server is * added/removed, without having to move the traffic from a backend#1 * to a backend #2 (which will break the TCP session) * * The load balancing algorith will select the proper backend based on an hash * on the most significant fields (i.e., session id) of the packet: * * __u32 backend_id = session_hash % pool_size + 1; * * where 'pool_size' is 4 for VIP 1. */ BPF_TABLE("hash", struct vip, struct backend, services, MAX_SERVICES); /* * Keeps the sessions handled by the load balancer in this table. This is * needed to translate the session ID back for return traffic. * __u32: key (hash the translated session: Hash(ipS | ipD=BCK | pS | pD | * pro) ) * struct vip: value (virtual service ID, to be used to translate * the return traffic) * * If there's a match, the (return) source IP address/port is translated with * the VIP; if there is no match, the traffic is left untouched. * Note that the hash is calculated, in both directions, using the IP.dst * of the backend, not the original one (virtual IP address of the service). */ BPF_TABLE("lru_hash", __u32, struct vip, hash_session, MAX_SESSIONS); enum { FROM_FRONTEND = 0, FROM_BACKEND = 1, }; struct src_ip_r_key { u32 netmask_len; __be32 network; }; struct src_ip_r_value { u32 sense; u32 net; // host network byte order u32 mask; // host network byte order }; BPF_F_TABLE("lpm_trie", struct src_ip_r_key, struct src_ip_r_value, src_ip_rewrite, MAX_SERVICES, BPF_F_NO_PREALLOC); BPF_TABLE("hash", struct backend, struct vip, backend_to_service, MAX_SERVICES); BPF_TABLE("hash", __be32, u16, ip_to_frontend_port, MAX_FRONTENDS); /* * This function is used to get the backend ip after the LoadBalancing. * For each packet that handled by the load balancer, we save the hash of * the session in the session table, to be used for the return traffic * (reverse proxy). */ static inline struct backend *get_bck_ip(struct CTXTYPE *ctx, __be32 ip_src, __be32 ip_dst, __be16 port_src, __be16 port_dst, __be16 proto, __u32 pool_size) { // lookup in the sessions_table struct sessions sessions_key = {}; sessions_key.ip_src = ip_src; sessions_key.ip_dst = ip_dst; sessions_key.port_src = port_src; sessions_key.port_dst = port_dst; sessions_key.proto = proto; if (!pool_size) { return 0; } // calculate the hashed session key u32 check = jhash((const void *)&sessions_key, sizeof(struct sessions), JHASH_INITVAL); // select the backend id __u32 id = check % pool_size + 1; struct vip v_key = {}; v_key.ip = ip_dst; v_key.port = port_dst; v_key.proto = proto; v_key.index = id; pcn_log( ctx, LOG_TRACE, "Selected backend index for the service - (ip: %I, port: %P, proto: 0x%04x) (index: %d)", ip_dst, port_dst, proto, id ); // Now, from the backend ID, let's get the actual backend server (IP/port) struct backend *bck_value = services.lookup(&v_key); if (!bck_value) { pcn_log( ctx, LOG_ERR, "Failed to retrieve backend for the service - (ip: %I, port: %P, proto: 0x%04x) (index: %d)", ip_dst, port_dst, proto, id ); return 0; } pcn_log(ctx, LOG_TRACE, "Retrieved backend for the given index - (index: %d) (be_ip: %I, be_port: %P)", id, bck_value->ip, bck_value->port ); // check if src ip rewrite applies for this packet, if yes, do not create a // new entry in the session table struct src_ip_r_key k = {32, ip_dst}; struct src_ip_r_value *v1 = src_ip_rewrite.lookup(&k); if (v1) { return bck_value; } // Calculate a second hash on the session, but this time we use the backend IP sessions_key.ip_dst = bck_value->ip; // backend ip address sessions_key.port_dst = bck_value->port; // backend port if (proto == ntohs(IPPROTO_ICMP)) { sessions_key.port_dst = port_dst; sessions_key.port_src = port_src; } check = jhash((const void *)&sessions_key, sizeof(struct sessions), JHASH_INITVAL); struct vip v = {}; v.ip = ip_dst; v.port = port_dst; v.proto = proto; v.index = 0; // update the session table with this entry. If the entry already exists, // nothing happens. // if the entry doesn't exist, it is added to the list hash_session.update(&check, &v); // hash-vip return bck_value; } static inline void checksum(struct CTXTYPE *ctx, __u16 old_port, __u16 new_port, __u32 old_dip, __u32 new_dip, __u32 old_sip, __u32 new_sip, __u32 flag) { pcn_l3_csum_replace(ctx, IP_CSUM_OFFSET, old_dip, new_dip, 4); pcn_l4_csum_replace(ctx, flag, old_port, new_port, 2); pcn_l4_csum_replace(ctx, flag, old_dip, new_dip, 4 | IS_PSEUDO); if (new_sip != 0) { pcn_l3_csum_replace(ctx, IP_CSUM_OFFSET, old_sip, new_sip, 4); pcn_l4_csum_replace(ctx, flag, old_sip, new_sip, 4 | IS_PSEUDO); } } static inline int send_to_frontend(struct CTXTYPE *ctx, struct pkt_metadata *md, __be32 ip_daddr) { if (SINGLE_PORT_MODE) { pcn_log(ctx, LOG_TRACE, "Sent pkt to the FRONTEND port - (out_port: %d)", FRONTEND_PORT); return pcn_pkt_redirect(ctx, md, FRONTEND_PORT); } u16 *fe_port = ip_to_frontend_port.lookup(&ip_daddr); if (!fe_port) { pcn_log(ctx, LOG_ERR, "Failed FRONTEND port lookup - (ip_dst: %I)", ip_daddr); return pcn_pkt_drop(ctx, md); } pcn_log( ctx, LOG_TRACE, "Sent pkt to the FRONTEND port associated with the destination - (ip_dst: %I) (out_port: %d)", ip_daddr, *fe_port ); return pcn_pkt_redirect(ctx, md, *fe_port); } static __always_inline int handle_rx(struct CTXTYPE *ctx, struct pkt_metadata *md) { __u16 source = 0; __u16 dest = 0; __u16 ip_proto = 0; __be32 l4csum_offset = 0; void *data = (void *)(long)ctx->data; void *data_end = (void *)(long)ctx->data_end; struct eth_hdr *eth = data; if (data + sizeof(*eth) > data_end) { pcn_log(ctx, LOG_TRACE, "Dropped Ethernet pkt - (in_port: %d) (reason: inconsistent_size)", md->in_port); return RX_DROP; } switch (eth->proto) { case htons(ETH_P_IP): goto IP; // ipv4 packet case htons(ETH_P_ARP): goto ARP; // arp packet default: goto NOIP; } IP:; struct iphdr *ip = data + sizeof(struct eth_hdr); if (data + sizeof(struct eth_hdr) + sizeof(struct iphdr) > data_end) { pcn_log(ctx, LOG_TRACE, "Dropped IP pkt - (in_port: %d) (reason: inconsistent_size)", md->in_port); return RX_DROP; } struct udphdr *udp = data + sizeof(struct eth_hdr) + sizeof(struct iphdr); struct tcphdr *tcp = data + sizeof(struct eth_hdr) + sizeof(struct iphdr); struct icmphdr *icmp = data + sizeof(struct eth_hdr) + sizeof(struct iphdr); __u32 old_ip = ip->daddr; __u32 new_ip = ip->daddr; __u32 old_sip = ip->saddr; __u32 new_sip = 0; switch (ip->protocol) { case IPPROTO_ICMP: goto ICMP; case IPPROTO_UDP: goto UDP; case IPPROTO_TCP: goto TCP; default: pcn_log(ctx, LOG_TRACE, "Dropped IP pkt - (in_port: %d) (reason: unsupported_type) (ip_proto: %d)", md->in_port, ip->protocol); return RX_DROP; } ICMP: if (data + sizeof(*eth) + sizeof(*ip) + sizeof(*icmp) > data_end) { pcn_log(ctx, LOG_TRACE, "Dropped ICMP pkt - (in_port: %d) (reason: inconsistent_size)", md->in_port); return RX_DROP; } // Only manage ICMP Request and Reply if (!((icmp->type == ICMP_ECHO) || (icmp->type == ICMP_ECHOREPLY))) { pcn_log(ctx, LOG_TRACE, "Dropped ICMP pkt - (in_port: %d) (reason: unsupported_type) (icmp_type: %d)", md->in_port, icmp->type); return RX_DROP; } source = icmp->un.echo.id; dest = 0x0; ip_proto = htons(IPPROTO_ICMP); pcn_log(ctx, LOG_DEBUG, "Received ICMP pkt - (ip_src: %I, ip_dst: %I)", ip->saddr, ip->daddr); l4csum_offset = ICMP_CSUM_OFFSET; goto LB; UDP: if (data + sizeof(*eth) + sizeof(*ip) + sizeof(*udp) > data_end) { pcn_log(ctx, LOG_TRACE, "Dropped UDP pkt - (in_port: %d) (reason: inconsistent_size)", md->in_port); return RX_DROP; } pcn_log(ctx, LOG_TRACE, "Received UDP pkt - (src: %I:%P, dst: %I:%P)", ip->saddr, udp->source, ip->daddr, udp->dest); source = udp->source; dest = udp->dest; ip_proto = htons(IPPROTO_UDP); l4csum_offset = UDP_CSUM_OFFSET; goto LB; TCP: if (data + sizeof(*eth) + sizeof(*ip) + sizeof(*tcp) > data_end) { pcn_log(ctx, LOG_TRACE, "Dropped TCP pkt - (in_port: %d) (reason: inconsistent_size)", md->in_port); return RX_DROP; } pcn_log(ctx, LOG_TRACE, "Received TCP pkt - (src: %I:%P, dst: %I:%P)", ip->saddr, tcp->source, ip->daddr, tcp->dest); source = tcp->source; dest = tcp->dest; ip_proto = htons(IPPROTO_TCP); l4csum_offset = TCP_CSUM_OFFSET; goto LB; LB:; __u32 old_port = dest; __u32 new_port = dest; // Currently, the "backend port" is the one connected to the backends // So, this packet is coming from a frontend and is returning to the // originating Pod. if (md->in_port != BACKEND_PORT) { pcn_log(ctx, LOG_TRACE, "Received pkt is from a FRONTEND port - (in_port %d)", md->in_port); struct vip v_key = {}; v_key.ip = ip->daddr; v_key.port = dest; v_key.proto = ip_proto; v_key.index = 0; // Look for the destination IP address in the map (with index=0) // If there's a match, it means this is a VIP, so we need to apply the LB // logic // If doesn't match, just send the packet as is (no need to load balance) struct backend *backend_value = services.lookup(&v_key); // The IP destination address is not a virtual service. Let's forward the // packet as is. if (!backend_value) { pcn_log(ctx, LOG_TRACE, "Failed service lookup: redirected as is to BACKEND port - (out_port: %d)", BACKEND_PORT); return pcn_pkt_redirect(ctx, md, BACKEND_PORT); } // Return the proper backend for this packet struct backend *bck_value = get_bck_ip(ctx, ip->saddr, ip->daddr, source, dest, ip_proto, backend_value->port); if (!bck_value) { pcn_log(ctx, LOG_TRACE, "Dropped pkt from FRONTEND port - (in_port: %d) (reason: failed_bck_lookup)", md->in_port); return RX_DROP; } ip->daddr = bck_value->ip; // should we rewrite the src ip? struct src_ip_r_key k = {32, ip->saddr}; struct src_ip_r_value *v = src_ip_rewrite.lookup(&k); if (v && v->sense == FROM_FRONTEND) { ip->saddr &= bpf_htonl(v->mask); ip->saddr |= bpf_htonl(v->net); new_sip = ip->saddr; } pcn_log(ctx, LOG_TRACE, "Pkt DNATted and redirected to BACKEND port - (src: %I:%P, new_dst: %I:%P)", ip->saddr, source, bck_value->ip, bck_value->port); // We are using l4csum_offset here, since it is equivalent of the protocol if (l4csum_offset == TCP_CSUM_OFFSET) { tcp->dest = bck_value->port; checksum(ctx, old_port, bck_value->port, old_ip, bck_value->ip, old_sip, new_sip, TCP_CSUM_OFFSET); } else if (l4csum_offset == UDP_CSUM_OFFSET) { udp->dest = bck_value->port; checksum(ctx, old_port, bck_value->port, old_ip, bck_value->ip, old_sip, new_sip, UDP_CSUM_OFFSET); } else { pcn_log(ctx, LOG_TRACE, "Translated existing ICMP session - (old_ip: %I, new_ip: %I)", new_ip, ip->daddr); pcn_l3_csum_replace(ctx, IP_CSUM_OFFSET, old_ip, bck_value->ip, 4); } return pcn_pkt_redirect(ctx, md, BACKEND_PORT); } else { // The packet is in its way back from the virtual servers. Coming // from the BACKEND port /* * if src is srrIpRewrite * CHANGE * else * SESSION TABLE */ pcn_log(ctx, LOG_TRACE, "Received pkt is from the BACKEND port - (in_port %d)", md->in_port); __u32 dst_ip_ = ip->daddr; // Lookup into srcIpRewrite map by backend ip (ip->daddr) // Hit: change src -> VIP and dst -> bck_ip_old // Miss: check if it is in the session table struct src_ip_r_key k = {32, ip->daddr}; struct src_ip_r_value *v = src_ip_rewrite.lookup(&k); if (v && v->sense == FROM_BACKEND) { struct backend key = {.ip = ip->saddr, .port = source, .proto = ip_proto}; struct vip *vip_v = backend_to_service.lookup(&key); if (!vip_v) { pcn_log(ctx, LOG_TRACE, "Dropped pkt from BACKEND port - (in_port: %d) (reason: failed_rev_bck_lookup)", md->in_port); return RX_DROP; } old_ip = ip->daddr; old_sip = ip->saddr; ip->daddr &= bpf_htonl(v->mask); ip->daddr |= bpf_htonl(v->net); ip->saddr = vip_v->ip; new_sip = vip_v->ip; new_ip = ip->daddr; new_port = vip_v->port; pcn_log(ctx, LOG_TRACE, "Found SrcIpRewrite: translation - (src: %I, dst: %I) (new_src: %I, new_dst: %I)", old_sip, old_ip, new_sip, new_ip); } else { struct sessions sessions_key = {}; sessions_key.ip_src = ip->daddr; sessions_key.ip_dst = ip->saddr; sessions_key.port_src = dest; sessions_key.port_dst = source; sessions_key.proto = ip_proto; if (ip_proto == ntohs(IPPROTO_ICMP)) { sessions_key.port_dst = dest; sessions_key.port_src = source; } __u32 check = jhash((const void *)&sessions_key, sizeof(struct sessions), JHASH_INITVAL); pcn_log(ctx, LOG_TRACE, "Check in session table - (session_id: %lu)", check); // Let's check if the this session is present in the session table struct vip *rev_proxy = hash_session.lookup(&check); // If this (return) packet belongs to a session that was handled by the // LB, // we have to translate IP addresses back to their original value if (!rev_proxy) { pcn_log(ctx, LOG_TRACE, "Failed session lookup: trying to redirect to a proper FRONTEND port"); return send_to_frontend(ctx, md, ip->daddr); } old_ip = ip->saddr; ip->saddr = rev_proxy->ip; new_ip = rev_proxy->ip; new_port = rev_proxy->port; } u16 fe_port; if (SINGLE_PORT_MODE) fe_port = FRONTEND_PORT; else { __be32 fe_ip = ip->daddr; u16 *fe_port_ptr = ip_to_frontend_port.lookup(&fe_ip); if (!fe_port_ptr) { pcn_log(ctx, LOG_ERR, "Dropped packet from BACKEND port - (in_port: %d) (reason: failed_frontend_port_lookup", md->in_port); return RX_DROP; } fe_port = *fe_port_ptr; } pcn_log( ctx, LOG_TRACE, "Found FRONTEND port for pkt destination - (dst_ip: %I) (out_port: %d)", ip->daddr, fe_port); if (l4csum_offset == TCP_CSUM_OFFSET) { old_port = tcp->source; tcp->source = new_port; pcn_log(ctx, LOG_TRACE, "Translated existing TCP session - (new_src: %I:%P, dst: %I:%P)", new_ip, tcp->source, ip->daddr, dest); checksum(ctx, old_port, new_port, old_ip, new_ip, old_sip, new_sip, TCP_CSUM_OFFSET); } else if (l4csum_offset == UDP_CSUM_OFFSET) { old_port = udp->source; udp->source = new_port; pcn_log(ctx, LOG_TRACE, "Translated existing UDP session - (new_src: %I:%P, dst: %I:%P)", new_ip, new_port, ip->daddr, dest); checksum(ctx, old_port, new_port, old_ip, new_ip, old_sip, new_sip, UDP_CSUM_OFFSET); } else { pcn_log(ctx, LOG_TRACE, "Translated existing ICMP session - (new_ip_src: %I, ip_dst: %I)", new_ip, ip->daddr); pcn_l3_csum_replace(ctx, IP_CSUM_OFFSET, old_ip, new_ip, 4); } pcn_log(ctx, LOG_TRACE, "Redirected pkt to FRONTEND port - (out_port: %d)", fe_port); return pcn_pkt_redirect(ctx, md, fe_port); } ARP:; struct arp_hdr *arp = data + sizeof(*eth); if (data + sizeof(*eth) + sizeof(*arp) > data_end) { pcn_log(ctx, LOG_TRACE, "Dropped ARP pkt - (in_port: %d) (reason: inconsistent_size)", md->in_port); return RX_DROP; } // if the packet comes from the backend port, check if this // is an ARP request for one of the virtual src IPs, if yes, change // it and send to the frontend port if (md->in_port == BACKEND_PORT) { pcn_log(ctx, LOG_TRACE, "Received ARP pkt from BACKEND port - (in_port: %d)", md->in_port); if (arp->ar_op == bpf_htons(ARPOP_REQUEST)) { pcn_log( ctx, LOG_TRACE, "Received ARP pkt is an ARP request - (in_port: %d) (arp_opcode: %d)", md->in_port, bpf_htons(arp->ar_op)); struct src_ip_r_key k = {32, arp->ar_tip}; struct src_ip_r_value *v = src_ip_rewrite.lookup(&k); if (v && v->sense == FROM_BACKEND) { arp->ar_tip &= bpf_htonl(v->mask); arp->ar_tip |= bpf_htonl(v->net); } } return send_to_frontend(ctx, md, arp->ar_tip); } else { pcn_log(ctx, LOG_TRACE, "Received ARP pkt from FRONTEND port - (in_port: %d)", md->in_port); if (arp->ar_op == bpf_htons(ARPOP_REPLY)) { pcn_log( ctx, LOG_TRACE, "Received ARP pkt is an ARP reply - (in_port: %d) (arp_opcode: %d)", md->in_port, arp->ar_op); struct src_ip_r_key k = {32, arp->ar_sip}; struct src_ip_r_value *v = src_ip_rewrite.lookup(&k); if (v && v->sense == FROM_FRONTEND) { // send to the slowpath, it'll send two copies of this // - the original one // - one for the virtual IPs pcn_log(ctx, LOG_TRACE, "Sent received ARP reply to slowpath - (in_port: %d)", md->in_port); pcn_pkt_controller(ctx, md, REASON_ARP_REPLY); return RX_DROP; } } pcn_log(ctx, LOG_TRACE, "Redirected ARP pkt to BACKEND port - (in_port: %d) (out_port: %d)", md->in_port, BACKEND_PORT); return pcn_pkt_redirect(ctx, md, BACKEND_PORT); } NOIP: if (md->in_port == BACKEND_PORT) { if (SINGLE_PORT_MODE) { pcn_log(ctx, LOG_TRACE, "Received non-ip pkt from BACKEND port: redirected to FRONTEND port - (in_port: %d) (proto: 0x%x) (out_port: %d)", md->in_port, bpf_htons(eth->proto), FRONTEND_PORT); return pcn_pkt_redirect(ctx, md, FRONTEND_PORT); } pcn_log(ctx, LOG_TRACE, "Received non-ip pkt from BACKEND port: sent to slowpath - (in_port: %d) (proto: 0x%x)", md->in_port, bpf_htons(eth->proto)); return pcn_pkt_controller(ctx, md, REASON_FLOODING); } else { pcn_log(ctx, LOG_TRACE, "Received non-ip pkt from FRONTEND port: redirected to BACKEND port - (in_port: %d) (proto: 0x%x) (out_port: %d)", md->in_port, bpf_htons(eth->proto), BACKEND_PORT); return pcn_pkt_redirect(ctx, md, BACKEND_PORT); } return RX_DROP; }
57be7cb09eaa5e861f1eb3e17e4b6af3244fbe65
e1cddfd754d952134e72dfd03522c5ea4fb6008e
/src/tools/perftool/delsvec.c
d49ba98b94da6ea71aae090aa6eeef67eb2a9283
[ "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
9,136
c
delsvec.c
/* *------------------------------------------------------------------ * Copyright (c) 2006-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. */ /* Break up a delimited string into a vector of substrings */ #include <stdio.h> #include <vppinfra/clib.h> #include <vppinfra/vec.h> #include <vppinfra/hash.h> #include <stdarg.h> /* * #define UNIT_TESTS 1 * #define MATCH_TRACE 1 */ /* * delsvec * break up an input string into a vector of [null-terminated] u8 *'s * * Each supplied delimiter character results in a string in the output * vector, unless the delimiters occur back-to-back. When matched, * a whitespace character in the delimiter consumes an arbitrary * run of whitespace. See the unit tests at the end of this file * for a set of examples. * * Returns a u8 **, or NULL if the input fails to match. It is assumed * that both input and fmt are C strings, not necessarily vectors. * * Output strings are both vectors and proper C strings. */ static u8 **string_cache; static u8 **svec_cache; void delsvec_recycle_this_string (u8 *s) { if (s) { vec_set_len (s, 0); vec_add1 (string_cache, s); } } void delsvec_recycle_this_svec (u8 **svec) { if (svec) { if (svec_cache) { vec_free (svec_cache); } vec_set_len (svec, 0); svec_cache = svec; } } int pvl (char *a) { return vec_len (a); } u8 ** delsvec (void *input_arg, char *fmt) { u8 **rv = 0; int input_index = 0; u8 *this; int dirflag = 0; int i; u8 *input = input_arg; if (svec_cache) { rv = svec_cache; svec_cache = 0; } while (fmt) { dirflag = 0; if (vec_len (string_cache) > 0) { this = string_cache[vec_len (string_cache) - 1]; vec_set_len (string_cache, vec_len (string_cache) - 1); } else this = 0; /* * '*' means one of two things: match the rest of the input, * or match as many characters as possible */ if (fmt[0] == '*') { fmt++; dirflag = 1; /* * no more format: eat rest of string... */ if (!fmt[0]) { for (; input[input_index]; input_index++) vec_add1 (this, input[input_index]); if (vec_len (this)) { vec_add1 (this, 0); #ifdef MATCH_TRACE printf ("final star-match adds: '%s'\n", this); #endif vec_add1 (rv, this); } else { vec_add1 (string_cache, this); } return (rv); } } /* * Left-to-right scan, adding chars until next delimiter char * appears. */ if (!dirflag) { while (input[input_index]) { if (input[input_index] == fmt[0]) { /* If we just (exact) matched a whitespace delimiter */ if (fmt[0] == ' ') { /* scan forward eating whitespace */ while (input[input_index] == ' ' || input[input_index] == '\t' || input[input_index] == '\n') input_index++; input_index--; } goto found; } /* If we're looking for whitespace */ if (fmt[0] == ' ') { /* and we have whitespace */ if (input[input_index] == ' ' || input[input_index] == '\t' || input[input_index] == '\n') { /* scan forward eating whitespace */ while (input[input_index] == ' ' || input[input_index] == '\t' || input[input_index] == '\n') { input_index++; } input_index--; goto found; } } /* Not a delimiter, save it */ vec_add1 (this, input[input_index]); input_index++; } /* * Fell off the wagon, clean up and bail out */ bail: #ifdef MATCH_TRACE printf ("failed, fmt[0] = '%c', input[%d]='%s'\n", fmt[0], input_index, &input[input_index]); #endif delsvec_recycle_this_string (this); for (i = 0; i < vec_len (rv); i++) delsvec_recycle_this_string (rv[i]); delsvec_recycle_this_svec (rv); return (0); found: /* * Delimiter matched */ input_index++; fmt++; /* * If we actually accumulated non-delimiter characters, * add them to the result vector */ if (vec_len (this)) { vec_add1 (this, 0); #ifdef MATCH_TRACE printf ("match: add '%s'\n", this); #endif vec_add1 (rv, this); } else { vec_add1 (string_cache, this); } } else { /* * right-to-left scan, '*' not at * the end of the delimiter string */ i = input_index; while (input[++i]) ; /* scan forward */ i--; while (i > input_index) { if (input[i] == fmt[0]) goto found2; if (fmt[0] == ' ' || fmt[0] == '\t' || fmt[0] == '\n') { if (input[i] == ' ' || input[i] == '\t' || input[i] == '\n') goto found2; } i--; } goto bail; found2: for (; input_index < i; input_index++) { vec_add1 (this, input[input_index]); } input_index++; fmt++; vec_add1 (this, 0); #ifdef MATCH_TRACE printf ("inner '*' match: add '%s'\n", this); #endif vec_add1 (rv, this); } } return (rv); } #ifdef UNIT_TESTS typedef struct utest_ { char *string; char *fmt; } utest_t; utest_t tests[] = { #ifdef NOTDEF { "Dec 7 08:56", " :*" }, { "Dec 17 08:56", " :*" }, { "Dec 7 08:56:41.239 install/inst_repl 0/9/CPU0 t1 [40989] File " "List:Successfully blobbified file list. Took 1 milliseconds", " ::. / // [] *" }, { "RP/0/9/CPU0:Dec 7 08:55:28.550 : sam_server[291]: SAM backs up digest " "list to memory file", "///: ::. : []: *" }, /* Expected to fail */ { "Dec 7 08:56:41.239 install/inst_repl 0/9/CPU0 t1 [40989] File " "List:Successfully blobbified file list. Took 1 milliseconds", "///: ::. : : *" }, /* Expected to fail */ { "RP/0/9/CPU0:Dec 7 08:55:28.550 : sam_server[291]: SAM backs up digest " "list to memory file", " ::. / // [] *" }, { "THIS that and + theother", "*+ *" }, { "Dec 12 15:33:07.103 ifmgr/errors 0/RP0/CPU0 3# t2 Failed to open IM " "connection: No such file or directory", " ::. / // *" }, { "Dec 16 21:43:47.328 ifmgr/bulk 0/3/CPU0 t8 Bulk DPC async download " "complete. Partitions 1, node_count 1, total_out 0, out_offset 0, " "out_expected 0: No error", " ::. / // *" }, { "t:0x53034bd6 CPU:00 PROCESS :PROCCREATE_NAME", ": : :*" }, { " pid:1", " *" }, { "t:0x53034cbb CPU:00 THREAD :THCREATE pid:1 tid:1", ": : : pid: tid:*" }, { "t:0x5303f950 CPU:00 COMM :REC_PULSE scoid:0x40000003 pid:364659", ": : : *" }, { "/hfr-base-3.3.85/lib/libttyconnection.dll 0xfc000000 0x0000306c " "0xfc027000 0x000001c8 1", " *" }, { "Feb 28 02:38:26.123 seqtrace 0/1/CPU0 t8 " ":msg_receive:ifmgr/t8:IMC_MSG_MTU_UPDATE:ppp_ma/t1", " ::. // ::::*" }, { "Feb 28 02:38:26.123 seqtrace 0/1/CPU0 t8 " ":msg_send_event:call:ifmgr/t8:124/0:cdp/t1", " ::. // :msg_send_event::::*" }, { "Feb 28 02:38:26.125 seqtrace 0/1/CPU0 t1 " ":msg_receive_event:cdp/t1:124/0", " ::. // :msg_receive_event::*" } { "t:0x645dd86d CPU:00 USREVENT:EVENT:100, d0:0x00000002 d1:0x00000000", ": : USREVENT:EVENT:, d0: *" } { "t:0x5303f950 CPU:00 COMM :REC_PULSE scoid:0x40000003 pid:364659", ": : : *" }, { "t:0x2ccf9f5a CPU:00 INT_ENTR:0x80000000 (-2147483648) " "IP:0x002d8b18", ": : INT_ENTR: IP:*" } { "t:0xd473951c CPU:00 KER_EXIT:SCHED_GET/88 ret_val:2 sched_priority:10", ": : KER_EXIT:SCHED_GET : sched_priority:*" } { "t:0x00000123 CPU:01 SYSTEM :FUNC_ENTER thisfn:0x40e62048 " "call_site:0x00000000", ": : SYSTEM :FUNC_ thisfn: *" }, { "t:0x5af8de95 CPU:00 INT_HANDLER_ENTR:0x0000004d (77) PID:8200 " "IP:0x00000000 AREA:0x0bf9b290", ": : INT_HANDLER_*" }, #endif { "t:0x6d1ff92f CPU:00 CONTROL: BUFFER sequence = 1053, num_events = 714", ": : CONTROL*" }, { "t:0x6d1ff92f CPU:00 CONTROL :TIME msb:0x0000003c lsb(offset):0x6d1ff921", ": : CONTROL*" }, }; int main (int argc, char **argv) { int i, j; u8 **svec; for (j = 0; j < ARRAY_LEN (tests); j++) { printf ("input string: '%s'\n", tests[j].string); printf ("delimiter arg: '%s'\n", tests[j].fmt); printf ("parse trace:\n"); svec = delsvec (tests[j].string, tests[j].fmt); if (!svec) { printf ("index %d failed\n", j); continue; } printf ("%d substring vectors\n", vec_len (svec)); for (i = 0; i < vec_len (svec); i++) { printf ("[%d]: '%s'\n", i, svec[i]); } printf ("-------------------\n"); } exit (0); } #endif
8a2dfd0d119fddc9305d2be8fdb72d34d226b4a9
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/third_party/intel/tsxldtrkintrin.internal.h
5a15093784b861bfca63da0f10447cf92e8dfbd7
[ "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
779
h
tsxldtrkintrin.internal.h
/* clang-format off */ #if defined(__x86_64__) && !(__ASSEMBLER__ + __LINKER__ + 0) #ifndef _X86GPRINTRIN_H_INCLUDED # error "Never use <tsxldtrkintrin.h> directly; include <x86gprintrin.h> instead." #endif #ifndef _TSXLDTRKINTRIN_H_INCLUDED #define _TSXLDTRKINTRIN_H_INCLUDED #if !defined(__TSXLDTRK__) #pragma GCC push_options #pragma GCC target("tsxldtrk") #define __DISABLE_TSXLDTRK__ #endif extern __inline void __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _xsusldtrk (void) { __builtin_ia32_xsusldtrk (); } extern __inline void __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _xresldtrk (void) { __builtin_ia32_xresldtrk (); } #ifdef __DISABLE_TSXLDTRK__ #undef __DISABLE_TSXLDTRK__ #pragma GCC pop_options #endif #endif #endif
31fec303e9a20327569697f9033de7d8d681485b
fb47ab6337a71029dee71933e449cf7f6805fc0f
/external/platform/cc13xx/cc13xxware/driverlib/aon_batmon.h
83062726f5f33ce08dd9f83b27920529a1218770
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
littlekernel/lk
7e7ba50b87b1f2e0b6e2f052c59249825c91975b
30dc320054f70910e1c1ee40a6948ee99672acec
refs/heads/master
2023-09-02T00:47:52.203963
2023-06-21T22:42:35
2023-06-21T22:42:35
3,058,456
3,077
618
MIT
2023-08-30T09:41:31
2011-12-27T19:19:36
C
UTF-8
C
false
false
10,200
h
aon_batmon.h
/****************************************************************************** * Filename: aon_batmon.h * Revised: 2015-07-16 12:12:04 +0200 (Thu, 16 Jul 2015) * Revision: 44151 * * Description: Defines and prototypes for the AON Battery and Temperature * Monitor * * Copyright (c) 2015, Texas Instruments Incorporated * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3) Neither the name of the ORGANIZATION nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ //***************************************************************************** // //! \addtogroup aon_group //! @{ //! \addtogroup aonbatmon_api //! @{ // //***************************************************************************** #ifndef __AON_BATMON_H__ #define __AON_BATMON_H__ //***************************************************************************** // // If building with a C++ compiler, make all of the definitions in this header // have a C binding. // //***************************************************************************** #ifdef __cplusplus extern "C" { #endif #include <stdbool.h> #include <stdint.h> #include <inc/hw_types.h> #include <inc/hw_memmap.h> #include <inc/hw_aon_batmon.h> #include <driverlib/debug.h> //***************************************************************************** // // API Functions and prototypes // //***************************************************************************** //***************************************************************************** // //! \brief Enable the temperature and battery monitoring. //! //! This function will enable the measurements of the temperature and the //! battery voltage. //! //! To speed up the measurement of the levels the measurement can be enabled //! before configuring the battery and temperature settings. When all of the //! AON_BATMON registers are configured, the calculation of the voltage and //! temperature values can be enabled (the measurement will now take //! effect/propagate to other blocks). //! //! It is possible to enable both at the same time, after the AON_BATMON //! registers are configured, but then the first values will be ready at a //! later point compared to the scenario above. //! //! \note Temperature and battery voltage measurements are not done in //! parallel. The measurement cycle is controlled by a hardware Finite State //! Machine. First the temperature and then the battery voltage each taking //! one cycle to complete. However, if the comparator measuring the battery //! voltage detects a change on the reference value, a new measurement of the //! battery voltage only is performed immediately after. This has no impact on //! the cycle count. //! //! \return None // //***************************************************************************** __STATIC_INLINE void AONBatMonEnable(void) { // // Enable the measurements. // HWREG(AON_BATMON_BASE + AON_BATMON_O_CTL) = AON_BATMON_CTL_CALC_EN | AON_BATMON_CTL_MEAS_EN; } //***************************************************************************** // //! \brief Disable the temperature and battery monitoring. //! //! This function will disable the measurements of the temperature and the //! battery voltage. //! //! \return None // //***************************************************************************** __STATIC_INLINE void AONBatMonDisable(void) { // // Disable the measurements. // HWREG(AON_BATMON_BASE + AON_BATMON_O_CTL) = 0; } //***************************************************************************** // //! \brief Get the current temperature measurement as a signed value in Deg Celsius. //! //! This function returns an calibrated and rounded value in degree Celsius. //! The temperature measurements are updated every cycle. //! //! \note The temperature drifts slightly depending on the battery voltage. //! This function compensates for this drift and returns a calibrated temperature. //! //! \note Use the function AONBatMonNewTempMeasureReady() to test for a new measurement. //! //! \return Returns signed integer part of temperature in Deg C (-256 .. +255) //! //! \sa AONBatMonNewTempMeasureReady() // //***************************************************************************** int32_t AONBatMonTemperatureGetDegC( void ); //***************************************************************************** // //! \brief Get the battery monitor measurement. //! //! This function will return the current battery monitor measurement. //! The battery voltage measurements are updated every cycle. //! //! \note The returned value is NOT sign-extended! //! //! \note Use the function \ref AONBatMonNewBatteryMeasureReady() to test for //! a change in measurement. //! //! \return Returns the current battery monitor value of the battery voltage //! measurement in a <int.frac> format size <3.8> in units of volt. //! //! \sa AONBatMonNewBatteryMeasureReady() // //***************************************************************************** __STATIC_INLINE uint32_t AONBatMonBatteryVoltageGet(void) { uint32_t ui32CurrentBattery; ui32CurrentBattery = HWREG(AON_BATMON_BASE + AON_BATMON_O_BAT); // // Return the current battery voltage measurement. // return (ui32CurrentBattery >> AON_BATMON_BAT_FRAC_S); } //***************************************************************************** // //! \brief Check if battery monitor measurement has changed. //! //! This function checks if a new battery monitor value is available. If the //! measurement value has \b changed since last clear the function returns \c true. //! //! If the measurement has changed the function will automatically clear the //! status bit. //! //! \note It is always possible to read out the current value of the //! battery level using AONBatMonBatteryVoltageGet() but this function can be //! used to check if the measurement has changed. //! //! \return Returns \c true if the measurement value has changed and \c false //! otherwise. //! //! \sa AONBatMonNewTempMeasureReady(), AONBatMonBatteryVoltageGet() // //***************************************************************************** __STATIC_INLINE bool AONBatMonNewBatteryMeasureReady(void) { bool bStatus; // // Check the status bit. // bStatus = HWREG(AON_BATMON_BASE + AON_BATMON_O_BATUPD) & AON_BATMON_BATUPD_STAT ? true : false; // // Clear status bit if set. // if(bStatus) { HWREG(AON_BATMON_BASE + AON_BATMON_O_BATUPD) = 1; } // // Return status. // return (bStatus); } //***************************************************************************** // //! \brief Check if temperature monitor measurement has changed. //! //! This function checks if a new temperature value is available. If the //! measurement value has \b changed since last clear the function returns \c true. //! //! If the measurement has changed the function will automatically clear the //! status bit. //! //! \note It is always possible to read out the current value of the //! temperature using \ref AONBatMonTemperatureGetDegC() //! but this function can be used to check if the measurement has changed. //! //! \return Returns \c true if the measurement value has changed and \c false //! otherwise. //! //! \sa AONBatMonNewBatteryMeasureReady(), AONBatMonTemperatureGetDegC() // //***************************************************************************** __STATIC_INLINE bool AONBatMonNewTempMeasureReady(void) { bool bStatus; // // Check the status bit. // bStatus = HWREG(AON_BATMON_BASE + AON_BATMON_O_TEMPUPD) & AON_BATMON_TEMPUPD_STAT ? true : false; // // Clear status bit if set. // if(bStatus) { HWREG(AON_BATMON_BASE + AON_BATMON_O_TEMPUPD) = 1; } // // Return status. // return (bStatus); } //***************************************************************************** // // Mark the end of the C bindings section for C++ compilers. // //***************************************************************************** #ifdef __cplusplus } #endif #endif // __AON_BATMON_H__ //***************************************************************************** // //! Close the Doxygen group. //! @} //! @} // //*****************************************************************************
1d25b57ab845947abcc27ee58cd617161a09f338
ac927e79d8c3fb7e1be6d4eb316ddea5920b1a60
/src/base/abc/abcUtil.c
88a16e7b629bb020b950cac99ee9f4b33f6f63c5
[ "MIT-Modern-Variant" ]
permissive
berkeley-abc/abc
f4cb3886bd4c34448b1b5c154fbed96f6095e6e1
756e21a81de1fe799df8189f77c4ea34399d2c8e
refs/heads/master
2023-08-22T17:11:30.017600
2023-08-20T08:50:59
2023-08-20T08:50:59
124,750,053
727
336
NOASSERTION
2023-09-13T18:24:40
2018-03-11T11:33:37
C
UTF-8
C
false
false
106,139
c
abcUtil.c
/**CFile**************************************************************** FileName [abcUtil.c] SystemName [ABC: Logic synthesis and verification system.] PackageName [Network and node package.] Synopsis [Various utilities.] Author [Alan Mishchenko] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - June 20, 2005.] Revision [$Id: abcUtil.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $] ***********************************************************************/ #include "abc.h" #include "base/main/main.h" #include "map/mio/mio.h" #include "bool/dec/dec.h" #include "opt/fxu/fxu.h" #include "aig/miniaig/ndr.h" #ifdef ABC_USE_CUDD #include "bdd/extrab/extraBdd.h" #endif ABC_NAMESPACE_IMPL_START //////////////////////////////////////////////////////////////////////// /// DECLARATIONS /// //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// FUNCTION DEFINITIONS /// //////////////////////////////////////////////////////////////////////// /**Function************************************************************* Synopsis [Frees one attribute manager.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void * Abc_NtkAttrFree( Abc_Ntk_t * pNtk, int Attr, int fFreeMan ) { void * pUserMan; Vec_Att_t * pAttrMan; pAttrMan = (Vec_Att_t *)Vec_PtrEntry( pNtk->vAttrs, Attr ); Vec_PtrWriteEntry( pNtk->vAttrs, Attr, NULL ); pUserMan = Vec_AttFree( pAttrMan, fFreeMan ); return pUserMan; } /**Function************************************************************* Synopsis [Order CI/COs.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkOrderCisCos( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj, * pTerm; int i, k; Vec_PtrClear( pNtk->vCis ); Vec_PtrClear( pNtk->vCos ); Abc_NtkForEachPi( pNtk, pObj, i ) Vec_PtrPush( pNtk->vCis, pObj ); Abc_NtkForEachPo( pNtk, pObj, i ) Vec_PtrPush( pNtk->vCos, pObj ); Abc_NtkForEachBox( pNtk, pObj, i ) { if ( Abc_ObjIsLatch(pObj) ) continue; Abc_ObjForEachFanin( pObj, pTerm, k ) Vec_PtrPush( pNtk->vCos, pTerm ); Abc_ObjForEachFanout( pObj, pTerm, k ) Vec_PtrPush( pNtk->vCis, pTerm ); } Abc_NtkForEachBox( pNtk, pObj, i ) { if ( !Abc_ObjIsLatch(pObj) ) continue; Abc_ObjForEachFanin( pObj, pTerm, k ) Vec_PtrPush( pNtk->vCos, pTerm ); Abc_ObjForEachFanout( pObj, pTerm, k ) Vec_PtrPush( pNtk->vCis, pTerm ); } } /**Function************************************************************* Synopsis [Reads the number of cubes of the node.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetCubeNum( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode; int i, nCubes = 0; assert( Abc_NtkHasSop(pNtk) ); Abc_NtkForEachNode( pNtk, pNode, i ) { if ( Abc_NodeIsConst(pNode) ) continue; assert( pNode->pData ); nCubes += Abc_SopGetCubeNum( (char *)pNode->pData ); } return nCubes; } /**Function************************************************************* Synopsis [Reads the number of cubes of the node.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetCubePairNum( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode; int i; word nCubes, nCubePairs = 0; assert( Abc_NtkHasSop(pNtk) ); Abc_NtkForEachNode( pNtk, pNode, i ) { if ( Abc_NodeIsConst(pNode) ) continue; assert( pNode->pData ); nCubes = (word)Abc_SopGetCubeNum( (char *)pNode->pData ); if ( nCubes > 1 ) nCubePairs += nCubes * (nCubes - 1) / 2; } return (int)(nCubePairs > (1<<30) ? (1<<30) : nCubePairs); } /**Function************************************************************* Synopsis [Reads the number of literals in the SOPs of the nodes.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetLitNum( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode; int i, nLits = 0; assert( Abc_NtkHasSop(pNtk) ); Abc_NtkForEachNode( pNtk, pNode, i ) { assert( pNode->pData ); nLits += Abc_SopGetLitNum( (char *)pNode->pData ); } return nLits; } /**Function************************************************************* Synopsis [Counts the number of literals in the factored forms.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetLitFactNum( Abc_Ntk_t * pNtk ) { Dec_Graph_t * pFactor; Abc_Obj_t * pNode; int nNodes, i; assert( Abc_NtkHasSop(pNtk) ); nNodes = 0; Abc_NtkForEachNode( pNtk, pNode, i ) { if ( Abc_NodeIsConst(pNode) ) continue; pFactor = Dec_Factor( (char *)pNode->pData ); nNodes += 1 + Dec_GraphNodeNum(pFactor); Dec_GraphFree( pFactor ); } return nNodes; } /**Function************************************************************* Synopsis [Counts the number of nodes with more than 1 reference.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetMultiRefNum( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode; int nNodes, i; assert( Abc_NtkIsStrash(pNtk) ); nNodes = 0; Abc_NtkForEachNode( pNtk, pNode, i ) nNodes += (int)(Abc_ObjFanoutNum(pNode) > 1); return nNodes; } /**Function************************************************************* Synopsis [Reads the number of BDD nodes.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetBddNodeNum( Abc_Ntk_t * pNtk ) { int nNodes = 0; #ifdef ABC_USE_CUDD Abc_Obj_t * pNode; int i; assert( Abc_NtkIsBddLogic(pNtk) ); Abc_NtkForEachNode( pNtk, pNode, i ) { assert( pNode->pData ); if ( Abc_ObjFaninNum(pNode) < 2 ) continue; nNodes += pNode->pData? -1 + Cudd_DagSize( (DdNode *)pNode->pData ) : 0; } #endif return nNodes; } /**Function************************************************************* Synopsis [Reads the number of BDD nodes.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetAigNodeNum( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode; int i, nNodes = 0; assert( Abc_NtkIsAigLogic(pNtk) ); Abc_NtkForEachNode( pNtk, pNode, i ) { assert( pNode->pData ); if ( Abc_ObjFaninNum(pNode) < 2 ) continue; //printf( "%d ", Hop_DagSize( pNode->pData ) ); nNodes += pNode->pData? Hop_DagSize( (Hop_Obj_t *)pNode->pData ) : 0; } return nNodes; } /**Function************************************************************* Synopsis [Reads the number of BDD nodes.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetClauseNum( Abc_Ntk_t * pNtk ) { int nClauses = 0; #ifdef ABC_USE_CUDD extern int Abc_CountZddCubes( DdManager * dd, DdNode * zCover ); Abc_Obj_t * pNode; DdNode * bCover, * zCover, * bFunc; DdManager * dd = (DdManager *)pNtk->pManFunc; int i; assert( Abc_NtkIsBddLogic(pNtk) ); Abc_NtkForEachNode( pNtk, pNode, i ) { assert( pNode->pData ); bFunc = (DdNode *)pNode->pData; bCover = Cudd_zddIsop( dd, bFunc, bFunc, &zCover ); Cudd_Ref( bCover ); Cudd_Ref( zCover ); nClauses += Abc_CountZddCubes( dd, zCover ); Cudd_RecursiveDeref( dd, bCover ); Cudd_RecursiveDerefZdd( dd, zCover ); bCover = Cudd_zddIsop( dd, Cudd_Not(bFunc), Cudd_Not(bFunc), &zCover ); Cudd_Ref( bCover ); Cudd_Ref( zCover ); nClauses += Abc_CountZddCubes( dd, zCover ); Cudd_RecursiveDeref( dd, bCover ); Cudd_RecursiveDerefZdd( dd, zCover ); } #endif return nClauses; } /**Function************************************************************* Synopsis [Computes the area of the mapped circuit.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ double Abc_NtkGetMappedArea( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; double TotalArea; int i; assert( Abc_NtkHasMapping(pNtk) ); TotalArea = 0.0; Abc_NtkForEachNode( pNtk, pObj, i ) { if ( Abc_ObjIsBarBuf(pObj) ) continue; // assert( pObj->pData ); if ( pObj->pData == NULL ) { printf( "Node without mapping is encountered.\n" ); continue; } TotalArea += Mio_GateReadArea( (Mio_Gate_t *)pObj->pData ); // assuming that twin gates follow each other if ( Abc_NtkFetchTwinNode(pObj) ) i++; } return TotalArea; } /**Function************************************************************* Synopsis [Counts the number of exors.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetExorNum( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode; int i, Counter = 0; Abc_NtkForEachNode( pNtk, pNode, i ) Counter += pNode->fExor; return Counter; } /**Function************************************************************* Synopsis [Counts the number of exors.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetMuxNum( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode; int i, Counter = 0; Abc_NtkForEachNode( pNtk, pNode, i ) Counter += Abc_NodeIsMuxType(pNode); return Counter; } /**Function************************************************************* Synopsis [Counts the number of exors.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetBufNum( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode; int i, Counter = 0; Abc_NtkForEachNode( pNtk, pNode, i ) Counter += (Abc_ObjFaninNum(pNode) == 1); return Counter; } /**Function************************************************************* Synopsis [Counts the number of exors.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetLargeNodeNum( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode; int i, Counter = 0; Abc_NtkForEachNode( pNtk, pNode, i ) Counter += (Abc_ObjFaninNum(pNode) > 1); return Counter; } /**Function************************************************************* Synopsis [Returns 1 if it is an AIG with choice nodes.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetChoiceNum( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode; int i, Counter; if ( !Abc_NtkIsStrash(pNtk) ) return 0; Counter = 0; Abc_NtkForEachNode( pNtk, pNode, i ) Counter += Abc_AigNodeIsChoice( pNode ); return Counter; } /**Function************************************************************* Synopsis [Reads the maximum number of fanins.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetFaninMax( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode; int i, nFaninsMax = 0; Abc_NtkForEachNode( pNtk, pNode, i ) { if ( nFaninsMax < Abc_ObjFaninNum(pNode) ) nFaninsMax = Abc_ObjFaninNum(pNode); } return nFaninsMax; } int Abc_NtkGetFanoutMax( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode; int i, nFaninsMax = 0; Abc_NtkForEachNode( pNtk, pNode, i ) { if ( nFaninsMax < Abc_ObjFanoutNum(pNode) ) nFaninsMax = Abc_ObjFanoutNum(pNode); } return nFaninsMax; } /**Function************************************************************* Synopsis [Reads the total number of all fanins.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkGetTotalFanins( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode; int i, nFanins = 0; Abc_NtkForEachNode( pNtk, pNode, i ) nFanins += Abc_ObjFaninNum(pNode); return nFanins; } /**Function************************************************************* Synopsis [Cleans the copy field of all objects.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkCleanCopy( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Abc_NtkForEachObj( pNtk, pObj, i ) pObj->pCopy = NULL; } void Abc_NtkCleanCopy_rec( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Abc_NtkCleanCopy( pNtk ); Abc_NtkForEachBox( pNtk, pObj, i ) Abc_NtkCleanCopy_rec( Abc_ObjModel(pObj) ); } /**Function************************************************************* Synopsis [Cleans the copy field of all objects.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkCleanData( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Abc_NtkForEachObj( pNtk, pObj, i ) pObj->pData = NULL; } /**Function************************************************************* Synopsis [Cleans the copy field of all objects.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkFillTemp( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Abc_NtkForEachObj( pNtk, pObj, i ) pObj->iTemp = -1; } /**Function************************************************************* Synopsis [Counts the number of nodes having non-trivial copies.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkCountCopy( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i, Counter = 0; Abc_NtkForEachObj( pNtk, pObj, i ) { if ( Abc_ObjIsNode(pObj) ) Counter += (pObj->pCopy != NULL); } return Counter; } /**Function************************************************************* Synopsis [Saves copy field of the objects.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Vec_Ptr_t * Abc_NtkSaveCopy( Abc_Ntk_t * pNtk ) { Vec_Ptr_t * vCopies; Abc_Obj_t * pObj; int i; vCopies = Vec_PtrStart( Abc_NtkObjNumMax(pNtk) ); Abc_NtkForEachObj( pNtk, pObj, i ) Vec_PtrWriteEntry( vCopies, i, pObj->pCopy ); return vCopies; } /**Function************************************************************* Synopsis [Loads copy field of the objects.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkLoadCopy( Abc_Ntk_t * pNtk, Vec_Ptr_t * vCopies ) { Abc_Obj_t * pObj; int i; Abc_NtkForEachObj( pNtk, pObj, i ) pObj->pCopy = (Abc_Obj_t *)Vec_PtrEntry( vCopies, i ); } /**Function************************************************************* Synopsis [Cleans the copy field of all objects.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkCleanNext( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Abc_NtkForEachObj( pNtk, pObj, i ) pObj->pNext = NULL; } void Abc_NtkCleanNext_rec( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Abc_NtkCleanNext( pNtk ); Abc_NtkForEachBox( pNtk, pObj, i ) Abc_NtkCleanNext_rec( Abc_ObjModel(pObj) ); } /**Function************************************************************* Synopsis [Cleans the copy field of all objects.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkCleanMarkA( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Abc_NtkForEachObj( pNtk, pObj, i ) pObj->fMarkA = 0; } /**Function************************************************************* Synopsis [Cleans the copy field of all objects.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkCleanMarkB( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Abc_NtkForEachObj( pNtk, pObj, i ) pObj->fMarkB = 0; } /**Function************************************************************* Synopsis [Cleans the copy field of all objects.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkCleanMarkC( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Abc_NtkForEachObj( pNtk, pObj, i ) pObj->fMarkC = 0; } /**Function************************************************************* Synopsis [Cleans the copy field of all objects.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkCleanMarkAB( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Abc_NtkForEachObj( pNtk, pObj, i ) pObj->fMarkA = pObj->fMarkB = 0; } /**Function************************************************************* Synopsis [Cleans the copy field of all objects.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkCleanMarkABC( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Abc_NtkForEachObj( pNtk, pObj, i ) pObj->fMarkA = pObj->fMarkB = pObj->fMarkC = 0; } /**Function************************************************************* Synopsis [Returns the index of the given fanin.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NodeFindFanin( Abc_Obj_t * pNode, Abc_Obj_t * pFanin ) { Abc_Obj_t * pThis; int i; Abc_ObjForEachFanin( pNode, pThis, i ) if ( pThis == pFanin ) return i; return -1; } /**Function************************************************************* Synopsis [Checks if the internal node has CO fanout.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Obj_t * Abc_NodeFindCoFanout( Abc_Obj_t * pNode ) { Abc_Obj_t * pFanout; int i; Abc_ObjForEachFanout( pNode, pFanout, i ) if ( Abc_ObjIsCo(pFanout) ) return pFanout; return NULL; } /**Function************************************************************* Synopsis [Checks if the internal node has CO fanout.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Obj_t * Abc_NodeFindNonCoFanout( Abc_Obj_t * pNode ) { Abc_Obj_t * pFanout; int i; Abc_ObjForEachFanout( pNode, pFanout, i ) if ( !Abc_ObjIsCo(pFanout) ) return pFanout; return NULL; } /**Function************************************************************* Synopsis [Checks if the internal node has CO drivers with the same name.] Description [Checks if the internal node can borrow its name from CO fanouts. This is possible if all COs with non-complemented fanin edge pointing to this node have the same name.] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Obj_t * Abc_NodeHasUniqueCoFanout( Abc_Obj_t * pNode ) { Abc_Obj_t * pFanout, * pFanoutCo; int i; pFanoutCo = NULL; Abc_ObjForEachFanout( pNode, pFanout, i ) { if ( !Abc_ObjIsCo(pFanout) ) continue; if ( Abc_ObjFaninC0(pFanout) ) continue; if ( pFanoutCo == NULL ) { assert( Abc_ObjFaninNum(pFanout) == 1 ); assert( Abc_ObjFanin0(pFanout) == pNode ); pFanoutCo = pFanout; continue; } if ( strcmp( Abc_ObjName(pFanoutCo), Abc_ObjName(pFanout) ) ) // they have diff names return NULL; } return pFanoutCo; } /**Function************************************************************* Synopsis [Fixes the CO driver problem.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkFixCoDriverProblem( Abc_Obj_t * pDriver, Abc_Obj_t * pNodeCo, int fDuplicate ) { Abc_Ntk_t * pNtk = pDriver->pNtk; Abc_Obj_t * pDriverNew, * pFanin; int k; if ( fDuplicate && !Abc_ObjIsCi(pDriver) ) { pDriverNew = Abc_NtkDupObj( pNtk, pDriver, 0 ); Abc_ObjForEachFanin( pDriver, pFanin, k ) Abc_ObjAddFanin( pDriverNew, pFanin ); if ( Abc_ObjFaninC0(pNodeCo) ) { // change polarity of the duplicated driver Abc_NodeComplement( pDriverNew ); Abc_ObjXorFaninC( pNodeCo, 0 ); } } else { // add inverters and buffers when necessary if ( Abc_ObjFaninC0(pNodeCo) ) { pDriverNew = Abc_NtkCreateNodeInv( pNtk, pDriver ); Abc_ObjXorFaninC( pNodeCo, 0 ); } else pDriverNew = Abc_NtkCreateNodeBuf( pNtk, pDriver ); } // update the fanin of the PO node Abc_ObjPatchFanin( pNodeCo, pDriver, pDriverNew ); assert( Abc_ObjFanoutNum(pDriverNew) == 1 ); // remove the old driver if it dangles // (this happens when the duplicated driver had only one complemented fanout) if ( Abc_ObjFanoutNum(pDriver) == 0 ) Abc_NtkDeleteObj( pDriver ); } /**Function************************************************************* Synopsis [Returns 1 if COs of a logic network are simple.] Description [The COs of a logic network are simple under three conditions: (1) The edge from CO to its driver is not complemented. (2) If CI is a driver of a CO, they have the same name.] (3) If two COs share the same driver, they have the same name.] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkLogicHasSimpleCos( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode, * pDriver; int i; assert( Abc_NtkIsLogic(pNtk) ); Abc_NtkIncrementTravId( pNtk ); Abc_NtkForEachCo( pNtk, pNode, i ) { // if the driver is complemented, this is an error pDriver = Abc_ObjFanin0(pNode); if ( Abc_ObjFaninC0(pNode) ) return 0; // if the driver is a CI and has different name, this is an error if ( Abc_ObjIsCi(pDriver) && strcmp(Abc_ObjName(pDriver), Abc_ObjName(pNode)) ) return 0; // if the driver is visited for the first time, remember the CO name if ( !Abc_NodeIsTravIdCurrent(pDriver) ) { pDriver->pNext = (Abc_Obj_t *)Abc_ObjName(pNode); Abc_NodeSetTravIdCurrent(pDriver); continue; } // the driver has second CO - if they have different name, this is an error if ( strcmp((char *)pDriver->pNext, Abc_ObjName(pNode)) ) // diff names return 0; } return 1; } /**Function************************************************************* Synopsis [Transforms the network to have simple COs.] Description [The COs of a logic network are simple under three conditions: (1) The edge from CO to its driver is not complemented. (2) If CI is a driver of a CO, they have the same name.] (3) If two COs share the same driver, they have the same name. In some cases, such as FPGA mapping, we prevent the increase in delay by duplicating the driver nodes, rather than adding invs/bufs.] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkLogicMakeSimpleCos2( Abc_Ntk_t * pNtk, int fDuplicate ) { Abc_Obj_t * pNode, * pDriver; int i, nDupGates = 0; assert( Abc_NtkIsLogic(pNtk) ); Abc_NtkIncrementTravId( pNtk ); Abc_NtkForEachCo( pNtk, pNode, i ) { // if the driver is complemented, this is an error pDriver = Abc_ObjFanin0(pNode); if ( Abc_ObjFaninC0(pNode) ) { Abc_NtkFixCoDriverProblem( pDriver, pNode, fDuplicate ); nDupGates++; continue; } // if the driver is a CI and has different name, this is an error if ( Abc_ObjIsCi(pDriver) && strcmp(Abc_ObjName(pDriver), Abc_ObjName(pNode)) ) { Abc_NtkFixCoDriverProblem( pDriver, pNode, fDuplicate ); nDupGates++; continue; } // if the driver is visited for the first time, remember the CO name if ( !Abc_NodeIsTravIdCurrent(pDriver) ) { pDriver->pNext = (Abc_Obj_t *)Abc_ObjName(pNode); Abc_NodeSetTravIdCurrent(pDriver); continue; } // the driver has second CO - if they have different name, this is an error if ( strcmp((char *)pDriver->pNext, Abc_ObjName(pNode)) ) // diff names { Abc_NtkFixCoDriverProblem( pDriver, pNode, fDuplicate ); nDupGates++; continue; } } assert( Abc_NtkLogicHasSimpleCos(pNtk) ); return nDupGates; } /**Function************************************************************* Synopsis [Transforms the network to have simple COs.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkLogicMakeSimpleCosTest( Abc_Ntk_t * pNtk, int fDuplicate ) { int nObjs = Abc_NtkObjNumMax(pNtk); unsigned * pType = ABC_CALLOC( unsigned, nObjs ); Abc_Obj_t * pNode; int i, Counts[4] = {0}, Consts[2] = {0}, Inputs[2] = {0}; // collect info Abc_NtkForEachCo( pNtk, pNode, i ) { if ( Abc_ObjFaninId0(pNode) == 0 ) Consts[Abc_ObjFaninC0(pNode)]++; if ( Abc_ObjIsCi(Abc_ObjFanin0(pNode)) ) Inputs[Abc_ObjFaninC0(pNode)]++; pType[Abc_ObjFaninId0(pNode)] |= (1 << Abc_ObjFaninC0(pNode)); } // count the numbers for ( i = 0; i < nObjs; i++ ) Counts[pType[i]]++; for ( i = 0; i < 4; i++ ) printf( "%d = %d ", i, Counts[i] ); for ( i = 0; i < 2; i++ ) printf( "c%d = %d ", i, Consts[i] ); for ( i = 0; i < 2; i++ ) printf( "i%d = %d ", i, Inputs[i] ); printf( "\n" ); ABC_FREE( pType ); } /**Function************************************************************* Synopsis [Transforms the network to have simple COs.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkLogicMakeSimpleCos( Abc_Ntk_t * pNtk, int fDuplicate ) { int fAddBuffers = 1; Vec_Ptr_t * vDrivers, * vCoTerms; Abc_Obj_t * pNode, * pDriver, * pDriverNew, * pFanin; int i, k, LevelMax, nTotal = 0; assert( Abc_NtkIsLogic(pNtk) ); LevelMax = Abc_NtkLevel(pNtk); // Abc_NtkLogicMakeSimpleCosTest( pNtk, fDuplicate ); // fix constant drivers Abc_NtkForEachCo( pNtk, pNode, i ) { pDriver = Abc_ObjFanin0(pNode); if ( !Abc_NodeIsConst(pDriver) ) continue; pDriverNew = (Abc_ObjFaninC0(pNode) == Abc_NodeIsConst0(pDriver)) ? Abc_NtkCreateNodeConst1(pNtk) : Abc_NtkCreateNodeConst0(pNtk); if ( Abc_ObjFaninC0(pNode) ) Abc_ObjXorFaninC( pNode, 0 ); Abc_ObjPatchFanin( pNode, pDriver, pDriverNew ); if ( Abc_ObjFanoutNum(pDriver) == 0 ) Abc_NtkDeleteObj( pDriver ); } // collect drivers pointed by complemented edges vDrivers = Vec_PtrAlloc( 100 ); Abc_NtkIncrementTravId( pNtk ); Abc_NtkForEachCo( pNtk, pNode, i ) { if ( !Abc_ObjFaninC0(pNode) ) continue; pDriver = Abc_ObjFanin0(pNode); if ( Abc_NodeIsTravIdCurrent(pDriver) ) continue; Abc_NodeSetTravIdCurrent(pDriver); Vec_PtrPush( vDrivers, pDriver ); } // fix complemented drivers if ( Vec_PtrSize(vDrivers) > 0 ) { int nDupGates = 0, nDupInvs = 0, nDupChange = 0; Vec_Ptr_t * vFanouts = Vec_PtrAlloc( 100 ); Vec_PtrForEachEntry( Abc_Obj_t *, vDrivers, pDriver, i ) { int fHasDir = 0, fHasInv = 0, fHasOther = 0; Abc_ObjForEachFanout( pDriver, pNode, k ) { if ( !Abc_ObjIsCo(pNode) ) { assert( !Abc_ObjFaninC0(pNode) ); fHasOther = 1; continue; } if ( Abc_ObjFaninC0(pNode) ) fHasInv = 1; else //if ( Abc_ObjFaninC0(pNode) ) fHasDir = 1; } assert( fHasInv ); if ( Abc_ObjIsCi(pDriver) || fHasDir || (fHasOther && Abc_NtkHasMapping(pNtk)) ) // cannot change { // duplicate if critical if ( fDuplicate && Abc_ObjIsNode(pDriver) && Abc_ObjLevel(pDriver) == LevelMax ) { pDriverNew = Abc_NtkDupObj( pNtk, pDriver, 0 ); Abc_ObjForEachFanin( pDriver, pFanin, k ) Abc_ObjAddFanin( pDriverNew, pFanin ); Abc_NodeComplement( pDriverNew ); nDupGates++; } else // add inverter { pDriverNew = Abc_NtkCreateNodeInv( pNtk, pDriver ); nDupInvs++; } // collect CO fanouts to be redirected to the new node Vec_PtrClear( vFanouts ); Abc_ObjForEachFanout( pDriver, pNode, k ) if ( Abc_ObjIsCo(pNode) && Abc_ObjFaninC0(pNode) ) Vec_PtrPush( vFanouts, pNode ); assert( Vec_PtrSize(vFanouts) > 0 ); Vec_PtrForEachEntry( Abc_Obj_t *, vFanouts, pNode, k ) { Abc_ObjXorFaninC( pNode, 0 ); Abc_ObjPatchFanin( pNode, pDriver, pDriverNew ); assert( Abc_ObjIsCi(pDriver) || Abc_ObjFanoutNum(pDriver) > 0 ); } } else // can change { // change polarity of the driver assert( Abc_ObjIsNode(pDriver) ); Abc_NodeComplement( pDriver ); Abc_ObjForEachFanout( pDriver, pNode, k ) { if ( Abc_ObjIsCo(pNode) ) { assert( Abc_ObjFaninC0(pNode) ); Abc_ObjXorFaninC( pNode, 0 ); } else if ( Abc_ObjIsNode(pNode) ) Abc_NodeComplementInput( pNode, pDriver ); else assert( 0 ); } nDupChange++; } } Vec_PtrFree( vFanouts ); // printf( "Resolving inverted CO drivers: Invs = %d. Dups = %d. Changes = %d.\n", // nDupInvs, nDupGates, nDupChange ); nTotal += nDupInvs + nDupGates; } Vec_PtrFree( vDrivers ); // collect COs that needs fixing by adding buffers or duplicating vCoTerms = Vec_PtrAlloc( 100 ); Abc_NtkIncrementTravId( pNtk ); // The following cases should be addressed only if the network is written // into a BLIF file. Otherwise, it is possible to skip them: // (1) if a CO points to a CI with a different name // (2) if an internal node drives more than one CO if ( fAddBuffers ) Abc_NtkForEachCo( pNtk, pNode, i ) { // if the driver is a CI and has different name, this is an error pDriver = Abc_ObjFanin0(pNode); if ( Abc_ObjIsCi(pDriver) && strcmp(Abc_ObjName(pDriver), Abc_ObjName(pNode)) ) { Vec_PtrPush( vCoTerms, pNode ); continue; } // if the driver is visited for the first time, remember the CO name if ( !Abc_NodeIsTravIdCurrent(pDriver) ) { pDriver->pNext = (Abc_Obj_t *)Abc_ObjName(pNode); Abc_NodeSetTravIdCurrent(pDriver); continue; } // the driver has second CO - if they have different name, this is an error if ( strcmp((char *)pDriver->pNext, Abc_ObjName(pNode)) ) // diff names { Vec_PtrPush( vCoTerms, pNode ); continue; } } // fix duplication problem if ( Vec_PtrSize(vCoTerms) > 0 ) { int nDupBufs = 0, nDupGates = 0; Vec_PtrForEachEntry( Abc_Obj_t *, vCoTerms, pNode, i ) { pDriver = Abc_ObjFanin0(pNode); // duplicate if critical if ( fDuplicate && Abc_ObjIsNode(pDriver) && (Abc_NtkHasMapping(pNtk) || Abc_ObjLevel(pDriver) == LevelMax) ) { pDriverNew = Abc_NtkDupObj( pNtk, pDriver, 0 ); Abc_ObjForEachFanin( pDriver, pFanin, k ) Abc_ObjAddFanin( pDriverNew, pFanin ); nDupGates++; } else // add buffer { pDriverNew = Abc_NtkCreateNodeBuf( pNtk, pDriver ); Abc_ObjAssignName( pDriverNew, Abc_ObjName(pDriver), "_buf" ); nDupBufs++; } // swing the PO Abc_ObjPatchFanin( pNode, pDriver, pDriverNew ); assert( Abc_ObjIsCi(pDriver) || Abc_ObjFanoutNum(pDriver) > 0 ); } // printf( "Resolving shared CO drivers: Bufs = %d. Dups = %d.\n", nDupBufs, nDupGates ); nTotal += nDupBufs + nDupGates; } Vec_PtrFree( vCoTerms ); return nTotal; } /**Function************************************************************* Synopsis [Inserts a new node in the order by levels.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_VecObjPushUniqueOrderByLevel( Vec_Ptr_t * p, Abc_Obj_t * pNode ) { Abc_Obj_t * pNode1, * pNode2; int i; if ( Vec_PtrPushUnique(p, pNode) ) return; // find the p of the node for ( i = p->nSize-1; i > 0; i-- ) { pNode1 = (Abc_Obj_t *)p->pArray[i ]; pNode2 = (Abc_Obj_t *)p->pArray[i-1]; if ( Abc_ObjRegular(pNode1)->Level <= Abc_ObjRegular(pNode2)->Level ) break; p->pArray[i ] = pNode2; p->pArray[i-1] = pNode1; } } /**Function************************************************************* Synopsis [Returns 1 if the node is the root of EXOR/NEXOR.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NodeIsExorType( Abc_Obj_t * pNode ) { Abc_Obj_t * pNode0, * pNode1; // check that the node is regular assert( !Abc_ObjIsComplement(pNode) ); // if the node is not AND, this is not EXOR if ( !Abc_AigNodeIsAnd(pNode) ) return 0; // if the children are not complemented, this is not EXOR if ( !Abc_ObjFaninC0(pNode) || !Abc_ObjFaninC1(pNode) ) return 0; // get children pNode0 = Abc_ObjFanin0(pNode); pNode1 = Abc_ObjFanin1(pNode); // if the children are not ANDs, this is not EXOR if ( Abc_ObjFaninNum(pNode0) != 2 || Abc_ObjFaninNum(pNode1) != 2 ) return 0; // this is AIG, which means the fanins should be ordered assert( Abc_ObjFaninId0(pNode0) != Abc_ObjFaninId1(pNode1) || Abc_ObjFaninId0(pNode1) != Abc_ObjFaninId1(pNode0) ); // if grand children are not the same, this is not EXOR if ( Abc_ObjFaninId0(pNode0) != Abc_ObjFaninId0(pNode1) || Abc_ObjFaninId1(pNode0) != Abc_ObjFaninId1(pNode1) ) return 0; // finally, if the complemented edges are matched, this is not EXOR if ( Abc_ObjFaninC0(pNode0) == Abc_ObjFaninC0(pNode1) || Abc_ObjFaninC1(pNode0) == Abc_ObjFaninC1(pNode1) ) return 0; return 1; } /**Function************************************************************* Synopsis [Returns 1 if the node is the root of MUX or EXOR/NEXOR.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NodeIsMuxType( Abc_Obj_t * pNode ) { Abc_Obj_t * pNode0, * pNode1; // check that the node is regular assert( !Abc_ObjIsComplement(pNode) ); // if the node is not AND, this is not MUX if ( !Abc_AigNodeIsAnd(pNode) ) return 0; // if the children are not complemented, this is not MUX if ( !Abc_ObjFaninC0(pNode) || !Abc_ObjFaninC1(pNode) ) return 0; // get children pNode0 = Abc_ObjFanin0(pNode); pNode1 = Abc_ObjFanin1(pNode); // if the children are not ANDs, this is not MUX if ( !Abc_AigNodeIsAnd(pNode0) || !Abc_AigNodeIsAnd(pNode1) ) return 0; // otherwise the node is MUX iff it has a pair of equal grandchildren with opposite polarity return (Abc_ObjFaninId0(pNode0) == Abc_ObjFaninId0(pNode1) && (Abc_ObjFaninC0(pNode0) ^ Abc_ObjFaninC0(pNode1))) || (Abc_ObjFaninId0(pNode0) == Abc_ObjFaninId1(pNode1) && (Abc_ObjFaninC0(pNode0) ^ Abc_ObjFaninC1(pNode1))) || (Abc_ObjFaninId1(pNode0) == Abc_ObjFaninId0(pNode1) && (Abc_ObjFaninC1(pNode0) ^ Abc_ObjFaninC0(pNode1))) || (Abc_ObjFaninId1(pNode0) == Abc_ObjFaninId1(pNode1) && (Abc_ObjFaninC1(pNode0) ^ Abc_ObjFaninC1(pNode1))); } /**Function************************************************************* Synopsis [Returns 1 if the node is the root of MUX or EXOR/NEXOR.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkCountMuxes( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pNode; int i; int Counter = 0; Abc_NtkForEachNode( pNtk, pNode, i ) Counter += Abc_NodeIsMuxType( pNode ); return Counter; } /**Function************************************************************* Synopsis [Returns 1 if the node is the control type of the MUX.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NodeIsMuxControlType( Abc_Obj_t * pNode ) { Abc_Obj_t * pNode0, * pNode1; // check that the node is regular assert( !Abc_ObjIsComplement(pNode) ); // skip the node that do not have two fanouts if ( Abc_ObjFanoutNum(pNode) != 2 ) return 0; // get the fanouts pNode0 = Abc_ObjFanout( pNode, 0 ); pNode1 = Abc_ObjFanout( pNode, 1 ); // if they have more than one fanout, we are not interested if ( Abc_ObjFanoutNum(pNode0) != 1 || Abc_ObjFanoutNum(pNode1) != 1 ) return 0; // if the fanouts have the same fanout, this is MUX or EXOR (or a redundant gate (CA)(CB)) return Abc_ObjFanout0(pNode0) == Abc_ObjFanout0(pNode1); } /**Function************************************************************* Synopsis [Recognizes what nodes are control and data inputs of a MUX.] Description [If the node is a MUX, returns the control variable C. Assigns nodes T and E to be the then and else variables of the MUX. Node C is never complemented. Nodes T and E can be complemented. This function also recognizes EXOR/NEXOR gates as MUXes.] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Obj_t * Abc_NodeRecognizeMux( Abc_Obj_t * pNode, Abc_Obj_t ** ppNodeT, Abc_Obj_t ** ppNodeE ) { Abc_Obj_t * pNode0, * pNode1; assert( !Abc_ObjIsComplement(pNode) ); assert( Abc_NodeIsMuxType(pNode) ); // get children pNode0 = Abc_ObjFanin0(pNode); pNode1 = Abc_ObjFanin1(pNode); // find the control variable // if ( pNode1->p1 == Fraig_Not(pNode2->p1) ) if ( Abc_ObjFaninId0(pNode0) == Abc_ObjFaninId0(pNode1) && (Abc_ObjFaninC0(pNode0) ^ Abc_ObjFaninC0(pNode1)) ) { // if ( Fraig_IsComplement(pNode1->p1) ) if ( Abc_ObjFaninC0(pNode0) ) { // pNode2->p1 is positive phase of C *ppNodeT = Abc_ObjNot(Abc_ObjChild1(pNode1));//pNode2->p2); *ppNodeE = Abc_ObjNot(Abc_ObjChild1(pNode0));//pNode1->p2); return Abc_ObjChild0(pNode1);//pNode2->p1; } else { // pNode1->p1 is positive phase of C *ppNodeT = Abc_ObjNot(Abc_ObjChild1(pNode0));//pNode1->p2); *ppNodeE = Abc_ObjNot(Abc_ObjChild1(pNode1));//pNode2->p2); return Abc_ObjChild0(pNode0);//pNode1->p1; } } // else if ( pNode1->p1 == Fraig_Not(pNode2->p2) ) else if ( Abc_ObjFaninId0(pNode0) == Abc_ObjFaninId1(pNode1) && (Abc_ObjFaninC0(pNode0) ^ Abc_ObjFaninC1(pNode1)) ) { // if ( Fraig_IsComplement(pNode1->p1) ) if ( Abc_ObjFaninC0(pNode0) ) { // pNode2->p2 is positive phase of C *ppNodeT = Abc_ObjNot(Abc_ObjChild0(pNode1));//pNode2->p1); *ppNodeE = Abc_ObjNot(Abc_ObjChild1(pNode0));//pNode1->p2); return Abc_ObjChild1(pNode1);//pNode2->p2; } else { // pNode1->p1 is positive phase of C *ppNodeT = Abc_ObjNot(Abc_ObjChild1(pNode0));//pNode1->p2); *ppNodeE = Abc_ObjNot(Abc_ObjChild0(pNode1));//pNode2->p1); return Abc_ObjChild0(pNode0);//pNode1->p1; } } // else if ( pNode1->p2 == Fraig_Not(pNode2->p1) ) else if ( Abc_ObjFaninId1(pNode0) == Abc_ObjFaninId0(pNode1) && (Abc_ObjFaninC1(pNode0) ^ Abc_ObjFaninC0(pNode1)) ) { // if ( Fraig_IsComplement(pNode1->p2) ) if ( Abc_ObjFaninC1(pNode0) ) { // pNode2->p1 is positive phase of C *ppNodeT = Abc_ObjNot(Abc_ObjChild1(pNode1));//pNode2->p2); *ppNodeE = Abc_ObjNot(Abc_ObjChild0(pNode0));//pNode1->p1); return Abc_ObjChild0(pNode1);//pNode2->p1; } else { // pNode1->p2 is positive phase of C *ppNodeT = Abc_ObjNot(Abc_ObjChild0(pNode0));//pNode1->p1); *ppNodeE = Abc_ObjNot(Abc_ObjChild1(pNode1));//pNode2->p2); return Abc_ObjChild1(pNode0);//pNode1->p2; } } // else if ( pNode1->p2 == Fraig_Not(pNode2->p2) ) else if ( Abc_ObjFaninId1(pNode0) == Abc_ObjFaninId1(pNode1) && (Abc_ObjFaninC1(pNode0) ^ Abc_ObjFaninC1(pNode1)) ) { // if ( Fraig_IsComplement(pNode1->p2) ) if ( Abc_ObjFaninC1(pNode0) ) { // pNode2->p2 is positive phase of C *ppNodeT = Abc_ObjNot(Abc_ObjChild0(pNode1));//pNode2->p1); *ppNodeE = Abc_ObjNot(Abc_ObjChild0(pNode0));//pNode1->p1); return Abc_ObjChild1(pNode1);//pNode2->p2; } else { // pNode1->p2 is positive phase of C *ppNodeT = Abc_ObjNot(Abc_ObjChild0(pNode0));//pNode1->p1); *ppNodeE = Abc_ObjNot(Abc_ObjChild0(pNode1));//pNode2->p1); return Abc_ObjChild1(pNode0);//pNode1->p2; } } assert( 0 ); // this is not MUX return NULL; } /**Function************************************************************* Synopsis [Prepares two network for a two-argument command similar to "verify".] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkPrepareTwoNtks( FILE * pErr, Abc_Ntk_t * pNtk, char ** argv, int argc, Abc_Ntk_t ** ppNtk1, Abc_Ntk_t ** ppNtk2, int * pfDelete1, int * pfDelete2, int fCheck ) { FILE * pFile; Abc_Ntk_t * pNtk1, * pNtk2, * pNtkTemp; int util_optind = 0; *pfDelete1 = 0; *pfDelete2 = 0; if ( argc == util_optind ) { // use the spec if ( pNtk == NULL ) { fprintf( pErr, "Empty current network.\n" ); return 0; } if ( pNtk->pSpec == NULL ) { fprintf( pErr, "The external spec is not given.\n" ); return 0; } pFile = fopen( pNtk->pSpec, "r" ); if ( pFile == NULL ) { fprintf( pErr, "Cannot open the external spec file \"%s\".\n", pNtk->pSpec ); return 0; } else fclose( pFile ); pNtk1 = Abc_NtkDup(pNtk); pNtk2 = Io_Read( pNtk->pSpec, Io_ReadFileType(pNtk->pSpec), fCheck, 0 ); if ( pNtk2 == NULL ) return 0; *pfDelete1 = 1; *pfDelete2 = 1; } else if ( argc == util_optind + 1 ) { if ( pNtk == NULL ) { fprintf( pErr, "Empty current network.\n" ); return 0; } pNtk1 = Abc_NtkDup(pNtk); pNtk2 = Io_Read( argv[util_optind], Io_ReadFileType(argv[util_optind]), fCheck, 0 ); if ( pNtk2 == NULL ) return 0; *pfDelete1 = 1; *pfDelete2 = 1; } else if ( argc == util_optind + 2 ) { pNtk1 = Io_Read( argv[util_optind], Io_ReadFileType(argv[util_optind]), fCheck, 0 ); if ( pNtk1 == NULL ) return 0; pNtk2 = Io_Read( argv[util_optind+1], Io_ReadFileType(argv[util_optind+1]), fCheck, 0 ); if ( pNtk2 == NULL ) { Abc_NtkDelete( pNtk1 ); return 0; } *pfDelete1 = 1; *pfDelete2 = 1; } else { fprintf( pErr, "Wrong number of arguments.\n" ); return 0; } // make sure the networks are strashed if ( !Abc_NtkIsStrash(pNtk1) ) { pNtkTemp = Abc_NtkStrash( pNtk1, 0, 1, 0 ); if ( *pfDelete1 ) Abc_NtkDelete( pNtk1 ); pNtk1 = pNtkTemp; *pfDelete1 = 1; } if ( !Abc_NtkIsStrash(pNtk2) ) { pNtkTemp = Abc_NtkStrash( pNtk2, 0, 1, 0 ); if ( *pfDelete2 ) Abc_NtkDelete( pNtk2 ); pNtk2 = pNtkTemp; *pfDelete2 = 1; } *ppNtk1 = pNtk1; *ppNtk2 = pNtk2; return 1; } /**Function************************************************************* Synopsis [Returns 1 if it is an AIG with choice nodes.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NodeCollectFanins( Abc_Obj_t * pNode, Vec_Ptr_t * vNodes ) { Abc_Obj_t * pFanin; int i; Vec_PtrClear(vNodes); Abc_ObjForEachFanin( pNode, pFanin, i ) Vec_PtrPush( vNodes, pFanin ); } /**Function************************************************************* Synopsis [Returns 1 if it is an AIG with choice nodes.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NodeCollectFanouts( Abc_Obj_t * pNode, Vec_Ptr_t * vNodes ) { Abc_Obj_t * pFanout; int i; Vec_PtrClear(vNodes); Abc_ObjForEachFanout( pNode, pFanout, i ) Vec_PtrPush( vNodes, pFanout ); } /**Function************************************************************* Synopsis [Collects all latches in the network.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Vec_Ptr_t * Abc_NtkCollectLatches( Abc_Ntk_t * pNtk ) { Vec_Ptr_t * vLatches; Abc_Obj_t * pObj; int i; vLatches = Vec_PtrAlloc( 10 ); Abc_NtkForEachObj( pNtk, pObj, i ) Vec_PtrPush( vLatches, pObj ); return vLatches; } /**Function************************************************************* Synopsis [Procedure used for sorting the nodes in increasing order of levels.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NodeCompareLevelsIncrease( Abc_Obj_t ** pp1, Abc_Obj_t ** pp2 ) { int Diff = Abc_ObjRegular(*pp1)->Level - Abc_ObjRegular(*pp2)->Level; if ( Diff < 0 ) return -1; if ( Diff > 0 ) return 1; Diff = Abc_ObjRegular(*pp1)->Id - Abc_ObjRegular(*pp2)->Id; if ( Diff < 0 ) return -1; if ( Diff > 0 ) return 1; return 0; } /**Function************************************************************* Synopsis [Procedure used for sorting the nodes in decreasing order of levels.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NodeCompareLevelsDecrease( Abc_Obj_t ** pp1, Abc_Obj_t ** pp2 ) { int Diff = Abc_ObjRegular(*pp1)->Level - Abc_ObjRegular(*pp2)->Level; if ( Diff > 0 ) return -1; if ( Diff < 0 ) return 1; Diff = Abc_ObjRegular(*pp1)->Id - Abc_ObjRegular(*pp2)->Id; if ( Diff > 0 ) return -1; if ( Diff < 0 ) return 1; return 0; } /**Function************************************************************* Synopsis [Creates the array of fanout counters.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Vec_Int_t * Abc_NtkFanoutCounts( Abc_Ntk_t * pNtk ) { Vec_Int_t * vFanNums; Abc_Obj_t * pObj; int i; vFanNums = Vec_IntAlloc( 0 ); Vec_IntFill( vFanNums, Abc_NtkObjNumMax(pNtk), -1 ); Abc_NtkForEachObj( pNtk, pObj, i ) if ( Abc_ObjIsCi(pObj) || Abc_ObjIsNode(pObj) ) Vec_IntWriteEntry( vFanNums, i, Abc_ObjFanoutNum(pObj) ); return vFanNums; } /**Function************************************************************* Synopsis [Collects all objects into one array.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Vec_Ptr_t * Abc_NtkCollectObjects( Abc_Ntk_t * pNtk ) { Vec_Ptr_t * vNodes; Abc_Obj_t * pNode; int i; vNodes = Vec_PtrAlloc( 100 ); Abc_NtkForEachObj( pNtk, pNode, i ) Vec_PtrPush( vNodes, pNode ); return vNodes; } /**Function************************************************************* Synopsis [Returns the array of CI IDs.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Vec_Int_t * Abc_NtkGetCiIds( Abc_Ntk_t * pNtk ) { Vec_Int_t * vCiIds; Abc_Obj_t * pObj; int i; vCiIds = Vec_IntAlloc( Abc_NtkCiNum(pNtk) ); Abc_NtkForEachCi( pNtk, pObj, i ) Vec_IntPush( vCiIds, pObj->Id ); return vCiIds; } /**Function************************************************************* Synopsis [Puts the nodes into the DFS order and reassign their IDs.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkReassignIds( Abc_Ntk_t * pNtk ) { Vec_Ptr_t * vNodes; Vec_Ptr_t * vObjsNew; Abc_Obj_t * pNode, * pTemp, * pConst1; int i, k; assert( Abc_NtkIsStrash(pNtk) ); //printf( "Total = %d. Current = %d.\n", Abc_NtkObjNumMax(pNtk), Abc_NtkObjNum(pNtk) ); // start the array of objects with new IDs vObjsNew = Vec_PtrAlloc( pNtk->nObjs ); // put constant node first pConst1 = Abc_AigConst1(pNtk); assert( pConst1->Id == 0 ); Vec_PtrPush( vObjsNew, pConst1 ); // put PI nodes next Abc_NtkForEachPi( pNtk, pNode, i ) { pNode->Id = Vec_PtrSize( vObjsNew ); Vec_PtrPush( vObjsNew, pNode ); } // put PO nodes next Abc_NtkForEachPo( pNtk, pNode, i ) { pNode->Id = Vec_PtrSize( vObjsNew ); Vec_PtrPush( vObjsNew, pNode ); } // put latches and their inputs/outputs next Abc_NtkForEachBox( pNtk, pNode, i ) { pNode->Id = Vec_PtrSize( vObjsNew ); Vec_PtrPush( vObjsNew, pNode ); Abc_ObjForEachFanin( pNode, pTemp, k ) { pTemp->Id = Vec_PtrSize( vObjsNew ); Vec_PtrPush( vObjsNew, pTemp ); } Abc_ObjForEachFanout( pNode, pTemp, k ) { pTemp->Id = Vec_PtrSize( vObjsNew ); Vec_PtrPush( vObjsNew, pTemp ); } } // finally, internal nodes in the DFS order vNodes = Abc_AigDfs( pNtk, 1, 0 ); Vec_PtrForEachEntry( Abc_Obj_t *, vNodes, pNode, i ) { if ( pNode == pConst1 ) continue; pNode->Id = Vec_PtrSize( vObjsNew ); Vec_PtrPush( vObjsNew, pNode ); } Vec_PtrFree( vNodes ); assert( Vec_PtrSize(vObjsNew) == pNtk->nObjs ); // update the fanin/fanout arrays Abc_NtkForEachObj( pNtk, pNode, i ) { Abc_ObjForEachFanin( pNode, pTemp, k ) pNode->vFanins.pArray[k] = pTemp->Id; Abc_ObjForEachFanout( pNode, pTemp, k ) pNode->vFanouts.pArray[k] = pTemp->Id; } // replace the array of objs Vec_PtrFree( pNtk->vObjs ); pNtk->vObjs = vObjsNew; // rehash the AIG Abc_AigRehash( (Abc_Aig_t *)pNtk->pManFunc ); // update the name manager!!! } /**Function************************************************************* Synopsis [Detect cases when non-trivial FF matching is possible.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkDetectMatching( Abc_Ntk_t * pNtk ) { /* Abc_Obj_t * pLatch, * pFanin; int i, nTFFs, nJKFFs; nTFFs = nJKFFs = 0; Abc_NtkForEachLatch( pNtk, pLatch, i ) { pFanin = Abc_ObjFanin0(pLatch); if ( Abc_ObjFaninNum(pFanin) != 2 ) continue; if ( Abc_NodeIsExorType(pLatch) ) { if ( Abc_ObjFanin0(Abc_ObjFanin0(pFanin)) == pLatch || Abc_ObjFanin1(Abc_ObjFanin0(pFanin)) == pLatch ) nTFFs++; } if ( Abc_ObjFaninNum( Abc_ObjFanin0(pFanin) ) != 2 || Abc_ObjFaninNum( Abc_ObjFanin1(pFanin) ) != 2 ) continue; if ( (Abc_ObjFanin0(Abc_ObjFanin0(pFanin)) == pLatch || Abc_ObjFanin1(Abc_ObjFanin0(pFanin)) == pLatch) && (Abc_ObjFanin0(Abc_ObjFanin1(pFanin)) == pLatch || Abc_ObjFanin1(Abc_ObjFanin1(pFanin)) == pLatch) ) { nJKFFs++; } } printf( "D = %6d. T = %6d. JK = %6d. (%6.2f %%)\n", Abc_NtkLatchNum(pNtk), nTFFs, nJKFFs, 100.0 * nJKFFs / Abc_NtkLatchNum(pNtk) ); */ } /**Function************************************************************* Synopsis [Compares the pointers.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_ObjPointerCompare( void ** pp1, void ** pp2 ) { if ( *pp1 < *pp2 ) return -1; if ( *pp1 > *pp2 ) return 1; return 0; } /**Function************************************************************* Synopsis [Adjusts the copy pointers.] Description [This procedure assumes that the network was transformed into another network, which was in turn transformed into yet another network. It makes the pCopy pointers of the original network point to the objects of the yet another network.] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkTransferCopy( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Abc_NtkForEachObj( pNtk, pObj, i ) if ( !Abc_ObjIsNet(pObj) ) pObj->pCopy = pObj->pCopy? Abc_ObjCopyCond(pObj->pCopy) : NULL; } /**Function************************************************************* Synopsis [Increaments the cut counter.] Description [Returns 1 if it becomes equal to the ref counter.] SideEffects [] SeeAlso [] ***********************************************************************/ static inline int Abc_ObjCrossCutInc( Abc_Obj_t * pObj ) { // pObj->pCopy = (void *)(((int)pObj->pCopy)++); int Value = (int)(ABC_PTRINT_T)pObj->pCopy; pObj->pCopy = (Abc_Obj_t *)(ABC_PTRINT_T)(Value + 1); return (int)(ABC_PTRINT_T)pObj->pCopy == Abc_ObjFanoutNum(pObj); } /**Function************************************************************* Synopsis [Computes cross-cut of the circuit.] Description [Returns 1 if it is the last visit to the node.] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkCrossCut_rec( Abc_Obj_t * pObj, int * pnCutSize, int * pnCutSizeMax ) { Abc_Obj_t * pFanin; int i, nDecrem = 0; int fReverse = 0; if ( Abc_ObjIsCi(pObj) ) return 0; // if visited, increment visit counter if ( Abc_NodeIsTravIdCurrent( pObj ) ) return Abc_ObjCrossCutInc( pObj ); Abc_NodeSetTravIdCurrent( pObj ); // visit the fanins if ( !Abc_ObjIsCi(pObj) ) { if ( fReverse ) { Abc_ObjForEachFanin( pObj, pFanin, i ) { pFanin = Abc_ObjFanin( pObj, Abc_ObjFaninNum(pObj) - 1 - i ); nDecrem += Abc_NtkCrossCut_rec( pFanin, pnCutSize, pnCutSizeMax ); } } else { Abc_ObjForEachFanin( pObj, pFanin, i ) nDecrem += Abc_NtkCrossCut_rec( pFanin, pnCutSize, pnCutSizeMax ); } } // count the node (*pnCutSize)++; if ( *pnCutSizeMax < *pnCutSize ) *pnCutSizeMax = *pnCutSize; (*pnCutSize) -= nDecrem; return Abc_ObjCrossCutInc( pObj ); } /**Function************************************************************* Synopsis [Computes cross-cut of the circuit.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkCrossCut( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int nCutSize = 0, nCutSizeMax = 0; int i; Abc_NtkCleanCopy( pNtk ); Abc_NtkIncrementTravId( pNtk ); Abc_NtkForEachCo( pNtk, pObj, i ) { Abc_NtkCrossCut_rec( pObj, &nCutSize, &nCutSizeMax ); nCutSize--; } assert( nCutSize == 0 ); printf( "Max cross cut size = %6d. Ratio = %6.2f %%\n", nCutSizeMax, 100.0 * nCutSizeMax/Abc_NtkObjNum(pNtk) ); return nCutSizeMax; } /**Function************************************************************* Synopsis [Prints all 3-var functions.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkPrint256() { FILE * pFile; unsigned i; pFile = fopen( "4varfs.txt", "w" ); for ( i = 1; i < (1<<16)-1; i++ ) { fprintf( pFile, "read_truth " ); Extra_PrintBinary( pFile, &i, 16 ); fprintf( pFile, "; clp; st; w 1.blif; map; cec 1.blif\n" ); } fclose( pFile ); } static int * pSupps; /**Function************************************************************* Synopsis [Compares the supergates by their level.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkCompareConesCompare( int * pNum1, int * pNum2 ) { if ( pSupps[*pNum1] > pSupps[*pNum2] ) return -1; if ( pSupps[*pNum1] < pSupps[*pNum2] ) return 1; return 0; } /**Function************************************************************* Synopsis [Analyze choice node support.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkCompareCones( Abc_Ntk_t * pNtk ) { Vec_Ptr_t * vSupp, * vNodes, * vReverse; Abc_Obj_t * pObj, * pTemp; int Iter, i, k, Counter, CounterCos, CounterCosNew; int * pPerms; // sort COs by support size pPerms = ABC_ALLOC( int, Abc_NtkCoNum(pNtk) ); pSupps = ABC_ALLOC( int, Abc_NtkCoNum(pNtk) ); Abc_NtkForEachCo( pNtk, pObj, i ) { pPerms[i] = i; vSupp = Abc_NtkNodeSupport( pNtk, &pObj, 1 ); pSupps[i] = Vec_PtrSize(vSupp); Vec_PtrFree( vSupp ); } qsort( (void *)pPerms, (size_t)Abc_NtkCoNum(pNtk), sizeof(int), (int (*)(const void *, const void *)) Abc_NtkCompareConesCompare ); // consider COs in this order Iter = 0; Abc_NtkForEachCo( pNtk, pObj, i ) { pObj = Abc_NtkCo( pNtk, pPerms[i] ); if ( pObj->fMarkA ) continue; Iter++; vSupp = Abc_NtkNodeSupport( pNtk, &pObj, 1 ); vNodes = Abc_NtkDfsNodes( pNtk, &pObj, 1 ); vReverse = Abc_NtkDfsReverseNodesContained( pNtk, (Abc_Obj_t **)Vec_PtrArray(vSupp), Vec_PtrSize(vSupp) ); // count the number of nodes in the reverse cone Counter = 0; for ( k = 1; k < Vec_PtrSize(vReverse) - 1; k++ ) for ( pTemp = (Abc_Obj_t *)Vec_PtrEntry(vReverse, k); pTemp; pTemp = (Abc_Obj_t *)pTemp->pCopy ) Counter++; CounterCos = CounterCosNew = 0; for ( pTemp = (Abc_Obj_t *)Vec_PtrEntryLast(vReverse); pTemp; pTemp = (Abc_Obj_t *)pTemp->pCopy ) { assert( Abc_ObjIsCo(pTemp) ); CounterCos++; if ( pTemp->fMarkA == 0 ) CounterCosNew++; pTemp->fMarkA = 1; } // print statistics printf( "%4d CO %5d : Supp = %5d. Lev = %3d. Cone = %5d. Rev = %5d. COs = %3d (%3d).\n", Iter, pPerms[i], Vec_PtrSize(vSupp), Abc_ObjLevel(Abc_ObjFanin0(pObj)), Vec_PtrSize(vNodes), Counter, CounterCos, CounterCosNew ); if ( Vec_PtrSize(vSupp) < 10 ) { // free arrays Vec_PtrFree( vSupp ); Vec_PtrFree( vNodes ); Vec_PtrFree( vReverse ); break; } // free arrays Vec_PtrFree( vSupp ); Vec_PtrFree( vNodes ); Vec_PtrFree( vReverse ); } Abc_NtkForEachCo( pNtk, pObj, i ) pObj->fMarkA = 0; ABC_FREE( pPerms ); ABC_FREE( pSupps ); } /**Function************************************************************* Synopsis [Analyze choice node support.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkCompareSupports( Abc_Ntk_t * pNtk ) { Vec_Ptr_t * vSupp; Abc_Obj_t * pObj, * pTemp; int i, nNodesOld; assert( Abc_NtkIsStrash(pNtk) ); Abc_AigForEachAnd( pNtk, pObj, i ) { if ( !Abc_AigNodeIsChoice(pObj) ) continue; vSupp = Abc_NtkNodeSupport( pNtk, &pObj, 1 ); nNodesOld = Vec_PtrSize(vSupp); Vec_PtrFree( vSupp ); for ( pTemp = (Abc_Obj_t *)pObj->pData; pTemp; pTemp = (Abc_Obj_t *)pTemp->pData ) { vSupp = Abc_NtkNodeSupport( pNtk, &pTemp, 1 ); if ( nNodesOld != Vec_PtrSize(vSupp) ) printf( "Choice orig = %3d Choice new = %3d\n", nNodesOld, Vec_PtrSize(vSupp) ); Vec_PtrFree( vSupp ); } } } /**Function************************************************************* Synopsis [Complements the constraint outputs.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkInvertConstraints( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; if ( Abc_NtkConstrNum(pNtk) == 0 ) return; Abc_NtkForEachPo( pNtk, pObj, i ) { if ( i >= Abc_NtkPoNum(pNtk) - Abc_NtkConstrNum(pNtk) ) Abc_ObjXorFaninC( pObj, 0 ); } } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkPrintCiLevels( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Abc_NtkForEachCi( pNtk, pObj, i ) printf( "%c=%d ", 'a'+i, pObj->Level ); printf( "\n" ); } /**Function************************************************************* Synopsis [Returns 1 if all other fanouts of pFanin are below pNode.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkAddBuffsEval( Abc_Obj_t * pNode, Abc_Obj_t * pFanin ) { Abc_Obj_t * pFanout; int i; Abc_ObjForEachFanout( pFanin, pFanout, i ) if ( pFanout != pNode && pFanout->Level >= pNode->Level ) return 0; return 1; } /**Function************************************************************* Synopsis [Returns 1 if there exist a fanout of pFanin higher than pNode.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkAddBuffsEval2( Abc_Obj_t * pNode, Abc_Obj_t * pFanin ) { Abc_Obj_t * pFanout; int i; Abc_ObjForEachFanout( pFanin, pFanout, i ) if ( pFanout != pNode && pFanout->Level > pNode->Level ) return 1; return 0; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Obj_t * Abc_NtkAddBuffsOne( Vec_Ptr_t * vBuffs, Abc_Obj_t * pFanin, int Level, int nLevelMax ) { Abc_Obj_t * pBuffer; assert( Level - 1 >= Abc_ObjLevel(pFanin) ); pBuffer = (Abc_Obj_t *)Vec_PtrEntry( vBuffs, Abc_ObjId(pFanin) * nLevelMax + Level ); if ( pBuffer == NULL ) { if ( Level - 1 == Abc_ObjLevel(pFanin) ) pBuffer = pFanin; else pBuffer = Abc_NtkAddBuffsOne( vBuffs, pFanin, Level - 1, nLevelMax ); pBuffer = Abc_NtkCreateNodeBuf( Abc_ObjNtk(pFanin), pBuffer ); Vec_PtrWriteEntry( vBuffs, Abc_ObjId(pFanin) * nLevelMax + Level, pBuffer ); } return pBuffer; } Abc_Ntk_t * Abc_NtkAddBuffsInt( Abc_Ntk_t * pNtkInit, int fReverse, int nImprove, int fVerbose ) { Vec_Ptr_t * vBuffs; Abc_Ntk_t * pNtk = Abc_NtkDup( pNtkInit ); Abc_Obj_t * pObj, * pFanin, * pBuffer; int i, k, Iter, nLevelMax = Abc_NtkLevel( pNtk ); Abc_NtkForEachCo( pNtk, pObj, i ) pObj->Level = nLevelMax + 1; if ( fReverse ) { Vec_Ptr_t * vNodes = Abc_NtkDfs( pNtk, 1 ); assert( nLevelMax < (1<<18) ); Vec_PtrForEachEntryReverse( Abc_Obj_t *, vNodes, pObj, i ) { pObj->Level = (1<<18); Abc_ObjForEachFanout( pObj, pFanin, k ) pObj->Level = Abc_MinInt( pFanin->Level - 1, pObj->Level ); assert( pObj->Level > 0 ); } Abc_NtkForEachCi( pNtk, pObj, i ) pObj->Level = 0; // move the nodes down one step at a time for ( Iter = 0; Iter < nImprove; Iter++ ) { int Counter = 0, TotalGain = 0; Vec_PtrForEachEntry( Abc_Obj_t *, vNodes, pObj, i ) { int CountGain = -1; assert( pObj->Level > 0 ); Abc_ObjForEachFanin( pObj, pFanin, k ) { assert( pFanin->Level < pObj->Level ); if ( pFanin->Level + 1 == pObj->Level ) break; } if ( k < Abc_ObjFaninNum(pObj) ) // cannot move continue; Abc_ObjForEachFanin( pObj, pFanin, k ) CountGain += Abc_NtkAddBuffsEval( pObj, pFanin ); if ( CountGain >= 0 ) // can move { pObj->Level--; Counter++; TotalGain += CountGain; } } if ( fVerbose ) printf( "Shifted %5d nodes down with total gain %5d.\n", Counter, TotalGain ); if ( Counter == 0 ) break; } Vec_PtrFree( vNodes ); } else { // move the nodes up one step at a time Vec_Ptr_t * vNodes = Abc_NtkDfs( pNtk, 1 ); for ( Iter = 0; Iter < nImprove; Iter++ ) { int Counter = 0, TotalGain = 0; Vec_PtrForEachEntryReverse( Abc_Obj_t *, vNodes, pObj, i ) { int CountGain = 1; assert( pObj->Level <= (unsigned)nLevelMax ); Abc_ObjForEachFanout( pObj, pFanin, k ) { assert( pFanin->Level > pObj->Level ); if ( pFanin->Level == pObj->Level + 1 ) break; } if ( k < Abc_ObjFanoutNum(pObj) ) // cannot move continue; Abc_ObjForEachFanin( pObj, pFanin, k ) CountGain -= !Abc_NtkAddBuffsEval2( pObj, pFanin ); if ( CountGain >= 0 ) // can move { pObj->Level++; Counter++; TotalGain += CountGain; } } if ( fVerbose ) printf( "Shifted %5d nodes up with total gain %5d.\n", Counter, TotalGain ); if ( Counter == 0 ) break; } Vec_PtrFree( vNodes ); } vBuffs = Vec_PtrStart( Abc_NtkObjNumMax(pNtk) * (nLevelMax + 1) ); Abc_NtkForEachObj( pNtk, pObj, i ) { if ( i == Vec_PtrSize(vBuffs) / (nLevelMax + 1) ) break; if ( !Abc_ObjIsNode(pObj) && !Abc_ObjIsCo(pObj) ) continue; Abc_ObjForEachFanin( pObj, pFanin, k ) { assert( Abc_ObjLevel(pObj) - 1 >= Abc_ObjLevel(pFanin) ); if ( Abc_ObjLevel(pObj) - 1 == Abc_ObjLevel(pFanin) ) continue; pBuffer = Abc_NtkAddBuffsOne( vBuffs, pFanin, Abc_ObjLevel(pObj) - 1, nLevelMax ); Abc_ObjPatchFanin( pObj, pFanin, pBuffer ); } } Vec_PtrFree( vBuffs ); Abc_NtkForEachCo( pNtk, pObj, i ) pObj->Level = 0; return pNtk; } Abc_Ntk_t * Abc_NtkAddBuffs( Abc_Ntk_t * pNtkInit, int fDirect, int fReverse, int nImprove, int fVerbose ) { Abc_Ntk_t * pNtkD, * pNtkR; if ( fDirect ) return Abc_NtkAddBuffsInt( pNtkInit, 0, nImprove, fVerbose ); if ( fReverse ) return Abc_NtkAddBuffsInt( pNtkInit, 1, nImprove, fVerbose ); pNtkD = Abc_NtkAddBuffsInt( pNtkInit, 0, nImprove, fVerbose ); pNtkR = Abc_NtkAddBuffsInt( pNtkInit, 1, nImprove, fVerbose ); if ( Abc_NtkNodeNum(pNtkD) < Abc_NtkNodeNum(pNtkR) ) { Abc_NtkDelete( pNtkR ); return pNtkD; } else { Abc_NtkDelete( pNtkD ); return pNtkR; } } /**Function************************************************************* Synopsis [Computes max delay using log(n) delay model.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ float Abc_NtkComputeDelay( Abc_Ntk_t * pNtk ) { static double GateDelays[20] = { 1.00, 1.00, 2.00, 2.58, 3.00, 3.32, 3.58, 3.81, 4.00, 4.17, 4.32, 4.46, 4.58, 4.70, 4.81, 4.91, 5.00, 5.09, 5.17, 5.25 }; Vec_Ptr_t * vNodes; Abc_Obj_t * pObj, * pFanin; float DelayMax, Delays[15] = {0}; int nFaninMax, i, k; // calculate relative gate delays nFaninMax = Abc_NtkGetFaninMax( pNtk ); assert( nFaninMax > 1 && nFaninMax < 15 ); for ( i = 0; i <= nFaninMax; i++ ) Delays[i] = GateDelays[i]/GateDelays[nFaninMax]; // set max CI delay Abc_NtkForEachCi( pNtk, pObj, i ) pObj->dTemp = 0.0; // compute delays for each node vNodes = Abc_NtkDfs( pNtk, 1 ); Vec_PtrForEachEntry( Abc_Obj_t *, vNodes, pObj, i ) { pObj->dTemp = 0.0; Abc_ObjForEachFanin( pObj, pFanin, k ) pObj->dTemp = Abc_MaxFloat( pObj->dTemp, pFanin->dTemp ); pObj->dTemp += Delays[Abc_ObjFaninNum(pObj)]; } Vec_PtrFree( vNodes ); DelayMax = 0.0; // find max CO delay Abc_NtkForEachCo( pNtk, pObj, i ) DelayMax = Abc_MaxFloat( DelayMax, Abc_ObjFanin0(pObj)->dTemp ); return DelayMax; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NodeSopToCubes( Abc_Obj_t * pNodeOld, Abc_Ntk_t * pNtkNew, int fXor ) { Abc_Obj_t * pNodeOr, * pNodeNew, * pFanin; char * pCube, * pSop = (char *)pNodeOld->pData; int v, Value, nVars = Abc_ObjFaninNum(pNodeOld), nFanins; // create the root node if ( Abc_SopGetCubeNum(pSop) < 2 ) { pNodeNew = Abc_NtkDupObj( pNtkNew, pNodeOld, 0 ); Abc_ObjForEachFanin( pNodeOld, pFanin, v ) Abc_ObjAddFanin( pNodeNew, pFanin->pCopy ); assert( pNodeOld->pCopy == pNodeNew ); return; } // add the OR gate pNodeOr = Abc_NtkCreateNode( pNtkNew ); if ( fXor ) pNodeOr->pData = Abc_SopCreateXorSpecial( (Mem_Flex_t *)pNtkNew->pManFunc, Abc_SopGetCubeNum(pSop) ); else pNodeOr->pData = Abc_SopCreateOr( (Mem_Flex_t *)pNtkNew->pManFunc, Abc_SopGetCubeNum(pSop), NULL ); // check the logic function of the node Abc_SopForEachCube( pSop, nVars, pCube ) { nFanins = 0; Abc_CubeForEachVar( pCube, Value, v ) if ( Value == '0' || Value == '1' ) nFanins++; if ( nFanins == 0 ) // const1 cube in ESOP { pNodeNew = Abc_NtkCreateNodeConst1( pNtkNew ); Abc_ObjAddFanin( pNodeOr, pNodeNew ); continue; } assert( nFanins > 0 ); // create node pNodeNew = Abc_NtkCreateNode( pNtkNew ); pNodeNew->pData = Abc_SopCreateAnd( (Mem_Flex_t *)pNtkNew->pManFunc, nFanins, NULL ); nFanins = 0; Abc_CubeForEachVar( pCube, Value, v ) { if ( Value != '0' && Value != '1' ) continue; Abc_ObjAddFanin( pNodeNew, Abc_ObjFanin(pNodeOld, v)->pCopy ); if ( Value == '0' ) Abc_SopComplementVar( (char *)pNodeNew->pData, nFanins ); nFanins++; } Abc_ObjAddFanin( pNodeOr, pNodeNew ); } // check the complement if ( Abc_SopIsComplement(pSop) ) Abc_SopComplement( (char *)pNodeOr->pData ); // mark the old node with the new one assert( pNodeOld->pCopy == NULL ); pNodeOld->pCopy = pNodeOr; } Abc_Ntk_t * Abc_NtkSopToCubes( Abc_Ntk_t * pNtk, int fXor ) { Abc_Ntk_t * pNtkNew; Abc_Obj_t * pNode; Vec_Ptr_t * vNodes; int i; assert( Abc_NtkIsSopLogic(pNtk) ); Abc_NtkCleanCopy( pNtk ); pNtkNew = Abc_NtkStartFrom( pNtk, ABC_NTK_LOGIC, ABC_FUNC_SOP ); // perform conversion in the topological order vNodes = Abc_NtkDfs( pNtk, 0 ); Vec_PtrForEachEntry( Abc_Obj_t *, vNodes, pNode, i ) Abc_NodeSopToCubes( pNode, pNtkNew, fXor ); Vec_PtrFree( vNodes ); // make sure everything is okay Abc_NtkFinalize( pNtk, pNtkNew ); if ( !Abc_NtkCheck( pNtkNew ) ) { printf( "Abc_NtkSopToCubes: The network check has failed.\n" ); Abc_NtkDelete( pNtkNew ); return NULL; } return pNtkNew; } /**Function************************************************************* Synopsis [Creates precomputed reverse topological order for each node.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ static inline int Abc_NtkTopoHasBeg( Abc_Obj_t * p ) { return Vec_IntEntry(p->pNtk->vTopo, 2*Abc_ObjId(p) ); } static inline int Abc_NtkTopoHasEnd( Abc_Obj_t * p ) { return Vec_IntEntry(p->pNtk->vTopo, 2*Abc_ObjId(p)+1); } static inline void Abc_NtkTopoSetBeg( Abc_Obj_t * p ) { Vec_IntWriteEntry(p->pNtk->vTopo, 2*Abc_ObjId(p) , Vec_IntSize(p->pNtk->vTopo)); } static inline void Abc_NtkTopoSetEnd( Abc_Obj_t * p ) { Vec_IntWriteEntry(p->pNtk->vTopo, 2*Abc_ObjId(p)+1, Vec_IntSize(p->pNtk->vTopo)); } void Abc_NtkReverseTopoOrder_rec( Abc_Obj_t * pObj, int fThisIsPivot ) { Abc_Obj_t * pNext, * pPivot = NULL; int i; if ( Abc_NodeIsTravIdCurrent( pObj ) ) return; Abc_NodeSetTravIdCurrent( pObj ); if ( Abc_ObjIsPo(pObj) ) { Vec_IntPush( pObj->pNtk->vTopo, Abc_ObjId(pObj) ); return; } assert( Abc_ObjIsNode(pObj) ); // mark begining if ( fThisIsPivot ) Abc_NtkTopoSetBeg( pObj ); // find fanout without topo Abc_ObjForEachFanout( pObj, pNext, i ) if ( !Abc_NtkTopoHasBeg(pNext) ) { assert( !Abc_NtkTopoHasEnd(pNext) ); Abc_NtkReverseTopoOrder_rec( pNext, 1 ); pPivot = pNext; break; } Abc_ObjForEachFanout( pObj, pNext, i ) if ( pNext != pPivot ) Abc_NtkReverseTopoOrder_rec( pNext, 0 ); // mark end if ( fThisIsPivot ) Abc_NtkTopoSetEnd( pObj ); // save current node Vec_IntPush( pObj->pNtk->vTopo, Abc_ObjId(pObj) ); } void Abc_NtkReverseTopoOrder( Abc_Ntk_t * p ) { Abc_Obj_t * pObj; int i; assert( p->vTopo == NULL ); p->vTopo = Vec_IntAlloc( 10 * Abc_NtkObjNumMax(p) ); Vec_IntFill( p->vTopo, 2 * Abc_NtkObjNumMax(p), 0 ); Abc_NtkForEachNode( p, pObj, i ) { if ( Abc_NtkTopoHasBeg(pObj) ) continue; Abc_NtkIncrementTravId( p ); Abc_NtkReverseTopoOrder_rec( pObj, 1 ); } printf( "Nodes = %d. Size = %d. Ratio = %f.\n", Abc_NtkNodeNum(p), Vec_IntSize(p->vTopo), 1.0*Vec_IntSize(p->vTopo)/Abc_NtkNodeNum(p) ); } void Abc_NtkReverse_rec( Abc_Obj_t * pObj, Vec_Int_t * vVisited ) { Abc_Obj_t * pNext; int i; if ( Abc_NodeIsTravIdCurrent( pObj ) ) return; Abc_NodeSetTravIdCurrent( pObj ); Abc_ObjForEachFanout( pObj, pNext, i ) Abc_NtkReverse_rec( pNext, vVisited ); Vec_IntPush( vVisited, Abc_ObjId(pObj) ); } void Abc_NtkReverseTopoOrderTest( Abc_Ntk_t * p ) { Vec_Int_t * vVisited; Abc_Obj_t * pObj; int i;//, k, iBeg, iEnd; abctime clk = Abc_Clock(); Abc_NtkReverseTopoOrder( p ); /* printf( "Reverse topological order for nodes:\n" ); Abc_NtkForEachNode( p, pObj, i ) { iBeg = Abc_NtkTopoHasBeg( pObj ); iEnd = Abc_NtkTopoHasEnd( pObj ); printf( "Node %4d : ", Abc_ObjId(pObj) ); for ( k = iEnd - 1; k >= iBeg; k-- ) printf( "%d ", Vec_IntEntry(p->vTopo, k) ); printf( "\n" ); } */ Vec_IntFreeP( &p->vTopo ); Abc_PrintTime( 1, "Time", Abc_Clock() - clk ); // compute regular fanout orders clk = Abc_Clock(); vVisited = Vec_IntAlloc( 1000 ); Abc_NtkForEachNode( p, pObj, i ) { Vec_IntClear( vVisited ); Abc_NtkIncrementTravId( p ); Abc_NtkReverse_rec( pObj, vVisited ); } Vec_IntFree( vVisited ); Abc_PrintTime( 1, "Time", Abc_Clock() - clk ); } /**Function************************************************************* Synopsis [Converts multi-output PLA into an AIG with logic sharing.] Description [The first argument is an array of char*-strings representing individual output of a multi-output PLA. The number of inputs (nInputs) and the number of outputs (nOutputs) are the second and third arguments. This procedure returns the AIG manager with the given number of inputs and outputs representing the PLA as a logic network with sharing. For example, if the original PLA is 1000 10 0110 01 0011 01 the individual PLA for each the two outputs should be 1000 1 and 0110 1 0011 1 Reprsentation in terms of two char*-strings will be: char * pPlas[2] = { "1000 1\n", "0110 1\n0011 1\n" }; The call to the procedure may look as follows: Abc_Ntk_t * pNtkAig = Abc_NtkFromPla( pPlas, 4, 2 );] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Ntk_t * Abc_NtkFromPla( char ** pPlas, int nInputs, int nOutputs ) { Fxu_Data_t Params, * p = &Params; Abc_Ntk_t * pNtkSop, * pNtkAig; Abc_Obj_t * pNode, * pFanin; int i, k; // allocate logic network with SOP local functions pNtkSop = Abc_NtkAlloc( ABC_NTK_LOGIC, ABC_FUNC_SOP, 1 ); pNtkSop->pName = Extra_FileNameGeneric("pla"); // create primary inputs/outputs for ( i = 0; i < nInputs; i++ ) Abc_NtkCreatePi( pNtkSop ); for ( i = 0; i < nOutputs; i++ ) Abc_NtkCreatePo( pNtkSop ); Abc_NtkAddDummyPiNames( pNtkSop ); Abc_NtkAddDummyPoNames( pNtkSop ); // create internal nodes for ( i = 0; i < nOutputs; i++ ) { pNode = Abc_NtkCreateNode( pNtkSop ); Abc_NtkForEachPi( pNtkSop, pFanin, k ) Abc_ObjAddFanin( pNode, pFanin ); pNode->pData = Abc_SopRegister( (Mem_Flex_t *)pNtkSop->pManFunc, pPlas[i] ); Abc_ObjAddFanin( Abc_NtkPo(pNtkSop, i), pNode ); // check that the number of inputs is the same assert( Abc_SopGetVarNum((char*)pNode->pData) == nInputs ); } if ( !Abc_NtkCheck( pNtkSop ) ) fprintf( stdout, "Abc_NtkFromPla(): Network check has failed.\n" ); // perform fast_extract Abc_NtkSetDefaultFxParams( p ); Abc_NtkFastExtract( pNtkSop, p ); Abc_NtkFxuFreeInfo( p ); // convert to an AIG pNtkAig = Abc_NtkStrash( pNtkSop, 0, 1, 0 ); Abc_NtkDelete( pNtkSop ); return pNtkAig; } void Abc_NtkFromPlaTest() { char * pPlas[2] = { "1000 1\n", "0110 1\n0011 1\n" }; Abc_Ntk_t * pNtkAig = Abc_NtkFromPla( pPlas, 4, 2 ); Io_WriteBlifLogic( pNtkAig, "temp.blif", 0 ); Abc_NtkDelete( pNtkAig ); } /**Function************************************************************* Synopsis [Checks if the logic network is in the topological order.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Ntk_t * Abc_NtkSplitSop( Abc_Ntk_t * pNtk, int nCubesMax, int fVerbose ) { Vec_Ptr_t * vNodes; Abc_Ntk_t * pNtkNew; Abc_Obj_t * pObj, * pFanin, * pObjNew, * pObjNewRoot; int i, k, j, nCubes, nCubesThis, nSplits; char * pSopStr, * pSopStr2, * pTempSop, Symb; if ( pNtk == NULL ) return NULL; assert( !Abc_NtkIsStrash(pNtk) && !Abc_NtkIsNetlist(pNtk) ); // start the network pNtkNew = Abc_NtkStartFrom( pNtk, pNtk->ntkType, pNtk->ntkFunc ); // copy the internal nodes vNodes = Abc_NtkDfs( pNtk, 0 ); Vec_PtrForEachEntry( Abc_Obj_t *, vNodes, pObj, i ) { assert( Abc_ObjIsNode(pObj) ); pObjNewRoot = Abc_NtkDupObj( pNtkNew, pObj, 0 ); nCubes = Abc_SopGetCubeNum( (char *)pObj->pData ); if ( nCubes <= nCubesMax ) { Abc_ObjForEachFanin( pObj, pFanin, k ) Abc_ObjAddFanin( pObj->pCopy, pFanin->pCopy ); continue; } nSplits = (nCubes / nCubesMax) + (int)(nCubes % nCubesMax > 0); pSopStr = (char *)pObjNewRoot->pData; pObjNewRoot->pData = Abc_SopCreateOr((Mem_Flex_t *)pNtkNew->pManFunc, nSplits, NULL); if ( Abc_SopIsComplement(pSopStr) ) { Abc_SopComplement( pSopStr ); Abc_SopComplement( (char *)pObjNewRoot->pData ); } pTempSop = (char *)pObj->pData; pObj->pData = (char *)"?"; for ( j = 0; j < nSplits; j++ ) { // clone the node pObjNew = Abc_NtkDupObj( pNtkNew, pObj, 0 ); Abc_ObjAddFanin( pObjNewRoot, pObjNew ); // get its cubes Abc_ObjForEachFanin( pObj, pFanin, k ) Abc_ObjAddFanin( pObj->pCopy, pFanin->pCopy ); // create SOP for this node nCubesThis = (j < nCubes / nCubesMax) ? nCubesMax : nCubes % nCubesMax; pSopStr2 = pSopStr + (Abc_ObjFaninNum(pObj) + 3) * nCubesThis; Symb = *pSopStr2; *pSopStr2 = 0; pObjNew->pData = Abc_SopRegister( (Mem_Flex_t *)pNtkNew->pManFunc, pSopStr ); *pSopStr2 = Symb; pSopStr = pSopStr2; } // update pObj->pData = pTempSop; pObj->pCopy = pObjNewRoot; } Vec_PtrFree( vNodes ); Abc_NtkFinalize( pNtk, pNtkNew ); // check correctness if ( !Abc_NtkCheck( pNtkNew ) ) fprintf( stdout, "Abc_NtkDup(): Network check has failed.\n" ); pNtk->pCopy = pNtkNew; return pNtkNew; } /**Function************************************************************* Synopsis [Checks if the logic network is in the topological order.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkIsTopo( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj, * pFanin; int i, k, Counter = 0; Abc_NtkIncrementTravId( pNtk ); Abc_NtkForEachCi( pNtk, pObj, i ) Abc_NodeSetTravIdCurrent(pObj); Abc_NtkForEachNode( pNtk, pObj, i ) { // check if fanins are in the topo order Abc_ObjForEachFanin( pObj, pFanin, k ) if ( !Abc_NodeIsTravIdCurrent(pFanin) ) break; if ( k != Abc_ObjFaninNum(pObj) ) { if ( Counter++ == 0 ) printf( "Node %d is out of topo order.\n", Abc_ObjId(pObj) ); } Abc_NodeSetTravIdCurrent(pObj); } if ( Counter ) printf( "Topological order does not hold for %d internal nodes.\n", Counter ); return (int)(Counter == 0); } /**Function************************************************************* Synopsis [Transfers phase information to the new network.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkTransferPhases( Abc_Ntk_t * pNtkNew, Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; assert( pNtk->vPhases != NULL ); assert( Vec_IntSize(pNtk->vPhases) == Abc_NtkObjNumMax(pNtk) ); assert( pNtkNew->vPhases == NULL ); pNtkNew->vPhases = Vec_IntStart( Abc_NtkObjNumMax(pNtkNew) ); Abc_NtkForEachObj( pNtk, pObj, i ) if ( pObj->pCopy && !Abc_ObjIsNone( (Abc_Obj_t *)pObj->pCopy ) ) Vec_IntWriteEntry( pNtkNew->vPhases, Abc_ObjId( (Abc_Obj_t *)pObj->pCopy ), Vec_IntEntry(pNtk->vPhases, i) ); } /**Function************************************************************* Synopsis [Starts a new network using existing network as a model.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Ntk_t * Abc_NtkDeriveWithOnePo( Abc_Ntk_t * pNtk, Vec_Int_t * vNodeIds, Vec_Int_t * vNodeValues ) { int fCopyNames = 1; Abc_Ntk_t * pNtkNew; Abc_Obj_t * pObj, * pFanin, * pObjNew, * pOutputNew; Vec_Ptr_t * vFanins = Vec_PtrAlloc( 100 ); int i, k, Id, Value; // start the network pNtkNew = Abc_NtkAlloc( pNtk->ntkType, pNtk->ntkFunc, 1 ); // duplicate the name and the spec pNtkNew->pName = Extra_UtilStrsav(pNtk->pName); pNtkNew->pSpec = Extra_UtilStrsav(pNtk->pSpec); // clean the node copy fields Abc_NtkCleanCopy( pNtk ); // map the constant nodes if ( Abc_NtkIsStrash(pNtk) && Abc_NtkIsStrash(pNtkNew) ) Abc_AigConst1(pNtk)->pCopy = Abc_AigConst1(pNtkNew); // clone CIs/CIs/boxes Abc_NtkForEachPi( pNtk, pObj, i ) Abc_NtkDupObj( pNtkNew, pObj, fCopyNames ); //Abc_NtkForEachPo( pNtk, pObj, i ) // Abc_NtkDupObj( pNtkNew, pObj, fCopyNames ); // create one PO pObjNew = Abc_NtkCreateObj( pNtkNew, ABC_OBJ_PO ); Abc_ObjAssignName( pObjNew, "monitor", NULL ); // create boxes Abc_NtkForEachBox( pNtk, pObj, i ) Abc_NtkDupBox( pNtkNew, pObj, fCopyNames ); // duplicate nodes (CIs/COs/latches are already duplicated) Abc_NtkForEachObj( pNtk, pObj, i ) if ( pObj->pCopy == NULL && !Abc_ObjIsPo(pObj) ) Abc_NtkDupObj(pNtkNew, pObj, 0); // reconnect all objects except boxes (they are already connected) and POs (they will be connected later) Abc_NtkForEachObj( pNtk, pObj, i ) if ( !Abc_ObjIsPo(pObj) && !Abc_ObjIsBox(pObj) && !Abc_ObjIsBo(pObj) ) Abc_ObjForEachFanin( pObj, pFanin, k ) Abc_ObjAddFanin( pObj->pCopy, pFanin->pCopy ); // AND nodes (with interters if needed) pOutputNew = NULL; Vec_IntForEachEntryTwo( vNodeIds, vNodeValues, Id, Value, i ) { pObjNew = Abc_NtkObj( pNtk, Id )->pCopy; if ( Value == 0 ) // negative polarity - add inverter pObjNew = Abc_NtkCreateNodeInv( pNtkNew, pObjNew ); if ( pOutputNew == NULL ) pOutputNew = pObjNew; else { Vec_PtrFillTwo( vFanins, 2, pOutputNew, pObjNew ); pOutputNew = Abc_NtkCreateNodeAnd( pNtkNew, vFanins ); } } Vec_PtrFree( vFanins ); // create the only POs, which is the AND of the corresponding nodes Abc_ObjAddFanin( Abc_NtkPo(pNtkNew, 0), pOutputNew ); // check that the CI/CO/latches are copied correctly assert( Abc_NtkPoNum(pNtkNew) == 1 ); assert( Abc_NtkCiNum(pNtkNew) == Abc_NtkCiNum(pNtk) ); assert( Abc_NtkLatchNum(pNtkNew) == Abc_NtkLatchNum(pNtk) ); return pNtkNew; } /**Function************************************************************* Synopsis [Derives the AIG representing a property.] Description [Given is a sequential logic network (Abc_Ntk_t) and an array of nodes (vector of object IDs) and their values (vector of 0s or 1s). This procedure creates a sequential AIG (Abc_Ntk_t), which can be given to a sequential model checker (in particular "pdr") to prove that the given combination of values never appears at the intenal nodes of the network, or produce a counter-example showing that it can appear.] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Ntk_t * Abc_NtkCreatePropertyMonitor( Abc_Ntk_t * p, Vec_Int_t * vNodeIds, Vec_Int_t * vNodeValues ) { Abc_Ntk_t * pMonitor, * pStrashed, * pResult; // sequential cleanup parameters int fLatchConst = 1; int fLatchEqual = 1; int fSaveNames = 1; int fUseMvSweep = 0; int nFramesSymb = 1; int nFramesSatur = 512; int fVerbose = 0; int fVeryVerbose = 0; // expecting sequential logic network assert( Abc_NtkIsLogic(p) ); assert( Abc_NtkLatchNum(p) > 0 ); assert( Vec_IntSize(vNodeIds) > 0 ); assert( Vec_IntSize(vNodeIds) == Vec_IntSize(vNodeValues) ); // derive ABC network whose only output is 1 iff the given nodes have the given values pMonitor = Abc_NtkDeriveWithOnePo( p, vNodeIds, vNodeValues ); // perform structural hashing pStrashed = Abc_NtkStrash( pMonitor, 0, 1, 0 ); Abc_NtkDelete( pMonitor ); // it is a good idea to run sequential cleanup before giving the network to PDR pResult = Abc_NtkDarLatchSweep( pStrashed, fLatchConst, fLatchEqual, fSaveNames, fUseMvSweep, nFramesSymb, nFramesSatur, fVerbose, fVeryVerbose ); Abc_NtkDelete( pStrashed ); return pResult; } /**Function************************************************************* Synopsis [Testbench.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Abc_Ntk_t * Abc_NtkCreatePropertyMonitorTest( Abc_Ntk_t * p ) { Abc_Ntk_t * pNtk; Vec_Int_t * vNodeIds = Vec_IntAlloc( 100 ); Vec_Int_t * vNodeValues = Vec_IntAlloc( 100 ); // this test will only work for the network, which has nodes with internal IDs such as these Vec_IntPush( vNodeIds, 90 ); Vec_IntPush( vNodeIds, 80 ); Vec_IntPush( vNodeIds, 100 ); Vec_IntPush( vNodeValues, 1 ); Vec_IntPush( vNodeValues, 0 ); Vec_IntPush( vNodeValues, 1 ); pNtk = Abc_NtkCreatePropertyMonitor( p, vNodeIds, vNodeValues ); Vec_IntFree( vNodeIds ); Vec_IntFree( vNodeValues ); return pNtk; } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_GateToType( Abc_Obj_t * pObj ) { char * pGateName = Mio_GateReadName((Mio_Gate_t *)pObj->pData); if ( !strncmp(pGateName, "buf", 3) ) return ABC_OPER_BIT_BUF; if ( !strncmp(pGateName, "inv", 3) ) return ABC_OPER_BIT_INV; if ( !strncmp(pGateName, "and", 3) ) return ABC_OPER_BIT_AND; if ( !strncmp(pGateName, "nand", 4) ) return ABC_OPER_BIT_NAND; if ( !strncmp(pGateName, "or", 2) ) return ABC_OPER_BIT_OR; if ( !strncmp(pGateName, "nor", 3) ) return ABC_OPER_BIT_NOR; if ( !strncmp(pGateName, "xor", 3) ) return ABC_OPER_BIT_XOR; if ( !strncmp(pGateName, "xnor", 4) ) return ABC_OPER_BIT_NXOR; if ( !strncmp(pGateName, "zero", 4) ) return ABC_OPER_CONST_F; if ( !strncmp(pGateName, "one", 3) ) return ABC_OPER_CONST_T; assert( 0 ); return -1; } Vec_Wec_t * Abc_SopSynthesize( Vec_Ptr_t * vSops ) { Vec_Wec_t * vRes = NULL; Abc_Ntk_t * pNtk = Abc_NtkCreateFromSops( "top", vSops ); Abc_Ntk_t * pNtkNew; Abc_Obj_t * pObj, * pFanin; int i, k, iNode = 0; Abc_FrameReplaceCurrentNetwork( Abc_FrameReadGlobalFrame(), pNtk ); //Cmd_CommandExecute( Abc_FrameGetGlobalFrame(), "fx; strash; balance; dc2; map -a" ); Abc_FrameSetBatchMode( 1 ); Cmd_CommandExecute( Abc_FrameGetGlobalFrame(), "st; collapse; sop; fx; strash; &get; &ps; &deepsyn -I 4 -J 50 -T 5 -S 111 -t; &ps; &put; map -a" ); Abc_FrameSetBatchMode( 0 ); pNtkNew = Abc_FrameReadNtk( Abc_FrameReadGlobalFrame() ); vRes = Vec_WecStart( Abc_NtkPiNum(pNtkNew) + Abc_NtkNodeNum(pNtkNew) + Abc_NtkPoNum(pNtkNew) ); Abc_NtkForEachPi( pNtkNew, pObj, i ) pObj->iTemp = iNode++; Abc_NtkForEachNode( pNtkNew, pObj, i ) { Vec_Int_t * vNode = Vec_WecEntry(vRes, iNode); Vec_IntPush( vNode, Abc_GateToType(pObj) ); Vec_IntPush( vNode, iNode ); Abc_ObjForEachFanin( pObj, pFanin, k ) Vec_IntPush( vNode, pFanin->iTemp ); pObj->iTemp = iNode++; } Abc_NtkForEachPo( pNtkNew, pObj, i ) Vec_IntPushTwo( Vec_WecEntry(vRes, iNode++), ABC_OPER_BIT_BUF, Abc_ObjFanin0(pObj)->iTemp ); assert( Vec_WecSize(vRes) == iNode ); return vRes; } Vec_Wec_t * Abc_GiaSynthesize( Vec_Ptr_t * vGias, Gia_Man_t * pMulti ) { Vec_Wec_t * vRes = NULL; Abc_Ntk_t * pNtk = Abc_NtkCreateFromGias( "top", vGias, pMulti ); Abc_Ntk_t * pNtkNew; Abc_Obj_t * pObj, * pFanin; int i, k, iNode = 0; Abc_FrameReplaceCurrentNetwork( Abc_FrameReadGlobalFrame(), pNtk ); Abc_FrameSetBatchMode( 1 ); Cmd_CommandExecute( Abc_FrameGetGlobalFrame(), "clp; sop; fx; strash; compress2rs; dch; map -a; strash; compress2rs; dch; map -a" ); Abc_FrameSetBatchMode( 0 ); pNtkNew = Abc_FrameReadNtk( Abc_FrameReadGlobalFrame() ); vRes = Vec_WecStart( Abc_NtkPiNum(pNtkNew) + Abc_NtkNodeNum(pNtkNew) + Abc_NtkPoNum(pNtkNew) ); Abc_NtkForEachPi( pNtkNew, pObj, i ) pObj->iTemp = iNode++; Abc_NtkForEachNode( pNtkNew, pObj, i ) { Vec_Int_t * vNode = Vec_WecEntry(vRes, iNode); Vec_IntPush( vNode, Abc_GateToType(pObj) ); Vec_IntPush( vNode, iNode ); Abc_ObjForEachFanin( pObj, pFanin, k ) Vec_IntPush( vNode, pFanin->iTemp ); pObj->iTemp = iNode++; } Abc_NtkForEachPo( pNtkNew, pObj, i ) Vec_IntPushTwo( Vec_WecEntry(vRes, iNode++), ABC_OPER_BIT_BUF, Abc_ObjFanin0(pObj)->iTemp ); assert( Vec_WecSize(vRes) == iNode ); return vRes; } Gia_Man_t * Abc_GiaSynthesizeInter( Gia_Man_t * p ) { Abc_Ntk_t * pNtkNew, * pNtk; Vec_Ptr_t * vGias = Vec_PtrAlloc( 1 ); Vec_PtrPush( vGias, p ); pNtk = Abc_NtkCreateFromGias( "top", vGias, NULL ); Vec_PtrFree( vGias ); Abc_FrameReplaceCurrentNetwork( Abc_FrameReadGlobalFrame(), pNtk ); Cmd_CommandExecute( Abc_FrameGetGlobalFrame(), "balance; collapse; muxes; strash; dc2" ); pNtkNew = Abc_FrameReadNtk( Abc_FrameReadGlobalFrame() ); return Abc_NtkClpGia( pNtkNew ); } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkClpOneGia_rec( Gia_Man_t * pNew, Abc_Obj_t * pNode ) { int iLit0, iLit1; if ( Abc_NodeIsTravIdCurrent(pNode) || Abc_ObjFaninNum(pNode) == 0 || Abc_ObjIsCi(pNode) ) return pNode->iTemp; assert( Abc_ObjIsNode( pNode ) ); Abc_NodeSetTravIdCurrent( pNode ); iLit0 = Abc_NtkClpOneGia_rec( pNew, Abc_ObjFanin0(pNode) ); iLit1 = Abc_NtkClpOneGia_rec( pNew, Abc_ObjFanin1(pNode) ); iLit0 = Abc_LitNotCond( iLit0, Abc_ObjFaninC0(pNode) ); iLit1 = Abc_LitNotCond( iLit1, Abc_ObjFaninC1(pNode) ); return (pNode->iTemp = Gia_ManHashAnd(pNew, iLit0, iLit1)); } Gia_Man_t * Abc_NtkStrashToGia( Abc_Ntk_t * pNtk ) { int i, iLit; Abc_Obj_t * pNode; Gia_Man_t * pNew, * pTemp; assert( Abc_NtkIsStrash(pNtk) ); Abc_NtkForEachObj( pNtk, pNode, i ) pNode->iTemp = -1; // start new manager pNew = Gia_ManStart( Abc_NtkObjNum(pNtk) ); pNew->pName = Abc_UtilStrsav( pNtk->pName ); pNew->pSpec = Abc_UtilStrsav( pNtk->pSpec ); Gia_ManHashStart( pNew ); // primary inputs Abc_AigConst1(pNtk)->iTemp = 1; Abc_NtkForEachCi( pNtk, pNode, i ) pNode->iTemp = Gia_ManAppendCi(pNew); // create the first cone Abc_NtkIncrementTravId( pNtk ); Abc_NtkForEachCo( pNtk, pNode, i ) { iLit = Abc_NtkClpOneGia_rec( pNew, Abc_ObjFanin0(pNode) ); iLit = Abc_LitNotCond( iLit, Abc_ObjFaninC0(pNode) ); Gia_ManAppendCo( pNew, iLit ); } // perform cleanup pNew = Gia_ManCleanup( pTemp = pNew ); Gia_ManStop( pTemp ); return pNew; } Gia_Man_t * Abc_SopSynthesizeOne( char * pSop, int fClp ) { Abc_Ntk_t * pNtkNew, * pNtk; Vec_Ptr_t * vSops; if ( strlen(pSop) == 3 ) { Gia_Man_t * pNew = Gia_ManStart( 1 ); pNew->pName = Abc_UtilStrsav( "top" ); //Gia_ManAppendCi( pNew ); assert( pSop[1] == '0' || pSop[1] == '1' ); Gia_ManAppendCo( pNew, pSop[1] == '1' ); return pNew; } vSops = Vec_PtrAlloc( 1 ); Vec_PtrPush( vSops, pSop ); pNtk = Abc_NtkCreateFromSops( "top", vSops ); Vec_PtrFree( vSops ); Abc_FrameReplaceCurrentNetwork( Abc_FrameReadGlobalFrame(), pNtk ); Abc_FrameSetBatchMode( 1 ); if ( fClp ) Cmd_CommandExecute( Abc_FrameGetGlobalFrame(), "clp; sop" ); Cmd_CommandExecute( Abc_FrameGetGlobalFrame(), "fx; strash; balance; dc2" ); Abc_FrameSetBatchMode( 0 ); pNtkNew = Abc_FrameReadNtk( Abc_FrameReadGlobalFrame() ); return Abc_NtkStrashToGia( pNtkNew ); } /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ static int s_ArraySize = 145; static int s_ArrayData[290] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 6, 14, 12, 10, 2, 22, 20, 2, 24, 16, 4, 28, 18, 16, 10, 8, 4, 34, 32, 30, 36, 38, 26, 16, 6, 36, 20, 44, 42, 46, 40, 42, 44, 14, 6, 52, 34, 32, 54, 56, 50, 58, 48, 32, 24, 20, 2, 12, 6, 66, 34, 68, 64, 62, 70, 28, 68, 74, 72, 76, 58, 70, 62, 80, 78, 68, 28, 84, 74, 4, 2, 88, 20, 64, 90, 92, 86, 66, 32, 18, 96, 98, 56, 100, 94, 52, 36, 104, 38, 90, 42, 36, 2, 108, 110, 112, 106, 114, 100, 102, 116, 118, 82, 116, 60, 120, 122, 124, 60, 118, 60, 102, 82, 128, 130, 132, 82, 134, 126, 82, 116, 122, 138, 122, 118, 142, 140, 60, 102, 130, 146, 130, 118, 150, 148, 152, 144, 154, 136, 18, 156, 144, 126, 68, 160, 32, 136, 164, 162, 166, 158, 28, 160, 70, 126, 90, 144, 174, 172, 176, 170, 152, 134, 36, 180, 2, 134, 184, 182, 186, 178, 188, 168, 64, 144, 164, 158, 194, 192, 96, 156, 44, 154, 200, 170, 202, 198, 204, 176, 206, 196, 204, 168, 62, 126, 212, 186, 24, 134, 108, 152, 218, 192, 220, 216, 222, 214, 224, 210, 220, 194, 110, 152, 30, 180, 232, 230, 184, 172, 236, 234, 238, 228, 234, 182, 242, 220, 244, 168, 42, 154, 248, 202, 54, 136, 252, 164, 254, 214, 256, 250, 218, 194, 252, 198, 262, 242, 264, 260, 232, 220, 268, 262, 270, 168, 191, 191, 209, 209, 226, 226, 240, 240, 246, 246, 259, 259, 267, 267, 272, 272, }; int Abc_NtkHasConstNode() { int i; for ( i = 1; i < s_ArraySize; i++ ) if ( s_ArrayData[2*i] || s_ArrayData[2*i+1] ) break; for ( ; i < s_ArraySize; i++ ) if ( s_ArrayData[2*i] < 2 && s_ArrayData[2*i+1] < 2 ) return 1; return 0; } Abc_Ntk_t * Abc_NtkFromArray() { Vec_Ptr_t * vNodes = Vec_PtrAlloc( s_ArraySize ); int i, nPos = 0; Abc_Ntk_t * pNtkNew = Abc_NtkAlloc( ABC_NTK_LOGIC, ABC_FUNC_SOP, 1 ); Abc_Obj_t * pObjNew = Abc_NtkHasConstNode() ? Abc_NtkCreateNode(pNtkNew) : NULL; if ( pObjNew ) pObjNew->pData = Abc_SopCreateConst0((Mem_Flex_t *)pNtkNew->pManFunc); Vec_PtrPush( vNodes, pObjNew ); for ( i = 1; i < s_ArraySize; i++ ) if ( !s_ArrayData[2*i] && !s_ArrayData[2*i+1] ) Vec_PtrPush( vNodes, Abc_NtkCreatePi(pNtkNew) ); else break; for ( ; i < s_ArraySize; i++ ) { char * pSop = NULL; if ( s_ArrayData[2*i] > s_ArrayData[2*i+1] ) pSop = Abc_SopCreateXor( (Mem_Flex_t *)pNtkNew->pManFunc, 2 ); else if ( s_ArrayData[2*i] < s_ArrayData[2*i+1] ) pSop = Abc_SopCreateAnd( (Mem_Flex_t *)pNtkNew->pManFunc, 2, NULL ); else break; pObjNew = Abc_NtkCreateNode( pNtkNew ); Abc_ObjAddFanin( pObjNew, (Abc_Obj_t *)Vec_PtrEntry(vNodes, Abc_Lit2Var(s_ArrayData[2*i])) ); Abc_ObjAddFanin( pObjNew, (Abc_Obj_t *)Vec_PtrEntry(vNodes, Abc_Lit2Var(s_ArrayData[2*i+1])) ); if ( Abc_LitIsCompl(s_ArrayData[2*i]) ) Abc_SopComplementVar( pSop, 0 ); if ( Abc_LitIsCompl(s_ArrayData[2*i+1]) ) Abc_SopComplementVar( pSop, 1 ); pObjNew->pData = pSop; Vec_PtrPush( vNodes, pObjNew ); } for ( ; i < s_ArraySize; i++ ) { char * pSop = NULL; assert( s_ArrayData[2*i] == s_ArrayData[2*i+1] ); pObjNew = Abc_NtkCreateNode( pNtkNew ); Abc_ObjAddFanin( pObjNew, (Abc_Obj_t *)Vec_PtrEntry(vNodes, Abc_Lit2Var(s_ArrayData[2*i])) ); if ( Abc_LitIsCompl(s_ArrayData[2*i]) ) pSop = Abc_SopCreateInv( (Mem_Flex_t *)pNtkNew->pManFunc ); else pSop = Abc_SopCreateBuf( (Mem_Flex_t *)pNtkNew->pManFunc ); pObjNew->pData = pSop; Vec_PtrPush( vNodes, pObjNew ); nPos++; } for ( i = 0; i < nPos; i++ ) Abc_ObjAddFanin( Abc_NtkCreatePo(pNtkNew), (Abc_Obj_t *)Vec_PtrEntry(vNodes, s_ArraySize-nPos+i) ); Vec_PtrFree( vNodes ); pNtkNew->pName = Extra_UtilStrsav("test"); Abc_NtkAddDummyPiNames( pNtkNew ); Abc_NtkAddDummyPoNames( pNtkNew ); Abc_NtkAddDummyBoxNames( pNtkNew ); if ( !Abc_NtkCheck( pNtkNew ) ) Abc_Print( 1, "Abc_NtkFromArray(): Network check has failed.\n" ); return pNtkNew; } //////////////////////////////////////////////////////////////////////// /// END OF FILE /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_IMPL_END
0d5f034b59093888e6f33b81208ee60864281f8c
473b1af5f787d5653701684e7223453fa6c2d70a
/cc/crypto/hpke/jni/com_google_oak_crypto_hpke_Context_RecipientRequestContext.h
f31451e6be173ec1117318d090850d4933e2c8ed
[ "Apache-2.0" ]
permissive
project-oak/oak
2b6200476528ce7537876b7f178a55b02298a807
a534e3c2fc4308ef6a77b71748af7334d9e7f161
refs/heads/main
2023-09-03T07:43:11.343182
2023-08-31T19:10:05
2023-09-01T17:08:53
173,796,172
948
98
Apache-2.0
2023-09-14T20:13:32
2019-03-04T18:08:59
Rust
UTF-8
C
false
true
923
h
com_google_oak_crypto_hpke_Context_RecipientRequestContext.h
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_google_oak_crypto_hpke_Context_RecipientRequestContext */ #ifndef _Included_com_google_oak_crypto_hpke_Context_RecipientRequestContext #define _Included_com_google_oak_crypto_hpke_Context_RecipientRequestContext #ifdef __cplusplus extern "C" { #endif /* * Class: com_google_oak_crypto_hpke_Context_RecipientRequestContext * Method: nativeOpen * Signature: ([B[B)[B */ JNIEXPORT jbyteArray JNICALL Java_com_google_oak_crypto_hpke_Context_00024RecipientRequestContext_nativeOpen (JNIEnv *, jobject, jbyteArray, jbyteArray); /* * Class: com_google_oak_crypto_hpke_Context_RecipientRequestContext * Method: nativeDestroy * Signature: ()V */ JNIEXPORT void JNICALL Java_com_google_oak_crypto_hpke_Context_00024RecipientRequestContext_nativeDestroy (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif
38dbb523e3d494224e88b2c9c43e2a06c77ea5f6
c0bfd93cd7f26a271268e504959256f1e02c6806
/components/protocomm/src/security/security1.c
36d99f0a29dd611ceb19d679bd1424565f3b752e
[ "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
18,052
c
security1.c
// Copyright 2018 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 <stdlib.h> #include <string.h> #include <esp_err.h> #include <esp_log.h> #include <mbedtls/aes.h> #include <mbedtls/sha256.h> #include <mbedtls/entropy.h> #include <mbedtls/ctr_drbg.h> #include <mbedtls/ecdh.h> #include <mbedtls/error.h> #include <mbedtls/ssl_internal.h> #include <protocomm_security.h> #include <protocomm_security1.h> #include "session.pb-c.h" #include "sec1.pb-c.h" #include "constants.pb-c.h" static const char* TAG = "security1"; #define PUBLIC_KEY_LEN 32 #define SZ_RANDOM 16 #define SESSION_STATE_CMD0 0 /* Session is not setup */ #define SESSION_STATE_CMD1 1 /* Session is not setup */ #define SESSION_STATE_DONE 2 /* Session setup successful */ typedef struct session { /* Session data */ uint32_t id; uint8_t state; uint8_t device_pubkey[PUBLIC_KEY_LEN]; uint8_t client_pubkey[PUBLIC_KEY_LEN]; uint8_t sym_key[PUBLIC_KEY_LEN]; uint8_t rand[SZ_RANDOM]; /* mbedtls context data for AES */ mbedtls_aes_context ctx_aes; unsigned char stb[16]; size_t nc_off; } session_t; static session_t *cur_session; static void flip_endian(uint8_t *data, size_t len) { uint8_t swp_buf; for (int i = 0; i < len/2; i++) { swp_buf = data[i]; data[i] = data[len - i - 1]; data[len - i - 1] = swp_buf; } } static void hexdump(const char *msg, uint8_t *buf, int len) { ESP_LOGD(TAG, "%s:", msg); ESP_LOG_BUFFER_HEX_LEVEL(TAG, buf, len, ESP_LOG_DEBUG); } static esp_err_t handle_session_command1(uint32_t session_id, SessionData *req, SessionData *resp) { ESP_LOGD(TAG, "Request to handle setup1_command"); Sec1Payload *in = (Sec1Payload *) req->sec1; uint8_t check_buf[PUBLIC_KEY_LEN]; int mbed_err; if (cur_session->state != SESSION_STATE_CMD1) { ESP_LOGE(TAG, "Invalid state of session %d (expected %d)", SESSION_STATE_CMD1, cur_session->state); return ESP_ERR_INVALID_STATE; } /* Initialize crypto context */ mbedtls_aes_init(&cur_session->ctx_aes); memset(cur_session->stb, 0, sizeof(cur_session->stb)); cur_session->nc_off = 0; hexdump("Client verifier", in->sc1->client_verify_data.data, in->sc1->client_verify_data.len); mbed_err = mbedtls_aes_setkey_enc(&cur_session->ctx_aes, cur_session->sym_key, sizeof(cur_session->sym_key)*8); if (mbed_err != 0) { ESP_LOGE(TAG, "Failure at mbedtls_aes_setkey_enc with error code : -0x%x", -mbed_err); mbedtls_aes_free(&cur_session->ctx_aes); return ESP_FAIL; } mbed_err = mbedtls_aes_crypt_ctr(&cur_session->ctx_aes, PUBLIC_KEY_LEN, &cur_session->nc_off, cur_session->rand, cur_session->stb, in->sc1->client_verify_data.data, check_buf); if (mbed_err != 0) { ESP_LOGE(TAG, "Failure at mbedtls_aes_crypt_ctr with error code : -0x%x", -mbed_err); mbedtls_aes_free(&cur_session->ctx_aes); return ESP_FAIL; } hexdump("Dec Client verifier", check_buf, sizeof(check_buf)); /* constant time memcmp */ if (mbedtls_ssl_safer_memcmp(check_buf, cur_session->device_pubkey, sizeof(cur_session->device_pubkey)) != 0) { ESP_LOGE(TAG, "Key mismatch. Close connection"); mbedtls_aes_free(&cur_session->ctx_aes); return ESP_FAIL; } Sec1Payload *out = (Sec1Payload *) malloc(sizeof(Sec1Payload)); SessionResp1 *out_resp = (SessionResp1 *) malloc(sizeof(SessionResp1)); if (!out || !out_resp) { ESP_LOGE(TAG, "Error allocating memory for response1"); free(out); free(out_resp); mbedtls_aes_free(&cur_session->ctx_aes); return ESP_ERR_NO_MEM; } sec1_payload__init(out); session_resp1__init(out_resp); out_resp->status = STATUS__Success; uint8_t *outbuf = (uint8_t *) malloc(PUBLIC_KEY_LEN); if (!outbuf) { ESP_LOGE(TAG, "Error allocating ciphertext buffer"); free(out); free(out_resp); mbedtls_aes_free(&cur_session->ctx_aes); return ESP_ERR_NO_MEM; } mbed_err = mbedtls_aes_crypt_ctr(&cur_session->ctx_aes, PUBLIC_KEY_LEN, &cur_session->nc_off, cur_session->rand, cur_session->stb, cur_session->client_pubkey, outbuf); if (mbed_err != 0) { ESP_LOGE(TAG, "Failure at mbedtls_aes_crypt_ctr with error code : -0x%x", -mbed_err); free(outbuf); free(out); free(out_resp); mbedtls_aes_free(&cur_session->ctx_aes); return ESP_FAIL; } out_resp->device_verify_data.data = outbuf; out_resp->device_verify_data.len = PUBLIC_KEY_LEN; hexdump("Device verify data", outbuf, PUBLIC_KEY_LEN); out->msg = SEC1_MSG_TYPE__Session_Response1; out->payload_case = SEC1_PAYLOAD__PAYLOAD_SR1; out->sr1 = out_resp; resp->proto_case = SESSION_DATA__PROTO_SEC1; resp->sec1 = out; cur_session->state = SESSION_STATE_DONE; ESP_LOGD(TAG, "Secure session established successfully"); return ESP_OK; } static esp_err_t handle_session_command0(uint32_t session_id, SessionData *req, SessionData *resp, const protocomm_security_pop_t *pop) { ESP_LOGD(TAG, "Request to handle setup0_command"); Sec1Payload *in = (Sec1Payload *) req->sec1; esp_err_t ret; int mbed_err; if (cur_session->state != SESSION_STATE_CMD0) { ESP_LOGE(TAG, "Invalid state of session %d (expected %d)", SESSION_STATE_CMD0, cur_session->state); return ESP_ERR_INVALID_STATE; } if (in->sc0->client_pubkey.len != PUBLIC_KEY_LEN) { ESP_LOGE(TAG, "Invalid public key length"); return ESP_ERR_INVALID_ARG; } mbedtls_ecdh_context *ctx_server = malloc(sizeof(mbedtls_ecdh_context)); mbedtls_entropy_context *entropy = malloc(sizeof(mbedtls_entropy_context)); mbedtls_ctr_drbg_context *ctr_drbg = malloc(sizeof(mbedtls_ctr_drbg_context)); if (!ctx_server || !ctx_server || !ctr_drbg) { ESP_LOGE(TAG, "Failed to allocate memory for mbedtls context"); free(ctx_server); free(entropy); free(ctr_drbg); return ESP_ERR_NO_MEM; } mbedtls_ecdh_init(ctx_server); mbedtls_ctr_drbg_init(ctr_drbg); mbedtls_entropy_init(entropy); mbed_err = mbedtls_ctr_drbg_seed(ctr_drbg, mbedtls_entropy_func, entropy, NULL, 0); if (mbed_err != 0) { ESP_LOGE(TAG, "Failed at mbedtls_ctr_drbg_seed with error code : -0x%x", -mbed_err); ret = ESP_FAIL; goto exit_cmd0; } mbed_err = mbedtls_ecp_group_load(&ctx_server->grp, MBEDTLS_ECP_DP_CURVE25519); if (mbed_err != 0) { ESP_LOGE(TAG, "Failed at mbedtls_ecp_group_load with error code : -0x%x", -mbed_err); ret = ESP_FAIL; goto exit_cmd0; } mbed_err = mbedtls_ecdh_gen_public(&ctx_server->grp, &ctx_server->d, &ctx_server->Q, mbedtls_ctr_drbg_random, ctr_drbg); if (mbed_err != 0) { ESP_LOGE(TAG, "Failed at mbedtls_ecdh_gen_public with error code : -0x%x", -mbed_err); ret = ESP_FAIL; goto exit_cmd0; } mbed_err = mbedtls_mpi_write_binary(&ctx_server->Q.X, cur_session->device_pubkey, PUBLIC_KEY_LEN); if (mbed_err != 0) { ESP_LOGE(TAG, "Failed at mbedtls_mpi_write_binary with error code : -0x%x", -mbed_err); ret = ESP_FAIL; goto exit_cmd0; } flip_endian(cur_session->device_pubkey, PUBLIC_KEY_LEN); memcpy(cur_session->client_pubkey, in->sc0->client_pubkey.data, PUBLIC_KEY_LEN); uint8_t *dev_pubkey = cur_session->device_pubkey; uint8_t *cli_pubkey = cur_session->client_pubkey; hexdump("Device pubkey", dev_pubkey, PUBLIC_KEY_LEN); hexdump("Client pubkey", cli_pubkey, PUBLIC_KEY_LEN); mbed_err = mbedtls_mpi_lset(&ctx_server->Qp.Z, 1); if (mbed_err != 0) { ESP_LOGE(TAG, "Failed at mbedtls_mpi_lset with error code : -0x%x", -mbed_err); ret = ESP_FAIL; goto exit_cmd0; } flip_endian(cur_session->client_pubkey, PUBLIC_KEY_LEN); mbed_err = mbedtls_mpi_read_binary(&ctx_server->Qp.X, cli_pubkey, PUBLIC_KEY_LEN); flip_endian(cur_session->client_pubkey, PUBLIC_KEY_LEN); if (mbed_err != 0) { ESP_LOGE(TAG, "Failed at mbedtls_mpi_read_binary with error code : -0x%x", -mbed_err); ret = ESP_FAIL; goto exit_cmd0; } mbed_err = mbedtls_ecdh_compute_shared(&ctx_server->grp, &ctx_server->z, &ctx_server->Qp, &ctx_server->d, mbedtls_ctr_drbg_random, ctr_drbg); if (mbed_err != 0) { ESP_LOGE(TAG, "Failed at mbedtls_ecdh_compute_shared with error code : -0x%x", -mbed_err); ret = ESP_FAIL; goto exit_cmd0; } mbed_err = mbedtls_mpi_write_binary(&ctx_server->z, cur_session->sym_key, PUBLIC_KEY_LEN); if (mbed_err != 0) { ESP_LOGE(TAG, "Failed at mbedtls_mpi_write_binary with error code : -0x%x", -mbed_err); ret = ESP_FAIL; goto exit_cmd0; } flip_endian(cur_session->sym_key, PUBLIC_KEY_LEN); if (pop != NULL && pop->data != NULL && pop->len != 0) { ESP_LOGD(TAG, "Adding proof of possession"); uint8_t sha_out[PUBLIC_KEY_LEN]; mbed_err = mbedtls_sha256_ret((const unsigned char *) pop->data, pop->len, sha_out, 0); if (mbed_err != 0) { ESP_LOGE(TAG, "Failed at mbedtls_sha256_ret with error code : -0x%x", -mbed_err); ret = ESP_FAIL; goto exit_cmd0; } for (int i = 0; i < PUBLIC_KEY_LEN; i++) { cur_session->sym_key[i] ^= sha_out[i]; } } hexdump("Shared key", cur_session->sym_key, PUBLIC_KEY_LEN); mbed_err = mbedtls_ctr_drbg_random(ctr_drbg, cur_session->rand, SZ_RANDOM); if (mbed_err != 0) { ESP_LOGE(TAG, "Failed at mbedtls_ctr_drbg_random with error code : -0x%x", -mbed_err); ret = ESP_FAIL; goto exit_cmd0; } hexdump("Device random", cur_session->rand, SZ_RANDOM); Sec1Payload *out = (Sec1Payload *) malloc(sizeof(Sec1Payload)); SessionResp0 *out_resp = (SessionResp0 *) malloc(sizeof(SessionResp0)); if (!out || !out_resp) { ESP_LOGE(TAG, "Error allocating memory for response0"); ret = ESP_ERR_NO_MEM; free(out); free(out_resp); goto exit_cmd0; } sec1_payload__init(out); session_resp0__init(out_resp); out_resp->status = STATUS__Success; out_resp->device_pubkey.data = dev_pubkey; out_resp->device_pubkey.len = PUBLIC_KEY_LEN; out_resp->device_random.data = (uint8_t *) cur_session->rand; out_resp->device_random.len = SZ_RANDOM; out->msg = SEC1_MSG_TYPE__Session_Response0; out->payload_case = SEC1_PAYLOAD__PAYLOAD_SR0; out->sr0 = out_resp; resp->proto_case = SESSION_DATA__PROTO_SEC1; resp->sec1 = out; cur_session->state = SESSION_STATE_CMD1; ESP_LOGD(TAG, "Session setup phase1 done"); ret = ESP_OK; exit_cmd0: mbedtls_ecdh_free(ctx_server); free(ctx_server); mbedtls_ctr_drbg_free(ctr_drbg); free(ctr_drbg); mbedtls_entropy_free(entropy); free(entropy); return ret; } static esp_err_t sec1_session_setup(uint32_t session_id, SessionData *req, SessionData *resp, const protocomm_security_pop_t *pop) { Sec1Payload *in = (Sec1Payload *) req->sec1; esp_err_t ret; if (!cur_session) { ESP_LOGE(TAG, "Invalid session context data"); return ESP_ERR_INVALID_ARG; } if (session_id != cur_session->id) { ESP_LOGE(TAG, "Invalid session ID : %d (expected %d)", session_id, cur_session->id); return ESP_ERR_INVALID_STATE; } if (!in) { ESP_LOGE(TAG, "Empty session data"); return ESP_ERR_INVALID_ARG; } switch (in->msg) { case SEC1_MSG_TYPE__Session_Command0: ret = handle_session_command0(session_id, req, resp, pop); break; case SEC1_MSG_TYPE__Session_Command1: ret = handle_session_command1(session_id, req, resp); break; default: ESP_LOGE(TAG, "Invalid security message type"); ret = ESP_ERR_INVALID_ARG; } return ret; } static void sec1_session_setup_cleanup(uint32_t session_id, SessionData *resp) { Sec1Payload *out = resp->sec1; if (!out) { return; } switch (out->msg) { case SEC1_MSG_TYPE__Session_Response0: { SessionResp0 *out_resp0 = out->sr0; if (out_resp0) { free(out_resp0); } break; } case SEC1_MSG_TYPE__Session_Response1: { SessionResp1 *out_resp1 = out->sr1; if (out_resp1) { free(out_resp1->device_verify_data.data); free(out_resp1); } break; } default: break; } free(out); return; } static esp_err_t sec1_close_session(uint32_t session_id) { if (!cur_session || cur_session->id != session_id) { ESP_LOGE(TAG, "Attempt to close invalid session"); return ESP_ERR_INVALID_ARG; } if (cur_session->state == SESSION_STATE_DONE) { /* Free AES context data */ mbedtls_aes_free(&cur_session->ctx_aes); } bzero(cur_session, sizeof(session_t)); free(cur_session); cur_session = NULL; return ESP_OK; } static esp_err_t sec1_new_session(uint32_t session_id) { if (cur_session) { /* Only one session is allowed at a time */ ESP_LOGE(TAG, "Closing old session with id %u", cur_session->id); sec1_close_session(cur_session->id); } cur_session = (session_t *) calloc(1, sizeof(session_t)); if (!cur_session) { ESP_LOGE(TAG, "Error allocating session structure"); return ESP_ERR_NO_MEM; } cur_session->id = session_id; return ESP_OK; } static esp_err_t sec1_init() { return ESP_OK; } static esp_err_t sec1_cleanup() { if (cur_session) { ESP_LOGD(TAG, "Closing current session with id %u", cur_session->id); sec1_close_session(cur_session->id); } return ESP_OK; } static esp_err_t sec1_decrypt(uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t *outbuf, ssize_t *outlen) { if (*outlen < inlen) { return ESP_ERR_INVALID_ARG; } if (!cur_session || cur_session->id != session_id) { ESP_LOGE(TAG, "Session with ID %d not found", session_id); return ESP_ERR_INVALID_STATE; } if (cur_session->state != SESSION_STATE_DONE) { ESP_LOGE(TAG, "Secure session not established"); return ESP_ERR_INVALID_STATE; } *outlen = inlen; int ret = mbedtls_aes_crypt_ctr(&cur_session->ctx_aes, inlen, &cur_session->nc_off, cur_session->rand, cur_session->stb, inbuf, outbuf); if (ret != 0) { ESP_LOGE(TAG, "Failed at mbedtls_aes_crypt_ctr with error code : %d", ret); return ESP_FAIL; } return ESP_OK; } static esp_err_t sec1_req_handler(const protocomm_security_pop_t *pop, uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen, void *priv_data) { SessionData *req; SessionData resp; esp_err_t ret; req = session_data__unpack(NULL, inlen, inbuf); if (!req) { ESP_LOGE(TAG, "Unable to unpack setup_req"); return ESP_ERR_INVALID_ARG; } if (req->sec_ver != protocomm_security1.ver) { ESP_LOGE(TAG, "Security version mismatch. Closing connection"); session_data__free_unpacked(req, NULL); return ESP_ERR_INVALID_ARG; } session_data__init(&resp); ret = sec1_session_setup(session_id, req, &resp, pop); if (ret != ESP_OK) { ESP_LOGE(TAG, "Session setup error %d", ret); session_data__free_unpacked(req, NULL); return ESP_FAIL; } resp.sec_ver = req->sec_ver; session_data__free_unpacked(req, NULL); *outlen = session_data__get_packed_size(&resp); *outbuf = (uint8_t *) malloc(*outlen); if (!*outbuf) { ESP_LOGE(TAG, "System out of memory"); return ESP_ERR_NO_MEM; } session_data__pack(&resp, *outbuf); sec1_session_setup_cleanup(session_id, &resp); return ESP_OK; } const protocomm_security_t protocomm_security1 = { .ver = 1, .init = sec1_init, .cleanup = sec1_cleanup, .new_transport_session = sec1_new_session, .close_transport_session = sec1_close_session, .security_req_handler = sec1_req_handler, .encrypt = sec1_decrypt, /* Encrypt == decrypt for AES-CTR */ .decrypt = sec1_decrypt, };
68de302998bfff290aa64c99df2a3b97da70d70d
f9e7d65cb784c01a0200145ba8d289afe41d4a56
/baseboard/honeybuns/baseboard.c
bb0a1c832d7a235d538a049a39cb9284b1628af5
[ "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,522
c
baseboard.c
/* Copyright 2020 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. */ /* Honeybuns family-specific configuration */ #include "console.h" #include "gpio.h" #include "hooks.h" #include "i2c.h" #include "timer.h" #define CPRINTS(format, args...) cprints(CC_SYSTEM, format, ## args) #define CPRINTF(format, args...) cprintf(CC_SYSTEM, format, ## args) /******************************************************************************/ __overridable const struct power_seq board_power_seq[] = { }; __overridable const size_t board_power_seq_count = ARRAY_SIZE(board_power_seq); static void board_power_sequence(void) { int i; for(i = 0; i < board_power_seq_count; i++) { gpio_set_level(board_power_seq[i].signal, board_power_seq[i].level); msleep(board_power_seq[i].delay_ms); } } /******************************************************************************/ /* I2C port map configuration */ const struct i2c_port_t i2c_ports[] = { {"usbc", I2C_PORT_USBC, 400, GPIO_EC_I2C1_SCL, GPIO_EC_I2C1_SDA}, {"usb_mst", I2C_PORT_MST, 400, GPIO_EC_I2C2_SCL, GPIO_EC_I2C2_SDA}, {"eeprom", I2C_PORT_EEPROM, 400, GPIO_EC_I2C3_SCL, GPIO_EC_I2C3_SDA}, }; const unsigned int i2c_ports_used = ARRAY_SIZE(i2c_ports); static void baseboard_init(void) { /* Turn on power rails */ board_power_sequence(); CPRINTS("board: Power rails enabled"); } DECLARE_HOOK(HOOK_INIT, baseboard_init, HOOK_PRIO_DEFAULT);
f9c18fcd1e8d1c3192c5cb42cde5949470917fa4
fb0f9abad373cd635c2635bbdf491ea0f32da5ff
/src/mono/mono/component/debugger-state-machine.c
f36a6c2397dc168f081df5a1c1f2e281db00bbb8
[ "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
13,092
c
debugger-state-machine.c
/** * \file * Support for verbose unmanaged crash dumps * * Author: * Alexander Kyte (alkyte@microsoft.com) * * (C) 2018 Microsoft, Inc. * */ #include <config.h> #include <glib.h> #include <mono/utils/json.h> #include "debugger-state-machine.h" #include <mono/metadata/object-internals.h> #include <mono/mini/mini-runtime.h> #include "debugger-engine.h" #include <mono/utils/mono-coop-mutex.h> #include <mono/utils/mono-flight-recorder.h> static const char * mono_debug_log_thread_state_to_string (MonoDebuggerThreadState state) { switch (state) { case MONO_DEBUGGER_SUSPENDED: return "suspended"; case MONO_DEBUGGER_RESUMED: return "resumed"; case MONO_DEBUGGER_TERMINATED: return "terminated"; case MONO_DEBUGGER_STARTED: return "started"; default: g_assert_not_reached (); } } typedef enum { DEBUG_LOG_ILLEGAL = 0x0, DEBUG_LOG_STATE_CHANGE = 0x1, DEBUG_LOG_BREAKPOINT = 0x2, DEBUG_LOG_COMMAND = 0x3, DEBUG_LOG_EVENT = 0x4, DEBUG_LOG_EXIT = 0x5 } MonoDebugLogKind; // Number of messages #define MONO_MAX_DEBUGGER_LOG_LEN 65 // Length of each message #define MONO_MAX_DEBUGGER_MSG_LEN 200 typedef struct { MonoDebugLogKind kind; intptr_t tid; char message [MONO_MAX_DEBUGGER_MSG_LEN]; } MonoDebugLogItem; static const char * mono_debug_log_kind_to_string (MonoDebugLogKind kind) { switch (kind) { case DEBUG_LOG_STATE_CHANGE: return "transition"; case DEBUG_LOG_BREAKPOINT: return "breakpoint"; case DEBUG_LOG_COMMAND: return "command"; case DEBUG_LOG_EVENT: return "event"; case DEBUG_LOG_EXIT: return "exit"; default: g_assert_not_reached (); } } #define MONO_DEBUGGER_LOG_FREED -1 static MonoFlightRecorder *debugger_log; static GPtrArray *breakpoint_copy; void mono_debugger_log_init (void) { if (debugger_log == GINT_TO_POINTER (MONO_DEBUGGER_LOG_FREED)) g_error ("Attempted to initialize debugger log after cleanup"); debugger_log = mono_flight_recorder_init (MONO_MAX_DEBUGGER_LOG_LEN, sizeof (MonoDebugLogItem)); breakpoint_copy = g_ptr_array_new (); } void mono_debugger_log_free (void) { MonoFlightRecorder *log = debugger_log; debugger_log = (MonoFlightRecorder*)GINT_TO_POINTER (MONO_DEBUGGER_LOG_FREED); mono_memory_barrier (); mono_flight_recorder_free (log); } void mono_debugger_log_command (const char *command_set, const char *command, guint8 *buf, int len) { if (debugger_log == GINT_TO_POINTER (MONO_DEBUGGER_LOG_FREED)) return; // FIXME: print the array in a format that can be decoded / printed? char *msg = g_strdup_printf ("Command Logged: %s %s Response: %d", command_set, command, len); MonoDebugLogItem payload; payload.kind = DEBUG_LOG_COMMAND; payload.tid = 0x0; g_snprintf ((gchar *) &payload.message, MONO_MAX_DEBUGGER_MSG_LEN, "%s", msg); mono_flight_recorder_append (debugger_log, &payload); } void mono_debugger_log_event (DebuggerTlsData *tls, const char *event, guint8 *buf, int len) { if (debugger_log == GINT_TO_POINTER (MONO_DEBUGGER_LOG_FREED)) return; // FIXME: print the array in a format that can be decoded / printed? intptr_t tid = mono_debugger_tls_thread_id (tls); char *msg = g_strdup_printf ("Event logged of type %s Response: %d", event, len); MonoDebugLogItem payload; payload.kind = DEBUG_LOG_EVENT; payload.tid = tid; g_snprintf ((gchar *) &payload.message, MONO_MAX_DEBUGGER_MSG_LEN, "%s", msg); mono_flight_recorder_append (debugger_log, &payload); } void mono_debugger_log_exit (int exit_code) { if (debugger_log == GINT_TO_POINTER (MONO_DEBUGGER_LOG_FREED)) return; char *msg = g_strdup_printf ("Exited with code %d", exit_code); MonoDebugLogItem payload; payload.kind = DEBUG_LOG_EXIT; payload.tid = 0x0; g_snprintf ((gchar *) &payload.message, MONO_MAX_DEBUGGER_MSG_LEN, "%s", msg); mono_flight_recorder_append (debugger_log, &payload); } void mono_debugger_log_add_bp (gpointer bp, MonoMethod *method, long il_offset) { if (debugger_log == GINT_TO_POINTER (MONO_DEBUGGER_LOG_FREED)) return; MonoCoopMutex *debugger_log_mutex = mono_flight_recorder_mutex (debugger_log); mono_coop_mutex_lock (debugger_log_mutex); g_ptr_array_add (breakpoint_copy, bp); mono_coop_mutex_unlock (debugger_log_mutex); char *msg = g_strdup_printf ("Add breakpoint %s %lu", method ? mono_method_full_name (method, TRUE) : "No method", il_offset); MonoDebugLogItem payload; payload.kind = DEBUG_LOG_BREAKPOINT; payload.tid = 0x0; g_snprintf ((gchar *) &payload.message, MONO_MAX_DEBUGGER_MSG_LEN, "%s", msg); mono_flight_recorder_append (debugger_log, &payload); } void mono_debugger_log_remove_bp (gpointer bp, MonoMethod *method, long il_offset) { if (debugger_log == GINT_TO_POINTER (MONO_DEBUGGER_LOG_FREED)) return; MonoCoopMutex *debugger_log_mutex = mono_flight_recorder_mutex (debugger_log); mono_coop_mutex_lock (debugger_log_mutex); g_ptr_array_remove (breakpoint_copy, bp); mono_coop_mutex_unlock (debugger_log_mutex); char *msg = g_strdup_printf ("Remove breakpoint %s %lu", method ? mono_method_full_name (method, TRUE) : "No method", il_offset); MonoDebugLogItem payload; payload.kind = DEBUG_LOG_BREAKPOINT; payload.tid = 0x0; g_snprintf ((gchar *) &payload.message, MONO_MAX_DEBUGGER_MSG_LEN, "%s", msg); mono_flight_recorder_append (debugger_log, &payload); } void mono_debugger_log_bp_hit (DebuggerTlsData *tls, MonoMethod *method, long il_offset) { if (debugger_log == GINT_TO_POINTER (MONO_DEBUGGER_LOG_FREED)) return; intptr_t tid = mono_debugger_tls_thread_id (tls); char *msg = g_strdup_printf ("Hit breakpoint %s %lu", method ? mono_method_full_name (method, TRUE) : "No method", il_offset); MonoDebugLogItem payload; payload.kind = DEBUG_LOG_BREAKPOINT; payload.tid = tid; g_snprintf ((gchar *) &payload.message, MONO_MAX_DEBUGGER_MSG_LEN, "%s", msg); mono_flight_recorder_append (debugger_log, &payload); } void mono_debugger_log_resume (DebuggerTlsData *tls) { if (debugger_log == GINT_TO_POINTER (MONO_DEBUGGER_LOG_FREED)) return; intptr_t tid = mono_debugger_tls_thread_id (tls); MonoDebuggerThreadState prev_state = mono_debugger_get_thread_state (tls); g_assert (prev_state == MONO_DEBUGGER_SUSPENDED || prev_state == MONO_DEBUGGER_STARTED); mono_debugger_set_thread_state (tls, prev_state, MONO_DEBUGGER_RESUMED); char *msg = g_strdup_printf ("Resuming 0x%p from state %s", (void*)tid, mono_debug_log_thread_state_to_string (prev_state)); MonoDebugLogItem payload; payload.kind = DEBUG_LOG_STATE_CHANGE; payload.tid = tid; g_snprintf ((gchar *) &payload.message, MONO_MAX_DEBUGGER_MSG_LEN, "%s", msg); mono_flight_recorder_append (debugger_log, &payload); } void mono_debugger_log_suspend (DebuggerTlsData *tls) { if (debugger_log == GINT_TO_POINTER (MONO_DEBUGGER_LOG_FREED)) return; intptr_t tid = mono_debugger_tls_thread_id (tls); MonoDebuggerThreadState prev_state = mono_debugger_get_thread_state (tls); g_assert (prev_state == MONO_DEBUGGER_RESUMED || prev_state == MONO_DEBUGGER_STARTED); mono_debugger_set_thread_state (tls, prev_state, MONO_DEBUGGER_SUSPENDED); char *msg = g_strdup_printf ("Suspending 0x%p from state %s", (void*)tid, mono_debug_log_thread_state_to_string (prev_state)); MonoDebugLogItem payload; payload.kind = DEBUG_LOG_STATE_CHANGE; payload.tid = tid; g_snprintf ((gchar *) &payload.message, MONO_MAX_DEBUGGER_MSG_LEN, "%s", msg); mono_flight_recorder_append (debugger_log, &payload); } typedef struct { JsonWriter *writer; gboolean not_first; } DebuggerThreadIterState; // FIXME: log TCP handshake / connection state static void dump_thread_state (gpointer key, gpointer value, gpointer user_data) { DebuggerTlsData *debugger_tls = (DebuggerTlsData *) value; DebuggerThreadIterState *data = (DebuggerThreadIterState *) user_data; if (data->not_first) mono_json_writer_printf (data->writer, ",\n"); else data->not_first = TRUE; mono_json_writer_indent (data->writer); mono_json_writer_object_begin (data->writer); mono_json_writer_indent (data->writer); mono_json_writer_object_key(data->writer, "thread_id"); mono_json_writer_printf (data->writer, "\"0x%x\",\n", (unsigned int) mono_debugger_tls_thread_id (debugger_tls)); mono_json_writer_indent (data->writer); mono_json_writer_object_key (data->writer, "thread_state"); const char *state = mono_debug_log_thread_state_to_string (mono_debugger_get_thread_state (debugger_tls)); mono_json_writer_printf (data->writer, "\"%s\"\n", state); mono_json_writer_indent_pop (data->writer); mono_json_writer_indent (data->writer); mono_json_writer_object_end (data->writer); } void mono_debugger_state (JsonWriter *writer) { if (debugger_log == GINT_TO_POINTER (MONO_DEBUGGER_LOG_FREED)) return; MonoCoopMutex *debugger_log_mutex = mono_flight_recorder_mutex (debugger_log); mono_coop_mutex_lock (debugger_log_mutex); mono_json_writer_object_begin(writer); mono_json_writer_indent (writer); mono_json_writer_object_key(writer, "debugger_state"); mono_json_writer_object_begin(writer); mono_json_writer_indent (writer); mono_json_writer_object_key(writer, "thread_states"); mono_json_writer_array_begin (writer); mono_json_writer_indent_push (writer); DebuggerThreadIterState iterState; iterState.writer = writer; iterState.not_first = FALSE; MonoGHashTable *thread_to_tls = mono_debugger_get_thread_states (); mono_g_hash_table_foreach (thread_to_tls, dump_thread_state, &iterState); mono_json_writer_printf (writer, "\n"); mono_json_writer_indent_pop (writer); mono_json_writer_indent (writer); mono_json_writer_array_end (writer); mono_json_writer_printf (writer, ",\n"); // FIXME: Log breakpoint state if (breakpoint_copy->len > 0) { mono_json_writer_indent (writer); mono_json_writer_object_key(writer, "breakpoints"); mono_json_writer_array_begin (writer); for (guint i=0; i < breakpoint_copy->len; i++) { MonoBreakpoint *bp = (MonoBreakpoint *) g_ptr_array_index (breakpoint_copy, i); mono_json_writer_indent (writer); mono_json_writer_object_begin(writer); mono_json_writer_indent (writer); mono_json_writer_object_key(writer, "method"); mono_json_writer_printf (writer, "\"%s\",\n", bp->method ? mono_method_full_name (bp->method, TRUE) : "No method"); mono_json_writer_indent (writer); mono_json_writer_object_key(writer, "il_offset"); mono_json_writer_printf (writer, "\"0x%x\",\n", (unsigned int) bp->il_offset); mono_json_writer_indent_pop (writer); mono_json_writer_indent (writer); mono_json_writer_object_end (writer); mono_json_writer_printf (writer, ",\n"); } mono_json_writer_indent_pop (writer); mono_json_writer_indent (writer); mono_json_writer_array_end (writer); mono_json_writer_printf (writer, ",\n"); } // Log history MonoFlightRecorderIter diter; mono_flight_recorder_iter_init (debugger_log, &diter); mono_json_writer_indent (writer); mono_json_writer_object_key(writer, "debugger_history"); mono_json_writer_array_begin (writer); gboolean first = TRUE; MonoDebugLogItem item; MonoFlightRecorderHeader header; while (mono_flight_recorder_iter_next (&diter, &header, (gpointer *) &item)) { if (!first) mono_json_writer_printf (writer, ",\n"); else first = FALSE; mono_json_writer_indent (writer); mono_json_writer_object_begin(writer); mono_json_writer_indent (writer); mono_json_writer_object_key(writer, "kind"); mono_json_writer_printf (writer, "\"%s\",\n", mono_debug_log_kind_to_string (item.kind)); mono_json_writer_indent (writer); mono_json_writer_object_key(writer, "tid"); mono_json_writer_printf (writer, "\"0x%x\",\n", (unsigned int) item.tid); mono_json_writer_indent (writer); mono_json_writer_object_key(writer, "message"); mono_json_writer_printf (writer, "\"%s\",\n", item.message); mono_json_writer_indent (writer); mono_json_writer_object_key(writer, "counter"); mono_json_writer_printf (writer, "\"%ld\"\n", header.counter); mono_json_writer_indent_pop (writer); mono_json_writer_indent (writer); mono_json_writer_object_end (writer); } mono_json_writer_printf (writer, "\n"); mono_json_writer_indent_pop (writer); mono_json_writer_indent (writer); mono_json_writer_array_end (writer); mono_json_writer_printf (writer, ",\n"); mono_flight_recorder_iter_destroy (&diter); // Log client/connection state gboolean disconnected = mono_debugger_is_disconnected (); mono_json_writer_indent (writer); mono_json_writer_object_key(writer, "client_state"); mono_json_writer_printf (writer, "\"%s\"\n", disconnected ? "disconnected" : "connected"); mono_json_writer_indent (writer); mono_json_writer_object_end (writer); mono_json_writer_printf (writer, "\n"); mono_json_writer_indent_pop (writer); mono_json_writer_indent (writer); mono_json_writer_object_end (writer); mono_coop_mutex_unlock (debugger_log_mutex); } char * mono_debugger_state_str (void) { if (debugger_log == GINT_TO_POINTER (MONO_DEBUGGER_LOG_FREED)) return NULL; JsonWriter writer; mono_json_writer_init (&writer); mono_debugger_state (&writer); char *result = g_strdup(writer.text->str); mono_json_writer_destroy (&writer); return result; }
93ab8c3d6d1880686b7758a6b115e16814d818a1
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/char/agp/amd-k7-agp.c
779f0ab845a949063ffc578dd31d7a758b7c0482
[ "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
15,610
c
amd-k7-agp.c
/* * AMD K7 AGPGART routines. */ #include <linux/module.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/agp_backend.h> #include <linux/page-flags.h> #include <linux/mm.h> #include <linux/slab.h> #include "agp.h" #define AMD_MMBASE 0x14 #define AMD_APSIZE 0xac #define AMD_MODECNTL 0xb0 #define AMD_MODECNTL2 0xb2 #define AMD_GARTENABLE 0x02 /* In mmio region (16-bit register) */ #define AMD_ATTBASE 0x04 /* In mmio region (32-bit register) */ #define AMD_TLBFLUSH 0x0c /* In mmio region (32-bit register) */ #define AMD_CACHEENTRY 0x10 /* In mmio region (32-bit register) */ static struct pci_device_id agp_amdk7_pci_table[]; struct amd_page_map { unsigned long *real; unsigned long __iomem *remapped; }; static struct _amd_irongate_private { volatile u8 __iomem *registers; struct amd_page_map **gatt_pages; int num_tables; } amd_irongate_private; static int amd_create_page_map(struct amd_page_map *page_map) { int i; page_map->real = (unsigned long *) __get_free_page(GFP_KERNEL); if (page_map->real == NULL) return -ENOMEM; set_memory_uc((unsigned long)page_map->real, 1); page_map->remapped = page_map->real; for (i = 0; i < PAGE_SIZE / sizeof(unsigned long); i++) { writel(agp_bridge->scratch_page, page_map->remapped+i); readl(page_map->remapped+i); /* PCI Posting. */ } return 0; } static void amd_free_page_map(struct amd_page_map *page_map) { set_memory_wb((unsigned long)page_map->real, 1); free_page((unsigned long) page_map->real); } static void amd_free_gatt_pages(void) { int i; struct amd_page_map **tables; struct amd_page_map *entry; tables = amd_irongate_private.gatt_pages; for (i = 0; i < amd_irongate_private.num_tables; i++) { entry = tables[i]; if (entry != NULL) { if (entry->real != NULL) amd_free_page_map(entry); kfree(entry); } } kfree(tables); amd_irongate_private.gatt_pages = NULL; } static int amd_create_gatt_pages(int nr_tables) { struct amd_page_map **tables; struct amd_page_map *entry; int retval = 0; int i; tables = kzalloc((nr_tables + 1) * sizeof(struct amd_page_map *),GFP_KERNEL); if (tables == NULL) return -ENOMEM; for (i = 0; i < nr_tables; i++) { entry = kzalloc(sizeof(struct amd_page_map), GFP_KERNEL); tables[i] = entry; if (entry == NULL) { retval = -ENOMEM; break; } retval = amd_create_page_map(entry); if (retval != 0) break; } amd_irongate_private.num_tables = i; amd_irongate_private.gatt_pages = tables; if (retval != 0) amd_free_gatt_pages(); return retval; } /* Since we don't need contiguous memory we just try * to get the gatt table once */ #define GET_PAGE_DIR_OFF(addr) (addr >> 22) #define GET_PAGE_DIR_IDX(addr) (GET_PAGE_DIR_OFF(addr) - \ GET_PAGE_DIR_OFF(agp_bridge->gart_bus_addr)) #define GET_GATT_OFF(addr) ((addr & 0x003ff000) >> 12) #define GET_GATT(addr) (amd_irongate_private.gatt_pages[\ GET_PAGE_DIR_IDX(addr)]->remapped) static int amd_create_gatt_table(struct agp_bridge_data *bridge) { struct aper_size_info_lvl2 *value; struct amd_page_map page_dir; unsigned long __iomem *cur_gatt; unsigned long addr; int retval; u32 temp; int i; value = A_SIZE_LVL2(agp_bridge->current_size); retval = amd_create_page_map(&page_dir); if (retval != 0) return retval; retval = amd_create_gatt_pages(value->num_entries / 1024); if (retval != 0) { amd_free_page_map(&page_dir); return retval; } agp_bridge->gatt_table_real = (u32 *)page_dir.real; agp_bridge->gatt_table = (u32 __iomem *)page_dir.remapped; agp_bridge->gatt_bus_addr = virt_to_phys(page_dir.real); /* Get the address for the gart region. * This is a bus address even on the alpha, b/c its * used to program the agp master not the cpu */ pci_read_config_dword(agp_bridge->dev, AGP_APBASE, &temp); addr = (temp & PCI_BASE_ADDRESS_MEM_MASK); agp_bridge->gart_bus_addr = addr; /* Calculate the agp offset */ for (i = 0; i < value->num_entries / 1024; i++, addr += 0x00400000) { writel(virt_to_phys(amd_irongate_private.gatt_pages[i]->real) | 1, page_dir.remapped+GET_PAGE_DIR_OFF(addr)); readl(page_dir.remapped+GET_PAGE_DIR_OFF(addr)); /* PCI Posting. */ } for (i = 0; i < value->num_entries; i++) { addr = (i * PAGE_SIZE) + agp_bridge->gart_bus_addr; cur_gatt = GET_GATT(addr); writel(agp_bridge->scratch_page, cur_gatt+GET_GATT_OFF(addr)); readl(cur_gatt+GET_GATT_OFF(addr)); /* PCI Posting. */ } return 0; } static int amd_free_gatt_table(struct agp_bridge_data *bridge) { struct amd_page_map page_dir; page_dir.real = (unsigned long *)agp_bridge->gatt_table_real; page_dir.remapped = (unsigned long __iomem *)agp_bridge->gatt_table; amd_free_gatt_pages(); amd_free_page_map(&page_dir); return 0; } static int amd_irongate_fetch_size(void) { int i; u32 temp; struct aper_size_info_lvl2 *values; pci_read_config_dword(agp_bridge->dev, AMD_APSIZE, &temp); temp = (temp & 0x0000000e); values = A_SIZE_LVL2(agp_bridge->driver->aperture_sizes); for (i = 0; i < agp_bridge->driver->num_aperture_sizes; i++) { if (temp == values[i].size_value) { agp_bridge->previous_size = agp_bridge->current_size = (void *) (values + i); agp_bridge->aperture_size_idx = i; return values[i].size; } } return 0; } static int amd_irongate_configure(void) { struct aper_size_info_lvl2 *current_size; u32 temp; u16 enable_reg; current_size = A_SIZE_LVL2(agp_bridge->current_size); if (!amd_irongate_private.registers) { /* Get the memory mapped registers */ pci_read_config_dword(agp_bridge->dev, AMD_MMBASE, &temp); temp = (temp & PCI_BASE_ADDRESS_MEM_MASK); amd_irongate_private.registers = (volatile u8 __iomem *) ioremap(temp, 4096); if (!amd_irongate_private.registers) return -ENOMEM; } /* Write out the address of the gatt table */ writel(agp_bridge->gatt_bus_addr, amd_irongate_private.registers+AMD_ATTBASE); readl(amd_irongate_private.registers+AMD_ATTBASE); /* PCI Posting. */ /* Write the Sync register */ pci_write_config_byte(agp_bridge->dev, AMD_MODECNTL, 0x80); /* Set indexing mode */ pci_write_config_byte(agp_bridge->dev, AMD_MODECNTL2, 0x00); /* Write the enable register */ enable_reg = readw(amd_irongate_private.registers+AMD_GARTENABLE); enable_reg = (enable_reg | 0x0004); writew(enable_reg, amd_irongate_private.registers+AMD_GARTENABLE); readw(amd_irongate_private.registers+AMD_GARTENABLE); /* PCI Posting. */ /* Write out the size register */ pci_read_config_dword(agp_bridge->dev, AMD_APSIZE, &temp); temp = (((temp & ~(0x0000000e)) | current_size->size_value) | 1); pci_write_config_dword(agp_bridge->dev, AMD_APSIZE, temp); /* Flush the tlb */ writel(1, amd_irongate_private.registers+AMD_TLBFLUSH); readl(amd_irongate_private.registers+AMD_TLBFLUSH); /* PCI Posting.*/ return 0; } static void amd_irongate_cleanup(void) { struct aper_size_info_lvl2 *previous_size; u32 temp; u16 enable_reg; previous_size = A_SIZE_LVL2(agp_bridge->previous_size); enable_reg = readw(amd_irongate_private.registers+AMD_GARTENABLE); enable_reg = (enable_reg & ~(0x0004)); writew(enable_reg, amd_irongate_private.registers+AMD_GARTENABLE); readw(amd_irongate_private.registers+AMD_GARTENABLE); /* PCI Posting. */ /* Write back the previous size and disable gart translation */ pci_read_config_dword(agp_bridge->dev, AMD_APSIZE, &temp); temp = ((temp & ~(0x0000000f)) | previous_size->size_value); pci_write_config_dword(agp_bridge->dev, AMD_APSIZE, temp); iounmap((void __iomem *) amd_irongate_private.registers); } /* * This routine could be implemented by taking the addresses * written to the GATT, and flushing them individually. However * currently it just flushes the whole table. Which is probably * more efficient, since agp_memory blocks can be a large number of * entries. */ static void amd_irongate_tlbflush(struct agp_memory *temp) { writel(1, amd_irongate_private.registers+AMD_TLBFLUSH); readl(amd_irongate_private.registers+AMD_TLBFLUSH); /* PCI Posting. */ } static int amd_insert_memory(struct agp_memory *mem, off_t pg_start, int type) { int i, j, num_entries; unsigned long __iomem *cur_gatt; unsigned long addr; num_entries = A_SIZE_LVL2(agp_bridge->current_size)->num_entries; if (type != mem->type || agp_bridge->driver->agp_type_to_mask_type(agp_bridge, type)) return -EINVAL; if ((pg_start + mem->page_count) > num_entries) return -EINVAL; j = pg_start; while (j < (pg_start + mem->page_count)) { addr = (j * PAGE_SIZE) + agp_bridge->gart_bus_addr; cur_gatt = GET_GATT(addr); if (!PGE_EMPTY(agp_bridge, readl(cur_gatt+GET_GATT_OFF(addr)))) return -EBUSY; j++; } if (!mem->is_flushed) { global_cache_flush(); mem->is_flushed = true; } for (i = 0, j = pg_start; i < mem->page_count; i++, j++) { addr = (j * PAGE_SIZE) + agp_bridge->gart_bus_addr; cur_gatt = GET_GATT(addr); writel(agp_generic_mask_memory(agp_bridge, page_to_phys(mem->pages[i]), mem->type), cur_gatt+GET_GATT_OFF(addr)); readl(cur_gatt+GET_GATT_OFF(addr)); /* PCI Posting. */ } amd_irongate_tlbflush(mem); return 0; } static int amd_remove_memory(struct agp_memory *mem, off_t pg_start, int type) { int i; unsigned long __iomem *cur_gatt; unsigned long addr; if (type != mem->type || agp_bridge->driver->agp_type_to_mask_type(agp_bridge, type)) return -EINVAL; for (i = pg_start; i < (mem->page_count + pg_start); i++) { addr = (i * PAGE_SIZE) + agp_bridge->gart_bus_addr; cur_gatt = GET_GATT(addr); writel(agp_bridge->scratch_page, cur_gatt+GET_GATT_OFF(addr)); readl(cur_gatt+GET_GATT_OFF(addr)); /* PCI Posting. */ } amd_irongate_tlbflush(mem); return 0; } static const struct aper_size_info_lvl2 amd_irongate_sizes[7] = { {2048, 524288, 0x0000000c}, {1024, 262144, 0x0000000a}, {512, 131072, 0x00000008}, {256, 65536, 0x00000006}, {128, 32768, 0x00000004}, {64, 16384, 0x00000002}, {32, 8192, 0x00000000} }; static const struct gatt_mask amd_irongate_masks[] = { {.mask = 1, .type = 0} }; static const struct agp_bridge_driver amd_irongate_driver = { .owner = THIS_MODULE, .aperture_sizes = amd_irongate_sizes, .size_type = LVL2_APER_SIZE, .num_aperture_sizes = 7, .needs_scratch_page = true, .configure = amd_irongate_configure, .fetch_size = amd_irongate_fetch_size, .cleanup = amd_irongate_cleanup, .tlb_flush = amd_irongate_tlbflush, .mask_memory = agp_generic_mask_memory, .masks = amd_irongate_masks, .agp_enable = agp_generic_enable, .cache_flush = global_cache_flush, .create_gatt_table = amd_create_gatt_table, .free_gatt_table = amd_free_gatt_table, .insert_memory = amd_insert_memory, .remove_memory = amd_remove_memory, .alloc_by_type = agp_generic_alloc_by_type, .free_by_type = agp_generic_free_by_type, .agp_alloc_page = agp_generic_alloc_page, .agp_alloc_pages = agp_generic_alloc_pages, .agp_destroy_page = agp_generic_destroy_page, .agp_destroy_pages = agp_generic_destroy_pages, .agp_type_to_mask_type = agp_generic_type_to_mask_type, }; static struct agp_device_ids amd_agp_device_ids[] = { { .device_id = PCI_DEVICE_ID_AMD_FE_GATE_7006, .chipset_name = "Irongate", }, { .device_id = PCI_DEVICE_ID_AMD_FE_GATE_700E, .chipset_name = "761", }, { .device_id = PCI_DEVICE_ID_AMD_FE_GATE_700C, .chipset_name = "760MP", }, { }, /* dummy final entry, always present */ }; static int agp_amdk7_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct agp_bridge_data *bridge; u8 cap_ptr; int j; cap_ptr = pci_find_capability(pdev, PCI_CAP_ID_AGP); if (!cap_ptr) return -ENODEV; j = ent - agp_amdk7_pci_table; dev_info(&pdev->dev, "AMD %s chipset\n", amd_agp_device_ids[j].chipset_name); bridge = agp_alloc_bridge(); if (!bridge) return -ENOMEM; bridge->driver = &amd_irongate_driver; bridge->dev_private_data = &amd_irongate_private, bridge->dev = pdev; bridge->capndx = cap_ptr; /* 751 Errata (22564_B-1.PDF) erratum 20: strobe glitch with Nvidia NV10 GeForce cards. system controller may experience noise due to strong drive strengths */ if (agp_bridge->dev->device == PCI_DEVICE_ID_AMD_FE_GATE_7006) { struct pci_dev *gfxcard=NULL; cap_ptr = 0; while (!cap_ptr) { gfxcard = pci_get_class(PCI_CLASS_DISPLAY_VGA<<8, gfxcard); if (!gfxcard) { dev_info(&pdev->dev, "no AGP VGA controller\n"); return -ENODEV; } cap_ptr = pci_find_capability(gfxcard, PCI_CAP_ID_AGP); } /* With so many variants of NVidia cards, it's simpler just to blacklist them all, and then whitelist them as needed (if necessary at all). */ if (gfxcard->vendor == PCI_VENDOR_ID_NVIDIA) { agp_bridge->flags |= AGP_ERRATA_1X; dev_info(&pdev->dev, "AMD 751 chipset with NVidia GeForce; forcing 1X due to errata\n"); } pci_dev_put(gfxcard); } /* 761 Errata (23613_F.pdf) * Revisions B0/B1 were a disaster. * erratum 44: SYSCLK/AGPCLK skew causes 2X failures -- Force mode to 1X * erratum 45: Timing problem prevents fast writes -- Disable fast write. * erratum 46: Setup violation on AGP SBA pins - Disable side band addressing. * With this lot disabled, we should prevent lockups. */ if (agp_bridge->dev->device == PCI_DEVICE_ID_AMD_FE_GATE_700E) { if (pdev->revision == 0x10 || pdev->revision == 0x11) { agp_bridge->flags = AGP_ERRATA_FASTWRITES; agp_bridge->flags |= AGP_ERRATA_SBA; agp_bridge->flags |= AGP_ERRATA_1X; dev_info(&pdev->dev, "AMD 761 chipset with errata; disabling AGP fast writes & SBA and forcing to 1X\n"); } } /* Fill in the mode register */ pci_read_config_dword(pdev, bridge->capndx+PCI_AGP_STATUS, &bridge->mode); pci_set_drvdata(pdev, bridge); return agp_add_bridge(bridge); } static void agp_amdk7_remove(struct pci_dev *pdev) { struct agp_bridge_data *bridge = pci_get_drvdata(pdev); agp_remove_bridge(bridge); agp_put_bridge(bridge); } #ifdef CONFIG_PM static int agp_amdk7_suspend(struct pci_dev *pdev, pm_message_t state) { pci_save_state(pdev); pci_set_power_state(pdev, pci_choose_state(pdev, state)); return 0; } static int agp_amdk7_resume(struct pci_dev *pdev) { pci_set_power_state(pdev, PCI_D0); pci_restore_state(pdev); return amd_irongate_driver.configure(); } #endif /* CONFIG_PM */ /* must be the same order as name table above */ static struct pci_device_id agp_amdk7_pci_table[] = { { .class = (PCI_CLASS_BRIDGE_HOST << 8), .class_mask = ~0, .vendor = PCI_VENDOR_ID_AMD, .device = PCI_DEVICE_ID_AMD_FE_GATE_7006, .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID, }, { .class = (PCI_CLASS_BRIDGE_HOST << 8), .class_mask = ~0, .vendor = PCI_VENDOR_ID_AMD, .device = PCI_DEVICE_ID_AMD_FE_GATE_700E, .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID, }, { .class = (PCI_CLASS_BRIDGE_HOST << 8), .class_mask = ~0, .vendor = PCI_VENDOR_ID_AMD, .device = PCI_DEVICE_ID_AMD_FE_GATE_700C, .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID, }, { } }; MODULE_DEVICE_TABLE(pci, agp_amdk7_pci_table); static struct pci_driver agp_amdk7_pci_driver = { .name = "agpgart-amdk7", .id_table = agp_amdk7_pci_table, .probe = agp_amdk7_probe, .remove = agp_amdk7_remove, #ifdef CONFIG_PM .suspend = agp_amdk7_suspend, .resume = agp_amdk7_resume, #endif }; static int __init agp_amdk7_init(void) { if (agp_off) return -EINVAL; return pci_register_driver(&agp_amdk7_pci_driver); } static void __exit agp_amdk7_cleanup(void) { pci_unregister_driver(&agp_amdk7_pci_driver); } module_init(agp_amdk7_init); module_exit(agp_amdk7_cleanup); MODULE_LICENSE("GPL and additional rights");
80e28e4608f3bf63ac0f8b0723b7c646c881ef1c
03666e5f961946fc1a0ac67781ac1425562ef0d7
/src/engine/main/CumulativeQueryNamedSelectionExtension.C
dc8939a59dc3b86ccc9d4853c24294f37f2ab034
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
visit-dav/visit
e9f81b4d4b9b9930a0db9d5282cd1bcabf465e2e
601ae46e0bef2e18425b482a755d03490ade0493
refs/heads/develop
2023-09-06T08:19:38.397058
2023-09-05T21:29:32
2023-09-05T21:29:32
165,565,988
335
120
BSD-3-Clause
2023-09-14T00:53:37
2019-01-13T23:27:26
C
UTF-8
C
false
false
106,573
c
CumulativeQueryNamedSelectionExtension.C
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt // Project developers. See the top-level LICENSE file for dates and other // details. No copyright assignment is required to contribute to VisIt. #include <CumulativeQueryNamedSelectionExtension.h> #include <avtThresholdFilter.h> #include <Expression.h> #include <ExpressionList.h> #include <ParsingExprList.h> #include <SelectionVariableSummary.h> #include <DebugStream.h> #include <StackTimer.h> #include <algorithm> #include <map> #include <avtDataTreeIterator.h> #include <avtExtents.h> #include <avtDatasetExaminer.h> #include <avtHistogramSpecification.h> #include <avtMetaData.h> #include <avtNamedSelectionManager.h> #include <avtParallel.h> #include <avtTimeLoopCollectorFilter.h> #include <vtkCellData.h> #include <vtkDataSet.h> #include <vtkDoubleArray.h> #include <vtkFloatArray.h> #include <vtkPointData.h> #include <vtkPointDataToCellData.h> #include <vtkRectilinearGrid.h> #include <vtkUnsignedIntArray.h> #include <float.h> // // Brad Whitlock, Fri May 20 14:48:44 PDT 2011 // // Implementation notes: // In this form, cumulative queries are implemented as 3 extra // filters: // // CQHistogramCalculationFilter // A filter that calculates histograms for the CQ's input // variables. // // avtThresholdFilter // Threshold away all of the cells that do not match the limits // for the variables set in the CQ properties. Using this // filter may allow the database to use selections to fulfill // the threshold operation. That would be good. // // CQFilter // This is a time loop filter that gets the thresholded output // for all time steps. The data that we get for each time step // is fed into a CumulativeQuery object that does the real work // of creating the selection. // // ---------------------------------------------------------------------------- // // CumulativeQuery // This class examines datasets and counts the number of cells // in each time step using the count to then figure out the // list of cells that exist in any or all time steps, depending // on the summation rule. We then take that set of cells and // sort it based on the desired histogramming method and then // we select a range of bins from the histogram to contribute // cells to our final selection. The final dataset produced by // the filter is a dummy dataset that contains the original // cell numbers that describe the cells in the selection. That // array is used later in named selection to create the // selection. // // This filter also computes an average frequency value for the // cells in each histogram bin. This is saved and returned to // the gui. // // CumulativeQueryNamedSelectionExtension // This class implements the GetSelection method to return a // vector of ints containing the doms/zones that identify the // cells that match the cumulative query selection // criteria. The class is smart enough to build a pipeline that // executes our 3 filters when it needs to. Alternatively, the // class can use intermediate cached data to prevent the time // iteration portion of CQ from being done again. // // Auxilary function for getting the cell from an id (CQDomainZoneId // and CQVariableId). These must be specialized. template< class T> double CellIdentifierFromID( T id ) { return 0; } // **************************************************************************** // Class: CQHistogramCalculationFilter // // Purpose: // This class is a specialized filter that computes histograms on specific // variables. We cache the histograms and make them available to the named // selection extension object that creates this filter. // // Notes: // // Programmer: Brad Whitlock // Creation: Fri Dec 17 14:50:16 PST 2010 // // Modifications: // Eric Brugger, Wed Aug 20 16:13:09 PDT 2014 // Modified the class to work with avtDataRepresentation. // // Kathleen Biagas, Wed Nov 18 2020 // Replace VISIT_LONG_LONG with long long. // // **************************************************************************** #define NBINS 256 // number of bins for the histogram. class CQHistogramCalculationFilter : public avtDataTreeIterator { public: struct Histogram { double minimum; double maximum; double frequency[NBINS]; }; CQHistogramCalculationFilter() : avtDataTreeIterator(), histograms() { cellCount = 0; totalCellCount = 0; totalNotSet = true; } virtual const char *GetType() { return "CQHistogramCalculationFilter"; } virtual const char *GetDescription() { return "Calculating histograms"; } virtual ~CQHistogramCalculationFilter() { for(std::map<std::string,Histogram*>::iterator it = histograms.begin(); it != histograms.end(); ++it) { if(it->second != 0) delete it->second; } } void AddVariable(const std::string &var) { histograms[var] = 0; } stringVector GetVariables() const { stringVector names; std::map<std::string,Histogram*>::const_iterator it; for(it = histograms.begin(); it != histograms.end(); ++it) { names.push_back(it->first); } return names; } const Histogram *GetHistogram(const std::string &var) const { const Histogram *retval = 0; std::map<std::string,Histogram*>::const_iterator it = histograms.find(var); if(it != histograms.end()) retval = it->second; return retval; } long GetTotalCellCount() const { return totalCellCount; } protected: virtual void PreExecute(void) { cellCount = 0; } virtual avtDataRepresentation *ExecuteData(avtDataRepresentation *dr) { // // Get the VTK data set. // vtkDataSet *ds = dr->GetDataVTK(); cellCount += ds->GetNumberOfCells(); return dr; } virtual void PostExecute(void) { const char *mName = "CQHistogramCalculationFilter::PostExecute: "; StackTimer t0(mName); avtDataObject_p dob = GetInput(); avtDataset_p ds; CopyTo(ds, dob); std::map<std::string,Histogram*>::iterator it; for(it = histograms.begin(); it != histograms.end(); ++it) { // If we have not created a histogram yet for this // variable then do it now. if(it->second == 0) { it->second = new Histogram; double minmax[2] = { +DBL_MAX, -DBL_MAX }; // Get the local extents fr this rank. avtDatasetExaminer::GetDataExtents(ds, minmax, it->first.c_str()); // Get the global extents across all ranks. minmax[0] = UnifyMinimumValue(minmax[0]); minmax[1] = UnifyMaximumValue(minmax[1]); debug5 << mName << "Calculated data extents for " << it->first << " [" << minmax[0] << ", " << minmax[1] << "]" << std::endl; // Get the local histogram for this rank. std::vector<long long> hist_in(NBINS, 0); if(!avtDatasetExaminer::CalculateHistogram(ds, it->first, minmax[0], minmax[1], hist_in)) { debug1 << "CalculateHistogram failed" << std::endl; } // Get the global histograms acrosss all ranks. std::vector<long long> hist_out(NBINS, 0); SumLongLongArrayAcrossAllProcessors( &(hist_in[0]), &(hist_out[0]), NBINS); for(int i = 0; i < NBINS; ++i) it->second->frequency[i] = (double) hist_out[i]; // Print the histogram. debug5 << mName << "Calculated histogram for " << it->first << std::endl; for(int i = 0; i < NBINS; ++i) debug5 << "\thist[" << i << "] = " << hist_out[i] << std::endl; it->second->minimum = minmax[0]; it->second->maximum = minmax[1]; } } // Sum the cells and send to all procs. SumLongAcrossAllProcessors(cellCount); if(totalNotSet) { totalCellCount += cellCount; totalNotSet = false; } } virtual avtContract_p ModifyContract(avtContract_p contract) { const char *mName = "CQHistogramCalculationFilter::ModifyContract: "; StackTimer t0(mName); avtContract_p newContract = new avtContract(contract); std::string origvar(newContract->GetDataRequest()->GetOriginalVariable()); std::map<std::string,Histogram*>::iterator it; for(it = histograms.begin(); it != histograms.end(); ++it) { // Request extents // newContract->SetCalculateVariableExtents(it->first, true); // Try and get a histogram. If we can't then request the // data as a secondary variable. avtHistogramSpecification hist; hist.SpecifyHistogram(contract->GetDataRequest()->GetTimestep(), it->first, NBINS); if(GetMetaData()->GetHistogram(&hist)) { it->second = new Histogram; it->second->minimum = hist.GetBounds()[0][0]; it->second->maximum = hist.GetBounds()[0][NBINS]; for(int i = 0; i < NBINS; ++i) it->second->frequency[i] = double(hist.GetCounts()[i]); // Print the histogram. debug5 << mName << "Obtained existing histogram spec. for " << it->first << std::endl; for(int i = 0; i < NBINS; ++i) debug5 << " bin " << i << " bounds = [" << hist.GetBounds()[0][i] << ", " << hist.GetBounds()[0][i+1] << ") " << " count = " << hist.GetCounts()[i] << " " << std::endl; } else if(origvar != it->first && !newContract->GetDataRequest()->HasSecondaryVariable(it->first.c_str())) { newContract->GetDataRequest()->AddSecondaryVariable(it->first.c_str()); } } return newContract; } std::map<std::string, Histogram *> histograms; long cellCount; long totalCellCount; bool totalNotSet; }; // ***************************************************************************** // ***************************************************************************** // *** // *** CumulativeQuery // *** // ***************************************************************************** // ***************************************************************************** // **************************************************************************** // Class: CumulativeQuery // // Purpose: // This class creates a cumulative query selection based on time step data. // // Notes: The class is templated on CQCellIdentifier and CQSelection so // we can use this class' logic to implement CQ that relates cells // using different strategies. The cellId-specific coding is moved // into the CQSelection implementation. // // Programmer: Brad Whitlock // Creation: Wed Sep 7 11:30:52 PDT 2011 // // Modifications: // Brad Whitlock, Fri Oct 28 14:46:00 PDT 2011 // Combine some doms/zones arguments into CQCellIdentifier. // // Brad Whitlock, Sat Nov 5 01:32:16 PDT 2011 // I templated the class so it can support different selection types that // use different cell id types. // // **************************************************************************** struct CQCellData { int frequency; double variable; }; template <class CQCellIdentifier, class CQSelection> class CumulativeQuery { public: CumulativeQuery() : idVariable(), cellFrequency(), cellsPerTimeStep() { } virtual ~CumulativeQuery() { } void SetIdVariable(const std::string &id) { idVariable = id; } const std::string &GetIdVariable() const { return idVariable; } // The CQFilter class uses this method to supply data objects from // which we calculate the selection. We calculate the // cellFrequency and then the selection. void CreateSelection(const SelectionProperties &props, std::vector<avtDataTree_p> &, CQSelection &outSel, doubleVector &hist, double &min, double &max); // Calculate the selection but use cellFrequency data we already // calculated. void CreateSelection(const SelectionProperties &props, const CQSelection &cellFrequency, const std::vector<CQSelection> &cellsPerTimeStep, CQSelection &narrowedSelection, doubleVector &hist, double &min, double &max); const CQSelection &GetCellFrequency() const { return cellFrequency; } const std::vector<CQSelection> &GetCellsPerTimeStep() const { return cellsPerTimeStep; } private: void CalculateFrequency(const SelectionProperties &props, std::vector<avtDataTree_p> &timesteps, CQSelection &cellFrequency, std::vector<CQSelection> &cellsPerTimeStep) const; void Summation(const SelectionProperties &props, const CQSelection &cellFrequency, const std::vector<CQSelection> &cellsPerTimeStep, CQSelection &selection, std::vector<CQSelection> &selectionPerTimeStep) const; bool GlobalizeSelection(const CQSelection &selection, CQCellIdentifier *&allIds, int *&allFrequencies, int &totalCells, const std::vector< CQSelection > &selectionPerTimeSteps, CQCellIdentifier **&allIdsPerTimeStep, double **&allVariablesPerTimeStep, std::vector< int >& totalCellsPerTimeStep) const; // void SelectAndHistogram(const SelectionProperties &props, // const std::vector< CQSelection > &selectionPerTimeStep, // CQSelection &narrowedSelection, // doubleVector &histogram) const; void SelectAndHistogram(const SelectionProperties &props, CQCellIdentifier **allIdsPerTimeStep, std::vector <int> totalCellsPerTimeStep, CQSelection &narrowedSelection, doubleVector &histogram) const; void SelectAndHistogram(const SelectionProperties &props, const CQCellIdentifier *allIds, const int *allFrequencies, int totalCells, CQSelection &narrowedSelection, doubleVector &histogram, double &min, double &max) const; void SelectAndHistogram(const SelectionProperties &props, CQCellIdentifier **allIdsPerTimeStep, double **allVariablesPerTimeStep, std::vector< int > totalCellsPerTimeStep, CQSelection &narrowedSelection, doubleVector &histogram, double &min, double &max) const; void ComputeGlobalSizeAndOffset(const CQSelection &selection, int &globalSize, int &myOffset) const; void GlobalizeData(const CQSelection &selection, int globalSize, int myOffset, int *&allFrequencies) const; void GlobalizeData(const CQSelection &selection, int globalSize, int myOffset, double *&allVariables) const; void MakeDataUnique(int &globalSize, CQCellIdentifier *&allIds, int *&allFrequencies) const; // Members that we calculate as stage 1 of the selection calculation during // frequency calculation. std::string idVariable; CQSelection cellFrequency; std::vector< CQSelection > cellsPerTimeStep; }; // **************************************************************************** // Method: CumulativeQuery::CreateSelection // // Purpose: // This method creates a selection based on datasets over time. // // Arguments: // props : The selection properties. // timesteps : The data trees for each timestep. // narrowedSelection : The returned selection that we created from CQ. // hist : The returned histogram for the selection. // // Returns: We return a data tree with a dummy dataset that has the number // of cells in our final selection and we place the original zones // array on it since that is what is used later to define the // named selection. // // Note: As a side-effect, we store the cell freqencies and cells per // timestep so we can get that information later for caching // purposes. // // Programmer: Brad Whitlock // Creation: Fri May 20 14:28:53 PDT 2011 // // Modifications: // Brad Whitlock, Sat Nov 5 01:32:16 PDT 2011 // I templated the class so it can support different cell identifier types. // // **************************************************************************** template <class CQCellIdentifier, class CQSelection> void CumulativeQuery<CQCellIdentifier, CQSelection>::CreateSelection( const SelectionProperties &props, std::vector<avtDataTree_p> &timesteps, CQSelection &narrowedSelection, doubleVector &hist, double &min, double &max) { const char *mName = "CumulativeQuery<>::CreateSelection Phase 1: "; StackTimer t0(mName); cellFrequency.clear(); cellsPerTimeStep.clear(); // // Iterate through the data for all time steps and come up with a // "cell frequency". We may find different cell ids over time so we // create a set that includes any cell that was present in any dataset // over time. Each time we find that cell in a different time step, // we increment its "cell frequency". The cell frequency thus becomes // a count of how many time steps contained the cell. // CalculateFrequency(props, timesteps, cellFrequency, cellsPerTimeStep); // Now that we know the cell frequency and the cells per time step, we // can pass them into the next phase of the selection creation. CreateSelection(props, cellFrequency, cellsPerTimeStep, narrowedSelection, hist, min, max); } // **************************************************************************** // Method: CumulativeQuery::CreateSelection // // Purpose: // This method creates a selection based on previously gathered cell // frequencies. // // Arguments: // props : The selection properties. // cellFrequency : The number of times each cell appears over time. // cellsPerTimeStep : Cells in each timestep. // narrowedSelection : The returned selection that we created from CQ. // hist : The returned histogram for the selection. // // Returns: We return a data tree with a dummy dataset that has the number // of cells in our final selection and we place the original zones // array on it since that is what is used later to define the // named selection. // // Note: // // Programmer: Brad Whitlock // Creation: Fri May 20 14:28:53 PDT 2011 // // Modifications: // Brad Whitlock, Fri Oct 28 14:32:35 PDT 2011 // Combine the doms/zones ids to be more general. // // **************************************************************************** template <class CQCellIdentifier, class CQSelection> void CumulativeQuery<CQCellIdentifier, CQSelection>::CreateSelection( const SelectionProperties &props, const CQSelection &cellFrequency, const std::vector<CQSelection> &cellsPerTimeStep, CQSelection &narrowedSelection, doubleVector &hist, double &min, double &max) { const char *mName = "CumulativeQuery<>::CreateSelection Phase 2: "; StackTimer t0(mName); // // Apply the summation rule so we get a subset of the // cellFrequency map that will contribute to our selection. // CQSelection selection; std::vector<CQSelection> selectionPerTimeStep; Summation(props, cellFrequency, cellsPerTimeStep, selection, selectionPerTimeStep); // SaveSelection("selection1.txt", selection); // // Let's combine the selections from all processors and then send // that global selection to all processors, in the process // transforming it into a set of arrays. // CQCellIdentifier *allIds = NULL; int *allFrequencies = NULL; CQCellIdentifier **allIdsPerTimeStep = NULL; double **allVariablesPerTimeStep = NULL; int totalCells = 0; std::vector< int > totalCellsPerTimeStep; if( !GlobalizeSelection(selection, allIds, allFrequencies, totalCells, selectionPerTimeStep, allIdsPerTimeStep, allVariablesPerTimeStep, totalCellsPerTimeStep) ) { EXCEPTION1(VisItException, "You have selected too many zones in your " "named selection. Disallowing ... no selection created"); } // // Sort the entire selection according to the selected sorting // mode and further narrow the selection. This is the // "histogramming" part. // hist.clear(); if(props.GetHistogramType() == SelectionProperties::HistogramTime) { SelectAndHistogram(props, allIdsPerTimeStep, totalCellsPerTimeStep, narrowedSelection, hist); } else if(props.GetHistogramType() == SelectionProperties::HistogramID || props.GetHistogramType() == SelectionProperties::HistogramMatches) { SelectAndHistogram(props, allIds, allFrequencies, totalCells, narrowedSelection, hist, min, max); } else if(props.GetHistogramType() == SelectionProperties::HistogramVariable) { SelectAndHistogram(props, allIdsPerTimeStep, allVariablesPerTimeStep, totalCellsPerTimeStep, narrowedSelection, hist, min, max); } selection.clear(); delete [] allIds; delete [] allFrequencies; for( size_t ts=0; ts<selectionPerTimeStep.size(); ++ts ) { delete [] allIdsPerTimeStep[ts]; delete [] allVariablesPerTimeStep[ts]; } delete [] allIdsPerTimeStep; delete [] allVariablesPerTimeStep; } // **************************************************************************** // Method: CumulativeQuery::CalculateFrequency // // Purpose: // This method iterates over this processor's datasets for all time steps and // builds up a map of cellid to number of times the cell appears in different // time steps. // // Arguments: // props : The selection properties. // timesteps : The vector of datasets for all time steps. // cellFrequency : The cell frequency map we're creating. // cellsPerTimeStep : Cells in each time step that match // // Returns: // // Note: // // Programmer: Brad Whitlock // Creation: Fri May 20 14:33:41 PDT 2011 // // Modifications: // Brad Whitlock, Wed Oct 12 12:08:16 PDT 2011 // I made histogram variable be a string instead of an index. // // Brad Whitlock, Fri Oct 28 13:37:23 PDT 2011 // I generalized the id variable. // // **************************************************************************** template <class CQCellIdentifier, class CQSelection> void CumulativeQuery<CQCellIdentifier, CQSelection>::CalculateFrequency( const SelectionProperties &props, std::vector<avtDataTree_p> &timesteps, CQSelection &cellFrequency, std::vector < CQSelection > &cellsPerTimeStep) const { const char *mName = "CumulativeQuery<>::CalculateFrequency: "; StackTimer t0(mName); // Make sure that the cellsPerTimestep vector is initialized properly. cellsPerTimeStep.resize(timesteps.size() ); std::string histVar; if(props.GetHistogramType() == SelectionProperties::HistogramVariable) { histVar = props.GetHistogramVariable(); debug5 << mName << "We're doing histogram by variable " << histVar << std::endl; } for(size_t ts = 0; ts < timesteps.size(); ++ts) { if(*timesteps[ts] == NULL) { debug5 << mName << "Time step " << ts << " of input dataset is empty." << std::endl; continue; } // Iterate over all pieces of the data for the current time step and // figure out the set of cells. int nleaves = 0; vtkDataSet **leaves = timesteps[ts]->GetAllLeaves(nleaves); debug5 << mName << "Time step " << ts << " " << mName << "nleaves " << nleaves << std::endl; for (int i = 0 ; i < nleaves ; i++) { vtkIdType ncells = leaves[i]->GetNumberOfCells(); debug5 << mName << " leaf[" << i << "] ncells " << ncells << std::endl; if(ncells == 0) continue; // Get the id variable. vtkDataArray *arr = leaves[i]->GetCellData()->GetArray(idVariable.c_str()); if(arr == NULL && leaves[i]->GetNumberOfCells() == leaves[i]->GetNumberOfPoints()) { arr = leaves[i]->GetPointData()->GetArray(idVariable.c_str()); } if (arr == NULL) { debug1 << mName << "Could not locate id variable " << idVariable << ". This dataset will not contribute to the selection." << std::endl; continue; } if (arr->GetVoidPointer(0) == NULL) { debug1 << mName << "Could not locate id variable " << idVariable << ". This dataset will not contribute to the selection." << std::endl; continue; } // If we need an extra variable, get it. vtkDataArray *var = 0, *cellVar = 0; if(!histVar.empty()) { var = leaves[i]->GetCellData()->GetArray(histVar.c_str()); if(var == 0) { // If we find that the variable is point data then // recenter it. vtkDataArray *pointVar = leaves[i]->GetPointData()->GetArray(histVar.c_str()); if(pointVar != NULL) { debug3 << mName << "Recentering " << histVar << " so we can histogram with it." << std::endl; vtkPointDataToCellData *pd2cd = vtkPointDataToCellData::New(); pd2cd->SetInputData(leaves[i]); pd2cd->Update(); vtkDataSet *ds2 = pd2cd->GetOutput(); cellVar = ds2->GetCellData()->GetArray(histVar.c_str()); if(cellVar != NULL) { debug3 << mName << "We have forced " << histVar << " to be zonal" << std::endl; cellVar->Register(NULL); } var = cellVar; pd2cd->Delete(); } else { debug1 << mName << "Could not get requested histogram variable: " << histVar << std::endl; } } } for(vtkIdType j = 0; j < ncells; ++j) { CQCellIdentifier cellId(cellsPerTimeStep[ts].CellIdentifierFromTuple(arr, j)); typename CQSelection::iterator p = cellsPerTimeStep[ts].find(cellId); double variable = var ? var->GetTuple1(j) : 0.; if(p == cellsPerTimeStep[ts].end()) { CQCellData c; c.frequency = 1; c.variable = variable; cellsPerTimeStep[ts][cellId] = c; } else { // we have a cell we've seen before so we must // have fragments of that cell so sum the // variables. p->second.variable += variable; } } if(cellVar != NULL) cellVar->Delete(); } delete [] leaves; // Merge the results from the current time step into the overall // cell frequency map. We do this so there are no duplicates from // cells that may have been split up previously. This way, cell // fragments do not impact the frequency. typename CQSelection::iterator it; for(it = cellsPerTimeStep[ts].begin(); it != cellsPerTimeStep[ts].end(); ++it) { typename CQSelection::iterator p = cellFrequency.find(it->first); if(p == cellFrequency.end()) { CQCellData c; c.frequency = 1; c.variable = 0; // insert new cell cellFrequency[it->first] = c; //it->second; } else { // we've seen this cell before in another time step so // increment. p->second.frequency += 1; } } } } // **************************************************************************** // Method: CumulativeQuery::Summation // // Purpose: // Examine the cell frequency map and apply the right "summation" to // combine the cells over time into a new selection. // // Arguments: // props : The selection properties. // cellFrequency : The number of times each cell was found // in the datasets over time. // cellsPerTimeStep : Cells in each time step that match // selection : The new "summed" selection. // selectionPerTimeStep : The new "summed" selection for each // time step that match // // Returns: // // Note: // // Programmer: Brad Whitlock // Creation: Thu Jun 9 11:04:39 PDT 2011 // // Modifications: // Brad Whitlock, Sat Nov 5 01:32:16 PDT 2011 // I templated the class so it can support different cell identifier types. // // **************************************************************************** template <class CQCellIdentifier, class CQSelection> void CumulativeQuery<CQCellIdentifier, CQSelection>::Summation( const SelectionProperties &props, const CQSelection &cellFrequency, const std::vector< CQSelection > &cellsPerTimeStep, CQSelection &selection, std::vector< CQSelection > &selectionPerTimeStep) const { const char *mName = "CumulativeQuery<>::Summation: "; StackTimer t0(mName); unsigned int nts = cellsPerTimeStep.size(); selectionPerTimeStep.resize( nts ); if(props.GetCombineRule() == SelectionProperties::CombineAnd) { typename CQSelection::const_iterator it; for(it = cellFrequency.begin(); it != cellFrequency.end(); ++it) { if((unsigned int)it->second.frequency == nts) { selection[it->first] = it->second; for( unsigned int ts=0; ts<nts; ++ts ) { // cellsPerTimeStep is a const but the [] operator // is not a const so use find instead which is a // const operation. typename CQSelection::const_iterator p = cellsPerTimeStep[ts].find(it->first); if(p == cellsPerTimeStep[ts].end()) { // This should never happen because for an and // operator the cell must be in all tiem time // steps. } else selectionPerTimeStep[ts][it->first] = p->second; } } } } else // if(props.GetCombineRule() == SelectionProperties::CombineOr) { selection = cellFrequency; for( unsigned int ts=0; ts<nts; ++ts ) selectionPerTimeStep[ts] = cellsPerTimeStep[ts]; } } // **************************************************************************** // Method: CumulativeQuery::ComputeGlobalSelectionSize // // Purpose: // Compute the global number of cells in the selection when all processors // are considered. Also provide an offset into a global array where the // local data should be stored. // // Arguments: // selection : The local selection. // globalSize : The size of the global selection. // myOffset : The offset in the global array where local data can be stored. // // Returns: // // Note: // // Programmer: Brad Whitlock // Creation: Fri Oct 28 14:35:49 PDT 2011 // // Modifications: // // **************************************************************************** template <class CQCellIdentifier, class CQSelection> void CumulativeQuery<CQCellIdentifier, CQSelection>::ComputeGlobalSizeAndOffset( const CQSelection &selection, int &globalSize, int &myOffset) const { const char *mName = "CumulativeQuery<>::ComputeGlobalSizeAndOffset: "; #ifdef PARALLEL // Compute the global selection size. int *numPerProcIn = new int[PAR_Size()]; int *numPerProc = new int[PAR_Size()]; for (int i = 0 ; i < PAR_Size() ; i++) numPerProcIn[i] = 0; numPerProcIn[PAR_Rank()] = selection.size(); SumIntArrayAcrossAllProcessors(numPerProcIn, numPerProc, PAR_Size()); globalSize = 0; for (int i = 0 ; i < PAR_Size() ; i++) globalSize += numPerProc[i]; myOffset = 0; for (int i = 0 ; i < PAR_Rank() ; i++) myOffset += numPerProc[i]; delete [] numPerProcIn; delete [] numPerProc; #else globalSize = (int) selection.size(); myOffset = 0; #endif debug5 << mName << "selection size " << selection.size() << " " << "global size " << globalSize << " " << "myOffset " << myOffset << " " << std::endl; } // **************************************************************************** // Method: CumulativeQuery::GlobalizeData // // Purpose: // Globalize the selection's data. // // Arguments: // selection : The local selection. // globalSize : The size of the global selection. // myOffset : The local offset into the global array. // allFrequencies : The returned array contains the global selection frequencies. // // Returns: // // Note: // // Programmer: Brad Whitlock // Creation: Fri Oct 28 14:37:39 PDT 2011 // // Modifications: // // **************************************************************************** template <class CQCellIdentifier, class CQSelection> void CumulativeQuery<CQCellIdentifier, CQSelection>::GlobalizeData( const CQSelection &selection, int globalSize, int myOffset, int *&allFrequencies) const { allFrequencies = new int[globalSize]; #ifdef PARALLEL // Unpack the data into arrays int *sendFrequency = new int[globalSize]; memset(sendFrequency, 0, sizeof(int) * globalSize); typename CQSelection::const_iterator it = selection.begin(); for(int i = myOffset; it != selection.end(); ++it, ++i) sendFrequency[i] = it->second.frequency; // Globalize SumIntArrayAcrossAllProcessors(sendFrequency, allFrequencies, globalSize); delete [] sendFrequency; #else // Unpack the data into arrays typename CQSelection::const_iterator it = selection.begin(); for(int i = myOffset; it != selection.end(); ++it, ++i) allFrequencies[i] = it->second.frequency; #endif } // **************************************************************************** // Method: CumulativeQuery::GlobalizeData // // Purpose: // Globalize the selection's data. // // Arguments: // selection : The local selection. // globalSize : The size of the global selection. // myOffset : The local offset into the global array. // allVariables : The returned array contains the global selection variables. // // Returns: // // Note: // // Programmer: Brad Whitlock // Creation: Fri Oct 28 14:37:39 PDT 2011 // // Modifications: // // **************************************************************************** template <class CQCellIdentifier, class CQSelection> void CumulativeQuery<CQCellIdentifier, CQSelection>::GlobalizeData( const CQSelection &selection, int globalSize, int myOffset, double *&allVariables) const { int i; typename CQSelection::const_iterator it; #ifdef PARALLEL // Unpack the data into arrays double *sendVariable = new double[globalSize]; memset(sendVariable, 0, sizeof(double) * globalSize); for(i = myOffset, it = selection.begin(); it != selection.end(); ++it, ++i) { sendVariable[i] = it->second.variable; } // Globalize allVariables = new double[globalSize]; SumDoubleArrayAcrossAllProcessors(sendVariable, allVariables, globalSize); delete [] sendVariable; #else // Unpack the data into arrays allVariables = new double[globalSize]; for(i = myOffset, it = selection.begin(); it != selection.end(); ++it, ++i) { allVariables[i] = it->second.variable; } #endif } // **************************************************************************** // Method: CumulativeQuery::MakeDataUnique // // Purpose: // Clean up the globalize selection data by removing all duplicates // cell ids and adjusting the frequency. This will occur when cell // ids are on different ranks for differening time steps thus may be // in allIds multiple times. // // Arguments: // globalSize : The size of the global selection. // allIds : The returned array contains the global selection ids // allFrequencies : The returned array contains the global selection frequencies. // // Programmer: Allen Sanderson // Creation: Fri Jan 20 2017 // // **************************************************************************** template <class CQCellIdentifier, class CQSelection> void CumulativeQuery<CQCellIdentifier, CQSelection>::MakeDataUnique( int &globalSize, CQCellIdentifier *&allIds, int *&allFrequencies) const { #ifdef PARALLEL std::map< CQCellIdentifier, int> idFreqMap; typename std::map< CQCellIdentifier, int>::iterator it; // Get each of the unique cell id for( int i=0; i<globalSize; ++i ) { CQCellIdentifier cellid(allIds[i]); it = idFreqMap.find(cellid); if( it == idFreqMap.end() ) idFreqMap[cellid] = allFrequencies[i]; else // We've seen this cell before idFreqMap[cellid] += allFrequencies[i]; } // If the map size differs from the global size then ids were not // all unique. if( idFreqMap.size() != globalSize ) { // Replace the previous globalSize = idFreqMap.size(); delete[] allIds; delete[] allFrequencies; allIds = new CQCellIdentifier[globalSize]; allFrequencies = new int[globalSize]; it = idFreqMap.begin(); for( int i=0; i<globalSize; ++i, ++it ) { allIds[i] = it->first; allFrequencies[i] = it->second; } } #endif } // **************************************************************************** // Method: CumulativeQuery::GlobalizeSelection // // Purpose: // This method takes the selections from each processor and combines them // and sends the results to each processor as a set of arrays that describe // the selection that was created. // // Arguments: // selection : This processor's selection // // allDomains : The array of domain numbers for each cell // in the global selection. // allCellIds : The array of cell ids for each cell // in the global selection. // allFrequencies : The array of frequencies for each cell // in the global selection. // allVariables : The array of variable values for each cell // in the global selection. // totalCells : The total number of cells in the global selection. // // Returns: True if the selection was globalized; False otherwise. // // Note: // // Programmer: Brad Whitlock // Creation: Thu Jun 9 10:58:41 PDT 2011 // // Modifications: // Brad Whitlock, Fri Oct 28 13:38:57 PDT 2011 // Rewrite. // // **************************************************************************** template <class CQCellIdentifier, class CQSelection> bool CumulativeQuery<CQCellIdentifier, CQSelection>::GlobalizeSelection( const CQSelection &selection, CQCellIdentifier *&allIds, int *&allFrequencies, int &globalSize, const std::vector< CQSelection > &selectionPerTimeSteps, CQCellIdentifier **&allIdsPerTimeStep, double **&allVariablesPerTimeStep, std::vector< int >& globalSizePerTimeStep) const { const char *mName = "CumulativeQuery<>::GlobalizeSelection: "; StackTimer t0(mName); int myOffset = 0; std::vector< int > myOffsetPerTimeStep; int nts = selectionPerTimeSteps.size(); globalSizePerTimeStep.resize( nts ); myOffsetPerTimeStep.resize( nts ); #ifdef PARALLEL globalSize = 0; ComputeGlobalSizeAndOffset(selection, globalSize, myOffset); if(globalSize > avtNamedSelection::MaximumSelectionSize()) { debug1 << mName<< "The number of total cells (" << globalSize << ") is above the allowed limit." << std::endl; return false; } for( int ts=0; ts<nts; ++ts ) { globalSizePerTimeStep[ts] = 0; ComputeGlobalSizeAndOffset(selectionPerTimeSteps[ts], globalSizePerTimeStep[ts], myOffsetPerTimeStep[ts]); } #else globalSize = (int) selection.size(); for( int ts=0; ts<nts; ++ts ) globalSizePerTimeStep[ts] = (int) selectionPerTimeSteps[ts].size(); #endif // Globalize the selection keys (ids). selection.GlobalizeIds(globalSize, myOffset, allIds); // Globalize the selection data GlobalizeData(selection, globalSize, myOffset, allFrequencies); // Make sure the ids are all unique if not, adjust the frequency. MakeDataUnique( globalSize, allIds, allFrequencies ); // Globalize across all time steps allIdsPerTimeStep = new CQCellIdentifier *[nts]; allVariablesPerTimeStep = new double *[nts]; for( int ts=0; ts<nts; ++ts ) { // Globalize the selection keys (ids) across all time steps selectionPerTimeSteps[ts].GlobalizeIds(globalSizePerTimeStep[ts], myOffsetPerTimeStep[ts], allIdsPerTimeStep[ts]); // Globalize the selection data across all time steps GlobalizeData(selectionPerTimeSteps[ts], globalSizePerTimeStep[ts], myOffsetPerTimeStep[ts], allVariablesPerTimeStep[ts]); } return true; } // **************************************************************************** // Class: cq_sort_by_value // // Purpose: // This class is a functor that lets std::sort sort an array of // values using value[i] instead of i. // // Notes: // // Programmer: Brad Whitlock // Creation: Fri May 20 14:04:49 PDT 2011 // // Modifications: // // **************************************************************************** template <class T> class cq_sort_by_value { public: cq_sort_by_value(const T *v) : value(v) { } bool operator()(int A, int B) const { return value[A] < value[B]; } private: const T *value; }; // **************************************************************************** // Method: CumulativeQuery::SelectAndHistogram // // Purpose: // This method takes the globalized selection (the list of matching cells // for all domains for all time) and sorts it in the manner prescribed by // the desired histogram operation and then we keep some number of bins // from that and create our final "narrowed" selection. We also compute an // average frequency for the cells in each histogram bin. // // Arguments: // props : The selection properties. // selectionPerTimeStep : The array containing the ids for the // global selectionper time step. // narrowedSelection : The returned selection. // histogram : The returned histogram of avg frequency per bin. // // Returns: narrowedSelection, histogram. // // Note: // // Programmer: Brad Whitlock // Creation: Fri May 20 14:20:58 PDT 2011 // // Modifications: // Brad Whitlock, Fri Oct 28 14:19:35 PDT 2011 // I combined the doms/zones into CQCellIdentifier. I removed the step to // restrict the narrowed selection to this processor's data. We just won't // have to globalize again later. // // Brad Whitlock, Sat Nov 5 01:32:16 PDT 2011 // I templated the class so it can support different cell identifier types. // // **************************************************************************** // template <class CQCellIdentifier, class CQSelection> // void // CumulativeQuery<CQCellIdentifier, CQSelection>::SelectAndHistogram( // const SelectionProperties &props, // const std::vector< CQSelection > &selectionPerTimeStep, // CQSelection &narrowedSelection, // doubleVector &histogram ) const // { // const char *mName = "CumulativeQuery<>::SelectAndHistogram: "; // debug5 << mName << "selectionPerTimeStep" << std::endl; // StackTimer t0(mName); // int numBins = selectionPerTimeStep.size(); // for(int bin = 0; bin < numBins; ++bin) // { // // If the bin is one that we're selecting then add its cells to the // // narrowed selection. // if(props.GetHistogramStartBin() <= bin && // bin <= props.GetHistogramEndBin()) // { // typename CQSelection::const_iterator it; // for(it = selectionPerTimeStep[bin].begin(); it != selectionPerTimeStep[bin].end(); ++it) // { // CQCellIdentifier cellid(it->first); // typename CQSelection::iterator p = // narrowedSelection.find(cellid); // if( p == narrowedSelection.end() ) // { // CQCellData c; // c.frequency = 1; // c.variable = 0.; // we don't need the variable anymore // // insert new cell // narrowedSelection[cellid] = c; // } // else // { // // we've seen this cell before in another time step so // // increment. // p->second.frequency += 1; // } // } // } // histogram.push_back( double(selectionPerTimeStep[bin].size()) ); // } // debug5 << mName << "Done selected " << narrowedSelection.size() // << std::endl; // } // **************************************************************************** // Method: CumulativeQuery::SelectAndHistogram // // Purpose: // This method takes the globalized selection (the list of matching cells // for all domains for all time) and sorts it in the manner prescribed by // the desired histogram operation and then we keep some number of bins // from that and create our final "narrowed" selection. We also compute an // average frequency for the cells in each histogram bin. // // Arguments: // props : The selection properties. // allIdsPerTimeStep : The array containing the ids // for the global selection per time step. // totalCellsPerTimeStep : The number of cells in the selection // per time step. // narrowedSelection : The returned selection. // histogram : The returned histogram of avg frequency per bin. // // Returns: narrowedSelection, histogram. // // Note: // // Programmer: Brad Whitlock // Creation: Fri May 20 14:20:58 PDT 2011 // // Modifications: // Brad Whitlock, Fri Oct 28 14:19:35 PDT 2011 // I combined the doms/zones into CQCellIdentifier. I removed the step to // restrict the narrowed selection to this processor's data. We just won't // have to globalize again later. // // Brad Whitlock, Sat Nov 5 01:32:16 PDT 2011 // I templated the class so it can support different cell identifier types. // // **************************************************************************** template <class CQCellIdentifier, class CQSelection> void CumulativeQuery<CQCellIdentifier, CQSelection>::SelectAndHistogram( const SelectionProperties &props, CQCellIdentifier **allIdsPerTimeStep, std::vector <int> totalCellsPerTimeStep, CQSelection &narrowedSelection, doubleVector &histogram) const { const char *mName = "CumulativeQuery<>::SelectAndHistogram: "; debug5 << mName << "HistogramTime" << std::endl; StackTimer t0( mName ); int numBins = totalCellsPerTimeStep.size(); for(int bin = 0; bin < numBins; ++bin) { debug5 << mName << "totalCellsPerTimeStep " << totalCellsPerTimeStep[bin] << std::endl; histogram.push_back(totalCellsPerTimeStep[bin]); // If the bin is one that we're selecting then add its cells // to the narrowed selection. if(props.GetHistogramStartBin() <= bin && bin <= props.GetHistogramEndBin()) { for( int j=0; j<totalCellsPerTimeStep[bin]; ++j ) { CQCellIdentifier cellid(allIdsPerTimeStep[bin][j]); typename CQSelection::iterator p = narrowedSelection.find(cellid); if( p == narrowedSelection.end() ) { CQCellData c; c.frequency = 1; c.variable = 0.; // we don't need the variable anymore narrowedSelection[cellid] = c; debug5 << mName << "cell selected " << CellIdentifierFromID( cellid ) << std::endl; } else { // we've seen this cell before in another time step // so increment. p->second.frequency += 1; } } } } debug5 << mName << "Done selected " << narrowedSelection.size() << std::endl; } // **************************************************************************** // Method: CumulativeQuery::SelectAndHistogram // // Purpose: // This method takes the globalized selection (the list of matching cells // for all domains for all time) and sorts it in the manner prescribed by // the desired histogram operation and then we keep some number of bins // from that and create our final "narrowed" selection. We also compute an // average frequency for the cells in each histogram bin. // // Arguments: // props : The selection properties. // allIds : The array containing the ids // for the global selection. // allFrequencies : The array containing the frequencies // for the global selection. // totalCells : The number of cells in the selection. // narrowedSelection : The returned selection. // histogram : The returned histogram of avg frequency per bin. // // Returns: narrowedSelection, histogram. // // Note: // // Programmer: Brad Whitlock // Creation: Fri May 20 14:20:58 PDT 2011 // // Modifications: // Brad Whitlock, Fri Oct 28 14:19:35 PDT 2011 // I combined the doms/zones into CQCellIdentifier. I removed the step to // restrict the narrowed selection to this processor's data. We just won't // have to globalize again later. // // Brad Whitlock, Sat Nov 5 01:32:16 PDT 2011 // I templated the class so it can support different cell identifier types. // // **************************************************************************** template <class CQCellIdentifier, class CQSelection> void CumulativeQuery<CQCellIdentifier, CQSelection>::SelectAndHistogram( const SelectionProperties &props, const CQCellIdentifier *allIds, const int *allFrequencies, int totalCells, CQSelection &narrowedSelection, doubleVector &histogram, double &min, double &max) const { const char *mName = "CumulativeQuery<>::SelectAndHistogram: "; if(props.GetHistogramType() == SelectionProperties::HistogramID) { debug5 << mName << "HistogramID" << std::endl; } else if(props.GetHistogramType() == SelectionProperties::HistogramMatches) { debug5 << mName << "HistogramMatches" << std::endl; } StackTimer t0(mName); // Create an index variable that we'll sort using another variable. int *index = new int[totalCells]; for(int i = 0; i < totalCells; ++i) index[i] = i; // We need to bin the index array into some number of bins and select // the cells in the selected bins into our new narrowed selection. int *binPoints = NULL, numBins = 0; // ID Histogram if(props.GetHistogramType() == SelectionProperties::HistogramID) { // Sort the index based on cell id debug5 << mName << "Sorting index based on cellid" << std::endl; std::sort(index, index + totalCells, cq_sort_by_value<CQCellIdentifier>(allIds)); // For IDs the number of bins is based on the user defined // number of bins or automatically set. min = CellIdentifierFromID( allIds[index[0]] ); max = CellIdentifierFromID( allIds[index[totalCells-1]] ); if( props.GetHistogramAutoScaleNumBins() ) numBins = (max-min+1 <= 1024 ? max-min+1 : 1024 ); else numBins = props.GetHistogramNumBins(); } // Matches Histogram else if(props.GetHistogramType() == SelectionProperties::HistogramMatches) { // Sort the index based on frequency debug5 << mName << "Sorting index based on frequency" << std::endl; std::sort(index, index + totalCells, cq_sort_by_value<int>(allFrequencies)); // For matches the number of bins is based on the number of matches min = allFrequencies[index[0]]; max = allFrequencies[index[totalCells-1]]; numBins = max-min+1; } // Get indexs of the counts that will be placed in each in bin. binPoints = new int[numBins + 1]; // The starting binPoints will always be the first cell. binPoints[0] = 0; for(int i=1, j=0; i<numBins; ++i) { // Get the threshold for this bin. The threshold is based on // the id. double t = min + double(i) * (max-min) / double(numBins); if(props.GetHistogramType() == SelectionProperties::HistogramID) { while( CellIdentifierFromID( allIds[index[j]] ) < t ) ++j; } else if(props.GetHistogramType() == SelectionProperties::HistogramMatches) { while( allFrequencies[index[j]] < t ) ++j; } binPoints[i] = j; } // The ending binPoints will always be the totalCells. binPoints[numBins] = totalCells; double cellsPerBin = double(max-min+1) / double(numBins); debug5 << mName << "min/max=" << min << "/" << max << ", totalCells=" << totalCells << ", cellsPerBin=" << cellsPerBin << ", numBins=" << numBins << ", startBin=" << props.GetHistogramStartBin() << ", endBin=" << props.GetHistogramEndBin() << std::endl; for(int bin = 0; bin < numBins; ++bin) { histogram.push_back((binPoints[bin+1] - binPoints[bin])/cellsPerBin); // If the bin is one that we're selecting then add its cells to the // narrowed selection. if( props.GetHistogramStartBin() <= bin && bin <= props.GetHistogramEndBin() ) { debug5 << mName << "Bin " << bin << " contains indices [" << binPoints[bin] << ", " << binPoints[bin+1] << "). Adding cells from this bin to the new selection." << std::endl; for(int i = binPoints[bin]; i < binPoints[bin+1]; ++i) { int idx = index[i]; CQCellIdentifier cellid(allIds[idx]); CQCellData c; c.frequency = allFrequencies[idx]; c.variable = 0.; // we don't need the variable anymore narrowedSelection[cellid] = c; debug5 << mName << "cell selected " << CellIdentifierFromID( cellid ) << std::endl; } } } delete [] binPoints; delete [] index; debug5 << mName << "Done selected " << narrowedSelection.size() << std::endl; } // **************************************************************************** // Method: CumulativeQuery::SelectAndHistogram // // Purpose: // This method takes the globalized selection (the list of matching cells // for all domains for all time) and sorts it in the manner prescribed by // the desired histogram operation and then we keep some number of bins // from that and create our final "narrowed" selection. We also compute an // average frequency for the cells in each histogram bin. // // Arguments: // props : The selection properties. // allIdsPerTimeStep : The array containing the ids for the // global selection per time step. // allVariablesPerTimeStep : The array containing the variables for the // global selection per time step. // totalCellsPerTimeStep : The number of cells in the selection // per time step. // narrowedSelection : The returned selection. // histogram : The returned histogram of avg frequency per bin. // // Returns: narrowedSelection, histogram. // // Note: // // Programmer: Brad Whitlock // Creation: Fri May 20 14:20:58 PDT 2011 // // Modifications: // Brad Whitlock, Fri Oct 28 14:19:35 PDT 2011 // I combined the doms/zones into CQCellIdentifier. I removed the step to // restrict the narrowed selection to this processor's data. We just won't // have to globalize again later. // // Brad Whitlock, Sat Nov 5 01:32:16 PDT 2011 // I templated the class so it can support different cell identifier types. // // **************************************************************************** template <class CQCellIdentifier, class CQSelection> void CumulativeQuery<CQCellIdentifier, CQSelection>::SelectAndHistogram( const SelectionProperties &props, CQCellIdentifier **allIdsPerTimeStep, double **allVariablesPerTimeStep, std::vector <int> totalCellsPerTimeStep, CQSelection &narrowedSelection, doubleVector &histogram, double &min, double &max) const { const char *mName = "CumulativeQuery<>::SelectAndHistogram: "; debug5 << mName << "HistogramVariable" << std::endl; StackTimer t0(mName); int nts = totalCellsPerTimeStep.size(); // Merge all of the data into a set of single arrays. int totalCells = 0; for( int ts=0; ts<nts; ++ts ) totalCells += totalCellsPerTimeStep[ts]; CQCellIdentifier *allIds = new CQCellIdentifier[totalCells]; double *allVariables = new double[totalCells]; int *index = new int[totalCells]; // Create an index variable that we'll sort using another variable // while storing the variables and ids in a one dimensional array. for( int ts=0, i=0; ts<nts; ++ts ) { for( int j=0; j<totalCellsPerTimeStep[ts]; ++j ) { allIds[i] = allIdsPerTimeStep[ts][j]; allVariables[i] = allVariablesPerTimeStep[ts][j]; index[i] = i; ++i; } } // We need to bin the index array into some number of bins and select // the cells in the selected bins into our new narrowed selection. int *binPoints = NULL, numBins = 0; // Sort the index based on variable debug5 << mName << "Sorting index based on variable" << std::endl; std::sort(index, index + totalCells, cq_sort_by_value<double>(allVariables)); // For IDs the number of bins is based on the user defined number // of bins or automatically set. min = allVariables[index[0]]; max = allVariables[index[totalCells-1]]; if( props.GetHistogramAutoScaleNumBins() ) numBins = (max-min+1 <= 1024 ? max-min+1 : 1024 ); else numBins = props.GetHistogramNumBins(); binPoints = new int[numBins + 1]; // The starting binPoints will always be the first cell. binPoints[0] = 0; for(int i=1, j=0; i<numBins; ++i) { // Get the threshold for this bin. The threshold is based on // the frequency of matches. double t = min + double(i) * (max-min) / double(numBins); while( allVariables[index[j]] < t ) ++j; binPoints[i] = j; } // The ending binPoints will always be the totalCells. binPoints[numBins] = totalCells; debug5 << mName << "numBins=" << numBins << ", startBin=" << props.GetHistogramStartBin() << ", endBin=" << props.GetHistogramEndBin() << std::endl; for(int bin = 0; bin < numBins; ++bin) { histogram.push_back(binPoints[bin+1] - binPoints[bin]); // If the bin is one that we're selecting then add its cells to the // narrowed selection. if(props.GetHistogramStartBin() <= bin && bin <= props.GetHistogramEndBin()) { debug5 << mName << "Bin " << bin << " contains indices [" << binPoints[bin] << ", " << binPoints[bin+1] << "). Adding cells from this bin to the new selection." << std::endl; for(int i = binPoints[bin]; i < binPoints[bin+1]; ++i) { int idx = index[i]; CQCellIdentifier cellid(allIds[idx]); typename CQSelection::iterator p = narrowedSelection.find(cellid); if( p == narrowedSelection.end() ) { CQCellData c; c.frequency = 1; c.variable = 0.; // we don't need the variable anymore narrowedSelection[cellid] = c; debug5 << mName << "cell selected " << CellIdentifierFromID( cellid ) << std::endl; } else { // we've seen this cell before in another time step // so increment. p->second.frequency += 1; } } } } delete [] binPoints; delete [] index; debug5 << mName << "Done selected " << narrowedSelection.size() << std::endl; } // ***************************************************************************** // ***************************************************************************** // *** // *** CQDomainZoneIdSelection // *** // ***************************************************************************** // ***************************************************************************** typedef std::pair<unsigned int, unsigned int> CQDomainZoneId; template<> double CellIdentifierFromID< CQDomainZoneId > ( CQDomainZoneId id ) { return id.second; } // **************************************************************************** // Class: CQDomainZoneIdSelection // // Purpose: // This class implemetns a selection type that lets us index cells using a // (domain,zoneid) tuple. // // Notes: // // Programmer: Brad Whitlock // Creation: Sat Nov 5 01:44:07 PDT 2011 // // Modifications: // // **************************************************************************** class CQDomainZoneIdSelection : public std::map<CQDomainZoneId, CQCellData> { public: CQDomainZoneIdSelection() : std::map<CQDomainZoneId, CQCellData>() { } avtNamedSelection *CreateNamedSelection(const std::string &name) const; vtkDataSet *CreateSelectedDataset(const std::string &idVariable) const; CQDomainZoneId CellIdentifierFromTuple(vtkDataArray *arr, vtkIdType cellid) const; void GlobalizeIds(int globalSize, int myOffset, CQDomainZoneId*&allIds) const; }; // **************************************************************************** // Method: CQDomainZoneIdSelection::CreateNamedSelection // // Purpose: // Create a new named selection from the selection map keys. // // Arguments: // name : The name of the new selection. // // Returns: We return a new avtZoneIdNamedSelection object. // // Note: // // Programmer: Brad Whitlock // Creation: Sat Nov 5 01:45:14 PDT 2011 // // Modifications: // // **************************************************************************** avtNamedSelection * CQDomainZoneIdSelection::CreateNamedSelection(const std::string &name) const { int *doms = new int[size()+1]; int *zones = new int[size()+1]; int i = 0; for(const_iterator it = begin(); it != end(); ++it, ++i) { doms[i] = it->first.first; zones[i] = it->first.second; debug5 << "CQDomainZoneIdSelection::CreateNamedSelection " << i << " domain " << it->first.first << " zone " << it->first.second << std::endl; } avtZoneIdNamedSelection *ns = new avtZoneIdNamedSelection(name); ns->SetIdentifiers((int)size(), doms, zones); delete [] doms; delete [] zones; return ns; } // **************************************************************************** // Method: CQDomainZoneIdSelection::CreateSelectedDataset // // Purpose: // Create a VTK that encodes the selection map keys. // // Arguments: // idVariable : The name of the array we'll put into the VTK dataset to // represent the selection. // // Returns: A new VTK dataset that encodes the selection. // // Note: // // Programmer: Brad Whitlock // Creation: Sat Nov 5 01:46:08 PDT 2011 // // Modifications: // // **************************************************************************** vtkDataSet * CQDomainZoneIdSelection::CreateSelectedDataset(const std::string &idVariable) const { // Create a dummy dataset. int dims[] = {1,1,1}; dims[0] = (int)size()+1; vtkRectilinearGrid *rgrid = vtkRectilinearGrid::New(); rgrid->SetDimensions(dims); vtkFloatArray *x = vtkFloatArray::New(); x->SetNumberOfTuples(dims[0]); for(int i = 0; i < dims[0]; ++i) x->SetTuple1(i, i); rgrid->SetXCoordinates(x); x->Delete(); // Store the map keys as avtOriginalCellNumbers. vtkUnsignedIntArray *ids = vtkUnsignedIntArray::New(); ids->SetName(idVariable.c_str()); ids->SetNumberOfComponents(2); ids->SetNumberOfTuples(size()); unsigned int *ptr = (unsigned int *)ids->GetVoidPointer(0); for(const_iterator it = begin(); it != end(); ++it) { *ptr++ = it->first.first; *ptr++ = it->first.second; } rgrid->GetCellData()->AddArray(ids); ids->Delete(); return rgrid; } // **************************************************************************** // Method: CQDomainZoneIdSelection::CellIdentifierFromTuple // // Purpose: // Return a cell identifier from a specific tuple in a data array. // // Arguments: // arr : The VTK data array that we're using to index the cells. // cellid : The index of the tuple to use. // // Returns: A new cell identifier. // // Note: // // Programmer: Brad Whitlock // Creation: Sat Nov 5 01:51:47 PDT 2011 // // Modifications: // // **************************************************************************** CQDomainZoneId CQDomainZoneIdSelection::CellIdentifierFromTuple(vtkDataArray *arr, vtkIdType cellid) const { const unsigned int *ptr = (const unsigned int *)arr->GetVoidPointer(0); // debug5 << "CQDomainZoneId " << cellid << " " // << ptr[cellid*2] << " " << ptr[cellid*2+1] << std::endl; return CQDomainZoneId(ptr[cellid*2], ptr[cellid*2+1]); } // **************************************************************************** // Method: CQDomainZoneIdSelection::GlobalizeIds // // Purpose: // Globalize the map keys so all processors will have the same set of keys. // // Arguments: // globalSize : The global number of map keys. // myOffset : This processor's local offset into the global array. // allIds : The returned globalized ids. // // Returns: // // Note: This implementation is specific to tuples of (domain,zone). // // Programmer: Brad Whitlock // Creation: Sat Nov 5 01:53:39 PDT 2011 // // Modifications: // // **************************************************************************** void CQDomainZoneIdSelection::GlobalizeIds(int globalSize, int myOffset, CQDomainZoneId*&allIds) const { int i = 0; const_iterator it; #ifdef PARALLEL // Unpack the keys into arrays int *sendKey = new int[globalSize*2]; memset(sendKey, 0, sizeof(int) * globalSize * 2); for(i = 0, it = begin(); it != end(); ++it, ++i) { int idx = (myOffset + i) * 2; sendKey[idx] = it->first.first; sendKey[idx + 1] = it->first.second; debug5 << "local keys " << i << " " << it->first.first << " " << it->first.second << std::endl; } // Globalize int *allKeys = new int[globalSize * 2]; SumIntArrayAcrossAllProcessors(sendKey, allKeys, globalSize * 2); delete [] sendKey; // Turn the arrays back into keys allIds = new CQDomainZoneId[globalSize]; int *ptr = allKeys; for(i = 0; i < globalSize; ++i, ptr += 2) { allIds[i] = CQDomainZoneId(ptr[0], ptr[1]); debug5 << "global keys " << i << " " << ptr[0] << " " << ptr[1] << std::endl; } delete [] allKeys; #else allIds = new CQDomainZoneId[size()+1]; for(i = 0, it = begin(); it != end(); ++it, ++i) allIds[i] = it->first; #endif } // ***************************************************************************** // ***************************************************************************** // *** // *** CQVariableIdSelection // *** // ***************************************************************************** // ***************************************************************************** typedef double CQVariableId; template<> double CellIdentifierFromID< CQVariableId > ( CQVariableId id ) { return id; } // **************************************************************************** // Class: CQVariableIdSelection // // Purpose: // This class implements a selection type that lets us index cells using a // user-defined variable. // // Notes: // // Programmer: Brad Whitlock // Creation: Sat Nov 5 01:44:07 PDT 2011 // // Modifications: // // **************************************************************************** class CQVariableIdSelection : public std::map<CQVariableId, CQCellData> { public: CQVariableIdSelection() : std::map<CQVariableId, CQCellData>() { } avtNamedSelection *CreateNamedSelection(const std::string &name) const; vtkDataSet *CreateSelectedDataset(const std::string &idVariable) const; CQVariableId CellIdentifierFromTuple(vtkDataArray *arr, vtkIdType cellid) const; void GlobalizeIds(int globalSize, int myOffset, CQVariableId*&allIds) const; }; // **************************************************************************** // Method: CQVariableIdSelection::CreateNamedSelection // // Purpose: // Create a new named selection from the selection map keys. // // Arguments: // name : The name of the new selection. // // Returns: We return a new avtFloatingPointIdNamedSelection object. // // Note: // // Programmer: Brad Whitlock // Creation: Sat Nov 5 01:45:14 PDT 2011 // // Modifications: // // **************************************************************************** avtNamedSelection * CQVariableIdSelection::CreateNamedSelection(const std::string &name) const { // Create the floating point named selection std::vector<double> ids; ids.reserve(size()); int i = 0; for(const_iterator it = begin(); it != end(); ++it) { ids.push_back(it->first); debug5 << "CQVariableIdSelection::CreateNamedSelection " << i++ << " value " << it->first << std::endl; } avtFloatingPointIdNamedSelection *ns = new avtFloatingPointIdNamedSelection(name); ns->SetIdentifiers(ids); return ns; } // **************************************************************************** // Method: CQVariableIdSelection::CreateSelectedDataset // // Purpose: // Create a VTK that encodes the selection map keys.. // // Arguments: // idVariable : The name of the array we'll put into the VTK dataset to // represent the selection. // // Returns: A new VTK dataset that encodes the selection. // // Note: // // Programmer: Brad Whitlock // Creation: Sat Nov 5 01:46:08 PDT 2011 // // Modifications: // // **************************************************************************** vtkDataSet * CQVariableIdSelection::CreateSelectedDataset(const std::string &idVariable) const { // Create a dummy dataset int dims[] = {1,1,1}; dims[0] = (int)size()+1; vtkRectilinearGrid *rgrid = vtkRectilinearGrid::New(); rgrid->SetDimensions(dims); vtkFloatArray *x = vtkFloatArray::New(); x->SetNumberOfTuples(dims[0]); for(int i = 0; i < dims[0]; ++i) x->SetTuple1(i, i); rgrid->SetXCoordinates(x); x->Delete(); // Encode the map keys as an array on the dataset. vtkDoubleArray *ids = vtkDoubleArray::New(); ids->SetName(idVariable.c_str()); ids->SetNumberOfTuples(size()); double *ptr = (double *)ids->GetVoidPointer(0); for(const_iterator it = begin(); it != end(); ++it) { *ptr++ = it->first; } rgrid->GetCellData()->AddArray(ids); ids->Delete(); return rgrid; } // **************************************************************************** // Method: CQVariableIdSelection::CellIdentifierFromTuple // // Purpose: // Return a cell identifier from a specific tuple in a data array. // // Arguments: // arr : The VTK data array that we're using to index the cells. // cellid : The index of the tuple to use. // // Returns: A new cell identifier. // // Note: // // Programmer: Brad Whitlock // Creation: Sat Nov 5 01:51:47 PDT 2011 // // Modifications: // // **************************************************************************** CQVariableId CQVariableIdSelection::CellIdentifierFromTuple(vtkDataArray *arr, vtkIdType cellid) const { debug5 << "CellIdentifierFromTuple " << cellid << " " << arr->GetTuple1(cellid) << std::endl; return arr->GetTuple1(cellid); } // **************************************************************************** // Method: CQVariableIdSelection::GlobalizeIds // // Purpose: // Globalize the map keys so all processors will have the same set of keys. // // Arguments: // globalSize : The global number of map keys. // myOffset : This processor's local offset into the global array. // allIds : The returned globalized ids. // // Returns: // // Note: This implementation is specific to tuples of double. // // Programmer: Brad Whitlock // Creation: Sat Nov 5 01:53:39 PDT 2011 // // Modifications: // // **************************************************************************** void CQVariableIdSelection::GlobalizeIds(int globalSize, int myOffset, CQVariableId*&allIds) const { int i = 0; const_iterator it; #ifdef PARALLEL // Unpack the keys into arrays double *sendKey = new double[globalSize]; memset(sendKey, 0, sizeof(double) * globalSize); for(i = 0, it = begin(); it != end(); ++it, ++i) { int idx = (myOffset + i); sendKey[idx] = it->first; } // Globalize double *allKeys = new double[globalSize]; SumDoubleArrayAcrossAllProcessors(sendKey, allKeys, globalSize); delete [] sendKey; // Turn the arrays back into keys allIds = new CQVariableId[globalSize]; for(i = 0; i < globalSize; ++i) allIds[i] = allKeys[i]; delete [] allKeys; #else allIds = new CQVariableId[size()+1]; for(i = 0, it = begin(); it != end(); ++it, ++i) allIds[i] = it->first; #endif } // ***************************************************************************** // ***************************************************************************** // *** // *** CQFilter // *** // ***************************************************************************** // ***************************************************************************** // **************************************************************************** // Class: CQFilter // // Purpose: // This filter collects selected time steps and comes up with the // set of cells that are present in any of the time steps. That set // of cells then gets further reduced using different // "histogramming" functions. The final, reduced set of cells is // returned as a new dataset which is used to construct the CQ // selection. // // Notes: We also extract information about the selection cells and store // them so we can use them in the selection summary. // // Programmer: Brad Whitlock // Creation: Mon May 9 15:24:10 PDT 2011 // // Modifications: // Brad Whitlock, Wed Sep 7 11:07:18 PDT 2011 // I moved most of the guts to the CumulativeQuery class. // // Brad Whitlock, Sat Nov 5 01:10:14 PDT 2011 // I templated the class on a CQ implementation and a CQ selection type so // we can do CQ's that use different index variables to relate cells. // // **************************************************************************** template <class CQImpl, class CQSelection> class CQFilter : public avtTimeLoopCollectorFilter { public: CQFilter() : avtTimeLoopCollectorFilter(), props(), summary(), CQ() { } virtual ~CQFilter() { } void SetSelectionProperties(const SelectionProperties &p) { props = p; } CQImpl &GetCumulativeQuery() { return CQ; } const SelectionSummary &GetSummary() const { return summary; } virtual const char *GetType() { return "CQFilter"; } virtual const char *GetDescription() { return "Creating cumulative query selection"; } virtual bool ExecutionSuccessful() { return true; } virtual avtDataTree_p ExecuteAllTimesteps(std::vector<avtDataTree_p> &); protected: virtual avtContract_p ModifyContract(avtContract_p contract); private: SelectionProperties props; SelectionSummary summary; CQImpl CQ; }; // **************************************************************************** // Method: CQFilter::ExecuteAllTimesteps // // Purpose: // This method implements the filter's time iteration loop. We take in the // datasets for all time steps and iterate over them, calculating our // histogrammed selection using the CumulativeQuery object. // // Arguments: // timesteps : The data trees for each timestep. // // Returns: We return a data tree with a dummy dataset that has the number // of cells in our final selection and we place the original zones // array on it since that is what is used later to define the // named selection. // // Note: // // Programmer: Brad Whitlock // Creation: Fri May 20 14:28:53 PDT 2011 // // Modifications: // Brad Whitlock, Wed Sep 7 11:04:34 PDT 2011 // I moved the guts of the function into the CumulativeQuery class. // // Brad Whitlock, Sat Nov 5 01:10:14 PDT 2011 // I templated the class on a CQ implementation and a CQ selection type so // we can do CQ's that use different index variables to relate cells. // // **************************************************************************** template <class CQImpl, class CQSelection> avtDataTree_p CQFilter<CQImpl,CQSelection>::ExecuteAllTimesteps(std::vector<avtDataTree_p> &timesteps) { CQSelection selection; summary = SelectionSummary(); doubleVector hist; double min, max; CQ.CreateSelection(this->props, timesteps, selection, hist, min, max); // Save the histogram values in the summary. summary.SetHistogramValues(hist); // if(this->props.GetHistogramType() == SelectionProperties::HistogramTime) // { // summary.SetHistogramMinBin( props.GetMinTimeState() ); // if(this->props.GetMaxTimeState() < 0) // summary.SetHistogramMaxBin( this->dob->GetInfo().GetAttributes().GetNumStates() - 1 ); // else // summary.SetHistogramMaxBin( this->props.GetMaxTimeState() ); // } // else if(this->props.GetHistogramType() == SelectionProperties::HistogramMatches || this->props.GetHistogramType() == SelectionProperties::HistogramID || this->props.GetHistogramType() == SelectionProperties::HistogramVariable ) { summary.SetHistogramMinBin(min); summary.SetHistogramMaxBin(max); } // // Now that we have the final set of local cells derived from the // selection, we create an output dataset that identifies this // processor's portion of the cells in the selection. // vtkDataSet *ds = selection.CreateSelectedDataset(CQ.GetIdVariable()); avtDataTree_p outputTree = new avtDataTree(ds, -1); ds->Delete(); return outputTree; } // **************************************************************************** // Method: CQFilter::ModifyContract // // Purpose: // We use this method to make sure that the histogram variable that we want // to use has been requested in the contract. // // Arguments: // contract : The input contract. // // Returns: The output contract. // // Note: // // Programmer: Brad Whitlock // Creation: Thu Jun 9 10:50:51 PDT 2011 // // Modifications: // Brad Whitlock, Wed Oct 12 12:09:52 PDT 2011 // I changed histogram variable from an index to a string. // // Brad Whitlock, Sat Nov 5 01:10:14 PDT 2011 // I templated the class on a CQ implementation and a CQ selection type so // we can do CQ's that use different index variables to relate cells. // // **************************************************************************** template <class CQImpl, class CQSelection> avtContract_p CQFilter<CQImpl,CQSelection>::ModifyContract(avtContract_p contract) { const char *mName = "CQFilter<>::ModifyContract: "; avtContract_p newContract = avtTimeLoopCollectorFilter::ModifyContract(contract); // We may need to extract another variable. if(props.GetHistogramType() == SelectionProperties::HistogramVariable) { const std::string &histVar = props.GetHistogramVariable(); debug5 << mName << "We're doing histogram by variable " << histVar << std::endl; std::string origvar(newContract->GetDataRequest()->GetOriginalVariable()); if(origvar != histVar && !newContract->GetDataRequest()->HasSecondaryVariable(histVar.c_str())) { debug5 << mName << "Making sure we add " << histVar << " to the contract so we'll have it" << std::endl; newContract->GetDataRequest()->AddSecondaryVariable(histVar.c_str()); } } return newContract; } // ***************************************************************************** // ***************************************************************************** // *** // *** CumulativeQueryCacheItem // *** // ***************************************************************************** // ***************************************************************************** // **************************************************************************** // Class: CumulativeQueryCacheItem // // Purpose: // This class contains intermediate results for CumulativeQuery that we can // store in the avtNamedSelectionManager's cache. // // Notes: // // Programmer: Brad Whitlock // Creation: Wed Sep 7 13:47:24 PDT 2011 // // Modifications: // Brad Whitlock, Sat Nov 5 01:11:50 PDT 2011 // I templated the class on the CQ selection type so we can store different // types of selections in the cache. // // **************************************************************************** template <class CQSelection> class CumulativeQueryCacheItem : public avtNamedSelectionCacheItem { public: CumulativeQueryCacheItem() : avtNamedSelectionCacheItem(), cellFrequency(), cellsPerTimeStep(), summary() { } virtual ~CumulativeQueryCacheItem() { const char *mName = "CumulativeQueryCacheItem::~CumulativeQueryCacheItem: "; debug5 << mName << "Deleting." << std::endl; } CQSelection cellFrequency; std::vector<CQSelection> cellsPerTimeStep; SelectionSummary summary; }; // ***************************************************************************** // ***************************************************************************** // *** // *** CumulativeQueryNamedSelectionExtension // *** // ***************************************************************************** // ***************************************************************************** // **************************************************************************** // Method: CumulativeQueryNamedSelectionExtension::CumulativeQueryNamedSelectionExtension // // Purpose: // Constructor // // Programmer: Brad Whitlock // Creation: Wed Sep 7 13:48:25 PDT 2011 // // Modifications: // // **************************************************************************** CumulativeQueryNamedSelectionExtension::CumulativeQueryNamedSelectionExtension() : avtNamedSelectionExtension() { } // **************************************************************************** // Method: CumulativeQueryNamedSelectionExtension::~CumulativeQueryNamedSelectionExtension // // Purpose: // Destructor // // Programmer: Brad Whitlock // Creation: Wed Sep 7 13:48:39 PDT 2011 // // Modifications: // // **************************************************************************** CumulativeQueryNamedSelectionExtension::~CumulativeQueryNamedSelectionExtension() { } // **************************************************************************** // Function: CreateSelectionKey // // Purpose: // Determine a key to use for caching, given the selection properties. // // Arguments: // props : The selection properties. // // Returns: A string that can be used for a cache key. // // Note: // // Programmer: Brad Whitlock // Creation: Wed Sep 7 13:48:54 PDT 2011 // // Modifications: // Brad Whitlock, Sat Nov 5 01:13:39 PDT 2011 // I turned it into a static function. // // **************************************************************************** static std::string CreateSelectionKey(const SelectionProperties &props) { // implement me... For now return the name. We could work more // information into the name to allow us to cache multiple // intermediate results for a single selection name. return props.GetName(); } // **************************************************************************** // Function: CheckProperties // // Purpose: // Check the old properties vs the new properties to see if we can use the // intermediate results that the old properties represent. // // Arguments: // newProps : The new selection properties. // oldProps : The old selection properties. // // Returns: True if the new and old selection properties are sufficiently // the same such that any intermediate selection results can be // reused to compute the selection. // // Note: // // Programmer: Brad Whitlock // Creation: Wed Sep 7 15:06:55 PDT 2011 // // Modifications: // Brad Whitlock, Wed Oct 12 12:11:01 PDT 2011 // I changed histogram variable to a string from an index. // // Brad Whitlock, Fri Oct 28 11:33:05 PDT 2011 // Account for id variable. // // Brad Whitlock, Sat Nov 5 01:13:39 PDT 2011 // I turned it into a static function. // // **************************************************************************** static bool CheckProperties(const SelectionProperties &newProps, const SelectionProperties &oldProps) { bool basicsSame = (newProps.GetName() == oldProps.GetName()) && (newProps.GetSource() == oldProps.GetSource()) && (newProps.GetSelectionType() == oldProps.GetSelectionType()); bool idvarSame = newProps.GetIdVariableType() == oldProps.GetIdVariableType(); if(idvarSame && newProps.GetIdVariableType() == SelectionProperties::UseVariableForID) { idvarSame = newProps.GetIdVariable() == oldProps.GetIdVariable(); } bool varsSame = (newProps.GetVariables() == oldProps.GetVariables()) && (newProps.GetVariableMins() == oldProps.GetVariableMins()) && (newProps.GetVariableMaxs() == oldProps.GetVariableMaxs()); bool timeSame = (newProps.GetMinTimeState() == oldProps.GetMinTimeState()) && (newProps.GetMaxTimeState() == oldProps.GetMaxTimeState()) && (newProps.GetTimeStateStride() == oldProps.GetTimeStateStride()); bool typeCloseEnough = true; if(newProps.GetHistogramType() == oldProps.GetHistogramType()) { if(newProps.GetHistogramType() == SelectionProperties::HistogramVariable && newProps.GetHistogramVariable() != oldProps.GetHistogramVariable()) { typeCloseEnough = false; } } return basicsSame && idvarSame && varsSame && timeSame && typeCloseEnough; } // **************************************************************************** // Function: BuildSummary // // Purpose: // Retrieve the histograms we've calculated in filters and store them into a // summary object. // // Programmer: Brad Whitlock // Creation: Fri Dec 17 14:47:17 PST 2010 // // Modifications: // Brad Whitlock, Tue Sep 6 15:41:23 PDT 2011 // I renamed the method to BuildSummary and removed code to delete filters // or set the internal summary object. // // Brad Whitlock, Sat Nov 5 01:13:39 PDT 2011 // I turned it into a static function. // // **************************************************************************** static SelectionSummary BuildSummary(const CQHistogramCalculationFilter &hist) { const char *mName = "CumulativeQueryNamedSelectionExtension::BuildSummary: "; StackTimer t0(mName); // Stash hist's histograms into this class so we can return them // from the engine. SelectionSummary s; stringVector vars = hist.GetVariables(); for(size_t i = 0; i < vars.size(); ++i) { const CQHistogramCalculationFilter::Histogram *h = hist.GetHistogram(vars[i]); if(h != 0) { SelectionVariableSummary vs; vs.SetName(vars[i]); vs.SetMinimum(h->minimum); vs.SetMaximum(h->maximum); vs.SetHistogram(h->frequency); s.AddVariables(vs); } else { debug5 << mName << "Could not locate histogram for " << vars[i] << " so create a default histogram." << std::endl; double frequency[NBINS]; memset(frequency, 0, NBINS * sizeof(double)); SelectionVariableSummary vs; vs.SetName(vars[i]); vs.SetMinimum(0.); vs.SetMaximum(1.); vs.SetHistogram(frequency); s.AddVariables(vs); } } // Set the total cell count. Note that we now divide that number // by the number of time steps that were processed because the // time loop filter causes our local histogram filter that counts // the number of original cells to sum the total number of cells // for all time steps. This gives us the per time step avg. debug5 << mName << "total cells = " << hist.GetTotalCellCount() << std::endl; s.SetTotalCellCount((int)hist.GetTotalCellCount()); return s; } // **************************************************************************** // Function: GetSelectionEx // // Purpose: // Compute a cumulative query selection based on the input data object and // return the selection. // // Arguments: // dob : The input data object (We don't always use it). // contract : The contract that that will be used if the pipeline // needs to reexecuted. // props : The selection properties. // cache : The NSM's cache. // cqFilter : The CQ filter implementation we want to use. // selection : The CQ selection that we want to use. // outSummary : Return the selection summary in this object. // // Returns: A named selection containing the pieces we care about. // // Note: // // Programmer: Brad Whitlock // Creation: Wed Sep 7 12:37:13 PDT 2011 // // Modifications: // // **************************************************************************** template <class CQFilterType, class CQSelection> static avtNamedSelection * GetSelectionEx(avtDataObject_p dob, avtContract_p contract, const SelectionProperties &props, avtNamedSelectionCache &cache, CQFilterType &cqFilter, CQSelection &selection, SelectionSummary &outSummary) { const char *mName = "GetSelectionEx<>::GetSelection: "; StackTimer t0(mName); avtNamedSelection *ns = NULL; // Check the selection cache for intermediate data we can use so we do not // have to execute the CQ over time. std::string selectionKey = CreateSelectionKey(props); CumulativeQueryCacheItem<CQSelection> *intermediateResults = NULL; if(cache.exists(selectionKey)) { debug1 << mName << "Found intermediate selection data for " << props.GetName() << std::endl; intermediateResults = (CumulativeQueryCacheItem<CQSelection> *)cache[selectionKey]; // Check to see if the intermediate results are okay to use. if(!CheckProperties(props, intermediateResults->properties)) { debug1 << mName << "Intermediate selection data was found but " "it could not be used." << std::endl; intermediateResults = NULL; } } if(intermediateResults != NULL) { StackTimer t1("Calculating CQ selection with intermediate data"); debug1 << mName << "Calculating selection " << props.GetName() << " using intermediate results." << std::endl; // Intermediate data exists. Let's just redo the histogramming part // of CQ so we don't have to do time iteration again. doubleVector hist; double min, max; cqFilter.GetCumulativeQuery().CreateSelection(props, intermediateResults->cellFrequency, intermediateResults->cellsPerTimeStep, selection, hist, min, max); // Now that we have a selection, convert it into a named // selection object. ns = selection.CreateNamedSelection(props.GetName()); // Save the histogram values in the summary. outSummary = intermediateResults->summary; outSummary.SetHistogramValues(hist); if(props.GetHistogramType() == SelectionProperties::HistogramTime) { outSummary.SetHistogramMinBin( props.GetMinTimeState() ); if(props.GetMaxTimeState() < 0) outSummary.SetHistogramMaxBin( dob->GetInfo().GetAttributes().GetNumStates() - 1 ); else outSummary.SetHistogramMaxBin( props.GetMaxTimeState() ); } else if(props.GetHistogramType() == SelectionProperties::HistogramMatches || props.GetHistogramType() == SelectionProperties::HistogramID || props.GetHistogramType() == SelectionProperties::HistogramVariable ) { outSummary.SetHistogramMinBin(min); outSummary.SetHistogramMaxBin(max); } } else { StackTimer t1("Calculating CQ selection"); debug1 << mName << "Calculating selection " << props.GetName() << " from scratch." << std::endl; // Add in our custom filters. avtDataObject_p newdob(dob); CQHistogramCalculationFilter hist; avtThresholdFilter threshold; if(!props.GetVariables().empty()) { // Set up the variable that we're going to use to threshold. SelectionProperties prop2(props); if(prop2.GetMaxTimeState() < 0) prop2.SetMaxTimeState(dob->GetInfo().GetAttributes().GetNumStates()-1); // // Add a CQHistogramCalculationFilter so we can calculate // histograms for the variables that we care about. // hist.SetInput(newdob); for(size_t i = 0; i < prop2.GetVariables().size(); ++i) hist.AddVariable(prop2.GetVariables()[i]); newdob = hist.GetOutput(); // // Add a threshold operator to the pipeline, thresholding // out the variables in our CQ selection. // ThresholdOpAttributes thresholdAtts; if(!props.GetVariables().empty()) thresholdAtts.SetDefaultVarName(props.GetVariables()[0]); thresholdAtts.SetListedVarNames(props.GetVariables()); thresholdAtts.SetLowerBounds(props.GetVariableMins()); thresholdAtts.SetUpperBounds(props.GetVariableMaxs()); threshold.SetInput(newdob); threshold.SetAtts(&thresholdAtts); newdob = threshold.GetOutput(); // // Add our time iteration CQ filter. // cqFilter.SetInput(newdob); cqFilter.SetTimeLoop(prop2.GetMinTimeState(), prop2.GetMaxTimeState(), prop2.GetTimeStateStride()); cqFilter.SetSelectionProperties(prop2); newdob = cqFilter.GetOutput(); } // Execute the full pipeline. debug1 << mName << "Must re-execute pipeline to create named selection" << std::endl; TimedCodeBlock("CQ Pipeline update", newdob->Update(contract); ); debug1 << mName << "Done re-executing pipeline to create named selection" << std::endl; // Extract the selection from the data tree. avtDataset_p ds; CopyTo(ds, newdob); ns = avtNamedSelectionExtension::GetSelectionFromDataset(ds, props); // Extract data from the filters and stick it in the summary. outSummary = BuildSummary(hist); outSummary.SetHistogramValues(cqFilter.GetSummary().GetHistogramValues()); if(props.GetHistogramType() == SelectionProperties::HistogramTime) { outSummary.SetHistogramMinBin( props.GetMinTimeState() ); if(props.GetMaxTimeState() < 0) outSummary.SetHistogramMaxBin( dob->GetInfo().GetAttributes().GetNumStates() - 1 ); else outSummary.SetHistogramMaxBin( props.GetMaxTimeState() ); } else if(props.GetHistogramType() == SelectionProperties::HistogramMatches || props.GetHistogramType() == SelectionProperties::HistogramID || props.GetHistogramType() == SelectionProperties::HistogramVariable ) { outSummary.SetHistogramMinBin(cqFilter.GetSummary().GetHistogramMinBin()); outSummary.SetHistogramMaxBin(cqFilter.GetSummary().GetHistogramMaxBin()); } // Cache the intermediate selection & summary. debug1 << mName << "Caching intermediate results for selection" << std::endl; CumulativeQueryCacheItem<CQSelection> *item = new CumulativeQueryCacheItem<CQSelection>; item->properties = props; item->cellFrequency = cqFilter.GetCumulativeQuery().GetCellFrequency(); item->cellsPerTimeStep = cqFilter.GetCumulativeQuery().GetCellsPerTimeStep(); item->summary = outSummary; cache[selectionKey] = item; } return ns; } // **************************************************************************** // Method: CumulativeQueryNamedSelectionExtension::GetSelection // // Purpose: // Compute a cumulative query selection based on the input data object and // return the selection. // // Arguments: // dob : The input data object (We don't always use it). // props : The selection properties. // cache : The NSM's cache. // // Returns: A named selection containing the pieces we care about. // // Note: This function calls GetSelectionEx with different CQ // implementations so we can do CQ with different cell indexing // schemes. // // Programmer: Brad Whitlock // Creation: Fri Oct 28 15:41:41 PDT 2011 // // Modifications: // // **************************************************************************** avtNamedSelection * CumulativeQueryNamedSelectionExtension::GetSelection(avtDataObject_p dob, const SelectionProperties &props, avtNamedSelectionCache &cache) { avtNamedSelection *ns = NULL; avtContract_p c0 = dob->GetContractFromPreviousExecution(); bool needsUpdate = false; avtContract_p contract = ModifyContract(c0, props, needsUpdate); if(props.GetIdVariableType() == SelectionProperties::UseZoneIDForID) { CQFilter<CumulativeQuery<CQDomainZoneId, CQDomainZoneIdSelection>, CQDomainZoneIdSelection > cqFilter; cqFilter.GetCumulativeQuery().SetIdVariable(GetIdVariable(props)); CQDomainZoneIdSelection selection; ns = GetSelectionEx(dob, contract, props, cache, cqFilter, selection, summary); } else if(props.GetIdVariableType() == SelectionProperties::UseGlobalZoneIDForID) { // This one might be long long for the index type. Check it... CQFilter<CumulativeQuery<CQVariableId, CQVariableIdSelection>, CQVariableIdSelection> cqFilter; cqFilter.GetCumulativeQuery().SetIdVariable(GetIdVariable(props)); CQVariableIdSelection selection; ns = GetSelectionEx(dob, contract, props, cache, cqFilter, selection, summary); } else if(props.GetIdVariableType() == SelectionProperties::UseVariableForID) { CQFilter<CumulativeQuery<CQVariableId, CQVariableIdSelection>, CQVariableIdSelection > cqFilter; cqFilter.GetCumulativeQuery().SetIdVariable(GetIdVariable(props)); CQVariableIdSelection selection; ns = GetSelectionEx(dob, contract, props, cache, cqFilter, selection, summary); } if(ns != NULL) ns->SetIdVariable(GetIdVariable(props)); return ns; } // **************************************************************************** // Method: CumulativeQueryNamedSelectionExtension::GetSelectionSummary // // Purpose: // Get the selection summary. // // Returns: Get the selection summary. // // Programmer: Brad Whitlock // Creation: Fri Dec 17 14:55:13 PST 2010 // // Modifications: // // **************************************************************************** const SelectionSummary & CumulativeQueryNamedSelectionExtension::GetSelectionSummary() const { return summary; }
ba27f350aea2bbfac7df29bbcc103e3211a5ab8e
a3cf3ed7895b6168fe0864770f944d0a25d5ad74
/src/libre/class/utf8_Gunjala_Gondi.c
712b6e136158f6d4d0a065387d23cf017f10d8a4
[ "BSD-2-Clause" ]
permissive
katef/libfsm
32269415d8ab61778bef9bfdb3c14c61117216d4
479d103357f4e1a8596437895bbc6ddf237a1da0
refs/heads/main
2023-08-12T06:21:35.611111
2023-06-03T22:17:25
2023-06-15T20:40:54
80,573,145
918
66
BSD-2-Clause
2023-09-12T13:31:36
2017-01-31T23:31:36
C
UTF-8
C
false
false
328
c
utf8_Gunjala_Gondi.c
/* generated */ #include "class.h" static const struct range ranges[] = { { 0x11D60UL, 0x11D65UL }, { 0x11D67UL, 0x11D68UL }, { 0x11D6AUL, 0x11D8EUL }, { 0x11D90UL, 0x11D91UL }, { 0x11D93UL, 0x11D98UL }, { 0x11DA0UL, 0x11DA9UL } }; const struct class utf8_Gunjala_Gondi = { ranges, sizeof ranges / sizeof *ranges };
c7688ee23a33468091eb88152b571253e02e6733
9ceacf33fd96913cac7ef15492c126d96cae6911
/usr.sbin/dvmrpd/kroute.c
ac4376046d0c0850d53ccf70b807963bf2c5dd3e
[]
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
8,674
c
kroute.c
/* $OpenBSD: kroute.c,v 1.14 2017/07/24 11:00:01 friehm Exp $ */ /* * Copyright (c) 2004 Esben Norby <norby@openbsd.org> * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.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. */ #include <sys/types.h> #include <sys/socket.h> #include <sys/sysctl.h> #include <sys/tree.h> #include <netinet/in.h> #include <arpa/inet.h> #include <net/if.h> #include <net/if_dl.h> #include <net/if_types.h> #include <net/route.h> #include <err.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "dvmrp.h" #include "dvmrpd.h" #include "log.h" struct { u_int32_t rtseq; pid_t pid; struct event ev; } kr_state; struct kif_node { RB_ENTRY(kif_node) entry; struct kif k; }; int kif_compare(struct kif_node *, struct kif_node *); struct kif_node *kif_find(int); int kif_insert(struct kif_node *); int kif_remove(struct kif_node *); void kif_clear(void); in_addr_t prefixlen2mask(u_int8_t); void get_rtaddrs(int, struct sockaddr *, struct sockaddr **); void if_change(u_short, int, struct if_data *); void if_announce(void *); int fetchifs(int); RB_HEAD(kif_tree, kif_node) kit; RB_PROTOTYPE(kif_tree, kif_node, entry, kif_compare) RB_GENERATE(kif_tree, kif_node, entry, kif_compare) int kif_init(void) { RB_INIT(&kit); if (fetchifs(0) == -1) return (-1); return (0); } int kr_init(void) { int opt, fd; if ((fd = socket(AF_ROUTE, SOCK_RAW | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)) == -1) { log_warn("kr_init: socket"); return (-1); } /* not interested in my own messages */ if (setsockopt(fd, SOL_SOCKET, SO_USELOOPBACK, &opt, sizeof(opt)) == -1) log_warn("kr_init: setsockopt"); /* not fatal */ kr_state.pid = getpid(); kr_state.rtseq = 1; event_set(&kr_state.ev, fd, EV_READ | EV_PERSIST, kr_dispatch_msg, NULL); event_add(&kr_state.ev, NULL); return (0); } void kr_shutdown(void) { kif_clear(); close(EVENT_FD((&kr_state.ev))); } void kr_ifinfo(char *ifname) { struct kif_node *kif; RB_FOREACH(kif, kif_tree, &kit) if (!strcmp(ifname, kif->k.ifname)) { main_imsg_compose_dvmrpe(IMSG_CTL_IFINFO, 0, &kif->k, sizeof(kif->k)); return; } } /* rb-tree compare */ int kif_compare(struct kif_node *a, struct kif_node *b) { return (b->k.ifindex - a->k.ifindex); } struct kif_node * kif_find(int ifindex) { struct kif_node s; memset(&s, 0, sizeof(s)); s.k.ifindex = ifindex; return (RB_FIND(kif_tree, &kit, &s)); } struct kif * kif_findname(char *ifname) { struct kif_node *kif; RB_FOREACH(kif, kif_tree, &kit) if (!strcmp(ifname, kif->k.ifname)) return (&kif->k); return (NULL); } int kif_insert(struct kif_node *kif) { if (RB_INSERT(kif_tree, &kit, kif) != NULL) { log_warnx("RB_INSERT(kif_tree, &kit, kif)"); free(kif); return (-1); } return (0); } int kif_remove(struct kif_node *kif) { if (RB_REMOVE(kif_tree, &kit, kif) == NULL) { log_warnx("RB_REMOVE(kif_tree, &kit, kif)"); return (-1); } free(kif); return (0); } void kif_clear(void) { struct kif_node *kif; while ((kif = RB_MIN(kif_tree, &kit)) != NULL) kif_remove(kif); } /* misc */ u_int8_t prefixlen_classful(in_addr_t ina) { /* it hurt to write this. */ if (ina >= 0xf0000000U) /* class E */ return (32); else if (ina >= 0xe0000000U) /* class D */ return (4); else if (ina >= 0xc0000000U) /* class C */ return (24); else if (ina >= 0x80000000U) /* class B */ return (16); else /* class A */ return (8); } u_int8_t mask2prefixlen(in_addr_t ina) { if (ina == 0) return (0); else return (33 - ffs(ntohl(ina))); } in_addr_t prefixlen2mask(u_int8_t prefixlen) { if (prefixlen == 0) return (0); return (0xffffffff << (32 - prefixlen)); } void if_change(u_short ifindex, int flags, struct if_data *ifd) { struct kif_node *kif; u_int8_t reachable; if ((kif = kif_find(ifindex)) == NULL) { log_warnx("interface with index %u not found", ifindex); return; } kif->k.flags = flags; kif->k.link_state = ifd->ifi_link_state; kif->k.if_type = ifd->ifi_type; kif->k.baudrate = ifd->ifi_baudrate; if ((reachable = (flags & IFF_UP) && LINK_STATE_IS_UP(ifd->ifi_link_state)) == kif->k.nh_reachable) return; /* nothing changed wrt nexthop validity */ kif->k.nh_reachable = reachable; main_imsg_compose_dvmrpe(IMSG_IFINFO, 0, &kif->k, sizeof(kif->k)); } void if_announce(void *msg) { struct if_announcemsghdr *ifan; struct kif_node *kif; ifan = msg; switch (ifan->ifan_what) { case IFAN_ARRIVAL: if ((kif = calloc(1, sizeof(struct kif_node))) == NULL) { log_warn("if_announce"); return; } kif->k.ifindex = ifan->ifan_index; strlcpy(kif->k.ifname, ifan->ifan_name, sizeof(kif->k.ifname)); kif_insert(kif); break; case IFAN_DEPARTURE: kif = kif_find(ifan->ifan_index); kif_remove(kif); break; } } /* rtsock */ #define ROUNDUP(a) \ ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long)) void get_rtaddrs(int addrs, struct sockaddr *sa, struct sockaddr **rti_info) { int i; for (i = 0; i < RTAX_MAX; i++) { if (addrs & (1 << i)) { rti_info[i] = sa; sa = (struct sockaddr *)((char *)(sa) + ROUNDUP(sa->sa_len)); } else rti_info[i] = NULL; } } int fetchifs(int ifindex) { size_t len; int mib[6]; char *buf, *next, *lim; struct if_msghdr ifm; struct kif_node *kif; struct sockaddr *sa, *rti_info[RTAX_MAX]; struct sockaddr_dl *sdl; mib[0] = CTL_NET; mib[1] = PF_ROUTE; mib[2] = 0; mib[3] = AF_INET; mib[4] = NET_RT_IFLIST; mib[5] = ifindex; if (sysctl(mib, 6, NULL, &len, NULL, 0) == -1) { log_warn("sysctl"); return (-1); } if ((buf = malloc(len)) == NULL) { log_warn("fetchif"); return (-1); } if (sysctl(mib, 6, buf, &len, NULL, 0) == -1) { log_warn("sysctl"); free(buf); return (-1); } lim = buf + len; for (next = buf; next < lim; next += ifm.ifm_msglen) { memcpy(&ifm, next, sizeof(ifm)); sa = (struct sockaddr *)(next + sizeof(ifm)); get_rtaddrs(ifm.ifm_addrs, sa, rti_info); if (ifm.ifm_version != RTM_VERSION) continue; if (ifm.ifm_type != RTM_IFINFO) continue; if ((kif = calloc(1, sizeof(struct kif_node))) == NULL) { log_warn("fetchifs"); free(buf); return (-1); } kif->k.ifindex = ifm.ifm_index; kif->k.flags = ifm.ifm_flags; kif->k.link_state = ifm.ifm_data.ifi_link_state; kif->k.if_type = ifm.ifm_data.ifi_type; kif->k.baudrate = ifm.ifm_data.ifi_baudrate; kif->k.mtu = ifm.ifm_data.ifi_mtu; kif->k.nh_reachable = (kif->k.flags & IFF_UP) && LINK_STATE_IS_UP(ifm.ifm_data.ifi_link_state); if ((sa = rti_info[RTAX_IFP]) != NULL) if (sa->sa_family == AF_LINK) { sdl = (struct sockaddr_dl *)sa; if (sdl->sdl_nlen >= sizeof(kif->k.ifname)) memcpy(kif->k.ifname, sdl->sdl_data, sizeof(kif->k.ifname) - 1); else if (sdl->sdl_nlen > 0) memcpy(kif->k.ifname, sdl->sdl_data, sdl->sdl_nlen); /* string already terminated via calloc() */ } kif_insert(kif); } free(buf); return (0); } void kr_dispatch_msg(int fd, short event, void *bula) { char buf[RT_BUF_SIZE]; ssize_t n; char *next, *lim; struct rt_msghdr *rtm; struct if_msghdr ifm; if ((n = read(fd, &buf, sizeof(buf))) == -1) { if (errno == EAGAIN || errno == EINTR) return; fatal("dispatch_rtmsg: read error"); } if (n == 0) fatalx("routing socket closed"); lim = buf + n; for (next = buf; next < lim; next += rtm->rtm_msglen) { rtm = (struct rt_msghdr *)next; if (lim < next + sizeof(u_short) || lim < next + rtm->rtm_msglen) fatalx("dispatch_rtmsg: partial rtm in buffer"); if (rtm->rtm_version != RTM_VERSION) continue; switch (rtm->rtm_type) { case RTM_IFINFO: memcpy(&ifm, next, sizeof(ifm)); if_change(ifm.ifm_index, ifm.ifm_flags, &ifm.ifm_data); break; case RTM_IFANNOUNCE: if_announce(next); break; default: /* ignore for now */ break; } } }
bdba83795852197b1a1f8a28ec3a758a432758a9
c26d7b0ed875357278e61627da2da0650da77986
/src/cmd/write.c
7dc9fd5176fe06befb1862b4c488bf8744b9dda8
[ "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
5,696
c
write.c
/* * write to another user */ #include <stdio.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <signal.h> #include <utmp.h> #include <paths.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #define NMAX sizeof(ubuf.ut_name) #define LMAX sizeof(ubuf.ut_line) struct utmp ubuf; int signum[] = {SIGHUP, SIGINT, SIGQUIT, 0}; char me[NMAX + 1] = "???"; char *him; char *mytty; char histty[32]; char ttybuf[32]; char *histtya; int logcnt; FILE *tf; void timout(sig) int sig; { fprintf(stderr, "write: Timeout opening their tty\n"); exit(1); } void eof(sig) int sig; { fprintf(tf, "EOF\r\n"); exit(0); } main(argc, argv) int argc; char *argv[]; { struct stat stbuf; register i; register FILE *uf; int c1, c2; time_t clock = time(0); int suser = getuid() == 0; int nomesg = 0; struct tm *localclock = localtime( &clock ); if (argc < 2) { fprintf(stderr, "Usage: write user [ttyname]\n"); exit(1); } him = argv[1]; if (argc > 2) histtya = argv[2]; if ((uf = fopen(_PATH_UTMP, "r")) == NULL) { fprintf(stderr, "write: %s: %s\n", _PATH_UTMP, strerror(errno)); if (histtya == 0) exit(10); goto cont; } mytty = ttyname(2); if (mytty == NULL) { fprintf(stderr, "write: Can't find your tty\n"); exit(1); } if (stat(mytty, &stbuf) < 0) { perror("write: Can't stat your tty"); exit(1); } if ((stbuf.st_mode&020) == 0) { fprintf(stderr, "write: You have write permission turned off\n"); if (!suser) exit(1); } mytty = strrchr(mytty, '/') + 1; if (histtya) { strcpy(histty, "/dev/"); strcat(histty, histtya); } while (fread((char *)&ubuf, sizeof(ubuf), 1, uf) == 1) { if (ubuf.ut_name[0] == '\0') continue; if (strcmp(ubuf.ut_line, mytty)==0) { for (i=0; i<NMAX; i++) { c1 = ubuf.ut_name[i]; if (c1 == ' ') c1 = 0; me[i] = c1; if (c1 == 0) break; } } if (him[0] == '-' && him[1] == 0) goto nomat; for (i=0; i<NMAX; i++) { c1 = him[i]; c2 = ubuf.ut_name[i]; if (c1 == 0) if (c2 == 0 || c2 == ' ') break; if (c1 != c2) goto nomat; } if (histtya && strncmp(histtya, ubuf.ut_line, sizeof(ubuf.ut_line))) continue; logcnt++; if (histty[0]==0 || nomesg && histtya == 0) { strcpy(ttybuf, "/dev/"); strcat(ttybuf, ubuf.ut_line); if (histty[0]==0) strcpy(histty, ttybuf); if (access(ttybuf, 0) < 0 || stat(ttybuf, &stbuf) < 0 || (stbuf.st_mode&020) == 0) nomesg++; else { strcpy(histty, ttybuf); nomesg = 0; } } nomat: ; } fclose(uf); if (logcnt==0) { fprintf(stderr, "write: %s not logged in%s\n", him, histtya ? " on that tty" : ""); exit(1); } if (histtya==0 && logcnt > 1) { fprintf(stderr, "write: %s logged in more than once ... writing to %s\n", him, histty+5); } cont: if (access(histty, 0) < 0) { fprintf(stderr, "write: No such tty\n"); exit(1); } signal(SIGALRM, timout); alarm(5); if ((tf = fopen(histty, "w")) == NULL) { fprintf(stderr, "write: Permission denied\n"); exit(1); } alarm(0); sigs(eof); { char hostname[32]; gethostname(hostname, sizeof (hostname)); fprintf(tf, "\r\nMessage from %s@%s on %s at %d:%02d ...\r\n\007\007\007", me, hostname, mytty, localclock->tm_hour, localclock->tm_min); fflush(tf); } for (;;) { char buf[BUFSIZ]; register char *bp; i = read(0, buf, sizeof buf); if (i <= 0) eof(); if (buf[0] == '!') { buf[i] = 0; ex(buf); continue; } for (bp = buf; --i >= 0; bp++) { if (*bp == '\n') putc('\r', tf); if (!isascii(*bp)) { putc('M', tf); putc('-', tf); *bp = toascii(*bp); } if (isprint(*bp) || *bp == ' ' || *bp == '\t' || *bp == '\n') { putc(*bp, tf); } else { putc('^', tf); putc(*bp ^ 0100, tf); } if (*bp == '\n') fflush(tf); if (ferror(tf) || feof(tf)) { printf("\n\007Write failed (%s logged out?)\n", him); exit(1); } } } } ex(bp) char *bp; { register i; sigs(SIG_IGN); i = fork(); if (i < 0) { printf("Try again\n"); goto out; } if (i == 0) { fclose(tf); /* Close his terminal */ setgid(getgid()); /* Give up effective group privs */ sigs((sig_t) 0); execl(getenv("SHELL") ? getenv("SHELL") : "/bin/sh", "sh", "-c", bp+1, 0); exit(0); } while (wait((int *)NULL) != i) ; printf("!\n"); out: sigs(eof); } sigs(sig) sig_t sig; { register i; for (i=0; signum[i]; i++) signal(signum[i], sig); }
8c5e64c8ef9fbb1a523c9bdc5e62cece7cc226b2
5c1625afdb9a9964cca81d0e1a9c44e70f5e769a
/tests/tis-ci.c
2e6438e09c2e3514e35ac21387180df68ea76d76
[ "BSD-3-Clause", "CC0-1.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
LoupVaillant/Monocypher
6a225147b3fd3671c1e3c9caf1fa2828bc3d874a
3a9557427201e78026048547988bbb582fe64f4a
refs/heads/master
2023-09-06T07:21:54.777041
2023-09-05T21:02:44
2023-09-05T21:02:44
97,625,830
583
87
NOASSERTION
2023-02-25T12:42:47
2017-07-18T17:28:53
C
UTF-8
C
false
false
14,761
c
tis-ci.c
// This file is dual-licensed. Choose whichever licence you want from // the two licences listed below. // // The first licence is a regular 2-clause BSD licence. The second licence // is the CC-0 from Creative Commons. It is intended to release Monocypher // to the public domain. The BSD licence serves as a fallback option. // // SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0 // // ------------------------------------------------------------------------ // // Copyright (c) 2020, Mike Pechkin and Loup Vaillant // All rights reserved. // // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ------------------------------------------------------------------------ // // Written in 2017-2020 by Mike Pechkin and Loup Vaillant // // To the extent possible under law, the author(s) have dedicated all copyright // and related neighboring rights to this software to the public domain // worldwide. This software is distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along // with this software. If not, see // <https://creativecommons.org/publicdomain/zero/1.0/> #include "monocypher.h" #include "monocypher-ed25519.h" #include "utils.h" #include "tis-ci-vectors.h" #include <stdio.h> #include <stdlib.h> #include <string.h> static void chacha20(vector_reader *reader) { vector key = next_input(reader); vector nonce = next_input(reader); vector plain = next_input(reader); u64 ctr = load64_le(next_input(reader).buf); vector out = next_output(reader); u64 nb_blocks = plain.size / 64 + (plain.size % 64 != 0); u64 new_ctr = crypto_chacha20_djb(out.buf, plain.buf, plain.size, key.buf, nonce.buf, ctr); if (new_ctr - ctr != nb_blocks) { printf("FAILURE: Chacha20 returned counter not correct: "); } } static void ietf_chacha20(vector_reader *reader) { vector key = next_input(reader); vector nonce = next_input(reader); vector plain = next_input(reader); u64 ctr = load64_le(next_input(reader).buf); vector out = next_output(reader); u32 nb_blocks = (u32)(plain.size / 64 + (plain.size % 64 != 0)); u32 new_ctr = crypto_chacha20_ietf(out.buf, plain.buf, plain.size, key.buf, nonce.buf, (u32)ctr); if (new_ctr - ctr != nb_blocks) { printf("FAILURE: IETF Chacha20 returned counter not correct: "); } } static void hchacha20(vector_reader *reader) { vector key = next_input(reader); vector nonce = next_input(reader); vector out = next_output(reader); crypto_chacha20_h(out.buf, key.buf, nonce.buf); } static void xchacha20(vector_reader *reader) { vector key = next_input(reader); vector nonce = next_input(reader); vector plain = next_input(reader); u64 ctr = load64_le(next_input(reader).buf); vector out = next_output(reader); u64 nb_blocks = plain.size / 64 + (plain.size % 64 != 0); u64 new_ctr = crypto_chacha20_x(out.buf, plain.buf, plain.size, key.buf, nonce.buf, ctr); if (new_ctr - ctr != nb_blocks) { printf("FAILURE: XChacha20 returned counter not correct: "); } } static void poly1305(vector_reader *reader) { vector key = next_input(reader); vector msg = next_input(reader); vector out = next_output(reader); crypto_poly1305(out.buf, msg.buf, msg.size, key.buf); } static void aead_ietf(vector_reader *reader) { vector key = next_input(reader); vector nonce = next_input(reader); vector ad = next_input(reader); vector text = next_input(reader); vector out = next_output(reader); crypto_aead_lock(out.buf + 16, out.buf, key.buf, nonce.buf, ad.buf, ad.size, text.buf, text.size); } static void blake2b(vector_reader *reader) { vector msg = next_input(reader); vector key = next_input(reader); vector out = next_output(reader); crypto_blake2b_keyed(out.buf, out.size, key.buf, key.size, msg.buf, msg.size); } static void sha512(vector_reader *reader) { vector in = next_input(reader); vector out = next_output(reader); crypto_sha512(out.buf, in.buf, in.size); } static void sha512_hmac(vector_reader *reader) { vector key = next_input(reader); vector msg = next_input(reader); vector out = next_output(reader); crypto_sha512_hmac(out.buf, key.buf, key.size, msg.buf, msg.size); } static void sha512_hkdf(vector_reader *reader) { vector ikm = next_input(reader); vector salt = next_input(reader); vector info = next_input(reader); vector okm = next_output(reader); crypto_sha512_hkdf(okm .buf, okm .size, ikm .buf, ikm .size, salt.buf, salt.size, info.buf, info.size); } static void argon2(vector_reader *reader) { crypto_argon2_config config; config.algorithm = load32_le(next_input(reader).buf); config.nb_blocks = load32_le(next_input(reader).buf); config.nb_passes = load32_le(next_input(reader).buf); config.nb_lanes = load32_le(next_input(reader).buf); vector pass = next_input(reader); vector salt = next_input(reader); vector key = next_input(reader); vector ad = next_input(reader); vector out = next_output(reader); void *work_area = alloc(config.nb_blocks * 1024); crypto_argon2_inputs inputs; inputs.pass = pass.buf; inputs.salt = salt.buf; inputs.pass_size = (u32)pass.size; inputs.salt_size = (u32)salt.size; crypto_argon2_extras extras; extras.key = key.buf; extras.ad = ad.buf; extras.key_size = (u32)key.size; extras.ad_size = (u32)ad.size; crypto_argon2(out.buf, (u32)out.size, work_area, config, inputs, extras); free(work_area); } static void x25519(vector_reader *reader) { vector scalar = next_input(reader); vector point = next_input(reader); vector out = next_output(reader); crypto_x25519(out.buf, scalar.buf, point.buf); } static void edDSA(vector_reader *reader) { vector secret_k = next_input(reader); vector public_k = next_input(reader); vector msg = next_input(reader); vector out = next_output(reader); u8 fat_secret_key[64]; memcpy(fat_secret_key , secret_k.buf, 32); memcpy(fat_secret_key + 32, public_k.buf, 32); crypto_eddsa_sign(out.buf, fat_secret_key, msg.buf, msg.size); } static void edDSA_pk(vector_reader *reader) { vector in = next_input(reader); vector out = next_output(reader); u8 seed [32]; u8 secret_key[64]; u8 public_key[32]; memcpy(seed, in.buf, 32); crypto_eddsa_key_pair(secret_key, public_key, seed); memcpy(out.buf, public_key, 32); u8 zeroes[32] = {0}; ASSERT_EQUAL(seed , zeroes , 32); ASSERT_EQUAL(secret_key , in.buf , 32); ASSERT_EQUAL(secret_key + 32, public_key, 32); } static void ed_25519(vector_reader *reader) { vector secret_k = next_input(reader); vector public_k = next_input(reader); vector msg = next_input(reader); vector out = next_output(reader); u8 fat_secret_key[64]; memcpy(fat_secret_key , secret_k.buf, 32); memcpy(fat_secret_key + 32, public_k.buf, 32); crypto_ed25519_sign(out.buf, fat_secret_key, msg.buf, msg.size); } static void ed_25519_check(vector_reader *reader) { vector public_k = next_input(reader); vector msg = next_input(reader); vector sig = next_input(reader); vector out = next_output(reader); out.buf[0] = (u8)crypto_ed25519_check(sig.buf, public_k.buf, msg.buf, msg.size); } static void elligator_dir(vector_reader *reader) { vector in = next_input(reader); vector out = next_output(reader); crypto_elligator_map(out.buf, in.buf); } static void elligator_inv(vector_reader *reader) { vector point = next_input(reader); u8 tweak = next_input(reader).buf[0]; u8 failure = next_input(reader).buf[0]; vector out = next_output(reader); int check = crypto_elligator_rev(out.buf, point.buf, tweak); ASSERT((u8)check == failure); if (check) { out.buf[0] = 0; } } //@ ensures \result == 0; static int p_wipe(void) { printf("\tcrypto_wipe\n"); u8 zeroes[50] = {0}; FOR (i, 0, 50) { RANDOM_INPUT(buf, 50); crypto_wipe(buf, i); ASSERT_EQUAL(zeroes, buf, i); } return 0; } //@ ensures \result == 0; static int p_eddsa_x25519(void) { RANDOM_INPUT(e_seed, 32); u8 secret [64]; u8 e_public1[32]; crypto_eddsa_key_pair(secret, e_public1, e_seed); u8 x_private[64]; crypto_blake2b(x_private, 64, secret, 32); u8 x_public1[32]; crypto_eddsa_to_x25519 (x_public1, e_public1); u8 x_public2[32]; crypto_x25519_public_key(x_public2, x_private); ASSERT_EQUAL(x_public1, x_public2, 32); u8 e_public2[32]; crypto_x25519_to_eddsa (e_public2, x_public1); ASSERT((e_public2[31] & 0x80) == 0); // x coordinate always positive e_public1[31] &= 0x7f; // y coordinate back to original ASSERT_EQUAL(e_public1, e_public2, 32); return 0; } //@ ensures \result == 0; static int p_dirty(void) { int status = 0; RANDOM_INPUT(sk1, 32); sk1[0] |= 1; // make sure it's dirty u8 skc [32]; memcpy(skc, sk1, 32); skc[0] &= 248; // make sure it's clean u8 pks [32]; crypto_x25519_dirty_small(pks , sk1); u8 pksc[32]; crypto_x25519_dirty_small(pksc, skc); u8 pkf [32]; crypto_x25519_dirty_fast (pkf , sk1); u8 pkfc[32]; crypto_x25519_dirty_fast (pkfc, skc); u8 pk1 [32]; crypto_x25519_public_key (pk1 , sk1); // Both dirty functions behave the same status |= memcmp(pks, pkf, 32); // Dirty functions behave cleanly if we clear the 3 msb first status |= memcmp(pksc, pk1, 32); status |= memcmp(pkfc, pk1, 32); printf("%s: x25519 dirty\n", status != 0 ? "FAILED" : "OK"); return status; } //@ ensures \result == 0; static int p_x25519_inverse(void) { int status = 0; RANDOM_INPUT(b, 32); u8 base[32]; // random point (cofactor is cleared). crypto_x25519_public_key(base, b); // check round trip RANDOM_INPUT(sk, 32); u8 pk [32]; u8 blind[32]; crypto_x25519(pk, sk, base); crypto_x25519_inverse(blind, sk, pk); status |= memcmp(blind, base, 32); // check cofactor clearing // (Multiplying by a low order point yields zero u8 low_order[32] = { 0x5f, 0x9c, 0x95, 0xbc, 0xa3, 0x50, 0x8c, 0x24, 0xb1, 0xd0, 0xb1, 0x55, 0x9c, 0x83, 0xef, 0x5b, 0x04, 0x44, 0x5c, 0xc4, 0x58, 0x1c, 0x8e, 0x86, 0xd8, 0x22, 0x4e, 0xdd, 0xd0, 0x9f, 0x11, 0x57, }; u8 zero[32] = {0}; crypto_x25519_inverse(blind, sk, low_order); status |= memcmp(blind, zero, 32); printf("%s: x25519_inverse\n", status != 0 ? "FAILED" : "OK"); return status; } //@ ensures \result == 0; static int p_verify(size_t size, int (*compare)(const u8*, const u8*)) { int status = 0; u8 a[64]; // size <= 64 u8 b[64]; // size <= 64 FOR (i, 0, 2) { FOR (j, 0, 2) { // Set every byte to the chosen value, then compare FOR (k, 0, size) { a[k] = (u8)i; b[k] = (u8)j; } int cmp = compare(a, b); status |= (i == j ? cmp : ~cmp); // Set only two bytes to the chosen value, then compare FOR (k, 0, size / 2) { FOR (l, 0, size) { a[l] = 0; b[l] = 0; } a[k] = (u8)i; a[k + size/2 - 1] = (u8)i; b[k] = (u8)j; b[k + size/2 - 1] = (u8)j; cmp = compare(a, b); status |= (i == j ? cmp : ~cmp); } } } printf("%s: crypto_verify%zu\n", status != 0 ? "FAILED" : "OK", size); return status; } //@ ensures \result == 0; static int p_verify16(void){ return p_verify(16, crypto_verify16); } //@ ensures \result == 0; static int p_verify32(void){ return p_verify(32, crypto_verify32); } //@ ensures \result == 0; static int p_verify64(void){ return p_verify(64, crypto_verify64); } #define TEST(name) \ int v_##name(void) { \ return vector_test(name, #name, nb_##name##_vectors, name##_vectors); \ } //@ ensures \result == 0; TEST(chacha20) //@ ensures \result == 0; TEST(ietf_chacha20) //@ ensures \result == 0; TEST(hchacha20) //@ ensures \result == 0; TEST(xchacha20) //@ ensures \result == 0; TEST(poly1305) //@ ensures \result == 0; TEST(aead_ietf) //@ ensures \result == 0; TEST(blake2b) //@ ensures \result == 0; TEST(sha512) //@ ensures \result == 0; TEST(sha512_hmac) //@ ensures \result == 0; TEST(sha512_hkdf) //@ ensures \result == 0; TEST(argon2) //@ ensures \result == 0; TEST(x25519) //@ ensures \result == 0; TEST(edDSA) //@ ensures \result == 0; TEST(edDSA_pk) //@ ensures \result == 0; TEST(ed_25519) //@ ensures \result == 0; TEST(ed_25519_check) //@ ensures \result == 0; TEST(elligator_dir) //@ ensures \result == 0; TEST(elligator_inv) //@ ensures \result == 0; int main(void) { ASSERT(v_chacha20 () == 0); ASSERT(v_ietf_chacha20 () == 0); ASSERT(v_hchacha20 () == 0); ASSERT(v_xchacha20 () == 0); ASSERT(v_poly1305 () == 0); ASSERT(v_aead_ietf () == 0); ASSERT(v_blake2b () == 0); ASSERT(v_sha512 () == 0); ASSERT(v_sha512_hmac () == 0); ASSERT(v_sha512_hkdf () == 0); ASSERT(v_argon2 () == 0); ASSERT(v_x25519 () == 0); ASSERT(v_edDSA () == 0); ASSERT(v_edDSA_pk () == 0); ASSERT(v_ed_25519 () == 0); ASSERT(v_ed_25519_check() == 0); ASSERT(v_elligator_dir () == 0); ASSERT(v_elligator_inv () == 0); ASSERT(p_wipe () == 0); ASSERT(p_eddsa_x25519 () == 0); ASSERT(p_dirty () == 0); ASSERT(p_x25519_inverse() == 0); ASSERT(p_verify16 () == 0); ASSERT(p_verify32 () == 0); ASSERT(p_verify64 () == 0); return 0; }
31b0cfceba203c678d4d71c641ad6735b06136ed
20e1c2f5cfac01f6b007124fa7792dd69751a6bb
/src/ut-stubs/osapi-timebase-handlers.c
fc86bc77697022d7cbec51b354ce9579131a287b
[ "Apache-2.0" ]
permissive
nasa/osal
71f159b767ba4a8c39df48f238b4f296cc571ac8
99e3b4007da51031b521d90390526e123ff740b4
refs/heads/main
2023-09-01T06:33:53.932829
2023-08-18T14:27:02
2023-08-18T14:27:02
4,814,601
493
229
Apache-2.0
2023-09-13T13:57:40
2012-06-27T23:10:37
C
UTF-8
C
false
false
5,114
c
osapi-timebase-handlers.c
/************************************************************************ * NASA Docket No. GSC-18,719-1, and identified as “core Flight System: Bootes” * * Copyright (c) 2020 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ************************************************************************/ /** * \file * * * Stub implementations for the functions defined in the OSAL API * * The stub implementation can be used for unit testing applications built * on top of OSAL. The stubs do not do any real function, but allow * the return code to be crafted such that error paths in the application * can be executed. */ #include "osapi-timebase.h" /* OSAL public API for this subsystem */ #include "utstub-helpers.h" /* * ----------------------------------------------------------------- * Default handler implementation for 'OS_TimeBaseCreate' stub * ----------------------------------------------------------------- */ void UT_DefaultHandler_OS_TimeBaseCreate(void *UserObj, UT_EntryKey_t FuncKey, const UT_StubContext_t *Context) { osal_id_t *timebase_id = UT_Hook_GetArgValueByName(Context, "timebase_id", osal_id_t *); int32 status; UT_Stub_GetInt32StatusCode(Context, &status); if (status == OS_SUCCESS) { *timebase_id = UT_AllocStubObjId(OS_OBJECT_TYPE_OS_TIMEBASE); } else { *timebase_id = UT_STUB_FAKE_OBJECT_ID; } } /* * ----------------------------------------------------------------- * Default handler implementation for 'OS_TimeBaseDelete' stub * ----------------------------------------------------------------- */ void UT_DefaultHandler_OS_TimeBaseDelete(void *UserObj, UT_EntryKey_t FuncKey, const UT_StubContext_t *Context) { osal_id_t timebase_id = UT_Hook_GetArgValueByName(Context, "timebase_id", osal_id_t); int32 status; UT_Stub_GetInt32StatusCode(Context, &status); if (status == OS_SUCCESS) { UT_DeleteStubObjId(OS_OBJECT_TYPE_OS_TIMEBASE, timebase_id); } } /* * ----------------------------------------------------------------- * Default handler implementation for 'OS_TimeBaseGetIdByName' stub * ----------------------------------------------------------------- */ void UT_DefaultHandler_OS_TimeBaseGetIdByName(void *UserObj, UT_EntryKey_t FuncKey, const UT_StubContext_t *Context) { osal_id_t *timebase_id = UT_Hook_GetArgValueByName(Context, "timebase_id", osal_id_t *); int32 status; UT_Stub_GetInt32StatusCode(Context, &status); if (status == OS_SUCCESS && UT_Stub_CopyToLocal(UT_KEY(OS_TimeBaseGetIdByName), timebase_id, sizeof(*timebase_id)) < sizeof(*timebase_id)) { UT_ObjIdCompose(1, OS_OBJECT_TYPE_OS_TIMEBASE, timebase_id); } } /* * ----------------------------------------------------------------- * Default handler implementation for 'OS_TimeBaseGetInfo' stub * ----------------------------------------------------------------- */ void UT_DefaultHandler_OS_TimeBaseGetInfo(void *UserObj, UT_EntryKey_t FuncKey, const UT_StubContext_t *Context) { OS_timebase_prop_t *timebase_prop = UT_Hook_GetArgValueByName(Context, "timebase_prop", OS_timebase_prop_t *); int32 status; UT_Stub_GetInt32StatusCode(Context, &status); if (status == OS_SUCCESS && UT_Stub_CopyToLocal(UT_KEY(OS_TimeBaseGetInfo), timebase_prop, sizeof(*timebase_prop)) < sizeof(*timebase_prop)) { UT_ObjIdCompose(1, OS_OBJECT_TYPE_OS_TASK, &timebase_prop->creator); strncpy(timebase_prop->name, "Name", sizeof(timebase_prop->name) - 1); timebase_prop->name[sizeof(timebase_prop->name) - 1] = '\0'; } } /* * ----------------------------------------------------------------- * Default handler implementation for 'OS_TimeBaseGetFreeRun' stub * ----------------------------------------------------------------- */ void UT_DefaultHandler_OS_TimeBaseGetFreeRun(void *UserObj, UT_EntryKey_t FuncKey, const UT_StubContext_t *Context) { uint32 *freerun_val = UT_Hook_GetArgValueByName(Context, "freerun_val", uint32 *); int32 status; UT_Stub_GetInt32StatusCode(Context, &status); if (status == OS_SUCCESS && UT_Stub_CopyToLocal(UT_KEY(OS_TimeBaseGetFreeRun), freerun_val, sizeof(*freerun_val)) < sizeof(*freerun_val)) { /* * Use the call count such that the value increases with each successive call. */ *freerun_val = UT_GetStubCount(FuncKey); } }
1d0a57061259b781cb2e28d5d487b32d2a098263
e9911598c43e8526da22b2773a73d9b5966f602a
/cunit/unit.c
5ab38f79398102ac658958ed0dd8d47a7c174247
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
cyrusimap/cyrus-imapd
07236dfd887ed92c147938cf1ed2591449d7e8fd
315441d067ba85814768f840f20bc3bb7f20ea6b
refs/heads/master
2023-09-05T09:57:10.683822
2023-09-05T06:09:43
2023-09-05T06:09:43
59,071,965
508
164
NOASSERTION
2023-09-13T04:34:31
2016-05-18T01:33:49
C
UTF-8
C
false
false
12,988
c
unit.c
/* * Copyright (c) 1994-2010 Carnegie Mellon University. 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 "Carnegie Mellon University" must not be used to * endorse or promote products derived from this software without * prior written permission. For permission or any legal * details, please contact * Carnegie Mellon University * Center for Technology Transfer and Enterprise Creation * 4615 Forbes Avenue * Suite 302 * Pittsburgh, PA 15213 * (412) 268-7393, fax: (412) 268-7395 * innovation@andrew.cmu.edu * * 4. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Computing Services * at Carnegie Mellon University (http://www.cmu.edu/computing/)." * * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <CUnit/CUnit.h> #include <CUnit/Basic.h> #include <CUnit/Automated.h> #if HAVE_VALGRIND_VALGRIND_H #include <valgrind/valgrind.h> #endif #include <setjmp.h> #include "timeout.h" #include "cyrunit.h" #include "util.h" #include "xmalloc.h" #include "lib/retry.h" #include "lib/libconfig.h" #include "lib/xunlink.h" /* generated headers are not necessarily in current directory */ #include "cunit/registers.h" int verbose = 0; int num_testspecs = 0; const char **testspecs; enum { RUN, LIST } mode = RUN; int xml_flag = 0; int timeouts_flag = 1; #if HAVE_VALGRIND_VALGRIND_H #define log1(fmt, a1) do { \ if (RUNNING_ON_VALGRIND) VALGRIND_PRINTF_BACKTRACE(fmt"\n", (a1)); \ else fprintf(stderr, "\nunit: "fmt"\n", (a1)); \ } while (0) #define log2(fmt, a1, a2) do { \ if (RUNNING_ON_VALGRIND) VALGRIND_PRINTF_BACKTRACE(fmt"\n", (a1), (a2));\ else fprintf(stderr, "\nunit: "fmt"\n", (a1), (a2)); \ } while (0) #else #define log1(fmt, a1) do { \ fprintf(stderr, "\nunit: "fmt"\n", (a1)); \ } while (0) #define log2(fmt, a1, a2) do { \ fprintf(stderr, "\nunit: "fmt"\n", (a1), (a2)); \ } while (0) #endif jmp_buf fatal_jbuf; int fatal_expected; char *fatal_string = NULL; int fatal_code; EXPORTED void fatal(const char *s, int code) { if (fatal_expected) { if (verbose) { log1("fatal(%s)", s); } fatal_expected = 0; fatal_string = xstrdupnull(s); fatal_code = code; longjmp(fatal_jbuf, code); } else { log1("fatal(%s)", s); exit(1); } } /* Each test gets a maximum of 20 seconds. */ #define TEST_TIMEOUT_MS (20*1000) static jmp_buf jbuf; static const char *code; static enum { IDLE, INTEST, INFIXTURE } running = IDLE; static struct cunit_param *current_params; void exit(int status) { switch (running) { case IDLE: break; case INTEST: log2("code under test (%s) exited with status %d", code, status); running = IDLE; CU_FAIL_FATAL("Code under test exited"); break; case INFIXTURE: log2("fixture code (%s) exited with status %d", code, status); running = IDLE; longjmp(jbuf, status); break; } /* had atexit() handlers? stiff! */ _exit(status); } static void handle_timeout(void) { switch (running) { case INTEST: log1("code under test (%s) timed out", code); running = IDLE; CU_FAIL_FATAL("Code under test timed out"); break; case INFIXTURE: log1("fixture code (%s) timed out", code); running = IDLE; longjmp(jbuf, -1); break; default: log1("unexpected timeout running=%d", running); _exit(1); } } void __cunit_wrap_test(const char *name, void (*fn)(void)) { code = name; running = INTEST; if (timeouts_flag && timeout_begin(TEST_TIMEOUT_MS) < 0) exit(1); fn(); if (timeouts_flag && timeout_end() < 0) exit(1); running = IDLE; } int __cunit_wrap_fixture(const char *name, int (*fn)(void)) { int r = setjmp(jbuf); if (r) return r; code = name; running = INFIXTURE; if (timeouts_flag && timeout_begin(TEST_TIMEOUT_MS) < 0) exit(1); r = fn(); if (timeouts_flag && timeout_end() < 0) exit(1); running = IDLE; return r; } static void describe_params(const struct cunit_param *params, char *buf, int maxlen) { const struct cunit_param *p; int n; if (maxlen <= 4) return; if (!params || !params->name) return; for (p = params ; p->name ; p++) { n = snprintf(buf, maxlen, "%s%s=%s", (p == params ? "" : ","), p->name, p->values[p->idx]); if (n >= maxlen) { /* truncated */ strcpy(buf+maxlen-4, "..."); return; } buf += n; maxlen -= n; } } static void params_assign(struct cunit_param *params) { struct cunit_param *p; for (p = params ; p->name ; p++) *(p->variable) = p->values[p->idx]; if (verbose) { char buf[1024]; buf[0] = '\0'; describe_params(params, buf, sizeof(buf)); fprintf(stderr, "[%s] ", buf); fflush(stderr); } } void __cunit_params_begin(struct cunit_param *params) { struct cunit_param *p; if (!params || !params[0].name) return; if (!params[0].values) { /* first call: split the original value of the * variable up into the ->values[] array */ for (p = params ; p->name ; p++) { char *v; static const char sep[] = ","; p->freeme1 = xstrdup(*(p->variable)); for (v = strtok(p->freeme1, sep) ; v ; v = strtok(NULL, sep)) { p->values = (p->nvalues ? xrealloc(p->values, sizeof(char*) * (p->nvalues+1)) : xmalloc(sizeof(char *))); p->values[p->nvalues++] = v; } } } for (p = params ; p->name ; p++) p->idx = 0; params_assign(params); current_params = params; } int __cunit_params_next(struct cunit_param *params) { struct cunit_param *p; if (!params || !params[0].name) return 0; for (p = params ; p->name ; p++) { if (++p->idx < p->nvalues) break; p->idx = 0; } if (!p->name) return 0; /* incremented off the end */ params_assign(params); return 1; } void __cunit_params_end(void) { current_params = NULL; } CU_BOOL CU_assertFormatImplementation( CU_BOOL bValue, unsigned int uiLine, char strFile[], char strFunction[], CU_BOOL bFatal, char strConditionFormat[], ...) { va_list args; char buf[1024]; va_start(args, strConditionFormat); vsnprintf(buf, sizeof(buf), strConditionFormat, args); va_end(args); if (current_params) { strncat(buf, " [", sizeof(buf)-strlen(buf)-1); describe_params(current_params, buf+strlen(buf), sizeof(buf)-strlen(buf)-1); strncat(buf, "]", sizeof(buf)-strlen(buf)-1); buf[sizeof(buf)-1] = '\0'; } if (verbose > 1 && bValue) fprintf(stderr, " %s:%u %s\n", strFile, uiLine, buf); return CU_assertImplementation(bValue, uiLine, buf, strFile, strFunction, bFatal); } EXPORTED void config_read_string(const char *s) { char *fname = xstrdup("/tmp/cyrus-cunit-configXXXXXX"); int fd = mkstemp(fname); retry_write(fd, s, strlen(s)); config_reset(); config_read(fname, 0); xunlink(fname); free(fname); close(fd); } static void run_tests(void) { int i; CU_Suite *suite; CU_Test *test; CU_ErrorCode err; char *testname; char suitename[256]; /* Setup to catch long-running tests. This seems to be * particularly a problem on CentOS 5.5. */ if (timeouts_flag && timeout_init(handle_timeout) < 0) exit(1); if (xml_flag) { if (num_testspecs == 0) { /* not specified: run all tests in order listed */ CU_automated_run_tests(); if (timeouts_flag) timeout_fini(); return; } fprintf(stderr, "unit: test specifications not " "supported in XML mode, sorry\n"); exit(1); } if (verbose) CU_basic_set_mode(CU_BRM_VERBOSE); if (num_testspecs == 0) { /* not specified: run all tests in order listed */ err = CU_basic_run_tests(); running = IDLE; /* Just In Case */ if (timeouts_flag) timeout_fini(); if (err != CUE_SUCCESS || CU_get_run_summary()->nAssertsFailed) exit(1); return; } /* * Run the specified suites and/or tests. * * bail on the first failure */ for (i = 0 ; i < num_testspecs ; i++) { xstrncpy(suitename, testspecs[i], sizeof(suitename)); if ((testname = strchr(suitename, ':')) != NULL) { *testname++ = '\0'; if (*testname == '\0') testname = NULL; } suite = CU_get_suite_by_name(suitename, CU_get_registry()); if (suite == NULL) { fprintf(stderr, "unit: no such suite \"%s\"\n", suitename); exit(1); } if (testname == NULL) { err = CU_basic_run_suite(suite); running = IDLE; /* Just In Case */ } else { /* run the named test in the named suite */ test = CU_get_test_by_name(testname, suite); if (test == NULL) { fprintf(stderr, "unit: no such test \"%s\" in suite \"%s\"\n", testname, suitename); exit(1); } err = CU_basic_run_test(suite, test); running = IDLE; /* Just In Case */ } if (err != CUE_SUCCESS || CU_get_run_summary()->nAssertsFailed) exit(1); } if (timeouts_flag) timeout_fini(); } static void list_tests(void) { CU_Suite *suite; CU_Test *test; for (suite = CU_get_registry()->pSuite ; suite != NULL ; suite = suite->pNext) { for (test = suite->pTest ; test != NULL ; test = test->pNext) { printf("%s:%s\n", suite->pName, test->pName); } } } static void usage(int ec) __attribute__((noreturn)); static void usage(int ec) { static const char usage_str[] = "Usage: cunit/unit [options] [suite|suite:test ...]\n" "options are:\n" " -l list all tests\n" " -t disable per-test timeouts\n" " -v be more verbose\n" " -h print this message\n" ; fputs(usage_str, stderr); fflush(stderr); exit(ec); } static void parse_args(int argc, char **argv) { int c; while ((c = getopt(argc, argv, "hltvx")) > 0) { switch (c) { case 'h': usage(0); break; case 'l': mode = LIST; break; case 't': timeouts_flag = 0; break; case 'v': verbose++; break; case 'x': xml_flag = 1; break; case '?': usage(1); exit(1); } } num_testspecs = argc - optind; testspecs = (const char **)(argv + optind); } int main(int argc, char **argv) { CU_initialize_registry(); register_cunit_suites(); parse_args(argc, argv); switch (mode) { case RUN: run_tests(); break; case LIST: list_tests(); break; } return 0; }
341fb2cad73f68e6613c2ff3332fab0dc21af234
7f523c407d45d116860eff67f079e807f2b53339
/src/third_party/capstone/cstool/cstool_evm.c
692a3f0a13cf54a66cfc0f17651e9d35df523126
[ "MIT", "NCSA", "BSD-3-Clause" ]
permissive
0vercl0k/rp
a352c96bfe3715eb9ce8c5942831123e65289dac
b24e7f58a594aaf0ce3771745bf06862f6ecc074
refs/heads/master
2023-08-30T08:03:14.842828
2023-08-09T00:41:00
2023-08-09T00:41:00
3,554,173
1,557
239
MIT
2023-08-09T00:41:02
2012-02-26T19:26:33
C++
UTF-8
C
false
false
524
c
cstool_evm.c
#include <stdio.h> #include <stdlib.h> #include <capstone/capstone.h> void print_string_hex(char *comment, unsigned char *str, size_t len); void print_insn_detail_evm(csh handle, cs_insn *ins) { cs_evm *evm; // detail can be NULL on "data" instruction if SKIPDATA option is turned ON if (ins->detail == NULL) return; evm = &(ins->detail->evm); if (evm->pop) printf("\tPop: %u\n", evm->pop); if (evm->push) printf("\tPush: %u\n", evm->push); if (evm->fee) printf("\tGas fee: %u\n", evm->fee); }
5ccdc6c4b5845461dae616aee26231ec3df91924
f52985c418a5568ce95318b8f26c8acd6ddca479
/src/tests/itests/iotc_itest_connect_error.h
7b8188573911def5ba74307c5f29dd3b4e19608f
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
GoogleCloudPlatform/iot-device-sdk-embedded-c
4de660b0921cff59489d7886d212b5d28057860c
8ba008d476d4ab1baae812db522302009fdbb7e6
refs/heads/master
2023-09-02T12:48:33.555549
2023-03-07T17:48:59
2023-03-07T17:48:59
153,112,323
268
98
NOASSERTION
2023-03-07T17:49:01
2018-10-15T12:52:18
C
UTF-8
C
false
false
3,900
h
iotc_itest_connect_error.h
/* Copyright 2018-2020 Google LLC * * This is part of the Google Cloud IoT Device SDK for Embedded C. * It is licensed under the BSD 3-Clause license; you may not use this file * except in compliance with the License. * * You may obtain a copy of the License at: * https://opensource.org/licenses/BSD-3-Clause * * 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 __IOTC_ITEST_CONNECT_ERROR_H__ #define __IOTC_ITEST_CONNECT_ERROR_H__ #include "iotc_itest_helpers.h" extern int iotc_itest_connect_error_setup(void** fixture_void); extern int iotc_itest_connect_error_teardown(void** fixture_void); extern void iotc_itest_test_valid_flow__call_connect_function_twice_in_a_row__second_call_returns_error( void** state); extern void iotc_itest_test_valid_flow__call_connect_function_twice__second_call_returns_error( void** state); extern void iotc_itest_test_valid_flow__call_is_context_connected_on_connecting_context__call_returns_false( void** state); extern void iotc_itest_test_valid_flow__call_is_context_connected_on_connected_context__call_returns_true( void** state); extern void iotc_itest_test_valid_flow__call_is_context_connected_on_disconnecting_context__call_returns_false( void** state); extern void iotc_itest_test_valid_flow__call_is_context_connected_on_disconnected_context__call_returns_false( void** state); extern void iotc_itest_test_valid_flow__call_disconnect_twice_on_connected_context__second_call_should_return_error( void** state); extern void iotc_itest_test_valid_flow__call_connect_function_then_disconnect_without_making_a_connection__shutdown_should_unregister_connect( void** state); #ifdef IOTC_MOCK_TEST_PREPROCESSOR_RUN struct CMUnitTest iotc_itests_connect_error[] = { cmocka_unit_test_setup_teardown( iotc_itest_test_valid_flow__call_connect_function_twice_in_a_row__second_call_returns_error, iotc_itest_connect_error_setup, iotc_itest_connect_error_teardown), cmocka_unit_test_setup_teardown( iotc_itest_test_valid_flow__call_connect_function_twice__second_call_returns_error, iotc_itest_connect_error_setup, iotc_itest_connect_error_teardown), cmocka_unit_test_setup_teardown( iotc_itest_test_valid_flow__call_disconnect_twice_on_connected_context__second_call_should_return_error, iotc_itest_connect_error_setup, iotc_itest_connect_error_teardown), cmocka_unit_test_setup_teardown( iotc_itest_test_valid_flow__call_connect_function_then_disconnect_without_making_a_connection__shutdown_should_unregister_connect, iotc_itest_connect_error_setup, iotc_itest_connect_error_teardown), cmocka_unit_test_setup_teardown( iotc_itest_test_valid_flow__call_is_context_connected_on_connecting_context__call_returns_false, iotc_itest_connect_error_setup, iotc_itest_connect_error_teardown), cmocka_unit_test_setup_teardown( iotc_itest_test_valid_flow__call_is_context_connected_on_connected_context__call_returns_true, iotc_itest_connect_error_setup, iotc_itest_connect_error_teardown), cmocka_unit_test_setup_teardown( iotc_itest_test_valid_flow__call_is_context_connected_on_disconnecting_context__call_returns_false, iotc_itest_connect_error_setup, iotc_itest_connect_error_teardown), cmocka_unit_test_setup_teardown( iotc_itest_test_valid_flow__call_is_context_connected_on_disconnected_context__call_returns_false, iotc_itest_connect_error_setup, iotc_itest_connect_error_teardown), }; #endif /* IOTC_MOCK_TEST_PREPROCESSOR_RUN */ #endif /* __IOTC_ITEST_CONNECT_ERROR_H__ */
d052a239c964ada42096a4e2478e4c8e04f242eb
e7e2ee02a1cd3e0229346855c9aa6d931e3ca1c4
/src/config_cyaml_config.h
5a96e81b2da6499e5f963d18281406a92b3afe89
[ "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
836
h
config_cyaml_config.h
#ifndef CACHEGRAND_CONFIG_CYAML_CONFIG_H #define CACHEGRAND_CONFIG_CYAML_CONFIG_H #ifdef __cplusplus extern "C" { #endif extern void config_internal_cyaml_log( cyaml_log_t level_cyaml, __attribute__((unused)) void *ctx, const char *fmt, va_list args); extern void* config_internal_cyaml_malloc( void *ctx, void *ptr, size_t size); extern cyaml_err_t config_internal_cyaml_load( config_t** config, char* config_path, cyaml_config_t* cyaml_config, cyaml_schema_value_t* schema); extern void config_internal_cyaml_free( config_t* config, cyaml_config_t* cyaml_config, cyaml_schema_value_t* schema); cyaml_config_t* config_cyaml_config_get_global(); #ifdef __cplusplus } #endif #endif //CACHEGRAND_CONFIG_CYAML_CONFIG_H
ba6a5f3bef87db24a1dace72cdf737505bab29b8
3c883e1084f0a61e558c2d210bb1b4ae8a5e6a06
/third_party/nvxs-1.0.2/CLAPACK/TESTING/LIN/clatsy.c
aa0da7550911eee9a842f3911989c95b9c0a04c9
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "Python-2.0", "BSD-3-Clause" ]
permissive
nya3jp/python-animeface
7e48aa333c9f365a80acdf43e5d516edc8d0b189
15caf8b1ca29847f0dceb54e4b91c77726c4111c
refs/heads/main
2022-04-29T20:17:01.198810
2022-04-04T10:17:59
2022-04-04T10:17:59
10,998,381
150
14
Apache-2.0
2022-04-03T07:18:40
2013-06-27T14:06:08
C
UTF-8
C
false
false
11,116
c
clatsy.c
#include "f2c.h" #include "blaswrap.h" /* Table of constant values */ static integer c__5 = 5; static integer c__2 = 2; /* Subroutine */ int clatsy_(char *uplo, integer *n, complex *x, integer *ldx, integer *iseed) { /* System generated locals */ integer x_dim1, x_offset, i__1, i__2, i__3; complex q__1, q__2, q__3; /* Builtin functions */ double sqrt(doublereal), c_abs(complex *); /* Local variables */ complex a, b, c__; integer i__, j; complex r__; integer n5; real beta, alpha, alpha3; extern /* Complex */ VOID clarnd_(complex *, integer *, integer *); /* -- LAPACK auxiliary test routine (version 3.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ /* November 2006 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* CLATSY generates a special test matrix for the complex symmetric */ /* (indefinite) factorization. The pivot blocks of the generated matrix */ /* will be in the following order: */ /* 2x2 pivot block, non diagonalizable */ /* 1x1 pivot block */ /* 2x2 pivot block, diagonalizable */ /* (cycle repeats) */ /* A row interchange is required for each non-diagonalizable 2x2 block. */ /* Arguments */ /* ========= */ /* UPLO (input) CHARACTER */ /* Specifies whether the generated matrix is to be upper or */ /* lower triangular. */ /* = 'U': Upper triangular */ /* = 'L': Lower triangular */ /* N (input) INTEGER */ /* The dimension of the matrix to be generated. */ /* X (output) COMPLEX array, dimension (LDX,N) */ /* The generated matrix, consisting of 3x3 and 2x2 diagonal */ /* blocks which result in the pivot sequence given above. */ /* The matrix outside of these diagonal blocks is zero. */ /* LDX (input) INTEGER */ /* The leading dimension of the array X. */ /* ISEED (input/output) INTEGER array, dimension (4) */ /* On entry, the seed for the random number generator. The last */ /* of the four integers must be odd. (modified on exit) */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Initialize constants */ /* Parameter adjustments */ x_dim1 = *ldx; x_offset = 1 + x_dim1; x -= x_offset; --iseed; /* Function Body */ alpha = (sqrt(17.f) + 1.f) / 8.f; beta = alpha - .001f; alpha3 = alpha * alpha * alpha; /* UPLO = 'U': Upper triangular storage */ if (*(unsigned char *)uplo == 'U') { /* Fill the upper triangle of the matrix with zeros. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * x_dim1; x[i__3].r = 0.f, x[i__3].i = 0.f; /* L10: */ } /* L20: */ } n5 = *n / 5; n5 = *n - n5 * 5 + 1; i__1 = n5; for (i__ = *n; i__ >= i__1; i__ += -5) { clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = alpha3 * q__2.r, q__1.i = alpha3 * q__2.i; a.r = q__1.r, a.i = q__1.i; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = q__2.r / alpha, q__1.i = q__2.i / alpha; b.r = q__1.r, b.i = q__1.i; q__3.r = b.r * 2.f, q__3.i = b.i * 2.f; q__2.r = q__3.r * 0.f - q__3.i * 1.f, q__2.i = q__3.r * 1.f + q__3.i * 0.f; q__1.r = a.r - q__2.r, q__1.i = a.i - q__2.i; c__.r = q__1.r, c__.i = q__1.i; q__1.r = c__.r / beta, q__1.i = c__.i / beta; r__.r = q__1.r, r__.i = q__1.i; i__2 = i__ + i__ * x_dim1; x[i__2].r = a.r, x[i__2].i = a.i; i__2 = i__ - 2 + i__ * x_dim1; x[i__2].r = b.r, x[i__2].i = b.i; i__2 = i__ - 2 + (i__ - 1) * x_dim1; x[i__2].r = r__.r, x[i__2].i = r__.i; i__2 = i__ - 2 + (i__ - 2) * x_dim1; x[i__2].r = c__.r, x[i__2].i = c__.i; i__2 = i__ - 1 + (i__ - 1) * x_dim1; clarnd_(&q__1, &c__2, &iseed[1]); x[i__2].r = q__1.r, x[i__2].i = q__1.i; i__2 = i__ - 3 + (i__ - 3) * x_dim1; clarnd_(&q__1, &c__2, &iseed[1]); x[i__2].r = q__1.r, x[i__2].i = q__1.i; i__2 = i__ - 4 + (i__ - 4) * x_dim1; clarnd_(&q__1, &c__2, &iseed[1]); x[i__2].r = q__1.r, x[i__2].i = q__1.i; if (c_abs(&x[i__ - 3 + (i__ - 3) * x_dim1]) > c_abs(&x[i__ - 4 + ( i__ - 4) * x_dim1])) { i__2 = i__ - 4 + (i__ - 3) * x_dim1; i__3 = i__ - 3 + (i__ - 3) * x_dim1; q__1.r = x[i__3].r * 2.f, q__1.i = x[i__3].i * 2.f; x[i__2].r = q__1.r, x[i__2].i = q__1.i; } else { i__2 = i__ - 4 + (i__ - 3) * x_dim1; i__3 = i__ - 4 + (i__ - 4) * x_dim1; q__1.r = x[i__3].r * 2.f, q__1.i = x[i__3].i * 2.f; x[i__2].r = q__1.r, x[i__2].i = q__1.i; } /* L30: */ } /* Clean-up for N not a multiple of 5. */ i__ = n5 - 1; if (i__ > 2) { clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = alpha3 * q__2.r, q__1.i = alpha3 * q__2.i; a.r = q__1.r, a.i = q__1.i; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = q__2.r / alpha, q__1.i = q__2.i / alpha; b.r = q__1.r, b.i = q__1.i; q__3.r = b.r * 2.f, q__3.i = b.i * 2.f; q__2.r = q__3.r * 0.f - q__3.i * 1.f, q__2.i = q__3.r * 1.f + q__3.i * 0.f; q__1.r = a.r - q__2.r, q__1.i = a.i - q__2.i; c__.r = q__1.r, c__.i = q__1.i; q__1.r = c__.r / beta, q__1.i = c__.i / beta; r__.r = q__1.r, r__.i = q__1.i; i__1 = i__ + i__ * x_dim1; x[i__1].r = a.r, x[i__1].i = a.i; i__1 = i__ - 2 + i__ * x_dim1; x[i__1].r = b.r, x[i__1].i = b.i; i__1 = i__ - 2 + (i__ - 1) * x_dim1; x[i__1].r = r__.r, x[i__1].i = r__.i; i__1 = i__ - 2 + (i__ - 2) * x_dim1; x[i__1].r = c__.r, x[i__1].i = c__.i; i__1 = i__ - 1 + (i__ - 1) * x_dim1; clarnd_(&q__1, &c__2, &iseed[1]); x[i__1].r = q__1.r, x[i__1].i = q__1.i; i__ += -3; } if (i__ > 1) { i__1 = i__ + i__ * x_dim1; clarnd_(&q__1, &c__2, &iseed[1]); x[i__1].r = q__1.r, x[i__1].i = q__1.i; i__1 = i__ - 1 + (i__ - 1) * x_dim1; clarnd_(&q__1, &c__2, &iseed[1]); x[i__1].r = q__1.r, x[i__1].i = q__1.i; if (c_abs(&x[i__ + i__ * x_dim1]) > c_abs(&x[i__ - 1 + (i__ - 1) * x_dim1])) { i__1 = i__ - 1 + i__ * x_dim1; i__2 = i__ + i__ * x_dim1; q__1.r = x[i__2].r * 2.f, q__1.i = x[i__2].i * 2.f; x[i__1].r = q__1.r, x[i__1].i = q__1.i; } else { i__1 = i__ - 1 + i__ * x_dim1; i__2 = i__ - 1 + (i__ - 1) * x_dim1; q__1.r = x[i__2].r * 2.f, q__1.i = x[i__2].i * 2.f; x[i__1].r = q__1.r, x[i__1].i = q__1.i; } i__ += -2; } else if (i__ == 1) { i__1 = i__ + i__ * x_dim1; clarnd_(&q__1, &c__2, &iseed[1]); x[i__1].r = q__1.r, x[i__1].i = q__1.i; --i__; } /* UPLO = 'L': Lower triangular storage */ } else { /* Fill the lower triangle of the matrix with zeros. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * x_dim1; x[i__3].r = 0.f, x[i__3].i = 0.f; /* L40: */ } /* L50: */ } n5 = *n / 5; n5 *= 5; i__1 = n5; for (i__ = 1; i__ <= i__1; i__ += 5) { clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = alpha3 * q__2.r, q__1.i = alpha3 * q__2.i; a.r = q__1.r, a.i = q__1.i; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = q__2.r / alpha, q__1.i = q__2.i / alpha; b.r = q__1.r, b.i = q__1.i; q__3.r = b.r * 2.f, q__3.i = b.i * 2.f; q__2.r = q__3.r * 0.f - q__3.i * 1.f, q__2.i = q__3.r * 1.f + q__3.i * 0.f; q__1.r = a.r - q__2.r, q__1.i = a.i - q__2.i; c__.r = q__1.r, c__.i = q__1.i; q__1.r = c__.r / beta, q__1.i = c__.i / beta; r__.r = q__1.r, r__.i = q__1.i; i__2 = i__ + i__ * x_dim1; x[i__2].r = a.r, x[i__2].i = a.i; i__2 = i__ + 2 + i__ * x_dim1; x[i__2].r = b.r, x[i__2].i = b.i; i__2 = i__ + 2 + (i__ + 1) * x_dim1; x[i__2].r = r__.r, x[i__2].i = r__.i; i__2 = i__ + 2 + (i__ + 2) * x_dim1; x[i__2].r = c__.r, x[i__2].i = c__.i; i__2 = i__ + 1 + (i__ + 1) * x_dim1; clarnd_(&q__1, &c__2, &iseed[1]); x[i__2].r = q__1.r, x[i__2].i = q__1.i; i__2 = i__ + 3 + (i__ + 3) * x_dim1; clarnd_(&q__1, &c__2, &iseed[1]); x[i__2].r = q__1.r, x[i__2].i = q__1.i; i__2 = i__ + 4 + (i__ + 4) * x_dim1; clarnd_(&q__1, &c__2, &iseed[1]); x[i__2].r = q__1.r, x[i__2].i = q__1.i; if (c_abs(&x[i__ + 3 + (i__ + 3) * x_dim1]) > c_abs(&x[i__ + 4 + ( i__ + 4) * x_dim1])) { i__2 = i__ + 4 + (i__ + 3) * x_dim1; i__3 = i__ + 3 + (i__ + 3) * x_dim1; q__1.r = x[i__3].r * 2.f, q__1.i = x[i__3].i * 2.f; x[i__2].r = q__1.r, x[i__2].i = q__1.i; } else { i__2 = i__ + 4 + (i__ + 3) * x_dim1; i__3 = i__ + 4 + (i__ + 4) * x_dim1; q__1.r = x[i__3].r * 2.f, q__1.i = x[i__3].i * 2.f; x[i__2].r = q__1.r, x[i__2].i = q__1.i; } /* L60: */ } /* Clean-up for N not a multiple of 5. */ i__ = n5 + 1; if (i__ < *n - 1) { clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = alpha3 * q__2.r, q__1.i = alpha3 * q__2.i; a.r = q__1.r, a.i = q__1.i; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = q__2.r / alpha, q__1.i = q__2.i / alpha; b.r = q__1.r, b.i = q__1.i; q__3.r = b.r * 2.f, q__3.i = b.i * 2.f; q__2.r = q__3.r * 0.f - q__3.i * 1.f, q__2.i = q__3.r * 1.f + q__3.i * 0.f; q__1.r = a.r - q__2.r, q__1.i = a.i - q__2.i; c__.r = q__1.r, c__.i = q__1.i; q__1.r = c__.r / beta, q__1.i = c__.i / beta; r__.r = q__1.r, r__.i = q__1.i; i__1 = i__ + i__ * x_dim1; x[i__1].r = a.r, x[i__1].i = a.i; i__1 = i__ + 2 + i__ * x_dim1; x[i__1].r = b.r, x[i__1].i = b.i; i__1 = i__ + 2 + (i__ + 1) * x_dim1; x[i__1].r = r__.r, x[i__1].i = r__.i; i__1 = i__ + 2 + (i__ + 2) * x_dim1; x[i__1].r = c__.r, x[i__1].i = c__.i; i__1 = i__ + 1 + (i__ + 1) * x_dim1; clarnd_(&q__1, &c__2, &iseed[1]); x[i__1].r = q__1.r, x[i__1].i = q__1.i; i__ += 3; } if (i__ < *n) { i__1 = i__ + i__ * x_dim1; clarnd_(&q__1, &c__2, &iseed[1]); x[i__1].r = q__1.r, x[i__1].i = q__1.i; i__1 = i__ + 1 + (i__ + 1) * x_dim1; clarnd_(&q__1, &c__2, &iseed[1]); x[i__1].r = q__1.r, x[i__1].i = q__1.i; if (c_abs(&x[i__ + i__ * x_dim1]) > c_abs(&x[i__ + 1 + (i__ + 1) * x_dim1])) { i__1 = i__ + 1 + i__ * x_dim1; i__2 = i__ + i__ * x_dim1; q__1.r = x[i__2].r * 2.f, q__1.i = x[i__2].i * 2.f; x[i__1].r = q__1.r, x[i__1].i = q__1.i; } else { i__1 = i__ + 1 + i__ * x_dim1; i__2 = i__ + 1 + (i__ + 1) * x_dim1; q__1.r = x[i__2].r * 2.f, q__1.i = x[i__2].i * 2.f; x[i__1].r = q__1.r, x[i__1].i = q__1.i; } i__ += 2; } else if (i__ == *n) { i__1 = i__ + i__ * x_dim1; clarnd_(&q__1, &c__2, &iseed[1]); x[i__1].r = q__1.r, x[i__1].i = q__1.i; ++i__; } } return 0; /* End of CLATSY */ } /* clatsy_ */
4f05f3e7e5cedd469abf227e30a3588eec5fef6d
010279e2ba272d09e9d2c4e903722e5faba2cf7a
/contrib/python/Pillow/py2/libImaging/QuantHash.c
3fcbf3c0263ec7d1dc9775340c5772452facde26
[ "Apache-2.0", "LicenseRef-scancode-secret-labs-2011" ]
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
6,686
c
QuantHash.c
/* * The Python Imaging Library * $Id$ * * hash tables used by the image quantizer * * history: * 98-09-10 tjs Contributed * 98-12-29 fl Added to PIL 1.0b1 * * Written by Toby J Sargeant <tjs@longford.cs.monash.edu.au>. * * Copyright (c) 1998 by Toby J Sargeant * Copyright (c) 1998 by Secret Labs AB * * See the README file for information on usage and redistribution. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "QuantHash.h" typedef struct _HashNode { struct _HashNode *next; HashKey_t key; HashVal_t value; } HashNode; struct _HashTable { HashNode **table; uint32_t length; uint32_t count; HashFunc hashFunc; HashCmpFunc cmpFunc; void *userData; }; #define MIN_LENGTH 11 #define RESIZE_FACTOR 3 static int _hashtable_insert_node(HashTable *,HashNode *,int,int,CollisionFunc); HashTable *hashtable_new(HashFunc hf,HashCmpFunc cf) { HashTable *h; h=malloc(sizeof(HashTable)); if (!h) { return NULL; } h->hashFunc=hf; h->cmpFunc=cf; h->length=MIN_LENGTH; h->count=0; h->userData=NULL; h->table=malloc(sizeof(HashNode *)*h->length); if (!h->table) { free(h); return NULL; } memset (h->table,0,sizeof(HashNode *)*h->length); return h; } static uint32_t _findPrime(uint32_t start,int dir) { static int unit[]={0,1,0,1,0,0,0,1,0,1,0,1,0,1,0,0}; uint32_t t; while (start>1) { if (!unit[start&0x0f]) { start+=dir; continue; } for (t=2;t<sqrt((double)start);t++) { if (!start%t) break; } if (t>=sqrt((double)start)) { break; } start+=dir; } return start; } static void _hashtable_rehash(HashTable *h,CollisionFunc cf,uint32_t newSize) { HashNode **oldTable=h->table; uint32_t i; HashNode *n,*nn; uint32_t oldSize; oldSize=h->length; h->table=malloc(sizeof(HashNode *)*newSize); if (!h->table) { h->table=oldTable; return; } h->length=newSize; h->count=0; memset (h->table,0,sizeof(HashNode *)*h->length); for (i=0;i<oldSize;i++) { for (n=oldTable[i];n;n=nn) { nn=n->next; _hashtable_insert_node(h,n,0,0,cf); } } free(oldTable); } static void _hashtable_resize(HashTable *h) { uint32_t newSize; uint32_t oldSize; oldSize=h->length; newSize=oldSize; if (h->count*RESIZE_FACTOR<h->length) { newSize=_findPrime(h->length/2-1,-1); } else if (h->length*RESIZE_FACTOR<h->count) { newSize=_findPrime(h->length*2+1,+1); } if (newSize<MIN_LENGTH) { newSize=oldSize; } if (newSize!=oldSize) { _hashtable_rehash(h,NULL,newSize); } } static int _hashtable_insert_node(HashTable *h,HashNode *node,int resize,int update,CollisionFunc cf) { uint32_t hash=h->hashFunc(h,node->key)%h->length; HashNode **n,*nv; int i; for (n=&(h->table[hash]);*n;n=&((*n)->next)) { nv=*n; i=h->cmpFunc(h,nv->key,node->key); if (!i) { if (cf) { nv->key=node->key; cf(h,&(nv->key),&(nv->value),node->key,node->value); free(node); return 1; } else { nv->key=node->key; nv->value=node->value; free(node); return 1; } } else if (i>0) { break; } } if (!update) { node->next=*n; *n=node; h->count++; if (resize) _hashtable_resize(h); return 1; } else { return 0; } } static int _hashtable_insert(HashTable *h,HashKey_t key,HashVal_t val,int resize,int update) { HashNode **n,*nv; HashNode *t; int i; uint32_t hash=h->hashFunc(h,key)%h->length; for (n=&(h->table[hash]);*n;n=&((*n)->next)) { nv=*n; i=h->cmpFunc(h,nv->key,key); if (!i) { nv->value=val; return 1; } else if (i>0) { break; } } if (!update) { t=malloc(sizeof(HashNode)); if (!t) return 0; t->next=*n; *n=t; t->key=key; t->value=val; h->count++; if (resize) _hashtable_resize(h); return 1; } else { return 0; } } int hashtable_insert_or_update_computed(HashTable *h, HashKey_t key, ComputeFunc newFunc, ComputeFunc existsFunc) { HashNode **n,*nv; HashNode *t; int i; uint32_t hash=h->hashFunc(h,key)%h->length; for (n=&(h->table[hash]);*n;n=&((*n)->next)) { nv=*n; i=h->cmpFunc(h,nv->key,key); if (!i) { if (existsFunc) { existsFunc(h,nv->key,&(nv->value)); } else { return 0; } return 1; } else if (i>0) { break; } } t=malloc(sizeof(HashNode)); if (!t) return 0; t->key=key; t->next=*n; *n=t; if (newFunc) { newFunc(h,t->key,&(t->value)); } else { free(t); return 0; } h->count++; _hashtable_resize(h); return 1; } int hashtable_insert(HashTable *h,HashKey_t key,HashVal_t val) { return _hashtable_insert(h,key,val,1,0); } void hashtable_foreach_update(HashTable *h,IteratorUpdateFunc i,void *u) { HashNode *n; uint32_t x; if (h->table) { for (x=0;x<h->length;x++) { for (n=h->table[x];n;n=n->next) { i(h,n->key,&(n->value),u); } } } } void hashtable_foreach(HashTable *h,IteratorFunc i,void *u) { HashNode *n; uint32_t x; if (h->table) { for (x=0;x<h->length;x++) { for (n=h->table[x];n;n=n->next) { i(h,n->key,n->value,u); } } } } void hashtable_free(HashTable *h) { HashNode *n,*nn; uint32_t i; if (h->table) { for (i=0;i<h->length;i++) { for (n=h->table[i];n;n=nn) { nn=n->next; free(n); } } free(h->table); } free(h); } void hashtable_rehash_compute(HashTable *h,CollisionFunc cf) { _hashtable_rehash(h,cf,h->length); } int hashtable_lookup(const HashTable *h,const HashKey_t key,HashVal_t *valp) { uint32_t hash=h->hashFunc(h,key)%h->length; HashNode *n; int i; for (n=h->table[hash];n;n=n->next) { i=h->cmpFunc(h,n->key,key); if (!i) { *valp=n->value; return 1; } else if (i>0) { break; } } return 0; } uint32_t hashtable_get_count(const HashTable *h) { return h->count; } void *hashtable_get_user_data(const HashTable *h) { return h->userData; } void *hashtable_set_user_data(HashTable *h,void *data) { void *r=h->userData; h->userData=data; return r; }
14911bda7d23a627baffda88a23e2f42e14f370a
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/gpu/drm/gma500/mdfld_tpo_vid.c
d8d4170725b293f50cf8d85f68dcc4b1a192463e
[ "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
4,086
c
mdfld_tpo_vid.c
/* * Copyright © 2010 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Authors: * jim liu <jim.liu@intel.com> * Jackie Li<yaodong.li@intel.com> */ #include "mdfld_dsi_dpi.h" static struct drm_display_mode *tpo_vid_get_config_mode(struct drm_device *dev) { struct drm_display_mode *mode; struct drm_psb_private *dev_priv = dev->dev_private; struct oaktrail_timing_info *ti = &dev_priv->gct_data.DTD; bool use_gct = false; mode = kzalloc(sizeof(*mode), GFP_KERNEL); if (!mode) return NULL; if (use_gct) { mode->hdisplay = (ti->hactive_hi << 8) | ti->hactive_lo; mode->vdisplay = (ti->vactive_hi << 8) | ti->vactive_lo; mode->hsync_start = mode->hdisplay + ((ti->hsync_offset_hi << 8) | ti->hsync_offset_lo); mode->hsync_end = mode->hsync_start + ((ti->hsync_pulse_width_hi << 8) | ti->hsync_pulse_width_lo); mode->htotal = mode->hdisplay + ((ti->hblank_hi << 8) | ti->hblank_lo); mode->vsync_start = mode->vdisplay + ((ti->vsync_offset_hi << 8) | ti->vsync_offset_lo); mode->vsync_end = mode->vsync_start + ((ti->vsync_pulse_width_hi << 8) | ti->vsync_pulse_width_lo); mode->vtotal = mode->vdisplay + ((ti->vblank_hi << 8) | ti->vblank_lo); mode->clock = ti->pixel_clock * 10; dev_dbg(dev->dev, "hdisplay is %d\n", mode->hdisplay); dev_dbg(dev->dev, "vdisplay is %d\n", mode->vdisplay); dev_dbg(dev->dev, "HSS is %d\n", mode->hsync_start); dev_dbg(dev->dev, "HSE is %d\n", mode->hsync_end); dev_dbg(dev->dev, "htotal is %d\n", mode->htotal); dev_dbg(dev->dev, "VSS is %d\n", mode->vsync_start); dev_dbg(dev->dev, "VSE is %d\n", mode->vsync_end); dev_dbg(dev->dev, "vtotal is %d\n", mode->vtotal); dev_dbg(dev->dev, "clock is %d\n", mode->clock); } else { mode->hdisplay = 864; mode->vdisplay = 480; mode->hsync_start = 873; mode->hsync_end = 876; mode->htotal = 887; mode->vsync_start = 487; mode->vsync_end = 490; mode->vtotal = 499; mode->clock = 33264; } drm_mode_set_name(mode); drm_mode_set_crtcinfo(mode, 0); mode->type |= DRM_MODE_TYPE_PREFERRED; return mode; } static int tpo_vid_get_panel_info(struct drm_device *dev, int pipe, struct panel_info *pi) { if (!dev || !pi) return -EINVAL; pi->width_mm = TPO_PANEL_WIDTH; pi->height_mm = TPO_PANEL_HEIGHT; return 0; } /*TPO DPI encoder helper funcs*/ static const struct drm_encoder_helper_funcs mdfld_tpo_dpi_encoder_helper_funcs = { .dpms = mdfld_dsi_dpi_dpms, .mode_fixup = mdfld_dsi_dpi_mode_fixup, .prepare = mdfld_dsi_dpi_prepare, .mode_set = mdfld_dsi_dpi_mode_set, .commit = mdfld_dsi_dpi_commit, }; /*TPO DPI encoder funcs*/ static const struct drm_encoder_funcs mdfld_tpo_dpi_encoder_funcs = { .destroy = drm_encoder_cleanup, }; const struct panel_funcs mdfld_tpo_vid_funcs = { .encoder_funcs = &mdfld_tpo_dpi_encoder_funcs, .encoder_helper_funcs = &mdfld_tpo_dpi_encoder_helper_funcs, .get_config_mode = &tpo_vid_get_config_mode, .get_panel_info = tpo_vid_get_panel_info, };
18c5960f1bfaf21fedf125a6910f13f10da90bff
03b2c80dbc41e904b167d504666e27d798da5447
/src/clos_instance.h
db2a50edd5114397f8a87a1f619e5d4689930a03
[ "Unlicense" ]
permissive
nptcl/npt
7c1570b497cdce0b8971cb445fbc04cb500232d3
aa714a2370ac9fa5348c2fc96159b40b9de3de07
refs/heads/master
2023-03-20T09:13:54.669118
2022-07-02T11:17:44
2022-07-02T11:17:44
171,985,905
160
12
Unlicense
2023-03-11T01:36:37
2019-02-22T03:11:34
C
UTF-8
C
false
false
3,399
h
clos_instance.h
#ifndef __CLOS_INSTANCE_HEADER__ #define __CLOS_INSTANCE_HEADER__ #include "execute.h" #include "local.h" #include "typedef.h" #define clos_subclass_p_ _n(clos_subclass_p_) #define clos_subtype_p_ _n(clos_subtype_p_) #define clos_class_p_ _n(clos_class_p_) #define clos_funcallable_p_ _n(clos_funcallable_p_) #define clos_generic_p_ _n(clos_generic_p_) #define clos_method_p_ _n(clos_method_p_) #define clos_define_combination_p_ _n(clos_define_combination_p_) #define clos_define_long_combination_p_ _n(clos_define_long_combination_p_) #define clos_define_short_combination_p_ _n(clos_define_short_combination_p_) #define clos_combination_p_ _n(clos_combination_p_) #define clos_long_combination_p_ _n(clos_long_combination_p_) #define clos_short_combination_p_ _n(clos_short_combination_p_) #define clos_specializer_p_ _n(clos_specializer_p_) #define clos_referenced_p_ _n(clos_referenced_p_) #define clos_built_p_ _n(clos_built_p_) #define funcallp_ _n(funcallp_) #define clos_instance_alloc_ _n(clos_instance_alloc_) #define clos_instance_local_ _n(clos_instance_local_) #define clos_instance_heap_ _n(clos_instance_heap_) #define clos_find_slotname_ _n(clos_find_slotname_) #define clos_precedence_list_redefine_ _n(clos_precedence_list_redefine_) #define clos_precedence_list_ _n(clos_precedence_list_) #define clos_compute_slots_ _n(clos_compute_slots_) #define clos_subclass_p_debug _n(clos_subclass_p_debug) #define clos_subtype_p_debug _n(clos_subtype_p_debug) #define clos_generic_p_debug _n(clos_generic_p_debug) #define clos_method_p_debug _n(clos_method_p_debug) #define clos_define_combination_p_debug _n(clos_define_combination_p_debug) /* check */ int clos_subclass_p_(Execute ptr, addr clos, addr super, int *ret); int clos_subtype_p_(Execute ptr, addr clos, addr super, int *ret); int clos_class_p_(Execute ptr, addr clos, int *ret); int clos_funcallable_p_(Execute ptr, addr clos, int *ret); int clos_generic_p_(Execute ptr, addr clos, int *ret); int clos_method_p_(Execute ptr, addr clos, int *ret); int clos_define_combination_p_(Execute ptr, addr clos, int *ret); int clos_define_long_combination_p_(Execute ptr, addr pos, int *ret); int clos_define_short_combination_p_(Execute ptr, addr pos, int *ret); int clos_combination_p_(Execute ptr, addr pos, int *ret); int clos_long_combination_p_(Execute ptr, addr pos, int *ret); int clos_short_combination_p_(Execute ptr, addr pos, int *ret); int clos_specializer_p_(Execute ptr, addr clos, int *ret); int clos_referenced_p_(addr clos, int *ret); int clos_built_p_(Execute ptr, addr clos, int *ret); int funcallp_(Execute ptr, addr pos, int *ret); /* make-instance */ int clos_instance_alloc_(Execute ptr, LocalRoot local, addr clos, addr *ret); int clos_instance_local_(Execute ptr, addr clos, addr *ret); int clos_instance_heap_(Execute ptr, addr clos, addr *ret); /* interface */ int clos_find_slotname_(Execute ptr, addr slots, size_t size, addr name, int *ret); int clos_precedence_list_redefine_( Execute ptr, addr pos, addr *ret, addr x, addr list); int clos_precedence_list_(Execute ptr, addr pos, addr *ret); int clos_compute_slots_(Execute ptr, addr clos, addr *ret); /* debug */ int clos_subclass_p_debug(addr clos, addr super); int clos_subtype_p_debug(addr clos, addr super); int clos_generic_p_debug(addr clos); int clos_method_p_debug(addr clos); int clos_define_combination_p_debug(addr clos); #endif
efb3dd056b09981f271ee3988acd30544fadcd9a
ecce427678ecff2a93a47f3b1b664202c7d27617
/src/game/behaviors/spawn_star_exit.inc.c
8c5515a3a8c296aac71e76fc6d43d446344b9c58
[]
no_license
sm64pc/sm64ex
ecf37f31b3f7426c4874254660d856030d789714
54cd27ccee45a2403b45f07a00d6043c51149969
refs/heads/nightly
2023-08-11T12:14:34.424168
2023-07-01T11:45:50
2023-07-01T11:45:50
262,091,731
795
238
null
2023-07-01T11:45:51
2020-05-07T15:43:27
C
UTF-8
C
false
false
285
c
spawn_star_exit.inc.c
// spawn_star_exit.c.inc void bhv_ccm_touched_star_spawn_loop(void) { if (gCCMEnteredSlide & 1) { o->oPosY += 100.0f; o->oPosX = 2780.0f; o->oPosZ = 4666.0f; spawn_default_star(2500.0f, -4350.0f, 5750.0f); obj_mark_for_deletion(o); } }
4dab22fa02c34e231bac422e719d63bc4c9137db
821128c7e0c6b41c08474e98dffc9dd5f72b8857
/pacing/pacer_queue.h
712f29c18123f24611827a0851cb277f61ef9f04
[ "MIT" ]
permissive
yuanrongxi/razor
304b9c5d5a9e011f212dbcb8c773f8e4b4133fef
b361d64ca3357226af3d6c9651bc235905066141
refs/heads/master
2023-07-19T07:47:49.092351
2023-07-16T07:17:50
2023-07-16T07:17:50
126,000,077
322
152
MIT
2021-09-07T10:49:37
2018-03-20T10:25:35
C++
GB18030
C
false
false
1,753
h
pacer_queue.h
/*- * Copyright (c) 2017-2018 Razor, Inc. * All rights reserved. * * See the file LICENSE for redistribution information. */ #ifndef __pacer_queue_h_ #define __pacer_queue_h_ #include "cf_platform.h" #include "cf_skiplist.h" #include "cf_list.h" #define k_max_pace_queue_ms 250 /*pacer queue缓冲的最大延迟*/ typedef struct { uint32_t seq; /*通信中的绝对seq,相当于帧的先后顺序,webRTC这块做的非常复杂,做了优先等级,对于视频来说,绝对的SEQ大小表明了先后关系,没有必要做各种等级区分*/ int retrans; /*是否是重传*/ size_t size; /*报文大小*/ int64_t que_ts; /*放入pacer queue的时间戳*/ int sent; /*是否已经发送*/ }packet_event_t; typedef struct { uint32_t max_que_ms; /*pacer可以接受最大的延迟*/ size_t total_size; int64_t oldest_ts; /*最早帧的时间戳*/ skiplist_t* cache; /*按绝对SEQ排队的队列*/ base_list_t* l; /*按时间先后的队列*/ }pacer_queue_t; void pacer_queue_init(pacer_queue_t* que, uint32_t que_ms); void pacer_queue_destroy(pacer_queue_t* que); int pacer_queue_push(pacer_queue_t* que, packet_event_t* ev); /*获取que中最小seq的包,按顺序发出,这样防止出现大范围的抖动*/ packet_event_t* pacer_queue_front(pacer_queue_t* que); void pacer_queue_sent_by_id(pacer_queue_t* que, uint32_t id); void pacer_queue_sent(pacer_queue_t* que, packet_event_t* ev); int pacer_queue_empty(pacer_queue_t* que); size_t pacer_queue_bytes(pacer_queue_t* que); int64_t pacer_queue_oldest(pacer_queue_t* que); /*计算que需要的码率*/ uint32_t pacer_queue_target_bitrate_kbps(pacer_queue_t* que, int64_t now_ts); #endif
f696a364aee717edbe9cc33ffb9413c0396eec3e
a5a7c59b04a1a64fe34653c7970c3cf173f9c1df
/numerics/src/SOCP/soclcp_compute_error.h
a99c5f550f34c2c6d9abdd52d8bbd20fda60eff0
[ "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
2,344
h
soclcp_compute_error.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 SOCLCP_compute_error_H #define SOCLCP_compute_error_H /*!\file soclcp_compute_error.h \brief functions related to error computation for SOCLCP */ #include "NumericsFwd.h" // for SecondOrderConeLinearComplementarityProblem #include "SiconosConfig.h" // for BUILD_AS_CPP // IWYU pragma: keep #if defined(__cplusplus) && !defined(BUILD_AS_CPP) extern "C" { #endif /** Error computation for SOCLCP problem \param problem the structure which defines the SOCLCP \param z vector \param w vector \param tolerance value for error computation \param options \param[in,out] error value \return 0 if ok */ int soclcp_compute_error(SecondOrderConeLinearComplementarityProblem* problem, double *z , double *w, double tolerance, SolverOptions * options, double * error); /** Error computation for one SOCLCP problem \param z vector \param w vector \param dim dimension of the cone \param mu coeficient of friction \param[in,out] error value \param worktmp */ void soclcp_unitary_compute_and_add_error(double z[3] , double w[3], unsigned int dim, double mu, double * error, double * worktmp); /** Error computation for SOCLCP problem \param problem the structure which defines the SOCLCP \param z vector \param w vector \param options \param tolerance value for error computation \param[in,out] error value \return 0 if ok */ int soclcp_compute_error_v(SecondOrderConeLinearComplementarityProblem* problem, double *z , double *w, double tolerance, SolverOptions * options, double * error); #if defined(__cplusplus) && !defined(BUILD_AS_CPP) } #endif #endif
7886015763c2e93cded8df5157040137aed2ca1e
c0bfd93cd7f26a271268e504959256f1e02c6806
/components/wpa_supplicant/src/ap/wpa_auth_ie.h
4999139510ec3b77b71b39e523daa3cc0c7b2f64
[ "Apache-2.0", "BSD-3-Clause" ]
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
1,162
h
wpa_auth_ie.h
/* * hostapd - WPA/RSN IE and KDE definitions * Copyright (c) 2004-2007, Jouni Malinen <j@w1.fi> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #ifndef WPA_AUTH_IE_H #define WPA_AUTH_IE_H struct wpa_eapol_ie_parse { const u8 *wpa_ie; size_t wpa_ie_len; const u8 *rsn_ie; size_t rsn_ie_len; const u8 *pmkid; const u8 *gtk; size_t gtk_len; const u8 *mac_addr; size_t mac_addr_len; #ifdef CONFIG_PEERKEY const u8 *smk; size_t smk_len; const u8 *nonce; size_t nonce_len; const u8 *lifetime; size_t lifetime_len; const u8 *error; size_t error_len; #endif /* CONFIG_PEERKEY */ #ifdef CONFIG_IEEE80211W const u8 *igtk; size_t igtk_len; #endif /* CONFIG_IEEE80211W */ #ifdef CONFIG_IEEE80211R const u8 *mdie; size_t mdie_len; const u8 *ftie; size_t ftie_len; #endif /* CONFIG_IEEE80211R */ }; int wpa_parse_kde_ies(const u8 *buf, size_t len, struct wpa_eapol_ie_parse *ie); u8 * wpa_add_kde(u8 *pos, u32 kde, const u8 *data, size_t data_len, const u8 *data2, size_t data2_len); int wpa_auth_gen_wpa_ie(struct wpa_authenticator *wpa_auth); #endif /* WPA_AUTH_IE_H */
5f325b8a4fea790c1cadb497dee6bae7134ea5fb
fae867d62224cdf27ceb85654525a311fb8c4226
/rp-api/api/src/daisy.h
34af7a88c76f7aaf55b21de17ca0854a3d075d01
[ "BSD-3-Clause" ]
permissive
RedPitaya/RedPitaya
a4a9b0bda0d1806e39b90ee9f3164e2e0dee0ab6
69826707f78c764e5835f3197e61f68ced90f77b
refs/heads/master
2023-09-01T12:25:51.370133
2023-07-26T03:51:31
2023-07-26T03:51:31
17,261,658
447
601
NOASSERTION
2023-07-27T04:07:43
2014-02-27T19:38:52
C
UTF-8
C
false
false
3,426
h
daisy.h
/** * $Id: $ * * @brief Red Pitaya library daisy module interface * * @Author Red Pitaya * * (c) Red Pitaya http://www.redpitaya.com * * This part of code is written in C programming language. * Please visit http://en.wikipedia.org/wiki/C_(programming_language) * for more details on the language used herein. */ #ifndef __DAISY_H #define __DAISY_H #include <stdint.h> #include <stdbool.h> #include "redpitaya/rp.h" #include "rp_hw-profiles.h" // Base daisy address static const int DAISY_BASE_ADDR = 0x00500000; static const int DAISY_BASE_SIZE = 0x20; typedef enum { ZERO = 0, // data is 0 USER = 1, // user data (from logic) CUSTOM = 2, // custom data (from daisy_transmit_t) TRAINING = 3, // training data (0x00FF) LOOPBACK = 4, // transmit received data RANDOM = 5 } daisy_data_source_t; typedef struct daisy_control_s { uint32_t tx_enable: 1; uint32_t rx_enable: 1; uint32_t : 30; // Reserve } daisy_control_t; typedef struct daisy_transmit_s { /* Data source 0 - data is 0 1 - user data (from logic) 2 - custom data (from this register) 3 - training data (0x00FF) 4 - transmit received data (loop back) 5 - random data (for testing) */ uint32_t data_source: 4; uint32_t : 12; uint32_t custom: 16; } daisy_transmit_t; typedef struct daisy_receiver_training_s { uint32_t enable: 1; uint32_t state: 1; uint32_t: 30; } daisy_receiver_training_t; typedef struct daisy_receiver_data_s { uint32_t raw: 16; uint32_t non_zero_data: 16; } daisy_receiver_data_t; typedef struct daisy_testing_control_s { uint32_t reset: 1; // Reset testing conters (error & data) uint32_t: 31; } daisy_testing_control_t; typedef struct daisy_regset_s { daisy_control_t cotrol; // 0x0 **Control** daisy_transmit_t transmit; // 0x4 **Transmitter data selector** daisy_receiver_training_t r_training; // 0x8 **Receiver training** daisy_receiver_data_t r_data; // 0xC **Receiver data** daisy_testing_control_t t_control; // 0x10 **Testing control** uint32_t t_error_counter; // 0x14 **Testing error counter** uint32_t t_data_counter; // 0x18 **Testing data counter** } daisy_regset_t; int daisy_Init(); int daisy_Release(); int daisy_SetTXEnable(bool enable); int daisy_GetTXEnable(bool *state); int daisy_SetRXEnable(bool enable); int daisy_GetRXEnable(bool *state); int daisy_SetDataMode(daisy_data_source_t mode); int daisy_GetDataMode(daisy_data_source_t *mode); int daisy_SetDataCustom(uint16_t data); int daisy_GetDataCustom(uint16_t *data); int daisy_SetReceiverTrainingEnable(bool enable); int daisy_GetReceiverTrainingEnable(bool *state); int daisy_GetReceiverTrainingState(bool *state); int daisy_GetReceiverDataRaw(uint16_t *data); int daisy_GetReceiverNonZeroData(uint16_t *data); int daisy_SetResetTesting(bool reset); int daisy_GetResetTesting(bool *state); int daisy_GetTestingErrorCounter(uint32_t *counter); int daisy_GetTestingDataCounter(uint32_t *counter); #endif //__DAISY_H
d754f4995e3e44ec9c2a9cccb93e1ad352dc60b1
bb38c44037a99d0a12a12d92059678f2faebbc80
/src/include/catalog/pg_inherits_fn.h
3c747c2c547918f76b9d54b4c66478b11319f90e
[ "LicenseRef-scancode-mulanpsl-2.0-en", "LicenseRef-scancode-unknown-license-reference", "PostgreSQL", "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-unicode", "LicenseRef-scancode-warranty-disclaimer", "curl", "GPL-1.0-or-later", "LGPL-2.1-or-later", "LGPL-2.1-only", "CC-BY-4.0", "LicenseRef-scancode-protobuf", "OpenSSL", "LicenseRef-scancode-generic-export-compliance", "X11-distribute-modifications-variant", "LicenseRef-scancode-other-permissive", "MIT", "NCSA", "Python-2.0", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "CC-BY-3.0", "LicenseRef-scancode-other-copyleft", "GPL-2.0-only", "BSL-1.0", "Apache-2.0", "LGPL-2.0-only", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "Zlib" ]
permissive
opengauss-mirror/openGauss-server
a9c5a62908643492347830826c56da49f0942796
310e84631c68c8bf37b004148b66f94064f701e4
refs/heads/master
2023-07-26T19:29:12.495484
2023-07-17T12:23:32
2023-07-17T12:23:32
276,117,477
591
208
MulanPSL-2.0
2023-04-28T12:30:18
2020-06-30T14:08:59
C++
UTF-8
C
false
false
853
h
pg_inherits_fn.h
/* ------------------------------------------------------------------------- * * pg_inherits_fn.h * prototypes for functions in catalog/pg_inherits.c * * * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/include/catalog/pg_inherits_fn.h * * ------------------------------------------------------------------------- */ #ifndef PG_INHERITS_FN_H #define PG_INHERITS_FN_H #include "nodes/pg_list.h" #include "storage/lock/lock.h" extern List *find_inheritance_children(Oid parentrelId, LOCKMODE lockmode); extern List *find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **parents); extern bool has_subclass(Oid relationId); extern bool typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId); #endif /* PG_INHERITS_FN_H */