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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
53583f0d2757bc82f1c8c45ddea6a1fdda18a9d1
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/gd32/risc-v/libraries/GD32VF103_Firmware_Library/RISCV/drivers/n200_timer.h
|
e27acd5fbe0dcaf00eced616c34d6264e884f62a
|
[
"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
| 439
|
h
|
n200_timer.h
|
/* See LICENSE file for licence details */
#ifndef N200_TIMER_H
#define N200_TIMER_H
#define TIMER_MSIP 0xFFC
#define TIMER_MSIP_size 0x4
#define TIMER_MTIMECMP 0x8
#define TIMER_MTIMECMP_size 0x8
#define TIMER_MTIME 0x0
#define TIMER_MTIME_size 0x8
#define TIMER_CTRL_ADDR 0xd1000000
#define TIMER_REG(offset) _REG32(TIMER_CTRL_ADDR, offset)
#define TIMER_FREQ ((uint32_t)SystemCoreClock/4)
#endif
|
8a332914a36dcd0b835f28b948a598b9f701a8ed
|
61be4a7bfc24468a1227ea797150520c83257844
|
/event/TipsField.c
|
a9d59bfa0e81a4535ba5a56545b35357dc9d9c37
|
[] |
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
| 3,371
|
c
|
TipsField.c
|
-------- EventFlow: TipsField --------
Actor: TipsSystemActor
entrypoint: None()
actions: ['Demo_TipsDisplayOK', 'Demo_TipsDisplayNG']
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: []
queries: ['CheckGameDataInt']
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 Arrive_Gerudo() {
if EventSystemActor.CheckGameDataInt({'Value': 0, 'Operator': 'GreaterThan', 'GameDataIntName': 'Location_Gerudo'}) {
Event1:
TipsSystemActor.Demo_TipsDisplayOK({'IsWaitFinish': True})
} else
if EventSystemActor.CheckGameDataInt({'Value': 0, 'Operator': 'GreaterThan', 'GameDataIntName': 'Location_GerudoDesert_Entrance'}) {
goto Event1
} else
if EventSystemActor.CheckGameDataInt({'Value': 0, 'Operator': 'GreaterThan', 'GameDataIntName': 'Location_Oasis'}) {
goto Event1
} else
if EventSystemActor.CheckGameDataInt({'Value': 0, 'Operator': 'GreaterThan', 'GameDataIntName': 'Location_Assassin'}) {
goto Event1
} else
if EventSystemActor.CheckGameDataInt({'Value': 0, 'Operator': 'GreaterThan', 'GameDataIntName': 'Location_GerudoHatago'}) {
goto Event1
} else
if EventSystemActor.CheckGameDataInt({'Value': 0, 'Operator': 'GreaterThan', 'GameDataIntName': 'Location_MapTower04'}) {
goto Event1
} else {
TipsSystemActor.Demo_TipsDisplayNG({'IsWaitFinish': True})
}
}
void Arrive_DeathMountain() {
if EventSystemActor.CheckGameDataInt({'Value': 0, 'Operator': 'GreaterThan', 'GameDataIntName': 'Location_Goron'}) {
Event10:
TipsSystemActor.Demo_TipsDisplayOK({'IsWaitFinish': True})
} else
if EventSystemActor.CheckGameDataInt({'Value': 0, 'Operator': 'GreaterThan', 'GameDataIntName': 'Location_SouthMine'}) {
goto Event10
} else
if EventSystemActor.CheckGameDataInt({'Value': 0, 'Operator': 'GreaterThan', 'GameDataIntName': 'Location_DeathMountain_Entrance'}) {
goto Event10
} else
if EventSystemActor.CheckGameDataInt({'Value': 0, 'Operator': 'GreaterThan', 'GameDataIntName': 'Location_GoronBridge'}) {
goto Event10
} else
if EventSystemActor.CheckGameDataInt({'Value': 0, 'Operator': 'GreaterThan', 'GameDataIntName': 'Location_DeathMountainHatago'}) {
goto Event10
} else
if EventSystemActor.CheckGameDataInt({'Value': 0, 'Operator': 'GreaterThan', 'GameDataIntName': 'Location_MapTower10'}) {
goto Event10
} else {
TipsSystemActor.Demo_TipsDisplayNG({'IsWaitFinish': True})
}
}
void Arrive_Kakariko() {
if EventSystemActor.CheckGameDataInt({'Value': 0, 'Operator': 'GreaterThan', 'GameDataIntName': 'Location_Kakariko'}) {
TipsSystemActor.Demo_TipsDisplayOK({'IsWaitFinish': True})
} else {
TipsSystemActor.Demo_TipsDisplayNG({'IsWaitFinish': True})
}
}
void Arrive_Hateno() {
if EventSystemActor.CheckGameDataInt({'Value': 0, 'Operator': 'GreaterThan', 'GameDataIntName': 'Location_Hateno'}) {
TipsSystemActor.Demo_TipsDisplayOK({'IsWaitFinish': True})
} else {
TipsSystemActor.Demo_TipsDisplayNG({'IsWaitFinish': True})
}
}
|
31cb42522f9fdcdad65147c6b0539b1e31ac7245
|
c72be999abf8848a7d09264ba9ee7bae30f4524a
|
/xme/xme/com/packet.h
|
18ff22ba48784339d815864b217116f4106870aa
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
ipa-rmb/autopnp
|
8399be67c1a3de61e01619dc8677c52728ffd836
|
f25517a093c772a1481bcff3e9da055d4c627954
|
refs/heads/indigo_dev
| 2022-05-05T01:57:05.858437
| 2022-04-29T07:31:42
| 2022-04-29T07:31:42
| 3,398,225
| 144
| 101
| null | 2019-07-08T06:11:13
| 2012-02-09T15:30:28
|
C
|
UTF-8
|
C
| false
| false
| 8,020
|
h
|
packet.h
|
/*
* Copyright (c) 2011-2012, fortiss GmbH.
* Licensed under the Apache License, Version 2.0.
*
* Use, modification and distribution are subject to the terms specified
* in the accompanying license file LICENSE.txt located at the root directory
* of this software distribution. A copy is available at
* http://chromosome.fortiss.org/.
*
* This file is part of CHROMOSOME.
*
* $Id: packet.h 4999 2013-09-06 08:57:49Z gulati $
*/
/**
* \file
* Low-level communication packet format definitions.
*/
#ifndef XME_COM_PACKET_H
#define XME_COM_PACKET_H
/******************************************************************************/
/*** Includes ***/
/******************************************************************************/
#include "xme/core/device.h"
#include "xme/core/topicData.h"
#include <stdint.h>
/******************************************************************************/
/*** Defines ***/
/******************************************************************************/
#define XME_COM_PACKET_HEADER_MAGIC 0xD7
#define XME_COM_PACKET_HEADER_VERSION 0x01
#define XME_COM_PACKET_HEADER_TYPE_LOGINREQUEST 0x01
#define XME_COM_PACKET_HEADER_TYPE_LOGINRESPONSE 0x02
#define XME_COM_PACKET_HEADER_TYPE_SAMPLE 0x03
#define XME_COM_PACKET_INIT(packet, type) \
do { \
(packet).packetHeader.magic = XME_COM_PACKET_HEADER_MAGIC; \
(packet).packetHeader.version = XME_COM_PACKET_HEADER_VERSION; \
(packet).packetHeader.packetType = (type); \
} while (0)
#define XME_COM_PACKET_VALID(packet) \
((XME_COM_PACKET_HEADER_MAGIC == (packet).packetHeader.magic) && (XME_COM_PACKET_HEADER_VERSION == (packet).packetHeader.version))
#define XME_COM_PACKET_TYPE(packet) \
(packet).packetHeader.packetType
/*Following is used when you are using the defined structure*/
/*This dependecncy can be removed. Keeping it for backward compaibility*/
#define XME_COM_PACKET_PAYLOAD(packet) \
(packet).data
/*This is a generic solution of the above macro*/
#define XME_COM_PACKET_SAMPLE_PAYLOAD(packet) \
(void *)(((xme_com_packet_sample_header_t *)packet)+1)
/******************************************************************************/
/*** Type definitions ***/
/******************************************************************************/
/**
* \struct xme_com_packet_header_t
*
* \brief Header packet.
*/
#pragma pack(push, 1)
typedef struct
{
uint8_t magic; ///< Magic byte.
uint8_t version; ///< Protocol version.
uint8_t packetType; ///< Packet type.
} xme_com_packet_header_t;
#pragma pack(pop)
/**
* \struct xme_com_packet_loginRequest_t
*
* \brief Login request packet.
*/
#pragma pack(push, 1)
typedef struct
{
xme_com_packet_header_t packetHeader; ///< Packet header.
xme_core_topic_loginRequestData_t data; ///< Login request data.
} xme_com_packet_loginRequest_t;
#pragma pack(pop)
/**
* \struct xme_com_packet_loginResponse_t
*
* \brief Login response packet.
*/
#pragma pack(push, 1)
typedef struct
{
xme_com_packet_header_t packetHeader; ///< Packet header.
xme_core_topic_loginResponseData_t data; ///< Login response data.
} xme_com_packet_loginResponse_t;
#pragma pack(pop)
#if 0
/**
* \typedef xme_com_packet_requestContext_t
*
* \brief Data that are always transmitted along with a request packet.
*/
#pragma pack(push, 1)
typedef struct
{
xme_core_rr_requestHandle_t localRequestHandle; ///< Request handle (only valid at the request issuer side).
xme_core_rr_requestInstanceHandle_t localRequestInstance; ///< Request instance identifier (only valid at the request issuer side).
uint64_t instanceUserData; // TODO: See ticket #540. The size of this member is currently the size of the largest pointer we support, which is 64 bit. See also comment below in xme_com_packet_responseContext_t.
}
xme_com_packet_requestContext_t;
#pragma pack(pop)
#endif
#if 0
/**
* \typedef xme_com_packet_responseContext_t
*
* \brief Data that are always transmitted along with a response packet.
*/
#pragma pack(push, 1)
typedef struct
{
xme_core_rr_requestHandle_t localRequestHandle; ///< Request handle (only valid at the request issuer side).
xme_core_rr_requestInstanceHandle_t localRequestInstance; ///< Request instance identifier (only valid at the request issuer side).
xme_core_topic_t responseTopic; ///< Response topic. Note: although the request sender specifies which topic he want to rceive as response, we might want to relax that semantic later on and hence this member is still useful.
xme_core_rr_responseStatus_t responseStatus; ///< Response status code.
// TODO: Response meta data. See ticket #646
uint64_t instanceUserData; // TODO: See ticket #540. The size of this member is currently the size of the largest pointer we support, which is 64 bit. See also comment above in xme_com_packet_requestContext_t.
}
xme_com_packet_responseContext_t;
#pragma pack(pop)
#endif
/**
* \brief Sample Packet
*/
typedef xme_hal_sharedPtr_t xme_com_packet_sample_t;
/**
* \struct xme_com_packet_sample_header_t
* \brief Defines a sample header structure.
*/
#pragma pack(push, 1)
typedef struct
{
xme_com_packet_header_t packetHeader; ///< Common XME packet header.
uint8_t key[XME_WP_UDP_HEADER_KEY_LENGTH]; ///< The key which is added in the packet header to correctly identify the intended receipent.
xme_core_device_guid_t senderGuid; ///< Globally unique identifier of packet sender.
// TODO: We should reduce the number of bytes for this field or implement an alternative mechanism for detecting own network packets. See ticket #787.
/**
Unused up to now
uint16_t topicID; ///< Topic ID.
uint16_t publisherIDSender; ///< ID of publisher.
uint16_t totalSize; ///< Total size of packet.
uint16_t dataOffset; ///< Offset of fragment within packet.
uint16_t sampleNumber; ///< Sample number.
*/
} xme_com_packet_sample_header_t;
#pragma pack(pop)
/******************************************************************************/
/*** Prototypes ***/
/******************************************************************************/
XME_EXTERN_C_BEGIN
/**
* \brief Creates and initializes a sample packet.
*
* \param dataSize Size of the payload.
*
* \return Handle to sample packet.
*/
xme_com_packet_sample_t xme_com_packet_sample_create_payloadSize(uint16_t dataSize);
/**
* \brief Creates and initializes a sample packet.
*
* \param totalSize Size of complete packet.
*
* \return Handle to sample packet.
*/
xme_com_packet_sample_t xme_com_packet_sample_create_totalSize(uint16_t totalSize);
/**
* \brief Retrieve size of payload within sample packet.
*
* \param sample Handle to sample packet.
*
* \return Size of payload.
*/
uint16_t xme_com_packet_sample_getPayloadSize(xme_com_packet_sample_t sample);
/**
* \brief Retrieve total size of sample packet, including headers.
*
* \param sample Handle to sample packet.
*
* \return Total size of sample packet.
*/
uint16_t xme_com_packet_sample_getCompleteSize(xme_com_packet_sample_t sample);
/**
* \brief Extracts header from sample packet.
*
* \param sample Handle to sample packet.
*
* \return Pointer to header of sample packet.
*/
xme_com_packet_sample_header_t* xme_com_packet_sample_header(xme_com_packet_sample_t sample);
/**
* \brief Extracts payload from sample packet.
*
* \param sample Handle to sample packet.
*
* \return Pointer to payload.
*/
void* xme_com_packet_sample_payload(xme_com_packet_sample_t sample);
/**
* \brief Frees memory of sample packet.
*
* \param sample Handle to sample packet.
*/
void xme_com_packet_sample_destroy(xme_com_packet_sample_t sample);
XME_EXTERN_C_END
#endif // #ifndef XME_COM_PACKET_H
|
f6c098b169bca14288b39c963bc0f20cb7357764
|
881e4c840637bcbf7694246c6acefeadf9577bdd
|
/bmp_rw.c
|
6ae703d19372606e1cbd67dc51eba33bf19c959c
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
LMP88959/NTSC-CRT
|
fedb7daf4d60e7b3c693338e8099f9e40c14c0ac
|
d9b498f08ff3c24221ca5c62968683f4232ea0ab
|
refs/heads/main
| 2023-08-17T00:10:27.739355
| 2023-08-06T18:00:21
| 2023-08-06T18:00:21
| 579,563,736
| 384
| 22
|
NOASSERTION
| 2023-08-06T16:23:51
| 2022-12-18T05:13:49
|
C
|
UTF-8
|
C
| false
| false
| 4,088
|
c
|
bmp_rw.c
|
/*****************************************************************************/
/*
* NTSC/CRT - integer-only NTSC video signal encoding / decoding emulation
*
* by EMMIR 2018-2023
*
* YouTube: https://www.youtube.com/@EMMIR_KC/videos
* Discord: https://discord.com/invite/hdYctSmyQJ
*/
/*****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "bmp_rw.h"
/*
* BMP image reader/writer kindly provided by 'deqmega' https://github.com/DEQ2000-cyber
*/
static unsigned char *
loadBMP(char *file, unsigned int *w, unsigned int *h, unsigned char *bpp,
void *(*calloc_func)(size_t, size_t))
{
FILE *f;
unsigned char header[54];
unsigned char pad[3];
unsigned char *data = NULL;
unsigned int width, height, size;
unsigned char BPP, padding;
unsigned int X;
int Y;
f = fopen(file, "rb");
if (f == NULL) {
return NULL;
}
fread(header, sizeof(unsigned char), 54, f);
width = *(int*) &header[18];
height = *(int*) &header[22];
BPP = *(int*) &header[28];
size = (width * height * (BPP / 8));
padding = ((4 - (width * (BPP / 8)) % 4) % 4);
data = calloc_func(size, (BPP / 8));
if (data == NULL) {
return NULL;
}
fseek(f, 54, SEEK_SET);
for (Y = height - 1; Y >= 0; Y--) {
for (X = 0; X < width; X++) {
fread(&data[(Y * width + X) * (BPP / 8)], (BPP / 8), 1, f);
}
fread(pad, padding, 1, f);
}
fclose(f), f = NULL;
*w = width;
*h = height;
*bpp = BPP;
return data;
}
static void *
loadBMPconverter(char *file, int *w, int *h,
void *(*calloc_func)(size_t, size_t))
{
unsigned int *data = NULL;
unsigned int x, y, i;
unsigned char n;
unsigned char *p;
unsigned int *pix;
p = loadBMP(file, &x, &y, &n, calloc_func);
if (p == NULL) {
return NULL;
}
*w = x;
*h = y;
data = calloc_func(x * y, sizeof(unsigned int));
if (data == NULL) {
return NULL;
}
pix = data;
if ((n / 8) == 4) {
memcpy(pix, p, (x * y * sizeof(unsigned int)));
free(p);
return data;
}
for (i = 0; i < (x * y * (n / 8)); i += (n / 8)) {
*(pix++) = (p[i] << 0) | (p[i + 1] << 8) | (p[i + 2] << 16) | (255 << 24);
}
free(p);
return data;
}
static int
saveBMP(char *file, int *data, unsigned int w,
unsigned int h)
{
FILE *f;
unsigned int filesize;
unsigned char pad[3], header[14], info[40];
unsigned char padding;
unsigned int X;
int Y, bpp = 4;
if (data == NULL) {
return 0;
}
padding = ((4 - (w * bpp) % 4) % 4);
memset(header, 0, sizeof(header));
memset(info, 0, sizeof(info));
filesize = 14 + 40 + w * h * bpp + padding * w;
header[0] = 'B';
header[1] = 'M';
header[2] = filesize;
header[3] = filesize >> 8;
header[4] = filesize >> 16;
header[5] = filesize >> 24;
header[10] = 14 + 40;
info[0] = 40;
info[4] = (w >> 0) & 0xff;
info[5] = (w >> 8) & 0xff;
info[6] = (w >> 16) & 0xff;
info[7] = (w >> 24) & 0xff;
info[8] = (h >> 0) & 0xff;
info[9] = (h >> 8) & 0xff;
info[10] = (h >> 16) & 0xff;
info[11] = (h >> 24) & 0xff;
info[12] = 1;
info[14] = bpp * 8;
f = fopen(file, "wb");
if (f == NULL) {
return 0;
}
fwrite(header, 14, 1, f);
fwrite(info, 40, 1, f);
for (Y = h - 1; Y >= 0; Y--) {
for (X = 0; X < w; X++) {
fwrite(&data[Y * w + X], sizeof(int), 1, f);
}
fwrite(pad, padding, 1, f);
}
fclose(f);
return 1;
}
extern int
bmp_read24(char *file, int **out_color, int *out_w, int *out_h,
void *(*calloc_func)(size_t, size_t))
{
*out_color = loadBMPconverter(file, out_w, out_h, calloc_func);
return (*out_color != NULL);
}
extern int
bmp_write24(char *name, int *color, int w, int h)
{
return saveBMP(name, color, (unsigned int) w, (unsigned int) h);
}
|
21c063ced9f5516f64bf37888dc52b30500c3bf8
|
5f86fc385c7dcfcb5b166cdea7c8b13057b8bb5f
|
/enclave/core/sgx/arena.h
|
8082512a87a5265dd76567599c027d7a039bb315
|
[
"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
| 374
|
h
|
arena.h
|
// Copyright (c) Open Enclave SDK contributors.
// Licensed under the MIT License.
#ifndef _OE_ARENA_H
#define _OE_ARENA_H
#include <openenclave/bits/types.h>
bool oe_configure_arena_capacity(size_t cap);
void* oe_arena_malloc(size_t size);
void* oe_arena_calloc(size_t num, size_t size);
void oe_arena_free_all();
void oe_teardown_arena();
#endif /* _OE_ARENA_H */
|
e006c67349ea8bc05bbfbc29fd1c3fa67eeefad1
|
4c690b473a2fd8baa53377195933c2b996a01244
|
/pcat/pcat-print.c
|
dee712759a4f0bc9d95bd237fe8e33edc85da801
|
[
"BSD-3-Clause"
] |
permissive
|
NLnetLabs/ldns
|
77bdf4bf6f814fe8d7e274a1754e9bbf23ae0a4a
|
67b9f0ae98910df882ca77f503673929a9e1db9b
|
refs/heads/develop
| 2023-08-28T07:19:23.088018
| 2023-06-03T13:08:41
| 2023-06-03T13:09:04
| 72,740,793
| 248
| 103
|
BSD-3-Clause
| 2023-09-14T14:40:58
| 2016-11-03T11:57:12
|
C
|
UTF-8
|
C
| false
| false
| 1,724
|
c
|
pcat-print.c
|
#define _GNU_SOURCE
#include "config.h"
#include <ldns/ldns.h>
#define SEQUENCE 1
#define QUERY 2
#define ANSWER1 3
#define ANSWER2 0
#define LINES 4
#ifndef HAVE_GETDELIM
ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);
#endif
void
printf_bar(void)
{
fprintf(stdout, "===================================================================\n");
}
int
main(int argc, char **argv)
{
ssize_t read;
char *line;
size_t i, j, k, len;
u_char pkt_buf[LDNS_MAX_PACKETLEN];
ldns_pkt *p;
ldns_status s;
FILE *diff = stdin;
i = 1;
len = 0;
line = NULL;
if (argc > 1) {
if (!(diff = fopen(argv[1], "r"))) {
fprintf(stderr, "Cannot open pcat diff file `%s\'\n", argv[1]);
exit(EXIT_FAILURE);
}
}
while((read = getdelim(&line, &len, '\n', diff)) != -1) {
if (read < 2 || read > LDNS_MAX_PACKETLEN) {
if(read == 1)
fprintf(stdout, "NO ANSWER (line %d)\n", (int)i);
else
fprintf(stdout, "Under- or overflow (%d) - "
"skipping line %d\n", (int)read, (int)i);
i++;
printf_bar();
continue;
}
line[read - 1] = '\0';
switch(i % LINES) {
case SEQUENCE:
printf_bar();
fprintf(stdout, "Index: %s\n", line);
printf_bar();
break;
case QUERY:
case ANSWER1:
case ANSWER2:
k = 0;
for(j = 0; j < read - 1; j += 2) {
pkt_buf[k] =
ldns_hexdigit_to_int(line[j]) * 16 +
ldns_hexdigit_to_int(line[j + 1]);
k++;
}
s = ldns_wire2pkt(&p, pkt_buf, k);
fprintf(stdout, "=* %s\n", line);
if (s != LDNS_STATUS_OK) {
fprintf(stdout, "%s\n", ldns_get_errorstr_by_id(s));
} else {
ldns_pkt_print(stdout, p);
}
printf_bar();
break;
}
i++;
len = 0;
}
return 0;
}
|
d3075d08e59a0b779841794f86428a6b7d8a23df
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/input/misc/dm355evm_keys.c
|
a309a5c0899e365c59bf8c45517e6cb93dd3b276
|
[
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 8,109
|
c
|
dm355evm_keys.c
|
/*
* dm355evm_keys.c - support buttons and IR remote on DM355 EVM board
*
* Copyright (c) 2008 by David Brownell
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/input/sparse-keymap.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/i2c/dm355evm_msp.h>
#include <linux/module.h>
/*
* The MSP430 firmware on the DM355 EVM monitors on-board pushbuttons
* and an IR receptor used for the remote control. When any key is
* pressed, or its autorepeat kicks in, an event is sent. This driver
* read those events from the small (32 event) queue and reports them.
*
* Note that physically there can only be one of these devices.
*
* This driver was tested with firmware revision A4.
*/
struct dm355evm_keys {
struct input_dev *input;
struct device *dev;
int irq;
};
/* These initial keycodes can be remapped */
static const struct key_entry dm355evm_keys[] = {
/*
* Pushbuttons on the EVM board ... note that the labels for these
* are SW10/SW11/etc on the PC board. The left/right orientation
* comes only from the firmware's documentation, and presumes the
* power connector is immediately in front of you and the IR sensor
* is to the right. (That is, rotate the board counter-clockwise
* by 90 degrees from the SW10/etc and "DM355 EVM" labels.)
*/
{ KE_KEY, 0x00d8, { KEY_OK } }, /* SW12 */
{ KE_KEY, 0x00b8, { KEY_UP } }, /* SW13 */
{ KE_KEY, 0x00e8, { KEY_DOWN } }, /* SW11 */
{ KE_KEY, 0x0078, { KEY_LEFT } }, /* SW14 */
{ KE_KEY, 0x00f0, { KEY_RIGHT } }, /* SW10 */
/*
* IR buttons ... codes assigned to match the universal remote
* provided with the EVM (Philips PM4S) using DVD code 0020.
*
* These event codes match firmware documentation, but other
* remote controls could easily send more RC5-encoded events.
* The PM4S manual was used in several cases to help select
* a keycode reflecting the intended usage.
*
* RC5 codes are 14 bits, with two start bits (0x3 prefix)
* and a toggle bit (masked out below).
*/
{ KE_KEY, 0x300c, { KEY_POWER } }, /* NOTE: docs omit this */
{ KE_KEY, 0x3000, { KEY_NUMERIC_0 } },
{ KE_KEY, 0x3001, { KEY_NUMERIC_1 } },
{ KE_KEY, 0x3002, { KEY_NUMERIC_2 } },
{ KE_KEY, 0x3003, { KEY_NUMERIC_3 } },
{ KE_KEY, 0x3004, { KEY_NUMERIC_4 } },
{ KE_KEY, 0x3005, { KEY_NUMERIC_5 } },
{ KE_KEY, 0x3006, { KEY_NUMERIC_6 } },
{ KE_KEY, 0x3007, { KEY_NUMERIC_7 } },
{ KE_KEY, 0x3008, { KEY_NUMERIC_8 } },
{ KE_KEY, 0x3009, { KEY_NUMERIC_9 } },
{ KE_KEY, 0x3022, { KEY_ENTER } },
{ KE_KEY, 0x30ec, { KEY_MODE } }, /* "tv/vcr/..." */
{ KE_KEY, 0x300f, { KEY_SELECT } }, /* "info" */
{ KE_KEY, 0x3020, { KEY_CHANNELUP } }, /* "up" */
{ KE_KEY, 0x302e, { KEY_MENU } }, /* "in/out" */
{ KE_KEY, 0x3011, { KEY_VOLUMEDOWN } }, /* "left" */
{ KE_KEY, 0x300d, { KEY_MUTE } }, /* "ok" */
{ KE_KEY, 0x3010, { KEY_VOLUMEUP } }, /* "right" */
{ KE_KEY, 0x301e, { KEY_SUBTITLE } }, /* "cc" */
{ KE_KEY, 0x3021, { KEY_CHANNELDOWN } },/* "down" */
{ KE_KEY, 0x3022, { KEY_PREVIOUS } },
{ KE_KEY, 0x3026, { KEY_SLEEP } },
{ KE_KEY, 0x3172, { KEY_REWIND } }, /* NOTE: docs wrongly say 0x30ca */
{ KE_KEY, 0x3175, { KEY_PLAY } },
{ KE_KEY, 0x3174, { KEY_FASTFORWARD } },
{ KE_KEY, 0x3177, { KEY_RECORD } },
{ KE_KEY, 0x3176, { KEY_STOP } },
{ KE_KEY, 0x3169, { KEY_PAUSE } },
};
/*
* Because we communicate with the MSP430 using I2C, and all I2C calls
* in Linux sleep, we use a threaded IRQ handler. The IRQ itself is
* active low, but we go through the GPIO controller so we can trigger
* on falling edges and not worry about enabling/disabling the IRQ in
* the keypress handling path.
*/
static irqreturn_t dm355evm_keys_irq(int irq, void *_keys)
{
static u16 last_event;
struct dm355evm_keys *keys = _keys;
const struct key_entry *ke;
unsigned int keycode;
int status;
u16 event;
/* For simplicity we ignore INPUT_COUNT and just read
* events until we get the "queue empty" indicator.
* Reading INPUT_LOW decrements the count.
*/
for (;;) {
status = dm355evm_msp_read(DM355EVM_MSP_INPUT_HIGH);
if (status < 0) {
dev_dbg(keys->dev, "input high err %d\n",
status);
break;
}
event = status << 8;
status = dm355evm_msp_read(DM355EVM_MSP_INPUT_LOW);
if (status < 0) {
dev_dbg(keys->dev, "input low err %d\n",
status);
break;
}
event |= status;
if (event == 0xdead)
break;
/* Press and release a button: two events, same code.
* Press and hold (autorepeat), then release: N events
* (N > 2), same code. For RC5 buttons the toggle bits
* distinguish (for example) "1-autorepeat" from "1 1";
* but PCB buttons don't support that bit.
*
* So we must synthesize release events. We do that by
* mapping events to a press/release event pair; then
* to avoid adding extra events, skip the second event
* of each pair.
*/
if (event == last_event) {
last_event = 0;
continue;
}
last_event = event;
/* ignore the RC5 toggle bit */
event &= ~0x0800;
/* find the key, or report it as unknown */
ke = sparse_keymap_entry_from_scancode(keys->input, event);
keycode = ke ? ke->keycode : KEY_UNKNOWN;
dev_dbg(keys->dev,
"input event 0x%04x--> keycode %d\n",
event, keycode);
/* report press + release */
input_report_key(keys->input, keycode, 1);
input_sync(keys->input);
input_report_key(keys->input, keycode, 0);
input_sync(keys->input);
}
return IRQ_HANDLED;
}
/*----------------------------------------------------------------------*/
static int dm355evm_keys_probe(struct platform_device *pdev)
{
struct dm355evm_keys *keys;
struct input_dev *input;
int status;
/* allocate instance struct and input dev */
keys = kzalloc(sizeof *keys, GFP_KERNEL);
input = input_allocate_device();
if (!keys || !input) {
status = -ENOMEM;
goto fail1;
}
keys->dev = &pdev->dev;
keys->input = input;
/* set up "threaded IRQ handler" */
status = platform_get_irq(pdev, 0);
if (status < 0)
goto fail1;
keys->irq = status;
input_set_drvdata(input, keys);
input->name = "DM355 EVM Controls";
input->phys = "dm355evm/input0";
input->dev.parent = &pdev->dev;
input->id.bustype = BUS_I2C;
input->id.product = 0x0355;
input->id.version = dm355evm_msp_read(DM355EVM_MSP_FIRMREV);
status = sparse_keymap_setup(input, dm355evm_keys, NULL);
if (status)
goto fail1;
/* REVISIT: flush the event queue? */
status = request_threaded_irq(keys->irq, NULL, dm355evm_keys_irq,
IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
dev_name(&pdev->dev), keys);
if (status < 0)
goto fail2;
/* register */
status = input_register_device(input);
if (status < 0)
goto fail3;
platform_set_drvdata(pdev, keys);
return 0;
fail3:
free_irq(keys->irq, keys);
fail2:
sparse_keymap_free(input);
fail1:
input_free_device(input);
kfree(keys);
dev_err(&pdev->dev, "can't register, err %d\n", status);
return status;
}
static int dm355evm_keys_remove(struct platform_device *pdev)
{
struct dm355evm_keys *keys = platform_get_drvdata(pdev);
free_irq(keys->irq, keys);
sparse_keymap_free(keys->input);
input_unregister_device(keys->input);
kfree(keys);
return 0;
}
/* REVISIT: add suspend/resume when DaVinci supports it. The IRQ should
* be able to wake up the system. When device_may_wakeup(&pdev->dev), call
* enable_irq_wake() on suspend, and disable_irq_wake() on resume.
*/
/*
* I2C is used to talk to the MSP430, but this platform device is
* exposed by an MFD driver that manages I2C communications.
*/
static struct platform_driver dm355evm_keys_driver = {
.probe = dm355evm_keys_probe,
.remove = dm355evm_keys_remove,
.driver = {
.owner = THIS_MODULE,
.name = "dm355evm_keys",
},
};
module_platform_driver(dm355evm_keys_driver);
MODULE_LICENSE("GPL");
|
5de44550ec08667da8b53e0d3dedb1fb1fc8e404
|
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
|
/security/openvas/files/patch-nasl_nasl_init.c
|
0e2f22567617e4d9164355da5f265bc127154fb7
|
[
"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
| 379
|
c
|
patch-nasl_nasl_init.c
|
--- nasl/nasl_init.c 2020-12-31 17:24:31.913454000 -0500
+++ nasl/nasl_init.c 2020-12-31 17:25:42.418759000 -0500
@@ -38,6 +38,8 @@
#include <stdlib.h> /* for getenv. */
#include <string.h> /* for memset */
+#include <sys/types.h>
+#include <sys/socket.h>
/* to e.g. favour BSD, but also for IPPROTO_TCP and TH_FIN */
#include "nasl_raw.h"
#include "nasl_scanner_glue.h"
|
29408b8695b000be41fae8f6ac1402c632ea5292
|
ec6a71b57ebe88538269197fd16bede6bc2062ae
|
/erts/lib_src/yielding_c_fun/ycf_printers.c
|
1326243dc37ecd30ed3597459e8f52fd00e8405e
|
[
"Apache-2.0"
] |
permissive
|
erlang/otp
|
7c6e88ca955bd6a3ede1530154c80e8ce449a370
|
334589af62a8db25a81afba2ecc50f33ff69ddb8
|
refs/heads/master
| 2023-08-30T23:37:28.061328
| 2023-08-30T04:20:48
| 2023-08-30T04:20:48
| 374,927
| 9,920
| 3,018
|
Apache-2.0
| 2023-09-14T10:37:26
| 2009-11-16T17:17:57
|
Erlang
|
UTF-8
|
C
| false
| false
| 18,578
|
c
|
ycf_printers.c
|
/*
* %CopyrightBegin%
*
* Copyright Ericsson AB and Kjell Winblad 2019-2021. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* %CopyrightEnd%
*/
/*
* Author: Kjell Winblad
*/
#include <stdio.h>
#include <stdlib.h>
#include "ycf_yield_fun.h"
#include "ycf_node.h"
void print_node_code_expression(ycf_node_expression e, ycf_string_printable_buffer* b);
void print_symbol_code(ycf_symbol* s, ycf_string_printable_buffer* b){
if(s == NULL){
return;
}
print_symbol_code(s->whitespace_or_comment_before, b);
ycf_string_printable_buffer_printf(b, "%s", ycf_symbol_get_text(s));
}
void print_symbol_list(ycf_symbol_list* l, ycf_string_printable_buffer* b){
ycf_symbol* s = l->head;
while(s != NULL){
print_symbol_code(s, b);
s = s->next;
}
}
void print_node_code_array_bracket(ycf_node_array_bracket n, ycf_string_printable_buffer* b){
print_symbol_code(n.start, b);
if(!n.empty){
print_node_code_expression(n.content, b);
}
print_symbol_code(n.end, b);
}
void print_node_code_definition_custom_end(ycf_node_definition d, bool dyn_array_to_ptr, ycf_symbol* end, ycf_string_printable_buffer* b){
int nr_of_empty_brackets = 0;
{
ycf_node* current = d.array_brackets.head;
while(current != NULL){
if(current->u.array_bracket.empty){
nr_of_empty_brackets++;
}
current = current->next;
}
}
print_symbol_list(&d.type_specifiers, b);
if(dyn_array_to_ptr){
for(int i = 0; i < nr_of_empty_brackets; i++){
ycf_string_printable_buffer_printf(b, "*");
}
}
print_symbol_code(d.identifier, b);
if (!dyn_array_to_ptr || nr_of_empty_brackets == 0){
print_node_list_code(d.array_brackets.head, b);
}
print_symbol_code(end, b);
}
void print_node_code_definition(ycf_node_definition d, ycf_string_printable_buffer* b){
print_node_code_definition_custom_end(d, false, d.end, b);
}
void print_node_code_definition_init(ycf_node_definition_init d, ycf_string_printable_buffer* b){
print_node_code_definition(d.definition, b);
print_symbol_list(&d.initializer_expression, b);
print_symbol_code(d.end, b);
}
void print_node_list_code(ycf_node* n, ycf_string_printable_buffer* b){
while(n != NULL){
ycf_node_print(n, b);
n = n->next;
}
}
void print_node_code_function_def_parameters(ycf_node_function_definition f_def, ycf_string_printable_buffer* b){
if(f_def.ignore_param_ending){
ycf_node* n = f_def.parameters.head;
while(n != NULL){
if(n->next == NULL){
print_node_code_definition_custom_end(n->u.definition, false, ycf_symbol_new_parenthesis(), b);
}else{
print_node_code_definition_custom_end(n->u.definition, false, ycf_symbol_new_comma(), b);
}
n = n->next;
}
if(f_def.end.head != NULL && f_def.end.head->type == ycf_symbol_type_end_parenthesis){
ycf_symbol_list end = f_def.end;
end.head = end.head->next;
print_symbol_list(&end, b);
}else if(f_def.end.head != NULL && f_def.end.head->type != ycf_symbol_type_void){
print_symbol_list(&f_def.end, b);
}
}else {
print_node_list_code(f_def.parameters.head, b);
print_symbol_list(&f_def.end, b);
}
}
void print_node_code_function_def(ycf_node_function_definition f_def, ycf_string_printable_buffer* b){
print_node_code_definition(f_def.definition, b);
print_node_code_function_def_parameters(f_def, b);
}
void print_node_code_scope(ycf_node_code_scope s, ycf_string_printable_buffer* b){
print_symbol_code(s.start, b);
print_node_list_code(s.definition_nodes.head, b);
print_node_list_code(s.other_nodes.head, b);
print_symbol_code(s.end, b);
}
void print_node_code_function(ycf_node_function f, ycf_string_printable_buffer* b){
print_node_code_function_def(f.definition, b);
print_node_code_scope(f.body, b);
}
void print_node_code_assignment(ycf_node_assignment a, ycf_string_printable_buffer* b){
print_node_code_expression(a.left_side, b);
print_symbol_code(a.assignment_symbol, b);
print_node_code_expression(a.right_side, b);
print_symbol_code(a.end, b);
}
void print_node_code_gen_struct(ycf_node_gen_typedef_struct n, ycf_string_printable_buffer* b){
ycf_string_printable_buffer_printf(b, "\n\n\nstruct %s {", n.name);
ycf_node* current = n.definition_nodes.head;
while(current != NULL){
print_node_code_definition_custom_end(current->u.definition, true, ycf_symbol_new_semicolon(), b);
current = current->next;
}
ycf_string_printable_buffer_printf(b, "\n};\n");
}
void print_node_code_yield(ycf_node_yield n, ycf_string_printable_buffer* b){
print_symbol_code(n.yield_symbol,b);
print_symbol_code(n.end_symbol,b);
}
void print_node_code_function_call(ycf_node_function_call n, ycf_string_printable_buffer* b){
print_symbol_list(&n.neg_symbols, b);
print_symbol_code(n.identifier, b);
print_symbol_code(n.start_symbol, b);
print_node_list_code(n.parameter_expressions.head, b);
print_symbol_code(n.end_symbol, b);
}
void print_node_code_expression(ycf_node_expression e, ycf_string_printable_buffer* b){
print_node_list_code(e.content.head, b);
}
void print_node_code_paran_expression(ycf_node_parentheses_expression e, ycf_string_printable_buffer* b){
print_symbol_code(e.start_symbol, b);
print_node_code_expression(e.content, b);
print_symbol_code(e.end_symbol, b);
}
void print_node_code_consume_reds(ycf_node_consume_reds e, ycf_string_printable_buffer* b){
print_symbol_code(e.consume_reds_symbol, b);
print_node_code_paran_expression(e.nr_of_reds_expression, b);
print_symbol_code(e.end_symbol, b);
}
void print_node_code_if_statement(ycf_node_if e, ycf_string_printable_buffer* b){
print_symbol_code(e.if_word, b);
print_node_code_paran_expression(e.expression, b);
ycf_node_print(e.if_statement, b);
}
void print_node_code_while_statement(ycf_node_while e, ycf_string_printable_buffer* b){
print_symbol_code(e.while_word, b);
print_node_code_paran_expression(e.expression, b);
ycf_node_print(e.statement, b);
}
void print_node_code_do_while_statement(ycf_node_do_while e, ycf_string_printable_buffer* b){
print_symbol_code(e.do_word, b);
ycf_node_print(e.statement, b);
print_symbol_code(e.while_word, b);
print_node_code_paran_expression(e.expression, b);
print_symbol_code(e.end, b);
}
void print_node_code_switch_statement(ycf_node_switch e, ycf_string_printable_buffer* b){
print_symbol_code(e.switch_word, b);
print_node_code_paran_expression(e.expression, b);
print_node_code_scope(e.scope, b);
}
void print_node_code_for_statement(ycf_node_for e, ycf_string_printable_buffer* b){
print_symbol_code(e.for_word, b);
print_symbol_code(e.start_parentheses, b);
ycf_node_print(e.init, b);
ycf_node_print(e.stop_cond, b);
print_symbol_code(e.stop_cond_end, b);
ycf_node_print(e.end_exp, b);
print_symbol_code(e.end_parentheses, b);
ycf_node_print(e.statement, b);
}
void print_node_code_if_else_statement(ycf_node_if_else e, ycf_string_printable_buffer* b){
print_node_code_if_statement(e.if_part, b);
print_symbol_code(e.else_word, b);
ycf_node_print(e.else_statement, b);
}
void print_node_code_for_assignment_fun_call(ycf_node_function_call_assignment e, ycf_string_printable_buffer* b){
print_node_code_expression(e.left_side, b);
print_symbol_code(e.assignment_symbol, b);
print_node_code_function_call(e.fun_call, b);
}
void print_node_code_special_code_block(ycf_node_special_code_block block, ycf_string_printable_buffer* b){
print_symbol_code(block.start, b);
print_node_code_if_statement(block.code, b);
print_symbol_code(block.end, b);
}
void print_node_code_goto(ycf_node_goto n, ycf_string_printable_buffer* b){
print_symbol_code(n.goto_symbol, b);
print_symbol_code(n.label_symbol, b);
print_symbol_code(n.end_symbol, b);
}
void print_node_code_period_field_access(ycf_node_period_field_access n, ycf_string_printable_buffer* b){
print_symbol_code(n.period, b);
print_symbol_code(n.field_name, b);
}
void print_node_code_pointer_field_access(ycf_pointer_field_access n, ycf_string_printable_buffer* b){
print_symbol_code(n.pointer, b);
print_symbol_code(n.field_name, b);
}
void print_node_code_return(ycf_node_return n, ycf_string_printable_buffer* b){
print_symbol_code(n.return_symbol, b);
if (n.return_expression != NULL) {
ycf_node_print(n.return_expression, b);
}
print_symbol_code(n.end_symbol, b);
}
void ycf_node_print(ycf_node* node, ycf_string_printable_buffer* b){
if(node == NULL){
return;
} else if(node->type == ycf_node_type_c_file){
print_node_list_code(node->u.c_file.content.head, b);
} else if(node->type == ycf_node_type_variable_definition){
print_node_code_definition(node->u.definition, b);
} else if(node->type == ycf_node_type_variable_definition_init){
print_node_code_definition_init(node->u.definition_init, b);
} else if(node->type == ycf_node_type_function_declaration){
print_node_code_function_def(node->u.function_definition, b);
} else if(node->type == ycf_node_type_other){
print_symbol_code(node->u.other.what, b);
} else if(node->type == ycf_node_type_code_scope){
print_node_code_scope(node->u.code_scope, b);
}else if(node->type == ycf_node_type_function_definition){
print_node_code_function(node->u.function, b);
}else if(node->type == ycf_node_type_assignment){
print_node_code_assignment(node->u.a, b);
}else if(node->type == ycf_node_type_gen_typedef_struct){
print_node_code_gen_struct(node->u.gen_typedef_struct, b);
}else if(node->type == ycf_node_type_yield){
print_node_code_yield(node->u.yield, b);
} else if(node->type == ycf_node_type_statement){
ycf_node_print(node->u.statement.expression, b);
print_symbol_code(node->u.statement.end_symbol, b);
} else if(node->type == ycf_node_type_function_call){
print_node_code_function_call(node->u.function_call, b);
} else if(node->type == ycf_node_type_expression){
print_node_code_expression(node->u.expression, b);
} else if(node->type == ycf_node_type_parentheses_expression){
print_node_code_paran_expression(node->u.parentheses_expression, b);
} else if(node->type == ycf_node_type_if){
print_node_code_if_statement(node->u.if_n, b);
}else if(node->type == ycf_node_type_if_else){
print_node_code_if_else_statement(node->u.if_else, b);
}else if(node->type == ycf_node_type_while){
print_node_code_while_statement(node->u.while_n, b);
}else if(node->type == ycf_node_type_do_while){
print_node_code_do_while_statement(node->u.do_while, b);
}else if(node->type == ycf_node_type_switch){
print_node_code_switch_statement(node->u.switch_n, b);
}else if(node->type == ycf_node_type_for){
print_node_code_for_statement(node->u.for_n, b);
}else if(node->type == ycf_node_type_assignment_function_call){
print_node_code_for_assignment_fun_call(node->u.function_call_assignment, b);
} else if(node->type == ycf_node_type_comma){
print_symbol_code(node->u.comma.comma_symbol, b);
} else if(node->type == ycf_node_type_array_bracket){
print_node_code_array_bracket(node->u.array_bracket, b);
} else if(node->type == ycf_node_type_macro_cmd){
print_symbol_code(node->u.macro_cmd.symbol, b);
} else if(node->type == ycf_node_type_on_save_yield_state_code ||
node->type == ycf_node_type_on_restore_yield_state_code ||
node->type == ycf_node_type_on_destroy_state_code ||
node->type == ycf_node_type_on_return_code ||
node->type == ycf_node_type_on_destroy_state_or_return_code){
print_node_code_special_code_block(node->u.special_code_block, b);
} else if(node->type == ycf_node_type_goto){
print_node_code_goto(node->u.goto_n, b);
} else if(node->type == ycf_node_type_return_statement){
print_node_code_return(node->u.return_n, b);
} else if(node->type == ycf_node_type_period_field_access){
print_node_code_period_field_access(node->u.period_field_access, b);
} else if(node->type == ycf_node_type_pointer_field_access){
print_node_code_pointer_field_access(node->u.pointer_field_access, b);
} else {
fprintf(stderr, "Unknown node type %d\n", node->type);
exit(1);
}
}
void print_definition(ycf_node_definition d){
printf("NODE: definition (type=%s,%s=%s)\n",
ycf_symbol_text_between(d.type_specifiers.head,
d.type_specifiers.last),
get_symbol_type_text(d.identifier->type),
ycf_symbol_get_text(d.identifier) );
}
void print_scope(ycf_node_code_scope node){
printf("NODE: scope\n");
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
printf("Definition Nodes:\n");
struct ycf_node* n = node.definition_nodes.head;
while(n != NULL){
print_abstract_syntax_tree(n);
n = n->next;
}
printf("Other Nodes:\n");
n = node.other_nodes.head;
while(n != NULL){
print_abstract_syntax_tree(n);
n = n->next;
}
printf("END SCOPE\n");
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
}
void print_function_def(ycf_node_function_definition node){
printf("NODE: function def:\n");
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
printf("definition:\n");
print_definition(node.definition);
printf("parameters:\n");
struct ycf_node* n = node.parameters.head;
while(n != NULL){
print_abstract_syntax_tree(n);
n = n->next;
}
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
}
void print_fun_call(ycf_node_function_call f_call){
printf("NODE: fun_call %s parameters:\n", ycf_symbol_get_text(f_call.identifier));
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
struct ycf_node* current = f_call.parameter_expressions.head;
int i = 1;
while(current != NULL){
printf("param %d: \n", i);
ycf_node_print(current, NULL);
current = current->next;
i++;
}
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
}
void print_abstract_syntax_tree(ycf_node* node){
printf("%p\n",(void*)node);
if(node == NULL){
return;
} else if(node->type == ycf_node_type_c_file){
printf("NODE: c_file\n");
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
struct ycf_node* n = node->u.c_file.content.head;
while(n != NULL){
print_abstract_syntax_tree(n);
n = n->next;
}
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
} else if(node->type == ycf_node_type_variable_definition){
print_definition(node->u.definition);
} else if(node->type == ycf_node_type_variable_definition_init){
printf("NODE: definition_init (type=%s,%s=%s,init=%s)\n",
ycf_symbol_text_between(node->u.definition_init.definition.type_specifiers.head,
node->u.definition_init.definition.type_specifiers.last),
get_symbol_type_text(node->u.definition_init.definition.identifier->type),
ycf_symbol_get_text(node->u.definition_init.definition.identifier),
ycf_symbol_text_between(node->u.definition_init.initializer_expression.head,
node->u.definition_init.initializer_expression.last));
} else if(node->type == ycf_node_type_function_declaration){
print_function_def(node->u.function_definition);
} else if(node->type == ycf_node_type_other){
printf("NODE: other (%s)\n", get_symbol_type_text(node->u.other.what->type));
} else if(node->type == ycf_node_type_code_scope){
print_scope(node->u.code_scope);
}else if(node->type == ycf_node_type_function_definition){
printf("NODE: function\n");
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
print_function_def(node->u.function.definition);
print_scope(node->u.function.body);
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
}else if(node->type == ycf_node_type_assignment){
printf("NODE: assignment\n");
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
print_node_code_assignment(node->u.a, NULL);
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
}else if(node->type == ycf_node_type_yield){
printf("NODE: yield\n");
}else if(node->type == ycf_node_type_statement){
printf("NODE: statement\n");
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
print_abstract_syntax_tree(node->u.statement.expression);
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
}else if(node->type == ycf_node_type_if){
printf("NODE: if_statement\n");
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
ycf_node_print(node, NULL);
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
}else if(node->type == ycf_node_type_if_else){
printf("NODE: if_else_statement\n");
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
ycf_node_print(node, NULL);
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
}else if(node->type == ycf_node_type_while){
printf("NODE: while_statement\n");
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
ycf_node_print(node, NULL);
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
}else if(node->type == ycf_node_type_do_while){
printf("NODE: do_while_statement\n");
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
ycf_node_print(node, NULL);
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
}else if(node->type == ycf_node_type_for){
printf("NODE: for_statement\n");
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
ycf_node_print(node, NULL);
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
}else if(node->type == ycf_node_type_switch){
printf("NODE: switch_statement\n");
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
ycf_node_print(node, NULL);
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
} else if(node->type == ycf_node_type_function_call) {
print_fun_call(node->u.function_call);
} else if(node->type == ycf_node_type_assignment_function_call) {
printf("NODE: assignment fun call\n");
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
printf("Assignment expression:\n");
print_node_code_expression(node->u.function_call_assignment.left_side, NULL);
print_fun_call(node->u.function_call_assignment.fun_call);
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
} else {
printf("NODE: OTHER???\n");
printf(">>>>>>>>>>>>>>>>>>>>>>>\n");
ycf_node_print(node, NULL);
printf("<<<<<<<<<<<<<<<<<<<<<<<\n");
}
}
|
517ec584e002436b251230956c392c6df548675f
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/staging/rtl8712/rtl871x_pwrctrl.c
|
9fd2ec7596cc8cfc4228addfbeb718613f539681
|
[
"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
| 7,121
|
c
|
rtl871x_pwrctrl.c
|
/******************************************************************************
* rtl871x_pwrctrl.c
*
* Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved.
* Linux device driver for RTL8192SU
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* Modifications for inclusion into the Linux staging tree are
* Copyright(c) 2010 Larry Finger. All rights reserved.
*
* Contact information:
* WLAN FAE <wlanfae@realtek.com>
* Larry Finger <Larry.Finger@lwfinger.net>
*
******************************************************************************/
#define _RTL871X_PWRCTRL_C_
#include "osdep_service.h"
#include "drv_types.h"
#include "osdep_intf.h"
#define RTL8712_SDIO_LOCAL_BASE 0X10100000
#define SDIO_HCPWM (RTL8712_SDIO_LOCAL_BASE + 0x0081)
void r8712_set_rpwm(struct _adapter *padapter, u8 val8)
{
u8 rpwm;
struct pwrctrl_priv *pwrpriv = &padapter->pwrctrlpriv;
if (pwrpriv->rpwm == val8) {
if (pwrpriv->rpwm_retry == 0)
return;
}
if ((padapter->bDriverStopped == true) ||
(padapter->bSurpriseRemoved == true))
return;
rpwm = val8 | pwrpriv->tog;
switch (val8) {
case PS_STATE_S1:
pwrpriv->cpwm = val8;
break;
case PS_STATE_S2:/* only for USB normal powersave mode use,
* temp mark some code. */
case PS_STATE_S3:
case PS_STATE_S4:
pwrpriv->cpwm = val8;
break;
default:
break;
}
pwrpriv->rpwm_retry = 0;
pwrpriv->rpwm = val8;
r8712_write8(padapter, 0x1025FE58, rpwm);
pwrpriv->tog += 0x80;
}
void r8712_set_ps_mode(struct _adapter *padapter, uint ps_mode, uint smart_ps)
{
struct pwrctrl_priv *pwrpriv = &padapter->pwrctrlpriv;
if (ps_mode > PM_Card_Disable)
return;
/* if driver is in active state, we dont need set smart_ps.*/
if (ps_mode == PS_MODE_ACTIVE)
smart_ps = 0;
if ((pwrpriv->pwr_mode != ps_mode) || (pwrpriv->smart_ps != smart_ps)) {
if (pwrpriv->pwr_mode == PS_MODE_ACTIVE)
pwrpriv->bSleep = true;
else
pwrpriv->bSleep = false;
pwrpriv->pwr_mode = ps_mode;
pwrpriv->smart_ps = smart_ps;
_set_workitem(&(pwrpriv->SetPSModeWorkItem));
}
}
/*
* Caller:ISR handler...
*
* This will be called when CPWM interrupt is up.
*
* using to update cpwn of drv; and drv will make a decision to up or
* down pwr level
*/
void r8712_cpwm_int_hdl(struct _adapter *padapter,
struct reportpwrstate_parm *preportpwrstate)
{
struct pwrctrl_priv *pwrpriv = &(padapter->pwrctrlpriv);
struct cmd_priv *pcmdpriv = &(padapter->cmdpriv);
if (pwrpriv->cpwm_tog == ((preportpwrstate->state) & 0x80))
return;
_cancel_timer_ex(&padapter->pwrctrlpriv. rpwm_check_timer);
_enter_pwrlock(&pwrpriv->lock);
pwrpriv->cpwm = (preportpwrstate->state) & 0xf;
if (pwrpriv->cpwm >= PS_STATE_S2) {
if (pwrpriv->alives & CMD_ALIVE)
up(&(pcmdpriv->cmd_queue_sema));
}
pwrpriv->cpwm_tog = (preportpwrstate->state) & 0x80;
up(&pwrpriv->lock);
}
static inline void register_task_alive(struct pwrctrl_priv *pwrctrl, uint tag)
{
pwrctrl->alives |= tag;
}
static inline void unregister_task_alive(struct pwrctrl_priv *pwrctrl, uint tag)
{
if (pwrctrl->alives & tag)
pwrctrl->alives ^= tag;
}
static void _rpwm_check_handler (struct _adapter *padapter)
{
struct pwrctrl_priv *pwrpriv = &padapter->pwrctrlpriv;
if (padapter->bDriverStopped == true ||
padapter->bSurpriseRemoved == true)
return;
if (pwrpriv->cpwm != pwrpriv->rpwm)
_set_workitem(&(pwrpriv->rpwm_workitem));
}
static void SetPSModeWorkItemCallback(struct work_struct *work)
{
struct pwrctrl_priv *pwrpriv = container_of(work,
struct pwrctrl_priv, SetPSModeWorkItem);
struct _adapter *padapter = container_of(pwrpriv,
struct _adapter, pwrctrlpriv);
if (!pwrpriv->bSleep) {
_enter_pwrlock(&pwrpriv->lock);
if (pwrpriv->pwr_mode == PS_MODE_ACTIVE)
r8712_set_rpwm(padapter, PS_STATE_S4);
up(&pwrpriv->lock);
}
}
static void rpwm_workitem_callback(struct work_struct *work)
{
struct pwrctrl_priv *pwrpriv = container_of(work,
struct pwrctrl_priv, rpwm_workitem);
struct _adapter *padapter = container_of(pwrpriv,
struct _adapter, pwrctrlpriv);
u8 cpwm = pwrpriv->cpwm;
if (pwrpriv->cpwm != pwrpriv->rpwm) {
_enter_pwrlock(&pwrpriv->lock);
cpwm = r8712_read8(padapter, SDIO_HCPWM);
pwrpriv->rpwm_retry = 1;
r8712_set_rpwm(padapter, pwrpriv->rpwm);
up(&pwrpriv->lock);
}
}
static void rpwm_check_handler (void *FunctionContext)
{
struct _adapter *adapter = (struct _adapter *)FunctionContext;
_rpwm_check_handler(adapter);
}
void r8712_init_pwrctrl_priv(struct _adapter *padapter)
{
struct pwrctrl_priv *pwrctrlpriv = &padapter->pwrctrlpriv;
memset((unsigned char *)pwrctrlpriv, 0, sizeof(struct pwrctrl_priv));
sema_init(&pwrctrlpriv->lock, 1);
pwrctrlpriv->cpwm = PS_STATE_S4;
pwrctrlpriv->pwr_mode = PS_MODE_ACTIVE;
pwrctrlpriv->smart_ps = 0;
pwrctrlpriv->tog = 0x80;
/* clear RPWM to ensure driver and fw back to initial state. */
r8712_write8(padapter, 0x1025FE58, 0);
_init_workitem(&(pwrctrlpriv->SetPSModeWorkItem),
SetPSModeWorkItemCallback, padapter);
_init_workitem(&(pwrctrlpriv->rpwm_workitem),
rpwm_workitem_callback, padapter);
_init_timer(&(pwrctrlpriv->rpwm_check_timer),
padapter->pnetdev, rpwm_check_handler, (u8 *)padapter);
}
/*
Caller: r8712_cmd_thread
Check if the fw_pwrstate is okay for issuing cmd.
If not (cpwm should be is less than P2 state), then the sub-routine
will raise the cpwm to be greater than or equal to P2.
Calling Context: Passive
Return Value:
_SUCCESS: r8712_cmd_thread can issue cmds to firmware afterwards.
_FAIL: r8712_cmd_thread can not do anything.
*/
sint r8712_register_cmd_alive(struct _adapter *padapter)
{
uint res = _SUCCESS;
struct pwrctrl_priv *pwrctrl = &padapter->pwrctrlpriv;
_enter_pwrlock(&pwrctrl->lock);
register_task_alive(pwrctrl, CMD_ALIVE);
if (pwrctrl->cpwm < PS_STATE_S2) {
r8712_set_rpwm(padapter, PS_STATE_S3);
res = _FAIL;
}
up(&pwrctrl->lock);
return res;
}
/*
Caller: ISR
If ISR's txdone,
No more pkts for TX,
Then driver shall call this fun. to power down firmware again.
*/
void r8712_unregister_cmd_alive(struct _adapter *padapter)
{
struct pwrctrl_priv *pwrctrl = &padapter->pwrctrlpriv;
_enter_pwrlock(&pwrctrl->lock);
unregister_task_alive(pwrctrl, CMD_ALIVE);
if ((pwrctrl->cpwm > PS_STATE_S2) &&
(pwrctrl->pwr_mode > PS_MODE_ACTIVE)) {
if ((pwrctrl->alives == 0) &&
(check_fwstate(&padapter->mlmepriv,
_FW_UNDER_LINKING) != true)) {
r8712_set_rpwm(padapter, PS_STATE_S0);
}
}
up(&pwrctrl->lock);
}
|
27674b31c537d71b5363e65a65e4c18280be5cf3
|
afd2087e80478010d9df66e78280f75e1ff17d45
|
/aten/src/ATen/native/quantized/cpu/qnnpack/src/q8gemm/4x4c2-dq-sse2.c
|
c3dffa55c2b7a969371c2eb38109de2ff5dd0a54
|
[
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-secret-labs-2011",
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0"
] |
permissive
|
pytorch/pytorch
|
7521ac50c47d18b916ae47a6592c4646c2cb69b5
|
a6f7dd4707ac116c0f5fb5f44f42429f38d23ab4
|
refs/heads/main
| 2023-08-03T05:05:02.822937
| 2023-08-03T00:40:33
| 2023-08-03T04:14:52
| 65,600,975
| 77,092
| 24,610
|
NOASSERTION
| 2023-09-14T21:58:39
| 2016-08-13T05:26:41
|
Python
|
UTF-8
|
C
| false
| false
| 11,857
|
c
|
4x4c2-dq-sse2.c
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <immintrin.h>
#include <qnnpack/q8gemm.h>
#include <requantization/runtime-sse2.h>
void pytorch_q8gemm_dq_ukernel_4x4c2__sse2(
size_t mr,
size_t nr,
size_t k,
const uint8_t* restrict a,
size_t a_stride,
const void* restrict w,
const float* restrict b,
float* restrict c,
size_t c_stride,
size_t output_channel_index,
const struct pytorch_qnnp_conv_dynamic_quantization_params
quantization_params[RESTRICT_STATIC 1]) {
__m128i vacc0x0123 = _mm_setzero_si128();
__m128i vacc1x0123 = _mm_setzero_si128();
__m128i vacc2x0123 = _mm_setzero_si128();
__m128i vacc3x0123 = _mm_setzero_si128();
w = (const void*)((uintptr_t)w + 16);
const uint8_t* a0 = a;
const uint8_t* a1 = (const uint8_t*)((uintptr_t)a0 + a_stride);
if (mr < 2) {
a1 = a0;
}
const uint8_t* a2 = (const uint8_t*)((uintptr_t)a1 + a_stride);
if (mr <= 2) {
a2 = a1;
}
const uint8_t* a3 = (const uint8_t*)((uintptr_t)a2 + a_stride);
if (mr != 4) {
a3 = a2;
}
const __m128i va_zero_point = _mm_set1_epi16(quantization_params->input_zero_point);
const int16_t vb_zero_point_0 =
(int16_t)(uint16_t)quantization_params->kernel_zero_points[
output_channel_index];
const int16_t vb_zero_point_1 =
(int16_t)(uint16_t)quantization_params->kernel_zero_points[
output_channel_index + 1];
const int16_t vb_zero_point_2 =
(int16_t)(uint16_t)quantization_params->kernel_zero_points[
output_channel_index + 2];
const int16_t vb_zero_point_3 =
(int16_t)(uint16_t)quantization_params->kernel_zero_points[
output_channel_index + 3];
__m128i vb_zero_point = _mm_set_epi16(vb_zero_point_3,
vb_zero_point_3,
vb_zero_point_2,
vb_zero_point_2,
vb_zero_point_1,
vb_zero_point_1,
vb_zero_point_0,
vb_zero_point_0
);
const __m128 vmultiplier =
_mm_loadu_ps(&quantization_params->multipliers[output_channel_index]);
const __m128 vbias = _mm_load_ps(b);
const __m128i vzero = _mm_setzero_si128();
for (; k >= 8; k -= 8) {
const __m128i va0 = _mm_loadl_epi64((const __m128i*)a0);
const __m128i vxa0 =
sub_zero_point(_mm_unpacklo_epi8(va0, vzero), va_zero_point);
a0 += 8;
const __m128i va1 = _mm_loadl_epi64((const __m128i*)a1);
const __m128i vxa1 =
sub_zero_point(_mm_unpacklo_epi8(va1, vzero), va_zero_point);
a1 += 8;
const __m128i va2 = _mm_loadl_epi64((const __m128i*)a2);
const __m128i vxa2 =
sub_zero_point(_mm_unpacklo_epi8(va2, vzero), va_zero_point);
a2 += 8;
const __m128i va3 = _mm_loadl_epi64((const __m128i*)a3);
const __m128i vxa3 =
sub_zero_point(_mm_unpacklo_epi8(va3, vzero), va_zero_point);
a3 += 8;
const __m128i vb0 = _mm_loadl_epi64((const __m128i*)w);
const __m128i vxb0 =
_mm_sub_epi16(_mm_unpacklo_epi8(vb0, vzero), vb_zero_point);
vacc0x0123 = _mm_add_epi32(
vacc0x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(0, 0, 0, 0)), vxb0));
vacc1x0123 = _mm_add_epi32(
vacc1x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(0, 0, 0, 0)), vxb0));
vacc2x0123 = _mm_add_epi32(
vacc2x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa2, _MM_SHUFFLE(0, 0, 0, 0)), vxb0));
vacc3x0123 = _mm_add_epi32(
vacc3x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa3, _MM_SHUFFLE(0, 0, 0, 0)), vxb0));
const __m128i vb1 = _mm_loadl_epi64((const __m128i*)((uintptr_t)w + 8));
const __m128i vxb1 =
_mm_sub_epi16(_mm_unpacklo_epi8(vb1, vzero), vb_zero_point);
vacc0x0123 = _mm_add_epi32(
vacc0x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(1, 1, 1, 1)), vxb1));
vacc1x0123 = _mm_add_epi32(
vacc1x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(1, 1, 1, 1)), vxb1));
vacc2x0123 = _mm_add_epi32(
vacc2x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa2, _MM_SHUFFLE(1, 1, 1, 1)), vxb1));
vacc3x0123 = _mm_add_epi32(
vacc3x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa3, _MM_SHUFFLE(1, 1, 1, 1)), vxb1));
const __m128i vb2 = _mm_loadl_epi64((const __m128i*)((uintptr_t)w + 16));
const __m128i vxb2 =
_mm_sub_epi16(_mm_unpacklo_epi8(vb2, vzero), vb_zero_point);
vacc0x0123 = _mm_add_epi32(
vacc0x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(2, 2, 2, 2)), vxb2));
vacc1x0123 = _mm_add_epi32(
vacc1x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(2, 2, 2, 2)), vxb2));
vacc2x0123 = _mm_add_epi32(
vacc2x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa2, _MM_SHUFFLE(2, 2, 2, 2)), vxb2));
vacc3x0123 = _mm_add_epi32(
vacc3x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa3, _MM_SHUFFLE(2, 2, 2, 2)), vxb2));
const __m128i vb3 = _mm_loadl_epi64((const __m128i*)((uintptr_t)w + 24));
const __m128i vxb3 =
_mm_sub_epi16(_mm_unpacklo_epi8(vb3, vzero), vb_zero_point);
w = (const void*)((uintptr_t)w + 32);
vacc0x0123 = _mm_add_epi32(
vacc0x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(3, 3, 3, 3)), vxb3));
vacc1x0123 = _mm_add_epi32(
vacc1x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(3, 3, 3, 3)), vxb3));
vacc2x0123 = _mm_add_epi32(
vacc2x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa2, _MM_SHUFFLE(3, 3, 3, 3)), vxb3));
vacc3x0123 = _mm_add_epi32(
vacc3x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa3, _MM_SHUFFLE(3, 3, 3, 3)), vxb3));
}
if (k != 0) {
const size_t a_predecrement = 8 - k;
const __m128i va_shift = _mm_cvtsi32_si128(8 * a_predecrement);
const __m128i va0 = _mm_srl_epi64(
_mm_loadl_epi64((const __m128i*)(a0 - a_predecrement)), va_shift);
const __m128i vxa0 =
sub_zero_point(_mm_unpacklo_epi8(va0, vzero), va_zero_point);
const __m128i va1 = _mm_srl_epi64(
_mm_loadl_epi64((const __m128i*)(a1 - a_predecrement)), va_shift);
const __m128i vxa1 =
sub_zero_point(_mm_unpacklo_epi8(va1, vzero), va_zero_point);
const __m128i va2 = _mm_srl_epi64(
_mm_loadl_epi64((const __m128i*)(a2 - a_predecrement)), va_shift);
const __m128i vxa2 =
sub_zero_point(_mm_unpacklo_epi8(va2, vzero), va_zero_point);
const __m128i va3 = _mm_srl_epi64(
_mm_loadl_epi64((const __m128i*)(a3 - a_predecrement)), va_shift);
const __m128i vxa3 =
sub_zero_point(_mm_unpacklo_epi8(va3, vzero), va_zero_point);
const __m128i vb0 = _mm_loadl_epi64((const __m128i*)w);
const __m128i vxb0 =
_mm_sub_epi16(_mm_unpacklo_epi8(vb0, vzero), vb_zero_point);
vacc0x0123 = _mm_add_epi32(
vacc0x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(0, 0, 0, 0)), vxb0));
vacc1x0123 = _mm_add_epi32(
vacc1x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(0, 0, 0, 0)), vxb0));
vacc2x0123 = _mm_add_epi32(
vacc2x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa2, _MM_SHUFFLE(0, 0, 0, 0)), vxb0));
vacc3x0123 = _mm_add_epi32(
vacc3x0123,
_mm_madd_epi16(_mm_shuffle_epi32(vxa3, _MM_SHUFFLE(0, 0, 0, 0)), vxb0));
if (k > 2) {
const __m128i vb1 = _mm_loadl_epi64((const __m128i*)((uintptr_t)w + 8));
const __m128i vxb1 =
_mm_sub_epi16(_mm_unpacklo_epi8(vb1, vzero), vb_zero_point);
vacc0x0123 = _mm_add_epi32(
vacc0x0123,
_mm_madd_epi16(
_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(1, 1, 1, 1)), vxb1));
vacc1x0123 = _mm_add_epi32(
vacc1x0123,
_mm_madd_epi16(
_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(1, 1, 1, 1)), vxb1));
vacc2x0123 = _mm_add_epi32(
vacc2x0123,
_mm_madd_epi16(
_mm_shuffle_epi32(vxa2, _MM_SHUFFLE(1, 1, 1, 1)), vxb1));
vacc3x0123 = _mm_add_epi32(
vacc3x0123,
_mm_madd_epi16(
_mm_shuffle_epi32(vxa3, _MM_SHUFFLE(1, 1, 1, 1)), vxb1));
if (k > 4) {
const __m128i vb2 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 16));
const __m128i vxb2 =
_mm_sub_epi16(_mm_unpacklo_epi8(vb2, vzero), vb_zero_point);
vacc0x0123 = _mm_add_epi32(
vacc0x0123,
_mm_madd_epi16(
_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(2, 2, 2, 2)), vxb2));
vacc1x0123 = _mm_add_epi32(
vacc1x0123,
_mm_madd_epi16(
_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(2, 2, 2, 2)), vxb2));
vacc2x0123 = _mm_add_epi32(
vacc2x0123,
_mm_madd_epi16(
_mm_shuffle_epi32(vxa2, _MM_SHUFFLE(2, 2, 2, 2)), vxb2));
vacc3x0123 = _mm_add_epi32(
vacc3x0123,
_mm_madd_epi16(
_mm_shuffle_epi32(vxa3, _MM_SHUFFLE(2, 2, 2, 2)), vxb2));
if (k > 6) {
const __m128i vb3 =
_mm_loadl_epi64((const __m128i*)((uintptr_t)w + 24));
const __m128i vxb3 =
_mm_sub_epi16(_mm_unpacklo_epi8(vb3, vzero), vb_zero_point);
vacc0x0123 = _mm_add_epi32(
vacc0x0123,
_mm_madd_epi16(
_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(3, 3, 3, 3)), vxb3));
vacc1x0123 = _mm_add_epi32(
vacc1x0123,
_mm_madd_epi16(
_mm_shuffle_epi32(vxa1, _MM_SHUFFLE(3, 3, 3, 3)), vxb3));
vacc2x0123 = _mm_add_epi32(
vacc2x0123,
_mm_madd_epi16(
_mm_shuffle_epi32(vxa2, _MM_SHUFFLE(3, 3, 3, 3)), vxb3));
vacc3x0123 = _mm_add_epi32(
vacc3x0123,
_mm_madd_epi16(
_mm_shuffle_epi32(vxa3, _MM_SHUFFLE(3, 3, 3, 3)), vxb3));
}
}
}
}
__m128 vout0 = _mm_mul_ps(vmultiplier, _mm_cvtepi32_ps(vacc0x0123));
__m128 vout1 = _mm_mul_ps(vmultiplier, _mm_cvtepi32_ps(vacc1x0123));
__m128 vout2 = _mm_mul_ps(vmultiplier, _mm_cvtepi32_ps(vacc2x0123));
__m128 vout3 = _mm_mul_ps(vmultiplier, _mm_cvtepi32_ps(vacc3x0123));
vout0 = _mm_add_ps(vout0, vbias);
vout1 = _mm_add_ps(vout1, vbias);
vout2 = _mm_add_ps(vout2, vbias);
vout3 = _mm_add_ps(vout3, vbias);
float* c0 = c;
float* c1 = c0 + c_stride;
if (mr < 2) {
c1 = c0;
}
float* c2 = c1 + c_stride;
if (mr <= 2) {
c2 = c1;
}
float* c3 = c2 + c_stride;
if (mr != 4) {
c3 = c2;
}
if (nr == 4) {
_mm_storeu_ps(c0, vout0);
_mm_storeu_ps(c1, vout1);
_mm_storeu_ps(c2, vout2);
_mm_storeu_ps(c3, vout3);
} else {
if (nr >= 2) {
_mm_storel_pi((__m64*)c0, vout0);
_mm_storel_pi((__m64*)c1, vout1);
_mm_storel_pi((__m64*)c2, vout2);
_mm_storel_pi((__m64*)c3, vout3);
c0 += 2;
vout0 = _mm_shuffle_ps(vout0, vout0, _MM_SHUFFLE(2, 2, 2, 2));
c1 += 2;
vout1 = _mm_shuffle_ps(vout1, vout1, _MM_SHUFFLE(2, 2, 2, 2));
c2 += 2;
vout2 = _mm_shuffle_ps(vout2, vout2, _MM_SHUFFLE(2, 2, 2, 2));
c3 += 2;
vout3 = _mm_shuffle_ps(vout3, vout3, _MM_SHUFFLE(2, 2, 2, 2));
nr -= 2;
}
if (nr != 0) {
*c0 = _mm_cvtss_f32(vout0);
*c1 = _mm_cvtss_f32(vout1);
*c2 = _mm_cvtss_f32(vout2);
*c3 = _mm_cvtss_f32(vout3);
}
}
}
|
5fcfd67a0a47950bc090025c914ca160c54362ba
|
8af0df63825350e791f95025b0873c80959454bd
|
/linalg/matmul-bench/c/packed_tile_8x8.c
|
da307491a3caefd8899f1585046637fad5a7930c
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
sonos/tract
|
7ec383b3ec8b8c9f4a6feac65d4375de43976c21
|
77231e2aea26efa71fc657f0b1f96b1a35bcc916
|
refs/heads/main
| 2023-09-01T02:14:35.596072
| 2023-08-31T07:10:27
| 2023-08-31T10:59:16
| 99,561,213
| 1,239
| 111
|
NOASSERTION
| 2023-09-13T20:35:02
| 2017-08-07T09:31:26
|
Rust
|
UTF-8
|
C
| false
| false
| 8,658
|
c
|
packed_tile_8x8.c
|
#include <stddef.h>
void c_packed_tile_8x8(size_t m, size_t k, size_t n, float *a, float *b, float *c) {
for(size_t row = 0 ; row < m / 8 ; row++) {
for(size_t col = 0 ; col < n / 8 ; col++) {
float sum00 = 0.0;
float sum01 = 0.0;
float sum02 = 0.0;
float sum03 = 0.0;
float sum04 = 0.0;
float sum05 = 0.0;
float sum06 = 0.0;
float sum07 = 0.0;
float sum10 = 0.0;
float sum11 = 0.0;
float sum12 = 0.0;
float sum13 = 0.0;
float sum14 = 0.0;
float sum15 = 0.0;
float sum16 = 0.0;
float sum17 = 0.0;
float sum20 = 0.0;
float sum21 = 0.0;
float sum22 = 0.0;
float sum23 = 0.0;
float sum24 = 0.0;
float sum25 = 0.0;
float sum26 = 0.0;
float sum27 = 0.0;
float sum30 = 0.0;
float sum31 = 0.0;
float sum32 = 0.0;
float sum33 = 0.0;
float sum34 = 0.0;
float sum35 = 0.0;
float sum36 = 0.0;
float sum37 = 0.0;
float sum40 = 0.0;
float sum41 = 0.0;
float sum42 = 0.0;
float sum43 = 0.0;
float sum44 = 0.0;
float sum45 = 0.0;
float sum46 = 0.0;
float sum47 = 0.0;
float sum50 = 0.0;
float sum51 = 0.0;
float sum52 = 0.0;
float sum53 = 0.0;
float sum54 = 0.0;
float sum55 = 0.0;
float sum56 = 0.0;
float sum57 = 0.0;
float sum60 = 0.0;
float sum61 = 0.0;
float sum62 = 0.0;
float sum63 = 0.0;
float sum64 = 0.0;
float sum65 = 0.0;
float sum66 = 0.0;
float sum67 = 0.0;
float sum70 = 0.0;
float sum71 = 0.0;
float sum72 = 0.0;
float sum73 = 0.0;
float sum74 = 0.0;
float sum75 = 0.0;
float sum76 = 0.0;
float sum77 = 0.0;
float *pa = a + row * k * 8;
float *pb = b + col * k * 8;
for(size_t i = 0 ; i < k ; i++) {
float a0 = a[0];
float a1 = a[1];
float a2 = a[2];
float a3 = a[3];
float a4 = a[4];
float a5 = a[5];
float a6 = a[6];
float a7 = a[7];
float b0 = b[0];
float b1 = b[1];
float b2 = b[2];
float b3 = b[3];
float b4 = b[4];
float b5 = b[5];
float b6 = b[6];
float b7 = b[7];
pa += 8;
pb += 8;
sum00 += a0 * b0;
sum01 += a0 * b1;
sum02 += a0 * b2;
sum03 += a0 * b3;
sum04 += a0 * b4;
sum05 += a0 * b5;
sum06 += a0 * b6;
sum07 += a0 * b7;
sum10 += a1 * b0;
sum11 += a1 * b1;
sum12 += a1 * b2;
sum13 += a1 * b3;
sum14 += a1 * b4;
sum15 += a1 * b5;
sum16 += a1 * b6;
sum17 += a1 * b7;
sum20 += a2 * b0;
sum21 += a2 * b1;
sum22 += a2 * b2;
sum23 += a2 * b3;
sum24 += a2 * b4;
sum25 += a2 * b5;
sum26 += a2 * b6;
sum27 += a2 * b7;
sum30 += a3 * b0;
sum31 += a3 * b1;
sum32 += a3 * b2;
sum33 += a3 * b3;
sum34 += a3 * b4;
sum35 += a3 * b5;
sum36 += a3 * b6;
sum37 += a3 * b7;
sum40 += a4 * b0;
sum41 += a4 * b1;
sum42 += a4 * b2;
sum43 += a4 * b3;
sum44 += a4 * b4;
sum45 += a4 * b5;
sum46 += a4 * b6;
sum47 += a4 * b7;
sum50 += a5 * b0;
sum51 += a5 * b1;
sum52 += a5 * b2;
sum53 += a5 * b3;
sum54 += a5 * b4;
sum55 += a5 * b5;
sum56 += a5 * b6;
sum57 += a5 * b7;
sum60 += a6 * b0;
sum61 += a6 * b1;
sum62 += a6 * b2;
sum63 += a6 * b3;
sum64 += a6 * b4;
sum65 += a6 * b5;
sum66 += a6 * b6;
sum67 += a6 * b7;
sum70 += a7 * b0;
sum71 += a7 * b1;
sum72 += a7 * b2;
sum73 += a7 * b3;
sum74 += a7 * b4;
sum75 += a7 * b5;
sum76 += a7 * b6;
sum77 += a7 * b7;
}
c[(row * 8 + 0) * n + col * 8] = sum00;
c[(row * 8 + 0) * n + col * 8 + 1] = sum01;
c[(row * 8 + 0) * n + col * 8 + 2] = sum02;
c[(row * 8 + 0) * n + col * 8 + 3] = sum03;
c[(row * 8 + 0) * n + col * 8 + 4] = sum04;
c[(row * 8 + 0) * n + col * 8 + 5] = sum05;
c[(row * 8 + 0) * n + col * 8 + 6] = sum06;
c[(row * 8 + 0) * n + col * 8 + 7] = sum07;
c[(row * 8 + 1) * n + col * 8] = sum10;
c[(row * 8 + 1) * n + col * 8 + 1] = sum11;
c[(row * 8 + 1) * n + col * 8 + 2] = sum12;
c[(row * 8 + 1) * n + col * 8 + 3] = sum13;
c[(row * 8 + 1) * n + col * 8 + 4] = sum14;
c[(row * 8 + 1) * n + col * 8 + 5] = sum15;
c[(row * 8 + 1) * n + col * 8 + 6] = sum16;
c[(row * 8 + 1) * n + col * 8 + 7] = sum17;
c[(row * 8 + 2) * n + col * 8] = sum20;
c[(row * 8 + 2) * n + col * 8 + 1] = sum21;
c[(row * 8 + 2) * n + col * 8 + 2] = sum22;
c[(row * 8 + 2) * n + col * 8 + 3] = sum23;
c[(row * 8 + 2) * n + col * 8 + 4] = sum24;
c[(row * 8 + 2) * n + col * 8 + 5] = sum25;
c[(row * 8 + 2) * n + col * 8 + 6] = sum26;
c[(row * 8 + 2) * n + col * 8 + 7] = sum27;
c[(row * 8 + 3) * n + col * 8] = sum30;
c[(row * 8 + 3) * n + col * 8 + 1] = sum31;
c[(row * 8 + 3) * n + col * 8 + 2] = sum32;
c[(row * 8 + 3) * n + col * 8 + 3] = sum33;
c[(row * 8 + 3) * n + col * 8 + 4] = sum34;
c[(row * 8 + 3) * n + col * 8 + 5] = sum35;
c[(row * 8 + 3) * n + col * 8 + 6] = sum36;
c[(row * 8 + 3) * n + col * 8 + 7] = sum37;
c[(row * 8 + 4) * n + col * 8] = sum40;
c[(row * 8 + 4) * n + col * 8 + 1] = sum41;
c[(row * 8 + 4) * n + col * 8 + 2] = sum42;
c[(row * 8 + 4) * n + col * 8 + 3] = sum43;
c[(row * 8 + 4) * n + col * 8 + 4] = sum44;
c[(row * 8 + 4) * n + col * 8 + 5] = sum45;
c[(row * 8 + 4) * n + col * 8 + 6] = sum46;
c[(row * 8 + 4) * n + col * 8 + 7] = sum47;
c[(row * 8 + 5) * n + col * 8] = sum50;
c[(row * 8 + 5) * n + col * 8 + 1] = sum51;
c[(row * 8 + 5) * n + col * 8 + 2] = sum52;
c[(row * 8 + 5) * n + col * 8 + 3] = sum53;
c[(row * 8 + 5) * n + col * 8 + 4] = sum54;
c[(row * 8 + 5) * n + col * 8 + 5] = sum55;
c[(row * 8 + 5) * n + col * 8 + 6] = sum56;
c[(row * 8 + 5) * n + col * 8 + 7] = sum57;
c[(row * 8 + 6) * n + col * 8] = sum60;
c[(row * 8 + 6) * n + col * 8 + 1] = sum61;
c[(row * 8 + 6) * n + col * 8 + 2] = sum62;
c[(row * 8 + 6) * n + col * 8 + 3] = sum63;
c[(row * 8 + 6) * n + col * 8 + 4] = sum64;
c[(row * 8 + 6) * n + col * 8 + 5] = sum65;
c[(row * 8 + 6) * n + col * 8 + 6] = sum66;
c[(row * 8 + 6) * n + col * 8 + 7] = sum67;
c[(row * 8 + 7) * n + col * 8] = sum70;
c[(row * 8 + 7) * n + col * 8 + 1] = sum71;
c[(row * 8 + 7) * n + col * 8 + 2] = sum72;
c[(row * 8 + 7) * n + col * 8 + 3] = sum73;
c[(row * 8 + 7) * n + col * 8 + 4] = sum74;
c[(row * 8 + 7) * n + col * 8 + 5] = sum75;
c[(row * 8 + 7) * n + col * 8 + 6] = sum76;
c[(row * 8 + 7) * n + col * 8 + 7] = sum77;
}
}
}
|
b6c87c2e3885e48ad175ffe6782be796a2961e30
|
75732426f13d523ab1c7be7bee23c2152eb9a77c
|
/bundles/pubsub/pubsub_admin_tcp/src/pubsub_tcp_admin.c
|
608b004eb85b234f3081f78d2cead62ec18f8171
|
[
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LGPL-2.0-or-later"
] |
permissive
|
apache/celix
|
841da4d364432bff49c796f908d64090cec1d759
|
28118976b802f421f4789ece0c15e791f542712f
|
refs/heads/master
| 2023-09-04T22:17:43.815664
| 2023-09-04T01:22:00
| 2023-09-04T01:22:00
| 22,781,134
| 158
| 114
|
Apache-2.0
| 2023-09-12T01:22:30
| 2014-08-09T07:00:07
|
C
|
UTF-8
|
C
| false
| false
| 31,796
|
c
|
pubsub_tcp_admin.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 <memory.h>
#include <pubsub_endpoint.h>
#include <pubsub_serializer.h>
#include <ip_utils.h>
#include <pubsub_matching.h>
#include "pubsub_utils.h"
#include "pubsub_tcp_admin.h"
#include "pubsub_tcp_handler.h"
#include "pubsub_psa_tcp_constants.h"
#include "pubsub_tcp_topic_sender.h"
#include "pubsub_tcp_topic_receiver.h"
#include "celix_compiler.h"
#include "celix_constants.h"
#define L_DEBUG(...) \
celix_logHelper_log(psa->log, CELIX_LOG_LEVEL_DEBUG, __VA_ARGS__)
#define L_INFO(...) \
celix_logHelper_log(psa->log, CELIX_LOG_LEVEL_INFO, __VA_ARGS__)
#define L_WARN(...) \
celix_logHelper_log(psa->log, CELIX_LOG_LEVEL_WARNING, __VA_ARGS__)
#define L_ERROR(...) \
celix_logHelper_log(psa->log, CELIX_LOG_LEVEL_ERROR, __VA_ARGS__)
struct pubsub_tcp_admin {
celix_bundle_context_t *ctx;
celix_log_helper_t *log;
const char *fwUUID;
char *ipAddress;
unsigned int basePort;
double qosSampleScore;
double qosControlScore;
double defaultScore;
bool verbose;
struct {
celix_thread_mutex_t mutex;
hash_map_t *map; //key = svcId, value = psa_tcp_protocol_entry_t*
} protocols;
struct {
celix_thread_mutex_t mutex;
hash_map_t *map; //key = scope:topic key, value = pubsub_tcp_topic_sender_t*
} topicSenders;
struct {
celix_thread_mutex_t mutex;
hash_map_t *map; //key = scope:topic key, value = pubsub_tcp_topic_sender_t*
} topicReceivers;
struct {
celix_thread_mutex_t mutex;
hash_map_t *map; //key = endpoint uuid, value = celix_properties_t* (endpoint)
} discoveredEndpoints;
struct {
celix_thread_mutex_t mutex;
hash_map_t *map; //key = pubsub message serialization marker svc id (long), pubsub_serialization_handler_t*.
} serializationHandlers;
pubsub_tcp_endPointStore_t endpointStore;
};
typedef struct psa_tcp_protocol_entry {
const char *protType;
long svcId;
pubsub_protocol_service_t *svc;
} psa_tcp_protocol_entry_t;
static celix_status_t
pubsub_tcpAdmin_connectEndpointToReceiver(pubsub_tcp_admin_t *psa, pubsub_tcp_topic_receiver_t *receiver,
const celix_properties_t *endpoint);
static celix_status_t
pubsub_tcpAdmin_disconnectEndpointFromReceiver(pubsub_tcp_admin_t *psa, pubsub_tcp_topic_receiver_t *receiver,
const celix_properties_t *endpoint);
static bool pubsub_tcpAdmin_endpointIsPublisher(const celix_properties_t *endpoint) {
const char *type = celix_properties_get(endpoint, PUBSUB_ENDPOINT_TYPE, NULL);
return type != NULL && strncmp(PUBSUB_PUBLISHER_ENDPOINT_TYPE, type, strlen(PUBSUB_PUBLISHER_ENDPOINT_TYPE)) == 0;
}
pubsub_tcp_admin_t *pubsub_tcpAdmin_create(celix_bundle_context_t *ctx, celix_log_helper_t *logHelper) {
pubsub_tcp_admin_t *psa = calloc(1, sizeof(*psa));
psa->ctx = ctx;
psa->log = logHelper;
psa->verbose = celix_bundleContext_getPropertyAsBool(ctx, PUBSUB_TCP_VERBOSE_KEY, PUBSUB_TCP_VERBOSE_DEFAULT);
psa->fwUUID = celix_bundleContext_getProperty(ctx, OSGI_FRAMEWORK_FRAMEWORK_UUID, NULL);
long basePort = celix_bundleContext_getPropertyAsLong(ctx, PSA_TCP_BASE_PORT, PSA_TCP_DEFAULT_BASE_PORT);
psa->basePort = (unsigned int) basePort;
psa->defaultScore = celix_bundleContext_getPropertyAsDouble(ctx, PSA_TCP_DEFAULT_SCORE_KEY, PSA_TCP_DEFAULT_SCORE);
psa->qosSampleScore = celix_bundleContext_getPropertyAsDouble(ctx, PSA_TCP_QOS_SAMPLE_SCORE_KEY,
PSA_TCP_DEFAULT_QOS_SAMPLE_SCORE);
psa->qosControlScore = celix_bundleContext_getPropertyAsDouble(ctx, PSA_TCP_QOS_CONTROL_SCORE_KEY,
PSA_TCP_DEFAULT_QOS_CONTROL_SCORE);
celixThreadMutex_create(&psa->protocols.mutex, NULL);
psa->protocols.map = hashMap_create(NULL, NULL, NULL, NULL);
celixThreadMutex_create(&psa->topicSenders.mutex, NULL);
psa->topicSenders.map = hashMap_create(utils_stringHash, NULL, utils_stringEquals, NULL);
celixThreadMutex_create(&psa->topicReceivers.mutex, NULL);
psa->topicReceivers.map = hashMap_create(utils_stringHash, NULL, utils_stringEquals, NULL);
celixThreadMutex_create(&psa->discoveredEndpoints.mutex, NULL);
psa->discoveredEndpoints.map = hashMap_create(utils_stringHash, NULL, utils_stringEquals, NULL);
celixThreadMutex_create(&psa->endpointStore.mutex, NULL);
psa->endpointStore.map = hashMap_create(utils_stringHash, NULL, utils_stringEquals, NULL);
celixThreadMutex_create(&psa->serializationHandlers.mutex, NULL);
psa->serializationHandlers.map = hashMap_create(NULL, NULL, NULL, NULL);
return psa;
}
void pubsub_tcpAdmin_destroy(pubsub_tcp_admin_t *psa) {
if (psa == NULL) {
return;
}
celixThreadMutex_lock(&psa->endpointStore.mutex);
hash_map_iterator_t iter = hashMapIterator_construct(psa->endpointStore.map);
while (hashMapIterator_hasNext(&iter)) {
pubsub_tcpHandler_t *tcpHandler = hashMapIterator_nextValue(&iter);
pubsub_tcpHandler_destroy(tcpHandler);
}
celixThreadMutex_unlock(&psa->endpointStore.mutex);
celixThreadMutex_lock(&psa->topicSenders.mutex);
iter = hashMapIterator_construct(psa->topicSenders.map);
while (hashMapIterator_hasNext(&iter)) {
pubsub_tcp_topic_sender_t *sender = hashMapIterator_nextValue(&iter);
pubsub_tcpTopicSender_destroy(sender);
}
celixThreadMutex_unlock(&psa->topicSenders.mutex);
celixThreadMutex_lock(&psa->topicReceivers.mutex);
iter = hashMapIterator_construct(psa->topicReceivers.map);
while (hashMapIterator_hasNext(&iter)) {
pubsub_tcp_topic_receiver_t *recv = hashMapIterator_nextValue(&iter);
pubsub_tcpTopicReceiver_destroy(recv);
}
celixThreadMutex_unlock(&psa->topicReceivers.mutex);
celixThreadMutex_lock(&psa->discoveredEndpoints.mutex);
iter = hashMapIterator_construct(psa->discoveredEndpoints.map);
while (hashMapIterator_hasNext(&iter)) {
celix_properties_t *ep = hashMapIterator_nextValue(&iter);
celix_properties_destroy(ep);
}
celixThreadMutex_unlock(&psa->discoveredEndpoints.mutex);
celixThreadMutex_lock(&psa->serializationHandlers.mutex);
iter = hashMapIterator_construct(psa->serializationHandlers.map);
while (hashMapIterator_hasNext(&iter)) {
pubsub_serializer_handler_t* entry = hashMapIterator_nextValue(&iter);
pubsub_serializerHandler_destroy(entry);
}
celixThreadMutex_unlock(&psa->serializationHandlers.mutex);
celixThreadMutex_lock(&psa->protocols.mutex);
iter = hashMapIterator_construct(psa->protocols.map);
while (hashMapIterator_hasNext(&iter)) {
psa_tcp_protocol_entry_t *entry = hashMapIterator_nextValue(&iter);
free(entry);
}
celixThreadMutex_unlock(&psa->protocols.mutex);
//note assuming al psa register services and service tracker are removed.
celixThreadMutex_destroy(&psa->endpointStore.mutex);
hashMap_destroy(psa->endpointStore.map, false, false);
celixThreadMutex_destroy(&psa->topicSenders.mutex);
hashMap_destroy(psa->topicSenders.map, true, false);
celixThreadMutex_destroy(&psa->topicReceivers.mutex);
hashMap_destroy(psa->topicReceivers.map, true, false);
celixThreadMutex_destroy(&psa->discoveredEndpoints.mutex);
hashMap_destroy(psa->discoveredEndpoints.map, false, false);
celixThreadMutex_destroy(&psa->serializationHandlers.mutex);
hashMap_destroy(psa->serializationHandlers.map, false, false);
celixThreadMutex_destroy(&psa->protocols.mutex);
hashMap_destroy(psa->protocols.map, false, false);
free(psa->ipAddress);
free(psa);
}
void pubsub_tcpAdmin_addProtocolSvc(void *handle, void *svc, const celix_properties_t *props) {
pubsub_tcp_admin_t *psa = handle;
const char *protType = celix_properties_get(props, PUBSUB_PROTOCOL_TYPE_KEY, NULL);
long svcId = celix_properties_getAsLong(props, OSGI_FRAMEWORK_SERVICE_ID, -1L);
if (protType == NULL) {
L_INFO("[PSA_tcp] Ignoring protocol service without %s property", PUBSUB_PROTOCOL_TYPE_KEY);
return;
}
celixThreadMutex_lock(&psa->protocols.mutex);
psa_tcp_protocol_entry_t *entry = hashMap_get(psa->protocols.map, (void *) svcId);
if (entry == NULL) {
entry = calloc(1, sizeof(*entry));
entry->protType = protType;
entry->svcId = svcId;
entry->svc = svc;
hashMap_put(psa->protocols.map, (void *) svcId, entry);
}
celixThreadMutex_unlock(&psa->protocols.mutex);
}
void pubsub_tcpAdmin_removeProtocolSvc(void *handle, void *svc, const celix_properties_t *props) {
pubsub_tcp_admin_t *psa = handle;
long svcId = celix_properties_getAsLong(props, OSGI_FRAMEWORK_SERVICE_ID, -1L);
//remove protocol
// 1) First find entry and
// 2) loop and destroy all topic sender using the protocol and
// 3) loop and destroy all topic receivers using the protocol
// Note that it is the responsibility of the topology manager to create new topic senders/receivers
celixThreadMutex_lock(&psa->protocols.mutex);
psa_tcp_protocol_entry_t *entry = hashMap_remove(psa->protocols.map, (void *) svcId);
celixThreadMutex_unlock(&psa->protocols.mutex);
if (entry != NULL) {
celixThreadMutex_lock(&psa->topicSenders.mutex);
hash_map_iterator_t iter = hashMapIterator_construct(psa->topicSenders.map);
while (hashMapIterator_hasNext(&iter)) {
hash_map_entry_t *senderEntry = hashMapIterator_nextEntry(&iter);
pubsub_tcp_topic_sender_t *sender = hashMapEntry_getValue(senderEntry);
if (sender != NULL && entry->svcId == pubsub_tcpTopicSender_protocolSvcId(sender)) {
char *key = hashMapEntry_getKey(senderEntry);
hashMapIterator_remove(&iter);
pubsub_tcpTopicSender_destroy(sender);
free(key);
}
}
celixThreadMutex_unlock(&psa->topicSenders.mutex);
celixThreadMutex_lock(&psa->topicReceivers.mutex);
iter = hashMapIterator_construct(psa->topicReceivers.map);
while (hashMapIterator_hasNext(&iter)) {
hash_map_entry_t *senderEntry = hashMapIterator_nextEntry(&iter);
pubsub_tcp_topic_receiver_t *receiver = hashMapEntry_getValue(senderEntry);
if (receiver != NULL && entry->svcId == pubsub_tcpTopicReceiver_protocolSvcId(receiver)) {
char *key = hashMapEntry_getKey(senderEntry);
hashMapIterator_remove(&iter);
pubsub_tcpTopicReceiver_destroy(receiver);
free(key);
}
}
celixThreadMutex_unlock(&psa->topicReceivers.mutex);
free(entry);
}
}
celix_status_t pubsub_tcpAdmin_matchPublisher(void *handle, long svcRequesterBndId, const celix_filter_t *svcFilter,
celix_properties_t **topicProperties, double *outScore,
long *outSerializerSvcId, long *outProtocolSvcId) {
pubsub_tcp_admin_t *psa = handle;
L_DEBUG("[PSA_TCP_V2] pubsub_tcpAdmin_matchPublisher");
celix_status_t status = CELIX_SUCCESS;
double score = pubsub_utils_matchPublisher(psa->ctx, svcRequesterBndId, svcFilter->filterStr, PUBSUB_TCP_ADMIN_TYPE,
psa->qosSampleScore, psa->qosControlScore, psa->defaultScore, true, topicProperties, outSerializerSvcId, outProtocolSvcId);
*outScore = score;
return status;
}
celix_status_t
pubsub_tcpAdmin_matchSubscriber(void *handle, long svcProviderBndId, const celix_properties_t *svcProperties,
celix_properties_t **topicProperties, double *outScore, long *outSerializerSvcId,
long *outProtocolSvcId) {
pubsub_tcp_admin_t *psa = handle;
L_DEBUG("[PSA_TCP_V2] pubsub_tcpAdmin_matchSubscriber");
celix_status_t status = CELIX_SUCCESS;
double score = pubsub_utils_matchSubscriber(psa->ctx, svcProviderBndId, svcProperties, PUBSUB_TCP_ADMIN_TYPE,
psa->qosSampleScore, psa->qosControlScore, psa->defaultScore, true, topicProperties, outSerializerSvcId, outProtocolSvcId);
if (outScore != NULL) {
*outScore = score;
}
return status;
}
celix_status_t
pubsub_tcpAdmin_matchDiscoveredEndpoint(void *handle, const celix_properties_t *endpoint, bool *outMatch) {
pubsub_tcp_admin_t *psa = handle;
L_DEBUG("[PSA_TCP_V2] pubsub_tcpAdmin_matchEndpoint");
celix_status_t status = CELIX_SUCCESS;
bool match = pubsub_utils_matchEndpoint(psa->ctx, psa->log, endpoint, PUBSUB_TCP_ADMIN_TYPE, true, NULL, NULL);
if (outMatch != NULL) {
*outMatch = match;
}
return status;
}
static pubsub_serializer_handler_t* pubsub_tcpAdmin_getSerializationHandler(pubsub_tcp_admin_t* psa, long msgSerializationMarkerSvcId) {
pubsub_serializer_handler_t* handler = NULL;
celixThreadMutex_lock(&psa->serializationHandlers.mutex);
handler = hashMap_get(psa->serializationHandlers.map, (void*)msgSerializationMarkerSvcId);
if (handler == NULL) {
handler = pubsub_serializerHandler_createForMarkerService(psa->ctx, msgSerializationMarkerSvcId, psa->log);
if (handler != NULL) {
hashMap_put(psa->serializationHandlers.map, (void*)msgSerializationMarkerSvcId, handler);
}
}
celixThreadMutex_unlock(&psa->serializationHandlers.mutex);
return handler;
}
celix_status_t pubsub_tcpAdmin_setupTopicSender(void *handle, const char *scope, const char *topic,
const celix_properties_t *topicProperties, long serializerSvcId,
long protocolSvcId, celix_properties_t **outPublisherEndpoint) {
pubsub_tcp_admin_t *psa = handle;
celix_status_t status = CELIX_SUCCESS;
//1) Get serialization handler
//2) Create TopicSender
//3) Store TopicSender
//4) Connect existing endpoints
//5) set outPublisherEndpoint
pubsub_serializer_handler_t* handler = pubsub_tcpAdmin_getSerializationHandler(psa, serializerSvcId);
if (handler == NULL) {
L_ERROR("Cannot create topic sender without serialization handler");
return CELIX_ILLEGAL_STATE;
}
celix_properties_t *newEndpoint = NULL;
char *key = pubsubEndpoint_createScopeTopicKey(scope, topic);
celixThreadMutex_lock(&psa->protocols.mutex);
celixThreadMutex_lock(&psa->topicSenders.mutex);
pubsub_tcp_topic_sender_t *sender = hashMap_get(psa->topicSenders.map, key);
celixThreadMutex_unlock(&psa->topicSenders.mutex);
if (sender == NULL) {
psa_tcp_protocol_entry_t *protEntry = hashMap_get(psa->protocols.map, (void *) protocolSvcId);
if (protEntry != NULL) {
sender = pubsub_tcpTopicSender_create(psa->ctx, psa->log, scope, topic, handler, handle, topicProperties,
&psa->endpointStore, protocolSvcId,
protEntry->svc);
}
if (sender != NULL) {
const char *psaType = PUBSUB_TCP_ADMIN_TYPE;
const char *protType = protEntry->protType;
newEndpoint = pubsubEndpoint_create(psa->fwUUID, scope, topic, PUBSUB_PUBLISHER_ENDPOINT_TYPE, psaType,
pubsub_serializerHandler_getSerializationType(handler), protType, NULL);
celix_properties_set(newEndpoint, PUBSUB_TCP_URL_KEY, pubsub_tcpTopicSender_url(sender));
celix_properties_setBool(newEndpoint, PUBSUB_TCP_STATIC_CONFIGURED, pubsub_tcpTopicSender_isStatic(sender));
if (pubsub_tcpTopicSender_isPassive(sender)) {
celix_properties_set(newEndpoint, PUBSUB_ENDPOINT_VISIBILITY, PUBSUB_ENDPOINT_LOCAL_VISIBILITY);
} else {
celix_properties_set(newEndpoint, PUBSUB_ENDPOINT_VISIBILITY, PUBSUB_ENDPOINT_SYSTEM_VISIBILITY);
}
//if available also set container name
const char *cn = celix_bundleContext_getProperty(psa->ctx, "CELIX_CONTAINER_NAME", NULL);
if (cn != NULL)
celix_properties_set(newEndpoint, "container_name", cn);
celixThreadMutex_lock(&psa->topicSenders.mutex);
hashMap_put(psa->topicSenders.map, key, sender);
celixThreadMutex_unlock(&psa->topicSenders.mutex);
} else {
L_ERROR("[PSA_TCP_V2] Error creating a TopicSender");
free(key);
}
} else {
free(key);
L_ERROR("[PSA_TCP_V2] Cannot setup already existing TopicSender for scope/topic %s/%s!", scope, topic);
}
celixThreadMutex_unlock(&psa->protocols.mutex);
if (newEndpoint != NULL && outPublisherEndpoint != NULL) {
*outPublisherEndpoint = newEndpoint;
}
return status;
}
celix_status_t pubsub_tcpAdmin_teardownTopicSender(void *handle, const char *scope, const char *topic) {
pubsub_tcp_admin_t *psa = handle;
celix_status_t status = CELIX_SUCCESS;
//1) Find and remove TopicSender from map
//2) destroy topic sender
char *key = pubsubEndpoint_createScopeTopicKey(scope, topic);
celixThreadMutex_lock(&psa->topicSenders.mutex);
hash_map_entry_t *entry = hashMap_getEntry(psa->topicSenders.map, key);
if (entry != NULL) {
char *mapKey = hashMapEntry_getKey(entry);
pubsub_tcp_topic_sender_t *sender = hashMap_remove(psa->topicSenders.map, key);
celixThreadMutex_unlock(&psa->topicSenders.mutex);
free(mapKey);
pubsub_tcpTopicSender_destroy(sender);
} else {
celixThreadMutex_unlock(&psa->topicSenders.mutex);
L_ERROR("[PSA_TCP_V2] Cannot teardown TopicSender with scope/topic %s/%s. Does not exists",
scope == NULL ? "(null)" : scope,
topic);
}
free(key);
return status;
}
celix_status_t pubsub_tcpAdmin_setupTopicReceiver(void *handle, const char *scope, const char *topic,
const celix_properties_t *topicProperties, long serializerSvcId,
long protocolSvcId, celix_properties_t **outSubscriberEndpoint) {
pubsub_tcp_admin_t *psa = handle;
pubsub_serializer_handler_t* handler = pubsub_tcpAdmin_getSerializationHandler(psa, serializerSvcId);
if (handler == NULL) {
L_ERROR("Cannot create topic receiver without serialization handler");
return CELIX_ILLEGAL_STATE;
}
celix_properties_t *newEndpoint = NULL;
char *key = pubsubEndpoint_createScopeTopicKey(scope, topic);
celixThreadMutex_lock(&psa->protocols.mutex);
celixThreadMutex_lock(&psa->topicReceivers.mutex);
pubsub_tcp_topic_receiver_t *receiver = hashMap_get(psa->topicReceivers.map, key);
celixThreadMutex_unlock(&psa->topicReceivers.mutex);
if (receiver == NULL) {
psa_tcp_protocol_entry_t *protEntry = hashMap_get(psa->protocols.map, (void *) protocolSvcId);
if (protEntry != NULL) {
receiver = pubsub_tcpTopicReceiver_create(psa->ctx, psa->log, scope, topic,
handler, handle, topicProperties,
&psa->endpointStore, protocolSvcId, protEntry->svc);
} else {
L_ERROR("[PSA_TCP_V2] Cannot find serializer or protocol for TopicSender %s/%s", scope == NULL ? "(null)" : scope, topic);
}
if (receiver != NULL) {
const char *psaType = PUBSUB_TCP_ADMIN_TYPE;
const char *protType = protEntry->protType;
newEndpoint = pubsubEndpoint_create(psa->fwUUID, scope, topic,
PUBSUB_SUBSCRIBER_ENDPOINT_TYPE, psaType, pubsub_serializerHandler_getSerializationType(handler), protType, NULL);
//if available also set container name
const char *cn = celix_bundleContext_getProperty(psa->ctx, "CELIX_CONTAINER_NAME", NULL);
if (cn != NULL) {
celix_properties_set(newEndpoint, "container_name", cn);
}
celixThreadMutex_lock(&psa->topicReceivers.mutex);
hashMap_put(psa->topicReceivers.map, key, receiver);
celixThreadMutex_unlock(&psa->topicReceivers.mutex);
} else {
L_ERROR("[PSA_TCP_V2] Error creating a TopicReceiver.");
free(key);
}
} else {
free(key);
L_ERROR("[PSA_TCP_V2] Cannot setup already existing TopicReceiver for scope/topic %s/%s!",
scope == NULL ? "(null)" : scope,
topic);
}
celixThreadMutex_unlock(&psa->protocols.mutex);
if (receiver != NULL && newEndpoint != NULL) {
celixThreadMutex_lock(&psa->discoveredEndpoints.mutex);
hash_map_iterator_t iter = hashMapIterator_construct(psa->discoveredEndpoints.map);
while (hashMapIterator_hasNext(&iter)) {
celix_properties_t *endpoint = hashMapIterator_nextValue(&iter);
if (pubsub_tcpAdmin_endpointIsPublisher(endpoint) && pubsubEndpoint_matchWithTopicAndScope(endpoint, topic, scope)) {
pubsub_tcpAdmin_connectEndpointToReceiver(psa, receiver, endpoint);
}
}
celixThreadMutex_unlock(&psa->discoveredEndpoints.mutex);
}
if (newEndpoint != NULL && outSubscriberEndpoint != NULL) {
*outSubscriberEndpoint = newEndpoint;
}
celix_status_t status = CELIX_SUCCESS;
return status;
}
celix_status_t pubsub_tcpAdmin_teardownTopicReceiver(void *handle, const char *scope, const char *topic) {
pubsub_tcp_admin_t *psa = handle;
char *key = pubsubEndpoint_createScopeTopicKey(scope, topic);
celixThreadMutex_lock(&psa->topicReceivers.mutex);
hash_map_entry_t *entry = hashMap_getEntry(psa->topicReceivers.map, key);
free(key);
if (entry != NULL) {
char *receiverKey = hashMapEntry_getKey(entry);
pubsub_tcp_topic_receiver_t *receiver = hashMapEntry_getValue(entry);
hashMap_remove(psa->topicReceivers.map, receiverKey);
celixThreadMutex_unlock(&psa->topicReceivers.mutex);
free(receiverKey);
pubsub_tcpTopicReceiver_destroy(receiver);
} else {
celixThreadMutex_unlock(&psa->topicReceivers.mutex);
}
celix_status_t status = CELIX_SUCCESS;
return status;
}
static celix_status_t
pubsub_tcpAdmin_connectEndpointToReceiver(pubsub_tcp_admin_t *psa, pubsub_tcp_topic_receiver_t *receiver,
const celix_properties_t *endpoint) {
//note can be called with discoveredEndpoint.mutex lock
celix_status_t status = CELIX_SUCCESS;
const char *url = celix_properties_get(endpoint, PUBSUB_TCP_URL_KEY, NULL);
if (url == NULL) {
const char *admin = celix_properties_get(endpoint, PUBSUB_ENDPOINT_ADMIN_TYPE, NULL);
const char *type = celix_properties_get(endpoint, PUBSUB_ENDPOINT_TYPE, NULL);
L_WARN("[PSA_TCP_V2] Error got endpoint without a tcp url (admin: %s, type: %s)", admin, type);
status = CELIX_BUNDLE_EXCEPTION;
} else {
pubsub_tcpTopicReceiver_connectTo(receiver, url);
}
return status;
}
celix_status_t pubsub_tcpAdmin_addDiscoveredEndpoint(void *handle, const celix_properties_t *endpoint) {
pubsub_tcp_admin_t *psa = handle;
if (pubsub_tcpAdmin_endpointIsPublisher(endpoint)) {
celixThreadMutex_lock(&psa->topicReceivers.mutex);
hash_map_iterator_t iter = hashMapIterator_construct(psa->topicReceivers.map);
while (hashMapIterator_hasNext(&iter)) {
pubsub_tcp_topic_receiver_t *receiver = hashMapIterator_nextValue(&iter);
if (pubsubEndpoint_matchWithTopicAndScope(endpoint, pubsub_tcpTopicReceiver_topic(receiver), pubsub_tcpTopicReceiver_scope(receiver))) {
pubsub_tcpAdmin_connectEndpointToReceiver(psa, receiver, endpoint);
}
}
celixThreadMutex_unlock(&psa->topicReceivers.mutex);
}
celix_properties_t *cpy = celix_properties_copy(endpoint);
const char *uuid = celix_properties_get(cpy, PUBSUB_ENDPOINT_UUID, NULL);
celixThreadMutex_lock(&psa->discoveredEndpoints.mutex);
hashMap_put(psa->discoveredEndpoints.map, (void *) uuid, cpy);
celixThreadMutex_unlock(&psa->discoveredEndpoints.mutex);
celix_status_t status = CELIX_SUCCESS;
return status;
}
static celix_status_t
pubsub_tcpAdmin_disconnectEndpointFromReceiver(pubsub_tcp_admin_t *psa, pubsub_tcp_topic_receiver_t *receiver,
const celix_properties_t *endpoint) {
//note can be called with discoveredEndpoint.mutex lock
celix_status_t status = CELIX_SUCCESS;
const char *url = celix_properties_get(endpoint, PUBSUB_TCP_URL_KEY, NULL);
if (url == NULL) {
L_WARN("[PSA_TCP_V2] Error got endpoint without tcp url");
status = CELIX_BUNDLE_EXCEPTION;
} else {
pubsub_tcpTopicReceiver_disconnectFrom(receiver, url);
}
return status;
}
celix_status_t pubsub_tcpAdmin_removeDiscoveredEndpoint(void *handle, const celix_properties_t *endpoint) {
pubsub_tcp_admin_t *psa = handle;
if (pubsub_tcpAdmin_endpointIsPublisher(endpoint)) {
celixThreadMutex_lock(&psa->topicReceivers.mutex);
hash_map_iterator_t iter = hashMapIterator_construct(psa->topicReceivers.map);
while (hashMapIterator_hasNext(&iter)) {
pubsub_tcp_topic_receiver_t *receiver = hashMapIterator_nextValue(&iter);
pubsub_tcpAdmin_disconnectEndpointFromReceiver(psa, receiver, endpoint);
}
celixThreadMutex_unlock(&psa->topicReceivers.mutex);
}
celixThreadMutex_lock(&psa->discoveredEndpoints.mutex);
const char *uuid = celix_properties_get(endpoint, PUBSUB_ENDPOINT_UUID, NULL);
celix_properties_t *found = hashMap_remove(psa->discoveredEndpoints.map, (void *) uuid);
celixThreadMutex_unlock(&psa->discoveredEndpoints.mutex);
if (found != NULL) {
celix_properties_destroy(found);
}
celix_status_t status = CELIX_SUCCESS;
return status;
}
bool pubsub_tcpAdmin_executeCommand(void *handle, const char *commandLine CELIX_UNUSED, FILE *out,
FILE *errStream CELIX_UNUSED) {
pubsub_tcp_admin_t *psa = handle;
celix_status_t status = CELIX_SUCCESS;
char *line = celix_utils_strdup(commandLine);
char *token = line;
strtok_r(line, " ", &token); //first token is command name
strtok_r(NULL, " ", &token); //second token is sub command
if (celix_utils_stringEquals(token, "nr_of_receivers")) {
celixThreadMutex_lock(&psa->topicReceivers.mutex);
fprintf(out,"%i\n", hashMap_size(psa->topicReceivers.map));
celixThreadMutex_unlock(&psa->topicReceivers.mutex);
}
if (celix_utils_stringEquals(token, "nr_of_senders")) {
celixThreadMutex_lock(&psa->topicSenders.mutex);
fprintf(out, "%i\n", hashMap_size(psa->topicSenders.map));
celixThreadMutex_unlock(&psa->topicSenders.mutex);
}
fprintf(out, "\n");
fprintf(out, "Topic Senders:\n");
celixThreadMutex_lock(&psa->protocols.mutex);
celixThreadMutex_lock(&psa->topicSenders.mutex);
hash_map_iterator_t iter = hashMapIterator_construct(psa->topicSenders.map);
while (hashMapIterator_hasNext(&iter)) {
pubsub_tcp_topic_sender_t *sender = hashMapIterator_nextValue(&iter);
long protSvcId = pubsub_tcpTopicSender_protocolSvcId(sender);
psa_tcp_protocol_entry_t *protEntry = hashMap_get(psa->protocols.map, (void *) protSvcId);
const char *serType = pubsub_tcpTopicSender_serializerType(sender);
const char *protType = protEntry == NULL ? "!Error!" : protEntry->protType;
const char *scope = pubsub_tcpTopicSender_scope(sender);
const char *topic = pubsub_tcpTopicSender_topic(sender);
const char *url = pubsub_tcpTopicSender_url(sender);
const char *isPassive = pubsub_tcpTopicSender_isPassive(sender) ? " (passive)" : "";
const char *postUrl = pubsub_tcpTopicSender_isStatic(sender) ? " (static)" : "";
fprintf(out, "|- Topic Sender %s/%s\n", scope == NULL ? "(null)" : scope, topic);
fprintf(out, " |- serializer type = %s\n", serType);
fprintf(out, " |- protocol type = %s\n", protType);
fprintf(out, " |- url = %s%s%s\n", url, postUrl, isPassive);
}
celixThreadMutex_unlock(&psa->topicSenders.mutex);
celixThreadMutex_unlock(&psa->protocols.mutex);
fprintf(out, "\n");
fprintf(out, "\nTopic Receivers:\n");
celixThreadMutex_lock(&psa->protocols.mutex);
celixThreadMutex_lock(&psa->topicReceivers.mutex);
iter = hashMapIterator_construct(psa->topicReceivers.map);
while (hashMapIterator_hasNext(&iter)) {
pubsub_tcp_topic_receiver_t *receiver = hashMapIterator_nextValue(&iter);
long protSvcId = pubsub_tcpTopicReceiver_protocolSvcId(receiver);
psa_tcp_protocol_entry_t *protEntry = hashMap_get(psa->protocols.map, (void *) protSvcId);
const char *serType = pubsub_tcpTopicReceiver_serializerType(receiver);
const char *protType = protEntry == NULL ? "!Error!" : protEntry->protType;
const char *scope = pubsub_tcpTopicReceiver_scope(receiver);
const char *topic = pubsub_tcpTopicReceiver_topic(receiver);
celix_array_list_t *connected = celix_arrayList_create();
celix_array_list_t *unconnected = celix_arrayList_create();
pubsub_tcpTopicReceiver_listConnections(receiver, connected, unconnected);
fprintf(out, "|- Topic Receiver %s/%s\n", scope == NULL ? "(null)" : scope, topic);
fprintf(out, " |- serializer type = %s\n", serType);
fprintf(out, " |- protocol type = %s\n", protType);
for (int i = 0; i < celix_arrayList_size(connected); ++i) {
char *url = celix_arrayList_get(connected, i);
fprintf(out, " |- connected url = %s\n", url);
free(url);
}
for (int i = 0; i < celix_arrayList_size(unconnected); ++i) {
char *url = celix_arrayList_get(unconnected, i);
fprintf(out, " |- unconnected url = %s\n", url);
free(url);
}
celix_arrayList_destroy(connected);
celix_arrayList_destroy(unconnected);
}
celixThreadMutex_unlock(&psa->topicReceivers.mutex);
celixThreadMutex_unlock(&psa->protocols.mutex);
fprintf(out, "\n");
free(line);
return status;
}
pubsub_admin_metrics_t *pubsub_tcpAdmin_metrics(void *handle) {
return NULL;
}
|
6805b9808d0d18a2c1c21eaafca701ce76536967
|
7194f93c2bfdd86aa32d4112899a07a4c6a73fb8
|
/clinkc/src/cybergarage/upnp/ssdp/cssdp_packet.c
|
4264c885951560845697903c7f81d541031d1e07
|
[
"MIT"
] |
permissive
|
FuruyamaTakeshi/DLNA
|
7e39224fc068fbfac2785342cd09a15fc6e420fe
|
1ae0b057948990a951b4333fb060c3c9bf9a9968
|
refs/heads/develop
| 2021-01-01T20:11:39.022055
| 2018-01-03T02:54:36
| 2018-01-03T02:54:36
| 5,936,931
| 186
| 43
| null | 2017-04-18T06:25:42
| 2012-09-24T15:58:41
|
C
|
UTF-8
|
C
| false
| false
| 6,410
|
c
|
cssdp_packet.c
|
/******************************************************************
*
* CyberLink for C
*
* Copyright (C) Satoshi Konno 2005
*
* Copyright (C) 2006 Nokia Corporation. All rights reserved.
*
* This is licensed under BSD-style license,
* see file COPYING.
*
* File: cssdp_packet.c
*
* Revision:
*
* 06/01/05
* - first revision
*
* 10/31/05
* - Delete also ssdpTok in cg_upnp_ssdp_packet_set_header()
******************************************************************/
#include <cybergarage/upnp/ssdp/cssdp_server.h>
#include <cybergarage/upnp/control/ccontrol.h>
#include <cybergarage/util/cstring.h>
#include <cybergarage/util/clog.h>
/****************************************
* cg_upnp_ssdp_packet_new
****************************************/
CgUpnpSSDPPacket *cg_upnp_ssdp_packet_new()
{
CgUpnpSSDPPacket *ssdpPkt;
cg_log_debug_l4("Entering...\n");
ssdpPkt = (CgUpnpSSDPPacket *)malloc(sizeof(CgUpnpSSDPPacket));
if ( NULL != ssdpPkt )
{
ssdpPkt->dgmPkt = cg_socket_datagram_packet_new();
ssdpPkt->headerList = cg_http_headerlist_new();
ssdpPkt->initialized = 0;
cg_upnp_ssdp_packet_setuserdata(ssdpPkt, NULL);
cg_upnp_ssdp_packet_settimestamp(ssdpPkt, cg_getcurrentsystemtime());
ssdpPkt->timestamps = (CgSysTime *)malloc(CG_UPNP_SSDP_FILTER_TABLE_SIZE * sizeof(CgSysTime));
}
return ssdpPkt;
cg_log_debug_l4("Leaving...\n");
}
/****************************************
* cg_upnp_ssdp_packet_delete
****************************************/
void cg_upnp_ssdp_packet_delete(CgUpnpSSDPPacket *ssdpPkt)
{
cg_log_debug_l4("Entering...\n");
cg_upnp_ssdp_packet_clear(ssdpPkt);
cg_socket_datagram_packet_delete(ssdpPkt->dgmPkt);
cg_http_headerlist_delete(ssdpPkt->headerList);
free(ssdpPkt->timestamps);
free(ssdpPkt);
cg_log_debug_l4("Leaving...\n");
}
/****************************************
* cg_upnp_ssdp_packet_clear
****************************************/
void cg_upnp_ssdp_packet_clear(CgUpnpSSDPPacket *ssdpPkt)
{
cg_log_debug_l4("Entering...\n");
cg_socket_datagram_packet_setdata(ssdpPkt->dgmPkt, NULL);
cg_http_headerlist_clear(ssdpPkt->headerList);
cg_log_debug_l4("Leaving...\n");
}
/****************************************
* cg_upnp_ssdp_packet_isrootdevice
****************************************/
BOOL cg_upnp_ssdp_packet_isrootdevice(CgUpnpSSDPPacket *ssdpPkt)
{
cg_log_debug_l4("Entering...\n");
if (cg_upnp_nt_isrootdevice(cg_upnp_ssdp_packet_getnt(ssdpPkt)) == TRUE)
return TRUE;
if (cg_upnp_st_isrootdevice(cg_upnp_ssdp_packet_getst(ssdpPkt)) == TRUE)
return TRUE;
return cg_upnp_usn_isrootdevice(cg_upnp_ssdp_packet_getusn(ssdpPkt));
cg_log_debug_l4("Leaving...\n");
}
/****************************************
* cg_upnp_ssdp_packet_setheader
****************************************/
void cg_upnp_ssdp_packet_setheader(CgUpnpSSDPPacket *ssdpPkt, char *ssdpMsg)
{
CgStringTokenizer *ssdpTok;
CgStringTokenizer *ssdpLineTok;
CgHttpHeader *header;
char *lineMsg;
char *name;
char *value;
cg_log_debug_l4("Entering...\n");
ssdpTok = cg_string_tokenizer_new(ssdpMsg, CG_HTTP_CRLF);
/**** skip the first line ****/
if (cg_string_tokenizer_hasmoretoken(ssdpTok) == FALSE)
return;
lineMsg = cg_string_tokenizer_nexttoken(ssdpTok);
while (cg_string_tokenizer_hasmoretoken(ssdpTok) == TRUE) {
lineMsg = cg_string_tokenizer_nexttoken(ssdpTok);
name = NULL;
value = NULL;
ssdpLineTok = cg_string_tokenizer_new(lineMsg, CG_HTTP_HEADERLINE_DELIM);
if (cg_string_tokenizer_hasmoretoken(ssdpLineTok) == TRUE)
name = cg_string_tokenizer_nexttoken(ssdpLineTok);
if (cg_string_tokenizer_hasmoretoken(ssdpLineTok) == TRUE) {
value = cg_string_tokenizer_nextalltoken(ssdpLineTok);
cg_strrtrim(value, CG_HTTP_HEADERLINE_DELIM, cg_strlen(CG_HTTP_HEADERLINE_DELIM));
}
if (name != NULL) {
if (value == NULL)
value = "";
header = cg_http_header_new();
cg_http_header_setname(header, name);
cg_http_header_setvalue(header, value);
cg_http_headerlist_add(ssdpPkt->headerList, header);
}
cg_string_tokenizer_delete(ssdpLineTok);
}
cg_string_tokenizer_delete(ssdpTok);
cg_log_debug_l4("Leaving...\n");
}
/****************************************
* cg_upnp_ssdp_packet_getmaxage
****************************************/
long cg_upnp_ssdp_packet_getmaxage(CgUpnpSSDPPacket *ssdpPkt)
{
char *cachecontrol = NULL;
int maxageIdx = 0;
cg_log_debug_l4("Entering...\n");
cachecontrol = cg_upnp_ssdp_packet_getcachecontrol(ssdpPkt);
if (cachecontrol == NULL) return 0;
maxageIdx = cg_strstr(cachecontrol, CG_HTTP_MAX_AGE);
if (maxageIdx < 0) return 0;
maxageIdx = cg_strstr(cachecontrol+maxageIdx, "=");
if (maxageIdx <= 0) return 0;
maxageIdx++;
return cg_str2long(cachecontrol+maxageIdx);
cg_log_debug_l4("Leaving...\n");
}
/****************************************
* cg_upnp_ssdp_packet_copy
****************************************/
void cg_upnp_ssdp_packet_copy(CgUpnpSSDPPacket *dstSsdpPkt, CgUpnpSSDPPacket *srcSsdpPkt)
{
CgHttpHeader *srcHeader;
CgHttpHeader *destHeader;
cg_log_debug_l4("Entering...\n");
cg_socket_datagram_packet_copy(dstSsdpPkt->dgmPkt, srcSsdpPkt->dgmPkt);
/**** copy headers ****/
cg_upnp_ssdp_packet_clear(dstSsdpPkt);
for (srcHeader = cg_upnp_ssdp_packet_getheaders(srcSsdpPkt); srcHeader != NULL; srcHeader = cg_http_header_next(srcHeader)) {
destHeader = cg_http_header_new();
cg_http_header_setname(destHeader, cg_http_header_getname(srcHeader));
cg_http_header_setvalue(destHeader, cg_http_header_getvalue(srcHeader));
cg_upnp_ssdp_packet_addheader(dstSsdpPkt, destHeader);
}
/* Set timestamp */
cg_upnp_ssdp_packet_settimestamp(dstSsdpPkt, cg_getcurrentsystemtime());
cg_log_debug_l4("Leaving...\n");
}
/****************************************
* cg_upnp_ssdp_packet_print
****************************************/
void cg_upnp_ssdp_packet_print(CgUpnpSSDPPacket *ssdpPkt)
{
CgHttpHeader *header;
cg_log_debug_l4("Entering...\n");
cg_log_debug_s("ssdp from %s %d\n",
cg_upnp_ssdp_packet_getremoteaddress(ssdpPkt),
cg_upnp_ssdp_packet_getremoteport(ssdpPkt));
/**** print headers ****/
for (header = cg_http_headerlist_gets(ssdpPkt->headerList); header != NULL; header = cg_http_header_next(header)) {
cg_log_debug_s("%s: %s\n",
cg_http_header_getname(header),
cg_http_header_getvalue(header));
}
cg_log_debug_l4("Leaving...\n");
}
|
8de804ef53efb1dcff186f6c3cf673dac85ebc9a
|
847ebadf2b0e7c01ad33ce92b42528a1a5c4846c
|
/lib/hmap.c
|
9ee05b6d499b502a50c99513381f04ed9f887e4f
|
[
"BSD-3-Clause",
"ISC",
"Apache-2.0",
"SISSL",
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
openvswitch/ovs
|
6f782527cf5fde4ccfd25e68d359b91ff41acf8a
|
bc79a7bf033fa4cda8ccfc5481db3cfccd72650c
|
refs/heads/master
| 2023-09-04T06:31:47.899017
| 2023-08-03T16:19:12
| 2023-09-01T20:15:05
| 18,383,364
| 3,366
| 2,259
|
Apache-2.0
| 2023-08-17T13:17:13
| 2014-04-02T22:15:28
|
C
|
UTF-8
|
C
| false
| false
| 8,789
|
c
|
hmap.c
|
/*
* Copyright (c) 2008, 2009, 2010, 2012, 2013, 2015, 2019 Nicira, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <config.h>
#include "openvswitch/hmap.h"
#include <stdint.h>
#include <string.h>
#include "coverage.h"
#include "random.h"
#include "util.h"
#include "openvswitch/vlog.h"
VLOG_DEFINE_THIS_MODULE(hmap);
COVERAGE_DEFINE(hmap_pathological);
COVERAGE_DEFINE(hmap_expand);
COVERAGE_DEFINE(hmap_shrink);
COVERAGE_DEFINE(hmap_reserve);
/* Initializes 'hmap' as an empty hash table. */
void
hmap_init(struct hmap *hmap)
{
hmap->buckets = &hmap->one;
hmap->one = NULL;
hmap->mask = 0;
hmap->n = 0;
}
/* Frees memory reserved by 'hmap'. It is the client's responsibility to free
* the nodes themselves, if necessary. */
void
hmap_destroy(struct hmap *hmap)
{
if (hmap && hmap->buckets != &hmap->one) {
free(hmap->buckets);
}
}
/* Removes all node from 'hmap', leaving it ready to accept more nodes. Does
* not free memory allocated for 'hmap'.
*
* This function is appropriate when 'hmap' will soon have about as many
* elements as it did before. If 'hmap' will likely have fewer elements than
* before, use hmap_destroy() followed by hmap_init() to save memory and
* iteration time. */
void
hmap_clear(struct hmap *hmap)
{
if (hmap->n > 0) {
hmap->n = 0;
memset(hmap->buckets, 0, (hmap->mask + 1) * sizeof *hmap->buckets);
}
}
/* Exchanges hash maps 'a' and 'b'. */
void
hmap_swap(struct hmap *a, struct hmap *b)
{
struct hmap tmp = *a;
*a = *b;
*b = tmp;
hmap_moved(a);
hmap_moved(b);
}
/* Adjusts 'hmap' to compensate for having moved position in memory (e.g. due
* to realloc()). */
void
hmap_moved(struct hmap *hmap)
{
if (!hmap->mask) {
hmap->buckets = &hmap->one;
}
}
static void
resize(struct hmap *hmap, size_t new_mask, const char *where)
{
struct hmap tmp;
size_t i;
ovs_assert(is_pow2(new_mask + 1));
hmap_init(&tmp);
if (new_mask) {
tmp.buckets = xmalloc(sizeof *tmp.buckets * (new_mask + 1));
tmp.mask = new_mask;
for (i = 0; i <= tmp.mask; i++) {
tmp.buckets[i] = NULL;
}
}
int n_big_buckets = 0;
int biggest_count = 0;
int n_biggest_buckets = 0;
for (i = 0; i <= hmap->mask; i++) {
struct hmap_node *node, *next;
int count = 0;
for (node = hmap->buckets[i]; node; node = next) {
next = node->next;
hmap_insert_fast(&tmp, node, node->hash);
count++;
}
if (count > 5) {
n_big_buckets++;
if (count > biggest_count) {
biggest_count = count;
n_biggest_buckets = 1;
} else if (count == biggest_count) {
n_biggest_buckets++;
}
}
}
hmap_swap(hmap, &tmp);
hmap_destroy(&tmp);
if (n_big_buckets) {
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
COVERAGE_INC(hmap_pathological);
VLOG_DBG_RL(&rl, "%s: %d bucket%s with 6+ nodes, "
"including %d bucket%s with %d nodes "
"(%"PRIuSIZE" nodes total across %"PRIuSIZE" buckets)",
where,
n_big_buckets, n_big_buckets > 1 ? "s" : "",
n_biggest_buckets, n_biggest_buckets > 1 ? "s" : "",
biggest_count,
hmap->n, hmap->mask + 1);
}
}
static size_t
calc_mask(size_t capacity)
{
size_t mask = capacity / 2;
mask |= mask >> 1;
mask |= mask >> 2;
mask |= mask >> 4;
mask |= mask >> 8;
mask |= mask >> 16;
#if SIZE_MAX > UINT32_MAX
mask |= mask >> 32;
#endif
/* If we need to dynamically allocate buckets we might as well allocate at
* least 4 of them. */
mask |= (mask & 1) << 1;
return mask;
}
/* Expands 'hmap', if necessary, to optimize the performance of searches.
*
* ('where' is used in debug logging. Commonly one would use hmap_expand() to
* automatically provide the caller's source file and line number for
* 'where'.) */
void
hmap_expand_at(struct hmap *hmap, const char *where)
{
size_t new_mask = calc_mask(hmap->n);
if (new_mask > hmap->mask) {
COVERAGE_INC(hmap_expand);
resize(hmap, new_mask, where);
}
}
/* Shrinks 'hmap', if necessary, to optimize the performance of iteration.
*
* ('where' is used in debug logging. Commonly one would use hmap_shrink() to
* automatically provide the caller's source file and line number for
* 'where'.) */
void
hmap_shrink_at(struct hmap *hmap, const char *where)
{
size_t new_mask = calc_mask(hmap->n);
if (new_mask < hmap->mask) {
COVERAGE_INC(hmap_shrink);
resize(hmap, new_mask, where);
}
}
/* Expands 'hmap', if necessary, to optimize the performance of searches when
* it has up to 'n' elements. (But iteration will be slow in a hash map whose
* allocated capacity is much higher than its current number of nodes.)
*
* ('where' is used in debug logging. Commonly one would use hmap_reserve() to
* automatically provide the caller's source file and line number for
* 'where'.) */
void
hmap_reserve_at(struct hmap *hmap, size_t n, const char *where)
{
size_t new_mask = calc_mask(n);
if (new_mask > hmap->mask) {
COVERAGE_INC(hmap_reserve);
resize(hmap, new_mask, where);
}
}
/* Adjusts 'hmap' to compensate for 'old_node' having moved position in memory
* to 'node' (e.g. due to realloc()). */
void
hmap_node_moved(struct hmap *hmap,
struct hmap_node *old_node, struct hmap_node *node)
{
struct hmap_node **bucket = &hmap->buckets[node->hash & hmap->mask];
while (*bucket != old_node) {
bucket = &(*bucket)->next;
}
*bucket = node;
}
/* Chooses and returns a randomly selected node from 'hmap', which must not be
* empty.
*
* I wouldn't depend on this algorithm to be fair, since I haven't analyzed it.
* But it does at least ensure that any node in 'hmap' can be chosen. */
struct hmap_node *
hmap_random_node(const struct hmap *hmap)
{
struct hmap_node *bucket, *node;
size_t n, i;
/* Choose a random non-empty bucket. */
for (;;) {
bucket = hmap->buckets[random_uint32() & hmap->mask];
if (bucket) {
break;
}
}
/* Count nodes in bucket. */
n = 0;
for (node = bucket; node; node = node->next) {
n++;
}
/* Choose random node from bucket. */
i = random_range(n);
for (node = bucket; i-- > 0; node = node->next) {
continue;
}
return node;
}
/* Returns the next node in 'hmap' in hash order, or NULL if no nodes remain in
* 'hmap'. Uses '*pos' to determine where to begin iteration, and updates
* '*pos' to pass on the next iteration into them before returning.
*
* It's better to use plain HMAP_FOR_EACH and related functions, since they are
* faster and better at dealing with hmaps that change during iteration.
*
* Before beginning iteration, set '*pos' to all zeros. */
struct hmap_node *
hmap_at_position(const struct hmap *hmap,
struct hmap_position *pos)
{
size_t offset;
size_t b_idx;
offset = pos->offset;
for (b_idx = pos->bucket; b_idx <= hmap->mask; b_idx++) {
struct hmap_node *node;
size_t n_idx;
for (n_idx = 0, node = hmap->buckets[b_idx]; node != NULL;
n_idx++, node = node->next) {
if (n_idx == offset) {
if (node->next) {
pos->bucket = node->hash & hmap->mask;
pos->offset = offset + 1;
} else {
pos->bucket = (node->hash & hmap->mask) + 1;
pos->offset = 0;
}
return node;
}
}
offset = 0;
}
pos->bucket = 0;
pos->offset = 0;
return NULL;
}
/* Returns true if 'node' is in 'hmap', false otherwise. */
bool
hmap_contains(const struct hmap *hmap, const struct hmap_node *node)
{
struct hmap_node *p;
for (p = hmap_first_in_bucket(hmap, node->hash); p; p = p->next) {
if (p == node) {
return true;
}
}
return false;
}
|
cbb204e6215d6b446da05d40a0912d66c47f16eb
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/stm32/stm32mp157a-st-ev1/board/ports/OpenAMP/libmetal/lib/dma.c
|
baeb21bd2a828823eb8e6e69437031a0a3ef3134
|
[
"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
| 1,426
|
c
|
dma.c
|
/*
* Copyright (c) 2015, Xilinx Inc. and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <metal/errno.h>
#include <string.h>
#include <metal/device.h>
#include <metal/log.h>
#include <metal/dma.h>
#include <metal/atomic.h>
int metal_dma_map(struct metal_device *dev,
uint32_t dir,
struct metal_sg *sg_in,
int nents_in,
struct metal_sg *sg_out)
{
int nents_out;
if (!dev || !sg_in || !sg_out)
return -EINVAL;
if (!dev->bus->ops.dev_dma_map)
return -ENODEV;
/* memory barrier */
if (dir == METAL_DMA_DEV_R)
/* If it is device read, apply memory write fence. */
atomic_thread_fence(memory_order_release);
else
/* If it is device write or device r/w,
apply memory r/w fence. */
atomic_thread_fence(memory_order_acq_rel);
nents_out = dev->bus->ops.dev_dma_map(dev->bus,
dev, dir, sg_in, nents_in, sg_out);
return nents_out;
}
void metal_dma_unmap(struct metal_device *dev,
uint32_t dir,
struct metal_sg *sg,
int nents)
{
/* memory barrier */
if (dir == METAL_DMA_DEV_R)
/* If it is device read, apply memory write fence. */
atomic_thread_fence(memory_order_release);
else
/* If it is device write or device r/w,
apply memory r/w fence. */
atomic_thread_fence(memory_order_acq_rel);
if (!dev || !dev->bus->ops.dev_dma_unmap || !sg)
return;
dev->bus->ops.dev_dma_unmap(dev->bus,
dev, dir, sg, nents);
}
|
9ed00251d7acd1761655e6551198a7eab7d9108c
|
badb70a0b235c98ac034cfe5b4bfafda36647831
|
/Library/OcMacInfoLib/MacInfoInternal.h
|
bd68bf4124a501d159ab9cea6af540847547142e
|
[
"BSD-3-Clause"
] |
permissive
|
acidanthera/OpenCorePkg
|
f34a7d67b22c74fb5ab559e48519e5f5855b6751
|
1d5b1736fe5a5ef7662b5c076c6d11aac96fd5d6
|
refs/heads/master
| 2023-08-30T21:03:02.993659
| 2023-08-28T23:30:43
| 2023-08-28T23:30:43
| 179,354,282
| 13,212
| 2,999
|
BSD-3-Clause
| 2023-09-10T18:29:53
| 2019-04-03T19:14:29
|
C
|
UTF-8
|
C
| false
| false
| 2,406
|
h
|
MacInfoInternal.h
|
/** @file
Copyright (C) 2019, vit9696. All rights reserved.
All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef MAC_INFO_INTERNAL_H
#define MAC_INFO_INTERNAL_H
#define MAC_INFO_PLATFORM_FEATURE_MISSING 0xFFFFFFFFU
#define MAC_INFO_BOARD_REVISION_MISSING 0xFFU
typedef struct {
CONST CHAR8 *CONST SystemProductName;
CONST CHAR8 *CONST BoardProduct;
CONST UINT8 BoardRevision;
CONST UINT8 SmcRevision[6];
CONST UINT8 SmcBranch[8];
CONST UINT8 SmcPlatform[8];
CONST CHAR8 *CONST BIOSVersion;
CONST CHAR8 *CONST BIOSReleaseDate;
CONST CHAR8 *CONST SystemVersion;
CONST CHAR8 *CONST SystemSKUNumber;
CONST CHAR8 *CONST SystemFamily;
CONST CHAR8 *CONST BoardVersion;
CONST CHAR8 *CONST BoardAssetTag;
CONST CHAR8 *CONST BoardLocationInChassis;
CONST UINT8 SmcGeneration;
CONST UINT8 BoardType;
CONST UINT8 ChassisType;
CONST UINT8 MemoryFormFactor;
CONST UINT32 PlatformFeature;
CONST CHAR8 *CONST ChassisAssetTag;
CONST UINT64 FirmwareFeatures;
CONST UINT64 FirmwareFeaturesMask;
CONST CHAR8 *CONST SecureBootModel;
} MAC_INFO_INTERNAL_ENTRY;
//
// Statically compiled array with model entries.
// The array is sorted by ProductName field.
//
extern CONST MAC_INFO_INTERNAL_ENTRY gMacInfoModels[];
//
// Entry count in statically compiled array with model entries.
//
extern CONST UINTN gMacInfoModelCount;
//
// Default entry in a statically compiled array with model entries.
//
extern CONST UINTN gMacInfoDefaultModel;
//
// Entry in 64-bit compatibility table.
//
typedef struct {
//
// Mac model.
//
CONST CHAR8 *ModelName;
//
// Minimum major version for 64-bit kernel mode under 10.6.
//
UINT8 SnowLeoMin64;
//
// Minimum major version for 64-bit kernel mode under 10.7.
//
UINT8 LionMin64;
} MAC_INFO_64BIT_COMPAT_ENTRY;
#endif // MAC_INFO_INTERNAL_H
|
e24a0872bf63a53809731df20faee5d074445a02
|
d3ef2463f556d6cd166eb29d3a5f5b210a6402e7
|
/cupy/_core/include/cupy/math_constants.h
|
94671451df00547af7d60a7feb15c3013cf5cbe6
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
cupy/cupy
|
ce7a010a57504dbfe4fb5af10d354a22e79f4907
|
96105afb78aa3f8380834d2516184b8365e23fcb
|
refs/heads/main
| 2023-08-31T00:36:47.967611
| 2023-08-30T09:19:27
| 2023-08-30T09:19:27
| 72,523,920
| 7,505
| 1,072
|
MIT
| 2023-09-14T01:04:42
| 2016-11-01T09:54:45
|
Python
|
UTF-8
|
C
| false
| false
| 655
|
h
|
math_constants.h
|
#ifndef CUPY_MATH_CONSTANTS_H
#define CUPY_MATH_CONSTANTS_H
/*
We bundle some constants found in math_constants.h, so that code can be
JIT compiled in environments without a full CUDA installation. The constants
are added as needed to avoid copying the entire header.
*/
/* single precision constants */
#define CUDART_INF_F __int_as_float(0x7f800000)
#define CUDART_NAN_F __int_as_float(0x7fffffff)
/* double precision constants */
#define CUDART_INF __longlong_as_double(0x7ff0000000000000ULL)
#define CUDART_NAN __longlong_as_double(0xfff8000000000000ULL)
#endif // CUPY_MATH_CONSTANTS_H
|
72eaae456133c6b95feb9f5d3e01f8a7591d40a0
|
f2aba95a466b2dc18b5c0fee55a1bf9653a896a5
|
/src/main.h
|
517d0d1f5e2560dd7450bc43d6853ef6a9b80d7c
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
joewing/jwm
|
a9ea46d9fc4b783411cd0b9ecab1110ff44f28a1
|
4640d3b48ea64bd57e3cea63e4c4a9cd558e6142
|
refs/heads/master
| 2023-08-28T20:10:59.577268
| 2022-10-22T07:10:18
| 2022-10-22T07:10:18
| 7,212,717
| 532
| 135
|
MIT
| 2022-10-24T07:50:03
| 2012-12-17T21:37:59
|
C
|
UTF-8
|
C
| false
| false
| 906
|
h
|
main.h
|
/**
* @file main.h
* @author Joe Wingbermuehle
* @date 2004-2006
*
* @brief Header for the main functions.
*
*/
#ifndef MAIN_H
#define MAIN_H
extern Display *display;
extern Window rootWindow;
extern int rootWidth, rootHeight;
extern int rootScreen;
extern Colormap rootColormap;
extern Visual *rootVisual;
extern int rootDepth;
extern GC rootGC;
extern int colormapCount;
extern Window supportingWindow;
extern Atom managerSelection;
extern char *exitCommand;
extern unsigned int currentDesktop;
extern unsigned int previousDesktop;
extern char shouldExit;
extern char shouldRestart;
extern char isRestarting;
extern char shouldReload;
extern char initializing;
extern XContext clientContext;
extern XContext frameContext;
#ifdef USE_SHAPE
extern char haveShape;
extern int shapeEvent;
#endif
#ifdef USE_XRENDER
extern char haveRender;
#endif
extern char *configPath;
#endif /* MAIN_H */
|
a590eff9e95d740c32db1b6eb3f1d78e48d2628c
|
90f4fefd00d7baf1fb0137c66f22222f3a0b1d4d
|
/Blinker/BlinkerDebug.h
|
cf4551c1291b4d2aab517c5d05451f1cdfcb752d
|
[] |
no_license
|
blinker-iot/blinker-nRF52
|
969e9f49e7c80d661215007a330232b2168a80c4
|
501322572e0ce4f633ef402419f879c2ab84d24c
|
refs/heads/dev_1.0
| 2023-04-03T11:46:04.909891
| 2021-04-15T14:33:14
| 2021-04-15T14:33:14
| 241,844,430
| 1,739
| 3
| null | 2021-04-15T09:33:19
| 2020-02-20T09:33:02
|
C
|
UTF-8
|
C
| false
| false
| 1,139
|
h
|
BlinkerDebug.h
|
#ifndef BLINKER_DEBUG_H__
#define BLINKER_DEBUG_H__
#include <stdint.h>
#include <string.h>
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include "BlinkerUtility.h"
// static bool is_debug_all = false;
// void blinker_log_init(void)
// {
// ret_code_t err_code = NRF_LOG_INIT(NULL);
// APP_ERROR_CHECK(err_code);
// NRF_LOG_DEFAULT_BACKENDS_INIT();
// }
// #define BLINKER_LOG_MODULE(...) { \
// printf("[%d]: ", blinker_millis()); \
// printf( __VA_ARGS__ ); \
// printf("\r\n"); \
// }
// #define BLINKER_ERR_LOG_MODULE(...) { \
// printf("[%d]: ERROR: ", blinker_millis()); \
// printf( __VA_ARGS__ ); \
// printf("\r\n"); \
// }
// #define BLINKER_LOG_ALL_MODULE(...) { \
// if (is_debug_all) { \
// BLINKER_LOG_MODULE(__VA_ARGS__); \
// } \
// }
// #define BLINKER_DEBUG_ALL() is_debug_all = true;
// #define BLINKER_LOG(...) BLINKER_LOG_MODULE( __VA_ARGS__ );
// #define BLINKER_LOG_ALL(...) BLINKER_LOG_ALL_MODULE( __VA_ARGS__ );
// #define BLINKER_ERR_LOG(...) BLINKER_ERR_LOG_MODULE( __VA_ARGS__ );
#endif
|
bdf4883b4f46b04b1589e43e01cdbbf2977d6bd0
|
971b2cea2d1c3001aadc8ca1a48110b7db1ed5f2
|
/deps/abc/src/misc/avl/avl.h
|
141e4f564ed8efafb72e47f984f9ae96df85583c
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"MIT-Modern-Variant"
] |
permissive
|
emsec/hal
|
70ad2921739967d914dd458984bd7d6d497d3b0a
|
e4fae37bec9168a61100eacfda37a1f291b4d0be
|
refs/heads/master
| 2023-09-02T20:27:32.909426
| 2023-09-01T13:03:24
| 2023-09-01T13:03:24
| 169,076,171
| 510
| 72
|
MIT
| 2023-09-01T13:03:26
| 2019-02-04T12:37:20
|
C++
|
UTF-8
|
C
| false
| false
| 2,249
|
h
|
avl.h
|
/*
* Revision Control Information
*
* $Source: /vol/opua/opua2/sis/sis-1.2/common/src/sis/avl/RCS/avl.h,v $
* $Author: sis $
* $Revision: 1.3 $
* $Date: 1994/07/15 23:00:40 $
*
*/
#ifndef ABC__misc__avl__avl_h
#define ABC__misc__avl__avl_h
ABC_NAMESPACE_HEADER_START
#define EXTERN
#ifndef ARGS
#define ARGS(protos) protos
#endif
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define NIL(type) \
((type *) 0)
#define ALLOC(type, num) \
((type *) malloc(sizeof(type) * (num)))
#define REALLOC(type, obj, num) \
((type *) realloc((char *) obj, sizeof(type) * (num)))
#define FREE(obj) \
free((char *) (obj))
typedef struct avl_node_struct avl_node;
struct avl_node_struct {
avl_node *left, *right;
char *key;
char *value;
int height;
};
typedef struct avl_tree_struct avl_tree;
struct avl_tree_struct {
avl_node *root;
int (*compar)();
int num_entries;
int modified;
};
typedef struct avl_generator_struct avl_generator;
struct avl_generator_struct {
avl_tree *tree;
avl_node **nodelist;
int count;
};
#define AVL_FORWARD 0
#define AVL_BACKWARD 1
EXTERN avl_tree *avl_init_table ARGS((int (*)()));
EXTERN int avl_delete ARGS((avl_tree *, char **, char **));
EXTERN int avl_insert ARGS((avl_tree *, char *, char *));
EXTERN int avl_lookup ARGS((avl_tree *, char *, char **));
EXTERN int avl_first ARGS((avl_tree *, char **, char **));
EXTERN int avl_last ARGS((avl_tree *, char **, char **));
EXTERN int avl_find_or_add ARGS((avl_tree *, char *, char ***));
EXTERN int avl_count ARGS((avl_tree *));
EXTERN int avl_numcmp ARGS((char *, char *));
EXTERN int avl_gen ARGS((avl_generator *, char **, char **));
EXTERN void avl_foreach ARGS((avl_tree *, void (*)(), int));
EXTERN void avl_free_table ARGS((avl_tree *, void (*)(), void (*)()));
EXTERN void avl_free_gen ARGS((avl_generator *));
EXTERN avl_generator *avl_init_gen ARGS((avl_tree *, int));
#define avl_is_member(tree, key) avl_lookup(tree, key, (char **) 0)
#define avl_foreach_item(table, gen, dir, key_p, value_p) \
for(gen = avl_init_gen(table, dir); \
avl_gen(gen, key_p, value_p) || (avl_free_gen(gen),0);)
ABC_NAMESPACE_HEADER_END
#endif
|
26f3eae9e9db0a91b2a7e498566d7fa8f8b1b9ce
|
1e21bfcd7a1a01e609be8ff4ecf959d3e7b048cb
|
/include/private/target/journald.h
|
d098e4676c92b3e3d80680a21efb90ada700cb31
|
[
"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
| 10,238
|
h
|
journald.h
|
/* SPDX-License-Identifier: Apache-2.0 */
/*
* Copyright 2021 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.
*/
#ifndef __STUMPLESS_PRIVATE_TARGET_JOURNALD_H
# define __STUMPLESS_PRIVATE_TARGET_JOURNALD_H
# include <stddef.h>
# include <stumpless/entry.h>
# include <stumpless/target.h>
/**
* Gets a journald-compliant field name from a given UTF-8 string.
*
* **Thread Safety: MT-Safe race:raw**
* This function is thread safe, of course assuming that the raw name is not
* changed by another thread during execution.
*
* **Async Signal Safety: AS-Safe**
* This function is safe to call from signal handlers.
*
* **Async Cancel Safety: AC-Safe**
* This function is safe to call from threads that may be asynchronously
* cancelled.
*
* @since v2.1.0
*
* @param flattened A buffer to write the flattened name to.
*
* @param raw The raw field name.
*
* @param size The number of bytes in the raw name.
*
* @return the number of bytes written to the flattened buffer.
*/
size_t
get_journald_field_name( char *flattened, const char *raw, size_t size );
/**
* Allocates the memory for the fields buffer.
*
* **Thread Safety: MT-Safe**
* This function is thread safe as it operates only on the active thread's
* resources.
*
* **Async Signal Safety: AS-Unsafe heap**
* This function is not safe to call from signal handlers due to the use of
* the memory allocation function to allocate memory.
*
* **Async Cancel Safety: AC-Unsafe heap**
* This function is not safe to call from threads that may be asynchronously
* cancelled, as the memory allocation function may not be AC-Safe itself.
*
* @since v2.1.0
*
* @param field_count The number of fields the buffer must have.
*/
void
init_fields( size_t field_count );
/**
* Allocates the memory for the buffer to hold the fixed fields.
*
* **Thread Safety: MT-Safe**
* This function is thread safe as it operates only on the active thread's
* resources.
*
* **Async Signal Safety: AS-Unsafe heap**
* This function is not safe to call from signal handlers due to the use of
* the memory allocation function to allocate memory.
*
* **Async Cancel Safety: AC-Unsafe heap**
* This function is not safe to call from threads that may be asynchronously
* cancelled, as the memory allocation function may not be AC-Safe itself.
*
* @since v2.1.0
*/
void
init_fixed_fields( void );
/**
* Destroys all thread-specific resources created to support journald.
*
* **Thread Safety: MT-Safe**
* This function is thread safe as it operates only on the active thread's
* resources.
*
* **Async Signal Safety: AS-Unsafe heap**
* This function is not safe to call from signal handlers due to the use of
* the memory deallocation function to release memory.
*
* **Async Cancel Safety: AC-Unsafe heap**
* This function is not safe to call from threads that may be asynchronously
* cancelled, as the memory deallocation function may not be AC-Safe itself.
*
* @since v2.1.0
*/
void
journald_free_thread( void );
/**
* Loads the facility field according to an entry's facility.
*
* **Thread Safety: MT-Safe race:entry**
* This function is thread safe, asssuming that the entry is already locked
* by the caller.
*
* **Async Signal Safety: AS-Unsafe lock**
* Logging to journald targets is not signal safe due to the use of
* non-reentrant locks.
*
* **Async Cancel Safety: AC-Unsafe lock**
* Logging to journald targets is not async cancellation safe as it uses locks
* that may not be released if a thread is cancelled.
*
* @since v2.1.0
*
* @param entry The entry to load the facility from.
*/
void
load_facility( const struct stumpless_entry *entry );
/**
* Loads the identifier field according to an entry's app name.
*
* **Thread Safety: MT-Safe race:entry**
* This function is thread safe, asssuming that the entry is already locked
* by the caller.
*
* **Async Signal Safety: AS-Unsafe lock**
* Logging to journald targets is not signal safe due to the use of
* non-reentrant locks.
*
* **Async Cancel Safety: AC-Unsafe lock**
* Logging to journald targets is not async cancellation safe as it uses locks
* that may not be released if a thread is cancelled.
*
* @since v2.1.0
*
* @param entry The entry to load the identifier from.
*/
void
load_identifier( const struct stumpless_entry *entry );
/**
* Loads the message field according to an entry.
*
* **Thread Safety: MT-Safe race:entry**
* This function is thread safe, asssuming that the entry is already locked
* by the caller.
*
* **Async Signal Safety: AS-Unsafe lock**
* Logging to journald targets is not signal safe due to the use of
* non-reentrant locks.
*
* **Async Cancel Safety: AC-Unsafe lock**
* Logging to journald targets is not async cancellation safe as it uses locks
* that may not be released if a thread is cancelled.
*
* @since v2.1.0
*
* @param entry The entry to load the message from.
*
* @return A pointer to the buffer holding the message, or NULL if an error
* was encountered.
*/
char *
load_message( const struct stumpless_entry *entry );
/**
* Loads the msgid field according to an entry's msgid.
*
* **Thread Safety: MT-Safe race:entry**
* This function is thread safe, asssuming that the entry is already locked
* by the caller.
*
* **Async Signal Safety: AS-Unsafe lock**
* Logging to journald targets is not signal safe due to the use of
* non-reentrant locks.
*
* **Async Cancel Safety: AC-Unsafe lock**
* Logging to journald targets is not async cancellation safe as it uses locks
* that may not be released if a thread is cancelled.
*
* @since v2.1.0
*
* @param entry The entry to load the msgid from.
*/
void
load_msgid( const struct stumpless_entry *entry );
/**
* Loads the pid field with the current pid.
*
* **Thread Safety: MT-Safe**
* This function is thread safe.
*
* **Async Signal Safety: AS-Unsafe**
* This function is not signal safe due to the use of a thread-local buffer.
*
* **Async Cancel Safety: AC-Safe**
* Logging to journald targets is async cancellation safe.
*
* @since v2.1.0
*
* @return The size of the loaded pid, including the field prefix.
*/
size_t
load_pid( void );
/**
* Loads the priority field according to an entry's severity.
*
* **Thread Safety: MT-Safe race:entry**
* This function is thread safe, asssuming that the entry is already locked
* by the caller.
*
* **Async Signal Safety: AS-Unsafe lock**
* Logging to journald targets is not signal safe due to the use of
* non-reentrant locks.
*
* **Async Cancel Safety: AC-Unsafe lock**
* Logging to journald targets is not async cancellation safe as it uses locks
* that may not be released if a thread is cancelled.
*
* @since v2.1.0
*
* @param entry The entry to load the priority from.
*/
void
load_priority( const struct stumpless_entry *entry );
/**
* Loads the structured data fields according to those in the entry.
*
* **Thread Safety: MT-Safe race:entry**
* This function is thread safe, asssuming that the entry is already locked
* by the caller. Elements and params within the entry are locked/unlocked
* as needed.
*
* **Async Signal Safety: AS-Unsafe lock**
* Logging to journald targets is not signal safe due to the use of
* non-reentrant locks.
*
* **Async Cancel Safety: AC-Unsafe lock**
* Logging to journald targets is not async cancellation safe as it uses locks
* that may not be released if a thread is cancelled.
*
* @since v2.1.0
*
* @param entry The entry to load the fields from.
*
* @return The total number of fields that will be logged with this entry,
* including the structured data fields, or 0 if an error was encountered. Note
* that a successful call will always be at least 6 as this number includes the
* fixed fields.
*/
size_t
load_sd_fields( const struct stumpless_entry *entry );
/**
* Loads the timestamp field with the current field.
*
* **Thread Safety: MT-Safe**
* This function is thread safe.
*
* **Async Signal Safety: AS-Unsafe**
* This function is not signal safe due to the use of a thread-local buffer.
*
* **Async Cancel Safety: AC-Safe**
* Logging to journald targets is async cancellation safe.
*
* @since v2.1.0
*
* @return The size of the loaded timestamp, including the field prefix.
*/
size_t
load_timestamp( void );
/**
* Sends the given entry to the given target.
*
* **Thread Safety: MT-Safe**
* This function is thread safe.
*
* **Async Signal Safety: AS-Unsafe**
* Logging to journald targets is not signal safe due to the use of a
* thread-local buffer.
*
* **Async Cancel Safety: AC-Unsafe**
* Logging to journald targets is not async cancellation safe as it relies on
* sd_journal_sendv which is not documented as such.
*
* @since v2.1.0
*
* @param target Where to send the entry.
*
* @param entry The message to log.
*
* @return The result of sd_journald_sendv, or -1 if an error is encountered
* before it can be called.
*/
int
send_entry_to_journald_target( const struct stumpless_target *target,
const struct stumpless_entry *entry );
/**
* Sets the base of each iovec in the fixed fields to the correct member of
* the fixed_fields structure.
*
* No NULL checks are performed on either buffer.
*
* **Thread Safety: MT-Safe**
* This function is thread safe.
*
* **Async Signal Safety: AS-Unsafe**
* This function is not signal safe due as it operates on a thread-local buffer.
*
* **Async Cancel Safety: AC-Unsafe**
* This function is not async cancellation safe as it may leave the buffers in
* an inconsistent state.
*
* @since v2.1.0
*/
void
set_field_bases( void );
#endif /* __STUMPLESS_PRIVATE_TARGET_JOURNALD_H */
|
2e837b353992e9ef4ea7f1453167e1819d510bfd
|
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
|
/time/xbeats/patches/patch-parser.c
|
d2a57616f6a5f4a492724a591e65a20da896d429
|
[] |
no_license
|
NetBSD/pkgsrc
|
a0732c023519650ef821ab89c23ab6ab59e25bdb
|
d042034ec4896cc5b47ed6f2e5b8802d9bc5c556
|
refs/heads/trunk
| 2023-09-01T07:40:12.138283
| 2023-09-01T05:25:19
| 2023-09-01T05:25:19
| 88,439,572
| 321
| 138
| null | 2023-07-12T22:34:14
| 2017-04-16T20:04:15
| null |
UTF-8
|
C
| false
| false
| 252
|
c
|
patch-parser.c
|
$NetBSD: patch-parser.c,v 1.1 2023/07/07 08:25:37 nia Exp $
Fix incompatible declaration of exit(3).
--- parser.c.orig 1999-01-25 16:13:46.000000000 +0000
+++ parser.c
@@ -1,4 +1,5 @@
#include <stdio.h>
+#include <stdlib.h>
#include "xbeats.h"
|
75086d74c959a2a112d94bf3128d1ad99fef5a1d
|
e1f3aa0a31eff83c12c2f9f60373313cbdeaadee
|
/pyuv_cffi/pyuv_cffi.c
|
9338b57a9a9dc894f443aa8eb429739eab098121
|
[
"MIT"
] |
permissive
|
veegee/guv
|
50975296b767f34b7047a4bd9e287fa0f29cf517
|
d7bac2ca6a73cc2059969af08223b82f3e187922
|
refs/heads/develop
| 2021-07-20T23:00:46.983748
| 2017-01-22T18:13:00
| 2017-01-22T18:13:00
| 26,725,514
| 121
| 14
|
NOASSERTION
| 2021-07-17T02:35:32
| 2014-11-16T19:39:59
|
Python
|
UTF-8
|
C
| false
| false
| 586
|
c
|
pyuv_cffi.c
|
/**
* Custom C functions for using libuv with CFFI
*/
#include <stdio.h>
#include <stdlib.h>
#include <uv.h>
#if UV_VERSION_MAJOR < 1
#error "libuv >= 1.0.0 is required"
#endif
/**
* Create a `uv_handle_t *` from a `uv_?_t` specific handle type
*
* The purpose of this is to instantiate the `Handle` class and use base
* `uv_handle_t` functions on any specific `uv_?_t` handle types. I couldn't
* figure out how to use `ffi.cast` to get what I wanted, so that is the purpose
* of this function.
*/
uv_handle_t *cast_handle(void *handle) {
return (uv_handle_t *)handle;
}
|
6eef9872ce2a833f1e55a4147d16b7d37e1fc485
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/essemi/es32vf2264/libraries/RV_CORE/Device/EastSoft/ES32VF2264/Include/ES32VF2264/reg_syscfg.h
|
97245328009c37808a2bc11180d7fcb0c9103d7d
|
[
"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
| 5,429
|
h
|
reg_syscfg.h
|
/**********************************************************************************
*
* @file reg_syscfg.h
* @brief SYSCFG Head File
*
* @date 07 July 2022
* @author AE Team
* @note
* Change Logs:
* Date Author Notes
* 07 July 2022 Lisq the first version
*
* Copyright (C) Shanghai Eastsoft Microelectronics Co. Ltd. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************
*/
#ifndef __REG_SYSCFG_H__
#define __REG_SYSCFG_H__
/****************** Bit definition for SYSCFG_PROT register ************************/
#define SYSCFG_PROT_KEY_POSS 1U
#define SYSCFG_PROT_KEY_POSE 31U
#define SYSCFG_PROT_KEY_MSK BITS(SYSCFG_PROT_KEY_POSS,SYSCFG_PROT_KEY_POSE)
#define SYSCFG_PROT_PROT_POS 0U
#define SYSCFG_PROT_PROT_MSK BIT(SYSCFG_PROT_PROT_POS)
/****************** Bit definition for SYSCFG_BTADDR register ************************/
#define SYSCFG_BTADDR_BTADDR_POSS 0U
#define SYSCFG_BTADDR_BTADDR_POSE 17U
#define SYSCFG_BTADDR_BTADDR_MSK BITS(SYSCFG_BTADDR_BTADDR_POSS,SYSCFG_BTADDR_BTADDR_POSE)
/****************** Bit definition for SYSCFG_TBKCFG register ************************/
#define SYSCFG_TBKCFG_CLUBKE_POS 2U
#define SYSCFG_TBKCFG_CLUBKE_MSK BIT(SYSCFG_TBKCFG_CLUBKE_POS)
#define SYSCFG_TBKCFG_LVDBKE_POS 1U
#define SYSCFG_TBKCFG_LVDBKE_MSK BIT(SYSCFG_TBKCFG_LVDBKE_POS)
#define SYSCFG_TBKCFG_CCSBKE_POS 0U
#define SYSCFG_TBKCFG_CCSBKE_MSK BIT(SYSCFG_TBKCFG_CCSBKE_POS)
/****************** Bit definition for SYSCFG_PISIOCFG register ************************/
#define SYSCFG_PISIOCFG_IO15SEL_POSS 30U
#define SYSCFG_PISIOCFG_IO15SEL_POSE 31U
#define SYSCFG_PISIOCFG_IO15SEL_MSK BITS(SYSCFG_PISIOCFG_IO15SEL_POSS,SYSCFG_PISIOCFG_IO15SEL_POSE)
#define SYSCFG_PISIOCFG_IO14SEL_POSS 28U
#define SYSCFG_PISIOCFG_IO14SEL_POSE 29U
#define SYSCFG_PISIOCFG_IO14SEL_MSK BITS(SYSCFG_PISIOCFG_IO14SEL_POSS,SYSCFG_PISIOCFG_IO14SEL_POSE)
#define SYSCFG_PISIOCFG_IO13SEL_POSS 26U
#define SYSCFG_PISIOCFG_IO13SEL_POSE 27U
#define SYSCFG_PISIOCFG_IO13SEL_MSK BITS(SYSCFG_PISIOCFG_IO13SEL_POSS,SYSCFG_PISIOCFG_IO13SEL_POSE)
#define SYSCFG_PISIOCFG_IO12SEL_POSS 24U
#define SYSCFG_PISIOCFG_IO12SEL_POSE 25U
#define SYSCFG_PISIOCFG_IO12SEL_MSK BITS(SYSCFG_PISIOCFG_IO12SEL_POSS,SYSCFG_PISIOCFG_IO12SEL_POSE)
#define SYSCFG_PISIOCFG_IO11SEL_POSS 22U
#define SYSCFG_PISIOCFG_IO11SEL_POSE 23U
#define SYSCFG_PISIOCFG_IO11SEL_MSK BITS(SYSCFG_PISIOCFG_IO11SEL_POSS,SYSCFG_PISIOCFG_IO11SEL_POSE)
#define SYSCFG_PISIOCFG_IO10SEL_POSS 20U
#define SYSCFG_PISIOCFG_IO10SEL_POSE 21U
#define SYSCFG_PISIOCFG_IO10SEL_MSK BITS(SYSCFG_PISIOCFG_IO10SEL_POSS,SYSCFG_PISIOCFG_IO10SEL_POSE)
#define SYSCFG_PISIOCFG_IO9SEL_POSS 18U
#define SYSCFG_PISIOCFG_IO9SEL_POSE 19U
#define SYSCFG_PISIOCFG_IO9SEL_MSK BITS(SYSCFG_PISIOCFG_IO9SEL_POSS,SYSCFG_PISIOCFG_IO9SEL_POSE)
#define SYSCFG_PISIOCFG_IO8SEL_POSS 16U
#define SYSCFG_PISIOCFG_IO8SEL_POSE 17U
#define SYSCFG_PISIOCFG_IO8SEL_MSK BITS(SYSCFG_PISIOCFG_IO8SEL_POSS,SYSCFG_PISIOCFG_IO8SEL_POSE)
#define SYSCFG_PISIOCFG_IO7SEL_POSS 14U
#define SYSCFG_PISIOCFG_IO7SEL_POSE 15U
#define SYSCFG_PISIOCFG_IO7SEL_MSK BITS(SYSCFG_PISIOCFG_IO7SEL_POSS,SYSCFG_PISIOCFG_IO7SEL_POSE)
#define SYSCFG_PISIOCFG_IO6SEL_POSS 12U
#define SYSCFG_PISIOCFG_IO6SEL_POSE 13U
#define SYSCFG_PISIOCFG_IO6SEL_MSK BITS(SYSCFG_PISIOCFG_IO6SEL_POSS,SYSCFG_PISIOCFG_IO6SEL_POSE)
#define SYSCFG_PISIOCFG_IO5SEL_POSS 10U
#define SYSCFG_PISIOCFG_IO5SEL_POSE 11U
#define SYSCFG_PISIOCFG_IO5SEL_MSK BITS(SYSCFG_PISIOCFG_IO5SEL_POSS,SYSCFG_PISIOCFG_IO5SEL_POSE)
#define SYSCFG_PISIOCFG_IO4SEL_POSS 8U
#define SYSCFG_PISIOCFG_IO4SEL_POSE 9U
#define SYSCFG_PISIOCFG_IO4SEL_MSK BITS(SYSCFG_PISIOCFG_IO4SEL_POSS,SYSCFG_PISIOCFG_IO4SEL_POSE)
#define SYSCFG_PISIOCFG_IO3SEL_POSS 6U
#define SYSCFG_PISIOCFG_IO3SEL_POSE 7U
#define SYSCFG_PISIOCFG_IO3SEL_MSK BITS(SYSCFG_PISIOCFG_IO3SEL_POSS,SYSCFG_PISIOCFG_IO3SEL_POSE)
#define SYSCFG_PISIOCFG_IO2SEL_POSS 4U
#define SYSCFG_PISIOCFG_IO2SEL_POSE 5U
#define SYSCFG_PISIOCFG_IO2SEL_MSK BITS(SYSCFG_PISIOCFG_IO2SEL_POSS,SYSCFG_PISIOCFG_IO2SEL_POSE)
#define SYSCFG_PISIOCFG_IO1SEL_POSS 2U
#define SYSCFG_PISIOCFG_IO1SEL_POSE 3U
#define SYSCFG_PISIOCFG_IO1SEL_MSK BITS(SYSCFG_PISIOCFG_IO1SEL_POSS,SYSCFG_PISIOCFG_IO1SEL_POSE)
#define SYSCFG_PISIOCFG_IO0SEL_POSS 0U
#define SYSCFG_PISIOCFG_IO0SEL_POSE 1U
#define SYSCFG_PISIOCFG_IO0SEL_MSK BITS(SYSCFG_PISIOCFG_IO0SEL_POSS,SYSCFG_PISIOCFG_IO0SEL_POSE)
typedef struct
{
__IO uint32_t PROT;
uint32_t RESERVED0 ;
__IO uint32_t BTADDR;
__IO uint32_t TBKCFG;
__IO uint32_t PISIOCFG;
} SYSCFG_TypeDef;
#endif /* __REG_SYSCFG_H__ */
/************* (C) COPYRIGHT Eastsoft Microelectronics *****END OF FILE****/
|
37a1cbf09e09e73c52b3945555cb563f780abadb
|
41db6c672362ccafdd28af40ecf7df51ffa90a15
|
/src/heapy/hv_cli_rel.c
|
5b7725f97cf23c1c937cef8bc047b9ec93010700
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
zhuyifei1999/guppy3
|
e5649a066199a92dc3bf8e77bdd6ffb44e790449
|
1b2db87af36388e43afd6ce5774b869bcc4a9452
|
refs/heads/master
| 2023-06-24T23:03:52.612921
| 2023-06-17T01:18:06
| 2023-06-17T01:54:06
| 202,611,372
| 371
| 24
|
MIT
| 2023-06-17T01:54:09
| 2019-08-15T21:05:15
|
Python
|
UTF-8
|
C
| false
| false
| 10,049
|
c
|
hv_cli_rel.c
|
/* Classify by 'relation', incoming (perhaps outcoming)
inrel
outrel
*/
PyDoc_STRVAR(hv_cli_inrel_doc,
"HV.cli_inrel(referrers, memo) -> ObjectClassifier\n"
"\n"
"Return a classifier that classifes by \"incoming relations\".\n"
"\n"
"The classification of an object is the set of incoming relations.\n"
"\n"
" referrers A NodeGraph object used to\n"
" map each object to its referrers.\n"
"\n"
" memo A dict object used to\n"
" memoize the classification sets.\n"
);
PyDoc_STRVAR(rel_doc,
"");
static void
rel_dealloc(NyRelationObject *op)
{
PyObject_GC_UnTrack(op);
Ny_TRASHCAN_BEGIN(op, rel_dealloc)
Py_XDECREF(op->relator);
Py_TYPE(op)->tp_free(op);
Ny_TRASHCAN_END(op)
}
PyObject *
NyRelation_SubTypeNew(PyTypeObject *type, int kind, PyObject *relator)
{
NyRelationObject *rel = (NyRelationObject *)type->tp_alloc(type, 1);
if (!rel)
return 0;
rel->kind = kind;
if (!relator) {
relator = Py_None;
}
rel->relator = relator;
Py_INCREF(relator);
return (PyObject *)rel;
}
NyRelationObject *
NyRelation_New(int kind, PyObject *relator)
{
return (NyRelationObject *)NyRelation_SubTypeNew(&NyRelation_Type, kind, relator);
}
static PyObject *
rel_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
int kind;
PyObject *relator;
static char *kwlist[] = {"kind", "relator", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "iO:rel_new",kwlist,
&kind,
&relator))
return NULL;
if (! (0 < kind && kind < NYHR_LIMIT) ) {
PyErr_Format(PyExc_ValueError,
"rel_new: Invalid relation kind: %d, must be > 0 and < %d.",
kind,
NYHR_LIMIT);
return 0;
}
return NyRelation_SubTypeNew(type, kind, relator);
}
static int
rel_traverse(NyRelationObject *op, visitproc visit, void *arg)
{
if (op->relator)
return visit(op->relator, arg);
return 0;
}
static int
rel_clear(NyRelationObject *op)
{
Py_XDECREF(op->relator);
op->relator = NULL;
return 0;
}
static Py_hash_t
rel_hash(NyRelationObject *op)
{
Py_hash_t x = PyObject_Hash(op->relator);
if (x == -1)
return -1;
x ^= op->kind;
if (x == -1)
x = -2;
return x;
}
static PyObject *
rel_richcompare(PyObject *v, PyObject *w, int op)
{
NyRelationObject *vr, *wr;
int vkind, wkind;
if (! (NyRelation_Check(v) && NyRelation_Check(w))) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
vr = (NyRelationObject *)v;
wr = (NyRelationObject *)w;
vkind = vr->kind;
wkind = wr->kind;
if (vkind != wkind) {
PyObject *result;
int cmp;
switch (op) {
case Py_LT: cmp = vkind < wkind; break;
case Py_LE: cmp = vkind <= wkind; break;
case Py_EQ: cmp = vkind == wkind; break;
case Py_NE: cmp = vkind != wkind; break;
case Py_GT: cmp = vkind > wkind; break;
case Py_GE: cmp = vkind >= wkind; break;
default: return NULL; /* cannot happen */
}
result = cmp? Py_True:Py_False;
Py_INCREF(result);
return result;
}
return PyObject_RichCompare(vr->relator, wr->relator, op);
}
static PyMethodDef rel_methods[] = {
{0} /* sentinel */
};
#define OFF(x) offsetof(NyRelationObject, x)
static PyMemberDef rel_members[] = {
{"kind", T_INT, OFF(kind), READONLY},
{"relator", T_OBJECT, OFF(relator), READONLY},
{0} /* Sentinel */
};
#undef OFF
PyTypeObject NyRelation_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "guppy.heapy.heapyc.Relation",
.tp_basicsize = sizeof(NyRelationObject),
.tp_dealloc = (destructor)rel_dealloc,
.tp_hash = (hashfunc)rel_hash,
.tp_getattro = PyObject_GenericGetAttr,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_doc = rel_doc,
.tp_traverse = (traverseproc)rel_traverse,
.tp_clear = (inquiry)rel_clear,
.tp_richcompare = rel_richcompare,
.tp_methods = rel_methods,
.tp_members = rel_members,
.tp_alloc = PyType_GenericAlloc,
.tp_new = rel_new,
.tp_free = PyObject_GC_Del,
};
typedef struct {
/* Mimics a tuple - xxx should perhaps make a proper object/use tuple macros?! */
PyObject_VAR_HEAD
NyHeapViewObject *hv;
NyNodeGraphObject *rg;
NyRelationObject *rel;
PyObject *memokind, *memorel;
} InRelObject;
typedef struct {
PyObject *memorel;
NyNodeSetObject *ns;
} MemoRelArg;
static int
inrel_visit_memoize_relation(PyObject *obj, MemoRelArg *arg)
{
PyObject *mrel;
if (!NyRelation_Check(obj)) {
PyErr_Format(PyExc_TypeError,
"inrel_visit_memoize_relation: can only memoize relation (not \"%.200s\")",
Py_TYPE(obj)->tp_name);
return -1;
}
mrel = PyDict_GetItem(arg->memorel, obj);
if (!mrel) {
if (PyErr_Occurred())
return -1;
if (PyDict_SetItem(arg->memorel, obj, obj) == -1)
return -1;
mrel = obj;
}
if (NyNodeSet_setobj(arg->ns, mrel) == -1)
return -1;
return 0;
}
static PyObject *
inrel_fast_memoized_kind(InRelObject * self, PyObject *kind)
/* When the elements are already memoized */
{
PyObject *result = PyDict_GetItem(self->memokind, kind);
if (!result) {
if (PyErr_Occurred())
goto Err;
if (PyDict_SetItem(self->memokind, kind, kind) == -1)
goto Err;
result = kind;
}
Py_INCREF(result);
return result;
Err:
return 0;
}
static PyObject *
hv_cli_inrel_memoized_kind(InRelObject * self, PyObject *kind)
{
MemoRelArg arg;
PyObject *result;
arg.memorel = self->memorel;
arg.ns = hv_mutnodeset_new(self->hv);
if (!arg.ns)
return 0;
if (iterable_iterate(kind, (visitproc)inrel_visit_memoize_relation, &arg) == -1)
goto Err;
if (NyNodeSet_be_immutable(&arg.ns) == -1)
goto Err;
result = inrel_fast_memoized_kind(self, (PyObject *)arg.ns);
Ret:
Py_DECREF(arg.ns);
return result;
Err:
result = 0;
goto Ret;
}
typedef struct {
NyHeapRelate hr;
int err;
NyNodeSetObject *relset;
NyRelationObject *rel;
PyObject *memorel;
} hv_cli_inrel_visit_arg;
static int
hv_cli_inrel_visit(unsigned int kind, PyObject *relator, NyHeapRelate *arg_)
{
hv_cli_inrel_visit_arg *arg = (void *)arg_;
PyObject *rel;
arg->err = -1;
if (!relator) {
if (PyErr_Occurred())
return -1;
relator = Py_None;
Py_INCREF(relator);
}
arg->rel->kind = kind;
arg->rel->relator = relator;
rel = PyDict_GetItem(arg->memorel, (PyObject *)arg->rel);
if (!rel) {
rel = (PyObject *)NyRelation_New(kind, relator);
if (!rel)
goto ret;
if (PyDict_SetItem(arg->memorel, rel, rel) == -1) {
Py_DECREF(rel);
goto ret;
}
Py_DECREF(rel);
}
if (NyNodeSet_setobj(arg->relset, rel) != -1)
arg->err = 0;
ret:
Py_DECREF(relator);
return arg->err;
}
static PyObject *
hv_cli_inrel_classify(InRelObject * self, PyObject *obj)
{
NyNodeGraphEdge *lo, *hi, *cur;
PyObject *result;
ExtraType *xt;
hv_cli_inrel_visit_arg crva;
crva.hr.flags = 0;
crva.hr.hv = (PyObject *)self->hv;
crva.hr.tgt = obj;
crva.hr.visit = hv_cli_inrel_visit;
crva.err = 0;
crva.memorel = self->memorel;
assert(self->rel->relator == Py_None); /* This will be restored, w/o incref, at return. */
crva.rel = self->rel;
crva.relset = hv_mutnodeset_new(self->hv);
if (!crva.relset)
return 0;
if (NyNodeGraph_Region(self->rg, obj, &lo, &hi) == -1) {
goto Err;
}
for (cur = lo; cur < hi; cur++) {
if (cur->tgt == Py_None)
continue;
crva.hr.src = cur->tgt;
xt = hv_extra_type(self->hv, Py_TYPE(crva.hr.src));
assert (xt->xt_hv == self->hv);
assert(self->hv == (void *)crva.hr.hv);
if (xt->xt_relate(xt, &crva.hr) == -1 || crva.err) {
/* fprintf(stderr, "xt 0x%x\n", xt); */
goto Err;
}
}
if (NyNodeSet_be_immutable(&crva.relset) == -1)
goto Err;
result = inrel_fast_memoized_kind(self, (PyObject *)crva.relset);
Ret:
Py_DECREF(crva.relset);
self->rel->relator = Py_None;
return result;
Err:
result = 0;
goto Ret;
}
static int
hv_cli_inrel_le(PyObject * self, PyObject *a, PyObject *b)
{
return PyObject_RichCompareBool(a, b, Py_LE);
}
static NyObjectClassifierDef hv_cli_inrel_def = {
0,
sizeof(NyObjectClassifierDef),
"hv_cli_rcs",
"classifier returning ...",
(binaryfunc)hv_cli_inrel_classify,
(binaryfunc)hv_cli_inrel_memoized_kind,
hv_cli_inrel_le
};
static PyObject *
hv_cli_inrel(NyHeapViewObject *hv, PyObject *args)
{
PyObject *r;
InRelObject *s, tmp;
if (!PyArg_ParseTuple(args, "O!O!O!:cli_inrel",
&NyNodeGraph_Type, &tmp.rg,
&PyDict_Type, &tmp.memokind,
&PyDict_Type, &tmp.memorel
)) {
return NULL;
}
s = NYTUPLELIKE_NEW(InRelObject);
if (!s)
return 0;
s->hv = hv;
Py_INCREF(s->hv);
s->rg = tmp.rg;
Py_INCREF(s->rg);
s->memokind = tmp.memokind;
Py_INCREF(s->memokind);
s->memorel = tmp.memorel;
Py_INCREF(s->memorel);
/* Init a relation object used for lookup, to save an allocation per relation. */
s->rel = NyRelation_New(1, Py_None); /* kind & relator will be changed */
if (!s->rel) {
Py_DECREF(s);
return 0;
}
r = NyObjectClassifier_New((PyObject *)s, &hv_cli_inrel_def);
Py_DECREF(s);
return r;
}
|
4d834508f57f3a2d15d8110cda5a65d33ec2a896
|
7be8e3636bf08ebdc6662879dc5afec548705537
|
/ios/Pods/Headers/Public/Flipper-Folly/folly/executors/thread_factory/PriorityThreadFactory.h
|
be80648642011a6989a5cfb92bb83bb683f105b8
|
[
"MIT"
] |
permissive
|
rdhox/react-native-smooth-picker
|
3c7384f1fed0e37f076361cce96071d01b70e209
|
ae9316c49512f7ed9824c5a3ad50cdf5e80fffa9
|
refs/heads/master
| 2023-01-08T16:59:40.709147
| 2021-07-03T14:13:21
| 2021-07-03T14:13:21
| 160,224,312
| 230
| 31
|
MIT
| 2023-01-06T01:46:04
| 2018-12-03T16:54:10
|
TypeScript
|
UTF-8
|
C
| false
| false
| 86
|
h
|
PriorityThreadFactory.h
|
../../../../../../Flipper-Folly/folly/executors/thread_factory/PriorityThreadFactory.h
|
42dec6f2152f6db0c3a7b310824d2a27e4338e37
|
7c857119fe1505b1d80d6e62969661c06dc1a2f4
|
/UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
|
a00786a8ebef0b5baaede821adec2b15f2d7b2fa
|
[
"BSD-2-Clause"
] |
permissive
|
CloverHackyColor/CloverBootloader
|
7042ca7dd6b513d22be591a295e49071ae1482ee
|
2711170df4f60b2ae5aa20add3e00f35cf57b7e5
|
refs/heads/master
| 2023-08-30T22:14:34.590134
| 2023-08-27T19:14:02
| 2023-08-27T19:14:02
| 205,810,121
| 4,734
| 770
|
BSD-2-Clause
| 2023-09-03T12:41:33
| 2019-09-02T08:22:14
|
C
|
UTF-8
|
C
| false
| false
| 22,044
|
c
|
SmmCpuFeaturesLib.c
|
/** @file
The CPU specific programming for PiSmmCpuDxeSmm module.
Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <PiSmm.h>
#include <Library/SmmCpuFeaturesLib.h>
#include <Library/BaseLib.h>
#include <Library/MtrrLib.h>
#include <Library/PcdLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/DebugLib.h>
#include <Register/Intel/Cpuid.h>
#include <Register/Intel/SmramSaveStateMap.h>
//
// Machine Specific Registers (MSRs)
//
#define SMM_FEATURES_LIB_IA32_MTRR_CAP 0x0FE
#define SMM_FEATURES_LIB_IA32_FEATURE_CONTROL 0x03A
#define SMM_FEATURES_LIB_IA32_SMRR_PHYSBASE 0x1F2
#define SMM_FEATURES_LIB_IA32_SMRR_PHYSMASK 0x1F3
#define SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSBASE 0x0A0
#define SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSMASK 0x0A1
#define EFI_MSR_SMRR_MASK 0xFFFFF000
#define EFI_MSR_SMRR_PHYS_MASK_VALID BIT11
#define SMM_FEATURES_LIB_SMM_FEATURE_CONTROL 0x4E0
//
// MSRs required for configuration of SMM Code Access Check
//
#define SMM_FEATURES_LIB_IA32_MCA_CAP 0x17D
#define SMM_CODE_ACCESS_CHK_BIT BIT58
/**
Internal worker function that is called to complete CPU initialization at the
end of SmmCpuFeaturesInitializeProcessor().
**/
VOID
FinishSmmCpuFeaturesInitializeProcessor (
VOID
);
//
// Set default value to assume SMRR is not supported
//
BOOLEAN mSmrrSupported = FALSE;
//
// Set default value to assume MSR_SMM_FEATURE_CONTROL is not supported
//
BOOLEAN mSmmFeatureControlSupported = FALSE;
//
// Set default value to assume IA-32 Architectural MSRs are used
//
UINT32 mSmrrPhysBaseMsr = SMM_FEATURES_LIB_IA32_SMRR_PHYSBASE;
UINT32 mSmrrPhysMaskMsr = SMM_FEATURES_LIB_IA32_SMRR_PHYSMASK;
//
// Set default value to assume MTRRs need to be configured on each SMI
//
BOOLEAN mNeedConfigureMtrrs = TRUE;
//
// Array for state of SMRR enable on all CPUs
//
BOOLEAN *mSmrrEnabled;
/**
The constructor function
@param[in] ImageHandle The firmware allocated handle for the EFI image.
@param[in] SystemTable A pointer to the EFI System Table.
@retval EFI_SUCCESS The constructor always returns EFI_SUCCESS.
**/
EFI_STATUS
EFIAPI
SmmCpuFeaturesLibConstructor (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
UINT32 RegEax;
UINT32 RegEdx;
UINTN FamilyId;
UINTN ModelId;
//
// Retrieve CPU Family and Model
//
AsmCpuid (CPUID_VERSION_INFO, &RegEax, NULL, NULL, &RegEdx);
FamilyId = (RegEax >> 8) & 0xf;
ModelId = (RegEax >> 4) & 0xf;
if (FamilyId == 0x06 || FamilyId == 0x0f) {
ModelId = ModelId | ((RegEax >> 12) & 0xf0);
}
//
// Check CPUID(CPUID_VERSION_INFO).EDX[12] for MTRR capability
//
if ((RegEdx & BIT12) != 0) {
//
// Check MTRR_CAP MSR bit 11 for SMRR support
//
if ((AsmReadMsr64 (SMM_FEATURES_LIB_IA32_MTRR_CAP) & BIT11) != 0) {
mSmrrSupported = TRUE;
}
}
//
// Intel(R) 64 and IA-32 Architectures Software Developer's Manual
// Volume 3C, Section 35.3 MSRs in the Intel(R) Atom(TM) Processor Family
//
// If CPU Family/Model is 06_1CH, 06_26H, 06_27H, 06_35H or 06_36H, then
// SMRR Physical Base and SMM Physical Mask MSRs are not available.
//
if (FamilyId == 0x06) {
if (ModelId == 0x1C || ModelId == 0x26 || ModelId == 0x27 || ModelId == 0x35 || ModelId == 0x36) {
mSmrrSupported = FALSE;
}
}
//
// Intel(R) 64 and IA-32 Architectures Software Developer's Manual
// Volume 3C, Section 35.2 MSRs in the Intel(R) Core(TM) 2 Processor Family
//
// If CPU Family/Model is 06_0F or 06_17, then use Intel(R) Core(TM) 2
// Processor Family MSRs
//
if (FamilyId == 0x06) {
if (ModelId == 0x17 || ModelId == 0x0f) {
mSmrrPhysBaseMsr = SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSBASE;
mSmrrPhysMaskMsr = SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSMASK;
}
}
//
// Intel(R) 64 and IA-32 Architectures Software Developer's Manual
// Volume 3C, Section 34.4.2 SMRAM Caching
// An IA-32 processor does not automatically write back and invalidate its
// caches before entering SMM or before exiting SMM. Because of this behavior,
// care must be taken in the placement of the SMRAM in system memory and in
// the caching of the SMRAM to prevent cache incoherence when switching back
// and forth between SMM and protected mode operation.
//
// An IA-32 processor is a processor that does not support the Intel 64
// Architecture. Support for the Intel 64 Architecture can be detected from
// CPUID(CPUID_EXTENDED_CPU_SIG).EDX[29]
//
// If an IA-32 processor is detected, then set mNeedConfigureMtrrs to TRUE,
// so caches are flushed on SMI entry and SMI exit, the interrupted code
// MTRRs are saved/restored, and MTRRs for SMM are loaded.
//
AsmCpuid (CPUID_EXTENDED_FUNCTION, &RegEax, NULL, NULL, NULL);
if (RegEax >= CPUID_EXTENDED_CPU_SIG) {
AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &RegEdx);
if ((RegEdx & BIT29) != 0) {
mNeedConfigureMtrrs = FALSE;
}
}
//
// Allocate array for state of SMRR enable on all CPUs
//
mSmrrEnabled = (BOOLEAN *)AllocatePool (sizeof (BOOLEAN) * PcdGet32 (PcdCpuMaxLogicalProcessorNumber));
ASSERT (mSmrrEnabled != NULL);
return EFI_SUCCESS;
}
/**
Called during the very first SMI into System Management Mode to initialize
CPU features, including SMBASE, for the currently executing CPU. Since this
is the first SMI, the SMRAM Save State Map is at the default address of
SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET. The currently executing
CPU is specified by CpuIndex and CpuIndex can be used to access information
about the currently executing CPU in the ProcessorInfo array and the
HotPlugCpuData data structure.
@param[in] CpuIndex The index of the CPU to initialize. The value
must be between 0 and the NumberOfCpus field in
the System Management System Table (SMST).
@param[in] IsMonarch TRUE if the CpuIndex is the index of the CPU that
was elected as monarch during System Management
Mode initialization.
FALSE if the CpuIndex is not the index of the CPU
that was elected as monarch during System
Management Mode initialization.
@param[in] ProcessorInfo Pointer to an array of EFI_PROCESSOR_INFORMATION
structures. ProcessorInfo[CpuIndex] contains the
information for the currently executing CPU.
@param[in] CpuHotPlugData Pointer to the CPU_HOT_PLUG_DATA structure that
contains the ApidId and SmBase arrays.
**/
VOID
EFIAPI
SmmCpuFeaturesInitializeProcessor (
IN UINTN CpuIndex,
IN BOOLEAN IsMonarch,
IN EFI_PROCESSOR_INFORMATION *ProcessorInfo,
IN CPU_HOT_PLUG_DATA *CpuHotPlugData
)
{
SMRAM_SAVE_STATE_MAP *CpuState;
UINT64 FeatureControl;
UINT32 RegEax;
UINT32 RegEdx;
UINTN FamilyId;
UINTN ModelId;
//
// Configure SMBASE.
//
CpuState = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
CpuState->x86.SMBASE = (UINT32)CpuHotPlugData->SmBase[CpuIndex];
//
// Intel(R) 64 and IA-32 Architectures Software Developer's Manual
// Volume 3C, Section 35.2 MSRs in the Intel(R) Core(TM) 2 Processor Family
//
// If Intel(R) Core(TM) Core(TM) 2 Processor Family MSRs are being used, then
// make sure SMRR Enable(BIT3) of MSR_FEATURE_CONTROL MSR(0x3A) is set before
// accessing SMRR base/mask MSRs. If Lock(BIT0) of MSR_FEATURE_CONTROL MSR(0x3A)
// is set, then the MSR is locked and can not be modified.
//
if (mSmrrSupported && mSmrrPhysBaseMsr == SMM_FEATURES_LIB_IA32_CORE_SMRR_PHYSBASE) {
FeatureControl = AsmReadMsr64 (SMM_FEATURES_LIB_IA32_FEATURE_CONTROL);
if ((FeatureControl & BIT3) == 0) {
if ((FeatureControl & BIT0) == 0) {
AsmWriteMsr64 (SMM_FEATURES_LIB_IA32_FEATURE_CONTROL, FeatureControl | BIT3);
} else {
mSmrrSupported = FALSE;
}
}
}
//
// If SMRR is supported, then program SMRR base/mask MSRs.
// The EFI_MSR_SMRR_PHYS_MASK_VALID bit is not set until the first normal SMI.
// The code that initializes SMM environment is running in normal mode
// from SMRAM region. If SMRR is enabled here, then the SMRAM region
// is protected and the normal mode code execution will fail.
//
if (mSmrrSupported) {
//
// SMRR size cannot be less than 4-KBytes
// SMRR size must be of length 2^n
// SMRR base alignment cannot be less than SMRR length
//
if ((CpuHotPlugData->SmrrSize < SIZE_4KB) ||
(CpuHotPlugData->SmrrSize != GetPowerOfTwo32 (CpuHotPlugData->SmrrSize)) ||
((CpuHotPlugData->SmrrBase & ~(CpuHotPlugData->SmrrSize - 1)) != CpuHotPlugData->SmrrBase)) {
//
// Print message and halt if CPU is Monarch
//
if (IsMonarch) {
DEBUG ((DEBUG_ERROR, "SMM Base/Size does not meet alignment/size requirement!\n"));
CpuDeadLoop ();
}
} else {
AsmWriteMsr64 (mSmrrPhysBaseMsr, CpuHotPlugData->SmrrBase | MTRR_CACHE_WRITE_BACK);
AsmWriteMsr64 (mSmrrPhysMaskMsr, (~(CpuHotPlugData->SmrrSize - 1) & EFI_MSR_SMRR_MASK));
mSmrrEnabled[CpuIndex] = FALSE;
}
}
//
// Retrieve CPU Family and Model
//
AsmCpuid (CPUID_VERSION_INFO, &RegEax, NULL, NULL, &RegEdx);
FamilyId = (RegEax >> 8) & 0xf;
ModelId = (RegEax >> 4) & 0xf;
if (FamilyId == 0x06 || FamilyId == 0x0f) {
ModelId = ModelId | ((RegEax >> 12) & 0xf0);
}
//
// Intel(R) 64 and IA-32 Architectures Software Developer's Manual
// Volume 3C, Section 35.10.1 MSRs in 4th Generation Intel(R) Core(TM)
// Processor Family.
//
// If CPU Family/Model is 06_3C, 06_45, or 06_46 then use 4th Generation
// Intel(R) Core(TM) Processor Family MSRs.
//
if (FamilyId == 0x06) {
if (ModelId == 0x3C || ModelId == 0x45 || ModelId == 0x46 ||
ModelId == 0x3D || ModelId == 0x47 || ModelId == 0x4E || ModelId == 0x4F ||
ModelId == 0x3F || ModelId == 0x56 || ModelId == 0x57 || ModelId == 0x5C) {
//
// Check to see if the CPU supports the SMM Code Access Check feature
// Do not access this MSR unless the CPU supports the SmmRegFeatureControl
//
if ((AsmReadMsr64 (SMM_FEATURES_LIB_IA32_MCA_CAP) & SMM_CODE_ACCESS_CHK_BIT) != 0) {
mSmmFeatureControlSupported = TRUE;
}
}
}
//
// Call internal worker function that completes the CPU initialization
//
FinishSmmCpuFeaturesInitializeProcessor ();
}
/**
This function updates the SMRAM save state on the currently executing CPU
to resume execution at a specific address after an RSM instruction. This
function must evaluate the SMRAM save state to determine the execution mode
the RSM instruction resumes and update the resume execution address with
either NewInstructionPointer32 or NewInstructionPoint. The auto HALT restart
flag in the SMRAM save state must always be cleared. This function returns
the value of the instruction pointer from the SMRAM save state that was
replaced. If this function returns 0, then the SMRAM save state was not
modified.
This function is called during the very first SMI on each CPU after
SmmCpuFeaturesInitializeProcessor() to set a flag in normal execution mode
to signal that the SMBASE of each CPU has been updated before the default
SMBASE address is used for the first SMI to the next CPU.
@param[in] CpuIndex The index of the CPU to hook. The value
must be between 0 and the NumberOfCpus
field in the System Management System Table
(SMST).
@param[in] CpuState Pointer to SMRAM Save State Map for the
currently executing CPU.
@param[in] NewInstructionPointer32 Instruction pointer to use if resuming to
32-bit execution mode from 64-bit SMM.
@param[in] NewInstructionPointer Instruction pointer to use if resuming to
same execution mode as SMM.
@retval 0 This function did modify the SMRAM save state.
@retval > 0 The original instruction pointer value from the SMRAM save state
before it was replaced.
**/
UINT64
EFIAPI
SmmCpuFeaturesHookReturnFromSmm (
IN UINTN CpuIndex,
IN SMRAM_SAVE_STATE_MAP *CpuState,
IN UINT64 NewInstructionPointer32,
IN UINT64 NewInstructionPointer
)
{
return 0;
}
/**
Hook point in normal execution mode that allows the one CPU that was elected
as monarch during System Management Mode initialization to perform additional
initialization actions immediately after all of the CPUs have processed their
first SMI and called SmmCpuFeaturesInitializeProcessor() relocating SMBASE
into a buffer in SMRAM and called SmmCpuFeaturesHookReturnFromSmm().
**/
VOID
EFIAPI
SmmCpuFeaturesSmmRelocationComplete (
VOID
)
{
}
/**
Determines if MTRR registers must be configured to set SMRAM cache-ability
when executing in System Management Mode.
@retval TRUE MTRR registers must be configured to set SMRAM cache-ability.
@retval FALSE MTRR registers do not need to be configured to set SMRAM
cache-ability.
**/
BOOLEAN
EFIAPI
SmmCpuFeaturesNeedConfigureMtrrs (
VOID
)
{
return mNeedConfigureMtrrs;
}
/**
Disable SMRR register if SMRR is supported and SmmCpuFeaturesNeedConfigureMtrrs()
returns TRUE.
**/
VOID
EFIAPI
SmmCpuFeaturesDisableSmrr (
VOID
)
{
if (mSmrrSupported && mNeedConfigureMtrrs) {
AsmWriteMsr64 (mSmrrPhysMaskMsr, AsmReadMsr64(mSmrrPhysMaskMsr) & ~EFI_MSR_SMRR_PHYS_MASK_VALID);
}
}
/**
Enable SMRR register if SMRR is supported and SmmCpuFeaturesNeedConfigureMtrrs()
returns TRUE.
**/
VOID
EFIAPI
SmmCpuFeaturesReenableSmrr (
VOID
)
{
if (mSmrrSupported && mNeedConfigureMtrrs) {
AsmWriteMsr64 (mSmrrPhysMaskMsr, AsmReadMsr64(mSmrrPhysMaskMsr) | EFI_MSR_SMRR_PHYS_MASK_VALID);
}
}
/**
Processor specific hook point each time a CPU enters System Management Mode.
@param[in] CpuIndex The index of the CPU that has entered SMM. The value
must be between 0 and the NumberOfCpus field in the
System Management System Table (SMST).
**/
VOID
EFIAPI
SmmCpuFeaturesRendezvousEntry (
IN UINTN CpuIndex
)
{
//
// If SMRR is supported and this is the first normal SMI, then enable SMRR
//
if (mSmrrSupported && !mSmrrEnabled[CpuIndex]) {
AsmWriteMsr64 (mSmrrPhysMaskMsr, AsmReadMsr64 (mSmrrPhysMaskMsr) | EFI_MSR_SMRR_PHYS_MASK_VALID);
mSmrrEnabled[CpuIndex] = TRUE;
}
}
/**
Processor specific hook point each time a CPU exits System Management Mode.
@param[in] CpuIndex The index of the CPU that is exiting SMM. The value must
be between 0 and the NumberOfCpus field in the System
Management System Table (SMST).
**/
VOID
EFIAPI
SmmCpuFeaturesRendezvousExit (
IN UINTN CpuIndex
)
{
}
/**
Check to see if an SMM register is supported by a specified CPU.
@param[in] CpuIndex The index of the CPU to check for SMM register support.
The value must be between 0 and the NumberOfCpus field
in the System Management System Table (SMST).
@param[in] RegName Identifies the SMM register to check for support.
@retval TRUE The SMM register specified by RegName is supported by the CPU
specified by CpuIndex.
@retval FALSE The SMM register specified by RegName is not supported by the
CPU specified by CpuIndex.
**/
BOOLEAN
EFIAPI
SmmCpuFeaturesIsSmmRegisterSupported (
IN UINTN CpuIndex,
IN SMM_REG_NAME RegName
)
{
if (mSmmFeatureControlSupported && RegName == SmmRegFeatureControl) {
return TRUE;
}
return FALSE;
}
/**
Returns the current value of the SMM register for the specified CPU.
If the SMM register is not supported, then 0 is returned.
@param[in] CpuIndex The index of the CPU to read the SMM register. The
value must be between 0 and the NumberOfCpus field in
the System Management System Table (SMST).
@param[in] RegName Identifies the SMM register to read.
@return The value of the SMM register specified by RegName from the CPU
specified by CpuIndex.
**/
UINT64
EFIAPI
SmmCpuFeaturesGetSmmRegister (
IN UINTN CpuIndex,
IN SMM_REG_NAME RegName
)
{
if (mSmmFeatureControlSupported && RegName == SmmRegFeatureControl) {
return AsmReadMsr64 (SMM_FEATURES_LIB_SMM_FEATURE_CONTROL);
}
return 0;
}
/**
Sets the value of an SMM register on a specified CPU.
If the SMM register is not supported, then no action is performed.
@param[in] CpuIndex The index of the CPU to write the SMM register. The
value must be between 0 and the NumberOfCpus field in
the System Management System Table (SMST).
@param[in] RegName Identifies the SMM register to write.
registers are read-only.
@param[in] Value The value to write to the SMM register.
**/
VOID
EFIAPI
SmmCpuFeaturesSetSmmRegister (
IN UINTN CpuIndex,
IN SMM_REG_NAME RegName,
IN UINT64 Value
)
{
if (mSmmFeatureControlSupported && RegName == SmmRegFeatureControl) {
AsmWriteMsr64 (SMM_FEATURES_LIB_SMM_FEATURE_CONTROL, Value);
}
}
/**
Read an SMM Save State register on the target processor. If this function
returns EFI_UNSUPPORTED, then the caller is responsible for reading the
SMM Save Sate register.
@param[in] CpuIndex The index of the CPU to read the SMM Save State. The
value must be between 0 and the NumberOfCpus field in
the System Management System Table (SMST).
@param[in] Register The SMM Save State register to read.
@param[in] Width The number of bytes to read from the CPU save state.
@param[out] Buffer Upon return, this holds the CPU register value read
from the save state.
@retval EFI_SUCCESS The register was read from Save State.
@retval EFI_INVALID_PARAMETER Buffer is NULL.
@retval EFI_UNSUPPORTED This function does not support reading Register.
**/
EFI_STATUS
EFIAPI
SmmCpuFeaturesReadSaveStateRegister (
IN UINTN CpuIndex,
IN EFI_SMM_SAVE_STATE_REGISTER Register,
IN UINTN Width,
OUT VOID *Buffer
)
{
return EFI_UNSUPPORTED;
}
/**
Writes an SMM Save State register on the target processor. If this function
returns EFI_UNSUPPORTED, then the caller is responsible for writing the
SMM Save Sate register.
@param[in] CpuIndex The index of the CPU to write the SMM Save State. The
value must be between 0 and the NumberOfCpus field in
the System Management System Table (SMST).
@param[in] Register The SMM Save State register to write.
@param[in] Width The number of bytes to write to the CPU save state.
@param[in] Buffer Upon entry, this holds the new CPU register value.
@retval EFI_SUCCESS The register was written to Save State.
@retval EFI_INVALID_PARAMETER Buffer is NULL.
@retval EFI_UNSUPPORTED This function does not support writing Register.
**/
EFI_STATUS
EFIAPI
SmmCpuFeaturesWriteSaveStateRegister (
IN UINTN CpuIndex,
IN EFI_SMM_SAVE_STATE_REGISTER Register,
IN UINTN Width,
IN CONST VOID *Buffer
)
{
return EFI_UNSUPPORTED;
}
/**
This function is hook point called after the gEfiSmmReadyToLockProtocolGuid
notification is completely processed.
**/
VOID
EFIAPI
SmmCpuFeaturesCompleteSmmReadyToLock (
VOID
)
{
}
/**
This API provides a method for a CPU to allocate a specific region for storing page tables.
This API can be called more once to allocate memory for page tables.
Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the
allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL
is returned. If there is not enough memory remaining to satisfy the request, then NULL is
returned.
This function can also return NULL if there is no preference on where the page tables are allocated in SMRAM.
@param Pages The number of 4 KB pages to allocate.
@return A pointer to the allocated buffer for page tables.
@retval NULL Fail to allocate a specific region for storing page tables,
Or there is no preference on where the page tables are allocated in SMRAM.
**/
VOID *
EFIAPI
SmmCpuFeaturesAllocatePageTableMemory (
IN UINTN Pages
)
{
return NULL;
}
|
24fea2c9c1f7e530c829e3a14f53ea776f8f4bb1
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/arch/risc-v/src/rv32m1/rv32m1_timerisr.c
|
60607b1efbee97e7977d25f75ff9bb001811a3b6
|
[
"MIT-open-group",
"BSD-3-Clause",
"HPND-sell-variant",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"LicenseRef-scancode-bsd-atmel",
"LicenseRef-scancode-gary-s-brown",
"LicenseRef-scancode-proprietary-license",
"SunPro",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-other-permissive",
"HPND",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"GPL-1.0-or-later",
"CC-BY-2.0",
"CC-BY-4.0"
] |
permissive
|
apache/nuttx
|
14519a7bff4a87935d94fb8fb2b19edb501c7cec
|
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
|
refs/heads/master
| 2023-08-25T06:55:45.822534
| 2023-08-23T16:03:31
| 2023-08-24T21:25:47
| 228,103,273
| 407
| 241
|
Apache-2.0
| 2023-09-14T18:26:05
| 2019-12-14T23:27:55
|
C
|
UTF-8
|
C
| false
| false
| 4,302
|
c
|
rv32m1_timerisr.c
|
/****************************************************************************
* arch/risc-v/src/rv32m1/rv32m1_timerisr.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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdint.h>
#include <time.h>
#include <debug.h>
#include <nuttx/arch.h>
#include <nuttx/clock.h>
#include <arch/board/board.h>
#include "riscv_internal.h"
#include "rv32m1.h"
#include "hardware/rv32m1_lptmr.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/****************************************************************************
* Data Definitions
****************************************************************************/
/****************************************************************************
* Private Data
****************************************************************************/
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: rv32m1_timerisr
****************************************************************************/
LOCATE_ITCM
static int rv32m1_timerisr(int irq, void *context, void *arg)
{
/* Write '1' to clear the pending flag */
uint32_t regval = getreg32(RV32M1_LPTMR_CSR);
regval |= LPTMR_CSR_TCF;
putreg32(regval, RV32M1_LPTMR_CSR);
/* Process timer interrupt */
nxsched_process_timer();
return 0;
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: up_timer_initialize
*
* Description:
* This function is called during start-up to initialize
* the timer interrupt.
*
****************************************************************************/
void up_timer_initialize(void)
{
uint32_t regaddr;
uint32_t regval;
/* Stop the timer and clear the pending flag */
regaddr = RV32M1_LPTMR_CSR;
regval = getreg32(regaddr);
regval &= ~LPTMR_CSR_TEN;
putreg32(regval, regaddr);
/* Counter mode,
* Reset counter when the compare value is matched,
* No DMA request
*/
regval &= ~(LPTMR_CSR_TMS | LPTMR_CSR_TFC |
LPTMR_CSR_TDRE | LPTMR_CSR_TPS_MASK);
regval |= LPTMR_CSR_TPS0;
putreg32(regval, regaddr);
regaddr = RV32M1_LPTMR_PSR;
regval = LPTMR_PSR_PCS_SIRCDIV3 | LPTMR_PSR_PBYP;
putreg32(regval, regaddr);
/* Attach timer interrupt handler */
irq_attach(RV32M1_IRQ_LPTMR, rv32m1_timerisr, NULL);
/* Open the timer interrupt gate */
up_enable_irq(RV32M1_IRQ_LPTMR);
/* Set ticks to compare */
regval = rv32m1_clockfreq(CLK_SIRCDIV3) / TICK_PER_SEC;
if (regval > 0)
{
/* Fine tune the ticks */
--regval;
}
putreg32(regval, RV32M1_LPTMR_CMR);
/* Start the timer with interrupt enabled */
regval = getreg32(RV32M1_LPTMR_CSR);
regval &= ~LPTMR_CSR_TCF;
regval |= LPTMR_CSR_TEN | LPTMR_CSR_TIE;
putreg32(regval, RV32M1_LPTMR_CSR);
}
|
164c7ca8fe3dca88177de51cbab626145f0c2f8b
|
cf35a104dabc3d3647df66aff9db32d18b002e1b
|
/lib/libstuff/util/strlcatprint.c
|
ffe139fb71aaf42f0f8cd146656d7cfea0dc8545
|
[
"MIT"
] |
permissive
|
0intro/wmii
|
ba2dff4be1a049c7d4475218a914585a3f810ab5
|
024f29d1058b58aa4ee6b956500a78f69355fb53
|
refs/heads/main
| 2023-07-11T18:08:43.660898
| 2023-06-25T18:57:45
| 2023-06-25T18:57:45
| 74,551,919
| 110
| 17
| null | null | null | null |
UTF-8
|
C
| false
| false
| 381
|
c
|
strlcatprint.c
|
/* Copyright ©2008-2010 Kris Maglione <maglione.k at Gmail>
* See LICENSE file for license details.
*/
#include <string.h>
#include <fmt.h>
#include "util.h"
int
strlcatprint(char *buf, int len, const char *fmt, ...) {
va_list ap;
int buflen;
int ret;
va_start(ap, fmt);
buflen = strlen(buf);
ret = vsnprint(buf+buflen, len-buflen, fmt, ap);
va_end(ap);
return ret;
}
|
50e05ec8273632a7ee79e0caf70b1b0119453715
|
933788c87c06998999dc8bdc1e34d104538995d2
|
/.Legacy Tweaks/HaptikCenter/hcprefs/HaptikPreferencesDefinitions.h
|
b53315b581abf46eee7ba9db3f4cea612459102e
|
[
"LicenseRef-scancode-free-unknown",
"MIT"
] |
permissive
|
LacertosusRepo/Open-Source-Tweaks
|
aca7c1d004e33257a1b6d136d41e70a694852be8
|
ccb00ba369cc8ee86b8a20fc5cae07ba69a1593b
|
refs/heads/master
| 2022-05-27T09:29:51.987726
| 2022-05-21T14:48:36
| 2022-05-21T14:48:36
| 49,115,831
| 280
| 93
|
MIT
| 2020-08-14T16:45:22
| 2016-01-06T05:55:35
|
Objective-C
|
UTF-8
|
C
| false
| false
| 362
|
h
|
HaptikPreferencesDefinitions.h
|
#define Main_Color [UIColor colorWithRed:189/255.0f green:195/255.0f blue:199/255.0f alpha:1.0f] //[UIColor colorWithRed:52/255.0f green:73/255.0f blue:95/255.0f alpha:1.0f]
#define Switch_Color [UIColor colorWithRed:52/255.0f green:73/255.0f blue:95/255.0f alpha:1.0f]
#define Nav_Color [UIColor colorWithRed:32/255.0f green:55/255.0f blue:77/255.0f alpha:1.0f]
|
ea1c22f0771e588fb1690abd843a65b88f6f10ae
|
a6f47c6b702055aa2cc1a9ee051017320a8c602b
|
/thirdparty/libvpx/rtcd/vp8_rtcd_arm.h
|
5c9b7aa392a508f8703bcc7fca200c3cbea64bbb
|
[
"FTL",
"Zlib",
"MIT",
"BSD-3-Clause",
"Bitstream-Vera",
"CC0-1.0",
"MPL-2.0",
"OFL-1.1",
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-free-unknown",
"Libpng"
] |
permissive
|
Stary2001/godot
|
849ca3045a687d9b34de7cc24a8b6d26f89f95bc
|
00c6ce9716ed542997bc2b59136bceb3729db970
|
refs/heads/3.5.2-stable_switch
| 2023-05-25T08:38:55.387308
| 2023-04-14T23:07:10
| 2023-04-23T20:32:29
| 148,190,960
| 306
| 38
|
MIT
| 2023-05-19T20:10:22
| 2018-09-10T17:11:15
|
C++
|
UTF-8
|
C
| false
| false
| 12,910
|
h
|
vp8_rtcd_arm.h
|
#ifndef VP8_RTCD_H_
#define VP8_RTCD_H_
#ifdef RTCD_C
#define RTCD_EXTERN
#else
#define RTCD_EXTERN extern
#endif
/*
* VP8
*/
struct blockd;
struct loop_filter_info;
#ifdef __cplusplus
extern "C" {
#endif
void vp8_bilinear_predict16x16_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
void vp8_bilinear_predict16x16_neon(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
RTCD_EXTERN void (*vp8_bilinear_predict16x16)(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
void vp8_bilinear_predict4x4_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
#define vp8_bilinear_predict4x4 vp8_bilinear_predict4x4_c
void vp8_bilinear_predict8x4_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
void vp8_bilinear_predict8x4_neon(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
RTCD_EXTERN void (*vp8_bilinear_predict8x4)(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
void vp8_bilinear_predict8x8_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
void vp8_bilinear_predict8x8_neon(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
RTCD_EXTERN void (*vp8_bilinear_predict8x8)(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
void vp8_clear_system_state_c();
#define vp8_clear_system_state vp8_clear_system_state_c
void vp8_copy_mem16x16_c(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch);
void vp8_copy_mem16x16_neon(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch);
RTCD_EXTERN void (*vp8_copy_mem16x16)(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch);
void vp8_copy_mem8x4_c(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch);
void vp8_copy_mem8x4_neon(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch);
RTCD_EXTERN void (*vp8_copy_mem8x4)(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch);
void vp8_copy_mem8x8_c(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch);
void vp8_copy_mem8x8_neon(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch);
RTCD_EXTERN void (*vp8_copy_mem8x8)(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch);
void vp8_dc_only_idct_add_c(short input, unsigned char *pred, int pred_stride, unsigned char *dst, int dst_stride);
void vp8_dc_only_idct_add_neon(short input, unsigned char *pred, int pred_stride, unsigned char *dst, int dst_stride);
RTCD_EXTERN void (*vp8_dc_only_idct_add)(short input, unsigned char *pred, int pred_stride, unsigned char *dst, int dst_stride);
void vp8_dequant_idct_add_c(short *input, short *dq, unsigned char *output, int stride);
void vp8_dequant_idct_add_neon(short *input, short *dq, unsigned char *output, int stride);
RTCD_EXTERN void (*vp8_dequant_idct_add)(short *input, short *dq, unsigned char *output, int stride);
void vp8_dequant_idct_add_uv_block_c(short *q, short *dq, unsigned char *dst_u, unsigned char *dst_v, int stride, char *eobs);
void vp8_dequant_idct_add_uv_block_neon(short *q, short *dq, unsigned char *dst_u, unsigned char *dst_v, int stride, char *eobs);
RTCD_EXTERN void (*vp8_dequant_idct_add_uv_block)(short *q, short *dq, unsigned char *dst_u, unsigned char *dst_v, int stride, char *eobs);
void vp8_dequant_idct_add_y_block_c(short *q, short *dq, unsigned char *dst, int stride, char *eobs);
void vp8_dequant_idct_add_y_block_neon(short *q, short *dq, unsigned char *dst, int stride, char *eobs);
RTCD_EXTERN void (*vp8_dequant_idct_add_y_block)(short *q, short *dq, unsigned char *dst, int stride, char *eobs);
void vp8_dequantize_b_c(struct blockd*, short *dqc);
void vp8_dequantize_b_neon(struct blockd*, short *dqc);
RTCD_EXTERN void (*vp8_dequantize_b)(struct blockd*, short *dqc);
void vp8_loop_filter_bh_c(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi);
void vp8_loop_filter_bh_neon(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi);
RTCD_EXTERN void (*vp8_loop_filter_bh)(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi);
void vp8_loop_filter_bv_c(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi);
void vp8_loop_filter_bv_neon(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi);
RTCD_EXTERN void (*vp8_loop_filter_bv)(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi);
void vp8_loop_filter_mbh_c(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi);
void vp8_loop_filter_mbh_neon(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi);
RTCD_EXTERN void (*vp8_loop_filter_mbh)(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi);
void vp8_loop_filter_mbv_c(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi);
void vp8_loop_filter_mbv_neon(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi);
RTCD_EXTERN void (*vp8_loop_filter_mbv)(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi);
void vp8_loop_filter_bhs_c(unsigned char *y, int ystride, const unsigned char *blimit);
void vp8_loop_filter_bhs_neon(unsigned char *y, int ystride, const unsigned char *blimit);
RTCD_EXTERN void (*vp8_loop_filter_simple_bh)(unsigned char *y, int ystride, const unsigned char *blimit);
void vp8_loop_filter_bvs_c(unsigned char *y, int ystride, const unsigned char *blimit);
void vp8_loop_filter_bvs_neon(unsigned char *y, int ystride, const unsigned char *blimit);
RTCD_EXTERN void (*vp8_loop_filter_simple_bv)(unsigned char *y, int ystride, const unsigned char *blimit);
void vp8_loop_filter_simple_horizontal_edge_c(unsigned char *y, int ystride, const unsigned char *blimit);
void vp8_loop_filter_mbhs_neon(unsigned char *y, int ystride, const unsigned char *blimit);
RTCD_EXTERN void (*vp8_loop_filter_simple_mbh)(unsigned char *y, int ystride, const unsigned char *blimit);
void vp8_loop_filter_simple_vertical_edge_c(unsigned char *y, int ystride, const unsigned char *blimit);
void vp8_loop_filter_mbvs_neon(unsigned char *y, int ystride, const unsigned char *blimit);
RTCD_EXTERN void (*vp8_loop_filter_simple_mbv)(unsigned char *y, int ystride, const unsigned char *blimit);
void vp8_short_idct4x4llm_c(short *input, unsigned char *pred, int pitch, unsigned char *dst, int dst_stride);
void vp8_short_idct4x4llm_neon(short *input, unsigned char *pred, int pitch, unsigned char *dst, int dst_stride);
RTCD_EXTERN void (*vp8_short_idct4x4llm)(short *input, unsigned char *pred, int pitch, unsigned char *dst, int dst_stride);
void vp8_short_inv_walsh4x4_c(short *input, short *output);
void vp8_short_inv_walsh4x4_neon(short *input, short *output);
RTCD_EXTERN void (*vp8_short_inv_walsh4x4)(short *input, short *output);
void vp8_short_inv_walsh4x4_1_c(short *input, short *output);
#define vp8_short_inv_walsh4x4_1 vp8_short_inv_walsh4x4_1_c
void vp8_sixtap_predict16x16_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
void vp8_sixtap_predict16x16_neon(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
RTCD_EXTERN void (*vp8_sixtap_predict16x16)(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
void vp8_sixtap_predict4x4_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
#define vp8_sixtap_predict4x4 vp8_sixtap_predict4x4_c
void vp8_sixtap_predict8x4_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
void vp8_sixtap_predict8x4_neon(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
RTCD_EXTERN void (*vp8_sixtap_predict8x4)(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
void vp8_sixtap_predict8x8_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
void vp8_sixtap_predict8x8_neon(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
RTCD_EXTERN void (*vp8_sixtap_predict8x8)(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch);
void vp8_rtcd(void);
#ifdef RTCD_C
#include "vpx_ports/arm.h"
static void setup_rtcd_internal(void)
{
int flags = arm_cpu_caps();
vp8_bilinear_predict16x16 = vp8_bilinear_predict16x16_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_bilinear_predict16x16 = vp8_bilinear_predict16x16_neon;
#endif
vp8_bilinear_predict8x4 = vp8_bilinear_predict8x4_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_bilinear_predict8x4 = vp8_bilinear_predict8x4_neon;
#endif
vp8_bilinear_predict8x8 = vp8_bilinear_predict8x8_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_bilinear_predict8x8 = vp8_bilinear_predict8x8_neon;
#endif
vp8_copy_mem16x16 = vp8_copy_mem16x16_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_copy_mem16x16 = vp8_copy_mem16x16_neon;
#endif
vp8_copy_mem8x4 = vp8_copy_mem8x4_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_copy_mem8x4 = vp8_copy_mem8x4_neon;
#endif
vp8_copy_mem8x8 = vp8_copy_mem8x8_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_copy_mem8x8 = vp8_copy_mem8x8_neon;
#endif
vp8_dc_only_idct_add = vp8_dc_only_idct_add_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_dc_only_idct_add = vp8_dc_only_idct_add_neon;
#endif
vp8_dequant_idct_add = vp8_dequant_idct_add_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_dequant_idct_add = vp8_dequant_idct_add_neon;
#endif
vp8_dequant_idct_add_uv_block = vp8_dequant_idct_add_uv_block_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_dequant_idct_add_uv_block = vp8_dequant_idct_add_uv_block_neon;
#endif
vp8_dequant_idct_add_y_block = vp8_dequant_idct_add_y_block_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_dequant_idct_add_y_block = vp8_dequant_idct_add_y_block_neon;
#endif
vp8_dequantize_b = vp8_dequantize_b_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_dequantize_b = vp8_dequantize_b_neon;
#endif
vp8_loop_filter_bh = vp8_loop_filter_bh_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_loop_filter_bh = vp8_loop_filter_bh_neon;
#endif
vp8_loop_filter_bv = vp8_loop_filter_bv_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_loop_filter_bv = vp8_loop_filter_bv_neon;
#endif
vp8_loop_filter_mbh = vp8_loop_filter_mbh_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_loop_filter_mbh = vp8_loop_filter_mbh_neon;
#endif
vp8_loop_filter_mbv = vp8_loop_filter_mbv_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_loop_filter_mbv = vp8_loop_filter_mbv_neon;
#endif
vp8_loop_filter_simple_bh = vp8_loop_filter_bhs_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_loop_filter_simple_bh = vp8_loop_filter_bhs_neon;
#endif
vp8_loop_filter_simple_bv = vp8_loop_filter_bvs_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_loop_filter_simple_bv = vp8_loop_filter_bvs_neon;
#endif
vp8_loop_filter_simple_mbh = vp8_loop_filter_simple_horizontal_edge_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_loop_filter_simple_mbh = vp8_loop_filter_mbhs_neon;
#endif
vp8_loop_filter_simple_mbv = vp8_loop_filter_simple_vertical_edge_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_loop_filter_simple_mbv = vp8_loop_filter_mbvs_neon;
#endif
vp8_short_idct4x4llm = vp8_short_idct4x4llm_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_short_idct4x4llm = vp8_short_idct4x4llm_neon;
#endif
vp8_short_inv_walsh4x4 = vp8_short_inv_walsh4x4_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_short_inv_walsh4x4 = vp8_short_inv_walsh4x4_neon;
#endif
vp8_sixtap_predict16x16 = vp8_sixtap_predict16x16_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_sixtap_predict16x16 = vp8_sixtap_predict16x16_neon;
#endif
vp8_sixtap_predict8x4 = vp8_sixtap_predict8x4_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_sixtap_predict8x4 = vp8_sixtap_predict8x4_neon;
#endif
vp8_sixtap_predict8x8 = vp8_sixtap_predict8x8_c;
#if HAVE_NEON
if (flags & HAS_NEON) vp8_sixtap_predict8x8 = vp8_sixtap_predict8x8_neon;
#endif
}
#endif
#ifdef __cplusplus
} // extern "C"
#endif
#endif
|
1e5b5e112ef91a1e6ffc8c0411604a1ef4d37a04
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/u-boot_new/lib/openssl/asn1/asn1_get_field_ptr.c
|
2068a3390b48fff1c1a075741b6e0078d82b9000
|
[
"GPL-2.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
|
GB18030
|
C
| false
| false
| 2,567
|
c
|
asn1_get_field_ptr.c
|
#include"asn1.h"
#include"asn1t.h"
#include"objects.h"
#include"err.h"
#define offset2ptr(addr, offset) (void *)(((char *) addr) + offset)
////////////////asn1_get_field_ptr///////////////////////////////////ok由tt中的offset计算要读取数据在"接收结构体"里面的偏移
ASN1_VALUE ** asn1_get_field_ptr(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt)
{
ASN1_VALUE **pvaltmp;
if (tt->flags & ASN1_TFLG_COMBINE)
return pval;
pvaltmp = offset2ptr(*pval, tt->offset);
return pvaltmp;
}
////////////////asn1_get_enc_ptr/////////////////////////ok
static ASN1_ENCODING *asn1_get_enc_ptr(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
const ASN1_AUX *aux;
if (!pval || !*pval)
return NULL;
aux = it->funcs;
if (!aux || !(aux->flags & ASN1_AFLG_ENCODING))
return NULL;
return offset2ptr(*pval, aux->enc_offset);
}
////////////////asn1_enc_save//////////////////////////////ok
int asn1_enc_save(ASN1_VALUE **pval, const unsigned char *in, int inlen,
const ASN1_ITEM *it)
{
ASN1_ENCODING *enc;
enc = asn1_get_enc_ptr(pval, it);
if (!enc)
return 1;
if (enc->enc)
OPENSSL_free(enc->enc);
enc->enc = OPENSSL_malloc(inlen);
if (!enc->enc)
return 0;
memcpy(enc->enc, in, inlen);
enc->len = inlen;
enc->modified = 0;
return 1;
}
////////////////asn1_do_adb//////////////////////////////////////ok
const ASN1_TEMPLATE *asn1_do_adb(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt,int nullerr)
{
const ASN1_ADB *adb;
const ASN1_ADB_TABLE *atbl;
long selector = 0;
ASN1_VALUE **sfld;
int i;
if (!(tt->flags & ASN1_TFLG_ADB_MASK))
return tt;//??
adb = ASN1_ADB_ptr(tt->item);
sfld = offset2ptr(*pval, adb->offset);
if (!sfld)
{
if (!adb->null_tt)
goto err;
return adb->null_tt;
}
if (tt->flags & ASN1_TFLG_ADB_OID)
selector = OBJ_obj2nid((ASN1_OBJECT *)*sfld);
else
//selector = ASN1_INTEGER_get((ASN1_INTEGER *)*sfld);
;
for (atbl = adb->tbl, i = 0; i < adb->tblcount; i++, atbl++)
if (atbl->value == selector)
return &atbl->tt;
if (!adb->default_tt)
goto err;
return adb->default_tt;
err:
if (nullerr)
ASN1err(ASN1_F_ASN1_DO_ADB,
ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE);
return NULL;
}
///////////////asn1_enc_init////////////////////////////////////ok
void asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
ASN1_ENCODING *enc;
enc = asn1_get_enc_ptr(pval, it);
if (enc)
{
enc->enc = NULL;
enc->len = 0;
enc->modified = 1;
}
}
|
3675d53131e4f01bf7cf5df1eabc22900e70089f
|
4e32ea5b4a215f427af04630e01b1312ffd31a55
|
/test/programs/smg_Explicity_Test/heap-memory/skiplist_2lvl.c
|
0bd2dfca708160b3ec3be03e3714d116bd1c0466
|
[
"Apache-2.0",
"GPL-1.0-or-later"
] |
permissive
|
sosy-lab/cpachecker
|
1add74cb774316dd6e1aea3fb1f352c8141466b7
|
1822761867d106301bda0bc99ed3cc0a25c529aa
|
refs/heads/trunk
| 2023-08-31T14:47:22.284597
| 2023-08-31T14:20:58
| 2023-08-31T14:20:58
| 20,107,238
| 186
| 90
|
Apache-2.0
| 2021-07-27T14:24:30
| 2014-05-23T16:57:37
|
SWIG
|
UTF-8
|
C
| false
| false
| 2,577
|
c
|
skiplist_2lvl.c
|
// SPDX-FileCopyrightText: The Predator authors
//
// SPDX-License-Identifier: GPL-3.0-only
extern void __VERIFIER_error() __attribute__ ((__noreturn__));
/*
* A slightly obfuscated implementation of skip lists without using ordering and height counters.
* For a better implementation, see, e.g., http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_skip.aspx
* or http://ck.kolivas.org/patches/bfs/test/bfs406-skiplists.patch
*
* We assume the height to be fixed to 2 and we always have the maximum height at the head and tail
* nodes---in other words, we do not let the height grow/shrink. Also, we do not consider a dynamic
* number of next pointers in the nodes.
*
* This source code is licensed under the GPLv3 license.
*
* Taken from Forester.
*/
#include <stdlib.h>
// a skip list node with three next pointers
struct sl_item {
struct sl_item *n1, *n2;
};
// a skip list
struct sl {
struct sl_item *head, *tail;
};
struct sl_item* alloc_or_die(void)
{
struct sl_item *pi = malloc(sizeof(struct sl_item));
return pi;
}
struct sl* create_sl_with_head_and_tail(void)
{
struct sl *sl = malloc(sizeof(*sl));
sl->head = malloc(sizeof(struct sl_item));
sl->tail = malloc(sizeof(struct sl_item));
sl->head->n2 = sl->head->n1 = sl->tail;
sl->tail->n2 = sl->tail->n1 = NULL;
return sl;
}
// The function inserts one node of a random height to a randomly chosen position in between of
// the head and tail.
void sl_random_insert(struct sl *sl)
{
// a1, a2 remember the nodes before the inserted one at the particular levels
struct sl_item *a1, *a2;
struct sl_item *new;
a2 = sl->head;
int a = 0;
while (a2->n2 != sl->tail && __VERIFIER_nondet_int() && a < 2) {
a++;
a2 = a2->n2;
}
// moving randomly on the 1st level, not going behind a2->n2
a1 = a2;
a = 0;
while (a1->n1 != a2->n2 && __VERIFIER_nondet_int() && a < 2) {
a++;
a1 = a1->n1;
}
// allocation and insertion of a new node
new = malloc(sizeof(struct sl_item));
// always insert at level 1
new->n1 = a1->n1;
a1->n1 = new;
// choose whether to insert at level 2
if (__VERIFIER_nondet_int()) {
new->n2 = a2->n2;
a2->n2 = new;
}
}
void destroy_sl(struct sl *sl)
{
struct sl_item *tmp;
while (sl->head) {
tmp = sl->head;
sl->head = sl->head->n1;
free(tmp);
}
free(sl);
}
int main()
{
struct sl *sl = create_sl_with_head_and_tail();
int c = 0;
while (c < 2 && __VERIFIER_nondet_int()) {
c++;
sl_random_insert(sl);
}
destroy_sl(sl);
return 0;
}
|
6aa8420cb23f3c635cc2c20a385a3e4c106e56bf
|
98ee5bc94e754d9b1802d66d7b5c5fcf184a6c90
|
/test/kat-app/xcbc_test.c
|
dbf866b55fbdac5c161cba07efaeeb21f7116f94
|
[
"BSD-3-Clause"
] |
permissive
|
intel/intel-ipsec-mb
|
f180701ca3dbdc26f310c5706cb3e8577defa2df
|
9e17d6cad1f99e64f3534053a3ff096c46646058
|
refs/heads/main
| 2023-08-30T13:20:47.709185
| 2023-08-28T13:17:46
| 2023-08-29T13:14:00
| 73,856,328
| 255
| 89
|
BSD-3-Clause
| 2023-08-30T08:42:45
| 2016-11-15T21:22:17
|
C
|
UTF-8
|
C
| false
| false
| 9,884
|
c
|
xcbc_test.c
|
/*****************************************************************************
Copyright (c) 2020-2023, Intel Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <intel-ipsec-mb.h>
#include "gcm_ctr_vectors_test.h"
#include "utils.h"
#include "mac_test.h"
int xcbc_test(struct IMB_MGR *mb_mgr);
extern const struct mac_test xcbc_test_json[];
static int
xcbc_job_ok(const struct mac_test *vec,
const struct IMB_JOB *job,
const uint8_t *auth,
const uint8_t *padding,
const size_t sizeof_padding)
{
const size_t auth_len = job->auth_tag_output_len_in_bytes;
if (job->status != IMB_STATUS_COMPLETED) {
printf("%d Error status:%d", __LINE__, job->status);
return 0;
}
/* hash checks */
if (memcmp(padding, &auth[sizeof_padding + auth_len],
sizeof_padding)) {
printf("hash overwrite tail\n");
hexdump(stderr, "Target",
&auth[sizeof_padding + auth_len], sizeof_padding);
return 0;
}
if (memcmp(padding, &auth[0], sizeof_padding)) {
printf("hash overwrite head\n");
hexdump(stderr, "Target", &auth[0], sizeof_padding);
return 0;
}
if (memcmp((const void *) vec->tag, &auth[sizeof_padding], auth_len)) {
printf("hash mismatched\n");
hexdump(stderr, "Received", &auth[sizeof_padding],
auth_len);
hexdump(stderr, "Expected", (const void *) vec->tag,
auth_len);
return 0;
}
return 1;
}
static int
test_xcbc(struct IMB_MGR *mb_mgr,
const struct mac_test *vec,
const int dir,
const int num_jobs)
{
DECLARE_ALIGNED(uint32_t k1_exp[4*11], 16);
uint8_t k2[16], k3[16];
struct IMB_JOB *job;
uint8_t padding[16];
uint8_t **auths = malloc(num_jobs * sizeof(void *));
int i = 0, jobs_rx = 0, ret = -1;
if (auths == NULL) {
fprintf(stderr, "Can't allocate buffer memory\n");
goto end2;
}
memset(padding, -1, sizeof(padding));
memset(auths, 0, num_jobs * sizeof(void *));
for (i = 0; i < num_jobs; i++) {
auths[i] = malloc(16 + (sizeof(padding) * 2));
if (auths[i] == NULL) {
fprintf(stderr, "Can't allocate buffer memory\n");
goto end;
}
memset(auths[i], -1, 16 + (sizeof(padding) * 2));
}
IMB_AES_XCBC_KEYEXP(mb_mgr, (const void *) vec->key, k1_exp, k2, k3);
while (IMB_FLUSH_JOB(mb_mgr) != NULL)
;
/**
* Submit all jobs then flush any outstanding jobs
*/
for (i = 0; i < num_jobs; i++) {
job = IMB_GET_NEXT_JOB(mb_mgr);
job->cipher_direction = dir;
job->chain_order = IMB_ORDER_HASH_CIPHER;
job->cipher_mode = IMB_CIPHER_NULL;
job->hash_alg = IMB_AUTH_AES_XCBC;
job->msg_len_to_hash_in_bytes = vec->msgSize / 8;
job->u.XCBC._k1_expanded = k1_exp;
job->u.XCBC._k2 = k2;
job->u.XCBC._k3 = k3;
job->src = (const void *) vec->msg;
job->hash_start_src_offset_in_bytes = 0;
job->auth_tag_output = auths[i] + sizeof(padding);
job->auth_tag_output_len_in_bytes = vec->tagSize / 8;
job->user_data = auths[i];
job = IMB_SUBMIT_JOB(mb_mgr);
if (job) {
jobs_rx++;
if (num_jobs < 4) {
printf("%d Unexpected return from submit_job\n",
__LINE__);
goto end;
}
if (!xcbc_job_ok(vec, job, job->user_data, padding,
sizeof(padding)))
goto end;
}
}
while ((job = IMB_FLUSH_JOB(mb_mgr)) != NULL) {
jobs_rx++;
if (!xcbc_job_ok(vec, job, job->user_data, padding,
sizeof(padding)))
goto end;
}
if (jobs_rx != num_jobs) {
printf("Expected %d jobs, received %d\n", num_jobs, jobs_rx);
goto end;
}
/**
* Submit each job and flush immediately
*/
for (i = 0; i < num_jobs; i++) {
struct IMB_JOB *first_job = NULL;
job = IMB_GET_NEXT_JOB(mb_mgr);
first_job = job;
job->cipher_direction = dir;
job->chain_order = IMB_ORDER_HASH_CIPHER;
job->cipher_mode = IMB_CIPHER_NULL;
job->hash_alg = IMB_AUTH_AES_XCBC;
job->msg_len_to_hash_in_bytes = vec->msgSize / 8;
job->u.XCBC._k1_expanded = k1_exp;
job->u.XCBC._k2 = k2;
job->u.XCBC._k3 = k3;
job->src = (const void *) vec->msg;
job->hash_start_src_offset_in_bytes = 0;
job->auth_tag_output = auths[i] + sizeof(padding);
job->auth_tag_output_len_in_bytes = vec->tagSize / 8;
job->user_data = auths[i];
job = IMB_SUBMIT_JOB(mb_mgr);
if (job != NULL) {
printf("Received job, expected NULL\n");
goto end;
}
while ((job = IMB_FLUSH_JOB(mb_mgr)) != NULL) {
if (job != first_job) {
printf("Invalid return job received\n");
goto end;
}
if (!xcbc_job_ok(vec, job, job->user_data, padding,
sizeof(padding)))
goto end;
}
}
ret = 0;
end:
while (IMB_FLUSH_JOB(mb_mgr) != NULL)
;
for (i = 0; i < num_jobs; i++) {
if (auths[i] != NULL)
free(auths[i]);
}
end2:
if (auths != NULL)
free(auths);
return ret;
}
static void
test_xcbc_std_vectors(struct IMB_MGR *mb_mgr,
struct test_suite_context *ctx,
const int num_jobs)
{
const struct mac_test *v = xcbc_test_json;
if (!quiet_mode)
printf("AES-XCBC-128 standard test vectors (N jobs = %d):\n", num_jobs);
for (; v->msg != NULL; v++) {
if (!quiet_mode) {
#ifdef DEBUG
printf("Standard XCBC-128 vector %zu Msg len: %zu, "
"Tag len:%zu\n",
v->tcId,
v->msgSize / 8,
v->tagSize / 8);
#else
printf(".");
#endif
}
if (test_xcbc(mb_mgr, v,
IMB_DIR_ENCRYPT, num_jobs)) {
printf("error #%zu encrypt\n", v->tcId);
test_suite_update(ctx, 0, 1);
} else {
test_suite_update(ctx, 1, 0);
}
if (test_xcbc(mb_mgr, v,
IMB_DIR_DECRYPT, num_jobs)) {
printf("error #%zu decrypt\n", v->tcId);
test_suite_update(ctx, 0, 1);
} else {
test_suite_update(ctx, 1, 0);
}
}
if (!quiet_mode)
printf("\n");
}
int
xcbc_test(struct IMB_MGR *mb_mgr)
{
struct test_suite_context ctx;
int i, errors;
test_suite_start(&ctx, "AES-XCBC-128");
/* AES-XCBC 128 with standard vectors */
for (i = 1; i < 20; i++)
test_xcbc_std_vectors(mb_mgr, &ctx, i);
errors = test_suite_end(&ctx);
return errors;
}
|
1454786a5ce88a04ecb0f7470e505743dbed5a32
|
ab22a09178ed636cdeb86b5ef9e5d9e2ee81d974
|
/ext/rbs_extension/lexer.c
|
af6c3a254b0f40be5873f27fcb53b26ea76a0a12
|
[
"BSD-2-Clause",
"Ruby"
] |
permissive
|
ruby/rbs
|
4eff69105f82dcf26d6f808c136bfe6ff159aba4
|
c5acacffd795826aad1196e157bf71f3834cb553
|
refs/heads/master
| 2023-09-04T09:54:33.201183
| 2023-09-04T05:44:52
| 2023-09-04T05:44:52
| 174,796,313
| 1,548
| 179
|
NOASSERTION
| 2023-09-12T06:19:10
| 2019-03-10T08:22:27
|
Ruby
|
UTF-8
|
C
| false
| false
| 52,275
|
c
|
lexer.c
|
/* Generated by re2c 3.0 */
#line 1 "ext/rbs_extension/lexer.re"
#include "rbs_extension.h"
token rbsparser_next_token(lexstate *state) {
lexstate backup;
start:
backup = *state;
#line 13 "ext/rbs_extension/lexer.c"
{
unsigned int yych;
unsigned int yyaccept = 0;
yych = peek(state);
switch (yych) {
case 0x00000000: goto yy1;
case '\t':
case '\n':
case '\r':
case ' ': goto yy4;
case '!': goto yy6;
case '"': goto yy8;
case '#': goto yy9;
case '$': goto yy11;
case '%': goto yy12;
case '&': goto yy13;
case '\'': goto yy14;
case '(': goto yy15;
case ')': goto yy16;
case '*': goto yy17;
case '+': goto yy18;
case ',': goto yy19;
case '-': goto yy20;
case '.': goto yy21;
case '/':
case '~': goto yy23;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': goto yy24;
case ':': goto yy26;
case '<': goto yy28;
case '=': goto yy30;
case '>': goto yy32;
case '?': goto yy33;
case '@': goto yy34;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z': goto yy35;
case '[': goto yy37;
case ']': goto yy38;
case '^': goto yy39;
case '_': goto yy40;
case '`': goto yy42;
case 'a': goto yy44;
case 'b': goto yy46;
case 'c': goto yy47;
case 'd': goto yy48;
case 'e': goto yy49;
case 'f': goto yy50;
case 'g':
case 'h':
case 'j':
case 'k':
case 'l':
case 'q':
case 'r':
case 'w':
case 'x':
case 'y':
case 'z': goto yy51;
case 'i': goto yy53;
case 'm': goto yy54;
case 'n': goto yy55;
case 'o': goto yy56;
case 'p': goto yy57;
case 's': goto yy58;
case 't': goto yy59;
case 'u': goto yy60;
case 'v': goto yy61;
case '{': goto yy62;
case '|': goto yy63;
case '}': goto yy64;
default: goto yy2;
}
yy1:
rbs_skip(state);
#line 140 "ext/rbs_extension/lexer.re"
{ return next_token(state, pEOF); }
#line 122 "ext/rbs_extension/lexer.c"
yy2:
rbs_skip(state);
yy3:
#line 141 "ext/rbs_extension/lexer.re"
{ return next_token(state, ErrorToken); }
#line 128 "ext/rbs_extension/lexer.c"
yy4:
rbs_skip(state);
yych = peek(state);
if (yych <= '\f') {
if (yych <= 0x00000008) goto yy5;
if (yych <= '\n') goto yy4;
} else {
if (yych <= '\r') goto yy4;
if (yych == ' ') goto yy4;
}
yy5:
#line 139 "ext/rbs_extension/lexer.re"
{ state->start = state->current; goto start; }
#line 142 "ext/rbs_extension/lexer.c"
yy6:
rbs_skip(state);
yych = peek(state);
if (yych == '=') goto yy23;
if (yych == '~') goto yy23;
yy7:
#line 49 "ext/rbs_extension/lexer.re"
{ return next_token(state, tOPERATOR); }
#line 151 "ext/rbs_extension/lexer.c"
yy8:
yyaccept = 0;
rbs_skip(state);
backup = *state;
yych = peek(state);
if (yych <= 0x00000000) goto yy3;
goto yy66;
yy9:
rbs_skip(state);
yych = peek(state);
if (yych <= 0x00000000) goto yy10;
if (yych != '\n') goto yy9;
yy10:
#line 60 "ext/rbs_extension/lexer.re"
{
return next_token(
state,
state->first_token_of_line ? tLINECOMMENT : tCOMMENT
);
}
#line 172 "ext/rbs_extension/lexer.c"
yy11:
rbs_skip(state);
yych = peek(state);
if (yych <= ')') {
if (yych <= 0x0000001F) {
if (yych <= '\n') {
if (yych <= 0x00000000) goto yy3;
if (yych <= 0x00000008) goto yy70;
goto yy3;
} else {
if (yych == '\r') goto yy3;
goto yy70;
}
} else {
if (yych <= '#') {
if (yych <= ' ') goto yy3;
if (yych <= '"') goto yy72;
goto yy70;
} else {
if (yych == '%') goto yy3;
if (yych <= '\'') goto yy72;
goto yy3;
}
}
} else {
if (yych <= 'Z') {
if (yych <= '/') {
if (yych == '-') goto yy70;
goto yy72;
} else {
if (yych <= '9') goto yy70;
if (yych <= '>') goto yy72;
goto yy70;
}
} else {
if (yych <= '^') {
if (yych == '\\') goto yy72;
goto yy3;
} else {
if (yych <= 'z') goto yy70;
if (yych <= '}') goto yy3;
if (yych <= '~') goto yy72;
goto yy70;
}
}
}
yy12:
yyaccept = 1;
rbs_skip(state);
backup = *state;
yych = peek(state);
if (yych == 'a') goto yy73;
goto yy7;
yy13:
rbs_skip(state);
#line 34 "ext/rbs_extension/lexer.re"
{ return next_token(state, pAMP); }
#line 230 "ext/rbs_extension/lexer.c"
yy14:
yyaccept = 0;
rbs_skip(state);
backup = *state;
yych = peek(state);
if (yych <= 0x00000000) goto yy3;
goto yy75;
yy15:
rbs_skip(state);
#line 25 "ext/rbs_extension/lexer.re"
{ return next_token(state, pLPAREN); }
#line 242 "ext/rbs_extension/lexer.c"
yy16:
rbs_skip(state);
#line 26 "ext/rbs_extension/lexer.re"
{ return next_token(state, pRPAREN); }
#line 247 "ext/rbs_extension/lexer.c"
yy17:
rbs_skip(state);
yych = peek(state);
if (yych == '*') goto yy79;
#line 36 "ext/rbs_extension/lexer.re"
{ return next_token(state, pSTAR); }
#line 254 "ext/rbs_extension/lexer.c"
yy18:
rbs_skip(state);
yych = peek(state);
if (yych <= '/') goto yy7;
if (yych <= '9') goto yy24;
if (yych == '@') goto yy23;
goto yy7;
yy19:
rbs_skip(state);
#line 31 "ext/rbs_extension/lexer.re"
{ return next_token(state, pCOMMA); }
#line 266 "ext/rbs_extension/lexer.c"
yy20:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') goto yy7;
if (yych <= '9') goto yy24;
goto yy7;
} else {
if (yych <= '>') goto yy80;
if (yych == '@') goto yy23;
goto yy7;
}
yy21:
yyaccept = 2;
rbs_skip(state);
backup = *state;
yych = peek(state);
if (yych == '.') goto yy81;
yy22:
#line 38 "ext/rbs_extension/lexer.re"
{ return next_token(state, pDOT); }
#line 288 "ext/rbs_extension/lexer.c"
yy23:
rbs_skip(state);
goto yy7;
yy24:
rbs_skip(state);
yych = peek(state);
if (yych <= '/') goto yy25;
if (yych <= '9') goto yy24;
if (yych == '_') goto yy24;
yy25:
#line 52 "ext/rbs_extension/lexer.re"
{ return next_token(state, tINTEGER); }
#line 301 "ext/rbs_extension/lexer.c"
yy26:
yyaccept = 3;
rbs_skip(state);
backup = *state;
yych = peek(state);
switch (yych) {
case '!': goto yy82;
case '"': goto yy84;
case '$': goto yy85;
case '%':
case '&':
case '/':
case '^':
case '`':
case '|':
case '~': goto yy86;
case '\'': goto yy87;
case '*': goto yy88;
case '+':
case '-': goto yy89;
case ':': goto yy90;
case '<': goto yy91;
case '=': goto yy92;
case '>': goto yy93;
case '@': goto yy94;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z': goto yy95;
case '[': goto yy97;
default: goto yy27;
}
yy27:
#line 45 "ext/rbs_extension/lexer.re"
{ return next_token(state, pCOLON); }
#line 386 "ext/rbs_extension/lexer.c"
yy28:
rbs_skip(state);
yych = peek(state);
if (yych <= ';') goto yy29;
if (yych <= '<') goto yy23;
if (yych <= '=') goto yy98;
yy29:
#line 47 "ext/rbs_extension/lexer.re"
{ return next_token(state, pLT); }
#line 396 "ext/rbs_extension/lexer.c"
yy30:
rbs_skip(state);
yych = peek(state);
if (yych <= '>') {
if (yych <= '<') goto yy31;
if (yych <= '=') goto yy99;
goto yy100;
} else {
if (yych == '~') goto yy23;
}
yy31:
#line 44 "ext/rbs_extension/lexer.re"
{ return next_token(state, pEQ); }
#line 410 "ext/rbs_extension/lexer.c"
yy32:
rbs_skip(state);
yych = peek(state);
if (yych <= '<') goto yy7;
if (yych <= '>') goto yy23;
goto yy7;
yy33:
rbs_skip(state);
#line 35 "ext/rbs_extension/lexer.re"
{ return next_token(state, pQUESTION); }
#line 421 "ext/rbs_extension/lexer.c"
yy34:
yyaccept = 0;
rbs_skip(state);
backup = *state;
yych = peek(state);
if (yych <= '^') {
if (yych <= '?') goto yy3;
if (yych <= '@') goto yy101;
if (yych <= 'Z') goto yy102;
goto yy3;
} else {
if (yych == '`') goto yy3;
if (yych <= 'z') goto yy102;
goto yy3;
}
yy35:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy35;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy36;
if (yych <= 'Z') goto yy35;
} else {
if (yych == '`') goto yy36;
if (yych <= 'z') goto yy35;
}
}
yy36:
#line 125 "ext/rbs_extension/lexer.re"
{ return next_token(state, tUIDENT); }
#line 459 "ext/rbs_extension/lexer.c"
yy37:
rbs_skip(state);
yych = peek(state);
if (yych == ']') goto yy106;
#line 27 "ext/rbs_extension/lexer.re"
{ return next_token(state, pLBRACKET); }
#line 466 "ext/rbs_extension/lexer.c"
yy38:
rbs_skip(state);
#line 28 "ext/rbs_extension/lexer.re"
{ return next_token(state, pRBRACKET); }
#line 471 "ext/rbs_extension/lexer.c"
yy39:
rbs_skip(state);
#line 33 "ext/rbs_extension/lexer.re"
{ return next_token(state, pHAT); }
#line 476 "ext/rbs_extension/lexer.c"
yy40:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy107;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy41;
if (yych <= 'Z') goto yy109;
} else {
if (yych == '`') goto yy41;
if (yych <= 'z') goto yy107;
}
}
yy41:
#line 128 "ext/rbs_extension/lexer.re"
{ return next_token(state, tULLIDENT); }
#line 499 "ext/rbs_extension/lexer.c"
yy42:
yyaccept = 4;
rbs_skip(state);
backup = *state;
yych = peek(state);
if (yych <= ' ') {
if (yych <= 0x00000000) goto yy43;
if (yych <= 0x0000001F) goto yy111;
} else {
if (yych != ':') goto yy111;
}
yy43:
#line 40 "ext/rbs_extension/lexer.re"
{ return next_token(state, tOPERATOR); }
#line 514 "ext/rbs_extension/lexer.c"
yy44:
rbs_skip(state);
yych = peek(state);
if (yych <= 'r') {
if (yych == 'l') goto yy112;
goto yy52;
} else {
if (yych <= 's') goto yy113;
if (yych <= 't') goto yy115;
goto yy52;
}
yy45:
#line 124 "ext/rbs_extension/lexer.re"
{ return next_token(state, tLIDENT); }
#line 529 "ext/rbs_extension/lexer.c"
yy46:
rbs_skip(state);
yych = peek(state);
if (yych == 'o') goto yy116;
goto yy52;
yy47:
rbs_skip(state);
yych = peek(state);
if (yych == 'l') goto yy117;
goto yy52;
yy48:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy118;
goto yy52;
yy49:
rbs_skip(state);
yych = peek(state);
if (yych == 'n') goto yy119;
if (yych == 'x') goto yy120;
goto yy52;
yy50:
rbs_skip(state);
yych = peek(state);
if (yych == 'a') goto yy121;
goto yy52;
yy51:
rbs_skip(state);
yych = peek(state);
yy52:
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
goto yy45;
} else {
if (yych <= '9') goto yy51;
if (yych <= '<') goto yy45;
goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy45;
if (yych <= 'Z') goto yy51;
goto yy45;
} else {
if (yych == '`') goto yy45;
if (yych <= 'z') goto yy51;
goto yy45;
}
}
yy53:
rbs_skip(state);
yych = peek(state);
if (yych == 'n') goto yy122;
goto yy52;
yy54:
rbs_skip(state);
yych = peek(state);
if (yych == 'o') goto yy124;
goto yy52;
yy55:
rbs_skip(state);
yych = peek(state);
if (yych == 'i') goto yy125;
goto yy52;
yy56:
rbs_skip(state);
yych = peek(state);
if (yych == 'u') goto yy126;
goto yy52;
yy57:
rbs_skip(state);
yych = peek(state);
if (yych == 'r') goto yy127;
if (yych == 'u') goto yy128;
goto yy52;
yy58:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy129;
if (yych == 'i') goto yy130;
goto yy52;
yy59:
rbs_skip(state);
yych = peek(state);
if (yych <= 'q') {
if (yych == 'o') goto yy131;
goto yy52;
} else {
if (yych <= 'r') goto yy132;
if (yych == 'y') goto yy133;
goto yy52;
}
yy60:
rbs_skip(state);
yych = peek(state);
if (yych == 'n') goto yy134;
if (yych == 's') goto yy135;
goto yy52;
yy61:
rbs_skip(state);
yych = peek(state);
if (yych == 'o') goto yy136;
goto yy52;
yy62:
rbs_skip(state);
#line 29 "ext/rbs_extension/lexer.re"
{ return next_token(state, pLBRACE); }
#line 638 "ext/rbs_extension/lexer.c"
yy63:
rbs_skip(state);
#line 32 "ext/rbs_extension/lexer.re"
{ return next_token(state, pBAR); }
#line 643 "ext/rbs_extension/lexer.c"
yy64:
rbs_skip(state);
#line 30 "ext/rbs_extension/lexer.re"
{ return next_token(state, pRBRACE); }
#line 648 "ext/rbs_extension/lexer.c"
yy65:
rbs_skip(state);
yych = peek(state);
yy66:
if (yych <= '"') {
if (yych <= 0x00000000) goto yy67;
if (yych <= '!') goto yy65;
goto yy68;
} else {
if (yych == '\\') goto yy69;
goto yy65;
}
yy67:
*state = backup;
if (yyaccept <= 3) {
if (yyaccept <= 1) {
if (yyaccept == 0) {
goto yy3;
} else {
goto yy7;
}
} else {
if (yyaccept == 2) {
goto yy22;
} else {
goto yy27;
}
}
} else {
if (yyaccept <= 5) {
if (yyaccept == 4) {
goto yy43;
} else {
goto yy77;
}
} else {
goto yy150;
}
}
yy68:
rbs_skip(state);
#line 102 "ext/rbs_extension/lexer.re"
{ return next_token(state, tDQSTRING); }
#line 692 "ext/rbs_extension/lexer.c"
yy69:
rbs_skip(state);
yych = peek(state);
if (yych <= 'd') {
if (yych <= '[') {
if (yych == '"') goto yy65;
goto yy67;
} else {
if (yych <= '\\') goto yy65;
if (yych <= '`') goto yy67;
if (yych <= 'b') goto yy65;
goto yy67;
}
} else {
if (yych <= 'q') {
if (yych <= 'f') goto yy65;
if (yych == 'n') goto yy65;
goto yy67;
} else {
if (yych == 'u') goto yy67;
if (yych <= 'v') goto yy65;
goto yy67;
}
}
yy70:
rbs_skip(state);
yych = peek(state);
if (yych <= ',') {
if (yych <= '\f') {
if (yych <= 0x00000000) goto yy71;
if (yych <= 0x00000008) goto yy70;
if (yych >= '\v') goto yy70;
} else {
if (yych <= 0x0000001F) {
if (yych >= 0x0000000E) goto yy70;
} else {
if (yych == '#') goto yy70;
}
}
} else {
if (yych <= '>') {
if (yych <= '-') goto yy70;
if (yych <= '/') goto yy71;
if (yych <= '9') goto yy70;
} else {
if (yych <= '^') {
if (yych <= 'Z') goto yy70;
} else {
if (yych <= 'z') goto yy70;
if (yych >= 0x0000007F) goto yy70;
}
}
}
yy71:
#line 135 "ext/rbs_extension/lexer.re"
{ return next_token(state, tGIDENT); }
#line 749 "ext/rbs_extension/lexer.c"
yy72:
rbs_skip(state);
goto yy71;
yy73:
rbs_skip(state);
yych = peek(state);
if (yych <= 'Z') {
if (yych <= '(') {
if (yych <= '\'') goto yy67;
goto yy137;
} else {
if (yych == '<') goto yy138;
goto yy67;
}
} else {
if (yych <= 'z') {
if (yych <= '[') goto yy139;
goto yy67;
} else {
if (yych <= '{') goto yy140;
if (yych <= '|') goto yy141;
goto yy67;
}
}
yy74:
rbs_skip(state);
yych = peek(state);
yy75:
if (yych <= '\'') {
if (yych <= 0x00000000) goto yy67;
if (yych <= '&') goto yy74;
} else {
if (yych == '\\') goto yy78;
goto yy74;
}
yy76:
rbs_skip(state);
yy77:
#line 103 "ext/rbs_extension/lexer.re"
{ return next_token(state, tSQSTRING); }
#line 790 "ext/rbs_extension/lexer.c"
yy78:
rbs_skip(state);
yych = peek(state);
if (yych <= '\'') {
if (yych <= 0x00000000) goto yy67;
if (yych <= '&') goto yy74;
goto yy142;
} else {
if (yych == '\\') goto yy78;
goto yy74;
}
yy79:
rbs_skip(state);
#line 37 "ext/rbs_extension/lexer.re"
{ return next_token(state, pSTAR2); }
#line 806 "ext/rbs_extension/lexer.c"
yy80:
rbs_skip(state);
#line 42 "ext/rbs_extension/lexer.re"
{ return next_token(state, pARROW); }
#line 811 "ext/rbs_extension/lexer.c"
yy81:
rbs_skip(state);
yych = peek(state);
if (yych == '.') goto yy143;
goto yy67;
yy82:
rbs_skip(state);
yych = peek(state);
if (yych == '=') goto yy86;
if (yych == '~') goto yy86;
yy83:
#line 122 "ext/rbs_extension/lexer.re"
{ return next_token(state, tSYMBOL); }
#line 825 "ext/rbs_extension/lexer.c"
yy84:
rbs_skip(state);
yych = peek(state);
if (yych <= '"') {
if (yych <= 0x00000000) goto yy67;
if (yych <= '!') goto yy84;
goto yy144;
} else {
if (yych == '\\') goto yy145;
goto yy84;
}
yy85:
rbs_skip(state);
yych = peek(state);
if (yych <= ')') {
if (yych <= 0x0000001F) {
if (yych <= '\n') {
if (yych <= 0x00000000) goto yy67;
if (yych <= 0x00000008) goto yy146;
goto yy67;
} else {
if (yych == '\r') goto yy67;
goto yy146;
}
} else {
if (yych <= '#') {
if (yych <= ' ') goto yy67;
if (yych <= '"') goto yy148;
goto yy146;
} else {
if (yych == '%') goto yy67;
if (yych <= '\'') goto yy148;
goto yy67;
}
}
} else {
if (yych <= 'Z') {
if (yych <= '/') {
if (yych == '-') goto yy146;
goto yy148;
} else {
if (yych <= '9') goto yy146;
if (yych <= '>') goto yy148;
goto yy146;
}
} else {
if (yych <= '^') {
if (yych == '\\') goto yy148;
goto yy67;
} else {
if (yych <= 'z') goto yy146;
if (yych <= '}') goto yy67;
if (yych <= '~') goto yy148;
goto yy146;
}
}
}
yy86:
rbs_skip(state);
goto yy83;
yy87:
rbs_skip(state);
yych = peek(state);
if (yych <= '\'') {
if (yych <= 0x00000000) goto yy67;
if (yych <= '&') goto yy87;
goto yy149;
} else {
if (yych == '\\') goto yy151;
goto yy87;
}
yy88:
rbs_skip(state);
yych = peek(state);
if (yych == '*') goto yy86;
goto yy83;
yy89:
rbs_skip(state);
yych = peek(state);
if (yych == '@') goto yy86;
goto yy83;
yy90:
rbs_skip(state);
#line 46 "ext/rbs_extension/lexer.re"
{ return next_token(state, pCOLON2); }
#line 911 "ext/rbs_extension/lexer.c"
yy91:
rbs_skip(state);
yych = peek(state);
if (yych <= ';') goto yy83;
if (yych <= '<') goto yy86;
if (yych <= '=') goto yy152;
goto yy83;
yy92:
rbs_skip(state);
yych = peek(state);
if (yych == '=') goto yy153;
if (yych == '~') goto yy86;
goto yy67;
yy93:
rbs_skip(state);
yych = peek(state);
if (yych <= '<') goto yy83;
if (yych <= '>') goto yy86;
goto yy83;
yy94:
rbs_skip(state);
yych = peek(state);
if (yych <= '^') {
if (yych <= '?') goto yy67;
if (yych <= '@') goto yy154;
if (yych <= 'Z') goto yy155;
goto yy67;
} else {
if (yych == '`') goto yy67;
if (yych <= 'z') goto yy155;
goto yy67;
}
yy95:
rbs_skip(state);
yych = peek(state);
if (yych <= '>') {
if (yych <= '/') {
if (yych == '!') goto yy157;
} else {
if (yych <= '9') goto yy95;
if (yych == '=') goto yy157;
}
} else {
if (yych <= '^') {
if (yych <= '?') goto yy157;
if (yych <= '@') goto yy96;
if (yych <= 'Z') goto yy95;
} else {
if (yych == '`') goto yy96;
if (yych <= 'z') goto yy95;
}
}
yy96:
#line 118 "ext/rbs_extension/lexer.re"
{ return next_token(state, tSYMBOL); }
#line 967 "ext/rbs_extension/lexer.c"
yy97:
rbs_skip(state);
yych = peek(state);
if (yych == ']') goto yy153;
goto yy67;
yy98:
rbs_skip(state);
yych = peek(state);
if (yych == '>') goto yy23;
goto yy7;
yy99:
rbs_skip(state);
yych = peek(state);
if (yych == '=') goto yy23;
goto yy7;
yy100:
rbs_skip(state);
#line 43 "ext/rbs_extension/lexer.re"
{ return next_token(state, pFATARROW); }
#line 987 "ext/rbs_extension/lexer.c"
yy101:
rbs_skip(state);
yych = peek(state);
if (yych <= '^') {
if (yych <= '@') goto yy67;
if (yych <= 'Z') goto yy158;
goto yy67;
} else {
if (yych == '`') goto yy67;
if (yych <= 'z') goto yy158;
goto yy67;
}
yy102:
rbs_skip(state);
yych = peek(state);
if (yych <= 'Z') {
if (yych <= '/') goto yy103;
if (yych <= '9') goto yy102;
if (yych >= 'A') goto yy102;
} else {
if (yych <= '_') {
if (yych >= '_') goto yy102;
} else {
if (yych <= '`') goto yy103;
if (yych <= 'z') goto yy102;
}
}
yy103:
#line 132 "ext/rbs_extension/lexer.re"
{ return next_token(state, tAIDENT); }
#line 1018 "ext/rbs_extension/lexer.c"
yy104:
rbs_skip(state);
#line 129 "ext/rbs_extension/lexer.re"
{ return next_token(state, tBANGIDENT); }
#line 1023 "ext/rbs_extension/lexer.c"
yy105:
rbs_skip(state);
#line 130 "ext/rbs_extension/lexer.re"
{ return next_token(state, tEQIDENT); }
#line 1028 "ext/rbs_extension/lexer.c"
yy106:
rbs_skip(state);
yych = peek(state);
if (yych == '=') goto yy23;
#line 48 "ext/rbs_extension/lexer.re"
{ return next_token(state, pAREF_OPR); }
#line 1035 "ext/rbs_extension/lexer.c"
yy107:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy107;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy108;
if (yych <= 'Z') goto yy107;
} else {
if (yych == '`') goto yy108;
if (yych <= 'z') goto yy107;
}
}
yy108:
#line 126 "ext/rbs_extension/lexer.re"
{ return next_token(state, tULLIDENT); }
#line 1058 "ext/rbs_extension/lexer.c"
yy109:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy109;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy110;
if (yych <= 'Z') goto yy109;
} else {
if (yych == '`') goto yy110;
if (yych <= 'z') goto yy109;
}
}
yy110:
#line 127 "ext/rbs_extension/lexer.re"
{ return next_token(state, tULIDENT); }
#line 1081 "ext/rbs_extension/lexer.c"
yy111:
rbs_skip(state);
yych = peek(state);
if (yych <= 0x00000000) goto yy67;
if (yych == '`') goto yy160;
goto yy111;
yy112:
rbs_skip(state);
yych = peek(state);
if (yych == 'i') goto yy161;
goto yy52;
yy113:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy114;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy114;
if (yych <= 'z') goto yy51;
}
}
yy114:
#line 97 "ext/rbs_extension/lexer.re"
{ return next_token(state, kAS); }
#line 1115 "ext/rbs_extension/lexer.c"
yy115:
rbs_skip(state);
yych = peek(state);
if (yych == 't') goto yy162;
goto yy52;
yy116:
rbs_skip(state);
yych = peek(state);
if (yych == 'o') goto yy163;
if (yych == 't') goto yy164;
goto yy52;
yy117:
rbs_skip(state);
yych = peek(state);
if (yych == 'a') goto yy166;
goto yy52;
yy118:
rbs_skip(state);
yych = peek(state);
if (yych == 'f') goto yy167;
goto yy52;
yy119:
rbs_skip(state);
yych = peek(state);
if (yych == 'd') goto yy169;
goto yy52;
yy120:
rbs_skip(state);
yych = peek(state);
if (yych == 't') goto yy171;
goto yy52;
yy121:
rbs_skip(state);
yych = peek(state);
if (yych == 'l') goto yy172;
goto yy52;
yy122:
rbs_skip(state);
yych = peek(state);
if (yych <= '^') {
if (yych <= '9') {
if (yych == '!') goto yy104;
if (yych >= '0') goto yy51;
} else {
if (yych <= '=') {
if (yych >= '=') goto yy105;
} else {
if (yych <= '@') goto yy123;
if (yych <= 'Z') goto yy51;
}
}
} else {
if (yych <= 'c') {
if (yych == '`') goto yy123;
if (yych <= 'b') goto yy51;
goto yy173;
} else {
if (yych <= 's') {
if (yych <= 'r') goto yy51;
goto yy174;
} else {
if (yych <= 't') goto yy175;
if (yych <= 'z') goto yy51;
}
}
}
yy123:
#line 78 "ext/rbs_extension/lexer.re"
{ return next_token(state, kIN); }
#line 1185 "ext/rbs_extension/lexer.c"
yy124:
rbs_skip(state);
yych = peek(state);
if (yych == 'd') goto yy176;
goto yy52;
yy125:
rbs_skip(state);
yych = peek(state);
if (yych == 'l') goto yy177;
goto yy52;
yy126:
rbs_skip(state);
yych = peek(state);
if (yych == 't') goto yy179;
goto yy52;
yy127:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy181;
if (yych == 'i') goto yy182;
goto yy52;
yy128:
rbs_skip(state);
yych = peek(state);
if (yych == 'b') goto yy183;
goto yy52;
yy129:
rbs_skip(state);
yych = peek(state);
if (yych == 'l') goto yy184;
goto yy52;
yy130:
rbs_skip(state);
yych = peek(state);
if (yych == 'n') goto yy185;
goto yy52;
yy131:
rbs_skip(state);
yych = peek(state);
if (yych == 'p') goto yy186;
goto yy52;
yy132:
rbs_skip(state);
yych = peek(state);
if (yych == 'u') goto yy188;
goto yy52;
yy133:
rbs_skip(state);
yych = peek(state);
if (yych == 'p') goto yy189;
goto yy52;
yy134:
rbs_skip(state);
yych = peek(state);
if (yych == 'c') goto yy190;
if (yych == 't') goto yy191;
goto yy52;
yy135:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy192;
goto yy52;
yy136:
rbs_skip(state);
yych = peek(state);
if (yych == 'i') goto yy194;
goto yy52;
yy137:
rbs_skip(state);
yych = peek(state);
if (yych <= 0x00000000) goto yy67;
if (yych == ')') goto yy195;
goto yy137;
yy138:
rbs_skip(state);
yych = peek(state);
if (yych <= 0x00000000) goto yy67;
if (yych == '>') goto yy196;
goto yy138;
yy139:
rbs_skip(state);
yych = peek(state);
if (yych <= 0x00000000) goto yy67;
if (yych == ']') goto yy197;
goto yy139;
yy140:
rbs_skip(state);
yych = peek(state);
if (yych <= 0x00000000) goto yy67;
if (yych == '}') goto yy198;
goto yy140;
yy141:
rbs_skip(state);
yych = peek(state);
if (yych <= 0x00000000) goto yy67;
if (yych == '|') goto yy199;
goto yy141;
yy142:
yyaccept = 5;
rbs_skip(state);
backup = *state;
yych = peek(state);
if (yych <= '\'') {
if (yych <= 0x00000000) goto yy77;
if (yych <= '&') goto yy74;
goto yy76;
} else {
if (yych == '\\') goto yy78;
goto yy74;
}
yy143:
rbs_skip(state);
#line 39 "ext/rbs_extension/lexer.re"
{ return next_token(state, pDOT3); }
#line 1300 "ext/rbs_extension/lexer.c"
yy144:
rbs_skip(state);
#line 104 "ext/rbs_extension/lexer.re"
{ return next_token(state, tDQSYMBOL); }
#line 1305 "ext/rbs_extension/lexer.c"
yy145:
rbs_skip(state);
yych = peek(state);
if (yych <= 'd') {
if (yych <= '[') {
if (yych == '"') goto yy84;
goto yy67;
} else {
if (yych <= '\\') goto yy84;
if (yych <= '`') goto yy67;
if (yych <= 'b') goto yy84;
goto yy67;
}
} else {
if (yych <= 'q') {
if (yych <= 'f') goto yy84;
if (yych == 'n') goto yy84;
goto yy67;
} else {
if (yych == 'u') goto yy67;
if (yych <= 'v') goto yy84;
goto yy67;
}
}
yy146:
rbs_skip(state);
yych = peek(state);
if (yych <= ',') {
if (yych <= '\f') {
if (yych <= 0x00000000) goto yy147;
if (yych <= 0x00000008) goto yy146;
if (yych >= '\v') goto yy146;
} else {
if (yych <= 0x0000001F) {
if (yych >= 0x0000000E) goto yy146;
} else {
if (yych == '#') goto yy146;
}
}
} else {
if (yych <= '>') {
if (yych <= '-') goto yy146;
if (yych <= '/') goto yy147;
if (yych <= '9') goto yy146;
} else {
if (yych <= '^') {
if (yych <= 'Z') goto yy146;
} else {
if (yych <= 'z') goto yy146;
if (yych >= 0x0000007F) goto yy146;
}
}
}
yy147:
#line 121 "ext/rbs_extension/lexer.re"
{ return next_token(state, tSYMBOL); }
#line 1362 "ext/rbs_extension/lexer.c"
yy148:
rbs_skip(state);
goto yy147;
yy149:
rbs_skip(state);
yy150:
#line 105 "ext/rbs_extension/lexer.re"
{ return next_token(state, tSQSYMBOL); }
#line 1371 "ext/rbs_extension/lexer.c"
yy151:
rbs_skip(state);
yych = peek(state);
if (yych <= '\'') {
if (yych <= 0x00000000) goto yy67;
if (yych <= '&') goto yy87;
goto yy200;
} else {
if (yych == '\\') goto yy151;
goto yy87;
}
yy152:
rbs_skip(state);
yych = peek(state);
if (yych == '>') goto yy86;
goto yy83;
yy153:
rbs_skip(state);
yych = peek(state);
if (yych == '=') goto yy86;
goto yy83;
yy154:
rbs_skip(state);
yych = peek(state);
if (yych <= '^') {
if (yych <= '@') goto yy67;
if (yych <= 'Z') goto yy201;
goto yy67;
} else {
if (yych == '`') goto yy67;
if (yych <= 'z') goto yy201;
goto yy67;
}
yy155:
rbs_skip(state);
yych = peek(state);
if (yych <= '>') {
if (yych <= '/') {
if (yych == '!') goto yy203;
} else {
if (yych <= '9') goto yy155;
if (yych == '=') goto yy203;
}
} else {
if (yych <= '^') {
if (yych <= '?') goto yy203;
if (yych <= '@') goto yy156;
if (yych <= 'Z') goto yy155;
} else {
if (yych == '`') goto yy156;
if (yych <= 'z') goto yy155;
}
}
yy156:
#line 119 "ext/rbs_extension/lexer.re"
{ return next_token(state, tSYMBOL); }
#line 1428 "ext/rbs_extension/lexer.c"
yy157:
rbs_skip(state);
goto yy96;
yy158:
rbs_skip(state);
yych = peek(state);
if (yych <= 'Z') {
if (yych <= '/') goto yy159;
if (yych <= '9') goto yy158;
if (yych >= 'A') goto yy158;
} else {
if (yych <= '_') {
if (yych >= '_') goto yy158;
} else {
if (yych <= '`') goto yy159;
if (yych <= 'z') goto yy158;
}
}
yy159:
#line 133 "ext/rbs_extension/lexer.re"
{ return next_token(state, tA2IDENT); }
#line 1450 "ext/rbs_extension/lexer.c"
yy160:
rbs_skip(state);
#line 41 "ext/rbs_extension/lexer.re"
{ return next_token(state, tQIDENT); }
#line 1455 "ext/rbs_extension/lexer.c"
yy161:
rbs_skip(state);
yych = peek(state);
if (yych == 'a') goto yy204;
goto yy52;
yy162:
rbs_skip(state);
yych = peek(state);
if (yych == 'r') goto yy205;
goto yy52;
yy163:
rbs_skip(state);
yych = peek(state);
if (yych == 'l') goto yy206;
goto yy52;
yy164:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy165;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy165;
if (yych <= 'z') goto yy51;
}
}
yy165:
#line 72 "ext/rbs_extension/lexer.re"
{ return next_token(state, kBOT); }
#line 1493 "ext/rbs_extension/lexer.c"
yy166:
rbs_skip(state);
yych = peek(state);
if (yych == 's') goto yy208;
goto yy52;
yy167:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy168;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy168;
if (yych <= 'z') goto yy51;
}
}
yy168:
#line 74 "ext/rbs_extension/lexer.re"
{ return next_token(state, kDEF); }
#line 1521 "ext/rbs_extension/lexer.c"
yy169:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy170;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy170;
if (yych <= 'z') goto yy51;
}
}
yy170:
#line 75 "ext/rbs_extension/lexer.re"
{ return next_token(state, kEND); }
#line 1544 "ext/rbs_extension/lexer.c"
yy171:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy209;
goto yy52;
yy172:
rbs_skip(state);
yych = peek(state);
if (yych == 's') goto yy210;
goto yy52;
yy173:
rbs_skip(state);
yych = peek(state);
if (yych == 'l') goto yy211;
goto yy52;
yy174:
rbs_skip(state);
yych = peek(state);
if (yych == 't') goto yy212;
goto yy52;
yy175:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy213;
goto yy52;
yy176:
rbs_skip(state);
yych = peek(state);
if (yych == 'u') goto yy214;
goto yy52;
yy177:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy178;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy178;
if (yych <= 'z') goto yy51;
}
}
yy178:
#line 83 "ext/rbs_extension/lexer.re"
{ return next_token(state, kNIL); }
#line 1597 "ext/rbs_extension/lexer.c"
yy179:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy180;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy180;
if (yych <= 'z') goto yy51;
}
}
yy180:
#line 84 "ext/rbs_extension/lexer.re"
{ return next_token(state, kOUT); }
#line 1620 "ext/rbs_extension/lexer.c"
yy181:
rbs_skip(state);
yych = peek(state);
if (yych == 'p') goto yy215;
goto yy52;
yy182:
rbs_skip(state);
yych = peek(state);
if (yych == 'v') goto yy216;
goto yy52;
yy183:
rbs_skip(state);
yych = peek(state);
if (yych == 'l') goto yy217;
goto yy52;
yy184:
rbs_skip(state);
yych = peek(state);
if (yych == 'f') goto yy218;
goto yy52;
yy185:
rbs_skip(state);
yych = peek(state);
if (yych == 'g') goto yy220;
goto yy52;
yy186:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy187;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy187;
if (yych <= 'z') goto yy51;
}
}
yy187:
#line 90 "ext/rbs_extension/lexer.re"
{ return next_token(state, kTOP); }
#line 1668 "ext/rbs_extension/lexer.c"
yy188:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy221;
goto yy52;
yy189:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy223;
goto yy52;
yy190:
rbs_skip(state);
yych = peek(state);
if (yych == 'h') goto yy225;
goto yy52;
yy191:
rbs_skip(state);
yych = peek(state);
if (yych == 'y') goto yy226;
goto yy52;
yy192:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy193;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy193;
if (yych <= 'z') goto yy51;
}
}
yy193:
#line 96 "ext/rbs_extension/lexer.re"
{ return next_token(state, kUSE); }
#line 1711 "ext/rbs_extension/lexer.c"
yy194:
rbs_skip(state);
yych = peek(state);
if (yych == 'd') goto yy227;
goto yy52;
yy195:
rbs_skip(state);
#line 55 "ext/rbs_extension/lexer.re"
{ return next_token(state, tANNOTATION); }
#line 1721 "ext/rbs_extension/lexer.c"
yy196:
rbs_skip(state);
#line 58 "ext/rbs_extension/lexer.re"
{ return next_token(state, tANNOTATION); }
#line 1726 "ext/rbs_extension/lexer.c"
yy197:
rbs_skip(state);
#line 56 "ext/rbs_extension/lexer.re"
{ return next_token(state, tANNOTATION); }
#line 1731 "ext/rbs_extension/lexer.c"
yy198:
rbs_skip(state);
#line 54 "ext/rbs_extension/lexer.re"
{ return next_token(state, tANNOTATION); }
#line 1736 "ext/rbs_extension/lexer.c"
yy199:
rbs_skip(state);
#line 57 "ext/rbs_extension/lexer.re"
{ return next_token(state, tANNOTATION); }
#line 1741 "ext/rbs_extension/lexer.c"
yy200:
yyaccept = 6;
rbs_skip(state);
backup = *state;
yych = peek(state);
if (yych <= '\'') {
if (yych <= 0x00000000) goto yy150;
if (yych <= '&') goto yy87;
goto yy149;
} else {
if (yych == '\\') goto yy151;
goto yy87;
}
yy201:
rbs_skip(state);
yych = peek(state);
if (yych <= '>') {
if (yych <= '/') {
if (yych == '!') goto yy229;
} else {
if (yych <= '9') goto yy201;
if (yych == '=') goto yy229;
}
} else {
if (yych <= '^') {
if (yych <= '?') goto yy229;
if (yych <= '@') goto yy202;
if (yych <= 'Z') goto yy201;
} else {
if (yych == '`') goto yy202;
if (yych <= 'z') goto yy201;
}
}
yy202:
#line 120 "ext/rbs_extension/lexer.re"
{ return next_token(state, tSYMBOL); }
#line 1778 "ext/rbs_extension/lexer.c"
yy203:
rbs_skip(state);
goto yy156;
yy204:
rbs_skip(state);
yych = peek(state);
if (yych == 's') goto yy230;
goto yy52;
yy205:
rbs_skip(state);
yych = peek(state);
if (yych == '_') goto yy232;
goto yy52;
yy206:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy207;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy207;
if (yych <= 'z') goto yy51;
}
}
yy207:
#line 71 "ext/rbs_extension/lexer.re"
{ return next_token(state, kBOOL); }
#line 1814 "ext/rbs_extension/lexer.c"
yy208:
rbs_skip(state);
yych = peek(state);
if (yych == 's') goto yy233;
goto yy52;
yy209:
rbs_skip(state);
yych = peek(state);
if (yych == 'n') goto yy235;
goto yy52;
yy210:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy236;
goto yy52;
yy211:
rbs_skip(state);
yych = peek(state);
if (yych == 'u') goto yy238;
goto yy52;
yy212:
rbs_skip(state);
yych = peek(state);
if (yych == 'a') goto yy239;
goto yy52;
yy213:
rbs_skip(state);
yych = peek(state);
if (yych == 'r') goto yy240;
goto yy52;
yy214:
rbs_skip(state);
yych = peek(state);
if (yych == 'l') goto yy241;
goto yy52;
yy215:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy242;
goto yy52;
yy216:
rbs_skip(state);
yych = peek(state);
if (yych == 'a') goto yy243;
goto yy52;
yy217:
rbs_skip(state);
yych = peek(state);
if (yych == 'i') goto yy244;
goto yy52;
yy218:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy219;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy219;
if (yych <= 'z') goto yy51;
}
}
yy219:
#line 88 "ext/rbs_extension/lexer.re"
{ return next_token(state, kSELF); }
#line 1887 "ext/rbs_extension/lexer.c"
yy220:
rbs_skip(state);
yych = peek(state);
if (yych == 'l') goto yy245;
goto yy52;
yy221:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy222;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy222;
if (yych <= 'z') goto yy51;
}
}
yy222:
#line 91 "ext/rbs_extension/lexer.re"
{ return next_token(state, kTRUE); }
#line 1915 "ext/rbs_extension/lexer.c"
yy223:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy224;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy224;
if (yych <= 'z') goto yy51;
}
}
yy224:
#line 92 "ext/rbs_extension/lexer.re"
{ return next_token(state, kTYPE); }
#line 1938 "ext/rbs_extension/lexer.c"
yy225:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy246;
goto yy52;
yy226:
rbs_skip(state);
yych = peek(state);
if (yych == 'p') goto yy247;
goto yy52;
yy227:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy228;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy228;
if (yych <= 'z') goto yy51;
}
}
yy228:
#line 95 "ext/rbs_extension/lexer.re"
{ return next_token(state, kVOID); }
#line 1971 "ext/rbs_extension/lexer.c"
yy229:
rbs_skip(state);
goto yy202;
yy230:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy231;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy231;
if (yych <= 'z') goto yy51;
}
}
yy231:
#line 67 "ext/rbs_extension/lexer.re"
{ return next_token(state, kALIAS); }
#line 1997 "ext/rbs_extension/lexer.c"
yy232:
rbs_skip(state);
yych = peek(state);
if (yych <= 'q') {
if (yych == 'a') goto yy248;
goto yy52;
} else {
if (yych <= 'r') goto yy249;
if (yych == 'w') goto yy250;
goto yy52;
}
yy233:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy234;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy234;
if (yych <= 'z') goto yy51;
}
}
yy234:
#line 73 "ext/rbs_extension/lexer.re"
{ return next_token(state, kCLASS); }
#line 2031 "ext/rbs_extension/lexer.c"
yy235:
rbs_skip(state);
yych = peek(state);
if (yych == 'd') goto yy251;
goto yy52;
yy236:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy237;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy237;
if (yych <= 'z') goto yy51;
}
}
yy237:
#line 77 "ext/rbs_extension/lexer.re"
{ return next_token(state, kFALSE); }
#line 2059 "ext/rbs_extension/lexer.c"
yy238:
rbs_skip(state);
yych = peek(state);
if (yych == 'd') goto yy253;
goto yy52;
yy239:
rbs_skip(state);
yych = peek(state);
if (yych == 'n') goto yy254;
goto yy52;
yy240:
rbs_skip(state);
yych = peek(state);
if (yych == 'f') goto yy255;
goto yy52;
yy241:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy256;
goto yy52;
yy242:
rbs_skip(state);
yych = peek(state);
if (yych == 'n') goto yy258;
goto yy52;
yy243:
rbs_skip(state);
yych = peek(state);
if (yych == 't') goto yy259;
goto yy52;
yy244:
rbs_skip(state);
yych = peek(state);
if (yych == 'c') goto yy260;
goto yy52;
yy245:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy262;
goto yy52;
yy246:
rbs_skip(state);
yych = peek(state);
if (yych == 'c') goto yy263;
goto yy52;
yy247:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy264;
goto yy52;
yy248:
rbs_skip(state);
yych = peek(state);
if (yych == 'c') goto yy265;
goto yy52;
yy249:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy266;
goto yy52;
yy250:
rbs_skip(state);
yych = peek(state);
if (yych == 'r') goto yy267;
goto yy52;
yy251:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy252;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy252;
if (yych <= 'z') goto yy51;
}
}
yy252:
#line 76 "ext/rbs_extension/lexer.re"
{ return next_token(state, kEXTEND); }
#line 2147 "ext/rbs_extension/lexer.c"
yy253:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy268;
goto yy52;
yy254:
rbs_skip(state);
yych = peek(state);
if (yych == 'c') goto yy270;
goto yy52;
yy255:
rbs_skip(state);
yych = peek(state);
if (yych == 'a') goto yy271;
goto yy52;
yy256:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy257;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy257;
if (yych <= 'z') goto yy51;
}
}
yy257:
#line 82 "ext/rbs_extension/lexer.re"
{ return next_token(state, kMODULE); }
#line 2185 "ext/rbs_extension/lexer.c"
yy258:
rbs_skip(state);
yych = peek(state);
if (yych == 'd') goto yy272;
goto yy52;
yy259:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy274;
goto yy52;
yy260:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy261;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy261;
if (yych <= 'z') goto yy51;
}
}
yy261:
#line 87 "ext/rbs_extension/lexer.re"
{ return next_token(state, kPUBLIC); }
#line 2218 "ext/rbs_extension/lexer.c"
yy262:
rbs_skip(state);
yych = peek(state);
if (yych == 't') goto yy276;
goto yy52;
yy263:
rbs_skip(state);
yych = peek(state);
if (yych == 'k') goto yy277;
goto yy52;
yy264:
rbs_skip(state);
yych = peek(state);
if (yych == 'd') goto yy278;
goto yy52;
yy265:
rbs_skip(state);
yych = peek(state);
if (yych == 'c') goto yy280;
goto yy52;
yy266:
rbs_skip(state);
yych = peek(state);
if (yych == 'a') goto yy281;
goto yy52;
yy267:
rbs_skip(state);
yych = peek(state);
if (yych == 'i') goto yy282;
goto yy52;
yy268:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy269;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy269;
if (yych <= 'z') goto yy51;
}
}
yy269:
#line 79 "ext/rbs_extension/lexer.re"
{ return next_token(state, kINCLUDE); }
#line 2271 "ext/rbs_extension/lexer.c"
yy270:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy283;
goto yy52;
yy271:
rbs_skip(state);
yych = peek(state);
if (yych == 'c') goto yy285;
goto yy52;
yy272:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy273;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy273;
if (yych <= 'z') goto yy51;
}
}
yy273:
#line 85 "ext/rbs_extension/lexer.re"
{ return next_token(state, kPREPEND); }
#line 2304 "ext/rbs_extension/lexer.c"
yy274:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy275;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy275;
if (yych <= 'z') goto yy51;
}
}
yy275:
#line 86 "ext/rbs_extension/lexer.re"
{ return next_token(state, kPRIVATE); }
#line 2327 "ext/rbs_extension/lexer.c"
yy276:
rbs_skip(state);
yych = peek(state);
if (yych == 'o') goto yy286;
goto yy52;
yy277:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy287;
goto yy52;
yy278:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy279;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy279;
if (yych <= 'z') goto yy51;
}
}
yy279:
#line 94 "ext/rbs_extension/lexer.re"
{ return next_token(state, kUNTYPED); }
#line 2360 "ext/rbs_extension/lexer.c"
yy280:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy288;
goto yy52;
yy281:
rbs_skip(state);
yych = peek(state);
if (yych == 'd') goto yy289;
goto yy52;
yy282:
rbs_skip(state);
yych = peek(state);
if (yych == 't') goto yy290;
goto yy52;
yy283:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy284;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy284;
if (yych <= 'z') goto yy51;
}
}
yy284:
#line 80 "ext/rbs_extension/lexer.re"
{ return next_token(state, kINSTANCE); }
#line 2398 "ext/rbs_extension/lexer.c"
yy285:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy291;
goto yy52;
yy286:
rbs_skip(state);
yych = peek(state);
if (yych == 'n') goto yy293;
goto yy52;
yy287:
rbs_skip(state);
yych = peek(state);
if (yych == 'd') goto yy295;
goto yy52;
yy288:
rbs_skip(state);
yych = peek(state);
if (yych == 's') goto yy297;
goto yy52;
yy289:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy298;
goto yy52;
yy290:
rbs_skip(state);
yych = peek(state);
if (yych == 'e') goto yy299;
goto yy52;
yy291:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy292;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy292;
if (yych <= 'z') goto yy51;
}
}
yy292:
#line 81 "ext/rbs_extension/lexer.re"
{ return next_token(state, kINTERFACE); }
#line 2451 "ext/rbs_extension/lexer.c"
yy293:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy294;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy294;
if (yych <= 'z') goto yy51;
}
}
yy294:
#line 89 "ext/rbs_extension/lexer.re"
{ return next_token(state, kSINGLETON); }
#line 2474 "ext/rbs_extension/lexer.c"
yy295:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy296;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy296;
if (yych <= 'z') goto yy51;
}
}
yy296:
#line 93 "ext/rbs_extension/lexer.re"
{ return next_token(state, kUNCHECKED); }
#line 2497 "ext/rbs_extension/lexer.c"
yy297:
rbs_skip(state);
yych = peek(state);
if (yych == 's') goto yy300;
goto yy52;
yy298:
rbs_skip(state);
yych = peek(state);
if (yych == 'r') goto yy301;
goto yy52;
yy299:
rbs_skip(state);
yych = peek(state);
if (yych == 'r') goto yy303;
goto yy52;
yy300:
rbs_skip(state);
yych = peek(state);
if (yych == 'o') goto yy305;
goto yy52;
yy301:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy302;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy302;
if (yych <= 'z') goto yy51;
}
}
yy302:
#line 69 "ext/rbs_extension/lexer.re"
{ return next_token(state, kATTRREADER); }
#line 2540 "ext/rbs_extension/lexer.c"
yy303:
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy304;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy304;
if (yych <= 'z') goto yy51;
}
}
yy304:
#line 70 "ext/rbs_extension/lexer.re"
{ return next_token(state, kATTRWRITER); }
#line 2563 "ext/rbs_extension/lexer.c"
yy305:
rbs_skip(state);
yych = peek(state);
if (yych != 'r') goto yy52;
rbs_skip(state);
yych = peek(state);
if (yych <= '=') {
if (yych <= '/') {
if (yych == '!') goto yy104;
} else {
if (yych <= '9') goto yy51;
if (yych >= '=') goto yy105;
}
} else {
if (yych <= '^') {
if (yych <= '@') goto yy306;
if (yych <= 'Z') goto yy51;
} else {
if (yych == '`') goto yy306;
if (yych <= 'z') goto yy51;
}
}
yy306:
#line 68 "ext/rbs_extension/lexer.re"
{ return next_token(state, kATTRACCESSOR); }
#line 2589 "ext/rbs_extension/lexer.c"
}
#line 142 "ext/rbs_extension/lexer.re"
}
|
804f9f05ef3c19f41c77aabf2b7af3c8079edc4f
|
9e3cd787de3b38f417e71a2c2d816713e38bf116
|
/litedram/gen-src/sdram_init/main.c
|
2d99410d993de8abc33c3536ca6f0eec183a90d7
|
[
"CC-BY-4.0"
] |
permissive
|
antonblanchard/microwatt
|
34cd0b8b730c937e9ae95fd7940cc1014845697a
|
83dcfeabf8d37e7ea1adfafcd782f1298a3ddbef
|
refs/heads/master
| 2023-07-25T04:37:31.872162
| 2023-02-20T06:18:35
| 2023-02-20T06:18:35
| 203,724,916
| 606
| 106
|
NOASSERTION
| 2023-09-14T07:55:48
| 2019-08-22T06:02:52
|
Verilog
|
UTF-8
|
C
| false
| false
| 7,542
|
c
|
main.c
|
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdarg.h>
#include <stdio.h>
#include <generated/git.h>
#include "console.h"
#include "microwatt_soc.h"
#include "io.h"
#include "sdram.h"
#include "elf64.h"
#define FLASH_LOADER_USE_MAP
int _printf(const char *fmt, ...)
{
int count;
char buffer[128];
va_list ap;
va_start(ap, fmt);
count = vsnprintf(buffer, sizeof(buffer), fmt, ap);
va_end(ap);
puts(buffer);
return count;
}
void flush_cpu_dcache(void)
{
}
void flush_cpu_icache(void)
{
__asm__ volatile ("icbi 0,0; isync" : : : "memory");
}
#define SPI_CMD_RDID 0x9f
#define SPI_CMD_READ 0x03
#define SPI_CMD_DUAL_FREAD 0x3b
#define SPI_CMD_QUAD_FREAD 0x6b
#define SPI_CMD_RDCR 0x35
#define SPI_CMD_WREN 0x06
#define SPI_CMD_PP 0x02
#define SPI_CMD_RDSR 0x05
#define SPI_CMD_WWR 0x01
static void fl_cs_on(void)
{
writeb(SPI_REG_CTRL_MANUAL_CS, SPI_FCTRL_BASE + SPI_REG_CTRL);
}
static void fl_cs_off(void)
{
writeb(0, SPI_FCTRL_BASE + SPI_REG_CTRL);
__asm__ volatile("nop");
__asm__ volatile("nop");
__asm__ volatile("nop");
__asm__ volatile("nop");
__asm__ volatile("nop");
}
static void wait_wip(void)
{
for (;;) {
uint8_t sr;
fl_cs_on();
writeb(SPI_CMD_RDSR, SPI_FCTRL_BASE + SPI_REG_DATA);
sr = readb(SPI_FCTRL_BASE + SPI_REG_DATA);
fl_cs_off();
if ((sr & 1) == 0)
break;
}
}
static void send_wren(void)
{
fl_cs_on();
writeb(SPI_CMD_WREN, SPI_FCTRL_BASE + SPI_REG_DATA);
fl_cs_off();
}
static void check_spansion_quad_mode(void)
{
uint8_t cf1;
writeb(SPI_CMD_RDCR, SPI_FCTRL_BASE + SPI_REG_DATA);
fl_cs_on();
writeb(SPI_CMD_RDCR, SPI_FCTRL_BASE + SPI_REG_DATA);
cf1 = readb(SPI_FCTRL_BASE + SPI_REG_DATA);
fl_cs_off();
printf(" Cypress/Spansion (CF1=%02x)", cf1);
if (cf1 & 0x02)
return;
printf(" enabling QUAD");
send_wren();
fl_cs_on();
writeb(SPI_CMD_WWR, SPI_FCTRL_BASE + SPI_REG_DATA);
writeb(0x00, SPI_FCTRL_BASE + SPI_REG_DATA);
writeb(cf1 | 0x02, SPI_FCTRL_BASE + SPI_REG_DATA);
writeb(0, SPI_FCTRL_BASE + SPI_REG_CTRL);
fl_cs_off();
wait_wip();
}
static bool check_flash(void)
{
bool quad = false;
uint8_t id[3];
fl_cs_on();
writeb(SPI_CMD_RDID, SPI_FCTRL_BASE + SPI_REG_DATA);
id[0] = readb(SPI_FCTRL_BASE + SPI_REG_DATA);
id[1] = readb(SPI_FCTRL_BASE + SPI_REG_DATA);
id[2] = readb(SPI_FCTRL_BASE + SPI_REG_DATA);
fl_cs_off();
printf(" SPI FLASH ID: %02x%02x%02x", id[0], id[1], id[2]);
if ((id[0] | id[1] | id[2]) == 0 ||
(id[0] & id[1] & id[2]) == 0xff)
return false;
/* Supported flash types for quad mode */
if (id[0] == 0x01 &&
(id[1] == 0x02 || id[1] == 0x20 || id[1] == 0x60) &&
(id[2] == 0x18 || id[2] == 0x19)) {
check_spansion_quad_mode();
quad = true;
}
if (id[0] == 0x20 && id[1] == 0xba && id[2] == 0x18) {
printf(" Micron");
quad = true;
}
if (quad) {
uint32_t cfg;
printf(" [quad IO mode]");
/* Preserve the default clock div for the board */
cfg = readl(SPI_FCTRL_BASE + SPI_REG_AUTO_CFG);
cfg &= SPI_REG_AUTO_CFG_CKDIV_MASK;
/* Enable quad mode, 8 dummy clocks, 32 cycles CS timeout */
cfg |= SPI_CMD_QUAD_FREAD |
(0x07 << SPI_REG_AUTO_CFG_DUMMIES_SHIFT) |
SPI_REG_AUT_CFG_MODE_QUAD |
(0x20 << SPI_REG_AUTO_CFG_CSTOUT_SHIFT);
writel(cfg, SPI_FCTRL_BASE + SPI_REG_AUTO_CFG);
}
printf("\n");
return true;
}
static bool fl_read(void *dst, uint32_t offset, uint32_t size)
{
uint8_t *d = dst;
#ifdef FLASH_LOADER_USE_MAP
memcpy(d, (void *)(unsigned long)(SPI_FLASH_BASE + offset), size);
#else
if (size < 1)
return false;
fl_cs_on();
writeb(SPI_CMD_QUAD_FREAD, SPI_FCTRL_BASE + SPI_REG_DATA);
writeb(offset >> 16, SPI_FCTRL_BASE + SPI_REG_DATA);
writeb(offset >> 8, SPI_FCTRL_BASE + SPI_REG_DATA);
writeb(offset, SPI_FCTRL_BASE + SPI_REG_DATA);
writeb(0x00, SPI_FCTRL_BASE + SPI_REG_DATA);
while(size--)
*(d++) = readb(SPI_FCTRL_BASE + SPI_REG_DATA_QUAD);
fl_cs_off();
#endif
return true;
}
static unsigned long boot_flash(unsigned int offset)
{
Elf64_Ehdr ehdr;
Elf64_Phdr ph;
unsigned int i, poff, size, off;
void *addr;
printf("Trying flash...\n");
if (!fl_read(&ehdr, offset, sizeof(ehdr)))
return -1ul;
if (!IS_ELF(ehdr) || ehdr.e_ident[EI_CLASS] != ELFCLASS64) {
printf("Doesn't look like an elf64\n");
goto dump;
}
if (ehdr.e_ident[EI_DATA] != ELFDATA2LSB ||
ehdr.e_machine != EM_PPC64) {
printf("Not a ppc64le binary\n");
goto dump;
}
poff = offset + ehdr.e_phoff;
for (i = 0; i < ehdr.e_phnum; i++) {
if (!fl_read(&ph, poff, sizeof(ph)))
goto dump;
if (ph.p_type != PT_LOAD)
continue;
/* XXX Add bound checking ! */
size = ph.p_filesz;
addr = (void *)ph.p_vaddr;
off = offset + ph.p_offset;
printf("Copy segment %d (0x%x bytes) to %p\n", i, size, addr);
fl_read(addr, off, size);
poff += ehdr.e_phentsize;
}
printf("Booting from DRAM at %x\n", (unsigned int)ehdr.e_entry);
flush_cpu_icache();
return ehdr.e_entry;
dump:
printf("HDR: %02x %02x %02x %02x %02x %02x %02x %02x\n",
ehdr.e_ident[0], ehdr.e_ident[1], ehdr.e_ident[2], ehdr.e_ident[3],
ehdr.e_ident[4], ehdr.e_ident[5], ehdr.e_ident[6], ehdr.e_ident[7]);
return -1ul;
}
static void boot_sdram(void)
{
void *s = (void *)(DRAM_INIT_BASE + 0x6000);
void *d = (void *)DRAM_BASE;
int sz = (0x10000 - 0x6000);
printf("Copying payload to DRAM...\n");
memcpy(d, s, sz);
printf("Booting from DRAM...\n");
flush_cpu_icache();
}
uint64_t main(void)
{
unsigned long ftr, val;
unsigned int fl_off = 0;
bool try_flash = false;
/* Init the UART */
console_init();
printf("\n\nWelcome to Microwatt !\n\n");
/* TODO: Add core version information somewhere in syscon, possibly
* extracted from git
*/
printf(" Soc signature: %016llx\n",
(unsigned long long)readq(SYSCON_BASE + SYS_REG_SIGNATURE));
printf(" Soc features: ");
ftr = readq(SYSCON_BASE + SYS_REG_INFO);
if (ftr & SYS_REG_INFO_HAS_UART)
printf("UART ");
if (ftr & SYS_REG_INFO_HAS_DRAM)
printf("DRAM ");
if (ftr & SYS_REG_INFO_HAS_BRAM)
printf("BRAM ");
if (ftr & SYS_REG_INFO_HAS_SPI_FLASH)
printf("SPIFLASH ");
if (ftr & SYS_REG_INFO_HAS_LITEETH)
printf("ETHERNET ");
if (ftr & SYS_REG_INFO_HAS_LITESDCARD)
printf("SDCARD ");
printf("\n");
if (ftr & SYS_REG_INFO_HAS_BRAM) {
val = readq(SYSCON_BASE + SYS_REG_BRAMINFO) & SYS_REG_BRAMINFO_SIZE_MASK;
printf(" BRAM: %ld KB\n", val / 1024);
}
if (ftr & SYS_REG_INFO_HAS_DRAM) {
val = readq(SYSCON_BASE + SYS_REG_DRAMINFO) & SYS_REG_DRAMINFO_SIZE_MASK;
printf(" DRAM: %ld MB\n", val / (1024 * 1024));
val = readq(SYSCON_BASE + SYS_REG_DRAMINITINFO);
printf(" DRAM INIT: %ld KB\n", val / 1024);
}
val = readq(SYSCON_BASE + SYS_REG_CLKINFO) & SYS_REG_CLKINFO_FREQ_MASK;
printf(" CLK: %ld MHz\n", val / 1000000);
if (ftr & SYS_REG_INFO_HAS_SPI_FLASH) {
val = readq(SYSCON_BASE + SYS_REG_SPI_INFO);
try_flash = check_flash();
fl_off = val & SYS_REG_SPI_INFO_FLASH_OFF_MASK;
printf(" SPI FLASH OFF: 0x%x bytes\n", fl_off);
try_flash = true;
}
printf("\n");
if (ftr & SYS_REG_INFO_HAS_DRAM && !ddrctrl_init_done_read()) {
printf("LiteDRAM built from LiteX %s\n", LITEX_GIT_SHA1);
sdram_init();
}
val = readq(SYSCON_BASE + SYS_REG_CTRL);
writeq(val & ~SYS_REG_CTRL_ALT_RESET, SYSCON_BASE + SYS_REG_CTRL);
if (ftr & SYS_REG_INFO_HAS_BRAM) {
printf("Booting from BRAM...\n");
return 0;
}
if (try_flash) {
val = boot_flash(fl_off);
if (val != (unsigned long)-1)
return val;
}
boot_sdram();
return 0;
}
|
14f7f66cb6e869408e0def6b234923517064ec79
|
44ad9d2de0fd2113501820e814511b355979e3de
|
/tests/doc/capi/chfl_residue/name.c
|
e69b7b7bf90df393d4023a71d5f93a56aa1e7150
|
[
"GPL-1.0-or-later",
"MPL-2.0",
"BSD-3-Clause",
"MPL-1.0"
] |
permissive
|
chemfiles/chemfiles
|
eae2760c50f01d225ddbf70c6bc7e9be8bd62f65
|
501b7cbb767899aa1e2e23eb8e23787ab5bbcc3b
|
refs/heads/master
| 2023-09-01T07:15:14.741611
| 2023-08-16T09:16:29
| 2023-08-22T14:18:55
| 30,712,631
| 148
| 67
|
BSD-3-Clause
| 2023-09-07T13:58:54
| 2015-02-12T16:50:09
|
C++
|
UTF-8
|
C
| false
| false
| 477
|
c
|
name.c
|
// Chemfiles, a modern library for chemistry file reading and writing
// Copyright (C) Guillaume Fraux and contributors -- BSD license
#include <chemfiles.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
int main() {
// [example]
CHFL_RESIDUE* residue = chfl_residue("water");
char name[32] = {0};
chfl_residue_name(residue, name, sizeof(name));
assert(strcmp(name, "water") == 0);
chfl_free(residue);
// [example]
return 0;
}
|
b659e0835bb6c2c3ca20e893d5b2954b2b64d030
|
b36f34b6a24d019d624d1cc74f5b29062eef2ba4
|
/frameworks/cocos2d-x/external/chipmunk/include/chipmunk/cpShape.h
|
cc20f80927b4485c8e3adc2f2779840561e2af3d
|
[
"MIT"
] |
permissive
|
zhongfq/cocos-lua
|
f49c1639f2c9a2a7678f9ed67e58114986ac882f
|
c2cf0f36ac0f0c91fb3456b555cacd8e8587be46
|
refs/heads/main
| 2023-08-17T17:13:05.705639
| 2023-08-17T06:06:36
| 2023-08-17T06:06:36
| 192,316,318
| 165
| 63
|
MIT
| 2023-08-14T23:59:30
| 2019-06-17T09:27:37
|
C
|
UTF-8
|
C
| false
| false
| 9,272
|
h
|
cpShape.h
|
/* Copyright (c) 2013 Scott Lembcke and Howling Moon Software
*
* 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.
*/
/// @defgroup cpShape cpShape
/// The cpShape struct defines the shape of a rigid body.
/// @{
/// Point query info struct.
typedef struct cpPointQueryInfo {
/// The nearest shape, NULL if no shape was within range.
const cpShape *shape;
/// The closest point on the shape's surface. (in world space coordinates)
cpVect point;
/// The distance to the point. The distance is negative if the point is inside the shape.
cpFloat distance;
/// The gradient of the signed distance function.
/// The value should be similar to info.p/info.d, but accurate even for very small values of info.d.
cpVect gradient;
} cpPointQueryInfo;
/// Segment query info struct.
typedef struct cpSegmentQueryInfo {
/// The shape that was hit, or NULL if no collision occured.
const cpShape *shape;
/// The point of impact.
cpVect point;
/// The normal of the surface hit.
cpVect normal;
/// The normalized distance along the query segment in the range [0, 1].
cpFloat alpha;
} cpSegmentQueryInfo;
/// Fast collision filtering type that is used to determine if two objects collide before calling collision or query callbacks.
typedef struct cpShapeFilter {
/// Two objects with the same non-zero group value do not collide.
/// This is generally used to group objects in a composite object together to disable self collisions.
cpGroup group;
/// A bitmask of user definable categories that this object belongs to.
/// The category/mask combinations of both objects in a collision must agree for a collision to occur.
cpBitmask categories;
/// A bitmask of user definable category types that this object object collides with.
/// The category/mask combinations of both objects in a collision must agree for a collision to occur.
cpBitmask mask;
} cpShapeFilter;
/// Collision filter value for a shape that will collide with anything except CP_SHAPE_FILTER_NONE.
static const cpShapeFilter CP_SHAPE_FILTER_ALL = {CP_NO_GROUP, CP_ALL_CATEGORIES, CP_ALL_CATEGORIES};
/// Collision filter value for a shape that does not collide with anything.
static const cpShapeFilter CP_SHAPE_FILTER_NONE = {CP_NO_GROUP, ~CP_ALL_CATEGORIES, ~CP_ALL_CATEGORIES};
/// Create a new collision filter.
static inline cpShapeFilter
cpShapeFilterNew(cpGroup group, cpBitmask categories, cpBitmask mask)
{
cpShapeFilter filter = {group, categories, mask};
return filter;
}
/// Destroy a shape.
CP_EXPORT void cpShapeDestroy(cpShape *shape);
/// Destroy and Free a shape.
CP_EXPORT void cpShapeFree(cpShape *shape);
/// Update, cache and return the bounding box of a shape based on the body it's attached to.
CP_EXPORT cpBB cpShapeCacheBB(cpShape *shape);
/// Update, cache and return the bounding box of a shape with an explicit transformation.
CP_EXPORT cpBB cpShapeUpdate(cpShape *shape, cpTransform transform);
/// Perform a nearest point query. It finds the closest point on the surface of shape to a specific point.
/// The value returned is the distance between the points. A negative distance means the point is inside the shape.
CP_EXPORT cpFloat cpShapePointQuery(const cpShape *shape, cpVect p, cpPointQueryInfo *out);
/// Perform a segment query against a shape. @c info must be a pointer to a valid cpSegmentQueryInfo structure.
CP_EXPORT cpBool cpShapeSegmentQuery(const cpShape *shape, cpVect a, cpVect b, cpFloat radius, cpSegmentQueryInfo *info);
/// Return contact information about two shapes.
CP_EXPORT cpContactPointSet cpShapesCollide(const cpShape *a, const cpShape *b);
/// The cpSpace this body is added to.
CP_EXPORT cpSpace* cpShapeGetSpace(const cpShape *shape);
/// The cpBody this shape is connected to.
CP_EXPORT cpBody* cpShapeGetBody(const cpShape *shape);
/// Set the cpBody this shape is connected to.
/// Can only be used if the shape is not currently added to a space.
CP_EXPORT void cpShapeSetBody(cpShape *shape, cpBody *body);
/// Get the mass of the shape if you are having Chipmunk calculate mass properties for you.
cpFloat cpShapeGetMass(cpShape *shape);
/// Set the mass of this shape to have Chipmunk calculate mass properties for you.
CP_EXPORT void cpShapeSetMass(cpShape *shape, cpFloat mass);
/// Get the density of the shape if you are having Chipmunk calculate mass properties for you.
CP_EXPORT cpFloat cpShapeGetDensity(cpShape *shape);
/// Set the density of this shape to have Chipmunk calculate mass properties for you.
CP_EXPORT void cpShapeSetDensity(cpShape *shape, cpFloat density);
/// Get the calculated moment of inertia for this shape.
CP_EXPORT cpFloat cpShapeGetMoment(cpShape *shape);
/// Get the calculated area of this shape.
CP_EXPORT cpFloat cpShapeGetArea(cpShape *shape);
/// Get the centroid of this shape.
CP_EXPORT cpVect cpShapeGetCenterOfGravity(cpShape *shape);
/// Get the bounding box that contains the shape given it's current position and angle.
CP_EXPORT cpBB cpShapeGetBB(const cpShape *shape);
/// Get if the shape is set to be a sensor or not.
CP_EXPORT cpBool cpShapeGetSensor(const cpShape *shape);
/// Set if the shape is a sensor or not.
CP_EXPORT void cpShapeSetSensor(cpShape *shape, cpBool sensor);
/// Get the elasticity of this shape.
CP_EXPORT cpFloat cpShapeGetElasticity(const cpShape *shape);
/// Set the elasticity of this shape.
CP_EXPORT void cpShapeSetElasticity(cpShape *shape, cpFloat elasticity);
/// Get the friction of this shape.
CP_EXPORT cpFloat cpShapeGetFriction(const cpShape *shape);
/// Set the friction of this shape.
CP_EXPORT void cpShapeSetFriction(cpShape *shape, cpFloat friction);
/// Get the surface velocity of this shape.
CP_EXPORT cpVect cpShapeGetSurfaceVelocity(const cpShape *shape);
/// Set the surface velocity of this shape.
CP_EXPORT void cpShapeSetSurfaceVelocity(cpShape *shape, cpVect surfaceVelocity);
/// Get the user definable data pointer of this shape.
CP_EXPORT cpDataPointer cpShapeGetUserData(const cpShape *shape);
/// Set the user definable data pointer of this shape.
CP_EXPORT void cpShapeSetUserData(cpShape *shape, cpDataPointer userData);
/// Set the collision type of this shape.
CP_EXPORT cpCollisionType cpShapeGetCollisionType(const cpShape *shape);
/// Get the collision type of this shape.
CP_EXPORT void cpShapeSetCollisionType(cpShape *shape, cpCollisionType collisionType);
/// Get the collision filtering parameters of this shape.
CP_EXPORT cpShapeFilter cpShapeGetFilter(const cpShape *shape);
/// Set the collision filtering parameters of this shape.
CP_EXPORT void cpShapeSetFilter(cpShape *shape, cpShapeFilter filter);
/// @}
/// @defgroup cpCircleShape cpCircleShape
/// Allocate a circle shape.
CP_EXPORT cpCircleShape* cpCircleShapeAlloc(void);
/// Initialize a circle shape.
CP_EXPORT cpCircleShape* cpCircleShapeInit(cpCircleShape *circle, cpBody *body, cpFloat radius, cpVect offset);
/// Allocate and initialize a circle shape.
CP_EXPORT cpShape* cpCircleShapeNew(cpBody *body, cpFloat radius, cpVect offset);
/// Get the offset of a circle shape.
CP_EXPORT cpVect cpCircleShapeGetOffset(const cpShape *shape);
/// Get the radius of a circle shape.
CP_EXPORT cpFloat cpCircleShapeGetRadius(const cpShape *shape);
/// @}
/// @defgroup cpSegmentShape cpSegmentShape
/// Allocate a segment shape.
CP_EXPORT cpSegmentShape* cpSegmentShapeAlloc(void);
/// Initialize a segment shape.
CP_EXPORT cpSegmentShape* cpSegmentShapeInit(cpSegmentShape *seg, cpBody *body, cpVect a, cpVect b, cpFloat radius);
/// Allocate and initialize a segment shape.
CP_EXPORT cpShape* cpSegmentShapeNew(cpBody *body, cpVect a, cpVect b, cpFloat radius);
/// Let Chipmunk know about the geometry of adjacent segments to avoid colliding with endcaps.
CP_EXPORT void cpSegmentShapeSetNeighbors(cpShape *shape, cpVect prev, cpVect next);
/// Get the first endpoint of a segment shape.
CP_EXPORT cpVect cpSegmentShapeGetA(const cpShape *shape);
/// Get the second endpoint of a segment shape.
CP_EXPORT cpVect cpSegmentShapeGetB(const cpShape *shape);
/// Get the normal of a segment shape.
CP_EXPORT cpVect cpSegmentShapeGetNormal(const cpShape *shape);
/// Get the first endpoint of a segment shape.
CP_EXPORT cpFloat cpSegmentShapeGetRadius(const cpShape *shape);
/// @}
|
977d691a6985523d6d21f558421c041168d6c5e0
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/weston/src/compositor/text-backend.c
|
722dcb2c1c4a86118db9fdedc1ade6f4542bf757
|
[
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"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
| 29,760
|
c
|
text-backend.c
|
/*
* Copyright © 2012 Openismus GmbH
* Copyright © 2012 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.
*/
#include "config.h"
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <libweston/libweston.h>
#include "weston.h"
#include "text-input-unstable-v1-server-protocol.h"
#include "input-method-unstable-v1-server-protocol.h"
#include "shared/helpers.h"
#include "shared/timespec-util.h"
struct text_input_manager;
struct input_method;
struct input_method_context;
struct text_backend;
struct text_input {
struct wl_resource *resource;
struct weston_compositor *ec;
struct wl_list input_methods;
struct weston_surface *surface;
pixman_box32_t cursor_rectangle;
bool input_panel_visible;
struct text_input_manager *manager;
};
struct text_input_manager {
struct wl_global *text_input_manager_global;
struct wl_listener destroy_listener;
struct text_input *current_text_input;
struct weston_compositor *ec;
};
struct input_method {
struct wl_resource *input_method_binding;
struct wl_global *input_method_global;
struct wl_listener destroy_listener;
struct weston_seat *seat;
struct text_input *input;
struct wl_list link;
struct wl_listener keyboard_focus_listener;
bool focus_listener_initialized;
struct input_method_context *context;
struct text_backend *text_backend;
};
struct input_method_context {
struct wl_resource *resource;
struct text_input *input;
struct input_method *input_method;
struct wl_resource *keyboard;
};
struct text_backend {
struct weston_compositor *compositor;
struct {
char *path;
struct wl_client *client;
unsigned deathcount;
struct timespec deathstamp;
} input_method;
struct wl_listener client_listener;
struct wl_listener seat_created_listener;
};
static void
input_method_context_create(struct text_input *input,
struct input_method *input_method);
static void
input_method_context_end_keyboard_grab(struct input_method_context *context);
static void
input_method_init_seat(struct weston_seat *seat);
static void
deactivate_input_method(struct input_method *input_method)
{
struct text_input *text_input = input_method->input;
struct weston_compositor *ec = text_input->ec;
if (input_method->context && input_method->input_method_binding) {
input_method_context_end_keyboard_grab(input_method->context);
zwp_input_method_v1_send_deactivate(
input_method->input_method_binding,
input_method->context->resource);
input_method->context->input = NULL;
}
wl_list_remove(&input_method->link);
input_method->input = NULL;
input_method->context = NULL;
if (wl_list_empty(&text_input->input_methods) &&
text_input->input_panel_visible &&
text_input->manager->current_text_input == text_input) {
wl_signal_emit(&ec->hide_input_panel_signal, ec);
text_input->input_panel_visible = false;
}
if (text_input->manager->current_text_input == text_input)
text_input->manager->current_text_input = NULL;
zwp_text_input_v1_send_leave(text_input->resource);
}
static void
destroy_text_input(struct wl_resource *resource)
{
struct text_input *text_input = wl_resource_get_user_data(resource);
struct input_method *input_method, *next;
wl_list_for_each_safe(input_method, next,
&text_input->input_methods, link)
deactivate_input_method(input_method);
free(text_input);
}
static void
text_input_set_surrounding_text(struct wl_client *client,
struct wl_resource *resource,
const char *text,
uint32_t cursor,
uint32_t anchor)
{
struct text_input *text_input = wl_resource_get_user_data(resource);
struct input_method *input_method, *next;
wl_list_for_each_safe(input_method, next,
&text_input->input_methods, link) {
if (!input_method->context)
continue;
zwp_input_method_context_v1_send_surrounding_text(
input_method->context->resource, text, cursor, anchor);
}
}
static void
text_input_activate(struct wl_client *client,
struct wl_resource *resource,
struct wl_resource *seat,
struct wl_resource *surface)
{
struct text_input *text_input = wl_resource_get_user_data(resource);
struct weston_seat *weston_seat = wl_resource_get_user_data(seat);
struct input_method *input_method;
struct weston_compositor *ec = text_input->ec;
struct text_input *current;
if (!weston_seat)
return;
input_method = weston_seat->input_method;
if (input_method->input == text_input)
return;
if (input_method->input)
deactivate_input_method(input_method);
input_method->input = text_input;
wl_list_insert(&text_input->input_methods, &input_method->link);
input_method_init_seat(weston_seat);
text_input->surface = wl_resource_get_user_data(surface);
input_method_context_create(text_input, input_method);
current = text_input->manager->current_text_input;
if (current && current != text_input) {
current->input_panel_visible = false;
wl_signal_emit(&ec->hide_input_panel_signal, ec);
}
if (text_input->input_panel_visible) {
wl_signal_emit(&ec->show_input_panel_signal,
text_input->surface);
wl_signal_emit(&ec->update_input_panel_signal,
&text_input->cursor_rectangle);
}
text_input->manager->current_text_input = text_input;
zwp_text_input_v1_send_enter(text_input->resource,
text_input->surface->resource);
}
static void
text_input_deactivate(struct wl_client *client,
struct wl_resource *resource,
struct wl_resource *seat)
{
struct weston_seat *weston_seat = wl_resource_get_user_data(seat);
if (weston_seat && weston_seat->input_method->input)
deactivate_input_method(weston_seat->input_method);
}
static void
text_input_reset(struct wl_client *client,
struct wl_resource *resource)
{
struct text_input *text_input = wl_resource_get_user_data(resource);
struct input_method *input_method, *next;
wl_list_for_each_safe(input_method, next,
&text_input->input_methods, link) {
if (!input_method->context)
continue;
zwp_input_method_context_v1_send_reset(
input_method->context->resource);
}
}
static void
text_input_set_cursor_rectangle(struct wl_client *client,
struct wl_resource *resource,
int32_t x,
int32_t y,
int32_t width,
int32_t height)
{
struct text_input *text_input = wl_resource_get_user_data(resource);
struct weston_compositor *ec = text_input->ec;
text_input->cursor_rectangle.x1 = x;
text_input->cursor_rectangle.y1 = y;
text_input->cursor_rectangle.x2 = x + width;
text_input->cursor_rectangle.y2 = y + height;
wl_signal_emit(&ec->update_input_panel_signal,
&text_input->cursor_rectangle);
}
static void
text_input_set_content_type(struct wl_client *client,
struct wl_resource *resource,
uint32_t hint,
uint32_t purpose)
{
struct text_input *text_input = wl_resource_get_user_data(resource);
struct input_method *input_method, *next;
wl_list_for_each_safe(input_method, next,
&text_input->input_methods, link) {
if (!input_method->context)
continue;
zwp_input_method_context_v1_send_content_type(
input_method->context->resource, hint, purpose);
}
}
static void
text_input_invoke_action(struct wl_client *client,
struct wl_resource *resource,
uint32_t button,
uint32_t index)
{
struct text_input *text_input = wl_resource_get_user_data(resource);
struct input_method *input_method, *next;
wl_list_for_each_safe(input_method, next,
&text_input->input_methods, link) {
if (!input_method->context)
continue;
zwp_input_method_context_v1_send_invoke_action(
input_method->context->resource, button, index);
}
}
static void
text_input_commit_state(struct wl_client *client,
struct wl_resource *resource,
uint32_t serial)
{
struct text_input *text_input = wl_resource_get_user_data(resource);
struct input_method *input_method, *next;
wl_list_for_each_safe(input_method, next,
&text_input->input_methods, link) {
if (!input_method->context)
continue;
zwp_input_method_context_v1_send_commit_state(
input_method->context->resource, serial);
}
}
static void
text_input_show_input_panel(struct wl_client *client,
struct wl_resource *resource)
{
struct text_input *text_input = wl_resource_get_user_data(resource);
struct weston_compositor *ec = text_input->ec;
text_input->input_panel_visible = true;
if (!wl_list_empty(&text_input->input_methods) &&
text_input == text_input->manager->current_text_input) {
wl_signal_emit(&ec->show_input_panel_signal,
text_input->surface);
wl_signal_emit(&ec->update_input_panel_signal,
&text_input->cursor_rectangle);
}
}
static void
text_input_hide_input_panel(struct wl_client *client,
struct wl_resource *resource)
{
struct text_input *text_input = wl_resource_get_user_data(resource);
struct weston_compositor *ec = text_input->ec;
text_input->input_panel_visible = false;
if (!wl_list_empty(&text_input->input_methods) &&
text_input == text_input->manager->current_text_input)
wl_signal_emit(&ec->hide_input_panel_signal, ec);
}
static void
text_input_set_preferred_language(struct wl_client *client,
struct wl_resource *resource,
const char *language)
{
struct text_input *text_input = wl_resource_get_user_data(resource);
struct input_method *input_method, *next;
wl_list_for_each_safe(input_method, next,
&text_input->input_methods, link) {
if (!input_method->context)
continue;
zwp_input_method_context_v1_send_preferred_language(
input_method->context->resource, language);
}
}
static const struct zwp_text_input_v1_interface text_input_implementation = {
text_input_activate,
text_input_deactivate,
text_input_show_input_panel,
text_input_hide_input_panel,
text_input_reset,
text_input_set_surrounding_text,
text_input_set_content_type,
text_input_set_cursor_rectangle,
text_input_set_preferred_language,
text_input_commit_state,
text_input_invoke_action
};
static void text_input_manager_create_text_input(struct wl_client *client,
struct wl_resource *resource,
uint32_t id)
{
struct text_input_manager *text_input_manager =
wl_resource_get_user_data(resource);
struct text_input *text_input;
text_input = zalloc(sizeof *text_input);
if (text_input == NULL)
return;
text_input->resource =
wl_resource_create(client, &zwp_text_input_v1_interface, 1, id);
wl_resource_set_implementation(text_input->resource,
&text_input_implementation,
text_input, destroy_text_input);
text_input->ec = text_input_manager->ec;
text_input->manager = text_input_manager;
wl_list_init(&text_input->input_methods);
};
static const struct zwp_text_input_manager_v1_interface manager_implementation = {
text_input_manager_create_text_input
};
static void
bind_text_input_manager(struct wl_client *client,
void *data,
uint32_t version,
uint32_t id)
{
struct text_input_manager *text_input_manager = data;
struct wl_resource *resource;
/* No checking for duplicate binding necessary. */
resource =
wl_resource_create(client,
&zwp_text_input_manager_v1_interface, 1, id);
if (resource)
wl_resource_set_implementation(resource,
&manager_implementation,
text_input_manager, NULL);
}
static void
text_input_manager_notifier_destroy(struct wl_listener *listener, void *data)
{
struct text_input_manager *text_input_manager =
container_of(listener,
struct text_input_manager,
destroy_listener);
wl_list_remove(&text_input_manager->destroy_listener.link);
wl_global_destroy(text_input_manager->text_input_manager_global);
free(text_input_manager);
}
static void
text_input_manager_create(struct weston_compositor *ec)
{
struct text_input_manager *text_input_manager;
text_input_manager = zalloc(sizeof *text_input_manager);
if (text_input_manager == NULL)
return;
text_input_manager->ec = ec;
text_input_manager->text_input_manager_global =
wl_global_create(ec->wl_display,
&zwp_text_input_manager_v1_interface, 1,
text_input_manager, bind_text_input_manager);
text_input_manager->destroy_listener.notify =
text_input_manager_notifier_destroy;
wl_signal_add(&ec->destroy_signal,
&text_input_manager->destroy_listener);
}
static void
input_method_context_destroy(struct wl_client *client,
struct wl_resource *resource)
{
wl_resource_destroy(resource);
}
static void
input_method_context_commit_string(struct wl_client *client,
struct wl_resource *resource,
uint32_t serial,
const char *text)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
if (context->input)
zwp_text_input_v1_send_commit_string(context->input->resource,
serial, text);
}
static void
input_method_context_preedit_string(struct wl_client *client,
struct wl_resource *resource,
uint32_t serial,
const char *text,
const char *commit)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
if (context->input)
zwp_text_input_v1_send_preedit_string(context->input->resource,
serial, text, commit);
}
static void
input_method_context_preedit_styling(struct wl_client *client,
struct wl_resource *resource,
uint32_t index,
uint32_t length,
uint32_t style)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
if (context->input)
zwp_text_input_v1_send_preedit_styling(context->input->resource,
index, length, style);
}
static void
input_method_context_preedit_cursor(struct wl_client *client,
struct wl_resource *resource,
int32_t cursor)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
if (context->input)
zwp_text_input_v1_send_preedit_cursor(context->input->resource,
cursor);
}
static void
input_method_context_delete_surrounding_text(struct wl_client *client,
struct wl_resource *resource,
int32_t index,
uint32_t length)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
if (context->input)
zwp_text_input_v1_send_delete_surrounding_text(
context->input->resource, index, length);
}
static void
input_method_context_cursor_position(struct wl_client *client,
struct wl_resource *resource,
int32_t index,
int32_t anchor)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
if (context->input)
zwp_text_input_v1_send_cursor_position(context->input->resource,
index, anchor);
}
static void
input_method_context_modifiers_map(struct wl_client *client,
struct wl_resource *resource,
struct wl_array *map)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
if (context->input)
zwp_text_input_v1_send_modifiers_map(context->input->resource,
map);
}
static void
input_method_context_keysym(struct wl_client *client,
struct wl_resource *resource,
uint32_t serial,
uint32_t time,
uint32_t sym,
uint32_t state,
uint32_t modifiers)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
if (context->input)
zwp_text_input_v1_send_keysym(context->input->resource,
serial, time,
sym, state, modifiers);
}
static void
unbind_keyboard(struct wl_resource *resource)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
input_method_context_end_keyboard_grab(context);
context->keyboard = NULL;
}
static void
input_method_context_grab_key(struct weston_keyboard_grab *grab,
const struct timespec *time, uint32_t key,
uint32_t state_w)
{
struct weston_keyboard *keyboard = grab->keyboard;
struct wl_display *display;
uint32_t serial;
uint32_t msecs;
if (!keyboard->input_method_resource)
return;
display = wl_client_get_display(
wl_resource_get_client(keyboard->input_method_resource));
serial = wl_display_next_serial(display);
msecs = timespec_to_msec(time);
wl_keyboard_send_key(keyboard->input_method_resource,
serial, msecs, key, state_w);
}
static void
input_method_context_grab_modifier(struct weston_keyboard_grab *grab,
uint32_t serial,
uint32_t mods_depressed,
uint32_t mods_latched,
uint32_t mods_locked,
uint32_t group)
{
struct weston_keyboard *keyboard = grab->keyboard;
if (!keyboard->input_method_resource)
return;
wl_keyboard_send_modifiers(keyboard->input_method_resource,
serial, mods_depressed, mods_latched,
mods_locked, group);
}
static void
input_method_context_grab_cancel(struct weston_keyboard_grab *grab)
{
weston_keyboard_end_grab(grab->keyboard);
}
static const struct weston_keyboard_grab_interface input_method_context_grab = {
input_method_context_grab_key,
input_method_context_grab_modifier,
input_method_context_grab_cancel,
};
static void
input_method_context_grab_keyboard(struct wl_client *client,
struct wl_resource *resource,
uint32_t id)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
struct wl_resource *cr;
struct weston_seat *seat = context->input_method->seat;
struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
cr = wl_resource_create(client, &wl_keyboard_interface, 1, id);
wl_resource_set_implementation(cr, NULL, context, unbind_keyboard);
context->keyboard = cr;
weston_keyboard_send_keymap(keyboard, cr);
if (keyboard->grab != &keyboard->default_grab) {
weston_keyboard_end_grab(keyboard);
}
weston_keyboard_start_grab(keyboard, &keyboard->input_method_grab);
keyboard->input_method_resource = cr;
}
static void
input_method_context_key(struct wl_client *client,
struct wl_resource *resource,
uint32_t serial,
uint32_t time,
uint32_t key,
uint32_t state_w)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
struct weston_seat *seat = context->input_method->seat;
struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
struct weston_keyboard_grab *default_grab = &keyboard->default_grab;
struct timespec ts;
timespec_from_msec(&ts, time);
default_grab->interface->key(default_grab, &ts, key, state_w);
}
static void
input_method_context_modifiers(struct wl_client *client,
struct wl_resource *resource,
uint32_t serial,
uint32_t mods_depressed,
uint32_t mods_latched,
uint32_t mods_locked,
uint32_t group)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
struct weston_seat *seat = context->input_method->seat;
struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
struct weston_keyboard_grab *default_grab = &keyboard->default_grab;
default_grab->interface->modifiers(default_grab,
serial, mods_depressed,
mods_latched, mods_locked,
group);
}
static void
input_method_context_language(struct wl_client *client,
struct wl_resource *resource,
uint32_t serial,
const char *language)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
if (context->input)
zwp_text_input_v1_send_language(context->input->resource,
serial, language);
}
static void
input_method_context_text_direction(struct wl_client *client,
struct wl_resource *resource,
uint32_t serial,
uint32_t direction)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
if (context->input)
zwp_text_input_v1_send_text_direction(context->input->resource,
serial, direction);
}
static const struct zwp_input_method_context_v1_interface context_implementation = {
input_method_context_destroy,
input_method_context_commit_string,
input_method_context_preedit_string,
input_method_context_preedit_styling,
input_method_context_preedit_cursor,
input_method_context_delete_surrounding_text,
input_method_context_cursor_position,
input_method_context_modifiers_map,
input_method_context_keysym,
input_method_context_grab_keyboard,
input_method_context_key,
input_method_context_modifiers,
input_method_context_language,
input_method_context_text_direction
};
static void
destroy_input_method_context(struct wl_resource *resource)
{
struct input_method_context *context =
wl_resource_get_user_data(resource);
if (context->keyboard)
wl_resource_destroy(context->keyboard);
if (context->input_method && context->input_method->context == context)
context->input_method->context = NULL;
free(context);
}
static void
input_method_context_create(struct text_input *input,
struct input_method *input_method)
{
struct input_method_context *context;
struct wl_resource *binding;
if (!input_method->input_method_binding)
return;
context = zalloc(sizeof *context);
if (context == NULL)
return;
binding = input_method->input_method_binding;
context->resource =
wl_resource_create(wl_resource_get_client(binding),
&zwp_input_method_context_v1_interface,
1, 0);
wl_resource_set_implementation(context->resource,
&context_implementation,
context, destroy_input_method_context);
context->input = input;
context->input_method = input_method;
input_method->context = context;
zwp_input_method_v1_send_activate(binding, context->resource);
}
static void
input_method_context_end_keyboard_grab(struct input_method_context *context)
{
struct weston_keyboard_grab *grab;
struct weston_keyboard *keyboard;
keyboard = weston_seat_get_keyboard(context->input_method->seat);
if (!keyboard)
return;
grab = &keyboard->input_method_grab;
keyboard = grab->keyboard;
if (!keyboard)
return;
if (keyboard->grab == grab)
weston_keyboard_end_grab(keyboard);
keyboard->input_method_resource = NULL;
}
static void
unbind_input_method(struct wl_resource *resource)
{
struct input_method *input_method = wl_resource_get_user_data(resource);
input_method->input_method_binding = NULL;
input_method->context = NULL;
}
static void
bind_input_method(struct wl_client *client,
void *data,
uint32_t version,
uint32_t id)
{
struct input_method *input_method = data;
struct text_backend *text_backend = input_method->text_backend;
struct wl_resource *resource;
resource =
wl_resource_create(client,
&zwp_input_method_v1_interface, 1, id);
if (input_method->input_method_binding != NULL) {
wl_resource_post_error(resource,
WL_DISPLAY_ERROR_INVALID_OBJECT,
"interface object already bound");
return;
}
if (text_backend->input_method.client != client) {
wl_resource_post_error(resource,
WL_DISPLAY_ERROR_INVALID_OBJECT,
"permission to bind "
"input_method denied");
return;
}
wl_resource_set_implementation(resource, NULL, input_method,
unbind_input_method);
input_method->input_method_binding = resource;
}
static void
input_method_notifier_destroy(struct wl_listener *listener, void *data)
{
struct input_method *input_method =
container_of(listener, struct input_method, destroy_listener);
if (input_method->input)
deactivate_input_method(input_method);
wl_global_destroy(input_method->input_method_global);
wl_list_remove(&input_method->destroy_listener.link);
free(input_method);
}
static void
handle_keyboard_focus(struct wl_listener *listener, void *data)
{
struct weston_keyboard *keyboard = data;
struct input_method *input_method =
container_of(listener, struct input_method,
keyboard_focus_listener);
struct weston_surface *surface = keyboard->focus;
if (!input_method->input)
return;
if (!surface || input_method->input->surface != surface)
deactivate_input_method(input_method);
}
static void
input_method_init_seat(struct weston_seat *seat)
{
struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
if (seat->input_method->focus_listener_initialized)
return;
if (keyboard) {
seat->input_method->keyboard_focus_listener.notify =
handle_keyboard_focus;
wl_signal_add(&keyboard->focus_signal,
&seat->input_method->keyboard_focus_listener);
keyboard->input_method_grab.interface =
&input_method_context_grab;
}
seat->input_method->focus_listener_initialized = true;
}
static void launch_input_method(struct text_backend *text_backend);
static void
respawn_input_method_process(struct text_backend *text_backend)
{
struct timespec time;
int64_t tdiff;
/* if input_method dies more than 5 times in 10 seconds, give up */
weston_compositor_get_time(&time);
tdiff = timespec_sub_to_msec(&time,
&text_backend->input_method.deathstamp);
if (tdiff > 10000) {
text_backend->input_method.deathstamp = time;
text_backend->input_method.deathcount = 0;
}
text_backend->input_method.deathcount++;
if (text_backend->input_method.deathcount > 5) {
weston_log("input_method disconnected, giving up.\n");
return;
}
weston_log("input_method disconnected, respawning...\n");
launch_input_method(text_backend);
}
static void
input_method_client_notifier(struct wl_listener *listener, void *data)
{
struct text_backend *text_backend;
text_backend = container_of(listener, struct text_backend,
client_listener);
text_backend->input_method.client = NULL;
respawn_input_method_process(text_backend);
}
static void
launch_input_method(struct text_backend *text_backend)
{
if (!text_backend->input_method.path)
return;
if (strcmp(text_backend->input_method.path, "") == 0)
return;
text_backend->input_method.client =
weston_client_start(text_backend->compositor,
text_backend->input_method.path);
if (!text_backend->input_method.client) {
weston_log("not able to start %s\n",
text_backend->input_method.path);
return;
}
text_backend->client_listener.notify = input_method_client_notifier;
wl_client_add_destroy_listener(text_backend->input_method.client,
&text_backend->client_listener);
}
static void
text_backend_seat_created(struct text_backend *text_backend,
struct weston_seat *seat)
{
struct input_method *input_method;
struct weston_compositor *ec = seat->compositor;
input_method = zalloc(sizeof *input_method);
if (input_method == NULL)
return;
input_method->seat = seat;
input_method->input = NULL;
input_method->focus_listener_initialized = false;
input_method->context = NULL;
input_method->text_backend = text_backend;
input_method->input_method_global =
wl_global_create(ec->wl_display,
&zwp_input_method_v1_interface, 1,
input_method, bind_input_method);
input_method->destroy_listener.notify = input_method_notifier_destroy;
wl_signal_add(&seat->destroy_signal, &input_method->destroy_listener);
seat->input_method = input_method;
}
static void
handle_seat_created(struct wl_listener *listener, void *data)
{
struct weston_seat *seat = data;
struct text_backend *text_backend =
container_of(listener, struct text_backend,
seat_created_listener);
text_backend_seat_created(text_backend, seat);
}
static void
text_backend_configuration(struct text_backend *text_backend)
{
struct weston_config *config = wet_get_config(text_backend->compositor);
struct weston_config_section *section;
char *client;
section = weston_config_get_section(config,
"input-method", NULL, NULL);
client = wet_get_libexec_path("weston-keyboard");
weston_config_section_get_string(section, "path",
&text_backend->input_method.path,
client);
free(client);
}
WL_EXPORT void
text_backend_destroy(struct text_backend *text_backend)
{
wl_list_remove(&text_backend->seat_created_listener.link);
if (text_backend->input_method.client) {
/* disable respawn */
wl_list_remove(&text_backend->client_listener.link);
wl_client_destroy(text_backend->input_method.client);
}
free(text_backend->input_method.path);
free(text_backend);
}
WL_EXPORT struct text_backend *
text_backend_init(struct weston_compositor *ec)
{
struct text_backend *text_backend;
struct weston_seat *seat;
text_backend = zalloc(sizeof(*text_backend));
if (text_backend == NULL)
return NULL;
text_backend->compositor = ec;
text_backend_configuration(text_backend);
wl_list_for_each(seat, &ec->seat_list, link)
text_backend_seat_created(text_backend, seat);
text_backend->seat_created_listener.notify = handle_seat_created;
wl_signal_add(&ec->seat_created_signal,
&text_backend->seat_created_listener);
text_input_manager_create(ec);
launch_input_method(text_backend);
return text_backend;
}
|
86f7df108d98e653e6ab968719d2056054c76a72
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/src/world/area_iwa/iwa_02/iwa_02_2_entity.c
|
b737531eb48bf0b302199697853307a72228b3ed
|
[] |
no_license
|
pmret/papermario
|
8b514b19653cef8d6145e47499b3636b8c474a37
|
9774b26d93f1045dd2a67e502b6efc9599fb6c31
|
refs/heads/main
| 2023-08-31T07:09:48.951514
| 2023-08-21T18:07:08
| 2023-08-21T18:07:08
| 287,151,133
| 904
| 139
| null | 2023-09-14T02:44:23
| 2020-08-13T01:22:57
|
C
|
UTF-8
|
C
| false
| false
| 494
|
c
|
iwa_02_2_entity.c
|
#include "iwa_02.h"
#include "entity.h"
EvtScript N(EVS_MakeEntities) = {
EVT_CALL(MakeEntity, EVT_PTR(Entity_ArrowSign), 64, 0, 95, 0, 120, MAKE_ENTITY_END)
EVT_CALL(MakeEntity, EVT_PTR(Entity_ArrowSign), 307, 67, 99, 0, 120, MAKE_ENTITY_END)
EVT_CALL(MakeEntity, EVT_PTR(Entity_ArrowSign), 700, 238, 15, 0, 90, MAKE_ENTITY_END)
EVT_CALL(MakeItemEntity, ITEM_STAR_PIECE, 35, 167, 120, ITEM_SPAWN_MODE_FIXED_NEVER_VANISH, GF_IWA02_Item_StarPiece)
EVT_RETURN
EVT_END
};
|
58d67f8bdb3e6035a375088effae55466bdff508
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/usr.bin/tmux/style.c
|
cb507c25372b2bbb578dca74aac8b593aee7d50b
|
[] |
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
| 10,758
|
c
|
style.c
|
/* $OpenBSD: style.c,v 1.33 2023/08/17 14:10:28 nicm Exp $ */
/*
* Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
* Copyright (c) 2014 Tiago Cunha <tcunha@users.sourceforge.net>
*
* 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 MIND, 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 <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "tmux.h"
/* Mask for bits not included in style. */
#define STYLE_ATTR_MASK (~0)
/* Default style. */
static struct style style_default = {
{ { { ' ' }, 0, 1, 1 }, 0, 0, 8, 8, 0, 0 },
0,
8,
STYLE_ALIGN_DEFAULT,
STYLE_LIST_OFF,
STYLE_RANGE_NONE, 0, "",
STYLE_DEFAULT_BASE
};
/* Set range string. */
static void
style_set_range_string(struct style *sy, const char *s)
{
strlcpy(sy->range_string, s, sizeof sy->range_string);
}
/*
* Parse an embedded style of the form "fg=colour,bg=colour,bright,...". Note
* that this adds onto the given style, so it must have been initialized
* already.
*/
int
style_parse(struct style *sy, const struct grid_cell *base, const char *in)
{
struct style saved;
const char delimiters[] = " ,\n", *cp;
char tmp[256], *found;
int value;
size_t end;
if (*in == '\0')
return (0);
style_copy(&saved, sy);
log_debug("%s: %s", __func__, in);
do {
while (*in != '\0' && strchr(delimiters, *in) != NULL)
in++;
if (*in == '\0')
break;
end = strcspn(in, delimiters);
if (end > (sizeof tmp) - 1)
goto error;
memcpy(tmp, in, end);
tmp[end] = '\0';
log_debug("%s: %s", __func__, tmp);
if (strcasecmp(tmp, "default") == 0) {
sy->gc.fg = base->fg;
sy->gc.bg = base->bg;
sy->gc.us = base->us;
sy->gc.attr = base->attr;
sy->gc.flags = base->flags;
} else if (strcasecmp(tmp, "ignore") == 0)
sy->ignore = 1;
else if (strcasecmp(tmp, "noignore") == 0)
sy->ignore = 0;
else if (strcasecmp(tmp, "push-default") == 0)
sy->default_type = STYLE_DEFAULT_PUSH;
else if (strcasecmp(tmp, "pop-default") == 0)
sy->default_type = STYLE_DEFAULT_POP;
else if (strcasecmp(tmp, "nolist") == 0)
sy->list = STYLE_LIST_OFF;
else if (strncasecmp(tmp, "list=", 5) == 0) {
if (strcasecmp(tmp + 5, "on") == 0)
sy->list = STYLE_LIST_ON;
else if (strcasecmp(tmp + 5, "focus") == 0)
sy->list = STYLE_LIST_FOCUS;
else if (strcasecmp(tmp + 5, "left-marker") == 0)
sy->list = STYLE_LIST_LEFT_MARKER;
else if (strcasecmp(tmp + 5, "right-marker") == 0)
sy->list = STYLE_LIST_RIGHT_MARKER;
else
goto error;
} else if (strcasecmp(tmp, "norange") == 0) {
sy->range_type = style_default.range_type;
sy->range_argument = style_default.range_type;
strlcpy(sy->range_string, style_default.range_string,
sizeof sy->range_string);
} else if (end > 6 && strncasecmp(tmp, "range=", 6) == 0) {
found = strchr(tmp + 6, '|');
if (found != NULL) {
*found++ = '\0';
if (*found == '\0')
goto error;
}
if (strcasecmp(tmp + 6, "left") == 0) {
if (found != NULL)
goto error;
sy->range_type = STYLE_RANGE_LEFT;
sy->range_argument = 0;
style_set_range_string(sy, "");
} else if (strcasecmp(tmp + 6, "right") == 0) {
if (found != NULL)
goto error;
sy->range_type = STYLE_RANGE_RIGHT;
sy->range_argument = 0;
style_set_range_string(sy, "");
} else if (strcasecmp(tmp + 6, "pane") == 0) {
if (found == NULL)
goto error;
if (*found != '%' || found[1] == '\0')
goto error;
for (cp = found + 1; *cp != '\0'; cp++) {
if (!isdigit((u_char)*cp))
goto error;
}
sy->range_type = STYLE_RANGE_PANE;
sy->range_argument = atoi(found + 1);
style_set_range_string(sy, "");
} else if (strcasecmp(tmp + 6, "window") == 0) {
if (found == NULL)
goto error;
for (cp = found; *cp != '\0'; cp++) {
if (!isdigit((u_char)*cp))
goto error;
}
sy->range_type = STYLE_RANGE_WINDOW;
sy->range_argument = atoi(found);
style_set_range_string(sy, "");
} else if (strcasecmp(tmp + 6, "session") == 0) {
if (found == NULL)
goto error;
if (*found != '$' || found[1] == '\0')
goto error;
for (cp = found + 1; *cp != '\0'; cp++) {
if (!isdigit((u_char)*cp))
goto error;
}
sy->range_type = STYLE_RANGE_SESSION;
sy->range_argument = atoi(found + 1);
style_set_range_string(sy, "");
} else if (strcasecmp(tmp + 6, "user") == 0) {
if (found == NULL)
goto error;
sy->range_type = STYLE_RANGE_USER;
sy->range_argument = 0;
style_set_range_string(sy, found);
}
} else if (strcasecmp(tmp, "noalign") == 0)
sy->align = style_default.align;
else if (end > 6 && strncasecmp(tmp, "align=", 6) == 0) {
if (strcasecmp(tmp + 6, "left") == 0)
sy->align = STYLE_ALIGN_LEFT;
else if (strcasecmp(tmp + 6, "centre") == 0)
sy->align = STYLE_ALIGN_CENTRE;
else if (strcasecmp(tmp + 6, "right") == 0)
sy->align = STYLE_ALIGN_RIGHT;
else if (strcasecmp(tmp + 6, "absolute-centre") == 0)
sy->align = STYLE_ALIGN_ABSOLUTE_CENTRE;
else
goto error;
} else if (end > 5 && strncasecmp(tmp, "fill=", 5) == 0) {
if ((value = colour_fromstring(tmp + 5)) == -1)
goto error;
sy->fill = value;
} else if (end > 3 && strncasecmp(tmp + 1, "g=", 2) == 0) {
if ((value = colour_fromstring(tmp + 3)) == -1)
goto error;
if (*in == 'f' || *in == 'F') {
if (value != 8)
sy->gc.fg = value;
else
sy->gc.fg = base->fg;
} else if (*in == 'b' || *in == 'B') {
if (value != 8)
sy->gc.bg = value;
else
sy->gc.bg = base->bg;
} else
goto error;
} else if (end > 3 && strncasecmp(tmp, "us=", 3) == 0) {
if ((value = colour_fromstring(tmp + 3)) == -1)
goto error;
if (value != 8)
sy->gc.us = value;
else
sy->gc.us = base->us;
} else if (strcasecmp(tmp, "none") == 0)
sy->gc.attr = 0;
else if (end > 2 && strncasecmp(tmp, "no", 2) == 0) {
if ((value = attributes_fromstring(tmp + 2)) == -1)
goto error;
sy->gc.attr &= ~value;
} else {
if ((value = attributes_fromstring(tmp)) == -1)
goto error;
sy->gc.attr |= value;
}
in += end + strspn(in + end, delimiters);
} while (*in != '\0');
return (0);
error:
style_copy(sy, &saved);
return (-1);
}
/* Convert style to a string. */
const char *
style_tostring(struct style *sy)
{
struct grid_cell *gc = &sy->gc;
int off = 0;
const char *comma = "", *tmp = "";
static char s[256];
char b[16];
*s = '\0';
if (sy->list != STYLE_LIST_OFF) {
if (sy->list == STYLE_LIST_ON)
tmp = "on";
else if (sy->list == STYLE_LIST_FOCUS)
tmp = "focus";
else if (sy->list == STYLE_LIST_LEFT_MARKER)
tmp = "left-marker";
else if (sy->list == STYLE_LIST_RIGHT_MARKER)
tmp = "right-marker";
off += xsnprintf(s + off, sizeof s - off, "%slist=%s", comma,
tmp);
comma = ",";
}
if (sy->range_type != STYLE_RANGE_NONE) {
if (sy->range_type == STYLE_RANGE_LEFT)
tmp = "left";
else if (sy->range_type == STYLE_RANGE_RIGHT)
tmp = "right";
else if (sy->range_type == STYLE_RANGE_PANE) {
snprintf(b, sizeof b, "pane|%%%u", sy->range_argument);
tmp = b;
} else if (sy->range_type == STYLE_RANGE_WINDOW) {
snprintf(b, sizeof b, "window|%u", sy->range_argument);
tmp = b;
} else if (sy->range_type == STYLE_RANGE_SESSION) {
snprintf(b, sizeof b, "session|$%u",
sy->range_argument);
tmp = b;
} else if (sy->range_type == STYLE_RANGE_USER) {
snprintf(b, sizeof b, "user|%s", sy->range_string);
tmp = b;
}
off += xsnprintf(s + off, sizeof s - off, "%srange=%s", comma,
tmp);
comma = ",";
}
if (sy->align != STYLE_ALIGN_DEFAULT) {
if (sy->align == STYLE_ALIGN_LEFT)
tmp = "left";
else if (sy->align == STYLE_ALIGN_CENTRE)
tmp = "centre";
else if (sy->align == STYLE_ALIGN_RIGHT)
tmp = "right";
else if (sy->align == STYLE_ALIGN_ABSOLUTE_CENTRE)
tmp = "absolute-centre";
off += xsnprintf(s + off, sizeof s - off, "%salign=%s", comma,
tmp);
comma = ",";
}
if (sy->default_type != STYLE_DEFAULT_BASE) {
if (sy->default_type == STYLE_DEFAULT_PUSH)
tmp = "push-default";
else if (sy->default_type == STYLE_DEFAULT_POP)
tmp = "pop-default";
off += xsnprintf(s + off, sizeof s - off, "%s%s", comma, tmp);
comma = ",";
}
if (sy->fill != 8) {
off += xsnprintf(s + off, sizeof s - off, "%sfill=%s", comma,
colour_tostring(sy->fill));
comma = ",";
}
if (gc->fg != 8) {
off += xsnprintf(s + off, sizeof s - off, "%sfg=%s", comma,
colour_tostring(gc->fg));
comma = ",";
}
if (gc->bg != 8) {
off += xsnprintf(s + off, sizeof s - off, "%sbg=%s", comma,
colour_tostring(gc->bg));
comma = ",";
}
if (gc->us != 8) {
off += xsnprintf(s + off, sizeof s - off, "%sus=%s", comma,
colour_tostring(gc->us));
comma = ",";
}
if (gc->attr != 0) {
xsnprintf(s + off, sizeof s - off, "%s%s", comma,
attributes_tostring(gc->attr));
comma = ",";
}
if (*s == '\0')
return ("default");
return (s);
}
/* Apply a style on top of the given style. */
void
style_add(struct grid_cell *gc, struct options *oo, const char *name,
struct format_tree *ft)
{
struct style *sy;
struct format_tree *ft0 = NULL;
if (ft == NULL)
ft = ft0 = format_create(NULL, NULL, 0, FORMAT_NOJOBS);
sy = options_string_to_style(oo, name, ft);
if (sy == NULL)
sy = &style_default;
if (sy->gc.fg != 8)
gc->fg = sy->gc.fg;
if (sy->gc.bg != 8)
gc->bg = sy->gc.bg;
if (sy->gc.us != 8)
gc->us = sy->gc.us;
gc->attr |= sy->gc.attr;
if (ft0 != NULL)
format_free(ft0);
}
/* Apply a style on top of the default style. */
void
style_apply(struct grid_cell *gc, struct options *oo, const char *name,
struct format_tree *ft)
{
memcpy(gc, &grid_default_cell, sizeof *gc);
style_add(gc, oo, name, ft);
}
/* Initialize style from cell. */
void
style_set(struct style *sy, const struct grid_cell *gc)
{
memcpy(sy, &style_default, sizeof *sy);
memcpy(&sy->gc, gc, sizeof sy->gc);
}
/* Copy style. */
void
style_copy(struct style *dst, struct style *src)
{
memcpy(dst, src, sizeof *dst);
}
|
72fd4c6df50d07179954d3173ef61b7f72fe930b
|
1efb2283837c9b70bc6449cec877799e4efa3268
|
/test/mpi/comm/comm_group_half.c
|
612ec6b28da60c0b06768bea65f7ea7a5dd494ad
|
[
"mpich2"
] |
permissive
|
pmodels/mpich
|
d2392e8e30536cad3e500c16aa1e71211101d83f
|
2d265f9f5f93ebdd07ad547423bc6212868262a4
|
refs/heads/main
| 2023-09-04T05:50:15.041823
| 2023-09-01T23:07:33
| 2023-09-01T23:07:33
| 70,918,679
| 506
| 313
|
NOASSERTION
| 2023-09-14T14:38:36
| 2016-10-14T14:39:42
|
C
|
UTF-8
|
C
| false
| false
| 880
|
c
|
comm_group_half.c
|
/*
* Copyright (C) by Argonne National Laboratory
* See COPYRIGHT in top-level directory
*/
#include <stdio.h>
#include <mpi.h>
#include "mpitestconf.h"
#include "mpitest.h"
int main(int argc, char **argv)
{
int rank, size;
MPI_Group full_group, half_group;
int range[1][3];
MPI_Comm comm;
MTest_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_group(MPI_COMM_WORLD, &full_group);
range[0][0] = 0;
range[0][1] = size / 2;
range[0][2] = 1;
MPI_Group_range_incl(full_group, 1, range, &half_group);
if (rank <= size / 2) {
MPI_Comm_create_group(MPI_COMM_WORLD, half_group, 0, &comm);
MPI_Barrier(comm);
MPI_Comm_free(&comm);
}
MPI_Group_free(&half_group);
MPI_Group_free(&full_group);
MTest_Finalize(0);
return 0;
}
|
90007ad3d0aee1ccb6f0d776f18095bea579db8c
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/ffmpeg/libavdevice/pulse_audio_dec.c
|
2545462939fa3186b61ecd9f9d5d6bdbdd25eb8e
|
[
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"LGPL-2.1-only",
"LGPL-3.0-only",
"GPL-2.0-only",
"LGPL-2.1-or-later",
"GPL-3.0-or-later",
"LGPL-3.0-or-later",
"IJG",
"LicenseRef-scancode-other-permissive",
"GPL-2.0-or-later",
"GPL-3.0-only"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 13,319
|
c
|
pulse_audio_dec.c
|
/*
* Pulseaudio input
* Copyright (c) 2011 Luca Barbato <lu_zero@gentoo.org>
* Copyright 2004-2006 Lennart Poettering
* Copyright (c) 2014 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <pulse/rtclock.h>
#include <pulse/error.h>
#include "libavutil/internal.h"
#include "libavutil/opt.h"
#include "libavutil/time.h"
#include "libavformat/avformat.h"
#include "libavformat/internal.h"
#include "libavformat/version.h"
#include "pulse_audio_common.h"
#include "timefilter.h"
#define DEFAULT_CODEC_ID AV_NE(AV_CODEC_ID_PCM_S16BE, AV_CODEC_ID_PCM_S16LE)
typedef struct PulseData {
AVClass *class;
char *server;
char *name;
char *stream_name;
int sample_rate;
int channels;
int frame_size;
int fragment_size;
pa_threaded_mainloop *mainloop;
pa_context *context;
pa_stream *stream;
size_t pa_frame_size;
TimeFilter *timefilter;
int last_period;
int wallclock;
} PulseData;
#define CHECK_SUCCESS_GOTO(rerror, expression, label) \
do { \
if (!(expression)) { \
rerror = AVERROR_EXTERNAL; \
goto label; \
} \
} while (0)
#define CHECK_DEAD_GOTO(p, rerror, label) \
do { \
if (!(p)->context || !PA_CONTEXT_IS_GOOD(pa_context_get_state((p)->context)) || \
!(p)->stream || !PA_STREAM_IS_GOOD(pa_stream_get_state((p)->stream))) { \
rerror = AVERROR_EXTERNAL; \
goto label; \
} \
} while (0)
static void context_state_cb(pa_context *c, void *userdata) {
PulseData *p = userdata;
switch (pa_context_get_state(c)) {
case PA_CONTEXT_READY:
case PA_CONTEXT_TERMINATED:
case PA_CONTEXT_FAILED:
pa_threaded_mainloop_signal(p->mainloop, 0);
break;
}
}
static void stream_state_cb(pa_stream *s, void * userdata) {
PulseData *p = userdata;
switch (pa_stream_get_state(s)) {
case PA_STREAM_READY:
case PA_STREAM_FAILED:
case PA_STREAM_TERMINATED:
pa_threaded_mainloop_signal(p->mainloop, 0);
break;
}
}
static void stream_request_cb(pa_stream *s, size_t length, void *userdata) {
PulseData *p = userdata;
pa_threaded_mainloop_signal(p->mainloop, 0);
}
static void stream_latency_update_cb(pa_stream *s, void *userdata) {
PulseData *p = userdata;
pa_threaded_mainloop_signal(p->mainloop, 0);
}
static av_cold int pulse_close(AVFormatContext *s)
{
PulseData *pd = s->priv_data;
if (pd->mainloop)
pa_threaded_mainloop_stop(pd->mainloop);
if (pd->stream)
pa_stream_unref(pd->stream);
pd->stream = NULL;
if (pd->context) {
pa_context_disconnect(pd->context);
pa_context_unref(pd->context);
}
pd->context = NULL;
if (pd->mainloop)
pa_threaded_mainloop_free(pd->mainloop);
pd->mainloop = NULL;
ff_timefilter_destroy(pd->timefilter);
pd->timefilter = NULL;
return 0;
}
static av_cold int pulse_read_header(AVFormatContext *s)
{
PulseData *pd = s->priv_data;
AVStream *st;
char *device = NULL;
int ret;
enum AVCodecID codec_id =
s->audio_codec_id == AV_CODEC_ID_NONE ? DEFAULT_CODEC_ID : s->audio_codec_id;
const pa_sample_spec ss = { ff_codec_id_to_pulse_format(codec_id),
pd->sample_rate,
pd->channels };
pa_buffer_attr attr = { -1 };
pa_channel_map cmap;
const pa_buffer_attr *queried_attr;
pa_channel_map_init_extend(&cmap, pd->channels, PA_CHANNEL_MAP_WAVEEX);
st = avformat_new_stream(s, NULL);
if (!st) {
av_log(s, AV_LOG_ERROR, "Cannot add stream\n");
return AVERROR(ENOMEM);
}
if (pd->fragment_size == -1) {
// 50 ms fragments/latency by default seem good enough
attr.fragsize = pa_frame_size(&ss) * (pd->sample_rate / 20);
} else {
attr.fragsize = pd->fragment_size;
}
if (s->url[0] != '\0' && strcmp(s->url, "default"))
device = s->url;
if (!(pd->mainloop = pa_threaded_mainloop_new())) {
pulse_close(s);
return AVERROR_EXTERNAL;
}
if (!(pd->context = pa_context_new(pa_threaded_mainloop_get_api(pd->mainloop), pd->name))) {
pulse_close(s);
return AVERROR_EXTERNAL;
}
pa_context_set_state_callback(pd->context, context_state_cb, pd);
if (pa_context_connect(pd->context, pd->server, 0, NULL) < 0) {
pulse_close(s);
return AVERROR(pa_context_errno(pd->context));
}
pa_threaded_mainloop_lock(pd->mainloop);
if (pa_threaded_mainloop_start(pd->mainloop) < 0) {
ret = -1;
goto unlock_and_fail;
}
for (;;) {
pa_context_state_t state;
state = pa_context_get_state(pd->context);
if (state == PA_CONTEXT_READY)
break;
if (!PA_CONTEXT_IS_GOOD(state)) {
ret = AVERROR(pa_context_errno(pd->context));
goto unlock_and_fail;
}
/* Wait until the context is ready */
pa_threaded_mainloop_wait(pd->mainloop);
}
if (!(pd->stream = pa_stream_new(pd->context, pd->stream_name, &ss, &cmap))) {
ret = AVERROR(pa_context_errno(pd->context));
goto unlock_and_fail;
}
pa_stream_set_state_callback(pd->stream, stream_state_cb, pd);
pa_stream_set_read_callback(pd->stream, stream_request_cb, pd);
pa_stream_set_write_callback(pd->stream, stream_request_cb, pd);
pa_stream_set_latency_update_callback(pd->stream, stream_latency_update_cb, pd);
ret = pa_stream_connect_record(pd->stream, device, &attr,
PA_STREAM_INTERPOLATE_TIMING
|PA_STREAM_ADJUST_LATENCY
|PA_STREAM_AUTO_TIMING_UPDATE);
if (ret < 0) {
ret = AVERROR(pa_context_errno(pd->context));
goto unlock_and_fail;
}
for (;;) {
pa_stream_state_t state;
state = pa_stream_get_state(pd->stream);
if (state == PA_STREAM_READY)
break;
if (!PA_STREAM_IS_GOOD(state)) {
ret = AVERROR(pa_context_errno(pd->context));
goto unlock_and_fail;
}
/* Wait until the stream is ready */
pa_threaded_mainloop_wait(pd->mainloop);
}
/* Query actual fragment size */
queried_attr = pa_stream_get_buffer_attr(pd->stream);
if (!queried_attr || queried_attr->fragsize > INT_MAX/100) {
ret = AVERROR_EXTERNAL;
goto unlock_and_fail;
}
pd->fragment_size = queried_attr->fragsize;
pd->pa_frame_size = pa_frame_size(&ss);
pa_threaded_mainloop_unlock(pd->mainloop);
/* take real parameters */
st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
st->codecpar->codec_id = codec_id;
st->codecpar->sample_rate = pd->sample_rate;
st->codecpar->ch_layout.nb_channels = pd->channels;
avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
pd->timefilter = ff_timefilter_new(1000000.0 / pd->sample_rate,
pd->fragment_size / pd->pa_frame_size, 1.5E-6);
if (!pd->timefilter) {
pulse_close(s);
return AVERROR(ENOMEM);
}
return 0;
unlock_and_fail:
pa_threaded_mainloop_unlock(pd->mainloop);
pulse_close(s);
return ret;
}
static int pulse_read_packet(AVFormatContext *s, AVPacket *pkt)
{
PulseData *pd = s->priv_data;
int ret;
size_t read_length;
const void *read_data = NULL;
int64_t dts;
pa_usec_t latency;
int negative;
ptrdiff_t pos = 0;
pa_threaded_mainloop_lock(pd->mainloop);
CHECK_DEAD_GOTO(pd, ret, unlock_and_fail);
while (pos < pd->fragment_size) {
int r;
r = pa_stream_peek(pd->stream, &read_data, &read_length);
CHECK_SUCCESS_GOTO(ret, r == 0, unlock_and_fail);
if (read_length <= 0) {
pa_threaded_mainloop_wait(pd->mainloop);
CHECK_DEAD_GOTO(pd, ret, unlock_and_fail);
} else if (!read_data) {
/* There's a hole in the stream, skip it. We could generate
* silence, but that wouldn't work for compressed streams. */
r = pa_stream_drop(pd->stream);
CHECK_SUCCESS_GOTO(ret, r == 0, unlock_and_fail);
} else {
if (!pos) {
if (av_new_packet(pkt, pd->fragment_size) < 0) {
ret = AVERROR(ENOMEM);
goto unlock_and_fail;
}
dts = av_gettime();
pa_operation_unref(pa_stream_update_timing_info(pd->stream, NULL, NULL));
if (pa_stream_get_latency(pd->stream, &latency, &negative) >= 0) {
if (negative) {
dts += latency;
} else
dts -= latency;
} else {
av_log(s, AV_LOG_WARNING, "pa_stream_get_latency() failed\n");
}
}
if (pkt->size - pos < read_length) {
if (pos)
break;
pa_stream_drop(pd->stream);
/* Oversized fragment??? */
ret = AVERROR_EXTERNAL;
goto unlock_and_fail;
}
memcpy(pkt->data + pos, read_data, read_length);
pos += read_length;
pa_stream_drop(pd->stream);
}
}
pa_threaded_mainloop_unlock(pd->mainloop);
av_shrink_packet(pkt, pos);
if (pd->wallclock)
pkt->pts = ff_timefilter_update(pd->timefilter, dts, pd->last_period);
pd->last_period = pkt->size / pd->pa_frame_size;
return 0;
unlock_and_fail:
av_packet_unref(pkt);
pa_threaded_mainloop_unlock(pd->mainloop);
return ret;
}
static int pulse_get_device_list(AVFormatContext *h, AVDeviceInfoList *device_list)
{
PulseData *s = h->priv_data;
return ff_pulse_audio_get_devices(device_list, s->server, 0);
}
#define OFFSET(a) offsetof(PulseData, a)
#define D AV_OPT_FLAG_DECODING_PARAM
#define DEPR AV_OPT_FLAG_DEPRECATED
static const AVOption options[] = {
{ "server", "set PulseAudio server", OFFSET(server), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, D },
{ "name", "set application name", OFFSET(name), AV_OPT_TYPE_STRING, {.str = LIBAVFORMAT_IDENT}, 0, 0, D },
{ "stream_name", "set stream description", OFFSET(stream_name), AV_OPT_TYPE_STRING, {.str = "record"}, 0, 0, D },
{ "sample_rate", "set sample rate in Hz", OFFSET(sample_rate), AV_OPT_TYPE_INT, {.i64 = 48000}, 1, INT_MAX, D },
{ "channels", "set number of audio channels", OFFSET(channels), AV_OPT_TYPE_INT, {.i64 = 2}, 1, INT_MAX, D },
{ "frame_size", "set number of bytes per frame", OFFSET(frame_size), AV_OPT_TYPE_INT, {.i64 = 1024}, 1, INT_MAX, D | DEPR },
{ "fragment_size", "set buffering size, affects latency and cpu usage", OFFSET(fragment_size), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D },
{ "wallclock", "set the initial pts using the current time", OFFSET(wallclock), AV_OPT_TYPE_INT, {.i64 = 1}, -1, 1, D },
{ NULL },
};
static const AVClass pulse_demuxer_class = {
.class_name = "Pulse indev",
.item_name = av_default_item_name,
.option = options,
.version = LIBAVUTIL_VERSION_INT,
.category = AV_CLASS_CATEGORY_DEVICE_AUDIO_INPUT,
};
const AVInputFormat ff_pulse_demuxer = {
.name = "pulse",
.long_name = NULL_IF_CONFIG_SMALL("Pulse audio input"),
.priv_data_size = sizeof(PulseData),
.read_header = pulse_read_header,
.read_packet = pulse_read_packet,
.read_close = pulse_close,
.get_device_list = pulse_get_device_list,
.flags = AVFMT_NOFILE,
.priv_class = &pulse_demuxer_class,
};
|
2fd6d51661acb9faf38d1df27d8b325374fca44f
|
d9bf5fb8eb0e8d30189d0f5ba5ffa2d267fb37aa
|
/src/fusion.c
|
e4f7cf5d7bcb60662994ccacbd2599a37ff7412f
|
[
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
thaytan/OpenHMD
|
3fb4549c4877922202a508e920346915c25a7a3d
|
e12700d622450ac9d26cea92597b1bb13c397adc
|
refs/heads/master
| 2023-02-04T19:51:21.686749
| 2021-08-28T19:30:54
| 2021-08-28T19:30:54
| 188,549,485
| 131
| 18
|
BSL-1.0
| 2021-06-07T06:25:59
| 2019-05-25T09:57:45
|
C
|
UTF-8
|
C
| false
| false
| 3,506
|
c
|
fusion.c
|
// Copyright 2013, Fredrik Hultin.
// Copyright 2013, Jakob Bornecrantz.
// SPDX-License-Identifier: BSL-1.0
/*
* OpenHMD - Free and Open Source API and drivers for immersive technology.
*/
/* Sensor Fusion Implementation */
#include <string.h>
#include "openhmdi.h"
void ofusion_init(fusion* me)
{
memset(me, 0, sizeof(fusion));
me->orient.w = 1.0f;
ofq_init(&me->mag_fq, 20);
ofq_init(&me->accel_fq, 20);
ofq_init(&me->ang_vel_fq, 20);
me->flags = FF_USE_GRAVITY;
me->grav_gain = 0.05f;
}
void ofusion_update(fusion* me, float dt, const vec3f* ang_vel, const vec3f* accel, const vec3f* mag)
{
me->ang_vel = *ang_vel;
me->accel = *accel;
me->raw_mag = *mag;
me->mag = *mag;
vec3f world_accel;
oquatf_get_rotated(&me->orient, accel, &world_accel);
me->iterations += 1;
me->time += dt;
ofq_add(&me->mag_fq, mag);
ofq_add(&me->accel_fq, &world_accel);
ofq_add(&me->ang_vel_fq, ang_vel);
float ang_vel_length = ovec3f_get_length(ang_vel);
if(ang_vel_length > 0.0001f){
vec3f rot_axis =
{{ ang_vel->x / ang_vel_length, ang_vel->y / ang_vel_length, ang_vel->z / ang_vel_length }};
float rot_angle = ang_vel_length * dt;
quatf delta_orient;
oquatf_init_axis(&delta_orient, &rot_axis, rot_angle);
oquatf_mult_me(&me->orient, &delta_orient);
}
// gravity correction
if(me->flags & FF_USE_GRAVITY){
const float gravity_tolerance = .4f, ang_vel_tolerance = .1f;
const float min_tilt_error = 0.05f, max_tilt_error = 0.01f;
// if the device is within tolerance levels, count this as the device is level and add to the counter
// otherwise reset the counter and start over
me->device_level_count =
fabsf(ovec3f_get_length(accel) - 9.82f) < gravity_tolerance * 2.0f && ang_vel_length < ang_vel_tolerance
? me->device_level_count + 1 : 0;
// device has been level for long enough, grab mean from the accelerometer filter queue (last n values)
// and use for correction
if(me->device_level_count > 50){
me->device_level_count = 0;
vec3f accel_mean;
ofq_get_mean(&me->accel_fq, &accel_mean);
if (ovec3f_get_length(&accel_mean) - 9.82f < gravity_tolerance)
{
// Calculate a cross product between what the device
// thinks is up and what gravity indicates is down.
// The values are optimized of what we would get out
// from the cross product.
vec3f tilt = {{accel_mean.z, 0, -accel_mean.x}};
ovec3f_normalize_me(&tilt);
ovec3f_normalize_me(&accel_mean);
vec3f up = {{0, 1.0f, 0}};
float tilt_angle = ovec3f_get_angle(&up, &accel_mean);
if(tilt_angle > max_tilt_error){
me->grav_error_angle = tilt_angle;
me->grav_error_axis = tilt;
}
}
}
// perform gravity tilt correction
if(me->grav_error_angle > min_tilt_error){
float use_angle;
// if less than 2000 iterations have passed, set the up axis to the correction value outright
if(me->iterations < 2000){
use_angle = -me->grav_error_angle;
me->grav_error_angle = 0;
}
// otherwise try to correct
else {
use_angle = -me->grav_gain * me->grav_error_angle * 0.005f * (5.0f * ang_vel_length + 1.0f);
me->grav_error_angle += use_angle;
}
// perform the correction
quatf corr_quat, old_orient;
oquatf_init_axis(&corr_quat, &me->grav_error_axis, use_angle);
old_orient = me->orient;
oquatf_mult(&corr_quat, &old_orient, &me->orient);
}
}
// mitigate drift due to floating point
// inprecision with quat multiplication.
oquatf_normalize_me(&me->orient);
}
|
947a30decf4e9be1d32f70d299839a05ff7bb3c4
|
ffdc77394c5b5532b243cf3c33bd584cbdc65cb7
|
/mindspore/ccsrc/plugin/device/cpu/kernel/nnacl/fp32/embedding_lookup_fp32.c
|
0ba41c0472a6ee17875a560994180fa0e86e1273
|
[
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"OpenSSL",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause-Open-MPI",
"MIT",
"MPL-2.0-no-copyleft-exception",
"NTP",
"BSD-3-Clause",
"GPL-1.0-or-later",
"0BSD",
"MPL-2.0",
"LicenseRef-scancode-free-unknown",
"AGPL-3.0-only",
"Libpng",
"MPL-1.1",
"IJG",
"GPL-2.0-only",
"BSL-1.0",
"Zlib",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-python-cwi",
"BSD-2-Clause",
"LicenseRef-scancode-gary-s-brown",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"Python-2.0",
"LicenseRef-scancode-mit-nagy",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense"
] |
permissive
|
mindspore-ai/mindspore
|
ca7d5bb51a3451c2705ff2e583a740589d80393b
|
54acb15d435533c815ee1bd9f6dc0b56b4d4cf83
|
refs/heads/master
| 2023-07-29T09:17:11.051569
| 2023-07-17T13:14:15
| 2023-07-17T13:14:15
| 239,714,835
| 4,178
| 768
|
Apache-2.0
| 2023-07-26T22:31:11
| 2020-02-11T08:43:48
|
C++
|
UTF-8
|
C
| false
| false
| 2,082
|
c
|
embedding_lookup_fp32.c
|
/**
* Copyright 2020 Huawei Technologies 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.
*/
#include "nnacl/fp32/embedding_lookup_fp32.h"
#include <string.h>
#include "nnacl/errorcode.h"
void l2_regulate(float *data, int size, float max_norm) {
float sum = 0;
for (int i = 0; i < size; ++i) {
sum += data[i];
}
if (sum != 0) {
for (int i = 0; i < size; ++i) {
data[i] *= max_norm / sum;
}
}
return;
}
int CopyData(float *input_data, const int32_t *ids, float *output_data, int num,
const EmbeddingLookupParameter *parameter) {
if (ids[num] >= parameter->layer_num_ || ids[num] < 0) {
return NNACL_ERRCODE_INDEX_OUT_OF_RANGE;
}
float *out_data = output_data + num * parameter->layer_size_;
float *in_data = input_data + ids[num] * parameter->layer_size_;
if (!parameter->is_regulated_[ids[num]]) {
l2_regulate(in_data, parameter->layer_size_, parameter->max_norm_);
parameter->is_regulated_[ids[num]] = true;
}
memcpy(out_data, in_data, sizeof(float) * (size_t)(parameter->layer_size_));
return NNACL_OK;
}
int EmbeddingLookup(float *input_data, const int32_t *ids, float *output_data,
const EmbeddingLookupParameter *parameter, int task_id) {
if (parameter->op_parameter_.thread_num_ == 0) {
return NNACL_PARAM_INVALID;
}
for (int i = task_id; i < parameter->ids_size_; i += parameter->op_parameter_.thread_num_) {
int ret = CopyData(input_data, ids, output_data, i, parameter);
if (ret != NNACL_OK) {
return ret;
}
}
return NNACL_OK;
}
|
2d506de6f77e67c4c8951d72be5977adac4802a0
|
2d07a646d50c6cc1547b069ecd27c512623d8574
|
/src/main.c
|
f888dc10378de9a1d656b566ea6b274eb13b2c7f
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
bjornbytes/lovr
|
da40e59eb9c42debbc6e22356d55194283740323
|
072452a4dafb466e8af9a4bc546b60ae077f8566
|
refs/heads/master
| 2023-08-16T13:42:30.581144
| 2023-07-29T10:37:18
| 2023-07-29T10:37:18
| 62,519,414
| 1,699
| 164
|
MIT
| 2023-09-13T22:21:32
| 2016-07-03T23:36:45
|
C
|
UTF-8
|
C
| false
| false
| 4,319
|
c
|
main.c
|
#include "api/api.h"
#include "event/event.h"
#include "core/os.h"
#include "util.h"
#include "boot.lua.h"
#include "nogame.lua.h"
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#ifdef EMSCRIPTEN
#include <emscripten.h>
typedef struct {
lua_State* L;
lua_State* T;
int argc;
char** argv;
} lovrEmscriptenContext;
static void emscriptenLoop(void*);
#endif
static Variant cookie;
static int luaopen_lovr_nogame(lua_State* L) {
if (!luaL_loadbuffer(L, (const char*) etc_nogame_lua, etc_nogame_lua_len, "@nogame.lua")) {
lua_call(L, 0, 1);
}
return 1;
}
int main(int argc, char** argv) {
if (argc > 1 && (!strcmp(argv[1], "--version") || !strcmp(argv[1], "-v"))) {
os_open_console();
printf("LOVR %d.%d.%d (%s)\n", LOVR_VERSION_MAJOR, LOVR_VERSION_MINOR, LOVR_VERSION_PATCH, LOVR_VERSION_ALIAS);
exit(0);
}
if (argc > 1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h"))) {
os_open_console();
printf(
"usage: lovr [options] [<source>]\n\n"
"options:\n"
" -h, --help\t\tShow help and exit\n"
" -v, --version\t\tShow version and exit\n"
" --console\t\tAttach Windows console\n\n"
"<source> can be a Lua file, a folder, or a zip archive\n"
);
exit(0);
}
if (!os_init()) {
fprintf(stderr, "Failed to initialize platform");
exit(1);
}
int status;
bool restart;
do {
lua_State* L = luaL_newstate();
luax_setmainthread(L);
luaL_openlibs(L);
luax_preload(L);
const luaL_Reg nogame[] = {
{ "nogame", luaopen_lovr_nogame },
{ NULL, NULL }
};
lua_getglobal(L, "package");
lua_getfield(L, -1, "preload");
luax_register(L, nogame);
lua_pop(L, 2);
// arg table
lua_newtable(L);
lua_pushstring(L, argc > 0 ? argv[0] : "lovr");
lua_setfield(L, -2, "exe");
luax_pushvariant(L, &cookie);
lua_setfield(L, -2, "restart");
int argOffset = 1;
for (int i = 1; i < argc; i++, argOffset++) {
if (!strcmp(argv[i], "--console")) {
os_open_console();
} else {
break; // This is the project path
}
}
// Now that we know the negative offset to start at, copy all args in the table
for (int i = 0; i < argc; i++) {
lua_pushstring(L, argv[i]);
lua_rawseti(L, -2, -argOffset + i);
}
lua_setglobal(L, "arg");
lua_pushcfunction(L, luax_getstack);
if (luaL_loadbuffer(L, (const char*) etc_boot_lua, etc_boot_lua_len, "@boot.lua") || lua_pcall(L, 0, 1, -2)) {
fprintf(stderr, "%s\n", lua_tostring(L, -1));
return 1;
}
lua_State* T = lua_newthread(L);
lua_pushvalue(L, -2);
lua_xmove(L, T, 1);
lovrSetErrorCallback(luax_vthrow, T);
lovrSetLogCallback(luax_vlog, T);
#ifdef EMSCRIPTEN
lovrEmscriptenContext context = { L, T, argc, argv };
emscripten_set_main_loop_arg(emscriptenLoop, (void*) &context, 0, 1);
return 0;
#endif
while (luax_resume(T, 0) == LUA_YIELD) {
os_sleep(0.);
}
restart = lua_type(T, 1) == LUA_TSTRING && !strcmp(lua_tostring(T, 1), "restart");
status = lua_tonumber(T, 1);
luax_checkvariant(T, 2, &cookie);
if (cookie.type == TYPE_OBJECT) {
cookie.type = TYPE_NIL;
memset(&cookie.value, 0, sizeof(cookie.value));
}
lua_close(L);
} while (restart);
os_destroy();
return status;
}
#ifdef EMSCRIPTEN
// Called by JS, don't delete
void lovrDestroy(void* arg) {
if (arg) {
lovrEmscriptenContext* context = arg;
lua_State* L = context->L;
emscripten_cancel_main_loop();
lua_close(L);
os_destroy();
}
}
static void emscriptenLoop(void* arg) {
lovrEmscriptenContext* context = arg;
lua_State* T = context->T;
if (luax_resume(T, 0) != LUA_YIELD) {
bool restart = lua_type(T, 1) == LUA_TSTRING && !strcmp(lua_tostring(T, 1), "restart");
int status = lua_tonumber(T, 1);
luax_checkvariant(T, 2, &cookie);
if (cookie.type == TYPE_OBJECT) {
cookie.type = TYPE_NIL;
memset(&cookie.value, 0, sizeof(cookie.value));
}
lua_close(context->L);
emscripten_cancel_main_loop();
if (restart) {
main(context->argc, context->argv);
} else {
os_destroy();
exit(status);
}
}
}
#endif
|
f58157cad43094a879dbc9c79c146fa1d9cde37b
|
9ca6d7ee24abbf3e2de2ec9499635a31ec863bb1
|
/QiniuSDK/include/QNRequestTransaction.h
|
8df8a41babf282ffb213af9cd6b36ba618344d9b
|
[
"MIT"
] |
permissive
|
qiniu/objc-sdk
|
be895a012f654f704b0781e2c600e78d5d81e2c9
|
c1bdb198c5aa00ff4a4e7e8d580ed587977f455d
|
refs/heads/master
| 2023-08-18T10:55:39.592753
| 2023-08-07T10:44:46
| 2023-08-07T10:44:46
| 24,551,801
| 476
| 249
|
MIT
| 2023-09-12T09:35:07
| 2014-09-28T06:14:51
|
Objective-C
|
UTF-8
|
C
| false
| false
| 38
|
h
|
QNRequestTransaction.h
|
../Http/Request/QNRequestTransaction.h
|
2a7432ae739bf7a8a7a009dfed3abf0afe1e1932
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/third_party/libzip/src/lib/zip_progress.c
|
ddb47c70a57cfa503ae5f70c3883a1cb3cbf040a
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"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
| 7,969
|
c
|
zip_progress.c
|
/*
zip_progress.c -- progress reporting
Copyright (C) 2017-2020 Dieter Baron and Thomas Klausner
This file is part of libzip, a library to manipulate ZIP archives.
The authors can be contacted at <libzip@nih.at>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The names of the authors may not be used to endorse or promote
products derived from this software without specific prior
written permission.
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.
*/
#include <stdlib.h>
#define _ZIP_COMPILING_DEPRECATED
#include "zipint.h"
struct zip_progress {
zip_t *za;
zip_progress_callback callback_progress;
void (*ud_progress_free)(void *);
void *ud_progress;
zip_cancel_callback callback_cancel;
void (*ud_cancel_free)(void *);
void *ud_cancel;
double precision;
/* state */
double last_update; /* last value callback function was called with */
double start; /* start of sub-progress section */
double end; /* end of sub-progress section */
};
static void _zip_progress_free_cancel_callback(zip_progress_t *progress);
static void _zip_progress_free_progress_callback(zip_progress_t *progress);
static zip_progress_t *_zip_progress_new(zip_t *za);
static void _zip_progress_set_cancel_callback(zip_progress_t *progress, zip_cancel_callback callback, void (*ud_free)(void *), void *ud);
static void _zip_progress_set_progress_callback(zip_progress_t *progress, double precision, zip_progress_callback callback, void (*ud_free)(void *), void *ud);
void
_zip_progress_end(zip_progress_t *progress) {
_zip_progress_update(progress, 1.0);
}
void
_zip_progress_free(zip_progress_t *progress) {
if (progress == NULL) {
return;
}
_zip_progress_free_progress_callback(progress);
_zip_progress_free_cancel_callback(progress);
free(progress);
}
static zip_progress_t *
_zip_progress_new(zip_t *za) {
zip_progress_t *progress = (zip_progress_t *)malloc(sizeof(*progress));
if (progress == NULL) {
zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
return NULL;
}
progress->za = za;
progress->callback_progress = NULL;
progress->ud_progress_free = NULL;
progress->ud_progress = NULL;
progress->precision = 0.0;
progress->callback_cancel = NULL;
progress->ud_cancel_free = NULL;
progress->ud_cancel = NULL;
return progress;
}
static void
_zip_progress_free_progress_callback(zip_progress_t *progress) {
if (progress->ud_progress_free) {
progress->ud_progress_free(progress->ud_progress);
}
progress->callback_progress = NULL;
progress->ud_progress = NULL;
progress->ud_progress_free = NULL;
}
static void
_zip_progress_free_cancel_callback(zip_progress_t *progress) {
if (progress->ud_cancel_free) {
progress->ud_cancel_free(progress->ud_cancel);
}
progress->callback_cancel = NULL;
progress->ud_cancel = NULL;
progress->ud_cancel_free = NULL;
}
static void
_zip_progress_set_progress_callback(zip_progress_t *progress, double precision, zip_progress_callback callback, void (*ud_free)(void *), void *ud) {
_zip_progress_free_progress_callback(progress);
progress->callback_progress = callback;
progress->ud_progress_free = ud_free;
progress->ud_progress = ud;
progress->precision = precision;
}
void
_zip_progress_set_cancel_callback(zip_progress_t *progress, zip_cancel_callback callback, void (*ud_free)(void *), void *ud) {
_zip_progress_free_cancel_callback(progress);
progress->callback_cancel = callback;
progress->ud_cancel_free = ud_free;
progress->ud_cancel = ud;
}
int
_zip_progress_start(zip_progress_t *progress) {
if (progress == NULL) {
return 0;
}
if (progress->callback_progress != NULL) {
progress->last_update = 0.0;
progress->callback_progress(progress->za, 0.0, progress->ud_progress);
}
if (progress->callback_cancel != NULL) {
if (progress->callback_cancel(progress->za, progress->ud_cancel)) {
return -1;
}
}
return 0;
}
int
_zip_progress_subrange(zip_progress_t *progress, double start, double end) {
if (progress == NULL) {
return 0;
}
progress->start = start;
progress->end = end;
return _zip_progress_update(progress, 0.0);
}
int
_zip_progress_update(zip_progress_t *progress, double sub_current) {
double current;
if (progress == NULL) {
return 0;
}
if (progress->callback_progress != NULL) {
current = ZIP_MIN(ZIP_MAX(sub_current, 0.0), 1.0) * (progress->end - progress->start) + progress->start;
if (current - progress->last_update > progress->precision) {
progress->callback_progress(progress->za, current, progress->ud_progress);
progress->last_update = current;
}
}
if (progress->callback_cancel != NULL) {
if (progress->callback_cancel(progress->za, progress->ud_cancel)) {
return -1;
}
}
return 0;
}
ZIP_EXTERN int
zip_register_progress_callback_with_state(zip_t *za, double precision, zip_progress_callback callback, void (*ud_free)(void *), void *ud) {
if (callback != NULL) {
if (za->progress == NULL) {
if ((za->progress = _zip_progress_new(za)) == NULL) {
return -1;
}
}
_zip_progress_set_progress_callback(za->progress, precision, callback, ud_free, ud);
}
else {
if (za->progress != NULL) {
if (za->progress->callback_cancel == NULL) {
_zip_progress_free(za->progress);
za->progress = NULL;
}
else {
_zip_progress_free_progress_callback(za->progress);
}
}
}
return 0;
}
ZIP_EXTERN int
zip_register_cancel_callback_with_state(zip_t *za, zip_cancel_callback callback, void (*ud_free)(void *), void *ud) {
if (callback != NULL) {
if (za->progress == NULL) {
if ((za->progress = _zip_progress_new(za)) == NULL) {
return -1;
}
}
_zip_progress_set_cancel_callback(za->progress, callback, ud_free, ud);
}
else {
if (za->progress != NULL) {
if (za->progress->callback_progress == NULL) {
_zip_progress_free(za->progress);
za->progress = NULL;
}
else {
_zip_progress_free_cancel_callback(za->progress);
}
}
}
return 0;
}
struct legacy_ud {
zip_progress_callback_t callback;
};
static void
_zip_legacy_progress_callback(zip_t *za, double progress, void *vud) {
struct legacy_ud *ud = (struct legacy_ud *)vud;
ud->callback(progress);
}
ZIP_EXTERN void
zip_register_progress_callback(zip_t *za, zip_progress_callback_t progress_callback) {
struct legacy_ud *ud;
if (progress_callback == NULL) {
zip_register_progress_callback_with_state(za, 0, NULL, NULL, NULL);
}
if ((ud = (struct legacy_ud *)malloc(sizeof(*ud))) == NULL) {
return;
}
ud->callback = progress_callback;
if (zip_register_progress_callback_with_state(za, 0.001, _zip_legacy_progress_callback, free, ud) < 0) {
free(ud);
}
}
|
08553215245430c62a3670370700e879eeb5716f
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/fm33lc026/libraries/FM33LC0xx_FL_Driver/Src/fm33lc0xx_fl_rtc.c
|
df96e3dad3a5f47dde8782457bf1c2c1ae9e99b7
|
[
"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
| 5,477
|
c
|
fm33lc0xx_fl_rtc.c
|
/**
*******************************************************************************************************
* @file fm33lc0xx_fl_rtc.c
* @author FMSH Application Team
* @brief Src file of RTC FL Module
*******************************************************************************************************
* @attention
*
* Copyright (c) [2021] [Fudan Microelectronics]
* THIS SOFTWARE is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*
*******************************************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "fm33lc0xx_fl.h"
/** @addtogroup FM33LC0XX_FL_Driver
* @{
*/
/** @addtogroup RTC
* @{
*/
#ifdef FL_RTC_DRIVER_ENABLED
/* Private macros ------------------------------------------------------------*/
/** @addtogroup RTC_FL_Private_Macros
* @{
*/
#define IS_RTC_INSTANCE(RTCx) ((RTCx) == RTC)
/**
* @}
*/
/** @addtogroup RTC_FL_EF_Init
* @{
*/
/**
* @brief 复位RTC
* @param RTCx 外设入口地址
* @retval 错误状态,可能值:
* -FL_PASS 外设寄存器值恢复复位值
* -FL_FAIL 未成功执行
*/
FL_ErrorStatus FL_RTC_DeInit(RTC_Type *RTCx)
{
FL_ErrorStatus result = FL_PASS;
/* Check the parameters */
assert_param(IS_RTC_INSTANCE(RTCx));
RTCx->IER = 0x00000000U;
RTCx->WER = 0x00000000U;
RTCx->ADJUST = 0x00000000U;
RTCx->ADSIGN = 0x00000000U;
RTCx->ALARM = 0x00000000U;
RTCx->BCDDAY = 0x00000000U;
RTCx->BCDHOUR = 0x00000000U;
RTCx->BCDMIN = 0x00000000U;
RTCx->BCDMONTH = 0x00000000U;
RTCx->BCDSEC = 0x00000000U;
RTCx->BCDWEEK = 0x00000000U;
RTCx->BCDYEAR = 0x00000000U;
RTCx->SBSCNT = 0x00000000U;
RTCx->TMSEL = 0x00000000U;
RTCx->WER = 0x00000000U;
return result;
}
/**
* @brief 配置RTC
* @param RTCx 外设入口地址
* @param initStruct 指向 @ref FL_RTC_InitTypeDef 结构体的指针
* @retval 错误状态,可能值:
* -FL_PASS 配置成功
* -FL_FAIL 配置过程发生错误
*/
FL_ErrorStatus FL_RTC_Init(RTC_Type *RTCx, FL_RTC_InitTypeDef *initStruct)
{
/* 参数检查 */
assert_param(IS_RTC_INSTANCE(RTCx));
/* 时钟总线使能配置 */
FL_RCC_EnableGroup1BusClock(FL_RCC_GROUP1_BUSCLK_RTC);
/* 配置时间 */
FL_RTC_ConfigTime(RTCx, initStruct);
return FL_PASS;
}
/**
* @brief 设置RTC实时时间
* @param RTCx 外设入口地址
* @param initStruct 指向 @ref FL_RTC_InitTypeDef 结构体的指针
* @retval 错误状态,可能值:
* -FL_PASS 配置成功
* -FL_FAIL 配置过程发生错误
*/
FL_ErrorStatus FL_RTC_ConfigTime(RTC_Type *RTCx, FL_RTC_InitTypeDef *initStruct)
{
/* 使能时间配置 */
FL_RTC_WriteEnable(RTCx);
/* 配置秒 */
FL_RTC_WriteSecond(RTCx, initStruct->second);
/* 配置分钟 */
FL_RTC_WriteMinute(RTCx, initStruct->minute);
/* 配置小时 */
FL_RTC_WriteHour(RTCx, initStruct->hour);
/* 配置日期 */
FL_RTC_WriteDay(RTCx, initStruct->day);
/* 配置周 */
FL_RTC_WriteWeek(RTCx, initStruct->week);
/* 配置月 */
FL_RTC_WriteMonth(RTCx, initStruct->month);
/* 配置年 */
FL_RTC_WriteYear(RTCx, initStruct->year);
/* 锁定时间配置 */
FL_RTC_WriteDisable(RTCx);
return FL_PASS;
}
/**
* @brief 获取RTC实时时间并保存到指定结构体中
* @param RTCx 外设入口地址
* @param initStruct 指向 @ref FL_RTC_InitTypeDef 结构体的指针
* @retval 错误状态,可能值:
* -FL_PASS 获取成功
* -FL_FAIL 获取过程发生错误
*/
FL_ErrorStatus FL_RTC_GetTime(RTC_Type *RTCx, FL_RTC_InitTypeDef *initStruct)
{
/* 配置秒 */
initStruct->second = FL_RTC_ReadSecond(RTCx);
/* 配置分钟 */
initStruct->minute = FL_RTC_ReadMinute(RTCx);
/* 配置小时 */
initStruct->hour = FL_RTC_ReadHour(RTCx);
/* 配置日期 */
initStruct->day = FL_RTC_ReadDay(RTCx);
/* 配置周 */
initStruct->week = FL_RTC_ReadWeek(RTCx);
/* 配置月 */
initStruct->month = FL_RTC_ReadMonth(RTCx);
/* 配置年 */
initStruct->year = FL_RTC_ReadYear(RTCx);
return FL_PASS;
}
/**
* @brief 将 @ref FL_RTC_InitTypeDef 结构体初始化为默认配置
* @param initStruct 指向 @ref FL_RTC_InitTypeDef 结构体的指针
*
* @retval None
*/
void FL_RTC_StructInit(FL_RTC_InitTypeDef *initStruct)
{
initStruct->year = 0x00;
initStruct->month = 0x00;
initStruct->day = 0x00;
initStruct->week = 0x00;
initStruct->hour = 0x00;
initStruct->minute = 0x00;
initStruct->second = 0x00;
}
/**
* @}
*/
#endif /* FL_RTC_DRIVER_ENABLED */
/**
* @}
*/
/**
* @}
*/
/********************** (C) COPYRIGHT Fudan Microelectronics **** END OF FILE ***********************/
|
ee0f9a9fd33b663450b16a5bce9d7fa4549aff66
|
8838eb997879add5759b6dfb23f9a646464e53ca
|
/src/drivers/tty/serial/ttys.c
|
4323a05adc00e10a87a61ba04b7a8ecc6e4d19d9
|
[
"BSD-2-Clause"
] |
permissive
|
embox/embox
|
d6aacec876978522f01cdc4b8de37a668c6f4c80
|
98e3c06e33f3fdac10a29c069c20775568e0a6d1
|
refs/heads/master
| 2023-09-04T03:02:20.165042
| 2023-09-02T14:55:31
| 2023-09-02T14:55:31
| 33,078,138
| 1,087
| 325
|
BSD-2-Clause
| 2023-09-14T16:58:34
| 2015-03-29T15:27:48
|
C
|
UTF-8
|
C
| false
| false
| 1,249
|
c
|
ttys.c
|
/**
* @file
* @brief
*
* @author Anton Kozlov
* @date 09.08.2013
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <util/err.h>
#include <util/indexator.h>
#include <mem/misc/pool.h>
#include <drivers/char_dev.h>
#include <drivers/serial/uart_dev.h>
#include <drivers/device.h>
#include "idesc_serial.h"
struct idesc *uart_cdev_open(struct dev_module *cdev, void *priv) {
struct idesc *idesc;
int res;
idesc = idesc_serial_create(cdev->dev_priv, (uintptr_t) priv);
if (err(idesc)) {
//return idesc;
// TODO now below on stack wait NULL
return NULL;
}
res = uart_open(cdev->dev_priv);
if (res) {
//return err_ptr(-res);
// TODO now below on stack wait NULL
return NULL;
}
return idesc;
}
#define SERIAL_POOL_SIZE OPTION_GET(NUMBER, serial_quantity)
POOL_DEF(cdev_serials_pool, struct dev_module, SERIAL_POOL_SIZE);
int ttys_register(const char *name, void *dev_info) {
struct dev_module *cdev;
cdev = pool_alloc(&cdev_serials_pool);
if (!cdev) {
return -ENOMEM;
}
memset(cdev, 0, sizeof(*cdev));
memcpy(cdev->name, name, sizeof(cdev->name));
cdev->dev_open = uart_cdev_open;
cdev->dev_iops = idesc_serial_get_ops();
cdev->dev_priv = dev_info;
return char_dev_register(cdev);
}
|
9eaad33573470f12484f62055b384a7b291ac9ba
|
07327b5e8b2831b12352bf7c6426bfda60129da7
|
/Include/10.0.10240.0/um/htiface.h
|
bdeaf9dbe0da0ddf97fc772e0c87ed9791ee51dd
|
[] |
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
| 26,355
|
h
|
htiface.h
|
/* this ALWAYS GENERATED file contains the definitions for the interfaces */
/* File created by MIDL compiler version 8.00.0613 */
/* @@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 __htiface_h__
#define __htiface_h__
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
/* Forward Declarations */
#ifndef __ITargetFrame_FWD_DEFINED__
#define __ITargetFrame_FWD_DEFINED__
typedef interface ITargetFrame ITargetFrame;
#endif /* __ITargetFrame_FWD_DEFINED__ */
#ifndef __ITargetEmbedding_FWD_DEFINED__
#define __ITargetEmbedding_FWD_DEFINED__
typedef interface ITargetEmbedding ITargetEmbedding;
#endif /* __ITargetEmbedding_FWD_DEFINED__ */
#ifndef __ITargetFramePriv_FWD_DEFINED__
#define __ITargetFramePriv_FWD_DEFINED__
typedef interface ITargetFramePriv ITargetFramePriv;
#endif /* __ITargetFramePriv_FWD_DEFINED__ */
#ifndef __ITargetFramePriv2_FWD_DEFINED__
#define __ITargetFramePriv2_FWD_DEFINED__
typedef interface ITargetFramePriv2 ITargetFramePriv2;
#endif /* __ITargetFramePriv2_FWD_DEFINED__ */
/* header files for imported files */
#include "objidl.h"
#include "oleidl.h"
#include "urlmon.h"
#ifdef __cplusplus
extern "C"{
#endif
/* interface __MIDL_itf_htiface_0000_0000 */
/* [local] */
//=--------------------------------------------------------------------------=
// HTIface.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")
//--------------------------------------------------------------------------
// OLE Hyperlinking ITargetFrame Interfaces.
#ifndef _LPTARGETFRAME2_DEFINED
#include "htiframe.h"
#endif // _LPTARGETFRAME2_DEFINED
EXTERN_C const IID IID_ITargetFrame;
EXTERN_C const IID IID_ITargetEmbedding;
EXTERN_C const IID IID_ITargetFramePriv;
EXTERN_C const IID IID_ITargetFramePriv2;
#ifndef _LPTARGETFRAME_DEFINED
#define _LPTARGETFRAME_DEFINED
extern RPC_IF_HANDLE __MIDL_itf_htiface_0000_0000_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_htiface_0000_0000_v0_0_s_ifspec;
#ifndef __ITargetFrame_INTERFACE_DEFINED__
#define __ITargetFrame_INTERFACE_DEFINED__
/* interface ITargetFrame */
/* [unique][uuid][object] */
typedef /* [unique] */ __RPC_unique_pointer ITargetFrame *LPTARGETFRAME;
typedef /* [public] */
enum __MIDL_ITargetFrame_0001
{
NAVIGATEFRAME_FL_RECORD = 0x1,
NAVIGATEFRAME_FL_POST = 0x2,
NAVIGATEFRAME_FL_NO_DOC_CACHE = 0x4,
NAVIGATEFRAME_FL_NO_IMAGE_CACHE = 0x8,
NAVIGATEFRAME_FL_AUTH_FAIL_CACHE_OK = 0x10,
NAVIGATEFRAME_FL_SENDING_FROM_FORM = 0x20,
NAVIGATEFRAME_FL_REALLY_SENDING_FROM_FORM = 0x40
} NAVIGATEFRAME_FLAGS;
typedef struct tagNavigateData
{
ULONG ulTarget;
ULONG ulURL;
ULONG ulRefURL;
ULONG ulPostData;
DWORD dwFlags;
} NAVIGATEDATA;
EXTERN_C const IID IID_ITargetFrame;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("d5f78c80-5252-11cf-90fa-00AA0042106e")
ITargetFrame : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE SetFrameName(
/* [in] */ __RPC__in LPCWSTR pszFrameName) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFrameName(
/* [out] */ __RPC__deref_out_opt LPWSTR *ppszFrameName) = 0;
virtual HRESULT STDMETHODCALLTYPE GetParentFrame(
/* [out] */ __RPC__deref_out_opt IUnknown **ppunkParent) = 0;
virtual HRESULT STDMETHODCALLTYPE FindFrame(
/* [in] */ __RPC__in LPCWSTR pszTargetName,
/* [in] */ __RPC__in_opt IUnknown *ppunkContextFrame,
/* [in] */ DWORD dwFlags,
/* [out] */ __RPC__deref_out_opt IUnknown **ppunkTargetFrame) = 0;
virtual HRESULT STDMETHODCALLTYPE SetFrameSrc(
/* [in] */ __RPC__in LPCWSTR pszFrameSrc) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFrameSrc(
/* [out] */ __RPC__deref_out_opt LPWSTR *ppszFrameSrc) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFramesContainer(
/* [out] */ __RPC__deref_out_opt IOleContainer **ppContainer) = 0;
virtual HRESULT STDMETHODCALLTYPE SetFrameOptions(
/* [in] */ DWORD dwFlags) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFrameOptions(
/* [out] */ __RPC__out DWORD *pdwFlags) = 0;
virtual HRESULT STDMETHODCALLTYPE SetFrameMargins(
/* [in] */ DWORD dwWidth,
/* [in] */ DWORD dwHeight) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFrameMargins(
/* [out] */ __RPC__out DWORD *pdwWidth,
/* [out] */ __RPC__out DWORD *pdwHeight) = 0;
virtual HRESULT STDMETHODCALLTYPE RemoteNavigate(
/* [in] */ ULONG cLength,
/* [size_is][in] */ __RPC__in_ecount_full(cLength) ULONG *pulData) = 0;
virtual HRESULT STDMETHODCALLTYPE OnChildFrameActivate(
/* [in] */ __RPC__in_opt IUnknown *pUnkChildFrame) = 0;
virtual HRESULT STDMETHODCALLTYPE OnChildFrameDeactivate(
/* [in] */ __RPC__in_opt IUnknown *pUnkChildFrame) = 0;
};
#else /* C style interface */
typedef struct ITargetFrameVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
__RPC__in ITargetFrame * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in ITargetFrame * This);
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in ITargetFrame * This);
HRESULT ( STDMETHODCALLTYPE *SetFrameName )(
__RPC__in ITargetFrame * This,
/* [in] */ __RPC__in LPCWSTR pszFrameName);
HRESULT ( STDMETHODCALLTYPE *GetFrameName )(
__RPC__in ITargetFrame * This,
/* [out] */ __RPC__deref_out_opt LPWSTR *ppszFrameName);
HRESULT ( STDMETHODCALLTYPE *GetParentFrame )(
__RPC__in ITargetFrame * This,
/* [out] */ __RPC__deref_out_opt IUnknown **ppunkParent);
HRESULT ( STDMETHODCALLTYPE *FindFrame )(
__RPC__in ITargetFrame * This,
/* [in] */ __RPC__in LPCWSTR pszTargetName,
/* [in] */ __RPC__in_opt IUnknown *ppunkContextFrame,
/* [in] */ DWORD dwFlags,
/* [out] */ __RPC__deref_out_opt IUnknown **ppunkTargetFrame);
HRESULT ( STDMETHODCALLTYPE *SetFrameSrc )(
__RPC__in ITargetFrame * This,
/* [in] */ __RPC__in LPCWSTR pszFrameSrc);
HRESULT ( STDMETHODCALLTYPE *GetFrameSrc )(
__RPC__in ITargetFrame * This,
/* [out] */ __RPC__deref_out_opt LPWSTR *ppszFrameSrc);
HRESULT ( STDMETHODCALLTYPE *GetFramesContainer )(
__RPC__in ITargetFrame * This,
/* [out] */ __RPC__deref_out_opt IOleContainer **ppContainer);
HRESULT ( STDMETHODCALLTYPE *SetFrameOptions )(
__RPC__in ITargetFrame * This,
/* [in] */ DWORD dwFlags);
HRESULT ( STDMETHODCALLTYPE *GetFrameOptions )(
__RPC__in ITargetFrame * This,
/* [out] */ __RPC__out DWORD *pdwFlags);
HRESULT ( STDMETHODCALLTYPE *SetFrameMargins )(
__RPC__in ITargetFrame * This,
/* [in] */ DWORD dwWidth,
/* [in] */ DWORD dwHeight);
HRESULT ( STDMETHODCALLTYPE *GetFrameMargins )(
__RPC__in ITargetFrame * This,
/* [out] */ __RPC__out DWORD *pdwWidth,
/* [out] */ __RPC__out DWORD *pdwHeight);
HRESULT ( STDMETHODCALLTYPE *RemoteNavigate )(
__RPC__in ITargetFrame * This,
/* [in] */ ULONG cLength,
/* [size_is][in] */ __RPC__in_ecount_full(cLength) ULONG *pulData);
HRESULT ( STDMETHODCALLTYPE *OnChildFrameActivate )(
__RPC__in ITargetFrame * This,
/* [in] */ __RPC__in_opt IUnknown *pUnkChildFrame);
HRESULT ( STDMETHODCALLTYPE *OnChildFrameDeactivate )(
__RPC__in ITargetFrame * This,
/* [in] */ __RPC__in_opt IUnknown *pUnkChildFrame);
END_INTERFACE
} ITargetFrameVtbl;
interface ITargetFrame
{
CONST_VTBL struct ITargetFrameVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define ITargetFrame_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define ITargetFrame_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define ITargetFrame_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define ITargetFrame_SetFrameName(This,pszFrameName) \
( (This)->lpVtbl -> SetFrameName(This,pszFrameName) )
#define ITargetFrame_GetFrameName(This,ppszFrameName) \
( (This)->lpVtbl -> GetFrameName(This,ppszFrameName) )
#define ITargetFrame_GetParentFrame(This,ppunkParent) \
( (This)->lpVtbl -> GetParentFrame(This,ppunkParent) )
#define ITargetFrame_FindFrame(This,pszTargetName,ppunkContextFrame,dwFlags,ppunkTargetFrame) \
( (This)->lpVtbl -> FindFrame(This,pszTargetName,ppunkContextFrame,dwFlags,ppunkTargetFrame) )
#define ITargetFrame_SetFrameSrc(This,pszFrameSrc) \
( (This)->lpVtbl -> SetFrameSrc(This,pszFrameSrc) )
#define ITargetFrame_GetFrameSrc(This,ppszFrameSrc) \
( (This)->lpVtbl -> GetFrameSrc(This,ppszFrameSrc) )
#define ITargetFrame_GetFramesContainer(This,ppContainer) \
( (This)->lpVtbl -> GetFramesContainer(This,ppContainer) )
#define ITargetFrame_SetFrameOptions(This,dwFlags) \
( (This)->lpVtbl -> SetFrameOptions(This,dwFlags) )
#define ITargetFrame_GetFrameOptions(This,pdwFlags) \
( (This)->lpVtbl -> GetFrameOptions(This,pdwFlags) )
#define ITargetFrame_SetFrameMargins(This,dwWidth,dwHeight) \
( (This)->lpVtbl -> SetFrameMargins(This,dwWidth,dwHeight) )
#define ITargetFrame_GetFrameMargins(This,pdwWidth,pdwHeight) \
( (This)->lpVtbl -> GetFrameMargins(This,pdwWidth,pdwHeight) )
#define ITargetFrame_RemoteNavigate(This,cLength,pulData) \
( (This)->lpVtbl -> RemoteNavigate(This,cLength,pulData) )
#define ITargetFrame_OnChildFrameActivate(This,pUnkChildFrame) \
( (This)->lpVtbl -> OnChildFrameActivate(This,pUnkChildFrame) )
#define ITargetFrame_OnChildFrameDeactivate(This,pUnkChildFrame) \
( (This)->lpVtbl -> OnChildFrameDeactivate(This,pUnkChildFrame) )
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* __ITargetFrame_INTERFACE_DEFINED__ */
#ifndef __ITargetEmbedding_INTERFACE_DEFINED__
#define __ITargetEmbedding_INTERFACE_DEFINED__
/* interface ITargetEmbedding */
/* [unique][uuid][object] */
typedef /* [unique] */ __RPC_unique_pointer ITargetEmbedding *LPTARGETEMBEDDING;
EXTERN_C const IID IID_ITargetEmbedding;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("548793C0-9E74-11cf-9655-00A0C9034923")
ITargetEmbedding : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetTargetFrame(
/* [out] */ __RPC__deref_out_opt ITargetFrame **ppTargetFrame) = 0;
};
#else /* C style interface */
typedef struct ITargetEmbeddingVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
__RPC__in ITargetEmbedding * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in ITargetEmbedding * This);
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in ITargetEmbedding * This);
HRESULT ( STDMETHODCALLTYPE *GetTargetFrame )(
__RPC__in ITargetEmbedding * This,
/* [out] */ __RPC__deref_out_opt ITargetFrame **ppTargetFrame);
END_INTERFACE
} ITargetEmbeddingVtbl;
interface ITargetEmbedding
{
CONST_VTBL struct ITargetEmbeddingVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define ITargetEmbedding_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define ITargetEmbedding_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define ITargetEmbedding_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define ITargetEmbedding_GetTargetFrame(This,ppTargetFrame) \
( (This)->lpVtbl -> GetTargetFrame(This,ppTargetFrame) )
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* __ITargetEmbedding_INTERFACE_DEFINED__ */
#ifndef __ITargetFramePriv_INTERFACE_DEFINED__
#define __ITargetFramePriv_INTERFACE_DEFINED__
/* interface ITargetFramePriv */
/* [unique][uuid][object] */
typedef /* [unique] */ __RPC_unique_pointer ITargetFramePriv *LPTARGETFRAMEPRIV;
EXTERN_C const IID IID_ITargetFramePriv;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("9216E421-2BF5-11d0-82B4-00A0C90C29C5")
ITargetFramePriv : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE FindFrameDownwards(
/* [in] */ __RPC__in LPCWSTR pszTargetName,
/* [in] */ DWORD dwFlags,
/* [out] */ __RPC__deref_out_opt IUnknown **ppunkTargetFrame) = 0;
virtual HRESULT STDMETHODCALLTYPE FindFrameInContext(
/* [in] */ __RPC__in LPCWSTR pszTargetName,
/* [in] */ __RPC__in_opt IUnknown *punkContextFrame,
/* [in] */ DWORD dwFlags,
/* [out] */ __RPC__deref_out_opt IUnknown **ppunkTargetFrame) = 0;
virtual HRESULT STDMETHODCALLTYPE OnChildFrameActivate(
/* [in] */ __RPC__in_opt IUnknown *pUnkChildFrame) = 0;
virtual HRESULT STDMETHODCALLTYPE OnChildFrameDeactivate(
/* [in] */ __RPC__in_opt IUnknown *pUnkChildFrame) = 0;
virtual HRESULT STDMETHODCALLTYPE NavigateHack(
/* [in] */ DWORD grfHLNF,
/* [unique][in] */ __RPC__in_opt LPBC pbc,
/* [unique][in] */ __RPC__in_opt IBindStatusCallback *pibsc,
/* [unique][in] */ __RPC__in_opt LPCWSTR pszTargetName,
/* [in] */ __RPC__in LPCWSTR pszUrl,
/* [unique][in] */ __RPC__in_opt LPCWSTR pszLocation) = 0;
virtual HRESULT STDMETHODCALLTYPE FindBrowserByIndex(
/* [in] */ DWORD dwID,
/* [out] */ __RPC__deref_out_opt IUnknown **ppunkBrowser) = 0;
};
#else /* C style interface */
typedef struct ITargetFramePrivVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
__RPC__in ITargetFramePriv * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in ITargetFramePriv * This);
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in ITargetFramePriv * This);
HRESULT ( STDMETHODCALLTYPE *FindFrameDownwards )(
__RPC__in ITargetFramePriv * This,
/* [in] */ __RPC__in LPCWSTR pszTargetName,
/* [in] */ DWORD dwFlags,
/* [out] */ __RPC__deref_out_opt IUnknown **ppunkTargetFrame);
HRESULT ( STDMETHODCALLTYPE *FindFrameInContext )(
__RPC__in ITargetFramePriv * This,
/* [in] */ __RPC__in LPCWSTR pszTargetName,
/* [in] */ __RPC__in_opt IUnknown *punkContextFrame,
/* [in] */ DWORD dwFlags,
/* [out] */ __RPC__deref_out_opt IUnknown **ppunkTargetFrame);
HRESULT ( STDMETHODCALLTYPE *OnChildFrameActivate )(
__RPC__in ITargetFramePriv * This,
/* [in] */ __RPC__in_opt IUnknown *pUnkChildFrame);
HRESULT ( STDMETHODCALLTYPE *OnChildFrameDeactivate )(
__RPC__in ITargetFramePriv * This,
/* [in] */ __RPC__in_opt IUnknown *pUnkChildFrame);
HRESULT ( STDMETHODCALLTYPE *NavigateHack )(
__RPC__in ITargetFramePriv * This,
/* [in] */ DWORD grfHLNF,
/* [unique][in] */ __RPC__in_opt LPBC pbc,
/* [unique][in] */ __RPC__in_opt IBindStatusCallback *pibsc,
/* [unique][in] */ __RPC__in_opt LPCWSTR pszTargetName,
/* [in] */ __RPC__in LPCWSTR pszUrl,
/* [unique][in] */ __RPC__in_opt LPCWSTR pszLocation);
HRESULT ( STDMETHODCALLTYPE *FindBrowserByIndex )(
__RPC__in ITargetFramePriv * This,
/* [in] */ DWORD dwID,
/* [out] */ __RPC__deref_out_opt IUnknown **ppunkBrowser);
END_INTERFACE
} ITargetFramePrivVtbl;
interface ITargetFramePriv
{
CONST_VTBL struct ITargetFramePrivVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define ITargetFramePriv_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define ITargetFramePriv_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define ITargetFramePriv_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define ITargetFramePriv_FindFrameDownwards(This,pszTargetName,dwFlags,ppunkTargetFrame) \
( (This)->lpVtbl -> FindFrameDownwards(This,pszTargetName,dwFlags,ppunkTargetFrame) )
#define ITargetFramePriv_FindFrameInContext(This,pszTargetName,punkContextFrame,dwFlags,ppunkTargetFrame) \
( (This)->lpVtbl -> FindFrameInContext(This,pszTargetName,punkContextFrame,dwFlags,ppunkTargetFrame) )
#define ITargetFramePriv_OnChildFrameActivate(This,pUnkChildFrame) \
( (This)->lpVtbl -> OnChildFrameActivate(This,pUnkChildFrame) )
#define ITargetFramePriv_OnChildFrameDeactivate(This,pUnkChildFrame) \
( (This)->lpVtbl -> OnChildFrameDeactivate(This,pUnkChildFrame) )
#define ITargetFramePriv_NavigateHack(This,grfHLNF,pbc,pibsc,pszTargetName,pszUrl,pszLocation) \
( (This)->lpVtbl -> NavigateHack(This,grfHLNF,pbc,pibsc,pszTargetName,pszUrl,pszLocation) )
#define ITargetFramePriv_FindBrowserByIndex(This,dwID,ppunkBrowser) \
( (This)->lpVtbl -> FindBrowserByIndex(This,dwID,ppunkBrowser) )
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* __ITargetFramePriv_INTERFACE_DEFINED__ */
#ifndef __ITargetFramePriv2_INTERFACE_DEFINED__
#define __ITargetFramePriv2_INTERFACE_DEFINED__
/* interface ITargetFramePriv2 */
/* [unique][uuid][object] */
typedef /* [unique] */ __RPC_unique_pointer ITargetFramePriv2 *LPTARGETFRAMEPRIV2;
EXTERN_C const IID IID_ITargetFramePriv2;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("B2C867E6-69D6-46F2-A611-DED9A4BD7FEF")
ITargetFramePriv2 : public ITargetFramePriv
{
public:
virtual HRESULT STDMETHODCALLTYPE AggregatedNavigation2(
/* [in] */ DWORD grfHLNF,
/* [unique][in] */ __RPC__in_opt LPBC pbc,
/* [unique][in] */ __RPC__in_opt IBindStatusCallback *pibsc,
/* [unique][in] */ __RPC__in_opt LPCWSTR pszTargetName,
/* [in] */ __RPC__in_opt IUri *pUri,
/* [unique][in] */ __RPC__in_opt LPCWSTR pszLocation) = 0;
};
#else /* C style interface */
typedef struct ITargetFramePriv2Vtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
__RPC__in ITargetFramePriv2 * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in ITargetFramePriv2 * This);
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in ITargetFramePriv2 * This);
HRESULT ( STDMETHODCALLTYPE *FindFrameDownwards )(
__RPC__in ITargetFramePriv2 * This,
/* [in] */ __RPC__in LPCWSTR pszTargetName,
/* [in] */ DWORD dwFlags,
/* [out] */ __RPC__deref_out_opt IUnknown **ppunkTargetFrame);
HRESULT ( STDMETHODCALLTYPE *FindFrameInContext )(
__RPC__in ITargetFramePriv2 * This,
/* [in] */ __RPC__in LPCWSTR pszTargetName,
/* [in] */ __RPC__in_opt IUnknown *punkContextFrame,
/* [in] */ DWORD dwFlags,
/* [out] */ __RPC__deref_out_opt IUnknown **ppunkTargetFrame);
HRESULT ( STDMETHODCALLTYPE *OnChildFrameActivate )(
__RPC__in ITargetFramePriv2 * This,
/* [in] */ __RPC__in_opt IUnknown *pUnkChildFrame);
HRESULT ( STDMETHODCALLTYPE *OnChildFrameDeactivate )(
__RPC__in ITargetFramePriv2 * This,
/* [in] */ __RPC__in_opt IUnknown *pUnkChildFrame);
HRESULT ( STDMETHODCALLTYPE *NavigateHack )(
__RPC__in ITargetFramePriv2 * This,
/* [in] */ DWORD grfHLNF,
/* [unique][in] */ __RPC__in_opt LPBC pbc,
/* [unique][in] */ __RPC__in_opt IBindStatusCallback *pibsc,
/* [unique][in] */ __RPC__in_opt LPCWSTR pszTargetName,
/* [in] */ __RPC__in LPCWSTR pszUrl,
/* [unique][in] */ __RPC__in_opt LPCWSTR pszLocation);
HRESULT ( STDMETHODCALLTYPE *FindBrowserByIndex )(
__RPC__in ITargetFramePriv2 * This,
/* [in] */ DWORD dwID,
/* [out] */ __RPC__deref_out_opt IUnknown **ppunkBrowser);
HRESULT ( STDMETHODCALLTYPE *AggregatedNavigation2 )(
__RPC__in ITargetFramePriv2 * This,
/* [in] */ DWORD grfHLNF,
/* [unique][in] */ __RPC__in_opt LPBC pbc,
/* [unique][in] */ __RPC__in_opt IBindStatusCallback *pibsc,
/* [unique][in] */ __RPC__in_opt LPCWSTR pszTargetName,
/* [in] */ __RPC__in_opt IUri *pUri,
/* [unique][in] */ __RPC__in_opt LPCWSTR pszLocation);
END_INTERFACE
} ITargetFramePriv2Vtbl;
interface ITargetFramePriv2
{
CONST_VTBL struct ITargetFramePriv2Vtbl *lpVtbl;
};
#ifdef COBJMACROS
#define ITargetFramePriv2_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define ITargetFramePriv2_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define ITargetFramePriv2_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define ITargetFramePriv2_FindFrameDownwards(This,pszTargetName,dwFlags,ppunkTargetFrame) \
( (This)->lpVtbl -> FindFrameDownwards(This,pszTargetName,dwFlags,ppunkTargetFrame) )
#define ITargetFramePriv2_FindFrameInContext(This,pszTargetName,punkContextFrame,dwFlags,ppunkTargetFrame) \
( (This)->lpVtbl -> FindFrameInContext(This,pszTargetName,punkContextFrame,dwFlags,ppunkTargetFrame) )
#define ITargetFramePriv2_OnChildFrameActivate(This,pUnkChildFrame) \
( (This)->lpVtbl -> OnChildFrameActivate(This,pUnkChildFrame) )
#define ITargetFramePriv2_OnChildFrameDeactivate(This,pUnkChildFrame) \
( (This)->lpVtbl -> OnChildFrameDeactivate(This,pUnkChildFrame) )
#define ITargetFramePriv2_NavigateHack(This,grfHLNF,pbc,pibsc,pszTargetName,pszUrl,pszLocation) \
( (This)->lpVtbl -> NavigateHack(This,grfHLNF,pbc,pibsc,pszTargetName,pszUrl,pszLocation) )
#define ITargetFramePriv2_FindBrowserByIndex(This,dwID,ppunkBrowser) \
( (This)->lpVtbl -> FindBrowserByIndex(This,dwID,ppunkBrowser) )
#define ITargetFramePriv2_AggregatedNavigation2(This,grfHLNF,pbc,pibsc,pszTargetName,pUri,pszLocation) \
( (This)->lpVtbl -> AggregatedNavigation2(This,grfHLNF,pbc,pibsc,pszTargetName,pUri,pszLocation) )
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* __ITargetFramePriv2_INTERFACE_DEFINED__ */
/* interface __MIDL_itf_htiface_0000_0004 */
/* [local] */
#endif
#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */
#pragma endregion
extern RPC_IF_HANDLE __MIDL_itf_htiface_0000_0004_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_htiface_0000_0004_v0_0_s_ifspec;
/* Additional Prototypes for ALL interfaces */
/* end of Additional Prototypes */
#ifdef __cplusplus
}
#endif
#endif
|
2bfa751010963dab22d81aa662e8ad4adfe3653f
|
7664f318ed04bd0680f3d82321c18896e3ef6ad5
|
/src/overlays/actors/ovl_Arms_Hook/z_arms_hook.c
|
a26f027ca615bc52b6aa1016da6ca6d8009f1027
|
[] |
no_license
|
zeldaret/oot
|
9c80ce17f2d8fd61514b375f92ee4739b5ce9d4e
|
2875ab4fcf5c5f81d76353d1ee0024c9ea8d0b23
|
refs/heads/master
| 2023-08-29T05:29:31.356427
| 2023-08-28T22:48:52
| 2023-08-28T22:48:52
| 247,875,738
| 4,401
| 802
| null | 2023-09-14T13:34:38
| 2020-03-17T04:02:19
|
C
|
UTF-8
|
C
| false
| false
| 13,094
|
c
|
z_arms_hook.c
|
#include "z_arms_hook.h"
#include "assets/objects/object_link_boy/object_link_boy.h"
#define FLAGS (ACTOR_FLAG_4 | ACTOR_FLAG_5)
void ArmsHook_Init(Actor* thisx, PlayState* play);
void ArmsHook_Destroy(Actor* thisx, PlayState* play);
void ArmsHook_Update(Actor* thisx, PlayState* play);
void ArmsHook_Draw(Actor* thisx, PlayState* play);
void ArmsHook_Wait(ArmsHook* this, PlayState* play);
void ArmsHook_Shoot(ArmsHook* this, PlayState* play);
ActorInit Arms_Hook_InitVars = {
ACTOR_ARMS_HOOK,
ACTORCAT_ITEMACTION,
FLAGS,
OBJECT_LINK_BOY,
sizeof(ArmsHook),
(ActorFunc)ArmsHook_Init,
(ActorFunc)ArmsHook_Destroy,
(ActorFunc)ArmsHook_Update,
(ActorFunc)ArmsHook_Draw,
};
static ColliderQuadInit sQuadInit = {
{
COLTYPE_NONE,
AT_ON | AT_TYPE_PLAYER,
AC_NONE,
OC1_NONE,
OC2_TYPE_PLAYER,
COLSHAPE_QUAD,
},
{
ELEMTYPE_UNK2,
{ 0x00000080, 0x00, 0x01 },
{ 0xFFCFFFFF, 0x00, 0x00 },
TOUCH_ON | TOUCH_NEAREST | TOUCH_SFX_NORMAL,
BUMP_NONE,
OCELEM_NONE,
},
{ { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } } },
};
static Vec3f sUnusedVec1 = { 0.0f, 0.5f, 0.0f };
static Vec3f sUnusedVec2 = { 0.0f, 0.5f, 0.0f };
static Color_RGB8 sUnusedColors[] = {
{ 255, 255, 100 },
{ 255, 255, 50 },
};
static Vec3f D_80865B70 = { 0.0f, 0.0f, 0.0f };
static Vec3f D_80865B7C = { 0.0f, 0.0f, 900.0f };
static Vec3f D_80865B88 = { 0.0f, 500.0f, -3000.0f };
static Vec3f D_80865B94 = { 0.0f, -500.0f, -3000.0f };
static Vec3f D_80865BA0 = { 0.0f, 500.0f, 1200.0f };
static Vec3f D_80865BAC = { 0.0f, -500.0f, 1200.0f };
void ArmsHook_SetupAction(ArmsHook* this, ArmsHookActionFunc actionFunc) {
this->actionFunc = actionFunc;
}
void ArmsHook_Init(Actor* thisx, PlayState* play) {
ArmsHook* this = (ArmsHook*)thisx;
Collider_InitQuad(play, &this->collider);
Collider_SetQuad(play, &this->collider, &this->actor, &sQuadInit);
ArmsHook_SetupAction(this, ArmsHook_Wait);
this->unk_1E8 = this->actor.world.pos;
}
void ArmsHook_Destroy(Actor* thisx, PlayState* play) {
ArmsHook* this = (ArmsHook*)thisx;
if (this->grabbed != NULL) {
this->grabbed->flags &= ~ACTOR_FLAG_13;
}
Collider_DestroyQuad(play, &this->collider);
}
void ArmsHook_Wait(ArmsHook* this, PlayState* play) {
if (this->actor.parent == NULL) {
Player* player = GET_PLAYER(play);
// get correct timer length for hookshot or longshot
s32 length = (player->heldItemAction == PLAYER_IA_HOOKSHOT) ? 13 : 26;
ArmsHook_SetupAction(this, ArmsHook_Shoot);
Actor_SetProjectileSpeed(&this->actor, 20.0f);
this->actor.parent = &GET_PLAYER(play)->actor;
this->timer = length;
}
}
void func_80865044(ArmsHook* this) {
this->actor.child = this->actor.parent;
this->actor.parent->parent = &this->actor;
}
s32 ArmsHook_AttachToPlayer(ArmsHook* this, Player* player) {
player->actor.child = &this->actor;
player->heldActor = &this->actor;
if (this->actor.child != NULL) {
player->actor.parent = NULL;
this->actor.child = NULL;
return true;
}
return false;
}
void ArmsHook_DetachHookFromActor(ArmsHook* this) {
if (this->grabbed != NULL) {
this->grabbed->flags &= ~ACTOR_FLAG_13;
this->grabbed = NULL;
}
}
s32 ArmsHook_CheckForCancel(ArmsHook* this) {
Player* player = (Player*)this->actor.parent;
if (Player_HoldsHookshot(player)) {
if ((player->itemAction != player->heldItemAction) || (player->actor.flags & ACTOR_FLAG_8) ||
((player->stateFlags1 & (PLAYER_STATE1_7 | PLAYER_STATE1_26)))) {
this->timer = 0;
ArmsHook_DetachHookFromActor(this);
Math_Vec3f_Copy(&this->actor.world.pos, &player->unk_3C8);
return 1;
}
}
return 0;
}
void ArmsHook_AttachHookToActor(ArmsHook* this, Actor* actor) {
actor->flags |= ACTOR_FLAG_13;
this->grabbed = actor;
Math_Vec3f_Diff(&actor->world.pos, &this->actor.world.pos, &this->grabbedDistDiff);
}
void ArmsHook_Shoot(ArmsHook* this, PlayState* play) {
Player* player = GET_PLAYER(play);
Actor* touchedActor;
Actor* grabbed;
Vec3f bodyDistDiffVec;
Vec3f newPos;
f32 bodyDistDiff;
f32 phi_f16;
DynaPolyActor* dynaPolyActor;
f32 curGrabbedDist;
f32 grabbedDist;
s32 pad;
CollisionPoly* poly;
s32 bgId;
Vec3f intersectPos;
Vec3f prevFrameDiff;
Vec3f sp60;
f32 polyNormalX;
f32 polyNormalZ;
f32 velocity;
s32 pad1;
if ((this->actor.parent == NULL) || (!Player_HoldsHookshot(player))) {
ArmsHook_DetachHookFromActor(this);
Actor_Kill(&this->actor);
return;
}
func_8002F8F0(&player->actor, NA_SE_IT_HOOKSHOT_CHAIN - SFX_FLAG);
ArmsHook_CheckForCancel(this);
if ((this->timer != 0) && (this->collider.base.atFlags & AT_HIT) &&
(this->collider.info.atHitInfo->elemType != ELEMTYPE_UNK4)) {
touchedActor = this->collider.base.at;
if ((touchedActor->update != NULL) && (touchedActor->flags & (ACTOR_FLAG_9 | ACTOR_FLAG_10))) {
if (this->collider.info.atHitInfo->bumperFlags & BUMP_HOOKABLE) {
ArmsHook_AttachHookToActor(this, touchedActor);
if (CHECK_FLAG_ALL(touchedActor->flags, ACTOR_FLAG_10)) {
func_80865044(this);
}
}
}
this->timer = 0;
Audio_PlaySfxGeneral(NA_SE_IT_ARROW_STICK_CRE, &this->actor.projectedPos, 4, &gSfxDefaultFreqAndVolScale,
&gSfxDefaultFreqAndVolScale, &gSfxDefaultReverb);
} else if (DECR(this->timer) == 0) {
grabbed = this->grabbed;
if (grabbed != NULL) {
if ((grabbed->update == NULL) || !CHECK_FLAG_ALL(grabbed->flags, ACTOR_FLAG_13)) {
grabbed = NULL;
this->grabbed = NULL;
} else if (this->actor.child != NULL) {
curGrabbedDist = Actor_WorldDistXYZToActor(&this->actor, grabbed);
grabbedDist =
sqrtf(SQ(this->grabbedDistDiff.x) + SQ(this->grabbedDistDiff.y) + SQ(this->grabbedDistDiff.z));
Math_Vec3f_Diff(&grabbed->world.pos, &this->grabbedDistDiff, &this->actor.world.pos);
if ((curGrabbedDist - grabbedDist) > 50.0f) {
ArmsHook_DetachHookFromActor(this);
grabbed = NULL;
}
}
}
bodyDistDiff = Math_Vec3f_DistXYZAndStoreDiff(&player->unk_3C8, &this->actor.world.pos, &bodyDistDiffVec);
if (bodyDistDiff < 30.0f) {
velocity = 0.0f;
phi_f16 = 0.0f;
} else {
if (this->actor.child != NULL) {
velocity = 30.0f;
} else if (grabbed != NULL) {
velocity = 50.0f;
} else {
velocity = 200.0f;
}
phi_f16 = bodyDistDiff - velocity;
if (bodyDistDiff <= velocity) {
phi_f16 = 0.0f;
}
velocity = phi_f16 / bodyDistDiff;
}
newPos.x = bodyDistDiffVec.x * velocity;
newPos.y = bodyDistDiffVec.y * velocity;
newPos.z = bodyDistDiffVec.z * velocity;
if (this->actor.child == NULL) {
if ((grabbed != NULL) && (grabbed->id == ACTOR_BG_SPOT06_OBJECTS)) {
Math_Vec3f_Diff(&grabbed->world.pos, &this->grabbedDistDiff, &this->actor.world.pos);
phi_f16 = 1.0f;
} else {
Math_Vec3f_Sum(&player->unk_3C8, &newPos, &this->actor.world.pos);
if (grabbed != NULL) {
Math_Vec3f_Sum(&this->actor.world.pos, &this->grabbedDistDiff, &grabbed->world.pos);
}
}
} else {
Math_Vec3f_Diff(&bodyDistDiffVec, &newPos, &player->actor.velocity);
player->actor.world.rot.x =
Math_Atan2S(sqrtf(SQ(bodyDistDiffVec.x) + SQ(bodyDistDiffVec.z)), -bodyDistDiffVec.y);
}
if (phi_f16 < 50.0f) {
ArmsHook_DetachHookFromActor(this);
if (phi_f16 == 0.0f) {
ArmsHook_SetupAction(this, ArmsHook_Wait);
if (ArmsHook_AttachToPlayer(this, player)) {
Math_Vec3f_Diff(&this->actor.world.pos, &player->actor.world.pos, &player->actor.velocity);
player->actor.velocity.y -= 20.0f;
}
}
}
} else {
Actor_MoveXZGravity(&this->actor);
Math_Vec3f_Diff(&this->actor.world.pos, &this->actor.prevPos, &prevFrameDiff);
Math_Vec3f_Sum(&this->unk_1E8, &prevFrameDiff, &this->unk_1E8);
this->actor.shape.rot.x = Math_Atan2S(this->actor.speed, -this->actor.velocity.y);
sp60.x = this->unk_1F4.x - (this->unk_1E8.x - this->unk_1F4.x);
sp60.y = this->unk_1F4.y - (this->unk_1E8.y - this->unk_1F4.y);
sp60.z = this->unk_1F4.z - (this->unk_1E8.z - this->unk_1F4.z);
if (BgCheck_EntityLineTest1(&play->colCtx, &sp60, &this->unk_1E8, &intersectPos, &poly, true, true, true, true,
&bgId) &&
!func_8002F9EC(play, &this->actor, poly, bgId, &intersectPos)) {
polyNormalX = COLPOLY_GET_NORMAL(poly->normal.x);
polyNormalZ = COLPOLY_GET_NORMAL(poly->normal.z);
Math_Vec3f_Copy(&this->actor.world.pos, &intersectPos);
this->actor.world.pos.x += 10.0f * polyNormalX;
this->actor.world.pos.z += 10.0f * polyNormalZ;
this->timer = 0;
if (SurfaceType_CanHookshot(&play->colCtx, poly, bgId)) {
if (bgId != BGCHECK_SCENE) {
dynaPolyActor = DynaPoly_GetActor(&play->colCtx, bgId);
if (dynaPolyActor != NULL) {
ArmsHook_AttachHookToActor(this, &dynaPolyActor->actor);
}
}
func_80865044(this);
Audio_PlaySfxGeneral(NA_SE_IT_HOOKSHOT_STICK_OBJ, &this->actor.projectedPos, 4,
&gSfxDefaultFreqAndVolScale, &gSfxDefaultFreqAndVolScale, &gSfxDefaultReverb);
} else {
CollisionCheck_SpawnShieldParticlesMetal(play, &this->actor.world.pos);
Audio_PlaySfxGeneral(NA_SE_IT_HOOKSHOT_REFLECT, &this->actor.projectedPos, 4,
&gSfxDefaultFreqAndVolScale, &gSfxDefaultFreqAndVolScale, &gSfxDefaultReverb);
}
} else if (CHECK_BTN_ANY(play->state.input[0].press.button,
(BTN_A | BTN_B | BTN_R | BTN_CUP | BTN_CLEFT | BTN_CRIGHT | BTN_CDOWN))) {
this->timer = 0;
}
}
}
void ArmsHook_Update(Actor* thisx, PlayState* play) {
ArmsHook* this = (ArmsHook*)thisx;
this->actionFunc(this, play);
this->unk_1F4 = this->unk_1E8;
}
void ArmsHook_Draw(Actor* thisx, PlayState* play) {
s32 pad;
ArmsHook* this = (ArmsHook*)thisx;
Player* player = GET_PLAYER(play);
Vec3f sp78;
Vec3f hookNewTip;
Vec3f hookNewBase;
f32 sp5C;
f32 sp58;
if ((player->actor.draw != NULL) && (player->rightHandType == PLAYER_MODELTYPE_RH_HOOKSHOT)) {
OPEN_DISPS(play->state.gfxCtx, "../z_arms_hook.c", 850);
if ((ArmsHook_Shoot != this->actionFunc) || (this->timer <= 0)) {
Matrix_MultVec3f(&D_80865B70, &this->unk_1E8);
Matrix_MultVec3f(&D_80865B88, &hookNewTip);
Matrix_MultVec3f(&D_80865B94, &hookNewBase);
this->hookInfo.active = 0;
} else {
Matrix_MultVec3f(&D_80865B7C, &this->unk_1E8);
Matrix_MultVec3f(&D_80865BA0, &hookNewTip);
Matrix_MultVec3f(&D_80865BAC, &hookNewBase);
}
func_80090480(play, &this->collider, &this->hookInfo, &hookNewTip, &hookNewBase);
Gfx_SetupDL_25Opa(play->state.gfxCtx);
gSPMatrix(POLY_OPA_DISP++, Matrix_NewMtx(play->state.gfxCtx, "../z_arms_hook.c", 895),
G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW);
gSPDisplayList(POLY_OPA_DISP++, gLinkAdultHookshotTipDL);
Matrix_Translate(this->actor.world.pos.x, this->actor.world.pos.y, this->actor.world.pos.z, MTXMODE_NEW);
Math_Vec3f_Diff(&player->unk_3C8, &this->actor.world.pos, &sp78);
sp58 = SQ(sp78.x) + SQ(sp78.z);
sp5C = sqrtf(sp58);
Matrix_RotateY(Math_FAtan2F(sp78.x, sp78.z), MTXMODE_APPLY);
Matrix_RotateX(Math_FAtan2F(-sp78.y, sp5C), MTXMODE_APPLY);
Matrix_Scale(0.015f, 0.015f, sqrtf(SQ(sp78.y) + sp58) * 0.01f, MTXMODE_APPLY);
gSPMatrix(POLY_OPA_DISP++, Matrix_NewMtx(play->state.gfxCtx, "../z_arms_hook.c", 910),
G_MTX_NOPUSH | G_MTX_LOAD | G_MTX_MODELVIEW);
gSPDisplayList(POLY_OPA_DISP++, gLinkAdultHookshotChainDL);
CLOSE_DISPS(play->state.gfxCtx, "../z_arms_hook.c", 913);
}
}
|
dad9081af8581248e63bdd2cc26a900f3b96b59e
|
65089dbc386e1184983c15fe3a2282763ae65960
|
/include/libposix.h
|
d31b30fb5da416cf25dc601d2bec81ad3c48193d
|
[
"MIT"
] |
permissive
|
gozfree/gear-lib
|
9f4db1bce799ded1cf1f3411cb51bdfbcbe7c7bc
|
bffbfd25af4ff7b04ebfafdab391b55270b0273e
|
refs/heads/master
| 2023-08-14T16:01:29.449910
| 2023-07-24T16:08:47
| 2023-07-24T16:09:41
| 40,359,871
| 1,771
| 488
|
MIT
| 2023-05-27T11:08:46
| 2015-08-07T12:41:05
|
C
|
UTF-8
|
C
| false
| false
| 31
|
h
|
libposix.h
|
../gear-lib/libposix/libposix.h
|
c4cffd6a5e71ed3fa8c920a797161bca0bc29e8f
|
a5a99f646e371b45974a6fb6ccc06b0a674818f2
|
/RecoLocalMuon/CSCValidation/macros/myFunctions_OLD.C
|
baf3f665ec9cacb5e9a330a4307ff4d0a5085842
|
[
"Apache-2.0"
] |
permissive
|
cms-sw/cmssw
|
4ecd2c1105d59c66d385551230542c6615b9ab58
|
19c178740257eb48367778593da55dcad08b7a4f
|
refs/heads/master
| 2023-08-23T21:57:42.491143
| 2023-08-22T20:22:40
| 2023-08-22T20:22:40
| 10,969,551
| 1,006
| 3,696
|
Apache-2.0
| 2023-09-14T19:14:28
| 2013-06-26T14:09:07
|
C++
|
UTF-8
|
C
| false
| false
| 63,541
|
c
|
myFunctions_OLD.C
|
TFile *OpenFiles(std::string path) {
TFile *f;
f = new TFile(path.c_str(), "READ");
return f;
}
void printEmptyChambers(std::string histoname, std::string oname, TFile *f) {
TH2I *plot = (TH2I *)f->Get(histoname.c_str());
std::string endcap, chamber;
int limitr, limitc;
std::vector<string> deadchambers;
for (int e = 0; e < 2; e++) {
for (int s = 0; s < 4; s++) {
if (s == 0)
limitr = 4;
if (s == 1 || s == 2)
limitr = 2;
if (s == 3)
limitr = 1;
for (int r = 0; r < limitr; r++) {
if (s == 0)
limitc = 36;
if (s != 0 && r == 0)
limitc = 18;
if (s != 0 && r == 1)
limitc = 36;
for (int c = 0; c < limitc; c++) {
int type = 0;
if (s == 0 && r == 0)
type = 2;
else if (s == 0 && r == 1)
type = 3;
else if (s == 0 && r == 2)
type = 4;
else if (s == 0 && r == 3)
type = 1;
else
type = (s + 1) * 2 + (r + 1);
if (e == 0)
type = type + 10;
if (e == 1)
type = 11 - type;
int bin = plot->GetBin((c + 1), type);
float content = plot->GetBinContent(bin);
std::ostringstream oss;
if (e == 0)
endcap = "+";
if (e == 1)
endcap = "-";
oss << "ME " << endcap << (s + 1) << "/" << (r + 1) << "/" << (c + 1);
chamber = oss.str();
if (content == 0) {
if (oname == "wire digis" && (s == 0 && r == 3))
continue;
else
deadchambers.push_back(chamber);
}
}
}
}
}
int n_dc = deadchambers.size();
ofstream file;
file.open("deadchamberlist.txt", ios::app);
file << "Chambers with missing " << oname << "...\n" << endl;
if (n_dc > 0) {
for (int n = 0; n < n_dc; n++) {
file << deadchambers[n] << endl;
}
}
file << "\n\n\n\n";
file.close();
}
void make1DPlot(std::string histoname, TFile *f1, std::string histotitle, int statoption, std::string savename) {
TH1F *h1 = (TH1F *)f1->Get(histoname.c_str());
TCanvas *c = new TCanvas("c", "my canvas", 1);
if (h1) {
if (statoption == 0)
gStyle->SetOptStat(kFALSE);
else
gStyle->SetOptStat(statoption);
gStyle->SetHistFillColor(92);
gStyle->SetFrameFillColor(4000);
gStyle->SetTitleW(0.7);
gStyle->SetTitleH(0.07);
gPad->SetFillColor(4000);
c->SetFillStyle(4000);
gStyle->SetStatColor(0);
gStyle->SetTitleFillColor(0);
h1->UseCurrentStyle();
h1->SetTitle(histotitle.c_str());
h1->GetXaxis()->SetLabelSize(0.04);
h1->GetYaxis()->SetLabelSize(0.04);
h1->GetXaxis()->SetTitleOffset(0.7);
h1->GetXaxis()->SetTitleSize(0.06);
h1->GetXaxis()->SetNdivisions(208, kTRUE);
h1->Draw();
c->Update();
c->Print(savename.c_str(), "png");
}
delete c;
}
void makeCSCOccupancy(std::string histoname, TFile *f1, std::string histotitle, std::string savename) {
TH1F *h1 = (TH1F *)f1->Get(histoname.c_str());
TCanvas *c = new TCanvas("c", "my canvas", 1);
if (h1) {
gStyle->SetOptStat(kFALSE);
gStyle->SetHistFillColor(92);
gStyle->SetFrameFillColor(4000);
gStyle->SetTitleW(0.7);
gStyle->SetTitleH(0.07);
gPad->SetFillColor(4000);
c->SetFillStyle(4000);
gStyle->SetStatColor(0);
gStyle->SetTitleFillColor(0);
h1->UseCurrentStyle();
h1->SetTitle(histotitle.c_str());
h1->GetXaxis()->SetLabelSize(0.04);
h1->GetYaxis()->SetLabelSize(0.04);
h1->GetXaxis()->SetTitleOffset(0.7);
h1->GetXaxis()->SetTitleSize(0.06);
h1->GetXaxis()->SetNdivisions(208, kTRUE);
h1->GetXaxis()->SetBinLabel(2, "Total Events");
h1->GetXaxis()->SetBinLabel(4, "# Events with Wires");
h1->GetXaxis()->SetBinLabel(6, "# Events with Strips");
h1->GetXaxis()->SetBinLabel(8, "# Events with Wires&Strips");
h1->GetXaxis()->SetBinLabel(10, "# Events with Rechits");
h1->GetXaxis()->SetBinLabel(12, "# Events with Segments");
h1->GetXaxis()->SetBinLabel(14, "Events Rejected");
h1->Draw();
c->Update();
c->Print(savename.c_str(), "png");
}
delete c;
}
void make1DPlot2(std::string histoname1,
std::string histoname2,
int statoption,
TFile *f1,
std::string t1,
std::string t2,
std::string savename) {
// use this if you want two plots on one canvas
TH1F *a1 = (TH1F *)f1->Get(histoname1.c_str());
TH1F *b1 = (TH1F *)f1->Get(histoname2.c_str());
TCanvas *c = new TCanvas("c", "my canvas", 1);
c->Divide(1, 2);
if (a1) {
c->cd(1);
if (statoption == 0)
gStyle->SetOptStat(kFALSE);
else
gStyle->SetOptStat(statoption);
gStyle->SetHistFillColor(92);
gStyle->SetFrameFillColor(4000);
gStyle->SetTitleW(0.4);
gStyle->SetTitleH(0.09);
gStyle->SetStatColor(0);
gStyle->SetTitleFillColor(0);
gPad->SetFillColor(4000);
c->SetFillStyle(4000);
a1->UseCurrentStyle();
a1->SetTitle(t1.c_str());
a1->GetXaxis()->SetLabelSize(0.06);
a1->GetYaxis()->SetLabelSize(0.06);
a1->GetXaxis()->SetTitleOffset(0.7);
a1->GetXaxis()->SetTitleSize(0.06);
a1->GetXaxis()->SetNdivisions(208, kTRUE);
a1->Draw();
}
if (b1) {
gStyle->SetHistFillColor(72);
b1->UseCurrentStyle();
t2 = t2 + " (run " + run + ")";
b1->SetTitle(t2.c_str());
b1->GetXaxis()->SetLabelSize(0.06);
b1->GetYaxis()->SetLabelSize(0.06);
b1->GetXaxis()->SetTitleOffset(0.7);
b1->GetXaxis()->SetTitleSize(0.06);
b1->GetXaxis()->SetNdivisions(508, kTRUE);
c->cd(2);
b1->Draw();
}
c->Update();
c->Print(savename.c_str(), "png");
delete c;
}
void makeEffGif(std::string histoname, TFile *f1, std::string histotitle, std::string savename) {
TH1F *ho = (TH1F *)f1->Get(histoname.c_str());
TCanvas *c = new TCanvas("c", "my canvas", 1);
TH1F *hn = new TH1F("tmp", histotitle.c_str(), 20, 0.5, 20.5);
if (ho) {
float Num = 1;
float Den = 1;
for (int i = 0; i < 20; i++) {
Num = ho->GetBinContent(i + 1);
Den = ho->GetBinContent(i + 21);
//getEfficiency(Num, Den, eff);
float Eff = 0.;
float EffE = 0.;
if (fabs(Den) > 0.000000001) {
Eff = Num / Den;
if (Num < Den) {
EffE = sqrt((1. - Eff) * Eff / Den);
}
}
hn->SetBinContent(i + 1, Eff);
hn->SetBinError(i + 1, EffE);
}
gStyle->SetOptStat(kFALSE);
gStyle->SetHistFillColor(92);
gStyle->SetFrameFillColor(4000);
gStyle->SetTitleW(0.7);
gStyle->SetTitleH(0.07);
gPad->SetFillColor(4000);
gStyle->SetStatColor(0);
gStyle->SetTitleFillColor(0);
c->SetFillStyle(4000);
hn->UseCurrentStyle();
hn->SetTitle(histotitle.c_str());
hn->GetXaxis()->SetLabelSize(0.04);
hn->GetYaxis()->SetLabelSize(0.04);
hn->GetXaxis()->SetTitleOffset(0.7);
hn->GetXaxis()->SetTitleSize(0.06);
hn->GetXaxis()->SetNdivisions(208, kTRUE);
hn->GetYaxis()->SetRangeUser(0.5, 1.1);
hn->SetMarkerStyle(6);
hn->GetXaxis()->SetBinLabel(1, "ME +1/1b");
hn->GetXaxis()->SetBinLabel(2, "ME +1/2");
hn->GetXaxis()->SetBinLabel(3, "ME +1/3");
hn->GetXaxis()->SetBinLabel(4, "ME +1/1a");
hn->GetXaxis()->SetBinLabel(5, "ME +2/1");
hn->GetXaxis()->SetBinLabel(6, "ME +2/2");
hn->GetXaxis()->SetBinLabel(7, "ME +3/1");
hn->GetXaxis()->SetBinLabel(8, "ME +3/2");
hn->GetXaxis()->SetBinLabel(9, "ME +4/1");
hn->GetXaxis()->SetBinLabel(10, "ME +4/2");
hn->GetXaxis()->SetBinLabel(11, "ME -1/1b");
hn->GetXaxis()->SetBinLabel(12, "ME -1/2");
hn->GetXaxis()->SetBinLabel(13, "ME -1/3");
hn->GetXaxis()->SetBinLabel(14, "ME -1/1a");
hn->GetXaxis()->SetBinLabel(15, "ME -2/1");
hn->GetXaxis()->SetBinLabel(16, "ME -2/2");
hn->GetXaxis()->SetBinLabel(17, "ME -3/1");
hn->GetXaxis()->SetBinLabel(18, "ME -3/2");
hn->GetXaxis()->SetBinLabel(19, "ME -4/1");
hn->GetXaxis()->SetBinLabel(20, "ME -4/2");
hn->Draw();
c->Update();
c->Print(savename.c_str(), "png");
}
delete c;
delete hn;
}
void Draw2DProfile(std::string histoname, TFile *f1, std::string title, std::string option, std::string savename) {
TProfile2D *test = f1->Get(histoname.c_str());
TH2D *plot = test->ProjectionXY("test2", option.c_str());
if (plot) {
TCanvas *c = new TCanvas("c", "my canvas", 1);
gStyle->SetPalette(1, 0);
gPad->SetFillColor(4000);
c->SetFillStyle(4000);
gStyle->SetStatColor(0);
gStyle->SetTitleFillColor(0);
plot->SetStats(kFALSE);
plot->GetYaxis()->SetBinLabel(1, "ME- 4/1");
plot->GetYaxis()->SetBinLabel(2, "ME- 3/2");
plot->GetYaxis()->SetBinLabel(3, "ME- 3/1");
plot->GetYaxis()->SetBinLabel(4, "ME- 2/2");
plot->GetYaxis()->SetBinLabel(5, "ME- 2/1");
plot->GetYaxis()->SetBinLabel(6, "ME- 1/3");
plot->GetYaxis()->SetBinLabel(7, "ME- 1/2");
plot->GetYaxis()->SetBinLabel(8, "ME- 1/1b");
plot->GetYaxis()->SetBinLabel(9, "ME- 1/1a");
plot->GetYaxis()->SetBinLabel(10, "ME+ 1/1a");
plot->GetYaxis()->SetBinLabel(11, "ME+ 1/1b");
plot->GetYaxis()->SetBinLabel(12, "ME+ 1/2");
plot->GetYaxis()->SetBinLabel(13, "ME+ 1/3");
plot->GetYaxis()->SetBinLabel(14, "ME+ 2/1");
plot->GetYaxis()->SetBinLabel(15, "ME+ 2/2");
plot->GetYaxis()->SetBinLabel(16, "ME+ 3/1");
plot->GetYaxis()->SetBinLabel(17, "ME+ 3/2");
plot->GetYaxis()->SetBinLabel(18, "ME+ 4/1");
plot->SetTitle(title.c_str());
for (int i = 1; i < 37; i++) {
ostringstream oss1;
oss1 << i;
string ch = oss1.str();
plot->GetXaxis()->SetBinLabel(i, ch.c_str());
}
c->SetRightMargin(0.12);
plot->GetYaxis()->SetNdivisions(20, kFALSE);
plot->GetXaxis()->SetNdivisions(36, kFALSE);
plot->GetXaxis()->SetTitle("Chamber #");
c->SetGrid();
plot->Draw("colz");
c->Update();
c->Print(savename.c_str(), "png");
delete c;
}
}
void Draw2DEfficiency(std::string histo, TFile *f1, std::string title, std::string savename) {
TCanvas *c = new TCanvas("c", "my canvas", 1);
gStyle->SetPalette(1, 0);
gPad->SetFillColor(4000);
c->SetFillStyle(4000);
gStyle->SetStatColor(0);
gStyle->SetTitleFillColor(0);
TH2F *num = (TH2F *)f1->Get(histo.c_str());
TH2F *denom = (TH2F *)f1->Get("Efficiency/hEffDenominator");
TH2F *plot = new TH2F("plot", title.c_str(), 36, 0.5, 36.5, 18, 0.5, 18.5);
plot->Divide(num, denom, 1., 1., "B");
plot->SetStats(kFALSE);
plot->GetYaxis()->SetBinLabel(1, "ME- 4/1");
plot->GetYaxis()->SetBinLabel(2, "ME- 3/2");
plot->GetYaxis()->SetBinLabel(3, "ME- 3/1");
plot->GetYaxis()->SetBinLabel(4, "ME- 2/2");
plot->GetYaxis()->SetBinLabel(5, "ME- 2/1");
plot->GetYaxis()->SetBinLabel(9, "ME- 1/1a");
plot->GetYaxis()->SetBinLabel(6, "ME- 1/3");
plot->GetYaxis()->SetBinLabel(7, "ME- 1/2");
plot->GetYaxis()->SetBinLabel(8, "ME- 1/1b");
plot->GetYaxis()->SetBinLabel(11, "ME+ 1/1b");
plot->GetYaxis()->SetBinLabel(12, "ME+ 1/2");
plot->GetYaxis()->SetBinLabel(13, "ME+ 1/3");
plot->GetYaxis()->SetBinLabel(10, "ME+ 1/1a");
plot->GetYaxis()->SetBinLabel(14, "ME+ 2/1");
plot->GetYaxis()->SetBinLabel(15, "ME+ 2/2");
plot->GetYaxis()->SetBinLabel(16, "ME+ 3/1");
plot->GetYaxis()->SetBinLabel(17, "ME+ 3/2");
plot->GetYaxis()->SetBinLabel(18, "ME+ 4/1");
for (int i = 1; i < 37; i++) {
ostringstream oss1;
oss1 << i;
string ch = oss1.str();
plot->GetXaxis()->SetBinLabel(i, ch.c_str());
}
c->SetRightMargin(0.12);
plot->GetYaxis()->SetNdivisions(20, kFALSE);
plot->GetXaxis()->SetNdivisions(36, kFALSE);
plot->GetXaxis()->SetTitle("Chamber #");
c->SetGrid();
plot->Draw("COLZ");
c->Update();
c->Print(savename.c_str(), "png");
delete c;
delete plot;
}
void Draw2DTempPlot(std::string histo, TFile *f1, bool includeME11, std::string savename) {
TCanvas *c = new TCanvas("c", "my canvas", 1);
gStyle->SetPalette(1, 0);
gPad->SetFillColor(4000);
c->SetFillStyle(4000);
gStyle->SetStatColor(0);
gStyle->SetTitleFillColor(0);
TH2I *plot = (TH2I *)f1->Get(histo.c_str());
plot->SetStats(kFALSE);
if (includeME11) {
plot->GetYaxis()->SetBinLabel(1, "ME- 4/2");
plot->GetYaxis()->SetBinLabel(2, "ME- 4/1");
plot->GetYaxis()->SetBinLabel(3, "ME- 3/2");
plot->GetYaxis()->SetBinLabel(4, "ME- 3/1");
plot->GetYaxis()->SetBinLabel(5, "ME- 2/2");
plot->GetYaxis()->SetBinLabel(6, "ME- 2/1");
plot->GetYaxis()->SetBinLabel(10, "ME- 1/1a");
plot->GetYaxis()->SetBinLabel(7, "ME- 1/3");
plot->GetYaxis()->SetBinLabel(8, "ME- 1/2");
plot->GetYaxis()->SetBinLabel(9, "ME- 1/1b");
plot->GetYaxis()->SetBinLabel(12, "ME+ 1/1b");
plot->GetYaxis()->SetBinLabel(13, "ME+ 1/2");
plot->GetYaxis()->SetBinLabel(14, "ME+ 1/3");
plot->GetYaxis()->SetBinLabel(11, "ME+ 1/1a");
plot->GetYaxis()->SetBinLabel(15, "ME+ 2/1");
plot->GetYaxis()->SetBinLabel(16, "ME+ 2/2");
plot->GetYaxis()->SetBinLabel(17, "ME+ 3/1");
plot->GetYaxis()->SetBinLabel(18, "ME+ 3/2");
plot->GetYaxis()->SetBinLabel(19, "ME+ 4/1");
plot->GetYaxis()->SetBinLabel(20, "ME+ 4/2");
} else {
plot->GetYaxis()->SetBinLabel(1, "ME- 4/1");
plot->GetYaxis()->SetBinLabel(2, "ME- 3/2");
plot->GetYaxis()->SetBinLabel(3, "ME- 3/1");
plot->GetYaxis()->SetBinLabel(4, "ME- 2/2");
plot->GetYaxis()->SetBinLabel(5, "ME- 2/1");
plot->GetYaxis()->SetBinLabel(6, "ME- 1/3");
plot->GetYaxis()->SetBinLabel(7, "ME- 1/2");
plot->GetYaxis()->SetBinLabel(8, "ME- 1/1b");
plot->GetYaxis()->SetBinLabel(9, "ME- 1/1a");
plot->GetYaxis()->SetBinLabel(10, "ME+ 1/1a");
plot->GetYaxis()->SetBinLabel(11, "ME+ 1/1b");
plot->GetYaxis()->SetBinLabel(12, "ME+ 1/2");
plot->GetYaxis()->SetBinLabel(13, "ME+ 1/3");
plot->GetYaxis()->SetBinLabel(14, "ME+ 2/1");
plot->GetYaxis()->SetBinLabel(15, "ME+ 2/2");
plot->GetYaxis()->SetBinLabel(16, "ME+ 3/1");
plot->GetYaxis()->SetBinLabel(17, "ME+ 3/2");
plot->GetYaxis()->SetBinLabel(18, "ME+ 4/1");
}
for (int i = 1; i < 37; i++) {
ostringstream oss1;
oss1 << i;
string ch = oss1.str();
plot->GetXaxis()->SetBinLabel(i, ch.c_str());
}
c->SetRightMargin(0.12);
plot->GetYaxis()->SetNdivisions(20, kFALSE);
plot->GetXaxis()->SetNdivisions(36, kFALSE);
plot->GetXaxis()->SetTitle("Chamber #");
c->SetGrid();
plot->Draw("COLZ");
c->Update();
c->Print(savename.c_str(), "png");
delete c;
}
void GlobalPosfromTree(
std::string graphname, TFile *f1, int endcap, int station, std::string type, std::string savename) {
TTree *t1;
TBranch *b1;
struct posRecord {
int endcap;
int station;
int ring;
int chamber;
int layer;
float localx;
float localy;
float globalx;
float globaly;
} points;
if (type == "rechit") {
t1 = (TTree *)f1->Get("recHits/rHPositions");
b1 = t1->GetBranch("rHpos");
b1->SetAddress(&points);
}
if (type == "segment") {
t1 = (TTree *)f1->Get("Segments/segPositions");
b1 = t1->GetBranch("segpos");
b1->SetAddress(&points);
}
int n1 = (int)t1->GetEntries();
const int nevents1 = n1;
float globx1[nevents1];
float globy1[nevents1];
int nstation1 = 0;
const int num_of_rings = 4;
const int num_of_chambers = 36;
int nchamber1[num_of_rings][num_of_chambers];
for (int i = 0; i < num_of_rings; i++) {
for (int j = 0; j < num_of_chambers; j++) {
nchamber1[i][j] = 0;
}
}
for (int i = 0; i < nevents1; i++) {
b1->GetEntry(i);
if (points.station == station && points.endcap == endcap) {
globx1[nstation1] = points.globalx;
globy1[nstation1] = points.globaly;
nstation1++;
nchamber1[points.ring - 1][points.chamber - 1]++;
}
}
TCanvas *c = new TCanvas("c", "my canvas", 1);
c->SetCanvasSize(700, 700);
TGraph *graph1 = new TGraph(nstation1, globx1, globy1);
std::string name1 = graphname;
gStyle->SetPalette(1, 0);
gStyle->SetTitleW(0.9);
gStyle->SetTitleH(0.1);
gStyle->SetStatColor(0);
gStyle->SetTitleFillColor(0);
gPad->SetFillColor(4000);
c->SetFillStyle(4000);
gStyle->SetOptStat(10);
graph1->GetXaxis()->SetLimits(-720, 720);
graph1->GetYaxis()->SetLimits(-720, 720);
graph1->GetXaxis()->SetRangeUser(-720, 720);
graph1->GetYaxis()->SetRangeUser(-720, 720);
graph1->SetTitle(name1.c_str());
graph1->UseCurrentStyle();
graph1->Draw("AP");
// drawChamberLines(station);
drawColoredChamberLines(station, nchamber1);
c->Print(savename.c_str(), "png");
delete c;
} // end GlobalPosfromTree
drawChamberLines(int station) {
gStyle->SetLineWidth(2);
float pi = 3.14159;
TVector3 x(0, 0, 1);
int linecolor = 1;
//for alternating colors, set 2 diff colors here
int lc1 = 1;
int lc2 = 1;
if (station == 1) {
TVector3 p1(101, 9.361, 0);
TVector3 p2(101, -9.361, 0);
TVector3 p3(260, -22.353, 0);
TVector3 p4(260, 22.353, 0);
TLine *line1;
TLine *line2;
TLine *line3;
TLine *line4;
for (int i = 0; i < 36; i++) {
if (linecolor == lc1)
linecolor = lc2;
else
linecolor = lc1;
line1 = new TLine(p1(0), p1(1), p2(0), p2(1));
line2 = new TLine(p2(0), p2(1), p3(0), p3(1));
line3 = new TLine(p3(0), p3(1), p4(0), p4(1));
line4 = new TLine(p4(0), p4(1), p1(0), p1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
p1.Rotate(pi / 18, x);
p2.Rotate(pi / 18, x);
p3.Rotate(pi / 18, x);
p4.Rotate(pi / 18, x);
}
TVector3 q1(281.49, 25.5, 0);
TVector3 q2(281.49, -25.5, 0);
TVector3 q3(455.99, -41.87, 0);
TVector3 q4(455.99, 41.87, 0);
for (int i = 0; i < 36; i++) {
if (linecolor == lc2)
linecolor = lc1;
else
linecolor = lc2;
line1 = new TLine(q1(0), q1(1), q2(0), q2(1));
line2 = new TLine(q2(0), q2(1), q3(0), q3(1));
line3 = new TLine(q3(0), q3(1), q4(0), q4(1));
line4 = new TLine(q4(0), q4(1), q1(0), q1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
q1.Rotate(pi / 18, x);
q2.Rotate(pi / 18, x);
q3.Rotate(pi / 18, x);
q4.Rotate(pi / 18, x);
}
TVector3 r1(511.99, 31.7, 0);
TVector3 r2(511.99, -31.7, 0);
TVector3 r3(676.15, -46.05, 0);
TVector3 r4(676.15, 46.05.6, 0);
for (int i = 0; i < 36; i++) {
if (linecolor == lc1)
linecolor = lc2;
else
linecolor = lc1;
line1 = new TLine(r1(0), r1(1), r2(0), r2(1));
line2 = new TLine(r2(0), r2(1), r3(0), r3(1));
line3 = new TLine(r3(0), r3(1), r4(0), r4(1));
line4 = new TLine(r4(0), r4(1), r1(0), r1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
r1.Rotate(pi / 18, x);
r2.Rotate(pi / 18, x);
r3.Rotate(pi / 18, x);
r4.Rotate(pi / 18, x);
}
}
if (station == 2) {
TVector3 p1(146.9, 27.0, 0);
TVector3 p2(146.9, -27.0, 0);
TVector3 p3(336.56, -62.855, 0);
TVector3 p4(336.56, 62.855, 0);
p1.Rotate(pi / 36, x);
p2.Rotate(pi / 36, x);
p3.Rotate(pi / 36, x);
p4.Rotate(pi / 36, x);
TLine *line1;
TLine *line2;
TLine *line3;
TLine *line4;
for (int i = 0; i < 36; i++) {
if (linecolor == lc1)
linecolor = lc2;
else
linecolor = lc1;
line1 = new TLine(p1(0), p1(1), p2(0), p2(1));
line2 = new TLine(p2(0), p2(1), p3(0), p3(1));
line3 = new TLine(p3(0), p3(1), p4(0), p4(1));
line4 = new TLine(p4(0), p4(1), p1(0), p1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
p1.Rotate(pi / 9, x);
p2.Rotate(pi / 9, x);
p3.Rotate(pi / 9, x);
p4.Rotate(pi / 9, x);
}
TVector3 q1(364.02, 33.23, 0);
TVector3 q2(364.02, -33.23, 0);
TVector3 q3(687.08, -63.575, 0);
TVector3 q4(687.08, 63.575, 0);
for (int i = 0; i < 36; i++) {
if (linecolor == lc2)
linecolor = lc1;
else
linecolor = lc2;
line1 = new TLine(q1(0), q1(1), q2(0), q2(1));
line2 = new TLine(q2(0), q2(1), q3(0), q3(1));
line3 = new TLine(q3(0), q3(1), q4(0), q4(1));
line4 = new TLine(q4(0), q4(1), q1(0), q1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
q1.Rotate(pi / 18, x);
q2.Rotate(pi / 18, x);
q3.Rotate(pi / 18, x);
q4.Rotate(pi / 18, x);
}
}
if (station == 3) {
TVector3 p1(166.89, 30.7, 0);
TVector3 p2(166.89, -30.7, 0);
TVector3 p3(336.59, -62.855, 0);
TVector3 p4(336.59, 62.855, 0);
p1.Rotate(pi / 36, x);
p2.Rotate(pi / 36, x);
p3.Rotate(pi / 36, x);
p4.Rotate(pi / 36, x);
TLine *line1;
TLine *line2;
TLine *line3;
TLine *line4;
for (int i = 0; i < 36; i++) {
if (linecolor == lc1)
linecolor = lc2;
else
linecolor = lc1;
line1 = new TLine(p1(0), p1(1), p2(0), p2(1));
line2 = new TLine(p2(0), p2(1), p3(0), p3(1));
line3 = new TLine(p3(0), p3(1), p4(0), p4(1));
line4 = new TLine(p4(0), p4(1), p1(0), p1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
p1.Rotate(pi / 9, x);
p2.Rotate(pi / 9, x);
p3.Rotate(pi / 9, x);
p4.Rotate(pi / 9, x);
}
TVector3 q1(364.02, 33.23, 0);
TVector3 q2(364.02, -33.23, 0);
TVector3 q3(687.08, -63.575, 0);
TVector3 q4(687.08, 63.575, 0);
for (int i = 0; i < 36; i++) {
if (linecolor == lc2)
linecolor = lc1;
else
linecolor = lc2;
line1 = new TLine(q1(0), q1(1), q2(0), q2(1));
line2 = new TLine(q2(0), q2(1), q3(0), q3(1));
line3 = new TLine(q3(0), q3(1), q4(0), q4(1));
line4 = new TLine(q4(0), q4(1), q1(0), q1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
q1.Rotate(pi / 18, x);
q2.Rotate(pi / 18, x);
q3.Rotate(pi / 18, x);
q4.Rotate(pi / 18, x);
}
}
if (station == 4) {
TVector3 p1(186.99, 34.505.15, 0);
TVector3 p2(186.99, -34.505, 0);
TVector3 p3(336.41, -62.825, 0);
TVector3 p4(336.41, 62.825, 0);
p1.Rotate(pi / 36, x);
p2.Rotate(pi / 36, x);
p3.Rotate(pi / 36, x);
p4.Rotate(pi / 36, x);
TLine *line1;
TLine *line2;
TLine *line3;
TLine *line4;
for (int i = 0; i < 36; i++) {
if (linecolor == lc1)
linecolor = lc2;
else
linecolor = lc1;
line1 = new TLine(p1(0), p1(1), p2(0), p2(1));
line2 = new TLine(p2(0), p2(1), p3(0), p3(1));
line3 = new TLine(p3(0), p3(1), p4(0), p4(1));
line4 = new TLine(p4(0), p4(1), p1(0), p1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
p1.Rotate(pi / 9, x);
p2.Rotate(pi / 9, x);
p3.Rotate(pi / 9, x);
p4.Rotate(pi / 9, x);
}
}
}
void compare1DPlot(
std::string histoname, TFile *f1, TFile *f2, std::string histotitle, int statoption, std::string savename) {
// used to compare two of the same histogram from different releases/runs/etc
TH1F *h2 = (TH1F *)f1->Get(histoname.c_str());
TH1F *h1 = (TH1F *)f2->Get(histoname.c_str());
TCanvas *c = new TCanvas("c", "my canvas", 1);
if (h1 && h2) {
gStyle->SetHistFillColor(92);
gStyle->SetFrameFillColor(4000);
gStyle->SetTitleW(0.5);
gStyle->SetTitleH(0.07);
gStyle->SetStatColor(0);
gStyle->SetTitleFillColor(0);
gPad->SetFillColor(4000);
c->SetFillStyle(4000);
gStyle->SetOptStat(statoption);
h1->UseCurrentStyle();
h2->UseCurrentStyle();
h2->SetFillColor(52);
h1->SetTitle(histotitle.c_str());
h1->GetXaxis()->SetLabelSize(0.04);
h1->GetYaxis()->SetLabelSize(0.04);
h1->GetXaxis()->SetTitleOffset(0.7);
h1->GetXaxis()->SetTitleSize(0.06);
h1->GetXaxis()->SetNdivisions(208, kTRUE);
TLegend *leg = new TLegend(0.79, 0.74, 0.89, 0.84);
leg->AddEntry(h1, "ref", "f");
leg->AddEntry(h2, "new", "l");
h1->Draw();
h2->Draw("same e");
leg->Draw();
}
c->Update();
c->Print(savename.c_str(), "png");
delete c;
}
void compareEffGif(std::string histoname, TFile *f1, TFile *f2, std::string histotitle, std::string savename) {
TH1F *h1 = (TH1F *)f1->Get(histoname.c_str());
TH1F *h2 = (TH1F *)f2->Get(histoname.c_str());
TCanvas *c = new TCanvas("c", "my canvas", 1);
TH1F *hn1 = new TH1F("tmp1", histotitle.c_str(), 20, 0.5, 20.5);
TH1F *hn2 = new TH1F("tmp2", histotitle.c_str(), 20, 0.5, 20.5);
if (h1 && h2) {
float Num = 1;
float Den = 1;
for (int i = 0; i < 20; i++) {
Num = h1->GetBinContent(i + 1);
Den = h1->GetBinContent(i + 21);
//getEfficiency(Num, Den, eff);
float Eff = 0.;
float EffE = 0.;
if (fabs(Den) > 0.000000001) {
Eff = Num / Den;
if (Num < Den) {
EffE = sqrt((1. - Eff) * Eff / Den);
}
}
hn1->SetBinContent(i + 1, Eff);
hn1->SetBinError(i + 1, EffE);
}
float Num = 1;
float Den = 1;
for (int i = 0; i < 20; i++) {
Num = h2->GetBinContent(i + 1);
Den = h2->GetBinContent(i + 21);
//getEfficiency(Num, Den, eff);
float Eff = 0.;
float EffE = 0.;
if (fabs(Den) > 0.000000001) {
Eff = Num / Den;
if (Num < Den) {
EffE = sqrt((1. - Eff) * Eff / Den);
}
}
hn2->SetBinContent(i + 1, Eff);
hn2->SetBinError(i + 1, EffE);
}
gStyle->SetOptStat(kFALSE);
gStyle->SetHistFillColor(92);
gStyle->SetFrameFillColor(4000);
gStyle->SetTitleW(0.7);
gStyle->SetTitleH(0.07);
gPad->SetFillColor(4000);
gStyle->SetStatColor(0);
gStyle->SetTitleFillColor(0);
c->SetFillStyle(4000);
hn1->UseCurrentStyle();
hn1->SetTitle(histotitle.c_str());
hn1->GetXaxis()->SetLabelSize(0.04);
hn1->GetYaxis()->SetLabelSize(0.04);
hn1->GetXaxis()->SetTitleOffset(0.7);
hn1->GetXaxis()->SetTitleSize(0.06);
hn1->GetXaxis()->SetNdivisions(208, kTRUE);
hn1->GetYaxis()->SetRangeUser(0.5, 1.1);
hn1->SetMarkerStyle(6);
hn1->SetMarkerColor(kBlue);
hn2->SetMarkerStyle(6);
hn2->SetMarkerColor(kRed);
hn1->GetXaxis()->SetBinLabel(1, "ME +1/1b");
hn1->GetXaxis()->SetBinLabel(2, "ME +1/2");
hn1->GetXaxis()->SetBinLabel(3, "ME +1/3");
hn1->GetXaxis()->SetBinLabel(4, "ME +1/1a");
hn1->GetXaxis()->SetBinLabel(5, "ME +2/1");
hn1->GetXaxis()->SetBinLabel(6, "ME +2/2");
hn1->GetXaxis()->SetBinLabel(7, "ME +3/1");
hn1->GetXaxis()->SetBinLabel(8, "ME +3/2");
hn1->GetXaxis()->SetBinLabel(9, "ME +4/1");
hn1->GetXaxis()->SetBinLabel(10, "ME +4/2");
hn1->GetXaxis()->SetBinLabel(11, "ME -1/1b");
hn1->GetXaxis()->SetBinLabel(12, "ME -1/2");
hn1->GetXaxis()->SetBinLabel(13, "ME -1/3");
hn1->GetXaxis()->SetBinLabel(14, "ME -1/1a");
hn1->GetXaxis()->SetBinLabel(15, "ME -2/1");
hn1->GetXaxis()->SetBinLabel(16, "ME -2/2");
hn1->GetXaxis()->SetBinLabel(17, "ME -3/1");
hn1->GetXaxis()->SetBinLabel(18, "ME -3/2");
hn1->GetXaxis()->SetBinLabel(19, "ME -4/1");
hn1->GetXaxis()->SetBinLabel(20, "ME -4/2");
TLegend *leg = new TLegend(0.79, 0.79, 0.89, 0.89);
leg->AddEntry(hn1, "new", "p");
leg->AddEntry(hn2, "ref", "p");
hn1->Draw();
hn2->Draw("same");
leg->Draw();
c->Update();
c->Print(savename.c_str(), "png");
}
delete c;
delete hn1;
delete hn2;
}
void GlobalPosfromTreeCompare(
std::string graphname, TFile *f1, TFile *f2, int endcap, int station, std::string type, std::string savename) {
struct posRecord {
int endcap;
int station;
int ring;
int chamber;
int layer;
float localx;
float localy;
float globalx;
float globaly;
} points1, points2;
TTree *t1;
TTree *t2;
TBranch *b1;
TBranch *b2;
if (type == "rechit") {
t1 = (TTree *)f1->Get("recHits/rHPositions");
t2 = (TTree *)f2->Get("recHits/rHPositions");
b1 = t1->GetBranch("rHpos");
b2 = t2->GetBranch("rHpos");
b1->SetAddress(&points1);
b2->SetAddress(&points2);
}
if (type == "segment") {
t1 = (TTree *)f1->Get("Segments/segPositions");
t2 = (TTree *)f2->Get("Segments/segPositions");
b1 = t1->GetBranch("segpos");
b2 = t2->GetBranch("segpos");
b1->SetAddress(&points1);
b2->SetAddress(&points2);
}
int n1 = (int)t1->GetEntries();
int n2 = (int)t2->GetEntries();
const int nevents1 = n1;
const int nevents2 = n2;
float globx1[nevents1];
float globy1[nevents1];
float globx2[nevents2];
float globy2[nevents2];
int nstation1 = 0;
int nstation2 = 0;
for (int i = 0; i < nevents1; i++) {
b1->GetEntry(i);
if (points1.station == station && points1.endcap == endcap) {
globx1[nstation1] = points1.globalx;
globy1[nstation1] = points1.globaly;
nstation1++;
}
}
for (int i = 0; i < nevents2; i++) {
b2->GetEntry(i);
if (points2.station == station && points2.endcap == endcap) {
globx2[nstation2] = points2.globalx;
globy2[nstation2] = points2.globaly;
nstation2++;
}
}
std::string name1 = graphname + " (New)";
std::string name2 = graphname + " (Ref)";
TCanvas *c = new TCanvas("c", "my canvas", 1);
c->SetCanvasSize(1300, 700);
c->Divide(2, 1);
TGraph *graph1 = new TGraph(nstation1, globx1, globy1);
TGraph *graph2 = new TGraph(nstation2, globx2, globy2);
gStyle->SetTitleW(0.6);
gStyle->SetTitleH(0.1);
gStyle->SetStatColor(0);
gStyle->SetTitleFillColor(0);
gStyle->SetOptStat(10);
c->cd(1);
graph1->SetTitle(name1.c_str());
graph1->UseCurrentStyle();
drawChamberLines(station);
graph1->Draw("AP");
c->cd(2);
graph2->SetTitle(name2.c_str());
graph2->UseCurrentStyle();
drawChamberLines(station);
graph2->Draw("AP");
//c->Update();
c->Print(savename.c_str(), "png");
delete c;
}
void NikolaiPlots(TFile *f_in, int flag) {
gROOT->SetStyle("Plain"); // to get rid of gray color of pad and have it white
gStyle->SetPalette(1, 0); //
std::ostringstream ss, ss1;
if (flag == 1) { // gas gain results
std::string folder = "GasGain/";
std::string input_histName = "gas_gain_rechit_adc_3_3_sum_location_ME_";
std::string input_title_X = "Location=(layer-1)*nsegm+segm";
std::string input_title_Y = "3X3 ADC Sum";
std::string slice_title_X = "3X3 ADC Sum Location";
Int_t ny = 30;
Float_t ylow = 1.0, yhigh = 31.0;
std::string result_histName = "mean_gas_gain_vs_location_csc_ME_";
std::string result_histTitle = "Mean 3X3 ADC Sum";
std::string result_title_Y = "Location=(layer-1)*nsegm+segm";
std::string result_histNameEntries = "entries_gas_gain_vs_location_csc_ME_";
std::string result_histTitleEntries = "Entries 3X3 ADC Sum";
}
if (flag == 2) { // AFEB timing results
std::string folder = "AFEBTiming/";
std::string input_histName = "afeb_time_bin_vs_afeb_occupancy_ME_";
std::string input_title_X = "AFEB";
std::string input_title_Y = "Time Bin";
std::string slice_title_X = "AFEB";
Int_t ny = 42;
Float_t ylow = 1.0, yhigh = 42.0;
std::string result_histName = "mean_afeb_time_bin_vs_afeb_csc_ME_";
std::string result_histTitle = "AFEB Mean Time Bin";
std::string result_title_Y = "AFEB";
std::string result_histNameEntries = "entries_afeb_time_bin_vs_afeb_csc_ME_";
std::string result_histTitleEntries = "Entries AFEB Time Bin";
}
if (flag == 3) { // Comparator timing results
std::string folder = "CompTiming/";
std::string input_histName = "comp_time_bin_vs_cfeb_occupancy_ME_";
std::string input_title_X = "CFEB";
std::string input_title_Y = "Time Bin";
std::string slice_title_X = "CFEB";
Int_t ny = 5;
Float_t ylow = 1.0, yhigh = 6.0;
std::string result_histName = "mean_comp_time_bin_vs_cfeb_csc_ME_";
std::string result_histTitle = "Comparator Mean Time Bin";
std::string result_title_Y = "CFEB";
std::string result_histNameEntries = "entries_comp_time_bin_vs_cfeb_csc_ME_";
std::string result_histTitleEntries = "Entries Comparator Time Bin";
}
if (flag == 4) { // Strip ADC timing results
std::string folder = "ADCTiming/";
std::string input_histName = "adc_3_3_weight_time_bin_vs_cfeb_occupancy_ME_";
std::string input_title_X = "CFEB";
std::string input_title_Y = "Time Bin";
std::string slice_title_X = "CFEB";
Int_t ny = 5;
Float_t ylow = 1.0, yhigh = 6.0;
std::string result_histName = "mean_adc_time_bin_vs_cfeb_csc_ME_";
std::string result_histTitle = "ADC 3X3 Mean Time Bin";
std::string result_title_Y = "CFEB";
std::string result_histNameEntries = "entries_adc_time_bin_vs_cfeb_csc_ME_";
std::string result_histTitleEntries = "Entries ADC 3X3 Time Bin";
}
std::vector<std::string> xTitle;
xTitle.push_back("ME+1/1 CSC");
xTitle.push_back("ME+1/2 CSC");
xTitle.push_back("ME+1/3 CSC");
xTitle.push_back("ME+2/1 CSC");
xTitle.push_back("ME+2/2 CSC");
xTitle.push_back("ME+3/1 CSC");
xTitle.push_back("ME+3/2 CSC");
xTitle.push_back("ME+4/1 CSC");
xTitle.push_back("ME+4/2 CSC");
xTitle.push_back("ME-1/1 CSC");
xTitle.push_back("ME-1/2 CSC");
xTitle.push_back("ME-1/3 CSC");
xTitle.push_back("ME-2/1 CSC");
xTitle.push_back("ME-2/2 CSC");
xTitle.push_back("ME-3/1 CSC");
xTitle.push_back("ME-3/2 CSC");
xTitle.push_back("ME-4/1 CSC");
xTitle.push_back("ME-4/2 CSC");
TH2F *h2[500];
TH2F *h;
Int_t esr[18] = {111, 112, 113, 121, 122, 131, 132, 141, 142, 211, 212, 213, 221, 222, 231, 232, 241, 242};
Int_t entries[18] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Int_t k = 0;
TCanvas *c1 = new TCanvas("c1", "canvas");
c1->cd();
//if(flag==2) { // adding special case for AFEB timing
ss.str("");
ss << "mean_afeb_time_bin_vs_csc_ME";
ss1.str("");
ss1 << "Mean AFEB time bin vs CSC and ME";
gStyle->SetOptStat(0);
TH2F *hb = new TH2F(ss.str().c_str(), ss1.str().c_str(), 36, 1.0, 37.0, 18, 1.0, 19.0);
hb->SetStats(kFALSE);
hb->GetXaxis()->SetTitle("CSC #");
hb->GetZaxis()->SetLabelSize(0.03);
hb->SetOption("COLZ");
hb->GetYaxis()->SetBinLabel(1, "ME- 4/2");
hb->GetYaxis()->SetBinLabel(2, "ME- 4/1");
hb->GetYaxis()->SetBinLabel(3, "ME- 3/2");
hb->GetYaxis()->SetBinLabel(4, "ME- 3/1");
hb->GetYaxis()->SetBinLabel(5, "ME- 2/2");
hb->GetYaxis()->SetBinLabel(6, "ME- 2/1");
hb->GetYaxis()->SetBinLabel(7, "ME- 1/3");
hb->GetYaxis()->SetBinLabel(8, "ME- 1/2");
hb->GetYaxis()->SetBinLabel(9, "ME- 1/1");
hb->GetYaxis()->SetBinLabel(10, "ME+ 1/1");
hb->GetYaxis()->SetBinLabel(11, "ME+ 1/2");
hb->GetYaxis()->SetBinLabel(12, "ME+ 1/3");
hb->GetYaxis()->SetBinLabel(13, "ME+ 2/1");
hb->GetYaxis()->SetBinLabel(14, "ME+ 2/2");
hb->GetYaxis()->SetBinLabel(15, "ME+ 3/1");
hb->GetYaxis()->SetBinLabel(16, "ME+ 3/2");
hb->GetYaxis()->SetBinLabel(17, "ME+ 4/1");
hb->GetYaxis()->SetBinLabel(18, "ME+ 4/2");
//}
for (Int_t jesr = 0; jesr < 18; jesr++) {
ss.str("");
ss << result_histName.c_str() << esr[jesr];
ss1.str("");
ss1 << result_histTitle;
TH2F *h = new TH2F(ss.str().c_str(), ss1.str().c_str(), 40, 0.0, 40.0, ny, ylow, yhigh);
h->SetStats(kFALSE);
h->GetXaxis()->SetTitle(xTitle[jesr].c_str());
h->GetYaxis()->SetTitle(result_title_Y.c_str());
h->GetZaxis()->SetLabelSize(0.03);
h->SetOption("COLZ");
ss.str("");
ss << result_histNameEntries.c_str() << esr[jesr];
ss1.str("");
ss1 << result_histTitleEntries;
TH2F *hentr = new TH2F(ss.str().c_str(), ss1.str().c_str(), 40, 0.0, 40.0, ny, ylow, yhigh);
hentr->SetStats(kFALSE);
hentr->GetXaxis()->SetTitle(xTitle[jesr].c_str());
hentr->GetYaxis()->SetTitle(result_title_Y.c_str());
hentr->GetZaxis()->SetLabelSize(0.03);
hentr->SetOption("COLZ");
if (flag == 2) { // adding special cases for AFEB timing
ss.str("");
ss << "normal_afeb_time_bin_vs_csc_ME_" << esr[jesr];
ss1.str("");
ss1 << "Normalized AFEB time bin, %";
TH2F *ha = new TH2F(ss.str().c_str(), ss1.str().c_str(), 40, 0.0, 40.0, 16, 0.0, 16.0);
ha->SetStats(kFALSE);
ha->GetXaxis()->SetTitle(xTitle[jesr].c_str());
ha->GetYaxis()->SetTitle("Time Bin");
ha->GetZaxis()->SetLabelSize(0.03);
ha->SetOption("COLZ");
}
for (Int_t csc = 1; csc < 37; csc++) {
Int_t idchamber = esr[jesr] * 100 + csc;
ss.str("");
ss << folder.c_str() << input_histName.c_str() << idchamber;
f_in->cd();
TH2F *h2[1];
h2[k] = (TH2F *)f_in->Get(ss.str().c_str());
if (h2[k] != NULL) {
// saving original, adding X,Y titles, color and "BOX" option
h2[k]->GetXaxis()->SetTitle(input_title_X.c_str());
h2[k]->GetYaxis()->SetTitle(input_title_Y.c_str());
h2[k]->GetYaxis()->SetTitleOffset(1.2);
h2[k]->SetFillColor(4);
h2[k]->SetOption("BOX");
gStyle->SetOptStat(1001111);
// saving Y projection of the whole 2D hist for given chamber
ss.str("");
ss << input_histName.c_str() << idchamber << "_Y_all";
TH1D *h1d = h2[k]->ProjectionY(ss.str().c_str(), 1, h2[k]->GetNbinsX(), "");
h1d->GetYaxis()->SetTitle("Entries");
h1d->GetYaxis()->SetTitleOffset(1.2);
gStyle->SetOptStat(1001111);
if (flag == 2 && h1d->GetEntries() > 0) { // adding spec. case for afeb timing
Float_t entr = h1d->GetEntries();
for (Int_t m = 1; m < h1d->GetNbinsX(); m++) {
Float_t w = h1d->GetBinContent(m);
w = 100.0 * w / entr;
ha->SetBinContent(csc + 1, m, w);
}
Float_t mean = h1d->GetMean();
Int_t me;
if (jesr < 9)
me = 10 + jesr;
if (jesr > 8)
me = 18 - jesr;
hb->SetBinContent(csc, me, mean);
}
delete h1d;
// saving slices, finding MEAN in each slice, fill 2D hist
for (Int_t j = 1; j <= h2[k]->GetNbinsX(); j++) {
Int_t n = j;
ss.str("");
ss << input_histName.c_str() << idchamber << "_Y_" << n;
TH1D *h1d = h2[k]->ProjectionY(ss.str().c_str(), j, j, "");
if (h1d->GetEntries() > 0) {
Float_t mean = h1d->GetMean();
Float_t entr = h1d->GetEntries();
entries[jesr] = entries[jesr] + 1;
h->SetBinContent(csc + 1, j, mean);
hentr->SetBinContent(csc + 1, j, entr);
ss.str("");
ss << slice_title_X << " " << n;
h1d->GetXaxis()->SetTitle(ss.str().c_str());
h1d->GetYaxis()->SetTitle("Entries");
h1d->GetYaxis()->SetTitleOffset(1.2);
gStyle->SetOptStat(1001111);
}
delete h1d;
}
}
}
if (entries[jesr] > 0) {
h->SetStats(kFALSE);
hentr->SetStats(kFALSE);
c1->Update();
// printing
h->Draw();
ss.str("");
ss << result_histName.c_str() << esr[jesr] << ".png";
c1->Print(ss.str().c_str(), "png");
hentr->Draw();
ss.str("");
ss << result_histNameEntries.c_str() << esr[jesr] << ".png";
c1->Print(ss.str().c_str(), "png");
}
delete h;
delete hentr;
if (flag == 2)
delete ha;
}
if (flag == 2) {
hb->Draw();
ss.str("");
ss << "mean_afeb_time_bin_vs_csc_ME"
<< ".png";
c1->Print(ss.str().c_str(), "png");
c1->Update();
//delete hb;
}
delete hb;
delete c1;
}
drawColoredChamberLines(int station, int nchamber1[4][36]) {
// thanks to Luca Sabbatini for this coe
const int maxRingIdxOfRelevance = 2;
const int maxChamberIdxOfRelevance = 35;
const int totalNumberOfChambersOfRelevance = 540;
Int_t thisRingIdx = 0;
Int_t numChambersInRing = 0;
float nchamber1Avg = 0.;
float thisRingNchamber1Avg = 0;
float thisRingNchamber1Max = 0;
// Note that thisRingNchamber1Min is only the minumum *non-zero*
// occupancy among all the cmabers for the given ring
float thisRingNchamber1Min = 0;
Int_t thisRingNchamber1Base = 0;
// rFloatRGB, gFloatRGB, bFloatRGB, are from the RGB color space;
// all three range between [0,1]
// hFloatHLS, lFloatHLS, sFloatHLS, are from the HLS color space;
// lFloatHLS and sFloatHLS range between [0,1], while hFloatHLS
// ranges between [0,360]
Float_t rFloatRGB = 0.;
Float_t gFloatRGB = 0.;
Float_t bFloatRGB = 0.;
Float_t hFloatHLS = 0.;
Float_t lFloatHLS = 0.5;
Float_t sFloatHLS = 1.0;
TColor tempColor;
// compute average chamber occupancy over all CSCs
for (int i = 0; i < maxRingIdxOfRelevance + 1; i++) {
for (int j = 0; j < maxChamberIdxOfRelevance + 1; j++) {
nchamber1Avg += nchamber1[i][j];
}
}
nchamber1Avg = nchamber1Avg / totalNumberOfChambersOfRelevance;
Float_t myFavoriteLineWidth = 2.0;
gStyle->SetLineWidth(myFavoriteLineWidth);
float pi = 3.14159;
TVector3 x(0, 0, 1);
int linecolor = 1;
// emptyLineColor is the color of the outline of empty chambers.
// if emptyLineColor is negative, no outline is drawn at all for
// that chamber.
Int_t emptyLineColor = kYellow;
// note that these can be greater than 360 because I have included
// a line down below that performs a modulus operation: %360, which
// ensures that the resulting hue will indeed be with [0,360]
//
// Hue: 0 30 60 120 180 240 270 300 360
// | | | | | | | | |
// Color: Red Orange Yellow Green Cyan Blue Vilet Magenta Red
Float_t lineHueMin = 240;
Float_t lineHueMax = 360;
TLine *line1;
TLine *line2;
TLine *line3;
TLine *line4;
if (station == 1) {
// station 1, ring 1 (inner-most ring)
thisRingIdx = 0;
numChambersInRing = 36;
TVector3 p1(101, 9.361, 0);
TVector3 p2(101, -9.361, 0);
TVector3 p3(260, -22.353, 0);
TVector3 p4(260, 22.353, 0);
// compute thisRingNchamber1Min, thisRingNchamber1Max,
// thisRingNchamber1Avg and thisRingNchamber1Base
thisRingNchamber1Avg = 0.;
thisRingNchamber1Max = 0.;
for (int j = 0; j < numChambersInRing; j++) {
thisRingNchamber1Avg += nchamber1[thisRingIdx][j];
if (thisRingNchamber1Max < nchamber1[thisRingIdx][j]) {
thisRingNchamber1Max = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Min = thisRingNchamber1Max;
for (int j = 0; j < numChambersInRing; j++) {
if (thisRingNchamber1Min > nchamber1[thisRingIdx][j] && //
nchamber1[thisRingIdx][j] != 0) {
thisRingNchamber1Min = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Avg = thisRingNchamber1Avg / numChambersInRing;
thisRingNchamber1Base = thisRingNchamber1Min;
for (int i = 0; i < numChambersInRing; i++) {
// set the line color
if (nchamber1[thisRingIdx][i] != 0) {
hFloatHLS = int((nchamber1[0][i] - thisRingNchamber1Base) / (thisRingNchamber1Max - thisRingNchamber1Base) * //
(lineHueMax - lineHueMin) +
lineHueMin) %
360;
tempColor.HLS2RGB(hFloatHLS, lFloatHLS, sFloatHLS, rFloatRGB, gFloatRGB, bFloatRGB);
linecolor = tempColor.GetColor(rFloatRGB, gFloatRGB, bFloatRGB);
} else if (emptyLineColor >= 0) {
linecolor = emptyLineColor;
}
// draw the chamber outline using the line color (so long
// as the the chamber isn't empty *and* the user did not
// set a negative line color for empty chambers)
if ((nchamber1[thisRingIdx][i] != 0) || //
(nchamber1[thisRingIdx][i] == 0 && emptyLineColor >= 0)) {
line1 = new TLine(p1(0), p1(1), p2(0), p2(1));
line2 = new TLine(p2(0), p2(1), p3(0), p3(1));
line3 = new TLine(p3(0), p3(1), p4(0), p4(1));
line4 = new TLine(p4(0), p4(1), p1(0), p1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
}
// Rotate coordinate by 1 chamber
p1.Rotate(2 * pi / numChambersInRing, x);
p2.Rotate(2 * pi / numChambersInRing, x);
p3.Rotate(2 * pi / numChambersInRing, x);
p4.Rotate(2 * pi / numChambersInRing, x);
}
// station 1, ring 2 (middle-ring)
thisRingIdx = 1;
numChambersInRing = 36;
TVector3 q1(281.49, 25.5, 0);
TVector3 q2(281.49, -25.5, 0);
TVector3 q3(455.99, -41.87, 0);
TVector3 q4(455.99, 41.87, 0);
thisRingNchamber1Avg = 0.;
thisRingNchamber1Max = 0.;
for (int j = 0; j < numChambersInRing; j++) {
thisRingNchamber1Avg += nchamber1[thisRingIdx][j];
if (thisRingNchamber1Max < nchamber1[thisRingIdx][j]) {
thisRingNchamber1Max = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Min = thisRingNchamber1Max;
for (int j = 0; j < numChambersInRing; j++) {
if (thisRingNchamber1Min > nchamber1[thisRingIdx][j] && //
nchamber1[thisRingIdx][j] != 0) {
thisRingNchamber1Min = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Avg = thisRingNchamber1Avg / numChambersInRing;
thisRingNchamber1Base = thisRingNchamber1Min;
for (int i = 0; i < numChambersInRing; i++) {
if (nchamber1[thisRingIdx][i] != 0) {
hFloatHLS = int((nchamber1[thisRingIdx][i] - thisRingNchamber1Base) /
(thisRingNchamber1Max - thisRingNchamber1Base) * //
(lineHueMax - lineHueMin) +
lineHueMin) %
360;
tempColor.HLS2RGB(hFloatHLS, lFloatHLS, sFloatHLS, rFloatRGB, gFloatRGB, bFloatRGB);
linecolor = tempColor.GetColor(rFloatRGB, gFloatRGB, bFloatRGB);
} else if (emptyLineColor >= 0) {
linecolor = emptyLineColor;
}
if ((nchamber1[thisRingIdx][i] != 0) || //
(nchamber1[thisRingIdx][i] == 0 && emptyLineColor >= 0)) {
line1 = new TLine(q1(0), q1(1), q2(0), q2(1));
line2 = new TLine(q2(0), q2(1), q3(0), q3(1));
line3 = new TLine(q3(0), q3(1), q4(0), q4(1));
line4 = new TLine(q4(0), q4(1), q1(0), q1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
}
q1.Rotate(2 * pi / numChambersInRing, x);
q2.Rotate(2 * pi / numChambersInRing, x);
q3.Rotate(2 * pi / numChambersInRing, x);
q4.Rotate(2 * pi / numChambersInRing, x);
}
// station 1, ring 3 (outer-most ring)
thisRingIdx = 2;
numChambersInRing = 36;
TVector3 r1(511.99, 31.7, 0);
TVector3 r2(511.99, -31.7, 0);
TVector3 r3(676.15, -46.05, 0);
TVector3 r4(676.15, 46.05.6, 0);
thisRingNchamber1Avg = 0.;
thisRingNchamber1Max = 0.;
for (int j = 0; j < numChambersInRing; j++) {
thisRingNchamber1Avg += nchamber1[thisRingIdx][j];
if (thisRingNchamber1Max < nchamber1[thisRingIdx][j]) {
thisRingNchamber1Max = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Min = thisRingNchamber1Max;
for (int j = 0; j < numChambersInRing; j++) {
if (thisRingNchamber1Min > nchamber1[thisRingIdx][j] && //
nchamber1[thisRingIdx][j] != 0) {
thisRingNchamber1Min = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Avg = thisRingNchamber1Avg / numChambersInRing;
thisRingNchamber1Base = thisRingNchamber1Min;
for (int i = 0; i < numChambersInRing; i++) {
if (nchamber1[thisRingIdx][i] != 0) {
hFloatHLS = int((nchamber1[thisRingIdx][i] - thisRingNchamber1Base) /
(thisRingNchamber1Max - thisRingNchamber1Base) * //
(lineHueMax - lineHueMin) +
lineHueMin) %
360;
tempColor.HLS2RGB(hFloatHLS, lFloatHLS, sFloatHLS, rFloatRGB, gFloatRGB, bFloatRGB);
linecolor = tempColor.GetColor(rFloatRGB, gFloatRGB, bFloatRGB);
} else if (emptyLineColor >= 0) {
linecolor = emptyLineColor;
}
if ((nchamber1[thisRingIdx][i] != 0) || //
(nchamber1[thisRingIdx][i] == 0 && emptyLineColor >= 0)) {
line1 = new TLine(r1(0), r1(1), r2(0), r2(1));
line2 = new TLine(r2(0), r2(1), r3(0), r3(1));
line3 = new TLine(r3(0), r3(1), r4(0), r4(1));
line4 = new TLine(r4(0), r4(1), r1(0), r1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
}
r1.Rotate(2 * pi / numChambersInRing, x);
r2.Rotate(2 * pi / numChambersInRing, x);
r3.Rotate(2 * pi / numChambersInRing, x);
r4.Rotate(2 * pi / numChambersInRing, x);
}
}
if (station == 2) {
// station 2, ring 1 (inner ring)
thisRingIdx = 0;
numChambersInRing = 18;
TVector3 p1(146.9, 27.0, 0);
TVector3 p2(146.9, -27.0, 0);
TVector3 p3(336.56, -62.855, 0);
TVector3 p4(336.56, 62.855, 0);
// must "pre-rotate" by one-fourth of a chamber
p1.Rotate((1 / 4.) * 2 * pi / numChambersInRing, x);
p2.Rotate((1 / 4.) * 2 * pi / numChambersInRing, x);
p3.Rotate((1 / 4.) * 2 * pi / numChambersInRing, x);
p4.Rotate((1 / 4.) * 2 * pi / numChambersInRing, x);
thisRingNchamber1Avg = 0.;
thisRingNchamber1Max = 0.;
for (int j = 0; j < numChambersInRing; j++) {
thisRingNchamber1Avg += nchamber1[thisRingIdx][j];
if (thisRingNchamber1Max < nchamber1[thisRingIdx][j]) {
thisRingNchamber1Max = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Min = thisRingNchamber1Max;
for (int j = 0; j < numChambersInRing; j++) {
if (thisRingNchamber1Min > nchamber1[thisRingIdx][j] && //
nchamber1[thisRingIdx][j] != 0) {
thisRingNchamber1Min = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Avg = thisRingNchamber1Avg / numChambersInRing;
thisRingNchamber1Base = thisRingNchamber1Min;
for (int i = 0; i < numChambersInRing; i++) {
if (nchamber1[thisRingIdx][i] != 0) {
hFloatHLS = int((nchamber1[0][i] - thisRingNchamber1Base) / (thisRingNchamber1Max - thisRingNchamber1Base) * //
(lineHueMax - lineHueMin) +
lineHueMin) %
360;
tempColor.HLS2RGB(hFloatHLS, lFloatHLS, sFloatHLS, rFloatRGB, gFloatRGB, bFloatRGB);
linecolor = tempColor.GetColor(rFloatRGB, gFloatRGB, bFloatRGB);
} else if (emptyLineColor >= 0) {
linecolor = emptyLineColor;
}
if ((nchamber1[thisRingIdx][i] != 0) || //
(nchamber1[thisRingIdx][i] == 0 && emptyLineColor >= 0)) {
line1 = new TLine(p1(0), p1(1), p2(0), p2(1));
line2 = new TLine(p2(0), p2(1), p3(0), p3(1));
line3 = new TLine(p3(0), p3(1), p4(0), p4(1));
line4 = new TLine(p4(0), p4(1), p1(0), p1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
}
p1.Rotate(2 * pi / numChambersInRing, x);
p2.Rotate(2 * pi / numChambersInRing, x);
p3.Rotate(2 * pi / numChambersInRing, x);
p4.Rotate(2 * pi / numChambersInRing, x);
}
// station 2, ring 2 (outer ring)
thisRingIdx = 1;
numChambersInRing = 36;
TVector3 q1(364.02, 33.23, 0);
TVector3 q2(364.02, -33.23, 0);
TVector3 q3(687.08, -63.575, 0);
TVector3 q4(687.08, 63.575, 0);
thisRingNchamber1Avg = 0.;
thisRingNchamber1Max = 0.;
for (int j = 0; j < numChambersInRing; j++) {
thisRingNchamber1Avg += nchamber1[thisRingIdx][j];
if (thisRingNchamber1Max < nchamber1[thisRingIdx][j]) {
thisRingNchamber1Max = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Min = thisRingNchamber1Max;
for (int j = 0; j < numChambersInRing; j++) {
if (thisRingNchamber1Min > nchamber1[thisRingIdx][j] && //
nchamber1[thisRingIdx][j] != 0) {
thisRingNchamber1Min = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Avg = thisRingNchamber1Avg / numChambersInRing;
thisRingNchamber1Base = thisRingNchamber1Min;
for (int i = 0; i < numChambersInRing; i++) {
if (nchamber1[thisRingIdx][i] != 0) {
hFloatHLS = int((nchamber1[thisRingIdx][i] - thisRingNchamber1Base) /
(thisRingNchamber1Max - thisRingNchamber1Base) * //
(lineHueMax - lineHueMin) +
lineHueMin) %
360;
tempColor.HLS2RGB(hFloatHLS, lFloatHLS, sFloatHLS, rFloatRGB, gFloatRGB, bFloatRGB);
linecolor = tempColor.GetColor(rFloatRGB, gFloatRGB, bFloatRGB);
} else if (emptyLineColor >= 0) {
linecolor = emptyLineColor;
}
if ((nchamber1[thisRingIdx][i] != 0) || //
(nchamber1[thisRingIdx][i] == 0 && emptyLineColor >= 0)) {
line1 = new TLine(q1(0), q1(1), q2(0), q2(1));
line2 = new TLine(q2(0), q2(1), q3(0), q3(1));
line3 = new TLine(q3(0), q3(1), q4(0), q4(1));
line4 = new TLine(q4(0), q4(1), q1(0), q1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
}
q1.Rotate(2 * pi / numChambersInRing, x);
q2.Rotate(2 * pi / numChambersInRing, x);
q3.Rotate(2 * pi / numChambersInRing, x);
q4.Rotate(2 * pi / numChambersInRing, x);
}
}
if (station == 3) {
// station 3, ring 1 (inner ring)
thisRingIdx = 0;
numChambersInRing = 18;
TVector3 p1(166.89, 30.7, 0);
TVector3 p2(166.89, -30.7, 0);
TVector3 p3(336.59, -62.855, 0);
TVector3 p4(336.59, 62.855, 0);
// must "pre-rotate" by one-fourth of a chamber
p1.Rotate((1 / 4.) * 2 * pi / numChambersInRing, x);
p2.Rotate((1 / 4.) * 2 * pi / numChambersInRing, x);
p3.Rotate((1 / 4.) * 2 * pi / numChambersInRing, x);
p4.Rotate((1 / 4.) * 2 * pi / numChambersInRing, x);
TLine *line1;
TLine *line2;
TLine *line3;
TLine *line4;
thisRingNchamber1Avg = 0.;
thisRingNchamber1Max = 0.;
for (int j = 0; j < numChambersInRing; j++) {
thisRingNchamber1Avg += nchamber1[thisRingIdx][j];
if (thisRingNchamber1Max < nchamber1[thisRingIdx][j]) {
thisRingNchamber1Max = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Min = thisRingNchamber1Max;
for (int j = 0; j < numChambersInRing; j++) {
if (thisRingNchamber1Min > nchamber1[thisRingIdx][j] && //
nchamber1[thisRingIdx][j] != 0) {
thisRingNchamber1Min = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Avg = thisRingNchamber1Avg / numChambersInRing;
thisRingNchamber1Base = thisRingNchamber1Min;
for (int i = 0; i < numChambersInRing; i++) {
if (nchamber1[thisRingIdx][i] != 0) {
hFloatHLS = int((nchamber1[0][i] - thisRingNchamber1Base) / (thisRingNchamber1Max - thisRingNchamber1Base) * //
(lineHueMax - lineHueMin) +
lineHueMin) %
360;
tempColor.HLS2RGB(hFloatHLS, lFloatHLS, sFloatHLS, rFloatRGB, gFloatRGB, bFloatRGB);
linecolor = tempColor.GetColor(rFloatRGB, gFloatRGB, bFloatRGB);
} else if (emptyLineColor >= 0) {
linecolor = emptyLineColor;
}
if ((nchamber1[thisRingIdx][i] != 0) || //
(nchamber1[thisRingIdx][i] == 0 && emptyLineColor >= 0)) {
line1 = new TLine(p1(0), p1(1), p2(0), p2(1));
line2 = new TLine(p2(0), p2(1), p3(0), p3(1));
line3 = new TLine(p3(0), p3(1), p4(0), p4(1));
line4 = new TLine(p4(0), p4(1), p1(0), p1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
}
p1.Rotate(2 * pi / numChambersInRing, x);
p2.Rotate(2 * pi / numChambersInRing, x);
p3.Rotate(2 * pi / numChambersInRing, x);
p4.Rotate(2 * pi / numChambersInRing, x);
}
// station 3, ring 2 (outer ring)
thisRingIdx = 1;
numChambersInRing = 36;
TVector3 q1(364.02, 33.23, 0);
TVector3 q2(364.02, -33.23, 0);
TVector3 q3(687.08, -63.575, 0);
TVector3 q4(687.08, 63.575, 0);
thisRingNchamber1Avg = 0.;
thisRingNchamber1Max = 0.;
for (int j = 0; j < numChambersInRing; j++) {
thisRingNchamber1Avg += nchamber1[thisRingIdx][j];
if (thisRingNchamber1Max < nchamber1[thisRingIdx][j]) {
thisRingNchamber1Max = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Min = thisRingNchamber1Max;
for (int j = 0; j < numChambersInRing; j++) {
if (thisRingNchamber1Min > nchamber1[thisRingIdx][j] && //
nchamber1[thisRingIdx][j] != 0) {
thisRingNchamber1Min = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Avg = thisRingNchamber1Avg / numChambersInRing;
thisRingNchamber1Base = thisRingNchamber1Min;
for (int i = 0; i < numChambersInRing; i++) {
if (nchamber1[thisRingIdx][i] != 0) {
hFloatHLS = int((nchamber1[thisRingIdx][i] - thisRingNchamber1Base) /
(thisRingNchamber1Max - thisRingNchamber1Base) * //
(lineHueMax - lineHueMin) +
lineHueMin) %
360;
tempColor.HLS2RGB(hFloatHLS, lFloatHLS, sFloatHLS, rFloatRGB, gFloatRGB, bFloatRGB);
linecolor = tempColor.GetColor(rFloatRGB, gFloatRGB, bFloatRGB);
} else if (emptyLineColor >= 0) {
linecolor = emptyLineColor;
}
if ((nchamber1[thisRingIdx][i] != 0) || //
(nchamber1[thisRingIdx][i] == 0 && emptyLineColor >= 0)) {
line1 = new TLine(q1(0), q1(1), q2(0), q2(1));
line2 = new TLine(q2(0), q2(1), q3(0), q3(1));
line3 = new TLine(q3(0), q3(1), q4(0), q4(1));
line4 = new TLine(q4(0), q4(1), q1(0), q1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
}
q1.Rotate(2 * pi / numChambersInRing, x);
q2.Rotate(2 * pi / numChambersInRing, x);
q3.Rotate(2 * pi / numChambersInRing, x);
q4.Rotate(2 * pi / numChambersInRing, x);
}
}
if (station == 4) {
// station 4, ring 1 (the only ring on station 4... so far)
thisRingIdx = 0;
numChambersInRing = 18;
TVector3 p1(186.99, 34.505.15, 0);
TVector3 p2(186.99, -34.505, 0);
TVector3 p3(336.41, -62.825, 0);
TVector3 p4(336.41, 62.825, 0);
// must "pre-rotate" by one-fourth of a chamber
p1.Rotate((1 / 4.) * 2 * pi / numChambersInRing, x);
p2.Rotate((1 / 4.) * 2 * pi / numChambersInRing, x);
p3.Rotate((1 / 4.) * 2 * pi / numChambersInRing, x);
p4.Rotate((1 / 4.) * 2 * pi / numChambersInRing, x);
TLine *line1;
TLine *line2;
TLine *line3;
TLine *line4;
thisRingNchamber1Avg = 0.;
thisRingNchamber1Max = 0.;
for (int j = 0; j < numChambersInRing; j++) {
thisRingNchamber1Avg += nchamber1[thisRingIdx][j];
if (thisRingNchamber1Max < nchamber1[thisRingIdx][j]) {
thisRingNchamber1Max = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Min = thisRingNchamber1Max;
for (int j = 0; j < numChambersInRing; j++) {
if (thisRingNchamber1Min > nchamber1[thisRingIdx][j] && //
nchamber1[thisRingIdx][j] != 0) {
thisRingNchamber1Min = nchamber1[thisRingIdx][j];
}
}
thisRingNchamber1Avg = thisRingNchamber1Avg / numChambersInRing;
thisRingNchamber1Base = thisRingNchamber1Min;
for (int i = 0; i < numChambersInRing; i++) {
if (nchamber1[thisRingIdx][i] != 0) {
hFloatHLS = int((nchamber1[0][i] - thisRingNchamber1Base) / (thisRingNchamber1Max - thisRingNchamber1Base) * //
(lineHueMax - lineHueMin) +
lineHueMin) %
360;
tempColor.HLS2RGB(hFloatHLS, lFloatHLS, sFloatHLS, rFloatRGB, gFloatRGB, bFloatRGB);
linecolor = tempColor.GetColor(rFloatRGB, gFloatRGB, bFloatRGB);
} else if (emptyLineColor >= 0) {
linecolor = emptyLineColor;
}
if ((nchamber1[thisRingIdx][i] != 0) || //
(nchamber1[thisRingIdx][i] == 0 && emptyLineColor >= 0)) {
line1 = new TLine(p1(0), p1(1), p2(0), p2(1));
line2 = new TLine(p2(0), p2(1), p3(0), p3(1));
line3 = new TLine(p3(0), p3(1), p4(0), p4(1));
line4 = new TLine(p4(0), p4(1), p1(0), p1(1));
line1->SetLineColor(linecolor);
line2->SetLineColor(linecolor);
line3->SetLineColor(linecolor);
line4->SetLineColor(linecolor);
line1->Draw();
line2->Draw();
line3->Draw();
line4->Draw();
}
p1.Rotate(2 * pi / numChambersInRing, x);
p2.Rotate(2 * pi / numChambersInRing, x);
p3.Rotate(2 * pi / numChambersInRing, x);
p4.Rotate(2 * pi / numChambersInRing, x);
}
}
}
|
80b295160bc56d769214b17d2b9dc14d4466e102
|
88aca3340574f733b9ecd6f76708ecd2d57cb07e
|
/vendor/bundle/ruby/2.6.0/gems/commonmarker-0.23.4/ext/commonmarker/commonmark.c
|
2e0719443d721fa0c1156628c414151840092e3a
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
collabnix/dockerlabs
|
65c63a8424d34120bddc0fc8d6fd54a688953491
|
0f2a6b906a8ca0ebc28561236d4d6516f93b184c
|
refs/heads/master
| 2023-09-05T07:30:30.601797
| 2023-09-05T07:25:53
| 2023-09-05T07:25:53
| 153,069,455
| 5,239
| 1,854
|
Apache-2.0
| 2023-09-03T05:51:41
| 2018-10-15T07:19:18
|
PHP
|
UTF-8
|
C
| false
| false
| 14,843
|
c
|
commonmark.c
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <assert.h>
#include "config.h"
#include "cmark-gfm.h"
#include "node.h"
#include "buffer.h"
#include "utf8.h"
#include "scanners.h"
#include "render.h"
#include "syntax_extension.h"
#define OUT(s, wrap, escaping) renderer->out(renderer, node, s, wrap, escaping)
#define LIT(s) renderer->out(renderer, node, s, false, LITERAL)
#define CR() renderer->cr(renderer)
#define BLANKLINE() renderer->blankline(renderer)
#define ENCODED_SIZE 20
#define LISTMARKER_SIZE 20
// Functions to convert cmark_nodes to commonmark strings.
static CMARK_INLINE void outc(cmark_renderer *renderer, cmark_node *node,
cmark_escaping escape,
int32_t c, unsigned char nextc) {
bool needs_escaping = false;
bool follows_digit =
renderer->buffer->size > 0 &&
cmark_isdigit(renderer->buffer->ptr[renderer->buffer->size - 1]);
char encoded[ENCODED_SIZE];
needs_escaping =
c < 0x80 && escape != LITERAL &&
((escape == NORMAL &&
(c < 0x20 ||
c == '*' || c == '_' || c == '[' || c == ']' || c == '#' || c == '<' ||
c == '>' || c == '\\' || c == '`' || c == '~' || c == '!' ||
(c == '&' && cmark_isalpha(nextc)) || (c == '!' && nextc == '[') ||
(renderer->begin_content && (c == '-' || c == '+' || c == '=') &&
// begin_content doesn't get set to false til we've passed digits
// at the beginning of line, so...
!follows_digit) ||
(renderer->begin_content && (c == '.' || c == ')') && follows_digit &&
(nextc == 0 || cmark_isspace(nextc))))) ||
(escape == URL &&
(c == '`' || c == '<' || c == '>' || cmark_isspace((char)c) || c == '\\' ||
c == ')' || c == '(')) ||
(escape == TITLE &&
(c == '`' || c == '<' || c == '>' || c == '"' || c == '\\')));
if (needs_escaping) {
if (escape == URL && cmark_isspace((char)c)) {
// use percent encoding for spaces
snprintf(encoded, ENCODED_SIZE, "%%%2X", c);
cmark_strbuf_puts(renderer->buffer, encoded);
renderer->column += 3;
} else if (cmark_ispunct((char)c)) {
cmark_render_ascii(renderer, "\\");
cmark_render_code_point(renderer, c);
} else { // render as entity
snprintf(encoded, ENCODED_SIZE, "&#%d;", c);
cmark_strbuf_puts(renderer->buffer, encoded);
renderer->column += (int)strlen(encoded);
}
} else {
cmark_render_code_point(renderer, c);
}
}
static int longest_backtick_sequence(const char *code) {
int longest = 0;
int current = 0;
size_t i = 0;
size_t code_len = strlen(code);
while (i <= code_len) {
if (code[i] == '`') {
current++;
} else {
if (current > longest) {
longest = current;
}
current = 0;
}
i++;
}
return longest;
}
static int shortest_unused_backtick_sequence(const char *code) {
// note: if the shortest sequence is >= 32, this returns 32
// so as not to overflow the bit array.
uint32_t used = 1;
int current = 0;
size_t i = 0;
size_t code_len = strlen(code);
while (i <= code_len) {
if (code[i] == '`') {
current++;
} else {
if (current > 0 && current < 32) {
used |= (1U << current);
}
current = 0;
}
i++;
}
// return number of first bit that is 0:
i = 0;
while (i < 32 && used & 1) {
used = used >> 1;
i++;
}
return (int)i;
}
static bool is_autolink(cmark_node *node) {
cmark_chunk *title;
cmark_chunk *url;
cmark_node *link_text;
char *realurl;
int realurllen;
if (node->type != CMARK_NODE_LINK) {
return false;
}
url = &node->as.link.url;
if (url->len == 0 || scan_scheme(url, 0) == 0) {
return false;
}
title = &node->as.link.title;
// if it has a title, we can't treat it as an autolink:
if (title->len > 0) {
return false;
}
link_text = node->first_child;
if (link_text == NULL) {
return false;
}
cmark_consolidate_text_nodes(link_text);
realurl = (char *)url->data;
realurllen = url->len;
if (strncmp(realurl, "mailto:", 7) == 0) {
realurl += 7;
realurllen -= 7;
}
return (realurllen == link_text->as.literal.len &&
strncmp(realurl, (char *)link_text->as.literal.data,
link_text->as.literal.len) == 0);
}
// if node is a block node, returns node.
// otherwise returns first block-level node that is an ancestor of node.
// if there is no block-level ancestor, returns NULL.
static cmark_node *get_containing_block(cmark_node *node) {
while (node) {
if (CMARK_NODE_BLOCK_P(node)) {
return node;
} else {
node = node->parent;
}
}
return NULL;
}
static int S_render_node(cmark_renderer *renderer, cmark_node *node,
cmark_event_type ev_type, int options) {
cmark_node *tmp;
int list_number;
cmark_delim_type list_delim;
int numticks;
bool extra_spaces;
int i;
bool entering = (ev_type == CMARK_EVENT_ENTER);
const char *info, *code, *title;
char fencechar[2] = {'\0', '\0'};
size_t info_len, code_len;
char listmarker[LISTMARKER_SIZE];
char *emph_delim;
bool first_in_list_item;
bufsize_t marker_width;
bool allow_wrap = renderer->width > 0 && !(CMARK_OPT_NOBREAKS & options) &&
!(CMARK_OPT_HARDBREAKS & options);
// Don't adjust tight list status til we've started the list.
// Otherwise we loose the blank line between a paragraph and
// a following list.
if (!(node->type == CMARK_NODE_ITEM && node->prev == NULL && entering)) {
tmp = get_containing_block(node);
renderer->in_tight_list_item =
tmp && // tmp might be NULL if there is no containing block
((tmp->type == CMARK_NODE_ITEM &&
cmark_node_get_list_tight(tmp->parent)) ||
(tmp && tmp->parent && tmp->parent->type == CMARK_NODE_ITEM &&
cmark_node_get_list_tight(tmp->parent->parent)));
}
if (node->extension && node->extension->commonmark_render_func) {
node->extension->commonmark_render_func(node->extension, renderer, node, ev_type, options);
return 1;
}
switch (node->type) {
case CMARK_NODE_DOCUMENT:
break;
case CMARK_NODE_BLOCK_QUOTE:
if (entering) {
LIT("> ");
renderer->begin_content = true;
cmark_strbuf_puts(renderer->prefix, "> ");
} else {
cmark_strbuf_truncate(renderer->prefix, renderer->prefix->size - 2);
BLANKLINE();
}
break;
case CMARK_NODE_LIST:
if (!entering && node->next && (node->next->type == CMARK_NODE_CODE_BLOCK ||
node->next->type == CMARK_NODE_LIST)) {
// this ensures that a following indented code block or list will be
// inteprereted correctly.
CR();
LIT("<!-- end list -->");
BLANKLINE();
}
break;
case CMARK_NODE_ITEM:
if (cmark_node_get_list_type(node->parent) == CMARK_BULLET_LIST) {
marker_width = 4;
} else {
list_number = cmark_node_get_list_start(node->parent);
list_delim = cmark_node_get_list_delim(node->parent);
tmp = node;
while (tmp->prev) {
tmp = tmp->prev;
list_number += 1;
}
// we ensure a width of at least 4 so
// we get nice transition from single digits
// to double
snprintf(listmarker, LISTMARKER_SIZE, "%d%s%s", list_number,
list_delim == CMARK_PAREN_DELIM ? ")" : ".",
list_number < 10 ? " " : " ");
marker_width = (bufsize_t)strlen(listmarker);
}
if (entering) {
if (cmark_node_get_list_type(node->parent) == CMARK_BULLET_LIST) {
LIT(" - ");
renderer->begin_content = true;
} else {
LIT(listmarker);
renderer->begin_content = true;
}
for (i = marker_width; i--;) {
cmark_strbuf_putc(renderer->prefix, ' ');
}
} else {
cmark_strbuf_truncate(renderer->prefix,
renderer->prefix->size - marker_width);
CR();
}
break;
case CMARK_NODE_HEADING:
if (entering) {
for (i = cmark_node_get_heading_level(node); i > 0; i--) {
LIT("#");
}
LIT(" ");
renderer->begin_content = true;
renderer->no_linebreaks = true;
} else {
renderer->no_linebreaks = false;
BLANKLINE();
}
break;
case CMARK_NODE_CODE_BLOCK:
first_in_list_item = node->prev == NULL && node->parent &&
node->parent->type == CMARK_NODE_ITEM;
if (!first_in_list_item) {
BLANKLINE();
}
info = cmark_node_get_fence_info(node);
info_len = strlen(info);
fencechar[0] = strchr(info, '`') == NULL ? '`' : '~';
code = cmark_node_get_literal(node);
code_len = strlen(code);
// use indented form if no info, and code doesn't
// begin or end with a blank line, and code isn't
// first thing in a list item
if (info_len == 0 && (code_len > 2 && !cmark_isspace(code[0]) &&
!(cmark_isspace(code[code_len - 1]) &&
cmark_isspace(code[code_len - 2]))) &&
!first_in_list_item) {
LIT(" ");
cmark_strbuf_puts(renderer->prefix, " ");
OUT(cmark_node_get_literal(node), false, LITERAL);
cmark_strbuf_truncate(renderer->prefix, renderer->prefix->size - 4);
} else {
numticks = longest_backtick_sequence(code) + 1;
if (numticks < 3) {
numticks = 3;
}
for (i = 0; i < numticks; i++) {
LIT(fencechar);
}
LIT(" ");
OUT(info, false, LITERAL);
CR();
OUT(cmark_node_get_literal(node), false, LITERAL);
CR();
for (i = 0; i < numticks; i++) {
LIT(fencechar);
}
}
BLANKLINE();
break;
case CMARK_NODE_HTML_BLOCK:
BLANKLINE();
OUT(cmark_node_get_literal(node), false, LITERAL);
BLANKLINE();
break;
case CMARK_NODE_CUSTOM_BLOCK:
BLANKLINE();
OUT(entering ? cmark_node_get_on_enter(node) : cmark_node_get_on_exit(node),
false, LITERAL);
BLANKLINE();
break;
case CMARK_NODE_THEMATIC_BREAK:
BLANKLINE();
LIT("-----");
BLANKLINE();
break;
case CMARK_NODE_PARAGRAPH:
if (!entering) {
BLANKLINE();
}
break;
case CMARK_NODE_TEXT:
OUT(cmark_node_get_literal(node), allow_wrap, NORMAL);
break;
case CMARK_NODE_LINEBREAK:
if (!(CMARK_OPT_HARDBREAKS & options)) {
LIT(" ");
}
CR();
break;
case CMARK_NODE_SOFTBREAK:
if (CMARK_OPT_HARDBREAKS & options) {
LIT(" ");
CR();
} else if (!renderer->no_linebreaks && renderer->width == 0 &&
!(CMARK_OPT_HARDBREAKS & options) &&
!(CMARK_OPT_NOBREAKS & options)) {
CR();
} else {
OUT(" ", allow_wrap, LITERAL);
}
break;
case CMARK_NODE_CODE:
code = cmark_node_get_literal(node);
code_len = strlen(code);
numticks = shortest_unused_backtick_sequence(code);
extra_spaces = code_len == 0 ||
code[0] == '`' || code[code_len - 1] == '`' ||
code[0] == ' ' || code[code_len - 1] == ' ';
for (i = 0; i < numticks; i++) {
LIT("`");
}
if (extra_spaces) {
LIT(" ");
}
OUT(cmark_node_get_literal(node), allow_wrap, LITERAL);
if (extra_spaces) {
LIT(" ");
}
for (i = 0; i < numticks; i++) {
LIT("`");
}
break;
case CMARK_NODE_HTML_INLINE:
OUT(cmark_node_get_literal(node), false, LITERAL);
break;
case CMARK_NODE_CUSTOM_INLINE:
OUT(entering ? cmark_node_get_on_enter(node) : cmark_node_get_on_exit(node),
false, LITERAL);
break;
case CMARK_NODE_STRONG:
if (entering) {
LIT("**");
} else {
LIT("**");
}
break;
case CMARK_NODE_EMPH:
// If we have EMPH(EMPH(x)), we need to use *_x_*
// because **x** is STRONG(x):
if (node->parent && node->parent->type == CMARK_NODE_EMPH &&
node->next == NULL && node->prev == NULL) {
emph_delim = "_";
} else {
emph_delim = "*";
}
if (entering) {
LIT(emph_delim);
} else {
LIT(emph_delim);
}
break;
case CMARK_NODE_LINK:
if (is_autolink(node)) {
if (entering) {
LIT("<");
if (strncmp(cmark_node_get_url(node), "mailto:", 7) == 0) {
LIT((const char *)cmark_node_get_url(node) + 7);
} else {
LIT((const char *)cmark_node_get_url(node));
}
LIT(">");
// return signal to skip contents of node...
return 0;
}
} else {
if (entering) {
LIT("[");
} else {
LIT("](");
OUT(cmark_node_get_url(node), false, URL);
title = cmark_node_get_title(node);
if (strlen(title) > 0) {
LIT(" \"");
OUT(title, false, TITLE);
LIT("\"");
}
LIT(")");
}
}
break;
case CMARK_NODE_IMAGE:
if (entering) {
LIT(";
OUT(cmark_node_get_url(node), false, URL);
title = cmark_node_get_title(node);
if (strlen(title) > 0) {
OUT(" \"", allow_wrap, LITERAL);
OUT(title, false, TITLE);
LIT("\"");
}
LIT(")");
}
break;
case CMARK_NODE_FOOTNOTE_REFERENCE:
if (entering) {
LIT("[^");
char *footnote_label = renderer->mem->calloc(node->parent_footnote_def->as.literal.len + 1, sizeof(char));
memmove(footnote_label, node->parent_footnote_def->as.literal.data, node->parent_footnote_def->as.literal.len);
OUT(footnote_label, false, LITERAL);
renderer->mem->free(footnote_label);
LIT("]");
}
break;
case CMARK_NODE_FOOTNOTE_DEFINITION:
if (entering) {
renderer->footnote_ix += 1;
LIT("[^");
char *footnote_label = renderer->mem->calloc(node->as.literal.len + 1, sizeof(char));
memmove(footnote_label, node->as.literal.data, node->as.literal.len);
OUT(footnote_label, false, LITERAL);
renderer->mem->free(footnote_label);
LIT("]:\n");
cmark_strbuf_puts(renderer->prefix, " ");
} else {
cmark_strbuf_truncate(renderer->prefix, renderer->prefix->size - 4);
}
break;
default:
assert(false);
break;
}
return 1;
}
char *cmark_render_commonmark(cmark_node *root, int options, int width) {
return cmark_render_commonmark_with_mem(root, options, width, cmark_node_mem(root));
}
char *cmark_render_commonmark_with_mem(cmark_node *root, int options, int width, cmark_mem *mem) {
if (options & CMARK_OPT_HARDBREAKS) {
// disable breaking on width, since it has
// a different meaning with OPT_HARDBREAKS
width = 0;
}
return cmark_render(mem, root, options, width, outc, S_render_node);
}
|
f3ad14eff514ab924c4dd7668cca800430352411
|
fb0f9abad373cd635c2635bbdf491ea0f32da5ff
|
/src/native/external/libunwind/src/sh/offsets.h
|
b02d8aee1e00087768d63828cde49e76da60ab33
|
[
"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
| 950
|
h
|
offsets.h
|
/* Linux-specific definitions: */
/* Define various structure offsets to simplify cross-compilation. */
/* Offsets for SH Linux "ucontext_t": */
#define LINUX_UC_FLAGS_OFF 0x0
#define LINUX_UC_LINK_OFF 0x4
#define LINUX_UC_STACK_OFF 0x8
#define LINUX_UC_MCONTEXT_OFF 0x14
#define LINUX_UC_SIGMASK_OFF 0xFC
/* Offsets for SH Linux "struct sigcontext": */
#define LINUX_SC_R0_OFF 0x4
#define LINUX_SC_R1_OFF 0x8
#define LINUX_SC_R2_OFF 0xC
#define LINUX_SC_R3_OFF 0x10
#define LINUX_SC_R4_OFF 0x14
#define LINUX_SC_R5_OFF 0x18
#define LINUX_SC_R6_OFF 0x1C
#define LINUX_SC_R7_OFF 0x20
#define LINUX_SC_R8_OFF 0x24
#define LINUX_SC_R9_OFF 0x28
#define LINUX_SC_R10_OFF 0x2C
#define LINUX_SC_R11_OFF 0x30
#define LINUX_SC_R12_OFF 0x34
#define LINUX_SC_R13_OFF 0x38
#define LINUX_SC_R14_OFF 0x3C
#define LINUX_SC_R15_OFF 0x40
#define LINUX_SC_PC_OFF 0x44
#define LINUX_SC_PR_OFF 0x48
|
aa735463f79daed7de61bcda4bdcc93e716995a0
|
4ba76056c744ada0a01fb27b7cad8464cefc7aa0
|
/supports/toolchains/LiveEditor/PainterEngine_LiveEditorModules_Exportlive.c
|
69d002bcd6bd9ca07b77c4d8cc1c6038d42d6d96
|
[
"BSD-3-Clause"
] |
permissive
|
matrixcascade/PainterEngine
|
23e110e25a39e1d016ed7936eac23e06932456b4
|
1d3e6e85f337e8a8db44680094ab3f4b988507cb
|
refs/heads/master
| 2023-08-29T11:29:26.934779
| 2023-08-23T09:23:04
| 2023-08-23T09:23:04
| 190,119,926
| 1,989
| 253
|
BSD-3-Clause
| 2023-09-05T12:19:31
| 2019-06-04T03:08:26
|
C
|
UTF-8
|
C
| false
| false
| 4,271
|
c
|
PainterEngine_LiveEditorModules_Exportlive.c
|
#include "PainterEngine_LiveEditorModules_ExportLive.h"
static px_int PX_ExportLive_ExplorerGetPathFolderCount(const px_char *path,const char *filter)
{
return PX_FileGetDirectoryFileCount(path,PX_FILEENUM_TYPE_FOLDER,filter);
}
static px_int PX_ExportLive_ExplorerGetPathFileCount(const px_char *path,const char *filter)
{
return 0;
}
static px_int PX_ExportLive_ExplorerGetPathFolderName(const char path[],int count,char FileName[][260],const char *filter)
{
return PX_FileGetDirectoryFileName(path,count,FileName,PX_FILEENUM_TYPE_FOLDER,filter);
}
static px_int PX_ExportLive_ExplorerGetPathFileName(const char path[],int count,char FileName[][260],const char *filter)
{
return 0;
}
px_void PX_Application_OnExportLive_OnConfirm(PX_Object *pObject,PX_Object_Event e,px_void *ptr)
{
px_char path[260];
px_int index=0;
PX_Object *pExportLiveObject=(PX_Object *)ptr;
PX_LiveEditorModule_ExportLive *pExportLive=(PX_LiveEditorModule_ExportLive *)pExportLiveObject->pObject;
PX_Object_ExplorerGetPath(pExportLive->explorer,path,index);
if (!path[0])
{
return;
}
PX_strcat(path,"\\release.live");
do
{
px_byte *cacheBuffer=(px_byte *)malloc(64*1024*1024);
px_memorypool mp=MP_Create(cacheBuffer,64*1024*1024);
px_memory data;
PX_MemoryInitialize(&mp,&data);
if(!PX_LiveFrameworkExport(pExportLive->pLiveFramework,&data))
{
px_char content[260];
PX_sprintf2(content,sizeof(content),"%1 %2",PX_STRINGFORMAT_STRING(PX_JsonGetString(pExportLive->pLanguageJson,"exportlive.out of memory")),PX_STRINGFORMAT_STRING((path)));
PX_ObjectPostEvent(pExportLiveObject->pParent,PX_OBJECT_BUILD_EVENT_STRING(PX_LIVEEDITORMODULE_EXPORTLIVE_EVENT_MESSAGE,content));
}
if(!PX_SaveDataToFile(data.buffer,data.usedsize,path))
{
px_char content[260];
PX_sprintf2(content,sizeof(content),"%1 %2",PX_STRINGFORMAT_STRING(PX_JsonGetString(pExportLive->pLanguageJson,"exportlive.could not export file")),PX_STRINGFORMAT_STRING((path)));
PX_ObjectPostEvent(pExportLiveObject->pParent,PX_OBJECT_BUILD_EVENT_STRING(PX_LIVEEDITORMODULE_EXPORTLIVE_EVENT_MESSAGE,content));
}
do
{
px_char content[260];
PX_sprintf2(content,sizeof(content),"%1 %2",PX_STRINGFORMAT_STRING(PX_JsonGetString(pExportLive->pLanguageJson,"exportlive.succeeded")),PX_STRINGFORMAT_STRING((path)));
PX_ObjectPostEvent(pExportLiveObject->pParent,PX_OBJECT_BUILD_EVENT_STRING(PX_LIVEEDITORMODULE_EXPORTLIVE_EVENT_MESSAGE,content));
} while (0);
} while (0);
}
PX_Object * PX_LiveEditorModule_ExportLiveInstall(PX_Object *parent,PX_Runtime *pruntime,PX_FontModule *fm,PX_LiveFramework *pLiveFramework,PX_Json *pLanguageJson)
{
PX_Object *pObject;
PX_LiveEditorModule_ExportLive ExportLive,*pExportLive;
PX_memset(&ExportLive,0,sizeof(ExportLive));
pObject=PX_ObjectCreateEx(&pruntime->mp_ui,parent,0,0,0,0,0,0,0,0,0,0,&ExportLive,sizeof(ExportLive));
pExportLive=(PX_LiveEditorModule_ExportLive *)pObject->pObject;
pExportLive->fontmodule=fm;
pExportLive->pLanguageJson=pLanguageJson;
pExportLive->pLiveFramework=pLiveFramework;
pExportLive->pruntime=pruntime;
pExportLive->explorer=PX_Object_ExplorerCreate(&pruntime->mp_ui,pObject,0,0,pruntime->surface_width,pruntime->surface_height,fm,\
PX_ExportLive_ExplorerGetPathFolderCount,\
PX_ExportLive_ExplorerGetPathFileCount,\
PX_ExportLive_ExplorerGetPathFolderName,\
PX_ExportLive_ExplorerGetPathFileName,\
"");
PX_Object_ExplorerSetFilter(pExportLive->explorer,".live\0.LIVE\0.Live");
PX_Object_ExplorerSetMaxSelectCount(pExportLive->explorer,1);
PX_ObjectRegisterEvent(pExportLive->explorer,PX_OBJECT_EVENT_EXECUTE,PX_Application_OnExportLive_OnConfirm,pObject);
return pObject;
}
px_void PX_LiveEditorModule_ExportLiveUninstall(PX_Object *pObject)
{
PX_ObjectDelete(pObject);
}
px_void PX_LiveEditorModule_ExportLiveEnable(PX_Object *pObject)
{
PX_LiveEditorModule_ExportLive *pExportLive=(PX_LiveEditorModule_ExportLive *)pObject->pObject;
PX_Object_ExplorerOpen(pExportLive->explorer);
}
px_void PX_LiveEditorModule_ExportLiveDisable(PX_Object *pObject)
{
PX_LiveEditorModule_ExportLive *pExportLive=(PX_LiveEditorModule_ExportLive *)pObject->pObject;
PX_ObjectReleaseFocus(pObject);
PX_Object_ExplorerClose(pExportLive->explorer);
}
|
eb755006be3ecb1dcc483005445863614088bd7f
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/arch/c6x/mm/dma-coherent.c
|
4187e5180373fc706301993c010d4cd7b7d25d55
|
[
"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
| 3,232
|
c
|
dma-coherent.c
|
/*
* Port on Texas Instruments TMS320C6x architecture
*
* Copyright (C) 2004, 2009, 2010, 2011 Texas Instruments Incorporated
* Author: Aurelien Jacquiot <aurelien.jacquiot@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* DMA uncached mapping support.
*
* Using code pulled from ARM
* Copyright (C) 2000-2004 Russell King
*
*/
#include <linux/slab.h>
#include <linux/bitmap.h>
#include <linux/bitops.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/memblock.h>
#include <asm/page.h>
/*
* DMA coherent memory management, can be redefined using the memdma=
* kernel command line
*/
/* none by default */
static phys_addr_t dma_base;
static u32 dma_size;
static u32 dma_pages;
static unsigned long *dma_bitmap;
/* bitmap lock */
static DEFINE_SPINLOCK(dma_lock);
/*
* Return a DMA coherent and contiguous memory chunk from the DMA memory
*/
static inline u32 __alloc_dma_pages(int order)
{
unsigned long flags;
u32 pos;
spin_lock_irqsave(&dma_lock, flags);
pos = bitmap_find_free_region(dma_bitmap, dma_pages, order);
spin_unlock_irqrestore(&dma_lock, flags);
return dma_base + (pos << PAGE_SHIFT);
}
static void __free_dma_pages(u32 addr, int order)
{
unsigned long flags;
u32 pos = (addr - dma_base) >> PAGE_SHIFT;
if (addr < dma_base || (pos + (1 << order)) >= dma_pages) {
printk(KERN_ERR "%s: freeing outside range.\n", __func__);
BUG();
}
spin_lock_irqsave(&dma_lock, flags);
bitmap_release_region(dma_bitmap, pos, order);
spin_unlock_irqrestore(&dma_lock, flags);
}
/*
* Allocate DMA coherent memory space and return both the kernel
* virtual and DMA address for that space.
*/
void *dma_alloc_coherent(struct device *dev, size_t size,
dma_addr_t *handle, gfp_t gfp)
{
u32 paddr;
int order;
if (!dma_size || !size)
return NULL;
order = get_count_order(((size - 1) >> PAGE_SHIFT) + 1);
paddr = __alloc_dma_pages(order);
if (handle)
*handle = paddr;
if (!paddr)
return NULL;
return phys_to_virt(paddr);
}
EXPORT_SYMBOL(dma_alloc_coherent);
/*
* Free DMA coherent memory as defined by the above mapping.
*/
void dma_free_coherent(struct device *dev, size_t size, void *vaddr,
dma_addr_t dma_handle)
{
int order;
if (!dma_size || !size)
return;
order = get_count_order(((size - 1) >> PAGE_SHIFT) + 1);
__free_dma_pages(virt_to_phys(vaddr), order);
}
EXPORT_SYMBOL(dma_free_coherent);
/*
* Initialise the coherent DMA memory allocator using the given uncached region.
*/
void __init coherent_mem_init(phys_addr_t start, u32 size)
{
phys_addr_t bitmap_phys;
if (!size)
return;
printk(KERN_INFO
"Coherent memory (DMA) region start=0x%x size=0x%x\n",
start, size);
dma_base = start;
dma_size = size;
/* allocate bitmap */
dma_pages = dma_size >> PAGE_SHIFT;
if (dma_size & (PAGE_SIZE - 1))
++dma_pages;
bitmap_phys = memblock_alloc(BITS_TO_LONGS(dma_pages) * sizeof(long),
sizeof(long));
dma_bitmap = phys_to_virt(bitmap_phys);
memset(dma_bitmap, 0, dma_pages * PAGE_SIZE);
}
|
3e7c043ac7f93b9857e8a5cefce23cec9fdb8d6a
|
19a9f2c19bcb81c4a14ba17831d3098de7731fb5
|
/ncarview/src/bin/rascat/rascat.c
|
04af00ff9d8907945cb484508249cc168bcb89c5
|
[
"Apache-2.0"
] |
permissive
|
NCAR/ncl
|
243c30eaefce642d53373aa583b73df72eb59f22
|
8a96101fe14d0cf0f5ed66a5e6b1733084bc69df
|
refs/heads/develop
| 2023-03-17T07:53:18.883458
| 2022-05-11T16:01:03
| 2022-05-11T16:01:03
| 67,087,395
| 254
| 68
|
NOASSERTION
| 2022-10-08T07:20:06
| 2016-09-01T01:34:28
|
C
|
UTF-8
|
C
| false
| false
| 15,160
|
c
|
rascat.c
|
/*
* $Id: rascat.c,v 1.25 2008-07-27 03:18:40 haley Exp $
*/
/************************************************************************
* *
* Copyright (C) 2000 *
* University Corporation for Atmospheric Research *
* All Rights Reserved *
* *
* The use of this Software is governed by a License Agreement. *
* *
************************************************************************/
/*
* File: rascat.c
*
* Author: Don Middleton-Link
* National Center for Atmospheric Research
* PO 3000, Boulder, Colorado
*
* Rev 1.1 John Clyne
*
* Date: Wed Feb 12 20:12:58 MST 1992
*
* Description: Read raster files and concatenate them to the
* standard output. The input files need not be of
* the same format but they must have the same resolution
* and encoding.
*
* Syntax: rascat [-v] [-V] [-ifmt format] [-ofmt format]
* [-win nx ny x y] [-o file] [ - | file... ]
*
* Options:
*
* -verbose Operate in verbose mode
*
* -Version Print version number to the tty
*
* -ifmt <format>
* 'format' specifies the file format of *all*
* the input raster files. If ommitted, file
* format is determined by the file name extension
*
* -ofmt <format>
* 'format' specifies the file format of the raster
* file to be written to. If ommitted, the output
* file format will be the same as the format
* of the *first* input file.
*
* -win <nx ny x y>
* nx, ny, x, and y specify a sub-region of the
* input file. 'x' and 'y' specify the upper-left
* corner. 'nx' and 'ny' specify the width
* and height of the region, respectively. The
* default is to copy the entire image.
*
* -outfile <file>
* Write output to 'file' instead of the standard
* output.
*
* - Read from standard input. The default.
*
* -scale <factor>
* Scale the input image by <factor>
*
* -resolution <nx>x<ny>
* Resample the input image to the resolution
* 'nx'x'ny'.
*
* -ira [nn|bl]
* Specify Nearest Neighbor (nn) or Bilinear
* interpolation (bl) algorithm for resampling.
*
* Environment:
*
*/
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <ncarg/c.h>
#include <ncarg/ncarg_ras.h>
static int cvt_to_rsfunc(const char *from, Voidptr to);
static int cvt_to_etype(const char *from, Voidptr to);
typedef struct Subregion_ {
int nx;
int ny;
int x;
int y;
} Subregion;
/*
* command line options
*/
static struct {
boolean do_verbose;
boolean do_version;
Subregion win;
boolean do_stdin;
char *dstfile;
char *srcformat;
char *dstformat;
float scale;
float rgbscale;
Dimension2D resolution;
boolean do_help;
char *pal;
RasterEncoding outtype;
int (*resample)();
} opt;
static OptDescRec set_options[] = {
{"verbose", 0, NULL, "Do operate in verbose mode"},
{"Version", 0, NULL, "Print version and exit"},
{"window", 4, "-1 -1 -1 -1", "Extract a subregion - nx ny x y"},
{"", 0, NULL, "Do get input from standard input"},
{"output", 1, "stdout", "Specify output file"},
{"ifmt", 1, NULL, "Specify format of input file"},
{"ofmt", 1, NULL, "Specify format of output file"},
{"scale", 1, "0.0", "Specify image scaling factor"},
{"rgbscale", 1, "1.0", "Specify color intensity scaling factor"},
{"resolution", 1, "0x0", "Specify output image resolution"},
{"help", 0, "NULL", "Print this message and exit"},
{"ira", 1, "nn", "Specify resampling algo, nn or bl"},
{"pal", 1, NULL, "Specify a color palette"},
{"outtype", 1, NULL, "Force output encoding type, indexed or direct"},
{NULL},
};
static Option get_options[] = {
{"verbose", NCARGCvtToBoolean, (Voidptr) &opt.do_verbose,
sizeof(opt.do_verbose)
},
{"Version", NCARGCvtToBoolean, (Voidptr) &opt.do_version,
sizeof(opt.do_version)
},
{"window", NCARGCvtToInt, (Voidptr) &opt.win, sizeof (opt.win.nx)
},
{"", NCARGCvtToBoolean, (Voidptr) &opt.do_stdin, sizeof(opt.do_stdin)
},
{"output", NCARGCvtToString, (Voidptr) &opt.dstfile, sizeof(opt.dstfile)
},
{"ifmt", NCARGCvtToString, (Voidptr) &opt.srcformat,
sizeof(opt.srcformat)
},
{"ofmt", NCARGCvtToString, (Voidptr) &opt.dstformat,
sizeof(opt.dstformat)
},
{"scale", NCARGCvtToFloat, (Voidptr) &opt.scale, sizeof(opt.scale)
},
{"rgbscale", NCARGCvtToFloat, (Voidptr) &opt.rgbscale,
sizeof(opt.rgbscale)
},
{"resolution", NCARGCvtToDimension2D, (Voidptr) &opt.resolution,
sizeof(opt.resolution)
},
{"help", NCARGCvtToBoolean, (Voidptr) &opt.do_help,
sizeof(opt.do_help)
},
{"ira", cvt_to_rsfunc, (Voidptr) &opt.resample, sizeof(opt.resample)
},
{"pal", NCARGCvtToString, (Voidptr) &opt.pal,
sizeof(opt.pal)
},
{"outtype", cvt_to_etype, (Voidptr) &opt.outtype,
sizeof(opt.outtype)
},
{NULL
}
};
/*
* default input file
*/
static char *stdin_array[] = {"stdin"};
static char *progName;
static int oD;
static void Usage(msg)
char *msg;
{
char *opts = "[-v] [-ifmt format] [-ofmt format] [-win nx ny x y] [-o file] [-scale factor | -res resolution [ -ira nn | bl]] [-rgbscale factor] [ - | file... ]";
if (msg) {
(void) fprintf(stderr, "%s: %s\n", progName, msg);
}
(void) fprintf(stderr, "Usage: %s %s\n", progName, opts);
PrintOptionHelp(oD, stderr);
exit(1);
}
main(argc, argv)
int argc;
char *argv[];
{
boolean do_window = False;
boolean do_scale = False;
boolean do_res = False;
boolean do_quant = False;
char *Comment = "Created by rascat";
Raster *src, *dst;
int frame = 1; /* num frames processed */
int src_frame; /* current source frame */
int rc; /* return codes */
int nX, nY; /* source dimension */
RasterEncoding rasterType; /* source encoding type */
Subregion *win;
int rcount; /* number of files to process */
char **rfiles; /* the input files */
int pipe_count = 0; /* number filters in pipeline */
Raster *win_ras = (Raster *) NULL;
Raster *sca_ras = (Raster *) NULL;
Raster *quant_ras = (Raster *) NULL;
int err = 0; /* exit rc */
int i;
unsigned char colors[768];
#ifdef DEAD
progName = (progName = strrchr(argv[0],'/')) ? ++progName : *argv;
#endif
if ((progName = strrchr(argv[0],'/')) == (char *) NULL) {
progName = *argv;
}
else {
++progName;
}
(void) RasterInit(&argc, argv);
oD = OpenOptionTbl();
if (ParseOptionTable(oD, &argc, argv, set_options) < 0) {
(void) fprintf(
stderr, "%s : Error parsing options : %s\n",
progName, ErrGetMsg()
);
exit(1);
}
/*
* load the options into opt
*/
if (GetOptions(oD, get_options) < 0) {
(void) fprintf(
stderr, "%s : Error getting options : %s\n",
progName, ErrGetMsg()
);
Usage(NULL);
}
if (opt.do_version) {
PrintVersion(progName);
exit(0);
}
if (opt.do_help) {
Usage(NULL);
}
win = &opt.win;
do_window = win->nx != -1;
do_scale = opt.scale != 0;
do_res = (! (opt.resolution.nx == 0 && opt.resolution.ny == 0));
do_quant = (opt.outtype != RAS_UNKNOWN);
if (do_scale && do_res) {
Usage("-scale and -res are mutually exclusive options");
}
/*
* count the number of image filters
*/
if (do_window) pipe_count++;
if (do_scale) pipe_count++;
if (do_res) pipe_count++;
if (do_quant) pipe_count++;
/*
* make sure no options left on command line
*/
for(i=1; i<argc; i++) {
if (*argv[i] == '-') {
(void) fprintf(
stderr, "%s: Invalid option : %s\n",
progName, argv[i]
);
Usage(NULL);
}
}
/*
* if no files read from stdin
*/
if (argc < 2) {
rcount = 1;
rfiles = stdin_array;
}
else {
rcount = argc - 1;
rfiles = argv + 1;
}
dst = (Raster *) NULL;
err = 0;
for(i=0; i<rcount; i++) {
src_frame = 1;
/* Open the source file and read the header. */
src = RasterOpen(rfiles[i], opt.srcformat);
if (src == (Raster *) NULL) {
(void) fprintf(stderr,
"%s: RasterOpen(%s, %s) [ %s ]\n",
progName, rfiles[i],
opt.srcformat ? opt.srcformat : "NULL",
ErrGetMsg()
);
err++;
continue;
}
rc = RasterRead(src);
if (rc != RAS_OK) {
fprintf(
stderr, "%s: Reading input file(%s) [ %s ]\n",
progName, rfiles[i], ErrGetMsg()
);
(void) RasterClose(src);
err++;
continue;
}
/*
* if this is the first time through open the destination
* file. We have to do this now because we can't open
* the output file until we know the encoding of the input
* file.
*/
if (! dst) {
int nx = src->nx;
int ny = src->ny;
RasterEncoding type = src->type;
int pipe_count_ = pipe_count;
/*
* if output is stdout and output format is unspecified
* use the input format. If thats not specified
* use whatever format the first input file is
*/
if (!strcmp(opt.dstfile,"stdout") &&
opt.dstformat == NULL)
{
opt.dstformat = src->format;
(void) fprintf(stderr,
"%s: Warning: output format not specified, using input format (%s)\n", progName, src->format
);
}
/*
* if an output encoding type was specified and
* the source type is the same as the requested
* out type - do nothing
*/
if (do_quant) {
if (opt.outtype == src->type) {
do_quant = False;
pipe_count--; pipe_count_--;
}
}
if (do_window) {
pipe_count_--;
nx = win->nx;
ny = win->ny;
check_win(win, src);
if (pipe_count_ > 0) {
win_ras = RasterCreate(nx,ny,src->type);
if (! win_ras) {
(void) fprintf(stderr,
"%s : RasterCreate() : %s\n",
progName, RasterGetError());
}
}
}
else {
win->x = 0; win->nx = src->nx;
win->y = 0; win->ny = src->ny;
}
if (do_scale || do_res) {
pipe_count_--;
if (do_scale) {
nx *= opt.scale;
ny *= opt.scale;
}
else if (do_res) {
nx = opt.resolution.nx;
ny = opt.resolution.ny;
}
if (pipe_count_ > 0) {
sca_ras = RasterCreate(nx,ny,src->type);
if (! sca_ras) {
(void) fprintf(stderr,
"%s : RasterCreate() : %s\n",
progName, RasterGetError());
}
}
}
if (do_quant) {
pipe_count_--;
type = opt.outtype;
if (pipe_count_ > 0) {
quant_ras = RasterCreate(nx,ny,type);
if (! quant_ras) {
(void) fprintf(stderr,
"%s : RasterCreate() : %s\n",
progName, RasterGetError());
}
}
}
dst = RasterOpenWrite(
opt.dstfile,nx,ny, Comment,
type, opt.dstformat
);
if (dst == (Raster *) NULL) {
(void) fprintf(stderr,
"%s: RasterOpenWrite(%s, %d, %d, %s,%d,%s) [ %s ]\n",
progName, opt.dstfile, nx, ny, Comment,
type,
opt.dstformat ? opt.dstformat : "NULL",
ErrGetMsg()
);
(void) RasterClose(src);
exit(1);
}
rasterType = src->type;
nX = src->nx;
nY = src->ny;
}
else {
if (! (src->nx == nX && src->ny == nY)) {
(void) fprintf(
stderr,
"%s: Raster size changes not allowed\n",
progName
);
RasterClose(src);
continue;
}
if (src->type != rasterType) {
(void) fprintf(
stderr,
"%s: Raster enconding changes not allowed\n",
progName
);
RasterClose(src);
continue;
}
}
do {
Raster *tmp = src;
Raster *new = src;
if (do_window || pipe_count == 0) {
new = win_ras ? win_ras : dst;
(void) RasterCopyColormap(tmp,new);
RasterOp(
tmp,new,win->x,win->y,
win->nx, win->ny,0,0,0
);
tmp = win_ras;
}
if (do_scale || do_res) {
new = sca_ras ? sca_ras : dst;
(void) RasterCopyColormap(tmp,new);
rc = opt.resample(tmp, new, opt.do_verbose);
if (rc != RAS_OK) {
(void) fprintf(
stderr,
"%s: Resampling failed : %s\n",
progName, RasterGetError()
);
exit(1);
}
tmp = sca_ras;
}
if (do_quant) {
new = quant_ras ? quant_ras : dst;
if (opt.outtype == RAS_INDEXED) {
rc = RasterDither(
tmp, new, opt.do_verbose
);
}
else {
rc = Raster8to24bit(
tmp, new, opt.do_verbose
);
}
if (rc != RAS_OK) {
(void) fprintf(
stderr,
"%s: Quantizing failed : %s\n",
progName, RasterGetError()
);
exit(1);
}
tmp = sca_ras;
}
if (opt.rgbscale != 1.0) {
if (RasterRGBScale(dst, opt.rgbscale) < 0) {
(void) fprintf(
stderr,
"%s: Color scaling failed : %s\n",
progName, RasterGetError()
);
err++;
}
}
if (dst->type == RAS_INDEXED && opt.pal &&
!dst->map_forced) {
rc = PaletteRead(opt.pal,NULL,colors);
if (rc != RAS_OK) {
(void) fprintf(stderr,
"%s: PaletteRead of \"%s\" failed: %s\n",
progName, opt.pal, RasterGetError());
err++;
}
rc = RasterLoadPalette(dst, colors);
if (rc != RAS_OK) {
(void) fprintf(stderr,
"%s: RasterLoadPalette failed\n",
progName, opt.pal, RasterGetError());
err++;
}
}
if (dst->type == RAS_DIRECT && opt.pal) {
(void) fprintf(stderr,
"%s: You can't add a palette to a true-color image\n",
progName);
exit(1);
}
rc = RasterWrite(dst);
if (rc != RAS_OK) {
(void) fprintf(
stderr,
"Writing output file(%s) [ %s ]\n",
opt.dstfile, ErrGetMsg()
);
exit(1);
}
if (opt.do_verbose) {
(void) fprintf(
stderr,
"Copied frame %s[%d] to %s[%d]\n",
rfiles[i], src_frame++,
opt.dstfile, frame++
);
}
rc = RasterRead(src);
} while ( rc == RAS_OK );
if (rc == RAS_ERROR) {
(void) fprintf(
stderr,"Reading source file(%s) [ %s ]\n",
rfiles[i], ErrGetMsg()
);
}
(void) RasterClose(src);
}
if (dst) RasterClose(dst);
exit(err);
}
static int cvt_to_rsfunc(from, to)
const char *from;
Voidptr to;
{
int (**fptr)() = (int (**)()) to;
if (! from) {
*fptr = RasterResampleNearestNeighbor;
}
else if (strcmp(from, "NN") == 0 || strcmp(from, "nn") == 0) {
*fptr = RasterResampleNearestNeighbor;
}
else if (strcmp(from, "BL") == 0 || strcmp(from, "bl") == 0) {
*fptr = RasterResampleBilinear;
}
else {
ESprintf(EINVAL, "Convert(%s) to function failed", from);
return(-1);
}
return(1);
}
static int cvt_to_etype(const char *from, Voidptr to)
{
RasterEncoding *type = (RasterEncoding *) to;
if (! from) {
*type = RAS_UNKNOWN;
}
else if (strncmp(from, "indexed", 3) == 0) {
*type = RAS_INDEXED;
}
else if (strncmp(from, "direct", 3) == 0) {
*type = RAS_DIRECT;
}
else {
ESprintf(EINVAL, "Convert(%s) to encoding type failed", from);
return(-1);
}
return(1);
}
check_win(win, src)
Subregion *win;
Raster *src;
{
if (win->x < 0 || win->x > src->nx - 1 ||
win->y < 0 || win->y > src->ny - 1 ||
(win->x + win->nx - 1) > src->nx - 1 ||
(win->y + win->ny - 1) > src->ny - 1) {
(void) fprintf(stderr,"Window out of range\n");
exit(1);
}
}
|
ffb0a5bc5d91786b1ebf86e78a5495c481146bb1
|
84cb88178fb1d6fcb72a6e38fd9b65e7d8693957
|
/src/gui/gui-search.c
|
2f158ce64a31f3337abab137b8091881e893be84
|
[
"MIT"
] |
permissive
|
alexandervdm/gummi
|
5bdf8dd57a0bae7312923760f3d5cd395ded95bb
|
0b204f0f50723dd8ff12dbee2b2129491178fab6
|
refs/heads/master
| 2023-07-26T00:18:12.829216
| 2022-04-29T09:41:24
| 2022-04-29T09:41:24
| 30,527,670
| 853
| 158
|
MIT
| 2023-07-12T19:39:16
| 2015-02-09T09:16:24
|
C
|
UTF-8
|
C
| false
| false
| 4,965
|
c
|
gui-search.c
|
/**
* @file gui-search.c
* @brief
*
* Copyright (C) 2009 Gummi Developers
* All Rights reserved.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "gui-search.h"
#include <glib.h>
#include <gtk/gtk.h>
#include "editor.h"
#include "environment.h"
#include "utils.h"
#include "gui/gui-main.h"
extern Gummi* gummi;
extern GummiGui* gui;
GuSearchGui* searchgui_init (GtkBuilder* builder) {
g_return_val_if_fail (GTK_IS_BUILDER (builder), NULL);
GuSearchGui* s = g_new0 (GuSearchGui, 1);
s->searchwindow =
GTK_WIDGET (gtk_builder_get_object (builder, "searchwindow"));
s->searchentry =
GTK_ENTRY (gtk_builder_get_object (builder, "searchentry"));
s->replaceentry =
GTK_ENTRY (gtk_builder_get_object (builder, "replaceentry"));
s->matchcase = FALSE;
s->backwards = FALSE;
s->wholeword = FALSE;
s->prev_search = NULL;
s->prev_replace = NULL;
g_signal_connect (s->searchentry, "changed",
G_CALLBACK (on_searchgui_text_changed), NULL);
return s;
}
void searchgui_main (GuSearchGui* gc) {
gtk_entry_set_text (gc->searchentry, gc->prev_search? gc->prev_search:"");
gtk_entry_set_text (gc->replaceentry, gc->prev_replace? gc->prev_replace:"");
gtk_widget_grab_focus (GTK_WIDGET (gc->searchentry));
gtk_widget_show_all (GTK_WIDGET (gc->searchwindow));
slog_set_gui_parent (GTK_WINDOW (gc->searchwindow));
}
G_MODULE_EXPORT
void on_toggle_matchcase_toggled (GtkWidget *widget, void* user) {
gui->searchgui->matchcase =
gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget));
g_active_editor->replace_activated = FALSE;
}
G_MODULE_EXPORT
void on_toggle_wholeword_toggled (GtkWidget *widget, void* user) {
gui->searchgui->wholeword =
gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget));
g_active_editor->replace_activated = FALSE;
}
G_MODULE_EXPORT
void on_toggle_backwards_toggled (GtkWidget *widget, void* user) {
gui->searchgui->backwards =
gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget));
g_active_editor->replace_activated = FALSE;
}
void on_searchgui_text_changed (GtkEditable *editable, void* user) {
g_active_editor->replace_activated = FALSE;
}
G_MODULE_EXPORT
gboolean on_button_searchwindow_close_clicked (GtkWidget* widget, void* user) {
g_free (gui->searchgui->prev_search);
g_free (gui->searchgui->prev_replace);
gui->searchgui->prev_search = g_strdup (gtk_entry_get_text (
gui->searchgui->searchentry));
gui->searchgui->prev_replace = g_strdup (gtk_entry_get_text (
gui->searchgui->replaceentry));
gtk_widget_hide (GTK_WIDGET (gui->searchgui->searchwindow));
slog_set_gui_parent (GTK_WINDOW (gui->mainwindow));
return TRUE;
}
G_MODULE_EXPORT
void on_button_searchwindow_find_clicked (GtkWidget* widget, void* user) {
editor_start_search (g_active_editor,
gtk_entry_get_text (gui->searchgui->searchentry),
gui->searchgui->backwards,
gui->searchgui->wholeword,
gui->searchgui->matchcase
);
}
G_MODULE_EXPORT
void on_button_searchwindow_replace_next_clicked (GtkWidget* widget, void* user) {
editor_start_replace_next (g_active_editor,
gtk_entry_get_text (gui->searchgui->searchentry),
gtk_entry_get_text (gui->searchgui->replaceentry),
gui->searchgui->backwards,
gui->searchgui->wholeword,
gui->searchgui->matchcase
);
}
G_MODULE_EXPORT
void on_button_searchwindow_replace_all_clicked (GtkWidget* widget, void* user) {
editor_start_replace_all (g_active_editor,
gtk_entry_get_text (gui->searchgui->searchentry),
gtk_entry_get_text (gui->searchgui->replaceentry),
gui->searchgui->backwards,
gui->searchgui->wholeword,
gui->searchgui->matchcase
);
}
|
034a0a2c4c30dd40e8b9d0b4bcbdf6ed772906ce
|
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
|
/PWGLF/SPECTRA/PiKaPr/TestAOD/HighLevelQA/NumberOfEventsMCvsDATA.C
|
adb575ce3f39dd2b02a2602b16b681650e64d211
|
[] |
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
| 5,797
|
c
|
NumberOfEventsMCvsDATA.C
|
/////////////////////////////////////////////////////////
// NumberOfEventsMCvsDATA.C //
// //
// plots the ratio (# of MC events)/(# of DATA events) //
// against the run number //
// //
// Written by John Groh //
/////////////////////////////////////////////////////////
// for cout
#include <iostream>
using namespace std;
// possible cuts to use - 0 1 2 3
Double_t CentCutMin[4] = {0, 30, 30, 30};
Double_t CentCutMax[4] = {5, 40, 40, 40};
Double_t QvecCutMin[4] = {0, 0, 0, 1.5};
Double_t QvecCutMax[4] = {100, 100, 0.4, 100};
Double_t EtaMin[4] = {-0.8,-0.8,-0.8,-0.8};
Double_t EtaMax[4] = {0.8, 0.8, 0.8, 0.8};
Double_t Nsigmapid = 3.;
UInt_t trkbit = 1024;
//--------------------
// Start of function -
//--------------------
// icut selects which cut to use (2 and 3 have too low statistics and cause divide-by-zero errors, so don't use)
// nSigmaCut is the size of the deviation with which to determine outliers
void NumberOfEventsMCvsDATA(Int_t icut = 1, const Float_t nSigmaCut = 3)
{
// load libraries (I'm not sure I need all of these...)
gSystem->Load("libCore");
gSystem->Load("libPhysics");
gSystem->Load("libTree");
gSystem->Load("libMatrix");
gSystem->Load("libSTEERBase");
gSystem->Load("libESD");
gSystem->Load("libAOD");
gSystem->Load("libANALYSIS");
gSystem->Load("libOADB");
gSystem->Load("libANALYSISalice");
gSystem->Load("libTender");
gSystem->Load("libCORRFW");
gSystem->Load("libPWGTools");
gSystem->Load("libPWGLFspectra");
gSystem->Load("libProof");
gSystem->AddIncludePath("-I$ALICE_ROOT/include");
// get number of runs used
Int_t nRunsTemp = 0;
Int_t dummy;
ifstream runList("output/AODQAChecks/RunList.txt");
while (!runList.eof())
{
runList >> dummy;
nRunsTemp++;
}
runList.close();
// I know this is silly, but you need a const for array sizes.
// Also, it seems to want to read one more line than there is in the file
const Int_t nRuns = nRunsTemp - 1;
// fill an array with the run numbers and another two with the file names
runList.open("output/AODQAChecks/RunList.txt");
Int_t runs[nRuns];
TString dataFilesDATA[nRuns];
TString dataFilesMC[nRuns];
for (Int_t irun=0; irun<nRuns; irun++)
{
runList >> runs[irun];
dataFilesDATA[irun] = Form("output/AODQAChecks/DATA/AnalysisResults%i.root",runs[irun]);
dataFilesMC[irun] = Form("output/AODQAChecks/MC/AnalysisResults%i.root",runs[irun]);
}
runList.close();
// choose which TDirectories in the .root files to use
TString snameDATA;
TString snameMC;
snameDATA = Form("OutputAODSpectraTask_Data_Cent%.0fto%.0f_QVec%.1fto%.1f_Eta%.1fto%.1f_%.1fSigmaPID_TrBit%d",CentCutMin[icut],CentCutMax[icut],QvecCutMin[icut],QvecCutMax[icut],EtaMin[icut],EtaMax[icut],Nsigmapid,trkbit);
snameMC = Form("OutputAODSpectraTask_MC_Cent%.0fto%.0f_QVec%.1fto%.1f_Eta%.1fto%.1f_%.1fSigmaPID_TrBit%d",CentCutMin[icut],CentCutMax[icut],QvecCutMin[icut],QvecCutMax[icut],EtaMin[icut],EtaMax[icut],Nsigmapid,trkbit);
TFile * fileDATA;
TDirectoryFile * DirDATA;
AliSpectraAODEventCuts * ecutsDATA;
TFile * fileMC;
TDirectoryFile * DirMC;
AliSpectraAODEventCuts * ecutsMC;
// histogram to be filled w/ the ratio (# of MC events)/(# of DATA events)
TH1F * hNEventsRatio = new TH1F("hNEventsRatio","",nRuns,0,nRuns);
// loop over all runs
for (Int_t irun=0; irun<nRuns; irun++)
{
Printf("\n--- Processing run %i ---",runs[irun]);
// open the file
fileDATA = TFile::Open(dataFilesDATA[irun].Data());
if (!fileDATA)
{
Printf("\n!!! ERROR: Could not open DATA file %s !!!\n",dataFiles[irun].Data());
continue;
}
fileMC = TFile::Open(dataFilesMC[irun].Data());
if (!fileMC)
{
Printf("\n!!! ERROR: Could not open MC file %s !!!\n",dataFiles[irun].Data());
continue;
}
// choose the right directory and event cut objects
DirDATA = (TDirectoryFile*)fileDATA->Get(Form("%s",snameDATA.Data()));
if (!DirDATA)
{
Printf("\n!!! ERROR: DirDATA is a null pointer. Skipping to next file !!!\n");
continue;
}
DirMC = (TDirectoryFile*)fileMC->Get(Form("%s",snameMC.Data()));
if (!DirMC)
{
Printf("\n!!! ERROR: DirMC is a null pointer. Skipping to next file !!!\n");
continue;
}
ecutsDATA = (AliSpectraAODEventCuts*)DirDATA->Get("Event Cuts");
if (!ecutsDATA)
{
Printf("\n!!! ERROR: ecutsDATA is a null pointer. Skipping to next file !!!\n");
continue;
}
ecutsMC = (AliSpectraAODEventCuts*)DirMC->Get("Event Cuts");
if (!ecutsMC)
{
Printf("\n!!! ERROR: ecutsMC is a null pointer. Skipping to next file !!!\n");
continue;
}
// calculate the ratio and fill the histogram
Int_t nEventsDATA = ecutsDATA->NumberOfEvents();
Int_t nEventsMC = ecutsMC->NumberOfEvents();
Float_t ratio = (Float_t)nEventsMC / (Float_t)nEventsDATA;
hNEventsRatio->SetBinContent(irun+1,ratio);
Printf("# of MC events: %i\n# of DATA events: %i\nRatio: %.2f",nEventsMC,nEventsDATA,ratio);
} // end loop over runs
// draw it
TCanvas * cNEventsRatio = new TCanvas("cNEventsRatio","cNEventsRatio");
for (Int_t irun=0; irun<nRuns; irun++)
hNEventsRatio->GetXaxis()->SetBinLabel(irun+1,Form("%i",runs[irun]));
hNEventsRatio->GetYaxis()->SetTitle("(# of MC events)/(# of DATA events)");
hNEventsRatio->GetYaxis()->SetTitleOffset(1.2);
hNEventsRatio->SetMarkerStyle(21);
hNEventsRatio->SetMarkerColor(kBlue);
hNEventsRatio->SetStats(kFALSE);
hNEventsRatio->DrawCopy("P");
}
|
28d6b99556a26ab4af5ed1e0869bf6eef9d9045d
|
450916eee7580beb928ed8f387db4f0a8c1aa508
|
/src/amuse/community/huayno/src/evolve_error_control.h
|
f1e990771258384ab05efccab49c5f7ff224a873
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
amusecode/amuse
|
42095545893f5a86ea79c2a52ce54d3ce8eb204f
|
b57c1e2fda1457d5025307be105c2aa59b19b574
|
refs/heads/main
| 2023-08-31T04:50:48.880044
| 2023-08-30T12:00:20
| 2023-08-30T12:00:20
| 18,516,331
| 158
| 118
|
Apache-2.0
| 2023-08-30T12:00:22
| 2014-04-07T12:35:07
|
AMPL
|
UTF-8
|
C
| false
| false
| 104
|
h
|
evolve_error_control.h
|
void evolve_error_control(int clevel,struct sys s, DOUBLE stime, DOUBLE etime, DOUBLE dt, FLOAT dtsys);
|
3e1352dd2f2c45f775d5d06e98a187b4de42b445
|
fbe68d84e97262d6d26dd65c704a7b50af2b3943
|
/third_party/virtualbox/include/VBox/vmm/apic.h
|
0e3c2df16ddb5c47aed2a2b3d684e242535574ca
|
[
"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
| 9,462
|
h
|
apic.h
|
/** @file
* APIC - Advanced Programmable Interrupt Controller.
*/
/*
* Copyright (C) 2006-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
#ifndef ___VBox_vmm_apic_h
#define ___VBox_vmm_apic_h
#include <VBox/vmm/pdmins.h>
#include <VBox/vmm/pdmdev.h>
/** @defgroup grp_apic The local APIC VMM API
* @ingroup grp_vmm
* @{
*/
/** Offset of APIC ID Register. */
#define XAPIC_OFF_ID 0x020
/** Offset of APIC Version Register. */
#define XAPIC_OFF_VERSION 0x030
/** Offset of Task Priority Register. */
#define XAPIC_OFF_TPR 0x080
/** Offset of Arbitrartion Priority register. */
#define XAPIC_OFF_APR 0x090
/** Offset of Processor Priority register. */
#define XAPIC_OFF_PPR 0x0A0
/** Offset of End Of Interrupt register. */
#define XAPIC_OFF_EOI 0x0B0
/** Offset of Remote Read Register. */
#define XAPIC_OFF_RRD 0x0C0
/** Offset of Logical Destination Register. */
#define XAPIC_OFF_LDR 0x0D0
/** Offset of Destination Format Register. */
#define XAPIC_OFF_DFR 0x0E0
/** Offset of Spurious Interrupt Vector Register. */
#define XAPIC_OFF_SVR 0x0F0
/** Offset of In-service Register (bits 31:0). */
#define XAPIC_OFF_ISR0 0x100
/** Offset of In-service Register (bits 63:32). */
#define XAPIC_OFF_ISR1 0x110
/** Offset of In-service Register (bits 95:64). */
#define XAPIC_OFF_ISR2 0x120
/** Offset of In-service Register (bits 127:96). */
#define XAPIC_OFF_ISR3 0x130
/** Offset of In-service Register (bits 159:128). */
#define XAPIC_OFF_ISR4 0x140
/** Offset of In-service Register (bits 191:160). */
#define XAPIC_OFF_ISR5 0x150
/** Offset of In-service Register (bits 223:192). */
#define XAPIC_OFF_ISR6 0x160
/** Offset of In-service Register (bits 255:224). */
#define XAPIC_OFF_ISR7 0x170
/** Offset of Trigger Mode Register (bits 31:0). */
#define XAPIC_OFF_TMR0 0x180
/** Offset of Trigger Mode Register (bits 63:32). */
#define XAPIC_OFF_TMR1 0x190
/** Offset of Trigger Mode Register (bits 95:64). */
#define XAPIC_OFF_TMR2 0x1A0
/** Offset of Trigger Mode Register (bits 127:96). */
#define XAPIC_OFF_TMR3 0x1B0
/** Offset of Trigger Mode Register (bits 159:128). */
#define XAPIC_OFF_TMR4 0x1C0
/** Offset of Trigger Mode Register (bits 191:160). */
#define XAPIC_OFF_TMR5 0x1D0
/** Offset of Trigger Mode Register (bits 223:192). */
#define XAPIC_OFF_TMR6 0x1E0
/** Offset of Trigger Mode Register (bits 255:224). */
#define XAPIC_OFF_TMR7 0x1F0
/** Offset of Interrupt Request Register (bits 31:0). */
#define XAPIC_OFF_IRR0 0x200
/** Offset of Interrupt Request Register (bits 63:32). */
#define XAPIC_OFF_IRR1 0x210
/** Offset of Interrupt Request Register (bits 95:64). */
#define XAPIC_OFF_IRR2 0x220
/** Offset of Interrupt Request Register (bits 127:96). */
#define XAPIC_OFF_IRR3 0x230
/** Offset of Interrupt Request Register (bits 159:128). */
#define XAPIC_OFF_IRR4 0x240
/** Offset of Interrupt Request Register (bits 191:160). */
#define XAPIC_OFF_IRR5 0x250
/** Offset of Interrupt Request Register (bits 223:192). */
#define XAPIC_OFF_IRR6 0x260
/** Offset of Interrupt Request Register (bits 255:224). */
#define XAPIC_OFF_IRR7 0x270
/** Offset of Error Status Register. */
#define XAPIC_OFF_ESR 0x280
/** Offset of LVT CMCI Register. */
#define XAPIC_OFF_LVT_CMCI 0x2F0
/** Offset of Interrupt Command Register - Lo. */
#define XAPIC_OFF_ICR_LO 0x300
/** Offset of Interrupt Command Register - Hi. */
#define XAPIC_OFF_ICR_HI 0x310
/** Offset of LVT Timer Register. */
#define XAPIC_OFF_LVT_TIMER 0x320
/** Offset of LVT Thermal Sensor Register. */
#define XAPIC_OFF_LVT_THERMAL 0x330
/** Offset of LVT Performance Counter Register. */
#define XAPIC_OFF_LVT_PERF 0x340
/** Offset of LVT LINT0 Register. */
#define XAPIC_OFF_LVT_LINT0 0x350
/** Offset of LVT LINT1 Register. */
#define XAPIC_OFF_LVT_LINT1 0x360
/** Offset of LVT Error Register . */
#define XAPIC_OFF_LVT_ERROR 0x370
/** Offset of Timer Initial Count Register. */
#define XAPIC_OFF_TIMER_ICR 0x380
/** Offset of Timer Current Count Register. */
#define XAPIC_OFF_TIMER_CCR 0x390
/** Offset of Timer Divide Configuration Register. */
#define XAPIC_OFF_TIMER_DCR 0x3E0
/** Offset of Self-IPI Register (x2APIC only). */
#define X2APIC_OFF_SELF_IPI 0x3F0
/** Offset of LVT range start. */
#define XAPIC_OFF_LVT_START XAPIC_OFF_LVT_TIMER
/** Offset of LVT range end (inclusive). */
#define XAPIC_OFF_LVT_END XAPIC_OFF_LVT_ERROR
/** Offset of LVT extended range start. */
#define XAPIC_OFF_LVT_EXT_START XAPIC_OFF_LVT_CMCI
/** Offset of LVT extended range end (inclusive). */
#define XAPIC_OFF_LVT_EXT_END XAPIC_OFF_LVT_CMCI
/**
* xAPIC trigger mode.
*/
typedef enum XAPICTRIGGERMODE
{
XAPICTRIGGERMODE_EDGE = 0,
XAPICTRIGGERMODE_LEVEL
} XAPICTRIGGERMODE;
RT_C_DECLS_BEGIN
#ifdef IN_RING3
/** @defgroup grp_apic_r3 The APIC Host Context Ring-3 API
* @{
*/
VMMR3_INT_DECL(void) APICR3InitIpi(PVMCPU pVCpu);
VMMR3_INT_DECL(void) APICR3HvEnable(PVM pVM);
/** @} */
#endif /* IN_RING3 */
/* These functions are exported as they are called from external modules (recompiler). */
VMMDECL(void) APICUpdatePendingInterrupts(PVMCPU pVCpu);
VMMDECL(int) APICGetTpr(PVMCPU pVCpu, uint8_t *pu8Tpr, bool *pfPending, uint8_t *pu8PendingIntr);
VMMDECL(int) APICSetTpr(PVMCPU pVCpu, uint8_t u8Tpr);
/* These functions are VMM internal. */
VMM_INT_DECL(bool) APICIsEnabled(PVMCPU pVCpu);
VMM_INT_DECL(bool) APICGetHighestPendingInterrupt(PVMCPU pVCpu, uint8_t *pu8PendingIntr);
VMM_INT_DECL(bool) APICQueueInterruptToService(PVMCPU pVCpu, uint8_t u8PendingIntr);
VMM_INT_DECL(void) APICDequeueInterruptFromService(PVMCPU pVCpu, uint8_t u8PendingIntr);
VMM_INT_DECL(VBOXSTRICTRC) APICReadMsr(PVMCPU pVCpu, uint32_t u32Reg, uint64_t *pu64Value);
VMM_INT_DECL(VBOXSTRICTRC) APICWriteMsr(PVMCPU pVCpu, uint32_t u32Reg, uint64_t u64Value);
VMM_INT_DECL(int) APICGetTimerFreq(PVM pVM, uint64_t *pu64Value);
VMM_INT_DECL(VBOXSTRICTRC) APICLocalInterrupt(PVMCPU pVCpu, uint8_t u8Pin, uint8_t u8Level, int rcRZ);
VMM_INT_DECL(uint64_t) APICGetBaseMsrNoCheck(PVMCPU pVCpu);
VMM_INT_DECL(VBOXSTRICTRC) APICGetBaseMsr(PVMCPU pVCpu, uint64_t *pu64Value);
VMM_INT_DECL(VBOXSTRICTRC) APICSetBaseMsr(PVMCPU pVCpu, uint64_t u64BaseMsr);
VMM_INT_DECL(int) APICGetInterrupt(PVMCPU pVCpu, uint8_t *pu8Vector, uint32_t *pu32TagSrc);
VMM_INT_DECL(int) APICBusDeliver(PVM pVM, uint8_t uDest, uint8_t uDestMode, uint8_t uDeliveryMode, uint8_t uVector,
uint8_t uPolarity, uint8_t uTriggerMode, uint32_t uTagSrc);
VMM_INT_DECL(int) APICGetApicPageForCpu(PVMCPU pVCpu, PRTHCPHYS pHCPhys, PRTR0PTR pR0Ptr, PRTR3PTR pR3Ptr,
PRTRCPTR pRCPtr);
/** @name Hyper-V interface (Ring-3 and all-context API).
* @{ */
#ifdef IN_RING3
VMMR3_INT_DECL(void) APICR3HvSetCompatMode(PVM pVM, bool fHyperVCompatMode);
#endif
VMM_INT_DECL(void) APICHvSendInterrupt(PVMCPU pVCpu, uint8_t uVector, bool fAutoEoi, XAPICTRIGGERMODE enmTriggerMode);
VMM_INT_DECL(VBOXSTRICTRC) APICHvSetTpr(PVMCPU pVCpu, uint8_t uTpr);
VMM_INT_DECL(uint8_t) APICHvGetTpr(PVMCPU pVCpu);
VMM_INT_DECL(VBOXSTRICTRC) APICHvSetIcr(PVMCPU pVCpu, uint64_t uIcr);
VMM_INT_DECL(uint64_t) APICHvGetIcr(PVMCPU pVCpu);
VMM_INT_DECL(VBOXSTRICTRC) APICHvSetEoi(PVMCPU pVCpu, uint32_t uEoi);
/** @} */
RT_C_DECLS_END
extern const PDMDEVREG g_DeviceAPIC;
/** @} */
#endif
|
434b740e8533c41197cd1734bcc2ccaa0a6dd7d3
|
7f6c235b0598353549959c18f69eefd20b766907
|
/libsrc/lib3d/mult_v.c
|
b6359d70078ab184f2c37f325d6d2e58a74a61a7
|
[
"ClArtistic"
] |
permissive
|
z88dk/z88dk
|
46dfd4905f36d99333173cadd0a660839befc9f0
|
8b07f37cc43c5d9ffe69b563c80763491d8faff7
|
refs/heads/master
| 2023-09-04T19:29:49.254958
| 2023-09-03T20:51:24
| 2023-09-03T20:51:24
| 54,035,569
| 820
| 263
|
NOASSERTION
| 2023-09-05T11:09:04
| 2016-03-16T13:48:16
|
Assembly
|
UTF-8
|
C
| false
| false
| 2,714
|
c
|
mult_v.c
|
/*
* mult_v.c
*
* Copyright (c) 2022 Phillip Stevens
* Create Time: October 2022
*
* The MIT License (MIT)
*
* Permission is hereby granted,free of charge,to any person obtaining a copy
* of this software and associated documentation files (the "Software"),to deal
* in the Software without restriction,including without limitation the rights
* to use,copy,modify,merge,publish,distribute,sublicense,and/or sell
* copies of the Software,and to permit persons to whom the Software is
* furnished to do so,subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS",WITHOUT WARRANTY OF ANY KIND,EXPRESS OR
* IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,DAMAGES OR OTHER
* LIABILITY,WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE,ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* 3D homogeneous coordinate definition
* https://en.wikipedia.org/wiki/Homogeneous_coordinates
*
* project 3D coords onto 2D screen:
* https://stackoverflow.com/questions/724219/how-to-convert-a-3d-point-into-2d-perspective-projection
*
* transformation matrix:
* https://www.tutorialspoint.com/computer_graphics/3d_transformation.htm
*
*/
/****************************************************************************/
/*** Include files ***/
/****************************************************************************/
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#include <lib3d.h>
/****************************************************************************/
/*** Function ***/
/****************************************************************************/
/* Vector Matrix Multiplication */
void mult_v(vector_t * vect, matrix_t * multiplier)
{
vector_t result;
result.x = vect->x*multiplier->e[0] + vect->y*multiplier->e[4] + vect->z*multiplier->e[8 ] + vect->w*multiplier->e[12];
result.y = vect->x*multiplier->e[1] + vect->y*multiplier->e[5] + vect->z*multiplier->e[9 ] + vect->w*multiplier->e[13];
result.z = vect->x*multiplier->e[2] + vect->y*multiplier->e[6] + vect->z*multiplier->e[10] + vect->w*multiplier->e[14];
result.w = vect->x*multiplier->e[3] + vect->y*multiplier->e[7] + vect->z*multiplier->e[11] + vect->w*multiplier->e[15];
*vect = result;
}
|
628f1ff21e300e883aab9df8c686a1e38b9cee5a
|
64a809e70c72c410d1c70621d21ce132235f3721
|
/m68kdasm.c
|
68d025a5073929325c67d036632d3671324ab2a0
|
[
"MIT"
] |
permissive
|
captain-amygdala/pistorm
|
f9b30d3c166f16753fcac375471e2601c5c70c26
|
da7408dbc6f38b7ec0d149fa2230080bb1828239
|
refs/heads/main
| 2023-09-02T09:36:52.396507
| 2023-07-08T22:58:32
| 2023-07-08T22:58:32
| 308,836,369
| 657
| 101
|
MIT
| 2022-09-24T04:45:43
| 2020-10-31T08:21:45
|
C
|
UTF-8
|
C
| false
| false
| 111,008
|
c
|
m68kdasm.c
|
/* ======================================================================== */
/* ========================= LICENSING & COPYRIGHT ======================== */
/* ======================================================================== */
/*
* MUSASHI
* Version 3.32
*
* A portable Motorola M680x0 processor emulation engine.
* Copyright Karl Stenerud. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/* ======================================================================== */
/* ================================ INCLUDES ============================== */
/* ======================================================================== */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "m68k.h"
#ifndef uint32
#define uint32 uint
#endif
#ifndef uint16
#define uint16 unsigned short
#endif
#ifndef DECL_SPEC
#define DECL_SPEC
#endif
/* ======================================================================== */
/* ============================ GENERAL DEFINES =========================== */
/* ======================================================================== */
/* unsigned int and int must be at least 32 bits wide */
#undef uint
#define uint unsigned int
/* Bit Isolation Functions */
#define BIT_0(A) ((A) & 0x00000001)
#define BIT_1(A) ((A) & 0x00000002)
#define BIT_2(A) ((A) & 0x00000004)
#define BIT_3(A) ((A) & 0x00000008)
#define BIT_4(A) ((A) & 0x00000010)
#define BIT_5(A) ((A) & 0x00000020)
#define BIT_6(A) ((A) & 0x00000040)
#define BIT_7(A) ((A) & 0x00000080)
#define BIT_8(A) ((A) & 0x00000100)
#define BIT_9(A) ((A) & 0x00000200)
#define BIT_A(A) ((A) & 0x00000400)
#define BIT_B(A) ((A) & 0x00000800)
#define BIT_C(A) ((A) & 0x00001000)
#define BIT_D(A) ((A) & 0x00002000)
#define BIT_E(A) ((A) & 0x00004000)
#define BIT_F(A) ((A) & 0x00008000)
#define BIT_10(A) ((A) & 0x00010000)
#define BIT_11(A) ((A) & 0x00020000)
#define BIT_12(A) ((A) & 0x00040000)
#define BIT_13(A) ((A) & 0x00080000)
#define BIT_14(A) ((A) & 0x00100000)
#define BIT_15(A) ((A) & 0x00200000)
#define BIT_16(A) ((A) & 0x00400000)
#define BIT_17(A) ((A) & 0x00800000)
#define BIT_18(A) ((A) & 0x01000000)
#define BIT_19(A) ((A) & 0x02000000)
#define BIT_1A(A) ((A) & 0x04000000)
#define BIT_1B(A) ((A) & 0x08000000)
#define BIT_1C(A) ((A) & 0x10000000)
#define BIT_1D(A) ((A) & 0x20000000)
#define BIT_1E(A) ((A) & 0x40000000)
#define BIT_1F(A) ((A) & 0x80000000)
/* These are the CPU types understood by this disassembler */
#define TYPE_68000 1
#define TYPE_68010 2
#define TYPE_68020 4
#define TYPE_68030 8
#define TYPE_68040 16
#define M68000_ONLY TYPE_68000
#define M68010_ONLY TYPE_68010
#define M68010_LESS (TYPE_68000 | TYPE_68010)
#define M68010_PLUS (TYPE_68010 | TYPE_68020 | TYPE_68030 | TYPE_68040)
#define M68020_ONLY TYPE_68020
#define M68020_LESS (TYPE_68010 | TYPE_68020)
#define M68020_PLUS (TYPE_68020 | TYPE_68030 | TYPE_68040)
#define M68030_ONLY TYPE_68030
#define M68030_LESS (TYPE_68010 | TYPE_68020 | TYPE_68030)
#define M68030_PLUS (TYPE_68030 | TYPE_68040)
#define M68040_PLUS TYPE_68040
/* Extension word formats */
#define EXT_8BIT_DISPLACEMENT(A) ((A)&0xff)
#define EXT_FULL(A) BIT_8(A)
#define EXT_EFFECTIVE_ZERO(A) (((A)&0xe4) == 0xc4 || ((A)&0xe2) == 0xc0)
#define EXT_BASE_REGISTER_PRESENT(A) (!BIT_7(A))
#define EXT_INDEX_REGISTER_PRESENT(A) (!BIT_6(A))
#define EXT_INDEX_REGISTER(A) (((A)>>12)&7)
#define EXT_INDEX_PRE_POST(A) (EXT_INDEX_PRESENT(A) && (A)&3)
#define EXT_INDEX_PRE(A) (EXT_INDEX_PRESENT(A) && ((A)&7) < 4 && ((A)&7) != 0)
#define EXT_INDEX_POST(A) (EXT_INDEX_PRESENT(A) && ((A)&7) > 4)
#define EXT_INDEX_SCALE(A) (((A)>>9)&3)
#define EXT_INDEX_LONG(A) BIT_B(A)
#define EXT_INDEX_AR(A) BIT_F(A)
#define EXT_BASE_DISPLACEMENT_PRESENT(A) (((A)&0x30) > 0x10)
#define EXT_BASE_DISPLACEMENT_WORD(A) (((A)&0x30) == 0x20)
#define EXT_BASE_DISPLACEMENT_LONG(A) (((A)&0x30) == 0x30)
#define EXT_OUTER_DISPLACEMENT_PRESENT(A) (((A)&3) > 1 && ((A)&0x47) < 0x44)
#define EXT_OUTER_DISPLACEMENT_WORD(A) (((A)&3) == 2 && ((A)&0x47) < 0x44)
#define EXT_OUTER_DISPLACEMENT_LONG(A) (((A)&3) == 3 && ((A)&0x47) < 0x44)
/* Opcode flags */
#if M68K_COMPILE_FOR_MAME == OPT_ON
#define SET_OPCODE_FLAGS(x) g_opcode_type = x;
#define COMBINE_OPCODE_FLAGS(x) ((x) | g_opcode_type | DASMFLAG_SUPPORTED)
#else
#define SET_OPCODE_FLAGS(x)
#define COMBINE_OPCODE_FLAGS(X) (X)
#endif
/* ======================================================================== */
/* =============================== PROTOTYPES ============================= */
/* ======================================================================== */
/* Read data at the PC and increment PC */
uint read_imm_8(void);
uint read_imm_16(void);
uint read_imm_32(void);
/* Read data at the PC but don't imcrement the PC */
uint peek_imm_8(void);
uint peek_imm_16(void);
uint peek_imm_32(void);
/* make signed integers 100% portably */
static int make_int_8(int value);
static int make_int_16(int value);
static int make_int_32(int value);
/* make a string of a hex value */
static char* make_signed_hex_str_8(uint val);
static char* make_signed_hex_str_16(uint val);
static char* make_signed_hex_str_32(uint val);
/* make string of ea mode */
static char* get_ea_mode_str(uint instruction, uint size);
char* get_ea_mode_str_8(uint instruction);
char* get_ea_mode_str_16(uint instruction);
char* get_ea_mode_str_32(uint instruction);
/* make string of immediate value */
static char* get_imm_str_s(uint size);
static char* get_imm_str_u(uint size);
char* get_imm_str_s8(void);
char* get_imm_str_s16(void);
char* get_imm_str_s32(void);
/* Stuff to build the opcode handler jump table */
static void build_opcode_table(void);
static int valid_ea(uint opcode, uint mask);
static int DECL_SPEC compare_nof_true_bits(const void *aptr, const void *bptr);
/* used to build opcode handler jump table */
typedef struct
{
void (*opcode_handler)(void); /* handler function */
uint mask; /* mask on opcode */
uint match; /* what to match after masking */
uint ea_mask; /* what ea modes are allowed */
} opcode_struct;
/* ======================================================================== */
/* ================================= DATA ================================= */
/* ======================================================================== */
/* Opcode handler jump table */
static void (*g_instruction_table[0x10000])(void);
/* Flag if disassembler initialized */
static int g_initialized = 0;
/* Address mask to simulate address lines */
static unsigned int g_address_mask = 0xffffffff;
static char g_dasm_str[100]; /* string to hold disassembly */
static char g_helper_str[100]; /* string to hold helpful info */
static uint g_cpu_pc; /* program counter */
static uint g_cpu_ir; /* instruction register */
static uint g_cpu_type;
static uint g_opcode_type;
static const unsigned char* g_rawop;
static uint g_rawbasepc;
/* used by ops like asr, ror, addq, etc */
static const uint g_3bit_qdata_table[8] = {8, 1, 2, 3, 4, 5, 6, 7};
static const uint g_5bit_data_table[32] =
{
32, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
};
static const char *const g_cc[16] =
{"t", "f", "hi", "ls", "cc", "cs", "ne", "eq", "vc", "vs", "pl", "mi", "ge", "lt", "gt", "le"};
static const char *const g_cpcc[64] =
{/* 000 001 010 011 100 101 110 111 */
"f", "eq", "ogt", "oge", "olt", "ole", "ogl", "or", /* 000 */
"un", "ueq", "ugt", "uge", "ult", "ule", "ne", "t", /* 001 */
"sf", "seq", "gt", "ge", "lt", "le", "gl" "gle", /* 010 */
"ngle", "ngl", "nle", "nlt", "nge", "ngt", "sne", "st", /* 011 */
"?", "?", "?", "?", "?", "?", "?", "?", /* 100 */
"?", "?", "?", "?", "?", "?", "?", "?", /* 101 */
"?", "?", "?", "?", "?", "?", "?", "?", /* 110 */
"?", "?", "?", "?", "?", "?", "?", "?" /* 111 */
};
static const char *const g_mmuregs[8] =
{
"tc", "drp", "srp", "crp", "cal", "val", "sccr", "acr"
};
static const char *const g_mmucond[16] =
{
"bs", "bc", "ls", "lc", "ss", "sc", "as", "ac",
"ws", "wc", "is", "ic", "gs", "gc", "cs", "cc"
};
/* ======================================================================== */
/* =========================== UTILITY FUNCTIONS ========================== */
/* ======================================================================== */
#define LIMIT_CPU_TYPES(ALLOWED_CPU_TYPES) \
if(!(g_cpu_type & ALLOWED_CPU_TYPES)) \
{ \
if((g_cpu_ir & 0xf000) == 0xf000) \
d68000_1111(); \
else d68000_illegal(); \
return; \
}
static uint dasm_read_imm_8(uint advance)
{
uint result;
if (g_rawop)
result = g_rawop[g_cpu_pc + 1 - g_rawbasepc];
else
result = m68k_read_disassembler_16(g_cpu_pc & g_address_mask) & 0xff;
g_cpu_pc += advance;
return result;
}
static uint dasm_read_imm_16(uint advance)
{
uint result;
if (g_rawop)
result = (g_rawop[g_cpu_pc + 0 - g_rawbasepc] << 8) |
g_rawop[g_cpu_pc + 1 - g_rawbasepc];
else
result = m68k_read_disassembler_16(g_cpu_pc & g_address_mask) & 0xffff;
g_cpu_pc += advance;
return result;
}
static uint dasm_read_imm_32(uint advance)
{
uint result;
if (g_rawop)
result = (g_rawop[g_cpu_pc + 0 - g_rawbasepc] << 24) |
(g_rawop[g_cpu_pc + 1 - g_rawbasepc] << 16) |
(g_rawop[g_cpu_pc + 2 - g_rawbasepc] << 8) |
g_rawop[g_cpu_pc + 3 - g_rawbasepc];
else
result = m68k_read_disassembler_32(g_cpu_pc & g_address_mask) & 0xffffffff;
g_cpu_pc += advance;
return result;
}
#define read_imm_8() dasm_read_imm_8(2)
#define read_imm_16() dasm_read_imm_16(2)
#define read_imm_32() dasm_read_imm_32(4)
#define peek_imm_8() dasm_read_imm_8(0)
#define peek_imm_16() dasm_read_imm_16(0)
#define peek_imm_32() dasm_read_imm_32(0)
/* Fake a split interface */
#define get_ea_mode_str_8(instruction) get_ea_mode_str(instruction, 0)
#define get_ea_mode_str_16(instruction) get_ea_mode_str(instruction, 1)
#define get_ea_mode_str_32(instruction) get_ea_mode_str(instruction, 2)
#define get_imm_str_s8() get_imm_str_s(0)
#define get_imm_str_s16() get_imm_str_s(1)
#define get_imm_str_s32() get_imm_str_s(2)
#define get_imm_str_u8() get_imm_str_u(0)
#define get_imm_str_u16() get_imm_str_u(1)
#define get_imm_str_u32() get_imm_str_u(2)
static int sext_7bit_int(int value)
{
return (value & 0x40) ? (value | 0xffffff80) : (value & 0x7f);
}
/* 100% portable signed int generators */
static int make_int_8(int value)
{
return (value & 0x80) ? value | ~0xff : value & 0xff;
}
static int make_int_16(int value)
{
return (value & 0x8000) ? value | ~0xffff : value & 0xffff;
}
static int make_int_32(int value)
{
return (value & 0x80000000) ? value | ~0xffffffff : value & 0xffffffff;
}
/* Get string representation of hex values */
static char* make_signed_hex_str_8(uint val)
{
static char str[20];
val &= 0xff;
if(val == 0x80)
sprintf(str, "-$80");
else if(val & 0x80)
sprintf(str, "-$%x", (0-val) & 0x7f);
else
sprintf(str, "$%x", val & 0x7f);
return str;
}
static char* make_signed_hex_str_16(uint val)
{
static char str[20];
val &= 0xffff;
if(val == 0x8000)
sprintf(str, "-$8000");
else if(val & 0x8000)
sprintf(str, "-$%x", (0-val) & 0x7fff);
else
sprintf(str, "$%x", val & 0x7fff);
return str;
}
static char* make_signed_hex_str_32(uint val)
{
static char str[20];
val &= 0xffffffff;
if(val == 0x80000000)
sprintf(str, "-$80000000");
else if(val & 0x80000000)
sprintf(str, "-$%x", (0-val) & 0x7fffffff);
else
sprintf(str, "$%x", val & 0x7fffffff);
return str;
}
/* make string of immediate value */
static char* get_imm_str_s(uint size)
{
static char str[25];
if(size == 0)
sprintf(str, "#%s", make_signed_hex_str_8(read_imm_8()));
else if(size == 1)
sprintf(str, "#%s", make_signed_hex_str_16(read_imm_16()));
else
sprintf(str, "#%s", make_signed_hex_str_32(read_imm_32()));
return str;
}
static char* get_imm_str_u(uint size)
{
static char str[25];
if(size == 0)
sprintf(str, "#$%x", read_imm_8() & 0xff);
else if(size == 1)
sprintf(str, "#$%x", read_imm_16() & 0xffff);
else
sprintf(str, "#$%x", read_imm_32() & 0xffffffff);
return str;
}
/* Make string of effective address mode */
static char* get_ea_mode_str(uint instruction, uint size)
{
static char b1[64];
static char b2[64];
static char* mode = b2;
uint extension;
uint base;
uint outer;
char base_reg[4];
char index_reg[8];
uint preindex;
uint postindex;
uint comma = 0;
uint temp_value;
/* Switch buffers so we don't clobber on a double-call to this function */
mode = mode == b1 ? b2 : b1;
switch(instruction & 0x3f)
{
case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07:
/* data register direct */
sprintf(mode, "D%d", instruction&7);
break;
case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f:
/* address register direct */
sprintf(mode, "A%d", instruction&7);
break;
case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17:
/* address register indirect */
sprintf(mode, "(A%d)", instruction&7);
break;
case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f:
/* address register indirect with postincrement */
sprintf(mode, "(A%d)+", instruction&7);
break;
case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27:
/* address register indirect with predecrement */
sprintf(mode, "-(A%d)", instruction&7);
break;
case 0x28: case 0x29: case 0x2a: case 0x2b: case 0x2c: case 0x2d: case 0x2e: case 0x2f:
/* address register indirect with displacement*/
sprintf(mode, "(%s,A%d)", make_signed_hex_str_16(read_imm_16()), instruction&7);
break;
case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37:
/* address register indirect with index */
extension = read_imm_16();
if(EXT_FULL(extension))
{
if(EXT_EFFECTIVE_ZERO(extension))
{
strcpy(mode, "0");
break;
}
base = EXT_BASE_DISPLACEMENT_PRESENT(extension) ? (EXT_BASE_DISPLACEMENT_LONG(extension) ? read_imm_32() : read_imm_16()) : 0;
outer = EXT_OUTER_DISPLACEMENT_PRESENT(extension) ? (EXT_OUTER_DISPLACEMENT_LONG(extension) ? read_imm_32() : read_imm_16()) : 0;
if(EXT_BASE_REGISTER_PRESENT(extension))
sprintf(base_reg, "A%d", instruction&7);
else
*base_reg = 0;
if(EXT_INDEX_REGISTER_PRESENT(extension))
{
sprintf(index_reg, "%c%d.%c", EXT_INDEX_AR(extension) ? 'A' : 'D', EXT_INDEX_REGISTER(extension), EXT_INDEX_LONG(extension) ? 'l' : 'w');
if(EXT_INDEX_SCALE(extension))
sprintf(index_reg+strlen(index_reg), "*%d", 1 << EXT_INDEX_SCALE(extension));
}
else
*index_reg = 0;
preindex = (extension&7) > 0 && (extension&7) < 4;
postindex = (extension&7) > 4;
strcpy(mode, "(");
if(preindex || postindex)
strcat(mode, "[");
if(base)
{
if (EXT_BASE_DISPLACEMENT_LONG(extension))
{
strcat(mode, make_signed_hex_str_32(base));
}
else
{
strcat(mode, make_signed_hex_str_16(base));
}
comma = 1;
}
if(*base_reg)
{
if(comma)
strcat(mode, ",");
strcat(mode, base_reg);
comma = 1;
}
if(postindex)
{
strcat(mode, "]");
comma = 1;
}
if(*index_reg)
{
if(comma)
strcat(mode, ",");
strcat(mode, index_reg);
comma = 1;
}
if(preindex)
{
strcat(mode, "]");
comma = 1;
}
if(outer)
{
if(comma)
strcat(mode, ",");
strcat(mode, make_signed_hex_str_16(outer));
}
strcat(mode, ")");
break;
}
if(EXT_8BIT_DISPLACEMENT(extension) == 0)
sprintf(mode, "(A%d,%c%d.%c", instruction&7, EXT_INDEX_AR(extension) ? 'A' : 'D', EXT_INDEX_REGISTER(extension), EXT_INDEX_LONG(extension) ? 'l' : 'w');
else
sprintf(mode, "(%s,A%d,%c%d.%c", make_signed_hex_str_8(extension), instruction&7, EXT_INDEX_AR(extension) ? 'A' : 'D', EXT_INDEX_REGISTER(extension), EXT_INDEX_LONG(extension) ? 'l' : 'w');
if(EXT_INDEX_SCALE(extension))
sprintf(mode+strlen(mode), "*%d", 1 << EXT_INDEX_SCALE(extension));
strcat(mode, ")");
break;
case 0x38:
/* absolute short address */
sprintf(mode, "$%x.w", read_imm_16());
break;
case 0x39:
/* absolute long address */
sprintf(mode, "$%x.l", read_imm_32());
break;
case 0x3a:
/* program counter with displacement */
temp_value = read_imm_16();
sprintf(mode, "(%s,PC)", make_signed_hex_str_16(temp_value));
sprintf(g_helper_str, "; ($%x)", (make_int_16(temp_value) + g_cpu_pc-2) & 0xffffffff);
break;
case 0x3b:
/* program counter with index */
extension = read_imm_16();
if(EXT_FULL(extension))
{
if(EXT_EFFECTIVE_ZERO(extension))
{
strcpy(mode, "0");
break;
}
base = EXT_BASE_DISPLACEMENT_PRESENT(extension) ? (EXT_BASE_DISPLACEMENT_LONG(extension) ? read_imm_32() : read_imm_16()) : 0;
outer = EXT_OUTER_DISPLACEMENT_PRESENT(extension) ? (EXT_OUTER_DISPLACEMENT_LONG(extension) ? read_imm_32() : read_imm_16()) : 0;
if(EXT_BASE_REGISTER_PRESENT(extension))
strcpy(base_reg, "PC");
else
*base_reg = 0;
if(EXT_INDEX_REGISTER_PRESENT(extension))
{
sprintf(index_reg, "%c%d.%c", EXT_INDEX_AR(extension) ? 'A' : 'D', EXT_INDEX_REGISTER(extension), EXT_INDEX_LONG(extension) ? 'l' : 'w');
if(EXT_INDEX_SCALE(extension))
sprintf(index_reg+strlen(index_reg), "*%d", 1 << EXT_INDEX_SCALE(extension));
}
else
*index_reg = 0;
preindex = (extension&7) > 0 && (extension&7) < 4;
postindex = (extension&7) > 4;
strcpy(mode, "(");
if(preindex || postindex)
strcat(mode, "[");
if(base)
{
strcat(mode, make_signed_hex_str_16(base));
comma = 1;
}
if(*base_reg)
{
if(comma)
strcat(mode, ",");
strcat(mode, base_reg);
comma = 1;
}
if(postindex)
{
strcat(mode, "]");
comma = 1;
}
if(*index_reg)
{
if(comma)
strcat(mode, ",");
strcat(mode, index_reg);
comma = 1;
}
if(preindex)
{
strcat(mode, "]");
comma = 1;
}
if(outer)
{
if(comma)
strcat(mode, ",");
strcat(mode, make_signed_hex_str_16(outer));
}
strcat(mode, ")");
break;
}
if(EXT_8BIT_DISPLACEMENT(extension) == 0)
sprintf(mode, "(PC,%c%d.%c", EXT_INDEX_AR(extension) ? 'A' : 'D', EXT_INDEX_REGISTER(extension), EXT_INDEX_LONG(extension) ? 'l' : 'w');
else
sprintf(mode, "(%s,PC,%c%d.%c", make_signed_hex_str_8(extension), EXT_INDEX_AR(extension) ? 'A' : 'D', EXT_INDEX_REGISTER(extension), EXT_INDEX_LONG(extension) ? 'l' : 'w');
if(EXT_INDEX_SCALE(extension))
sprintf(mode+strlen(mode), "*%d", 1 << EXT_INDEX_SCALE(extension));
strcat(mode, ")");
break;
case 0x3c:
/* Immediate */
sprintf(mode, "%s", get_imm_str_u(size));
break;
default:
sprintf(mode, "INVALID %x", instruction & 0x3f);
}
return mode;
}
/* ======================================================================== */
/* ========================= INSTRUCTION HANDLERS ========================= */
/* ======================================================================== */
/* Instruction handler function names follow this convention:
*
* d68000_NAME_EXTENSIONS(void)
* where NAME is the name of the opcode it handles and EXTENSIONS are any
* extensions for special instances of that opcode.
*
* Examples:
* d68000_add_er_8(): add opcode, from effective address to register,
* size = byte
*
* d68000_asr_s_8(): arithmetic shift right, static count, size = byte
*
*
* Common extensions:
* 8 : size = byte
* 16 : size = word
* 32 : size = long
* rr : register to register
* mm : memory to memory
* r : register
* s : static
* er : effective address -> register
* re : register -> effective address
* ea : using effective address mode of operation
* d : data register direct
* a : address register direct
* ai : address register indirect
* pi : address register indirect with postincrement
* pd : address register indirect with predecrement
* di : address register indirect with displacement
* ix : address register indirect with index
* aw : absolute word
* al : absolute long
*/
static void d68000_illegal(void)
{
sprintf(g_dasm_str, "dc.w $%04x; ILLEGAL", g_cpu_ir);
}
static void d68000_1010(void)
{
sprintf(g_dasm_str, "dc.w $%04x; opcode 1010", g_cpu_ir);
}
static void d68000_1111(void)
{
sprintf(g_dasm_str, "dc.w $%04x; opcode 1111", g_cpu_ir);
}
static void d68000_abcd_rr(void)
{
sprintf(g_dasm_str, "abcd D%d, D%d", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_abcd_mm(void)
{
sprintf(g_dasm_str, "abcd -(A%d), -(A%d)", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_add_er_8(void)
{
sprintf(g_dasm_str, "add.b %s, D%d", get_ea_mode_str_8(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_add_er_16(void)
{
sprintf(g_dasm_str, "add.w %s, D%d", get_ea_mode_str_16(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_add_er_32(void)
{
sprintf(g_dasm_str, "add.l %s, D%d", get_ea_mode_str_32(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_add_re_8(void)
{
sprintf(g_dasm_str, "add.b D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_add_re_16(void)
{
sprintf(g_dasm_str, "add.w D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_add_re_32(void)
{
sprintf(g_dasm_str, "add.l D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_adda_16(void)
{
sprintf(g_dasm_str, "adda.w %s, A%d", get_ea_mode_str_16(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_adda_32(void)
{
sprintf(g_dasm_str, "adda.l %s, A%d", get_ea_mode_str_32(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_addi_8(void)
{
char* str = get_imm_str_s8();
sprintf(g_dasm_str, "addi.b %s, %s", str, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_addi_16(void)
{
char* str = get_imm_str_s16();
sprintf(g_dasm_str, "addi.w %s, %s", str, get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_addi_32(void)
{
char* str = get_imm_str_s32();
sprintf(g_dasm_str, "addi.l %s, %s", str, get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_addq_8(void)
{
sprintf(g_dasm_str, "addq.b #%d, %s", g_3bit_qdata_table[(g_cpu_ir>>9)&7], get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_addq_16(void)
{
sprintf(g_dasm_str, "addq.w #%d, %s", g_3bit_qdata_table[(g_cpu_ir>>9)&7], get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_addq_32(void)
{
sprintf(g_dasm_str, "addq.l #%d, %s", g_3bit_qdata_table[(g_cpu_ir>>9)&7], get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_addx_rr_8(void)
{
sprintf(g_dasm_str, "addx.b D%d, D%d", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_addx_rr_16(void)
{
sprintf(g_dasm_str, "addx.w D%d, D%d", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_addx_rr_32(void)
{
sprintf(g_dasm_str, "addx.l D%d, D%d", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_addx_mm_8(void)
{
sprintf(g_dasm_str, "addx.b -(A%d), -(A%d)", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_addx_mm_16(void)
{
sprintf(g_dasm_str, "addx.w -(A%d), -(A%d)", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_addx_mm_32(void)
{
sprintf(g_dasm_str, "addx.l -(A%d), -(A%d)", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_and_er_8(void)
{
sprintf(g_dasm_str, "and.b %s, D%d", get_ea_mode_str_8(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_and_er_16(void)
{
sprintf(g_dasm_str, "and.w %s, D%d", get_ea_mode_str_16(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_and_er_32(void)
{
sprintf(g_dasm_str, "and.l %s, D%d", get_ea_mode_str_32(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_and_re_8(void)
{
sprintf(g_dasm_str, "and.b D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_and_re_16(void)
{
sprintf(g_dasm_str, "and.w D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_and_re_32(void)
{
sprintf(g_dasm_str, "and.l D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_andi_8(void)
{
char* str = get_imm_str_u8();
sprintf(g_dasm_str, "andi.b %s, %s", str, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_andi_16(void)
{
char* str = get_imm_str_u16();
sprintf(g_dasm_str, "andi.w %s, %s", str, get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_andi_32(void)
{
char* str = get_imm_str_u32();
sprintf(g_dasm_str, "andi.l %s, %s", str, get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_andi_to_ccr(void)
{
sprintf(g_dasm_str, "andi %s, CCR", get_imm_str_u8());
}
static void d68000_andi_to_sr(void)
{
sprintf(g_dasm_str, "andi %s, SR", get_imm_str_u16());
}
static void d68000_asr_s_8(void)
{
sprintf(g_dasm_str, "asr.b #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_asr_s_16(void)
{
sprintf(g_dasm_str, "asr.w #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_asr_s_32(void)
{
sprintf(g_dasm_str, "asr.l #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_asr_r_8(void)
{
sprintf(g_dasm_str, "asr.b D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_asr_r_16(void)
{
sprintf(g_dasm_str, "asr.w D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_asr_r_32(void)
{
sprintf(g_dasm_str, "asr.l D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_asr_ea(void)
{
sprintf(g_dasm_str, "asr.w %s", get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_asl_s_8(void)
{
sprintf(g_dasm_str, "asl.b #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_asl_s_16(void)
{
sprintf(g_dasm_str, "asl.w #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_asl_s_32(void)
{
sprintf(g_dasm_str, "asl.l #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_asl_r_8(void)
{
sprintf(g_dasm_str, "asl.b D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_asl_r_16(void)
{
sprintf(g_dasm_str, "asl.w D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_asl_r_32(void)
{
sprintf(g_dasm_str, "asl.l D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_asl_ea(void)
{
sprintf(g_dasm_str, "asl.w %s", get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_bcc_8(void)
{
uint temp_pc = g_cpu_pc;
sprintf(g_dasm_str, "b%-2s $%x", g_cc[(g_cpu_ir>>8)&0xf], temp_pc + make_int_8(g_cpu_ir));
}
static void d68000_bcc_16(void)
{
uint temp_pc = g_cpu_pc;
sprintf(g_dasm_str, "b%-2s $%x", g_cc[(g_cpu_ir>>8)&0xf], temp_pc + make_int_16(read_imm_16()));
}
static void d68020_bcc_32(void)
{
uint temp_pc = g_cpu_pc;
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "b%-2s $%x; (2+)", g_cc[(g_cpu_ir>>8)&0xf], temp_pc + read_imm_32());
}
static void d68000_bchg_r(void)
{
sprintf(g_dasm_str, "bchg D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_bchg_s(void)
{
char* str = get_imm_str_u8();
sprintf(g_dasm_str, "bchg %s, %s", str, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_bclr_r(void)
{
sprintf(g_dasm_str, "bclr D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_bclr_s(void)
{
char* str = get_imm_str_u8();
sprintf(g_dasm_str, "bclr %s, %s", str, get_ea_mode_str_8(g_cpu_ir));
}
static void d68010_bkpt(void)
{
LIMIT_CPU_TYPES(M68010_PLUS);
sprintf(g_dasm_str, "bkpt #%d; (1+)", g_cpu_ir&7);
}
static void d68020_bfchg(void)
{
uint extension;
char offset[3];
char width[3];
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
if(BIT_B(extension))
sprintf(offset, "D%d", (extension>>6)&7);
else
sprintf(offset, "%d", (extension>>6)&31);
if(BIT_5(extension))
sprintf(width, "D%d", extension&7);
else
sprintf(width, "%d", g_5bit_data_table[extension&31]);
sprintf(g_dasm_str, "bfchg %s {%s:%s}; (2+)", get_ea_mode_str_8(g_cpu_ir), offset, width);
}
static void d68020_bfclr(void)
{
uint extension;
char offset[3];
char width[3];
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
if(BIT_B(extension))
sprintf(offset, "D%d", (extension>>6)&7);
else
sprintf(offset, "%d", (extension>>6)&31);
if(BIT_5(extension))
sprintf(width, "D%d", extension&7);
else
sprintf(width, "%d", g_5bit_data_table[extension&31]);
sprintf(g_dasm_str, "bfclr %s {%s:%s}; (2+)", get_ea_mode_str_8(g_cpu_ir), offset, width);
}
static void d68020_bfexts(void)
{
uint extension;
char offset[3];
char width[3];
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
if(BIT_B(extension))
sprintf(offset, "D%d", (extension>>6)&7);
else
sprintf(offset, "%d", (extension>>6)&31);
if(BIT_5(extension))
sprintf(width, "D%d", extension&7);
else
sprintf(width, "%d", g_5bit_data_table[extension&31]);
sprintf(g_dasm_str, "bfexts %s {%s:%s}, D%d; (2+)", get_ea_mode_str_8(g_cpu_ir), offset, width, (extension>>12)&7);
}
static void d68020_bfextu(void)
{
uint extension;
char offset[3];
char width[3];
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
if(BIT_B(extension))
sprintf(offset, "D%d", (extension>>6)&7);
else
sprintf(offset, "%d", (extension>>6)&31);
if(BIT_5(extension))
sprintf(width, "D%d", extension&7);
else
sprintf(width, "%d", g_5bit_data_table[extension&31]);
sprintf(g_dasm_str, "bfextu %s {%s:%s}, D%d; (2+)", get_ea_mode_str_8(g_cpu_ir), offset, width, (extension>>12)&7);
}
static void d68020_bfffo(void)
{
uint extension;
char offset[3];
char width[3];
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
if(BIT_B(extension))
sprintf(offset, "D%d", (extension>>6)&7);
else
sprintf(offset, "%d", (extension>>6)&31);
if(BIT_5(extension))
sprintf(width, "D%d", extension&7);
else
sprintf(width, "%d", g_5bit_data_table[extension&31]);
sprintf(g_dasm_str, "bfffo %s {%s:%s}, D%d; (2+)", get_ea_mode_str_8(g_cpu_ir), offset, width, (extension>>12)&7);
}
static void d68020_bfins(void)
{
uint extension;
char offset[3];
char width[3];
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
if(BIT_B(extension))
sprintf(offset, "D%d", (extension>>6)&7);
else
sprintf(offset, "%d", (extension>>6)&31);
if(BIT_5(extension))
sprintf(width, "D%d", extension&7);
else
sprintf(width, "%d", g_5bit_data_table[extension&31]);
sprintf(g_dasm_str, "bfins D%d, %s {%s:%s}; (2+)", (extension>>12)&7, get_ea_mode_str_8(g_cpu_ir), offset, width);
}
static void d68020_bfset(void)
{
uint extension;
char offset[3];
char width[3];
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
if(BIT_B(extension))
sprintf(offset, "D%d", (extension>>6)&7);
else
sprintf(offset, "%d", (extension>>6)&31);
if(BIT_5(extension))
sprintf(width, "D%d", extension&7);
else
sprintf(width, "%d", g_5bit_data_table[extension&31]);
sprintf(g_dasm_str, "bfset %s {%s:%s}; (2+)", get_ea_mode_str_8(g_cpu_ir), offset, width);
}
static void d68020_bftst(void)
{
uint extension;
char offset[3];
char width[3];
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
if(BIT_B(extension))
sprintf(offset, "D%d", (extension>>6)&7);
else
sprintf(offset, "%d", (extension>>6)&31);
if(BIT_5(extension))
sprintf(width, "D%d", extension&7);
else
sprintf(width, "%d", g_5bit_data_table[extension&31]);
sprintf(g_dasm_str, "bftst %s {%s:%s}; (2+)", get_ea_mode_str_8(g_cpu_ir), offset, width);
}
static void d68000_bra_8(void)
{
uint temp_pc = g_cpu_pc;
sprintf(g_dasm_str, "bra $%x", temp_pc + make_int_8(g_cpu_ir));
}
static void d68000_bra_16(void)
{
uint temp_pc = g_cpu_pc;
sprintf(g_dasm_str, "bra $%x", temp_pc + make_int_16(read_imm_16()));
}
static void d68020_bra_32(void)
{
uint temp_pc = g_cpu_pc;
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "bra $%x; (2+)", temp_pc + read_imm_32());
}
static void d68000_bset_r(void)
{
sprintf(g_dasm_str, "bset D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_bset_s(void)
{
char* str = get_imm_str_u8();
sprintf(g_dasm_str, "bset %s, %s", str, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_bsr_8(void)
{
uint temp_pc = g_cpu_pc;
sprintf(g_dasm_str, "bsr $%x", temp_pc + make_int_8(g_cpu_ir));
SET_OPCODE_FLAGS(DASMFLAG_STEP_OVER);
}
static void d68000_bsr_16(void)
{
uint temp_pc = g_cpu_pc;
sprintf(g_dasm_str, "bsr $%x", temp_pc + make_int_16(read_imm_16()));
SET_OPCODE_FLAGS(DASMFLAG_STEP_OVER);
}
static void d68020_bsr_32(void)
{
uint temp_pc = g_cpu_pc;
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "bsr $%x; (2+)", temp_pc + read_imm_32());
SET_OPCODE_FLAGS(DASMFLAG_STEP_OVER);
}
static void d68000_btst_r(void)
{
sprintf(g_dasm_str, "btst D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_btst_s(void)
{
char* str = get_imm_str_u8();
sprintf(g_dasm_str, "btst %s, %s", str, get_ea_mode_str_8(g_cpu_ir));
}
static void d68020_callm(void)
{
char* str;
LIMIT_CPU_TYPES(M68020_ONLY);
str = get_imm_str_u8();
sprintf(g_dasm_str, "callm %s, %s; (2)", str, get_ea_mode_str_8(g_cpu_ir));
}
static void d68020_cas_8(void)
{
uint extension;
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
sprintf(g_dasm_str, "cas.b D%d, D%d, %s; (2+)", extension&7, (extension>>6)&7, get_ea_mode_str_8(g_cpu_ir));
}
static void d68020_cas_16(void)
{
uint extension;
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
sprintf(g_dasm_str, "cas.w D%d, D%d, %s; (2+)", extension&7, (extension>>6)&7, get_ea_mode_str_16(g_cpu_ir));
}
static void d68020_cas_32(void)
{
uint extension;
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
sprintf(g_dasm_str, "cas.l D%d, D%d, %s; (2+)", extension&7, (extension>>6)&7, get_ea_mode_str_32(g_cpu_ir));
}
static void d68020_cas2_16(void)
{
/* CAS2 Dc1:Dc2,Du1:Dc2:(Rn1):(Rn2)
f e d c b a 9 8 7 6 5 4 3 2 1 0
DARn1 0 0 0 Du1 0 0 0 Dc1
DARn2 0 0 0 Du2 0 0 0 Dc2
*/
uint extension;
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_32();
sprintf(g_dasm_str, "cas2.w D%d:D%d, D%d:D%d, (%c%d):(%c%d); (2+)",
(extension>>16)&7, extension&7, (extension>>22)&7, (extension>>6)&7,
BIT_1F(extension) ? 'A' : 'D', (extension>>28)&7,
BIT_F(extension) ? 'A' : 'D', (extension>>12)&7);
}
static void d68020_cas2_32(void)
{
uint extension;
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_32();
sprintf(g_dasm_str, "cas2.l D%d:D%d, D%d:D%d, (%c%d):(%c%d); (2+)",
(extension>>16)&7, extension&7, (extension>>22)&7, (extension>>6)&7,
BIT_1F(extension) ? 'A' : 'D', (extension>>28)&7,
BIT_F(extension) ? 'A' : 'D', (extension>>12)&7);
}
static void d68000_chk_16(void)
{
sprintf(g_dasm_str, "chk.w %s, D%d", get_ea_mode_str_16(g_cpu_ir), (g_cpu_ir>>9)&7);
SET_OPCODE_FLAGS(DASMFLAG_STEP_OVER);
}
static void d68020_chk_32(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "chk.l %s, D%d; (2+)", get_ea_mode_str_32(g_cpu_ir), (g_cpu_ir>>9)&7);
SET_OPCODE_FLAGS(DASMFLAG_STEP_OVER);
}
static void d68020_chk2_cmp2_8(void)
{
uint extension;
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
sprintf(g_dasm_str, "%s.b %s, %c%d; (2+)", BIT_B(extension) ? "chk2" : "cmp2", get_ea_mode_str_8(g_cpu_ir), BIT_F(extension) ? 'A' : 'D', (extension>>12)&7);
}
static void d68020_chk2_cmp2_16(void)
{
uint extension;
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
sprintf(g_dasm_str, "%s.w %s, %c%d; (2+)", BIT_B(extension) ? "chk2" : "cmp2", get_ea_mode_str_16(g_cpu_ir), BIT_F(extension) ? 'A' : 'D', (extension>>12)&7);
}
static void d68020_chk2_cmp2_32(void)
{
uint extension;
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
sprintf(g_dasm_str, "%s.l %s, %c%d; (2+)", BIT_B(extension) ? "chk2" : "cmp2", get_ea_mode_str_32(g_cpu_ir), BIT_F(extension) ? 'A' : 'D', (extension>>12)&7);
}
static void d68040_cinv(void)
{
LIMIT_CPU_TYPES(M68040_PLUS);
switch((g_cpu_ir>>3)&3)
{
case 0:
sprintf(g_dasm_str, "cinv (illegal scope); (4)");
break;
case 1:
sprintf(g_dasm_str, "cinvl %d, (A%d); (4)", (g_cpu_ir>>6)&3, g_cpu_ir&7);
break;
case 2:
sprintf(g_dasm_str, "cinvp %d, (A%d); (4)", (g_cpu_ir>>6)&3, g_cpu_ir&7);
break;
case 3:
sprintf(g_dasm_str, "cinva %d; (4)", (g_cpu_ir>>6)&3);
break;
}
}
static void d68000_clr_8(void)
{
sprintf(g_dasm_str, "clr.b %s", get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_clr_16(void)
{
sprintf(g_dasm_str, "clr.w %s", get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_clr_32(void)
{
sprintf(g_dasm_str, "clr.l %s", get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_cmp_8(void)
{
sprintf(g_dasm_str, "cmp.b %s, D%d", get_ea_mode_str_8(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_cmp_16(void)
{
sprintf(g_dasm_str, "cmp.w %s, D%d", get_ea_mode_str_16(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_cmp_32(void)
{
sprintf(g_dasm_str, "cmp.l %s, D%d", get_ea_mode_str_32(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_cmpa_16(void)
{
sprintf(g_dasm_str, "cmpa.w %s, A%d", get_ea_mode_str_16(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_cmpa_32(void)
{
sprintf(g_dasm_str, "cmpa.l %s, A%d", get_ea_mode_str_32(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_cmpi_8(void)
{
char* str = get_imm_str_s8();
sprintf(g_dasm_str, "cmpi.b %s, %s", str, get_ea_mode_str_8(g_cpu_ir));
}
static void d68020_cmpi_pcdi_8(void)
{
char* str;
LIMIT_CPU_TYPES(M68010_PLUS);
str = get_imm_str_s8();
sprintf(g_dasm_str, "cmpi.b %s, %s; (2+)", str, get_ea_mode_str_8(g_cpu_ir));
}
static void d68020_cmpi_pcix_8(void)
{
char* str;
LIMIT_CPU_TYPES(M68010_PLUS);
str = get_imm_str_s8();
sprintf(g_dasm_str, "cmpi.b %s, %s; (2+)", str, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_cmpi_16(void)
{
char* str;
str = get_imm_str_s16();
sprintf(g_dasm_str, "cmpi.w %s, %s", str, get_ea_mode_str_16(g_cpu_ir));
}
static void d68020_cmpi_pcdi_16(void)
{
char* str;
LIMIT_CPU_TYPES(M68010_PLUS);
str = get_imm_str_s16();
sprintf(g_dasm_str, "cmpi.w %s, %s; (2+)", str, get_ea_mode_str_16(g_cpu_ir));
}
static void d68020_cmpi_pcix_16(void)
{
char* str;
LIMIT_CPU_TYPES(M68010_PLUS);
str = get_imm_str_s16();
sprintf(g_dasm_str, "cmpi.w %s, %s; (2+)", str, get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_cmpi_32(void)
{
char* str;
str = get_imm_str_s32();
sprintf(g_dasm_str, "cmpi.l %s, %s", str, get_ea_mode_str_32(g_cpu_ir));
}
static void d68020_cmpi_pcdi_32(void)
{
char* str;
LIMIT_CPU_TYPES(M68010_PLUS);
str = get_imm_str_s32();
sprintf(g_dasm_str, "cmpi.l %s, %s; (2+)", str, get_ea_mode_str_32(g_cpu_ir));
}
static void d68020_cmpi_pcix_32(void)
{
char* str;
LIMIT_CPU_TYPES(M68010_PLUS);
str = get_imm_str_s32();
sprintf(g_dasm_str, "cmpi.l %s, %s; (2+)", str, get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_cmpm_8(void)
{
sprintf(g_dasm_str, "cmpm.b (A%d)+, (A%d)+", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_cmpm_16(void)
{
sprintf(g_dasm_str, "cmpm.w (A%d)+, (A%d)+", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_cmpm_32(void)
{
sprintf(g_dasm_str, "cmpm.l (A%d)+, (A%d)+", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68020_cpbcc_16(void)
{
uint extension;
uint new_pc = g_cpu_pc;
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
new_pc += make_int_16(read_imm_16());
sprintf(g_dasm_str, "%db%-4s %s; %x (extension = %x) (2-3)", (g_cpu_ir>>9)&7, g_cpcc[g_cpu_ir&0x3f], get_imm_str_s16(), new_pc, extension);
}
static void d68020_cpbcc_32(void)
{
uint extension;
uint new_pc = g_cpu_pc;
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
new_pc += read_imm_32();
sprintf(g_dasm_str, "%db%-4s %s; %x (extension = %x) (2-3)", (g_cpu_ir>>9)&7, g_cpcc[g_cpu_ir&0x3f], get_imm_str_s16(), new_pc, extension);
}
static void d68020_cpdbcc(void)
{
uint extension1;
uint extension2;
uint new_pc = g_cpu_pc;
LIMIT_CPU_TYPES(M68020_PLUS);
extension1 = read_imm_16();
extension2 = read_imm_16();
new_pc += make_int_16(read_imm_16());
sprintf(g_dasm_str, "%ddb%-4s D%d,%s; %x (extension = %x) (2-3)", (g_cpu_ir>>9)&7, g_cpcc[extension1&0x3f], g_cpu_ir&7, get_imm_str_s16(), new_pc, extension2);
}
static void d68020_cpgen(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "%dgen %s; (2-3)", (g_cpu_ir>>9)&7, get_imm_str_u32());
}
static void d68020_cprestore(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
if (((g_cpu_ir>>9)&7) == 1)
{
sprintf(g_dasm_str, "frestore %s", get_ea_mode_str_8(g_cpu_ir));
}
else
{
sprintf(g_dasm_str, "%drestore %s; (2-3)", (g_cpu_ir>>9)&7, get_ea_mode_str_8(g_cpu_ir));
}
}
static void d68020_cpsave(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
if (((g_cpu_ir>>9)&7) == 1)
{
sprintf(g_dasm_str, "fsave %s", get_ea_mode_str_8(g_cpu_ir));
}
else
{
sprintf(g_dasm_str, "%dsave %s; (2-3)", (g_cpu_ir>>9)&7, get_ea_mode_str_8(g_cpu_ir));
}
}
static void d68020_cpscc(void)
{
uint extension1;
uint extension2;
LIMIT_CPU_TYPES(M68020_PLUS);
extension1 = read_imm_16();
extension2 = read_imm_16();
sprintf(g_dasm_str, "%ds%-4s %s; (extension = %x) (2-3)", (g_cpu_ir>>9)&7, g_cpcc[extension1&0x3f], get_ea_mode_str_8(g_cpu_ir), extension2);
}
static void d68020_cptrapcc_0(void)
{
uint extension1;
uint extension2;
LIMIT_CPU_TYPES(M68020_PLUS);
extension1 = read_imm_16();
extension2 = read_imm_16();
sprintf(g_dasm_str, "%dtrap%-4s; (extension = %x) (2-3)", (g_cpu_ir>>9)&7, g_cpcc[extension1&0x3f], extension2);
}
static void d68020_cptrapcc_16(void)
{
uint extension1;
uint extension2;
LIMIT_CPU_TYPES(M68020_PLUS);
extension1 = read_imm_16();
extension2 = read_imm_16();
sprintf(g_dasm_str, "%dtrap%-4s %s; (extension = %x) (2-3)", (g_cpu_ir>>9)&7, g_cpcc[extension1&0x3f], get_imm_str_u16(), extension2);
}
static void d68020_cptrapcc_32(void)
{
uint extension1;
uint extension2;
LIMIT_CPU_TYPES(M68020_PLUS);
extension1 = read_imm_16();
extension2 = read_imm_16();
sprintf(g_dasm_str, "%dtrap%-4s %s; (extension = %x) (2-3)", (g_cpu_ir>>9)&7, g_cpcc[extension1&0x3f], get_imm_str_u32(), extension2);
}
static void d68040_cpush(void)
{
LIMIT_CPU_TYPES(M68040_PLUS);
switch((g_cpu_ir>>3)&3)
{
case 0:
sprintf(g_dasm_str, "cpush (illegal scope); (4)");
break;
case 1:
sprintf(g_dasm_str, "cpushl %d, (A%d); (4)", (g_cpu_ir>>6)&3, g_cpu_ir&7);
break;
case 2:
sprintf(g_dasm_str, "cpushp %d, (A%d); (4)", (g_cpu_ir>>6)&3, g_cpu_ir&7);
break;
case 3:
sprintf(g_dasm_str, "cpusha %d; (4)", (g_cpu_ir>>6)&3);
break;
}
}
static void d68000_dbra(void)
{
uint temp_pc = g_cpu_pc;
sprintf(g_dasm_str, "dbra D%d, $%x", g_cpu_ir & 7, temp_pc + make_int_16(read_imm_16()));
SET_OPCODE_FLAGS(DASMFLAG_STEP_OVER);
}
static void d68000_dbcc(void)
{
uint temp_pc = g_cpu_pc;
sprintf(g_dasm_str, "db%-2s D%d, $%x", g_cc[(g_cpu_ir>>8)&0xf], g_cpu_ir & 7, temp_pc + make_int_16(read_imm_16()));
SET_OPCODE_FLAGS(DASMFLAG_STEP_OVER);
}
static void d68000_divs(void)
{
sprintf(g_dasm_str, "divs.w %s, D%d", get_ea_mode_str_16(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_divu(void)
{
sprintf(g_dasm_str, "divu.w %s, D%d", get_ea_mode_str_16(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68020_divl(void)
{
uint extension;
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
if(BIT_A(extension))
sprintf(g_dasm_str, "div%c.l %s, D%d:D%d; (2+)", BIT_B(extension) ? 's' : 'u', get_ea_mode_str_32(g_cpu_ir), extension&7, (extension>>12)&7);
else if((extension&7) == ((extension>>12)&7))
sprintf(g_dasm_str, "div%c.l %s, D%d; (2+)", BIT_B(extension) ? 's' : 'u', get_ea_mode_str_32(g_cpu_ir), (extension>>12)&7);
else
sprintf(g_dasm_str, "div%cl.l %s, D%d:D%d; (2+)", BIT_B(extension) ? 's' : 'u', get_ea_mode_str_32(g_cpu_ir), extension&7, (extension>>12)&7);
}
static void d68000_eor_8(void)
{
sprintf(g_dasm_str, "eor.b D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_eor_16(void)
{
sprintf(g_dasm_str, "eor.w D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_eor_32(void)
{
sprintf(g_dasm_str, "eor.l D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_eori_8(void)
{
char* str = get_imm_str_u8();
sprintf(g_dasm_str, "eori.b %s, %s", str, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_eori_16(void)
{
char* str = get_imm_str_u16();
sprintf(g_dasm_str, "eori.w %s, %s", str, get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_eori_32(void)
{
char* str = get_imm_str_u32();
sprintf(g_dasm_str, "eori.l %s, %s", str, get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_eori_to_ccr(void)
{
sprintf(g_dasm_str, "eori %s, CCR", get_imm_str_u8());
}
static void d68000_eori_to_sr(void)
{
sprintf(g_dasm_str, "eori %s, SR", get_imm_str_u16());
}
static void d68000_exg_dd(void)
{
sprintf(g_dasm_str, "exg D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_exg_aa(void)
{
sprintf(g_dasm_str, "exg A%d, A%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_exg_da(void)
{
sprintf(g_dasm_str, "exg D%d, A%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_ext_16(void)
{
sprintf(g_dasm_str, "ext.w D%d", g_cpu_ir&7);
}
static void d68000_ext_32(void)
{
sprintf(g_dasm_str, "ext.l D%d", g_cpu_ir&7);
}
static void d68020_extb_32(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "extb.l D%d; (2+)", g_cpu_ir&7);
}
static void d68040_fpu(void)
{
char float_data_format[8][3] =
{
".l", ".s", ".x", ".p", ".w", ".d", ".b", ".p"
};
char mnemonic[40];
uint32 w2, src, dst_reg;
LIMIT_CPU_TYPES(M68030_PLUS);
w2 = read_imm_16();
src = (w2 >> 10) & 0x7;
dst_reg = (w2 >> 7) & 0x7;
// special override for FMOVECR
if ((((w2 >> 13) & 0x7) == 2) && (((w2>>10)&0x7) == 7))
{
sprintf(g_dasm_str, "fmovecr #$%0x, fp%d", (w2&0x7f), dst_reg);
return;
}
switch ((w2 >> 13) & 0x7)
{
case 0x0:
case 0x2:
{
switch(w2 & 0x7f)
{
case 0x00: sprintf(mnemonic, "fmove"); break;
case 0x01: sprintf(mnemonic, "fint"); break;
case 0x02: sprintf(mnemonic, "fsinh"); break;
case 0x03: sprintf(mnemonic, "fintrz"); break;
case 0x04: sprintf(mnemonic, "fsqrt"); break;
case 0x06: sprintf(mnemonic, "flognp1"); break;
case 0x08: sprintf(mnemonic, "fetoxm1"); break;
case 0x09: sprintf(mnemonic, "ftanh1"); break;
case 0x0a: sprintf(mnemonic, "fatan"); break;
case 0x0c: sprintf(mnemonic, "fasin"); break;
case 0x0d: sprintf(mnemonic, "fatanh"); break;
case 0x0e: sprintf(mnemonic, "fsin"); break;
case 0x0f: sprintf(mnemonic, "ftan"); break;
case 0x10: sprintf(mnemonic, "fetox"); break;
case 0x11: sprintf(mnemonic, "ftwotox"); break;
case 0x12: sprintf(mnemonic, "ftentox"); break;
case 0x14: sprintf(mnemonic, "flogn"); break;
case 0x15: sprintf(mnemonic, "flog10"); break;
case 0x16: sprintf(mnemonic, "flog2"); break;
case 0x18: sprintf(mnemonic, "fabs"); break;
case 0x19: sprintf(mnemonic, "fcosh"); break;
case 0x1a: sprintf(mnemonic, "fneg"); break;
case 0x1c: sprintf(mnemonic, "facos"); break;
case 0x1d: sprintf(mnemonic, "fcos"); break;
case 0x1e: sprintf(mnemonic, "fgetexp"); break;
case 0x1f: sprintf(mnemonic, "fgetman"); break;
case 0x20: sprintf(mnemonic, "fdiv"); break;
case 0x21: sprintf(mnemonic, "fmod"); break;
case 0x22: sprintf(mnemonic, "fadd"); break;
case 0x23: sprintf(mnemonic, "fmul"); break;
case 0x24: sprintf(mnemonic, "fsgldiv"); break;
case 0x25: sprintf(mnemonic, "frem"); break;
case 0x26: sprintf(mnemonic, "fscale"); break;
case 0x27: sprintf(mnemonic, "fsglmul"); break;
case 0x28: sprintf(mnemonic, "fsub"); break;
case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37:
sprintf(mnemonic, "fsincos"); break;
case 0x38: sprintf(mnemonic, "fcmp"); break;
case 0x3a: sprintf(mnemonic, "ftst"); break;
case 0x41: sprintf(mnemonic, "fssqrt"); break;
case 0x45: sprintf(mnemonic, "fdsqrt"); break;
case 0x58: sprintf(mnemonic, "fsabs"); break;
case 0x5a: sprintf(mnemonic, "fsneg"); break;
case 0x5c: sprintf(mnemonic, "fdabs"); break;
case 0x5e: sprintf(mnemonic, "fdneg"); break;
case 0x60: sprintf(mnemonic, "fsdiv"); break;
case 0x62: sprintf(mnemonic, "fsadd"); break;
case 0x63: sprintf(mnemonic, "fsmul"); break;
case 0x64: sprintf(mnemonic, "fddiv"); break;
case 0x66: sprintf(mnemonic, "fdadd"); break;
case 0x67: sprintf(mnemonic, "fdmul"); break;
case 0x68: sprintf(mnemonic, "fssub"); break;
case 0x6c: sprintf(mnemonic, "fdsub"); break;
default: sprintf(mnemonic, "FPU (?)"); break;
}
if (w2 & 0x4000)
{
sprintf(g_dasm_str, "%s%s %s, FP%d", mnemonic, float_data_format[src], get_ea_mode_str_32(g_cpu_ir), dst_reg);
}
else
{
sprintf(g_dasm_str, "%s.x FP%d, FP%d", mnemonic, src, dst_reg);
}
break;
}
case 0x3:
{
switch ((w2>>10)&7)
{
case 3: // packed decimal w/fixed k-factor
sprintf(g_dasm_str, "fmove%s FP%d, %s {#%d}", float_data_format[(w2>>10)&7], dst_reg, get_ea_mode_str_32(g_cpu_ir), sext_7bit_int(w2&0x7f));
break;
case 7: // packed decimal w/dynamic k-factor (register)
sprintf(g_dasm_str, "fmove%s FP%d, %s {D%d}", float_data_format[(w2>>10)&7], dst_reg, get_ea_mode_str_32(g_cpu_ir), (w2>>4)&7);
break;
default:
sprintf(g_dasm_str, "fmove%s FP%d, %s", float_data_format[(w2>>10)&7], dst_reg, get_ea_mode_str_32(g_cpu_ir));
break;
}
break;
}
case 0x4: // ea to control
{
sprintf(g_dasm_str, "fmovem.l %s, ", get_ea_mode_str_32(g_cpu_ir));
if (w2 & 0x1000) strcat(g_dasm_str, "fpcr");
if (w2 & 0x0800) strcat(g_dasm_str, "/fpsr");
if (w2 & 0x0400) strcat(g_dasm_str, "/fpiar");
break;
}
case 0x5: // control to ea
{
strcpy(g_dasm_str, "fmovem.l ");
if (w2 & 0x1000) strcat(g_dasm_str, "fpcr");
if (w2 & 0x0800) strcat(g_dasm_str, "/fpsr");
if (w2 & 0x0400) strcat(g_dasm_str, "/fpiar");
strcat(g_dasm_str, ", ");
strcat(g_dasm_str, get_ea_mode_str_32(g_cpu_ir));
break;
}
case 0x6: // memory to FPU, list
{
char temp[32];
if ((w2>>11) & 1) // dynamic register list
{
sprintf(g_dasm_str, "fmovem.x %s, D%d", get_ea_mode_str_32(g_cpu_ir), (w2>>4)&7);
}
else // static register list
{
int i;
sprintf(g_dasm_str, "fmovem.x %s, ", get_ea_mode_str_32(g_cpu_ir));
for (i = 0; i < 8; i++)
{
if (w2 & (1<<i))
{
if ((w2>>12) & 1) // postincrement or control
{
sprintf(temp, "FP%d ", 7-i);
}
else // predecrement
{
sprintf(temp, "FP%d ", i);
}
strcat(g_dasm_str, temp);
}
}
}
break;
}
case 0x7: // FPU to memory, list
{
char temp[32];
if ((w2>>11) & 1) // dynamic register list
{
sprintf(g_dasm_str, "fmovem.x D%d, %s", (w2>>4)&7, get_ea_mode_str_32(g_cpu_ir));
}
else // static register list
{
int i;
sprintf(g_dasm_str, "fmovem.x ");
for (i = 0; i < 8; i++)
{
if (w2 & (1<<i))
{
if ((w2>>12) & 1) // postincrement or control
{
sprintf(temp, "FP%d ", 7-i);
}
else // predecrement
{
sprintf(temp, "FP%d ", i);
}
strcat(g_dasm_str, temp);
}
}
strcat(g_dasm_str, ", ");
strcat(g_dasm_str, get_ea_mode_str_32(g_cpu_ir));
}
break;
}
default:
{
sprintf(g_dasm_str, "FPU (?) ");
break;
}
}
}
static void d68000_jmp(void)
{
sprintf(g_dasm_str, "jmp %s", get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_jsr(void)
{
sprintf(g_dasm_str, "jsr %s", get_ea_mode_str_32(g_cpu_ir));
SET_OPCODE_FLAGS(DASMFLAG_STEP_OVER);
}
static void d68000_lea(void)
{
sprintf(g_dasm_str, "lea %s, A%d", get_ea_mode_str_32(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_link_16(void)
{
sprintf(g_dasm_str, "link A%d, %s", g_cpu_ir&7, get_imm_str_s16());
}
static void d68020_link_32(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "link A%d, %s; (2+)", g_cpu_ir&7, get_imm_str_s32());
}
static void d68000_lsr_s_8(void)
{
sprintf(g_dasm_str, "lsr.b #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_lsr_s_16(void)
{
sprintf(g_dasm_str, "lsr.w #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_lsr_s_32(void)
{
sprintf(g_dasm_str, "lsr.l #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_lsr_r_8(void)
{
sprintf(g_dasm_str, "lsr.b D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_lsr_r_16(void)
{
sprintf(g_dasm_str, "lsr.w D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_lsr_r_32(void)
{
sprintf(g_dasm_str, "lsr.l D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_lsr_ea(void)
{
sprintf(g_dasm_str, "lsr.w %s", get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_lsl_s_8(void)
{
sprintf(g_dasm_str, "lsl.b #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_lsl_s_16(void)
{
sprintf(g_dasm_str, "lsl.w #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_lsl_s_32(void)
{
sprintf(g_dasm_str, "lsl.l #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_lsl_r_8(void)
{
sprintf(g_dasm_str, "lsl.b D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_lsl_r_16(void)
{
sprintf(g_dasm_str, "lsl.w D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_lsl_r_32(void)
{
sprintf(g_dasm_str, "lsl.l D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_lsl_ea(void)
{
sprintf(g_dasm_str, "lsl.w %s", get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_move_8(void)
{
char* str = get_ea_mode_str_8(g_cpu_ir);
sprintf(g_dasm_str, "move.b %s, %s", str, get_ea_mode_str_8(((g_cpu_ir>>9) & 7) | ((g_cpu_ir>>3) & 0x38)));
}
static void d68000_move_16(void)
{
char* str = get_ea_mode_str_16(g_cpu_ir);
sprintf(g_dasm_str, "move.w %s, %s", str, get_ea_mode_str_16(((g_cpu_ir>>9) & 7) | ((g_cpu_ir>>3) & 0x38)));
}
static void d68000_move_32(void)
{
char* str = get_ea_mode_str_32(g_cpu_ir);
sprintf(g_dasm_str, "move.l %s, %s", str, get_ea_mode_str_32(((g_cpu_ir>>9) & 7) | ((g_cpu_ir>>3) & 0x38)));
}
static void d68000_movea_16(void)
{
sprintf(g_dasm_str, "movea.w %s, A%d", get_ea_mode_str_16(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_movea_32(void)
{
sprintf(g_dasm_str, "movea.l %s, A%d", get_ea_mode_str_32(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_move_to_ccr(void)
{
sprintf(g_dasm_str, "move %s, CCR", get_ea_mode_str_8(g_cpu_ir));
}
static void d68010_move_fr_ccr(void)
{
LIMIT_CPU_TYPES(M68010_PLUS);
sprintf(g_dasm_str, "move CCR, %s; (1+)", get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_move_fr_sr(void)
{
sprintf(g_dasm_str, "move SR, %s", get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_move_to_sr(void)
{
sprintf(g_dasm_str, "move %s, SR", get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_move_fr_usp(void)
{
sprintf(g_dasm_str, "move USP, A%d", g_cpu_ir&7);
}
static void d68000_move_to_usp(void)
{
sprintf(g_dasm_str, "move A%d, USP", g_cpu_ir&7);
}
static void d68010_movec(void)
{
uint extension;
char* reg_name;
char* processor;
LIMIT_CPU_TYPES(M68010_PLUS);
extension = read_imm_16();
switch(extension & 0xfff)
{
case 0x000:
reg_name = "SFC";
processor = "1+";
break;
case 0x001:
reg_name = "DFC";
processor = "1+";
break;
case 0x800:
reg_name = "USP";
processor = "1+";
break;
case 0x801:
reg_name = "VBR";
processor = "1+";
break;
case 0x002:
reg_name = "CACR";
processor = "2+";
break;
case 0x802:
reg_name = "CAAR";
processor = "2,3";
break;
case 0x803:
reg_name = "MSP";
processor = "2+";
break;
case 0x804:
reg_name = "ISP";
processor = "2+";
break;
case 0x003:
reg_name = "TC";
processor = "4+";
break;
case 0x004:
reg_name = "ITT0";
processor = "4+";
break;
case 0x005:
reg_name = "ITT1";
processor = "4+";
break;
case 0x006:
reg_name = "DTT0";
processor = "4+";
break;
case 0x007:
reg_name = "DTT1";
processor = "4+";
break;
case 0x805:
reg_name = "MMUSR";
processor = "4+";
break;
case 0x806:
reg_name = "URP";
processor = "4+";
break;
case 0x807:
reg_name = "SRP";
processor = "4+";
break;
default:
reg_name = make_signed_hex_str_16(extension & 0xfff);
processor = "?";
}
if(BIT_0(g_cpu_ir))
sprintf(g_dasm_str, "movec %c%d, %s; (%s)", BIT_F(extension) ? 'A' : 'D', (extension>>12)&7, reg_name, processor);
else
sprintf(g_dasm_str, "movec %s, %c%d; (%s)", reg_name, BIT_F(extension) ? 'A' : 'D', (extension>>12)&7, processor);
}
static void d68000_movem_pd_16(void)
{
uint data = read_imm_16();
char buffer[40];
uint first;
uint run_length;
uint i;
buffer[0] = 0;
for(i=0;i<8;i++)
{
if(data&(1<<(15-i)))
{
first = i;
run_length = 0;
while(i<7 && (data&(1<<(15-(i+1)))))
{
i++;
run_length++;
}
if(buffer[0] != 0)
strcat(buffer, "/");
sprintf(buffer+strlen(buffer), "D%d", first);
if(run_length > 0)
sprintf(buffer+strlen(buffer), "-D%d", first + run_length);
}
}
for(i=0;i<8;i++)
{
if(data&(1<<(7-i)))
{
first = i;
run_length = 0;
while(i<7 && (data&(1<<(7-(i+1)))))
{
i++;
run_length++;
}
if(buffer[0] != 0)
strcat(buffer, "/");
sprintf(buffer+strlen(buffer), "A%d", first);
if(run_length > 0)
sprintf(buffer+strlen(buffer), "-A%d", first + run_length);
}
}
sprintf(g_dasm_str, "movem.w %s, %s", buffer, get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_movem_pd_32(void)
{
uint data = read_imm_16();
char buffer[40];
uint first;
uint run_length;
uint i;
buffer[0] = 0;
for(i=0;i<8;i++)
{
if(data&(1<<(15-i)))
{
first = i;
run_length = 0;
while(i<7 && (data&(1<<(15-(i+1)))))
{
i++;
run_length++;
}
if(buffer[0] != 0)
strcat(buffer, "/");
sprintf(buffer+strlen(buffer), "D%d", first);
if(run_length > 0)
sprintf(buffer+strlen(buffer), "-D%d", first + run_length);
}
}
for(i=0;i<8;i++)
{
if(data&(1<<(7-i)))
{
first = i;
run_length = 0;
while(i<7 && (data&(1<<(7-(i+1)))))
{
i++;
run_length++;
}
if(buffer[0] != 0)
strcat(buffer, "/");
sprintf(buffer+strlen(buffer), "A%d", first);
if(run_length > 0)
sprintf(buffer+strlen(buffer), "-A%d", first + run_length);
}
}
sprintf(g_dasm_str, "movem.l %s, %s", buffer, get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_movem_er_16(void)
{
uint data = read_imm_16();
char buffer[40];
uint first;
uint run_length;
uint i;
buffer[0] = 0;
for(i=0;i<8;i++)
{
if(data&(1<<i))
{
first = i;
run_length = 0;
while(i<7 && (data&(1<<(i+1))))
{
i++;
run_length++;
}
if(buffer[0] != 0)
strcat(buffer, "/");
sprintf(buffer+strlen(buffer), "D%d", first);
if(run_length > 0)
sprintf(buffer+strlen(buffer), "-D%d", first + run_length);
}
}
for(i=0;i<8;i++)
{
if(data&(1<<(i+8)))
{
first = i;
run_length = 0;
while(i<7 && (data&(1<<(i+8+1))))
{
i++;
run_length++;
}
if(buffer[0] != 0)
strcat(buffer, "/");
sprintf(buffer+strlen(buffer), "A%d", first);
if(run_length > 0)
sprintf(buffer+strlen(buffer), "-A%d", first + run_length);
}
}
sprintf(g_dasm_str, "movem.w %s, %s", get_ea_mode_str_16(g_cpu_ir), buffer);
}
static void d68000_movem_er_32(void)
{
uint data = read_imm_16();
char buffer[40];
uint first;
uint run_length;
uint i;
buffer[0] = 0;
for(i=0;i<8;i++)
{
if(data&(1<<i))
{
first = i;
run_length = 0;
while(i<7 && (data&(1<<(i+1))))
{
i++;
run_length++;
}
if(buffer[0] != 0)
strcat(buffer, "/");
sprintf(buffer+strlen(buffer), "D%d", first);
if(run_length > 0)
sprintf(buffer+strlen(buffer), "-D%d", first + run_length);
}
}
for(i=0;i<8;i++)
{
if(data&(1<<(i+8)))
{
first = i;
run_length = 0;
while(i<7 && (data&(1<<(i+8+1))))
{
i++;
run_length++;
}
if(buffer[0] != 0)
strcat(buffer, "/");
sprintf(buffer+strlen(buffer), "A%d", first);
if(run_length > 0)
sprintf(buffer+strlen(buffer), "-A%d", first + run_length);
}
}
sprintf(g_dasm_str, "movem.l %s, %s", get_ea_mode_str_32(g_cpu_ir), buffer);
}
static void d68000_movem_re_16(void)
{
uint data = read_imm_16();
char buffer[40];
uint first;
uint run_length;
uint i;
buffer[0] = 0;
for(i=0;i<8;i++)
{
if(data&(1<<i))
{
first = i;
run_length = 0;
while(i<7 && (data&(1<<(i+1))))
{
i++;
run_length++;
}
if(buffer[0] != 0)
strcat(buffer, "/");
sprintf(buffer+strlen(buffer), "D%d", first);
if(run_length > 0)
sprintf(buffer+strlen(buffer), "-D%d", first + run_length);
}
}
for(i=0;i<8;i++)
{
if(data&(1<<(i+8)))
{
first = i;
run_length = 0;
while(i<7 && (data&(1<<(i+8+1))))
{
i++;
run_length++;
}
if(buffer[0] != 0)
strcat(buffer, "/");
sprintf(buffer+strlen(buffer), "A%d", first);
if(run_length > 0)
sprintf(buffer+strlen(buffer), "-A%d", first + run_length);
}
}
sprintf(g_dasm_str, "movem.w %s, %s", buffer, get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_movem_re_32(void)
{
uint data = read_imm_16();
char buffer[40];
uint first;
uint run_length;
uint i;
buffer[0] = 0;
for(i=0;i<8;i++)
{
if(data&(1<<i))
{
first = i;
run_length = 0;
while(i<7 && (data&(1<<(i+1))))
{
i++;
run_length++;
}
if(buffer[0] != 0)
strcat(buffer, "/");
sprintf(buffer+strlen(buffer), "D%d", first);
if(run_length > 0)
sprintf(buffer+strlen(buffer), "-D%d", first + run_length);
}
}
for(i=0;i<8;i++)
{
if(data&(1<<(i+8)))
{
first = i;
run_length = 0;
while(i<7 && (data&(1<<(i+8+1))))
{
i++;
run_length++;
}
if(buffer[0] != 0)
strcat(buffer, "/");
sprintf(buffer+strlen(buffer), "A%d", first);
if(run_length > 0)
sprintf(buffer+strlen(buffer), "-A%d", first + run_length);
}
}
sprintf(g_dasm_str, "movem.l %s, %s", buffer, get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_movep_re_16(void)
{
sprintf(g_dasm_str, "movep.w D%d, ($%x,A%d)", (g_cpu_ir>>9)&7, read_imm_16(), g_cpu_ir&7);
}
static void d68000_movep_re_32(void)
{
sprintf(g_dasm_str, "movep.l D%d, ($%x,A%d)", (g_cpu_ir>>9)&7, read_imm_16(), g_cpu_ir&7);
}
static void d68000_movep_er_16(void)
{
sprintf(g_dasm_str, "movep.w ($%x,A%d), D%d", read_imm_16(), g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_movep_er_32(void)
{
sprintf(g_dasm_str, "movep.l ($%x,A%d), D%d", read_imm_16(), g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68010_moves_8(void)
{
uint extension;
LIMIT_CPU_TYPES(M68010_PLUS);
extension = read_imm_16();
if(BIT_B(extension))
sprintf(g_dasm_str, "moves.b %c%d, %s; (1+)", BIT_F(extension) ? 'A' : 'D', (extension>>12)&7, get_ea_mode_str_8(g_cpu_ir));
else
sprintf(g_dasm_str, "moves.b %s, %c%d; (1+)", get_ea_mode_str_8(g_cpu_ir), BIT_F(extension) ? 'A' : 'D', (extension>>12)&7);
}
static void d68010_moves_16(void)
{
uint extension;
LIMIT_CPU_TYPES(M68010_PLUS);
extension = read_imm_16();
if(BIT_B(extension))
sprintf(g_dasm_str, "moves.w %c%d, %s; (1+)", BIT_F(extension) ? 'A' : 'D', (extension>>12)&7, get_ea_mode_str_16(g_cpu_ir));
else
sprintf(g_dasm_str, "moves.w %s, %c%d; (1+)", get_ea_mode_str_16(g_cpu_ir), BIT_F(extension) ? 'A' : 'D', (extension>>12)&7);
}
static void d68010_moves_32(void)
{
uint extension;
LIMIT_CPU_TYPES(M68010_PLUS);
extension = read_imm_16();
if(BIT_B(extension))
sprintf(g_dasm_str, "moves.l %c%d, %s; (1+)", BIT_F(extension) ? 'A' : 'D', (extension>>12)&7, get_ea_mode_str_32(g_cpu_ir));
else
sprintf(g_dasm_str, "moves.l %s, %c%d; (1+)", get_ea_mode_str_32(g_cpu_ir), BIT_F(extension) ? 'A' : 'D', (extension>>12)&7);
}
static void d68000_moveq(void)
{
sprintf(g_dasm_str, "moveq #%s, D%d", make_signed_hex_str_8(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68040_move16_pi_pi(void)
{
LIMIT_CPU_TYPES(M68040_PLUS);
sprintf(g_dasm_str, "move16 (A%d)+, (A%d)+; (4)", g_cpu_ir&7, (read_imm_16()>>12)&7);
}
static void d68040_move16_pi_al(void)
{
LIMIT_CPU_TYPES(M68040_PLUS);
sprintf(g_dasm_str, "move16 (A%d)+, %s; (4)", g_cpu_ir&7, get_imm_str_u32());
}
static void d68040_move16_al_pi(void)
{
LIMIT_CPU_TYPES(M68040_PLUS);
sprintf(g_dasm_str, "move16 %s, (A%d)+; (4)", get_imm_str_u32(), g_cpu_ir&7);
}
static void d68040_move16_ai_al(void)
{
LIMIT_CPU_TYPES(M68040_PLUS);
sprintf(g_dasm_str, "move16 (A%d), %s; (4)", g_cpu_ir&7, get_imm_str_u32());
}
static void d68040_move16_al_ai(void)
{
LIMIT_CPU_TYPES(M68040_PLUS);
sprintf(g_dasm_str, "move16 %s, (A%d); (4)", get_imm_str_u32(), g_cpu_ir&7);
}
static void d68000_muls(void)
{
sprintf(g_dasm_str, "muls.w %s, D%d", get_ea_mode_str_16(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_mulu(void)
{
sprintf(g_dasm_str, "mulu.w %s, D%d", get_ea_mode_str_16(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68020_mull(void)
{
uint extension;
LIMIT_CPU_TYPES(M68020_PLUS);
extension = read_imm_16();
if(BIT_A(extension))
sprintf(g_dasm_str, "mul%c.l %s, D%d:D%d; (2+)", BIT_B(extension) ? 's' : 'u', get_ea_mode_str_32(g_cpu_ir), extension&7, (extension>>12)&7);
else
sprintf(g_dasm_str, "mul%c.l %s, D%d; (2+)", BIT_B(extension) ? 's' : 'u', get_ea_mode_str_32(g_cpu_ir), (extension>>12)&7);
}
static void d68000_nbcd(void)
{
sprintf(g_dasm_str, "nbcd %s", get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_neg_8(void)
{
sprintf(g_dasm_str, "neg.b %s", get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_neg_16(void)
{
sprintf(g_dasm_str, "neg.w %s", get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_neg_32(void)
{
sprintf(g_dasm_str, "neg.l %s", get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_negx_8(void)
{
sprintf(g_dasm_str, "negx.b %s", get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_negx_16(void)
{
sprintf(g_dasm_str, "negx.w %s", get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_negx_32(void)
{
sprintf(g_dasm_str, "negx.l %s", get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_nop(void)
{
sprintf(g_dasm_str, "nop");
}
static void d68000_not_8(void)
{
sprintf(g_dasm_str, "not.b %s", get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_not_16(void)
{
sprintf(g_dasm_str, "not.w %s", get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_not_32(void)
{
sprintf(g_dasm_str, "not.l %s", get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_or_er_8(void)
{
sprintf(g_dasm_str, "or.b %s, D%d", get_ea_mode_str_8(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_or_er_16(void)
{
sprintf(g_dasm_str, "or.w %s, D%d", get_ea_mode_str_16(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_or_er_32(void)
{
sprintf(g_dasm_str, "or.l %s, D%d", get_ea_mode_str_32(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_or_re_8(void)
{
sprintf(g_dasm_str, "or.b D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_or_re_16(void)
{
sprintf(g_dasm_str, "or.w D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_or_re_32(void)
{
sprintf(g_dasm_str, "or.l D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_ori_8(void)
{
char* str = get_imm_str_u8();
sprintf(g_dasm_str, "ori.b %s, %s", str, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_ori_16(void)
{
char* str = get_imm_str_u16();
sprintf(g_dasm_str, "ori.w %s, %s", str, get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_ori_32(void)
{
char* str = get_imm_str_u32();
sprintf(g_dasm_str, "ori.l %s, %s", str, get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_ori_to_ccr(void)
{
sprintf(g_dasm_str, "ori %s, CCR", get_imm_str_u8());
}
static void d68000_ori_to_sr(void)
{
sprintf(g_dasm_str, "ori %s, SR", get_imm_str_u16());
}
static void d68020_pack_rr(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "pack D%d, D%d, %s; (2+)", g_cpu_ir&7, (g_cpu_ir>>9)&7, get_imm_str_u16());
}
static void d68020_pack_mm(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "pack -(A%d), -(A%d), %s; (2+)", g_cpu_ir&7, (g_cpu_ir>>9)&7, get_imm_str_u16());
}
static void d68000_pea(void)
{
sprintf(g_dasm_str, "pea %s", get_ea_mode_str_32(g_cpu_ir));
}
// this is a 68040-specific form of PFLUSH
static void d68040_pflush(void)
{
LIMIT_CPU_TYPES(M68040_PLUS);
if (g_cpu_ir & 0x10)
{
sprintf(g_dasm_str, "pflusha%s", (g_cpu_ir & 8) ? "" : "n");
}
else
{
sprintf(g_dasm_str, "pflush%s(A%d)", (g_cpu_ir & 8) ? "" : "n", g_cpu_ir & 7);
}
}
static void d68000_reset(void)
{
sprintf(g_dasm_str, "reset");
}
static void d68000_ror_s_8(void)
{
sprintf(g_dasm_str, "ror.b #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_ror_s_16(void)
{
sprintf(g_dasm_str, "ror.w #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7],g_cpu_ir&7);
}
static void d68000_ror_s_32(void)
{
sprintf(g_dasm_str, "ror.l #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_ror_r_8(void)
{
sprintf(g_dasm_str, "ror.b D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_ror_r_16(void)
{
sprintf(g_dasm_str, "ror.w D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_ror_r_32(void)
{
sprintf(g_dasm_str, "ror.l D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_ror_ea(void)
{
sprintf(g_dasm_str, "ror.w %s", get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_rol_s_8(void)
{
sprintf(g_dasm_str, "rol.b #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_rol_s_16(void)
{
sprintf(g_dasm_str, "rol.w #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_rol_s_32(void)
{
sprintf(g_dasm_str, "rol.l #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_rol_r_8(void)
{
sprintf(g_dasm_str, "rol.b D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_rol_r_16(void)
{
sprintf(g_dasm_str, "rol.w D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_rol_r_32(void)
{
sprintf(g_dasm_str, "rol.l D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_rol_ea(void)
{
sprintf(g_dasm_str, "rol.w %s", get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_roxr_s_8(void)
{
sprintf(g_dasm_str, "roxr.b #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_roxr_s_16(void)
{
sprintf(g_dasm_str, "roxr.w #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_roxr_s_32(void)
{
sprintf(g_dasm_str, "roxr.l #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_roxr_r_8(void)
{
sprintf(g_dasm_str, "roxr.b D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_roxr_r_16(void)
{
sprintf(g_dasm_str, "roxr.w D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_roxr_r_32(void)
{
sprintf(g_dasm_str, "roxr.l D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_roxr_ea(void)
{
sprintf(g_dasm_str, "roxr.w %s", get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_roxl_s_8(void)
{
sprintf(g_dasm_str, "roxl.b #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_roxl_s_16(void)
{
sprintf(g_dasm_str, "roxl.w #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_roxl_s_32(void)
{
sprintf(g_dasm_str, "roxl.l #%d, D%d", g_3bit_qdata_table[(g_cpu_ir>>9)&7], g_cpu_ir&7);
}
static void d68000_roxl_r_8(void)
{
sprintf(g_dasm_str, "roxl.b D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_roxl_r_16(void)
{
sprintf(g_dasm_str, "roxl.w D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_roxl_r_32(void)
{
sprintf(g_dasm_str, "roxl.l D%d, D%d", (g_cpu_ir>>9)&7, g_cpu_ir&7);
}
static void d68000_roxl_ea(void)
{
sprintf(g_dasm_str, "roxl.w %s", get_ea_mode_str_32(g_cpu_ir));
}
static void d68010_rtd(void)
{
LIMIT_CPU_TYPES(M68010_PLUS);
sprintf(g_dasm_str, "rtd %s; (1+)", get_imm_str_s16());
SET_OPCODE_FLAGS(DASMFLAG_STEP_OUT);
}
static void d68000_rte(void)
{
sprintf(g_dasm_str, "rte");
SET_OPCODE_FLAGS(DASMFLAG_STEP_OUT);
}
static void d68020_rtm(void)
{
LIMIT_CPU_TYPES(M68020_ONLY);
sprintf(g_dasm_str, "rtm %c%d; (2+)", BIT_3(g_cpu_ir) ? 'A' : 'D', g_cpu_ir&7);
SET_OPCODE_FLAGS(DASMFLAG_STEP_OUT);
}
static void d68000_rtr(void)
{
sprintf(g_dasm_str, "rtr");
SET_OPCODE_FLAGS(DASMFLAG_STEP_OUT);
}
static void d68000_rts(void)
{
sprintf(g_dasm_str, "rts");
SET_OPCODE_FLAGS(DASMFLAG_STEP_OUT);
}
static void d68000_sbcd_rr(void)
{
sprintf(g_dasm_str, "sbcd D%d, D%d", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_sbcd_mm(void)
{
sprintf(g_dasm_str, "sbcd -(A%d), -(A%d)", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_scc(void)
{
sprintf(g_dasm_str, "s%-2s %s", g_cc[(g_cpu_ir>>8)&0xf], get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_stop(void)
{
sprintf(g_dasm_str, "stop %s", get_imm_str_s16());
}
static void d68000_sub_er_8(void)
{
sprintf(g_dasm_str, "sub.b %s, D%d", get_ea_mode_str_8(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_sub_er_16(void)
{
sprintf(g_dasm_str, "sub.w %s, D%d", get_ea_mode_str_16(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_sub_er_32(void)
{
sprintf(g_dasm_str, "sub.l %s, D%d", get_ea_mode_str_32(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_sub_re_8(void)
{
sprintf(g_dasm_str, "sub.b D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_sub_re_16(void)
{
sprintf(g_dasm_str, "sub.w D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_sub_re_32(void)
{
sprintf(g_dasm_str, "sub.l D%d, %s", (g_cpu_ir>>9)&7, get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_suba_16(void)
{
sprintf(g_dasm_str, "suba.w %s, A%d", get_ea_mode_str_16(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_suba_32(void)
{
sprintf(g_dasm_str, "suba.l %s, A%d", get_ea_mode_str_32(g_cpu_ir), (g_cpu_ir>>9)&7);
}
static void d68000_subi_8(void)
{
char* str = get_imm_str_s8();
sprintf(g_dasm_str, "subi.b %s, %s", str, get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_subi_16(void)
{
char* str = get_imm_str_s16();
sprintf(g_dasm_str, "subi.w %s, %s", str, get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_subi_32(void)
{
char* str = get_imm_str_s32();
sprintf(g_dasm_str, "subi.l %s, %s", str, get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_subq_8(void)
{
sprintf(g_dasm_str, "subq.b #%d, %s", g_3bit_qdata_table[(g_cpu_ir>>9)&7], get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_subq_16(void)
{
sprintf(g_dasm_str, "subq.w #%d, %s", g_3bit_qdata_table[(g_cpu_ir>>9)&7], get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_subq_32(void)
{
sprintf(g_dasm_str, "subq.l #%d, %s", g_3bit_qdata_table[(g_cpu_ir>>9)&7], get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_subx_rr_8(void)
{
sprintf(g_dasm_str, "subx.b D%d, D%d", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_subx_rr_16(void)
{
sprintf(g_dasm_str, "subx.w D%d, D%d", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_subx_rr_32(void)
{
sprintf(g_dasm_str, "subx.l D%d, D%d", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_subx_mm_8(void)
{
sprintf(g_dasm_str, "subx.b -(A%d), -(A%d)", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_subx_mm_16(void)
{
sprintf(g_dasm_str, "subx.w -(A%d), -(A%d)", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_subx_mm_32(void)
{
sprintf(g_dasm_str, "subx.l -(A%d), -(A%d)", g_cpu_ir&7, (g_cpu_ir>>9)&7);
}
static void d68000_swap(void)
{
sprintf(g_dasm_str, "swap D%d", g_cpu_ir&7);
}
static void d68000_tas(void)
{
sprintf(g_dasm_str, "tas %s", get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_trap(void)
{
sprintf(g_dasm_str, "trap #$%x", g_cpu_ir&0xf);
}
static void d68020_trapcc_0(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "trap%-2s; (2+)", g_cc[(g_cpu_ir>>8)&0xf]);
SET_OPCODE_FLAGS(DASMFLAG_STEP_OVER);
}
static void d68020_trapcc_16(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "trap%-2s %s; (2+)", g_cc[(g_cpu_ir>>8)&0xf], get_imm_str_u16());
SET_OPCODE_FLAGS(DASMFLAG_STEP_OVER);
}
static void d68020_trapcc_32(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "trap%-2s %s; (2+)", g_cc[(g_cpu_ir>>8)&0xf], get_imm_str_u32());
SET_OPCODE_FLAGS(DASMFLAG_STEP_OVER);
}
static void d68000_trapv(void)
{
sprintf(g_dasm_str, "trapv");
SET_OPCODE_FLAGS(DASMFLAG_STEP_OVER);
}
static void d68000_tst_8(void)
{
sprintf(g_dasm_str, "tst.b %s", get_ea_mode_str_8(g_cpu_ir));
}
static void d68020_tst_pcdi_8(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "tst.b %s; (2+)", get_ea_mode_str_8(g_cpu_ir));
}
static void d68020_tst_pcix_8(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "tst.b %s; (2+)", get_ea_mode_str_8(g_cpu_ir));
}
static void d68020_tst_i_8(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "tst.b %s; (2+)", get_ea_mode_str_8(g_cpu_ir));
}
static void d68000_tst_16(void)
{
sprintf(g_dasm_str, "tst.w %s", get_ea_mode_str_16(g_cpu_ir));
}
static void d68020_tst_a_16(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "tst.w %s; (2+)", get_ea_mode_str_16(g_cpu_ir));
}
static void d68020_tst_pcdi_16(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "tst.w %s; (2+)", get_ea_mode_str_16(g_cpu_ir));
}
static void d68020_tst_pcix_16(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "tst.w %s; (2+)", get_ea_mode_str_16(g_cpu_ir));
}
static void d68020_tst_i_16(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "tst.w %s; (2+)", get_ea_mode_str_16(g_cpu_ir));
}
static void d68000_tst_32(void)
{
sprintf(g_dasm_str, "tst.l %s", get_ea_mode_str_32(g_cpu_ir));
}
static void d68020_tst_a_32(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "tst.l %s; (2+)", get_ea_mode_str_32(g_cpu_ir));
}
static void d68020_tst_pcdi_32(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "tst.l %s; (2+)", get_ea_mode_str_32(g_cpu_ir));
}
static void d68020_tst_pcix_32(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "tst.l %s; (2+)", get_ea_mode_str_32(g_cpu_ir));
}
static void d68020_tst_i_32(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "tst.l %s; (2+)", get_ea_mode_str_32(g_cpu_ir));
}
static void d68000_unlk(void)
{
sprintf(g_dasm_str, "unlk A%d", g_cpu_ir&7);
}
static void d68020_unpk_rr(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "unpk D%d, D%d, %s; (2+)", g_cpu_ir&7, (g_cpu_ir>>9)&7, get_imm_str_u16());
}
static void d68020_unpk_mm(void)
{
LIMIT_CPU_TYPES(M68020_PLUS);
sprintf(g_dasm_str, "unpk -(A%d), -(A%d), %s; (2+)", g_cpu_ir&7, (g_cpu_ir>>9)&7, get_imm_str_u16());
}
// PFLUSH: 001xxx0xxxxxxxxx
// PLOAD: 001000x0000xxxxx
// PVALID1: 0010100000000000
// PVALID2: 0010110000000xxx
// PMOVE 1: 010xxxx000000000
// PMOVE 2: 011xxxx0000xxx00
// PMOVE 3: 011xxxx000000000
// PTEST: 100xxxxxxxxxxxxx
// PFLUSHR: 1010000000000000
static void d68851_p000(void)
{
char* str;
uint modes = read_imm_16();
// do this after fetching the second PMOVE word so we properly get the 3rd if necessary
str = get_ea_mode_str_32(g_cpu_ir);
if ((modes & 0xfde0) == 0x2000) // PLOAD
{
if (modes & 0x0200)
{
sprintf(g_dasm_str, "pload #%d, %s", (modes>>10)&7, str);
}
else
{
sprintf(g_dasm_str, "pload %s, #%d", str, (modes>>10)&7);
}
return;
}
if ((modes & 0xe200) == 0x2000) // PFLUSH
{
sprintf(g_dasm_str, "pflushr %x, %x, %s", modes & 0x1f, (modes>>5)&0xf, str);
return;
}
if (modes == 0xa000) // PFLUSHR
{
sprintf(g_dasm_str, "pflushr %s", str);
}
if (modes == 0x2800) // PVALID (FORMAT 1)
{
sprintf(g_dasm_str, "pvalid VAL, %s", str);
return;
}
if ((modes & 0xfff8) == 0x2c00) // PVALID (FORMAT 2)
{
sprintf(g_dasm_str, "pvalid A%d, %s", modes & 0xf, str);
return;
}
if ((modes & 0xe000) == 0x8000) // PTEST
{
sprintf(g_dasm_str, "ptest #%d, %s", modes & 0x1f, str);
return;
}
switch ((modes>>13) & 0x7)
{
case 0: // MC68030/040 form with FD bit
case 2: // MC68881 form, FD never set
if (modes & 0x0100)
{
if (modes & 0x0200)
{
sprintf(g_dasm_str, "pmovefd %s, %s", g_mmuregs[(modes>>10)&7], str);
}
else
{
sprintf(g_dasm_str, "pmovefd %s, %s", str, g_mmuregs[(modes>>10)&7]);
}
}
else
{
if (modes & 0x0200)
{
sprintf(g_dasm_str, "pmove %s, %s", g_mmuregs[(modes>>10)&7], str);
}
else
{
sprintf(g_dasm_str, "pmove %s, %s", str, g_mmuregs[(modes>>10)&7]);
}
}
break;
case 3: // MC68030 to/from status reg
if (modes & 0x0200)
{
sprintf(g_dasm_str, "pmove mmusr, %s", str);
}
else
{
sprintf(g_dasm_str, "pmove %s, mmusr", str);
}
break;
default:
sprintf(g_dasm_str, "pmove [unknown form] %s", str);
break;
}
}
static void d68851_pbcc16(void)
{
uint32 temp_pc = g_cpu_pc;
sprintf(g_dasm_str, "pb%s %x", g_mmucond[g_cpu_ir&0xf], temp_pc + make_int_16(read_imm_16()));
}
static void d68851_pbcc32(void)
{
uint32 temp_pc = g_cpu_pc;
sprintf(g_dasm_str, "pb%s %x", g_mmucond[g_cpu_ir&0xf], temp_pc + make_int_32(read_imm_32()));
}
static void d68851_pdbcc(void)
{
uint32 temp_pc = g_cpu_pc;
uint16 modes = read_imm_16();
sprintf(g_dasm_str, "pb%s %x", g_mmucond[modes&0xf], temp_pc + make_int_16(read_imm_16()));
}
// PScc: 0000000000xxxxxx
static void d68851_p001(void)
{
sprintf(g_dasm_str, "MMU 001 group");
}
/* ======================================================================== */
/* ======================= INSTRUCTION TABLE BUILDER ====================== */
/* ======================================================================== */
/* EA Masks:
800 = data register direct
400 = address register direct
200 = address register indirect
100 = ARI postincrement
80 = ARI pre-decrement
40 = ARI displacement
20 = ARI index
10 = absolute short
8 = absolute long
4 = immediate / sr
2 = pc displacement
1 = pc idx
*/
static const opcode_struct g_opcode_info[] =
{
/* opcode handler mask match ea mask */
{d68000_1010 , 0xf000, 0xa000, 0x000},
{d68000_1111 , 0xf000, 0xf000, 0x000},
{d68000_abcd_rr , 0xf1f8, 0xc100, 0x000},
{d68000_abcd_mm , 0xf1f8, 0xc108, 0x000},
{d68000_add_er_8 , 0xf1c0, 0xd000, 0xbff},
{d68000_add_er_16 , 0xf1c0, 0xd040, 0xfff},
{d68000_add_er_32 , 0xf1c0, 0xd080, 0xfff},
{d68000_add_re_8 , 0xf1c0, 0xd100, 0x3f8},
{d68000_add_re_16 , 0xf1c0, 0xd140, 0x3f8},
{d68000_add_re_32 , 0xf1c0, 0xd180, 0x3f8},
{d68000_adda_16 , 0xf1c0, 0xd0c0, 0xfff},
{d68000_adda_32 , 0xf1c0, 0xd1c0, 0xfff},
{d68000_addi_8 , 0xffc0, 0x0600, 0xbf8},
{d68000_addi_16 , 0xffc0, 0x0640, 0xbf8},
{d68000_addi_32 , 0xffc0, 0x0680, 0xbf8},
{d68000_addq_8 , 0xf1c0, 0x5000, 0xbf8},
{d68000_addq_16 , 0xf1c0, 0x5040, 0xff8},
{d68000_addq_32 , 0xf1c0, 0x5080, 0xff8},
{d68000_addx_rr_8 , 0xf1f8, 0xd100, 0x000},
{d68000_addx_rr_16 , 0xf1f8, 0xd140, 0x000},
{d68000_addx_rr_32 , 0xf1f8, 0xd180, 0x000},
{d68000_addx_mm_8 , 0xf1f8, 0xd108, 0x000},
{d68000_addx_mm_16 , 0xf1f8, 0xd148, 0x000},
{d68000_addx_mm_32 , 0xf1f8, 0xd188, 0x000},
{d68000_and_er_8 , 0xf1c0, 0xc000, 0xbff},
{d68000_and_er_16 , 0xf1c0, 0xc040, 0xbff},
{d68000_and_er_32 , 0xf1c0, 0xc080, 0xbff},
{d68000_and_re_8 , 0xf1c0, 0xc100, 0x3f8},
{d68000_and_re_16 , 0xf1c0, 0xc140, 0x3f8},
{d68000_and_re_32 , 0xf1c0, 0xc180, 0x3f8},
{d68000_andi_to_ccr , 0xffff, 0x023c, 0x000},
{d68000_andi_to_sr , 0xffff, 0x027c, 0x000},
{d68000_andi_8 , 0xffc0, 0x0200, 0xbf8},
{d68000_andi_16 , 0xffc0, 0x0240, 0xbf8},
{d68000_andi_32 , 0xffc0, 0x0280, 0xbf8},
{d68000_asr_s_8 , 0xf1f8, 0xe000, 0x000},
{d68000_asr_s_16 , 0xf1f8, 0xe040, 0x000},
{d68000_asr_s_32 , 0xf1f8, 0xe080, 0x000},
{d68000_asr_r_8 , 0xf1f8, 0xe020, 0x000},
{d68000_asr_r_16 , 0xf1f8, 0xe060, 0x000},
{d68000_asr_r_32 , 0xf1f8, 0xe0a0, 0x000},
{d68000_asr_ea , 0xffc0, 0xe0c0, 0x3f8},
{d68000_asl_s_8 , 0xf1f8, 0xe100, 0x000},
{d68000_asl_s_16 , 0xf1f8, 0xe140, 0x000},
{d68000_asl_s_32 , 0xf1f8, 0xe180, 0x000},
{d68000_asl_r_8 , 0xf1f8, 0xe120, 0x000},
{d68000_asl_r_16 , 0xf1f8, 0xe160, 0x000},
{d68000_asl_r_32 , 0xf1f8, 0xe1a0, 0x000},
{d68000_asl_ea , 0xffc0, 0xe1c0, 0x3f8},
{d68000_bcc_8 , 0xf000, 0x6000, 0x000},
{d68000_bcc_16 , 0xf0ff, 0x6000, 0x000},
{d68020_bcc_32 , 0xf0ff, 0x60ff, 0x000},
{d68000_bchg_r , 0xf1c0, 0x0140, 0xbf8},
{d68000_bchg_s , 0xffc0, 0x0840, 0xbf8},
{d68000_bclr_r , 0xf1c0, 0x0180, 0xbf8},
{d68000_bclr_s , 0xffc0, 0x0880, 0xbf8},
{d68020_bfchg , 0xffc0, 0xeac0, 0xa78},
{d68020_bfclr , 0xffc0, 0xecc0, 0xa78},
{d68020_bfexts , 0xffc0, 0xebc0, 0xa7b},
{d68020_bfextu , 0xffc0, 0xe9c0, 0xa7b},
{d68020_bfffo , 0xffc0, 0xedc0, 0xa7b},
{d68020_bfins , 0xffc0, 0xefc0, 0xa78},
{d68020_bfset , 0xffc0, 0xeec0, 0xa78},
{d68020_bftst , 0xffc0, 0xe8c0, 0xa7b},
{d68010_bkpt , 0xfff8, 0x4848, 0x000},
{d68000_bra_8 , 0xff00, 0x6000, 0x000},
{d68000_bra_16 , 0xffff, 0x6000, 0x000},
{d68020_bra_32 , 0xffff, 0x60ff, 0x000},
{d68000_bset_r , 0xf1c0, 0x01c0, 0xbf8},
{d68000_bset_s , 0xffc0, 0x08c0, 0xbf8},
{d68000_bsr_8 , 0xff00, 0x6100, 0x000},
{d68000_bsr_16 , 0xffff, 0x6100, 0x000},
{d68020_bsr_32 , 0xffff, 0x61ff, 0x000},
{d68000_btst_r , 0xf1c0, 0x0100, 0xbff},
{d68000_btst_s , 0xffc0, 0x0800, 0xbfb},
{d68020_callm , 0xffc0, 0x06c0, 0x27b},
{d68020_cas_8 , 0xffc0, 0x0ac0, 0x3f8},
{d68020_cas_16 , 0xffc0, 0x0cc0, 0x3f8},
{d68020_cas_32 , 0xffc0, 0x0ec0, 0x3f8},
{d68020_cas2_16 , 0xffff, 0x0cfc, 0x000},
{d68020_cas2_32 , 0xffff, 0x0efc, 0x000},
{d68000_chk_16 , 0xf1c0, 0x4180, 0xbff},
{d68020_chk_32 , 0xf1c0, 0x4100, 0xbff},
{d68020_chk2_cmp2_8 , 0xffc0, 0x00c0, 0x27b},
{d68020_chk2_cmp2_16 , 0xffc0, 0x02c0, 0x27b},
{d68020_chk2_cmp2_32 , 0xffc0, 0x04c0, 0x27b},
{d68040_cinv , 0xff20, 0xf400, 0x000},
{d68000_clr_8 , 0xffc0, 0x4200, 0xbf8},
{d68000_clr_16 , 0xffc0, 0x4240, 0xbf8},
{d68000_clr_32 , 0xffc0, 0x4280, 0xbf8},
{d68000_cmp_8 , 0xf1c0, 0xb000, 0xbff},
{d68000_cmp_16 , 0xf1c0, 0xb040, 0xfff},
{d68000_cmp_32 , 0xf1c0, 0xb080, 0xfff},
{d68000_cmpa_16 , 0xf1c0, 0xb0c0, 0xfff},
{d68000_cmpa_32 , 0xf1c0, 0xb1c0, 0xfff},
{d68000_cmpi_8 , 0xffc0, 0x0c00, 0xbf8},
{d68020_cmpi_pcdi_8 , 0xffff, 0x0c3a, 0x000},
{d68020_cmpi_pcix_8 , 0xffff, 0x0c3b, 0x000},
{d68000_cmpi_16 , 0xffc0, 0x0c40, 0xbf8},
{d68020_cmpi_pcdi_16 , 0xffff, 0x0c7a, 0x000},
{d68020_cmpi_pcix_16 , 0xffff, 0x0c7b, 0x000},
{d68000_cmpi_32 , 0xffc0, 0x0c80, 0xbf8},
{d68020_cmpi_pcdi_32 , 0xffff, 0x0cba, 0x000},
{d68020_cmpi_pcix_32 , 0xffff, 0x0cbb, 0x000},
{d68000_cmpm_8 , 0xf1f8, 0xb108, 0x000},
{d68000_cmpm_16 , 0xf1f8, 0xb148, 0x000},
{d68000_cmpm_32 , 0xf1f8, 0xb188, 0x000},
{d68020_cpbcc_16 , 0xf1c0, 0xf080, 0x000},
{d68020_cpbcc_32 , 0xf1c0, 0xf0c0, 0x000},
{d68020_cpdbcc , 0xf1f8, 0xf048, 0x000},
{d68020_cpgen , 0xf1c0, 0xf000, 0x000},
{d68020_cprestore , 0xf1c0, 0xf140, 0x37f},
{d68020_cpsave , 0xf1c0, 0xf100, 0x2f8},
{d68020_cpscc , 0xf1c0, 0xf040, 0xbf8},
{d68020_cptrapcc_0 , 0xf1ff, 0xf07c, 0x000},
{d68020_cptrapcc_16 , 0xf1ff, 0xf07a, 0x000},
{d68020_cptrapcc_32 , 0xf1ff, 0xf07b, 0x000},
{d68040_cpush , 0xff20, 0xf420, 0x000},
{d68000_dbcc , 0xf0f8, 0x50c8, 0x000},
{d68000_dbra , 0xfff8, 0x51c8, 0x000},
{d68000_divs , 0xf1c0, 0x81c0, 0xbff},
{d68000_divu , 0xf1c0, 0x80c0, 0xbff},
{d68020_divl , 0xffc0, 0x4c40, 0xbff},
{d68000_eor_8 , 0xf1c0, 0xb100, 0xbf8},
{d68000_eor_16 , 0xf1c0, 0xb140, 0xbf8},
{d68000_eor_32 , 0xf1c0, 0xb180, 0xbf8},
{d68000_eori_to_ccr , 0xffff, 0x0a3c, 0x000},
{d68000_eori_to_sr , 0xffff, 0x0a7c, 0x000},
{d68000_eori_8 , 0xffc0, 0x0a00, 0xbf8},
{d68000_eori_16 , 0xffc0, 0x0a40, 0xbf8},
{d68000_eori_32 , 0xffc0, 0x0a80, 0xbf8},
{d68000_exg_dd , 0xf1f8, 0xc140, 0x000},
{d68000_exg_aa , 0xf1f8, 0xc148, 0x000},
{d68000_exg_da , 0xf1f8, 0xc188, 0x000},
{d68020_extb_32 , 0xfff8, 0x49c0, 0x000},
{d68000_ext_16 , 0xfff8, 0x4880, 0x000},
{d68000_ext_32 , 0xfff8, 0x48c0, 0x000},
{d68040_fpu , 0xffc0, 0xf200, 0x000},
{d68000_illegal , 0xffff, 0x4afc, 0x000},
{d68000_jmp , 0xffc0, 0x4ec0, 0x27b},
{d68000_jsr , 0xffc0, 0x4e80, 0x27b},
{d68000_lea , 0xf1c0, 0x41c0, 0x27b},
{d68000_link_16 , 0xfff8, 0x4e50, 0x000},
{d68020_link_32 , 0xfff8, 0x4808, 0x000},
{d68000_lsr_s_8 , 0xf1f8, 0xe008, 0x000},
{d68000_lsr_s_16 , 0xf1f8, 0xe048, 0x000},
{d68000_lsr_s_32 , 0xf1f8, 0xe088, 0x000},
{d68000_lsr_r_8 , 0xf1f8, 0xe028, 0x000},
{d68000_lsr_r_16 , 0xf1f8, 0xe068, 0x000},
{d68000_lsr_r_32 , 0xf1f8, 0xe0a8, 0x000},
{d68000_lsr_ea , 0xffc0, 0xe2c0, 0x3f8},
{d68000_lsl_s_8 , 0xf1f8, 0xe108, 0x000},
{d68000_lsl_s_16 , 0xf1f8, 0xe148, 0x000},
{d68000_lsl_s_32 , 0xf1f8, 0xe188, 0x000},
{d68000_lsl_r_8 , 0xf1f8, 0xe128, 0x000},
{d68000_lsl_r_16 , 0xf1f8, 0xe168, 0x000},
{d68000_lsl_r_32 , 0xf1f8, 0xe1a8, 0x000},
{d68000_lsl_ea , 0xffc0, 0xe3c0, 0x3f8},
{d68000_move_8 , 0xf000, 0x1000, 0xbff},
{d68000_move_16 , 0xf000, 0x3000, 0xfff},
{d68000_move_32 , 0xf000, 0x2000, 0xfff},
{d68000_movea_16 , 0xf1c0, 0x3040, 0xfff},
{d68000_movea_32 , 0xf1c0, 0x2040, 0xfff},
{d68000_move_to_ccr , 0xffc0, 0x44c0, 0xbff},
{d68010_move_fr_ccr , 0xffc0, 0x42c0, 0xbf8},
{d68000_move_to_sr , 0xffc0, 0x46c0, 0xbff},
{d68000_move_fr_sr , 0xffc0, 0x40c0, 0xbf8},
{d68000_move_to_usp , 0xfff8, 0x4e60, 0x000},
{d68000_move_fr_usp , 0xfff8, 0x4e68, 0x000},
{d68010_movec , 0xfffe, 0x4e7a, 0x000},
{d68000_movem_pd_16 , 0xfff8, 0x48a0, 0x000},
{d68000_movem_pd_32 , 0xfff8, 0x48e0, 0x000},
{d68000_movem_re_16 , 0xffc0, 0x4880, 0x2f8},
{d68000_movem_re_32 , 0xffc0, 0x48c0, 0x2f8},
{d68000_movem_er_16 , 0xffc0, 0x4c80, 0x37b},
{d68000_movem_er_32 , 0xffc0, 0x4cc0, 0x37b},
{d68000_movep_er_16 , 0xf1f8, 0x0108, 0x000},
{d68000_movep_er_32 , 0xf1f8, 0x0148, 0x000},
{d68000_movep_re_16 , 0xf1f8, 0x0188, 0x000},
{d68000_movep_re_32 , 0xf1f8, 0x01c8, 0x000},
{d68010_moves_8 , 0xffc0, 0x0e00, 0x3f8},
{d68010_moves_16 , 0xffc0, 0x0e40, 0x3f8},
{d68010_moves_32 , 0xffc0, 0x0e80, 0x3f8},
{d68000_moveq , 0xf100, 0x7000, 0x000},
{d68040_move16_pi_pi , 0xfff8, 0xf620, 0x000},
{d68040_move16_pi_al , 0xfff8, 0xf600, 0x000},
{d68040_move16_al_pi , 0xfff8, 0xf608, 0x000},
{d68040_move16_ai_al , 0xfff8, 0xf610, 0x000},
{d68040_move16_al_ai , 0xfff8, 0xf618, 0x000},
{d68000_muls , 0xf1c0, 0xc1c0, 0xbff},
{d68000_mulu , 0xf1c0, 0xc0c0, 0xbff},
{d68020_mull , 0xffc0, 0x4c00, 0xbff},
{d68000_nbcd , 0xffc0, 0x4800, 0xbf8},
{d68000_neg_8 , 0xffc0, 0x4400, 0xbf8},
{d68000_neg_16 , 0xffc0, 0x4440, 0xbf8},
{d68000_neg_32 , 0xffc0, 0x4480, 0xbf8},
{d68000_negx_8 , 0xffc0, 0x4000, 0xbf8},
{d68000_negx_16 , 0xffc0, 0x4040, 0xbf8},
{d68000_negx_32 , 0xffc0, 0x4080, 0xbf8},
{d68000_nop , 0xffff, 0x4e71, 0x000},
{d68000_not_8 , 0xffc0, 0x4600, 0xbf8},
{d68000_not_16 , 0xffc0, 0x4640, 0xbf8},
{d68000_not_32 , 0xffc0, 0x4680, 0xbf8},
{d68000_or_er_8 , 0xf1c0, 0x8000, 0xbff},
{d68000_or_er_16 , 0xf1c0, 0x8040, 0xbff},
{d68000_or_er_32 , 0xf1c0, 0x8080, 0xbff},
{d68000_or_re_8 , 0xf1c0, 0x8100, 0x3f8},
{d68000_or_re_16 , 0xf1c0, 0x8140, 0x3f8},
{d68000_or_re_32 , 0xf1c0, 0x8180, 0x3f8},
{d68000_ori_to_ccr , 0xffff, 0x003c, 0x000},
{d68000_ori_to_sr , 0xffff, 0x007c, 0x000},
{d68000_ori_8 , 0xffc0, 0x0000, 0xbf8},
{d68000_ori_16 , 0xffc0, 0x0040, 0xbf8},
{d68000_ori_32 , 0xffc0, 0x0080, 0xbf8},
{d68020_pack_rr , 0xf1f8, 0x8140, 0x000},
{d68020_pack_mm , 0xf1f8, 0x8148, 0x000},
{d68000_pea , 0xffc0, 0x4840, 0x27b},
{d68040_pflush , 0xffe0, 0xf500, 0x000},
{d68000_reset , 0xffff, 0x4e70, 0x000},
{d68000_ror_s_8 , 0xf1f8, 0xe018, 0x000},
{d68000_ror_s_16 , 0xf1f8, 0xe058, 0x000},
{d68000_ror_s_32 , 0xf1f8, 0xe098, 0x000},
{d68000_ror_r_8 , 0xf1f8, 0xe038, 0x000},
{d68000_ror_r_16 , 0xf1f8, 0xe078, 0x000},
{d68000_ror_r_32 , 0xf1f8, 0xe0b8, 0x000},
{d68000_ror_ea , 0xffc0, 0xe6c0, 0x3f8},
{d68000_rol_s_8 , 0xf1f8, 0xe118, 0x000},
{d68000_rol_s_16 , 0xf1f8, 0xe158, 0x000},
{d68000_rol_s_32 , 0xf1f8, 0xe198, 0x000},
{d68000_rol_r_8 , 0xf1f8, 0xe138, 0x000},
{d68000_rol_r_16 , 0xf1f8, 0xe178, 0x000},
{d68000_rol_r_32 , 0xf1f8, 0xe1b8, 0x000},
{d68000_rol_ea , 0xffc0, 0xe7c0, 0x3f8},
{d68000_roxr_s_8 , 0xf1f8, 0xe010, 0x000},
{d68000_roxr_s_16 , 0xf1f8, 0xe050, 0x000},
{d68000_roxr_s_32 , 0xf1f8, 0xe090, 0x000},
{d68000_roxr_r_8 , 0xf1f8, 0xe030, 0x000},
{d68000_roxr_r_16 , 0xf1f8, 0xe070, 0x000},
{d68000_roxr_r_32 , 0xf1f8, 0xe0b0, 0x000},
{d68000_roxr_ea , 0xffc0, 0xe4c0, 0x3f8},
{d68000_roxl_s_8 , 0xf1f8, 0xe110, 0x000},
{d68000_roxl_s_16 , 0xf1f8, 0xe150, 0x000},
{d68000_roxl_s_32 , 0xf1f8, 0xe190, 0x000},
{d68000_roxl_r_8 , 0xf1f8, 0xe130, 0x000},
{d68000_roxl_r_16 , 0xf1f8, 0xe170, 0x000},
{d68000_roxl_r_32 , 0xf1f8, 0xe1b0, 0x000},
{d68000_roxl_ea , 0xffc0, 0xe5c0, 0x3f8},
{d68010_rtd , 0xffff, 0x4e74, 0x000},
{d68000_rte , 0xffff, 0x4e73, 0x000},
{d68020_rtm , 0xfff0, 0x06c0, 0x000},
{d68000_rtr , 0xffff, 0x4e77, 0x000},
{d68000_rts , 0xffff, 0x4e75, 0x000},
{d68000_sbcd_rr , 0xf1f8, 0x8100, 0x000},
{d68000_sbcd_mm , 0xf1f8, 0x8108, 0x000},
{d68000_scc , 0xf0c0, 0x50c0, 0xbf8},
{d68000_stop , 0xffff, 0x4e72, 0x000},
{d68000_sub_er_8 , 0xf1c0, 0x9000, 0xbff},
{d68000_sub_er_16 , 0xf1c0, 0x9040, 0xfff},
{d68000_sub_er_32 , 0xf1c0, 0x9080, 0xfff},
{d68000_sub_re_8 , 0xf1c0, 0x9100, 0x3f8},
{d68000_sub_re_16 , 0xf1c0, 0x9140, 0x3f8},
{d68000_sub_re_32 , 0xf1c0, 0x9180, 0x3f8},
{d68000_suba_16 , 0xf1c0, 0x90c0, 0xfff},
{d68000_suba_32 , 0xf1c0, 0x91c0, 0xfff},
{d68000_subi_8 , 0xffc0, 0x0400, 0xbf8},
{d68000_subi_16 , 0xffc0, 0x0440, 0xbf8},
{d68000_subi_32 , 0xffc0, 0x0480, 0xbf8},
{d68000_subq_8 , 0xf1c0, 0x5100, 0xbf8},
{d68000_subq_16 , 0xf1c0, 0x5140, 0xff8},
{d68000_subq_32 , 0xf1c0, 0x5180, 0xff8},
{d68000_subx_rr_8 , 0xf1f8, 0x9100, 0x000},
{d68000_subx_rr_16 , 0xf1f8, 0x9140, 0x000},
{d68000_subx_rr_32 , 0xf1f8, 0x9180, 0x000},
{d68000_subx_mm_8 , 0xf1f8, 0x9108, 0x000},
{d68000_subx_mm_16 , 0xf1f8, 0x9148, 0x000},
{d68000_subx_mm_32 , 0xf1f8, 0x9188, 0x000},
{d68000_swap , 0xfff8, 0x4840, 0x000},
{d68000_tas , 0xffc0, 0x4ac0, 0xbf8},
{d68000_trap , 0xfff0, 0x4e40, 0x000},
{d68020_trapcc_0 , 0xf0ff, 0x50fc, 0x000},
{d68020_trapcc_16 , 0xf0ff, 0x50fa, 0x000},
{d68020_trapcc_32 , 0xf0ff, 0x50fb, 0x000},
{d68000_trapv , 0xffff, 0x4e76, 0x000},
{d68000_tst_8 , 0xffc0, 0x4a00, 0xbf8},
{d68020_tst_pcdi_8 , 0xffff, 0x4a3a, 0x000},
{d68020_tst_pcix_8 , 0xffff, 0x4a3b, 0x000},
{d68020_tst_i_8 , 0xffff, 0x4a3c, 0x000},
{d68000_tst_16 , 0xffc0, 0x4a40, 0xbf8},
{d68020_tst_a_16 , 0xfff8, 0x4a48, 0x000},
{d68020_tst_pcdi_16 , 0xffff, 0x4a7a, 0x000},
{d68020_tst_pcix_16 , 0xffff, 0x4a7b, 0x000},
{d68020_tst_i_16 , 0xffff, 0x4a7c, 0x000},
{d68000_tst_32 , 0xffc0, 0x4a80, 0xbf8},
{d68020_tst_a_32 , 0xfff8, 0x4a88, 0x000},
{d68020_tst_pcdi_32 , 0xffff, 0x4aba, 0x000},
{d68020_tst_pcix_32 , 0xffff, 0x4abb, 0x000},
{d68020_tst_i_32 , 0xffff, 0x4abc, 0x000},
{d68000_unlk , 0xfff8, 0x4e58, 0x000},
{d68020_unpk_rr , 0xf1f8, 0x8180, 0x000},
{d68020_unpk_mm , 0xf1f8, 0x8188, 0x000},
{d68851_p000 , 0xffc0, 0xf000, 0x000},
{d68851_pbcc16 , 0xffc0, 0xf080, 0x000},
{d68851_pbcc32 , 0xffc0, 0xf0c0, 0x000},
{d68851_pdbcc , 0xfff8, 0xf048, 0x000},
{d68851_p001 , 0xffc0, 0xf040, 0x000},
{0, 0, 0, 0}
};
/* Check if opcode is using a valid ea mode */
static int valid_ea(uint opcode, uint mask)
{
if(mask == 0)
return 1;
switch(opcode & 0x3f)
{
case 0x00: case 0x01: case 0x02: case 0x03:
case 0x04: case 0x05: case 0x06: case 0x07:
return (mask & 0x800) != 0;
case 0x08: case 0x09: case 0x0a: case 0x0b:
case 0x0c: case 0x0d: case 0x0e: case 0x0f:
return (mask & 0x400) != 0;
case 0x10: case 0x11: case 0x12: case 0x13:
case 0x14: case 0x15: case 0x16: case 0x17:
return (mask & 0x200) != 0;
case 0x18: case 0x19: case 0x1a: case 0x1b:
case 0x1c: case 0x1d: case 0x1e: case 0x1f:
return (mask & 0x100) != 0;
case 0x20: case 0x21: case 0x22: case 0x23:
case 0x24: case 0x25: case 0x26: case 0x27:
return (mask & 0x080) != 0;
case 0x28: case 0x29: case 0x2a: case 0x2b:
case 0x2c: case 0x2d: case 0x2e: case 0x2f:
return (mask & 0x040) != 0;
case 0x30: case 0x31: case 0x32: case 0x33:
case 0x34: case 0x35: case 0x36: case 0x37:
return (mask & 0x020) != 0;
case 0x38:
return (mask & 0x010) != 0;
case 0x39:
return (mask & 0x008) != 0;
case 0x3a:
return (mask & 0x002) != 0;
case 0x3b:
return (mask & 0x001) != 0;
case 0x3c:
return (mask & 0x004) != 0;
}
return 0;
}
/* Used by qsort */
static int DECL_SPEC compare_nof_true_bits(const void *aptr, const void *bptr)
{
uint a = ((const opcode_struct*)aptr)->mask;
uint b = ((const opcode_struct*)bptr)->mask;
a = ((a & 0xAAAA) >> 1) + (a & 0x5555);
a = ((a & 0xCCCC) >> 2) + (a & 0x3333);
a = ((a & 0xF0F0) >> 4) + (a & 0x0F0F);
a = ((a & 0xFF00) >> 8) + (a & 0x00FF);
b = ((b & 0xAAAA) >> 1) + (b & 0x5555);
b = ((b & 0xCCCC) >> 2) + (b & 0x3333);
b = ((b & 0xF0F0) >> 4) + (b & 0x0F0F);
b = ((b & 0xFF00) >> 8) + (b & 0x00FF);
return b - a; /* reversed to get greatest to least sorting */
}
/* build the opcode handler jump table */
static void build_opcode_table(void)
{
uint i;
uint opcode;
opcode_struct* ostruct;
opcode_struct opcode_info[ARRAY_LENGTH(g_opcode_info)];
memcpy(opcode_info, g_opcode_info, sizeof(g_opcode_info));
qsort((void *)opcode_info, ARRAY_LENGTH(opcode_info)-1, sizeof(opcode_info[0]), compare_nof_true_bits);
for(i=0;i<0x10000;i++)
{
g_instruction_table[i] = d68000_illegal; /* default to illegal */
opcode = i;
/* search through opcode info for a match */
for(ostruct = opcode_info;ostruct->opcode_handler != 0;ostruct++)
{
/* match opcode mask and allowed ea modes */
if((opcode & ostruct->mask) == ostruct->match)
{
/* Handle destination ea for move instructions */
if((ostruct->opcode_handler == d68000_move_8 ||
ostruct->opcode_handler == d68000_move_16 ||
ostruct->opcode_handler == d68000_move_32) &&
!valid_ea(((opcode>>9)&7) | ((opcode>>3)&0x38), 0xbf8))
continue;
if(valid_ea(opcode, ostruct->ea_mask))
{
g_instruction_table[i] = ostruct->opcode_handler;
break;
}
}
}
}
}
/* ======================================================================== */
/* ================================= API ================================== */
/* ======================================================================== */
/* Disasemble one instruction at pc and store in str_buff */
unsigned int m68k_disassemble(char* str_buff, unsigned int pc, unsigned int cpu_type)
{
if(!g_initialized)
{
build_opcode_table();
g_initialized = 1;
}
switch(cpu_type)
{
case M68K_CPU_TYPE_68000:
g_cpu_type = TYPE_68000;
g_address_mask = 0x00ffffff;
break;
case M68K_CPU_TYPE_68010:
g_cpu_type = TYPE_68010;
g_address_mask = 0x00ffffff;
break;
case M68K_CPU_TYPE_68EC020:
g_cpu_type = TYPE_68020;
g_address_mask = 0x00ffffff;
break;
case M68K_CPU_TYPE_68020:
g_cpu_type = TYPE_68020;
g_address_mask = 0xffffffff;
break;
case M68K_CPU_TYPE_68EC030:
case M68K_CPU_TYPE_68030:
g_cpu_type = TYPE_68030;
g_address_mask = 0xffffffff;
break;
case M68K_CPU_TYPE_68040:
case M68K_CPU_TYPE_68EC040:
case M68K_CPU_TYPE_68LC040:
g_cpu_type = TYPE_68040;
g_address_mask = 0xffffffff;
break;
default:
return 0;
}
g_cpu_pc = pc;
g_helper_str[0] = 0;
g_cpu_ir = read_imm_16();
g_opcode_type = 0;
g_instruction_table[g_cpu_ir]();
sprintf(str_buff, "%s%s", g_dasm_str, g_helper_str);
return COMBINE_OPCODE_FLAGS(g_cpu_pc - pc);
}
char* m68ki_disassemble_quick(unsigned int pc, unsigned int cpu_type)
{
static char buff[1000];
buff[0] = 0;
m68k_disassemble(buff, pc, cpu_type);
return buff;
}
unsigned int m68k_disassemble_raw(char* str_buff, unsigned int pc, const unsigned char* opdata, const unsigned char* argdata, unsigned int cpu_type)
{
unsigned int result;
(void)argdata;
g_rawop = opdata;
g_rawbasepc = pc;
result = m68k_disassemble(str_buff, pc, cpu_type);
g_rawop = NULL;
return result;
}
/* Check if the instruction is a valid one */
unsigned int m68k_is_valid_instruction(unsigned int instruction, unsigned int cpu_type)
{
if(!g_initialized)
{
build_opcode_table();
g_initialized = 1;
}
instruction &= 0xffff;
if(g_instruction_table[instruction] == d68000_illegal)
return 0;
switch(cpu_type)
{
case M68K_CPU_TYPE_68000:
if(g_instruction_table[instruction] == d68010_bkpt)
return 0;
if(g_instruction_table[instruction] == d68010_move_fr_ccr)
return 0;
if(g_instruction_table[instruction] == d68010_movec)
return 0;
if(g_instruction_table[instruction] == d68010_moves_8)
return 0;
if(g_instruction_table[instruction] == d68010_moves_16)
return 0;
if(g_instruction_table[instruction] == d68010_moves_32)
return 0;
if(g_instruction_table[instruction] == d68010_rtd)
return 0;
// Fallthrough
case M68K_CPU_TYPE_68010:
if(g_instruction_table[instruction] == d68020_bcc_32)
return 0;
if(g_instruction_table[instruction] == d68020_bfchg)
return 0;
if(g_instruction_table[instruction] == d68020_bfclr)
return 0;
if(g_instruction_table[instruction] == d68020_bfexts)
return 0;
if(g_instruction_table[instruction] == d68020_bfextu)
return 0;
if(g_instruction_table[instruction] == d68020_bfffo)
return 0;
if(g_instruction_table[instruction] == d68020_bfins)
return 0;
if(g_instruction_table[instruction] == d68020_bfset)
return 0;
if(g_instruction_table[instruction] == d68020_bftst)
return 0;
if(g_instruction_table[instruction] == d68020_bra_32)
return 0;
if(g_instruction_table[instruction] == d68020_bsr_32)
return 0;
if(g_instruction_table[instruction] == d68020_callm)
return 0;
if(g_instruction_table[instruction] == d68020_cas_8)
return 0;
if(g_instruction_table[instruction] == d68020_cas_16)
return 0;
if(g_instruction_table[instruction] == d68020_cas_32)
return 0;
if(g_instruction_table[instruction] == d68020_cas2_16)
return 0;
if(g_instruction_table[instruction] == d68020_cas2_32)
return 0;
if(g_instruction_table[instruction] == d68020_chk_32)
return 0;
if(g_instruction_table[instruction] == d68020_chk2_cmp2_8)
return 0;
if(g_instruction_table[instruction] == d68020_chk2_cmp2_16)
return 0;
if(g_instruction_table[instruction] == d68020_chk2_cmp2_32)
return 0;
if(g_instruction_table[instruction] == d68020_cmpi_pcdi_8)
return 0;
if(g_instruction_table[instruction] == d68020_cmpi_pcix_8)
return 0;
if(g_instruction_table[instruction] == d68020_cmpi_pcdi_16)
return 0;
if(g_instruction_table[instruction] == d68020_cmpi_pcix_16)
return 0;
if(g_instruction_table[instruction] == d68020_cmpi_pcdi_32)
return 0;
if(g_instruction_table[instruction] == d68020_cmpi_pcix_32)
return 0;
if(g_instruction_table[instruction] == d68020_cpbcc_16)
return 0;
if(g_instruction_table[instruction] == d68020_cpbcc_32)
return 0;
if(g_instruction_table[instruction] == d68020_cpdbcc)
return 0;
if(g_instruction_table[instruction] == d68020_cpgen)
return 0;
if(g_instruction_table[instruction] == d68020_cprestore)
return 0;
if(g_instruction_table[instruction] == d68020_cpsave)
return 0;
if(g_instruction_table[instruction] == d68020_cpscc)
return 0;
if(g_instruction_table[instruction] == d68020_cptrapcc_0)
return 0;
if(g_instruction_table[instruction] == d68020_cptrapcc_16)
return 0;
if(g_instruction_table[instruction] == d68020_cptrapcc_32)
return 0;
if(g_instruction_table[instruction] == d68020_divl)
return 0;
if(g_instruction_table[instruction] == d68020_extb_32)
return 0;
if(g_instruction_table[instruction] == d68020_link_32)
return 0;
if(g_instruction_table[instruction] == d68020_mull)
return 0;
if(g_instruction_table[instruction] == d68020_pack_rr)
return 0;
if(g_instruction_table[instruction] == d68020_pack_mm)
return 0;
if(g_instruction_table[instruction] == d68020_rtm)
return 0;
if(g_instruction_table[instruction] == d68020_trapcc_0)
return 0;
if(g_instruction_table[instruction] == d68020_trapcc_16)
return 0;
if(g_instruction_table[instruction] == d68020_trapcc_32)
return 0;
if(g_instruction_table[instruction] == d68020_tst_pcdi_8)
return 0;
if(g_instruction_table[instruction] == d68020_tst_pcix_8)
return 0;
if(g_instruction_table[instruction] == d68020_tst_i_8)
return 0;
if(g_instruction_table[instruction] == d68020_tst_a_16)
return 0;
if(g_instruction_table[instruction] == d68020_tst_pcdi_16)
return 0;
if(g_instruction_table[instruction] == d68020_tst_pcix_16)
return 0;
if(g_instruction_table[instruction] == d68020_tst_i_16)
return 0;
if(g_instruction_table[instruction] == d68020_tst_a_32)
return 0;
if(g_instruction_table[instruction] == d68020_tst_pcdi_32)
return 0;
if(g_instruction_table[instruction] == d68020_tst_pcix_32)
return 0;
if(g_instruction_table[instruction] == d68020_tst_i_32)
return 0;
if(g_instruction_table[instruction] == d68020_unpk_rr)
return 0;
if(g_instruction_table[instruction] == d68020_unpk_mm)
return 0;
// Fallthrough
case M68K_CPU_TYPE_68EC020:
case M68K_CPU_TYPE_68020:
case M68K_CPU_TYPE_68030:
case M68K_CPU_TYPE_68EC030:
if(g_instruction_table[instruction] == d68040_cinv)
return 0;
if(g_instruction_table[instruction] == d68040_cpush)
return 0;
if(g_instruction_table[instruction] == d68040_move16_pi_pi)
return 0;
if(g_instruction_table[instruction] == d68040_move16_pi_al)
return 0;
if(g_instruction_table[instruction] == d68040_move16_al_pi)
return 0;
if(g_instruction_table[instruction] == d68040_move16_ai_al)
return 0;
if(g_instruction_table[instruction] == d68040_move16_al_ai)
return 0;
// Fallthrough
case M68K_CPU_TYPE_68040:
case M68K_CPU_TYPE_68EC040:
case M68K_CPU_TYPE_68LC040:
if(g_instruction_table[instruction] == d68020_cpbcc_16)
return 0;
if(g_instruction_table[instruction] == d68020_cpbcc_32)
return 0;
if(g_instruction_table[instruction] == d68020_cpdbcc)
return 0;
if(g_instruction_table[instruction] == d68020_cpgen)
return 0;
if(g_instruction_table[instruction] == d68020_cprestore)
return 0;
if(g_instruction_table[instruction] == d68020_cpsave)
return 0;
if(g_instruction_table[instruction] == d68020_cpscc)
return 0;
if(g_instruction_table[instruction] == d68020_cptrapcc_0)
return 0;
if(g_instruction_table[instruction] == d68020_cptrapcc_16)
return 0;
if(g_instruction_table[instruction] == d68020_cptrapcc_32)
return 0;
if(g_instruction_table[instruction] == d68040_pflush)
return 0;
}
if(cpu_type != M68K_CPU_TYPE_68020 && cpu_type != M68K_CPU_TYPE_68EC020 &&
(g_instruction_table[instruction] == d68020_callm ||
g_instruction_table[instruction] == d68020_rtm))
return 0;
return 1;
}
// f028 2215 0008
/* ======================================================================== */
/* ============================== END OF FILE ============================= */
/* ======================================================================== */
|
ab8c5614024f9fbfad9ee744894d351f22773aba
|
971b2cea2d1c3001aadc8ca1a48110b7db1ed5f2
|
/deps/abc/src/misc/extra/extraUtilFile.c
|
54e6efc25964260dd8d61562f0b80619d0e47a41
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"MIT-Modern-Variant"
] |
permissive
|
emsec/hal
|
70ad2921739967d914dd458984bd7d6d497d3b0a
|
e4fae37bec9168a61100eacfda37a1f291b4d0be
|
refs/heads/master
| 2023-09-02T20:27:32.909426
| 2023-09-01T13:03:24
| 2023-09-01T13:03:24
| 169,076,171
| 510
| 72
|
MIT
| 2023-09-01T13:03:26
| 2019-02-04T12:37:20
|
C++
|
UTF-8
|
C
| false
| false
| 25,920
|
c
|
extraUtilFile.c
|
/**CFile****************************************************************
FileName [extraUtilFile.c]
SystemName [ABC: Logic synthesis and verification system.]
PackageName [extra]
Synopsis [File management utilities.]
Author [Alan Mishchenko]
Affiliation [UC Berkeley]
Date [Ver. 1.0. Started - June 20, 2005.]
Revision [$Id: extraUtilFile.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $]
***********************************************************************/
#include "extra.h"
ABC_NAMESPACE_IMPL_START
/*---------------------------------------------------------------------------*/
/* Constant declarations */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/* Stucture declarations */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/* Type declarations */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/* Variable declarations */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/* Macro declarations */
/*---------------------------------------------------------------------------*/
/**AutomaticStart*************************************************************/
/*---------------------------------------------------------------------------*/
/* Static function prototypes */
/*---------------------------------------------------------------------------*/
/**AutomaticEnd***************************************************************/
/*---------------------------------------------------------------------------*/
/* Definition of exported functions */
/*---------------------------------------------------------------------------*/
/**Function*************************************************************
Synopsis [Tries to find a file name with a different extension.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
char * Extra_FileGetSimilarName( char * pFileNameWrong, char * pS1, char * pS2, char * pS3, char * pS4, char * pS5 )
{
FILE * pFile;
char * pFileNameOther;
char * pFileGen;
if ( pS1 == NULL )
return NULL;
// get the generic file name
pFileGen = Extra_FileNameGeneric( pFileNameWrong );
pFileNameOther = Extra_FileNameAppend( pFileGen, pS1 );
pFile = fopen( pFileNameOther, "r" );
if ( pFile == NULL && pS2 )
{ // try one more
pFileNameOther = Extra_FileNameAppend( pFileGen, pS2 );
pFile = fopen( pFileNameOther, "r" );
if ( pFile == NULL && pS3 )
{ // try one more
pFileNameOther = Extra_FileNameAppend( pFileGen, pS3 );
pFile = fopen( pFileNameOther, "r" );
if ( pFile == NULL && pS4 )
{ // try one more
pFileNameOther = Extra_FileNameAppend( pFileGen, pS4 );
pFile = fopen( pFileNameOther, "r" );
if ( pFile == NULL && pS5 )
{ // try one more
pFileNameOther = Extra_FileNameAppend( pFileGen, pS5 );
pFile = fopen( pFileNameOther, "r" );
}
}
}
}
ABC_FREE( pFileGen );
if ( pFile )
{
fclose( pFile );
return pFileNameOther;
}
// did not find :(
return NULL;
}
/**Function*************************************************************
Synopsis [Returns the pointer to the file extension.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
char * Extra_FileNameExtension( char * FileName )
{
char * pDot;
// find the last "dot" in the file name, if it is present
for ( pDot = FileName + strlen(FileName)-1; pDot >= FileName; pDot-- )
if ( *pDot == '.' )
return pDot + 1;
return FileName;
}
/**Function*************************************************************
Synopsis [Returns the composite name of the file.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
char * Extra_FileNameAppend( char * pBase, char * pSuffix )
{
static char Buffer[500];
assert( strlen(pBase) + strlen(pSuffix) < 500 );
sprintf( Buffer, "%s%s", pBase, pSuffix );
return Buffer;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
char * Extra_FileNameGeneric( char * FileName )
{
char * pDot, * pRes;
pRes = Extra_UtilStrsav( FileName );
if ( (pDot = strrchr( pRes, '.' )) )
*pDot = 0;
return pRes;
}
/**Function*************************************************************
Synopsis [Returns the composite name of the file.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
char * Extra_FileNameGenericAppend( char * pBase, char * pSuffix )
{
static char Buffer[1000];
char * pDot;
assert( strlen(pBase) + strlen(pSuffix) < 1000 );
strcpy( Buffer, pBase );
if ( (pDot = strrchr( Buffer, '.' )) )
*pDot = 0;
strcat( Buffer, pSuffix );
return Buffer;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Extra_FileNameCorrectPath( char * FileName )
{
char * pStart;
if ( FileName )
for ( pStart = FileName; *pStart; pStart++ )
if ( *pStart == '>' || *pStart == '\\' )
*pStart = '/';
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
char * Extra_FileNameWithoutPath( char * FileName )
{
char * pRes;
for ( pRes = FileName + strlen(FileName) - 1; pRes >= FileName; pRes-- )
if ( *pRes == '\\' || *pRes == '/' )
return pRes + 1;
return FileName;
}
char * Extra_FilePathWithoutName( char * FileName )
{
char * pRes;
FileName = Abc_UtilStrsav( FileName );
for ( pRes = FileName + strlen(FileName) - 1; pRes >= FileName; pRes-- )
if ( *pRes == '\\' || *pRes == '/' )
{
pRes[1] = '\0';
Extra_FileNameCorrectPath( FileName );
return FileName;
}
ABC_FREE( FileName );
return NULL;
}
char * Extra_FileInTheSameDir( char * pPathFile, char * pFileName )
{
static char pBuffer[1000]; char * pThis;
assert( strlen(pPathFile) + strlen(pFileName) < 990 );
memmove( pBuffer, pPathFile, strlen(pPathFile) );
for ( pThis = pBuffer + strlen(pPathFile) - 1; pThis >= pBuffer; pThis-- )
if ( *pThis == '\\' || *pThis == '/' )
break;
memmove( ++pThis, pFileName, strlen(pFileName) );
pThis[strlen(pFileName)] = '\0';
return pBuffer;
}
char * Extra_FileDesignName( char * pFileName )
{
char * pBeg, * pEnd, * pStore, * pCur;
// find the first dot
for ( pEnd = pFileName; *pEnd; pEnd++ )
if ( *pEnd == '.' )
break;
// find the first char
for ( pBeg = pEnd - 1; pBeg >= pFileName; pBeg-- )
if ( !((*pBeg >= 'a' && *pBeg <= 'z') || (*pBeg >= 'A' && *pBeg <= 'Z') || (*pBeg >= '0' && *pBeg <= '9') || *pBeg == '_') )
break;
pBeg++;
// fill up storage
pStore = ABC_ALLOC( char, pEnd - pBeg + 1 );
for ( pCur = pStore; pBeg < pEnd; pBeg++, pCur++ )
*pCur = *pBeg;
*pCur = 0;
return pStore;
}
/**Function*************************************************************
Synopsis [Returns the file size.]
Description [The file should be closed.]
SideEffects []
SeeAlso []
***********************************************************************/
int Extra_FileCheck( char * pFileName )
{
FILE * pFile;
pFile = fopen( pFileName, "rb" );
if ( pFile == NULL )
{
printf( "Extra_FileCheck(): File \"%s\" does not exist.\n", pFileName );
return 0;
}
fseek( pFile, 0, SEEK_END );
if ( ftell( pFile ) == 0 )
printf( "Extra_FileCheck(): File \"%s\" is empty.\n", pFileName );
fclose( pFile );
return 1;
}
/**Function*************************************************************
Synopsis [Returns the file size.]
Description [The file should be closed.]
SideEffects []
SeeAlso []
***********************************************************************/
int Extra_FileSize( char * pFileName )
{
FILE * pFile;
int nFileSize;
pFile = fopen( pFileName, "rb" );
if ( pFile == NULL )
{
printf( "Extra_FileSize(): The file is unavailable (absent or open).\n" );
return 0;
}
fseek( pFile, 0, SEEK_END );
nFileSize = ftell( pFile );
fclose( pFile );
return nFileSize;
}
/**Function*************************************************************
Synopsis [Read the file into the internal buffer.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
char * Extra_FileRead( FILE * pFile )
{
int nFileSize;
char * pBuffer;
int RetValue;
// get the file size, in bytes
fseek( pFile, 0, SEEK_END );
nFileSize = ftell( pFile );
// move the file current reading position to the beginning
rewind( pFile );
// load the contents of the file into memory
pBuffer = ABC_ALLOC( char, nFileSize + 3 );
RetValue = fread( pBuffer, nFileSize, 1, pFile );
// terminate the string with '\0'
pBuffer[ nFileSize + 0] = '\n';
pBuffer[ nFileSize + 1] = '\0';
return pBuffer;
}
char * Extra_FileRead2( FILE * pFile, FILE * pFile2 )
{
char * pBuffer;
int nSize, nSize2;
int RetValue;
// get the file size, in bytes
fseek( pFile, 0, SEEK_END );
nSize = ftell( pFile );
rewind( pFile );
// get the file size, in bytes
fseek( pFile2, 0, SEEK_END );
nSize2 = ftell( pFile2 );
rewind( pFile2 );
// load the contents of the file into memory
pBuffer = ABC_ALLOC( char, nSize + nSize2 + 3 );
RetValue = fread( pBuffer, nSize, 1, pFile );
RetValue = fread( pBuffer + nSize, nSize2, 1, pFile2 );
// terminate the string with '\0'
pBuffer[ nSize + nSize2 + 0] = '\n';
pBuffer[ nSize + nSize2 + 1] = '\0';
return pBuffer;
}
/**Function*************************************************************
Synopsis [Read the file into the internal buffer.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
char * Extra_FileReadContents( char * pFileName )
{
FILE * pFile;
char * pBuffer;
pFile = fopen( pFileName, "rb" );
pBuffer = pFile ? Extra_FileRead( pFile ) : NULL;
if ( pFile ) fclose( pFile );
return pBuffer;
}
char * Extra_FileReadContents2( char * pFileName, char * pFileName2 )
{
FILE * pFile, * pFile2;
char * pBuffer;
pFile = fopen( pFileName, "rb" );
pFile2 = fopen( pFileName2, "rb" );
pBuffer = (pFile && pFile2) ? Extra_FileRead2( pFile, pFile2 ) : NULL;
if ( pFile ) fclose( pFile );
if ( pFile2 ) fclose( pFile2 );
return pBuffer;
}
/**Function*************************************************************
Synopsis [Returns one if the file has a given extension.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Extra_FileIsType( char * pFileName, char * pS1, char * pS2, char * pS3 )
{
int lenS, lenF = strlen(pFileName);
lenS = pS1 ? strlen(pS1) : 0;
if ( lenS && lenF > lenS && !strncmp( pFileName+lenF-lenS, pS1, lenS ) )
return 1;
lenS = pS2 ? strlen(pS2) : 0;
if ( lenS && lenF > lenS && !strncmp( pFileName+lenF-lenS, pS2, lenS ) )
return 1;
lenS = pS3 ? strlen(pS3) : 0;
if ( lenS && lenF > lenS && !strncmp( pFileName+lenF-lenS, pS3, lenS ) )
return 1;
return 0;
}
/**Function*************************************************************
Synopsis [Returns the time stamp.]
Description [The file should be closed.]
SideEffects []
SeeAlso []
***********************************************************************/
char * Extra_TimeStamp()
{
static char Buffer[100];
char * TimeStamp;
time_t ltime;
// get the current time
time( <ime );
TimeStamp = asctime( localtime( <ime ) );
TimeStamp[ strlen(TimeStamp) - 1 ] = 0;
strcpy( Buffer, TimeStamp );
return Buffer;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
unsigned Extra_ReadBinary( char * Buffer )
{
unsigned Result;
int i;
Result = 0;
for ( i = 0; Buffer[i]; i++ )
if ( Buffer[i] == '0' || Buffer[i] == '1' )
Result = Result * 2 + Buffer[i] - '0';
else
{
assert( 0 );
}
return Result;
}
/**Function*************************************************************
Synopsis [Prints the bit string.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Extra_PrintBinary( FILE * pFile, unsigned Sign[], int nBits )
{
int i;
for ( i = nBits-1; i >= 0; i-- )
fprintf( pFile, "%c", '0' + Abc_InfoHasBit(Sign, i) );
// fprintf( pFile, "\n" );
}
void Extra_PrintBinary2( FILE * pFile, unsigned Sign[], int nBits )
{
int i;
for ( i = 0; i < nBits; i++ )
fprintf( pFile, "%c", '0' + Abc_InfoHasBit(Sign, i) );
// fprintf( pFile, "\n" );
}
/**Function*************************************************************
Synopsis [Reads the hex unsigned into the bit-string.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Extra_ReadHex( unsigned Sign[], char * pString, int nDigits )
{
int Digit, k, c;
for ( k = 0; k < nDigits; k++ )
{
c = nDigits-1-k;
if ( pString[c] >= '0' && pString[c] <= '9' )
Digit = pString[c] - '0';
else if ( pString[c] >= 'A' && pString[c] <= 'F' )
Digit = pString[c] - 'A' + 10;
else if ( pString[c] >= 'a' && pString[c] <= 'f' )
Digit = pString[c] - 'a' + 10;
else { assert( 0 ); return 0; }
Sign[k/8] |= ( (Digit & 15) << ((k%8) * 4) );
}
return 1;
}
int Extra_ReadHexadecimal( unsigned Sign[], char * pString, int nVars )
{
int nWords, nDigits, k;
nWords = Extra_TruthWordNum( nVars );
for ( k = 0; k < nWords; k++ )
Sign[k] = 0;
// read the number from the string
nDigits = (1 << nVars) / 4;
if ( nDigits == 0 )
nDigits = 1;
Extra_ReadHex( Sign, pString, nDigits );
return 1;
}
/**Function*************************************************************
Synopsis [Prints the hex unsigned into a file.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Extra_PrintHexadecimal( FILE * pFile, unsigned Sign[], int nVars )
{
int nDigits, Digit, k;
// write the number into the file
nDigits = (1 << nVars) / 4;
for ( k = nDigits - 1; k >= 0; k-- )
{
Digit = ((Sign[k/8] >> ((k%8) * 4)) & 15);
if ( Digit < 10 )
fprintf( pFile, "%d", Digit );
else
fprintf( pFile, "%c", 'a' + Digit-10 );
}
// fprintf( pFile, "\n" );
}
/**Function*************************************************************
Synopsis [Prints the hex unsigned into a file.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Extra_PrintHexadecimalString( char * pString, unsigned Sign[], int nVars )
{
int nDigits, Digit, k;
if ( nVars == 0 && !(Sign[0] & 1) ) { sprintf(pString, "0"); return; } // const0
if ( nVars == 0 && (Sign[0] & 1) ) { sprintf(pString, "1"); return; } // const1
if ( nVars == 1 && (Sign[0] & 1) ) { sprintf(pString, "1"); return; } // inverter
if ( nVars == 1 && !(Sign[0] & 1) ) { sprintf(pString, "2"); return; } // buffer
// write the number into the file
nDigits = (1 << nVars) / 4;
for ( k = nDigits - 1; k >= 0; k-- )
{
Digit = ((Sign[k/8] >> ((k%8) * 4)) & 15);
if ( Digit < 10 )
*pString++ = '0' + Digit;
else
*pString++ = 'a' + Digit-10;
}
// fprintf( pFile, "\n" );
*pString = 0;
}
/**Function*************************************************************
Synopsis [Prints the hex unsigned into a file.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Extra_PrintHex( FILE * pFile, unsigned * pTruth, int nVars )
{
int nMints, nDigits, Digit, k;
// write the number into the file
fprintf( pFile, "0x" );
nMints = (1 << nVars);
nDigits = nMints / 4 + ((nMints % 4) > 0);
for ( k = nDigits - 1; k >= 0; k-- )
{
Digit = ((pTruth[k/8] >> (k * 4)) & 15);
if ( Digit < 10 )
fprintf( pFile, "%d", Digit );
else
fprintf( pFile, "%c", 'A' + Digit-10 );
}
// fprintf( pFile, "\n" );
}
void Extra_PrintHex2( FILE * pFile, unsigned * pTruth, int nVars )
{
int nMints, nDigits, Digit, k;
// write the number into the file
//fprintf( pFile, "0x" );
nMints = (1 << nVars);
nDigits = nMints / 4 + ((nMints % 4) > 0);
for ( k = nDigits - 1; k >= 0; k-- )
{
Digit = ((pTruth[k/8] >> (k * 4)) & 15);
if ( Digit < 10 )
fprintf( pFile, "%d", Digit );
else
fprintf( pFile, "%c", 'A' + Digit-10 );
}
// fprintf( pFile, "\n" );
}
void Extra_PrintHexReverse( FILE * pFile, unsigned * pTruth, int nVars )
{
int nMints, nDigits, Digit, k;
// write the number into the file
fprintf( pFile, "0x" );
nMints = (1 << nVars);
nDigits = nMints / 4 + ((nMints % 4) > 0);
for ( k = 0; k < nDigits; k++ )
{
Digit = ((pTruth[k/8] >> (k * 4)) & 15);
if ( Digit < 10 )
fprintf( pFile, "%d", Digit );
else
fprintf( pFile, "%c", 'A' + Digit-10 );
}
// fprintf( pFile, "\n" );
}
/**Function*************************************************************
Synopsis [Returns the composite name of the file.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Extra_PrintSymbols( FILE * pFile, char Char, int nTimes, int fPrintNewLine )
{
int i;
for ( i = 0; i < nTimes; i++ )
printf( "%c", Char );
if ( fPrintNewLine )
printf( "\n" );
}
/**Function*************************************************************
Synopsis [Appends the string.]
Description [Assumes that the given string (pStrGiven) has been allocated
before using malloc(). The additional string has not been allocated.
Allocs more root, appends the additional part, frees the old given string.]
SideEffects []
SeeAlso []
***********************************************************************/
char * Extra_StringAppend( char * pStrGiven, char * pStrAdd )
{
char * pTemp;
if ( pStrGiven )
{
pTemp = ABC_ALLOC( char, strlen(pStrGiven) + strlen(pStrAdd) + 2 );
sprintf( pTemp, "%s%s", pStrGiven, pStrAdd );
ABC_FREE( pStrGiven );
}
else
pTemp = Extra_UtilStrsav( pStrAdd );
return pTemp;
}
/**Function*************************************************************
Synopsis [Only keep characters belonging to the second string.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Extra_StringClean( char * pStrGiven, char * pCharKeep )
{
char * pTemp, * pChar, * pSave = pStrGiven;
for ( pTemp = pStrGiven; *pTemp; pTemp++ )
{
for ( pChar = pCharKeep; *pChar; pChar++ )
if ( *pTemp == *pChar )
break;
if ( *pChar == 0 )
continue;
*pSave++ = *pTemp;
}
*pSave = 0;
}
/**Function*************************************************************
Synopsis [String comparison procedure.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Extra_StringCompare( const char * pp1, const char * pp2 )
{
return strcmp(*(char **)pp1, *(char **)pp2);
}
/**Function*************************************************************
Synopsis [Sorts lines in the file alphabetically.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Extra_FileSort( char * pFileName, char * pFileNameOut )
{
FILE * pFile;
char * pContents;
char ** pLines;
int i, nLines, Begin;
pFile = fopen( pFileName, "rb" );
if ( pFile == NULL )
{
printf( "Extra_FileSort(): Cannot open file \"%s\".\n", pFileName );
return;
}
pContents = Extra_FileRead( pFile );
fclose( pFile );
if ( pContents == NULL )
{
printf( "Extra_FileSort(): Cannot read contents of file \"%s\".\n", pFileName );
return;
}
// count end of lines
for ( nLines = 0, i = 0; pContents[i]; i++ )
nLines += (pContents[i] == '\n');
// break the file into lines
pLines = (char **)malloc( sizeof(char *) * nLines );
Begin = 0;
for ( nLines = 0, i = 0; pContents[i]; i++ )
if ( pContents[i] == '\n' )
{
pContents[i] = 0;
pLines[nLines++] = pContents + Begin;
Begin = i + 1;
}
// sort the lines
qsort( pLines, (size_t)nLines, sizeof(char *), (int(*)(const void *,const void *))Extra_StringCompare );
// write a new file
pFile = fopen( pFileNameOut, "wb" );
for ( i = 0; i < nLines; i++ )
if ( pLines[i][0] )
fprintf( pFile, "%s\n", pLines[i] );
fclose( pFile );
// cleanup
free( pLines );
free( pContents );
// report the result
printf( "The file after sorting is \"%s\".\n", pFileNameOut );
}
/**Function*************************************************************
Synopsis [Appends line number in the end.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Extra_FileLineNumAdd( char * pFileName, char * pFileNameOut )
{
char Buffer[1000];
FILE * pFile;
FILE * pFile2;
int iLine;
pFile = fopen( pFileName, "rb" );
if ( pFile == NULL )
{
printf( "Extra_FileLineNumAdd(): Cannot open file \"%s\".\n", pFileName );
return;
}
pFile2 = fopen( pFileNameOut, "wb" );
if ( pFile2 == NULL )
{
fclose( pFile );
printf( "Extra_FileLineNumAdd(): Cannot open file \"%s\".\n", pFileNameOut );
return;
}
for ( iLine = 0; fgets( Buffer, 1000, pFile ); iLine++ )
{
sprintf( Buffer + strlen(Buffer) - 2, "%03d\n%c", iLine, 0 );
fputs( Buffer, pFile2 );
}
fclose( pFile );
fclose( pFile2 );
// report the result
printf( "The resulting file is \"%s\".\n", pFileNameOut );
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
/*
int main( int argc, char ** argv )
{
if ( argc == 2 )
Extra_FileSort( argv[1], Extra_FileNameAppend(argv[1], "_sorted") );
else
printf( "%s: Wrong number of command line arguments.\n", argv[0] );
return 1;
}
*/
/*---------------------------------------------------------------------------*/
/* Definition of internal functions */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/* Definition of static Functions */
/*---------------------------------------------------------------------------*/
////////////////////////////////////////////////////////////////////////
/// END OF FILE ///
////////////////////////////////////////////////////////////////////////
ABC_NAMESPACE_IMPL_END
|
bbd7f91e9bbfe7f10731f875a4bf3fbefd1756c0
|
2c73a693c2b3c162eae2ab94f649d8c4494878ba
|
/components/lvgl/lv_demos/src/lv_ex_style/lv_ex_style_10.c
|
15177a6a793dd99ddcf8c47da39a62f1d1f79f16
|
[
"MIT"
] |
permissive
|
openLuat/LuatOS
|
185e1e140aed908434168133571ddcafe98f4e12
|
4b29d5121ab4f7133630331e8502c526c7856897
|
refs/heads/master
| 2023-08-23T04:57:23.263539
| 2023-08-23T04:46:46
| 2023-08-23T04:46:46
| 230,403,844
| 378
| 93
|
MIT
| 2021-12-17T02:19:30
| 2019-12-27T08:29:19
|
C
|
UTF-8
|
C
| false
| false
| 1,226
|
c
|
lv_ex_style_10.c
|
#include "../../lv_examples.h"
/**
* Using the transitions style properties
*/
void lv_ex_style_10(void)
{
static lv_style_t style;
lv_style_init(&style);
/*Set a background color and a radius*/
lv_style_set_radius(&style, LV_STATE_DEFAULT, 5);
lv_style_set_bg_opa(&style, LV_STATE_DEFAULT, LV_OPA_COVER);
lv_style_set_bg_color(&style, LV_STATE_DEFAULT, LV_COLOR_SILVER);
/*Set different background color in pressed state*/
lv_style_set_bg_color(&style, LV_STATE_PRESSED, LV_COLOR_GRAY);
/*Set different transition time in default and pressed state
*fast press, slower revert to default*/
lv_style_set_transition_time(&style, LV_STATE_DEFAULT, 500);
lv_style_set_transition_time(&style, LV_STATE_PRESSED, 200);
/*Small delay to make transition more visible*/
lv_style_set_transition_delay(&style, LV_STATE_DEFAULT, 100);
/*Add `bg_color` to transitioned properties*/
lv_style_set_transition_prop_1(&style, LV_STATE_DEFAULT, LV_STYLE_BG_COLOR);
/*Create an object with the new style*/
lv_obj_t * obj = lv_obj_create(lv_scr_act(), NULL);
lv_obj_add_style(obj, LV_OBJ_PART_MAIN, &style);
lv_obj_align(obj, NULL, LV_ALIGN_CENTER, 0, 0);
}
|
478b37edb95e278f31618fcda28636d2f8f5d2f2
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/ffmpeg/libavdevice/alsa_enc.c
|
62a20c7ba486b9239a735871c21d63baca9f83c4
|
[
"BSD-3-Clause",
"LGPL-2.1-only",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.1-or-later",
"GPL-3.0-or-later",
"LGPL-3.0-or-later",
"IJG",
"LicenseRef-scancode-other-permissive",
"MIT",
"GPL-2.0-or-later",
"Apache-2.0",
"GPL-3.0-only"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 5,763
|
c
|
alsa_enc.c
|
/*
* ALSA input and output
* Copyright (c) 2007 Luca Abeni ( lucabe72 email it )
* Copyright (c) 2007 Benoit Fouet ( benoit fouet free fr )
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* ALSA input and output: output
* @author Luca Abeni ( lucabe72 email it )
* @author Benoit Fouet ( benoit fouet free fr )
*
* This avdevice encoder can play audio to an ALSA (Advanced Linux
* Sound Architecture) device.
*
* The filename parameter is the name of an ALSA PCM device capable of
* capture, for example "default" or "plughw:1"; see the ALSA documentation
* for naming conventions. The empty string is equivalent to "default".
*
* The playback period is set to the lower value available for the device,
* which gives a low latency suitable for real-time playback.
*/
#include <alsa/asoundlib.h>
#include "libavutil/internal.h"
#include "libavutil/time.h"
#include "libavformat/internal.h"
#include "libavformat/mux.h"
#include "avdevice.h"
#include "alsa.h"
static av_cold int audio_write_header(AVFormatContext *s1)
{
AlsaData *s = s1->priv_data;
AVStream *st = NULL;
unsigned int sample_rate;
enum AVCodecID codec_id;
int res;
if (s1->nb_streams != 1 || s1->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO) {
av_log(s1, AV_LOG_ERROR, "Only a single audio stream is supported.\n");
return AVERROR(EINVAL);
}
st = s1->streams[0];
sample_rate = st->codecpar->sample_rate;
codec_id = st->codecpar->codec_id;
res = ff_alsa_open(s1, SND_PCM_STREAM_PLAYBACK, &sample_rate,
st->codecpar->ch_layout.nb_channels, &codec_id);
if (sample_rate != st->codecpar->sample_rate) {
av_log(s1, AV_LOG_ERROR,
"sample rate %d not available, nearest is %d\n",
st->codecpar->sample_rate, sample_rate);
goto fail;
}
avpriv_set_pts_info(st, 64, 1, sample_rate);
return res;
fail:
snd_pcm_close(s->h);
return AVERROR(EIO);
}
static int audio_write_packet(AVFormatContext *s1, AVPacket *pkt)
{
AlsaData *s = s1->priv_data;
int res;
int size = pkt->size;
const uint8_t *buf = pkt->data;
size /= s->frame_size;
if (pkt->dts != AV_NOPTS_VALUE)
s->timestamp = pkt->dts;
s->timestamp += pkt->duration ? pkt->duration : size;
if (s->reorder_func) {
if (size > s->reorder_buf_size)
if (ff_alsa_extend_reorder_buf(s, size))
return AVERROR(ENOMEM);
s->reorder_func(buf, s->reorder_buf, size);
buf = s->reorder_buf;
}
while ((res = snd_pcm_writei(s->h, buf, size)) < 0) {
if (res == -EAGAIN) {
return AVERROR(EAGAIN);
}
if (ff_alsa_xrun_recover(s1, res) < 0) {
av_log(s1, AV_LOG_ERROR, "ALSA write error: %s\n",
snd_strerror(res));
return AVERROR(EIO);
}
}
return 0;
}
static int audio_write_frame(AVFormatContext *s1, int stream_index,
AVFrame **frame, unsigned flags)
{
AlsaData *s = s1->priv_data;
AVPacket pkt;
/* ff_alsa_open() should have accepted only supported formats */
if ((flags & AV_WRITE_UNCODED_FRAME_QUERY))
return av_sample_fmt_is_planar(s1->streams[stream_index]->codecpar->format) ?
AVERROR(EINVAL) : 0;
/* set only used fields */
pkt.data = (*frame)->data[0];
pkt.size = (*frame)->nb_samples * s->frame_size;
pkt.dts = (*frame)->pkt_dts;
#if FF_API_PKT_DURATION
FF_DISABLE_DEPRECATION_WARNINGS
if ((*frame)->pkt_duration)
pkt.duration = (*frame)->pkt_duration;
else
FF_ENABLE_DEPRECATION_WARNINGS
#endif
pkt.duration = (*frame)->duration;
return audio_write_packet(s1, &pkt);
}
static void
audio_get_output_timestamp(AVFormatContext *s1, int stream,
int64_t *dts, int64_t *wall)
{
AlsaData *s = s1->priv_data;
snd_pcm_sframes_t delay = 0;
*wall = av_gettime();
snd_pcm_delay(s->h, &delay);
*dts = s->timestamp - delay;
}
static int audio_get_device_list(AVFormatContext *h, AVDeviceInfoList *device_list)
{
return ff_alsa_get_device_list(device_list, SND_PCM_STREAM_PLAYBACK);
}
static const AVClass alsa_muxer_class = {
.class_name = "ALSA outdev",
.item_name = av_default_item_name,
.version = LIBAVUTIL_VERSION_INT,
.category = AV_CLASS_CATEGORY_DEVICE_AUDIO_OUTPUT,
};
const FFOutputFormat ff_alsa_muxer = {
.p.name = "alsa",
.p.long_name = NULL_IF_CONFIG_SMALL("ALSA audio output"),
.priv_data_size = sizeof(AlsaData),
.p.audio_codec = DEFAULT_CODEC_ID,
.p.video_codec = AV_CODEC_ID_NONE,
.write_header = audio_write_header,
.write_packet = audio_write_packet,
.write_trailer = ff_alsa_close,
.write_uncoded_frame = audio_write_frame,
.get_device_list = audio_get_device_list,
.get_output_timestamp = audio_get_output_timestamp,
.p.flags = AVFMT_NOFILE,
.p.priv_class = &alsa_muxer_class,
};
|
863573dfd6dccf3840ac684c47de96b911bddb3f
|
50dd46b8ece33f3cdd174284b15d1d51f89669d4
|
/third_party/edk2/EmbeddedPkg/MetronomeDxe/Metronome.c
|
b43bf9558b4fce28ac34587102881852af5a5cb1
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause",
"OpenSSL"
] |
permissive
|
google/google-ctf
|
f99da1ee07729bbccb869fff1cbaed6a80e43bcc
|
df02323eaf945d15e124801c74abaadca2749dc7
|
refs/heads/master
| 2023-08-31T14:30:27.548081
| 2023-08-29T13:04:20
| 2023-08-29T13:04:20
| 131,317,137
| 4,136
| 607
|
Apache-2.0
| 2023-08-30T22:17:02
| 2018-04-27T15:56:03
|
Go
|
UTF-8
|
C
| false
| false
| 4,608
|
c
|
Metronome.c
|
/** @file
Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
Copyright (c) 2013, ARM Ltd. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include <PiDxe.h>
#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiLib.h>
#include <Library/PcdLib.h>
#include <Library/TimerLib.h>
#include <Protocol/Metronome.h>
EFI_STATUS
EFIAPI
WaitForTick (
IN EFI_METRONOME_ARCH_PROTOCOL *This,
IN UINT32 TickNumber
);
/**
Interface structure for the Metronome Architectural Protocol.
@par Protocol Description:
This protocol provides access to a known time source in the platform to the
core. The core uses this known time source to produce core services that
require calibrated delays.
@param WaitForTick
Waits for a specified number of ticks from a known time source
in the platform. The actual time passed between entry of this
function and the first tick is between 0 and TickPeriod 100 nS
units. If you want to guarantee that at least TickPeriod time
has elapsed, wait for two ticks.
@param TickPeriod
The period of platform's known time source in 100 nS units.
This value on any platform must be at least 10 uS, and must not
exceed 200 uS. The value in this field is a constant that must
not be modified after the Metronome architectural protocol is
installed. All consumers must treat this as a read-only field.
**/
EFI_METRONOME_ARCH_PROTOCOL gMetronome = {
WaitForTick,
FixedPcdGet32 (PcdMetronomeTickPeriod)
};
/**
The WaitForTick() function waits for the number of ticks specified by
TickNumber from a known time source in the platform. If TickNumber of
ticks are detected, then EFI_SUCCESS is returned. The actual time passed
between entry of this function and the first tick is between 0 and
TickPeriod 100 nS units. If you want to guarantee that at least TickPeriod
time has elapsed, wait for two ticks. This function waits for a hardware
event to determine when a tick occurs. It is possible for interrupt
processing, or exception processing to interrupt the execution of the
WaitForTick() function. Depending on the hardware source for the ticks, it
is possible for a tick to be missed. This function cannot guarantee that
ticks will not be missed. If a timeout occurs waiting for the specified
number of ticks, then EFI_TIMEOUT is returned.
@param This The EFI_METRONOME_ARCH_PROTOCOL instance.
@param TickNumber Number of ticks to wait.
@retval EFI_SUCCESS The wait for the number of ticks specified by TickNumber
succeeded.
@retval EFI_TIMEOUT A timeout occurred waiting for the specified number of ticks.
**/
EFI_STATUS
EFIAPI
WaitForTick (
IN EFI_METRONOME_ARCH_PROTOCOL *This,
IN UINT32 TickNumber
)
{
//
// Compute how long to stall the CPU.
// gMetronome.TickPeriod is in 100 ns units so it needs to be divided by 10
// to get it in microseconds units.
//
MicroSecondDelay (TickNumber * gMetronome.TickPeriod / 10);
return EFI_SUCCESS;
}
EFI_HANDLE gMetronomeHandle = NULL;
/**
Initialize the state information for the CPU Architectural Protocol
@param ImageHandle of the loaded driver
@param SystemTable Pointer to the System Table
@retval EFI_SUCCESS Protocol registered
@retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
@retval EFI_DEVICE_ERROR Hardware problems
**/
EFI_STATUS
MetronomeInitialize (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
EFI_STATUS Status;
//
// Do any hardware init required to make WaitForTick () to work here.
//
Status = gBS->InstallMultipleProtocolInterfaces (
&gMetronomeHandle,
&gEfiMetronomeArchProtocolGuid, &gMetronome,
NULL
);
ASSERT_EFI_ERROR (Status);
return Status;
}
|
58d16fa4297154ead7697942bba7217b6c4947d7
|
6832a9c81b16ead373325f70fb97753d6a211539
|
/src/wrapped/wrappedgstaudio_private.h
|
2a40615ac56ec4526ce2d4e0548f8f318d8ce1f6
|
[
"MIT"
] |
permissive
|
ptitSeb/box86
|
2d3a0c4574905ff8d9dc7b5afb5444a273832bd6
|
ad934455c1b40feeebe5e6bd09b9063519102859
|
refs/heads/master
| 2023-08-22T05:30:54.331500
| 2023-08-20T13:01:58
| 2023-08-20T13:01:58
| 164,844,546
| 2,877
| 294
|
MIT
| 2023-07-27T11:19:10
| 2019-01-09T10:49:32
|
C
|
UTF-8
|
C
| false
| false
| 10,001
|
h
|
wrappedgstaudio_private.h
|
#if !(defined(GO) && defined(GOM) && defined(GO2) && defined(DATA))
#error meh!
#endif
//GO(gst_audio_aggregator_convert_pad_get_type,
//GO(gst_audio_aggregator_get_type,
//GO(gst_audio_aggregator_pad_get_type,
//GO(gst_audio_aggregator_set_sink_caps,
//GO(gst_audio_base_sink_create_ringbuffer,
//GO(gst_audio_base_sink_discont_reason_get_type,
//GO(gst_audio_base_sink_get_alignment_threshold,
//GO(gst_audio_base_sink_get_discont_wait,
//GO(gst_audio_base_sink_get_drift_tolerance,
//GO(gst_audio_base_sink_get_provide_clock,
//GO(gst_audio_base_sink_get_slave_method,
//GO(gst_audio_base_sink_get_type,
//GO(gst_audio_base_sink_report_device_failure,
//GO(gst_audio_base_sink_set_alignment_threshold,
//GO(gst_audio_base_sink_set_custom_slaving_callback,
//GO(gst_audio_base_sink_set_discont_wait,
//GO(gst_audio_base_sink_set_drift_tolerance,
//GO(gst_audio_base_sink_set_provide_clock,
//GO(gst_audio_base_sink_set_slave_method,
//GO(gst_audio_base_sink_slave_method_get_type,
//GO(gst_audio_base_src_create_ringbuffer,
//GO(gst_audio_base_src_get_provide_clock,
//GO(gst_audio_base_src_get_slave_method,
//GO(gst_audio_base_src_get_type,
//GO(gst_audio_base_src_set_provide_clock,
//GO(gst_audio_base_src_set_slave_method,
//GO(gst_audio_base_src_slave_method_get_type,
//GO(gst_audio_buffer_clip,
//GO(gst_audio_buffer_map,
//GO(gst_audio_buffer_reorder_channels,
//GO(gst_audio_buffer_truncate,
//GO(gst_audio_buffer_unmap,
//GO(gst_audio_cd_src_add_track,
//GO(gst_audio_cd_src_get_type,
//GO(gst_audio_cd_src_mode_get_type,
//GO(gst_audio_channel_get_fallback_mask,
//GO(gst_audio_channel_mixer_flags_get_type,
//GO(gst_audio_channel_mixer_free,
//GO(gst_audio_channel_mixer_is_passthrough,
//GO(gst_audio_channel_mixer_new,
//GO(gst_audio_channel_mixer_new_with_matrix,
//GO(gst_audio_channel_mixer_samples,
//GO(gst_audio_channel_position_get_type,
//GO(gst_audio_channel_positions_from_mask,
//GO(gst_audio_channel_positions_to_mask,
//GO(gst_audio_channel_positions_to_string,
//GO(gst_audio_channel_positions_to_valid_order,
//GO(gst_audio_check_valid_channel_positions,
//GO(gst_audio_clipping_meta_api_get_type,
//GO(gst_audio_clipping_meta_get_info,
//GO(gst_audio_clock_adjust,
//GO(gst_audio_clock_get_time,
//GO(gst_audio_clock_get_type,
//GO(gst_audio_clock_invalidate,
//GO(gst_audio_clock_new,
//GO(gst_audio_clock_reset,
//GO(gst_audio_converter_convert,
//GO(gst_audio_converter_flags_get_type,
//GO(gst_audio_converter_free,
//GO(gst_audio_converter_get_config,
//GO(gst_audio_converter_get_in_frames,
//GO(gst_audio_converter_get_max_latency,
//GO(gst_audio_converter_get_out_frames,
//GO(gst_audio_converter_get_type,
//GO(gst_audio_converter_is_passthrough,
//GO(gst_audio_converter_new,
//GO(gst_audio_converter_reset,
//GO(gst_audio_converter_samples,
//GO(gst_audio_converter_supports_inplace,
//GO(gst_audio_converter_update_config,
//GO(gst_audio_decoder_allocate_output_buffer,
//GO(_gst_audio_decoder_error,
//GO(gst_audio_decoder_finish_frame,
//GO(gst_audio_decoder_finish_subframe,
//GO(gst_audio_decoder_get_allocator,
//GO(gst_audio_decoder_get_audio_info,
//GO(gst_audio_decoder_get_delay,
//GO(gst_audio_decoder_get_drainable,
//GO(gst_audio_decoder_get_estimate_rate,
//GO(gst_audio_decoder_get_latency,
//GO(gst_audio_decoder_get_max_errors,
//GO(gst_audio_decoder_get_min_latency,
//GO(gst_audio_decoder_get_needs_format,
//GO(gst_audio_decoder_get_parse_state,
//GO(gst_audio_decoder_get_plc,
//GO(gst_audio_decoder_get_plc_aware,
//GO(gst_audio_decoder_get_tolerance,
//GO(gst_audio_decoder_get_type,
//GO(gst_audio_decoder_merge_tags,
//GO(gst_audio_decoder_negotiate,
//GO(gst_audio_decoder_proxy_getcaps,
//GO(gst_audio_decoder_set_allocation_caps,
//GO(gst_audio_decoder_set_drainable,
//GO(gst_audio_decoder_set_estimate_rate,
//GO(gst_audio_decoder_set_latency,
//GO(gst_audio_decoder_set_max_errors,
//GO(gst_audio_decoder_set_min_latency,
//GO(gst_audio_decoder_set_needs_format,
//GO(gst_audio_decoder_set_output_caps,
//GO(gst_audio_decoder_set_output_format,
//GO(gst_audio_decoder_set_plc,
//GO(gst_audio_decoder_set_plc_aware,
//GO(gst_audio_decoder_set_tolerance,
//GO(gst_audio_decoder_set_use_default_pad_acceptcaps,
//GO(gst_audio_dither_method_get_type,
//GO(gst_audio_downmix_meta_api_get_type,
//GO(gst_audio_downmix_meta_get_info,
//GO(gst_audio_encoder_allocate_output_buffer,
//GO(gst_audio_encoder_finish_frame,
//GO(gst_audio_encoder_get_allocator,
//GO(gst_audio_encoder_get_audio_info,
//GO(gst_audio_encoder_get_drainable,
//GO(gst_audio_encoder_get_frame_max,
//GO(gst_audio_encoder_get_frame_samples_max,
//GO(gst_audio_encoder_get_frame_samples_min,
//GO(gst_audio_encoder_get_hard_min,
//GO(gst_audio_encoder_get_hard_resync,
//GO(gst_audio_encoder_get_latency,
//GO(gst_audio_encoder_get_lookahead,
//GO(gst_audio_encoder_get_mark_granule,
//GO(gst_audio_encoder_get_perfect_timestamp,
//GO(gst_audio_encoder_get_tolerance,
//GO(gst_audio_encoder_get_type,
//GO(gst_audio_encoder_merge_tags,
//GO(gst_audio_encoder_negotiate,
//GO(gst_audio_encoder_proxy_getcaps,
//GO(gst_audio_encoder_set_allocation_caps,
//GO(gst_audio_encoder_set_drainable,
//GO(gst_audio_encoder_set_frame_max,
//GO(gst_audio_encoder_set_frame_samples_max,
//GO(gst_audio_encoder_set_frame_samples_min,
//GO(gst_audio_encoder_set_hard_min,
//GO(gst_audio_encoder_set_hard_resync,
//GO(gst_audio_encoder_set_headers,
//GO(gst_audio_encoder_set_latency,
//GO(gst_audio_encoder_set_lookahead,
//GO(gst_audio_encoder_set_mark_granule,
//GO(gst_audio_encoder_set_output_format,
//GO(gst_audio_encoder_set_perfect_timestamp,
//GO(gst_audio_encoder_set_tolerance,
//GO(gst_audio_filter_class_add_pad_templates,
//GO(gst_audio_filter_get_type,
//GO(gst_audio_flags_get_type,
GO(gst_audio_format_build_integer, iFiiii)
//GO(gst_audio_format_fill_silence,
//GO(gst_audio_format_flags_get_type,
//GO(gst_audio_format_from_string,
//GO(gst_audio_format_get_info,
//GO(gst_audio_format_get_type,
//GO(gst_audio_format_info_get_type,
//GO(gst_audio_formats_raw,
GO(gst_audio_format_to_string, pFi)
//GO(gst_audio_get_channel_reorder_map,
//GO(gst_audio_iec61937_frame_size,
//GO(gst_audio_iec61937_payload,
GO(gst_audio_info_convert, iFpiIip)
GO(gst_audio_info_copy, pFp)
GO(gst_audio_info_free, vFp)
GO(gst_audio_info_from_caps, iFpp)
GO(gst_audio_info_get_type, pFv)
GO(gst_audio_info_init, vFp)
GO(gst_audio_info_is_equal, iFpp)
GO(gst_audio_info_new, pFv)
GO(gst_audio_info_set_format, vFpiiip)
GO(gst_audio_info_to_caps, pFp)
GO(gst_audio_layout_get_type, pFv)
//GO(gst_audio_make_raw_caps,
//GO(gst_audio_meta_api_get_type,
//GO(gst_audio_meta_get_info,
//GO(gst_audio_noise_shaping_method_get_type,
//GO(gst_audio_pack_flags_get_type,
//GO(gst_audio_quantize_flags_get_type,
//GO(gst_audio_quantize_free,
//GO(gst_audio_quantize_new,
//GO(gst_audio_quantize_reset,
//GO(gst_audio_quantize_samples,
//GO(gst_audio_reorder_channels,
//GO(gst_audio_resampler_filter_interpolation_get_type,
//GO(gst_audio_resampler_filter_mode_get_type,
//GO(gst_audio_resampler_flags_get_type,
//GO(gst_audio_resampler_free,
//GO(gst_audio_resampler_get_in_frames,
//GO(gst_audio_resampler_get_max_latency,
//GO(gst_audio_resampler_get_out_frames,
//GO(gst_audio_resampler_method_get_type,
//GO(gst_audio_resampler_new,
//GO(gst_audio_resampler_options_set_quality,
//GO(gst_audio_resampler_resample,
//GO(gst_audio_resampler_reset,
//GO(gst_audio_resampler_update,
//GO(gst_audio_ring_buffer_acquire,
//GO(gst_audio_ring_buffer_activate,
//GO(gst_audio_ring_buffer_advance,
//GO(gst_audio_ring_buffer_clear,
//GO(gst_audio_ring_buffer_clear_all,
//GO(gst_audio_ring_buffer_close_device,
//GO(gst_audio_ring_buffer_commit,
//GO(gst_audio_ring_buffer_convert,
//GO(gst_audio_ring_buffer_debug_spec_buff,
//GO(gst_audio_ring_buffer_debug_spec_caps,
//GO(gst_audio_ring_buffer_delay,
//GO(gst_audio_ring_buffer_device_is_open,
//GO(gst_audio_ring_buffer_format_type_get_type,
//GO(gst_audio_ring_buffer_get_type,
//GO(gst_audio_ring_buffer_is_acquired,
//GO(gst_audio_ring_buffer_is_active,
//GO(gst_audio_ring_buffer_is_flushing,
//GO(gst_audio_ring_buffer_may_start,
//GO(gst_audio_ring_buffer_open_device,
//GO(gst_audio_ring_buffer_parse_caps,
//GO(gst_audio_ring_buffer_pause,
//GO(gst_audio_ring_buffer_prepare_read,
//GO(gst_audio_ring_buffer_read,
//GO(gst_audio_ring_buffer_release,
//GO(gst_audio_ring_buffer_samples_done,
//GO(gst_audio_ring_buffer_set_callback,
//GO(gst_audio_ring_buffer_set_callback_full,
//GO(gst_audio_ring_buffer_set_channel_positions,
//GO(gst_audio_ring_buffer_set_flushing,
//GO(gst_audio_ring_buffer_set_sample,
//GO(gst_audio_ring_buffer_set_timestamp,
//GO(gst_audio_ring_buffer_start,
//GO(gst_audio_ring_buffer_state_get_type,
//GO(gst_audio_ring_buffer_stop,
//GO(gst_audio_sink_get_type,
//GO(gst_audio_src_get_type,
//GO(gst_audio_stream_align_copy,
//GO(gst_audio_stream_align_free,
//GO(gst_audio_stream_align_get_alignment_threshold,
//GO(gst_audio_stream_align_get_discont_wait,
//GO(gst_audio_stream_align_get_rate,
//GO(gst_audio_stream_align_get_samples_since_discont,
//GO(gst_audio_stream_align_get_timestamp_at_discont,
//GO(gst_audio_stream_align_get_type,
//GO(gst_audio_stream_align_mark_discont,
//GO(gst_audio_stream_align_new,
//GO(gst_audio_stream_align_process,
//GO(gst_audio_stream_align_set_alignment_threshold,
//GO(gst_audio_stream_align_set_discont_wait,
//GO(gst_audio_stream_align_set_rate,
//GO(gst_buffer_add_audio_clipping_meta,
//GO(gst_buffer_add_audio_downmix_meta,
//GO(gst_buffer_add_audio_meta,
//GO(gst_buffer_get_audio_downmix_meta_for_channels,
//GO(gst_stream_volume_convert_volume,
//GO(gst_stream_volume_get_mute,
//GO(gst_stream_volume_get_type,
//GO(gst_stream_volume_get_volume,
//GO(gst_stream_volume_set_mute,
//GO(gst_stream_volume_set_volume,
|
9d408f1bb8bdb7e91db133220511fefe82ae8129
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/games/warp/object.c
|
a6b9f6a74b054bbc4b7d94741244881d7af699f4
|
[
"BSD-2-Clause"
] |
permissive
|
NetBSD/src
|
1a9cbc22ed778be638b37869ed4fb5c8dd616166
|
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
|
refs/heads/trunk
| 2023-08-31T13:24:58.105962
| 2023-08-27T15:50:47
| 2023-08-27T15:50:47
| 88,439,547
| 656
| 348
| null | 2023-07-20T20:07:24
| 2017-04-16T20:03:43
| null |
UTF-8
|
C
| false
| false
| 1,450
|
c
|
object.c
|
/* Header: object.c,v 7.0 86/10/08 15:12:55 lwall Exp */
/* Log: object.c,v
* Revision 7.0 86/10/08 15:12:55 lwall
* Split into separate files. Added amoebas and pirates.
*
*/
#include "EXTERN.h"
#include "warp.h"
#include "INTERN.h"
#include "object.h"
void
object_init(void)
{
;
}
OBJECT *
make_object(char typ, char img, int px, int py, int vx, int vy, long energ,
long mas, OBJECT *where)
{
OBJECT *obj;
if (free_root.next == &free_root)
#ifndef lint
obj = (OBJECT *) malloc(sizeof root);
#else
obj = Null(OBJECT*);
#endif
else {
obj = free_root.next;
free_root.next = obj->next;
obj->next->prev = &free_root;
}
obj->type = typ;
obj->image = img;
obj->next = where;
obj->prev = where->prev;
where->prev = obj;
obj->prev->next = obj;
obj->velx = vx;
obj->vely = vy;
obj->contend = 0;
obj->strategy = 0;
obj->flags = 0;
obj->posx = px;
obj->posy = py;
if (typ != Torp && typ != Web) {
occupant[py][px] = obj;
}
obj->energy = energ;
obj->mass = mas;
return(obj);
}
void
unmake_object(OBJECT *curobj)
{
curobj->prev->next = curobj->next;
curobj->next->prev = curobj->prev;
if (curobj == movers) {
movers = curobj->next;
}
free_object(curobj);
}
void
free_object(OBJECT *curobj)
{
curobj->next = free_root.next;
curobj->prev = &free_root;
free_root.next->prev = curobj;
free_root.next = curobj;
}
|
3a3d8189a8560c43285828a1b1f470119ff2cef1
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/nuvoton/libraries/m2354/StdDriver/inc/nu_fmc.h
|
98700d318ca1d19baa1166fe8ea16733787b6904
|
[
"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
| 22,126
|
h
|
nu_fmc.h
|
/**************************************************************************//**
* @file nu_fmc.h
* @version V3.0
* $Revision: 2 $
* $Date: 19/11/27 3:11p $
* @brief M2355 Series Flash Memory Controller(FMC) driver header file
*
* @copyright SPDX-License-Identifier: Apache-2.0
* @copyright Copyright (C) 2020 Nuvoton Technology Corp. All rights reserved.
******************************************************************************/
#ifndef __NU_FMC_H__
#define __NU_FMC_H__
#ifdef __cplusplus
extern "C"
{
#endif
/** @addtogroup Standard_Driver Standard Driver
@{
*/
/** @addtogroup FMC_Driver FMC Driver
@{
*/
/** @addtogroup FMC_EXPORTED_CONSTANTS FMC Exported Constants
@{
*/
/*---------------------------------------------------------------------------------------------------------*/
/* Global constant definitions */
/*---------------------------------------------------------------------------------------------------------*/
#define ISBEN 0UL
#define FMC_ISP ( (__PC() & 0x10000000) ? FMC_NS : FMC)
/*---------------------------------------------------------------------------------------------------------*/
/* Define Base Address */
/*---------------------------------------------------------------------------------------------------------*/
#define FMC_APROM_BASE 0x00000000UL /*!< APROM Base Address */
#define FMC_APROM_END 0x00100000UL /*!< APROM end address */
#define FMC_APROM_BANK0_END (FMC_APROM_END/2UL) /*!< APROM bank0 end address */
#define FMC_LDROM_BASE 0x00100000UL /*!< LDROM Base Address */
#define FMC_LDROM_END 0x00104000UL /*!< LDROM end address */
#define FMC_DTFSH_BASE 0x00110000UL /*!< LDROM Base Address */
#define FMC_DTFSH_END 0x00112000UL /*!< LDROM end address */
#define FMC_XOM_BASE 0x00200000UL /*!< XOM Base Address */
#define FMC_XOMR0_BASE 0x00200000UL /*!< XOMR 0 Base Address */
#define FMC_XOMR1_BASE 0x00200010UL /*!< XOMR 1 Base Address */
#define FMC_XOMR2_BASE 0x00200020UL /*!< XOMR 2 Base Address */
#define FMC_XOMR3_BASE 0x00200030UL /*!< XOMR 3 Base Address */
#define FMC_NSCBA_BASE 0x00210800UL /*!< Non-Secure base address */
#define FMC_SCRLOCK_BASE 0x00610000UL /*!< Secure Region Lock base address */
#define FMC_ARLOCK_BASE 0x00610008UL /*!< All Region Lock base address */
#define FMC_CONFIG_BASE 0x00300000UL /*!< CONFIG Base Address */
#define FMC_USER_CONFIG_0 0x00300000UL /*!< CONFIG 0 Address */
#define FMC_USER_CONFIG_1 0x00300004UL /*!< CONFIG 1 Address */
#define FMC_USER_CONFIG_2 0x00300008UL /*!< CONFIG 2 Address */
#define FMC_USER_CONFIG_3 0x0030000CUL /*!< CONFIG 3 Address */
#define FMC_OTP_BASE 0x00310000UL /*!< OTP flash base address */
#define FMC_FLASH_PAGE_SIZE 0x800UL /*!< Flash Page Size (2048 Bytes) */
#define FMC_PAGE_ADDR_MASK 0xFFFFF800UL /*!< Flash page address mask */
#define FMC_MULTI_WORD_PROG_LEN 512UL /*!< The maximum length of a multi-word program. */
#define FMC_APROM_SIZE FMC_APROM_END /*!< APROM Size */
#define FMC_BANK_SIZE (FMC_APROM_SIZE/2UL) /*!< APROM Bank Size */
#define FMC_LDROM_SIZE 0x4000UL /*!< LDROM Size (4 Kbytes) */
#define FMC_OTP_ENTRY_CNT 256UL /*!< OTP entry number */
/*---------------------------------------------------------------------------------------------------------*/
/* XOM region number constant definitions */
/*---------------------------------------------------------------------------------------------------------*/
#define XOMR0 0UL /*!< XOM region 0 */
#define XOMR1 1UL /*!< XOM region 1 */
#define XOMR2 2UL /*!< XOM region 2 */
#define XOMR3 3UL /*!< XOM region 3 */
/*---------------------------------------------------------------------------------------------------------*/
/* ISPCTL constant definitions */
/*---------------------------------------------------------------------------------------------------------*/
#define IS_BOOT_FROM_LDROM 0x1UL /*!< ISPCTL setting to select to boot from LDROM */
#define IS_BOOT_FROM_APROM 0x0UL /*!< ISPCTL setting to select to boot from APROM */
/*---------------------------------------------------------------------------------------------------------*/
/* ISPCMD constant definitions */
/*---------------------------------------------------------------------------------------------------------*/
#define FMC_ISPCMD_READ 0x00UL /*!< ISP Command: Read Flash */
#define FMC_ISPCMD_READ_UID 0x04UL /*!< ISP Command: Read Unique ID */
#define FMC_ISPCMD_READ_ALL1 0x08UL /*!< ISP Command: Read all-one result */
#define FMC_ISPCMD_READ_CID 0x0BUL /*!< ISP Command: Read Company ID */
#define FMC_ISPCMD_READ_DID 0x0CUL /*!< ISP Command: Read Device ID */
#define FMC_ISPCMD_READ_CKS 0x0DUL /*!< ISP Command: Read Checksum */
#define FMC_ISPCMD_PROGRAM 0x21UL /*!< ISP Command: 32-bit Program Flash */
#define FMC_ISPCMD_PAGE_ERASE 0x22UL /*!< ISP Command: Page Erase Flash */
#define FMC_ISPCMD_BANK_ERASE 0x23UL /*!< ISP Command: Erase Flash bank 0 or 1 */
#define FMC_ISPCMD_PROGRAM_MUL 0x27UL /*!< ISP Command: Flash Multi-Word Program */
#define FMC_ISPCMD_RUN_ALL1 0x28UL /*!< ISP Command: Run all-one verification */
#define FMC_ISPCMD_BANK_REMAP 0x2CUL /*!< ISP Command: Bank Remap */
#define FMC_ISPCMD_RUN_CKS 0x2DUL /*!< ISP Command: Run Check Calculation */
#define FMC_ISPCMD_VECMAP 0x2EUL /*!< ISP Command: Set vector mapping */
#define FMC_ISPCMD_READ_64 0x40UL /*!< ISP Command: 64-bit read Flash */
#define FMC_ISPCMD_PROGRAM_64 0x61UL /*!< ISP Command: 64-bit program Flash */
#define READ_ALLONE_YES 0xA11FFFFFUL /*!< Check-all-one result is all one. */
#define READ_ALLONE_NOT 0xA1100000UL /*!< Check-all-one result is not all one. */
#define READ_ALLONE_CMD_FAIL 0xFFFFFFFFUL /*!< Check-all-one command failed. */
/**@}*/ /* end of group FMC_EXPORTED_CONSTANTS */
/** @addtogroup FMC_EXPORTED_FUNCTIONS FMC Exported Functions
@{
*/
/*---------------------------------------------------------------------------------------------------------*/
/* FMC Macro Definitions */
/*---------------------------------------------------------------------------------------------------------*/
/**
* @brief Enable ISP Function
*
* @param None
*
* @return None
*
* @details This function will set ISPEN bit of ISPCTL control register to enable ISP function.
*
*/
#define FMC_ENABLE_ISP() (FMC_ISP->ISPCTL |= FMC_ISPCTL_ISPEN_Msk) /*!< Enable ISP Function */
/**
* @brief Disable ISP Function
*
* @param None
*
* @return None
*
* @details This function will clear ISPEN bit of ISPCTL control register to disable ISP function.
*
*/
#define FMC_DISABLE_ISP() (FMC_ISP->ISPCTL &= ~FMC_ISPCTL_ISPEN_Msk) /*!< Disable ISP Function */
/**
* @brief Disable Non Secure ISP Function
*
* @param None
*
* @return None
*
* @details This function will clear ISPEN bit of ISPCTL control register to disable Non Secure ISP function.
*
*/
#define FMC_ENABLE_LD_UPDATE() (FMC->ISPCTL |= FMC_ISPCTL_LDUEN_Msk) /*!< Enable LDROM Update Function */
/**
* @brief Disable LDROM Update Function
*
* @param None
*
* @return None
*
* @details This function will set ISPEN bit of ISPCTL control register to disable LDROM update function.
*
*/
#define FMC_DISABLE_LD_UPDATE() (FMC->ISPCTL &= ~FMC_ISPCTL_LDUEN_Msk) /*!< Disable LDROM Update Function */
/**
* @brief Enable User Configuration Update Function
*
* @param None
*
* @return None
*
* @details This function will set CFGUEN bit of ISPCTL control register to enable User Configuration update function.
* User needs to set CFGUEN bit before they can update User Configuration area.
*
*/
#define FMC_ENABLE_CFG_UPDATE() (FMC->ISPCTL |= FMC_ISPCTL_CFGUEN_Msk) /*!< Enable CONFIG Update Function */
/**
* @brief Disable User Configuration Update Function
*
* @param None
*
* @return None
*
* @details This function will clear CFGUEN bit of ISPCTL control register to disable User Configuration update function.
*
*/
#define FMC_DISABLE_CFG_UPDATE() (FMC->ISPCTL &= ~FMC_ISPCTL_CFGUEN_Msk) /*!< Disable CONFIG Update Function */
/**
* @brief Enable APROM Update Function
*
* @param None
*
* @return None
*
* @details This function will set APUEN bit of ISPCTL control register to enable APROM update function.
* User needs to set APUEN bit before they can update APROM in APROM boot mode.
*
*/
#define FMC_ENABLE_AP_UPDATE() (FMC_ISP->ISPCTL |= FMC_ISPCTL_APUEN_Msk) /*!< Enable APROM Update Function */
/**
* @brief Disable APROM Update Function
*
* @param None
*
* @return None
*
* @details This function will clear APUEN bit of ISPCTL control register to disable APROM update function.
*
*/
#define FMC_DISABLE_AP_UPDATE() (FMC_ISP->ISPCTL &= ~FMC_ISPCTL_APUEN_Msk) /*!< Disable APROM Update Function */
/**
* @brief Get ISP Fail Flag
*
* @param None
*
* @return None
*
* @details This function is used to get ISP fail flag when do ISP actoin.
*
*/
#define FMC_GET_FAIL_FLAG() ((FMC_ISP->ISPCTL & FMC_ISPCTL_ISPFF_Msk) ? 1UL : 0UL) /*!< Get ISP fail flag */
/**
* @brief Clear ISP Fail Flag
*
* @param None
*
* @return None
*
* @details This function is used to clear ISP fail flag when ISP fail flag set.
*
*/
#define FMC_CLR_FAIL_FLAG() (FMC_ISP->ISPCTL |= FMC_ISPCTL_ISPFF_Msk) /*!< Clear ISP fail flag */
/**
* @brief Enable ISP Interrupt
*
* @param None
*
* @return None
*
* @details This function will enable ISP action interrupt.
*
*/
#define FMC_ENABLE_ISP_INT() (FMC_ISP->ISPCTL |= FMC_ISPCTL_INTEN_Msk) /*!< Enable ISP interrupt */
/**
* @brief Disable ISP Interrupt
*
* @param None
*
* @return None
*
* @details This function will disable ISP action interrupt.
*
*/
#define FMC_DISABLE_ISP_INT() (FMC_ISP->ISPCTL &= ~FMC_ISPCTL_INTEN_Msk) /*!< Disable ISP interrupt */
/**
* @brief Get ISP Interrupt Flag
*
* @param None
*
* @return None
*
* @details This function will get ISP action interrupt status
*
*/
#define FMC_GET_ISP_INT_FLAG() ((FMC_ISP->ISPSTS & FMC_ISPSTS_INTFLAG_Msk) ? 1UL : 0UL) /*!< Get ISP interrupt flag Status */
/**
* @brief Clear ISP Interrupt Flag
*
* @param None
*
* @return None
*
* @details This function will clear ISP interrupt flag
*
*/
#define FMC_CLEAR_ISP_INT_FLAG() (FMC_ISP->ISPSTS = FMC_ISPSTS_INTFLAG_Msk) /*!< Clear ISP interrupt flag*/
/**
* @brief Enable Data Flash Scrambling Function
*
* @param None
*
* @return None
*
* @details This function will set SCRAMEN bit of DFCTL control register to enable Data Flash Scrambling Function.
*
*/
#define FMC_ENABLE_SCRAMBLE() (FMC->DFCTL |= FMC_DFCTL_SCRAMEN_Msk) /*!< Enable Data Flash Scrambling Function */
/**
* @brief Disable Data Flash Scrambling Function
*
* @param None
*
* @return None
*
* @details This function will clear SCRAMEN bit of DFCTL control register to disable Data Flash Scrambling Function.
*
*/
#define FMC_DISABLE_SCRAMBLE() (FMC->DFCTL &= ~FMC_DFCTL_SCRAMEN_Msk) /*!< Disable Data Flash Scrambling Function */
/**
* @brief Enable Data Flash Silent Access Function
*
* @param None
*
* @return None
*
* @details This function will set SILENTEN bit of DFCTL control register to enable Data Flash Silent Access Function.
*
*/
#define FMC_ENABLE_SILENT() (FMC->DFCTL |= FMC_DFCTL_SILENTEN_Msk) /*!< Enable Data Flash Silent Access Function */
/**
* @brief Disable Data Flash Silent Access Function
*
* @param None
*
* @return None
*
* @details This function will clear SILENTEN bit of DFCTL control register to disable Data Flash Silent Access Function.
*
*/
#define FMC_DISABLE_SILENT() (FMC->DFCTL &= ~FMC_DFCTL_SILENTEN_Msk) /*!< Disable Data Flash Silent Access Function */
/**
* @brief Enable Data Flash Temper Attack Program Function
*
* @param None
*
* @return None
*
* @details This function will set TMPCLR bit of DFCTL control register to enable Data Flash Temper Attack Program Function.
*
*/
#define FMC_ENABLE_TMPCLR() (FMC->DFCTL |= FMC_DFCTL_TMPCLR_Msk) /*!< Enable Data Flash Temper Attack Program Function */
/**
* @brief Disable Data Flash Temper Attack Program Function
*
* @param None
*
* @return None
*
* @details This function will clear TMPCLR bit of DFCTL control register to disable Data Flash Temper Attack Program Function.
*
*/
#define FMC_DISABLE_TMPCLR() (FMC->DFCTL &= ~FMC_DFCTL_TMPCLR_Msk) /*!< Disable Data Flash Temper Attack Program Function */
/**
* @brief Get Data Flash Temper Attack Programming Done Flag
*
* @param None
*
* @return None
*
* @details This function will get Data Flash Temper Attack Programming Done flag
*
*/
#define FMC_GET_TMPCLRDONE_FLAG() ((FMC->DFSTS & FMC_DFSTS_TMPCLRDONE_Msk) ? 1UL : 0UL) /*!< Get Data Flash Temper Attack Programming Done Flag */
/**
* @brief Get Data Flash Temper Attack Programming Busy Flag
*
* @param None
*
* @return None
*
* @details This function will get Data Flash Temper Attack Programming Busy flag
*
*/
#define FMC_GET_TMPCLRBUSY_FLAG() ((FMC->DFSTS & FMC_DFSTS_TMPCLRBUSY_Msk) ? 1UL : 0UL) /*!< Get Data Flash Temper Attack Programming Busy Flag */
/**
* @brief Clear Data Flash Temper Attack Programming Done Flag
*
* @param None
*
* @return None
*
* @details This function will clear Data Flash Temper Attack Programming Done flag
*
*/
#define FMC_CLEAR_TMPCLRDONE_FLAG() (FMC->DFSTS |= FMC_DFSTS_TMPCLRDONE_Msk) /*!< Clear Data Flash Temper Attack Programming Done Flag */
/*---------------------------------------------------------------------------------------------------------*/
/* inline functions */
/*---------------------------------------------------------------------------------------------------------*/
__STATIC_INLINE uint32_t FMC_ReadCID(void);
__STATIC_INLINE uint32_t FMC_ReadPID(void);
__STATIC_INLINE uint32_t FMC_ReadUID(uint8_t u8Index);
__STATIC_INLINE uint32_t FMC_ReadUCID(uint32_t u32Index);
__STATIC_INLINE void FMC_SetVectorPageAddr(uint32_t u32PageAddr);
__STATIC_INLINE uint32_t FMC_GetVECMAP(void);
__STATIC_INLINE void FMC_SetScrambleKey(uint32_t u32ScrambleKey);
/**
* @brief Get current vector mapping address.
*
* @param None
*
* @return The current vector mapping address.
*
* @details To get VECMAP value which is the page address for remapping to vector page (0x0).
*
*/
__STATIC_INLINE uint32_t FMC_GetVECMAP(void)
{
return (FMC->ISPSTS & FMC_ISPSTS_VECMAP_Msk);
}
/**
* @brief Read company ID
*
* @param None
*
* @return The company ID (32-bit)
*
* @details The company ID of Nuvoton is fixed to be 0xDA
*/
__STATIC_INLINE uint32_t FMC_ReadCID(void)
{
FMC_ISP->ISPCMD = FMC_ISPCMD_READ_CID; /* Set ISP Command Code */
FMC_ISP->ISPADDR = 0x0u; /* Must keep 0x0 when read CID */
FMC_ISP->ISPTRG = FMC_ISPTRG_ISPGO_Msk; /* Trigger to start ISP procedure */
#if ISBEN
__ISB();
#endif /* To make sure ISP/CPU be Synchronized */
while(FMC_ISP->ISPTRG & FMC_ISPTRG_ISPGO_Msk) {} /* Waiting for ISP Done */
return FMC_ISP->ISPDAT;
}
/**
* @brief Read product ID
*
* @param None
*
* @return The product ID (32-bit)
*
* @details This function is used to read product ID.
*/
__STATIC_INLINE uint32_t FMC_ReadPID(void)
{
FMC_ISP->ISPCMD = FMC_ISPCMD_READ_DID; /* Set ISP Command Code */
FMC_ISP->ISPADDR = 0x04u; /* Must keep 0x4 when read PID */
FMC_ISP->ISPTRG = FMC_ISPTRG_ISPGO_Msk; /* Trigger to start ISP procedure */
#if ISBEN
__ISB();
#endif /* To make sure ISP/CPU be Synchronized */
while(FMC_ISP->ISPTRG & FMC_ISPTRG_ISPGO_Msk) {} /* Waiting for ISP Done */
return FMC_ISP->ISPDAT;
}
/**
* @brief Read Unique ID
*
* @param[in] u8Index UID index. 0 = UID[31:0], 1 = UID[63:32], 2 = UID[95:64]
*
* @return The 32-bit unique ID data of specified UID index.
*
* @details To read out 96-bit Unique ID.
*/
__STATIC_INLINE uint32_t FMC_ReadUID(uint8_t u8Index)
{
FMC_ISP->ISPCMD = FMC_ISPCMD_READ_UID;
FMC_ISP->ISPADDR = ((uint32_t)u8Index << 2u);
FMC_ISP->ISPDAT = 0u;
FMC_ISP->ISPTRG = 0x1u;
#if ISBEN
__ISB();
#endif
while(FMC_ISP->ISPTRG) {}
return FMC_ISP->ISPDAT;
}
/**
* @brief To read UCID
*
* @param[in] u32Index Index of the UCID to read. u32Index must be 0, 1, 2, or 3.
*
* @return The UCID of specified index
*
* @details This function is used to read unique chip ID (UCID).
*/
__STATIC_INLINE uint32_t FMC_ReadUCID(uint32_t u32Index)
{
FMC_ISP->ISPCMD = FMC_ISPCMD_READ_UID; /* Set ISP Command Code */
FMC_ISP->ISPADDR = (0x04u * u32Index) + 0x10u; /* The UCID is at offset 0x10 with word alignment. */
FMC_ISP->ISPTRG = FMC_ISPTRG_ISPGO_Msk; /* Trigger to start ISP procedure */
#if ISBEN
__ISB();
#endif /* To make sure ISP/CPU be Synchronized */
while(FMC_ISP->ISPTRG & FMC_ISPTRG_ISPGO_Msk) {} /* Waiting for ISP Done */
return FMC_ISP->ISPDAT;
}
/**
* @brief Set vector mapping address
*
* @param[in] u32PageAddr The page address to remap to address 0x0. The address must be page alignment.
*
* @return To set VECMAP to remap specified page address to 0x0.
*
* @details This function is used to set VECMAP to map specified page to vector page (0x0).
*/
__STATIC_INLINE void FMC_SetVectorPageAddr(uint32_t u32PageAddr)
{
FMC->ISPCMD = FMC_ISPCMD_VECMAP; /* Set ISP Command Code */
FMC->ISPADDR = u32PageAddr; /* The address of specified page which will be map to address 0x0. It must be page alignment. */
FMC->ISPTRG = 0x1u; /* Trigger to start ISP procedure */
#if ISBEN
__ISB();
#endif /* To make sure ISP/CPU be Synchronized */
while(FMC->ISPTRG) {} /* Waiting for ISP Done */
}
/**
* @brief Set Data Flash scrambling key
*
* @param[in] u32ScramKey The value of scrambling key.
*
* @return NULL
*
* @details This function is used to set Data Flash scrambling key.
*/
__STATIC_INLINE void FMC_SetScrambleKey(uint32_t u32ScrambleKey)
{
FMC->SCRKEY = u32ScrambleKey;
}
/*---------------------------------------------------------------------------------------------------------*/
/* Functions */
/*---------------------------------------------------------------------------------------------------------*/
extern uint32_t FMC_CheckAllOne(uint32_t u32addr, uint32_t u32count);
extern void FMC_Close(void);
extern int32_t FMC_ConfigXOM(uint32_t xom_num, uint32_t xom_base, uint8_t xom_page);
extern int32_t FMC_Erase(uint32_t u32PageAddr);
extern int32_t FMC_EraseBank(uint32_t u32BankAddr);
extern int32_t FMC_EraseXOM(uint32_t xom_num);
extern uint32_t FMC_GetChkSum(uint32_t u32addr, uint32_t u32count);
extern int32_t FMC_IsOTPLocked(uint32_t otp_num);
extern int32_t FMC_GetXOMState(uint32_t xom_num);
extern int32_t FMC_LockOTP(uint32_t otp_num);
extern void FMC_Open(void);
extern uint32_t FMC_Read(uint32_t u32Addr);
extern int32_t FMC_Read64(uint32_t u32addr, uint32_t * u32data0, uint32_t * u32data1);
extern int32_t FMC_ReadOTP(uint32_t otp_num, uint32_t *low_word, uint32_t *high_word);
extern int32_t FMC_ReadConfig(uint32_t u32Config[], uint32_t u32Count);
extern void FMC_Write(uint32_t u32Addr, uint32_t u32Data);
extern int32_t FMC_Write8Bytes(uint32_t u32addr, uint32_t u32data0, uint32_t u32data1);
extern int32_t FMC_WriteConfig(uint32_t au32Config[], uint32_t u32Count);
extern int32_t FMC_WriteMultiple(uint32_t u32Addr, uint32_t pu32Buf[], uint32_t u32Len);
extern int32_t FMC_WriteOTP(uint32_t otp_num, uint32_t low_word, uint32_t high_word);
extern int32_t FMC_WriteMultipleA(uint32_t u32Addr, uint32_t pu32Buf[], uint32_t u32Len);
extern int32_t FMC_RemapBank(uint32_t u32Bank);
/**@}*/ /* end of group FMC_EXPORTED_FUNCTIONS */
/**@}*/ /* end of group FMC_Driver */
/**@}*/ /* end of group Standard_Driver */
#ifdef __cplusplus
}
#endif
#endif /* __NU_FMC_H__ */
|
3d9f4c1fcf2d69b01677aa9f930335a610a08a95
|
9819c45475d0cd2dd4748c809e6db173c18bff37
|
/test/invalid_malloc_object_size_small.c
|
33cc78f5055f4d5cfccaad55ab4b3a5e10b9b985
|
[
"MIT"
] |
permissive
|
GrapheneOS/hardened_malloc
|
8fe46cbba026b7d0ad7825eb3111f0a9746a3978
|
2d302f7d85944bcaa1ce6419a4c51732f76daaa6
|
refs/heads/main
| 2023-08-23T21:51:23.120660
| 2023-06-10T18:58:33
| 2023-06-10T18:58:33
| 145,801,335
| 972
| 97
|
MIT
| 2023-09-04T19:37:50
| 2018-08-23T04:43:10
|
C
|
UTF-8
|
C
| false
| false
| 244
|
c
|
invalid_malloc_object_size_small.c
|
#include <stdlib.h>
#include "test_util.h"
size_t malloc_object_size(void *ptr);
OPTNONE int main(void) {
char *p = malloc(16);
if (!p) {
return 1;
}
char *q = p + 4096 * 4;
malloc_object_size(q);
return 0;
}
|
4a7fc72671a0a0d6a82e5b7e672e7a6e307cb7ac
|
89db60818afeb3dc7c3b7abe9ceae155f074f7f2
|
/src/cmd/fossil/9fsys.c
|
121e5b66c34c59ef378f032daaae7f15ccb72a2b
|
[
"bzip2-1.0.6",
"LPL-1.02",
"MIT"
] |
permissive
|
9fans/plan9port
|
63c3d01928c6f8a8617d3ea6ecc05bac72391132
|
65c090346a38a8c30cb242d345aa71060116340c
|
refs/heads/master
| 2023-08-25T17:14:26.233105
| 2023-08-23T13:21:37
| 2023-08-23T18:47:08
| 26,095,474
| 1,645
| 468
|
NOASSERTION
| 2023-09-05T16:55:41
| 2014-11-02T22:40:13
|
C
|
UTF-8
|
C
| false
| false
| 35,143
|
c
|
9fsys.c
|
#include "stdinc.h"
#include <bio.h>
#include "dat.h"
#include "fns.h"
#include "9.h"
struct Fsys {
QLock lock;
char* name; /* copy here & Fs to ease error reporting */
char* dev;
char* venti;
Fs* fs;
VtConn* session;
int ref;
int noauth;
int noperm;
int wstatallow;
Fsys* next;
};
int mempcnt; /* from fossil.c */
int fsGetBlockSize(Fs *fs);
static struct {
RWLock lock;
Fsys* head;
Fsys* tail;
char* curfsys;
} sbox;
static char *_argv0;
#define argv0 _argv0
static char FsysAll[] = "all";
static char EFsysBusy[] = "fsys: '%s' busy";
static char EFsysExists[] = "fsys: '%s' already exists";
static char EFsysNoCurrent[] = "fsys: no current fsys";
static char EFsysNotFound[] = "fsys: '%s' not found";
static char EFsysNotOpen[] = "fsys: '%s' not open";
static char *
ventihost(char *host)
{
if(host != nil)
return vtstrdup(host);
host = getenv("venti");
if(host == nil)
host = vtstrdup("$venti");
return host;
}
static void
prventihost(char *host)
{
char *vh;
vh = ventihost(host);
fprint(2, "%s: dialing venti at %s\n",
argv0, netmkaddr(vh, 0, "venti"));
free(vh);
}
static VtConn *
myDial(char *host)
{
prventihost(host);
return vtdial(host);
}
static int
myRedial(VtConn *z, char *host)
{
prventihost(host);
return vtredial(z, host);
}
static Fsys*
_fsysGet(char* name)
{
Fsys *fsys;
if(name == nil || name[0] == '\0')
name = "main";
rlock(&sbox.lock);
for(fsys = sbox.head; fsys != nil; fsys = fsys->next){
if(strcmp(name, fsys->name) == 0){
fsys->ref++;
break;
}
}
runlock(&sbox.lock);
if(fsys == nil)
werrstr(EFsysNotFound, name);
return fsys;
}
static int
cmdPrintConfig(int argc, char* argv[])
{
Fsys *fsys;
char *usage = "usage: printconfig";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc)
return cliError(usage);
rlock(&sbox.lock);
for(fsys = sbox.head; fsys != nil; fsys = fsys->next){
consPrint("\tfsys %s config %s\n", fsys->name, fsys->dev);
if(fsys->venti && fsys->venti[0])
consPrint("\tfsys %s venti %q\n", fsys->name,
fsys->venti);
}
runlock(&sbox.lock);
return 1;
}
Fsys*
fsysGet(char* name)
{
Fsys *fsys;
if((fsys = _fsysGet(name)) == nil)
return nil;
qlock(&fsys->lock);
if(fsys->fs == nil){
werrstr(EFsysNotOpen, fsys->name);
qunlock(&fsys->lock);
fsysPut(fsys);
return nil;
}
qunlock(&fsys->lock);
return fsys;
}
char*
fsysGetName(Fsys* fsys)
{
return fsys->name;
}
Fsys*
fsysIncRef(Fsys* fsys)
{
wlock(&sbox.lock);
fsys->ref++;
wunlock(&sbox.lock);
return fsys;
}
void
fsysPut(Fsys* fsys)
{
wlock(&sbox.lock);
assert(fsys->ref > 0);
fsys->ref--;
wunlock(&sbox.lock);
}
Fs*
fsysGetFs(Fsys* fsys)
{
assert(fsys != nil && fsys->fs != nil);
return fsys->fs;
}
void
fsysFsRlock(Fsys* fsys)
{
rlock(&fsys->fs->elk);
}
void
fsysFsRUnlock(Fsys* fsys)
{
runlock(&fsys->fs->elk);
}
int
fsysNoAuthCheck(Fsys* fsys)
{
return fsys->noauth;
}
int
fsysNoPermCheck(Fsys* fsys)
{
return fsys->noperm;
}
int
fsysWstatAllow(Fsys* fsys)
{
return fsys->wstatallow;
}
static char modechars[] = "YUGalLdHSATs";
static ulong modebits[] = {
ModeSticky,
ModeSetUid,
ModeSetGid,
ModeAppend,
ModeExclusive,
ModeLink,
ModeDir,
ModeHidden,
ModeSystem,
ModeArchive,
ModeTemporary,
ModeSnapshot,
0
};
char*
fsysModeString(ulong mode, char *buf)
{
int i;
char *p;
p = buf;
for(i=0; modebits[i]; i++)
if(mode & modebits[i])
*p++ = modechars[i];
sprint(p, "%luo", mode&0777);
return buf;
}
int
fsysParseMode(char* s, ulong* mode)
{
ulong x, y;
char *p;
x = 0;
for(; *s < '0' || *s > '9'; s++){
if(*s == 0)
return 0;
p = strchr(modechars, *s);
if(p == nil)
return 0;
x |= modebits[p-modechars];
}
y = strtoul(s, &p, 8);
if(*p != '\0' || y > 0777)
return 0;
*mode = x|y;
return 1;
}
File*
fsysGetRoot(Fsys* fsys, char* name)
{
File *root, *sub;
assert(fsys != nil && fsys->fs != nil);
root = fsGetRoot(fsys->fs);
if(name == nil || strcmp(name, "") == 0)
return root;
sub = fileWalk(root, name);
fileDecRef(root);
return sub;
}
static Fsys*
fsysAlloc(char* name, char* dev)
{
Fsys *fsys;
wlock(&sbox.lock);
for(fsys = sbox.head; fsys != nil; fsys = fsys->next){
if(strcmp(fsys->name, name) != 0)
continue;
werrstr(EFsysExists, name);
wunlock(&sbox.lock);
return nil;
}
fsys = vtmallocz(sizeof(Fsys));
fsys->name = vtstrdup(name);
fsys->dev = vtstrdup(dev);
fsys->ref = 1;
if(sbox.tail != nil)
sbox.tail->next = fsys;
else
sbox.head = fsys;
sbox.tail = fsys;
wunlock(&sbox.lock);
return fsys;
}
static int
fsysClose(Fsys* fsys, int argc, char* argv[])
{
char *usage = "usage: [fsys name] close";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc)
return cliError(usage);
return cliError("close isn't working yet; halt %s and then kill fossil",
fsys->name);
/*
* Oooh. This could be hard. What if fsys->ref != 1?
* Also, fsClose() either does the job or panics, can we
* gracefully detect it's still busy?
*
* More thought and care needed here.
fsClose(fsys->fs);
fsys->fs = nil;
vtfreeconn(fsys->session);
fsys->session = nil;
if(sbox.curfsys != nil && strcmp(fsys->name, sbox.curfsys) == 0){
sbox.curfsys = nil;
consPrompt(nil);
}
return 1;
*/
}
static int
fsysVac(Fsys* fsys, int argc, char* argv[])
{
uchar score[VtScoreSize];
char *usage = "usage: [fsys name] vac path";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc != 1)
return cliError(usage);
if(!fsVac(fsys->fs, argv[0], score))
return 0;
consPrint("vac:%V\n", score);
return 1;
}
static int
fsysSnap(Fsys* fsys, int argc, char* argv[])
{
int doarchive;
char *usage = "usage: [fsys name] snap [-a] [-s /active] [-d /archive/yyyy/mmmm]";
char *src, *dst;
src = nil;
dst = nil;
doarchive = 0;
ARGBEGIN{
default:
return cliError(usage);
case 'a':
doarchive = 1;
break;
case 'd':
if((dst = ARGF()) == nil)
return cliError(usage);
break;
case 's':
if((src = ARGF()) == nil)
return cliError(usage);
break;
}ARGEND
if(argc)
return cliError(usage);
if(!fsSnapshot(fsys->fs, src, dst, doarchive))
return 0;
return 1;
}
static int
fsysSnapClean(Fsys *fsys, int argc, char* argv[])
{
u32int arch, snap, life;
char *usage = "usage: [fsys name] snapclean [maxminutes]\n";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc > 1)
return cliError(usage);
if(argc == 1)
life = atoi(argv[0]);
else
snapGetTimes(fsys->fs->snap, &arch, &snap, &life);
fsSnapshotCleanup(fsys->fs, life);
return 1;
}
static int
fsysSnapTime(Fsys* fsys, int argc, char* argv[])
{
char buf[128], *x;
int hh, mm, changed;
u32int arch, snap, life;
char *usage = "usage: [fsys name] snaptime [-a hhmm] [-s snapminutes] [-t maxminutes]";
changed = 0;
snapGetTimes(fsys->fs->snap, &arch, &snap, &life);
ARGBEGIN{
case 'a':
changed = 1;
x = ARGF();
if(x == nil)
return cliError(usage);
if(strcmp(x, "none") == 0){
arch = ~(u32int)0;
break;
}
if(strlen(x) != 4 || strspn(x, "0123456789") != 4)
return cliError(usage);
hh = (x[0]-'0')*10 + x[1]-'0';
mm = (x[2]-'0')*10 + x[3]-'0';
if(hh >= 24 || mm >= 60)
return cliError(usage);
arch = hh*60+mm;
break;
case 's':
changed = 1;
x = ARGF();
if(x == nil)
return cliError(usage);
if(strcmp(x, "none") == 0){
snap = ~(u32int)0;
break;
}
snap = atoi(x);
break;
case 't':
changed = 1;
x = ARGF();
if(x == nil)
return cliError(usage);
if(strcmp(x, "none") == 0){
life = ~(u32int)0;
break;
}
life = atoi(x);
break;
default:
return cliError(usage);
}ARGEND
if(argc > 0)
return cliError(usage);
if(changed){
snapSetTimes(fsys->fs->snap, arch, snap, life);
return 1;
}
snapGetTimes(fsys->fs->snap, &arch, &snap, &life);
if(arch != ~(u32int)0)
sprint(buf, "-a %02d%02d", arch/60, arch%60);
else
sprint(buf, "-a none");
if(snap != ~(u32int)0)
sprint(buf+strlen(buf), " -s %d", snap);
else
sprint(buf+strlen(buf), " -s none");
if(life != ~(u32int)0)
sprint(buf+strlen(buf), " -t %ud", life);
else
sprint(buf+strlen(buf), " -t none");
consPrint("\tsnaptime %s\n", buf);
return 1;
}
static int
fsysSync(Fsys* fsys, int argc, char* argv[])
{
char *usage = "usage: [fsys name] sync";
int n;
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc > 0)
return cliError(usage);
n = cacheDirty(fsys->fs->cache);
fsSync(fsys->fs);
consPrint("\t%s sync: wrote %d blocks\n", fsys->name, n);
return 1;
}
static int
fsysHalt(Fsys *fsys, int argc, char* argv[])
{
char *usage = "usage: [fsys name] halt";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc > 0)
return cliError(usage);
fsHalt(fsys->fs);
return 1;
}
static int
fsysUnhalt(Fsys *fsys, int argc, char* argv[])
{
char *usage = "usage: [fsys name] unhalt";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc > 0)
return cliError(usage);
if(!fsys->fs->halted)
return cliError("file system %s not halted", fsys->name);
fsUnhalt(fsys->fs);
return 1;
}
static int
fsysRemove(Fsys* fsys, int argc, char* argv[])
{
File *file;
char *usage = "usage: [fsys name] remove path ...";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc == 0)
return cliError(usage);
rlock(&fsys->fs->elk);
while(argc > 0){
if((file = fileOpen(fsys->fs, argv[0])) == nil)
consPrint("%s: %r\n", argv[0]);
else{
if(!fileRemove(file, uidadm))
consPrint("%s: %r\n", argv[0]);
fileDecRef(file);
}
argc--;
argv++;
}
runlock(&fsys->fs->elk);
return 1;
}
static int
fsysClri(Fsys* fsys, int argc, char* argv[])
{
char *usage = "usage: [fsys name] clri path ...";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc == 0)
return cliError(usage);
rlock(&fsys->fs->elk);
while(argc > 0){
if(!fileClriPath(fsys->fs, argv[0], uidadm))
consPrint("clri %s: %r\n", argv[0]);
argc--;
argv++;
}
runlock(&fsys->fs->elk);
return 1;
}
/*
* Inspect and edit the labels for blocks on disk.
*/
static int
fsysLabel(Fsys* fsys, int argc, char* argv[])
{
Fs *fs;
Label l;
int n, r;
u32int addr;
Block *b, *bb;
char *usage = "usage: [fsys name] label addr [type state epoch epochClose tag]";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc != 1 && argc != 6)
return cliError(usage);
r = 0;
rlock(&fsys->fs->elk);
fs = fsys->fs;
addr = strtoul(argv[0], 0, 0);
b = cacheLocal(fs->cache, PartData, addr, OReadOnly);
if(b == nil)
goto Out0;
l = b->l;
consPrint("%slabel %#ux %ud %ud %ud %ud %#x\n",
argc==6 ? "old: " : "", addr, l.type, l.state,
l.epoch, l.epochClose, l.tag);
if(argc == 6){
if(strcmp(argv[1], "-") != 0)
l.type = atoi(argv[1]);
if(strcmp(argv[2], "-") != 0)
l.state = atoi(argv[2]);
if(strcmp(argv[3], "-") != 0)
l.epoch = strtoul(argv[3], 0, 0);
if(strcmp(argv[4], "-") != 0)
l.epochClose = strtoul(argv[4], 0, 0);
if(strcmp(argv[5], "-") != 0)
l.tag = strtoul(argv[5], 0, 0);
consPrint("new: label %#ux %ud %ud %ud %ud %#x\n",
addr, l.type, l.state, l.epoch, l.epochClose, l.tag);
bb = _blockSetLabel(b, &l);
if(bb == nil)
goto Out1;
n = 0;
for(;;){
if(blockWrite(bb, Waitlock)){
while(bb->iostate != BioClean){
assert(bb->iostate == BioWriting);
rsleep(&bb->ioready);
}
break;
}
consPrint("blockWrite: %r\n");
if(n++ >= 5){
consPrint("giving up\n");
break;
}
sleep(5*1000);
}
blockPut(bb);
}
r = 1;
Out1:
blockPut(b);
Out0:
runlock(&fs->elk);
return r;
}
/*
* Inspect and edit the blocks on disk.
*/
static int
fsysBlock(Fsys* fsys, int argc, char* argv[])
{
Fs *fs;
char *s;
Block *b;
uchar *buf;
u32int addr;
int c, count, i, offset;
char *usage = "usage: [fsys name] block addr offset [count [data]]";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc < 2 || argc > 4)
return cliError(usage);
fs = fsys->fs;
addr = strtoul(argv[0], 0, 0);
offset = strtoul(argv[1], 0, 0);
if(offset < 0 || offset >= fs->blockSize){
werrstr("bad offset");
return 0;
}
if(argc > 2)
count = strtoul(argv[2], 0, 0);
else
count = 100000000;
if(offset+count > fs->blockSize)
count = fs->blockSize - count;
rlock(&fs->elk);
b = cacheLocal(fs->cache, PartData, addr, argc==4 ? OReadWrite : OReadOnly);
if(b == nil){
werrstr("cacheLocal %#ux: %r", addr);
runlock(&fs->elk);
return 0;
}
consPrint("\t%sblock %#ux %ud %ud %.*H\n",
argc==4 ? "old: " : "", addr, offset, count, count, b->data+offset);
if(argc == 4){
s = argv[3];
if(strlen(s) != 2*count){
werrstr("bad data count");
goto Out;
}
buf = vtmallocz(count);
for(i = 0; i < count*2; i++){
if(s[i] >= '0' && s[i] <= '9')
c = s[i] - '0';
else if(s[i] >= 'a' && s[i] <= 'f')
c = s[i] - 'a' + 10;
else if(s[i] >= 'A' && s[i] <= 'F')
c = s[i] - 'A' + 10;
else{
werrstr("bad hex");
vtfree(buf);
goto Out;
}
if((i & 1) == 0)
c <<= 4;
buf[i>>1] |= c;
}
memmove(b->data+offset, buf, count);
consPrint("\tnew: block %#ux %ud %ud %.*H\n",
addr, offset, count, count, b->data+offset);
blockDirty(b);
}
Out:
blockPut(b);
runlock(&fs->elk);
return 1;
}
/*
* Free a disk block.
*/
static int
fsysBfree(Fsys* fsys, int argc, char* argv[])
{
Fs *fs;
Label l;
char *p;
Block *b;
u32int addr;
char *usage = "usage: [fsys name] bfree addr ...";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc == 0)
return cliError(usage);
fs = fsys->fs;
rlock(&fs->elk);
while(argc > 0){
addr = strtoul(argv[0], &p, 0);
if(*p != '\0'){
consPrint("bad address - '%ud'\n", addr);
/* syntax error; let's stop */
runlock(&fs->elk);
return 0;
}
b = cacheLocal(fs->cache, PartData, addr, OReadOnly);
if(b == nil){
consPrint("loading %#ux: %r\n", addr);
continue;
}
l = b->l;
if(l.state == BsFree)
consPrint("%#ux is already free\n", addr);
else{
consPrint("label %#ux %ud %ud %ud %ud %#x\n",
addr, l.type, l.state, l.epoch, l.epochClose, l.tag);
l.state = BsFree;
l.type = BtMax;
l.tag = 0;
l.epoch = 0;
l.epochClose = 0;
if(!blockSetLabel(b, &l, 0))
consPrint("freeing %#ux: %r\n", addr);
}
blockPut(b);
argc--;
argv++;
}
runlock(&fs->elk);
return 1;
}
static int
fsysDf(Fsys *fsys, int argc, char* argv[])
{
char *usage = "usage: [fsys name] df";
u32int used, tot, bsize;
Fs *fs;
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc != 0)
return cliError(usage);
fs = fsys->fs;
cacheCountUsed(fs->cache, fs->elo, &used, &tot, &bsize);
consPrint("\t%s: %,llud used + %,llud free = %,llud (%.1f%% used)\n",
fsys->name, used*(vlong)bsize, (tot-used)*(vlong)bsize,
tot*(vlong)bsize, used*100.0/tot);
return 1;
}
/*
* Zero an entry or a pointer.
*/
static int
fsysClrep(Fsys* fsys, int argc, char* argv[], int ch)
{
Fs *fs;
Entry e;
Block *b;
u32int addr;
int i, max, offset, sz;
uchar zero[VtEntrySize];
char *usage = "usage: [fsys name] clr%c addr offset ...";
ARGBEGIN{
default:
return cliError(usage, ch);
}ARGEND
if(argc < 2)
return cliError(usage, ch);
fs = fsys->fs;
rlock(&fsys->fs->elk);
addr = strtoul(argv[0], 0, 0);
b = cacheLocal(fs->cache, PartData, addr, argc==4 ? OReadWrite : OReadOnly);
if(b == nil){
werrstr("cacheLocal %#ux: %r", addr);
Err:
runlock(&fsys->fs->elk);
return 0;
}
switch(ch){
default:
werrstr("clrep");
goto Err;
case 'e':
if(b->l.type != BtDir){
werrstr("wrong block type");
goto Err;
}
sz = VtEntrySize;
memset(&e, 0, sizeof e);
entryPack(&e, zero, 0);
break;
case 'p':
if(b->l.type == BtDir || b->l.type == BtData){
werrstr("wrong block type");
goto Err;
}
sz = VtScoreSize;
memmove(zero, vtzeroscore, VtScoreSize);
break;
}
max = fs->blockSize/sz;
for(i = 1; i < argc; i++){
offset = atoi(argv[i]);
if(offset >= max){
consPrint("\toffset %d too large (>= %d)\n", i, max);
continue;
}
consPrint("\tblock %#ux %d %d %.*H\n", addr, offset*sz, sz, sz, b->data+offset*sz);
memmove(b->data+offset*sz, zero, sz);
}
blockDirty(b);
blockPut(b);
runlock(&fsys->fs->elk);
return 1;
}
static int
fsysClre(Fsys* fsys, int argc, char* argv[])
{
return fsysClrep(fsys, argc, argv, 'e');
}
static int
fsysClrp(Fsys* fsys, int argc, char* argv[])
{
return fsysClrep(fsys, argc, argv, 'p');
}
static int
fsysEsearch1(File* f, char* s, u32int elo)
{
int n, r;
DirEntry de;
DirEntryEnum *dee;
File *ff;
Entry e, ee;
char *t;
dee = deeOpen(f);
if(dee == nil)
return 0;
n = 0;
for(;;){
r = deeRead(dee, &de);
if(r < 0){
consPrint("\tdeeRead %s/%s: %r\n", s, de.elem);
break;
}
if(r == 0)
break;
if(de.mode & ModeSnapshot){
if((ff = fileWalk(f, de.elem)) == nil)
consPrint("\tcannot walk %s/%s: %r\n", s, de.elem);
else{
if(!fileGetSources(ff, &e, &ee))
consPrint("\tcannot get sources for %s/%s: %r\n", s, de.elem);
else if(e.snap != 0 && e.snap < elo){
consPrint("\t%ud\tclri %s/%s\n", e.snap, s, de.elem);
n++;
}
fileDecRef(ff);
}
}
else if(de.mode & ModeDir){
if((ff = fileWalk(f, de.elem)) == nil)
consPrint("\tcannot walk %s/%s: %r\n", s, de.elem);
else{
t = smprint("%s/%s", s, de.elem);
n += fsysEsearch1(ff, t, elo);
vtfree(t);
fileDecRef(ff);
}
}
deCleanup(&de);
if(r < 0)
break;
}
deeClose(dee);
return n;
}
static int
fsysEsearch(Fs* fs, char* path, u32int elo)
{
int n;
File *f;
DirEntry de;
f = fileOpen(fs, path);
if(f == nil)
return 0;
if(!fileGetDir(f, &de)){
consPrint("\tfileGetDir %s failed: %r\n", path);
fileDecRef(f);
return 0;
}
if((de.mode & ModeDir) == 0){
fileDecRef(f);
deCleanup(&de);
return 0;
}
deCleanup(&de);
n = fsysEsearch1(f, path, elo);
fileDecRef(f);
return n;
}
static int
fsysEpoch(Fsys* fsys, int argc, char* argv[])
{
Fs *fs;
int force, n, remove;
u32int low, old;
char *usage = "usage: [fsys name] epoch [[-ry] low]";
force = 0;
remove = 0;
ARGBEGIN{
case 'y':
force = 1;
break;
case 'r':
remove = 1;
break;
default:
return cliError(usage);
}ARGEND
if(argc > 1)
return cliError(usage);
if(argc > 0)
low = strtoul(argv[0], 0, 0);
else
low = ~(u32int)0;
if(low == 0)
return cliError("low epoch cannot be zero");
fs = fsys->fs;
rlock(&fs->elk);
consPrint("\tlow %ud hi %ud\n", fs->elo, fs->ehi);
if(low == ~(u32int)0){
runlock(&fs->elk);
return 1;
}
n = fsysEsearch(fsys->fs, "/archive", low);
n += fsysEsearch(fsys->fs, "/snapshot", low);
consPrint("\t%d snapshot%s found with epoch < %ud\n", n, n==1 ? "" : "s", low);
runlock(&fs->elk);
/*
* There's a small race here -- a new snapshot with epoch < low might
* get introduced now that we unlocked fs->elk. Low has to
* be <= fs->ehi. Of course, in order for this to happen low has
* to be equal to the current fs->ehi _and_ a snapshot has to
* run right now. This is a small enough window that I don't care.
*/
if(n != 0 && !force){
consPrint("\tnot setting low epoch\n");
return 1;
}
old = fs->elo;
if(!fsEpochLow(fs, low))
consPrint("\tfsEpochLow: %r\n");
else{
consPrint("\told: epoch%s %ud\n", force ? " -y" : "", old);
consPrint("\tnew: epoch%s %ud\n", force ? " -y" : "", fs->elo);
if(fs->elo < low)
consPrint("\twarning: new low epoch < old low epoch\n");
if(force && remove)
fsSnapshotRemove(fs);
}
return 1;
}
static int
fsysCreate(Fsys* fsys, int argc, char* argv[])
{
int r;
ulong mode;
char *elem, *p, *path;
char *usage = "usage: [fsys name] create path uid gid perm";
DirEntry de;
File *file, *parent;
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc != 4)
return cliError(usage);
if(!fsysParseMode(argv[3], &mode))
return cliError(usage);
if(mode&ModeSnapshot)
return cliError("create - cannot create with snapshot bit set");
if(strcmp(argv[1], uidnoworld) == 0)
return cliError("permission denied");
rlock(&fsys->fs->elk);
path = vtstrdup(argv[0]);
if((p = strrchr(path, '/')) != nil){
*p++ = '\0';
elem = p;
p = path;
if(*p == '\0')
p = "/";
}
else{
p = "/";
elem = path;
}
r = 0;
if((parent = fileOpen(fsys->fs, p)) == nil)
goto out;
file = fileCreate(parent, elem, mode, argv[1]);
fileDecRef(parent);
if(file == nil){
werrstr("create %s/%s: %r", p, elem);
goto out;
}
if(!fileGetDir(file, &de)){
werrstr("stat failed after create: %r");
goto out1;
}
if(strcmp(de.gid, argv[2]) != 0){
vtfree(de.gid);
de.gid = vtstrdup(argv[2]);
if(!fileSetDir(file, &de, argv[1])){
werrstr("wstat failed after create: %r");
goto out2;
}
}
r = 1;
out2:
deCleanup(&de);
out1:
fileDecRef(file);
out:
vtfree(path);
runlock(&fsys->fs->elk);
return r;
}
static void
fsysPrintStat(char *prefix, char *file, DirEntry *de)
{
char buf[64];
if(prefix == nil)
prefix = "";
consPrint("%sstat %q %q %q %q %s %llud\n", prefix,
file, de->elem, de->uid, de->gid, fsysModeString(de->mode, buf), de->size);
}
static int
fsysStat(Fsys* fsys, int argc, char* argv[])
{
int i;
File *f;
DirEntry de;
char *usage = "usage: [fsys name] stat files...";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc == 0)
return cliError(usage);
rlock(&fsys->fs->elk);
for(i=0; i<argc; i++){
if((f = fileOpen(fsys->fs, argv[i])) == nil){
consPrint("%s: %r\n", argv[i]);
continue;
}
if(!fileGetDir(f, &de)){
consPrint("%s: %r\n", argv[i]);
fileDecRef(f);
continue;
}
fsysPrintStat("\t", argv[i], &de);
deCleanup(&de);
fileDecRef(f);
}
runlock(&fsys->fs->elk);
return 1;
}
static int
fsysWstat(Fsys *fsys, int argc, char* argv[])
{
File *f;
char *p;
DirEntry de;
char *usage = "usage: [fsys name] wstat file elem uid gid mode length\n"
"\tuse - for any field to mean don't change";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc != 6)
return cliError(usage);
rlock(&fsys->fs->elk);
if((f = fileOpen(fsys->fs, argv[0])) == nil){
werrstr("console wstat - walk - %r");
runlock(&fsys->fs->elk);
return 0;
}
if(!fileGetDir(f, &de)){
werrstr("console wstat - stat - %r");
fileDecRef(f);
runlock(&fsys->fs->elk);
return 0;
}
fsysPrintStat("\told: w", argv[0], &de);
if(strcmp(argv[1], "-") != 0){
if(!validFileName(argv[1])){
werrstr("console wstat - bad elem");
goto error;
}
vtfree(de.elem);
de.elem = vtstrdup(argv[1]);
}
if(strcmp(argv[2], "-") != 0){
if(!validUserName(argv[2])){
werrstr("console wstat - bad uid");
goto error;
}
vtfree(de.uid);
de.uid = vtstrdup(argv[2]);
}
if(strcmp(argv[3], "-") != 0){
if(!validUserName(argv[3])){
werrstr("console wstat - bad gid");
goto error;
}
vtfree(de.gid);
de.gid = vtstrdup(argv[3]);
}
if(strcmp(argv[4], "-") != 0){
if(!fsysParseMode(argv[4], &de.mode)){
werrstr("console wstat - bad mode");
goto error;
}
}
if(strcmp(argv[5], "-") != 0){
de.size = strtoull(argv[5], &p, 0);
if(argv[5][0] == '\0' || *p != '\0' || (vlong)de.size < 0){
werrstr("console wstat - bad length");
goto error;
}
}
if(!fileSetDir(f, &de, uidadm)){
werrstr("console wstat - %r");
goto error;
}
deCleanup(&de);
if(!fileGetDir(f, &de)){
werrstr("console wstat - stat2 - %r");
goto error;
}
fsysPrintStat("\tnew: w", argv[0], &de);
deCleanup(&de);
fileDecRef(f);
runlock(&fsys->fs->elk);
return 1;
error:
deCleanup(&de); /* okay to do this twice */
fileDecRef(f);
runlock(&fsys->fs->elk);
return 0;
}
static void
fsckClri(Fsck *fsck, char *name, MetaBlock *mb, int i, Block *b)
{
USED(name);
if((fsck->flags&DoClri) == 0)
return;
mbDelete(mb, i);
mbPack(mb);
blockDirty(b);
}
static void
fsckClose(Fsck *fsck, Block *b, u32int epoch)
{
Label l;
if((fsck->flags&DoClose) == 0)
return;
l = b->l;
if(l.state == BsFree || (l.state&BsClosed)){
consPrint("%#ux is already closed\n", b->addr);
return;
}
if(epoch){
l.state |= BsClosed;
l.epochClose = epoch;
}else
l.state = BsFree;
if(!blockSetLabel(b, &l, 0))
consPrint("%#ux setlabel: %r\n", b->addr);
}
static void
fsckClre(Fsck *fsck, Block *b, int offset)
{
Entry e;
if((fsck->flags&DoClre) == 0)
return;
if(offset<0 || offset*VtEntrySize >= fsck->bsize){
consPrint("bad clre\n");
return;
}
memset(&e, 0, sizeof e);
entryPack(&e, b->data, offset);
blockDirty(b);
}
static void
fsckClrp(Fsck *fsck, Block *b, int offset)
{
if((fsck->flags&DoClrp) == 0)
return;
if(offset<0 || offset*VtScoreSize >= fsck->bsize){
consPrint("bad clre\n");
return;
}
memmove(b->data+offset*VtScoreSize, vtzeroscore, VtScoreSize);
blockDirty(b);
}
static int
fsysCheck(Fsys *fsys, int argc, char *argv[])
{
int i, halting;
char *usage = "usage: [fsys name] check [-v] [options]";
Fsck fsck;
Block *b;
Super super;
memset(&fsck, 0, sizeof fsck);
fsck.fs = fsys->fs;
fsck.clri = fsckClri;
fsck.clre = fsckClre;
fsck.clrp = fsckClrp;
fsck.close = fsckClose;
fsck.print = consPrint;
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
for(i=0; i<argc; i++){
if(strcmp(argv[i], "pblock") == 0)
fsck.printblocks = 1;
else if(strcmp(argv[i], "pdir") == 0)
fsck.printdirs = 1;
else if(strcmp(argv[i], "pfile") == 0)
fsck.printfiles = 1;
else if(strcmp(argv[i], "bclose") == 0)
fsck.flags |= DoClose;
else if(strcmp(argv[i], "clri") == 0)
fsck.flags |= DoClri;
else if(strcmp(argv[i], "clre") == 0)
fsck.flags |= DoClre;
else if(strcmp(argv[i], "clrp") == 0)
fsck.flags |= DoClrp;
else if(strcmp(argv[i], "fix") == 0)
fsck.flags |= DoClose|DoClri|DoClre|DoClrp;
else if(strcmp(argv[i], "venti") == 0)
fsck.useventi = 1;
else if(strcmp(argv[i], "snapshot") == 0)
fsck.walksnapshots = 1;
else{
consPrint("unknown option '%s'\n", argv[i]);
return cliError(usage);
}
}
halting = fsys->fs->halted==0;
if(halting)
fsHalt(fsys->fs);
if(fsys->fs->arch){
b = superGet(fsys->fs->cache, &super);
if(b == nil){
consPrint("could not load super block\n");
goto Out;
}
blockPut(b);
if(super.current != NilBlock){
consPrint("cannot check fs while archiver is running; "
"wait for it to finish\n");
goto Out;
}
}
fsCheck(&fsck);
consPrint("fsck: %d clri, %d clre, %d clrp, %d bclose\n",
fsck.nclri, fsck.nclre, fsck.nclrp, fsck.nclose);
Out:
if(halting)
fsUnhalt(fsys->fs);
return 1;
}
static int
fsysVenti(char* name, int argc, char* argv[])
{
int r;
char *host;
char *usage = "usage: [fsys name] venti [address]";
Fsys *fsys;
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc == 0)
host = nil;
else if(argc == 1)
host = argv[0];
else
return cliError(usage);
if((fsys = _fsysGet(name)) == nil)
return 0;
qlock(&fsys->lock);
if(host == nil)
host = fsys->venti;
else{
vtfree(fsys->venti);
if(host[0])
fsys->venti = vtstrdup(host);
else{
host = nil;
fsys->venti = nil;
}
}
/* already open: do a redial */
if(fsys->fs != nil){
if(fsys->session == nil){
werrstr("file system was opened with -V");
r = 0;
goto out;
}
r = 1;
if(myRedial(fsys->session, host) < 0
|| vtconnect(fsys->session) < 0)
r = 0;
goto out;
}
/* not yet open: try to dial */
if(fsys->session)
vtfreeconn(fsys->session);
r = 1;
if((fsys->session = myDial(host)) == nil
|| vtconnect(fsys->session) < 0)
r = 0;
out:
qunlock(&fsys->lock);
fsysPut(fsys);
return r;
}
static ulong
freemem(void)
{
int nf, pgsize = 0;
uvlong size, userpgs = 0, userused = 0;
char *ln, *sl;
char *fields[2];
Biobuf *bp;
size = 64*1024*1024;
bp = Bopen("#c/swap", OREAD);
if (bp != nil) {
while ((ln = Brdline(bp, '\n')) != nil) {
ln[Blinelen(bp)-1] = '\0';
nf = tokenize(ln, fields, nelem(fields));
if (nf != 2)
continue;
if (strcmp(fields[1], "pagesize") == 0)
pgsize = atoi(fields[0]);
else if (strcmp(fields[1], "user") == 0) {
sl = strchr(fields[0], '/');
if (sl == nil)
continue;
userpgs = atoll(sl+1);
userused = atoll(fields[0]);
}
}
Bterm(bp);
if (pgsize > 0 && userpgs > 0)
size = (userpgs - userused) * pgsize;
}
/* cap it to keep the size within 32 bits */
if (size >= 3840UL * 1024 * 1024)
size = 3840UL * 1024 * 1024;
return size;
}
static int
fsysOpen(char* name, int argc, char* argv[])
{
char *p, *host;
Fsys *fsys;
int noauth, noventi, noperm, rflag, wstatallow, noatimeupd;
long ncache;
char *usage = "usage: fsys name open [-APVWr] [-c ncache]";
ncache = 1000;
noauth = noperm = wstatallow = noventi = noatimeupd = 0;
rflag = OReadWrite;
ARGBEGIN{
default:
return cliError(usage);
case 'A':
noauth = 1;
break;
case 'P':
noperm = 1;
break;
case 'V':
noventi = 1;
break;
case 'W':
wstatallow = 1;
break;
case 'a':
noatimeupd = 1;
break;
case 'c':
p = ARGF();
if(p == nil)
return cliError(usage);
ncache = strtol(argv[0], &p, 0);
if(ncache <= 0 || p == argv[0] || *p != '\0')
return cliError(usage);
break;
case 'r':
rflag = OReadOnly;
break;
}ARGEND
if(argc)
return cliError(usage);
if((fsys = _fsysGet(name)) == nil)
return 0;
/* automatic memory sizing? */
if(mempcnt > 0) {
/* TODO: 8K is a hack; use the actual block size */
ncache = (((vlong)freemem() * mempcnt) / 100) / (8*1024);
if (ncache < 100)
ncache = 100;
}
qlock(&fsys->lock);
if(fsys->fs != nil){
werrstr(EFsysBusy, fsys->name);
qunlock(&fsys->lock);
fsysPut(fsys);
return 0;
}
if(noventi){
if(fsys->session){
vtfreeconn(fsys->session);
fsys->session = nil;
}
}
else if(fsys->session == nil){
if(fsys->venti && fsys->venti[0])
host = fsys->venti;
else
host = nil;
if((fsys->session = myDial(host)) == nil
|| vtconnect(fsys->session) < 0 && !noventi)
fprint(2, "warning: connecting to venti: %r\n");
}
if((fsys->fs = fsOpen(fsys->dev, fsys->session, ncache, rflag)) == nil){
werrstr("fsOpen: %r");
qunlock(&fsys->lock);
fsysPut(fsys);
return 0;
}
fsys->fs->name = fsys->name; /* for better error messages */
fsys->noauth = noauth;
fsys->noperm = noperm;
fsys->wstatallow = wstatallow;
fsys->fs->noatimeupd = noatimeupd;
qunlock(&fsys->lock);
fsysPut(fsys);
if(strcmp(name, "main") == 0)
usersFileRead(nil);
return 1;
}
static int
fsysUnconfig(char* name, int argc, char* argv[])
{
Fsys *fsys, **fp;
char *usage = "usage: fsys name unconfig";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc)
return cliError(usage);
wlock(&sbox.lock);
fp = &sbox.head;
for(fsys = *fp; fsys != nil; fsys = fsys->next){
if(strcmp(fsys->name, name) == 0)
break;
fp = &fsys->next;
}
if(fsys == nil){
werrstr(EFsysNotFound, name);
wunlock(&sbox.lock);
return 0;
}
if(fsys->ref != 0 || fsys->fs != nil){
werrstr(EFsysBusy, fsys->name);
wunlock(&sbox.lock);
return 0;
}
*fp = fsys->next;
wunlock(&sbox.lock);
if(fsys->session != nil)
vtfreeconn(fsys->session);
if(fsys->venti != nil)
vtfree(fsys->venti);
if(fsys->dev != nil)
vtfree(fsys->dev);
if(fsys->name != nil)
vtfree(fsys->name);
vtfree(fsys);
return 1;
}
static int
fsysConfig(char* name, int argc, char* argv[])
{
Fsys *fsys;
char *part;
char *usage = "usage: fsys name config [dev]";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc > 1)
return cliError(usage);
if(argc == 0)
part = foptname;
else
part = argv[0];
if((fsys = _fsysGet(part)) != nil){
qlock(&fsys->lock);
if(fsys->fs != nil){
werrstr(EFsysBusy, fsys->name);
qunlock(&fsys->lock);
fsysPut(fsys);
return 0;
}
vtfree(fsys->dev);
fsys->dev = vtstrdup(part);
qunlock(&fsys->lock);
}
else if((fsys = fsysAlloc(name, part)) == nil)
return 0;
fsysPut(fsys);
return 1;
}
static struct {
char* cmd;
int (*f)(Fsys*, int, char**);
int (*f1)(char*, int, char**);
} fsyscmd[] = {
{ "close", fsysClose, },
{ "config", nil, fsysConfig, },
{ "open", nil, fsysOpen, },
{ "unconfig", nil, fsysUnconfig, },
{ "venti", nil, fsysVenti, },
{ "bfree", fsysBfree, },
{ "block", fsysBlock, },
{ "check", fsysCheck, },
{ "clre", fsysClre, },
{ "clri", fsysClri, },
{ "clrp", fsysClrp, },
{ "create", fsysCreate, },
{ "df", fsysDf, },
{ "epoch", fsysEpoch, },
{ "halt", fsysHalt, },
{ "label", fsysLabel, },
{ "remove", fsysRemove, },
{ "snap", fsysSnap, },
{ "snaptime", fsysSnapTime, },
{ "snapclean", fsysSnapClean, },
{ "stat", fsysStat, },
{ "sync", fsysSync, },
{ "unhalt", fsysUnhalt, },
{ "wstat", fsysWstat, },
{ "vac", fsysVac, },
{ nil, nil, },
};
static int
fsysXXX1(Fsys *fsys, int i, int argc, char* argv[])
{
int r;
qlock(&fsys->lock);
if(fsys->fs == nil){
qunlock(&fsys->lock);
werrstr(EFsysNotOpen, fsys->name);
return 0;
}
if(fsys->fs->halted
&& fsyscmd[i].f != fsysUnhalt && fsyscmd[i].f != fsysCheck){
werrstr("file system %s is halted", fsys->name);
qunlock(&fsys->lock);
return 0;
}
r = (*fsyscmd[i].f)(fsys, argc, argv);
qunlock(&fsys->lock);
return r;
}
static int
fsysXXX(char* name, int argc, char* argv[])
{
int i, r;
Fsys *fsys;
for(i = 0; fsyscmd[i].cmd != nil; i++){
if(strcmp(fsyscmd[i].cmd, argv[0]) == 0)
break;
}
if(fsyscmd[i].cmd == nil){
werrstr("unknown command - '%s'", argv[0]);
return 0;
}
/* some commands want the name... */
if(fsyscmd[i].f1 != nil){
if(strcmp(name, FsysAll) == 0){
werrstr("cannot use fsys %#q with %#q command", FsysAll, argv[0]);
return 0;
}
return (*fsyscmd[i].f1)(name, argc, argv);
}
/* ... but most commands want the Fsys */
if(strcmp(name, FsysAll) == 0){
r = 1;
rlock(&sbox.lock);
for(fsys = sbox.head; fsys != nil; fsys = fsys->next){
fsys->ref++;
r = fsysXXX1(fsys, i, argc, argv) && r;
fsys->ref--;
}
runlock(&sbox.lock);
}else{
if((fsys = _fsysGet(name)) == nil)
return 0;
r = fsysXXX1(fsys, i, argc, argv);
fsysPut(fsys);
}
return r;
}
static int
cmdFsysXXX(int argc, char* argv[])
{
char *name;
if((name = sbox.curfsys) == nil){
werrstr(EFsysNoCurrent, argv[0]);
return 0;
}
return fsysXXX(name, argc, argv);
}
static int
cmdFsys(int argc, char* argv[])
{
Fsys *fsys;
char *usage = "usage: fsys [name ...]";
ARGBEGIN{
default:
return cliError(usage);
}ARGEND
if(argc == 0){
rlock(&sbox.lock);
currfsysname = sbox.head->name;
for(fsys = sbox.head; fsys != nil; fsys = fsys->next)
consPrint("\t%s\n", fsys->name);
runlock(&sbox.lock);
return 1;
}
if(argc == 1){
fsys = nil;
if(strcmp(argv[0], FsysAll) != 0 && (fsys = fsysGet(argv[0])) == nil)
return 0;
sbox.curfsys = vtstrdup(argv[0]);
consPrompt(sbox.curfsys);
if(fsys)
fsysPut(fsys);
return 1;
}
return fsysXXX(argv[0], argc-1, argv+1);
}
int
fsysInit(void)
{
int i;
fmtinstall('H', encodefmt);
fmtinstall('V', scoreFmt);
fmtinstall('L', labelFmt);
cliAddCmd("fsys", cmdFsys);
for(i = 0; fsyscmd[i].cmd != nil; i++){
if(fsyscmd[i].f != nil)
cliAddCmd(fsyscmd[i].cmd, cmdFsysXXX);
}
/* the venti cmd is special: the fs can be either open or closed */
cliAddCmd("venti", cmdFsysXXX);
cliAddCmd("printconfig", cmdPrintConfig);
return 1;
}
|
f1da918aafaac0edfd1aa7cefb518d1f3b60dc92
|
035660e8cc10571ebbd0d4393fef063bb7eb98f6
|
/src/boot_O2/system_malloc.c
|
cea017b38bec02619e95ad4633c2b3b2cfd08b25
|
[] |
no_license
|
zeldaret/mm
|
f163a5e7c4314105777369fa7671ce9c2a99922a
|
4ae00e909e74044f05155683b49d2561f91de7ba
|
refs/heads/master
| 2023-08-06T07:22:04.912966
| 2023-08-04T20:36:03
| 2023-08-04T20:36:03
| 247,875,852
| 915
| 328
| null | 2023-09-14T11:48:59
| 2020-03-17T04:03:07
|
C
|
UTF-8
|
C
| false
| false
| 1,181
|
c
|
system_malloc.c
|
#include "global.h"
#include "os_malloc.h"
Arena gSystemArena;
void* SystemArena_Malloc(size_t size) {
return __osMalloc(&gSystemArena, size);
}
void* SystemArena_MallocR(size_t size) {
return __osMallocR(&gSystemArena, size);
}
void* SystemArena_Realloc(void* oldPtr, size_t newSize) {
return __osRealloc(&gSystemArena, oldPtr, newSize);
}
void SystemArena_Free(void* ptr) {
__osFree(&gSystemArena, ptr);
}
void* SystemArena_Calloc(u32 elements, size_t size) {
void* ptr;
size_t totalSize = elements * size;
ptr = __osMalloc(&gSystemArena, totalSize);
if (ptr != NULL) {
bzero(ptr, totalSize);
}
return ptr;
}
void SystemArena_GetSizes(size_t* maxFreeBlock, size_t* bytesFree, size_t* bytesAllocated) {
__osGetSizes(&gSystemArena, maxFreeBlock, bytesFree, bytesAllocated);
}
u32 SystemArena_CheckArena(void) {
return __osCheckArena(&gSystemArena);
}
void SystemArena_Init(void* start, size_t size) {
__osMallocInit(&gSystemArena, start, size);
}
void SystemArena_Cleanup(void) {
__osMallocCleanup(&gSystemArena);
}
u8 SystemArena_IsInitialized(void) {
return __osMallocIsInitalized(&gSystemArena);
}
|
73ab5ef64920192c37f73950ed7e3c9808c575c7
|
14ed2724b7c610543959f23d401e7b90283e63c4
|
/Source/tmalloc.h
|
10800cd8e8c7fd3235ccd7eaf0695f02f2999c73
|
[
"MIT"
] |
permissive
|
powervr-graphics/PowerVR-Series1
|
d0ec36623d257e05c078e5d3f4bdfcd786ba46a4
|
c8c11cbe29c5b758ed1ef9600fc8614fc8da618e
|
refs/heads/main
| 2023-08-14T18:42:40.609670
| 2022-03-23T10:29:37
| 2022-03-23T10:29:37
| 467,444,934
| 260
| 17
| null | null | null | null |
UTF-8
|
C
| false
| false
| 2,973
|
h
|
tmalloc.h
|
/******************************************************************************
* Name : tmalloc.h
* Title : Controls the allocation of texture memory.
* Author : Peter Leaback
* Created : 23/06/1995
*
* Copyright : 1995-2022 Imagination Technologies (c)
* License : MIT
*
* Description : These routines don't actually touch the texture memory.
*
* Platform : ANSI
*
* Modifications:
* $Log: tmalloc.h,v $
* Revision 1.9 1997/06/23 22:00:27 jop
* Added vlock counter and low water mark to mnode
*
* Revision 1.8 1997/06/22 17:38:52 jop
* Added adaptive TSP parameter stuff and backwards allocation
*
* Revision 1.7 1997/06/04 15:33:45 gdc
* added prototypes for TMAlloc etc as they have no prototypes
* elsewhere
*
* Revision 1.6 1997/04/30 19:29:27 mjg
* Removed Texheap and prototypes for TMalloc, TFree and
* InitTextureMemory as they are now in pvrosapi.h
*
* Revision 1.5 1997/04/29 15:04:45 erf
* 1. Changed prototype definitions of TMalloc() and TFree().
* 2. Changed UINT's to sgl_uint's etc...
*
* Revision 1.4 1997/04/28 22:11:45 erf
* Added #ifndef __TMALLOC_H__ etc etc...
*
* Revision 1.3 1997/04/25 16:06:01 mjg
* Added TEXTUREHEAP structure and altered the prototypes for
* TFree and TMalloc.
*
* Revision 1.2 1997/03/13 11:46:46 sxy
* Changed MemoryRoot to a parameter rather than static.
*
* Revision 1.1 1995/07/17 16:04:05 pdl
* Initial revision
*
*
*****************************************************************************/
#ifndef __TMALLOC_H__
#define __TMALLOC_H__
#define TMALLOC_BACKWARDS 1
#define A_BANK 1 /*these numbers are assumed in the code*/
#define B_BANK 2
#define PROBABLE_CYCLE 10000 /*to test for cyclic lists*/
typedef enum
{
NORMAL_BLOCK,
TSP_PARAM_BLOCK,
ISP_OUT_OF_CACHE_BLOCK
} BLOCK_TYPE;
typedef struct _MNODE {
struct _MNODE *Next; /*required for the coalescing */
struct _MNODE *Prev; /*increasing address */
sgl_uint32 MemoryAddress;
sgl_uint32 BlockSize; /* Does not have to be texture size */
sgl_uint8 UsedStatus; /* A_BANK | B_BANK */
sgl_uint32 MemoryLeft; /*memory left */
struct _MNODE *NextFree; /* this list does not contain free budies*/
struct _MNODE *PrevFree; /* random order */
struct _MNODE *NextBuddy; /* block size of these has to be texture size*/
struct _MNODE *PrevBuddy;
#if TMALLOC_BACKWARDS
sgl_uint32 MemoryOffset;
sgl_uint32 MemorySize;
#endif
BLOCK_TYPE BlockType;
sgl_int32 AllocatedBlocks;
sgl_int32 LowWaterMark;
} MNODE;
typedef struct {
MNODE *MNode;
int Status; /* A_BANK ^ B_BANK ^ -1 */
} MNODE_BLOCK;
#include "texapi.h"
void InitTextureMemory(sgl_uint32 TextureMemorySize, HTEXHEAP hTexHeap);
void TMalloc(sgl_uint32 RequestSize, HTEXHEAP hTexHeap, MNODE_BLOCK *FreeNode);
void TFree(MNODE_BLOCK *FreeNode, HTEXHEAP hTexHeap);
sgl_int32 TSetHighWaterMark (HTEXHEAP hTexHeap, sgl_int32 nRequested);
#endif /* __TMALLOC_H__ */
|
e97c1bfed42a0c7d9080cc321e18dc03b0db12de
|
5eff7a36d9a9917dce9111f0c3074375fe6f7656
|
/lib/mesa/src/mesa/main/draw_validate.c
|
2ed59d90d5b6fab1be14e67ac38fb0c4a21cc717
|
[] |
no_license
|
openbsd/xenocara
|
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
|
a012b5de33ea0b977095d77316a521195b26cc6b
|
refs/heads/master
| 2023-08-25T12:16:58.862008
| 2023-08-12T16:16:25
| 2023-08-12T16:16:25
| 66,967,384
| 177
| 66
| null | 2023-07-22T18:12:37
| 2016-08-30T18:36:01
|
C
|
UTF-8
|
C
| false
| false
| 19,091
|
c
|
draw_validate.c
|
/*
* Mesa 3-D graphics library
*
* Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdbool.h>
#include "glheader.h"
#include "draw_validate.h"
#include "arrayobj.h"
#include "bufferobj.h"
#include "context.h"
#include "mtypes.h"
#include "pipelineobj.h"
#include "enums.h"
#include "state.h"
#include "transformfeedback.h"
#include "uniforms.h"
#include "program/prog_print.h"
/**
* Compute the bitmask of allowed primitive types (ValidPrimMask) depending
* on shaders and current states. This is used by draw validation.
*
* If some combinations of shaders and states are invalid, ValidPrimMask is
* set to 0, which will always set GL_INVALID_OPERATION in draw calls
* except for invalid enums, which will set GL_INVALID_ENUM, minimizing
* the number of gl_context variables that have to be read by draw calls.
*/
void
_mesa_update_valid_to_render_state(struct gl_context *ctx)
{
struct gl_pipeline_object *shader = ctx->_Shader;
unsigned mask = ctx->SupportedPrimMask;
bool drawpix_valid = true;
if (_mesa_is_no_error_enabled(ctx)) {
ctx->ValidPrimMask = mask;
ctx->ValidPrimMaskIndexed = mask;
ctx->DrawPixValid = drawpix_valid;
return;
}
/* Start with an empty mask and set this to the trimmed mask at the end. */
ctx->ValidPrimMask = 0;
ctx->ValidPrimMaskIndexed = 0;
ctx->DrawPixValid = false;
/* The default error is GL_INVALID_OPERATION if mode is a valid enum.
* It can be overriden by following code if we should return a different
* error.
*/
ctx->DrawGLError = GL_INVALID_OPERATION;
if (!ctx->DrawBuffer ||
ctx->DrawBuffer->_Status != GL_FRAMEBUFFER_COMPLETE_EXT) {
ctx->DrawGLError = GL_INVALID_FRAMEBUFFER_OPERATION;
return;
}
/* A pipeline object is bound */
if (shader->Name && !shader->Validated &&
!_mesa_validate_program_pipeline(ctx, shader))
return;
/* If a program is active and SSO not in use, check if validation of
* samplers succeeded for the active program. */
if (shader->ActiveProgram && shader != ctx->Pipeline.Current &&
!_mesa_sampler_uniforms_are_valid(shader->ActiveProgram, NULL, 0))
return;
/* The ARB_blend_func_extended spec's ERRORS section says:
*
* "The error INVALID_OPERATION is generated by Begin or any procedure
* that implicitly calls Begin if any draw buffer has a blend function
* requiring the second color input (SRC1_COLOR, ONE_MINUS_SRC1_COLOR,
* SRC1_ALPHA or ONE_MINUS_SRC1_ALPHA), and a framebuffer is bound that
* has more than the value of MAX_DUAL_SOURCE_DRAW_BUFFERS-1 active
* color attachements."
*/
unsigned max_dual_source_buffers = ctx->Const.MaxDualSourceDrawBuffers;
unsigned num_color_buffers = ctx->DrawBuffer->_NumColorDrawBuffers;
if (num_color_buffers > max_dual_source_buffers &&
ctx->Color._BlendUsesDualSrc &
BITFIELD_RANGE(max_dual_source_buffers,
num_color_buffers - max_dual_source_buffers))
return;
if (ctx->Color.BlendEnabled &&
ctx->Color._AdvancedBlendMode != BLEND_NONE) {
/* The KHR_blend_equation_advanced spec says:
*
* "If any non-NONE draw buffer uses a blend equation found in table
* X.1 or X.2, the error INVALID_OPERATION is generated by Begin or
* any operation that implicitly calls Begin (such as DrawElements)
* if:
*
* * the draw buffer for color output zero selects multiple color
* buffers (e.g., FRONT_AND_BACK in the default framebuffer); or
*
* * the draw buffer for any other color output is not NONE."
*/
if (ctx->DrawBuffer->ColorDrawBuffer[0] == GL_FRONT_AND_BACK)
return;
for (unsigned i = 1; i < num_color_buffers; i++) {
if (ctx->DrawBuffer->ColorDrawBuffer[i] != GL_NONE)
return;
}
/* The KHR_blend_equation_advanced spec says:
*
* "Advanced blending equations require the use of a fragment shader
* with a matching "blend_support" layout qualifier. If the current
* blend equation is found in table X.1 or X.2, and the active
* fragment shader does not include the layout qualifier matching
* the blend equation or "blend_support_all_equations", the error
* INVALID_OPERATION is generated [...]"
*/
const struct gl_program *prog =
ctx->_Shader->CurrentProgram[MESA_SHADER_FRAGMENT];
const GLbitfield blend_support = !prog ? 0 : prog->info.fs.advanced_blend_modes;
if ((blend_support & BITFIELD_BIT(ctx->Color._AdvancedBlendMode)) == 0)
return;
}
if (ctx->API == API_OPENGL_COMPAT) {
if (!shader->CurrentProgram[MESA_SHADER_FRAGMENT]) {
if (ctx->FragmentProgram.Enabled &&
!_mesa_arb_fragment_program_enabled(ctx))
return;
/* If drawing to integer-valued color buffers, there must be an
* active fragment shader (GL_EXT_texture_integer).
*/
if (ctx->DrawBuffer->_IntegerBuffers)
return;
}
}
/* DrawPixels/CopyPixels/Bitmap is valid after this point. */
ctx->DrawPixValid = true;
/* Section 11.2 (Tessellation) of the ES 3.2 spec says:
*
* "An INVALID_OPERATION error is generated by any command that
* transfers vertices to the GL if the current program state has
* one but not both of a tessellation control shader and tessellation
* evaluation shader."
*
* The OpenGL spec argues that this is allowed because a tess ctrl shader
* without a tess eval shader can be used with transform feedback.
* However, glBeginTransformFeedback doesn't allow GL_PATCHES and
* therefore doesn't allow tessellation.
*
* Further investigation showed that this is indeed a spec bug and
* a tess ctrl shader without a tess eval shader shouldn't have been
* allowed, because there is no API in GL 4.0 that can make use this
* to produce something useful.
*
* Also, all vendors except one don't support a tess ctrl shader without
* a tess eval shader anyway.
*/
if (shader->CurrentProgram[MESA_SHADER_TESS_CTRL] &&
!shader->CurrentProgram[MESA_SHADER_TESS_EVAL])
return;
switch (ctx->API) {
case API_OPENGLES2:
/* Section 11.2 (Tessellation) of the ES 3.2 spec says:
*
* "An INVALID_OPERATION error is generated by any command that
* transfers vertices to the GL if the current program state has
* one but not both of a tessellation control shader and tessellation
* evaluation shader."
*/
if (_mesa_is_gles3(ctx) &&
shader->CurrentProgram[MESA_SHADER_TESS_EVAL] &&
!shader->CurrentProgram[MESA_SHADER_TESS_CTRL])
return;
/* From GL_EXT_color_buffer_float:
*
* "Blending applies only if the color buffer has a fixed-point or
* or floating-point format. If the color buffer has an integer
* format, proceed to the next operation. Furthermore, an
* INVALID_OPERATION error is generated by DrawArrays and the other
* drawing commands defined in section 2.8.3 (10.5 in ES 3.1) if
* blending is enabled (see below) and any draw buffer has 32-bit
* floating-point format components."
*
* However GL_EXT_float_blend removes this text.
*/
if (!ctx->Extensions.EXT_float_blend &&
(ctx->DrawBuffer->_FP32Buffers & ctx->Color.BlendEnabled))
return;
break;
case API_OPENGL_CORE:
/* Section 10.4 (Drawing Commands Using Vertex Arrays) of the OpenGL 4.5
* Core Profile spec says:
*
* "An INVALID_OPERATION error is generated if no vertex array
* object is bound (see section 10.3.1)."
*/
if (ctx->Array.VAO == ctx->Array.DefaultVAO)
return;
break;
case API_OPENGLES:
break;
case API_OPENGL_COMPAT:
/* Check invalid ARB vertex programs. */
if (!shader->CurrentProgram[MESA_SHADER_VERTEX] &&
ctx->VertexProgram.Enabled &&
!_mesa_arb_vertex_program_enabled(ctx))
return;
break;
default:
unreachable("Invalid API value in _mesa_update_valid_to_render_state");
}
/* From the GL_NV_fill_rectangle spec:
*
* "An INVALID_OPERATION error is generated by Begin or any Draw command if
* only one of the front and back polygon mode is FILL_RECTANGLE_NV."
*/
if ((ctx->Polygon.FrontMode == GL_FILL_RECTANGLE_NV) !=
(ctx->Polygon.BackMode == GL_FILL_RECTANGLE_NV))
return;
/* From GL_INTEL_conservative_rasterization spec:
*
* The conservative rasterization option applies only to polygons with
* PolygonMode state set to FILL. Draw requests for polygons with different
* PolygonMode setting or for other primitive types (points/lines) generate
* INVALID_OPERATION error.
*/
if (ctx->IntelConservativeRasterization) {
if (ctx->Polygon.FrontMode != GL_FILL ||
ctx->Polygon.BackMode != GL_FILL) {
return;
} else {
mask &= (1 << GL_TRIANGLES) |
(1 << GL_TRIANGLE_STRIP) |
(1 << GL_TRIANGLE_FAN) |
(1 << GL_QUADS) |
(1 << GL_QUAD_STRIP) |
(1 << GL_POLYGON) |
(1 << GL_TRIANGLES_ADJACENCY) |
(1 << GL_TRIANGLE_STRIP_ADJACENCY);
}
}
/* From the GL_EXT_transform_feedback spec:
*
* "The error INVALID_OPERATION is generated if Begin, or any command
* that performs an explicit Begin, is called when:
*
* * a geometry shader is not active and <mode> does not match the
* allowed begin modes for the current transform feedback state as
* given by table X.1.
*
* * a geometry shader is active and the output primitive type of the
* geometry shader does not match the allowed begin modes for the
* current transform feedback state as given by table X.1.
*
*/
if (_mesa_is_xfb_active_and_unpaused(ctx)) {
if(shader->CurrentProgram[MESA_SHADER_GEOMETRY]) {
switch (shader->CurrentProgram[MESA_SHADER_GEOMETRY]->
info.gs.output_primitive) {
case GL_POINTS:
if (ctx->TransformFeedback.Mode != GL_POINTS)
mask = 0;
break;
case GL_LINE_STRIP:
if (ctx->TransformFeedback.Mode != GL_LINES)
mask = 0;
break;
case GL_TRIANGLE_STRIP:
if (ctx->TransformFeedback.Mode != GL_TRIANGLES)
mask = 0;
break;
default:
mask = 0;
}
}
else if (shader->CurrentProgram[MESA_SHADER_TESS_EVAL]) {
struct gl_program *tes =
shader->CurrentProgram[MESA_SHADER_TESS_EVAL];
if (tes->info.tess.point_mode) {
if (ctx->TransformFeedback.Mode != GL_POINTS)
mask = 0;
} else if (tes->info.tess._primitive_mode == TESS_PRIMITIVE_ISOLINES) {
if (ctx->TransformFeedback.Mode != GL_LINES)
mask = 0;
} else {
if (ctx->TransformFeedback.Mode != GL_TRIANGLES)
mask = 0;
}
}
else {
switch (ctx->TransformFeedback.Mode) {
case GL_POINTS:
mask &= 1 << GL_POINTS;
break;
case GL_LINES:
mask &= (1 << GL_LINES) |
(1 << GL_LINE_LOOP) |
(1 << GL_LINE_STRIP);
break;
case GL_TRIANGLES:
/* TODO: This doesn't look right, but it matches the original code. */
mask &= ~((1 << GL_POINTS) |
(1 << GL_LINES) |
(1 << GL_LINE_LOOP) |
(1 << GL_LINE_STRIP));
break;
}
}
if (!mask)
return;
}
/* From the OpenGL 4.5 specification, section 11.3.1:
*
* The error INVALID_OPERATION is generated if Begin, or any command that
* implicitly calls Begin, is called when a geometry shader is active and:
*
* * the input primitive type of the current geometry shader is
* POINTS and <mode> is not POINTS,
*
* * the input primitive type of the current geometry shader is
* LINES and <mode> is not LINES, LINE_STRIP, or LINE_LOOP,
*
* * the input primitive type of the current geometry shader is
* TRIANGLES and <mode> is not TRIANGLES, TRIANGLE_STRIP or
* TRIANGLE_FAN,
*
* * the input primitive type of the current geometry shader is
* LINES_ADJACENCY_ARB and <mode> is not LINES_ADJACENCY_ARB or
* LINE_STRIP_ADJACENCY_ARB, or
*
* * the input primitive type of the current geometry shader is
* TRIANGLES_ADJACENCY_ARB and <mode> is not
* TRIANGLES_ADJACENCY_ARB or TRIANGLE_STRIP_ADJACENCY_ARB.
*
* The GL spec doesn't mention any interaction with tessellation, which
* is clearly a spec bug. The same rule should apply, but instead of
* the draw primitive mode, the tessellation evaluation shader primitive
* mode should be used for the checking.
*/
if (shader->CurrentProgram[MESA_SHADER_GEOMETRY]) {
const GLenum geom_mode =
shader->CurrentProgram[MESA_SHADER_GEOMETRY]->
info.gs.input_primitive;
struct gl_program *tes =
shader->CurrentProgram[MESA_SHADER_TESS_EVAL];
if (tes) {
bool valid;
if (tes->info.tess.point_mode)
valid = geom_mode == GL_POINTS;
else if (tes->info.tess._primitive_mode == TESS_PRIMITIVE_ISOLINES)
valid = geom_mode == GL_LINES;
else
/* the GL_QUADS mode generates triangles too */
valid = geom_mode == GL_TRIANGLES;
/* TES and GS use incompatible primitive types. Discard all draws. */
if (!valid)
return;
} else {
switch (geom_mode) {
case GL_POINTS:
mask &= 1 << GL_POINTS;
break;
case GL_LINES:
mask &= (1 << GL_LINES) |
(1 << GL_LINE_LOOP) |
(1 << GL_LINE_STRIP);
break;
case GL_TRIANGLES:
mask &= (1 << GL_TRIANGLES) |
(1 << GL_TRIANGLE_STRIP) |
(1 << GL_TRIANGLE_FAN);
break;
case GL_LINES_ADJACENCY:
mask &= (1 << GL_LINES_ADJACENCY) |
(1 << GL_LINE_STRIP_ADJACENCY);
break;
case GL_TRIANGLES_ADJACENCY:
mask &= (1 << GL_TRIANGLES_ADJACENCY) |
(1 << GL_TRIANGLE_STRIP_ADJACENCY);
break;
}
}
}
/* From the OpenGL 4.0 (Core Profile) spec (section 2.12):
*
* "Tessellation operates only on patch primitives. If tessellation is
* active, any command that transfers vertices to the GL will
* generate an INVALID_OPERATION error if the primitive mode is not
* PATCHES.
* Patch primitives are not supported by pipeline stages below the
* tessellation evaluation shader. If there is no active program
* object or the active program object does not contain a tessellation
* evaluation shader, the error INVALID_OPERATION is generated by any
* command that transfers vertices to the GL if the primitive mode is
* PATCHES."
*
*/
if (shader->CurrentProgram[MESA_SHADER_TESS_EVAL] ||
shader->CurrentProgram[MESA_SHADER_TESS_CTRL]) {
mask &= 1 << GL_PATCHES;
}
else {
mask &= ~(1 << GL_PATCHES);
}
#ifdef DEBUG
if (shader->Flags & GLSL_LOG) {
struct gl_program **prog = shader->CurrentProgram;
for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
if (prog[i] == NULL || prog[i]->_Used)
continue;
/* This is the first time this shader is being used.
* Append shader's constants/uniforms to log file.
*
* Only log data for the program target that matches the shader
* target. It's possible to have a program bound to the vertex
* shader target that also supplied a fragment shader. If that
* program isn't also bound to the fragment shader target we don't
* want to log its fragment data.
*/
_mesa_append_uniforms_to_file(prog[i]);
}
for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
if (prog[i] != NULL)
prog[i]->_Used = GL_TRUE;
}
}
#endif
/* Non-indexed draws are valid after this point. */
ctx->ValidPrimMask = mask;
/* Section 2.14.2 (Transform Feedback Primitive Capture) of the OpenGL ES
* 3.1 spec says:
*
* The error INVALID_OPERATION is also generated by DrawElements,
* DrawElementsInstanced, and DrawRangeElements while transform feedback
* is active and not paused, regardless of mode.
*
* The OES_geometry_shader_spec says:
*
* Issues:
*
* ...
*
* (13) Does this extension change how transform feedback operates
* compared to unextended OpenGL ES 3.0 or 3.1?
*
* RESOLVED: Yes... Since we no longer require being able to predict how
* much geometry will be generated, we also lift the restriction that
* only DrawArray* commands are supported and also support the
* DrawElements* commands for transform feedback.
*
* This should also be reflected in the body of the spec, but that appears
* to have been overlooked. The body of the spec only explicitly allows
* the indirect versions.
*/
if (_mesa_is_gles3(ctx) &&
!_mesa_has_OES_geometry_shader(ctx) &&
_mesa_is_xfb_active_and_unpaused(ctx))
return;
ctx->ValidPrimMaskIndexed = mask;
}
|
8ccd1c8f3be5c126fa2a24d5c85f0253b1ccb2a1
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/usr.bin/mail/mime_decode.c
|
9ec27302c17944f64be8463448d7d3ea0022f641
|
[] |
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
| 31,000
|
c
|
mime_decode.c
|
/* $NetBSD: mime_decode.c,v 1.17 2010/06/21 19:49:31 christos Exp $ */
/*-
* Copyright (c) 2006 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Anon Ymous.
*
* 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 NETBSD FOUNDATION, INC. 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 FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef MIME_SUPPORT
#include <sys/cdefs.h>
#ifndef __lint__
__RCSID("$NetBSD: mime_decode.c,v 1.17 2010/06/21 19:49:31 christos Exp $");
#endif /* not __lint__ */
#include <assert.h>
#include <err.h>
#include <fcntl.h>
#include <libgen.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <iconv.h>
#include "def.h"
#include "extern.h"
#ifdef USE_EDITLINE
#include "complete.h"
#endif
#ifdef MIME_SUPPORT
#include "mime.h"
#include "mime_child.h"
#include "mime_codecs.h"
#include "mime_header.h"
#include "mime_detach.h"
#endif
#include "glob.h"
#include "thread.h"
#if 0
#ifndef __lint__
/*
* XXX - This block for debugging only and eventually should go away.
*/
static void
show_one_mime_info(FILE *fp, struct mime_info *mip)
{
#define XX(a) (a) ? (a) : "<null>"
(void)fprintf(fp, ">> --------\n");
(void)fprintf(fp, "mip %d:\n", mip->mi_partnum);
(void)fprintf(fp, "** Version: %s\n", XX(mip->mi_version));
(void)fprintf(fp, "** type: %s\n", XX(mip->mi_type));
(void)fprintf(fp, "** subtype: %s\n", XX(mip->mi_subtype));
(void)fprintf(fp, "** boundary: %s\n", XX(mip->mi_boundary));
(void)fprintf(fp, "** charset: %s\n", XX(mip->mi_charset));
(void)fprintf(fp, "** encoding: %s\n", XX(mip->mi_encoding));
(void)fprintf(fp, "** disposition: %s\n", XX(mip->mi_disposition));
(void)fprintf(fp, "** filename: %s\n", XX(mip->mi_filename));
(void)fprintf(fp, "** %p: flag: 0x%x, block: %ld, offset: %d, size: %lld, lines: %ld:%ld\n",
mip->mp,
mip->mp->m_flag,
mip->mp->m_block, mip->mp->m_offset, mip->mp->m_size,
mip->mp->m_lines, mip->mp->m_blines);
(void)fprintf(fp, "** mip: %p\n", mip);
(void)fprintf(fp, "** mi_flink: %p\n", mip->mi_flink);
(void)fprintf(fp, "** mi_blink: %p\n", mip->mi_blink);
(void)fprintf(fp, "** mip %p, mp %p, parent_mip %p, parent_mp %p\n",
mip, mip->mp, mip->mi_parent.mip, mip->mi_parent.mp);
(void)fprintf(fp, "** mi_fo %p, mi_head_end %p, mi_pipe_end %p\n",
mip->mi_fo, mip->mi_head_end, mip->mi_pipe_end);
(void)fprintf(fp, "** mi_ignore_body: %d\n", mip->mi_ignore_body);
(void)fprintf(fp, "** mi_partnum: %d\n", mip->mi_partnum);
(void)fprintf(fp, "** mi_partstr: %s\n", mip->mi_partstr);
(void)fprintf(fp, "** mi_msgstr: %s\n", mip->mi_msgstr);
(void)fflush(fp);
#undef XX
}
__unused
static void
show_mime_info(FILE *fp, struct mime_info *mip, struct mime_info *end_mip)
{
for (/* EMTPY */; mip != end_mip; mip = mip->mi_flink)
show_one_mime_info(fp, mip);
(void)fprintf(fp, "++ =========\n");
(void)fflush(fp);
}
#endif /* __lint__ */
#endif /* #if */
/*
* Our interface to the file registry in popen.c
*/
PUBLIC FILE *
pipe_end(struct mime_info *mip)
{
FILE *fp;
fp = last_registered_file(0); /* get last registered file or pipe */
if (fp == NULL)
fp = mip->mi_fo;
return fp;
}
/*
* Copy the first ';' delimited substring from 'src' (null terminated)
* into 'dst', expanding quotes and removing comments (as per RFC
* 822). Returns a pointer in src to the next non-white character
* following ';'. The caller is responsible for ensuring 'dst' is
* sufficiently large to hold the result.
*/
static char *
get_param(char *dst, char *src)
{
char *lastq;
char *cp;
char *cp2;
int nesting;
cp2 = dst;
lastq = dst;
for (cp = src; *cp && *cp != ';'; cp++) {
switch (*cp) {
case '"': /* start of quoted string */
for (cp++; *cp; cp++) {
if (*cp == '"')
break;
if (*cp == '\\' && cp[1] != '\0')
++cp;
*cp2++ = *cp;
}
lastq = cp2-1;
break;
case '(': /* start of comment */
nesting = 1;
while (nesting > 0 && *++cp) {
if (*cp == '\\' && cp[1] != '\0')
cp++;
if (*cp == '(')
nesting++;
if (*cp == ')')
nesting--;
}
break;
default:
*cp2++ = *cp;
break;
}
}
/* remove trailing white space */
while (cp2 > lastq && is_WSP(cp2[-1]))
cp2--;
*cp2 = '\0';
if (*cp == ';')
cp++;
cp = skip_WSP(cp);
return cp;
}
/*
* Content parameter
* if field is NULL, return the content "specifier".
*/
static char*
cparam(const char field[], char *src, int downcase)
{
char *cp;
char *dst;
if (src == NULL)
return NULL;
dst = salloc(strlen(src) + 1); /* large enough for any param in src */
cp = skip_WSP(src);
cp = get_param(dst, cp);
if (field == NULL)
return dst;
while (*cp != '\0') {
size_t len = strlen(field);
cp = get_param(dst, cp);
if (strncasecmp(dst, field, len) == 0 && dst[len] == '=') {
char *cp2;
cp2 = dst + len + 1;
if (downcase)
istrcpy(cp2, cp2);
return cp2;
}
}
return NULL;
}
static void
get_content(struct mime_info *mip)
{
char *mime_disposition_field;
char *mime_type_field;
char *filename;
struct message *mp;
char *cp;
mp = mip->mp;
mip->mi_version = cparam(NULL, hfield(MIME_HDR_VERSION, mp), 0);
mip->mi_encoding = cparam(NULL, hfield(MIME_HDR_ENCODING, mp), 1);
mime_type_field = hfield(MIME_HDR_TYPE, mp);
mip->mi_type = cparam(NULL, mime_type_field, 1);
if (mip->mi_type) {
cp = strchr(mip->mi_type, '/');
if (cp)
*cp++ = '\0';
mip->mi_subtype = cp;
}
mip->mi_boundary = cparam("boundary", mime_type_field, 0);
mip->mi_charset = cparam("charset", mime_type_field, 1);
mime_disposition_field = hfield(MIME_HDR_DISPOSITION, mp);
mip->mi_disposition = cparam(NULL, mime_disposition_field, 1);
/*
* The type field typically has a "name" parameter for "image"
* and "video" types, and I assume for other types as well.
* We grab it, but override it if the disposition field has a
* filename parameter as it often does for "attachments".
* More careful analysis could be done, but this seems to work
* pretty well.
*/
filename = cparam("name", mime_type_field, 0);
if ((cp = cparam("filename", mime_disposition_field, 0)) != NULL)
filename = cp;
if (filename) {
filename = basename(filename); /* avoid absolute pathnames */
filename = savestr(filename); /* save it! */
}
mip->mi_filename = filename;
/*
* XXX: If we have a "Content-Type" in the header, then assume
* we also have a "MIME-Version: 1.0". This fixes some broken
* MIME headers that I have seen occasionally.
*/
if (mip->mi_version == NULL && mip->mi_type != NULL)
mip->mi_version = MIME_VERSION;
}
static struct message *
salloc_message(int flag, long block, short offset)
{
struct message *mp;
/* use csalloc in case someone adds a field someday! */
mp = csalloc(1, sizeof(*mp));
mp->m_flag = flag;
mp->m_block = block;
mp->m_offset = offset;
#if 0
mp->m_lines = 0;
mp->m_size = 0;
mp->m_blines = 0;
#endif
return mp;
}
static struct mime_info *
insert_new_mip(struct mime_info *this_mip, struct mime_info *top_mip,
struct message *top_mp, off_t end_pos, int partnum)
{
struct mime_info *new_mip;
new_mip = csalloc(1, sizeof(*new_mip));
new_mip->mi_blink = this_mip;
new_mip->mi_flink = this_mip->mi_flink;
this_mip->mi_flink = new_mip;
new_mip->mp = salloc_message(this_mip->mp->m_flag,
(long)blockof(end_pos), blkoffsetof(end_pos));
new_mip->mi_parent.mip = top_mip;
new_mip->mi_parent.mp = top_mp;
new_mip->mi_partnum = partnum;
return new_mip;
}
static void
split_multipart(struct mime_info *top_mip)
{
FILE *fp;
struct message *top_mp;
struct message *this_mp;
struct mime_info *this_mip;
off_t beg_pos;
const char *boundary;
size_t boundary_len;
long lines_left; /* must be signed and same size as m_lines */
int partnum;
int in_header;
top_mp = top_mip->mp;
this_mp = salloc_message(top_mp->m_flag, top_mp->m_block, top_mp->m_offset);
this_mip = top_mip;
this_mip->mp = this_mp;
partnum = 1;
/* top_mip->mi_partnum = partnum++; */ /* Keep the number set by the caller */
in_header = 1;
boundary = top_mip->mi_boundary;
boundary_len = boundary ? strlen(boundary) : 0;
fp = setinput(top_mp);
beg_pos = ftello(fp);
#if 0
warnx("beg_pos: %lld, m_lines: %ld, m_blines: %ld",
beg_pos, top_mp->m_lines, top_mp->m_blines);
#endif
for (lines_left = top_mp->m_lines - 1; lines_left >= 0; lines_left--) {
char *line;
size_t line_len;
line = fgetln(fp, &line_len);
this_mp->m_lines++; /* count the message lines */
if (!in_header)
this_mp->m_blines++; /* count the body lines */
if (lines_left == 0 || (
!in_header &&
line_len >= boundary_len + 2 &&
line[0] == '-' && line[1] == '-' &&
strncmp(line + 2, boundary, boundary_len) == 0)) {
off_t cur_pos;
off_t end_pos;
cur_pos = ftello(fp);
/* the boundary belongs to the next part */
end_pos = cur_pos - line_len;
this_mp->m_lines -= 1;
this_mp->m_blines -= 1;
this_mp->m_size = end_pos - beg_pos;
#if 0
warnx("end_pos: %lld, m_lines: %ld, m_blines: %ld",
end_pos, this_mp->m_lines, this_mp->m_blines);
#endif
if (line[boundary_len + 2] == '-' &&
line[boundary_len + 3] == '-') {/* end of multipart */
/* do a sanity check on the EOM */
if (lines_left != 1) {
/*
* XXX - this can happen!
* Should we display the
* trailing garbage or check
* that it is blank or just
* ignore it?
*/
#if 0
(void)printf("EOM: lines left: %ld\n", lines_left);
#endif
}
break; /* XXX - stop at this point or grab the rest? */
}
this_mip = insert_new_mip(this_mip, top_mip, top_mp, end_pos, partnum++);
this_mp = this_mip->mp;
this_mp->m_lines = 1; /* already read the first line in the header! */
beg_pos = end_pos;
in_header = 1;
}
if (line_len == 1)
in_header = 0;
}
}
static void
split_message(struct mime_info *top_mip)
{
struct mime_info *this_mip;
struct message *top_mp;
struct message *this_mp;
FILE *fp;
off_t beg_pos;
long lines_left; /* must be same size as m_lines */
int in_header;
top_mp = top_mip->mp;
this_mp = salloc_message(top_mp->m_flag, top_mp->m_block, top_mp->m_offset);
this_mip = top_mip;
this_mip->mp = this_mp;
in_header = 1;
fp = setinput(top_mp);
beg_pos = ftello(fp);
for (lines_left = top_mp->m_lines; lines_left > 0; lines_left--) {
size_t line_len;
(void)fgetln(fp, &line_len);
this_mp->m_lines++; /* count the message lines */
if (!in_header)
this_mp->m_blines++; /* count the body lines */
if (in_header && line_len == 1) { /* end of header */
off_t end_pos;
end_pos = ftello(fp);
this_mp->m_size = end_pos - beg_pos;
this_mip = insert_new_mip(this_mip, top_mip,top_mp, end_pos, 0);
this_mp = this_mip->mp;
this_mp->m_lines = 1; /* we already counted one line in the header! */
beg_pos = end_pos;
in_header = 0; /* never in header again */
}
}
/* close the last message */
this_mp->m_size = ftello(fp) - beg_pos;
}
static const char *
get_command_hook(struct mime_info *mip, const char *domain)
{
char *key;
char *cmd;
if (mip->mi_type == NULL)
return NULL;
/* XXX - should we use easprintf() here? We are probably
* hosed elsewhere if this fails anyway. */
cmd = NULL;
if (mip->mi_subtype) {
if (asprintf(&key, "mime%s-%s-%s",
domain, mip->mi_type, mip->mi_subtype) == -1) {
warn("get_command_hook: subtupe: asprintf");
return NULL;
}
cmd = value(key);
free(key);
}
if (cmd == NULL) {
if (asprintf(&key, "mime%s-%s", domain, mip->mi_type) == -1) {
warn("get_command_hook: type: asprintf");
return NULL;
}
cmd = value(key);
free(key);
}
return cmd;
}
static int
is_basic_alternative(struct mime_info *mip)
{
return
strcasecmp(mip->mi_type, "text") == 0 &&
strcasecmp(mip->mi_subtype, "plain") == 0;
}
static struct mime_info *
select_alternative(struct mime_info *top_mip, struct mime_info *end_mip)
{
struct mime_info *the_mip; /* the chosen alternate */
struct mime_info *this_mip;
/*
* The alternates are supposed to occur in order of
* increasing "complexity". So: if there is at least
* one alternate of type "text/plain", use the last
* one, otherwise default to the first alternate.
*/
the_mip = top_mip->mi_flink;
for (this_mip = top_mip->mi_flink;
this_mip != end_mip;
this_mip = this_mip->mi_flink) {
const char *cmd;
if (this_mip->mi_type == NULL ||
this_mip->mi_subtype == NULL)
continue;
if (is_basic_alternative(this_mip))
the_mip = this_mip;
else if (
(cmd = get_command_hook(this_mip, "-hook")) ||
(cmd = get_command_hook(this_mip, "-head")) ||
(cmd = get_command_hook(this_mip, "-body"))) {
int flags;
/* just get the flags. */
flags = mime_run_command(cmd, NULL);
if ((flags & CMD_FLAG_ALTERNATIVE) != 0)
the_mip = this_mip;
}
}
return the_mip;
}
static inline int
is_multipart(struct mime_info *mip)
{
return mip->mi_type &&
strcasecmp("multipart", mip->mi_type) == 0;
}
static inline int
is_message(struct mime_info *mip)
{
return mip->mi_type &&
strcasecmp("message", mip->mi_type) == 0;
}
static inline int
is_alternative(struct mime_info *mip)
{
return mip->mi_subtype &&
strcasecmp("alternative", mip->mi_subtype) == 0;
}
/*
* Take a mime_info pointer and expand it recursively into all its
* mime parts. Only "multipart" and "message" types recursed into;
* they are handled separately.
*/
static struct mime_info *
expand_mip(struct mime_info *top_mip)
{
struct mime_info *this_mip;
struct mime_info *next_mip;
if (top_mip->mi_partnum == 0) {
if (top_mip->mi_blink)
top_mip->mi_partstr = top_mip->mi_blink->mi_partstr;
}
else if (top_mip->mi_parent.mip) {
const char *prefix;
char *cp;
prefix = top_mip->mi_parent.mip->mi_partstr;
(void)sasprintf(&cp, "%s%s%d", prefix,
*prefix ? "." : "", top_mip->mi_partnum);
top_mip->mi_partstr = cp;
}
next_mip = top_mip->mi_flink;
if (is_multipart(top_mip)) {
top_mip->mi_ignore_body = 1; /* the first body is ignored */
split_multipart(top_mip);
for (this_mip = top_mip->mi_flink;
this_mip != next_mip;
this_mip = this_mip->mi_flink) {
get_content(this_mip);
}
if (is_alternative(top_mip)) {
this_mip = select_alternative(top_mip, next_mip);
this_mip->mi_partnum = 0; /* suppress partnum display */
this_mip->mi_flink = next_mip;
this_mip->mi_blink = top_mip;
top_mip->mi_flink = this_mip;
}
/*
* Recurse into each part.
*/
for (this_mip = top_mip->mi_flink;
this_mip != next_mip;
this_mip = expand_mip(this_mip))
continue;
}
else if (is_message(top_mip)) {
top_mip->mi_ignore_body = 1; /* the first body is ignored */
split_message(top_mip);
this_mip = top_mip->mi_flink;
if (this_mip) {
get_content(this_mip);
/*
* If the one part is MIME encoded, recurse into it.
* XXX - Should this be conditional on subtype "rcs822"?
*/
if (this_mip->mi_type &&
this_mip->mi_version &&
equal(this_mip->mi_version, MIME_VERSION)) {
this_mip->mi_partnum = 0;
(void)expand_mip(this_mip);
}
}
}
return next_mip;
}
#if 0
static int
show_partnum(FILE *fp, struct mime_info *mip)
{
int need_dot;
need_dot = 0;
if (mip->mi_parent.mip && mip->mi_parent.mip->mi_parent.mip)
need_dot = show_partnum(fp, mip->mi_parent.mip);
if (mip->mi_partnum) {
(void)fprintf(fp, "%s%d", need_dot ? "." : "", mip->mi_partnum);
need_dot = 1;
}
return need_dot;
}
#endif
PUBLIC struct mime_info *
mime_decode_open(struct message *mp)
{
struct mime_info *mip;
struct mime_info *p;
mip = csalloc(1, sizeof(*mip));
mip->mp = salloc(sizeof(*mip->mp));
*mip->mp = *mp; /* copy this so we don't trash the master mp */
get_content(mip);
/* RFC 2049 - sec 2 item 1 */
if (mip->mi_version == NULL ||
!equal(mip->mi_version, MIME_VERSION))
return NULL;
mip->mi_partstr = "";
if (mip->mi_type)
(void)expand_mip(mip);
/*
* Get the pipe_end and propagate it down the chain.
*/
mip->mi_pipe_end = last_registered_file(0); /* for mime_decode_close() */
for (p = mip->mi_flink; p; p = p->mi_flink)
p->mi_pipe_end = mip->mi_pipe_end;
/* show_mime_info(stderr, mip, NULL); */
return mip;
}
PUBLIC void
mime_decode_close(struct mime_info *mip)
{
if (mip)
close_top_files(mip->mi_pipe_end);
}
struct prefix_line_args_s {
const char *prefix;
size_t prefixlen;
};
static void
prefix_line(FILE *fi, FILE *fo, void *cookie)
{
struct prefix_line_args_s *args;
const char *line;
const char *prefix;
size_t prefixlen;
size_t length;
args = cookie;
prefix = args->prefix;
prefixlen = args->prefixlen;
while ((line = fgetln(fi, &length)) != NULL) {
if (length > 1)
(void)fputs(prefix, fo);
else
(void)fwrite(prefix, sizeof(*prefix),
prefixlen, fo);
(void)fwrite(line, sizeof(*line), length, fo);
}
(void)fflush(fo);
}
PUBLIC int
mime_sendmessage(struct message *mp, FILE *obuf, struct ignoretab *igntab,
const char *prefix, struct mime_info *mip)
{
int error;
int detachall_flag;
const char *detachdir;
FILE *end_of_prefix;
if (mip == NULL)
return obuf ? /* were we trying to detach? */
sendmessage(mp, obuf, igntab, prefix, NULL) : 0;
/*
* The prefix has two meanigs which we handle here:
* 1) If obuf == NULL, then we are detaching to the 'prefix' directory.
* 2) If obuf != NULL, then the prefix is prepended to each line.
*/
detachdir = NULL;
detachall_flag = igntab == detachall;
if (obuf == NULL) {
assert(prefix != NULL); /* coding error! */
if ((obuf = last_registered_file(0)) == NULL)
obuf = stdout;
detachdir = prefix;
prefix = NULL;
igntab = ignoreall; /* always ignore the headers */
}
/*
* Set this early so pipe_end() will work!
*/
mip->mi_fo = obuf;
(void)fflush(obuf); /* Be safe and flush! XXX - necessary? */
/*
* Handle the prefix as a pipe stage so it doesn't get seen by
* any decoding or hooks.
*/
if (prefix != NULL) {
static struct prefix_line_args_s prefix_line_args;
const char *dp, *dp2 = NULL;
for (dp = prefix; *dp; dp++)
if (!is_WSP(*dp))
dp2 = dp;
prefix_line_args.prefixlen = dp2 == 0 ? 0 : dp2 - prefix + 1;
prefix_line_args.prefix = prefix;
mime_run_function(prefix_line, pipe_end(mip), (void*)&prefix_line_args);
}
end_of_prefix = last_registered_file(0);
error = 0;
for (/*EMPTY*/; mip; mip = mip->mi_flink) {
mip->mi_fo = obuf;
mip->mi_head_end = obuf;
mip->mi_detachdir = detachdir;
mip->mi_detachall = detachall_flag;
error |= sendmessage(mip->mp, pipe_end(mip), igntab, NULL, mip);
close_top_files(end_of_prefix); /* don't close the prefixer! */
}
return error;
}
#ifdef CHARSET_SUPPORT
/**********************************************
* higher level interface to run mime_ficonv().
*/
static void
run_mime_ficonv(struct mime_info *mip, const char *charset)
{
FILE *fo;
iconv_t cd;
fo = pipe_end(mip);
if (charset == NULL ||
mip->mi_charset == NULL ||
strcasecmp(mip->mi_charset, charset) == 0 ||
strcasecmp(mip->mi_charset, "unknown") == 0)
return;
cd = iconv_open(charset, mip->mi_charset);
if (cd == (iconv_t)-1) {
(void)fprintf(fo, "\t [ iconv_open failed: %s ]\n\n",
strerror(errno));
(void)fflush(fo); /* flush here or see double! */
return;
}
if (mip->mi_detachdir == NULL && /* don't contaminate the detach! */
value(ENAME_MIME_CHARSET_VERBOSE))
(void)fprintf(fo, "\t[ converting %s -> %s ]\n\n",
mip->mi_charset, charset);
mime_run_function(mime_ficonv, fo, cd);
(void)iconv_close(cd);
}
#endif /* CHARSET_SUPPORT */
PUBLIC void
run_decoder(struct mime_info *mip, void(*fn)(FILE*, FILE*, void *))
{
#ifdef CHARSET_SUPPORT
char *charset;
charset = value(ENAME_MIME_CHARSET);
if (charset && mip->mi_type && strcasecmp(mip->mi_type, "text") == 0)
run_mime_ficonv(mip, charset);
#endif /* CHARSET_SUPPORT */
if (mip->mi_detachdir == NULL &&
fn == mime_fio_copy)/* XXX - avoid an extra unnecessary pipe stage */
return;
mime_run_function(fn, pipe_end(mip),
mip->mi_detachdir ? NULL : __UNCONST("add_lf"));
}
/*
* Determine how to handle the display based on the type and subtype
* fields.
*/
enum dispmode_e {
DM_IGNORE = 0x00, /* silently ignore part - must be zero! */
DM_DISPLAY, /* decode and display the part */
DM_UNKNOWN, /* unknown display */
DM_BINARY, /* indicate binary data */
DM_PGPSIGN, /* OpenPGP signed part */
DM_PGPENCR, /* OpenPGP encrypted part */
DM_PGPKEYS, /* OpenPGP keys part */
DM_SENTINEL /* end marker; shouldn't be used */
};
#define APPLICATION_OCTET_STREAM DM_BINARY
static enum dispmode_e
get_display_mode(struct mime_info *mip, mime_codec_t dec)
{
struct mime_subtype_s {
const char *st_name;
enum dispmode_e st_dispmode;
};
struct mime_type_s {
const char *mt_type;
const struct mime_subtype_s *mt_subtype;
enum dispmode_e mt_dispmode; /* default if NULL subtype */
};
static const struct mime_subtype_s text_subtype_tbl[] = {
{ "plain", DM_DISPLAY },
{ "html", DM_DISPLAY }, /* rfc2854 */
{ "rfc822-headers", DM_DISPLAY },
{ "css", DM_DISPLAY }, /* rfc2318 */
{ "enriched", DM_DISPLAY }, /* rfc1523/rfc1563/rfc1896 */
{ "graphics", DM_DISPLAY }, /* rfc0553 */
{ "nroff", DM_DISPLAY }, /* rfc4263 */
{ "red", DM_DISPLAY }, /* rfc4102 */
{ NULL, DM_DISPLAY } /* default */
};
static const struct mime_subtype_s image_subtype_tbl[] = {
{ "tiff", DM_BINARY }, /* rfc2302/rfc3302 */
{ "tiff-fx", DM_BINARY }, /* rfc3250/rfc3950 */
{ "t38", DM_BINARY }, /* rfc3362 */
{ NULL, DM_BINARY } /* default */
};
static const struct mime_subtype_s audio_subtype_tbl[] = {
{ "mpeg", DM_BINARY }, /* rfc3003 */
{ "t38", DM_BINARY }, /* rfc4612 */
{ NULL, DM_BINARY } /* default */
};
static const struct mime_subtype_s video_subtype_tbl[] = {
{ NULL, DM_BINARY } /* default */
};
static const struct mime_subtype_s application_subtype_tbl[] = {
{ "octet-stream", APPLICATION_OCTET_STREAM },
{ "pgp-encrypted", DM_PGPENCR }, /* rfc3156 */
{ "pgp-keys", DM_PGPKEYS }, /* rfc3156 */
{ "pgp-signature", DM_PGPSIGN }, /* rfc3156 */
{ "pdf", DM_BINARY }, /* rfc3778 */
{ "whoispp-query", DM_UNKNOWN }, /* rfc2957 */
{ "whoispp-response", DM_UNKNOWN }, /* rfc2958 */
{ "font-tdpfr", DM_UNKNOWN }, /* rfc3073 */
{ "xhtml+xml", DM_UNKNOWN }, /* rfc3236 */
{ "ogg", DM_UNKNOWN }, /* rfc3534 */
{ "rdf+xml", DM_UNKNOWN }, /* rfc3870 */
{ "soap+xml", DM_UNKNOWN }, /* rfc3902 */
{ "mbox", DM_UNKNOWN }, /* rfc4155 */
{ "xv+xml", DM_UNKNOWN }, /* rfc4374 */
{ "smil", DM_UNKNOWN }, /* rfc4536 */
{ "smil+xml", DM_UNKNOWN }, /* rfc4536 */
{ "json", DM_UNKNOWN }, /* rfc4627 */
{ "voicexml+xml", DM_UNKNOWN }, /* rfc4267 */
{ "ssml+xml", DM_UNKNOWN }, /* rfc4267 */
{ "srgs", DM_UNKNOWN }, /* rfc4267 */
{ "srgs+xml", DM_UNKNOWN }, /* rfc4267 */
{ "ccxml+xml", DM_UNKNOWN }, /* rfc4267 */
{ "pls+xml.", DM_UNKNOWN }, /* rfc4267 */
{ NULL, APPLICATION_OCTET_STREAM } /* default */
};
static const struct mime_type_s mime_type_tbl[] = {
{ "text", text_subtype_tbl, DM_DISPLAY },
{ "image", image_subtype_tbl, DM_IGNORE },
{ "audio", audio_subtype_tbl, DM_IGNORE },
{ "video", video_subtype_tbl, DM_IGNORE },
{ "application", application_subtype_tbl, APPLICATION_OCTET_STREAM },
{ NULL, NULL, DM_UNKNOWN }, /* default */
};
const struct mime_type_s *mtp;
const struct mime_subtype_s *stp;
const char *mi_type;
const char *mi_subtype;
/*
* Silently ignore all multipart bodies.
* 1) In the case of "multipart" types, this typically
* contains a message for non-mime enabled mail readers.
* 2) In the case of "message" type, there should be no body.
*/
if (mip->mi_ignore_body) /*is_multipart(mip) || is_message(mip))*/
return DM_IGNORE;
/*
* If the encoding type given but not recognized, treat block
* as "application/octet-stream". rfc 2049 sec 2 part 2.
*/
if (mip->mi_encoding && dec == NULL)
return APPLICATION_OCTET_STREAM;
mi_type = mip->mi_type;
mi_subtype = mip->mi_type ? mip->mi_subtype : NULL;
/*
* If there was no type specified, display anyway so we don't
* miss anything. (The encoding type is known.)
*/
if (mi_type == NULL)
return DM_DISPLAY; /* XXX - default to something safe! */
for (mtp = mime_type_tbl; mtp->mt_type; mtp++) {
if (strcasecmp(mtp->mt_type, mi_type) == 0) {
if (mi_subtype == NULL)
return mtp->mt_dispmode;
for (stp = mtp->mt_subtype; stp->st_name; stp++) {
if (strcasecmp(stp->st_name, mi_subtype) == 0)
return stp->st_dispmode;
}
return stp->st_dispmode;
}
}
return mtp->mt_dispmode;
}
PUBLIC FILE *
mime_decode_body(struct mime_info *mip)
{
static enum dispmode_e dispmode;
mime_codec_t dec;
const char *cmd;
/* close anything left over from mime_decode_head() */
close_top_files(mip->mi_head_end);
/*
* Make sure we flush everything down the pipe so children
* don't see it.
*/
(void)fflush(pipe_end(mip));
if (mip->mi_detachdir) /* We are detaching! Ignore the hooks. */
return mime_detach_parts(mip);
cmd = NULL;
if (mip->mi_command_hook == NULL)
cmd = get_command_hook(mip, "-body");
dec = mime_fio_decoder(mip->mi_encoding);
/*
* If there is a filter running, we need to send the message
* to it. Otherwise, get the default display mode for this body.
*/
dispmode = cmd || mip->mi_command_hook ? DM_DISPLAY : get_display_mode(mip, dec);
if (dec == NULL) /* make sure we have a usable decoder */
dec = mime_fio_decoder(MIME_TRANSFER_7BIT);
if (dispmode == DM_DISPLAY) {
int flags;
if (cmd == NULL)
/* just get the flags */
flags = mime_run_command(mip->mi_command_hook, NULL);
else
flags = mime_run_command(cmd, pipe_end(mip));
if ((flags & CMD_FLAG_NO_DECODE) == 0)
run_decoder(mip, dec);
return pipe_end(mip);
}
else {
static const struct msg_tbl_s {
enum dispmode_e dm;
const char *msg;
} msg_tbl[] = {
{ DM_BINARY, "binary content" },
{ DM_PGPSIGN, "OpenPGP signature" },
{ DM_PGPENCR, "OpenPGP encrypted" },
{ DM_PGPKEYS, "OpenPGP keys" },
{ DM_UNKNOWN, "unknown data" },
{ DM_IGNORE, NULL },
{ DM_SENTINEL, NULL },
};
const struct msg_tbl_s *mp;
for (mp = msg_tbl; mp->dm != DM_SENTINEL; mp++)
if (mp->dm == dispmode)
break;
assert(mp->dm != DM_SENTINEL); /* msg_tbl is short if this happens! */
if (mp->msg)
(void)fprintf(pipe_end(mip), " [%s]\n\n", mp->msg);
return NULL;
}
}
/************************************************************************
* Higher level header decoding interface.
*
* The core routines are in mime_header.c.
*/
/*
* Decode a portion of the header field.
*
* linebuf buffer to decode into.
* bufsize size of linebuf.
* hdrline full header line including header name.
* srcstr pointer to string to decode
*/
PUBLIC char *
mime_decode_hfield(char *linebuf, size_t bufsize, const char *hdrline, char *srcstr)
{
hfield_decoder_t decode;
decode = mime_hfield_decoder(hdrline);
if (decode) {
decode(linebuf, bufsize, srcstr);
return linebuf;
}
return srcstr;
}
/*
* Return the next header field found in the input stream.
* Return 0 if something found, -1 otherwise.
* For a proper header, "*colon" is set to point to the colon
* terminating the header name. Otherwise it is NULL.
*
* NOTE: unlike gethfield() in support.c this:
* 1) preserves folding (newlines),
* 2) reads until fgetln() gets an EOF,
* 3) only sets *colon if there is a "proper" one.
*/
static int
get_folded_hfield(FILE *f, char *linebuf, size_t bufsize, char **colon)
{
char *cp, *cp2;
char *line;
size_t len;
if ((cp = fgetln(f, &len)) == NULL)
return -1;
for (cp2 = cp;
cp2 < cp + len && isprint((unsigned char)*cp2) &&
!is_WSP(*cp2) && *cp2 != ':';
cp2++)
continue;
len = MIN(bufsize - 1, len);
bufsize -= len;
(void)memcpy(linebuf, cp, len);
*colon = *cp2 == ':' ? linebuf + (cp2 - cp) : NULL;
line = linebuf + len;
for (;;) {
int c;
(void)ungetc(c = getc(f), f);
if (!is_WSP(c))
break;
if ((cp = fgetln(f, &len)) == NULL)
break;
len = MIN(bufsize - 1, len);
bufsize -= len;
if (len == 0)
break;
(void)memcpy(line, cp, len);
line += len;
}
*line = 0;
return 0;
}
static void
decode_header(FILE *fi, FILE *fo, void *cookie __unused)
{
char linebuf[LINESIZE];
char *colon;
#ifdef __lint__
cookie = cookie;
#endif
while (get_folded_hfield(fi, linebuf, sizeof(linebuf), &colon) >= 0) {
char decbuf[LINESIZE];
char *hdrstr;
hdrstr = linebuf;
if (colon)
hdrstr = mime_decode_hfield(decbuf, sizeof(decbuf), hdrstr, hdrstr);
(void)fputs(hdrstr, fo);
}
}
PUBLIC FILE *
mime_decode_header(struct mime_info *mip)
{
int flags;
const char *cmd;
FILE *fo;
fo = pipe_end(mip);
if (mip->mi_detachdir) { /* We are detaching. Don't run anything! */
(void)fflush(fo);
return pipe_end(mip);
}
if (mip->mi_partnum)
(void)fprintf(fo, "----- Part %s -----\n", mip->mi_partstr);
(void)fflush(fo); /* Flush so the childern don't see it. */
/*
* install the message hook before the head hook.
*/
cmd = get_command_hook(mip, "-hook");
mip->mi_command_hook = cmd;
if (cmd) {
flags = mime_run_command(cmd, pipe_end(mip));
mip->mi_head_end = last_registered_file(0);
}
else {
cmd = get_command_hook(mip, "-head");
mip->mi_head_end = last_registered_file(0);
flags = mime_run_command(cmd, pipe_end(mip));
}
if (value(ENAME_MIME_DECODE_HDR) && (flags & CMD_FLAG_NO_DECODE) == 0)
mime_run_function(decode_header, pipe_end(mip), NULL);
return pipe_end(mip);
}
#endif /* MIME_SUPPORT */
|
cc6b66d0f31cdaa23b5b1bc8a0bc7a6cce08b464
|
30b736259b38c916e96f8e1517f92231070f5464
|
/apps/btshell/src/main.c
|
4c4a6bb7873cd28e16731a93c7d33990403c70aa
|
[
"Apache-2.0",
"LicenseRef-scancode-gary-s-brown",
"BSD-3-Clause"
] |
permissive
|
apache/mynewt-nimble
|
5bcc87df4482705c5a6542467bab028c8fd4e5fe
|
b5e107e9c55f32d18b16e5afc0a7e1720b901b68
|
refs/heads/master
| 2023-09-01T19:28:57.874159
| 2023-08-31T09:07:59
| 2023-08-31T14:46:07
| 113,086,218
| 606
| 354
|
Apache-2.0
| 2023-09-14T12:14:19
| 2017-12-04T19:34:47
|
C
|
UTF-8
|
C
| false
| false
| 73,767
|
c
|
main.c
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include "os/mynewt.h"
#include "bsp/bsp.h"
#include "log/log.h"
#include "stats/stats.h"
#include "hal/hal_gpio.h"
#include "console/console.h"
#include "btshell.h"
#include "cmd.h"
/* BLE */
#include "nimble/ble.h"
#include "nimble/nimble_opt.h"
#include "host/ble_hs.h"
#include "host/ble_hs_adv.h"
#include "host/ble_uuid.h"
#include "host/ble_att.h"
#include "host/ble_gap.h"
#include "host/ble_gatt.h"
#include "host/ble_store.h"
#include "host/ble_sm.h"
#include "host/util/util.h"
/* Mandatory services. */
#include "services/gap/ble_svc_gap.h"
#include "services/gatt/ble_svc_gatt.h"
/* XXX: An app should not include private headers from a library. The btshell
* app uses some of nimble's internal details for logging.
*/
#include "../src/ble_hs_conn_priv.h"
#include "../src/ble_hs_atomic_priv.h"
#include "../src/ble_hs_priv.h"
#if MYNEWT_VAL(BLE_ROLE_CENTRAL)
#define BTSHELL_MAX_SVCS 32
#define BTSHELL_MAX_CHRS 64
#define BTSHELL_MAX_DSCS 64
#else
#define BTSHELL_MAX_SVCS 1
#define BTSHELL_MAX_CHRS 1
#define BTSHELL_MAX_DSCS 1
#endif
#if MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM)
#define BTSHELL_COC_MTU (256)
/* We use same pool for incoming and outgoing sdu */
#define BTSHELL_COC_BUF_COUNT (3 * MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM))
#define INT_TO_PTR(x) (void *)((intptr_t)(x))
#define PTR_TO_INT(x) (int) ((intptr_t)(x))
#endif
bssnz_t struct btshell_conn btshell_conns[MYNEWT_VAL(BLE_MAX_CONNECTIONS)];
int btshell_num_conns;
static uint8_t default_own_addr_type;
static os_membuf_t btshell_svc_mem[
OS_MEMPOOL_SIZE(BTSHELL_MAX_SVCS, sizeof(struct btshell_svc))
];
static struct os_mempool btshell_svc_pool;
static os_membuf_t btshell_chr_mem[
OS_MEMPOOL_SIZE(BTSHELL_MAX_CHRS, sizeof(struct btshell_chr))
];
static struct os_mempool btshell_chr_pool;
static os_membuf_t btshell_dsc_mem[
OS_MEMPOOL_SIZE(BTSHELL_MAX_DSCS, sizeof(struct btshell_dsc))
];
static struct os_mempool btshell_dsc_pool;
#if MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM)
static os_membuf_t btshell_coc_conn_mem[
OS_MEMPOOL_SIZE(MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM),
sizeof(struct btshell_l2cap_coc))
];
static struct os_mempool btshell_coc_conn_pool;
static os_membuf_t btshell_sdu_coc_mem[
OS_MEMPOOL_SIZE(BTSHELL_COC_BUF_COUNT, BTSHELL_COC_MTU)
];
struct os_mbuf_pool sdu_os_mbuf_pool;
static struct os_mempool sdu_coc_mbuf_mempool;
#endif
static struct os_callout btshell_tx_timer;
struct btshell_tx_data_s
{
uint16_t tx_num;
uint16_t tx_num_requested;
uint16_t tx_rate;
uint16_t tx_conn_handle;
uint16_t tx_len;
struct ble_hs_conn *conn;
};
static struct btshell_tx_data_s btshell_tx_data;
int btshell_full_disc_prev_chr_val;
struct ble_sm_sc_oob_data oob_data_local;
struct ble_sm_sc_oob_data oob_data_remote;
#define XSTR(s) STR(s)
#ifndef STR
#define STR(s) #s
#endif
#ifdef DEVICE_NAME
#define BTSHELL_AUTO_DEVICE_NAME XSTR(DEVICE_NAME)
#else
#define BTSHELL_AUTO_DEVICE_NAME ""
#endif
#if MYNEWT_VAL(BLE_EXT_ADV)
struct {
bool restart;
uint16_t conn_handle;
} ext_adv_restart[BLE_ADV_INSTANCES];
#endif
static struct {
bool restart;
uint8_t own_addr_type;
ble_addr_t direct_addr;
int32_t duration_ms;
struct ble_gap_adv_params params;
} adv_params;
static void
btshell_print_error(char *msg, uint16_t conn_handle,
const struct ble_gatt_error *error)
{
if (msg == NULL) {
msg = "ERROR";
}
console_printf("%s: conn_handle=%d status=%d att_handle=%d\n",
msg, conn_handle, error->status, error->att_handle);
}
static void
btshell_print_adv_fields(const struct ble_hs_adv_fields *fields)
{
const uint8_t *u8p;
int i;
if (fields->flags != 0) {
console_printf(" flags=0x%02x:\n", fields->flags);
if (!(fields->flags & BLE_HS_ADV_F_DISC_LTD) &&
!(fields->flags & BLE_HS_ADV_F_DISC_GEN)) {
console_printf(" Non-discoverable mode\n");
}
if (fields->flags & BLE_HS_ADV_F_DISC_LTD) {
console_printf(" Limited discoverable mode\n");
}
if (fields->flags & BLE_HS_ADV_F_DISC_GEN) {
console_printf(" General discoverable mode\n");
}
if (fields->flags & BLE_HS_ADV_F_BREDR_UNSUP) {
console_printf(" BR/EDR not supported\n");
}
}
if (fields->uuids16 != NULL) {
console_printf(" uuids16(%scomplete)=",
fields->uuids16_is_complete ? "" : "in");
for (i = 0; i < fields->num_uuids16; i++) {
print_uuid(&fields->uuids16[i].u);
console_printf(" ");
}
console_printf("\n");
}
if (fields->uuids32 != NULL) {
console_printf(" uuids32(%scomplete)=",
fields->uuids32_is_complete ? "" : "in");
for (i = 0; i < fields->num_uuids32; i++) {
print_uuid(&fields->uuids32[i].u);
console_printf(" ");
}
console_printf("\n");
}
if (fields->uuids128 != NULL) {
console_printf(" uuids128(%scomplete)=",
fields->uuids128_is_complete ? "" : "in");
for (i = 0; i < fields->num_uuids128; i++) {
print_uuid(&fields->uuids128[i].u);
console_printf(" ");
}
console_printf("\n");
}
if (fields->name != NULL) {
console_printf(" name(%scomplete)=",
fields->name_is_complete ? "" : "in");
console_write((char *)fields->name, fields->name_len);
console_printf("\n");
}
if (fields->tx_pwr_lvl_is_present) {
console_printf(" tx_pwr_lvl=%d\n", fields->tx_pwr_lvl);
}
if (fields->slave_itvl_range != NULL) {
console_printf(" slave_itvl_range=");
print_bytes(fields->slave_itvl_range,
BLE_HS_ADV_SLAVE_ITVL_RANGE_LEN);
console_printf("\n");
}
if (fields->svc_data_uuid16 != NULL) {
console_printf(" svc_data_uuid16=");
print_bytes(fields->svc_data_uuid16,
fields->svc_data_uuid16_len);
console_printf("\n");
}
if (fields->public_tgt_addr != NULL) {
console_printf(" public_tgt_addr=");
u8p = fields->public_tgt_addr;
for (i = 0; i < fields->num_public_tgt_addrs; i++) {
print_addr(u8p);
u8p += BLE_HS_ADV_PUBLIC_TGT_ADDR_ENTRY_LEN;
}
console_printf("\n");
}
if (fields->appearance_is_present) {
console_printf(" appearance=0x%04x\n", fields->appearance);
}
if (fields->adv_itvl_is_present) {
console_printf(" adv_itvl=0x%04x\n", fields->adv_itvl);
}
if (fields->svc_data_uuid32 != NULL) {
console_printf(" svc_data_uuid32=");
print_bytes(fields->svc_data_uuid32,
fields->svc_data_uuid32_len);
console_printf("\n");
}
if (fields->svc_data_uuid128 != NULL) {
console_printf(" svc_data_uuid128=");
print_bytes(fields->svc_data_uuid128,
fields->svc_data_uuid128_len);
console_printf("\n");
}
if (fields->uri != NULL) {
console_printf(" uri=");
print_bytes(fields->uri, fields->uri_len);
console_printf("\n");
}
if (fields->mfg_data != NULL) {
console_printf(" mfg_data=");
print_bytes(fields->mfg_data, fields->mfg_data_len);
console_printf("\n");
}
}
static int
btshell_conn_find_idx(uint16_t handle)
{
int i;
for (i = 0; i < btshell_num_conns; i++) {
if (btshell_conns[i].handle == handle) {
return i;
}
}
return -1;
}
static struct btshell_conn *
btshell_conn_find(uint16_t handle)
{
int idx;
idx = btshell_conn_find_idx(handle);
if (idx == -1) {
return NULL;
} else {
return btshell_conns + idx;
}
}
static struct btshell_svc *
btshell_svc_find_prev(struct btshell_conn *conn, uint16_t svc_start_handle)
{
struct btshell_svc *prev;
struct btshell_svc *svc;
prev = NULL;
SLIST_FOREACH(svc, &conn->svcs, next) {
if (svc->svc.start_handle >= svc_start_handle) {
break;
}
prev = svc;
}
return prev;
}
static struct btshell_svc *
btshell_svc_find(struct btshell_conn *conn, uint16_t svc_start_handle,
struct btshell_svc **out_prev)
{
struct btshell_svc *prev;
struct btshell_svc *svc;
prev = btshell_svc_find_prev(conn, svc_start_handle);
if (prev == NULL) {
svc = SLIST_FIRST(&conn->svcs);
} else {
svc = SLIST_NEXT(prev, next);
}
if (svc != NULL && svc->svc.start_handle != svc_start_handle) {
svc = NULL;
}
if (out_prev != NULL) {
*out_prev = prev;
}
return svc;
}
static struct btshell_svc *
btshell_svc_find_range(struct btshell_conn *conn, uint16_t attr_handle)
{
struct btshell_svc *svc;
SLIST_FOREACH(svc, &conn->svcs, next) {
if (svc->svc.start_handle <= attr_handle &&
svc->svc.end_handle >= attr_handle) {
return svc;
}
}
return NULL;
}
static void
btshell_chr_delete(struct btshell_chr *chr)
{
struct btshell_dsc *dsc;
while ((dsc = SLIST_FIRST(&chr->dscs)) != NULL) {
SLIST_REMOVE_HEAD(&chr->dscs, next);
os_memblock_put(&btshell_dsc_pool, dsc);
}
os_memblock_put(&btshell_chr_pool, chr);
}
static void
btshell_svc_delete(struct btshell_svc *svc)
{
struct btshell_chr *chr;
while ((chr = SLIST_FIRST(&svc->chrs)) != NULL) {
SLIST_REMOVE_HEAD(&svc->chrs, next);
btshell_chr_delete(chr);
}
os_memblock_put(&btshell_svc_pool, svc);
}
static struct btshell_svc *
btshell_svc_add(uint16_t conn_handle, const struct ble_gatt_svc *gatt_svc)
{
struct btshell_conn *conn;
struct btshell_svc *prev;
struct btshell_svc *svc;
conn = btshell_conn_find(conn_handle);
if (conn == NULL) {
MODLOG_DFLT(DEBUG, "RECEIVED SERVICE FOR UNKNOWN CONNECTION; "
"HANDLE=%d\n",
conn_handle);
return NULL;
}
svc = btshell_svc_find(conn, gatt_svc->start_handle, &prev);
if (svc != NULL) {
/* Service already discovered. */
return svc;
}
svc = os_memblock_get(&btshell_svc_pool);
if (svc == NULL) {
MODLOG_DFLT(DEBUG, "OOM WHILE DISCOVERING SERVICE\n");
return NULL;
}
memset(svc, 0, sizeof *svc);
svc->svc = *gatt_svc;
SLIST_INIT(&svc->chrs);
if (prev == NULL) {
SLIST_INSERT_HEAD(&conn->svcs, svc, next);
} else {
SLIST_INSERT_AFTER(prev, svc, next);
}
return svc;
}
static struct btshell_chr *
btshell_chr_find_prev(const struct btshell_svc *svc, uint16_t chr_val_handle)
{
struct btshell_chr *prev;
struct btshell_chr *chr;
prev = NULL;
SLIST_FOREACH(chr, &svc->chrs, next) {
if (chr->chr.val_handle >= chr_val_handle) {
break;
}
prev = chr;
}
return prev;
}
static struct btshell_chr *
btshell_chr_find(const struct btshell_svc *svc, uint16_t chr_val_handle,
struct btshell_chr **out_prev)
{
struct btshell_chr *prev;
struct btshell_chr *chr;
prev = btshell_chr_find_prev(svc, chr_val_handle);
if (prev == NULL) {
chr = SLIST_FIRST(&svc->chrs);
} else {
chr = SLIST_NEXT(prev, next);
}
if (chr != NULL && chr->chr.val_handle != chr_val_handle) {
chr = NULL;
}
if (out_prev != NULL) {
*out_prev = prev;
}
return chr;
}
static struct btshell_chr *
btshell_chr_add(uint16_t conn_handle, uint16_t svc_start_handle,
const struct ble_gatt_chr *gatt_chr)
{
struct btshell_conn *conn;
struct btshell_chr *prev;
struct btshell_chr *chr;
struct btshell_svc *svc;
conn = btshell_conn_find(conn_handle);
if (conn == NULL) {
MODLOG_DFLT(DEBUG, "RECEIVED SERVICE FOR UNKNOWN CONNECTION; "
"HANDLE=%d\n",
conn_handle);
return NULL;
}
svc = btshell_svc_find(conn, svc_start_handle, NULL);
if (svc == NULL) {
MODLOG_DFLT(DEBUG, "CAN'T FIND SERVICE FOR DISCOVERED CHR; HANDLE=%d\n",
conn_handle);
return NULL;
}
chr = btshell_chr_find(svc, gatt_chr->val_handle, &prev);
if (chr != NULL) {
/* Characteristic already discovered. */
return chr;
}
chr = os_memblock_get(&btshell_chr_pool);
if (chr == NULL) {
MODLOG_DFLT(DEBUG, "OOM WHILE DISCOVERING CHARACTERISTIC\n");
return NULL;
}
memset(chr, 0, sizeof *chr);
chr->chr = *gatt_chr;
if (prev == NULL) {
SLIST_INSERT_HEAD(&svc->chrs, chr, next);
} else {
SLIST_NEXT(prev, next) = chr;
}
return chr;
}
static struct btshell_dsc *
btshell_dsc_find_prev(const struct btshell_chr *chr, uint16_t dsc_handle)
{
struct btshell_dsc *prev;
struct btshell_dsc *dsc;
prev = NULL;
SLIST_FOREACH(dsc, &chr->dscs, next) {
if (dsc->dsc.handle >= dsc_handle) {
break;
}
prev = dsc;
}
return prev;
}
static struct btshell_dsc *
btshell_dsc_find(const struct btshell_chr *chr, uint16_t dsc_handle,
struct btshell_dsc **out_prev)
{
struct btshell_dsc *prev;
struct btshell_dsc *dsc;
prev = btshell_dsc_find_prev(chr, dsc_handle);
if (prev == NULL) {
dsc = SLIST_FIRST(&chr->dscs);
} else {
dsc = SLIST_NEXT(prev, next);
}
if (dsc != NULL && dsc->dsc.handle != dsc_handle) {
dsc = NULL;
}
if (out_prev != NULL) {
*out_prev = prev;
}
return dsc;
}
static struct btshell_dsc *
btshell_dsc_add(uint16_t conn_handle, uint16_t chr_val_handle,
const struct ble_gatt_dsc *gatt_dsc)
{
struct btshell_conn *conn;
struct btshell_dsc *prev;
struct btshell_dsc *dsc;
struct btshell_svc *svc;
struct btshell_chr *chr;
conn = btshell_conn_find(conn_handle);
if (conn == NULL) {
MODLOG_DFLT(DEBUG, "RECEIVED SERVICE FOR UNKNOWN CONNECTION; "
"HANDLE=%d\n",
conn_handle);
return NULL;
}
svc = btshell_svc_find_range(conn, chr_val_handle);
if (svc == NULL) {
MODLOG_DFLT(DEBUG, "CAN'T FIND SERVICE FOR DISCOVERED DSC; HANDLE=%d\n",
conn_handle);
return NULL;
}
chr = btshell_chr_find(svc, chr_val_handle, NULL);
if (chr == NULL) {
MODLOG_DFLT(DEBUG, "CAN'T FIND CHARACTERISTIC FOR DISCOVERED DSC; "
"HANDLE=%d\n",
conn_handle);
return NULL;
}
dsc = btshell_dsc_find(chr, gatt_dsc->handle, &prev);
if (dsc != NULL) {
/* Descriptor already discovered. */
return dsc;
}
dsc = os_memblock_get(&btshell_dsc_pool);
if (dsc == NULL) {
console_printf("OOM WHILE DISCOVERING DESCRIPTOR\n");
return NULL;
}
memset(dsc, 0, sizeof *dsc);
dsc->dsc = *gatt_dsc;
if (prev == NULL) {
SLIST_INSERT_HEAD(&chr->dscs, dsc, next);
} else {
SLIST_NEXT(prev, next) = dsc;
}
return dsc;
}
static struct btshell_conn *
btshell_conn_add(struct ble_gap_conn_desc *desc)
{
struct btshell_conn *conn;
assert(btshell_num_conns < MYNEWT_VAL(BLE_MAX_CONNECTIONS));
conn = btshell_conns + btshell_num_conns;
btshell_num_conns++;
conn->handle = desc->conn_handle;
SLIST_INIT(&conn->svcs);
SLIST_INIT(&conn->coc_list);
return conn;
}
static void
btshell_conn_delete_idx(int idx)
{
struct btshell_conn *conn;
struct btshell_svc *svc;
assert(idx >= 0 && idx < btshell_num_conns);
conn = btshell_conns + idx;
while ((svc = SLIST_FIRST(&conn->svcs)) != NULL) {
SLIST_REMOVE_HEAD(&conn->svcs, next);
btshell_svc_delete(svc);
}
/* This '#if' is not strictly necessary. It is here to prevent a spurious
* warning from being reported.
*/
#if MYNEWT_VAL(BLE_MAX_CONNECTIONS) > 1
int i;
for (i = idx + 1; i < btshell_num_conns; i++) {
btshell_conns[i - 1] = btshell_conns[i];
}
#endif
btshell_num_conns--;
}
static int
btshell_on_mtu(uint16_t conn_handle, const struct ble_gatt_error *error,
uint16_t mtu, void *arg)
{
switch (error->status) {
case 0:
console_printf("mtu exchange complete: conn_handle=%d mtu=%d\n",
conn_handle, mtu);
break;
default:
btshell_print_error(NULL, conn_handle, error);
break;
}
return 0;
}
static void
btshell_full_disc_complete(int rc)
{
console_printf("full discovery complete; rc=%d\n", rc);
btshell_full_disc_prev_chr_val = 0;
}
static void
btshell_disc_full_dscs(uint16_t conn_handle)
{
struct btshell_conn *conn;
struct btshell_chr *chr;
struct btshell_svc *svc;
int rc;
conn = btshell_conn_find(conn_handle);
if (conn == NULL) {
MODLOG_DFLT(DEBUG, "Failed to discover descriptors for conn=%d; "
"not connected\n", conn_handle);
btshell_full_disc_complete(BLE_HS_ENOTCONN);
return;
}
SLIST_FOREACH(svc, &conn->svcs, next) {
SLIST_FOREACH(chr, &svc->chrs, next) {
if (!chr_is_empty(svc, chr) &&
SLIST_EMPTY(&chr->dscs) &&
btshell_full_disc_prev_chr_val <= chr->chr.def_handle) {
rc = btshell_disc_all_dscs(conn_handle,
chr->chr.val_handle,
chr_end_handle(svc, chr));
if (rc != 0) {
btshell_full_disc_complete(rc);
}
btshell_full_disc_prev_chr_val = chr->chr.val_handle;
return;
}
}
}
/* All descriptors discovered. */
btshell_full_disc_complete(0);
}
static void
btshell_disc_full_chrs(uint16_t conn_handle)
{
struct btshell_conn *conn;
struct btshell_svc *svc;
int rc;
conn = btshell_conn_find(conn_handle);
if (conn == NULL) {
MODLOG_DFLT(DEBUG, "Failed to discover characteristics for conn=%d; "
"not connected\n", conn_handle);
btshell_full_disc_complete(BLE_HS_ENOTCONN);
return;
}
SLIST_FOREACH(svc, &conn->svcs, next) {
if (!svc->discovered) {
rc = btshell_disc_all_chrs_in_svc(conn_handle, svc);
if (rc != 0) {
btshell_full_disc_complete(rc);
}
return;
}
}
/* All characteristics discovered. */
btshell_disc_full_dscs(conn_handle);
}
static int
btshell_on_disc_s(uint16_t conn_handle, const struct ble_gatt_error *error,
const struct ble_gatt_svc *service, void *arg)
{
switch (error->status) {
case 0:
btshell_svc_add(conn_handle, service);
break;
case BLE_HS_EDONE:
console_printf("service discovery successful\n");
if (btshell_full_disc_prev_chr_val > 0) {
btshell_disc_full_chrs(conn_handle);
}
break;
default:
btshell_print_error(NULL, conn_handle, error);
break;
}
return 0;
}
static int
btshell_on_disc_c(uint16_t conn_handle, const struct ble_gatt_error *error,
const struct ble_gatt_chr *chr, void *arg)
{
intptr_t svc_start_handle;
svc_start_handle = (intptr_t)arg;
switch (error->status) {
case 0:
btshell_chr_add(conn_handle, svc_start_handle, chr);
break;
case BLE_HS_EDONE:
console_printf("characteristic discovery successful\n");
if (btshell_full_disc_prev_chr_val > 0) {
btshell_disc_full_chrs(conn_handle);
}
break;
default:
btshell_print_error(NULL, conn_handle, error);
break;
}
return 0;
}
static int
btshell_on_disc_c_in_s(uint16_t conn_handle, const struct ble_gatt_error *error,
const struct ble_gatt_chr *chr, void *arg)
{
struct btshell_svc *svc = arg;
switch (error->status) {
case 0:
btshell_chr_add(conn_handle, svc->svc.start_handle, chr);
break;
case BLE_HS_EDONE:
svc->discovered = true;
console_printf("characteristic discovery successful\n");
if (btshell_full_disc_prev_chr_val > 0) {
btshell_disc_full_chrs(conn_handle);
}
break;
default:
btshell_print_error(NULL, conn_handle, error);
break;
}
return 0;
}
static int
btshell_on_disc_d(uint16_t conn_handle, const struct ble_gatt_error *error,
uint16_t chr_val_handle, const struct ble_gatt_dsc *dsc,
void *arg)
{
switch (error->status) {
case 0:
btshell_dsc_add(conn_handle, chr_val_handle, dsc);
break;
case BLE_HS_EDONE:
console_printf("descriptor discovery successful\n");
if (btshell_full_disc_prev_chr_val > 0) {
btshell_disc_full_dscs(conn_handle);
}
break;
default:
btshell_print_error(NULL, conn_handle, error);
break;
}
return 0;
}
static int
btshell_on_read_var(uint16_t conn_handle, const struct ble_gatt_error *error,
struct ble_gatt_attr *attr, uint8_t num_attrs, void *arg)
{
int i;
switch (error->status) {
case 0:
console_printf("characteristic read; conn_handle=%d , number of attributes=%d\n", conn_handle, num_attrs);
for (i = 0; i < num_attrs; i++) {
console_printf("\t attr_handle=%d, len=%d value=",
attr[i].handle, OS_MBUF_PKTLEN(attr[i].om));
print_mbuf(attr[i].om);
console_printf("\n");
}
break;
case BLE_HS_EDONE:
console_printf("characteristic read complete\n");
break;
default:
btshell_print_error(NULL, conn_handle, error);
break;
}
return 0;
}
static int
btshell_on_read(uint16_t conn_handle, const struct ble_gatt_error *error,
struct ble_gatt_attr *attr, void *arg)
{
switch (error->status) {
case 0:
console_printf("characteristic read; conn_handle=%d "
"attr_handle=%d len=%d value=", conn_handle,
attr->handle, OS_MBUF_PKTLEN(attr->om));
print_mbuf(attr->om);
console_printf("\n");
break;
case BLE_HS_EDONE:
console_printf("characteristic read complete\n");
break;
default:
btshell_print_error(NULL, conn_handle, error);
break;
}
return 0;
}
static int
btshell_on_write(uint16_t conn_handle, const struct ble_gatt_error *error,
struct ble_gatt_attr *attr, void *arg)
{
switch (error->status) {
case 0:
console_printf("characteristic write complete; conn_handle=%d "
"attr_handle=%d\n", conn_handle, attr->handle);
break;
default:
btshell_print_error(NULL, conn_handle, error);
break;
}
return 0;
}
static int
btshell_on_write_reliable(uint16_t conn_handle,
const struct ble_gatt_error *error,
struct ble_gatt_attr *attrs, uint8_t num_attrs,
void *arg)
{
int i;
switch (error->status) {
case 0:
console_printf("characteristic write reliable complete; "
"conn_handle=%d", conn_handle);
for (i = 0; i < num_attrs; i++) {
console_printf(" attr_handle=%d len=%d value=", attrs[i].handle,
OS_MBUF_PKTLEN(attrs[i].om));
print_mbuf(attrs[i].om);
}
console_printf("\n");
break;
default:
btshell_print_error(NULL, conn_handle, error);
break;
}
return 0;
}
static void
btshell_decode_adv_data(const uint8_t *adv_data, uint8_t adv_data_len, void *arg)
{
struct btshell_scan_opts *scan_opts = arg;
struct ble_hs_adv_fields fields;
console_printf(" data_length=%d data=", adv_data_len);
if (scan_opts) {
adv_data_len = min(adv_data_len, scan_opts->limit);
}
print_bytes(adv_data, adv_data_len);
console_printf(" fields:\n");
ble_hs_adv_parse_fields(&fields, adv_data, adv_data_len);
btshell_print_adv_fields(&fields);
}
#if MYNEWT_VAL(BLE_EXT_ADV)
static void
btshell_decode_event_type(struct ble_gap_ext_disc_desc *desc, void *arg)
{
const struct ble_hs_adv_field *ad_name = NULL;
struct btshell_scan_opts *scan_opts = arg;
uint8_t directed = 0;
if (scan_opts && scan_opts->name_filter_len) {
if (ble_hs_adv_find_field(BLE_HS_ADV_TYPE_COMP_NAME, desc->data,
desc->length_data, &ad_name)) {
ble_hs_adv_find_field(BLE_HS_ADV_TYPE_INCOMP_NAME, desc->data,
desc->length_data, &ad_name);
}
if (!ad_name) {
return;
}
if (ad_name->length < scan_opts->name_filter_len) {
return;
}
if (strncasecmp(scan_opts->name_filter, (const char *)ad_name->value,
scan_opts->name_filter_len)) {
return;
}
}
if (desc->props & BLE_HCI_ADV_LEGACY_MASK) {
if (scan_opts && scan_opts->ignore_legacy) {
return;
}
console_printf("Legacy PDU type %d", desc->legacy_event_type);
if (desc->legacy_event_type == BLE_HCI_ADV_RPT_EVTYPE_DIR_IND) {
directed = 1;
}
goto common_data;
} else {
if (scan_opts && scan_opts->periodic_only && desc->periodic_adv_itvl == 0) {
return;
}
}
console_printf("Extended adv: ");
if (desc->props & BLE_HCI_ADV_CONN_MASK) {
console_printf("'conn' ");
}
if (desc->props & BLE_HCI_ADV_SCAN_MASK) {
console_printf("'scan' ");
}
if (desc->props & BLE_HCI_ADV_DIRECT_MASK) {
console_printf("'dir' ");
directed = 1;
}
if (desc->props & BLE_HCI_ADV_SCAN_RSP_MASK) {
console_printf("'scan rsp' ");
}
switch(desc->data_status) {
case BLE_GAP_EXT_ADV_DATA_STATUS_COMPLETE:
console_printf("complete");
break;
case BLE_GAP_EXT_ADV_DATA_STATUS_INCOMPLETE:
console_printf("incomplete");
break;
case BLE_GAP_EXT_ADV_DATA_STATUS_TRUNCATED:
console_printf("truncated");
break;
default:
console_printf("reserved %d", desc->data_status);
break;
}
common_data:
console_printf(" rssi=%d txpower=%d, pphy=%d, sphy=%d, sid=%d,"
" periodic_adv_itvl=%u, addr_type=%d addr=",
desc->rssi, desc->tx_power, desc->prim_phy, desc->sec_phy,
desc->sid, desc->periodic_adv_itvl, desc->addr.type);
print_addr(desc->addr.val);
if (directed) {
console_printf(" init_addr_type=%d inita=", desc->direct_addr.type);
print_addr(desc->direct_addr.val);
}
console_printf("\n");
if(!desc->length_data) {
return;
}
btshell_decode_adv_data(desc->data, desc->length_data, arg);
}
#endif
static int
btshell_restart_adv(struct ble_gap_event *event)
{
int rc = 0;
#if MYNEWT_VAL(BLE_EXT_ADV)
uint8_t i;
#endif
if (event->type != BLE_GAP_EVENT_DISCONNECT) {
return -1;
}
#if MYNEWT_VAL(BLE_EXT_ADV)
for (i = 0; i < BLE_ADV_INSTANCES; ++i) {
if (ext_adv_restart[i].restart &&
(ext_adv_restart[i].conn_handle ==
event->disconnect.conn.conn_handle)) {
rc = ble_gap_ext_adv_start(i, 0, 0);
break;
}
}
#else
if (!adv_params.restart) {
return 0;
}
rc = ble_gap_adv_start(adv_params.own_addr_type, &adv_params.direct_addr,
adv_params.duration_ms, &adv_params.params,
btshell_gap_event, NULL);
#endif
return rc;
}
#if MYNEWT_VAL(BLE_PERIODIC_ADV)
struct psync {
bool established;
unsigned int complete;
unsigned int truncated;
size_t off;
bool changed;
uint8_t data[1650]; /* TODO make this configurable */
};
static struct psync g_periodic_data[MYNEWT_VAL(BLE_MAX_PERIODIC_SYNCS)];
void
btshell_sync_stats(uint16_t handle)
{
struct psync *psync;
if (handle >= MYNEWT_VAL(BLE_MAX_PERIODIC_SYNCS)) {
return;
}
psync = &g_periodic_data[handle];
if (!psync->established) {
console_printf("Sync not established\n");
return;
}
console_printf("completed=%u truncated=%u\n",
psync->complete, psync->truncated);
}
static void
handle_periodic_report(struct ble_gap_event *event)
{
struct psync *psync;
uint16_t handle = event->periodic_report.sync_handle;
if (handle >= MYNEWT_VAL(BLE_MAX_PERIODIC_SYNCS)) {
return;
}
psync = &g_periodic_data[handle];
if (psync->changed ||
memcmp(psync->data + psync->off, event->periodic_report.data,
event->periodic_report.data_length)) {
/* first fragment with changed data */
if (!psync->changed) {
console_printf("Sync data changed, completed=%u, truncated=%u\n",
psync->complete, psync->truncated);
}
psync->changed = true;
console_printf("Sync report handle=%u status=", handle);
switch(event->periodic_report.data_status) {
case BLE_HCI_PERIODIC_DATA_STATUS_COMPLETE:
console_printf("complete");
break;
case BLE_HCI_PERIODIC_DATA_STATUS_INCOMPLETE:
console_printf("incomplete");
break;
case BLE_HCI_PERIODIC_DATA_STATUS_TRUNCATED:
console_printf("truncated");
break;
default:
console_printf("reserved 0x%x", event->periodic_report.data_status);
break;
}
btshell_decode_adv_data(event->periodic_report.data,
event->periodic_report.data_length, NULL);
psync->complete = 0;
psync->truncated = 0;
}
/* cache data */
memcpy(psync->data + psync->off, event->periodic_report.data,
event->periodic_report.data_length);
switch(event->periodic_report.data_status) {
case BLE_HCI_PERIODIC_DATA_STATUS_INCOMPLETE:
psync->off += event->periodic_report.data_length;
break;
case BLE_HCI_PERIODIC_DATA_STATUS_COMPLETE:
psync->complete++;
psync->off = 0;
psync->changed = false;
break;
case BLE_HCI_PERIODIC_DATA_STATUS_TRUNCATED:
psync->truncated++;
psync->off = 0;
psync->changed = false;
break;
default:
break;
}
}
#endif
int
btshell_gap_event(struct ble_gap_event *event, void *arg)
{
struct ble_gap_conn_desc desc;
int conn_idx;
int rc;
#if MYNEWT_VAL(BLE_PERIODIC_ADV)
struct psync *psync;
#endif
switch (event->type) {
case BLE_GAP_EVENT_CONNECT:
console_printf("connection %s; status=%d ",
event->connect.status == 0 ? "established" : "failed",
event->connect.status);
if (event->connect.status == 0) {
rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
assert(rc == 0);
print_conn_desc(&desc);
btshell_conn_add(&desc);
}
return 0;
case BLE_GAP_EVENT_DISCONNECT:
console_printf("disconnect; reason=%d ", event->disconnect.reason);
print_conn_desc(&event->disconnect.conn);
conn_idx = btshell_conn_find_idx(event->disconnect.conn.conn_handle);
if (conn_idx != -1) {
btshell_conn_delete_idx(conn_idx);
}
return btshell_restart_adv(event);
#if MYNEWT_VAL(BLE_EXT_ADV)
case BLE_GAP_EVENT_EXT_DISC:
btshell_decode_event_type(&event->ext_disc, arg);
return 0;
#endif
case BLE_GAP_EVENT_DISC:
console_printf("received advertisement; event_type=%d rssi=%d "
"addr_type=%d addr=", event->disc.event_type,
event->disc.rssi, event->disc.addr.type);
print_addr(event->disc.addr.val);
/*
* There is no adv data to print in case of connectable
* directed advertising
*/
if (event->disc.event_type == BLE_HCI_ADV_RPT_EVTYPE_DIR_IND) {
console_printf("\nConnectable directed advertising event\n");
return 0;
}
btshell_decode_adv_data(event->disc.data, event->disc.length_data, arg);
return 0;
case BLE_GAP_EVENT_CONN_UPDATE:
console_printf("connection updated; status=%d ",
event->conn_update.status);
rc = ble_gap_conn_find(event->conn_update.conn_handle, &desc);
assert(rc == 0);
print_conn_desc(&desc);
return 0;
case BLE_GAP_EVENT_CONN_UPDATE_REQ:
console_printf("connection update request\n");
*event->conn_update_req.self_params =
*event->conn_update_req.peer_params;
return 0;
case BLE_GAP_EVENT_PASSKEY_ACTION:
console_printf("passkey action event; action=%d",
event->passkey.params.action);
if (event->passkey.params.action == BLE_SM_IOACT_NUMCMP) {
console_printf(" numcmp=%lu",
(unsigned long)event->passkey.params.numcmp);
}
console_printf("\n");
return 0;
case BLE_GAP_EVENT_DISC_COMPLETE:
console_printf("discovery complete; reason=%d\n",
event->disc_complete.reason);
return 0;
case BLE_GAP_EVENT_ADV_COMPLETE:
#if MYNEWT_VAL(BLE_EXT_ADV)
console_printf("advertise complete; reason=%d, instance=%u, handle=%d\n",
event->adv_complete.reason, event->adv_complete.instance,
event->adv_complete.conn_handle);
ext_adv_restart[event->adv_complete.instance].conn_handle =
event->adv_complete.conn_handle;
#else
console_printf("advertise complete; reason=%d\n",
event->adv_complete.reason);
#endif
return 0;
case BLE_GAP_EVENT_ENC_CHANGE:
console_printf("encryption change event; status=%d ",
event->enc_change.status);
rc = ble_gap_conn_find(event->enc_change.conn_handle, &desc);
assert(rc == 0);
print_conn_desc(&desc);
return 0;
case BLE_GAP_EVENT_NOTIFY_RX:
console_printf("notification rx event; attr_handle=%d indication=%d "
"len=%d data=",
event->notify_rx.attr_handle,
event->notify_rx.indication,
OS_MBUF_PKTLEN(event->notify_rx.om));
print_mbuf(event->notify_rx.om);
console_printf("\n");
return 0;
case BLE_GAP_EVENT_NOTIFY_TX:
console_printf("notification tx event; status=%d attr_handle=%d "
"indication=%d\n",
event->notify_tx.status,
event->notify_tx.attr_handle,
event->notify_tx.indication);
return 0;
case BLE_GAP_EVENT_SUBSCRIBE:
console_printf("subscribe event; conn_handle=%d attr_handle=%d "
"reason=%d prevn=%d curn=%d previ=%d curi=%d\n",
event->subscribe.conn_handle,
event->subscribe.attr_handle,
event->subscribe.reason,
event->subscribe.prev_notify,
event->subscribe.cur_notify,
event->subscribe.prev_indicate,
event->subscribe.cur_indicate);
return 0;
case BLE_GAP_EVENT_MTU:
console_printf("mtu update event; conn_handle=%d cid=%d mtu=%d\n",
event->mtu.conn_handle,
event->mtu.channel_id,
event->mtu.value);
return 0;
case BLE_GAP_EVENT_IDENTITY_RESOLVED:
console_printf("identity resolved ");
rc = ble_gap_conn_find(event->identity_resolved.conn_handle, &desc);
assert(rc == 0);
print_conn_desc(&desc);
return 0;
case BLE_GAP_EVENT_PHY_UPDATE_COMPLETE:
console_printf("PHY update complete; status=%d, conn_handle=%d "
" tx_phy=%d, rx_phy=%d\n",
event->phy_updated.status,
event->phy_updated.conn_handle,
event->phy_updated.tx_phy,
event->phy_updated.rx_phy);
return 0;
case BLE_GAP_EVENT_REPEAT_PAIRING:
/* We already have a bond with the peer, but it is attempting to
* establish a new secure link. This app sacrifices security for
* convenience: just throw away the old bond and accept the new link.
*/
/* Delete the old bond. */
rc = ble_gap_conn_find(event->repeat_pairing.conn_handle, &desc);
assert(rc == 0);
ble_store_util_delete_peer(&desc.peer_id_addr);
/* Return BLE_GAP_REPEAT_PAIRING_RETRY to indicate that the host should
* continue with the pairing operation.
*/
return BLE_GAP_REPEAT_PAIRING_RETRY;
#if MYNEWT_VAL(BLE_PERIODIC_ADV)
case BLE_GAP_EVENT_PERIODIC_SYNC:
if (event->periodic_sync.status) {
console_printf("Periodic Sync Establishment Failed; status=%u\n",
event->periodic_sync.status);
} else {
console_printf("Periodic Sync Established; sync_handle=%u sid=%u "
"phy=%u adv_interval=%u ca=%u addr_type=%u addr=",
event->periodic_sync.sync_handle,
event->periodic_sync.sid, event->periodic_sync.adv_phy,
event->periodic_sync.per_adv_ival,
event->periodic_sync.adv_clk_accuracy,
event->periodic_sync.adv_addr.type);
print_addr(event->periodic_sync.adv_addr.val);
console_printf("\n");
/* TODO non-NimBLE controllers may not start handles from 0 */
if (event->periodic_sync.sync_handle >= MYNEWT_VAL(BLE_MAX_PERIODIC_SYNCS)) {
console_printf("Unable to prepare cache for sync data\n");
} else {
psync = &g_periodic_data[event->periodic_sync.sync_handle];
memset(psync, 0, sizeof(*psync));
psync->changed = true;
psync->established = true;
}
}
return 0;
case BLE_GAP_EVENT_PERIODIC_SYNC_LOST:
/* TODO non-NimBLE controllers may not start handles from 0 */
if (event->periodic_sync_lost.sync_handle >= MYNEWT_VAL(BLE_MAX_PERIODIC_SYNCS)) {
console_printf("Periodic Sync Lost; sync_handle=%d reason=%d\n",
event->periodic_sync_lost.sync_handle,
event->periodic_sync_lost.reason);
} else {
psync = &g_periodic_data[event->periodic_sync_lost.sync_handle];
console_printf("Periodic Sync Lost; sync_handle=%d reason=%d completed=%u truncated=%u\n",
event->periodic_sync_lost.sync_handle,
event->periodic_sync_lost.reason,
psync->complete, psync->truncated);
memset(psync, 0, sizeof(*psync));
}
return 0;
case BLE_GAP_EVENT_PERIODIC_REPORT:
handle_periodic_report(event);
return 0;
#if MYNEWT_VAL(BLE_PERIODIC_ADV_SYNC_TRANSFER)
case BLE_GAP_EVENT_PERIODIC_TRANSFER:
console_printf("Periodic Sync Transfer Received on conn=%u; status=%u,"
" sync_handle=%u sid=%u phy=%u adv_interval=%u ca=%u "
"addr_type=%u addr=",
event->periodic_transfer.conn_handle,
event->periodic_transfer.status,
event->periodic_transfer.sync_handle,
event->periodic_transfer.sid,
event->periodic_transfer.adv_phy,
event->periodic_transfer.per_adv_itvl,
event->periodic_transfer.adv_clk_accuracy,
event->periodic_transfer.adv_addr.type);
print_addr(event->periodic_transfer.adv_addr.val);
console_printf("\n");
if (!event->periodic_transfer.status) {
/* TODO non-NimBLE controllers may not start handles from 0 */
if (event->periodic_transfer.sync_handle >= MYNEWT_VAL(BLE_MAX_PERIODIC_SYNCS)) {
console_printf("Unable to prepare cache for sync data\n");
} else {
psync = &g_periodic_data[event->periodic_transfer.sync_handle];
memset(psync, 0, sizeof(*psync));
psync->changed = true;
psync->established = true;
}
}
return 0;
#endif
#endif
default:
return 0;
}
}
static void
btshell_on_l2cap_update(uint16_t conn_handle, int status, void *arg)
{
console_printf("l2cap update complete; conn_handle=%d status=%d\n",
conn_handle, status);
}
static void
btshell_tx_timer_cb(struct os_event *ev)
{
uint8_t i;
uint8_t len;
int32_t timeout;
struct ble_l2cap_hdr l2cap_hdr;
struct os_mbuf *om;
if ((btshell_tx_data.tx_num == 0) || (btshell_tx_data.tx_len == 0)) {
return;
}
console_printf("Sending %d/%d len: %d\n",
btshell_tx_data.tx_num_requested - btshell_tx_data.tx_num + 1,
btshell_tx_data.tx_num_requested, btshell_tx_data.tx_len);
len = btshell_tx_data.tx_len;
om = NULL;
if (os_msys_num_free() >= 4) {
om = os_msys_get_pkthdr(len + BLE_L2CAP_HDR_SZ, BLE_HCI_DATA_HDR_SZ);
}
if (om) {
/*
* NOTE: CID is 0xffff so it is not confused with valid l2cap channel.
* The rest of the data gets filled with incrementing pattern starting
* from 0.
*/
put_le16(&l2cap_hdr.len, len);
put_le16(&l2cap_hdr.cid, 0xffff);
os_mbuf_append(om, (void *)&l2cap_hdr, BLE_L2CAP_HDR_SZ);
for (i = 0; i < len; ++i) {
os_mbuf_append(om, (void *)&i, 1);
}
ble_hs_lock();
ble_hs_hci_acl_tx_now(btshell_tx_data.conn, &om);
ble_hs_unlock();
--btshell_tx_data.tx_num;
}
if (btshell_tx_data.tx_num) {
timeout = (int32_t)btshell_tx_data.tx_rate;
timeout = (timeout * OS_TICKS_PER_SEC) / 1000;
os_callout_reset(&btshell_tx_timer, timeout);
}
}
int
btshell_exchange_mtu(uint16_t conn_handle)
{
int rc;
rc = ble_gattc_exchange_mtu(conn_handle, btshell_on_mtu, NULL);
return rc;
}
int
btshell_disc_all_chrs(uint16_t conn_handle, uint16_t start_handle,
uint16_t end_handle)
{
intptr_t svc_start_handle;
int rc;
svc_start_handle = start_handle;
rc = ble_gattc_disc_all_chrs(conn_handle, start_handle, end_handle,
btshell_on_disc_c, (void *)svc_start_handle);
return rc;
}
int
btshell_disc_all_chrs_in_svc(uint16_t conn_handle, struct btshell_svc *svc)
{
int rc;
rc = ble_gattc_disc_all_chrs(conn_handle, svc->svc.start_handle,
svc->svc.end_handle, btshell_on_disc_c_in_s,
svc);
return rc;
}
int
btshell_disc_chrs_by_uuid(uint16_t conn_handle, uint16_t start_handle,
uint16_t end_handle, const ble_uuid_t *uuid)
{
intptr_t svc_start_handle;
int rc;
svc_start_handle = start_handle;
rc = ble_gattc_disc_chrs_by_uuid(conn_handle, start_handle, end_handle,
uuid, btshell_on_disc_c,
(void *)svc_start_handle);
return rc;
}
int
btshell_disc_svcs(uint16_t conn_handle)
{
int rc;
rc = ble_gattc_disc_all_svcs(conn_handle, btshell_on_disc_s, NULL);
return rc;
}
int
btshell_disc_svc_by_uuid(uint16_t conn_handle, const ble_uuid_t *uuid)
{
int rc;
rc = ble_gattc_disc_svc_by_uuid(conn_handle, uuid,
btshell_on_disc_s, NULL);
return rc;
}
int
btshell_disc_all_dscs(uint16_t conn_handle, uint16_t start_handle,
uint16_t end_handle)
{
int rc;
rc = ble_gattc_disc_all_dscs(conn_handle, start_handle, end_handle,
btshell_on_disc_d, NULL);
return rc;
}
int
btshell_disc_full(uint16_t conn_handle)
{
struct btshell_conn *conn;
struct btshell_svc *svc;
/* Undiscover everything first. */
conn = btshell_conn_find(conn_handle);
if (conn == NULL) {
return BLE_HS_ENOTCONN;
}
while ((svc = SLIST_FIRST(&conn->svcs)) != NULL) {
SLIST_REMOVE_HEAD(&conn->svcs, next);
btshell_svc_delete(svc);
}
btshell_full_disc_prev_chr_val = 1;
btshell_disc_svcs(conn_handle);
return 0;
}
int
btshell_find_inc_svcs(uint16_t conn_handle, uint16_t start_handle,
uint16_t end_handle)
{
int rc;
rc = ble_gattc_find_inc_svcs(conn_handle, start_handle, end_handle,
btshell_on_disc_s, NULL);
return rc;
}
int
btshell_read(uint16_t conn_handle, uint16_t attr_handle)
{
struct os_mbuf *om;
int rc;
if (conn_handle == BLE_HS_CONN_HANDLE_NONE) {
rc = ble_att_svr_read_local(attr_handle, &om);
if (rc == 0) {
console_printf("read local; attr_handle=%d len=%d value=",
attr_handle, OS_MBUF_PKTLEN(om));
print_mbuf(om);
console_printf("\n");
os_mbuf_free_chain(om);
}
} else {
rc = ble_gattc_read(conn_handle, attr_handle, btshell_on_read, NULL);
}
return rc;
}
int
btshell_read_long(uint16_t conn_handle, uint16_t attr_handle, uint16_t offset)
{
int rc;
rc = ble_gattc_read_long(conn_handle, attr_handle, offset,
btshell_on_read, NULL);
return rc;
}
int
btshell_read_by_uuid(uint16_t conn_handle, uint16_t start_handle,
uint16_t end_handle, const ble_uuid_t *uuid)
{
int rc;
rc = ble_gattc_read_by_uuid(conn_handle, start_handle, end_handle, uuid,
btshell_on_read, NULL);
return rc;
}
int
btshell_read_mult(uint16_t conn_handle, uint16_t *attr_handles,
int num_attr_handles, bool variable)
{
if (variable) {
return ble_gattc_read_mult_var(conn_handle, attr_handles, num_attr_handles,
btshell_on_read_var, NULL);
}
return ble_gattc_read_mult(conn_handle, attr_handles,
num_attr_handles,
btshell_on_read, NULL);
}
int
btshell_write(uint16_t conn_handle, uint16_t attr_handle, struct os_mbuf *om)
{
int rc;
if (conn_handle == BLE_HS_CONN_HANDLE_NONE) {
rc = ble_att_svr_write_local(attr_handle, om);
} else {
rc = ble_gattc_write(conn_handle, attr_handle, om,
btshell_on_write, NULL);
}
return rc;
}
int
btshell_write_no_rsp(uint16_t conn_handle, uint16_t attr_handle,
struct os_mbuf *om)
{
int rc;
rc = ble_gattc_write_no_rsp(conn_handle, attr_handle, om);
return rc;
}
int
btshell_write_long(uint16_t conn_handle, uint16_t attr_handle,
uint16_t offset, struct os_mbuf *om)
{
int rc;
rc = ble_gattc_write_long(conn_handle, attr_handle, offset,
om, btshell_on_write, NULL);
return rc;
}
int
btshell_write_reliable(uint16_t conn_handle,
struct ble_gatt_attr *attrs,
int num_attrs)
{
int rc;
rc = ble_gattc_write_reliable(conn_handle, attrs, num_attrs,
btshell_on_write_reliable, NULL);
return rc;
}
#if MYNEWT_VAL(BLE_EXT_ADV)
int
btshell_ext_adv_configure(uint8_t instance,
const struct ble_gap_ext_adv_params *params,
int8_t *selected_tx_power)
{
return ble_gap_ext_adv_configure(instance, params, selected_tx_power,
btshell_gap_event, NULL);
}
int
btshell_ext_adv_start(uint8_t instance, int duration,
int max_events, bool restart)
{
int rc;
/* Advertising restart doesn't make sense
* with limited duration or events
*/
if (restart && (duration == 0) && (max_events == 0)) {
ext_adv_restart[instance].restart = restart;
}
rc = ble_gap_ext_adv_start(instance, duration, max_events);
return rc;
}
int
btshell_ext_adv_stop(uint8_t instance)
{
int rc;
ext_adv_restart[instance].restart = false;
rc = ble_gap_ext_adv_stop(instance);
return rc;
}
#endif
int
btshell_adv_stop(void)
{
int rc;
adv_params.restart = false;
rc = ble_gap_adv_stop();
return rc;
}
int
btshell_adv_start(uint8_t own_addr_type, const ble_addr_t *direct_addr,
int32_t duration_ms, const struct ble_gap_adv_params *params,
bool restart)
{
int rc;
if (restart) {
adv_params.restart = restart;
adv_params.own_addr_type = own_addr_type;
adv_params.duration_ms = duration_ms;
if (direct_addr) {
memcpy(&adv_params.direct_addr, direct_addr, sizeof(adv_params.direct_addr));
}
if (params) {
memcpy(&adv_params.params, params, sizeof(adv_params.params));
}
}
rc = ble_gap_adv_start(own_addr_type, direct_addr, duration_ms, params,
btshell_gap_event, NULL);
return rc;
}
int
btshell_conn_initiate(uint8_t own_addr_type, const ble_addr_t *peer_addr,
int32_t duration_ms, struct ble_gap_conn_params *params)
{
int rc;
rc = ble_gap_connect(own_addr_type, peer_addr, duration_ms, params,
btshell_gap_event, NULL);
return rc;
}
int
btshell_ext_conn_initiate(uint8_t own_addr_type, const ble_addr_t *peer_addr,
int32_t duration_ms,
struct ble_gap_conn_params *phy_1m_params,
struct ble_gap_conn_params *phy_2m_params,
struct ble_gap_conn_params *phy_coded_params)
{
#if !MYNEWT_VAL(BLE_EXT_ADV)
console_printf("BLE extended advertising not supported.");
console_printf(" Configure nimble host to enable it\n");
return 0;
#else
int rc;
uint8_t phy_mask = 0;
if (phy_1m_params) {
phy_mask |= BLE_GAP_LE_PHY_1M_MASK;
}
if (phy_2m_params) {
phy_mask |= BLE_GAP_LE_PHY_2M_MASK;
}
if (phy_coded_params) {
phy_mask |= BLE_GAP_LE_PHY_CODED_MASK;
}
rc = ble_gap_ext_connect(own_addr_type, peer_addr, duration_ms, phy_mask,
phy_1m_params, phy_2m_params, phy_coded_params,
btshell_gap_event, NULL);
return rc;
#endif
}
int
btshell_conn_cancel(void)
{
int rc;
rc = ble_gap_conn_cancel();
return rc;
}
int
btshell_term_conn(uint16_t conn_handle, uint8_t reason)
{
int rc;
rc = ble_gap_terminate(conn_handle, reason);
return rc;
}
int
btshell_wl_set(ble_addr_t *addrs, int addrs_count)
{
int rc;
rc = ble_gap_wl_set(addrs, addrs_count);
return rc;
}
int
btshell_scan(uint8_t own_addr_type, int32_t duration_ms,
const struct ble_gap_disc_params *disc_params, void *cb_args)
{
int rc;
rc = ble_gap_disc(own_addr_type, duration_ms, disc_params,
btshell_gap_event, cb_args);
return rc;
}
int
btshell_ext_scan(uint8_t own_addr_type, uint16_t duration, uint16_t period,
uint8_t filter_duplicates, uint8_t filter_policy,
uint8_t limited,
const struct ble_gap_ext_disc_params *uncoded_params,
const struct ble_gap_ext_disc_params *coded_params,
void *cb_args)
{
#if !MYNEWT_VAL(BLE_EXT_ADV)
console_printf("BLE extended advertising not supported.");
console_printf(" Configure nimble host to enable it\n");
return 0;
#else
int rc;
rc = ble_gap_ext_disc(own_addr_type, duration, period, filter_duplicates,
filter_policy, limited, uncoded_params, coded_params,
btshell_gap_event, cb_args);
return rc;
#endif
}
int
btshell_scan_cancel(void)
{
int rc;
rc = ble_gap_disc_cancel();
return rc;
}
int
btshell_update_conn(uint16_t conn_handle, struct ble_gap_upd_params *params)
{
int rc;
rc = ble_gap_update_params(conn_handle, params);
return rc;
}
void
btshell_notify(uint16_t attr_handle)
{
ble_gatts_chr_updated(attr_handle);
}
int
btshell_datalen(uint16_t conn_handle, uint16_t tx_octets, uint16_t tx_time)
{
int rc;
rc = ble_hs_hci_util_set_data_len(conn_handle, tx_octets, tx_time);
return rc;
}
int
btshell_l2cap_update(uint16_t conn_handle,
struct ble_l2cap_sig_update_params *params)
{
int rc;
rc = ble_l2cap_sig_update(conn_handle, params, btshell_on_l2cap_update,
NULL);
return rc;
}
int
btshell_sec_pair(uint16_t conn_handle)
{
#if !NIMBLE_BLE_SM
return BLE_HS_ENOTSUP;
#endif
int rc;
rc = ble_gap_pair_initiate(conn_handle);
return rc;
}
int
btshell_sec_unpair(ble_addr_t *peer_addr)
{
#if !NIMBLE_BLE_SM
return BLE_HS_ENOTSUP;
#endif
int rc;
rc = ble_gap_unpair(peer_addr);
return rc;
}
int
btshell_sec_start(uint16_t conn_handle)
{
#if !NIMBLE_BLE_SM
return BLE_HS_ENOTSUP;
#endif
int rc;
rc = ble_gap_security_initiate(conn_handle);
return rc;
}
int
btshell_sec_restart(uint16_t conn_handle,
uint8_t key_size,
uint8_t *ltk,
uint16_t ediv,
uint64_t rand_val,
int auth)
{
#if !NIMBLE_BLE_SM
return BLE_HS_ENOTSUP;
#endif
struct ble_store_value_sec value_sec;
struct ble_store_key_sec key_sec;
struct ble_gap_conn_desc desc;
ble_hs_conn_flags_t conn_flags;
int rc;
if (ltk == NULL) {
/* The user is requesting a store lookup. */
rc = ble_gap_conn_find(conn_handle, &desc);
if (rc != 0) {
return rc;
}
memset(&key_sec, 0, sizeof key_sec);
key_sec.peer_addr = desc.peer_id_addr;
rc = ble_hs_atomic_conn_flags(conn_handle, &conn_flags);
if (rc != 0) {
return rc;
}
if (conn_flags & BLE_HS_CONN_F_MASTER) {
rc = ble_store_read_peer_sec(&key_sec, &value_sec);
} else {
rc = ble_store_read_our_sec(&key_sec, &value_sec);
}
if (rc != 0) {
return rc;
}
ltk = value_sec.ltk;
key_size = value_sec.key_size;
ediv = value_sec.ediv;
rand_val = value_sec.rand_num;
auth = value_sec.authenticated;
}
rc = ble_gap_encryption_initiate(conn_handle, key_size, ltk,
ediv, rand_val, auth);
return rc;
}
/**
* Called to start transmitting 'num' packets at rate 'rate' of size 'size'
* to connection handle 'handle'
*
* @param handle
* @param len
* @param rate
* @param num
*
* @return int
*/
int
btshell_tx_start(uint16_t conn_handle, uint16_t len, uint16_t rate, uint16_t num)
{
/* Cannot be currently in a session */
if (num == 0) {
return 0;
}
/* Do not allow start if already in progress */
if (btshell_tx_data.tx_num != 0) {
return -1;
}
/* XXX: for now, must have contiguous mbuf space */
if ((len + 4) > MYNEWT_VAL_MSYS_1_BLOCK_SIZE) {
return -2;
}
btshell_tx_data.tx_num = num;
btshell_tx_data.tx_num_requested = num;
btshell_tx_data.tx_rate = rate;
btshell_tx_data.tx_len = len;
btshell_tx_data.tx_conn_handle = conn_handle;
ble_hs_lock();
btshell_tx_data.conn = ble_hs_conn_find(conn_handle);
ble_hs_unlock();
if (!btshell_tx_data.conn) {
console_printf("Could not find ble_hs_conn for handle: %d\n",
conn_handle);
return -1;
}
os_callout_reset(&btshell_tx_timer, 0);
return 0;
}
void
btshell_tx_stop(void)
{
os_callout_stop(&btshell_tx_timer);
btshell_tx_data.tx_num = 0;
}
int
btshell_rssi(uint16_t conn_handle, int8_t *out_rssi)
{
int rc;
rc = ble_gap_conn_rssi(conn_handle, out_rssi);
if (rc != 0) {
return rc;
}
return 0;
}
static void
btshell_on_reset(int reason)
{
console_printf("Error: Resetting state; reason=%d\n", reason);
}
static void
btshell_on_sync(void)
{
/* Make sure we have proper identity address set (public preferred) */
if (ble_hs_util_ensure_addr(0) != 0) {
console_printf("Failed to set identity address\n");
}
ble_hs_id_infer_auto(0, &default_own_addr_type);
#if MYNEWT_VAL(BLE_SM_SC)
int rc;
rc = ble_sm_sc_oob_generate_data(&oob_data_local);
if (rc) {
console_printf("Error: generating oob data; reason=%d\n", rc);
return;
}
#endif
console_printf("Host and controller synced\n");
}
#if MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM) != 0
static int
btshell_l2cap_coc_add(uint16_t conn_handle, struct ble_l2cap_chan *chan)
{
struct btshell_conn *conn;
struct btshell_l2cap_coc *coc;
struct btshell_l2cap_coc *prev, *cur;
conn = btshell_conn_find(conn_handle);
assert(conn != NULL);
coc = os_memblock_get(&btshell_coc_conn_pool);
if (!coc) {
return ENOMEM;
}
coc->chan = chan;
prev = NULL;
SLIST_FOREACH(cur, &conn->coc_list, next) {
prev = cur;
}
if (prev == NULL) {
SLIST_INSERT_HEAD(&conn->coc_list, coc, next);
} else {
SLIST_INSERT_AFTER(prev, coc, next);
}
return 0;
}
static void
btshell_l2cap_coc_remove(uint16_t conn_handle, struct ble_l2cap_chan *chan)
{
struct btshell_conn *conn;
struct btshell_l2cap_coc *coc;
struct btshell_l2cap_coc *cur;
conn = btshell_conn_find(conn_handle);
assert(conn != NULL);
coc = NULL;
SLIST_FOREACH(cur, &conn->coc_list, next) {
if (cur->chan == chan) {
coc = cur;
break;
}
}
if (!coc) {
return;
}
SLIST_REMOVE(&conn->coc_list, coc, btshell_l2cap_coc, next);
os_memblock_put(&btshell_coc_conn_pool, coc);
}
static void
btshell_l2cap_coc_recv(struct ble_l2cap_chan *chan, struct os_mbuf *sdu)
{
console_printf("LE CoC SDU received, chan: 0x%08lx, data len %d\n",
(uint32_t) chan, OS_MBUF_PKTLEN(sdu));
os_mbuf_free_chain(sdu);
sdu = os_mbuf_get_pkthdr(&sdu_os_mbuf_pool, 0);
assert(sdu != NULL);
if (ble_l2cap_recv_ready(chan, sdu) != 0) {
assert(0);
}
}
static int
btshell_l2cap_coc_accept(uint16_t conn_handle, uint16_t peer_mtu,
struct ble_l2cap_chan *chan)
{
struct os_mbuf *sdu_rx;
int rc;
console_printf("LE CoC accepting, chan: 0x%08lx, peer_mtu %d\n",
(uint32_t) chan, peer_mtu);
for (int i = 0; i < MYNEWT_VAL(BLE_L2CAP_COC_SDU_BUFF_COUNT); i++) {
sdu_rx = os_mbuf_get_pkthdr(&sdu_os_mbuf_pool, 0);
if (!sdu_rx) {
return BLE_HS_ENOMEM;
}
rc = ble_l2cap_recv_ready(chan, sdu_rx);
assert(rc == 0);
}
return rc;
}
static void
btshell_l2cap_coc_unstalled(uint16_t conn_handle, struct ble_l2cap_chan *chan)
{
struct btshell_conn *conn;
struct btshell_l2cap_coc *coc;
struct btshell_l2cap_coc *cur;
conn = btshell_conn_find(conn_handle);
assert(conn != NULL);
coc = NULL;
SLIST_FOREACH(cur, &conn->coc_list, next) {
if (cur->chan == chan) {
coc = cur;
break;
}
}
if (!coc) {
return;
}
coc->stalled = false;
}
static int
btshell_l2cap_event(struct ble_l2cap_event *event, void *arg)
{
int accept_response;
struct ble_l2cap_chan_info chan_info;
switch(event->type) {
case BLE_L2CAP_EVENT_COC_CONNECTED:
if (event->connect.status) {
console_printf("LE COC error: %d\n", event->connect.status);
return 0;
}
if (ble_l2cap_get_chan_info(event->connect.chan, &chan_info)) {
assert(0);
}
console_printf("LE COC connected, conn: %d, chan: %p, psm: 0x%02x, scid: 0x%04x, "
"dcid: 0x%04x, our_mps: %d, our_mtu: %d, peer_mps: %d, peer_mtu: %d\n",
event->connect.conn_handle, event->connect.chan,
chan_info.psm, chan_info.scid, chan_info.dcid,
chan_info.our_l2cap_mtu, chan_info.our_coc_mtu, chan_info.peer_l2cap_mtu, chan_info.peer_coc_mtu);
btshell_l2cap_coc_add(event->connect.conn_handle,
event->connect.chan);
return 0;
case BLE_L2CAP_EVENT_COC_DISCONNECTED:
console_printf("LE CoC disconnected, chan: %p\n",
event->disconnect.chan);
btshell_l2cap_coc_remove(event->disconnect.conn_handle,
event->disconnect.chan);
return 0;
case BLE_L2CAP_EVENT_COC_ACCEPT:
accept_response = PTR_TO_INT(arg);
if (accept_response) {
return accept_response;
}
return btshell_l2cap_coc_accept(event->accept.conn_handle,
event->accept.peer_sdu_size,
event->accept.chan);
case BLE_L2CAP_EVENT_COC_DATA_RECEIVED:
btshell_l2cap_coc_recv(event->receive.chan, event->receive.sdu_rx);
return 0;
case BLE_L2CAP_EVENT_COC_RECONFIG_COMPLETED:
if (ble_l2cap_get_chan_info(event->reconfigured.chan, &chan_info)) {
assert(0);
}
console_printf("LE CoC reconfigure completed status 0x%02x," \
"chan: %p\n",
event->reconfigured.status,
event->reconfigured.chan);
if (event->reconfigured.status == 0) {
console_printf("\t our_mps: %d our_mtu %d\n", chan_info.our_l2cap_mtu, chan_info.our_coc_mtu);
}
return 0;
case BLE_L2CAP_EVENT_COC_PEER_RECONFIGURED:
if (ble_l2cap_get_chan_info(event->reconfigured.chan, &chan_info)) {
assert(0);
}
console_printf("LE CoC peer reconfigured status 0x%02x," \
"chan: %p\n",
event->reconfigured.status,
event->reconfigured.chan);
if (event->reconfigured.status == 0) {
console_printf("\t peer_mps: %d peer_mtu %d\n", chan_info.peer_l2cap_mtu, chan_info.peer_coc_mtu);
}
return 0;
case BLE_L2CAP_EVENT_COC_TX_UNSTALLED:
console_printf("L2CAP CoC channel %p unstalled, last sdu sent with err=0x%02x\n",
event->tx_unstalled.chan, event->tx_unstalled.status);
btshell_l2cap_coc_unstalled(event->tx_unstalled.conn_handle, event->tx_unstalled.chan);
return 0;
default:
return 0;
}
}
#endif
int
btshell_l2cap_create_srv(uint16_t psm, uint16_t mtu, int accept_response)
{
#if MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM) == 0
console_printf("BLE L2CAP LE COC not supported.");
console_printf(" Configure nimble host to enable it\n");
return 0;
#else
if (mtu == 0 || mtu > BTSHELL_COC_MTU) {
mtu = BTSHELL_COC_MTU;
}
return ble_l2cap_create_server(psm, mtu, btshell_l2cap_event,
INT_TO_PTR(accept_response));
#endif
}
int
btshell_l2cap_connect(uint16_t conn_handle, uint16_t psm, uint16_t mtu, uint8_t num)
{
#if MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM) == 0
console_printf("BLE L2CAP LE COC not supported.");
console_printf(" Configure nimble host to enable it\n");
return 0;
#else
struct os_mbuf *sdu_rx[num];
int i;
if (mtu == 0 || mtu > BTSHELL_COC_MTU) {
mtu = BTSHELL_COC_MTU;
}
console_printf("L2CAP CoC MTU: %d, max available %d\n", mtu, BTSHELL_COC_MTU);
for (i = 0; i < num; i++) {
sdu_rx[i] = os_mbuf_get_pkthdr(&sdu_os_mbuf_pool, 0);
assert(sdu_rx != NULL);
}
if (num == 1) {
return ble_l2cap_connect(conn_handle, psm, mtu, sdu_rx[0],
btshell_l2cap_event, NULL);
}
return ble_l2cap_enhanced_connect(conn_handle, psm, mtu,
num, sdu_rx,btshell_l2cap_event, NULL);
#endif
}
int
btshell_l2cap_disconnect(uint16_t conn_handle, uint16_t idx)
{
#if MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM) == 0
console_printf("BLE L2CAP LE COC not supported.");
console_printf(" Configure nimble host to enable it\n");
return 0;
#else
struct btshell_conn *conn;
struct btshell_l2cap_coc *coc;
int i;
int rc = 0;
conn = btshell_conn_find(conn_handle);
assert(conn != NULL);
i = 0;
SLIST_FOREACH(coc, &conn->coc_list, next) {
if (i == idx) {
break;
}
i++;
}
assert(coc != NULL);
rc = ble_l2cap_disconnect(coc->chan);
if (rc) {
console_printf("Could not disconnect channel rc=%d\n", rc);
}
return rc;
#endif
}
int
btshell_l2cap_reconfig(uint16_t conn_handle, uint16_t mtu,
uint8_t num, uint8_t idxs[])
{
struct btshell_conn *conn;
struct btshell_l2cap_coc *coc;
struct ble_l2cap_chan * chans[5] = {0};
int i, j;
int cnt;
conn = btshell_conn_find(conn_handle);
if (conn == NULL) {
console_printf("conn=%d does not exist\n", conn_handle);
return 0;
}
i = 0;
j = 0;
cnt = 0;
SLIST_FOREACH(coc, &conn->coc_list, next) {
for (i = 0; i < num; i++) {
if (idxs[i] == j) {
chans[cnt] = coc->chan;
cnt++;
break;
}
}
j++;
}
if (cnt != num) {
console_printf("Missing coc? (%d!=%d)\n", num, cnt);
return BLE_HS_EINVAL;
}
return ble_l2cap_reconfig(chans, cnt, mtu);
}
int
btshell_l2cap_send(uint16_t conn_handle, uint16_t idx, uint16_t bytes)
{
#if MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM) == 0
console_printf("BLE L2CAP LE COC not supported.");
console_printf(" Configure nimble host to enable it\n");
return 0;
#else
struct btshell_conn *conn;
struct btshell_l2cap_coc *coc;
struct os_mbuf *sdu_tx;
uint8_t b[] = {0x00, 0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88, 0x99};
int i;
int rc;
console_printf("conn=%d, idx=%d, bytes=%d\n", conn_handle, idx, bytes);
conn = btshell_conn_find(conn_handle);
if (conn == NULL) {
console_printf("conn=%d does not exist\n", conn_handle);
return 0;
}
i = 0;
SLIST_FOREACH(coc, &conn->coc_list, next) {
if (i == idx) {
break;
}
i++;
}
if (coc == NULL) {
console_printf("Are you sure your channel exist?\n");
return 0;
}
if (coc->stalled) {
console_printf("Channel is stalled, wait ...\n");
return 0;
}
sdu_tx = os_mbuf_get_pkthdr(&sdu_os_mbuf_pool, 0);
if (sdu_tx == NULL) {
console_printf("No memory in the test sdu pool\n");
return 0;
}
/* For the testing purpose we fill up buffer with known data, easy
* to validate on other side. In this loop we add as many full chunks as we
* can
*/
for (i = 0; i < bytes / sizeof(b); i++) {
rc = os_mbuf_append(sdu_tx, b, sizeof(b));
if (rc) {
console_printf("Cannot append data %i !\n", i);
os_mbuf_free_chain(sdu_tx);
return rc;
}
}
/* Here we add the rest < sizeof(b) */
rc = os_mbuf_append(sdu_tx, b, bytes - (sizeof(b) * i));
if (rc) {
console_printf("Cannot append data %i !\n", i);
os_mbuf_free_chain(sdu_tx);
return rc;
}
rc = ble_l2cap_send(coc->chan, sdu_tx);
if (rc) {
if (rc == BLE_HS_ESTALLED) {
console_printf("CoC module is stalled with data. Wait for unstalled \n");
coc->stalled = true;
} else {
console_printf("Could not send data rc=%d\n", rc);
}
os_mbuf_free_chain(sdu_tx);
}
return rc;
#endif
}
static void
btshell_init_ext_adv_restart(void)
{
#if MYNEWT_VAL(BLE_EXT_ADV)
int i;
for (i = 0; i < BLE_ADV_INSTANCES; ++i) {
ext_adv_restart[i].conn_handle = BLE_HS_CONN_HANDLE_NONE;
}
#endif
}
uint8_t
btshell_get_default_own_addr_type(void)
{
return default_own_addr_type;
}
/**
* main
*
* The main task for the project. This function initializes the packages,
* then starts serving events from default event queue.
*
* @return int NOTE: this function should never return!
*/
static int
main_fn(int argc, char **argv)
{
int rc;
#ifdef ARCH_sim
mcu_sim_parse_args(argc, argv);
#endif
/* Initialize OS */
sysinit();
/* Initialize some application specific memory pools. */
rc = os_mempool_init(&btshell_svc_pool, BTSHELL_MAX_SVCS,
sizeof (struct btshell_svc), btshell_svc_mem,
"btshell_svc_pool");
assert(rc == 0);
rc = os_mempool_init(&btshell_chr_pool, BTSHELL_MAX_CHRS,
sizeof (struct btshell_chr), btshell_chr_mem,
"btshell_chr_pool");
assert(rc == 0);
rc = os_mempool_init(&btshell_dsc_pool, BTSHELL_MAX_DSCS,
sizeof (struct btshell_dsc), btshell_dsc_mem,
"btshell_dsc_pool");
assert(rc == 0);
#if MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM) != 0
/* For testing we want to support all the available channels */
rc = os_mempool_init(&sdu_coc_mbuf_mempool, BTSHELL_COC_BUF_COUNT,
BTSHELL_COC_MTU, btshell_sdu_coc_mem,
"btshell_coc_sdu_pool");
assert(rc == 0);
rc = os_mbuf_pool_init(&sdu_os_mbuf_pool, &sdu_coc_mbuf_mempool,
BTSHELL_COC_MTU, BTSHELL_COC_BUF_COUNT);
assert(rc == 0);
rc = os_mempool_init(&btshell_coc_conn_pool,
MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM),
sizeof (struct btshell_l2cap_coc), btshell_coc_conn_mem,
"btshell_coc_conn_pool");
assert(rc == 0);
#endif
/* Initialize the NimBLE host configuration. */
ble_hs_cfg.reset_cb = btshell_on_reset;
ble_hs_cfg.sync_cb = btshell_on_sync;
ble_hs_cfg.gatts_register_cb = gatt_svr_register_cb;
ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
rc = gatt_svr_init();
assert(rc == 0);
cmd_init();
/* Set the default device name. */
rc = ble_svc_gap_device_name_set("nimble-btshell");
assert(rc == 0);
/* Create a callout (timer). This callout is used by the "tx" btshell
* command to repeatedly send packets of sequential data bytes.
*/
os_callout_init(&btshell_tx_timer, os_eventq_dflt_get(),
btshell_tx_timer_cb, NULL);
btshell_init_ext_adv_restart();
while (1) {
os_eventq_run(os_eventq_dflt_get());
}
/* os start should never return. If it does, this should be an error */
assert(0);
return 0;
}
int
main(int argc, char **argv)
{
#if BABBLESIM
extern void bsim_init(int argc, char** argv, void *main_fn);
bsim_init(argc, argv, main_fn);
#else
main_fn(argc, argv);
#endif
return 0;
}
|
8d7ba6a4f80195f24424416a5a1a2e174419cced
|
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
|
/net/xl2tpd/patches/patch-control.c
|
9f559ebd11da79cb95b027f0319fc503988a928a
|
[] |
no_license
|
NetBSD/pkgsrc
|
a0732c023519650ef821ab89c23ab6ab59e25bdb
|
d042034ec4896cc5b47ed6f2e5b8802d9bc5c556
|
refs/heads/trunk
| 2023-09-01T07:40:12.138283
| 2023-09-01T05:25:19
| 2023-09-01T05:25:19
| 88,439,572
| 321
| 138
| null | 2023-07-12T22:34:14
| 2017-04-16T20:04:15
| null |
UTF-8
|
C
| false
| false
| 645
|
c
|
patch-control.c
|
$NetBSD: patch-control.c,v 1.3 2017/10/13 17:24:05 christos Exp $
Remove static from inline; each inlined copy might have its own buffer and
this is not want you want if you define it static. In this case it does not
matter, since it is only 4K and we don't return it, so don't try to play
around with saving stack space for no good reason.
--- control.c.orig 2017-08-02 13:46:06.000000000 -0400
+++ control.c 2017-10-13 12:46:33.920249976 -0400
@@ -1600,7 +1600,7 @@
int x;
unsigned char e;
int err;
- static unsigned char wbuf[MAX_RECV_SIZE];
+ unsigned char wbuf[MAX_RECV_SIZE];
int pos = 0;
if (c->fd < 0)
|
7571a38a544e6848383e43fb36c8eb0ee23c6ebf
|
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
|
/sysutils/diskscrub/patches/patch-src_util.h
|
f583251bd9754f8f29e01632aab7f289a7b246ff
|
[] |
no_license
|
NetBSD/pkgsrc
|
a0732c023519650ef821ab89c23ab6ab59e25bdb
|
d042034ec4896cc5b47ed6f2e5b8802d9bc5c556
|
refs/heads/trunk
| 2023-09-01T07:40:12.138283
| 2023-09-01T05:25:19
| 2023-09-01T05:25:19
| 88,439,572
| 321
| 138
| null | 2023-07-12T22:34:14
| 2017-04-16T20:04:15
| null |
UTF-8
|
C
| false
| false
| 312
|
h
|
patch-src_util.h
|
$NetBSD: patch-src_util.h,v 1.1 2015/03/05 21:29:20 sevan Exp $
--- src/util.h.orig 2015-03-05 19:13:14.116234563 +0000
+++ src/util.h
@@ -30,6 +30,10 @@
typedef enum { false, true } bool;
#endif
+#ifdef HAVE_SYS_MMAN_H
+#include <sys/mman.h>
+#endif
+
typedef enum {
FILE_NOEXIST,
FILE_REGULAR,
|
682fa475c446d5fd25740045fdd21501f80acef0
|
7be8e3636bf08ebdc6662879dc5afec548705537
|
/ios/Pods/Flipper-PeerTalk/peertalk/PTPrivate.h
|
7878ef69cdcf5c6fdc1d908a70c8a3c89dfd1af8
|
[
"MIT"
] |
permissive
|
rdhox/react-native-smooth-picker
|
3c7384f1fed0e37f076361cce96071d01b70e209
|
ae9316c49512f7ed9824c5a3ad50cdf5e80fffa9
|
refs/heads/master
| 2023-01-08T16:59:40.709147
| 2021-07-03T14:13:21
| 2021-07-03T14:13:21
| 160,224,312
| 230
| 31
|
MIT
| 2023-01-06T01:46:04
| 2018-12-03T16:54:10
|
TypeScript
|
UTF-8
|
C
| false
| false
| 597
|
h
|
PTPrivate.h
|
#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && (!defined(__IPHONE_6_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_6_0)) || \
(defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (!defined(__MAC_10_8) || __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8))
#define PT_DISPATCH_RETAIN_RELEASE 1
#else
#define PT_DISPATCH_RETAIN_RELEASE 0
#endif
#if PT_DISPATCH_RETAIN_RELEASE
#define PT_PRECISE_LIFETIME
#define PT_PRECISE_LIFETIME_UNUSED
#else
#define PT_PRECISE_LIFETIME __attribute__((objc_precise_lifetime))
#define PT_PRECISE_LIFETIME_UNUSED __attribute__((objc_precise_lifetime, unused))
#endif
|
804725d35997dfc224a8b2370b8feeb3fcaf7722
|
676acab8ff535019faff7da3afb8eecc3fa127f5
|
/src/module/sensor/sensor_hub.h
|
b34e9c0d4705808658d0fb68a7d8789fca88f19a
|
[
"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
| 3,837
|
h
|
sensor_hub.h
|
/******************************************************************************
* Copyright 2020-2021 The Firmament 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.
*****************************************************************************/
#ifndef SENSOR_HUB_H__
#define SENSOR_HUB_H__
#include <firmament.h>
#ifdef __cplusplus
extern "C" {
#endif
#define RAW_TEMPERATURE_POS 0
#define RAW_PRESSURE_POS 1
#define COLLECT_DATA_POS 2
#define GYR_RAW_POS 0
#define GYR_SCALE_POS 1
#define ACC_RAW_POS 2
#define ACC_SCALE_POS 3
#define MAG_RAW_POS 4
#define MAG_SCLAE_POS 5
//common cmd
#define SENSOR_GET_DEVICE_ID 0x00
//acc,mag cmd
#define SENSOR_SET_ACC_RANGE 0x01
#define SENSOR_SET_ACC_SAMPLERATE 0x02
#define SENSOR_SET_MAG_RANGE 0x03
#define SENSOR_SET_MAG_SAMPLERATE 0x04
//gyr cmd
#define SENSOR_SET_GYR_RANGE 0x20
//baro cmd
#define SENSOR_CONVERSION 0x30
#define SENSOR_IS_CONV_FIN 0x31
struct sensor_imu {
rt_device_t gyr_dev;
rt_device_t acc_dev;
float gyr_rotation[3][3];
float gyr_offset[3];
float acc_rotation[3][3];
float acc_offset[3];
};
typedef struct sensor_imu* sensor_imu_t;
struct sensor_mag {
rt_device_t dev;
float rotation[3][3];
float offset[3];
};
typedef struct sensor_mag* sensor_mag_t;
struct sensor_baro {
rt_device_t dev;
};
typedef struct sensor_baro* sensor_baro_t;
struct sensor_gps {
rt_device_t dev;
};
typedef struct sensor_gps* sensor_gps_t;
struct sensor_airspeed {
rt_device_t dev;
};
typedef struct sensor_airspeed* sensor_airspeed_t;
typedef struct {
uint32_t timestamp_ms;
float gyr_B_radDs[3];
float acc_B_mDs2[3];
} imu_data_t;
typedef struct {
uint32_t timestamp_ms;
float mag_B_gauss[3];
} mag_data_t;
typedef struct {
uint32_t timestamp_ms;
float temperature_deg;
float pressure_pa;
float altitude_m;
} baro_data_t;
typedef struct {
uint32_t timestamp_ms;
int32_t lon;
int32_t lat;
int32_t height;
float hAcc;
float vAcc;
float velN;
float velE;
float velD;
float vel;
float cog;
float sAcc;
uint8_t fixType;
uint8_t numSV;
uint16_t reserved;
} gps_data_t;
typedef struct {
uint32_t timestamp_ms;
float vx_mPs;
float vy_mPs;
uint8_t quality;
} optflow_data_t;
typedef struct {
uint32_t timestamp_ms;
float distance_m; // negative value indicate invalid
} rf_data_t;
typedef struct {
uint32_t timestamp_ms;
float diff_pressure_pa;
float temperature_deg;
} airspeed_data_t;
void sensor_collect(void);
fmt_err_t advertise_sensor_imu(uint8_t id);
fmt_err_t advertise_sensor_mag(uint8_t id);
fmt_err_t advertise_sensor_baro(uint8_t id);
fmt_err_t advertise_sensor_airspeed(uint8_t id);
fmt_err_t advertise_sensor_gps(uint8_t id);
fmt_err_t advertise_sensor_optflow(uint8_t id);
fmt_err_t advertise_sensor_rangefinder(uint8_t id);
fmt_err_t register_sensor_imu(const char* gyr_dev_name, const char* acc_dev_name, uint8_t id);
fmt_err_t register_sensor_mag(const char* dev_name, uint8_t id);
fmt_err_t register_sensor_barometer(const char* dev_name);
fmt_err_t register_sensor_airspeed(const char* dev_name);
fmt_err_t register_sensor_gps(const char* dev_name);
#ifdef __cplusplus
}
#endif
#endif
|
36fb25ad043180160dd00e0b743b7fcd43df09da
|
bb7a80648bf830c2fb813cdb335032142cbee06d
|
/mod/svp/3516a/nnie/yolo.c
|
9b9413111322e5db0787b47165970e8f1b564c32
|
[] |
no_license
|
openhisilicon/HIVIEW
|
44574a29da60e3bb400c7ce97c722dfc9f2959e6
|
60bbfa5cb66cc82f0cdc0bba1242dbc9491b0f37
|
refs/heads/master
| 2023-09-01T01:42:19.069724
| 2023-08-31T09:57:39
| 2023-08-31T09:57:39
| 189,036,134
| 336
| 121
| null | 2023-01-07T14:10:22
| 2019-05-28T13:41:40
|
C
|
UTF-8
|
C
| false
| false
| 4,203
|
c
|
yolo.c
|
#include <stdlib.h>
#include<stdio.h>
#include<string.h>
#include <sys/timeb.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include "yolo_sample.h"
#include "sample_comm_ive.h"
#include "ivs_md.h"
#include "svp.h"
#include "cfg.h"
#include "polyiou.h"
extern void* svp_pub;
static pthread_t s_hMdThread = 0;
static HI_BOOL s_bStopSignal = HI_FALSE;
static void* pHand = NULL;
static void* yolo_task(void* p);
int yolo_start(char *home_path)
{
int VpssGrp = 0;
int VpssChn = 1;
char ModelPath[256];
sprintf(ModelPath, "%s/model/yolov5-voc.wk", home_path);
printf("ModelPath:[%s]\n", ModelPath);
if(yolo_init(VpssGrp, VpssChn, ModelPath) < 0)
{
printf("yolo_init err.\n");
return -1;
}
s_bStopSignal = HI_FALSE;
return pthread_create(&s_hMdThread, NULL, yolo_task, NULL);
}
int yolo_stop()
{
if(s_hMdThread)
{
s_bStopSignal = HI_TRUE;
pthread_join(s_hMdThread, NULL);
s_hMdThread = 0;
}
}
static pub_send(yolo_boxs_t *boxs)
{
int i;
char buf[sizeof(gsf_msg_t) + sizeof(gsf_svp_yolos_t)];
gsf_msg_t *msg = (gsf_msg_t*)buf;
memset(msg, 0, sizeof(*msg));
msg->id = GSF_EV_SVP_YOLO;
msg->ts = time(NULL)*1000;
msg->sid = 0;
msg->err = 0;
msg->size = sizeof(gsf_svp_yolos_t);
gsf_svp_yolos_t *yolos = (gsf_svp_yolos_t*)msg->data;
yolos->pts = 0;
yolos->w = boxs->w;
yolos->h = boxs->h;
yolos->cnt = 0;
for(i=0;i<boxs->size;i++)
{
if(yolos->cnt >= sizeof(yolos->box)/sizeof(yolos->box[0]))
{
break;
}
boxs->box[i].x = (boxs->box[i].x > 0.0)?boxs->box[i].x:0;
boxs->box[i].y = (boxs->box[i].y > 0.0)?boxs->box[i].y:0;
boxs->box[i].w = (boxs->box[i].w < yolos->w)?boxs->box[i].w:yolos->w;
boxs->box[i].h = (boxs->box[i].h < yolos->h)?boxs->box[i].h:yolos->h;
//only used polygons[0];
double iou = 0.1;
if(svp_parm.yolo.det_polygon.polygon_num && svp_parm.yolo.det_polygon.polygons[0].point_num)
{
int pn = svp_parm.yolo.det_polygon.polygons[0].point_num;
double P[10*2] = {0};
double Q[4*2] = {0};
for(int p = 0; p < pn; p++)
{
P[p*2+0] = svp_parm.yolo.det_polygon.polygons[0].points[p].x * yolos->w;
P[p*2+1] = svp_parm.yolo.det_polygon.polygons[0].points[p].y * yolos->h;
}
Q[0] = boxs->box[i].x;
Q[1] = boxs->box[i].y;
Q[2] = (boxs->box[i].x + boxs->box[i].w);
Q[3] = boxs->box[i].y;
Q[4] = (boxs->box[i].x + boxs->box[i].w);
Q[5] = (boxs->box[i].y + boxs->box[i].h);
Q[6] = boxs->box[i].x;
Q[7] = (boxs->box[i].y + boxs->box[i].h);
#if 0
printf("P(%d)[%.4f %.4f, %.4f %.4f, %.4f %.4f, %.4f %.4f, %.4f %.4f, %.4f %.4f, %.4f %.4f, %.4f %.4f]\n"
, pn, P[0],P[1], P[2],P[3], P[4],P[5], P[6],P[7], P[8],P[9], P[10],P[11], P[12],P[13], P[14],P[15]);
printf("Q(%d)[ %.4f %.4f, %.4f %.4f, %.4f %.4f, %.4f %.4f]\n"
, 4, Q[0],Q[1], Q[2],Q[3], Q[4],Q[5], Q[6],Q[7]);
#endif
iou = poly_iou(P, pn*2, Q, 4*2);
if(iou < 0.001)
continue;
}
yolos->box[yolos->cnt].score = boxs->box[i].score;
yolos->box[yolos->cnt].rect[0] = boxs->box[i].x;
yolos->box[yolos->cnt].rect[1] = boxs->box[i].y;
yolos->box[yolos->cnt].rect[2] = boxs->box[i].w;
yolos->box[yolos->cnt].rect[3] = boxs->box[i].h;
strncpy(yolos->box[yolos->cnt].label, boxs->box[i].label, sizeof(yolos->box[yolos->cnt].label)-1);
#if 0
printf("iou: %.4f, w:%d,h:%d, rect[%d,%d,%d,%d], label[%s], score:%f\n"
, iou, yolos->w, yolos->h
, yolos->box[yolos->cnt].rect[0]
, yolos->box[yolos->cnt].rect[1]
, yolos->box[yolos->cnt].rect[2]
, yolos->box[yolos->cnt].rect[3]
, yolos->box[yolos->cnt].label, yolos->box[i].score);
#endif
yolos->cnt++;
}
nm_pub_send(svp_pub, (char*)msg, sizeof(*msg)+msg->size);
}
static void* yolo_task(void* p)
{
while (HI_FALSE == s_bStopSignal)
{
usleep(33/3*1000);
yolo_boxs_t boxs = {0};
int ret = yolo_detect(&boxs);
if(ret == 0)
pub_send(&boxs);
}
yolo_boxs_t boxs = {0};
pub_send(&boxs);
yolo_deinit();
return NULL;
}
|
d503916d8cd218293314fa2e6593cb8c51a23f77
|
cf60f9591fef521d3092f81785de7942d0ca568e
|
/PubNub/include/PNSetChannelMetadataStatus.h
|
16a5dee2213595c77d4d53ba34d045955bde897a
|
[
"MIT"
] |
permissive
|
pubnub/objective-c
|
a49e2e5c7898eb893b601ae31a098361fb8b4406
|
eef06ae76fd45931ea09900e3b3ce50133870eca
|
refs/heads/master
| 2023-04-07T08:28:47.174178
| 2023-01-05T11:15:57
| 2023-01-05T11:15:57
| 8,490,984
| 137
| 145
|
NOASSERTION
| 2023-03-30T08:47:36
| 2013-03-01T00:10:41
|
Objective-C
|
UTF-8
|
C
| false
| false
| 52
|
h
|
PNSetChannelMetadataStatus.h
|
../Data/Service Objects/PNSetChannelMetadataStatus.h
|
7aecda82a0f64085b537924ae098183c2e68d6e1
|
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
|
/security/prelude-pflogger/files/run-prelude-pflogger.c
|
e065663f4b8f4549bc0a6104677d78f965753691
|
[] |
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
| 3,802
|
c
|
run-prelude-pflogger.c
|
#define PRELUDE_PFLOGGER_USER "@PRELUDE_USER@"
#define PRELUDE_PFLOGGER_PATH "@PREFIX@/bin/prelude-pflogger"
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <pwd.h>
#include <syslog.h>
#define MAX_ARGS 40
#ifndef TRUE
#define TRUE 1
#endif /* TRUE */
#ifndef FALSE
#define FALSE 0
#endif /* FALSE */
void error_sys(char *str)
{
/* Output error message to syslog */
char msg[1024];
snprintf(msg, sizeof(msg), "run-prelude-pflogger : %s : %s", str, strerror(errno));
syslog(LOG_ALERT, msg);
}
int obtainUIDandGID(const char *name, uid_t *pw_uid, gid_t *pw_gid)
{
/* Obtain UID and GID from passwd entry identified by name */
struct passwd *pw_entry;
char msg[100];
if ((pw_entry = getpwnam(name)) == NULL)
{
snprintf(msg, sizeof(msg), "failed to get password entry for %s", name);
error_sys(msg);
return FALSE;
}
else
{
*pw_uid = pw_entry->pw_uid;
*pw_gid = pw_entry->pw_gid;
return TRUE;
}
}
int main (int argc, char **argv )
{
pid_t pid;
uid_t UID;
gid_t GID;
pid_t pidwait;
int waitstat;
int s;
int max_fd;
/* Sanity check */
if (argc > MAX_ARGS)
{
error_sys("arg buffer too small");
exit(-1);
}
if (geteuid() != 0)
{
error_sys("must be called by root");
exit(-1);
}
/* fork child that will become prelude-pflogger */
if ((pid = fork()) < 0)
error_sys("fork error");
else
{
if (pid == 0)
{
/* We're the child */
char *args[MAX_ARGS];
unsigned int i;
/* Become session leader */
setsid();
/* Change working directory to root directory.
The current working directory could be a mounted
filesystem; if the daemon stays on a mounted
filesystem it could prevent the filesystem from
being umounted. */
chdir("/");
/* Clear out file creation mask */
umask(0);
/* Close unneeded file descriptors */
max_fd = (int) sysconf(_SC_OPEN_MAX);
if (max_fd == -1)
max_fd = getdtablesize();
for (s = 3; s < max_fd; s++)
(void) close(s);
if (!obtainUIDandGID(PRELUDE_PFLOGGER_USER, &UID, &GID))
exit(-1);
/* Drop privileges immediately */
if (setgid(GID) < 0)
{
/* It is VERY important to check return
value and not continue if setgid fails
*/
error_sys ("setgid failed");
exit (-1);
}
if (setuid(UID) < 0)
{
/* It is VERY important to check return
value and not continue if setuid fails
*/
error_sys ("setuid failed");
exit (-1);
}
/* Build calling argv */
args[0] = PRELUDE_PFLOGGER_PATH;
for (i=1;i<argc;i++)
{
args[i] = argv[i];
}
args[i++] = NULL;
/* Finally transform self into prelude-pflogger */
if (execvp(PRELUDE_PFLOGGER_PATH, args) < 0)
error_sys("execve error");
else
; /* avoid if-then ambiguity */
}
else
{
/* We're the parent
Terminate
*/
exit(0);
}
}
}
|
16e624f1332455402fc6cb8311cab373c9a253d7
|
6840356bb8428865c1c64fa8ca9b42c0aca348a7
|
/Core/SoarKernel/src/soar_representation/production_reorder.h
|
facb4c7e8b63ac687adea514fcf60c341ebe5ab0
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
SoarGroup/Soar
|
a5c7281e0673665a4b7eddd39ae4e5eb2a507aef
|
ef42bb24f7b58f9d244c83f5a2f2153c3ee17b77
|
refs/heads/development
| 2023-09-01T08:47:44.349033
| 2023-08-31T22:54:57
| 2023-08-31T22:54:57
| 21,206,914
| 289
| 86
|
NOASSERTION
| 2023-09-14T05:14:06
| 2014-06-25T14:50:12
|
C++
|
UTF-8
|
C
| false
| false
| 1,432
|
h
|
production_reorder.h
|
/*************************************************************************
* PLEASE SEE THE FILE "license.txt" (INCLUDED WITH THIS SOFTWARE PACKAGE)
* FOR LICENSE AND COPYRIGHT INFORMATION.
*************************************************************************/
/* =======================================================================
reorder.h
Need to add comments here
======================================================================= */
#ifndef REORDER_H
#define REORDER_H
#include "kernel.h"
#include "stl_typedefs.h"
typedef struct saved_test_struct
{
struct saved_test_struct* next;
Symbol* var;
uint64_t inst_identity;
Identity* identity;
test the_test;
} saved_test;
extern bool reorder_action_list(agent* thisAgent, action** action_list, tc_number lhs_tc, matched_symbol_list* ungrounded_syms, bool add_ungrounded = false);
extern bool reorder_lhs(agent* thisAgent, condition** lhs_top, bool reorder_nccs, matched_symbol_list* ungrounded_syms = NULL, bool add_ungrounded = false);
extern void init_reorderer(agent* thisAgent);
/* this prototype moved here from osupport.cpp -ajc (5/3/02) */
extern cons* collect_root_variables(agent* thisAgent, condition* cond_list, tc_number tc, matched_symbol_list* ungrounded_syms = NULL, bool add_ungrounded = false);
#endif
|
ed75e0dcc0393a26e8e6757ba370c2654320bdad
|
fa1ad2e2ac7e376fc7cb3b3a6e1bb88eed3e80be
|
/govern/data-security/krb-1.2.1/src/lib/crypto/krb/crypto_length.c
|
57b21e742cce08cf119a88d347e31cafbcd319f3
|
[
"BSD-4-Clause",
"LicenseRef-scancode-generic-export-compliance",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-mit-old-style",
"BSD-4-Clause-UC",
"LicenseRef-scancode-rsa-1990",
"BSD-3-Clause",
"MIT-CMU",
"LicenseRef-scancode-mit-no-advert-export-control",
"CC-BY-SA-3.0",
"LicenseRef-scancode-mit-modification-obligations",
"LicenseRef-scancode-proprietary-license",
"GPL-2.0-or-later",
"LicenseRef-scancode-michigan-disclaimer",
"ISC",
"LicenseRef-scancode-nrl-permission",
"FreeBSD-DOC",
"LicenseRef-scancode-rsa-md4",
"RSA-MD",
"OLDAP-2.8",
"FSFULLRWD",
"BSD-2-Clause",
"LicenseRef-scancode-brian-gladman",
"MIT",
"Apache-2.0"
] |
permissive
|
alldatacenter/alldata
|
7bc7713c9f1d56ad6b8e59ea03206d1073b7e047
|
8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6
|
refs/heads/master
| 2023-08-05T07:32:25.442740
| 2023-08-03T13:17:24
| 2023-08-03T13:17:24
| 213,321,771
| 774
| 250
|
Apache-2.0
| 2023-09-06T17:35:32
| 2019-10-07T07:36:18
| null |
UTF-8
|
C
| false
| false
| 4,030
|
c
|
crypto_length.c
|
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* lib/crypto/krb/crypto_length.c */
/*
* Copyright 2008 by the Massachusetts Institute of Technology.
* All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*/
#include "crypto_int.h"
krb5_error_code KRB5_CALLCONV
krb5_c_crypto_length(krb5_context context, krb5_enctype enctype,
krb5_cryptotype type, unsigned int *size)
{
const struct krb5_keytypes *ktp;
ktp = find_enctype(enctype);
if (ktp == NULL)
return KRB5_BAD_ENCTYPE;
switch (type) {
case KRB5_CRYPTO_TYPE_EMPTY:
case KRB5_CRYPTO_TYPE_SIGN_ONLY:
*size = 0;
break;
case KRB5_CRYPTO_TYPE_DATA:
*size = (unsigned int)~0; /* match Heimdal */
break;
case KRB5_CRYPTO_TYPE_HEADER:
case KRB5_CRYPTO_TYPE_PADDING:
case KRB5_CRYPTO_TYPE_TRAILER:
case KRB5_CRYPTO_TYPE_CHECKSUM:
*size = ktp->crypto_length(ktp, type);
break;
default:
return EINVAL;
}
return 0;
}
krb5_error_code KRB5_CALLCONV
krb5_c_padding_length(krb5_context context, krb5_enctype enctype,
size_t data_length, unsigned int *pad_length)
{
const struct krb5_keytypes *ktp;
ktp = find_enctype(enctype);
if (ktp == NULL)
return KRB5_BAD_ENCTYPE;
*pad_length = krb5int_c_padding_length(ktp, data_length);
return 0;
}
krb5_error_code KRB5_CALLCONV
krb5_c_crypto_length_iov(krb5_context context, krb5_enctype enctype,
krb5_crypto_iov *data, size_t num_data)
{
size_t i;
const struct krb5_keytypes *ktp;
unsigned int data_length = 0, pad_length;
krb5_crypto_iov *padding = NULL;
/*
* XXX need to rejig internal interface so we can accurately
* report variable header lengths.
*/
ktp = find_enctype(enctype);
if (ktp == NULL)
return KRB5_BAD_ENCTYPE;
for (i = 0; i < num_data; i++) {
krb5_crypto_iov *iov = &data[i];
switch (iov->flags) {
case KRB5_CRYPTO_TYPE_DATA:
data_length += iov->data.length;
break;
case KRB5_CRYPTO_TYPE_PADDING:
if (padding != NULL)
return EINVAL;
padding = iov;
break;
case KRB5_CRYPTO_TYPE_HEADER:
case KRB5_CRYPTO_TYPE_TRAILER:
case KRB5_CRYPTO_TYPE_CHECKSUM:
iov->data.length = ktp->crypto_length(ktp, iov->flags);
break;
case KRB5_CRYPTO_TYPE_EMPTY:
case KRB5_CRYPTO_TYPE_SIGN_ONLY:
default:
break;
}
}
pad_length = krb5int_c_padding_length(ktp, data_length);
if (pad_length != 0 && padding == NULL)
return EINVAL;
if (padding != NULL)
padding->data.length = pad_length;
return 0;
}
|
e98bc7e0124e2bfc59972b42b82816c3feb3e02a
|
03666e5f961946fc1a0ac67781ac1425562ef0d7
|
/src/plots/ParallelCoordinates/ParallelCoordinatesCommonPluginInfo.C
|
a956014c59fc83f7711d5439b7684e2b5e67b8ea
|
[
"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
| 2,464
|
c
|
ParallelCoordinatesCommonPluginInfo.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.
// ****************************************************************************
// File: ParallelCoordinatesCommonPluginInfo.C
// ****************************************************************************
#include <ParallelCoordinatesPluginInfo.h>
#include <ParallelCoordinatesAttributes.h>
// ****************************************************************************
// Method: ParallelCoordinatesCommonPluginInfo::AllocAttributes
//
// Purpose:
// Return a pointer to a newly allocated attribute subject.
//
// Returns: A pointer to the newly allocated attribute subject.
//
// Programmer: generated by xml2info
// Creation: omitted
//
// ****************************************************************************
AttributeSubject *
ParallelCoordinatesCommonPluginInfo::AllocAttributes()
{
return new ParallelCoordinatesAttributes;
}
// ****************************************************************************
// Method: ParallelCoordinatesCommonPluginInfo::CopyAttributes
//
// Purpose:
// Copy a ParallelCoordinates attribute subject.
//
// Arguments:
// to The destination attribute subject.
// from The source attribute subject.
//
// Programmer: generated by xml2info
// Creation: omitted
//
// ****************************************************************************
void
ParallelCoordinatesCommonPluginInfo::CopyAttributes(AttributeSubject *to,
AttributeSubject *from)
{
*((ParallelCoordinatesAttributes *) to) = *((ParallelCoordinatesAttributes *) from);
}
// ****************************************************************************
// Method: ParallelCoordinatesCommonPluginInfo::GetVariableTypes
//
// Purpose:
// Returns a flag indicating the types of variables that can be put in the
// plot's variable list.
//
// Returns: A flag indicating the types of variables that can be put in
// the plot's variable list.
//
// Programmer: generated by xml2info
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
int
ParallelCoordinatesCommonPluginInfo::GetVariableTypes() const
{
return VAR_CATEGORY_SCALAR | VAR_CATEGORY_CURVE | VAR_CATEGORY_ARRAY;
}
|
cd46344ea6cccf056c7cad6bbc11ecdea7484be1
|
f4ea6db9183b38e0cb1af1d317b0a02db24455d1
|
/mudlib/sys/configuration.h
|
a89cd5142532b6a3857e6f3e96a700b69f96854d
|
[
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] |
permissive
|
ldmud/ldmud
|
1446ff7101f5a47ee1dfa4cfb97d5a326f2edcce
|
f1cfc9a8d911412d854055058889bb32432da2db
|
refs/heads/master
| 2023-05-25T00:36:28.318383
| 2023-02-14T21:07:35
| 2023-02-18T10:20:44
| 1,085,012
| 124
| 71
|
NOASSERTION
| 2023-09-01T16:54:48
| 2010-11-16T12:13:17
|
C
|
UTF-8
|
C
| false
| false
| 2,286
|
h
|
configuration.h
|
#ifndef LPC_CONFIGURATION_H_
#define LPC_CONFIGURATION_H_
/* Definition of argument values for the configure_*() efuns.
*/
/* Possible options for configure_interactive().
*/
#define IC_MAX_WRITE_BUFFER_SIZE 0
#define IC_SOCKET_BUFFER_SIZE 1
#define IC_COMBINE_CHARSET_AS_STRING 2
#define IC_COMBINE_CHARSET_AS_ARRAY 3
#define IC_CONNECTION_CHARSET_AS_STRING 4
#define IC_CONNECTION_CHARSET_AS_ARRAY 5
#define IC_QUOTE_IAC 6
#define IC_TELNET_ENABLED 7
#define IC_MCCP 8
#define IC_PROMPT 9
#define IC_MAX_COMMANDS 10
#define IC_MODIFY_COMMAND 11
#define IC_ENCODING 12
/* Possible options for configure_object().
*/
#define OC_COMMANDS_ENABLED 0
#define OC_HEART_BEAT 1
#define OC_EUID 2
/* Possible options for configure_lwobject().
*/
#define LC_EUID 0
/* Possible options for configure_driver().
*/
#define DC_MEMORY_LIMIT 0
#define DC_ENABLE_HEART_BEATS 1
#define DC_LONG_EXEC_TIME 2
#define DC_DATA_CLEAN_TIME 3
#define DC_TLS_CERTIFICATE 4
#define DC_TLS_DHE_PARAMETER 5
#define DC_TLS_CIPHERLIST 6
#define DC_EXTRA_WIZINFO_SIZE 7
#define DC_DEFAULT_RUNTIME_LIMITS 8
#define DC_SWAP_COMPACT_MODE 9
#define DC_SWAP_TIME 10
#define DC_SWAP_VAR_TIME 11
#define DC_CLEANUP_TIME 12
#define DC_RESET_TIME 13
#define DC_DEBUG_FILE 14
#define DC_FILESYSTEM_ENCODING 15
#define DC_SIGACTION_SIGHUP 20
#define DC_SIGACTION_SIGINT 21
#define DC_SIGACTION_SIGUSR1 22
#define DC_SIGACTION_SIGUSR2 23
/* Values for the DC_SIGACTION_SIG* options:
*/
#define DCS_DEFAULT 0
#define DCS_IGNORE 1
#define DCS_TERMINATE 2
#define DCS_SHUTDOWN 3
#define DCS_INFORM_MASTER 4
#define DCS_RELOAD_MASTER 5
#define DCS_THROW_EXCEPTION 6
#endif /* LPC_CONFIGURATION_H_ */
|
81dfd038b7b9d9c49a4a0119027f65f6d1408edb
|
6ffd23679939f59f0a09c9507a126ba056b239d7
|
/imperative/src/include/megbrain/imperative.h
|
ed0fac50a499f7d4e50ff8980d29ae94642a64f4
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] |
permissive
|
MegEngine/MegEngine
|
74c1c9b6022c858962caf7f27e6f65220739999f
|
66b79160d35b2710c00befede0c3fd729109e474
|
refs/heads/master
| 2023-08-23T20:01:32.476848
| 2023-08-01T07:12:01
| 2023-08-11T06:04:12
| 248,175,118
| 5,697
| 585
|
Apache-2.0
| 2023-07-19T05:11:07
| 2020-03-18T08:21:58
|
C++
|
UTF-8
|
C
| false
| false
| 170
|
h
|
imperative.h
|
#pragma once
#include "megbrain/imperative/op_def.h"
#include "megbrain/imperative/physical_tensor.h"
// vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}
|
e3eff63a20f177e52002e53477bf09834e4e47d2
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/arch/evbarm/ifpga/sm_ifpga.c
|
23c838bf047f54fa5f04e7f343c892f25399993b
|
[] |
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
| 3,224
|
c
|
sm_ifpga.c
|
/* $NetBSD: sm_ifpga.c,v 1.2 2013/02/23 08:23:03 skrll Exp $ */
/*-
* Copyright (c) 2013 Sergio Lopez <slp@sinrega.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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: sm_ifpga.c,v 1.2 2013/02/23 08:23:03 skrll Exp $");
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <net/if.h>
#include <net/if_ether.h>
#include <net/if_media.h>
#include <machine/intr.h>
#include <sys/bus.h>
#include <dev/mii/mii.h>
#include <dev/mii/miivar.h>
#include <dev/ic/smc91cxxreg.h>
#include <dev/ic/smc91cxxvar.h>
#include <evbarm/ifpga/ifpgareg.h>
#include <evbarm/ifpga/ifpgavar.h>
static int sm_ifpga_match(device_t, cfdata_t, void *);
static void sm_ifpga_attach(device_t, device_t, void *);
struct sm_ifpga_softc {
struct smc91cxx_softc sc_sm;
void *ih;
};
CFATTACH_DECL_NEW(sm_ifpga, sizeof(struct sm_ifpga_softc), sm_ifpga_match,
sm_ifpga_attach, NULL, NULL);
static int
sm_ifpga_match(device_t parent, cfdata_t match, void *aux)
{
struct ifpga_attach_args *ifa = aux;
if (ifa->ifa_addr == IFPGA_SMC911_BASE)
return 1;
return 0;
}
static void
sm_ifpga_attach(device_t parent, device_t self, void *aux)
{
struct sm_ifpga_softc *isc = device_private(self);
struct smc91cxx_softc *sc = &isc->sc_sm;
struct ifpga_attach_args *ifa = aux;
bus_space_tag_t bst = ifa->ifa_iot;
bus_space_handle_t bsh;
/* map i/o space */
if (bus_space_map(bst, ifa->ifa_addr, SMC_IOSIZE, 0, &bsh) != 0) {
aprint_error(": sm_ifpga_attach: can't map i/o space");
return;
}
isc->ih = ifpga_intr_establish(ifa->ifa_irq, IPL_NET, smc91cxx_intr, sc);
if (isc->ih == NULL) {
aprint_error(": couldn't establish interrupt\n");
bus_space_unmap(bst, bsh, SMC_IOSIZE);
return;
}
aprint_normal("\n");
/* fill in master sc */
sc->sc_dev = self;
sc->sc_bst = bst;
sc->sc_bsh = bsh;
sc->sc_flags = SMC_FLAGS_ENABLED;
smc91cxx_attach(sc, NULL);
}
|
2a15608fee5bed64ec72a2e155ed36187418404c
|
010279e2ba272d09e9d2c4e903722e5faba2cf7a
|
/contrib/tools/python3/src/Include/internal/pycore_atomic_funcs.h
|
a708789cea733bbc56cc3c3271a280a413a8ce4f
|
[
"LicenseRef-scancode-python-cwi",
"LicenseRef-scancode-other-copyleft",
"Python-2.0",
"BSD-3-Clause",
"0BSD",
"GPL-1.0-or-later",
"LicenseRef-scancode-free-unknown",
"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
| 2,438
|
h
|
pycore_atomic_funcs.h
|
/* Atomic functions: similar to pycore_atomic.h, but don't need
to declare variables as atomic.
Py_ssize_t type:
* value = _Py_atomic_size_get(&var)
* _Py_atomic_size_set(&var, value)
Use sequentially-consistent ordering (__ATOMIC_SEQ_CST memory order):
enforce total ordering with all other atomic functions.
*/
#ifndef Py_ATOMIC_FUNC_H
#define Py_ATOMIC_FUNC_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef Py_BUILD_CORE
# error "this header requires Py_BUILD_CORE define"
#endif
#if defined(_MSC_VER)
# include <intrin.h> // _InterlockedExchange()
#endif
// Use builtin atomic operations in GCC >= 4.7 and clang
#ifdef HAVE_BUILTIN_ATOMIC
static inline Py_ssize_t _Py_atomic_size_get(Py_ssize_t *var)
{
return __atomic_load_n(var, __ATOMIC_SEQ_CST);
}
static inline void _Py_atomic_size_set(Py_ssize_t *var, Py_ssize_t value)
{
__atomic_store_n(var, value, __ATOMIC_SEQ_CST);
}
#elif defined(_MSC_VER)
static inline Py_ssize_t _Py_atomic_size_get(Py_ssize_t *var)
{
#if SIZEOF_VOID_P == 8
Py_BUILD_ASSERT(sizeof(__int64) == sizeof(*var));
volatile __int64 *volatile_var = (volatile __int64 *)var;
__int64 old;
do {
old = *volatile_var;
} while(_InterlockedCompareExchange64(volatile_var, old, old) != old);
#else
Py_BUILD_ASSERT(sizeof(long) == sizeof(*var));
volatile long *volatile_var = (volatile long *)var;
long old;
do {
old = *volatile_var;
} while(_InterlockedCompareExchange(volatile_var, old, old) != old);
#endif
return old;
}
static inline void _Py_atomic_size_set(Py_ssize_t *var, Py_ssize_t value)
{
#if SIZEOF_VOID_P == 8
Py_BUILD_ASSERT(sizeof(__int64) == sizeof(*var));
volatile __int64 *volatile_var = (volatile __int64 *)var;
_InterlockedExchange64(volatile_var, value);
#else
Py_BUILD_ASSERT(sizeof(long) == sizeof(*var));
volatile long *volatile_var = (volatile long *)var;
_InterlockedExchange(volatile_var, value);
#endif
}
#else
// Fallback implementation using volatile
static inline Py_ssize_t _Py_atomic_size_get(Py_ssize_t *var)
{
volatile Py_ssize_t *volatile_var = (volatile Py_ssize_t *)var;
return *volatile_var;
}
static inline void _Py_atomic_size_set(Py_ssize_t *var, Py_ssize_t value)
{
volatile Py_ssize_t *volatile_var = (volatile Py_ssize_t *)var;
*volatile_var = value;
}
#endif
#ifdef __cplusplus
}
#endif
#endif /* Py_ATOMIC_FUNC_H */
|
58d2c1253502c97cf00a0ac9ed9769f136fc8642
|
4c4deee160ee4a3056b2973f6202e5cbaafb5925
|
/core/lrutree.h
|
a19f4df530b6bd8821efa81948372f736d6c7771
|
[
"AGPL-3.0-only",
"LGPL-3.0-only"
] |
permissive
|
open-io/oio-sds
|
b9bc7cec283838a59b83b5279cb181cded69034f
|
08abd65aac86e47cf324826487ab9b475e014938
|
refs/heads/master
| 2023-09-05T05:09:29.653325
| 2023-08-01T16:37:37
| 2023-08-31T16:05:19
| 32,169,193
| 663
| 121
|
MIT
| 2022-03-04T13:08:03
| 2015-03-13T17:06:25
|
Python
|
UTF-8
|
C
| false
| false
| 2,780
|
h
|
lrutree.h
|
/*
OpenIO SDS metautils
Copyright (C) 2014 Worldline, as part of Redcurrant
Copyright (C) 2015-2020 OpenIO SAS, as part of OpenIO SDS
Copyright (C) 2021 OVH SAS
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library.
*/
#ifndef OIO_SDS__core__lrutree_h
# define OIO_SDS__core__lrutree_h 1
# include <glib.h>
#define LTO_NONE 0x00
/** Do not set time on access
* (lru_tree_get()) */
#define LTO_NOATIME 0x01
/** Do not set time on update
* (lru_tree_insert() and the key was already in the tree) */
#define LTO_NOUTIME 0x02
#ifdef __cplusplus
extern "C" {
#endif
struct lru_tree_s;
/**
* @param compare
* @param kfree
* @param vfree
* @param options a binary OR'ed combination of LTO_* flags.
* @return NULL in case of error or a valid lru_tree_s ready to be used
*/
struct lru_tree_s* lru_tree_create(GCompareFunc compare,
GDestroyNotify kfree, GDestroyNotify vfree, guint32 options);
/* Destroys the LRU-Tree and calls the liberation hook for each stored
* pair. */
void lru_tree_destroy(struct lru_tree_s *lt);
guint lru_tree_remove_older (struct lru_tree_s *lt, gint64 oldest);
guint lru_tree_remove_exceeding (struct lru_tree_s *lt, guint count);
void lru_tree_insert(struct lru_tree_s *lt, gpointer k, gpointer v);
gpointer lru_tree_get(struct lru_tree_s *lt, gconstpointer k);
/* Returns TRUE if the item keyed with 'k' has been removed. */
gboolean lru_tree_remove(struct lru_tree_s *lt, gconstpointer k);
/* Returns the value of the item keyed with 'k', and remove it from the tree.
* 'k' is kept, but the internal key is freed. Returns NULL if no item with
* such key was present in the tree. */
gpointer lru_tree_steal(struct lru_tree_s *lt, gconstpointer k);
void lru_tree_foreach(struct lru_tree_s *lt, GTraverseFunc h, gpointer hdata);
gpointer lru_tree_get_oldest_key(struct lru_tree_s *lt);
/** Remove from the LRU-Tree at most `max` elements older than `oldest`,
* and call `func` on each of them. `func` is responsible for freeing
* both key and value. */
void lru_tree_foreach_older_steal(struct lru_tree_s *lt,
GTraverseFunc func, gpointer hdata, gint64 oldest, guint max);
gint64 lru_tree_count(struct lru_tree_s *lt);
#ifdef __cplusplus
}
#endif
#endif /*OIO_SDS__core__lrutree_h*/
|
ea7463e2178e3d56e9a0cd81630110fb06143a30
|
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
|
/PWGCF/FLOW/macros/AddTaskCMEMC.C
|
7fbed26030b4e1ffbe4e3f4f78f5d1f71dd51c52
|
[] |
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
| 6,748
|
c
|
AddTaskCMEMC.C
|
class AliAnalysisTaskCMEMC;
void AddTaskCMEMC(Int_t gFilterBit = 96, Double_t fPtMin=0.2, Double_t fPtMax=5.0, Double_t fEtaMin=-0.8, Double_t fEtaMax=0.8, Double_t fDCAxyMax=2.4,Double_t fDCAzMax=3.2, Int_t gNclustTPC=70, TString sCentEstimator="V0M", Double_t fCentralityMin=0., Double_t fCentralityMax=90., Float_t fVzMin = -10.0, Float_t fVzMax = 10.0, TString sNuclei="PbPb", TString sTrigger="kINT7", Bool_t bSkipPileUp=kFALSE, Double_t fSlope=3.45, Float_t fConst=100, Int_t gN = 1, Int_t gM = 2, Int_t gPsiN=2, Bool_t bUseMC=kFALSE, TString sMCfilePath = "alien:///alice/cern.ch/user/m/mhaque/gain/FB96_Hijing_LHC15o_HI_CorSec.root", Bool_t bUseNUA=kFALSE, TString sNUAFilePath = "alien:///alice/cern.ch/user/m/mhaque/gain/NUA15o_pass1_FB96_C15k_CentBin5_AvgEtaFull.root", Bool_t bV0MCorr=kFALSE, TString sV0MFile="alien:///alice/cern.ch/user/m/mhaque/gain/V0GainEq_LHC15o_pass1HI_C15K_RbyR.root", Bool_t bFillNUAPID=kTRUE, const char *suffix = "")
{
// standard with task
printf("========================================================================================\n");
printf(" Info: Initialising AliAnalysisTaskCMEMC \n" );
printf("========================================================================================\n");
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
TString file = AliAnalysisManager::GetCommonFileName();
TString ContainerFE;
ContainerFE.Form("FlowEventCont_%s", suffix);
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); //AOD event
TString listOutName1 = file; // file is the common outfile filename
listOutName1 += ":Results";
AliAnalysisDataContainer *coutputCont1;
Int_t gCentMin = fCentralityMin;
Int_t gCentMax = fCentralityMax;
TString TaskCMEV0PID;
TString fCME_container;
TaskCMEV0PID.Form("TaskCMEV0PID_Cent_%d_%d_%s", gCentMin, gCentMax, suffix);
//cout<<"Add taskname = "<<TaskCMEV0PID.Data()<<endl;
AliAnalysisTaskCMEMC *task_CME = new AliAnalysisTaskCMEMC(TaskCMEV0PID);
//task_CME->SelectCollisionCandidates(AliVEvent::kINT7); //default if kINT7
// if(sTrigger=="kMB" || sTrigger=="kmb" || sTrigger=="MB"){
// task_CME->SelectCollisionCandidates(AliVEvent::kMB);
// }
//Track cuts:
task_CME->SetFilterBit(gFilterBit);
task_CME->SetNSigmaCutTPC(2.0);
task_CME->SetPtRangeMin(fPtMin);
task_CME->SetPtRangeMax(fPtMax);
task_CME->SetEtaRangeMin(fEtaMin);
task_CME->SetEtaRangeMax(fEtaMax);
task_CME->SetTrackCutdEdxMin(10.0);
task_CME->SetTrackCutDCAzMax(fDCAxyMax);
task_CME->SetTrackCutDCAxyMax(fDCAzMax);
task_CME->SetTrackCutChi2Min(0.1);
task_CME->SetTrackCutNclusterMin(gNclustTPC);
task_CME->SetFlagUseKinkTracks(kFALSE);
//Event cuts:
task_CME->SetCentralityPercentileMin(fCentralityMin);
task_CME->SetCentralityPercentileMax(fCentralityMax);
task_CME->SetPileUpCutParam(fSlope,fConst);
task_CME->SetCollisionSystem(sNuclei);
task_CME->SetHarmonicsFor3Particle(gN,gM); // n and m, Cos(n*phi1 + m*phi2 - (n+m)Psi_{gPsiN})
task_CME->SetEventPlaneHarmonic(gPsiN); // gPsiN = order N of Event Plane. Look Here ---->^
task_CME->SetFlagSkipPileUpCuts(bSkipPileUp);
task_CME->SetVzRangeMin(fVzMin);
task_CME->SetVzRangeMax(fVzMax);
//if(sCentEstimator=="V0" || sCentEstimator=="V0M"){
//task_CME->SetCentralityEstimator("V0M"); //V0M or V0A or V0C or V0=V0M
//}
//else{
//task_CME->SetCentralityEstimator(sCentEstimator); //V0M or V0A or V0C or V0=V0M
//}
if(bFillNUAPID){
task_CME->SetFlagFillNUAforPID(kTRUE);
}
TFile* fMCFile=NULL;
TList* fListMC=NULL;
if(bUseMC) {
task_CME->SetFlagForMCcorrection(kTRUE);
fMCFile = TFile::Open(sMCfilePath,"READ");
if(!fMCFile) {
Ssiz_t pos = sMCfilePath.Index(".root");
sMCfilePath.Replace(pos,5,"_copy.root");
fMCFile = TFile::Open(sMCfilePath,"READ");
if(!fMCFile) printf("\n\n *** ERROR: MC correction file not found! \n Please check path/name \n\n");
//exit(1);
}
else {
fListMC = dynamic_cast <TList*> (fMCFile->FindObjectAny("fMcEffiHij"));
if(fListMC) {
//std::cout<<" \n ==============> List found for MC corr, here is all the histograms : ";
//fListMC->ls();
task_CME->SetFBEfficiencyList(fListMC);
}
else{
printf("\n\n *** ERROR: MC file Exist, But fList name is wrong!!\n please check name \n\n");
}
}
}
else{
task_CME->SetFlagForMCcorrection(kFALSE);
}
//--------------------------
TFile* fNUAFile=NULL;
TList* fListNUA=NULL;
if(bUseNUA){
fNUAFile = TFile::Open(sNUAFilePath,"READ");
if(!fNUAFile) {
Ssiz_t pos = sNUAFilePath.Index(".root");
sNUAFilePath.Replace(pos,5,"_copy.root");
fNUAFile = TFile::Open(sNUAFilePath,"READ");
if(!fNUAFile) printf("\n\n *** ERROR: NUA wgt file not found! \n Please check path/name \n\n");
//exit(1);
}
else {
fListNUA = dynamic_cast <TList*> (fNUAFile->FindObjectAny("fNUA_ChPosChNeg"));
//std::cout<<" \n ==============> List found for NUA, here is all the histograms : ";
//fListNUA->ls();
if(fListNUA) {
task_CME->SetListForNUACorr(fListNUA);
}
else{
printf("\n\n *** ERROR: NUA file Exist, But fList name is wrong!!\n please check name \n\n");
}
}
}
//----------------------------
if(bV0MCorr){
TFile* fV0MFile = TFile::Open(sV0MFile,"READ");
if(!fV0MFile) {
Ssiz_t pos = sV0MFile.Index(".root");
sV0MFile.Replace(pos,5,"_copy.root");
fV0MFile = TFile::Open(sV0MFile,"READ");
if(!fV0MFile) printf("\n\n !!! ERROR: VOM Gain correction file not found! Please check path \n ***(EXIT now)*** \n\n");
//exit(1);
}
else{
TList* fListV0MUse = dynamic_cast<TList*>(fV0MFile->FindObjectAny("fV0MChWgts"));
if(fListV0MUse) {
task_CME->SetFlagV0MGainCorr(kTRUE);
task_CME->SetListForV0MCorr(fListV0MUse);
}
else{
printf("\n\n !!!**** ERROR: TList for VOM Gain Correction found \n Please check name !!!\n\n");
task_CME->SetListForV0MCorr(NULL);
}
}
}
mgr->AddTask(task_CME); // connect the task to the analysis manager
mgr->ConnectInput(task_CME, 0, cinput); // give AOD event to my Task..!!
fCME_container.Form("CME_PID_%s", suffix);
coutputCont1 = (AliAnalysisDataContainer *) mgr->CreateContainer(fCME_container,TList::Class(),AliAnalysisManager::kOutputContainer,listOutName1.Data());
mgr->ConnectOutput(task_CME, 1, coutputCont1);
printf("\n ===================> AddTaskCMEV0PID() Configured properly Panos <=====================\n");
//return task_CME;
}//main ends
|
79f92cd08c64f05bc0fb1c29270c0d2948b397c1
|
fb47ab6337a71029dee71933e449cf7f6805fc0f
|
/lib/fs/fs.c
|
256c244fa970524dc386165e4ab0aaf10f97afea
|
[
"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
| 17,122
|
c
|
fs.c
|
/*
* Copyright (c) 2009-2015 Travis Geiselbrecht
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT
*/
#include <lib/fs.h>
#include <lk/debug.h>
#include <lk/trace.h>
#include <lk/list.h>
#include <lk/err.h>
#include <string.h>
#include <stdlib.h>
#include <lib/bio.h>
#include <lk/init.h>
#include <kernel/mutex.h>
#define LOCAL_TRACE 0
struct fs_mount {
struct list_node node;
char *path;
size_t pathlen; // save the strlen of path above to help with path matching
bdev_t *dev;
fscookie *cookie;
int ref;
const struct fs_impl *fs;
const struct fs_api *api;
};
struct filehandle {
filecookie *cookie;
struct fs_mount *mount;
};
struct dirhandle {
dircookie *cookie;
struct fs_mount *mount;
};
static mutex_t mount_lock = MUTEX_INITIAL_VALUE(mount_lock);
static struct list_node mounts = LIST_INITIAL_VALUE(mounts);
static struct list_node fses = LIST_INITIAL_VALUE(fses);
// defined by the linker, wrapping all structs in the "fs_impl" section
extern const struct fs_impl __start_fs_impl __WEAK;
extern const struct fs_impl __stop_fs_impl __WEAK;
static const struct fs_impl *find_fs(const char *name) {
for (const struct fs_impl *fs = &__start_fs_impl; fs != &__stop_fs_impl; fs++) {
if (!strcmp(name, fs->name))
return fs;
}
return NULL;
}
void fs_dump_list(void) {
for (const struct fs_impl *fs = &__start_fs_impl; fs != &__stop_fs_impl; fs++) {
puts(fs->name);
}
}
void fs_dump_mounts(void) {
printf("%-16s%s\n", "Filesystem", "Path");
mutex_acquire(&mount_lock);
struct fs_mount *mount;
list_for_every_entry(&mounts, mount, struct fs_mount, node) {
printf("%-16s%s\n", mount->fs->name, mount->path);
}
mutex_release(&mount_lock);
}
// find a mount structure based on the prefix of this path
// bump the ref to the mount structure before returning
static struct fs_mount *find_mount(const char *path, const char **trimmed_path) {
// paths must be absolute and start with /
if (path[0] != '/') {
return NULL;
}
size_t pathlen = strlen(path);
mutex_acquire(&mount_lock);
struct fs_mount *mount;
list_for_every_entry(&mounts, mount, struct fs_mount, node) {
// if the path is shorter than this mount point, no point continuing
if (pathlen < mount->pathlen) {
continue;
}
LTRACEF("comparing %s with %s\n", path, mount->path);
if (memcmp(path, mount->path, mount->pathlen) == 0) {
// If we got a match, make sure the next element in the path is
// a path separator or the end of the string. This keeps from
// matching /foo2 with /foo, but /foo/bar would match correctly.
if (path[mount->pathlen] != '/' && path[mount->pathlen] != 0) {
continue;
}
// we got a match, skip forward to the next element
if (trimmed_path) {
*trimmed_path = &path[mount->pathlen];
// if we matched against the end of the path, at least return
// a "/".
// TODO: decide if this is necessary
if (*trimmed_path[0] == 0) {
*trimmed_path = "/";
}
}
mount->ref++;
mutex_release(&mount_lock);
return mount;
}
}
mutex_release(&mount_lock);
return NULL;
}
// decrement the ref to the mount structure, which may
// cause an unmount operation
static void put_mount(struct fs_mount *mount) {
mutex_acquire(&mount_lock);
if ((--mount->ref) == 0) {
LTRACEF("last ref, unmounting fs at '%s'\n", mount->path);
list_delete(&mount->node);
mount->api->unmount(mount->cookie);
free(mount->path);
if (mount->dev)
bio_close(mount->dev);
free(mount);
}
mutex_release(&mount_lock);
}
static status_t mount(const char *path, const char *device, const struct fs_impl *fs) {
struct fs_mount *mount;
const struct fs_api *api = fs->api;
char temppath[FS_MAX_PATH_LEN];
strlcpy(temppath, path, sizeof(temppath));
fs_normalize_path(temppath);
if (temppath[0] != '/')
return ERR_BAD_PATH;
/* see if there's already something at this path, abort if there is */
mount = find_mount(temppath, NULL);
if (mount) {
put_mount(mount);
return ERR_ALREADY_MOUNTED;
}
/* open a bio device if the string is nonnull */
bdev_t *dev = NULL;
if (device && device[0] != '\0') {
dev = bio_open(device);
if (!dev)
return ERR_NOT_FOUND;
}
/* call into the fs implementation */
fscookie *cookie;
status_t err = api->mount(dev, &cookie);
if (err < 0) {
if (dev) bio_close(dev);
return err;
}
/* create the mount structure and add it to the list */
mount = malloc(sizeof(struct fs_mount));
if (!mount) {
if (dev) bio_close(dev);
return ERR_NO_MEMORY;
}
mount->path = strdup(temppath);
if (!mount->path) {
if (dev) bio_close(dev);
free(mount);
return ERR_NO_MEMORY;
}
mount->pathlen = strlen(mount->path);
mount->dev = dev;
mount->cookie = cookie;
mount->ref = 1;
mount->fs = fs;
mount->api = api;
list_add_head(&mounts, &mount->node);
return 0;
}
status_t fs_format_device(const char *fsname, const char *device, const void *args) {
const struct fs_impl *fs = find_fs(fsname);
if (!fs) {
return ERR_NOT_FOUND;
}
if (fs->api->format == NULL) {
return ERR_NOT_SUPPORTED;
}
bdev_t *dev = NULL;
if (device && device[0] != '\0') {
dev = bio_open(device);
if (!dev)
return ERR_NOT_FOUND;
}
return fs->api->format(dev, args);
}
status_t fs_mount(const char *path, const char *fsname, const char *device) {
const struct fs_impl *fs = find_fs(fsname);
if (!fs)
return ERR_NOT_FOUND;
return mount(path, device, fs);
}
status_t fs_unmount(const char *path) {
char temppath[FS_MAX_PATH_LEN];
strlcpy(temppath, path, sizeof(temppath));
fs_normalize_path(temppath);
struct fs_mount *mount = find_mount(temppath, NULL);
if (!mount)
return ERR_NOT_FOUND;
// return the ref that find_mount added and one extra
put_mount(mount);
put_mount(mount);
return 0;
}
status_t fs_open_file(const char *path, filehandle **handle) {
char temppath[FS_MAX_PATH_LEN];
strlcpy(temppath, path, sizeof(temppath));
fs_normalize_path(temppath);
LTRACEF("path %s temppath %s\n", path, temppath);
const char *newpath;
struct fs_mount *mount = find_mount(temppath, &newpath);
if (!mount)
return ERR_NOT_FOUND;
LTRACEF("path %s temppath %s newpath %s\n", path, temppath, newpath);
filecookie *cookie;
status_t err = mount->api->open(mount->cookie, newpath, &cookie);
if (err < 0) {
put_mount(mount);
return err;
}
filehandle *f = malloc(sizeof(*f));
f->cookie = cookie;
f->mount = mount;
*handle = f;
return 0;
}
status_t fs_file_ioctl(filehandle *handle, int request, void *argp) {
LTRACEF("filehandle %p, request %d, argp, %p\n", handle, request, argp);
if (unlikely(!handle || !handle->mount ||
!handle->mount->api || !handle->mount->api->file_ioctl)) {
return ERR_INVALID_ARGS;
}
return handle->mount->api->file_ioctl(handle->cookie, request, argp);
}
status_t fs_create_file(const char *path, filehandle **handle, uint64_t len) {
char temppath[FS_MAX_PATH_LEN];
strlcpy(temppath, path, sizeof(temppath));
fs_normalize_path(temppath);
const char *newpath;
struct fs_mount *mount = find_mount(temppath, &newpath);
if (!mount)
return ERR_NOT_FOUND;
if (!mount->api->create) {
put_mount(mount);
return ERR_NOT_SUPPORTED;
}
filecookie *cookie;
status_t err = mount->api->create(mount->cookie, newpath, &cookie, len);
if (err < 0) {
put_mount(mount);
return err;
}
filehandle *f = malloc(sizeof(*f));
if (!f) {
put_mount(mount);
return err;
}
f->cookie = cookie;
f->mount = mount;
*handle = f;
return 0;
}
status_t fs_truncate_file(filehandle *handle, uint64_t len) {
LTRACEF("filehandle %p, length %llu\n", handle, len);
if (unlikely(!handle))
return ERR_INVALID_ARGS;
return handle->mount->api->truncate(handle->cookie, len);
}
status_t fs_remove_file(const char *path) {
char temppath[FS_MAX_PATH_LEN];
strlcpy(temppath, path, sizeof(temppath));
fs_normalize_path(temppath);
const char *newpath;
struct fs_mount *mount = find_mount(temppath, &newpath);
if (!mount)
return ERR_NOT_FOUND;
if (!mount->api->remove) {
put_mount(mount);
return ERR_NOT_SUPPORTED;
}
status_t err = mount->api->remove(mount->cookie, newpath);
put_mount(mount);
return err;
}
ssize_t fs_read_file(filehandle *handle, void *buf, off_t offset, size_t len) {
return handle->mount->api->read(handle->cookie, buf, offset, len);
}
ssize_t fs_write_file(filehandle *handle, const void *buf, off_t offset, size_t len) {
if (!handle->mount->api->write)
return ERR_NOT_SUPPORTED;
return handle->mount->api->write(handle->cookie, buf, offset, len);
}
status_t fs_close_file(filehandle *handle) {
status_t err = handle->mount->api->close(handle->cookie);
if (err < 0)
return err;
put_mount(handle->mount);
free(handle);
return 0;
}
status_t fs_stat_file(filehandle *handle, struct file_stat *stat) {
return handle->mount->api->stat(handle->cookie, stat);
}
status_t fs_make_dir(const char *path) {
char temppath[FS_MAX_PATH_LEN];
strlcpy(temppath, path, sizeof(temppath));
fs_normalize_path(temppath);
const char *newpath;
struct fs_mount *mount = find_mount(temppath, &newpath);
if (!mount)
return ERR_NOT_FOUND;
if (!mount->api->mkdir) {
put_mount(mount);
return ERR_NOT_SUPPORTED;
}
status_t err = mount->api->mkdir(mount->cookie, newpath);
put_mount(mount);
return err;
}
status_t fs_open_dir(const char *path, dirhandle **handle) {
char temppath[FS_MAX_PATH_LEN];
strlcpy(temppath, path, sizeof(temppath));
fs_normalize_path(temppath);
LTRACEF("path %s temppath %s\n", path, temppath);
const char *newpath;
struct fs_mount *mount = find_mount(temppath, &newpath);
if (!mount)
return ERR_NOT_FOUND;
LTRACEF("path %s temppath %s newpath %s\n", path, temppath, newpath);
if (!mount->api->opendir) {
put_mount(mount);
return ERR_NOT_SUPPORTED;
}
dircookie *cookie;
status_t err = mount->api->opendir(mount->cookie, newpath, &cookie);
if (err < 0) {
put_mount(mount);
return err;
}
dirhandle *d = malloc(sizeof(*d));
if (!d) {
put_mount(mount);
return ERR_NO_MEMORY;
}
d->cookie = cookie;
d->mount = mount;
*handle = d;
return 0;
}
status_t fs_read_dir(dirhandle *handle, struct dirent *ent) {
if (!handle->mount->api->readdir)
return ERR_NOT_SUPPORTED;
return handle->mount->api->readdir(handle->cookie, ent);
}
status_t fs_close_dir(dirhandle *handle) {
if (!handle->mount->api->closedir)
return ERR_NOT_SUPPORTED;
status_t err = handle->mount->api->closedir(handle->cookie);
if (err < 0)
return err;
put_mount(handle->mount);
free(handle);
return 0;
}
status_t fs_stat_fs(const char *mountpoint, struct fs_stat *stat) {
LTRACEF("mountpoint %s stat %p\n", mountpoint, stat);
if (!stat) {
return ERR_INVALID_ARGS;
}
const char *newpath;
struct fs_mount *mount = find_mount(mountpoint, &newpath);
if (!mount) {
return ERR_NOT_FOUND;
}
if (!mount->api->fs_stat) {
put_mount(mount);
return ERR_NOT_SUPPORTED;
}
status_t result = mount->api->fs_stat(mount->cookie, stat);
put_mount(mount);
return result;
}
ssize_t fs_load_file(const char *path, void *ptr, size_t maxlen) {
filehandle *handle;
/* open the file */
status_t err = fs_open_file(path, &handle);
if (err < 0)
return err;
/* stat it for size, see how much we need to read */
struct file_stat stat;
fs_stat_file(handle, &stat);
ssize_t read_bytes = fs_read_file(handle, ptr, 0, MIN(maxlen, stat.size));
fs_close_file(handle);
return read_bytes;
}
const char *trim_name(const char *_name) {
const char *name = &_name[0];
// chew up leading spaces
while (*name == ' ')
name++;
// chew up leading slashes
while (*name == '/')
name++;
return name;
}
void fs_normalize_path(char *path) {
int outpos;
int pos;
char c;
bool done;
enum {
INITIAL,
FIELD_START,
IN_FIELD,
SEP,
SEEN_SEP,
DOT,
SEEN_DOT,
DOTDOT,
SEEN_DOTDOT,
} state;
state = INITIAL;
pos = 0;
outpos = 0;
done = false;
/* remove duplicate path separators, flatten empty fields (only composed of .), backtrack fields with .., remove trailing slashes */
while (!done) {
c = path[pos];
switch (state) {
case INITIAL:
if (c == '/') {
state = SEP;
} else if (c == '.') {
state = DOT;
} else {
state = FIELD_START;
}
break;
case FIELD_START:
if (c == '.') {
state = DOT;
} else if (c == 0) {
done = true;
} else {
state = IN_FIELD;
}
break;
case IN_FIELD:
if (c == '/') {
state = SEP;
} else if (c == 0) {
done = true;
} else {
path[outpos++] = c;
pos++;
}
break;
case SEP:
pos++;
path[outpos++] = '/';
state = SEEN_SEP;
break;
case SEEN_SEP:
if (c == '/') {
// eat it
pos++;
} else if (c == 0) {
done = true;
} else {
state = FIELD_START;
}
break;
case DOT:
pos++; // consume the dot
state = SEEN_DOT;
break;
case SEEN_DOT:
if (c == '.') {
// dotdot now
state = DOTDOT;
} else if (c == '/') {
// a field composed entirely of a .
// consume the / and move directly to the SEEN_SEP state
pos++;
state = SEEN_SEP;
} else if (c == 0) {
done = true;
} else {
// a field prefixed with a .
// emit a . and move directly into the IN_FIELD state
path[outpos++] = '.';
state = IN_FIELD;
}
break;
case DOTDOT:
pos++; // consume the dot
state = SEEN_DOTDOT;
break;
case SEEN_DOTDOT:
if (c == '/' || c == 0) {
// a field composed entirely of '..'
// search back and consume a field we've already emitted
if (outpos > 0) {
// we have already consumed at least one field
outpos--;
// walk backwards until we find the next field boundary
while (outpos > 0) {
if (path[outpos - 1] == '/') {
break;
}
outpos--;
}
}
pos++;
state = SEEN_SEP;
if (c == 0)
done = true;
} else {
// a field prefixed with ..
// emit the .. and move directly to the IN_FIELD state
path[outpos++] = '.';
path[outpos++] = '.';
state = IN_FIELD;
}
break;
}
}
/* don't end with trailing slashes */
if (outpos > 0 && path[outpos - 1] == '/')
outpos--;
path[outpos++] = 0;
}
|
90dea78c6f6a2085bfe4417b375e324b7919df05
|
83e7dc1281874779c46dfadcc15b2bb66d8e599c
|
/src/misc/lv_style_gen.h
|
0697011af25c8e74efeca7c2358de76d25e51a99
|
[
"MIT"
] |
permissive
|
lvgl/lvgl
|
7d51d6774d6ac71df7101fc7ded56fea4b70be01
|
5c984b4a5364b6455966eb3a860153806c51626f
|
refs/heads/master
| 2023-08-30T22:39:20.283922
| 2023-08-30T19:55:29
| 2023-08-30T19:55:29
| 60,667,730
| 9,296
| 2,218
|
MIT
| 2023-09-14T17:59:34
| 2016-06-08T04:14:34
|
C
|
UTF-8
|
C
| false
| false
| 30,070
|
h
|
lv_style_gen.h
|
/*
**********************************************************************
* DO NOT EDIT
* This file is automatically generated by "style_api_gen.py"
**********************************************************************
*/
#ifndef LV_STYLE_GEN_H
#define LV_STYLE_GEN_H
void lv_style_set_width(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_WIDTH;
void lv_style_set_min_width(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_MIN_WIDTH;
void lv_style_set_max_width(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_MAX_WIDTH;
void lv_style_set_height(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_HEIGHT;
void lv_style_set_min_height(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_MIN_HEIGHT;
void lv_style_set_max_height(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_MAX_HEIGHT;
void lv_style_set_x(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_X;
void lv_style_set_y(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_Y;
void lv_style_set_align(lv_style_t * style, lv_align_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_ALIGN;
void lv_style_set_transform_width(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_TRANSFORM_WIDTH;
void lv_style_set_transform_height(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_TRANSFORM_HEIGHT;
void lv_style_set_translate_x(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_TRANSLATE_X;
void lv_style_set_translate_y(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_TRANSLATE_Y;
void lv_style_set_transform_zoom(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_TRANSFORM_ZOOM;
void lv_style_set_transform_angle(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_TRANSFORM_ANGLE;
void lv_style_set_transform_pivot_x(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_TRANSFORM_PIVOT_X;
void lv_style_set_transform_pivot_y(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_TRANSFORM_PIVOT_Y;
void lv_style_set_pad_top(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_PAD_TOP;
void lv_style_set_pad_bottom(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_PAD_BOTTOM;
void lv_style_set_pad_left(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_PAD_LEFT;
void lv_style_set_pad_right(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_PAD_RIGHT;
void lv_style_set_pad_row(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_PAD_ROW;
void lv_style_set_pad_column(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_PAD_COLUMN;
void lv_style_set_margin_top(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_MARGIN_TOP;
void lv_style_set_margin_bottom(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_MARGIN_BOTTOM;
void lv_style_set_margin_left(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_MARGIN_LEFT;
void lv_style_set_margin_right(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_MARGIN_RIGHT;
void lv_style_set_bg_color(lv_style_t * style, lv_color_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BG_COLOR;
void lv_style_set_bg_opa(lv_style_t * style, lv_opa_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BG_OPA;
void lv_style_set_bg_grad_color(lv_style_t * style, lv_color_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BG_GRAD_COLOR;
void lv_style_set_bg_grad_dir(lv_style_t * style, lv_grad_dir_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BG_GRAD_DIR;
void lv_style_set_bg_main_stop(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BG_MAIN_STOP;
void lv_style_set_bg_grad_stop(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BG_GRAD_STOP;
void lv_style_set_bg_grad(lv_style_t * style, const lv_grad_dsc_t * value);
extern const lv_style_prop_t _lv_style_const_prop_id_BG_GRAD;
void lv_style_set_bg_dither_mode(lv_style_t * style, lv_dither_mode_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BG_DITHER_MODE;
void lv_style_set_bg_img_src(lv_style_t * style, const void * value);
extern const lv_style_prop_t _lv_style_const_prop_id_BG_IMG_SRC;
void lv_style_set_bg_img_opa(lv_style_t * style, lv_opa_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BG_IMG_OPA;
void lv_style_set_bg_img_recolor(lv_style_t * style, lv_color_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BG_IMG_RECOLOR;
void lv_style_set_bg_img_recolor_opa(lv_style_t * style, lv_opa_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BG_IMG_RECOLOR_OPA;
void lv_style_set_bg_img_tiled(lv_style_t * style, bool value);
extern const lv_style_prop_t _lv_style_const_prop_id_BG_IMG_TILED;
void lv_style_set_border_color(lv_style_t * style, lv_color_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BORDER_COLOR;
void lv_style_set_border_opa(lv_style_t * style, lv_opa_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BORDER_OPA;
void lv_style_set_border_width(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BORDER_WIDTH;
void lv_style_set_border_side(lv_style_t * style, lv_border_side_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BORDER_SIDE;
void lv_style_set_border_post(lv_style_t * style, bool value);
extern const lv_style_prop_t _lv_style_const_prop_id_BORDER_POST;
void lv_style_set_outline_width(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_OUTLINE_WIDTH;
void lv_style_set_outline_color(lv_style_t * style, lv_color_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_OUTLINE_COLOR;
void lv_style_set_outline_opa(lv_style_t * style, lv_opa_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_OUTLINE_OPA;
void lv_style_set_outline_pad(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_OUTLINE_PAD;
void lv_style_set_shadow_width(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_SHADOW_WIDTH;
void lv_style_set_shadow_ofs_x(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_SHADOW_OFS_X;
void lv_style_set_shadow_ofs_y(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_SHADOW_OFS_Y;
void lv_style_set_shadow_spread(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_SHADOW_SPREAD;
void lv_style_set_shadow_color(lv_style_t * style, lv_color_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_SHADOW_COLOR;
void lv_style_set_shadow_opa(lv_style_t * style, lv_opa_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_SHADOW_OPA;
void lv_style_set_img_opa(lv_style_t * style, lv_opa_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_IMG_OPA;
void lv_style_set_img_recolor(lv_style_t * style, lv_color_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_IMG_RECOLOR;
void lv_style_set_img_recolor_opa(lv_style_t * style, lv_opa_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_IMG_RECOLOR_OPA;
void lv_style_set_line_width(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_LINE_WIDTH;
void lv_style_set_line_dash_width(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_LINE_DASH_WIDTH;
void lv_style_set_line_dash_gap(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_LINE_DASH_GAP;
void lv_style_set_line_rounded(lv_style_t * style, bool value);
extern const lv_style_prop_t _lv_style_const_prop_id_LINE_ROUNDED;
void lv_style_set_line_color(lv_style_t * style, lv_color_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_LINE_COLOR;
void lv_style_set_line_opa(lv_style_t * style, lv_opa_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_LINE_OPA;
void lv_style_set_arc_width(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_ARC_WIDTH;
void lv_style_set_arc_rounded(lv_style_t * style, bool value);
extern const lv_style_prop_t _lv_style_const_prop_id_ARC_ROUNDED;
void lv_style_set_arc_color(lv_style_t * style, lv_color_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_ARC_COLOR;
void lv_style_set_arc_opa(lv_style_t * style, lv_opa_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_ARC_OPA;
void lv_style_set_arc_img_src(lv_style_t * style, const void * value);
extern const lv_style_prop_t _lv_style_const_prop_id_ARC_IMG_SRC;
void lv_style_set_text_color(lv_style_t * style, lv_color_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_TEXT_COLOR;
void lv_style_set_text_opa(lv_style_t * style, lv_opa_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_TEXT_OPA;
void lv_style_set_text_font(lv_style_t * style, const lv_font_t * value);
extern const lv_style_prop_t _lv_style_const_prop_id_TEXT_FONT;
void lv_style_set_text_letter_space(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_TEXT_LETTER_SPACE;
void lv_style_set_text_line_space(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_TEXT_LINE_SPACE;
void lv_style_set_text_decor(lv_style_t * style, lv_text_decor_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_TEXT_DECOR;
void lv_style_set_text_align(lv_style_t * style, lv_text_align_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_TEXT_ALIGN;
void lv_style_set_radius(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_RADIUS;
void lv_style_set_clip_corner(lv_style_t * style, bool value);
extern const lv_style_prop_t _lv_style_const_prop_id_CLIP_CORNER;
void lv_style_set_opa(lv_style_t * style, lv_opa_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_OPA;
void lv_style_set_opa_layered(lv_style_t * style, lv_opa_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_OPA_LAYERED;
void lv_style_set_color_filter_dsc(lv_style_t * style, const lv_color_filter_dsc_t * value);
extern const lv_style_prop_t _lv_style_const_prop_id_COLOR_FILTER_DSC;
void lv_style_set_color_filter_opa(lv_style_t * style, lv_opa_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_COLOR_FILTER_OPA;
void lv_style_set_anim(lv_style_t * style, const lv_anim_t * value);
extern const lv_style_prop_t _lv_style_const_prop_id_ANIM;
void lv_style_set_anim_time(lv_style_t * style, uint32_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_ANIM_TIME;
void lv_style_set_anim_speed(lv_style_t * style, uint32_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_ANIM_SPEED;
void lv_style_set_transition(lv_style_t * style, const lv_style_transition_dsc_t * value);
extern const lv_style_prop_t _lv_style_const_prop_id_TRANSITION;
void lv_style_set_blend_mode(lv_style_t * style, lv_blend_mode_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BLEND_MODE;
void lv_style_set_layout(lv_style_t * style, uint16_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_LAYOUT;
void lv_style_set_base_dir(lv_style_t * style, lv_base_dir_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_BASE_DIR;
void lv_style_set_flex_flow(lv_style_t * style, lv_flex_flow_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_FLEX_FLOW;
void lv_style_set_flex_main_place(lv_style_t * style, lv_flex_align_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_FLEX_MAIN_PLACE;
void lv_style_set_flex_cross_place(lv_style_t * style, lv_flex_align_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_FLEX_CROSS_PLACE;
void lv_style_set_flex_track_place(lv_style_t * style, lv_flex_align_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_FLEX_TRACK_PLACE;
void lv_style_set_flex_grow(lv_style_t * style, uint8_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_FLEX_GROW;
void lv_style_set_grid_column_dsc_array(lv_style_t * style, const lv_coord_t * value);
extern const lv_style_prop_t _lv_style_const_prop_id_GRID_COLUMN_DSC_ARRAY;
void lv_style_set_grid_column_align(lv_style_t * style, lv_grid_align_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_GRID_COLUMN_ALIGN;
void lv_style_set_grid_row_dsc_array(lv_style_t * style, const lv_coord_t * value);
extern const lv_style_prop_t _lv_style_const_prop_id_GRID_ROW_DSC_ARRAY;
void lv_style_set_grid_row_align(lv_style_t * style, lv_grid_align_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_GRID_ROW_ALIGN;
void lv_style_set_grid_cell_column_pos(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_GRID_CELL_COLUMN_POS;
void lv_style_set_grid_cell_x_align(lv_style_t * style, lv_grid_align_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_GRID_CELL_X_ALIGN;
void lv_style_set_grid_cell_column_span(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_GRID_CELL_COLUMN_SPAN;
void lv_style_set_grid_cell_row_pos(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_GRID_CELL_ROW_POS;
void lv_style_set_grid_cell_y_align(lv_style_t * style, lv_grid_align_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_GRID_CELL_Y_ALIGN;
void lv_style_set_grid_cell_row_span(lv_style_t * style, lv_coord_t value);
extern const lv_style_prop_t _lv_style_const_prop_id_GRID_CELL_ROW_SPAN;
#define LV_STYLE_CONST_WIDTH(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_WIDTH, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_MIN_WIDTH(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_MIN_WIDTH, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_MAX_WIDTH(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_MAX_WIDTH, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_HEIGHT(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_HEIGHT, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_MIN_HEIGHT(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_MIN_HEIGHT, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_MAX_HEIGHT(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_MAX_HEIGHT, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_X(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_X, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_Y(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_Y, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_ALIGN(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_ALIGN, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_TRANSFORM_WIDTH(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TRANSFORM_WIDTH, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_TRANSFORM_HEIGHT(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TRANSFORM_HEIGHT, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_TRANSLATE_X(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TRANSLATE_X, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_TRANSLATE_Y(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TRANSLATE_Y, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_TRANSFORM_ZOOM(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TRANSFORM_ZOOM, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_TRANSFORM_ANGLE(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TRANSFORM_ANGLE, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_TRANSFORM_PIVOT_X(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TRANSFORM_PIVOT_X, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_TRANSFORM_PIVOT_Y(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TRANSFORM_PIVOT_Y, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_PAD_TOP(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_PAD_TOP, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_PAD_BOTTOM(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_PAD_BOTTOM, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_PAD_LEFT(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_PAD_LEFT, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_PAD_RIGHT(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_PAD_RIGHT, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_PAD_ROW(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_PAD_ROW, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_PAD_COLUMN(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_PAD_COLUMN, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_MARGIN_TOP(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_MARGIN_TOP, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_MARGIN_BOTTOM(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_MARGIN_BOTTOM, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_MARGIN_LEFT(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_MARGIN_LEFT, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_MARGIN_RIGHT(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_MARGIN_RIGHT, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_BG_COLOR(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BG_COLOR, .value = { .color = val } \
}
#define LV_STYLE_CONST_BG_OPA(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BG_OPA, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_BG_GRAD_COLOR(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BG_GRAD_COLOR, .value = { .color = val } \
}
#define LV_STYLE_CONST_BG_GRAD_DIR(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BG_GRAD_DIR, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_BG_MAIN_STOP(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BG_MAIN_STOP, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_BG_GRAD_STOP(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BG_GRAD_STOP, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_BG_GRAD(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BG_GRAD, .value = { .ptr = val } \
}
#define LV_STYLE_CONST_BG_DITHER_MODE(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BG_DITHER_MODE, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_BG_IMG_SRC(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BG_IMG_SRC, .value = { .ptr = val } \
}
#define LV_STYLE_CONST_BG_IMG_OPA(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BG_IMG_OPA, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_BG_IMG_RECOLOR(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BG_IMG_RECOLOR, .value = { .color = val } \
}
#define LV_STYLE_CONST_BG_IMG_RECOLOR_OPA(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BG_IMG_RECOLOR_OPA, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_BG_IMG_TILED(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BG_IMG_TILED, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_BORDER_COLOR(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BORDER_COLOR, .value = { .color = val } \
}
#define LV_STYLE_CONST_BORDER_OPA(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BORDER_OPA, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_BORDER_WIDTH(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BORDER_WIDTH, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_BORDER_SIDE(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BORDER_SIDE, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_BORDER_POST(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BORDER_POST, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_OUTLINE_WIDTH(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_OUTLINE_WIDTH, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_OUTLINE_COLOR(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_OUTLINE_COLOR, .value = { .color = val } \
}
#define LV_STYLE_CONST_OUTLINE_OPA(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_OUTLINE_OPA, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_OUTLINE_PAD(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_OUTLINE_PAD, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_SHADOW_WIDTH(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_SHADOW_WIDTH, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_SHADOW_OFS_X(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_SHADOW_OFS_X, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_SHADOW_OFS_Y(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_SHADOW_OFS_Y, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_SHADOW_SPREAD(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_SHADOW_SPREAD, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_SHADOW_COLOR(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_SHADOW_COLOR, .value = { .color = val } \
}
#define LV_STYLE_CONST_SHADOW_OPA(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_SHADOW_OPA, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_IMG_OPA(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_IMG_OPA, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_IMG_RECOLOR(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_IMG_RECOLOR, .value = { .color = val } \
}
#define LV_STYLE_CONST_IMG_RECOLOR_OPA(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_IMG_RECOLOR_OPA, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_LINE_WIDTH(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_LINE_WIDTH, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_LINE_DASH_WIDTH(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_LINE_DASH_WIDTH, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_LINE_DASH_GAP(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_LINE_DASH_GAP, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_LINE_ROUNDED(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_LINE_ROUNDED, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_LINE_COLOR(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_LINE_COLOR, .value = { .color = val } \
}
#define LV_STYLE_CONST_LINE_OPA(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_LINE_OPA, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_ARC_WIDTH(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_ARC_WIDTH, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_ARC_ROUNDED(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_ARC_ROUNDED, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_ARC_COLOR(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_ARC_COLOR, .value = { .color = val } \
}
#define LV_STYLE_CONST_ARC_OPA(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_ARC_OPA, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_ARC_IMG_SRC(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_ARC_IMG_SRC, .value = { .ptr = val } \
}
#define LV_STYLE_CONST_TEXT_COLOR(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TEXT_COLOR, .value = { .color = val } \
}
#define LV_STYLE_CONST_TEXT_OPA(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TEXT_OPA, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_TEXT_FONT(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TEXT_FONT, .value = { .ptr = val } \
}
#define LV_STYLE_CONST_TEXT_LETTER_SPACE(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TEXT_LETTER_SPACE, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_TEXT_LINE_SPACE(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TEXT_LINE_SPACE, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_TEXT_DECOR(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TEXT_DECOR, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_TEXT_ALIGN(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TEXT_ALIGN, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_RADIUS(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_RADIUS, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_CLIP_CORNER(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_CLIP_CORNER, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_OPA(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_OPA, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_OPA_LAYERED(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_OPA_LAYERED, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_COLOR_FILTER_DSC(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_COLOR_FILTER_DSC, .value = { .ptr = val } \
}
#define LV_STYLE_CONST_COLOR_FILTER_OPA(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_COLOR_FILTER_OPA, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_ANIM(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_ANIM, .value = { .ptr = val } \
}
#define LV_STYLE_CONST_ANIM_TIME(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_ANIM_TIME, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_ANIM_SPEED(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_ANIM_SPEED, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_TRANSITION(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_TRANSITION, .value = { .ptr = val } \
}
#define LV_STYLE_CONST_BLEND_MODE(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BLEND_MODE, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_LAYOUT(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_LAYOUT, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_BASE_DIR(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_BASE_DIR, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_FLEX_FLOW(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_FLEX_FLOW, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_FLEX_MAIN_PLACE(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_FLEX_MAIN_PLACE, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_FLEX_CROSS_PLACE(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_FLEX_CROSS_PLACE, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_FLEX_TRACK_PLACE(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_FLEX_TRACK_PLACE, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_FLEX_GROW(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_FLEX_GROW, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_GRID_COLUMN_DSC_ARRAY(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_GRID_COLUMN_DSC_ARRAY, .value = { .ptr = val } \
}
#define LV_STYLE_CONST_GRID_COLUMN_ALIGN(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_GRID_COLUMN_ALIGN, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_GRID_ROW_DSC_ARRAY(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_GRID_ROW_DSC_ARRAY, .value = { .ptr = val } \
}
#define LV_STYLE_CONST_GRID_ROW_ALIGN(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_GRID_ROW_ALIGN, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_GRID_CELL_COLUMN_POS(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_GRID_CELL_COLUMN_POS, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_GRID_CELL_X_ALIGN(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_GRID_CELL_X_ALIGN, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_GRID_CELL_COLUMN_SPAN(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_GRID_CELL_COLUMN_SPAN, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_GRID_CELL_ROW_POS(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_GRID_CELL_ROW_POS, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_GRID_CELL_Y_ALIGN(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_GRID_CELL_Y_ALIGN, .value = { .num = (int32_t)val } \
}
#define LV_STYLE_CONST_GRID_CELL_ROW_SPAN(val) \
{ \
.prop_ptr = &_lv_style_const_prop_id_GRID_CELL_ROW_SPAN, .value = { .num = (int32_t)val } \
}
#endif /* LV_STYLE_GEN_H */
|
2db4f7e4d57f0de3b39cd0fbc605972583dae666
|
c2634ebec1d4448e372d174f459c3cbc03fd1edc
|
/lib/node_modules/@stdlib/ndarray/base/unary/include/stdlib/ndarray/base/unary/s_s.h
|
3c221d6ccca10bfed93251432854fc3f7733cf51
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"SunPro",
"BSD-3-Clause",
"BSL-1.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
stdlib-js/stdlib
|
ede11aee78f08e4f78a0bb939cb0bc244850b55b
|
f10c6e7db1a2b15cdd2b6237dd0927466ebd7278
|
refs/heads/develop
| 2023-09-05T03:29:36.368208
| 2023-09-03T22:42:11
| 2023-09-03T22:42:11
| 54,614,238
| 4,163
| 230
|
Apache-2.0
| 2023-09-13T21:26:07
| 2016-03-24T04:19:52
|
JavaScript
|
UTF-8
|
C
| false
| false
| 5,758
|
h
|
s_s.h
|
/**
* @license Apache-2.0
*
* Copyright (c) 2023 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* The following is auto-generated. Do not manually edit. See scripts/loops.js.
*/
#ifndef STDLIB_NDARRAY_BASE_UNARY_S_S_H
#define STDLIB_NDARRAY_BASE_UNARY_S_S_H
#include "stdlib/ndarray/ctor.h"
#include <stdint.h>
/*
* If C++, prevent name mangling so that the compiler emits a binary file having undecorated names, thus mirroring the behavior of a C compiler.
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* Applies a unary callback to an input ndarray and assigns results to elements in an output ndarray.
*/
int8_t stdlib_ndarray_s_s( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a zero-dimensional input ndarray and assigns results to elements in a zero-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_0d( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a one-dimensional input ndarray and assigns results to elements in a one-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_1d( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a two-dimensional input ndarray and assigns results to elements in a two-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_2d( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a two-dimensional input ndarray and assigns results to elements in a two-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_2d_blocked( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a three-dimensional input ndarray and assigns results to elements in a three-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_3d( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a three-dimensional input ndarray and assigns results to elements in a three-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_3d_blocked( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a four-dimensional input ndarray and assigns results to elements in a four-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_4d( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a four-dimensional input ndarray and assigns results to elements in a four-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_4d_blocked( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a five-dimensional input ndarray and assigns results to elements in a five-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_5d( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a five-dimensional input ndarray and assigns results to elements in a five-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_5d_blocked( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a six-dimensional input ndarray and assigns results to elements in a six-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_6d( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a six-dimensional input ndarray and assigns results to elements in a six-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_6d_blocked( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a seven-dimensional input ndarray and assigns results to elements in a seven-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_7d( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a seven-dimensional input ndarray and assigns results to elements in a seven-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_7d_blocked( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to an eight-dimensional input ndarray and assigns results to elements in an eight-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_8d( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to an eight-dimensional input ndarray and assigns results to elements in an eight-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_8d_blocked( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a nine-dimensional input ndarray and assigns results to elements in a nine-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_9d( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a nine-dimensional input ndarray and assigns results to elements in a nine-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_9d_blocked( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a ten-dimensional input ndarray and assigns results to elements in a ten-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_10d( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to a ten-dimensional input ndarray and assigns results to elements in a ten-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_10d_blocked( struct ndarray *arrays[], void *fcn );
/**
* Applies a unary callback to an n-dimensional input ndarray and assigns results to elements in an n-dimensional output ndarray.
*/
int8_t stdlib_ndarray_s_s_nd( struct ndarray *arrays[], void *fcn );
#ifdef __cplusplus
}
#endif
#endif // !STDLIB_NDARRAY_BASE_UNARY_S_S_H
|
587a43013775ad11d090a0aa607b9c28050caac2
|
19102a3c11268052348cf669e23bbfe2780bb067
|
/MinecraftC/GameSettings.c
|
5f747b351dbc22a3ed3b3aa18bcd6772b1909b3e
|
[
"MIT"
] |
permissive
|
johnpayne-dev/MinecraftC
|
4f6578fd12c0ff8b70e8b9d2c11c4934a822203c
|
43928d42e1f32bd76a994f0bb22c0153a7271b3f
|
refs/heads/main
| 2023-08-04T00:51:16.467779
| 2022-07-31T18:45:33
| 2022-07-31T18:45:33
| 338,597,768
| 303
| 31
|
MIT
| 2022-07-31T18:45:34
| 2021-02-13T14:55:07
|
C
|
UTF-8
|
C
| false
| false
| 10,340
|
c
|
GameSettings.c
|
#include <string.h>
#include <cute_sound.h>
#include "GameSettings.h"
#include "Minecraft.h"
#include "Utilities/Log.h"
#include "Mods/Raytracer.h"
static void Load(GameSettings * settings) {
SDL_RWops * file = SDL_RWFromFile(settings->file, "r");
if (file == NULL) {
return;
}
int size = (int)SDL_RWsize(file);
char * text = malloc(size);
SDL_RWread(file, text, size, 1);
for (int i = 0, j = -1; i < size; i++) {
if (text[i] == '\n') {
String line = StringSub(StringCreate(text), j + 1, i - 1);
j = i;
int split = StringIndexOf(line, ':');
if (split <= 0) { continue; }
String value = StringSub(StringCreate(line), split + 1, StringLength(line) - 1);
line = StringSub(line, 0, split - 1);
if (strcmp(line, "music") == 0) { settings->music = strcmp(value, "true") == 0; }
if (strcmp(line, "sound") == 0) { settings->sound = strcmp(value, "true") == 0; }
if (strcmp(line, "invertYMouse") == 0) { settings->invertMouse = strcmp(value, "true") == 0; }
if (strcmp(line, "showFrameRate") == 0) { settings->showFrameRate = strcmp(value, "true") == 0; }
if (strcmp(line, "viewDistance") == 0) { settings->viewDistance = StringToInt(value); }
if (strcmp(line, "bobView") == 0) { settings->viewBobbing = strcmp(value, "true") == 0; }
if (strcmp(line, "anaglyph3d") == 0) { settings->anaglyph = strcmp(value, "true") == 0; }
if (strcmp(line, "limitFramerate") == 0) { settings->limitFramerate = strcmp(value, "true") == 0; }
for (int i = 0; i < ListLength(settings->bindings); i++) {
String keyName = StringCreate(settings->bindings[i]->name);
StringConcatFront("key_", &keyName);
if (strcmp(line, keyName) == 0) { settings->bindings[i]->key = StringToInt(value); }
StringFree(keyName);
}
#if MINECRAFTC_MODS
if (strcmp(line, "explodingTNT") == 0) { settings->explodingTNT = strcmp(value, "true") == 0; }
if (strcmp(line, "raytracing") == 0) { settings->raytracing = strcmp(value, "true") == 0; }
if (strcmp(line, "largerWorldGen") == 0) { settings->largerWorldGen = strcmp(value, "true") == 0; }
#endif
StringFree(value);
StringFree(line);
}
}
free(text);
SDL_RWclose(file);
}
static void Save(GameSettings * settings) {
SDL_RWops * file = SDL_RWFromFile(settings->file, "w");
if (file == NULL) {
LogWarning("Failed to save options: %s\n", SDL_GetError());
return;
}
String line = StringCreate("");
StringSet(&line, settings->music ? "true\n" : "false\n");
StringConcatFront("music:", &line);
SDL_RWwrite(file, line, StringLength(line), 1);
StringSet(&line, settings->sound ? "true\n" : "false\n");
StringConcatFront("sound:", &line);
SDL_RWwrite(file, line, StringLength(line), 1);
StringSet(&line, settings->invertMouse ? "true\n" : "false\n");
StringConcatFront("invertYMouse:", &line);
SDL_RWwrite(file, line, StringLength(line), 1);
StringSet(&line, settings->invertMouse ? "true\n" : "false\n");
StringConcatFront("invertYMouse:", &line);
SDL_RWwrite(file, line, StringLength(line), 1);
StringSet(&line, settings->showFrameRate ? "true\n" : "false\n");
StringConcatFront("showFrameRate:", &line);
SDL_RWwrite(file, line, StringLength(line), 1);
StringSetFromInt(&line, settings->viewDistance);
StringConcatFront("viewDistance:", &line);
StringConcat(&line, "\n");
SDL_RWwrite(file, line, StringLength(line), 1);
StringSet(&line, settings->viewBobbing ? "true\n" : "false\n");
StringConcatFront("bobView:", &line);
SDL_RWwrite(file, line, StringLength(line), 1);
StringSet(&line, settings->anaglyph ? "true\n" : "false\n");
StringConcatFront("anaglyph3d:", &line);
SDL_RWwrite(file, line, StringLength(line), 1);
StringSet(&line, settings->limitFramerate ? "true\n" : "false\n");
StringConcatFront("limitFramerate:", &line);
SDL_RWwrite(file, line, StringLength(line), 1);
for (int i = 0; i < ListLength(settings->bindings); i++) {
String keyName = StringCreate(settings->bindings[i]->name);
StringConcatFront("key_", &keyName);
StringConcat(&keyName, ":");
StringSetFromInt(&line, settings->bindings[i]->key);
StringConcatFront(keyName, &line);
StringConcat(&line, "\n");
SDL_RWwrite(file, line, StringLength(line), 1);
StringFree(keyName);
}
#if MINECRAFTC_MODS
StringSet(&line, settings->explodingTNT ? "true\n" : "false\n");
StringConcatFront("explodingTNT:", &line);
SDL_RWwrite(file, line, StringLength(line), 1);
StringSet(&line, settings->raytracing ? "true\n" : "false\n");
StringConcatFront("raytracing:", &line);
SDL_RWwrite(file, line, StringLength(line), 1);
StringSet(&line, settings->largerWorldGen ? "true\n" : "false\n");
StringConcatFront("largerWorldGen:", &line);
SDL_RWwrite(file, line, StringLength(line), 1);
#endif
StringFree(line);
SDL_RWclose(file);
}
void GameSettingsCreate(GameSettings * settings, Minecraft * minecraft) {
*settings = (GameSettings) {
.music = true,
.sound = true,
.invertMouse = false,
.showFrameRate = false,
.viewDistance = 0,
.viewBobbing = true,
.anaglyph = false,
.limitFramerate = false,
.forwardKey = (KeyBinding){ .name = "Forward", .key = SDL_SCANCODE_W },
.leftKey = (KeyBinding){ .name = "Left", .key = SDL_SCANCODE_A },
.backKey = (KeyBinding){ .name = "Back", .key = SDL_SCANCODE_S },
.rightKey = (KeyBinding){ .name = "Right", .key = SDL_SCANCODE_D },
.jumpKey = (KeyBinding){ .name = "Jump", .key = SDL_SCANCODE_SPACE },
.buildKey = (KeyBinding){ .name = "Build", .key = SDL_SCANCODE_B },
.chatKey = (KeyBinding){ .name = "Chat", .key = SDL_SCANCODE_T },
.toggleFogKey = (KeyBinding){ .name = "Toggle fog", .key = SDL_SCANCODE_F },
.saveLocationKey = (KeyBinding){ .name = "Save location", .key = SDL_SCANCODE_RETURN },
.loadLocationKey = (KeyBinding){ .name = "Load location", .key = SDL_SCANCODE_R },
.bindings = ListCreate(sizeof(KeyBinding *)),
.settingsCount = 8,
#if MINECRAFTC_MODS
.modsCount = 3,
#endif
.minecraft = minecraft,
};
settings->file = StringCreate(minecraft->workingDirectory);
StringConcat(&settings->file, "Options.txt");
KeyBinding * bindings[] = { &settings->forwardKey, &settings->leftKey, &settings->backKey, &settings->rightKey, &settings->jumpKey, &settings->buildKey, &settings->chatKey, &settings->toggleFogKey, &settings->saveLocationKey, &settings->loadLocationKey };
for (int i = 0; i < sizeof(bindings) / sizeof(bindings[0]); i++) { settings->bindings = ListPush(settings->bindings, &bindings[i]); }
Load(settings);
}
String GameSettingsGetBinding(GameSettings * settings, int binding) {
String string = StringCreate(settings->bindings[binding]->name);
StringConcat(&string, ": ");
StringConcat(&string, (char *)SDL_GetKeyName(SDL_SCANCODE_TO_KEYCODE(settings->bindings[binding]->key)));
return string;
}
void GameSettingsSetBinding(GameSettings * settings, int binding, int key) {
settings->bindings[binding]->key = key;
Save(settings);
}
void GameSettingsToggleSetting(GameSettings * settings, int setting) {
if (setting == 0) {
settings->music = !settings->music;
cs_music_set_volume((float)settings->music);
}
if (setting == 1) { settings->sound = !settings->sound; }
if (setting == 2) { settings->invertMouse = !settings->invertMouse; }
if (setting == 3) { settings->showFrameRate = !settings->showFrameRate; }
if (setting == 4) { settings->viewDistance = (settings->viewDistance + 1) % 4; }
if (setting == 5) { settings->viewBobbing = !settings->viewBobbing; }
if (setting == 6) {
settings->anaglyph = !settings->anaglyph;
TextureManagerReload(&settings->minecraft->textureManager);
settings->minecraft->font.texture = TextureManagerLoad(&settings->minecraft->textureManager, settings->minecraft->font.textureName);
}
if (setting == 7) {
settings->limitFramerate = !settings->limitFramerate;
SDL_GL_SetSwapInterval(settings->limitFramerate ? 1 : 0);
}
#if MINECRAFTC_MODS
if (setting == 8) { settings->explodingTNT = !settings->explodingTNT; }
if (setting == 9) {
settings->raytracing = !settings->raytracing;
if (settings->raytracing) {
LevelCreateDistanceField(&settings->minecraft->level);
if (!RaytracerInitialize(&settings->minecraft->textureManager, &settings->minecraft->level, settings->minecraft->frameWidth, settings->minecraft->frameHeight)) {
settings->raytracing = false;
LevelDestroyDistanceField(&settings->minecraft->level);
}
} else {
LevelDestroyDistanceField(&settings->minecraft->level);
RaytracerDestroy();
}
}
if (setting == 10) { settings->largerWorldGen = !settings->largerWorldGen; }
#endif
Save(settings);
}
static char * RenderDistances[] = { "FAR", "NORMAL", "SHORT", "TINY" };
String GameSettingsGetSetting(GameSettings * settings, int setting) {
String string;
switch (setting) {
case 0:
string = StringCreate("Music: ");
StringConcat(&string, settings->music ? "ON" : "OFF");
break;
case 1:
string = StringCreate("Sound: ");
StringConcat(&string, settings->sound ? "ON" : "OFF");
break;
case 2:
string = StringCreate("Invert mouse: ");
StringConcat(&string, settings->invertMouse ? "ON" : "OFF");
break;
case 3:
string = StringCreate("Show FPS: ");
StringConcat(&string, settings->showFrameRate ? "ON" : "OFF");
break;
case 4:
string = StringCreate("Render distance: ");
StringConcat(&string, RenderDistances[settings->viewDistance]);
break;
case 5:
string = StringCreate("View bobbing: ");
StringConcat(&string, settings->viewBobbing ? "ON" : "OFF");
break;
case 6:
string = StringCreate("3d anaglyph: ");
StringConcat(&string, settings->anaglyph ? "ON" : "OFF");
break;
case 7:
string = StringCreate("Limit framerate: ");
StringConcat(&string, settings->limitFramerate ? "ON" : "OFF");
break;
#if MINECRAFTC_MODS
case 8:
string = StringCreate("Exploding TNT: ");
StringConcat(&string, settings->explodingTNT ? "ON" : "OFF");
break;
case 9:
string = StringCreate("Raytracing: ");
StringConcat(&string, settings->raytracing ? "ON" : "OFF");
break;
case 10:
string = StringCreate("Larger world gen: ");
StringConcat(&string, settings->largerWorldGen ? "ON" : "OFF");
break;
#endif
default:
string = StringCreate("Error");
break;
}
return string;
}
void GameSettingsDestroy(GameSettings * settings) {
StringFree(settings->file);
ListFree(settings->bindings);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.