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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7d99246a0ded115b270949db34503897c93d9555
|
1782b2a608d4336b018f30f4d2c619a84afe99db
|
/DSihax_legacy/rop_payload/rop_gadgets.h
|
37b30d37d9d199f47f545f095bd76f82f2e22cd0
|
[
"MIT"
] |
permissive
|
zoogie/Bannerbomb3
|
e60636ad9bf63909e660e1fe47d9addc2401ecab
|
785231079bd0a7a72c973c309d5fb5ddd8123c88
|
refs/heads/master
| 2023-05-25T14:11:58.244332
| 2023-05-23T07:47:09
| 2023-05-23T07:47:09
| 198,808,647
| 121
| 13
|
MIT
| 2022-10-15T06:00:42
| 2019-07-25T10:15:52
|
C
|
UTF-8
|
C
| false
| false
| 994
|
h
|
rop_gadgets.h
|
#define TID_H 0x00048005
#define DLP 0x484E4441
#define INT 0x42383841
#define WBUFF 0x00681000
#define ENTRY 0x0ffffe48
#define POP_R0PC 0x00146760
#define POP_R1PC 0x001d53f8
#define POP_R2PC 0x00207d31
#define POP_R3PC 0x0010d44c
#define POP_R4R8PC 0x0010d20c
#define ROP_POPR3_ADDSPR3_POPPC 0x0014660c + 4
#define STACK_PIVOT ROP_POPR3_ADDSPR3_POPPC
#define PIVOT_OFFSET -0x110
#define ROP_MOV_R3_R6_BLX_ADDRR5 0x001264AC
#define ROP_STR_R12R0 0x0010df64
#define ROP_MOV_R1_0 0x0019DFB4 @sp!,{ r4 pc }
#define ROP_MOV_R3_4_JUNKTOR0 0x001317A4 @ LDMFD SP!, {R4-R8,PC}
#define ROP_MOV_R2_4_BLX_R3 0x00104bbc
#define svcSleepThread 0x001bdbd0
#define STR_YS 0x0028cb60
#define GARBAGE 0xADDEADDE
#define NULL 0
#define GSPGPU_SERVHANDLEADR 0x002993c4
#define GSPGPU_WriteHWRegs 0x00136200 @sp!,{ r4 pc }
#define GSPGPU_SetLcdForceBlack 0x001c13a4 @sp!,{ r4-r6 pc }
#define MAGENTA_ADDR 0x002A800C
#define HWREGS_ADDR 0x00202A04
#define AM_TwlExport 0x00156d28 + 0x10
|
b12617271b7beb28795912b171235ca06f64c944
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/arch/openrisc/kernel/setup.c
|
f4d5bedc3b4f72bc92a939d0cb84b71215fbd929
|
[
"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
| 10,178
|
c
|
setup.c
|
/*
* OpenRISC setup.c
*
* Linux architectural port borrowing liberally from similar works of
* others. All original copyrights apply as per the original source
* declaration.
*
* Modifications for the OpenRISC architecture:
* Copyright (C) 2003 Matjaz Breskvar <phoenix@bsemi.com>
* Copyright (C) 2010-2011 Jonas Bonn <jonas@southpole.se>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* This file handles the architecture-dependent parts of initialization
*/
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/stddef.h>
#include <linux/unistd.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/console.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/seq_file.h>
#include <linux/serial.h>
#include <linux/initrd.h>
#include <linux/of_fdt.h>
#include <linux/of.h>
#include <linux/memblock.h>
#include <linux/device.h>
#include <linux/of_platform.h>
#include <asm/segment.h>
#include <asm/pgtable.h>
#include <asm/types.h>
#include <asm/setup.h>
#include <asm/io.h>
#include <asm/cpuinfo.h>
#include <asm/delay.h>
#include "vmlinux.h"
char __initdata cmd_line[COMMAND_LINE_SIZE] = CONFIG_CMDLINE;
static unsigned long __init setup_memory(void)
{
unsigned long bootmap_size;
unsigned long ram_start_pfn;
unsigned long free_ram_start_pfn;
unsigned long ram_end_pfn;
phys_addr_t memory_start, memory_end;
struct memblock_region *region;
memory_end = memory_start = 0;
/* Find main memory where is the kernel */
for_each_memblock(memory, region) {
memory_start = region->base;
memory_end = region->base + region->size;
printk(KERN_INFO "%s: Memory: 0x%x-0x%x\n", __func__,
memory_start, memory_end);
}
if (!memory_end) {
panic("No memory!");
}
ram_start_pfn = PFN_UP(memory_start);
/* free_ram_start_pfn is first page after kernel */
free_ram_start_pfn = PFN_UP(__pa(&_end));
ram_end_pfn = PFN_DOWN(memblock_end_of_DRAM());
max_pfn = ram_end_pfn;
/*
* initialize the boot-time allocator (with low memory only).
*
* This makes the memory from the end of the kernel to the end of
* RAM usable.
* init_bootmem sets the global values min_low_pfn, max_low_pfn.
*/
bootmap_size = init_bootmem(free_ram_start_pfn,
ram_end_pfn - ram_start_pfn);
free_bootmem(PFN_PHYS(free_ram_start_pfn),
(ram_end_pfn - free_ram_start_pfn) << PAGE_SHIFT);
reserve_bootmem(PFN_PHYS(free_ram_start_pfn), bootmap_size,
BOOTMEM_DEFAULT);
for_each_memblock(reserved, region) {
printk(KERN_INFO "Reserved - 0x%08x-0x%08x\n",
(u32) region->base, (u32) region->size);
reserve_bootmem(region->base, region->size, BOOTMEM_DEFAULT);
}
return ram_end_pfn;
}
struct cpuinfo cpuinfo;
static void print_cpuinfo(void)
{
unsigned long upr = mfspr(SPR_UPR);
unsigned long vr = mfspr(SPR_VR);
unsigned int version;
unsigned int revision;
version = (vr & SPR_VR_VER) >> 24;
revision = (vr & SPR_VR_REV);
printk(KERN_INFO "CPU: OpenRISC-%x (revision %d) @%d MHz\n",
version, revision, cpuinfo.clock_frequency / 1000000);
if (!(upr & SPR_UPR_UP)) {
printk(KERN_INFO
"-- no UPR register... unable to detect configuration\n");
return;
}
if (upr & SPR_UPR_DCP)
printk(KERN_INFO
"-- dcache: %4d bytes total, %2d bytes/line, %d way(s)\n",
cpuinfo.dcache_size, cpuinfo.dcache_block_size, 1);
else
printk(KERN_INFO "-- dcache disabled\n");
if (upr & SPR_UPR_ICP)
printk(KERN_INFO
"-- icache: %4d bytes total, %2d bytes/line, %d way(s)\n",
cpuinfo.icache_size, cpuinfo.icache_block_size, 1);
else
printk(KERN_INFO "-- icache disabled\n");
if (upr & SPR_UPR_DMP)
printk(KERN_INFO "-- dmmu: %4d entries, %lu way(s)\n",
1 << ((mfspr(SPR_DMMUCFGR) & SPR_DMMUCFGR_NTS) >> 2),
1 + (mfspr(SPR_DMMUCFGR) & SPR_DMMUCFGR_NTW));
if (upr & SPR_UPR_IMP)
printk(KERN_INFO "-- immu: %4d entries, %lu way(s)\n",
1 << ((mfspr(SPR_IMMUCFGR) & SPR_IMMUCFGR_NTS) >> 2),
1 + (mfspr(SPR_IMMUCFGR) & SPR_IMMUCFGR_NTW));
printk(KERN_INFO "-- additional features:\n");
if (upr & SPR_UPR_DUP)
printk(KERN_INFO "-- debug unit\n");
if (upr & SPR_UPR_PCUP)
printk(KERN_INFO "-- performance counters\n");
if (upr & SPR_UPR_PMP)
printk(KERN_INFO "-- power management\n");
if (upr & SPR_UPR_PICP)
printk(KERN_INFO "-- PIC\n");
if (upr & SPR_UPR_TTP)
printk(KERN_INFO "-- timer\n");
if (upr & SPR_UPR_CUP)
printk(KERN_INFO "-- custom unit(s)\n");
}
void __init setup_cpuinfo(void)
{
struct device_node *cpu;
unsigned long iccfgr, dccfgr;
unsigned long cache_set_size, cache_ways;
cpu = of_find_compatible_node(NULL, NULL, "opencores,or1200-rtlsvn481");
if (!cpu)
panic("No compatible CPU found in device tree...\n");
iccfgr = mfspr(SPR_ICCFGR);
cache_ways = 1 << (iccfgr & SPR_ICCFGR_NCW);
cache_set_size = 1 << ((iccfgr & SPR_ICCFGR_NCS) >> 3);
cpuinfo.icache_block_size = 16 << ((iccfgr & SPR_ICCFGR_CBS) >> 7);
cpuinfo.icache_size =
cache_set_size * cache_ways * cpuinfo.icache_block_size;
dccfgr = mfspr(SPR_DCCFGR);
cache_ways = 1 << (dccfgr & SPR_DCCFGR_NCW);
cache_set_size = 1 << ((dccfgr & SPR_DCCFGR_NCS) >> 3);
cpuinfo.dcache_block_size = 16 << ((dccfgr & SPR_DCCFGR_CBS) >> 7);
cpuinfo.dcache_size =
cache_set_size * cache_ways * cpuinfo.dcache_block_size;
if (of_property_read_u32(cpu, "clock-frequency",
&cpuinfo.clock_frequency)) {
printk(KERN_WARNING
"Device tree missing CPU 'clock-frequency' parameter."
"Assuming frequency 25MHZ"
"This is probably not what you want.");
}
of_node_put(cpu);
print_cpuinfo();
}
/**
* or32_early_setup
*
* Handles the pointer to the device tree that this kernel is to use
* for establishing the available platform devices.
*
* Falls back on built-in device tree in case null pointer is passed.
*/
void __init or32_early_setup(unsigned int fdt)
{
if (fdt) {
early_init_devtree((void*) fdt);
printk(KERN_INFO "FDT at 0x%08x\n", fdt);
} else {
early_init_devtree(__dtb_start);
printk(KERN_INFO "Compiled-in FDT at %p\n", __dtb_start);
}
}
static int __init openrisc_device_probe(void)
{
of_platform_populate(NULL, NULL, NULL, NULL);
return 0;
}
device_initcall(openrisc_device_probe);
static inline unsigned long extract_value_bits(unsigned long reg,
short bit_nr, short width)
{
return (reg >> bit_nr) & (0 << width);
}
static inline unsigned long extract_value(unsigned long reg, unsigned long mask)
{
while (!(mask & 0x1)) {
reg = reg >> 1;
mask = mask >> 1;
}
return mask & reg;
}
void __init detect_unit_config(unsigned long upr, unsigned long mask,
char *text, void (*func) (void))
{
if (text != NULL)
printk("%s", text);
if (upr & mask) {
if (func != NULL)
func();
else
printk("present\n");
} else
printk("not present\n");
}
/*
* calibrate_delay
*
* Lightweight calibrate_delay implementation that calculates loops_per_jiffy
* from the clock frequency passed in via the device tree
*
*/
void __cpuinit calibrate_delay(void)
{
const int *val;
struct device_node *cpu = NULL;
cpu = of_find_compatible_node(NULL, NULL, "opencores,or1200-rtlsvn481");
val = of_get_property(cpu, "clock-frequency", NULL);
if (!val)
panic("no cpu 'clock-frequency' parameter in device tree");
loops_per_jiffy = *val / HZ;
pr_cont("%lu.%02lu BogoMIPS (lpj=%lu)\n",
loops_per_jiffy / (500000 / HZ),
(loops_per_jiffy / (5000 / HZ)) % 100, loops_per_jiffy);
}
void __init setup_arch(char **cmdline_p)
{
unsigned long max_low_pfn;
unflatten_device_tree();
setup_cpuinfo();
/* process 1's initial memory region is the kernel code/data */
init_mm.start_code = (unsigned long)&_stext;
init_mm.end_code = (unsigned long)&_etext;
init_mm.end_data = (unsigned long)&_edata;
init_mm.brk = (unsigned long)&_end;
#ifdef CONFIG_BLK_DEV_INITRD
initrd_start = (unsigned long)&__initrd_start;
initrd_end = (unsigned long)&__initrd_end;
if (initrd_start == initrd_end) {
initrd_start = 0;
initrd_end = 0;
}
initrd_below_start_ok = 1;
#endif
/* setup bootmem allocator */
max_low_pfn = setup_memory();
/* paging_init() sets up the MMU and marks all pages as reserved */
paging_init();
#if defined(CONFIG_VT) && defined(CONFIG_DUMMY_CONSOLE)
if (!conswitchp)
conswitchp = &dummy_con;
#endif
*cmdline_p = cmd_line;
printk(KERN_INFO "OpenRISC Linux -- http://openrisc.net\n");
}
static int show_cpuinfo(struct seq_file *m, void *v)
{
unsigned long vr;
int version, revision;
vr = mfspr(SPR_VR);
version = (vr & SPR_VR_VER) >> 24;
revision = vr & SPR_VR_REV;
return seq_printf(m,
"cpu\t\t: OpenRISC-%x\n"
"revision\t: %d\n"
"frequency\t: %ld\n"
"dcache size\t: %d bytes\n"
"dcache block size\t: %d bytes\n"
"icache size\t: %d bytes\n"
"icache block size\t: %d bytes\n"
"immu\t\t: %d entries, %lu ways\n"
"dmmu\t\t: %d entries, %lu ways\n"
"bogomips\t: %lu.%02lu\n",
version,
revision,
loops_per_jiffy * HZ,
cpuinfo.dcache_size,
cpuinfo.dcache_block_size,
cpuinfo.icache_size,
cpuinfo.icache_block_size,
1 << ((mfspr(SPR_DMMUCFGR) & SPR_DMMUCFGR_NTS) >> 2),
1 + (mfspr(SPR_DMMUCFGR) & SPR_DMMUCFGR_NTW),
1 << ((mfspr(SPR_IMMUCFGR) & SPR_IMMUCFGR_NTS) >> 2),
1 + (mfspr(SPR_IMMUCFGR) & SPR_IMMUCFGR_NTW),
(loops_per_jiffy * HZ) / 500000,
((loops_per_jiffy * HZ) / 5000) % 100);
}
static void *c_start(struct seq_file *m, loff_t * pos)
{
/* We only have one CPU... */
return *pos < 1 ? (void *)1 : NULL;
}
static void *c_next(struct seq_file *m, void *v, loff_t * pos)
{
++*pos;
return NULL;
}
static void c_stop(struct seq_file *m, void *v)
{
}
const struct seq_operations cpuinfo_op = {
.start = c_start,
.next = c_next,
.stop = c_stop,
.show = show_cpuinfo,
};
|
1c5bde3443df8e1d20ea2aca83e5de57ffb35281
|
ec6a71b57ebe88538269197fd16bede6bc2062ae
|
/erts/emulator/sys/win32/erl_win_sys.h
|
a7b1f7ac95833a0ca2943dbead5eebfef72892ae
|
[
"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
| 8,232
|
h
|
erl_win_sys.h
|
/*
* %CopyrightBegin%
*
* Copyright Ericsson AB 1997-2022. 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%
*/
/*
* This file handles differences between operating systems.
* This should be the only place with conditional compilation
* depending on the type of OS.
*/
#ifndef _ERL_WIN_SYS_H
#define _ERL_WIN_SYS_H
#define HAS_STDARG
#ifdef __GNUC__
#ifdef pid_t
/* Really... */
#undef pid_t
#endif
#endif
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <limits.h>
#include <process.h>
#include <malloc.h>
#ifndef __GNUC__
#include <direct.h>
#endif
#include "erl_errno.h"
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <sys/timeb.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
#ifndef MAXPATHLEN
#define MAXPATHLEN 4096
/*
erts-6.0 (OTP 17.0):
We now accept windows paths longer than 260 (MAX_PATH) by conversion to
UNC path format. In order to also return long paths from the driver we
increased MAXPATHLEN from 260 to larger (but arbitrary) value 4096.
It would of course be nicer to instead dynamically allocate large enough
tmp buffers when efile_drv needs to return really long paths, and do that
for unix as well.
*/
#endif /* MAXPATHLEN */
/*
* Various configuration options, used to be in the Makefile.
*/
#define NO_ASINH
#define NO_ACOSH
#define NO_ATANH
#define NO_ERF
#define NO_ERFC
#define NO_SYSCONF
#define NO_DAEMON
#define NO_PWD
#define strncasecmp _strnicmp
#ifndef __GNUC__
# undef ERTS_I64_LITERAL
# define ERTS_I64_LITERAL(X) X##i64
#endif
#define ERTS_HAVE_ERTS_SYS_ALIGNED_ALLOC 1
/*
* Practical Windows specific macros.
*/
#define CreateAutoEvent(state) CreateEvent(NULL, FALSE, state, NULL)
#define CreateManualEvent(state) CreateEvent(NULL, TRUE, state, NULL)
/*
* Min number of async threads
*/
#define ERTS_MIN_NO_OF_ASYNC_THREADS 0
/*
* Our own type of "FD's"
*/
#define ERTS_SYS_FD_INVALID INVALID_HANDLE_VALUE
#define ERTS_SYS_FD_TYPE HANDLE
#define NO_FSTAT_ON_SYS_FD_TYPE 1 /* They are events, not files */
/*
* For erl_time_sup
*/
#define SYS_CLK_TCK 1000
#define SYS_CLOCK_RESOLUTION 1
#if SIZEOF_TIME_T != 8
# error "Unexpected sizeof(time_t)"
#endif
/*
* gcc uses a 4 byte time_t and vc++ uses an 8 byte time_t.
* Types seen in beam_emu.c *need* to have the same size
* as in the rest of the system...
*/
typedef __int64 erts_time_t;
struct tm *sys_localtime_r(time_t *epochs, struct tm *ptm);
struct tm *sys_gmtime_r(time_t *epochs, struct tm *ptm);
time_t sys_mktime( struct tm *ptm);
#define gmtime_r sys_gmtime_r
#define HAVE_GMTIME_R
#define mktime sys_mktime
typedef struct {
erts_time_t tv_sec;
erts_time_t tv_usec;
} SysTimeval;
typedef struct {
clock_t tms_utime;
clock_t tms_stime;
clock_t tms_cutime;
clock_t tms_cstime;
} SysTimes;
#define HAVE_INT64 1
#if defined (__GNUC__)
typedef unsigned long long Uint64;
typedef long long Sint64;
# ifdef ULLONG_MAX
# define ERTS_UINT64_MAX ULLONG_MAX
# endif
# ifdef LLONG_MAX
# define ERTS_SINT64_MAX LLONG_MAX
# endif
# ifdef LLONG_MIN
# define ERTS_SINT64_MIN LLONG_MIN
# endif
typedef long long ErtsMonotonicTime;
typedef long long ErtsSysHrTime;
#else
typedef ULONGLONG Uint64;
typedef LONGLONG Sint64;
typedef LONGLONG ErtsMonotonicTime;
typedef LONGLONG ErtsSysHrTime;
#endif
#define ErtsStrToSint64 _strtoi64
typedef ErtsMonotonicTime ErtsSystemTime;
typedef ErtsMonotonicTime ErtsSysPerfCounter;
ErtsSystemTime erts_os_system_time(void);
#define ERTS_MONOTONIC_TIME_MIN ((ErtsMonotonicTime) (1ULL << 63))
#define ERTS_MONOTONIC_TIME_MAX (~ERTS_MONOTONIC_TIME_MIN)
#define ERTS_HAVE_OS_MONOTONIC_TIME_SUPPORT 1
#define ERTS_COMPILE_TIME_MONOTONIC_TIME_UNIT 0
struct erts_sys_time_read_only_data__ {
ErtsMonotonicTime (*os_monotonic_time)(void);
void (*os_times)(ErtsMonotonicTime *, ErtsSystemTime*);
ErtsSysHrTime (*sys_hrtime)(void);
};
typedef struct {
union {
struct erts_sys_time_read_only_data__ o;
char align__[(((sizeof(struct erts_sys_time_read_only_data__) - 1)
/ ASSUMED_CACHE_LINE_SIZE) + 1)
* ASSUMED_CACHE_LINE_SIZE];
} r;
} ErtsSysTimeData__;
extern ErtsSysTimeData__ erts_sys_time_data__;
ERTS_GLB_INLINE ErtsMonotonicTime erts_os_monotonic_time(void);
ERTS_GLB_INLINE void erts_os_times(ErtsMonotonicTime *,
ErtsSystemTime *);
ERTS_GLB_INLINE ErtsSysHrTime erts_sys_hrtime(void);
ERTS_GLB_INLINE ErtsSysPerfCounter erts_sys_perf_counter(void);
#if ERTS_GLB_INLINE_INCL_FUNC_DEF
ERTS_GLB_INLINE ErtsMonotonicTime
erts_os_monotonic_time(void)
{
return (*erts_sys_time_data__.r.o.os_monotonic_time)();
}
ERTS_GLB_INLINE void
erts_os_times(ErtsMonotonicTime *mtimep, ErtsSystemTime *stimep)
{
(*erts_sys_time_data__.r.o.os_times)(mtimep, stimep);
}
ERTS_GLB_INLINE ErtsSysHrTime
erts_sys_hrtime(void)
{
return (*erts_sys_time_data__.r.o.sys_hrtime)();
}
ERTS_GLB_INLINE ErtsSysPerfCounter
erts_sys_perf_counter(void)
{
return (*erts_sys_time_data__.r.o.sys_hrtime)();
}
ERTS_GLB_INLINE ErtsSysPerfCounter
erts_sys_perf_counter_unit(void)
{
return 1000 * 1000 * 1000;
}
#endif /* ERTS_GLB_INLINE_INCL_FUNC_DEF */
extern void sys_gettimeofday(SysTimeval *tv);
extern clock_t sys_times(SysTimes *buffer);
extern char *win_build_environment(char *);
typedef struct {
WCHAR *environment_strings;
WCHAR *next_string;
} GETENV_STATE;
void erts_sys_env_init(void);
/*
** These are to avoid irritating warnings
*/
#pragma warning(disable : 4244)
#pragma warning(disable : 4018)
/*
* Floating point support.
*/
extern volatile int erl_fp_exception;
#include <float.h>
/* I suspect this test isn't right, it might depend on the version of GCC
rather than if it's a MINGW gcc, but I haven't been able to pinpoint the
exact point where _finite was added to the headers in cygwin... */
#if defined (__GNUC__) && !defined(__MINGW32__)
int _finite(double x);
#endif
#define erts_isfinite _finite
/*#define NO_FPE_SIGNALS*/
#define erts_get_current_fp_exception() NULL
#define __ERTS_FP_CHECK_INIT(fpexnp) do {} while (0)
#define __ERTS_FP_ERROR(fpexnp, f, Action) if (!_finite(f)) { Action; } else {}
#define __ERTS_FP_ERROR_THOROUGH(fpexnp, f, Action) __ERTS_FP_ERROR(fpexnp, f, Action)
#define __ERTS_SAVE_FP_EXCEPTION(fpexnp)
#define __ERTS_RESTORE_FP_EXCEPTION(fpexnp)
#define ERTS_FP_CHECK_INIT(p) __ERTS_FP_CHECK_INIT(&(p)->fp_exception)
#define ERTS_FP_ERROR(p, f, A) __ERTS_FP_ERROR(&(p)->fp_exception, f, A)
#define ERTS_SAVE_FP_EXCEPTION(p) __ERTS_SAVE_FP_EXCEPTION(&(p)->fp_exception)
#define ERTS_RESTORE_FP_EXCEPTION(p) __ERTS_RESTORE_FP_EXCEPTION(&(p)->fp_exception)
#define ERTS_FP_ERROR_THOROUGH(p, f, A) __ERTS_FP_ERROR_THOROUGH(&(p)->fp_exception, f, A)
#define erts_sys_block_fpe() 0
#define erts_sys_unblock_fpe(x) do{}while(0)
/*
* Seems to be missing.
*/
#ifndef __GNUC__
typedef long ssize_t;
#endif
/* Threads */
int init_async(int);
int exit_async(void);
#define ERTS_HAVE_TRY_CATCH 1
#define ERTS_SYS_TRY_CATCH(EXPR,CATCH) \
__try { \
EXPR; \
} \
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) \
{ \
CATCH; \
}
#endif
|
d57a636294185a325e16f307754f18c76212e2fd
|
83372fce92c9088ee5c1e1c13bc67385a3b02a36
|
/targettest/moddiv-test.c
|
b8ea19d915d5acccf9e0a79665f77f4f7092f24b
|
[
"Zlib"
] |
permissive
|
cc65/cc65
|
2cd1b20b61ddd0691cd4601b4da37a9200a50afb
|
16e90187e8e80c6e2fcfcc04f068ac865d2290e5
|
refs/heads/master
| 2023-09-03T17:16:46.027934
| 2023-09-02T22:30:44
| 2023-09-02T22:30:44
| 8,932,489
| 2,103
| 526
|
Zlib
| 2023-09-13T06:19:01
| 2013-03-21T15:56:48
|
C
|
UTF-8
|
C
| false
| false
| 924
|
c
|
moddiv-test.c
|
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
int a, b;
int div, mod;
printf ("Please note that this program does an\n"
"exhaustive test for the division and\n"
"modulo operation and therefore runs for\n"
"almost ever. On my box, it's nearly two\n"
"days in warp mode of VICE.\n\n");
a = 0;
do {
b = 1;
do {
div = a / b;
mod = a % b;
if (div * b + mod != a) {
printf ("Found problems:\n"
" Result of %u / %u is %u\n"
" Result of %u %% %u is %u\n",
a, b, div, a, b, mod);
return EXIT_FAILURE;
}
++b;
} while (b != 0);
if ((a & 0xFF) == 0) {
printf ("%5u ", a);
}
++a;
} while (a != 0);
return EXIT_SUCCESS;
}
|
c1a71e60e442b0bba0efc353266d02c596cdeca4
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/apps/examples/testcase/ta_tc/eventloop/utc/utc_eventloop_main.c
|
8d317a16b288fedb4bb97bdbf927eb739e43d053
|
[
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] |
permissive
|
Samsung/TizenRT
|
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
|
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
|
refs/heads/master
| 2023-08-31T08:59:33.327998
| 2023-08-08T06:09:20
| 2023-08-31T04:38:20
| 82,517,252
| 590
| 719
|
Apache-2.0
| 2023-09-14T06:54:49
| 2017-02-20T04:38:30
|
C
|
UTF-8
|
C
| false
| false
| 13,684
|
c
|
utc_eventloop_main.c
|
/****************************************************************************
*
* Copyright 2018 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
#include <tinyara/config.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <eventloop/eventloop.h>
#include "tc_common.h"
#define EL_INVALID_EVENT -1
#define EL_TIMER_DATA "timer"
#define EL_REPEAT_TIMER_DATA "repeat_timer"
#define EL_THREAD_SAFE_DATA "thread_safe"
#define EL_CB_DATA "EVENT CB DATA"
#define EL_WIFI_ON_DATA "HELLO WIFI-ON"
#define EL_WIFI_OFF_DATA "HELLO WIFI-OFF"
#define EL_SEND_COUNT 5
#define EL_WIFI_ON_COUNT 3
static int el_timer_flag;
static int el_thread_safe_flag;
static bool loop_stop_flag;
static bool el_event_wifi_off_flag;
static int el_event_wifi_on_cnt;
static int send_cnt;
static el_timer_t *g_repeat_timer;
static void timer_cb(void *data)
{
printf("Timer callback\n");
if (strncmp((char *)data, EL_TIMER_DATA, strlen(EL_TIMER_DATA) + 1) == 0) {
el_timer_flag++;
}
}
static bool repeat_timer_cb(void *data)
{
printf("Repeat timer callback\n");
el_timer_flag++;
return EVENTLOOP_CALLBACK_CONTINUE;
}
static void repeat_timer_stop_cb(void *data)
{
int ret;
ret = eventloop_delete_timer(g_repeat_timer);
if (ret == OK) {
printf("Stop the repeat timer SUCCESS!\n");
} else {
printf("Stop the repeat timer FAIL!\n");
}
}
static bool repeat_timer_3times_cb(void *data)
{
static int cnt = 0;
printf("Repeat timer 3 times callback %d\n", ++cnt);
if (strncmp((char *)data, EL_REPEAT_TIMER_DATA, strlen(EL_REPEAT_TIMER_DATA) + 1) == 0) {
el_timer_flag++;
}
if (cnt >= 3) {
printf("Calling count is %d, it will be stopped by itself.\n", cnt);
cnt = 0;
return EVENTLOOP_CALLBACK_STOP;
}
return EVENTLOOP_CALLBACK_CONTINUE;
}
static void utc_eventloop_loop_run_p(void)
{
int ret;
ret = eventloop_loop_run();
TC_ASSERT_EQ("eventloop_loop_run", ret, OK);
TC_SUCCESS_RESULT();
}
static void loop_stop_cb(void *data)
{
int ret;
printf("Loop will be stopped!\n");
ret = eventloop_loop_stop();
if (ret == OK) {
loop_stop_flag = true;
}
}
static void utc_eventloop_loop_stop_p(void)
{
int ret;
el_timer_t *timer;
loop_stop_flag = false;
timer = eventloop_add_timer(3000, false, (timeout_callback)loop_stop_cb, NULL);
TC_ASSERT_NEQ("eventloop_add_timer", timer, NULL);
ret = eventloop_loop_run();
TC_ASSERT_EQ("eventloop_loop_run", ret, OK);
TC_ASSERT_EQ("eventloop_loop_stop", loop_stop_flag, true);
/* Try to stop already stopped loop. It will be return EVENTLOOP_LOOP_FAIL. */
ret = eventloop_loop_stop();
TC_ASSERT_EQ("eventloop_loop_stop", ret, EVENTLOOP_LOOP_FAIL);
TC_SUCCESS_RESULT();
}
static void utc_eventloop_add_timer_n(void)
{
el_timer_t *timer;
timer = eventloop_add_timer(1000, false, NULL, NULL);
TC_ASSERT_EQ("eventloop_add_timer", timer, NULL);
TC_SUCCESS_RESULT();
}
static void utc_eventloop_add_timer_p(void)
{
int ret;
el_timer_t *timer;
el_timer_t *repeat_timer;
el_timer_t *loop_stop_timer;
el_timer_flag = 0;
timer = eventloop_add_timer(0, false, (timeout_callback)timer_cb, EL_TIMER_DATA);
TC_ASSERT_NEQ("eventloop_add_timer", timer, NULL);
ret = eventloop_loop_run();
TC_ASSERT_EQ("eventloop_loop_run", ret, OK);
TC_ASSERT_EQ("eventloop_add_timer", el_timer_flag, 1);
/* Add timer, it is stopped by returning EVENTLOOP_CALLBACK_STOP in callback function after 3 times. */
el_timer_flag = 0;
repeat_timer = eventloop_add_timer(1000, true, repeat_timer_3times_cb, EL_REPEAT_TIMER_DATA);
TC_ASSERT_NEQ("eventloop_add_timer", repeat_timer, NULL);
ret = eventloop_loop_run();
TC_ASSERT_EQ("eventloop_loop_run", ret, OK);
TC_ASSERT_EQ("eventloop_add_timer", el_timer_flag, 3);
/* Add timer which repeats forever, it is stopped by calling eventloop_delete_timer. */
el_timer_flag = 0;
g_repeat_timer = eventloop_add_timer(1000, true, repeat_timer_cb, EL_REPEAT_TIMER_DATA);
TC_ASSERT_NEQ("eventloop_add_timer", g_repeat_timer, NULL);
/* Add timer which will stop above repeated timer, g_repeat_timer after 5s. */
timer = eventloop_add_timer(5000, false, (timeout_callback)repeat_timer_stop_cb, EL_REPEAT_TIMER_DATA);
TC_ASSERT_NEQ("eventloop_add_timer", timer, NULL);
ret = eventloop_loop_run();
TC_ASSERT_EQ("eventloop_loop_run", ret, OK);
TC_ASSERT_EQ("eventloop_add_timer", el_timer_flag, 4);
/* Add timer which repeats forever, it is stopped by calling eventloop_loop_stop. */
el_timer_flag = 0;
repeat_timer = eventloop_add_timer(2000, true, repeat_timer_cb, EL_REPEAT_TIMER_DATA);
TC_ASSERT_NEQ("eventloop_add_timer", repeat_timer, NULL);
loop_stop_timer = eventloop_add_timer(3000, false, (timeout_callback)loop_stop_cb, NULL);
TC_ASSERT_NEQ("eventloop_add_timer", loop_stop_timer, NULL);
ret = eventloop_loop_run();
TC_ASSERT_EQ("eventloop_loop_run", ret, OK);
TC_ASSERT_EQ("eventloop_add_timer", el_timer_flag, 1);
TC_SUCCESS_RESULT();
}
static void utc_eventloop_delete_timer_n(void)
{
int ret;
ret = eventloop_delete_timer(NULL);
TC_ASSERT_EQ("eventloop_delete_timer", ret, EVENTLOOP_INVALID_PARAM);
TC_SUCCESS_RESULT();
}
static void utc_eventloop_delete_timer_p(void)
{
el_timer_t *timer;
int ret;
timer = eventloop_add_timer(0, false, (timeout_callback)timer_cb, NULL);
TC_ASSERT_NEQ("eventloop_add_timer", timer, NULL);
ret = eventloop_delete_timer(timer);
TC_ASSERT_EQ("eventloop_delete_timer", ret, OK);
/* Try to delete already deleted timer, it will be return EVENTLOOP_INVALID_HANDLE. */
ret = eventloop_delete_timer(timer);
TC_ASSERT_EQ("eventloop_delete_timer", ret, EVENTLOOP_INVALID_HANDLE);
TC_SUCCESS_RESULT();
}
static void utc_eventloop_add_timer_async_n(void)
{
el_timer_t *timer;
timer = eventloop_add_timer_async(1000, false, NULL, NULL);
TC_ASSERT_EQ("eventloop_add_timer_async", timer, NULL);
TC_SUCCESS_RESULT();
}
static void utc_eventloop_add_timer_async_p(void)
{
int sleep_cnt;
el_timer_t *timer;
el_timer_t *repeat_timer;
el_timer_flag = 0;
timer = eventloop_add_timer_async(0, false, (timeout_callback)timer_cb, EL_TIMER_DATA);
TC_ASSERT_NEQ("eventloop_add_timer_async", timer, NULL);
sleep_cnt = 0;
while (sleep_cnt < 5) {
sleep(1);
sleep_cnt++;
if (el_timer_flag == 1) {
break;
}
}
TC_ASSERT_EQ("eventloop_add_timer_async", el_timer_flag, 1);
el_timer_flag = 0;
repeat_timer = eventloop_add_timer_async(1000, true, repeat_timer_3times_cb, EL_REPEAT_TIMER_DATA);
TC_ASSERT_NEQ("eventloop_add_timer_async", repeat_timer, NULL);
sleep_cnt = 0;
while (sleep_cnt < 5) {
sleep(1);
sleep_cnt++;
if (el_timer_flag == 3) {
break;
}
}
TC_ASSERT_EQ("eventloop_add_timer_async", el_timer_flag, 3);
TC_SUCCESS_RESULT();
}
static int wifi_on_callback(void *cb_data, void *event_data)
{
static int cnt = 0;
printf("WIFI ON CALLBACK!! %d\n", ++cnt);
if (cb_data == NULL && event_data != NULL && strncmp(event_data, EL_WIFI_ON_DATA, sizeof(EL_WIFI_ON_DATA)) == 0) {
el_event_wifi_on_cnt++;
}
if (cnt >= EL_WIFI_ON_COUNT) {
cnt = 0;
return EVENTLOOP_CALLBACK_STOP;
}
return EVENTLOOP_CALLBACK_CONTINUE;
}
static int wifi_on_once_callback(void *cb_data, void *event_data)
{
printf("WIFI ON ONCE CALLBACK!!\n");
return EVENTLOOP_CALLBACK_STOP;
}
static void wifi_off_callback(void *cb_data, void *event_data)
{
int ret;
printf("WIFI OFF CALLBACK!!\n");
if (cb_data != NULL && strncmp(cb_data, EL_CB_DATA, sizeof(EL_CB_DATA)) == 0 && event_data != NULL && strncmp(event_data, EL_WIFI_OFF_DATA, sizeof(EL_WIFI_OFF_DATA)) == 0) {
printf("Callback data: %s\n", (char *)cb_data);
el_event_wifi_off_flag = true;
}
ret = eventloop_loop_stop();
if (ret == OK) {
loop_stop_flag = true;
}
}
static void utc_eventloop_add_event_handler_n(void)
{
el_event_t *event_handle;
event_handle = eventloop_add_event_handler(EL_INVALID_EVENT, (event_callback)wifi_on_callback, NULL);
TC_ASSERT_EQ("eventloop_add_event_handler", event_handle, NULL);
event_handle = eventloop_add_event_handler(EL_EVENT_WIFI_ON, NULL, NULL);
TC_ASSERT_EQ("eventloop_add_event_handler", event_handle, NULL);
TC_SUCCESS_RESULT();
}
static void utc_eventloop_add_event_handler_p(void)
{
el_event_t *wifi_on_handle;
el_event_t *wifi_off_handle;
wifi_on_handle = eventloop_add_event_handler(EL_EVENT_WIFI_ON, (event_callback)wifi_on_callback, NULL);
TC_ASSERT_NEQ("eventloop_add_event_handler", wifi_on_handle, NULL);
wifi_off_handle = eventloop_add_event_handler(EL_EVENT_WIFI_OFF, (event_callback)wifi_off_callback, EL_CB_DATA);
TC_ASSERT_NEQ("eventloop_add_event_handler", wifi_off_handle, NULL);
TC_SUCCESS_RESULT();
}
static void utc_eventloop_del_event_handler_n(void)
{
int ret;
ret = eventloop_del_event_handler(NULL);
TC_ASSERT_EQ("eventloop_del_event_handler", ret, EVENTLOOP_INVALID_PARAM);
TC_SUCCESS_RESULT();
}
static void utc_eventloop_del_event_handler_p(void)
{
int ret;
el_event_t *event_handle;
event_handle = eventloop_add_event_handler(EL_EVENT_WIFI_ON, (event_callback)wifi_on_callback, NULL);
TC_ASSERT_NEQ("eventloop_add_event_handler", event_handle, NULL);
ret = eventloop_del_event_handler(event_handle);
TC_ASSERT_EQ("eventloop_del_event_handler", ret, OK);
/* Try to delete already deleted event handler, it will be return EVENTLOOP_INVALID_HANDLE. */
ret = eventloop_del_event_handler(event_handle);
TC_ASSERT_EQ("eventloop_del_event_handler", ret, EVENTLOOP_INVALID_HANDLE);
TC_SUCCESS_RESULT();
}
static void utc_eventloop_send_event_n(void)
{
int ret;
ret = eventloop_send_event(EL_INVALID_EVENT, NULL, 0);
TC_ASSERT_EQ("eventloop_send_event", ret, EVENTLOOP_INVALID_PARAM);
TC_SUCCESS_RESULT();
}
static bool eventloop_send_event_func(void *data)
{
static int cnt = 0;
int ret;
if (++cnt < EL_SEND_COUNT) {
/* Send EL_EVENT_WIFI_ON event 4 times */
ret = eventloop_send_event(EL_EVENT_WIFI_ON, EL_WIFI_ON_DATA, sizeof(EL_WIFI_ON_DATA));
if (ret == OK) {
send_cnt++;
}
return EVENTLOOP_CALLBACK_CONTINUE;
}
/* Send EL_EVENT_WIFI_OFF event and loop will be stopped in callback function. */
ret = eventloop_send_event(EL_EVENT_WIFI_OFF, EL_WIFI_OFF_DATA, sizeof(EL_WIFI_OFF_DATA));
if (ret == OK) {
send_cnt++;
}
cnt = 0;
return EVENTLOOP_CALLBACK_STOP;
}
static void utc_eventloop_send_event_p(void)
{
int ret;
el_timer_t *timer;
el_event_t *event_handle;
send_cnt = 0;
el_event_wifi_on_cnt = 0;
el_event_wifi_off_flag = false;
loop_stop_flag = false;
timer = eventloop_add_timer(2000, true, (timeout_callback)eventloop_send_event_func, NULL);
TC_ASSERT_NEQ("eventloop_add_timer", timer, NULL);
ret = eventloop_loop_run();
TC_ASSERT_EQ("eventloop_loop_run", ret, OK);
TC_ASSERT_EQ("eventloop_send_event", send_cnt, EL_SEND_COUNT);
TC_ASSERT_EQ("eventloop_send_event", el_event_wifi_on_cnt, EL_WIFI_ON_COUNT);
TC_ASSERT_EQ("eventloop_send_event", el_event_wifi_off_flag, true);
TC_ASSERT_EQ("eventloop_send_event", loop_stop_flag, true);
event_handle = eventloop_add_event_handler(EL_EVENT_WIFI_ON, (event_callback)wifi_on_once_callback, NULL);
TC_ASSERT_NEQ("eventloop_add_event_handler", event_handle, NULL);
ret = eventloop_send_event(EL_EVENT_WIFI_ON, NULL, 0);
TC_ASSERT_EQ("eventloop_send_event", ret, OK);
ret = eventloop_loop_run();
TC_ASSERT_EQ("eventloop_loop_run", ret, OK);
TC_SUCCESS_RESULT();
}
static void el_thread_safe_cb(void *data)
{
if (strncmp((char *)data, EL_THREAD_SAFE_DATA, sizeof(EL_THREAD_SAFE_DATA)) == 0) {
el_thread_safe_flag = true;
}
}
static void utc_eventloop_thread_safe_function_call_n(void)
{
int ret;
ret = eventloop_thread_safe_function_call(NULL, NULL);
TC_ASSERT_EQ("eventloop_thread_safe_function_call", ret, EVENTLOOP_INVALID_PARAM);
TC_SUCCESS_RESULT();
}
static void utc_eventloop_thread_safe_function_call_p(void)
{
int ret;
el_thread_safe_flag = false;
ret = eventloop_thread_safe_function_call(el_thread_safe_cb, EL_THREAD_SAFE_DATA);
TC_ASSERT_EQ("eventloop_thread_safe_function_call", ret, OK);
ret = eventloop_loop_run();
TC_ASSERT_EQ("eventloop_loop_run", ret, OK);
TC_ASSERT_EQ("eventloop_thread_safe_function_call", el_thread_safe_flag, true);
TC_SUCCESS_RESULT();
}
#ifdef CONFIG_BUILD_KERNEL
int main(int argc, FAR char *argv[])
#else
int utc_eventloop_main(int argc, char *argv[])
#endif
{
if (testcase_state_handler(TC_START, "Eventloop UTC") == ERROR) {
return ERROR;
}
utc_eventloop_loop_run_p();
utc_eventloop_add_timer_n();
utc_eventloop_add_timer_p();
utc_eventloop_delete_timer_n();
utc_eventloop_delete_timer_p();
utc_eventloop_add_timer_async_n();
utc_eventloop_add_timer_async_p();
utc_eventloop_add_event_handler_n();
utc_eventloop_add_event_handler_p();
utc_eventloop_del_event_handler_n();
utc_eventloop_del_event_handler_p();
utc_eventloop_send_event_n();
utc_eventloop_send_event_p();
utc_eventloop_thread_safe_function_call_n();
utc_eventloop_thread_safe_function_call_p();
utc_eventloop_loop_stop_p();
(void)testcase_state_handler(TC_END, "Eventloop UTC");
return 0;
}
|
b8a861a0a36a260036f3e6522dffdbfc3f8a0c3f
|
5eff7a36d9a9917dce9111f0c3074375fe6f7656
|
/app/xlockmore/modes/ant.c
|
1212a515d8081d24500060c7ae442ae6e09d0bf8
|
[] |
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
| 41,244
|
c
|
ant.c
|
/* -*- Mode: C; tab-width: 4 -*- */
/*-
* ant --- Chris Langton's generalized turing machine ants (also known
* as Greg Turk's turmites) whose tape is the screen
*/
#if !defined( lint ) && !defined( SABER )
static const char sccsid[] = "@(#)ant.c 5.13 2004/06/23 xlockmore";
#endif
/*-
* Copyright (c) 1995 by David Bagley.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation.
*
* This file is provided AS IS with no warranties of any kind. The author
* shall have no liability with respect to the infringement of copyrights,
* trade secrets or any patents by this file or any part thereof. In no
* event will the author be liable for any lost revenue or profits or
* other special, indirect and consequential damages.
*
* Revision History:
* 01-Nov-2000: Allocation checks
* 10-May-1997: Compatible with xscreensaver
* 16-Apr-1997: -neighbors 3 and 8 added
* 01-Jan-1997: Updated ant.c to handle more kinds of ants. Thanks to
* J Austin David <Austin.David@tlogic.com>. Check it out in
* java at http://havoc.gtf.gatech.edu/austin He thought up the
* new Ladder ant.
* 04-Apr-1996: -neighbors 6 runtime-time option added for hexagonal ants
* (bees), coded from an idea of Jim Propp's in Science News,
* Oct 28, 1995 VOL. 148 page 287
* 20-Sep-1995: Memory leak in ant fixed. Now random colors.
* 05-Sep-1995: Coded from A.K. Dewdney's "Computer Recreations", Scientific
* American Magazine" Sep 1989 pp 180-183, Mar 1990 p 121
* Also used Ian Stewart's Mathematical Recreations, Scientific
* American Jul 1994 pp 104-107
* also used demon.c and life.c as a guide.
*/
/*-
Species Grid Number of Neighbors
------- ---- ------------------
Ants Square 4 (or 8)
Bees Hexagon 6
Bees Triangle 3 (or 9, 12)
Neighbors 6 and neighbors 3 produce the same Turk ants.
*/
#ifdef STANDALONE
#define MODE_ant
#define PROGCLASS "Ant"
#define HACK_INIT init_ant
#define HACK_DRAW draw_ant
#define ant_opts xlockmore_opts
#define DEFAULTS "*delay: 1000 \n" \
"*count: -3 \n" \
"*cycles: 40000 \n" \
"*size: -12 \n" \
"*ncolors: 64 \n" \
"*neighbors: 0 \n" \
"*sharpturn: False \n" \
"*fullrandom: True \n" \
"*verbose: False \n"
#include "xlockmore.h" /* in xscreensaver distribution */
#else /* STANDALONE */
#include "xlock.h" /* in xlockmore distribution */
#endif /* STANDALONE */
#include "automata.h"
#ifdef MODE_ant
#define DEF_LABEL "True"
#define FONT_HEIGHT 19
#define FONT_WIDTH 15
/*-
* neighbors of 0 randomizes it for 3, 4, 6, 8, 12 (last 2 are less likely)
*/
#define DEF_NEIGHBORS "0" /* choose random value */
#define DEF_RULE "A" /* All rules */
#define DEF_TRUCHET "False"
#define DEF_EYES "False"
#define DEF_SHARPTURN "False"
static int neighbors;
static char *rule;
static Bool truchet;
static Bool eyes;
static Bool sharpturn;
static Bool label;
static XrmOptionDescRec opts[] =
{
{(char *) "-label", (char *) ".ant.label", XrmoptionNoArg, (caddr_t) "on"},
{(char *) "+label", (char *) ".ant.label", XrmoptionNoArg, (caddr_t) "off"},
{(char *) "-neighbors", (char *) ".ant.neighbors", XrmoptionSepArg, (caddr_t) NULL},
{(char *) "-rule", (char *) ".ant.rule", XrmoptionSepArg, (caddr_t) NULL},
{(char *) "-truchet", (char *) ".ant.truchet", XrmoptionNoArg, (caddr_t) "on"},
{(char *) "+truchet", (char *) ".ant.truchet", XrmoptionNoArg, (caddr_t) "off"},
{(char *) "-eyes", (char *) ".ant.eyes", XrmoptionNoArg, (caddr_t) "on"},
{(char *) "+eyes", (char *) ".ant.eyes", XrmoptionNoArg, (caddr_t) "off"},
{(char *) "-sharpturn", (char *) ".ant.sharpturn", XrmoptionNoArg, (caddr_t) "on"},
{(char *) "+sharpturn", (char *) ".ant.sharpturn", XrmoptionNoArg, (caddr_t) "off"}
};
static argtype vars[] =
{
{(void *) & label, (char *) "label", (char *) "Label", (char *) DEF_LABEL, t_Bool},
{(void *) & neighbors, (char *) "neighbors", (char *) "Neighbors", (char *) DEF_NEIGHBORS, t_Int},
{(void *) & rule, (char *) "rule", (char *) "Rule", (char *) DEF_RULE, t_String},
{(void *) & truchet, (char *) "truchet", (char *) "Truchet", (char *) DEF_TRUCHET, t_Bool},
{(void *) & eyes, (char *) "eyes", (char *) "Eyes", (char *) DEF_EYES, t_Bool},
{(void *) & sharpturn, (char *) "sharpturn", (char *) "SharpTurn", (char *) DEF_SHARPTURN, t_Bool}
};
static OptionStruct desc[] =
{
{(char *) "-/+label", (char *) "turn on/off rule labeling"},
{(char *) "-neighbors num", (char *) "squares 4 or 8, hexagons 6, triangles 3 or 12"},
{(char *) "-rule string", (char *) "binary string for Turk's Ant"},
{(char *) "-/+truchet", (char *) "turn on/off Truchet lines"},
{(char *) "-/+eyes", (char *) "turn on/off eyes"},
{(char *) "-/+sharpturn", (char *) "turn on/off sharp turns (6, 8 or 12 neighbors only)"}
};
ModeSpecOpt ant_opts =
{sizeof opts / sizeof opts[0], opts, sizeof vars / sizeof vars[0], vars, desc};
#ifdef USE_MODULES
const ModStruct ant_description =
{"ant",
"init_ant", "draw_ant", "release_ant",
"refresh_ant", "init_ant", (char *) NULL, &ant_opts,
1000, -3, 40000, -12, 64, 1.0, "",
"Shows Langton's and Turk's generalized ants", 0, NULL};
#endif
#define ANTBITS(n,w,h)\
if ((ap->pixmaps[ap->init_bits]=\
XCreatePixmapFromBitmapData(display,window,(char *)n,w,h,1,0,1))==None){\
free_ant(display,ap); return;} else {ap->init_bits++;}
/* If you change the table you may have to change the following 2 constants */
#define STATES 2
#define MINANTS 1
#define REDRAWSTEP 2000 /* How much tape to draw per cycle */
#define MINGRIDSIZE 24
#define MINSIZE 1
#define MINRANDOMSIZE 5
#define ANGLES 360
typedef struct {
unsigned char color;
short direction;
unsigned char next;
} statestruct;
typedef struct {
int col, row;
short direction;
unsigned char state;
} antstruct;
typedef struct {
Bool painted;
int neighbors;
int generation;
int xs, ys;
int xb, yb;
int init_dir;
int nrows, ncols;
int width, height;
unsigned char ncolors, nstates;
int n;
int redrawing, redrawpos;
Bool truchet; /* Only for Turk modes */
Bool eyes;
Bool sharpturn;
statestruct machine[NUMSTIPPLES * STATES];
unsigned char *tape;
unsigned char *truchet_state;
antstruct *ants;
int init_bits;
unsigned char colors[NUMSTIPPLES - 1];
GC stippledGC;
Pixmap pixmaps[NUMSTIPPLES - 1];
int labelOffsetX, labelOffsetY;
char ruleString[40];
union {
XPoint hexagon[7]; /* Need more than 6 for truchet */
XPoint triangle[2][4]; /* Need more than 3 for truchet */
} shape;
} antfarmstruct;
static char plots[] =
{3, 4, 6, 8,
#ifdef NUMBER_9
9,
#endif
12};
#define NEIGHBORKINDS ((long) (sizeof plots / sizeof *plots))
#define GOODNEIGHBORKINDS 3
/* Relative ant moves */
#define FS 0 /* Step */
#define TRS 1 /* Turn right, then step */
#define THRS 2 /* Turn hard right, then step */
#define TBS 3 /* Turn back, then step */
#define THLS 4 /* Turn hard left, then step */
#define TLS 5 /* Turn left, then step */
#define SF 6 /* Step */
#define STR 7 /* Step then turn right */
#define STHR 8 /* Step then turn hard right */
#define STB 9 /* Step then turn back */
#define STHL 10 /* Step then turn hard left */
#define STL 11 /* Step then turn left */
static antfarmstruct *antfarms = (antfarmstruct *) NULL;
/* LANGTON'S ANT (10) Chaotic after 500, Builder after 10,000 (104p) */
/* TURK'S 100 ANT Always chaotic?, tested past 150,000,000 */
/* TURK'S 101 ANT Always chaotic? */
/* TURK'S 110 ANT Builder at 150 (18p) */
/* TURK'S 1000 ANT Always chaotic? */
/* TURK'S 1100 SYMMETRIC ANT all even run 1's and 0's are symmetric */
/* other examples 1001, 110011, 110000, 1001101 */
/* TURK'S 1101 ANT Builder after 250,000 (388p) */
/* Once saw a chess horse type builder (i.e. non-45 degree builder) */
/* BEE ONLY */
/* All alternating 10 appear symmetric, no proof (i.e. 10, 1010, etc) */
/* Even runs of 0's and 1's are also symmetric */
/* I have seen Hexagonal builders but they are more rare. */
static unsigned char tables[][3 * NUMSTIPPLES * STATES + 2] =
{
#if 0
/* Here just so you can figure out notation */
{ /* Langton's ant (-rule 10) */
2, 1,
1, TLS, 0, 0, TRS, 0
},
#else
/* First 2 numbers are the size (ncolors, nstates) */
{ /* LADDER BUILDER */
4, 1,
1, STR, 0, 2, STL, 0, 3, TRS, 0, 0, TLS, 0
},
{ /* SPIRALING PATTERN */
2, 2,
1, TLS, 0, 0, FS, 1,
1, TRS, 0, 1, TRS, 0
},
{ /* SQUARE (HEXAGON) BUILDER */
2, 2,
1, TLS, 0, 0, FS, 1,
0, TRS, 0, 1, TRS, 0
},
#endif
};
#define NTABLES (sizeof tables / sizeof tables[0])
static void
position_of_neighbor(antfarmstruct * ap, int dir, int *pcol, int *prow)
{
int col = *pcol, row = *prow;
if (ap->neighbors == 4 || ap->neighbors == 6 || ap->neighbors == 8) {
switch (dir) {
case 0:
col = (col + 1 == ap->ncols) ? 0 : col + 1;
break;
case 45:
col = (col + 1 == ap->ncols) ? 0 : col + 1;
row = (!row) ? ap->nrows - 1 : row - 1;
break;
case 60:
if (!(row & 1))
col = (col + 1 == ap->ncols) ? 0 : col + 1;
row = (!row) ? ap->nrows - 1 : row - 1;
break;
case 90:
row = (!row) ? ap->nrows - 1 : row - 1;
break;
case 120:
if (row & 1)
col = (!col) ? ap->ncols - 1 : col - 1;
row = (!row) ? ap->nrows - 1 : row - 1;
break;
case 135:
col = (!col) ? ap->ncols - 1 : col - 1;
row = (!row) ? ap->nrows - 1 : row - 1;
break;
case 180:
col = (!col) ? ap->ncols - 1 : col - 1;
break;
case 225:
col = (!col) ? ap->ncols - 1 : col - 1;
row = (row + 1 == ap->nrows) ? 0 : row + 1;
break;
case 240:
if (row & 1)
col = (!col) ? ap->ncols - 1 : col - 1;
row = (row + 1 == ap->nrows) ? 0 : row + 1;
break;
case 270:
row = (row + 1 == ap->nrows) ? 0 : row + 1;
break;
case 300:
if (!(row & 1))
col = (col + 1 == ap->ncols) ? 0 : col + 1;
row = (row + 1 == ap->nrows) ? 0 : row + 1;
break;
case 315:
col = (col + 1 == ap->ncols) ? 0 : col + 1;
row = (row + 1 == ap->nrows) ? 0 : row + 1;
break;
default:
(void) fprintf(stderr, "wrong direction %d\n", dir);
}
} else { /* TRI */
if ((col + row) % 2) { /* right */
switch (dir) {
case 0:
col = (!col) ? ap->ncols - 1 : col - 1;
break;
case 30:
case 40:
col = (!col) ? ap->ncols - 1 : col - 1;
row = (!row) ? ap->nrows - 1 : row - 1;
break;
case 60:
col = (!col) ? ap->ncols - 1 : col - 1;
if (!row)
row = ap->nrows - 2;
else if (!(row - 1))
row = ap->nrows - 1;
else
row = row - 2;
break;
case 80:
case 90:
if (!row)
row = ap->nrows - 2;
else if (!(row - 1))
row = ap->nrows - 1;
else
row = row - 2;
break;
case 120:
row = (!row) ? ap->nrows - 1 : row - 1;
break;
case 150:
case 160:
col = (col + 1 == ap->ncols) ? 0 : col + 1;
row = (!row) ? ap->nrows - 1 : row - 1;
break;
case 180:
col = (col + 1 == ap->ncols) ? 0 : col + 1;
break;
case 200:
case 210:
col = (col + 1 == ap->ncols) ? 0 : col + 1;
row = (row + 1 == ap->nrows) ? 0 : row + 1;
break;
case 240:
row = (row + 1 == ap->nrows) ? 0 : row + 1;
break;
case 270:
case 280:
if (row + 1 == ap->nrows)
row = 1;
else if (row + 2 == ap->nrows)
row = 0;
else
row = row + 2;
break;
case 300:
col = (!col) ? ap->ncols - 1 : col - 1;
if (row + 1 == ap->nrows)
row = 1;
else if (row + 2 == ap->nrows)
row = 0;
else
row = row + 2;
break;
case 320:
case 330:
col = (!col) ? ap->ncols - 1 : col - 1;
row = (row + 1 == ap->nrows) ? 0 : row + 1;
break;
default:
(void) fprintf(stderr, "wrong direction %d\n", dir);
}
} else { /* left */
switch (dir) {
case 0:
col = (col + 1 == ap->ncols) ? 0 : col + 1;
break;
case 30:
case 40:
col = (col + 1 == ap->ncols) ? 0 : col + 1;
row = (row + 1 == ap->nrows) ? 0 : row + 1;
break;
case 60:
col = (col + 1 == ap->ncols) ? 0 : col + 1;
if (row + 1 == ap->nrows)
row = 1;
else if (row + 2 == ap->nrows)
row = 0;
else
row = row + 2;
break;
case 80:
case 90:
if (row + 1 == ap->nrows)
row = 1;
else if (row + 2 == ap->nrows)
row = 0;
else
row = row + 2;
break;
case 120:
row = (row + 1 == ap->nrows) ? 0 : row + 1;
break;
case 150:
case 160:
col = (!col) ? ap->ncols - 1 : col - 1;
row = (row + 1 == ap->nrows) ? 0 : row + 1;
break;
case 180:
col = (!col) ? ap->ncols - 1 : col - 1;
break;
case 200:
case 210:
col = (!col) ? ap->ncols - 1 : col - 1;
row = (!row) ? ap->nrows - 1 : row - 1;
break;
case 240:
row = (!row) ? ap->nrows - 1 : row - 1;
break;
case 270:
case 280:
if (!row)
row = ap->nrows - 2;
else if (row == 1)
row = ap->nrows - 1;
else
row = row - 2;
break;
case 300:
col = (col + 1 == ap->ncols) ? 0 : col + 1;
if (!row)
row = ap->nrows - 2;
else if (row == 1)
row = ap->nrows - 1;
else
row = row - 2;
break;
case 320:
case 330:
col = (col + 1 == ap->ncols) ? 0 : col + 1;
row = (!row) ? ap->nrows - 1 : row - 1;
break;
default:
(void) fprintf(stderr, "wrong direction %d\n", dir);
}
}
}
*pcol = col;
*prow = row;
}
static void
fillcell(ModeInfo * mi, GC gc, int col, int row)
{
antfarmstruct *ap = &antfarms[MI_SCREEN(mi)];
if (ap->neighbors == 6) {
int ccol = 2 * col + !(row & 1), crow = 2 * row;
ap->shape.hexagon[0].x = ap->xb + ccol * ap->xs;
ap->shape.hexagon[0].y = ap->yb + crow * ap->ys;
if (ap->xs == 1 && ap->ys == 1)
XDrawPoint(MI_DISPLAY(mi), MI_WINDOW(mi), gc,
ap->shape.hexagon[0].x, ap->shape.hexagon[0].y);
else
XFillPolygon(MI_DISPLAY(mi), MI_WINDOW(mi), gc,
ap->shape.hexagon, 6, Convex, CoordModePrevious);
} else if (ap->neighbors == 4 || ap->neighbors == 8) {
XFillRectangle(MI_DISPLAY(mi), MI_WINDOW(mi), gc,
ap->xb + ap->xs * col, ap->yb + ap->ys * row,
ap->xs - (ap->xs > 3), ap->ys - (ap->ys > 3));
} else { /* TRI */
int orient = (col + row) % 2; /* O left 1 right */
ap->shape.triangle[orient][0].x = ap->xb + col * ap->xs;
ap->shape.triangle[orient][0].y = ap->yb + row * ap->ys;
if (ap->xs <= 3 || ap->ys <= 3)
XDrawPoint(MI_DISPLAY(mi), MI_WINDOW(mi), gc,
((orient) ? -1 : 1) + ap->shape.triangle[orient][0].x,
ap->shape.triangle[orient][0].y);
else {
if (orient)
ap->shape.triangle[orient][0].x += (ap->xs / 2 - 1);
else
ap->shape.triangle[orient][0].x -= (ap->xs / 2 - 1);
XFillPolygon(MI_DISPLAY(mi), MI_WINDOW(mi), gc,
ap->shape.triangle[orient], 3, Convex, CoordModePrevious);
}
}
}
static void
truchetcell(ModeInfo * mi, int col, int row, int truchetstate)
{
antfarmstruct *ap = &antfarms[MI_SCREEN(mi)];
if (ap->neighbors == 6) {
int ccol = 2 * col + !(row & 1), crow = 2 * row;
int side;
int fudge = 7; /* fudge because the hexagons are not exact */
XPoint hex, hex2;
if (ap->sharpturn) {
hex.x = ap->xb + ccol * ap->xs - (int) ((double) ap->xs / 2.0) - 1;
hex.y = ap->yb + crow * ap->ys - (int) ((double) ap->ys / 2.0) - 1;
for (side = 0; side < 6; side++) {
if (side) {
hex.x += ap->shape.hexagon[side].x;
hex.y += ap->shape.hexagon[side].y;
}
if (truchetstate == side % 2)
XDrawArc(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
hex.x, hex.y, ap->xs, ap->ys,
((570 - (side * 60) + fudge) % 360) * 64, (120 - 2 * fudge) * 64);
}
} else {
/* Very crude approx of Sqrt 3, so it will not cause drawing errors. */
hex.x = ap->xb + ccol * ap->xs - (int) ((double) ap->xs * 1.6 / 2.0) - 1;
hex.y = ap->yb + crow * ap->ys - (int) ((double) ap->ys * 1.6 / 2.0) - 1;
for (side = 0; side < 6; side++) {
if (side) {
hex.x += ap->shape.hexagon[side].x;
hex.y += ap->shape.hexagon[side].y;
}
hex2.x = hex.x + ap->shape.hexagon[side + 1].x / 2;
hex2.y = hex.y + ap->shape.hexagon[side + 1].y / 2 + 1;
/* Lots of fudging here */
if (side == 0) {
hex2.x += 1;
} else if (side == 1) {
hex2.x += (short) (ap->xs * 0.1 + 1);
hex2.y += (short) (ap->ys * 0.1 - ((ap->ys > 5) ? 1 : 0));
} else if (side == 2) {
hex2.x += (short) (ap->xs * 0.1 + 1);
hex2.y += 1;
} else if (side == 3) {
hex2.y += 1;
} else if (side == 4) {
hex2.x += (short) (ap->xs * 0.1);
hex2.y += (short) (ap->ys * 0.1 - 1);
} else if (side == 5) {
hex2.x += (short) (ap->xs * 0.5);
hex2.y += (short) (-ap->ys * 0.3);
}
if (truchetstate == side % 3)
/* Crude approx of 120 deg, so it will not cause drawing errors. */
XDrawArc(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
hex2.x, hex2.y,
(int) ((double) ap->xs * 1.5), (int) ((double) ap->ys * 1.5),
((555 - (side * 60)) % 360) * 64, 90 * 64);
}
}
} else if (ap->neighbors == 4) {
if (truchetstate) {
XDrawArc(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
ap->xb + ap->xs * col - (ap->xs - 1) / 2,
ap->yb + ap->ys * row + (ap->ys - 1) / 2,
ap->xs - 2, ap->ys - 2,
0 * 64, 90 * 64);
XDrawArc(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
ap->xb + ap->xs * col + (ap->xs - 1) / 2,
ap->yb + ap->ys * row - (ap->ys - 1) / 2,
ap->xs - 2, ap->ys - 2,
-90 * 64, -90 * 64);
} else {
XDrawArc(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
ap->xb + ap->xs * col - (ap->xs - 1) / 2,
ap->yb + ap->ys * row - (ap->ys - 1) / 2,
ap->xs - 2, ap->ys - 2,
0 * 64, -90 * 64);
XDrawArc(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
ap->xb + ap->xs * col + (ap->xs - 1) / 2,
ap->yb + ap->ys * row + (ap->ys - 1) / 2,
ap->xs - 2, ap->ys - 2,
90 * 64, 90 * 64);
}
} else if (ap->neighbors == 3) {
int orient = (col + row) % 2; /* O left 1 right */
int side, ang;
int fudge = 7; /* fudge because the triangles are not exact */
double fudge2 = 1.18;
XPoint tri;
tri.x = ap->xb + col * ap->xs;
tri.y = ap->yb + row * ap->ys;
if (orient) {
tri.x += (ap->xs / 2 - 1);
} else {
tri.x -= (ap->xs / 2 - 1);
}
for (side = 0; side < 3; side++) {
if (side > 0) {
tri.x += ap->shape.triangle[orient][side].x;
tri.y += ap->shape.triangle[orient][side].y;
}
if (truchetstate == side) {
if (orient)
ang = (510 - side * 120) % 360; /* Right */
else
ang = (690 - side * 120) % 360; /* Left */
XDrawArc(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
(int) (tri.x - ap->xs * fudge2 / 2),
(int) (tri.y - 3 * ap->ys * fudge2 / 4),
(unsigned int) (ap->xs * fudge2),
(unsigned int) (3 * ap->ys * fudge2 / 2),
(ang + fudge) * 64, (60 - 2 * fudge) * 64);
}
}
}
}
static void
drawcell(ModeInfo * mi, int col, int row, unsigned char color)
{
antfarmstruct *ap = &antfarms[MI_SCREEN(mi)];
GC gc;
if (!color) {
XSetForeground(MI_DISPLAY(mi), MI_GC(mi), MI_BLACK_PIXEL(mi));
gc = MI_GC(mi);
} else if (MI_NPIXELS(mi) > 2) {
XSetForeground(MI_DISPLAY(mi), MI_GC(mi),
MI_PIXEL(mi, ap->colors[color - 1]));
gc = MI_GC(mi);
} else {
XGCValues gcv;
gcv.stipple = ap->pixmaps[color - 1];
gcv.foreground = MI_WHITE_PIXEL(mi);
gcv.background = MI_BLACK_PIXEL(mi);
XChangeGC(MI_DISPLAY(mi), ap->stippledGC,
GCStipple | GCForeground | GCBackground, &gcv);
gc = ap->stippledGC;
}
fillcell(mi, gc, col, row);
}
static void
drawtruchet(ModeInfo * mi, int col, int row,
unsigned char color, unsigned char truchetstate)
{
antfarmstruct *ap = &antfarms[MI_SCREEN(mi)];
if (!color)
XSetForeground(MI_DISPLAY(mi), MI_GC(mi), MI_WHITE_PIXEL(mi));
else if (MI_NPIXELS(mi) > 2 || color > ap->ncolors / 2)
XSetForeground(MI_DISPLAY(mi), MI_GC(mi), MI_BLACK_PIXEL(mi));
else
XSetForeground(MI_DISPLAY(mi), MI_GC(mi), MI_WHITE_PIXEL(mi));
truchetcell(mi, col, row, truchetstate);
}
static void
draw_anant(ModeInfo * mi, int direction, int col, int row)
{
antfarmstruct *ap = &antfarms[MI_SCREEN(mi)];
Display *display = MI_DISPLAY(mi);
Window window = MI_WINDOW(mi);
XSetForeground(display, MI_GC(mi), MI_WHITE_PIXEL(mi));
fillcell(mi, MI_GC(mi), col, row);
if (ap->eyes) { /* Draw Eyes */
XSetForeground(display, MI_GC(mi), MI_BLACK_PIXEL(mi));
if (ap->neighbors == 6) {
int ccol = 2 * col + !(row & 1), crow = 2 * row;
int side, ang;
XPoint hex;
if (!(ap->xs > 3 && ap->ys > 3))
return;
hex.x = ap->xb + ccol * ap->xs;
hex.y = ap->yb + crow * ap->ys + ap->ys / 2;
ang = direction * ap->neighbors / ANGLES;
for (side = 0; side < ap->neighbors; side++) {
if (side) {
hex.x -= ap->shape.hexagon[side].x / 2;
hex.y += ap->shape.hexagon[side].y / 2;
}
if (side == (ap->neighbors + ang - 2) % ap->neighbors)
XDrawPoint(display, window, MI_GC(mi), hex.x, hex.y);
if (side == (ap->neighbors + ang - 1) % ap->neighbors)
XDrawPoint(display, window, MI_GC(mi), hex.x, hex.y);
}
} else if (ap->neighbors == 4 || ap->neighbors == 8) {
if (!(ap->xs > 3 && ap->ys > 3))
return;
switch (direction) {
case 0:
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * (col + 1) - 3,
ap->yb + ap->ys * row + ap->ys / 2 - 2);
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * (col + 1) - 3,
ap->yb + ap->ys * row + ap->ys / 2);
break;
case 45:
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * (col + 1) - 4,
ap->yb + ap->ys * row + 1);
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * (col + 1) - 3,
ap->yb + ap->ys * row + 2);
break;
case 90:
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * col + ap->xs / 2 - 2,
ap->yb + ap->ys * row + 1);
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * col + ap->xs / 2,
ap->yb + ap->ys * row + 1);
break;
case 135:
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * col + 2,
ap->yb + ap->ys * row + 1);
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * col + 1,
ap->yb + ap->ys * row + 2);
break;
case 180:
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * col + 1,
ap->yb + ap->ys * row + ap->ys / 2 - 2);
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * col + 1,
ap->yb + ap->ys * row + ap->ys / 2);
break;
case 225:
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * col + 2,
ap->yb + ap->ys * (row + 1) - 3);
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * col + 1,
ap->yb + ap->ys * (row + 1) - 4);
break;
case 270:
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * col + ap->xs / 2 - 2,
ap->yb + ap->ys * (row + 1) - 3);
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * col + ap->xs / 2,
ap->yb + ap->ys * (row + 1) - 3);
break;
case 315:
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * (col + 1) - 4,
ap->yb + ap->ys * (row + 1) - 3);
XDrawPoint(display, window, MI_GC(mi),
ap->xb + ap->xs * (col + 1) - 3,
ap->yb + ap->ys * (row + 1) - 4);
break;
default:
(void) fprintf(stderr, "wrong eyes direction %d for ant eyes\n", direction);
}
} else { /* TRI */
int orient = (col + row) % 2; /* O left 1 right */
int side, ang;
XPoint tri;
if (!(ap->xs > 6 && ap->ys > 6))
return;
tri.x = ap->xb + col * ap->xs;
tri.y = ap->yb + row * ap->ys;
if (orient)
tri.x += (ap->xs / 6 - 1);
else
tri.x -= (ap->xs / 6 - 1);
ang = direction * ap->neighbors / ANGLES;
/* approx... does not work that well for even numbers */
if (
#ifdef NUMBER_9
ap->neighbors == 9 ||
#endif
ap->neighbors == 12) {
#ifdef UNDER_CONSTRUCTION
/* Not sure why this does not work */
ang = ((ang + ap->neighbors / 6) / (ap->neighbors / 3)) % 3;
#else
return;
#endif
}
for (side = 0; side < 3; side++) {
if (side) {
tri.x += ap->shape.triangle[orient][side].x / 3;
tri.y += ap->shape.triangle[orient][side].y / 3;
}
/* Either you have the eyes in back or one eye in front */
#if 0
if (side == ang)
XDrawPoint(display, window, MI_GC(mi), tri.x, tri.y);
#else
if (side == (ang + 2) % 3)
XDrawPoint(display, window, MI_GC(mi), tri.x, tri.y);
if (side == (ang + 1) % 3)
XDrawPoint(display, window, MI_GC(mi), tri.x, tri.y);
#endif
}
}
}
}
#if 0
static void
RandomSoup(mi)
ModeInfo *mi;
{
antfarmstruct *ap = &antfarms[MI_SCREEN(mi)];
int row, col, mrow = 0;
for (row = 0; row < ap->nrows; ++row) {
for (col = 0; col < ap->ncols; ++col) {
ap->old[col + mrow] = (unsigned char) NRAND((int) ap->ncolors);
drawcell(mi, col, row, ap->old[col + mrow]);
}
mrow += ap->nrows;
}
}
#endif
static short
fromTableDirection(unsigned char dir, int local_neighbors)
{
/* Crafted to work for odd number of neighbors */
switch (dir) {
case FS:
return 0;
case TLS:
return (ANGLES / local_neighbors);
case THLS:
return (2 * ANGLES / local_neighbors);
case TBS:
return ((local_neighbors / 2) * ANGLES / local_neighbors);
case THRS:
return (ANGLES - 2 * ANGLES / local_neighbors);
case TRS:
return (ANGLES - ANGLES / local_neighbors);
case SF:
return ANGLES;
case STL:
return (ANGLES + ANGLES / local_neighbors);
case STHL:
return (ANGLES + 2 * ANGLES / local_neighbors);
case STB:
return (ANGLES + (local_neighbors / 2) * ANGLES / local_neighbors);
case STHR:
return (2 * ANGLES - 2 * ANGLES / local_neighbors);
case STR:
return (2 * ANGLES - ANGLES / local_neighbors);
default:
(void) fprintf(stderr, "wrong direction %d from table\n", dir);
}
return -1;
}
static void
getTable(ModeInfo * mi, int i)
{
antfarmstruct *ap = &antfarms[MI_SCREEN(mi)];
int j, total;
unsigned char *patptr;
statestruct *status;
patptr = &tables[i][0];
ap->ncolors = *patptr++;
ap->nstates = *patptr++;
total = ap->ncolors * ap->nstates;
if (MI_IS_VERBOSE(mi))
(void) fprintf(stdout,
"ants %d, neighbors %d, table number %d, colors %d, states %d\n",
ap->n, ap->neighbors, i, ap->ncolors, ap->nstates);
if (label)
(void) sprintf(ap->ruleString, "table number %d", i);
for (j = 0; j < total; j++) {
status = &(ap->machine[j]);
status->color = *patptr++;
if (ap->sharpturn && ap->neighbors > 4) {
int k = *patptr++;
switch (k) {
case TRS:
k = THRS;
break;
case THRS:
k = TRS;
break;
case THLS:
k = TLS;
break;
case TLS:
k = THLS;
break;
case STR:
k = STHR;
break;
case STHR:
k = STR;
break;
case STHL:
k = STL;
break;
case STL:
k = STHL;
break;
default:
break;
}
status->direction = fromTableDirection(k, ap->neighbors);
} else {
status->direction = fromTableDirection(*patptr++, ap->neighbors);
}
status->next = *patptr++;
}
ap->truchet = False;
}
static void
getTurk(ModeInfo * mi, int logClass, int number)
{
antfarmstruct *ap = &antfarms[MI_SCREEN(mi)];
int power2, j, total;
power2 = 1 << (logClass - 1);
ap->ncolors = logClass;
ap->nstates = 1;
total = ap->ncolors * ap->nstates;
for (j = 0; j < total; j++) {
ap->machine[j].color = (j + 1) % total;
if (ap->sharpturn && ap->neighbors > 4) {
ap->machine[j].direction = (power2 & number) ?
fromTableDirection(THRS, ap->neighbors) :
fromTableDirection(THLS, ap->neighbors);
} else {
ap->machine[j].direction = (power2 & number) ?
fromTableDirection(TRS, ap->neighbors) :
fromTableDirection(TLS, ap->neighbors);
}
ap->machine[j].next = 0;
power2 >>= 1;
}
ap->truchet = (ap->truchet && ap->xs > 2 && ap->ys > 2 &&
(ap->neighbors == 3 || ap->neighbors == 4 || ap->neighbors == 6));
if (MI_IS_VERBOSE(mi))
(void) fprintf(stdout,
"ants %d, neighbors %d, Turk's number 0x%x, colors %d\n",
ap->n, ap->neighbors, number, ap->ncolors);
if (label)
(void) sprintf(ap->ruleString, "Turk's number 0x%x", number);
}
static void
parseRule(ModeInfo * mi)
{
if (rule) {
int n = 0, l, number = 0, logClass = 0, power2;
Bool aZero = False;
while (rule[n]) {
if (rule[n] == 'T' || rule[n] == 't') {
n++;
while (rule[n]) {
number = number * 10 +
(int) (rule[n] - '0');
n++;
}
getTable(mi, number);
return;
}
if (rule[n] == 'A' || rule[n] == 'a') {
if (!NRAND(NUMSTIPPLES)) {
getTable(mi, (int) (NRAND(NTABLES)));
return;
} else {
logClass = (int) (NRAND(NUMSTIPPLES - 2)) + 2;
/* <logClass = 4;> has 4 binary digits */
power2 = 1 << (logClass - 1);
/* Do not want numbers which in binary are all 1's. */
number = NRAND(power2 - 1) + power2;
getTurk(mi, logClass, number);
return;
}
} else {
l = rule[n] - '0';
if (l >= 0 && l <= 1) {
number = (number << 1) + l;
if (logClass > 0 || l != 0)
logClass++;
if (logClass > 0 && l == 0)
aZero = True;
}
}
n++;
}
if (!aZero) {
getTurk(mi, 2, 2); /* Default to Langton's ant */
} else {
getTurk(mi, logClass, number);
}
}
}
static void
free_ant(Display *display, antfarmstruct *ap)
{
int shade;
if (ap->stippledGC != None) {
XFreeGC(display, ap->stippledGC);
ap->stippledGC = None;
}
for (shade = 0; shade < ap->init_bits; shade++) {
XFreePixmap(display, ap->pixmaps[shade]);
}
ap->init_bits = 0;
if (ap->tape != NULL) {
free(ap->tape);
ap->tape = (unsigned char *) NULL;
}
if (ap->ants != NULL) {
free(ap->ants);
ap->ants = (antstruct *) NULL;
}
if (ap->truchet_state != NULL) {
free(ap->truchet_state);
ap->truchet_state = (unsigned char *) NULL;
}
}
void
init_ant(ModeInfo * mi)
{
Display *display = MI_DISPLAY(mi);
Window window = MI_WINDOW(mi);
int size = MI_SIZE(mi);
antfarmstruct *ap;
int col, row, dir;
int i;
if (antfarms == NULL) {
if ((antfarms = (antfarmstruct *) calloc(MI_NUM_SCREENS(mi),
sizeof (antfarmstruct))) == NULL)
return;
}
ap = &antfarms[MI_SCREEN(mi)];
ap->redrawing = 0;
if (MI_NPIXELS(mi) <= 2) {
if (ap->stippledGC == None) {
XGCValues gcv;
gcv.fill_style = FillOpaqueStippled;
if ((ap->stippledGC = XCreateGC(display, window,
GCFillStyle, &gcv)) == None) {
free_ant(display, ap);
return;
}
}
if (ap->init_bits == 0) {
for (i = 1; i < NUMSTIPPLES; i++) {
ANTBITS(stipples[i], STIPPLESIZE, STIPPLESIZE);
}
}
}
ap->generation = 0;
ap->n = MI_COUNT(mi);
if (ap->n < -MINANTS) {
/* if ap->n is random ... the size can change */
if (ap->ants != NULL) {
free(ap->ants);
ap->ants = (antstruct *) NULL;
}
ap->n = NRAND(-ap->n - MINANTS + 1) + MINANTS;
} else if (ap->n < MINANTS)
ap->n = MINANTS;
ap->width = MI_WIDTH(mi);
ap->height = MI_HEIGHT(mi);
for (i = 0; i < NEIGHBORKINDS; i++) {
if (neighbors == plots[i]) {
ap->neighbors = plots[i];
break;
}
if (i == NEIGHBORKINDS - 1) {
if (!NRAND(10)) {
/* Make above 6 rare */
ap->neighbors = plots[NRAND(NEIGHBORKINDS)];
} else {
ap->neighbors = plots[NRAND(GOODNEIGHBORKINDS)];
}
break;
}
}
if (ap->neighbors == 6) {
int nccols, ncrows;
if (ap->width < 8)
ap->width = 8;
if (ap->height < 8)
ap->height = 8;
if (size < -MINSIZE) {
ap->ys = NRAND(MIN(-size, MAX(MINSIZE, MIN(ap->width, ap->height) /
MINGRIDSIZE)) - MINSIZE + 1) + MINSIZE;
if (ap->ys < MINRANDOMSIZE)
ap->ys = MIN(MINRANDOMSIZE,
MAX(MINSIZE, MIN(ap->width, ap->height) / MINGRIDSIZE));
} else if (size < MINSIZE) {
if (!size)
ap->ys = MAX(MINSIZE, MIN(ap->width, ap->height) / MINGRIDSIZE);
else
ap->ys = MINSIZE;
} else
ap->ys = MIN(size, MAX(MINSIZE, MIN(ap->width, ap->height) /
MINGRIDSIZE));
ap->xs = ap->ys;
nccols = MAX(ap->width / ap->xs - 2, 2);
ncrows = MAX(ap->height / ap->ys - 1, 4);
ap->ncols = nccols / 2;
ap->nrows = 2 * (ncrows / 4);
ap->xb = (ap->width - ap->xs * nccols) / 2 + ap->xs / 2;
ap->yb = (ap->height - ap->ys * (ncrows / 2) * 2) / 2 + ap->ys - 2;
for (i = 0; i < 6; i++) {
ap->shape.hexagon[i].x = (ap->xs - 1) * hexagonUnit[i].x;
ap->shape.hexagon[i].y = ((ap->ys - 1) * hexagonUnit[i].y / 2) * 4 / 3;
}
/* Avoid array bounds read of hexagonUnit */
ap->shape.hexagon[6].x = 0;
ap->shape.hexagon[6].y = 0;
} else if (ap->neighbors == 4 || ap->neighbors == 8) {
if (size < -MINSIZE) {
ap->ys = NRAND(MIN(-size, MAX(MINSIZE, MIN(ap->width, ap->height) /
MINGRIDSIZE)) - MINSIZE + 1) + MINSIZE;
if (ap->ys < MINRANDOMSIZE)
ap->ys = MIN(MINRANDOMSIZE,
MAX(MINSIZE, MIN(ap->width, ap->height) / MINGRIDSIZE));
} else if (size < MINSIZE) {
if (!size)
ap->ys = MAX(MINSIZE, MIN(ap->width, ap->height) / MINGRIDSIZE);
else
ap->ys = MINSIZE;
} else
ap->ys = MIN(size, MAX(MINSIZE, MIN(ap->width, ap->height) /
MINGRIDSIZE));
ap->xs = ap->ys;
ap->ncols = MAX(ap->width / ap->xs, 2);
ap->nrows = MAX(ap->height / ap->ys, 2);
ap->xb = (ap->width - ap->xs * ap->ncols) / 2;
ap->yb = (ap->height - ap->ys * ap->nrows) / 2;
} else { /* TRI */
int orient;
if (ap->width < 2)
ap->width = 2;
if (ap->height < 2)
ap->height = 2;
if (size < -MINSIZE) {
ap->ys = NRAND(MIN(-size, MAX(MINSIZE, MIN(ap->width, ap->height) /
MINGRIDSIZE)) - MINSIZE + 1) + MINSIZE;
if (ap->ys < MINRANDOMSIZE)
ap->ys = MIN(MINRANDOMSIZE,
MAX(MINSIZE, MIN(ap->width, ap->height) / MINGRIDSIZE));
} else if (size < MINSIZE) {
if (!size)
ap->ys = MAX(MINSIZE, MIN(ap->width, ap->height) / MINGRIDSIZE);
else
ap->ys = MINSIZE;
} else
ap->ys = MIN(size, MAX(MINSIZE, MIN(ap->width, ap->height) /
MINGRIDSIZE));
ap->xs = (int) (1.52 * ap->ys);
ap->ncols = (MAX(ap->width / ap->xs - 1, 2) / 2) * 2;
ap->nrows = (MAX(ap->height / ap->ys - 1, 2) / 2) * 2;
ap->xb = (ap->width - ap->xs * ap->ncols) / 2 + ap->xs / 2;
ap->yb = (ap->height - ap->ys * ap->nrows) / 2 + ap->ys;
for (orient = 0; orient < 2; orient++) {
for (i = 0; i < 3; i++) {
ap->shape.triangle[orient][i].x =
(ap->xs - 2) * triangleUnit[orient][i].x;
ap->shape.triangle[orient][i].y =
(ap->ys - 2) * triangleUnit[orient][i].y;
}
/* Avoid array bounds read of triangleUnit */
ap->shape.triangle[orient][3].x = 0;
ap->shape.triangle[orient][3].y = 0;
}
}
XSetLineAttributes(display, MI_GC(mi), 1, LineSolid, CapNotLast, JoinMiter);
MI_CLEARWINDOW(mi);
ap->painted = False;
if (MI_IS_FULLRANDOM(mi)) {
ap->truchet = (Bool) (LRAND() & 1);
ap->eyes = (Bool) (LRAND() & 1);
ap->sharpturn = (Bool) (LRAND() & 1);
} else {
ap->truchet = truchet;
ap->eyes = eyes;
ap->sharpturn = sharpturn;
}
ap->labelOffsetX = NRAND(8);
ap->labelOffsetY = NRAND(8);
parseRule(mi);
if (MI_NPIXELS(mi) > 2)
for (i = 0; i < (int) ap->ncolors - 1; i++)
ap->colors[i] = (unsigned char) (NRAND(MI_NPIXELS(mi)) +
i * MI_NPIXELS(mi)) / ((int) (ap->ncolors - 1));
if (ap->ants == NULL) {
if ((ap->ants = (antstruct *) malloc(ap->n * sizeof (antstruct))) ==
NULL) {
free_ant(display, ap);
return;
}
}
if (ap->tape != NULL)
free(ap->tape);
if ((ap->tape = (unsigned char *) calloc(ap->ncols * ap->nrows,
sizeof (unsigned char))) == NULL) {
free_ant(display, ap);
return;
}
if (ap->truchet_state != NULL)
free(ap->truchet_state);
if ((ap->truchet_state = (unsigned char *) calloc(ap->ncols * ap->nrows,
sizeof (unsigned char))) == NULL) {
free_ant(display, ap);
return;
}
row = ap->nrows / 2;
col = ap->ncols / 2;
if (col > 0 && ((ap->neighbors % 2) || ap->neighbors == 12) && (LRAND() & 1))
col--;
dir = NRAND(ap->neighbors) * ANGLES / ap->neighbors;
ap->init_dir = dir;
#ifdef NUMBER_9
if (ap->neighbors == 9 && !((col + row) & 1))
dir = (dir + ANGLES - ANGLES / (ap->neighbors * 2)) % ANGLES;
#endif
/* Have them all start in the same spot, why not? */
for (i = 0; i < ap->n; i++) {
ap->ants[i].col = col;
ap->ants[i].row = row;
ap->ants[i].direction = dir;
ap->ants[i].state = 0;
}
draw_anant(mi, dir, col, row);
}
void
draw_ant(ModeInfo * mi)
{
antstruct *anant;
statestruct *status;
int i, state_pos, tape_pos;
unsigned char color;
short chg_dir, old_dir;
antfarmstruct *ap;
if (antfarms == NULL)
return;
ap = &antfarms[MI_SCREEN(mi)];
if (ap->ants == NULL)
return;
MI_IS_DRAWN(mi) = True;
ap->painted = True;
for (i = 0; i < ap->n; i++) {
anant = &ap->ants[i];
tape_pos = anant->col + anant->row * ap->ncols;
color = ap->tape[tape_pos]; /* read tape */
state_pos = color + anant->state * ap->ncolors;
status = &(ap->machine[state_pos]);
drawcell(mi, anant->col, anant->row, status->color);
ap->tape[tape_pos] = status->color; /* write on tape */
/* Find direction of Bees or Ants. */
/* Translate relative direction to actual direction */
old_dir = anant->direction;
chg_dir = (2 * ANGLES - status->direction) % ANGLES;
anant->direction = (chg_dir + old_dir) % ANGLES;
if (ap->truchet) {
int a = 0, b;
if (ap->neighbors == 6) {
if (ap->sharpturn) {
a = (((ANGLES + anant->direction - old_dir) % ANGLES) == 240);
/* should be some way of getting rid of the init_dir dependency... */
b = !(ap->init_dir % 120);
a = ((a && !b) || (b && !a));
drawtruchet(mi, anant->col, anant->row, status->color, a);
} else {
a = (old_dir / 60) % 3;
b = (anant->direction / 60) % 3;
a = (a + b + 1) % 3;
drawtruchet(mi, anant->col, anant->row, status->color, a);
}
} else if (ap->neighbors == 4) {
a = old_dir / 180;
b = anant->direction / 180;
a = ((a && !b) || (b && !a));
drawtruchet(mi, anant->col, anant->row, status->color, a);
} else if (ap->neighbors == 3) {
if (chg_dir == 240)
a = (2 + anant->direction / 120) % 3;
else
a = (1 + anant->direction / 120) % 3;
drawtruchet(mi, anant->col, anant->row, status->color, a);
}
ap->truchet_state[tape_pos] = a + 1;
}
anant->state = status->next;
/* Allow step first then turn */
old_dir = ((status->direction < ANGLES) ? anant->direction : old_dir);
#ifdef DEBUG
(void) printf("old_dir %d, col %d, row %d", old_dir, anant->col, anant->row);
#endif
position_of_neighbor(ap, old_dir, &(anant->col), &(anant->row));
#ifdef DEBUG
(void) printf(", ncol %d, nrow %d\n", anant->col, anant->row);
#endif
draw_anant(mi, anant->direction, anant->col, anant->row);
}
if (++ap->generation > MI_CYCLES(mi)) {
init_ant(mi);
}
if (ap->redrawing) {
for (i = 0; i < REDRAWSTEP; i++) {
if (ap->tape[ap->redrawpos] ||
(ap->truchet && ap->truchet_state[ap->redrawpos])) {
drawcell(mi, ap->redrawpos % ap->ncols, ap->redrawpos / ap->ncols,
ap->tape[ap->redrawpos]);
if (ap->truchet)
drawtruchet(mi, ap->redrawpos % ap->ncols, ap->redrawpos / ap->ncols,
ap->tape[ap->redrawpos],
ap->truchet_state[ap->redrawpos] - 1);
}
if (++(ap->redrawpos) >= ap->ncols * ap->nrows) {
ap->redrawing = 0;
break;
}
}
}
if (label) {
int size = MAX(MIN(MI_WIDTH(mi), MI_HEIGHT(mi)) - 1, 1);
if (size >= 10 * FONT_WIDTH) {
/* hard code these to corners */
XSetForeground(MI_DISPLAY(mi), MI_GC(mi),
MI_WHITE_PIXEL(mi));
/*XDrawString(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
16 + ap->labelOffsetX,
16 + ap->labelOffsetY + FONT_HEIGHT,
ap->ruleString, strlen(ap->ruleString)); */
XDrawString(MI_DISPLAY(mi), MI_WINDOW(mi), MI_GC(mi),
16 + ap->labelOffsetX, MI_HEIGHT(mi) - 16 -
ap->labelOffsetY - FONT_HEIGHT / 2,
ap->ruleString, strlen(ap->ruleString));
}
}
}
void
release_ant(ModeInfo * mi)
{
if (antfarms != NULL) {
int screen;
for (screen = 0; screen < MI_NUM_SCREENS(mi); screen++)
free_ant(MI_DISPLAY(mi), &antfarms[screen]);
free(antfarms);
antfarms = (antfarmstruct *) NULL;
}
}
void
refresh_ant(ModeInfo * mi)
{
antfarmstruct *ap;
if (antfarms == NULL)
return;
ap = &antfarms[MI_SCREEN(mi)];
if (ap->painted) {
MI_CLEARWINDOW(mi);
ap->redrawing = 1;
ap->redrawpos = 0;
}
}
#endif /* MODE_ant */
|
23cf187f794fa32e3decb73fff6a16fde859b22d
|
83372fce92c9088ee5c1e1c13bc67385a3b02a36
|
/src/cc65/locals.h
|
53d08447ce5eaa6b2dd596bbc2c19ccdfaf04063
|
[
"Zlib",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
cc65/cc65
|
2cd1b20b61ddd0691cd4601b4da37a9200a50afb
|
16e90187e8e80c6e2fcfcc04f068ac865d2290e5
|
refs/heads/master
| 2023-09-03T17:16:46.027934
| 2023-09-02T22:30:44
| 2023-09-02T22:30:44
| 8,932,489
| 2,103
| 526
|
Zlib
| 2023-09-13T06:19:01
| 2013-03-21T15:56:48
|
C
|
UTF-8
|
C
| false
| false
| 3,322
|
h
|
locals.h
|
/*****************************************************************************/
/* */
/* locals.h */
/* */
/* Local variable handling for the cc65 C compiler */
/* */
/* */
/* */
/* (C) 2000-2001 Ullrich von Bassewitz */
/* Wacholderweg 14 */
/* D-70597 Stuttgart */
/* EMail: uz@cc65.org */
/* */
/* */
/* This software is provided 'as-is', without any expressed or implied */
/* warranty. In no event will the authors be held liable for any damages */
/* arising from the use of this software. */
/* */
/* Permission is granted to anyone to use this software for any purpose, */
/* including commercial applications, and to alter it and redistribute it */
/* freely, subject to the following restrictions: */
/* */
/* 1. The origin of this software must not be misrepresented; you must not */
/* claim that you wrote the original software. If you use this software */
/* in a product, an acknowledgment in the product documentation would be */
/* appreciated but is not required. */
/* 2. Altered source versions must be plainly marked as such, and must not */
/* be misrepresented as being the original software. */
/* 3. This notice may not be removed or altered from any source */
/* distribution. */
/* */
/*****************************************************************************/
#ifndef LOCALS_H
#define LOCALS_H
/*****************************************************************************/
/* Code */
/*****************************************************************************/
void InitRegVars (void);
/* Initialize register variable control data */
void DoneRegVars (void);
/* Free the register variables */
void DeclareLocals (void);
/* Declare local variables and types. */
void RestoreRegVars (int HaveResult);
/* Restore the register variables for the local function if there are any.
** The parameter tells us if there is a return value in ax, in that case,
** the accumulator must be saved across the restore.
*/
/* End of locals.h */
#endif
|
cd3b12bd0f3f47e677edfeb3b06bcae24f1839f5
|
cc91a1c30f6c5a176b225bdbf96c7bfd6dfeca52
|
/framework/delibs/debase/deInt32Test.c
|
a79d08e63b090be6ba5dfdbb2d2f5ddf67783180
|
[
"Apache-2.0"
] |
permissive
|
KhronosGroup/VK-GL-CTS
|
d07b2611dc3a258b5be4ff87c1fe55623f32bac1
|
a745d5c29c5609cb7805f59444520a7700cf39d1
|
refs/heads/main
| 2023-08-31T19:34:48.447202
| 2023-08-25T13:17:54
| 2023-08-25T13:17:54
| 50,466,830
| 454
| 267
|
Apache-2.0
| 2023-09-02T20:49:14
| 2016-01-26T23:29:28
|
C++
|
UTF-8
|
C
| false
| false
| 6,649
|
c
|
deInt32Test.c
|
/*-------------------------------------------------------------------------
* drawElements Base Portability Library
* -------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Testing of deInt32 functions.
*//*--------------------------------------------------------------------*/
#include "deInt32.h"
#include "deRandom.h"
#include <stdio.h> /* printf() */
DE_BEGIN_EXTERN_C
void deInt32_computeLUTs (void)
{
enum
{
RCP_LUT_BITS = 8
};
int ndx;
printf("enum { RCP_LUT_BITS = %d };\n", RCP_LUT_BITS);
printf("static const deUint32 s_rcpLUT[1<<RCP_LUT_BITS] =\n");
printf("{\n");
for (ndx = 0; ndx < (1<<RCP_LUT_BITS); ndx++)
{
deUint32 val = (1u << RCP_LUT_BITS) | (deUint32)ndx;
deUint32 rcp = (deUint32)((1u << DE_RCP_FRAC_BITS) / ((double)val / (1<<RCP_LUT_BITS)));
if ((ndx & 3) == 0)
printf("\t");
printf("0x%08x", rcp);
if ((ndx & 3) == 3)
{
if (ndx != (1<<RCP_LUT_BITS)-1)
printf(",");
printf("\n");
}
else
printf(", ");
}
printf("};\n");
}
void deInt32_selfTest (void)
{
const int NUM_ACCURATE_BITS = 29;
deRandom rnd;
deUint32 rcp;
int exp;
int numBits;
deRandom_init(&rnd, 0xdeadbeefu-1);
/* Test deClz32(). */
{
int i;
for (i = 0; i < 32; i++)
{
DE_TEST_ASSERT(deClz32(1u << i) == 31-i);
DE_TEST_ASSERT(deClz32((1u << i) | ((1u << i)-1u)) == 31-i);
}
}
DE_TEST_ASSERT(deClz32(0) == 32);
DE_TEST_ASSERT(deClz32(1) == 31);
DE_TEST_ASSERT(deClz32(0xF1) == 24);
DE_TEST_ASSERT(deClz32(0xBC12) == 16);
DE_TEST_ASSERT(deClz32(0xABBACD) == 8);
DE_TEST_ASSERT(deClz32(0x10000000) == 3);
DE_TEST_ASSERT(deClz32(0x20000000) == 2);
DE_TEST_ASSERT(deClz32(0x40000000) == 1);
DE_TEST_ASSERT(deClz32(0x80000000) == 0);
/* Test deCtz32(). */
{
int i;
for (i = 0; i < 32; i++)
{
DE_TEST_ASSERT(deCtz32(1u << i) == i);
DE_TEST_ASSERT(deCtz32(~((1u << i)-1u)) == i);
}
}
DE_TEST_ASSERT(deCtz32(0) == 32);
DE_TEST_ASSERT(deCtz32(1) == 0);
DE_TEST_ASSERT(deCtz32(0x3F4) == 2);
DE_TEST_ASSERT(deCtz32(0x3F40) == 6);
DE_TEST_ASSERT(deCtz32(0xFFFFFFFF) == 0);
/* Test simple inputs for dePop32(). */
DE_TEST_ASSERT(dePop32(0u) == 0);
DE_TEST_ASSERT(dePop32(~0u) == 32);
DE_TEST_ASSERT(dePop32(0xFF) == 8);
DE_TEST_ASSERT(dePop32(0xFF00FF) == 16);
DE_TEST_ASSERT(dePop32(0x3333333) == 14);
DE_TEST_ASSERT(dePop32(0x33333333) == 16);
/* dePop32(): Check exp2(N) values and inverses. */
for (numBits = 0; numBits < 32; numBits++)
{
DE_TEST_ASSERT(dePop32(1u<<numBits) == 1);
DE_TEST_ASSERT(dePop32(~(1u<<numBits)) == 31);
}
/* Check exp2(N) values. */
for (numBits = 0; numBits < 32; numBits++)
{
deUint32 val = (1u<<numBits);
deRcp32(val, &rcp, &exp);
DE_TEST_ASSERT(rcp == (1u<<DE_RCP_FRAC_BITS));
DE_TEST_ASSERT(exp == numBits);
}
/* Check random values. */
for (numBits = 0; numBits < 32; numBits++)
{
int NUM_ITERS = deMax32(16, 1 << (numBits/2));
int iter;
for (iter = 0; iter < NUM_ITERS; iter++)
{
const deUint32 EPS = 1u << (DE_RCP_FRAC_BITS - NUM_ACCURATE_BITS);
deUint32 val = (deRandom_getUint32(&rnd) & ((1u<<numBits)-1)) | (1u<<numBits);
deUint32 ref = (deUint32)(((1.0f / (double)val) * (double)(1<<DE_RCP_FRAC_BITS)) * (double)(1u<<numBits));
deRcp32(val, &rcp, &exp);
DE_TEST_ASSERT(rcp >= ref-EPS && rcp < ref+EPS);
DE_TEST_ASSERT(exp == numBits);
}
}
DE_TEST_ASSERT(deBitMask32(0, 0) == 0);
DE_TEST_ASSERT(deBitMask32(8, 0) == 0);
DE_TEST_ASSERT(deBitMask32(16, 0) == 0);
DE_TEST_ASSERT(deBitMask32(31, 0) == 0);
DE_TEST_ASSERT(deBitMask32(32, 0) == 0);
DE_TEST_ASSERT(deBitMask32(0, 2) == 3);
DE_TEST_ASSERT(deBitMask32(0, 32) == 0xFFFFFFFFu);
DE_TEST_ASSERT(deBitMask32(16, 16) == 0xFFFF0000u);
DE_TEST_ASSERT(deBitMask32(31, 1) == 0x80000000u);
DE_TEST_ASSERT(deBitMask32(8, 4) == 0xF00u);
DE_TEST_ASSERT(deUintMaxValue32(1) == 1);
DE_TEST_ASSERT(deUintMaxValue32(2) == 3);
DE_TEST_ASSERT(deUintMaxValue32(32) == 0xFFFFFFFFu);
DE_TEST_ASSERT(deIntMaxValue32(1) == 0);
DE_TEST_ASSERT(deIntMaxValue32(2) == 1);
DE_TEST_ASSERT(deIntMaxValue32(32) == 0x7FFFFFFF);
DE_TEST_ASSERT(deIntMinValue32(1) == -1);
DE_TEST_ASSERT(deIntMinValue32(2) == -2);
DE_TEST_ASSERT(deIntMinValue32(32) == -0x7FFFFFFF - 1);
DE_TEST_ASSERT(deSignExtendTo32((int)0x0, 1) == 0);
DE_TEST_ASSERT(deSignExtendTo32((int)0x1, 1) == (int)0xFFFFFFFF);
DE_TEST_ASSERT(deSignExtendTo32((int)0x3, 3) == 3);
DE_TEST_ASSERT(deSignExtendTo32((int)0x6, 3) == (int)0xFFFFFFFE);
DE_TEST_ASSERT(deSignExtendTo32((int)0x3, 4) == 3);
DE_TEST_ASSERT(deSignExtendTo32((int)0xC, 4) == (int)0xFFFFFFFC);
DE_TEST_ASSERT(deSignExtendTo32((int)0x7FC3, 16) == (int)0x7FC3);
DE_TEST_ASSERT(deSignExtendTo32((int)0x84A0, 16) == (int)0xFFFF84A0);
DE_TEST_ASSERT(deSignExtendTo32((int)0xFFC3, 17) == (int)0xFFC3);
DE_TEST_ASSERT(deSignExtendTo32((int)0x184A0, 17) == (int)0xFFFF84A0);
DE_TEST_ASSERT(deSignExtendTo32((int)0x7A016601, 32) == (int)0x7A016601);
DE_TEST_ASSERT(deSignExtendTo32((int)0x8A016601, 32) == (int)0x8A016601);
DE_TEST_ASSERT(deReverseBytes32(0x11223344) == 0x44332211);
DE_TEST_ASSERT(deReverseBytes32(0xfecddeef) == 0xefdecdfe);
DE_TEST_ASSERT(deReverseBytes16(0x1122) == 0x2211);
DE_TEST_ASSERT(deReverseBytes16(0xdeef) == 0xefde);
DE_TEST_ASSERT(deInt64InInt32Range((deInt64)0x7FFFFFF));
DE_TEST_ASSERT(deInt64InInt32Range(0));
DE_TEST_ASSERT(deInt64InInt32Range(1));
DE_TEST_ASSERT(deInt64InInt32Range(-1));
DE_TEST_ASSERT(deInt64InInt32Range(-((deInt64)0x7FFFFFF)));
DE_TEST_ASSERT(deInt64InInt32Range(-((deInt64)0x8000 << 16)));
DE_TEST_ASSERT(deInt64InInt32Range((deInt64)deIntMinValue32(32)));
DE_TEST_ASSERT(!deInt64InInt32Range((((deInt64)0x7FFFFFF) << 32) | (deInt64)0xFFFFFFFF));
DE_TEST_ASSERT(!deInt64InInt32Range((deInt64)0x7FFFFFFF + 1));
DE_TEST_ASSERT(!deInt64InInt32Range(-((deInt64)0x7FFFFFFF + 2)));
DE_TEST_ASSERT(!deInt64InInt32Range(-((((deInt64)0x7FFFFFF) << 32) | (deInt64)0xFFFFFFFF)));
DE_TEST_ASSERT(!deInt64InInt32Range((deInt64)deIntMinValue32(32) - 1));
}
DE_END_EXTERN_C
|
01c7ebbb4af9ea39d6b856c63a5be51805fde9f0
|
fd016aacb50a65dbda2f0e2b35cec38a63baf68d
|
/targets/TI_SimpleLink/_nanoCLR/targetSimpleLinkCC32xx_Sntp.c
|
aa13e3b190be35954477e5f9c251d58640a3c7d6
|
[
"MIT"
] |
permissive
|
nanoframework/nf-interpreter
|
4795563afe8b1d8e4819a4b4ebd700c9e36a4d80
|
2ebb0aeef2d9482a6233e4c78f562878ba726cf6
|
refs/heads/main
| 2023-08-29T11:30:31.384324
| 2023-08-29T10:55:46
| 2023-08-29T10:55:46
| 74,834,622
| 283
| 266
|
MIT
| 2023-09-14T00:22:43
| 2016-11-26T15:45:06
|
C
|
UTF-8
|
C
| false
| false
| 11,549
|
c
|
targetSimpleLinkCC32xx_Sntp.c
|
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Texas Instruments Incorporated. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include <targetSimpleLinkCC32xx_Sntp.h>
#include <targetSimpleLinkCC32xx_Threads.h>
#include <targetSimpleLinkCC32xx_ProvisioningTask.h>
// POSIX Header files
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <ti/drivers/net/wifi/slnetifwifi.h>
#include <ti/net/slnetsock.h>
// nanoFramework header files
#include <targetHAL.h>
static struct sntp_server SNTP_ServersList[NTP_SERVERS];
pthread_t sntpWorkingThread = (pthread_t)NULL;
void *SntpWorkingThread(void *arg0);
void sntp_init(void)
{
struct sched_param priorityParams;
pthread_attr_t threadAttributes;
int retc;
if (sntpWorkingThread == NULL)
{
pthread_attr_init(&threadAttributes);
priorityParams.sched_priority = NF_TASK_PRIORITY;
retc = pthread_attr_setschedparam(&threadAttributes, &priorityParams);
retc |= pthread_attr_setstacksize(&threadAttributes, 1024);
if (retc != 0)
{
// failed to set attributes
while (1)
{
}
}
retc = pthread_create(&sntpWorkingThread, &threadAttributes, SntpWorkingThread, NULL);
if (retc != 0)
{
// pthread_create() failed
HAL_AssertEx();
UART_PRINT("Unable to create SNTP thread \n");
while (1)
{
;
}
}
}
}
void sntp_stop(void)
{
pthread_cancel(sntpWorkingThread);
sntpWorkingThread = NULL;
}
bool sntp_enabled(void)
{
return (sntpWorkingThread != NULL) ? true : false;
}
char *sntp_getservername(int index)
{
if (index < NTP_SERVERS)
{
return SNTP_ServersList[index].name;
}
return NULL;
}
void sntp_setservername(int index, char *server)
{
if (index < NTP_SERVERS)
{
SNTP_ServersList[index].name = server;
}
}
static int32_t getAddrByName(const char *name, uint32_t *addr, uint16_t *family)
{
int32_t ifID;
uint16_t addrLen = 1;
/* Query DNS for IPv4 address. */
ifID = SlNetUtil_getHostByName(0, (char *)name, strlen(name), addr, &addrLen, SLNETSOCK_AF_INET);
if (ifID < 0)
{
/* If call fails, try again for IPv6. */
ifID = SlNetUtil_getHostByName(0, (char *)name, strlen(name), addr, &addrLen, SLNETSOCK_AF_INET6);
if (ifID < 0)
{
/* return an error */
return -1;
}
else
{
*family = SLNETSOCK_AF_INET6;
}
}
else
{
*family = SLNETSOCK_AF_INET;
}
/* Return the interface ID */
return (ifID);
}
static int32_t hasKissCode(char *str)
{
if (strncmp((char *)SNTP_KOD_RATE_STR, str, SNTP_KOD_ERROR_CODE_SIZE) == 0)
{
return (SNTP_KOD_RATE_CODE);
}
else if (strncmp((char *)SNTP_KOD_DENY_STR, str, SNTP_KOD_ERROR_CODE_SIZE) == 0)
{
return (SNTP_KOD_DENY_CODE);
}
else if (strncmp((char *)SNTP_KOD_RSTR_STR, str, SNTP_KOD_ERROR_CODE_SIZE) == 0)
{
return (SNTP_KOD_RSTR_CODE);
}
else
{
return (0);
}
}
static int32_t getTime(SlNetSock_Addr_t *server, uint16_t ifID, SlNetSock_Timeval_t *timeout, uint64_t *ntpTimeStamp)
{
SNTP_Header_t sntpPkt;
int32_t ret = 0;
int16_t sd = -1;
SlNetSocklen_t saLen;
uint32_t integrityCheck;
struct timespec tspec;
if (server->sa_family == SLNETSOCK_AF_INET)
{
saLen = sizeof(SlNetSock_AddrIn_t);
}
else if (server->sa_family == SLNETSOCK_AF_INET6)
{
saLen = sizeof(SlNetSock_AddrIn6_t);
}
else
{
return (SNTP_EINVALIDFAMILY);
}
/* Create a UDP socket to communicate with NTP server */
sd = SlNetSock_create(server->sa_family, SLNETSOCK_SOCK_DGRAM, SLNETSOCK_PROTO_UDP, ifID, 0);
if (sd < 0)
{
return (SNTP_ESOCKCREATEFAIL);
}
ret = SlNetSock_connect(sd, server, saLen);
if (ret < 0)
{
SlNetSock_close(sd);
return (SNTP_ECONNECTFAIL);
}
if (timeout != NULL)
{
/* Set the timeout for the server response to the user's value */
ret = SlNetSock_setOpt(
sd,
SLNETSOCK_LVL_SOCKET,
SLNETSOCK_OPSOCK_RCV_TIMEO,
timeout,
sizeof(SlNetSock_Timeval_t));
if (ret < 0)
{
SlNetSock_close(sd);
return (SNTP_ESOCKOPTFAIL);
}
}
/* Initialize the SNTP packet, setting version and mode = client */
memset(&sntpPkt, 0, sizeof(SNTP_Header_t));
sntpPkt.flags = SNTP_VERSION << 3;
sntpPkt.flags |= SNTP_MODE_CLIENT;
/* Set packet's transmit time as integrity check value */
clock_gettime(CLOCK_REALTIME, &tspec);
integrityCheck = tspec.tv_sec;
sntpPkt.transmitTS[0] = integrityCheck;
/* Send out our SNTP request to the current server */
ret = SlNetSock_send(sd, (void *)&sntpPkt, sizeof(SNTP_Header_t), 0);
if (ret < 0)
{
SlNetSock_close(sd);
return (SNTP_ESENDFAIL);
}
memset(&sntpPkt, 0, sizeof(SNTP_Header_t));
/* Retrieve the NTP packet from the socket and update our time. */
ret = SlNetSock_recv(sd, &sntpPkt, sizeof(SNTP_Header_t), 0);
if ((ret < 0) || (ret != sizeof(SNTP_Header_t)) || (sntpPkt.originateTS[0] != integrityCheck))
{
SlNetSock_close(sd);
return (SNTP_ERECVFAIL);
}
/* Check for errors in server response */
if (sntpPkt.stratum == 0)
{
/* Per RFC5905, we MUST handle Kiss O' Death packet */
if ((sntpPkt.flags >> 6) == SNTP_NOSYNC)
{
/* KOD recv'd. Inspect kiss code & handle accordingly */
ret = hasKissCode((char *)&sntpPkt.referenceID);
if (ret == SNTP_KOD_RATE_CODE)
{
SlNetSock_close(sd);
return (SNTP_ERATEBACKOFF);
}
/* Check for fatal kiss codes */
else if ((ret == SNTP_KOD_DENY_CODE) || (ret == SNTP_KOD_RSTR_CODE))
{
SlNetSock_close(sd);
return (SNTP_EFATALNORETRY);
}
/* Per RFC5905, other kiss codes are ignored */
}
else
{
/*
* A server response with stratum == 0, with no kiss
* code, is a fatal error. Mark server as invalid
*/
SlNetSock_close(sd);
return (SNTP_EINVALIDRESP);
}
}
/* return the time in seconds */
sntpPkt.transmitTS[0] = SlNetUtil_ntohl(sntpPkt.transmitTS[0]);
sntpPkt.transmitTS[1] = SlNetUtil_ntohl(sntpPkt.transmitTS[1]);
*ntpTimeStamp = ((uint64_t)sntpPkt.transmitTS[0] << 32) | sntpPkt.transmitTS[1];
SlNetSock_close(sd);
return (0);
}
int32_t SNTP_getTime(SlNetSock_Timeval_t *timeout, uint64_t *ntpTimeStamp)
{
int32_t ret = 0;
int32_t ifID;
SlNetSock_AddrIn_t sa4;
SlNetSock_AddrIn6_t sa6;
SlNetSock_Addr_t *sa;
uint32_t addr[4];
uint16_t family;
uint32_t i;
size_t count = NTP_SERVERS;
for (i = 0; i < count; i++)
{
memset(&addr, 0, sizeof(addr));
ifID = getAddrByName(SNTP_ServersList[i].name, addr, &family);
if (ifID >= 0)
{
if (family == SLNETSOCK_AF_INET)
{
sa4.sin_family = SLNETSOCK_AF_INET;
sa4.sin_port = SlNetUtil_htons(NTP_SERVER_PORT);
sa4.sin_addr.s_addr = SlNetUtil_htonl(addr[0]);
sa = (SlNetSock_Addr_t *)&sa4;
}
else
{
sa6.sin6_family = SLNETSOCK_AF_INET6;
sa6.sin6_port = SlNetUtil_htons(NTP_SERVER_PORT);
sa6.sin6_addr._S6_un._S6_u32[0] = SlNetUtil_htonl(addr[0]);
sa6.sin6_addr._S6_un._S6_u32[1] = SlNetUtil_htonl(addr[1]);
sa6.sin6_addr._S6_un._S6_u32[2] = SlNetUtil_htonl(addr[2]);
sa6.sin6_addr._S6_un._S6_u32[3] = SlNetUtil_htonl(addr[3]);
sa = (SlNetSock_Addr_t *)&sa6;
}
}
else
{
ret = SNTP_EGETHOSTBYNAMEFAIL;
continue;
}
ret = getTime(sa, ifID, timeout, ntpTimeStamp);
if (ret == 0)
{
break;
}
}
return (ret);
}
////////////////////////////////////////////////////////////////////////////////
// SNTP working thread
////////////////////////////////////////////////////////////////////////////////
void *SntpWorkingThread(void *argument)
{
(void)argument;
uint64_t ntpTimeStamp;
uint32_t currentTime;
int32_t retval;
time_t ts;
SlNetSock_Timeval_t timeval;
struct timespec tspec;
// Set timeout value for NTP server reply
timeval.tv_sec = NTP_REPLY_WAIT_TIME;
timeval.tv_usec = 0;
UART_PRINT("[SNTP task] started\n\r");
// delay 1st request, if configured
if (SNTP_STARTUP_DELAY > 0)
{
UART_PRINT("[SNTP task] start delay: %d\n\r", SNTP_STARTUP_DELAY);
ClockP_sleep(SNTP_STARTUP_DELAY);
}
while (1)
{
// need to be connected and have an IP
if (!IS_IP_ACQUIRED(nF_ControlBlock.Status))
{
UART_PRINT("[SNTP task] not connected. Retrying in %d seconds.\n\r", SNTP_RETRY_TIMEOUT);
clock_gettime(CLOCK_REALTIME, &tspec);
tspec.tv_sec += SNTP_RETRY_TIMEOUT;
// wait for connection event with retry timeout
// don't bother checking if it exited on timeout or event
// because the loop is restarted and the check for connection & address is performed
sem_timedwait(&Provisioning_ControlBlock.connectionAsyncEvent, &tspec);
// retrying: start over
continue;
}
UART_PRINT("[SNTP task] getting time...\n\r");
// Get the time use the SNTP_ServersList
retval = SNTP_getTime(&timeval, &ntpTimeStamp);
if (retval != 0)
{
UART_PRINT("[SNTP task] failed to get time. Error: %d\n\r", retval);
clock_gettime(CLOCK_REALTIME, &tspec);
tspec.tv_sec += SNTP_RETRY_TIMEOUT;
// wait for connection event with retry timeout
// don't bother checking if it exited on timeout or event
// because the loop is restarted and the check for connection & address is performed
sem_timedwait(&Provisioning_ControlBlock.connectionAsyncEvent, &tspec);
// retrying: start over
continue;
}
currentTime = ntpTimeStamp >> 32;
currentTime = TIME_NTP_TO_LOCAL(currentTime);
tspec.tv_nsec = 0;
tspec.tv_sec = currentTime;
UART_PRINT("[SNTP task] updated time: %d\n\r", currentTime);
if (clock_settime(CLOCK_REALTIME, &tspec) != 0)
{
// failed to set current time
// don't do anything, just wait for the next attempt
}
// wait for connection event with retry timeout
// don't bother checking if it exited on timeout or event
// because the loop is restarted and the check for connection & address is performed
clock_gettime(CLOCK_REALTIME, &tspec);
tspec.tv_sec += SNTP_UPDATE_DELAY;
sem_timedwait(&Provisioning_ControlBlock.connectionAsyncEvent, &tspec);
}
pthread_exit(0);
}
|
15887cf99945956519e6a64925e4cf56f4cbe53a
|
f3eed0234b4d0ad2bbb2abd700cf1e2c7a0e8a1d
|
/AKWF-c/AKWF_altosax/AKWF_altosax_0025.h
|
654f8c68ae712878a7a9be9e797c27b3294e9b84
|
[
"CC0-1.0"
] |
permissive
|
KristofferKarlAxelEkstrand/AKWF-FREE
|
b2defa1a2d389d309be6dd2e9f968923daf80d1b
|
cf8171df36e9fec25416b5f568b72a6e2cb69194
|
refs/heads/master
| 2023-07-23T18:22:36.939705
| 2023-07-10T17:14:40
| 2023-07-10T17:14:40
| 145,817,187
| 359
| 59
|
CC0-1.0
| 2023-07-10T17:14:41
| 2018-08-23T07:26:56
| null |
UTF-8
|
C
| false
| false
| 4,688
|
h
|
AKWF_altosax_0025.h
|
/* Adventure Kid Waveforms (AKWF) converted for use with Teensy Audio Library
*
* Adventure Kid Waveforms(AKWF) Open waveforms library
* https://www.adventurekid.se/akrt/waveforms/adventure-kid-waveforms/
*
* This code is in the public domain, CC0 1.0 Universal (CC0 1.0)
* https://creativecommons.org/publicdomain/zero/1.0/
*
* Converted by Brad Roy, https://github.com/prosper00
*/
/* AKWF_altosax_0025 256 samples
+-----------------------------------------------------------------------------------------------------------------+
| ** *** |
| ** **** |
| ** ** **** **** |
| ** *** * ******* ** |
| ** ***** ** |
| *** ** |
| *** ** *** |
|*** *** ** * *|
| **************** * ** *|
| ** * * * |
| ** ************ * ******* |
| * ****** ** * ** |
| ** ** ** * |
| *** ** ** |
| ** * |
+-----------------------------------------------------------------------------------------------------------------+
*/
const uint16_t AKWF_altosax_0025 [] = {
32886, 33378, 33449, 33277, 33194, 33286, 33565, 33879, 34280, 34903, 35809, 36962, 38286, 39606, 40815, 41887,
42999, 44381, 45967, 47558, 48902, 49792, 50167, 50193, 49987, 49530, 48852, 47990, 47068, 46166, 45342, 44611,
43982, 43474, 43169, 43138, 43345, 43788, 44677, 46111, 47901, 49799, 51655, 53431, 55210, 57011, 58741, 60344,
61693, 62706, 63316, 63573, 63707, 63828, 63882, 63751, 63332, 62681, 61831, 60854, 59808, 58790, 57884, 57181,
56707, 56359, 56015, 55559, 55110, 54686, 54130, 53567, 53109, 52665, 52050, 51058, 50039, 49223, 48556, 47894,
47118, 46445, 46028, 45969, 46198, 46608, 47124, 47676, 48227, 48790, 49411, 50089, 50736, 51217, 51456, 51440,
51199, 50586, 49602, 48403, 47092, 45729, 44295, 42802, 41280, 39830, 38476, 37114, 35837, 34744, 33706, 32689,
31732, 30951, 30400, 30016, 29726, 29469, 29337, 29352, 29472, 29660, 29813, 29697, 29303, 28772, 28337, 28120,
28062, 28056, 28020, 28040, 28178, 28471, 28875, 29291, 29558, 29673, 29700, 29637, 29503, 29299, 29057, 28785,
28472, 28154, 27864, 27612, 27235, 26442, 25160, 23437, 21425, 19307, 17253, 15440, 13883, 12489, 11236, 10172,
9360, 8979, 9192, 9868, 10811, 11845, 12894, 13924, 14772, 15510, 16303, 17020, 17512, 17704, 17704, 17709,
17788, 17916, 17937, 18137, 18632, 19121, 19467, 19616, 19578, 19337, 18873, 18345, 17929, 17710, 17709, 17883,
18241, 18739, 19321, 19878, 20347, 20744, 21056, 21241, 21345, 21337, 21082, 20470, 19442, 18038, 16339, 14418,
12389, 10325, 8185, 6024, 3943, 2148, 835, 150, 6, 329, 1096, 2507, 4817, 8058, 12026, 16277,
20432, 24221, 27668, 30766, 33432, 35516, 36665, 36349, 34567, 31711, 28489, 25467, 22943, 21127, 19963, 19228,
18827, 18778, 18979, 19272, 19374, 19304, 19155, 19259, 19663, 20394, 21536, 23178, 25238, 27533, 29701, 31579,
};
|
89e2ca728f0fd2f36a90aa68178e61b82f7a137e
|
4d78977ee7a816f97134d92b5826e929fb56c571
|
/libhttp/source/http-server-internal.h
|
4a462660a61601b4cc5e6da43871d78729e61c7e
|
[
"MIT"
] |
permissive
|
ireader/sdk
|
312e3ebdd4b0f694977236efab012d75cbd4bdd1
|
9fb240206c4d925d12be5b29aeb94c7884ea8262
|
refs/heads/master
| 2023-09-01T17:49:04.171634
| 2023-07-22T01:56:22
| 2023-07-22T01:56:22
| 11,940,320
| 394
| 250
|
MIT
| 2022-05-01T08:18:58
| 2013-08-07T03:16:47
|
C
|
UTF-8
|
C
| false
| false
| 2,025
|
h
|
http-server-internal.h
|
#ifndef _http_server_internal_h_
#define _http_server_internal_h_
#include "http-server.h"
#include "http-parser.h"
#include "http-websocket-internal.h"
#include "aio-transport.h"
#include "sys/sock.h"
#include "sys/atomic.h"
struct http_websocket_t
{
struct websocket_parser_t parser;
};
struct http_server_t
{
void* aio;
http_server_handler handler;
void* param;
struct websocket_handler_t wshandler;
void* wsparam;
};
struct http_session_t
{
int32_t ref;
http_parser_t* parser; // HTTP parser
aio_transport_t* transport; // TCP transporot
socket_t socket;
socklen_t addrlen;
struct sockaddr_storage addr;
char* data; // recv buffer
size_t remain; // remain size
void* rlocker; // recv status
char status_line[64];
struct
{
char* ptr;
size_t len;
size_t cap;
} header;
int http_response_code_flag; // 0-don't set status code
int http_response_header_flag; // 0-don't send response header, 1-sent
int http_content_length_flag; // 0-calc length, 1-user input value
int http_transfer_encoding_chunked_flag; // 0-bytes, 1-chunked
// send buffer vector
struct
{
int count;
int capacity;
socket_bufvec_t* vec;
socket_bufvec_t vec12[12];
socket_bufvec_t* __vec;
} vec;
// payload
struct
{
char* ptr;
size_t len;
size_t cap;
size_t max;
} payload;
struct http_server_t* server;
struct http_websocket_t websocket;
struct
{
struct http_streaming_handler_t handler;
void* param;
} streaming;
http_server_onsend onsend;
void* onsendparam;
int tryupgrade;
void* wsupgrade;
};
struct http_session_t* http_session_create(struct http_server_t *server, socket_t socket, const struct sockaddr* sa, socklen_t salen);
int http_session_add_header(struct http_session_t* session, const char* name, const char* value, size_t bytes);
int http_session_websocket_destroy(struct http_websocket_t* ws);
int http_session_websocket_send_vec(struct http_websocket_t* ws, int opcode, const struct http_vec_t* vec, int num);
#endif /* !_http_server_internal_h_ */
|
e93060b652acfe21edfbd9f2bf86e07204f668ed
|
d78d8e2eba9180c174caec9594c8d9e9b78b7b9f
|
/src/ctest/test_coinselection.c
|
5e614da3e1687db061d5a64c268ee7c86a1f243c
|
[
"MIT"
] |
permissive
|
ElementsProject/libwally-core
|
21adf16982aecc5de7c19044cec078794bde883b
|
0131dd7d746ed4c1ecfc0ebd9ea5b168cf15c7f9
|
refs/heads/master
| 2023-08-10T21:07:00.174677
| 2023-08-02T01:47:54
| 2023-08-02T01:47:54
| 95,169,962
| 269
| 146
|
NOASSERTION
| 2023-09-14T09:49:22
| 2017-06-23T01:09:27
|
C
|
UTF-8
|
C
| false
| false
| 3,554
|
c
|
test_coinselection.c
|
#include "config.h"
#include <wally_coinselection.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define NUM_ELEMS(a) (sizeof(a) / sizeof(a[0]))
#define MAX_TEST_UTXOS 16
#ifdef BUILD_ELEMENTS
static const struct asset_test {
const char *name;
uint64_t values[MAX_TEST_UTXOS];
size_t num_values;
uint64_t target;
size_t attempts;
uint32_t io_ratio;
uint32_t expected[MAX_TEST_UTXOS];
size_t num_expected;
} g_asset_tests[] = {
{
"Insufficient",
{ 50, 25, 15, 5 }, 4,
500, 0xffffffff, 5,
{ 0 }, 0 /* 0 length = no solution found */
}, {
"Single exact match: first",
{ 50, 25, 15, 5 }, 4,
50, 0xffffffff, 5,
{ 0 }, 1
}, {
"Single exact match: last",
{ 50, 25, 15, 5 }, 4,
5, 0xffffffff, 5,
{ 3 }, 1
}, {
"Require all",
{ 50, 25, 15, 5 }, 4,
50 + 25 + 15 + 5, 4 + 1, 5, /* Only N+1 attempts are required */
{ 0, 1, 2, 3 }, 4
}, {
"All larger than target",
{ 50, 25, 15, 5 }, 4,
3, 0xffffffff, 5,
{ 0 }, 1 /* Largest single value is returned */
}, {
"Cores hard_test_case(12) io_ratio=4",
/* 6 input exact match beats the first 2 inputs with io_ratio=4 or
* greater. Solution is found in 314 attempts.
*/
{ 2049, 2048, 1026, 1024, 516, 512, 264, 256, 144, 128, 96, 64 }, 12,
2048 + 1024 + 512 + 256 + 128 + 64, 0xffffffff, 4,
{ 1, 3, 5, 7, 9, 11 }, 6
}, {
"Cores hard_test_case(12) io_ratio=3",
/* With io_ratio=3, matches beyond length 5 are not searched once we
* discover the initial 2 input solution, so the best solution is the
* first 2 inputs, found in 154 attempts.
*/
{ 2049, 2048, 1026, 1024, 516, 512, 264, 256, 144, 128, 96, 64 }, 12,
2048 + 1024 + 512 + 256 + 128 + 64, 0xffffffff, 3,
{ 0, 1 }, 2
}, {
"Middle and last",
{ 2049, 2048, 1026, 1024, 516, 512, 264, 256, 144, 128, 96, 64 }, 12,
512 + 64, 0xffffffff, 5,
{ 5, 11 }, 2 /* Found in 48 attempts */
},
};
static bool test_coinselection_assets(void)
{
size_t i, n, written;
uint32_t out[WALLY_CS_MAX_ASSETS];
int ret;
for (i = 0; i < NUM_ELEMS(g_asset_tests); ++i) {
const struct asset_test *test = g_asset_tests + i;
ret = wally_coinselect_assets(test->values, test->num_values,
test->target, test->attempts,
test->io_ratio, out, sizeof(out),
&written);
if (ret != WALLY_OK) {
printf("[%s] test failed!\n", test->name);
return false;
}
if (written != test->num_expected) {
printf("[%s] test unexpected result size!\n", test->name);
return false;
}
for (n = 0; n < test->num_expected; ++n) {
if (out[n] != test->expected[n]) {
printf("[%s] test unexpected result %d(%d != %d)!\n",
test->name, (int)n, out[n], test->expected[n]);
return false;
}
}
}
return true;
}
#endif /* BUILD_ELEMENTS */
int main(void)
{
bool tests_ok = true;
#define RUN(t) if (!t()) { printf(#t " test_coinselection() test failed!\n"); tests_ok = false; }
#ifdef BUILD_ELEMENTS
RUN(test_coinselection_assets);
#endif
return tests_ok ? 0 : 1;
}
|
cfc743739492e3aed1bee248bedfc5e3574467cb
|
800c3c4eee1687e46edc16fb5ed3a5c49f64b6fd
|
/test/eeed8b54e0df.c
|
d97796da5578951de13abff2621e5d5bad2784bb
|
[
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"Linux-syscall-note",
"MIT",
"LGPL-2.1-only",
"GPL-2.0-only"
] |
permissive
|
axboe/liburing
|
8ced1953de2fca05bf689e322d4f68a6a2b4ef1e
|
58ec7c1aea2d57acbc3d398d0c8b2625746eaf04
|
refs/heads/master
| 2023-09-04T04:34:14.490712
| 2023-08-26T14:17:34
| 2023-08-28T14:22:13
| 200,663,555
| 2,276
| 374
|
MIT
| 2023-09-13T14:12:03
| 2019-08-05T13:43:57
|
C
|
UTF-8
|
C
| false
| false
| 1,904
|
c
|
eeed8b54e0df.c
|
/* SPDX-License-Identifier: MIT */
/*
* Description: -EAGAIN handling
*
*/
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include "helpers.h"
#include "liburing.h"
#define BLOCK 4096
#ifndef RWF_NOWAIT
#define RWF_NOWAIT 8
#endif
static int get_file_fd(void)
{
ssize_t ret;
char *buf;
int fd;
fd = open("testfile", O_RDWR | O_CREAT, 0644);
unlink("testfile");
if (fd < 0) {
perror("open file");
return -1;
}
buf = t_malloc(BLOCK);
memset(buf, 0, BLOCK);
ret = write(fd, buf, BLOCK);
if (ret != BLOCK) {
if (ret < 0)
perror("write");
else
printf("Short write\n");
goto err;
}
fsync(fd);
if (posix_fadvise(fd, 0, 4096, POSIX_FADV_DONTNEED)) {
perror("fadvise");
err:
close(fd);
free(buf);
return -1;
}
free(buf);
return fd;
}
int main(int argc, char *argv[])
{
struct io_uring ring;
struct io_uring_sqe *sqe;
struct io_uring_cqe *cqe;
struct iovec iov;
int ret, fd;
if (argc > 1)
return T_EXIT_SKIP;
iov.iov_base = t_malloc(4096);
iov.iov_len = 4096;
ret = io_uring_queue_init(2, &ring, 0);
if (ret) {
printf("ring setup failed\n");
return T_EXIT_FAIL;
}
sqe = io_uring_get_sqe(&ring);
if (!sqe) {
printf("get sqe failed\n");
return T_EXIT_FAIL;
}
fd = get_file_fd();
if (fd < 0)
return T_EXIT_FAIL;
io_uring_prep_readv(sqe, fd, &iov, 1, 0);
sqe->rw_flags = RWF_NOWAIT;
ret = io_uring_submit(&ring);
if (ret != 1) {
printf("Got submit %d, expected 1\n", ret);
goto err;
}
ret = io_uring_peek_cqe(&ring, &cqe);
if (ret) {
printf("Ring peek got %d\n", ret);
goto err;
}
ret = T_EXIT_PASS;
if (cqe->res != -EAGAIN && cqe->res != 4096) {
if (cqe->res == -EOPNOTSUPP) {
ret = T_EXIT_SKIP;
} else {
printf("cqe error: %d\n", cqe->res);
goto err;
}
}
close(fd);
return ret;
err:
close(fd);
return T_EXIT_FAIL;
}
|
acb18a9e97018e2f19307763a69c33418a9d405d
|
58fe7cb3949dd1930e709696659a0296500b64a6
|
/tests/fuzz/LD_PRELOAD/global_overrides.c
|
83a826556b17911f28d5289a5e075373822df2e2
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
aws/s2n-tls
|
3344638a6a69c6f20665cf6847e1bc4b85f2e558
|
62dc7a6d4876e5eee0dea3690d528a4c7080a1d5
|
refs/heads/main
| 2023-08-31T23:26:33.780048
| 2023-08-31T05:17:33
| 2023-08-31T05:17:33
| 21,287,076
| 513
| 213
|
Apache-2.0
| 2023-09-13T23:52:29
| 2014-06-27T19:37:59
|
C
|
UTF-8
|
C
| false
| false
| 2,783
|
c
|
global_overrides.c
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
#include "api/s2n.h"
#include "crypto/s2n_drbg.h"
#include "error/s2n_errno.h"
#include "stuffer/s2n_stuffer.h"
#include "utils/s2n_safety.h"
#include "utils/s2n_random.h"
S2N_RESULT s2n_drbg_generate(struct s2n_drbg *drbg, struct s2n_blob *blob) {
/* If fuzzing, only generate "fake" random numbers in order to ensure that fuzz tests are deterministic and repeatable.
* This function should generate non-zero values since this function may be called repeatedly at startup until a
* non-zero value is generated.
*/
RESULT_GUARD(s2n_get_public_random_data(blob));
drbg->bytes_used += blob->size;
return S2N_RESULT_OK;
}
int s2n_stuffer_send_to_fd(struct s2n_stuffer *stuffer, const int wfd, const uint32_t len, uint32_t *bytes_sent)
{
/* Override the original s2n_stuffer_send_to_fd to check if the write file descriptor is -1, and if so, skip
* writing anything. This is to speed up fuzz tests that write unnecessary data that is never actually read.
*/
if(wfd == -1){
stuffer->read_cursor += len;
return len;
}
/* Otherwise, call the original s2n_stuffer_send_to_fd() */
typedef int (*orig_s2n_stuffer_send_to_fd_func_type)(struct s2n_stuffer *stuffer, const int wfd, const uint32_t len, uint32_t *bytes_sent);
orig_s2n_stuffer_send_to_fd_func_type orig_s2n_stuffer_send_to_fd;
orig_s2n_stuffer_send_to_fd = (orig_s2n_stuffer_send_to_fd_func_type) dlsym(RTLD_NEXT, "s2n_stuffer_send_to_fd");
POSIX_GUARD_PTR(orig_s2n_stuffer_send_to_fd);
POSIX_GUARD(orig_s2n_stuffer_send_to_fd(stuffer, wfd, len, bytes_sent));
return S2N_SUCCESS;
}
S2N_RESULT s2n_get_public_random_data(struct s2n_blob *blob){
/* If fuzzing, only generate "fake" random numbers in order to ensure that fuzz tests are deterministic and repeatable.
* This function should generate non-zero values since this function may be called repeatedly at startup until a
* non-zero value is generated.
*/
for(int i=0; i < blob->size; i++){
blob->data[i] = 4; /* Fake RNG. Chosen by fair dice roll. https://xkcd.com/221/ */
}
return S2N_RESULT_OK;
}
|
8677aa4ef737393c0d2372b0a3db5a93c0615074
|
6ea5925c00da2e4da856c05957e712c07c2be939
|
/src/fxlibc/strcasestr.c
|
29986f45c1da646ebfa30a4f64625336090a3e89
|
[
"MIT"
] |
permissive
|
Manawyrm/fxIP
|
afdefc8624292b04ca51e8bdb146b67cb1906501
|
6c5c6894087a39e33519dcf222b98ee0b64e07e2
|
refs/heads/main
| 2023-08-17T20:16:34.033100
| 2022-06-05T09:05:52
| 2022-06-05T09:05:52
| 369,902,982
| 215
| 8
| null | 2021-07-12T18:57:38
| 2021-05-22T20:47:30
|
C
|
UTF-8
|
C
| false
| false
| 153
|
c
|
strcasestr.c
|
#include <string.h>
#include "string_p.h"
char *strcasestr(char const *haystack, char const *needle)
{
return __strstr_base(haystack, needle, true);
}
|
7bd58d87d8353c3d4192f5b89d69ed8b1e379583
|
2e28c1eca20462ac36a801377364cf7f28454a07
|
/ext/htslib/faidx.c
|
50c3adba47fd5b5a890e6ade4862fce81474a89e
|
[
"BSD-2-Clause",
"BSD-3-Clause",
"MIT"
] |
permissive
|
pachterlab/kallisto
|
0fbe2a0058eca81d07cb968d6af6c662b9bea48b
|
ff32921dbeb4f9853984a88c1c7534562e256d7a
|
refs/heads/master
| 2023-09-01T13:00:40.473948
| 2023-07-02T01:41:55
| 2023-07-02T01:41:55
| 26,562,905
| 605
| 207
|
BSD-2-Clause
| 2023-08-27T09:13:53
| 2014-11-13T00:27:48
|
C
|
UTF-8
|
C
| false
| false
| 17,875
|
c
|
faidx.c
|
/* faidx.c -- FASTA random access.
Copyright (C) 2008, 2009, 2013-2017 Genome Research Ltd.
Portions copyright (C) 2011 Broad Institute.
Author: Heng Li <lh3@sanger.ac.uk>
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 <config.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include <assert.h>
#include "htslib/bgzf.h"
#include "htslib/faidx.h"
#include "htslib/hfile.h"
#include "htslib/khash.h"
#include "htslib/kstring.h"
#include "hts_internal.h"
typedef struct {
int32_t line_len, line_blen;
int64_t len;
uint64_t offset;
} faidx1_t;
KHASH_MAP_INIT_STR(s, faidx1_t)
struct __faidx_t {
BGZF *bgzf;
int n, m;
char **name;
khash_t(s) *hash;
};
#ifndef kroundup32
#define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x))
#endif
static inline int fai_insert_index(faidx_t *idx, const char *name, int64_t len, int line_len, int line_blen, uint64_t offset)
{
if (!name) {
fprintf(stderr, "[fai_build_core] malformed line\n");
return -1;
}
char *name_key = strdup(name);
int absent;
khint_t k = kh_put(s, idx->hash, name_key, &absent);
faidx1_t *v = &kh_value(idx->hash, k);
if (! absent) {
fprintf(stderr, "[fai_build_core] ignoring duplicate sequence \"%s\" at byte offset %"PRIu64"\n", name, offset);
free(name_key);
return 0;
}
if (idx->n == idx->m) {
char **tmp;
idx->m = idx->m? idx->m<<1 : 16;
if (!(tmp = (char**)realloc(idx->name, sizeof(char*) * idx->m))) {
fprintf(stderr, "[fai_build_core] out of memory\n");
return -1;
}
idx->name = tmp;
}
idx->name[idx->n++] = name_key;
v->len = len;
v->line_len = line_len;
v->line_blen = line_blen;
v->offset = offset;
return 0;
}
faidx_t *fai_build_core(BGZF *bgzf)
{
kstring_t name = { 0, 0, NULL };
int c;
int line_len, line_blen, state;
int l1, l2;
faidx_t *idx;
uint64_t offset;
int64_t len;
idx = (faidx_t*)calloc(1, sizeof(faidx_t));
idx->hash = kh_init(s);
len = line_len = line_blen = -1; state = 0; l1 = l2 = -1; offset = 0;
while ( (c=bgzf_getc(bgzf))>=0 ) {
if (c == '\n') { // an empty line
if (state == 1) {
offset = bgzf_utell(bgzf);
continue;
} else if ((state == 0 && len < 0) || state == 2) continue;
else if (state == 0) { state = 2; continue; }
}
if (c == '>') { // fasta header
if (len >= 0) {
if (fai_insert_index(idx, name.s, len, line_len, line_blen, offset) != 0)
goto fail;
}
name.l = 0;
while ((c = bgzf_getc(bgzf)) >= 0)
if (! isspace(c)) kputc_(c, &name);
else if (name.l > 0 || c == '\n') break;
kputsn("", 0, &name);
if ( c<0 ) {
fprintf(stderr, "[fai_build_core] the last entry has no sequence\n");
goto fail;
}
if (c != '\n') while ( (c=bgzf_getc(bgzf))>=0 && c != '\n');
state = 1; len = 0;
offset = bgzf_utell(bgzf);
} else {
if (state == 3) {
fprintf(stderr, "[fai_build_core] inlined empty line is not allowed in sequence '%s'.\n", name.s);
goto fail;
}
if (state == 2) state = 3;
l1 = l2 = 0;
do {
++l1;
if (isgraph(c)) ++l2;
} while ( (c=bgzf_getc(bgzf))>=0 && c != '\n');
if (state == 3 && l2) {
fprintf(stderr, "[fai_build_core] different line length in sequence '%s'.\n", name.s);
goto fail;
}
++l1; len += l2;
if (state == 1) line_len = l1, line_blen = l2, state = 0;
else if (state == 0) {
if (l1 != line_len || l2 != line_blen) state = 2;
}
}
}
if (len >= 0) {
if (fai_insert_index(idx, name.s, len, line_len, line_blen, offset) != 0)
goto fail;
} else {
goto fail;
}
free(name.s);
return idx;
fail:
free(name.s);
fai_destroy(idx);
return NULL;
}
static int fai_save(const faidx_t *fai, hFILE *fp) {
khint_t k;
int i;
char buf[96]; // Must be big enough for format below.
for (i = 0; i < fai->n; ++i) {
faidx1_t x;
k = kh_get(s, fai->hash, fai->name[i]);
assert(k < kh_end(fai->hash));
x = kh_value(fai->hash, k);
snprintf(buf, sizeof(buf),
"\t%"PRId64"\t%"PRIu64"\t%"PRId32"\t%"PRId32"\n",
x.len, x.offset, x.line_blen, x.line_len);
if (hputs(fai->name[i], fp) != 0) return -1;
if (hputs(buf, fp) != 0) return -1;
}
return 0;
}
static faidx_t *fai_read(hFILE *fp, const char *fname)
{
faidx_t *fai;
char *buf = NULL, *p;
int line_len, line_blen, n;
int64_t len;
uint64_t offset;
ssize_t l, lnum = 1;
fai = (faidx_t*)calloc(1, sizeof(faidx_t));
if (!fai) return NULL;
fai->hash = kh_init(s);
if (!fai->hash) goto fail;
buf = (char*)calloc(0x10000, 1);
if (!buf) goto fail;
while ((l = hgetln(buf, 0x10000, fp)) > 0) {
for (p = buf; *p && !isspace_c(*p); ++p);
if (p - buf < l) {
*p = 0; ++p;
}
n = sscanf(p, "%"SCNd64"%"SCNu64"%d%d", &len, &offset, &line_blen, &line_len);
if (n != 4) {
if (hts_verbose > 1)
fprintf(stderr, "[fai_load] couldn't understand FAI %s line %zd\n",
fname, lnum);
goto fail;
}
if (fai_insert_index(fai, buf, len, line_len, line_blen, offset) != 0) {
goto fail;
}
if (buf[l - 1] == '\n') ++lnum;
}
if (l < 0) {
if (hts_verbose > 1)
fprintf(stderr, "[fai_load] error while reading \"%s\": %s\n",
fname, strerror(errno));
goto fail;
}
free(buf);
return fai;
fail:
free(buf);
fai_destroy(fai);
return NULL;
}
void fai_destroy(faidx_t *fai)
{
int i;
if (!fai) return;
for (i = 0; i < fai->n; ++i) free(fai->name[i]);
free(fai->name);
kh_destroy(s, fai->hash);
if (fai->bgzf) bgzf_close(fai->bgzf);
free(fai);
}
int fai_build3(const char *fn, const char *fnfai, const char *fngzi)
{
kstring_t fai_kstr = { 0, 0, NULL };
kstring_t gzi_kstr = { 0, 0, NULL };
BGZF *bgzf = NULL;
hFILE *fp = NULL;
faidx_t *fai = NULL;
int save_errno, res;
if (!fnfai) {
if (ksprintf(&fai_kstr, "%s.fai", fn) < 0) goto fail;
fnfai = fai_kstr.s;
}
if (!fngzi) {
if (ksprintf(&gzi_kstr, "%s.gzi", fn) < 0) goto fail;
fngzi = gzi_kstr.s;
}
bgzf = bgzf_open(fn, "r");
if ( !bgzf ) {
if (hts_verbose > 1)
fprintf(stderr, "[fai_build] fail to open the FASTA file %s\n",fn);
goto fail;
}
if ( bgzf->is_compressed ) {
if (bgzf_index_build_init(bgzf) != 0) {
if (hts_verbose > 1)
fprintf(stderr, "[fai_build] fail to allocate bgzf index");
goto fail;
}
}
fai = fai_build_core(bgzf);
if ( !fai )
{
if ( bgzf->is_compressed && bgzf->is_gzip && hts_verbose > 1)
fprintf(stderr, "Cannot index files compressed with gzip, please use bgzip\n");
goto fail;
}
if ( bgzf->is_compressed ) {
if (bgzf_index_dump(bgzf, fngzi, NULL) < 0) {
if (hts_verbose > 1)
fprintf(stderr, "[fai_build] fail to make bgzf index %s\n",
fngzi);
goto fail;
}
}
res = bgzf_close(bgzf);
bgzf = NULL;
if (res < 0) {
if (hts_verbose > 1)
fprintf(stderr, "[fai_build] Error on closing %s : %s\n",
fn, strerror(errno));
goto fail;
}
fp = hopen(fnfai, "wb");
if ( !fp ) {
if (hts_verbose > 1)
fprintf(stderr, "[fai_build] fail to open FASTA index %s : %s\n",
fnfai, strerror(errno));
goto fail;
}
if (fai_save(fai, fp) != 0) {
if (hts_verbose > 1)
fprintf(stderr, "[fai_build] fail to write FASTA index %s : %s\n",
fnfai, strerror(errno));
goto fail;
}
if (hclose(fp) != 0) {
if (hts_verbose > 1)
fprintf(stderr, "[fai_build] fail on closing FASTA index %s : %s\n",
fnfai, strerror(errno));
goto fail;
}
free(fai_kstr.s);
free(gzi_kstr.s);
fai_destroy(fai);
return 0;
fail:
save_errno = errno;
free(fai_kstr.s);
free(gzi_kstr.s);
bgzf_close(bgzf);
fai_destroy(fai);
errno = save_errno;
return -1;
}
int fai_build(const char *fn) {
return fai_build3(fn, NULL, NULL);
}
faidx_t *fai_load3(const char *fn, const char *fnfai, const char *fngzi,
int flags)
{
kstring_t fai_kstr = { 0, 0, NULL };
kstring_t gzi_kstr = { 0, 0, NULL };
hFILE *fp = NULL;
faidx_t *fai = NULL;
int res;
if (fn == NULL)
return NULL;
if (fnfai == NULL) {
if (ksprintf(&fai_kstr, "%s.fai", fn) < 0) goto fail;
fnfai = fai_kstr.s;
}
if (fngzi == NULL) {
if (ksprintf(&gzi_kstr, "%s.gzi", fn) < 0) goto fail;
fngzi = gzi_kstr.s;
}
fp = hopen(fnfai, "rb");
if (fp == 0) {
if (!(flags & FAI_CREATE) || errno != ENOENT) {
if (hts_verbose >= 1) {
fprintf(stderr, "[fai_load] failed to open FASTA index %s: %s\n",
fnfai, strerror(errno));
}
goto fail;
}
if (hts_verbose >= 1) {
fprintf(stderr, "[fai_load] build FASTA index.\n");
}
if (fai_build3(fn, fnfai, fngzi) < 0) {
goto fail;
}
fp = hopen(fnfai, "rb");
if (fp == 0) {
if (hts_verbose >= 1) {
fprintf(stderr, "[fai_load] failed to open FASTA index %s: %s\n",
fnfai, strerror(errno));
}
goto fail;
}
}
fai = fai_read(fp, fnfai);
if (fai == NULL) {
if (hts_verbose >= 1)
fprintf(stderr, "[fai_load] failed to read FASTA index %s\n",
fnfai);
goto fail;
}
res = hclose(fp);
fp = NULL;
if (res < 0) {
if (hts_verbose >= 1)
fprintf(stderr, "[fai_load] fail on closing FASTA index %s : %s\n",
fnfai, strerror(errno));
goto fail;
}
fai->bgzf = bgzf_open(fn, "rb");
if (fai->bgzf == 0) {
if (hts_verbose >= 1)
fprintf(stderr, "[fai_load] fail to open FASTA file %s.\n", fn);
goto fail;
}
if ( fai->bgzf->is_compressed==1 )
{
if ( bgzf_index_load(fai->bgzf, fngzi, NULL) < 0 )
{
if (hts_verbose >= 1)
fprintf(stderr, "[fai_load] failed to load .gzi index: %s\n",
fngzi);
goto fail;
}
}
free(fai_kstr.s);
free(gzi_kstr.s);
return fai;
fail:
if (fai) fai_destroy(fai);
if (fp) hclose_abruptly(fp);
free(fai_kstr.s);
free(gzi_kstr.s);
return NULL;
}
faidx_t *fai_load(const char *fn)
{
return fai_load3(fn, NULL, NULL, FAI_CREATE);
}
static char *fai_retrieve(const faidx_t *fai, const faidx1_t *val,
long beg, long end, int *len) {
char *s;
size_t l;
int c = 0;
int ret = bgzf_useek(fai->bgzf,
val->offset
+ beg / val->line_blen * val->line_len
+ beg % val->line_blen, SEEK_SET);
if (ret < 0) {
*len = -1;
if (hts_verbose >= 1)
fprintf(stderr, "[fai_fetch] Error: fai_fetch failed. (Seeking in a compressed, .gzi unindexed, file?)\n");
return NULL;
}
l = 0;
s = (char*)malloc((size_t) end - beg + 2);
if (!s) {
*len = -1;
return NULL;
}
while ( l < end - beg && (c=bgzf_getc(fai->bgzf))>=0 )
if (isgraph(c)) s[l++] = c;
if (c < 0) {
if (hts_verbose >= 1) {
fprintf(stderr, "[E::fai_fetch] fai_fetch failed : %s\n",
c == -1 ? "unexpected end of file" : "error reading file");
}
free(s);
*len = -1;
return NULL;
}
s[l] = '\0';
*len = l < INT_MAX ? l : INT_MAX;
return s;
}
char *fai_fetch(const faidx_t *fai, const char *str, int *len)
{
char *s, *ep;
size_t i, l, k, name_end;
khiter_t iter;
faidx1_t val;
khash_t(s) *h;
long beg, end;
beg = end = -1;
h = fai->hash;
name_end = l = strlen(str);
s = (char*)malloc(l+1);
if (!s) {
*len = -1;
return NULL;
}
// remove space
for (i = k = 0; i < l; ++i)
if (!isspace_c(str[i])) s[k++] = str[i];
s[k] = 0;
name_end = l = k;
// determine the sequence name
for (i = l; i > 0; --i) if (s[i - 1] == ':') break; // look for colon from the end
if (i > 0) name_end = i - 1;
if (name_end < l) { // check if this is really the end
int n_hyphen = 0;
for (i = name_end + 1; i < l; ++i) {
if (s[i] == '-') ++n_hyphen;
else if (!isdigit_c(s[i]) && s[i] != ',') break;
}
if (i < l || n_hyphen > 1) name_end = l; // malformated region string; then take str as the name
s[name_end] = 0;
iter = kh_get(s, h, s);
if (iter == kh_end(h)) { // cannot find the sequence name
iter = kh_get(s, h, str); // try str as the name
if (iter != kh_end(h)) {
s[name_end] = ':';
name_end = l;
}
}
} else iter = kh_get(s, h, str);
if(iter == kh_end(h)) {
fprintf(stderr, "[fai_fetch] Warning - Reference %s not found in FASTA file, returning empty sequence\n", str);
free(s);
*len = -2;
return 0;
}
val = kh_value(h, iter);
// parse the interval
if (name_end < l) {
int save_errno = errno;
errno = 0;
for (i = k = name_end + 1; i < l; ++i)
if (s[i] != ',') s[k++] = s[i];
s[k] = 0;
if (s[name_end + 1] == '-') {
beg = 0;
i = name_end + 2;
} else {
beg = strtol(s + name_end + 1, &ep, 10);
for (i = ep - s; i < k;) if (s[i++] == '-') break;
}
end = i < k? strtol(s + i, &ep, 10) : val.len;
if (beg > 0) --beg;
// Check for out of range numbers. Only going to be a problem on
// 32-bit platforms with >2Gb sequence length.
if (errno == ERANGE && (uint64_t) val.len > LONG_MAX) {
fprintf(stderr, "[fai_fetch] Positions in range %s are too large"
" for this platform.\n", s);
free(s);
*len = -2;
return NULL;
}
errno = save_errno;
} else beg = 0, end = val.len;
if (beg >= val.len) beg = val.len;
if (end >= val.len) end = val.len;
if (beg > end) beg = end;
free(s);
// now retrieve the sequence
return fai_retrieve(fai, &val, beg, end, len);
}
int faidx_fetch_nseq(const faidx_t *fai)
{
return fai->n;
}
int faidx_nseq(const faidx_t *fai)
{
return fai->n;
}
const char *faidx_iseq(const faidx_t *fai, int i)
{
return fai->name[i];
}
int faidx_seq_len(const faidx_t *fai, const char *seq)
{
khint_t k = kh_get(s, fai->hash, seq);
if ( k == kh_end(fai->hash) ) return -1;
return kh_val(fai->hash, k).len;
}
char *faidx_fetch_seq(const faidx_t *fai, const char *c_name, int p_beg_i, int p_end_i, int *len)
{
khiter_t iter;
faidx1_t val;
// Adjust position
iter = kh_get(s, fai->hash, c_name);
if (iter == kh_end(fai->hash))
{
*len = -2;
fprintf(stderr, "[fai_fetch_seq] The sequence \"%s\" not found\n", c_name);
return NULL;
}
val = kh_value(fai->hash, iter);
if(p_end_i < p_beg_i) p_beg_i = p_end_i;
if(p_beg_i < 0) p_beg_i = 0;
else if(val.len <= p_beg_i) p_beg_i = val.len - 1;
if(p_end_i < 0) p_end_i = 0;
else if(val.len <= p_end_i) p_end_i = val.len - 1;
// Now retrieve the sequence
return fai_retrieve(fai, &val, p_beg_i, (long) p_end_i + 1, len);
}
int faidx_has_seq(const faidx_t *fai, const char *seq)
{
khiter_t iter = kh_get(s, fai->hash, seq);
if (iter == kh_end(fai->hash)) return 0;
return 1;
}
|
ec8cc4f99db7757b4da5132f9bad5e788351ba81
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/arch/x86/include/asm/bitops.h
|
6dfd0195bb5529ce8a86fa379726f43b9f513ab4
|
[
"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
| 13,688
|
h
|
bitops.h
|
#ifndef _ASM_X86_BITOPS_H
#define _ASM_X86_BITOPS_H
/*
* Copyright 1992, Linus Torvalds.
*
* Note: inlines with more than a single statement should be marked
* __always_inline to avoid problems with older gcc's inlining heuristics.
*/
#ifndef _LINUX_BITOPS_H
#error only <linux/bitops.h> can be included directly
#endif
#include <linux/compiler.h>
#include <asm/alternative.h>
#define BIT_64(n) (U64_C(1) << (n))
/*
* These have to be done with inline assembly: that way the bit-setting
* is guaranteed to be atomic. All bit operations return 0 if the bit
* was cleared before the operation and != 0 if it was not.
*
* bit 0 is the LSB of addr; bit 32 is the LSB of (addr+1).
*/
#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 1)
/* Technically wrong, but this avoids compilation errors on some gcc
versions. */
#define BITOP_ADDR(x) "=m" (*(volatile long *) (x))
#else
#define BITOP_ADDR(x) "+m" (*(volatile long *) (x))
#endif
#define ADDR BITOP_ADDR(addr)
/*
* We do the locked ops that don't return the old value as
* a mask operation on a byte.
*/
#define IS_IMMEDIATE(nr) (__builtin_constant_p(nr))
#define CONST_MASK_ADDR(nr, addr) BITOP_ADDR((void *)(addr) + ((nr)>>3))
#define CONST_MASK(nr) (1 << ((nr) & 7))
/**
* set_bit - Atomically set a bit in memory
* @nr: the bit to set
* @addr: the address to start counting from
*
* This function is atomic and may not be reordered. See __set_bit()
* if you do not require the atomic guarantees.
*
* Note: there are no guarantees that this function will not be reordered
* on non x86 architectures, so if you are writing portable code,
* make sure not to rely on its reordering guarantees.
*
* Note that @nr may be almost arbitrarily large; this function is not
* restricted to acting on a single-word quantity.
*/
static __always_inline void
set_bit(unsigned int nr, volatile unsigned long *addr)
{
if (IS_IMMEDIATE(nr)) {
asm volatile(LOCK_PREFIX "orb %1,%0"
: CONST_MASK_ADDR(nr, addr)
: "iq" ((u8)CONST_MASK(nr))
: "memory");
} else {
asm volatile(LOCK_PREFIX "bts %1,%0"
: BITOP_ADDR(addr) : "Ir" (nr) : "memory");
}
}
/**
* __set_bit - Set a bit in memory
* @nr: the bit to set
* @addr: the address to start counting from
*
* Unlike set_bit(), this function is non-atomic and may be reordered.
* If it's called on the same region of memory simultaneously, the effect
* may be that only one operation succeeds.
*/
static inline void __set_bit(int nr, volatile unsigned long *addr)
{
asm volatile("bts %1,%0" : ADDR : "Ir" (nr) : "memory");
}
/**
* clear_bit - Clears a bit in memory
* @nr: Bit to clear
* @addr: Address to start counting from
*
* clear_bit() is atomic and may not be reordered. However, it does
* not contain a memory barrier, so if it is used for locking purposes,
* you should call smp_mb__before_clear_bit() and/or smp_mb__after_clear_bit()
* in order to ensure changes are visible on other processors.
*/
static __always_inline void
clear_bit(int nr, volatile unsigned long *addr)
{
if (IS_IMMEDIATE(nr)) {
asm volatile(LOCK_PREFIX "andb %1,%0"
: CONST_MASK_ADDR(nr, addr)
: "iq" ((u8)~CONST_MASK(nr)));
} else {
asm volatile(LOCK_PREFIX "btr %1,%0"
: BITOP_ADDR(addr)
: "Ir" (nr));
}
}
/*
* clear_bit_unlock - Clears a bit in memory
* @nr: Bit to clear
* @addr: Address to start counting from
*
* clear_bit() is atomic and implies release semantics before the memory
* operation. It can be used for an unlock.
*/
static inline void clear_bit_unlock(unsigned nr, volatile unsigned long *addr)
{
barrier();
clear_bit(nr, addr);
}
static inline void __clear_bit(int nr, volatile unsigned long *addr)
{
asm volatile("btr %1,%0" : ADDR : "Ir" (nr));
}
/*
* __clear_bit_unlock - Clears a bit in memory
* @nr: Bit to clear
* @addr: Address to start counting from
*
* __clear_bit() is non-atomic and implies release semantics before the memory
* operation. It can be used for an unlock if no other CPUs can concurrently
* modify other bits in the word.
*
* No memory barrier is required here, because x86 cannot reorder stores past
* older loads. Same principle as spin_unlock.
*/
static inline void __clear_bit_unlock(unsigned nr, volatile unsigned long *addr)
{
barrier();
__clear_bit(nr, addr);
}
#define smp_mb__before_clear_bit() barrier()
#define smp_mb__after_clear_bit() barrier()
/**
* __change_bit - Toggle a bit in memory
* @nr: the bit to change
* @addr: the address to start counting from
*
* Unlike change_bit(), this function is non-atomic and may be reordered.
* If it's called on the same region of memory simultaneously, the effect
* may be that only one operation succeeds.
*/
static inline void __change_bit(int nr, volatile unsigned long *addr)
{
asm volatile("btc %1,%0" : ADDR : "Ir" (nr));
}
/**
* change_bit - Toggle a bit in memory
* @nr: Bit to change
* @addr: Address to start counting from
*
* change_bit() is atomic and may not be reordered.
* Note that @nr may be almost arbitrarily large; this function is not
* restricted to acting on a single-word quantity.
*/
static inline void change_bit(int nr, volatile unsigned long *addr)
{
if (IS_IMMEDIATE(nr)) {
asm volatile(LOCK_PREFIX "xorb %1,%0"
: CONST_MASK_ADDR(nr, addr)
: "iq" ((u8)CONST_MASK(nr)));
} else {
asm volatile(LOCK_PREFIX "btc %1,%0"
: BITOP_ADDR(addr)
: "Ir" (nr));
}
}
/**
* test_and_set_bit - Set a bit and return its old value
* @nr: Bit to set
* @addr: Address to count from
*
* This operation is atomic and cannot be reordered.
* It also implies a memory barrier.
*/
static inline int test_and_set_bit(int nr, volatile unsigned long *addr)
{
int oldbit;
asm volatile(LOCK_PREFIX "bts %2,%1\n\t"
"sbb %0,%0" : "=r" (oldbit), ADDR : "Ir" (nr) : "memory");
return oldbit;
}
/**
* test_and_set_bit_lock - Set a bit and return its old value for lock
* @nr: Bit to set
* @addr: Address to count from
*
* This is the same as test_and_set_bit on x86.
*/
static __always_inline int
test_and_set_bit_lock(int nr, volatile unsigned long *addr)
{
return test_and_set_bit(nr, addr);
}
/**
* __test_and_set_bit - Set a bit and return its old value
* @nr: Bit to set
* @addr: Address to count from
*
* This operation is non-atomic and can be reordered.
* If two examples of this operation race, one can appear to succeed
* but actually fail. You must protect multiple accesses with a lock.
*/
static inline int __test_and_set_bit(int nr, volatile unsigned long *addr)
{
int oldbit;
asm("bts %2,%1\n\t"
"sbb %0,%0"
: "=r" (oldbit), ADDR
: "Ir" (nr));
return oldbit;
}
/**
* test_and_clear_bit - Clear a bit and return its old value
* @nr: Bit to clear
* @addr: Address to count from
*
* This operation is atomic and cannot be reordered.
* It also implies a memory barrier.
*/
static inline int test_and_clear_bit(int nr, volatile unsigned long *addr)
{
int oldbit;
asm volatile(LOCK_PREFIX "btr %2,%1\n\t"
"sbb %0,%0"
: "=r" (oldbit), ADDR : "Ir" (nr) : "memory");
return oldbit;
}
/**
* __test_and_clear_bit - Clear a bit and return its old value
* @nr: Bit to clear
* @addr: Address to count from
*
* This operation is non-atomic and can be reordered.
* If two examples of this operation race, one can appear to succeed
* but actually fail. You must protect multiple accesses with a lock.
*
* Note: the operation is performed atomically with respect to
* the local CPU, but not other CPUs. Portable code should not
* rely on this behaviour.
* KVM relies on this behaviour on x86 for modifying memory that is also
* accessed from a hypervisor on the same CPU if running in a VM: don't change
* this without also updating arch/x86/kernel/kvm.c
*/
static inline int __test_and_clear_bit(int nr, volatile unsigned long *addr)
{
int oldbit;
asm volatile("btr %2,%1\n\t"
"sbb %0,%0"
: "=r" (oldbit), ADDR
: "Ir" (nr));
return oldbit;
}
/* WARNING: non atomic and it can be reordered! */
static inline int __test_and_change_bit(int nr, volatile unsigned long *addr)
{
int oldbit;
asm volatile("btc %2,%1\n\t"
"sbb %0,%0"
: "=r" (oldbit), ADDR
: "Ir" (nr) : "memory");
return oldbit;
}
/**
* test_and_change_bit - Change a bit and return its old value
* @nr: Bit to change
* @addr: Address to count from
*
* This operation is atomic and cannot be reordered.
* It also implies a memory barrier.
*/
static inline int test_and_change_bit(int nr, volatile unsigned long *addr)
{
int oldbit;
asm volatile(LOCK_PREFIX "btc %2,%1\n\t"
"sbb %0,%0"
: "=r" (oldbit), ADDR : "Ir" (nr) : "memory");
return oldbit;
}
static __always_inline int constant_test_bit(unsigned int nr, const volatile unsigned long *addr)
{
return ((1UL << (nr % BITS_PER_LONG)) &
(addr[nr / BITS_PER_LONG])) != 0;
}
static inline int variable_test_bit(int nr, volatile const unsigned long *addr)
{
int oldbit;
asm volatile("bt %2,%1\n\t"
"sbb %0,%0"
: "=r" (oldbit)
: "m" (*(unsigned long *)addr), "Ir" (nr));
return oldbit;
}
#if 0 /* Fool kernel-doc since it doesn't do macros yet */
/**
* test_bit - Determine whether a bit is set
* @nr: bit number to test
* @addr: Address to start counting from
*/
static int test_bit(int nr, const volatile unsigned long *addr);
#endif
#define test_bit(nr, addr) \
(__builtin_constant_p((nr)) \
? constant_test_bit((nr), (addr)) \
: variable_test_bit((nr), (addr)))
/**
* __ffs - find first set bit in word
* @word: The word to search
*
* Undefined if no bit exists, so code should check against 0 first.
*/
static inline unsigned long __ffs(unsigned long word)
{
asm("rep; bsf %1,%0"
: "=r" (word)
: "rm" (word));
return word;
}
/**
* ffz - find first zero bit in word
* @word: The word to search
*
* Undefined if no zero exists, so code should check against ~0UL first.
*/
static inline unsigned long ffz(unsigned long word)
{
asm("rep; bsf %1,%0"
: "=r" (word)
: "r" (~word));
return word;
}
/*
* __fls: find last set bit in word
* @word: The word to search
*
* Undefined if no set bit exists, so code should check against 0 first.
*/
static inline unsigned long __fls(unsigned long word)
{
asm("bsr %1,%0"
: "=r" (word)
: "rm" (word));
return word;
}
#undef ADDR
#ifdef __KERNEL__
/**
* ffs - find first set bit in word
* @x: the word to search
*
* This is defined the same way as the libc and compiler builtin ffs
* routines, therefore differs in spirit from the other bitops.
*
* ffs(value) returns 0 if value is 0 or the position of the first
* set bit if value is nonzero. The first (least significant) bit
* is at position 1.
*/
static inline int ffs(int x)
{
int r;
#ifdef CONFIG_X86_64
/*
* AMD64 says BSFL won't clobber the dest reg if x==0; Intel64 says the
* dest reg is undefined if x==0, but their CPU architect says its
* value is written to set it to the same as before, except that the
* top 32 bits will be cleared.
*
* We cannot do this on 32 bits because at the very least some
* 486 CPUs did not behave this way.
*/
asm("bsfl %1,%0"
: "=r" (r)
: "rm" (x), "0" (-1));
#elif defined(CONFIG_X86_CMOV)
asm("bsfl %1,%0\n\t"
"cmovzl %2,%0"
: "=&r" (r) : "rm" (x), "r" (-1));
#else
asm("bsfl %1,%0\n\t"
"jnz 1f\n\t"
"movl $-1,%0\n"
"1:" : "=r" (r) : "rm" (x));
#endif
return r + 1;
}
/**
* fls - find last set bit in word
* @x: the word to search
*
* This is defined in a similar way as the libc and compiler builtin
* ffs, but returns the position of the most significant set bit.
*
* fls(value) returns 0 if value is 0 or the position of the last
* set bit if value is nonzero. The last (most significant) bit is
* at position 32.
*/
static inline int fls(int x)
{
int r;
#ifdef CONFIG_X86_64
/*
* AMD64 says BSRL won't clobber the dest reg if x==0; Intel64 says the
* dest reg is undefined if x==0, but their CPU architect says its
* value is written to set it to the same as before, except that the
* top 32 bits will be cleared.
*
* We cannot do this on 32 bits because at the very least some
* 486 CPUs did not behave this way.
*/
asm("bsrl %1,%0"
: "=r" (r)
: "rm" (x), "0" (-1));
#elif defined(CONFIG_X86_CMOV)
asm("bsrl %1,%0\n\t"
"cmovzl %2,%0"
: "=&r" (r) : "rm" (x), "rm" (-1));
#else
asm("bsrl %1,%0\n\t"
"jnz 1f\n\t"
"movl $-1,%0\n"
"1:" : "=r" (r) : "rm" (x));
#endif
return r + 1;
}
/**
* fls64 - find last set bit in a 64-bit word
* @x: the word to search
*
* This is defined in a similar way as the libc and compiler builtin
* ffsll, but returns the position of the most significant set bit.
*
* fls64(value) returns 0 if value is 0 or the position of the last
* set bit if value is nonzero. The last (most significant) bit is
* at position 64.
*/
#ifdef CONFIG_X86_64
static __always_inline int fls64(__u64 x)
{
int bitpos = -1;
/*
* AMD64 says BSRQ won't clobber the dest reg if x==0; Intel64 says the
* dest reg is undefined if x==0, but their CPU architect says its
* value is written to set it to the same as before.
*/
asm("bsrq %1,%q0"
: "+r" (bitpos)
: "rm" (x));
return bitpos + 1;
}
#else
#include <asm-generic/bitops/fls64.h>
#endif
#include <asm-generic/bitops/find.h>
#include <asm-generic/bitops/sched.h>
#define ARCH_HAS_FAST_MULTIPLIER 1
#include <asm/arch_hweight.h>
#include <asm-generic/bitops/const_hweight.h>
#include <asm-generic/bitops/le.h>
#include <asm-generic/bitops/ext2-atomic-setbit.h>
#endif /* __KERNEL__ */
#endif /* _ASM_X86_BITOPS_H */
|
a0a2055acab03318210f108feb873ff3334f09f5
|
6dde0318ea83e9475973a1963582609d36b125d4
|
/src/secp256k1/group.h
|
6a9c4837ee34281e83a056d6d7ab92116b699db3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
handshake-org/hnsd
|
a0783a03c858c925fcedbf5084286ac228a7a828
|
9ba045a0fb9e19bfac877c3973c9f627fbf436cf
|
refs/heads/master
| 2023-07-20T04:01:51.845433
| 2023-02-08T08:58:20
| 2023-02-08T09:12:30
| 120,840,335
| 279
| 59
|
NOASSERTION
| 2023-05-25T03:27:18
| 2018-02-09T01:30:38
|
C
|
UTF-8
|
C
| false
| false
| 8,547
|
h
|
group.h
|
/**********************************************************************
* Copyright (c) 2013, 2014 Pieter Wuille *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
**********************************************************************/
#ifndef HSK_SECP256K1_GROUP_H
#define HSK_SECP256K1_GROUP_H
#include "num.h"
#include "field.h"
/** A group element of the secp256k1 curve, in affine coordinates. */
typedef struct {
hsk_secp256k1_fe x;
hsk_secp256k1_fe y;
int infinity; /* whether this represents the point at infinity */
} hsk_secp256k1_ge;
#define HSK_SECP256K1_GE_CONST(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {HSK_SECP256K1_FE_CONST((a),(b),(c),(d),(e),(f),(g),(h)), HSK_SECP256K1_FE_CONST((i),(j),(k),(l),(m),(n),(o),(p)), 0}
#define HSK_SECP256K1_GE_CONST_INFINITY {HSK_SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), HSK_SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), 1}
/** A group element of the secp256k1 curve, in jacobian coordinates. */
typedef struct {
hsk_secp256k1_fe x; /* actual X: x/z^2 */
hsk_secp256k1_fe y; /* actual Y: y/z^3 */
hsk_secp256k1_fe z;
int infinity; /* whether this represents the point at infinity */
} hsk_secp256k1_gej;
#define HSK_SECP256K1_GEJ_CONST(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {HSK_SECP256K1_FE_CONST((a),(b),(c),(d),(e),(f),(g),(h)), HSK_SECP256K1_FE_CONST((i),(j),(k),(l),(m),(n),(o),(p)), HSK_SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 1), 0}
#define HSK_SECP256K1_GEJ_CONST_INFINITY {HSK_SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), HSK_SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), HSK_SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), 1}
typedef struct {
hsk_secp256k1_fe_storage x;
hsk_secp256k1_fe_storage y;
} hsk_secp256k1_ge_storage;
#define HSK_SECP256K1_GE_STORAGE_CONST(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {HSK_SECP256K1_FE_STORAGE_CONST((a),(b),(c),(d),(e),(f),(g),(h)), HSK_SECP256K1_FE_STORAGE_CONST((i),(j),(k),(l),(m),(n),(o),(p))}
#define HSK_SECP256K1_GE_STORAGE_CONST_GET(t) HSK_SECP256K1_FE_STORAGE_CONST_GET(t.x), HSK_SECP256K1_FE_STORAGE_CONST_GET(t.y)
/** Set a group element equal to the point with given X and Y coordinates */
static void hsk_secp256k1_ge_set_xy(hsk_secp256k1_ge *r, const hsk_secp256k1_fe *x, const hsk_secp256k1_fe *y);
/** Set a group element (affine) equal to the point with the given X coordinate
* and a Y coordinate that is a quadratic residue modulo p. The return value
* is true iff a coordinate with the given X coordinate exists.
*/
static int hsk_secp256k1_ge_set_xquad(hsk_secp256k1_ge *r, const hsk_secp256k1_fe *x);
/** Set a group element (affine) equal to the point with the given X coordinate, and given oddness
* for Y. Return value indicates whether the result is valid. */
static int hsk_secp256k1_ge_set_xo_var(hsk_secp256k1_ge *r, const hsk_secp256k1_fe *x, int odd);
/** Check whether a group element is the point at infinity. */
static int hsk_secp256k1_ge_is_infinity(const hsk_secp256k1_ge *a);
/** Check whether a group element is valid (i.e., on the curve). */
static int hsk_secp256k1_ge_is_valid_var(const hsk_secp256k1_ge *a);
static void hsk_secp256k1_ge_neg(hsk_secp256k1_ge *r, const hsk_secp256k1_ge *a);
/** Set a group element equal to another which is given in jacobian coordinates */
static void hsk_secp256k1_ge_set_gej(hsk_secp256k1_ge *r, hsk_secp256k1_gej *a);
/** Set a batch of group elements equal to the inputs given in jacobian coordinates */
static void hsk_secp256k1_ge_set_all_gej_var(hsk_secp256k1_ge *r, const hsk_secp256k1_gej *a, size_t len, const hsk_secp256k1_callback *cb);
/** Set a batch of group elements equal to the inputs given in jacobian
* coordinates (with known z-ratios). zr must contain the known z-ratios such
* that mul(a[i].z, zr[i+1]) == a[i+1].z. zr[0] is ignored. */
static void hsk_secp256k1_ge_set_table_gej_var(hsk_secp256k1_ge *r, const hsk_secp256k1_gej *a, const hsk_secp256k1_fe *zr, size_t len);
/** Bring a batch inputs given in jacobian coordinates (with known z-ratios) to
* the same global z "denominator". zr must contain the known z-ratios such
* that mul(a[i].z, zr[i+1]) == a[i+1].z. zr[0] is ignored. The x and y
* coordinates of the result are stored in r, the common z coordinate is
* stored in globalz. */
static void hsk_secp256k1_ge_globalz_set_table_gej(size_t len, hsk_secp256k1_ge *r, hsk_secp256k1_fe *globalz, const hsk_secp256k1_gej *a, const hsk_secp256k1_fe *zr);
/** Set a group element (affine) equal to the point at infinity. */
static void hsk_secp256k1_ge_set_infinity(hsk_secp256k1_ge *r);
/** Set a group element (jacobian) equal to the point at infinity. */
static void hsk_secp256k1_gej_set_infinity(hsk_secp256k1_gej *r);
/** Set a group element (jacobian) equal to another which is given in affine coordinates. */
static void hsk_secp256k1_gej_set_ge(hsk_secp256k1_gej *r, const hsk_secp256k1_ge *a);
/** Compare the X coordinate of a group element (jacobian). */
static int hsk_secp256k1_gej_eq_x_var(const hsk_secp256k1_fe *x, const hsk_secp256k1_gej *a);
/** Set r equal to the inverse of a (i.e., mirrored around the X axis) */
static void hsk_secp256k1_gej_neg(hsk_secp256k1_gej *r, const hsk_secp256k1_gej *a);
/** Check whether a group element is the point at infinity. */
static int hsk_secp256k1_gej_is_infinity(const hsk_secp256k1_gej *a);
/** Check whether a group element's y coordinate is a quadratic residue. */
static int hsk_secp256k1_gej_has_quad_y_var(const hsk_secp256k1_gej *a);
/** Set r equal to the double of a. If rzr is not-NULL, r->z = a->z * *rzr (where infinity means an implicit z = 0).
* a may not be zero. Constant time. */
static void hsk_secp256k1_gej_double_nonzero(hsk_secp256k1_gej *r, const hsk_secp256k1_gej *a, hsk_secp256k1_fe *rzr);
/** Set r equal to the double of a. If rzr is not-NULL, r->z = a->z * *rzr (where infinity means an implicit z = 0). */
static void hsk_secp256k1_gej_double_var(hsk_secp256k1_gej *r, const hsk_secp256k1_gej *a, hsk_secp256k1_fe *rzr);
/** Set r equal to the sum of a and b. If rzr is non-NULL, r->z = a->z * *rzr (a cannot be infinity in that case). */
static void hsk_secp256k1_gej_add_var(hsk_secp256k1_gej *r, const hsk_secp256k1_gej *a, const hsk_secp256k1_gej *b, hsk_secp256k1_fe *rzr);
/** Set r equal to the sum of a and b (with b given in affine coordinates, and not infinity). */
static void hsk_secp256k1_gej_add_ge(hsk_secp256k1_gej *r, const hsk_secp256k1_gej *a, const hsk_secp256k1_ge *b);
/** Set r equal to the sum of a and b (with b given in affine coordinates). This is more efficient
than hsk_secp256k1_gej_add_var. It is identical to hsk_secp256k1_gej_add_ge but without constant-time
guarantee, and b is allowed to be infinity. If rzr is non-NULL, r->z = a->z * *rzr (a cannot be infinity in that case). */
static void hsk_secp256k1_gej_add_ge_var(hsk_secp256k1_gej *r, const hsk_secp256k1_gej *a, const hsk_secp256k1_ge *b, hsk_secp256k1_fe *rzr);
/** Set r equal to the sum of a and b (with the inverse of b's Z coordinate passed as bzinv). */
static void hsk_secp256k1_gej_add_zinv_var(hsk_secp256k1_gej *r, const hsk_secp256k1_gej *a, const hsk_secp256k1_ge *b, const hsk_secp256k1_fe *bzinv);
#ifdef HSK_USE_ENDOMORPHISM
/** Set r to be equal to lambda times a, where lambda is chosen in a way such that this is very fast. */
static void hsk_secp256k1_ge_mul_lambda(hsk_secp256k1_ge *r, const hsk_secp256k1_ge *a);
#endif
/** Clear a hsk_secp256k1_gej to prevent leaking sensitive information. */
static void hsk_secp256k1_gej_clear(hsk_secp256k1_gej *r);
/** Clear a hsk_secp256k1_ge to prevent leaking sensitive information. */
static void hsk_secp256k1_ge_clear(hsk_secp256k1_ge *r);
/** Convert a group element to the storage type. */
static void hsk_secp256k1_ge_to_storage(hsk_secp256k1_ge_storage *r, const hsk_secp256k1_ge *a);
/** Convert a group element back from the storage type. */
static void hsk_secp256k1_ge_from_storage(hsk_secp256k1_ge *r, const hsk_secp256k1_ge_storage *a);
/** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. */
static void hsk_secp256k1_ge_storage_cmov(hsk_secp256k1_ge_storage *r, const hsk_secp256k1_ge_storage *a, int flag);
/** Rescale a jacobian point by b which must be non-zero. Constant-time. */
static void hsk_secp256k1_gej_rescale(hsk_secp256k1_gej *r, const hsk_secp256k1_fe *b);
#endif /* HSK_SECP256K1_GROUP_H */
|
91a19cb75901bffb3ec4329b6aba3c61dc670e66
|
996414c9504318dfb2cf82848332c757437b0848
|
/test/include/linear_algebra_test_helpers.h
|
9ffaad6623322d477a4a3e7a63c2396624e38f57
|
[
"MIT"
] |
permissive
|
nmwsharp/geometry-central
|
686cbb5dec05aaf4e59d6239ff7b856718494e4a
|
071756157a6122ead8fa978a35b06d1acc16451f
|
refs/heads/master
| 2023-08-27T18:13:11.146387
| 2023-06-21T20:47:16
| 2023-06-21T20:47:18
| 111,429,681
| 842
| 108
|
MIT
| 2023-06-05T20:20:49
| 2017-11-20T15:40:25
|
C++
|
UTF-8
|
C
| false
| false
| 106
|
h
|
linear_algebra_test_helpers.h
|
#pragma once
#include "geometrycentral/numerical/linear_algebra_utilities.h"
#include "gtest/gtest.h"
|
bec36b89ea5ac8e205d031c25066e39531f866a1
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/xnnpack/src/src/f32-rmax/f32-rmax-avx.c
|
365050b8a9362181af451645e65af2c23b107a05
|
[
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 1,659
|
c
|
f32-rmax-avx.c
|
// Copyright 2019 Google LLC
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include <assert.h>
#include <immintrin.h>
#include <xnnpack/rmax.h>
void xnn_f32_rmax_ukernel__avx(
size_t batch,
const float* input,
float* output)
{
assert(batch != 0);
assert(batch % sizeof(float) == 0);
assert(input != NULL);
assert(output != NULL);
__m256 vmax0 = _mm256_broadcast_ss(input);
__m256 vmax1 = vmax0;
__m256 vmax2 = vmax0;
__m256 vmax3 = vmax0;
for (; batch >= 128; batch -= 128) {
const __m256 vx0 = _mm256_loadu_ps(input);
const __m256 vx1 = _mm256_loadu_ps(input + 8);
const __m256 vx2 = _mm256_loadu_ps(input + 16);
const __m256 vx3 = _mm256_loadu_ps(input + 24);
input += 32;
vmax0 = _mm256_max_ps(vmax0, vx0);
vmax1 = _mm256_max_ps(vmax1, vx1);
vmax2 = _mm256_max_ps(vmax2, vx2);
vmax3 = _mm256_max_ps(vmax3, vx3);
}
__m256 vmax = _mm256_max_ps(_mm256_max_ps(vmax0, vmax1), _mm256_max_ps(vmax2, vmax3));
for (; batch >= 32; batch -= 32) {
const __m256 vx = _mm256_loadu_ps(input);
vmax = _mm256_max_ps(vmax, vx);
input += 8;
}
__m128 vmax_lo = _mm_max_ps(_mm256_castps256_ps128(vmax), _mm256_extractf128_ps(vmax, 1));
vmax_lo = _mm_max_ps(vmax_lo, _mm_movehl_ps(vmax_lo, vmax_lo));
vmax_lo = _mm_max_ss(vmax_lo, _mm_shuffle_ps(vmax_lo, vmax_lo, _MM_SHUFFLE(3, 3, 1, 1)));
if XNN_UNLIKELY(batch != 0) {
do {
vmax_lo = _mm_max_ss(vmax_lo, _mm_load_ss(input));
input += 1;
batch -= 4;
} while (batch != 0);
}
_mm_store_ss(output, vmax_lo);
}
|
9612bb93f6f2ae86f8e66998af71915776fe5913
|
d84c7df450292867f8c7bb58d1507735479d746d
|
/include/ceed/jit-source/sycl/sycl-gen-templates.h
|
25a3a2d2fb66b378eccadbefa7fd5113cb391a9b
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
CEED/libCEED
|
c17e8b2f8e9ccfafc0505bb6db451e2f7cfed690
|
c6c10e0994b55ea1726a79024cd4c333c40de38a
|
refs/heads/main
| 2023-09-01T20:13:21.268643
| 2023-09-01T20:08:36
| 2023-09-01T20:08:36
| 113,349,904
| 167
| 54
|
BSD-2-Clause
| 2023-09-14T20:37:58
| 2017-12-06T17:57:40
|
C
|
UTF-8
|
C
| false
| false
| 18,340
|
h
|
sycl-gen-templates.h
|
// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and other CEED contributors.
// All Rights Reserved. See the top-level LICENSE and NOTICE files for details.
//
// SPDX-License-Identifier: BSD-2-Clause
//
// This file is part of CEED: http://github.com/ceed
/// @file
/// Internal header for SYCL backend macro and type definitions for JiT source
#ifndef CEED_SYCL_GEN_TEMPLATES_H
#define CEED_SYCL_GEN_TEMPLATES_H
#include <ceed/types.h>
#pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable
#pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable
// TODO: Handle FP32 case
typedef atomic_double CeedAtomicScalar;
//------------------------------------------------------------------------------
// Load matrices for basis actions
//------------------------------------------------------------------------------
inline void loadMatrix(const CeedInt N, const CeedScalar* restrict d_B, CeedScalar* restrict B) {
const CeedInt item_id = get_local_linear_id();
const CeedInt group_size = get_local_size(0) * get_local_size(1) * get_local_size(2);
for (CeedInt i = item_id; i < N; i += group_size) B[i] = d_B[i];
}
//------------------------------------------------------------------------------
// 1D
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// L-vector -> E-vector, offsets provided
//------------------------------------------------------------------------------
inline void readDofsOffset1d(const CeedInt num_comp, const CeedInt strides_comp, const CeedInt P_1D, const CeedInt num_elem,
const global CeedInt* restrict indices, const global CeedScalar* restrict d_u, private CeedScalar* restrict r_u) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt elem = get_global_id(2);
if (item_id_x < P_1D && elem < num_elem) {
const CeedInt node = item_id_x;
const CeedInt ind = indices[node + elem * P_1D];
for (CeedInt comp = 0; comp < num_comp; ++comp) {
r_u[comp] = d_u[ind + strides_comp * comp];
}
}
}
//------------------------------------------------------------------------------
// L-vector -> E-vector, strided
//------------------------------------------------------------------------------
inline void readDofsStrided1d(const CeedInt num_comp, const CeedInt P_1D, const CeedInt strides_node, const CeedInt strides_comp,
const CeedInt strides_elem, const CeedInt num_elem, global const CeedScalar* restrict d_u,
private CeedScalar* restrict r_u) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt elem = get_global_id(2);
if (item_id_x < P_1D && elem < num_elem) {
const CeedInt node = item_id_x;
const CeedInt ind = node * strides_node + elem * strides_elem;
for (CeedInt comp = 0; comp < num_comp; comp++) {
r_u[comp] = d_u[ind + comp * strides_comp];
}
}
}
//------------------------------------------------------------------------------
// E-vector -> L-vector, offsets provided
//------------------------------------------------------------------------------
inline void writeDofsOffset1d(const CeedInt num_comp, const CeedInt strides_comp, const CeedInt P_1D, const CeedInt num_elem,
const global CeedInt* restrict indices, const private CeedScalar* restrict r_v, global CeedAtomicScalar* restrict d_v) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt elem = get_global_id(2);
if (item_id_x < P_1D && elem < num_elem) {
const CeedInt node = item_id_x;
const CeedInt ind = indices[node + elem * P_1D];
for (CeedInt comp = 0; comp < num_comp; ++comp)
atomic_fetch_add_explicit(&d_v[ind + strides_comp * comp], r_v[comp], memory_order_relaxed, memory_scope_device);
}
}
//------------------------------------------------------------------------------
// E-vector -> L-vector, strided
//------------------------------------------------------------------------------
inline void writeDofsStrided1d(const CeedInt num_comp, const CeedInt P_1D, const CeedInt strides_node, const CeedInt strides_comp,
const CeedInt strides_elem, const CeedInt num_elem, private const CeedScalar* restrict r_v,
global CeedScalar* restrict d_v) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt elem = get_global_id(2);
if (item_id_x < P_1D && elem < num_elem) {
const CeedInt node = item_id_x;
const CeedInt ind = node * strides_node + elem * strides_elem;
for (CeedInt comp = 0; comp < num_comp; comp++) {
d_v[ind + comp * strides_comp] = r_v[comp];
}
}
}
//------------------------------------------------------------------------------
// 2D
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// L-vector -> E-vector, offsets provided
//------------------------------------------------------------------------------
inline void readDofsOffset2d(const CeedInt num_comp, const CeedInt strides_comp, const CeedInt P_1D, const CeedInt num_elem,
const global CeedInt* restrict indices, const global CeedScalar* restrict d_u, private CeedScalar* restrict r_u) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt item_id_y = get_local_id(1);
const CeedInt elem = get_global_id(2);
if (item_id_x < P_1D && item_id_y < P_1D && elem < num_elem) {
const CeedInt node = item_id_x + item_id_y * P_1D;
const CeedInt ind = indices[node + elem * P_1D * P_1D];
for (CeedInt comp = 0; comp < num_comp; ++comp) r_u[comp] = d_u[ind + strides_comp * comp];
}
}
//------------------------------------------------------------------------------
// L-vector -> E-vector, strided
//------------------------------------------------------------------------------
inline void readDofsStrided2d(const CeedInt num_comp, const CeedInt P_1D, const CeedInt strides_node, const CeedInt strides_comp,
const CeedInt strides_elem, const CeedInt num_elem, const global CeedScalar* restrict d_u,
private CeedScalar* restrict r_u) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt item_id_y = get_local_id(1);
const CeedInt elem = get_global_id(2);
if (item_id_x < P_1D && item_id_y < P_1D && elem < num_elem) {
const CeedInt node = item_id_x + item_id_y * P_1D;
const CeedInt ind = node * strides_node + elem * strides_elem;
for (CeedInt comp = 0; comp < num_comp; ++comp) r_u[comp] = d_u[ind + comp * strides_comp];
}
}
//------------------------------------------------------------------------------
// E-vector -> L-vector, offsets provided
//------------------------------------------------------------------------------
inline void writeDofsOffset2d(const CeedInt num_comp, const CeedInt strides_comp, const CeedInt P_1D, const CeedInt num_elem,
const global CeedInt* restrict indices, const private CeedScalar* restrict r_v, global CeedAtomicScalar* restrict d_v) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt item_id_y = get_local_id(1);
const CeedInt elem = get_global_id(2);
if (item_id_x < P_1D && item_id_y < P_1D && elem < num_elem) {
const CeedInt node = item_id_x + item_id_y * P_1D;
const CeedInt ind = indices[node + elem * P_1D * P_1D];
for (CeedInt comp = 0; comp < num_comp; ++comp)
atomic_fetch_add_explicit(&d_v[ind + strides_comp * comp], r_v[comp], memory_order_relaxed, memory_scope_device);
}
}
//------------------------------------------------------------------------------
// E-vector -> L-vector, strided
//------------------------------------------------------------------------------
inline void writeDofsStrided2d(const CeedInt num_comp, const CeedInt P_1D, const CeedInt strides_node, const CeedInt strides_comp,
const CeedInt strides_elem, const CeedInt num_elem, const private CeedScalar* restrict r_v,
global CeedScalar* restrict d_v) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt item_id_y = get_local_id(1);
const CeedInt elem = get_global_id(2);
if (item_id_x < P_1D && item_id_y < P_1D && elem < num_elem) {
const CeedInt node = item_id_x + item_id_y * P_1D;
const CeedInt ind = node * strides_node + elem * strides_elem;
for (CeedInt comp = 0; comp < num_comp; ++comp) d_v[ind + comp * strides_comp] += r_v[comp];
}
}
//------------------------------------------------------------------------------
// 3D
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// L-vector -> E-vector, offsets provided
//------------------------------------------------------------------------------
inline void readDofsOffset3d(const CeedInt num_comp, const CeedInt strides_comp, const CeedInt P_1D, const CeedInt num_elem,
const global CeedInt* restrict indices, const global CeedScalar* restrict d_u, private CeedScalar* restrict r_u) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt item_id_y = get_local_id(1);
const CeedInt elem = get_global_id(2);
if (item_id_x < P_1D && item_id_y < P_1D && elem < num_elem) {
for (CeedInt z = 0; z < P_1D; ++z) {
const CeedInt node = item_id_x + P_1D * (item_id_y + P_1D * z);
const CeedInt ind = indices[node + elem * P_1D * P_1D * P_1D];
for (CeedInt comp = 0; comp < num_comp; ++comp) r_u[z + comp * P_1D] = d_u[ind + strides_comp * comp];
}
}
}
//------------------------------------------------------------------------------
// L-vector -> E-vector, strided
//------------------------------------------------------------------------------
inline void readDofsStrided3d(const CeedInt num_comp, const CeedInt P_1D, const CeedInt strides_node, const CeedInt strides_comp,
const CeedInt strides_elem, const CeedInt num_elem, const global CeedScalar* restrict d_u,
private CeedScalar* restrict r_u) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt item_id_y = get_local_id(1);
const CeedInt elem = get_global_id(2);
if (item_id_x < P_1D && item_id_y < P_1D && elem < num_elem) {
for (CeedInt z = 0; z < P_1D; ++z) {
const CeedInt node = item_id_x + P_1D * (item_id_y + P_1D * z);
const CeedInt ind = node * strides_node + elem * strides_elem;
for (CeedInt comp = 0; comp < num_comp; ++comp) r_u[z + comp * P_1D] = d_u[ind + comp * strides_comp];
}
}
}
//------------------------------------------------------------------------------
// E-vector -> Q-vector, offests provided
//------------------------------------------------------------------------------
inline void readSliceQuadsOffset3d(const CeedInt num_comp, const CeedInt strides_comp, const CeedInt Q_1D, const CeedInt num_elem, const CeedInt q,
const global CeedInt* restrict indices, const global CeedScalar* restrict d_u, private CeedScalar* restrict r_u) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt item_id_y = get_local_id(1);
const CeedInt elem = get_global_id(2);
if (item_id_x < Q_1D && item_id_y < Q_1D && elem < num_elem) {
const CeedInt node = item_id_x + Q_1D * (item_id_y + Q_1D * q);
const CeedInt ind = indices[node + elem * Q_1D * Q_1D * Q_1D];
for (CeedInt comp = 0; comp < num_comp; ++comp) r_u[comp] = d_u[ind + strides_comp * comp];
}
}
//------------------------------------------------------------------------------
// E-vector -> Q-vector, strided
//------------------------------------------------------------------------------
inline void readSliceQuadsStrided3d(const CeedInt num_comp, const CeedInt Q_1D, CeedInt strides_node, CeedInt strides_comp, CeedInt strides_elem,
const CeedInt num_elem, const CeedInt q, const global CeedScalar* restrict d_u,
private CeedScalar* restrict r_u) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt item_id_y = get_local_id(1);
const CeedInt elem = get_global_id(2);
if (item_id_x < Q_1D && item_id_y < Q_1D && elem < num_elem) {
const CeedInt node = item_id_x + Q_1D * (item_id_y + Q_1D * q);
const CeedInt ind = node * strides_node + elem * strides_elem;
for (CeedInt comp = 0; comp < num_comp; ++comp) r_u[comp] = d_u[ind + comp * strides_comp];
}
}
//------------------------------------------------------------------------------
// E-vector -> L-vector, offsets provided
//------------------------------------------------------------------------------
inline void writeDofsOffset3d(const CeedInt num_comp, const CeedInt strides_comp, const CeedInt P_1D, const CeedInt num_elem,
const global CeedInt* restrict indices, const private CeedScalar* restrict r_v, global CeedAtomicScalar* restrict d_v) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt item_id_y = get_local_id(1);
const CeedInt elem = get_global_id(2);
if (item_id_x < P_1D && item_id_y < P_1D && elem < num_elem) {
for (CeedInt z = 0; z < P_1D; ++z) {
const CeedInt node = item_id_x + item_id_y * P_1D + z * P_1D * P_1D;
const CeedInt ind = indices[node + elem * P_1D * P_1D * P_1D];
for (CeedInt comp = 0; comp < num_comp; ++comp)
atomic_fetch_add_explicit(&d_v[ind + strides_comp * comp], r_v[z + comp * P_1D], memory_order_relaxed, memory_scope_device);
}
}
}
//------------------------------------------------------------------------------
// E-vector -> L-vector, strided
//------------------------------------------------------------------------------
inline void writeDofsStrided3d(const CeedInt num_comp, const CeedInt P_1D, const CeedInt strides_node, const CeedInt strides_comp,
const CeedInt strides_elem, const CeedInt num_elem, const private CeedScalar* restrict r_v,
global CeedScalar* restrict d_v) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt item_id_y = get_local_id(1);
const CeedInt elem = get_global_id(2);
if (item_id_x < P_1D && item_id_y < P_1D && elem < num_elem) {
for (CeedInt z = 0; z < P_1D; ++z) {
const CeedInt node = item_id_x + P_1D * (item_id_y + P_1D * z);
const CeedInt ind = node * strides_node + elem * strides_elem;
for (CeedInt comp = 0; comp < num_comp; ++comp) d_v[ind + comp * strides_comp] += r_v[z + comp * P_1D];
}
}
}
//------------------------------------------------------------------------------
// 3D collocated derivatives computation
//------------------------------------------------------------------------------
inline void gradCollo3d(const CeedInt num_comp, const CeedInt Q_1D, const CeedInt q, const private CeedScalar* restrict r_U,
const local CeedScalar* s_G, private CeedScalar* restrict r_V, local CeedScalar* restrict scratch) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt item_id_y = get_local_id(1);
for (CeedInt comp = 0; comp < num_comp; ++comp) {
if (item_id_x < Q_1D && item_id_y < Q_1D) {
scratch[item_id_x + item_id_y * T_1D] = r_U[q + comp * Q_1D];
}
work_group_barrier(CLK_LOCAL_MEM_FENCE);
if (item_id_x < Q_1D && item_id_y < Q_1D) {
// X derivative
r_V[comp + 0 * num_comp] = 0.0;
for (CeedInt i = 0; i < Q_1D; ++i)
r_V[comp + 0 * num_comp] += s_G[i + item_id_x * Q_1D] * scratch[i + item_id_y * T_1D]; // Contract x direction (X derivative)
// Y derivative
r_V[comp + 1 * num_comp] = 0.0;
for (CeedInt i = 0; i < Q_1D; ++i)
r_V[comp + 1 * num_comp] += s_G[i + item_id_y * Q_1D] * scratch[item_id_x + i * T_1D]; // Contract y direction (Y derivative)
// Z derivative
r_V[comp + 2 * num_comp] = 0.0;
for (CeedInt i = 0; i < Q_1D; ++i) r_V[comp + 2 * num_comp] += s_G[i + q * Q_1D] * r_U[i + comp * Q_1D]; // Contract z direction (Z derivative)
}
work_group_barrier(CLK_LOCAL_MEM_FENCE);
}
}
//------------------------------------------------------------------------------
// 3D collocated derivatives transpose
//------------------------------------------------------------------------------
inline void gradColloTranspose3d(const CeedInt num_comp, const CeedInt Q_1D, const CeedInt q, const private CeedScalar* restrict r_U,
const local CeedScalar* restrict s_G, private CeedScalar* restrict r_V, local CeedScalar* restrict scratch) {
const CeedInt item_id_x = get_local_id(0);
const CeedInt item_id_y = get_local_id(1);
for (CeedInt comp = 0; comp < num_comp; ++comp) {
// X derivative
if (item_id_x < Q_1D && item_id_y < Q_1D) {
scratch[item_id_x + item_id_y * T_1D] = r_U[comp + 0 * num_comp];
}
work_group_barrier(CLK_LOCAL_MEM_FENCE);
if (item_id_x < Q_1D && item_id_y < Q_1D) {
for (CeedInt i = 0; i < Q_1D; ++i)
r_V[q + comp * Q_1D] += s_G[item_id_x + i * Q_1D] * scratch[i + item_id_y * T_1D]; // Contract x direction (X derivative)
}
work_group_barrier(CLK_LOCAL_MEM_FENCE);
// Y derivative
if (item_id_x < Q_1D && item_id_y < Q_1D) {
scratch[item_id_x + item_id_y * T_1D] = r_U[comp + 1 * num_comp];
}
work_group_barrier(CLK_LOCAL_MEM_FENCE);
if (item_id_x < Q_1D && item_id_y < Q_1D) {
for (CeedInt i = 0; i < Q_1D; ++i)
r_V[q + comp * Q_1D] += s_G[item_id_y + i * Q_1D] * scratch[item_id_x + i * T_1D]; // Contract y direction (Y derivative)
}
work_group_barrier(CLK_LOCAL_MEM_FENCE);
// Z derivative
if (item_id_x < Q_1D && item_id_y < Q_1D) {
for (CeedInt i = 0; i < Q_1D; ++i)
r_V[i + comp * Q_1D] += s_G[i + q * Q_1D] * r_U[comp + 2 * num_comp]; // PARTIAL contract z direction (Z derivative)
}
}
}
//------------------------------------------------------------------------------
#endif // CEED_SYCL_GEN_TEMPLATES_H
|
4afacfa8c164f036ab7eacb4b1b5f52b73c76a6c
|
765f7b8c2caf2d50da8f431f1332207456ba33ee
|
/apps/terminal.c
|
f436f7c1af411cce0c666cb40e80cbba95f66ebe
|
[
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later",
"GPL-1.0-or-later",
"NCSA",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
klange/toaruos
|
a840f8d46993dc7a8850f82b6d04ba0c2af276a9
|
4a31a09ba27904b42ee35e8fb1a3c7f87669a2ef
|
refs/heads/master
| 2023-09-01T02:00:53.151334
| 2023-08-28T00:59:18
| 2023-08-28T00:59:18
| 1,259,258
| 5,557
| 613
|
NCSA
| 2023-02-04T08:24:11
| 2011-01-16T00:59:27
|
C
|
UTF-8
|
C
| false
| false
| 77,920
|
c
|
terminal.c
|
/**
* @brief Virtual terminal emulator.
*
* Provides a graphical character cell terminal with support for
* antialiased text, basic Unicode, bitmap fallbacks, nearly
* complete ANSI escape sequence support, 256- and 24-bit color,
* scrollback, selection, alternate screens, and various scroll
* methods.
*
* @copyright
* This file is part of ToaruOS and is released under the terms
* of the NCSA / University of Illinois License - see LICENSE.md
* Copyright (C) 2013-2022 K. Lange
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <getopt.h>
#include <errno.h>
#include <pty.h>
#include <wchar.h>
#include <dlfcn.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/fswait.h>
#define TRACE_APP_NAME "terminal"
#include <toaru/trace.h>
#include <toaru/decodeutf8.h>
#include <toaru/yutani.h>
#include <toaru/decorations.h>
#include <toaru/graphics.h>
#include <toaru/kbd.h>
#include <toaru/termemu.h>
#include <toaru/spinlock.h>
#include <toaru/list.h>
#include <toaru/menu.h>
#include <toaru/text.h>
/* 16- and 256-color palette */
#include "terminal-palette.h"
/* Bitmap font */
#include "terminal-font.h"
/* Show help text */
static void usage(char * argv[]) {
printf(
"Terminal Emulator\n"
"\n"
"usage: %s [-Fbxn] [-s SCALE] [-g WIDTHxHEIGHT] [COMMAND...]\n"
"\n"
" -F --fullscreen \033[3mRun in fullscreen (background) mode.\033[0m\n"
" -b --bitmap \033[3mUse the integrated bitmap font.\033[0m\n"
" -s --scale \033[3mScale the font in antialiased mode by a given amount.\033[0m\n"
" -h --help \033[3mShow this help message.\033[0m\n"
" -x --grid \033[3mMake resizes round to nearest match for character cell size.\033[0m\n"
" -n --no-frame \033[3mDisable decorations.\033[0m\n"
" -g --geometry \033[3mSet requested terminal size WIDTHxHEIGHT\033[0m\n"
" -B --blurred \033[3mBlur background behind terminal.\033[0m\n"
" -S --scrollback \033[3mSet the scrollback buffer size, 0 for unlimited.\033[0m\n"
"\n"
" This terminal emulator provides basic support for VT220 escapes and\n"
" XTerm extensions, including 256 color support and font effects.\n",
argv[0]);
}
/* master and slave pty descriptors */
static int fd_master, fd_slave;
static FILE * terminal;
static pid_t child_pid = 0;
static int scale_fonts = 0; /* Whether fonts should be scaled */
static float font_scaling = 1.0; /* How much they should be scaled by */
static uint16_t term_width = 0; /* Width of the terminal (in cells) */
static uint16_t term_height = 0; /* Height of the terminal (in cells) */
static uint16_t font_size = 16; /* Font size according to tt library */
static uint16_t char_width = 8; /* Width of a cell in pixels */
static uint16_t char_height = 17; /* Height of a cell in pixels */
static uint16_t char_offset = 0; /* Offset of the font within the cell */
static int csr_x = 0; /* Cursor X */
static int csr_y = 0; /* Cursor Y */
static int csr_h = 0; /* Cursor last column hold flag */
static uint32_t current_fg = 7; /* Current foreground color */
static uint32_t current_bg = 0; /* Current background color */
static term_cell_t * term_buffer = NULL; /* The active terminal cell buffer */
static term_cell_t * term_buffer_a = NULL; /* The main buffer */
static term_cell_t * term_buffer_b = NULL; /* The secondary buffer */
static term_cell_t * term_mirror = NULL; /* What we want to draw */
static term_cell_t * term_display = NULL; /* What we think we've drawn already */
static term_state_t * ansi_state = NULL; /* ANSI parser library state */
static int active_buffer = 0;
static int _orig_x = 0;
static int _orig_y = 0;
static uint32_t _orig_fg = 7;
static uint32_t _orig_bg = 0;
static bool cursor_on = 1; /* Whether or not the cursor should be rendered */
static bool _fullscreen = 0; /* Whether or not we are running in fullscreen mode (GUI only) */
static bool _no_frame = 0; /* Whether to disable decorations or not */
static bool _use_aa = 1; /* Whether or not to use best-available anti-aliased renderer */
static bool _free_size = 1; /* Disable rounding when resized */
static struct TT_Font * _tt_font_normal = NULL;
static struct TT_Font * _tt_font_bold = NULL;
static struct TT_Font * _tt_font_oblique = NULL;
static struct TT_Font * _tt_font_bold_oblique = NULL;
static struct TT_Font * _tt_font_fallback = NULL;
static struct TT_Font * _tt_font_japanese = NULL;
static list_t * images_list = NULL;
static int menu_bar_height = 24;
/* Text selection information */
static int selection = 0;
static int selection_start_x = 0;
static int selection_start_y = 0;
static int selection_end_x = 0;
static int selection_end_y = 0;
static char * selection_text = NULL;
static int _selection_count = 0;
static int _selection_i = 0;
/* Mouse state */
static int last_mouse_x = -1;
static int last_mouse_y = -1;
static int button_state = 0;
static unsigned long long mouse_ticks = 0;
static yutani_window_t * window = NULL; /* GUI window */
static yutani_t * yctx = NULL;
/* Window flip bounds */
static int32_t l_x = INT32_MAX;
static int32_t l_y = INT32_MAX;
static int32_t r_x = -1;
static int32_t r_y = -1;
static uint32_t window_width = 640;
static uint32_t window_height = 480;
static bool window_position_set = 0;
static int32_t window_left = 0;
static int32_t window_top = 0;
#define TERMINAL_TITLE_SIZE 512
static char terminal_title[TERMINAL_TITLE_SIZE];
static size_t terminal_title_length = 0;
static gfx_context_t * ctx;
static struct MenuList * menu_right_click = NULL;
static void render_decors(void);
static void term_clear(int i);
static void reinit(void);
static void term_redraw_cursor();
static int decor_left_width = 0;
static int decor_top_height = 0;
static int decor_right_width = 0;
static int decor_bottom_height = 0;
static int decor_width = 0;
static int decor_height = 0;
struct scrollback_row {
unsigned short width;
term_cell_t cells[];
};
static size_t max_scrollback = 10000;
static list_t * scrollback_list = NULL;
static int scrollback_offset = 0;
/* Menu bar entries */
struct menu_bar terminal_menu_bar = {0};
struct menu_bar_entries terminal_menu_entries[] = {
{"File", "file"},
{"Edit", "edit"},
{"View", "view"},
{"Help", "help"},
{NULL, NULL},
};
/* Trigger to exit the terminal when the child process dies or
* we otherwise receive an exit signal */
static volatile int exit_application = 0;
static void cell_redraw(uint16_t x, uint16_t y);
static void cell_redraw_inverted(uint16_t x, uint16_t y);
static void cell_redraw_offset(uint16_t x, uint16_t y);
static void cell_redraw_offset_inverted(uint16_t x, uint16_t y);
static void update_bounds(void);
static uint64_t get_ticks(void) {
struct timeval now;
gettimeofday(&now, NULL);
return (uint64_t)now.tv_sec * 1000000LL + (uint64_t)now.tv_usec;
}
static void display_flip(void) {
if (l_x != INT32_MAX && l_y != INT32_MAX) {
flip(ctx);
yutani_flip_region(yctx, window, l_x, l_y, r_x - l_x, r_y - l_y);
l_x = INT32_MAX;
l_y = INT32_MAX;
r_x = -1;
r_y = -1;
}
}
/* Returns the lower of two shorts */
static int32_t min(int32_t a, int32_t b) {
return (a < b) ? a : b;
}
/* Returns the higher of two shorts */
static int32_t max(int32_t a, int32_t b) {
return (a > b) ? a : b;
}
/*
* Convert codepoint to UTF-8
*
* Returns length of byte sequence written.
*/
static int to_eight(uint32_t codepoint, char * out) {
memset(out, 0x00, 7);
if (codepoint < 0x0080) {
out[0] = (char)codepoint;
} else if (codepoint < 0x0800) {
out[0] = 0xC0 | (codepoint >> 6);
out[1] = 0x80 | (codepoint & 0x3F);
} else if (codepoint < 0x10000) {
out[0] = 0xE0 | (codepoint >> 12);
out[1] = 0x80 | ((codepoint >> 6) & 0x3F);
out[2] = 0x80 | (codepoint & 0x3F);
} else if (codepoint < 0x200000) {
out[0] = 0xF0 | (codepoint >> 18);
out[1] = 0x80 | ((codepoint >> 12) & 0x3F);
out[2] = 0x80 | ((codepoint >> 6) & 0x3F);
out[3] = 0x80 | ((codepoint) & 0x3F);
} else if (codepoint < 0x4000000) {
out[0] = 0xF8 | (codepoint >> 24);
out[1] = 0x80 | (codepoint >> 18);
out[2] = 0x80 | ((codepoint >> 12) & 0x3F);
out[3] = 0x80 | ((codepoint >> 6) & 0x3F);
out[4] = 0x80 | ((codepoint) & 0x3F);
} else {
out[0] = 0xF8 | (codepoint >> 30);
out[1] = 0x80 | ((codepoint >> 24) & 0x3F);
out[2] = 0x80 | ((codepoint >> 18) & 0x3F);
out[3] = 0x80 | ((codepoint >> 12) & 0x3F);
out[4] = 0x80 | ((codepoint >> 6) & 0x3F);
out[5] = 0x80 | ((codepoint) & 0x3F);
}
return strlen(out);
}
/* Set the terminal title string */
static void set_title(char * c) {
int len = min(TERMINAL_TITLE_SIZE, strlen(c)+1);
memcpy(terminal_title, c, len);
terminal_title[len-1] = '\0';
terminal_title_length = len - 1;
render_decors();
}
/* Call a function for each selected cell */
static void iterate_selection(void (*func)(uint16_t x, uint16_t y)) {
if (!selection) return;
if (selection_end_y < selection_start_y) {
for (int x = selection_end_x; x < term_width; ++x) {
func(x, selection_end_y);
}
for (int y = selection_end_y + 1; y < selection_start_y; ++y) {
for (int x = 0; x < term_width; ++x) {
func(x, y);
}
}
for (int x = 0; x <= selection_start_x; ++x) {
func(x, selection_start_y);
}
} else if (selection_start_y == selection_end_y) {
if (selection_start_x > selection_end_x) {
for (int x = selection_end_x; x <= selection_start_x; ++x) {
func(x, selection_start_y);
}
} else {
for (int x = selection_start_x; x <= selection_end_x; ++x) {
func(x, selection_start_y);
}
}
} else {
for (int x = selection_start_x; x < term_width; ++x) {
func(x, selection_start_y);
}
for (int y = selection_start_y + 1; y < selection_end_y; ++y) {
for (int x = 0; x < term_width; ++x) {
func(x, y);
}
}
for (int x = 0; x <= selection_end_x; ++x) {
func(x, selection_end_y);
}
}
}
/* Redraw the selection with the selection hint (inversion) */
static void redraw_selection(void) {
iterate_selection(cell_redraw_offset_inverted);
}
static term_cell_t * cell_at(uint16_t x, uint16_t _y) {
int y = _y;
y -= scrollback_offset;
if (y >= 0) {
return &term_buffer[y * term_width + x];
} else {
node_t * node = scrollback_list->tail;
for (; y < -1; y++) {
if (!node) break;
node = node->prev;
}
if (node) {
struct scrollback_row * row = (struct scrollback_row *)node->value;
if (row && x < row->width) {
return &row->cells[x];
}
}
}
return NULL;
}
static void mark_cell(uint16_t x, uint16_t y) {
term_cell_t * c = cell_at(x,y);
if (c) {
c->flags |= 0x200;
}
}
static void mark_selection(void) {
iterate_selection(mark_cell);
}
static void red_cell(uint16_t x, uint16_t y) {
term_cell_t * c = cell_at(x,y);
if (c) {
if (c->flags & 0x200) {
c->flags &= ~(0x200);
} else {
c->flags |= 0x400;
}
}
}
static void flip_selection(void) {
iterate_selection(red_cell);
for (int y = 0; y < term_height; ++y) {
for (int x = 0; x < term_width; ++x) {
term_cell_t * c = cell_at(x,y);
if (c) {
if (c->flags & 0x200) cell_redraw_offset(x,y);
if (c->flags & 0x400) cell_redraw_offset_inverted(x,y);
c->flags &= ~(0x600);
}
}
}
}
/* Figure out how long the UTF-8 selection string should be. */
static void count_selection(uint16_t x, uint16_t _y) {
int y = _y;
y -= scrollback_offset;
if (y >= 0) {
term_cell_t * cell = &term_buffer[y * term_width + x];
if (!(cell->flags & ANSI_EXT_IMG)) {
if (((uint32_t *)cell)[0] != 0x00000000) {
char tmp[7];
_selection_count += to_eight(cell->c, tmp);
}
}
} else {
node_t * node = scrollback_list->tail;
for (; y < -1; y++) {
if (!node) break;
node = node->prev;
}
if (node) {
struct scrollback_row * row = (struct scrollback_row *)node->value;
if (row && x < row->width) {
term_cell_t * cell = &row->cells[x];
if (cell && ((uint32_t *)cell)[0] != 0x00000000) {
char tmp[7];
_selection_count += to_eight(cell->c, tmp);
}
}
}
}
if (x == term_width - 1) {
_selection_count++;
}
}
/* Fill the selection text buffer with the selected text. */
void write_selection(uint16_t x, uint16_t _y) {
int y = _y;
y -= scrollback_offset;
if (y >= 0) {
term_cell_t * cell = &term_buffer[y * term_width + x];
if (!(cell->flags & ANSI_EXT_IMG)) {
if (((uint32_t *)cell)[0] != 0x00000000 && cell->c != 0xFFFF) {
char tmp[7];
int count = to_eight(cell->c, tmp);
for (int i = 0; i < count; ++i) {
selection_text[_selection_i] = tmp[i];
_selection_i++;
}
}
}
} else {
node_t * node = scrollback_list->tail;
for (; y < -1; y++) {
if (!node) break;
node = node->prev;
}
if (node) {
struct scrollback_row * row = (struct scrollback_row *)node->value;
if (row && x < row->width) {
term_cell_t * cell = &row->cells[x];
if (cell && ((uint32_t *)cell)[0] != 0x00000000 && cell->c != 0xFFFF) {
char tmp[7];
int count = to_eight(cell->c, tmp);
for (int i = 0; i < count; ++i) {
selection_text[_selection_i] = tmp[i];
_selection_i++;
}
}
}
}
}
if (x == term_width - 1) {
selection_text[_selection_i] = '\n';;
_selection_i++;
}
}
/* Copy the selection text to the clipboard. */
static char * copy_selection(void) {
_selection_count = 0;
iterate_selection(count_selection);
if (selection_text) {
free(selection_text);
}
if (_selection_count == 0) {
return NULL;
}
selection_text = malloc(_selection_count + 1);
selection_text[_selection_count] = '\0';
_selection_i = 0;
iterate_selection(write_selection);
if (selection_text[_selection_count-1] == '\n') {
/* Don't end on a line feed */
selection_text[_selection_count-1] = '\0';
}
yutani_set_clipboard(yctx, selection_text);
return selection_text;
}
static volatile int input_buffer_lock = 0;
static int input_buffer_semaphore[2];
static list_t * input_buffer_queue = NULL;
struct input_data {
size_t len;
char data[];
};
void * handle_input_writing(void * unused) {
(void)unused;
while (1) {
/* Read one byte from semaphore; as long as semaphore has data,
* there is another input blob to write to the TTY */
char tmp[1];
int c = read(input_buffer_semaphore[0],tmp,1);
if (c > 0) {
/* Retrieve blob */
spin_lock(&input_buffer_lock);
node_t * blob = list_dequeue(input_buffer_queue);
spin_unlock(&input_buffer_lock);
/* No blobs? This shouldn't happen, but just in case, just continue */
if (!blob) {
continue;
}
/* Write blob data to the tty */
struct input_data * value = blob->value;
write(fd_master, value->data, value->len);
free(blob->value);
free(blob);
} else {
/* The pipe has closed, terminal is exiting */
break;
}
}
return NULL;
}
static void write_input_buffer(char * data, size_t len) {
struct input_data * d = malloc(sizeof(struct input_data) + len);
d->len = len;
memcpy(&d->data, data, len);
spin_lock(&input_buffer_lock);
list_insert(input_buffer_queue, d);
spin_unlock(&input_buffer_lock);
write(input_buffer_semaphore[1], d, 1);
}
/* Stuffs a string into the stdin of the terminal's child process
* Useful for things like the ANSI DSR command. */
static void input_buffer_stuff(char * str) {
size_t len = strlen(str);
write_input_buffer(str, len);
}
/* Redraw the decorations */
static void render_decors(void) {
/* Don't draw decorations or bother advertising the window if in "fullscreen mode" */
if (_fullscreen) return;
if (!_no_frame) {
/* Draw the decorations */
render_decorations(window, ctx, terminal_title_length ? terminal_title : "Terminal");
/* Update menu bar position and size */
terminal_menu_bar.x = decor_left_width;
terminal_menu_bar.y = decor_top_height;
terminal_menu_bar.width = window_width;
terminal_menu_bar.window = window;
/* Redraw the menu bar */
menu_bar_render(&terminal_menu_bar, ctx);
}
/* Advertise the window icon to the panel. */
yutani_window_advertise_icon(yctx, window, terminal_title_length ? terminal_title : "Terminal", "utilities-terminal");
/*
* Flip the whole window
* We do this regardless of whether we drew decorations to catch
* a case where decorations are toggled.
*/
l_x = 0; l_y = 0;
r_x = window->width;
r_y = window->height;
display_flip();
}
/* Set a pixel in the terminal cell area */
static inline void term_set_point(uint16_t x, uint16_t y, uint32_t color ) {
GFX(ctx, (x+decor_left_width),(y+decor_top_height+menu_bar_height)) = color;
}
static void _fill_region(uint32_t _bg, uint16_t x, uint16_t y, uint16_t width, uint16_t height) {
for (uint8_t i = 0; i < height; ++i) {
for (uint8_t j = 0; j < width; ++j) {
term_set_point(x+j,y+i,_bg);
}
}
}
/* Draw a partial block character. */
static void draw_semi_block(int c, int x, int y, uint32_t fg, uint32_t bg) {
bg = premultiply(bg);
fg = alpha_blend_rgba(bg, premultiply(fg));
_fill_region(bg, x, y, char_width, char_height);
if (c == 0x2580) {
for (uint8_t i = 0; i < char_height / 2; ++i) {
for (uint8_t j = 0; j < char_width; ++j) {
term_set_point(x+j,y+i,fg);
}
}
} else if (c >= 0x2589) {
c -= 0x2588;
int width = char_width - ((c * char_width) / 8);
for (uint8_t i = 0; i < char_height; ++i) {
for (uint8_t j = 0; j < width; ++j) {
term_set_point(x+j, y+i, fg);
}
}
} else {
c -= 0x2580;
int height = char_height - ((c * char_height) / 8);
for (uint8_t i = height; i < char_height; ++i) {
for (uint8_t j = 0; j < char_width; ++j) {
term_set_point(x+j, y+i,fg);
}
}
}
}
static void draw_box_drawing(int c, int x, int y, uint32_t fg, uint32_t bg) {
bg = premultiply(bg);
fg = alpha_blend_rgba(bg, premultiply(fg));
_fill_region(bg, x, y, char_width, char_height);
int lineheight = char_height / 16;
int linewidth = char_width / 8;
lineheight = lineheight < 1 ? 1 : lineheight;
linewidth = linewidth < 1 ? 1 : linewidth;
int mid_x = char_width / 2 - linewidth / 2;
int mid_y = char_height / 2 - lineheight / 2;
int extra_x = (mid_x * 2 < char_width) ? char_width - mid_x * 2 : 0;
int extra_y = (mid_y * 2 < char_height) ? char_height - mid_y * 2 : 0;
#define UP _fill_region(fg, x + mid_x, y, linewidth, mid_y + lineheight)
#define DOWN _fill_region(fg, x + mid_x, y + mid_y, linewidth, mid_y + extra_y)
#define LEFT _fill_region(fg, x, y + mid_y, mid_x + linewidth, lineheight)
#define RIGHT _fill_region(fg, x + mid_x, y + mid_y, mid_x + extra_x, lineheight)
#define VERT _fill_region(fg, x + mid_x, y, linewidth, char_height)
#define HORI _fill_region(fg, x, y + mid_y, char_width, lineheight)
switch (c) {
case 0x2500: HORI; break;
case 0x2502: VERT; break;
case 0x250c: RIGHT; DOWN; break;
case 0x2510: LEFT; DOWN; break;
case 0x2514: UP; RIGHT; break;
case 0x2518: UP; LEFT; break;
case 0x251c: VERT; RIGHT; break;
case 0x2524: VERT; LEFT; break;
case 0x252c: HORI; DOWN; break;
case 0x2534: UP; HORI; break;
case 0x253c: HORI; VERT; break;
case 0x2574: LEFT; break;
case 0x2575: UP; break;
case 0x2576: RIGHT; break;
case 0x2577: DOWN; break;
}
}
#include "apps/ununicode.h"
struct GlyphCacheEntry {
struct TT_Font * font;
sprite_t * sprite;
uint32_t size;
uint32_t glyph;
uint32_t color;
};
static struct GlyphCacheEntry glyph_cache[1024];
static unsigned long _hits = 0;
static unsigned long _misses = 0;
static unsigned long _wrongcolor = 0;
static void _menu_action_cache_stats(struct MenuEntry * self) {
char msg[400];
unsigned long count = 0;
unsigned long size = 0;
for (int i = 0; i < 1024; ++i) {
if (glyph_cache[i].sprite) {
count++;
size += glyph_cache[i].sprite->width * glyph_cache[i].sprite->height * 4;
}
}
snprintf(msg, 400,
"Hits: %lu\n"
"Misses: %lu\n"
"Wrong color: %lu\n"
"Populated cache entries: %lu\n"
"Size of sprites: %lu\n",
_hits, _misses, _wrongcolor, count, size);
write(fd_slave, msg, strlen(msg));
}
static void _menu_action_clear_cache(struct MenuEntry * self) {
for (int i = 0; i < 1024; ++i) {
if (glyph_cache[i].sprite) {
sprite_free(glyph_cache[i].sprite);
}
}
memset(glyph_cache,0,sizeof(glyph_cache));
}
static void draw_cached_glyph(gfx_context_t * ctx, struct TT_Font * _font, uint32_t size, int x, int y, uint32_t glyph, uint32_t fg, int flags) {
unsigned int hash = (((uintptr_t)_font >> 8) ^ (glyph * size)) & 1023;
struct GlyphCacheEntry * entry = &glyph_cache[hash];
if (entry->font != _font || entry->size != size || entry->glyph != glyph) {
if (entry->sprite) sprite_free(entry->sprite);
int wide = (flags & ANSI_WIDE) ? 2 : 1;
tt_set_size(_font, size);
entry->font = _font;
entry->size = size;
entry->glyph = glyph;
entry->sprite = create_sprite(char_width * wide, char_height, ALPHA_EMBEDDED);
entry->color = _ALP(fg) == 255 ? fg : 0xFFFFFFFF;
gfx_context_t * _ctx = init_graphics_sprite(entry->sprite);
draw_fill(_ctx, 0);
tt_draw_glyph(_ctx, entry->font, 0, char_offset, glyph, entry->color);
free(_ctx);
_misses++;
} else {
_hits++;
}
if (entry->color != fg) {
_wrongcolor++;
draw_sprite_alpha_paint(ctx, entry->sprite, x, y, 1.0, fg);
} else {
draw_sprite(ctx, entry->sprite, x, y);
}
}
/* Write a character to the window. */
static void term_write_char(uint32_t val, uint16_t x, uint16_t y, uint32_t fg, uint32_t bg, uint8_t flags) {
uint32_t _fg, _bg;
/* Select foreground color from palette. */
if (fg < PALETTE_COLORS) {
_fg = term_colors[fg];
_fg |= 0xFF << 24;
} else {
_fg = fg;
}
/* Select background color from aplette. */
if (bg < PALETTE_COLORS) {
_bg = term_colors[bg];
if (flags & ANSI_SPECBG) {
_bg |= 0xFF << 24;
} else {
_bg |= TERM_DEFAULT_OPAC << 24;
}
} else {
_bg = bg;
}
if (_fullscreen) {
_bg |= 0xFF << 24;
}
switch (val) {
/* Line drawing */
case 0x2500:
case 0x2502:
case 0x250c:
case 0x2510:
case 0x2514:
case 0x2518:
case 0x251c:
case 0x2524:
case 0x252c:
case 0x2534:
case 0x253c:
case 0x2574:
case 0x2575:
case 0x2576:
case 0x2577:
draw_box_drawing(val, x, y, _fg, _bg);
goto _extra_stuff;
/* Semi-filled blocks */
case 0x2580 ... 0x258f: {
draw_semi_block(val, x, y, _fg, _bg);
goto _extra_stuff;
}
/* Instead of checker, does 50% opacity fill */
case 0x2591:
case 0x2592:
case 0x2593:
_fill_region(alpha_blend_rgba(premultiply(_bg), interp_colors(rgb(0,0,0), premultiply(_fg), 255 * (val - 0x2590) / 4)), x, y, char_width, char_height);
goto _extra_stuff;
default:
break;
}
/* Draw glyphs */
if (_use_aa) {
if (val == 0xFFFF) return;
for (uint8_t i = 0; i < char_height; ++i) {
for (uint8_t j = 0; j < char_width; ++j) {
term_set_point(x+j,y+i,_bg);
}
}
if (flags & ANSI_WIDE) {
for (uint8_t i = 0; i < char_height; ++i) {
for (uint8_t j = char_width; j < 2 * char_width; ++j) {
term_set_point(x+j,y+i,_bg);
}
}
}
if (val < 32 || val == ' ') {
goto _extra_stuff;
}
struct TT_Font * _font = _tt_font_normal;
if (flags & ANSI_BOLD && flags & ANSI_ITALIC) {
_font = _tt_font_bold_oblique;
} else if (flags & ANSI_BOLD) {
_font = _tt_font_bold;
} else if (flags & ANSI_ITALIC) {
_font = _tt_font_oblique;
}
unsigned int glyph = tt_glyph_for_codepoint(_font, val);
/* Try the regular sans serif font as a fallback */
if (!glyph) {
int nglyph = tt_glyph_for_codepoint(_tt_font_fallback, val);
if (nglyph) {
_font = _tt_font_fallback;
glyph = nglyph;
}
}
/* Try the VL Gothic, if it's installed and this is a reasonably high codepoint */
if (!glyph && _tt_font_japanese && val >= 0x2E80) {
int nglyph = tt_glyph_for_codepoint(_tt_font_japanese, val);
if (nglyph) {
_font = _tt_font_japanese;
glyph = nglyph;
}
}
int _x = x + decor_left_width;
int _y = y + decor_top_height + menu_bar_height;
draw_cached_glyph(ctx, _font, font_size, _x,_y, glyph, _fg, flags);
} else {
/* Convert other unicode characters. */
if (val > 128) {
val = ununicode(val);
}
/* Draw using the bitmap font. */
uint8_t * c = large_font[val];
for (uint8_t i = 0; i < char_height; ++i) {
for (uint8_t j = 0; j < char_width; ++j) {
if (c[i] & (1 << (LARGE_FONT_MASK-j))) {
term_set_point(x+j,y+i,_fg);
} else {
term_set_point(x+j,y+i,_bg);
}
}
}
}
/* Draw additional text elements, like underlines and cross-outs. */
_extra_stuff:
if (flags & ANSI_UNDERLINE) {
for (uint8_t i = 0; i < char_width; ++i) {
term_set_point(x + i, y + char_height - 1, _fg);
}
}
if (flags & ANSI_CROSS) {
for (uint8_t i = 0; i < char_width; ++i) {
term_set_point(x + i, y + char_height - 7, _fg);
}
}
if (flags & ANSI_BORDER) {
for (uint8_t i = 0; i < char_height; ++i) {
term_set_point(x , y + i, _fg);
term_set_point(x + (char_width - 1), y + i, _fg);
}
for (uint8_t j = 0; j < char_width; ++j) {
term_set_point(x + j, y, _fg);
term_set_point(x + j, y + (char_height - 1), _fg);
}
}
/* Calculate the bounds of the updated region of the window */
l_x = min(l_x, decor_left_width + x);
l_y = min(l_y, decor_top_height+menu_bar_height + y);
if (flags & ANSI_WIDE) {
r_x = max(r_x, decor_left_width + x + char_width * 2);
r_y = max(r_y, decor_top_height+menu_bar_height + y + char_height * 2);
} else {
r_x = max(r_x, decor_left_width + x + char_width);
r_y = max(r_y, decor_top_height+menu_bar_height + y + char_height);
}
}
static void term_mirror_set(uint16_t x, uint16_t y, uint32_t val, uint32_t fg, uint32_t bg, uint8_t flags) {
if (x >= term_width || y >= term_height) return;
term_cell_t * cell = &term_mirror[y * term_width + x];
cell->c = val;
cell->fg = fg;
cell->bg = bg;
cell->flags = flags;
}
static void term_mirror_copy(uint16_t x, uint16_t y, term_cell_t * from) {
if (x >= term_width || y >= term_height) return;
term_cell_t * cell = &term_mirror[y * term_width + x];
if (!from->c && !from->fg && !from->bg) {
cell->c = ' ';
cell->fg = TERM_DEFAULT_FG;
cell->bg = TERM_DEFAULT_BG;
cell->flags = from->flags;
} else {
*cell = *from;
}
}
static void term_mirror_copy_inverted(uint16_t x, uint16_t y, term_cell_t * from) {
if (x >= term_width || y >= term_height) return;
term_cell_t * cell = &term_mirror[y * term_width + x];
if (!from->c && !from->fg && !from->bg) {
cell->c = ' ';
cell->fg = TERM_DEFAULT_BG;
cell->bg = TERM_DEFAULT_FG;
cell->flags = from->flags;
} else if (from->flags & ANSI_EXT_IMG) {
cell->c = ' ';
cell->fg = from->fg;
cell->bg = from->bg;
cell->flags = from->flags | ANSI_SPECBG;
} else {
cell->c = from->c;
cell->fg = from->bg;
cell->bg = from->fg;
cell->flags = from->flags | ANSI_SPECBG;
}
}
/* Set a terminal cell */
static void cell_set(uint16_t x, uint16_t y, uint32_t c, uint32_t fg, uint32_t bg, uint32_t flags) {
/* Avoid setting cells out of range. */
if (x >= term_width || y >= term_height) return;
/* Calculate the cell position in the terminal buffer */
term_cell_t * cell = &term_buffer[y * term_width + x];
/* Set cell attributes */
cell->c = c;
cell->fg = fg;
cell->bg = bg;
cell->flags = flags;
}
/* Redraw an embedded image cell */
static void redraw_cell_image(uint16_t x, uint16_t y, term_cell_t * cell, int inverted) {
/* Avoid setting cells out of range. */
if (x >= term_width || y >= term_height) return;
/* Draw the image data */
uint32_t * data = (uint32_t *)((uintptr_t)cell->bg << 32 | cell->fg);
if (inverted) {
for (uint32_t yy = 0; yy < char_height; ++yy) {
for (uint32_t xx = 0; xx < char_width; ++xx) {
uint32_t alpha = 0xFF000000 & *data;
uint32_t color = 0xFFFFFF - (*data & 0xFFFFFF);
term_set_point(x * char_width + xx, y * char_height + yy, color | alpha);
data++;
}
}
} else {
for (uint32_t yy = 0; yy < char_height; ++yy) {
for (uint32_t xx = 0; xx < char_width; ++xx) {
term_set_point(x * char_width + xx, y * char_height + yy, *data);
data++;
}
}
}
/* Update bounds */
l_x = min(l_x, decor_left_width + x * char_width);
l_y = min(l_y, decor_top_height+menu_bar_height + y * char_height);
r_x = max(r_x, decor_left_width + x * char_width + char_width);
r_y = max(r_y, decor_top_height+menu_bar_height + y * char_height + char_height);
}
static void maybe_flip_display(int force) {
static uint64_t last_refresh;
uint64_t ticks = get_ticks();
if (!force) {
if (ticks < last_refresh + 33330L) {
return;
}
}
last_refresh = ticks;
for (unsigned int y = 0; y < term_height; ++y) {
for (unsigned int x = 0; x < term_width; ++x) {
term_cell_t * cell_m = &term_mirror[y * term_width + x];
term_cell_t * cell_d = &term_display[y * term_width + x];
if (memcmp(cell_m, cell_d, sizeof(term_cell_t))) {
*cell_d = *cell_m;
if (cell_m->flags & ANSI_EXT_IMG) {
redraw_cell_image(x,y,cell_m,cell_m->flags & ANSI_SPECBG);
} else {
term_write_char(cell_m->c, x * char_width, y * char_height, cell_m->fg, cell_m->bg, cell_m->flags);
}
}
}
}
display_flip();
}
static void cell_redraw_offset(uint16_t x, uint16_t _y) {
int y = _y;
int i = y;
y -= scrollback_offset;
if (y >= 0) {
term_mirror_copy(x,i,&term_buffer[y * term_width + x]);
} else {
node_t * node = scrollback_list->tail;
for (; y < -1; y++) {
if (!node) break;
node = node->prev;
}
if (node) {
struct scrollback_row * row = (struct scrollback_row *)node->value;
if (row && x < row->width) {
term_mirror_copy(x,i,&row->cells[x]);
} else {
term_mirror_set(x,i,' ',TERM_DEFAULT_FG, TERM_DEFAULT_BG, TERM_DEFAULT_FLAGS);
}
}
}
}
static void cell_redraw_offset_inverted(uint16_t x, uint16_t _y) {
int y = _y;
int i = y;
y -= scrollback_offset;
if (y >= 0) {
term_mirror_copy_inverted(x,i,&term_buffer[y * term_width + x]);
} else {
node_t * node = scrollback_list->tail;
for (; y < -1; y++) {
if (!node) break;
node = node->prev;
}
if (node) {
struct scrollback_row * row = (struct scrollback_row *)node->value;
if (row && x < row->width) {
term_mirror_copy_inverted(x,i,&row->cells[x]);
} else {
term_mirror_set(x, i, ' ', TERM_DEFAULT_BG, TERM_DEFAULT_FG, TERM_DEFAULT_FLAGS|ANSI_SPECBG);
}
}
}
}
/* Redraw a text cell normally. */
static void cell_redraw(uint16_t x, uint16_t y) {
if (x >= term_width || y >= term_height) return;
term_mirror_copy(x,y,&term_buffer[y * term_width + x]);
}
/* Redraw text cell inverted. */
static void cell_redraw_inverted(uint16_t x, uint16_t y) {
/* Avoid cells out of range. */
if (x >= term_width || y >= term_height) return;
term_mirror_copy_inverted(x,y,&term_buffer[y * term_width + x]);
}
/* Redraw text cell with a surrounding box (used by cursor) */
static void cell_redraw_box(uint16_t x, uint16_t y) {
if (x >= term_width || y >= term_height) return;
term_cell_t cell = term_buffer[y * term_width + x];
cell.flags |= ANSI_BORDER;
term_mirror_copy(x,y,&cell);
}
/* Draw the cursor cell */
static void render_cursor() {
if (!cursor_on) return;
if (!window->focused) {
/* An unfocused terminal should draw an unfilled box. */
cell_redraw_box(csr_x, csr_y);
} else {
/* A focused terminal draws a solid box. */
cell_redraw_inverted(csr_x, csr_y);
}
}
static uint8_t cursor_flipped = 0;
/* A soft request to draw the cursor. */
static void draw_cursor() {
if (!cursor_on) return;
cursor_flipped = 0;
render_cursor();
}
/* Timer callback to flip (flash) the cursor */
static void maybe_flip_cursor(void) {
uint64_t ticks = get_ticks();
if (ticks > mouse_ticks + 600000LL) {
mouse_ticks = ticks;
if (scrollback_offset != 0) {
return; /* Don't flip cursor while drawing scrollback */
}
if (window->focused && cursor_flipped) {
cell_redraw(csr_x, csr_y);
} else {
render_cursor();
}
cursor_flipped = 1 - cursor_flipped;
}
}
/* Draw all cells. Duplicates code from cell_redraw to avoid unecessary bounds checks. */
static void term_redraw_all() {
for (int i = 0; i < term_height; i++) {
for (int x = 0; x < term_width; ++x) {
term_mirror_copy(x,i,&term_buffer[i * term_width + x]);
}
}
}
static void _menu_action_redraw(struct MenuEntry * self) {
term_redraw_all();
}
/* Remove no-longer-visible image cell data. */
static void flush_unused_images(void) {
if (!images_list->length) return;
list_t * tmp = list_create();
/* Go through scrollback, too */
if (scrollback_list) {
foreach(node, scrollback_list) {
struct scrollback_row * row = (struct scrollback_row *)node->value;
for (unsigned int x = 0; x < row->width; ++x) {
term_cell_t * cell = &row->cells[x];
if (cell->flags & ANSI_EXT_IMG) {
uint32_t * data = (uint32_t *)((uintptr_t)cell->bg << 32 | cell->fg);
list_insert(tmp, data);
}
}
}
}
for (int y = 0; y < term_height; ++y) {
for (int x = 0; x < term_width; ++x) {
term_cell_t * cell = &term_buffer_a[y * term_width + x];
if (cell->flags & ANSI_EXT_IMG) {
uint32_t * data = (uint32_t *)((uintptr_t)cell->bg << 32 | cell->fg);
list_insert(tmp, data);
}
}
}
for (int y = 0; y < term_height; ++y) {
for (int x = 0; x < term_width; ++x) {
term_cell_t * cell = &term_buffer_b[y * term_width + x];
if (cell->flags & ANSI_EXT_IMG) {
uint32_t * data = (uint32_t *)((uintptr_t)cell->bg << 32 | cell->fg);
list_insert(tmp, data);
}
}
}
foreach(node, images_list) {
if (!list_find(tmp, node->value)) {
free(node->value);
}
}
list_free(images_list);
images_list = tmp;
}
static void term_shift_region(int top, int height, int how_much) {
if (how_much == 0) return;
int destination, source;
int count, new_top, new_bottom;
if (how_much > height) {
count = 0;
new_top = top;
new_bottom = top + height;
} else if (how_much > 0) {
destination = term_width * top;
source = term_width * (top + how_much);
count = height - how_much;
new_top = top + height - how_much;
new_bottom = top + height;
} else if (how_much < 0) {
destination = term_width * (top - how_much);
source = term_width * top;
count = height + how_much;
new_top = top;
new_bottom = top - how_much;
}
/* Move from top+how_much to top */
if (count) {
memmove(term_buffer + destination, term_buffer + source, count * term_width * sizeof(term_cell_t));
memmove(term_mirror + destination, term_mirror + source, count * term_width * sizeof(term_cell_t));
}
l_x = 0; l_y = 0;
r_x = window->width;
r_y = window->height;
/* Clear new lines at bottom */
for (int i = new_top; i < new_bottom; ++i) {
for (uint16_t x = 0; x < term_width; ++x) {
cell_set(x, i, ' ', current_fg, current_bg, ansi_state->flags);
cell_redraw(x, i);
}
}
}
/* Scroll the terminal up or down. */
static void term_scroll(int how_much) {
term_shift_region(0, term_height, how_much);
/* Remove image data for image cells that are no longer on screen. */
flush_unused_images();
/* Flip the entire window. */
yutani_flip(yctx, window);
}
static void insert_delete_lines(int how_many) {
if (how_many == 0) return;
if (how_many > 0) {
/* Insert lines is equivalent to scrolling from the current line */
term_shift_region(csr_y,term_height-csr_y,-how_many);
} else {
term_shift_region(csr_y,term_height-csr_y,-how_many);
}
}
/* Is this a wide character? (does wcwidth == 2) */
static int is_wide(uint32_t codepoint) {
if (codepoint < 256) return 0;
return wcwidth(codepoint) == 2;
}
/* Save the row that is about to be scrolled offscreen into the scrollback buffer. */
static void save_scrollback(void) {
/* If the scrollback is already full, remove the oldest element. */
struct scrollback_row * row = NULL;
node_t * n = NULL;
if (max_scrollback && scrollback_list->length == max_scrollback) {
n = list_dequeue(scrollback_list);
row = n->value;
if (row->width < term_width) {
free(row);
row = NULL;
}
}
if (!row) {
row = malloc(sizeof(struct scrollback_row) + sizeof(term_cell_t) * term_width);
row->width = term_width;
}
if (!n) {
list_insert(scrollback_list, row);
} else {
n->value = row;
list_append(scrollback_list, n);
}
for (int i = 0; i < term_width; ++i) {
term_cell_t * cell = &term_buffer[i];
memcpy(&row->cells[i], cell, sizeof(term_cell_t));
}
}
/* Draw the scrollback. */
static void redraw_scrollback(void) {
if (!scrollback_offset) {
term_redraw_all();
return;
}
if (scrollback_offset < term_height) {
for (int i = scrollback_offset; i < term_height; i++) {
int y = i - scrollback_offset;
for (int x = 0; x < term_width; ++x) {
term_mirror_copy(x,i,&term_buffer[y * term_width + x]);
}
}
node_t * node = scrollback_list->tail;
for (int i = 0; i < scrollback_offset; ++i) {
struct scrollback_row * row = (struct scrollback_row *)node->value;
int y = scrollback_offset - 1 - i;
int width = row->width;
if (width > term_width) {
width = term_width;
} else {
for (int x = row->width; x < term_width; ++x) {
term_mirror_set(x, y, ' ', TERM_DEFAULT_FG, TERM_DEFAULT_BG, TERM_DEFAULT_FLAGS);
}
}
for (int x = 0; x < width; ++x) {
term_mirror_copy(x,y,&row->cells[x]);
}
node = node->prev;
}
} else {
node_t * node = scrollback_list->tail;
for (int i = 0; i < scrollback_offset - term_height; ++i) {
node = node->prev;
}
for (int i = scrollback_offset - term_height; i < scrollback_offset; ++i) {
struct scrollback_row * row = (struct scrollback_row *)node->value;
int y = scrollback_offset - 1 - i;
int width = row->width;
if (width > term_width) {
width = term_width;
} else {
for (int x = row->width; x < term_width; ++x) {
term_mirror_set(x, y, ' ', TERM_DEFAULT_FG, TERM_DEFAULT_BG, TERM_DEFAULT_FLAGS);
}
}
for (int x = 0; x < width; ++x) {
term_mirror_copy(x,y,&row->cells[x]);
}
node = node->prev;
}
}
}
static void undraw_cursor(void) {
cell_redraw(csr_x, csr_y);
}
static void normalize_x(int setting_lcf) {
if (csr_x >= term_width) {
csr_x = term_width - 1;
if (setting_lcf) {
csr_h = 1;
}
}
}
static void normalize_y(void) {
if (csr_y == term_height) {
save_scrollback();
term_scroll(1);
csr_y = term_height - 1;
}
}
/*
* ANSI callback for writing characters.
* Parses some things (\n\r, etc.) itself that should probably
* be moved into the ANSI library.
*/
static void term_write(char c) {
static uint32_t unicode_state = 0;
static uint32_t codepoint = 0;
if (!decode(&unicode_state, &codepoint, (uint8_t)c)) {
uint32_t o = codepoint;
codepoint = 0;
switch (c) {
case '\a':
/* boop */
return;
case '\r':
undraw_cursor();
csr_x = csr_h = 0;
draw_cursor();
return;
case '\t':
undraw_cursor();
csr_x += (8 - csr_x % 8);
normalize_x(0);
draw_cursor();
return;
case '\v':
case '\f':
case '\n':
undraw_cursor();
csr_h = 0;
++csr_y;
normalize_y();
draw_cursor();
return;
case '\b':
if (csr_x > 0) {
undraw_cursor();
--csr_x;
draw_cursor();
}
csr_h = 0;
return;
default: {
int wide = is_wide(o);
uint8_t flags = ansi_state->flags;
undraw_cursor();
if (csr_h || (wide && csr_x == term_width - 1)) {
csr_x = csr_h = 0;
++csr_y;
normalize_y();
}
if (wide) {
flags = flags | ANSI_WIDE;
}
cell_set(csr_x,csr_y, o, current_fg, current_bg, flags);
cell_redraw(csr_x,csr_y);
csr_x++;
if (wide && csr_x != term_width) {
cell_set(csr_x, csr_y, 0xFFFF, current_fg, current_bg, ansi_state->flags);
cell_redraw(csr_x,csr_y);
cell_redraw(csr_x-1,csr_y);
csr_x++;
}
normalize_x(1);
draw_cursor();
return;
}
}
} else if (unicode_state == UTF8_REJECT) {
unicode_state = 0;
codepoint = 0;
}
}
/* ANSI callback to set cursor position */
static void term_set_csr(int x, int y) {
cell_redraw(csr_x,csr_y);
if (x < 0) x = 0;
if (x >= term_width) x = term_width - 1;
if (y < 0) y = 0;
if (y >= term_height) y = term_height - 1;
csr_x = x;
csr_y = y;
csr_h = 0;
draw_cursor();
}
/* ANSI callback to get cursor x position */
static int term_get_csr_x(void) {
return csr_x;
}
/* ANSI callback to get cursor y position */
static int term_get_csr_y(void) {
return csr_y;
}
/* ANSI callback to set cell image data. */
static void term_set_cell_contents(int x, int y, char * data) {
char * cell_data = malloc(char_width * char_height * sizeof(uint32_t));
memcpy(cell_data, data, char_width * char_height * sizeof(uint32_t));
list_insert(images_list, cell_data);
cell_set(x, y, ' ',
(uintptr_t)(cell_data) & 0xFFFFFFFF,
(uintptr_t)(cell_data) >> 32,
ANSI_EXT_IMG);
}
/* ANSI callback to get character cell width */
static int term_get_cell_width(void) {
return char_width;
}
/* ANSI callback to get character cell height */
static int term_get_cell_height(void) {
return char_height;
}
/* ANSI callback to set cursor visibility */
static void term_set_csr_show(int on) {
cursor_on = on;
if (on) {
draw_cursor();
}
}
/* ANSI callback to set the foreground/background colors. */
static void term_set_colors(uint32_t fg, uint32_t bg) {
current_fg = fg;
current_bg = bg;
}
/* ANSI callback to force the cursor to draw */
static void term_redraw_cursor() {
if (term_buffer) {
draw_cursor();
}
}
/* ANSI callback to set a cell to a codepoint (only ever used to set spaces) */
static void term_set_cell(int x, int y, uint32_t c) {
cell_set(x, y, c, current_fg, current_bg, ansi_state->flags);
cell_redraw(x, y);
}
/* ANSI callback to clear the terminal. */
static void term_clear(int i) {
if (i == 2) {
/* Clear all */
csr_x = 0;
csr_y = 0;
csr_h = 0;
memset((void *)term_buffer, 0x00, term_width * term_height * sizeof(term_cell_t));
if (!_no_frame) {
render_decors();
}
term_redraw_all();
} else if (i == 0) {
/* Clear after cursor */
for (int x = csr_x; x < term_width; ++x) {
term_set_cell(x, csr_y, ' ');
}
for (int y = csr_y + 1; y < term_height; ++y) {
for (int x = 0; x < term_width; ++x) {
term_set_cell(x, y, ' ');
}
}
} else if (i == 1) {
/* Clear before cursor */
for (int y = 0; y < csr_y; ++y) {
for (int x = 0; x < term_width; ++x) {
term_set_cell(x, y, ' ');
}
}
for (int x = 0; x < csr_x; ++x) {
term_set_cell(x, csr_y, ' ');
}
} else if (i == 3) {
/* Clear scrollback */
if (scrollback_list) {
while (scrollback_list->length) {
node_t * n = list_dequeue(scrollback_list);
free(n->value);
free(n);
}
scrollback_offset = 0;
}
}
flush_unused_images();
}
#define SWAP(T,a,b) do { T _a = a; a = b; b = _a; } while(0);
static void term_switch_buffer(int buffer) {
if (buffer != 0 && buffer != 1) return;
if (buffer != active_buffer) {
active_buffer = buffer;
term_buffer = active_buffer == 0 ? term_buffer_a : term_buffer_b;
SWAP(int, csr_x, _orig_x);
SWAP(int, csr_y, _orig_y);
SWAP(uint32_t, current_fg, _orig_fg);
SWAP(uint32_t, current_bg, _orig_bg);
term_redraw_all();
}
}
/* ANSI callbacks */
term_callbacks_t term_callbacks = {
term_write,
term_set_colors,
term_set_csr,
term_get_csr_x,
term_get_csr_y,
term_set_cell,
term_clear,
term_scroll,
term_redraw_cursor,
input_buffer_stuff,
set_title,
term_set_cell_contents,
term_get_cell_width,
term_get_cell_height,
term_set_csr_show,
term_switch_buffer,
insert_delete_lines,
};
static void handle_input(char c) {
write_input_buffer(&c, 1);
if (scrollback_offset != 0) {
scrollback_offset = 0;
term_redraw_all();
}
}
static void handle_input_s(char * c) {
size_t len = strlen(c);
write_input_buffer(c, len);
if (scrollback_offset != 0) {
scrollback_offset = 0;
term_redraw_all();
}
}
/* Scroll the view up (scrollback) */
static void scroll_up(int amount) {
int i = 0;
while (i < amount && scrollback_list && scrollback_offset < (int)scrollback_list->length) {
scrollback_offset ++;
i++;
}
redraw_scrollback();
}
/* Scroll the view down (scrollback) */
void scroll_down(int amount) {
int i = 0;
while (i < amount && scrollback_list && scrollback_offset != 0) {
scrollback_offset -= 1;
i++;
}
redraw_scrollback();
}
/* Handle a key press from Yutani */
static void key_event(int ret, key_event_t * event) {
if (ret) {
/* Ctrl-Shift-C - Copy selection */
if ((event->modifiers & KEY_MOD_LEFT_SHIFT || event->modifiers & KEY_MOD_RIGHT_SHIFT) &&
(event->modifiers & KEY_MOD_LEFT_CTRL || event->modifiers & KEY_MOD_RIGHT_CTRL) &&
(event->keycode == 'c')) {
if (selection) {
/* Copy selection */
copy_selection();
}
return;
}
/* Ctrl-Shift-V - Paste selection */
if ((event->modifiers & KEY_MOD_LEFT_SHIFT || event->modifiers & KEY_MOD_RIGHT_SHIFT) &&
(event->modifiers & KEY_MOD_LEFT_CTRL || event->modifiers & KEY_MOD_RIGHT_CTRL) &&
(event->keycode == 'v')) {
/* Paste selection */
yutani_special_request(yctx, NULL, YUTANI_SPECIAL_REQUEST_CLIPBOARD);
return;
}
if ((event->modifiers & KEY_MOD_LEFT_CTRL || event->modifiers & KEY_MOD_RIGHT_CTRL) &&
(event->keycode == '0')) {
scale_fonts = 0;
font_scaling = 1.0;
reinit();
return;
}
if ((event->modifiers & KEY_MOD_LEFT_SHIFT || event->modifiers & KEY_MOD_RIGHT_SHIFT) &&
(event->modifiers & KEY_MOD_LEFT_CTRL || event->modifiers & KEY_MOD_RIGHT_CTRL) &&
(event->keycode == '=')) {
scale_fonts = 1;
font_scaling = font_scaling * 1.2;
reinit();
return;
}
if ((event->modifiers & KEY_MOD_LEFT_CTRL || event->modifiers & KEY_MOD_RIGHT_CTRL) &&
(event->keycode == '-')) {
scale_fonts = 1;
font_scaling = font_scaling * 0.8333333;
reinit();
return;
}
/* Left alt */
if (event->modifiers & KEY_MOD_LEFT_ALT || event->modifiers & KEY_MOD_RIGHT_ALT) {
handle_input('\033');
}
/* Shift-Tab */
if ((event->modifiers & KEY_MOD_LEFT_SHIFT || event->modifiers & KEY_MOD_RIGHT_SHIFT) &&
event->key == '\t') {
handle_input_s("\033[Z");
return;
}
/* ENTER = reads as linefeed, should be carriage return */
if (event->keycode == 10) {
handle_input('\r');
return;
}
/* BACKSPACE = reads as ^H, should be ^? */
if (event->keycode == 8) {
handle_input(0x7F);
return;
}
/* Pass key value to PTY */
handle_input(event->key);
} else {
/* Special keys without ->key values */
/* Only trigger on key down */
if (event->action == KEY_ACTION_UP) return;
switch (event->keycode) {
case KEY_F1:
handle_input_s("\033OP");
break;
case KEY_F2:
handle_input_s("\033OQ");
break;
case KEY_F3:
handle_input_s("\033OR");
break;
case KEY_F4:
handle_input_s("\033OS");
break;
case KEY_F5:
handle_input_s("\033[15~");
break;
case KEY_F6:
handle_input_s("\033[17~");
break;
case KEY_F7:
handle_input_s("\033[18~");
break;
case KEY_F8:
handle_input_s("\033[19~");
break;
case KEY_F9:
handle_input_s("\033[20~");
break;
case KEY_F10:
handle_input_s("\033[21~");
break;
case KEY_F11:
handle_input_s("\033[23~");
break;
case KEY_F12:
/* Toggle decorations */
if (!_fullscreen) {
_no_frame = !_no_frame;
update_bounds();
window_width = window->width - decor_width;
window_height = window->height - (decor_height + menu_bar_height);
reinit();
}
break;
case KEY_ARROW_UP:
if (event->modifiers & KEY_MOD_LEFT_SHIFT && event->modifiers & KEY_MOD_LEFT_CTRL) {
handle_input_s("\033[6A");
} else if (event->modifiers & KEY_MOD_LEFT_CTRL) {
handle_input_s("\033[5A");
} else if (event->modifiers & KEY_MOD_LEFT_SHIFT && event->modifiers & KEY_MOD_LEFT_ALT) {
handle_input_s("\033[4A");
} else if (event->modifiers & KEY_MOD_LEFT_ALT) {
handle_input_s("\033[3A");
} else if (event->modifiers & KEY_MOD_LEFT_SHIFT) {
handle_input_s("\033[2A");
} else {
handle_input_s("\033[A");
}
break;
case KEY_ARROW_DOWN:
if (event->modifiers & KEY_MOD_LEFT_SHIFT && event->modifiers & KEY_MOD_LEFT_CTRL) {
handle_input_s("\033[6B");
} else if (event->modifiers & KEY_MOD_LEFT_CTRL) {
handle_input_s("\033[5B");
} else if (event->modifiers & KEY_MOD_LEFT_SHIFT && event->modifiers & KEY_MOD_LEFT_ALT) {
handle_input_s("\033[4B");
} else if (event->modifiers & KEY_MOD_LEFT_ALT) {
handle_input_s("\033[3B");
} else if (event->modifiers & KEY_MOD_LEFT_SHIFT) {
handle_input_s("\033[2B");
} else {
handle_input_s("\033[B");
}
break;
case KEY_ARROW_RIGHT:
if (event->modifiers & KEY_MOD_LEFT_SHIFT && event->modifiers & KEY_MOD_LEFT_CTRL) {
handle_input_s("\033[6C");
} else if (event->modifiers & KEY_MOD_LEFT_CTRL) {
handle_input_s("\033[5C");
} else if (event->modifiers & KEY_MOD_LEFT_SHIFT && event->modifiers & KEY_MOD_LEFT_ALT) {
handle_input_s("\033[4C");
} else if (event->modifiers & KEY_MOD_LEFT_ALT) {
handle_input_s("\033[3C");
} else if (event->modifiers & KEY_MOD_LEFT_SHIFT) {
handle_input_s("\033[2C");
} else {
handle_input_s("\033[C");
}
break;
case KEY_ARROW_LEFT:
if (event->modifiers & KEY_MOD_LEFT_SHIFT && event->modifiers & KEY_MOD_LEFT_CTRL) {
handle_input_s("\033[6D");
} else if (event->modifiers & KEY_MOD_LEFT_CTRL) {
handle_input_s("\033[5D");
} else if (event->modifiers & KEY_MOD_LEFT_SHIFT && event->modifiers & KEY_MOD_LEFT_ALT) {
handle_input_s("\033[4D");
} else if (event->modifiers & KEY_MOD_LEFT_ALT) {
handle_input_s("\033[3D");
} else if (event->modifiers & KEY_MOD_LEFT_SHIFT) {
handle_input_s("\033[2D");
} else {
handle_input_s("\033[D");
}
break;
case KEY_PAGE_UP:
if (event->modifiers & KEY_MOD_LEFT_SHIFT) {
scroll_up(term_height/2);
} else {
handle_input_s("\033[5~");
}
break;
case KEY_PAGE_DOWN:
if (event->modifiers & KEY_MOD_LEFT_SHIFT) {
scroll_down(term_height/2);
} else {
handle_input_s("\033[6~");
}
break;
case KEY_HOME:
if (event->modifiers & KEY_MOD_LEFT_SHIFT) {
if (scrollback_list) {
scrollback_offset = scrollback_list->length;
redraw_scrollback();
}
} else {
handle_input_s("\033[H");
}
break;
case KEY_END:
if (event->modifiers & KEY_MOD_LEFT_SHIFT) {
scrollback_offset = 0;
redraw_scrollback();
} else {
handle_input_s("\033[F");
}
break;
case KEY_DEL:
handle_input_s("\033[3~");
break;
case KEY_INSERT:
handle_input_s("\033[2~");
break;
}
}
}
/* Check if the Terminal should close. */
static void check_for_exit(void) {
/* If something has set exit_application, we should exit. */
if (exit_application) return;
pid_t pid = waitpid(-1, NULL, WNOHANG);
/* If the child has exited, we should exit. */
if (pid != child_pid) return;
/* Clean up */
exit_application = 1;
/* Write [Process terminated] */
char exit_message[] = "[Process terminated]\n";
write(fd_slave, exit_message, sizeof(exit_message));
close(input_buffer_semaphore[1]);
}
static term_cell_t * copy_terminal(int old_width, int old_height, term_cell_t * term_buffer) {
term_cell_t * new_term_buffer = malloc(sizeof(term_cell_t) * term_width * term_height);
memset(new_term_buffer, 0x0, sizeof(term_cell_t) * term_width * term_height);
int offset = 0;
if (term_height < old_height) {
while (csr_y >= term_height) {
offset++;
old_height--;
csr_y--;
}
}
for (int row = 0; row < min(old_height, term_height); ++row) {
for (int col = 0; col < min(old_width, term_width); ++col) {
term_cell_t * old_cell = &term_buffer[(row+offset) * old_width + col];
term_cell_t * new_cell = &new_term_buffer[row * term_width + col];
*new_cell = *old_cell;
}
}
if (csr_x >= term_width) {
csr_x = term_width-1;
}
return new_term_buffer;
}
/* Reinitialize the terminal after a resize. */
static void reinit(void) {
/* Figure out character sizes if fonts have changed. */
if (_use_aa) {
char_width = 8;
char_height = 17;
font_size = 13;
char_offset = 13;
if (scale_fonts) {
font_size *= font_scaling;
char_height *= font_scaling;
char_width *= font_scaling;
char_offset *= font_scaling;
}
} else {
char_width = LARGE_FONT_CELL_WIDTH;
char_height = LARGE_FONT_CELL_HEIGHT;
}
int old_width = term_width;
int old_height = term_height;
/* Resize the terminal buffer */
term_width = window_width / char_width;
term_height = window_height / char_height;
if (term_width == old_width && term_height == old_height) {
memset(term_display, 0xFF, sizeof(term_cell_t) * term_width * term_height);
draw_fill(ctx, rgba(0,0,0, TERM_DEFAULT_OPAC));
render_decors();
maybe_flip_display(1);
return;
}
if (term_buffer) {
term_cell_t * new_a = copy_terminal(old_width, old_height, term_buffer_a);
term_cell_t * new_b = copy_terminal(old_width, old_height, term_buffer_b);
free(term_buffer_a);
term_buffer_a = new_a;
free(term_buffer_b);
term_buffer_b = new_b;
if (active_buffer == 0) {
term_buffer = new_a;
} else {
term_buffer = new_b;
}
} else {
term_buffer_a = malloc(sizeof(term_cell_t) * term_width * term_height);
memset(term_buffer_a, 0x0, sizeof(term_cell_t) * term_width * term_height);
term_buffer_b = malloc(sizeof(term_cell_t) * term_width * term_height);
memset(term_buffer_b, 0x0, sizeof(term_cell_t) * term_width * term_height);
term_buffer = term_buffer_a;
}
term_mirror = realloc(term_mirror, sizeof(term_cell_t) * term_width * term_height);
memcpy(term_mirror, term_buffer, sizeof(term_cell_t) * term_width * term_height);
term_display = realloc(term_display, sizeof(term_cell_t) * term_width * term_height);
memset(term_display, 0xFF, sizeof(term_cell_t) * term_width * term_height);
/* Reset the ANSI library, ensuring we keep certain values */
int old_mouse_state = 0;
if (ansi_state) old_mouse_state = ansi_state->mouse_on;
ansi_state = ansi_init(ansi_state, term_width, term_height, &term_callbacks);
ansi_state->mouse_on = old_mouse_state;
/* Send window size change ioctl */
struct winsize w;
w.ws_row = term_height;
w.ws_col = term_width;
w.ws_xpixel = term_width * char_width;
w.ws_ypixel = term_height * char_height;
ioctl(fd_master, TIOCSWINSZ, &w);
/* Redraw the window */
draw_fill(ctx, rgba(0,0,0, TERM_DEFAULT_OPAC));
render_decors();
term_redraw_all();
}
static void update_bounds(void) {
if (!_no_frame) {
struct decor_bounds bounds;
decor_get_bounds(window, &bounds);
decor_left_width = bounds.left_width;
decor_top_height = bounds.top_height;
decor_right_width = bounds.right_width;
decor_bottom_height = bounds.bottom_height;
decor_width = bounds.width;
decor_height = bounds.height;
menu_bar_height = 24;
} else {
decor_left_width = 0;
decor_top_height = 0;
decor_right_width = 0;
decor_bottom_height = 0;
decor_width = 0;
decor_height = 0;
menu_bar_height = 0;
}
}
/* Handle window resize event. */
static void resize_finish(int width, int height) {
static int resize_attempts = 0;
/* Calculate window size */
update_bounds();
int extra_x = decor_width;
int extra_y = decor_height + menu_bar_height;
int t_window_width = width - extra_x;
int t_window_height = height - extra_y;
/* Prevent the terminal from becoming too small. */
if (t_window_width < char_width * 20 || t_window_height < char_height * 10) {
resize_attempts++;
int n_width = extra_x + max(char_width * 20, t_window_width);
int n_height = extra_y + max(char_height * 10, t_window_height);
yutani_window_resize_offer(yctx, window, n_width, n_height);
return;
}
/* If requested, ensure the terminal resizes to a fixed size based on the cell size. */
if (!_free_size && ((t_window_width % char_width != 0 || t_window_height % char_height != 0) && resize_attempts < 3)) {
resize_attempts++;
int n_width = extra_x + t_window_width - (t_window_width % char_width);
int n_height = extra_y + t_window_height - (t_window_height % char_height);
yutani_window_resize_offer(yctx, window, n_width, n_height);
return;
}
resize_attempts = 0;
/* Accept new window size */
yutani_window_resize_accept(yctx, window, width, height);
window_width = window->width - extra_x;
window_height = window->height - extra_y;
/* Reinitialize the graphics library */
reinit_graphics_yutani(ctx, window);
/* Reinitialize the terminal buffer and ANSI library */
reinit();
maybe_flip_display(1);
/* We are done resizing. */
yutani_window_resize_done(yctx, window);
yutani_flip(yctx, window);
}
/* Insert a mouse event sequence into the PTY */
static void mouse_event(int button, int x, int y) {
if (ansi_state->mouse_on & TERMEMU_MOUSE_SGR) {
char buf[100];
sprintf(buf,"\033[<%d;%d;%d%c", button == 3 ? 0 : button, x+1, y+1, button == 3 ? 'm' : 'M');
handle_input_s(buf);
} else {
char buf[7];
sprintf(buf, "\033[M%c%c%c", button + 32, x + 33, y + 33);
handle_input_s(buf);
}
}
/* Handle Yutani messages */
static void * handle_incoming(void) {
static uint64_t last_click = 0;
yutani_msg_t * m = yutani_poll(yctx);
while (m) {
if (menu_process_event(yctx, m)) {
render_decors();
}
switch (m->type) {
case YUTANI_MSG_KEY_EVENT:
{
struct yutani_msg_key_event * ke = (void*)m->data;
int ret = (ke->event.action == KEY_ACTION_DOWN) && (ke->event.key);
key_event(ret, &ke->event);
}
break;
case YUTANI_MSG_WINDOW_FOCUS_CHANGE:
{
struct yutani_msg_window_focus_change * wf = (void*)m->data;
yutani_window_t * win = hashmap_get(yctx->windows, (void*)(uintptr_t)wf->wid);
if (win == window) {
win->focused = wf->focused;
render_decors();
draw_cursor();
maybe_flip_display(1);
}
}
break;
case YUTANI_MSG_WINDOW_CLOSE:
{
struct yutani_msg_window_close * wc = (void*)m->data;
if (wc->wid == window->wid) {
kill(child_pid, SIGKILL);
exit_application = 1;
}
}
break;
case YUTANI_MSG_SESSION_END:
{
kill(child_pid, SIGKILL);
exit_application = 1;
}
break;
case YUTANI_MSG_RESIZE_OFFER:
{
struct yutani_msg_window_resize * wr = (void*)m->data;
resize_finish(wr->width, wr->height);
}
break;
case YUTANI_MSG_CLIPBOARD:
{
struct yutani_msg_clipboard * cb = (void *)m->data;
if (selection_text) {
free(selection_text);
}
if (*cb->content == '\002') {
int size = atoi(&cb->content[2]);
FILE * clipboard = yutani_open_clipboard(yctx);
selection_text = malloc(size + 1);
fread(selection_text, 1, size, clipboard);
selection_text[size] = '\0';
fclose(clipboard);
} else {
selection_text = malloc(cb->size+1);
memcpy(selection_text, cb->content, cb->size);
selection_text[cb->size] = '\0';
}
if (ansi_state->paste_mode) {
handle_input_s("\033[200~");
handle_input_s(selection_text);
handle_input_s("\033[201~");
} else {
handle_input_s(selection_text);
}
}
break;
case YUTANI_MSG_WINDOW_MOUSE_EVENT:
{
struct yutani_msg_window_mouse_event * me = (void*)m->data;
if (me->wid != window->wid) break;
if (!_no_frame) {
int decor_response = decor_handle_event(yctx, m);
switch (decor_response) {
case DECOR_CLOSE:
kill(child_pid, SIGKILL);
exit_application = 1;
break;
case DECOR_RIGHT:
/* right click in decoration, show appropriate menu */
decor_show_default_menu(window, window->x + me->new_x, window->y + me->new_y);
break;
default:
break;
}
menu_bar_mouse_event(yctx, window, &terminal_menu_bar, me, me->new_x, me->new_y);
}
if (me->new_x < 0 || me->new_y < 0 ||
(!_no_frame && (me->new_x >= (int)window_width + (int)decor_width ||
me->new_y < (int)decor_top_height+menu_bar_height ||
me->new_y >= (int)(window_height + decor_top_height+menu_bar_height) ||
me->new_x < (int)decor_left_width ||
me->new_x >= (int)(window_width + decor_left_width))) ||
(_no_frame && (me->new_x >= (int)window_width || me->new_y >= (int)window_height))) {
if (window->mouse_state == YUTANI_CURSOR_TYPE_IBEAM) {
yutani_window_show_mouse(yctx, window, YUTANI_CURSOR_TYPE_RESET);
}
break;
}
if (!(ansi_state->mouse_on & TERMEMU_MOUSE_ENABLE)) {
if (window->mouse_state == YUTANI_CURSOR_TYPE_RESET) {
yutani_window_show_mouse(yctx, window, YUTANI_CURSOR_TYPE_IBEAM);
}
} else {
if (window->mouse_state == YUTANI_CURSOR_TYPE_IBEAM) {
yutani_window_show_mouse(yctx, window, YUTANI_CURSOR_TYPE_RESET);
}
}
int new_x = me->new_x;
int new_y = me->new_y;
if (!_no_frame) {
new_x -= decor_left_width;
new_y -= decor_top_height+menu_bar_height;
}
/* Convert from coordinate to cell positon */
new_x /= char_width;
new_y /= char_height;
if (new_x < 0 || new_y < 0) break;
if (new_x >= term_width || new_y >= term_height) break;
/* Map Cursor Action */
if ((ansi_state->mouse_on & TERMEMU_MOUSE_ENABLE) && !(me->modifiers & YUTANI_KEY_MODIFIER_SHIFT)) {
if (me->buttons & YUTANI_MOUSE_SCROLL_UP) {
mouse_event(32+32, new_x, new_y);
} else if (me->buttons & YUTANI_MOUSE_SCROLL_DOWN) {
mouse_event(32+32+1, new_x, new_y);
}
if (me->buttons != button_state) {
/* Figure out what changed */
if (me->buttons & YUTANI_MOUSE_BUTTON_LEFT &&
!(button_state & YUTANI_MOUSE_BUTTON_LEFT))
mouse_event(0, new_x, new_y);
if (me->buttons & YUTANI_MOUSE_BUTTON_MIDDLE &&
!(button_state & YUTANI_MOUSE_BUTTON_MIDDLE))
mouse_event(1, new_x, new_y);
if (me->buttons & YUTANI_MOUSE_BUTTON_RIGHT &&
!(button_state & YUTANI_MOUSE_BUTTON_RIGHT))
mouse_event(2, new_x, new_y);
if (!(me->buttons & YUTANI_MOUSE_BUTTON_LEFT) &&
button_state & YUTANI_MOUSE_BUTTON_LEFT)
mouse_event(3, new_x, new_y);
if (!(me->buttons & YUTANI_MOUSE_BUTTON_MIDDLE) &&
button_state & YUTANI_MOUSE_BUTTON_MIDDLE)
mouse_event(3, new_x, new_y);
if (!(me->buttons & YUTANI_MOUSE_BUTTON_RIGHT) &&
button_state & YUTANI_MOUSE_BUTTON_RIGHT)
mouse_event(3, new_x, new_y);
last_mouse_x = new_x;
last_mouse_y = new_y;
button_state = me->buttons;
} else if (ansi_state->mouse_on & TERMEMU_MOUSE_DRAG) {
/* Report motion for pressed buttons */
if (last_mouse_x == new_x && last_mouse_y == new_y) break;
if (button_state & YUTANI_MOUSE_BUTTON_LEFT) mouse_event(32, new_x, new_y);
if (button_state & YUTANI_MOUSE_BUTTON_MIDDLE) mouse_event(33, new_x, new_y);
if (button_state & YUTANI_MOUSE_BUTTON_RIGHT) mouse_event(34, new_x, new_y);
last_mouse_x = new_x;
last_mouse_y = new_y;
}
} else {
if (me->command == YUTANI_MOUSE_EVENT_DOWN && me->buttons & YUTANI_MOUSE_BUTTON_LEFT) {
redraw_scrollback();
uint64_t now = get_ticks();
if (now - last_click < 500000UL && (new_x == selection_start_x && new_y == selection_start_y)) {
/* Double click */
while (selection_start_x > 0) {
term_cell_t * c = cell_at(selection_start_x-1, selection_start_y);
if (!c || c->c == ' ' || !c->c) break;
selection_start_x--;
}
while (selection_end_x < term_width - 1) {
term_cell_t * c = cell_at(selection_end_x+1, selection_end_y);
if (!c || c->c == ' ' || !c->c) break;
selection_end_x++;
}
selection = 1;
} else {
last_click = get_ticks();
selection_start_x = new_x;
selection_start_y = new_y;
selection_end_x = new_x;
selection_end_y = new_y;
selection = 0;
}
redraw_selection();
}
if (me->command == YUTANI_MOUSE_EVENT_DRAG && me->buttons & YUTANI_MOUSE_BUTTON_LEFT ){
mark_selection();
selection_end_x = new_x;
selection_end_y = new_y;
selection = 1;
flip_selection();
}
if (me->command == YUTANI_MOUSE_EVENT_RAISE) {
if (me->new_x == me->old_x && me->new_y == me->old_y) {
selection = 0;
term_redraw_all();
redraw_scrollback();
} /* else selection */
}
if (me->buttons & YUTANI_MOUSE_SCROLL_UP) {
scroll_up(5);
} else if (me->buttons & YUTANI_MOUSE_SCROLL_DOWN) {
scroll_down(5);
} else if (me->buttons & YUTANI_MOUSE_BUTTON_RIGHT) {
if (!menu_right_click->window) {
menu_prepare(menu_right_click, yctx);
if (menu_right_click->window) {
if (window->x + me->new_x + menu_right_click->window->width > yctx->display_width) {
yutani_window_move(yctx, menu_right_click->window, window->x + me->new_x - menu_right_click->window->width, window->y + me->new_y);
} else {
yutani_window_move(yctx, menu_right_click->window, window->x + me->new_x, window->y + me->new_y);
}
yutani_flip(yctx, menu_right_click->window);
}
}
}
}
}
break;
default:
break;
}
free(m);
m = yutani_poll_async(yctx);
}
return NULL;
}
/*
* Menu Actions
*/
/* File > Exit */
static void _menu_action_exit(struct MenuEntry * self) {
kill(child_pid, SIGKILL);
exit_application = 1;
}
/* We need to track these so we can retitle both of them */
static struct MenuEntry * _menu_toggle_borders_context = NULL;
static struct MenuEntry * _menu_toggle_borders_bar = NULL;
static void _menu_action_hide_borders(struct MenuEntry * self) {
_no_frame = !(_no_frame);
update_bounds();
window_width = window->width - decor_width;
window_height = window->height - (decor_height + menu_bar_height);
menu_update_icon(_menu_toggle_borders_context, _no_frame ? NULL : "check");
menu_update_icon(_menu_toggle_borders_bar, _no_frame ? NULL : "check");
reinit();
}
static struct MenuEntry * _menu_toggle_bitmap_context = NULL;
static struct MenuEntry * _menu_toggle_bitmap_bar = NULL;
static void _menu_action_toggle_tt(struct MenuEntry * self) {
_use_aa = !(_use_aa);
menu_update_icon(_menu_toggle_bitmap_context, _use_aa ? NULL : "check");
menu_update_icon(_menu_toggle_bitmap_bar, _use_aa ? NULL : "check");
reinit();
}
static void _menu_action_toggle_free_size(struct MenuEntry * self) {
_free_size = !(_free_size);
menu_update_icon(self, _free_size ? NULL : "check");
}
static void _menu_action_show_about(struct MenuEntry * self) {
char about_cmd[1024] = "\0";
strcat(about_cmd, "about \"About Terminal\" /usr/share/icons/48/utilities-terminal.png \"ToaruOS Terminal\" \"© 2013-2022 K. Lange\n-\nPart of ToaruOS, which is free software\nreleased under the NCSA/University of Illinois\nlicense.\n-\n%https://toaruos.org\n%https://github.com/klange/toaruos\" ");
char coords[100];
sprintf(coords, "%d %d &", (int)window->x + (int)window->width / 2, (int)window->y + (int)window->height / 2);
strcat(about_cmd, coords);
system(about_cmd);
render_decors();
}
static void _menu_action_show_help(struct MenuEntry * self) {
system("help-browser terminal.trt &");
render_decors();
}
static void _menu_action_copy(struct MenuEntry * self) {
copy_selection();
}
static void _menu_action_paste(struct MenuEntry * self) {
yutani_special_request(yctx, NULL, YUTANI_SPECIAL_REQUEST_CLIPBOARD);
}
static void _menu_action_set_scale(struct MenuEntry * self) {
struct MenuEntry_Normal * _self = (struct MenuEntry_Normal *)self;
if (!_self->action) {
scale_fonts = 0;
font_scaling = 1.0;
} else {
scale_fonts = 1;
font_scaling = atof(_self->action);
}
reinit();
}
static void render_decors_callback(struct menu_bar * self) {
(void)self;
render_decors();
}
/**
* Geometry argument follows this format:
* [@]WxH[+X,Y]
*
* If @ is present, W and H are in characters.
* If + is present, X and Y are the left and top offset.
*/
static void parse_geometry(char ** argv, char * str) {
int in_chars = 0;
if (*str == '@') {
in_chars = 1;
str++;
}
/* Split on 'x', which is required. */
char * c = strstr(str, "x");
if (!c) return; /* Ignore invalid arg */
*c = '\0';
c++;
/* Find optional + that starts position */
char * plus = strstr(c, "+");
if (plus) {
*plus = '\0';
plus++;
}
/* Parse size */
window_width = atoi(str) * (in_chars ? char_width : 1);
window_height = atoi(c) * (in_chars ? char_height : 1);
if (plus) {
/* If there was a plus, let's look for a comma */
char * comma = strstr(plus, ",");
if (!comma) return; /* Skip invalid position */
*comma = '\0';
comma++;
window_position_set = 1;
window_left = atoi(plus);
window_top = atoi(comma);
}
}
int main(int argc, char ** argv) {
int _flags = 0;
window_width = char_width * 80;
window_height = char_height * 24;
static struct option long_opts[] = {
{"fullscreen", no_argument, 0, 'F'},
{"bitmap", no_argument, 0, 'b'},
{"scale", required_argument, 0, 's'},
{"help", no_argument, 0, 'h'},
{"grid", no_argument, 0, 'x'},
{"no-frame", no_argument, 0, 'n'},
{"geometry", required_argument, 0, 'g'},
{"blurred", no_argument, 0, 'B'},
{"scrollback", required_argument, 0, 'S'},
{0,0,0,0}
};
/* Read some arguments */
int index, c;
while ((c = getopt_long(argc, argv, "bhxnFls:g:BS:", long_opts, &index)) != -1) {
if (!c) {
if (long_opts[index].flag == 0) {
c = long_opts[index].val;
}
}
switch (c) {
case 'x':
_free_size = 0;
break;
case 'n':
_no_frame = 1;
break;
case 'F':
_fullscreen = 1;
_no_frame = 1;
break;
case 'b':
_use_aa = 0;
break;
case 'h':
usage(argv);
return 0;
break;
case 's':
scale_fonts = 1;
font_scaling = atof(optarg);
break;
case 'g':
parse_geometry(argv,optarg);
break;
case 'B':
_flags = YUTANI_WINDOW_FLAG_BLUR_BEHIND;
break;
case 'S':
max_scrollback = strtoull(optarg,NULL,10);
break;
case '?':
break;
default:
break;
}
}
/* Initialize the windowing library */
yctx = yutani_init();
if (!yctx) {
fprintf(stderr, "%s: failed to connect to compositor\n", argv[0]);
return 1;
}
_tt_font_normal = tt_font_from_shm("monospace");
_tt_font_bold = tt_font_from_shm("monospace.bold");
_tt_font_oblique = tt_font_from_shm("monospace.italic");
_tt_font_bold_oblique = tt_font_from_shm("monospace.bolditalic");
_tt_font_fallback = _tt_font_normal;
_tt_font_japanese = tt_font_from_file("/usr/share/fonts/truetype/vlgothic/VL-Gothic-Regular.ttf"); /* Might not be present */
/* Full screen mode forces window size to be that the display server */
if (_fullscreen) {
window_width = yctx->display_width;
window_height = yctx->display_height;
}
if (_no_frame) {
window = yutani_window_create_flags(yctx, window_width, window_height, YUTANI_WINDOW_FLAG_NO_ANIMATION);
} else {
init_decorations();
struct decor_bounds bounds;
decor_get_bounds(NULL, &bounds);
window = yutani_window_create_flags(yctx, window_width + bounds.width, window_height + bounds.height + menu_bar_height, _flags);
yutani_window_update_shape(yctx, window, 20);
}
if (_fullscreen) {
/* If fullscreen, assume we're always focused and put us on the bottom. */
yutani_set_stack(yctx, window, YUTANI_ZORDER_BOTTOM);
window->focused = 1;
} else {
window->focused = 0;
}
update_bounds();
/* Set up menus */
terminal_menu_bar.entries = terminal_menu_entries;
terminal_menu_bar.redraw_callback = render_decors_callback;
struct MenuEntry * _menu_exit = menu_create_normal("exit","exit","Exit", _menu_action_exit);
struct MenuEntry * _menu_copy = menu_create_normal(NULL, NULL, "Copy", _menu_action_copy);
struct MenuEntry * _menu_paste = menu_create_normal(NULL, NULL, "Paste", _menu_action_paste);
menu_right_click = menu_create();
menu_insert(menu_right_click, _menu_copy);
menu_insert(menu_right_click, _menu_paste);
menu_insert(menu_right_click, menu_create_separator());
if (!_fullscreen) {
_menu_toggle_borders_context = menu_create_normal(_no_frame ? NULL : "check", NULL, "Show borders", _menu_action_hide_borders);
menu_insert(menu_right_click, _menu_toggle_borders_context);
}
_menu_toggle_bitmap_context = menu_create_normal(_use_aa ? NULL : "check", NULL, "Bitmap font", _menu_action_toggle_tt);
menu_insert(menu_right_click, _menu_toggle_bitmap_context);
menu_insert(menu_right_click, menu_create_separator());
menu_insert(menu_right_click, _menu_exit);
/* Menu Bar menus */
terminal_menu_bar.set = menu_set_create();
struct MenuList * m;
m = menu_create(); /* File */
menu_insert(m, _menu_exit);
menu_set_insert(terminal_menu_bar.set, "file", m);
m = menu_create();
menu_insert(m, _menu_copy);
menu_insert(m, _menu_paste);
menu_set_insert(terminal_menu_bar.set, "edit", m);
m = menu_create();
menu_insert(m, menu_create_normal(NULL, "0.75", "75%", _menu_action_set_scale));
menu_insert(m, menu_create_normal(NULL, NULL, "100%", _menu_action_set_scale));
menu_insert(m, menu_create_normal(NULL, "1.5", "150%", _menu_action_set_scale));
menu_insert(m, menu_create_normal(NULL, "2.0", "200%", _menu_action_set_scale));
menu_set_insert(terminal_menu_bar.set, "zoom", m);
m = menu_create();
menu_insert(m, menu_create_normal(NULL, NULL, "View stats", _menu_action_cache_stats));
menu_insert(m, menu_create_normal(NULL, NULL, "Clear cache", _menu_action_clear_cache));
menu_set_insert(terminal_menu_bar.set, "cache", m);
m = menu_create();
_menu_toggle_borders_bar = menu_create_normal(_no_frame ? NULL : "check", NULL, "Show borders", _menu_action_hide_borders);
menu_insert(m, _menu_toggle_borders_bar);
menu_insert(m, menu_create_submenu(NULL,"zoom","Set zoom..."));
_menu_toggle_bitmap_bar = menu_create_normal(_use_aa ? NULL : "check", NULL, "Bitmap font", _menu_action_toggle_tt);
menu_insert(m, _menu_toggle_bitmap_bar);
menu_insert(m, menu_create_normal(_free_size ? NULL : "check", NULL, "Snap to Cell Size", _menu_action_toggle_free_size));
menu_insert(m, menu_create_separator());
menu_insert(m, menu_create_normal(NULL, NULL, "Redraw", _menu_action_redraw));
menu_insert(m, menu_create_submenu(NULL,"cache","Glyph cache..."));
menu_set_insert(terminal_menu_bar.set, "view", m);
m = menu_create();
menu_insert(m, menu_create_normal("help","help","Contents", _menu_action_show_help));
menu_insert(m, menu_create_separator());
menu_insert(m, menu_create_normal("star","star","About Terminal", _menu_action_show_about));
menu_set_insert(terminal_menu_bar.set, "help", m);
scrollback_list = list_create();
images_list = list_create();
/* Initialize the graphics context */
ctx = init_graphics_yutani_double_buffer(window);
/* Clear to black */
draw_fill(ctx, rgba(0,0,0,0));
if (window_position_set) {
/* Move to requested position */
yutani_window_move(yctx, window, window_left, window_top);
} else {
/* Move window to screen center */
yutani_window_move(yctx, window, yctx->display_width / 2 - window->width / 2, yctx->display_height / 2 - window->height / 2);
}
/* Open a PTY */
openpty(&fd_master, &fd_slave, NULL, NULL, NULL);
terminal = fdopen(fd_slave, "w");
/* Initialize the terminal buffer and ANSI library for the first time. */
reinit();
/* Run thread to handle asynchronous writes to the tty */
pthread_t input_buffer_thread;
pipe(input_buffer_semaphore);
input_buffer_queue = list_create();
pthread_create(&input_buffer_thread, NULL, handle_input_writing, NULL);
/* Make sure we're not passing anything to stdin on the child */
fflush(stdin);
/* Fork off child */
child_pid = fork();
if (!child_pid) {
setsid();
/* Prepare stdin/out/err */
dup2(fd_slave, 0);
dup2(fd_slave, 1);
dup2(fd_slave, 2);
tcsetpgrp(STDIN_FILENO, getpid());
/* Set the TERM environment variable. */
putenv("TERM=toaru");
/* Execute requested initial process */
if (argv[optind] != NULL) {
/* Run something specified by the terminal startup */
execvp(argv[optind], &argv[optind]);
fprintf(stderr, "Failed to launch requested startup application.\n");
} else {
/* Run the user's shell */
char * shell = getenv("SHELL");
if (!shell) shell = "/bin/sh"; /* fallback */
char * tokens[] = {shell,NULL};
execvp(tokens[0], tokens);
exit(1);
}
/* Failed to start */
exit_application = 1;
return 1;
} else {
/* Set up fswait to check Yutani and the PTY master */
int fds[2] = {fileno(yctx->sock), fd_master};
/* PTY read buffer */
unsigned char buf[4096];
int next_wait = 200;
while (!exit_application) {
/* Wait for something to happen. */
int res[] = {0,0};
fswait3(2,fds,next_wait,res);
/* Check if the child application has closed. */
check_for_exit();
maybe_flip_cursor();
int force_flip = (!res[1] && (next_wait == 10));
if (res[1]) {
/* Read from PTY */
ssize_t r = read(fd_master, buf, 4096);
for (ssize_t i = 0; i < r; ++i) {
ansi_put(ansi_state, buf[i]);
}
next_wait = 10;
} else {
next_wait = 200;
}
if (res[0]) {
/* Handle Yutani events. */
handle_incoming();
}
maybe_flip_display(force_flip);
}
}
close(input_buffer_semaphore[1]);
/* Windows will close automatically on exit. */
return 0;
}
|
079b600846d37040790ea946d0eb3507c2a4c548
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/rump/include/machine/intr.h
|
2d33c203b8fb371f6f5379f5b7b7361822d4fe09
|
[] |
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
| 2,330
|
h
|
intr.h
|
/* $NetBSD: intr.h,v 1.23 2023/08/17 14:19:49 andvar Exp $ */
/*
* Copyright (c) 2009, 2010 Antti Kantee. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef _SYS_RUMP_INTR_H_
#define _SYS_RUMP_INTR_H_
#ifndef _LOCORE
typedef uint8_t ipl_t;
typedef struct {
ipl_t _ipl;
} ipl_cookie_t;
static __inline ipl_cookie_t
makeiplcookie(ipl_t ipl)
{
ipl_cookie_t c;
c._ipl = ipl;
return c;
}
#endif /* !_LOCORE */
#define spllower(x) ((void)x)
#define splraise(x) 0
#define splsoftserial() 0
#define splsoftnet() 0
#define splsoftclock() 0
#define splhigh() 0
#define splsched() 0
#define splvm() 0
#define splx(x) ((void)x)
#define spl0() ((void)0)
/*
* IPL_* does not mean anything to a run-to-completion rump kernel,
* but we sometimes assert a "not higher than" condition, so we assign
* different values (following spl(9)).
*/
#define IPL_NONE 0
#define IPL_SOFTCLOCK 1
#define IPL_SOFTBIO 2
#define IPL_SOFTNET 3
#define IPL_SOFTSERIAL 4
#define IPL_VM 5
#define IPL_SCHED 6
#define IPL_HIGH 7
#define splraiseipl(COOKIE) 0
#endif /* _SYS_RUMP_INTR_H_ */
|
4a8edb169a79f05923885068041fd3f403545bdc
|
dbc5fd6f0b741d07aca08cff31fe88d2f62e8483
|
/tools/clang/test/zapcc/multi/include-extern-c/ScenarioRepository.h
|
272aa2b18a736149bb774bb1c636df77c899e77e
|
[
"LicenseRef-scancode-unknown-license-reference",
"NCSA"
] |
permissive
|
yrnkrn/zapcc
|
647246a2ed860f73adb49fa1bd21333d972ff76b
|
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
|
refs/heads/master
| 2023-03-08T22:55:12.842122
| 2020-07-21T10:21:59
| 2020-07-21T10:21:59
| 137,340,494
| 1,255
| 88
|
NOASSERTION
| 2020-07-21T10:22:01
| 2018-06-14T10:00:31
|
C++
|
UTF-8
|
C
| false
| false
| 37
|
h
|
ScenarioRepository.h
|
void Bug2020GetScenarioRepository();
|
677ea46014c6b8c2b9e91685318ea201c204c0ee
|
07bbe7a0a829cfbc9789831d981aedf36e4e94d9
|
/source/lexbor/html/tokenizer/state_rawtext.c
|
90a2d4017788e6547f95598a4f3c3fe49745fae8
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
lexbor/lexbor
|
0bf3a22898d8e295fa20cc1391e31a68502c458a
|
31e3d9d7f9032cd475d5afa788999de2d4b891dd
|
refs/heads/master
| 2023-08-31T23:25:49.903737
| 2023-08-30T08:25:12
| 2023-08-30T08:25:12
| 122,375,902
| 758
| 95
|
Apache-2.0
| 2023-08-30T08:25:13
| 2018-02-21T18:28:52
|
C
|
UTF-8
|
C
| false
| false
| 9,187
|
c
|
state_rawtext.c
|
/*
* Copyright (C) 2018-2020 Alexander Borisov
*
* Author: Alexander Borisov <borisov@lexbor.com>
*/
#include "lexbor/html/tokenizer/state_rawtext.h"
#include "lexbor/html/tokenizer/state.h"
#define LEXBOR_STR_RES_ANSI_REPLACEMENT_CHARACTER
#define LEXBOR_STR_RES_ALPHA_CHARACTER
#include "lexbor/core/str_res.h"
const lxb_tag_data_t *
lxb_tag_append_lower(lexbor_hash_t *hash,
const lxb_char_t *name, size_t length);
static const lxb_char_t *
lxb_html_tokenizer_state_rawtext(lxb_html_tokenizer_t *tkz,
const lxb_char_t *data,
const lxb_char_t *end);
static const lxb_char_t *
lxb_html_tokenizer_state_rawtext_less_than_sign(lxb_html_tokenizer_t *tkz,
const lxb_char_t *data,
const lxb_char_t *end);
static const lxb_char_t *
lxb_html_tokenizer_state_rawtext_end_tag_open(lxb_html_tokenizer_t *tkz,
const lxb_char_t *data,
const lxb_char_t *end);
static const lxb_char_t *
lxb_html_tokenizer_state_rawtext_end_tag_name(lxb_html_tokenizer_t *tkz,
const lxb_char_t *data,
const lxb_char_t *end);
/*
* Helper function. No in the specification. For 12.2.5.3 RAWTEXT state
*/
const lxb_char_t *
lxb_html_tokenizer_state_rawtext_before(lxb_html_tokenizer_t *tkz,
const lxb_char_t *data,
const lxb_char_t *end)
{
if (tkz->is_eof == false) {
lxb_html_tokenizer_state_token_set_begin(tkz, data);
}
tkz->state = lxb_html_tokenizer_state_rawtext;
return data;
}
/*
* 12.2.5.3 RAWTEXT state
*/
static const lxb_char_t *
lxb_html_tokenizer_state_rawtext(lxb_html_tokenizer_t *tkz,
const lxb_char_t *data,
const lxb_char_t *end)
{
lxb_html_tokenizer_state_begin_set(tkz, data);
while (data != end) {
switch (*data) {
/* U+003C LESS-THAN SIGN (<) */
case 0x3C:
lxb_html_tokenizer_state_append_data_m(tkz, data + 1);
lxb_html_tokenizer_state_token_set_end(tkz, data);
tkz->state = lxb_html_tokenizer_state_rawtext_less_than_sign;
return (data + 1);
/* U+000D CARRIAGE RETURN (CR) */
case 0x0D:
if (++data >= end) {
lxb_html_tokenizer_state_append_data_m(tkz, data - 1);
tkz->state = lxb_html_tokenizer_state_cr;
tkz->state_return = lxb_html_tokenizer_state_rawtext;
return data;
}
lxb_html_tokenizer_state_append_data_m(tkz, data);
tkz->pos[-1] = 0x0A;
lxb_html_tokenizer_state_begin_set(tkz, data + 1);
if (*data != 0x0A) {
lxb_html_tokenizer_state_begin_set(tkz, data);
data--;
}
break;
/*
* U+0000 NULL
* EOF
*/
case 0x00:
lxb_html_tokenizer_state_append_data_m(tkz, data);
if (tkz->is_eof) {
if (tkz->token->begin != NULL) {
lxb_html_tokenizer_state_token_set_end_oef(tkz);
}
tkz->token->tag_id = LXB_TAG__TEXT;
lxb_html_tokenizer_state_set_text(tkz);
lxb_html_tokenizer_state_token_done_m(tkz, end);
return end;
}
lxb_html_tokenizer_state_begin_set(tkz, data + 1);
lxb_html_tokenizer_state_append_replace_m(tkz);
lxb_html_tokenizer_error_add(tkz->parse_errors, data,
LXB_HTML_TOKENIZER_ERROR_UNNUCH);
break;
default:
break;
}
data++;
}
lxb_html_tokenizer_state_append_data_m(tkz, data);
return data;
}
/*
* 12.2.5.12 RAWTEXT less-than sign state
*/
static const lxb_char_t *
lxb_html_tokenizer_state_rawtext_less_than_sign(lxb_html_tokenizer_t *tkz,
const lxb_char_t *data,
const lxb_char_t *end)
{
/* U+002F SOLIDUS (/) */
if (*data == 0x2F) {
tkz->state = lxb_html_tokenizer_state_rawtext_end_tag_open;
return (data + 1);
}
tkz->state = lxb_html_tokenizer_state_rawtext;
return data;
}
/*
* 12.2.5.13 RAWTEXT end tag open state
*/
static const lxb_char_t *
lxb_html_tokenizer_state_rawtext_end_tag_open(lxb_html_tokenizer_t *tkz,
const lxb_char_t *data,
const lxb_char_t *end)
{
if (lexbor_str_res_alpha_character[*data] != LEXBOR_STR_RES_SLIP) {
tkz->temp = data;
tkz->entity_start = (tkz->pos - 1) - tkz->start;
tkz->state = lxb_html_tokenizer_state_rawtext_end_tag_name;
}
else {
tkz->state = lxb_html_tokenizer_state_rawtext;
}
lxb_html_tokenizer_state_append_m(tkz, "/", 1);
return data;
}
/*
* 12.2.5.14 RAWTEXT end tag name state
*/
static const lxb_char_t *
lxb_html_tokenizer_state_rawtext_end_tag_name(lxb_html_tokenizer_t *tkz,
const lxb_char_t *data,
const lxb_char_t *end)
{
lxb_html_tokenizer_state_begin_set(tkz, data);
while (data != end) {
switch (*data) {
/*
* U+0009 CHARACTER TABULATION (tab)
* U+000A LINE FEED (LF)
* U+000C FORM FEED (FF)
* U+000D CARRIAGE RETURN (CR)
* U+0020 SPACE
*/
case 0x09:
case 0x0A:
case 0x0C:
case 0x0D:
case 0x20:
lxb_html_tokenizer_state_append_data_m(tkz, data);
lxb_html_tokenizer_state_set_tag_m(tkz, &tkz->start[tkz->entity_start] + 2,
tkz->pos);
if (tkz->tmp_tag_id != tkz->token->tag_id) {
goto anything_else;
}
tkz->state = lxb_html_tokenizer_state_before_attribute_name;
goto done;
/* U+002F SOLIDUS (/) */
case 0x2F:
lxb_html_tokenizer_state_append_data_m(tkz, data);
lxb_html_tokenizer_state_set_tag_m(tkz, &tkz->start[tkz->entity_start] + 2,
tkz->pos);
if (tkz->tmp_tag_id != tkz->token->tag_id) {
goto anything_else;
}
tkz->state = lxb_html_tokenizer_state_self_closing_start_tag;
goto done;
/* U+003E GREATER-THAN SIGN (>) */
case 0x3E:
lxb_html_tokenizer_state_append_data_m(tkz, data);
lxb_html_tokenizer_state_set_tag_m(tkz, &tkz->start[tkz->entity_start] + 2,
tkz->pos);
if (tkz->tmp_tag_id != tkz->token->tag_id) {
goto anything_else;
}
tkz->state = lxb_html_tokenizer_state_data_before;
/* Emit text token */
tkz->token->tag_id = LXB_TAG__TEXT;
tkz->pos = &tkz->start[tkz->entity_start];
lxb_html_tokenizer_state_set_text(tkz);
lxb_html_tokenizer_state_token_done_m(tkz, end);
/* Init close token */
tkz->token->tag_id = tkz->tmp_tag_id;
tkz->token->begin = tkz->temp;
tkz->token->end = data;
tkz->token->type |= LXB_HTML_TOKEN_TYPE_CLOSE;
/* Emit close token */
lxb_html_tokenizer_state_token_done_m(tkz, end);
return (data + 1);
default:
if (lexbor_str_res_alpha_character[*data]
== LEXBOR_STR_RES_SLIP)
{
lxb_html_tokenizer_state_append_data_m(tkz, data);
goto anything_else;
}
break;
}
data++;
}
lxb_html_tokenizer_state_append_data_m(tkz, data);
return data;
anything_else:
tkz->state = lxb_html_tokenizer_state_rawtext;
return data;
done:
/* Emit text token */
tkz->token->tag_id = LXB_TAG__TEXT;
tkz->pos = &tkz->start[tkz->entity_start];
lxb_html_tokenizer_state_set_text(tkz);
lxb_html_tokenizer_state_token_done_m(tkz, end);
/* Init close token */
tkz->token->tag_id = tkz->tmp_tag_id;
tkz->token->begin = tkz->temp;
tkz->token->end = data;
tkz->token->type |= LXB_HTML_TOKEN_TYPE_CLOSE;
return (data + 1);
}
|
b1d1ae4be7f742d57d795ff91d99bcbbf1014c83
|
3a30cfb29aac91e5c75d4dbcefddfd1f34d5f18c
|
/c-tests/gcc/961122-1.c
|
f954d9a8c42213c2ad5a9d552ab8dbecb3c42330
|
[
"MIT",
"MPL-1.0",
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"LGPL-2.0-only",
"GPL-3.0-only",
"GPL-2.0-only"
] |
permissive
|
vnmakarov/mir
|
a1725bc9c828e8580df6b7ae94e04175db8abe93
|
928e28fb3acaa50d051a906e76a55cc48a556574
|
refs/heads/master
| 2023-09-02T11:10:37.434581
| 2023-08-25T19:25:40
| 2023-08-25T19:25:40
| 178,932,492
| 2,005
| 156
|
MIT
| 2023-08-01T20:29:59
| 2019-04-01T19:24:56
|
C
|
UTF-8
|
C
| false
| false
| 309
|
c
|
961122-1.c
|
extern void exit (int);
long long acc;
addhi (short a)
{
acc += (long long) a << 32;
}
subhi (short a)
{
acc -= (long long) a << 32;
}
main ()
{
acc = 0xffff00000000ll;
addhi (1);
if (acc != 0x1000000000000ll)
abort ();
subhi (1);
if (acc != 0xffff00000000ll)
abort ();
exit (0);
}
|
b1d8cc2a97e3111730e52410c7f79d61f0441de0
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/arch/arm/src/stm32h7/hardware/stm32h7x3xx_rcc.h
|
b7545523b1da560fb468aa8e61393ce98e19fd02
|
[
"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
| 78,283
|
h
|
stm32h7x3xx_rcc.h
|
/****************************************************************************
* arch/arm/src/stm32h7/hardware/stm32h7x3xx_rcc.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
#ifndef __ARCH_ARM_SRC_STM32H7_HARDWARE_STM32H7X3XX_RCC_H
#define __ARCH_ARM_SRC_STM32H7_HARDWARE_STM32H7X3XX_RCC_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Register Offsets *********************************************************/
/* TODO: Complete comments */
#define STM32_RCC_CR_OFFSET 0x0000 /* Clock control register */
#define STM32_RCC_ICSCR_OFFSET 0x0004
#define STM32_RCC_CRRCR_OFFSET 0x0008
#define STM32_RCC_CFGR_OFFSET 0x0010 /* Clock configuration register */
#define STM32_RCC_D1CFGR_OFFSET 0x0018
#define STM32_RCC_D2CFGR_OFFSET 0x001c
#define STM32_RCC_D3CFGR_OFFSET 0x0020
#define STM32_RCC_PLLCKSELR_OFFSET 0x0028
#define STM32_RCC_PLLCFGR_OFFSET 0x002c
#define STM32_RCC_PLL1DIVR_OFFSET 0x0030
#define STM32_RCC_PLL1FRACR_OFFSET 0x0034
#define STM32_RCC_PLL2DIVR_OFFSET 0x0038
#define STM32_RCC_PLL2FRACR_OFFSET 0x003c
#define STM32_RCC_PLL3DIVR_OFFSET 0x0040
#define STM32_RCC_PLL3FRACR_OFFSET 0x0044
#define STM32_RCC_D1CCIPR_OFFSET 0x004c /* Domain 1 Kernel Clock configuration register */
#define STM32_RCC_D2CCIP1R_OFFSET 0x0050 /* Domain 2 Kernel Clock configuration register 1 */
#define STM32_RCC_D2CCIP2R_OFFSET 0x0054 /* Domain 2 Kernel Clock configuration register 2 */
#define STM32_RCC_D3CCIPR_OFFSET 0x0058 /* Domain 3 Kernel Clock configuration register */
#define STM32_RCC_CIER_OFFSET 0x0060 /* Clock Source Interrupt enable register */
#define STM32_RCC_CIFR_OFFSET 0x0064 /* Clock Source Interrupt Flag register */
#define STM32_RCC_CICR_OFFSET 0x0068 /* Clock Source Interrupt Clear register */
#define STM32_RCC_BDCR_OFFSET 0x0070 /* Backup Domain Control register */
#define STM32_RCC_CSR_OFFSET 0x0074 /* Clock Control and Status register */
#define STM32_RCC_AHB1RSTR_OFFSET 0x0080 /* AHB1 peripheral reset register */
#define STM32_RCC_AHB2RSTR_OFFSET 0x0084 /* AHB2 peripheral reset register */
#define STM32_RCC_AHB3RSTR_OFFSET 0x007c /* AHB3 peripheral reset register */
#define STM32_RCC_AHB4RSTR_OFFSET 0x0088 /* AHB4 peripheral reset register */
#define STM32_RCC_APB1LRSTR_OFFSET 0x0090 /* APB1 L Peripheral reset register */
#define STM32_RCC_APB1HRSTR_OFFSET 0x0094 /* APB1 H Peripheral reset register */
#define STM32_RCC_APB2RSTR_OFFSET 0x0098 /* APB2 Peripheral reset register */
#define STM32_RCC_APB3RSTR_OFFSET 0x008c /* APB3 Peripheral reset register */
#define STM32_RCC_APB4RSTR_OFFSET 0x009c /* APB4 Peripheral reset register */
#define STM32_RCC_GCR_OFFSET 0x00a0 /* RCC Global Control register */
#define STM32_RCC_D3AMR_OFFSET 0x00a8 /* D3 Autonomous mode register */
#define STM32_RCC_RSR_OFFSET 0x00d0 /* RCC Reset Status register */
#define STM32_RCC_AHB1ENR_OFFSET 0x00d8 /* AHB1 Peripheral Clock enable register */
#define STM32_RCC_AHB2ENR_OFFSET 0x00dc /* AHB2 Peripheral Clock enable register */
#define STM32_RCC_AHB3ENR_OFFSET 0x00d4 /* AHB3 Peripheral Clock enable register */
#define STM32_RCC_AHB4ENR_OFFSET 0x00e0 /* AHB4 Peripheral Clock enable register */
#define STM32_RCC_APB1LENR_OFFSET 0x00e8 /* APB1 L Peripheral Clock enable register */
#define STM32_RCC_APB1HENR_OFFSET 0x00ec /* APB1 H Peripheral Clock enable register */
#define STM32_RCC_APB2ENR_OFFSET 0x00f0 /* APB2 Peripheral Clock enable register */
#define STM32_RCC_APB3ENR_OFFSET 0x00e4 /* APB3 Peripheral Clock enable register */
#define STM32_RCC_APB4ENR_OFFSET 0x00f4 /* APB4 Peripheral Clock enable register */
#define STM32_RCC_AHB1LPENR_OFFSET 0x0100 /* RCC AHB1 low power mode peripheral clock enable register */
#define STM32_RCC_AHB2LPENR_OFFSET 0x0104 /* RCC AHB2 low power mode peripheral clock enable register */
#define STM32_RCC_AHB3LPENR_OFFSET 0x00fc /* RCC AHB3 low power mode peripheral clock enable register */
#define STM32_RCC_AHB4LPENR_OFFSET 0x0108 /* RCC AHB4 low power mode peripheral clock enable register */
#define STM32_RCC_APB1LLPENR_OFFSET 0x0110 /* RCC APB1 L low power mode peripheral clock enable register */
#define STM32_RCC_APB1HLPENR_OFFSET 0x0114 /* RCC APB1 H low power mode peripheral clock enable register */
#define STM32_RCC_APB2LPENR_OFFSET 0x0118 /* RCC APB2 low power mode peripheral clock enable register */
#define STM32_RCC_APB3LPENR_OFFSET 0x010c /* RCC APB3 low power mode peripheral clock enable register */
#define STM32_RCC_APB4LPENR_OFFSET 0x011c /* RCC APB4 low power mode peripheral clock enable register */
/* Register Addresses *******************************************************/
#define STM32_RCC_CR (STM32_RCC_BASE + STM32_RCC_CR_OFFSET)
#define STM32_RCC_ICSCR (STM32_RCC_BASE + STM32_RCC_ICSCR_OFFSET)
#define STM32_RCC_CRRCR (STM32_RCC_BASE + STM32_RCC_CRRCR_OFFSET)
#define STM32_RCC_CFGR (STM32_RCC_BASE + STM32_RCC_CFGR_OFFSET)
#define STM32_RCC_D1CFGR (STM32_RCC_BASE + STM32_RCC_D1CFGR_OFFSET)
#define STM32_RCC_D2CFGR (STM32_RCC_BASE + STM32_RCC_D2CFGR_OFFSET)
#define STM32_RCC_D3CFGR (STM32_RCC_BASE + STM32_RCC_D3CFGR_OFFSET)
#define STM32_RCC_PLLCKSELR (STM32_RCC_BASE + STM32_RCC_PLLCKSELR_OFFSET)
#define STM32_RCC_PLLCFGR (STM32_RCC_BASE + STM32_RCC_PLLCFGR_OFFSET)
#define STM32_RCC_PLL1DIVR (STM32_RCC_BASE + STM32_RCC_PLL1DIVR_OFFSET)
#define STM32_RCC_PLL1FRACR (STM32_RCC_BASE + STM32_RCC_PLL1FRACR_OFFSET)
#define STM32_RCC_PLL2DIVR (STM32_RCC_BASE + STM32_RCC_PLL2DIVR_OFFSET)
#define STM32_RCC_PLL2FRACR (STM32_RCC_BASE + STM32_RCC_PLL2FRACR_OFFSET)
#define STM32_RCC_PLL3DIVR (STM32_RCC_BASE + STM32_RCC_PLL3DIVR_OFFSET)
#define STM32_RCC_PLL3FRACR (STM32_RCC_BASE + STM32_RCC_PLL3FRACR_OFFSET)
#define STM32_RCC_D1CCIPR (STM32_RCC_BASE + STM32_RCC_D1CCIPR_OFFSET)
#define STM32_RCC_D2CCIP1R (STM32_RCC_BASE + STM32_RCC_D2CCIP1R_OFFSET)
#define STM32_RCC_D2CCIP2R (STM32_RCC_BASE + STM32_RCC_D2CCIP2R_OFFSET)
#define STM32_RCC_D3CCIPR (STM32_RCC_BASE + STM32_RCC_D3CCIPR_OFFSET)
#define STM32_RCC_CIER (STM32_RCC_BASE + STM32_RCC_CIER_OFFSET)
#define STM32_RCC_CIFR (STM32_RCC_BASE + STM32_RCC_CIFR_OFFSET)
#define STM32_RCC_CICR (STM32_RCC_BASE + STM32_RCC_CICR_OFFSET)
#define STM32_RCC_BDCR (STM32_RCC_BASE + STM32_RCC_BDCR_OFFSET)
#define STM32_RCC_CSR (STM32_RCC_BASE + STM32_RCC_CSR_OFFSET)
#define STM32_RCC_AHB1RSTR (STM32_RCC_BASE + STM32_RCC_AHB1RSTR_OFFSET)
#define STM32_RCC_AHB2RSTR (STM32_RCC_BASE + STM32_RCC_AHB2RSTR_OFFSET)
#define STM32_RCC_AHB3RSTR (STM32_RCC_BASE + STM32_RCC_AHB3RSTR_OFFSET)
#define STM32_RCC_AHB4RSTR (STM32_RCC_BASE + STM32_RCC_AHB4RSTR_OFFSET)
#define STM32_RCC_APB1LRSTR (STM32_RCC_BASE + STM32_RCC_APB1LRSTR_OFFSET)
#define STM32_RCC_APB1HRSTR (STM32_RCC_BASE + STM32_RCC_APB1HRSTR_OFFSET)
#define STM32_RCC_APB2RSTR (STM32_RCC_BASE + STM32_RCC_APB2RSTR_OFFSET)
#define STM32_RCC_APB3RSTR (STM32_RCC_BASE + STM32_RCC_APB3RSTR_OFFSET)
#define STM32_RCC_APB4RSTR (STM32_RCC_BASE + STM32_RCC_APB4RSTR_OFFSET)
#define STM32_RCC_GCR (STM32_RCC_BASE + STM32_RCC_GCR_OFFSET)
#define STM32_RCC_D3AMR (STM32_RCC_BASE + STM32_RCC_D3AMR_OFFSET)
#define STM32_RCC_RSR (STM32_RCC_BASE + STM32_RCC_RSR_OFFSET)
#define STM32_RCC_AHB1ENR (STM32_RCC_BASE + STM32_RCC_AHB1ENR_OFFSET)
#define STM32_RCC_AHB2ENR (STM32_RCC_BASE + STM32_RCC_AHB2ENR_OFFSET)
#define STM32_RCC_AHB3ENR (STM32_RCC_BASE + STM32_RCC_AHB3ENR_OFFSET)
#define STM32_RCC_AHB4ENR (STM32_RCC_BASE + STM32_RCC_AHB4ENR_OFFSET)
#define STM32_RCC_APB1LENR (STM32_RCC_BASE + STM32_RCC_APB1LENR_OFFSET)
#define STM32_RCC_APB1HENR (STM32_RCC_BASE + STM32_RCC_APB1HENR_OFFSET)
#define STM32_RCC_APB2ENR (STM32_RCC_BASE + STM32_RCC_APB2ENR_OFFSET)
#define STM32_RCC_APB3ENR (STM32_RCC_BASE + STM32_RCC_APB3ENR_OFFSET)
#define STM32_RCC_APB4ENR (STM32_RCC_BASE + STM32_RCC_APB4ENR_OFFSET)
#define STM32_RCC_AHB1LPENR (STM32_RCC_BASE + STM32_RCC_AHB1LPENR_OFFSET)
#define STM32_RCC_AHB2LPENR (STM32_RCC_BASE + STM32_RCC_AHB2LPENR_OFFSET)
#define STM32_RCC_AHB3LPENR (STM32_RCC_BASE + STM32_RCC_AHB3LPENR_OFFSET)
#define STM32_RCC_AHB4LPENR (STM32_RCC_BASE + STM32_RCC_AHB4LPENR_OFFSET)
#define STM32_RCC_APB1LLPENR (STM32_RCC_BASE + STM32_RCC_APB1LLPENR_OFFSET)
#define STM32_RCC_APB1HLPENR (STM32_RCC_BASE + STM32_RCC_APB1HLPENR_OFFSET)
#define STM32_RCC_APB2LPENR (STM32_RCC_BASE + STM32_RCC_APB2LPENR_OFFSET)
#define STM32_RCC_APB3LPENR (STM32_RCC_BASE + STM32_RCC_APB3LPENR_OFFSET)
#define STM32_RCC_APB4LPENR (STM32_RCC_BASE + STM32_RCC_APB4LPENR_OFFSET)
/* Register Bitfield Definitions ********************************************/
/* Source Control Register */
#define RCC_CR_HSION (1 << 0) /* Bit 0: Internal High Speed clock enable */
#define RCC_CR_HSIKERON (1 << 1) /* Bit 1: Internal High Speed clock enable for some IPs Kernel ?? */
#define RCC_CR_HSIRDY (1 << 2) /* Bit 2: Internal High Speed clock ready flag */
#define RCC_CR_HSIDIV_SHIFT (3) /* Bits 3-4: HSI clock divider */
#define RCC_CR_HSIDIV_MASK (3 << RCC_CR_HSIDIV_SHIFT)
# define RCC_CR_HSIDIV_1 (0 << RCC_CR_HSIDIV_SHIFT)
# define RCC_CR_HSIDIV_2 (1 << RCC_CR_HSIDIV_SHIFT)
# define RCC_CR_HSIDIV_4 (2 << RCC_CR_HSIDIV_SHIFT)
# define RCC_CR_HSIDIV_8 (3 << RCC_CR_HSIDIV_SHIFT)
#define RCC_CR_HSIDIVF (1 << 5) /* Bit 5: HSI Divider flag */
/* Bit 6: Reserved */
#define RCC_CR_CSION (1 << 7) /* Bit 7: The Internal RC 4MHz oscillator clock enable */
#define RCC_CR_CSIRDY (1 << 8) /* Bit 8: The Internal RC 4MHz oscillator clock ready */
#define RCC_CR_CSIKERON (1 << 9) /* Bit 9: Internal RC 4MHz oscillator clock enable for some IPs Kernel */
/* Bits 10-11: Reserved */
#define RCC_CR_HSI48ON (1 << 12) /* Bit 12: HSI48 clock enable clock enable */
#define RCC_CR_HSI48RDY (1 << 13) /* Bit 13: HSI48 clock ready */
#define RCC_CR_D1CKRDY (1 << 14) /* Bit 14: D1 domain clocks ready flag */
#define RCC_CR_D2CKRDY (1 << 15) /* Bit 15: D2 domain clocks ready flag */
#define RCC_CR_HSEON (1 << 16) /* Bit 16: External High Speed clock enable */
#define RCC_CR_HSERDY (1 << 17) /* Bit 17: External High Speed clock ready */
#define RCC_CR_HSEBYP (1 << 18) /* Bit 18: External High Speed clock Bypass */
#define RCC_CR_CSSHSEON (1 << 19) /* Bit 19: HSE Clock security System enable */
/* Bits 20-23: Reserved */
#define RCC_CR_PLL1ON (1 << 24) /* Bit 24: System PLL1 clock enable */
#define RCC_CR_PLL1RDY (1 << 25) /* Bit 25: System PLL1 clock ready */
#define RCC_CR_PLL2ON (1 << 26) /* Bit 26: System PLL2 clock enable */
#define RCC_CR_PLL2RDY (1 << 27) /* Bit 27: System PLL2 clock ready */
#define RCC_CR_PLL3ON (1 << 28) /* Bit 28: System PLL3 clock enable */
#define RCC_CR_PLL3RDY (1 << 29) /* Bit 29: System PLL3 clock ready */
/* Bits 30-31: Reserved */
/* Internal Clock Source Calibration Register */
/* HSICAL configuration */
#define RCC_ICSCR_HSICAL_SHIFT (0ul)
#define RCC_ICSCR_HSICAL_MASK (0xFFFul << RCC_ICSCR_HSICAL_SHIFT)
#define RCC_ICSCR_HSICAL RCC_ICSCR_HSICAL_MASK /* HSICAL[11:0] bits */
/* HSITRIM configuration */
#define RCC_ICSCR_HSITRIM_SHIFT (12ul)
#define RCC_ICSCR_HSITRIM_MASK (0x3Ful << RCC_ICSCR_HSITRIM_SHIFT)
#define RCC_ICSCR_HSITRIM RCC_ICSCR_HSITRIM_MASK /* HSITRIM[5:0] bits */
/* CSICAL configuration */
#define RCC_ICSCR_CSICAL_SHIFT (18ul)
#define RCC_ICSCR_CSICAL_MASK (0xFFul << RCC_ICSCR_CSICAL_SHIFT)
#define RCC_ICSCR_CSICAL RCC_ICSCR_CSICAL_MASK /* CSICAL[7:0] bits */
/* CSITRIM configuration */
#define RCC_ICSCR_CSITRIM_SHIFT (26ul)
#define RCC_ICSCR_CSITRIM_MASK (0x1Ful << RCC_ICSCR_CSITRIM_SHIFT)
#define RCC_ICSCR_CSITRIM RCC_ICSCR_CSITRIM_MASK /* CSITRIM[4:0] bits */
/* Clock Recovery RC Register */
/* HSI48CAL configuration */
#define RCC_CRRCR_HSI48CAL_SHIFT (0ul)
#define RCC_CRRCR_HSI48CAL_MASK (0x3FFul << RCC_CRRCR_HSI48CAL_SHIFT)
#define RCC_CRRCR_HSI48CAL RCC_CRRCR_HSI48CAL_MASK /* HSI48CAL[9:0] bits */
/* Clock Configuration Register (CFGR) */
#define RCC_CFGR_SW_SHIFT (0) /* Bits 0-2: System clock Switch */
#define RCC_CFGR_SW_MASK (7 << RCC_CFGR_SW_SHIFT)
# define RCC_CFGR_SW_HSI (0 << RCC_CFGR_SW_SHIFT) /* 000: HSI selection as system clock */
# define RCC_CFGR_SW_CSI (1 << RCC_CFGR_SW_SHIFT) /* 001: CSI selection as system clock */
# define RCC_CFGR_SW_HSE (2 << RCC_CFGR_SW_SHIFT) /* 010: HSE selection as system clock */
# define RCC_CFGR_SW_PLL1 (3 << RCC_CFGR_SW_SHIFT) /* 011: PLL1 selection as system clock */
#define RCC_CFGR_SWS_SHIFT (3) /* Bits 3-5: System Clock Switch Status */
#define RCC_CFGR_SWS_MASK (7 << RCC_CFGR_SWS_SHIFT)
# define RCC_CFGR_SWS_HSI (0 << RCC_CFGR_SWS_SHIFT) /* 000: HSI used as system clock */
# define RCC_CFGR_SWS_CSI (1 << RCC_CFGR_SWS_SHIFT) /* 001: CSI used as system clock */
# define RCC_CFGR_SWS_HSE (2 << RCC_CFGR_SWS_SHIFT) /* 010: HSE used as system clock */
# define RCC_CFGR_SWS_PLL1 (3 << RCC_CFGR_SWS_SHIFT) /* 011: PLL1 used as system clock */
#define RCC_CFGR_STOPWUCK (1 << 6) /* Bit 6: Wake Up from stop and CSS backup clock selection */
#define RCC_CFGR_STOPKERWUCK (1 << 7) /* Bit 7: Kernel Clock Selection after a Wake Up from STOP */
#define RCC_CFGR_RTCPRE_SHIFT (8) /* Bits 8-13: HSE division factor for RTC clock */
#define RCC_CFGR_RTCPRE_MASK (0x3f << RCC_CFGR_RTCPRE_SHIFT)
# define RCC_CFGR_RTCPRE(x) (((uint32_t)(x)) << RCC_CFGR_RTCPRE_SHIFT)
#define RCC_CFGR_HRTIMSEL (1 << 14) /* Bit 14: HRTIM TImer clock prescaler */
#define RCC_CFGR_TIMPRE (1 << 15) /* Timers clocks prescaler */
#define RCC_CFGR_MCO1PRE_SHIFT (18) /* Bits 18-21: MCO1 prescaler */
#define RCC_CFGR_MCO1PRE_MASK (0xf << RCC_CFGR_MCO1PRE_SHIFT)
# define RCC_CFGR_MCO1PRE(x) (((uint32_t)(x)) << 18)
#define RCC_CFGR_MCO1_SHIFT (22) /* Bits 22-24: Microcontroller Clock Output 1 */
#define RCC_CFGR_MCO1_MASK (7 << RCC_CFGR_MCO1_SHIFT)
# define RCC_CFGR_MCO1_HSI (0 << RCC_CFGR_MCO1_SHIFT) /* 000: HSI clock selected */
# define RCC_CFGR_MCO1_LSE (1 << RCC_CFGR_MCO1_SHIFT) /* 001: LSE oscillator selected */
# define RCC_CFGR_MCO1_HSE (2 << RCC_CFGR_MCO1_SHIFT) /* 010: HSE oscillator clock selected */
# define RCC_CFGR_MCO1_PLL1Q (3 << RCC_CFGR_MCO1_SHIFT) /* 011: PLL clock selected */
# define RCC_CFGR_MCO1_HSI48 (4 << RCC_CFGR_MCO1_SHIFT) /* 100: HSI48 clock selected */
#define RCC_CFGR_MCO2PRE_SHIFT (25) /* Bits 25-28: MCO2 prescaler */
#define RCC_CFGR_MCO2PRE_MASK (0xf << RCC_CFGR_MCO2PRE_SHIFT)
# define RCC_CFGR_MCO2PRE(x) (((uint32_t)(x)) << RCC_CFGR_MCO2PRE_SHIFT)
#define RCC_CFGR_MCO2_SHIFT (29) /* Bits 29-31: Microcontroller Clock Output 2 */
#define RCC_CFGR_MCO2_MASK (7 << RCC_CFGR_MCO2_SHIFT)
# define RCC_CFGR_MCO2_SYS (0 << RCC_CFGR_MCO2_SHIFT) /* 000: HSI clock selected */
# define RCC_CFGR_MCO2_PLL2P (1 << RCC_CFGR_MCO2_SHIFT) /* 001: PLL2 peripheral clock selected */
# define RCC_CFGR_MCO2_HSE (2 << RCC_CFGR_MCO2_SHIFT) /* 010: HSE oscillator clock selected */
# define RCC_CFGR_MCO2_PLL1P (3 << RCC_CFGR_MCO2_SHIFT) /* 011: PLL1 peripheral clock selected */
# define RCC_CFGR_MCO2_CSI (4 << RCC_CFGR_MCO2_SHIFT) /* 100: CSI clock selected */
# define RCC_CFGR_MCO2_LSI (5 << RCC_CFGR_MCO2_SHIFT) /* 101: LSI clock selected */
/* Bit definitions for RCC_D1CFGR */
#define RCC_D1CFGR_HPRE_SHIFT (0) /* Bits 0-3: D1 domain AHB prescaler */
#define RCC_D1CFGR_HPRE_MASK (15 << RCC_D1CFGR_HPRE_SHIFT)
# define RCC_D1CFGR_HPRE_SYSCLK (0 << RCC_D1CFGR_HPRE_SHIFT)
# define RCC_D1CFGR_HPRE_SYSCLKd2 (8 << RCC_D1CFGR_HPRE_SHIFT)
# define RCC_D1CFGR_HPRE_SYSCLKd4 (9 << RCC_D1CFGR_HPRE_SHIFT)
# define RCC_D1CFGR_HPRE_SYSCLKd8 (10 << RCC_D1CFGR_HPRE_SHIFT)
# define RCC_D1CFGR_HPRE_SYSCLKd16 (11 << RCC_D1CFGR_HPRE_SHIFT)
# define RCC_D1CFGR_HPRE_SYSCLKd64 (12 << RCC_D1CFGR_HPRE_SHIFT)
# define RCC_D1CFGR_HPRE_SYSCLKd128 (13 << RCC_D1CFGR_HPRE_SHIFT)
# define RCC_D1CFGR_HPRE_SYSCLKd256 (14 << RCC_D1CFGR_HPRE_SHIFT)
# define RCC_D1CFGR_HPRE_SYSCLKd512 (15 << RCC_D1CFGR_HPRE_SHIFT)
#define RCC_D1CFGR_D1PPRE_SHIFT (4) /* Bits 4-6: D1 domain APB3 prescaler */
#define RCC_D1CFGR_D1PPRE_MASK (7 << RCC_D1CFGR_D1PPRE_SHIFT)
# define RCC_D1CFGR_D1PPRE_HCLK (0 << RCC_D1CFGR_D1PPRE_SHIFT)
# define RCC_D1CFGR_D1PPRE_HCLKd2 (4 << RCC_D1CFGR_D1PPRE_SHIFT)
# define RCC_D1CFGR_D1PPRE_HCLKd4 (5 << RCC_D1CFGR_D1PPRE_SHIFT)
# define RCC_D1CFGR_D1PPRE_HCLKd8 (6 << RCC_D1CFGR_D1PPRE_SHIFT)
# define RCC_D1CFGR_D1PPRE_HCLKd16 (7 << RCC_D1CFGR_D1PPRE_SHIFT)
/* Bit 7: Reserved */
#define RCC_D1CFGR_D1CPRE_SHIFT (8) /* Bits 8-11: D1 domain Core prescaler */
#define RCC_D1CFGR_D1CPRE_MASK (15 << RCC_D1CFGR_D1CPRE_SHIFT)
# define RCC_D1CFGR_D1CPRE_SYSCLK (0 << RCC_D1CFGR_D1CPRE_SHIFT)
# define RCC_D1CFGR_D1CPRE_SYSCLKd2 (8 << RCC_D1CFGR_D1CPRE_SHIFT)
# define RCC_D1CFGR_D1CPRE_SYSCLKd4 (9 << RCC_D1CFGR_D1CPRE_SHIFT)
# define RCC_D1CFGR_D1CPRE_SYSCLKd8 (10 << RCC_D1CFGR_D1CPRE_SHIFT)
# define RCC_D1CFGR_D1CPRE_SYSCLKd16 (11 << RCC_D1CFGR_D1CPRE_SHIFT)
# define RCC_D1CFGR_D1CPRE_SYSCLKd64 (12 << RCC_D1CFGR_D1CPRE_SHIFT)
# define RCC_D1CFGR_D1CPRE_SYSCLKd128 (13 << RCC_D1CFGR_D1CPRE_SHIFT)
# define RCC_D1CFGR_D1CPRE_SYSCLKd256 (14 << RCC_D1CFGR_D1CPRE_SHIFT)
# define RCC_D1CFGR_D1CPRE_SYSCLKd512 (15 << RCC_D1CFGR_D1CPRE_SHIFT)
/* Bits 12-31: Reserved */
/* Bit definitions for RCC_D2CFGR */
/* Bits 0-3: Reserved */
#define RCC_D2CFGR_D2PPRE1_SHIFT (4) /* Bits 4-6: D2 domain APB1 prescaler */
#define RCC_D2CFGR_D2PPRE1_MASK (7 << RCC_D2CFGR_D2PPRE1_SHIFT)
# define RCC_D2CFGR_D2PPRE1_HCLK (0 << RCC_D2CFGR_D2PPRE1_SHIFT)
# define RCC_D2CFGR_D2PPRE1_HCLKd2 (4 << RCC_D2CFGR_D2PPRE1_SHIFT)
# define RCC_D2CFGR_D2PPRE1_HCLKd4 (5 << RCC_D2CFGR_D2PPRE1_SHIFT)
# define RCC_D2CFGR_D2PPRE1_HCLKd8 (6 << RCC_D2CFGR_D2PPRE1_SHIFT)
# define RCC_D2CFGR_D2PPRE1_HCLKd16 (7 << RCC_D2CFGR_D2PPRE1_SHIFT)
/* Bit 7: Reserved */
#define RCC_D2CFGR_D2PPRE2_SHIFT (8) /* Bits 8-10: D2 domain APB2 prescaler */
#define RCC_D2CFGR_D2PPRE2_MASK (7 << RCC_D2CFGR_D2PPRE2_SHIFT)
# define RCC_D2CFGR_D2PPRE2_HCLK (0 << RCC_D2CFGR_D2PPRE2_SHIFT)
# define RCC_D2CFGR_D2PPRE2_HCLKd2 (4 << RCC_D2CFGR_D2PPRE2_SHIFT)
# define RCC_D2CFGR_D2PPRE2_HCLKd4 (5 << RCC_D2CFGR_D2PPRE2_SHIFT)
# define RCC_D2CFGR_D2PPRE2_HCLKd8 (6 << RCC_D2CFGR_D2PPRE2_SHIFT)
# define RCC_D2CFGR_D2PPRE2_HCLKd16 (7 << RCC_D2CFGR_D2PPRE2_SHIFT)
/* Bits 11-31: Reserved */
/* Bit definitions for RCC_D3CFGR */
/* Bits 0-3: Reserved */
#define RCC_D3CFGR_D3PPRE_SHIFT (4) /* Bits 4-6: D3 domain APB4 prescaler */
#define RCC_D3CFGR_D3PPRE_MASK (7 << RCC_D3CFGR_D3PPRE_SHIFT)
# define RCC_D3CFGR_D3PPRE_HCLK (0 << RCC_D3CFGR_D3PPRE_SHIFT)
# define RCC_D3CFGR_D3PPRE_HCLKd2 (4 << RCC_D3CFGR_D3PPRE_SHIFT)
# define RCC_D3CFGR_D3PPRE_HCLKd4 (5 << RCC_D3CFGR_D3PPRE_SHIFT)
# define RCC_D3CFGR_D3PPRE_HCLKd8 (6 << RCC_D3CFGR_D3PPRE_SHIFT)
# define RCC_D3CFGR_D3PPRE_HCLKd16 (7 << RCC_D3CFGR_D3PPRE_SHIFT)
/* Bits 7-31: Reserved */
/* Bit definitions for RCC_PLLCKSELR register */
#define RCC_PLLCKSELR_PLLSRC_SHIFT (0) /* Bit 0: */
#define RCC_PLLCKSELR_PLLSRC_MASK (0x3 << RCC_PLLCKSELR_PLLSRC_SHIFT)
#define RCC_PLLCKSELR_PLLSRC RCC_PLLCKSELR_PLLSRC_MASK
#define RCC_PLLCKSELR_PLLSRC_HSI ((uint32_t)0x00000000) /* HSI source clock selected */
#define RCC_PLLCKSELR_PLLSRC_CSI ((uint32_t)0x00000001) /* CSI source clock selected */
#define RCC_PLLCKSELR_PLLSRC_HSE ((uint32_t)0x00000002) /* HSE source clock selected */
#define RCC_PLLCKSELR_PLLSRC_NONE ((uint32_t)0x00000003) /* No source clock selected */
#define RCC_PLLCKSELR_DIVM1_SHIFT (4ul)
#define RCC_PLLCKSELR_DIVM1(x) ((x) << RCC_PLLCKSELR_DIVM1_SHIFT) /* Prescaler for PLL1: 1 - 63, 0 = disabled */
#define RCC_PLLCKSELR_DIVM2_SHIFT (12ul)
#define RCC_PLLCKSELR_DIVM2(x) ((x) << RCC_PLLCKSELR_DIVM2_SHIFT) /* Prescaler for PLL2: 1 - 63, 0 = disabled */
#define RCC_PLLCKSELR_DIVM3_SHIFT (20ul)
#define RCC_PLLCKSELR_DIVM3(x) ((x) << RCC_PLLCKSELR_DIVM3_SHIFT) /* Prescaler for PLL3: 1 - 63, 0 = disabled */
/* Bit definition for RCC_PLLCFGR register */
#define RCC_PLLCFGR_RESET ((uint32_t)0x01FF0000)
#define RCC_PLLCFGR_PLL1FRACEN_SHIFT (0ul)
#define RCC_PLLCFGR_PLL1FRACEN_MASK (0x1ul << RCC_PLLCFGR_PLL1FRACEN_SHIFT)
#define RCC_PLLCFGR_PLL1FRACEN RCC_PLLCFGR_PLL1FRACEN_MASK /* Fractional latch enable */
#define RCC_PLLCFGR_PLL1VCOSEL_SHIFT (1ul)
#define RCC_PLLCFGR_PLL1VCOSEL_MASK (0x1ul << RCC_PLLCFGR_PLL1VCOSEL_SHIFT)
#define RCC_PLLCFGR_PLL1VCOSEL RCC_PLLCFGR_PLL1VCOSEL_MASK /* VCO freq range: 1 = Medium VCO range: 150 to 420 MHz, 0 = Wide VCO range: 192 to 836 MHz */
#define RCC_PLLCFGR_PLL1VCOSEL_WIDE (0ul) /* VCO freq range: Wide VCO range: 192 to 836 MHz, input clock >= 2 MHz */
#define RCC_PLLCFGR_PLL1VCOSEL_MEDIUM RCC_PLLCFGR_PLL3VCOSEL /* VCO freq range: Medium VCO range: 150 to 420 MHz, input clock <= 2 MHz */
#define RCC_PLLCFGR_PLL1RGE_SHIFT (2ul)
#define RCC_PLLCFGR_PLL1RGE_MASK (0x3ul << RCC_PLLCFGR_PLL1RGE_SHIFT)
#define RCC_PLLCFGR_PLL1RGE RCC_PLLCFGR_PLL1RGE_MASK
#define RCC_PLLCFGR_PLL1RGE_1_2_MHZ (0x0ul << RCC_PLLCFGR_PLL1RGE_SHIFT) /* The PLL input clock range frequency is between 1 and 2 MHz */
#define RCC_PLLCFGR_PLL1RGE_2_4_MHZ (0x1ul << RCC_PLLCFGR_PLL1RGE_SHIFT) /* The PLL input clock range frequency is between 2 and 4 MHz */
#define RCC_PLLCFGR_PLL1RGE_4_8_MHZ (0x2ul << RCC_PLLCFGR_PLL1RGE_SHIFT) /* The PLL input clock range frequency is between 4 and 8 MHz */
#define RCC_PLLCFGR_PLL1RGE_8_16_MHZ (0x3ul << RCC_PLLCFGR_PLL1RGE_SHIFT) /* The PLL input clock range frequency is between 8 and 16 MHz */
#define RCC_PLLCFGR_PLL2FRACEN_SHIFT (4ul)
#define RCC_PLLCFGR_PLL2FRACEN_MASK (0x1ul << RCC_PLLCFGR_PLL2FRACEN_SHIFT)
#define RCC_PLLCFGR_PLL2FRACEN RCC_PLLCFGR_PLL2FRACEN_MASK /* Fractional latch enable */
#define RCC_PLLCFGR_PLL2VCOSEL_SHIFT (5ul)
#define RCC_PLLCFGR_PLL2VCOSEL_MASK (0x1ul << RCC_PLLCFGR_PLL2VCOSEL_SHIFT)
#define RCC_PLLCFGR_PLL2VCOSEL RCC_PLLCFGR_PLL2VCOSEL_MASK /* VCO freq range: 1 = Medium VCO range: 150 to 420 MHz, 0 = Wide VCO range: 192 to 836 MHz */
#define RCC_PLLCFGR_PLL2VCOSEL_WIDE (0ul) /* VCO freq range: Wide VCO range: 192 to 836 MHz, input clock >= 2 MHz */
#define RCC_PLLCFGR_PLL2VCOSEL_MEDIUM RCC_PLLCFGR_PLL3VCOSEL /* VCO freq range: Medium VCO range: 150 to 420 MHz, input clock <= 2 MHz */
#define RCC_PLLCFGR_PLL2RGE_SHIFT (6ul)
#define RCC_PLLCFGR_PLL2RGE_MASK (0x3ul << RCC_PLLCFGR_PLL2RGE_SHIFT)
#define RCC_PLLCFGR_PLL2RGE RCC_PLLCFGR_PLL2RGE_MASK
#define RCC_PLLCFGR_PLL2RGE_1_2_MHZ (0x0ul << RCC_PLLCFGR_PLL2RGE_SHIFT) /* The PLL input clock range frequency is between 1 and 2 MHz */
#define RCC_PLLCFGR_PLL2RGE_2_4_MHZ (0x1ul << RCC_PLLCFGR_PLL2RGE_SHIFT) /* The PLL input clock range frequency is between 2 and 4 MHz */
#define RCC_PLLCFGR_PLL2RGE_4_8_MHZ (0x2ul << RCC_PLLCFGR_PLL2RGE_SHIFT) /* The PLL input clock range frequency is between 4 and 8 MHz */
#define RCC_PLLCFGR_PLL2RGE_8_16_MHZ (0x3ul << RCC_PLLCFGR_PLL2RGE_SHIFT) /* The PLL input clock range frequency is between 8 and 16 MHz */
#define RCC_PLLCFGR_PLL3FRACEN_SHIFT (8ul)
#define RCC_PLLCFGR_PLL3FRACEN_MASK (0x1ul << RCC_PLLCFGR_PLL3FRACEN_SHIFT)
#define RCC_PLLCFGR_PLL3FRACEN RCC_PLLCFGR_PLL3FRACEN_MASK /* Fractional latch enable */
#define RCC_PLLCFGR_PLL3VCOSEL_SHIFT (9ul)
#define RCC_PLLCFGR_PLL3VCOSEL_MASK (0x1ul << RCC_PLLCFGR_PLL3VCOSEL_SHIFT)
#define RCC_PLLCFGR_PLL3VCOSEL RCC_PLLCFGR_PLL3VCOSEL_MASK /* VCO freq range: 1 = Medium VCO range: 150 to 420 MHz, 0 = Wide VCO range: 192 to 836 MHz */
#define RCC_PLLCFGR_PLL3VCOSEL_WIDE (0ul) /* VCO freq range: Wide VCO range: 192 to 836 MHz, input clock >= 2 MHz */
#define RCC_PLLCFGR_PLL3VCOSEL_MEDIUM RCC_PLLCFGR_PLL3VCOSEL /* VCO freq range: Medium VCO range: 150 to 420 MHz, input clock <= 2 MHz */
#define RCC_PLLCFGR_PLL3RGE_SHIFT (10ul)
#define RCC_PLLCFGR_PLL3RGE_MASK (0x3ul << RCC_PLLCFGR_PLL3RGE_SHIFT)
#define RCC_PLLCFGR_PLL3RGE RCC_PLLCFGR_PLL3RGE_MASK
#define RCC_PLLCFGR_PLL3RGE_1_2_MHZ (0x0ul << RCC_PLLCFGR_PLL3RGE_SHIFT) /* The PLL input clock range frequency is between 1 and 2 MHz */
#define RCC_PLLCFGR_PLL3RGE_2_4_MHZ (0x1ul << RCC_PLLCFGR_PLL3RGE_SHIFT) /* The PLL input clock range frequency is between 2 and 4 MHz */
#define RCC_PLLCFGR_PLL3RGE_4_8_MHZ (0x2ul << RCC_PLLCFGR_PLL3RGE_SHIFT) /* The PLL input clock range frequency is between 4 and 8 MHz */
#define RCC_PLLCFGR_PLL3RGE_8_16_MHZ (0x3ul << RCC_PLLCFGR_PLL3RGE_SHIFT) /* The PLL input clock range frequency is between 8 and 16 MHz */
#define RCC_PLLCFGR_DIVP1EN_SHIFT (16ul)
#define RCC_PLLCFGR_DIVP1EN_MASK (0x1ul << RCC_PLLCFGR_DIVP1EN_SHIFT)
#define RCC_PLLCFGR_DIVP1EN RCC_PLLCFGR_DIVP1EN_MASK
#define RCC_PLLCFGR_DIVQ1EN_SHIFT (17ul)
#define RCC_PLLCFGR_DIVQ1EN_MASK (0x1ul << RCC_PLLCFGR_DIVQ1EN_SHIFT)
#define RCC_PLLCFGR_DIVQ1EN RCC_PLLCFGR_DIVQ1EN_MASK
#define RCC_PLLCFGR_DIVR1EN_SHIFT (18ul)
#define RCC_PLLCFGR_DIVR1EN_MASK (0x1ul << RCC_PLLCFGR_DIVR1EN_SHIFT)
#define RCC_PLLCFGR_DIVR1EN RCC_PLLCFGR_DIVR1EN_MASK
#define RCC_PLLCFGR_DIVP2EN_SHIFT (19ul)
#define RCC_PLLCFGR_DIVP2EN_MASK (0x1ul << RCC_PLLCFGR_DIVP2EN_SHIFT)
#define RCC_PLLCFGR_DIVP2EN RCC_PLLCFGR_DIVP2EN_MASK
#define RCC_PLLCFGR_DIVQ2EN_SHIFT (20ul)
#define RCC_PLLCFGR_DIVQ2EN_MASK (0x1ul << RCC_PLLCFGR_DIVQ2EN_SHIFT)
#define RCC_PLLCFGR_DIVQ2EN RCC_PLLCFGR_DIVQ2EN_MASK
#define RCC_PLLCFGR_DIVR2EN_SHIFT (21ul)
#define RCC_PLLCFGR_DIVR2EN_MASK (0x1ul << RCC_PLLCFGR_DIVR2EN_SHIFT)
#define RCC_PLLCFGR_DIVR2EN RCC_PLLCFGR_DIVR2EN_MASK
#define RCC_PLLCFGR_DIVP3EN_SHIFT (22ul)
#define RCC_PLLCFGR_DIVP3EN_MASK (0x1ul << RCC_PLLCFGR_DIVP3EN_SHIFT)
#define RCC_PLLCFGR_DIVP3EN RCC_PLLCFGR_DIVP3EN_MASK
#define RCC_PLLCFGR_DIVQ3EN_SHIFT (23ul)
#define RCC_PLLCFGR_DIVQ3EN_MASK (0x1ul << RCC_PLLCFGR_DIVQ3EN_SHIFT)
#define RCC_PLLCFGR_DIVQ3EN RCC_PLLCFGR_DIVQ3EN_MASK
#define RCC_PLLCFGR_DIVR3EN_SHIFT (24ul)
#define RCC_PLLCFGR_DIVR3EN_MASK (0x1ul << RCC_PLLCFGR_DIVR3EN_SHIFT)
#define RCC_PLLCFGR_DIVR3EN RCC_PLLCFGR_DIVR3EN_MASK
/* Bit definitions for RCC_PLL1DIVR register */
#define RCC_PLL1DIVR_N1_SHIFT (0ul)
#define RCC_PLL1DIVR_N1(x) (((x) - 1) << RCC_PLL1DIVR_N1_SHIFT) /* Multiplication factor for VCO: 4 - 512 */
#define RCC_PLL1DIVR_P1_SHIFT (9ul)
#define RCC_PLL1DIVR_P1(x) (((x) - 1) << RCC_PLL1DIVR_P1_SHIFT) /* DIVP division factor: 2 - 128, must be even */
#define RCC_PLL1DIVR_Q1_SHIFT (16ul)
#define RCC_PLL1DIVR_Q1(x) (((x) - 1) << RCC_PLL1DIVR_Q1_SHIFT) /* DIVQ division factor: 2 - 128 */
#define RCC_PLL1DIVR_R1_SHIFT (24ul)
#define RCC_PLL1DIVR_R1(x) (((x) - 1) << RCC_PLL1DIVR_R1_SHIFT) /* DIVR division factor: 2 - 128 */
/* Bit definitions for RCC_PLL1FRACR register */
#define RCC_PLL1FRACR_FRACN1_SHIFT (3ul)
#define RCC_PLL1FRACR_FRACN1_MASK (0x1FFFul << RCC_PLL1FRACR_FRACN1_SHIFT)
#define RCC_PLL1FRACR_FRACN1 RCC_PLL1FRACR_FRACN1_MASK
/* Bit definitions for RCC_PLL2DIVR register */
#define RCC_PLL2DIVR_N2_SHIFT (0ul)
#define RCC_PLL2DIVR_N2(x) (((x) - 1) << RCC_PLL2DIVR_N2_SHIFT) /* Multiplication factor for VCO: 4 - 512 */
#define RCC_PLL2DIVR_P2_SHIFT (9ul)
#define RCC_PLL2DIVR_P2(x) (((x) - 1) << RCC_PLL2DIVR_P2_SHIFT) /* DIVP division factor: 2 - 128 */
#define RCC_PLL2DIVR_Q2_SHIFT (16ul)
#define RCC_PLL2DIVR_Q2(x) (((x) - 1) << RCC_PLL2DIVR_Q2_SHIFT) /* DIVQ division factor: 2 - 128 */
#define RCC_PLL2DIVR_R2_SHIFT (24ul)
#define RCC_PLL2DIVR_R2(x) (((x) - 1) << RCC_PLL2DIVR_R2_SHIFT) /* DIVR division factor: 2 - 128 */
/* Bit definitions for RCC_PLL2FRACR register */
#define RCC_PLL2FRACR_FRACN2_SHIFT (3ul)
#define RCC_PLL2FRACR_FRACN2_MASK (0x1FFFul << RCC_PLL2FRACR_FRACN2_SHIFT)
#define RCC_PLL2FRACR_FRACN2 RCC_PLL2FRACR_FRACN2_MASK
/* Bit definitions for RCC_PLL3DIVR register */
#define RCC_PLL3DIVR_N3_SHIFT (0ul)
#define RCC_PLL3DIVR_N3(x) (((x) - 1) << RCC_PLL3DIVR_N3_SHIFT) /* Multiplication factor for VCO: 4 - 512 */
#define RCC_PLL3DIVR_P3_SHIFT (9ul)
#define RCC_PLL3DIVR_P3(x) (((x) - 1) << RCC_PLL3DIVR_P3_SHIFT) /* DIVP division factor: 2 - 128 */
#define RCC_PLL3DIVR_Q3_SHIFT (16ul)
#define RCC_PLL3DIVR_Q3(x) (((x) - 1) << RCC_PLL3DIVR_Q3_SHIFT) /* DIVQ division factor: 2 - 128 */
#define RCC_PLL3DIVR_R3_SHIFT (24ul)
#define RCC_PLL3DIVR_R3(x) (((x) - 1) << RCC_PLL3DIVR_R3_SHIFT) /* DIVR division factor: 2 - 128 */
/* Bit definitions for RCC_PLL3FRACR register */
#define RCC_PLL3FRACR_FRACN3_SHIFT (3ul)
#define RCC_PLL3FRACR_FRACN3_MASK (0x1FFFul << RCC_PLL3FRACR_FRACN3_SHIFT)
#define RCC_PLL3FRACR_FRACN3 RCC_PLL3FRACR_FRACN3_MASK
/* Bit definitions for RCC_D1CCIPR register */
#define RCC_D1CCIPR_FMCSEL_SHIFT (0) /* Bits 0-1: */
#define RCC_D1CCIPR_FMCSEL_MASK (3 << RCC_D1CCIPR_FMCSEL_SHIFT)
# define RCC_D1CCIPR_FMCSEL_HCLK (0 << RCC_D1CCIPR_FMCSEL_SHIFT)
# define RCC_D1CCIPR_FMCSEL_PLL1 (1 << RCC_D1CCIPR_FMCSEL_SHIFT)
# define RCC_D1CCIPR_FMCSEL_PLL2 (2 << RCC_D1CCIPR_FMCSEL_SHIFT)
# define RCC_D1CCIPR_FMCSEL_PER (3 << RCC_D1CCIPR_FMCSEL_SHIFT)
/* Bits 2-3: Reserved */
#define RCC_D1CCIPR_QSPISEL_SHIFT (4) /* Bits 4-5: */
#define RCC_D1CCIPR_QSPISEL_MASK (3 << RCC_D1CCIPR_QSPISEL_SHIFT)
# define RCC_D1CCIPR_QSPISEL_HCLK (0 << RCC_D1CCIPR_QSPISEL_SHIFT)
# define RCC_D1CCIPR_QSPISEL_PLL1 (1 << RCC_D1CCIPR_QSPISEL_SHIFT)
# define RCC_D1CCIPR_QSPISEL_PLL2 (2 << RCC_D1CCIPR_QSPISEL_SHIFT)
# define RCC_D1CCIPR_QSPISEL_PER (3 << RCC_D1CCIPR_QSPISEL_SHIFT)
/* Bits 6-15: Reserved */
#define RCC_D1CCIPR_SDMMC_SHIFT (16) /* Bit 16: */
#define RCC_D1CCIPR_SDMMC_MASK (1 << RCC_D1CCIPR_SDMMC_SHIFT)
# define RCC_D1CCIPR_SDMMC_PLL1 (0 << RCC_D1CCIPR_SDMMC_SHIFT)
# define RCC_D1CCIPR_SDMMC_PLL2 (1 << RCC_D1CCIPR_SDMMC_SHIFT)
/* Bits 17-27: Reserved */
#define RCC_D1CCIPR_CKPERSEL_SHIFT (28) /* Bits 28-29: */
#define RCC_D1CCIPR_CKPERSEL_MASK (3 << RCC_D1CCIPR_CKPERSEL_SHIFT)
# define RCC_D1CCIPR_CKPERSEL_HSI (0 << RCC_D1CCIPR_CKPERSEL_SHIFT)
# define RCC_D1CCIPR_CKPERSEL_CSI (1 << RCC_D1CCIPR_CKPERSEL_SHIFT)
# define RCC_D1CCIPR_CKPERSEL_HSE (2 << RCC_D1CCIPR_CKPERSEL_SHIFT)
/* Bits 30-31: Reserved */
/* Bit definitions for RCC_D2CCIP1R register */
#define RCC_D2CCIP1R_SAI1SEL_SHIFT (0) /* Bits 0-2 */
#define RCC_D2CCIP1R_SAI1SEL_MASK (7 << RCC_D2CCIP1R_SAI1SEL_MASK)
# define RCC_D2CCIP1R_SAI1SEL_PLL1 (0 << RCC_D2CCIP1R_SAI1SEL_SHIFT)
# define RCC_D2CCIP1R_SAI1SEL_PLL2 (1 << RCC_D2CCIP1R_SAI1SEL_SHIFT)
# define RCC_D2CCIP1R_SAI1SEL_PLL3 (2 << RCC_D2CCIP1R_SAI1SEL_SHIFT)
# define RCC_D2CCIP1R_SAI1SEL_I2SCKIN (3 << RCC_D2CCIP1R_SAI1SEL_SHIFT)
# define RCC_D2CCIP1R_SAI1SEL_PER (4 << RCC_D2CCIP1R_SAI1SEL_SHIFT)
/* Bits 3-5: Reserved */
#define RCC_D2CCIP1R_SAI23SEL_SHIFT (6) /* Bits 6-8 */
#define RCC_D2CCIP1R_SAI23SEL_MASK (7 << RCC_D2CCIP1R_SAI23SEL_SHIFT)
# define RCC_D2CCIP1R_SAI23SEL_PLL1 (0 << RCC_D2CCIP1R_SAI23SEL_SHIFT)
# define RCC_D2CCIP1R_SAI23SEL_PLL2 (1 << RCC_D2CCIP1R_SAI23SEL_SHIFT)
# define RCC_D2CCIP1R_SAI23SEL_PLL3 (2 << RCC_D2CCIP1R_SAI23SEL_SHIFT)
# define RCC_D2CCIP1R_SAI23SEL_I2SCKIN (3 << RCC_D2CCIP1R_SAI23SEL_SHIFT)
# define RCC_D2CCIP1R_SAI23SEL_PER (4 << RCC_D2CCIP1R_SAI23SEL_SHIFT)
/* Bits 9-11: Reserved */
#define RCC_D2CCIP1R_SPI123SEL_SHIFT (12) /* Bits 12-14 */
#define RCC_D2CCIP1R_SPI123SEL_MASK (7 << RCC_D2CCIP1R_SPI123SEL_SHIFT)
# define RCC_D2CCIP1R_SPI123SEL_PLL1 (0 << RCC_D2CCIP1R_SPI123SEL_SHIFT)
# define RCC_D2CCIP1R_SPI123SEL_PLL2 (1 << RCC_D2CCIP1R_SPI123SEL_SHIFT)
# define RCC_D2CCIP1R_SPI123SEL_PLL3 (2 << RCC_D2CCIP1R_SPI123SEL_SHIFT)
# define RCC_D2CCIP1R_SPI123SEL_I2SCKIN (3 << RCC_D2CCIP1R_SPI123SEL_SHIFT)
# define RCC_D2CCIP1R_SPI123SEL_PER (4 << RCC_D2CCIP1R_SPI123SEL_SHIFT)
/* Bit 15: Reserved */
#define RCC_D2CCIP1R_SPI45SEL_SHIFT (16) /* Bits 16-18 */
#define RCC_D2CCIP1R_SPI45SEL_MASK (7 << RCC_D2CCIP1R_SPI45SEL_SHIFT)
# define RCC_D2CCIP1R_SPI45SEL_APB (0 << RCC_D2CCIP1R_SPI45SEL_SHIFT)
# define RCC_D2CCIP1R_SPI45SEL_PLL2 (1 << RCC_D2CCIP1R_SPI45SEL_SHIFT)
# define RCC_D2CCIP1R_SPI45SEL_PLL3 (2 << RCC_D2CCIP1R_SPI45SEL_SHIFT)
# define RCC_D2CCIP1R_SPI45SEL_HSI (3 << RCC_D2CCIP1R_SPI45SEL_SHIFT)
# define RCC_D2CCIP1R_SPI45SEL_CSI (4 << RCC_D2CCIP1R_SPI45SEL_SHIFT)
# define RCC_D2CCIP1R_SPI45SEL_HSE (5 << RCC_D2CCIP1R_SPI45SEL_SHIFT)
/* Bit 19: Reserved */
#define RCC_D2CCIP1R_SPDIFSEL_SHIFT (20) /* Bits 20-21 */
#define RCC_D2CCIP1R_SPDIFSEL_MASK (3 << RCC_D2CCIP1R_SPDIFSEL_SHIFT)
# define RCC_D2CCIP1R_SPDIFSEL_PLL1 (0 << RCC_D2CCIP1R_SPDIFSEL_SHIFT)
# define RCC_D2CCIP1R_SPDIFSEL_PLL2 (1 << RCC_D2CCIP1R_SPDIFSEL_SHIFT)
# define RCC_D2CCIP1R_SPDIFSEL_PLL3 (2 << RCC_D2CCIP1R_SPDIFSEL_SHIFT)
# define RCC_D2CCIP1R_SPDIFSEL_HSI (3 << RCC_D2CCIP1R_SPDIFSEL_SHIFT)
/* Bits 22-23: Reserved */
#define RCC_D2CCIP1R_DFSDM1SEL_SHIFT (24) /* Bit 24 */
#define RCC_D2CCIP1R_DFSDM1SEL_MASK (1 << RCC_D2CCIP1R_DFSDM1SEL_SHIFT)
# define RCC_D2CCIP1R_DFSDM1SEL_PCLK2 (0 << RCC_D2CCIP1R_DFSDM1SEL_SHIFT)
# define RCC_D2CCIP1R_DFSDM1SEL_SYSCLK (1 << RCC_D2CCIP1R_DFSDM1SEL_SHIFT)
/* Bits 25-27: Reserved */
#define RCC_D2CCIP1R_FDCANSEL_SHIFT (28) /* Bits 28-29 */
#define RCC_D2CCIP1R_FDCANSEL_MASK (3 << RCC_D2CCIP1R_FDCANSEL_SHIFT)
# define RCC_D2CCIP1R_FDCANSEL_HSE (0 << RCC_D2CCIP1R_FDCANSEL_SHIFT)
# define RCC_D2CCIP1R_FDCANSEL_PLL1 (1 << RCC_D2CCIP1R_FDCANSEL_SHIFT)
# define RCC_D2CCIP1R_FDCANSEL_PLL2 (2 << RCC_D2CCIP1R_FDCANSEL_SHIFT)
/* Bit 30: Reserved */
#define RCC_D2CCIP1R_SWPSEL_SHIFT (31) /* Bit 31 */
#define RCC_D2CCIP1R_SWPSEL_MASK (1 << RCC_D2CCIP1R_SWPSEL_SHIFT)
# define RCC_D2CCIP1R_SWPSEL_PCLK (0 << RCC_D2CCIP1R_SWPSEL_SHIFT)
# define RCC_D2CCIP1R_SWPSEL_HSI (1 << RCC_D2CCIP1R_SWPSEL_SHIFT)
/* Bit definitions for RCC_D2CCIP2R register */
#define RCC_D2CCIP2R_USART234578SEL_SHIFT (0) /* Bits 0-2 */
# define RCC_D2CCIP2R_USART234578SEL_MASK (7 << RCC_D2CCIP2R_USART234578SEL_SHIFT)
#define RCC_D2CCIP2R_USART16SEL_SHIFT (3) /* Bits 3-5 */
# define RCC_D2CCIP2R_USART16SEL_MASK (7 << RCC_D2CCIP2R_USART16SEL_SHIFT)
/* Bits 6-7: Reserved */
#define RCC_D2CCIP2R_RNGSEL_SHIFT (8) /* Bits 8-9 */
# define RCC_D2CCIP2R_RNGSEL_MASK (3 << RCC_D2CCIP2R_RNGSEL_SHIFT)
/* Bits 10-11: Reserved */
#define RCC_D2CCIP2R_I2C123SEL_SHIFT (12) /* Bits 12-13 */
#define RCC_D2CCIP2R_I2C123SEL_MASK (3 << RCC_D2CCIP2R_I2C123SEL_SHIFT)
# define RCC_D2CCIP2R_I2C123SEL_PCLK1 (0 << RCC_D2CCIP2R_I2C123SEL_SHIFT)
# define RCC_D2CCIP2R_I2C123SEL_PLL3 (1 << RCC_D2CCIP2R_I2C123SEL_SHIFT)
# define RCC_D2CCIP2R_I2C123SEL_HSI (2 << RCC_D2CCIP2R_I2C123SEL_SHIFT)
# define RCC_D2CCIP2R_I2C123SEL_CSI (3 << RCC_D2CCIP2R_I2C123SEL_SHIFT)
/* Bits 14-19: Reserved */
#define RCC_D2CCIP2R_USBSEL_SHIFT (20) /* Bits 20-21 */
# define RCC_D2CCIP2R_USBSEL_MASK (3 << RCC_D2CCIP2R_USBSEL_SHIFT)
# define RCC_D2CCIP2R_USBSEL_DISABLE (0 << RCC_D2CCIP2R_USBSEL_SHIFT)
# define RCC_D2CCIP2R_USBSEL_PLL1 (1 << RCC_D2CCIP2R_USBSEL_SHIFT)
# define RCC_D2CCIP2R_USBSEL_PLL3 (2 << RCC_D2CCIP2R_USBSEL_SHIFT)
# define RCC_D2CCIP2R_USBSEL_HSI48 (3 << RCC_D2CCIP2R_USBSEL_SHIFT)
#define RCC_D2CCIP2R_CECSEL_SHIFT (22) /* Bits 22-23 */
# define RCC_D2CCIP2R_CECSEL_MASK (3 << RCC_D2CCIP2R_CECSEL_SHIFT)
/* Bits 24-27: Reserved */
#define RCC_D2CCIP2R_LPTIM1SEL_SHIFT (28) /* Bits 28-30 */
# define RCC_D2CCIP2R_LPTIM1SEL_MASK (3 << RCC_D2CCIP2R_LPTIM1SEL_SHIFT)
/* Bit 31: Reserved */
/* Bit definitions for RCC_D3CCIPR register */
#define RCC_D3CCIPR_LPUART1SEL_SHIFT (0) /* Bits 0-2: LPUART1 kernel clock source selection */
#define RCC_D3CCIPR_LPUART1SEL_MASK (7 << RCC_D3CCIPR_LPUART1SEL_SHIFT)
# define RCC_D3CCIPR_LPUART1SEL_PCLK (0 << RCC_D3CCIPR_LPUART1SEL_SHIFT)
# define RCC_D3CCIPR_LPUART1SEL_PLL2 (1 << RCC_D3CCIPR_LPUART1SEL_SHIFT)
# define RCC_D3CCIPR_LPUART1SEL_PLL3 (2 << RCC_D3CCIPR_LPUART1SEL_SHIFT)
# define RCC_D3CCIPR_LPUART1SEL_HSI (3 << RCC_D3CCIPR_LPUART1SEL_SHIFT)
# define RCC_D3CCIPR_LPUART1SEL_CSI (4 << RCC_D3CCIPR_LPUART1SEL_SHIFT)
# define RCC_D3CCIPR_LPUART1SEL_LSE (5 << RCC_D3CCIPR_LPUART1SEL_SHIFT)
/* Bits 3-7: Reserved */
#define RCC_D3CCIPR_I2C4SEL_SHIFT (8) /* Bits 8-9: I2C4 kernel clock source selection */
#define RCC_D3CCIPR_I2C4SEL_MASK (3 << RCC_D3CCIPR_I2C4SEL_SHIFT)
# define RCC_D3CCIPR_I2C4SEL_PCLK4 (0 << RCC_D3CCIPR_I2C4SEL_SHIFT)
# define RCC_D3CCIPR_I2C4SEL_PLL3 (1 << RCC_D3CCIPR_I2C4SEL_SHIFT)
# define RCC_D3CCIPR_I2C4SEL_HSI (2 << RCC_D3CCIPR_I2C4SEL_SHIFT)
# define RCC_D3CCIPR_I2C4SEL_CSI (3 << RCC_D3CCIPR_I2C4SEL_SHIFT)
#define RCC_D3CCIPR_LPTIM2SEL_SHIFT (10) /* Bits 10-12: LPTIM2 kernel clock source selection */
#define RCC_D3CCIPR_LPTIM2SEL_MASK (7 << RCC_D3CCIPR_LPTIM2SEL_SHIFT)
# define RCC_D3CCIPR_LPTIM2SEL_PCLK4 (0 << RCC_D3CCIPR_LPTIM2SEL_SHIFT)
# define RCC_D3CCIPR_LPTIM2SEL_PLL2 (1 << RCC_D3CCIPR_LPTIM2SEL_SHIFT)
# define RCC_D3CCIPR_LPTIM2SEL_PLL3 (2 << RCC_D3CCIPR_LPTIM2SEL_SHIFT)
# define RCC_D3CCIPR_LPTIM2SEL_LSE (3 << RCC_D3CCIPR_LPTIM2SEL_SHIFT)
# define RCC_D3CCIPR_LPTIM2SEL_LSI (4 << RCC_D3CCIPR_LPTIM2SEL_SHIFT)
# define RCC_D3CCIPR_LPTIM2SEL_PER (5 << RCC_D3CCIPR_LPTIM2SEL_SHIFT)
#define RCC_D3CCIPR_LPTIM345SEL_SHIFT (13) /* Bits 13-15: LPTIM3,4,5 kernel clock source selection */
#define RCC_D3CCIPR_LPTIM345SEL_MASK (7 << RCC_D3CCIPR_LPTIM345SEL_SHIFT)
# define RCC_D3CCIPR_LPTIM345SEL_PCLK4 (0 << RCC_D3CCIPR_LPTIM345SEL_SHIFT)
# define RCC_D3CCIPR_LPTIM345SEL_PLL2 (1 << RCC_D3CCIPR_LPTIM345SEL_SHIFT)
# define RCC_D3CCIPR_LPTIM345SEL_PLL3 (2 << RCC_D3CCIPR_LPTIM345SEL_SHIFT)
# define RCC_D3CCIPR_LPTIM345SEL_LSE (3 << RCC_D3CCIPR_LPTIM345SEL_SHIFT)
# define RCC_D3CCIPR_LPTIM345SEL_LSI (4 << RCC_D3CCIPR_LPTIM345SEL_SHIFT)
# define RCC_D3CCIPR_LPTIM345SEL_PER (5 << RCC_D3CCIPR_LPTIM345SEL_SHIFT)
#define RCC_D3CCIPR_ADCSEL_SHIFT (16) /* Bits 16-17: SAR ADC kernel clock source selection */
#define RCC_D3CCIPR_ADCSEL_MASK (3 << RCC_D3CCIPR_ADCSEL_SHIFT)
# define RCC_D3CCIPR_ADCSEL_PLL2 (0 << RCC_D3CCIPR_ADCSEL_SHIFT)
# define RCC_D3CCIPR_ADCSEL_PLL3 (1 << RCC_D3CCIPR_ADCSEL_SHIFT)
# define RCC_D3CCIPR_ADCSEL_PER (2 << RCC_D3CCIPR_ADCSEL_SHIFT)
/* Bits 18-20: Reserved */
#define RCC_D3CCIPR_SAI4ASEL_SHIFT (21) /* Bits 21-23: Sub-Block A of SAI4 kernel clock source selection */
#define RCC_D3CCIPR_SAI4ASEL_MASK (7 << RCC_D3CCIPR_SAI4ASEL_SHIFT)
# define RCC_D3CCIPR_SAI4ASEL_PLL1 (0 << RCC_D3CCIPR_SAI4ASEL_SHIFT)
# define RCC_D3CCIPR_SAI4ASEL_PLL2 (1 << RCC_D3CCIPR_SAI4ASEL_SHIFT)
# define RCC_D3CCIPR_SAI4ASEL_PLL3 (2 << RCC_D3CCIPR_SAI4ASEL_SHIFT)
# define RCC_D3CCIPR_SAI4ASEL_I2CCKIN (3 << RCC_D3CCIPR_SAI4ASEL_SHIFT)
# define RCC_D3CCIPR_SAI4ASEL_PER (4 << RCC_D3CCIPR_SAI4ASEL_SHIFT)
#define RCC_D3CCIPR_SAI4BSEL_SHIFT (24) /* Bits 24-26: Sub-Block B of SAI4 kernel clock source selection */
#define RCC_D3CCIPR_SAI4BSEL_MASK (7 << RCC_D3CCIPR_SAI4BSEL_SHIFT)
# define RCC_D3CCIPR_SAI4BSEL_PLL1 (0 << RCC_D3CCIPR_SAI4BSEL_SHIFT)
# define RCC_D3CCIPR_SAI4BSEL_PLL2 (1 << RCC_D3CCIPR_SAI4BSEL_SHIFT)
# define RCC_D3CCIPR_SAI4BSEL_PLL3 (2 << RCC_D3CCIPR_SAI4BSEL_SHIFT)
# define RCC_D3CCIPR_SAI4BSEL_I2CCKIN (3 << RCC_D3CCIPR_SAI4BSEL_SHIFT)
# define RCC_D3CCIPR_SAI4BSEL_PER (4 << RCC_D3CCIPR_SAI4BSEL_SHIFT)
#define RCC_D3CCIPR_SPI6SEL_SHIFT (28) /* Bits 28-30: SPI6 kernel clock source selection */
#define RCC_D3CCIPR_SPI6SEL_MASK (7 << RCC_D3CCIPR_SPI6SEL_SHIFT)
# define RCC_D3CCIPR_SPI6SEL_PCLK4 (0 << RCC_D3CCIPR_SPI6SEL_SHIFT)
# define RCC_D3CCIPR_SPI6SEL_PLL2 (1 << RCC_D3CCIPR_SPI6SEL_SHIFT)
# define RCC_D3CCIPR_SPI6SEL_PLL3 (2 << RCC_D3CCIPR_SPI6SEL_SHIFT)
# define RCC_D3CCIPR_SPI6SEL_HSI (3 << RCC_D3CCIPR_SPI6SEL_SHIFT)
# define RCC_D3CCIPR_SPI6SEL_CSI (4 << RCC_D3CCIPR_SPI6SEL_SHIFT)
# define RCC_D3CCIPR_SPI6SEL_HSE (5 << RCC_D3CCIPR_SPI6SEL_SHIFT)
/* Bit 31: Reserved */
/* TODO: CIER */
/* TODO: CIFR */
/* TODO: CICR */
/* TODO: BDCR */
/* Bit definitions for RCC_CSR register */
#define RCC_CSR_LSION (1 << 0) /* RCC CSR: LSION */
#define RCC_CSR_LSIRDY (1 << 1) /* RCC CSR: LSIRDY */
/* AHB3 peripheral reset register */
#define RCC_AHB3RSTR_MDMARST (1 << 0) /* RCC AHB3RSTR: MDMARST */
#define RCC_AHB3RSTR_DMA2DRST (1 << 4) /* RCC AHB3RSTR: DMA2DRST */
#define RCC_AHB3RSTR_JPGDECRST (1 << 5) /* RCC AHB3RSTR: JPGDECRST */
#define RCC_AHB3RSTR_FMCRST (1 << 12) /* RCC AHB3RSTR: FMCRST */
#define RCC_AHB3RSTR_QSPIRST (1 << 14) /* RCC AHB3RSTR: QSPIRST */
#define RCC_AHB3RSTR_SDMMC1RST (1 << 16) /* RCC AHB3RSTR: SDMMC1RST */
#define RCC_AHB3RSTR_CPURST (1 << 31) /* RCC AHB3RSTR: CPURST */
/* AHB1 peripheral reset register */
#define RCC_AHB1RSTR_DMA1RST (1 << 0) /* RCC AHB1RSTR: DMA1RST */
#define RCC_AHB1RSTR_DMA2RST (1 << 1) /* RCC AHB1RSTR: DMA2RST */
#define RCC_AHB1RSTR_ADC12RST (1 << 5) /* RCC AHB1RSTR: ADC12RST */
/* Bits 6-14: Reserved */
#define RCC_AHB1RSTR_ETH1MACRST (1 << 15) /* RCC AHB1RSTR: ETH1MACRST */
/* Bits 16-24: Reserved */
#define RCC_AHB1RSTR_OTGHSRST (1 << 25) /* RCC AHB1RSTR: OTGHSRST */
/* Bit 26: Reserved */
#define RCC_AHB1RSTR_OTGFSRST (1 << 27) /* RCC AHB1RSTR: OTGFSRST */
/* Bits 28-31: Reserved */
/* AHB2 peripheral reset register */
#define RCC_AHB2RSTR_CAMITFRST (1 << 0) /* RCC AHB2RSTR: CAMITFRST */
/* Bits 1-3: Reserved */
#define RCC_AHB2RSTR_CRYPTRST (1 << 4) /* RCC AHB2RSTR: CRYPTRST */
#define RCC_AHB2RSTR_HASHRST (1 << 5) /* RCC AHB2RSTR: HASHRST */
#define RCC_AHB2RSTR_RNGRST (1 << 6) /* RCC AHB2RSTR: RNGRST */
/* Bits 7-8: Reserved */
#define RCC_AHB2RSTR_SDMMC2RST (1 << 9) /* RCC AHB2RSTR: SDMMC2RST */
/* Bits 10-31: Reserved */
/* AHB4 peripheral reset register */
#define RCC_AHB4RSTR_GPIOARST (1 << 0) /* RCC AHB4RSTR: GPIOARST */
#define RCC_AHB4RSTR_GPIOBRST (1 << 1) /* RCC AHB4RSTR: GPIOBRST */
#define RCC_AHB4RSTR_GPIOCRST (1 << 2) /* RCC AHB4RSTR: GPIOCRST */
#define RCC_AHB4RSTR_GPIODRST (1 << 3) /* RCC AHB4RSTR: GPIODRST */
#define RCC_AHB4RSTR_GPIOERST (1 << 4) /* RCC AHB4RSTR: GPIOERST */
#define RCC_AHB4RSTR_GPIOFRST (1 << 5) /* RCC AHB4RSTR: GPIOFRST */
#define RCC_AHB4RSTR_GPIOGRST (1 << 6) /* RCC AHB4RSTR: GPIOGRST */
#define RCC_AHB4RSTR_GPIOHRST (1 << 7) /* RCC AHB4RSTR: GPIOHRST */
#define RCC_AHB4RSTR_GPIOIRST (1 << 8) /* RCC AHB4RSTR: GPIOIRST */
#define RCC_AHB4RSTR_GPIOJRST (1 << 9) /* RCC AHB4RSTR: GPIOJRST */
#define RCC_AHB4RSTR_GPIOKRST (1 << 10) /* RCC AHB4RSTR: GPIOKRST */
/* Bits 11-18: Reserved */
#define RCC_AHB4RSTR_CRCRST (1 << 19) /* RCC AHB4RSTR: CRCRST */
/* Bit 20: Reserved */
#define RCC_AHB4RSTR_BDMARST (1 << 21) /* RCC AHB4RSTR: BDMARST */
/* Bits 22-23: Reserved */
#define RCC_AHB4RSTR_ADC3RST (1 << 24) /* RCC AHB4RSTR: ADC3RST */
#define RCC_AHB4RSTR_HSEMRST (1 << 25) /* RCC AHB4RSTR: HSEMRST */
/* Bits 26-31: Reserved */
/* APB3 peripheral reset register */
/* Bits 0-2: Reserved */
#define RCC_APB3RSTR_LTDCRST (1 << 3) /* RCC APB3RSTR: LTDCRST */
/* Bits 4-31: Reserved */
/* APB3 L peripheral reset register */
#define RCC_APB1LRSTR_TIM2RST (1 << 0) /* RCC APB1LRSTR: TIM2RST */
#define RCC_APB1LRSTR_TIM3RST (1 << 1) /* RCC APB1LRSTR: TIM3RST */
#define RCC_APB1LRSTR_TIM4RST (1 << 2) /* RCC APB1LRSTR: TIM4RST */
#define RCC_APB1LRSTR_TIM5RST (1 << 3) /* RCC APB1LRSTR: TIM5RST */
#define RCC_APB1LRSTR_TIM6RST (1 << 4) /* RCC APB1LRSTR: TIM6RST */
#define RCC_APB1LRSTR_TIM7RST (1 << 5) /* RCC APB1LRSTR: TIM7RST */
#define RCC_APB1LRSTR_TIM12RST (1 << 6) /* RCC APB1LRSTR: TIM12RST */
#define RCC_APB1LRSTR_TIM13RST (1 << 7) /* RCC APB1LRSTR: TIM13RST */
#define RCC_APB1LRSTR_TIM14RST (1 << 8) /* RCC APB1LRSTR: TIM14RST */
#define RCC_APB1LRSTR_LPTIM1RST (1 << 9) /* RCC APB1LRSTR: LPTIM1RST */
/* Bits 10-13: Reserved */
#define RCC_APB1LRSTR_SPI2RST (1 << 14) /* RCC APB1LRSTR: SPI2RST */
#define RCC_APB1LRSTR_SPI3RST (1 << 15) /* RCC APB1LRSTR: SPI3RST */
#define RCC_APB1LRSTR_SPDIFRXRST (1 << 16) /* RCC APB1LRSTR: SPDIFRXRST */
#define RCC_APB1LRSTR_USART2RST (1 << 17) /* RCC APB1LRSTR: USART2RST */
#define RCC_APB1LRSTR_USART3RST (1 << 18) /* RCC APB1LRSTR: USART3RST */
#define RCC_APB1LRSTR_UART4RST (1 << 19) /* RCC APB1LRSTR: UART4RST */
#define RCC_APB1LRSTR_UART5RST (1 << 20) /* RCC APB1LRSTR: UART5RST */
#define RCC_APB1LRSTR_I2C1RST (1 << 21) /* RCC APB1LRSTR: I2C1RST */
#define RCC_APB1LRSTR_I2C2RST (1 << 22) /* RCC APB1LRSTR: I2C2RST */
#define RCC_APB1LRSTR_I2C3RST (1 << 23) /* RCC APB1LRSTR: I2C3RST */
/* Bits 24-26: Reserved */
#define RCC_APB1LRSTR_HDMICECRST (1 << 27) /* RCC APB1LRSTR: HDMICECRST */
/* Bit 28: Reserved */
#define RCC_APB1LRSTR_DAC1RST (1 << 29) /* RCC APB1LRSTR: DAC1RST */
#define RCC_APB1LRSTR_UART7RST (1 << 30) /* RCC APB1LRSTR: UART7RST */
#define RCC_APB1LRSTR_UART8RST (1 << 31) /* RCC APB1LRSTR: UART8RST */
/* APB1 H peripheral reset register */
/* Bit 0: Reserved */
#define RCC_APB1HRSTR_CRSRST (1 << 1) /* RCC APB1HRSTR: CRSRST */
#define RCC_APB1HRSTR_SWPRST (1 << 2) /* RCC APB1HRSTR: SWPRST */
/* Bit 3: Reserved */
#define RCC_APB1HRSTR_OPAMPRST (1 << 4) /* RCC APB1HRSTR: OPAMPRST*/
#define RCC_APB1HRSTR_MDIOSRST (1 << 5) /* RCC APB1HRSTR: MDIOSRST */
/* Bits 6-7: Reserved */
#define RCC_APB1HRSTR_FDCANRST (1 << 8) /* RCC APB1HRSTR: FDCANRST*/
/* Bits 9-31: Reserved */
/* APB2 peripheral reset register */
#define RCC_APB2RSTR_TIM1RST (1 << 0) /* RCC APB2RSTR: TIM1RST */
#define RCC_APB2RSTR_TIM8RST (1 << 1) /* RCC APB2RSTR: TIM8RST */
#define RCC_APB2RSTR_USART1RST (1 << 4) /* RCC APB2RSTR: USART1RST */
#define RCC_APB2RSTR_USART6RST (1 << 5) /* RCC APB2RSTR: USART6RST */
#define RCC_APB2RSTR_SPI1RST (1 << 12) /* RCC APB2RSTR: SPI1RST */
#define RCC_APB2RSTR_SPI4RST (1 << 13) /* RCC APB2RSTR: SPI4RST */
#define RCC_APB2RSTR_TIM15RST (1 << 16) /* RCC APB2RSTR: TIM15RST */
#define RCC_APB2RSTR_TIM16RST (1 << 17) /* RCC APB2RSTR: TIM16RST */
#define RCC_APB2RSTR_TIM17RST (1 << 18) /* RCC APB2RSTR: TIM17RST */
#define RCC_APB2RSTR_SPI5RST (1 << 20) /* RCC APB2RSTR: SPI5RST */
#define RCC_APB2RSTR_SAI1RST (1 << 22) /* RCC APB2RSTR: SAI1RST */
#define RCC_APB2RSTR_SAI2RST (1 << 23) /* RCC APB2RSTR: SAI2RST */
#define RCC_APB2RSTR_SAI3RST (1 << 24) /* RCC APB2RSTR: SAI3RST */
#define RCC_APB2RSTR_DFSDM1RST (1 << 28) /* RCC APB2RSTR: DFSDM1RST */
#define RCC_APB2RSTR_HRTIMRST (1 << 29) /* RCC APB2RSTR: HRTIMRST */
/* APB4 peripheral reset register */
#define RCC_APB4RSTR_SYSCFGRST (1 << 1) /* RCC APB4RSTR: SYSCFGRST */
#define RCC_APB4RSTR_LPUART1RST (1 << 3) /* RCC APB4RSTR: LPUART1RST */
#define RCC_APB4RSTR_SPI6RST (1 << 5) /* RCC APB4RSTR: SPI6RST */
#define RCC_APB4RSTR_I2C4RST (1 << 7) /* RCC APB4RSTR: I2C4RST */
#define RCC_APB4RSTR_LPTIM2RST (1 << 9) /* RCC APB4RSTR: LPTIM2RST */
#define RCC_APB4RSTR_LPTIM3RST (1 << 10) /* RCC APB4RSTR: LPTIM3RST */
#define RCC_APB4RSTR_LPTIM4RST (1 << 11) /* RCC APB4RSTR: LPTIM4RST */
#define RCC_APB4RSTR_LPTIM5RST (1 << 12) /* RCC APB4RSTR: LPTIM5RST */
#define RCC_APB4RSTR_COMP12RST (1 << 14) /* RCC APB4RSTR: COMP12RST */
#define RCC_APB4RSTR_VREFRST (1 << 15) /* RCC APB4RSTR: VREFRST */
#define RCC_APB4RSTR_SAI4RST (1 << 21) /* RCC APB4RSTR: SAI4RST */
/* RCC Global Control register */
#define RCC_GCR_WW1RSC (1 << 0) /* Bit 0: WWDG1 reset scope control */
/* TODO: D3 Autonomous mode register */
/* RCC Reset Status register */
/* Bits 0-15: Reserved */
#define RCC_RSR_RMVF (1 << 16) /* Bit 16: Remove reset flag */
#define RCC_RSR_CPURSTF (1 << 17) /* Bit 17: CPU reset flag */
/* Bit 18: Reserved */
#define RCC_RSR_D1RSTF (1 << 19) /* Bit 19: D1 domain power switch reset flag */
#define RCC_RSR_D2RSTF (1 << 20) /* Bit 20: D2 domain power switch reset flag */
#define RCC_RSR_BORRSTF (1 << 21) /* Bit 21: BOR reset flag */
#define RCC_RSR_PINRSTF (1 << 22) /* Bit 22: Pin reset flag */
#define RCC_RSR_PORRSTF (1 << 23) /* Bit 23: POR/PDR reset flag */
#define RCC_RSR_SFTRSTF (1 << 24) /* Bit 24: System reset from CPU flag */
/* Bit 25: Reserved */
#define RCC_RSR_IWDG1RSTF (1 << 26) /* Bit 26: Independent watchdog reset flag */
/* Bit 27: Reserved */
#define RCC_RSR_WWDG1RSTF (1 << 28) /* Bit 28: Window watchdog reset flag */
/* Bit 29: Reserved */
#define RCC_RSR_LPWRRSTF (1 << 30) /* Bit 30: Reset due to illegal D1 DStandby or CPU Cstop flag */
/* Bit 31: Reserved */
/* AHB3 Peripheral Clock enable register */
#define RCC_AHB3ENR_MDMAEN (1 << 0) /* RCC AHB3ENR: MDMAEN */
#define RCC_AHB3ENR_DMA2DEN (1 << 4) /* RCC AHB3ENR: DMA2DEN */
#define RCC_AHB3ENR_JPGDECEN (1 << 5) /* RCC AHB3ENR: JPGDECEN */
#define RCC_AHB3ENR_FMCEN (1 << 12) /* RCC AHB3ENR: FMCEN */
#define RCC_AHB3ENR_QSPIEN (1 << 14) /* RCC AHB3ENR: QSPIEN */
#define RCC_AHB3ENR_SDMMC1EN (1 << 16) /* RCC AHB3ENR: SDMMC1EN */
/* AHB1 Peripheral Clock enable register */
#define RCC_AHB1ENR_DMA1EN (1 << 0) /* RCC AHB1ENR: DMA1EN */
#define RCC_AHB1ENR_DMA2EN (1 << 1) /* RCC AHB1ENR: DMA2EN */
#define RCC_AHB1ENR_ADC12EN (1 << 5) /* RCC AHB1ENR: ADC12EN */
#define RCC_AHB1ENR_ETH1MACEN (1 << 15) /* RCC AHB1ENR: ETH1MACEN */
#define RCC_AHB1ENR_ETH1TXEN (1 << 16) /* RCC AHB1ENR: ETH1TXEN */
#define RCC_AHB1ENR_ETH1RXEN (1 << 17) /* RCC AHB1ENR: ETH1RXEN */
#define RCC_AHB1ENR_OTGHSEN (1 << 25) /* RCC AHB1ENR: OTGHSEN */
#define RCC_AHB1ENR_OTGHSULPIEN (1 << 26) /* RCC AHB1ENR: OTGHSULPIEN */
#define RCC_AHB1ENR_OTGFSEN (1 << 27) /* RCC AHB1ENR: OTGFSEN */
/* AHB2 Peripheral Clock enable register */
#define RCC_AHB2ENR_CAMITFEN (1 << 0) /* RCC AHB2ENR: CAMITFEN */
#define RCC_AHB2ENR_CRYPTEN (1 << 4) /* RCC AHB2ENR: CRYPTEN */
#define RCC_AHB2ENR_HASHEN (1 << 5) /* RCC AHB2ENR: HASHEN */
#define RCC_AHB2ENR_RNGEN (1 << 6) /* RCC AHB2ENR: RNGEN */
#define RCC_AHB2ENR_SDMMC2EN (1 << 9) /* RCC AHB2ENR: SDMMC2EN */
#define RCC_AHB2ENR_SRAM1EN (1 << 29) /* RCC AHB2ENR: SRAM1EN */
#define RCC_AHB2ENR_SRAM2EN (1 << 30) /* RCC AHB2ENR: SRAM2EN */
#define RCC_AHB2ENR_SRAM3EN (1 << 31) /* RCC AHB2ENR: SRAM3EN */
/* AHB4 Peripheral Clock enable register */
#define RCC_AHB4ENR_GPIOAEN (1 << 0) /* RCC AHB4ENR: GPIOAEN */
#define RCC_AHB4ENR_GPIOBEN (1 << 1) /* RCC AHB4ENR: GPIOBEN */
#define RCC_AHB4ENR_GPIOCEN (1 << 2) /* RCC AHB4ENR: GPIOCEN */
#define RCC_AHB4ENR_GPIODEN (1 << 3) /* RCC AHB4ENR: GPIODEN */
#define RCC_AHB4ENR_GPIOEEN (1 << 4) /* RCC AHB4ENR: GPIOEEN */
#define RCC_AHB4ENR_GPIOFEN (1 << 5) /* RCC AHB4ENR: GPIOFEN */
#define RCC_AHB4ENR_GPIOGEN (1 << 6) /* RCC AHB4ENR: GPIOGEN */
#define RCC_AHB4ENR_GPIOHEN (1 << 7) /* RCC AHB4ENR: GPIOHEN */
#define RCC_AHB4ENR_GPIOIEN (1 << 8) /* RCC AHB4ENR: GPIOIEN */
#define RCC_AHB4ENR_GPIOJEN (1 << 9) /* RCC AHB4ENR: GPIOJEN */
#define RCC_AHB4ENR_GPIOKEN (1 << 10) /* RCC AHB4ENR: GPIOKEN */
#define RCC_AHB4ENR_CRCEN (1 << 19) /* RCC AHB4ENR: CRCEN */
#define RCC_AHB4ENR_BDMAEN (1 << 21) /* RCC AHB4ENR: BDMAEN and DMAMUX2 */
#define RCC_AHB4ENR_ADC3EN (1 << 24) /* RCC AHB4ENR: ADC3EN */
#define RCC_AHB4ENR_HSEMEN (1 << 25) /* RCC AHB4ENR: HSEMEN */
#define RCC_AHB4ENR_BKPSRAMEN (1 << 28) /* RCC AHB4ENR: BKPRAMEN */
/* APB3 Peripheral Clock enable register */
#define RCC_APB3ENR_LTDCEN (1 << 3) /* RCC APB3ENR: LTDCEN */
#define RCC_APB3ENR_WWDG1EN (1 << 6) /* RCC APB3ENR: WWDG1EN */
/* APB1 L Peripheral Clock enable register */
#define RCC_APB1LENR_TIM2EN (1 << 0) /* RCC APB1LENR: TIM2EN */
#define RCC_APB1LENR_TIM3EN (1 << 1) /* RCC APB1LENR: TIM3EN */
#define RCC_APB1LENR_TIM4EN (1 << 2) /* RCC APB1LENR: TIM4EN */
#define RCC_APB1LENR_TIM5EN (1 << 3) /* RCC APB1LENR: TIM5EN */
#define RCC_APB1LENR_TIM6EN (1 << 4) /* RCC APB1LENR: TIM6EN */
#define RCC_APB1LENR_TIM7EN (1 << 5) /* RCC APB1LENR: TIM7EN */
#define RCC_APB1LENR_TIM12EN (1 << 6) /* RCC APB1LENR: TIM12EN */
#define RCC_APB1LENR_TIM13EN (1 << 7) /* RCC APB1LENR: TIM13EN */
#define RCC_APB1LENR_TIM14EN (1 << 8) /* RCC APB1LENR: TIM14EN */
#define RCC_APB1LENR_LPTIM1EN (1 << 9) /* RCC APB1LENR: LPTIM1EN */
/* Bits 10-13: Reserved */
#define RCC_APB1LENR_SPI2EN (1 << 14) /* RCC APB1LENR: SPI2EN */
#define RCC_APB1LENR_SPI3EN (1 << 15) /* RCC APB1LENR: SPI3EN */
#define RCC_APB1LENR_SPDIFRXEN (1 << 16) /* RCC APB1LENR: SPDIFRXEN */
#define RCC_APB1LENR_USART2EN (1 << 17) /* RCC APB1LENR: USART2EN */
#define RCC_APB1LENR_USART3EN (1 << 18) /* RCC APB1LENR: USART3EN */
#define RCC_APB1LENR_UART4EN (1 << 19) /* RCC APB1LENR: UART4EN */
#define RCC_APB1LENR_UART5EN (1 << 20) /* RCC APB1LENR: UART5EN */
#define RCC_APB1LENR_I2C1EN (1 << 21) /* RCC APB1LENR: I2C1EN */
#define RCC_APB1LENR_I2C2EN (1 << 22) /* RCC APB1LENR: I2C2EN */
#define RCC_APB1LENR_I2C3EN (1 << 23) /* RCC APB1LENR: I2C3EN */
/* Bits 24-25: Reserved */
#define RCC_APB1LENR_HDMICECEN (1 << 27) /* RCC APB1LENR: HDMICECEN */
/* Bit 28: Reserved */
#define RCC_APB1LENR_DAC1EN (1 << 29) /* RCC APB1LENR: DAC1EN */
#define RCC_APB1LENR_UART7EN (1 << 30) /* RCC APB1LENR: UART7EN */
#define RCC_APB1LENR_UART8EN (1 << 31) /* RCC APB1LENR: UART8EN */
/* APB1 H Peripheral Clock enable register */
/* Bit 0: Reserved */
#define RCC_APB1HENR_CRSEN (1 << 1) /* RCC APB1HENR: CRSEN */
#define RCC_APB1HENR_SWPEN (1 << 2) /* RCC APB1HENR: SWPEN */
/* Bit 3: Reserved */
#define RCC_APB1HENR_OPAMPEN (1 << 4) /* RCC APB1HENR: OPAMPEN */
#define RCC_APB1HENR_MDIOSEN (1 << 5) /* RCC APB1HENR: MDIOSEN */
/* Bits 6-7: Reserved */
#define RCC_APB1HENR_FDCANEN (1 << 8) /* RCC APB1HENR: FDCANEN */
/* Bits 9-31: Reserved */
/* APB2 Peripheral Clock enable register */
#define RCC_APB2ENR_TIM1EN (1 << 0) /* Bit 0: RCC APB2ENR: TIM1EN */
#define RCC_APB2ENR_TIM8EN (1 << 1) /* Bit 1: RCC APB2ENR: TIM8EN */
/* Bits 2-3: Reserved */
#define RCC_APB2ENR_USART1EN (1 << 4) /* Bit 4: RCC APB2ENR: USART1EN */
#define RCC_APB2ENR_USART6EN (1 << 5) /* Bit 5: RCC APB2ENR: USART6EN */
/* Bits 6-11: Reserved */
#define RCC_APB2ENR_SPI1EN (1 << 12) /* Bit 12: RCC APB2ENR: SPI1EN */
#define RCC_APB2ENR_SPI4EN (1 << 13) /* Bit 13: RCC APB2ENR: SPI4EN */
/* Bits 14-15: Reserved */
#define RCC_APB2ENR_TIM15EN (1 << 16) /* Bit 16: RCC APB2ENR: TIM15EN */
#define RCC_APB2ENR_TIM16EN (1 << 17) /* Bit 17: RCC APB2ENR: TIM16EN */
#define RCC_APB2ENR_TIM17EN (1 << 18) /* Bit 18: RCC APB2ENR: TIM17EN */
#define RCC_APB2ENR_SPI5EN (1 << 20) /* Bit 20: RCC APB2ENR: SPI5EN */
/* Bit 21: Reserved */
#define RCC_APB2ENR_SAI1EN (1 << 22) /* Bit 22: RCC APB2ENR: SAI1EN */
#define RCC_APB2ENR_SAI2EN (1 << 23) /* Bit 23: RCC APB2ENR: SAI2EN */
#define RCC_APB2ENR_SAI3EN (1 << 24) /* Bit 24: RCC APB2ENR: SAI3EN */
/* Bits 25-27: Reserved */
#define RCC_APB2ENR_DFSDM1EN (1 << 28) /* Bit 28: RCC APB2ENR: DFSDM1EN */
#define RCC_APB2ENR_HRTIMEN (1 << 29) /* Bit 29: RCC APB2ENR: HRTIMEN */
/* Bits 30-31: Reserved */
/* APB4 Peripheral Clock enable register */
/* Bit 0: Reserved */
#define RCC_APB4ENR_SYSCFGEN (1 << 1) /* Bit 1: RCC APB4ENR: SYSCFGEN */
/* Bit 2: Reserved */
#define RCC_APB4ENR_LPUART1EN (1 << 3) /* Bit 3: RCC APB4ENR: LPUART1EN */
/* Bit 4: Reserved */
#define RCC_APB4ENR_SPI6EN (1 << 5) /* Bit 5: RCC APB4ENR: SPI6EN */
/* Bit 6: Reserved */
#define RCC_APB4ENR_I2C4EN (1 << 7) /* Bit 7: RCC APB4ENR: I2C4EN */
/* Bit 8: Reserved */
#define RCC_APB4ENR_LPTIM2EN (1 << 9) /* Bit 9: RCC APB4ENR: LPTIM2EN */
#define RCC_APB4ENR_LPTIM3EN (1 << 10) /* Bit 10: RCC APB4ENR: LPTIM3EN */
#define RCC_APB4ENR_LPTIM4EN (1 << 11) /* Bit 11: RCC APB4ENR: LPTIM4EN */
#define RCC_APB4ENR_LPTIM5EN (1 << 12) /* Bit 12: RCC APB4ENR: LPTIM5EN */
/* Bit 13: Reserved */
#define RCC_APB4ENR_COMP12EN (1 << 14) /* Bit 14: RCC APB4ENR: COMP12EN */
#define RCC_APB4ENR_VREFEN (1 << 15) /* Bit 15: RCC APB4ENR: VREFEN */
#define RCC_APB4ENR_RTCAPBEN (1 << 16) /* Bit 16: RCC APB4ENR: RTCAPBEN */
/* Bits 17-20: Reserved */
#define RCC_APB4ENR_SAI4EN (1 << 21) /* Bit 21: RCC APB4ENR: SAI4EN */
/* Bit2 22-31: Reserved */
/* AHB3 low power mode peripheral clock enable register */
#define RCC_AHB3LPENR_MDMALPEN (1 << 0) /* RCC AHB3LPENR: MDMALPEN */
#define RCC_AHB3LPENR_DMA2DLPEN (1 << 4) /* RCC AHB3LPENR: DMA2DLPEN */
#define RCC_AHB3LPENR_JPGDECLPEN (1 << 5) /* RCC AHB3LPENR: JPGDECLPEN */
#define RCC_AHB3LPENR_FLITFLPEN (1 << 8) /* RCC AHB3LPENR: FLITFLPEN */
#define RCC_AHB3LPENR_FMCLPEN (1 << 12) /* RCC AHB3LPENR: FMCLPEN */
#define RCC_AHB3LPENR_QSPILPEN (1 << 14) /* RCC AHB3LPENR: QSPILPEN */
#define RCC_AHB3LPENR_SDMMC1LPEN (1 << 16) /* RCC AHB3LPENR: SDMMC1LPEN */
#define RCC_AHB3LPENR_D1DTCM1LPEN (1 << 28) /* RCC AHB3LPENR: D1DTCM1LPEN */
#define RCC_AHB3LPENR_DTCM2LPEN (1 << 29) /* RCC AHB3LPENR: DTCM2LPEN */
#define RCC_AHB3LPENR_ITCMLPEN (1 << 30) /* RCC AHB3LPENR: ITCMLPEN */
#define RCC_AHB3LPENR_AXISRAMLPEN (1 << 31) /* RCC AHB3LPENR: AXISRAMLPEN */
/* AHB1 low power mode peripheral clock enable register */
#define RCC_AHB1LPENR_DMA1LPEN (1 << 0) /* RCC AHB1LPENR: DMA1LPEN */
#define RCC_AHB1LPENR_DMA2LPEN (1 << 1) /* RCC AHB1LPENR: DMA2LPEN */
#define RCC_AHB1LPENR_ADC12LPEN (1 << 5) /* RCC AHB1LPENR: ADC12LPEN */
#define RCC_AHB1LPENR_ETH1MACLPEN (1 << 15) /* RCC AHB1LPENR: ETH1MACLPEN */
#define RCC_AHB1LPENR_ETH1TXLPEN (1 << 16) /* RCC AHB1LPENR: ETH1TXLPEN */
#define RCC_AHB1LPENR_ETH1RXLPEN (1 << 17) /* RCC AHB1LPENR: ETH1RXLPEN */
#define RCC_AHB1LPENR_OTGHSLPEN (1 << 25) /* RCC AHB1LPENR: OTGHSLPEN */
#define RCC_AHB1LPENR_OTGHSULPILPEN (1 << 26) /* RCC AHB1LPENR: OTGHSULPILPEN */
#define RCC_AHB1LPENR_OTGFSLPEN (1 << 27) /* RCC AHB1LPENR: OTGFSLPEN */
/* AHB2 low power mode peripheral clock enable register */
#define RCC_AHB2LPENR_CAMITFLPEN (1 << 0) /* RCC AHB2LPENR: CAMITFLPEN */
#define RCC_AHB2LPENR_CRYPTLPEN (1 << 4) /* RCC AHB2LPENR: CRYPTLPEN */
#define RCC_AHB2LPENR_HASHLPEN (1 << 5) /* RCC AHB2LPENR: HASHLPEN */
#define RCC_AHB2LPENR_SDMMC2LPEN (1 << 6) /* RCC AHB2LPENR: SDMMC2LPEN */
#define RCC_AHB2LPENR_RNGLPEN (1 << 9) /* RCC AHB2LPENR: RNGLPEN */
#define RCC_AHB2LPENR_SRAM1LPEN (1 << 29) /* RCC AHB2LPENR: SRAM1LPEN */
#define RCC_AHB2LPENR_SRAM2LPEN (1 << 30) /* RCC AHB2LPENR: SRAM2LPEN */
#define RCC_AHB2LPENR_SRAM3LPEN (1 << 31) /* RCC AHB2LPENR: SRAM3LPEN */
/* AHB4 low power mode peripheral clock enable register */
#define RCC_AHB4LPENR_GPIOALPEN (1 << 0) /* RCC AHB4LPENR: GPIOALPEN */
#define RCC_AHB4LPENR_GPIOBLPEN (1 << 1) /* RCC AHB4LPENR: GPIOBLPEN */
#define RCC_AHB4LPENR_GPIOCLPEN (1 << 2) /* RCC AHB4LPENR: GPIOCLPEN */
#define RCC_AHB4LPENR_GPIODLPEN (1 << 3) /* RCC AHB4LPENR: GPIODLPEN */
#define RCC_AHB4LPENR_GPIOELPEN (1 << 4) /* RCC AHB4LPENR: GPIOELPEN */
#define RCC_AHB4LPENR_GPIOFLPEN (1 << 5) /* RCC AHB4LPENR: GPIOFLPEN */
#define RCC_AHB4LPENR_GPIOGLPEN (1 << 6) /* RCC AHB4LPENR: GPIOGLPEN */
#define RCC_AHB4LPENR_GPIOHLPEN (1 << 7) /* RCC AHB4LPENR: GPIOHLPEN */
#define RCC_AHB4LPENR_GPIOILPEN (1 << 8) /* RCC AHB4LPENR: GPIOILPEN */
#define RCC_AHB4LPENR_GPIOJLPEN (1 << 9) /* RCC AHB4LPENR: GPIOJLPEN */
#define RCC_AHB4LPENR_GPIOKLPEN (1 << 10) /* RCC AHB4LPENR: GPIOKLPEN */
#define RCC_AHB4LPENR_CRCLPEN (1 << 19) /* RCC AHB4LPENR: CRCLPEN */
#define RCC_AHB4LPENR_BDMALPEN (1 << 21) /* RCC AHB4LPENR: BDMALPEN */
#define RCC_AHB4LPENR_ADC3LPEN (1 << 24) /* RCC AHB4LPENR: ADC3LPEN */
#define RCC_AHB4LPENR_BKPRAMLPEN (1 << 28) /* RCC AHB4LPENR: BKPRAMLPEN */
#define RCC_AHB4LPENR_SRAM4LPEN (1 << 29) /* RCC AHB4LPENR: SRAM4LPEN */
/* APB3 low power mode peripheral clock enable register */
#define RCC_APB3LPENR_LTDCLPEN (1 << 3) /* RCC APB3LPENR: LTDCLPEN */
#define RCC_APB3LPENR_WWDG1LPEN (1 << 6) /* RCC APB3LPENR: WWDG1LPEN */
/* APB1 L low power mode peripheral clock enable register */
#define RCC_APB1LLPENR_TIM2LPEN (1 << 0) /* RCC APB1LLPENR: TIM2LPEN */
#define RCC_APB1LLPENR_TIM3LPEN (1 << 1) /* RCC APB1LLPENR: TIM3LPEN */
#define RCC_APB1LLPENR_TIM4LPEN (1 << 2) /* RCC APB1LLPENR: TIM4LPEN */
#define RCC_APB1LLPENR_TIM5LPEN (1 << 3) /* RCC APB1LLPENR: TIM5LPEN */
#define RCC_APB1LLPENR_TIM6LPEN (1 << 4) /* RCC APB1LLPENR: TIM6LPEN */
#define RCC_APB1LLPENR_TIM7LPEN (1 << 5) /* RCC APB1LLPENR: TIM7LPEN */
#define RCC_APB1LLPENR_TIM12LPEN (1 << 6) /* RCC APB1LLPENR: TIM12LPEN */
#define RCC_APB1LLPENR_TIM13LPEN (1 << 7) /* RCC APB1LLPENR: TIM13LPEN */
#define RCC_APB1LLPENR_TIM14LPEN (1 << 8) /* RCC APB1LLPENR: TIM14LPEN */
#define RCC_APB1LLPENR_LPTIM1LPEN (1 << 9) /* RCC APB1LLPENR: LPTIM1LPEN */
#define RCC_APB1LLPENR_SPI2LPEN (1 << 14) /* RCC APB1LLPENR: SPI2LPEN */
#define RCC_APB1LLPENR_SPI3LPEN (1 << 15) /* RCC APB1LLPENR: SPI3LPEN */
#define RCC_APB1LLPENR_SPDIFRXLPEN (1 << 16) /* RCC APB1LLPENR: SPDIFRXLPEN */
#define RCC_APB1LLPENR_USART2LPEN (1 << 17) /* RCC APB1LLPENR: USART2LPEN */
#define RCC_APB1LLPENR_USART3LPEN (1 << 18) /* RCC APB1LLPENR: USART3LPEN */
#define RCC_APB1LLPENR_UART4LPEN (1 << 19) /* RCC APB1LLPENR: UART4LPEN */
#define RCC_APB1LLPENR_UART5LPEN (1 << 20) /* RCC APB1LLPENR: UART5LPEN */
#define RCC_APB1LLPENR_I2C1LPEN (1 << 21) /* RCC APB1LLPENR: I2C1LPEN */
#define RCC_APB1LLPENR_I2C2LPEN (1 << 22) /* RCC APB1LLPENR: I2C2LPEN */
#define RCC_APB1LLPENR_I2C3LPEN (1 << 23) /* RCC APB1LLPENR: I2C3LPEN */
#define RCC_APB1LLPENR_HDMICECLPEN (1 << 27) /* RCC APB1LLPENR: HDMICECLPEN */
#define RCC_APB1LLPENR_DAC1LPEN (1 << 29) /* RCC APB1LLPENR: DAC1LPEN */
#define RCC_APB1LLPENR_UART7LPEN (1 << 30) /* RCC APB1LLPENR: UART7LPEN */
#define RCC_APB1LLPENR_UART8LPEN (1 << 31) /* RCC APB1LLPENR: UART8LPEN */
/* APB1 H low power mode peripheral clock enable register */
#define RCC_APB1HLPENR_CRSLPEN (1 << 1) /* RCC APB1HLPENR: CRSLPEN */
#define RCC_APB1HLPENR_SWPLPEN (1 << 2) /* RCC APB1HLPENR: SWPLPEN */
#define RCC_APB1HLPENR_OPAMPLPEN (1 << 4) /* RCC APB1HLPENR: OPAMPLPEN */
#define RCC_APB1HLPENR_MDIOSLPEN (1 << 5) /* RCC APB1HLPENR: MDIOSLPEN */
#define RCC_APB1HLPENR_FDCANLPEN (1 << 8) /* RCC APB1HLPENR: FDCANLPEN */
/* APB2 low power mode peripheral clock enable register */
#define RCC_APB2LPENR_TIM1LPEN (1 << 0) /* RCC APB2LPENR: TIM1LPEN */
#define RCC_APB2LPENR_TIM8LPEN (1 << 1) /* RCC APB2LPENR: TIM8LPEN */
#define RCC_APB2LPENR_USART1LPEN (1 << 4) /* RCC APB2LPENR: USART1LPEN */
#define RCC_APB2LPENR_USART6LPEN (1 << 5) /* RCC APB2LPENR: USART6LPEN */
#define RCC_APB2LPENR_SPI1LPEN (1 << 12) /* RCC APB2LPENR: SPI1LPEN */
#define RCC_APB2LPENR_SPI4LPEN (1 << 13) /* RCC APB2LPENR: SPI4LPEN */
#define RCC_APB2LPENR_TIM15LPEN (1 << 16) /* RCC APB2LPENR: TIM15LPEN */
#define RCC_APB2LPENR_TIM16LPEN (1 << 17) /* RCC APB2LPENR: TIM16LPEN */
#define RCC_APB2LPENR_TIM17LPEN (1 << 18) /* RCC APB2LPENR: TIM17LPEN */
#define RCC_APB2LPENR_SPI5LPEN (1 << 20) /* RCC APB2LPENR: SPI5LPEN */
#define RCC_APB2LPENR_SAI1LPEN (1 << 22) /* RCC APB2LPENR: SAI1LPEN */
#define RCC_APB2LPENR_SAI2LPEN (1 << 23) /* RCC APB2LPENR: SAI2LPEN */
#define RCC_APB2LPENR_SAI3LPEN (1 << 24) /* RCC APB2LPENR: SAI3LPEN */
#define RCC_APB2LPENR_DFSDM1LPEN (1 << 28) /* RCC APB2LPENR: DFSDM1LPEN */
#define RCC_APB2LPENR_HRTIMLPEN (1 << 29) /* RCC APB2LPENR: HRTIMLPEN */
/* APB4 low power mode peripheral clock enable register */
#define RCC_APB4LPENR_SYSCFGLPEN (1 << 1) /* RCC APB4LPENR: SYSCFGLPEN */
#define RCC_APB4LPENR_LPUART1LPEN (1 << 3) /* RCC APB4LPENR: LPUART1LPEN */
#define RCC_APB4LPENR_SPI6LPEN (1 << 5) /* RCC APB4LPENR: SPI6LPEN */
#define RCC_APB4LPENR_I2C4LPEN (1 << 7) /* RCC APB4LPENR: I2C4LPEN */
#define RCC_APB4LPENR_LPTIM2LPEN (1 << 9) /* RCC APB4LPENR: LPTIM2LPEN */
#define RCC_APB4LPENR_LPTIM3LPEN (1 << 10) /* RCC APB4LPENR: LPTIM3LPEN */
#define RCC_APB4LPENR_LPTIM4LPEN (1 << 11) /* RCC APB4LPENR: LPTIM4LPEN */
#define RCC_APB4LPENR_LPTIM5LPEN (1 << 12) /* RCC APB4LPENR: LPTIM5LPEN */
#define RCC_APB4LPENR_COMP12LPEN (1 << 14) /* RCC APB4LPENR: COMP12LPEN */
#define RCC_APB4LPENR_VREFLPEN (1 << 15) /* RCC APB4LPENR: VREFLPEN */
#define RCC_APB4LPENR_RTCAPBLPEN (1 << 16) /* RCC APB4LPENR: RTCAPBLPEN */
#define RCC_APB4LPENR_SAI4LPEN (1 << 21) /* RCC APB4LPENR: SAI4LPEN */
/* Backup domain control register */
#define RCC_BDCR_LSEON (1 << 0) /* Bit 0: External Low Speed oscillator enable */
#define RCC_BDCR_LSERDY (1 << 1) /* Bit 1: External Low Speed oscillator Ready */
#define RCC_BDCR_LSEBYP (1 << 2) /* Bit 2: External Low Speed oscillator Bypass */
#define RCC_BDCR_LSEDRV_SHIFT (3) /* Bits 4:3: LSE oscillator Drive selection */
#define RCC_BDCR_LSEDRV_MASK (3 << RCC_BDCR_LSEDRV_SHIFT) /* See errata ES0392 Rev 7. 2.2.14 */
# define RCC_BDCR_LSEDRV_LOW (0 << RCC_BDCR_LSEDRV_SHIFT) /* 00: Low driving capability */
# define RCC_BDCR_LSEDRV_MEDHI_Y (1 << RCC_BDCR_LSEDRV_SHIFT) /* 01: Medium high driving capability rev y */
# define RCC_BDCR_LSEDRV_MEDHI (2 << RCC_BDCR_LSEDRV_SHIFT) /* 10: Medium high driving capability */
# define RCC_BDCR_LSEDRV_MEDLO_Y (2 << RCC_BDCR_LSEDRV_SHIFT) /* 10: Medium low driving capability rev y */
# define RCC_BDCR_LSEDRV_MEDLO (1 << RCC_BDCR_LSEDRV_SHIFT) /* 01: Medium low driving capability */
# define RCC_BDCR_LSEDRV_HIGH (3 << RCC_BDCR_LSEDRV_SHIFT) /* 11: High driving capability */
#define RCC_BDCR_LSECSSON (1 << 5) /* Bit 5: LSE clock security system enable */
#define RCC_BDCR_LSECSSD (1 << 6) /* Bit 6: LSE clock security system failure detection */
/* Bit 7: Reserved */
#define RCC_BDCR_RTCSEL_SHIFT (8) /* Bits 9:8: RTC clock source selection */
#define RCC_BDCR_RTCSEL_MASK (3 << RCC_BDCR_RTCSEL_SHIFT)
# define RCC_BDCR_RTCSEL_NOCLK (0 << RCC_BDCR_RTCSEL_SHIFT) /* 00: No clock */
# define RCC_BDCR_RTCSEL_LSE (1 << RCC_BDCR_RTCSEL_SHIFT) /* 01: LSE oscillator clock used as RTC clock */
# define RCC_BDCR_RTCSEL_LSI (2 << RCC_BDCR_RTCSEL_SHIFT) /* 10: LSI oscillator clock used as RTC clock */
# define RCC_BDCR_RTCSEL_HSE (3 << RCC_BDCR_RTCSEL_SHIFT) /* 11: HSE oscillator clock divided by 128 used as RTC clock */
/* Bits 10-15: Reserved */
#define RCC_BDCR_RTCEN (1 << 15) /* Bit 15: RTC clock enable */
#define RCC_BDCR_BDRST (1 << 16) /* Bit 16: Backup domain software reset */
/* Bits 17-31: Reserved */
#endif /* __ARCH_ARM_SRC_STM32H7_HARDWARE_STM32H7X3XX_RCC_H */
|
afe897a83379be36fcb246cab563288c4b768436
|
7f6c235b0598353549959c18f69eefd20b766907
|
/examples/vz/dstar.c
|
8e7f4ccab317c3d035cdcbcd352e9155de306834
|
[
"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
| 10,600
|
c
|
dstar.c
|
/*
* dstar.c
*
* dstarz88 is a conversion of a TI86 game I found with
* source on www.ticalc.org.
*
* The original program was written by Andrew Von Dollen who
* in turn based it on a HP game by Joe W.
*
* The aim of the game is to collect all the clear bubbles by
* running over them. You control either the dark bubble or
* the solid box. The dark bubble is used to collect the clear
* bubbles, and the solid box is used as a sort of movable wall.
*
* Both objects carry on moving until they hit something else
* (except for the dark bubble in the case of clear bubbles).
*
* The keys are defined in #define statements, and default thus:
*
* Up: Q
* Down: A
* Left: O
* Right: P
* Quit: G
* Retry: H
* Switch: [SPACE]
*
* Switch changes between the dark bubble and the solid box.
*
* This is the first game ever produced with the Small C compiler -
* it was written as a statement saying that it is possible to
* write something easily, quickly and efficiently using the
* compiler. Hopefully it will be an encouragement for others to
* do likewise!
*
* For your interest I've also included the original Z88 converted
* assembler from which I worked - it's quite crude but it just
* about functions, the C is much more refined!
*
* Enough twaddle, enjoy the game and study the source!
*
* d. <djm@jb.man.ac.uk> 1/12/98
*
*
* Rejigged for the Spectrum 17/5/99 djm
*
* Ported to VZ200 2/5/99 - Stefano Bodrato
*
* Compile it, then run rbinary create a VZ loadable file;
* start the emulator then poke 30862,0 / 30863,128
*
* Type in a small basic program to enter in graphics mode:
* 10 mode(1)
* 20 X=usr(0)
*
* At last, RUN and play !
*/
/* Skip closeall() gunk */
#pragma output nostreams
/* Call up the required header files */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/* dstar.h contains the levels and "sprite" data */
#include "dstar.h"
#define NO 0
#define MAXLEVEL 25
#define STARTLEV 0 /* Start level -1 */
/* Block numbers.. */
#define WALL 1
#define BUBB 2
#define BALL 3
#define BOX 4
/* Key definitions, change these to define your keys! */
#define K_UP 'Q'
#define K_DOWN 'A'
#define K_LEFT 'O'
#define K_RIGHT 'P'
#define K_SWITCH 32
#define K_EXIT 'G'
#define K_CLEAR 'H'
/* Declare some variables to start off with! */
char balloffset; /* Ball position */
char boxoffset; /* Box position */
char ballorbox; /* 1 if box, 0 if ball */
char level; /* Take a guess! */
char board[144]; /* Level internal map thing */
char tiscr[1024]; /* Our very own TI86 screen! */
/* prototype to stop barfing */
void redrawscreen(void);
static void myexit(void);
static void playgame(void);
static void setupgame(void);
static void gamekeys(void);
static void left(char *ptr);
static void right(char *ptr);
static void down(char *ptr);
static void up(char *ptr);
static int standardmiddle(char nextpos);
static int checkfinish(void);
static void setuplevel(void);
static void drawboard(void);
static void puttiblock(unsigned char spr,int x, int y);
static void dovzcopyasm(void);
void main()
{
redrawscreen(); /* Define the windows */
playgame(); /* Play the game */
myexit(); /* Clean up after ourselves */
}
void myexit()
{
exit(0); /* Get outta here! */
}
void playgame()
{
setupgame(); /* Set level to 1, get level etc */
/* Loop while checkfinish() says we haven't finished! */
while ( checkfinish() ) {
gamekeys(); /* Scan keys */
}
}
/* Set some variables up at the start.. */
void setupgame()
{
ballorbox=NO;
level=STARTLEV;
setuplevel();
}
void gamekeys()
{
char *charptr;
/* Set up a pointer to the variable we want to change (either for
* box or for ball
*/
if (ballorbox) charptr=&boxoffset;
else charptr=&balloffset;
switch( toupper(getk()) ) { /* Use OZ to get the key */
case K_DOWN:
down(charptr);
break;
case K_UP:
up(charptr);
break;
case K_RIGHT:
right(charptr);
break;
case K_LEFT:
left(charptr);
break;
case K_SWITCH:
ballorbox^=1; /* Toggle ball/box */
break;
case K_EXIT:
myexit();
case K_CLEAR:
setuplevel();
}
}
/* Movement functions - all of these are pretty well similar so I
* will only comment the first one - it's fairly obvious what is
* happening though
*/
void left(char *ptr)
{
char *locn;
while(1) {
locn=*(ptr)+board;
if (standardmiddle(*(locn-1)) ) return;
*(locn-1)=*locn;
*locn=0;
(*ptr)--; /* ptr is the location of blob */
drawboard(); /* Draw screen */
}
}
void right(char *ptr)
{
char *locn;
while(1) {
locn=*(ptr)+board;
if (standardmiddle(*(locn+1)) ) return;
*(locn+1)=*locn;
*locn=0;
(*ptr)++;
drawboard();
}
}
void down(char *ptr)
{
char *locn;
while(1) {
locn=*(ptr)+board;
if (standardmiddle(*(locn+16)) ) return;
*(locn+16)=*locn;
*locn=0;
(*ptr)+=16;
drawboard();
}
}
void up(char *ptr)
{
char *locn;
while(1) {
locn=*(ptr)+board;
if ( standardmiddle(*(locn-16)) ) return;
*(locn-16)=*locn;
*locn=0;
(*ptr)-=16;
drawboard();
}
}
/* Check to see if we're running into anything, if box is set then
* if we hit anything we want to stop, if we're ball then if we
* hit anything except for bubble we wanna stop
*/
int standardmiddle(char nextpos)
{
if (ballorbox)
return (nextpos); /* For box */
else
if (nextpos==BUBB || nextpos==NO) return(0);
return(1);
}
/* Check to see if a level is finished
* There are 144 squares in each level, note the use of != instead of
* </<= - this is quicker to execute on the Z80!
*/
int checkfinish()
{
char *ptr;
int i;
ptr=board;
for (i=1; i!=144; i++) {
if (*ptr++ == BUBB) return(1);
}
if ( ++level==MAXLEVEL ) return(0); /* Done all the levels!! */
setuplevel();
return(1);
}
/* Setup a level..the level is stored compressed, taking up 38 bytes a
* time.
* byte 0 - position of ball
* byte 1 - position of box
* 2-37 - level data
*
* Level data is stored as two bits per square, so we have to shift our
* picked up byte round to get it
*/
void setuplevel()
{
int y,x;
char *ptr,*ptr2;
ptr2=board;
ptr=levels+(level*38);
/* ptr points to start of level now */
/* First two bytes are the ball and the boxes position */
balloffset=*ptr++;
boxoffset=*ptr++;
/* Now, decompress level into board */
for (y=0; y!=9; y++) {
for (x=0; x !=4; x++) {
*ptr2++=((*ptr)>>6)&3;
*ptr2++=((*ptr)>>4)&3;
*ptr2++=((*ptr)>>2)&3;
*ptr2++=(*ptr)&3;
ptr++;
}
}
/* Now, plot the ball and box into the internal map */
ptr2=board;
*(ptr2+balloffset)=BALL;
*(ptr2+boxoffset)=BOX;
drawboard();
}
/* Define the text window and the graphics window
* If can't open graphics window then exit gracefully
*/
void redrawscreen(void)
{
/* Init Graphics page */
#asm
ld a,8
ld (6800h),a
ld (783bh),a ; force graph mode
ld hl,7000h ; base of graphics area
ld (hl),0
ld d,h
ld e,1 ; de = base_graphics+1
ld bc,128*64/4-1
ldir ; reset graphics window (2K)
#endasm
}
/* Draw the board, mostly written in C, even though we did take a bit
* of a performance hit when it was converted over from asm
*/
void drawboard()
{
int x,y;
char *ptr;
ptr=board;
for (y=0;y!=9;y++) {
for (x=0;x!=16;x++) {
puttiblock((*ptr++),x,y);
}
}
dovzcopyasm();
}
/* Dump a sprite onto the TI screen we've built
* The TI screen is 16 characters wide by 8 deep i.e. half the size
* of the Z88's map screen. It's stored line by line (sensible!)
*
* We enter with y being y/7 and x being x/8 (if we think in pixels)
* So for each y we have to step down by 112.
* The increment between rows is 16.
*/
void puttiblock(unsigned char spr,int x, int y)
{
char *ptr2,*ptr;
int i;
/* We use this method instead of y*=112 because the compiler has special
* cases for multiplying by ints less than 16 (except for 11 and 13
* (Hmmm, I wonder why?!?!)
*/
y=(y*14)*8;
/* So, get where we want to dump our sprite into ptr */
ptr=tiscr+y+x;
/* Calculate where the sprite is */
spr*=8;
ptr2=sprites+spr;
/* And dump it in there */
for (i=0; i!=7;i++) {
*ptr=*(ptr2++);
ptr+=16;
}
}
/* Ooops, forgive me this one bit of assembler in the entire program!
* This just copies the TI screen onto the OZ map.
*
* It really is easier to keep this routine in here, change it into
* C if you like..
*/
void dovzcopyasm()
{
#asm
ld de,28672
ld hl,_tiscr
ld bc,1024
.cploop
ld a,(hl)
push bc
ld b,4
.nibble1
rla
push af
rl c
pop af
rl c
djnz nibble1
push bc
push af
ld a,c
ld (de),a
pop af
pop bc
inc de
ld b,4
.nibble2
rla
push af
rl c
pop af
rl c
djnz nibble2
push bc
ld a,c
ld (de),a
pop bc
inc de
inc hl
pop bc
dec bc
ld a,b
or c
jr nz,cploop
/* Every function always has a ret at the end! So don't need one of
* our own!!
*/
#endasm
}
/* THE END! */
|
82d6a462b39d71e3bbe047622c8cdf486fcb9e7b
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/components/net/lwip/lwip-2.1.2/src/netif/ppp/polarssl/md4.c
|
b1701a07b998a86f4bc962a007adc1a025ba0e01
|
[
"BSD-3-Clause",
"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
| 8,088
|
c
|
md4.c
|
/*
* RFC 1186/1320 compliant MD4 implementation
*
* Based on XySSL: Copyright (C) 2006-2008 Christophe Devine
*
* Copyright (C) 2009 Paul Bakker <polarssl_maintainer at polarssl dot org>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of PolarSSL or XySSL 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.
*/
/*
* The MD4 algorithm was designed by Ron Rivest in 1990.
*
* http://www.ietf.org/rfc/rfc1186.txt
* http://www.ietf.org/rfc/rfc1320.txt
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && LWIP_INCLUDED_POLARSSL_MD4
#include "netif/ppp/polarssl/md4.h"
#include <string.h>
/*
* 32-bit integer manipulation macros (little endian)
*/
#ifndef GET_ULONG_LE
#define GET_ULONG_LE(n,b,i) \
{ \
(n) = ( (unsigned long) (b)[(i) ] ) \
| ( (unsigned long) (b)[(i) + 1] << 8 ) \
| ( (unsigned long) (b)[(i) + 2] << 16 ) \
| ( (unsigned long) (b)[(i) + 3] << 24 ); \
}
#endif
#ifndef PUT_ULONG_LE
#define PUT_ULONG_LE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( (n) ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 3] = (unsigned char) ( (n) >> 24 ); \
}
#endif
/*
* MD4 context setup
*/
void md4_starts( md4_context *ctx )
{
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = 0x67452301;
ctx->state[1] = 0xEFCDAB89;
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
}
static void md4_process( md4_context *ctx, const unsigned char data[64] )
{
unsigned long X[16], A, B, C, D;
GET_ULONG_LE( X[ 0], data, 0 );
GET_ULONG_LE( X[ 1], data, 4 );
GET_ULONG_LE( X[ 2], data, 8 );
GET_ULONG_LE( X[ 3], data, 12 );
GET_ULONG_LE( X[ 4], data, 16 );
GET_ULONG_LE( X[ 5], data, 20 );
GET_ULONG_LE( X[ 6], data, 24 );
GET_ULONG_LE( X[ 7], data, 28 );
GET_ULONG_LE( X[ 8], data, 32 );
GET_ULONG_LE( X[ 9], data, 36 );
GET_ULONG_LE( X[10], data, 40 );
GET_ULONG_LE( X[11], data, 44 );
GET_ULONG_LE( X[12], data, 48 );
GET_ULONG_LE( X[13], data, 52 );
GET_ULONG_LE( X[14], data, 56 );
GET_ULONG_LE( X[15], data, 60 );
#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n)))
A = ctx->state[0];
B = ctx->state[1];
C = ctx->state[2];
D = ctx->state[3];
#define F(x, y, z) ((x & y) | ((~x) & z))
#define P(a,b,c,d,x,s) { a += F(b,c,d) + x; a = S(a,s); }
P( A, B, C, D, X[ 0], 3 );
P( D, A, B, C, X[ 1], 7 );
P( C, D, A, B, X[ 2], 11 );
P( B, C, D, A, X[ 3], 19 );
P( A, B, C, D, X[ 4], 3 );
P( D, A, B, C, X[ 5], 7 );
P( C, D, A, B, X[ 6], 11 );
P( B, C, D, A, X[ 7], 19 );
P( A, B, C, D, X[ 8], 3 );
P( D, A, B, C, X[ 9], 7 );
P( C, D, A, B, X[10], 11 );
P( B, C, D, A, X[11], 19 );
P( A, B, C, D, X[12], 3 );
P( D, A, B, C, X[13], 7 );
P( C, D, A, B, X[14], 11 );
P( B, C, D, A, X[15], 19 );
#undef P
#undef F
#define F(x,y,z) ((x & y) | (x & z) | (y & z))
#define P(a,b,c,d,x,s) { a += F(b,c,d) + x + 0x5A827999; a = S(a,s); }
P( A, B, C, D, X[ 0], 3 );
P( D, A, B, C, X[ 4], 5 );
P( C, D, A, B, X[ 8], 9 );
P( B, C, D, A, X[12], 13 );
P( A, B, C, D, X[ 1], 3 );
P( D, A, B, C, X[ 5], 5 );
P( C, D, A, B, X[ 9], 9 );
P( B, C, D, A, X[13], 13 );
P( A, B, C, D, X[ 2], 3 );
P( D, A, B, C, X[ 6], 5 );
P( C, D, A, B, X[10], 9 );
P( B, C, D, A, X[14], 13 );
P( A, B, C, D, X[ 3], 3 );
P( D, A, B, C, X[ 7], 5 );
P( C, D, A, B, X[11], 9 );
P( B, C, D, A, X[15], 13 );
#undef P
#undef F
#define F(x,y,z) (x ^ y ^ z)
#define P(a,b,c,d,x,s) { a += F(b,c,d) + x + 0x6ED9EBA1; a = S(a,s); }
P( A, B, C, D, X[ 0], 3 );
P( D, A, B, C, X[ 8], 9 );
P( C, D, A, B, X[ 4], 11 );
P( B, C, D, A, X[12], 15 );
P( A, B, C, D, X[ 2], 3 );
P( D, A, B, C, X[10], 9 );
P( C, D, A, B, X[ 6], 11 );
P( B, C, D, A, X[14], 15 );
P( A, B, C, D, X[ 1], 3 );
P( D, A, B, C, X[ 9], 9 );
P( C, D, A, B, X[ 5], 11 );
P( B, C, D, A, X[13], 15 );
P( A, B, C, D, X[ 3], 3 );
P( D, A, B, C, X[11], 9 );
P( C, D, A, B, X[ 7], 11 );
P( B, C, D, A, X[15], 15 );
#undef F
#undef P
ctx->state[0] += A;
ctx->state[1] += B;
ctx->state[2] += C;
ctx->state[3] += D;
}
/*
* MD4 process buffer
*/
void md4_update( md4_context *ctx, const unsigned char *input, int ilen )
{
int fill;
unsigned long left;
if( ilen <= 0 )
return;
left = ctx->total[0] & 0x3F;
fill = 64 - left;
ctx->total[0] += ilen;
ctx->total[0] &= 0xFFFFFFFF;
if( ctx->total[0] < (unsigned long) ilen )
ctx->total[1]++;
if( left && ilen >= fill )
{
MEMCPY( (void *) (ctx->buffer + left),
input, fill );
md4_process( ctx, ctx->buffer );
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 64 )
{
md4_process( ctx, input );
input += 64;
ilen -= 64;
}
if( ilen > 0 )
{
MEMCPY( (void *) (ctx->buffer + left),
input, ilen );
}
}
static const unsigned char md4_padding[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/*
* MD4 final digest
*/
void md4_finish( md4_context *ctx, unsigned char output[16] )
{
unsigned long last, padn;
unsigned long high, low;
unsigned char msglen[8];
high = ( ctx->total[0] >> 29 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
PUT_ULONG_LE( low, msglen, 0 );
PUT_ULONG_LE( high, msglen, 4 );
last = ctx->total[0] & 0x3F;
padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
md4_update( ctx, md4_padding, padn );
md4_update( ctx, msglen, 8 );
PUT_ULONG_LE( ctx->state[0], output, 0 );
PUT_ULONG_LE( ctx->state[1], output, 4 );
PUT_ULONG_LE( ctx->state[2], output, 8 );
PUT_ULONG_LE( ctx->state[3], output, 12 );
}
/*
* output = MD4( input buffer )
*/
void md4( unsigned char *input, int ilen, unsigned char output[16] )
{
md4_context ctx;
md4_starts( &ctx );
md4_update( &ctx, input, ilen );
md4_finish( &ctx, output );
}
#endif /* PPP_SUPPORT && LWIP_INCLUDED_POLARSSL_MD4 */
|
ee09c1dbdfaa9fa65b7788395013eef9de717b41
|
dbd900c1027953471ed77411ad9c5390e52b58b2
|
/ykpers_lcl.h
|
52af7b9006de9e0242d7fe53b1c359c0a072d644
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
Yubico/yubikey-personalization
|
b8c8ab2bc0619fcccd52cb76152e0a63d60b3d61
|
db0c0d641d47ee52e43af94dcee603d76186b6d3
|
refs/heads/master
| 2023-08-25T15:58:26.565422
| 2022-06-13T08:22:07
| 2022-06-13T08:22:07
| 1,186,996
| 251
| 88
|
BSD-2-Clause
| 2022-06-13T08:22:08
| 2010-12-21T12:04:03
|
C
|
UTF-8
|
C
| false
| false
| 3,495
|
h
|
ykpers_lcl.h
|
/* -*- mode:C; c-file-style: "bsd" -*- */
/*
* Copyright (c) 2013 Yubico AB
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __YKPERS_LCL_H_INCLUDED__
#define __YKPERS_LCL_H_INCLUDED__
#include "ykcore_lcl.h"
#include "ykpers.h"
# ifdef __cplusplus
extern "C" {
# endif
struct ykp_config_t {
unsigned int yk_major_version;
unsigned int yk_minor_version;
unsigned int yk_build_version;
unsigned int command;
YK_CONFIG ykcore_config;
unsigned int ykp_acccode_type;
};
extern bool capability_has_hidtrig(const YKP_CONFIG *cfg);
extern bool capability_has_ticket_first(const YKP_CONFIG *cfg);
extern bool capability_has_static(const YKP_CONFIG *cfg);
extern bool capability_has_static_extras(const YKP_CONFIG *cfg);
extern bool capability_has_slot_two(const YKP_CONFIG *cfg);
extern bool capability_has_chal_resp(const YKP_CONFIG *cfg);
extern bool capability_has_oath_imf(const YKP_CONFIG *cfg);
extern bool capability_has_serial_api(const YKP_CONFIG *cfg);
extern bool capability_has_serial(const YKP_CONFIG *cfg);
extern bool capability_has_oath(const YKP_CONFIG *cfg);
extern bool capability_has_ticket_mods(const YKP_CONFIG *cfg);
extern bool capability_has_update(const YKP_CONFIG *cfg);
extern bool capability_has_fast(const YKP_CONFIG *cfg);
extern bool capability_has_numeric(const YKP_CONFIG *cfg);
extern bool capability_has_dormant(const YKP_CONFIG *cfg);
extern bool capability_has_led_inv(const YKP_CONFIG *cfg);
struct map_st {
uint8_t flag;
const char *flag_text;
const char *json_text;
bool (*capability)(const YKP_CONFIG *cfg);
unsigned char mode;
int (*setter)(YKP_CONFIG *cfg, bool state);
};
extern struct map_st _ticket_flags_map[];
extern struct map_st _config_flags_map[];
extern struct map_st _extended_flags_map[];
extern struct map_st _modes_map[];
#define MODE_CHAL_HMAC 0x01
#define MODE_OATH_HOTP 0x02
#define MODE_OTP_YUBICO 0x04
#define MODE_CHAL_YUBICO 0x08
#define MODE_STATIC_TICKET 0x10
#define MODE_CHAL_RESP MODE_CHAL_YUBICO | MODE_CHAL_HMAC
#define MODE_OUTPUT MODE_STATIC_TICKET | MODE_OTP_YUBICO | MODE_OATH_HOTP
#define MODE_ALL 0xff
# ifdef __cplusplus
}
# endif
#endif /* __YKPERS_LCL_H_INCLUDED__ */
|
2af0ca7708c60f48ff1b7729460532e85a0ffe00
|
2b3bbfc742ad6a2529f2906193c3c5263ebd5fac
|
/src/app/application/algorithm/moving_average/moving_average.c
|
d9dbfd7457aec99e204d039c182707eff1c8f206
|
[
"CC-BY-4.0",
"BSD-3-Clause"
] |
permissive
|
foxBMS/foxbms-2
|
35502ef8441dfc7374fd6c0839e7f5328a5bda8f
|
9eb6d1c44e63e43e62bbf6983b2e618fb6ad02cc
|
refs/heads/master
| 2023-05-22T05:30:25.862475
| 2023-02-23T15:03:35
| 2023-02-24T15:04:15
| 353,751,476
| 151
| 80
|
NOASSERTION
| 2023-09-01T09:59:30
| 2021-04-01T15:52:24
|
C
|
UTF-8
|
C
| false
| false
| 21,642
|
c
|
moving_average.c
|
/**
*
* @copyright © 2010 - 2023, Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V.
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* We kindly request you to use one or more of the following phrases to refer to
* foxBMS in your hardware, software, documentation or advertising materials:
*
* - ″This product uses parts of foxBMS®″
* - ″This product includes parts of foxBMS®″
* - ″This product is derived from foxBMS®″
*
*/
/**
* @file moving_average.c
* @author foxBMS Team
* @date 2017-12-18 (date of creation)
* @updated 2023-02-23 (date of last update)
* @version v1.5.1
* @ingroup ALGORITHMS
* @prefix ALGO
*
* @brief moving average algorithm
*
*/
/*========== Includes =======================================================*/
#include "moving_average.h"
#include "algorithm_cfg.h"
#include "database.h"
#include "fstd_types.h"
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
/*========== Macros and Definitions =========================================*/
/** TODO */
#define MEM_EXT_SDRAM
#if ALGO_TICK_ms > ISA_CURRENT_CYCLE_TIME_ms
#define ALGO_NUMBER_AVERAGE_VALUES_CUR_1s ((1000u) / ALGO_TICK_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_CUR_5s ((5000u) / ALGO_TICK_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_CUR_10s ((10000u) / ALGO_TICK_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_CUR_30s ((30000u) / ALGO_TICK_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_CUR_60s ((60000u) / ALGO_TICK_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_CUR_CFG (MOVING_AVERAGE_DURATION_CURRENT_CONFIG_ms / ALGO_TICK_ms)
#else
#define ALGO_NUMBER_AVERAGE_VALUES_CUR_1s ((1000u) / ISA_CURRENT_CYCLE_TIME_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_CUR_5s ((5000u) / ISA_CURRENT_CYCLE_TIME_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_CUR_10s ((10000u) / ISA_CURRENT_CYCLE_TIME_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_CUR_30s ((30000u) / ISA_CURRENT_CYCLE_TIME_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_CUR_60s ((60000u) / ISA_CURRENT_CYCLE_TIME_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_CUR_CFG (MOVING_AVERAGE_DURATION_CURRENT_CONFIG_ms / ISA_CURRENT_CYCLE_TIME_ms)
#endif
#if ALGO_TICK_ms > ISA_POWER_CYCLE_TIME_ms
#define ALGO_NUMBER_AVERAGE_VALUES_POW_1s ((1000u) / ALGO_TICK_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_POW_5s ((5000u) / ALGO_TICK_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_POW_10s ((10000u) / ALGO_TICK_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_POW_30s ((30000u) / ALGO_TICK_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_POW_60s ((60000u) / ALGO_TICK_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_POW_CFG (MOVING_AVERAGE_DURATION_POWER_CONFIG_ms / ALGO_TICK_ms)
#else
#define ALGO_NUMBER_AVERAGE_VALUES_POW_1s ((1000u) / ISA_POWER_CYCLE_TIME_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_POW_5s ((5000u) / ISA_POWER_CYCLE_TIME_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_POW_10s ((10000u) / ISA_POWER_CYCLE_TIME_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_POW_30s ((30000u) / ISA_POWER_CYCLE_TIME_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_POW_60s ((60000u) / ISA_POWER_CYCLE_TIME_ms)
#define ALGO_NUMBER_AVERAGE_VALUES_POW_CFG (MOVING_AVERAGE_DURATION_POWER_CONFIG_ms / ISA_POWER_CYCLE_TIME_ms)
#endif
/*========== Static Constant and Variable Definitions =======================*/
/* Arrays in extern SDRAM to calculate moving average current and power */
/* Check if minimum algo cycle time > current sensor sample time */
#if ALGO_TICK_ms > ISA_CURRENT_CYCLE_TIME_ms
#if MOVING_AVERAGE_DURATION_CURRENT_CONFIG_ms / ALGO_TICK_ms > 60000u / ALGO_TICK_ms
/* If array length of configured time > 60s array take this array size */
static float_t MEM_EXT_SDRAM curValues[(MOVING_AVERAGE_DURATION_CURRENT_CONFIG_ms / ALGO_TICK_ms) + 1u] = {};
static uint32_t movingAverageCurrentLength = (MOVING_AVERAGE_DURATION_CURRENT_CONFIG_ms / ALGO_TICK_ms) + 1u;
#else
/* Take array size of 60s moving average */
static float_t MEM_EXT_SDRAM curValues[(60000u / ALGO_TICK_ms) + 1u] = {};
static uint32_t movingAverageCurrentLength = (60000u / ALGO_TICK_ms) + 1;
#endif
#else
/* If array length of configured time > 60s array take this array size */
#if (MOVING_AVERAGE_DURATION_CURRENT_CONFIG_ms / ISA_CURRENT_CYCLE_TIME_ms) > (60000u / ISA_CURRENT_CYCLE_TIME_ms)
static float_t MEM_EXT_SDRAM
curValues[(MOVING_AVERAGE_DURATION_CURRENT_CONFIG_ms / ISA_CURRENT_CYCLE_TIME_ms) + 1u] = {};
static uint32_t movingAverageCurrentLength = (MOVING_AVERAGE_DURATION_CURRENT_CONFIG_ms / ISA_CURRENT_CYCLE_TIME_ms) +
1u;
#else
/* Take array size of 60s moving average */
static float_t MEM_EXT_SDRAM curValues[(60000u / ISA_CURRENT_CYCLE_TIME_ms) + 1u] = {0.0f};
static uint32_t movingAverageCurrentLength = (60000u / ISA_CURRENT_CYCLE_TIME_ms) + 1u;
#endif
#endif
/* Check if minimum algo cycle time > current sensor sample time */
#if ALGO_TICK_ms > ISA_POWER_CYCLE_TIME_ms
#if (MOVING_AVERAGE_DURATION_POWER_CONFIG_ms / ALGO_TICK_ms) > (60000u / ALGO_TICK_ms)
/* If array length of configured time > 60s array take this array size */
static float_t MEM_EXT_SDRAM powValues[(MOVING_AVERAGE_DURATION_POWER_CONFIG_ms / ALGO_TICK_ms) + 1u] = {};
static uint32_t movingAveragePowerLength = (MOVING_AVERAGE_DURATION_POWER_CONFIG_ms / ALGO_TICK_ms) + 1u;
#else
/* Take array size of 60s moving average */
static float_t MEM_EXT_SDRAM powValues[(60000u / ALGO_TICK_ms) + 1] = {};
static uint32_t movingAveragePowerLength = (60000u / ALGO_TICK_ms) + 1u;
#endif
#else
#if (MOVING_AVERAGE_DURATION_POWER_CONFIG_ms / ISA_POWER_CYCLE_TIME_ms) > (60000u / ISA_POWER_CYCLE_TIME_ms)
/* If array length of configured time > 60s array take this array size */
static float_t MEM_EXT_SDRAM powValues[(MOVING_AVERAGE_DURATION_POWER_CONFIG_ms / ISA_POWER_CYCLE_TIME_ms) + 1u] = {};
static uint32_t movingAveragePowerLength = (MOVING_AVERAGE_DURATION_POWER_CONFIG_ms / ISA_POWER_CYCLE_TIME_ms) + 1u;
#else
/* Take array size of 60s moving average */
static float_t MEM_EXT_SDRAM powValues[(60000u / ISA_POWER_CYCLE_TIME_ms) + 1u] = {0.0f};
static uint32_t movingAveragePowerLength = (60000u / ISA_POWER_CYCLE_TIME_ms) + 1u;
#endif
#endif
/** Pointer for current moving average calculation @{*/
static float_t *pMovingAverageCurrentNew = &curValues[0];
static float_t *pMovingAverageCurrent_1s = &curValues[0];
static float_t *pMovingAverageCurrent_5s = &curValues[0];
static float_t *pMovingAverageCurrent_10s = &curValues[0];
static float_t *pMovingAverageCurrent_30s = &curValues[0];
static float_t *pMovingAverageCurrent_60s = &curValues[0];
static float_t *pMovingAverageCurrent_cfg = &curValues[0];
/**@}*/
/** Pointer for power moving average calculation @{*/
static float_t *pMovingAveragePowerNew = &powValues[0];
static float_t *pMovingAveragePower_1s = &powValues[0];
static float_t *pMovingAveragePower_5s = &powValues[0];
static float_t *pMovingAveragePower_10s = &powValues[0];
static float_t *pMovingAveragePower_30s = &powValues[0];
static float_t *pMovingAveragePower_60s = &powValues[0];
static float_t *pMovingAveragePower_cfg = &powValues[0];
/**@}*/
/*========== Extern Constant and Variable Definitions =======================*/
/*========== Static Function Prototypes =====================================*/
/*========== Static Function Implementations ================================*/
/*========== Extern Function Implementations ================================*/
extern void ALGO_MovAverage(void) {
static uint8_t curCounter = 0u;
static uint8_t powCounter = 0u;
static DATA_BLOCK_CURRENT_SENSOR_s curPow_tab = {.header.uniqueId = DATA_BLOCK_ID_CURRENT_SENSOR};
static DATA_BLOCK_MOVING_AVERAGE_s movingAverage_tab = {.header.uniqueId = DATA_BLOCK_ID_MOVING_AVERAGE};
static uint8_t curInit = 0u; /* bit0: 1s, bit1: 5s, bit2: 10s, bit3: 30s, bit4: 60s, bit5: cfg */
static uint8_t powInit = 0u; /* bit0: 1s, bit1: 5s, bit2: 10s, bit3: 30s, bit4: 60s, bit5: cfg */
static uint8_t newValues = 0u;
float_t divider = 0.0f;
bool validValues = true;
DATA_READ_DATA(&curPow_tab);
DATA_READ_DATA(&movingAverage_tab);
/* Check if new current value */
if (curCounter != curPow_tab.newCurrent) {
curCounter = curPow_tab.newCurrent;
/* Check if valid values */
for (uint8_t s = 0u; s < BS_NR_OF_STRINGS; s++) {
if (curPow_tab.invalidCurrentMeasurement[s] != 0u) {
validValues = false;
}
}
if (validValues == true) {
/* new Values -> Save later in database */
newValues = 1u;
int32_t packCurrent = 0;
for (uint8_t s = 0u; s < BS_NR_OF_STRINGS; s++) {
packCurrent += curPow_tab.current_mA[s];
}
/* Add value to array and calculate new moving average values */
*pMovingAverageCurrentNew = packCurrent;
/* Calculate new moving average - first add new value */
divider = ALGO_NUMBER_AVERAGE_VALUES_CUR_1s;
movingAverage_tab.movingAverageCurrent1sInterval_mA += (*pMovingAverageCurrentNew) / divider;
divider = ALGO_NUMBER_AVERAGE_VALUES_CUR_5s;
movingAverage_tab.movingAverageCurrent5sInterval_mA += (*pMovingAverageCurrentNew) / divider;
divider = ALGO_NUMBER_AVERAGE_VALUES_CUR_10s;
movingAverage_tab.movingAverageCurrent10sInterval_mA += (*pMovingAverageCurrentNew) / divider;
divider = ALGO_NUMBER_AVERAGE_VALUES_CUR_30s;
movingAverage_tab.movingAverageCurrent30sInterval_mA += (*pMovingAverageCurrentNew) / divider;
divider = ALGO_NUMBER_AVERAGE_VALUES_CUR_60s;
movingAverage_tab.movingAverageCurrent60sInterval_mA += (*pMovingAverageCurrentNew) / divider;
divider = ALGO_NUMBER_AVERAGE_VALUES_CUR_CFG;
movingAverage_tab.movingAverageCurrentConfigurableInterval_mA += (*pMovingAverageCurrentNew) / divider;
/* Then, increment pointer and subtract oldest value when respective window is filled with data */
pMovingAverageCurrentNew++;
if ((curInit & 0x01u) == 0x01u) {
divider = ALGO_NUMBER_AVERAGE_VALUES_CUR_1s;
movingAverage_tab.movingAverageCurrent1sInterval_mA -= ((*pMovingAverageCurrent_1s) / divider);
pMovingAverageCurrent_1s++;
} else {
if (pMovingAverageCurrentNew == &curValues[ALGO_NUMBER_AVERAGE_VALUES_CUR_1s]) {
curInit |= 0x01u;
}
}
if ((curInit & 0x02u) == 0x02u) {
divider = ALGO_NUMBER_AVERAGE_VALUES_CUR_5s;
movingAverage_tab.movingAverageCurrent5sInterval_mA -= (*pMovingAverageCurrent_5s) / divider;
pMovingAverageCurrent_5s++;
} else {
if (pMovingAverageCurrentNew == &curValues[ALGO_NUMBER_AVERAGE_VALUES_CUR_5s]) {
curInit |= 0x02u;
}
}
if ((curInit & 0x04u) == 0x04u) {
divider = ALGO_NUMBER_AVERAGE_VALUES_CUR_10s;
movingAverage_tab.movingAverageCurrent10sInterval_mA -= (*pMovingAverageCurrent_10s) / divider;
pMovingAverageCurrent_10s++;
} else {
if (pMovingAverageCurrentNew == &curValues[ALGO_NUMBER_AVERAGE_VALUES_CUR_10s]) {
curInit |= 0x04u;
}
}
if ((curInit & 0x08u) == 0x08u) {
divider = ALGO_NUMBER_AVERAGE_VALUES_CUR_30s;
movingAverage_tab.movingAverageCurrent30sInterval_mA -= (*pMovingAverageCurrent_30s) / divider;
pMovingAverageCurrent_30s++;
} else {
if (pMovingAverageCurrentNew == &curValues[ALGO_NUMBER_AVERAGE_VALUES_CUR_30s]) {
curInit |= 0x08u;
}
}
if ((curInit & 0x10u) == 0x10u) {
divider = ALGO_NUMBER_AVERAGE_VALUES_CUR_60s;
movingAverage_tab.movingAverageCurrent60sInterval_mA -= (*pMovingAverageCurrent_60s) / divider;
pMovingAverageCurrent_60s++;
} else {
if (pMovingAverageCurrentNew == &curValues[ALGO_NUMBER_AVERAGE_VALUES_CUR_60s]) {
curInit |= 0x10u;
}
}
if ((curInit & 0x20u) == 0x20u) {
divider = ALGO_NUMBER_AVERAGE_VALUES_CUR_CFG;
movingAverage_tab.movingAverageCurrentConfigurableInterval_mA -= (*pMovingAverageCurrent_cfg) / divider;
pMovingAverageCurrent_cfg++;
} else {
if (pMovingAverageCurrentNew == &curValues[ALGO_NUMBER_AVERAGE_VALUES_CUR_CFG]) {
curInit |= 0x20u;
}
}
/* Check pointer for buffer overflow */
if (pMovingAverageCurrentNew > &curValues[movingAverageCurrentLength - 1u]) {
pMovingAverageCurrentNew = &curValues[0u];
}
if (pMovingAverageCurrent_1s > &curValues[movingAverageCurrentLength - 1u]) {
pMovingAverageCurrent_1s = &curValues[0u];
}
if (pMovingAverageCurrent_5s > &curValues[movingAverageCurrentLength - 1u]) {
pMovingAverageCurrent_5s = &curValues[0u];
}
if (pMovingAverageCurrent_10s > &curValues[movingAverageCurrentLength - 1u]) {
pMovingAverageCurrent_10s = &curValues[0u];
}
if (pMovingAverageCurrent_30s > &curValues[movingAverageCurrentLength - 1u]) {
pMovingAverageCurrent_30s = &curValues[0u];
}
if (pMovingAverageCurrent_60s > &curValues[movingAverageCurrentLength - 1u]) {
pMovingAverageCurrent_60s = &curValues[0u];
}
if (pMovingAverageCurrent_cfg > &curValues[movingAverageCurrentLength - 1u]) {
pMovingAverageCurrent_cfg = &curValues[0u];
}
}
}
validValues = true;
/* Check if new power value */
if (powCounter != curPow_tab.newPower) {
powCounter = curPow_tab.newPower;
/* Check if valid values */
for (uint8_t s = 0u; s < BS_NR_OF_STRINGS; s++) {
if (curPow_tab.invalidPowerMeasurement[s] != 0u) {
validValues = false;
}
}
if (validValues == true) {
newValues = 1u;
int32_t packPower = 0;
for (uint8_t s = 0u; s < BS_NR_OF_STRINGS; s++) {
packPower += curPow_tab.power_W[s];
}
/* Add value to array and calculate new moving mean values */
*pMovingAveragePowerNew = packPower;
/* Calculate new moving means - first add new value */
divider = ALGO_NUMBER_AVERAGE_VALUES_POW_1s;
movingAverage_tab.movingAveragePower1sInterval_mA += (*pMovingAveragePowerNew) / divider;
divider = ALGO_NUMBER_AVERAGE_VALUES_POW_5s;
movingAverage_tab.movingAveragePower5sInterval_mA += (*pMovingAveragePowerNew) / divider;
divider = ALGO_NUMBER_AVERAGE_VALUES_POW_10s;
movingAverage_tab.movingAveragePower10sInterval_mA += (*pMovingAveragePowerNew) / divider;
divider = ALGO_NUMBER_AVERAGE_VALUES_POW_30s;
movingAverage_tab.movingAveragePower30sInterval_mA += (*pMovingAveragePowerNew) / divider;
divider = ALGO_NUMBER_AVERAGE_VALUES_POW_60s;
movingAverage_tab.movingAveragePower60sInterval_mA += (*pMovingAveragePowerNew) / divider;
divider = ALGO_NUMBER_AVERAGE_VALUES_POW_CFG;
movingAverage_tab.movingAveragePowerConfigurableInterval_mA += (*pMovingAveragePowerNew) / divider;
/* Then, increment pointer and subtract oldest value when respective window is filled with data */
pMovingAveragePowerNew++;
if ((powInit & 0x01u) == 0x01u) {
divider = ALGO_NUMBER_AVERAGE_VALUES_POW_1s;
movingAverage_tab.movingAveragePower1sInterval_mA -= ((*pMovingAveragePower_1s) / divider);
pMovingAveragePower_1s++;
} else {
if (pMovingAveragePowerNew == &powValues[ALGO_NUMBER_AVERAGE_VALUES_POW_1s]) {
powInit |= 0x01u;
}
}
if ((powInit & 0x02u) == 0x02u) {
divider = ALGO_NUMBER_AVERAGE_VALUES_POW_5s;
movingAverage_tab.movingAveragePower5sInterval_mA -= ((*pMovingAveragePower_5s) / divider);
pMovingAveragePower_5s++;
} else {
if (pMovingAveragePowerNew == &powValues[ALGO_NUMBER_AVERAGE_VALUES_POW_5s]) {
powInit |= 0x02u;
}
}
if ((powInit & 0x04u) == 0x04u) {
divider = ALGO_NUMBER_AVERAGE_VALUES_POW_10s;
movingAverage_tab.movingAveragePower10sInterval_mA -= ((*pMovingAveragePower_10s) / divider);
pMovingAveragePower_10s++;
} else {
if (pMovingAveragePowerNew == &powValues[ALGO_NUMBER_AVERAGE_VALUES_POW_10s]) {
powInit |= 0x04u;
}
}
if ((powInit & 0x08u) == 0x08u) {
divider = ALGO_NUMBER_AVERAGE_VALUES_POW_30s;
movingAverage_tab.movingAveragePower30sInterval_mA -= ((*pMovingAveragePower_30s) / divider);
pMovingAveragePower_30s++;
} else {
if (pMovingAveragePowerNew == &powValues[ALGO_NUMBER_AVERAGE_VALUES_POW_30s]) {
powInit |= 0x08u;
}
}
if ((powInit & 0x10u) == 0x10u) {
divider = ALGO_NUMBER_AVERAGE_VALUES_POW_60s;
movingAverage_tab.movingAveragePower60sInterval_mA -= ((*pMovingAveragePower_60s) / divider);
pMovingAveragePower_60s++;
} else {
if (pMovingAveragePowerNew == &powValues[ALGO_NUMBER_AVERAGE_VALUES_POW_60s]) {
powInit |= 0x10u;
}
}
if ((powInit & 0x20u) == 0x20u) {
divider = ALGO_NUMBER_AVERAGE_VALUES_POW_CFG;
movingAverage_tab.movingAveragePowerConfigurableInterval_mA -= ((*pMovingAveragePower_cfg) / divider);
pMovingAveragePower_cfg++;
} else {
if (pMovingAveragePowerNew == &powValues[ALGO_NUMBER_AVERAGE_VALUES_POW_CFG]) {
powInit |= 0x20u;
}
}
/* Check pointer for buffer overflow */
if (pMovingAveragePowerNew > &powValues[movingAveragePowerLength - 1u]) {
pMovingAveragePowerNew = &powValues[0u];
}
if (pMovingAveragePower_1s > &powValues[movingAveragePowerLength - 1u]) {
pMovingAveragePower_1s = &powValues[0u];
}
if (pMovingAveragePower_5s > &powValues[movingAveragePowerLength - 1u]) {
pMovingAveragePower_5s = &powValues[0u];
}
if (pMovingAveragePower_10s > &powValues[movingAveragePowerLength - 1u]) {
pMovingAveragePower_10s = &powValues[0u];
}
if (pMovingAveragePower_30s > &powValues[movingAveragePowerLength - 1u]) {
pMovingAveragePower_30s = &powValues[0u];
}
if (pMovingAveragePower_60s > &powValues[movingAveragePowerLength - 1u]) {
pMovingAveragePower_60s = &powValues[0u];
}
if (pMovingAveragePower_cfg > &powValues[movingAveragePowerLength - 1u]) {
pMovingAveragePower_cfg = &powValues[0u];
}
}
}
if (newValues == 1u) {
newValues = 0;
DATA_WRITE_DATA(&movingAverage_tab);
}
}
/*========== Externalized Static Function Implementations (Unit Test) =======*/
#ifdef UNITY_UNIT_TEST
#endif
|
8c9b36e4147298323567080794f0b262d59f0643
|
f62ddee2dcadcae0e90f969be513b04e16dabf58
|
/data/source/yaltools/mount_handle/get_file_entry_by_path-file_entry_initialize.c
|
7dbd69cf1af29e83a2886eed60817adacd2575f6
|
[
"Apache-2.0"
] |
permissive
|
libyal/libyal
|
30bccf56471dbf874292fe32d5d9173fd470df0e
|
124111953917f65782a66a80e96a502ce2331b09
|
refs/heads/main
| 2023-07-25T09:25:46.068071
| 2023-07-08T09:56:44
| 2023-07-08T09:56:44
| 23,780,738
| 196
| 30
|
Apache-2.0
| 2022-11-27T19:01:42
| 2014-09-08T05:57:58
|
C
|
UTF-8
|
C
| false
| false
| 399
|
c
|
get_file_entry_by_path-file_entry_initialize.c
|
if( mount_file_entry_initialize(
file_entry,
mount_handle->file_system,
filename,
filename_length,
${mount_tool_file_entry_type_name},
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to initialize file entry.",
function );
goto on_error;
}
|
b7cf2e37b797a2f4cf5595b270062aa672438679
|
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
|
/lib/libc/musl/src/env/getenv.c
|
a90d39cf74f35bf0324ea7dea20ecdabdb5030dd
|
[
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-musl-exception",
"MIT"
] |
permissive
|
ziglang/zig
|
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
|
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
|
refs/heads/master
| 2023-08-31T13:16:45.980913
| 2023-08-31T05:50:29
| 2023-08-31T05:50:29
| 40,276,274
| 25,560
| 2,399
|
MIT
| 2023-09-14T21:09:50
| 2015-08-06T00:51:28
|
Zig
|
UTF-8
|
C
| false
| false
| 288
|
c
|
getenv.c
|
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char *getenv(const char *name)
{
size_t l = __strchrnul(name, '=') - name;
if (l && !name[l] && __environ)
for (char **e = __environ; *e; e++)
if (!strncmp(name, *e, l) && l[*e] == '=')
return *e + l+1;
return 0;
}
|
6b40a4f922594d8a16ff4c66cc61e0599fe280ba
|
f9e7d65cb784c01a0200145ba8d289afe41d4a56
|
/baseboard/fwk/fan.c
|
735139e54d306c4ba57a664f951f7c17ee975837
|
[
"BSD-3-Clause"
] |
permissive
|
FrameworkComputer/EmbeddedController
|
ad7086769e87d0a4179eae96a7c9ff5e383ff54e
|
f6d6b927eed71550d3475411cfc3e59abe5cef2a
|
refs/heads/hx20-hx30
| 2023-08-08T20:45:10.621169
| 2023-05-26T07:03:59
| 2023-05-26T07:03:59
| 447,021,040
| 846
| 48
|
BSD-3-Clause
| 2023-05-26T07:04:59
| 2022-01-12T00:11:14
|
C
|
UTF-8
|
C
| false
| false
| 6,714
|
c
|
fan.c
|
/* Copyright 2020 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* MCHP MEC fan control module. */
/* This assumes 2-pole fan. For each rotation, 5 edges are measured. */
#include "common.h"
#include "console.h"
#include "fan.h"
#include "gpio.h"
#include "hooks.h"
#include "host_command.h"
#include "host_command_customization.h"
#include "pwm.h"
#include "pwm_chip.h"
#include "registers.h"
#include "tfdp_chip.h"
#include "util.h"
#include "math_util.h"
#include "timer.h"
#include "chipset.h"
#define CPRINTS(format, args...) cprints(CC_THERMAL, format, ## args)
#define CPRINTF(format, args...) cprintf(CC_THERMAL, format, ## args)
/* Maximum tach reading/target value */
#define MAX_TACH 0xffff
/* Tach target value for disable fan */
#define FAN_OFF_TACH 0xffff
/*
* RPM = (n - 1) * m * f * 60 / poles / TACH
* n = number of edges = 9
* m = multiplier defined by RANGE = 1 in our case
* f = 100K
* poles = 2
*/
#define TACH_TO_RPM(tach) ((2*100000*60) / MAX((tach), 1))
#define FAN_PID_I_INV 100
#define FAN_PID_I_MAX (10*FAN_PID_I_INV)
#define STABLE_RPM 2200
static int rpm_setting[FAN_CH_COUNT];
static int duty_setting[FAN_CH_COUNT];
static int integral_factor[FAN_CH_COUNT];
static int in_rpm_mode = 1;
void fan_set_enabled(int ch, int enabled)
{
if (in_rpm_mode) {
if (enabled) {
fan_set_rpm_target(ch, rpm_setting[ch]);
pwm_enable(ch, enabled);
} else {
integral_factor[ch] = 0;
}
} else {
if (enabled) {
pwm_enable(ch, enabled);
fan_set_duty(ch, duty_setting[ch]);
} else {
pwm_enable(ch, enabled);
fan_set_duty(ch, 0);
}
}
}
int fan_get_enabled(int ch)
{
return pwm_get_enabled(ch);
}
int fan_rpm_to_percent(int fan, int rpm)
{
int pct, max, min;
if (!rpm) {
pct = 0;
} else {
min = fans[fan].rpm->rpm_min;
max = fans[fan].rpm->rpm_max;
if (rpm < min)
rpm = min;
else if (rpm > max)
rpm = max;
if (rpm <= STABLE_RPM) {
pct = rpm / 100;
return pct;
} else if (rpm <= 4000)
min = 1040 + (28 * ((rpm - STABLE_RPM) / 100));
else if (rpm <= 5200)
min = 1040 + (20 * ((rpm - STABLE_RPM) / 100));
/* make formula More in line with the actual-fan speed -
* Note that this will limit the fan % to about 94%
* if we want a performance mode we can tweak this
* to get a few more % of fan speed to unlock additional
* cooling TODO FRAMEWORK */
pct = (rpm - min) / ((FAN_HARDARE_MAX - min) / 100);
/*CPRINTS(" Fan max min : %d , %d", max, min);*/
}
/*CPRINTS(" Fan PCT = %d ", pct);*/
return pct;
}
void fan_set_duty(int ch, int percent)
{
if (ch < 0 || ch > MCHP_TACH_ID_MAX || ch > FAN_CH_COUNT)
return;
if (percent < 0)
percent = 0;
else if (percent > 100)
percent = 100;
duty_setting[ch] = percent;
pwm_set_duty(ch, percent);
}
int fan_get_duty(int ch)
{
if (ch < 0 || ch > MCHP_TACH_ID_MAX || ch > FAN_CH_COUNT)
return -1;
return duty_setting[ch];
}
int fan_get_rpm_mode(int ch)
{
return in_rpm_mode;
}
void fan_set_rpm_mode(int ch, int rpm_mode)
{
in_rpm_mode = rpm_mode;
}
int fan_get_rpm_actual(int ch)
{
if (ch < 0 || ch > MCHP_TACH_ID_MAX || ch > FAN_CH_COUNT)
return -1;
if (MCHP_TACH_CTRL_CNT(ch) == 0xffff)
return 0;
else
return TACH_TO_RPM(MCHP_TACH_CTRL_CNT(ch));
}
int fan_get_rpm_target(int ch)
{
if (ch < 0 || ch > FAN_CH_COUNT)
return -1;
return rpm_setting[ch];
}
timestamp_t fan_spindown_time;
/**
* fan gain should not be greater than 1 for stability
* since fan goes up to 5500rpm and pwm is 0-100%
* then we can choose something less than
* 1/(100/5500)
* This is called at Hhz from the thermal task if active
*/
void fan_set_rpm_target(int ch, int rpm)
{
int delta;
int pct = 0;
bool requested_rpm_same = rpm_setting[ch] == rpm;
if (ch < 0 || ch > MCHP_TACH_ID_MAX || ch > FAN_CH_COUNT)
return;
/* Keep the fan spinning at min speed for a minute after we transition to 0 rpm*/
if (rpm == 0 && rpm_setting[ch] != rpm) {
timestamp_t now = get_time();
fan_spindown_time.val = now.val + 60*SECOND;
}
rpm_setting[ch] = rpm;
if (chipset_in_state(CHIPSET_STATE_ON) && rpm == 0 &&
!timestamp_expired(fan_spindown_time, NULL)) {
rpm = 1200;
}
pct = fan_rpm_to_percent(ch, rpm);
delta = rpm - fan_get_rpm_actual(ch);
/**
* Only integrate in steady state
* allow the fan to ramp naturally in response to a step
* assuming a time delta of around a second or so otherwise
* we will integrate during the fan ramp up/ramp down time
* also do not integrate when the fan is off
*/
if (requested_rpm_same && rpm > 0)
integral_factor[ch] += delta;
duty_setting[ch] = pct;
/*Cap integral factor at FAN_PID_I_MAX, to prevent runaway conditions */
integral_factor[ch] = MIN(MAX(integral_factor[ch], -FAN_PID_I_MAX),
FAN_PID_I_MAX);
#if 0
CPRINTS(" Fan delta : %drpm %dintegral, commanded %d",
delta, integral_factor[ch],
pct +
integral_factor[ch]/FAN_PID_I_INV);
#endif
if (rpm == 0)
integral_factor[ch] = 0;
fan_set_duty(ch, pct + integral_factor[ch]/FAN_PID_I_INV);
}
enum fan_status fan_get_status(int ch)
{
/* TODO */
if (fan_get_rpm_actual(ch) == 0)
return FAN_STATUS_STOPPED;
if (ABS(integral_factor[ch]) >= FAN_PID_I_MAX)
return FAN_STATUS_FRUSTRATED;
if (ABS(fan_get_rpm_actual(ch)-fan_get_rpm_target(ch)) > 200)
return FAN_STATUS_CHANGING;
return FAN_STATUS_LOCKED;
}
int fan_is_stalled(int ch)
{
/* Must be enabled with non-zero target to stall */
if (!fan_get_enabled(ch) || fan_get_rpm_target(ch) == 0)
return 0;
/* Check for stall condition */
return fan_get_status(ch) == FAN_STATUS_STOPPED;
}
void fan_channel_setup(int ch, unsigned int flags)
{
int i;
for (i = 0; i < FAN_CH_COUNT; ++i) {
pwm_slp_en(pwm_channels[i].channel, 0);
pwm_configure(pwm_channels[i].channel,
pwm_channels[i].flags & PWM_CONFIG_ACTIVE_LOW,
pwm_channels[i].flags & PWM_CONFIG_ALT_CLOCK);
pwm_set_duty(i, 0);
MCHP_PCR_SLP_DIS_DEV(MCHP_PCR_TACH0);
MCHP_TACH_CTRL(i) = MCHP_TACH_CTRL_MODE_SELECT +
MCHP_TACH_CTRL_ENABLE +
MCHP_TACH_CTRL_FILTER_EN +
MCHP_TACH_CTRL_TACH_EDGES_9;
}
}
/*****************************************************************************/
/* Host commands */
static enum ec_status
hc_pwm_get_fan_actual_rpm(struct host_cmd_handler_args *args)
{
struct ec_response_pwm_get_actual_fan_rpm *r = args->response;
if (FAN_CH_COUNT == 0)
return EC_ERROR_INVAL;
r->rpm = fan_get_rpm_actual(FAN_CH(0));
args->response_size = sizeof(*r);
return EC_SUCCESS;
}
DECLARE_HOST_COMMAND(EC_CMD_PWM_GET_FAN_ACTUAL_RPM,
hc_pwm_get_fan_actual_rpm,
EC_VER_MASK(0));
|
472a807a7cbcbaa23a2e253f414f4ecf7ff65680
|
0bcd128368e2de959ca648960ffd7944067fcf27
|
/src/core/SkReadPixelsRec.h
|
959b51b3b52aa0fbbc371a4167f0633cface932d
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
google/skia
|
ac6e39179cd33cf0c8a46d29c1a70bf78b4d74ee
|
bf6b239838d3eb56562fffd0856f4047867ae771
|
refs/heads/main
| 2023-08-31T21:03:04.620734
| 2023-08-31T18:24:15
| 2023-08-31T20:20:26
| 15,773,229
| 8,064
| 1,487
|
BSD-3-Clause
| 2023-09-11T13:42:07
| 2014-01-09T17:09:57
|
C++
|
UTF-8
|
C
| false
| false
| 1,285
|
h
|
SkReadPixelsRec.h
|
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkReadPixelsRec_DEFINED
#define SkReadPixelsRec_DEFINED
#include "include/core/SkImageInfo.h"
#include "include/core/SkPixmap.h"
#include <cstddef>
/**
* Helper class to package and trim the parameters passed to readPixels()
*/
struct SkReadPixelsRec {
SkReadPixelsRec(const SkImageInfo& info, void* pixels, size_t rowBytes, int x, int y)
: fPixels(pixels)
, fRowBytes(rowBytes)
, fInfo(info)
, fX(x)
, fY(y)
{}
SkReadPixelsRec(const SkPixmap& pm, int x, int y)
: fPixels(pm.writable_addr())
, fRowBytes(pm.rowBytes())
, fInfo(pm.info())
, fX(x)
, fY(y)
{}
void* fPixels;
size_t fRowBytes;
SkImageInfo fInfo;
int fX;
int fY;
/*
* On true, may have modified its fields (except fRowBytes) to make it a legal subset
* of the specified src width/height.
*
* On false, leaves self unchanged, but indicates that it does not overlap src, or
* is not valid (e.g. bad fInfo) for readPixels().
*/
bool trim(int srcWidth, int srcHeight);
};
#endif
|
f25c911b1810508a6b5e552f52eb6aa55cdfcdb6
|
00613931db0dc1113d628b673b8a242fee684fac
|
/Core/Atom/AtomEcho/Arduino/StreamHttpClient_ECHO/src/libmad/fixed.c
|
928c011bac66f84a8631ed8cd6c92fb8f91a538a
|
[
"GPL-3.0-only",
"GPL-1.0-or-later",
"GPL-2.0-or-later",
"GPL-2.0-only",
"LicenseRef-scancode-proprietary-license",
"MIT"
] |
permissive
|
m5stack/M5-ProductExampleCodes
|
437b9413d92adb43c873149dd768da3d0b979869
|
1bc38736e61a362080d1dffc4020b3a2a1dff6ae
|
refs/heads/master
| 2022-09-16T07:38:54.184583
| 2022-07-21T01:05:46
| 2022-07-21T01:05:46
| 156,688,327
| 316
| 524
|
MIT
| 2022-07-21T01:05:47
| 2018-11-08T10:17:23
|
C
|
UTF-8
|
C
| false
| false
| 1,794
|
c
|
fixed.c
|
/*
* libmad - MPEG audio decoder library
* Copyright (C) 2000-2004 Underbit Technologies, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: fixed.c,v 1.13 2004/01/23 09:41:32 rob Exp $
*/
#pragma GCC optimize ("O3")
# include "config.h"
# include "global.h"
# include "fixed.h"
/*
* NAME: fixed->abs()
* DESCRIPTION: return absolute value of a fixed-point number
*/
mad_fixed_t mad_f_abs(mad_fixed_t x)
{
return x < 0 ? -x : x;
}
/*
* NAME: fixed->div()
* DESCRIPTION: perform division using fixed-point math
*/
mad_fixed_t mad_f_div(mad_fixed_t x, mad_fixed_t y)
{
mad_fixed_t q, r;
unsigned int bits;
q = mad_f_abs(x / y);
if (x < 0) {
x = -x;
y = -y;
}
r = x % y;
if (y < 0) {
x = -x;
y = -y;
}
if (q > mad_f_intpart(MAD_F_MAX) &&
!(q == -mad_f_intpart(MAD_F_MIN) && r == 0 && (x < 0) != (y < 0)))
return 0;
for (bits = MAD_F_FRACBITS; bits && r; --bits) {
q <<= 1, r <<= 1;
if (r >= y)
r -= y, ++q;
}
/* round */
if (2 * r >= y)
++q;
/* fix sign */
if ((x < 0) != (y < 0))
q = -q;
return q << bits;
}
|
4ed0017bdcfb9a0252539f61cf4dd249e90ff8a5
|
8e7034a79519ec05d0fb8c6d474b59509a39835f
|
/src/pt2_blep.h
|
4fb51eb094fc3c2e6cf59eb55011fd5cb8080d01
|
[
"BSD-3-Clause"
] |
permissive
|
8bitbubsy/pt2-clone
|
f390494cf60f49e428c56ed3496201f457477b5f
|
9593a88d48b93006533d054c89b04a79e9d56014
|
refs/heads/master
| 2023-08-29T06:58:24.551643
| 2023-08-16T10:02:32
| 2023-08-16T10:02:32
| 225,353,154
| 350
| 34
|
BSD-3-Clause
| 2023-01-01T11:27:27
| 2019-12-02T11:00:24
|
C
|
UTF-8
|
C
| false
| false
| 1,284
|
h
|
pt2_blep.h
|
// these BLEP routines were coded by aciddose
#pragma once
#include <stdint.h>
#include "pt2_paula.h" // PAULA_VOICES
/* aciddose:
** information on blep variables
**
** ZC = zero crossings, the number of ripples in the impulse
** OS = oversampling, how many samples per zero crossing are taken
** SP = step size per output sample, used to lower the cutoff (play the impulse slower)
** NS = number of samples of impulse to insert
** RNS = the lowest power of two greater than NS, minus one (used to wrap output buffer)
**
** ZC and OS are here only for reference, they depend upon the data in the table and can't be changed.
** SP, the step size can be any number lower or equal to OS, as long as the result NS remains an integer.
** for example, if ZC=8,OS=5, you can set SP=1, the result is NS=40, and RNS must then be 63.
** the result of that is the filter cutoff is set at nyquist * (SP/OS), in this case nyquist/5.
*/
#define BLEP_ZC 16
#define BLEP_OS 16
#define BLEP_SP 16
#define BLEP_NS (BLEP_ZC * BLEP_OS / BLEP_SP)
#define BLEP_RNS 31 // RNS = (2^ > NS) - 1
typedef struct blep_t
{
int32_t index, samplesLeft;
double dBuffer[BLEP_RNS + 1], dLastValue;
} blep_t;
void blepAdd(blep_t *b, double dOffset, double dAmplitude);
double blepRun(blep_t *b, double dInput);
|
38fc6a10e97b067e35cd2e76ae2241a30db152e4
|
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
|
/Engine/Source/ThirdParty/Oculus/LibOVRPlatform/LibOVRPlatform/include/OVR_Voip_LowLevel.h
|
471276840d3c9cd502717465e37046a9d2cac53a
|
[
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
windystrife/UnrealEngine_NVIDIAGameWorks
|
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
refs/heads/4.18-GameWorks
| 2023-03-11T02:50:08.471040
| 2022-01-13T20:50:29
| 2022-01-13T20:50:29
| 124,100,479
| 262
| 179
|
MIT
| 2022-12-16T05:36:38
| 2018-03-06T15:44:09
|
C++
|
UTF-8
|
C
| false
| false
| 762
|
h
|
OVR_Voip_LowLevel.h
|
#ifndef OVR_VOIP_LOWLEVEL_H
#define OVR_VOIP_LOWLEVEL_H
#include "OVR_Platform_Defs.h"
#include "OVR_Types.h"
#include "OVR_VoipEncoder.h"
#include "OVR_VoipDecoder.h"
#include "OVR_Microphone.h"
#ifdef __cplusplus
extern "C" {
#endif
OVRP_PUBLIC_FUNCTION(ovrVoipEncoderHandle) ovr_Voip_CreateEncoder();
OVRP_PUBLIC_FUNCTION(void) ovr_Voip_DestroyEncoder(ovrVoipEncoderHandle encoder);
OVRP_PUBLIC_FUNCTION(ovrVoipDecoderHandle) ovr_Voip_CreateDecoder();
OVRP_PUBLIC_FUNCTION(void) ovr_Voip_DestroyDecoder(ovrVoipDecoderHandle decoder);
OVRP_PUBLIC_FUNCTION(ovrMicrophoneHandle) ovr_Microphone_Create();
OVRP_PUBLIC_FUNCTION(void) ovr_Microphone_Destroy(ovrMicrophoneHandle obj);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // OVR_VOIP_LOWLEVEL_H
|
8fcecbd4581cde943b38c79c9e8d3a8be5a6ca5f
|
bed3ac926beac0f4e0293303d7b2a6031ee476c9
|
/Modules/ThirdParty/NrrdIO/src/NrrdIO/biffbiff.c
|
4a3ea609d39526b7a9163f68a231cc1c264baf96
|
[
"Zlib",
"LicenseRef-scancode-unknown-license-reference",
"IJG",
"LicenseRef-scancode-proprietary-license",
"SMLNJ",
"BSD-3-Clause",
"BSD-4.3TAHOE",
"LicenseRef-scancode-free-unknown",
"Spencer-86",
"LicenseRef-scancode-llnl",
"FSFUL",
"Libpng",
"libtiff",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-hdf5",
"MIT",
"NTP",
"LicenseRef-scancode-mit-old-style",
"GPL-1.0-or-later",
"MPL-2.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] |
permissive
|
InsightSoftwareConsortium/ITK
|
ed9dbbc5b8b3f7511f007c0fc0eebb3ad37b88eb
|
3eb8fd7cdfbc5ac2d0c2e5e776848a4cbab3d7e1
|
refs/heads/master
| 2023-08-31T17:21:47.754304
| 2023-08-31T00:58:51
| 2023-08-31T14:12:21
| 800,928
| 1,229
| 656
|
Apache-2.0
| 2023-09-14T17:54:00
| 2010-07-27T15:48:04
|
C++
|
UTF-8
|
C
| false
| false
| 10,377
|
c
|
biffbiff.c
|
/*
NrrdIO: stand-alone code for basic nrrd functionality
Copyright (C) 2013, 2012, 2011, 2010, 2009 University of Chicago
Copyright (C) 2008, 2007, 2006, 2005 Gordon Kindlmann
Copyright (C) 2004, 2003, 2002, 2001, 2000, 1999, 1998 University of Utah
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "NrrdIO.h"
#include "privateBiff.h"
/*
** Until Teem has its own printf implementation, this will have to do;
** it is imperfect because these are not functionally identical.
*/
#if defined(WIN32) || defined(_WIN32)
# define snprintf _snprintf
#endif
static biffMsg **
_bmsg=NULL; /* master array of biffMsg pointers */
static unsigned int
_bmsgNum=0; /* length of _biffErr == # keys maintained */
static airArray *
_bmsgArr=NULL; /* air array of _biffErr and _biffNum */
#define __INCR 2
typedef union {
biffMsg ***b;
void **v;
} _beu;
/*
** _bmsgStart()
**
** allocates data structers needed by biff. Panics if
** anything goes wrong.
**
** NOTE: Can be harmlessly called multiple times.
*/
static void
_bmsgStart(void) {
static const char me[]="[biff] _bmsgStart";
_beu uu;
if (_bmsgArr) {
/* its non-NULL, must have been called already */
return;
}
uu.b = &_bmsg;
_bmsgArr = airArrayNew(uu.v, &_bmsgNum, sizeof(biffMsg*), __INCR);
if (!_bmsgArr) {
fprintf(stderr, "%s: PANIC: couldn't allocate internal data\n", me);
/* exit(1); */
}
/* airArrayPointerCB(_bmsgArr, NULL, (airMopper)biffMsgNix);*/
return;
}
static void
_bmsgFinish(void) {
if (_bmsgArr) {
/* setting _bmsgArr to NULL is needed to put biff back in initial state
so that next calls to biff re-trigger _bmsgStart() */
_bmsgArr = airArrayNuke(_bmsgArr);
}
return;
}
/*
** _bmsgFind()
**
** returns the biffMsg (in _bmsg) of the entry with the given key, or
** NULL if it was not found
*/
static biffMsg *
_bmsgFind(const char *key) {
static const char me[]="[biff] _bmsgFind";
biffMsg *msg;
unsigned int ii;
if (!key) {
fprintf(stderr, "%s: PANIC got NULL key", me);
return NULL; /* exit(1); */
}
msg = NULL;
if (_bmsgNum) {
for (ii=0; ii<_bmsgNum; ii++) {
if (!strcmp(_bmsg[ii]->key, key)) {
msg = _bmsg[ii];
break;
}
}
}
return msg;
}
/*
** assumes that msg really is in _bmsg[]
*/
static unsigned int
_bmsgFindIdx(biffMsg *msg) {
unsigned int ii;
for (ii=0; ii<_bmsgNum; ii++) {
if (msg == _bmsg[ii]) {
break;
}
}
return ii;
}
/*
** _bmsgAdd()
**
** if given key already has a biffMsg in _bmsg, returns that.
** otherise, adds a new biffMsg for given key to _bmsg, and returns it
** panics if there is a problem
*/
static biffMsg *
_bmsgAdd(const char *key) {
static const char me[]="[biff] _bmsgAdd";
unsigned int ii;
biffMsg *msg;
msg = NULL;
/* find if key exists already */
for (ii=0; ii<_bmsgNum; ii++) {
if (!strcmp(key, _bmsg[ii]->key)) {
msg = _bmsg[ii];
break;
}
}
if (!msg) {
/* have to add new biffMsg */
ii = airArrayLenIncr(_bmsgArr, 1);
if (!_bmsg) {
fprintf(stderr, "%s: PANIC: couldn't accommodate one more key\n", me);
return NULL; /* exit(1); */
}
msg = _bmsg[ii] = biffMsgNew(key);
}
return msg;
}
/***********************************************************************/
/***********************************************************************/
/*
******** biffAdd()
**
** Adds string "err" at key "key", whether or not there are any
** existing messages there. Since biffSet() was killed
** Wed Apr 20 11:11:51 EDT 2005, this has become the main biff
** function.
*/
void
biffAdd(const char *key, const char *err) {
biffMsg *msg;
_bmsgStart();
msg = _bmsgAdd(key);
biffMsgAdd(msg, err);
return;
}
static void
_biffAddVL(const char *key, const char *errfmt, va_list args) {
biffMsg *msg;
_bmsgStart();
msg = _bmsgAdd(key);
_biffMsgAddVL(msg, errfmt, args);
return;
}
/*
******** biffAddf()
**
** Adds string "err" at key "key", whether or not there are any
** existing messages there. This version accepts a printf style
** format string as input.
*/
void
biffAddf(const char *key, const char *errfmt, ...) {
va_list args;
va_start(args, errfmt);
_biffAddVL(key, errfmt, args);
va_end(args);
return;
}
#if 0
/*
******** biffAddf_e
**
** calls (eventually) biffMsgAdd if msg is non-NULL, otherwise calls
** biffAdd if msg is NULL.
*/
void
biffAddf_e(biffMsg *msg, const char *key, const char *errfmt, ...) {
va_list args;
va_start(args, errfmt);
if (msg) {
_biffMsgAddVL(msg, errfmt, args);
} else {
_biffAddVL(key, errfmt, args);
}
va_end(args);
return;
}
#endif
/*
******** biffMaybeAdd()
**
** wrapper around biffAdd() but doesn't actually do anything if !useBiff
*/
void
biffMaybeAdd(const char *key, const char *err, int useBiff) {
if (useBiff) {
biffAdd(key, err);
}
return;
}
void
biffMaybeAddf(int useBiff, const char *key, const char *errfmt, ...) {
va_list args;
va_start(args, errfmt);
if (useBiff) {
_biffAddVL(key, errfmt, args);
}
va_end(args);
return;
}
/*
******** biffGet()
**
** creates a string which records all the errors at given key and
** returns it. Returns NULL in case of error. This function should
** be considered a glorified strdup(): it is the callers responsibility
** to free() this string later
*/
char * /*Teem: allocates char* */ /* this comment is an experiment */
biffGet(const char *key) {
static const char me[]="biffGet";
char *ret;
biffMsg *msg;
_bmsgStart();
msg = _bmsgFind(key);
if (!msg) {
static const char err[]="[%s] No information for this key!";
size_t errlen;
fprintf(stderr, "%s: WARNING: no information for key \"%s\"\n", me, key);
errlen = strlen(err)+strlen(key)+1;
ret = AIR_CALLOC(errlen, char);
if (!ret) {
fprintf(stderr, "%s: PANIC: unable to allocate buffer\n", me);
return NULL; /* exit(1); */
}
snprintf(ret, errlen, err, key);
return ret;
}
ret = AIR_CALLOC(biffMsgStrlen(msg)+1, char);
if (!ret) {
fprintf(stderr, "%s: PANIC: unable to allocate buffer\n", me);
return NULL; /* exit(1); */
}
biffMsgStrSet(ret, msg);
return ret;
}
/*
******** biffGetStrlen()
**
** for when you want to allocate the buffer for the biff string, this is
** how you learn its length
*/
unsigned int
biffGetStrlen(const char *key) {
static const char me[]="biffGetStrlen";
biffMsg *msg;
unsigned int len;
_bmsgStart();
msg = _bmsgFind(key);
if (!msg) {
fprintf(stderr, "%s: WARNING: no information for key \"%s\"\n", me, key);
return 0;
}
len = biffMsgStrlen(msg);
len += 1; /* GLK forgets if the convention is that the caller allocates
for one more to include '\0'; this is safer */
return len;
}
/*
******** biffSetStr()
**
** for when you want to allocate the buffer for the biff string, this is
** how you get the error message itself
*/
void
biffSetStr(char *str, const char *key) {
static const char me[]="biffSetStr";
biffMsg *msg;
if (!str) {
fprintf(stderr, "%s: ERROR: got NULL buffer for \"%s\"\n", me, key);
return;
}
_bmsgStart();
msg = _bmsgFind(key);
if (!msg) {
fprintf(stderr, "%s: WARNING: no information for key \"%s\"\n", me, key);
return;
}
biffMsgStrSet(str, msg);
return;
}
/*
******** biffCheck()
**
** sees how many messages there are for a given key;
** Note that this is just a simple wrapper around biffMsgErrNum
*/
unsigned int
biffCheck(const char *key) {
_bmsgStart();
return biffMsgErrNum(_bmsgFind(key));
}
/*
******** biffDone()
**
** frees everything associated with given key, and shrinks list of keys,
** and calls _bmsgFinish() if there are no keys left
*/
void
biffDone(const char *key) {
static const char me[]="biffDone";
unsigned int idx;
biffMsg *msg;
_bmsgStart();
msg = _bmsgFind(key);
if (!msg) {
fprintf(stderr, "%s: WARNING: no information for key \"%s\"\n", me, key);
return;
}
idx = _bmsgFindIdx(msg);
biffMsgNix(msg);
if (_bmsgNum > 1) {
/* if we have more than one key in action, move the last biffMsg
to the position that was just cleared up */
_bmsg[idx] = _bmsg[_bmsgNum-1];
}
airArrayLenIncr(_bmsgArr, -1);
/* if that was the last key, close shop */
if (!_bmsgArr->len) {
_bmsgFinish();
}
return;
}
void
biffMove(const char *destKey, const char *err, const char *srcKey) {
static const char me[]="biffMove";
biffMsg *dest, *src;
_bmsgStart();
dest = _bmsgAdd(destKey);
src = _bmsgFind(srcKey);
if (!src) {
fprintf(stderr, "%s: WARNING: key \"%s\" unknown\n", me, srcKey);
return;
}
biffMsgMove(dest, src, err);
return;
}
static void
_biffMoveVL(const char *destKey, const char *srcKey,
const char *errfmt, va_list args) {
static const char me[]="biffMovev";
biffMsg *dest, *src;
_bmsgStart();
dest = _bmsgAdd(destKey);
src = _bmsgFind(srcKey);
if (!src) {
fprintf(stderr, "%s: WARNING: key \"%s\" unknown\n", me, srcKey);
return;
}
_biffMsgMoveVL(dest, src, errfmt, args);
return;
}
void
biffMovef(const char *destKey, const char *srcKey,
const char *errfmt, ...) {
va_list args;
va_start(args, errfmt);
_biffMoveVL(destKey, srcKey, errfmt, args);
va_end(args);
return;
}
char *
biffGetDone(const char *key) {
char *ret;
_bmsgStart();
ret = biffGet(key);
biffDone(key); /* will call _bmsgFinish if this is the last key */
return ret;
}
/* this is the end */
|
1e2b213d6a350b4e1c5dc4ef30c852f62cbc00ed
|
e1d9c54e9925e30e388a255b53a93cccad0b94cb
|
/kubernetes/model/core_v1_event_series.h
|
8eeb73f76bb19724ed01953fbcdfdaf816e22170
|
[
"curl",
"Apache-2.0"
] |
permissive
|
kubernetes-client/c
|
dd4fd8095485c083e0f40f2b48159b1609a6141b
|
5ac5ff25e9809a92a48111b1f77574b6d040b711
|
refs/heads/master
| 2023-08-13T10:51:03.702497
| 2023-08-07T19:18:32
| 2023-08-07T19:18:32
| 247,958,425
| 127
| 47
|
Apache-2.0
| 2023-09-07T20:07:00
| 2020-03-17T11:59:05
|
C
|
UTF-8
|
C
| false
| false
| 974
|
h
|
core_v1_event_series.h
|
/*
* core_v1_event_series.h
*
* EventSeries contain information on series of events, i.e. thing that was/is happening continuously for some time.
*/
#ifndef _core_v1_event_series_H_
#define _core_v1_event_series_H_
#include <string.h>
#include "../external/cJSON.h"
#include "../include/list.h"
#include "../include/keyValuePair.h"
#include "../include/binary.h"
typedef struct core_v1_event_series_t core_v1_event_series_t;
typedef struct core_v1_event_series_t {
int count; //numeric
char *last_observed_time; //date time
} core_v1_event_series_t;
core_v1_event_series_t *core_v1_event_series_create(
int count,
char *last_observed_time
);
void core_v1_event_series_free(core_v1_event_series_t *core_v1_event_series);
core_v1_event_series_t *core_v1_event_series_parseFromJSON(cJSON *core_v1_event_seriesJSON);
cJSON *core_v1_event_series_convertToJSON(core_v1_event_series_t *core_v1_event_series);
#endif /* _core_v1_event_series_H_ */
|
0788f93514a46293a149397ba462f4ad55159756
|
fbef550c1f0206aac0582a58f7e3db945f442a9a
|
/Pods/Headers/Public/CocoaHTTPServer/HTTPServer.h
|
0f483c2b44598bbb307701adff23013f044dbf67
|
[
"MIT"
] |
permissive
|
Hammerspoon/hammerspoon
|
0f03b4dd2ef3b44ea4c0a1cd0b94fcb513b5f2b7
|
0ccc9d07641a660140d1d2f05b76f682b501a0e8
|
refs/heads/master
| 2023-08-19T01:26:41.898873
| 2023-06-20T22:52:50
| 2023-06-20T22:52:50
| 24,956,772
| 11,379
| 676
|
MIT
| 2023-06-09T02:51:33
| 2014-10-08T19:24:44
|
Objective-C
|
UTF-8
|
C
| false
| false
| 42
|
h
|
HTTPServer.h
|
../../../CocoaHTTPServer/Core/HTTPServer.h
|
0c2b3360562742d5d26cfb50641da865a59ce447
|
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
|
/games/quarry/patches/patch-src_gui-gtk_gtk-utils.c
|
61f5be56e0967a35265550343f2e27b726b6dfe7
|
[] |
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
| 910
|
c
|
patch-src_gui-gtk_gtk-utils.c
|
$NetBSD: patch-src_gui-gtk_gtk-utils.c,v 1.1 2015/03/31 15:38:49 joerg Exp $
--- src/gui-gtk/gtk-utils.c.orig 2015-03-26 10:57:34.000000000 +0000
+++ src/gui-gtk/gtk-utils.c
@@ -87,7 +87,7 @@ static void invoke_toolbar_button_callb
gpointer user_data);
static void set_toolbar_item_sensitive
(GtkWidget *button,
- const GtkUtilsToolbarCallbackArguments *arguments);
+ GtkUtilsToolbarCallbackArguments *arguments);
static void set_widget_sensitivity_on_toggle
(GtkToggleButton *toggle_button, GtkWidget *widget);
@@ -1076,7 +1076,7 @@ gtk_utils_set_toolbar_buttons_sensitive
static void
set_toolbar_item_sensitive (GtkWidget *button,
- const GtkUtilsToolbarCallbackArguments *arguments)
+ GtkUtilsToolbarCallbackArguments *arguments)
{
const GtkUtilsToolbarEntry *button_entry
= g_object_get_qdata (G_OBJECT (button), toolbar_button_entry_quark);
|
8862a2c62ab33fdde75de8a26c2fbfbee40246b0
|
83e7dc1281874779c46dfadcc15b2bb66d8e599c
|
/demos/keypad_encoder/lv_demo_keypad_encoder.c
|
1b55bca103dad08a311203be06ae02a01568f25c
|
[
"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
| 6,495
|
c
|
lv_demo_keypad_encoder.c
|
/**
* @file lv_demo_keypad_encoder.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_demo_keypad_encoder.h"
#if LV_USE_DEMO_KEYPAD_AND_ENCODER
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static void selectors_create(lv_obj_t * parent);
static void text_input_create(lv_obj_t * parent);
static void msgbox_create(void);
static void msgbox_event_cb(lv_event_t * e);
static void ta_event_cb(lv_event_t * e);
/**********************
* STATIC VARIABLES
**********************/
static lv_group_t * g;
static lv_obj_t * tv;
static lv_obj_t * t1;
static lv_obj_t * t2;
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void lv_demo_keypad_encoder(void)
{
g = lv_group_create();
lv_group_set_default(g);
lv_indev_t * indev = NULL;
for(;;) {
indev = lv_indev_get_next(indev);
if(!indev) {
break;
}
lv_indev_type_t indev_type = lv_indev_get_type(indev);
if(indev_type == LV_INDEV_TYPE_KEYPAD) {
lv_indev_set_group(indev, g);
}
if(indev_type == LV_INDEV_TYPE_ENCODER) {
lv_indev_set_group(indev, g);
}
}
tv = lv_tabview_create(lv_scr_act(), LV_DIR_TOP, LV_DPI_DEF / 3);
t1 = lv_tabview_add_tab(tv, "Selectors");
t2 = lv_tabview_add_tab(tv, "Text input");
selectors_create(t1);
text_input_create(t2);
msgbox_create();
}
/**********************
* STATIC FUNCTIONS
**********************/
static void selectors_create(lv_obj_t * parent)
{
lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(parent, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_t * obj;
obj = lv_table_create(parent);
lv_table_set_cell_value(obj, 0, 0, "00");
lv_table_set_cell_value(obj, 0, 1, "01");
lv_table_set_cell_value(obj, 1, 0, "10");
lv_table_set_cell_value(obj, 1, 1, "11");
lv_table_set_cell_value(obj, 2, 0, "20");
lv_table_set_cell_value(obj, 2, 1, "21");
lv_table_set_cell_value(obj, 3, 0, "30");
lv_table_set_cell_value(obj, 3, 1, "31");
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
obj = lv_calendar_create(parent);
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
obj = lv_btnmatrix_create(parent);
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
obj = lv_checkbox_create(parent);
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
obj = lv_slider_create(parent);
lv_slider_set_range(obj, 0, 10);
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
obj = lv_switch_create(parent);
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
obj = lv_spinbox_create(parent);
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
obj = lv_dropdown_create(parent);
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
obj = lv_roller_create(parent);
lv_obj_add_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS);
lv_obj_t * list = lv_list_create(parent);
lv_obj_update_layout(list);
if(lv_obj_get_height(list) > lv_obj_get_content_height(parent)) {
lv_obj_set_height(list, lv_obj_get_content_height(parent));
}
lv_list_add_btn(list, LV_SYMBOL_OK, "Apply");
lv_list_add_btn(list, LV_SYMBOL_CLOSE, "Close");
lv_list_add_btn(list, LV_SYMBOL_EYE_OPEN, "Show");
lv_list_add_btn(list, LV_SYMBOL_EYE_CLOSE, "Hide");
lv_list_add_btn(list, LV_SYMBOL_TRASH, "Delete");
lv_list_add_btn(list, LV_SYMBOL_COPY, "Copy");
lv_list_add_btn(list, LV_SYMBOL_PASTE, "Paste");
}
static void text_input_create(lv_obj_t * parent)
{
lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN);
lv_obj_t * ta1 = lv_textarea_create(parent);
lv_obj_set_width(ta1, LV_PCT(100));
lv_textarea_set_one_line(ta1, true);
lv_textarea_set_placeholder_text(ta1, "Click with an encoder to show a keyboard");
lv_obj_t * ta2 = lv_textarea_create(parent);
lv_obj_set_width(ta2, LV_PCT(100));
lv_textarea_set_one_line(ta2, true);
lv_textarea_set_placeholder_text(ta2, "Type something");
lv_obj_t * kb = lv_keyboard_create(lv_scr_act());
lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_event(ta1, ta_event_cb, LV_EVENT_ALL, kb);
lv_obj_add_event(ta2, ta_event_cb, LV_EVENT_ALL, kb);
}
static void msgbox_create(void)
{
static const char * btns[] = {"Ok", "Cancel", ""};
lv_obj_t * mbox = lv_msgbox_create(NULL, "Hi", "Welcome to the keyboard and encoder demo", btns, false);
lv_obj_add_event(mbox, msgbox_event_cb, LV_EVENT_ALL, NULL);
lv_group_focus_obj(lv_msgbox_get_btns(mbox));
lv_obj_add_state(lv_msgbox_get_btns(mbox), LV_STATE_FOCUS_KEY);
lv_group_focus_freeze(g, true);
lv_obj_align(mbox, LV_ALIGN_CENTER, 0, 0);
lv_obj_t * bg = lv_obj_get_parent(mbox);
lv_obj_set_style_bg_opa(bg, LV_OPA_70, 0);
lv_obj_set_style_bg_color(bg, lv_palette_main(LV_PALETTE_GREY), 0);
}
static void msgbox_event_cb(lv_event_t * e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * msgbox = lv_event_get_current_target(e);
if(code == LV_EVENT_VALUE_CHANGED) {
const char * txt = lv_msgbox_get_active_btn_text(msgbox);
if(txt) {
lv_msgbox_close(msgbox);
lv_group_focus_freeze(g, false);
lv_group_focus_obj(lv_obj_get_child(t1, 0));
lv_obj_scroll_to(t1, 0, 0, LV_ANIM_OFF);
}
}
}
static void ta_event_cb(lv_event_t * e)
{
lv_indev_t * indev = lv_indev_get_act();
if(indev == NULL) return;
lv_indev_type_t indev_type = lv_indev_get_type(indev);
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * ta = lv_event_get_target(e);
lv_obj_t * kb = lv_event_get_user_data(e);
if(code == LV_EVENT_CLICKED && indev_type == LV_INDEV_TYPE_ENCODER) {
lv_keyboard_set_textarea(kb, ta);
lv_obj_clear_flag(kb, LV_OBJ_FLAG_HIDDEN);
lv_group_focus_obj(kb);
lv_group_set_editing(lv_obj_get_group(kb), kb);
lv_obj_set_height(tv, LV_VER_RES / 2);
lv_obj_align(kb, LV_ALIGN_BOTTOM_MID, 0, 0);
}
if(code == LV_EVENT_READY || code == LV_EVENT_CANCEL) {
lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
lv_obj_set_height(tv, LV_VER_RES);
}
}
#endif
|
a5ba3b69752ceb27e544e57b98ec31eafffec125
|
bb157fd805d63dc4cb6d6bfb7cd120f519bc17c1
|
/src/libserver/dns.c
|
abe47dfdc979c4ef0b5c6d9f289b874921559291
|
[
"Apache-2.0"
] |
permissive
|
rspamd/rspamd
|
faffd25f1c084400839589e576a911db1d7d6089
|
c4e54b4daa77bee29862a00900bede165ea16b52
|
refs/heads/master
| 2023-08-30T23:40:52.860552
| 2023-08-29T18:20:25
| 2023-08-29T18:20:25
| 9,549,081
| 1,039
| 291
|
NOASSERTION
| 2023-09-13T10:17:46
| 2013-04-19T16:00:18
|
C
|
UTF-8
|
C
| false
| false
| 29,167
|
c
|
dns.c
|
/*
* Copyright 2023 Vsevolod Stakhov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "contrib/librdns/rdns.h"
#include "config.h"
#include "dns.h"
#include "rspamd.h"
#include "utlist.h"
#include "contrib/librdns/rdns.h"
#include "contrib/librdns/dns_private.h"
#include "contrib/librdns/rdns_ev.h"
#include "unix-std.h"
#include <unicode/uidna.h>
static const gchar *M = "rspamd dns";
static struct rdns_upstream_elt *rspamd_dns_select_upstream(const char *name,
size_t len, void *ups_data);
static struct rdns_upstream_elt *rspamd_dns_select_upstream_retransmit(
const char *name,
size_t len,
struct rdns_upstream_elt *prev_elt,
void *ups_data);
static void rspamd_dns_upstream_ok(struct rdns_upstream_elt *elt,
void *ups_data);
static void rspamd_dns_upstream_fail(struct rdns_upstream_elt *elt,
void *ups_data, const gchar *reason);
static unsigned int rspamd_dns_upstream_count(void *ups_data);
static struct rdns_upstream_context rspamd_ups_ctx = {
.select = rspamd_dns_select_upstream,
.select_retransmit = rspamd_dns_select_upstream_retransmit,
.ok = rspamd_dns_upstream_ok,
.fail = rspamd_dns_upstream_fail,
.count = rspamd_dns_upstream_count,
.data = NULL};
struct rspamd_dns_request_ud {
struct rspamd_async_session *session;
dns_callback_type cb;
gpointer ud;
rspamd_mempool_t *pool;
struct rspamd_task *task;
struct rspamd_symcache_dynamic_item *item;
struct rdns_request *req;
struct rdns_reply *reply;
};
struct rspamd_dns_fail_cache_entry {
const char *name;
gint32 namelen;
enum rdns_request_type type;
};
static const gint8 ascii_dns_table[128] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* HYPHEN-MINUS..FULL STOP */
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, -1,
/* 0..9 digits */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1,
/* LATIN CAPITAL LETTER A..LATIN CAPITAL LETTER Z */
-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* _ */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, 1,
/* LATIN SMALL LETTER A..LATIN SMALL LETTER Z */
-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1};
static guint
rspamd_dns_fail_hash(gconstpointer ptr)
{
struct rspamd_dns_fail_cache_entry *elt =
(struct rspamd_dns_fail_cache_entry *) ptr;
/* We don't care about type when doing hashing */
return rspamd_cryptobox_fast_hash(elt->name, elt->namelen,
rspamd_hash_seed());
}
static gboolean
rspamd_dns_fail_equal(gconstpointer p1, gconstpointer p2)
{
struct rspamd_dns_fail_cache_entry *e1 = (struct rspamd_dns_fail_cache_entry *) p1,
*e2 = (struct rspamd_dns_fail_cache_entry *) p2;
if (e1->type == e2->type && e1->namelen == e2->namelen) {
return memcmp(e1->name, e2->name, e1->namelen) == 0;
}
return FALSE;
}
static void
rspamd_dns_fin_cb(gpointer arg)
{
struct rspamd_dns_request_ud *reqdata = (struct rspamd_dns_request_ud *) arg;
if (reqdata->item) {
rspamd_symcache_set_cur_item(reqdata->task, reqdata->item);
}
if (reqdata->reply) {
reqdata->cb(reqdata->reply, reqdata->ud);
}
else {
struct rdns_reply fake_reply;
memset(&fake_reply, 0, sizeof(fake_reply));
fake_reply.code = RDNS_RC_TIMEOUT;
fake_reply.request = reqdata->req;
fake_reply.resolver = reqdata->req->resolver;
fake_reply.requested_name = reqdata->req->requested_names[0].name;
reqdata->cb(&fake_reply, reqdata->ud);
}
rdns_request_release(reqdata->req);
if (reqdata->item) {
rspamd_symcache_item_async_dec_check(reqdata->task,
reqdata->item, M);
}
if (reqdata->pool == NULL) {
g_free(reqdata);
}
}
static void
rspamd_dns_callback(struct rdns_reply *reply, gpointer ud)
{
struct rspamd_dns_request_ud *reqdata = ud;
reqdata->reply = reply;
if (reqdata->session) {
if (reply->code == RDNS_RC_SERVFAIL &&
reqdata->task &&
reqdata->task->resolver->fails_cache) {
/* Add to cache... */
const gchar *name = reqdata->req->requested_names[0].name;
gchar *target;
gsize namelen;
struct rspamd_dns_fail_cache_entry *nentry;
/* Allocate in a single entry to allow further free in a single call */
namelen = strlen(name);
nentry = g_malloc(sizeof(nentry) + namelen + 1);
target = ((gchar *) nentry) + sizeof(nentry);
rspamd_strlcpy(target, name, namelen + 1);
nentry->type = reqdata->req->requested_names[0].type;
nentry->name = target;
nentry->namelen = namelen;
/* Rdns request is retained there */
rspamd_lru_hash_insert(reqdata->task->resolver->fails_cache,
nentry, rdns_request_retain(reply->request),
reqdata->task->task_timestamp,
reqdata->task->resolver->fails_cache_time);
}
/*
* Ref event to avoid double unref by
* event removing
*/
rdns_request_retain(reply->request);
rspamd_session_remove_event(reqdata->session,
rspamd_dns_fin_cb, reqdata);
}
else {
reqdata->cb(reply, reqdata->ud);
if (reqdata->pool == NULL) {
g_free(reqdata);
}
}
}
struct rspamd_dns_request_ud *
rspamd_dns_resolver_request(struct rspamd_dns_resolver *resolver,
struct rspamd_async_session *session,
rspamd_mempool_t *pool,
dns_callback_type cb,
gpointer ud,
enum rdns_request_type type,
const char *name)
{
struct rdns_request *req;
struct rspamd_dns_request_ud *reqdata = NULL;
guint nlen = strlen(name);
gchar *real_name = NULL;
g_assert(resolver != NULL);
if (resolver->r == NULL) {
return NULL;
}
if (nlen == 0 || nlen > DNS_D_MAXNAME) {
return NULL;
}
if (session && rspamd_session_blocked(session)) {
return NULL;
}
if (rspamd_str_has_8bit(name, nlen)) {
/* Convert to idna using libicu as it follows all the standards */
real_name = rspamd_dns_resolver_idna_convert_utf8(resolver, pool,
name, nlen, &nlen);
if (real_name == NULL) {
return NULL;
}
name = real_name;
}
/* Name is now in ASCII only */
for (gsize i = 0; i < nlen; i++) {
if (ascii_dns_table[((unsigned int) name[i]) & 0x7F] == -1) {
/* Invalid DNS name requested */
if (!pool) {
g_free(real_name);
}
return NULL;
}
}
if (pool != NULL) {
reqdata =
rspamd_mempool_alloc0(pool, sizeof(struct rspamd_dns_request_ud));
}
else {
reqdata = g_malloc0(sizeof(struct rspamd_dns_request_ud));
}
reqdata->pool = pool;
reqdata->session = session;
reqdata->cb = cb;
reqdata->ud = ud;
req = rdns_make_request_full(resolver->r, rspamd_dns_callback, reqdata,
resolver->request_timeout, resolver->max_retransmits, 1, name,
type);
reqdata->req = req;
if (session) {
if (req != NULL) {
rspamd_session_add_event(session,
(event_finalizer_t) rspamd_dns_fin_cb,
reqdata,
M);
}
}
if (req == NULL) {
if (pool == NULL) {
g_free(reqdata);
g_free(real_name);
}
return NULL;
}
if (real_name && pool == NULL) {
g_free(real_name);
}
return reqdata;
}
struct rspamd_dns_cached_delayed_cbdata {
struct rspamd_task *task;
dns_callback_type cb;
gpointer ud;
ev_timer tm;
struct rdns_request *req;
};
static void
rspamd_fail_cache_cb(EV_P_ ev_timer *w, int revents)
{
struct rspamd_dns_cached_delayed_cbdata *cbd =
(struct rspamd_dns_cached_delayed_cbdata *) w->data;
struct rdns_reply fake_reply;
ev_timer_stop(EV_A_ w);
memset(&fake_reply, 0, sizeof(fake_reply));
fake_reply.code = RDNS_RC_SERVFAIL;
fake_reply.request = cbd->req;
fake_reply.resolver = cbd->req->resolver;
fake_reply.requested_name = cbd->req->requested_names[0].name;
cbd->cb(&fake_reply, cbd->ud);
rdns_request_release(cbd->req);
}
static gboolean
make_dns_request_task_common(struct rspamd_task *task,
dns_callback_type cb,
gpointer ud,
enum rdns_request_type type,
const char *name,
gboolean forced)
{
struct rspamd_dns_request_ud *reqdata;
if (!forced && task->dns_requests >= task->cfg->dns_max_requests) {
return FALSE;
}
if (task->resolver->fails_cache) {
/* Search in failures cache */
struct rspamd_dns_fail_cache_entry search;
struct rdns_request *req;
search.name = name;
search.namelen = strlen(name);
search.type = type;
if ((req = rspamd_lru_hash_lookup(task->resolver->fails_cache,
&search, task->task_timestamp)) != NULL) {
/*
* We need to reply with SERVFAIL again to the API, so add a special
* timer, uh-oh, and fire it
*/
struct rspamd_dns_cached_delayed_cbdata *cbd =
rspamd_mempool_alloc0(task->task_pool, sizeof(*cbd));
ev_timer_init(&cbd->tm, rspamd_fail_cache_cb, 0.0, 0.0);
cbd->task = task;
cbd->cb = cb;
cbd->ud = ud;
cbd->req = rdns_request_retain(req);
cbd->tm.data = cbd;
return TRUE;
}
}
reqdata = rspamd_dns_resolver_request(
task->resolver, task->s, task->task_pool, cb, ud,
type, name);
if (reqdata) {
task->dns_requests++;
reqdata->task = task;
reqdata->item = rspamd_symcache_get_cur_item(task);
if (reqdata->item) {
/* We are inside some session */
rspamd_symcache_item_async_inc(task, reqdata->item, M);
}
if (!forced && task->dns_requests >= task->cfg->dns_max_requests) {
msg_info_task("stop resolving on reaching %ud requests",
task->dns_requests);
}
return TRUE;
}
return FALSE;
}
gboolean
rspamd_dns_resolver_request_task(struct rspamd_task *task,
dns_callback_type cb,
gpointer ud,
enum rdns_request_type type,
const char *name)
{
return make_dns_request_task_common(task, cb, ud, type, name, FALSE);
}
gboolean
rspamd_dns_resolver_request_task_forced(struct rspamd_task *task,
dns_callback_type cb,
gpointer ud,
enum rdns_request_type type,
const char *name)
{
return make_dns_request_task_common(task, cb, ud, type, name, TRUE);
}
static void rspamd_rnds_log_bridge(
void *log_data,
enum rdns_log_level level,
const char *function,
const char *format,
va_list args)
{
rspamd_logger_t *logger = log_data;
rspamd_common_logv(logger, (GLogLevelFlags) level, "rdns", NULL,
function, format, args);
}
static void
rspamd_dns_server_init(struct upstream *up, guint idx, gpointer ud)
{
struct rspamd_dns_resolver *r = ud;
rspamd_inet_addr_t *addr;
void *serv;
struct rdns_upstream_elt *elt;
addr = rspamd_upstream_addr_next(up);
if (r->cfg) {
serv = rdns_resolver_add_server(r->r, rspamd_inet_address_to_string(addr),
rspamd_inet_address_get_port(addr), 0, r->cfg->dns_io_per_server);
elt = rspamd_mempool_alloc0(r->cfg->cfg_pool, sizeof(*elt));
elt->server = serv;
elt->lib_data = up;
rspamd_upstream_set_data(up, elt);
}
else {
serv = rdns_resolver_add_server(r->r, rspamd_inet_address_to_string(addr),
rspamd_inet_address_get_port(addr), 0, 8);
}
g_assert(serv != NULL);
}
static void
rspamd_dns_server_reorder(struct upstream *up, guint idx, gpointer ud)
{
struct rspamd_dns_resolver *r = ud;
rspamd_upstream_set_weight(up, rspamd_upstreams_count(r->ups) - idx + 1);
}
static bool
rspamd_dns_resolv_conf_on_server(struct rdns_resolver *resolver,
const char *name, unsigned int port,
int priority, unsigned int io_cnt, void *ud)
{
struct rspamd_dns_resolver *dns_resolver = ud;
struct rspamd_config *cfg;
rspamd_inet_addr_t *addr;
gint test_fd;
cfg = dns_resolver->cfg;
msg_info_config("parsed nameserver %s from resolv.conf", name);
/* Try to open a connection */
if (!rspamd_parse_inet_address(&addr, name, strlen(name),
RSPAMD_INET_ADDRESS_PARSE_DEFAULT)) {
msg_warn_config("cannot parse nameserver address %s", name);
return FALSE;
}
rspamd_inet_address_set_port(addr, port);
test_fd = rspamd_inet_address_connect(addr, SOCK_DGRAM, TRUE);
if (test_fd == -1 && (errno != EINTR || errno != ECONNREFUSED || errno != ECONNRESET)) {
msg_info_config("cannot open connection to nameserver at address %s: %s",
name, strerror(errno));
rspamd_inet_address_free(addr);
return FALSE;
}
rspamd_inet_address_free(addr);
close(test_fd);
return rspamd_upstreams_add_upstream(dns_resolver->ups, name, port,
RSPAMD_UPSTREAM_PARSE_NAMESERVER,
NULL);
}
static void
rspamd_process_fake_reply(struct rspamd_config *cfg,
struct rspamd_dns_resolver *dns_resolver,
const ucl_object_t *cur_arr)
{
const ucl_object_t *cur;
ucl_object_iter_t it;
it = ucl_object_iterate_new(cur_arr);
while ((cur = ucl_object_iterate_safe(it, true))) {
const ucl_object_t *type_obj, *name_obj, *code_obj, *replies_obj;
enum rdns_request_type rtype = RDNS_REQUEST_A;
enum dns_rcode rcode = RDNS_RC_NOERROR;
struct rdns_reply_entry *replies = NULL;
const gchar *name = NULL;
if (ucl_object_type(cur) != UCL_OBJECT) {
continue;
}
name_obj = ucl_object_lookup(cur, "name");
if (name_obj == NULL ||
(name = ucl_object_tostring(name_obj)) == NULL) {
msg_err_config("no name for fake dns reply");
continue;
}
type_obj = ucl_object_lookup(cur, "type");
if (type_obj) {
rtype = rdns_type_fromstr(ucl_object_tostring(type_obj));
if (rtype == RDNS_REQUEST_INVALID) {
msg_err_config("invalid type for %s: %s", name,
ucl_object_tostring(type_obj));
continue;
}
}
code_obj = ucl_object_lookup_any(cur, "code", "rcode", NULL);
if (code_obj) {
rcode = rdns_rcode_fromstr(ucl_object_tostring(code_obj));
if (rcode == RDNS_RC_INVALID) {
msg_err_config("invalid rcode for %s: %s", name,
ucl_object_tostring(code_obj));
continue;
}
}
if (rcode == RDNS_RC_NOERROR) {
/* We want replies to be set for this rcode */
replies_obj = ucl_object_lookup(cur, "replies");
if (replies_obj == NULL || ucl_object_type(replies_obj) != UCL_ARRAY) {
msg_err_config("invalid replies for fake DNS record %s", name);
continue;
}
ucl_object_iter_t rep_it;
const ucl_object_t *rep_obj;
rep_it = ucl_object_iterate_new(replies_obj);
while ((rep_obj = ucl_object_iterate_safe(rep_it, true))) {
const gchar *str_rep = ucl_object_tostring(rep_obj);
struct rdns_reply_entry *rep;
gchar **svec;
if (str_rep == NULL) {
msg_err_config("invalid reply element for fake DNS record %s",
name);
continue;
}
rep = calloc(1, sizeof(*rep));
g_assert(rep != NULL);
rep->type = rtype;
rep->ttl = 0;
switch (rtype) {
case RDNS_REQUEST_A:
if (inet_pton(AF_INET, str_rep, &rep->content.a.addr) != 1) {
msg_err_config("invalid A reply element for fake "
"DNS record %s: %s",
name, str_rep);
free(rep);
}
else {
DL_APPEND(replies, rep);
}
break;
case RDNS_REQUEST_NS:
rep->content.ns.name = strdup(str_rep);
DL_APPEND(replies, rep);
break;
case RDNS_REQUEST_PTR:
rep->content.ptr.name = strdup(str_rep);
DL_APPEND(replies, rep);
break;
case RDNS_REQUEST_MX:
svec = g_strsplit_set(str_rep, " :", -1);
if (svec && svec[0] && svec[1]) {
rep->content.mx.priority = strtoul(svec[0], NULL, 10);
rep->content.mx.name = strdup(svec[1]);
DL_APPEND(replies, rep);
}
else {
msg_err_config("invalid MX reply element for fake "
"DNS record %s: %s",
name, str_rep);
free(rep);
}
g_strfreev(svec);
break;
case RDNS_REQUEST_TXT:
rep->content.txt.data = strdup(str_rep);
DL_APPEND(replies, rep);
break;
case RDNS_REQUEST_SOA:
svec = g_strsplit_set(str_rep, " :", -1);
/* 7 elements */
if (svec && svec[0] && svec[1] && svec[2] &&
svec[3] && svec[4] && svec[5] && svec[6]) {
rep->content.soa.mname = strdup(svec[0]);
rep->content.soa.admin = strdup(svec[1]);
rep->content.soa.serial = strtoul(svec[2], NULL, 10);
rep->content.soa.refresh = strtol(svec[3], NULL, 10);
rep->content.soa.retry = strtol(svec[4], NULL, 10);
rep->content.soa.expire = strtol(svec[5], NULL, 10);
rep->content.soa.minimum = strtoul(svec[6], NULL, 10);
DL_APPEND(replies, rep);
}
else {
msg_err_config("invalid MX reply element for fake "
"DNS record %s: %s",
name, str_rep);
free(rep);
}
g_strfreev(svec);
break;
case RDNS_REQUEST_AAAA:
if (inet_pton(AF_INET6, str_rep, &rep->content.aaa.addr) != 1) {
msg_err_config("invalid AAAA reply element for fake "
"DNS record %s: %s",
name, str_rep);
free(rep);
}
else {
DL_APPEND(replies, rep);
}
break;
case RDNS_REQUEST_SRV:
default:
msg_err_config("invalid or unsupported reply element "
"for fake DNS record %s(%s): %s",
name, rdns_str_from_type(rtype), str_rep);
free(rep);
break;
}
}
ucl_object_iterate_free(rep_it);
if (replies) {
struct rdns_reply_entry *tmp_entry;
guint i = 0;
DL_COUNT(replies, tmp_entry, i);
msg_info_config("added fake record: %s(%s); %d replies", name,
rdns_str_from_type(rtype), i);
rdns_resolver_set_fake_reply(dns_resolver->r,
name, rtype, rcode, replies);
}
else {
msg_warn_config("record %s has no replies, not adding",
name);
}
}
else {
/* This entry returns some non valid code, no replies are possible */
replies_obj = ucl_object_lookup(cur, "replies");
if (replies_obj) {
msg_warn_config("replies are set for non-successful return "
"code for %s(%s), they will be ignored",
name, rdns_str_from_type(rtype));
}
rdns_resolver_set_fake_reply(dns_resolver->r,
name, rtype, rcode, NULL);
}
}
ucl_object_iterate_free(it);
}
static bool
rspamd_dns_read_hosts_file(struct rspamd_config *cfg,
struct rspamd_dns_resolver *dns_resolver,
const gchar *fname)
{
gchar *linebuf = NULL;
gsize buflen = 0;
gssize r;
FILE *fp;
guint nadded = 0;
fp = fopen(fname, "r");
if (fp == NULL) {
/* Hack to reduce noise */
if (strcmp(fname, "/etc/hosts") == 0) {
msg_info_config("cannot open hosts file %s: %s", fname,
strerror(errno));
}
else {
msg_err_config("cannot open hosts file %s: %s", fname,
strerror(errno));
}
return false;
}
while ((r = getline(&linebuf, &buflen, fp)) > 0) {
if (linebuf[0] == '#' || g_ascii_isspace(linebuf[0])) {
/* Skip comment or empty line */
continue;
}
g_strchomp(linebuf);
gchar **elts = g_strsplit_set(linebuf, " \t\v", -1);
rspamd_inet_addr_t *addr;
if (!rspamd_parse_inet_address(&addr, elts[0], strlen(elts[0]),
RSPAMD_INET_ADDRESS_PARSE_REMOTE | RSPAMD_INET_ADDRESS_PARSE_NO_UNIX)) {
msg_warn_config("bad hosts file line: %s; cannot parse address", linebuf);
}
else {
/* Add all FQDN + aliases if any */
gchar **cur_name = &elts[1];
while (*cur_name) {
if (strlen(*cur_name) == 0) {
cur_name++;
continue;
}
if (*cur_name[0] == '#') {
/* Start of the comment */
break;
}
struct rdns_reply_entry *rep;
rep = calloc(1, sizeof(*rep));
g_assert(rep != NULL);
rep->ttl = 0;
if (rspamd_inet_address_get_af(addr) == AF_INET) {
socklen_t unused;
const struct sockaddr_in *sin = (const struct sockaddr_in *)
rspamd_inet_address_get_sa(addr, &unused);
rep->type = RDNS_REQUEST_A;
memcpy(&rep->content.a.addr, &sin->sin_addr,
sizeof(rep->content.a.addr));
}
else {
socklen_t unused;
const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)
rspamd_inet_address_get_sa(addr, &unused);
rep->type = RDNS_REQUEST_AAAA;
memcpy(&rep->content.aaa.addr, &sin6->sin6_addr,
sizeof(rep->content.aaa.addr));
}
rep->next = NULL;
rep->prev = rep;
rdns_resolver_set_fake_reply(dns_resolver->r,
*cur_name, rep->type, RDNS_RC_NOERROR, rep);
msg_debug_config("added fake record %s -> %s from hosts file %s",
*cur_name, rspamd_inet_address_to_string(addr), fname);
cur_name++;
nadded++;
}
rspamd_inet_address_free(addr);
}
g_strfreev(elts);
}
if (linebuf) {
free(linebuf);
}
msg_info_config("processed host file %s; %d records added", fname, nadded);
fclose(fp);
return true;
}
static void
rspamd_dns_resolver_config_ucl(struct rspamd_config *cfg,
struct rspamd_dns_resolver *dns_resolver,
const ucl_object_t *dns_section)
{
const ucl_object_t *fake_replies, *fails_cache_size, *fails_cache_time,
*hosts;
static const ev_tstamp default_fails_cache_time = 10.0;
/* Process fake replies */
fake_replies = ucl_object_lookup_any(dns_section, "fake_records",
"fake_replies", NULL);
if (fake_replies && ucl_object_type(fake_replies) == UCL_ARRAY) {
const ucl_object_t *cur_arr;
DL_FOREACH(fake_replies, cur_arr)
{
rspamd_process_fake_reply(cfg, dns_resolver, cur_arr);
}
}
hosts = ucl_object_lookup(dns_section, "hosts");
if (hosts == NULL) {
/* Read normal `/etc/hosts` file */
rspamd_dns_read_hosts_file(cfg, dns_resolver, "/etc/hosts");
}
else if (ucl_object_type(hosts) == UCL_NULL) {
/* Do nothing, hosts are explicitly disabled */
}
else if (ucl_object_type(hosts) == UCL_STRING) {
if (!rspamd_dns_read_hosts_file(cfg, dns_resolver, ucl_object_tostring(hosts))) {
msg_err_config("cannot read hosts file %s", ucl_object_tostring(hosts));
}
}
else if (ucl_object_type(hosts) == UCL_ARRAY) {
const ucl_object_t *cur;
ucl_object_iter_t it = NULL;
while ((cur = ucl_object_iterate(hosts, &it, true)) != NULL) {
if (!rspamd_dns_read_hosts_file(cfg, dns_resolver, ucl_object_tostring(cur))) {
msg_err_config("cannot read hosts file %s", ucl_object_tostring(cur));
}
}
}
else {
msg_err_config("invalid type for hosts parameter: %s",
ucl_object_type_to_string(ucl_object_type(hosts)));
}
fails_cache_size = ucl_object_lookup(dns_section, "fails_cache_size");
if (fails_cache_size && ucl_object_type(fails_cache_size) == UCL_INT) {
dns_resolver->fails_cache_time = default_fails_cache_time;
fails_cache_time = ucl_object_lookup(dns_section, "fails_cache_time");
if (fails_cache_time) {
dns_resolver->fails_cache_time = ucl_object_todouble(fails_cache_time);
}
dns_resolver->fails_cache = rspamd_lru_hash_new_full(
ucl_object_toint(fails_cache_size),
g_free, (GDestroyNotify) rdns_request_release,
rspamd_dns_fail_hash, rspamd_dns_fail_equal);
}
}
struct rspamd_dns_resolver *
rspamd_dns_resolver_init(rspamd_logger_t *logger,
struct ev_loop *ev_base,
struct rspamd_config *cfg)
{
struct rspamd_dns_resolver *dns_resolver;
dns_resolver = g_malloc0(sizeof(struct rspamd_dns_resolver));
dns_resolver->event_loop = ev_base;
if (cfg != NULL) {
dns_resolver->request_timeout = cfg->dns_timeout;
dns_resolver->max_retransmits = cfg->dns_retransmits;
}
else {
dns_resolver->request_timeout = 1;
dns_resolver->max_retransmits = 2;
}
/* IDN translation is performed in Rspamd now */
dns_resolver->r = rdns_resolver_new(RDNS_RESOLVER_NOIDN);
UErrorCode uc_err = U_ZERO_ERROR;
dns_resolver->uidna = uidna_openUTS46(UIDNA_DEFAULT, &uc_err);
g_assert(!U_FAILURE(uc_err));
rdns_bind_libev(dns_resolver->r, dns_resolver->event_loop);
if (cfg != NULL) {
rdns_resolver_set_log_level(dns_resolver->r, cfg->log_level);
dns_resolver->cfg = cfg;
rdns_resolver_set_dnssec(dns_resolver->r, cfg->enable_dnssec);
if (cfg->nameservers == NULL) {
/* Parse resolv.conf */
dns_resolver->ups = rspamd_upstreams_create(cfg->ups_ctx);
rspamd_upstreams_set_flags(dns_resolver->ups,
RSPAMD_UPSTREAM_FLAG_NORESOLVE);
rspamd_upstreams_set_rotation(dns_resolver->ups,
RSPAMD_UPSTREAM_MASTER_SLAVE);
if (!rdns_resolver_parse_resolv_conf_cb(dns_resolver->r,
"/etc/resolv.conf",
rspamd_dns_resolv_conf_on_server,
dns_resolver)) {
msg_err("cannot parse resolv.conf and no nameservers defined, "
"so no ways to resolve addresses");
rdns_resolver_release(dns_resolver->r);
dns_resolver->r = NULL;
return dns_resolver;
}
/* Use normal resolv.conf rules */
rspamd_upstreams_foreach(dns_resolver->ups, rspamd_dns_server_reorder,
dns_resolver);
}
else {
dns_resolver->ups = rspamd_upstreams_create(cfg->ups_ctx);
rspamd_upstreams_set_flags(dns_resolver->ups,
RSPAMD_UPSTREAM_FLAG_NORESOLVE);
if (!rspamd_upstreams_from_ucl(dns_resolver->ups, cfg->nameservers,
53, dns_resolver)) {
msg_err_config("cannot parse DNS nameservers definitions");
rdns_resolver_release(dns_resolver->r);
dns_resolver->r = NULL;
return dns_resolver;
}
}
rspamd_upstreams_foreach(dns_resolver->ups, rspamd_dns_server_init,
dns_resolver);
rdns_resolver_set_upstream_lib(dns_resolver->r, &rspamd_ups_ctx,
dns_resolver->ups);
cfg->dns_resolver = dns_resolver;
if (cfg->cfg_ucl_obj) {
/* Configure additional options */
const ucl_object_t *opts_section, *dns_section, *tmp;
opts_section = ucl_object_lookup(cfg->cfg_ucl_obj, "options");
if (opts_section) {
/* TODO: implement a more simple merge logic */
DL_FOREACH(opts_section, tmp)
{
dns_section = ucl_object_lookup(opts_section, "dns");
if (dns_section) {
rspamd_dns_resolver_config_ucl(cfg, dns_resolver,
dns_section);
}
}
}
}
}
rdns_resolver_set_logger(dns_resolver->r, rspamd_rnds_log_bridge, logger);
rdns_resolver_init(dns_resolver->r);
return dns_resolver;
}
void rspamd_dns_resolver_deinit(struct rspamd_dns_resolver *resolver)
{
if (resolver) {
if (resolver->r) {
rdns_resolver_release(resolver->r);
}
if (resolver->ups) {
rspamd_upstreams_destroy(resolver->ups);
}
if (resolver->fails_cache) {
rspamd_lru_hash_destroy(resolver->fails_cache);
}
uidna_close(resolver->uidna);
g_free(resolver);
}
}
static struct rdns_upstream_elt *
rspamd_dns_select_upstream(const char *name,
size_t len, void *ups_data)
{
struct upstream_list *ups = ups_data;
struct upstream *up;
up = rspamd_upstream_get(ups, RSPAMD_UPSTREAM_ROUND_ROBIN, name, len);
if (up) {
msg_debug("select %s", rspamd_upstream_name(up));
return rspamd_upstream_get_data(up);
}
return NULL;
}
static struct rdns_upstream_elt *
rspamd_dns_select_upstream_retransmit(
const char *name,
size_t len,
struct rdns_upstream_elt *prev_elt,
void *ups_data)
{
struct upstream_list *ups = ups_data;
struct upstream *up;
if (prev_elt) {
up = rspamd_upstream_get_except(ups, (struct upstream *) prev_elt->lib_data,
RSPAMD_UPSTREAM_MASTER_SLAVE, name, len);
}
else {
up = rspamd_upstream_get_forced(ups, RSPAMD_UPSTREAM_RANDOM, name, len);
}
if (up) {
msg_debug("select forced %s", rspamd_upstream_name(up));
return rspamd_upstream_get_data(up);
}
return NULL;
}
static void
rspamd_dns_upstream_ok(struct rdns_upstream_elt *elt,
void *ups_data)
{
struct upstream *up = elt->lib_data;
rspamd_upstream_ok(up);
}
static void
rspamd_dns_upstream_fail(struct rdns_upstream_elt *elt,
void *ups_data, const gchar *reason)
{
struct upstream *up = elt->lib_data;
rspamd_upstream_fail(up, FALSE, reason);
}
static unsigned int
rspamd_dns_upstream_count(void *ups_data)
{
struct upstream_list *ups = ups_data;
return rspamd_upstreams_alive(ups);
}
gchar *
rspamd_dns_resolver_idna_convert_utf8(struct rspamd_dns_resolver *resolver,
rspamd_mempool_t *pool,
const char *name,
gint namelen,
guint *outlen)
{
if (resolver == NULL || resolver->uidna == NULL || name == NULL || namelen > DNS_D_MAXNAME) {
return NULL;
}
guint dest_len;
UErrorCode uc_err = U_ZERO_ERROR;
UIDNAInfo info = UIDNA_INFO_INITIALIZER;
/* Calculate length required */
dest_len = uidna_nameToASCII_UTF8(resolver->uidna, name, namelen,
NULL, 0, &info, &uc_err);
if (uc_err == U_BUFFER_OVERFLOW_ERROR) {
gchar *dest;
if (pool) {
dest = rspamd_mempool_alloc(pool, dest_len + 1);
}
else {
dest = g_malloc(dest_len + 1);
}
uc_err = U_ZERO_ERROR;
dest_len = uidna_nameToASCII_UTF8(resolver->uidna, name, namelen,
dest, dest_len + 1, &info, &uc_err);
if (U_FAILURE(uc_err)) {
if (!pool) {
g_free(dest);
}
return NULL;
}
dest[dest_len] = '\0';
if (outlen) {
*outlen = dest_len;
}
return dest;
}
return NULL;
}
|
aa9e67f8ae8fc5e76c9cad4bead075a8ef7d583a
|
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
|
/third_party/ctags/routines.c
|
5710a587e1b95a4198bdf38d897c612824c745f9
|
[
"GPL-2.0-only",
"ISC"
] |
permissive
|
jart/cosmopolitan
|
fb11b5658939023977060a7c6c71a74093d9cb44
|
0d748ad58e1063dd1f8560f18a0c75293b9415b7
|
refs/heads/master
| 2023-09-06T09:17:29.303607
| 2023-09-02T03:49:13
| 2023-09-02T03:50:18
| 272,457,606
| 11,887
| 435
|
ISC
| 2023-09-14T17:47:58
| 2020-06-15T14:16:13
|
C
|
UTF-8
|
C
| false
| false
| 12,123
|
c
|
routines.c
|
/*
* $Id: routines.c 536 2007-06-02 06:09:00Z elliotth $
*
* Copyright (c) 2002-2003, Darren Hiebert
*
* This source code is released for free distribution under the terms of the
* GNU General Public License.
*
* This module contains a lose assortment of shared functions.
*/
#include "third_party/ctags/general.h"
/**/
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/s.h"
#include "third_party/ctags/config.h"
#include "third_party/ctags/debug.h"
#include "third_party/ctags/routines.h"
// clang-format off
/*
* Miscellaneous macros
*/
#define selected(var,feature) (((int)(var) & (int)(feature)) == (int)feature)
char *CurrentDirectory;
static const char *ExecutableProgram;
static const char *ExecutableName;
/*
* FUNCTION DEFINITIONS
*/
extern void freeRoutineResources (void)
{
if (CurrentDirectory != NULL)
eFree (CurrentDirectory);
}
extern void setExecutableName (const char *const path)
{
ExecutableProgram = path;
ExecutableName = baseFilename (path);
#ifdef VAXC
{
/* remove filetype from executable name */
char *p = strrchr (ExecutableName, '.');
if (p != NULL)
*p = '\0';
}
#endif
}
extern const char *getExecutableName (void)
{
return ExecutableName;
}
extern const char *getExecutablePath (void)
{
return ExecutableProgram;
}
extern void error (
const errorSelection selection, const char *const format, ...)
{
va_list ap;
va_start (ap, format);
fprintf (errout, "%s: %s", getExecutableName (),
selected (selection, WARNING) ? "Warning: " : "");
vfprintf (errout, format, ap);
if (selected (selection, PERROR))
fprintf (errout, " : %s", strerror (errno));
fputs ("\n", errout);
va_end (ap);
if (selected (selection, FATAL))
exit (1);
}
/*
* Memory allocation functions
*/
extern void *eMalloc (const size_t size)
{
void *buffer = malloc (size);
if (buffer == NULL)
error (FATAL, "out of memory");
return buffer;
}
extern void *eCalloc (const size_t count, const size_t size)
{
void *buffer = calloc (count, size);
if (buffer == NULL)
error (FATAL, "out of memory");
return buffer;
}
extern void *eRealloc (void *const ptr, const size_t size)
{
void *buffer;
if (ptr == NULL)
buffer = eMalloc (size);
else
{
buffer = realloc (ptr, size);
if (buffer == NULL)
error (FATAL, "out of memory");
}
return buffer;
}
extern void eFree (void *const ptr)
{
Assert (ptr != NULL);
free (ptr);
}
/*
* String manipulation functions
*/
/*
* Compare two strings, ignoring case.
* Return 0 for match, < 0 for smaller, > 0 for bigger
* Make sure case is folded to uppercase in comparison (like for 'sort -f')
* This makes a difference when one of the chars lies between upper and lower
* ie. one of the chars [ \ ] ^ _ ` for ascii. (The '_' in particular !)
*/
extern int struppercmp (const char *s1, const char *s2)
{
int result;
do
{
result = toupper ((int) *s1) - toupper ((int) *s2);
} while (result == 0 && *s1++ != '\0' && *s2++ != '\0');
return result;
}
extern int strnuppercmp (const char *s1, const char *s2, size_t n)
{
int result;
do
{
result = toupper ((int) *s1) - toupper ((int) *s2);
} while (result == 0 && --n > 0 && *s1++ != '\0' && *s2++ != '\0');
return result;
}
extern char* eStrdup (const char* str)
{
char* result = xMalloc (strlen (str) + 1, char);
strcpy (result, str);
return result;
}
extern void toLowerString (char* str)
{
while (*str != '\0')
{
*str = tolower ((int) *str);
++str;
}
}
extern void toUpperString (char* str)
{
while (*str != '\0')
{
*str = toupper ((int) *str);
++str;
}
}
/* Newly allocated string containing lower case conversion of a string.
*/
extern char* newLowerString (const char* str)
{
char* const result = xMalloc (strlen (str) + 1, char);
int i = 0;
do
result [i] = tolower ((int) str [i]);
while (str [i++] != '\0');
return result;
}
/* Newly allocated string containing upper case conversion of a string.
*/
extern char* newUpperString (const char* str)
{
char* const result = xMalloc (strlen (str) + 1, char);
int i = 0;
do
result [i] = toupper ((int) str [i]);
while (str [i++] != '\0');
return result;
}
/*
* File system functions
*/
extern void setCurrentDirectory (void)
{
char* buf;
if (CurrentDirectory == NULL)
CurrentDirectory = xMalloc ((size_t) (PATH_MAX + 1), char);
buf = getcwd (CurrentDirectory, PATH_MAX);
if (buf == NULL)
perror ("");
if (CurrentDirectory [strlen (CurrentDirectory) - (size_t) 1] !=
PATH_SEPARATOR)
{
sprintf (CurrentDirectory + strlen (CurrentDirectory), "%c",
OUTPUT_PATH_SEPARATOR);
}
}
/* For caching of stat() calls */
extern fileStatus *eStat (const char *const fileName)
{
struct stat status;
static fileStatus file;
if (file.name == NULL || strcmp (fileName, file.name) != 0)
{
eStatFree (&file);
file.name = eStrdup (fileName);
if (lstat (file.name, &status) != 0)
file.exists = FALSE;
else
{
file.isSymbolicLink = (boolean) S_ISLNK (status.st_mode);
if (file.isSymbolicLink && stat (file.name, &status) != 0)
file.exists = FALSE;
else
{
file.exists = TRUE;
file.isDirectory = (boolean) S_ISDIR (status.st_mode);
file.isNormalFile = (boolean) (S_ISREG (status.st_mode));
file.isExecutable = (boolean) ((status.st_mode &
(S_IXUSR | S_IXGRP | S_IXOTH)) != 0);
file.isSetuid = (boolean) ((status.st_mode & S_ISUID) != 0);
file.size = status.st_size;
}
}
}
return &file;
}
extern void eStatFree (fileStatus *status)
{
if (status->name != NULL)
{
eFree (status->name);
status->name = NULL;
}
}
extern boolean doesFileExist (const char *const fileName)
{
fileStatus *status = eStat (fileName);
return status->exists;
}
extern boolean isRecursiveLink (const char* const dirName)
{
boolean result = FALSE;
fileStatus *status = eStat (dirName);
if (status->isSymbolicLink)
{
char* const path = absoluteFilename (dirName);
while (path [strlen (path) - 1] == PATH_SEPARATOR)
path [strlen (path) - 1] = '\0';
while (! result && strlen (path) > (size_t) 1)
{
char *const separator = strrchr (path, PATH_SEPARATOR);
if (separator == NULL)
break;
else if (separator == path) /* backed up to root directory */
*(separator + 1) = '\0';
else
*separator = '\0';
result = isSameFile (path, dirName);
}
eFree (path);
}
return result;
}
/*
* Pathname manipulation (O/S dependent!!!)
*/
static boolean isPathSeparator (const int c)
{
boolean result;
result = (boolean) (c == PATH_SEPARATOR);
return result;
}
extern boolean isSameFile (const char *const name1, const char *const name2)
{
boolean result = FALSE;
struct stat stat1, stat2;
if (stat (name1, &stat1) == 0 && stat (name2, &stat2) == 0)
result = (boolean) (stat1.st_ino == stat2.st_ino);
return result;
}
extern const char *baseFilename (const char *const filePath)
{
const char *tail = strrchr (filePath, PATH_SEPARATOR);
if (tail == NULL)
tail = filePath;
else
++tail; /* step past last delimiter */
return tail;
}
extern const char *fileExtension (const char *const fileName)
{
const char *extension;
const char *pDelimiter = NULL;
const char *const base = baseFilename (fileName);
if (pDelimiter == NULL)
pDelimiter = strrchr (base, '.');
if (pDelimiter == NULL)
extension = "";
else
extension = pDelimiter + 1; /* skip to first char of extension */
return extension;
}
extern boolean isAbsolutePath (const char *const path)
{
boolean result = FALSE;
result = isPathSeparator (path [0]);
return result;
}
extern vString *combinePathAndFile (
const char *const path, const char *const file)
{
vString *const filePath = vStringNew ();
const int lastChar = path [strlen (path) - 1];
boolean terminated = isPathSeparator (lastChar);
vStringCopyS (filePath, path);
if (! terminated)
{
vStringPut (filePath, OUTPUT_PATH_SEPARATOR);
vStringTerminate (filePath);
}
vStringCatS (filePath, file);
return filePath;
}
/* Return a newly-allocated string whose contents concatenate those of
* s1, s2, s3.
* Routine adapted from Gnu etags.
*/
static char* concat (const char *s1, const char *s2, const char *s3)
{
int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
char *result = xMalloc (len1 + len2 + len3 + 1, char);
strcpy (result, s1);
strcpy (result + len1, s2);
strcpy (result + len1 + len2, s3);
result [len1 + len2 + len3] = '\0';
return result;
}
/* Return a newly allocated string containing the absolute file name of FILE
* given CWD (which should end with a slash).
* Routine adapted from Gnu etags.
*/
extern char* absoluteFilename (const char *file)
{
char *slashp, *cp;
char *res = NULL;
if (isAbsolutePath (file))
{
res = eStrdup (file);
}
else
res = concat (CurrentDirectory, file, "");
/* Delete the "/dirname/.." and "/." substrings. */
slashp = strchr (res, PATH_SEPARATOR);
while (slashp != NULL && slashp [0] != '\0')
{
if (slashp[1] == '.')
{
if (slashp [2] == '.' &&
(slashp [3] == PATH_SEPARATOR || slashp [3] == '\0'))
{
cp = slashp;
do
cp--;
while (cp >= res && ! isAbsolutePath (cp));
if (cp < res)
cp = slashp;/* the absolute name begins with "/.." */
memmove (cp, slashp + 3, strlen(slashp + 3) + 1);
slashp = cp;
continue;
}
else if (slashp [2] == PATH_SEPARATOR || slashp [2] == '\0')
{
memmove (slashp, slashp + 2, strlen(slashp + 2) + 1);
continue;
}
}
slashp = strchr (slashp + 1, PATH_SEPARATOR);
}
if (res [0] == '\0')
return eStrdup ("/");
else
{
return res;
}
}
/* Return a newly allocated string containing the absolute file name of dir
* where `file' resides given `CurrentDirectory'.
* Routine adapted from Gnu etags.
*/
extern char* absoluteDirname (char *file)
{
char *slashp, *res;
char save;
slashp = strrchr (file, PATH_SEPARATOR);
if (slashp == NULL)
res = eStrdup (CurrentDirectory);
else
{
save = slashp [1];
slashp [1] = '\0';
res = absoluteFilename (file);
slashp [1] = save;
}
return res;
}
/* Return a newly allocated string containing the file name of FILE relative
* to the absolute directory DIR (which should end with a slash).
* Routine adapted from Gnu etags.
*/
extern char* relativeFilename (const char *file, const char *dir)
{
const char *fp, *dp;
char *absdir, *res;
int i;
/* Find the common root of file and dir (with a trailing slash). */
absdir = absoluteFilename (file);
fp = absdir;
dp = dir;
while (*fp++ == *dp++)
continue;
fp--;
dp--; /* back to the first differing char */
do
{ /* look at the equal chars until path sep */
if (fp == absdir)
return absdir; /* first char differs, give up */
fp--;
dp--;
} while (*fp != PATH_SEPARATOR);
/* Build a sequence of "../" strings for the resulting relative file name.
*/
i = 0;
while ((dp = strchr (dp + 1, PATH_SEPARATOR)) != NULL)
i += 1;
res = xMalloc (3 * i + strlen (fp + 1) + 1, char);
res [0] = '\0';
while (i-- > 0)
strcat (res, "../");
/* Add the file name relative to the common root of file and dir. */
strcat (res, fp + 1);
free (absdir);
return res;
}
extern FILE *tempFile (const char *const mode, char **const pName)
{
char *name;
FILE *fp;
int fd;
const char *const pattern = "tags.XXXXXX";
const char *tmpdir = NULL;
fileStatus *file = eStat (ExecutableProgram);
if (! file->isSetuid)
tmpdir = getenv ("TMPDIR");
if (tmpdir == NULL)
tmpdir = TMPDIR;
name = xMalloc (strlen (tmpdir) + 1 + strlen (pattern) + 1, char);
sprintf (name, "%s%c%s", tmpdir, OUTPUT_PATH_SEPARATOR, pattern);
fd = mkstemp (name);
eStatFree (file);
if (fd == -1)
error (FATAL | PERROR, "cannot open temporary file");
fp = fdopen (fd, mode);
if (fp == NULL)
error (FATAL | PERROR, "cannot open temporary file");
DebugStatement (
debugPrintf (DEBUG_STATUS, "opened temporary file %s\n", name); )
Assert (*pName == NULL);
*pName = name;
return fp;
}
/* vi:set tabstop=4 shiftwidth=4: */
|
e76c189751eeff7683ac6628c80be65e2fe929dd
|
59864cbd213b5da6f50d6255b0a021564b3d5bd4
|
/challenges/Filesystem_Command_Shell/src/tokenizer.c
|
44ab0e23a162ba277a2a67e5f8e5ac84f30f3ec9
|
[
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-unknown",
"BSD-2-Clause"
] |
permissive
|
trailofbits/cb-multios
|
8af96a4fbc3b34644367faa135347f88e0e0d0a3
|
810d7b24b1f62f56ef49b148fe155b0d0629cad2
|
refs/heads/master
| 2023-09-05T03:56:20.229403
| 2022-12-27T15:47:54
| 2022-12-27T15:47:54
| 41,688,943
| 522
| 133
|
MIT
| 2023-06-29T02:47:13
| 2015-08-31T17:04:31
|
C
|
UTF-8
|
C
| false
| false
| 2,334
|
c
|
tokenizer.c
|
/*
Author: Steve Wood <swood@cromulence.com>
Copyright (c) 2016 Cromulence LLC
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 "libcgc.h"
#include "cgc_stdlib.h"
#include "cgc_service.h"
#include "cgc_filesystem.h"
#include "cgc_string.h"
#include "cgc_ctype.h"
#include "cgc_stdio.h"
#include "cgc_malloc.h"
// returns the number of tokens, and an array of pointers to the items in the original string argument
int cgc_tokenize(char *string, char delimiter, char **args[]) {
int i;
int count;
if (cgc_strlen(string) == 0) {
return 0;
}
i = 0;
count = 0;
// pass one is to just determine how many tokens there are so memory can be allocated
while(*(string+i) != 0) {
while ( cgc_isspace(*(string+i)) && *(string+i) != 0)
++i;
if (*(string+i) == 0)
break;
++count;
while ( !cgc_isspace(*(string+i)) && *(string+i) != 0)
++i;
if (*(string+i) == 0 )
break;
}
*args = cgc_malloc(count * sizeof(char *));
if (*args == 0 )
return -1;
i = 0;
count = 0;
while(*(string+i) != 0) {
while ( cgc_isspace(*(string+i)) && *(string+i) != 0)
++i;
if (*(string+i) == 0)
break;
(*args)[count] = (string+i);
++count;
while ( !cgc_isspace(*(string+i)) && *(string+i) != 0)
++i;
if (*(string+i) == 0 )
break;
else {
*(string+i) = 0;
++i;
}
}
return count;
}
|
cf7a804f150fa039f3be8e471d568be6d1876387
|
efe37ebcbadc6dda488f321f59b34b3a8f918960
|
/tools/gfx2snes/lz77.c
|
37d0b50a4c6950a9294a41a70b976be4ca1182c9
|
[
"MIT"
] |
permissive
|
alekmaul/pvsneslib
|
83fd163e1fdca6a4ce7bc49b5562cb7e49a021df
|
69203c23f3e0c0f8a61e9452819f8690aefa476b
|
refs/heads/master
| 2023-08-31T21:09:17.036094
| 2023-08-26T06:21:28
| 2023-08-26T06:21:28
| 32,628,824
| 673
| 83
| null | 2023-09-06T04:23:42
| 2015-03-21T10:49:52
|
C
|
UTF-8
|
C
| false
| false
| 13,496
|
c
|
lz77.c
|
/*
AGBCOMP compatible LZSS compressor
Compresses files in a format that the GBA BIOS can decode.
Original code by Haruhiko Okumura, 4/6/1989.
12-2-404 Green Heights, 580 Nagasawa, Yokosuka 239, Japan.
Anonymous, December 2001:
Converted I/O to load the entire file into memory and operate
on buffers.
Modified to output in the GBA BIOS's native format.
Damian Yerrick, July 2002:
Translated the program into C from C++.
Removed use of non-ANSI <sys/stat.h> that some compilers don't
support.
Made messages more informational.
Corrected an off-by-one error in the allocation of the output
size.
Removed comp.h. Now it's one file.
Damian Yerrick, December 2002:
Prevented matches that reference data before start of file.
Began to standardize comments.
J. Vijn, Feb 2005
* Removed main() and added lzgb_compress() so that the file acts
more like a plugin.
// declaration:
unsigned char *lzgb_compress(const char *src, int src_len,
int *pdst_len);
* Removed InsertNode for ii=[N-2*F, N-F-1] because they create
spurious nodes that allow strings to start _before_ the actual
data. Using uninitialized data would fit nicely into the Bad
Things category. Also removed the safeguards to counter this,
since they're not necessary anymore.
* Made the code VRAM safe (I hope)
On this issue: remember that VRAM cannot be written to in bytes.
Therefore, LZ77UnCompVram prepares an u16 before writing. The
problem occurs when the matched position is one before the current
position, in which case the destination bytes haven't been copied
in yet. There's that using uninitialized data again.
First a little more about the process. Nodes are built for each
bytes. rson[N+1..N+256] are the trees for each byte and each node in
that tree represents a possible match. There will be as many nodes
in the tree as there are of those bytes in the ring buffer.
Naturally the last node added is the one before the current one: r-1.
The routine will traverse the tree of the byte at [r], looking
for two things: a) the longest match and b) the closest match if there
are matches of equal length. And this is where shit happens. Both of
them can go wrong, but always for a very special case. As said, the
problem occurs when the match is the previous position. This can only
happen under one condition: for _stretches_ of the same bytes. The
solution is to use the latest length UNLESS the current node p is the
last one added (r-1). This will work out for both new partial stretches
(which will only have one pass and as a result the 2nd byte will have
match_length=0) and F-long stretches. It's basically a 1 line fix.
Gawd I hate those. (20050312: ok, so it turned out to be a 2 line fix)
Use, distribute, and modify this code freely.
"I do not accept responsibility for any effects, adverse or otherwise,
that this code may have on you, your computer, your sanity, your dog,
and anything else that you can think of. Use it at your own risk."
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/// === TYPES =========================================================
typedef unsigned char u8, BYTE;
typedef struct RECORD
{
int width;
int height;
BYTE *data;
} RECORD;
#define ALIGN4(nn) ( ((nn)+3)&~3 )
#define CPRS_LZ77_TAG 0x10
// --------------------------------------------------------------------
// CONSTANTS
// --------------------------------------------------------------------
// Define information for compression
// (dont modify from 4096/18/2 if AGBCOMP format is required)
#define N 4096 // size of ring buffer (12 bit)
#define F 18 // upper limit for match_length
#define THRESHOLD 2 // encode string into position and length
// if matched length is greater than this
#define NIL N // index for root of binary search trees
#define TEXT_BUF_CLEAR 0 // byte to initialize the area before text_buf with
#define NMASK (N-1) // for wrapping
// --------------------------------------------------------------------
// GLOBALS
// --------------------------------------------------------------------
/* Compressor global variables. If you actually want to USE this
code in a non-trivial app, put these global variables in a struct,
as the Allegro library did.
*/
static unsigned int codesize = 0; // code size counter
unsigned int textsize = 0; /* text size counter */
// ring buffer of size N with extra F-1 bytes to facilitate string comparison
unsigned char text_buf[N + F - 1];
int match_position; // global string match position
int match_length; // global string match length
int lson[N+1], rson[N+256+1], dad[N+1]; // left & right children & parents -- These constitute binary search trees.
//BYTE *InBuf, *OutBuf;
int InSize, OutSize, InOffset;
// --------------------------------------------------------------------
// PROTOTYPES
// --------------------------------------------------------------------
//! GBA lz77 interface function
int cprs_gba_lz77(RECORD *dst, const RECORD *src);
/* Binary search tree functions */
void InitTree(void);
void InsertNode(int r);
void DeleteNode(int p);
/* Misc Functions */
int InChar(unsigned char *bufin);
// --------------------------------------------------------------------
// FUNCTIONS
// --------------------------------------------------------------------
// Initializes InBuf, InSize; allocates OutBuf.
// the rest is done in CompressLZ77
/*
int cprs_gba_lz77(RECORD *dst, const RECORD *src)
{
// fail on the obvious
if(src==NULL || src->data==NULL || dst==NULL)
return 0;
InSize= src->width*src->height;
OutSize = InSize + (InSize>>3) + 16;
OutBuf = (BYTE*)malloc(OutSize);
if(OutBuf == NULL)
return 0;
InBuf= (BYTE*)src->data;
CompressLZ77();
OutSize= ALIGN4(OutSize);
free(dst->data);
dst->data= (BYTE*)malloc(OutSize);
memcpy(dst->data, OutBuf, OutSize);
dst->width= 1;
dst->height= OutSize;
free(OutBuf);
return OutSize;
}
*/
/* InitTree() **************************
Initialize a binary search tree.
For i = 0 to N - 1, rson[i] and lson[i] will be the right and
left children of node i. These nodes need not be initialized.
Also, dad[i] is the parent of node i. These are initialized
to NIL (= N), which stands for 'not used.'
For i = 0 to 255, rson[N + i + 1] is the root of the tree
for strings that begin with character i. These are
initialized to NIL. Note there are 256 trees.
*/
void InitTree(void)
{
int i;
for(i= N+1; i <= N+256; i++)
rson[i]= NIL;
for(i=0; i < N; i++)
dad[i]= NIL;
}
/* InsertNode() ************************
Inserts string of length F, text_buf[r..r+F-1], into one of the
trees (text_buf[r]'th tree) and returns the longest-match position
and length via the global variables match_position and match_length.
If match_length = F, then removes the old node in favor of the new
one, because the old one will be deleted sooner.
Note r plays double role, as tree node and position in buffer.
*/
void InsertNode(int r)
{
int i, p, cmp/*, prev_length*/;
BYTE *key;
cmp= 1; key= &text_buf[r]; p= N + 1 + key[0];
rson[r]= lson[r]= NIL;
/*prev_length= */match_length= 0;
for( ; ; )
{
if(cmp >= 0)
{
if(rson[p] != NIL)
p= rson[p];
else
{
rson[p]= r;
dad[r]= p;
return;
}
}
else
{
if(lson[p] != NIL)
p= lson[p];
else
{
lson[p]= r;
dad[r]= p;
return;
}
}
for(i=1; i < F; i++)
if((cmp = key[i] - text_buf[p + i]) != 0)
break;
if(i > match_length)
{
// VRAM safety:
// match_length= i ONLY if the matched position
// isn't the previous one (r-1)
// for normal case, remove the if.
// That's _IT_?!? Yup, that's it.
if(p != ((r-1)&NMASK) )
{
match_length= i;
match_position= p;
}
if(match_length >= F)
break;
}
}
// Full length match, remove old node in favor of this one
dad[r]= dad[p];
lson[r]= lson[p];
rson[r]= rson[p];
dad[lson[p]]= r;
dad[rson[p]]= r;
if(rson[dad[p]] == p)
rson[dad[p]]= r;
else
lson[dad[p]]= r;
dad[p]= NIL;
}
/* DeleteNode() ************************
Deletes node p from the tree.
*/
void DeleteNode(int p)
{
int q;
if(dad[p] == NIL)
return; /* not in tree */
if(rson[p] == NIL)
q = lson[p];
else if(lson[p] == NIL)
q = rson[p];
else
{
q = lson[p];
if(rson[q] != NIL)
{
do {
q = rson[q];
} while(rson[q] != NIL);
rson[dad[q]] = lson[q];
dad[lson[q]] = dad[q];
lson[q] = lson[p];
dad[lson[p]] = q;
}
rson[q] = rson[p];
dad[rson[p]] = q;
}
dad[q] = dad[p];
if(rson[dad[p]] == p)
rson[dad[p]] = q;
else
lson[dad[p]] = q;
dad[p] = NIL;
}
/* InChar() ****************************
Get the next character from the input stream, or -1 for end of file.
*/
int InChar(unsigned char *bufin)
{
return (InOffset < InSize) ? bufin[InOffset++] : -1;
}
int Convert2PicLZ77(int quietmode, unsigned char *bufin, int buflen, unsigned char *bufout)
{
int i, c, len, r, s, last_match_length, code_buf_ptr;
unsigned char code_buf[17];
unsigned short mask;
BYTE *FileSize;
unsigned int curmatch; // PONDER: doesn't this do what r does?
unsigned int savematch;
InSize= buflen;
OutSize=4; // skip the compression type and file size
InOffset=0;
match_position= curmatch= N-F;
InitTree(); // initialize trees
code_buf[0] = 0; /* code_buf[1..16] saves eight units of code, and
code_buf[0] works as eight flags, "0" representing that the unit
is an unencoded letter (1 byte), "1" a position-and-length pair
(2 bytes). Thus, eight units require at most 16 bytes of code. */
code_buf_ptr = 1;
s = 0; r = N - F;
// Clear the buffer
for(i = s; i < r; i++)
text_buf[i] = TEXT_BUF_CLEAR;
// Read F bytes into the last F bytes of the buffer
for(len = 0; len < F && (c = InChar(bufin)) != -1; len++)
text_buf[r + len] = c;
if((textsize=len) == 0)
{
printf("\ngfx2snes: error 'Size to compress is null'\n");
return 0;
}
/* Insert the F strings, each of which begins with one or more
// 'space' characters. Note the order in which these strings are
// inserted. This way, degenerate trees will be less likely to occur.
*/
// Perhaps.
// However, the strings you create here have no relation to
// the actual data and are therefore completely bogus. Removed!
//for (i = 1; i <= F; i++)
// InsertNode(r - i);
// Create the first node, sets match_length to 0
InsertNode(r);
// GBA LZSS masks are big-endian
mask = 0x80;
do
{
if(match_length > len)
match_length = len;
// match too short: add one unencoded byte
if(match_length <= THRESHOLD)
{
match_length = 1;
code_buf[code_buf_ptr++] = text_buf[r];
}
else // Long enough: add position and length pair.
{
code_buf[0] |= mask; // set match flag
// 0 byte is 4:length and 4:top 4 bits of match_position
savematch= ((curmatch-match_position)&NMASK)-1;
code_buf[code_buf_ptr++] = ((BYTE)((savematch>>8)&0xf))
| ((match_length - (THRESHOLD + 1))<<4);
code_buf[code_buf_ptr++] = (BYTE)savematch;
}
curmatch += match_length;
curmatch &= NMASK;
// if mask is empty, the buffer's full; write it out the code buffer
// at end of source, code_buf_ptr will be <17
if((mask >>= 1) == 0)
{
for(i=0; i < code_buf_ptr; i++)
bufout[OutSize++]= code_buf[i];
codesize += code_buf_ptr;
code_buf[0] = 0;
code_buf_ptr = 1;
mask = 0x80;
}
// Inserts nodes for this match. The last_match_length is
// required because InsertNode changes match_length.
last_match_length = match_length;
for(i=0; i < last_match_length && (c = InChar(bufin)) != -1; i++)
{
DeleteNode(s); // Delete string beforelook-ahead
text_buf[s] = c; // place new bytes
// text_buf[N..N+F> is a double for text_buf[0..F>
// for easier string comparison
if(s < F-1)
text_buf[s + N] = c;
// add and wrap around the buffer
s = (s + 1) & NMASK;
r = (r + 1) & NMASK;
// Register the string in text_buf[r..r+F-1]
InsertNode(r);
}
textsize += i;
while(i++ < last_match_length)
{
// After the end of text
DeleteNode(s); // no need to read, but
s = (s + 1) & NMASK;
r = (r + 1) & NMASK;
if(--len)
InsertNode(r); // buffer may not be empty
}
} while(len > 0); // until length of string to be processed is zero
if(code_buf_ptr > 1)
{
// Send remaining code.
for(i=0; i < code_buf_ptr; i++)
bufout[OutSize++]=code_buf[i];
codesize += code_buf_ptr;
}
FileSize= (BYTE*)bufout;
FileSize[0]= CPRS_LZ77_TAG;
FileSize[1]= ((InSize>>0)&0xFF);
FileSize[2]= ((InSize>>8)&0xFF);
FileSize[3]= ((InSize>>16)&0xFF);
// return an error if ratio<100
if ( ((textsize*100)/ OutSize)<100)
{
printf("\ngfx2snes: error 'Ratio for compression is not good (%d%%))'\n",((textsize*100)/ OutSize));
return 0;
}
// remove trails bytes
OutSize=ALIGN4(OutSize);
if (quietmode == 0)
{
printf("\ngfx2snes: 'Compression Lz77 from %d bytes to %d bytes (ratio %d%%)'", textsize, OutSize, ((textsize*100)/ OutSize)-100 ); /* Encoding is done. */
}
return OutSize;
} // end of Convert2PicLZSS
|
4d57d875602ec8e29332c7acc5653f2bff64950b
|
488e6c9b8555a253df765edc2232e8750e8b3a1b
|
/firmware-src/sources/devices/mfrc522.c
|
ffbb02c9899ce9e6195c38d2e525580ec6e990ef
|
[
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
devicehive/esp8266-firmware
|
32edadae1d919438fd13388b562979030cc4472a
|
eb8a61482035bfc93a343db386d4470d17fa13d6
|
refs/heads/develop
| 2021-01-01T16:44:57.970370
| 2019-03-28T12:48:43
| 2019-03-28T12:48:43
| 39,383,605
| 182
| 61
|
MIT
| 2018-05-07T20:43:14
| 2015-07-20T12:53:51
|
C
|
UTF-8
|
C
| false
| false
| 75,353
|
c
|
mfrc522.c
|
/*
* MFRC522.cpp - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
* NOTE: Please also check the comments in MFRC522.h - they provide useful hints and background information.
* Released into the public domain.
*/
#include "devices/mfrc522.h"
#include "DH/spi.h"
#include "dhdebug.h"
#include "snprintf.h"
#include <osapi.h>
#include <ets_forward.h>
#if defined(DH_DEVICE_MFRC522)
static int _chipSelectPin = 15; // pin connected to MFRC522's SPI slave select input (Pin 24, NSS, active low)
// Member variables
static MFRC522_Uid uid; // Used by MFRC522_PICC_ReadCardSerial().
MFRC522_StatusCode MFRC522_MIFARE_TwoStepHelper(uint8_t command, uint8_t blockAddr, int32_t data);
/////////////////////////////////////////////////////////////////////////////////////
// Functions for setting up ESP8266
/////////////////////////////////////////////////////////////////////////////////////
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_Set_CS(int pin) {
if(0 == dh_spi_set_cs_pin(pin)) {
_chipSelectPin = pin;
return MFRC522_STATUS_OK;
}
return MFRC522_STATUS_ERROR;
}
MFRC522_Uid * ICACHE_FLASH_ATTR MFRC522_Get_Uid() {
return &uid;
}
/////////////////////////////////////////////////////////////////////////////////////
// Basic interface functions for communicating with the MFRC522
/////////////////////////////////////////////////////////////////////////////////////
/**
* Writes a uint8_t to the specified register in the MFRC522 chip.
* The interface is described in the datasheet section 8.1.2.
*/
void ICACHE_FLASH_ATTR MFRC522_PCD_WriteRegister( uint8_t reg, ///< The register to write to. One of the PCD_Register enums.
uint8_t value ///< The value to write.
) {
uint8_t buf;
dh_spi_set_cs_pin(_chipSelectPin);
dh_spi_set_mode(DH_SPI_CPOL0CPHA0);
buf = reg & 0x7E; // MSB == 0 is for writing. LSB is not used in address. Datasheet section 8.1.2.3.
dh_spi_write(&buf, 1, 0);
dh_spi_write(&value, 1, 1);
} // End MFRC522_PCD_WriteRegister()
/**
* Writes a number of uint8_ts to the specified register in the MFRC522 chip.
* The interface is described in the datasheet section 8.1.2.
*/
void ICACHE_FLASH_ATTR MFRC522_PCD_WriteRegister_n( uint8_t reg, ///< The register to write to. One of the PCD_Register enums.
uint8_t count, ///< The number of uint8_ts to write to the register
uint8_t *values ///< The values to write. Byte array.
) {
uint8_t buf;
dh_spi_set_cs_pin(_chipSelectPin);
dh_spi_set_mode(DH_SPI_CPOL0CPHA0);
buf = reg & 0x7E; // MSB == 0 is for writing. LSB is not used in address. Datasheet section 8.1.2.3.
dh_spi_write(&buf, 1, 0);
dh_spi_write(values, count - 1, 0);
dh_spi_write(&values[count - 1], 1, 1);
} // End MFRC522_PCD_WriteRegister()
/**
* Reads a uint8_t from the specified register in the MFRC522 chip.
* The interface is described in the datasheet section 8.1.2.
*/
uint8_t ICACHE_FLASH_ATTR MFRC522_PCD_ReadRegister( uint8_t reg ///< The register to read from. One of the PCD_Register enums.
) {
uint8_t buf;
dh_spi_set_cs_pin(_chipSelectPin);
dh_spi_set_mode(DH_SPI_CPOL0CPHA0);
buf = 0x80 | (reg & 0x7E); // MSB == 1 is for reading. LSB is not used in address. Datasheet section 8.1.2.3.
dh_spi_write(&buf, 1, 0);
dh_spi_read(&buf, 1);
return buf;
} // End MFRC522_PCD_ReadRegister()
/**
* Reads a number of uint8_ts from the specified register in the MFRC522 chip.
* The interface is described in the datasheet section 8.1.2.
*/
void ICACHE_FLASH_ATTR MFRC522_PCD_ReadRegister_n( uint8_t reg, ///< The register to read from. One of the PCD_Register enums.
uint8_t count, ///< The number of uint8_ts to read
uint8_t *values, ///< Byte array to store the values in.
uint8_t rxAlign ///< Only bit positions rxAlign..7 in values[0] are updated.
) {
if (count == 0) {
return;
}
//Serial.print(F("Reading ")); Serial.print(count); Serial.println(F(" uint8_ts from register."));
uint8_t address = 0x80 | (reg & 0x7E); // MSB == 1 is for reading. LSB is not used in address. Datasheet section 8.1.2.3.
uint8_t index = 0; // Index in values array.
dh_spi_set_mode(DH_SPI_CPOL0CPHA0); // Set the settings to work with SPI bus
dh_spi_set_cs_pin(_chipSelectPin); // Select slave
count--; // One read is performed outside of the loop
dh_spi_write(&address, 1, 0); // Tell MFRC522 which address we want to read
while (index < count) {
if (index == 0 && rxAlign) { // Only update bit positions rxAlign..7 in values[0]
// Create bit mask for bit positions rxAlign..7
uint8_t mask = 0;
uint8_t i;
for (i = rxAlign; i <= 7; i++) {
mask |= (1 << i);
}
// Read value and tell that we want to read the same address again.
uint8_t value;
dh_spi_read(&value, 1);
dh_spi_write(&address, 1, 0);
// Apply mask to both current value of values[0] and the new data in value.
values[0] = (values[index] & ~mask) | (value & mask);
}
else { // Normal case
dh_spi_read(&values[index], 1);
dh_spi_write(&address, 1, 0);
}
index++;
}
dh_spi_read(&values[index], 1); // Read the final uint8_t.
} // End MFRC522_PCD_ReadRegister()
/**
* Sets the bits given in mask in register reg.
*/
void ICACHE_FLASH_ATTR MFRC522_PCD_SetRegisterBitMask( uint8_t reg, ///< The register to update. One of the PCD_Register enums.
uint8_t mask ///< The bits to set.
) {
uint8_t tmp;
tmp = MFRC522_PCD_ReadRegister(reg);
MFRC522_PCD_WriteRegister(reg, tmp | mask); // set bit mask
} // End MFRC522_PCD_SetRegisterBitMask()
/**
* Clears the bits given in mask from register reg.
*/
void ICACHE_FLASH_ATTR MFRC522_PCD_ClearRegisterBitMask( uint8_t reg, ///< The register to update. One of the PCD_Register enums.
uint8_t mask ///< The bits to clear.
) {
uint8_t tmp;
tmp = MFRC522_PCD_ReadRegister(reg);
MFRC522_PCD_WriteRegister(reg, tmp & (~mask)); // clear bit mask
} // End MFRC522_PCD_ClearRegisterBitMask()
/**
* Use the CRC coprocessor in the MFRC522 to calculate a CRC_A.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_PCD_CalculateCRC( uint8_t *data, ///< In: Pointer to the data to transfer to the FIFO for CRC calculation.
uint8_t length, ///< In: The number of uint8_ts to transfer.
uint8_t *result ///< Out: Pointer to result buffer. Result is written to result[0..1], low uint8_t first.
) {
MFRC522_PCD_WriteRegister(CommandReg, PCD_Idle); // Stop any active command.
MFRC522_PCD_WriteRegister(DivIrqReg, 0x04); // Clear the CRCIRq interrupt request bit
MFRC522_PCD_SetRegisterBitMask(FIFOLevelReg, 0x80); // FlushBuffer = 1, FIFO initialization
MFRC522_PCD_WriteRegister_n(FIFODataReg, length, data); // Write data to the FIFO
MFRC522_PCD_WriteRegister(CommandReg, PCD_CalcCRC); // Start the calculation
// Wait for the CRC calculation to complete. Each iteration of the while-loop takes 17.73μs.
// TODO check/modify for other architectures than Arduino Uno 16bit
uint16_t i = 5000;
uint8_t n;
while (1) {
n = MFRC522_PCD_ReadRegister(DivIrqReg); // DivIrqReg[7..0] bits are: Set2 reserved reserved MfinActIRq reserved CRCIRq reserved reserved
if (n & 0x04) { // CRCIRq bit set - calculation done
break;
}
if (--i == 0) { // The emergency break. We will eventually terminate on this one after 89ms. Communication with the MFRC522 might be down.
return MFRC522_STATUS_TIMEOUT;
}
}
MFRC522_PCD_WriteRegister(CommandReg, PCD_Idle); // Stop calculating CRC for new content in the FIFO.
// Transfer the result from the registers to the result buffer
result[0] = MFRC522_PCD_ReadRegister(CRCResultRegL);
result[1] = MFRC522_PCD_ReadRegister(CRCResultRegH);
return MFRC522_STATUS_OK;
} // End MFRC522_PCD_CalculateCRC()
/////////////////////////////////////////////////////////////////////////////////////
// Functions for manipulating the MFRC522
/////////////////////////////////////////////////////////////////////////////////////
/**
* Initializes the MFRC522 chip.
*/
void ICACHE_FLASH_ATTR MFRC522_PCD_Init() {
// Set the chipSelectPin as digital output, do not select the slave yet
dh_spi_set_cs_pin(_chipSelectPin);
dh_spi_set_mode(DH_SPI_CPOL0CPHA0);
// When communicating with a PICC we need a timeout if something goes wrong.
// f_timer = 13.56 MHz / (2*TPreScaler+1) where TPreScaler = [TPrescaler_Hi:TPrescaler_Lo].
// TPrescaler_Hi are the four low bits in TModeReg. TPrescaler_Lo is TPrescalerReg.
MFRC522_PCD_WriteRegister(TModeReg, 0x80); // TAuto=1; timer starts automatically at the end of the transmission in all communication modes at all speeds
MFRC522_PCD_WriteRegister(TPrescalerReg, 0xA9); // TPreScaler = TModeReg[3..0]:TPrescalerReg, ie 0x0A9 = 169 => f_timer=40kHz, ie a timer period of 25μs.
MFRC522_PCD_WriteRegister(TReloadRegH, 0x03); // Reload timer with 0x3E8 = 1000, ie 25ms before timeout.
MFRC522_PCD_WriteRegister(TReloadRegL, 0xE8);
MFRC522_PCD_WriteRegister(TxASKReg, 0x40); // Default 0x00. Force a 100 % ASK modulation independent of the ModGsPReg register setting
MFRC522_PCD_WriteRegister(ModeReg, 0x3D); // Default 0x3F. Set the preset value for the CRC coprocessor for the CalcCRC command to 0x6363 (ISO 14443-3 part 6.2.4)
MFRC522_PCD_AntennaOn(); // Enable the antenna driver pins TX1 and TX2 (they were disabled by the reset)
} // End PCD_Init()
/**
* Performs a soft reset on the MFRC522 chip and waits for it to be ready again.
*/
void ICACHE_FLASH_ATTR MFRC522_PCD_Reset() {
MFRC522_PCD_WriteRegister(CommandReg, PCD_SoftReset); // Issue the SoftReset command.
// The datasheet does not mention how long the SoftRest command takes to complete.
// But the MFRC522 might have been in soft power-down mode (triggered by bit 4 of CommandReg)
// Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74μs. Let us be generous: 50ms.
os_delay_us(50000);
// Wait for the PowerDown bit in CommandReg to be cleared
while (MFRC522_PCD_ReadRegister(CommandReg) & (1<<4)) {
// PCD still restarting - unlikely after waiting 50ms, but better safe than sorry.
}
} // End MFRC522_PCD_Reset()
/**
* Turns the antenna on by enabling pins TX1 and TX2.
* After a reset these pins are disabled.
*/
void ICACHE_FLASH_ATTR MFRC522_PCD_AntennaOn() {
uint8_t value = MFRC522_PCD_ReadRegister(TxControlReg);
if ((value & 0x03) != 0x03) {
MFRC522_PCD_WriteRegister(TxControlReg, value | 0x03);
}
} // End MFRC522_PCD_AntennaOn()
/**
* Turns the antenna off by disabling pins TX1 and TX2.
*/
void ICACHE_FLASH_ATTR MFRC522_PCD_AntennaOff() {
MFRC522_PCD_ClearRegisterBitMask(TxControlReg, 0x03);
} // End PCD_AntennaOff()
/**
* Get the current MFRC522 Receiver Gain (RxGain[2:0]) value.
* See 9.3.3.6 / table 98 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf
* NOTE: Return value scrubbed with (0x07<<4)=01110000b as RCFfgReg may use reserved bits.
*
* @return Value of the RxGain, scrubbed to the 3 bits used.
*/
uint8_t ICACHE_FLASH_ATTR MFRC522_PCD_GetAntennaGain() {
return MFRC522_PCD_ReadRegister(RFCfgReg) & (0x07<<4);
} // End MFRC522_PCD_GetAntennaGain()
/**
* Set the MFRC522 Receiver Gain (RxGain) to value specified by given mask.
* See 9.3.3.6 / table 98 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf
* NOTE: Given mask is scrubbed with (0x07<<4)=01110000b as RCFfgReg may use reserved bits.
*/
void ICACHE_FLASH_ATTR MFRC522_PCD_SetAntennaGain(uint8_t mask) {
if (MFRC522_PCD_GetAntennaGain() != mask) { // only bother if there is a change
MFRC522_PCD_ClearRegisterBitMask(RFCfgReg, (0x07<<4)); // clear needed to allow 000 pattern
MFRC522_PCD_SetRegisterBitMask(RFCfgReg, mask & (0x07<<4)); // only set RxGain[2:0] bits
}
} // End PCD_SetAntennaGain()
/**
* Performs a self-test of the MFRC522
* See 16.1.1 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf
*
* @return Whether or not the test passed. Or false if no firmware reference is available.
*/
bool ICACHE_FLASH_ATTR MFRC522_PCD_PerformSelfTest() {
// This follows directly the steps outlined in 16.1.1
// 1. Perform a soft reset.
MFRC522_PCD_Reset();
// 2. Clear the internal buffer by writing 25 uint8_ts of 00h
uint8_t ZEROES[25] = {0x00};
MFRC522_PCD_SetRegisterBitMask(FIFOLevelReg, 0x80); // flush the FIFO buffer
MFRC522_PCD_WriteRegister_n(FIFODataReg, 25, ZEROES); // write 25 uint8_ts of 00h to FIFO
MFRC522_PCD_WriteRegister(CommandReg, PCD_Mem); // transfer to internal buffer
// 3. Enable self-test
MFRC522_PCD_WriteRegister(AutoTestReg, 0x09);
// 4. Write 00h to FIFO buffer
MFRC522_PCD_WriteRegister(FIFODataReg, 0x00);
// 5. Start self-test by issuing the CalcCRC command
MFRC522_PCD_WriteRegister(CommandReg, PCD_CalcCRC);
// 6. Wait for self-test to complete
uint8_t n;
uint8_t i;
for (i = 0; i < 0xFF; i++) {
// The datasheet does not specify exact completion condition except
// that FIFO buffer should contain 64 uint8_ts.
// While selftest is initiated by CalcCRC command
// it behaves differently from normal CRC computation,
// so one can't reliably use DivIrqReg to check for completion.
// It is reported that some devices does not trigger CRCIRq flag
// during selftest.
n = MFRC522_PCD_ReadRegister(FIFOLevelReg);
if (n >= 64) {
break;
}
}
MFRC522_PCD_WriteRegister(CommandReg, PCD_Idle); // Stop calculating CRC for new content in the FIFO.
// 7. Read out resulting 64 uint8_ts from the FIFO buffer.
uint8_t result[64];
MFRC522_PCD_ReadRegister_n(FIFODataReg, 64, result, 0);
// Auto self-test done
// Reset AutoTestReg register to be 0 again. Required for normal operation.
MFRC522_PCD_WriteRegister(AutoTestReg, 0x00);
// Determine firmware version (see section 9.3.4.8 in spec)
uint8_t version = MFRC522_PCD_ReadRegister(VersionReg);
// Pick the appropriate reference values
const uint8_t *reference;
switch (version) {
case 0x88: // Fudan Semiconductor FM17522 clone
reference = FM17522_firmware_reference;
break;
case 0x90: // Version 0.0
reference = MFRC522_firmware_referenceV0_0;
break;
case 0x91: // Version 1.0
reference = MFRC522_firmware_referenceV1_0;
break;
case 0x92: // Version 2.0
reference = MFRC522_firmware_referenceV2_0;
break;
default: // Unknown version
return false; // abort test
}
// Verify that the results match up to our expectations
if (0 != irom_cmp(result, 64, reference))
return false;
// Test passed; all is good.
return true;
} // End PCD_PerformSelfTest()
/////////////////////////////////////////////////////////////////////////////////////
// Functions for communicating with PICCs
/////////////////////////////////////////////////////////////////////////////////////
/**
* Executes the Transceive command.
* CRC validation can only be done if backData and backLen are specified.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_PCD_TransceiveData( uint8_t *sendData, ///< Pointer to the data to transfer to the FIFO.
uint8_t sendLen, ///< Number of uint8_ts to transfer to the FIFO.
uint8_t *backData, ///< NULL or pointer to buffer if data should be read back after executing the command.
uint8_t *backLen, ///< In: Max number of uint8_ts to write to *backData. Out: The number of uint8_ts returned.
uint8_t *validBits, ///< In/Out: The number of valid bits in the last uint8_t. 0 for 8 valid bits. Default NULL.
uint8_t rxAlign, ///< In: Defines the bit position in backData[0] for the first bit received. Default 0.
bool checkCRC ///< In: True => The last two uint8_ts of the response is assumed to be a CRC_A that must be validated.
) {
uint8_t waitIRq = 0x30; // RxIRq and IdleIRq
return MFRC522_PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, sendData, sendLen, backData, backLen, validBits, rxAlign, checkCRC);
} // End MFRC522_PCD_TransceiveData()
/**
* Transfers data to the MFRC522 FIFO, executes a command, waits for completion and transfers data back from the FIFO.
* CRC validation can only be done if backData and backLen are specified.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_PCD_CommunicateWithPICC( uint8_t command, ///< The command to execute. One of the PCD_Command enums.
uint8_t waitIRq, ///< The bits in the ComIrqReg register that signals successful completion of the command.
uint8_t *sendData, ///< Pointer to the data to transfer to the FIFO.
uint8_t sendLen, ///< Number of uint8_ts to transfer to the FIFO.
uint8_t *backData, ///< NULL or pointer to buffer if data should be read back after executing the command.
uint8_t *backLen, ///< In: Max number of uint8_ts to write to *backData. Out: The number of uint8_ts returned.
uint8_t *validBits, ///< In/Out: The number of valid bits in the last uint8_t. 0 for 8 valid bits.
uint8_t rxAlign, ///< In: Defines the bit position in backData[0] for the first bit received. Default 0.
bool checkCRC ///< In: True => The last two uint8_ts of the response is assumed to be a CRC_A that must be validated.
) {
uint8_t n, _validBits;
uint16_t i;
// Prepare values for BitFramingReg
uint8_t txLastBits = validBits ? *validBits : 0;
uint8_t bitFraming = (rxAlign << 4) + txLastBits; // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0]
MFRC522_PCD_WriteRegister(CommandReg, PCD_Idle); // Stop any active command.
MFRC522_PCD_WriteRegister(ComIrqReg, 0x7F); // Clear all seven interrupt request bits
MFRC522_PCD_SetRegisterBitMask(FIFOLevelReg, 0x80); // FlushBuffer = 1, FIFO initialization
MFRC522_PCD_WriteRegister_n(FIFODataReg, sendLen, sendData); // Write sendData to the FIFO
MFRC522_PCD_WriteRegister(BitFramingReg, bitFraming); // Bit adjustments
MFRC522_PCD_WriteRegister(CommandReg, command); // Execute the command
if (command == PCD_Transceive) {
MFRC522_PCD_SetRegisterBitMask(BitFramingReg, 0x80); // StartSend=1, transmission of data starts
}
// Wait for the command to complete.
// In PCD_Init() we set the TAuto flag in TModeReg. This means the timer automatically starts when the PCD stops transmitting.
// Each iteration of the do-while-loop takes 17.86μs.
// TODO check/modify for other architectures than Arduino Uno 16bit
i = 250;
while (1) {
n = MFRC522_PCD_ReadRegister(ComIrqReg); // ComIrqReg[7..0] bits are: Set1 TxIRq RxIRq IdleIRq HiAlertIRq LoAlertIRq ErrIRq TimerIRq
if (n & waitIRq) { // One of the interrupts that signal success has been set.
break;
}
if (n & 0x01) { // Timer interrupt - nothing received in 25ms
return MFRC522_STATUS_TIMEOUT;
}
if (--i == 0) { // The emergency break. If all other conditions fail we will eventually terminate on this one after 35.7ms. Communication with the MFRC522 might be down.
return MFRC522_STATUS_TIMEOUT;
}
os_delay_us(1000);
}
// Stop now if any errors except collisions were detected.
uint8_t errorRegValue = MFRC522_PCD_ReadRegister(ErrorReg); // ErrorReg[7..0] bits are: WrErr TempErr reserved BufferOvfl CollErr CRCErr ParityErr ProtocolErr
if (errorRegValue & 0x13) { // BufferOvfl ParityErr ProtocolErr
return MFRC522_STATUS_ERROR;
}
// If the caller wants data back, get it from the MFRC522.
if (backData && backLen) {
n = MFRC522_PCD_ReadRegister(FIFOLevelReg); // Number of uint8_ts in the FIFO
if (n > *backLen) {
return MFRC522_STATUS_NO_ROOM;
}
*backLen = n; // Number of uint8_ts returned
MFRC522_PCD_ReadRegister_n(FIFODataReg, n, backData, rxAlign); // Get received data from FIFO
_validBits = MFRC522_PCD_ReadRegister(ControlReg) & 0x07; // RxLastBits[2:0] indicates the number of valid bits in the last received uint8_t. If this value is 000b, the whole uint8_t is valid.
if (validBits) {
*validBits = _validBits;
}
}
// Tell about collisions
if (errorRegValue & 0x08) { // CollErr
return MFRC522_STATUS_COLLISION;
}
// Perform CRC_A validation if requested.
if (backData && backLen && checkCRC) {
// In this case a MIFARE Classic NAK is not OK.
if (*backLen == 1 && _validBits == 4) {
return MFRC522_STATUS_MIFARE_NACK;
}
// We need at least the CRC_A value and all 8 bits of the last uint8_t must be received.
if (*backLen < 2 || _validBits != 0) {
return MFRC522_STATUS_CRC_WRONG;
}
// Verify CRC_A - do our own calculation and store the control in controlBuffer.
uint8_t controlBuffer[2];
MFRC522_StatusCode status = MFRC522_PCD_CalculateCRC(&backData[0], *backLen - 2, &controlBuffer[0]);
if (status != MFRC522_STATUS_OK) {
return status;
}
if ((backData[*backLen - 2] != controlBuffer[0]) || (backData[*backLen - 1] != controlBuffer[1])) {
return MFRC522_STATUS_CRC_WRONG;
}
}
return MFRC522_STATUS_OK;
} // End MFRC522_PCD_CommunicateWithPICC()
/**
* Transmits a REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for anticollision or selection. 7 bit frame.
* Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_PICC_RequestA( uint8_t *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in
uint8_t *bufferSize ///< Buffer size, at least two uint8_ts. Also number of uint8_ts returned if STATUS_OK.
) {
return MFRC522_PICC_REQA_or_WUPA(PICC_CMD_REQA, bufferATQA, bufferSize);
} // End MFRC522_PICC_RequestA()
/**
* Transmits a Wake-UP command, Type A. Invites PICCs in state IDLE and HALT to go to READY(*) and prepare for anticollision or selection. 7 bit frame.
* Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_PICC_WakeupA( uint8_t *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in
uint8_t *bufferSize ///< Buffer size, at least two uint8_ts. Also number of uint8_ts returned if STATUS_OK.
) {
return MFRC522_PICC_REQA_or_WUPA(PICC_CMD_WUPA, bufferATQA, bufferSize);
} // End MFRC522_PICC_WakeupA()
/**
* Transmits REQA or WUPA commands.
* Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_PICC_REQA_or_WUPA( uint8_t command, ///< The command to send - PICC_CMD_REQA or PICC_CMD_WUPA
uint8_t *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in
uint8_t *bufferSize ///< Buffer size, at least two uint8_ts. Also number of uint8_ts returned if STATUS_OK.
) {
uint8_t validBits;
MFRC522_StatusCode status;
if (bufferATQA == NULL || *bufferSize < 2) { // The ATQA response is 2 uint8_ts long.
return MFRC522_STATUS_NO_ROOM;
}
MFRC522_PCD_ClearRegisterBitMask(CollReg, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared.
validBits = 7; // For REQA and WUPA we need the short frame format - transmit only 7 bits of the last (and only) uint8_t. TxLastBits = BitFramingReg[2..0]
status = MFRC522_PCD_TransceiveData(&command, 1, bufferATQA, bufferSize, &validBits, 0, false);
if (status != MFRC522_STATUS_OK) {
return status;
}
if (*bufferSize != 2 || validBits != 0) { // ATQA must be exactly 16 bits.
return MFRC522_STATUS_ERROR;
}
return MFRC522_STATUS_OK;
} // End MFRC522_PICC_REQA_or_WUPA()
/**
* Transmits SELECT/ANTICOLLISION commands to select a single PICC.
* Before calling this function the PICCs must be placed in the READY(*) state by calling MFRC522_PICC_RequestA() or MFRC522_PICC_WakeupA().
* On success:
* - The chosen PICC is in state ACTIVE(*) and all other PICCs have returned to state IDLE/HALT. (Figure 7 of the ISO/IEC 14443-3 draft.)
* - The UID size and value of the chosen PICC is returned in *uid along with the SAK.
*
* A PICC UID consists of 4, 7 or 10 uint8_ts.
* Only 4 uint8_ts can be specified in a SELECT command, so for the longer UIDs two or three iterations are used:
* UID size Number of UID uint8_ts Cascade levels Example of PICC
* ======== =================== ============== ===============
* single 4 1 MIFARE Classic
* double 7 2 MIFARE Ultralight
* triple 10 3 Not currently in use?
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_PICC_Select( MFRC522_Uid *uid, ///< Pointer to Uid struct. Normally output, but can also be used to supply a known UID.
uint8_t validBits ///< The number of known UID bits supplied in *uid. Normally 0. If set you must also supply uid->size.
) {
bool uidComplete;
bool selectDone;
bool useCascadeTag;
uint8_t cascadeLevel = 1;
MFRC522_StatusCode result;
uint8_t count;
uint8_t index;
uint8_t uidIndex; // The first index in uid->uidByte[] that is used in the current Cascade Level.
int8_t currentLevelKnownBits; // The number of known UID bits in the current Cascade Level.
uint8_t buffer[9]; // The SELECT/ANTICOLLISION commands uses a 7 uint8_t standard frame + 2 uint8_ts CRC_A
uint8_t bufferUsed; // The number of uint8_ts used in the buffer, ie the number of uint8_ts to transfer to the FIFO.
uint8_t rxAlign; // Used in BitFramingReg. Defines the bit position for the first bit received.
uint8_t txLastBits; // Used in BitFramingReg. The number of valid bits in the last transmitted uint8_t.
uint8_t *responseBuffer;
uint8_t responseLength;
// Description of buffer structure:
// Byte 0: SEL Indicates the Cascade Level: PICC_CMD_SEL_CL1, PICC_CMD_SEL_CL2 or PICC_CMD_SEL_CL3
// Byte 1: NVB Number of Valid Bits (in complete command, not just the UID): High nibble: complete uint8_ts, Low nibble: Extra bits.
// Byte 2: UID-data or CT See explanation below. CT means Cascade Tag.
// Byte 3: UID-data
// Byte 4: UID-data
// Byte 5: UID-data
// Byte 6: BCC Block Check Character - XOR of uint8_ts 2-5
// Byte 7: CRC_A
// Byte 8: CRC_A
// The BCC and CRC_A are only transmitted if we know all the UID bits of the current Cascade Level.
//
// Description of uint8_ts 2-5: (Section 6.5.4 of the ISO/IEC 14443-3 draft: UID contents and cascade levels)
// UID size Cascade level Byte2 Byte3 Byte4 Byte5
// ======== ============= ===== ===== ===== =====
// 4 uint8_ts 1 uid0 uid1 uid2 uid3
// 7 uint8_ts 1 CT uid0 uid1 uid2
// 2 uid3 uid4 uid5 uid6
// 10 uint8_ts 1 CT uid0 uid1 uid2
// 2 CT uid3 uid4 uid5
// 3 uid6 uid7 uid8 uid9
// Sanity checks
if (validBits > 80) {
return MFRC522_STATUS_INVALID;
}
// Prepare MFRC522
MFRC522_PCD_ClearRegisterBitMask(CollReg, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared.
// Repeat Cascade Level loop until we have a complete UID.
uidComplete = false;
while (!uidComplete) {
// Set the Cascade Level in the SEL uint8_t, find out if we need to use the Cascade Tag in uint8_t 2.
switch (cascadeLevel) {
case 1:
buffer[0] = PICC_CMD_SEL_CL1;
uidIndex = 0;
useCascadeTag = validBits && uid->size > 4; // When we know that the UID has more than 4 uint8_ts
break;
case 2:
buffer[0] = PICC_CMD_SEL_CL2;
uidIndex = 3;
useCascadeTag = validBits && uid->size > 7; // When we know that the UID has more than 7 uint8_ts
break;
case 3:
buffer[0] = PICC_CMD_SEL_CL3;
uidIndex = 6;
useCascadeTag = false; // Never used in CL3.
break;
default:
return MFRC522_STATUS_INTERNAL_ERROR;
break;
}
// How many UID bits are known in this Cascade Level?
currentLevelKnownBits = validBits - (8 * uidIndex);
if (currentLevelKnownBits < 0) {
currentLevelKnownBits = 0;
}
// Copy the known bits from uid->uidByte[] to buffer[]
index = 2; // destination index in buffer[]
if (useCascadeTag) {
buffer[index++] = PICC_CMD_CT;
}
uint8_t uint8_tsToCopy = currentLevelKnownBits / 8 + (currentLevelKnownBits % 8 ? 1 : 0); // The number of uint8_ts needed to represent the known bits for this level.
if (uint8_tsToCopy) {
uint8_t maxBytes = useCascadeTag ? 3 : 4; // Max 4 uint8_ts in each Cascade Level. Only 3 left if we use the Cascade Tag
if (uint8_tsToCopy > maxBytes) {
uint8_tsToCopy = maxBytes;
}
for (count = 0; count < uint8_tsToCopy; count++) {
buffer[index++] = uid->uidByte[uidIndex + count];
}
}
// Now that the data has been copied we need to include the 8 bits in CT in currentLevelKnownBits
if (useCascadeTag) {
currentLevelKnownBits += 8;
}
// Repeat anti collision loop until we can transmit all UID bits + BCC and receive a SAK - max 32 iterations.
selectDone = false;
while (!selectDone) {
// Find out how many bits and uint8_ts to send and receive.
if (currentLevelKnownBits >= 32) { // All UID bits in this Cascade Level are known. This is a SELECT.
//Serial.print(F("SELECT: currentLevelKnownBits=")); Serial.println(currentLevelKnownBits, DEC);
buffer[1] = 0x70; // NVB - Number of Valid Bits: Seven whole uint8_ts
// Calculate BCC - Block Check Character
buffer[6] = buffer[2] ^ buffer[3] ^ buffer[4] ^ buffer[5];
// Calculate CRC_A
result = MFRC522_PCD_CalculateCRC(buffer, 7, &buffer[7]);
if (result != MFRC522_STATUS_OK) {
return result;
}
txLastBits = 0; // 0 => All 8 bits are valid.
bufferUsed = 9;
// Store response in the last 3 uint8_ts of buffer (BCC and CRC_A - not needed after tx)
responseBuffer = &buffer[6];
responseLength = 3;
}
else { // This is an ANTICOLLISION.
//Serial.print(F("ANTICOLLISION: currentLevelKnownBits=")); Serial.println(currentLevelKnownBits, DEC);
txLastBits = currentLevelKnownBits % 8;
count = currentLevelKnownBits / 8; // Number of whole uint8_ts in the UID part.
index = 2 + count; // Number of whole uint8_ts: SEL + NVB + UIDs
buffer[1] = (index << 4) + txLastBits; // NVB - Number of Valid Bits
bufferUsed = index + (txLastBits ? 1 : 0);
// Store response in the unused part of buffer
responseBuffer = &buffer[index];
responseLength = sizeof(buffer) - index;
}
// Set bit adjustments
rxAlign = txLastBits; // Having a separate variable is overkill. But it makes the next line easier to read.
MFRC522_PCD_WriteRegister(BitFramingReg, (rxAlign << 4) + txLastBits); // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0]
// Transmit the buffer and receive the response.
result = MFRC522_PCD_TransceiveData(buffer, bufferUsed, responseBuffer, &responseLength, &txLastBits, rxAlign, false);
if (result == MFRC522_STATUS_COLLISION) { // More than one PICC in the field => collision.
uint8_t valueOfCollReg = MFRC522_PCD_ReadRegister(CollReg); // CollReg[7..0] bits are: ValuesAfterColl reserved CollPosNotValid CollPos[4:0]
if (valueOfCollReg & 0x20) { // CollPosNotValid
return MFRC522_STATUS_COLLISION; // Without a valid collision position we cannot continue
}
uint8_t collisionPos = valueOfCollReg & 0x1F; // Values 0-31, 0 means bit 32.
if (collisionPos == 0) {
collisionPos = 32;
}
if (collisionPos <= currentLevelKnownBits) { // No progress - should not happen
return MFRC522_STATUS_INTERNAL_ERROR;
}
// Choose the PICC with the bit set.
currentLevelKnownBits = collisionPos;
count = (currentLevelKnownBits - 1) % 8; // The bit to modify
index = 1 + (currentLevelKnownBits / 8) + (count ? 1 : 0); // First uint8_t is index 0.
buffer[index] |= (1 << count);
}
else if (result != MFRC522_STATUS_OK) {
return result;
}
else { // STATUS_OK
if (currentLevelKnownBits >= 32) { // This was a SELECT.
selectDone = true; // No more anticollision
// We continue below outside the while.
}
else { // This was an ANTICOLLISION.
// We now have all 32 bits of the UID in this Cascade Level
currentLevelKnownBits = 32;
// Run loop again to do the SELECT.
}
}
} // End of while (!selectDone)
// We do not check the CBB - it was constructed by us above.
// Copy the found UID uint8_ts from buffer[] to uid->uidByte[]
index = (buffer[2] == PICC_CMD_CT) ? 3 : 2; // source index in buffer[]
uint8_tsToCopy = (buffer[2] == PICC_CMD_CT) ? 3 : 4;
for (count = 0; count < uint8_tsToCopy; count++) {
uid->uidByte[uidIndex + count] = buffer[index++];
}
// Check response SAK (Select Acknowledge)
if (responseLength != 3 || txLastBits != 0) { // SAK must be exactly 24 bits (1 uint8_t + CRC_A).
return MFRC522_STATUS_ERROR;
}
// Verify CRC_A - do our own calculation and store the control in buffer[2..3] - those uint8_ts are not needed anymore.
result = MFRC522_PCD_CalculateCRC(responseBuffer, 1, &buffer[2]);
if (result != MFRC522_STATUS_OK) {
return result;
}
if ((buffer[2] != responseBuffer[1]) || (buffer[3] != responseBuffer[2])) {
return MFRC522_STATUS_CRC_WRONG;
}
if (responseBuffer[0] & 0x04) { // Cascade bit set - UID not complete yes
cascadeLevel++;
}
else {
uidComplete = true;
uid->sak = responseBuffer[0];
}
} // End of while (!uidComplete)
// Set correct uid->size
uid->size = 3 * cascadeLevel + 1;
return MFRC522_STATUS_OK;
} // End MFRC522_PICC_Select()
/**
* Instructs a PICC in state ACTIVE(*) to go to state HALT.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_PICC_HaltA() {
MFRC522_StatusCode result;
uint8_t buffer[4];
// Build command buffer
buffer[0] = PICC_CMD_HLTA;
buffer[1] = 0;
// Calculate CRC_A
result = MFRC522_PCD_CalculateCRC(buffer, 2, &buffer[2]);
if (result != MFRC522_STATUS_OK) {
return result;
}
// Send the command.
// The standard says:
// If the PICC responds with any modulation during a period of 1 ms after the end of the frame containing the
// HLTA command, this response shall be interpreted as 'not acknowledge'.
// We interpret that this way: Only STATUS_TIMEOUT is a success.
result = MFRC522_PCD_TransceiveData(buffer, sizeof(buffer), NULL, 0, NULL, 0, false);
if (result == MFRC522_STATUS_TIMEOUT) {
return MFRC522_STATUS_OK;
}
if (result == MFRC522_STATUS_OK) { // That is ironically NOT ok in this case ;-)
return MFRC522_STATUS_ERROR;
}
return result;
} // End MFRC522_PICC_HaltA()
/////////////////////////////////////////////////////////////////////////////////////
// Functions for communicating with MIFARE PICCs
/////////////////////////////////////////////////////////////////////////////////////
/**
* Executes the MFRC522 MFAuthent command.
* This command manages MIFARE authentication to enable a secure communication to any MIFARE Mini, MIFARE 1K and MIFARE 4K card.
* The authentication is described in the MFRC522 datasheet section 10.3.1.9 and http://www.nxp.com/documents/data_sheet/MF1S503x.pdf section 10.1.
* For use with MIFARE Classic PICCs.
* The PICC must be selected - ie in state ACTIVE(*) - before calling this function.
* Remember to call MFRC522_PCD_StopCrypto1() after communicating with the authenticated PICC - otherwise no new communications can start.
*
* All keys are set to FFFFFFFFFFFFh at chip delivery.
*
* @return STATUS_OK on success, STATUS_??? otherwise. Probably STATUS_TIMEOUT if you supply the wrong key.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_PCD_Authenticate(uint8_t command, ///< PICC_CMD_MF_AUTH_KEY_A or PICC_CMD_MF_AUTH_KEY_B
uint8_t blockAddr, ///< The block number. See numbering in the comments in the .h file.
MIFARE_Key *key, ///< Pointer to the Crypteo1 key to use (6 uint8_ts)
MFRC522_Uid *uid ///< Pointer to Uid struct. The first 4 uint8_ts of the UID is used.
) {
uint8_t waitIRq = 0x10; // IdleIRq
// Build command buffer
uint8_t sendData[12];
sendData[0] = command;
sendData[1] = blockAddr;
uint8_t i;
for (i = 0; i < MF_KEY_SIZE; i++) { // 6 key uint8_ts
sendData[2+i] = key->keyByte[i];
}
// Use the last uid uint8_ts as specified in http://cache.nxp.com/documents/application_note/AN10927.pdf
// section 3.2.5 "MIFARE Classic Authentication".
// The only missed case is the MF1Sxxxx shortcut activation,
// but it requires cascade tag (CT) uint8_t, that is not part of uid.
for (i = 0; i < 4; i++) { // The last 4 uint8_ts of the UID
sendData[8+i] = uid->uidByte[i+uid->size-4];
}
// Start the authentication.
return MFRC522_PCD_CommunicateWithPICC(PCD_MFAuthent, waitIRq, &sendData[0], sizeof(sendData), NULL, NULL, NULL, 0 , false);
} // End MFRC522_PCD_Authenticate()
/**
* Used to exit the PCD from its authenticated state.
* Remember to call this function after communicating with an authenticated PICC - otherwise no new communications can start.
*/
void ICACHE_FLASH_ATTR MFRC522_PCD_StopCrypto1() {
// Clear MFCrypto1On bit
MFRC522_PCD_ClearRegisterBitMask(Status2Reg, 0x08); // Status2Reg[7..0] bits are: TempSensClear I2CForceHS reserved reserved MFCrypto1On ModemState[2:0]
} // End MFRC522_PCD_StopCrypto1()
/**
* Reads 16 uint8_ts (+ 2 uint8_ts CRC_A) from the active PICC.
*
* For MIFARE Classic the sector containing the block must be authenticated before calling this function.
*
* For MIFARE Ultralight only addresses 00h to 0Fh are decoded.
* The MF0ICU1 returns a NAK for higher addresses.
* The MF0ICU1 responds to the READ command by sending 16 uint8_ts starting from the page address defined by the command argument.
* For example; if blockAddr is 03h then pages 03h, 04h, 05h, 06h are returned.
* A roll-back is implemented: If blockAddr is 0Eh, then the contents of pages 0Eh, 0Fh, 00h and 01h are returned.
*
* The buffer must be at least 16 uint8_ts. CRC_A is checked.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_MIFARE_Read( uint8_t blockAddr, ///< MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The first page to return data from.
uint8_t *buffer, ///< The buffer to store the data in
uint8_t *bufferSize ///< Buffer size, at least 18 uint8_ts. Also number of uint8_ts returned if STATUS_OK.
) {
MFRC522_StatusCode result;
// Sanity check
if (buffer == NULL || *bufferSize < 18) {
return MFRC522_STATUS_NO_ROOM;
}
// Build command buffer
buffer[0] = PICC_CMD_MF_READ;
buffer[1] = blockAddr;
// Calculate CRC_A
result = MFRC522_PCD_CalculateCRC(buffer, 2, &buffer[2]);
if (result != MFRC522_STATUS_OK) {
return result;
}
// Transmit the buffer and receive the response, validate CRC_A.
MFRC522_StatusCode status = MFRC522_PCD_TransceiveData(buffer, 4, buffer, bufferSize, NULL, 0, true);
if (status != MFRC522_STATUS_OK) {
return status;
}
// Verify CRC_A - do our own calculation and store the control in controlBuffer.
uint8_t controlBuffer[2];
status = MFRC522_PCD_CalculateCRC(&buffer[0], *bufferSize - 2, &controlBuffer[0]);
if (status != MFRC522_STATUS_OK) {
return status;
}
if ((buffer[*bufferSize - 2] != controlBuffer[0]) || (buffer[*bufferSize - 1] != controlBuffer[1])) {
return MFRC522_STATUS_CRC_WRONG;
}
*bufferSize -= 2;
return status;
} // End MFRC522_MIFARE_Read()
/**
* Writes 16 uint8_ts to the active PICC.
*
* For MIFARE Classic the sector containing the block must be authenticated before calling this function.
*
* For MIFARE Ultralight the operation is called "COMPATIBILITY WRITE".
* Even though 16 uint8_ts are transferred to the Ultralight PICC, only the least significant 4 uint8_ts (uint8_ts 0 to 3)
* are written to the specified address. It is recommended to set the remaining uint8_ts 04h to 0Fh to all logic 0.
* *
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_MIFARE_Write( uint8_t blockAddr, ///< MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The page (2-15) to write to.
uint8_t *buffer, ///< The 16 uint8_ts to write to the PICC
uint8_t bufferSize ///< Buffer size, must be at least 16 uint8_ts. Exactly 16 uint8_ts are written.
) {
MFRC522_StatusCode result;
// Sanity check
if (buffer == NULL || bufferSize < 16) {
return MFRC522_STATUS_INVALID;
}
// Mifare Classic protocol requires two communications to perform a write.
// Step 1: Tell the PICC we want to write to block blockAddr.
uint8_t cmdBuffer[2];
cmdBuffer[0] = PICC_CMD_MF_WRITE;
cmdBuffer[1] = blockAddr;
result = MFRC522_PCD_MIFARE_Transceive(cmdBuffer, 2, false); // Adds CRC_A and checks that the response is MF_ACK.
if (result != MFRC522_STATUS_OK) {
return result;
}
// Step 2: Transfer the data
result = MFRC522_PCD_MIFARE_Transceive(buffer, bufferSize, false); // Adds CRC_A and checks that the response is MF_ACK.
if (result != MFRC522_STATUS_OK) {
return result;
}
return MFRC522_STATUS_OK;
} // End MFRC522_MIFARE_Write()
/**
* Writes a 4 uint8_t page to the active MIFARE Ultralight PICC.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_MIFARE_Ultralight_Write( uint8_t page, ///< The page (2-15) to write to.
uint8_t *buffer, ///< The 4 uint8_ts to write to the PICC
uint8_t bufferSize ///< Buffer size, must be at least 4 uint8_ts. Exactly 4 uint8_ts are written.
) {
MFRC522_StatusCode result;
// Sanity check
if (buffer == NULL || bufferSize < 4) {
return MFRC522_STATUS_INVALID;
}
// Build commmand buffer
uint8_t cmdBuffer[6];
cmdBuffer[0] = PICC_CMD_UL_WRITE;
cmdBuffer[1] = page;
os_memcpy(&cmdBuffer[2], buffer, 4);
// Perform the write
result = MFRC522_PCD_MIFARE_Transceive(cmdBuffer, 6, false); // Adds CRC_A and checks that the response is MF_ACK.
if (result != MFRC522_STATUS_OK) {
return result;
}
return MFRC522_STATUS_OK;
} // End MIFARE_Ultralight_Write()
/**
* MIFARE Decrement subtracts the delta from the value of the addressed block, and stores the result in a volatile memory.
* For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
* Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
* Use MIFARE_Transfer() to store the result in a block.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_MIFARE_Decrement( uint8_t blockAddr, ///< The block (0-0xff) number.
int32_t delta ///< This number is subtracted from the value of block blockAddr.
) {
return MFRC522_MIFARE_TwoStepHelper(PICC_CMD_MF_DECREMENT, blockAddr, delta);
} // End MIFARE_Decrement()
/**
* MIFARE Increment adds the delta to the value of the addressed block, and stores the result in a volatile memory.
* For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
* Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
* Use MIFARE_Transfer() to store the result in a block.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_MIFARE_Increment( uint8_t blockAddr, ///< The block (0-0xff) number.
int32_t delta ///< This number is added to the value of block blockAddr.
) {
return MFRC522_MIFARE_TwoStepHelper(PICC_CMD_MF_INCREMENT, blockAddr, delta);
} // End MIFARE_Increment()
/**
* MIFARE Restore copies the value of the addressed block into a volatile memory.
* For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
* Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
* Use MIFARE_Transfer() to store the result in a block.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_MIFARE_Restore( uint8_t blockAddr ///< The block (0-0xff) number.
) {
// The datasheet describes Restore as a two step operation, but does not explain what data to transfer in step 2.
// Doing only a single step does not work, so I chose to transfer 0L in step two.
return MFRC522_MIFARE_TwoStepHelper(PICC_CMD_MF_RESTORE, blockAddr, 0L);
} // End MIFARE_Restore()
/**
* Helper function for the two-step MIFARE Classic protocol operations Decrement, Increment and Restore.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_MIFARE_TwoStepHelper( uint8_t command, ///< The command to use
uint8_t blockAddr, ///< The block (0-0xff) number.
int32_t data ///< The data to transfer in step 2
) {
MFRC522_StatusCode result;
uint8_t cmdBuffer[2]; // We only need room for 2 uint8_ts.
// Step 1: Tell the PICC the command and block address
cmdBuffer[0] = command;
cmdBuffer[1] = blockAddr;
result = MFRC522_PCD_MIFARE_Transceive( cmdBuffer, 2, false); // Adds CRC_A and checks that the response is MF_ACK.
if (result != MFRC522_STATUS_OK) {
return result;
}
// Step 2: Transfer the data
result = MFRC522_PCD_MIFARE_Transceive( (uint8_t *)&data, 4, true); // Adds CRC_A and accept timeout as success.
if (result != MFRC522_STATUS_OK) {
return result;
}
return MFRC522_STATUS_OK;
} // End MFRC522_MIFARE_TwoStepHelper()
/**
* MIFARE Transfer writes the value stored in the volatile memory into one MIFARE Classic block.
* For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
* Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_MIFARE_Transfer( uint8_t blockAddr ///< The block (0-0xff) number.
) {
MFRC522_StatusCode result;
uint8_t cmdBuffer[2]; // We only need room for 2 uint8_ts.
// Tell the PICC we want to transfer the result into block blockAddr.
cmdBuffer[0] = PICC_CMD_MF_TRANSFER;
cmdBuffer[1] = blockAddr;
result = MFRC522_PCD_MIFARE_Transceive( cmdBuffer, 2, false); // Adds CRC_A and checks that the response is MF_ACK.
if (result != MFRC522_STATUS_OK) {
return result;
}
return MFRC522_STATUS_OK;
} // End MIFARE_Transfer()
/**
* Helper routine to read the current value from a Value Block.
*
* Only for MIFARE Classic and only for blocks in "value block" mode, that
* is: with access bits [C1 C2 C3] = [110] or [001]. The sector containing
* the block must be authenticated before calling this function.
*
* @param[in] blockAddr The block (0x00-0xff) number.
* @param[out] value Current value of the Value Block.
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_MIFARE_GetValue(uint8_t blockAddr, int32_t *value) {
MFRC522_StatusCode status;
uint8_t buffer[18];
uint8_t size = sizeof(buffer);
// Read the block
status = MFRC522_MIFARE_Read(blockAddr, buffer, &size);
if (status == MFRC522_STATUS_OK) {
// Extract the value
*value = ((int32_t)(buffer[3])<<24) | ((int32_t)(buffer[2])<<16) | ((int32_t)(buffer[1])<<8) | (int32_t)(buffer[0]);
}
return status;
} // End MIFARE_GetValue()
/**
* Helper routine to write a specific value into a Value Block.
*
* Only for MIFARE Classic and only for blocks in "value block" mode, that
* is: with access bits [C1 C2 C3] = [110] or [001]. The sector containing
* the block must be authenticated before calling this function.
*
* @param[in] blockAddr The block (0x00-0xff) number.
* @param[in] value New value of the Value Block.
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_MIFARE_SetValue(uint8_t blockAddr, int32_t value) {
uint8_t buffer[18];
// Translate the int32_t into 4 uint8_ts; repeated 2x in value block
buffer[0] = buffer[ 8] = (value & 0xFF);
buffer[1] = buffer[ 9] = (value & 0xFF00) >> 8;
buffer[2] = buffer[10] = (value & 0xFF0000) >> 16;
buffer[3] = buffer[11] = (value & 0xFF000000) >> 24;
// Inverse 4 uint8_ts also found in value block
buffer[4] = ~buffer[0];
buffer[5] = ~buffer[1];
buffer[6] = ~buffer[2];
buffer[7] = ~buffer[3];
// Address 2x with inverse address 2x
buffer[12] = buffer[14] = blockAddr;
buffer[13] = buffer[15] = ~blockAddr;
// Write the whole data block
return MFRC522_MIFARE_Write(blockAddr, buffer, 16);
} // End MIFARE_SetValue()
/**
* Authenticate with a NTAG216.
*
* Only for NTAG216. First implemented by Gargantuanman.
*
* @param[in] passWord password.
* @param[in] pACK result success???.
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_PCD_NTAG216_AUTH(uint8_t* passWord, uint8_t pACK[]) //Authenticate with 32bit password
{
MFRC522_StatusCode result;
uint8_t cmdBuffer[18]; // We need room for 16 uint8_ts data and 2 uint8_ts CRC_A.
cmdBuffer[0] = 0x1B; //Comando de autentificacion
uint8_t i;
for (i = 0; i<4; i++)
cmdBuffer[i+1] = passWord[i];
result = MFRC522_PCD_CalculateCRC(cmdBuffer, 5, &cmdBuffer[5]);
if (result!=MFRC522_STATUS_OK) {
return result;
}
// Transceive the data, store the reply in cmdBuffer[]
uint8_t waitIRq = 0x30; // RxIRq and IdleIRq
uint8_t validBits = 0;
uint8_t rxlength = 5;
result = MFRC522_PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, cmdBuffer, 7, cmdBuffer, &rxlength, &validBits, 0, false);
pACK[0] = cmdBuffer[0];
pACK[1] = cmdBuffer[1];
if (result!=MFRC522_STATUS_OK) {
return result;
}
return MFRC522_STATUS_OK;
} // End PCD_NTAG216_AUTH()
/////////////////////////////////////////////////////////////////////////////////////
// Support functions
/////////////////////////////////////////////////////////////////////////////////////
/**
* Wrapper for MIFARE protocol communication.
* Adds CRC_A, executes the Transceive command and checks that the response is MF_ACK or a timeout.
*
* @return STATUS_OK on success, STATUS_??? otherwise.
*/
MFRC522_StatusCode ICACHE_FLASH_ATTR MFRC522_PCD_MIFARE_Transceive( uint8_t *sendData, ///< Pointer to the data to transfer to the FIFO. Do NOT include the CRC_A.
uint8_t sendLen, ///< Number of uint8_ts in sendData.
bool acceptTimeout ///< True => A timeout is also success
) {
MFRC522_StatusCode result;
uint8_t cmdBuffer[18]; // We need room for 16 uint8_ts data and 2 uint8_ts CRC_A.
// Sanity check
if (sendData == NULL || sendLen > 16) {
return MFRC522_STATUS_INVALID;
}
// Copy sendData[] to cmdBuffer[] and add CRC_A
os_memcpy(cmdBuffer, sendData, sendLen);
result = MFRC522_PCD_CalculateCRC(cmdBuffer, sendLen, &cmdBuffer[sendLen]);
if (result != MFRC522_STATUS_OK) {
return result;
}
sendLen += 2;
// Transceive the data, store the reply in cmdBuffer[]
uint8_t waitIRq = 0x30; // RxIRq and IdleIRq
uint8_t cmdBufferSize = sizeof(cmdBuffer);
uint8_t validBits = 0;
result = MFRC522_PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, cmdBuffer, sendLen, cmdBuffer, &cmdBufferSize, &validBits, 0, false);
if (acceptTimeout && result == MFRC522_STATUS_TIMEOUT) {
return MFRC522_STATUS_OK;
}
if (result != MFRC522_STATUS_OK) {
return result;
}
// The PICC must reply with a 4 bit ACK
if (cmdBufferSize != 1 || validBits != 4) {
return MFRC522_STATUS_ERROR;
}
if (cmdBuffer[0] != MF_ACK) {
return MFRC522_STATUS_MIFARE_NACK;
}
return MFRC522_STATUS_OK;
} // End MFRC522_PCD_MIFARE_Transceive()
/**
* Returns a __FlashStringHelper pointer to a status code name.
*
* @return const __FlashStringHelper *
*/
const char * ICACHE_FLASH_ATTR MFRC522_GetStatusCodeName(MFRC522_StatusCode code ///< One of the StatusCode enums.
) {
switch (code) {
case MFRC522_STATUS_OK: return "Success.";
case MFRC522_STATUS_ERROR: return "Error in communication.";
case MFRC522_STATUS_COLLISION: return "Collission detected.";
case MFRC522_STATUS_TIMEOUT: return "Timeout in communication.";
case MFRC522_STATUS_NO_ROOM: return "A buffer is not big enough.";
case MFRC522_STATUS_INTERNAL_ERROR: return "Internal error in the code. Should not happen.";
case MFRC522_STATUS_INVALID: return "Invalid argument.";
case MFRC522_STATUS_CRC_WRONG: return "The CRC_A does not match.";
case MFRC522_STATUS_MIFARE_NACK: return "A MIFARE PICC responded with NAK.";
default: return "Unknown error";
}
} // End MFRC522_GetStatusCodeName()
/**
* Translates the SAK (Select Acknowledge) to a PICC type.
*
* @return PICC_Type
*/
MFRC522_PICC_Type ICACHE_FLASH_ATTR MFRC522_PICC_GetType(uint8_t sak ///< The SAK uint8_t returned from MFRC522_PICC_Select().
) {
// http://www.nxp.com/documents/application_note/AN10833.pdf
// 3.2 Coding of Select Acknowledge (SAK)
// ignore 8-bit (iso14443 starts with LSBit = bit 1)
// fixes wrong type for manufacturer Infineon (http://nfc-tools.org/index.php?title=ISO14443A)
sak &= 0x7F;
switch (sak) {
case 0x04: return PICC_TYPE_NOT_COMPLETE; // UID not complete
case 0x09: return PICC_TYPE_MIFARE_MINI;
case 0x08: return PICC_TYPE_MIFARE_1K;
case 0x18: return PICC_TYPE_MIFARE_4K;
case 0x00: return PICC_TYPE_MIFARE_UL;
case 0x10:
case 0x11: return PICC_TYPE_MIFARE_PLUS;
case 0x01: return PICC_TYPE_TNP3XXX;
case 0x20: return PICC_TYPE_ISO_14443_4;
case 0x40: return PICC_TYPE_ISO_18092;
default: return PICC_TYPE_UNKNOWN;
}
} // End MFRC522_PICC_GetType()
/**
* Returns a __FlashStringHelper pointer to the PICC type name.
*
* @return const __FlashStringHelper *
*/
const char * ICACHE_FLASH_ATTR MFRC522_PICC_GetTypeName(MFRC522_PICC_Type piccType ///< One of the PICC_Type enums.
) {
switch (piccType) {
case PICC_TYPE_ISO_14443_4: return "PICC compliant with ISO/IEC 14443-4";
case PICC_TYPE_ISO_18092: return "PICC compliant with ISO/IEC 18092 (NFC)";
case PICC_TYPE_MIFARE_MINI: return "MIFARE Mini, 320 uint8_ts";
case PICC_TYPE_MIFARE_1K: return "MIFARE 1KB";
case PICC_TYPE_MIFARE_4K: return "MIFARE 4KB";
case PICC_TYPE_MIFARE_UL: return "MIFARE Ultralight or Ultralight C";
case PICC_TYPE_MIFARE_PLUS: return "MIFARE Plus";
case PICC_TYPE_TNP3XXX: return "MIFARE TNP3XXX";
case PICC_TYPE_NOT_COMPLETE: return "SAK indicates UID is not complete.";
case PICC_TYPE_UNKNOWN:
default: return "Unknown type";
}
} // End MFRC522_PICC_GetTypeName()
/**
* Dumps debug info about the connected PCD to Serial.
* Shows all known firmware versions
*/
void ICACHE_FLASH_ATTR MFRC522_PCD_DumpVersionToSerial() {
// Get the MFRC522 firmware version
uint8_t v = MFRC522_PCD_ReadRegister(VersionReg);
dhdebug("Firmware Version: 0x%X", v);
// Lookup which version
switch(v) {
case 0x88: dhdebug(" = (clone)"); break;
case 0x90: dhdebug(" = v0.0"); break;
case 0x91: dhdebug(" = v1.0"); break;
case 0x92: dhdebug(" = v2.0"); break;
default: dhdebug(" = (unknown)");
}
// When 0x00 or 0xFF is returned, communication probably failed
if ((v == 0x00) || (v == 0xFF))
dhdebug("WARNING: Communication failure, is the MFRC522 properly connected?");
} // End MFRC522_PCD_DumpVersionToSerial()
/**
* Dumps debug info about the selected PICC to Serial.
* On success the PICC is halted after dumping the data.
* For MIFARE Classic the factory default key of 0xFFFFFFFFFFFF is tried.
*/
void ICACHE_FLASH_ATTR MFRC522_PICC_DumpToSerial(MFRC522_Uid *uid ///< Pointer to Uid struct returned from a successful MFRC522_PICC_Select().
) {
MIFARE_Key key;
uint8_t i;
// Dump UID, SAK and Type
MFRC522_PICC_DumpDetailsToSerial(uid);
// Dump contents
MFRC522_PICC_Type piccType = MFRC522_PICC_GetType(uid->sak);
switch (piccType) {
case PICC_TYPE_MIFARE_MINI:
case PICC_TYPE_MIFARE_1K:
case PICC_TYPE_MIFARE_4K:
// All keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
for (i = 0; i < 6; i++) {
key.keyByte[i] = 0xFF;
}
MFRC522_PICC_DumpMifareClassicToSerial(uid, piccType, &key);
break;
case PICC_TYPE_MIFARE_UL:
MFRC522_PICC_DumpMifareUltralightToSerial();
break;
case PICC_TYPE_ISO_14443_4:
case PICC_TYPE_ISO_18092:
case PICC_TYPE_MIFARE_PLUS:
case PICC_TYPE_TNP3XXX:
dhdebug("Dumping memory contents not implemented for that PICC type.");
break;
case PICC_TYPE_UNKNOWN:
case PICC_TYPE_NOT_COMPLETE:
default:
break; // No memory dump here
}
MFRC522_PICC_HaltA(); // Already done if it was a MIFARE Classic PICC.
} // End PICC_DumpToSerial()
/**
* Dumps card info (UID,SAK,Type) about the selected PICC to Serial.
*/
void ICACHE_FLASH_ATTR MFRC522_PICC_DumpDetailsToSerial(MFRC522_Uid *uid ///< Pointer to Uid struct returned from a successful MFRC522_PICC_Select().
) {
// UID
dhdebug("Card UID:");
uint8_t i;
for (i = 0; i < uid->size; i++) {
if(uid->uidByte[i] < 0x10)
dhdebug("Card UID: 0%X", uid->uidByte[i]);
else
dhdebug("Card UID: %X", uid->uidByte[i]);
}
// SAK
dhdebug("Card SAK: %X", uid->sak);
// (suggested) PICC type
MFRC522_PICC_Type piccType = MFRC522_PICC_GetType(uid->sak);
dhdebug("PICC type: %s", MFRC522_PICC_GetTypeName(piccType));
} // End MFRC522_PICC_DumpDetailsToSerial()
/**
* Dumps memory contents of a MIFARE Classic PICC.
* On success the PICC is halted after dumping the data.
*/
void ICACHE_FLASH_ATTR MFRC522_PICC_DumpMifareClassicToSerial( MFRC522_Uid *uid, ///< Pointer to Uid struct returned from a successful MFRC522_PICC_Select().
MFRC522_PICC_Type piccType, ///< One of the PICC_Type enums.
MIFARE_Key *key ///< Key A used for all sectors.
) {
uint8_t no_of_sectors = 0;
switch (piccType) {
case PICC_TYPE_MIFARE_MINI:
// Has 5 sectors * 4 blocks/sector * 16 uint8_ts/block = 320 uint8_ts.
no_of_sectors = 5;
break;
case PICC_TYPE_MIFARE_1K:
// Has 16 sectors * 4 blocks/sector * 16 uint8_ts/block = 1024 uint8_ts.
no_of_sectors = 16;
break;
case PICC_TYPE_MIFARE_4K:
// Has (32 sectors * 4 blocks/sector + 8 sectors * 16 blocks/sector) * 16 uint8_ts/block = 4096 uint8_ts.
no_of_sectors = 40;
break;
default: // Should not happen. Ignore.
break;
}
// Dump sectors, highest address first.
if (no_of_sectors) {
dhdebug("Sector Block 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 AccessBits");
uint8_t i;
for (i = no_of_sectors - 1; i >= 0; i--) {
MFRC522_PICC_DumpMifareClassicSectorToSerial(uid, key, i);
}
}
MFRC522_PICC_HaltA(); // Halt the PICC before stopping the encrypted session.
MFRC522_PCD_StopCrypto1();
} // End MFRC522_PICC_DumpMifareClassicToSerial()
/**
* Dumps memory contents of a sector of a MIFARE Classic PICC.
* Uses MFRC522_PCD_Authenticate(), MFRC522_MIFARE_Read() and MFRC522_PCD_StopCrypto1.
* Always uses PICC_CMD_MF_AUTH_KEY_A because only Key A can always read the sector trailer access bits.
*/
void ICACHE_FLASH_ATTR MFRC522_PICC_DumpMifareClassicSectorToSerial(MFRC522_Uid *uid, ///< Pointer to Uid struct returned from a successful MFRC522_PICC_Select().
MIFARE_Key *key, ///< Key A for the sector.
uint8_t sector ///< The sector to dump, 0..39.
) {
MFRC522_StatusCode status;
uint8_t firstBlock; // Address of lowest address to dump actually last block dumped)
uint8_t no_of_blocks; // Number of blocks in sector
bool isSectorTrailer; // Set to true while handling the "last" (ie highest address) in the sector.
// The access bits are stored in a peculiar fashion.
// There are four groups:
// g[3] Access bits for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39)
// g[2] Access bits for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39)
// g[1] Access bits for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39)
// g[0] Access bits for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39)
// Each group has access bits [C1 C2 C3]. In this code C1 is MSB and C3 is LSB.
// The four CX bits are stored together in a nible cx and an inverted nible cx_.
uint8_t c1, c2, c3; // Nibbles
uint8_t c1_, c2_, c3_; // Inverted nibbles
bool invertedError = false; // True if one of the inverted nibbles did not match
uint8_t g[4]; // Access bits for each of the four groups.
uint8_t group; // 0-3 - active group for access bits
bool firstInGroup; // True for the first block dumped in the group
char buf[255];
char *bufptr = buf;
// Determine position and size of sector.
if (sector < 32) { // Sectors 0..31 has 4 blocks each
no_of_blocks = 4;
firstBlock = sector * no_of_blocks;
}
else if (sector < 40) { // Sectors 32-39 has 16 blocks each
no_of_blocks = 16;
firstBlock = 128 + (sector - 32) * no_of_blocks;
}
else { // Illegal input, no MIFARE Classic PICC has more than 40 sectors.
return;
}
// Dump blocks, highest address first.
uint8_t uint8_tCount;
uint8_t buffer[18];
uint8_t blockAddr;
isSectorTrailer = true;
uint8_t blockOffset;
for (blockOffset = no_of_blocks - 1; blockOffset >= 0; blockOffset--) {
blockAddr = firstBlock + blockOffset;
// Sector number - only on first line
if (isSectorTrailer) {
if(sector < 10)
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " "); // Pad with spaces
else
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " "); // Pad with spaces
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, "%d ", sector);
}
else {
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " ");
}
// Block number
if(blockAddr < 10)
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " "); // Pad with spaces
else {
if(blockAddr < 100)
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " "); // Pad with spaces
else
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " "); // Pad with spaces
}
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, "%d ", blockAddr);
// Establish encrypted communications before reading the first block
if (isSectorTrailer) {
status = MFRC522_PCD_Authenticate(PICC_CMD_MF_AUTH_KEY_A, firstBlock, key, uid);
if (status != MFRC522_STATUS_OK) {
dhdebug("MFRC522_PCD_Authenticate() failed: %s", MFRC522_GetStatusCodeName(status));
return;
}
}
// Read block
uint8_tCount = sizeof(buffer);
status = MFRC522_MIFARE_Read(blockAddr, buffer, &uint8_tCount);
if (status != MFRC522_STATUS_OK) {
dhdebug("MFRC522_MIFARE_Read() failed: %s", MFRC522_GetStatusCodeName(status));
continue;
}
// Dump data
uint8_t index;
for (index = 0; index < 16; index++) {
if(buffer[index] < 0x10)
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " 0");
else
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " ");
bufptr += snprintf(buf, sizeof(buf) + buf - bufptr, "%X", buffer[index]);
if ((index % 4) == 3) {
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " ");
}
}
// Parse sector trailer data
if (isSectorTrailer) {
c1 = buffer[7] >> 4;
c2 = buffer[8] & 0xF;
c3 = buffer[8] >> 4;
c1_ = buffer[6] & 0xF;
c2_ = buffer[6] >> 4;
c3_ = buffer[7] & 0xF;
invertedError = (c1 != (~c1_ & 0xF)) || (c2 != (~c2_ & 0xF)) || (c3 != (~c3_ & 0xF));
g[0] = ((c1 & 1) << 2) | ((c2 & 1) << 1) | ((c3 & 1) << 0);
g[1] = ((c1 & 2) << 1) | ((c2 & 2) << 0) | ((c3 & 2) >> 1);
g[2] = ((c1 & 4) << 0) | ((c2 & 4) >> 1) | ((c3 & 4) >> 2);
g[3] = ((c1 & 8) >> 1) | ((c2 & 8) >> 2) | ((c3 & 8) >> 3);
isSectorTrailer = false;
}
// Which access group is this block in?
if (no_of_blocks == 4) {
group = blockOffset;
firstInGroup = true;
}
else {
group = blockOffset / 5;
firstInGroup = (group == 3) || (group != (blockOffset + 1) / 5);
}
if (firstInGroup) {
// Print access bits
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " [ %d %d %d ] ", (g[group] >> 2) & 1, (g[group] >> 1) & 1, (g[group] >> 0) & 1);
if (invertedError) {
dhdebug(" Inverted access bits did not match! ");
}
}
if (group != 3 && (g[group] == 1 || g[group] == 6)) { // Not a sector trailer, a value block
int32_t value = ((int32_t)(buffer[3])<<24) | ((int32_t)(buffer[2])<<16) | ((int32_t)(buffer[1])<<8) | (int32_t)(buffer[0]);
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " Value=0x%X", value);
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " Adr=0x%X", buffer[12]);
}
dhdebug_ram(buf);
bufptr = buf;
}
return;
} // End MFRC522_PICC_DumpMifareClassicSectorToSerial()
/**
* Dumps memory contents of a MIFARE Ultralight PICC.
*/
void ICACHE_FLASH_ATTR MFRC522_PICC_DumpMifareUltralightToSerial() {
MFRC522_StatusCode status;
uint8_t uint8_tCount;
uint8_t buffer[18];
uint8_t i;
uint8_t page;
uint8_t offset;
uint8_t index;
char buf[255];
char *bufptr = buf;
dhdebug("Page 0 1 2 3");
// Try the mpages of the original Ultralight. Ultralight C has more pages.
for (page = 0; page < 16; page +=4) { // Read returns data for 4 pages at a time.
// Read pages
uint8_tCount = sizeof(buffer);
status = MFRC522_MIFARE_Read(page, buffer, &uint8_tCount);
if (status != MFRC522_STATUS_OK) {
dhdebug("MFRC522_MIFARE_Read() failed: %s", MFRC522_GetStatusCodeName(status));
break;
}
// Dump data
for (offset = 0; offset < 4; offset++) {
i = page + offset;
if(i < 10)
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " "); // Pad with spaces
else
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " "); // Pad with spaces
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, "%d ", i);
for (index = 0; index < 4; index++) {
i = 4 * offset + index;
if(buffer[i] < 0x10)
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " 0");
else
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, " ");
bufptr += snprintf(bufptr, sizeof(buf) + buf - bufptr, "%X", buffer[i]);
}
dhdebug_ram(buf);
bufptr = buf;
}
}
} // End MFRC522_PICC_DumpMifareUltralightToSerial()
/**
* Calculates the bit pattern needed for the specified access bits. In the [C1 C2 C3] tuples C1 is MSB (=4) and C3 is LSB (=1).
*/
void ICACHE_FLASH_ATTR MFRC522_MIFARE_SetAccessBits( uint8_t *accessBitBuffer, ///< Pointer to uint8_t 6, 7 and 8 in the sector trailer. Bytes [0..2] will be set.
uint8_t g0, ///< Access bits [C1 C2 C3] for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39)
uint8_t g1, ///< Access bits C1 C2 C3] for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39)
uint8_t g2, ///< Access bits C1 C2 C3] for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39)
uint8_t g3 ///< Access bits C1 C2 C3] for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39)
) {
uint8_t c1 = ((g3 & 4) << 1) | ((g2 & 4) << 0) | ((g1 & 4) >> 1) | ((g0 & 4) >> 2);
uint8_t c2 = ((g3 & 2) << 2) | ((g2 & 2) << 1) | ((g1 & 2) << 0) | ((g0 & 2) >> 1);
uint8_t c3 = ((g3 & 1) << 3) | ((g2 & 1) << 2) | ((g1 & 1) << 1) | ((g0 & 1) << 0);
accessBitBuffer[0] = (~c2 & 0xF) << 4 | (~c1 & 0xF);
accessBitBuffer[1] = c1 << 4 | (~c3 & 0xF);
accessBitBuffer[2] = c3 << 4 | c2;
} // End MIFARE_SetAccessBits()
/**
* Performs the "magic sequence" needed to get Chinese UID changeable
* Mifare cards to allow writing to sector 0, where the card UID is stored.
*
* Note that you do not need to have selected the card through REQA or WUPA,
* this sequence works immediately when the card is in the reader vicinity.
* This means you can use this method even on "bricked" cards that your reader does
* not recognise anymore (see MFRC522_MIFARE_UnbrickUidSector).
*
* Of course with non-bricked devices, you're free to select them before calling this function.
*/
bool ICACHE_FLASH_ATTR MFRC522_MIFARE_OpenUidBackdoor(bool logErrors) {
// Magic sequence:
// > 50 00 57 CD (HALT + CRC)
// > 40 (7 bits only)
// < A (4 bits only)
// > 43
// < A (4 bits only)
// Then you can write to sector 0 without authenticating
MFRC522_PICC_HaltA(); // 50 00 57 CD
uint8_t cmd = 0x40;
uint8_t validBits = 7; /* Our command is only 7 bits. After receiving card response,
this will contain amount of valid response bits. */
uint8_t response[32]; // Card's response is written here
uint8_t received;
MFRC522_StatusCode status = MFRC522_PCD_TransceiveData(&cmd, (uint8_t)1, response, &received, &validBits, (uint8_t)0, false); // 40
if(status != MFRC522_STATUS_OK) {
if(logErrors) {
dhdebug("Card did not respond to 0x40 after HALT command. Are you sure it is a UID changeable one?");
dhdebug("Error name: ", MFRC522_GetStatusCodeName(status));
}
return false;
}
if (received != 1 || response[0] != 0x0A) {
if (logErrors) {
dhdebug("Got bad response on backdoor 0x40 command: %X (%d valid bits)", response[0], validBits);
}
return false;
}
cmd = 0x43;
validBits = 8;
status = MFRC522_PCD_TransceiveData(&cmd, (uint8_t)1, response, &received, &validBits, (uint8_t)0, false); // 43
if(status != MFRC522_STATUS_OK) {
if(logErrors) {
dhdebug("Error in communication at command 0x43, after successfully executing 0x40");
dhdebug("Error name: %s", MFRC522_GetStatusCodeName(status));
}
return false;
}
if (received != 1 || response[0] != 0x0A) {
if (logErrors) {
dhdebug("Got bad response on backdoor 0x43 command: %X (%d valid bits)", response[0], validBits);
}
return false;
}
// You can now write to sector 0 without authenticating!
return true;
} // End MFRC522_MIFARE_OpenUidBackdoor()
/**
* Reads entire block 0, including all manufacturer data, and overwrites
* that block with the new UID, a freshly calculated BCC, and the original
* manufacturer data.
*
* It assumes a default KEY A of 0xFFFFFFFFFFFF.
* Make sure to have selected the card before this function is called.
*/
bool ICACHE_FLASH_ATTR MFRC522_MIFARE_SetUid(uint8_t *newUid, uint8_t uidSize, bool logErrors) {
// UID + BCC uint8_t can not be larger than 16 together
if (!newUid || !uidSize || uidSize > 15) {
if (logErrors) {
dhdebug("New UID buffer empty, size 0, or size > 15 given");
}
return false;
}
// Authenticate for reading
MIFARE_Key key = {.keyByte = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}};
MFRC522_StatusCode status = MFRC522_PCD_Authenticate(PICC_CMD_MF_AUTH_KEY_A, (uint8_t)1, &key, &uid);
if (status != MFRC522_STATUS_OK) {
if (status == MFRC522_STATUS_TIMEOUT) {
// We get a read timeout if no card is selected yet, so let's select one
// Wake the card up again if sleeping
// uint8_t atqa_answer[2];
// uint8_t atqa_size = 2;
// MFRC522_PICC_WakeupA(atqa_answer, &atqa_size);
if (!MFRC522_PICC_IsNewCardPresent() || !MFRC522_PICC_ReadCardSerial()) {
dhdebug("No card was previously selected, and none are available. Failed to set UID.");
return false;
}
status = MFRC522_PCD_Authenticate(PICC_CMD_MF_AUTH_KEY_A, (uint8_t)1, &key, &uid);
if (status != MFRC522_STATUS_OK) {
// We tried, time to give up
if (logErrors) {
dhdebug("Failed to authenticate to card for reading, could not set UID: %s", MFRC522_GetStatusCodeName(status));
}
return false;
}
}
else {
if (logErrors) {
dhdebug("MFRC522_PCD_Authenticate() failed: %s", MFRC522_GetStatusCodeName(status));
}
return false;
}
}
// Read block 0
uint8_t block0_buffer[18];
uint8_t uint8_tCount = sizeof(block0_buffer);
status = MFRC522_MIFARE_Read((uint8_t)0, block0_buffer, &uint8_tCount);
if (status != MFRC522_STATUS_OK) {
if (logErrors) {
dhdebug("MFRC522_MIFARE_Read() failed: ", MFRC522_GetStatusCodeName(status));
dhdebug("Are you sure your KEY A for sector 0 is 0xFFFFFFFFFFFF?");
}
return false;
}
// Write new UID to the data we just read, and calculate BCC uint8_t
uint8_t bcc = 0;
uint8_t i;
for (i = 0; i < uidSize; i++) {
block0_buffer[i] = newUid[i];
bcc ^= newUid[i];
}
// Write BCC uint8_t to buffer
block0_buffer[uidSize] = bcc;
// Stop encrypted traffic so we can send raw uint8_ts
MFRC522_PCD_StopCrypto1();
// Activate UID backdoor
if (!MFRC522_MIFARE_OpenUidBackdoor(logErrors)) {
if (logErrors) {
dhdebug("Activating the UID backdoor failed.");
}
return false;
}
// Write modified block 0 back to card
status = MFRC522_MIFARE_Write((uint8_t)0, block0_buffer, (uint8_t)16);
if (status != MFRC522_STATUS_OK) {
if (logErrors) {
dhdebug("MFRC522_MIFARE_Write() failed: %s", MFRC522_GetStatusCodeName(status));
}
return false;
}
// Wake the card up again
uint8_t atqa_answer[2];
uint8_t atqa_size = 2;
MFRC522_PICC_WakeupA(atqa_answer, &atqa_size);
return true;
}
/**
* Resets entire sector 0 to zeroes, so the card can be read again by readers.
*/
bool ICACHE_FLASH_ATTR MFRC522_MIFARE_UnbrickUidSector(bool logErrors) {
MFRC522_MIFARE_OpenUidBackdoor(logErrors);
uint8_t block0_buffer[] = {0x01, 0x02, 0x03, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
// Write modified block 0 back to card
MFRC522_StatusCode status = MFRC522_MIFARE_Write((uint8_t)0, block0_buffer, (uint8_t)16);
if (status != MFRC522_STATUS_OK) {
if (logErrors) {
dhdebug("MFRC522_MIFARE_Write() failed: %s", MFRC522_GetStatusCodeName(status));
}
return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////////////////////
// Convenience functions - does not add extra functionality
/////////////////////////////////////////////////////////////////////////////////////
/**
* Returns true if a PICC responds to PICC_CMD_REQA.
* Only "new" cards in state IDLE are invited. Sleeping cards in state HALT are ignored.
*
* @return bool
*/
bool ICACHE_FLASH_ATTR MFRC522_PICC_IsNewCardPresent() {
uint8_t bufferATQA[2];
uint8_t bufferSize = sizeof(bufferATQA);
MFRC522_StatusCode result = MFRC522_PICC_RequestA(bufferATQA, &bufferSize);
return (result == MFRC522_STATUS_OK || result == MFRC522_STATUS_COLLISION);
} // End MFRC522_PICC_IsNewCardPresent()
/**
* Simple wrapper around MFRC522_PICC_Select.
* Returns true if a UID could be read.
* Remember to call MFRC522_PICC_IsNewCardPresent(), MFRC522_PICC_RequestA() or MFRC522_PICC_WakeupA() first.
* The read UID is available in the class variable uid.
*
* @return bool
*/
bool ICACHE_FLASH_ATTR MFRC522_PICC_ReadCardSerial() {
MFRC522_StatusCode result = MFRC522_PICC_Select(&uid, 0);
return (result == MFRC522_STATUS_OK);
} // End
#endif /* DH_DEVICE_MFRC522 */
|
c2b0ea51208d10b184abf58a18594db034f16671
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/arch/arm/src/xmc4/hardware/xmc4_pinmux.h
|
5ccc6dd5e543226d6f71769311d7e2a023491e5b
|
[
"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
| 59,253
|
h
|
xmc4_pinmux.h
|
/****************************************************************************
* arch/arm/src/xmc4/hardware/xmc4_pinmux.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/* Reference: XMC4500 Reference Manual V1.5 2014-07 Microcontrollers. */
#ifndef __ARCH_ARM_SRC_XMC4_HARDWARE_XMC4_PINMUX_H
#define __ARCH_ARM_SRC_XMC4_HARDWARE_XMC4_PINMUX_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Alternate Pin Functions. All members of the XMC4xxx family share the same
* pin multiplexing (although they may differ in the pins physically
* available).
*
* Alternative pin selections are provided with a numeric suffix like _1, _2,
* etc. Drivers, however, will use the pin selection without the numeric
* suffix.
* Additional definitions are required in the board.h file. For example, if
* CAN_N2TXD connects vis P1.9 on some board, then the following definition
* should appear in the board.h header file for that board:
*
* #define GPIO_CAN_N2TXD GPIO_CAN_N2TXD_1
*
* The driver will then automatically configure PA11 as the CAN1 RX pin.
*/
/* WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!!
* Additional effort is required to select specific GPIO options such as
* frequency, open-drain/push-pull, and pull-up/down! Just the basics are
* defined for most pins in this file.
*/
#define GPIO_CAN_N0RXDA (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN5)
#define GPIO_CAN_N0RXDB (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN3)
#define GPIO_CAN_N0RXDC (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN12)
#define GPIO_CAN_N0TXD_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT0 | GPIO_PIN0)
#define GPIO_CAN_N0TXD_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN4)
#define GPIO_CAN_N0TXD_3 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN10)
#define GPIO_CAN_N0TXD_4 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN2)
#define GPIO_CAN_N1RXDA (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN6)
#define GPIO_CAN_N1RXDB (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN11)
#define GPIO_CAN_N1RXDC (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN13)
#define GPIO_CAN_N1RXDD (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN4)
#define GPIO_CAN_N1TXD_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT1 | GPIO_PIN5)
#define GPIO_CAN_N1TXD_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN12)
#define GPIO_CAN_N1TXD_3 (GPIO_OUTPUT_ALT2 | GPIO_PORT2 | GPIO_PIN7)
#define GPIO_CAN_N1TXD_4 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN9)
#define GPIO_CAN_N2RXDA (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN8)
#define GPIO_CAN_N2RXDB (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN8)
#define GPIO_CAN_N2RXDC (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN6)
#define GPIO_CAN_N2TXD_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN9)
#define GPIO_CAN_N2TXD_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN7)
#define GPIO_CAN_N2TXD_3 (GPIO_OUTPUT_ALT2 | GPIO_PORT4 | GPIO_PIN7)
#define GPIO_CCU40_IN0A (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN3)
#define GPIO_CCU40_IN0B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN8)
#define GPIO_CCU40_IN0C (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN1)
#define GPIO_CCU40_IN1A (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN2)
#define GPIO_CCU40_IN1B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN8)
#define GPIO_CCU40_IN1C (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN0)
#define GPIO_CCU40_IN2A (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN1)
#define GPIO_CCU40_IN2B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN8)
#define GPIO_CCU40_IN2C (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN7)
#define GPIO_CCU40_IN3A (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN0)
#define GPIO_CCU40_IN3B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN8)
#define GPIO_CCU40_IN3C (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN6)
#define GPIO_CCU40_OUT0_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT0 | GPIO_PIN15)
#define GPIO_CCU40_OUT0_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT1 | GPIO_PIN3)
#define GPIO_CCU40_OUT1_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT0 | GPIO_PIN14)
#define GPIO_CCU40_OUT1_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT1 | GPIO_PIN2)
#define GPIO_CCU40_OUT2_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT0 | GPIO_PIN13)
#define GPIO_CCU40_OUT2_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT1 | GPIO_PIN1)
#define GPIO_CCU40_OUT3_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT0 | GPIO_PIN12)
#define GPIO_CCU40_OUT3_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT1 | GPIO_PIN0)
#define GPIO_CCU41_IN0A (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN5)
#define GPIO_CCU41_IN0B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN9)
#define GPIO_CCU41_IN0C (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN4)
#define GPIO_CCU41_IN1A (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN4)
#define GPIO_CCU41_IN1B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN9)
#define GPIO_CCU41_IN1C (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN5)
#define GPIO_CCU41_IN2A (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN3)
#define GPIO_CCU41_IN2B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN9)
#define GPIO_CCU41_IN2C (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN10)
#define GPIO_CCU41_IN3A (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN2)
#define GPIO_CCU41_IN3B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN9)
#define GPIO_CCU41_IN3C (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN11)
#define GPIO_CCU41_OUT0_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT2 | GPIO_PIN5)
#define GPIO_CCU41_OUT0_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT3 | GPIO_PIN10)
#define GPIO_CCU41_OUT1_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT2 | GPIO_PIN4)
#define GPIO_CCU41_OUT1_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT3 | GPIO_PIN9)
#define GPIO_CCU41_OUT2_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT2 | GPIO_PIN3)
#define GPIO_CCU41_OUT2_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT3 | GPIO_PIN8)
#define GPIO_CCU41_OUT3_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT2 | GPIO_PIN2)
#define GPIO_CCU41_OUT3_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT3 | GPIO_PIN7)
#define GPIO_CCU42_IN0A (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN6)
#define GPIO_CCU42_IN0B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN15)
#define GPIO_CCU42_IN0C (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN15)
#define GPIO_CCU42_IN1A (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN5)
#define GPIO_CCU42_IN1B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN15)
#define GPIO_CCU42_IN1C (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN14)
#define GPIO_CCU42_IN2A (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN4)
#define GPIO_CCU42_IN2B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN15)
#define GPIO_CCU42_IN2C (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN15)
#define GPIO_CCU42_IN3A (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN3)
#define GPIO_CCU42_IN3B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN15)
#define GPIO_CCU42_IN3C (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN14)
#define GPIO_CCU42_OUT0_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT3 | GPIO_PIN0)
#define GPIO_CCU42_OUT0_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT3 | GPIO_PIN6)
#define GPIO_CCU42_OUT1_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT3 | GPIO_PIN13)
#define GPIO_CCU42_OUT1_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT3 | GPIO_PIN5)
#define GPIO_CCU42_OUT2_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT3 | GPIO_PIN12)
#define GPIO_CCU42_OUT2_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT3 | GPIO_PIN4)
#define GPIO_CCU42_OUT3_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT3 | GPIO_PIN11)
#define GPIO_CCU42_OUT3_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT3 | GPIO_PIN3)
#define GPIO_CCU43_IN0A (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN6)
#define GPIO_CCU43_IN0B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN14)
#define GPIO_CCU43_IN0C (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN7)
#define GPIO_CCU43_IN1A (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN5)
#define GPIO_CCU43_IN1B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN14)
#define GPIO_CCU43_IN1C (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN2)
#define GPIO_CCU43_IN2A (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN4)
#define GPIO_CCU43_IN2B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN14)
#define GPIO_CCU43_IN2C (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN13)
#define GPIO_CCU43_IN3A (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN3)
#define GPIO_CCU43_IN3B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN14)
#define GPIO_CCU43_IN3C (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN12)
#define GPIO_CCU43_OUT0_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT4 | GPIO_PIN6)
#define GPIO_CCU43_OUT0_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT6 | GPIO_PIN5)
#define GPIO_CCU43_OUT1_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT4 | GPIO_PIN5)
#define GPIO_CCU43_OUT1_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT6 | GPIO_PIN4)
#define GPIO_CCU43_OUT2_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT4 | GPIO_PIN4)
#define GPIO_CCU43_OUT2_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT6 | GPIO_PIN3)
#define GPIO_CCU43_OUT3_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT4 | GPIO_PIN3)
#define GPIO_CCU43_OUT3_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT6 | GPIO_PIN2)
#define GPIO_CCU80_IN0A (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN7)
#define GPIO_CCU80_IN0B (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN4)
#define GPIO_CCU80_IN0C (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN2)
#define GPIO_CCU80_IN1A (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN7)
#define GPIO_CCU80_IN1B (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN8)
#define GPIO_CCU80_IN1C (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN1)
#define GPIO_CCU80_IN2A (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN7)
#define GPIO_CCU80_IN2B (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN6)
#define GPIO_CCU80_IN2C (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN0)
#define GPIO_CCU80_IN3A (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN7)
#define GPIO_CCU80_IN3B (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN3)
#define GPIO_CCU80_IN3C (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN13)
#define GPIO_CCU80_OUT00_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT0 | GPIO_PIN5)
#define GPIO_CCU80_OUT00_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT5 | GPIO_PIN11)
#define GPIO_CCU80_OUT01_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT0 | GPIO_PIN2)
#define GPIO_CCU80_OUT01_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT5 | GPIO_PIN8)
#define GPIO_CCU80_OUT02 1 (GPIO_OUTPUT_ALT3 | GPIO_PORT0 | GPIO_PIN10)
#define GPIO_CCU80_OUT03 2 (GPIO_OUTPUT_ALT3 | GPIO_PORT2 | GPIO_PIN7)
#define GPIO_CCU80_OUT10_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT0 | GPIO_PIN4)
#define GPIO_CCU80_OUT10_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT5 | GPIO_PIN10)
#define GPIO_CCU80_OUT11_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT0 | GPIO_PIN1)
#define GPIO_CCU80_OUT11_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT2 | GPIO_PIN15)
#define GPIO_CCU80_OUT12 (GPIO_OUTPUT_ALT3 | GPIO_PORT0 | GPIO_PIN9)
#define GPIO_CCU80_OUT13 (GPIO_OUTPUT_ALT3 | GPIO_PORT2 | GPIO_PIN6)
#define GPIO_CCU80_OUT20_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT0 | GPIO_PIN3)
#define GPIO_CCU80_OUT20_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT5 | GPIO_PIN9)
#define GPIO_CCU80_OUT21_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT0 | GPIO_PIN0)
#define GPIO_CCU80_OUT21_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT2 | GPIO_PIN14)
#define GPIO_CCU80_OUT22_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT2 | GPIO_PIN11)
#define GPIO_CCU80_OUT22_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT2 | GPIO_PIN9)
#define GPIO_CCU80_OUT23 (GPIO_OUTPUT_ALT3 | GPIO_PORT1 | GPIO_PIN5)
#define GPIO_CCU80_OUT30 (GPIO_OUTPUT_ALT3 | GPIO_PORT0 | GPIO_PIN6)
#define GPIO_CCU80_OUT31 (GPIO_OUTPUT_ALT3 | GPIO_PORT0 | GPIO_PIN11)
#define GPIO_CCU80_OUT32 (GPIO_OUTPUT_ALT3 | GPIO_PORT2 | GPIO_PIN8)
#define GPIO_CCU80_OUT33 (GPIO_OUTPUT_ALT3 | GPIO_PORT1 | GPIO_PIN4)
#define GPIO_CCU81_IN0A (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN0)
#define GPIO_CCU81_IN0B (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN1)
#define GPIO_CCU81_IN0C (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN0)
#define GPIO_CCU81_IN1A (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN0)
#define GPIO_CCU81_IN1B (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN2)
#define GPIO_CCU81_IN1C (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN13)
#define GPIO_CCU81_IN2A (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN0)
#define GPIO_CCU81_IN2B (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN3)
#define GPIO_CCU81_IN2C (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN12)
#define GPIO_CCU81_IN3A (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN0)
#define GPIO_CCU81_IN3B (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN4)
#define GPIO_CCU81_IN3C (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN11)
#define GPIO_CCU81_OUT00 (GPIO_OUTPUT_ALT3 | GPIO_PORT1 | GPIO_PIN15)
#define GPIO_CCU81_OUT01_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT2 | GPIO_PIN2)
#define GPIO_CCU81_OUT01_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT1 | GPIO_PIN12)
#define GPIO_CCU81_OUT02 (GPIO_OUTPUT_ALT3 | GPIO_PORT5 | GPIO_PIN7)
#define GPIO_CCU81_OUT03 (GPIO_OUTPUT_ALT3 | GPIO_PORT5 | GPIO_PIN6)
#define GPIO_CCU81_OUT10_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT1 | GPIO_PIN14)
#define GPIO_CCU81_OUT10_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT1 | GPIO_PIN5)
#define GPIO_CCU81_OUT11_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT2 | GPIO_PIN1)
#define GPIO_CCU81_OUT11_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT1 | GPIO_PIN11)
#define GPIO_CCU81_OUT12 (GPIO_OUTPUT_ALT3 | GPIO_PORT5 | GPIO_PIN5)
#define GPIO_CCU81_OUT13 (GPIO_OUTPUT_ALT3 | GPIO_PORT5 | GPIO_PIN4)
#define GPIO_CCU81_OUT20_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT1 | GPIO_PIN13)
#define GPIO_CCU81_OUT20_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT1 | GPIO_PIN4)
#define GPIO_CCU81_OUT21_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT2 | GPIO_PIN0)
#define GPIO_CCU81_OUT21_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT1 | GPIO_PIN10)
#define GPIO_CCU81_OUT22 (GPIO_OUTPUT_ALT3 | GPIO_PORT5 | GPIO_PIN3)
#define GPIO_CCU81_OUT23 (GPIO_OUTPUT_ALT3 | GPIO_PORT5 | GPIO_PIN2)
#define GPIO_CCU81_OUT30 (GPIO_OUTPUT_ALT3 | GPIO_PORT6 | GPIO_PIN1)
#define GPIO_CCU81_OUT31 (GPIO_OUTPUT_ALT3 | GPIO_PORT6 | GPIO_PIN0)
#define GPIO_CCU81_OUT32 (GPIO_OUTPUT_ALT3 | GPIO_PORT5 | GPIO_PIN1)
#define GPIO_CCU81_OUT33_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT2 | GPIO_PIN12)
#define GPIO_CCU81_OUT33_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT5 | GPIO_PIN0)
#define GPIO_DAC_OUT0 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT14 | GPIO_PIN8)
#define GPIO_DAC_OUT1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT14 | GPIO_PIN9)
#define GPIO_DAC_TRIGGER4 (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN9)
#define GPIO_DAC_TRIGGER5 (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN8)
#define GPIO_DB_ETMTRACECLK_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN14)
#define GPIO_DB_ETMTRACECLK_2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT6 | GPIO_PIN0)
#define GPIO_DB_ETMTRACEDATA0_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN13)
#define GPIO_DB_ETMTRACEDATA0_2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT6 | GPIO_PIN6)
#define GPIO_DB_ETMTRACEDATA1_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN12)
#define GPIO_DB_ETMTRACEDATA1_2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT6 | GPIO_PIN5)
#define GPIO_DB_ETMTRACEDATA2_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN11)
#define GPIO_DB_ETMTRACEDATA2_2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT6 | GPIO_PIN2)
#define GPIO_DB_ETMTRACEDATA3_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN10)
#define GPIO_DB_ETMTRACEDATA3_2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT6 | GPIO_PIN1)
#define GPIO_DB_TDI (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN7)
#define GPIO_DB_TDO (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN1)
#define GPIO_DB_TRST (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN8)
#define GPIO_DSD_CGPWMN_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT1 | GPIO_PIN0)
#define GPIO_DSD_CGPWMN_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT5 | GPIO_PIN0)
#define GPIO_DSD_CGPWMN_3 (GPIO_OUTPUT_ALT3 | GPIO_PORT2 | GPIO_PIN0)
#define GPIO_DSD_CGPWMP_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT1 | GPIO_PIN1)
#define GPIO_DSD_CGPWMP_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT5 | GPIO_PIN1)
#define GPIO_DSD_CGPWMP_3 (GPIO_OUTPUT_ALT3 | GPIO_PORT2 | GPIO_PIN1)
#define GPIO_DSD_DIN0A (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN8)
#define GPIO_DSD_DIN0B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN7)
#define GPIO_DSD_DIN1A (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN7)
#define GPIO_DSD_DIN1B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN6)
#define GPIO_DSD_DIN2A (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN6)
#define GPIO_DSD_DIN2B (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN5)
#define GPIO_DSD_DIN3A (GPIO_INPUT | GPIO_PORT6 | GPIO_PIN5)
#define GPIO_DSD_DIN3B (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN3)
#define GPIO_DSD_MCLK0 (GPIO_OUTPUT_ALT3 | GPIO_PORT4 | GPIO_PIN1)
#define GPIO_DSD_MCLK0A (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN9)
#define GPIO_DSD_MCLK0B (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN1)
#define GPIO_DSD_MCLK1_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT1 | GPIO_PIN8)
#define GPIO_DSD_MCLK1_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT4 | GPIO_PIN0)
#define GPIO_DSD_MCLK1A (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN8)
#define GPIO_DSD_MCLK1B (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN0)
#define GPIO_DSD_MCLK2_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN15)
#define GPIO_DSD_MCLK2_2 (GPIO_OUTPUT_ALT3 | GPIO_PORT1 | GPIO_PIN7)
#define GPIO_DSD_MCLK2A (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN7)
#define GPIO_DSD_MCLK2B (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN15)
#define GPIO_DSD_MCLK3_1 (GPIO_OUTPUT_ALT3 | GPIO_PORT6 | GPIO_PIN6)
#define GPIO_DSD_MCLK3_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT3 | GPIO_PIN4)
#define GPIO_DSD_MCLK3A (GPIO_INPUT | GPIO_PORT6 | GPIO_PIN6)
#define GPIO_DSD_MCLK3B (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN4)
#define GPIO_EBU_A16 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT6 | GPIO_PIN0)
#define GPIO_EBU_A17 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT6 | GPIO_PIN1)
#define GPIO_EBU_A18 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT6 | GPIO_PIN2)
#define GPIO_EBU_A19 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT6 | GPIO_PIN4)
#define GPIO_EBU_A20 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT5 | GPIO_PIN3)
#define GPIO_EBU_A21 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT5 | GPIO_PIN4)
#define GPIO_EBU_A22 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT5 | GPIO_PIN5)
#define GPIO_EBU_A23 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT5 | GPIO_PIN6)
#define GPIO_EBU_AD0 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN2)
#define GPIO_EBU_AD1 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN3)
#define GPIO_EBU_AD2 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN4)
#define GPIO_EBU_AD3 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN5)
#define GPIO_EBU_AD4 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT3 | GPIO_PIN5)
#define GPIO_EBU_AD5 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT3 | GPIO_PIN6)
#define GPIO_EBU_AD6 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN7)
#define GPIO_EBU_AD7 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN8)
#define GPIO_EBU_AD8 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT4 | GPIO_PIN0)
#define GPIO_EBU_AD9 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT4 | GPIO_PIN1)
#define GPIO_EBU_AD10 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN6)
#define GPIO_EBU_AD11 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN7)
#define GPIO_EBU_AD12 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN8)
#define GPIO_EBU_AD13 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN9)
#define GPIO_EBU_AD14 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN2)
#define GPIO_EBU_AD15 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN3)
#define GPIO_EBU_AD16 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN12)
#define GPIO_EBU_AD17 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN13)
#define GPIO_EBU_AD18 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN14)
#define GPIO_EBU_AD19 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN15)
#define GPIO_EBU_AD20 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN0)
#define GPIO_EBU_AD21 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN1)
#define GPIO_EBU_AD22 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN2)
#define GPIO_EBU_AD23 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN3)
#define GPIO_EBU_AD24 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN4)
#define GPIO_EBU_AD25 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN5)
#define GPIO_EBU_AD26 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN8)
#define GPIO_EBU_AD27 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN9)
#define GPIO_EBU_AD28 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN10)
#define GPIO_EBU_AD29 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN11)
#define GPIO_EBU_AD30 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN12)
#define GPIO_EBU_AD31 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN13)
#define GPIO_EBU_ADV (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN6)
#define GPIO_EBU_BC0 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN14)
#define GPIO_EBU_BC1 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN15)
#define GPIO_EBU_BC2 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT6 | GPIO_PIN5)
#define GPIO_EBU_BC3 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT6 | GPIO_PIN6)
#define GPIO_EBU_BFCLKI (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN6)
#define GPIO_EBU_BFCLKO_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT5 | GPIO_PIN6)
#define GPIO_EBU_BFCLKO_2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT5 | GPIO_PIN9)
#define GPIO_EBU_BREQ (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN11)
#define GPIO_EBU_CAS (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT5 | GPIO_PIN5)
#define GPIO_EBU_CKE (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT5 | GPIO_PIN3)
#define GPIO_EBU_CS0 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT3 | GPIO_PIN2)
#define GPIO_EBU_CS1 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN9)
#define GPIO_EBU_CS2 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT5 | GPIO_PIN8)
#define GPIO_EBU_CS3 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT5 | GPIO_PIN9)
#define GPIO_EBU_D0 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN2)
#define GPIO_EBU_D1 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN3)
#define GPIO_EBU_D2 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN4)
#define GPIO_EBU_D3 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN5)
#define GPIO_EBU_D4 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT3 | GPIO_PIN5)
#define GPIO_EBU_D5 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT3 | GPIO_PIN6)
#define GPIO_EBU_D6 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN7)
#define GPIO_EBU_D7 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN8)
#define GPIO_EBU_D8 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT4 | GPIO_PIN0)
#define GPIO_EBU_D9 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT4 | GPIO_PIN1)
#define GPIO_EBU_D10 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN6)
#define GPIO_EBU_D11 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN7)
#define GPIO_EBU_D12 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN8)
#define GPIO_EBU_D13 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN9)
#define GPIO_EBU_D14 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN2)
#define GPIO_EBU_D15 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN3)
#define GPIO_EBU_D16 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN12)
#define GPIO_EBU_D17 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN13)
#define GPIO_EBU_D18 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN14)
#define GPIO_EBU_D19 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT1 | GPIO_PIN15)
#define GPIO_EBU_D20 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN0)
#define GPIO_EBU_D21 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN1)
#define GPIO_EBU_D22 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN2)
#define GPIO_EBU_D23 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN3)
#define GPIO_EBU_D24 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN4)
#define GPIO_EBU_D25 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN5)
#define GPIO_EBU_D26 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN8)
#define GPIO_EBU_D27 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN9)
#define GPIO_EBU_D28 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN10)
#define GPIO_EBU_D29 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN11)
#define GPIO_EBU_D30 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN12)
#define GPIO_EBU_D31 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT2 | GPIO_PIN13)
#define GPIO_EBU_HLDA_1 (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN12)
#define GPIO_EBU_HLDA_2 (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT0 | GPIO_PIN12)
#define GPIO_EBU_HOLD (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT3 | GPIO_PIN4)
#define GPIO_EBU_RAS (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT5 | GPIO_PIN4)
#define GPIO_EBU_RD (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT3 | GPIO_PIN0)
#define GPIO_EBU_RDWR (GPIO_OUTPUT | GPIO_PINCTRL_HW1 | GPIO_PORT3 | GPIO_PIN1)
#define GPIO_EBU_SDCLKI (GPIO_INPUT | GPIO_PORT6 | GPIO_PIN4)
#define GPIO_EBU_SDCLKO_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT5 | GPIO_PIN8)
#define GPIO_EBU_SDCLKO_2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT6 | GPIO_PIN4)
#define GPIO_EBU_WAIT (GPIO_INPUT | GPIO_PINCTRL_HW1 | GPIO_PORT3 | GPIO_PIN3)
#define GPIO_ERU0_0A0 (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN1)
#define GPIO_ERU0_0A1 (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN2)
#define GPIO_ERU0_0A2 (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN5)
#define GPIO_ERU0_0B0 (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN0)
#define GPIO_ERU0_0B1 (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN1)
#define GPIO_ERU0_0B2 (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN4)
#define GPIO_ERU0_0B3 (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN0)
#define GPIO_ERU0_1A0 (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN10)
#define GPIO_ERU0_1A2 (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN3)
#define GPIO_ERU0_1B0 (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN9)
#define GPIO_ERU0_1B2 (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN2)
#define GPIO_ERU0_1B3 (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN6)
#define GPIO_ERU0_2A0 (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN5)
#define GPIO_ERU0_2A1 (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN8)
#define GPIO_ERU0_2A2 (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN13)
#define GPIO_ERU0_2B0 (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN4)
#define GPIO_ERU0_2B1 (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN7)
#define GPIO_ERU0_2B2 (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN12)
#define GPIO_ERU0_2B3 (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN4)
#define GPIO_ERU0_3A0 (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN1)
#define GPIO_ERU0_3A1 (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN6)
#define GPIO_ERU0_3A2 (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN11)
#define GPIO_ERU0_3B0 (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN0)
#define GPIO_ERU0_3B1 (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN5)
#define GPIO_ERU0_3B2 (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN6)
#define GPIO_ERU0_3B3 (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN2)
#define GPIO_ERU1_0A0 (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN5)
#define GPIO_ERU1_0B0 (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN1)
#define GPIO_ERU1_1A0 (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN15)
#define GPIO_ERU1_1B0 (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN7)
#define GPIO_ERU1_2A0 (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN3)
#define GPIO_ERU1_2B0 (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN2)
#define GPIO_ERU1_3A0 (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN5)
#define GPIO_ERU1_3B0 (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN3)
#define GPIO_ERU1_PDOUT0 (GPIO_OUTPUT_ALT4 | GPIO_PORT1 | GPIO_PIN3)
#define GPIO_ERU1_PDOUT1 (GPIO_OUTPUT_ALT4 | GPIO_PORT1 | GPIO_PIN2)
#define GPIO_ERU1_PDOUT2 (GPIO_OUTPUT_ALT4 | GPIO_PORT1 | GPIO_PIN1)
#define GPIO_ERU1_PDOUT3 (GPIO_OUTPUT_ALT4 | GPIO_PORT1 | GPIO_PIN0)
#define GPIO_ETH0_CLKRMIIA (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN1)
#define GPIO_ETH0_CLKRMIIB (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN0)
#define GPIO_ETH0_CLKRMIIC (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN8)
#define GPIO_ETH0_CLKRMIID (GPIO_INPUT | GPIO_PORT6 | GPIO_PIN5)
#define GPIO_ETH0_CLKRXA (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN1)
#define GPIO_ETH0_CLKRXB (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN0)
#define GPIO_ETH0_CLKRXC (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN8)
#define GPIO_ETH0_CLKRXD (GPIO_INPUT | GPIO_PORT6 | GPIO_PIN5)
#define GPIO_ETH0_CLKTXA (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN10)
#define GPIO_ETH0_CLKTXB (GPIO_INPUT | GPIO_PORT6 | GPIO_PIN6)
#define GPIO_ETH0_COLA (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN15)
#define GPIO_ETH0_COLD (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN5)
#define GPIO_ETH0_CRSA (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN11)
#define GPIO_ETH0_CRSD (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN4)
#define GPIO_ETH0_CRSDVA_1 (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN5)
#define GPIO_ETH0_CRSDVA_2 (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN5)
#define GPIO_ETH0_CRSDVB (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN1)
#define GPIO_ETH0_CRSDVC (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN9)
#define GPIO_ETH0_CRSDVD (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN2)
#define GPIO_ETH0_MDC_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT0 | GPIO_PIN10)
#define GPIO_ETH0_MDC_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT1 | GPIO_PIN10)
#define GPIO_ETH0_MDC_3 (GPIO_OUTPUT_ALT1 | GPIO_PORT2 | GPIO_PIN7)
#define GPIO_ETH0_MDIA (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN9)
#define GPIO_ETH0_MDIB (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN0)
#define GPIO_ETH0_MDIC (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN11)
#define GPIO_ETH0_MDO_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN9)
#define GPIO_ETH0_MDO_2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN11)
#define GPIO_ETH0_MDO_3 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN0)
#define GPIO_ETH0_RXD0A (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN2)
#define GPIO_ETH0_RXD0B (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN2)
#define GPIO_ETH0_RXD0C (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN8)
#define GPIO_ETH0_RXD0D (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN0)
#define GPIO_ETH0_RXD1A (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN3)
#define GPIO_ETH0_RXD1B (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN3)
#define GPIO_ETH0_RXD1C (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN9)
#define GPIO_ETH0_RXD1D (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN1)
#define GPIO_ETH0_RXD2A (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN8)
#define GPIO_ETH0_RXD2B (GPIO_INPUT | GPIO_PORT6 | GPIO_PIN4)
#define GPIO_ETH0_RXD3A (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN9)
#define GPIO_ETH0_RXD3B (GPIO_INPUT | GPIO_PORT6 | GPIO_PIN3)
#define GPIO_ETH0_RXDVB (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN1)
#define GPIO_ETH0_RXDVC (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN9)
#define GPIO_ETH0_RXDVD (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN2)
#define GPIO_ETH0_RXERA (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN4)
#define GPIO_ETH0_RXERB (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN11)
#define GPIO_ETH0_RXERD (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN3)
#define GPIO_ETH0_TXD0_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT0 | GPIO_PIN5)
#define GPIO_ETH0_TXD0_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT1 | GPIO_PIN13)
#define GPIO_ETH0_TXD0_3 (GPIO_OUTPUT_ALT1 | GPIO_PORT2 | GPIO_PIN8)
#define GPIO_ETH0_TXD0_4 (GPIO_OUTPUT_ALT4 | GPIO_PORT2 | GPIO_PIN12)
#define GPIO_ETH0_TXD1_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT0 | GPIO_PIN6)
#define GPIO_ETH0_TXD1_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT1 | GPIO_PIN14)
#define GPIO_ETH0_TXD1_3 (GPIO_OUTPUT_ALT1 | GPIO_PORT2 | GPIO_PIN9)
#define GPIO_ETH0_TXD1_4 (GPIO_OUTPUT_ALT4 | GPIO_PORT2 | GPIO_PIN13)
#define GPIO_ETH0_TXD2_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT2 | GPIO_PIN12)
#define GPIO_ETH0_TXD2_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT6 | GPIO_PIN0)
#define GPIO_ETH0_TXD3_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT2 | GPIO_PIN13)
#define GPIO_ETH0_TXD3_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT6 | GPIO_PIN1)
#define GPIO_ETH0_TXEN_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT0 | GPIO_PIN4)
#define GPIO_ETH0_TXEN_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT1 | GPIO_PIN12)
#define GPIO_ETH0_TXEN_3 (GPIO_OUTPUT_ALT1 | GPIO_PORT2 | GPIO_PIN5)
#define GPIO_ETH0_TXEN_4 (GPIO_OUTPUT_ALT4 | GPIO_PORT5 | GPIO_PIN9)
#define GPIO_ETH0_TXER_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT2 | GPIO_PIN11)
#define GPIO_ETH0_TXER_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT6 | GPIO_PIN2)
#define GPIO_G0ORC6 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN6)
#define GPIO_G0ORC7 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN7)
#define GPIO_G1ORC6 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN14)
#define GPIO_G1ORC7 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN15)
#define GPIO_LEDTS0_COL0_1 (GPIO_OUTPUT_ALT4 | GPIO_PORT0 | GPIO_PIN9)
#define GPIO_LEDTS0_COL0_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT2 | GPIO_PIN1)
#define GPIO_LEDTS0_COL1_1 (GPIO_OUTPUT_ALT4 | GPIO_PORT0 | GPIO_PIN10)
#define GPIO_LEDTS0_COL1_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT2 | GPIO_PIN0)
#define GPIO_LEDTS0_COL2_1 (GPIO_OUTPUT_ALT4 | GPIO_PORT0 | GPIO_PIN0)
#define GPIO_LEDTS0_COL2_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT2 | GPIO_PIN7)
#define GPIO_LEDTS0_COL3_1 (GPIO_OUTPUT_ALT4 | GPIO_PORT0 | GPIO_PIN1)
#define GPIO_LEDTS0_COL3_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT2 | GPIO_PIN6)
#define GPIO_LEDTS0_COLA_1 (GPIO_OUTPUT_ALT4 | GPIO_PORT3 | GPIO_PIN2)
#define GPIO_LEDTS0_COLA_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT5 | GPIO_PIN7)
#define GPIO_LEDTS0_EXTENDED0 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN2)
#define GPIO_LEDTS0_EXTENDED1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN3)
#define GPIO_LEDTS0_EXTENDED2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN4)
#define GPIO_LEDTS0_EXTENDED3 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN5)
#define GPIO_LEDTS0_EXTENDED4 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN8)
#define GPIO_LEDTS0_EXTENDED5 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN9)
#define GPIO_LEDTS0_EXTENDED6 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN15)
#define GPIO_LEDTS0_EXTENDED7 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT5 | GPIO_PIN10)
#define GPIO_LEDTS0_LINE0_1 (GPIO_OUTPUT_ALT4 | GPIO_PORT2 | GPIO_PIN2)
#define GPIO_LEDTS0_LINE0_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT3 | GPIO_PIN7)
#define GPIO_LEDTS0_LINE1_1 (GPIO_OUTPUT_ALT4 | GPIO_PORT2 | GPIO_PIN3)
#define GPIO_LEDTS0_LINE1_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT3 | GPIO_PIN8)
#define GPIO_LEDTS0_LINE2_1 (GPIO_OUTPUT_ALT4 | GPIO_PORT2 | GPIO_PIN4)
#define GPIO_LEDTS0_LINE2_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT3 | GPIO_PIN9)
#define GPIO_LEDTS0_LINE3_1 (GPIO_OUTPUT_ALT4 | GPIO_PORT2 | GPIO_PIN5)
#define GPIO_LEDTS0_LINE3_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT3 | GPIO_PIN10)
#define GPIO_LEDTS0_LINE4_1 (GPIO_OUTPUT_ALT4 | GPIO_PORT2 | GPIO_PIN8)
#define GPIO_LEDTS0_LINE4_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT3 | GPIO_PIN11)
#define GPIO_LEDTS0_LINE5_1 (GPIO_OUTPUT_ALT4 | GPIO_PORT2 | GPIO_PIN9)
#define GPIO_LEDTS0_LINE5_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT3 | GPIO_PIN12)
#define GPIO_LEDTS0_LINE6_1 (GPIO_OUTPUT_ALT4 | GPIO_PORT2 | GPIO_PIN15)
#define GPIO_LEDTS0_LINE6_2 (GPIO_OUTPUT_ALT4 | GPIO_PORT3 | GPIO_PIN13)
#define GPIO_LEDTS0_LINE7 (GPIO_OUTPUT_ALT4 | GPIO_PORT5 | GPIO_PIN10)
#define GPIO_LEDTS0_TSIN0A (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN2)
#define GPIO_LEDTS0_TSIN1A (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN3)
#define GPIO_LEDTS0_TSIN2A (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN4)
#define GPIO_LEDTS0_TSIN3A (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN5)
#define GPIO_LEDTS0_TSIN4A (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN8)
#define GPIO_LEDTS0_TSIN5A (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN9)
#define GPIO_LEDTS0_TSIN6A (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN15)
#define GPIO_LEDTS0_TSIN7A (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT5 | GPIO_PIN10)
#define GPIO_POSIF0_IN0A (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN3)
#define GPIO_POSIF0_IN0B (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN7)
#define GPIO_POSIF0_IN1A (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN2)
#define GPIO_POSIF0_IN1B (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN6)
#define GPIO_POSIF0_IN2A (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN1)
#define GPIO_POSIF0_IN2B (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN5)
#define GPIO_POSIF1_IN0A (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN5)
#define GPIO_POSIF1_IN0B (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN10)
#define GPIO_POSIF1_IN1A (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN4)
#define GPIO_POSIF1_IN1B (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN9)
#define GPIO_POSIF1_IN2A (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN3)
#define GPIO_POSIF1_IN2B (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN8)
#define GPIO_SCU_EXTCLK_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT0 | GPIO_PIN8)
#define GPIO_SCU_EXTCLK_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT1 | GPIO_PIN15)
#define GPIO_SDMMC_BUSPOWER (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN4)
#define GPIO_SDMMC_CLKIN (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN6)
#define GPIO_SDMMC_CLKOUT (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN6)
#define GPIO_SDMMC_CMDIN (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN5)
#define GPIO_SDMMC_CMDOUT (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN5)
#define GPIO_SDMMC_DATA0IN (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT4 | GPIO_PIN0)
#define GPIO_SDMMC_DATA0OUT (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT4 | GPIO_PIN0)
#define GPIO_SDMMC_DATA1IN (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN6)
#define GPIO_SDMMC_DATA1OUT (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN6)
#define GPIO_SDMMC_DATA2IN (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN7)
#define GPIO_SDMMC_DATA2OUT (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN7)
#define GPIO_SDMMC_DATA3IN (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT4 | GPIO_PIN1)
#define GPIO_SDMMC_DATA3OUT (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT4 | GPIO_PIN1)
#define GPIO_SDMMC_DATA4IN (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN8)
#define GPIO_SDMMC_DATA4OUT (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN8)
#define GPIO_SDMMC_DATA5IN (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN9)
#define GPIO_SDMMC_DATA5OUT (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN9)
#define GPIO_SDMMC_DATA6IN (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN12)
#define GPIO_SDMMC_DATA6OUT (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN12)
#define GPIO_SDMMC_DATA7IN (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN13)
#define GPIO_SDMMC_DATA7OUT (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN13)
#define GPIO_SDMMC_LED (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN3)
#define GPIO_SDMMC_RST (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN11)
#define GPIO_SDMMC_SDCD (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN10)
#define GPIO_SDMMC_SDWC (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN1)
#define GPIO_TRACESWO (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN1)
#define GPIO_U0C0_DOUT0_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN5)
#define GPIO_U0C0_DOUT0_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT5 | GPIO_PIN1)
#define GPIO_U0C0_DOUT0_3 (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN5)
#define GPIO_U0C0_DOUT0_4 (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN7)
#define GPIO_U0C0_DOUT1_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN4)
#define GPIO_U0C0_DOUT2_2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN3)
#define GPIO_U0C0_DOUT3_3 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN2)
#define GPIO_U0C0_DX0A (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN5)
#define GPIO_U0C0_DX0B (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN4)
#define GPIO_U0C0_DX0C (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN7)
#define GPIO_U0C0_DX0D (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN0)
#define GPIO_U0C0_DX1A (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN1)
#define GPIO_U0C0_DX1B (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN8)
#define GPIO_U0C0_DX2A (GPIO_INPUT | GPIO_PORT1 | GPIO_PIN0)
#define GPIO_U0C0_DX2B (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN7)
#define GPIO_U0C0_HWIN0 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN5)
#define GPIO_U0C0_HWIN1 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN4)
#define GPIO_U0C0_HWIN2 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN3)
#define GPIO_U0C0_HWIN3 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT1 | GPIO_PIN2)
#define GPIO_U0C0_MCLKOUT (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN3)
#define GPIO_U0C0_SCLKOUT_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT0 | GPIO_PIN8)
#define GPIO_U0C0_SCLKOUT_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN1)
#define GPIO_U0C0_SCLKOUT_3 (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN10)
#define GPIO_U0C0_SCLKOUT_4 (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN6)
#define GPIO_U0C0_SELO0_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT0 | GPIO_PIN7)
#define GPIO_U0C0_SELO0_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN0)
#define GPIO_U0C0_SELO0_3 (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN11)
#define GPIO_U0C0_SELO1 (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN8)
#define GPIO_U0C0_SELO2 (GPIO_OUTPUT_ALT2 | GPIO_PORT4 | GPIO_PIN6)
#define GPIO_U0C0_SELO3 (GPIO_OUTPUT_ALT2 | GPIO_PORT4 | GPIO_PIN5)
#define GPIO_U0C0_SELO4 (GPIO_OUTPUT_ALT2 | GPIO_PORT4 | GPIO_PIN4)
#define GPIO_U0C0_SELO5 (GPIO_OUTPUT_ALT2 | GPIO_PORT4 | GPIO_PIN3)
#define GPIO_U0C1_DOUT0_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN13)
#define GPIO_U0C1_DOUT0_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT2 | GPIO_PIN5)
#define GPIO_U0C1_DOUT0_3 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN13)
#define GPIO_U0C1_DOUT0_4 (GPIO_OUTPUT_ALT2 | GPIO_PORT6 | GPIO_PIN4)
#define GPIO_U0C1_DOUT0_5 (GPIO_OUTPUT_ALT4 | GPIO_PORT3 | GPIO_PIN5)
#define GPIO_U0C1_DOUT1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN12)
#define GPIO_U0C1_DOUT2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN11)
#define GPIO_U0C1_DOUT3 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN10)
#define GPIO_U0C1_DX0A (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN2)
#define GPIO_U0C1_DX0B (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN5)
#define GPIO_U0C1_DX0C (GPIO_INPUT | GPIO_PORT6 | GPIO_PIN3)
#define GPIO_U0C1_DX0D (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN13)
#define GPIO_U0C1_DX0E (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN0)
#define GPIO_U0C1_DX1A (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN4)
#define GPIO_U0C1_DX1B (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN0)
#define GPIO_U0C1_DX1C (GPIO_INPUT | GPIO_PORT6 | GPIO_PIN2)
#define GPIO_U0C1_DX2A (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN3)
#define GPIO_U0C1_DX2B (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN1)
#define GPIO_U0C1_DX2C (GPIO_INPUT | GPIO_PORT6 | GPIO_PIN1)
#define GPIO_U0C1_HWIN0 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN13)
#define GPIO_U0C1_HWIN1 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN12)
#define GPIO_U0C1_HWIN2 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN11)
#define GPIO_U0C1_HWIN3 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN10)
#define GPIO_U0C1_MCLKOUT (GPIO_OUTPUT_ALT2 | GPIO_PORT6 | GPIO_PIN5)
#define GPIO_U0C1_SCLKOUT_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT2 | GPIO_PIN4)
#define GPIO_U0C1_SCLKOUT_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN0)
#define GPIO_U0C1_SCLKOUT_3 (GPIO_OUTPUT_ALT2 | GPIO_PORT6 | GPIO_PIN2)
#define GPIO_U0C1_SCLKOUT_4 (GPIO_OUTPUT_ALT4 | GPIO_PORT3 | GPIO_PIN6)
#define GPIO_U0C1_SELO0_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT2 | GPIO_PIN3)
#define GPIO_U0C1_SELO0_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN1)
#define GPIO_U0C1_SELO0_3 (GPIO_OUTPUT_ALT2 | GPIO_PORT6 | GPIO_PIN1)
#define GPIO_U0C1_SELO0_4 (GPIO_OUTPUT_ALT4 | GPIO_PORT4 | GPIO_PIN1)
#define GPIO_U0C1_SELO1_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN12)
#define GPIO_U0C1_SELO1_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT6 | GPIO_PIN0)
#define GPIO_U0C1_SELO2_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN14)
#define GPIO_U0C1_SELO2_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN11)
#define GPIO_U0C1_SELO3_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT1 | GPIO_PIN13)
#define GPIO_U0C1_SELO3_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN8)
#define GPIO_U1C0_DOUT0_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN5)
#define GPIO_U1C0_DOUT0_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT0 | GPIO_PIN5)
#define GPIO_U1C0_DOUT0_3 (GPIO_OUTPUT_ALT2 | GPIO_PORT2 | GPIO_PIN14)
#define GPIO_U1C0_DOUT1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN4)
#define GPIO_U1C0_DOUT2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN3)
#define GPIO_U1C0_DOUT3 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN2)
#define GPIO_U1C0_DX0A (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN4)
#define GPIO_U1C0_DX0B (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN5)
#define GPIO_U1C0_DX0C (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN15)
#define GPIO_U1C0_DX0D (GPIO_INPUT | GPIO_PORT2 | GPIO_PIN14)
#define GPIO_U1C0_DX1A (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN11)
#define GPIO_U1C0_DX1B (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN8)
#define GPIO_U1C0_DX2A (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN6)
#define GPIO_U1C0_DX2B (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN9)
#define GPIO_U1C0_HWIN0 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN5)
#define GPIO_U1C0_HWIN1 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN4)
#define GPIO_U1C0_HWIN2 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN3)
#define GPIO_U1C0_HWIN3 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN2)
#define GPIO_U1C0_MCLKOUT (GPIO_OUTPUT_ALT2 | GPIO_PORT5 | GPIO_PIN10)
#define GPIO_U1C0_SCLKOUT_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT0 | GPIO_PIN11)
#define GPIO_U1C0_SCLKOUT_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT5 | GPIO_PIN8)
#define GPIO_U1C0_SELO0_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT0 | GPIO_PIN6)
#define GPIO_U1C0_SELO0_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT5 | GPIO_PIN9)
#define GPIO_U1C0_SELO1_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT0 | GPIO_PIN14)
#define GPIO_U1C0_SELO1_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT5 | GPIO_PIN11)
#define GPIO_U1C0_SELO2 (GPIO_OUTPUT_ALT2 | GPIO_PORT0 | GPIO_PIN15)
#define GPIO_U1C0_SELO3 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN14)
#define GPIO_U1C1_DOUT0_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN15)
#define GPIO_U1C1_DOUT0_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT0 | GPIO_PIN1)
#define GPIO_U1C1_DOUT0_3 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN15)
#define GPIO_U1C1_DOUT0_4 (GPIO_OUTPUT_ALT2 | GPIO_PORT4 | GPIO_PIN2)
#define GPIO_U1C1_DOUT1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN14)
#define GPIO_U1C1_DOUT2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN15)
#define GPIO_U1C1_DOUT3 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN14)
#define GPIO_U1C1_DX0A (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN15)
#define GPIO_U1C1_DX0B (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN14)
#define GPIO_U1C1_DX0C (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN2)
#define GPIO_U1C1_DX0D (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN0)
#define GPIO_U1C1_DX1A (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN10)
#define GPIO_U1C1_DX1B (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN13)
#define GPIO_U1C1_DX1C (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN0)
#define GPIO_U1C1_DX2A (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN9)
#define GPIO_U1C1_DX2B (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN12)
#define GPIO_U1C1_HWIN0 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN15)
#define GPIO_U1C1_HWIN1 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT3 | GPIO_PIN14)
#define GPIO_U1C1_HWIN2 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN15)
#define GPIO_U1C1_HWIN3 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT0 | GPIO_PIN14)
#define GPIO_U1C1_SCLKOUT_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT0 | GPIO_PIN10)
#define GPIO_U1C1_SCLKOUT_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT0 | GPIO_PIN13)
#define GPIO_U1C1_SELO0_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT0 | GPIO_PIN12)
#define GPIO_U1C1_SELO0_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT0 | GPIO_PIN9)
#define GPIO_U1C1_SELO1_1 (GPIO_OUTPUT_ALT2 | GPIO_PORT0 | GPIO_PIN2)
#define GPIO_U1C1_SELO1_2 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN3)
#define GPIO_U1C1_SELO2 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN4)
#define GPIO_U1C1_SELO3 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN5)
#define GPIO_U1C1_SELO4 (GPIO_OUTPUT_ALT2 | GPIO_PORT3 | GPIO_PIN6)
#define GPIO_U2C0_DOUT0_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT5 | GPIO_PIN0)
#define GPIO_U2C0_DOUT0_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT3 | GPIO_PIN8)
#define GPIO_U2C0_DOUT0_3 (GPIO_OUTPUT_ALT1 | GPIO_PORT5 | GPIO_PIN0)
#define GPIO_U2C0_DOUT1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT5 | GPIO_PIN1)
#define GPIO_U2C0_DOUT2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT5 | GPIO_PIN7)
#define GPIO_U2C0_DOUT3 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN6)
#define GPIO_U2C0_DX0A (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN1)
#define GPIO_U2C0_DX0B (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN0)
#define GPIO_U2C0_DX0C (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN7)
#define GPIO_U2C0_DX1A (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN2)
#define GPIO_U2C0_DX2A (GPIO_INPUT | GPIO_PORT5 | GPIO_PIN3)
#define GPIO_U2C0_HWIN0 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT5 | GPIO_PIN0)
#define GPIO_U2C0_HWIN1 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT5 | GPIO_PIN1)
#define GPIO_U2C0_HWIN2 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT5 | GPIO_PIN7)
#define GPIO_U2C0_HWIN3 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT2 | GPIO_PIN6)
#define GPIO_U2C0_SCLKOUT_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT3 | GPIO_PIN9)
#define GPIO_U2C0_SCLKOUT_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT5 | GPIO_PIN2)
#define GPIO_U2C0_SELO0_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT3 | GPIO_PIN10)
#define GPIO_U2C0_SELO0_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT5 | GPIO_PIN3)
#define GPIO_U2C0_SELO1 (GPIO_OUTPUT_ALT1 | GPIO_PORT5 | GPIO_PIN4)
#define GPIO_U2C0_SELO2 (GPIO_OUTPUT_ALT1 | GPIO_PORT5 | GPIO_PIN5)
#define GPIO_U2C0_SELO3 (GPIO_OUTPUT_ALT1 | GPIO_PORT5 | GPIO_PIN6)
#define GPIO_U2C0_SELO4 (GPIO_OUTPUT_ALT1 | GPIO_PORT2 | GPIO_PIN6)
#define GPIO_U2C1_DOUT0_1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT4 | GPIO_PIN7)
#define GPIO_U2C1_DOUT0_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT3 | GPIO_PIN11)
#define GPIO_U2C1_DOUT0_3 (GPIO_OUTPUT_ALT1 | GPIO_PORT3 | GPIO_PIN5)
#define GPIO_U2C1_DOUT1 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT4 | GPIO_PIN6)
#define GPIO_U2C1_DOUT2 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT4 | GPIO_PIN5)
#define GPIO_U2C1_DOUT3 (GPIO_OUTPUT | GPIO_PINCTRL_HW0 | GPIO_PORT4 | GPIO_PIN4)
#define GPIO_U2C1_DX0A (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN5)
#define GPIO_U2C1_DX0B (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN4)
#define GPIO_U2C1_DX0C (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN0)
#define GPIO_U2C1_DX0D (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN12)
#define GPIO_U2C1_DX1A (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN2)
#define GPIO_U2C1_DX1B (GPIO_INPUT | GPIO_PORT3 | GPIO_PIN6)
#define GPIO_U2C1_DX2A (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN1)
#define GPIO_U2C1_DX2B (GPIO_INPUT | GPIO_PORT4 | GPIO_PIN1)
#define GPIO_U2C1_HWIN0 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT4 | GPIO_PIN7)
#define GPIO_U2C1_HWIN1 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT4 | GPIO_PIN6)
#define GPIO_U2C1_HWIN2 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT4 | GPIO_PIN5)
#define GPIO_U2C1_HWIN3 (GPIO_INPUT | GPIO_PINCTRL_HW0 | GPIO_PORT4 | GPIO_PIN4)
#define GPIO_U2C1_MCLKOUT (GPIO_OUTPUT_ALT1 | GPIO_PORT3 | GPIO_PIN4)
#define GPIO_U2C1_SCLKOUT_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT3 | GPIO_PIN13)
#define GPIO_U2C1_SCLKOUT_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT3 | GPIO_PIN6)
#define GPIO_U2C1_SCLKOUT_3 (GPIO_OUTPUT_ALT4 | GPIO_PORT4 | GPIO_PIN2)
#define GPIO_U2C1_SELO0_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT3 | GPIO_PIN0)
#define GPIO_U2C1_SELO0_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT4 | GPIO_PIN1)
#define GPIO_U2C1_SELO1 (GPIO_OUTPUT_ALT1 | GPIO_PORT4 | GPIO_PIN2)
#define GPIO_U2C1_SELO2 (GPIO_OUTPUT_ALT1 | GPIO_PORT4 | GPIO_PIN3)
#define GPIO_USB_DRIVEVBUS_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT0 | GPIO_PIN1)
#define GPIO_USB_DRIVEVBUS_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT3 | GPIO_PIN2)
#define GPIO_USB_ID (GPIO_INPUT | GPIO_PORT0 | GPIO_PIN9)
#define GPIO_VADC_EMUX00 (GPIO_OUTPUT_ALT1 | GPIO_PORT2 | GPIO_PIN2)
#define GPIO_VADC_EMUX01 (GPIO_OUTPUT_ALT1 | GPIO_PORT2 | GPIO_PIN3)
#define GPIO_VADC_EMUX02 (GPIO_OUTPUT_ALT1 | GPIO_PORT2 | GPIO_PIN4)
#define GPIO_VADC_EMUX10 (GPIO_OUTPUT_ALT1 | GPIO_PORT2 | GPIO_PIN10)
#define GPIO_VADC_EMUX11 (GPIO_OUTPUT_ALT1 | GPIO_PORT2 | GPIO_PIN14)
#define GPIO_VADC_EMUX12 (GPIO_OUTPUT_ALT1 | GPIO_PORT2 | GPIO_PIN15)
#define GPIO_VADC_G0CH0 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN0)
#define GPIO_VADC_G0CH1 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN1)
#define GPIO_VADC_G0CH2 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN2)
#define GPIO_VADC_G0CH3 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN3)
#define GPIO_VADC_G0CH4 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN4)
#define GPIO_VADC_G0CH5 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN5)
#define GPIO_VADC_G0CH6 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN6)
#define GPIO_VADC_G0CH7 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN7)
#define GPIO_VADC_G1CH0 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN8)
#define GPIO_VADC_G1CH1 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN9)
#define GPIO_VADC_G1CH2 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN2)
#define GPIO_VADC_G1CH3 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN3)
#define GPIO_VADC_G1CH4 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN12)
#define GPIO_VADC_G1CH5 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN13)
#define GPIO_VADC_G1CH6 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN14)
#define GPIO_VADC_G1CH7 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN15)
#define GPIO_VADC_G2CH0 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN4)
#define GPIO_VADC_G2CH1 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN5)
#define GPIO_VADC_G2CH2 (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN2)
#define GPIO_VADC_G2CH3 (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN3)
#define GPIO_VADC_G2CH4 (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN4)
#define GPIO_VADC_G2CH5 (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN5)
#define GPIO_VADC_G2CH6 (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN6)
#define GPIO_VADC_G2CH7 (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN7)
#define GPIO_VADC_G3CH0 (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN8)
#define GPIO_VADC_G3CH1 (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN9)
#define GPIO_VADC_G3CH2 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN8)
#define GPIO_VADC_G3CH3 (GPIO_INPUT | GPIO_PORT14 | GPIO_PIN9)
#define GPIO_VADC_G3CH4 (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN12)
#define GPIO_VADC_G3CH5 (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN13)
#define GPIO_VADC_G3CH6 (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN14)
#define GPIO_VADC_G3CH7 (GPIO_INPUT | GPIO_PORT15 | GPIO_PIN15)
#define GPIO_WWDT_SERVICEOUT_1 (GPIO_OUTPUT_ALT1 | GPIO_PORT0 | GPIO_PIN7)
#define GPIO_WWDT_SERVICEOUT_2 (GPIO_OUTPUT_ALT1 | GPIO_PORT1 | GPIO_PIN4)
#endif /* __ARCH_ARM_SRC_XMC4_HARDWARE_XMC4_PINMXU_H */
|
18e0834724f64a6d06ce323e13e7f6f0db842fea
|
f9e7d65cb784c01a0200145ba8d289afe41d4a56
|
/chip/stm32/usart-stm32l.c
|
2b7406a0a41dadd8f088ad08ce707708a7ec11a6
|
[
"BSD-3-Clause"
] |
permissive
|
FrameworkComputer/EmbeddedController
|
ad7086769e87d0a4179eae96a7c9ff5e383ff54e
|
f6d6b927eed71550d3475411cfc3e59abe5cef2a
|
refs/heads/hx20-hx30
| 2023-08-08T20:45:10.621169
| 2023-05-26T07:03:59
| 2023-05-26T07:03:59
| 447,021,040
| 846
| 48
|
BSD-3-Clause
| 2023-05-26T07:04:59
| 2022-01-12T00:11:14
|
C
|
UTF-8
|
C
| false
| false
| 3,413
|
c
|
usart-stm32l.c
|
/* Copyright 2014 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "usart-stm32l.h"
#include "clock.h"
#include "common.h"
#include "compile_time_macros.h"
#include "hooks.h"
#include "registers.h"
#include "task.h"
#include "util.h"
/*
* This configs array stores the currently active usart_config structure for
* each USART, an entry will be NULL if no USART driver is initialized for the
* corresponding hardware instance.
*/
#define STM32_USARTS_MAX 3
static struct usart_config const *configs[STM32_USARTS_MAX];
struct usart_configs usart_get_configs(void)
{
return (struct usart_configs) {configs, ARRAY_SIZE(configs)};
}
static void usart_variant_enable(struct usart_config const *config)
{
/* Use single-bit sampling */
STM32_USART_CR3(config->hw->base) |= STM32_USART_CR3_ONEBIT;
/*
* Make sure we register this config before enabling the HW.
* If we did it the other way around the FREQ_CHANGE hook could be
* called before we update the configs array and we would miss the
* clock frequency change event, leaving our baud rate divisor wrong.
*/
configs[config->hw->index] = config;
usart_set_baud_f0_l(config, config->baud, clock_get_freq());
task_enable_irq(config->hw->irq);
}
static void usart_variant_disable(struct usart_config const *config)
{
task_disable_irq(config->hw->irq);
configs[config->hw->index] = NULL;
}
static struct usart_hw_ops const usart_variant_hw_ops = {
.enable = usart_variant_enable,
.disable = usart_variant_disable,
};
static void freq_change(void)
{
size_t i;
for (i = 0; i < ARRAY_SIZE(configs); ++i)
if (configs[i])
usart_set_baud_f0_l(configs[i], configs[i]->baud,
clock_get_freq());
}
DECLARE_HOOK(HOOK_FREQ_CHANGE, freq_change, HOOK_PRIO_DEFAULT);
void usart_clear_tc(struct usart_config const *config)
{
STM32_USART_SR(config->hw->base) &= ~STM32_USART_SR_TC;
}
/*
* USART interrupt bindings. These functions can not be defined as static or
* they will be removed by the linker because of the way that DECLARE_IRQ works.
*/
#if defined(CONFIG_STREAM_USART1)
struct usart_hw_config const usart1_hw = {
.index = 0,
.base = STM32_USART1_BASE,
.irq = STM32_IRQ_USART1,
.clock_register = &STM32_RCC_APB2ENR,
.clock_enable = STM32_RCC_PB2_USART1,
.ops = &usart_variant_hw_ops,
};
void usart1_interrupt(void)
{
usart_interrupt(configs[0]);
}
DECLARE_IRQ(STM32_IRQ_USART1, usart1_interrupt, 2);
#endif
#if defined(CONFIG_STREAM_USART2)
struct usart_hw_config const usart2_hw = {
.index = 1,
.base = STM32_USART2_BASE,
.irq = STM32_IRQ_USART2,
.clock_register = &STM32_RCC_APB1ENR,
.clock_enable = STM32_RCC_PB1_USART2,
.ops = &usart_variant_hw_ops,
};
void usart2_interrupt(void)
{
usart_interrupt(configs[1]);
}
DECLARE_IRQ(STM32_IRQ_USART2, usart2_interrupt, 2);
#endif
#if defined(CONFIG_STREAM_USART3)
struct usart_hw_config const usart3_hw = {
.index = 2,
.base = STM32_USART3_BASE,
.irq = STM32_IRQ_USART3,
.clock_register = &STM32_RCC_APB1ENR,
.clock_enable = STM32_RCC_PB1_USART3,
.ops = &usart_variant_hw_ops,
};
void usart3_interrupt(void)
{
usart_interrupt(configs[2]);
}
DECLARE_IRQ(STM32_IRQ_USART3, usart3_interrupt, 2);
#endif
|
f2e64604f683e44c70e6cb6108c4bb93c54bfc4c
|
f47cb02269307e83d86373d9ab4bfb8b46283d22
|
/src/libguac/guacamole/pool.h
|
0a250046afddbe4a8c3259b968dec715c703c749
|
[
"Apache-2.0"
] |
permissive
|
apache/guacamole-server
|
7c8adf3f389f0539df353ef8f7ea6d44144ffb16
|
fe24e2d45ac0ac90588f64b43da6e0d518e59177
|
refs/heads/master
| 2023-09-04T02:42:34.907413
| 2023-08-30T22:57:11
| 2023-08-30T22:57:11
| 54,452,627
| 2,019
| 580
|
Apache-2.0
| 2023-09-13T00:15:57
| 2016-03-22T07:00:06
|
C
|
UTF-8
|
C
| false
| false
| 3,513
|
h
|
pool.h
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef _GUAC_POOL_H
#define _GUAC_POOL_H
/**
* Provides functions and structures for maintaining dynamically allocated and
* freed pools of integers.
*
* @file pool.h
*/
#include "pool-types.h"
#include <pthread.h>
struct guac_pool {
/**
* The minimum number of integers which must have been returned by
* guac_pool_next_int before previously-used and freed integers are
* allowed to be returned.
*/
int min_size;
/**
* The number of integers currently in use.
*/
int active;
/**
* The next integer to be released (after no more integers remain in the
* pool.
*/
int __next_value;
/**
* The first integer in the pool, if any.
*/
guac_pool_int* __head;
/**
* The last integer in the pool, if any.
*/
guac_pool_int* __tail;
/**
* Lock which is acquired when the pool is being modified or accessed.
*/
pthread_mutex_t __lock;
};
struct guac_pool_int {
/**
* The integer value of this pool entry.
*/
int value;
/**
* The next available (unused) guac_pool_int in the list of
* allocated but free'd ints.
*/
guac_pool_int* __next;
};
/**
* Allocates a new guac_pool having the given minimum size.
*
* @param size The minimum number of integers which must have been returned by
* guac_pool_next_int before freed integers (previously used
* integers) are allowed to be returned.
* @return A new, empty guac_pool, having the given minimum size.
*/
guac_pool* guac_pool_alloc(int size);
/**
* Frees the given guac_pool.
*
* @param pool The guac_pool to free.
*/
void guac_pool_free(guac_pool* pool);
/**
* Returns the next available integer from the given guac_pool. All integers
* returned are non-negative, and are returned in sequences, starting from 0.
* This operation is threadsafe.
*
* @param pool
* The guac_pool to retrieve an integer from.
*
* @return
* The next available integer, which may be either an integer not yet
* returned by a call to guac_pool_next_int, or an integer which was
* previously returned, but has since been freed.
*/
int guac_pool_next_int(guac_pool* pool);
/**
* Frees the given integer back into the given guac_pool. The integer given
* will be available for future calls to guac_pool_next_int. This operation is
* threadsafe.
*
* @param pool
* The guac_pool to free the given integer into.
*
* @param value
* The integer which should be returned to the given pool, such that it can
* be received by a future call to guac_pool_next_int.
*/
void guac_pool_free_int(guac_pool* pool, int value);
#endif
|
aeecdee3400153db946bde14ceea6c60b015b9cc
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/ios/chrome/app/memory_monitor.h
|
25b7b480ef3070b2a4bcb5b04cd00572251307f2
|
[
"BSD-3-Clause"
] |
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
| 426
|
h
|
memory_monitor.h
|
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_CHROME_APP_MEMORY_MONITOR_H_
#define IOS_CHROME_APP_MEMORY_MONITOR_H_
// Starts the memory monitor that periodically updates the amount of free
// memory and free disk space in the background.
void StartFreeMemoryMonitor();
#endif // IOS_CHROME_APP_MEMORY_MONITOR_H_
|
20bd0d1c5b218f814e2c971aa5826061e6fc8720
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/nrf5x/libraries/drivers/drv_flash.c
|
259ee09aa23a10c8b6dbff9cc2c3752ccd6c26c5
|
[
"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
| 4,378
|
c
|
drv_flash.c
|
/*
* Copyright (c) 2006-2022, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2020-04-29 supperthomas first version
*/
#include "board.h"
#include <nrfx.h>
#include "nrfx_nvmc.h"
#ifdef BSP_USING_ON_CHIP_FLASH
#if defined(RT_USING_FAL)
#include "fal.h"
#endif
#include <rtdbg.h>
#define LOG_TAG "drv.flash"
/**
* @brief Gets the page of a given address
* @param Addr: Address of the FLASH Memory
* @retval The page of a given address
*/
static uint32_t GetPage(uint32_t Addr)
{
uint32_t page = 0;
if (Addr < (MCU_FLASH_START_ADDRESS + MCU_FLASH_SIZE))
{
page = (Addr - MCU_FLASH_START_ADDRESS) / MCU_FLASH_PAGE_SIZE;
}
else
{
return 0xffffffff;
}
return page;
}
/**
* Read data from flash.
* @note This operation's units is word.
*
* @param addr flash address
* @param buf buffer to store read data
* @param size read bytes size
*
* @return result
*/
int mcu_flash_read(rt_uint32_t addr, rt_uint8_t *buf, size_t size)
{
size_t i;
if ((addr + size) > MCU_FLASH_END_ADDRESS)
{
LOG_E("read outrange flash size! addr is (0x%p)", (void *)(addr + size));
return -RT_EINVAL;
}
for (i = 0; i < size; i++, buf++, addr++)
{
*buf = *(rt_uint8_t *) addr;
}
return size;
}
/**
* Write data to flash.
* @note This operation's units is word.
* @note This operation must after erase. @see flash_erase.
*
* @param addr flash address
* @param buf the write data buffer
* @param size write bytes size
*
* @return result
*/
int mcu_flash_write(rt_uint32_t addr, const uint8_t *buf, size_t size)
{
if ((addr + size) > MCU_FLASH_END_ADDRESS)
{
LOG_E("ERROR: write outrange flash size! addr is (0x%p)\n", (void *)(addr + size));
return -RT_EINVAL;
}
if (addr % 4 != 0)
{
LOG_E("write addr should be 4-byte alignment");
//4byte write
//else byts
return -RT_EINVAL;
}
if (size < 1)
{
return -RT_ERROR;
}
if (size % 4 != 0)
{
nrfx_nvmc_bytes_write(addr, buf, size);
return size;
}
else
{
nrfx_nvmc_words_write(addr, buf, size / 4);
return size;
}
}
/**
* Erase data on flash.
* @note This operation is irreversible.
* @note This operation's units is different which on many chips.
*
* @param addr flash address
* @param size erase bytes size
*
* @return result
*/
int mcu_flash_erase(rt_uint32_t addr, size_t size)
{
nrfx_err_t result = NRFX_SUCCESS;
uint32_t FirstPage = 0, NbOfPages = 0;
if ((addr + size) > MCU_FLASH_END_ADDRESS)
{
LOG_E("ERROR: erase outrange flash size! addr is (0x%p)\n", (void *)(addr + size));
return -RT_EINVAL;
}
FirstPage = GetPage(addr);
NbOfPages = GetPage(addr + size - 1) - FirstPage + 1;
for (int i = 0; i < NbOfPages ; i++)
{
result = nrfx_nvmc_page_erase((FirstPage + i) * MCU_FLASH_PAGE_SIZE);
if (NRFX_SUCCESS != result)
{
LOG_E("ERROR: erase flash page %d ! error code is (%x)\n", FirstPage + i, result);
return -RT_EINVAL;
}
}
LOG_D("erase done: addr (0x%p), size %d", (void *)addr, NbOfPages * MCU_FLASH_PAGE_SIZE);
return size;
}
#if defined(RT_USING_FAL)
static int fal_flash_read(long offset, rt_uint8_t *buf, size_t size);
static int fal_flash_write(long offset, const rt_uint8_t *buf, size_t size);
static int fal_flash_erase(long offset, size_t size);
static int fal_flash_read(long offset, rt_uint8_t *buf, size_t size)
{
return mcu_flash_read(mcu_onchip_flash.addr + offset, buf, size);
}
static int fal_flash_write(long offset, const rt_uint8_t *buf, size_t size)
{
return mcu_flash_write(mcu_onchip_flash.addr + offset, buf, size);
}
static int fal_flash_erase(long offset, size_t size)
{
return mcu_flash_erase(mcu_onchip_flash.addr + offset, size);
}
const struct fal_flash_dev mcu_onchip_flash =
{
.name = ON_CHIP_FLASH_DEV_NAME,
.addr = MCU_FLASH_START_ADDRESS,
.len = MCU_FLASH_SIZE,
.blk_size = MCU_FLASH_PAGE_SIZE,
.ops = {NULL, fal_flash_read, fal_flash_write, fal_flash_erase},
.write_gran = 8
};
#endif
#endif /* BSP_USING_ON_CHIP_FLASH */
|
49c043e9ba8026d5d96667f35a2648d45be54f10
|
1c015973d4df0f85787c93c486ce7917c1f0af0d
|
/ext/agoo/doc.c
|
52c3d47adbab4def7353e2a9a354de97e96745d4
|
[
"MIT"
] |
permissive
|
ohler55/agoo
|
73d4a876d79a2cd075d88f02a9260bccb031d1dd
|
20b47d51c1ea4b2660031f7b4bf7b9ed88413b4f
|
refs/heads/develop
| 2023-08-31T23:12:22.615271
| 2023-07-10T19:21:33
| 2023-07-10T19:21:33
| 115,074,220
| 853
| 43
|
MIT
| 2023-09-04T05:38:49
| 2017-12-22T03:51:02
|
C
|
UTF-8
|
C
| false
| false
| 10,153
|
c
|
doc.c
|
// Copyright (c) 2018, Peter Ohler, All rights reserved.
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "doc.h"
#include "gqlvalue.h"
#include "graphql.h"
#define EXP_MAX 100000
#define DEC_MAX 16
static char char_map[256] = "\
.........ww..w..................\
wpq.....pp..w.p.ttttttttttp..p..\
pttttttttttttttttttttttttttp.p.t\
.ttttttttttttttttttttttttttppp..\
................................\
................................\
................................\
................................";
static char json_map[256] = "\
.........ww..w..................\
wpq.....pp..c.p.ttttttttttp..p..\
pttttttttttttttttttttttttttp.p.t\
.ttttttttttttttttttttttttttppp..\
................................\
................................\
................................\
................................";
static char value_map[256] = "\
.........ww..w..................\
wpq.....pp..ctt.ttttttttttt..p..\
pttttttttttttttttttttttttttp.p.t\
.ttttttttttttttttttttttttttppp..\
................................\
................................\
................................\
................................";
void
agoo_doc_init(agooDoc doc, const char *str, int len) {
if (0 >= len) {
len = (int)strlen(str);
}
doc->str = str;
doc->cur = str;
doc->end = str + len;
// If there is a BOM, skip it.
if (0xEF == (uint8_t)*doc->str && 0xBB == (uint8_t)doc->str[1] && 0xBF == (uint8_t)doc->str[2]) {
doc->cur += 3;
}
}
int
agoo_doc_skip_white(agooDoc doc) {
const char *start = doc->cur;
while (true) {
for (; 'w' == char_map[*(uint8_t*)doc->cur]; doc->cur++) {
}
if ('#' == *doc->cur) {
agoo_doc_skip_comment(doc);
} else {
break;
}
}
return (int)(doc->cur - start);
}
int
agoo_doc_skip_jwhite(agooDoc doc) {
const char *start = doc->cur;
for (; 'w' == json_map[*(uint8_t*)doc->cur]; doc->cur++) {
}
return (int)(doc->cur - start);
}
void
agoo_doc_skip_comment(agooDoc doc) {
for (; true; doc->cur++) {
switch (*doc->cur) {
case '\r':
case '\n':
return;
default:
break;
}
}
}
// Return true if found, false if not.
bool
agoo_doc_skip_to(agooDoc doc, char c) {
const char *orig = doc->cur;
for (; doc->cur < doc->end; doc->cur++) {
if (c == *doc->cur) {
return true;
}
}
doc->cur = orig;
return false;
}
void
agoo_doc_read_token(agooDoc doc) {
if ('t' == char_map[*(uint8_t*)doc->cur] && '9' < *doc->cur) {
doc->cur++;
for (; 't' == char_map[*(uint8_t*)doc->cur]; doc->cur++) {
}
}
}
void
agoo_doc_next_token(agooDoc doc) {
while (true) {
agoo_doc_skip_white(doc);
if ('#' == *doc->cur) {
agoo_doc_skip_comment(doc);
} else {
break;
}
}
}
void
agoo_doc_read_value_token(agooDoc doc) {
for (; 't' == value_map[*(uint8_t*)doc->cur]; doc->cur++) {
}
}
// Just find end.
int
agoo_doc_read_string(agooErr err, agooDoc doc) {
doc->cur++; // skip first "
if ('"' == *doc->cur) { // a """ string or an empty string
doc->cur++;
if ('"' != *doc->cur) {
return AGOO_ERR_OK; // empty string
}
doc->cur++;
for (; doc->cur < doc->end; doc->cur++) {
if ('"' == *doc->cur && '"' == doc->cur[1] && '"' == doc->cur[2]) {
doc->cur += 3;
break;
}
}
} else {
for (; doc->cur < doc->end; doc->cur++) {
if ('"' == *doc->cur) {
if ('\\' != doc->cur[-1]) {
doc->cur++;
break;
}
}
}
}
if (doc->end <= doc->cur) {
return agoo_doc_err(doc, err, "String not terminated");
}
return AGOO_ERR_OK;
}
// string delimited by a single quote
int
agoo_doc_read_quote(agooErr err, agooDoc doc) {
doc->cur++; // skip first '
if ('\'' == *doc->cur) { // an empty string
doc->cur++;
return AGOO_ERR_OK; // empty string
}
for (; doc->cur < doc->end; doc->cur++) {
if ('\'' == *doc->cur) {
doc->cur++;
break;
}
}
if (doc->end <= doc->cur) {
return agoo_doc_err(doc, err, "String not terminated");
}
return AGOO_ERR_OK;
}
int
agoo_doc_err(agooDoc doc, agooErr err, const char *fmt, ...) {
va_list ap;
char msg[248];
int line = 0;
int col = 0;
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg), fmt, ap);
agoo_doc_location(doc, &line, &col);
va_end(ap);
return agoo_err_set(err, AGOO_ERR_PARSE, "%s at %d:%d", msg, line, col);
}
void
agoo_doc_location(agooDoc doc, int *linep, int *colp) {
const char *s;
int line = 1;
int col = 1;
for (s = doc->str; s < doc->cur; s++) {
switch (*s) {
case '\n':
line++;
col = 1;
break;
case '\r':
if ('\n' == *(s + 1)) {
s++;
}
line++;
col = 1;
break;
default:
col++;
break;
}
}
*linep = line;
*colp = col;
}
static gqlValue
read_number(agooErr err, agooDoc doc) {
int64_t i = 0;
int64_t num = 0;
int64_t div = 1;
int64_t di = 0;
long exp = 0;
int neg = false;
int hasExp = false;
int dec_cnt = 0;
int d;
if ('-' == *doc->cur) {
doc->cur++;
neg = true;
} else if ('+' == *doc->cur) {
doc->cur++;
}
for (; '0' <= *doc->cur && *doc->cur <= '9'; doc->cur++) {
if (0 < i) {
dec_cnt++;
}
d = *doc->cur - '0';
i = i * 10 + d;
if (INT64_MAX <= (uint64_t)i) {
agoo_doc_err(doc, err, "number is too large");
return NULL;
}
}
if ('.' == *doc->cur) {
doc->cur++;
for (; '0' <= *doc->cur && *doc->cur <= '9'; doc->cur++) {
d = (*doc->cur - '0');
if (0 < num || 0 < i) {
dec_cnt++;
}
num = num * 10 + d;
div *= 10;
di++;
if (INT64_MAX <= (uint64_t)div || DEC_MAX < dec_cnt) {
agoo_doc_err(doc, err, "number has too many digits");
return NULL;
}
}
if ('e' == *doc->cur || 'E' == *doc->cur) {
int eneg = 0;
hasExp = true;
doc->cur++;
if ('-' == *doc->cur) {
doc->cur++;
eneg = true;
} else if ('+' == *doc->cur) {
doc->cur++;
}
for (; '0' <= *doc->cur && *doc->cur <= '9'; doc->cur++) {
exp = exp * 10 + (*doc->cur - '0');
if (EXP_MAX <= exp) {
agoo_doc_err(doc, err, "number has too many digits");
return NULL;
}
}
if (eneg) {
exp = -exp;
}
}
}
if (hasExp || 0 < num) {
long double d = (long double)i * (long double)div + (long double)num;
int x = (int)((int64_t)exp - di);
d = roundl(d);
if (0 < x) {
d *= powl(10.0L, x);
} else if (0 > x) {
d /= powl(10.0L, -x);
}
if (neg) {
d = -d;
}
return gql_float_create(err, (double)d);
}
if (INT32_MAX < i) {
if (neg) {
return gql_i64_create(err, -i);
} else {
return gql_i64_create(err, i);
}
}
if (neg) {
return gql_int_create(err, (int32_t)-i);
}
return gql_int_create(err, (int32_t)i);
}
gqlValue
agoo_doc_read_value(agooErr err, agooDoc doc, gqlType type) {
gqlValue value = NULL;
const char *start;
agoo_doc_skip_white(doc);
start = doc->cur;
switch (*doc->cur) {
case '$':
doc->cur++;
start++;
agoo_doc_read_token(doc);
value = gql_var_create(err, start, (int)(doc->cur - start));
break;
case '"': {
const char *end;
start++;
if (AGOO_ERR_OK != agoo_doc_read_string(err, doc)) {
return NULL;
}
if ('"' == *start) { // must be a """
start += 2;
end = doc->cur - 3;
} else {
end = doc->cur - 1;
}
value = gql_string_create(err, start, (int)(end - start));
break;
}
case '-':
case '+':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = read_number(err, doc);
break;
case 'n':
agoo_doc_read_token(doc);
if (doc->cur - start == 4 && 0 == strncmp("null", start, 4)) {
value = gql_null_create(err);
} else {
value = gql_token_create(err, start, (int)(doc->cur - start), type);
}
break;
case 't':
agoo_doc_read_token(doc);
if (doc->cur - start == 4 && 0 == strncmp("true", start, 4)) {
value = gql_bool_create(err, true);
} else {
value = gql_token_create(err, start, (int)(doc->cur - start), type);
}
break;
case 'f':
agoo_doc_read_token(doc);
if (doc->cur - start == 5 && 0 == strncmp("false", start, 5)) {
value = gql_bool_create(err, false);
} else {
value = gql_token_create(err, start, (int)(doc->cur - start), type);
}
break;
case '[':
if (NULL != type) {
if (GQL_LIST != type->kind) {
agoo_doc_err(doc, err, "Not a list type");
return NULL;
}
type = type->base;
}
if (NULL== (value = gql_list_create(err, type))) {
return NULL;
}
doc->cur++;
while (doc->cur < doc->end) {
gqlValue member;
agoo_doc_skip_white(doc);
if (']' == *doc->cur) {
doc->cur++;
break;
}
if (NULL == (member = agoo_doc_read_value(err, doc, type))) {
return NULL;
}
if (AGOO_ERR_OK != gql_list_append(err, value, member)) {
return NULL;
}
}
break;
case '{':
if (NULL == (value = gql_object_create(err))) {
return NULL;
}
//value->type = type; // values are always the base object type
doc->cur++;
while (doc->cur < doc->end) {
char key[256];
gqlValue member;
agoo_doc_skip_white(doc);
if ('}' == *doc->cur) {
doc->cur++;
break;
}
start = doc->cur;
agoo_doc_read_token(doc);
if (start == doc->cur) {
agoo_doc_err(doc, err, "Expected a member name.");
return NULL;
}
if ((int)sizeof(key) <= doc->cur - start) {
agoo_doc_err(doc, err, "Member name too long.");
return NULL;
}
strncpy(key, start, doc->cur - start);
key[doc->cur - start] = '\0';
agoo_doc_read_token(doc);
if (':' != *doc->cur) {
agoo_doc_err(doc, err, "Expected a ':' after member name.");
return NULL;
}
doc->cur++;
if (NULL == (member = agoo_doc_read_value(err, doc, type))) {
return NULL;
}
if (AGOO_ERR_OK != gql_object_set(err, value, key, member)) {
return NULL;
}
}
break;
default: // Enum value
agoo_doc_read_token(doc);
value = gql_token_create(err, start, (int)(doc->cur - start), type);
break;
}
return value;
}
|
434a6eef4780518af1d547f15e928311470bd1e6
|
ac2f43c8e0d9649a7f063c59b3dffdfed9fd7ed7
|
/common/recipes-core/oob-nic/oob-nic/mac_platform.c
|
15b1792d2968842641d1066647796d80ecada377
|
[] |
no_license
|
facebook/openbmc
|
bef10604ced226288600f55248b7f1be9945aea4
|
32777c66a8410d767eae15baabf71c61a0bef13c
|
refs/heads/helium
| 2023-08-17T03:13:54.729494
| 2023-08-16T23:24:18
| 2023-08-16T23:24:18
| 31,917,712
| 684
| 331
| null | 2023-07-25T21:19:08
| 2015-03-09T19:18:35
|
C
|
UTF-8
|
C
| false
| false
| 112
|
c
|
mac_platform.c
|
#include <stdint.h>
int platform_get_mac(uint8_t mac[6])
{
// TODO Try hard-coded MAC address
return -1;
}
|
a4d1482cf757003b266bd64f6ca23ec1750ca05a
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/microchip/same70/bsp/hri/hri_wdt_e70b.h
|
fd3cef092fac75c896530f7087ef4e73dc574647
|
[
"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
| 11,182
|
h
|
hri_wdt_e70b.h
|
/**
* \file
*
* \brief SAM WDT
*
* Copyright (c) 2017-2018 Microchip Technology Inc. and its subsidiaries.
*
* \asf_license_start
*
* \page License
*
* Subject to your compliance with these terms, you may use Microchip
* software and any derivatives exclusively with Microchip products.
* It is your responsibility to comply with third party license terms applicable
* to your use of third party software (including open source software) that
* may accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES,
* WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE,
* INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY,
* AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE
* LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL
* LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE
* SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE
* POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT
* ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY
* RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*
* \asf_license_stop
*/
#ifdef _SAME70_WDT_COMPONENT_
#ifndef _HRI_WDT_E70B_H_INCLUDED_
#define _HRI_WDT_E70B_H_INCLUDED_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <hal_atomic.h>
#if defined(ENABLE_WDT_CRITICAL_SECTIONS)
#define WDT_CRITICAL_SECTION_ENTER() CRITICAL_SECTION_ENTER()
#define WDT_CRITICAL_SECTION_LEAVE() CRITICAL_SECTION_LEAVE()
#else
#define WDT_CRITICAL_SECTION_ENTER()
#define WDT_CRITICAL_SECTION_LEAVE()
#endif
typedef uint32_t hri_wdt_cr_reg_t;
typedef uint32_t hri_wdt_mr_reg_t;
typedef uint32_t hri_wdt_sr_reg_t;
static inline bool hri_wdt_get_SR_WDUNF_bit(const void *const hw)
{
return (((Wdt *)hw)->WDT_SR & WDT_SR_WDUNF) > 0;
}
static inline bool hri_wdt_get_SR_WDERR_bit(const void *const hw)
{
return (((Wdt *)hw)->WDT_SR & WDT_SR_WDERR) > 0;
}
static inline hri_wdt_sr_reg_t hri_wdt_get_SR_reg(const void *const hw, hri_wdt_sr_reg_t mask)
{
uint32_t tmp;
tmp = ((Wdt *)hw)->WDT_SR;
tmp &= mask;
return tmp;
}
static inline hri_wdt_sr_reg_t hri_wdt_read_SR_reg(const void *const hw)
{
return ((Wdt *)hw)->WDT_SR;
}
static inline void hri_wdt_set_MR_WDFIEN_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR |= WDT_MR_WDFIEN;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline bool hri_wdt_get_MR_WDFIEN_bit(const void *const hw)
{
uint32_t tmp;
tmp = ((Wdt *)hw)->WDT_MR;
tmp = (tmp & WDT_MR_WDFIEN) >> WDT_MR_WDFIEN_Pos;
return (bool)tmp;
}
static inline void hri_wdt_write_MR_WDFIEN_bit(const void *const hw, bool value)
{
uint32_t tmp;
WDT_CRITICAL_SECTION_ENTER();
tmp = ((Wdt *)hw)->WDT_MR;
tmp &= ~WDT_MR_WDFIEN;
tmp |= value << WDT_MR_WDFIEN_Pos;
((Wdt *)hw)->WDT_MR = tmp;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_clear_MR_WDFIEN_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR &= ~WDT_MR_WDFIEN;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_toggle_MR_WDFIEN_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR ^= WDT_MR_WDFIEN;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_set_MR_WDRSTEN_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR |= WDT_MR_WDRSTEN;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline bool hri_wdt_get_MR_WDRSTEN_bit(const void *const hw)
{
uint32_t tmp;
tmp = ((Wdt *)hw)->WDT_MR;
tmp = (tmp & WDT_MR_WDRSTEN) >> WDT_MR_WDRSTEN_Pos;
return (bool)tmp;
}
static inline void hri_wdt_write_MR_WDRSTEN_bit(const void *const hw, bool value)
{
uint32_t tmp;
WDT_CRITICAL_SECTION_ENTER();
tmp = ((Wdt *)hw)->WDT_MR;
tmp &= ~WDT_MR_WDRSTEN;
tmp |= value << WDT_MR_WDRSTEN_Pos;
((Wdt *)hw)->WDT_MR = tmp;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_clear_MR_WDRSTEN_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR &= ~WDT_MR_WDRSTEN;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_toggle_MR_WDRSTEN_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR ^= WDT_MR_WDRSTEN;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_set_MR_WDDIS_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR |= WDT_MR_WDDIS;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline bool hri_wdt_get_MR_WDDIS_bit(const void *const hw)
{
uint32_t tmp;
tmp = ((Wdt *)hw)->WDT_MR;
tmp = (tmp & WDT_MR_WDDIS) >> WDT_MR_WDDIS_Pos;
return (bool)tmp;
}
static inline void hri_wdt_write_MR_WDDIS_bit(const void *const hw, bool value)
{
uint32_t tmp;
WDT_CRITICAL_SECTION_ENTER();
tmp = ((Wdt *)hw)->WDT_MR;
tmp &= ~WDT_MR_WDDIS;
tmp |= value << WDT_MR_WDDIS_Pos;
((Wdt *)hw)->WDT_MR = tmp;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_clear_MR_WDDIS_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR &= ~WDT_MR_WDDIS;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_toggle_MR_WDDIS_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR ^= WDT_MR_WDDIS;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_set_MR_WDDBGHLT_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR |= WDT_MR_WDDBGHLT;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline bool hri_wdt_get_MR_WDDBGHLT_bit(const void *const hw)
{
uint32_t tmp;
tmp = ((Wdt *)hw)->WDT_MR;
tmp = (tmp & WDT_MR_WDDBGHLT) >> WDT_MR_WDDBGHLT_Pos;
return (bool)tmp;
}
static inline void hri_wdt_write_MR_WDDBGHLT_bit(const void *const hw, bool value)
{
uint32_t tmp;
WDT_CRITICAL_SECTION_ENTER();
tmp = ((Wdt *)hw)->WDT_MR;
tmp &= ~WDT_MR_WDDBGHLT;
tmp |= value << WDT_MR_WDDBGHLT_Pos;
((Wdt *)hw)->WDT_MR = tmp;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_clear_MR_WDDBGHLT_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR &= ~WDT_MR_WDDBGHLT;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_toggle_MR_WDDBGHLT_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR ^= WDT_MR_WDDBGHLT;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_set_MR_WDIDLEHLT_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR |= WDT_MR_WDIDLEHLT;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline bool hri_wdt_get_MR_WDIDLEHLT_bit(const void *const hw)
{
uint32_t tmp;
tmp = ((Wdt *)hw)->WDT_MR;
tmp = (tmp & WDT_MR_WDIDLEHLT) >> WDT_MR_WDIDLEHLT_Pos;
return (bool)tmp;
}
static inline void hri_wdt_write_MR_WDIDLEHLT_bit(const void *const hw, bool value)
{
uint32_t tmp;
WDT_CRITICAL_SECTION_ENTER();
tmp = ((Wdt *)hw)->WDT_MR;
tmp &= ~WDT_MR_WDIDLEHLT;
tmp |= value << WDT_MR_WDIDLEHLT_Pos;
((Wdt *)hw)->WDT_MR = tmp;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_clear_MR_WDIDLEHLT_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR &= ~WDT_MR_WDIDLEHLT;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_toggle_MR_WDIDLEHLT_bit(const void *const hw)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR ^= WDT_MR_WDIDLEHLT;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_set_MR_WDV_bf(const void *const hw, hri_wdt_mr_reg_t mask)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR |= WDT_MR_WDV(mask);
WDT_CRITICAL_SECTION_LEAVE();
}
static inline hri_wdt_mr_reg_t hri_wdt_get_MR_WDV_bf(const void *const hw, hri_wdt_mr_reg_t mask)
{
uint32_t tmp;
tmp = ((Wdt *)hw)->WDT_MR;
tmp = (tmp & WDT_MR_WDV(mask)) >> WDT_MR_WDV_Pos;
return tmp;
}
static inline void hri_wdt_write_MR_WDV_bf(const void *const hw, hri_wdt_mr_reg_t data)
{
uint32_t tmp;
WDT_CRITICAL_SECTION_ENTER();
tmp = ((Wdt *)hw)->WDT_MR;
tmp &= ~WDT_MR_WDV_Msk;
tmp |= WDT_MR_WDV(data);
((Wdt *)hw)->WDT_MR = tmp;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_clear_MR_WDV_bf(const void *const hw, hri_wdt_mr_reg_t mask)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR &= ~WDT_MR_WDV(mask);
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_toggle_MR_WDV_bf(const void *const hw, hri_wdt_mr_reg_t mask)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR ^= WDT_MR_WDV(mask);
WDT_CRITICAL_SECTION_LEAVE();
}
static inline hri_wdt_mr_reg_t hri_wdt_read_MR_WDV_bf(const void *const hw)
{
uint32_t tmp;
tmp = ((Wdt *)hw)->WDT_MR;
tmp = (tmp & WDT_MR_WDV_Msk) >> WDT_MR_WDV_Pos;
return tmp;
}
static inline void hri_wdt_set_MR_WDD_bf(const void *const hw, hri_wdt_mr_reg_t mask)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR |= WDT_MR_WDD(mask);
WDT_CRITICAL_SECTION_LEAVE();
}
static inline hri_wdt_mr_reg_t hri_wdt_get_MR_WDD_bf(const void *const hw, hri_wdt_mr_reg_t mask)
{
uint32_t tmp;
tmp = ((Wdt *)hw)->WDT_MR;
tmp = (tmp & WDT_MR_WDD(mask)) >> WDT_MR_WDD_Pos;
return tmp;
}
static inline void hri_wdt_write_MR_WDD_bf(const void *const hw, hri_wdt_mr_reg_t data)
{
uint32_t tmp;
WDT_CRITICAL_SECTION_ENTER();
tmp = ((Wdt *)hw)->WDT_MR;
tmp &= ~WDT_MR_WDD_Msk;
tmp |= WDT_MR_WDD(data);
((Wdt *)hw)->WDT_MR = tmp;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_clear_MR_WDD_bf(const void *const hw, hri_wdt_mr_reg_t mask)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR &= ~WDT_MR_WDD(mask);
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_toggle_MR_WDD_bf(const void *const hw, hri_wdt_mr_reg_t mask)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR ^= WDT_MR_WDD(mask);
WDT_CRITICAL_SECTION_LEAVE();
}
static inline hri_wdt_mr_reg_t hri_wdt_read_MR_WDD_bf(const void *const hw)
{
uint32_t tmp;
tmp = ((Wdt *)hw)->WDT_MR;
tmp = (tmp & WDT_MR_WDD_Msk) >> WDT_MR_WDD_Pos;
return tmp;
}
static inline void hri_wdt_set_MR_reg(const void *const hw, hri_wdt_mr_reg_t mask)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR |= mask;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline hri_wdt_mr_reg_t hri_wdt_get_MR_reg(const void *const hw, hri_wdt_mr_reg_t mask)
{
uint32_t tmp;
tmp = ((Wdt *)hw)->WDT_MR;
tmp &= mask;
return tmp;
}
static inline void hri_wdt_write_MR_reg(const void *const hw, hri_wdt_mr_reg_t data)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR = data;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_clear_MR_reg(const void *const hw, hri_wdt_mr_reg_t mask)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR &= ~mask;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline void hri_wdt_toggle_MR_reg(const void *const hw, hri_wdt_mr_reg_t mask)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_MR ^= mask;
WDT_CRITICAL_SECTION_LEAVE();
}
static inline hri_wdt_mr_reg_t hri_wdt_read_MR_reg(const void *const hw)
{
return ((Wdt *)hw)->WDT_MR;
}
static inline void hri_wdt_write_CR_reg(const void *const hw, hri_wdt_cr_reg_t data)
{
WDT_CRITICAL_SECTION_ENTER();
((Wdt *)hw)->WDT_CR = data;
WDT_CRITICAL_SECTION_LEAVE();
}
#ifdef __cplusplus
}
#endif
#endif /* _HRI_WDT_E70B_H_INCLUDED */
#endif /* _SAME70_WDT_COMPONENT_ */
|
e80b59782780864dc9b6beeafc6223b35d1b308f
|
b4995c17067e4c16e287b4d0d454a9437ed38751
|
/src/njs_generator.c
|
6a47dc1149af9b74edd1fe08e78f763df1f945cc
|
[
"BSD-2-Clause"
] |
permissive
|
nginx/njs
|
95f44a9128d26f8ed6a052b2e00dd7cff1410efb
|
e694d61a94c711b7c48b0ae23909a4cef7c65700
|
refs/heads/master
| 2023-08-24T18:52:57.529281
| 2023-08-23T17:09:22
| 2023-08-23T17:09:22
| 43,038,779
| 742
| 120
|
BSD-2-Clause
| 2023-07-30T09:23:31
| 2015-09-24T02:03:58
|
C
|
UTF-8
|
C
| false
| false
| 176,799
|
c
|
njs_generator.c
|
/*
* Copyright (C) Igor Sysoev
* Copyright (C) Dmitry Volyntsev
* Copyright (C) Alexander Borisov
* Copyright (C) NGINX, Inc.
*/
#include <njs_main.h>
#define NJS_FUNCTION_MAX_DEPTH 128
typedef struct njs_generator_patch_s njs_generator_patch_t;
typedef enum {
NJS_GENERATOR_LOOP = 1,
NJS_GENERATOR_SWITCH = 2,
NJS_GENERATOR_BLOCK = 4,
NJS_GENERATOR_TRY = 8,
#define NJS_GENERATOR_ALL (NJS_GENERATOR_LOOP | NJS_GENERATOR_SWITCH)
} njs_generator_block_type_t;
typedef enum {
NJS_GENERATOR_CONTINUATION = 1,
NJS_GENERATOR_EXIT = 2,
} njs_generator_patch_type_t;
struct njs_generator_patch_s {
/*
* The jump_offset field points to jump offset field which contains a small
* adjustment and the adjustment should be added as (njs_jump_off_t *)
* because pointer to u_char accesses only one byte so this does not
* work on big endian platforms.
*/
njs_jump_off_t jump_offset;
njs_generator_patch_t *next;
njs_str_t label;
};
struct njs_generator_block_s {
njs_generator_block_type_t type; /* 4 bits */
njs_str_t label;
/* list of "continue" instruction offsets to be patched. */
njs_generator_patch_t *continuation;
/*
* list of "return" from try-catch block and "break"
* instruction offsets to be patched.
*/
njs_generator_patch_t *exit;
njs_generator_block_t *next;
/* exit value index, used only for NJS_GENERATOR_TRY blocks. */
njs_index_t index;
};
typedef struct {
njs_generator_state_func_t state;
njs_queue_link_t link;
njs_parser_node_t *node;
void *context;
} njs_generator_stack_entry_t;
typedef struct {
njs_generator_patch_t *patch;
njs_generator_patch_t **last;
njs_vmcode_jump_t *jump;
njs_jump_off_t jump_offset;
njs_index_t index;
} njs_generator_switch_ctx_t;
typedef struct {
njs_jump_off_t jump_offset;
njs_jump_off_t loop_offset;
njs_vmcode_jump_t *jump;
njs_variable_t *var;
njs_index_t index;
njs_index_t index_next_value;
} njs_generator_loop_ctx_t;
typedef struct {
njs_index_t exception_index;
njs_jump_off_t try_offset;
njs_jump_off_t catch_offset;
njs_generator_block_t *try_block;
njs_generator_block_t *catch_block;
njs_str_t try_cont_label;
njs_str_t try_exit_label;
njs_str_t catch_cont_label;
njs_str_t catch_exit_label;
} njs_generator_try_ctx_t;
static u_char *njs_generate_reserve(njs_vm_t *vm, njs_generator_t *generator,
size_t size);
static njs_int_t njs_generate_code_map(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node, u_char *code);
static njs_int_t njs_generate_name(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node);
static njs_int_t njs_generate_variable(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node, njs_reference_type_t type,
njs_variable_t **retvar);
static njs_int_t njs_generate_var_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_var_statement_after(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_let(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node, njs_variable_t *var);
static njs_int_t njs_generate_if_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_if_statement_cond(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_if_statement_then(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_if_statement_else(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_cond_expression(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_cond_expression_handler(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_cond_expression_true(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_cond_expression_false(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_switch_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_switch_expression(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *swtch);
static njs_int_t njs_generate_switch_case(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *swtch);
static njs_int_t njs_generate_switch_case_after(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *branch);
static njs_int_t njs_generate_switch_case_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *branch);
static njs_int_t njs_generate_switch_default(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *branch);
static njs_int_t njs_generate_switch_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *swtch);
static njs_int_t njs_generate_while_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_while_condition(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_while_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_do_while_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_do_while_condition(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_do_while_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_for_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_for_init(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node);
static njs_int_t njs_generate_for_body(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node);
static njs_int_t njs_generate_for_update(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_for_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node);
static njs_int_t njs_generate_for_let_update(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_for_resolve_closure(njs_vm_t *vm,
njs_parser_node_t *node);
static njs_int_t njs_generate_for_in_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_for_in_set_prop_block(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_for_in_name_assign(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_for_in_object(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_for_in_object_wo_decl(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_for_in_object_left_hand_expr(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_for_in_body(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_for_in_body_wo_decl(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_for_in_body_left_hand_expr(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_start_block(njs_vm_t *vm,
njs_generator_t *generator, njs_generator_block_type_t type,
const njs_str_t *label);
static njs_generator_block_t *njs_generate_lookup_block(
njs_generator_block_t *block, uint32_t mask, const njs_str_t *label);
static njs_generator_block_t *njs_generate_find_block(njs_vm_t *vm,
njs_generator_block_t *block, uint32_t mask, const njs_str_t *label);
static void njs_generate_patch_block(njs_vm_t *vm, njs_generator_t *generator,
njs_generator_block_t *block, unsigned type);
static njs_generator_patch_t *njs_generate_make_continuation_patch(njs_vm_t *vm,
njs_generator_block_t *block, const njs_str_t *label,
njs_jump_off_t offset);
static njs_generator_patch_t *njs_generate_make_exit_patch(njs_vm_t *vm,
njs_generator_block_t *block, const njs_str_t *label,
njs_jump_off_t offset);
static void njs_generate_patch_block_exit(njs_vm_t *vm,
njs_generator_t *generator);
static const njs_str_t *njs_generate_jump_destination(njs_vm_t *vm,
njs_generator_block_t *block, const char *inst_type, uint32_t mask,
const njs_str_t *label1, const njs_str_t *label2);
static njs_int_t njs_generate_continue_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_break_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_debugger_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_block_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_block_statement_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_children(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node);
static njs_int_t njs_generate_stop_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_stop_statement_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_comma_expression(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_comma_expression_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_global_property_set(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node_dst,
njs_parser_node_t *node_src);
static njs_int_t njs_generate_assignment(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_assignment_name(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_assignment_prop(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_assignment_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_operation_assignment(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_operation_assignment_name(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_operation_assignment_prop(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_operation_assignment_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_object(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node);
static njs_int_t njs_generate_property_accessor(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_property_accessor_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_array(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node);
static njs_int_t njs_generate_function_expression(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_function(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node);
static njs_int_t njs_generate_regexp(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node);
static njs_int_t njs_generate_template_literal(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_template_literal_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_test_jump_expression(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_test_jump_expression_after(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_test_jump_expression_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_3addr_operation(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node, njs_bool_t swap);
static njs_int_t njs_generate_3addr_operation_name(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_3addr_operation_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_2addr_operation(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_2addr_operation_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_typeof_operation(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_typeof_operation_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_inc_dec_operation(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node, njs_bool_t post);
static njs_int_t njs_generate_inc_dec_operation_prop(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_function_declaration(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_function_scope(njs_vm_t *vm,
njs_generator_t *generator, njs_function_lambda_t *lambda,
njs_parser_node_t *node, const njs_str_t *name);
static njs_int_t njs_generate_scope_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static int64_t njs_generate_lambda_variables(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_return_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_return_statement_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_function_call(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_function_call_arguments(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_function_call_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_method_call(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_method_call_arguments(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_method_call_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_call(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node);
static njs_int_t njs_generate_move_arguments(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_try_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_try_left(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node);
static njs_int_t njs_generate_try_catch(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_try_finally(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_try_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node);
static njs_int_t njs_generate_throw_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_throw_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_import_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_export_statement(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_export_statement_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_await(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node);
static njs_int_t njs_generate_await_end(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_wo_dest(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_wo_dest_after(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_global_reference(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node, njs_bool_t exception);
static njs_int_t njs_generate_reference_error(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_index_t njs_generate_dest_index(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_index_t njs_generate_object_dest_index(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_index_t njs_generate_node_temp_index_get(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_index_t njs_generate_temp_index_get(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_children_indexes_release(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_node_index_release(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_node_index_release_pop(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node);
static njs_int_t njs_generate_index_release(njs_vm_t *vm,
njs_generator_t *generator, njs_index_t index);
#define njs_generate_code(generator, type, _code, _op, nargs, nd) \
do { \
_code = (type *) njs_generate_reserve(vm, generator, sizeof(type)); \
if (njs_slow_path(_code == NULL)) { \
return NJS_ERROR; \
} \
\
if (njs_generate_code_map(vm, generator, nd, (u_char *) _code) \
!= NJS_OK) \
{ \
return NJS_ERROR; \
} \
\
generator->code_end += sizeof(type); \
\
_code->code.operation = _op; \
_code->code.operands = 3 - nargs; \
} while (0)
#define njs_generate_code_jump(generator, _code, _offset) \
do { \
njs_generate_code(generator, njs_vmcode_jump_t, _code, \
NJS_VMCODE_JUMP, 0, NULL); \
_code->offset = _offset; \
} while (0)
#define njs_generate_code_move(generator, _code, _dst, _src, node) \
do { \
njs_generate_code(generator, njs_vmcode_move_t, _code, \
NJS_VMCODE_MOVE, 2, node); \
_code->dst = _dst; \
_code->src = _src; \
} while (0)
#define njs_code_offset(generator, code) \
((u_char *) code - generator->code_start)
#define njs_code_ptr(generator, type, offset) \
(type *) (generator->code_start + offset)
#define njs_code_jump_ptr(generator, offset) \
(njs_jump_off_t *) (generator->code_start + offset)
#define njs_code_offset_diff(generator, offset) \
((generator->code_end - generator->code_start) - offset)
#define njs_code_set_offset(generator, offset, target) \
*(njs_code_jump_ptr(generator, offset)) \
= njs_code_offset_diff(generator, target)
#define njs_code_set_jump_offset(generator, type, code_offset) \
*(njs_code_jump_ptr(generator, code_offset + offsetof(type, offset))) \
= njs_code_offset_diff(generator, code_offset)
#define njs_code_update_offset(generator, patch) \
*(njs_code_jump_ptr(generator, patch->jump_offset)) += \
njs_code_offset_diff(generator, patch->jump_offset)
#define njs_generate_syntax_error(vm, node, file, fmt, ...) \
njs_parser_node_error(vm, NJS_OBJ_TYPE_SYNTAX_ERROR, node, file, fmt, \
##__VA_ARGS__)
#ifdef NJS_DEBUG_GENERATOR
#define njs_debug_generator(vm, msg, ...) \
if (vm->options.generator_debug) \
njs_printf("GENERATOR " msg "\n", ##__VA_ARGS__)
#define njs_debug_generator_code(code) \
if (vm->options.generator_debug) \
njs_disassemble((u_char *) code, NULL, 1, NULL)
#else
#define njs_debug_generator(vm, msg, ...)
#define njs_debug_generator_code(code)
#endif
static const njs_str_t no_label = njs_str("");
static const njs_str_t return_label = njs_str("@return");
/* GCC and Clang complain about NULL argument passed to memcmp(). */
static const njs_str_t undef_label = { 0xffffffff, (u_char *) "" };
njs_int_t
njs_generator_init(njs_generator_t *generator, njs_str_t *file,
njs_int_t depth, njs_bool_t runtime)
{
njs_memzero(generator, sizeof(njs_generator_t));
njs_queue_init(&generator->stack);
generator->file = *file;
generator->depth = depth;
generator->runtime = runtime;
return NJS_OK;
}
njs_inline void
njs_generator_next(njs_generator_t *generator, njs_generator_state_func_t state,
njs_parser_node_t *node)
{
generator->state = state;
generator->node = node;
}
njs_inline njs_int_t
njs_generator_after(njs_vm_t *vm, njs_generator_t *generator,
njs_queue_link_t *link, njs_parser_node_t *node,
njs_generator_state_func_t state, void *ctx, size_t size)
{
njs_generator_stack_entry_t *entry;
entry = njs_mp_alloc(vm->mem_pool, sizeof(njs_generator_stack_entry_t));
if (njs_slow_path(entry == NULL)) {
return NJS_ERROR;
}
entry->state = state;
entry->node = node;
entry->context = ctx;
njs_queue_insert_before(link, &entry->link);
if (size > 0) {
entry->context = njs_mp_alloc(vm->mem_pool, size);
if (njs_slow_path(entry->context == NULL)) {
return NJS_ERROR;
}
memcpy(entry->context, ctx, size);
}
return NJS_OK;
}
njs_inline njs_int_t
njs_generator_stack_pop(njs_vm_t *vm, njs_generator_t *generator, void *ctx)
{
njs_queue_link_t *link;
njs_generator_stack_entry_t *entry;
entry = njs_queue_link_data(njs_queue_first(&generator->stack),
njs_generator_stack_entry_t, link);
link = njs_queue_first(&generator->stack);
njs_queue_remove(link);
if (ctx != NULL) {
njs_mp_free(vm->mem_pool, ctx);
}
generator->context = entry->context;
njs_generator_next(generator, entry->state, entry->node);
njs_mp_free(vm->mem_pool, entry);
return NJS_OK;
}
static njs_int_t
njs_generate(njs_vm_t *vm, njs_generator_t *generator, njs_parser_node_t *node)
{
if (node == NULL) {
return njs_generator_stack_pop(vm, generator, NULL);
}
switch (node->token_type) {
case NJS_TOKEN_VAR:
case NJS_TOKEN_LET:
case NJS_TOKEN_CONST:
return njs_generate_var_statement(vm, generator, node);
case NJS_TOKEN_IF:
return njs_generate_if_statement(vm, generator, node);
case NJS_TOKEN_CONDITIONAL:
return njs_generate_cond_expression(vm, generator, node);
case NJS_TOKEN_SWITCH:
return njs_generate_switch_statement(vm, generator, node);
case NJS_TOKEN_WHILE:
return njs_generate_while_statement(vm, generator, node);
case NJS_TOKEN_DO:
return njs_generate_do_while_statement(vm, generator, node);
case NJS_TOKEN_FOR:
return njs_generate_for_statement(vm, generator, node);
case NJS_TOKEN_FOR_IN:
return njs_generate_for_in_statement(vm, generator, node);
case NJS_TOKEN_CONTINUE:
return njs_generate_continue_statement(vm, generator, node);
case NJS_TOKEN_BREAK:
return njs_generate_break_statement(vm, generator, node);
case NJS_TOKEN_DEBUGGER:
return njs_generate_debugger_statement(vm, generator, node);
case NJS_TOKEN_STATEMENT:
return njs_generate_statement(vm, generator, node);
case NJS_TOKEN_BLOCK:
return njs_generate_block_statement(vm, generator, node);
case NJS_TOKEN_END:
return njs_generate_stop_statement(vm, generator, node);
case NJS_TOKEN_COMMA:
return njs_generate_comma_expression(vm, generator, node);
case NJS_TOKEN_ASSIGNMENT:
return njs_generate_assignment(vm, generator, node);
case NJS_TOKEN_BITWISE_OR_ASSIGNMENT:
case NJS_TOKEN_BITWISE_XOR_ASSIGNMENT:
case NJS_TOKEN_BITWISE_AND_ASSIGNMENT:
case NJS_TOKEN_LEFT_SHIFT_ASSIGNMENT:
case NJS_TOKEN_RIGHT_SHIFT_ASSIGNMENT:
case NJS_TOKEN_UNSIGNED_RIGHT_SHIFT_ASSIGNMENT:
case NJS_TOKEN_ADDITION_ASSIGNMENT:
case NJS_TOKEN_SUBTRACTION_ASSIGNMENT:
case NJS_TOKEN_MULTIPLICATION_ASSIGNMENT:
case NJS_TOKEN_EXPONENTIATION_ASSIGNMENT:
case NJS_TOKEN_DIVISION_ASSIGNMENT:
case NJS_TOKEN_REMAINDER_ASSIGNMENT:
return njs_generate_operation_assignment(vm, generator, node);
case NJS_TOKEN_BITWISE_OR:
case NJS_TOKEN_BITWISE_XOR:
case NJS_TOKEN_BITWISE_AND:
case NJS_TOKEN_EQUAL:
case NJS_TOKEN_NOT_EQUAL:
case NJS_TOKEN_STRICT_EQUAL:
case NJS_TOKEN_STRICT_NOT_EQUAL:
case NJS_TOKEN_INSTANCEOF:
case NJS_TOKEN_LESS:
case NJS_TOKEN_LESS_OR_EQUAL:
case NJS_TOKEN_GREATER:
case NJS_TOKEN_GREATER_OR_EQUAL:
case NJS_TOKEN_LEFT_SHIFT:
case NJS_TOKEN_RIGHT_SHIFT:
case NJS_TOKEN_UNSIGNED_RIGHT_SHIFT:
case NJS_TOKEN_ADDITION:
case NJS_TOKEN_SUBTRACTION:
case NJS_TOKEN_MULTIPLICATION:
case NJS_TOKEN_EXPONENTIATION:
case NJS_TOKEN_DIVISION:
case NJS_TOKEN_REMAINDER:
case NJS_TOKEN_PROPERTY_DELETE:
case NJS_TOKEN_PROPERTY:
return njs_generate_3addr_operation(vm, generator, node, 0);
case NJS_TOKEN_IN:
/*
* An "in" operation is parsed as standard binary expression
* by njs_parser_binary_expression(). However, its operands
* should be swapped to be uniform with other property operations
* (get/set and delete) to use the property trap.
*/
return njs_generate_3addr_operation(vm, generator, node, 1);
case NJS_TOKEN_LOGICAL_AND:
case NJS_TOKEN_LOGICAL_OR:
case NJS_TOKEN_COALESCE:
return njs_generate_test_jump_expression(vm, generator, node);
case NJS_TOKEN_DELETE:
case NJS_TOKEN_VOID:
case NJS_TOKEN_UNARY_PLUS:
case NJS_TOKEN_UNARY_NEGATION:
case NJS_TOKEN_LOGICAL_NOT:
case NJS_TOKEN_BITWISE_NOT:
return njs_generate_2addr_operation(vm, generator, node);
case NJS_TOKEN_TYPEOF:
return njs_generate_typeof_operation(vm, generator, node);
case NJS_TOKEN_INCREMENT:
case NJS_TOKEN_DECREMENT:
return njs_generate_inc_dec_operation(vm, generator, node, 0);
case NJS_TOKEN_POST_INCREMENT:
case NJS_TOKEN_POST_DECREMENT:
return njs_generate_inc_dec_operation(vm, generator, node, 1);
case NJS_TOKEN_NULL:
case NJS_TOKEN_TRUE:
case NJS_TOKEN_FALSE:
case NJS_TOKEN_NUMBER:
case NJS_TOKEN_STRING:
node->index = njs_scope_global_index(vm, &node->u.value,
generator->runtime);
if (njs_slow_path(node->index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
return njs_generator_stack_pop(vm, generator, NULL);
case NJS_TOKEN_OBJECT_VALUE:
node->index = node->u.object->index;
return njs_generator_stack_pop(vm, generator, NULL);
case NJS_TOKEN_OBJECT:
return njs_generate_object(vm, generator, node);
case NJS_TOKEN_PROPERTY_GETTER:
case NJS_TOKEN_PROPERTY_SETTER:
return njs_generate_property_accessor(vm, generator, node);
case NJS_TOKEN_ARRAY:
return njs_generate_array(vm, generator, node);
case NJS_TOKEN_FUNCTION_EXPRESSION:
case NJS_TOKEN_ASYNC_FUNCTION_EXPRESSION:
return njs_generate_function_expression(vm, generator, node);
case NJS_TOKEN_FUNCTION:
case NJS_TOKEN_ASYNC_FUNCTION:
return njs_generate_function(vm, generator, node);
case NJS_TOKEN_REGEXP:
return njs_generate_regexp(vm, generator, node);
case NJS_TOKEN_TEMPLATE_LITERAL:
return njs_generate_template_literal(vm, generator, node);
case NJS_TOKEN_EXTERNAL:
return njs_generator_stack_pop(vm, generator, NULL);
case NJS_TOKEN_NAME:
case NJS_TOKEN_ARGUMENTS:
case NJS_TOKEN_EVAL:
case NJS_TOKEN_THIS:
return njs_generate_name(vm, generator, node);
case NJS_TOKEN_FUNCTION_DECLARATION:
case NJS_TOKEN_ASYNC_FUNCTION_DECLARATION:
return njs_generate_function_declaration(vm, generator, node);
case NJS_TOKEN_FUNCTION_CALL:
return njs_generate_function_call(vm, generator, node);
case NJS_TOKEN_RETURN:
return njs_generate_return_statement(vm, generator, node);
case NJS_TOKEN_METHOD_CALL:
return njs_generate_method_call(vm, generator, node);
case NJS_TOKEN_TRY:
return njs_generate_try_statement(vm, generator, node);
case NJS_TOKEN_THROW:
return njs_generate_throw_statement(vm, generator, node);
case NJS_TOKEN_IMPORT:
return njs_generate_import_statement(vm, generator, node);
case NJS_TOKEN_EXPORT:
return njs_generate_export_statement(vm, generator, node);
case NJS_TOKEN_AWAIT:
return njs_generate_await(vm, generator, node);
default:
njs_internal_error(vm, "Generator failed: unknown token");
return NJS_ERROR;
}
}
static njs_int_t
njs_generator_pop(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
return njs_generator_stack_pop(vm, generator, NULL);
}
static u_char *
njs_generate_reserve(njs_vm_t *vm, njs_generator_t *generator, size_t size)
{
u_char *p;
if (generator->code_end + size <=
generator->code_start + generator->code_size)
{
return generator->code_end;
}
size = njs_max(generator->code_end - generator->code_start + size,
generator->code_size);
if (size < 1024) {
size *= 2;
} else {
size += size / 2;
}
p = njs_mp_alloc(vm->mem_pool, size);
if (njs_slow_path(p == NULL)) {
njs_memory_error(vm);
return NULL;
}
generator->code_size = size;
size = generator->code_end - generator->code_start;
memcpy(p, generator->code_start, size);
njs_mp_free(vm->mem_pool, generator->code_start);
generator->code_start = p;
generator->code_end = p + size;
return generator->code_end;
}
static njs_int_t
njs_generate_code_map(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node, u_char *code)
{
njs_arr_t *map;
njs_vm_line_num_t *last;
map = generator->lines;
if (map != NULL && node != NULL) {
last = (map->items != 0) ? njs_arr_last(map) : NULL;
if (last == NULL || (node->token_line != last->line)) {
last = njs_arr_add(map);
if (njs_slow_path(last == NULL)) {
return NJS_ERROR;
}
last->line = node->token_line;
last->offset = njs_code_offset(generator, code);
}
}
return NJS_OK;
}
njs_vm_code_t *
njs_lookup_code(njs_vm_t *vm, u_char *pc)
{
njs_uint_t i;
njs_vm_code_t *code;
code = vm->codes->start;
for (i = 0; i < vm->codes->items; i++, code++) {
if (code->start <= pc && pc < code->end) {
return code;
}
}
return NULL;
}
uint32_t
njs_lookup_line(njs_arr_t *lines, uint32_t offset)
{
njs_uint_t n;
njs_vm_line_num_t *map;
n = 0;
map = NULL;
if (lines != NULL) {
n = lines->items;
map = (njs_vm_line_num_t *) lines->start;
}
while (n != 0) {
if (offset >= map->offset && (n == 1 || offset < map[1].offset)) {
return map->line;
}
map++;
n--;
}
return 0;
}
static njs_int_t
njs_generate_name(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_variable_t *var;
njs_parser_scope_t *scope;
njs_vmcode_variable_t *variable;
njs_vmcode_function_copy_t *copy;
var = njs_variable_reference(vm, node);
if (njs_slow_path(var == NULL)) {
ret = njs_generate_global_reference(vm, generator, node, 1);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, NULL);
}
if (var->function && var->type == NJS_VARIABLE_FUNCTION) {
njs_generate_code(generator, njs_vmcode_function_copy_t, copy,
NJS_VMCODE_FUNCTION_COPY, 0, node);
copy->function = &var->value;
copy->retval = node->index;
}
if (var->init) {
return njs_generator_stack_pop(vm, generator, NULL);
}
if (var->type == NJS_VARIABLE_LET || var->type == NJS_VARIABLE_CONST) {
scope = njs_function_scope(node->scope);
if (scope->dest_disable) {
njs_generate_code(generator, njs_vmcode_variable_t, variable,
NJS_VMCODE_NOT_INITIALIZED, 1, node);
variable->dst = node->index;
}
}
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_variable(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node, njs_reference_type_t type, njs_variable_t **retvar)
{
njs_variable_t *var;
njs_parser_scope_t *scope;
njs_vmcode_variable_t *variable;
njs_vmcode_function_copy_t *copy;
var = njs_variable_reference(vm, node);
if (retvar != NULL) {
*retvar = var;
}
if (njs_slow_path(var == NULL)) {
switch (type) {
case NJS_DECLARATION:
return njs_generate_reference_error(vm, generator, node);
case NJS_REFERENCE:
case NJS_TYPEOF:
return njs_generate_global_reference(vm, generator, node,
type == NJS_REFERENCE);
}
}
if (var->function && var->type == NJS_VARIABLE_FUNCTION) {
njs_generate_code(generator, njs_vmcode_function_copy_t, copy,
NJS_VMCODE_FUNCTION_COPY, 0, node);
copy->function = &var->value;
copy->retval = node->index;
}
if (var->init) {
return NJS_OK;
}
if (var->type == NJS_VARIABLE_LET || var->type == NJS_VARIABLE_CONST) {
scope = njs_function_scope(node->scope);
if ((!scope->dest_disable && njs_function_scope(var->scope) == scope)) {
njs_generate_code(generator, njs_vmcode_variable_t, variable,
NJS_VMCODE_NOT_INITIALIZED, 1, node);
variable->dst = node->index;
}
}
return NJS_OK;
}
static njs_int_t
njs_generate_variable_wo_dest(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node, njs_reference_type_t type, njs_variable_t **retvar)
{
njs_int_t ret;
njs_parser_scope_t *scope;
scope = njs_function_scope(node->scope);
scope->dest_disable = 1;
ret = njs_generate_variable(vm, generator, node, type, retvar);
scope->dest_disable = 0;
return ret;
}
static njs_int_t
njs_generate_var_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_variable_t *var;
njs_parser_node_t *lvalue, *expr;
lvalue = node->left;
ret = njs_generate_variable_wo_dest(vm, generator, lvalue,
NJS_DECLARATION, &var);
if (njs_slow_path(ret != NJS_OK)) {
return NJS_ERROR;
}
expr = node->right;
if (expr == NULL) {
/* Variable is only declared. */
if (var->type == NJS_VARIABLE_CONST) {
njs_syntax_error(vm, "missing initializer in const declaration");
return NJS_ERROR;
}
if (var->type == NJS_VARIABLE_LET) {
ret = njs_generate_let(vm, generator, node, var);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
}
var->init = 1;
return njs_generator_stack_pop(vm, generator, NULL);
}
if (var->type == NJS_VARIABLE_LET || var->type == NJS_VARIABLE_CONST) {
ret = njs_generate_wo_dest(vm, generator, expr);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
} else {
expr->dest = lvalue;
njs_generator_next(generator, njs_generate, expr);
}
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_var_statement_after, var, 0);
}
static njs_int_t
njs_generate_var_statement_after(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
ssize_t length;
njs_int_t ret;
njs_variable_t *var;
njs_parser_node_t *lvalue, *expr;
njs_vmcode_move_t *move;
const njs_lexer_entry_t *lex_entry;
lvalue = node->left;
expr = node->right;
var = generator->context;
if (var->type == NJS_VARIABLE_LET || var->type == NJS_VARIABLE_CONST) {
ret = njs_generate_let(vm, generator, node, var);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
}
var->init = 1;
/*
* lvalue and expression indexes are equal if the expression is an
* empty object or expression result is stored directly in variable.
*/
if (lvalue->index != expr->index) {
njs_generate_code_move(generator, move, lvalue->index, expr->index,
lvalue);
}
node->index = expr->index;
node->temporary = expr->temporary;
if ((expr->token_type == NJS_TOKEN_FUNCTION_EXPRESSION
|| expr->token_type == NJS_TOKEN_ASYNC_FUNCTION_EXPRESSION)
&& njs_values_same(&expr->u.value.data.u.lambda->name,
&njs_string_empty))
{
lex_entry = njs_lexer_entry(node->left->u.reference.unique_id);
if (njs_slow_path(lex_entry == NULL)) {
return NJS_ERROR;
}
length = njs_utf8_length(lex_entry->name.start, lex_entry->name.length);
if (njs_slow_path(length < 0)) {
return NJS_ERROR;
}
ret = njs_string_new(vm, &expr->u.value.data.u.lambda->name,
lex_entry->name.start, lex_entry->name.length,
length);
if (njs_slow_path(ret != NJS_OK)) {
return NJS_ERROR;
}
}
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_let(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node, njs_variable_t *var)
{
njs_vmcode_variable_t *code;
njs_generate_code(generator, njs_vmcode_variable_t, code,
NJS_VMCODE_LET, 0, node);
code->dst = var->index;
return NJS_OK;
}
static njs_int_t
njs_generate_if_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
ret = njs_generate_start_block(vm, generator, NJS_GENERATOR_BLOCK,
&node->name);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
/* The condition expression. */
njs_generator_next(generator, njs_generate, node->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_if_statement_cond, NULL, 0);
}
static njs_int_t
njs_generate_if_statement_cond(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_jump_off_t jump_offset;
njs_vmcode_cond_jump_t *cond_jump;
njs_generate_code(generator, njs_vmcode_cond_jump_t, cond_jump,
NJS_VMCODE_IF_FALSE_JUMP, 2, node);
cond_jump->cond = node->left->index;
ret = njs_generate_node_index_release(vm, generator, node->left);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
jump_offset = njs_code_offset(generator, cond_jump);
if (node->right != NULL && node->right->token_type == NJS_TOKEN_BRANCHING) {
/* The "then" branch in a case of "if/then/else" statement. */
node = node->right;
njs_generator_next(generator, njs_generate, node->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_if_statement_then,
&jump_offset, sizeof(njs_jump_off_t));
}
/*
* The "then" branch in a case of "if/then" statement
* or the "else" branch in a case of "if/then/else" statement.
*/
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_if_statement_else,
&jump_offset, sizeof(njs_jump_off_t));
}
static njs_int_t
njs_generate_if_statement_then(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_jump_off_t *jump_offset, label_offset;
njs_vmcode_jump_t *jump;
ret = njs_generate_node_index_release(vm, generator, node->left);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
jump_offset = (njs_jump_off_t *) generator->context;
label_offset = *jump_offset + offsetof(njs_vmcode_cond_jump_t, offset);
njs_generate_code_jump(generator, jump, 0);
njs_code_set_offset(generator, label_offset, *jump_offset);
*jump_offset = njs_code_offset(generator, jump);
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_if_statement_else,
jump_offset, 0);
}
static njs_int_t
njs_generate_if_statement_else(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_jump_off_t *jump_offset, label_offset;
jump_offset = (njs_jump_off_t *) generator->context;
label_offset = *jump_offset + offsetof(njs_vmcode_cond_jump_t, offset);
ret = njs_generate_node_index_release(vm, generator, node->right);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
njs_code_set_offset(generator, label_offset, *jump_offset);
njs_generate_patch_block_exit(vm, generator);
return njs_generator_stack_pop(vm, generator, generator->context);
}
static njs_int_t
njs_generate_cond_expression(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_generator_next(generator, njs_generate, node->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_cond_expression_handler, NULL, 0);
}
static njs_int_t
njs_generate_cond_expression_handler(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_jump_off_t jump_offset;
njs_vmcode_cond_jump_t *cond_jump;
njs_generate_code(generator, njs_vmcode_cond_jump_t, cond_jump,
NJS_VMCODE_IF_FALSE_JUMP, 2, node);
jump_offset = njs_code_offset(generator, cond_jump);
cond_jump->cond = node->left->index;
node->index = njs_generate_dest_index(vm, generator, node);
if (njs_slow_path(node->index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generator_next(generator, njs_generate, node->right->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_cond_expression_true,
&jump_offset, sizeof(njs_jump_off_t));
}
static njs_int_t
njs_generate_cond_expression_true(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_jump_off_t jump_offset;
njs_parser_node_t *branch;
njs_vmcode_move_t *move;
njs_vmcode_jump_t *jump;
branch = node->right;
/*
* Branches usually uses node->index as destination, however,
* if branch expression is a literal, variable or assignment,
* then a MOVE operation is required.
*/
if (node->index != branch->left->index) {
njs_generate_code_move(generator, move, node->index,
branch->left->index, node);
}
ret = njs_generate_node_index_release(vm, generator, branch->left);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
njs_generate_code_jump(generator, jump, 0);
jump_offset = njs_code_offset(generator, jump);
njs_code_set_jump_offset(generator, njs_vmcode_cond_jump_t,
*((njs_jump_off_t *) generator->context));
njs_generator_next(generator, njs_generate, branch->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_cond_expression_false,
&jump_offset, sizeof(njs_jump_off_t));
}
static njs_int_t
njs_generate_cond_expression_false(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_parser_node_t *branch;
njs_vmcode_move_t *move;
branch = node->right;
if (node->index != branch->right->index) {
njs_generate_code_move(generator, move, node->index,
branch->right->index, node);
}
njs_code_set_jump_offset(generator, njs_vmcode_cond_jump_t,
*((njs_jump_off_t *) generator->context));
ret = njs_generate_node_index_release(vm, generator, branch->right);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, generator->context);
}
static njs_int_t
njs_generate_switch_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *swtch)
{
njs_generator_switch_ctx_t ctx;
/* The "switch" expression. */
njs_generator_next(generator, njs_generate, swtch->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), swtch,
njs_generate_switch_expression,
&ctx, sizeof(njs_generator_switch_ctx_t));
}
static njs_int_t
njs_generate_switch_expression(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *swtch)
{
njs_int_t ret;
njs_parser_node_t *expr;
njs_vmcode_move_t *move;
njs_generator_switch_ctx_t *ctx;
ctx = generator->context;
expr = swtch->left;
ctx->index = expr->index;
if (!expr->temporary) {
ctx->index = njs_generate_temp_index_get(vm, generator, swtch);
if (njs_slow_path(ctx->index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generate_code_move(generator, move, ctx->index, expr->index, swtch);
}
ret = njs_generate_start_block(vm, generator, NJS_GENERATOR_SWITCH,
&swtch->name);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
ctx->patch = NULL;
ctx->last = &ctx->patch;
if (swtch->right != NULL) {
/* The "case" expression. */
njs_generator_next(generator, njs_generate_switch_case, swtch->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), swtch,
njs_generate_switch_case_end, ctx, 0);
}
return njs_generate_switch_case_end(vm, generator, swtch);
}
static njs_int_t
njs_generate_switch_case(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *branch)
{
if (branch->token_type == NJS_TOKEN_DEFAULT) {
if (branch->left == NULL) {
return njs_generator_stack_pop(vm, generator, NULL);
}
branch = branch->left;
}
njs_generator_next(generator, njs_generate, branch->right->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), branch,
njs_generate_switch_case_after,
generator->context, 0);
}
static njs_int_t
njs_generate_switch_case_after(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *branch)
{
njs_int_t ret;
njs_parser_node_t *node;
njs_generator_patch_t *patch;
njs_vmcode_equal_jump_t *equal;
njs_generator_switch_ctx_t *ctx;
ctx = generator->context;
node = branch->right;
njs_generate_code(generator, njs_vmcode_equal_jump_t, equal,
NJS_VMCODE_IF_EQUAL_JUMP, 3, branch);
equal->offset = offsetof(njs_vmcode_equal_jump_t, offset);
equal->value1 = ctx->index;
equal->value2 = node->left->index;
ret = njs_generate_node_index_release(vm, generator, node->left);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
patch = njs_mp_alloc(vm->mem_pool, sizeof(njs_generator_patch_t));
if (njs_slow_path(patch == NULL)) {
return NJS_ERROR;
}
patch->jump_offset = njs_code_offset(generator, equal)
+ offsetof(njs_vmcode_equal_jump_t, offset);
patch->label = no_label;
*ctx->last = patch;
ctx->last = &patch->next;
if (branch->left == NULL) {
return njs_generator_stack_pop(vm, generator, NULL);
}
branch = branch->left;
if (branch->token_type == NJS_TOKEN_DEFAULT) {
branch = branch->left;
if (branch == NULL) {
return njs_generator_stack_pop(vm, generator, NULL);
}
}
njs_generator_next(generator, njs_generate, branch->right->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), branch,
njs_generate_switch_case_after, ctx, 0);
}
static njs_int_t
njs_generate_switch_case_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *swtch)
{
njs_int_t ret;
njs_parser_node_t *branch;
njs_generator_switch_ctx_t *ctx;
ctx = generator->context;
/* Release either temporary index or temporary expr->index. */
ret = njs_generate_index_release(vm, generator, ctx->index);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
njs_generate_code_jump(generator, ctx->jump,
offsetof(njs_vmcode_jump_t, offset));
ctx->jump_offset = njs_code_offset(generator, ctx->jump);
branch = swtch->right;
if (branch != NULL) {
njs_generator_next(generator, njs_generate_switch_default, branch);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), swtch,
njs_generate_switch_end, ctx, 0);
}
return njs_generate_switch_end(vm, generator, swtch);
}
static njs_int_t
njs_generate_switch_default(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *branch)
{
njs_parser_node_t *node;
njs_generator_patch_t *next;
njs_generator_switch_ctx_t *ctx;
ctx = generator->context;
if (branch->token_type == NJS_TOKEN_DEFAULT) {
njs_code_set_jump_offset(generator, njs_vmcode_jump_t,
ctx->jump_offset);
ctx->jump = NULL;
node = branch;
} else {
njs_code_update_offset(generator, ctx->patch);
next = ctx->patch->next;
njs_mp_free(vm->mem_pool, ctx->patch);
ctx->patch = next;
node = branch->right;
}
njs_generator_next(generator, njs_generate, node->right);
branch = branch->left;
if (branch == NULL) {
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), branch,
njs_generator_pop, NULL, 0);
}
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), branch,
njs_generate_switch_default, ctx, 0);
}
static njs_int_t
njs_generate_switch_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *swtch)
{
njs_generator_switch_ctx_t *ctx;
ctx = generator->context;
if (ctx->jump != NULL) {
/* A "switch" without default case. */
njs_code_set_jump_offset(generator, njs_vmcode_jump_t,
ctx->jump_offset);
}
/* Patch "break" statements offsets. */
njs_generate_patch_block_exit(vm, generator);
return njs_generator_stack_pop(vm, generator, ctx);
}
static njs_int_t
njs_generate_while_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_vmcode_jump_t *jump;
njs_generator_loop_ctx_t ctx;
/*
* Set a jump to the loop condition. This jump is executed once just on
* the loop enter and eliminates execution of one additional jump inside
* the loop per each iteration.
*/
njs_generate_code_jump(generator, jump, 0);
ctx.jump_offset = njs_code_offset(generator, jump);
ret = njs_generate_start_block(vm, generator, NJS_GENERATOR_LOOP,
&node->name);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
ctx.loop_offset = njs_code_offset(generator, generator->code_end);
njs_generator_next(generator, njs_generate, node->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_while_condition,
&ctx, sizeof(njs_generator_loop_ctx_t));
}
static njs_int_t
njs_generate_while_condition(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_generator_loop_ctx_t *ctx;
ctx = generator->context;
njs_generate_patch_block(vm, generator, generator->block,
NJS_GENERATOR_CONTINUATION);
njs_code_set_jump_offset(generator, njs_vmcode_jump_t, ctx->jump_offset);
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_while_end, ctx, 0);
}
static njs_int_t
njs_generate_while_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_vmcode_cond_jump_t *cond_jump;
njs_generator_loop_ctx_t *ctx;
ctx = generator->context;
njs_generate_code(generator, njs_vmcode_cond_jump_t, cond_jump,
NJS_VMCODE_IF_TRUE_JUMP, 2, node->right);
cond_jump->offset = ctx->loop_offset - njs_code_offset(generator,
cond_jump);
cond_jump->cond = node->right->index;
njs_generate_patch_block_exit(vm, generator);
ret = njs_generate_node_index_release(vm, generator, node->right);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, ctx);
}
static njs_int_t
njs_generate_do_while_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_generator_loop_ctx_t ctx;
ret = njs_generate_start_block(vm, generator, NJS_GENERATOR_LOOP,
&node->name);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
ctx.loop_offset = njs_code_offset(generator, generator->code_end);
njs_generator_next(generator, njs_generate, node->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_do_while_condition,
&ctx, sizeof(njs_generator_loop_ctx_t));
}
static njs_int_t
njs_generate_do_while_condition(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_generate_patch_block(vm, generator, generator->block,
NJS_GENERATOR_CONTINUATION);
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_do_while_end,
generator->context, 0);
}
static njs_int_t
njs_generate_do_while_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_vmcode_cond_jump_t *cond_jump;
njs_generator_loop_ctx_t *ctx;
ctx = generator->context;
njs_generate_code(generator, njs_vmcode_cond_jump_t, cond_jump,
NJS_VMCODE_IF_TRUE_JUMP, 2, node->right);
cond_jump->offset = ctx->loop_offset
- njs_code_offset(generator, cond_jump);
cond_jump->cond = node->right->index;
njs_generate_patch_block_exit(vm, generator);
ret = njs_generate_node_index_release(vm, generator, node->right);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, ctx);
}
static njs_int_t
njs_generate_for_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_generator_loop_ctx_t ctx;
ret = njs_generate_start_block(vm, generator, NJS_GENERATOR_LOOP,
&node->name);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
ctx.jump = NULL;
njs_generator_next(generator, njs_generate, node->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_for_init,
&ctx, sizeof(njs_generator_loop_ctx_t));
}
static njs_int_t
njs_generate_for_init(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_parser_node_t *condition;
njs_generator_loop_ctx_t *ctx;
ctx = generator->context;
ret = njs_generate_node_index_release(vm, generator, node->left);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
condition = node->right->left;
/*
* Closures can occur in conditional and loop updates. This must be
* foreseen in order to generate optimized code for let updates.
*/
ret = njs_generate_for_resolve_closure(vm, condition);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
ctx->jump_offset = 0;
if (condition != NULL) {
/*
* The loop condition presents so set a jump to it. This jump is
* executed once just after the loop initialization and eliminates
* execution of one additional jump inside the loop per each iteration.
*/
njs_generate_code_jump(generator, ctx->jump, 0);
ctx->jump_offset = njs_code_offset(generator, ctx->jump);
}
/* The loop body. */
ctx->loop_offset = njs_code_offset(generator, generator->code_end);
njs_generator_next(generator, njs_generate, node->right->right->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_for_body, ctx, 0);
}
static njs_int_t
njs_generate_for_body(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_parser_node_t *update, *init;
njs_generator_loop_ctx_t *ctx;
ctx = generator->context;
/* The loop update. */
init = node->left;
update = node->right->right->right;
ret = njs_generate_for_resolve_closure(vm, update);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
ret = njs_generate_for_let_update(vm, generator, init);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
njs_generate_patch_block(vm, generator, generator->block,
NJS_GENERATOR_CONTINUATION);
njs_generator_next(generator, njs_generate, update);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_for_update, ctx, 0);
}
static njs_int_t
njs_generate_for_update(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_parser_node_t *condition, *update;
njs_generator_loop_ctx_t *ctx;
ctx = generator->context;
update = node->right->right->right;
condition = node->right->left;
ret = njs_generate_node_index_release(vm, generator, update);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
/* The loop condition. */
if (condition != NULL) {
njs_code_set_jump_offset(generator, njs_vmcode_jump_t,
ctx->jump_offset);
njs_generator_next(generator, njs_generate, condition);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_for_end, ctx, 0);
}
return njs_generate_for_end(vm, generator, node);
}
static njs_int_t
njs_generate_for_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_parser_node_t *condition;
njs_vmcode_cond_jump_t *cond_jump;
njs_generator_loop_ctx_t *ctx;
ctx = generator->context;
condition = node->right->left;
if (condition != NULL) {
njs_generate_code(generator, njs_vmcode_cond_jump_t, cond_jump,
NJS_VMCODE_IF_TRUE_JUMP, 2, condition);
cond_jump->offset = ctx->loop_offset
- njs_code_offset(generator, cond_jump);
cond_jump->cond = condition->index;
njs_generate_patch_block_exit(vm, generator);
ret = njs_generate_node_index_release(vm, generator, condition);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, ctx);
}
njs_generate_code_jump(generator, ctx->jump,
ctx->loop_offset - njs_code_offset(generator,
ctx->jump));
njs_generate_patch_block_exit(vm, generator);
return njs_generator_stack_pop(vm, generator, ctx);
}
static njs_int_t
njs_generate_for_let_update(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_parser_node_t *let;
njs_vmcode_variable_t *code_var;
njs_variable_reference_t *ref;
while (node != NULL && node->token_type == NJS_TOKEN_STATEMENT) {
let = node->right;
if (let->token_type != NJS_TOKEN_LET
&& let->token_type != NJS_TOKEN_CONST)
{
return NJS_OK;
}
ref = &let->left->u.reference;
if (ref->variable->closure) {
njs_generate_code(generator, njs_vmcode_variable_t, code_var,
NJS_VMCODE_LET_UPDATE, 0, let);
code_var->dst = let->left->index;
}
node = node->left;
}
return NJS_OK;
}
static njs_int_t
njs_generate_for_resolve_closure_cb(njs_vm_t *vm, njs_parser_node_t *node,
void *unused)
{
njs_bool_t closure;
njs_variable_t *var;
if (node->token_type == NJS_TOKEN_NAME) {
var = njs_variable_resolve(vm, node);
if (njs_fast_path(var != NULL)) {
closure = njs_variable_closure_test(node->scope, var->scope);
if (closure) {
var->closure = 1;
}
}
}
return NJS_OK;
}
static njs_int_t
njs_generate_for_resolve_closure(njs_vm_t *vm, njs_parser_node_t *node)
{
return njs_parser_traverse(vm, node, NULL,
njs_generate_for_resolve_closure_cb);
}
static njs_int_t
njs_generate_for_in_name_assign(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_variable_t *var;
njs_parser_node_t *foreach, *lvalue, *expr;
njs_vmcode_move_t *move;
njs_generator_loop_ctx_t *ctx;
ctx = generator->context;
foreach = node->left;
lvalue = foreach->left;
expr = node->right;
var = njs_variable_reference(vm, lvalue);
if (var != NULL) {
ctx->index_next_value = lvalue->index;
} else {
ctx->index_next_value = njs_generate_temp_index_get(vm, generator,
foreach->left);
if (njs_slow_path(ctx->index_next_value == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
if (expr != NULL) {
expr->index = ctx->index_next_value;
/*
* lvalue and expression indexes are equal if the expression is an
* empty object or expression result is stored directly in variable.
*/
if (lvalue->index != expr->index) {
njs_generate_code_move(generator, move, lvalue->index,
expr->index, expr);
}
ret = njs_generate_global_property_set(vm, generator, foreach->left,
expr);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
}
}
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_for_in_body_wo_decl(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_jump_off_t prop_offset;
njs_parser_node_t *foreach, *name;
njs_vmcode_prop_next_t *prop_next;
njs_generator_loop_ctx_t *ctx;
ctx = generator->context;
foreach = node->left;
name = foreach->left->right;
/* The loop iterator. */
if (name != NULL) {
ret = njs_generate_for_let_update(vm, generator, foreach->left);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
}
njs_generate_patch_block(vm, generator, generator->block,
NJS_GENERATOR_CONTINUATION);
njs_code_set_jump_offset(generator, njs_vmcode_prop_foreach_t,
ctx->jump_offset);
njs_generate_code(generator, njs_vmcode_prop_next_t, prop_next,
NJS_VMCODE_PROPERTY_NEXT, 3, node->left->left);
prop_offset = njs_code_offset(generator, prop_next);
prop_next->retval = ctx->index_next_value;
prop_next->object = foreach->right->index;
prop_next->next = ctx->index;
prop_next->offset = ctx->loop_offset - prop_offset;
njs_generate_patch_block_exit(vm, generator);
/*
* Release object and iterator indexes: an object can be a function result
* or a property of another object and an iterator can be given with "let".
*/
ret = njs_generate_children_indexes_release(vm, generator, foreach);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
ret = njs_generate_index_release(vm, generator, ctx->index);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, ctx);
}
static njs_int_t
njs_generate_for_in_object_wo_decl(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_parser_node_t *foreach, *name;
njs_generator_loop_ctx_t *ctx;
njs_vmcode_prop_foreach_t *prop_foreach;
ctx = generator->context;
foreach = node->left;
name = foreach->left->right;
if (name != NULL) {
ctx->var->init = 1;
}
njs_generate_code(generator, njs_vmcode_prop_foreach_t, prop_foreach,
NJS_VMCODE_PROPERTY_FOREACH, 2, foreach);
ctx->jump_offset = njs_code_offset(generator, prop_foreach);
prop_foreach->object = foreach->right->index;
ctx->index = njs_generate_temp_index_get(vm, generator, foreach->right);
if (njs_slow_path(ctx->index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
prop_foreach->next = ctx->index;
/* The loop body. */
ctx->loop_offset = njs_code_offset(generator, generator->code_end);
/* 1) left. */
njs_generator_next(generator, njs_generate, foreach->left);
/* 4) loop-body-end. */
ret = njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_for_in_body_wo_decl, ctx, 0);
if (ret != NJS_OK) {
return ret;
}
/* 3) loop-body. */
ret = njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node->right,
njs_generate, ctx, 0);
if (ret != NJS_OK) {
return ret;
}
/* 2) assign value to name. */
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_for_in_name_assign, ctx, 0);
}
static njs_int_t
njs_generate_for_in_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_parser_node_t *foreach, *name;
njs_generator_loop_ctx_t ctx;
ret = njs_generate_start_block(vm, generator, NJS_GENERATOR_LOOP,
&node->name);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
/* The object. */
foreach = node->left;
if (foreach->left->token_type != NJS_TOKEN_PROPERTY) {
name = foreach->left->right;
if (name != NULL) {
name = name->left;
ret = njs_generate_variable_wo_dest(vm, generator, name,
NJS_DECLARATION, &ctx.var);
if (njs_slow_path(ret != NJS_OK)) {
return NJS_ERROR;
}
foreach->left->index = name->index;
njs_generator_next(generator, njs_generate, foreach->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_for_in_object,
&ctx, sizeof(njs_generator_loop_ctx_t));
}
} else {
/* foreach->right is object in 'in object'. */
njs_generator_next(generator, njs_generate, foreach->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_for_in_object_left_hand_expr,
&ctx, sizeof(njs_generator_loop_ctx_t));
}
njs_generator_next(generator, njs_generate, foreach->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_for_in_object_wo_decl,
&ctx, sizeof(njs_generator_loop_ctx_t));
}
static njs_int_t
njs_generate_for_in_object_left_hand_expr(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node)
{
njs_int_t ret;
njs_parser_node_t *foreach;
njs_generator_loop_ctx_t *ctx;
njs_vmcode_prop_foreach_t *prop_foreach;
ctx = generator->context;
foreach = node->left;
njs_generate_code(generator, njs_vmcode_prop_foreach_t, prop_foreach,
NJS_VMCODE_PROPERTY_FOREACH, 2, foreach);
ctx->jump_offset = njs_code_offset(generator, prop_foreach);
prop_foreach->object = foreach->right->index;
ctx->index = njs_generate_temp_index_get(vm, generator, foreach->right);
if (njs_slow_path(ctx->index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
ctx->index_next_value = njs_generate_temp_index_get(vm, generator,
foreach->left);
if (njs_slow_path(ctx->index_next_value == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
prop_foreach->next = ctx->index;
ctx->loop_offset = njs_code_offset(generator, generator->code_end);
/* Object part calculation. */
njs_generator_next(generator, njs_generate, foreach->left->left);
/* The loop body. */
ret = njs_generator_after(vm, generator, njs_queue_first(&generator->stack),
node, njs_generate_for_in_body_left_hand_expr,
ctx, sizeof(njs_generator_loop_ctx_t));
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
/* set-property and block. */
ret = njs_generator_after(vm, generator, njs_queue_first(&generator->stack),
node, njs_generate_for_in_set_prop_block, ctx,
sizeof(njs_generator_loop_ctx_t));
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
/* Key part calculation. */
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack),
foreach->left->right, njs_generate, NULL, 0);
}
static njs_int_t
njs_generate_for_in_set_prop_block(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_parser_node_t *foreach;
njs_vmcode_prop_set_t *prop_set;
njs_generator_loop_ctx_t *ctx;
ctx = generator->context;
foreach = node->left;
njs_generate_code(generator, njs_vmcode_prop_set_t, prop_set,
NJS_VMCODE_PROPERTY_SET, 3, foreach);
prop_set->object = foreach->left->left->index;
prop_set->property = foreach->left->right->index;
prop_set->value = ctx->index_next_value;
njs_generator_next(generator, njs_generate, node->right);
return NJS_OK;
}
static njs_int_t
njs_generate_for_in_object(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_parser_node_t *foreach, *name;
njs_generator_loop_ctx_t *ctx;
njs_vmcode_prop_foreach_t *prop_foreach;
ctx = generator->context;
foreach = node->left;
name = foreach->left->right;
if (name != NULL) {
ctx->var->init = 1;
}
njs_generate_code(generator, njs_vmcode_prop_foreach_t, prop_foreach,
NJS_VMCODE_PROPERTY_FOREACH, 2, foreach);
ctx->jump_offset = njs_code_offset(generator, prop_foreach);
prop_foreach->object = foreach->right->index;
ctx->index = njs_generate_temp_index_get(vm, generator, foreach->right);
if (njs_slow_path(ctx->index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
prop_foreach->next = ctx->index;
/* The loop body. */
ctx->loop_offset = njs_code_offset(generator, generator->code_end);
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_for_in_body, ctx, 0);
}
static njs_int_t
njs_generate_for_in_body_left_hand_expr(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node)
{
njs_int_t ret;
njs_jump_off_t prop_offset;
njs_parser_node_t *foreach;
njs_vmcode_prop_next_t *prop_next;
njs_generator_loop_ctx_t *ctx;
ctx = generator->context;
foreach = node->left;
njs_generate_patch_block(vm, generator, generator->block,
NJS_GENERATOR_CONTINUATION);
njs_code_set_jump_offset(generator, njs_vmcode_prop_foreach_t,
ctx->jump_offset);
njs_generate_code(generator, njs_vmcode_prop_next_t, prop_next,
NJS_VMCODE_PROPERTY_NEXT, 3, node->left->left);
prop_offset = njs_code_offset(generator, prop_next);
prop_next->retval = ctx->index_next_value;
prop_next->object = foreach->right->index;
prop_next->next = ctx->index;
prop_next->offset = ctx->loop_offset - prop_offset;
njs_generate_patch_block_exit(vm, generator);
/*
* Release object and iterator indexes: an object can be a function result
* or a property of another object and an iterator can be given with "let".
*/
ret = njs_generate_children_indexes_release(vm, generator, foreach);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
ret = njs_generate_index_release(vm, generator, ctx->index);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, ctx);
}
static njs_int_t
njs_generate_for_in_body(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_jump_off_t prop_offset;
njs_parser_node_t *foreach, *name;
njs_vmcode_prop_next_t *prop_next;
njs_generator_loop_ctx_t *ctx;
ctx = generator->context;
foreach = node->left;
name = foreach->left->right;
/* The loop iterator. */
if (name != NULL) {
ret = njs_generate_for_let_update(vm, generator, foreach->left);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
}
njs_generate_patch_block(vm, generator, generator->block,
NJS_GENERATOR_CONTINUATION);
njs_code_set_jump_offset(generator, njs_vmcode_prop_foreach_t,
ctx->jump_offset);
njs_generate_code(generator, njs_vmcode_prop_next_t, prop_next,
NJS_VMCODE_PROPERTY_NEXT, 3, node->left->left);
prop_offset = njs_code_offset(generator, prop_next);
prop_next->retval = foreach->left->index;
prop_next->object = foreach->right->index;
prop_next->next = ctx->index;
prop_next->offset = ctx->loop_offset - prop_offset;
njs_generate_patch_block_exit(vm, generator);
/*
* Release object and iterator indexes: an object can be a function result
* or a property of another object and an iterator can be given with "let".
*/
ret = njs_generate_children_indexes_release(vm, generator, foreach);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
ret = njs_generate_index_release(vm, generator, ctx->index);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, ctx);
}
#ifdef NJS_DEBUG_GENERATOR
njs_inline const char*
njs_block_type(njs_generator_block_type_t type)
{
switch (type) {
case NJS_GENERATOR_LOOP:
return "LOOP ";
case NJS_GENERATOR_SWITCH:
return "SWITCH";
case NJS_GENERATOR_BLOCK:
return "BLOCK ";
default:
return "TRY ";
}
}
#endif
static njs_int_t
njs_generate_start_block(njs_vm_t *vm, njs_generator_t *generator,
njs_generator_block_type_t type, const njs_str_t *label)
{
njs_generator_block_t *block;
block = njs_mp_alloc(vm->mem_pool, sizeof(njs_generator_block_t));
if (njs_fast_path(block != NULL)) {
block->next = generator->block;
generator->block = block;
block->type = type;
block->label = *label;
block->continuation = NULL;
block->exit = NULL;
block->index = 0;
njs_debug_generator(vm, "START %s %p", njs_block_type(type), block);
return NJS_OK;
}
return NJS_ERROR;
}
static njs_generator_block_t *
njs_generate_lookup_block(njs_generator_block_t *block, uint32_t mask,
const njs_str_t *label)
{
if (njs_strstr_eq(label, &return_label)) {
mask = NJS_GENERATOR_TRY;
label = &no_label;
}
while (block != NULL) {
if ((block->type & mask) != 0
&& (label->length == 0 || njs_strstr_eq(&block->label, label)))
{
return block;
}
block = block->next;
}
return NULL;
}
static njs_generator_block_t *
njs_generate_find_block(njs_vm_t *vm, njs_generator_block_t *block,
uint32_t mask, const njs_str_t *label)
{
njs_generator_block_t *dest_block;
/*
* ES5.1: 12.8 The break Statement
* "break" without a label is valid only from within
* loop or switch statement.
*/
if ((mask & NJS_GENERATOR_ALL) == NJS_GENERATOR_ALL
&& label->length != 0)
{
mask |= NJS_GENERATOR_BLOCK;
}
dest_block = njs_generate_lookup_block(block, mask, label);
if (dest_block != NULL) {
/*
* Looking for intermediate try-catch blocks. Before jumping to
* the destination finally blocks have to be executed.
*/
while (block != NULL) {
if (block->type & NJS_GENERATOR_TRY) {
njs_debug_generator(vm, "FIND %s %p",
njs_block_type(block->type), block);
return block;
}
if (block == dest_block) {
break;
}
block = block->next;
}
}
njs_debug_generator(vm, "FIND %s %p",
dest_block != NULL ? njs_block_type(dest_block->type)
: "NONE ",
dest_block);
return dest_block;
}
static njs_generator_patch_t *
njs_generate_make_continuation_patch(njs_vm_t *vm, njs_generator_block_t *block,
const njs_str_t *label, njs_jump_off_t offset)
{
njs_generator_patch_t *patch;
patch = njs_mp_alloc(vm->mem_pool, sizeof(njs_generator_patch_t));
if (njs_slow_path(patch == NULL)) {
njs_memory_error(vm);
return NULL;
}
patch->next = block->continuation;
block->continuation = patch;
patch->jump_offset = offset;
patch->label = *label;
njs_debug_generator(vm, "MAKE CONT %p %L %V", patch, patch->jump_offset,
&patch->label);
return patch;
}
static void
njs_generate_patch(njs_vm_t *vm, njs_generator_t *generator,
njs_generator_patch_t *list)
{
njs_generator_patch_t *patch, *next;
for (patch = list; patch != NULL; patch = next) {
njs_code_update_offset(generator, patch);
njs_debug_generator(vm, "PATCH %p at %L to %L %V", patch,
patch->jump_offset,
*(njs_code_jump_ptr(generator, patch->jump_offset)),
&patch->label);
next = patch->next;
njs_mp_free(vm->mem_pool, patch);
}
}
static void
njs_generate_patch_block(njs_vm_t *vm, njs_generator_t *generator,
njs_generator_block_t *block, unsigned type)
{
if (type & NJS_GENERATOR_CONTINUATION) {
njs_debug_generator(vm, "PATCH CONT %p", block);
njs_generate_patch(vm, generator, block->continuation);
}
if (type & NJS_GENERATOR_EXIT) {
njs_debug_generator(vm, "PATCH EXIT %p", block);
njs_generate_patch(vm, generator, block->exit);
}
}
static njs_generator_patch_t *
njs_generate_make_exit_patch(njs_vm_t *vm, njs_generator_block_t *block,
const njs_str_t *label, njs_jump_off_t offset)
{
njs_generator_patch_t *patch;
patch = njs_mp_alloc(vm->mem_pool, sizeof(njs_generator_patch_t));
if (njs_slow_path(patch == NULL)) {
njs_memory_error(vm);
return NULL;
}
patch->next = block->exit;
block->exit = patch;
patch->jump_offset = offset;
patch->label = *label;
njs_debug_generator(vm, "MAKE EXIT %p %L %V", patch, patch->jump_offset,
&patch->label);
return patch;
}
static void
njs_generate_patch_block_exit(njs_vm_t *vm, njs_generator_t *generator)
{
njs_generator_block_t *block;
block = generator->block;
generator->block = block->next;
njs_generate_patch_block(vm, generator, block, NJS_GENERATOR_EXIT);
njs_debug_generator(vm, "EXIT %s %p", njs_block_type(block->type), block);
njs_mp_free(vm->mem_pool, block);
}
/*
* TODO: support multiple destination points from within try-catch block.
*/
static const njs_str_t *
njs_generate_jump_destination(njs_vm_t *vm, njs_generator_block_t *block,
const char *inst_type, uint32_t mask, const njs_str_t *label1,
const njs_str_t *label2)
{
njs_generator_block_t *block1, *block2;
if (label1->length == undef_label.length) {
return label2;
}
if (label2->length == undef_label.length) {
return label1;
}
block1 = njs_generate_lookup_block(block, mask, label1);
block2 = njs_generate_lookup_block(block, mask, label2);
if (block1 != block2) {
njs_internal_error(vm, "%s instructions with different labels "
"(\"%V\" vs \"%V\") "
"from try-catch block are not supported", inst_type,
label1, label2);
return NULL;
}
return label1;
}
static njs_int_t
njs_generate_continue_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
const njs_str_t *label, *dest;
njs_vmcode_jump_t *jump;
njs_generator_patch_t *patch;
njs_generator_block_t *block;
label = &node->name;
block = njs_generate_find_block(vm, generator->block, NJS_GENERATOR_LOOP,
label);
if (njs_slow_path(block == NULL)) {
goto syntax_error;
}
if (block->type == NJS_GENERATOR_TRY && block->continuation != NULL) {
dest = njs_generate_jump_destination(vm, block->next, "continue",
NJS_GENERATOR_LOOP,
&block->continuation->label,
label);
if (njs_slow_path(dest == NULL)) {
return NJS_ERROR;
}
}
njs_generate_code_jump(generator, jump,
offsetof(njs_vmcode_jump_t, offset));
patch = njs_generate_make_continuation_patch(vm, block, label,
njs_code_offset(generator, jump)
+ offsetof(njs_vmcode_jump_t, offset));
if (njs_slow_path(patch == NULL)) {
return NJS_ERROR;
}
return njs_generator_stack_pop(vm, generator, NULL);
syntax_error:
njs_generate_syntax_error(vm, node, &generator->file,
"Illegal continue statement");
return NJS_ERROR;
}
static njs_int_t
njs_generate_break_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
const njs_str_t *label, *dest;
njs_vmcode_jump_t *jump;
njs_generator_patch_t *patch;
njs_generator_block_t *block;
label = &node->name;
block = njs_generate_find_block(vm, generator->block, NJS_GENERATOR_ALL,
label);
if (njs_slow_path(block == NULL)) {
goto syntax_error;
}
if (block->type == NJS_GENERATOR_TRY && block->exit != NULL) {
dest = njs_generate_jump_destination(vm, block->next, "break/return",
NJS_GENERATOR_ALL,
&block->exit->label, label);
if (njs_slow_path(dest == NULL)) {
return NJS_ERROR;
}
}
njs_generate_code_jump(generator, jump,
offsetof(njs_vmcode_jump_t, offset));
patch = njs_generate_make_exit_patch(vm, block, label,
njs_code_offset(generator, jump)
+ offsetof(njs_vmcode_jump_t, offset));
if (njs_slow_path(patch == NULL)) {
return NJS_ERROR;
}
return njs_generator_stack_pop(vm, generator, NULL);
syntax_error:
njs_generate_syntax_error(vm, node, &generator->file,
"Illegal break statement");
return NJS_ERROR;
}
static njs_int_t
njs_generate_debugger_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_vmcode_debugger_t *debugger;
njs_generate_code(generator, njs_vmcode_debugger_t, debugger,
NJS_VMCODE_DEBUGGER, 0, node);
debugger->retval = njs_generate_dest_index(vm, generator, node);
if (njs_slow_path(debugger->retval == NJS_INDEX_ERROR)) {
return debugger->retval;
}
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_variable_t *var;
njs_queue_link_t *link;
njs_parser_node_t *right;
njs_vmcode_variable_t *code;
right = node->right;
if (right != NULL && right->token_type == NJS_TOKEN_NAME) {
var = njs_variable_reference(vm, right);
if (njs_slow_path(var == NULL)) {
goto statement;
}
if (!var->init && (var->type == NJS_VARIABLE_LET
|| var->type == NJS_VARIABLE_CONST))
{
njs_generate_code(generator, njs_vmcode_variable_t, code,
NJS_VMCODE_INITIALIZATION_TEST, 0, right);
code->dst = right->index;
}
if (node->left == NULL) {
return njs_generator_stack_pop(vm, generator, NULL);
}
node = node->left;
}
statement:
link = njs_queue_first(&generator->stack);
ret = njs_generate_children(vm, generator, node);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_after(vm, generator, link, right,
njs_generate_node_index_release_pop, NULL, 0);
}
static njs_int_t
njs_generate_block_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_queue_link_t *link;
ret = njs_generate_start_block(vm, generator, NJS_GENERATOR_BLOCK,
&node->name);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
link = njs_queue_first(&generator->stack);
ret = njs_generate_statement(vm, generator, node);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_after(vm, generator, link, node,
njs_generate_block_statement_end, NULL, 0);
}
static njs_int_t
njs_generate_block_statement_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_generate_patch_block_exit(vm, generator);
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_children(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_generator_next(generator, njs_generate, node->left);
ret = njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node->right,
njs_generate, NULL, 0);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node->left,
njs_generate_node_index_release_pop, NULL, 0);
}
static njs_int_t
njs_generate_stop_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_queue_link_t *link;
link = njs_queue_first(&generator->stack);
ret = njs_generate_children(vm, generator, node);
if (njs_fast_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_after(vm, generator, link, node,
njs_generate_stop_statement_end, NULL, 0);
}
static njs_int_t
njs_generate_stop_statement_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_index_t index;
njs_vmcode_stop_t *stop;
njs_generate_code(generator, njs_vmcode_stop_t, stop,
NJS_VMCODE_STOP, 1, node);
index = njs_scope_undefined_index(vm, 0);
node = node->right;
if (node != NULL) {
if ((node->index != NJS_INDEX_NONE
&& node->token_type != NJS_TOKEN_FUNCTION_DECLARATION
&& node->token_type != NJS_TOKEN_ASYNC_FUNCTION_DECLARATION)
|| node->token_type == NJS_TOKEN_THIS)
{
index = node->index;
}
}
stop->retval = index;
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_comma_expression(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_queue_link_t *link;
link = njs_queue_first(&generator->stack);
ret = njs_generate_children(vm, generator, node);
if (njs_fast_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_after(vm, generator, link, node,
njs_generate_comma_expression_end, NULL, 0);
}
static njs_int_t
njs_generate_comma_expression_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
node->index = node->right->index;
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_global_property_set(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node_dst, njs_parser_node_t *node_src)
{
ssize_t length;
njs_int_t ret;
njs_value_t property;
njs_variable_t *var;
njs_vmcode_prop_set_t *prop_set;
const njs_lexer_entry_t *lex_entry;
var = njs_variable_reference(vm, node_dst);
if (var == NULL) {
njs_generate_code(generator, njs_vmcode_prop_set_t, prop_set,
NJS_VMCODE_PROPERTY_SET, 3, node_src);
prop_set->value = node_dst->index;
prop_set->object = njs_scope_global_this_index();
lex_entry = njs_lexer_entry(node_dst->u.reference.unique_id);
if (njs_slow_path(lex_entry == NULL)) {
return NJS_ERROR;
}
length = njs_utf8_length(lex_entry->name.start, lex_entry->name.length);
if (njs_slow_path(length < 0)) {
return NJS_ERROR;
}
ret = njs_string_new(vm, &property, lex_entry->name.start,
lex_entry->name.length, length);
if (njs_slow_path(ret != NJS_OK)) {
return NJS_ERROR;
}
prop_set->property = njs_scope_global_index(vm, &property,
generator->runtime);
if (njs_slow_path(prop_set->property == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
}
return NJS_OK;
}
static njs_int_t
njs_generate_assignment(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_variable_t *var;
njs_parser_node_t *lvalue, *expr;
njs_vmcode_variable_t *var_code;
lvalue = node->left;
expr = node->right;
expr->dest = NULL;
if (lvalue->token_type == NJS_TOKEN_NAME) {
ret = njs_generate_variable(vm, generator, lvalue, NJS_REFERENCE,
&var);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
if (var != NULL && var->type == NJS_VARIABLE_CONST) {
njs_generate_code(generator, njs_vmcode_variable_t, var_code,
NJS_VMCODE_ASSIGNMENT_ERROR, 0, node);
var_code->dst = var->index;
return njs_generator_stack_pop(vm, generator, NULL);
}
expr->dest = lvalue;
njs_generator_next(generator, njs_generate, expr);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_assignment_name, NULL, 0);
}
/* lvalue->token == NJS_TOKEN_PROPERTY(_INIT) */
/* Object. */
njs_generator_next(generator, njs_generate, lvalue->left);
ret = njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_assignment_prop, NULL, 0);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
/* Property. */
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack),
lvalue->right, njs_generate, NULL, 0);
}
static njs_int_t
njs_generate_assignment_name(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_parser_node_t *lvalue, *expr;
njs_vmcode_move_t *move;
lvalue = node->left;
expr = node->right;
/*
* lvalue and expression indexes are equal if the expression is an
* empty object or expression result is stored directly in variable.
*/
if (lvalue->index != expr->index) {
njs_generate_code_move(generator, move, lvalue->index, expr->index,
expr);
}
node->index = expr->index;
node->temporary = expr->temporary;
ret = njs_generate_global_property_set(vm, generator, node->left, expr);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_assignment_prop(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_index_t index, src;
njs_parser_node_t *lvalue, *expr, *object, *property;
njs_vmcode_move_t *move;
lvalue = node->left;
expr = node->right;
object = lvalue->left;
property = lvalue->right;
if (njs_slow_path(njs_parser_has_side_effect(expr))) {
/*
* Preserve object and property values stored in variables in a case
* if the variables can be changed by side effects in expression.
*/
if (object->token_type == NJS_TOKEN_NAME) {
src = object->index;
index = njs_generate_node_temp_index_get(vm, generator, object);
if (njs_slow_path(index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generate_code_move(generator, move, index, src, object);
}
if (property->token_type == NJS_TOKEN_NAME) {
src = property->index;
index = njs_generate_node_temp_index_get(vm, generator, property);
if (njs_slow_path(index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generate_code_move(generator, move, index, src, property);
}
}
njs_generator_next(generator, njs_generate, expr);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_assignment_end, NULL, 0);
}
static njs_int_t
njs_generate_assignment_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_index_t prop_index;
njs_parser_node_t *lvalue, *expr, *object, *property;
njs_vmcode_2addr_t *set_function, *to_prop_key;
njs_vmcode_prop_set_t *prop_set;
lvalue = node->left;
expr = node->right;
object = lvalue->left;
property = lvalue->right;
prop_index = property->index;
switch (lvalue->token_type) {
case NJS_TOKEN_PROPERTY_INIT:
if ((object->token_type == NJS_TOKEN_OBJECT
|| (object->token_type == NJS_TOKEN_OBJECT_VALUE
&& object->u.object->token_type == NJS_TOKEN_OBJECT))
&& (expr->token_type == NJS_TOKEN_FUNCTION
|| expr->token_type == NJS_TOKEN_FUNCTION_EXPRESSION
|| expr->token_type == NJS_TOKEN_ASYNC_FUNCTION_EXPRESSION))
{
if (property->token_type == NJS_TOKEN_STRING) {
njs_value_assign(&expr->u.value.data.u.lambda->name,
&property->u.value);
} else {
njs_generate_code(generator, njs_vmcode_2addr_t, to_prop_key,
NJS_VMCODE_TO_PROPERTY_KEY, 2, property);
prop_index = njs_generate_temp_index_get(vm, generator,
property);
if (njs_slow_path(prop_index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
to_prop_key->src = property->index;
to_prop_key->dst = prop_index;
njs_generate_code(generator, njs_vmcode_2addr_t, set_function,
NJS_VMCODE_SET_FUNCTION_NAME, 2, expr);
set_function->dst = expr->index;
set_function->src = prop_index;
}
}
njs_generate_code(generator, njs_vmcode_prop_set_t, prop_set,
NJS_VMCODE_PROPERTY_INIT, 3, expr);
break;
case NJS_TOKEN_PROTO_INIT:
njs_generate_code(generator, njs_vmcode_prop_set_t, prop_set,
NJS_VMCODE_PROTO_INIT, 3, expr);
break;
default:
/* NJS_VMCODE_PROPERTY_SET */
njs_generate_code(generator, njs_vmcode_prop_set_t, prop_set,
NJS_VMCODE_PROPERTY_SET, 3, expr);
}
prop_set->value = expr->index;
prop_set->object = object->index;
prop_set->property = prop_index;
if (prop_index != property->index) {
ret = njs_generate_index_release(vm, generator, prop_index);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
}
node->index = expr->index;
node->temporary = expr->temporary;
ret = njs_generate_children_indexes_release(vm, generator, lvalue);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_operation_assignment(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_index_t index;
njs_variable_t *var;
njs_parser_node_t *lvalue, *expr;
njs_vmcode_move_t *move;
njs_vmcode_variable_t *var_code;
lvalue = node->left;
if (lvalue->token_type == NJS_TOKEN_NAME) {
ret = njs_generate_variable(vm, generator, lvalue, NJS_REFERENCE,
&var);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
if (var != NULL && var->type == NJS_VARIABLE_CONST) {
njs_generate_code(generator, njs_vmcode_variable_t, var_code,
NJS_VMCODE_ASSIGNMENT_ERROR, 0, node);
var_code->dst = var->index;
return njs_generator_stack_pop(vm, generator, NULL);
}
index = lvalue->index;
expr = node->right;
if (njs_slow_path(njs_parser_has_side_effect(expr))) {
/* Preserve variable value if it may be changed by expression. */
njs_generate_code(generator, njs_vmcode_move_t, move,
NJS_VMCODE_MOVE, 2, expr);
move->src = lvalue->index;
index = njs_generate_temp_index_get(vm, generator, expr);
if (njs_slow_path(index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
move->dst = index;
}
njs_generator_next(generator, njs_generate, expr);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_operation_assignment_name,
&index, sizeof(njs_index_t));
}
/* lvalue->token == NJS_TOKEN_PROPERTY */
/* Object. */
njs_generator_next(generator, njs_generate, lvalue->left);
ret = njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_operation_assignment_prop, NULL, 0);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
/* Property. */
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack),
lvalue->right, njs_generate, NULL, 0);
}
static njs_int_t
njs_generate_operation_assignment_name(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_index_t index;
njs_parser_node_t *lvalue, *expr;
njs_vmcode_3addr_t *code;
lvalue = node->left;
expr = node->right;
index = *((njs_index_t *) generator->context);
njs_generate_code(generator, njs_vmcode_3addr_t, code,
node->u.operation, 3, expr);
code->dst = lvalue->index;
code->src1 = index;
code->src2 = expr->index;
node->index = lvalue->index;
ret = njs_generate_global_property_set(vm, generator, node->left, expr);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
if (lvalue->index != index) {
ret = njs_generate_index_release(vm, generator, index);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
}
njs_mp_free(vm->mem_pool, generator->context);
return njs_generate_node_index_release_pop(vm, generator, expr);
}
static njs_int_t
njs_generate_operation_assignment_prop(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_index_t index, src, prop_index;
njs_parser_node_t *lvalue, *object, *property;
njs_vmcode_move_t *move;
njs_vmcode_3addr_t *to_property_key;
njs_vmcode_prop_get_t *prop_get;
lvalue = node->left;
object = lvalue->left;
property = lvalue->right;
if (njs_slow_path(njs_parser_has_side_effect(node->right))) {
/*
* Preserve object and property values stored in variables in a case
* if the variables can be changed by side effects in expression.
*/
if (object->token_type == NJS_TOKEN_NAME) {
src = object->index;
index = njs_generate_node_temp_index_get(vm, generator, object);
if (njs_slow_path(index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generate_code_move(generator, move, index, src, object);
}
if (property->token_type == NJS_TOKEN_NAME) {
src = property->index;
index = njs_generate_node_temp_index_get(vm, generator, property);
if (njs_slow_path(index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generate_code_move(generator, move, index, src, property);
}
}
prop_index = property->index;
if (!njs_parser_is_primitive(property)) {
prop_index = njs_generate_node_temp_index_get(vm, generator, node);
if (njs_slow_path(prop_index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generate_code(generator, njs_vmcode_3addr_t, to_property_key,
NJS_VMCODE_TO_PROPERTY_KEY_CHK, 2, property);
to_property_key->src2 = object->index;
to_property_key->src1 = property->index;
to_property_key->dst = prop_index;
}
index = njs_generate_node_temp_index_get(vm, generator, node);
if (njs_slow_path(index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generate_code(generator, njs_vmcode_prop_get_t, prop_get,
NJS_VMCODE_PROPERTY_GET, 3, property);
prop_get->value = index;
prop_get->object = object->index;
prop_get->property = prop_index;
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_operation_assignment_end,
&prop_index, sizeof(njs_index_t));
}
static njs_int_t
njs_generate_operation_assignment_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_index_t prop_index;
njs_parser_node_t *lvalue, *expr;
njs_vmcode_3addr_t *code;
njs_vmcode_prop_set_t *prop_set;
lvalue = node->left;
expr = node->right;
prop_index = *((njs_index_t *) generator->context);
njs_generate_code(generator, njs_vmcode_3addr_t, code,
node->u.operation, 3, expr);
code->dst = node->index;
code->src1 = node->index;
code->src2 = expr->index;
njs_generate_code(generator, njs_vmcode_prop_set_t, prop_set,
NJS_VMCODE_PROPERTY_SET, 3, expr);
prop_set->value = node->index;
prop_set->object = lvalue->left->index;
prop_set->property = prop_index;
ret = njs_generate_children_indexes_release(vm, generator, lvalue);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generate_node_index_release_pop(vm, generator, expr);
}
static njs_int_t
njs_generate_object(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_vmcode_object_t *object;
node->index = njs_generate_object_dest_index(vm, generator, node);
if (njs_slow_path(node->index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generate_code(generator, njs_vmcode_object_t, object,
NJS_VMCODE_OBJECT, 1, node);
object->retval = node->index;
/* Initialize object. */
njs_generator_next(generator, njs_generate, node->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack),
NULL, njs_generator_pop, NULL, 0);
}
static njs_int_t
njs_generate_property_accessor(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_generator_next(generator, njs_generate, node->left->left);
ret = njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_property_accessor_end, NULL, 0);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
ret = njs_generator_after(vm, generator,
njs_queue_first(&generator->stack),
node->right, njs_generate, NULL, 0);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack),
node->left->right, njs_generate, NULL, 0);
}
static njs_int_t
njs_generate_property_accessor_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_parser_node_t *lvalue, *function;
njs_vmcode_prop_accessor_t *accessor;
lvalue = node->left;
function = node->right;
njs_generate_code(generator, njs_vmcode_prop_accessor_t, accessor,
NJS_VMCODE_PROPERTY_ACCESSOR, 3, function);
accessor->value = function->index;
accessor->object = lvalue->left->index;
accessor->property = lvalue->right->index;
accessor->type = (node->token_type == NJS_TOKEN_PROPERTY_GETTER)
? NJS_OBJECT_PROP_GETTER : NJS_OBJECT_PROP_SETTER;
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_array(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_vmcode_array_t *array;
node->index = njs_generate_object_dest_index(vm, generator, node);
if (njs_slow_path(node->index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generate_code(generator, njs_vmcode_array_t, array,
NJS_VMCODE_ARRAY, 1, node);
array->ctor = node->ctor;
array->retval = node->index;
array->length = node->u.length;
/* Initialize array. */
njs_generator_next(generator, njs_generate, node->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack),
NULL, njs_generator_pop, NULL, 0);
}
static njs_int_t
njs_generate_function_expression(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
ssize_t length;
njs_int_t ret;
njs_variable_t *var;
njs_function_lambda_t *lambda;
njs_vmcode_function_t *function;
const njs_lexer_entry_t *lex_entry;
var = njs_variable_reference(vm, node->left);
if (njs_slow_path(var == NULL)) {
ret = njs_generate_reference_error(vm, generator, node->left);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, NULL);
}
lambda = node->u.value.data.u.lambda;
lex_entry = njs_lexer_entry(var->unique_id);
if (njs_slow_path(lex_entry == NULL)) {
return NJS_ERROR;
}
ret = njs_generate_function_scope(vm, generator, lambda, node,
&lex_entry->name);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
length = njs_utf8_length(lex_entry->name.start, lex_entry->name.length);
if (njs_slow_path(length < 0)) {
return NJS_ERROR;
}
ret = njs_string_new(vm, &lambda->name, lex_entry->name.start,
lex_entry->name.length, length);
if (njs_slow_path(ret != NJS_OK)) {
return NJS_ERROR;
}
njs_generate_code(generator, njs_vmcode_function_t, function,
NJS_VMCODE_FUNCTION, 1, node);
function->lambda = lambda;
function->async = (node->token_type == NJS_TOKEN_ASYNC_FUNCTION_EXPRESSION);
node->index = njs_generate_object_dest_index(vm, generator, node);
if (njs_slow_path(node->index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
function->retval = node->index;
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_function(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_function_lambda_t *lambda;
njs_vmcode_function_t *function;
lambda = node->u.value.data.u.lambda;
ret = njs_generate_function_scope(vm, generator, lambda, node,
&njs_entry_empty);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
njs_generate_code(generator, njs_vmcode_function_t, function,
NJS_VMCODE_FUNCTION, 1, node);
function->lambda = lambda;
function->async = (node->token_type == NJS_TOKEN_ASYNC_FUNCTION);
node->index = njs_generate_object_dest_index(vm, generator, node);
if (njs_slow_path(node->index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
function->retval = node->index;
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_regexp(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_vmcode_regexp_t *regexp;
node->index = njs_generate_object_dest_index(vm, generator, node);
if (njs_slow_path(node->index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generate_code(generator, njs_vmcode_regexp_t, regexp,
NJS_VMCODE_REGEXP, 1, node);
regexp->retval = node->index;
regexp->pattern = node->u.value.data.u.data;
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_template_literal(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_generator_next(generator, njs_generate, node->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_template_literal_end, NULL, 0);
}
static njs_int_t
njs_generate_template_literal_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_vmcode_template_literal_t *code;
njs_generate_code(generator, njs_vmcode_template_literal_t, code,
NJS_VMCODE_TEMPLATE_LITERAL, 1, node);
code->retval = node->left->index;
node->index = node->left->index;
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_test_jump_expression(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_generator_next(generator, njs_generate, node->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_test_jump_expression_after,
NULL, 0);
}
static njs_int_t
njs_generate_test_jump_expression_after(njs_vm_t *vm,
njs_generator_t *generator, njs_parser_node_t *node)
{
njs_jump_off_t jump_offset;
njs_vmcode_test_jump_t *test_jump;
njs_generate_code(generator, njs_vmcode_test_jump_t, test_jump,
node->u.operation, 2, node);
jump_offset = njs_code_offset(generator, test_jump);
test_jump->value = node->left->index;
node->index = njs_generate_node_temp_index_get(vm, generator, node);
if (njs_slow_path(node->index == NJS_INDEX_ERROR)) {
return node->index;
}
test_jump->retval = node->index;
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_test_jump_expression_end,
&jump_offset, sizeof(njs_jump_off_t));
}
static njs_int_t
njs_generate_test_jump_expression_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_vmcode_move_t *move;
/*
* The right expression usually uses node->index as destination,
* however, if the expression is a literal, variable or assignment,
* then a MOVE operation is required.
*/
if (node->index != node->right->index) {
njs_generate_code_move(generator, move, node->index,
node->right->index, node);
}
njs_code_set_jump_offset(generator, njs_vmcode_test_jump_t,
*((njs_jump_off_t *) generator->context));
ret = njs_generate_children_indexes_release(vm, generator, node);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, generator->context);
}
static njs_int_t
njs_generate_3addr_operation(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node, njs_bool_t swap)
{
njs_int_t ret;
njs_parser_node_t *left, *right;
left = node->left;
right = node->right;
njs_generator_next(generator, njs_generate, left);
if (left->token_type == NJS_TOKEN_NAME) {
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_3addr_operation_name,
&swap, sizeof(njs_bool_t));
}
ret = njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_3addr_operation_end, &swap,
sizeof(njs_bool_t));
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), right,
njs_generate, NULL, 0);
}
static njs_int_t
njs_generate_3addr_operation_name(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_index_t index;
njs_parser_node_t *left;
njs_vmcode_move_t *move;
left = node->left;
if (njs_slow_path(njs_parser_has_side_effect(node->right))) {
njs_generate_code(generator, njs_vmcode_move_t, move,
NJS_VMCODE_MOVE, 2, node);
move->src = left->index;
index = njs_generate_node_temp_index_get(vm, generator, left);
if (njs_slow_path(index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
move->dst = index;
}
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_3addr_operation_end,
generator->context, 0);
}
static njs_int_t
njs_generate_3addr_operation_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_bool_t swap;
njs_parser_node_t *left, *right;
njs_vmcode_3addr_t *code;
left = node->left;
right = node->right;
njs_generate_code(generator, njs_vmcode_3addr_t, code,
node->u.operation, 3, node);
swap = *((njs_bool_t *) generator->context);
if (!swap) {
code->src1 = left->index;
code->src2 = right->index;
} else {
code->src1 = right->index;
code->src2 = left->index;
}
/*
* The temporary index of MOVE destination
* will be released here as index of node->left.
*/
node->index = njs_generate_dest_index(vm, generator, node);
if (njs_slow_path(node->index == NJS_INDEX_ERROR)) {
return node->index;
}
code->dst = node->index;
njs_debug_generator_code(code);
return njs_generator_stack_pop(vm, generator, generator->context);
}
static njs_int_t
njs_generate_2addr_operation(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_generator_next(generator, njs_generate, node->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_2addr_operation_end, NULL, 0);
}
static njs_int_t
njs_generate_2addr_operation_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_vmcode_2addr_t *code;
njs_generate_code(generator, njs_vmcode_2addr_t, code,
node->u.operation, 2, node);
code->src = node->left->index;
node->index = njs_generate_dest_index(vm, generator, node);
if (njs_slow_path(node->index == NJS_INDEX_ERROR)) {
return node->index;
}
code->dst = node->index;
njs_debug_generator_code(code);
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_typeof_operation(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_parser_node_t *expr;
expr = node->left;
if (expr->token_type != NJS_TOKEN_NAME) {
njs_generator_next(generator, njs_generate, node->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_typeof_operation_end, NULL, 0);
}
ret = njs_generate_variable(vm, generator, expr, NJS_TYPEOF, NULL);
if (njs_slow_path(ret != NJS_OK)) {
return NJS_ERROR;
}
return njs_generate_typeof_operation_end(vm, generator, node);
}
static njs_int_t
njs_generate_typeof_operation_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_vmcode_2addr_t *code;
njs_generate_code(generator, njs_vmcode_2addr_t, code,
node->u.operation, 2, node->left);
code->src = node->left->index;
node->index = njs_generate_dest_index(vm, generator, node);
if (njs_slow_path(node->index == NJS_INDEX_ERROR)) {
return node->index;
}
code->dst = node->index;
njs_debug_generator_code(code);
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_inc_dec_operation(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node, njs_bool_t post)
{
njs_int_t ret;
njs_index_t index;
njs_variable_t *var;
njs_parser_node_t *lvalue;
njs_vmcode_3addr_t *code;
njs_vmcode_variable_t *var_code;
lvalue = node->left;
if (lvalue->token_type == NJS_TOKEN_NAME) {
ret = njs_generate_variable(vm, generator, lvalue, NJS_REFERENCE,
&var);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
if (var != NULL && var->type == NJS_VARIABLE_CONST) {
njs_generate_code(generator, njs_vmcode_variable_t, var_code,
NJS_VMCODE_ASSIGNMENT_ERROR, 0, node);
var_code->dst = var->index;
return njs_generator_stack_pop(vm, generator, NULL);
}
index = njs_generate_dest_index(vm, generator, node);
if (njs_slow_path(index == NJS_INDEX_ERROR)) {
return index;
}
node->index = index;
njs_generate_code(generator, njs_vmcode_3addr_t, code,
node->u.operation, 3, node);
code->dst = index;
code->src1 = lvalue->index;
code->src2 = lvalue->index;
ret = njs_generate_global_property_set(vm, generator, lvalue, lvalue);
if (njs_slow_path(ret) != NJS_OK) {
return ret;
}
return njs_generator_stack_pop(vm, generator, NULL);
}
/* lvalue->token == NJS_TOKEN_PROPERTY */
/* Object. */
njs_generator_next(generator, njs_generate, lvalue->left);
ret = njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_inc_dec_operation_prop,
&post, sizeof(njs_bool_t));
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
/* Property. */
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack),
lvalue->right, njs_generate, NULL, 0);
}
static njs_int_t
njs_generate_inc_dec_operation_prop(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_bool_t post;
njs_index_t index, dest_index, prop_index;
njs_parser_node_t *lvalue;
njs_vmcode_3addr_t *code, *to_property_key;
njs_vmcode_prop_get_t *prop_get;
njs_vmcode_prop_set_t *prop_set;
lvalue = node->left;
if (node->dest != NULL) {
dest_index = node->dest->index;
if (dest_index != NJS_INDEX_NONE
&& dest_index != lvalue->left->index
&& dest_index != lvalue->right->index)
{
node->index = dest_index;
goto found;
}
}
dest_index = njs_generate_node_temp_index_get(vm, generator, node);
found:
prop_index = lvalue->right->index;
if (!njs_parser_is_primitive(lvalue->right)) {
prop_index = njs_generate_temp_index_get(vm, generator, node);
if (njs_slow_path(prop_index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generate_code(generator, njs_vmcode_3addr_t, to_property_key,
NJS_VMCODE_TO_PROPERTY_KEY_CHK, 2, node);
to_property_key->src2 = lvalue->left->index;
to_property_key->src1 = lvalue->right->index;
to_property_key->dst = prop_index;
}
post = *((njs_bool_t *) generator->context);
index = post ? njs_generate_temp_index_get(vm, generator, node)
: dest_index;
if (njs_slow_path(index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generate_code(generator, njs_vmcode_prop_get_t, prop_get,
NJS_VMCODE_PROPERTY_GET, 3, node);
prop_get->value = index;
prop_get->object = lvalue->left->index;
prop_get->property = prop_index;
njs_generate_code(generator, njs_vmcode_3addr_t, code,
node->u.operation, 3, node);
code->dst = dest_index;
code->src1 = index;
code->src2 = index;
njs_generate_code(generator, njs_vmcode_prop_set_t, prop_set,
NJS_VMCODE_PROPERTY_SET, 3, node);
prop_set->value = index;
prop_set->object = lvalue->left->index;
prop_set->property = prop_index;
if (post) {
ret = njs_generate_index_release(vm, generator, index);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
}
njs_mp_free(vm->mem_pool, generator->context);
ret = njs_generate_children_indexes_release(vm, generator, lvalue);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_function_declaration(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
ssize_t length;
njs_int_t ret;
njs_bool_t async;
njs_variable_t *var;
njs_function_t *function;
njs_function_lambda_t *lambda;
const njs_lexer_entry_t *lex_entry;
var = njs_variable_reference(vm, node);
if (njs_slow_path(var == NULL)) {
ret = njs_generate_reference_error(vm, generator, node);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, NULL);
}
lambda = njs_variable_lambda(var);
lex_entry = njs_lexer_entry(node->u.reference.unique_id);
if (njs_slow_path(lex_entry == NULL)) {
return NJS_ERROR;
}
length = njs_utf8_length(lex_entry->name.start, lex_entry->name.length);
if (njs_slow_path(length < 0)) {
return NJS_ERROR;
}
ret = njs_string_new(vm, &lambda->name, lex_entry->name.start,
lex_entry->name.length, length);
if (njs_slow_path(ret != NJS_OK)) {
return NJS_ERROR;
}
ret = njs_generate_function_scope(vm, generator, lambda, node,
&lex_entry->name);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
async = (node->token_type == NJS_TOKEN_ASYNC_FUNCTION_DECLARATION);
function = njs_function_alloc(vm, lambda, async);
if (njs_slow_path(function == NULL)) {
return NJS_ERROR;
}
function->global = njs_function_scope(var->scope)->type == NJS_SCOPE_GLOBAL;
function->object.shared = 1;
function->args_count = lambda->nargs - lambda->rest_parameters;
njs_set_function(&var->value, function);
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_function_scope(njs_vm_t *vm, njs_generator_t *prev,
njs_function_lambda_t *lambda, njs_parser_node_t *node,
const njs_str_t *name)
{
njs_int_t ret;
njs_arr_t *arr;
njs_uint_t depth;
njs_vm_code_t *code;
njs_generator_t generator;
depth = prev->depth;
if (++depth >= NJS_FUNCTION_MAX_DEPTH) {
njs_range_error(vm, "Maximum function nesting depth exceeded");
return NJS_ERROR;
}
ret = njs_generator_init(&generator, &prev->file, depth, prev->runtime);
if (njs_slow_path(ret != NJS_OK)) {
njs_internal_error(vm, "njs_generator_init() failed");
return NJS_ERROR;
}
node = node->right;
code = njs_generate_scope(vm, &generator, node->scope, name);
if (njs_slow_path(code == NULL)) {
if (!njs_is_error(&vm->exception)) {
njs_internal_error(vm, "njs_generate_scope() failed");
}
return NJS_ERROR;
}
lambda->start = generator.code_start;
lambda->closures = generator.closures->start;
lambda->nclosures = generator.closures->items;
lambda->nlocal = node->scope->items;
arr = node->scope->declarations;
lambda->declarations = (arr != NULL) ? arr->start : NULL;
lambda->ndeclarations = (arr != NULL) ? arr->items : 0;
return NJS_OK;
}
njs_vm_code_t *
njs_generate_scope(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_scope_t *scope, const njs_str_t *name)
{
u_char *p;
int64_t nargs;
njs_int_t ret;
njs_uint_t index;
njs_vm_code_t *code;
generator->code_size = 128;
p = njs_mp_alloc(vm->mem_pool, generator->code_size);
if (njs_slow_path(p == NULL)) {
njs_memory_error(vm);
return NULL;
}
generator->code_start = p;
generator->code_end = p;
nargs = njs_generate_lambda_variables(vm, generator, scope->top);
if (njs_slow_path(nargs < NJS_OK)) {
return NULL;
}
if (vm->codes == NULL) {
vm->codes = njs_arr_create(vm->mem_pool, 4, sizeof(njs_vm_code_t));
if (njs_slow_path(vm->codes == NULL)) {
return NULL;
}
}
index = vm->codes->items;
code = njs_arr_add(vm->codes);
if (njs_slow_path(code == NULL)) {
njs_memory_error(vm);
return NULL;
}
code->lines = NULL;
if (vm->options.backtrace) {
code->lines = njs_arr_create(vm->mem_pool, 4,
sizeof(njs_vm_line_num_t));
if (njs_slow_path(code->lines == NULL)) {
njs_memory_error(vm);
return NULL;
}
generator->lines = code->lines;
}
generator->closures = njs_arr_create(vm->mem_pool, 4, sizeof(njs_index_t));
if (njs_slow_path(generator->closures == NULL)) {
return NULL;
}
scope->closures = generator->closures;
njs_queue_init(&generator->stack);
njs_generator_next(generator, njs_generate, scope->top);
ret = njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), NULL,
njs_generate_scope_end, NULL, 0);
if (njs_slow_path(ret != NJS_OK)) {
return NULL;
}
do {
ret = generator->state(vm, generator, generator->node);
if (njs_slow_path(ret != NJS_OK)) {
return NULL;
}
} while (generator->state != NULL);
code = njs_arr_item(vm->codes, index);
code->start = generator->code_start;
code->end = generator->code_end;
code->file = generator->file;
code->name = *name;
generator->code_size = generator->code_end - generator->code_start;
return code;
}
static njs_int_t
njs_generate_scope_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
generator->state = NULL;
return NJS_OK;
}
static int64_t
njs_generate_lambda_variables(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
int64_t nargs;
njs_variable_t *var;
njs_rbtree_node_t *rb_node;
njs_variable_node_t *var_node;
njs_vmcode_arguments_t *arguments;
nargs = 0;
rb_node = njs_rbtree_min(&node->scope->variables);
while (njs_rbtree_is_there_successor(&node->scope->variables, rb_node)) {
var_node = (njs_variable_node_t *) rb_node;
var = var_node->variable;
if (var == NULL) {
break;
}
if (var->argument) {
nargs++;
}
if (var->arguments_object) {
njs_generate_code(generator, njs_vmcode_arguments_t, arguments,
NJS_VMCODE_ARGUMENTS, 1, NULL);
arguments->dst = var->index;
}
rb_node = njs_rbtree_node_successor(&node->scope->variables, rb_node);
}
return nargs;
}
static njs_int_t
njs_generate_return_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_return_statement_end, NULL, 0);
}
static njs_int_t
njs_generate_return_statement_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_index_t index;
const njs_str_t *dest;
njs_vmcode_return_t *code;
njs_generator_patch_t *patch;
njs_generator_block_t *block, *immediate, *top;
njs_vmcode_try_return_t *try_return;
if (node->right != NULL) {
index = node->right->index;
} else {
index = njs_scope_global_index(vm, &njs_value_undefined,
generator->runtime);
}
if (njs_slow_path(index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
immediate = njs_generate_lookup_block(generator->block, NJS_GENERATOR_TRY,
&no_label);
njs_debug_generator(vm, "LOOKUP TRY %p", immediate);
if (njs_fast_path(immediate == NULL)) {
njs_generate_code(generator, njs_vmcode_return_t, code,
NJS_VMCODE_RETURN, 1, node);
code->retval = index;
node->index = index;
return njs_generator_stack_pop(vm, generator, NULL);
}
if (immediate->type == NJS_GENERATOR_TRY && immediate->exit != NULL) {
dest = njs_generate_jump_destination(vm, immediate->next,
"break/return",
NJS_GENERATOR_ALL,
&immediate->exit->label,
&return_label);
if (njs_slow_path(dest == NULL)) {
return NJS_ERROR;
}
}
top = immediate;
block = immediate->next;
while (block != NULL) {
if (block->type & NJS_GENERATOR_TRY) {
top = block;
}
block = block->next;
}
njs_generate_code(generator, njs_vmcode_try_return_t, try_return,
NJS_VMCODE_TRY_RETURN, 2, node);
try_return->retval = index;
try_return->save = top->index;
try_return->offset = offsetof(njs_vmcode_try_return_t, offset);
patch = njs_generate_make_exit_patch(vm, immediate, &return_label,
njs_code_offset(generator, try_return)
+ offsetof(njs_vmcode_try_return_t,
offset));
if (njs_slow_path(patch == NULL)) {
return NJS_ERROR;
}
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_function_call(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_variable_t *var;
var = NULL;
if (node->left != NULL) {
/* Generate function code in function expression. */
njs_generator_next(generator, njs_generate, node->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_function_call_arguments,
NULL, 0);
}
ret = njs_generate_variable(vm, generator, node, NJS_REFERENCE, &var);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generate_function_call_arguments(vm, generator, node);
}
static njs_int_t
njs_generate_function_call_arguments(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_jump_off_t func_offset;
njs_parser_node_t *name;
njs_vmcode_function_frame_t *func;
name = node;
if (node->left != NULL) {
name = node->left;
}
njs_generate_code(generator, njs_vmcode_function_frame_t, func,
NJS_VMCODE_FUNCTION_FRAME, 2, node);
func_offset = njs_code_offset(generator, func);
func->ctor = node->ctor;
func->name = name->index;
func->nargs = 0;
njs_generator_next(generator, njs_generate,
(node->right != NULL ? node->right->left : NULL));
ret = njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_function_call_end, NULL, 0);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
if (node->right == NULL) {
return NJS_OK;
}
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node->right,
njs_generate_move_arguments,
&func_offset, sizeof(njs_jump_off_t));
}
static njs_int_t
njs_generate_function_call_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
ret = njs_generate_call(vm, generator, node);
if (njs_fast_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, generator->context);
}
static njs_int_t
njs_generate_method_call(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_parser_node_t *prop;
prop = node->left;
/* Object. */
njs_generator_next(generator, njs_generate, prop->left);
ret = njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_method_call_arguments, NULL, 0);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
/* Method name. */
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), prop->right,
njs_generate, NULL, 0);
}
static njs_int_t
njs_generate_method_call_arguments(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_jump_off_t method_offset;
njs_parser_node_t *prop;
njs_vmcode_method_frame_t *method;
prop = node->left;
njs_generate_code(generator, njs_vmcode_method_frame_t, method,
NJS_VMCODE_METHOD_FRAME, 3, prop);
method_offset = njs_code_offset(generator, method);
method->ctor = node->ctor;
method->object = prop->left->index;
method->method = prop->right->index;
method->nargs = 0;
njs_generator_next(generator, njs_generate,
(node->right != NULL ? node->right->left : node->right));
ret = njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_method_call_end, NULL, 0);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
if (node->right == NULL) {
return NJS_OK;
}
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node->right,
njs_generate_move_arguments,
&method_offset, sizeof(njs_jump_off_t));
}
static njs_int_t
njs_generate_method_call_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
ret = njs_generate_call(vm, generator, node);
if (njs_fast_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, generator->context);
}
static njs_int_t
njs_generate_call(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_index_t retval;
njs_vmcode_function_call_t *call;
retval = njs_generate_dest_index(vm, generator, node);
if (njs_slow_path(retval == NJS_INDEX_ERROR)) {
return retval;
}
node->index = retval;
njs_generate_code(generator, njs_vmcode_function_call_t, call,
NJS_VMCODE_FUNCTION_CALL, 1, node);
call->retval = retval;
return NJS_OK;
}
static njs_int_t
njs_generate_move_arguments(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_jump_off_t func_offset;
njs_vmcode_1addr_t *put_arg;
njs_vmcode_function_frame_t *func;
if (node == NULL) {
return njs_generator_stack_pop(vm, generator, generator->context);
}
njs_generate_code(generator, njs_vmcode_1addr_t, put_arg,
NJS_VMCODE_PUT_ARG, 0, node);
put_arg->index = node->left->index;
func_offset = *((njs_jump_off_t *) generator->context);
func = njs_code_ptr(generator, njs_vmcode_function_frame_t, func_offset);
func->nargs++;
if (node->right == NULL) {
return njs_generator_stack_pop(vm, generator, generator->context);
}
njs_generator_next(generator, njs_generate, node->right->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node->right,
njs_generate_move_arguments,
generator->context, 0);
}
#define njs_generate_code_catch(generator, _code, _exception, node) \
do { \
njs_generate_code(generator, njs_vmcode_catch_t, _code, \
NJS_VMCODE_CATCH, 2, node); \
_code->offset = sizeof(njs_vmcode_catch_t); \
_code->exception = _exception; \
} while (0)
#define njs_generate_code_finally(generator, _code, _retval, _exit, node) \
do { \
njs_generate_code(generator, njs_vmcode_finally_t, _code, \
NJS_VMCODE_FINALLY, 1, node); \
_code->retval = _retval; \
_code->exit_value = _exit; \
_code->continue_offset = offsetof(njs_vmcode_finally_t, \
continue_offset); \
_code->break_offset = offsetof(njs_vmcode_finally_t, \
break_offset); \
} while (0)
static njs_int_t
njs_generate_try_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_index_t exception_index, exit_index;
njs_vmcode_try_start_t *try_start;
njs_generator_try_ctx_t ctx;
njs_memzero(&ctx, sizeof(njs_generator_try_ctx_t));
njs_generate_code(generator, njs_vmcode_try_start_t, try_start,
NJS_VMCODE_TRY_START, 2, node);
ctx.try_offset = njs_code_offset(generator, try_start);
exception_index = njs_generate_temp_index_get(vm, generator, node);
if (njs_slow_path(exception_index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
try_start->exception_value = exception_index;
/*
* exit_value is used in njs_vmcode_finally to make a decision
* which way to go after "break", "continue" and "return" instruction
* inside "try" or "catch" blocks.
*/
exit_index = njs_generate_temp_index_get(vm, generator, node);
if (njs_slow_path(exit_index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
try_start->exit_value = exit_index;
ret = njs_generate_start_block(vm, generator, NJS_GENERATOR_TRY, &no_label);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
ctx.try_block = generator->block;
ctx.try_block->index = exit_index;
ctx.exception_index = exception_index;
ctx.catch_cont_label = undef_label;
ctx.catch_exit_label = undef_label;
ctx.try_cont_label = undef_label;
ctx.try_exit_label = undef_label;
njs_generator_next(generator, njs_generate, node->left);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_try_left,
&ctx, sizeof(njs_generator_try_ctx_t));
}
static njs_int_t
njs_generate_try_left(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_index_t exit_index, catch_index;
njs_jump_off_t try_end_offset;
njs_variable_t *var;
njs_vmcode_catch_t *catch;
njs_vmcode_try_end_t *try_end;
njs_generator_block_t *try_block;
njs_generator_try_ctx_t *ctx;
njs_vmcode_try_trampoline_t *try_break, *try_continue;
ctx = generator->context;
try_block = ctx->try_block;
exit_index = try_block->index;
njs_generate_code(generator, njs_vmcode_try_end_t, try_end,
NJS_VMCODE_TRY_END, 0, NULL);
try_end_offset = njs_code_offset(generator, try_end);
if (try_block->exit != NULL) {
ctx->try_exit_label = try_block->exit->label;
njs_debug_generator(vm, "TRY CTX %p EXIT LABEL %V", ctx,
&ctx->try_exit_label);
njs_generate_patch_block(vm, generator, try_block,
NJS_GENERATOR_EXIT);
njs_generate_code(generator, njs_vmcode_try_trampoline_t, try_break,
NJS_VMCODE_TRY_BREAK, 1, NULL);
try_break->exit_value = exit_index;
try_break->offset = -sizeof(njs_vmcode_try_end_t);
} else {
try_break = NULL;
}
if (try_block->continuation != NULL) {
ctx->try_cont_label = try_block->continuation->label;
njs_generate_patch_block(vm, generator, try_block,
NJS_GENERATOR_CONTINUATION);
njs_generate_code(generator, njs_vmcode_try_trampoline_t, try_continue,
NJS_VMCODE_TRY_CONTINUE, 1, NULL);
try_continue->exit_value = exit_index;
try_continue->offset = -sizeof(njs_vmcode_try_end_t);
if (try_break != NULL) {
try_continue->offset -= sizeof(njs_vmcode_try_trampoline_t);
}
}
njs_debug_generator(vm, "EXIT %s %p",
njs_block_type(generator->block->type),
generator->block);
generator->block = try_block->next;
njs_code_set_jump_offset(generator, njs_vmcode_try_start_t,
ctx->try_offset);
ctx->try_offset = try_end_offset;
node = node->right;
if (node->token_type == NJS_TOKEN_CATCH) {
/* A "try/catch" case. */
var = njs_variable_reference(vm, node->left);
if (njs_slow_path(var == NULL)) {
return NJS_ERROR;
}
catch_index = node->left->index;
njs_generate_code_catch(generator, catch, catch_index, node);
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_try_catch, ctx, 0);
}
if (node->left != NULL) {
/* A try/catch/finally case. */
var = njs_variable_reference(vm, node->left->left);
if (njs_slow_path(var == NULL)) {
return NJS_ERROR;
}
catch_index = node->left->left->index;
njs_generate_code_catch(generator, catch, catch_index, node);
ctx->catch_offset = njs_code_offset(generator, catch);
ret = njs_generate_start_block(vm, generator, NJS_GENERATOR_TRY,
&no_label);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
ctx->catch_block = generator->block;
ctx->catch_block->index = exit_index;
njs_generator_next(generator, njs_generate, node->left->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_try_finally, ctx, 0);
}
/* A try/finally case. */
njs_generate_code_catch(generator, catch, ctx->exception_index, NULL);
ctx->catch_block = NULL;
njs_code_set_jump_offset(generator, njs_vmcode_try_end_t,
ctx->try_offset);
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_try_end, ctx, 0);
}
static njs_int_t
njs_generate_try_catch(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_index_t exit_index;
njs_vmcode_finally_t *finally;
njs_generator_patch_t *patch;
njs_generator_block_t *block, *try_block;
njs_generator_try_ctx_t *ctx;
ctx = generator->context;
try_block = ctx->try_block;
exit_index = try_block->index;
njs_code_set_jump_offset(generator, njs_vmcode_try_end_t,
ctx->try_offset);
if (try_block->continuation != NULL || try_block->exit != NULL) {
njs_generate_code_finally(generator, finally, ctx->exception_index,
exit_index, NULL);
if (try_block->continuation != NULL) {
/*
* block != NULL is checked
* by njs_generate_continue_statement()
*/
block = njs_generate_find_block(vm, generator->block,
NJS_GENERATOR_LOOP,
&ctx->try_cont_label);
patch = njs_generate_make_continuation_patch(vm, block,
&ctx->try_cont_label,
njs_code_offset(generator, finally)
+ offsetof(njs_vmcode_finally_t, continue_offset));
if (njs_slow_path(patch == NULL)) {
return NJS_ERROR;
}
}
if (try_block->exit != NULL) {
block = njs_generate_find_block(vm, generator->block,
NJS_GENERATOR_ALL,
&ctx->try_exit_label);
/*
* block can be NULL when &ctx->try_exit_label is "@return"
* for outermost try-catch block.
*/
if (block != NULL) {
patch = njs_generate_make_exit_patch(vm, block,
&ctx->try_exit_label,
njs_code_offset(generator, finally)
+ offsetof(njs_vmcode_finally_t, break_offset));
if (njs_slow_path(patch == NULL)) {
return NJS_ERROR;
}
} else {
/*
* when block == NULL, we still want to patch the "finally"
* instruction break_offset.
*/
block = njs_generate_find_block(vm, generator->block,
NJS_GENERATOR_ALL,
&no_label);
if (block != NULL) {
patch = njs_generate_make_exit_patch(vm, block, &no_label,
njs_code_offset(generator, finally)
+ offsetof(njs_vmcode_finally_t, break_offset));
if (njs_slow_path(patch == NULL)) {
return NJS_ERROR;
}
}
}
}
}
/* TODO: release exception variable index. */
ret = njs_generate_index_release(vm, generator, ctx->exception_index);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, ctx);
}
static njs_int_t
njs_generate_try_finally(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_index_t exit_index;
njs_jump_off_t catch_end_offset;
njs_vmcode_catch_t *catch;
njs_vmcode_try_end_t *catch_end;
njs_generator_block_t *try_block, *catch_block;
njs_generator_try_ctx_t *ctx;
njs_vmcode_try_trampoline_t *try_break, *try_continue;
ctx = generator->context;
try_block = ctx->try_block;
exit_index = try_block->index;
catch_block = ctx->catch_block;
njs_generate_code(generator, njs_vmcode_try_end_t, catch_end,
NJS_VMCODE_TRY_END, 0, node->left->right);
catch_end_offset = njs_code_offset(generator, catch_end);
if (catch_block->exit != NULL) {
ctx->catch_exit_label = catch_block->exit->label;
njs_generate_patch_block(vm, generator, catch_block,
NJS_GENERATOR_EXIT);
njs_generate_code(generator, njs_vmcode_try_trampoline_t,
try_break, NJS_VMCODE_TRY_BREAK, 1, NULL);
try_break->exit_value = exit_index;
try_break->offset = -sizeof(njs_vmcode_try_end_t);
} else {
try_break = NULL;
}
if (catch_block->continuation != NULL) {
ctx->catch_cont_label = catch_block->continuation->label;
njs_generate_patch_block(vm, generator, catch_block,
NJS_GENERATOR_CONTINUATION);
njs_generate_code(generator, njs_vmcode_try_trampoline_t,
try_continue, NJS_VMCODE_TRY_CONTINUE, 1,
NULL);
try_continue->exit_value = exit_index;
try_continue->offset = -sizeof(njs_vmcode_try_end_t);
if (try_break != NULL) {
try_continue->offset -= sizeof(njs_vmcode_try_trampoline_t);
}
}
njs_debug_generator(vm, "EXIT %s %p",
njs_block_type(generator->block->type),
generator->block);
generator->block = catch_block->next;
njs_code_set_jump_offset(generator, njs_vmcode_catch_t,
ctx->catch_offset);
/* TODO: release exception variable index. */
njs_generate_code_catch(generator, catch, ctx->exception_index, NULL);
njs_code_set_jump_offset(generator, njs_vmcode_try_end_t,
catch_end_offset);
njs_code_set_jump_offset(generator, njs_vmcode_try_end_t,
ctx->try_offset);
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_try_end, ctx, 0);
}
static njs_int_t
njs_generate_try_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
njs_index_t exit_index;
const njs_str_t *dest_label;
njs_vmcode_finally_t *finally;
njs_generator_patch_t *patch;
njs_generator_block_t *block, *try_block, *catch_block;
njs_generator_try_ctx_t *ctx;
ctx = generator->context;
try_block = ctx->try_block;
exit_index = try_block->index;
catch_block = ctx->catch_block;
njs_generate_code_finally(generator, finally, ctx->exception_index,
exit_index, node);
if (try_block->continuation != NULL
|| (catch_block && catch_block->continuation != NULL))
{
dest_label = njs_generate_jump_destination(vm, generator->block,
"try continue",
NJS_GENERATOR_LOOP,
&ctx->try_cont_label,
&ctx->catch_cont_label);
if (njs_slow_path(dest_label == NULL)) {
return NJS_ERROR;
}
/*
* block != NULL is checked
* by njs_generate_continue_statement()
*/
block = njs_generate_find_block(vm, generator->block,
NJS_GENERATOR_LOOP, dest_label);
patch = njs_generate_make_continuation_patch(vm, block, dest_label,
njs_code_offset(generator, finally)
+ offsetof(njs_vmcode_finally_t, continue_offset));
if (njs_slow_path(patch == NULL)) {
return NJS_ERROR;
}
}
if (try_block->exit != NULL
|| (catch_block != NULL && catch_block->exit != NULL))
{
dest_label = njs_generate_jump_destination(vm, generator->block,
"try break/return",
NJS_GENERATOR_ALL
| NJS_GENERATOR_TRY,
&ctx->try_exit_label,
&ctx->catch_exit_label);
if (njs_slow_path(dest_label == NULL)) {
return NJS_ERROR;
}
/*
* block can be NULL for "return" instruction in
* outermost try-catch block.
*/
block = njs_generate_find_block(vm, generator->block,
NJS_GENERATOR_ALL, dest_label);
if (block != NULL) {
patch = njs_generate_make_exit_patch(vm, block, dest_label,
njs_code_offset(generator, finally)
+ offsetof(njs_vmcode_finally_t, break_offset));
if (njs_slow_path(patch == NULL)) {
return NJS_ERROR;
}
} else {
block = njs_generate_find_block(vm, generator->block,
NJS_GENERATOR_ALL, &no_label);
if (block != NULL) {
patch = njs_generate_make_exit_patch(vm, block, &no_label,
njs_code_offset(generator, finally)
+ offsetof(njs_vmcode_finally_t, break_offset));
if (njs_slow_path(patch == NULL)) {
return NJS_ERROR;
}
}
}
}
ret = njs_generate_index_release(vm, generator, ctx->exception_index);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
return njs_generator_stack_pop(vm, generator, ctx);
}
static njs_int_t
njs_generate_throw_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_throw_end, NULL, 0);
}
static njs_int_t
njs_generate_throw_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_vmcode_throw_t *throw;
njs_generate_code(generator, njs_vmcode_throw_t, throw,
NJS_VMCODE_THROW, 1, node);
node->index = node->right->index;
throw->retval = node->index;
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_import_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_variable_t *var;
njs_parser_node_t *lvalue;
njs_vmcode_import_t *import;
lvalue = node->left;
var = njs_variable_reference(vm, lvalue);
if (njs_slow_path(var == NULL)) {
return NJS_ERROR;
}
njs_generate_code(generator, njs_vmcode_import_t, import,
NJS_VMCODE_IMPORT, 1, node);
import->module = node->u.module;
import->retval = lvalue->index;
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_export_statement(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_export_statement_end, NULL, 0);
}
static njs_int_t
njs_generate_export_statement_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_parser_node_t *obj;
njs_vmcode_return_t *code;
obj = node->right;
njs_generate_code(generator, njs_vmcode_return_t, code,
NJS_VMCODE_RETURN, 1, NULL);
code->retval = obj->index;
node->index = obj->index;
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_await(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_generator_next(generator, njs_generate, node->right);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_await_end, NULL, 0);
}
static njs_int_t
njs_generate_await_end(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_index_t index;
njs_vmcode_await_t *code;
index = node->right->index;
if (njs_slow_path(index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generate_code(generator, njs_vmcode_await_t, code,
NJS_VMCODE_AWAIT, 1, node);
code->retval = index;
node->index = index;
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_wo_dest(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_parser_scope_t *scope;
scope = njs_function_scope(node->scope);
scope->dest_disable = 1;
njs_generator_next(generator, njs_generate, node);
return njs_generator_after(vm, generator,
njs_queue_first(&generator->stack), node,
njs_generate_wo_dest_after, NULL, 0);
}
static njs_int_t
njs_generate_wo_dest_after(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_parser_scope_t *scope;
scope = njs_function_scope(node->scope);
scope->dest_disable = 0;
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_global_reference(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node, njs_bool_t exception)
{
ssize_t length;
njs_int_t ret;
njs_index_t index;
njs_value_t property;
njs_vmcode_prop_get_t *prop_get;
const njs_lexer_entry_t *lex_entry;
index = njs_generate_temp_index_get(vm, generator, node);
if (njs_slow_path(index == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
njs_generate_code(generator, njs_vmcode_prop_get_t, prop_get,
exception ? NJS_VMCODE_GLOBAL_GET: NJS_VMCODE_PROPERTY_GET,
3, node);
prop_get->value = index;
prop_get->object = njs_scope_global_this_index();
if (njs_slow_path(prop_get->object == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
lex_entry = njs_lexer_entry(node->u.reference.unique_id);
if (njs_slow_path(lex_entry == NULL)) {
return NJS_ERROR;
}
length = njs_utf8_length(lex_entry->name.start, lex_entry->name.length);
if (njs_slow_path(length < 0)) {
return NJS_ERROR;
}
ret = njs_string_new(vm, &property, lex_entry->name.start,
lex_entry->name.length, length);
if (njs_slow_path(ret != NJS_OK)) {
return NJS_ERROR;
}
prop_get->property = njs_scope_global_index(vm, &property,
generator->runtime);
if (njs_slow_path(prop_get->property == NJS_INDEX_ERROR)) {
return NJS_ERROR;
}
node->index = index;
if (!exception) {
return NJS_OK;
}
return njs_generate_reference_error(vm, generator, node);
}
static njs_int_t
njs_generate_reference_error(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_vmcode_error_t *ref_err;
const njs_lexer_entry_t *lex_entry;
if (njs_slow_path(!node->u.reference.not_defined)) {
njs_internal_error(vm, "variable is not defined but not_defined "
"is not set");
return NJS_ERROR;
}
njs_generate_code(generator, njs_vmcode_error_t, ref_err, NJS_VMCODE_ERROR,
0, NULL);
ref_err->type = NJS_OBJ_TYPE_REF_ERROR;
lex_entry = njs_lexer_entry(node->u.reference.unique_id);
if (njs_slow_path(lex_entry == NULL)) {
return NJS_ERROR;
}
return njs_name_copy(vm, &ref_err->u.name, &lex_entry->name);
}
static njs_index_t
njs_generate_dest_index(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_index_t ret;
njs_parser_node_t *dest;
njs_parser_scope_t *scope;
ret = njs_generate_children_indexes_release(vm, generator, node);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
dest = node->dest;
if (dest != NULL && dest->index != NJS_INDEX_NONE) {
scope = njs_function_scope(node->scope);
if (!scope->dest_disable) {
return dest->index;
}
}
return njs_generate_node_temp_index_get(vm, generator, node);
}
static njs_index_t
njs_generate_object_dest_index(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_index_t index;
njs_parser_node_t *dest;
dest = node->dest;
if (dest != NULL && dest->index != NJS_INDEX_NONE) {
index = dest->index;
if (node->left == NULL) {
/* Assign empty object directly to variable */
return index;
}
}
return njs_generate_node_temp_index_get(vm, generator, node);
}
static njs_index_t
njs_generate_node_temp_index_get(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
node->temporary = 1;
node->index = njs_generate_temp_index_get(vm, generator, node);
return node->index;
}
static njs_index_t
njs_generate_temp_index_get(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_arr_t *cache;
njs_index_t *last;
njs_parser_scope_t *scope;
cache = generator->index_cache;
if (cache != NULL && cache->items != 0) {
last = njs_arr_remove_last(cache);
njs_debug_generator(vm, "INDEX REUSE %04Xz", (size_t) *last);
return *last;
}
scope = njs_function_scope(node->scope);
if (njs_slow_path(scope == NULL)) {
return NJS_ERROR;
}
return njs_scope_index(scope->type, scope->items++, NJS_LEVEL_LOCAL,
NJS_VARIABLE_VAR);
}
static njs_int_t
njs_generate_children_indexes_release(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
ret = njs_generate_node_index_release(vm, generator, node->left);
if (njs_fast_path(ret == NJS_OK)) {
return njs_generate_node_index_release(vm, generator, node->right);
}
return ret;
}
static njs_int_t
njs_generate_node_index_release(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
if (node != NULL && node->temporary) {
return njs_generate_index_release(vm, generator, node->index);
}
return NJS_OK;
}
static njs_int_t
njs_generate_node_index_release_pop(njs_vm_t *vm, njs_generator_t *generator,
njs_parser_node_t *node)
{
njs_int_t ret;
if (node != NULL && node->temporary) {
ret = njs_generate_index_release(vm, generator, node->index);
if (njs_slow_path(ret != NJS_OK)) {
return ret;
}
}
return njs_generator_stack_pop(vm, generator, NULL);
}
static njs_int_t
njs_generate_index_release(njs_vm_t *vm, njs_generator_t *generator,
njs_index_t index)
{
njs_arr_t *cache;
njs_index_t *last;
njs_debug_generator(vm, "INDEX RELEASE %04Xz", (size_t) index);
cache = generator->index_cache;
if (cache == NULL) {
cache = njs_arr_create(vm->mem_pool, 4, sizeof(njs_value_t *));
if (njs_slow_path(cache == NULL)) {
return NJS_ERROR;
}
generator->index_cache = cache;
}
last = njs_arr_add(cache);
if (njs_fast_path(last != NULL)) {
*last = index;
return NJS_OK;
}
return NJS_ERROR;
}
|
2644d35d2e430943916bb4da4fa33e041ebc235c
|
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
|
/emulators/BasiliskII/patches/patch-src-slirp-misc.c
|
c23785b090c4939d3c333bfd2055b06569234dc7
|
[] |
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
| 392
|
c
|
patch-src-slirp-misc.c
|
$NetBSD: patch-src-slirp-misc.c,v 1.1 2011/08/20 15:30:36 joerg Exp $
--- src/slirp/misc.c.orig 2011-08-20 13:13:50.000000000 +0000
+++ src/slirp/misc.c
@@ -106,7 +106,7 @@ struct quehead_32 {
u_int32_t qh_rlink;
};
-inline void
+void
insque_32(a, b)
void *a;
void *b;
@@ -120,7 +120,7 @@ insque_32(a, b)
= (u_int32_t)element;
}
-inline void
+void
remque_32(a)
void *a;
{
|
03b8f1c1aedce23a15d480fbb7f0e5830657d302
|
3f308bd1e45dc44276d57c089e7698b4fcda79a4
|
/xenix/draft/object.c
|
9e643931e76ed20e93afacd602254fae85524b82
|
[] |
no_license
|
jhallen/joes-sandbox
|
b5b6d1acf3f66645c3a00757f217f7a8fe2cad27
|
0ec8c38756e4cdc40fc5f881b7c87e2628d15f24
|
refs/heads/master
| 2022-01-18T21:38:24.514745
| 2022-01-03T01:08:53
| 2022-01-03T01:08:53
| 25,269,713
| 760
| 42
| null | 2020-10-27T05:34:56
| 2014-10-15T19:21:16
|
C
|
UTF-8
|
C
| false
| false
| 3,217
|
c
|
object.c
|
/* Object management */
#include "object.h"
O *downfix(o)
O *o;
{
if(o)
{
o->up=0; o->down=MAXINT; o->right=0; o->left=MAXINT;
if(o->what==OLINE)
{
if(o->v.line.x+o->x>o->right) o->right=o->v.line.x+o->x;
if(o->v.line.x+o->x<o->left) o->left=o->v.line.x+o->x;
if(o->v.line.y+o->y>o->up) o->up=o->v.line.y+o->y;
if(o->v.line.y+o->y<o->down) o->down=o->v.line.y+o->y;
if(o->x>o->right) o->right=o->x;
if(o->x<o->left) o->left=o->x;
if(o->y>o->up) o->up=o->y;
if(o->y<o->down) o->down=o->y;
}
else
{
O *p;
if(p=o->v.list) do
{
downfix(p);
if(p->up>o->up) o->up=p->up;
if(p->down<o->down) o->down=p->down;
if(p->right>o->right) o->right=p->right;
if(p->left<o->left) o->left=p->left;
}
while((p=p->link.next)!=o->v.list);
}
}
return o;
}
O *upfix(o)
O *o;
{
if(o)
while(o->parent)
{
if(o->up>o->parent->up) o->parent->up=o->up;
if(o->down<o->parent->down) o->parent->down=o->down;
if(o->right>o->parent->right) o->parent->right=o->right;
if(o->left<o->parent->left) o->parent->left=o->left;
o=o->parent;
}
return o;
}
O *modfix(o)
O *o;
{
if(o)
{
o->up=0; o->down=MAXINT; o->right=0; o->left=MAXINT;
if(o->what==OLINE)
{
if(o->v.line.x+o->x>o->right) o->right=o->v.line.x+o->x;
if(o->v.line.x+o->x<o->left) o->left=o->v.line.x+o->x;
if(o->v.line.y+o->y>o->up) o->up=o->v.line.y+o->y;
if(o->v.line.y+o->y<o->down) o->down=o->v.line.y+o->y;
if(o->x>o->right) o->right=o->x;
if(o->x<o->left) o->left=o->x;
if(o->y>o->up) o->up=o->y;
if(o->y<o->down) o->down=o->y;
}
else if(o->what==OLIST)
{
O *p;
if(p=o->v.list) do
{
if(p->up>o->up) o->up=p->up;
if(p->down<o->down) o->down=p->down;
if(p->right>o->right) o->right=p->right;
if(p->left<o->left) o->left=p->left;
}
while((p=p->link.next)!=o->v.list);
}
upfix(o);
}
return o;
}
O *fixext(o)
O *o;
{
if(o)
{
downfix(o);
upfix(o);
}
return o;
}
O *mkline(parent,x,y,tox,toy)
O *parent;
int x,y,tox,toy;
{
O *o=(O *)malloc(sizeof(O));
o->what=OLINE;
o->parent=parent;
o->x=x;
o->y=y;
o->v.line.x=tox;
o->v.line.y=toy;
izque(O,link,o);
if(parent)
if(parent->v.list) enqueb(O,link,parent->v.list,o);
else parent->v.list=o;
modfix(o);
return o;
}
O *mklist(parent,x,y,list)
O *parent;
int x,y;
O *list;
{
O *o=(O *)malloc(sizeof(O));
o->what=OLIST;
o->parent=parent;
o->x=x;
o->y=y;
o->v.list=list;
izque(O,link,o);
if(parent)
if(parent->v.list) enqueb(O,link,parent->v.list,o);
else parent->v.list=o;
modfix(o);
return o;
}
void del(o)
O *o;
{
if(!o) return;
if(o->what==OLIST)
{
O *p, *e, *n;
if(e=p=o->v.list) do
{
n=p->link.next;
del(p);
} while(p=n, p!=e);
}
free(o);
}
O *rm(o)
O *o;
{
if(o)
{
if(o->parent)
{
if(qempty(O,link,o)) o->parent->v.list=0;
else
{
deque(O,link,o);
if(o->parent->v.list==o) o->parent->v.list=o->link.next;
izque(O,link,o);
}
modfix(o->parent);
}
}
return o;
}
O *dup(parent,o,x,y,mx,my)
O *parent, *o;
{
O *n, *p;
if(!o) return 0;
if(o->what==OLIST)
{
n=mklist(parent,x,y,NULL);
if(p=o->v.list) do
dup(n,p,(p->x-o->x)*mx+x,(p->y-o->y)*my+y,mx,my);
while((p=p->link.next)!=o->v.list);
}
else n=mkline(parent,x,y,o->v.line.x*mx,o->v.line.y*my);
return n;
}
|
d942a92d3e8fb9d4960d7d49ed54abd861148ec3
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/lib/libc/signal/signal.c
|
09960609f95b6c68b1bb7395d6064987ad6810df
|
[
"Apache-2.0"
] |
permissive
|
Samsung/TizenRT
|
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
|
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
|
refs/heads/master
| 2023-08-31T08:59:33.327998
| 2023-08-08T06:09:20
| 2023-08-31T04:38:20
| 82,517,252
| 590
| 719
|
Apache-2.0
| 2023-09-14T06:54:49
| 2017-02-20T04:38:30
|
C
|
UTF-8
|
C
| false
| false
| 5,170
|
c
|
signal.c
|
/****************************************************************************
*
* Copyright 2017 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
/****************************************************************************
* lib/libc/signal/signal.c
*
* Copyright (C) 2015-2016 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <signal.h>
#include <assert.h>
#include <sys/types.h>
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: signal
*
* Description:
* The signal() function will modify signal dispositions. The 'sig'
* argument specifies the signal. The 'func' argument specifies the
* signal's disposition, which may be SIG_DFL, SIG_IGN, or the address
* of a signal handler. If 'func' is the address of a signal handler, the
* system will add 'sig' to the calling process' signal mask before
* executing the signal handler; when the signal handler returns, the
* system will restore the calling process' signal mask to its state prior
* to the delivery of the signal.
*
* Input Parameters:
* sig - Identifies the signal to operate on
* func - The new disposition of the signal
*
* Returned Value:
* Upon successful completion, signal() will return the previous
* disposition of the signal handling. Otherwise, SIG_ERR will be returned
* and errno set to indicate the nature of the error.
*
****************************************************************************/
CODE void (*signal(int sig, CODE void (*func)(int sig)))(int sig)
{
struct sigaction act;
struct sigaction oact;
int ret;
if (GOOD_SIGNO(sig)) {
/* Initialize the sigaction structure */
act.sa_handler = func;
act.sa_flags = 0;
(void)sigemptyset(&act.sa_mask);
/* Check for SIG_IGN and SIG_DFL (and someday SIG_HOLD)
*
* REVISIT: Currently SIG_IGN, SIG_DFL, and SIG_HOLD have the same value
* and cannot be distinguished.
*/
if (func != SIG_DFL /* && func != SIG_IGN */) {
/* Add the signal to the set of signals to be ignored when the signal
* handler executes.
*/
ret = sigaddset(&act.sa_mask, sig);
if (ret < 0) {
/* Would happen if sig were invalid */
return (_sa_handler_t)SIG_ERR;
}
}
/* Set the signal disposition */
ret = sigaction(sig, &act, &oact);
/* Upon successful completion, signal() will the signal's previous
* disposition. Otherwise, SIG_ERR will be returned and errno set to
* indicate the error.
*/
if (ret == OK) {
return oact.sa_handler;
}
}
return (_sa_handler_t)SIG_ERR;
}
|
53d3f0d94ad658ddfbd0534e1b33025beabadc12
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/samd21/board/board.h
|
0f964a7b3e670af59fe36e5b309aacb3be719533
|
[
"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
| 991
|
h
|
board.h
|
/* This is a template file for board configuration created by MCUXpresso Project Generator. Enjoy! */
#ifndef _BOARD_H_
#define _BOARD_H_
/*******************************************************************************
* Definitions
******************************************************************************/
#include <stdint.h>
#include "samd21.h"
#include "system_samd21.h"
#include "core_cm0plus.h" /* Core Peripheral Access Layer */
/* The board name */
#define BOARD_NAME "###-not-specified-###"
#define CHIP_SRAM_END (0x20000000 + 32*1024)
/*******************************************************************************
* API
******************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif /* __cplusplus */
/*!
* @brief initialize debug console to enable printf for this demo/example
*/
void rt_board_init(void);
#if defined(__cplusplus)
}
#endif /* __cplusplus */
#endif /* _BOARD_H_ */
|
9171d54e8bb329603bae5d58df0458ef7fc10c80
|
98ebf9cb3e47e54c9f5ca3a21574ae423d90081c
|
/sw/example/demo_spi_irq/drv/neorv32_spi_irq.c
|
64d3beaab986b25699cb5675749601c989f24877
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
stnolting/neorv32
|
4a42ceae7a6bcbee4044ca50ab88f138025f1813
|
4cc0b8c296517e4b7c22296fe95253816a1dae55
|
refs/heads/main
| 2023-09-05T00:29:41.538253
| 2023-09-03T18:44:00
| 2023-09-03T18:44:00
| 274,442,284
| 1,224
| 210
|
BSD-3-Clause
| 2023-09-12T05:45:14
| 2020-06-23T15:29:41
|
VHDL
|
UTF-8
|
C
| false
| false
| 7,524
|
c
|
neorv32_spi_irq.c
|
// #################################################################################################
// # << NEORV32: neorv32_spi_irq.c - IRQ driven SPI Controller HW Driver >> #
// # ********************************************************************************************* #
// # BSD 3-Clause License #
// # #
// # Copyright (c) 2023, Stephan Nolting. All rights reserved. #
// # #
// # Redistribution and use in source and binary forms, with or without modification, are #
// # permitted provided that the following conditions are met: #
// # #
// # 1. Redistributions of source code must retain the above copyright notice, this list of #
// # conditions and the following disclaimer. #
// # #
// # 2. Redistributions in binary form must reproduce the above copyright notice, this list of #
// # conditions and the following disclaimer in the documentation and/or other materials #
// # provided with the distribution. #
// # #
// # 3. Neither the name of the copyright holder nor the names of its contributors may be used to #
// # endorse or promote products derived from this software without specific prior written #
// # permission. #
// # #
// # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS #
// # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF #
// # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE #
// # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, #
// # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE #
// # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED #
// # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING #
// # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED #
// # OF THE POSSIBILITY OF SUCH DAMAGE. #
// # ********************************************************************************************* #
// # The NEORV32 Processor - https://github.com/stnolting/neorv32 (c) Stephan Nolting #
// #################################################################################################
/**********************************************************************//**
* @file neorv32_spi_irq.c
* @author Andreas Kaeberlein
* @brief Addition to neorv32_spi.c, which provides an IRQ driven data flow.
*
* @note These functions should only be used if the SPI unit was synthesized (IO_SPI_EN = true).
**************************************************************************/
#include "neorv32.h"
#include "neorv32_spi_irq.h"
/**********************************************************************//**
* Initializes SPI flow control handle. The data structure elements are listed in #t_neorv32_spi.
*
* @param[in,out] *self SPI driver common data handle. See #t_neorv32_spi.
**************************************************************************/
void neorv32_spi_init(t_neorv32_spi *self) {
self->uint8IsBusy = 0;
self->uint16Fifo = (uint16_t) neorv32_spi_get_fifo_depth(); // acquire FIFO depth in elements
self->uint32Total = 0;
self->uint32Write = 0; // write element count
self->uint32Read = 0; // read element count
return;
}
/**********************************************************************//**
* SPI interrupt service routine. The data structure elements are listed in #t_neorv32_spi.
*
* @param[in,out] *self SPI driver common data handle. See #t_neorv32_spi.
**************************************************************************/
void neorv32_spi_isr(t_neorv32_spi *self) {
uint32_t uint32Lim; // loop limit
if ( 0 == self->uint32Total ) { // leave if accidentally called ISR
return;
}
// read data from SPI from last transfer
for ( ; self->uint32Read<self->uint32Write; (self->uint32Read)++ ) {
(self->ptrSpiBuf)[self->uint32Read] = (uint8_t) (NEORV32_SPI->DATA & 0xff); // capture from last transfer
}
if ( self->uint32Read == self->uint32Total ) { // transfer done, no new data
neorv32_spi_cs_dis(); // deselect slave
self->uint32Total = 0;
self->uint8IsBusy = 0;
neorv32_cpu_csr_clr(CSR_MIP, 1 << SPI_FIRQ_PENDING); // ack/clear pending FIRQ
return;
}
// write next packet
uint32Lim = min(self->uint32Write+self->uint16Fifo, self->uint32Total);
for ( ; self->uint32Write<uint32Lim; (self->uint32Write)++ ) {
NEORV32_SPI->DATA = (uint32_t) (self->ptrSpiBuf)[self->uint32Write]; // next transfer
}
neorv32_cpu_csr_clr(CSR_MIP, 1 << SPI_FIRQ_PENDING); // ack/clear pending FIRQ
return;
}
/**********************************************************************//**
* Starts ISR driven read/write SPI transfer.
*
* @param[in,out] *self SPI driver common data handle. See #t_neorv32_spi.
* @param[in] csn Used chip select index for transfer.
* @param[in,out] *spi write/read data buffer for SPI. Before transmission contents the write data and after the read data.
* @param[in] len number of bytes to transfer.
* @return int status of function.
* @retval 0 new transfer started.
* @retval 1 transfer active, refused request.
* @retval 2 unsupported data size, only 1/2/4 allowed.
**************************************************************************/
int neorv32_spi_rw(t_neorv32_spi *self, uint8_t csn, void *spi, uint32_t len) {
if ( 0 != self->uint8IsBusy ) {
return 1; // transfer active, no new request
}
self->uint32Total = len;
self->uint32Write = 0; // write element count
self->uint32Read = 0; // read element count
self->ptrSpiBuf = (uint8_t*) spi; // spi is byte orientated
self->uint8Csn = csn;
self->uint8IsBusy = 1; // mark as busy
neorv32_spi_cs_en(self->uint8Csn); // select SPI channel
(self->uint32Write)++;
NEORV32_SPI->DATA = (uint32_t) (self->ptrSpiBuf)[0]; // sent first element
return 0; // successful end
}
/**********************************************************************//**
* Check if transfer is active. see #neorv32_spi_rw
*
* @param[in,out] *self SPI driver common data handle. See #t_neorv32_spi.
* @return int status of function.
* @retval 0 idle.
* @retval 1 busy.
**************************************************************************/
int neorv32_spi_rw_busy(t_neorv32_spi *self) {
if ( 0 != self->uint8IsBusy ) {
return 1;
}
return 0;
}
|
dc0cf1f21c5774b0d9028e751d25c97b83a529b1
|
010279e2ba272d09e9d2c4e903722e5faba2cf7a
|
/contrib/tools/python3/src/Include/internal/pycore_pylifecycle.h
|
b4718b8ade2354aabad2ee075a4ccb9fe4cb47b2
|
[
"Apache-2.0",
"LicenseRef-scancode-python-cwi",
"LicenseRef-scancode-other-copyleft",
"Python-2.0",
"BSD-3-Clause",
"0BSD",
"GPL-1.0-or-later",
"LicenseRef-scancode-free-unknown"
] |
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
| 3,507
|
h
|
pycore_pylifecycle.h
|
#ifndef Py_INTERNAL_LIFECYCLE_H
#define Py_INTERNAL_LIFECYCLE_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef Py_BUILD_CORE
# error "this header requires Py_BUILD_CORE define"
#endif
#include "pycore_runtime.h" // _PyRuntimeState
/* Forward declarations */
struct _PyArgv;
struct pyruntimestate;
/* True if the main interpreter thread exited due to an unhandled
* KeyboardInterrupt exception, suggesting the user pressed ^C. */
PyAPI_DATA(int) _Py_UnhandledKeyboardInterrupt;
extern int _Py_SetFileSystemEncoding(
const char *encoding,
const char *errors);
extern void _Py_ClearFileSystemEncoding(void);
extern PyStatus _PyUnicode_InitEncodings(PyThreadState *tstate);
#ifdef MS_WINDOWS
extern int _PyUnicode_EnableLegacyWindowsFSEncoding(void);
#endif
PyAPI_FUNC(void) _Py_ClearStandardStreamEncoding(void);
PyAPI_FUNC(int) _Py_IsLocaleCoercionTarget(const char *ctype_loc);
/* Various one-time initializers */
extern PyStatus _PyFaulthandler_Init(int enable);
extern int _PyTraceMalloc_Init(int enable);
extern PyObject * _PyBuiltin_Init(PyInterpreterState *interp);
extern PyStatus _PySys_Create(
PyThreadState *tstate,
PyObject **sysmod_p);
extern PyStatus _PySys_ReadPreinitWarnOptions(PyWideStringList *options);
extern PyStatus _PySys_ReadPreinitXOptions(PyConfig *config);
extern int _PySys_UpdateConfig(PyThreadState *tstate);
extern void _PySys_Fini(PyInterpreterState *interp);
extern int _PyBuiltins_AddExceptions(PyObject * bltinmod);
extern PyStatus _Py_HashRandomization_Init(const PyConfig *);
extern PyStatus _PyImportZip_Init(PyThreadState *tstate);
extern PyStatus _PyGC_Init(PyInterpreterState *interp);
extern PyStatus _PyAtExit_Init(PyInterpreterState *interp);
extern int _Py_Deepfreeze_Init(void);
/* Various internal finalizers */
extern int _PySignal_Init(int install_signal_handlers);
extern void _PySignal_Fini(void);
extern void _PyImport_Fini(void);
extern void _PyImport_Fini2(void);
extern void _PyGC_Fini(PyInterpreterState *interp);
extern void _Py_HashRandomization_Fini(void);
extern void _PyFaulthandler_Fini(void);
extern void _PyHash_Fini(void);
extern void _PyTraceMalloc_Fini(void);
extern void _PyWarnings_Fini(PyInterpreterState *interp);
extern void _PyAST_Fini(PyInterpreterState *interp);
extern void _PyAtExit_Fini(PyInterpreterState *interp);
extern void _PyThread_FiniType(PyInterpreterState *interp);
extern void _Py_Deepfreeze_Fini(void);
extern void _PyArg_Fini(void);
extern PyStatus _PyGILState_Init(_PyRuntimeState *runtime);
extern PyStatus _PyGILState_SetTstate(PyThreadState *tstate);
extern void _PyGILState_Fini(PyInterpreterState *interp);
PyAPI_FUNC(void) _PyGC_DumpShutdownStats(PyInterpreterState *interp);
PyAPI_FUNC(PyStatus) _Py_PreInitializeFromPyArgv(
const PyPreConfig *src_config,
const struct _PyArgv *args);
PyAPI_FUNC(PyStatus) _Py_PreInitializeFromConfig(
const PyConfig *config,
const struct _PyArgv *args);
PyAPI_FUNC(wchar_t *) _Py_GetStdlibDir(void);
PyAPI_FUNC(int) _Py_HandleSystemExit(int *exitcode_p);
PyAPI_FUNC(PyObject*) _PyErr_WriteUnraisableDefaultHook(PyObject *unraisable);
PyAPI_FUNC(void) _PyErr_Print(PyThreadState *tstate);
PyAPI_FUNC(void) _PyErr_Display(PyObject *file, PyObject *exception,
PyObject *value, PyObject *tb);
PyAPI_FUNC(void) _PyThreadState_DeleteCurrent(PyThreadState *tstate);
extern void _PyAtExit_Call(PyInterpreterState *interp);
#ifdef __cplusplus
}
#endif
#endif /* !Py_INTERNAL_LIFECYCLE_H */
|
a6130d27d48e168d1eb7bc47fe5e20781b6a28e0
|
32056cf2a9af9ff234c60779d5e026cd5d63b123
|
/include/mln_chain.h
|
d9b646e4ece415442f27e1b1ac6ad0c4861a0929
|
[
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] |
permissive
|
Water-Melon/Melon
|
d513c764c503a4513c3e55430b28fe5d2dbab8b0
|
41e4cc44120cc57ffc7697a43c87ea355b0628c2
|
refs/heads/master
| 2023-08-25T08:37:48.730809
| 2023-08-24T12:06:45
| 2023-08-24T12:06:45
| 22,993,286
| 900
| 125
| null | null | null | null |
UTF-8
|
C
| false
| false
| 1,738
|
h
|
mln_chain.h
|
/*
* Copyright (C) Niklaus F.Schen.
*/
#ifndef __MLN_CHAIN_H
#define __MLN_CHAIN_H
#include "mln_types.h"
#include "mln_string.h"
#include "mln_alloc.h"
#include "mln_file.h"
typedef struct mln_buf_s {
mln_u8ptr_t left_pos;
mln_u8ptr_t pos;
mln_u8ptr_t last;
mln_u8ptr_t start;
mln_u8ptr_t end;
struct mln_buf_s *shadow;
mln_off_t file_left_pos;
mln_off_t file_pos;
mln_off_t file_last;
mln_file_t *file;
mln_u32_t temporary:1;
#if !defined(WIN32)
mln_u32_t mmap:1;
#endif
mln_u32_t in_memory:1;
mln_u32_t in_file:1;
mln_u32_t flush:1;
mln_u32_t sync:1;
mln_u32_t last_buf:1;
mln_u32_t last_in_chain:1;
} mln_buf_t;
typedef struct mln_chain_s {
mln_buf_t *buf;
struct mln_chain_s *next;
} mln_chain_t;
#define mln_buf_size(pbuf) \
((pbuf) == NULL? 0: \
((pbuf)->in_file? (pbuf)->file_last - (pbuf)->file_pos: (pbuf)->last - (pbuf)->pos))
#define mln_buf_left_size(pbuf) \
((pbuf) == NULL? 0: \
((pbuf)->in_file? (pbuf)->file_last - (pbuf)->file_left_pos: (pbuf)->last - (pbuf)->left_pos))
#define mln_chain_add(pphead,pptail,c) \
{\
if (*(pphead) == NULL) {\
*(pphead) = *(pptail) = (c);\
} else {\
(*(pptail))->next = (c);\
*(pptail) = (c);\
}\
}
extern mln_buf_t *mln_buf_new(mln_alloc_t *pool);
extern mln_chain_t *mln_chain_new(mln_alloc_t *pool);
extern void mln_buf_pool_release(mln_buf_t *b);
extern void mln_chain_pool_release(mln_chain_t *c);
extern void mln_chain_pool_release_all(mln_chain_t *c);
#endif
|
791b7072a7aa5296a8582fd3fed7e6cf879b397d
|
8f3bf2d3f72e9c7022b3e2efde3d787c9ca354fc
|
/test/integration/esys-tr-getTpmHandle-nv.int.c
|
62291868d43f068ec8906d9a1802d75196eb66d3
|
[
"BSD-2-Clause"
] |
permissive
|
tpm2-software/tpm2-tss
|
27dc9cddb545a04958c29839a9cdafb0df54ff3c
|
b7bad346b4b55def7fd1cd78c8724df00dddd76c
|
refs/heads/master
| 2023-09-03T19:58:41.440023
| 2023-08-15T18:30:40
| 2023-08-16T07:09:48
| 38,320,020
| 563
| 311
|
BSD-2-Clause
| 2023-09-14T08:28:43
| 2015-06-30T16:21:57
|
C
|
UTF-8
|
C
| false
| false
| 2,600
|
c
|
esys-tr-getTpmHandle-nv.int.c
|
/* SPDX-License-Identifier: BSD-2-Clause */
/*******************************************************************************
* Copyright 2017-2018, Fraunhofer SIT sponsored by Infineon Technologies AG
* All rights reserved.
*******************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include "tss2_esys.h"
#include "esys_iutil.h"
#define LOGMODULE test
#include "util/log.h"
#include "util/aux_util.h"
/** This tests the Esys_TR_ToTPMPublic function by
* creating an NV index object and then attempting to retrieve
* the TPM2_HANDLE for it and validating that the handle is correct for the
* expected object type.
*
* Tested ESYS commands:
* - Esys_NV_DefineSpace() (M)
* - Esys_NV_UndefineSpace() (M)
* - Esys_TR_ToTPMPublic() (M)
*
* @param[in,out] ectx The ESYS_CONTEXT.
* @retval EXIT_FAILURE
* @retval EXIT_SUCCESS
*/
int
test_esys_tr_toTpmPublic_nv(ESYS_CONTEXT * ectx)
{
int rc = EXIT_FAILURE;
TSS2_RC r;
ESYS_TR nvHandle = ESYS_TR_NONE;
TPM2B_AUTH auth = {.size = 20,
.buffer={10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29}};
TPM2B_NV_PUBLIC publicInfo = {
.size = 0,
.nvPublic = {
.nvIndex =TPM2_NV_INDEX_FIRST,
.nameAlg = TPM2_ALG_SHA256,
.attributes = TPMA_NV_AUTHWRITE | TPMA_NV_AUTHREAD,
.authPolicy = {
.size = 0,
.buffer = {},
},
.dataSize = 1,
}
};
r = Esys_NV_DefineSpace(ectx, ESYS_TR_RH_OWNER,
ESYS_TR_PASSWORD, ESYS_TR_NONE, ESYS_TR_NONE,
&auth, &publicInfo, &nvHandle);
goto_if_error(r, "NV define space", out);
/* the handle should be NV */
TPM2_HANDLE tpmHandle = ESYS_TR_NONE;
r = Esys_TR_GetTpmHandle(ectx, nvHandle, &tpmHandle);
goto_if_error(r, "Esys_TR_ToTPMPublic", error);
if (!(tpmHandle & TPM2_HR_NV_INDEX)) {
LOG_ERROR("Retrieved handle should be NV, got: 0x%x", tpmHandle);
goto error;
}
rc = EXIT_SUCCESS;
error:
r = Esys_NV_UndefineSpace(ectx, ESYS_TR_RH_OWNER, nvHandle,
ESYS_TR_PASSWORD, ESYS_TR_NONE, ESYS_TR_NONE);
if (r != TSS2_RC_SUCCESS) {
LOG_ERROR("NV UndefineSpace");
rc = EXIT_FAILURE;
}
out:
return rc;
}
int
test_invoke_esys(ESYS_CONTEXT * esys_context) {
return test_esys_tr_toTpmPublic_nv(esys_context);
}
|
730fe5e12e6f631f3a6bc61caca61a9faa7b9fc7
|
e910318d01528d82040507a49eeeb8dade45b31f
|
/ports/minimal/mphalport.h
|
5130d19a24ac5fef6608239a86faa40b4689cad7
|
[
"MIT"
] |
permissive
|
pfalcon/pycopy
|
e844480a5e5cd463530328889daed2ba87552b8a
|
3ac90ae9c3c6bbebfba9cada2d37025e35c62796
|
refs/heads/pfalcon
| 2023-08-30T09:39:52.290147
| 2022-09-08T16:42:38
| 2022-09-08T16:42:38
| 15,507,576
| 753
| 71
|
MIT
| 2021-05-08T04:59:21
| 2013-12-29T11:38:47
|
C
|
UTF-8
|
C
| false
| false
| 121
|
h
|
mphalport.h
|
static inline mp_uint_t mp_hal_ticks_ms(void) {
return 0;
}
static inline void mp_hal_set_interrupt_char(char c) {
}
|
87a32bc94837318c88c40f546feb18ba5aba93ae
|
56df646849b0cb65e5980beca86ba852a92130b3
|
/Apps/02-HelloCube/Shaders/HelloCubeUniforms.h
|
98aa4604d8513fde7a0fd4f5b54d54d28aab26de
|
[
"Apache-2.0"
] |
permissive
|
egorodet/MethaneKit
|
fbf9cf6acf501886175d9abb156f023e774d4453
|
a8fe4ae985174e648adb356dccfa36d3b1a16a24
|
refs/heads/master
| 2023-08-28T21:02:12.570098
| 2023-08-06T20:45:53
| 2023-08-06T20:45:53
| 175,065,270
| 561
| 21
| null | null | null | null |
UTF-8
|
C
| false
| false
| 615
|
h
|
HelloCubeUniforms.h
|
/******************************************************************************
Copyright 2021 Evgeny Gorodetskiy
Licensed under the Apache License, Version 2.0
*******************************************************************************
FILE: MethaneKit/Apps/Tutorials/02-HelloCubeUniforms/Shaders/HelloCubeUniforms.h
Shader uniform structure shared between HLSL and C++ code via HLSL++
******************************************************************************/
#ifndef HELLO_CUBE_UNIFORMS_H
#define HELLO_CUBE_UNIFORMS_H
struct Uniforms
{
float4x4 mvp_matrix;
};
#endif // HELLO_CUBE_UNIFORMS_H
|
61de59d82a709977103770a78a9030a798d8a14d
|
bdf358386d2669d01be07865051646135f6d4c64
|
/tst/test_multiset.c
|
53434516a444e2fee2f875e18d52aea968370012
|
[
"MIT"
] |
permissive
|
bkthomps/Containers
|
591bbcc075b9484b4c9aa59ab0ecd879851edb00
|
5f222507b077b8e223cc56d0c57a6ef4ea29b5f5
|
refs/heads/master
| 2022-06-23T08:50:40.631232
| 2022-06-12T18:43:04
| 2022-06-12T18:43:04
| 106,978,489
| 201
| 23
|
MIT
| 2022-06-12T18:43:05
| 2017-10-15T02:43:17
|
C
|
UTF-8
|
C
| false
| false
| 18,612
|
c
|
test_multiset.c
|
#include "test.h"
#include "../src/include/multiset.h"
/*
* Include this to verify the tree.
*/
struct internal_multiset {
size_t size;
size_t key_size;
int (*comparator)(const void *const one, const void *const two);
char *root;
};
/*
* Include this to verify the tree.
*/
static const size_t ptr_size = sizeof(char *);
/* static const size_t count_size = sizeof(size_t); */
/* Node balance is always the first byte (at index 0). */
/* static const size_t node_count_offset = sizeof(signed char); */
static const size_t node_parent_offset = 1 + sizeof(size_t);
static const size_t node_left_child_offset =
1 + sizeof(size_t) + sizeof(char *);
static const size_t node_right_child_offset =
1 + sizeof(size_t) + 2 * sizeof(char *);
static const size_t node_key_offset = 1 + sizeof(size_t) + 3 * sizeof(char *);
/*
* Verifies that the AVL tree rules are followed. The balance factor of an item
* must be the right height minus the left height. Also, the left key must be
* less than the right key.
*/
static int multiset_verify_recursive(char *const item)
{
int left;
int right;
int max;
char *item_left;
char *item_right;
if (!item) {
return 0;
}
memcpy(&item_left, item + node_left_child_offset, ptr_size);
memcpy(&item_right, item + node_right_child_offset, ptr_size);
left = multiset_verify_recursive(item_left);
right = multiset_verify_recursive(item_right);
max = left > right ? left : right;
assert(right - left == item[0]);
if (item_left && item_right) {
const int left_val = *(int *) (item_left + node_key_offset);
const int right_val = *(int *) (item_right + node_key_offset);
assert(left_val < right_val);
}
if (item_left) {
char *item_left_parent;
memcpy(&item_left_parent, item_left + node_parent_offset, ptr_size);
assert(item_left_parent == item);
assert(item_left_parent + node_key_offset == item + node_key_offset);
}
if (item_right) {
char *item_right_parent;
memcpy(&item_right_parent, item_right + node_parent_offset, ptr_size);
assert(item_right_parent == item);
assert(item_right_parent + node_key_offset == item + node_key_offset);
}
return max + 1;
}
static size_t multiset_compute_size(char *const item)
{
char *left;
char *right;
if (!item) {
return 0;
}
memcpy(&left, item + node_left_child_offset, ptr_size);
memcpy(&right, item + node_right_child_offset, ptr_size);
return 1 + multiset_compute_size(left) + multiset_compute_size(right);
}
static void multiset_verify(multiset me)
{
multiset_verify_recursive(me->root);
assert(multiset_compute_size(me->root) == multiset_size(me));
}
static int compare_int(const void *const one, const void *const two)
{
const int a = *(int *) one;
const int b = *(int *) two;
return a - b;
}
static void test_invalid_init(void)
{
const size_t max_size = -1;
assert(!multiset_init(0, compare_int));
assert(!multiset_init(sizeof(int), NULL));
assert(!multiset_init(max_size, compare_int));
}
static void mutation_order(multiset me, const int *const arr, const int size)
{
int i;
size_t actual_size = 0;
assert(multiset_is_empty(me));
for (i = 0; i < size; i++) {
int num = arr[i];
if (num > 0) {
assert(multiset_put(me, &num) == 0);
actual_size++;
} else {
int actual_num = -1 * num;
assert(multiset_remove(me, &actual_num));
actual_size--;
}
}
assert(multiset_size(me) == actual_size);
multiset_verify(me);
}
/*
* Targets the (child->balance == 0) branch.
*/
static void test_rotate_left_balanced_child(multiset me)
{
int i;
int arr[] = {2, 4, 1, 3, 5, -1};
int size = sizeof(arr) / sizeof(arr[0]);
mutation_order(me, arr, size);
for (i = 2; i <= 5; i++) {
assert(multiset_contains(me, &i));
}
}
/*
* Targets the else branch.
*/
static void test_rotate_left_unbalanced_child(multiset me)
{
int i;
int arr[] = {1, 2, 3};
int size = sizeof(arr) / sizeof(arr[0]);
mutation_order(me, arr, size);
for (i = 1; i <= 3; i++) {
assert(multiset_contains(me, &i));
}
}
/*
* Targets (parent->balance == 2 && child->balance >= 0) in the multiset_repair
* function.
*/
static void test_rotate_left(void)
{
multiset me = multiset_init(sizeof(int), compare_int);
assert(me);
test_rotate_left_balanced_child(me);
multiset_clear(me);
test_rotate_left_unbalanced_child(me);
assert(!multiset_destroy(me));
}
/*
* Targets the (child->balance == 0) branch.
*/
static void test_rotate_right_balanced_child(multiset me)
{
int i;
int arr[] = {4, 2, 5, 1, 3, -5};
int size = sizeof(arr) / sizeof(arr[0]);
mutation_order(me, arr, size);
for (i = 1; i <= 4; i++) {
assert(multiset_contains(me, &i));
}
}
/*
* Targets the else branch.
*/
static void test_rotate_right_unbalanced_child(multiset me)
{
int i;
int arr[] = {3, 2, 1};
int size = sizeof(arr) / sizeof(arr[0]);
mutation_order(me, arr, size);
for (i = 1; i <= 3; i++) {
assert(multiset_contains(me, &i));
}
}
/*
* Targets (parent->balance == -2 && child->balance <= 0) in the multiset_repair
* function.
*/
static void test_rotate_right(void)
{
multiset me = multiset_init(sizeof(int), compare_int);
assert(me);
test_rotate_right_balanced_child(me);
multiset_clear(me);
test_rotate_right_unbalanced_child(me);
assert(!multiset_destroy(me));
}
/*
* Targets the (grand_child->balance == 1) branch.
*/
static void test_rotate_left_right_positively_balanced_grand_child(multiset me)
{
int i;
int arr[] = {5, 2, 6, 1, 3, 4};
int size = sizeof(arr) / sizeof(arr[0]);
mutation_order(me, arr, size);
for (i = 1; i <= 6; i++) {
assert(multiset_contains(me, &i));
}
}
/*
* Targets the (grand_child->balance == 0) branch.
*/
static void test_rotate_left_right_neutral_balanced_grand_child(multiset me)
{
int i;
int arr[] = {3, 1, 2};
int size = sizeof(arr) / sizeof(arr[0]);
mutation_order(me, arr, size);
for (i = 1; i <= 3; i++) {
assert(multiset_contains(me, &i));
}
}
/*
* Targets the else branch.
*/
static void test_rotate_left_right_negatively_balanced_grand_child(multiset me)
{
int i;
int arr[] = {5, 2, 6, 1, 4, 3};
int size = sizeof(arr) / sizeof(arr[0]);
mutation_order(me, arr, size);
for (i = 1; i <= 6; i++) {
assert(multiset_contains(me, &i));
}
}
/*
* Targets (parent->balance == -2 && child->balance == 1) in the multiset_repair
* function.
*/
static void test_rotate_left_right(void)
{
multiset me = multiset_init(sizeof(int), compare_int);
assert(me);
test_rotate_left_right_positively_balanced_grand_child(me);
multiset_clear(me);
test_rotate_left_right_neutral_balanced_grand_child(me);
multiset_clear(me);
test_rotate_left_right_negatively_balanced_grand_child(me);
assert(!multiset_destroy(me));
}
/*
* Targets the (grand_child->balance == 1) branch.
*/
static void test_rotate_right_left_positively_balanced_grand_child(multiset me)
{
int i;
int arr[] = {2, 1, 5, 3, 6, 4};
int size = sizeof(arr) / sizeof(arr[0]);
mutation_order(me, arr, size);
for (i = 1; i <= 6; i++) {
assert(multiset_contains(me, &i));
}
}
/*
* Targets the (grand_child->balance == 0) branch.
*/
static void test_rotate_right_left_neutral_balanced_grand_child(multiset me)
{
int i;
int arr[] = {1, 3, 2};
int size = sizeof(arr) / sizeof(arr[0]);
mutation_order(me, arr, size);
for (i = 1; i <= 3; i++) {
assert(multiset_contains(me, &i));
}
}
/*
* Targets the else branch.
*/
static void test_rotate_right_left_negatively_balanced_grand_child(multiset me)
{
int i;
int arr[] = {2, 1, 5, 4, 6, 3};
int size = sizeof(arr) / sizeof(arr[0]);
mutation_order(me, arr, size);
for (i = 1; i <= 6; i++) {
assert(multiset_contains(me, &i));
}
}
/*
* Targets (parent->balance == 2 && child->balance == -1) in the multiset_repair
* function.
*/
static void test_rotate_right_left(void)
{
multiset me = multiset_init(sizeof(int), compare_int);
assert(me);
test_rotate_right_left_positively_balanced_grand_child(me);
multiset_clear(me);
test_rotate_right_left_neutral_balanced_grand_child(me);
multiset_clear(me);
test_rotate_right_left_negatively_balanced_grand_child(me);
assert(!multiset_destroy(me));
}
/*
* Targets the multiset_repair function.
*/
static void test_auto_balancing(void)
{
test_rotate_left();
test_rotate_right();
test_rotate_left_right();
test_rotate_right_left();
}
static void test_put_already_existing(void)
{
int key = 5;
multiset me = multiset_init(sizeof(int), compare_int);
assert(me);
assert(multiset_size(me) == 0);
multiset_put(me, &key);
assert(multiset_size(me) == 1);
multiset_put(me, &key);
assert(multiset_size(me) == 2);
assert(!multiset_destroy(me));
}
static void test_remove_nothing(void)
{
int key;
multiset me = multiset_init(sizeof(int), compare_int);
assert(me);
key = 3;
multiset_put(me, &key);
key = 5;
assert(!multiset_remove(me, &key));
assert(!multiset_destroy(me));
}
static void test_contains(void)
{
int key;
multiset me = multiset_init(sizeof(int), compare_int);
assert(me);
key = 7;
assert(!multiset_contains(me, &key));
key = 3;
multiset_put(me, &key);
key = 1;
multiset_put(me, &key);
key = 5;
multiset_put(me, &key);
key = 0;
assert(!multiset_contains(me, &key));
key = 1;
assert(multiset_contains(me, &key));
key = 2;
assert(!multiset_contains(me, &key));
key = 3;
assert(multiset_contains(me, &key));
key = 4;
assert(!multiset_contains(me, &key));
key = 5;
assert(multiset_contains(me, &key));
key = 6;
assert(!multiset_contains(me, &key));
assert(!multiset_destroy(me));
}
static void test_stress_add(void)
{
size_t count = 0;
int flip = 0;
int i;
multiset me = multiset_init(sizeof(int), compare_int);
assert(me);
for (i = 1234; i < 82400; i++) {
int num = i % 765;
multiset_put(me, &num);
assert(multiset_contains(me, &num));
count++;
if (i == 1857 && !flip) {
i *= -1;
flip = 1;
}
}
assert(count == multiset_size(me));
assert(!multiset_destroy(me));
}
static void test_stress_remove(void)
{
int i;
multiset me = multiset_init(sizeof(int), compare_int);
assert(me);
for (i = 8123; i < 12314; i += 3) {
multiset_put(me, &i);
assert(multiset_contains(me, &i));
}
for (i = 13000; i > 8000; i--) {
multiset_remove(me, &i);
assert(!multiset_contains(me, &i));
}
assert(!multiset_destroy(me));
}
static void test_unique_delete_one_child(multiset me)
{
int arr1[] = {2, 1, -2};
int arr2[] = {1, 2, -1};
int arr3[] = {3, 2, 4, 1, -2};
int arr4[] = {3, 1, 4, 2, -1};
int arr5[] = {3, 1, 4, 2, -4};
int arr6[] = {2, 1, 3, 4, -3};
int sz1 = sizeof(arr1) / sizeof(arr1[0]);
int sz2 = sizeof(arr2) / sizeof(arr2[0]);
int sz3 = sizeof(arr3) / sizeof(arr3[0]);
int sz4 = sizeof(arr4) / sizeof(arr4[0]);
int sz5 = sizeof(arr5) / sizeof(arr5[0]);
int sz6 = sizeof(arr6) / sizeof(arr6[0]);
mutation_order(me, arr1, sz1);
multiset_clear(me);
mutation_order(me, arr2, sz2);
multiset_clear(me);
mutation_order(me, arr3, sz3);
multiset_clear(me);
mutation_order(me, arr4, sz4);
multiset_clear(me);
mutation_order(me, arr5, sz5);
multiset_clear(me);
mutation_order(me, arr6, sz6);
}
static void test_unique_delete_two_children(multiset me)
{
int arr1[] = {2, 1, 3, -2};
int arr2[] = {4, 2, 5, 1, 3, -2};
int arr3[] = {2, 1, 4, 3, 5, -4};
int sz1 = sizeof(arr1) / sizeof(arr1[0]);
int sz2 = sizeof(arr2) / sizeof(arr2[0]);
int sz3 = sizeof(arr3) / sizeof(arr3[0]);
mutation_order(me, arr1, sz1);
multiset_clear(me);
mutation_order(me, arr2, sz2);
multiset_clear(me);
mutation_order(me, arr3, sz3);
}
static void test_unique_deletion_patterns(void)
{
multiset me = multiset_init(sizeof(int), compare_int);
assert(me);
test_unique_delete_one_child(me);
multiset_clear(me);
test_unique_delete_two_children(me);
assert(!multiset_destroy(me));
}
static void test_multiple_operations(void)
{
int key = 5;
multiset me = multiset_init(sizeof(int), compare_int);
assert(me);
assert(multiset_count(me, &key) == 0);
assert(!multiset_remove_all(me, &key));
multiset_put(me, &key);
multiset_put(me, &key);
assert(multiset_size(me) == 2);
key = 7;
multiset_put(me, &key);
assert(multiset_size(me) == 3);
assert(multiset_count(me, &key) == 1);
key = 5;
assert(multiset_count(me, &key) == 2);
assert(multiset_size(me) == 3);
assert(multiset_remove(me, &key));
assert(multiset_count(me, &key) == 1);
assert(multiset_size(me) == 2);
assert(multiset_remove(me, &key));
assert(multiset_count(me, &key) == 0);
assert(multiset_size(me) == 1);
multiset_remove_all(me, &key);
assert(multiset_size(me) == 1);
key = 7;
multiset_remove_all(me, &key);
assert(multiset_size(me) == 0);
assert(!multiset_destroy(me));
}
#if STUB_MALLOC
static void test_init_out_of_memory(void)
{
fail_malloc = 1;
assert(!multiset_init(sizeof(int), compare_int));
}
#endif
#if STUB_MALLOC
static void test_put_root_out_of_memory(multiset me)
{
int key = 2;
fail_malloc = 1;
assert(multiset_put(me, &key) == -ENOMEM);
}
#endif
#if STUB_MALLOC
static void test_put_on_left_out_of_memory(multiset me)
{
int key = 1;
fail_malloc = 1;
assert(multiset_put(me, &key) == -ENOMEM);
}
#endif
#if STUB_MALLOC
static void test_put_on_right_out_of_memory(multiset me)
{
int key = 3;
fail_malloc = 1;
assert(multiset_put(me, &key) == -ENOMEM);
}
#endif
#if STUB_MALLOC
static void test_put_out_of_memory(void)
{
int key = 2;
multiset me = multiset_init(sizeof(int), compare_int);
assert(me);
test_put_root_out_of_memory(me);
assert(multiset_put(me, &key) == 0);
test_put_on_left_out_of_memory(me);
test_put_on_right_out_of_memory(me);
assert(!multiset_destroy(me));
}
#endif
struct big_object {
int n;
double d;
signed char c[8];
};
static int compare_big_object(const void *const one, const void *const two)
{
const struct big_object *const a = one;
const struct big_object *const b = two;
return a->n - b->n;
}
static void test_big_object(void)
{
int i;
multiset me = multiset_init(sizeof(struct big_object), compare_big_object);
assert(me);
for (i = 0; i < 16; i++) {
int j;
struct big_object b;
b.n = INT_MIN + i;
b.d = i + 0.5;
for (j = 0; j < 8; j++) {
b.c[j] = (signed char) (SCHAR_MIN + i + j);
}
assert(multiset_put(me, &b) == 0);
b.n = -1;
b.d = -1;
for (j = 0; j < 8; j++) {
b.c[j] = -1;
}
}
for (i = 0; i < 16; i++) {
int j;
struct big_object b;
b.n = INT_MIN + i;
b.d = i + 0.5;
for (j = 0; j < 8; j++) {
b.c[j] = (signed char) (SCHAR_MIN + i + j);
}
assert(multiset_contains(me, &b) == 1);
assert(b.n == INT_MIN + i);
assert(b.d == i + 0.5);
for (j = 0; j < 8; j++) {
assert(b.c[j] == SCHAR_MIN + i + j);
}
}
assert(!multiset_destroy(me));
}
static void test_ordered_retrieval(void)
{
int *get;
int val = 4;
multiset me = multiset_init(sizeof(int), compare_int);
assert(!multiset_first(me));
assert(!multiset_last(me));
assert(multiset_put(me, &val) == BK_OK);
get = multiset_first(me);
assert(val == *get);
get = multiset_last(me);
assert(val == *get);
val = 5;
assert(multiset_put(me, &val) == BK_OK);
val = 3;
assert(multiset_put(me, &val) == BK_OK);
get = multiset_first(me);
assert(3 == *get);
get = multiset_last(me);
assert(5 == *get);
/* Lower tests */
val = 7;
get = multiset_lower(me, &val);
assert(5 == *get);
val = 6;
get = multiset_lower(me, &val);
assert(5 == *get);
val = 5;
get = multiset_lower(me, &val);
assert(4 == *get);
val = 4;
get = multiset_lower(me, &val);
assert(3 == *get);
val = 3;
get = multiset_lower(me, &val);
assert(!get);
/* Higher tests */
val = 1;
get = multiset_higher(me, &val);
assert(3 == *get);
val = 2;
get = multiset_higher(me, &val);
assert(3 == *get);
val = 3;
get = multiset_higher(me, &val);
assert(4 == *get);
val = 4;
get = multiset_higher(me, &val);
assert(5 == *get);
val = 5;
get = multiset_higher(me, &val);
assert(!get);
/* Floor tests */
val = 7;
get = multiset_floor(me, &val);
assert(5 == *get);
val = 6;
get = multiset_floor(me, &val);
assert(5 == *get);
val = 5;
get = multiset_floor(me, &val);
assert(5 == *get);
val = 4;
get = multiset_floor(me, &val);
assert(4 == *get);
val = 3;
get = multiset_floor(me, &val);
assert(3 == *get);
val = 2;
get = multiset_floor(me, &val);
assert(!get);
/* Ceiling tests */
val = 1;
get = multiset_ceiling(me, &val);
assert(3 == *get);
val = 2;
get = multiset_ceiling(me, &val);
assert(3 == *get);
val = 3;
get = multiset_ceiling(me, &val);
assert(3 == *get);
val = 4;
get = multiset_ceiling(me, &val);
assert(4 == *get);
val = 5;
get = multiset_ceiling(me, &val);
assert(5 == *get);
val = 6;
get = multiset_ceiling(me, &val);
assert(!get);
multiset_destroy(me);
}
void test_multiset(void)
{
test_invalid_init();
test_auto_balancing();
test_put_already_existing();
test_remove_nothing();
test_contains();
test_stress_add();
test_stress_remove();
test_unique_deletion_patterns();
test_multiple_operations();
#if STUB_MALLOC
test_init_out_of_memory();
test_put_out_of_memory();
#endif
test_big_object();
test_ordered_retrieval();
multiset_destroy(NULL);
}
|
4fdecb515f14f859f5193b334213357670f0cce2
|
7be8e3636bf08ebdc6662879dc5afec548705537
|
/ios/Pods/Headers/Private/Flipper-Folly/folly/ssl/OpenSSLPtrTypes.h
|
c9a6663f75df7aea441e951213ae826dfe98d518
|
[
"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
| 56
|
h
|
OpenSSLPtrTypes.h
|
../../../../../Flipper-Folly/folly/ssl/OpenSSLPtrTypes.h
|
63c29fea6158e14de7be9bef2207eaa3a2f64704
|
01bcef56ade123623725ca78d233ac8653a91ece
|
/utils/shadercompile/shadercompile_ps3_helpers.h
|
44fed64c03c3506eb42cb89646e45bff7691ad31
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
SwagSoftware/Kisak-Strike
|
1085ba3c6003e622dac5ebc0c9424cb16ef58467
|
4c2fdc31432b4f5b911546c8c0d499a9cff68a85
|
refs/heads/master
| 2023-09-01T02:06:59.187775
| 2022-09-05T00:51:46
| 2022-09-05T00:51:46
| 266,676,410
| 921
| 123
| null | 2022-10-01T16:26:41
| 2020-05-25T03:41:35
|
C++
|
UTF-8
|
C
| false
| false
| 3,309
|
h
|
shadercompile_ps3_helpers.h
|
//============ Copyright (c) Valve Corporation, All rights reserved. ============
//
// Functionality to handle collation of shader debugging metadata
// (i.e. shader PDBs) sent from shadercompile workers to the master.
//
//===============================================================================
#pragma once
#ifndef SHADERCOMPILE_PS3_HELPERS_H
#define SHADERCOMPILE_PS3_HELPERS_H
#include "vmpi.h"
//-----------------------------------------------------------------------------
// The ID of the VMPI packet sent from workers to the master for each
// small PS3 shader debug metadata file generated by the Sony/Cg compiler.
//-----------------------------------------------------------------------------
#define PS3_SHADER_DEBUG_INFO_PACKETID 6
#define PS3_SHADER_COMPILE_LOG_PACKETID 11
//-----------------------------------------------------------------------------
// Structure of the packet corresponding to PS3_SHADER_DEBUG_INFO_PACKETID
//-----------------------------------------------------------------------------
struct PS3ShaderDebugInfoPacket_t
{
char m_PacketID; // This should be PS3_SHADER_DEBUG_INFO_PACKETID
int m_nFileNameLength;
int m_nFileDataLength;
// Followed by m_nFileNameLength + m_nFileDataLength bytes of data
};
//-----------------------------------------------------------------------------
// Handler for VMPI packet: PS3_SHADER_DEBUG_INFO_PACKETID.
// Called on the master when such a packet is received.
//-----------------------------------------------------------------------------
bool PS3ShaderDebugInfoDispatch( MessageBuffer *pBuf, int nSource, int nPacketID );
//-----------------------------------------------------------------------------
// Initializes the TOC and Pack files used to store the large amount
// of shader metadata generated by the worker machines.
// Called on the master.
//-----------------------------------------------------------------------------
void InitializePS3ShaderDebugPackFiles();
//-----------------------------------------------------------------------------
// Expand PS3 debug information that has been accumulated into giant pack
// files on the master's machine.
// These giant files expand into hundreds of thousands of tiny files
// required for shader debugging.
// Called on the master.
//-----------------------------------------------------------------------------
void ExpandPS3DebugInfo();
//-----------------------------------------------------------------------------
// Sends all files and non-empty directories to the VMPI master, one packet
// per file (see PS3_SHADER_DEBUG_INFO_PACKETID). Called by workers.
//-----------------------------------------------------------------------------
void SendSubDirectoryToMaster( const char *pStartingPath );
//-----------------------------------------------------------------------------
// Shader compile statistics log file
//-----------------------------------------------------------------------------
struct PS3ShaderCompileLogPacket_t
{
char m_PacketID; // This should be PS3_SHADER_COMPILE_LOG_PACKETID
int m_nPacketSize;
// Followed by m_nPacketSize bytes of data
};
void PS3SendShaderCompileLogContentsToMaster();
bool PS3ShaderCompileLogDispatch( MessageBuffer *pBuf, int nSource, int nPacketID );
#endif // SHADERCOMPILE_PS3_HELPERS_H
|
f033a20354438bc95f326a4c4f23078ae1c5db19
|
d02efc7755dc4c9e9b51bc11642b2127a7142c2a
|
/examples/03_displaytypes/02_glcd/LCDML_03021_u8g2lib/PlaformIO/src/LCDML_display_menu.h
|
12ffc16e55662ff91eb4d262d0a7168303177bf5
|
[
"MIT"
] |
permissive
|
Jomelo/LCDMenuLib2
|
cf34836b644e12070707ba563f65aac31d6fd5d1
|
99f09ac3a60962bb3a809899061c22c3d4449d03
|
refs/heads/master
| 2023-01-03T18:48:23.921234
| 2022-12-30T12:38:01
| 2022-12-30T12:38:01
| 108,138,897
| 233
| 50
|
MIT
| 2022-12-17T15:06:48
| 2017-10-24T14:30:45
|
C++
|
UTF-8
|
C
| false
| false
| 4,423
|
h
|
LCDML_display_menu.h
|
// =====================================================================
//
// Output function
//
// =====================================================================
/* ******************************************************************** */
void lcdml_menu_clear()
/* ******************************************************************** */
{
}
/* ******************************************************************** */
void lcdml_menu_display()
/* ******************************************************************** */
{
// for first test set font here
u8g2.setFont(_LCDML_DISP_font);
// declaration of some variables
// ***************
// content variable
char content_text[_LCDML_DISP_cols]; // save the content text of every menu element
// menu element object
LCDMenuLib2_menu *tmp;
// some limit values
uint8_t i = LCDML.MENU_getScroll();
uint8_t maxi = _LCDML_DISP_rows + i;
uint8_t n = 0;
// init vars
uint8_t n_max = (LCDML.MENU_getChilds() >= _LCDML_DISP_rows) ? _LCDML_DISP_rows : (LCDML.MENU_getChilds());
//uint8_t scrollbar_min = 0;
uint8_t scrollbar_max = LCDML.MENU_getChilds();
uint8_t scrollbar_cur_pos = LCDML.MENU_getCursorPosAbs();
//uint8_t scroll_pos = ((1.*n_max * _LCDML_DISP_rows) / (scrollbar_max - 1) * scrollbar_cur_pos);
// generate content
u8g2.firstPage();
do {
n = 0;
i = LCDML.MENU_getScroll();
// update content
// ***************
// clear menu
// ***************
// check if this element has children
if ((tmp = LCDML.MENU_getDisplayedObj()) != NULL)
{
// loop to display lines
do
{
// check if a menu element has a condition and if the condition be true
if (tmp->checkCondition())
{
// check the type off a menu element
if(tmp->checkType_menu() == true)
{
// display normal content
LCDML_getContent(content_text, tmp->getID());
u8g2.drawStr( _LCDML_DISP_box_x0+_LCDML_DISP_font_w + _LCDML_DISP_cur_space_behind, _LCDML_DISP_box_y0 + _LCDML_DISP_font_h * (n + 1), content_text);
}
else
{
if(tmp->checkType_dynParam()) {
tmp->callback(n);
}
}
// increment some values
i++;
n++;
}
// try to go to the next sibling and check the number of displayed rows
} while (((tmp = tmp->getSibling(1)) != NULL) && (i < maxi));
}
// set cursor
u8g2.drawStr( _LCDML_DISP_box_x0+_LCDML_DISP_cur_space_before, _LCDML_DISP_box_y0 + _LCDML_DISP_font_h * (LCDML.MENU_getCursorPos() + 1), _LCDML_DISP_cursor_char);
if(_LCDML_DISP_draw_frame == 1) {
u8g2.drawFrame(_LCDML_DISP_box_x0, _LCDML_DISP_box_y0, (_LCDML_DISP_box_x1-_LCDML_DISP_box_x0), (_LCDML_DISP_box_y1-_LCDML_DISP_box_y0));
}
// display scrollbar when more content as rows available and with > 2
if (scrollbar_max > n_max && _LCDML_DISP_scrollbar_w > 2)
{
// set frame for scrollbar
u8g2.drawFrame(_LCDML_DISP_box_x1 - _LCDML_DISP_scrollbar_w, _LCDML_DISP_box_y0, _LCDML_DISP_scrollbar_w, _LCDML_DISP_box_y1-_LCDML_DISP_box_y0);
// calculate scrollbar length
uint8_t scrollbar_block_length = scrollbar_max - n_max;
scrollbar_block_length = (_LCDML_DISP_box_y1-_LCDML_DISP_box_y0) / (scrollbar_block_length + _LCDML_DISP_rows);
//set scrollbar
if (scrollbar_cur_pos == 0) { // top position (min)
u8g2.drawBox(_LCDML_DISP_box_x1 - (_LCDML_DISP_scrollbar_w-1), _LCDML_DISP_box_y0 + 1 , (_LCDML_DISP_scrollbar_w-2) , scrollbar_block_length);
}
else if (scrollbar_cur_pos == (scrollbar_max-1)) { // bottom position (max)
u8g2.drawBox(_LCDML_DISP_box_x1 - (_LCDML_DISP_scrollbar_w-1), _LCDML_DISP_box_y1 - scrollbar_block_length , (_LCDML_DISP_scrollbar_w-2) , scrollbar_block_length);
}
else { // between top and bottom
u8g2.drawBox(_LCDML_DISP_box_x1 - (_LCDML_DISP_scrollbar_w-1), _LCDML_DISP_box_y0 + (scrollbar_block_length * scrollbar_cur_pos + 1),(_LCDML_DISP_scrollbar_w-2) , scrollbar_block_length);
}
}
} while ( u8g2.nextPage() );
}
|
02180e7dda652c9ea17f4ef79b71f2a77e64b2ac
|
a8b8e3d31b51fe3de9bfaa5c609af0c013744d85
|
/jsregexp.c
|
85c4a0df06844e43e1f430f40f3f108dcca67bbd
|
[
"ISC",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later"
] |
permissive
|
ccxvii/mujs
|
cec222f8c8d0642e78281af6a1f11c48ebe9a529
|
ddd770933bded000ad332f551892e061498e74d1
|
refs/heads/master
| 2023-08-16T05:09:41.914711
| 2023-05-08T10:36:05
| 2023-05-08T10:38:46
| 15,402,008
| 788
| 112
|
ISC
| 2023-07-20T09:19:21
| 2013-12-23T18:35:20
|
C
|
UTF-8
|
C
| false
| false
| 4,902
|
c
|
jsregexp.c
|
#include "jsi.h"
#include "regexp.h"
static char *escaperegexp(js_State *J, const char *pattern) {
char *copy, *p;
const char *s;
int n = 0;
for (s = pattern; *s; ++s) {
if (*s == '/')
++n;
++n;
}
copy = p = js_malloc(J, n+1);
for (s = pattern; *s; ++s) {
if (*s == '/')
*p++ = '\\';
*p++ = *s;
}
*p = 0;
return copy;
}
static void js_newregexpx(js_State *J, const char *pattern, int flags, int is_clone)
{
const char *error;
js_Object *obj;
Reprog *prog;
int opts;
obj = jsV_newobject(J, JS_CREGEXP, J->RegExp_prototype);
opts = 0;
if (flags & JS_REGEXP_I) opts |= REG_ICASE;
if (flags & JS_REGEXP_M) opts |= REG_NEWLINE;
prog = js_regcompx(J->alloc, J->actx, pattern, opts, &error);
if (!prog)
js_syntaxerror(J, "regular expression: %s", error);
obj->u.r.prog = prog;
obj->u.r.source = is_clone ? js_strdup(J, pattern) : escaperegexp(J, pattern);
obj->u.r.flags = flags;
obj->u.r.last = 0;
js_pushobject(J, obj);
}
void js_newregexp(js_State *J, const char *pattern, int flags)
{
js_newregexpx(J, pattern, flags, 0);
}
void js_RegExp_prototype_exec(js_State *J, js_Regexp *re, const char *text)
{
const char *haystack;
int result;
int i;
int opts;
Resub m;
haystack = text;
opts = 0;
if (re->flags & JS_REGEXP_G) {
if (re->last > strlen(haystack)) {
re->last = 0;
js_pushnull(J);
return;
}
if (re->last > 0) {
haystack = text + re->last;
opts |= REG_NOTBOL;
}
}
result = js_regexec(re->prog, haystack, &m, opts);
if (result < 0)
js_error(J, "regexec failed");
if (result == 0) {
js_newarray(J);
js_pushstring(J, text);
js_setproperty(J, -2, "input");
js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp));
js_setproperty(J, -2, "index");
for (i = 0; i < m.nsub; ++i) {
js_pushlstring(J, m.sub[i].sp, m.sub[i].ep - m.sub[i].sp);
js_setindex(J, -2, i);
}
if (re->flags & JS_REGEXP_G)
re->last = m.sub[0].ep - text;
return;
}
if (re->flags & JS_REGEXP_G)
re->last = 0;
js_pushnull(J);
}
static void Rp_test(js_State *J)
{
js_Regexp *re;
const char *text;
int result;
int opts;
Resub m;
re = js_toregexp(J, 0);
text = js_tostring(J, 1);
opts = 0;
if (re->flags & JS_REGEXP_G) {
if (re->last > strlen(text)) {
re->last = 0;
js_pushboolean(J, 0);
return;
}
if (re->last > 0) {
text += re->last;
opts |= REG_NOTBOL;
}
}
result = js_regexec(re->prog, text, &m, opts);
if (result < 0)
js_error(J, "regexec failed");
if (result == 0) {
if (re->flags & JS_REGEXP_G)
re->last = re->last + (m.sub[0].ep - text);
js_pushboolean(J, 1);
return;
}
if (re->flags & JS_REGEXP_G)
re->last = 0;
js_pushboolean(J, 0);
}
static void jsB_new_RegExp(js_State *J)
{
js_Regexp *old;
const char *pattern;
int flags;
int is_clone = 0;
if (js_isregexp(J, 1)) {
if (js_isdefined(J, 2))
js_typeerror(J, "cannot supply flags when creating one RegExp from another");
old = js_toregexp(J, 1);
pattern = old->source;
flags = old->flags;
is_clone = 1;
} else if (js_isundefined(J, 1)) {
pattern = "(?:)";
flags = 0;
} else {
pattern = js_tostring(J, 1);
flags = 0;
}
if (strlen(pattern) == 0)
pattern = "(?:)";
if (js_isdefined(J, 2)) {
const char *s = js_tostring(J, 2);
int g = 0, i = 0, m = 0;
while (*s) {
if (*s == 'g') ++g;
else if (*s == 'i') ++i;
else if (*s == 'm') ++m;
else js_syntaxerror(J, "invalid regular expression flag: '%c'", *s);
++s;
}
if (g > 1) js_syntaxerror(J, "invalid regular expression flag: 'g'");
if (i > 1) js_syntaxerror(J, "invalid regular expression flag: 'i'");
if (m > 1) js_syntaxerror(J, "invalid regular expression flag: 'm'");
if (g) flags |= JS_REGEXP_G;
if (i) flags |= JS_REGEXP_I;
if (m) flags |= JS_REGEXP_M;
}
js_newregexpx(J, pattern, flags, is_clone);
}
static void jsB_RegExp(js_State *J)
{
if (js_isregexp(J, 1))
return;
jsB_new_RegExp(J);
}
static void Rp_toString(js_State *J)
{
js_Regexp *re;
char * volatile out = NULL;
re = js_toregexp(J, 0);
if (js_try(J)) {
js_free(J, out);
js_throw(J);
}
out = js_malloc(J, strlen(re->source) + 6); /* extra space for //gim */
strcpy(out, "/");
strcat(out, re->source);
strcat(out, "/");
if (re->flags & JS_REGEXP_G) strcat(out, "g");
if (re->flags & JS_REGEXP_I) strcat(out, "i");
if (re->flags & JS_REGEXP_M) strcat(out, "m");
js_pop(J, 0);
js_pushstring(J, out);
js_endtry(J);
js_free(J, out);
}
static void Rp_exec(js_State *J)
{
js_RegExp_prototype_exec(J, js_toregexp(J, 0), js_tostring(J, 1));
}
void jsB_initregexp(js_State *J)
{
js_pushobject(J, J->RegExp_prototype);
{
jsB_propf(J, "RegExp.prototype.toString", Rp_toString, 0);
jsB_propf(J, "RegExp.prototype.test", Rp_test, 0);
jsB_propf(J, "RegExp.prototype.exec", Rp_exec, 0);
}
js_newcconstructor(J, jsB_RegExp, jsB_new_RegExp, "RegExp", 1);
js_defglobal(J, "RegExp", JS_DONTENUM);
}
|
dca88a272160d04fb816bd8f82ff0d68690ff24e
|
971b2cea2d1c3001aadc8ca1a48110b7db1ed5f2
|
/deps/abc/src/proof/acec/acecFadds.c
|
a2bdcfbebcd99f88f273609aecb6950b61240ae2
|
[
"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
| 47,061
|
c
|
acecFadds.c
|
/**CFile****************************************************************
FileName [acecFadds.c]
SystemName [ABC: Logic synthesis and verification system.]
PackageName [CEC for arithmetic circuits.]
Synopsis [Detecting half-adders and full-adders.]
Author [Alan Mishchenko]
Affiliation [UC Berkeley]
Date [Ver. 1.0. Started - June 20, 2005.]
Revision [$Id: acecFadds.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $]
***********************************************************************/
#include "acecInt.h"
#include "misc/vec/vecWec.h"
#include "misc/tim/tim.h"
ABC_NAMESPACE_IMPL_START
////////////////////////////////////////////////////////////////////////
/// DECLARATIONS ///
////////////////////////////////////////////////////////////////////////
#define Dtc_ForEachCut( pList, pCut, i ) for ( i = 0, pCut = pList + 1; i < pList[0]; i++, pCut += pCut[0] + 1 )
#define Dtc_ForEachFadd( vFadds, i ) for ( i = 0; i < Vec_IntSize(vFadds)/5; i++ )
////////////////////////////////////////////////////////////////////////
/// FUNCTION DEFINITIONS ///
////////////////////////////////////////////////////////////////////////
/**Function*************************************************************
Synopsis [Detecting HADDs in the AIG.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Vec_Int_t * Gia_ManDetectHalfAdders( Gia_Man_t * p, int fVerbose )
{
Vec_Int_t * vHadds = Vec_IntAlloc( 1000 );
Gia_Obj_t * pObj, * pFan0, * pFan1;
int i, iLit, iFan0, iFan1, fComplDiff, Count, Counts[5] = {0};
Gia_ManHashStart( p );
if ( p->nXors )
{
Gia_ManForEachAnd( p, pObj, i )
{
if ( !Gia_ObjIsXor(pObj) )
continue;
Count = 0;
iFan0 = Gia_ObjFaninId0(pObj, i);
iFan1 = Gia_ObjFaninId1(pObj, i);
if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 0), Abc_Var2Lit(iFan1, 0))) )
Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 1), Abc_Var2Lit(iFan1, 1))) )
Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 0), Abc_Var2Lit(iFan1, 1))) )
Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 1), Abc_Var2Lit(iFan1, 0))) )
Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
Counts[Count]++;
}
}
else
{
ABC_FREE( p->pRefs );
Gia_ManCreateRefs( p );
Gia_ManForEachAnd( p, pObj, i )
{
if ( !Gia_ObjRecognizeExor(pObj, &pFan0, &pFan1) )
continue;
Count = 0;
if ( Gia_ObjRefNumId(p, Gia_ObjFaninId0(pObj, i)) > 1 )
Vec_IntPushTwo( vHadds, i, Gia_ObjFaninId0(pObj, i) ), Count++;
if ( Gia_ObjRefNumId(p, Gia_ObjFaninId1(pObj, i)) > 1 )
Vec_IntPushTwo( vHadds, i, Gia_ObjFaninId1(pObj, i) ), Count++;
iFan0 = Gia_ObjId( p, pFan0 );
iFan1 = Gia_ObjId( p, pFan1 );
fComplDiff = (Gia_ObjFaninC0(Gia_ObjFanin0(pObj)) ^ Gia_ObjFaninC1(Gia_ObjFanin0(pObj)));
assert( fComplDiff == (Gia_ObjFaninC0(Gia_ObjFanin1(pObj)) ^ Gia_ObjFaninC1(Gia_ObjFanin1(pObj))) );
if ( fComplDiff )
{
if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 0), Abc_Var2Lit(iFan1, 0))) )
Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 1), Abc_Var2Lit(iFan1, 1))) )
Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
}
else
{
if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 0), Abc_Var2Lit(iFan1, 1))) )
Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 1), Abc_Var2Lit(iFan1, 0))) )
Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
}
Counts[Count]++;
}
ABC_FREE( p->pRefs );
}
Gia_ManHashStop( p );
if ( fVerbose )
{
int iXor, iAnd;
printf( "Found %d half-adders with XOR gates: ", Vec_IntSize(vHadds)/2 );
for ( i = 0; i <= 4; i++ )
printf( "%d=%d ", i, Counts[i] );
printf( "\n" );
Vec_IntForEachEntryDouble( vHadds, iXor, iAnd, i )
{
pObj = Gia_ManObj( p, iXor );
printf( "%3d : %5d %5d -> %5d %5d\n", i, Gia_ObjFaninId0(pObj, iXor), Gia_ObjFaninId1(pObj, iXor), iXor, iAnd );
}
}
return vHadds;
}
/**Function*************************************************************
Synopsis [Derive GIA with boxes containing adder-chains.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Gia_ManIllustrateBoxes( Gia_Man_t * p )
{
Tim_Man_t * pManTime = (Tim_Man_t *)p->pManTime;
int nBoxes = Tim_ManBoxNum( pManTime );
int i, k, curCi, curCo, nBoxIns, nBoxOuts;
Gia_Obj_t * pObj;
// walk through the boxes
curCi = Tim_ManPiNum(pManTime);
curCo = 0;
for ( i = 0; i < nBoxes; i++ )
{
nBoxIns = Tim_ManBoxInputNum(pManTime, i);
nBoxOuts = Tim_ManBoxOutputNum(pManTime, i);
printf( "Box %4d [%d x %d] : ", i, nBoxIns, nBoxOuts );
printf( "Input obj IDs = " );
for ( k = 0; k < nBoxIns; k++ )
{
pObj = Gia_ManCo( p, curCo + k );
printf( "%d ", Gia_ObjId(p, pObj) );
}
printf( " Output obj IDs = " );
for ( k = 0; k < nBoxOuts; k++ )
{
pObj = Gia_ManCi( p, curCi + k );
printf( "%d ", Gia_ObjId(p, pObj) );
}
curCo += nBoxIns;
curCi += nBoxOuts;
printf( "\n" );
}
curCo += Tim_ManPoNum(pManTime);
// verify counts
assert( curCi == Gia_ManCiNum(p) );
assert( curCo == Gia_ManCoNum(p) );
}
/**Function*************************************************************
Synopsis [Detecting FADDs in the AIG.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Dtc_ManCutMergeOne( int * pCut0, int * pCut1, int * pCut )
{
int i, k;
for ( k = 0; k <= pCut1[0]; k++ )
pCut[k] = pCut1[k];
for ( i = 1; i <= pCut0[0]; i++ )
{
for ( k = 1; k <= pCut1[0]; k++ )
if ( pCut0[i] == pCut1[k] )
break;
if ( k <= pCut1[0] )
continue;
if ( pCut[0] == 3 )
return 0;
pCut[1+pCut[0]++] = pCut0[i];
}
assert( pCut[0] == 2 || pCut[0] == 3 );
if ( pCut[1] > pCut[2] )
ABC_SWAP( int, pCut[1], pCut[2] );
assert( pCut[1] < pCut[2] );
if ( pCut[0] == 2 )
return 1;
if ( pCut[2] > pCut[3] )
ABC_SWAP( int, pCut[2], pCut[3] );
if ( pCut[1] > pCut[2] )
ABC_SWAP( int, pCut[1], pCut[2] );
assert( pCut[1] < pCut[2] );
assert( pCut[2] < pCut[3] );
return 1;
}
int Dtc_ManCutCheckEqual( Vec_Int_t * vCuts, int * pCutNew )
{
int * pList = Vec_IntArray( vCuts );
int i, k, * pCut;
Dtc_ForEachCut( pList, pCut, i )
{
for ( k = 0; k <= pCut[0]; k++ )
if ( pCut[k] != pCutNew[k] )
break;
if ( k > pCut[0] )
return 1;
}
return 0;
}
int Dtc_ObjComputeTruth_rec( Gia_Obj_t * pObj )
{
int Truth0, Truth1;
if ( pObj->Value )
return pObj->Value;
assert( Gia_ObjIsAnd(pObj) );
Truth0 = Dtc_ObjComputeTruth_rec( Gia_ObjFanin0(pObj) );
Truth1 = Dtc_ObjComputeTruth_rec( Gia_ObjFanin1(pObj) );
if ( Gia_ObjIsXor(pObj) )
return (pObj->Value = (Gia_ObjFaninC0(pObj) ? ~Truth0 : Truth0) ^ (Gia_ObjFaninC1(pObj) ? ~Truth1 : Truth1));
else
return (pObj->Value = (Gia_ObjFaninC0(pObj) ? ~Truth0 : Truth0) & (Gia_ObjFaninC1(pObj) ? ~Truth1 : Truth1));
}
void Dtc_ObjCleanTruth_rec( Gia_Obj_t * pObj )
{
if ( !pObj->Value )
return;
pObj->Value = 0;
if ( !Gia_ObjIsAnd(pObj) )
return;
Dtc_ObjCleanTruth_rec( Gia_ObjFanin0(pObj) );
Dtc_ObjCleanTruth_rec( Gia_ObjFanin1(pObj) );
}
int Dtc_ObjComputeTruth( Gia_Man_t * p, int iObj, int * pCut, int * pTruth )
{
unsigned Truth, Truths[3] = { 0xAA, 0xCC, 0xF0 }; int i;
for ( i = 1; i <= pCut[0]; i++ )
Gia_ManObj(p, pCut[i])->Value = Truths[i-1];
Truth = 0xFF & Dtc_ObjComputeTruth_rec( Gia_ManObj(p, iObj) );
Dtc_ObjCleanTruth_rec( Gia_ManObj(p, iObj) );
if ( pTruth )
*pTruth = Truth;
if ( Truth == 0x66 || Truth == 0x99 )
return 3;
if ( Truth == 0x96 || Truth == 0x69 )
return 1;
if ( Truth == 0xE8 || Truth == 0xD4 || Truth == 0xB2 || Truth == 0x71 ||
Truth == 0x17 || Truth == 0x2B || Truth == 0x4D || Truth == 0x8E )
return 2;
return 0;
}
void Dtc_ManCutMerge( Gia_Man_t * p, int iObj, int * pList0, int * pList1, Vec_Int_t * vCuts, Vec_Int_t * vCutsXor2, Vec_Int_t * vCutsXor, Vec_Int_t * vCutsMaj )
{
int fVerbose = 0;
Vec_Int_t * vTemp;
int i, k, c, Type, * pCut0, * pCut1, pCut[4];
if ( fVerbose )
printf( "Object %d = :\n", iObj );
Vec_IntFill( vCuts, 2, 1 );
Vec_IntPush( vCuts, iObj );
Dtc_ForEachCut( pList0, pCut0, i )
Dtc_ForEachCut( pList1, pCut1, k )
{
if ( !Dtc_ManCutMergeOne(pCut0, pCut1, pCut) )
continue;
if ( Dtc_ManCutCheckEqual(vCuts, pCut) )
continue;
Vec_IntAddToEntry( vCuts, 0, 1 );
if ( fVerbose )
printf( "%d : ", pCut[0] );
for ( c = 0; c <= pCut[0]; c++ )
{
Vec_IntPush( vCuts, pCut[c] );
if ( fVerbose && c )
printf( "%d ", pCut[c] );
}
if ( fVerbose )
printf( "\n" );
if ( pCut[0] == 2 )
{
int Value = Dtc_ObjComputeTruth( p, iObj, pCut, NULL );
assert( Value == 3 || Value == 0 );
if ( Value == 3 )
{
Vec_IntPush( vCutsXor2, pCut[1] );
Vec_IntPush( vCutsXor2, pCut[2] );
Vec_IntPush( vCutsXor2, iObj );
}
continue;
}
if ( pCut[0] != 3 )
continue;
Type = Dtc_ObjComputeTruth( p, iObj, pCut, NULL );
if ( Type == 0 )
continue;
vTemp = Type == 1 ? vCutsXor : vCutsMaj;
if ( 0 && Type == 2 )
{
fVerbose = 1;
if ( fVerbose )
printf( "%d = %s(", iObj, Type == 1 ? "XOR" : "MAJ" );
for ( c = 1; c <= pCut[0]; c++ )
{
if ( fVerbose )
printf( " %d", pCut[c] );
Vec_IntPush( vTemp, pCut[c] );
}
if ( fVerbose )
printf( " )\n" );
fVerbose = 0;
}
Vec_IntPush( vTemp, iObj );
}
}
void Dtc_ManComputeCuts( Gia_Man_t * p, Vec_Int_t ** pvCutsXor2, Vec_Int_t ** pvCutsXor, Vec_Int_t ** pvCutsMaj, int fVerbose )
{
Gia_Obj_t * pObj;
int * pList0, * pList1, i, nCuts = 0;
Vec_Int_t * vTemp = Vec_IntAlloc( 1000 );
Vec_Int_t * vCutsXor2 = Vec_IntAlloc( Gia_ManAndNum(p) );
Vec_Int_t * vCutsXor = Vec_IntAlloc( Gia_ManAndNum(p) );
Vec_Int_t * vCutsMaj = Vec_IntAlloc( Gia_ManAndNum(p) );
Vec_Int_t * vCuts = Vec_IntAlloc( 30 * Gia_ManAndNum(p) );
Vec_IntFill( vCuts, Gia_ManObjNum(p), 0 );
Gia_ManCleanValue( p );
Gia_ManForEachCi( p, pObj, i )
{
Vec_IntWriteEntry( vCuts, Gia_ObjId(p, pObj), Vec_IntSize(vCuts) );
Vec_IntPush( vCuts, 1 );
Vec_IntPush( vCuts, 1 );
Vec_IntPush( vCuts, Gia_ObjId(p, pObj) );
}
Gia_ManForEachAnd( p, pObj, i )
{
pList0 = Vec_IntEntryP( vCuts, Vec_IntEntry(vCuts, Gia_ObjFaninId0(pObj, i)) );
pList1 = Vec_IntEntryP( vCuts, Vec_IntEntry(vCuts, Gia_ObjFaninId1(pObj, i)) );
Dtc_ManCutMerge( p, i, pList0, pList1, vTemp, vCutsXor2, vCutsXor, vCutsMaj );
Vec_IntWriteEntry( vCuts, i, Vec_IntSize(vCuts) );
Vec_IntAppend( vCuts, vTemp );
nCuts += Vec_IntEntry( vTemp, 0 );
}
if ( fVerbose )
printf( "Nodes = %d. Cuts = %d. Cuts/Node = %.2f. Ints/Node = %.2f.\n",
Gia_ManAndNum(p), nCuts, 1.0*nCuts/Gia_ManAndNum(p), 1.0*Vec_IntSize(vCuts)/Gia_ManAndNum(p) );
Vec_IntFree( vTemp );
Vec_IntFree( vCuts );
if ( pvCutsXor2 )
*pvCutsXor2 = vCutsXor2;
else
Vec_IntFree( vCutsXor2 );
*pvCutsXor = vCutsXor;
*pvCutsMaj = vCutsMaj;
}
Vec_Int_t * Dtc_ManFindCommonCuts( Gia_Man_t * p, Vec_Int_t * vCutsXor, Vec_Int_t * vCutsMaj )
{
int * pCuts0 = Vec_IntArray(vCutsXor);
int * pCuts1 = Vec_IntArray(vCutsMaj);
int * pLimit0 = Vec_IntLimit(vCutsXor);
int * pLimit1 = Vec_IntLimit(vCutsMaj); int i;
Vec_Int_t * vFadds = Vec_IntAlloc( 1000 );
assert( Vec_IntSize(vCutsXor) % 4 == 0 );
assert( Vec_IntSize(vCutsMaj) % 4 == 0 );
while ( pCuts0 < pLimit0 && pCuts1 < pLimit1 )
{
for ( i = 0; i < 3; i++ )
if ( pCuts0[i] != pCuts1[i] )
break;
if ( i == 3 )
{
for ( i = 0; i < 4; i++ )
Vec_IntPush( vFadds, pCuts0[i] );
Vec_IntPush( vFadds, pCuts1[3] );
pCuts0 += 4;
pCuts1 += 4;
}
else if ( pCuts0[i] < pCuts1[i] )
pCuts0 += 4;
else if ( pCuts0[i] > pCuts1[i] )
pCuts1 += 4;
}
assert( Vec_IntSize(vFadds) % 5 == 0 );
return vFadds;
}
void Dtc_ManPrintFadds( Vec_Int_t * vFadds )
{
int i;
Dtc_ForEachFadd( vFadds, i )
{
printf( "%6d : ", i );
printf( "%6d ", Vec_IntEntry(vFadds, 5*i+0) );
printf( "%6d ", Vec_IntEntry(vFadds, 5*i+1) );
printf( "%6d ", Vec_IntEntry(vFadds, 5*i+2) );
printf( " -> " );
printf( "%6d ", Vec_IntEntry(vFadds, 5*i+3) );
printf( "%6d ", Vec_IntEntry(vFadds, 5*i+4) );
printf( "\n" );
if ( i == 100 )
{
printf( "Skipping other FADDs.\n" );
break;
}
}
}
int Dtc_ManCompare( int * pCut0, int * pCut1 )
{
if ( pCut0[0] < pCut1[0] ) return -1;
if ( pCut0[0] > pCut1[0] ) return 1;
if ( pCut0[1] < pCut1[1] ) return -1;
if ( pCut0[1] > pCut1[1] ) return 1;
if ( pCut0[2] < pCut1[2] ) return -1;
if ( pCut0[2] > pCut1[2] ) return 1;
return 0;
}
int Dtc_ManCompare2( int * pCut0, int * pCut1 )
{
if ( pCut0[4] < pCut1[4] ) return -1;
if ( pCut0[4] > pCut1[4] ) return 1;
return 0;
}
// returns array of 5-tuples containing inputs/sum/cout of each full adder
Vec_Int_t * Gia_ManDetectFullAdders( Gia_Man_t * p, int fVerbose, Vec_Int_t ** pvCutsXor2 )
{
Vec_Int_t * vCutsXor, * vCutsMaj, * vFadds;
Dtc_ManComputeCuts( p, pvCutsXor2, &vCutsXor, &vCutsMaj, fVerbose );
qsort( Vec_IntArray(vCutsXor), (size_t)(Vec_IntSize(vCutsXor)/4), 16, (int (*)(const void *, const void *))Dtc_ManCompare );
qsort( Vec_IntArray(vCutsMaj), (size_t)(Vec_IntSize(vCutsMaj)/4), 16, (int (*)(const void *, const void *))Dtc_ManCompare );
vFadds = Dtc_ManFindCommonCuts( p, vCutsXor, vCutsMaj );
qsort( Vec_IntArray(vFadds), (size_t)(Vec_IntSize(vFadds)/5), 20, (int (*)(const void *, const void *))Dtc_ManCompare2 );
if ( fVerbose )
printf( "XOR3 cuts = %d. MAJ cuts = %d. Full-adders = %d.\n", Vec_IntSize(vCutsXor)/4, Vec_IntSize(vCutsMaj)/4, Vec_IntSize(vFadds)/5 );
if ( fVerbose )
Dtc_ManPrintFadds( vFadds );
Vec_IntFree( vCutsXor );
Vec_IntFree( vCutsMaj );
return vFadds;
}
void Gia_ManDetectFullAdders2( Gia_Man_t * p, int fVerbose )
{
Vec_Int_t * vCutsXor2, * vCutsXor, * vCutsMaj;
Dtc_ManComputeCuts( p, &vCutsXor2, &vCutsXor, &vCutsMaj, fVerbose );
if ( fVerbose )
printf( "XOR3 cuts = %d. MAJ cuts = %d.\n", Vec_IntSize(vCutsXor)/4, Vec_IntSize(vCutsMaj)/4 );
Vec_IntFree( vCutsXor2 );
Vec_IntFree( vCutsXor );
Vec_IntFree( vCutsMaj );
}
/**Function*************************************************************
Synopsis [Map each MAJ into the topmost MAJ of its chain.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
// maps MAJ nodes into FADD indexes
Vec_Int_t * Gia_ManCreateMap( Gia_Man_t * p, Vec_Int_t * vFadds )
{
Vec_Int_t * vMap = Vec_IntStartFull( Gia_ManObjNum(p) ); int i;
Dtc_ForEachFadd( vFadds, i )
Vec_IntWriteEntry( vMap, Vec_IntEntry(vFadds, 5*i+4), i );
return vMap;
}
// find chain length (for each MAJ, how many FADDs are rooted in its first input)
int Gia_ManFindChains_rec( Gia_Man_t * p, int iMaj, Vec_Int_t * vFadds, Vec_Int_t * vMap, Vec_Int_t * vLength )
{
assert( Vec_IntEntry(vMap, iMaj) >= 0 ); // MAJ
if ( Vec_IntEntry(vLength, iMaj) >= 0 )
return Vec_IntEntry(vLength, iMaj);
assert( Gia_ObjIsAnd(Gia_ManObj(p, iMaj)) );
{
int iFadd = Vec_IntEntry( vMap, iMaj );
int iXor0 = Vec_IntEntry( vFadds, 5*iFadd+0 );
int iXor1 = Vec_IntEntry( vFadds, 5*iFadd+1 );
int iXor2 = Vec_IntEntry( vFadds, 5*iFadd+2 );
int iLen0 = Vec_IntEntry( vMap, iXor0 ) == -1 ? 0 : Gia_ManFindChains_rec( p, iXor0, vFadds, vMap, vLength );
int iLen1 = Vec_IntEntry( vMap, iXor1 ) == -1 ? 0 : Gia_ManFindChains_rec( p, iXor1, vFadds, vMap, vLength );
int iLen2 = Vec_IntEntry( vMap, iXor2 ) == -1 ? 0 : Gia_ManFindChains_rec( p, iXor2, vFadds, vMap, vLength );
int iLen = Abc_MaxInt( iLen0, Abc_MaxInt(iLen1, iLen2) );
if ( iLen0 < iLen )
{
if ( iLen == iLen1 )
{
ABC_SWAP( int, Vec_IntArray(vFadds)[5*iFadd+0], Vec_IntArray(vFadds)[5*iFadd+1] );
}
else if ( iLen == iLen2 )
{
ABC_SWAP( int, Vec_IntArray(vFadds)[5*iFadd+0], Vec_IntArray(vFadds)[5*iFadd+2] );
}
}
Vec_IntWriteEntry( vLength, iMaj, iLen + 1 );
return iLen + 1;
}
}
// for each FADD find the longest chain and reorder its inputs
void Gia_ManFindChains( Gia_Man_t * p, Vec_Int_t * vFadds, Vec_Int_t * vMap )
{
int i;
// for each FADD find the longest chain rooted in it
Vec_Int_t * vLength = Vec_IntStartFull( Gia_ManObjNum(p) );
Dtc_ForEachFadd( vFadds, i )
Gia_ManFindChains_rec( p, Vec_IntEntry(vFadds, 5*i+4), vFadds, vMap, vLength );
Vec_IntFree( vLength );
}
// collect one carry-chain
void Gia_ManCollectOneChain( Gia_Man_t * p, Vec_Int_t * vFadds, int iFaddTop, Vec_Int_t * vMap, Vec_Int_t * vChain )
{
int iFadd;
Vec_IntClear( vChain );
for ( iFadd = iFaddTop; iFadd >= 0 &&
!Gia_ObjIsTravIdCurrentId(p, Vec_IntEntry(vFadds, 5*iFadd+3)) &&
!Gia_ObjIsTravIdCurrentId(p, Vec_IntEntry(vFadds, 5*iFadd+4));
iFadd = Vec_IntEntry(vMap, Vec_IntEntry(vFadds, 5*iFadd+0)) )
{
Vec_IntPush( vChain, iFadd );
}
Vec_IntReverseOrder( vChain );
}
void Gia_ManMarkWithTravId_rec( Gia_Man_t * p, int Id )
{
Gia_Obj_t * pObj;
if ( Gia_ObjIsTravIdCurrentId(p, Id) )
return;
Gia_ObjSetTravIdCurrentId(p, Id);
pObj = Gia_ManObj( p, Id );
if ( Gia_ObjIsAnd(pObj) )
Gia_ManMarkWithTravId_rec( p, Gia_ObjFaninId0(pObj, Id) );
if ( Gia_ObjIsAnd(pObj) )
Gia_ManMarkWithTravId_rec( p, Gia_ObjFaninId1(pObj, Id) );
}
// returns mapping of each MAJ into the topmost elements of its chain
Vec_Wec_t * Gia_ManCollectTopmost( Gia_Man_t * p, Vec_Int_t * vFadds, Vec_Int_t * vMap, int nFaddMin )
{
int i, j, iFadd;
Vec_Int_t * vChain = Vec_IntAlloc( 100 );
Vec_Wec_t * vChains = Vec_WecAlloc( Vec_IntSize(vFadds)/5 );
// erase elements appearing as FADD inputs
Vec_Bit_t * vMarksTop = Vec_BitStart( Vec_IntSize(vFadds)/5 );
Dtc_ForEachFadd( vFadds, i )
if ( (iFadd = Vec_IntEntry(vMap, Vec_IntEntry(vFadds, 5*i+0))) >= 0 )
Vec_BitWriteEntry( vMarksTop, iFadd, 1 );
// compress the remaining ones
Gia_ManIncrementTravId( p );
Dtc_ForEachFadd( vFadds, i )
{
if ( Vec_BitEntry(vMarksTop, i) )
continue;
Gia_ManCollectOneChain( p, vFadds, i, vMap, vChain );
if ( Vec_IntSize(vChain) < nFaddMin )
continue;
Vec_IntAppend( Vec_WecPushLevel(vChains), vChain );
Vec_IntForEachEntry( vChain, iFadd, j )
{
assert( !Gia_ObjIsTravIdCurrentId(p, Vec_IntEntry(vFadds, 5*iFadd+3)) );
assert( !Gia_ObjIsTravIdCurrentId(p, Vec_IntEntry(vFadds, 5*iFadd+4)) );
Gia_ManMarkWithTravId_rec( p, Vec_IntEntry(vFadds, 5*iFadd+3) );
Gia_ManMarkWithTravId_rec( p, Vec_IntEntry(vFadds, 5*iFadd+4) );
}
}
// cleanup
Vec_BitFree( vMarksTop );
Vec_IntFree( vChain );
return vChains;
}
// prints chains beginning in majority nodes contained in vTops
void Gia_ManPrintChains( Gia_Man_t * p, Vec_Int_t * vFadds, Vec_Int_t * vMap, Vec_Wec_t * vChains )
{
Vec_Int_t * vChain;
int i, k, iFadd, Count = 0;
Vec_WecForEachLevel( vChains, vChain, i )
{
Count += Vec_IntSize(vChain);
if ( i < 10 )
{
printf( "Chain %4d : %4d ", i, Vec_IntSize(vChain) );
Vec_IntForEachEntry( vChain, iFadd, k )
{
printf( "%d(%d) ", iFadd, Vec_IntEntry(vFadds, 5*iFadd+4) );
if ( k != Vec_IntSize(vChain) - 1 )
printf( "-> " );
if ( k > 6 )
{
printf( "..." );
break;
}
}
printf( "\n" );
}
else if ( i == 10 )
printf( "...\n" );
}
printf( "Total chains = %d. Total full-adders = %d.\n", Vec_WecSize(vChains), Count );
}
// map SUM bits and topmost MAJ into topmost FADD number
Vec_Int_t * Gia_ManFindMapping( Gia_Man_t * p, Vec_Int_t * vFadds, Vec_Int_t * vMap, Vec_Wec_t * vChains )
{
Vec_Int_t * vChain;
int i, k, iFadd = -1;
Vec_Int_t * vMap2Chain = Vec_IntStartFull( Gia_ManObjNum(p) );
Vec_WecForEachLevel( vChains, vChain, i )
{
assert( Vec_IntSize(vChain) > 0 );
Vec_IntForEachEntry( vChain, iFadd, k )
{
//printf( "Chain %d: setting SUM %d (obj %d)\n", i, k, Vec_IntEntry(vFadds, 5*iFadd+3) );
assert( Vec_IntEntry(vMap2Chain, Vec_IntEntry(vFadds, 5*iFadd+3)) == -1 );
Vec_IntWriteEntry( vMap2Chain, Vec_IntEntry(vFadds, 5*iFadd+3), i );
}
//printf( "Chain %d: setting CARRY (obj %d)\n", i, Vec_IntEntry(vFadds, 5*iFadd+4) );
assert( Vec_IntEntry(vMap2Chain, Vec_IntEntry(vFadds, 5*iFadd+4)) == -1 );
Vec_IntWriteEntry( vMap2Chain, Vec_IntEntry(vFadds, 5*iFadd+4), i );
}
return vMap2Chain;
}
/**Function*************************************************************
Synopsis [Derive GIA with boxes containing adder-chains.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Vec_Int_t * Gia_ManCollectTruthTables( Gia_Man_t * p, Vec_Int_t * vFadds )
{
int i, k, Type, Truth, pCut[4] = {3};
Vec_Int_t * vTruths = Vec_IntAlloc( 2*Vec_IntSize(vFadds)/5 );
Gia_ManCleanValue( p );
Dtc_ForEachFadd( vFadds, i )
{
for ( k = 0; k < 3; k++ )
pCut[k+1] = Vec_IntEntry( vFadds, 5*i+k );
Type = Dtc_ObjComputeTruth( p, Vec_IntEntry(vFadds, 5*i+3), pCut, &Truth );
assert( Type == 1 );
Vec_IntPush( vTruths, Truth );
Type = Dtc_ObjComputeTruth( p, Vec_IntEntry(vFadds, 5*i+4), pCut, &Truth );
assert( Type == 2 );
Vec_IntPush( vTruths, Truth );
}
return vTruths;
}
float * Gia_ManGenerateDelayTableFloat( int nIns, int nOuts )
{
int i, Total = nIns * nOuts;
float * pDelayTable = ABC_ALLOC( float, Total + 3 );
pDelayTable[0] = 0;
pDelayTable[1] = nIns;
pDelayTable[2] = nOuts;
for ( i = 0; i < Total; i++ )
pDelayTable[i+3] = 1;
pDelayTable[i+3 - nIns] = -ABC_INFINITY;
return pDelayTable;
}
Tim_Man_t * Gia_ManGenerateTim( int nPis, int nPos, int nBoxes, int nIns, int nOuts )
{
Tim_Man_t * pMan;
int i, curPi, curPo;
Vec_Ptr_t * vDelayTables = Vec_PtrAlloc( 1 );
Vec_PtrPush( vDelayTables, Gia_ManGenerateDelayTableFloat(nIns, nOuts) );
pMan = Tim_ManStart( nPis + nOuts * nBoxes, nPos + nIns * nBoxes );
Tim_ManSetDelayTables( pMan, vDelayTables );
curPi = nPis;
curPo = 0;
for ( i = 0; i < nBoxes; i++ )
{
Tim_ManCreateBox( pMan, curPo, nIns, curPi, nOuts, 0, 0 );
curPi += nOuts;
curPo += nIns;
}
curPo += nPos;
assert( curPi == Tim_ManCiNum(pMan) );
assert( curPo == Tim_ManCoNum(pMan) );
//Tim_ManPrint( pMan );
return pMan;
}
Gia_Man_t * Gia_ManGenerateExtraAig( int nBoxes, int nIns, int nOuts )
{
Gia_Man_t * pNew = Gia_ManStart( nBoxes * 20 );
int i, k, pInLits[16], pOutLits[16];
assert( nIns < 16 && nOuts < 16 );
for ( i = 0; i < nIns; i++ )
pInLits[i] = Gia_ManAppendCi( pNew );
pOutLits[0] = Gia_ManAppendXor( pNew, Gia_ManAppendXor(pNew, pInLits[0], pInLits[1]), pInLits[2] );
pOutLits[1] = Gia_ManAppendMaj( pNew, pInLits[0], pInLits[1], pInLits[2] );
for ( i = 0; i < nBoxes; i++ )
for ( k = 0; k < nOuts; k++ )
Gia_ManAppendCo( pNew, pOutLits[k] );
return pNew;
}
void Gia_ManDupFadd( Gia_Man_t * pNew, Gia_Man_t * p, Vec_Int_t * vChain, Vec_Int_t * vFadds, Vec_Int_t * vMap, Vec_Wec_t * vChains, Vec_Int_t * vMap2Chain, Vec_Int_t * vTruths )
{
extern void Gia_ManDupWithFaddBoxes_rec( Gia_Man_t * pNew, Gia_Man_t * p, Gia_Obj_t * pObj, Vec_Int_t * vFadds, Vec_Int_t * vMap, Vec_Wec_t * vChains, Vec_Int_t * vMap2Chain, Vec_Int_t * vTruths );
int i, k, iFadd = -1, iCiLit, pLits[3];
Gia_Obj_t * pObj;
// construct FADD inputs
Vec_IntForEachEntry( vChain, iFadd, i )
for ( k = 0; k < 3; k++ )
{
if ( i && !k ) continue;
pObj = Gia_ManObj( p, Vec_IntEntry(vFadds, 5*iFadd+k) );
Gia_ManDupWithFaddBoxes_rec( pNew, p, pObj, vFadds, vMap, vChains, vMap2Chain, vTruths );
}
// construct boxes
iCiLit = 0;
Vec_IntForEachEntry( vChain, iFadd, i )
{
int iXorTruth = Vec_IntEntry( vTruths, 2*iFadd+0 );
int iMajTruth = Vec_IntEntry( vTruths, 2*iFadd+1 );
for ( k = 0; k < 3; k++ )
{
pObj = Gia_ManObj( p, Vec_IntEntry(vFadds, 5*iFadd+k) );
pLits[k] = (!k && iCiLit) ? iCiLit : pObj->Value;
assert( pLits[k] >= 0 );
}
// normalize truth table
// if ( Truth == 0xE8 || Truth == 0xD4 || Truth == 0xB2 || Truth == 0x71 ||
// Truth == 0x17 || Truth == 0x2B || Truth == 0x4D || Truth == 0x8E )
if ( iMajTruth == 0x4D )
pLits[0] = Abc_LitNot(pLits[0]), iMajTruth = 0x8E, iXorTruth = 0xFF & ~iXorTruth;
else if ( iMajTruth == 0xD4 )
pLits[0] = Abc_LitNot(pLits[0]), iMajTruth = 0xE8, iXorTruth = 0xFF & ~iXorTruth;
else if ( iMajTruth == 0x2B )
pLits[1] = Abc_LitNot(pLits[1]), iMajTruth = 0x8E, iXorTruth = 0xFF & ~iXorTruth;
else if ( iMajTruth == 0xB2 )
pLits[1] = Abc_LitNot(pLits[1]), iMajTruth = 0xE8, iXorTruth = 0xFF & ~iXorTruth;
if ( iMajTruth == 0x8E )
pLits[2] = Abc_LitNot(pLits[2]), iMajTruth = 0xE8, iXorTruth = 0xFF & ~iXorTruth;
else if ( iMajTruth == 0x71 )
pLits[2] = Abc_LitNot(pLits[2]), iMajTruth = 0x17, iXorTruth = 0xFF & ~iXorTruth;
else assert( iMajTruth == 0xE8 || iMajTruth == 0x17 );
// normalize carry-in
if ( Abc_LitIsCompl(pLits[0]) )
{
for ( k = 0; k < 3; k++ )
pLits[k] = Abc_LitNot(pLits[k]);
iXorTruth = 0xFF & ~iXorTruth;
iMajTruth = 0xFF & ~iMajTruth;
}
// add COs
assert( !Abc_LitIsCompl(pLits[0]) );
for ( k = 0; k < 3; k++ )
Gia_ManAppendCo( pNew, pLits[k] );
// create CI
assert( iXorTruth == 0x96 || iXorTruth == 0x69 );
pObj = Gia_ManObj( p, Vec_IntEntry(vFadds, 5*iFadd+3) );
pObj->Value = Abc_LitNotCond( Gia_ManAppendCi(pNew), (int)(iXorTruth == 0x69) );
// create CI
assert( iMajTruth == 0xE8 || iMajTruth == 0x17 );
iCiLit = Abc_LitNotCond( Gia_ManAppendCi(pNew), (int)(iMajTruth == 0x17) );
}
// assign carry out
assert( iFadd == Vec_IntEntryLast(vChain) );
pObj = Gia_ManObj( p, Vec_IntEntry(vFadds, 5*iFadd+4) );
pObj->Value = iCiLit;
}
void Gia_ManDupWithFaddBoxes_rec( Gia_Man_t * pNew, Gia_Man_t * p, Gia_Obj_t * pObj, Vec_Int_t * vFadds, Vec_Int_t * vMap, Vec_Wec_t * vChains, Vec_Int_t * vMap2Chain, Vec_Int_t * vTruths )
{
int iChain;
if ( ~pObj->Value )
return;
assert( Gia_ObjIsAnd(pObj) );
iChain = Vec_IntEntry( vMap2Chain, Gia_ObjId(p, pObj) );
/*
assert( iChain == -1 );
if ( iChain >= 0 )
{
Gia_ManDupFadd( pNew, p, Vec_WecEntry(vChains, iChain), vFadds, vMap, vChains, vMap2Chain, vTruths );
assert( ~pObj->Value );
return;
}
*/
Gia_ManDupWithFaddBoxes_rec( pNew, p, Gia_ObjFanin0(pObj), vFadds, vMap, vChains, vMap2Chain, vTruths );
Gia_ManDupWithFaddBoxes_rec( pNew, p, Gia_ObjFanin1(pObj), vFadds, vMap, vChains, vMap2Chain, vTruths );
pObj->Value = Gia_ManAppendAnd( pNew, Gia_ObjFanin0Copy(pObj), Gia_ObjFanin1Copy(pObj) );
}
Gia_Man_t * Gia_ManDupWithNaturalBoxes( Gia_Man_t * p, int nFaddMin, int fVerbose )
{
abctime clk = Abc_Clock();
Gia_Man_t * pNew;//, * pTemp;
Vec_Int_t * vFadds, * vMap, * vMap2Chain, * vTruths, * vChain;
Vec_Wec_t * vChains;
Gia_Obj_t * pObj;
int i, nBoxes;
if ( Gia_ManBoxNum(p) > 0 )
{
printf( "Currently natural carry-chains cannot be detected when boxes are present.\n" );
return NULL;
}
assert( Gia_ManBoxNum(p) == 0 );
// detect FADDs
vFadds = Gia_ManDetectFullAdders( p, fVerbose, NULL );
assert( Vec_IntSize(vFadds) % 5 == 0 );
// map MAJ into its FADD
vMap = Gia_ManCreateMap( p, vFadds );
// for each FADD, find the longest chain and reorder its inputs
Gia_ManFindChains( p, vFadds, vMap );
// returns the set of topmost MAJ nodes
vChains = Gia_ManCollectTopmost( p, vFadds, vMap, nFaddMin );
if ( fVerbose )
Gia_ManPrintChains( p, vFadds, vMap, vChains );
if ( Vec_WecSize(vChains) == 0 )
{
Vec_IntFree( vFadds );
Vec_IntFree( vMap );
Vec_WecFree( vChains );
return Gia_ManDup( p );
}
// returns mapping of each MAJ into the topmost elements of its chain
vMap2Chain = Gia_ManFindMapping( p, vFadds, vMap, vChains );
// compute truth tables for FADDs
vTruths = Gia_ManCollectTruthTables( p, vFadds );
if ( fVerbose )
Abc_PrintTime( 1, "Carry-chain detection time", Abc_Clock() - clk );
// duplicate
clk = Abc_Clock();
Gia_ManFillValue( p );
pNew = Gia_ManStart( Gia_ManObjNum(p) );
pNew->pName = Abc_UtilStrsav( p->pName );
pNew->pSpec = Abc_UtilStrsav( p->pSpec );
Gia_ManConst0(p)->Value = 0;
Gia_ManForEachCi( p, pObj, i )
pObj->Value = Gia_ManAppendCi( pNew );
Vec_WecForEachLevel( vChains, vChain, i )
Gia_ManDupFadd( pNew, p, vChain, vFadds, vMap, vChains, vMap2Chain, vTruths );
Gia_ManForEachCo( p, pObj, i )
Gia_ManDupWithFaddBoxes_rec( pNew, p, Gia_ObjFanin0(pObj), vFadds, vMap, vChains, vMap2Chain, vTruths );
Gia_ManForEachCo( p, pObj, i )
Gia_ManAppendCo( pNew, Gia_ObjFanin0Copy(pObj) );
Gia_ManSetRegNum( pNew, Gia_ManRegNum(p) );
if ( Gia_ManRegNum(p) )
{
if ( fVerbose )
printf( "Warning: Sequential design is coverted into combinational one by adding white boxes.\n" );
pNew->nRegs = 0;
}
assert( !Gia_ManHasDangling(pNew) );
// cleanup
Vec_IntFree( vFadds );
Vec_IntFree( vMap );
Vec_WecFree( vChains );
Vec_IntFree( vMap2Chain );
Vec_IntFree( vTruths );
// other information
nBoxes = (Gia_ManCiNum(pNew) - Gia_ManCiNum(p)) / 2;
assert( nBoxes == (Gia_ManCoNum(pNew) - Gia_ManCoNum(p)) / 3 );
pNew->pManTime = Gia_ManGenerateTim( Gia_ManCiNum(p), Gia_ManCoNum(p), nBoxes, 3, 2 );
pNew->pAigExtra = Gia_ManGenerateExtraAig( nBoxes, 3, 2 );
/*
// normalize
pNew = Gia_ManDupNormalize( pTemp = pNew, 0 );
pNew->pManTime = pTemp->pManTime; pTemp->pManTime = NULL;
pNew->pAigExtra = pTemp->pAigExtra; pTemp->pAigExtra = NULL;
Gia_ManStop( pTemp );
*/
//pNew = Gia_ManDupCollapse( pTemp = pNew, pNew->pAigExtra, NULL );
//Gia_ManStop( pTemp );
//Gia_ManIllustrateBoxes( pNew );
if ( fVerbose )
Abc_PrintTime( 1, "AIG with boxes construction time", Abc_Clock() - clk );
return pNew;
}
/**Function*************************************************************
Synopsis [Converting AIG with annotated carry-chains into AIG with boxes.]
Description [Assumes that annotations are pObj->fMark0 or pObj->fMark1.
Only one of these can be set to 1. If fMark0 (fMark1) is set to 1,
the first (second) input of an AND-gate is chained.]
SideEffects []
SeeAlso []
***********************************************************************/
int Gia_ObjFanin0CopyCarry( Vec_Int_t * vCarries, Gia_Obj_t * pObj, int Id )
{
if ( vCarries == NULL || Vec_IntEntry(vCarries, Gia_ObjFaninId0(pObj, Id)) == -1 )
return Gia_ObjFanin0Copy(pObj);
return Abc_LitNotCond( Vec_IntEntry(vCarries, Gia_ObjFaninId0(pObj, Id)), Gia_ObjFaninC0(pObj) );
}
int Gia_ObjFanin1CopyCarry( Vec_Int_t * vCarries, Gia_Obj_t * pObj, int Id )
{
if ( vCarries == NULL || Vec_IntEntry(vCarries, Gia_ObjFaninId1(pObj, Id)) == -1 )
return Gia_ObjFanin1Copy(pObj);
return Abc_LitNotCond( Vec_IntEntry(vCarries, Gia_ObjFaninId1(pObj, Id)), Gia_ObjFaninC1(pObj) );
}
Gia_Man_t * Gia_ManDupWithArtificalFaddBoxes( Gia_Man_t * p, int fUseFanout, int fXorTrick )
{
Gia_Man_t * pNew;
Gia_Obj_t * pObj;
int nBoxes = Gia_ManBoxNum(p);
int i, nRealPis, nRealPos;
Vec_Int_t * vCarries = NULL;
// make sure two chains do not overlap
Gia_ManCleanPhase( p );
Gia_ManForEachCi( p, pObj, i )
assert( !pObj->fMark0 && !pObj->fMark1 );
Gia_ManForEachCo( p, pObj, i )
assert( !pObj->fMark0 && !pObj->fMark1 );
Gia_ManForEachAnd( p, pObj, i )
{
assert( !pObj->fMark0 || !pObj->fMark1 );
if ( pObj->fMark0 )
{
assert( Gia_ObjFanin0(pObj)->fPhase == 0 );
Gia_ObjFanin0(pObj)->fPhase = 1;
}
if ( pObj->fMark1 )
{
assert( Gia_ObjFanin1(pObj)->fPhase == 0 );
Gia_ObjFanin1(pObj)->fPhase = 1;
}
}
// create mapping for carry-chains
if ( !fUseFanout )
vCarries = Vec_IntStartFull( Gia_ManObjNum(p) );
// create references and discount carries
if ( vCarries )
{
Gia_ManCreateRefs( p );
Gia_ManForEachAnd( p, pObj, i )
if ( pObj->fMark0 )
Gia_ObjRefFanin0Dec( p, pObj );
else if ( pObj->fMark1 )
Gia_ObjRefFanin1Dec( p, pObj );
}
// if AIG already has (natural) FADD boxes, it should not un-normalized
Gia_ManFillValue( p );
pNew = Gia_ManStart( Gia_ManObjNum(p) );
pNew->pName = Abc_UtilStrsav( p->pName );
pNew->pSpec = Abc_UtilStrsav( p->pSpec );
Gia_ManConst0(p)->Value = 0;
Gia_ManForEachObj1( p, pObj, i )
{
if ( Gia_ObjIsCi(pObj) )
pObj->Value = Gia_ManAppendCi( pNew );
else if ( Gia_ObjIsCo(pObj) )
pObj->Value = Gia_ManAppendCo( pNew, Gia_ObjFanin0Copy(pObj) );
else if ( !pObj->fMark0 && !pObj->fMark1 ) // AND-gate
pObj->Value = Gia_ManAppendAnd( pNew, Gia_ObjFanin0Copy(pObj), Gia_ObjFanin1Copy(pObj) );
else // AND-gate with chain
{
int iCiLit, iOtherLit, iLit0, iLit1, iLit2, iXorLit;
assert( pObj->fMark0 != pObj->fMark1 );
iCiLit = pObj->fMark0 ? Gia_ObjFanin0CopyCarry(vCarries, pObj, i) : Gia_ObjFanin1CopyCarry(vCarries, pObj, i);
iOtherLit = pObj->fMark0 ? Gia_ObjFanin1Copy(pObj) : Gia_ObjFanin0Copy(pObj);
assert( iCiLit >= 0 && iOtherLit >= 0 );
iLit0 = Abc_LitNotCond( iCiLit, Abc_LitIsCompl(iCiLit) );
iLit1 = Abc_LitNotCond( iOtherLit, Abc_LitIsCompl(iCiLit) );
iLit2 = Abc_LitNotCond( 0, Abc_LitIsCompl(iCiLit) );
// add COs
assert( !Abc_LitIsCompl(iLit0) );
Gia_ManAppendCo( pNew, iLit0 );
Gia_ManAppendCo( pNew, iLit1 );
Gia_ManAppendCo( pNew, iLit2 );
// add CI (unused sum bit)
iXorLit = Gia_ManAppendCi(pNew);
// add CI (carry bit)
pObj->Value = Abc_LitNotCond( Gia_ManAppendCi(pNew), Abc_LitIsCompl(iCiLit) );
if ( vCarries && pObj->fPhase )
{
Vec_IntWriteEntry( vCarries, i, pObj->Value );
if ( Gia_ObjRefNum(p, pObj) > 0 )
{
if ( fXorTrick )
pObj->Value = Gia_ManAppendAnd( pNew, Abc_LitNotCond(iXorLit, !Abc_LitIsCompl(iCiLit)), iOtherLit );
else
pObj->Value = Gia_ManAppendAnd( pNew, Gia_ObjFanin0Copy(pObj), Gia_ObjFanin1Copy(pObj) );
}
}
nBoxes++;
}
}
Gia_ManCleanPhase( p );
Vec_IntFreeP( &vCarries );
ABC_FREE( p->pRefs );
assert( !Gia_ManHasDangling(pNew) );
// other information
// nBoxes += (Gia_ManCiNum(pNew) - Gia_ManCiNum(p)) / 2;
// assert( nBoxes == Gia_ManBoxNum(p) + (Gia_ManCoNum(pNew) - Gia_ManCoNum(p)) / 3 );
nRealPis = Gia_ManBoxNum(p) ? Tim_ManPiNum((Tim_Man_t *)p->pManTime) : Gia_ManCiNum(p);
nRealPos = Gia_ManBoxNum(p) ? Tim_ManPoNum((Tim_Man_t *)p->pManTime) : Gia_ManCoNum(p);
pNew->pManTime = Gia_ManGenerateTim( nRealPis, nRealPos, nBoxes, 3, 2 );
pNew->pAigExtra = Gia_ManGenerateExtraAig( nBoxes, 3, 2 );
// optionally normalize the AIG
return pNew;
}
Gia_Man_t * Gia_ManDupWithArtificalFaddBoxesTest( Gia_Man_t * p )
{
Gia_Man_t * pNew;
Gia_Obj_t * pObj;
int i;
// label some and-gates
Gia_ManCleanMark01( p );
Gia_ManForEachAnd( p, pObj, i )
{
pObj->fMark0 = i % 5;
pObj->fMark1 = i % 7;
if ( pObj->fMark0 && pObj->fMark1 )
pObj->fMark0 = pObj->fMark1 = 0;
}
// output new AIG
pNew = Gia_ManDupWithArtificalFaddBoxes( p, 0, 0 );
Gia_ManCleanMark01( p );
return pNew;
}
/**Function*************************************************************
Synopsis [Adds artificial carry chains to the manager.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
// computes AIG delay information when boxes are used
int Gia_ManFindAnnotatedDelay( Gia_Man_t * p, int DelayC, int * pnBoxes, int fIgnoreBoxDelays )
{
Gia_Obj_t * pObj;
int nRealPis = Gia_ManBoxNum(p) ? Tim_ManPiNum((Tim_Man_t *)p->pManTime) : Gia_ManCiNum(p);
int * pDelays = Vec_IntArray(p->vLevels);
int i, k, iBox, iBoxOutId, Delay, Delay0, Delay1, DelayMax = 0, nBoxes = 0;
Vec_IntFill( p->vLevels, Gia_ManObjNum(p), 0 );
Gia_ManForEachObj1( p, pObj, i )
{
if ( Gia_ObjIsCi(pObj) )
{
if ( fIgnoreBoxDelays )
continue;
// check if it is real PI
iBoxOutId = Gia_ObjCioId(pObj) - nRealPis;
if ( iBoxOutId < 0 )
continue;
// if it is a box output, find box number
iBox = iBoxOutId / 2;
assert( iBox < Gia_ManBoxNum(p) );
// check find the maximum delay of the box inputs
Delay = 0;
for ( k = 0; k < 3; k++ )
{
int Id = Gia_ObjId( p, Gia_ManCo(p, iBox*3+k) );
assert( Id < i );
Delay = Abc_MaxInt( Delay, pDelays[Id] );
}
// consider outputs
if ( iBoxOutId & 1 ) // carry output
Delay += DelayC;
else // sum output
Delay += 100;
pDelays[i] = Delay;
continue;
}
if ( Gia_ObjIsCo(pObj) )
{
pDelays[i] = pDelays[Gia_ObjFaninId0(pObj, i)];
DelayMax = Abc_MaxInt( DelayMax, pDelays[i] );
continue;
}
assert( !pObj->fMark0 || !pObj->fMark1 );
Delay0 = pDelays[Gia_ObjFaninId0(pObj, i)];
Delay1 = pDelays[Gia_ObjFaninId1(pObj, i)];
if ( pObj->fMark0 )
{
Delay = Abc_MaxInt( Delay0 + DelayC, Delay1 + 100 );
nBoxes++;
}
else if ( pObj->fMark1 )
{
Delay = Abc_MaxInt( Delay1 + DelayC, Delay0 + 100 );
nBoxes++;
}
else
Delay = Abc_MaxInt( Delay0 + 100, Delay1 + 100 );
pDelays[i] = Delay;
}
if ( pnBoxes )
*pnBoxes = nBoxes;
return DelayMax;
}
// check if the object is already used in some chain
static inline int Gia_ObjIsUsed( Gia_Obj_t * pObj )
{
return pObj->fMark0 || pObj->fMark1 || pObj->fPhase;
}
// finds internal node that can begin a new chain
int Gia_ManFindChainStart( Gia_Man_t * p )
{
Gia_Obj_t * pObj;
int * pDelays = Vec_IntArray(p->vLevels);
int i, iMax = -1, DelayMax = 0;
Gia_ManForEachAnd( p, pObj, i )
{
if ( Gia_ObjIsUsed(pObj) )
continue;
if ( DelayMax > pDelays[i] )
continue;
DelayMax = pDelays[i];
iMax = i;
}
return iMax;
}
// finds a sequence of internal nodes that creates a new chain
int Gia_ManFindPath( Gia_Man_t * p, int DelayC, int nPathMin, int nPathMax, Vec_Int_t * vPath )
{
Gia_Obj_t * pObj, * pFanin0, * pFanin1;
int * pDelays = Vec_IntArray(p->vLevels);
int i, iLit, iMax = Gia_ManFindChainStart( p );
if ( iMax == -1 )
return -1;
Vec_IntClear( vPath );
pObj = Gia_ManObj(p, iMax);
assert( Gia_ObjIsAnd(pObj) );
while ( Gia_ObjIsAnd(pObj) )
{
assert( !Gia_ObjIsUsed(pObj) );
pFanin0 = Gia_ObjFanin0(pObj);
pFanin1 = Gia_ObjFanin1(pObj);
if ( Gia_ObjIsUsed(pFanin0) && Gia_ObjIsUsed(pFanin1) )
break;
if ( Gia_ObjIsUsed(pFanin0) )
{
Vec_IntPush( vPath, Abc_Var2Lit(Gia_ObjId(p, pObj), 1) );
pObj = pFanin1;
}
else if ( Gia_ObjIsUsed(pFanin1) )
{
Vec_IntPush( vPath, Abc_Var2Lit(Gia_ObjId(p, pObj), 0) );
pObj = pFanin0;
}
else
{
if ( pDelays[Gia_ObjId(p, pFanin1)] > pDelays[Gia_ObjId(p, pFanin0)] )
{
Vec_IntPush( vPath, Abc_Var2Lit(Gia_ObjId(p, pObj), 1) );
pObj = pFanin1;
}
else
{
Vec_IntPush( vPath, Abc_Var2Lit(Gia_ObjId(p, pObj), 0) );
pObj = pFanin0;
}
}
}
if ( Vec_IntSize(vPath) < nPathMin )
{
Gia_ManObj(p, iMax)->fPhase = 1;
return 0;
}
// label nodes
if ( Vec_IntSize(vPath) > nPathMax )
Vec_IntShrink( vPath, nPathMax );
Vec_IntForEachEntry( vPath, iLit, i )
{
pObj = Gia_ManObj( p, Abc_Lit2Var(iLit) );
if ( Abc_LitIsCompl(iLit) )
{
assert( pObj->fMark1 == 0 );
pObj->fMark1 = 1;
assert( Gia_ObjFanin1(pObj)->fPhase == 0 );
Gia_ObjFanin1(pObj)->fPhase = 1;
}
else
{
assert( pObj->fMark0 == 0 );
pObj->fMark0 = 1;
assert( Gia_ObjFanin0(pObj)->fPhase == 0 );
Gia_ObjFanin0(pObj)->fPhase = 1;
}
}
return Vec_IntSize(vPath);
}
// iteratively create the given number of chains
int Gia_ManIteratePaths( Gia_Man_t * p, int DelayC, int nPathMin, int nPathMax, int nPathLimit, int fIgnoreBoxDelays, int fVerbose )
{
Gia_Obj_t * pObj;
Vec_Int_t * vPath = Vec_IntAlloc( 100 );
int i, RetValue, nBoxes, MaxDelay, nPaths = 0;
assert( p->vLevels == NULL );
p->vLevels = Vec_IntStart( Gia_ManObjNum(p) );
Gia_ManCleanMark01( p );
Gia_ManCleanPhase( p );
Gia_ManForEachCi( p, pObj, i )
pObj->fPhase = 1;
if ( fVerbose )
printf( "Running path detection: BoxDelay = %d, PathMin = %d, PathMax = %d, PathLimit = %d.\n", DelayC, nPathMin, nPathMax, nPathLimit );
for ( i = 0; i < nPathLimit; i++ )
{
MaxDelay = Gia_ManFindAnnotatedDelay( p, DelayC, &nBoxes, fIgnoreBoxDelays );
RetValue = Gia_ManFindPath( p, DelayC, nPathMin, nPathMax, vPath );
if ( RetValue == -1 )
break;
nPaths += (RetValue > 0);
if ( fVerbose )
printf( "Iter %5d : Paths = %2d. Boxes = %2d. Total boxes = %6d. Max delay = %5d.\n", i, nPaths, RetValue, nBoxes, MaxDelay );
}
Vec_IntFree( vPath );
Vec_IntFreeP( &p->vLevels );
Gia_ManCleanPhase( p );
return 1;
}
// annotate artificial chains and then put them into boxes
Gia_Man_t * Gia_ManDupWithArtificialBoxes( Gia_Man_t * p, int DelayC, int nPathMin, int nPathMax, int nPathLimit, int fUseFanout, int fXorTrick, int fIgnoreBoxDelays, int fVerbose )
{
Gia_Man_t * pNew;
/*
if ( Gia_ManBoxNum(p) > 0 )
{
printf( "Currently artifical carry-chains cannot be detected when natural ones are present.\n" );
return NULL;
}
*/
Gia_ManIteratePaths( p, DelayC, nPathMin, nPathMax, nPathLimit, fIgnoreBoxDelays, fVerbose );
pNew = Gia_ManDupWithArtificalFaddBoxes( p, fUseFanout, fXorTrick );
Gia_ManCleanMark01( p );
return pNew;
}
////////////////////////////////////////////////////////////////////////
/// END OF FILE ///
////////////////////////////////////////////////////////////////////////
ABC_NAMESPACE_IMPL_END
|
7a4df95eca8f9f669a22d8cf3a572495058f0a64
|
516529a515c2d870c21502162fe1701a18a23543
|
/posts/cuda-aware-mpi-example/src/Jacobi.h
|
316c2d24ce820ebbcce2c83fab000ecc173e584b
|
[
"LicenseRef-scancode-free-unknown"
] |
permissive
|
NVIDIA-developer-blog/code-samples
|
8a254a30b16e8598f8d8119acb57361f9538decd
|
3a495ce6219629f819c51cdaed5cd7bf5d91a636
|
refs/heads/master
| 2023-05-10T23:26:07.326839
| 2023-05-10T19:53:39
| 2023-05-10T19:53:39
| 3,694,405
| 662
| 287
|
BSD-3-Clause
| 2023-05-10T19:53:40
| 2012-03-12T11:21:35
|
HTML
|
UTF-8
|
C
| false
| false
| 6,752
|
h
|
Jacobi.h
|
/* Copyright (c) 2012, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA 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 ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __JACOBI_H__
#define __JACOBI_H__
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <cuda_runtime.h>
/**
* @file Jacobi.h
* @brief The header containing the most relevant functions for the Jacobi solver
*/
// =========
// Constants
// =========
/**
* Setting this to 1 makes the application use only single-precision floating-point data. Set this to
* 0 in order to use double-precision floating-point data instead.
*/
#define USE_FLOAT 0
/**
* This is the default domain size (when not explicitly stated with "-d" in the command-line arguments).
*/
#define DEFAULT_DOMAIN_SIZE 4096
/**
* This is the minimum acceptable domain size in any of the 2 dimensions.
*/
#define MIN_DOM_SIZE 3
/**
* This is the environment variable which allows the reading of the local rank of the current MPI
* process before the MPI environment gets initialized with MPI_Init(). This is necessary when running
* the CUDA-aware MPI version of the Jacobi solver, which needs this information in order to be able to
* set the CUDA device for the MPI process before MPI environment initialization. If you are using MVAPICH2,
* set this constant to "MV2_COMM_WORLD_LOCAL_RANK"; for Open MPI, use "OMPI_COMM_WORLD_LOCAL_RANK".
*/
#define ENV_LOCAL_RANK "MV2_COMM_WORLD_LOCAL_RANK"
/**
* This is the global rank of the root (master) process; in this application, it is mostly relevant for
* printing purposes.
*/
#define MPI_MASTER_RANK 0
/**
* This is the Jacobi tolerance threshold. The run is considered to have converged when the maximum residue
* falls below this value.
*/
#define JACOBI_TOLERANCE 1.0E-5F
/**
* This is the Jacobi iteration count limit. The Jacobi run will never cycle more than this, even if it
* has not converged when finishing the last allowed iteration.
*/
#define JACOBI_MAX_LOOPS 1000
#define DIR_TOP 0
#define DIR_RIGHT 1
#define DIR_BOTTOM 2
#define DIR_LEFT 3
/**
* This is the status value that indicates a successful operation.
*/
#define STATUS_OK 0
/**
* This is the status value that indicates an error.
*/
#define STATUS_ERR -1
#if USE_FLOAT
#define real float
#define MPI_CUSTOM_REAL MPI_FLOAT
#else
#define real double
#define MPI_CUSTOM_REAL MPI_DOUBLE
#endif
#define uint64 unsigned long long
#define SafeCudaCall(call) CheckCudaCall(call, #call, __FILE__, __LINE__)
#define SafeHostFree(block) { if (block) free(block); }
#define SafeDevFree(block) { if (block) SafeCudaCall(cudaFree(block)); }
#define OnePrintf(allow, ...) { if (allow) printf(__VA_ARGS__); }
#define OneErrPrintf(allow, ...) { if (allow) fprintf(stderr, __VA_ARGS__); }
#define HasNeighbor(neighbors, dir) (neighbors[dir] != MPI_PROC_NULL)
// =============
// Host routines
// =============
void Initialize(int * argc, char *** argv, int * rank, int * size);
void Finalize(real * devBlocks[2], real * devSideEdges[2], real * devHaloLines[2], real * hostSendLines[2],
real * hostRecvLines[2], real * devResidue, cudaStream_t copyStream);
int ParseCommandLineArguments(int argc, char ** argv, int rank, int size, int2 * domSize, int2 * topSize, int * useFastSwap);
int ApplyTopology(int * rank, int size, const int2 * topSize, int * neighbors, int2 * topIndex, MPI_Comm * cartComm);
void InitializeDataChunk(int topSizeY, int topIdxY, const int2 * domSize, const int * neighbors, cudaStream_t * copyStream, real * devBlocks[2],
real * devSideEdges[2], real * devHaloLines[2], real * hostSendLines[2], real * hostRecvLines[2], real ** devResidue);
void PreRunJacobi(MPI_Comm cartComm, int rank, int size, double * timerStart);
void RunJacobi(MPI_Comm cartComm, int rank, int size, const int2 * domSize, const int2 * topIndex, const int * neighbors, int useFastSwap,
real * devBlocks[2], real * devSideEdges[2], real * devHaloLines[2], real * hostSendLines[2], real * hostRecvLines[2], real * devResidue,
cudaStream_t copyStream, int * iterations, double * avgTransferTime);
void PostRunJacobi(MPI_Comm cartComm, int rank, int size, const int2 * topSize, const int2 * domSize, int iterations,
int useFastSwap, double timerStart, double avgTransferTime);
void SetDeviceBeforeInit();
void SetDeviceAfterInit(int rank);
void SafeCheckMPIStatus(MPI_Status * status, int expectedElems);
void ExchangeHalos(MPI_Comm cartComm, real * devSend, real * hostSend, real * hostRecv, real * devRecv, int neighbor, int elemCount);
// ===============
// Device wrappers
// ===============
#ifdef __cplusplus
extern "C"
{
#endif
void CheckCudaCall(cudaError_t command, const char * commandName, const char * fileName, int line);
real CallJacobiKernel(real * devBlocks[2], real * devResidue, const int4 * bounds, const int2 * size);
void CopyDeviceBlock(real * devBlocks[2], const int4 * bounds, const int2 * size);
void CopyDevHalosToBlock(real * devBlock, const real * devHaloLineLeft, const real * devHaloLineRight, const int2 * size, const int * neighbors);
void CopyDevSideEdgesFromBlock(const real * devBlock, real * devSideEdges[2], const int2 * size, const int * neighbors, cudaStream_t copyStream);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // __JACOBI_H__
|
05aff3d63a5883b1639836c1bff47f5396820336
|
821128c7e0c6b41c08474e98dffc9dd5f72b8857
|
/common/cf_unwrapper.c
|
4f54143c61a4f1c1166bf1d0cb79c5a82622bacf
|
[
"MIT"
] |
permissive
|
yuanrongxi/razor
|
304b9c5d5a9e011f212dbcb8c773f8e4b4133fef
|
b361d64ca3357226af3d6c9651bc235905066141
|
refs/heads/master
| 2023-07-19T07:47:49.092351
| 2023-07-16T07:17:50
| 2023-07-16T07:17:50
| 126,000,077
| 322
| 152
|
MIT
| 2021-09-07T10:49:37
| 2018-03-20T10:25:35
|
C++
|
UTF-8
|
C
| false
| false
| 2,162
|
c
|
cf_unwrapper.c
|
/*-
* Copyright (c) 2017-2018 Razor, Inc.
* All rights reserved.
*
* See the file LICENSE for redistribution information.
*/
#include "cf_unwrapper.h"
#include <assert.h>
#define UINT32_MAX_VAL 0XFFFFFFFF
#define UINT16_MAX_VAL 0XFFFF
#define IS_NEWER(type, bp, val, prev_val) do{ \
if (val - prev_val == (bp)) \
return (val > prev_val ? 0 : -1); \
if (val != prev_val && ((type)(val - prev_val)) < (bp)) \
return 0; \
return -1; \
}while (0)
void init_unwrapper16(cf_unwrapper_t* wrap)
{
wrap->size = sizeof(uint16_t);
wrap->last_value = 0;
}
static int wrap16_is_newer(uint16_t val, uint16_t prev_val)
{
IS_NEWER(uint16_t, (UINT16_MAX_VAL >> 1) + 1, val, prev_val);
}
static int64_t wrap16_update(cf_unwrapper_t* wrap, uint16_t val)
{
int64_t max_plus = (int64_t)UINT16_MAX_VAL + 1;
uint16_t cropped_last = (uint16_t)(wrap->last_value);
int64_t delta = val - cropped_last;
if (wrap16_is_newer(val, cropped_last) == 0){
if (delta < 0)
delta += max_plus;
}
else if (delta > 0 && wrap->last_value + delta - max_plus >= 0){
delta -= max_plus;
}
return wrap->last_value + delta;
}
int64_t wrap_uint16(cf_unwrapper_t* wrap, uint16_t val)
{
assert(wrap->size == sizeof(uint16_t));
wrap->last_value = wrap16_update(wrap, val);
return wrap->last_value;
}
void init_unwrapper32(cf_unwrapper_t* wrap)
{
wrap->size = sizeof(uint32_t);
wrap->last_value = 0;
}
static int wrap32_is_newer(uint32_t val, uint32_t prev_val)
{
IS_NEWER(uint32_t, (UINT32_MAX_VAL >> 1) + 1, val, prev_val);
}
static int64_t wrap32_update(cf_unwrapper_t* wrap, uint32_t val)
{
int64_t max_plus = (int64_t)UINT32_MAX_VAL + 1;
uint32_t cropped_last = (uint32_t)(wrap->last_value);
int64_t delta = val - cropped_last;
if (wrap32_is_newer(val, cropped_last) == 0){
if (delta < 0)
delta += max_plus;
}
else if (delta > 0 && wrap->last_value + delta - max_plus >= 0){
delta -= max_plus;
}
return wrap->last_value + delta;
}
int64_t wrap_uint32(cf_unwrapper_t* wrap, uint32_t val)
{
assert(wrap->size == sizeof(uint32_t));
wrap->last_value = wrap32_update(wrap, val);
return wrap->last_value;
}
|
e8189a699c21e4a87b9f6e590dbdfc046acc5f37
|
31406f420f019a191a74b9288a6e37dcd89e8e82
|
/tools/node-hermes/third-party/libuv/src/unix/os390-syscalls.h
|
ea599107b30281084918ce2bda9613318c6ae47c
|
[
"CC-BY-4.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"ISC",
"BSD-2-Clause"
] |
permissive
|
facebook/hermes
|
b1bf3cb60b5946450c7c9a421ac8dad7a675e0f5
|
440578b31ecce46fcc5ba2ad745ffd5712d63a35
|
refs/heads/main
| 2023-09-06T04:16:02.263184
| 2023-09-05T20:12:54
| 2023-09-05T20:12:54
| 154,201,259
| 8,449
| 593
|
MIT
| 2023-09-14T21:25:56
| 2018-10-22T19:13:00
|
C++
|
UTF-8
|
C
| false
| false
| 2,415
|
h
|
os390-syscalls.h
|
/* Copyright libuv project contributors. 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.
*/
#ifndef UV_OS390_SYSCALL_H_
#define UV_OS390_SYSCALL_H_
#include "uv.h"
#include "internal.h"
#include <dirent.h>
#include <poll.h>
#include <pthread.h>
#define EPOLL_CTL_ADD 1
#define EPOLL_CTL_DEL 2
#define EPOLL_CTL_MOD 3
#define MAX_EPOLL_INSTANCES 256
#define MAX_ITEMS_PER_EPOLL 1024
#define UV__O_CLOEXEC 0x80000
struct epoll_event {
int events;
int fd;
};
typedef struct {
QUEUE member;
struct pollfd* items;
unsigned long size;
int msg_queue;
} uv__os390_epoll;
/* epoll api */
uv__os390_epoll* epoll_create1(int flags);
int epoll_ctl(uv__os390_epoll* ep, int op, int fd, struct epoll_event *event);
int epoll_wait(uv__os390_epoll* ep, struct epoll_event *events, int maxevents, int timeout);
int epoll_file_close(int fd);
/* utility functions */
int nanosleep(const struct timespec* req, struct timespec* rem);
int scandir(const char* maindir, struct dirent*** namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **,
const struct dirent **));
char *mkdtemp(char* path);
ssize_t os390_readlink(const char* path, char* buf, size_t len);
size_t strnlen(const char* str, size_t maxlen);
#endif /* UV_OS390_SYSCALL_H_ */
|
5da200541fe5bb052b4571d84e894d47b23064fe
|
a8194cf6ffd12f7551eaba53572744080a0bfef3
|
/lib/trace/trace_internal.h
|
4d015229e120ca375fd7fd5cd7af5313e9594aa6
|
[
"Intel",
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
spdk/spdk
|
51294f67104b8c3d18f19147d63a212e9486c687
|
d62a3810364cb87be352c66acf7c7f968508ca17
|
refs/heads/master
| 2023-08-08T16:07:41.263000
| 2023-08-02T09:06:56
| 2023-08-08T07:01:20
| 39,042,157
| 2,708
| 1,158
|
NOASSERTION
| 2023-08-11T09:50:50
| 2015-07-13T23:15:15
|
C
|
UTF-8
|
C
| false
| false
| 282
|
h
|
trace_internal.h
|
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright (C) 2022 Intel Corporation.
* All rights reserved.
*/
#ifndef __TRACE_INTERNAL_H__
#define __TRACE_INTERNAL_H__
#include "spdk/trace.h"
/* Get shared memory file name. */
const char *trace_get_shm_name(void);
#endif
|
4cca60f56c0e658233e5bc6c938e10aa2d829dea
|
f7dc806f341ef5dbb0e11252a4693003a66853d5
|
/thirdparty/libwebp/src/enc/config_enc.c
|
3518b41403d8ecff957cdc02ec8a5fb6fd439052
|
[
"LicenseRef-scancode-free-unknown",
"MIT",
"CC-BY-4.0",
"OFL-1.1",
"Bison-exception-2.2",
"CC0-1.0",
"LicenseRef-scancode-nvidia-2002",
"LicenseRef-scancode-other-permissive",
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unicode",
"BSD-2-Clause",
"FTL",
"GPL-3.0-or-later",
"Bitstream-Vera",
"Zlib",
"MPL-2.0",
"MIT-Modern-Variant",
"JSON",
"Libpng"
] |
permissive
|
godotengine/godot
|
8a2419750f4851d1426a8f3bcb52cac5c86f23c2
|
970be7afdc111ccc7459d7ef3560de70e6d08c80
|
refs/heads/master
| 2023-08-21T14:37:00.262883
| 2023-08-21T06:26:15
| 2023-08-21T06:26:15
| 15,634,981
| 68,852
| 18,388
|
MIT
| 2023-09-14T21:42:16
| 2014-01-04T16:05:36
|
C++
|
UTF-8
|
C
| false
| false
| 5,774
|
c
|
config_enc.c
|
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the COPYING file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
// Coding tools configuration
//
// Author: Skal (pascal.massimino@gmail.com)
#ifdef HAVE_CONFIG_H
#include "src/webp/config.h"
#endif
#include "src/webp/encode.h"
//------------------------------------------------------------------------------
// WebPConfig
//------------------------------------------------------------------------------
int WebPConfigInitInternal(WebPConfig* config,
WebPPreset preset, float quality, int version) {
if (WEBP_ABI_IS_INCOMPATIBLE(version, WEBP_ENCODER_ABI_VERSION)) {
return 0; // caller/system version mismatch!
}
if (config == NULL) return 0;
config->quality = quality;
config->target_size = 0;
config->target_PSNR = 0.;
config->method = 4;
config->sns_strength = 50;
config->filter_strength = 60; // mid-filtering
config->filter_sharpness = 0;
config->filter_type = 1; // default: strong (so U/V is filtered too)
config->partitions = 0;
config->segments = 4;
config->pass = 1;
config->qmin = 0;
config->qmax = 100;
config->show_compressed = 0;
config->preprocessing = 0;
config->autofilter = 0;
config->partition_limit = 0;
config->alpha_compression = 1;
config->alpha_filtering = 1;
config->alpha_quality = 100;
config->lossless = 0;
config->exact = 0;
config->image_hint = WEBP_HINT_DEFAULT;
config->emulate_jpeg_size = 0;
config->thread_level = 0;
config->low_memory = 0;
config->near_lossless = 100;
config->use_delta_palette = 0;
config->use_sharp_yuv = 0;
// TODO(skal): tune.
switch (preset) {
case WEBP_PRESET_PICTURE:
config->sns_strength = 80;
config->filter_sharpness = 4;
config->filter_strength = 35;
config->preprocessing &= ~2; // no dithering
break;
case WEBP_PRESET_PHOTO:
config->sns_strength = 80;
config->filter_sharpness = 3;
config->filter_strength = 30;
config->preprocessing |= 2;
break;
case WEBP_PRESET_DRAWING:
config->sns_strength = 25;
config->filter_sharpness = 6;
config->filter_strength = 10;
break;
case WEBP_PRESET_ICON:
config->sns_strength = 0;
config->filter_strength = 0; // disable filtering to retain sharpness
config->preprocessing &= ~2; // no dithering
break;
case WEBP_PRESET_TEXT:
config->sns_strength = 0;
config->filter_strength = 0; // disable filtering to retain sharpness
config->preprocessing &= ~2; // no dithering
config->segments = 2;
break;
case WEBP_PRESET_DEFAULT:
default:
break;
}
return WebPValidateConfig(config);
}
int WebPValidateConfig(const WebPConfig* config) {
if (config == NULL) return 0;
if (config->quality < 0 || config->quality > 100) return 0;
if (config->target_size < 0) return 0;
if (config->target_PSNR < 0) return 0;
if (config->method < 0 || config->method > 6) return 0;
if (config->segments < 1 || config->segments > 4) return 0;
if (config->sns_strength < 0 || config->sns_strength > 100) return 0;
if (config->filter_strength < 0 || config->filter_strength > 100) return 0;
if (config->filter_sharpness < 0 || config->filter_sharpness > 7) return 0;
if (config->filter_type < 0 || config->filter_type > 1) return 0;
if (config->autofilter < 0 || config->autofilter > 1) return 0;
if (config->pass < 1 || config->pass > 10) return 0;
if (config->qmin < 0 || config->qmax > 100 || config->qmin > config->qmax) {
return 0;
}
if (config->show_compressed < 0 || config->show_compressed > 1) return 0;
if (config->preprocessing < 0 || config->preprocessing > 7) return 0;
if (config->partitions < 0 || config->partitions > 3) return 0;
if (config->partition_limit < 0 || config->partition_limit > 100) return 0;
if (config->alpha_compression < 0) return 0;
if (config->alpha_filtering < 0) return 0;
if (config->alpha_quality < 0 || config->alpha_quality > 100) return 0;
if (config->lossless < 0 || config->lossless > 1) return 0;
if (config->near_lossless < 0 || config->near_lossless > 100) return 0;
if (config->image_hint >= WEBP_HINT_LAST) return 0;
if (config->emulate_jpeg_size < 0 || config->emulate_jpeg_size > 1) return 0;
if (config->thread_level < 0 || config->thread_level > 1) return 0;
if (config->low_memory < 0 || config->low_memory > 1) return 0;
if (config->exact < 0 || config->exact > 1) return 0;
if (config->use_delta_palette < 0 || config->use_delta_palette > 1) {
return 0;
}
if (config->use_sharp_yuv < 0 || config->use_sharp_yuv > 1) return 0;
return 1;
}
//------------------------------------------------------------------------------
#define MAX_LEVEL 9
// Mapping between -z level and -m / -q parameter settings.
static const struct {
uint8_t method_;
uint8_t quality_;
} kLosslessPresets[MAX_LEVEL + 1] = {
{ 0, 0 }, { 1, 20 }, { 2, 25 }, { 3, 30 }, { 3, 50 },
{ 4, 50 }, { 4, 75 }, { 4, 90 }, { 5, 90 }, { 6, 100 }
};
int WebPConfigLosslessPreset(WebPConfig* config, int level) {
if (config == NULL || level < 0 || level > MAX_LEVEL) return 0;
config->lossless = 1;
config->method = kLosslessPresets[level].method_;
config->quality = kLosslessPresets[level].quality_;
return 1;
}
//------------------------------------------------------------------------------
|
26e18b4cd6567dce5ecccc7399cf66e8e54d0554
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/dm365/platform/reset.c
|
b706e5a4cc3aca3ddbe575e0da6413661de0fb32
|
[
"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
| 827
|
c
|
reset.c
|
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2010-11-13 weety first version
*/
#include <rthw.h>
#include <rtthread.h>
#include "dm36x.h"
/**
* @addtogroup DM36X
*/
/*@{*/
/**
* reset cpu by dog's time-out
*
*/
void machine_reset()
{
reset_system();
}
/**
* shutdown CPU
*
*/
void machine_shutdown()
{
}
#ifdef RT_USING_FINSH
#include <finsh.h>
#ifdef FINSH_USING_MSH
int cmd_reset(int argc, char** argv)
{
rt_hw_cpu_reset();
return 0;
}
MSH_CMD_EXPORT_ALIAS(cmd_reset, reset, restart the system);
int cmd_shutdown(int argc, char** argv)
{
rt_hw_cpu_shutdown();
return 0;
}
MSH_CMD_EXPORT_ALIAS(cmd_shutdown, shutdown, shutdown the system);
#endif
#endif
/*@}*/
|
aea388098e87208e4baa92eab1f4ecc6ba9a83ec
|
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
|
/lib/libc/musl/src/linux/setfsuid.c
|
1bae44186fdb791f627633ce8a0001d7f40830c3
|
[
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-musl-exception",
"MIT"
] |
permissive
|
ziglang/zig
|
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
|
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
|
refs/heads/master
| 2023-08-31T13:16:45.980913
| 2023-08-31T05:50:29
| 2023-08-31T05:50:29
| 40,276,274
| 25,560
| 2,399
|
MIT
| 2023-09-14T21:09:50
| 2015-08-06T00:51:28
|
Zig
|
UTF-8
|
C
| false
| false
| 109
|
c
|
setfsuid.c
|
#include <sys/fsuid.h>
#include "syscall.h"
int setfsuid(uid_t uid)
{
return syscall(SYS_setfsuid, uid);
}
|
581e515af2d0f0dea97cbec4976fac536e783350
|
d61b532db0d3e08818338cfaac530a1ced1ffe3b
|
/plat/pdpv7/libsys/gtty.c
|
5dd37c23b90b050fdd4e07362dbc0b79ab9d9f6f
|
[
"LicenseRef-scancode-other-permissive"
] |
permissive
|
davidgiven/ack
|
61049c7a8e95ff61a77b1edd3c22bb290720e276
|
db5a32c68c4a60ca26a3927a799ea662b5b2b0e5
|
refs/heads/default
| 2023-08-29T07:33:12.771205
| 2023-07-08T20:17:27
| 2023-07-08T20:17:27
| 37,686,316
| 376
| 74
|
NOASSERTION
| 2023-07-08T20:17:28
| 2015-06-18T21:33:42
|
C
|
UTF-8
|
C
| false
| false
| 192
|
c
|
gtty.c
|
extern int ioctl(int fd, unsigned int request, ...);
extern int _ioctl(int fd, int ioc, void* ptr);
int gtty(int fildes, char* argp)
{
return ioctl(fildes,/*TIOCGETP*/(('t'<<8)|8),argp) ;
}
|
81b994b010745f2ebf04e4d65eb6c64a9511c9a7
|
f9e7d65cb784c01a0200145ba8d289afe41d4a56
|
/driver/temp_sensor/g78x.h
|
fdd987fcbdeb73c925e3ba711836c0b2065cb6de
|
[
"BSD-3-Clause"
] |
permissive
|
FrameworkComputer/EmbeddedController
|
ad7086769e87d0a4179eae96a7c9ff5e383ff54e
|
f6d6b927eed71550d3475411cfc3e59abe5cef2a
|
refs/heads/hx20-hx30
| 2023-08-08T20:45:10.621169
| 2023-05-26T07:03:59
| 2023-05-26T07:03:59
| 447,021,040
| 846
| 48
|
BSD-3-Clause
| 2023-05-26T07:04:59
| 2022-01-12T00:11:14
|
C
|
UTF-8
|
C
| false
| false
| 4,900
|
h
|
g78x.h
|
/* Copyright 2016 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* G781/G782 temperature sensor module for Chrome EC */
#ifndef __CROS_EC_G78X_H
#define __CROS_EC_G78X_H
#if defined(CONFIG_TEMP_SENSOR_G781) && defined(CONFIG_TEMP_SENSOR_G782)
#error Cannot support both G781 and G782 together!
#endif
#define G78X_I2C_ADDR_FLAGS 0x4C
#define G78X_IDX_INTERNAL 0
#define G78X_IDX_EXTERNAL1 1
#define G78X_IDX_EXTERNAL2 2
#if defined(CONFIG_TEMP_SENSOR_G781)
/* G781 register */
#define G78X_TEMP_LOCAL 0x00
#define G78X_TEMP_REMOTE1 0x01
#define G78X_STATUS 0x02
#define G78X_CONFIGURATION_R 0x03
#define G78X_CONVERSION_RATE_R 0x04
#define G78X_LOCAL_TEMP_HIGH_LIMIT_R 0x05
#define G78X_LOCAL_TEMP_LOW_LIMIT_R 0x06
#define G78X_REMOTE1_TEMP_HIGH_LIMIT_R 0x07
#define G78X_REMOTE1_TEMP_LOW_LIMIT_R 0x08
#define G78X_CONFIGURATION_W 0x09
#define G78X_CONVERSION_RATE_W 0x0a
#define G78X_LOCAL_TEMP_HIGH_LIMIT_W 0x0b
#define G78X_LOCAL_TEMP_LOW_LIMIT_W 0x0c
#define G78X_REMOTE1_TEMP_HIGH_LIMIT_W 0x0d
#define G78X_REMOTE1_TEMP_LOW_LIMIT_W 0x0e
#define G78X_ONESHOT 0x0f
#define G78X_REMOTE1_TEMP_EXTENDED 0x10
#define G78X_REMOTE1_TEMP_OFFSET_HIGH 0x11
#define G78X_REMOTE1_TEMP_OFFSET_EXTD 0x12
#define G78X_REMOTE1_T_HIGH_LIMIT_EXTD 0x13
#define G78X_REMOTE1_T_LOW_LIMIT_EXTD 0x14
#define G78X_REMOTE1_TEMP_THERM_LIMIT 0x19
#define G78X_LOCAL_TEMP_THERM_LIMIT 0x20
#define G78X_THERM_HYSTERESIS 0x21
#define G78X_ALERT_FAULT_QUEUE_CODE 0x22
#define G78X_MANUFACTURER_ID 0xFE
#define G78X_DEVICE_ID 0xFF
/* Config register bits */
#define G78X_CONFIGURATION_STANDBY BIT(6)
#define G78X_CONFIGURATION_ALERT_MASK BIT(7)
/* Status register bits */
#define G78X_STATUS_LOCAL_TEMP_THERM_ALARM BIT(0)
#define G78X_STATUS_REMOTE1_TEMP_THERM_ALARM BIT(1)
#define G78X_STATUS_REMOTE1_TEMP_FAULT BIT(2)
#define G78X_STATUS_REMOTE1_TEMP_LOW_ALARM BIT(3)
#define G78X_STATUS_REMOTE1_TEMP_HIGH_ALARM BIT(4)
#define G78X_STATUS_LOCAL_TEMP_LOW_ALARM BIT(5)
#define G78X_STATUS_LOCAL_TEMP_HIGH_ALARM BIT(6)
#define G78X_STATUS_BUSY BIT(7)
#elif defined(CONFIG_TEMP_SENSOR_G782)
/* G782 register */
#define G78X_TEMP_LOCAL 0x00
#define G78X_TEMP_REMOTE1 0x01
#define G78X_TEMP_REMOTE2 0x02
#define G78X_STATUS 0x03
#define G78X_CONFIGURATION_R 0x04
#define G78X_CONFIGURATION_W 0x04
#define G78X_CONVERSION_RATE_R 0x05
#define G78X_CONVERSION_RATE_W 0x05
#define G78X_LOCAL_TEMP_HIGH_LIMIT_R 0x06
#define G78X_LOCAL_TEMP_HIGH_LIMIT_W 0x06
#define G78X_LOCAL_TEMP_LOW_LIMIT_R 0x07
#define G78X_LOCAL_TEMP_LOW_LIMIT_W 0x07
#define G78X_REMOTE1_TEMP_HIGH_LIMIT_R 0x08
#define G78X_REMOTE1_TEMP_HIGH_LIMIT_W 0x08
#define G78X_REMOTE1_TEMP_LOW_LIMIT_R 0x09
#define G78X_REMOTE1_TEMP_LOW_LIMIT_W 0x09
#define G78X_REMOTE2_TEMP_HIGH_LIMIT_R 0x0a
#define G78X_REMOTE2_TEMP_HIGH_LIMIT_W 0x0a
#define G78X_REMOTE2_TEMP_LOW_LIMIT_R 0x0b
#define G78X_REMOTE2_TEMP_LOW_LIMIT_W 0x0b
#define G78X_ONESHOT 0x0c
#define G78X_REMOTE1_TEMP_EXTENDED 0x0d
#define G78X_REMOTE1_TEMP_OFFSET_HIGH 0x0e
#define G78X_REMOTE1_TEMP_OFFSET_EXTD 0x0f
#define G78X_REMOTE1_T_HIGH_LIMIT_EXTD 0x10
#define G78X_REMOTE1_T_LOW_LIMIT_EXTD 0x11
#define G78X_REMOTE1_TEMP_THERM_LIMIT 0x12
#define G78X_REMOTE2_TEMP_EXTENDED 0x13
#define G78X_REMOTE2_TEMP_OFFSET_HIGH 0x14
#define G78X_REMOTE2_TEMP_OFFSET_EXTD 0x15
#define G78X_REMOTE2_T_HIGH_LIMIT_EXTD 0x16
#define G78X_REMOTE2_T_LOW_LIMIT_EXTD 0x17
#define G78X_REMOTE2_TEMP_THERM_LIMIT 0x18
#define G78X_STATUS1 0x19
#define G78X_LOCAL_TEMP_THERM_LIMIT 0x20
#define G78X_THERM_HYSTERESIS 0x21
#define G78X_ALERT_FAULT_QUEUE_CODE 0x22
#define G78X_MANUFACTURER_ID 0xFE
#define G78X_DEVICE_ID 0xFF
/* Config register bits */
#define G78X_CONFIGURATION_REMOTE2_DIS BIT(5)
#define G78X_CONFIGURATION_STANDBY BIT(6)
#define G78X_CONFIGURATION_ALERT_MASK BIT(7)
/* Status register bits */
#define G78X_STATUS_LOCAL_TEMP_LOW_ALARM BIT(0)
#define G78X_STATUS_LOCAL_TEMP_HIGH_ALARM BIT(1)
#define G78X_STATUS_LOCAL_TEMP_THERM_ALARM BIT(2)
#define G78X_STATUS_REMOTE2_TEMP_THERM_ALARM BIT(3)
#define G78X_STATUS_REMOTE1_TEMP_THERM_ALARM BIT(4)
#define G78X_STATUS_REMOTE2_TEMP_FAULT BIT(5)
#define G78X_STATUS_REMOTE1_TEMP_FAULT BIT(6)
#define G78X_STATUS_BUSY BIT(7)
/* Status1 register bits */
#define G78X_STATUS_REMOTE2_TEMP_LOW_ALARM BIT(4)
#define G78X_STATUS_REMOTE2_TEMP_HIGH_ALARM BIT(5)
#define G78X_STATUS_REMOTE1_TEMP_LOW_ALARM BIT(6)
#define G78X_STATUS_REMOTE1_TEMP_HIGH_ALARM BIT(7)
#endif
/**
* Get the last polled value of a sensor.
*
* @param idx Index to read. Idx indicates whether to read die
* temperature or external temperature.
* @param temp_ptr Destination for temperature in K.
*
* @return EC_SUCCESS if successful, non-zero if error.
*/
int g78x_get_val(int idx, int *temp_ptr);
#endif /* __CROS_EC_G78X_H */
|
d4994ec5a405ceb83df702dd180421b92df569e4
|
03666e5f961946fc1a0ac67781ac1425562ef0d7
|
/src/engine/rpc/EnginePropertiesRPC.C
|
443ef494c60c4ec7036ffe1409313b7606686759
|
[
"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
| 669
|
c
|
EnginePropertiesRPC.C
|
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
#include "EnginePropertiesRPC.h"
// ****************************************************************************
// Method: EnginePropertiesRPC
//
// Purpose:
// This is the RPC's constructor
//
// Programmer: Brad Whitlock
// Creation: Mon Oct 10 11:13:18 PDT 2011
//
// ****************************************************************************
EnginePropertiesRPC::EnginePropertiesRPC() : NonBlockingRPC("a", &returnAtts)
{
}
|
d737f1995c66591f3b12945dfd35a5a0c0ecb199
|
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
|
/lib/libc/include/any-macos.13-any/sys/event.h
|
d56e6dfaf09b2b6e3f063d9c0435be67ed4e9b29
|
[
"MIT"
] |
permissive
|
ziglang/zig
|
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
|
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
|
refs/heads/master
| 2023-08-31T13:16:45.980913
| 2023-08-31T05:50:29
| 2023-08-31T05:50:29
| 40,276,274
| 25,560
| 2,399
|
MIT
| 2023-09-14T21:09:50
| 2015-08-06T00:51:28
|
Zig
|
UTF-8
|
C
| false
| false
| 17,881
|
h
|
event.h
|
/*
* Copyright (c) 2003-2021 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
/*-
* Copyright (c) 1999,2000,2001 Jonathan Lemon <jlemon@FreeBSD.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/sys/sys/event.h,v 1.5.2.5 2001/12/14 19:21:22 jlemon Exp $
*/
#ifndef _SYS_EVENT_H_
#define _SYS_EVENT_H_
#include <machine/types.h>
#include <sys/cdefs.h>
#include <sys/queue.h>
#include <stdint.h>
#include <sys/types.h>
/*
* Filter types
*/
#define EVFILT_READ (-1)
#define EVFILT_WRITE (-2)
#define EVFILT_AIO (-3) /* attached to aio requests */
#define EVFILT_VNODE (-4) /* attached to vnodes */
#define EVFILT_PROC (-5) /* attached to struct proc */
#define EVFILT_SIGNAL (-6) /* attached to struct proc */
#define EVFILT_TIMER (-7) /* timers */
#define EVFILT_MACHPORT (-8) /* Mach portsets */
#define EVFILT_FS (-9) /* Filesystem events */
#define EVFILT_USER (-10) /* User events */
#define EVFILT_VM (-12) /* Virtual memory events */
#define EVFILT_EXCEPT (-15) /* Exception events */
#define EVFILT_SYSCOUNT 17
#define EVFILT_THREADMARKER EVFILT_SYSCOUNT /* Internal use only */
#pragma pack(4)
struct kevent {
uintptr_t ident; /* identifier for this event */
int16_t filter; /* filter for event */
uint16_t flags; /* general flags */
uint32_t fflags; /* filter-specific flags */
intptr_t data; /* filter-specific data */
void *udata; /* opaque user data identifier */
};
#pragma pack()
struct kevent64_s {
uint64_t ident; /* identifier for this event */
int16_t filter; /* filter for event */
uint16_t flags; /* general flags */
uint32_t fflags; /* filter-specific flags */
int64_t data; /* filter-specific data */
uint64_t udata; /* opaque user data identifier */
uint64_t ext[2]; /* filter-specific extensions */
};
#define EV_SET(kevp, a, b, c, d, e, f) do { \
struct kevent *__kevp__ = (kevp); \
__kevp__->ident = (a); \
__kevp__->filter = (b); \
__kevp__->flags = (c); \
__kevp__->fflags = (d); \
__kevp__->data = (e); \
__kevp__->udata = (f); \
} while(0)
#define EV_SET64(kevp, a, b, c, d, e, f, g, h) do { \
struct kevent64_s *__kevp__ = (kevp); \
__kevp__->ident = (a); \
__kevp__->filter = (b); \
__kevp__->flags = (c); \
__kevp__->fflags = (d); \
__kevp__->data = (e); \
__kevp__->udata = (f); \
__kevp__->ext[0] = (g); \
__kevp__->ext[1] = (h); \
} while(0)
/* kevent system call flags */
#define KEVENT_FLAG_NONE 0x000000 /* no flag value */
#define KEVENT_FLAG_IMMEDIATE 0x000001 /* immediate timeout */
#define KEVENT_FLAG_ERROR_EVENTS 0x000002 /* output events only include change errors */
/* actions */
#define EV_ADD 0x0001 /* add event to kq (implies enable) */
#define EV_DELETE 0x0002 /* delete event from kq */
#define EV_ENABLE 0x0004 /* enable event */
#define EV_DISABLE 0x0008 /* disable event (not reported) */
/* flags */
#define EV_ONESHOT 0x0010 /* only report one occurrence */
#define EV_CLEAR 0x0020 /* clear event state after reporting */
#define EV_RECEIPT 0x0040 /* force immediate event output */
/* ... with or without EV_ERROR */
/* ... use KEVENT_FLAG_ERROR_EVENTS */
/* on syscalls supporting flags */
#define EV_DISPATCH 0x0080 /* disable event after reporting */
#define EV_UDATA_SPECIFIC 0x0100 /* unique kevent per udata value */
#define EV_DISPATCH2 (EV_DISPATCH | EV_UDATA_SPECIFIC)
/* ... in combination with EV_DELETE */
/* will defer delete until udata-specific */
/* event enabled. EINPROGRESS will be */
/* returned to indicate the deferral */
#define EV_VANISHED 0x0200 /* report that source has vanished */
/* ... only valid with EV_DISPATCH2 */
#define EV_SYSFLAGS 0xF000 /* reserved by system */
#define EV_FLAG0 0x1000 /* filter-specific flag */
#define EV_FLAG1 0x2000 /* filter-specific flag */
/* returned values */
#define EV_EOF 0x8000 /* EOF detected */
#define EV_ERROR 0x4000 /* error, data contains errno */
/*
* Filter specific flags for EVFILT_READ
*
* The default behavior for EVFILT_READ is to make the "read" determination
* relative to the current file descriptor read pointer.
*
* The EV_POLL flag indicates the determination should be made via poll(2)
* semantics. These semantics dictate always returning true for regular files,
* regardless of the amount of unread data in the file.
*
* On input, EV_OOBAND specifies that filter should actively return in the
* presence of OOB on the descriptor. It implies that filter will return
* if there is OOB data available to read OR when any other condition
* for the read are met (for example number of bytes regular data becomes >=
* low-watermark).
* If EV_OOBAND is not set on input, it implies that the filter should not actively
* return for out of band data on the descriptor. The filter will then only return
* when some other condition for read is met (ex: when number of regular data bytes
* >=low-watermark OR when socket can't receive more data (SS_CANTRCVMORE)).
*
* On output, EV_OOBAND indicates the presence of OOB data on the descriptor.
* If it was not specified as an input parameter, then the data count is the
* number of bytes before the current OOB marker, else data count is the number
* of bytes beyond OOB marker.
*/
#define EV_POLL EV_FLAG0
#define EV_OOBAND EV_FLAG1
/*
* data/hint fflags for EVFILT_USER, shared with userspace
*/
/*
* On input, NOTE_TRIGGER causes the event to be triggered for output.
*/
#define NOTE_TRIGGER 0x01000000
/*
* On input, the top two bits of fflags specifies how the lower twenty four
* bits should be applied to the stored value of fflags.
*
* On output, the top two bits will always be set to NOTE_FFNOP and the
* remaining twenty four bits will contain the stored fflags value.
*/
#define NOTE_FFNOP 0x00000000 /* ignore input fflags */
#define NOTE_FFAND 0x40000000 /* and fflags */
#define NOTE_FFOR 0x80000000 /* or fflags */
#define NOTE_FFCOPY 0xc0000000 /* copy fflags */
#define NOTE_FFCTRLMASK 0xc0000000 /* mask for operations */
#define NOTE_FFLAGSMASK 0x00ffffff
/*
* data/hint fflags for EVFILT_{READ|WRITE}, shared with userspace
*
* The default behavior for EVFILT_READ is to make the determination
* realtive to the current file descriptor read pointer.
*/
#define NOTE_LOWAT 0x00000001 /* low water mark */
/* data/hint flags for EVFILT_EXCEPT, shared with userspace */
#define NOTE_OOB 0x00000002 /* OOB data */
/*
* data/hint fflags for EVFILT_VNODE, shared with userspace
*/
#define NOTE_DELETE 0x00000001 /* vnode was removed */
#define NOTE_WRITE 0x00000002 /* data contents changed */
#define NOTE_EXTEND 0x00000004 /* size increased */
#define NOTE_ATTRIB 0x00000008 /* attributes changed */
#define NOTE_LINK 0x00000010 /* link count changed */
#define NOTE_RENAME 0x00000020 /* vnode was renamed */
#define NOTE_REVOKE 0x00000040 /* vnode access was revoked */
#define NOTE_NONE 0x00000080 /* No specific vnode event: to test for EVFILT_READ activation*/
#define NOTE_FUNLOCK 0x00000100 /* vnode was unlocked by flock(2) */
#define NOTE_LEASE_DOWNGRADE 0x00000200 /* lease downgrade requested */
#define NOTE_LEASE_RELEASE 0x00000400 /* lease release requested */
/*
* data/hint fflags for EVFILT_PROC, shared with userspace
*
* Please note that EVFILT_PROC and EVFILT_SIGNAL share the same knote list
* that hangs off the proc structure. They also both play games with the hint
* passed to KNOTE(). If NOTE_SIGNAL is passed as a hint, then the lower bits
* of the hint contain the signal. IF NOTE_FORK is passed, then the lower bits
* contain the PID of the child (but the pid does not get passed through in
* the actual kevent).
*/
enum {
eNoteReapDeprecated __deprecated_enum_msg("This kqueue(2) EVFILT_PROC flag is deprecated") = 0x10000000
};
#define NOTE_EXIT 0x80000000 /* process exited */
#define NOTE_FORK 0x40000000 /* process forked */
#define NOTE_EXEC 0x20000000 /* process exec'd */
#define NOTE_REAP ((unsigned int)eNoteReapDeprecated /* 0x10000000 */ ) /* process reaped */
#define NOTE_SIGNAL 0x08000000 /* shared with EVFILT_SIGNAL */
#define NOTE_EXITSTATUS 0x04000000 /* exit status to be returned, valid for child process or when allowed to signal target pid */
#define NOTE_EXIT_DETAIL 0x02000000 /* provide details on reasons for exit */
#define NOTE_PDATAMASK 0x000fffff /* mask for signal & exit status */
#define NOTE_PCTRLMASK (~NOTE_PDATAMASK)
/*
* If NOTE_EXITSTATUS is present, provide additional info about exiting process.
*/
enum {
eNoteExitReparentedDeprecated __deprecated_enum_msg("This kqueue(2) EVFILT_PROC flag is no longer sent") = 0x00080000
};
#define NOTE_EXIT_REPARENTED ((unsigned int)eNoteExitReparentedDeprecated) /* exited while reparented */
/*
* If NOTE_EXIT_DETAIL is present, these bits indicate specific reasons for exiting.
*/
#define NOTE_EXIT_DETAIL_MASK 0x00070000
#define NOTE_EXIT_DECRYPTFAIL 0x00010000
#define NOTE_EXIT_MEMORY 0x00020000
#define NOTE_EXIT_CSERROR 0x00040000
/*
* data/hint fflags for EVFILT_VM, shared with userspace.
*/
#define NOTE_VM_PRESSURE 0x80000000 /* will react on memory pressure */
#define NOTE_VM_PRESSURE_TERMINATE 0x40000000 /* will quit on memory pressure, possibly after cleaning up dirty state */
#define NOTE_VM_PRESSURE_SUDDEN_TERMINATE 0x20000000 /* will quit immediately on memory pressure */
#define NOTE_VM_ERROR 0x10000000 /* there was an error */
/*
* data/hint fflags for EVFILT_TIMER, shared with userspace.
* The default is a (repeating) interval timer with the data
* specifying the timeout interval in milliseconds.
*
* All timeouts are implicitly EV_CLEAR events.
*/
#define NOTE_SECONDS 0x00000001 /* data is seconds */
#define NOTE_USECONDS 0x00000002 /* data is microseconds */
#define NOTE_NSECONDS 0x00000004 /* data is nanoseconds */
#define NOTE_ABSOLUTE 0x00000008 /* absolute timeout */
/* ... implicit EV_ONESHOT, timeout uses the gettimeofday epoch */
#define NOTE_LEEWAY 0x00000010 /* ext[1] holds leeway for power aware timers */
#define NOTE_CRITICAL 0x00000020 /* system does minimal timer coalescing */
#define NOTE_BACKGROUND 0x00000040 /* system does maximum timer coalescing */
#define NOTE_MACH_CONTINUOUS_TIME 0x00000080
/*
* NOTE_MACH_CONTINUOUS_TIME:
* with NOTE_ABSOLUTE: causes the timer to continue to tick across sleep,
* still uses gettimeofday epoch
* with NOTE_MACHTIME and NOTE_ABSOLUTE: uses mach continuous time epoch
* without NOTE_ABSOLUTE (interval timer mode): continues to tick across sleep
*/
#define NOTE_MACHTIME 0x00000100 /* data is mach absolute time units */
/* timeout uses the mach absolute time epoch */
/*
* data/hint fflags for EVFILT_MACHPORT, shared with userspace.
*
* Only portsets are supported at this time.
*
* The fflags field can optionally contain the MACH_RCV_MSG, MACH_RCV_LARGE,
* and related trailer receive options as defined in <mach/message.h>.
* The presence of these flags directs the kevent64() call to attempt to receive
* the message during kevent delivery, rather than just indicate that a message exists.
* On setup, The ext[0] field contains the receive buffer pointer and ext[1] contains
* the receive buffer length. Upon event delivery, the actual received message size
* is returned in ext[1]. As with mach_msg(), the buffer must be large enough to
* receive the message and the requested (or default) message trailers. In addition,
* the fflags field contains the return code normally returned by mach_msg().
*
* If MACH_RCV_MSG is specified, and the ext[1] field specifies a zero length, the
* system call argument specifying an ouput area (kevent_qos) will be consulted. If
* the system call specified an output data area, the user-space address
* of the received message is carved from that provided output data area (if enough
* space remains there). The address and length of each received message is
* returned in the ext[0] and ext[1] fields (respectively) of the corresponding kevent.
*
* IF_MACH_RCV_VOUCHER_CONTENT is specified, the contents of the message voucher is
* extracted (as specified in the xflags field) and stored in ext[2] up to ext[3]
* length. If the input length is zero, and the system call provided a data area,
* the space for the voucher content is carved from the provided space and its
* address and length is returned in ext[2] and ext[3] respectively.
*
* If no message receipt options were provided in the fflags field on setup, no
* message is received by this call. Instead, on output, the data field simply
* contains the name of the actual port detected with a message waiting.
*/
/*
* DEPRECATED!!!!!!!!!
* NOTE_TRACK, NOTE_TRACKERR, and NOTE_CHILD are no longer supported as of 10.5
*/
/* additional flags for EVFILT_PROC */
#define NOTE_TRACK 0x00000001 /* follow across forks */
#define NOTE_TRACKERR 0x00000002 /* could not track child */
#define NOTE_CHILD 0x00000004 /* am a child process */
/* Temporay solution for BootX to use inode.h till kqueue moves to vfs layer */
struct knote;
SLIST_HEAD(klist, knote);
struct timespec;
__BEGIN_DECLS
int kqueue(void);
int kevent(int kq,
const struct kevent *changelist, int nchanges,
struct kevent *eventlist, int nevents,
const struct timespec *timeout);
int kevent64(int kq,
const struct kevent64_s *changelist, int nchanges,
struct kevent64_s *eventlist, int nevents,
unsigned int flags,
const struct timespec *timeout);
__END_DECLS
#endif /* !_SYS_EVENT_H_ */
|
71b474119eb2b55cab3661773f294a8330a6a058
|
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
|
/audio/lash/files/patch-liblash_lash.c
|
d6d9279625fc48353f41563339c73e89c3a3162a
|
[
"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
| 271
|
c
|
patch-liblash_lash.c
|
--- liblash/lash.c.orig 2007-03-09 15:34:40 UTC
+++ liblash/lash.c
@@ -23,6 +23,8 @@
#include <strings.h>
#include <pthread.h>
#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/resource.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netdb.h>
|
21b2576310036171dd38fad2bf9bab5d9c2ec043
|
1efb2283837c9b70bc6449cec877799e4efa3268
|
/src/mpid/ch4/shm/posix/posix_coll_gpu_ipc.h
|
116dc0f63d3f2b5f37cf109ac756c600d5bfee9f
|
[
"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
| 10,702
|
h
|
posix_coll_gpu_ipc.h
|
/*
* Copyright (C) by Argonne National Laboratory
* See COPYRIGHT in top-level directory
*/
/*
=== BEGIN_MPI_T_CVAR_INFO_BLOCK ===
cvars:
- name : MPIR_CVAR_BCAST_IPC_READ_MSG_SIZE_THRESHOLD
category : COLLECTIVE
type : int
default : 256
class : none
verbosity : MPI_T_VERBOSITY_USER_BASIC
scope : MPI_T_SCOPE_ALL_EQ
description : >-
Use gpu ipc read bcast only when the message size is larger than this
threshold.
- name : MPIR_CVAR_ALLTOALL_IPC_READ_MSG_SIZE_THRESHOLD
category : COLLECTIVE
type : int
default : 256
class : none
verbosity : MPI_T_VERBOSITY_USER_BASIC
scope : MPI_T_SCOPE_ALL_EQ
description : >-
Use gpu ipc read alltoall only when the message size is larger than this
threshold.
=== END_MPI_T_CVAR_INFO_BLOCK ===
*/
#ifndef POSIX_COLL_GPU_IPC_H_INCLUDED
#define POSIX_COLL_GPU_IPC_H_INCLUDED
#include "../ipc/src/ipc_types.h"
#include "../ipc/src/ipc_p2p.h"
#include "../gpu/gpu_post.h"
#include "../../../include/mpir_err.h"
MPL_STATIC_INLINE_PREFIX int MPIDI_POSIX_mpi_bcast_gpu_ipc_read(void *buffer,
MPI_Aint count,
MPI_Datatype datatype,
int root, MPIR_Comm * comm_ptr,
MPIR_Errflag_t errflag)
{
MPIR_FUNC_ENTER;
MPIR_CHKLMEM_DECL(1);
int mpi_errno = MPI_SUCCESS, mpi_errno_ret = MPI_SUCCESS;
MPI_Aint true_lb;
MPIR_Datatype *dt_ptr;
bool dt_contig;
uintptr_t data_sz;
MPIDI_Datatype_get_info(count, datatype, dt_contig, data_sz, dt_ptr, true_lb);
/* fallback if datatype is not contiguous or data size is not large enough */
if (!dt_contig || data_sz <= MPIR_CVAR_BCAST_IPC_READ_MSG_SIZE_THRESHOLD) {
goto fallback;
}
void *mem_addr = MPIR_get_contig_ptr(buffer, true_lb);
int my_rank = MPIR_Comm_rank(comm_ptr);
int comm_size = MPIR_Comm_size(comm_ptr);
MPIDI_IPCI_ipc_attr_t ipc_attr;
memset(&ipc_attr, 0, sizeof(ipc_attr));
MPIR_GPU_query_pointer_attr(mem_addr, &ipc_attr.gpu_attr);
/* set up ipc_handles */
MPIDI_IPCI_ipc_handle_t *ipc_handles = NULL;
MPIR_CHKLMEM_MALLOC(ipc_handles, MPIDI_IPCI_ipc_handle_t *,
sizeof(MPIDI_IPCI_ipc_handle_t) * comm_size, mpi_errno, "IPC handles",
MPL_MEM_COLL);
MPIDI_IPCI_ipc_handle_t my_ipc_handle;
memset(&my_ipc_handle, 0, sizeof(my_ipc_handle));
int dev_id = MPL_gpu_get_dev_id_from_attr(&ipc_attr.gpu_attr);
/* CPU memory, registered host memory and USM fallback to P2P bcast,
* GPU memory will use ipc read bcast
*/
if (dev_id >= 0 && ipc_attr.gpu_attr.type == MPL_GPU_POINTER_DEV) {
mpi_errno = MPIDI_GPU_get_ipc_attr(mem_addr, my_rank, comm_ptr, &ipc_attr);
MPIR_ERR_CHECK(mpi_errno);
my_ipc_handle = ipc_attr.ipc_handle;
} else {
my_ipc_handle.gpu.global_dev_id = -1;
}
/* allgather is needed to exchange all the IPC handles */
mpi_errno =
MPIR_Allgather_impl(&my_ipc_handle, sizeof(MPIDI_IPCI_ipc_handle_t), MPI_BYTE, ipc_handles,
sizeof(MPIDI_IPCI_ipc_handle_t), MPI_BYTE, comm_ptr, errflag);
MPIR_ERR_CHECK(mpi_errno);
/* check the ipc_handles to make sure all the buffers are on GPU */
int errs = 0;
for (int i = 0; i < comm_size; i++) {
if (ipc_handles[i].gpu.global_dev_id < 0) {
errs++;
break;
}
}
if (errs > 0) {
goto fallback;
}
if (my_rank != root) {
/* map root's ipc_handle to remote_buf */
void *remote_buf = NULL;
bool do_mmap = (data_sz <= MPIR_CVAR_CH4_IPC_GPU_FAST_COPY_MAX_SIZE);
int root_dev =
MPIDI_GPU_ipc_get_map_dev(ipc_handles[root].gpu.global_dev_id, dev_id, datatype);
mpi_errno = MPIDI_GPU_ipc_handle_map(ipc_handles[root].gpu, root_dev, &remote_buf, do_mmap);
MPIR_ERR_CHECK(mpi_errno);
/* get engine type */
MPL_gpu_engine_type_t engine_type =
MPIDI_IPCI_choose_engine(ipc_handles[root].gpu.global_dev_id,
my_ipc_handle.gpu.global_dev_id);
/* copy data from root */
mpi_errno = MPIR_Localcopy_gpu(remote_buf, count, datatype, NULL,
mem_addr, count, datatype, &ipc_attr.gpu_attr,
MPL_GPU_COPY_D2D_INCOMING, engine_type, true);
MPIR_ERR_CHECK(mpi_errno);
}
fn_exit:
MPIR_CHKLMEM_FREEALL();
MPIR_FUNC_EXIT;
return mpi_errno_ret;
fn_fail:
goto fn_exit;
fallback:
/* Fall back to other algorithms as gpu ipc bcast cannot be used */
mpi_errno = MPIR_Bcast_impl(buffer, count, datatype, root, comm_ptr, errflag);
MPIR_ERR_COLL_CHECKANDCONT(mpi_errno, errflag, mpi_errno_ret);
goto fn_exit;
}
MPL_STATIC_INLINE_PREFIX int MPIDI_POSIX_mpi_alltoall_gpu_ipc_read(const void *sendbuf,
MPI_Aint sendcount,
MPI_Datatype sendtype,
void *recvbuf,
MPI_Aint recvcount,
MPI_Datatype recvtype,
MPIR_Comm * comm_ptr,
MPIR_Errflag_t errflag)
{
MPIR_FUNC_ENTER;
MPIR_CHKLMEM_DECL(3);
int mpi_errno = MPI_SUCCESS, mpi_errno_ret = MPI_SUCCESS;
/* fallback if sendtype and recvtype is different */
if (sendtype != recvtype || sendcount != recvcount) {
goto fallback;
}
MPI_Aint true_lb;
MPIR_Datatype *dt_ptr;
bool dt_contig;
uintptr_t data_sz;
MPIDI_Datatype_get_info(sendcount, sendtype, dt_contig, data_sz, dt_ptr, true_lb);
/* fallback if datatype is not contiguous or data size is not large enough */
if (!dt_contig || data_sz <= MPIR_CVAR_ALLTOALL_IPC_READ_MSG_SIZE_THRESHOLD) {
goto fallback;
}
void *send_mem_addr = MPIR_get_contig_ptr(sendbuf, true_lb);
void *recv_mem_addr = MPIR_get_contig_ptr(recvbuf, true_lb);
MPIDI_IPCI_ipc_attr_t ipc_attr;
memset(&ipc_attr, 0, sizeof(ipc_attr));
MPIR_GPU_query_pointer_attr(send_mem_addr, &ipc_attr.gpu_attr);
int my_rank = MPIR_Comm_rank(comm_ptr);
int comm_size = MPIR_Comm_size(comm_ptr);
/* set up ipc_handles */
MPIDI_IPCI_ipc_handle_t *ipc_handles = NULL;
MPIR_CHKLMEM_MALLOC(ipc_handles, MPIDI_IPCI_ipc_handle_t *,
sizeof(MPIDI_IPCI_ipc_handle_t) * comm_size, mpi_errno, "IPC handles",
MPL_MEM_COLL);
MPIDI_IPCI_ipc_handle_t my_ipc_handle;
memset(&my_ipc_handle, 0, sizeof(my_ipc_handle));
int dev_id = MPL_gpu_get_dev_id_from_attr(&ipc_attr.gpu_attr);
/* CPU memory, registered host memory and USM fallback to P2P alltoall,
* GPU memory will use ipc read alltoall
*/
if (dev_id >= 0 && ipc_attr.gpu_attr.type == MPL_GPU_POINTER_DEV) {
mpi_errno = MPIDI_GPU_get_ipc_attr(send_mem_addr, my_rank, comm_ptr, &ipc_attr);
MPIR_ERR_CHECK(mpi_errno);
my_ipc_handle = ipc_attr.ipc_handle;
} else {
my_ipc_handle.gpu.global_dev_id = -1;
}
/* allgather is needed to exchange all the IPC handles */
mpi_errno =
MPIR_Allgather_impl(&my_ipc_handle, sizeof(MPIDI_IPCI_ipc_handle_t), MPI_BYTE, ipc_handles,
sizeof(MPIDI_IPCI_ipc_handle_t), MPI_BYTE, comm_ptr, errflag);
MPIR_ERR_CHECK(mpi_errno);
/* check the ipc_handles to make sure all the buffers are on GPU */
int errs = 0;
for (int i = 0; i < comm_size; i++) {
if (ipc_handles[i].gpu.global_dev_id < 0) {
errs++;
break;
}
}
if (errs > 0) {
goto fallback;
}
/* map ipc_handles to remote_bufs */
void **remote_bufs = NULL;
MPIR_CHKLMEM_MALLOC(remote_bufs, void **, sizeof(void *) * comm_size, mpi_errno, "Remote bufs",
MPL_MEM_COLL);
for (int i = 0; i < comm_size; i++) {
if (i != my_rank) {
int remote_dev =
MPIDI_GPU_ipc_get_map_dev(ipc_handles[i].gpu.global_dev_id, dev_id, sendtype);
mpi_errno =
MPIDI_GPU_ipc_handle_map(ipc_handles[i].gpu, remote_dev, &(remote_bufs[i]), false);
MPIR_ERR_CHECK(mpi_errno);
} else {
remote_bufs[i] = send_mem_addr;
}
}
/* use imemcpy to copy the data concurrently */
MPL_gpu_request *reqs = NULL;
MPIR_CHKLMEM_MALLOC(reqs, MPL_gpu_request *, sizeof(MPL_gpu_request) * comm_size, mpi_errno,
"Memcpy requests", MPL_MEM_COLL);
for (int i = 0; i < comm_size; i++) {
char *temp_recv = (char *) recv_mem_addr + i * data_sz;
char *temp_send = (char *) (remote_bufs[i]) + my_rank * data_sz;
/* get engine type */
MPL_gpu_engine_type_t engine_type =
MPIDI_IPCI_choose_engine(ipc_handles[i].gpu.global_dev_id,
my_ipc_handle.gpu.global_dev_id);
mpi_errno =
MPL_gpu_imemcpy((char *) MPIR_get_contig_ptr(temp_recv, true_lb),
(char *) MPIR_get_contig_ptr(temp_send, true_lb),
data_sz, dev_id, MPL_GPU_COPY_DIRECTION_NONE,
engine_type, &reqs[i], true);
MPIR_ERR_CHECK(mpi_errno);
}
/* wait for the imemcpy to finish */
for (int i = 0; i < comm_size; i++) {
int completed = 0;
while (!completed) {
mpi_errno = MPL_gpu_test(&reqs[i], &completed);
MPIR_ERR_CHECK(mpi_errno);
}
}
fn_exit:
MPIR_CHKLMEM_FREEALL();
MPIR_FUNC_EXIT;
return mpi_errno_ret;
fn_fail:
goto fn_exit;
fallback:
/* Fall back to other algorithms as gpu ipc alltoall cannot be used */
mpi_errno = MPIR_Alltoall_impl(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype,
comm_ptr, errflag);
MPIR_ERR_COLL_CHECKANDCONT(mpi_errno, errflag, mpi_errno_ret);
goto fn_exit;
}
#endif /* POSIX_COLL_GPU_IPC_H_INCLUDED */
|
9126449540d3420c76bd9f0997001e37e1b3055d
|
33377c4d113cf9ea1338077af6bd645f3c5796b3
|
/extensions/android/ringlibsdl/project/jni/libmikmod-3.1.12/playercode/sloader.c
|
2fe62409064adf42492e0f370c887bf863d5cd78
|
[
"LicenseRef-scancode-free-unknown",
"MIT",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LGPL-2.1-only",
"LGPL-2.0-only",
"xlock"
] |
permissive
|
ring-lang/ring
|
56f55111f751b0274d4f588871f806a8c2734dea
|
2081d2efb41c9dacd49b7a6944b9ca332638ba64
|
refs/heads/master
| 2023-09-04T16:54:44.309452
| 2023-09-03T10:28:57
| 2023-09-03T10:28:57
| 54,633,811
| 1,360
| 555
|
MIT
| 2023-08-03T01:48:24
| 2016-03-24T10:29:27
|
C
|
UTF-8
|
C
| false
| false
| 11,665
|
c
|
sloader.c
|
/* MikMod sound library
(c) 1998, 1999, 2000, 2001 Miodrag Vallat and others - see file AUTHORS
for complete list.
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This 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 Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
*/
/*==============================================================================
$Id: sloader.c,v 1.1.1.1 2004/06/01 12:16:18 raph Exp $
Routines for loading samples. The sample loader utilizes the routines
provided by the "registered" sample loader.
==============================================================================*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "mikmod_internals.h"
static int sl_rlength;
static SWORD sl_old;
static SWORD *sl_buffer=NULL;
static SAMPLOAD *musiclist=NULL,*sndfxlist=NULL;
/* size of the loader buffer in words */
#define SLBUFSIZE 2048
/* IT-Compressed status structure */
typedef struct ITPACK {
UWORD bits; /* current number of bits */
UWORD bufbits; /* bits in buffer */
SWORD last; /* last output */
UBYTE buf; /* bit buffer */
} ITPACK;
BOOL SL_Init(SAMPLOAD* s)
{
if(!sl_buffer)
if(!(sl_buffer=_mm_malloc(SLBUFSIZE*sizeof(SWORD)))) return 0;
sl_rlength = s->length;
if(s->infmt & SF_16BITS) sl_rlength>>=1;
sl_old = 0;
return 1;
}
void SL_Exit(SAMPLOAD *s)
{
if(sl_rlength>0) _mm_fseek(s->reader,sl_rlength,SEEK_CUR);
if(sl_buffer) {
free(sl_buffer);
sl_buffer=NULL;
}
}
/* unpack a 8bit IT packed sample */
static BOOL read_itcompr8(ITPACK* status,MREADER *reader,SWORD *sl_buffer,UWORD count,UWORD* incnt)
{
SWORD *dest=sl_buffer,*end=sl_buffer+count;
UWORD x,y,needbits,havebits,new_count=0;
UWORD bits = status->bits;
UWORD bufbits = status->bufbits;
SBYTE last = status->last;
UBYTE buf = status->buf;
while (dest<end) {
needbits=new_count?3:bits;
x=havebits=0;
while (needbits) {
/* feed buffer */
if (!bufbits) {
if((*incnt)--)
buf=_mm_read_UBYTE(reader);
else
buf=0;
bufbits=8;
}
/* get as many bits as necessary */
y = needbits<bufbits?needbits:bufbits;
x|= (buf & ((1<<y)- 1))<<havebits;
buf>>=y;
bufbits-=y;
needbits-=y;
havebits+=y;
}
if (new_count) {
new_count = 0;
if (++x >= bits)
x++;
bits = x;
continue;
}
if (bits<7) {
if (x==(1<<(bits-1))) {
new_count = 1;
continue;
}
}
else if (bits<9) {
y = (0xff >> (9-bits)) - 4;
if ((x>y)&&(x<=y+8)) {
if ((x-=y)>=bits)
x++;
bits = x;
continue;
}
}
else if (bits<10) {
if (x>=0x100) {
bits=x-0x100+1;
continue;
}
} else {
/* error in compressed data... */
_mm_errno=MMERR_ITPACK_INVALID_DATA;
return 0;
}
if (bits<8) /* extend sign */
x = ((SBYTE)(x <<(8-bits))) >> (8-bits);
*(dest++)= (last+=x) << 8; /* convert to 16 bit */
}
status->bits = bits;
status->bufbits = bufbits;
status->last = last;
status->buf = buf;
return dest-sl_buffer;
}
/* unpack a 16bit IT packed sample */
static BOOL read_itcompr16(ITPACK *status,MREADER *reader,SWORD *sl_buffer,UWORD count,UWORD* incnt)
{
SWORD *dest=sl_buffer,*end=sl_buffer+count;
SLONG x,y,needbits,havebits,new_count=0;
UWORD bits = status->bits;
UWORD bufbits = status->bufbits;
SWORD last = status->last;
UBYTE buf = status->buf;
while (dest<end) {
needbits=new_count?4:bits;
x=havebits=0;
while (needbits) {
/* feed buffer */
if (!bufbits) {
if((*incnt)--)
buf=_mm_read_UBYTE(reader);
else
buf=0;
bufbits=8;
}
/* get as many bits as necessary */
y=needbits<bufbits?needbits:bufbits;
x|=(buf &((1<<y)-1))<<havebits;
buf>>=y;
bufbits-=y;
needbits-=y;
havebits+=y;
}
if (new_count) {
new_count = 0;
if (++x >= bits)
x++;
bits = x;
continue;
}
if (bits<7) {
if (x==(1<<(bits-1))) {
new_count=1;
continue;
}
}
else if (bits<17) {
y=(0xffff>>(17-bits))-8;
if ((x>y)&&(x<=y+16)) {
if ((x-=y)>=bits)
x++;
bits = x;
continue;
}
}
else if (bits<18) {
if (x>=0x10000) {
bits=x-0x10000+1;
continue;
}
} else {
/* error in compressed data... */
_mm_errno=MMERR_ITPACK_INVALID_DATA;
return 0;
}
if (bits<16) /* extend sign */
x = ((SWORD)(x<<(16-bits)))>>(16-bits);
*(dest++)=(last+=x);
}
status->bits = bits;
status->bufbits = bufbits;
status->last = last;
status->buf = buf;
return dest-sl_buffer;
}
static BOOL SL_LoadInternal(void* buffer,UWORD infmt,UWORD outfmt,int scalefactor,ULONG length,MREADER* reader,BOOL dither)
{
SBYTE *bptr = (SBYTE*)buffer;
SWORD *wptr = (SWORD*)buffer;
int stodo,t,u;
int result,c_block=0; /* compression bytes until next block */
ITPACK status;
UWORD incnt;
while(length) {
stodo=(length<SLBUFSIZE)?length:SLBUFSIZE;
if(infmt&SF_ITPACKED) {
sl_rlength=0;
if (!c_block) {
status.bits = (infmt & SF_16BITS) ? 17 : 9;
status.last = status.bufbits = 0;
incnt=_mm_read_I_UWORD(reader);
c_block = (infmt & SF_16BITS) ? 0x4000 : 0x8000;
if(infmt&SF_DELTA) sl_old=0;
}
if (infmt & SF_16BITS) {
if(!(result=read_itcompr16(&status,reader,sl_buffer,stodo,&incnt)))
return 1;
} else {
if(!(result=read_itcompr8(&status,reader,sl_buffer,stodo,&incnt)))
return 1;
}
if(result!=stodo) {
_mm_errno=MMERR_ITPACK_INVALID_DATA;
return 1;
}
c_block -= stodo;
} else {
if(infmt&SF_16BITS) {
if(infmt&SF_BIG_ENDIAN)
_mm_read_M_SWORDS(sl_buffer,stodo,reader);
else
_mm_read_I_SWORDS(sl_buffer,stodo,reader);
} else {
SBYTE *src;
SWORD *dest;
reader->Read(reader,sl_buffer,sizeof(SBYTE)*stodo);
src = (SBYTE*)sl_buffer;
dest = sl_buffer;
src += stodo;dest += stodo;
for(t=0;t<stodo;t++) {
src--;dest--;
*dest = (*src)<<8;
}
}
sl_rlength-=stodo;
}
if(infmt & SF_DELTA)
for(t=0;t<stodo;t++) {
sl_buffer[t] += sl_old;
sl_old = sl_buffer[t];
}
if((infmt^outfmt) & SF_SIGNED)
for(t=0;t<stodo;t++)
sl_buffer[t]^= 0x8000;
if(scalefactor) {
int idx = 0;
SLONG scaleval;
/* Sample Scaling... average values for better results. */
t= 0;
while(t<stodo && length) {
scaleval = 0;
for(u=scalefactor;u && t<stodo;u--,t++)
scaleval+=sl_buffer[t];
sl_buffer[idx++]=scaleval/(scalefactor-u);
length--;
}
stodo = idx;
} else
length -= stodo;
if (dither) {
if((infmt & SF_STEREO) && !(outfmt & SF_STEREO)) {
/* dither stereo to mono, average together every two samples */
SLONG avgval;
int idx = 0;
t=0;
while(t<stodo && length) {
avgval=sl_buffer[t++];
avgval+=sl_buffer[t++];
sl_buffer[idx++]=avgval>>1;
length-=2;
}
stodo = idx;
}
}
if(outfmt & SF_16BITS) {
for(t=0;t<stodo;t++)
*(wptr++)=sl_buffer[t];
} else {
for(t=0;t<stodo;t++)
*(bptr++)=sl_buffer[t]>>8;
}
}
return 0;
}
BOOL SL_Load(void* buffer,SAMPLOAD *smp,ULONG length)
{
return SL_LoadInternal(buffer,smp->infmt,smp->outfmt,smp->scalefactor,
length,smp->reader,0);
}
/* Registers a sample for loading when SL_LoadSamples() is called. */
SAMPLOAD* SL_RegisterSample(SAMPLE* s,int type,MREADER* reader)
{
SAMPLOAD *news,**samplist,*cruise;
if(type==MD_MUSIC) {
samplist = &musiclist;
cruise = musiclist;
} else
if (type==MD_SNDFX) {
samplist = &sndfxlist;
cruise = sndfxlist;
} else
return NULL;
/* Allocate and add structure to the END of the list */
if(!(news=(SAMPLOAD*)_mm_malloc(sizeof(SAMPLOAD)))) return NULL;
if(cruise) {
while(cruise->next) cruise=cruise->next;
cruise->next = news;
} else
*samplist = news;
news->infmt = s->flags & SF_FORMATMASK;
news->outfmt = news->infmt;
news->reader = reader;
news->sample = s;
news->length = s->length;
news->loopstart = s->loopstart;
news->loopend = s->loopend;
return news;
}
static void FreeSampleList(SAMPLOAD* s)
{
SAMPLOAD *old;
while(s) {
old = s;
s = s->next;
free(old);
}
}
/* Returns the total amount of memory required by the samplelist queue. */
static ULONG SampleTotal(SAMPLOAD* samplist,int type)
{
int total = 0;
while(samplist) {
samplist->sample->flags=
(samplist->sample->flags&~SF_FORMATMASK)|samplist->outfmt;
total += MD_SampleLength(type,samplist->sample);
samplist=samplist->next;
}
return total;
}
static ULONG RealSpeed(SAMPLOAD *s)
{
return(s->sample->speed/(s->scalefactor?s->scalefactor:1));
}
static BOOL DitherSamples(SAMPLOAD* samplist,int type)
{
SAMPLOAD *c2smp=NULL;
ULONG maxsize, speed;
SAMPLOAD *s;
if(!samplist) return 0;
if((maxsize=MD_SampleSpace(type)*1024))
while(SampleTotal(samplist,type)>maxsize) {
/* First Pass - check for any 16 bit samples */
s = samplist;
while(s) {
if(s->outfmt & SF_16BITS) {
SL_Sample16to8(s);
break;
}
s=s->next;
}
/* Second pass (if no 16bits found above) is to take the sample with
the highest speed and dither it by half. */
if(!s) {
s = samplist;
speed = 0;
while(s) {
if((s->sample->length) && (RealSpeed(s)>speed)) {
speed=RealSpeed(s);
c2smp=s;
}
s=s->next;
}
if (c2smp)
SL_HalveSample(c2smp,2);
}
}
/* Samples dithered, now load them ! */
s = samplist;
while(s) {
/* sample has to be loaded ? -> increase number of samples, allocate
memory and load sample. */
if(s->sample->length) {
if(s->sample->seekpos)
_mm_fseek(s->reader, s->sample->seekpos, SEEK_SET);
/* Call the sample load routine of the driver module. It has to
return a 'handle' (>=0) that identifies the sample. */
s->sample->handle = MD_SampleLoad(s, type);
s->sample->flags = (s->sample->flags & ~SF_FORMATMASK) | s->outfmt;
if(s->sample->handle<0) {
FreeSampleList(samplist);
if(_mm_errorhandler) _mm_errorhandler();
return 1;
}
}
s = s->next;
}
FreeSampleList(samplist);
return 0;
}
BOOL SL_LoadSamples(void)
{
BOOL ok;
_mm_critical = 0;
if((!musiclist)&&(!sndfxlist)) return 0;
ok=DitherSamples(musiclist,MD_MUSIC)||DitherSamples(sndfxlist,MD_SNDFX);
musiclist=sndfxlist=NULL;
return ok;
}
void SL_Sample16to8(SAMPLOAD* s)
{
s->outfmt &= ~SF_16BITS;
s->sample->flags = (s->sample->flags&~SF_FORMATMASK) | s->outfmt;
}
void SL_Sample8to16(SAMPLOAD* s)
{
s->outfmt |= SF_16BITS;
s->sample->flags = (s->sample->flags&~SF_FORMATMASK) | s->outfmt;
}
void SL_SampleSigned(SAMPLOAD* s)
{
s->outfmt |= SF_SIGNED;
s->sample->flags = (s->sample->flags&~SF_FORMATMASK) | s->outfmt;
}
void SL_SampleUnsigned(SAMPLOAD* s)
{
s->outfmt &= ~SF_SIGNED;
s->sample->flags = (s->sample->flags&~SF_FORMATMASK) | s->outfmt;
}
void SL_HalveSample(SAMPLOAD* s,int factor)
{
s->scalefactor=factor>0?factor:2;
s->sample->divfactor = s->scalefactor;
s->sample->length = s->length / s->scalefactor;
s->sample->loopstart = s->loopstart / s->scalefactor;
s->sample->loopend = s->loopend / s->scalefactor;
}
/* ex:set ts=4: */
|
59440c5396bd954c298233186a7aa76d44da6f5d
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/fs/debugfs/file.c
|
c5ca6ae5a30cc750e5a33b42ce746da6cf2f4591
|
[
"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
| 26,946
|
c
|
file.c
|
/*
* file.c - part of debugfs, a tiny little debug file system
*
* Copyright (C) 2004 Greg Kroah-Hartman <greg@kroah.com>
* Copyright (C) 2004 IBM Inc.
*
* 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.
*
* debugfs is for people to use instead of /proc or /sys.
* See Documentation/DocBook/filesystems for more details.
*
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/seq_file.h>
#include <linux/pagemap.h>
#include <linux/namei.h>
#include <linux/debugfs.h>
#include <linux/io.h>
#include <linux/slab.h>
static ssize_t default_read_file(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
return 0;
}
static ssize_t default_write_file(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
return count;
}
const struct file_operations debugfs_file_operations = {
.read = default_read_file,
.write = default_write_file,
.open = simple_open,
.llseek = noop_llseek,
};
static void *debugfs_follow_link(struct dentry *dentry, struct nameidata *nd)
{
nd_set_link(nd, dentry->d_inode->i_private);
return NULL;
}
const struct inode_operations debugfs_link_operations = {
.readlink = generic_readlink,
.follow_link = debugfs_follow_link,
};
static int debugfs_u8_set(void *data, u64 val)
{
*(u8 *)data = val;
return 0;
}
static int debugfs_u8_get(void *data, u64 *val)
{
*val = *(u8 *)data;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(fops_u8, debugfs_u8_get, debugfs_u8_set, "%llu\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_u8_ro, debugfs_u8_get, NULL, "%llu\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_u8_wo, NULL, debugfs_u8_set, "%llu\n");
/**
* debugfs_create_u8 - create a debugfs file that is used to read and write an unsigned 8-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*
* This function creates a file in debugfs with the given name that
* contains the value of the variable @value. If the @mode variable is so
* set, it can be read from, and written to.
*
* This function will return a pointer to a dentry if it succeeds. This
* pointer must be passed to the debugfs_remove() function when the file is
* to be removed (no automatic cleanup happens if your module is unloaded,
* you are responsible here.) If an error occurs, %NULL will be returned.
*
* If debugfs is not enabled in the kernel, the value -%ENODEV will be
* returned. It is not wise to check for this value, but rather, check for
* %NULL or !%NULL instead as to eliminate the need for #ifdef in the calling
* code.
*/
struct dentry *debugfs_create_u8(const char *name, umode_t mode,
struct dentry *parent, u8 *value)
{
/* if there are no write bits set, make read only */
if (!(mode & S_IWUGO))
return debugfs_create_file(name, mode, parent, value, &fops_u8_ro);
/* if there are no read bits set, make write only */
if (!(mode & S_IRUGO))
return debugfs_create_file(name, mode, parent, value, &fops_u8_wo);
return debugfs_create_file(name, mode, parent, value, &fops_u8);
}
EXPORT_SYMBOL_GPL(debugfs_create_u8);
static int debugfs_u16_set(void *data, u64 val)
{
*(u16 *)data = val;
return 0;
}
static int debugfs_u16_get(void *data, u64 *val)
{
*val = *(u16 *)data;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(fops_u16, debugfs_u16_get, debugfs_u16_set, "%llu\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_u16_ro, debugfs_u16_get, NULL, "%llu\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_u16_wo, NULL, debugfs_u16_set, "%llu\n");
/**
* debugfs_create_u16 - create a debugfs file that is used to read and write an unsigned 16-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*
* This function creates a file in debugfs with the given name that
* contains the value of the variable @value. If the @mode variable is so
* set, it can be read from, and written to.
*
* This function will return a pointer to a dentry if it succeeds. This
* pointer must be passed to the debugfs_remove() function when the file is
* to be removed (no automatic cleanup happens if your module is unloaded,
* you are responsible here.) If an error occurs, %NULL will be returned.
*
* If debugfs is not enabled in the kernel, the value -%ENODEV will be
* returned. It is not wise to check for this value, but rather, check for
* %NULL or !%NULL instead as to eliminate the need for #ifdef in the calling
* code.
*/
struct dentry *debugfs_create_u16(const char *name, umode_t mode,
struct dentry *parent, u16 *value)
{
/* if there are no write bits set, make read only */
if (!(mode & S_IWUGO))
return debugfs_create_file(name, mode, parent, value, &fops_u16_ro);
/* if there are no read bits set, make write only */
if (!(mode & S_IRUGO))
return debugfs_create_file(name, mode, parent, value, &fops_u16_wo);
return debugfs_create_file(name, mode, parent, value, &fops_u16);
}
EXPORT_SYMBOL_GPL(debugfs_create_u16);
static int debugfs_u32_set(void *data, u64 val)
{
*(u32 *)data = val;
return 0;
}
static int debugfs_u32_get(void *data, u64 *val)
{
*val = *(u32 *)data;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(fops_u32, debugfs_u32_get, debugfs_u32_set, "%llu\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_u32_ro, debugfs_u32_get, NULL, "%llu\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_u32_wo, NULL, debugfs_u32_set, "%llu\n");
/**
* debugfs_create_u32 - create a debugfs file that is used to read and write an unsigned 32-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*
* This function creates a file in debugfs with the given name that
* contains the value of the variable @value. If the @mode variable is so
* set, it can be read from, and written to.
*
* This function will return a pointer to a dentry if it succeeds. This
* pointer must be passed to the debugfs_remove() function when the file is
* to be removed (no automatic cleanup happens if your module is unloaded,
* you are responsible here.) If an error occurs, %NULL will be returned.
*
* If debugfs is not enabled in the kernel, the value -%ENODEV will be
* returned. It is not wise to check for this value, but rather, check for
* %NULL or !%NULL instead as to eliminate the need for #ifdef in the calling
* code.
*/
struct dentry *debugfs_create_u32(const char *name, umode_t mode,
struct dentry *parent, u32 *value)
{
/* if there are no write bits set, make read only */
if (!(mode & S_IWUGO))
return debugfs_create_file(name, mode, parent, value, &fops_u32_ro);
/* if there are no read bits set, make write only */
if (!(mode & S_IRUGO))
return debugfs_create_file(name, mode, parent, value, &fops_u32_wo);
return debugfs_create_file(name, mode, parent, value, &fops_u32);
}
EXPORT_SYMBOL_GPL(debugfs_create_u32);
static int debugfs_u64_set(void *data, u64 val)
{
*(u64 *)data = val;
return 0;
}
static int debugfs_u64_get(void *data, u64 *val)
{
*val = *(u64 *)data;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(fops_u64, debugfs_u64_get, debugfs_u64_set, "%llu\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_u64_ro, debugfs_u64_get, NULL, "%llu\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_u64_wo, NULL, debugfs_u64_set, "%llu\n");
/**
* debugfs_create_u64 - create a debugfs file that is used to read and write an unsigned 64-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*
* This function creates a file in debugfs with the given name that
* contains the value of the variable @value. If the @mode variable is so
* set, it can be read from, and written to.
*
* This function will return a pointer to a dentry if it succeeds. This
* pointer must be passed to the debugfs_remove() function when the file is
* to be removed (no automatic cleanup happens if your module is unloaded,
* you are responsible here.) If an error occurs, %NULL will be returned.
*
* If debugfs is not enabled in the kernel, the value -%ENODEV will be
* returned. It is not wise to check for this value, but rather, check for
* %NULL or !%NULL instead as to eliminate the need for #ifdef in the calling
* code.
*/
struct dentry *debugfs_create_u64(const char *name, umode_t mode,
struct dentry *parent, u64 *value)
{
/* if there are no write bits set, make read only */
if (!(mode & S_IWUGO))
return debugfs_create_file(name, mode, parent, value, &fops_u64_ro);
/* if there are no read bits set, make write only */
if (!(mode & S_IRUGO))
return debugfs_create_file(name, mode, parent, value, &fops_u64_wo);
return debugfs_create_file(name, mode, parent, value, &fops_u64);
}
EXPORT_SYMBOL_GPL(debugfs_create_u64);
DEFINE_SIMPLE_ATTRIBUTE(fops_x8, debugfs_u8_get, debugfs_u8_set, "0x%02llx\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_x8_ro, debugfs_u8_get, NULL, "0x%02llx\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_x8_wo, NULL, debugfs_u8_set, "0x%02llx\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_x16, debugfs_u16_get, debugfs_u16_set, "0x%04llx\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_x16_ro, debugfs_u16_get, NULL, "0x%04llx\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_x16_wo, NULL, debugfs_u16_set, "0x%04llx\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_x32, debugfs_u32_get, debugfs_u32_set, "0x%08llx\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_x32_ro, debugfs_u32_get, NULL, "0x%08llx\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_x32_wo, NULL, debugfs_u32_set, "0x%08llx\n");
DEFINE_SIMPLE_ATTRIBUTE(fops_x64, debugfs_u64_get, debugfs_u64_set, "0x%016llx\n");
/*
* debugfs_create_x{8,16,32,64} - create a debugfs file that is used to read and write an unsigned {8,16,32,64}-bit value
*
* These functions are exactly the same as the above functions (but use a hex
* output for the decimal challenged). For details look at the above unsigned
* decimal functions.
*/
/**
* debugfs_create_x8 - create a debugfs file that is used to read and write an unsigned 8-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*/
struct dentry *debugfs_create_x8(const char *name, umode_t mode,
struct dentry *parent, u8 *value)
{
/* if there are no write bits set, make read only */
if (!(mode & S_IWUGO))
return debugfs_create_file(name, mode, parent, value, &fops_x8_ro);
/* if there are no read bits set, make write only */
if (!(mode & S_IRUGO))
return debugfs_create_file(name, mode, parent, value, &fops_x8_wo);
return debugfs_create_file(name, mode, parent, value, &fops_x8);
}
EXPORT_SYMBOL_GPL(debugfs_create_x8);
/**
* debugfs_create_x16 - create a debugfs file that is used to read and write an unsigned 16-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*/
struct dentry *debugfs_create_x16(const char *name, umode_t mode,
struct dentry *parent, u16 *value)
{
/* if there are no write bits set, make read only */
if (!(mode & S_IWUGO))
return debugfs_create_file(name, mode, parent, value, &fops_x16_ro);
/* if there are no read bits set, make write only */
if (!(mode & S_IRUGO))
return debugfs_create_file(name, mode, parent, value, &fops_x16_wo);
return debugfs_create_file(name, mode, parent, value, &fops_x16);
}
EXPORT_SYMBOL_GPL(debugfs_create_x16);
/**
* debugfs_create_x32 - create a debugfs file that is used to read and write an unsigned 32-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*/
struct dentry *debugfs_create_x32(const char *name, umode_t mode,
struct dentry *parent, u32 *value)
{
/* if there are no write bits set, make read only */
if (!(mode & S_IWUGO))
return debugfs_create_file(name, mode, parent, value, &fops_x32_ro);
/* if there are no read bits set, make write only */
if (!(mode & S_IRUGO))
return debugfs_create_file(name, mode, parent, value, &fops_x32_wo);
return debugfs_create_file(name, mode, parent, value, &fops_x32);
}
EXPORT_SYMBOL_GPL(debugfs_create_x32);
/**
* debugfs_create_x64 - create a debugfs file that is used to read and write an unsigned 64-bit value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*/
struct dentry *debugfs_create_x64(const char *name, umode_t mode,
struct dentry *parent, u64 *value)
{
return debugfs_create_file(name, mode, parent, value, &fops_x64);
}
EXPORT_SYMBOL_GPL(debugfs_create_x64);
static int debugfs_size_t_set(void *data, u64 val)
{
*(size_t *)data = val;
return 0;
}
static int debugfs_size_t_get(void *data, u64 *val)
{
*val = *(size_t *)data;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(fops_size_t, debugfs_size_t_get, debugfs_size_t_set,
"%llu\n"); /* %llu and %zu are more or less the same */
/**
* debugfs_create_size_t - create a debugfs file that is used to read and write an size_t value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*/
struct dentry *debugfs_create_size_t(const char *name, umode_t mode,
struct dentry *parent, size_t *value)
{
return debugfs_create_file(name, mode, parent, value, &fops_size_t);
}
EXPORT_SYMBOL_GPL(debugfs_create_size_t);
static ssize_t read_file_bool(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
char buf[3];
u32 *val = file->private_data;
if (*val)
buf[0] = 'Y';
else
buf[0] = 'N';
buf[1] = '\n';
buf[2] = 0x00;
return simple_read_from_buffer(user_buf, count, ppos, buf, 2);
}
static ssize_t write_file_bool(struct file *file, const char __user *user_buf,
size_t count, loff_t *ppos)
{
char buf[32];
size_t buf_size;
bool bv;
u32 *val = file->private_data;
buf_size = min(count, (sizeof(buf)-1));
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
if (strtobool(buf, &bv) == 0)
*val = bv;
return count;
}
static const struct file_operations fops_bool = {
.read = read_file_bool,
.write = write_file_bool,
.open = simple_open,
.llseek = default_llseek,
};
/**
* debugfs_create_bool - create a debugfs file that is used to read and write a boolean value
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @value: a pointer to the variable that the file should read to and write
* from.
*
* This function creates a file in debugfs with the given name that
* contains the value of the variable @value. If the @mode variable is so
* set, it can be read from, and written to.
*
* This function will return a pointer to a dentry if it succeeds. This
* pointer must be passed to the debugfs_remove() function when the file is
* to be removed (no automatic cleanup happens if your module is unloaded,
* you are responsible here.) If an error occurs, %NULL will be returned.
*
* If debugfs is not enabled in the kernel, the value -%ENODEV will be
* returned. It is not wise to check for this value, but rather, check for
* %NULL or !%NULL instead as to eliminate the need for #ifdef in the calling
* code.
*/
struct dentry *debugfs_create_bool(const char *name, umode_t mode,
struct dentry *parent, u32 *value)
{
return debugfs_create_file(name, mode, parent, value, &fops_bool);
}
EXPORT_SYMBOL_GPL(debugfs_create_bool);
static ssize_t read_file_blob(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct debugfs_blob_wrapper *blob = file->private_data;
return simple_read_from_buffer(user_buf, count, ppos, blob->data,
blob->size);
}
static const struct file_operations fops_blob = {
.read = read_file_blob,
.open = simple_open,
.llseek = default_llseek,
};
/**
* debugfs_create_blob - create a debugfs file that is used to read a binary blob
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @blob: a pointer to a struct debugfs_blob_wrapper which contains a pointer
* to the blob data and the size of the data.
*
* This function creates a file in debugfs with the given name that exports
* @blob->data as a binary blob. If the @mode variable is so set it can be
* read from. Writing is not supported.
*
* This function will return a pointer to a dentry if it succeeds. This
* pointer must be passed to the debugfs_remove() function when the file is
* to be removed (no automatic cleanup happens if your module is unloaded,
* you are responsible here.) If an error occurs, %NULL will be returned.
*
* If debugfs is not enabled in the kernel, the value -%ENODEV will be
* returned. It is not wise to check for this value, but rather, check for
* %NULL or !%NULL instead as to eliminate the need for #ifdef in the calling
* code.
*/
struct dentry *debugfs_create_blob(const char *name, umode_t mode,
struct dentry *parent,
struct debugfs_blob_wrapper *blob)
{
return debugfs_create_file(name, mode, parent, blob, &fops_blob);
}
EXPORT_SYMBOL_GPL(debugfs_create_blob);
struct array_data {
void *array;
u32 elements;
};
static size_t u32_format_array(char *buf, size_t bufsize,
u32 *array, int array_size)
{
size_t ret = 0;
while (--array_size >= 0) {
size_t len;
char term = array_size ? ' ' : '\n';
len = snprintf(buf, bufsize, "%u%c", *array++, term);
ret += len;
buf += len;
bufsize -= len;
}
return ret;
}
static int u32_array_open(struct inode *inode, struct file *file)
{
struct array_data *data = inode->i_private;
int size, elements = data->elements;
char *buf;
/*
* Max size:
* - 10 digits + ' '/'\n' = 11 bytes per number
* - terminating NUL character
*/
size = elements*11;
buf = kmalloc(size+1, GFP_KERNEL);
if (!buf)
return -ENOMEM;
buf[size] = 0;
file->private_data = buf;
u32_format_array(buf, size, data->array, data->elements);
return nonseekable_open(inode, file);
}
static ssize_t u32_array_read(struct file *file, char __user *buf, size_t len,
loff_t *ppos)
{
size_t size = strlen(file->private_data);
return simple_read_from_buffer(buf, len, ppos,
file->private_data, size);
}
static int u32_array_release(struct inode *inode, struct file *file)
{
kfree(file->private_data);
return 0;
}
static const struct file_operations u32_array_fops = {
.owner = THIS_MODULE,
.open = u32_array_open,
.release = u32_array_release,
.read = u32_array_read,
.llseek = no_llseek,
};
/**
* debugfs_create_u32_array - create a debugfs file that is used to read u32
* array.
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have.
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @array: u32 array that provides data.
* @elements: total number of elements in the array.
*
* This function creates a file in debugfs with the given name that exports
* @array as data. If the @mode variable is so set it can be read from.
* Writing is not supported. Seek within the file is also not supported.
* Once array is created its size can not be changed.
*
* The function returns a pointer to dentry on success. If debugfs is not
* enabled in the kernel, the value -%ENODEV will be returned.
*/
struct dentry *debugfs_create_u32_array(const char *name, umode_t mode,
struct dentry *parent,
u32 *array, u32 elements)
{
struct array_data *data = kmalloc(sizeof(*data), GFP_KERNEL);
if (data == NULL)
return NULL;
data->array = array;
data->elements = elements;
return debugfs_create_file(name, mode, parent, data, &u32_array_fops);
}
EXPORT_SYMBOL_GPL(debugfs_create_u32_array);
#ifdef CONFIG_HAS_IOMEM
/*
* The regset32 stuff is used to print 32-bit registers using the
* seq_file utilities. We offer printing a register set in an already-opened
* sequential file or create a debugfs file that only prints a regset32.
*/
/**
* debugfs_print_regs32 - use seq_print to describe a set of registers
* @s: the seq_file structure being used to generate output
* @regs: an array if struct debugfs_reg32 structures
* @nregs: the length of the above array
* @base: the base address to be used in reading the registers
* @prefix: a string to be prefixed to every output line
*
* This function outputs a text block describing the current values of
* some 32-bit hardware registers. It is meant to be used within debugfs
* files based on seq_file that need to show registers, intermixed with other
* information. The prefix argument may be used to specify a leading string,
* because some peripherals have several blocks of identical registers,
* for example configuration of dma channels
*/
int debugfs_print_regs32(struct seq_file *s, const struct debugfs_reg32 *regs,
int nregs, void __iomem *base, char *prefix)
{
int i, ret = 0;
for (i = 0; i < nregs; i++, regs++) {
if (prefix)
ret += seq_printf(s, "%s", prefix);
ret += seq_printf(s, "%s = 0x%08x\n", regs->name,
readl(base + regs->offset));
}
return ret;
}
EXPORT_SYMBOL_GPL(debugfs_print_regs32);
static int debugfs_show_regset32(struct seq_file *s, void *data)
{
struct debugfs_regset32 *regset = s->private;
debugfs_print_regs32(s, regset->regs, regset->nregs, regset->base, "");
return 0;
}
static int debugfs_open_regset32(struct inode *inode, struct file *file)
{
return single_open(file, debugfs_show_regset32, inode->i_private);
}
static const struct file_operations fops_regset32 = {
.open = debugfs_open_regset32,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
/**
* debugfs_create_regset32 - create a debugfs file that returns register values
* @name: a pointer to a string containing the name of the file to create.
* @mode: the permission that the file should have
* @parent: a pointer to the parent dentry for this file. This should be a
* directory dentry if set. If this parameter is %NULL, then the
* file will be created in the root of the debugfs filesystem.
* @regset: a pointer to a struct debugfs_regset32, which contains a pointer
* to an array of register definitions, the array size and the base
* address where the register bank is to be found.
*
* This function creates a file in debugfs with the given name that reports
* the names and values of a set of 32-bit registers. If the @mode variable
* is so set it can be read from. Writing is not supported.
*
* This function will return a pointer to a dentry if it succeeds. This
* pointer must be passed to the debugfs_remove() function when the file is
* to be removed (no automatic cleanup happens if your module is unloaded,
* you are responsible here.) If an error occurs, %NULL will be returned.
*
* If debugfs is not enabled in the kernel, the value -%ENODEV will be
* returned. It is not wise to check for this value, but rather, check for
* %NULL or !%NULL instead as to eliminate the need for #ifdef in the calling
* code.
*/
struct dentry *debugfs_create_regset32(const char *name, umode_t mode,
struct dentry *parent,
struct debugfs_regset32 *regset)
{
return debugfs_create_file(name, mode, parent, regset, &fops_regset32);
}
EXPORT_SYMBOL_GPL(debugfs_create_regset32);
#endif /* CONFIG_HAS_IOMEM */
|
ab205db54b5f7af84447d548b72f1623afd0971e
|
6832a9c81b16ead373325f70fb97753d6a211539
|
/src/wrapped/wrappednspr4.c
|
b9a4b7dfb5e0ef16722c404992ebd6ac6f46355e
|
[
"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
| 3,653
|
c
|
wrappednspr4.c
|
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
#include "wrappedlibs.h"
#include "debug.h"
#include "wrapper.h"
#include "bridge.h"
#include "librarian/library_private.h"
#include "x86emu.h"
#include "emu/x86emu_private.h"
#include "callback.h"
#include "librarian.h"
#include "box86context.h"
#include "emu/x86emu_private.h"
#include "myalign.h"
const char* nspr4Name = "libnspr4.so";
#define LIBNAME nspr4
#define ADDED_FUNCTIONS() \
#include "generated/wrappednspr4types.h"
#include "wrappercallback.h"
#undef SUPER
#define SUPER() \
GO(0) \
GO(1) \
GO(2) \
GO(3) \
GO(4)
// PRCallOnceWithArg ...
#define GO(A) \
static uintptr_t my_PRCallOnceWithArg_fct_##A = 0; \
static int my_PRCallOnceWithArg_##A(void* a) \
{ \
return (int)RunFunctionFmt(my_PRCallOnceWithArg_fct_##A, "p", a); \
}
SUPER()
#undef GO
static void* find_PRCallOnceWithArg_Fct(void* fct)
{
if(!fct) return fct;
if(GetNativeFnc((uintptr_t)fct)) return GetNativeFnc((uintptr_t)fct);
#define GO(A) if(my_PRCallOnceWithArg_fct_##A == (uintptr_t)fct) return my_PRCallOnceWithArg_##A;
SUPER()
#undef GO
#define GO(A) if(my_PRCallOnceWithArg_fct_##A == 0) {my_PRCallOnceWithArg_fct_##A = (uintptr_t)fct; return my_PRCallOnceWithArg_##A; }
SUPER()
#undef GO
printf_log(LOG_NONE, "Warning, no more slot for nspr4 PRCallOnceWithArg callback\n");
return NULL;
}
// PRCallOnce ...
#define GO(A) \
static uintptr_t my_PRCallOnce_fct_##A = 0; \
static int my_PRCallOnce_##A() \
{ \
return (int)RunFunctionFmt(my_PRCallOnce_fct_##A, ""); \
}
SUPER()
#undef GO
static void* find_PRCallOnce_Fct(void* fct)
{
if(!fct) return fct;
if(GetNativeFnc((uintptr_t)fct)) return GetNativeFnc((uintptr_t)fct);
#define GO(A) if(my_PRCallOnce_fct_##A == (uintptr_t)fct) return my_PRCallOnce_##A;
SUPER()
#undef GO
#define GO(A) if(my_PRCallOnce_fct_##A == 0) {my_PRCallOnce_fct_##A = (uintptr_t)fct; return my_PRCallOnce_##A; }
SUPER()
#undef GO
printf_log(LOG_NONE, "Warning, no more slot for nspr4 PRCallOnce callback\n");
return NULL;
}
#undef SUPER
typedef struct my_PRLibrary_s {
char* name;
struct my_PRLibrary_s* next;
int refCount;
void* staticTable;
void* dlh;
} my_PRLibrary_t;
EXPORT int my_PR_CallOnceWithArg(x86emu_t* emu, void* once, void* f, void* arg)
{
(void)emu;
return my->PR_CallOnceWithArg(once, find_PRCallOnceWithArg_Fct(f), arg);
}
EXPORT int my_PR_CallOnce(x86emu_t* emu, void* once, void* f)
{
(void)emu;
return my->PR_CallOnce(once, find_PRCallOnce_Fct(f));
}
EXPORT void* my_PR_FindFunctionSymbol(x86emu_t* emu, void* symbol, void* name)
{
(void)emu;
//TODO!!!
printf_log(LOG_NONE, "Error: using unimplemented PR_FindFunctionSymbol(%p, \"%s\")\n", symbol, (char*)name);
return NULL;
}
EXPORT void* my_PR_CreateIOLayerStub(x86emu_t* emu, int ident, void* methods)
{
(void)emu;
//TODO!!!
printf_log(LOG_NONE, "Error: using unimplemented PR_CreateIOLayerStub(%d, %p)\n", ident, methods);
return NULL;
}
#define CUSTOM_INIT \
getMy(lib);
#define CUSTOM_FINI \
freeMy();
#include "wrappedlib_init.h"
|
594e0ee83a20c6c09217f70676f74eec5bd69e43
|
17d7357e5c5130ace022b3c9d9f98e7b13dda0ca
|
/src/coding/compresswave_decoder_lib.h
|
ae53e2ccda25e3f1eb281de68e59478093d8c931
|
[
"ISC",
"LicenseRef-scancode-public-domain"
] |
permissive
|
vgmstream/vgmstream
|
4a7747bb75ff513f8fc8cc26f31d6e3a4150bc43
|
883d796d4b63c42810586e9f1ffbdcdd28c73ef5
|
refs/heads/master
| 2023-09-04T16:14:38.136915
| 2023-09-02T18:06:38
| 2023-09-02T18:06:38
| 5,591,410
| 762
| 137
|
NOASSERTION
| 2023-09-10T22:58:26
| 2012-08-28T20:08:24
|
C
|
UTF-8
|
C
| false
| false
| 1,286
|
h
|
compresswave_decoder_lib.h
|
#ifndef _COMPRESSWAVE_DECODER_LIB_H
#define _COMPRESSWAVE_DECODER_LIB_H
#include "../streamfile.h"
typedef struct TCompressWaveData TCompressWaveData;
void TCompressWaveData_GetLoopState(TCompressWaveData* this);
void TCompressWaveData_SetLoopState(TCompressWaveData* this);
TCompressWaveData* TCompressWaveData_Create(void);
void TCompressWaveData_Free(TCompressWaveData* this);
int TCompressWaveData_Rendering(TCompressWaveData* this, int16_t* buf, uint32_t Len);
int TCompressWaveData_LoadFromStream(TCompressWaveData* this, STREAMFILE* ss);
void TCompressWaveData_SetCipherCode(TCompressWaveData* this, uint32_t Num);
void TCompressWaveData_Play(TCompressWaveData* this, int loop);
void TCompressWaveData_Stop(TCompressWaveData* this);
void TCompressWaveData_Previous(TCompressWaveData* this);
void TCompressWaveData_Pause(TCompressWaveData* this);
void TCompressWaveData_SetVolume(TCompressWaveData* this, float vol, float fade);
float TCompressWaveData_GetVolume(TCompressWaveData* this);
float TCompressWaveData_GetSetVolume(TCompressWaveData* this);
float TCompressWaveData_GetFade(TCompressWaveData* this);
float TCompressWaveData_GetPlayTime(TCompressWaveData* this);
float TCompressWaveData_GetTotalTime(TCompressWaveData* this);
#endif /*_COMPRESSWAVE_DECODER_LIB_H */
|
68cd32115274570efc6f520ebc2e95da7a6332a1
|
76db964c1e74ba457a40f5407a74982d3d5d6f22
|
/core/interpreter/cmd_variables.c
|
3ae0dc718b9af7e66f01080c83f33953c0c6a8a5
|
[
"Zlib"
] |
permissive
|
timoinutilis/lowres-nx
|
dd2fd8eb103925e7fc2f66ce5c631d9a373b3e45
|
10a48e309ac5284724010eea56372fbc72b9f975
|
refs/heads/master
| 2023-04-08T22:05:33.039947
| 2023-03-23T15:02:02
| 2023-03-23T15:02:02
| 75,659,563
| 158
| 26
|
Zlib
| 2023-03-23T15:02:04
| 2016-12-05T19:38:19
|
JavaScript
|
UTF-8
|
C
| false
| false
| 6,936
|
c
|
cmd_variables.c
|
//
// Copyright 2017-2020 Timo Kloss
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#include "cmd_variables.h"
#include "core.h"
enum ErrorCode cmd_LET(struct Core *core)
{
struct Interpreter *interpreter = core->interpreter;
// LET keyword is optional
if (interpreter->pc->type == TokenLET)
{
++interpreter->pc;
if (interpreter->pc->type != TokenIdentifier && interpreter->pc->type != TokenStringIdentifier) return ErrorSyntax;
}
// identifier
enum ErrorCode errorCode = ErrorNone;
enum ValueType valueType = ValueTypeNull;
union Value *varValue = itp_readVariable(core, &valueType, &errorCode, true);
if (!varValue) return errorCode;
if (interpreter->pc->type != TokenEq) return ErrorSyntax;
++interpreter->pc;
// value
struct TypedValue value = itp_evaluateExpression(core, TypeClassAny);
if (value.type == ValueTypeError) return value.v.errorCode;
if (value.type != valueType) return ErrorTypeMismatch;
if (interpreter->pass == PassRun)
{
if (valueType == ValueTypeString && varValue->stringValue)
{
rcstring_release(varValue->stringValue);
}
*varValue = value.v;
}
return itp_endOfCommand(interpreter);
}
enum ErrorCode cmd_DIM(struct Core *core)
{
struct Interpreter *interpreter = core->interpreter;
if (interpreter->pass == PassRun && interpreter->mode == ModeInterrupt) return ErrorNotAllowedInInterrupt;
bool isGlobal = false;
struct Token *nextToken = interpreter->pc + 1;
if (nextToken->type == TokenGLOBAL)
{
++interpreter->pc;
if (interpreter->pass == PassPrepare && interpreter->subLevel > 0) return ErrorGlobalInsideOfASubprogram;
isGlobal = true;
}
do
{
// DIM, GLOBAL or comma
++interpreter->pc;
// identifier
struct Token *tokenIdentifier = interpreter->pc;
++interpreter->pc;
if (tokenIdentifier->type != TokenIdentifier && tokenIdentifier->type != TokenStringIdentifier)
{
return ErrorSyntax;
}
int numDimensions = 0;
int dimensionSizes[MAX_ARRAY_DIMENSIONS];
if (interpreter->pc->type != TokenBracketOpen) return ErrorSyntax;
++interpreter->pc;
for (int i = 0; i < MAX_ARRAY_DIMENSIONS; i++)
{
struct TypedValue value = itp_evaluateExpression(core, TypeClassNumeric);
if (value.type == ValueTypeError) return value.v.errorCode;
dimensionSizes[i] = value.v.floatValue + 1; // value is max index, so size is +1
numDimensions++;
if (interpreter->pc->type == TokenComma)
{
++interpreter->pc;
}
else
{
break;
}
}
if (interpreter->pc->type != TokenBracketClose) return ErrorSyntax;
++interpreter->pc;
if (interpreter->pass == PassRun)
{
enum ErrorCode errorCode = ErrorNone;
struct ArrayVariable *variable = var_dimVariable(interpreter, &errorCode, tokenIdentifier->symbolIndex, numDimensions, dimensionSizes);
if (!variable) return errorCode;
variable->type = (tokenIdentifier->type == TokenStringIdentifier) ? ValueTypeString : ValueTypeFloat;
if (isGlobal)
{
variable->subLevel = SUB_LEVEL_GLOBAL;
}
interpreter->cycles += variable->numValues;
}
}
while (interpreter->pc->type == TokenComma);
return itp_endOfCommand(interpreter);
}
struct TypedValue fnc_UBOUND(struct Core *core)
{
struct Interpreter *interpreter = core->interpreter;
// UBOUND
++interpreter->pc;
// bracket open
if (interpreter->pc->type != TokenBracketOpen) return val_makeError(ErrorSyntax);
++interpreter->pc;
// array
if (interpreter->pc->type != TokenIdentifier && interpreter->pc->type != TokenStringIdentifier) return val_makeError(ErrorSyntax);
int symbolIndex = interpreter->pc->symbolIndex;
++interpreter->pc;
int d = 0;
if (interpreter->pc->type == TokenComma)
{
// comma
++interpreter->pc;
// dimension value
struct TypedValue dValue = itp_evaluateNumericExpression(core, 1, MAX_ARRAY_DIMENSIONS);
if (dValue.type == ValueTypeError) return val_makeError(dValue.v.errorCode);
d = dValue.v.floatValue - 1;
}
// bracket close
if (interpreter->pc->type != TokenBracketClose) return val_makeError(ErrorSyntax);
++interpreter->pc;
struct TypedValue value;
value.type = ValueTypeFloat;
if (interpreter->pass == PassRun)
{
struct ArrayVariable *variable = var_getArrayVariable(interpreter, symbolIndex, interpreter->subLevel);
if (!variable) return val_makeError(ErrorArrayNotDimensionized);
value.v.floatValue = variable->dimensionSizes[d] - 1;
}
return value;
}
enum ErrorCode cmd_SWAP(struct Core *core)
{
struct Interpreter *interpreter = core->interpreter;
// SWAP
++interpreter->pc;
enum ErrorCode errorCode = ErrorNone;
// x identifier
enum ValueType xValueType = ValueTypeNull;
union Value *xVarValue = itp_readVariable(core, &xValueType, &errorCode, false);
if (!xVarValue) return errorCode;
// comma
if (interpreter->pc->type != TokenComma) return ErrorSyntax;
++interpreter->pc;
// y identifier
enum ValueType yValueType = ValueTypeNull;
union Value *yVarValue = itp_readVariable(core, &yValueType, &errorCode, false);
if (!yVarValue) return errorCode;
if (xValueType != yValueType) return ErrorTypeMismatch;
if (interpreter->pass == PassRun)
{
union Value spareValue = *xVarValue;
*xVarValue = *yVarValue;
*yVarValue = spareValue;
}
return itp_endOfCommand(interpreter);
}
|
b91df2d9243609ada01a80f87c3063157ff5e2db
|
bed3ac926beac0f4e0293303d7b2a6031ee476c9
|
/Modules/ThirdParty/HDF5/src/itkhdf5/src/H5Zpkg.h
|
726478a08800155f5e47344802421572fd0ca694
|
[
"IJG",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"SMLNJ",
"BSD-3-Clause",
"BSD-4.3TAHOE",
"LicenseRef-scancode-free-unknown",
"Spencer-86",
"LicenseRef-scancode-llnl",
"FSFUL",
"Libpng",
"libtiff",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-hdf5",
"MIT",
"NTP",
"LicenseRef-scancode-mit-old-style",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"MPL-2.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] |
permissive
|
InsightSoftwareConsortium/ITK
|
ed9dbbc5b8b3f7511f007c0fc0eebb3ad37b88eb
|
3eb8fd7cdfbc5ac2d0c2e5e776848a4cbab3d7e1
|
refs/heads/master
| 2023-08-31T17:21:47.754304
| 2023-08-31T00:58:51
| 2023-08-31T14:12:21
| 800,928
| 1,229
| 656
|
Apache-2.0
| 2023-09-14T17:54:00
| 2010-07-27T15:48:04
|
C++
|
UTF-8
|
C
| false
| false
| 1,961
|
h
|
H5Zpkg.h
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the COPYING file, which can be found at the root of the source code *
* distribution tree, or in https://www.hdfgroup.org/licenses. *
* If you do not have access to either file, you may request a copy from *
* help@hdfgroup.org. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#if !(defined H5Z_FRIEND || defined H5Z_MODULE)
#error "Do not include this file outside the H5Z package!"
#endif
#ifndef H5Zpkg_H
#define H5Zpkg_H
/* Include private header file */
#include "H5Zprivate.h" /* Filter functions */
/********************/
/* Internal filters */
/********************/
/* Shuffle filter */
H5_DLLVAR const H5Z_class2_t H5Z_SHUFFLE[1];
/* Fletcher32 filter */
H5_DLLVAR const H5Z_class2_t H5Z_FLETCHER32[1];
/* n-bit filter */
H5_DLLVAR H5Z_class2_t H5Z_NBIT[1];
/* Scale/offset filter */
H5_DLLVAR H5Z_class2_t H5Z_SCALEOFFSET[1];
/********************/
/* External filters */
/********************/
/* Deflate filter */
#ifdef H5_HAVE_FILTER_DEFLATE
H5_DLLVAR const H5Z_class2_t H5Z_DEFLATE[1];
#endif /* H5_HAVE_FILTER_DEFLATE */
/* szip filter */
#ifdef H5_HAVE_FILTER_SZIP
H5_DLLVAR H5Z_class2_t H5Z_SZIP[1];
#endif /* H5_HAVE_FILTER_SZIP */
/* Package internal routines */
H5_DLL herr_t H5Z__unregister(H5Z_filter_t filter_id);
#endif /* H5Zpkg_H */
|
3df298af482709141275ad8f009a3cb80595c066
|
e22fd36933c9114a9df1694e7a6274bf059de2a6
|
/third_party/acados/include/hpipm/include/hpipm_s_dense_qcqp.h
|
d03c065375f323c20d22ce3e9e73b9aa3da75f57
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
commaai/openpilot
|
66dfb7f31290bc8f58c9ead95d56697a52b45afb
|
a0b49d54222c52ff0112c402bc0e0d9262e77a66
|
refs/heads/master
| 2023-09-05T21:34:14.076796
| 2023-09-05T21:15:18
| 2023-09-05T21:15:18
| 74,627,617
| 46,071
| 9,878
|
MIT
| 2023-09-14T21:51:23
| 2016-11-24T01:33:30
|
Python
|
UTF-8
|
C
| false
| false
| 8,329
|
h
|
hpipm_s_dense_qcqp.h
|
/**************************************************************************************************
* *
* This file is part of HPIPM. *
* *
* HPIPM -- High-Performance Interior Point Method. *
* Copyright (C) 2019 by Gianluca Frison. *
* Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. *
* All rights reserved. *
* *
* The 2-Clause BSD License *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice, this *
* list of conditions and the following disclaimer. *
* 2. Redistributions in binary form must reproduce the above copyright notice, *
* this list of conditions and the following disclaimer in the documentation *
* and/or other materials provided with the distribution. *
* *
* 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. *
* *
* Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de *
* *
**************************************************************************************************/
#ifndef HPIPM_S_DENSE_QCQP_H_
#define HPIPM_S_DENSE_QCQP_H_
#include <blasfeo_target.h>
#include <blasfeo_common.h>
#include "hpipm_s_dense_qcqp_dim.h"
#ifdef __cplusplus
extern "C" {
#endif
struct s_dense_qcqp
{
struct s_dense_qcqp_dim *dim;
struct blasfeo_smat *Hv; // hessian of cost & vector work space
struct blasfeo_smat *A; // equality constraint matrix
struct blasfeo_smat *Ct; // inequality constraints matrix
struct blasfeo_smat *Hq; // hessians of quadratic constraints
struct blasfeo_svec *gz; // gradient of cost & gradient of slacks
struct blasfeo_svec *b; // equality constraint vector
struct blasfeo_svec *d; // inequality constraints vector
struct blasfeo_svec *d_mask; // inequality constraints mask vector
struct blasfeo_svec *m; // rhs of complementarity condition
struct blasfeo_svec *Z; // (diagonal) hessian of slacks
int *idxb; // indices of box constrained variables within [u; x]
int *idxs_rev; // index of soft constraints (reverse storage)
int *Hq_nzero; // for each int, the last 3 bits ...abc, {a,b,c}=0 => {R,S,Q}=0
hpipm_size_t memsize; // memory size in bytes
};
//
hpipm_size_t s_dense_qcqp_memsize(struct s_dense_qcqp_dim *dim);
//
void s_dense_qcqp_create(struct s_dense_qcqp_dim *dim, struct s_dense_qcqp *qp, void *memory);
//
void s_dense_qcqp_set(char *field, void *value, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_H(float *H, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_g(float *g, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_A(float *A, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_b(float *b, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_idxb(int *idxb, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_lb(float *lb, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_lb_mask(float *lb, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_ub(float *ub, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_ub_mask(float *ub, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_C(float *C, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_lg(float *lg, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_lg_mask(float *lg, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_ug(float *ug, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_ug_mask(float *ug, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_Hq(float *Hq, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_gq(float *gq, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_uq(float *uq, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_uq_mask(float *uq, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_idxs(int *idxs, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_idxs_rev(int *idxs_rev, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_Zl(float *Zl, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_Zu(float *Zu, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_zl(float *zl, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_zu(float *zu, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_ls(float *ls, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_ls_mask(float *ls, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_us(float *us, struct s_dense_qcqp *qp);
//
void s_dense_qcqp_set_us_mask(float *us, struct s_dense_qcqp *qp);
// getters (COLMAJ)
void s_dense_qcqp_get_H(struct s_dense_qcqp *qp, float *H);
//
void s_dense_qcqp_get_g(struct s_dense_qcqp *qp, float *g);
//
void s_dense_qcqp_get_A(struct s_dense_qcqp *qp, float *A);
//
void s_dense_qcqp_get_b(struct s_dense_qcqp *qp, float *b);
//
void s_dense_qcqp_get_idxb(struct s_dense_qcqp *qp, int *idxb);
//
void s_dense_qcqp_get_lb(struct s_dense_qcqp *qp, float *lb);
//
void s_dense_qcqp_get_lb_mask(struct s_dense_qcqp *qp, float *lb);
//
void s_dense_qcqp_get_ub(struct s_dense_qcqp *qp, float *ub);
//
void s_dense_qcqp_get_ub_mask(struct s_dense_qcqp *qp, float *ub);
//
void s_dense_qcqp_get_C(struct s_dense_qcqp *qp, float *C);
//
void s_dense_qcqp_get_lg(struct s_dense_qcqp *qp, float *lg);
//
void s_dense_qcqp_get_lg_mask(struct s_dense_qcqp *qp, float *lg);
//
void s_dense_qcqp_get_ug(struct s_dense_qcqp *qp, float *ug);
//
void s_dense_qcqp_get_ug_mask(struct s_dense_qcqp *qp, float *ug);
//
void s_dense_qcqp_get_idxs(struct s_dense_qcqp *qp, int *idxs);
//
void s_dense_qcqp_get_idxs_rev(struct s_dense_qcqp *qp, int *idxs_rev);
//
void s_dense_qcqp_get_Zl(struct s_dense_qcqp *qp, float *Zl);
//
void s_dense_qcqp_get_Zu(struct s_dense_qcqp *qp, float *Zu);
//
void s_dense_qcqp_get_zl(struct s_dense_qcqp *qp, float *zl);
//
void s_dense_qcqp_get_zu(struct s_dense_qcqp *qp, float *zu);
//
void s_dense_qcqp_get_ls(struct s_dense_qcqp *qp, float *ls);
//
void s_dense_qcqp_get_ls_mask(struct s_dense_qcqp *qp, float *ls);
//
void s_dense_qcqp_get_us(struct s_dense_qcqp *qp, float *us);
//
void s_dense_qcqp_get_us_mask(struct s_dense_qcqp *qp, float *us);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // HPIPM_S_DENSE_QCQP_H_
|
65fcc6000ef4c061a1ba30c3a901131d40d4f63e
|
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
|
/editors/emacs23/patches/patch-src_m_amdx86-64.h
|
eb1642db0db87de8cad1b8f7f28b7f96f2d99a38
|
[] |
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
| 462
|
h
|
patch-src_m_amdx86-64.h
|
$NetBSD: patch-src_m_amdx86-64.h,v 1.2 2014/07/09 03:18:44 taca Exp $
Add support for DragonFly.
--- src/m/amdx86-64.h.orig 2011-11-26 03:20:20.000000000 +0000
+++ src/m/amdx86-64.h
@@ -101,6 +101,10 @@ along with GNU Emacs. If not, see <http
/* LIB_STANDARD and START_FILES set correctly in s/netbsd.h */
+#elif defined(__DragonFly__)
+
+/* LIB_STANDARD and START_FILES set correctly in s/dragonfly.h */
+
#elif defined(SOLARIS2)
#undef START_FILES
|
8d5236226ed6519ad4aa18ed48f8d67f3afb6ce8
|
471caab2fb3ca88ccae11ab6602f0792d479a067
|
/src/gz/menu_option.c
|
892f11544d6ed63bfb0ba9a25203efe84928f8e6
|
[] |
no_license
|
glankk/gz
|
8c37041cc12834a9c068964bb9654cb4881d7710
|
ac5a68f60cc851cc457ddc0f2f1b0ef1d2903775
|
refs/heads/master
| 2023-05-12T02:00:01.285112
| 2023-05-08T00:39:50
| 2023-05-08T00:39:50
| 58,239,100
| 200
| 71
| null | 2023-01-08T04:06:28
| 2016-05-06T22:57:18
|
C
|
UTF-8
|
C
| false
| false
| 4,051
|
c
|
menu_option.c
|
#include <stdlib.h>
#include <string.h>
#include <vector/vector.h>
#include "menu.h"
struct item_data
{
struct vector options;
menu_generic_callback callback_proc;
void *callback_data;
int value;
_Bool active;
};
static int think_proc(struct menu_item *item)
{
struct item_data *data = item->data;
if (data->callback_proc) {
int r = data->callback_proc(item, MENU_CALLBACK_THINK, data->callback_data);
if (r)
return r;
if (data->active)
r = data->callback_proc(item, MENU_CALLBACK_THINK_ACTIVE,
data->callback_data);
else
r = data->callback_proc(item, MENU_CALLBACK_THINK_INACTIVE,
data->callback_data);
return r;
}
return 0;
}
static int navigate_proc(struct menu_item *item,
enum menu_navigation nav)
{
struct item_data *data = item->data;
if (data->callback_proc &&
data->callback_proc(item, MENU_CALLBACK_NAV_UP + nav,
data->callback_data))
return 1;
int value = data->value;
switch (nav) {
case MENU_NAVIGATE_UP: value += 1; break;
case MENU_NAVIGATE_DOWN: value -= 1; break;
case MENU_NAVIGATE_LEFT: value -= 3; break;
case MENU_NAVIGATE_RIGHT: value += 3; break;
}
value %= (int)data->options.size;
if (value < 0)
value += (int)data->options.size;
data->value = value;
char **option = vector_at(&data->options, data->value);
item->text = *option;
if (data->callback_proc)
data->callback_proc(item, MENU_CALLBACK_CHANGED, data->callback_data);
return 1;
};
static int activate_proc(struct menu_item *item)
{
struct item_data *data = item->data;
if (data->active) {
if (data->callback_proc && data->callback_proc(item,
MENU_CALLBACK_DEACTIVATE,
data->callback_data))
return 1;
item->navigate_proc = NULL;
item->animate_highlight = 0;
}
else {
if (data->callback_proc && data->callback_proc(item,
MENU_CALLBACK_ACTIVATE,
data->callback_data))
return 1;
item->navigate_proc = navigate_proc;
item->animate_highlight = 1;
}
data->active = !data->active;
return 1;
}
static int destroy_proc(struct menu_item *item)
{
struct item_data *data = item->data;
item->text = NULL;
for (size_t i = 0; i < data->options.size; ++i) {
char **option = vector_at(&data->options, i);
free(*option);
}
vector_destroy(&data->options);
return 0;
}
struct menu_item *menu_add_option(struct menu *menu, int x, int y,
const char *options,
menu_generic_callback callback_proc,
void *callback_data)
{
struct item_data *data = malloc(sizeof(*data));
vector_init(&data->options, sizeof(char *));
for (const char *option = options; *option;) {
size_t option_length = strlen(option);
char *new_option = malloc(option_length + 1);
strcpy(new_option, option);
vector_push_back(&data->options, 1, &new_option);
option += option_length + 1;
}
data->callback_proc = callback_proc;
data->callback_data = callback_data;
data->value = 0;
data->active = 0;
struct menu_item *item = menu_item_add(menu, x, y, NULL, 0xFFFFFF);
char **option = vector_at(&data->options, data->value);
item->text = *option;
item->data = data;
item->think_proc = think_proc;
item->activate_proc = activate_proc;
item->destroy_proc = destroy_proc;
return item;
}
int menu_option_get(struct menu_item *item)
{
struct item_data *data = item->data;
return data->value;
}
void menu_option_set(struct menu_item *item, int value)
{
struct item_data *data = item->data;
data->value = value;
char **option = vector_at(&data->options, data->value);
item->text = *option;
}
|
4102dbc11802aed41ad36e74bbfea97c0c007a48
|
f42190636add23ead6a5022d706a124032d66f92
|
/src/Microsoft.DotNet.Wpf/src/WpfGfx/include/Generated/wgx_commands.h
|
74cb45ff887e9949651d0de16d4c7ab646a76ca0
|
[
"MIT"
] |
permissive
|
dotnet/wpf
|
b8f73a99e03f87b4dee5db643e38e2c0704f707a
|
2ff355a607d79eef5fea7796de1f29cf9ea4fbed
|
refs/heads/main
| 2023-09-04T09:35:19.355384
| 2023-09-03T02:30:37
| 2023-09-03T02:30:37
| 153,711,945
| 6,927
| 1,397
|
MIT
| 2023-09-14T17:22:06
| 2018-10-19T01:55:23
|
C#
|
UTF-8
|
C
| false
| false
| 24,611
|
h
|
wgx_commands.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//---------------------------------------------------------------------------
//
// This file is automatically generated. Please do not edit it directly.
//
// File name: wgx_commands.h
//---------------------------------------------------------------------------
#pragma once
typedef struct
{
MILCMD Type;
} MILCMD_TRANSPORT_SYNCFLUSH;
typedef struct
{
MILCMD Type;
HMIL_CHANNEL hChannel;
} MILCMD_TRANSPORT_DESTROYRESOURCESONCHANNEL;
typedef struct
{
MILCMD Type;
BOOL Enable;
} MILCMD_PARTITION_REGISTERFORNOTIFICATIONS;
typedef struct
{
MILCMD Type;
BOOL ReturnCommonMinimum;
} MILCMD_CHANNEL_REQUESTTIER;
typedef struct
{
MILCMD Type;
BOOL Enable;
} MILCMD_PARTITION_SETVBLANKSYNCMODE;
typedef struct
{
MILCMD Type;
UINT64 FrameTime;
} MILCMD_PARTITION_NOTIFYPRESENT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MIL_RESOURCE_TYPE resType;
} MILCMD_CHANNEL_CREATERESOURCE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MIL_RESOURCE_TYPE resType;
} MILCMD_CHANNEL_DELETERESOURCE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Original;
HMIL_CHANNEL TargetChannel;
HMIL_RESOURCE Duplicate;
} MILCMD_CHANNEL_DUPLICATEHANDLE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT64 pInteropDeviceBitmap;
UINT64 pSoftwareBitmap;
} MILCMD_D3DIMAGE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT64 hEvent;
} MILCMD_D3DIMAGE_PRESENT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
IWICBitmapSource* pIBitmap;
} MILCMD_BITMAP_SOURCE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
BOOL UseDirtyRect;
RECT DirtyRect;
} MILCMD_BITMAP_INVALIDATE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE Value;
} MILCMD_DOUBLERESOURCE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilColorF Value;
} MILCMD_COLORRESOURCE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilPoint2D Value;
} MILCMD_POINTRESOURCE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilPointAndSizeD Value;
} MILCMD_RECTRESOURCE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilSizeD Value;
} MILCMD_SIZERESOURCE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilMatrix3x2D Value;
} MILCMD_MATRIXRESOURCE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilPoint3F Value;
} MILCMD_POINT3DRESOURCE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilPoint3F Value;
} MILCMD_VECTOR3DRESOURCE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilQuaternionF Value;
} MILCMD_QUATERNIONRESOURCE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT64 pMedia;
BOOL notifyUceDirect;
} MILCMD_MEDIAPLAYER;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT cbData;
} MILCMD_RENDERDATA;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT id;
} MILCMD_ETWEVENTRESOURCE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
} MILCMD_VISUAL_CREATE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE offsetX;
DOUBLE offsetY;
} MILCMD_VISUAL_SETOFFSET;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hTransform;
} MILCMD_VISUAL_SETTRANSFORM;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hEffect;
} MILCMD_VISUAL_SETEFFECT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hCacheMode;
} MILCMD_VISUAL_SETCACHEMODE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hClip;
} MILCMD_VISUAL_SETCLIP;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE alpha;
} MILCMD_VISUAL_SETALPHA;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilRenderOptions renderOptions;
} MILCMD_VISUAL_SETRENDEROPTIONS;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hContent;
} MILCMD_VISUAL_SETCONTENT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hAlphaMask;
} MILCMD_VISUAL_SETALPHAMASK;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
} MILCMD_VISUAL_REMOVEALLCHILDREN;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hChild;
} MILCMD_VISUAL_REMOVECHILD;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hChild;
UINT index;
} MILCMD_VISUAL_INSERTCHILDAT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
WORD countX;
UINT16 UINT16Padding0;
WORD countY;
UINT16 UINT16Padding1;
} MILCMD_VISUAL_SETGUIDELINECOLLECTION;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilPointAndSizeD Clip;
BOOL IsEnabled;
} MILCMD_VISUAL_SETSCROLLABLEAREACLIP;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hCamera;
} MILCMD_VIEWPORT3DVISUAL_SETCAMERA;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilPointAndSizeD Viewport;
} MILCMD_VIEWPORT3DVISUAL_SETVIEWPORT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hChild;
} MILCMD_VIEWPORT3DVISUAL_SET3DCHILD;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hContent;
} MILCMD_VISUAL3D_SETCONTENT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hTransform;
} MILCMD_VISUAL3D_SETTRANSFORM;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
} MILCMD_VISUAL3D_REMOVEALLCHILDREN;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hChild;
} MILCMD_VISUAL3D_REMOVECHILD;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hChild;
UINT index;
} MILCMD_VISUAL3D_INSERTCHILDAT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT64 hwnd;
UINT64 hSection;
UINT64 masterDevice;
UINT width;
UINT height;
MilColorF clearColor;
UINT flags;
HMIL_RESOURCE hBitmap;
UINT stride;
MilPixelFormat::Enum ePixelFormat;
INT DpiAwarenessContext;
DOUBLE DpiX;
DOUBLE DpiY;
} MILCMD_HWNDTARGET_CREATE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
BOOL Suppress;
} MILCMD_HWNDTARGET_SUPPRESSLAYERED;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
RECT windowRect;
MilWindowLayerType::Enum windowLayerType;
MilTransparency::Flags transparencyMode;
FLOAT constantAlpha;
BOOL isChild;
BOOL isRTL;
BOOL renderingEnabled;
MilColorF colorKey;
UINT disableCookie;
BOOL gdiBlt;
} MILCMD_TARGET_UPDATEWINDOWSETTINGS;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT64 hwnd;
UINT64 pRenderTarget;
UINT width;
UINT height;
UINT dummy;
} MILCMD_GENERICTARGET_CREATE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hRoot;
} MILCMD_TARGET_SETROOT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilColorF clearColor;
} MILCMD_TARGET_SETCLEARCOLOR;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
RECT rc;
} MILCMD_TARGET_INVALIDATE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT flags;
} MILCMD_TARGET_SETFLAGS;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE DpiX;
DOUBLE DpiY;
BOOL AfterParent;
} MILCMD_HWNDTARGET_DPICHANGED;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT64 pIDWriteFont;
WORD GlyphRunFlags;
UINT16 UINT16Padding0;
MilPoint2F Origin;
FLOAT MuSize;
MilPointAndSizeD ManagedBounds;
WORD GlyphCount;
UINT16 UINT16Padding1;
WORD BidiLevel;
UINT16 UINT16Padding2;
WORD DWriteTextMeasuringMethod;
UINT16 UINT16Padding3;
} MILCMD_GLYPHRUN_CREATE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT64 SwDoubleBufferedBitmap;
BOOL UseBackBuffer;
} MILCMD_DOUBLEBUFFEREDBITMAP;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT64 CopyCompletedEvent;
} MILCMD_DOUBLEBUFFEREDBITMAP_COPYFORWARD;
typedef struct
{
MILCMD Type;
BOOL ShouldRenderEvenWhenNoDisplayDevicesAreAvailable;
} MILCMD_PARTITION_NOTIFYPOLICYCHANGEFORNONINTERACTIVEMODE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE angle;
MilPoint3F axis;
HMIL_RESOURCE hAxisAnimations;
HMIL_RESOURCE hAngleAnimations;
} MILCMD_AXISANGLEROTATION3D;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilQuaternionF quaternion;
HMIL_RESOURCE hQuaternionAnimations;
} MILCMD_QUATERNIONROTATION3D;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE nearPlaneDistance;
DOUBLE farPlaneDistance;
DOUBLE fieldOfView;
MilPoint3F position;
HMIL_RESOURCE htransform;
MilPoint3F lookDirection;
HMIL_RESOURCE hNearPlaneDistanceAnimations;
MilPoint3F upDirection;
HMIL_RESOURCE hFarPlaneDistanceAnimations;
HMIL_RESOURCE hPositionAnimations;
HMIL_RESOURCE hLookDirectionAnimations;
HMIL_RESOURCE hUpDirectionAnimations;
HMIL_RESOURCE hFieldOfViewAnimations;
} MILCMD_PERSPECTIVECAMERA;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE nearPlaneDistance;
DOUBLE farPlaneDistance;
DOUBLE width;
MilPoint3F position;
HMIL_RESOURCE htransform;
MilPoint3F lookDirection;
HMIL_RESOURCE hNearPlaneDistanceAnimations;
MilPoint3F upDirection;
HMIL_RESOURCE hFarPlaneDistanceAnimations;
HMIL_RESOURCE hPositionAnimations;
HMIL_RESOURCE hLookDirectionAnimations;
HMIL_RESOURCE hUpDirectionAnimations;
HMIL_RESOURCE hWidthAnimations;
} MILCMD_ORTHOGRAPHICCAMERA;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
D3DMATRIX viewMatrix;
D3DMATRIX projectionMatrix;
HMIL_RESOURCE htransform;
} MILCMD_MATRIXCAMERA;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE htransform;
UINT32 ChildrenSize;
} MILCMD_MODEL3DGROUP;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilColorF color;
HMIL_RESOURCE htransform;
HMIL_RESOURCE hColorAnimations;
} MILCMD_AMBIENTLIGHT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilColorF color;
MilPoint3F direction;
HMIL_RESOURCE htransform;
HMIL_RESOURCE hColorAnimations;
HMIL_RESOURCE hDirectionAnimations;
} MILCMD_DIRECTIONALLIGHT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilColorF color;
DOUBLE range;
DOUBLE constantAttenuation;
DOUBLE linearAttenuation;
DOUBLE quadraticAttenuation;
MilPoint3F position;
HMIL_RESOURCE htransform;
HMIL_RESOURCE hColorAnimations;
HMIL_RESOURCE hPositionAnimations;
HMIL_RESOURCE hRangeAnimations;
HMIL_RESOURCE hConstantAttenuationAnimations;
HMIL_RESOURCE hLinearAttenuationAnimations;
HMIL_RESOURCE hQuadraticAttenuationAnimations;
} MILCMD_POINTLIGHT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilColorF color;
DOUBLE range;
DOUBLE constantAttenuation;
DOUBLE linearAttenuation;
DOUBLE quadraticAttenuation;
DOUBLE outerConeAngle;
DOUBLE innerConeAngle;
MilPoint3F position;
HMIL_RESOURCE htransform;
MilPoint3F direction;
HMIL_RESOURCE hColorAnimations;
HMIL_RESOURCE hPositionAnimations;
HMIL_RESOURCE hRangeAnimations;
HMIL_RESOURCE hConstantAttenuationAnimations;
HMIL_RESOURCE hLinearAttenuationAnimations;
HMIL_RESOURCE hQuadraticAttenuationAnimations;
HMIL_RESOURCE hDirectionAnimations;
HMIL_RESOURCE hOuterConeAngleAnimations;
HMIL_RESOURCE hInnerConeAngleAnimations;
} MILCMD_SPOTLIGHT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE htransform;
HMIL_RESOURCE hgeometry;
HMIL_RESOURCE hmaterial;
HMIL_RESOURCE hbackMaterial;
} MILCMD_GEOMETRYMODEL3D;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT32 PositionsSize;
UINT32 NormalsSize;
UINT32 TextureCoordinatesSize;
UINT32 TriangleIndicesSize;
} MILCMD_MESHGEOMETRY3D;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT32 ChildrenSize;
} MILCMD_MATERIALGROUP;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilColorF color;
MilColorF ambientColor;
HMIL_RESOURCE hbrush;
} MILCMD_DIFFUSEMATERIAL;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilColorF color;
DOUBLE specularPower;
HMIL_RESOURCE hbrush;
} MILCMD_SPECULARMATERIAL;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilColorF color;
HMIL_RESOURCE hbrush;
} MILCMD_EMISSIVEMATERIAL;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT32 ChildrenSize;
} MILCMD_TRANSFORM3DGROUP;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE offsetX;
DOUBLE offsetY;
DOUBLE offsetZ;
HMIL_RESOURCE hOffsetXAnimations;
HMIL_RESOURCE hOffsetYAnimations;
HMIL_RESOURCE hOffsetZAnimations;
} MILCMD_TRANSLATETRANSFORM3D;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE scaleX;
DOUBLE scaleY;
DOUBLE scaleZ;
DOUBLE centerX;
DOUBLE centerY;
DOUBLE centerZ;
HMIL_RESOURCE hScaleXAnimations;
HMIL_RESOURCE hScaleYAnimations;
HMIL_RESOURCE hScaleZAnimations;
HMIL_RESOURCE hCenterXAnimations;
HMIL_RESOURCE hCenterYAnimations;
HMIL_RESOURCE hCenterZAnimations;
} MILCMD_SCALETRANSFORM3D;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE centerX;
DOUBLE centerY;
DOUBLE centerZ;
HMIL_RESOURCE hCenterXAnimations;
HMIL_RESOURCE hCenterYAnimations;
HMIL_RESOURCE hCenterZAnimations;
HMIL_RESOURCE hrotation;
} MILCMD_ROTATETRANSFORM3D;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
D3DMATRIX matrix;
} MILCMD_MATRIXTRANSFORM3D;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
ShaderEffectShaderRenderMode::Enum ShaderRenderMode;
UINT32 PixelShaderBytecodeSize;
BOOL CompileSoftwareShader;
} MILCMD_PIXELSHADER;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE Opacity;
HMIL_RESOURCE hOpacityAnimations;
HMIL_RESOURCE hTransform;
HMIL_RESOURCE hRelativeTransform;
} MILCMD_IMPLICITINPUTBRUSH;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE Radius;
HMIL_RESOURCE hRadiusAnimations;
MilKernelType::Enum KernelType;
MilEffectRenderingBias::Enum RenderingBias;
} MILCMD_BLUREFFECT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE ShadowDepth;
MilColorF Color;
DOUBLE Direction;
DOUBLE Opacity;
DOUBLE BlurRadius;
HMIL_RESOURCE hShadowDepthAnimations;
HMIL_RESOURCE hColorAnimations;
HMIL_RESOURCE hDirectionAnimations;
HMIL_RESOURCE hOpacityAnimations;
HMIL_RESOURCE hBlurRadiusAnimations;
MilEffectRenderingBias::Enum RenderingBias;
} MILCMD_DROPSHADOWEFFECT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE TopPadding;
DOUBLE BottomPadding;
DOUBLE LeftPadding;
DOUBLE RightPadding;
HMIL_RESOURCE hPixelShader;
INT DdxUvDdyUvRegisterIndex;
UINT32 ShaderConstantFloatRegistersSize;
UINT32 DependencyPropertyFloatValuesSize;
UINT32 ShaderConstantIntRegistersSize;
UINT32 DependencyPropertyIntValuesSize;
UINT32 ShaderConstantBoolRegistersSize;
UINT32 DependencyPropertyBoolValuesSize;
UINT32 ShaderSamplerRegistrationInfoSize;
UINT32 DependencyPropertySamplerValuesSize;
} MILCMD_SHADEREFFECT;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hDrawing;
} MILCMD_DRAWINGIMAGE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT32 ChildrenSize;
} MILCMD_TRANSFORMGROUP;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE X;
DOUBLE Y;
HMIL_RESOURCE hXAnimations;
HMIL_RESOURCE hYAnimations;
} MILCMD_TRANSLATETRANSFORM;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE ScaleX;
DOUBLE ScaleY;
DOUBLE CenterX;
DOUBLE CenterY;
HMIL_RESOURCE hScaleXAnimations;
HMIL_RESOURCE hScaleYAnimations;
HMIL_RESOURCE hCenterXAnimations;
HMIL_RESOURCE hCenterYAnimations;
} MILCMD_SCALETRANSFORM;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE AngleX;
DOUBLE AngleY;
DOUBLE CenterX;
DOUBLE CenterY;
HMIL_RESOURCE hAngleXAnimations;
HMIL_RESOURCE hAngleYAnimations;
HMIL_RESOURCE hCenterXAnimations;
HMIL_RESOURCE hCenterYAnimations;
} MILCMD_SKEWTRANSFORM;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE Angle;
DOUBLE CenterX;
DOUBLE CenterY;
HMIL_RESOURCE hAngleAnimations;
HMIL_RESOURCE hCenterXAnimations;
HMIL_RESOURCE hCenterYAnimations;
} MILCMD_ROTATETRANSFORM;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilMatrix3x2D Matrix;
HMIL_RESOURCE hMatrixAnimations;
} MILCMD_MATRIXTRANSFORM;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilPoint2D StartPoint;
MilPoint2D EndPoint;
HMIL_RESOURCE hTransform;
HMIL_RESOURCE hStartPointAnimations;
HMIL_RESOURCE hEndPointAnimations;
} MILCMD_LINEGEOMETRY;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE RadiusX;
DOUBLE RadiusY;
MilPointAndSizeD Rect;
HMIL_RESOURCE hTransform;
HMIL_RESOURCE hRadiusXAnimations;
HMIL_RESOURCE hRadiusYAnimations;
HMIL_RESOURCE hRectAnimations;
} MILCMD_RECTANGLEGEOMETRY;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE RadiusX;
DOUBLE RadiusY;
MilPoint2D Center;
HMIL_RESOURCE hTransform;
HMIL_RESOURCE hRadiusXAnimations;
HMIL_RESOURCE hRadiusYAnimations;
HMIL_RESOURCE hCenterAnimations;
} MILCMD_ELLIPSEGEOMETRY;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hTransform;
MilFillMode::Enum FillRule;
UINT32 ChildrenSize;
} MILCMD_GEOMETRYGROUP;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hTransform;
MilCombineMode::Enum GeometryCombineMode;
HMIL_RESOURCE hGeometry1;
HMIL_RESOURCE hGeometry2;
} MILCMD_COMBINEDGEOMETRY;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hTransform;
MilFillMode::Enum FillRule;
UINT32 FiguresSize;
} MILCMD_PATHGEOMETRY;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE Opacity;
MilColorF Color;
HMIL_RESOURCE hOpacityAnimations;
HMIL_RESOURCE hTransform;
HMIL_RESOURCE hRelativeTransform;
HMIL_RESOURCE hColorAnimations;
} MILCMD_SOLIDCOLORBRUSH;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE Opacity;
MilPoint2D StartPoint;
MilPoint2D EndPoint;
HMIL_RESOURCE hOpacityAnimations;
HMIL_RESOURCE hTransform;
HMIL_RESOURCE hRelativeTransform;
MilColorInterpolationMode::Enum ColorInterpolationMode;
MilBrushMappingMode::Enum MappingMode;
MilGradientSpreadMethod::Enum SpreadMethod;
UINT32 GradientStopsSize;
HMIL_RESOURCE hStartPointAnimations;
HMIL_RESOURCE hEndPointAnimations;
} MILCMD_LINEARGRADIENTBRUSH;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE Opacity;
MilPoint2D Center;
DOUBLE RadiusX;
DOUBLE RadiusY;
MilPoint2D GradientOrigin;
HMIL_RESOURCE hOpacityAnimations;
HMIL_RESOURCE hTransform;
HMIL_RESOURCE hRelativeTransform;
MilColorInterpolationMode::Enum ColorInterpolationMode;
MilBrushMappingMode::Enum MappingMode;
MilGradientSpreadMethod::Enum SpreadMethod;
UINT32 GradientStopsSize;
HMIL_RESOURCE hCenterAnimations;
HMIL_RESOURCE hRadiusXAnimations;
HMIL_RESOURCE hRadiusYAnimations;
HMIL_RESOURCE hGradientOriginAnimations;
} MILCMD_RADIALGRADIENTBRUSH;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE Opacity;
MilPointAndSizeD Viewport;
MilPointAndSizeD Viewbox;
DOUBLE CacheInvalidationThresholdMinimum;
DOUBLE CacheInvalidationThresholdMaximum;
HMIL_RESOURCE hOpacityAnimations;
HMIL_RESOURCE hTransform;
HMIL_RESOURCE hRelativeTransform;
MilBrushMappingMode::Enum ViewportUnits;
MilBrushMappingMode::Enum ViewboxUnits;
HMIL_RESOURCE hViewportAnimations;
HMIL_RESOURCE hViewboxAnimations;
MilStretch::Enum Stretch;
MilTileMode::Enum TileMode;
MilHorizontalAlignment::Enum AlignmentX;
MilVerticalAlignment::Enum AlignmentY;
MilCachingHint::Enum CachingHint;
HMIL_RESOURCE hImageSource;
} MILCMD_IMAGEBRUSH;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE Opacity;
MilPointAndSizeD Viewport;
MilPointAndSizeD Viewbox;
DOUBLE CacheInvalidationThresholdMinimum;
DOUBLE CacheInvalidationThresholdMaximum;
HMIL_RESOURCE hOpacityAnimations;
HMIL_RESOURCE hTransform;
HMIL_RESOURCE hRelativeTransform;
MilBrushMappingMode::Enum ViewportUnits;
MilBrushMappingMode::Enum ViewboxUnits;
HMIL_RESOURCE hViewportAnimations;
HMIL_RESOURCE hViewboxAnimations;
MilStretch::Enum Stretch;
MilTileMode::Enum TileMode;
MilHorizontalAlignment::Enum AlignmentX;
MilVerticalAlignment::Enum AlignmentY;
MilCachingHint::Enum CachingHint;
HMIL_RESOURCE hDrawing;
} MILCMD_DRAWINGBRUSH;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE Opacity;
MilPointAndSizeD Viewport;
MilPointAndSizeD Viewbox;
DOUBLE CacheInvalidationThresholdMinimum;
DOUBLE CacheInvalidationThresholdMaximum;
HMIL_RESOURCE hOpacityAnimations;
HMIL_RESOURCE hTransform;
HMIL_RESOURCE hRelativeTransform;
MilBrushMappingMode::Enum ViewportUnits;
MilBrushMappingMode::Enum ViewboxUnits;
HMIL_RESOURCE hViewportAnimations;
HMIL_RESOURCE hViewboxAnimations;
MilStretch::Enum Stretch;
MilTileMode::Enum TileMode;
MilHorizontalAlignment::Enum AlignmentX;
MilVerticalAlignment::Enum AlignmentY;
MilCachingHint::Enum CachingHint;
HMIL_RESOURCE hVisual;
} MILCMD_VISUALBRUSH;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE Opacity;
HMIL_RESOURCE hOpacityAnimations;
HMIL_RESOURCE hTransform;
HMIL_RESOURCE hRelativeTransform;
HMIL_RESOURCE hBitmapCache;
HMIL_RESOURCE hInternalTarget;
} MILCMD_BITMAPCACHEBRUSH;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE Offset;
HMIL_RESOURCE hOffsetAnimations;
UINT32 DashesSize;
} MILCMD_DASHSTYLE;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE Thickness;
DOUBLE MiterLimit;
HMIL_RESOURCE hBrush;
HMIL_RESOURCE hThicknessAnimations;
MilPenCap::Enum StartLineCap;
MilPenCap::Enum EndLineCap;
MilPenCap::Enum DashCap;
MilPenJoin::Enum LineJoin;
HMIL_RESOURCE hDashStyle;
} MILCMD_PEN;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hBrush;
HMIL_RESOURCE hPen;
HMIL_RESOURCE hGeometry;
} MILCMD_GEOMETRYDRAWING;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
HMIL_RESOURCE hGlyphRun;
HMIL_RESOURCE hForegroundBrush;
} MILCMD_GLYPHRUNDRAWING;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilPointAndSizeD Rect;
HMIL_RESOURCE hImageSource;
HMIL_RESOURCE hRectAnimations;
} MILCMD_IMAGEDRAWING;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
MilPointAndSizeD Rect;
HMIL_RESOURCE hPlayer;
HMIL_RESOURCE hRectAnimations;
} MILCMD_VIDEODRAWING;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE Opacity;
UINT32 ChildrenSize;
HMIL_RESOURCE hClipGeometry;
HMIL_RESOURCE hOpacityAnimations;
HMIL_RESOURCE hOpacityMask;
HMIL_RESOURCE hTransform;
HMIL_RESOURCE hGuidelineSet;
MilEdgeMode::Enum EdgeMode;
MilBitmapScalingMode::Enum bitmapScalingMode;
MilClearTypeHint::Enum ClearTypeHint;
} MILCMD_DRAWINGGROUP;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
UINT32 GuidelinesXSize;
UINT32 GuidelinesYSize;
BOOL IsDynamic;
} MILCMD_GUIDELINESET;
typedef struct
{
MILCMD Type;
HMIL_RESOURCE Handle;
DOUBLE RenderAtScale;
HMIL_RESOURCE hRenderAtScaleAnimations;
BOOL SnapsToDevicePixels;
BOOL EnableClearType;
} MILCMD_BITMAPCACHE;
|
9dbc87c44334770f9b92081203df6e5c86005cec
|
f49f91984f6942c01547a780f8f37eed7ec5b159
|
/include/wlr_screencast.h
|
efd7269bf3c311ae8bbc33613adafd799400e256
|
[
"MIT"
] |
permissive
|
hyprwm/xdg-desktop-portal-hyprland
|
d04c3d116afe17316c710595a9dc1630098c01c6
|
57a3a41ba6b358109e4fc25c6a4706b5f7d93c6b
|
refs/heads/master
| 2023-08-17T00:59:21.709337
| 2023-08-12T11:52:50
| 2023-08-12T11:52:50
| 573,914,869
| 107
| 22
|
BSD-3-Clause
| 2023-09-10T16:26:10
| 2022-12-03T20:44:32
|
C++
|
UTF-8
|
C
| false
| false
| 1,032
|
h
|
wlr_screencast.h
|
#ifndef WLR_SCREENCAST_H
#define WLR_SCREENCAST_H
#include "screencast_common.h"
#define WL_OUTPUT_VERSION 1
#define SC_MANAGER_VERSION 3
#define SC_MANAGER_VERSION_MIN 2
#define WL_SHM_VERSION 1
#define XDG_OUTPUT_MANAGER_VERSION 3
#define LINUX_DMABUF_VERSION 4
#define LINUX_DMABUF_VERSION_MIN 3
struct xdpw_state;
int xdpw_wlr_screencopy_init(struct xdpw_state *state);
void xdpw_wlr_screencopy_finish(struct xdpw_screencast_context *ctx);
struct xdpw_wlr_output *xdpw_wlr_output_find_by_name(struct wl_list *output_list,
const char *name);
struct xdpw_wlr_output *xdpw_wlr_output_first(struct wl_list *output_list);
struct xdpw_wlr_output *xdpw_wlr_output_find(struct xdpw_screencast_context *ctx,
struct wl_output *out, uint32_t id);
struct xdpw_share xdpw_wlr_chooser(struct xdpw_screencast_context *ctx);
void xdpw_wlr_frame_finish(struct xdpw_screencast_instance *cast);
void xdpw_wlr_frame_start(struct xdpw_screencast_instance *cast);
void xdpw_wlr_register_cb(struct xdpw_screencast_instance *cast);
#endif
|
a8fd5233067fc1ceaad61f524b3e08920fd3ec01
|
a00712528fef854d2c6fbe8c8c9a940ee88035bf
|
/Engine/Graphics/OpenGL/Shader/ShaderPrimitive.h
|
6f825e29e3798891425fa4efa99eb53fc2e2a743
|
[
"MIT"
] |
permissive
|
scottcgi/Mojoc
|
c7f43344dfeeb604d8500024c34ac66d3567df1a
|
097dde01cad6111acc5e3015ad13c12c1f140243
|
refs/heads/master
| 2023-07-20T14:15:05.546293
| 2023-07-07T14:19:43
| 2023-07-07T14:19:43
| 83,890,107
| 1,209
| 199
|
MIT
| 2023-03-28T23:01:15
| 2017-03-04T11:57:24
|
C
|
UTF-8
|
C
| false
| false
| 1,126
|
h
|
ShaderPrimitive.h
|
/*
* Copyright (c) scott.cgi All Rights Reserved.
*
* This source code belongs to project Mojoc, which is a pure C Game Engine hosted on GitHub.
* The Mojoc Game Engine is licensed under the MIT License, and will continue to be iterated with coding passion.
*
* License : https://github.com/scottcgi/Mojoc/blob/master/LICENSE
* GitHub : https://github.com/scottcgi/Mojoc
* CodeStyle: https://github.com/scottcgi/Mojoc/blob/master/Docs/CodeStyle.md
*
* Since : 2014-2-26
* Update : 2019-1-24
* Author : scott.cgi
*/
#ifndef SHADER_PRIMITIVE_H
#define SHADER_PRIMITIVE_H
#include "Engine/Graphics/OpenGL/Platform/gl3.h"
#include "Engine/Toolkit/Math/Matrix.h"
#include "Engine/Toolkit/Math/Math.h"
#include "Engine/Graphics/Draw/Color.h"
/**
* Shader control for GLPrimitive.
*/
struct AShaderPrimitive
{
GLuint program;
GLint attribPosition;
GLint uniformMVPMatrix;
GLint uniformColor;
GLint uniformPointSize;
void (*Use) (Matrix4* mvpMatrix, Color* color, GLfloat pointSize);
void (*Init)(void);
};
extern struct AShaderPrimitive AShaderPrimitive[1];
#endif
|
803e2d38bb4e0fe8f37951aa835fc1eedbc6d7ef
|
ac2f43c8e0d9649a7f063c59b3dffdfed9fd7ed7
|
/common/recipes-lib/ipc/files/ipc.h
|
a657b90e6b97624207993fae52b9b1497d1b604b
|
[] |
no_license
|
facebook/openbmc
|
bef10604ced226288600f55248b7f1be9945aea4
|
32777c66a8410d767eae15baabf71c61a0bef13c
|
refs/heads/helium
| 2023-08-17T03:13:54.729494
| 2023-08-16T23:24:18
| 2023-08-16T23:24:18
| 31,917,712
| 684
| 331
| null | 2023-07-25T21:19:08
| 2015-03-09T19:18:35
|
C
|
UTF-8
|
C
| false
| false
| 784
|
h
|
ipc.h
|
#ifndef _IPC_CLIENT_H_
#define _IPC_CLIENT_H_
#include <stdint.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX_ENDPOINT_LEN 32
struct client_s;
typedef struct client_s client_t;
typedef int (*ipc_handle_req_t)(client_t *cli);
struct service_s;
typedef struct service_s service_t;
struct client_s {
char endpoint[MAX_ENDPOINT_LEN];
void *svc_cookie;
int fd;
service_t *svc;
};
int ipc_send_req(const char *endpoint, uint8_t *req, size_t req_len, uint8_t *resp, size_t *resp_len, int timeout);
int ipc_recv_req(client_t *cli, uint8_t *req, size_t *req_len, int timeout);
int ipc_send_resp(client_t *cli, uint8_t *resp, size_t resp_len);
int ipc_start_svc(const char *endpoint, ipc_handle_req_t handle_req, int max_active, void *cookie, pthread_t *waiter);
#endif
|
3ca9714bec363561e446acf083c4716bcd7b849e
|
fdf08b05ff4c660e183739dbc18009d0a9b8a49a
|
/OpenTESArena/src/Rendering/RenderShaderUtils.h
|
71157510537eff158c84501e084b820eac6ae065
|
[
"MIT"
] |
permissive
|
afritz1/OpenTESArena
|
f67c4f6ee8981ef3bffbfe5894e2b48d67554475
|
7e91599157e2b9268237b6689f691d29e89b1d74
|
refs/heads/main
| 2023-08-31T09:25:21.908575
| 2023-08-27T01:24:29
| 2023-08-27T01:24:29
| 50,629,945
| 942
| 100
|
MIT
| 2023-08-21T03:42:36
| 2016-01-29T02:07:08
|
C++
|
UTF-8
|
C
| false
| false
| 941
|
h
|
RenderShaderUtils.h
|
#ifndef RENDER_SHADER_UTILS_H
#define RENDER_SHADER_UTILS_H
enum class VertexShaderType
{
Voxel,
SwingingDoor,
SlidingDoor,
RaisingDoor,
SplittingDoor,
Entity
};
enum class PixelShaderType
{
Opaque,
OpaqueWithAlphaTestLayer, // Chasm walls.
AlphaTested,
AlphaTestedWithVariableTexCoordUMin, // Sliding doors.
AlphaTestedWithVariableTexCoordVMin, // Raising doors.
AlphaTestedWithPaletteIndexLookup, // Citizens.
AlphaTestedWithLightLevelColor, // Clouds, distant moons.
AlphaTestedWithLightLevelOpacity, // Ghosts, screen-space fog.
AlphaTestedWithPreviousBrightnessLimit // Stars.
};
enum class TextureSamplingType
{
Default,
ScreenSpaceRepeatY // Chasms.
};
// Unique ID for a light allocated in the renderer's internal format.
using RenderLightID = int;
enum class RenderLightingType
{
PerMesh, // Mesh is uniformly shaded by a single draw call value.
PerPixel // Mesh is shaded by lights in the scene.
};
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.