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
9854e2057499f2a9db2ffc3627c537d62e9f409b
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/mips/alchemy/devboards/db1550.c
016cddacd7ea34bb40717c183d94f12f99b75050
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
15,991
c
db1550.c
/* * Alchemy Db1550/Pb1550 board support * * (c) 2011 Manuel Lauss <manuel.lauss@googlemail.com> */ #include <linux/dma-mapping.h> #include <linux/gpio.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/io.h> #include <linux/interrupt.h> #include <linux/mtd/mtd.h> #include <linux/mtd/nand.h> #include <linux/mtd/partitions.h> #include <linux/platform_device.h> #include <linux/pm.h> #include <linux/spi/spi.h> #include <linux/spi/flash.h> #include <asm/bootinfo.h> #include <asm/mach-au1x00/au1000.h> #include <asm/mach-au1x00/au1xxx_eth.h> #include <asm/mach-au1x00/au1xxx_dbdma.h> #include <asm/mach-au1x00/au1xxx_psc.h> #include <asm/mach-au1x00/au1550_spi.h> #include <asm/mach-au1x00/au1550nd.h> #include <asm/mach-db1x00/bcsr.h> #include <prom.h> #include "platform.h" static void __init db1550_hw_setup(void) { void __iomem *base; /* complete SPI setup: link psc0_intclk to a 48MHz source, * and assign GPIO16 to PSC0_SYNC1 (SPI cs# line) as well as PSC1_SYNC * for AC97 on PB1550. */ base = (void __iomem *)SYS_CLKSRC; __raw_writel(__raw_readl(base) | 0x000001e0, base); base = (void __iomem *)SYS_PINFUNC; __raw_writel(__raw_readl(base) | 1 | SYS_PF_PSC1_S1, base); wmb(); /* reset the AC97 codec now, the reset time in the psc-ac97 driver * is apparently too short although it's ridiculous as it is. */ base = (void __iomem *)KSEG1ADDR(AU1550_PSC1_PHYS_ADDR); __raw_writel(PSC_SEL_CLK_SERCLK | PSC_SEL_PS_AC97MODE, base + PSC_SEL_OFFSET); __raw_writel(PSC_CTRL_DISABLE, base + PSC_CTRL_OFFSET); wmb(); __raw_writel(PSC_AC97RST_RST, base + PSC_AC97RST_OFFSET); wmb(); } int __init db1550_board_setup(void) { unsigned short whoami; bcsr_init(DB1550_BCSR_PHYS_ADDR, DB1550_BCSR_PHYS_ADDR + DB1550_BCSR_HEXLED_OFS); whoami = bcsr_read(BCSR_WHOAMI); /* PB1550 hexled offset differs */ if ((BCSR_WHOAMI_BOARD(whoami) == BCSR_WHOAMI_PB1550_SDR) || (BCSR_WHOAMI_BOARD(whoami) == BCSR_WHOAMI_PB1550_DDR)) bcsr_init(PB1550_BCSR_PHYS_ADDR, PB1550_BCSR_PHYS_ADDR + PB1550_BCSR_HEXLED_OFS); pr_info("Alchemy/AMD %s Board, CPLD Rev %d Board-ID %d " \ "Daughtercard ID %d\n", get_system_type(), (whoami >> 4) & 0xf, (whoami >> 8) & 0xf, whoami & 0xf); db1550_hw_setup(); return 0; } /*****************************************************************************/ static struct mtd_partition db1550_spiflash_parts[] = { { .name = "spi_flash", .offset = 0, .size = MTDPART_SIZ_FULL, }, }; static struct flash_platform_data db1550_spiflash_data = { .name = "s25fl010", .parts = db1550_spiflash_parts, .nr_parts = ARRAY_SIZE(db1550_spiflash_parts), .type = "m25p10", }; static struct spi_board_info db1550_spi_devs[] __initdata = { { /* TI TMP121AIDBVR temp sensor */ .modalias = "tmp121", .max_speed_hz = 2400000, .bus_num = 0, .chip_select = 0, .mode = SPI_MODE_0, }, { /* Spansion S25FL001D0FMA SPI flash */ .modalias = "m25p80", .max_speed_hz = 2400000, .bus_num = 0, .chip_select = 1, .mode = SPI_MODE_0, .platform_data = &db1550_spiflash_data, }, }; static struct i2c_board_info db1550_i2c_devs[] __initdata = { { I2C_BOARD_INFO("24c04", 0x52),}, /* AT24C04-10 I2C eeprom */ { I2C_BOARD_INFO("ne1619", 0x2d),}, /* adm1025-compat hwmon */ { I2C_BOARD_INFO("wm8731", 0x1b),}, /* I2S audio codec WM8731 */ }; /**********************************************************************/ static void au1550_nand_cmd_ctrl(struct mtd_info *mtd, int cmd, unsigned int ctrl) { struct nand_chip *this = mtd->priv; unsigned long ioaddr = (unsigned long)this->IO_ADDR_W; ioaddr &= 0xffffff00; if (ctrl & NAND_CLE) { ioaddr += MEM_STNAND_CMD; } else if (ctrl & NAND_ALE) { ioaddr += MEM_STNAND_ADDR; } else { /* assume we want to r/w real data by default */ ioaddr += MEM_STNAND_DATA; } this->IO_ADDR_R = this->IO_ADDR_W = (void __iomem *)ioaddr; if (cmd != NAND_CMD_NONE) { __raw_writeb(cmd, this->IO_ADDR_W); wmb(); } } static int au1550_nand_device_ready(struct mtd_info *mtd) { return __raw_readl((void __iomem *)MEM_STSTAT) & 1; } static struct mtd_partition db1550_nand_parts[] = { { .name = "NAND FS 0", .offset = 0, .size = 8 * 1024 * 1024, }, { .name = "NAND FS 1", .offset = MTDPART_OFS_APPEND, .size = MTDPART_SIZ_FULL }, }; struct platform_nand_data db1550_nand_platdata = { .chip = { .nr_chips = 1, .chip_offset = 0, .nr_partitions = ARRAY_SIZE(db1550_nand_parts), .partitions = db1550_nand_parts, .chip_delay = 20, }, .ctrl = { .dev_ready = au1550_nand_device_ready, .cmd_ctrl = au1550_nand_cmd_ctrl, }, }; static struct resource db1550_nand_res[] = { [0] = { .start = 0x20000000, .end = 0x200000ff, .flags = IORESOURCE_MEM, }, }; static struct platform_device db1550_nand_dev = { .name = "gen_nand", .num_resources = ARRAY_SIZE(db1550_nand_res), .resource = db1550_nand_res, .id = -1, .dev = { .platform_data = &db1550_nand_platdata, } }; static struct au1550nd_platdata pb1550_nand_pd = { .parts = db1550_nand_parts, .num_parts = ARRAY_SIZE(db1550_nand_parts), .devwidth = 0, /* x8 NAND default, needs fixing up */ }; static struct platform_device pb1550_nand_dev = { .name = "au1550-nand", .id = -1, .resource = db1550_nand_res, .num_resources = ARRAY_SIZE(db1550_nand_res), .dev = { .platform_data = &pb1550_nand_pd, }, }; static void __init pb1550_nand_setup(void) { int boot_swapboot = (au_readl(MEM_STSTAT) & (0x7 << 1)) | ((bcsr_read(BCSR_STATUS) >> 6) & 0x1); gpio_direction_input(206); /* de-assert NAND CS# */ switch (boot_swapboot) { case 0: case 2: case 8: case 0xC: case 0xD: /* x16 NAND Flash */ pb1550_nand_pd.devwidth = 1; /* fallthrough */ case 1: case 3: case 9: case 0xE: case 0xF: /* x8 NAND, already set up */ platform_device_register(&pb1550_nand_dev); } } /**********************************************************************/ static struct resource au1550_psc0_res[] = { [0] = { .start = AU1550_PSC0_PHYS_ADDR, .end = AU1550_PSC0_PHYS_ADDR + 0xfff, .flags = IORESOURCE_MEM, }, [1] = { .start = AU1550_PSC0_INT, .end = AU1550_PSC0_INT, .flags = IORESOURCE_IRQ, }, [2] = { .start = AU1550_DSCR_CMD0_PSC0_TX, .end = AU1550_DSCR_CMD0_PSC0_TX, .flags = IORESOURCE_DMA, }, [3] = { .start = AU1550_DSCR_CMD0_PSC0_RX, .end = AU1550_DSCR_CMD0_PSC0_RX, .flags = IORESOURCE_DMA, }, }; static void db1550_spi_cs_en(struct au1550_spi_info *spi, int cs, int pol) { if (cs) bcsr_mod(BCSR_BOARD, 0, BCSR_BOARD_SPISEL); else bcsr_mod(BCSR_BOARD, BCSR_BOARD_SPISEL, 0); } static struct au1550_spi_info db1550_spi_platdata = { .mainclk_hz = 48000000, /* PSC0 clock: max. 2.4MHz SPI clk */ .num_chipselect = 2, .activate_cs = db1550_spi_cs_en, }; static u64 spi_dmamask = DMA_BIT_MASK(32); static struct platform_device db1550_spi_dev = { .dev = { .dma_mask = &spi_dmamask, .coherent_dma_mask = DMA_BIT_MASK(32), .platform_data = &db1550_spi_platdata, }, .name = "au1550-spi", .id = 0, /* bus number */ .num_resources = ARRAY_SIZE(au1550_psc0_res), .resource = au1550_psc0_res, }; /**********************************************************************/ static struct resource au1550_psc1_res[] = { [0] = { .start = AU1550_PSC1_PHYS_ADDR, .end = AU1550_PSC1_PHYS_ADDR + 0xfff, .flags = IORESOURCE_MEM, }, [1] = { .start = AU1550_PSC1_INT, .end = AU1550_PSC1_INT, .flags = IORESOURCE_IRQ, }, [2] = { .start = AU1550_DSCR_CMD0_PSC1_TX, .end = AU1550_DSCR_CMD0_PSC1_TX, .flags = IORESOURCE_DMA, }, [3] = { .start = AU1550_DSCR_CMD0_PSC1_RX, .end = AU1550_DSCR_CMD0_PSC1_RX, .flags = IORESOURCE_DMA, }, }; static struct platform_device db1550_ac97_dev = { .name = "au1xpsc_ac97", .id = 1, /* PSC ID */ .num_resources = ARRAY_SIZE(au1550_psc1_res), .resource = au1550_psc1_res, }; static struct resource au1550_psc2_res[] = { [0] = { .start = AU1550_PSC2_PHYS_ADDR, .end = AU1550_PSC2_PHYS_ADDR + 0xfff, .flags = IORESOURCE_MEM, }, [1] = { .start = AU1550_PSC2_INT, .end = AU1550_PSC2_INT, .flags = IORESOURCE_IRQ, }, [2] = { .start = AU1550_DSCR_CMD0_PSC2_TX, .end = AU1550_DSCR_CMD0_PSC2_TX, .flags = IORESOURCE_DMA, }, [3] = { .start = AU1550_DSCR_CMD0_PSC2_RX, .end = AU1550_DSCR_CMD0_PSC2_RX, .flags = IORESOURCE_DMA, }, }; static struct platform_device db1550_i2c_dev = { .name = "au1xpsc_smbus", .id = 0, /* bus number */ .num_resources = ARRAY_SIZE(au1550_psc2_res), .resource = au1550_psc2_res, }; /**********************************************************************/ static struct resource au1550_psc3_res[] = { [0] = { .start = AU1550_PSC3_PHYS_ADDR, .end = AU1550_PSC3_PHYS_ADDR + 0xfff, .flags = IORESOURCE_MEM, }, [1] = { .start = AU1550_PSC3_INT, .end = AU1550_PSC3_INT, .flags = IORESOURCE_IRQ, }, [2] = { .start = AU1550_DSCR_CMD0_PSC3_TX, .end = AU1550_DSCR_CMD0_PSC3_TX, .flags = IORESOURCE_DMA, }, [3] = { .start = AU1550_DSCR_CMD0_PSC3_RX, .end = AU1550_DSCR_CMD0_PSC3_RX, .flags = IORESOURCE_DMA, }, }; static struct platform_device db1550_i2s_dev = { .name = "au1xpsc_i2s", .id = 3, /* PSC ID */ .num_resources = ARRAY_SIZE(au1550_psc3_res), .resource = au1550_psc3_res, }; /**********************************************************************/ static struct platform_device db1550_stac_dev = { .name = "ac97-codec", .id = 1, /* on PSC1 */ }; static struct platform_device db1550_ac97dma_dev = { .name = "au1xpsc-pcm", .id = 1, /* on PSC3 */ }; static struct platform_device db1550_i2sdma_dev = { .name = "au1xpsc-pcm", .id = 3, /* on PSC3 */ }; static struct platform_device db1550_sndac97_dev = { .name = "db1550-ac97", }; static struct platform_device db1550_sndi2s_dev = { .name = "db1550-i2s", }; /**********************************************************************/ static int db1550_map_pci_irq(const struct pci_dev *d, u8 slot, u8 pin) { if ((slot < 11) || (slot > 13) || pin == 0) return -1; if (slot == 11) return (pin == 1) ? AU1550_PCI_INTC : 0xff; if (slot == 12) { switch (pin) { case 1: return AU1550_PCI_INTB; case 2: return AU1550_PCI_INTC; case 3: return AU1550_PCI_INTD; case 4: return AU1550_PCI_INTA; } } if (slot == 13) { switch (pin) { case 1: return AU1550_PCI_INTA; case 2: return AU1550_PCI_INTB; case 3: return AU1550_PCI_INTC; case 4: return AU1550_PCI_INTD; } } return -1; } static int pb1550_map_pci_irq(const struct pci_dev *d, u8 slot, u8 pin) { if ((slot < 12) || (slot > 13) || pin == 0) return -1; if (slot == 12) { switch (pin) { case 1: return AU1500_PCI_INTB; case 2: return AU1500_PCI_INTC; case 3: return AU1500_PCI_INTD; case 4: return AU1500_PCI_INTA; } } if (slot == 13) { switch (pin) { case 1: return AU1500_PCI_INTA; case 2: return AU1500_PCI_INTB; case 3: return AU1500_PCI_INTC; case 4: return AU1500_PCI_INTD; } } return -1; } static struct resource alchemy_pci_host_res[] = { [0] = { .start = AU1500_PCI_PHYS_ADDR, .end = AU1500_PCI_PHYS_ADDR + 0xfff, .flags = IORESOURCE_MEM, }, }; static struct alchemy_pci_platdata db1550_pci_pd = { .board_map_irq = db1550_map_pci_irq, }; static struct platform_device db1550_pci_host_dev = { .dev.platform_data = &db1550_pci_pd, .name = "alchemy-pci", .id = 0, .num_resources = ARRAY_SIZE(alchemy_pci_host_res), .resource = alchemy_pci_host_res, }; /**********************************************************************/ static struct platform_device *db1550_devs[] __initdata = { &db1550_i2c_dev, &db1550_ac97_dev, &db1550_spi_dev, &db1550_i2s_dev, &db1550_stac_dev, &db1550_ac97dma_dev, &db1550_i2sdma_dev, &db1550_sndac97_dev, &db1550_sndi2s_dev, }; /* must be arch_initcall; MIPS PCI scans busses in a subsys_initcall */ int __init db1550_pci_setup(int id) { if (id) db1550_pci_pd.board_map_irq = pb1550_map_pci_irq; return platform_device_register(&db1550_pci_host_dev); } static void __init db1550_devices(void) { alchemy_gpio_direction_output(203, 0); /* red led on */ irq_set_irq_type(AU1550_GPIO0_INT, IRQ_TYPE_EDGE_BOTH); /* CD0# */ irq_set_irq_type(AU1550_GPIO1_INT, IRQ_TYPE_EDGE_BOTH); /* CD1# */ irq_set_irq_type(AU1550_GPIO3_INT, IRQ_TYPE_LEVEL_LOW); /* CARD0# */ irq_set_irq_type(AU1550_GPIO5_INT, IRQ_TYPE_LEVEL_LOW); /* CARD1# */ irq_set_irq_type(AU1550_GPIO21_INT, IRQ_TYPE_LEVEL_LOW); /* STSCHG0# */ irq_set_irq_type(AU1550_GPIO22_INT, IRQ_TYPE_LEVEL_LOW); /* STSCHG1# */ db1x_register_pcmcia_socket( AU1000_PCMCIA_ATTR_PHYS_ADDR, AU1000_PCMCIA_ATTR_PHYS_ADDR + 0x000400000 - 1, AU1000_PCMCIA_MEM_PHYS_ADDR, AU1000_PCMCIA_MEM_PHYS_ADDR + 0x000400000 - 1, AU1000_PCMCIA_IO_PHYS_ADDR, AU1000_PCMCIA_IO_PHYS_ADDR + 0x000010000 - 1, AU1550_GPIO3_INT, AU1550_GPIO0_INT, /*AU1550_GPIO21_INT*/0, 0, 0); db1x_register_pcmcia_socket( AU1000_PCMCIA_ATTR_PHYS_ADDR + 0x004000000, AU1000_PCMCIA_ATTR_PHYS_ADDR + 0x004400000 - 1, AU1000_PCMCIA_MEM_PHYS_ADDR + 0x004000000, AU1000_PCMCIA_MEM_PHYS_ADDR + 0x004400000 - 1, AU1000_PCMCIA_IO_PHYS_ADDR + 0x004000000, AU1000_PCMCIA_IO_PHYS_ADDR + 0x004010000 - 1, AU1550_GPIO5_INT, AU1550_GPIO1_INT, /*AU1550_GPIO22_INT*/0, 0, 1); platform_device_register(&db1550_nand_dev); alchemy_gpio_direction_output(202, 0); /* green led on */ } static void __init pb1550_devices(void) { irq_set_irq_type(AU1550_GPIO0_INT, IRQ_TYPE_LEVEL_LOW); irq_set_irq_type(AU1550_GPIO1_INT, IRQ_TYPE_LEVEL_LOW); irq_set_irq_type(AU1550_GPIO201_205_INT, IRQ_TYPE_LEVEL_HIGH); /* enable both PCMCIA card irqs in the shared line */ alchemy_gpio2_enable_int(201); /* socket 0 card irq */ alchemy_gpio2_enable_int(202); /* socket 1 card irq */ /* Pb1550, like all others, also has statuschange irqs; however they're * wired up on one of the Au1550's shared GPIO201_205 line, which also * services the PCMCIA card interrupts. So we ignore statuschange and * use the GPIO201_205 exclusively for card interrupts, since a) pcmcia * drivers are used to shared irqs and b) statuschange isn't really use- * ful anyway. */ db1x_register_pcmcia_socket( AU1000_PCMCIA_ATTR_PHYS_ADDR, AU1000_PCMCIA_ATTR_PHYS_ADDR + 0x000400000 - 1, AU1000_PCMCIA_MEM_PHYS_ADDR, AU1000_PCMCIA_MEM_PHYS_ADDR + 0x000400000 - 1, AU1000_PCMCIA_IO_PHYS_ADDR, AU1000_PCMCIA_IO_PHYS_ADDR + 0x000010000 - 1, AU1550_GPIO201_205_INT, AU1550_GPIO0_INT, 0, 0, 0); db1x_register_pcmcia_socket( AU1000_PCMCIA_ATTR_PHYS_ADDR + 0x008000000, AU1000_PCMCIA_ATTR_PHYS_ADDR + 0x008400000 - 1, AU1000_PCMCIA_MEM_PHYS_ADDR + 0x008000000, AU1000_PCMCIA_MEM_PHYS_ADDR + 0x008400000 - 1, AU1000_PCMCIA_IO_PHYS_ADDR + 0x008000000, AU1000_PCMCIA_IO_PHYS_ADDR + 0x008010000 - 1, AU1550_GPIO201_205_INT, AU1550_GPIO1_INT, 0, 0, 1); pb1550_nand_setup(); } int __init db1550_dev_setup(void) { int swapped, id; id = (BCSR_WHOAMI_BOARD(bcsr_read(BCSR_WHOAMI)) != BCSR_WHOAMI_DB1550); i2c_register_board_info(0, db1550_i2c_devs, ARRAY_SIZE(db1550_i2c_devs)); spi_register_board_info(db1550_spi_devs, ARRAY_SIZE(db1550_i2c_devs)); /* Audio PSC clock is supplied by codecs (PSC1, 3) FIXME: platdata!! */ __raw_writel(PSC_SEL_CLK_SERCLK, (void __iomem *)KSEG1ADDR(AU1550_PSC1_PHYS_ADDR) + PSC_SEL_OFFSET); wmb(); __raw_writel(PSC_SEL_CLK_SERCLK, (void __iomem *)KSEG1ADDR(AU1550_PSC3_PHYS_ADDR) + PSC_SEL_OFFSET); wmb(); /* SPI/I2C use internally supplied 50MHz source */ __raw_writel(PSC_SEL_CLK_INTCLK, (void __iomem *)KSEG1ADDR(AU1550_PSC0_PHYS_ADDR) + PSC_SEL_OFFSET); wmb(); __raw_writel(PSC_SEL_CLK_INTCLK, (void __iomem *)KSEG1ADDR(AU1550_PSC2_PHYS_ADDR) + PSC_SEL_OFFSET); wmb(); id ? pb1550_devices() : db1550_devices(); swapped = bcsr_read(BCSR_STATUS) & (id ? BCSR_STATUS_PB1550_SWAPBOOT : BCSR_STATUS_DB1000_SWAPBOOT); db1x_register_norflash(128 << 20, 4, swapped); return platform_add_devices(db1550_devs, ARRAY_SIZE(db1550_devs)); }
4ea5e9b93ad1c084a84647a1879b7afc82ec9a35
869e1cee7b2d74565848697eec65d28c6219e57d
/src/lib/io.c
2c6d88c74b50f598ae54ae65a2b1aadf96954a51
[ "BSD-2-Clause" ]
permissive
zchunk/zchunk
273b7b9690606cbcae738198ffb0a11418600906
c8538d6ddb1f78a819952b20b9510618b6573192
refs/heads/main
2023-06-14T01:16:16.830200
2023-04-16T13:33:31
2023-04-16T13:33:31
124,198,735
196
41
BSD-2-Clause
2023-04-16T13:33:32
2018-03-07T07:46:20
C
UTF-8
C
false
false
4,321
c
io.c
/* * Copyright 2018 Jonathan Dieter <jdieter@gmail.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <zck.h> #include "zck_private.h" ssize_t read_data(zckCtx *zck, char *data, size_t length) { VALIDATE_READ_INT(zck); if(length == 0) return 0; if(data == NULL) { set_error(zck, "Unable to read to NULL data pointer"); return -1; } ssize_t read_bytes = read(zck->fd, data, length); if(read_bytes == -1) { set_error(zck, "Error reading data: %s", strerror(errno)); return -1; } return read_bytes; } int write_data(zckCtx *zck, int fd, const char *data, size_t length) { VALIDATE_INT(zck); if(length == 0) return true; if(data == NULL) { set_error(zck, "Unable to write from NULL data pointer"); return false; } ssize_t write_bytes = write(fd, data, length); if(write_bytes == -1) { set_fatal_error(zck, "Error writing data: %s", strerror(errno)); return false; } else if(write_bytes < length) { // According to man page, if write is less than full amount, we should try again length -= write_bytes; write_bytes = write(fd, data+write_bytes, length); if(write_bytes == -1) { set_fatal_error(zck, "Error writing data: %s", strerror(errno)); return false; } else if(write_bytes < length) { set_fatal_error(zck, "Short write (after two attempts)"); return false; } } return true; } int seek_data(zckCtx *zck, off_t offset, int whence) { VALIDATE_INT(zck); if(lseek(zck->fd, offset, whence) == -1) { char *wh_str = NULL; if(whence == SEEK_CUR) { wh_str = "from current position"; } else if(whence == SEEK_END) { wh_str = "from end of file"; } else if(whence == SEEK_SET) { wh_str = "from beginning of file"; } else { wh_str = "using unknown measurement"; } set_error( zck, "Unable to seek to %llu %s: %s", (long long unsigned) offset, wh_str, strerror(errno) ); return false; } return true; } ssize_t tell_data(zckCtx *zck) { ssize_t loc = lseek(zck->fd, 0, SEEK_CUR); return loc; } int chunks_from_temp(zckCtx *zck) { int read_count; if(zck->no_write == 1) return true; if(lseek(zck->temp_fd, 0, SEEK_SET) == -1) return false; char *data = zmalloc(BUF_SIZE); if (!data) { zck_log(ZCK_LOG_ERROR, "OOM in %s", __func__); return false; } while((read_count = read(zck->temp_fd, data, BUF_SIZE)) > 0) { if(!write_data(zck, zck->fd, data, read_count)) { free(data); return false; } } free(data); if(read_count == -1) return false; return true; }
24f723d594bdb8c1dddc0c73e690e4b74660b93f
3f55217e912141e04815bc8bcb6fbd5638d0896e
/src/gen/genworm.c
f6595d522fe3fdb674791799bf6aa38f96a9b321
[ "BSD-2-Clause" ]
permissive
NREL/Radiance
bfbb93c99d86368ad0f27052a2a5504aeced47f8
2fcca99ace2f2435f32a09525ad31f2b3be3c1bc
refs/heads/master
2021-12-26T12:42:04.586614
2021-12-18T00:43:56
2021-12-18T00:43:56
8,210,805
164
68
NOASSERTION
2019-06-06T19:57:11
2013-02-15T00:47:56
C
UTF-8
C
false
false
4,082
c
genworm.c
#ifndef lint static const char RCSid[] = "$Id: genworm.c,v 2.12 2019/12/28 18:05:14 greg Exp $"; #endif /* * genworm.c - program to generate worms (strings with varying thickness). * * The program takes as input the functions of t for x, y, * z and r (the radius). Cylinders and cones will be * joined by spheres. Negative radii are forbidden. * * 9/24/87 */ #include <stdlib.h> #include <math.h> #include "calcomp.h" #include "rtio.h" #include "resolu.h" #include "rterror.h" #include "fvect.h" #define XNAME "X`SYS`" /* x function name */ #define YNAME "Y`SYS`" /* y function name */ #define ZNAME "Z`SYS`" /* z function name */ #define RNAME "R`SYS`" /* r function name */ #define PI 3.14159265358979323846 #define max(a,b) ((a) > (b) ? (a) : (b)) /* XXX redundant, move to library */ double l_hermite(char *), l_bezier(char *), l_bspline(char *); int main(argc, argv) int argc; char *argv[]; { char stmp[256]; double t, f, lastr = 0, r; FVECT lastp, p; int i, nseg; esupport |= E_VARIABLE|E_FUNCTION|E_RCONST; esupport &= ~(E_OUTCHAN|E_INCHAN); varset("PI", ':', PI); funset("hermite", 5, ':', l_hermite); funset("bezier", 5, ':', l_bezier); funset("bspline", 5, ':', l_bspline); if (argc < 8) goto userror; for (i = 8; i < argc; i++) if (!strcmp(argv[i], "-e")) scompile(argv[++i], NULL, 0); else if (!strcmp(argv[i], "-f")) { char *fpath = getpath(argv[++i], getrlibpath(), 0); if (fpath == NULL) { fprintf(stderr, "%s: cannot find file '%s'\n", argv[0], argv[i]); quit(1); } fcompile(fpath); } else goto userror; sprintf(stmp, "%s(t)=%s;", XNAME, argv[3]); scompile(stmp, NULL, 0); sprintf(stmp, "%s(t)=%s;", YNAME, argv[4]); scompile(stmp, NULL, 0); sprintf(stmp, "%s(t)=%s;", ZNAME, argv[5]); scompile(stmp, NULL, 0); sprintf(stmp, "%s(t)=%s;", RNAME, argv[6]); scompile(stmp, NULL, 0); nseg = eval(argv[7]) + .5; if (nseg <= 0) goto userror; fputs("# ", stdout); printargs(argc, argv, stdout); eclock = 0; for (i = 0; i <= nseg; i++) { t = (double)i/nseg; p[0] = funvalue(XNAME, 1, &t); p[1] = funvalue(YNAME, 1, &t); p[2] = funvalue(ZNAME, 1, &t); r = funvalue(RNAME, 1, &t); if (i) { if (lastr <= r+FTINY && lastr >= r-FTINY) { printf("\n%s cylinder %s.c%d\n", argv[1], argv[2], i); printf("0\n0\n7\n"); printf("%18.12g %18.12g %18.12g\n", lastp[0], lastp[1], lastp[2]); printf("%18.12g %18.12g %18.12g\n", p[0], p[1], p[2]); printf("%18.12g\n", r); } else { printf("\n%s cone %s.c%d\n", argv[1], argv[2], i); printf("0\n0\n8\n"); f = (lastr - r)/dist2(lastp,p); printf("%18.12g %18.12g %18.12g\n", lastp[0] + f*lastr*(p[0] - lastp[0]), lastp[1] + f*lastr*(p[1] - lastp[1]), lastp[2] + f*lastr*(p[2] - lastp[2])); printf("%18.12g %18.12g %18.12g\n", p[0] + f*r*(p[0] - lastp[0]), p[1] + f*r*(p[1] - lastp[1]), p[2] + f*r*(p[2] - lastp[2])); f = 1.0 - (lastr-r)*f; f = f <= 0.0 ? 0.0 : sqrt(f); printf("%18.12g %18.12g\n", f*lastr, f*r); } } printf("\n%s sphere %s.s%d\n", argv[1], argv[2], i); printf("0\n0\n4 %18.12g %18.12g %18.12g %18.12g\n", p[0], p[1], p[2], r); VCOPY(lastp, p); lastr = r; } return 0; userror: fprintf(stderr, "Usage: %s material name x(t) y(t) z(t) r(t) nseg [-e expr] [-f file]\n", argv[0]); return 1; } double l_hermite(char *nm) { double t; t = argument(5); return( argument(1)*((2.0*t-3.0)*t*t+1.0) + argument(2)*(-2.0*t+3.0)*t*t + argument(3)*((t-2.0)*t+1.0)*t + argument(4)*(t-1.0)*t*t ); } double l_bezier(char *nm) { double t; t = argument(5); return( argument(1) * (1.+t*(-3.+t*(3.-t))) + argument(2) * 3.*t*(1.+t*(-2.+t)) + argument(3) * 3.*t*t*(1.-t) + argument(4) * t*t*t ); } double l_bspline(char *nm) { double t; t = argument(5); return( argument(1) * (1./6.+t*(-1./2.+t*(1./2.-1./6.*t))) + argument(2) * (2./3.+t*t*(-1.+1./2.*t)) + argument(3) * (1./6.+t*(1./2.+t*(1./2.-1./2.*t))) + argument(4) * (1./6.*t*t*t) ); }
bdea1af098c29b5b071007c8db45fb6494f23b42
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/mips/mm/tlb-r8k.c
91c2499f806a25809259a0b9682667ce2d7f31d5
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
5,474
c
tlb-r8k.c
/* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 1996 David S. Miller (davem@davemloft.net) * Copyright (C) 1997, 1998, 1999, 2000 Ralf Baechle ralf@gnu.org * Carsten Langgaard, carstenl@mips.com * Copyright (C) 2002 MIPS Technologies, Inc. All rights reserved. */ #include <linux/init.h> #include <linux/sched.h> #include <linux/smp.h> #include <linux/mm.h> #include <asm/cpu.h> #include <asm/bootinfo.h> #include <asm/mmu_context.h> #include <asm/pgtable.h> extern void build_tlb_refill_handler(void); #define TFP_TLB_SIZE 384 #define TFP_TLB_SET_SHIFT 7 /* CP0 hazard avoidance. */ #define BARRIER __asm__ __volatile__(".set noreorder\n\t" \ "nop; nop; nop; nop; nop; nop;\n\t" \ ".set reorder\n\t") void local_flush_tlb_all(void) { unsigned long flags; unsigned long old_ctx; int entry; local_irq_save(flags); /* Save old context and create impossible VPN2 value */ old_ctx = read_c0_entryhi(); write_c0_entrylo(0); for (entry = 0; entry < TFP_TLB_SIZE; entry++) { write_c0_tlbset(entry >> TFP_TLB_SET_SHIFT); write_c0_vaddr(entry << PAGE_SHIFT); write_c0_entryhi(CKSEG0 + (entry << (PAGE_SHIFT + 1))); mtc0_tlbw_hazard(); tlb_write(); } tlbw_use_hazard(); write_c0_entryhi(old_ctx); local_irq_restore(flags); } void local_flush_tlb_mm(struct mm_struct *mm) { int cpu = smp_processor_id(); if (cpu_context(cpu, mm) != 0) drop_mmu_context(mm, cpu); } void local_flush_tlb_range(struct vm_area_struct *vma, unsigned long start, unsigned long end) { struct mm_struct *mm = vma->vm_mm; int cpu = smp_processor_id(); unsigned long flags; int oldpid, newpid, size; if (!cpu_context(cpu, mm)) return; size = (end - start + (PAGE_SIZE - 1)) >> PAGE_SHIFT; size = (size + 1) >> 1; local_irq_save(flags); if (size > TFP_TLB_SIZE / 2) { drop_mmu_context(mm, cpu); goto out_restore; } oldpid = read_c0_entryhi(); newpid = cpu_asid(cpu, mm); write_c0_entrylo(0); start &= PAGE_MASK; end += (PAGE_SIZE - 1); end &= PAGE_MASK; while (start < end) { signed long idx; write_c0_vaddr(start); write_c0_entryhi(start); start += PAGE_SIZE; tlb_probe(); idx = read_c0_tlbset(); if (idx < 0) continue; write_c0_entryhi(CKSEG0 + (idx << (PAGE_SHIFT + 1))); tlb_write(); } write_c0_entryhi(oldpid); out_restore: local_irq_restore(flags); } /* Usable for KV1 addresses only! */ void local_flush_tlb_kernel_range(unsigned long start, unsigned long end) { unsigned long size, flags; size = (end - start + (PAGE_SIZE - 1)) >> PAGE_SHIFT; size = (size + 1) >> 1; if (size > TFP_TLB_SIZE / 2) { local_flush_tlb_all(); return; } local_irq_save(flags); write_c0_entrylo(0); start &= PAGE_MASK; end += (PAGE_SIZE - 1); end &= PAGE_MASK; while (start < end) { signed long idx; write_c0_vaddr(start); write_c0_entryhi(start); start += PAGE_SIZE; tlb_probe(); idx = read_c0_tlbset(); if (idx < 0) continue; write_c0_entryhi(CKSEG0 + (idx << (PAGE_SHIFT + 1))); tlb_write(); } local_irq_restore(flags); } void local_flush_tlb_page(struct vm_area_struct *vma, unsigned long page) { int cpu = smp_processor_id(); unsigned long flags; int oldpid, newpid; signed long idx; if (!cpu_context(cpu, vma->vm_mm)) return; newpid = cpu_asid(cpu, vma->vm_mm); page &= PAGE_MASK; local_irq_save(flags); oldpid = read_c0_entryhi(); write_c0_vaddr(page); write_c0_entryhi(newpid); tlb_probe(); idx = read_c0_tlbset(); if (idx < 0) goto finish; write_c0_entrylo(0); write_c0_entryhi(CKSEG0 + (idx << (PAGE_SHIFT + 1))); tlb_write(); finish: write_c0_entryhi(oldpid); local_irq_restore(flags); } /* * We will need multiple versions of update_mmu_cache(), one that just * updates the TLB with the new pte(s), and another which also checks * for the R4k "end of page" hardware bug and does the needy. */ void __update_tlb(struct vm_area_struct * vma, unsigned long address, pte_t pte) { unsigned long flags; pgd_t *pgdp; pmd_t *pmdp; pte_t *ptep; int pid; /* * Handle debugger faulting in for debugee. */ if (current->active_mm != vma->vm_mm) return; pid = read_c0_entryhi() & ASID_MASK; local_irq_save(flags); address &= PAGE_MASK; write_c0_vaddr(address); write_c0_entryhi(pid); pgdp = pgd_offset(vma->vm_mm, address); pmdp = pmd_offset(pgdp, address); ptep = pte_offset_map(pmdp, address); tlb_probe(); write_c0_entrylo(pte_val(*ptep++) >> 6); tlb_write(); write_c0_entryhi(pid); local_irq_restore(flags); } static void __cpuinit probe_tlb(unsigned long config) { struct cpuinfo_mips *c = &current_cpu_data; c->tlbsize = 3 * 128; /* 3 sets each 128 entries */ } void __cpuinit tlb_init(void) { unsigned int config = read_c0_config(); unsigned long status; probe_tlb(config); status = read_c0_status(); status &= ~(ST0_UPS | ST0_KPS); #ifdef CONFIG_PAGE_SIZE_4KB status |= (TFP_PAGESIZE_4K << 32) | (TFP_PAGESIZE_4K << 36); #elif defined(CONFIG_PAGE_SIZE_8KB) status |= (TFP_PAGESIZE_8K << 32) | (TFP_PAGESIZE_8K << 36); #elif defined(CONFIG_PAGE_SIZE_16KB) status |= (TFP_PAGESIZE_16K << 32) | (TFP_PAGESIZE_16K << 36); #elif defined(CONFIG_PAGE_SIZE_64KB) status |= (TFP_PAGESIZE_64K << 32) | (TFP_PAGESIZE_64K << 36); #endif write_c0_status(status); write_c0_wired(0); local_flush_tlb_all(); build_tlb_refill_handler(); }
3c1f678f73cb1725b4c55155ebf3b6e6b05d3d03
3859ab0e52eb8df571de99c911b91df7628434a2
/parser/include/bearparser/bearparser.h
e25b68e0bb53525b36a2f616d601dab59084c45d
[ "BSD-2-Clause" ]
permissive
hasherezade/bearparser
ae182a3964cd09add079a7cc8447b97fac02bd84
65d6417b1283eb64237141ee0c865bdf0f13ac73
refs/heads/master
2023-08-15T11:11:04.586123
2023-06-12T01:07:46
2023-06-12T01:07:46
23,022,106
608
120
BSD-2-Clause
2023-03-07T14:22:01
2014-08-16T16:27:14
C++
UTF-8
C
false
false
157
h
bearparser.h
#ifndef BEARPARSER_H #define BEARPARSER_H #define BEARPARSER_VERSION "0.3" #include <bearparser/core.h> #include <bearparser/pe.h> #endif //BEARPARSER_H
6b45b54d354c9b48d96c3b98b372832cbf71d537
66f993723f09163d2ebfcc93b6b803238af841ff
/av1/encoder/arm/neon/dct_neon.c
f6ce24a3ddbf510a825d737be0f832ac12dbcded
[ "BSD-2-Clause" ]
permissive
mozilla/aom
e83efb7a6409048a2c6d87c1c2a10016c1c8c55f
46b7bb243b39929c02d6decc1bdb2e39e11540d6
refs/heads/master
2023-07-04T02:23:11.547136
2019-04-01T03:33:42
2019-04-01T03:33:42
96,821,694
160
36
NOASSERTION
2019-04-01T03:33:43
2017-07-10T21:11:39
C
UTF-8
C
false
false
1,581
c
dct_neon.c
/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include <arm_neon.h> #include "./av1_rtcd.h" #include "./aom_config.h" #include "./aom_dsp_rtcd.h" #include "av1/common/blockd.h" #include "aom_dsp/txfm_common.h" void av1_fdct8x8_quant_neon(const int16_t *input, int stride, int16_t *coeff_ptr, intptr_t n_coeffs, int skip_block, const int16_t *zbin_ptr, const int16_t *round_ptr, const int16_t *quant_ptr, const int16_t *quant_shift_ptr, int16_t *qcoeff_ptr, int16_t *dqcoeff_ptr, const int16_t *dequant_ptr, uint16_t *eob_ptr, const int16_t *scan_ptr, const int16_t *iscan_ptr) { int16_t temp_buffer[64]; (void)coeff_ptr; aom_fdct8x8_neon(input, temp_buffer, stride); av1_quantize_fp_neon(temp_buffer, n_coeffs, skip_block, zbin_ptr, round_ptr, quant_ptr, quant_shift_ptr, qcoeff_ptr, dqcoeff_ptr, dequant_ptr, eob_ptr, scan_ptr, iscan_ptr); }
0fc40bd164a7bfa825c48d87fa6336a8bb87bf17
030d0641553fe32c41dc302cd191dd63466a4eb9
/src/logit.c
65dd8c7bc5a292a911cbbdaf79182b1ac268603d
[ "MIT" ]
permissive
troglobit/finit
0e03c0a37af5568baab2484b5203ff104dbaa4af
a58002588eb30b5ac595a0d6f8902f4abffc1b5c
refs/heads/master
2023-08-03T04:18:53.053351
2023-07-30T07:56:30
2023-07-30T08:09:34
5,778,132
605
69
MIT
2023-02-06T15:13:14
2012-09-12T10:07:53
C
UTF-8
C
false
false
5,115
c
logit.c
/* * Copyright (c) 2018-2023 Joachim Wiberg <troglobit@gmail.com> * * 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 <errno.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define SYSLOG_NAMES #include <syslog.h> #include <unistd.h> #include <sys/stat.h> #ifdef _LIBITE_LITE # include <libite/lite.h> #else # include <lite/lite.h> #endif static const char version_info[] = PACKAGE_NAME " v" PACKAGE_VERSION; extern int logrotate(char *file, int num, off_t sz); static int checksz(FILE *fp, off_t sz) { struct stat st; if (sz <= 0) return 0; if (!fstat(fileno(fp), &st) && st.st_size > sz) { fclose(fp); return 1; } return 0; } static int flogit(char *logfile, int num, off_t sz, char *buf, size_t len) { FILE *fp; reopen: fp = fopen(logfile, "a"); if (!fp) { syslog(LOG_ERR | LOG_PERROR, "Failed opening %s: %s", logfile, strerror(errno)); return 1; } if (buf[0]) { fprintf(fp, "%s\n", buf); fsync(fileno(fp)); if (checksz(fp, sz)) return logrotate(logfile, num, sz); } else { while ((fgets(buf, len, stdin))) { fputs(buf, fp); fsync(fileno(fp)); if (checksz(fp, sz)) { logrotate(logfile, num, sz); buf[0] = 0; goto reopen; } } } return fclose(fp); } static int logit(int level, char *buf, size_t len) { if (buf[0]) { syslog(level, "%s", buf); return 0; } while ((fgets(buf, len, stdin))) syslog(level, "%s", buf); return 0; } static int parse_prio(char *arg, int *f, int *l) { char *duparg = strdup(arg); char *ptr, *prio; if (!duparg) prio = arg; else prio = duparg; ptr = strchr(prio, '.'); if (ptr) { *ptr++ = 0; for (int i = 0; facilitynames[i].c_name; i++) { if (!strcmp(facilitynames[i].c_name, prio)) { *f = facilitynames[i].c_val; break; } } prio = ptr; } for (int i = 0; prioritynames[i].c_name; i++) { if (!strcmp(prioritynames[i].c_name, prio)) { *l = prioritynames[i].c_val; break; } } if (duparg != arg) free(duparg); return 0; } static int usage(int code) { fprintf(stderr, "Usage: logit [OPTIONS] [MESSAGE]\n" "\n" "Write MESSAGE (or stdin) to syslog, or file (with logrotate)\n" "\n" " -h This help text\n" " -p PRIO Priority (numeric or facility.level pair)\n" " -t TAG Log using the specified tag (defaults to user name)\n" " -s Log to stderr as well as the system log\n" "\n" " -f FILE File to write log messages to, instead of syslog\n" " -n SIZE Number of bytes before rotating, default: 200 kB\n" " -r NUM Number of rotated files to keep, default: 5\n" " -v Show program version\n" "\n" "This version of logit is distributed as part of Finit.\n" "Bug report address: %s\n", PACKAGE_BUGREPORT); return code; } int main(int argc, char *argv[]) { int c, rc, num = 5; int facility = LOG_USER; int level = LOG_INFO; int log_opts = LOG_NOWAIT; off_t size = 200 * 1024; char *ident = NULL, *logfile = NULL; char buf[512] = ""; while ((c = getopt(argc, argv, "f:hn:p:r:st:v")) != EOF) { switch (c) { case 'f': logfile = optarg; break; case 'h': return usage(0); case 'n': size = atoi(optarg); break; case 'p': if (parse_prio(optarg, &facility, &level)) return usage(1); break; case 'r': num = atoi(optarg); break; case 's': log_opts |= LOG_PERROR; break; case 't': ident = optarg; break; case 'v': /* version */ fprintf(stderr, "%s\n", version_info); return 0; default: return usage(1); } } if (!ident) { ident = getenv("LOGNAME"); if (!ident) ident = getenv("USER"); if (!ident) ident = PACKAGE_NAME; } if (optind < argc) { size_t pos = 0, len = sizeof(buf); while (optind < argc) { size_t bytes; bytes = snprintf(&buf[pos], len, "%s ", argv[optind++]); pos += bytes; len -= bytes; } } openlog(ident, log_opts, facility); if (logfile) rc = flogit(logfile, num, size, buf, sizeof(buf)); else rc = logit(level, buf, sizeof(buf)); closelog(); return rc; }
29e9b3ff822bf05d75c9f0df295d53cf90e2a7db
76d055f9836055eb91fc8f224f56fab1aea47b0a
/Pods/Headers/Private/KMCGeigerCounter/KMCGeigerCounter.h
724485f25b934f11a4a7f6995b3064912a6fec01
[ "MIT" ]
permissive
tianliangyihou/LBPhotoBrowser
3982bea24eee2cc28fdf56d5f398ebad1c23a690
eab0aaa911290d4f7cbf973b33e37112e5e0f859
refs/heads/master
2021-01-23T04:29:49.128417
2019-04-24T06:54:05
2019-04-24T06:54:05
102,447,408
436
59
null
null
null
null
UTF-8
C
false
false
61
h
KMCGeigerCounter.h
../../../KMCGeigerCounter/KMCGeigerCounter/KMCGeigerCounter.h
455abf16849305d5d58d305ed1cc938df34bbf1e
e683a0b8dbb87c7ceb99e0d06896174a559d2c67
/Library/JS/srccore/jselib.c
71e85d777a760ca6e457f3a84751e53a6efac9a7
[ "Apache-2.0" ]
permissive
bluewaysw/pcgeos
f093d79567d977d992f47065056d14d5a04b9f14
c6ae4c8e77b54b9ff654c3916f2191f8b1a1b65d
refs/heads/master
2023-08-31T00:17:54.481175
2023-08-29T19:00:49
2023-08-29T19:00:49
157,968,410
603
88
Apache-2.0
2023-09-13T07:44:06
2018-11-17T09:09:55
Assembly
UTF-8
C
false
false
90,597
c
jselib.c
/* jselib.c ISDK API interface functions */ /* (c) COPYRIGHT 1993-2000 NOMBAS, INC. * 64 SALEM ST. * MEDFORD, MA 02155 USA * * ALL RIGHTS RESERVED * * This software is the property of Nombas, Inc. and is furnished under * license by Nombas, Inc.; this software may be used only in accordance * with the terms of said license. This copyright notice may not be removed, * modified or obliterated without the prior written permission of Nombas, Inc. * * This software is a Trade Secret of Nombas, Inc. * * This software may not be copied, transmitted, provided to or otherwise made * available to any other person, company, corporation or other entity except * as specified in the terms of said license. * * No right, title, ownership or other interest in the software is hereby * granted or transferred. * * The information contained herein is subject to change without notice and * should not be construed as a commitment by Nombas, Inc. */ #include "srccore.h" #if defined(__JSE_GEOS__) #include <Ansi/stdio.h> #elif !defined(__JSE_WINCE__) && !defined(__JSE_IOS__) #include <stdio.h> #endif /* Cleanup all remaining API variable structures. If we are in * debug mode, also report any unfreed variables as errors. */ void seapiCleanup(struct Call *call) { uint i; seAPIVar vars = call->Global->APIVars; # if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 jsebool bad = FALSE; # endif call->Global->APIVars = NULL; /* since we are freeing them */ while( vars!=NULL ) { seAPIVar nxt = vars->next; #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 if( vars->shouldBeFreed && !vars->alreadyFreed ) { DebugPrintf(UNISTR("A variable that you received from the API using one of\n")); DebugPrintf(UNISTR("the functions that returns a variable you must free was\n")); DebugPrintf(UNISTR("never freed. This variable must be freed before you exit.\n")); DebugPrintf(UNISTR("Don't blindly 'jseDestroyVariable()' it - make sure first\n")); DebugPrintf(UNISTR("you have not made a mistake elsewhere in your code where\n")); DebugPrintf(UNISTR("you thought you had freed it. This variable was returned\n")); DebugPrintf(UNISTR("from the ScriptEase API to your code at:\n")); DebugPrintf(UNISTR(" File: %s, Line %d by function %s.\n\n"), vars->file,vars->line,vars->function); bad = TRUE; } jseMustFree(vars->function); jseMustFree(vars->file); #endif # if JSE_MEMEXT_STRINGS==1 if( vars->data ) SEVAR_FREE_DATA(call,vars->data); # endif jseMustFree(vars); vars = nxt; } # if 0==JSE_DONT_POOL for( i=0;i<call->Global->api_pool_count;i++ ) { jseMustFree(call->Global->api_pool[i]); } # endif #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 if( bad ) { #ifdef __JSE_GEOS__ DebugPrintf(UNISTR("Some variables were not freed, see C:\\JseDebug.log for details.\n")); FatalError(-1); #else fprintf_jsechar(stderr,UNISTR("Some variables were not freed, see C:\\JseDebug.log for details.\n")); exit(1); #endif } #endif } #if !defined(NDEBUG) && JSE_TRACKVARS==1 static JSE_POINTER_UINT computeChecksum(seAPIVar var) { /* A simple algorithm, but we don't expect anyone to be trying to * 'trick' us, so it will work fine. */ /* ignore the next and prev because they change */ return (JSE_POINTER_UINT)(var->function)+ (JSE_POINTER_UINT)(var->file)+ (JSE_POINTER_UINT)(var->line); } static void NEAR_CALL trackvar_check(seAPIVar var) { JSE_POINTER_UINT checksum; checksum = computeChecksum(var); if( checksum!=var->checksum ) { DebugPrintf(UNISTR("Variable passed to API function is not a valid variable.\n")); DebugPrintf(UNISTR("Likely cause is that you have already freed the variable or\n")); DebugPrintf(UNISTR("passed it to an API function in a way that implicitly frees\n")); DebugPrintf(UNISTR("it, such as passing it to jseReturnVar() with the flag set\n")); DebugPrintf(UNISTR("to jseRetTempVar.\n")); #ifdef __JSE_GEOS__ DebugPrintf(UNISTR("Invalid variable error, check C:\\JseDebug.log for details.\n")); FatalError(-1); #else fprintf_jsechar(stderr,UNISTR("Invalid variable error, check C:\\JseDebug.log for details.\n")); exit(1); #endif } if( var->alreadyFreed ) { DebugPrintf(UNISTR("Variable passed to API function is no longer valid. Many\n")); DebugPrintf(UNISTR("API functions do not force you to free the returned variable.\n")); DebugPrintf(UNISTR("Such variables are only valid until the wrapper function\n")); DebugPrintf(UNISTR("that allocated it exits. If you need to retain such a variable\n")); DebugPrintf(UNISTR("use 'jseCreateSiblingVariable()'. This variable was returned\n")); DebugPrintf(UNISTR("from the ScriptEase API to your code at:\n")); DebugPrintf(UNISTR(" File: %s, Line %d by function %s.\n\n"), var->file,var->line,var->function); #ifdef __JSE_GEOS__ DebugPrintf(UNISTR("Variable no longer valid error, check C:\\JseDebug.log for details.\n")); FatalError(-1); #else fprintf_jsechar(stderr,UNISTR("Variable no longer valid error, check C:\\JseDebug.log for details.\n")); exit(1); #endif } } #endif /* First, validate the given variable, and report any appropriate errors. * This includes in TRACKVAR builds making sure reading to it is allowed. * Then get the readable contents to an internal buffer. Return the internal * buffer. Note that this is reentrant as long as you don't expect the * buffer to 'hang around'. */ wSEVar seapiGetValue(struct Call *call,seAPIVar var) { if( var==NULL ) return NULL; # if ( 0 < JSE_API_ASSERTLEVEL ) if( var->cookie!=APIVAR_COOKIE ) { #if !defined(NDEBUG) && JSE_TRACKVARS==1 DebugPrintf(UNISTR("Variable passed to API function is not a valid variable.\n")); DebugPrintf(UNISTR("This has been triggered because the variable does not\n")); DebugPrintf(UNISTR("have a valid cookie. Likely cause is passing a garbage\n")); DebugPrintf(UNISTR("pointer to the function. Because this pointer is not one\n")); DebugPrintf(UNISTR("recognized, we can give no further information on it.\n")); fprintf_jsechar(stderr,UNISTR("Invalid variable error, check C:\\JseDebug.log for details.\n")); #endif exit(1); } # endif #if !defined(NDEBUG) && JSE_TRACKVARS==1 trackvar_check(var); #endif if( SEVAR_GET_TYPE(&(var->value))<VReference ) { return &(var->value); } else { SEVAR_COPY(&(var->last_access),&(var->value)); SEVAR_DEREFERENCE(call,&(var->last_access)); return &(var->last_access); } } /* Update the given API variable to have the given new value. Usually, * this is simply a copy to the api var's internal 'seVar' structure, * but if this is a reference, we must put the value in the given * structure member, doing a dynamic put if necessary. */ static void NEAR_CALL seapiPutValue(struct Call *call,seAPIVar var,wSEVar from) { # if ( 0 < JSE_API_ASSERTLEVEL ) if( var->cookie!=APIVAR_COOKIE ) { #if !defined(NDEBUG) && JSE_TRACKVARS==1 DebugPrintf(UNISTR("Variable passed to API function is not a valid variable.\n")); DebugPrintf(UNISTR("This has been triggered because the variable does not\n")); DebugPrintf(UNISTR("have a valid cookie. Likely cause is passing a garbage\n")); DebugPrintf(UNISTR("pointer to the function. Because this pointer is not one\n")); DebugPrintf(UNISTR("recognized, we can give no further information on it.\n")); fprintf_jsechar(stderr,UNISTR("Invalid variable error, check C:\\JseDebug.log for details.\n")); #endif exit(1); } # endif #if !defined(NDEBUG) && JSE_TRACKVARS==1 trackvar_check(var); #endif SEVAR_DO_PUT(call,&(var->value),from); } void NEAR_CALL seapiDeleteVariable(struct Call *call,seAPIVar var) { #if !defined(NDEBUG) && JSE_TRACKVARS==1 JSE_POINTER_UINT checksum = computeChecksum(var); if( checksum!=var->checksum ) { DebugPrintf(UNISTR("Variable passed to API function is not a valid variable.\n")); DebugPrintf(UNISTR("Likely cause is that you have already freed the variable or\n")); DebugPrintf(UNISTR("passed it to an API function in a way that implicitly frees\n")); DebugPrintf(UNISTR("it, such as passing it to jseReturnVar() with the flag set\n")); DebugPrintf(UNISTR("to jseRetTempVar.\n")); #ifdef __JSE_GEOS__ DebugPrintf(UNISTR("Invalid variable error, check C:\\JseDebug.log for details.\n")); FatalError(-1); #else fprintf_jsechar(stderr,UNISTR("Invalid variable error, check C:\\JseDebug.log for details.\n")); exit(1); #endif } if( var->alreadyFreed ) { DebugPrintf(UNISTR("Variable passed to API function is no longer valid. Many\n")); DebugPrintf(UNISTR("API functions do not force you to free the returned variable.\n")); DebugPrintf(UNISTR("Such variables are only valid until the wrapper function\n")); DebugPrintf(UNISTR("that allocated it exits. If you need to retain such a variable\n")); DebugPrintf(UNISTR("use 'jseCreateSiblingVariable()'. This variable was returned\n")); DebugPrintf(UNISTR("from the ScriptEase API to your code at:\n")); DebugPrintf(UNISTR(" File: %s, Line %d by function %s.\n\n"), var->file,var->line,var->function); #ifdef __JSE_GEOS__ DebugPrintf(UNISTR("Variable no longer valid error, check C:\\JseDebug.log for details.\n")); FatalError(-1); #else fprintf_jsechar(stderr,UNISTR("Variable no longer valid error, check C:\\JseDebug.log for details.\n")); exit(1); #endif } if( !var->shouldBeFreed ) { DebugPrintf(UNISTR("You are trying to delete a variable that is not supposed to be\n")); DebugPrintf(UNISTR("freed. This can also happen if you pass a variable that implicitly\n")); DebugPrintf(UNISTR("deletes the variable (such as jseReturnVar() with jseRetTempVar\n")); DebugPrintf(UNISTR("This variable was returned to you by an API function which doesn't\n")); DebugPrintf(UNISTR("gibe you a variable to be freed. This variable was returned\n")); DebugPrintf(UNISTR("from the ScriptEase API to your code at:\n")); DebugPrintf(UNISTR(" File: %s, Line %d by function %s.\n\n"), var->file,var->line,var->function); #ifdef __JSE_GEOS__ DebugPrintf(UNISTR("Variable freed that shouldn't be, check C:\\JseDebug.log for details.\n")); FatalError(-1); #else fprintf_jsechar(stderr,UNISTR("Variable freed that shouldn't be, check C:\\JseDebug.log for details.\n")); exit(1); #endif } #else /* mgroeber: I prefer these to be fatals... */ assert( !var->alreadyFreed ); assert( var->shouldBeFreed ); if( var->alreadyFreed || !var->shouldBeFreed ) return; #endif var->alreadyFreed = True; if( var->prev==NULL ) { call->Global->APIVars = var->next; } else { var->prev->next = var->next; } if( var->next!=NULL ) var->next->prev = var->prev; # if JSE_MEMEXT_STRINGS==1 if( var->data ) SEVAR_FREE_DATA(call,var->data); # endif #if !defined(NDEBUG) && JSE_TRACKVARS==1 jseMustFree(var->function); jseMustFree(var->file); #endif # if 0==JSE_DONT_POOL if( call->Global->api_pool_count<API_VAR_POOL_SIZE ) call->Global->api_pool[call->Global->api_pool_count++] = var; else # endif jseMustFree(var); } /* Package a real variable for returning. Allocates a new seAPIVar, locks * it in, copies the given variable's contents to it, and fills in all * the fields. */ seAPIVar seapiCopyAndReturn(struct Call *call,rSEVar realvar, jsebool api_lock #if !defined(NDEBUG) && JSE_TRACKVARS==1 /* NOT jsechar, these are generated by __FILE__, which * appear to always be char strings. */ ,jsecharptr apiname,char *file,uint line #endif ) { seAPIVar ret; if( realvar==NULL ) return NULL; # if 0==JSE_DONT_POOL if( call->Global->api_pool_count ) { ret = call->Global->api_pool[--(call->Global->api_pool_count)]; } else # endif { ret = jseMustMalloc(struct seAPIVar,sizeof(struct seAPIVar)); } ret->prev = NULL; if( api_lock ) { if( call->Global->APIVars!=NULL ) call->Global->APIVars->prev = ret; ret->next = call->Global->APIVars; call->Global->APIVars = ret; } else { if( call->tempvars!=NULL ) call->tempvars->prev = ret; ret->next = call->tempvars; call->tempvars = ret; } /* mgroeber: catch code that creates infinite tempvar loops */ assert( ret->next!=ret ); # if JSE_MEMEXT_STRINGS==1 ret->data = NULL; # endif #if !defined(NDEBUG) && JSE_TRACKVARS==1 #if (!defined(JSE_UNICODE) || (0==JSE_UNICODE)) ret->file = StrCpyMalloc(file); /* it is a null-terminated MBCS string, can be copied just * like a regular one. */ ret->function = StrCpyMalloc((char *)apiname); #else { size_t nameLen = strlen(file); ret->file = jseMustMalloc(char,nameLen+1); memcpy(ret->file,file,nameLen+1); nameLen = strlen_jsechar(apiname); ret->function = jseMustMalloc(char,nameLen+1); memcpy(ret->function,apiname,nameLen+1); } #endif ret->line = line; ret->checksum = computeChecksum(ret); #endif ret->shouldBeFreed = api_lock; ret->alreadyFreed = False; # if ( 0 < JSE_API_ASSERTLEVEL ) ret->cookie = APIVAR_COOKIE; # endif SEVAR_COPY(&(ret->value),realvar); SEVAR_INIT_UNDEFINED(&(ret->last_access)); return ret; } /* ---------------------------------------------------------------------- */ JSECALLSEQ( void ) jseLibSetExitFlag(jseContext call,jseVariable variable) { wSEVar loc = STACK_PUSH; JSE_API_STRING(ThisFuncName,"jseLibSetExitFlag"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); if( variable!=NULL ) { /* since the seapiGetValue is called first, and can collect, * we need protection. */ SEVAR_INIT_UNDEFINED(loc); SEVAR_COPY(loc,seapiGetValue(call,variable)); } else { SEVAR_INIT_SLONG(loc,EXIT_SUCCESS); } CALL_SET_ERROR(call,FlowExit); } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jseContext ) jseReallyInterpInit(jseContext call, const jsecharptr SourceFile, const jsecharptr SourceText, const void * PreTokenizedSource, jseNewContextSettings NewContextSettings, int howToInterpret, jseVariable *retvar, char *FILE, int LINE ) #else JSECALLSEQ( jseContext ) jseInterpInit(jseContext call, const jsecharptr SourceFile, const jsecharptr SourceText, const void * PreTokenizedSource, jseNewContextSettings NewContextSettings, int howToInterpret, jseContext unused_parameter, jseVariable *retvar ) #endif { jseContext ret; # if defined(NDEBUG) || !defined(JSE_TRACKVARS) || JSE_TRACKVARS==0 UNUSED_PARAMETER(unused_parameter); # endif assert( call->next==NULL ); if( retvar ) *retvar = NULL; JSE_API_ASSERT_C(call,1,jseContext_cookie,UNISTR("jseInterpInit"),return NULL); CALL_SET_ERROR(call,FlowNoReasonToQuit); ret = interpretInit(call,SourceFile,SourceText,PreTokenizedSource, NewContextSettings,howToInterpret); if( ret==NULL ) { rSEVar err = &(call->error_var); if( (howToInterpret & JSE_INTERPRET_TRAP_ERRORS)!=0 && retvar!=NULL ) { /* In this case, the error is propogated up into our call */ *retvar = SEAPI_RETURN(call,err,TRUE,UNISTR("jseInterpInit")); } else { /* error already printed */ CALL_SET_ERROR(call,FlowNoReasonToQuit); } STACK_POP; } return ret; } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jseVariable ) jseReallyInterpTerm(jseContext call,jsebool traperrors,char *FILE,int LINE) #else JSECALLSEQ( jseVariable ) jseInterpTerm(jseContext call,jsebool traperrors) #endif { jseVariable ret; jsebool error; rSEVar tmp; jsebool disregard = False; JSE_API_ASSERT_C(call,1,jseContext_cookie,UNISTR("jseInterpTerm"),return NULL); /* Some people may mistakenly pass the higher level context in, * we allow that. */ if( call->next ) call = call->next; /* If there is any more, they have just plain passed the wrong context */ assert( call->next==NULL ); /* If not a NULL frame, more code to execute, in which case * this is an 'abort', so disregard the return value. */ if( FRAME!=NULL ) disregard = True; call = interpretTerm(call); error = CALL_ERROR(call); tmp = error?&(call->error_var):STACK0; if( (traperrors && error) || !disregard ) { ret = SEAPI_RETURN(call,tmp,TRUE,UNISTR("jseInterpTerm")); } else { /* error already printed */ ret = NULL; } STACK_POP; CALL_SET_ERROR(call,FlowNoReasonToQuit); return ret; } /* API returns NULL when nothing left to interpret */ JSECALLSEQ( jseContext ) jseInterpExec(jseContext call) { JSE_API_ASSERT_C(call,1,jseContext_cookie,UNISTR("jseInterpExec"),return NULL); assert( call->next==NULL ); return secodeInterpret(call)?call:NULL; } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jsebool ) jseReallyInterpret(jseContext call, const jsecharptr SourceFile, const jsecharptr SourceText, const void * PreTokenizedSource, jseNewContextSettings NewContextSettings, int howToInterpret, jseVariable *retvar, char *FILE, int LINE) #else JSECALLSEQ( jsebool ) jseInterpret(jseContext call, const jsecharptr SourceFile, const jsecharptr SourceText, const void * PreTokenizedSource, jseNewContextSettings NewContextSettings, int howToInterpret, jseContext unused_parameter, jseVariable *retvar) #endif { jseContext newc; jsebool retbool; rSEVar ret; #if (0!=JSE_COMPILER) uint compilingSave; #endif # if defined(NDEBUG) || !defined(JSE_TRACKVARS) || JSE_TRACKVARS==0 UNUSED_PARAMETER(unused_parameter); # endif JSE_API_ASSERT_C(call,1,jseContext_cookie,UNISTR("jseInterpret"),return False); assert( call->next==NULL ); CALL_SET_ERROR(call,FlowNoReasonToQuit); newc = interpretInit(call,SourceFile,SourceText,PreTokenizedSource, NewContextSettings,howToInterpret); if( newc!=NULL ) { /* This is a really ugly hack which is meant to preserve the compilation state. * Because we may actually do an interpret() within a compilation (as with our * binary object files), we want to make sure that the interpret doesn't think * we're still compiling files, because we're not. Well, sort of. */ #if (0!=JSE_COMPILER) compilingSave = call->Global->CompileStatus.NowCompiling; call->Global->CompileStatus.NowCompiling = 0; #endif /* remain in loop calling statement after statement, even if the * level of function changes. */ while( secodeInterpret(newc) ) { /* context has not changed; still in the same function */ if( !callMayIContinue(newc) ) { /* probably in the middle of a function, but something * sensible on the top of the stack to return */ wSEVar tmp = STACK_PUSH; SEVAR_INIT_UNDEFINED(tmp); break; } } interpretTerm(newc); #if (0!=JSE_COMPILER) call->Global->CompileStatus.NowCompiling = compilingSave; #endif } /* it only fails on error, exiting is ok */ retbool = !CALL_ERROR(call); ret = retbool?STACK0:&(call->error_var); if( retvar!=NULL && (retbool || (howToInterpret&JSE_INTERPRET_TRAP_ERRORS)!=0) ) { *retvar = SEAPI_RETURN(call,ret,TRUE,UNISTR("jseInterpTerm")); } else { if( retvar!=NULL ) *retvar = NULL; if( !retbool ) { /* error already printed */ CALL_SET_ERROR(call,FlowNoReasonToQuit); } } STACK_POP; CALL_SET_ERROR(call,FlowNoReasonToQuit); return retbool; } #if defined(JSE_TOKENSRC) && (0!=JSE_TOKENSRC) JSECALLSEQ( jseTokenRetBuffer) jseCreateCodeTokenBuffer(jseContext call, const jsecharptr source, jsebool sourceIsFileName /*else is source string*/, uint *bufferLen) { struct Call *newCall; void *ret; JSE_API_STRING(ThisFuncName,"jseCreateCodeTokenBuffer"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return NULL); assert( call->next==NULL ); JSE_API_ASSERT_(source,2,ThisFuncName,return NULL); JSE_API_ASSERT_(bufferLen,4,ThisFuncName,return NULL); newCall = callInterpret(call,jseNewGlobalObject|jseNewLibrary,False,False); ret = CompileIntoTokens(newCall,source,sourceIsFileName,bufferLen); callDelete(newCall); return ret; } #endif JSECALLSEQ( jsebool ) jseAddLibrary(jseContext call, const jsecharptr objectVariableName, const struct jseFunctionDescription *FunctionList, void _FAR_ *InitLibData, jseLibraryInitFunction libInitFunction, jseLibraryTermFunction libTermFunction) { JSE_API_STRING(ThisFuncName,"jseAddLibrary"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return False); assert( call->next==NULL ); JSE_API_ASSERT_(FunctionList,3,ThisFuncName,return False); return libraryAddFunctions(call->TheLibrary,call, objectVariableName,FunctionList, libInitFunction,libTermFunction,InitLibData); } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jseVariable ) jseReallyFuncVar(jseContext call,uint ParameterOffset,char *FILE,int LINE) #else JSECALLSEQ( jseVariable ) jseFuncVar(jseContext call,uint ParameterOffset) #endif { jsecharptr cname; JSE_API_ASSERT_C(call,1,jseContext_cookie,UNISTR("jseFuncVar"),return NULL); assert( call->next==NULL ); if( call->num_args <= ParameterOffset ) { cname = callCurrentName(call); callError(call,textcoreFUNCPARAM_NOT_PASSED,1 + ParameterOffset, LFOM(cname)); UFOM(cname); return NULL; } return ( SEAPI_RETURN(call,CALL_PARAM(ParameterOffset),FALSE,UNISTR("jseFuncVar")) ); } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jseVariable ) jseReallyFuncVarNeed(jseContext call,uint parameterOffset,jseVarNeeded need, char *FILE,int LINE) #else JSECALLSEQ( jseVariable ) jseFuncVarNeed(jseContext call,uint parameterOffset,jseVarNeeded need) #endif { wSEVar dest = STACK_PUSH; jseVariable ret; JSE_API_ASSERT_C(call,1,jseContext_cookie,UNISTR("jseFuncVarNeed"),return NULL); assert( call->next==NULL ); SEVAR_INIT_UNDEFINED(dest); callGetVarNeed(call,NULL,dest,parameterOffset,need); if( CALL_QUIT(call) ) { /* leave error on top of stack */ ret = NULL; } else { ret = SEAPI_RETURN(call,dest,(need&JSE_VN_CREATEVAR)?TRUE:FALSE,UNISTR("jseFuncVarNeed")); STACK_POP; } return ret; } JSECALLSEQ( jsebool ) jseVarNeed(jseContext call,jseVariable variable,jseVarNeeded need) { wSEVar v; JSE_API_STRING(ThisFuncName,"jseVarNeed"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return False); assert( call->next==NULL ); v = seapiGetValue(call,variable); callGetVarNeed(call,v,v,0,need); seapiPutValue(call,variable,v); return CALL_QUIT(call)==0; } #if ( 0 < JSE_API_ASSERTLEVEL ) static jsebool NEAR_CALL TestValidForArrayLength(/*jseContext call,*/rSEVar var) { jseVarType vType = SEVAR_GET_TYPE(var); if ( VObject != vType # if defined(JSE_TYPE_BUFFER) && (0!=JSE_TYPE_BUFFER) && VBuffer != vType # endif && VString != vType ) { SetLastApiError(UNISTR("Invalid var type for Get/SetArrayLength")); return False; } return True; } #endif JSECALLSEQ( JSE_POINTER_UINDEX ) jseGetArrayLength(jseContext call,jseVariable variable, JSE_POINTER_SINDEX *MinIndex) { rSEVar var; JSE_POINTER_UINDEX ret; JSE_API_STRING(ThisFuncName,"jseGetArrayLength"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return 0); assert( call->next==NULL ); var = seapiGetValue(call,variable); # if ( 0 < JSE_API_ASSERTLEVEL ) if ( !TestValidForArrayLength(var) ) { ret = 0; if ( NULL != MinIndex ) *MinIndex = 0; } else # endif { ret = sevarGetArrayLength(call,var,MinIndex); } return ret; } JSECALLSEQ( void ) jseSetArrayLength(jseContext call,jseVariable variable, JSE_POINTER_SINDEX MinIndex,JSE_POINTER_UINDEX Length) { wSEVar var; JSE_API_STRING(ThisFuncName,"jseSetArrayLength"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); var = seapiGetValue(call,variable); # if ( 0 < JSE_API_ASSERTLEVEL ) if ( TestValidForArrayLength(var) ) # endif { sevarSetArrayLength(call,var,MinIndex,Length); } } JSECALLSEQ( void ) jseSetAttributes(jseContext call,jseVariable variable, jseVarAttributes attr) { rSEVar var; struct Function *func; JSE_API_STRING(ThisFuncName,"jseSetAttributes"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); var = seapiGetValue(call,variable); if( SEVAR_GET_TYPE(var)==VObject ) { wSEObject wobj; SEOBJECT_ASSIGN_LOCK_W(wobj,SEVAR_GET_OBJECT(var)); if( (func = SEOBJECT_PTR(wobj)->func)!=NULL ) func->attributes = attr; if( attr & jseEcmaArray ) seobjMakeEcmaArray(call,wobj); if( attr & jseDynamicOnUndefined ) SEOBJ_MAKE_DYNAMIC_UNDEFINED(wobj); SEOBJECT_UNLOCK_W(wobj); } if( SEVAR_GET_TYPE(&(variable->value))==VReference ) { /* set these on the object member itself */ seobjSetAttributes(call,variable->value.data.ref_val.hBase, variable->value.data.ref_val.reference, attr); } } #if defined(JSE_DYNAMIC_OBJS) JSECALLSEQ(void) jseSetObjectCallbacks(jseContext call,jseVariable obj,struct jseObjectCallbacks *cbs) { rSEVar var; JSE_API_STRING(ThisFuncName,"jseSetObjectCallbacks"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); var = seapiGetValue(call,obj); if( SEVAR_GET_TYPE(var)==VObject ) { wSEObject wobj; SEOBJECT_ASSIGN_LOCK_W(wobj,SEVAR_GET_OBJECT(var)); SEOBJECT_PTR(wobj)->callbacks = cbs; SEOBJ_MAKE_DYNAMIC(wobj); SEOBJECT_UNLOCK_W(wobj); } } JSECALLSEQ(struct jseObjectCallbacks *) jseGetObjectCallbacks(jseContext call,jseVariable obj) { rSEVar var; struct jseObjectCallbacks *callbacks; JSE_API_STRING(ThisFuncName,"jseGetObjectCallbacks"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return NULL); assert( call->next==NULL ); var = seapiGetValue(call,obj); if( SEVAR_GET_TYPE(var)==VObject ) { rSEObject robj; SEOBJECT_ASSIGN_LOCK_R(robj,SEVAR_GET_OBJECT(var)); callbacks = SEOBJECT_PTR(robj)->callbacks; SEOBJECT_UNLOCK_R(robj); } else { callbacks = NULL; } return callbacks; } #endif JSECALLSEQ( jseVarAttributes ) jseGetAttributes(jseContext call,jseVariable variable) { jseVarAttributes ret; JSE_API_STRING(ThisFuncName,"jseGetAttributes"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return 0); assert( call->next==NULL ); if( SEVAR_GET_TYPE(&(variable->value))==VReference ) { /* get these from the object member itself */ ret = seobjGetAttributes(call,variable->value.data.ref_val.hBase, variable->value.data.ref_val.reference); } else if( SEVAR_GET_TYPE(&(variable->value))==VReferenceIndex ) { rSEObject robj; rSEMembers rMembers; uint index; index = (uint)(ulong)(variable->value.data.ref_val.reference); SEOBJECT_ASSIGN_LOCK_R(robj,variable->value.data.ref_val.hBase); /* get these from the object member itself */ assert( index < SEOBJECT_PTR(robj)->used ); SEMEMBERS_ASSIGN_LOCK_R(rMembers,SEOBJECT_PTR(robj)->hsemembers); SEOBJECT_UNLOCK_R(robj); ret = SEMEMBERS_PTR(rMembers)[index].attributes; SEMEMBERS_UNLOCK_R(rMembers); } else { rSEVar var; ret = 0; var = seapiGetValue(call,variable); if( SEVAR_GET_TYPE(var)==VObject ) { rSEObject robj; SEOBJECT_ASSIGN_LOCK_R(robj,SEVAR_GET_OBJECT(var)); if ( SEOBJECT_PTR(robj)->func != NULL ) ret = SEOBJECT_PTR(robj)->func->attributes; SEOBJECT_UNLOCK_R(robj); } } return ret; } JSECALLSEQ( void ) jseReturnLong(jseContext call,slong longValue) { wSEVar var = STACK_PUSH; JSE_API_ASSERT_C(call,1,jseContext_cookie,UNISTR("jseReturnLong"),return); assert( call->next==NULL ); SEVAR_INIT_SLONG(var,longValue); } JSECALLSEQ( void ) jseReturnNumber(jseContext call,jsenumber number) { wSEVar var = STACK_PUSH; JSE_API_ASSERT_C(call,1,jseContext_cookie,UNISTR("jseReturnNumber"),return); assert( call->next==NULL ); SEVAR_INIT_NUMBER(var,number); } JSECALLSEQ( void ) jseReturnVar(jseContext call,jseVariable variable, jseReturnAction RetAction) { rSEVar ret; wSEVar tmp; JSE_API_STRING(ThisFuncName,"jseReturnVar"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); /* We always return the given variable's value, there is no * return-by-reference (what would that mean?) The copy-to-temp-var * differentiation really only made sense in old versions of the * core. */ ret = seapiGetValue(call,variable); tmp = STACK_PUSH; SEVAR_COPY(tmp,ret); if( RetAction==jseRetTempVar ) { seapiDeleteVariable(call,variable); } } JSECALLSEQ( jsebool ) jseCompare(jseContext call,jseVariable variable1,jseVariable variable2, slong *CompareResult) { wSEVar var1,var2; jsebool ret; JSE_API_STRING(ThisFuncName,"jseCompare"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return False); assert( call->next==NULL ); JSE_API_ASSERT_(CompareResult,4,ThisFuncName,return False); if( CompareResult==JSE_COMPVAR && ((SEVAR_GET_TYPE(&(variable1->value))==VReference && SEVAR_GET_TYPE(&(variable2->value))==VReference) || (SEVAR_GET_TYPE(&(variable1->value))==VReferenceIndex && SEVAR_GET_TYPE(&(variable2->value))==VReferenceIndex)) ) { if( variable1->value.data.ref_val.hBase==variable2->value.data.ref_val.hBase && variable1->value.data.ref_val.reference==variable2->value.data.ref_val.reference ) return True; } var1 = seapiGetValue(call,variable1); var2 = seapiGetValue(call,variable2); if( CompareResult==JSE_COMPVAR ) { if( SEVAR_GET_TYPE(var1)==SEVAR_GET_TYPE(var2) ) { if( SEVAR_GET_TYPE(var1)==VObject ) { ret = SEVAR_GET_OBJECT(var1)==SEVAR_GET_OBJECT(var2); } else if( # if defined(JSE_TYPE_BUFFER) && (0!=JSE_TYPE_BUFFER) SEVAR_GET_TYPE(var1)==VBuffer || # endif SEVAR_GET_TYPE(var1)==VString ) { ret = SEVAR_GET_STRING(var1).loffset==SEVAR_GET_STRING(var2).loffset && SEVAR_GET_STRING(var1).data==SEVAR_GET_STRING(var2).data; } else { ret = (var1==var2); } } else { ret = False; } } else { if( CompareResult==JSE_COMPLESS ) { ret = (SEVAR_COMPARE_LESS(call,var1,var2)==1); } else if( CompareResult==JSE_COMPEQUAL ) { ret = SEVAR_COMPARE_EQUALITY(call,var1,var2); } else { ret = sevarCompare(call,var1,var2,CompareResult); } } return ret; } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ(jseVariable) jseReallyFindVariable(jseContext call, const jsecharptr name, ulong flags, char *FILE,int LINE) #else JSECALLSEQ(jseVariable) jseFindVariable(jseContext call, const jsecharptr name, ulong flags) #endif { wSEVar it = STACK_PUSH; jsebool found; uword8 tmp; VarName varname; jseVariable ret; JSE_API_ASSERT_C(call,1,jseContext_cookie,UNISTR("jseFindVariable"), return NULL); assert( call->next==NULL ); varname = GrabStringTableEntryStrlen(call,name,&tmp); SEVAR_INIT_UNDEFINED(it); found = callFindAnyVariable(call,varname,True,True); ReleaseStringTableEntry(/*call,*/varname,tmp); if( found ) { ret = SEAPI_RETURN(call,it,(flags&jseCreateVar)?TRUE:FALSE,UNISTR("jseFindVariable")); } else { ret = NULL; } STACK_POP; return ret; } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jseVariable ) jseReallyCreateVariable(jseContext call,jseDataType VDataType,char *FILE,int LINE) #else JSECALLSEQ( jseVariable ) jseCreateVariable(jseContext call,jseDataType VDataType) #endif { wSEVar ret = STACK_PUSH; jseVariable retvar; JSE_API_ASSERT_C(call,1,jseContext_cookie,UNISTR("jseCreateVariable"), return NULL); assert( call->next==NULL ); if( !SEVAR_IS_VALID_TYPE(VDataType) ) { # if ( 0 < JSE_API_ASSERTLEVEL ) # if (0!=JSE_API_ASSERTNAMES) SetLastApiError( UNISTR("%s: Invalid data type"),UNISTR("jseCreateVariable")); # else SetLastApiError(UNISTR("Invalid data type")); # endif # endif SEVAR_INIT_UNDEFINED(ret); } sevarInitType(call,ret,VDataType); retvar = SEAPI_RETURN(call,ret,TRUE,UNISTR("jseCreateVariable")); STACK_POP; return retvar; } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jseVariable ) jseReallyCreateSiblingVariable(jseContext call,jseVariable olderSiblingVar, JSE_POINTER_SINDEX elem, char *FILE,int LINE) #else JSECALLSEQ( jseVariable ) jseCreateSiblingVariable(jseContext call,jseVariable olderSiblingVar, JSE_POINTER_SINDEX elem) #endif { wSEVar dest = STACK_PUSH; rSEVar old; jseVariable ret; JSE_API_STRING(ThisFuncName,"jseCreateSiblingVariable"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return NULL); assert( call->next==NULL ); SEVAR_INIT_UNDEFINED(dest); old = seapiGetValue(call,olderSiblingVar); if( SEVAR_ARRAY_PTR(old) ) { SEVAR_INIT_ARRAY_SIBLING(dest,old,elem); } else { SEVAR_INIT_OBJECT_SIBLING(dest,old); } ret = SEAPI_RETURN(call,dest,TRUE,UNISTR("jseCreateSiblingVariable")); STACK_POP; return ret; } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ(jseVariable) jseReallyCreateConvertedVariable(jseContext call,jseVariable variableToConvert, jseConversionTarget targetType,char *FILE,int LINE) #else JSECALLSEQ(jseVariable) jseCreateConvertedVariable(jseContext call,jseVariable variableToConvert, jseConversionTarget targetType) #endif { wSEVar dest; rSEVar tmp; jseVariable ret; JSE_API_STRING(ThisFuncName,"jseCreateConvertedVariable"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return NULL); assert( call->next==NULL ); tmp = seapiGetValue(call,variableToConvert); dest = STACK_PUSH; SEVAR_COPY(dest,tmp); sevarConvert(call,dest,targetType); if( CALL_QUIT(call) ) { ret = NULL; } else { ret = SEAPI_RETURN(call,dest,TRUE,UNISTR("jseCreateConvertedVariable")); STACK_POP; } return ret; } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jseVariable ) jseReallyCreateLongVariable(jseContext call,slong value,char *FILE,int LINE) #else JSECALLSEQ( jseVariable ) jseCreateLongVariable(jseContext call,slong value) #endif { wSEVar tmp = STACK_PUSH; jseVariable ret; JSE_API_ASSERT_C(call,1,jseContext_cookie,UNISTR("jseCreateLongVariable"), return NULL); assert( call->next==NULL ); SEVAR_INIT_SLONG(tmp,value); ret = SEAPI_RETURN(call,tmp,TRUE,UNISTR("jseCreateLongVariable")); STACK_POP; return ret; } JSECALLSEQ( void ) jseDestroyVariable(jseContext call,jseVariable variable) { JSE_API_STRING(ThisFuncName,"jseDestroyVariable"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); if( variable ) seapiDeleteVariable(call,variable); } JSECALLSEQ( jseDataType ) jseGetType(jseContext call,jseVariable variable) { jseVarType ret; JSE_API_STRING(ThisFuncName,"jseGetType"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return 0); assert( call->next==NULL ); ret = variable?SEVAR_GET_TYPE(seapiGetValue(call,variable)):(jseVarType)VUndefined; assert( SEVAR_IS_VALID_TYPE(ret) ); return ret; } jsenumber GenericGetNumber( # if (0!=JSE_API_ASSERTNAMES) const jsecharptr ThisFuncName, # endif jseContext call,jseVariable variable) { wSEVar var; rSEVar tmp; jsenumber number; JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return jseNaN); assert( call->next==NULL ); tmp = seapiGetValue(call,variable); var = STACK_PUSH; SEVAR_COPY(var,tmp); number = sevarConvertToNumber(call,var); STACK_POP; return number; } JSECALLSEQ( jsebool ) jseEvaluateBoolean(jseContext call,jseVariable variable) { wSEVar var; rSEVar tmp; jsebool ret; JSE_API_STRING(ThisFuncName,"jseEvaluateBoolean"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return False); assert( call->next==NULL ); tmp = seapiGetValue(call,variable); var = STACK_PUSH; SEVAR_COPY(var,tmp); ret = sevarConvertToBoolean(call,var); STACK_POP; return ret; } JSECALLSEQ( void ) jsePutBoolean(jseContext call,jseVariable variable,jsebool boolValue) { wSEVar val; JSE_API_STRING(ThisFuncName,"jsePutBoolean"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); val = STACK_PUSH; SEVAR_INIT_BOOLEAN(val,boolValue!=False); seapiPutValue(call,variable,val); STACK_POP; } JSECALLSEQ( void ) jsePutNumber(jseContext call,jseVariable variable,jsenumber number) { wSEVar val; JSE_API_STRING(ThisFuncName,"jsePutNumber"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); val = STACK_PUSH; SEVAR_INIT_NUMBER(val,number); seapiPutValue(call,variable,val); STACK_POP; } JSECALLSEQ( void ) jsePutLong(jseContext call,jseVariable variable,slong longValue) { wSEVar val; JSE_API_STRING(ThisFuncName,"jsePutLong"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); val = STACK_PUSH; SEVAR_INIT_SLONG(val,longValue); seapiPutValue(call,variable,val); STACK_POP; } #if !defined(NDEBUG) && JSE_TRACKVARS==1 void _HUGE_ * GenericGetDataPtr( # if (0!=JSE_API_ASSERTNAMES) const jsecharptr ThisFuncName, # endif jseContext call,jseVariable variable, JSE_POINTER_UINDEX *filled,jseVarType vType, jsebool Writeable,char *FILE,int LINE) #else void _HUGE_ * GenericGetDataPtr( # if (0!=JSE_API_ASSERTNAMES) const jsecharptr ThisFuncName, # endif jseContext call,jseVariable variable, JSE_POINTER_UINDEX *filled,jseVarType vType, jsebool Writeable) #endif { wSEVar ret; JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return NULL); assert( call->next==NULL ); ret = seapiGetValue(call,variable); if( SEVAR_GET_TYPE(ret) != vType ) { if( ret!=&(variable->last_access) ) { SEVAR_COPY(&(variable->last_access),ret); ret = &(variable->last_access); } if( !Writeable && (jseOptLenientConversion & call->Global->ExternalLinkParms.options) ) { sevarConvert(call,ret, # if defined(JSE_TYPE_BUFFER) && (0!=JSE_TYPE_BUFFER) vType == VBuffer ? jseToBuffer : # endif jseToString); } else { /* should not have called in this way; but don't crash */ if ( filled ) *filled = 0; # if ( 0 < JSE_API_ASSERTLEVEL ) # if (0!=JSE_API_ASSERTNAMES) SetLastApiError( UNISTR("%s: Data type is not correct string or buffer type"),ThisFuncName); # else SetLastApiError(UNISTR("Data type is not correct string or buffer type")); # endif # endif return UNISTR(""); } } if( SEVAR_GET_TYPE(&(variable->value))==VReference ) { /* make a temp variable to lock it into memory. */ SEAPI_RETURN(call,ret,FALSE,UNISTR("GenericGetDataPtr")); } if( filled ) *filled = SEVAR_STRING_LEN(ret); # if JSE_MEMEXT_STRINGS==1 if( variable->data ) SEVAR_FREE_DATA(call,variable->data); return variable->data = (void *)sevarGetData(call,ret); # else return (void _HUGE_ *)sevarGetData(call,ret); # endif } #if defined(JSE_C_EXTENSIONS) && (0!=JSE_C_EXTENSIONS) /* Determine if calling script function is cbehavior, FALSE if none */ static jsebool NEAR_CALL callLocalCBehavior(struct Call *call) { const struct Function *func_orig = call->funcptr; wSEVar wfptr = FRAME; /* no enclosing function */ if( func_orig==NULL ) return False; /* Find the enclosing local function */ while( !FUNCTION_IS_LOCAL(func_orig) ) { uword16 num_args = (uword16)SEVAR_GET_STORAGE_LONG(wfptr-ARGS_OFFSET); # if defined(JSE_GROWABLE_STACK) && (0!=JSE_GROWABLE_STACK) wfptr = STACK_FROM_STACKPTR(SEVAR_GET_STORAGE_LONG(wfptr)); if( wfptr==call->Global->growingStack ) return False; # else wfptr = SEVAR_GET_STORAGE_PTR(wfptr); /* no enclosing local function */ if( wfptr==NULL ) return False; # endif { rSEObject robj; SEOBJECT_ASSIGN_LOCK_R(robj,SEVAR_GET_OBJECT(wfptr - (num_args + FUNC_OFFSET))); func_orig = SEOBJECT_PTR(robj)->func; SEOBJECT_UNLOCK_R(robj); } } return FUNCTION_C_BEHAVIOR(func_orig); } #endif /* #if defined(JSE_C_EXTENSIONS) && (0!=JSE_C_EXTENSIONS) */ void GenericPutDataPtr( # if (0!=JSE_API_ASSERTNAMES) const jsecharptr ThisFuncName, # endif jseContext call,jseVariable variable,void _HUGE_ *data, jseVarType vType,JSE_POINTER_UINDEX *size) { wSEVar val; JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); # if ( 0 < JSE_API_ASSERTLEVEL ) if ( NULL != size && 0 != *size ) { JSE_API_ASSERT_(data,3,ThisFuncName,return); } # endif assert( SEVAR_IS_VALID_TYPE(vType) ); if( data==NULL ) return; /* In C functions, we physically update the old pointer. * In regular functions, we write a new string by updating it first. * We must also always copy constant strings. */ val = seapiGetValue(call,variable); # if JSE_MEMEXT_STRINGS!=0 if( variable->data ) { SEVAR_FREE_DATA(call,variable->data); variable->data = NULL; } # endif if ( SEVAR_GET_TYPE(val)==VString ) { # if defined(JSE_C_EXTENSIONS) && (0!=JSE_C_EXTENSIONS) if ( SESTR_IS_CONSTANT(SEVAR_GET_STRING(val).data) || !callLocalCBehavior(call) ) # endif sevarDuplicateString(call,val); } if( val!=NULL && SEVAR_GET_TYPE(val)==vType ) { JSE_POINTER_SINDEX minidx; sevarGetArrayLength(call,val,&minidx); if( minidx<0 ) { /* merge with existing data, this is so something like: * * Clib.strcpy(foo+5,"goo"); * * will work as expected. */ # if defined(JSE_TYPE_BUFFER) && (0!=JSE_TYPE_BUFFER) if( vType!=VString ) { JSE_MEMEXT_R void *olddata = SESTRING_GET_DATA(val->data.string_val.data); ubyte *newdata = jseMustMalloc(void,((*size)-minidx+1)*sizeof(jsechar)); assert( minidx <= 0 ); memcpy(newdata,olddata,(JSE_POINTER_UINDEX)-minidx); SESTRING_UNGET_DATA(val->data.string_val.data,olddata); memcpy(newdata-minidx,data,*size); newdata[-minidx+*size] = '\0'; /* physically update the old ptr */ SESTRING_FREE_DATA(val->data.string_val.data); SESTRING_PUT_DATA(val->data.string_val.data,newdata, ((*size)-minidx+1)*sizeof(jsechar)); val->data.string_val.data->length = (*size)-minidx; } else # endif { JSE_POINTER_UINDEX actual_size = size?(*size):strlen_jsechar((const jsecharptr)data); ubyte *newdata = jseMustMalloc(ubyte,(actual_size-minidx+1)*sizeof(jsechar)); JSE_POINTER_UINDEX s1,s2; JSE_MEMEXT_R void *olddata = SESTRING_GET_DATA(val->data.string_val.data); assert( minidx <= 0 ); memcpy(newdata,olddata,s1 = BYTECOUNT_FROM_STRLEN(olddata, (JSE_POINTER_UINDEX)-minidx)); memcpy(newdata+s1,data, s2 = BYTECOUNT_FROM_STRLEN((const jsecharptr)data,actual_size)); assert( sizeof(jsecharptrdatum) == sizeof_jsechar('\0') ); *((jsecharptrdatum *)(newdata+s1+s2)) = '\0'; SESTRING_UNGET_DATA(val->data.string_val.data,olddata); /* physically update the old ptr */ SESTRING_FREE_DATA(val->data.string_val.data); SESTRING_PUT_DATA(val->data.string_val.data,newdata, (actual_size-minidx+1)*sizeof(jsechar)); val->data.string_val.data->length = actual_size-minidx; } } else { if ( size ) { # if defined(JSE_TYPE_BUFFER) && (0!=JSE_TYPE_BUFFER) if( vType==VBuffer ) { void *newdata = jseMustMalloc(void,(*size)+sizeof(jsecharptrdatum)); memcpy(newdata,data,*size); *(((ubyte *)newdata)+(*size)) = '\0'; SESTRING_FREE_DATA(val->data.string_val.data); SESTRING_PUT_DATA(val->data.string_val.data,newdata,(*size)+sizeof(jsecharptrdatum)); val->data.string_val.data->length = *size; } else # endif { JSE_POINTER_UINDEX len = BYTECOUNT_FROM_STRLEN(data,*size); void *newdata = jseMustMalloc(void,len+sizeof(jsecharptrdatum)); memcpy(newdata,data,len); *((jsechar *)(((ubyte *)newdata)+len)) = '\0'; SESTRING_FREE_DATA(val->data.string_val.data); SESTRING_PUT_DATA(val->data.string_val.data,newdata,len+sizeof(jsecharptrdatum)); val->data.string_val.data->length = *size; } } else { JSE_POINTER_UINDEX length = strlen_jsechar( (const jsecharptr )data); JSE_POINTER_UINDEX len = BYTECOUNT_FROM_STRLEN(data,length); void *newdata = jseMustMalloc(void,len+sizeof(jsechar)); /* only way to not pass length is for null-term string length */ assert( VString == vType ); memcpy(newdata,data,len); *((jsechar *)(((ubyte *)newdata)+len)) = '\0'; SESTRING_FREE_DATA(val->data.string_val.data); SESTRING_PUT_DATA(val->data.string_val.data,newdata,len+sizeof(jsechar)); val->data.string_val.data->length = length; } } # if defined(JSE_MBCS) && (JSE_MBCS!=0) /* recalculate physical length */ /* NYI: MBCS byte length probably can be done better in * the individual cases above */ val->data.string_val.data->bytelength = BYTECOUNT_FROM_STRLEN(SESTRING_GET_DATA(val->data.string_val.data), val->data.string_val.data->length); # endif } /* put it back to make sure dynamic changes happen */ seapiPutValue(call,variable,val); } JSECALLSEQ( void ) jseConvert(jseContext call,jseVariable variable,jseDataType dType) { wSEVar orig; JSE_API_STRING(ThisFuncName,"jseConvert"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); if( !SEVAR_IS_VALID_TYPE(dType) ) { # if ( 0 < JSE_API_ASSERTLEVEL ) # if (0!=JSE_API_ASSERTNAMES) SetLastApiError( UNISTR("%s: Invalid data type"),UNISTR("jseConvert")); # else SetLastApiError(UNISTR("Invalid data type")); # endif # endif } else { orig = seapiGetValue(call,variable); if( SEVAR_GET_TYPE(orig)!=dType ) { orig = STACK_PUSH; sevarInitType(call,orig,dType); seapiPutValue(call,variable,orig); STACK_POP; } } } #pragma codeseg JSELIB2_TEXT JSECALLSEQ( jsebool ) jseAssign(jseContext call,jseVariable destVar,jseVariable srcVar) { wSEVar src; JSE_API_STRING(ThisFuncName,"jseAssign"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return False); assert( call->next==NULL ); seapiPutValue(call,destVar,src = seapiGetValue(call,srcVar)); # if ( 0 != JSE_DYNAMIC_OBJ_INHERIT ) /* if assigning a _prototype to another object, then inherit * the dynamic properties of that other object */ if( SEVAR_GET_TYPE(&(destVar->value))==VReference && destVar->value.data.ref_val.reference==STOCK_STRING(_prototype) && SEVAR_GET_TYPE(src)==VObject ) { uword8 srcFlags; rSEObject robj; wSEObject wobj; SEOBJECT_ASSIGN_LOCK_R(robj,SEVAR_GET_OBJECT(src)); srcFlags = SEOBJECT_PTR(robj)->flags; SEOBJECT_UNLOCK_R(robj); SEOBJECT_ASSIGN_LOCK_W(wobj,destVar->value.data.ref_val.hBase); if( (srcFlags & OBJ_IS_DYNAMIC)!=0 ) SEOBJ_MAKE_DYNAMIC(wobj); SEOBJECT_UNLOCK_W(wobj); } # endif return True; } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 static jseVariable jseMemberGuts(jseContext call,jseVariable objectVar,VarName vName, jseDataType DType,uword16 flags,char *FILE,int LINE) #else static jseVariable jseMemberGuts(jseContext call,jseVariable objectVar,VarName vName, jseDataType DType,uword16 flags) #endif { jseVariable done; wSEVar vobj = seapiGetValue(call,objectVar); jsebool found = False; wSEVar tmpvar = STACK_PUSH; wSEVar ret = STACK_PUSH; rSEObject robj; hSEObject hobj; int prop_flags = 0; SEVAR_INIT_UNDEFINED(tmpvar); SEVAR_INIT_UNDEFINED(ret); if( vobj==NULL ) { SEVAR_INIT_OBJECT(tmpvar,CALL_GLOBAL(call)); vobj = tmpvar; } else if( SEVAR_GET_TYPE(vobj)!=VObject ) { /* Assert here to help the person track down the problem */ assert( False ); return NULL; } hobj = SEVAR_GET_OBJECT(vobj); SEOBJECT_ASSIGN_LOCK_R(robj,hobj); if( (flags&jseLockRead)==0 ) prop_flags |= HP_REFERENCE; if( (flags&jseDontSearchPrototype)!=0 ) prop_flags |= HP_NO_PROTOTYPE; found = seobjHasProperty(call,robj,vName,ret,prop_flags); SEOBJECT_UNLOCK_R(robj); if( !found ) { /* the member is undefined, if we are not supposed to create * types, this is a signal to return NULL. */ if( flags & jseDontCreateMember ) { STACK_POPX(2); return NULL; } else { /* Else we create it with the given type and put it in */ sevarInitType(call,ret,DType); SEVAR_PUT_VALUE(call,vobj,vName,ret); /* even if an error, jseMember() (i.e. when the jseDontCreateMember * flag is off, this branch of the if) must never return NULL. * We still return the reference. */ } } assert( ret!=NULL ); /* With lock read, we return that value we found */ if( (flags & jseLockRead)==0 ) { /* If not lock read, we create a reference so when the user * goes to write to it, any dynamic stuff happens. Note that * jseLockWrite really has no meaning any more, but the effect * will be the same. */ /* if the given member is itself a reference, return * it instead, since we don't ever allow 'doubly indirect' * stuff. It is pointless to point to a member which * just then points to something else, point at that * something else instead (plus the internals all * assume and assert that this isn't happening.) */ if( SEVAR_GET_TYPE(ret)<VReference ) { SEVAR_INIT_REFERENCE(ret,hobj,vName); } } /* We have something to return, use the CreateVar flag to determine * if this should be destroyed by the user. */ done = SEAPI_RETURN(call,ret,(flags&jseCreateVar)!=0,UNISTR("jseMemberEx")); STACK_POPX(2); return done; } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jseVariable ) jseReallyMemberInternal(jseContext call,jseVariable objectVar, const jsecharptr Name, jseDataType DType,uword16 flags,char *FILE,int LINE) { uword8 tmp; jseVariable ret; VarName vName = GrabStringTableEntryStrlen(call,Name,&tmp); ret = jseMemberGuts(call,objectVar,vName,DType,flags,FILE,LINE); ReleaseStringTableEntry(/*call,*/vName,tmp); return ret; } #else JSECALLSEQ( jseVariable ) jseMemberInternal(jseContext call,jseVariable objectVar, const jsecharptr Name, jseDataType DType,uword16 flags) { uword8 tmp; jseVariable ret; VarName vName = GrabStringTableEntryStrlen(call,Name,&tmp); ret = jseMemberGuts(call,objectVar,vName,DType,flags); ReleaseStringTableEntry(/*call,*/vName,tmp); return ret; } #endif #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jseVariable ) jseReallyIndexMemberEx(jseContext call,jseVariable objectVar, JSE_POINTER_SINDEX index,jseDataType dType,uword16 flags, char *FILE,int LINE) { return jseMemberGuts(call,objectVar, (index<0)? NegativeStringTableEntry(index): PositiveStringTableEntry(index), dType,flags,FILE,LINE); } #else JSECALLSEQ( jseVariable ) jseIndexMemberEx(jseContext call,jseVariable objectVar, JSE_POINTER_SINDEX index,jseDataType dType,uword16 flags) { return jseMemberGuts(call,objectVar, (index<0)? NegativeStringTableEntry(index): PositiveStringTableEntry(index), dType,flags); } #endif #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jseVariable ) jseReallyGetNextMember(jseContext call,jseVariable objectVariable, jseVariable prevMemberVariable, const jsecharptr * name,char *FILE,int LINE) #else JSECALLSEQ( jseVariable ) jseGetNextMember(jseContext call,jseVariable objectVariable, jseVariable prevMemberVariable, const jsecharptr * name) #endif { rSEVar objvar; wSEVar ret; jseVariable apiret; hSEObject hobj; rSEObject robj; JSE_API_STRING(ThisFuncName,"jseGetNextMember"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return NULL); assert( call->next==NULL ); JSE_API_ASSERT_(name,4,ThisFuncName,return NULL); if( objectVariable!=NULL ) { objvar = seapiGetValue(call,objectVariable); if( SEVAR_GET_TYPE(objvar)!=VObject ) return NULL; hobj = SEVAR_GET_OBJECT(objvar); } else { /* NULL = global object */ hobj = CALL_GLOBAL(call); } ret = STACK_PUSH; if( prevMemberVariable==NULL ) { SEVAR_INIT_REFERENCE_INDEX(ret,hobj,0); } else { MemCountUInt index; /* the returned variables are references into the object, * so the index variable better be indexing into this * same object. */ assert( SEVAR_GET_TYPE(&(prevMemberVariable->value))==VReferenceIndex && prevMemberVariable->value.data.ref_val.hBase==hobj ); index = ((MemCountUInt)(ulong)(prevMemberVariable->value.data.ref_val.reference))+1; SEVAR_INIT_REFERENCE_INDEX(ret,hobj,(VarName)index); } /* check if we have used up all the members */ SEOBJECT_ASSIGN_LOCK_R(robj,hobj); if( (MemCountUInt)(ulong)(ret->data.ref_val.reference) >= SEOBJECT_PTR(robj)->used ) { apiret = NULL; if( name ) *name = NULL; } else { apiret = SEAPI_RETURN(call,ret,False,UNISTR("jseGetNextMember")); if( name ) { rSEMembers rMembers; VarName n; SEMEMBERS_ASSIGN_LOCK_R(rMembers,SEOBJECT_PTR(robj)->hsemembers); n = SEMEMBERS_PTR(rMembers)[(MemCountUInt)(ulong)(ret->data.ref_val.reference)].name; SEMEMBERS_UNLOCK_R(rMembers); *name = ( n ) ? GetStringTableEntry(call,n,NULL) : NULL ; } } SEOBJECT_UNLOCK_R(robj); STACK_POP; return apiret; } JSECALLSEQ( void ) jseDeleteMember(jseContext call,jseVariable objectVar, const jsecharptr name) { VarName varname; rSEVar objVar = seapiGetValue(call,objectVar); wSEVar var = STACK_PUSH; JSE_API_STRING(ThisFuncName,"jseDeleteMember"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); JSE_API_ASSERT_(name,3,ThisFuncName,return); if ( objVar == NULL ) { SEVAR_INIT_OBJECT(var,CALL_GLOBAL(call)); objVar = var; } else { SEVAR_INIT_UNDEFINED(var); } if ( VObject == SEVAR_GET_TYPE(objVar) ) { wSEObject wobj; uword8 tmp; varname = GrabStringTableEntryStrlen(call,name,&tmp); SEOBJECT_ASSIGN_LOCK_W(wobj,SEVAR_GET_OBJECT(objVar)); seobjDeleteMember(call,wobj,varname,False); SEOBJECT_UNLOCK_W(wobj); ReleaseStringTableEntry(/*call,*/varname,tmp); } STACK_POP; } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jseVariable ) jseReallyActivationObject(jseContext call,char *FILE,int LINE) #else JSECALLSEQ( jseVariable ) jseActivationObject(jseContext call) #endif { if( call->hVariableObject==hSEObjectNull ) callCreateVariableObject(call,NULL); if( call->hVariableObject==hSEObjectNull || call->hVariableObject==call->hGlobalObject ) { return NULL; } else { wSEVar retvar = STACK_PUSH; jseVariable ret; SEVAR_INIT_OBJECT(retvar,call->hVariableObject); ret = SEAPI_RETURN(call,retvar,False,UNISTR("jseActivationObject")); STACK_POP; return ret; } } static rSEVar NEAR_CALL jselibFindFunction(jseContext call,rSEVar FunctionVar,const struct Function **FindFunc, const jsecharptr FunctionName /*null if don't use sub-function*/, rSEObjectMem *rMem/*set SEOBJECTMEM_PTR(rMem) non-NULL if must free*/) /* return NULL if not a function object */ { rSEVar ret = NULL; hSEObject hLook; if( FunctionVar == NULL || SEVAR_GET_TYPE(FunctionVar)!=VObject ) { hLook = CALL_GLOBAL(call); } else { hLook = SEVAR_GET_OBJECT(FunctionVar); } if( FunctionName!=NULL ) { uword8 temp; rSEObject rLook; VarName funcname = GrabStringTableEntryStrlen(call,FunctionName,&temp); SEOBJECT_ASSIGN_LOCK_R(rLook,hLook); *rMem = rseobjGetMemberStruct(call,rLook,funcname); SEOBJECT_UNLOCK_R(rLook); ReleaseStringTableEntry(/*call,*/funcname,temp); if( NULL != SEOBJECTMEM_PTR(*rMem) ) { ret = SEOBJECTMEM_VAR(*rMem); if( SEVAR_GET_TYPE(ret)!=VObject || NULL == (*FindFunc = sevarGetFunction(call,ret)) ) { /* failed to find full function - free object mem and return NULL */ SEOBJECTMEM_UNLOCK_R(*rMem); SEOBJECTMEM_PTR(*rMem) = NULL; ret = NULL; } } } else { SEOBJECTMEM_PTR(*rMem) = NULL; if( NULL != (*FindFunc = sevarGetFunction(call,FunctionVar)) ) { ret = FunctionVar; } } return ret; } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jseVariable ) jseReallyGetFunction(jseContext call,jseVariable object, const jsecharptr functionName,jsebool errorIfNotFound, char *FILE,int LINE) #else JSECALLSEQ( jseVariable ) jseGetFunction(jseContext call,jseVariable object, const jsecharptr functionName,jsebool errorIfNotFound) #endif { const struct Function *func; rSEVar FunctionVar; jseVariable ret; rSEObjectMem rMem; JSE_API_STRING(ThisFuncName,"jseGetFunction"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return NULL); assert( call->next==NULL ); JSE_API_ASSERT_(functionName,3,ThisFuncName,return NULL); FunctionVar = jselibFindFunction(call,seapiGetValue(call,object),&func,functionName,&rMem); if ( NULL == FunctionVar ) { if ( errorIfNotFound ) { callQuit(call,textcoreFUNCTION_NAME_NOT_FOUND,functionName); } ret = NULL; } else { ret = SEAPI_RETURN(call,FunctionVar,FALSE,UNISTR("jseGetFunction")); # if 0!=JSE_MEMEXT_MEMBERS if ( NULL != SEOBJECTMEM_PTR(rMem) ) SEOBJECTMEM_UNLOCK_R(rMem); # endif } return ret; } static jsebool NEAR_CALL IsItAFunction(jseContext call,rSEVar functionVariable, jsebool TestIfLibraryFunction) { const struct Function *func; rSEVar v; jsebool ret; rSEObjectMem rMem; assert( NULL != call ); v = jselibFindFunction(call,functionVariable,&func,NULL,&rMem); if ( NULL == v ) { ret = False; } else { ret = ( !TestIfLibraryFunction || !FUNCTION_IS_LOCAL(func) ); # if 0!=JSE_MEMEXT_MEMBERS if ( NULL != SEOBJECTMEM_PTR(rMem) ) SEOBJECTMEM_UNLOCK_R(rMem); # endif } return ret; } JSECALLSEQ( jsebool ) jseIsFunction(jseContext call,jseVariable functionVariable) { JSE_API_STRING(ThisFuncName,"jseIsFunction"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return False); assert( call->next==NULL ); return IsItAFunction(call,seapiGetValue(call,functionVariable),False); } JSECALLSEQ(jsebool) jseIsLibraryFunction(jseContext call,jseVariable functionVariable) { JSE_API_STRING(ThisFuncName,"jseIsLibraryFunction"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return False); assert( call->next==NULL ); return IsItAFunction(call,seapiGetValue(call,functionVariable),True); } void secallstackPush(/*struct Call *call,*/ struct seCallStack *This, seAPIVar v,jsebool deleteme) { This->vars = jseMustReMalloc(struct seCallStackVar,This->vars, (This->Count+1) * sizeof(This->vars[0])); This->vars[This->Count].var = v; This->vars[This->Count].free_on_del = deleteme; This->Count++; } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jsebool ) jseReallyCallFunctionEx(jseContext call,jseVariable jsefunc,jseStack jsestack, jseVariable *retvar,jseVariable thisVar,uint flags, char *FILE,int LINE) #else JSECALLSEQ( jsebool ) jseCallFunctionEx(jseContext call,jseVariable jsefunc,jseStack jsestack, jseVariable *retvar,jseVariable thisVar,uint flags) #endif { rSEVar rvar,tmp2,ret; wSEVar tmp; const struct Function *func; uint origdepth, depth; jsebool retbool; jsebool old_must = call->mustPrintError; JSE_API_STRING(ThisFuncName,"jseCallFunction"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return False); assert( call->next==NULL ); if( jsestack!=NULL ) { JSE_API_ASSERT_C(jsestack,3,jseStack_cookie,ThisFuncName,return False); } CALL_SET_ERROR(call,FlowNoReasonToQuit); *retvar = NULL; rvar = seapiGetValue(call,jsefunc); # if ( 0 < JSE_API_ASSERTLEVEL ) if( SEVAR_GET_TYPE(rvar)!=VObject ) { SetLastApiError( UNISTR("%s: parameter 2 not a function"),ThisFuncName ); return False; } # endif tmp = STACK_PUSH; SEVAR_INIT_UNDEFINED(tmp); if( (flags & JSE_FUNC_CONSTRUCT)!=0 ) { rSEObjectMem rvarmem; sevarInitNewObject(call,tmp,rvar); rvar = seobjGetFuncVar(call,rvar,STOCK_STRING(_construct),&rvarmem); tmp = STACK_PUSH; SEVAR_COPY(tmp,rvar); func = sevarGetFunction(call,rvar); # if 0!=JSE_MEMEXT_MEMBERS if ( NULL != SEOBJECTMEM_PTR(rvarmem) ) SEOBJECTMEM_UNLOCK_R(rvarmem); # endif } else { if( thisVar ) { tmp2 = seapiGetValue(call,thisVar); SEVAR_COPY(tmp,tmp2); } else { SEVAR_INIT_OBJECT(tmp,CALL_GLOBAL(call)); } func = sevarGetFunction(call,rvar); tmp = STACK_PUSH; SEVAR_COPY(tmp,rvar); } # if ( 0 < JSE_API_ASSERTLEVEL ) if ( NULL == func ) { STACK_POPX(2); SetLastApiError( UNISTR("%s: parameter 2 not a function"),ThisFuncName ); return False; } # endif assert( NULL != func ); /* transfer the parameters to the real stack */ if( jsestack!=NULL ) { origdepth = depth = SECALLSTACK_DEPTH(jsestack); while( depth-- ) { /* top of the stack is 0 */ jseVariable param = SECALLSTACK_PEEK(jsestack,depth); wSEVar onstack; uword8 varAttrib = 0; uint index = origdepth-depth-1; if( FUNCTION_IS_LOCAL(func) && index < ((struct LocalFunction*)func)->InputParameterCount) { varAttrib = ((struct LocalFunction*)func)->items[index].VarAttrib; assert(varAttrib == 0 || varAttrib == 1); } onstack = STACK_PUSH; if( varAttrib==0 && !FUNCTION_C_BEHAVIOR(func) ) { rSEVar val = seapiGetValue(call,param); SEVAR_COPY(onstack,val); } else { /* Pass by reference */ SEVAR_COPY(onstack,&(param->value)); } } } /* Normally, if we just call a function, the system will think we * are just another script function, and will treat errors like * we are in the context of our parent - it won't realize we are * an API function that gets to specifically determine whether or * not to trap errors and will instead try to determine the context * of the error and if it should be printed from the state of our * parent. That is wrong. Therefore, we turn off error printing * so the error will always be trapped, then when we get here, * we can go ahead and make sure the error gets printed. If we * did not do so, and our parents were trapping errors, then we * would also always trap errors. Since the API params determines whether * or not he wants to trap the error, that should be the determining * case, not the context of the parent. */ call->mustPrintError = False; callFunctionFully(call,(uword16)((jsestack==NULL)?0:SECALLSTACK_DEPTH(jsestack)), (flags&JSE_FUNC_CONSTRUCT)!=0); call->mustPrintError = old_must; retbool = !CALL_ERROR(call); ret = retbool?STACK0:&(call->error_var); if( retvar ) *retvar = NULL; if( retvar && (retbool || (flags&JSE_FUNC_TRAP_ERRORS)!=0) ) { /* If the stack is non-null, we stuff it on there, so it * is to be destroyed (when the stack exits.) Alternately, * we have no stack to put it on, so make it a tempvar. */ *retvar = SEAPI_RETURN(call,ret,jsestack!=NULL,UNISTR("jseCallFunctionEx")); if( jsestack ) { secallstackPush(/*call,*/jsestack,*retvar,True); } } else { if( !retbool ) { /* error deliberately trapped above, else we will get confused * by the stuff that has called on us, when we shouldn't - * if we are inside a try/catch block, that is irrelevent because * we are called by an API who gets to specify whether or not * trapping should occur. * * In this case, we must print the error. */ call->mustPrintError = True; callPrintError(call); call->mustPrintError = old_must; CALL_SET_ERROR(call,FlowNoReasonToQuit); } } STACK_POP; CALL_SET_ERROR(call,FlowNoReasonToQuit); call->errorPrinted = False; return retbool; } #if (0!=JSE_CREATEFUNCTIONTEXTVARIABLE) #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jseVariable ) jseReallyCreateFunctionTextVariable(jseContext call,jseVariable FuncVar, char *FILE,int LINE) #else JSECALLSEQ( jseVariable ) jseCreateFunctionTextVariable(jseContext call,jseVariable FuncVar) #endif { const struct Function *func; rSEVar v; jseVariable ret; rSEObjectMem rMem; JSE_API_STRING(ThisFuncName,"jseCreateFunctionTextVariable"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return NULL); assert( call->next==NULL ); v = jselibFindFunction(call,seapiGetValue(call,FuncVar),&func,NULL,&rMem); # if ( 0 < JSE_API_ASSERTLEVEL ) if ( NULL == v ) { SetLastApiError( UNISTR("%s: parameter 2 not a function"),ThisFuncName ); return NULL; } # endif assert( NULL != v ); assert( NULL != func ); /* we only want the function so free up the variable */ functionTextAsVariable(func,call,0); v = STACK0; ret = SEAPI_RETURN(call,v,TRUE,UNISTR("jseCreateFunctionTextVariable")); STACK_POP; # if 0!=JSE_MEMEXT_MEMBERS if ( NULL != SEOBJECTMEM_PTR(rMem) ) SEOBJECTMEM_UNLOCK_R(rMem); # endif return ret; } #endif #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ(jseVariable) jseReallyCreateWrapperFunction(jseContext call, const jsecharptr functionName, void (JSE_CFUNC FAR_CALL *funcPtr)(jseContext jsecontext), sword8 minVariableCount, sword8 maxVariableCount, jseVarAttributes varAttributes, jseFuncAttributes funcAttributes, void _FAR_ *fData, char *FILE,int LINE) #else JSECALLSEQ(jseVariable) jseCreateWrapperFunction(jseContext call, const jsecharptr functionName, void (JSE_CFUNC FAR_CALL *funcPtr)(jseContext jsecontext), sword8 minVariableCount, sword8 maxVariableCount, jseVarAttributes varAttributes, jseFuncAttributes funcAttributes, void _FAR_ *fData) #endif { struct LibraryFunction *libfunc; wSEVar var; jseVariable ret; JSE_API_STRING(ThisFuncName,"jseCreateWrapperFunction"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return NULL); assert( call->next==NULL ); JSE_API_ASSERT_(functionName,2,ThisFuncName,return NULL); JSE_API_ASSERT_(funcPtr,3,ThisFuncName,return NULL); var = STACK_PUSH; SEVAR_INIT_BLANK_OBJECT(call,var); libfunc = libfuncNewWrapper(call,functionName,funcPtr, minVariableCount,maxVariableCount, varAttributes,funcAttributes,fData, var); seobjSetFunction(call,SEVAR_GET_OBJECT(var),(struct Function *)libfunc); ret = SEAPI_RETURN(call,var,TRUE,UNISTR("jseCreateWrapperFunction")); STACK_POP; return ret; } JSECALLSEQ( void ) jseTerminateExternalLink(jseContext call) { JSE_API_ASSERT_C(call,1,jseContext_cookie,UNISTR("jseTerminateExternalLink"), return); assert( call->next==NULL ); callDelete(call); } JSECALLSEQ( void ) jseDestroyStack(jseContext call,jseStack jsestack) { uint i; JSE_API_STRING(ThisFuncName,"jseDestroyStack"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); JSE_API_ASSERT_C(jsestack,2,jseStack_cookie,ThisFuncName,return); i = jsestack->Count; while ( i-- ) { if( jsestack->vars[i].free_on_del ) jseDestroyVariable(call,jsestack->vars[i].var); } # if ( 2 <= JSE_API_ASSERTLEVEL ) jsestack->cookie = 0; # endif jseMustFree(jsestack->vars); jseMustFree(jsestack); } #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ(jseVariable) jseReallyPop(jseContext call, jseStack jsestack,char *FILE,int LINE) #else JSECALLSEQ(jseVariable) jsePop(jseContext call, jseStack jsestack) #endif { jseVariable ret; JSE_API_STRING(ThisFuncName,"jsePop"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return NULL); assert( call->next==NULL ); JSE_API_ASSERT_C(jsestack,2,jseStack_cookie,ThisFuncName,return NULL); jsestack->Count--; ret = SEAPI_RETURN(call,&(jsestack->vars[jsestack->Count].var->value),TRUE,UNISTR("jsePop")); if( jsestack->vars[jsestack->Count].free_on_del ) jseDestroyVariable(call,jsestack->vars[jsestack->Count].var); return ret; } JSECALLSEQ(void) jseSetGlobalObject(jseContext call,jseVariable newGlobal) { rSEVar newVar; JSE_API_STRING(ThisFuncName,"jseSetGlobalObject"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); newVar = seapiGetValue(call,newGlobal); if( SEVAR_GET_TYPE(newVar)==VObject ) { CALL_SET_GLOBAL(call,SEVAR_GET_OBJECT(newVar)); } } #if (0!=JSE_ENABLE_DYNAMETH) JSECALLSEQ( jsebool ) jseEnableDynamicMethod(jseContext call,jseVariable obj, const jsecharptr methodName,jsebool enable) { #if 0 wSEVar var; VarName vName; jsebool was = False; /* if any parameters wrong assume false */ uword8 offFlag; uword8 tmp; JSE_API_STRING(ThisFuncName,"jseEnableDynamicMethod"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return False); assert( call->next==NULL ); JSE_API_ASSERT_(methodName,3,ThisFuncName,return NULL); vName = GrabStringTableEntryStrlen(call,methodName,&tmp); var = seapiGetValue(call,obj); if( VObject == SEVAR_GET_TYPE(var) ) { struct Global_ *global = call->Global; wSEObject obj; SEOBJECT_ASSIGN_LOCK_W(obj,SEVAR_GET_OBJECT(var)); /* find the offFlag that applies to this name (0 if not found) */ if( vName==STOCK_STRING(_delete) ) offFlag = OFF_DELETE_PROP; else if( vName==STOCK_STRING(_put) ) offFlag = OFF_PUT_PROP; else if( vName==STOCK_STRING(_canPut) ) offFlag = OFF_CANPUT_PROP; else if( vName==STOCK_STRING(_get) ) offFlag = OFF_GET_PROP; else if( vName==STOCK_STRING(_hasProperty) ) offFlag = OFF_HAS_PROP; # if defined(JSE_OPERATOR_OVERLOADING) && (0!=JSE_OPERATOR_OVERLOADING) else if( vName==STOCK_STRING(_operator) ) offFlag = OFF_OPERATOR_PROP; # endif else offFlag = 0; if ( 0 != offFlag ) { /* was it enabled (not disabled) */ was = ( 0 == (SEOBJECT_PTR(obj)->flags & offFlag) ); /* if enable then turn off offFlag, else turn the flag on */ if ( enable ) { SEOBJECT_PTR(obj)->flags &= ~offFlag; } else { SEOBJECT_PTR(obj)->flags |= offFlag; } } SEOBJECT_UNLOCK_W(obj); } ReleaseStringTableEntry(/*call,*/vName,tmp); return was; #else return True; #endif } #endif /* ---------------------------------------------------------------------- */ #if !defined(NDEBUG) && defined(JSE_TRACKVARS) && JSE_TRACKVARS==1 JSECALLSEQ( jsebool ) jseReallyCallStackInfo(jseContext call,struct jseStackInfo *info,uint depth, char *FILE,int LINE) #else JSECALLSEQ( jsebool ) jseCallStackInfo(jseContext call,struct jseStackInfo *info,uint depth) #endif { rSEVar func; struct Function *funcptr; wSEVar fptr; hSEObject hvarobj; uword16 num_args; struct TryBlock *tries; wSEVar tmp; rSEObject rfuncobj; rSEObject rCallScopeChain; rSEMembers rMembers; MemCountUInt scope_chain_loc; # if JSE_MEMEXT_SECODES==1 ulong iptr_offset; # else secode iptr; # endif jsecharptr fname; JSE_API_STRING(ThisFuncName,"jseCallStackInfo"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return False); assert( call->next==NULL ); func = FUNCVAR; fptr = FRAME; if( fptr==NULL ) return False; if( CALL_QUIT(call) ) return False; hvarobj = call->hVariableObject; num_args = call->num_args; SEOBJECT_ASSIGN_LOCK_R(rCallScopeChain,call->hScopeChain); scope_chain_loc = SEOBJECT_PTR(rCallScopeChain)->used-1; # if JSE_MEMEXT_SECODES==1 iptr_offset = call->iptr - call->base; # else iptr = call->iptr; # endif memset(info,0,sizeof(struct jseStackInfo)); SEMEMBERS_ASSIGN_LOCK_R(rMembers,SEOBJECT_PTR(rCallScopeChain)->hsemembers); while( scope_chain_loc>0 && SEMEMBERS_PTR(rMembers)[scope_chain_loc].value.type!=VNull ) scope_chain_loc--; while( depth-->0 ) { const struct Function *f = sevarGetFunction(call,func); if( FUNCTION_IS_LOCAL(f) ) { while( scope_chain_loc>0 && SEMEMBERS_PTR(rMembers)[scope_chain_loc].value.type!=VNull ) scope_chain_loc--; } # if JSE_MEMEXT_SECODES==1 iptr_offset = SEVAR_GET_STORAGE_LONG(fptr-IPTR_OFFSET); # else iptr = SEVAR_GET_STORAGE_PTR(fptr-IPTR_OFFSET); # endif num_args = (uword16)SEVAR_GET_STORAGE_LONG(fptr-ARGS_OFFSET); assert( sizeof(hvarobj) <= sizeof(void *) ); hvarobj = (hSEObject)SEVAR_GET_STORAGE_PTR(OLD_VAROBJ); # if defined(JSE_GROWABLE_STACK) && (0!=JSE_GROWABLE_STACK) fptr = STACK_FROM_STACKPTR(SEVAR_GET_STORAGE_LONG(fptr)); if( fptr==call->Global->growingStack ) # else fptr = SEVAR_GET_STORAGE_PTR(fptr); if( fptr==NULL ) # endif { SEOBJECT_UNLOCK_R(rCallScopeChain); return False; } /* restore func from stack */ func = fptr - (num_args + FUNC_OFFSET); } SEMEMBERS_UNLOCK_R(rMembers); tmp = STACK_PUSH; SEVAR_INIT_UNDEFINED(tmp); assert( SEVAR_GET_TYPE(func)==VObject ); SEOBJECT_ASSIGN_LOCK_R(rfuncobj,SEVAR_GET_OBJECT(func)); funcptr = SEOBJECT_PTR(rfuncobj)->func; SEOBJECT_UNLOCK_R(rfuncobj); assert( funcptr!=NULL ); info->wrapper = !FUNCTION_IS_LOCAL(funcptr); info->function = SEAPI_RETURN(call,func,TRUE,UNISTR("jseCallStackInfo")); fname = functionName(funcptr,call); info->funcname = StrCpyMalloc(LFOM(fname)); UFOM(fname); if( !call->mustPrintError ) { info->trapped = True; } else { info->trapped = False; for( tries = call->tries; tries!=NULL; tries = tries->prev ) { if( !tries->incatch && tries->catch!=(ADDR_TYPE)-1 && STACK_FROM_STACKPTR(tries->fptr)<=fptr ) { /* found a trap */ info->trapped = True; break; } } } # if 0 != JSE_MULTIPLE_GLOBAL SEVAR_INIT_OBJECT(tmp,funcptr->hglobal_object?funcptr->hglobal_object:call->hGlobalObject); # else SEVAR_INIT_OBJECT(tmp,call->hGlobalObject); # endif info->global = SEAPI_RETURN(call,tmp,TRUE,UNISTR("jseCallStackInfo")); info->filename = UNISTR("no filename"); info->linenumber = 0; if( info->wrapper ) { info->linkdata = (Func_StaticLibrary & funcptr->flags) ? *(((struct LibraryFunction *)funcptr)->LibData.DataPtr) : ((struct LibraryFunction *)funcptr)->LibData.Data; /* return the global also as the var obj */ info->varObj = SEAPI_RETURN(call,tmp,TRUE,UNISTR("jseCallStackInfo")); info->scopeChain = NULL; } else { /* first find the source location */ wSEObjectMem wMem; hSEObject hssc; wSEObject wTmp; rSEMembers rMembers; secode sptr; # if JSE_MEMEXT_SECODES==1 secode base = jsememextLockRead(((struct LocalFunction *)funcptr)->op_handle, jseMemExtSecodeType); secode iptr = base + iptr_offset; # else secode base = ((struct LocalFunction *)funcptr)->opcodes; assert( (iptr-((struct LocalFunction *)funcptr)->opcodes)>=0 ); assert( (uint)(iptr-((struct LocalFunction *)funcptr)->opcodes)< ((struct LocalFunction *)funcptr)->opcodesUsed ); # endif for( sptr = base;sptr<=iptr;sptr++ ) { if ( seFilename == *sptr ) { info->filename = GetStringTableEntry(call,SECODE_GET_ONLY(sptr+1,VarName),NULL); break; } sptr += SECODE_DATUM_SIZE(*sptr); } /* search forward for next line number, it must be there */ for( sptr = iptr;;sptr++ ) { if ( seLineNumber == *sptr || seContinueFunc == *sptr ) { info->linenumber = SECODE_GET_ONLY(sptr+1,CONST_TYPE); break; } sptr += SECODE_DATUM_SIZE(*sptr); } # if JSE_MEMEXT_SECODES==1 jsememextUnlockRead(((struct LocalFunction *)funcptr)->op_handle,base,jseMemExtSecodeType); # endif /* Get the activation object */ SEVAR_INIT_OBJECT(tmp,hvarobj); info->varObj = SEAPI_RETURN(call,tmp,TRUE,UNISTR("jseCallStackInfo")); /* get the scope chain and free it below. */ SEVAR_INIT_OBJECT(tmp,seobjNew(call,False)); info->scopeChain = SEAPI_RETURN(call,tmp,TRUE,UNISTR("jseCallStackInfo")); SEOBJECT_ASSIGN_LOCK_W(wTmp,SEVAR_GET_OBJECT(tmp)); SEMEMBERS_ASSIGN_LOCK_W(rMembers,SEOBJECT_PTR(rCallScopeChain)->hsemembers); if( SEMEMBERS_PTR(rMembers)[scope_chain_loc].value.type==VNull ) { while( 1 ) { scope_chain_loc++; if( scope_chain_loc>=SEOBJECT_PTR(rCallScopeChain)->used || SEMEMBERS_PTR(rMembers)[scope_chain_loc].value.type==VNull ) { break; } /* add a new entry */ seobjCreateMemberCopy(NULL,call,wTmp,NULL, &(SEMEMBERS_PTR(rMembers)[scope_chain_loc].value)); } } SEMEMBERS_UNLOCK_R(rMembers); if( (hssc = func->data.object_val.hSavedScopeChain)!=hSEObjectNull ) { uint lookin; rSEObject rssc; SEOBJECT_ASSIGN_LOCK_R(rssc,hssc); if (SEOBJECT_PTR(rssc)->used != 0) { SEMEMBERS_ASSIGN_LOCK_R(rMembers,SEOBJECT_PTR(rssc)->hsemembers); for( lookin=0;lookin<SEOBJECT_PTR(rssc)->used;lookin++ ) { seobjCreateMemberCopy(NULL,call,wTmp,NULL, &(SEMEMBERS_PTR(rMembers)[lookin].value)); } SEMEMBERS_UNLOCK_R(rMembers); } SEOBJECT_UNLOCK_R(rssc); } wMem = SEOBJ_CREATE_MEMBER(call,wTmp,NULL); # if 0 != JSE_MULTIPLE_GLOBAL SEVAR_INIT_OBJECT(SEOBJECTMEM_VAR(wMem),funcptr->hglobal_object?funcptr->hglobal_object:call->hGlobalObject); # else SEVAR_INIT_OBJECT(SEOBJECTMEM_VAR(wMem),call->hGlobalObject); # endif SEOBJECTMEM_UNLOCK_W(wMem); SEOBJECT_UNLOCK_W(wTmp); } STACK_POP; tmp = (fptr-(THIS_OFFSET+num_args)); info->thisvar = SEAPI_RETURN(call,tmp,TRUE,UNISTR("jseCallStackInfo")); assert( info->filename!=NULL ); info->filename = StrCpyMalloc(info->filename); SEOBJECT_UNLOCK_R(rCallScopeChain); return True; } JSECALLSEQ( void ) jseFreeStackInfo(jseContext call,struct jseStackInfo *info) { JSE_API_STRING(ThisFuncName,"jseFreeStackInfo"); JSE_API_ASSERT_C(call,1,jseContext_cookie,ThisFuncName,return); assert( call->next==NULL ); jseDestroyVariable(call,info->function); jseDestroyVariable(call,info->global); jseDestroyVariable(call,info->thisvar); jseDestroyVariable(call,info->varObj); if( info->scopeChain!=NULL ) jseDestroyVariable(call,info->scopeChain); jseMustFree((void *)info->filename); jseMustFree((void *)info->funcname); } /* ---------------------------------------------------------------------- */ /* Get an internal representation of the original string, suitable * for passing to API functions that require a member name. You * must free that using 'jseFreeString' when finished with it */ JSECALLSEQ(jseString) jseInternalizeString(jseContext call,const jsecharptr str, JSE_POINTER_UINDEX len) { uword8 tmp; VarName result = GrabStringTableEntry(call,str,(stringLengthType)len,&tmp); jseString ret = callApiStringEntry(call,result); ReleaseStringTableEntry(/*call,*/result,tmp); return ret; } JSECALLSEQ(const jsecharptr) jseGetInternalString(jseContext call,jseString str, JSE_POINTER_UINDEX *len) { struct api_string *it = (struct api_string *)str; const jsecharptr ret; /* In case the user messed up, make the check */ if( it>=call->Global->api_strings && it<(call->Global->api_strings + call->Global->api_strings_used) ) { stringLengthType alen; /* Note, JSE_POINTER_UINDEX and stringLengthType can be different * so cannot merge the call */ ret = GetStringTableEntry(call,it->name,&alen); if( len ) *len = alen; } else { assert( False ); ret = NULL; } return ret; } JSECALLSEQ(void) jseFreeInternalString(jseContext call,jseString str) { struct api_string *it = (struct api_string *)str; /* In case the user messed up, make the check */ if( it>=call->Global->api_strings && it<(call->Global->api_strings + call->Global->api_strings_used) ) { callRemoveApiStringEntry(call,it); } else { assert( False ); } }
97d46636863510cbaa6ae417e7628a023d9035be
69db0de8c61c7cba691193edd3f087fdb54351c2
/src/data/object_events/object_event_anims.h
cd6a8a04b67c022aef0874405a887c0f3ee6769d
[]
no_license
pret/pokefirered
5363c332321c7650d4c85be6aa2e8baf3acda162
f8741615bfa0123e38680f30103f217c269ec96a
refs/heads/master
2023-08-31T15:22:19.498797
2023-08-31T15:15:29
2023-08-31T15:15:29
115,841,713
847
709
null
2023-09-12T22:48:38
2017-12-31T04:07:51
C
UTF-8
C
false
false
37,750
h
object_event_anims.h
static const union AnimCmd sAnim_StayStill[] = { ANIMCMD_FRAME(0, 8), ANIMCMD_FRAME(0, 8), ANIMCMD_FRAME(0, 8), ANIMCMD_FRAME(0, 8), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpFaceSouth[] = { ANIMCMD_FRAME(0, 16), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpFaceNorth[] = { ANIMCMD_FRAME(1, 16), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpFaceWest[] = { ANIMCMD_FRAME(2, 16), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpFaceEast[] = { ANIMCMD_FRAME(2, 16, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoSouth[] = { ANIMCMD_FRAME(3, 8), ANIMCMD_FRAME(0, 8), ANIMCMD_FRAME(3, 8, .hFlip = TRUE), ANIMCMD_FRAME(0, 8), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoNorth[] = { ANIMCMD_FRAME(4, 8), ANIMCMD_FRAME(1, 8), ANIMCMD_FRAME(4, 8, .hFlip = TRUE), ANIMCMD_FRAME(1, 8), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoWest[] = { ANIMCMD_FRAME(5, 8), ANIMCMD_FRAME(2, 8), ANIMCMD_FRAME(6, 8), ANIMCMD_FRAME(2, 8), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoEast[] = { ANIMCMD_FRAME(5, 8, .hFlip = TRUE), ANIMCMD_FRAME(2, 8, .hFlip = TRUE), ANIMCMD_FRAME(6, 8, .hFlip = TRUE), ANIMCMD_FRAME(2, 8, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoFastSouth[] = { ANIMCMD_FRAME(3, 4), ANIMCMD_FRAME(0, 4), ANIMCMD_FRAME(3, 4, .hFlip = TRUE), ANIMCMD_FRAME(0, 4), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoFastNorth[] = { ANIMCMD_FRAME(4, 4), ANIMCMD_FRAME(1, 4), ANIMCMD_FRAME(4, 4, .hFlip = TRUE), ANIMCMD_FRAME(1, 4), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoFastWest[] = { ANIMCMD_FRAME(5, 4), ANIMCMD_FRAME(2, 4), ANIMCMD_FRAME(6, 4), ANIMCMD_FRAME(2, 4), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoFastEast[] = { ANIMCMD_FRAME(5, 4, .hFlip = TRUE), ANIMCMD_FRAME(2, 4, .hFlip = TRUE), ANIMCMD_FRAME(6, 4, .hFlip = TRUE), ANIMCMD_FRAME(2, 4, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoFasterSouth[] = { ANIMCMD_FRAME(3, 2), ANIMCMD_FRAME(0, 2), ANIMCMD_FRAME(3, 2, .hFlip = TRUE), ANIMCMD_FRAME(0, 2), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoFasterNorth[] = { ANIMCMD_FRAME(4, 2), ANIMCMD_FRAME(1, 2), ANIMCMD_FRAME(4, 2, .hFlip = TRUE), ANIMCMD_FRAME(1, 2), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoFasterWest[] = { ANIMCMD_FRAME(5, 2), ANIMCMD_FRAME(2, 2), ANIMCMD_FRAME(6, 2), ANIMCMD_FRAME(2, 2), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoFasterEast[] = { ANIMCMD_FRAME(5, 2, .hFlip = TRUE), ANIMCMD_FRAME(2, 2, .hFlip = TRUE), ANIMCMD_FRAME(6, 2, .hFlip = TRUE), ANIMCMD_FRAME(2, 2, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoFastestSouth[] = { ANIMCMD_FRAME(3, 1), ANIMCMD_FRAME(0, 1), ANIMCMD_FRAME(3, 1, .hFlip = TRUE), ANIMCMD_FRAME(0, 1), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoFastestNorth[] = { ANIMCMD_FRAME(4, 1), ANIMCMD_FRAME(1, 1), ANIMCMD_FRAME(4, 1, .hFlip = TRUE), ANIMCMD_FRAME(1, 1), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoFastestWest[] = { ANIMCMD_FRAME(5, 1), ANIMCMD_FRAME(2, 1), ANIMCMD_FRAME(6, 1), ANIMCMD_FRAME(2, 1), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_QuintyPlumpGoFastestEast[] = { ANIMCMD_FRAME(5, 1, .hFlip = TRUE), ANIMCMD_FRAME(2, 1, .hFlip = TRUE), ANIMCMD_FRAME(6, 1, .hFlip = TRUE), ANIMCMD_FRAME(2, 1, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_FaceSouth[] = { ANIMCMD_FRAME(0, 16), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_FaceNorth[] = { ANIMCMD_FRAME(1, 16), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_FaceWest[] = { ANIMCMD_FRAME(2, 16), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_FaceEast[] = { ANIMCMD_FRAME(2, 16, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoSouth[] = { ANIMCMD_FRAME(3, 8), ANIMCMD_FRAME(0, 8), ANIMCMD_FRAME(4, 8), ANIMCMD_FRAME(0, 8), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoNorth[] = { ANIMCMD_FRAME(5, 8), ANIMCMD_FRAME(1, 8), ANIMCMD_FRAME(6, 8), ANIMCMD_FRAME(1, 8), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoWest[] = { ANIMCMD_FRAME(7, 8), ANIMCMD_FRAME(2, 8), ANIMCMD_FRAME(8, 8), ANIMCMD_FRAME(2, 8), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoEast[] = { ANIMCMD_FRAME(7, 8, .hFlip = TRUE), ANIMCMD_FRAME(2, 8, .hFlip = TRUE), ANIMCMD_FRAME(8, 8, .hFlip = TRUE), ANIMCMD_FRAME(2, 8, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoFastSouth[] = { ANIMCMD_FRAME(3, 4), ANIMCMD_FRAME(0, 4), ANIMCMD_FRAME(4, 4), ANIMCMD_FRAME(0, 4), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoFastNorth[] = { ANIMCMD_FRAME(5, 4), ANIMCMD_FRAME(1, 4), ANIMCMD_FRAME(6, 4), ANIMCMD_FRAME(1, 4), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoFastWest[] = { ANIMCMD_FRAME(7, 4), ANIMCMD_FRAME(2, 4), ANIMCMD_FRAME(8, 4), ANIMCMD_FRAME(2, 4), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoFastEast[] = { ANIMCMD_FRAME(7, 4, .hFlip = TRUE), ANIMCMD_FRAME(2, 4, .hFlip = TRUE), ANIMCMD_FRAME(8, 4, .hFlip = TRUE), ANIMCMD_FRAME(2, 4, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoFasterSouth[] = { ANIMCMD_FRAME(3, 2), ANIMCMD_FRAME(0, 2), ANIMCMD_FRAME(4, 2), ANIMCMD_FRAME(0, 2), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoFasterNorth[] = { ANIMCMD_FRAME(5, 2), ANIMCMD_FRAME(1, 2), ANIMCMD_FRAME(6, 2), ANIMCMD_FRAME(1, 2), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoFasterWest[] = { ANIMCMD_FRAME(7, 2), ANIMCMD_FRAME(2, 2), ANIMCMD_FRAME(8, 2), ANIMCMD_FRAME(2, 2), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoFasterEast[] = { ANIMCMD_FRAME(7, 2, .hFlip = TRUE), ANIMCMD_FRAME(2, 2, .hFlip = TRUE), ANIMCMD_FRAME(8, 2, .hFlip = TRUE), ANIMCMD_FRAME(2, 2, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoFastestSouth[] = { ANIMCMD_FRAME(3, 1), ANIMCMD_FRAME(0, 1), ANIMCMD_FRAME(4, 1), ANIMCMD_FRAME(0, 1), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoFastestNorth[] = { ANIMCMD_FRAME(5, 1), ANIMCMD_FRAME(1, 1), ANIMCMD_FRAME(6, 1), ANIMCMD_FRAME(1, 1), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoFastestWest[] = { ANIMCMD_FRAME(7, 1), ANIMCMD_FRAME(2, 1), ANIMCMD_FRAME(8, 1), ANIMCMD_FRAME(2, 1), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GoFastestEast[] = { ANIMCMD_FRAME(7, 1, .hFlip = TRUE), ANIMCMD_FRAME(2, 1, .hFlip = TRUE), ANIMCMD_FRAME(8, 1, .hFlip = TRUE), ANIMCMD_FRAME(2, 1, .hFlip = TRUE), ANIMCMD_JUMP(0), }; // For indicating a VS Seeker rematch static const union AnimCmd sAnim_RaiseHand[] = { ANIMCMD_FRAME(9, 0), ANIMCMD_END, }; static const union AnimCmd sAnim_HoOhFlapWings[] = { ANIMCMD_FRAME(3, 8), ANIMCMD_FRAME(4, 8), ANIMCMD_FRAME(3, 8), ANIMCMD_FRAME(4, 8), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_HoOhStayStill[] = { ANIMCMD_FRAME(3, 16), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_SurfFaceSouth[] = { ANIMCMD_FRAME(0, 60), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_SurfFaceNorth[] = { ANIMCMD_FRAME(1, 60), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_SurfFaceWest[] = { ANIMCMD_FRAME(2, 60), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_SurfFaceEast[] = { ANIMCMD_FRAME(2, 60, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownFaceSouth[] = { ANIMCMD_FRAME(0, 16), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownFaceNorth[] = { ANIMCMD_FRAME(1, 16), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownFaceWest[] = { ANIMCMD_FRAME(2, 16), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownFaceEast[] = { ANIMCMD_FRAME(2, 16, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoSouth[] = { ANIMCMD_FRAME(3, 4), ANIMCMD_FRAME(4, 4), ANIMCMD_FRAME(3, 4), ANIMCMD_FRAME(0, 4), ANIMCMD_FRAME(5, 4), ANIMCMD_FRAME(6, 4), ANIMCMD_FRAME(5, 4), ANIMCMD_FRAME(0, 4), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoNorth[] = { ANIMCMD_FRAME(7, 4), ANIMCMD_FRAME(8, 4), ANIMCMD_FRAME(7, 4), ANIMCMD_FRAME(1, 4), ANIMCMD_FRAME(9, 4), ANIMCMD_FRAME(10, 4), ANIMCMD_FRAME(9, 4), ANIMCMD_FRAME(1, 4), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoWest[] = { ANIMCMD_FRAME(11, 4), ANIMCMD_FRAME(12, 4), ANIMCMD_FRAME(11, 4), ANIMCMD_FRAME(2, 4), ANIMCMD_FRAME(13, 4), ANIMCMD_FRAME(14, 4), ANIMCMD_FRAME(13, 4), ANIMCMD_FRAME(2, 4), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoEast[] = { ANIMCMD_FRAME(11, 4, .hFlip = TRUE), ANIMCMD_FRAME(12, 4, .hFlip = TRUE), ANIMCMD_FRAME(11, 4, .hFlip = TRUE), ANIMCMD_FRAME(2, 4, .hFlip = TRUE), ANIMCMD_FRAME(13, 4, .hFlip = TRUE), ANIMCMD_FRAME(14, 4, .hFlip = TRUE), ANIMCMD_FRAME(13, 4, .hFlip = TRUE), ANIMCMD_FRAME(2, 4, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoFastNorth[] = { ANIMCMD_FRAME(3, 2), ANIMCMD_FRAME(4, 2), ANIMCMD_FRAME(3, 2), ANIMCMD_FRAME(0, 2), ANIMCMD_FRAME(5, 2), ANIMCMD_FRAME(6, 2), ANIMCMD_FRAME(5, 2), ANIMCMD_FRAME(0, 2), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoFastSouth[] = { ANIMCMD_FRAME(7, 2), ANIMCMD_FRAME(8, 2), ANIMCMD_FRAME(7, 2), ANIMCMD_FRAME(1, 2), ANIMCMD_FRAME(9, 2), ANIMCMD_FRAME(10, 2), ANIMCMD_FRAME(9, 2), ANIMCMD_FRAME(1, 2), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoFastWest[] = { ANIMCMD_FRAME(11, 2), ANIMCMD_FRAME(12, 2), ANIMCMD_FRAME(11, 2), ANIMCMD_FRAME(2, 2), ANIMCMD_FRAME(13, 2), ANIMCMD_FRAME(14, 2), ANIMCMD_FRAME(13, 2), ANIMCMD_FRAME(2, 2), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoFastEast[] = { ANIMCMD_FRAME(11, 2, .hFlip = TRUE), ANIMCMD_FRAME(12, 2, .hFlip = TRUE), ANIMCMD_FRAME(11, 2, .hFlip = TRUE), ANIMCMD_FRAME(2, 2, .hFlip = TRUE), ANIMCMD_FRAME(13, 2, .hFlip = TRUE), ANIMCMD_FRAME(14, 2, .hFlip = TRUE), ANIMCMD_FRAME(13, 2, .hFlip = TRUE), ANIMCMD_FRAME(2, 2, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoFasterNorth[] = { ANIMCMD_FRAME(3, 1), ANIMCMD_FRAME(4, 1), ANIMCMD_FRAME(3, 1), ANIMCMD_FRAME(0, 1), ANIMCMD_FRAME(5, 1), ANIMCMD_FRAME(6, 1), ANIMCMD_FRAME(5, 1), ANIMCMD_FRAME(0, 1), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoFasterSouth[] = { ANIMCMD_FRAME(7, 1), ANIMCMD_FRAME(8, 1), ANIMCMD_FRAME(7, 1), ANIMCMD_FRAME(1, 1), ANIMCMD_FRAME(9, 1), ANIMCMD_FRAME(10, 1), ANIMCMD_FRAME(9, 1), ANIMCMD_FRAME(1, 1), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoFasterWest[] = { ANIMCMD_FRAME(11, 1), ANIMCMD_FRAME(12, 1), ANIMCMD_FRAME(11, 1), ANIMCMD_FRAME(2, 1), ANIMCMD_FRAME(13, 1), ANIMCMD_FRAME(14, 1), ANIMCMD_FRAME(13, 1), ANIMCMD_FRAME(2, 1), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoFasterEast[] = { ANIMCMD_FRAME(11, 1, .hFlip = TRUE), ANIMCMD_FRAME(12, 1, .hFlip = TRUE), ANIMCMD_FRAME(11, 1, .hFlip = TRUE), ANIMCMD_FRAME(2, 1, .hFlip = TRUE), ANIMCMD_FRAME(13, 1, .hFlip = TRUE), ANIMCMD_FRAME(14, 1, .hFlip = TRUE), ANIMCMD_FRAME(13, 1, .hFlip = TRUE), ANIMCMD_FRAME(2, 1, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoFastestNorth[] = { ANIMCMD_FRAME(3, 0), ANIMCMD_FRAME(4, 0), ANIMCMD_FRAME(3, 0), ANIMCMD_FRAME(0, 0), ANIMCMD_FRAME(5, 0), ANIMCMD_FRAME(6, 0), ANIMCMD_FRAME(5, 0), ANIMCMD_FRAME(0, 0), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoFastestSouth[] = { ANIMCMD_FRAME(7, 0), ANIMCMD_FRAME(8, 0), ANIMCMD_FRAME(7, 0), ANIMCMD_FRAME(1, 0), ANIMCMD_FRAME(9, 0), ANIMCMD_FRAME(10, 0), ANIMCMD_FRAME(9, 0), ANIMCMD_FRAME(1, 0), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoFastestWest[] = { ANIMCMD_FRAME(11, 0), ANIMCMD_FRAME(12, 0), ANIMCMD_FRAME(11, 0), ANIMCMD_FRAME(2, 0), ANIMCMD_FRAME(13, 0), ANIMCMD_FRAME(14, 0), ANIMCMD_FRAME(13, 0), ANIMCMD_FRAME(2, 0), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_UnknownGoFastestEast[] = { ANIMCMD_FRAME(11, 0, .hFlip = TRUE), ANIMCMD_FRAME(12, 0, .hFlip = TRUE), ANIMCMD_FRAME(11, 0, .hFlip = TRUE), ANIMCMD_FRAME(2, 0, .hFlip = TRUE), ANIMCMD_FRAME(13, 0, .hFlip = TRUE), ANIMCMD_FRAME(14, 0, .hFlip = TRUE), ANIMCMD_FRAME(13, 0, .hFlip = TRUE), ANIMCMD_FRAME(2, 0, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_SpinSouth[] = { ANIMCMD_FRAME(0, 2), ANIMCMD_FRAME(2, 2, .hFlip = TRUE), ANIMCMD_FRAME(1, 2), ANIMCMD_FRAME(2, 2), ANIMCMD_LOOP(1), ANIMCMD_END, }; static const union AnimCmd sAnim_SpinNorth[] = { ANIMCMD_FRAME(1, 2), ANIMCMD_FRAME(2, 2), ANIMCMD_FRAME(0, 2), ANIMCMD_FRAME(2, 2, .hFlip = TRUE), ANIMCMD_LOOP(1), ANIMCMD_END, }; static const union AnimCmd sAnim_SpinWest[] = { ANIMCMD_FRAME(2, 2, .hFlip = TRUE), // Starts by facing East? ANIMCMD_FRAME(1, 2), ANIMCMD_FRAME(2, 2), ANIMCMD_FRAME(0, 2), ANIMCMD_LOOP(1), ANIMCMD_END, }; static const union AnimCmd sAnim_SpinEast[] = { ANIMCMD_FRAME(2, 2), // Starts by facing West? ANIMCMD_FRAME(0, 2), ANIMCMD_FRAME(2, 2, .hFlip = TRUE), ANIMCMD_FRAME(1, 2), ANIMCMD_LOOP(1), ANIMCMD_END, }; static const union AnimCmd sAnim_ShakeHeadOrWalkInPlace[] = { ANIMCMD_FRAME(18, 16), ANIMCMD_FRAME(0, 16), ANIMCMD_FRAME(19, 16), ANIMCMD_FRAME(0, 32), ANIMCMD_LOOP(1), ANIMCMD_END, }; static const union AnimCmd sAnim_RunSouth[] = { ANIMCMD_FRAME(9, 5), ANIMCMD_FRAME(10, 3), ANIMCMD_FRAME(9, 5), ANIMCMD_FRAME(11, 3), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_RunNorth[] = { ANIMCMD_FRAME(12, 5), ANIMCMD_FRAME(13, 3), ANIMCMD_FRAME(12, 5), ANIMCMD_FRAME(14, 3), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_RunWest[] = { ANIMCMD_FRAME(15, 5), ANIMCMD_FRAME(16, 3), ANIMCMD_FRAME(15, 5), ANIMCMD_FRAME(17, 3), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_RunEast[] = { ANIMCMD_FRAME(15, 5, .hFlip = TRUE), ANIMCMD_FRAME(16, 3, .hFlip = TRUE), ANIMCMD_FRAME(15, 5, .hFlip = TRUE), ANIMCMD_FRAME(17, 3, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_FieldMove[] = { ANIMCMD_FRAME(0, 4), ANIMCMD_FRAME(1, 4), ANIMCMD_FRAME(2, 4), ANIMCMD_FRAME(3, 4), ANIMCMD_FRAME(4, 8), ANIMCMD_END, }; static const union AnimCmd sAnim_VSSeeker[] = { ANIMCMD_FRAME(0, 4), ANIMCMD_FRAME(1, 4), ANIMCMD_FRAME(5, 4), ANIMCMD_FRAME(6, 4), ANIMCMD_LOOP(0), ANIMCMD_FRAME(7, 4), ANIMCMD_FRAME(8, 4), ANIMCMD_LOOP(6), ANIMCMD_FRAME(6, 4), ANIMCMD_FRAME(1, 4), ANIMCMD_FRAME(0, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_VSSeekerBike[] = { ANIMCMD_FRAME(0, 4), ANIMCMD_FRAME(1, 4), ANIMCMD_FRAME(2, 4), ANIMCMD_FRAME(3, 4), ANIMCMD_LOOP(0), ANIMCMD_FRAME(4, 4), ANIMCMD_FRAME(5, 4), ANIMCMD_LOOP(6), ANIMCMD_FRAME(3, 4), ANIMCMD_FRAME(2, 4), ANIMCMD_FRAME(1, 4), ANIMCMD_FRAME(0, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_GetOnOffSurfSouth[] = { ANIMCMD_FRAME(9, 32), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GetOnOffSurfNorth[] = { ANIMCMD_FRAME(10, 32), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GetOnOffSurfWest[] = { ANIMCMD_FRAME(11, 32), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_GetOnOffSurfEast[] = { ANIMCMD_FRAME(11, 32, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_BunnyHopBackWheelSouth[] = { ANIMCMD_FRAME(15, 4), ANIMCMD_FRAME(16, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_BunnyHopBackWheelNorth[] = { ANIMCMD_FRAME(19, 4), ANIMCMD_FRAME(20, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_BunnyHopBackWheelWest[] = { ANIMCMD_FRAME(23, 4), ANIMCMD_FRAME(24, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_BunnyHopBackWheelEast[] = { ANIMCMD_FRAME(23, 4, .hFlip = TRUE), ANIMCMD_FRAME(24, 4, .hFlip = TRUE), ANIMCMD_END, }; static const union AnimCmd sAnim_BunnyHopFrontWheelSouth[] = { ANIMCMD_FRAME(17, 4), ANIMCMD_FRAME(18, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_BunnyHopFrontWheelNorth[] = { ANIMCMD_FRAME(21, 4), ANIMCMD_FRAME(22, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_BunnyHopFrontWheelWest[] = { ANIMCMD_FRAME(25, 4), ANIMCMD_FRAME(26, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_BunnyHopFrontWheelEast[] = { ANIMCMD_FRAME(25, 4, .hFlip = TRUE), ANIMCMD_FRAME(26, 4, .hFlip = TRUE), ANIMCMD_END, }; static const union AnimCmd sAnim_StandingWheelieBackWheelSouth[] = { ANIMCMD_FRAME(15, 4), ANIMCMD_FRAME(0, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_StandingWheelieBackWheelNorth[] = { ANIMCMD_FRAME(19, 4), ANIMCMD_FRAME(1, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_StandingWheelieBackWheelWest[] = { ANIMCMD_FRAME(23, 4), ANIMCMD_FRAME(2, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_StandingWheelieBackWheelEast[] = { ANIMCMD_FRAME(23, 4, .hFlip = TRUE), ANIMCMD_FRAME(2, 4, .hFlip = TRUE), ANIMCMD_END, }; static const union AnimCmd sAnim_StandingWheelieFrontWheelSouth[] = { ANIMCMD_FRAME(17, 4), ANIMCMD_FRAME(0, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_StandingWheelieFrontWheelNorth[] = { ANIMCMD_FRAME(21, 4), ANIMCMD_FRAME(1, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_StandingWheelieFrontWheelWest[] = { ANIMCMD_FRAME(25, 4), ANIMCMD_FRAME(2, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_StandingWheelieFrontWheelEast[] = { ANIMCMD_FRAME(25, 4, .hFlip = TRUE), ANIMCMD_FRAME(2, 4, .hFlip = TRUE), ANIMCMD_END, }; static const union AnimCmd sAnim_MovingWheelieSouth[] = { ANIMCMD_FRAME(27, 4), ANIMCMD_FRAME(16, 4), ANIMCMD_FRAME(28, 4), ANIMCMD_FRAME(16, 4), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_MovingWheelieNorth[] = { ANIMCMD_FRAME(29, 4), ANIMCMD_FRAME(20, 4), ANIMCMD_FRAME(30, 4), ANIMCMD_FRAME(20, 4), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_MovingWheelieWest[] = { ANIMCMD_FRAME(31, 4), ANIMCMD_FRAME(24, 4), ANIMCMD_FRAME(32, 4), ANIMCMD_FRAME(24, 4), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_MovingWheelieEast[] = { ANIMCMD_FRAME(31, 4, .hFlip = TRUE), ANIMCMD_FRAME(24, 4, .hFlip = TRUE), ANIMCMD_FRAME(32, 4, .hFlip = TRUE), ANIMCMD_FRAME(24, 4, .hFlip = TRUE), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_BerryTreeStage0[] = { ANIMCMD_FRAME(0, 32), ANIMCMD_END, }; static const union AnimCmd sAnim_BerryTreeStage1[] = { ANIMCMD_FRAME(1, 32), ANIMCMD_FRAME(2, 32), ANIMCMD_END, }; static const union AnimCmd sAnim_BerryTreeStage2[] = { ANIMCMD_FRAME(3, 48), ANIMCMD_FRAME(4, 48), ANIMCMD_END, }; static const union AnimCmd sAnim_BerryTreeStage3[] = { ANIMCMD_FRAME(5, 32), ANIMCMD_FRAME(5, 32), ANIMCMD_FRAME(6, 32), ANIMCMD_FRAME(6, 32), ANIMCMD_END, }; static const union AnimCmd sAnim_BerryTreeStage4[] = { ANIMCMD_FRAME(7, 48), ANIMCMD_FRAME(7, 48), ANIMCMD_FRAME(8, 48), ANIMCMD_FRAME(8, 48), ANIMCMD_END, }; static const union AnimCmd sAnim_NurseBow[] = { ANIMCMD_FRAME(0, 8), ANIMCMD_FRAME(9, 32), ANIMCMD_FRAME(0, 8), ANIMCMD_END, }; static const union AnimCmd sAnim_RockBreak[] = { ANIMCMD_FRAME(0, 8), ANIMCMD_FRAME(1, 8), ANIMCMD_FRAME(2, 8), ANIMCMD_FRAME(3, 8), ANIMCMD_END, }; static const union AnimCmd sAnim_TreeCut[] = { ANIMCMD_FRAME(0, 6), ANIMCMD_FRAME(1, 6), ANIMCMD_FRAME(2, 6), ANIMCMD_FRAME(3, 6), ANIMCMD_END, }; static const union AnimCmd sAnim_TakeOutRodSouth[] = { ANIMCMD_FRAME(8, 4), ANIMCMD_FRAME(9, 4), ANIMCMD_FRAME(10, 4), ANIMCMD_FRAME(11, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_TakeOutRodNorth[] = { ANIMCMD_FRAME(4, 4), ANIMCMD_FRAME(5, 4), ANIMCMD_FRAME(6, 4), ANIMCMD_FRAME(7, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_TakeOutRodWest[] = { ANIMCMD_FRAME(0, 4), ANIMCMD_FRAME(1, 4), ANIMCMD_FRAME(2, 4), ANIMCMD_FRAME(3, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_TakeOutRodEast[] = { ANIMCMD_FRAME(0, 4, .hFlip = TRUE), ANIMCMD_FRAME(1, 4, .hFlip = TRUE), ANIMCMD_FRAME(2, 4, .hFlip = TRUE), ANIMCMD_FRAME(3, 4, .hFlip = TRUE), ANIMCMD_END, }; static const union AnimCmd sAnim_PutAwayRodSouth[] = { ANIMCMD_FRAME(11, 4), ANIMCMD_FRAME(10, 6), ANIMCMD_FRAME(9, 6), ANIMCMD_FRAME(8, 6), ANIMCMD_END, }; static const union AnimCmd sAnim_PutAwayRodNorth[] = { ANIMCMD_FRAME(7, 4), ANIMCMD_FRAME(6, 6), ANIMCMD_FRAME(5, 6), ANIMCMD_FRAME(4, 6), ANIMCMD_END, }; static const union AnimCmd sAnim_PutAwayRodWest[] = { ANIMCMD_FRAME(3, 4), ANIMCMD_FRAME(2, 4), ANIMCMD_FRAME(1, 4), ANIMCMD_FRAME(0, 4), ANIMCMD_END, }; static const union AnimCmd sAnim_PutAwayRodEast[] = { ANIMCMD_FRAME(3, 4, .hFlip = TRUE), ANIMCMD_FRAME(2, 4, .hFlip = TRUE), ANIMCMD_FRAME(1, 4, .hFlip = TRUE), ANIMCMD_FRAME(0, 4, .hFlip = TRUE), ANIMCMD_END, }; static const union AnimCmd sAnim_HookedPokemonSouth[] = { ANIMCMD_FRAME(10, 6), ANIMCMD_FRAME(11, 6), ANIMCMD_LOOP(1), ANIMCMD_FRAME(11, 30), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_HookedPokemonNorth[] = { ANIMCMD_FRAME(6, 6), ANIMCMD_FRAME(7, 6), ANIMCMD_LOOP(1), ANIMCMD_FRAME(7, 30), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_HookedPokemonWest[] = { ANIMCMD_FRAME(2, 6), ANIMCMD_FRAME(3, 6), ANIMCMD_LOOP(1), ANIMCMD_FRAME(3, 30), ANIMCMD_JUMP(0), }; static const union AnimCmd sAnim_HookedPokemonEast[] = { ANIMCMD_FRAME(2, 6, .hFlip = TRUE), ANIMCMD_FRAME(3, 6, .hFlip = TRUE), ANIMCMD_LOOP(1), ANIMCMD_FRAME(3, 30, .hFlip = TRUE), ANIMCMD_JUMP(0), }; // Unused static const union AffineAnimCmd sAffineAnim_KyogreGroudon_GoSouthStart[] = { AFFINEANIMCMD_FRAME(0, 0, 1, 1), AFFINEANIMCMD_FRAME(0, 0, 0, 1), AFFINEANIMCMD_FRAME(0, 0, 0, 1), AFFINEANIMCMD_FRAME(0, 0, 0, 1), AFFINEANIMCMD_LOOP(7), AFFINEANIMCMD_JUMP(0), }; // Unused static const union AffineAnimCmd sAffineAnim_KyogreGroudon_GoSouth[] = { AFFINEANIMCMD_FRAME(0, 0, -1, 1), AFFINEANIMCMD_FRAME(0, 0, 0, 1), AFFINEANIMCMD_LOOP(15), AFFINEANIMCMD_FRAME(0, 0, 1, 1), AFFINEANIMCMD_FRAME(0, 0, 0, 1), AFFINEANIMCMD_LOOP(15), AFFINEANIMCMD_JUMP(0), }; static const union AnimCmd *const sAnimTable_Inanimate[] = { [ANIM_STAY_STILL] = sAnim_StayStill }; // Leftover from Ruby/Sapphire static const union AnimCmd *const sAnimTable_QuintyPlump[] = { [ANIM_STD_FACE_SOUTH] = sAnim_QuintyPlumpFaceSouth, [ANIM_STD_FACE_NORTH] = sAnim_QuintyPlumpFaceNorth, [ANIM_STD_FACE_WEST] = sAnim_QuintyPlumpFaceWest, [ANIM_STD_FACE_EAST] = sAnim_QuintyPlumpFaceEast, [ANIM_STD_GO_SOUTH] = sAnim_QuintyPlumpGoSouth, [ANIM_STD_GO_NORTH] = sAnim_QuintyPlumpGoNorth, [ANIM_STD_GO_WEST] = sAnim_QuintyPlumpGoWest, [ANIM_STD_GO_EAST] = sAnim_QuintyPlumpGoEast, [ANIM_STD_GO_FAST_SOUTH] = sAnim_QuintyPlumpGoFastSouth, [ANIM_STD_GO_FAST_NORTH] = sAnim_QuintyPlumpGoFastNorth, [ANIM_STD_GO_FAST_WEST] = sAnim_QuintyPlumpGoFastWest, [ANIM_STD_GO_FAST_EAST] = sAnim_QuintyPlumpGoFastEast, [ANIM_STD_GO_FASTER_SOUTH] = sAnim_QuintyPlumpGoFasterSouth, [ANIM_STD_GO_FASTER_NORTH] = sAnim_QuintyPlumpGoFasterNorth, [ANIM_STD_GO_FASTER_WEST] = sAnim_QuintyPlumpGoFasterWest, [ANIM_STD_GO_FASTER_EAST] = sAnim_QuintyPlumpGoFasterEast, [ANIM_STD_GO_FASTEST_SOUTH] = sAnim_QuintyPlumpGoFastestSouth, [ANIM_STD_GO_FASTEST_NORTH] = sAnim_QuintyPlumpGoFastestNorth, [ANIM_STD_GO_FASTEST_WEST] = sAnim_QuintyPlumpGoFastestWest, [ANIM_STD_GO_FASTEST_EAST] = sAnim_QuintyPlumpGoFastestEast, }; static const union AnimCmd *const sAnimTable_Standard[] = { [ANIM_STD_FACE_SOUTH] = sAnim_FaceSouth, [ANIM_STD_FACE_NORTH] = sAnim_FaceNorth, [ANIM_STD_FACE_WEST] = sAnim_FaceWest, [ANIM_STD_FACE_EAST] = sAnim_FaceEast, [ANIM_STD_GO_SOUTH] = sAnim_GoSouth, [ANIM_STD_GO_NORTH] = sAnim_GoNorth, [ANIM_STD_GO_WEST] = sAnim_GoWest, [ANIM_STD_GO_EAST] = sAnim_GoEast, [ANIM_STD_GO_FAST_SOUTH] = sAnim_GoFastSouth, [ANIM_STD_GO_FAST_NORTH] = sAnim_GoFastNorth, [ANIM_STD_GO_FAST_WEST] = sAnim_GoFastWest, [ANIM_STD_GO_FAST_EAST] = sAnim_GoFastEast, [ANIM_STD_GO_FASTER_SOUTH] = sAnim_GoFasterSouth, [ANIM_STD_GO_FASTER_NORTH] = sAnim_GoFasterNorth, [ANIM_STD_GO_FASTER_WEST] = sAnim_GoFasterWest, [ANIM_STD_GO_FASTER_EAST] = sAnim_GoFasterEast, [ANIM_STD_GO_FASTEST_SOUTH] = sAnim_GoFastestSouth, [ANIM_STD_GO_FASTEST_NORTH] = sAnim_GoFastestNorth, [ANIM_STD_GO_FASTEST_WEST] = sAnim_GoFastestWest, [ANIM_STD_GO_FASTEST_EAST] = sAnim_GoFastestEast, [ANIM_RAISE_HAND] = sAnim_RaiseHand, }; static const union AnimCmd *const sAnimTable_HoOh[] = { [ANIM_STD_FACE_SOUTH] = sAnim_FaceSouth, [ANIM_STD_FACE_NORTH] = sAnim_FaceNorth, [ANIM_STD_FACE_WEST] = sAnim_FaceWest, [ANIM_STD_FACE_EAST] = sAnim_FaceEast, [ANIM_STD_GO_SOUTH] = sAnim_HoOhFlapWings, [ANIM_STD_GO_NORTH] = sAnim_HoOhStayStill, [ANIM_STD_GO_WEST] = sAnim_GoWest, [ANIM_STD_GO_EAST] = sAnim_GoEast, [ANIM_STD_GO_FAST_SOUTH] = sAnim_GoFastSouth, [ANIM_STD_GO_FAST_NORTH] = sAnim_GoFastNorth, [ANIM_STD_GO_FAST_WEST] = sAnim_GoFastWest, [ANIM_STD_GO_FAST_EAST] = sAnim_GoFastEast, [ANIM_STD_GO_FASTER_SOUTH] = sAnim_GoFasterSouth, [ANIM_STD_GO_FASTER_NORTH] = sAnim_GoFasterNorth, [ANIM_STD_GO_FASTER_WEST] = sAnim_GoFasterWest, [ANIM_STD_GO_FASTER_EAST] = sAnim_GoFasterEast, [ANIM_STD_GO_FASTEST_SOUTH] = sAnim_GoFastestSouth, [ANIM_STD_GO_FASTEST_NORTH] = sAnim_GoFastestNorth, [ANIM_STD_GO_FASTEST_WEST] = sAnim_GoFastestWest, [ANIM_STD_GO_FASTEST_EAST] = sAnim_GoFastestEast, [ANIM_RAISE_HAND] = sAnim_RaiseHand, }; static const union AnimCmd *const sAnimTable_Unknown[] = { [ANIM_STD_FACE_SOUTH] = sAnim_UnknownFaceSouth, [ANIM_STD_FACE_NORTH] = sAnim_UnknownFaceNorth, [ANIM_STD_FACE_WEST] = sAnim_UnknownFaceWest, [ANIM_STD_FACE_EAST] = sAnim_UnknownFaceEast, [ANIM_STD_GO_SOUTH] = sAnim_UnknownGoSouth, [ANIM_STD_GO_NORTH] = sAnim_UnknownGoNorth, [ANIM_STD_GO_WEST] = sAnim_UnknownGoWest, [ANIM_STD_GO_EAST] = sAnim_UnknownGoEast, [ANIM_STD_GO_FAST_SOUTH] = sAnim_UnknownGoFastNorth, [ANIM_STD_GO_FAST_NORTH] = sAnim_UnknownGoFastSouth, [ANIM_STD_GO_FAST_WEST] = sAnim_UnknownGoFastWest, [ANIM_STD_GO_FAST_EAST] = sAnim_UnknownGoFastEast, [ANIM_STD_GO_FASTER_SOUTH] = sAnim_UnknownGoFasterNorth, [ANIM_STD_GO_FASTER_NORTH] = sAnim_UnknownGoFasterSouth, [ANIM_STD_GO_FASTER_WEST] = sAnim_UnknownGoFasterWest, [ANIM_STD_GO_FASTER_EAST] = sAnim_UnknownGoFasterEast, [ANIM_STD_GO_FASTEST_SOUTH] = sAnim_UnknownGoFastestNorth, [ANIM_STD_GO_FASTEST_NORTH] = sAnim_UnknownGoFastestSouth, [ANIM_STD_GO_FASTEST_WEST] = sAnim_UnknownGoFastestWest, [ANIM_STD_GO_FASTEST_EAST] = sAnim_UnknownGoFastestEast, [ANIM_RUN_SOUTH] = sAnim_RunSouth, [ANIM_RUN_NORTH] = sAnim_RunNorth, [ANIM_RUN_WEST] = sAnim_RunWest, [ANIM_RUN_EAST] = sAnim_RunEast, }; static const union AnimCmd *const sAnimTable_RedGreenNormal[] = { [ANIM_STD_FACE_SOUTH] = sAnim_FaceSouth, [ANIM_STD_FACE_NORTH] = sAnim_FaceNorth, [ANIM_STD_FACE_WEST] = sAnim_FaceWest, [ANIM_STD_FACE_EAST] = sAnim_FaceEast, [ANIM_STD_GO_SOUTH] = sAnim_GoSouth, [ANIM_STD_GO_NORTH] = sAnim_GoNorth, [ANIM_STD_GO_WEST] = sAnim_GoWest, [ANIM_STD_GO_EAST] = sAnim_GoEast, [ANIM_STD_GO_FAST_SOUTH] = sAnim_GoFastSouth, [ANIM_STD_GO_FAST_NORTH] = sAnim_GoFastNorth, [ANIM_STD_GO_FAST_WEST] = sAnim_GoFastWest, [ANIM_STD_GO_FAST_EAST] = sAnim_GoFastEast, [ANIM_STD_GO_FASTER_SOUTH] = sAnim_GoFasterSouth, [ANIM_STD_GO_FASTER_NORTH] = sAnim_GoFasterNorth, [ANIM_STD_GO_FASTER_WEST] = sAnim_GoFasterWest, [ANIM_STD_GO_FASTER_EAST] = sAnim_GoFasterEast, [ANIM_STD_GO_FASTEST_SOUTH] = sAnim_GoFastestSouth, [ANIM_STD_GO_FASTEST_NORTH] = sAnim_GoFastestNorth, [ANIM_STD_GO_FASTEST_WEST] = sAnim_GoFastestWest, [ANIM_STD_GO_FASTEST_EAST] = sAnim_GoFastestEast, [ANIM_RUN_SOUTH] = sAnim_RunSouth, [ANIM_RUN_NORTH] = sAnim_RunNorth, [ANIM_RUN_WEST] = sAnim_RunWest, [ANIM_RUN_EAST] = sAnim_RunEast, [ANIM_SPIN_SOUTH] = sAnim_SpinSouth, [ANIM_SPIN_NORTH] = sAnim_SpinNorth, [ANIM_SPIN_WEST] = sAnim_SpinWest, [ANIM_SPIN_EAST] = sAnim_SpinEast, [ANIM_SHAKE_HEAD_OR_WALK_IN_PLACE] = sAnim_ShakeHeadOrWalkInPlace, }; // Leftover from Ruby/Sapphire static const union AnimCmd *const sAnimTable_AcroBike[] = { [ANIM_STD_FACE_SOUTH] = sAnim_FaceSouth, [ANIM_STD_FACE_NORTH] = sAnim_FaceNorth, [ANIM_STD_FACE_WEST] = sAnim_FaceWest, [ANIM_STD_FACE_EAST] = sAnim_FaceEast, [ANIM_STD_GO_SOUTH] = sAnim_GoSouth, [ANIM_STD_GO_NORTH] = sAnim_GoNorth, [ANIM_STD_GO_WEST] = sAnim_GoWest, [ANIM_STD_GO_EAST] = sAnim_GoEast, [ANIM_STD_GO_FAST_SOUTH] = sAnim_GoFastSouth, [ANIM_STD_GO_FAST_NORTH] = sAnim_GoFastNorth, [ANIM_STD_GO_FAST_WEST] = sAnim_GoFastWest, [ANIM_STD_GO_FAST_EAST] = sAnim_GoFastEast, [ANIM_STD_GO_FASTER_SOUTH] = sAnim_GoFasterSouth, [ANIM_STD_GO_FASTER_NORTH] = sAnim_GoFasterNorth, [ANIM_STD_GO_FASTER_WEST] = sAnim_GoFasterWest, [ANIM_STD_GO_FASTER_EAST] = sAnim_GoFasterEast, [ANIM_STD_GO_FASTEST_SOUTH] = sAnim_GoFastestSouth, [ANIM_STD_GO_FASTEST_NORTH] = sAnim_GoFastestNorth, [ANIM_STD_GO_FASTEST_WEST] = sAnim_GoFastestWest, [ANIM_STD_GO_FASTEST_EAST] = sAnim_GoFastestEast, [ANIM_BUNNY_HOP_BACK_WHEEL_SOUTH] = sAnim_BunnyHopBackWheelSouth, [ANIM_BUNNY_HOP_BACK_WHEEL_NORTH] = sAnim_BunnyHopBackWheelNorth, [ANIM_BUNNY_HOP_BACK_WHEEL_WEST] = sAnim_BunnyHopBackWheelWest, [ANIM_BUNNY_HOP_BACK_WHEEL_EAST] = sAnim_BunnyHopBackWheelEast, [ANIM_BUNNY_HOP_FRONT_WHEEL_SOUTH] = sAnim_BunnyHopFrontWheelSouth, [ANIM_BUNNY_HOP_FRONT_WHEEL_NORTH] = sAnim_BunnyHopFrontWheelNorth, [ANIM_BUNNY_HOP_FRONT_WHEEL_WEST] = sAnim_BunnyHopFrontWheelWest, [ANIM_BUNNY_HOP_FRONT_WHEEL_EAST] = sAnim_BunnyHopFrontWheelEast, [ANIM_STANDING_WHEELIE_BACK_WHEEL_SOUTH] = sAnim_StandingWheelieBackWheelSouth, [ANIM_STANDING_WHEELIE_BACK_WHEEL_NORTH] = sAnim_StandingWheelieBackWheelNorth, [ANIM_STANDING_WHEELIE_BACK_WHEEL_WEST] = sAnim_StandingWheelieBackWheelWest, [ANIM_STANDING_WHEELIE_BACK_WHEEL_EAST] = sAnim_StandingWheelieBackWheelEast, [ANIM_STANDING_WHEELIE_FRONT_WHEEL_SOUTH] = sAnim_StandingWheelieFrontWheelSouth, [ANIM_STANDING_WHEELIE_FRONT_WHEEL_NORTH] = sAnim_StandingWheelieFrontWheelNorth, [ANIM_STANDING_WHEELIE_FRONT_WHEEL_WEST] = sAnim_StandingWheelieFrontWheelWest, [ANIM_STANDING_WHEELIE_FRONT_WHEEL_EAST] = sAnim_StandingWheelieFrontWheelEast, [ANIM_MOVING_WHEELIE_SOUTH] = sAnim_MovingWheelieSouth, [ANIM_MOVING_WHEELIE_NORTH] = sAnim_MovingWheelieNorth, [ANIM_MOVING_WHEELIE_WEST] = sAnim_MovingWheelieWest, [ANIM_MOVING_WHEELIE_EAST] = sAnim_MovingWheelieEast, }; static const union AnimCmd *const sAnimTable_RedGreenSurf[] = { [ANIM_STD_FACE_SOUTH] = sAnim_SurfFaceSouth, [ANIM_STD_FACE_NORTH] = sAnim_SurfFaceNorth, [ANIM_STD_FACE_WEST] = sAnim_SurfFaceWest, [ANIM_STD_FACE_EAST] = sAnim_SurfFaceEast, [ANIM_STD_GO_SOUTH] = sAnim_SurfFaceSouth, [ANIM_STD_GO_NORTH] = sAnim_SurfFaceNorth, [ANIM_STD_GO_WEST] = sAnim_SurfFaceWest, [ANIM_STD_GO_EAST] = sAnim_SurfFaceEast, [ANIM_STD_GO_FAST_SOUTH] = sAnim_SurfFaceSouth, [ANIM_STD_GO_FAST_NORTH] = sAnim_SurfFaceNorth, [ANIM_STD_GO_FAST_WEST] = sAnim_SurfFaceWest, [ANIM_STD_GO_FAST_EAST] = sAnim_SurfFaceEast, [ANIM_STD_GO_FASTER_SOUTH] = sAnim_SurfFaceSouth, [ANIM_STD_GO_FASTER_NORTH] = sAnim_SurfFaceNorth, [ANIM_STD_GO_FASTER_WEST] = sAnim_SurfFaceWest, [ANIM_STD_GO_FASTER_EAST] = sAnim_SurfFaceEast, [ANIM_STD_GO_FASTEST_SOUTH] = sAnim_SurfFaceSouth, [ANIM_STD_GO_FASTEST_NORTH] = sAnim_SurfFaceNorth, [ANIM_STD_GO_FASTEST_WEST] = sAnim_SurfFaceWest, [ANIM_STD_GO_FASTEST_EAST] = sAnim_SurfFaceEast, [ANIM_GET_ON_OFF_POKEMON_SOUTH] = sAnim_GetOnOffSurfSouth, [ANIM_GET_ON_OFF_POKEMON_NORTH] = sAnim_GetOnOffSurfNorth, [ANIM_GET_ON_OFF_POKEMON_WEST] = sAnim_GetOnOffSurfWest, [ANIM_GET_ON_OFF_POKEMON_EAST] = sAnim_GetOnOffSurfEast, }; static const union AnimCmd *const sAnimTable_Nurse[] = { [ANIM_STD_FACE_SOUTH] = sAnim_FaceSouth, [ANIM_STD_FACE_NORTH] = sAnim_FaceNorth, [ANIM_STD_FACE_WEST] = sAnim_FaceWest, [ANIM_STD_FACE_EAST] = sAnim_FaceEast, [ANIM_STD_GO_SOUTH] = sAnim_GoSouth, [ANIM_STD_GO_NORTH] = sAnim_GoNorth, [ANIM_STD_GO_WEST] = sAnim_GoWest, [ANIM_STD_GO_EAST] = sAnim_GoEast, [ANIM_STD_GO_FAST_SOUTH] = sAnim_GoFastSouth, [ANIM_STD_GO_FAST_NORTH] = sAnim_GoFastNorth, [ANIM_STD_GO_FAST_WEST] = sAnim_GoFastWest, [ANIM_STD_GO_FAST_EAST] = sAnim_GoFastEast, [ANIM_STD_GO_FASTER_SOUTH] = sAnim_GoFasterSouth, [ANIM_STD_GO_FASTER_NORTH] = sAnim_GoFasterNorth, [ANIM_STD_GO_FASTER_WEST] = sAnim_GoFasterWest, [ANIM_STD_GO_FASTER_EAST] = sAnim_GoFasterEast, [ANIM_STD_GO_FASTEST_SOUTH] = sAnim_GoFastestSouth, [ANIM_STD_GO_FASTEST_NORTH] = sAnim_GoFastestNorth, [ANIM_STD_GO_FASTEST_WEST] = sAnim_GoFastestWest, [ANIM_STD_GO_FASTEST_EAST] = sAnim_GoFastestEast, [ANIM_NURSE_BOW] = sAnim_NurseBow, }; static const union AnimCmd *const sAnimTable_RedGreenFieldMove[] = { [ANIM_FIELD_MOVE] = sAnim_FieldMove, }; static const union AnimCmd *const sAnimTable_RedGreenVSSeeker[] = { [ANIM_VS_SEEKER] = sAnim_VSSeeker, }; static const union AnimCmd *const sAnimTable_RedGreenVSSeekerBike[] = { [ANIM_VS_SEEKER] = sAnim_VSSeekerBike, }; // Unused static const union AnimCmd *const sAnimTable_BerryTree[] = { sAnim_BerryTreeStage0, sAnim_BerryTreeStage1, sAnim_BerryTreeStage2, sAnim_BerryTreeStage3, sAnim_BerryTreeStage4, }; static const union AnimCmd *const sAnimTable_RockSmashRock[] = { [ANIM_STAY_STILL] = sAnim_StayStill, [ANIM_REMOVE_OBSTACLE] = sAnim_RockBreak, }; static const union AnimCmd *const sAnimTable_CutTree[] = { [ANIM_STAY_STILL] = sAnim_StayStill, [ANIM_REMOVE_OBSTACLE] = sAnim_TreeCut, }; static const union AnimCmd *const sAnimTable_RedGreenFish[] = { [ANIM_TAKE_OUT_ROD_SOUTH] = sAnim_TakeOutRodSouth, [ANIM_TAKE_OUT_ROD_NORTH] = sAnim_TakeOutRodNorth, [ANIM_TAKE_OUT_ROD_WEST] = sAnim_TakeOutRodWest, [ANIM_TAKE_OUT_ROD_EAST] = sAnim_TakeOutRodEast, [ANIM_PUT_AWAY_ROD_SOUTH] = sAnim_PutAwayRodSouth, [ANIM_PUT_AWAY_ROD_NORTH] = sAnim_PutAwayRodNorth, [ANIM_PUT_AWAY_ROD_WEST] = sAnim_PutAwayRodWest, [ANIM_PUT_AWAY_ROD_EAST] = sAnim_PutAwayRodEast, [ANIM_HOOKED_POKEMON_SOUTH] = sAnim_HookedPokemonSouth, [ANIM_HOOKED_POKEMON_NORTH] = sAnim_HookedPokemonNorth, [ANIM_HOOKED_POKEMON_WEST] = sAnim_HookedPokemonWest, [ANIM_HOOKED_POKEMON_EAST] = sAnim_HookedPokemonEast, }; static const struct StepAnimTable sStepAnimTables[] = { { .anims = sAnimTable_QuintyPlump, .animPos = {1, 3, 0, 2}, }, { .anims = sAnimTable_Standard, .animPos = {1, 3, 0, 2}, }, { .anims = sAnimTable_RedGreenNormal, .animPos = {1, 3, 0, 2}, }, { .anims = sAnimTable_AcroBike, .animPos = {1, 3, 0, 2}, }, { .anims = sAnimTable_RedGreenSurf, .animPos = {1, 3, 0, 2}, }, { .anims = sAnimTable_Nurse, .animPos = {1, 3, 0, 2}, }, { .anims = sAnimTable_RedGreenFish, .animPos = {1, 3, 0, 2}, }, { .anims = sAnimTable_Unknown, .animPos = {3, 7, 0, 4}, }, {} };
b9275533e39e9d52749abbd0b5da0074055963a7
487c8455b34e2b312da42bf8a43162aa5c5027df
/Target/Demo/TRICORE_TC3_TC375_Lite_Kit_ADS/Prog/Libraries/iLLD/TC37A/Tricore/Gtm/Std/IfxGtm_Spe.c
fed2e8dc50495bda7d590cf87c4cd4c4bcd2d8cd
[]
no_license
feaser/openblt
bf3a72e7beb998cb635a67db85fa68100d048bb8
57b517eabeb37d945606e18736e106bde34010bc
refs/heads/master
2023-08-31T23:54:09.030534
2023-07-07T10:29:56
2023-07-07T10:29:56
102,110,352
534
236
null
2023-09-14T11:11:56
2017-09-01T12:26:08
C
UTF-8
C
false
false
5,528
c
IfxGtm_Spe.c
/** * \file IfxGtm_Spe.c * \brief GTM basic functionality * * \version iLLD_1_0_1_12_0_1 * \copyright Copyright (c) 2018 Infineon Technologies AG. All rights reserved. * * * IMPORTANT NOTICE * * Use of this file is subject to the terms of use agreed between (i) you or * the company in which ordinary course of business you are acting and (ii) * Infineon Technologies AG or its licensees. If and as long as no such terms * of use are agreed, use of this file is subject to following: * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, must * be included in all copies of the Software, in whole or in part, and all * derivative works of the Software, unless such copies or derivative works are * solely in the form of machine-executable object code generated by a source * language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * */ /******************************************************************************/ /*----------------------------------Includes----------------------------------*/ /******************************************************************************/ #include "IfxGtm_Spe.h" /******************************************************************************/ /*-------------------------Function Implementations---------------------------*/ /******************************************************************************/ void IfxGtm_Spe_disableInterrupt(Ifx_GTM_SPE *spe, IfxGtm_Spe_InterruptSignal interrupt) { uint32 irqen_temp = spe->IRQ.EN.U; irqen_temp = (irqen_temp ^ ((uint32)1 << interrupt)); spe->IRQ.EN.U = irqen_temp; } void IfxGtm_Spe_enableErrorInterrupt(Ifx_GTM_SPE *spe, IfxGtm_Spe_InterruptSignal interrupt, boolean enabled) { uint32 irqen_temp = spe->EIRQ_EN.U; irqen_temp = (irqen_temp | ((uint32)1 << interrupt)) & ((uint32)enabled << interrupt); spe->EIRQ_EN.U = irqen_temp; } void IfxGtm_Spe_enableInput(Ifx_GTM_SPE *spe, IfxGtm_Spe_InputSignal inputSignal, boolean enabled) { switch (enabled) { case TRUE: { spe->CTRL_STAT.U |= ((uint32)enabled << ((uint32)inputSignal + IFX_GTM_SPE_CTRL_STAT_SIE0_OFF)); break; } case FALSE: spe->CTRL_STAT.U &= ((uint32)enabled << ((uint32)inputSignal + IFX_GTM_SPE_CTRL_STAT_SIE0_OFF)); break; } } void IfxGtm_Spe_enableInterrupt(Ifx_GTM_SPE *spe, IfxGtm_Spe_InterruptSignal interrupt) { uint32 irqen_temp = spe->IRQ.EN.U; irqen_temp = (irqen_temp | ((uint32)1 << interrupt)); spe->IRQ.EN.U = irqen_temp; } uint32 IfxGtm_Spe_getFastShutoffLevel(Ifx_GTM_SPE *spe, IfxGtm_Spe_OutChannel channel) { uint32 fsol_temp = (uint32)(spe->CTRL_STAT.B.FSOL); fsol_temp = (fsol_temp & (uint32)(1 << (uint32)channel)) >> (uint32)channel; return (uint32)fsol_temp; } boolean IfxGtm_Spe_getInterruptStatus(Ifx_GTM_SPE *spe, IfxGtm_Spe_InterruptSignal interrupt) { return (((spe->IRQ.NOTIFY.U) >> interrupt) & (uint32)1) == (uint32)1; } uint32 IfxGtm_Spe_getRevCompare(Ifx_GTM_SPE *spe) { return (uint32)(spe->REV_CMP.B.REV_CMP); } void IfxGtm_Spe_selectTrigger(Ifx_GTM_SPE *spe, IfxGtm_Spe_TriggerSource trigger) { Ifx_GTM_SPE_CTRL_STAT ctrl_stat; ctrl_stat.U = spe->CTRL_STAT.U; ctrl_stat.B.TRIG_SEL = IFXGTM_SPE_GET_TRIGSEL(trigger); ctrl_stat.B.ETRIG_SEL = IFXGTM_SPE_GET_ETRIG(trigger); spe->CTRL_STAT.U = ctrl_stat.U; } void IfxGtm_Spe_setAllInputPatterns(Ifx_GTM_SPE *spe, IfxGtm_Spe_InputPattern *patPtr) { uint32 spepat_temp = spe->PAT.U; spepat_temp = IFXGTM_SPE_GETALLPATTERNS(patPtr); spe->PAT.U = spepat_temp; } void IfxGtm_Spe_setInputPattern(Ifx_GTM_SPE *spe, IfxGtm_Spe_InputPattern *patPtr, IfxGtm_Spe_PatternIndex patIndex) { uint32 pattern = patPtr->U; uint32 spepat_temp = spe->PAT.U; spepat_temp = IFXGTM_SPE_SETSINGLEPATTERN(spepat_temp, pattern, patIndex); spe->PAT.U = spepat_temp; } void IfxGtm_Spe_setInterrupt(Ifx_GTM_SPE *spe, IfxGtm_Spe_InterruptSignal interrupt) { uint32 forceirq_temp = spe->IRQ.FORCINT.U; forceirq_temp = (forceirq_temp | ((uint32)1 << interrupt)); spe->IRQ.FORCINT.U = forceirq_temp; } void IfxGtm_Spe_setOutputPattern(Ifx_GTM_SPE *spe, IfxGtm_Spe_OutputPattern *patPtr, IfxGtm_Spe_PatternIndex patIndex) { spe->OUT_PAT[patIndex].U = patPtr->U; } void IfxGtm_Spe_setRevCompare(Ifx_GTM_SPE *spe, uint32 count) { spe->REV_CMP.B.REV_CMP = count; }
75e0a67702a39bdf4fccfd00e167a6f294ffb5a0
4edd539e79d33f7a08a4c928d113771e9dac0740
/source/ceilng.c
c387ee1bd282969e48212b7b4de10f19b87b9c40
[ "MIT" ]
permissive
Olde-Skuul/doom3do
84ae4f312e919d070dcb838f7765c5c1ad3f5efd
8a5cdae476e09f2bedd2cc4dcd105dae4b35d4af
refs/heads/master
2023-03-07T19:10:13.752129
2023-01-11T22:54:07
2023-01-11T22:54:07
27,351,671
658
55
MIT
2022-11-03T04:07:37
2014-11-30T22:02:07
C
UTF-8
C
false
false
7,519
c
ceilng.c
#include "Doom.h" /********************************** Local structures for moving ceilings **********************************/ #define CEILSPEED (2<<FRACBITS) /* Speed of crushing ceilings */ typedef struct ceiling_t { sector_t *sector; /* Pointer to the sector structure */ struct ceiling_t *next; /* Next entry in the linked list */ Fixed bottomheight; /* Lowest point to move to */ Fixed topheight; /* Highest point to move to */ Fixed speed; /* Speed of motion */ Word tag; /* ID */ int direction; /* 1 = up, 0 = waiting, -1 = down */ int olddirection; /* Previous direction to restart with */ ceiling_e type; /* Type of ceiling */ Boolean crush; /* Can it crush? */ } ceiling_t; static ceiling_t *MainCeilingPtr; /* Pointer to the first ceiling in list */ /********************************** Insert a new ceiling record into the linked list, use a simple insert into the head to add. **********************************/ static void AddActiveCeiling(ceiling_t *CeilingPtr) { CeilingPtr->next = MainCeilingPtr; /* Insert into the chain */ MainCeilingPtr = CeilingPtr; /* Set this one as the first */ } /********************************** Remove a ceiling record from the linked list. I also call RemoveThinker to actually perform the memory disposal. **********************************/ static void RemoveActiveCeiling(ceiling_t *CeilingPtrKill) { ceiling_t *CeilingPtr; /* Temp pointer */ ceiling_t *PrevPtr; /* Previous pointer (For linked list) */ PrevPtr = 0; /* Init the previous pointer */ CeilingPtr = MainCeilingPtr; /* Get the main list entry */ while (CeilingPtr) { /* Failsafe! */ if (CeilingPtr==CeilingPtrKill) { /* Master pointer matches? */ CeilingPtr = CeilingPtr->next; /* Get the next link */ if (!PrevPtr) { /* First one in chain? */ MainCeilingPtr = CeilingPtr; /* Make the next one the new head */ } else { PrevPtr->next = CeilingPtr; /* Remove the link */ } break; /* Get out of the loop */ } PrevPtr = CeilingPtr; /* Make the current pointer the previous one */ CeilingPtr = CeilingPtr->next; /* Get the next link */ } CeilingPtrKill->sector->specialdata = 0; /* Unlink from the sector */ RemoveThinker(CeilingPtrKill); /* Remove the thinker */ } /********************************** Think logic. This code will move the ceiling up and down. **********************************/ static void T_MoveCeiling(ceiling_t *ceiling) { result_e res; if (ceiling->direction==1) { /* Going up? */ res = T_MovePlane(ceiling->sector,ceiling->speed, /* Move it */ ceiling->topheight,FALSE,TRUE,ceiling->direction); if (Tick2) { /* Sound? */ S_StartSound(&ceiling->sector->SoundX,sfx_stnmov); } if (res == pastdest) { /* Did it reach the top? */ switch(ceiling->type) { case raiseToHighest: RemoveActiveCeiling(ceiling); /* Remove the thinker */ break; case fastCrushAndRaise: case crushAndRaise: ceiling->direction = -1; /* Go down now */ } } } else if (ceiling->direction==-1) { /* Going down? */ res = T_MovePlane(ceiling->sector,ceiling->speed, /* Move it */ ceiling->bottomheight,ceiling->crush,TRUE,ceiling->direction); if (Tick2) { /* Time for sound? */ S_StartSound(&ceiling->sector->SoundX,sfx_stnmov); } if (res == pastdest) { /* Reached the bottom? */ switch(ceiling->type) { case crushAndRaise: ceiling->speed = CEILSPEED; /* Reset the speed ALWAYS */ case fastCrushAndRaise: ceiling->direction = 1; /* Go up now */ break; case lowerAndCrush: case lowerToFloor: RemoveActiveCeiling(ceiling); /* Remove it */ } } else if (res == crushed) { /* Is it crushing something? */ switch(ceiling->type) { case crushAndRaise: case lowerAndCrush: ceiling->speed = (CEILSPEED/8); /* Slow down for more fun! */ } } } } /********************************** Given a tag ID number, activate a ceiling that is currently inactive. **********************************/ static void ActivateInStasisCeiling(Word tag) { ceiling_t *CeilingPtr; /* Temp pointer */ CeilingPtr = MainCeilingPtr; /* Get the main list entry */ if (CeilingPtr) { /* Scan all entries in the thinker list */ do { if (CeilingPtr->tag == tag && !CeilingPtr->direction) { /* Match? */ CeilingPtr->direction = CeilingPtr->olddirection; /* Restart the platform */ ChangeThinkCode(CeilingPtr,T_MoveCeiling); /* Reset code */ } CeilingPtr = CeilingPtr->next; /* Get the next link */ } while (CeilingPtr); } } /********************************** Move a ceiling up/down and all around! **********************************/ Boolean EV_DoCeiling (line_t *line, ceiling_e type) { Boolean rtn; /* Return value */ Word secnum; /* Sector being scanned */ sector_t *sec; ceiling_t *ceiling; secnum = -1; rtn = FALSE; /* Reactivate in-stasis ceilings...for certain types. */ switch(type) { case fastCrushAndRaise: case crushAndRaise: ActivateInStasisCeiling(line->tag); } while ((secnum = P_FindSectorFromLineTag(line,secnum)) != -1) { sec = &sectors[secnum]; /* Get the sector pointer */ if (sec->specialdata) { /* Already something is here? */ continue; } /* New ceiling thinker */ rtn = TRUE; ceiling = (ceiling_t *)AddThinker(T_MoveCeiling,sizeof(ceiling_t)); sec->specialdata = ceiling; /* Pass the pointer */ ceiling->sector = sec; /* Save the sector ptr */ ceiling->tag = sec->tag; /* Set the tag number */ ceiling->crush = FALSE; /* Assume it can't crush */ ceiling->type = type; /* Set the ceiling type */ switch(type) { case fastCrushAndRaise: ceiling->crush = TRUE; ceiling->topheight = sec->ceilingheight; ceiling->bottomheight = sec->floorheight; ceiling->direction = -1; /* Down */ ceiling->speed = CEILSPEED*2; /* Go down fast! */ break; case crushAndRaise: ceiling->crush = TRUE; ceiling->topheight = sec->ceilingheight; /* Floor and ceiling */ case lowerAndCrush: case lowerToFloor: ceiling->bottomheight = sec->floorheight; /* To the floor! */ ceiling->direction = -1; /* Down */ ceiling->speed = CEILSPEED; break; case raiseToHighest: ceiling->topheight = P_FindHighestCeilingSurrounding(sec); ceiling->direction = 1; /* Go up */ ceiling->speed = CEILSPEED; break; } AddActiveCeiling(ceiling); /* Add the ceiling to the list */ } return rtn; } /********************************** Deactivate a ceiling Only affect ceilings that have the same ID tag as the line segment and also are active. **********************************/ Boolean EV_CeilingCrushStop(line_t *line) { Word tag; /* ID Tag to scan for */ Boolean rtn; /* Return value */ ceiling_t *CeilingPtr; /* Temp pointer */ rtn = FALSE; tag = line->tag; /* Get the tag to look for */ CeilingPtr = MainCeilingPtr; /* Get the main list entry */ while (CeilingPtr) { /* Scan all entries in the thinker list */ if (CeilingPtr->tag == tag && CeilingPtr->direction) { /* Match? */ CeilingPtr->olddirection = CeilingPtr->direction; /* Save the platform's state */ ChangeThinkCode(CeilingPtr,0); /* Shut down */ CeilingPtr->direction = 0; /* In statis */ rtn = TRUE; } CeilingPtr = CeilingPtr->next; /* Get the next link */ } return rtn; } /********************************** Reset the master ceiling pointer Called from InitThinkers **********************************/ void ResetCeilings(void) { MainCeilingPtr = 0; /* Discard the links */ }
5c47496eb5972759b9cb708c6f4a9121f06f9458
c30beb817a4788c3eb9027c5cede0c7ae4006578
/demos/additions/final_random.h
7562f6ea48d31d3b03c6794fd1748925b0847907
[ "MIT" ]
permissive
f1nalspace/final_game_tech
232c34ce6d737b9069073b53c665bf14e513898c
33b63dc0664e16682d4298371f3166869c233b0f
refs/heads/master
2023-06-25T07:27:01.747802
2021-09-07T08:03:17
2021-09-07T08:08:08
91,165,055
178
18
MIT
2023-01-04T12:40:05
2017-05-13T09:59:36
C
UTF-8
C
false
false
3,258
h
final_random.h
/* Name: Final Random Description: Pseudo random number generator and utils. This file is part of the final_framework. License: MIT License Copyright 2019 Torsten Spaete */ #ifndef FINAL_RANDOM_H #define FINAL_RANDOM_H #include "final_math.h" // https://arvid.io/2018/07/02/better-cxx-prng/ #define RANDOMTYPE_SPLITMIX 1 #define RANDOMTYPE_XORSHIFT 2 #define RANDOMTYPE_CRT 3 #define RANDOMTYPE RANDOMTYPE_XORSHIFT struct RandomSeries { uint64_t seed; }; inline RandomSeries RandomSeed(const uint64_t seed) { RandomSeries result = {}; result.seed = seed; #if RANDOMTYPE == RANDOMTYPE_CRT srand(seed); #endif return(result); } #if RANDOMTYPE == RANDOMTYPE_SPLITMIX inline uint32_t RandomU32(RandomSeries *series) { uint64_t z = (series->seed += UINT64_C(0x9E3779B97F4A7C15)); z = (z ^ (z >> 30)) * UINT64_C(0xBF58476D1CE4E5B9); z = (z ^ (z >> 27)) * UINT64_C(0x94D049BB133111EB); return uint32_t((z ^ (z >> 31)) >> 31); } #endif #if RANDOMTYPE == RANDOMTYPE_XORSHIFT inline uint32_t RandomU32(RandomSeries *series) { uint64_t result = (series->seed * UINT64_C(0xd989bcacc137dcd5)); series->seed ^= series->seed >> 11; series->seed ^= series->seed << 31; series->seed ^= series->seed >> 18; return uint32_t(result >> 32ull); } #endif #if RANDOMTYPE == RANDOMTYPE_CRT inline uint32_t RandomU32(RandomSeries *series) { srand(series->seed++); uint32_t result = (uint32_t)(rand() / (double)RAND_MAX * (double)UINT32_MAX); return(result); } #endif inline uint8_t RandomU8(RandomSeries *series) { uint8_t result = RandomU32(series) % UINT8_MAX; return(result); } // -1.0 to +1.0 inline float RandomBilateral(RandomSeries *series) { uint32_t s = RandomU32(series); float result = -1.0f + (s / (float)UINT32_MAX) * 2.0f; return(result); } // 0.0 to 1.0 inline float RandomUnilateral(RandomSeries *series) { uint32_t u = RandomU32(series); float result = u / (float)UINT32_MAX; return(result); } inline Vec3f RandomV3f(RandomSeries *series) { float x = RandomBilateral(series); float y = RandomBilateral(series); float z = RandomBilateral(series); Vec3f result = V3fInit(x, y, z); return(result); } inline Vec3f RandomDirection(RandomSeries *series) { Vec3f result = V3fNormalize(RandomV3f(series)); return(result); } // http://www.rorydriscoll.com/2009/01/07/better-sampling/ inline Vec3f UniformSampleHemisphere(const float u1, const float u2) { const float r = SquareRoot(1.0f - u1 * u1); const float phi = 2.0f * Pi32 * u2; const float x = Cosine(phi) * r; const float y = Sine(phi) * r; const float z = u1; Vec3f result = V3fNormalize(V3fInit(x, y, z)); return(result); } inline Vec3f CosineSampleHemisphere(const float u1, const float u2) { const float r = SquareRoot(u1); const float theta = 2.0f * Pi32 * u2; const float x = r * Cosine(theta); const float y = r * Sine(theta); const float z = SquareRoot(Max(0.0f, 1.0f - u1)); const Vec3f result = V3fNormalize(V3fInit(x, y, z)); return(result); } // Returns a random direction inside the universal unit hemisphere inline Vec3f RandomUnitHemisphere(RandomSeries *series) { float u1 = RandomUnilateral(series); float u2 = RandomUnilateral(series); Vec3f result = CosineSampleHemisphere(u1, u2); return(result); } #endif // FINAL_RANDOM_H
528a4a7dce1805b5e39e054410d58e768aa66878
17d7357e5c5130ace022b3c9d9f98e7b13dda0ca
/src/coding/relic_decoder_lib.c
9aa6552bb00b5235869739c9aa99fe31709146a5
[ "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
15,207
c
relic_decoder_lib.c
#include <stdlib.h> #include <string.h> #include <math.h> #include "relic_decoder_lib.h" /* Relic Codec decoder, a fairly simple mono-interleave DCT-based codec. * * Decompiled from Relic's dec.exe with some info from Homeworld source code .h/lib * files (released around 2003 through Relic Dev Network), accurate with minor +-1 * samples due to double<>float ops or maybe original compiler (Intel's) diffs. */ /* mixfft.c */ extern void fft(int n, float* xRe, float* xIm, float* yRe, float* yIm); #define RELIC_MAX_CHANNELS 2 #define RELIC_MAX_SCALES 6 #define RELIC_BASE_SCALE 10.0f #define RELIC_FREQUENCY_MASKING_FACTOR 1.0f #define RELIC_CRITICAL_BAND_COUNT 27 #define RELIC_PI 3.14159265358979323846f #define RELIC_SIZE_LOW 128 #define RELIC_SIZE_MID 256 #define RELIC_SIZE_HIGH 512 #define RELIC_MAX_SIZE RELIC_SIZE_HIGH #define RELIC_MAX_FREQ (RELIC_MAX_SIZE / 2) #define RELIC_MAX_FFT (RELIC_MAX_SIZE / 4) #define RELIC_MIN_BITRATE 256 #define RELIC_MAX_BITRATE 2048 //#define RELIC_MAX_FRAME_SIZE ((RELIC_MAX_BITRATE / 8) + 0x04) /* extra 0x04 for the bitreader */ struct relic_handle_t { /* decoder info */ int channels; int frame_size; int wave_size; int freq_size; int dct_mode; int samples_mode; /* decoder init state */ float scales[RELIC_MAX_SCALES]; /* quantization scales */ float dct[RELIC_MAX_SIZE]; float window[RELIC_MAX_SIZE]; /* decoder frame state */ uint8_t exponents[RELIC_MAX_CHANNELS][RELIC_MAX_FREQ]; /* quantization/scale indexes */ float freq1[RELIC_MAX_FREQ]; /* dequantized spectrum */ float freq2[RELIC_MAX_FREQ]; float wave_cur[RELIC_MAX_CHANNELS][RELIC_MAX_SIZE]; /* current frame samples */ float wave_prv[RELIC_MAX_CHANNELS][RELIC_MAX_SIZE]; /* previous frame samples */ }; /* ************************************* */ static const int16_t critical_band_data[RELIC_CRITICAL_BAND_COUNT] = { 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15, 17, 20, 23, 27, 31, 37, 43, 51, 62, 74, 89, 110, 139, 180, 256 }; static void init_dct(float* dct, int dct_size) { int i; int dct_quarter = dct_size >> 2; for (i = 0; i < dct_quarter; i++) { double temp = ((float)i + 0.125f) * (RELIC_PI * 2.0f) * (1.0f / (float)dct_size); dct[i] = sin(temp); dct[dct_quarter + i] = cos(temp); } } static int apply_idct(const float* freq, float* wave, const float* dct, int dct_size) { int i; float factor; float out_re[RELIC_MAX_FFT]; float out_im[RELIC_MAX_FFT]; float in_re[RELIC_MAX_FFT]; float in_im[RELIC_MAX_FFT]; float wave_tmp[RELIC_MAX_SIZE]; int dct_half = dct_size >> 1; int dct_quarter = dct_size >> 2; int dct_3quarter = 3 * (dct_size >> 2); /* prerotation? */ for (i = 0; i < dct_quarter; i++) { float coef1 = freq[2 * i] * 0.5f; float coef2 = freq[dct_half - 1 - 2 * i] * 0.5f; in_re[i] = coef1 * dct[dct_quarter + i] + coef2 * dct[i]; in_im[i] = -coef1 * dct[i] + coef2 * dct[dct_quarter + i]; } /* main FFT */ fft(dct_quarter, in_re, in_im, out_re, out_im); /* postrotation, window and reorder? */ factor = 8.0 / sqrt(dct_size); for (i = 0; i < dct_quarter; i++) { float out_re_i = out_re[i]; out_re[i] = (out_re[i] * dct[dct_quarter + i] + out_im[i] * dct[i]) * factor; out_im[i] = (-out_re_i * dct[i] + out_im[i] * dct[dct_quarter + i]) * factor; wave_tmp[i * 2] = out_re[i]; wave_tmp[i * 2 + dct_half] = out_im[i]; } for (i = 1; i < dct_size; i += 2) { wave_tmp[i] = -wave_tmp[dct_size - 1 - i]; } /* wave mix thing? */ for (i = 0; i < dct_3quarter; i++) { wave[i] = wave_tmp[dct_quarter + i]; } for (i = dct_3quarter; i < dct_size; i++) { wave[i] = -wave_tmp[i - dct_3quarter]; } return 0; } static void decode_frame(const float* freq1, const float* freq2, float* wave_cur, float* wave_prv, const float* dct, const float* window, int dct_size) { int i; float wave_tmp[RELIC_MAX_SIZE]; int dct_half = dct_size >> 1; /* copy for first half(?) */ memcpy(wave_cur, wave_prv, RELIC_MAX_SIZE * sizeof(float)); /* transform frequency domain to time domain with DCT/FFT */ apply_idct(freq1, wave_tmp, dct, dct_size); apply_idct(freq2, wave_prv, dct, dct_size); /* overlap and apply window function to filter this block's beginning */ for (i = 0; i < dct_half; i++) { wave_cur[dct_half + i] = wave_tmp[i] * window[i] + wave_cur[dct_half + i] * window[dct_half + i]; wave_prv[i] = wave_prv[i] * window[i] + wave_tmp[dct_half + i] * window[dct_half + i]; } } static void init_window(float *window, int dct_size) { int i; for (i = 0; i < dct_size; i++) { window[i] = sin((float)i * (RELIC_PI / dct_size)); } } static void decode_frame_base(const float* freq1, const float* freq2, float* wave_cur, float* wave_prv, const float* dct, const float* window, int dct_mode, int samples_mode) { int i; float wave_tmp[RELIC_MAX_SIZE]; /* dec_relic only uses 512/512 mode, source references 256/256 (effects only?) too */ if (samples_mode == RELIC_SIZE_LOW) { { /* 128 DCT to 128 samples */ decode_frame(freq1, freq2, wave_cur, wave_prv, dct, window, RELIC_SIZE_LOW); } } else if (samples_mode == RELIC_SIZE_MID) { if (dct_mode == RELIC_SIZE_LOW) { /* 128 DCT to 256 samples (repeat sample x2) */ decode_frame(freq1, freq2, wave_tmp, wave_prv, dct, window, RELIC_SIZE_LOW); for (i = 0; i < 256 - 1; i += 2) { wave_cur[i + 0] = wave_tmp[i >> 1]; wave_cur[i + 1] = wave_tmp[i >> 1]; } } else { /* 256 DCT to 256 samples */ decode_frame(freq1, freq2, wave_cur, wave_prv, dct, window, RELIC_SIZE_MID); } } else if (samples_mode == RELIC_SIZE_HIGH) { if (dct_mode == RELIC_SIZE_LOW) { /* 128 DCT to 512 samples (repeat sample x4) */ decode_frame(freq1, freq2, wave_tmp, wave_prv, dct, window, RELIC_SIZE_LOW); for (i = 0; i < 512 - 1; i += 4) { wave_cur[i + 0] = wave_tmp[i >> 2]; wave_cur[i + 1] = wave_tmp[i >> 2]; wave_cur[i + 2] = wave_tmp[i >> 2]; wave_cur[i + 3] = wave_tmp[i >> 2]; } } else if (dct_mode == RELIC_SIZE_MID) { /* 256 DCT to 512 samples (repeat sample x2) */ decode_frame(freq1, freq2, wave_tmp, wave_prv, dct, window, RELIC_SIZE_MID); for (i = 0; i < 512 - 1; i += 2) { wave_cur[i + 0] = wave_tmp[i >> 1]; wave_cur[i + 1] = wave_tmp[i >> 1]; } } else { /* 512 DCT to 512 samples */ decode_frame(freq1, freq2, wave_cur, wave_prv, dct, window, RELIC_SIZE_HIGH); } } } /* reads 32b max, packed in LSB order per byte (like Vorbis), ex. * with 0x45 6A=01000101 01101010 could read 4b=0101, 6b=100100, 3b=010 ... * assumes buf has enough extra bits to read 32b (size +0x04) */ static uint32_t read_ubits(uint8_t bits, uint32_t offset, uint8_t* buf) { uint32_t shift, mask, pos, val; shift = offset - 8 * (offset / 8); mask = (1 << bits) - 1; pos = offset / 8; val = ((uint32_t)buf[pos+0]) | ((uint32_t)buf[pos+1]<<8) | ((uint32_t)buf[pos+2]<<16) | ((uint32_t)buf[pos+3]<<24); return (val >> shift) & mask; } static int read_sbits(uint8_t bits, uint32_t offset, uint8_t* buf) { uint32_t val = read_ubits(bits, offset, buf); int outval; if (val >> (bits - 1) == 1) { /* upper bit = sign */ uint32_t mask = (1 << (bits - 1)) - 1; outval = (int)(val & mask); outval = -outval; } else { outval = (int)val; } return outval; } static void init_dequantization(float* scales) { int i; scales[0] = RELIC_BASE_SCALE; for (i = 1; i < RELIC_MAX_SCALES; i++) { scales[i] = scales[i - 1] * scales[0]; } for (i = 0; i < RELIC_MAX_SCALES; i++) { scales[i] = RELIC_FREQUENCY_MASKING_FACTOR / (double) ((1 << (i + 1)) - 1) * scales[i]; } } static int unpack_frame(uint8_t* buf, int buf_size, float* freq1, float* freq2, const float* scales, uint8_t* exponents, int freq_size) { uint8_t flags, cb_bits, ev_bits, ei_bits, qv_bits; int qv, pos; uint8_t ev; uint8_t move; uint32_t bit_offset, max_offset; int i, j; int freq_half = freq_size >> 1; memset(freq1, 0, RELIC_MAX_FREQ * sizeof(float)); memset(freq2, 0, RELIC_MAX_FREQ * sizeof(float)); flags = read_ubits(2u, 0u, buf); cb_bits = read_ubits(3u, 2u, buf); ev_bits = read_ubits(2u, 5u, buf); ei_bits = read_ubits(4u, 7u, buf); bit_offset = 11; max_offset = buf_size * 8u; /* reset exponents indexes */ if ((flags & 1) == 1) { memset(exponents, 0, RELIC_MAX_FREQ); } /* read packed exponents indexes for all bands */ if (cb_bits > 0 && ev_bits > 0) { pos = 0; for (i = 0; i < RELIC_CRITICAL_BAND_COUNT - 1; i++) { if (bit_offset + cb_bits > max_offset) goto fail; move = read_ubits(cb_bits, bit_offset, buf); bit_offset += cb_bits; if (i > 0 && move == 0) break; pos += move; if (bit_offset + ev_bits > max_offset) goto fail; ev = read_ubits(ev_bits, bit_offset, buf); bit_offset += ev_bits; if (pos + 1 >= sizeof(critical_band_data)) goto fail; for (j = critical_band_data[pos]; j < critical_band_data[pos + 1]; j++) { exponents[j] = ev; } } } /* read quantized values */ if (freq_half > 0 && ei_bits > 0) { /* read first part */ pos = 0; for (i = 0; i < RELIC_MAX_FREQ; i++) { if (bit_offset + ei_bits > max_offset) goto fail; move = read_ubits(ei_bits, bit_offset, buf); bit_offset += ei_bits; if (i > 0 && move == 0) break; pos += move; if (pos >= RELIC_MAX_FREQ) goto fail; qv_bits = exponents[pos]; if (bit_offset + qv_bits + 2u > max_offset) goto fail; qv = read_sbits(qv_bits + 2u, bit_offset, buf); bit_offset += qv_bits + 2u; if (qv != 0 && pos < freq_half && qv_bits < 6) { freq1[pos] = (float)qv * scales[qv_bits]; } } /* read second part, or clone it */ if ((flags & 2) == 2) { memcpy(freq2, freq1, RELIC_MAX_FREQ * sizeof(float)); } else { pos = 0; for (i = 0; i < RELIC_MAX_FREQ; i++) { if (bit_offset + ei_bits > max_offset) goto fail; move = read_ubits(ei_bits, bit_offset, buf); bit_offset += ei_bits; if (i > 0 && move == 0) break; pos += move; if (pos >= RELIC_MAX_FREQ) goto fail; qv_bits = exponents[pos]; if (bit_offset + qv_bits + 2u > max_offset) goto fail; qv = read_sbits(qv_bits + 2u, bit_offset, buf); bit_offset += qv_bits + 2u; if (qv != 0 && pos < freq_half && qv_bits < 6) { freq2[pos] = (float)qv * scales[qv_bits]; } } } } return 1; fail: return 0; /* original code doesn't check bad sizes so no return errcode */ } /*****************************************************************************/ relic_handle_t* relic_init(int channels, int bitrate, int codec_rate) { relic_handle_t* handle = NULL; if (channels < 0 || channels > RELIC_MAX_CHANNELS) goto fail; handle = calloc(1, sizeof(relic_handle_t)); if (!handle) goto fail; handle->channels = channels; /* dequantized freq1+2 size (separate from DCT) */ if (codec_rate < 22050) /* probably 11025 only */ handle->freq_size = RELIC_SIZE_LOW; else if (codec_rate == 22050) handle->freq_size = RELIC_SIZE_MID; else if (codec_rate > 22050) /* probably 44100 only */ handle->freq_size = RELIC_SIZE_HIGH; /* default for streams (only a few mode combos are valid, see decode) */ handle->wave_size = RELIC_SIZE_HIGH; handle->dct_mode = RELIC_SIZE_HIGH; handle->samples_mode = RELIC_SIZE_HIGH; init_dct(handle->dct, RELIC_SIZE_HIGH); init_window(handle->window, RELIC_SIZE_HIGH); init_dequantization(handle->scales); memset(handle->wave_prv, 0, RELIC_MAX_CHANNELS * RELIC_MAX_SIZE * sizeof(float)); /* known bitrates: 0x100, 0x180, 0x200, 0x280, 0x300, 0x380, 0x400, 0x800 * dec.exe doesn't validate this, so there may be more */ if (bitrate < RELIC_MIN_BITRATE || bitrate > RELIC_MAX_BITRATE) goto fail; handle->frame_size = (bitrate / 8); /* 0x100 and 0x80 are common */ return handle; fail: relic_free(handle); return NULL; } void relic_free(relic_handle_t* handle) { if (!handle) return; free(handle); } void relic_reset(relic_handle_t* handle) { if (!handle) return; memset(handle->wave_prv, 0, RELIC_MAX_CHANNELS * RELIC_MAX_SIZE * sizeof(float)); } int relic_get_frame_size(relic_handle_t* handle) { if (!handle) return 0; return handle->frame_size; } int relic_decode_frame(relic_handle_t* handle, uint8_t* buf, int channel) { int ok; /* clean extra bytes for bitreader (due to a quirk in the original code it may read outside max frame size) */ memset(buf + handle->frame_size, 0, RELIC_BUFFER_SIZE - handle->frame_size); ok = unpack_frame(buf, RELIC_BUFFER_SIZE, handle->freq1, handle->freq2, handle->scales, handle->exponents[channel], handle->freq_size); if (!ok) return ok; decode_frame_base(handle->freq1, handle->freq2, handle->wave_cur[channel], handle->wave_prv[channel], handle->dct, handle->window, handle->dct_mode, handle->samples_mode); return 1; } static inline int clamp16(int32_t val) { if (val > 32767) return 32767; else if (val < -32768) return -32768; else return val; } void relic_get_pcm16(relic_handle_t* handle, int16_t* outbuf, int32_t samples, int32_t skip) { int s, ch; int ichs = handle->channels; for (ch = 0; ch < ichs; ch++) { for (s = 0; s < samples; s++) { double d64_sample = handle->wave_cur[ch][skip + s]; int pcm_sample = clamp16((int32_t)d64_sample); /* f32 in PCM 32767.0 .. -32768.0 format, original code * does some custom double-to-int rint() though */ //FQ_BNUM ((float)(1<<26)*(1<<26)*1.5) //rint(x) ((d64 = (double)(x)+FQ_BNUM), *(int*)(&d64)) outbuf[s*ichs + ch] = pcm_sample; } } }
f971ec5100b37097edc0f2ca3d5336cfd6def934
9ceacf33fd96913cac7ef15492c126d96cae6911
/usr.sbin/installboot/bootstrap.c
19332ff487da157541dcef6261dd01bfc2fba839
[]
no_license
openbsd/src
ab97ef834fd2d5a7f6729814665e9782b586c130
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
refs/heads/master
2023-09-02T18:54:56.624627
2023-09-02T15:16:12
2023-09-02T15:16:12
66,966,208
3,394
1,235
null
2023-08-08T02:42:25
2016-08-30T18:18:25
C
UTF-8
C
false
false
3,766
c
bootstrap.c
/* $OpenBSD: bootstrap.c,v 1.13 2019/06/28 13:32:48 deraadt Exp $ */ /* * Copyright (c) 2013 Joel Sing <jsing@openbsd.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/param.h> /* DEV_BSIZE */ #include <sys/disklabel.h> #include <sys/dkio.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <err.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "installboot.h" void bootstrap(int devfd, char *dev, char *bootfile) { struct disklabel dl; struct disklabel *lp; struct partition *pp; char *boot, *p, part; size_t bootsize; size_t bootsec; struct stat sb; int fd, i; /* * Install bootstrap code onto the given disk, preserving the * existing disklabel. */ /* Read disklabel from disk. */ if (ioctl(devfd, DIOCGDINFO, &dl) == -1) err(1, "disklabel"); if (dl.d_secsize == 0) { warnx("disklabel has sector size of 0, assuming %d", DEV_BSIZE); dl.d_secsize = DEV_BSIZE; } /* Read bootstrap file. */ if (verbose) fprintf(stderr, "reading bootstrap from %s\n", bootfile); fd = open(bootfile, O_RDONLY); if (fd == -1) err(1, "open %s", bootfile); if (fstat(fd, &sb) == -1) err(1, "fstat %s", bootfile); bootsec = howmany((ssize_t)sb.st_size, dl.d_secsize); bootsize = bootsec * dl.d_secsize; if (verbose) fprintf(stderr, "bootstrap is %zu bytes " "(%zu sectors @ %u bytes = %zu bytes)\n", (ssize_t)sb.st_size, bootsec, dl.d_secsize, bootsize); boot = calloc(1, bootsize); if (boot == NULL) err(1, "calloc"); if (read(fd, boot, bootsize) != (ssize_t)sb.st_size) err(1, "read"); close(fd); /* * Check that the bootstrap will fit - partitions must not overlap, * or if they do, the partition type must be either FS_BOOT or * FS_UNUSED. The 'c' partition will always overlap and is ignored. */ if (verbose) fprintf(stderr, "ensuring used partitions do not overlap " "with bootstrap sectors 0-%zu\n", bootsec); for (i = 0; i < dl.d_npartitions; i++) { part = 'a' + i; pp = &dl.d_partitions[i]; if (i == RAW_PART) continue; if (DL_GETPSIZE(pp) == 0) continue; if ((u_int64_t)bootsec <= DL_GETPOFFSET(pp)) continue; switch (pp->p_fstype) { case FS_BOOT: break; case FS_UNUSED: warnx("bootstrap overlaps with unused partition %c", part); break; default: errx(1, "bootstrap overlaps with partition %c", part); } } /* * Make sure the bootstrap has left space for the disklabel. * N.B.: LABELSECTOR *is* a DEV_BSIZE quantity! */ lp = (struct disklabel *)(boot + (LABELSECTOR * DEV_BSIZE) + LABELOFFSET); for (i = 0, p = (char *)lp; i < (int)sizeof(*lp); i++) if (p[i] != 0) errx(1, "bootstrap has data in disklabel area"); /* Patch the disklabel into the bootstrap code. */ memcpy(lp, &dl, sizeof(dl)); /* Write the bootstrap out to the disk. */ if (verbose) fprintf(stderr, "%s bootstrap to disk\n", (nowrite ? "would write" : "writing")); if (nowrite) return; if (pwrite(devfd, boot, bootsize, 0) != (ssize_t)bootsize) err(1, "pwrite"); }
91c79fb5cd052584bff34c4f1cbe2b28fb2a3c5e
984bc4181baec6e5a4b05a657e666b0e9f89f3f3
/3rdparty/mongo-c-driver-1.21.2/src/libmongoc/src/mongoc/mongoc-server-monitor-private.h
49d45c08ff2369a84db7a43658c193c59fe9884c
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
treefrogframework/treefrog-framework
0173245ff92162d2107af79861505981980d1eca
a1df97793e8cc628779378e5adae9af6987460c1
refs/heads/master
2023-08-22T03:57:58.891846
2023-05-18T14:00:42
2023-05-18T14:00:42
7,067,532
1,152
263
BSD-3-Clause
2023-08-08T20:25:03
2012-12-08T13:17:01
C++
UTF-8
C
false
false
1,794
h
mongoc-server-monitor-private.h
/* * Copyright 2020-present MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mongoc-prelude.h" #ifndef MONGOC_SERVER_MONITOR_PRIVATE_H #define MONGOC_SERVER_MONITOR_PRIVATE_H #include "mongoc.h" #include "mongoc-server-description-private.h" #include "mongoc-topology-private.h" /* For background monitoring of a single server. */ typedef struct _mongoc_server_monitor_t mongoc_server_monitor_t; mongoc_server_monitor_t * mongoc_server_monitor_new (mongoc_topology_t *topology, mongoc_topology_description_t *td, mongoc_server_description_t *init_description); void mongoc_server_monitor_request_cancel (mongoc_server_monitor_t *server_monitor); void mongoc_server_monitor_request_scan (mongoc_server_monitor_t *server_monitor); bool mongoc_server_monitor_request_shutdown ( mongoc_server_monitor_t *server_monitor); void mongoc_server_monitor_wait_for_shutdown ( mongoc_server_monitor_t *server_monitor); void mongoc_server_monitor_destroy (mongoc_server_monitor_t *server_monitor); void mongoc_server_monitor_run (mongoc_server_monitor_t *server_monitor); void mongoc_server_monitor_run_as_rtt (mongoc_server_monitor_t *server_monitor); #endif /* MONGOC_SERVER_MONITOR_PRIVATE_H */
37fc0cb72c6518cac5655381f262f4b2caf1fc71
fb127294ed7fb48e37342ca0950a34015fe8bd4e
/components/game_mod/dobj_utils.h
4ffc667e75d84643198fa9e3a2fffe4c15be1c46
[]
no_license
Nukem9/LinkerMod
89c826f42cfc0aabe111002ca3696df07ac156c9
72ee05bbf42dfb2a1893e655788b631be63ea317
refs/heads/development
2021-07-14T16:23:00.813862
2020-04-09T05:05:38
2020-04-09T05:05:38
30,128,803
134
56
null
2021-04-04T14:04:54
2015-01-31T22:35:11
C++
UTF-8
C
false
false
896
h
dobj_utils.h
#pragma once #define DOBJ_MAX_SUBMODELS 32 #define DOBJ_MAX_SURFS 128 struct XAnimTree_s; struct DSkelPartBits { int anim[5]; int control[5]; int skel[5]; }; struct DSkel { DSkelPartBits partBits; int timeStamp; union { struct DObjAnimMat *mat; struct DObjAnimMat *localMat; }; }; struct DObj { union { struct XAnimTree_s *localTree; struct XAnimTree_s *tree; }; unsigned __int16 duplicateParts; unsigned __int16 entnum; char duplicatePartsSize; char numModels; char numBones; unsigned int ignoreCollision; volatile int locked; DSkel skel; float radius; unsigned int hidePartBits[5]; char localClientIndex; unsigned char flags; unsigned char *ikState; union { XModel **localModels; XModel **models; }; }; int DObjGetNumModels(DObj *obj); XModel *DObjGetModel(DObj *obj, int modelIndex); void DObjGetHidePartBits(DObj *obj, unsigned int *partBits);
2d40ad0d35faa49e55f30ed9baaa3e5164909505
3f308bd1e45dc44276d57c089e7698b4fcda79a4
/compression/lz78.h
ed18aec207f027705bd9752c7b39f02326bd320b
[]
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
133
h
lz78.h
int izcmp(void); int cmp(unsigned char *dst,unsigned char *src,int len); int ucmp(unsigned char *dst,unsigned char *src,int len);
913efd36cab706c8e2a97ae393b56462ad353150
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
/lib/libc/mingw/secapi/_strtime_s.c
b66e3f95a8d8d7fb30a5e11fb6f3e309029f32b2
[ "LGPL-2.0-or-later", "ZPL-2.1", "LicenseRef-scancode-public-domain", "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
1,366
c
_strtime_s.c
#include <windows.h> #include <malloc.h> #include <time.h> #include <errno.h> #include <msvcrt.h> static errno_t __cdecl _int_strtime_s (char *, size_t); static errno_t __cdecl _stub (char *, size_t); errno_t __cdecl (*__MINGW_IMP_SYMBOL(_strtime_s))(char *, size_t) = _stub; static errno_t __cdecl _stub (char *d, size_t dn) { errno_t __cdecl (*f)(char *, size_t) = __MINGW_IMP_SYMBOL(_strtime_s); if (f == _stub) { f = (errno_t __cdecl (*)(char *, size_t)) GetProcAddress (__mingw_get_msvcrt_handle (), "_strtime_s"); if (!f) f = _int_strtime_s; __MINGW_IMP_SYMBOL(_strtime_s) = f; } return (*f)(d, dn); } errno_t __cdecl _strtime_s (char *d, size_t dn) { return _stub (d, dn); } static errno_t __cdecl _int_strtime_s (char *d, size_t dn) { SYSTEMTIME dt; int hours, minutes, seconds; if (!d || !dn) { errno = EINVAL; return EINVAL; } d[0] = 0; if (dn < 9) { errno = ERANGE; return ERANGE; } GetLocalTime (&dt); dt.wYear %= 100; hours = dt.wHour; minutes = dt.wMinute; seconds = dt.wSecond; d[2] = d[5] = ':'; d[0] = (char) (hours / 10 + '0'); d[1] = (char) (hours % 10 + '0'); d[3] = (char) (minutes / 10 + '0'); d[4] = (char) (minutes % 10 + '0'); d[6] = (char) (seconds / 10 + '0'); d[7] = (char) (seconds % 10 + '0'); d[8] = 0; return 0; }
fa10dff0dc57066f927008b88ef6877c629f4343
1f399edf85d995443d01f66d77eca0723886d0ff
/devicemodel/include/xhci.h
ad5e1d961378a38a825ce5205b5f32647db5093f
[ "BSD-3-Clause" ]
permissive
projectacrn/acrn-hypervisor
f9c5864d54929a5d2fa36b5e78c08f19b46b8f98
390740aa1b1e9d62c51f8e3afa0c29e07e43fa23
refs/heads/master
2023-08-18T05:07:01.310327
2023-08-11T07:49:36
2023-08-16T13:20:27
123,983,554
1,059
686
BSD-3-Clause
2023-09-14T09:51:10
2018-03-05T21:52:25
C
UTF-8
C
false
false
15,150
h
xhci.h
/*- * Copyright (c) 2014 Leon Dang <ldang@nahannisys.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 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$ */ #ifndef _XHCI_H_ #define _XHCI_H_ #define PCI_USBREV 0x60 /* USB protocol revision */ enum { /* dsc_slotstate */ XHCI_ST_DISABLED, XHCI_ST_ENABLED, XHCI_ST_DEFAULT, XHCI_ST_ADDRESSED, XHCI_ST_CONFIGURED, XHCI_ST_MAX }; enum { XHCI_ST_SLCTX_DISABLED, XHCI_ST_SLCTX_DEFAULT, XHCI_ST_SLCTX_ADDRESSED, XHCI_ST_SLCTX_CONFIGURED }; enum { XHCI_ST_EPCTX_DISABLED, XHCI_ST_EPCTX_RUNNING, XHCI_ST_EPCTX_HALTED, XHCI_ST_EPCTX_STOPPED, XHCI_ST_EPCTX_ERROR }; #define XHCI_MAX_VIRT_PORTS MIN(USB_MAX_DEVICES, 128) #define XHCI_MAX_ENDPOINTS 32 /* hardcoded - do not change */ #define XHCI_MAX_SCRATCHPADS 32 #define XHCI_MAX_EVENTS (16 * 13) #define XHCI_MAX_COMMANDS (16 * 1) #define XHCI_MAX_RSEG 1 #define XHCI_MAX_TRANSFERS 4 #if USB_MAX_EP_STREAMS == 8 #define XHCI_MAX_STREAMS 8 #define XHCI_MAX_STREAMS_LOG 3 #elif USB_MAX_EP_STREAMS == 1 #define XHCI_MAX_STREAMS 1 #define XHCI_MAX_STREAMS_LOG 0 #else #error "The USB_MAX_EP_STREAMS value is not supported." #endif #define XHCI_DEV_CTX_ADDR_ALIGN 64 /* bytes */ #define XHCI_DEV_CTX_ALIGN 64 /* bytes */ #define XHCI_INPUT_CTX_ALIGN 64 /* bytes */ #define XHCI_SLOT_CTX_ALIGN 32 /* bytes */ #define XHCI_ENDP_CTX_ALIGN 32 /* bytes */ #define XHCI_STREAM_CTX_ALIGN 16 /* bytes */ #define XHCI_TRANS_RING_SEG_ALIGN 16 /* bytes */ #define XHCI_CMD_RING_SEG_ALIGN 64 /* bytes */ #define XHCI_EVENT_RING_SEG_ALIGN 64 /* bytes */ #define XHCI_SCRATCH_BUF_ARRAY_ALIGN 64 /* bytes */ #define XHCI_SCRATCH_BUFFER_ALIGN USB_PAGE_SIZE #define XHCI_TRB_ALIGN 16 /* bytes */ #define XHCI_TD_ALIGN 64 /* bytes */ #define XHCI_PAGE_SIZE 4096 /* bytes */ /* xHCI extended capability supported protocol fileds */ #define DEFINE_EXCP_PROT(name, next_ptr, revmaj, portoff, portcnt) \ struct pci_xhci_excap_prot excap_##name = { \ { \ .cap_id = XHCI_ID_PROTOCOLS, \ .cap_ptr = next_ptr \ }, \ .rev_min = 0x00, \ .rev_maj = revmaj, \ .string = "USB"#revmaj, \ .port_off = portoff, \ .port_cnt = portcnt, \ .psic_prot_def = 0x00, \ .reserve = 0x00 \ } /* Intel ApolloLake xHCI extended capability for DRD. */ #define DEFINE_EXCP_VENDOR_DRD(capid, next_ptr, reg0, reg1) \ struct pci_xhci_excap_drd_apl excap_drd_apl = { \ { \ .cap_id = capid, \ .cap_ptr = next_ptr \ }, \ .padding = {0}, \ .drdcfg0 = reg0, \ .drdcfg1 = reg1 \ } struct xhci_slot_ctx { volatile uint32_t dwSctx0; #define XHCI_SCTX_0_ROUTE_SET(x) ((x) & 0xFFFFF) #define XHCI_SCTX_0_ROUTE_GET(x) ((x) & 0xFFFFF) #define XHCI_SCTX_0_SPEED_SET(x) (((x) & 0xF) << 20) #define XHCI_SCTX_0_SPEED_GET(x) (((x) >> 20) & 0xF) #define XHCI_SCTX_0_MTT_SET(x) (((x) & 0x1) << 25) #define XHCI_SCTX_0_MTT_GET(x) (((x) >> 25) & 0x1) #define XHCI_SCTX_0_HUB_SET(x) (((x) & 0x1) << 26) #define XHCI_SCTX_0_HUB_GET(x) (((x) >> 26) & 0x1) #define XHCI_SCTX_0_CTX_NUM_SET(x) (((x) & 0x1F) << 27) #define XHCI_SCTX_0_CTX_NUM_GET(x) (((x) >> 27) & 0x1F) volatile uint32_t dwSctx1; #define XHCI_SCTX_1_MAX_EL_SET(x) ((x) & 0xFFFF) #define XHCI_SCTX_1_MAX_EL_GET(x) ((x) & 0xFFFF) #define XHCI_SCTX_1_RH_PORT_SET(x) (((x) & 0xFF) << 16) #define XHCI_SCTX_1_RH_PORT_GET(x) (((x) >> 16) & 0xFF) #define XHCI_SCTX_1_NUM_PORTS_SET(x) (((x) & 0xFF) << 24) #define XHCI_SCTX_1_NUM_PORTS_GET(x) (((x) >> 24) & 0xFF) volatile uint32_t dwSctx2; #define XHCI_SCTX_2_TT_HUB_SID_SET(x) ((x) & 0xFF) #define XHCI_SCTX_2_TT_HUB_SID_GET(x) ((x) & 0xFF) #define XHCI_SCTX_2_TT_PORT_NUM_SET(x) (((x) & 0xFF) << 8) #define XHCI_SCTX_2_TT_PORT_NUM_GET(x) (((x) >> 8) & 0xFF) #define XHCI_SCTX_2_TT_THINK_TIME_SET(x) (((x) & 0x3) << 16) #define XHCI_SCTX_2_TT_THINK_TIME_GET(x) (((x) >> 16) & 0x3) #define XHCI_SCTX_2_IRQ_TARGET_SET(x) (((x) & 0x3FF) << 22) #define XHCI_SCTX_2_IRQ_TARGET_GET(x) (((x) >> 22) & 0x3FF) volatile uint32_t dwSctx3; #define XHCI_SCTX_3_DEV_ADDR_SET(x) ((x) & 0xFF) #define XHCI_SCTX_3_DEV_ADDR_GET(x) ((x) & 0xFF) #define XHCI_SCTX_3_SLOT_STATE_SET(x) (((x) & 0x1F) << 27) #define XHCI_SCTX_3_SLOT_STATE_GET(x) (((x) >> 27) & 0x1F) volatile uint32_t dwSctx4; volatile uint32_t dwSctx5; volatile uint32_t dwSctx6; volatile uint32_t dwSctx7; }; struct xhci_endp_ctx { volatile uint32_t dwEpCtx0; #define XHCI_EPCTX_0_EPSTATE_SET(x) ((x) & 0x7) #define XHCI_EPCTX_0_EPSTATE_GET(x) ((x) & 0x7) #define XHCI_EPCTX_0_MULT_SET(x) (((x) & 0x3) << 8) #define XHCI_EPCTX_0_MULT_GET(x) (((x) >> 8) & 0x3) #define XHCI_EPCTX_0_MAXP_STREAMS_SET(x) (((x) & 0x1F) << 10) #define XHCI_EPCTX_0_MAXP_STREAMS_GET(x) (((x) >> 10) & 0x1F) #define XHCI_EPCTX_0_LSA_SET(x) (((x) & 0x1) << 15) #define XHCI_EPCTX_0_LSA_GET(x) (((x) >> 15) & 0x1) #define XHCI_EPCTX_0_IVAL_SET(x) (((x) & 0xFF) << 16) #define XHCI_EPCTX_0_IVAL_GET(x) (((x) >> 16) & 0xFF) volatile uint32_t dwEpCtx1; #define XHCI_EPCTX_1_CERR_SET(x) (((x) & 0x3) << 1) #define XHCI_EPCTX_1_CERR_GET(x) (((x) >> 1) & 0x3) #define XHCI_EPCTX_1_EPTYPE_SET(x) (((x) & 0x7) << 3) #define XHCI_EPCTX_1_EPTYPE_GET(x) (((x) >> 3) & 0x7) #define XHCI_EPCTX_1_HID_SET(x) (((x) & 0x1) << 7) #define XHCI_EPCTX_1_HID_GET(x) (((x) >> 7) & 0x1) #define XHCI_EPCTX_1_MAXB_SET(x) (((x) & 0xFF) << 8) #define XHCI_EPCTX_1_MAXB_GET(x) (((x) >> 8) & 0xFF) #define XHCI_EPCTX_1_MAXP_SIZE_SET(x) (((x) & 0xFFFF) << 16) #define XHCI_EPCTX_1_MAXP_SIZE_GET(x) (((x) >> 16) & 0xFFFF) volatile uint64_t qwEpCtx2; #define XHCI_EPCTX_2_DCS_SET(x) ((x) & 0x1) #define XHCI_EPCTX_2_DCS_GET(x) ((x) & 0x1) #define XHCI_EPCTX_2_TR_DQ_PTR_MASK 0xFFFFFFFFFFFFFFF0U volatile uint32_t dwEpCtx4; #define XHCI_EPCTX_4_AVG_TRB_LEN_SET(x) ((x) & 0xFFFF) #define XHCI_EPCTX_4_AVG_TRB_LEN_GET(x) ((x) & 0xFFFF) #define XHCI_EPCTX_4_MAX_ESIT_PAYLOAD_SET(x) (((x) & 0xFFFF) << 16) #define XHCI_EPCTX_4_MAX_ESIT_PAYLOAD_GET(x) (((x) >> 16) & 0xFFFF) volatile uint32_t dwEpCtx5; volatile uint32_t dwEpCtx6; volatile uint32_t dwEpCtx7; }; #define XHCI_EPTYPE_INVALID 0 #define XHCI_EPTYPE_ISOC_OUT 1 #define XHCI_EPTYPE_BULK_OUT 2 #define XHCI_EPTYPE_INT_OUT 3 #define XHCI_EPTYPE_CTRL 4 #define XHCI_EPTYPE_ISOC_IN 5 #define XHCI_EPTYPE_BULK_IN 6 #define XHCI_EPTYPE_INT_IN 7 struct xhci_input_ctx { #define XHCI_INCTX_NON_CTRL_MASK 0xFFFFFFFCU volatile uint32_t dwInCtx0; #define XHCI_INCTX_0_DROP_MASK(n) (1U << (n)) volatile uint32_t dwInCtx1; #define XHCI_INCTX_1_ADD_MASK(n) (1U << (n)) volatile uint32_t dwInCtx2; volatile uint32_t dwInCtx3; volatile uint32_t dwInCtx4; volatile uint32_t dwInCtx5; volatile uint32_t dwInCtx6; volatile uint32_t dwInCtx7; }; struct xhci_input_dev_ctx { struct xhci_input_ctx ctx_input; union { struct xhci_slot_ctx u_slot; struct xhci_endp_ctx u_ep[XHCI_MAX_ENDPOINTS]; } ctx_dev_slep; }; struct xhci_dev_ctx { union { struct xhci_slot_ctx u_slot; struct xhci_endp_ctx u_ep[XHCI_MAX_ENDPOINTS]; } ctx_dev_slep; } __aligned(XHCI_DEV_CTX_ALIGN); #define ctx_slot ctx_dev_slep.u_slot #define ctx_ep ctx_dev_slep.u_ep struct xhci_stream_ctx { volatile uint64_t qwSctx0; #define XHCI_SCTX_0_DCS_GET(x) ((x) & 0x1) #define XHCI_SCTX_0_DCS_SET(x) ((x) & 0x1) #define XHCI_SCTX_0_SCT_SET(x) (((x) & 0x7) << 1) #define XHCI_SCTX_0_SCT_GET(x) (((x) >> 1) & 0x7) #define XHCI_SCTX_0_SCT_SEC_TR_RING 0x0 #define XHCI_SCTX_0_SCT_PRIM_TR_RING 0x1 #define XHCI_SCTX_0_SCT_PRIM_SSA_8 0x2 #define XHCI_SCTX_0_SCT_PRIM_SSA_16 0x3 #define XHCI_SCTX_0_SCT_PRIM_SSA_32 0x4 #define XHCI_SCTX_0_SCT_PRIM_SSA_64 0x5 #define XHCI_SCTX_0_SCT_PRIM_SSA_128 0x6 #define XHCI_SCTX_0_SCT_PRIM_SSA_256 0x7 #define XHCI_SCTX_0_TR_DQ_PTR_MASK 0xFFFFFFFFFFFFFFF0U volatile uint32_t dwSctx2; volatile uint32_t dwSctx3; }; struct xhci_trb { volatile uint64_t qwTrb0; #define XHCI_TRB_0_DIR_IN_MASK (0x80ULL << 0) #define XHCI_TRB_0_WLENGTH_MASK (0xFFFFULL << 48) volatile uint32_t dwTrb2; #define XHCI_TRB_2_ERROR_GET(x) (((x) >> 24) & 0xFF) #define XHCI_TRB_2_ERROR_SET(x) (((x) & 0xFF) << 24) #define XHCI_TRB_2_TDSZ_GET(x) (((x) >> 17) & 0x1F) #define XHCI_TRB_2_TDSZ_SET(x) (((x) & 0x1F) << 17) #define XHCI_TRB_2_REM_GET(x) ((x) & 0xFFFFFF) #define XHCI_TRB_2_REM_SET(x) ((x) & 0xFFFFFF) #define XHCI_TRB_2_BYTES_GET(x) ((x) & 0x1FFFF) #define XHCI_TRB_2_BYTES_SET(x) ((x) & 0x1FFFF) #define XHCI_TRB_2_IRQ_GET(x) (((x) >> 22) & 0x3FF) #define XHCI_TRB_2_IRQ_SET(x) (((x) & 0x3FF) << 22) #define XHCI_TRB_2_STREAM_GET(x) (((x) >> 16) & 0xFFFF) #define XHCI_TRB_2_STREAM_SET(x) (((x) & 0xFFFF) << 16) volatile uint32_t dwTrb3; #define XHCI_TRB_3_TYPE_GET(x) (((x) >> 10) & 0x3F) #define XHCI_TRB_3_TYPE_SET(x) (((x) & 0x3F) << 10) #define XHCI_TRB_3_CYCLE_BIT (1U << 0) #define XHCI_TRB_3_TC_BIT (1U << 1) /* command ring only */ #define XHCI_TRB_3_ENT_BIT (1U << 1) /* transfer ring only */ #define XHCI_TRB_3_ISP_BIT (1U << 2) #define XHCI_TRB_3_ED_BIT (1U << 2) #define XHCI_TRB_3_NSNOOP_BIT (1U << 3) #define XHCI_TRB_3_CHAIN_BIT (1U << 4) #define XHCI_TRB_3_IOC_BIT (1U << 5) #define XHCI_TRB_3_IDT_BIT (1U << 6) #define XHCI_TRB_3_TBC_GET(x) (((x) >> 7) & 3) #define XHCI_TRB_3_TBC_SET(x) (((x) & 3) << 7) #define XHCI_TRB_3_BEI_BIT (1U << 9) #define XHCI_TRB_3_DCEP_BIT (1U << 9) #define XHCI_TRB_3_PRSV_BIT (1U << 9) #define XHCI_TRB_3_BSR_BIT (1U << 9) #define XHCI_TRB_3_TRT_MASK (3U << 16) #define XHCI_TRB_3_TRT_NONE (0U << 16) #define XHCI_TRB_3_TRT_OUT (2U << 16) #define XHCI_TRB_3_TRT_IN (3U << 16) #define XHCI_TRB_3_DIR_IN (1U << 16) #define XHCI_TRB_3_TLBPC_GET(x) (((x) >> 16) & 0xF) #define XHCI_TRB_3_TLBPC_SET(x) (((x) & 0xF) << 16) #define XHCI_TRB_3_EP_GET(x) (((x) >> 16) & 0x1F) #define XHCI_TRB_3_EP_SET(x) (((x) & 0x1F) << 16) #define XHCI_TRB_3_FRID_GET(x) (((x) >> 20) & 0x7FF) #define XHCI_TRB_3_FRID_SET(x) (((x) & 0x7FF) << 20) #define XHCI_TRB_3_ISO_SIA_BIT (1U << 31) #define XHCI_TRB_3_SUSP_EP_BIT (1U << 23) #define XHCI_TRB_3_SLOT_GET(x) (((x) >> 24) & 0xFF) #define XHCI_TRB_3_SLOT_SET(x) (((x) & 0xFF) << 24) /* Commands */ #define XHCI_TRB_TYPE_RESERVED 0x00 #define XHCI_TRB_TYPE_NORMAL 0x01 #define XHCI_TRB_TYPE_SETUP_STAGE 0x02 #define XHCI_TRB_TYPE_DATA_STAGE 0x03 #define XHCI_TRB_TYPE_STATUS_STAGE 0x04 #define XHCI_TRB_TYPE_ISOCH 0x05 #define XHCI_TRB_TYPE_LINK 0x06 #define XHCI_TRB_TYPE_EVENT_DATA 0x07 #define XHCI_TRB_TYPE_NOOP 0x08 #define XHCI_TRB_TYPE_ENABLE_SLOT 0x09 #define XHCI_TRB_TYPE_DISABLE_SLOT 0x0A #define XHCI_TRB_TYPE_ADDRESS_DEVICE 0x0B #define XHCI_TRB_TYPE_CONFIGURE_EP 0x0C #define XHCI_TRB_TYPE_EVALUATE_CTX 0x0D #define XHCI_TRB_TYPE_RESET_EP 0x0E #define XHCI_TRB_TYPE_STOP_EP 0x0F #define XHCI_TRB_TYPE_SET_TR_DEQUEUE 0x10 #define XHCI_TRB_TYPE_RESET_DEVICE 0x11 #define XHCI_TRB_TYPE_FORCE_EVENT 0x12 #define XHCI_TRB_TYPE_NEGOTIATE_BW 0x13 #define XHCI_TRB_TYPE_SET_LATENCY_TOL 0x14 #define XHCI_TRB_TYPE_GET_PORT_BW 0x15 #define XHCI_TRB_TYPE_FORCE_HEADER 0x16 #define XHCI_TRB_TYPE_NOOP_CMD 0x17 /* Events */ #define XHCI_TRB_EVENT_TRANSFER 0x20 #define XHCI_TRB_EVENT_CMD_COMPLETE 0x21 #define XHCI_TRB_EVENT_PORT_STS_CHANGE 0x22 #define XHCI_TRB_EVENT_BW_REQUEST 0x23 #define XHCI_TRB_EVENT_DOORBELL 0x24 #define XHCI_TRB_EVENT_HOST_CTRL 0x25 #define XHCI_TRB_EVENT_DEVICE_NOTIFY 0x26 #define XHCI_TRB_EVENT_MFINDEX_WRAP 0x27 /* Error codes */ #define XHCI_TRB_ERROR_INVALID 0x00 #define XHCI_TRB_ERROR_SUCCESS 0x01 #define XHCI_TRB_ERROR_DATA_BUF 0x02 #define XHCI_TRB_ERROR_BABBLE 0x03 #define XHCI_TRB_ERROR_XACT 0x04 #define XHCI_TRB_ERROR_TRB 0x05 #define XHCI_TRB_ERROR_STALL 0x06 #define XHCI_TRB_ERROR_RESOURCE 0x07 #define XHCI_TRB_ERROR_BANDWIDTH 0x08 #define XHCI_TRB_ERROR_NO_SLOTS 0x09 #define XHCI_TRB_ERROR_STREAM_TYPE 0x0A #define XHCI_TRB_ERROR_SLOT_NOT_ON 0x0B #define XHCI_TRB_ERROR_ENDP_NOT_ON 0x0C #define XHCI_TRB_ERROR_SHORT_PKT 0x0D #define XHCI_TRB_ERROR_RING_UNDERRUN 0x0E #define XHCI_TRB_ERROR_RING_OVERRUN 0x0F #define XHCI_TRB_ERROR_VF_RING_FULL 0x10 #define XHCI_TRB_ERROR_PARAMETER 0x11 #define XHCI_TRB_ERROR_BW_OVERRUN 0x12 #define XHCI_TRB_ERROR_CONTEXT_STATE 0x13 #define XHCI_TRB_ERROR_NO_PING_RESP 0x14 #define XHCI_TRB_ERROR_EV_RING_FULL 0x15 #define XHCI_TRB_ERROR_INCOMPAT_DEV 0x16 #define XHCI_TRB_ERROR_MISSED_SERVICE 0x17 #define XHCI_TRB_ERROR_CMD_RING_STOP 0x18 #define XHCI_TRB_ERROR_CMD_ABORTED 0x19 #define XHCI_TRB_ERROR_STOPPED 0x1A #define XHCI_TRB_ERROR_LENGTH 0x1B #define XHCI_TRB_ERROR_BAD_MELAT 0x1D #define XHCI_TRB_ERROR_ISOC_OVERRUN 0x1F #define XHCI_TRB_ERROR_EVENT_LOST 0x20 #define XHCI_TRB_ERROR_UNDEFINED 0x21 #define XHCI_TRB_ERROR_INVALID_SID 0x22 #define XHCI_TRB_ERROR_SEC_BW 0x23 #define XHCI_TRB_ERROR_SPLIT_XACT 0x24 } __aligned(8); /* * The Block Event Interrupt (BEI) bit in the TRB descriptor could * delay the triggering of interrupt. For most OSes, the native * driver for xHCI will use this bit to optimize the IO performence, * due to reduction of number of interrupts. * * But in Linux, the native xHCI driver for Intel brand controller * doesn't use this bit. It is fine for the native scenario due to * most work is completed by hardware. But in virtualization scenario, * it is almost impossible to support heavy data IO such as high * resolution video recording (ISOC transfer). * * Hence, this issue is solved by a 'quirk' when the intel hardware is * emulated (when vendor id is set as 0x8086). For other cases, a * virtal hardware called 'ACRN xHCI' is emulated, and both Linux and * Windows will use BEI bit by default. */ #define XHCI_QUIRK_INTEL_ISOCH_NO_BEI (1 << 0) struct xhci_dev_endpoint_trbs { struct xhci_trb trb[(XHCI_MAX_STREAMS * XHCI_MAX_TRANSFERS) + XHCI_MAX_STREAMS]; }; struct xhci_erst { volatile uint64_t qwRingSegBase; volatile uint32_t dwRingSegSize; volatile uint32_t dwRingSegRsv; }; #endif /* _XHCI_H_ */
a82a1148b1a72b816d3429810b143bd8dbf8576d
ecce427678ecff2a93a47f3b1b664202c7d27617
/actors/chuckya/anims/data.inc.c
3eaa6d96f9000ddceece2e07171b8aab61f9d895
[]
no_license
sm64pc/sm64ex
ecf37f31b3f7426c4874254660d856030d789714
54cd27ccee45a2403b45f07a00d6043c51149969
refs/heads/nightly
2023-08-11T12:14:34.424168
2023-07-01T11:45:50
2023-07-01T11:45:50
262,091,731
795
238
null
2023-07-01T11:45:51
2020-05-07T15:43:27
C
UTF-8
C
false
false
186
c
data.inc.c
#include "anim_0800AF68.inc.c" #include "anim_0800B1A8.inc.c" #include "anim_0800B4A8.inc.c" #include "anim_0800B9F8.inc.c" #include "anim_0800BBEC.inc.c" #include "anim_0800C058.inc.c"
7f56a13fc50f16864e4de1541e835654d79a98a8
08fb252e3f70e245cdd0e5a8fed47f6fada8b6f8
/src/evolve.c
a93283c1459f6074941969314244d46c6bae94b3
[ "MIT" ]
permissive
VirtualPlanetaryLaboratory/vplanet
3bba2126520cbe7bee1a512f87435064d3545517
cb683af69e80e07bc17c06e45678effdc98fc19a
refs/heads/main
2023-08-31T04:13:58.700282
2023-08-30T05:10:20
2023-08-30T05:10:20
138,067,409
128
54
MIT
2023-09-06T21:30:37
2018-06-20T17:53:00
C
UTF-8
C
false
false
28,904
c
evolve.c
/** @file evolve.c @brief This file contains all the core VPLANET integration routines including the timestepping algorithm and the Runge-Kutta Integration scheme. @author Rory Barnes ([RoryBarnes](https://github.com/RoryBarnes/)) @date May 2014 */ #define NUM_THREADS 4 #include "vplanet.h" void PropsAuxGeneral(BODY *body, CONTROL *control) { /* Recompute the mean motion, necessary for most modules */ int iBody; // Dummy counting variable for (iBody = 0; iBody < control->Evolve.iNumBodies; iBody++) { if (iBody != 0 && body[iBody].bBinary == 0) { body[iBody].dMeanMotion = fdSemiToMeanMotion( body[iBody].dSemi, (body[0].dMass + body[iBody].dMass)); } } } void PropertiesAuxiliary(BODY *body, CONTROL *control, SYSTEM *system, UPDATE *update) { /* Evaluate single and multi-module auxialliary functions to update parameters * of interest such as mean motion. */ int iBody, iModule; // Dummy counter variables PropsAuxGeneral(body, control); /* Get properties from each module */ for (iBody = 0; iBody < control->Evolve.iNumBodies; iBody++) { // Uni-module properties for (iModule = 0; iModule < control->Evolve.iNumModules[iBody]; iModule++) { control->fnPropsAux[iBody][iModule](body, &control->Evolve, &control->Io, update, iBody); } // Multi-module properties for (iModule = 0; iModule < control->iNumMultiProps[iBody]; iModule++) { control->fnPropsAuxMulti[iBody][iModule](body, &control->Evolve, &control->Io, update, iBody); } } } void CalculateDerivatives(BODY *body, SYSTEM *system, UPDATE *update, fnUpdateVariable ***fnUpdate, int iNumBodies) { int iBody, iVar, iEqn; for (iBody = 0; iBody < iNumBodies; iBody++) { for (iVar = 0; iVar < update[iBody].iNumVars; iVar++) { update[iBody].daDeriv[iVar] = 0; for (iEqn = 0; iEqn < update[iBody].iNumEqns[iVar]; iEqn++) { update[iBody].daDerivProc[iVar][iEqn] = fnUpdate[iBody][iVar][iEqn]( body, system, update[iBody].iaBody[iVar][iEqn]); update[iBody].daDeriv[iVar] += update[iBody].daDerivProc[iVar][iEqn]; } } } iBody = 0; } void CheckProgress(BODY *body, CONTROL *control, SYSTEM *system, UPDATE *update) { int iBody, jBody; if (control->Io.iVerbose >= VERBPROG && !control->Io.bMutualIncMessage && control->Io.dMaxMutualInc > 0) { // If made it here, more than 1 body must be present if (body[1].bSpiNBody) { // Calculate orbital elements for (iBody = 0; iBody < control->Evolve.iNumBodies; iBody++) { cart2osc(body, iBody); } } // Skip central body for (iBody = 1; iBody < control->Evolve.iNumBodies; iBody++) { for (jBody = iBody + 1; jBody < control->Evolve.iNumBodies; jBody++) { // 1 to check progress, not halt if (fbCheckMaxMutualInc(body, &control->Evolve, control->Halt, &control->Io, iBody, jBody, 1)) { /* if (control->Io.iVerbose >= VERBPROG) { printf("WARNING: Mutual inclination of %s and %s exceeds ", body[iBody].cName,body[jBody].cName); fprintd(stdout,control->Io.dMaxMutualInc,control->Io.iSciNot, control->Io.iDigits); printf(" at t = %.2e years.\n",control->Evolve.dTime); } */ control->Io.bMutualIncMessage = 1; } } } } } /* * Integration Control */ double AssignDt(double dMin, double dNextOutput, double dEta) { /* Compute the next timestep, dt, making sure it's not larger than the output * cadence */ dMin = dEta * dMin; if (dNextOutput < dMin) { dMin = dNextOutput; } return dMin; } double fdGetTimeStep(BODY *body, CONTROL *control, SYSTEM *system, UPDATE *update, fnUpdateVariable ***fnUpdate) { /* Fills the Update arrays with the derivatives * or new values. It returns the smallest timescale for use * in variable timestepping. Uses either a 4th order Runge-Kutte integrator or * an Euler step. */ int iBody, iVar, iEqn; // Dummy counting variables EVOLVE integr; // Dummy EVOLVE struct so we don't have to dereference control a lot double dVarNow, dMinNow, dMin = dHUGE, dVarTotal; // Intermediate storage variables integr = control->Evolve; dMin = dHUGE; for (iBody = 0; iBody < control->Evolve.iNumBodies; iBody++) { if (update[iBody].iNumVars > 0) { for (iVar = 0; iVar < update[iBody].iNumVars; iVar++) { // The parameter does not require a derivative, but is calculated // explicitly as a function of age. /* printf("%d %d\n",iBody,iVar); fflush(stdout); */ if (update[iBody].iaType[iVar][0] == 0) { dVarNow = *update[iBody].pdVar[iVar]; for (iEqn = 0; iEqn < update[iBody].iNumEqns[iVar]; iEqn++) { update[iBody].daDerivProc[iVar][iEqn] = fnUpdate[iBody][iVar][iEqn]( body, system, update[iBody].iaBody[iVar][iEqn]); } if (control->Evolve.bFirstStep) { dMin = integr.dTimeStep; control->Evolve.bFirstStep = 0; } else { /* Sum over all equations giving new value of the variable */ dVarTotal = 0.; for (iEqn = 0; iEqn < update[iBody].iNumEqns[iVar]; iEqn++) { dVarTotal += update[iBody].daDerivProc[iVar][iEqn]; } // Prevent division by zero if (dVarNow != dVarTotal) { dMinNow = fabs(dVarNow / ((dVarNow - dVarTotal) / integr.dTimeStep)); if (dMinNow < dMin) { dMin = dMinNow; } } } /* Equations that are integrated in the matrix but are NOT allowed to dictate timestepping. These are derived quantities, like lost energy, that must be integrated as primary variables to keep track of them properly, i.e. lost energy depends on changing radii, which are integrated. But in this case, since they are derived quantities, they should NOT participate in timestep selection - dflemin3 */ } else if (update[iBody].iaType[iVar][0] == 5) { // continue; for (iEqn = 0; iEqn < update[iBody].iNumEqns[iVar]; iEqn++) { update[iBody].daDerivProc[iVar][iEqn] = fnUpdate[iBody][iVar][iEqn]( body, system, update[iBody].iaBody[iVar][iEqn]); } /* Integration for binary, where parameters can be computed via derivatives, or as an explicit function of age */ } else if (update[iBody].iaType[iVar][0] == 10) { /* Equations not in matrix, computing things as explicit function of time, so we set dMin to time until next output Figure out time until next output */ dMinNow = control->Io.dNextOutput; if (dMinNow < dMin) { dMin = dMinNow; } /* The parameter does not require a derivative, but is calculated explicitly as a function of age and is a sinusoidal quantity (e.g. h,k,p,q in DistOrb) */ } else if (update[iBody].iaType[iVar][0] == 3) { dVarNow = *update[iBody].pdVar[iVar]; for (iEqn = 0; iEqn < update[iBody].iNumEqns[iVar]; iEqn++) { update[iBody].daDerivProc[iVar][iEqn] = fnUpdate[iBody][iVar][iEqn]( body, system, update[iBody].iaBody[iVar][iEqn]); } if (control->Evolve.bFirstStep) { dMin = integr.dTimeStep; control->Evolve.bFirstStep = 0; } else { /* Sum over all equations giving new value of the variable */ dVarTotal = 0.; for (iEqn = 0; iEqn < update[iBody].iNumEqns[iVar]; iEqn++) { dVarTotal += update[iBody].daDerivProc[iVar][iEqn]; } // Prevent division by zero if (dVarNow != dVarTotal) { dMinNow = fabs(1.0 / ((dVarNow - dVarTotal) / integr.dTimeStep)); if (dMinNow < dMin) { dMin = dMinNow; } } } /* The parameter is a "polar/sinusoidal quantity" and controlled by a time derivative */ } else { for (iEqn = 0; iEqn < update[iBody].iNumEqns[iVar]; iEqn++) { if (update[iBody].iaType[iVar][iEqn] == 2) { update[iBody].daDerivProc[iVar][iEqn] = fnUpdate[iBody][iVar][iEqn]( body, system, update[iBody].iaBody[iVar][iEqn]); // if (update[iBody].daDerivProc[iVar][iEqn] != 0 && // *(update[iBody].pdVar[iVar]) != 0) { if (update[iBody].daDerivProc[iVar][iEqn] != 0) { /* ?Obl require special treatment because they can overconstrain obliquity and PrecA */ if (iVar == update[iBody].iXobl || iVar == update[iBody].iYobl || iVar == update[iBody].iZobl) { if (body[iBody].dObliquity != 0) { dMinNow = fabs(sin(body[iBody].dObliquity) / update[iBody].daDerivProc[iVar][iEqn]); } else { // Obliquity is 0, so its evolution shouldn't impact // the timestep dMinNow = dHUGE; } } else if (iVar == update[iBody].iHecc || iVar == update[iBody].iKecc) { if (body[iBody].dEcc != 0) { dMinNow = fabs(body[iBody].dEcc / update[iBody].daDerivProc[iVar][iEqn]); } else { // Eccentricity is 0, so its evolution shouldn't // impact the timestep dMinNow = dHUGE; } } else { dMinNow = fabs(1.0 / update[iBody].daDerivProc[iVar][iEqn]); } if (dMinNow < dMin) { dMin = dMinNow; } } // enforce a minimum step size for ice sheets, otherwise dDt -> 0 // real fast } else if (update[iBody].iaType[iVar][iEqn] == 9) { update[iBody].daDerivProc[iVar][iEqn] = fnUpdate[iBody][iVar][iEqn]( body, system, update[iBody].iaBody[iVar][iEqn]); if (update[iBody].daDerivProc[iVar][iEqn] != 0 && *(update[iBody].pdVar[iVar]) != 0) { dMinNow = fabs((*(update[iBody].pdVar[iVar])) / update[iBody].daDerivProc[iVar][iEqn]); if (dMinNow < dMin) { if (dMinNow < control->Halt[iBody].iMinIceDt * (2 * PI / body[iBody].dMeanMotion) / control->Evolve.dEta) { dMin = control->Halt[iBody].iMinIceDt * (2 * PI / body[iBody].dMeanMotion) / control->Evolve.dEta; } else { dMin = dMinNow; } } } /* SpiNBody timestep: As x,y,z can cross over 0, the usual x/(dx/dt) timstep doesn't work. This version compares the orbital radius to velocity. Probably room for improvement here. */ } else if (update[iBody].iaType[iVar][iEqn] == 7) { if ((control->Evolve.bSpiNBodyDistOrb == 0) || (control->Evolve.bUsingSpiNBody == 1)) { update[iBody].daDerivProc[iVar][iEqn] = fnUpdate[iBody][iVar][iEqn]( body, system, update[iBody].iaBody[iVar][iEqn]); dMinNow = sqrt((body[iBody].dPositionX * body[iBody].dPositionX + body[iBody].dPositionY * body[iBody].dPositionY + body[iBody].dPositionZ * body[iBody].dPositionZ) / (body[iBody].dVelX * body[iBody].dVelX + body[iBody].dVelY * body[iBody].dVelY + body[iBody].dVelZ * body[iBody].dVelZ)); if (dMinNow < dMin) { dMin = dMinNow; } } } else { // The parameter is controlled by a time derivative update[iBody].daDerivProc[iVar][iEqn] = fnUpdate[iBody][iVar][iEqn]( body, system, update[iBody].iaBody[iVar][iEqn]); if (!bFloatComparison(update[iBody].daDerivProc[iVar][iEqn], 0.0) && !bFloatComparison(*(update[iBody].pdVar[iVar]), 0.0)) { dMinNow = fabs((*(update[iBody].pdVar[iVar])) / update[iBody].daDerivProc[iVar][iEqn]); if (dMinNow < dMin) { dMin = dMinNow; } } } } // for loop } // else polar/sinusoidal } // for iNumVars } // if (update[iBody].iNumVars > 0) } // for loop iNumBodies return dMin; } void fdGetUpdateInfo(BODY *body, CONTROL *control, SYSTEM *system, UPDATE *update, fnUpdateVariable ***fnUpdate) { /* Fills the Update arrays with the derivatives * or new values.. */ int iBody, iVar, iEqn, iNumBodies, iNumVars, iNumEqns; // Dummy counting variables EVOLVE integr; // Dummy EVOLVE struct so we don't have to dereference control a lot double dVarNow, dMinNow, dMin = dHUGE, dVarTotal; // Intermediate storage variables integr = control->Evolve; iNumBodies = control->Evolve.iNumBodies; for (iBody = 0; iBody < iNumBodies; iBody++) { if (update[iBody].iNumVars > 0) { iNumVars = update[iBody].iNumVars; for (iVar = 0; iVar < iNumVars; iVar++) { iNumEqns = update[iBody].iNumEqns[iVar]; for (iEqn = 0; iEqn < iNumEqns; iEqn++) { update[iBody].daDerivProc[iVar][iEqn] = fnUpdate[iBody][iVar][iEqn]( body, system, update[iBody].iaBody[iVar][iEqn]); } } } } } void EulerStep(BODY *body, CONTROL *control, SYSTEM *system, UPDATE *update, fnUpdateVariable ***fnUpdate, double *dDt, int iDir) { /* Compute and apply an Euler update step to a given parameter (x = dx/dt * * dt) */ int iBody, iVar, iEqn; double dFoo; /* Adjust dt? */ if (control->Evolve.bVarDt) { /* dDt is the dynamical timescale */ *dDt = fdGetTimeStep(body, control, system, update, fnUpdate); *dDt = AssignDt(*dDt, (control->Io.dNextOutput - control->Evolve.dTime), control->Evolve.dEta); } for (iBody = 0; iBody < control->Evolve.iNumBodies; iBody++) { for (iVar = 0; iVar < update[iBody].iNumVars; iVar++) { for (iEqn = 0; iEqn < update[iBody].iNumEqns[iVar]; iEqn++) { if (update[iBody].iaType[iVar][iEqn] == 0) { *(update[iBody].pdVar[iVar]) = update[iBody].daDerivProc[iVar][iEqn]; } else { /* Update the parameter in the BODY struct! Be careful! */ *(update[iBody].pdVar[iVar]) += iDir * update[iBody].daDerivProc[iVar][iEqn] * (*dDt); } } } } } void RungeKutta4Step(BODY *body, CONTROL *control, SYSTEM *system, UPDATE *update, fnUpdateVariable ***fnUpdate, double *dDt, int iDir) { /* Compute and apply a 4th order Runge-Kutta update step a given parameter. */ int iBody, iVar, iEqn, iSubStep, iNumBodies, iNumVars, iNumEqns; double dFoo, dDelta; EVOLVE *evolve = &( control->Evolve); // Save Evolve as a variable for speed and legibility /* Create a copy of BODY array */ BodyCopy(evolve->tmpBody, body, &control->Evolve); /* Derivatives at start */ *dDt = fdGetTimeStep(body, control, system, control->Evolve.tmpUpdate, fnUpdate); /* Adjust dt? */ if (evolve->bVarDt) { /* This is minimum dynamical timescale */ *dDt = AssignDt(*dDt, (control->Io.dNextOutput - evolve->dTime), evolve->dEta); } else { *dDt = evolve->dTimeStep; } evolve->dCurrentDt = *dDt; iNumBodies = evolve->iNumBodies; #pragma omp parallel for num_threads(NUM_THREADS) private(iNumVars, iNumEqns, \ iVar, iEqn) for (iBody = 0; iBody < iNumBodies; iBody++) { // int thread_num = omp_get_thread_num(); // int cpu_num = sched_getcpu(); // printf("Thread %3d is running on CPU %3d\n", thread_num, cpu_num); double daDerivVar; iNumVars = update[iBody].iNumVars; for (iVar = 0; iVar < iNumVars; iVar++) { daDerivVar = 0; iNumEqns = update[iBody].iNumEqns[iVar]; for (iEqn = 0; iEqn < iNumEqns; iEqn++) { daDerivVar += iDir * evolve->tmpUpdate[iBody].daDerivProc[iVar][iEqn]; evolve->daDerivProc[0][iBody][iVar][iEqn] = evolve->tmpUpdate[iBody].daDerivProc[iVar][iEqn]; } evolve->daDeriv[0][iBody][iVar] = daDerivVar; } } for (iBody = 0; iBody < iNumBodies; iBody++) { iNumVars = update[iBody].iNumVars; for (iVar = 0; iVar < iNumVars; iVar++) { if (update[iBody].iaType[iVar][0] == 0 || update[iBody].iaType[iVar][0] == 3 || update[iBody].iaType[iVar][0] == 10) { // LUGER: Note that this is the VALUE of the variable getting passed, // contrary to what the names suggest These values are updated in the // tmpUpdate struct so that equations which are dependent upon them will // be evaluated with higher accuracy *(evolve->tmpUpdate[iBody].pdVar[iVar]) = evolve->daDeriv[0][iBody][iVar]; } else { /* While we're in this loop, move each parameter to the midpoint of the * timestep */ *(evolve->tmpUpdate[iBody].pdVar[iVar]) = *(update[iBody].pdVar[iVar]) + 0.5 * (*dDt) * evolve->daDeriv[0][iBody][iVar]; } } } /* First midpoint derivative.*/ PropertiesAuxiliary(evolve->tmpBody, control, system, update); fdGetUpdateInfo(evolve->tmpBody, control, system, evolve->tmpUpdate, fnUpdate); #pragma omp parallel for num_threads(NUM_THREADS) private(iNumVars, iNumEqns, \ iVar, iEqn) for (iBody = 0; iBody < iNumBodies; iBody++) { iNumVars = update[iBody].iNumVars; double daDerivVar; for (iVar = 0; iVar < iNumVars; iVar++) { daDerivVar = 0; iNumEqns = update[iBody].iNumEqns[iVar]; for (iEqn = 0; iEqn < iNumEqns; iEqn++) { daDerivVar += iDir * evolve->tmpUpdate[iBody].daDerivProc[iVar][iEqn]; evolve->daDerivProc[1][iBody][iVar][iEqn] = evolve->tmpUpdate[iBody].daDerivProc[iVar][iEqn]; } evolve->daDeriv[1][iBody][iVar] = daDerivVar; } } for (iBody = 0; iBody < iNumBodies; iBody++) { iNumVars = update[iBody].iNumVars; for (iVar = 0; iVar < iNumVars; iVar++) { if (update[iBody].iaType[iVar][0] == 0 || update[iBody].iaType[iVar][0] == 3 || update[iBody].iaType[iVar][0] == 10) { // LUGER: Note that this is the VALUE of the variable getting passed, // contrary to what the names suggest These values are updated in the // tmpUpdate struct so that equations which are dependent upon them will // be evaluated with higher accuracy *(evolve->tmpUpdate[iBody].pdVar[iVar]) = evolve->daDeriv[1][iBody][iVar]; } else { /* While we're in this loop, move each parameter to the midpoint of the timestep based on the midpoint derivative. */ *(evolve->tmpUpdate[iBody].pdVar[iVar]) = *(update[iBody].pdVar[iVar]) + 0.5 * (*dDt) * evolve->daDeriv[1][iBody][iVar]; } } } /* Second midpoint derivative */ PropertiesAuxiliary(evolve->tmpBody, control, system, update); fdGetUpdateInfo(evolve->tmpBody, control, system, evolve->tmpUpdate, fnUpdate); #pragma omp parallel for num_threads(NUM_THREADS) private(iNumVars, iNumEqns, \ iVar, iEqn) for (iBody = 0; iBody < iNumBodies; iBody++) { iNumVars = update[iBody].iNumVars; double daDerivVar; for (iVar = 0; iVar < iNumVars; iVar++) { daDerivVar = 0; iNumEqns = update[iBody].iNumEqns[iVar]; for (iEqn = 0; iEqn < iNumEqns; iEqn++) { daDerivVar += iDir * evolve->tmpUpdate[iBody].daDerivProc[iVar][iEqn]; evolve->daDerivProc[2][iBody][iVar][iEqn] = evolve->tmpUpdate[iBody].daDerivProc[iVar][iEqn]; } evolve->daDeriv[2][iBody][iVar] = daDerivVar; } } for (iBody = 0; iBody < iNumBodies; iBody++) { iNumVars = update[iBody].iNumVars; for (iVar = 0; iVar < iNumVars; iVar++) { if (update[iBody].iaType[iVar][0] == 0 || update[iBody].iaType[iVar][0] == 3 || update[iBody].iaType[iVar][0] == 10) { // LUGER: Note that this is the VALUE of the variable getting passed, // contrary to what the names suggest These values are updated in the // tmpUpdate struct so that equations which are dependent upon them will // be evaluated with higher accuracy *(evolve->tmpUpdate[iBody].pdVar[iVar]) = evolve->daDeriv[2][iBody][iVar]; } else { /* While we're in this loop, move each parameter to the end of the timestep based on the second midpoint derivative. */ *(evolve->tmpUpdate[iBody].pdVar[iVar]) = *(update[iBody].pdVar[iVar]) + *dDt * evolve->daDeriv[2][iBody][iVar]; } } } /* Full step derivative */ PropertiesAuxiliary(evolve->tmpBody, control, system, update); fdGetUpdateInfo(evolve->tmpBody, control, system, evolve->tmpUpdate, fnUpdate); #pragma omp parallel for num_threads(NUM_THREADS) private(iNumVars, iNumEqns, \ iVar, iEqn) for (iBody = 0; iBody < iNumBodies; iBody++) { double daDerivVar; iNumVars = update[iBody].iNumVars; for (iVar = 0; iVar < iNumVars; iVar++) { daDerivVar = 0; if (update[iBody].iaType[iVar][0] == 0 || update[iBody].iaType[iVar][0] == 3 || update[iBody].iaType[iVar][0] == 10) { // NOTHING! } else { evolve->daDeriv[3][iBody][iVar] = 0; iNumEqns = update[iBody].iNumEqns[iVar]; for (iEqn = 0; iEqn < iNumEqns; iEqn++) { daDerivVar += iDir * evolve->tmpUpdate[iBody].daDerivProc[iVar][iEqn]; evolve->daDerivProc[3][iBody][iVar][iEqn] = evolve->tmpUpdate[iBody].daDerivProc[iVar][iEqn]; } evolve->daDeriv[3][iBody][iVar] = daDerivVar; } } } /* Now do the update -- Note the pointer to the home of the actual * variables!!! */ for (iBody = 0; iBody < iNumBodies; iBody++) { iNumVars = update[iBody].iNumVars; for (iVar = 0; iVar < iNumVars; iVar++) { update[iBody].daDeriv[iVar] = 1. / 6 * (evolve->daDeriv[0][iBody][iVar] + 2 * evolve->daDeriv[1][iBody][iVar] + 2 * evolve->daDeriv[2][iBody][iVar] + evolve->daDeriv[3][iBody][iVar]); for (iEqn = 0; iEqn < update[iBody].iNumEqns[iVar]; iEqn++) { update[iBody].daDerivProc[iVar][iEqn] = 1. / 6 * (evolve->daDerivProc[0][iBody][iVar][iEqn] + 2 * evolve->daDerivProc[1][iBody][iVar][iEqn] + 2 * evolve->daDerivProc[2][iBody][iVar][iEqn] + evolve->daDerivProc[3][iBody][iVar][iEqn]); } if (update[iBody].iaType[iVar][0] == 0 || update[iBody].iaType[iVar][0] == 3 || update[iBody].iaType[iVar][0] == 10) { // LUGER: Note that this is the VALUE of the variable getting passed, // contrary to what the names suggest *(update[iBody].pdVar[iVar]) = evolve->daDeriv[0][iBody][iVar]; } else { *(update[iBody].pdVar[iVar]) += update[iBody].daDeriv[iVar] * (*dDt); } } } } /* * Evolution Subroutine */ void Evolve(BODY *body, CONTROL *control, FILES *files, MODULE *module, OUTPUT *output, SYSTEM *system, UPDATE *update, fnUpdateVariable ***fnUpdate, fnWriteOutput *fnWrite, fnIntegrate fnOneStep) { /* Master evolution routine that controls the simulation integration. */ int iDir, iBody, iModule, nSteps; // Dummy counting variables double dDt, dFoo; // Next timestep, dummy variable double dEqSpinRate; // Store the equilibrium spin rate nSteps = 0; if (control->Evolve.bDoForward) { iDir = 1; } else { iDir = -1; } PropertiesAuxiliary(body, control, system, update); control->Io.dNextOutput = control->Evolve.dTime + control->Io.dOutputTime; // Get derivatives at start, useful for logging dDt = fdGetTimeStep(body, control, system, update, fnUpdate); /* Adjust dt? */ if (control->Evolve.bVarDt) { /* Now choose the correct timestep */ dDt = AssignDt(dDt, (control->Io.dNextOutput - control->Evolve.dTime), control->Evolve.dEta); } else { dDt = control->Evolve.dTimeStep; } /* Write out initial conditions */ WriteOutput(body, control, files, output, system, update, fnWrite, control->Evolve.dTime, dDt); /* If Runge-Kutta need to copy actual update to that in control->Evolve. This transfer all the meta-data about the struct. */ UpdateCopy(control->Evolve.tmpUpdate, update, control->Evolve.iNumBodies); /* * * Main loop begins here * */ while (control->Evolve.dTime < control->Evolve.dStopTime) { /* Take one step */ fnOneStep(body, control, system, update, fnUpdate, &dDt, iDir); for (iBody = 0; iBody < control->Evolve.iNumBodies; iBody++) { for (iModule = 0; iModule < control->Evolve.iNumModules[iBody]; iModule++) { control->fnForceBehavior[iBody][iModule](body, module, &control->Evolve, &control->Io, system, update, fnUpdate, iBody, iModule); } for (iModule = 0; iModule < control->iNumMultiForce[iBody]; iModule++) { control->fnForceBehaviorMulti[iBody][iModule]( body, module, &control->Evolve, &control->Io, system, update, fnUpdate, iBody, iModule); } } fdGetUpdateInfo(body, control, system, update, fnUpdate); /* Halt? */ if (fbCheckHalt(body, control, update, fnUpdate)) { fdGetUpdateInfo(body, control, system, update, fnUpdate); WriteOutput(body, control, files, output, system, update, fnWrite, control->Evolve.dTime, control->Io.dOutputTime / control->Evolve.nSteps); return; } for (iBody = 0; iBody < control->Evolve.iNumBodies; iBody++) { body[iBody].dAge += iDir * dDt; } control->Evolve.dTime += dDt; nSteps++; /* Time for Output? */ if (control->Evolve.dTime >= control->Io.dNextOutput) { control->Evolve.nSteps += nSteps; WriteOutput(body, control, files, output, system, update, fnWrite, control->Evolve.dTime, control->Io.dOutputTime / control->Evolve.nSteps); // Timesteps are synchronized with the output time, so this statement is // sufficient control->Io.dNextOutput += control->Io.dOutputTime; nSteps = 0; } /* Get auxiliary properties for next step -- first call was prior to loop. */ PropertiesAuxiliary(body, control, system, update); // If control->Evolve.bFirstStep hasn't been switched off by now, do so. if (control->Evolve.bFirstStep) { control->Evolve.bFirstStep = 0; } // Any variables reached an interesting value? CheckProgress(body, control, system, update); } if (control->Io.iVerbose >= VERBPROG) { printf("Evolution completed.\n"); } // printf("%d\n",body[1].iBadImpulse); }
f3535eb29f08461e0a6239356f7d86b9731337ed
1095cfe2e29ddf4e4c5e12d713bd12f45c9b6f7d
/ext/fputils/tests/fp80_cvfd.c
132a23738d15ace4080e52ece9f47ee5ccfcf3b2
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license", "LGPL-2.0-or-later", "MIT" ]
permissive
gem5/gem5
9ec715ae036c2e08807b5919f114e1d38d189bce
48a40cf2f5182a82de360b7efa497d82e06b1631
refs/heads/stable
2023-09-03T15:56:25.819189
2023-08-31T05:53:03
2023-08-31T05:53:03
27,425,638
1,185
1,177
BSD-3-Clause
2023-09-14T08:29:31
2014-12-02T09:46:00
C++
UTF-8
C
false
false
4,243
c
fp80_cvfd.c
/* * Copyright (c) 2013 Andreas Sandberg * All rights reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. * * Authors: Andreas Sandberg */ #include <fputils/fp80.h> #include "test_helper.h" #include <assert.h> #include <math.h> #include <stdio.h> #include <stdlib.h> static void test_cvfd_class(const char *name, double fin) { test_diag("converting '%e' -> fp80...", fin); fp80_t v = fp80_cvfd(fin); int class_ok; int fp64_class = fpclassify(fin); int class = fp64_class == FP_SUBNORMAL ? FP_NORMAL : fp64_class; int fp80_class = fp80_classify(v); printf("# "); fp80_debug_dump(stdout, v); test_diag("isnan: %i, isinf: %i, iszero: %i, isnormal: %i, issubnormal: %i", fp80_isnan(v), fp80_isinf(v), fp80_iszero(v), fp80_isnormal(v), fp80_issubnormal(v)); test_diag("class(fp64): %i, expected class: %i, class(fp80): %i", fp64_class, class, fp80_classify(v)); switch (class) { case FP_NAN: class_ok = fp80_isnan(v) && !fp80_isinf(v) && !fp80_iszero(v) && !fp80_isnormal(v) && !fp80_issubnormal(v); break; case FP_INFINITE: class_ok = !fp80_isnan(v) && fp80_isinf(v) && !fp80_iszero(v) && !fp80_isnormal(v) && !fp80_issubnormal(v); break; case FP_ZERO: class_ok = !fp80_isnan(v) && !fp80_isinf(v) && fp80_iszero(v) && !fp80_isnormal(v) && !fp80_issubnormal(v); break; case FP_SUBNORMAL: class_ok = !fp80_isnan(v) && !fp80_isinf(v) && !fp80_iszero(v) && !fp80_isnormal(v) && fp80_issubnormal(v); break; case FP_NORMAL: class_ok = !fp80_isnan(v) && !fp80_isinf(v) && !fp80_iszero(v) && fp80_isnormal(v) && !fp80_issubnormal(v); break; default: test_bail("unexpected FP class (%i)", class); } if (!class_ok) { test_diag("inconsistent classification"); test_fail(name); } else if (fp80_class != class) { test_diag("class mismatch"); test_fail(name); } else { test_ok(name); } } static void test_cvfd_class_exp(const char *name, double x, int exp) { double val = ldexp(x, exp); test_cvfd_class(name, val); } int main(int argc, char *argv[]) { test_init(9); test_cvfd_class("double->fp80 +inf", -INFINITY); test_cvfd_class("double->fp80 -inf", INFINITY); test_cvfd_class("double->fp80 +nan", NAN); test_cvfd_class("double->fp80 -nan", -NAN); test_cvfd_class("double->fp80 +0", 0); test_cvfd_class("double->fp80 PI", M_PI); test_cvfd_class_exp("double->fp80 smallest normal", 1.0, -1022); test_cvfd_class_exp("double->fp80 denormal1", 0.5, -1022); test_cvfd_class_exp("double->fp80 denormal2", 0.25, -1022); test_exit(); }
f651f9f6a8e7fefeefd14e8a35bf4edc8ce6bea5
533d5e1a40def1e1118895f6ba2b4d503c918d1a
/tools/BORLANDC/CRTL/CLIB/CTIME.C
a8acb9efa8cca641e3945cb5917ed75bb0672452
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
gandrewstone/GameMaker
415cccdf0f9ecf5f339b7551469f07d53e43a6fd
1fe0070a9f8412b5b53923aae7e64769722685a3
refs/heads/master
2020-06-12T19:30:07.252432
2014-07-14T14:38:55
2014-07-14T14:38:55
21,754,773
103
23
null
null
null
null
UTF-8
C
false
false
13,788
c
CTIME.C
/*------------------------------------------------------------------------ * filename - ctime.c * * function(s) * comtime - converts long timedate to a structure * atime - converts date and time to ASCII without trailing '\n' * asctime - converts date and time to ASCII * ctime - converts date and time to a string * gmtime - converts date and time to Greenwich Mean Time * localtime - converts date and time to a structure * mktime - normalizes the date and time structure * strftime - converts date and time structure to a string *-----------------------------------------------------------------------*/ /* * C/C++ Run Time Library - Version 5.0 * * Copyright (c) 1987, 1992 by Borland International * All Rights Reserved. * */ #include <_io.h> #include <_printf.h> #include <time.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <RtlData.h> static const char Days[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; static int YDays[12] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; static char *SWeekday[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static char *LWeekday[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static char *SMonth[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static char *LMonth[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; static char *AmPm[2] = { "AM", "PM" }; #if !defined( _RTLDLL ) static struct tm tmX; #endif /*---------------------------------------------------------------------* Name comtime Usage static struct tm *comtime(unsigned long time, int dst); Prototype in local to this module Description fills the time structure tm by translating the long time. Return value the broken down time structure. This structure is a static which is overwritten with each call. *---------------------------------------------------------------------*/ static struct tm *comtime(time_t time, int dst) { int hpery; unsigned i; unsigned cumdays; _QRTLDataBlock; if (time < 0) time = 0; _QRTLInstanceData(tmX).tm_sec = (int)(time % 60); time /= 60; /* Time in minutes */ _QRTLInstanceData(tmX).tm_min = (int)(time % 60); time /= 60; /* Time in hours */ i = (unsigned)(time / (1461L * 24L)); /* Number of 4 year blocks */ _QRTLInstanceData(tmX).tm_year = (i << 2); _QRTLInstanceData(tmX).tm_year+= 70; cumdays = 1461 * i; time %= 1461L * 24L; /* Hours since end of last 4 year block */ for (;;) { hpery = 365 * 24; if ((_QRTLInstanceData(tmX).tm_year & 3) == 0) hpery += 24; if (time < hpery) break; cumdays += hpery / 24; _QRTLInstanceData(tmX).tm_year++; time -= hpery; } /* at end, time is number of hours into current year */ if (dst && daylight && __isDST( (int)(time % 24), (int)(time / 24), 0, _QRTLInstanceData(tmX).tm_year-70)) { time++; _QRTLInstanceData(tmX).tm_isdst = 1; } else _QRTLInstanceData(tmX).tm_isdst = 0; _QRTLInstanceData(tmX).tm_hour = (int)(time % 24); time /= 24; /* Time in days */ _QRTLInstanceData(tmX).tm_yday = (int)time; cumdays += (int)time + 4; _QRTLInstanceData(tmX).tm_wday = cumdays % 7; time++; if ((_QRTLInstanceData(tmX).tm_year & 3) == 0) { if (time > 60) time--; else if (time == 60) { _QRTLInstanceData(tmX).tm_mon = 1; _QRTLInstanceData(tmX).tm_mday = 29; return(&_QRTLInstanceData(tmX)); } } for (_QRTLInstanceData(tmX).tm_mon = 0; Days[_QRTLInstanceData(tmX).tm_mon] < time; _QRTLInstanceData(tmX).tm_mon++) time -= Days[_QRTLInstanceData(tmX).tm_mon]; _QRTLInstanceData(tmX).tm_mday = (int)(time); return(&_QRTLInstanceData(tmX)); } /*------------------------------------------------------------------------* Name atime - converts date and time to ASCII without trailing '\n' Usage #include <time.h> static int atime( char *dest, const struct tm *tmPtr ); Local to this module Description Provides the basic formatting capabilities for asctime() and strftime( "%c" ). These two functions both provide an ASCII version of the date and time in the struct tm, but asctime() adds a newline to the end. Return value Returns the number of characters in the ASCII string *---------------------------------------------------------------------------*/ static int _FARFUNC atime( char *dest, const struct tm *tmPtr ) { return sprintf( dest, "%s %s %02d %02d:%02d:%02d %4d", SWeekday[tmPtr->tm_wday], SMonth[tmPtr->tm_mon], tmPtr->tm_mday, tmPtr->tm_hour, tmPtr->tm_min, tmPtr->tm_sec, tmPtr->tm_year + 1900 ); } /*------------------------------------------------------------------------* Name asctime - converts date and time to ASCII ctime - converts date and time to a string gmtime - converts date and time to Greenwich Mean Time localtime - converts date and time to a structure Usage #include <time.h> char *asctime(struct tm *_QRTLInstanceData(tmX)); char *ctime(long *clock); struct tm *gmtime(long *clock); struct tm *localtime(long *clock); Prototype in time.h Description asctime converts a time stored as a structure to a 26-character string in the following form: Mon Nov 21 11:31:54 1983\n\0 All the fields have a constant width. ctime converts a time pointed to by clock (such as returned by the function time) to a 26-character string of the form described above. localtime and gmtime return pointers to structures containing the broken-down time. localtime corrects for the time zone and possible daylight savings time; gmtime converts directly to GMT. The global long variable timezone contains the difference in seconds between GMT and local standard time (in EST, timezone is 5*60*60). The global variable daylight is non-zero if and only if the standard U.S.A. Daylight Savings Time conversion should be applied. Return value asctime and ctime return a pointer to the character string containing the date and time. This string is a static which is overwritten with each call. gmtime and localtime return the broken down time structure. This structure is a static which is overwritten with each call. *---------------------------------------------------------------------------*/ struct tm *_FARFUNC gmtime(const time_t *clock) { return(comtime(*clock, 0)); } struct tm *_FARFUNC localtime(const time_t *clock) { unsigned long x; tzset(); /* get timezone info */ x = *clock - timezone; return(comtime(x, 1)); } char *_FARFUNC asctime(const struct tm *tmPtr) { #if !defined( _RTLDLL ) static char a[26]; #endif int end; _QRTLDataBlock; end = atime( _QRTLInstanceData(a), tmPtr ); _QRTLInstanceData(a)[end++] = '\n'; // add terminating newline _QRTLInstanceData(a)[end] = '\0'; return(_QRTLInstanceData(a)); } char * _FARFUNC ctime(const time_t *clock) { return(asctime(localtime(clock))); } /*------------------------------------------------------------------------* Converts a date expressed in local time to the number of seconds elapsed since year 70 (1970) in calendar time. All arguments are zero based. *------------------------------------------------------------------------*/ static unsigned long near totalsec(int year, int month, int day, int hour, int min, int sec) { int leaps; time_t days, secs; if (year < 70 || year > 138) return ((time_t) -1); min += sec / 60; sec %= 60; /* Seconds are normalized */ hour += min / 60; min %= 60; /* Minutes are normalized */ day += hour / 24; hour %= 24; /* Hours are normalized */ year += month / 12; /* Normalize month (not necessarily final) */ month %= 12; while (day >= Days[month]) { if (!(year & 3) && (month ==1)) { if (day > 28) { day -= 29; month++; } else break; } else { day -= Days[month]; month++; } year += month / 12; /* Normalize month */ month %= 12; } year -= 70; leaps = (year + 2) / 4; if (!((year+70) & 3) && (month < 2)) --leaps; days = year*365L + leaps + YDays[month] + day; secs = days*86400L + hour*3600L + min*60L + sec + timezone; if (daylight && __isDST(hour, day, month+1, year)) secs -= 3600; return(secs > 0 ? secs : (time_t) -1); } time_t _FARFUNC mktime(struct tm *t) { time_t secs; secs = totalsec(t->tm_year, t->tm_mon, t->tm_mday-1, t->tm_hour, t->tm_min, t->tm_sec); if (secs != (time_t) -1){ localtime(&secs); *t = _RTLInstanceData(tmX); } return(secs); } size_t _FARFUNC strftime( char *s, size_t maxsize, const char *fmt, const struct tm *t ) { char buf[ 25 ]; char *p = buf; int i, len; for( len = 1; len < maxsize && *fmt; ++fmt, p = buf ) { if( *fmt != '%' ) { ++len; *s++ = *fmt; } else { strcpy( buf, "00" ); switch( *++fmt ) { case 'a': p = SWeekday[t->tm_wday]; break; case 'A': p = LWeekday[t->tm_wday]; break; case 'b': p = SMonth[t->tm_mon]; break; case 'B': p = LMonth[t->tm_mon]; break; case 'c': atime( p, t ); break; case 'd': __utoa( t->tm_mday, buf + (t->tm_mday < 10) ); break; case 'H': __utoa( t->tm_hour, buf + (t->tm_hour < 10) ); break; case 'I': i = t->tm_hour % 12; if (i == 0) i = 12; __utoa( i, buf + (i < 10) ); break; case 'j': i = t->tm_yday + 1; __utoa( i, buf + (i < 10) + (i < 100) ); break; case 'm': i = t->tm_mon + 1; __utoa( i, buf + (i < 10) ); break; case 'M': __utoa( t->tm_min, buf + (t->tm_min < 10) ); break; case 'p': p = AmPm[ t->tm_hour / 12 ]; break; case 'S': __utoa( t->tm_sec, buf + (t->tm_sec < 10) ); break; case 'U': i = t->tm_wday - (t->tm_yday % 7); if( i < 0 ) i += 7; i = (t->tm_yday + i) / 7; __utoa( i, buf + (i < 10) ); break; case 'w': __utoa( t->tm_wday, buf ); break; case 'W': i = t->tm_wday - (t->tm_yday % 7); if( i < 0 ) i += 7; i = (t->tm_yday + i - 1) / 7; __utoa( i, buf + (i < 10) ); break; case 'x': strcpy( buf, SWeekday[t->tm_wday] ); strcat( buf, " " ); strcat( buf, SMonth[t->tm_mon] ); strcat( buf, " " ); __utoa( t->tm_mday, buf + strlen( buf ) ); strcat( buf, ", " ); __utoa( t->tm_year + 1900, buf + strlen( buf ) ); break; case 'X': __utoa( t->tm_hour, buf + (t->tm_hour < 10) ); strcat( buf, ":0" ); __utoa( t->tm_min, buf + strlen( buf ) - (t->tm_min > 9) ); strcat( buf, ":0" ); __utoa( t->tm_sec, buf + strlen( buf ) - (t->tm_sec > 9) ); break; case 'y': i = t->tm_year % 100; __utoa( i, buf + (i < 10) ); break; case 'Y': __utoa( 1900 + t->tm_year, buf ); break; case 'Z': p = tzname[ t->tm_isdst ]; break; case '%': p = "%"; } i = min( strlen( p ), maxsize - len ); strncpy( s, p, i ); len += i; s += i; } } *s = '\0'; if( *fmt ) return( 0 ); else return( len - 1 ); }
73ea85f46dbc79287e903228bed79edbe4fe3625
c7c73566784a7896100e993606e1bd8fdd0ea94e
/contrib/src/speedtree/speedtree_api.h
29761a97a4c774eb871e48aa0f4d064f44e50224
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
panda3d/panda3d
c3f94df2206ff7cfe4a3b370777a56fb11a07926
160ba090a5e80068f61f34fc3d6f49dbb6ad52c5
refs/heads/master
2023-08-21T13:23:16.904756
2021-04-11T22:55:33
2023-08-06T06:09:32
13,212,165
4,417
1,072
NOASSERTION
2023-09-09T19:26:14
2013-09-30T10:20:25
C++
UTF-8
C
false
false
884
h
speedtree_api.h
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file speedtree_api.h * @author drose * @date 2010-10-05 */ #ifndef SPEEDTREE_API_H #define SPEEDTREE_API_H // This header file should be included first, to pull in any of the required // headers from the SpeedTree API, needed in this directory. #include "speedtree_parameters.h" #include <Core/Core.h> #include <Forest/Forest.h> #if defined(SPEEDTREE_OPENGL) #include <Renderers/OpenGL/OpenGLRenderer.h> #elif defined(SPEEDTREE_DIRECTX9) #undef Configure #include <Renderers/DirectX9/DirectX9Renderer.h> #else #error Unexpected graphics API. #endif #endif // SPEEDTREE_API_H
84cb7cadcace5644133d9b503acc373c89b322d7
15050cf4e2dfa69dd0764502831c5d6a02856c2d
/src/d3d/shaders/im2d_PS.h
71f8b28d337f2e32e7ad3c9ea589ef3a87e14f65
[ "MIT" ]
permissive
aap/librw
5644223e69b5ab5ce26a643081918bc45a8c937a
05db81b92f30484a536990a6b792166102405c51
refs/heads/master
2023-08-31T00:14:50.862209
2023-02-21T00:24:42
2023-02-21T00:24:42
28,191,349
465
114
MIT
2023-08-24T01:26:56
2014-12-18T16:25:07
C++
UTF-8
C
false
false
1,852
h
im2d_PS.h
#if 0 // // Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111 // // fxc /nologo /T ps_2_0 /Fh im2d_PS.h im2d_PS.hlsl // // // Parameters: // // float4 fogColor; // // // Registers: // // Name Reg Size // ------------ ----- ---- // fogColor c0 1 // ps_2_0 dcl t0.xyz dcl v0 add r0.xyz, v0, -c0 mad r0.xyz, t0.z, r0, c0 mov r0.w, v0.w mov oC0, r0 // approximately 4 instruction slots used #endif const BYTE g_ps20_main[] = { 0, 2, 255, 255, 254, 255, 34, 0, 67, 84, 65, 66, 28, 0, 0, 0, 83, 0, 0, 0, 0, 2, 255, 255, 1, 0, 0, 0, 28, 0, 0, 0, 0, 1, 0, 0, 76, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 1, 0, 2, 0, 60, 0, 0, 0, 0, 0, 0, 0, 102, 111, 103, 67, 111, 108, 111, 114, 0, 171, 171, 171, 1, 0, 3, 0, 1, 0, 4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 112, 115, 95, 50, 95, 48, 0, 77, 105, 99, 114, 111, 115, 111, 102, 116, 32, 40, 82, 41, 32, 72, 76, 83, 76, 32, 83, 104, 97, 100, 101, 114, 32, 67, 111, 109, 112, 105, 108, 101, 114, 32, 57, 46, 50, 57, 46, 57, 53, 50, 46, 51, 49, 49, 49, 0, 31, 0, 0, 2, 0, 0, 0, 128, 0, 0, 7, 176, 31, 0, 0, 2, 0, 0, 0, 128, 0, 0, 15, 144, 2, 0, 0, 3, 0, 0, 7, 128, 0, 0, 228, 144, 0, 0, 228, 161, 4, 0, 0, 4, 0, 0, 7, 128, 0, 0, 170, 176, 0, 0, 228, 128, 0, 0, 228, 160, 1, 0, 0, 2, 0, 0, 8, 128, 0, 0, 255, 144, 1, 0, 0, 2, 0, 8, 15, 128, 0, 0, 228, 128, 255, 255, 0, 0 };
45eecfff76e58ae6573e7fd8428a2a1a2c6d4037
a3f2c5dcf6eac598fdcf74c863bbcb2cb270b1cc
/Chapter5/Exercise 5-05/strncat.c
75b0d153c70748d25b82d01ca57e61e8421c681e
[]
no_license
ccpalettes/the-c-programming-language-second-edition-solutions
3908c3731f40bb9434563d157cb7e35ba0e08c4d
96c17173e05310c9475edfaf2566c525e0970178
refs/heads/master
2022-07-19T16:30:38.494508
2022-07-18T09:33:58
2022-07-18T09:33:58
8,107,202
681
240
null
2020-12-19T05:01:15
2013-02-09T07:08:51
C
UTF-8
C
false
false
385
c
strncat.c
/** * Solution for Exercise 5-05, Chapter5. */ #include <stdio.h> void _strncat(char *s, char *t, int n); int main(void) { char *s, *t; s = "test"; t = "ring1234"; _strncat(s, t, 4); printf("cat: %s\n", s); return 0; } void _strncat(char *s, char *t, int n) { while (*s) ++s; while (n-- > 0 && *t) *s++ = *t++; *s = '\0'; }
3f2ee22eada2ee4665335fefd6fdd70b49f1eb1e
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/video/savage/savagefb_accel.c
bfefa6234cf0c46fc3f51bdba62461395be88fec
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
3,244
c
savagefb_accel.c
/*-*- linux-c -*- * linux/drivers/video/savage/savage_accel.c -- Hardware Acceleration * * Copyright (C) 2004 Antonino Daplas<adaplas@pol.net> * All Rights Reserved * * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of this archive for * more details. */ #include <linux/kernel.h> #include <linux/string.h> #include <linux/fb.h> #include <linux/module.h> #include "savagefb.h" static u32 savagefb_rop[] = { 0xCC, /* ROP_COPY */ 0x5A /* ROP_XOR */ }; int savagefb_sync(struct fb_info *info) { struct savagefb_par *par = info->par; par->SavageWaitIdle(par); return 0; } void savagefb_copyarea(struct fb_info *info, const struct fb_copyarea *region) { struct savagefb_par *par = info->par; int sx = region->sx, dx = region->dx; int sy = region->sy, dy = region->dy; int cmd; if (!region->width || !region->height) return; par->bci_ptr = 0; cmd = BCI_CMD_RECT | BCI_CMD_DEST_GBD | BCI_CMD_SRC_GBD; BCI_CMD_SET_ROP(cmd, savagefb_rop[0]); if (dx <= sx) { cmd |= BCI_CMD_RECT_XP; } else { sx += region->width - 1; dx += region->width - 1; } if (dy <= sy) { cmd |= BCI_CMD_RECT_YP; } else { sy += region->height - 1; dy += region->height - 1; } par->SavageWaitFifo(par,4); BCI_SEND(cmd); BCI_SEND(BCI_X_Y(sx, sy)); BCI_SEND(BCI_X_Y(dx, dy)); BCI_SEND(BCI_W_H(region->width, region->height)); } void savagefb_fillrect(struct fb_info *info, const struct fb_fillrect *rect) { struct savagefb_par *par = info->par; int cmd, color; if (!rect->width || !rect->height) return; if (info->fix.visual == FB_VISUAL_PSEUDOCOLOR) color = rect->color; else color = ((u32 *)info->pseudo_palette)[rect->color]; cmd = BCI_CMD_RECT | BCI_CMD_RECT_XP | BCI_CMD_RECT_YP | BCI_CMD_DEST_GBD | BCI_CMD_SRC_SOLID | BCI_CMD_SEND_COLOR; par->bci_ptr = 0; BCI_CMD_SET_ROP(cmd, savagefb_rop[rect->rop]); par->SavageWaitFifo(par,4); BCI_SEND(cmd); BCI_SEND(color); BCI_SEND( BCI_X_Y(rect->dx, rect->dy) ); BCI_SEND( BCI_W_H(rect->width, rect->height) ); } void savagefb_imageblit(struct fb_info *info, const struct fb_image *image) { struct savagefb_par *par = info->par; int fg, bg, size, i, width; int cmd; u32 *src = (u32 *) image->data; if (!image->width || !image->height) return; if (image->depth != 1) { cfb_imageblit(info, image); return; } if (info->fix.visual == FB_VISUAL_PSEUDOCOLOR) { fg = image->fg_color; bg = image->bg_color; } else { fg = ((u32 *)info->pseudo_palette)[image->fg_color]; bg = ((u32 *)info->pseudo_palette)[image->bg_color]; } cmd = BCI_CMD_RECT | BCI_CMD_RECT_XP | BCI_CMD_RECT_YP | BCI_CMD_CLIP_LR | BCI_CMD_DEST_GBD | BCI_CMD_SRC_MONO | BCI_CMD_SEND_COLOR; par->bci_ptr = 0; BCI_CMD_SET_ROP(cmd, savagefb_rop[0]); width = (image->width + 31) & ~31; size = (width * image->height)/8; size >>= 2; par->SavageWaitFifo(par, size + 5); BCI_SEND(cmd); BCI_SEND(BCI_CLIP_LR(image->dx, image->dx + image->width - 1)); BCI_SEND(fg); BCI_SEND(bg); BCI_SEND(BCI_X_Y(image->dx, image->dy)); BCI_SEND(BCI_W_H(width, image->height)); for (i = 0; i < size; i++) BCI_SEND(src[i]); } MODULE_LICENSE("GPL");
144fa0def173689c92dddd05e9c688a0d1947891
2d11442aa09b51e10c245ee2b64231aeb051744f
/platforms/win32/vm/sqWin32Main.c
e58ce6977644c21f4f16dc4f7fbe9fa83d9a4842
[ "MIT" ]
permissive
OpenSmalltalk/opensmalltalk-vm
622b01c10017a93fdff4f1ef2188c45342384c78
330d6779ad2ecbce1f07131f53d75cd168165f0b
refs/heads/Cog
2023-09-04T05:36:54.320281
2023-08-17T11:32:52
2023-08-31T12:26:44
59,481,716
556
153
NOASSERTION
2023-06-19T19:58:13
2016-05-23T12:40:27
C
UTF-8
C
false
false
75,064
c
sqWin32Main.c
/**************************************************************************** * PROJECT: Squeak port for Win32 (NT / Win95) * FILE: sqWin32Main.c * CONTENT: Main entry point and support stuff for Win95/WinNT/WinXP on x86 * * AUTHOR: Andreas Raab (ar) * ADDRESS: University of Magdeburg, Germany * EMAIL: raab@isg.cs.uni-magdeburg.de * * NOTES: (I think this comment of Andreas' is obsolete; eem 6/2013) * 1) When using this module the virtual machine MUST NOT be compiled * with Unicode support. *****************************************************************************/ #include <Windows.h> #include <process.h> // for _cexit #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <tchar.h> #include <fcntl.h> /* _O_BINARY */ #include <float.h> #include <ole2.h> /* N.B. As of cygwin 1.5.25 fopen("crash.dmp","a") DOES NOT WORK! crash.dmp * contains garbled output as if the file pointer gets set to the start of the * file, not the end. So we synthesize our own append mode. */ #if __MINGW32__ # include <io.h> #endif #if defined(DIR_RELATIVE_LOG_LOCATION) # include <ShlObj.h> #endif #include "sq.h" #include "sqImageFileAccess.h" #include "sqWin32Prefs.h" #include "sqAssert.h" #include "sqWin32Backtrace.h" #include "sqSCCSVersion.h" /************************************************************************************************************/ /* few addtional definitions for those having older include files especially #include <fileextd.h> */ /************************************************************************************************************/ #if (WINVER < 0x0600) /*Copied from winbase.h*/ typedef struct _FILE_NAME_INFO { DWORD FileNameLength; WCHAR FileName[1]; } FILE_NAME_INFO, *PFILE_NAME_INFO; typedef enum _FILE_INFO_BY_HANDLE_CLASS { FileBasicInfo = 0, FileStandardInfo = 1, FileNameInfo = 2, FileRenameInfo = 3, FileDispositionInfo = 4, FileAllocationInfo = 5, FileEndOfFileInfo = 6, FileStreamInfo = 7, FileCompressionInfo = 8, FileAttributeTagInfo = 9, FileIdBothDirectoryInfo = 10, // 0xA FileIdBothDirectoryRestartInfo = 11, // 0xB FileIoPriorityHintInfo = 12, // 0xC FileRemoteProtocolInfo = 13, // 0xD FileFullDirectoryInfo = 14, // 0xE FileFullDirectoryRestartInfo = 15, // 0xF FileStorageInfo = 16, // 0x10 FileAlignmentInfo = 17, // 0x11 FileIdInfo = 18, // 0x12 FileIdExtdDirectoryInfo = 19, // 0x13 FileIdExtdDirectoryRestartInfo = 20, // 0x14 MaximumFileInfoByHandlesClass } FILE_INFO_BY_HANDLE_CLASS, *PFILE_INFO_BY_HANDLE_CLASS; #endif //(WINVER < 0x0600) #if !defined(IMAGE_SIZEOF_NT_OPTIONAL_HEADER) #include <winnt.h> #define IMAGE_SIZEOF_NT_OPTIONAL_HEADER sizeof(IMAGE_OPTIONAL_HEADER) #endif /* Windows Vista support * AUTHOR: Korakurider (kr) * CHANGE NOTES: * 1) new command line option "-lowRights" was introduced * to support IE7/protected mode. */ #define VISTA_SECURITY 1 /* IE7/Vista protected mode support */ # define VMOPTION(arg) "-"arg /*** Crash debug -- Imported from Virtual Machine ***/ int getFullScreenFlag(void); sqInt methodPrimitiveIndex(void); sqInt getCurrentBytecode(void); extern void printPhaseTime(int); /* Import from sqWin32Alloc.c */ LONG CALLBACK sqExceptionFilter(PEXCEPTION_POINTERS exp); /* Import from sqWin32Window.c */ const char *getAttributeString(sqInt id); void ShowSplashScreen(void); void HideSplashScreen(void); /* Import from sqWin32Heartbeat.c */ void ioReleaseTime(void); /* Import from SecurityPlugin/sqWin32Security.c */ sqInt ioInitSecurity(void); /* forwarded declaration */ static void printCrashDebugInformation(PEXCEPTION_POINTERS exp); /*** Variables -- command line */ static char *initialCmdLine; static int numOptionsVM = 0; static char **vmOptions; static int numOptionsImage = 0; static char **imageOptions; static int clargc; /* the Unix-style command line, saved for GetImageOption */ static char **clargv; /* console buffer */ BOOL fIsConsole = 0; char consoleBuffer[4096]; /* stderr and stdout names */ WCHAR stderrName[MAX_PATH+1]; WCHAR stdoutName[MAX_PATH+1]; static char vmLogDirA[MAX_PATH_UTF8]; static WCHAR vmLogDirW[MAX_PATH]; WCHAR *logName = L""; /* full path and name to log file */ #ifdef VISTA_SECURITY BOOL fLowRights = 0; /* started as low integiry process, need to use alternate untrustedUserDirectory */ #endif /* VISTA_SECURITY */ /* Service stuff */ WCHAR serviceName[MAX_PATH+1]; /* The name of the NT service */ WCHAR *installServiceName = NULL; /* the name under which the service is to install */ UINT WM_BROADCAST_SERVICE = 0; /* The broadcast message we send */ TCHAR *msgBroadcastService = TEXT("SQUEAK_SERVICE_BROADCAST_MESSAGE"); /* The name of the broadcast message */ UINT SQ_LAUNCH_DROP = 0; /* Message sent when second instance launches */ /* Embedded images */ static sqImageFile imageFile = 0; static int imageSize = 0; void SetSystemTrayIcon(BOOL on); /****************************************************************************/ /* Exception handling */ /****************************************************************************/ /* The following installs us a global exception filter for *all* exceptions */ /* in Squeak. This is necessary since the C support of Mingw32 for SEH is */ /* not as sophisticated as MSVC's support. However, with this new handling */ /* scheme the entire thing becomes actually a lot simpler... */ /****************************************************************************/ /* default fpu control word: _RC_NEAR: round to nearest _PC_53 : double precision arithmetic (instead of extended) _EM_XXX: silent operations (no signals please) NOTE: precision control and infinity control are not defined on ARM or X64 (SSE oblige), only X86 */ # if defined(_M_IX86) || defined(X86) || defined(_M_I386) || defined(_X86_) \ || defined(i386) || defined(i486) || defined(i586) || defined(i686) \ || defined(__i386__) || defined(__386__) || defined(I386) # define FPU_DEFAULT (_RC_NEAR + _PC_53 + _EM_INVALID + _EM_ZERODIVIDE \ + _EM_OVERFLOW + _EM_UNDERFLOW + _EM_INEXACT + _EM_DENORMAL) # define FPU_MASK (_MCW_EM | _MCW_RC | _MCW_PC | _MCW_IC) #else # define FPU_DEFAULT (_RC_NEAR + _EM_INVALID + _EM_ZERODIVIDE \ + _EM_OVERFLOW + _EM_UNDERFLOW + _EM_INEXACT + _EM_DENORMAL) # define FPU_MASK (_MCW_EM | _MCW_RC) #endif static void UninstallExceptionHandler(void); #if _WIN64 static PVECTORED_EXCEPTION_HANDLER ourVEHHandle = NULL; static BOOL inFatalException = false; #endif static LPTOP_LEVEL_EXCEPTION_FILTER TopLevelFilter = NULL; static BOOL debugBreakOnException = false; // Until we can implement a reliable first-chance exception handler on WIN64 // we cannot support primitiveFailForFFIExceptionat there-on. sqInt ioCanCatchFFIExceptions() { return 1; } extern sqInt primitiveFailForFFIExceptionat(usqLong exceptionCode, usqInt pc); #if _WIN64 static LONG NTAPI squeakVectoredExceptionHandler(PEXCEPTION_POINTERS exp) { DWORD code = exp->ExceptionRecord->ExceptionCode; if (inFatalException) return EXCEPTION_CONTINUE_SEARCH; // #1: Try to handle any FP problems if (code >= EXCEPTION_FLT_DENORMAL_OPERAND && code <= EXCEPTION_FLT_UNDERFLOW) { /* turn on the default masking of exceptions in the FPU and proceed */ _controlfp(FPU_DEFAULT, FPU_MASK); return EXCEPTION_CONTINUE_EXECUTION; } // codes defined in Include/{SDK Version}/um/winnt.h if (code == STATUS_ACCESS_VIOLATION /* 0xC0000005 */ || code == STATUS_ILLEGAL_INSTRUCTION /* 0xC000001D */ || code == STATUS_NONCONTINUABLE_EXCEPTION /* 0xC0000025 */ || code == STATUS_INTEGER_DIVIDE_BY_ZERO /* 0xC0000094 */ || code == STATUS_INTEGER_OVERFLOW /* 0xC0000095 */ || code == STATUS_PRIVILEGED_INSTRUCTION /* 0xC0000096 */ || code == STATUS_STACK_OVERFLOW /* 0xC00000FD */) { // #2: Allow the VM to fail an FFI call in which an exception occurred. if (debugBreakOnException) { while (!IsDebuggerPresent()) Sleep(250); DebugBreak(); } primitiveFailForFFIExceptionat(exp->ExceptionRecord->ExceptionCode, exp->ContextRecord->CONTEXT_PC); inFatalException = true; // avoid looping exception handling // #3: If that didn't work print crash debug information and exit UninstallExceptionHandler(); printCrashDebugInformation(exp); DestroyWindow(stWindow); ioExit(); } return EXCEPTION_CONTINUE_SEARCH; } #endif // _WIN64 static LONG CALLBACK squeakExceptionHandler(PEXCEPTION_POINTERS exp) { #if defined(NDEBUG) // in release mode, execute exception handler notifying user what happened DWORD result = EXCEPTION_EXECUTE_HANDLER; #else // in debug mode, let the system crash so that we can see where it happened DWORD result = EXCEPTION_CONTINUE_SEARCH; #endif #if _WIN64 if (inFatalException) return EXCEPTION_CONTINUE_SEARCH; #endif // #1: Try to handle any FP problems DWORD code = exp->ExceptionRecord->ExceptionCode; if (code >= EXCEPTION_FLT_DENORMAL_OPERAND && code <= EXCEPTION_FLT_UNDERFLOW) { /* turn on the default masking of exceptions in the FPU and proceed */ _controlfp(FPU_DEFAULT, FPU_MASK); return EXCEPTION_CONTINUE_EXECUTION; } // #2: If that didn't work try passing it on to the old top-level filter if (result != EXCEPTION_CONTINUE_EXECUTION && TopLevelFilter) result = TopLevelFilter(exp); if (result != EXCEPTION_CONTINUE_EXECUTION) { // #3: Allow the VM to fail an FFI call in which an exception occurred. if (debugBreakOnException) { while (!IsDebuggerPresent()) Sleep(250); DebugBreak(); } primitiveFailForFFIExceptionat(exp->ExceptionRecord->ExceptionCode, exp->ContextRecord->CONTEXT_PC); /* #4: If that didn't work either give up and print crash debug information */ UninstallExceptionHandler(); printCrashDebugInformation(exp); result = EXCEPTION_EXECUTE_HANDLER; } return result; } /* Structured exception handling is implemented completely differently in 64-bit * Windows to 32-bit Windows (David Simmons, private communication, Sept 2021). * To be able to write a stack trace in crash.dmp we need to be informed of * exceptions before stack unwind. On 64-bit Windows one must use vectored * exception handling to be so informed. */ static void InstallExceptionHandler(void) { #if _WIN64 # define CallFirst 1 # define CallLast 0 ourVEHHandle = AddVectoredExceptionHandler(CallLast, squeakVectoredExceptionHandler); #endif TopLevelFilter = SetUnhandledExceptionFilter(squeakExceptionHandler); } static void UninstallExceptionHandler(void) { #if _WIN64 RemoveVectoredExceptionHandler(ourVEHHandle); ourVEHHandle = NULL; #endif SetUnhandledExceptionFilter(TopLevelFilter); TopLevelFilter = NULL; } /* N.B. As of cygwin 1.5.25 fopen("crash.dmp","a") DOES NOT WORK! crash.dmp * contains garbled output as if the file pointer gets set to the start of the * file, not the end. So we synthesize our own append mode. */ #if __MINGW32__ static FILE * fopen_for_append(WCHAR *filename) { FILE *f = !_waccess(filename, F_OK) /* access is bass ackwards */ ? _wfopen(filename,L"r+") : _wfopen(filename,L"w+"); if (f) _fseeki64(f,0,SEEK_END); return f; } #else # define fopen_for_append(filename) _wfopen(filename,L"a+t") #endif static FILE * crashDumpFile( /* OUT */ WCHAR fileName[]) { #if NewspeakVM // dump to current directory wcscpy(fileName,L"crash.dmp"); #else # if defined(DIR_RELATIVE_LOG_LOCATION) // dump to CSIDL_XXX dir if (SHGetFolderPathW(0, LOGDIR_LOCATION, 0, 0, fileName) == S_OK) { wcscat(fileName, L"\\" DIR_RELATIVE_LOG_LOCATION); wcscat(fileName, L"\\crash.dmp"); } else // fall through to dump to vmLogDir # endif wsprintfW(fileName,L"%s%s",vmLogDirW,L"crash.dmp"); #endif return fopen_for_append(fileName); } /****************************************************************************/ /* Console Window functions */ /****************************************************************************/ static int OutputLogMessage(char *string) { FILE *fp; if (!*logName) return 1; fp = fopen_for_append(logName); if (!fp) return 1; fprintf(fp, "%s", string); fflush(fp); fclose(fp); return 1; } static int OutputLogMessageW(WCHAR *string) { int len = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL); char *utf8 = malloc(len); if (!utf8) return 1; WideCharToMultiByte(CP_UTF8, 0, string, -1, utf8, len, NULL, NULL); OutputLogMessage(utf8); free(utf8); return 1; } static int OutputConsoleString(char *string) { int pos; if (fDynamicConsole && !fShowConsole) { /* show console window */ ShowWindow(consoleWindow, SW_SHOW); fShowConsole = TRUE; #ifndef NO_PREFERENCES CheckMenuItem(vmPrefsMenu, 0x0030, MF_BYCOMMAND | MF_CHECKED); #endif OutputConsoleString( "# Debug console\n" "# To close: F2 -> 'debug options' -> 'show output console'\n" "# To disable: F2 -> 'debug options' -> 'show console on errors'\n" ); } pos = SendMessageA(consoleWindow,WM_GETTEXTLENGTH, 0,0); SendMessageA(consoleWindow, EM_SETSEL, pos, pos); while (*string) { SendMessageA( consoleWindow, WM_CHAR, *string, 1); string++; } return 1; } // recommend using DPRINTF ifdef'ing to DPRINTF for debug output int __cdecl DPRINTF(const char *fmt, ...) { va_list al; va_start(al, fmt); if (!fIsConsole) { vsprintf(consoleBuffer, fmt, al); OutputDebugStringA(consoleBuffer); } vfprintf(stdout, fmt, al); va_end(al); return 1; } #if defined(DBGPRINT) // redefining printf doesn't seem like a good idea to me... int __cdecl printf(const char *fmt, ...) { va_list al; int result; va_start(al, fmt); if (!fIsConsole) { vsprintf(consoleBuffer, fmt, al); OutputLogMessage(consoleBuffer); if (IsWindow(stWindow)) /* not running as service? */ OutputConsoleString(consoleBuffer); } result = vfprintf(stdout, fmt, al); va_end(al); return result; } int __cdecl fprintf(FILE *fp, const char *fmt, ...) { va_list al; int result; va_start(al, fmt); if (!fIsConsole && (fp == stdout || fp == stderr)) { vsprintf(consoleBuffer, fmt, al); OutputLogMessage(consoleBuffer); if (IsWindow(stWindow)) /* not running as service? */ OutputConsoleString(consoleBuffer); } result = vfprintf(fp, fmt, al); va_end(al); return result; } int __cdecl putchar(int c) { return printf("%c",c); } #endif /* defined(DBGPRINT) */ /****************************************************************************/ /* Message Processing */ /****************************************************************************/ static messageHook nextMessageHook = NULL; int ServiceMessageHook(void * hwnd, unsigned int message, unsigned int wParam, long lParam) { if (message == WM_USERCHANGED) { SetSystemTrayIcon(1); return 1; } if (nextMessageHook) return(*nextMessageHook)(hwnd, message,wParam, lParam); else return 0; } /****************************************************************************/ /* Window Setup */ /****************************************************************************/ /* SetSystemTrayIcon(): Set the icon in the system tray */ void SetSystemTrayIcon(BOOL on) { NOTIFYICONDATA nid; nid.cbSize = sizeof(nid); nid.hWnd = stWindow; nid.uID = (usqIntptr_t)hInstance; nid.uFlags = NIF_MESSAGE | NIF_TIP | NIF_ICON; nid.uCallbackMessage = WM_USER+42; nid.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(1)); _tcscpy(nid.szTip, TEXT(VM_NAME) TEXT("!")); Shell_NotifyIcon( on ? NIM_ADD : NIM_DELETE, &nid); } /****************************************************************************/ /* System Attributes */ /****************************************************************************/ char *GetVMOption(int id) { if (id >= 0 && id < numOptionsVM) return vmOptions[id]; return NULL; } char *GetImageOption(int id) { if (id >= 0 && id < numOptionsImage) return imageOptions[id]; return NULL; } char *ioGetLogDirectory(void) { return vmLogDirA; } sqInt ioSetLogDirectoryOfSize(void* lblIndex, sqInt sz) { if (sz >= MAX_PATH_UTF8) return 0; strncpy(vmLogDirA, lblIndex, sz); vmLogDirA[sz] = 0; MultiByteToWideChar(CP_UTF8, 0, vmLogDirA, -1, vmLogDirW, MAX_PATH); return 1; } /* New MinGW defines this, as does MSVC - so who still needs it? */ #if !defined(VerifyVersionInfo) typedef struct _OSVERSIONINFOEX { DWORD dwOSVersionInfoSize; DWORD dwMajorVersion; DWORD dwMinorVersion; DWORD dwBuildNumber; DWORD dwPlatformId; TCHAR szCSDVersion[128]; WORD wServicePackMajor; WORD wServicePackMinor; WORD wSuiteMask; BYTE wProductType; BYTE wReserved; } OSVERSIONINFOEX; #endif /* !defined(VerifyVersionInfo) */ /* New MinGW defines this, as does MSVC - so who still needs it? */ #if !defined(EnumDisplayDevices) typedef struct _DISPLAY_DEVICE { DWORD cb; TCHAR DeviceName[32]; TCHAR DeviceString[128]; DWORD StateFlags; TCHAR DeviceID[128]; TCHAR DeviceKey[128]; } DISPLAY_DEVICE, *PDISPLAY_DEVICE; #endif /* !defined(EnumDisplayDevices) */ typedef BOOL (CALLBACK *pfnEnumDisplayDevices)( LPCTSTR lpDevice, // device name DWORD iDevNum, // display device PDISPLAY_DEVICE lpDisplayDevice, // device information DWORD dwFlags // reserved ); char *osInfoString = ""; char *hwInfoString = ""; char *gdInfoString = ""; char *win32VersionName = ""; void RegLookupUTF8String(HKEY hk, WCHAR *name, char *utf8, size_t utf8_len) { WCHAR bufferW[MAX_PATH]; DWORD dwSize = MAX_PATH * sizeof(WCHAR); LSTATUS ok = RegQueryValueExW(hk, name, NULL, NULL,(LPBYTE)bufferW, &dwSize); if (ok != ERROR_SUCCESS) strncpy(utf8, "???",utf8_len); else { int len = WideCharToMultiByte(CP_UTF8, 0, bufferW, -1, utf8, utf8_len, NULL, NULL); if (len <= 0) strncpy(utf8, "???", utf8_len); } } void gatherSystemInfo(void) { OSVERSIONINFOEX osInfo; MEMORYSTATUS memStat; SYSTEM_INFO sysInfo; DISPLAY_DEVICE gDev; int proc, screenX, screenY; char tmpString[2048]; WCHAR keyName[256]; DWORD ok, dwSize; HKEY hk; /* Retrieve version info for crash logs */ ZeroMemory(&osInfo, sizeof(osInfo)); osInfo.dwOSVersionInfoSize = sizeof(osInfo); GetVersionEx((OSVERSIONINFO*)&osInfo); GetSystemInfo(&sysInfo); /* Set up the win32VersionName */ sprintf(tmpString, "%lu.%lu", osInfo.dwMajorVersion, osInfo.dwMinorVersion); win32VersionName = _strdup(tmpString); ZeroMemory(&memStat, sizeof(memStat)); memStat.dwLength = sizeof(memStat); GlobalMemoryStatus(&memStat); screenX = GetSystemMetrics(SM_CXSCREEN); screenY = GetSystemMetrics(SM_CYSCREEN); { HANDLE hUser = LoadLibraryA( "user32.dll" ); ZeroMemory(&gDev, sizeof(gDev)); gDev.cb = sizeof(gDev); if (hUser) { pfnEnumDisplayDevices pEnumDisplayDevices = (pfnEnumDisplayDevices) GetProcAddress(hUser, "EnumDisplayDevicesA"); if (pEnumDisplayDevices) pEnumDisplayDevices(NULL, 0, &gDev, 0); } } { /* Figure out make and model from OEMINFO.ini */ WCHAR iniName[MAX_PATH]; WCHAR bufferW[MAX_PATH]; char manufacturer[MAX_PATH_UTF8]; char model[MAX_PATH_UTF8]; GetSystemDirectoryW(iniName, MAX_PATH); wcsncat(iniName,L"\\OEMINFO.INI",MAX_PATH-1-wcslen(iniName)); GetPrivateProfileStringW(L"General", L"Manufacturer", L"Unknown", bufferW, MAX_PATH, iniName); if (WideCharToMultiByte(CP_UTF8, 0, bufferW, -1, manufacturer, MAX_PATH_UTF8, NULL, NULL) == 0) strcpy(manufacturer, "???"); GetPrivateProfileStringW(L"General", L"Model", L"Unknown", bufferW, MAX_PATH, iniName); if (WideCharToMultiByte(CP_UTF8, 0, bufferW, -1, model, MAX_PATH_UTF8, NULL, NULL) == 0) strcpy(model, "???"); sprintf(tmpString, "Hardware information: \n" "\tManufacturer: %s\n" "\tModel: %s\n" "\tNumber of processors: %lu\n" "\tPage size: %lu\n" "\nMemory Information (upon launch):\n" "\tPhysical Memory Size: %" PRIuSQPTR " kbytes\n" "\tPhysical Memory Free: %" PRIuSQPTR " kbytes\n" "\tPage File Size: %" PRIuSQPTR " kbytes\n" "\tPage File Free: %" PRIuSQPTR " kbytes\n" "\tVirtual Memory Size: %" PRIuSQPTR " kbytes\n" "\tVirtual Memory Free: %" PRIuSQPTR " kbytes\n" "\tMemory Load: %lu percent\n", manufacturer, model, sysInfo.dwNumberOfProcessors, sysInfo.dwPageSize, memStat.dwTotalPhys / 1024, memStat.dwAvailPhys / 1024, memStat.dwTotalPageFile / 1024, memStat.dwAvailPageFile / 1024, memStat.dwTotalVirtual / 1024, memStat.dwAvailVirtual / 1024, memStat.dwMemoryLoad); } /* find more information about each processor */ for(proc=0; proc < sysInfo.dwNumberOfProcessors; proc++) { char *tmp = tmpString + strlen(tmpString); wcscpy(keyName, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"); keyName[wcslen(keyName)-1] = 48+proc; /* 0, 1, 2 etc. */ ok = RegOpenKeyW(HKEY_LOCAL_MACHINE, keyName, &hk); if (!ok) { char nameString[MAX_PATH_UTF8]; char identifier[MAX_PATH_UTF8]; DWORD mhz; RegLookupUTF8String(hk, L"ProcessorNameString", nameString, MAX_PATH_UTF8); RegLookupUTF8String(hk, L"Identifier", identifier, MAX_PATH_UTF8); dwSize = sizeof(DWORD); ok = RegQueryValueExW(hk, L"~MHz", NULL, NULL, (LPBYTE)&mhz, &dwSize); if (ok) mhz = -1; snprintf(tmp, sizeof(tmpString)-strlen(tmpString), "\nProcessor %d: %s\n" "\tIdentifier: %s\n" "\t~MHZ: %lu\n", proc, nameString, identifier, mhz); RegCloseKey(hk); } } hwInfoString = _strdup(tmpString); { char owner[MAX_PATH_UTF8]; char company[MAX_PATH_UTF8]; char product[MAX_PATH_UTF8]; if (osInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) { wcscpy(keyName, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"); } else { wcscpy(keyName, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion"); } ok = RegOpenKeyW(HKEY_LOCAL_MACHINE, keyName, &hk); if (!ok) { RegLookupUTF8String(hk, L"RegisteredOwner", owner, MAX_PATH_UTF8); RegLookupUTF8String(hk, L"RegisteredOrganization", company, MAX_PATH_UTF8); RegLookupUTF8String(hk, L"ProductName", product, MAX_PATH_UTF8); } else { strcpy(owner, "???"); strcpy(company, "???"); strcpy(product, "???"); } #if defined(_MSC_VER) && _MSC_VER < 1300 # define wSuiteMask wReserved[0] # define wProductType wReserved[1] & 0xFF #endif #if _UNICODE { char buf[128 * 3]; if (WideCharToMultiByte(CP_UTF8,0, osInfo.szCSDVersion,-1,buf,sizeof(buf),NULL,NULL)) snprintf(tmpString, sizeof(tmpString), "Operating System: %s (Build %lu %s)\n" "\tRegistered Owner: %s\n" "\tRegistered Company: %s\n" "\tSP major version: %d\n" "\tSP minor version: %d\n" "\tSuite mask: %x\n" "\tProduct type: %x\n", product, osInfo.dwBuildNumber, buf, owner, company, osInfo.wServicePackMajor, osInfo.wServicePackMinor, osInfo.wSuiteMask, osInfo.wProductType); } #else snprintf(tmpString,sizeof(tmpString), "Operating System: %s (Build %lu %s)\n" "\tRegistered Owner: %s\n" "\tRegistered Company: %s\n" "\tSP major version: %d\n" "\tSP minor version: %d\n" "\tSuite mask: %x\n" "\tProduct type: %x\n", product, osInfo.dwBuildNumber, osInfo.szCSDVersion, owner, company, osInfo.wServicePackMajor, osInfo.wServicePackMinor, osInfo.wSuiteMask, osInfo.wProductType); #endif osInfoString = _strdup(tmpString); } #if _UNICODE { char buf[128*3]; if (WideCharToMultiByte(CP_UTF8,0,gDev.DeviceString,-1,buf,sizeof(buf),NULL,NULL)) snprintf(tmpString, sizeof(tmpString), "Display Information: \n" "\tGraphics adapter name: %s\n" "\tPrimary monitor resolution: %d x %d\n", buf, screenX, screenY); } #else snprintf(tmpString, sizeof(tmpString), "Display Information: \n" "\tGraphics adapter name: %s\n" "\tPrimary monitor resolution: %d x %d\n", gDev.DeviceString, screenX, screenY); #endif /* Find the driver key in the registry */ keyName[0] = 0; ok = RegOpenKeyW(HKEY_LOCAL_MACHINE, L"HARDWARE\\DEVICEMAP\\VIDEO", &hk); if (!ok) { dwSize = 256*sizeof(WCHAR); RegQueryValueExW(hk,L"\\Device\\Video0", NULL, NULL, (LPBYTE)keyName, &dwSize); RegCloseKey(hk); } if (*keyName) { /* Got the key name; open it and get the info out of there */ char *tmp = tmpString + strlen(tmpString); char deviceDesc[MAX_PATH_UTF8]; char adapterString[MAX_PATH_UTF8]; char biosString[MAX_PATH_UTF8]; char chipType[MAX_PATH_UTF8]; char dacType[MAX_PATH_UTF8]; WCHAR *drivers, *drv; WCHAR buffer[256]; DWORD memSize; /* Argh. It seems that the registry key regularly starts with \Registry\Machine\ which doesn't work with RegOpenKey below. I have no idea why but for now I'll just truncate that part if we recognize it... */ if (_wcsnicmp(keyName, L"\\registry\\machine\\", 18) == 0) { memmove(keyName, keyName+18, (wcslen(keyName)+1-18)*sizeof(WCHAR)); /* +1 for terminating NULL */ } ok = RegOpenKeyW(HKEY_LOCAL_MACHINE, keyName, &hk); if (ok) MessageBoxW(0, keyName, L"Cannot open:", MB_OK); if (!ok) { RegLookupUTF8String(hk, L"Device Description", deviceDesc, MAX_PATH_UTF8); RegLookupUTF8String(hk, L"HardwareInformation.AdapterString", adapterString, MAX_PATH_UTF8); RegLookupUTF8String(hk, L"HardwareInformation.BiosString", biosString, MAX_PATH_UTF8); RegLookupUTF8String(hk, L"HardwareInformation.ChipType", chipType, MAX_PATH_UTF8); RegLookupUTF8String(hk, L"HardwareInformation.DacType", dacType, MAX_PATH_UTF8); dwSize = sizeof(DWORD); ok = RegQueryValueExW(hk,L"HardwareInformation.MemorySize", NULL, NULL, (LPBYTE)&memSize, &dwSize); if (ok) memSize = -1; sprintf(tmp, "\nDevice: %s\n" "\tAdapter String: %s\n" "\tBios String: %s\n" "\tChip Type: %s\n" "\tDAC Type: %s\n" "\tMemory Size: 0x%.8lX\n", deviceDesc, adapterString, biosString, chipType, dacType, memSize); /* Now process the installed drivers */ ok = RegQueryValueExW(hk,L"InstalledDisplayDrivers", NULL, NULL, NULL, &dwSize); if (!ok) { drivers = malloc(dwSize); ok = RegQueryValueExW(hk,L"InstalledDisplayDrivers", NULL, NULL, (LPBYTE)drivers, &dwSize); } if (!ok) { strncat(tmpString,"\nDriver Versions:",sizeof(tmpString) - 1 - strlen(tmpString)); /* InstalledDrivers is REG_MULTI_SZ (extra terminating zero) */ for(drv = drivers; drv[0]; drv +=wcslen(drv)) { DWORD verSize, hh; UINT vLen; LPVOID verInfo = NULL, vInfo; char drvA[MAX_PATH_UTF8]; /* Concat driver name */ if (WideCharToMultiByte(CP_UTF8,0,drv,-1,drvA,MAX_PATH_UTF8,NULL,NULL)>0) { strncat(tmpString, "\n\t", sizeof(tmpString) - 1 - strlen(tmpString)); strncat(tmpString, drvA , sizeof(tmpString) - 1 - strlen(tmpString)); strncat(tmpString, ": " , sizeof(tmpString) - 1 - strlen(tmpString)); } verSize = GetFileVersionInfoSizeW(drv, &hh); if (!verSize) goto done; verInfo = malloc(verSize); if (!GetFileVersionInfoW(drv, 0, verSize, verInfo)) goto done; /* Try Unicode first */ if (VerQueryValueW(verInfo,L"\\StringFileInfo\\040904B0\\FileVersion", &vInfo, &vLen)) { int utf8_len = WideCharToMultiByte(CP_UTF8, 0, vInfo, -1, NULL, 0, NULL, NULL); char *utf8 = (char *)malloc(utf8_len); if (utf8) { WideCharToMultiByte(CP_UTF8, 0, vInfo, -1, utf8, utf8_len, NULL, NULL); strncat(tmpString, utf8,sizeof(tmpString) - 1 - strlen(tmpString)); free(utf8); goto done; } } /* Try US/English next */ if (VerQueryValueW(verInfo,L"\\StringFileInfo\\040904E4\\FileVersion", &vInfo, &vLen)) { int utf8_len = WideCharToMultiByte(CP_UTF8, 0, vInfo, -1, NULL, 0, NULL, NULL); char *utf8 = (char *)malloc(utf8_len); if (utf8) { WideCharToMultiByte(CP_UTF8, 0, vInfo, -1, utf8, utf8_len, NULL, NULL); strncat(tmpString, utf8, sizeof(tmpString) - 1 - strlen(tmpString)); free(utf8); goto done; } } strncat(tmpString, "???", sizeof(tmpString) - 1 - strlen(tmpString)); done: if (verInfo) { free(verInfo); verInfo = NULL; } } strncat(tmpString,"\n",sizeof(tmpString) - 1 - strlen(tmpString)); } RegCloseKey(hk); } } gdInfoString = _strdup(tmpString); } char * getVersionInfo(int verbose) { #if STACKVM extern char *__interpBuildInfo; # define INTERP_BUILD __interpBuildInfo # if COGVM extern char *__cogitBuildInfo; # endif #else # define INTERP_BUILD interpreterVersion #endif char *info = (char *)malloc(4096); info[0] = '\0'; #if SPURVM # if BytesPerOop == 8 # define ObjectMemory " Spur 64-bit" # else # define ObjectMemory " Spur" # endif #else # define ObjectMemory #endif #if defined(NDEBUG) # define BuildVariant "Production" ObjectMemory #elif DEBUGVM # define BuildVariant "Debug" ObjectMemory # else # define BuildVariant "Assert" ObjectMemory #endif sprintf(info+strlen(info), "%s [" BuildVariant " %s VM]\n", vmBuildString, getAttributeString(1003)); // 1003 == processor if (verbose) sprintf(info+strlen(info), "Built from: "); sprintf(info+strlen(info), "%s\n", INTERP_BUILD); #if COGVM if (verbose) sprintf(info+strlen(info), "With: "); sprintf(info+strlen(info), "%s\n", getAttributeString(1008)); /* __cogitBuildInfo */ #endif if (verbose) sprintf(info+strlen(info), "Revision: "); sprintf(info+strlen(info), "%s\n", sourceVersionString('\n')); return info; } /* Calling exit(ec) apparently does NOT provide the correct exit code for the * terminating process (MinGW bug?). So instead call the shutdown sequence via * _cexit() and then terminate explicitly. */ #define exit(ec) do { _cexit(); ExitProcess(ec); } while (0) /* * Allow to test if the standard input/output files are from a console or not * Inspired of: https://fossies.org/linux/misc/vim-8.0.tar.bz2/vim80/src/iscygpty.c?m=t * Return values: * -1 - Error * 0 - no console (windows only) * 1 - normal terminal (unix terminal / windows console) * 2 - pipe * 3 - file * 4 - cygwin terminal (windows only) */ sqInt fileHandleType(HANDLE fdHandle) { if (fdHandle == INVALID_HANDLE_VALUE) return -1; /* In case of Windows Shell case */ DWORD fileType = GetFileType(fdHandle); if (fileType == FILE_TYPE_CHAR) /* The specified file is a character file, typically an LPT device or a console. */ /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa364960(v=vs.85).aspx */ return 1; /* In case of Unix emulator, we need to parse the name of the pipe */ /* Cygwin/msys's pty is a pipe. */ if (fileType != FILE_TYPE_PIPE) { if (fileType == FILE_TYPE_DISK) return 3; //We have a file here if (fileType == FILE_TYPE_UNKNOWN && GetLastError() == ERROR_INVALID_HANDLE) return 0; //No stdio allocated return -1; } typedef BOOL(WINAPI *pfnGetFileInformationByHandleEx)( HANDLE hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, LPVOID lpFileInformation, DWORD dwBufferSize ); static pfnGetFileInformationByHandleEx pGetFileInformationByHandleEx = NULL; if (!pGetFileInformationByHandleEx) { pGetFileInformationByHandleEx = (pfnGetFileInformationByHandleEx) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetFileInformationByHandleEx"); if (!pGetFileInformationByHandleEx) return -1; } int size = sizeof(FILE_NAME_INFO) + sizeof(WCHAR) * MAX_PATH; FILE_NAME_INFO *nameinfo; if (!(nameinfo = alloca(size))) return -1; // Check the name of the pipe: '\{cygwin,msys}-XXXXXXXXXXXXXXXX-ptyN-{from,to}-master' if (pGetFileInformationByHandleEx(fdHandle, FileNameInfo, nameinfo, size)) { nameinfo->FileName[nameinfo->FileNameLength / sizeof(WCHAR)] = L'\0'; WCHAR *p = nameinfo->FileName; //Check that the pipe name contains msys or cygwin if ((wcsstr(p, L"msys-") || wcsstr(p, L"cygwin-")) && (wcsstr(p, L"-pty") && wcsstr(p, L"-master"))) return 4; // The openned pipe is a msys or cygwin pipe to pty return 2; // else it is just a standard pipe } return -1; } /* * Allow to test whether the file handle is from a console or not * 1 if one of the stdio is redirected to a console pipe, else 0 (and in this case, a file should be created) */ sqInt isFileHandleATTY(HANDLE fdHandle) { sqInt res = fileHandleType(fdHandle) ; return res == 1 || res == 4; } /* * Allow to test whether one of the standard input/output files is from a console or not * 1 if one of the stdio is redirected to a console pipe, else 0 (and in this case, a file should be created) */ sqInt isOneStdioDescriptorATTY() { return isFileHandleATTY(GetStdHandle(STD_INPUT_HANDLE)) || isFileHandleATTY(GetStdHandle(STD_OUTPUT_HANDLE)) || isFileHandleATTY(GetStdHandle(STD_ERROR_HANDLE)); } static void versionInfo(void) { #if 0 /* we could create a console but to version the non-consoel VM it is * sufficient to do e.g. Squeak.exe >foo; cat foo. But feel free to * add the code if you have the energy ;) */ DWORD mode; HANDLE stdouth = GetStdHandle(STD_OUTPUT_HANDLE); if (GetConsoleMode(stdouth, &mode) != 0) { char *vi = getVersionInfo(0); WriteConsole(stdouth, vi, strlen(vi), 0, 0); } else #endif printf("%s", getVersionInfo(0)); exit(0); } /****************************************************************************/ /* Error handling */ /****************************************************************************/ void SetupStderr() { WCHAR tmpName[MAX_PATH+1]; *stderrName = *stdoutName = 0; /* re-open stdout && stderr */ GetTempPathW(MAX_PATH,tmpName); if (GetStdHandle(STD_ERROR_HANDLE) == INVALID_HANDLE_VALUE) { GetTempFileNameW(tmpName,L"sq",0,stderrName); _wfreopen(stderrName,L"w+t",stderr); } else *stderrName = 0; if (GetStdHandle(STD_OUTPUT_HANDLE) == INVALID_HANDLE_VALUE) { GetTempFileNameW(tmpName,L"sq",0,stdoutName); _wfreopen(stdoutName,L"w+t",stdout); } else *stdoutName = 0; } /****************************************************************************/ /* Release */ /****************************************************************************/ static void dumpSmalltalkStackIfInMainThread(FILE *file) { extern sqInt nilObject(void); if (!nilObject()) // If no nilObject the image hasn't been loaded yet... return; if (ioOSThreadsEqual(ioCurrentOSThread(),getVMOSThread())) { fprintf(file, "\n\nSmalltalk stack dump:\n"); printCallStackOn(file); fprintf(file,"\n"); } else fprintf(file,"\nCan't dump Smalltalk stack. Not in VM thread\n"); fflush(file); } #if STACKVM static void dumpPrimTrace(FILE *file) { fprintf(file,"\nPrimitive trace:\n"); dumpPrimTraceLogOn(file); fprintf(file,"\n"); } #else # define dumpPrimTrace(f) 0 #endif void printCommonCrashDumpInfo(FILE *f) { #if STACKVM extern char *__interpBuildInfo; # if COGVM extern char *__cogitBuildInfo; # endif #endif fprintf(f,"\n\n%s", hwInfoString); fprintf(f,"\n%s", osInfoString); fprintf(f,"\n%s", gdInfoString); /* print VM version information */ fprintf(f,"\nVM Version: %s\n", VM_VERSION_VERBOSE); #if STACKVM fprintf(f,"Interpreter Build: %s\n", __interpBuildInfo); # if COGVM fprintf(f,"Cogit Build: %s\n", __cogitBuildInfo); # endif #endif fprintf(f,"Source Version: %s\n", sourceVersionString('\n')); fflush(f); fprintf(f,"\n" "Current byte code: %" PRIdSQINT "\n" "Primitive index: %" PRIdSQINT "\n", getCurrentBytecode(), methodPrimitiveIndex()); fflush(f); /* print loaded plugins */ fprintf(f,"\nLoaded plugins:\n"); int index = 0; char *pluginName; while ((pluginName = ioListLoadedModule(++index))) { fprintf(f,"\t%s\n", pluginName); fflush(f); index++; } printModuleInfo(f); fflush(f); } #define MAXFRAMES 64 /* Print an error message, possibly Smalltalk and C stack traces, and exit. */ /* Disable Intel compiler inlining of error which is used for breakpoints */ #pragma auto_inline(off) static int inError = 0; void error(const char *msg) { FILE *f; WCHAR crashInfo[1024]; void *callstack[MAXFRAMES]; symbolic_pc symbolic_pcs[MAXFRAMES]; WCHAR crashdumpname[MAX_PATH]; int nframes; int inVMThread = ioOSThreadsEqual(ioCurrentOSThread(),getVMOSThread()); int len; WCHAR *msgW; if (inError) exit(-2); inError = 1; nframes = backtrace(callstack, MAXFRAMES); symbolic_backtrace(++nframes, callstack, symbolic_pcs); len = MultiByteToWideChar(CP_UTF8, 0, msg, -1, NULL, 0); if (len > 0) { msgW = alloca(len * sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8, 0, msg, -1, msgW, len); } else { msgW = alloca(4 * sizeof(WCHAR)); wcscpy(msgW, L"???"); } f = crashDumpFile(crashdumpname); _snwprintf(crashInfo,1024, L"Sorry but the " VM_NAME " VM has crashed.\n\n" L"Reason: %s\n\n" L"Current byte code: %d\n" L"Primitive index: %" _UNICODE_TEXT(PRIdSQINT) L"\n\n" L"This information will be stored in the file\n" L"%s\n" L"with a complete stack dump", msgW, getCurrentBytecode(), methodPrimitiveIndex(), crashdumpname); if (!fHeadlessImage) MessageBoxW(stWindow,crashInfo,L"Fatal " VM_NAME " VM error", MB_OK | MB_APPLMODAL | MB_ICONSTOP); if (f) { time_t crashTime = time(NULL); fprintf(f,"---------------------------------------------------------------------\n"); fprintf(f,"%s %s\n\n", ctime(&crashTime), getAttributeString(0)); fprintf(f, "Error in %s thread\nReason: %s\n\n", inVMThread ? "the VM" : "some other", msg); printCommonCrashDumpInfo(f); dumpPrimTrace(f); fflush(f); print_backtrace(f, nframes, MAXFRAMES, callstack, symbolic_pcs); fflush(f); dumpSmalltalkStackIfInMainThread(f); fflush(f); fclose(f); } printf("Error in %s thread\nReason: %s\n\n", inVMThread ? "the VM" : "some other", msg); dumpPrimTrace(stdout); print_backtrace(stdout, nframes, MAXFRAMES, callstack, symbolic_pcs); /* /Don't/ print the caller's stack to stdout here; Cleanup will do so. */ /* dumpSmalltalkStackIfInMainThread(stdout); */ exit(EXIT_FAILURE); } static int inCleanExit = 0; /* to suppress stack trace in Cleanup */ sqInt ioExit(void) { return ioExitWithErrorCode(0); } sqInt ioExitWithErrorCode(int ec) { #if COGVM extern sqInt reportStackHeadroom; if (reportStackHeadroom) reportMinimumUnusedHeadroom(); #endif printPhaseTime(3); inCleanExit = 1; exit(ec); return ec; } #pragma auto_inline(on) static void printCrashDebugInformation(PEXCEPTION_POINTERS exp) { void *callstack[MAXFRAMES]; symbolic_pc symbolic_pcs[MAXFRAMES]; WCHAR crashdumpname[MAX_PATH]; int nframes, inVMThread; WCHAR crashInfo[1024]; FILE *f; int byteCode = -2; if ((inVMThread = ioOSThreadsEqual(ioCurrentOSThread(),getVMOSThread()))) /* Retrieve current byte code. If this fails the IP is probably wrong */ TRY { byteCode = getCurrentBytecode(); } EXCEPT(EXCEPTION_EXECUTE_HANDLER) { byteCode = -1; } TRY { if (inVMThread) ifValidWriteBackStackPointersSaveTo((void *)exp->ContextRecord->CONTEXT_FP, (void *)exp->ContextRecord->CONTEXT_SP, 0, 0); callstack[0] = (void *)exp->ContextRecord->CONTEXT_PC; nframes = backtrace_from_fp((void*)exp->ContextRecord->CONTEXT_FP, callstack+1, MAXFRAMES-1); symbolic_backtrace(++nframes, callstack, symbolic_pcs); f = crashDumpFile(crashdumpname); _snwprintf(crashInfo,1024, L"Sorry but the " VM_NAME " VM has crashed.\n\n" L"Exception code: %08x\n" #ifdef _WIN64 L"Exception address: %016" _UNICODE_TEXT(PRIxSQPTR) L"\n" #else L"Exception address: %08" _UNICODE_TEXT(PRIxSQPTR) L"\n" #endif L"Current byte code: %d\n" L"Primitive index: %" _UNICODE_TEXT(PRIdSQINT) L"\n\n" L"Crashed in %s thread\n\n" L"This information will be stored in the file\n" L"%s\n" L"with a complete stack dump", exp->ExceptionRecord->ExceptionCode, (sqIntptr_t) (exp->ExceptionRecord->ExceptionAddress), byteCode, methodPrimitiveIndex(), inVMThread ? L"the VM" : L"some other", crashdumpname); if (!fHeadlessImage) MessageBoxW(stWindow,crashInfo,L"Fatal " VM_NAME " VM error", MB_OK | MB_APPLMODAL | MB_ICONSTOP); if (f) { time_t crashTime = time(NULL); fprintf(f,"---------------------------------------------------------------------\n"); fprintf(f,"%s\n", ctime(&crashTime)); /* Print the exception code */ fprintf(f,"Exception code: %08lX\nException addr: %0*" PRIXSQPTR "\n", exp->ExceptionRecord->ExceptionCode, (int) sizeof(exp->ExceptionRecord->ExceptionAddress)*2, (usqIntptr_t) exp->ExceptionRecord->ExceptionAddress); if (exp->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) { /* For access violations print what actually happened */ fprintf(f,"Access violation (%s) at %0*" PRIXSQPTR "\n", (exp->ExceptionRecord->ExceptionInformation[0] ? "write access" : "read access"), (int) sizeof(exp->ExceptionRecord->ExceptionInformation[1])*2, exp->ExceptionRecord->ExceptionInformation[1]); } #if defined(_M_IX86) || defined(_M_I386) || defined(_X86_) || defined(i386) || defined(__i386__) fprintf(f,"EAX:%08lX\tEBX:%08lX\tECX:%08lX\tEDX:%08lX\n", exp->ContextRecord->Eax, exp->ContextRecord->Ebx, exp->ContextRecord->Ecx, exp->ContextRecord->Edx); fprintf(f,"ESI:%08lX\tEDI:%08lX\tEBP:%08lX\tESP:%08lX\n", exp->ContextRecord->Esi, exp->ContextRecord->Edi, exp->ContextRecord->Ebp, exp->ContextRecord->Esp); fprintf(f,"EIP:%08lX\tEFL:%08lX\n", exp->ContextRecord->Eip, exp->ContextRecord->EFlags); fprintf(f,"FP Control: %08lX\nFP Status: %08lX\nFP Tag: %08lX\n", exp->ContextRecord->FloatSave.ControlWord, exp->ContextRecord->FloatSave.StatusWord, exp->ContextRecord->FloatSave.TagWord); #elif defined(x86_64) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__amd64__) || defined(x64) || defined(_M_AMD64) || defined(_M_X64) || defined(_M_IA64) # define FMT PRIxSQPTR fprintf(f, "RAX:%016" FMT "\tRBX:%016" FMT "\tRCX:%016" FMT "\n", exp->ContextRecord->Rax, exp->ContextRecord->Rbx, exp->ContextRecord->Rcx); fprintf(f, "RDX:%016" FMT "\tRSI:%016" FMT "\tRDI:%016" FMT "\n", exp->ContextRecord->Rdx, exp->ContextRecord->Rsi, exp->ContextRecord->Rdi); fprintf(f, "RBP:%016" FMT "\tRSP:%016" FMT "\tR8 :%016" FMT "\n", exp->ContextRecord->Rbp, exp->ContextRecord->Rsp, exp->ContextRecord->R8); fprintf(f,"R9 :%016" FMT "\tR10:%016" FMT "\tR11:%016" FMT "\n", exp->ContextRecord->R9, exp->ContextRecord->R10, exp->ContextRecord->R11); fprintf(f,"R12:%016" FMT "\tR13:%016" FMT "\tR14:%016" FMT "\n", exp->ContextRecord->R12, exp->ContextRecord->R13, exp->ContextRecord->R14); fprintf(f,"R15:%016" FMT "\tRIP:%016" FMT " EFL:%08lx\n", exp->ContextRecord->R15, exp->ContextRecord->Rip, exp->ContextRecord->EFlags); fprintf(f,"FP Control: %08x\tFP Status: %08x\tFP Tag: %08x\n", exp->ContextRecord->FltSave.ControlWord, exp->ContextRecord->FltSave.StatusWord, exp->ContextRecord->FltSave.TagWord); #else # error "unknown architecture, cannot pick dump registers" #endif fprintf(f, "\n\nCrashed in %s thread\n\n", inVMThread ? "the VM" : "some other"); printCommonCrashDumpInfo(f); dumpPrimTrace(f); print_backtrace(f, nframes, MAXFRAMES, callstack, symbolic_pcs); dumpSmalltalkStackIfInMainThread(f); #if COGVM reportMinimumUnusedHeadroomOn(f); #endif fclose(f); } /* print recently called prims to stdout */ dumpPrimTrace(stdout); /* print C stack to stdout */ print_backtrace(stdout, nframes, MAXFRAMES, callstack, symbolic_pcs); /* print the caller's stack to stdout */ dumpSmalltalkStackIfInMainThread(stdout); #if COGVM reportMinimumUnusedHeadroomOn(stdout); #endif } EXCEPT(EXCEPTION_EXECUTE_HANDLER) { /* that's too bad ... */ if (!fHeadlessImage) MessageBox(0,TEXT("The VM has crashed. Sorry."),TEXT("Fatal error:"), MB_OK | MB_APPLMODAL | MB_ICONSTOP); else abortMessage(TEXT("The VM has crashed. Sorry.")); } } void __cdecl Cleanup(void) { /* not all of these are essential, but they're polite... */ if (!inCleanExit) dumpSmalltalkStackIfInMainThread(stdout); ioShutdownAllModules(); ioReleaseTime(); /* tricky ... we have no systray icon when running headfull or when running as service on NT */ if (fHeadlessImage && (!fRunService)) SetSystemTrayIcon(0); if (palette) DeleteObject(palette); PROFILE_SHOW(ticksForReversal); PROFILE_SHOW(ticksForBlitting); if (*stderrName) { fclose(stderr); _wremove(stderrName); } if (*stdoutName) { fclose(stdout); _wremove(stdoutName); } OleUninitialize(); } /****************************************************************************/ /* Embedded Images */ /****************************************************************************/ #if 0 /* SQ_IMAGE_MAGIC - the magic number for embedded images "SQIM" */ #define SQ_IMAGE_MAGIC 0x83817377 sqImageFile findEmbeddedImage(void) { sqImageFile f; int endMarker; int magic; int start; int length; f = sqImageFileOpen(vmNameA, "rb"); if (!f) { MessageBox(0,"Error opening VM",VM_NAME,MB_OK); return 0; } endMarker = sqImageFileSize(f) - 8; magic = start = 0; sqImageFileSeek(f, endMarker); sqImageFileRead(&magic, 1, 4, f); sqImageFileRead(&start, 1, 4, f); sqMessageBox(MB_OK, TEXT("Magic number", "Expected:\t%x\nFound:\t\t%x"), SQ_IMAGE_MAGIC, magic); /* Magic number must be okay and start must be within executable boundaries */ if (magic != SQ_IMAGE_MAGIC || start < 0 || start >= endMarker) { /* nope */ sqImageFileClose(f); return 0; } /* Might have an embedded image; seek back and double check */ sqImageFileSeek(f,start); sqImageFileRead(&magic, 1, 4, f); sqMessageBox(MB_OK, TEXT("Magic number", "Expected:\t%x\nFound:\t\t%x"), SQ_IMAGE_MAGIC, magic); if (magic != SQ_IMAGE_MAGIC) { /* nope */ sqImageFileClose(f); return 0; } /* now triple check for image format */ sqImageFileRead(&magic, 1, 4, f); if (!readableFormat(magic) && !readableFormat(byteSwapped(magic)) { /* nope */ sqImageFileClose(f); return 0; } /* Gotcha! */ sqImageFileSeek(f, sqImageFilePosition(f) - 4); strcpy(imageName, name); MultiByteToWideChar(CP_UTF8,0,imageName,-1,imageNameW,MAX_PATH,NULL,NULL); imageSize = endMarker - sqImageFilePosition(f); return f; } #else sqImageFile findEmbeddedImage(void) { return 0; } #endif /****************************************************************************/ /* sqMain */ /****************************************************************************/ #if (STACKVM || NewspeakVM) && !COGVM extern volatile int sendTrace; #endif #if STACKVM || NewspeakVM extern sqInt checkForLeaks; #endif /* STACKVM || NewspeakVM */ #if STACKVM extern sqInt desiredNumStackPages; extern sqInt desiredEdenBytes; extern sqInt suppressHeartbeatFlag; #endif /* STACKVM */ #if COGVM extern sqInt desiredCogCodeSize; extern int traceFlags; extern sqInt traceStores; extern usqIntptr_t debugPrimCallStackOffset; extern sqInt maxLiteralCountForCompile; extern sqInt minBackwardJumpCountForCompile; #endif /* COGVM */ /* sqMain: This is common entry point regardless of whether we're running as a normal app or as a service. Note that a number of things may have been set up before coming here. In particular, * fRunService - to determine whether we're running as NT service However, the command line must always contain all parameters necessary. In other words, even though the logName may have been set before, the command line has to include the -log switch. */ static int parseArguments(int argc, char *argv[]); int sqMain(int argc, char *argv[]) { int virtualMemory; /* set default fpu control word */ _controlfp(FPU_DEFAULT, FPU_MASK); LoadPreferences(); /* If running as single app, find the previous instance */ if (fRunSingleApp) { HWND win = GetTopWindow(0); while (win != NULL) { TCHAR buf[MAX_PATH]; GetClassName(win, buf, MAX_PATH); if (_tcscmp(windowClassName, buf) == 0) break; win = GetNextWindow(win, GW_HWNDNEXT); } if (win) { WCHAR *cmdLineW = GetCommandLineW(); /* An instance is running already. Inform it about the app. */ int bytes = (wcslen(cmdLineW)+1) * sizeof(WCHAR); HANDLE h = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, bytes); WCHAR *string = GlobalLock(h); memcpy(string, cmdLineW, bytes); GlobalUnlock(h); OpenClipboard(NULL); EmptyClipboard(); SetClipboardData(CF_UNICODETEXT, h); CloseClipboard(); if (IsIconic(win)) ShowWindow(win, SW_RESTORE); SetForegroundWindow(win); SetActiveWindow(win); return PostMessage(win, SQ_LAUNCH_DROP, 0, 0); } } /* parse command line args */ if (!parseArguments(argc, argv)) return printUsage(1); /* a quick check if we have any argument at all */ if (!fRunService && (*imageName == 0)) { /* Check if the image is embedded */ imageFile = findEmbeddedImage(); if (!imageFile) { /* Search the current directory if there's a single image file */ if (!findImageFile()) { /* Nope. Give the user a chance to open an image interactively */ if (fHeadlessImage || !openImageFile()) return -1; /* User cancelled file open */ } } } #ifdef NO_SERVICE fRunService = 0; #endif /* set time zone accordingly */ _tzset(); /* Initialize OLE library so we don't have to do it from other places */ OleInitialize(NULL); /* Give us some log information when running as service */ if (fRunService) { time_t svcStart; svcStart = time(NULL); OutputLogMessage("\n\n"); OutputLogMessage(ctime(&svcStart)); OutputLogMessageW(serviceName); OutputLogMessage(" started with the following command line\n"); OutputLogMessage(initialCmdLine); OutputLogMessage("\n"); } SetupFilesAndPath(); ioSetLogDirectoryOfSize(vmPathA, strlen(vmPathA)); /* release resources on exit */ atexit(Cleanup); #ifndef NO_SERVICE /* if service installing is requested, do so */ if (installServiceName && *installServiceName) { wcscpy(serviceName, installServiceName); sqServiceInstall(); /* When installing was successful we won't come to this point. Otherwise ... */ exit(EXIT_FAILURE); /* this will show any printfs during install */ } #endif /* initialisation */ SetupWindows(); SetupPixmaps(); ioInitTime(); ioInitThreads(); # if !COGMTVM /* Set the current VM thread. If the main thread isn't the VM thread then * when that thread is spawned it can reassign ioVMThread. */ ioVMThread = ioCurrentOSThread(); # endif /* check the interpreter's size assumptions for basic data types */ if (sizeof(int) != 4) error("This C compiler's integers are not 32 bits."); if (sizeof(sqLong) != 8) error("This C compiler's long longs are not 64 bits."); if (sizeof(double) != 8) error("This C compiler's floats are not 64 bits."); if (!imageFile) { imageSize = SqueakImageLength(imageNameW); if (imageSize == 0) printUsage(2); } /* allocate this before anything is going to happen */ vmWakeUpEvent = CreateEvent(NULL, 1, 0, NULL); /* initial commit size = imageSize + 4MB */ virtualMemory = imageSize + 0x00400000; #if !NO_FIRST_LEVEL_EXCEPTION_HANDLER /* Install our top-level exception handler */ InstallExceptionHandler(); # ifdef _MSC_VER __try { // belt and braces... # endif #endif /* !NO_FIRST_LEVEL_EXCEPTION_HANDLER */ #if !NewspeakVM /* set the CWD to the image location */ if (*imageNameW) { WCHAR path[MAX_PATH+1], *ptr; wcsncpy(path,imageNameW,MAX_PATH); path[MAX_PATH] = 0; ptr = wcsrchr(path, '\\'); if (ptr) { *ptr = 0; SetCurrentDirectoryW(path); } } #endif /* !NewspeakVM */ /* display the splash screen */ ShowSplashScreen(); /* if headless running is requested, try to to create an icon in the Win95/NT system tray */ if(fHeadlessImage && !fRunService) SetSystemTrayIcon(1); /* read the image file */ if (!imageFile) { imageFile = sqImageFileOpen(imageName,"rb"); readImageFromFileHeapSizeStartingAt(imageFile, virtualMemory, 0); } else { readImageFromFileHeapSizeStartingAt(imageFile, virtualMemory, sqImageFilePosition(imageFile)); } sqImageFileClose(imageFile); if (fHeadlessImage) HideSplashScreen(); /* need to do it manually */ SetWindowSize(); ioSetFullScreen(getFullScreenFlag()); /* run Squeak */ ioInitSecurity(); printPhaseTime(2); interpret(); #if !NO_FIRST_LEVEL_EXCEPTION_HANDLER # ifdef _MSC_VER } __except(squeakExceptionHandler(GetExceptionInformation())) { /* Do nothing */ } # endif /* remove the top-level exception handler */ UninstallExceptionHandler(); #endif /* !NO_FIRST_LEVEL_EXCEPTION_HANDLER */ return 1; } /****************************************************************************/ /* WinMain */ /****************************************************************************/ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { /* Determine if we're running as a console application We can't report * allocation failures unless running as a console app because doing so * via a MessageBox will make the system unusable. */ fIsConsole = isOneStdioDescriptorATTY(); /* a few things which need to be done first */ gatherSystemInfo(); /* fetch us a copy of the command line */ initialCmdLine = _strdup(lpCmdLine); /* fetch us the name of the executable */ { GetModuleFileNameW(hInst, vmNameW, MAX_PATH); WideCharToMultiByte(CP_UTF8, 0, vmNameW, -1, vmNameA, MAX_PATH_UTF8, NULL, NULL); } /* parse the command line into the unix-style argc, argv, converting to * UTF-8 on the way. */ { LPWSTR *argList = CommandLineToArgvW(GetCommandLineW(), &clargc); int i; clargv = calloc(clargc + 1, sizeof(char *)); vmOptions = calloc(clargc + 1, sizeof(char *)); imageOptions = calloc(clargc + 1, sizeof(char *)); if (!clargv || !vmOptions || !imageOptions) { fprintf(stderr,"out of memory for command line?!\n"); return 1; } for (i = 0; i < clargc; i++) { int n = WideCharToMultiByte(CP_UTF8, 0, argList[i], -1, 0, 0, 0, 0); if (!(clargv[i] = malloc(n))) { fprintf(stderr,"out of memory for command line?!\n"); return 1; } WideCharToMultiByte(CP_UTF8, 0, argList[i], -1, clargv[i], n, 0, 0); } LocalFree(argList); } /* open all streams in binary mode */ _fmode = _O_BINARY; /* get us the instance handle */ hInstance = hInst; #ifndef NO_SERVICE /* Find out if we're running from a service. That's a bit tricky since there is no difference between usual startup and service startup. We do two assumptions here: 1) If we're NOT running on NT we can't be service 2) If there is a command line we can't be service Still, there is a chance that a user just double clicks on the Squeak executable in NT. Therefore we _try_ to connect to the service control manager in the sqServiceMain function. If this fails, we try the usual startup. It might take a bit longer than the normal startup but this only happens if there is no image name given - and that's not our fault. Anyways, if somebody out there knows how to find out when we're starting as a service - LET ME KNOW! */ if (!*lpCmdLine) /* No command line */ if (sqServiceMain()) /* try starting the service */ return 0; /* service was run - exit */ #endif SQ_LAUNCH_DROP = RegisterWindowMessage(TEXT("SQUEAK_LAUNCH_DROP")); /* start the non-service version */ sqMain(clargc, clargv); return 0; } /* Mingw32 automatically adds a main routine for -mconsole links. MSVC's LINK * does not. So define a main routine for the console VM, but only if not on * mingw. */ #if (!defined(__MINGW32__) && !defined(__MINGW64__)) int main(int argc, char *argv[]) { /* Determine if we're running as a console application We can't report * allocation failures unless running as a console app because doing so * via a MessageBox will make the system unusable. */ fIsConsole = isOneStdioDescriptorATTY(); /* a few things which need to be done first */ gatherSystemInfo(); /* get us the instance handle */ hInstance = GetModuleHandle(0); /* fetch us the name of the executable */ { GetModuleFileNameW(hInstance, vmNameW, MAX_PATH); WideCharToMultiByte(CP_UTF8, 0, vmNameW, -1, vmNameA, MAX_PATH_UTF8, NULL, NULL); } /* open all streams in binary mode */ _fmode = _O_BINARY; #ifndef NO_SERVICE /* Find out if we're running from a service. That's a bit tricky since there is no difference between usual startup and service startup. We do two assumptions here: 1) If we're NOT running on NT we can't be service 2) If there is a command line we can't be service Still, there is a chance that a user just double clicks on the Squeak executable in NT. Therefore we _try_ to connect to the service control manager in the sqServiceMain function. If this fails, we try the usual startup. It might take a bit longer than the normal startup but this only happens if there is no image name given - and that's not our fault. Anyways, if somebody out there knows how to find out when we're starting as a service - LET ME KNOW! */ if (!*lpCmdLine) /* No command line */ if (sqServiceMain()) /* try starting the service */ return 0; /* service was run - exit */ #endif SQ_LAUNCH_DROP = RegisterWindowMessage(TEXT("SQUEAK_LAUNCH_DROP")); vmOptions = calloc(argc + 1, sizeof(char *)); imageOptions = calloc(argc + 1, sizeof(char *)); /* start the non-service version */ sqMain(argc, argv); return 0; } #endif /* (!defined(__MINGW32__) && !defined(__MINGW64__)) */ static sqIntptr_t strtobkm(const char *str) { char *suffix; #if SQ_HOST64 sqIntptr_t value = strtoll(str, &suffix, 10); #else sqIntptr_t value = strtol(str, &suffix, 10); #endif switch (*suffix) { case 'k': case 'K': return value * 1024ULL; case 'm': case 'M': return value * 1024ULL*1024ULL; } return value; } static usqIntptr_t strtobkmg(const char *str) { char *suffix; #if SQ_HOST64 sqIntptr_t value = strtoll(str, &suffix, 10); #else sqIntptr_t value = strtol(str, &suffix, 10); #endif switch (*suffix) { case 'k': case 'K': return value * 1024ULL; case 'm': case 'M': return value * 1024ULL*1024ULL; case 'g': case 'G': return value * 1024ULL*1024ULL*1024ULL; } return value; } static int parseVMArgument(int argc, char *argv[]) { #if SPURVM extern usqInt maxOldSpaceSize; #endif /* flags */ if (!strcmp(argv[0], VMOPTION("help"))) { printUsage(1); return 1; } else if (!strcmp(argv[0], VMOPTION("version"))) { versionInfo(); return 1; } else if (!strcmp(argv[0], VMOPTION("headless"))) { fHeadlessImage = true; return 1; } else if (!strcmp(argv[0], VMOPTION("headfull"))) { fHeadlessImage = false; return 1;} else if (!strcmp(argv[0], VMOPTION("timephases"))) { printPhaseTime(1); return 1; } #ifdef VISTA_SECURITY /* IE7/Vista protected mode support */ /* started with low rights, use alternate untrustedUserDirectory */ else if (!strcmp(argv[0], VMOPTION("lowRights"))) { fLowRights = true; return 1; } #endif /* VISTA_SECURITY */ #if (STACKVM || NewspeakVM) && !COGVM else if (!strcmp(argv[0], VMOPTION("sendtrace"))) { extern volatile int sendTrace; sendTrace = 1; return 1; } #endif /* parameters */ else if (argc > 1 && !strcmp(argv[0], VMOPTION("service"))) { int len = MultiByteToWideChar(CP_UTF8, 0, argv[1], -1, installServiceName, 0); installServiceName = malloc(len * sizeof(WCHAR)); /* note: we will never free installServiceName - it's a global for lifetime of the VM */ MultiByteToWideChar(CP_UTF8, 0, argv[1], -1, installServiceName, len); return 2; } else if (!strncmp(argv[0], VMOPTION("service:"), strlen(VMOPTION("service:")))) { int len = MultiByteToWideChar(CP_UTF8, 0, argv[0] + strlen(VMOPTION("log:")), -1, installServiceName, 0); logName = malloc(len * sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8, 0, argv[0] + strlen(VMOPTION("log:")), -1, installServiceName, len); return 1; } else if (argc > 1 && !strcmp(argv[0], VMOPTION("log"))) { int len=MultiByteToWideChar(CP_UTF8, 0, argv[1], -1, logName, 0); logName = malloc(len * sizeof(WCHAR)); /* note: we will never free logName - it's a global for lifetime of the VM */ MultiByteToWideChar(CP_UTF8, 0, argv[1], -1, logName, len); return 2; } else if (!strncmp(argv[0], VMOPTION("log:"), strlen(VMOPTION("log:")))) { int len = MultiByteToWideChar(CP_UTF8, 0, argv[0] + strlen(VMOPTION("log:")), -1, logName, 0); logName = malloc(len * sizeof(WCHAR)); MultiByteToWideChar(CP_UTF8, 0, argv[0] + strlen(VMOPTION("log:")), -1, logName, len); return 1; } else if (argc > 1 && !strcmp(argv[0], VMOPTION("memory"))) { dwMemorySize = strtobkmg(argv[1]); return 2; } else if (!strncmp(argv[0], VMOPTION("memory:"), strlen(VMOPTION("memory:")))) { dwMemorySize = strtobkmg(argv[0] + strlen(VMOPTION("memory:"))); return 1; } #if STACKVM || NewspeakVM else if (argc > 1 && !strcmp(argv[0], VMOPTION("breaksel"))) { extern void setBreakSelector(char *); setBreakSelector(argv[1]); return 2; } else if (!strncmp(argv[0], VMOPTION("breaksel:"), strlen(VMOPTION("breaksel:")))) { extern void setBreakSelector(char *); setBreakSelector(argv[0] + strlen(VMOPTION("breaksel:"))); return 1; } else if (argc > 1 && !strcmp(argv[0], VMOPTION("numextsems"))) { ioSetMaxExtSemTableSize(atoi(argv[1])); return 2; } else if (!strncmp(argv[0], VMOPTION("numextsems:"), strlen(VMOPTION("numextsems:")))) { ioSetMaxExtSemTableSize(atoi(argv[0]+strlen(VMOPTION("numextsems:")))); return 1; } #endif /* STACKVM || NewspeakVM */ #if STACKVM else if (argc > 1 && !strcmp(argv[0], VMOPTION("breakmnu"))) { extern void setBreakMNUSelector(char *); setBreakMNUSelector(argv[1]); return 2; } else if (!strncmp(argv[0], VMOPTION("breakmnu:"), strlen(VMOPTION("breakmnu:")))) { extern void setBreakMNUSelector(char *); setBreakMNUSelector(argv[0] + strlen(VMOPTION("breakmnu:"))); return 1; } else if (argc > 1 && !strcmp(argv[0], VMOPTION("eden"))) { extern sqInt desiredEdenBytes; desiredEdenBytes = strtobkmg(argv[1]); return 2; } else if (!strncmp(argv[0], VMOPTION("eden:"), strlen(VMOPTION("eden:")))) { extern sqInt desiredEdenBytes; desiredEdenBytes = strtobkmg(argv[0]+strlen(VMOPTION("eden:"))); return 1; } else if (argc > 1 && !strcmp(argv[0], VMOPTION("leakcheck"))) { extern sqInt checkForLeaks; checkForLeaks = atoi(argv[1]); return 2; } else if (!strncmp(argv[0], VMOPTION("leakcheck:"), strlen(VMOPTION("leakcheck:")))) { extern sqInt checkForLeaks; checkForLeaks = atoi(argv[0]+strlen(VMOPTION("leakcheck:"))); return 1; } else if (argc > 1 && !strcmp(argv[0], VMOPTION("stackpages"))) { extern sqInt desiredNumStackPages; desiredNumStackPages = atoi(argv[1]); return 2; } else if (!strncmp(argv[0], VMOPTION("stackpages:"), strlen(VMOPTION("stackpages:")))) { extern sqInt desiredNumStackPages; desiredNumStackPages = atoi(argv[0]+strlen(VMOPTION("stackpages:"))); return 1; } else if (!strcmp(argv[0], VMOPTION("noheartbeat"))) { extern sqInt suppressHeartbeatFlag; suppressHeartbeatFlag = 1; return 1; } else if (!strcmp(argv[0], VMOPTION("warnpid"))) { extern sqInt warnpid; warnpid = GetCurrentProcessId(); return 1; } else if (!strcmp(argv[0], VMOPTION("failonffiexception"))) { extern sqInt ffiExceptionResponse; ffiExceptionResponse = 1; return 1; } else if (!strcmp(argv[0], VMOPTION("nofailonffiexception"))) { extern sqInt ffiExceptionResponse; ffiExceptionResponse = -1; return 1; } else if (!strcmp(argv[0], VMOPTION("debugfailonffiexception"))) { debugBreakOnException = true; return 1; } else if (argc > 1 && !strcmp(argv[0], VMOPTION("eventtrace"))) { extern sqInt eventTraceMask; eventTraceMask = atoi(argv[1]); return 2; } else if (!strncmp(argv[0], VMOPTION("eventtrace:"), strlen(VMOPTION("eventtrace:")))) { extern sqInt eventTraceMask; eventTraceMask = atoi(argv[0]+strlen(VMOPTION("leakcheck:"))); return 1; } #endif /* STACKVM */ #if COGVM else if (argc > 1 && !strcmp(argv[0], VMOPTION("codesize"))) { extern sqInt desiredCogCodeSize; desiredCogCodeSize = strtobkm(argv[1]); return 2; } else if (argc > 1 && !strcmp(argv[0], VMOPTION("logplugin"))) { extern char *primTracePluginName; primTracePluginName = argv[1]; return 2; } # define TLSLEN (sizeof(VMOPTION("trace"))-1) else if (!strncmp(argv[0], VMOPTION("trace"), TLSLEN)) { extern int traceFlags; char *equalsPos = strchr(argv[0],'='); if (!equalsPos) { traceFlags = 1; return 1; } if (equalsPos - argv[0] != TLSLEN || (equalsPos[1] != '-' && !isdigit(equalsPos[1]))) return 0; traceFlags = atoi(equalsPos + 1); return 1; } else if (!strcmp(argv[0], VMOPTION("tracestores"))) { extern sqInt traceStores; traceStores = 1; return 1; } else if (argc > 1 && !strcmp(argv[0], VMOPTION("cogmaxlits"))) { extern sqInt maxLiteralCountForCompile; maxLiteralCountForCompile = strtobkm(argv[1]); return 2; } else if (!strncmp(argv[0], VMOPTION("cogmaxlits:"), strlen(VMOPTION("cogmaxlits:")))) { extern sqInt maxLiteralCountForCompile; maxLiteralCountForCompile = strtobkm(argv[0]+strlen(VMOPTION("cogmaxlits:"))); return 1; } else if (argc > 1 && !strcmp(argv[0], VMOPTION("cogminjumps"))) { extern sqInt minBackwardJumpCountForCompile; minBackwardJumpCountForCompile = strtobkm(argv[1]); return 2; } else if (!strncmp(argv[0], VMOPTION("cogminjumps:"),strlen(VMOPTION("cogminjumps:")))) { extern sqInt minBackwardJumpCountForCompile; minBackwardJumpCountForCompile = strtobkm(argv[0]+strlen(VMOPTION("cogminjumps:"))); return 1; } else if (!strcmp(argv[0], VMOPTION("reportheadroom")) || !strcmp(argv[0], VMOPTION("rh"))) { extern sqInt reportStackHeadroom; reportStackHeadroom = 1; return 1; } #endif /* COGVM */ #if SPURVM else if (argc > 1 && !strcmp(argv[0], VMOPTION("maxoldspace"))) { maxOldSpaceSize = (usqInt) strtobkmg(argv[1]); return 2; } else if (!strncmp(argv[0], VMOPTION("maxoldspace:"), strlen(VMOPTION("maxoldspace:")))) { maxOldSpaceSize = (usqInt) strtobkmg(argv[0]+strlen(VMOPTION("maxoldspace:"))); return 2; } else if (!strcmp(argv[0], VMOPTION("logscavenge"))) { extern void openScavengeLog(void); openScavengeLog(); return 1; } #endif return 0; /* option not recognised */ } /* parse all arguments meaningful to the VM; answer index of last VM arg + 1 */ static int parseVMArgs(int argc, char *argv[]) { int n,j,ddash,i = 0; while (++i < argc && *argv[i] == '-' && strcmp(argv[i],"--")) { ddash= (argv[i][1] == '-'); if (ddash) argv[i]++; n = parseVMArgument(argc - i, argv + i); if (ddash) argv[i]--; if (n > 0) { for (j = 0; j < n; j++) vmOptions[numOptionsVM++] = argv[i+j]; i += n - 1; } else { fprintf(stderr,"Unknown option encountered!\n"); return i; } } return i; } static int IsImage(char *name) { int magic; sqImageFile fp; fp = sqImageFileOpen(name,"rb"); if (!fp) return 0; /* not an image */ if (sqImageFileSize(fp) < (64 * 1024)) { sqImageFileClose(fp); return 0; } if (sqImageFileRead(&magic, 1, sizeof(magic), fp) != sizeof(magic)) { sqImageFileClose(fp); return 0; } if (readableFormat(magic) || readableFormat(byteSwapped(magic))) { sqImageFileClose(fp); return true; } /* no luck at beginning of file, seek to 512 and try again */ sqImageFileSeek(fp, 512); if (sqImageFileRead(&magic, 1, sizeof(magic), fp) != sizeof(magic)) { sqImageFileClose(fp); return 0; } sqImageFileClose(fp); return readableFormat(magic) || readableFormat(byteSwapped(magic)); } /* * Answer exe's SUBSYSTEM type. From http://support.microsoft.com/kb/90493. */ static int SubsystemType() { HANDLE hImage; DWORD bytes; ULONG ntSignature; IMAGE_DOS_HEADER image_dos_header; IMAGE_OPTIONAL_HEADER image_optional_header; /* Open the reference file. */ hImage = CreateFileW(vmNameW, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hImage) return -1; /* Read the MS-DOS image header. */ if (!ReadFile(hImage, &image_dos_header, sizeof(IMAGE_DOS_HEADER), &bytes, 0) || bytes != sizeof(IMAGE_DOS_HEADER)) return -2; if (image_dos_header.e_magic != IMAGE_DOS_SIGNATURE) return -3; /* Get actual COFF header. */ if (SetFilePointer( hImage, image_dos_header.e_lfanew, 0, FILE_BEGIN) == 0xFFFFFFFF) return -4; if (!ReadFile(hImage, &ntSignature, sizeof(ULONG), &bytes, 0) || bytes != sizeof(ULONG)) return -5; if (IMAGE_NT_SIGNATURE != ntSignature) return -6; if (SetFilePointer( hImage, IMAGE_SIZEOF_FILE_HEADER, 0, FILE_CURRENT) == 0xFFFFFFFF) return -7; /* Read optional header. */ if (!ReadFile(hImage, &image_optional_header, IMAGE_SIZEOF_NT_OPTIONAL_HEADER, &bytes, 0) || bytes != IMAGE_SIZEOF_NT_OPTIONAL_HEADER) return -8; CloseHandle(hImage); return image_optional_header.Subsystem; } /* parse all arguments starting with the image name */ static int parseGenericArgs(int argc, char *argv[]) { int i; if (argc < 1) switch (SubsystemType()) { case IMAGE_SUBSYSTEM_WINDOWS_GUI: case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI: return 1; /* ok not to have an image since user can choose one. */ default: /* It is OK to run the console VM provided an image has been * provided by the ini file. */ return imageName[0] != 0; } /* Always allow the command-line to override an implicit image name. */ if (*argv[0] && IsImage(argv[0])) { strncpy(imageName, argv[0], MAX_PATH_UTF8); MultiByteToWideChar(CP_UTF8, 0, imageName, -1, imageNameW, MAX_PATH); /* if provided, the image is a vm argument. */ vmOptions[numOptionsVM++] = argv[0]; } else if (*imageName) /* provide image name as second argument if implicitly specified */ imageOptions[numOptionsImage++] = imageName; for (i = 0; i < argc; i++) imageOptions[numOptionsImage++] = argv[i]; return 1; } static int parseArguments(int argc, char *argv[]) { int nvmargs; /* argv[0] = executable name */ vmOptions[numOptionsVM++] = argv[0]; /* parse VM options */ nvmargs = parseVMArgs(argc, argv); /* parse image and generic args */ return parseGenericArgs(argc - nvmargs, argv + nvmargs); } #if COGVM #include <signal.h> /* * Support code for Cog. * a) Answer whether the C frame pointer is in use, for capture of the C stack * pointers. * b) answer the amount of stack room to ensure in a Cog stack page, including * the size of the redzone, if any. */ # if defined(_M_IX86) || defined(_M_I386) || defined(_X86_) || defined(i386) || defined(__i386) || defined(__i386__) \ || defined(x86_64) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(__amd64__) || defined(x64) || defined(_M_AMD64) || defined(_M_X64) || defined(_M_IA64) int isCFramePointerInUse(usqIntptr_t *cFrmPtrPtr, usqIntptr_t *cStkPtrPtr) { extern void (*ceCaptureCStackPointers)(void); usqIntptr_t currentCSP = *cStkPtrPtr; ceCaptureCStackPointers(); assert(*cStkPtrPtr < currentCSP); return *cFrmPtrPtr >= *cStkPtrPtr && *cFrmPtrPtr <= currentCSP; } # else # error please provide a definition of isCFramePointerInUse for this platform # endif /* defined(_M_IX86) et al */ /* Answer an approximation of the size of the redzone (if any). Do so by * sending a signal to the process and computing the difference between the * stack pointer in the signal handler and that in the caller. Assumes stacks * descend. */ #if !defined(min) # define min(x,y) (((x)>(y))?(y):(x)) #endif static char * volatile p = 0; static void sighandler(int sig) { p = (char *)&sig; } static int getRedzoneSize() { #if defined(SIGPROF) /* cygwin */ struct sigaction handler_action, old; handler_action.sa_sigaction = sighandler; handler_action.sa_flags = SA_NODEFER | SA_SIGINFO; sigemptyset(&handler_action.sa_mask); (void)sigaction(SIGPROF, &handler_action, &old); do kill(getpid(),SIGPROF); while (!p); (void)sigaction(SIGPROF, &old, 0); return (char *)min(&old,&handler_action) - p; #else /* cygwin */ void (*old)(int) = signal(SIGBREAK, sighandler); do raise(SIGBREAK); while (!p); return (char *)&old - p; #endif /* cygwin */ } sqInt reportStackHeadroom; static int stackPageHeadroom; /* Answer the redzone size plus space for any signal handlers to run in. * N.B. Space for signal handers may include space for the dynamic linker to * run in since signal handlers may reference other functions, and linking may * be lazy. The reportheadroom switch can be used to check empirically that * there is sufficient headroom. */ int osCogStackPageHeadroom() { if (!stackPageHeadroom) stackPageHeadroom = getRedzoneSize() + 1024; return stackPageHeadroom; } #endif /* COGVM */
8f3ce233f21f5ffbcd0493791ea639d119c4be16
a935ec8dab61675b6a3e348511fb9f8c5d490026
/src/feature/spectral_algorithm.h
cde69638b5fbd0b2ad464b1e72cb890af3a95967
[ "MIT" ]
permissive
libAudioFlux/audioFlux
d604c54941c17d90e1ef42f04ba353ef6e244926
3ae59434e2c1cacb6da43562677ed4899d7047c7
refs/heads/master
2023-04-28T05:17:22.649299
2023-04-25T09:45:59
2023-04-25T09:45:59
589,514,195
1,701
85
MIT
2023-04-25T09:00:05
2023-01-16T09:53:04
C
UTF-8
C
false
false
3,694
h
spectral_algorithm.h
#ifndef SPECTRAL_ALGORITHM_H #define SPECTRAL_ALGORITHM_H #ifdef __cplusplus extern "C" { #endif #include <stdio.h> #include <stdlib.h> #include "../flux_base.h" typedef struct OpaqueSpectral *SpectralObj; int spectralObj_new(SpectralObj *spectralObj,int num,float *freBandArr); // 0~num-1 void spectralObj_setEdge(SpectralObj spectralObj,int start,int end); void spectralObj_setEdgeArr(SpectralObj spectralObj,int *indexArr,int indexLength); void spectralObj_setTimeLength(SpectralObj spectralObj,int timeLength); void spectralObj_flatness(SpectralObj spectralObj,float *mDataArr,float *dataArr); // isExp 0;step 1,p 1,type 0 sum 1 mean; void spectralObj_flux(SpectralObj spectralObj,float *mDataArr, int step,float p,int isPostive,int *isExp,int *type, float *dataArr); void spectralObj_rolloff(SpectralObj spectralObj,float *mDataArr,float threshold,float *dataArr); void spectralObj_centroid(SpectralObj spectralObj,float *mDataArr,float *dataArr); void spectralObj_spread(SpectralObj spectralObj,float *mDataArr,float *dataArr); void spectralObj_skewness(SpectralObj spectralObj,float *mDataArr,float *dataArr); void spectralObj_kurtosis(SpectralObj spectralObj,float *mDataArr,float *dataArr); void spectralObj_entropy(SpectralObj spectralObj,float *mDataArr,int isNorm,float *dataArr); void spectralObj_crest(SpectralObj spectralObj,float *mDataArr,float *dataArr); void spectralObj_slope(SpectralObj spectralObj,float *mDataArr,float *dataArr); void spectralObj_decrease(SpectralObj spectralObj,float *mDataArr,float *dataArr); // p 2 !=0 void spectralObj_bandWidth(SpectralObj spectralObj,float *mDataArr,float p,float *dataArr); void spectralObj_rms(SpectralObj spectralObj,float *mDataArr,float *dataArr); // gamma 10 void spectralObj_energy(SpectralObj spectralObj,float *mDataArr,int isLog,float gamma,float *dataArr); void spectralObj_hfc(SpectralObj spectralObj,float *mDataArr,float *dataArr); void spectralObj_sd(SpectralObj spectralObj,float *mDataArr,int step,int isPostive,float *dataArr); void spectralObj_sf(SpectralObj spectralObj,float *mDataArr,int step,int isPostive,float *dataArr); void spectralObj_mkl(SpectralObj spectralObj,float *mDataArr,int type,float *dataArr); void spectralObj_pd(SpectralObj spectralObj,float *mSpecArr,float *mPhaseArr,float *dataArr); void spectralObj_wpd(SpectralObj spectralObj,float *mSpecArr,float *mPhaseArr,float *dataArr); void spectralObj_nwpd(SpectralObj spectralObj,float *mSpecArr,float *mPhaseArr,float *dataArr); void spectralObj_cd(SpectralObj spectralObj,float *mSpecArr,float *mPhaseArr,float *dataArr); void spectralObj_rcd(SpectralObj spectralObj,float *mSpecArr,float *mPhaseArr,float *dataArr); // mag|power threshold >=0 void spectralObj_broadband(SpectralObj spectralObj,float *mDataArr,float threshold,float *dataArr); /*** step >=1 threshold 0 methodType 'sub' dataType 'value' ****/ void spectralObj_novelty(SpectralObj spectralObj,float *mDataArr, int step,float threshold, SpectralNoveltyMethodType *methodType,SpectralNoveltyDataType *dataType, float *dataArr); void spectralObj_eef(SpectralObj spectralObj,float *mDataArr,int isNorm,float *dataArr); // gamma 1/10/20... song 0.5 void spectralObj_eer(SpectralObj spectralObj,float *mDataArr,int isNorm,float gamma,float *dataArr); // statistics void spectralObj_max(SpectralObj spectralObj,float *mDataArr,float *valueArr,float *freArr); void spectralObj_mean(SpectralObj spectralObj,float *mDataArr,float *valueArr,float *freArr); void spectralObj_var(SpectralObj spectralObj,float *mDataArr,float *valueArr,float *freArr); void spectralObj_free(SpectralObj spectralObj); #ifdef __cplusplus } #endif #endif
b196818490fc748863c9e16bd08336a9c96fb3d2
eb9f655206c43c12b497c667ba56a0d358b6bc3a
/plugins/hg4idea/testData/bin/mercurial/cext/revlog.h
9ba65a27b3879a63bfa41fb96d12b996131d2038
[ "Apache-2.0" ]
permissive
JetBrains/intellij-community
2ed226e200ecc17c037dcddd4a006de56cd43941
05dbd4575d01a213f3f4d69aa4968473f2536142
refs/heads/master
2023-09-03T17:06:37.560889
2023-09-03T11:51:00
2023-09-03T12:12:27
2,489,216
16,288
6,635
Apache-2.0
2023-09-12T07:41:58
2011-09-30T13:33:05
null
UTF-8
C
false
false
392
h
revlog.h
/* revlog.h - efficient revlog parsing This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. */ #ifndef _HG_REVLOG_H_ #define _HG_REVLOG_H_ #include <Python.h> extern PyTypeObject HgRevlogIndex_Type; #define HgRevlogIndex_Check(op) PyObject_TypeCheck(op, &HgRevlogIndex_Type) #endif /* _HG_REVLOG_H_ */
4afd320dcc1ec29b87f9f9790442cccaf44b9173
382a4dacbf7d6e6da096ddac660ba7a40af350cf
/src/libraries/GxEPD2/src/bitmaps/WS_Bitmaps3c104x212.h
0e14c5c589f09db87877993edd206cbef7692d0d
[ "GPL-3.0-only", "MIT" ]
permissive
Xinyuan-LilyGO/TTGO_TWatch_Library
84b1a580ad931caac7407bf110fde5b9248be3c4
6a07f3762a4d11c8e5c0c2d6f9340ee4fdaa5fcb
refs/heads/master
2023-08-18T15:36:22.029944
2023-07-03T01:27:29
2023-07-03T01:27:29
202,286,916
776
293
MIT
2023-08-31T05:18:44
2019-08-14T06:17:29
C
UTF-8
C
false
false
29,485
h
WS_Bitmaps3c104x212.h
/** * @filename : imagedata.cpp * @brief : data file for epd demo * * Copyright (C) Waveshare August 22 2017 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documnetation 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 * furished 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 OR 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 _WS_Bitmaps3c104x212_H_ #define _WS_Bitmaps3c104x212_H_ #if defined(ESP8266) || defined(ESP32) #include <pgmspace.h> #else #include <avr/pgmspace.h> #endif const unsigned char WS_Bitmap3c104x212_black[] PROGMEM = { /* 0X00,0X01,0X68,0X00,0XD4,0X00, */ 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XBF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XCF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XFF, 0XC3,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC7,0XFF,0XFF,0XC0,0X3F,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XFF,0XE0,0X0F,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XFF,0XF0,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XE7,0XFF,0XFF,0XF8,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF, 0XFF,0XFC,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XFF,0XFE,0X01, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XFF,0XFF,0X00,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XFF,0XFF,0X80,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XE7,0XFF,0XFF,0XFF,0XC0,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7, 0XFF,0XFF,0XFF,0XC0,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XFF,0XFF, 0XE0,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XFF,0XFF,0XE0,0X7F,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XFF,0XFF,0XE0,0X7F,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XE7,0XFF,0XFF,0XFF,0XF0,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XE7,0XFF,0XFF,0XFF,0XF0,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XFF, 0XFF,0XF0,0X7F,0XDF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XFF,0XFF,0XF0,0X7F, 0XBF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XFF,0XFF,0XF0,0X7E,0X7F,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XFF,0XFF,0XF0,0X7E,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XE7,0XFF,0XFF,0XFF,0XF0,0X7C,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF, 0XFF,0XFF,0XF0,0X7D,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XFC,0X03,0XE0, 0XFD,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XF8,0X00,0XE0,0X79,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XF0,0X00,0X60,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XE7,0XFF,0XE0,0X00,0X30,0XF8,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7, 0XFF,0XC0,0X60,0X11,0X80,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0X00,0X30, 0X19,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFE,0X40,0X20,0X08,0X00,0X00, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XC1,0XC0,0X00,0X08,0X00,0X7F,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XE7,0X80,0XC0,0X20,0X08,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XE7,0X00,0X4C,0X20,0X08,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE6,0X10,0X04, 0X20,0X00,0X1D,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE6,0X10,0X04,0X20,0X40,0X7C, 0XFF,0XF9,0XFF,0XFF,0XFF,0XFF,0XFF,0XE4,0X10,0X00,0X00,0X80,0XFC,0XFF,0XE0,0X7F, 0XFF,0XFF,0XFF,0XFF,0XE4,0X0C,0X00,0X03,0X0F,0XFC,0X7F,0XE4,0X3F,0XFF,0XFF,0XFF, 0XFF,0XE4,0X0E,0X00,0XC0,0X1F,0XFC,0X7F,0XC0,0X1F,0XFF,0XFF,0XFF,0XFF,0XE4,0X0B, 0X83,0XE0,0X0F,0XFC,0X7F,0XC2,0X1F,0XFF,0XFF,0XFF,0XFF,0XE6,0X00,0X07,0XF0,0X0F, 0XFE,0X7F,0XC1,0X0F,0XFF,0XFF,0XFF,0XFF,0XE6,0X00,0X07,0XF0,0X07,0XFE,0X7F,0XC0, 0X8F,0XFF,0XFF,0XFF,0XFF,0XE7,0X00,0X07,0XF0,0X03,0XFE,0X7F,0XE0,0X7F,0XFF,0XFF, 0XFF,0XFF,0XE7,0X80,0X03,0XF3,0X01,0XFE,0X7F,0XE0,0X1F,0XFF,0XFF,0XFF,0XFF,0XE7, 0XC0,0X03,0XE3,0X80,0XFE,0X7F,0XF0,0X1F,0XFF,0XFF,0XFF,0XFF,0XE7,0XF8,0X00,0XC0, 0XE0,0XFC,0X7F,0XF0,0X87,0XFF,0XFF,0XFF,0XFF,0XE7,0XF7,0X00,0X00,0X3C,0XFC,0X7F, 0XF0,0X83,0XFF,0XFF,0XFF,0XFF,0XE7,0XF9,0X80,0X00,0X18,0XFC,0XFF,0XF0,0X81,0XFF, 0XFF,0XFF,0XFF,0XE7,0X9D,0X80,0X04,0X00,0XFC,0XFF,0XF1,0XC1,0XFF,0XFF,0XFF,0XFF, 0XE6,0X35,0X01,0X04,0X00,0XFD,0XFF,0XF3,0X71,0XFF,0XFF,0XFF,0XFF,0XE6,0X62,0X02, 0X00,0X00,0XFD,0XFF,0XE2,0X01,0XFF,0XFF,0XFF,0XFF,0XE4,0XC2,0X02,0X00,0X00,0XFB, 0XFF,0XE2,0X01,0XFF,0XFF,0XFF,0XFF,0XE5,0X82,0X02,0X00,0X01,0XF3,0XFF,0XE0,0X01, 0XFF,0XFF,0XFF,0XFF,0XE3,0X01,0X0E,0X00,0X03,0XF3,0XFF,0XE4,0X01,0XFF,0XFF,0XFF, 0XFF,0XE6,0X01,0X83,0X00,0X7F,0XE7,0XFF,0XC0,0X00,0XFF,0XFF,0XFF,0XFF,0XE4,0X01, 0X81,0X00,0XFF,0XCF,0XFF,0XE0,0X00,0X3F,0XFF,0XFF,0XFF,0XE0,0X01,0X80,0X00,0XFF, 0X8F,0XFF,0XE0,0X00,0X1F,0XFF,0XFF,0XFF,0XE0,0X03,0XC0,0X01,0XFF,0X9F,0XFF,0XE0, 0X01,0X1F,0XFF,0XFF,0XFF,0XE0,0X0F,0XF8,0X01,0XFF,0XDF,0XFF,0XFC,0X16,0X1F,0XFF, 0XFF,0XFF,0XE0,0X1F,0XF0,0XC7,0XF8,0X3F,0XFF,0XF6,0X1F,0X1F,0XFF,0XFF,0XFF,0XE0, 0X3F,0XC0,0X6F,0XF0,0X1F,0XFF,0XE2,0X01,0X1F,0XFF,0XFF,0XFF,0XE0,0X7F,0XC0,0X3F, 0XC0,0X0F,0XFF,0XCC,0X00,0X9F,0XFF,0XFF,0XFF,0XE0,0XFF,0XC0,0X1F,0XC0,0X0F,0XFF, 0XDE,0X00,0X19,0XFF,0XFF,0XFF,0XE0,0XFF,0X80,0X0F,0X80,0X0F,0XFF,0X9F,0X00,0X00, 0XFF,0XFF,0XFF,0XE1,0XFF,0X80,0X40,0X00,0X07,0XFF,0X9F,0XFE,0X00,0XFF,0XFF,0XFF, 0XF3,0XFF,0X80,0XC0,0X00,0X07,0XFF,0XBF,0XFF,0X00,0X7F,0XFF,0XFF,0XE7,0XFF,0XC0, 0X80,0X00,0X07,0XFF,0XBF,0XFF,0X90,0X7F,0XFF,0XFF,0XE7,0XFF,0XC7,0X80,0X00,0X0F, 0XFF,0XBF,0XFF,0XD8,0X7F,0XFF,0XFF,0XE7,0XFF,0XE0,0XC0,0X00,0X3F,0XFF,0X3F,0XFF, 0XE0,0X7F,0XFF,0XFF,0XE7,0XFF,0XE0,0XC0,0X00,0X1F,0XFF,0X3F,0XFF,0XF0,0XFF,0XFF, 0XFF,0XE7,0XFF,0XF0,0X20,0X80,0X07,0XFF,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF, 0XE0,0X30,0X00,0X03,0XFF,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFF,0XC0,0X30,0X40, 0X03,0XFF,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XFC,0X40,0X10,0X60,0X03,0XFF,0X7F, 0XFF,0XFF,0XFF,0XFF,0XFF,0XE7,0XE0,0XC0,0X18,0X3C,0X07,0XFE,0X7F,0XFF,0XFF,0XFF, 0XFF,0XFF,0XE7,0X87,0XC0,0X08,0X18,0X0F,0XFC,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7, 0X0F,0XE0,0X08,0X10,0X1F,0XFC,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF6,0X7F,0XFE,0X0C, 0X10,0X43,0XF9,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0XFF,0XF1,0X04,0X10,0X81,0XF3, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF1,0XFF,0XE1,0X04,0X11,0X81,0XE3,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XF3,0XFF,0XC0,0X06,0X11,0X80,0X4F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XF3,0XFF,0XC0,0X02,0X10,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0XFF,0XC0, 0X22,0X10,0X08,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0XFF,0XC0,0X3A,0X30,0X0C, 0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0XFF,0XC2,0X18,0X00,0X0C,0X7F,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XF7,0XFF,0XC3,0X10,0X00,0X1C,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XF7,0XFF,0XC1,0X80,0X00,0X60,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0XFF, 0X80,0XC0,0X00,0XC0,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0XFF,0X80,0XC0,0X01, 0X80,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0XF0,0X00,0X30,0X00,0X00,0X1F,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0X03,0XE0,0X00,0XE0,0X00,0X1F,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XF6,0X0F,0XF0,0X01,0XF0,0X02,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0, 0XFF,0XF8,0X03,0XF8,0X3C,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF1,0XE0,0X04,0X07, 0XF8,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF3,0X80,0X02,0X07,0XF8,0X00,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF6,0X0F,0XFE,0X07,0XF8,0X01,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XF0,0X7F,0XFC,0X03,0XF8,0X03,0XBF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XF1,0XE0,0X10,0X21,0XF0,0X03,0X27,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF3,0X07,0XC0, 0XC0,0X60,0X81,0X91,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X3F,0XC1,0X00,0X00,0XC1, 0XD8,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X7F,0X87,0X04,0X00,0X60,0X4C,0X3F,0XFF, 0XFF,0XFF,0XFF,0XFF,0XF3,0XFF,0X86,0X0C,0X00,0X20,0X4F,0X3F,0XFF,0XFF,0XFF,0XFF, 0XFF,0XF7,0XFF,0X80,0X18,0X08,0X10,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0XFF, 0XC0,0X18,0X08,0X08,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0XFF,0XC0,0X10,0X4C, 0X0F,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0X00,0X40,0X00,0X44,0X0C,0X3F,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00,0X00,0X0C,0X46,0X0C,0X3F,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XF0,0X00,0X30,0X1C,0XC6,0X0C,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF1, 0XFF,0XF8,0XF8,0XC6,0X0C,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00,0X1C,0X00, 0XC6,0X0C,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00,0X0C,0X00,0XC3,0X00,0X3F, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF3,0X80,0X18,0X00,0XC3,0X00,0X3F,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XF7,0XFF,0X70,0X00,0XC1,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XF7,0XFF,0XE0,0X00,0XC3,0X80,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF3,0XFF,0XC0, 0X00,0XC7,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF1,0XFF,0X80,0X00,0XC6,0X07, 0X9F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X7F,0XC0,0X08,0XC4,0X03,0X0F,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XF0,0X0F,0XC0,0X18,0XC0,0X03,0X47,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XF3,0X83,0X80,0X20,0XC0,0X02,0X39,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0XE0, 0XC0,0X00,0XC0,0X02,0X0C,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X1C,0X40,0X43,0X70, 0XFC,0X03,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X0F,0X20,0XC2,0X31,0XEC,0X03,0X8F, 0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X03,0X9F,0XC4,0X03,0XFF,0X00,0XC7,0XFF,0XFF,0XFF, 0XFF,0XFF,0XF0,0X00,0X6F,0XE0,0X07,0X3F,0X80,0X63,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7, 0X00,0X31,0XE0,0X04,0XFF,0XC0,0X31,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0XE0,0X18,0XF0, 0X01,0XFF,0XF0,0X1C,0XFF,0XFF,0XFF,0XFF,0XFF,0XF7,0XF8,0X0E,0X30,0X0B,0XFF,0XF0, 0X0C,0X7F,0XFF,0XFF,0XFF,0XFF,0XF7,0XFC,0X07,0X18,0X1F,0XFF,0XFC,0X0F,0X3F,0XFF, 0XFF,0XFF,0XFF,0XF3,0XFE,0X07,0X1C,0X3F,0XFF,0XFE,0X07,0X9F,0XFF,0XFF,0XFF,0XFF, 0XF3,0XFF,0X83,0XCF,0XFF,0XFF,0XFF,0X03,0X8F,0XFF,0XFF,0XFF,0XFF,0XF3,0XFF,0XC3, 0XE7,0XFF,0XFF,0XFF,0X83,0XE7,0XFF,0XFF,0XFF,0XFF,0XF3,0XFF,0XC1,0XF7,0XFF,0XFF, 0XFF,0X81,0XE3,0XFF,0XFF,0XFF,0XFF,0XF3,0XFF,0XE1,0XF3,0XFF,0XFF,0XFF,0XC1,0XF1, 0XFF,0XFF,0XFF,0XFF,0XF3,0XFF,0XE0,0XFB,0XFF,0XFF,0XFF,0XE0,0XF9,0XFF,0XFF,0XFF, 0XFF,0XF3,0XFF,0XF0,0XF9,0XFF,0XFF,0XFF,0XF0,0XFC,0XFF,0XFF,0XFF,0XFF,0XF3,0XFF, 0XF8,0XFD,0XFF,0XFF,0XFF,0XF8,0XFE,0XFF,0XFF,0XFF,0XFF,0XF3,0XFF,0XF8,0X7C,0XFF, 0XFF,0XFF,0XFC,0X7F,0X7F,0XFF,0XFF,0XFF,0XF3,0XFF,0XFC,0X7C,0X7F,0XFF,0XFF,0XFE, 0X7F,0X3F,0XFF,0XFF,0XFF,0XF3,0XFF,0XFC,0X3E,0X7F,0XFF,0XFF,0XFF,0X7F,0XBF,0XFF, 0XFF,0XFF,0XF3,0XFF,0XFE,0X3E,0X3F,0XFF,0XFF,0XFF,0XFF,0XDF,0XFF,0XFF,0XFF,0XF3, 0XFF,0XFE,0X3F,0X3F,0XFF,0XFF,0XFF,0XFF,0XCF,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0X3F, 0X3F,0XF0,0XFF,0XFF,0XFF,0XEF,0XFF,0XFF,0XFF,0XF3,0XFF,0XFE,0X3F,0XBF,0XF0,0X03, 0XFF,0XFF,0XC7,0XFF,0XFF,0XFF,0XF3,0XFF,0XFE,0X3F,0XBF,0XE0,0X01,0XFF,0XFF,0XE7, 0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0X3F,0X9F,0XE0,0X00,0XFF,0XFF,0XE7,0XFF,0XFF,0XFF, 0XF3,0XFF,0XFF,0X3F,0XDF,0XF0,0X00,0X7F,0XFF,0XF3,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF, 0X3F,0XDF,0XFB,0X00,0X7F,0XFF,0XF3,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0X3F,0XDF,0XF0, 0X00,0X7F,0XFF,0XFB,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0X7F,0XDF,0XC0,0X10,0X3F,0XFF, 0XFB,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0XFF,0XDF,0XC0,0X10,0X3F,0XFF,0XFB,0XFF,0XFF, 0XFF,0XF3,0XFF,0XFF,0XFF,0XDF,0XC0,0X10,0X1F,0XFF,0XFB,0XFF,0XFF,0XFF,0XF3,0XFF, 0XFF,0XFF,0XDF,0XC1,0XF8,0X1F,0XFF,0XFB,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0XFF,0XDF, 0XC0,0X0C,0X0F,0XFF,0XFB,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0XFF,0XDF,0XE0,0X06,0X03, 0XFF,0XF3,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0XFF,0XDF,0XE0,0X03,0X00,0X1F,0XF3,0XFF, 0XFF,0XFF,0XF3,0XFF,0XFF,0XFF,0XDF,0XF8,0X01,0XC0,0X03,0XE7,0XFF,0XFF,0XFF,0XF3, 0XFF,0XFF,0XFF,0XDF,0XFC,0X00,0X7F,0X01,0XE7,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0XFF, 0XDF,0XFC,0X00,0X3F,0XC0,0XC7,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0XFF,0XDF,0XFC,0X00, 0X00,0X00,0XEF,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0XFF,0XDF,0XFC,0X00,0X00,0X00,0XDF, 0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0XFF,0XDF,0XFC,0X00,0X00,0X00,0XDF,0XFF,0XFF,0XFF, 0XF3,0XFF,0XFF,0XFF,0X9F,0XFE,0X00,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF, 0XFF,0X1F,0XFF,0X80,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0XFE,0X1F,0XFF, 0XE0,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0XFC,0X1F,0XFF,0XF0,0X00,0X00, 0X1F,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0XFF,0X9F,0XFF,0XF0,0X00,0X18,0X1F,0XFF,0XFF, 0XFF,0XF3,0XFF,0XFF,0XFF,0XDF,0XFF,0XF0,0X00,0X30,0X1F,0XFF,0XFF,0XFF,0XF3,0XFF, 0XFF,0XFF,0XDF,0XFF,0XF1,0X83,0XC0,0X3F,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0XFE,0XCF, 0XFF,0XE0,0XFF,0X01,0X3F,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0X84,0XCF,0XFF,0X00,0X70, 0X01,0X1F,0XFF,0XFF,0XFF,0XF3,0XFF,0XFF,0X06,0X67,0XFE,0X00,0X40,0X02,0X3F,0XFF, 0XFF,0XFF,0XF3,0XFF,0XFE,0X07,0XE7,0XFE,0X00,0X40,0X06,0X3F,0XFF,0XFF,0XFF,0XFB, 0XFF,0XFC,0X03,0XE1,0XFE,0X00,0X40,0X06,0X7F,0XFF,0XFF,0XFF,0XFB,0XFF,0XFC,0X04, 0X60,0XFF,0X00,0X40,0X0C,0XFF,0XFF,0XFF,0XFF,0XFB,0XFF,0XFE,0X18,0X30,0X7F,0X80, 0X00,0X18,0XFF,0XFF,0XFF,0XFF,0XFB,0XFF,0XE0,0X38,0X36,0X3F,0XC0,0X00,0X19,0XFF, 0XFF,0XFF,0XFF,0XFB,0XFF,0XC0,0X20,0X33,0X1F,0XF0,0X00,0X31,0XFF,0XFF,0XFF,0XFF, 0XFB,0XFF,0XC0,0XC8,0X11,0X8F,0XF8,0X00,0X63,0XFF,0XFF,0XFF,0XFF,0XFB,0XFF,0X80, 0XC0,0X39,0X8F,0XFC,0X00,0X63,0XFF,0XFF,0XFF,0XFF,0XFB,0XFF,0XF9,0X80,0X48,0XC7, 0XFC,0X00,0X43,0XFF,0XFF,0XFF,0XFF,0XFB,0XFF,0XBF,0X06,0XC4,0X07,0XFC,0X00,0XC3, 0XFF,0XFF,0XFF,0XFF,0XFB,0XFE,0X03,0X07,0X86,0X07,0XFC,0X0C,0X83,0XFF,0XFF,0XFF, 0XFF,0XFB,0XFE,0X01,0X07,0X86,0X07,0XFC,0X1E,0X83,0XFF,0XFF,0XFF,0XFF,0XFB,0XFC, 0X05,0X07,0X93,0X07,0XFC,0X1D,0X81,0XFF,0XFF,0XFF,0XFF,0XFB,0XFC,0X08,0X0F,0XB1, 0X03,0XFE,0X23,0XE1,0XFF,0XFF,0XFF,0XFF,0XFB,0XFF,0XF8,0XFF,0X99,0X23,0XFF,0XE7, 0X30,0XFF,0XFF,0XFF,0XFF,0XFB,0XFE,0X00,0XFF,0XC0,0X91,0XFF,0X80,0X10,0X7F,0XFF, 0XFF,0XFF,0XFB,0XFC,0X00,0XFF,0XE0,0X98,0XFF,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF, 0XFC,0X00,0XFF,0XE0,0X8C,0X7F,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFC,0X21,0XFF, 0XF8,0X80,0X7F,0X00,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFC,0X71,0XFF,0XFC,0X80,0X7F, 0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X40,0X3F,0X80,0X00,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X3F,0X80,0X01,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X3F,0XE0,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XC0,0X7F,0XFC,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0, 0X3F,0XFC,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X3F,0XFC,0X01, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X03,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X9F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF, }; const unsigned char WS_Bitmap3c104x212_red[] PROGMEM = { /* 0X00,0X01,0X68,0X00,0XD4,0X00, */ 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X7F, 0XFE,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF8,0X3F,0XFC,0X3F,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X1F,0XF0,0X3F,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X0F,0XC0,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0X80,0X47,0X80,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80, 0X02,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X83,0X86,0X78,0X3F, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X82,0X0C,0XE0,0X0F,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X0C,0X80,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0X80,0X05,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XC6,0X04,0X00,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X04,0X00, 0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X04,0X60,0X01,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X06,0X60,0X01,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFC,0X0E,0X00,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XE2,0X20,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00, 0X10,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X80,0X00,0X07,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X80,0X18,0X07,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00,0X80,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XF0,0XC0,0X80,0X3C,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0, 0XC0,0X7F,0XF0,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X60,0X40,0X00, 0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X38,0X20,0X00,0X0F,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X1C,0X18,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFC,0X03,0X0C,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0X06,0X03,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC,0X01, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0XC9,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0XCF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X47,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XE0,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0, 0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X07,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF9,0XCF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XEF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X3F, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X3F,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFE,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00, 0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0X07,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X4E,0X07,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X01,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFE,0X01,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE, 0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X00,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X03,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFE,0X1C,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFE,0X68,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XF0,0XC4,0X00,0X7F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF1,0X06,0X00, 0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE1,0X03,0X00,0X3F,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE2,0X01,0X80,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XC1,0XC0,0X80,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XC0,0X70,0XC0,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X38, 0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X0C,0X01,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X1F,0XFF,0X8F,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0X80,0X70,0X00,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0X81,0X00,0X00,0X1F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC1, 0X00,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X0F,0XC0,0X7F, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X0F,0XC0,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XF0,0X00,0X3F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFA,0X07,0X0F,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFE,0X07,0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X08,0X03, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0X00,0X03,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XC0,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XE0,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XF8,0X01,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFC, 0X07,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF, }; #endif
e9334b4ad776ab06abf328cf2e7d5d4a6717ca0b
cc634f8e37d1a7fdc5649cec719ed434b88385ec
/libpkgconf/dependency.c
da92c3ab66e69f720425d92c75935d1b48211ec1
[ "LicenseRef-scancode-mit-taylor-variant" ]
permissive
pkgconf/pkgconf
86af3a2533d0f44f12b42b88c4f7425916ff5951
6a84d70439f03815080a3805fb10c81ffc8eece8
refs/heads/master
2023-08-16T07:29:54.561561
2023-08-11T21:23:08
2023-08-11T21:23:08
4,180,110
349
96
NOASSERTION
2023-09-13T17:50:50
2012-04-30T05:28:36
C
UTF-8
C
false
false
14,307
c
dependency.c
/* * dependency.c * dependency parsing and management * * Copyright (c) 2011, 2012, 2013 pkgconf authors (see AUTHORS). * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * This software is provided 'as is' and without any warranty, express or * implied. In no event shall the authors be liable for any damages arising * from the use of this software. */ #include <libpkgconf/stdinc.h> #include <libpkgconf/libpkgconf.h> /* * !doc * * libpkgconf `dependency` module * ============================== * * The `dependency` module provides support for building `dependency lists` (the basic component of the overall `dependency graph`) and * `dependency nodes` which store dependency information. */ typedef enum { OUTSIDE_MODULE = 0, INSIDE_MODULE_NAME = 1, BEFORE_OPERATOR = 2, INSIDE_OPERATOR = 3, AFTER_OPERATOR = 4, INSIDE_VERSION = 5 } parse_state_t; #define DEBUG_PARSE 0 static const char * dependency_to_str(const pkgconf_dependency_t *dep, char *buf, size_t buflen) { pkgconf_strlcpy(buf, dep->package, buflen); if (dep->version != NULL) { pkgconf_strlcat(buf, " ", buflen); pkgconf_strlcat(buf, pkgconf_pkg_get_comparator(dep), buflen); pkgconf_strlcat(buf, " ", buflen); pkgconf_strlcat(buf, dep->version, buflen); } return buf; } /* find a colliding dependency that is coloured differently */ static inline pkgconf_dependency_t * find_colliding_dependency(const pkgconf_dependency_t *dep, const pkgconf_list_t *list) { const pkgconf_node_t *n; PKGCONF_FOREACH_LIST_ENTRY(list->head, n) { pkgconf_dependency_t *dep2 = n->data; if (strcmp(dep->package, dep2->package)) continue; if (dep->flags != dep2->flags) return dep2; } return NULL; } static inline pkgconf_dependency_t * add_or_replace_dependency_node(pkgconf_client_t *client, pkgconf_dependency_t *dep, pkgconf_list_t *list) { char depbuf[PKGCONF_ITEM_SIZE]; pkgconf_dependency_t *dep2 = find_colliding_dependency(dep, list); /* there is already a node in the graph which describes this dependency */ if (dep2 != NULL) { char depbuf2[PKGCONF_ITEM_SIZE]; PKGCONF_TRACE(client, "dependency collision: [%s/%x] -- [%s/%x]", dependency_to_str(dep, depbuf, sizeof depbuf), dep->flags, dependency_to_str(dep2, depbuf2, sizeof depbuf2), dep2->flags); /* prefer the uncoloured node, either dep or dep2 */ if (dep->flags && dep2->flags == 0) { PKGCONF_TRACE(client, "dropping dependency [%s]@%p because of collision", depbuf, dep); pkgconf_dependency_unref(dep->owner, dep); return NULL; } else if (dep2->flags && dep->flags == 0) { PKGCONF_TRACE(client, "dropping dependency [%s]@%p because of collision", depbuf2, dep2); pkgconf_node_delete(&dep2->iter, list); pkgconf_dependency_unref(dep2->owner, dep2); } else /* If both dependencies have equal strength, we keep both, because of situations like: * Requires: foo > 1, foo < 3 * * If the situation is that both dependencies are literally equal, it is still harmless because * fragment deduplication will handle the excessive fragments. */ PKGCONF_TRACE(client, "keeping both dependencies (harmless)"); } PKGCONF_TRACE(client, "added dependency [%s] to list @%p; flags=%x", dependency_to_str(dep, depbuf, sizeof depbuf), list, dep->flags); pkgconf_node_insert_tail(&dep->iter, pkgconf_dependency_ref(dep->owner, dep), list); /* This dependency is intentionally unowned. * * Internally we have no use for the returned type, and usually just * discard it. However, there is a publig pkgconf_dependency_add * function, which references this return value before returning it, * giving ownership at that point. */ return dep; } static inline pkgconf_dependency_t * pkgconf_dependency_addraw(pkgconf_client_t *client, pkgconf_list_t *list, const char *package, size_t package_sz, const char *version, size_t version_sz, pkgconf_pkg_comparator_t compare, unsigned int flags) { pkgconf_dependency_t *dep; dep = calloc(sizeof(pkgconf_dependency_t), 1); dep->package = pkgconf_strndup(package, package_sz); if (version_sz != 0) dep->version = pkgconf_strndup(version, version_sz); dep->compare = compare; dep->flags = flags; dep->owner = client; dep->refcount = 0; return add_or_replace_dependency_node(client, dep, list); } /* * !doc * * .. c:function:: pkgconf_dependency_t *pkgconf_dependency_add(pkgconf_list_t *list, const char *package, const char *version, pkgconf_pkg_comparator_t compare) * * Adds a parsed dependency to a dependency list as a dependency node. * * :param pkgconf_client_t* client: The client object that owns the package this dependency list belongs to. * :param pkgconf_list_t* list: The dependency list to add a dependency node to. * :param char* package: The package `atom` to set on the dependency node. * :param char* version: The package `version` to set on the dependency node. * :param pkgconf_pkg_comparator_t compare: The comparison operator to set on the dependency node. * :param uint flags: Any flags to attach to the dependency node. * :return: A dependency node. * :rtype: pkgconf_dependency_t * */ pkgconf_dependency_t * pkgconf_dependency_add(pkgconf_client_t *client, pkgconf_list_t *list, const char *package, const char *version, pkgconf_pkg_comparator_t compare, unsigned int flags) { pkgconf_dependency_t *dep; dep = pkgconf_dependency_addraw(client, list, package, strlen(package), version, version != NULL ? strlen(version) : 0, compare, flags); return pkgconf_dependency_ref(dep->owner, dep); } /* * !doc * * .. c:function:: void pkgconf_dependency_append(pkgconf_list_t *list, pkgconf_dependency_t *tail) * * Adds a dependency node to a pre-existing dependency list. * * :param pkgconf_list_t* list: The dependency list to add a dependency node to. * :param pkgconf_dependency_t* tail: The dependency node to add to the tail of the dependency list. * :return: nothing */ void pkgconf_dependency_append(pkgconf_list_t *list, pkgconf_dependency_t *tail) { pkgconf_node_insert_tail(&tail->iter, tail, list); } /* * !doc * * .. c:function:: void pkgconf_dependency_free_one(pkgconf_dependency_t *dep) * * Frees a dependency node. * * :param pkgconf_dependency_t* dep: The dependency node to free. * :return: nothing */ void pkgconf_dependency_free_one(pkgconf_dependency_t *dep) { if (dep->match != NULL) pkgconf_pkg_unref(dep->match->owner, dep->match); if (dep->package != NULL) free(dep->package); if (dep->version != NULL) free(dep->version); free(dep); } /* * !doc * * .. c:function:: pkgconf_dependency_t *pkgconf_dependency_ref(pkgconf_client_t *owner, pkgconf_dependency_t *dep) * * Increases a dependency node's refcount. * * :param pkgconf_client_t* owner: The client object which owns the memory of this dependency node. * :param pkgconf_dependency_t* dep: The dependency to increase the refcount of. * :return: the dependency node on success, else NULL */ pkgconf_dependency_t * pkgconf_dependency_ref(pkgconf_client_t *client, pkgconf_dependency_t *dep) { if (client != dep->owner) return NULL; dep->refcount++; PKGCONF_TRACE(client, "%s refcount@%p: %d", dep->package, dep, dep->refcount); return dep; } /* * !doc * * .. c:function:: void pkgconf_dependency_unref(pkgconf_client_t *owner, pkgconf_dependency_t *dep) * * Decreases a dependency node's refcount and frees it if necessary. * * :param pkgconf_client_t* owner: The client object which owns the memory of this dependency node. * :param pkgconf_dependency_t* dep: The dependency to decrease the refcount of. * :return: nothing */ void pkgconf_dependency_unref(pkgconf_client_t *client, pkgconf_dependency_t *dep) { if (client != dep->owner) return; --dep->refcount; PKGCONF_TRACE(client, "%s refcount@%p: %d", dep->package, dep, dep->refcount); if (dep->refcount <= 0) pkgconf_dependency_free_one(dep); } /* * !doc * * .. c:function:: void pkgconf_dependency_free(pkgconf_list_t *list) * * Release a dependency list and it's child dependency nodes. * * :param pkgconf_list_t* list: The dependency list to release. * :return: nothing */ void pkgconf_dependency_free(pkgconf_list_t *list) { pkgconf_node_t *node, *next; PKGCONF_FOREACH_LIST_ENTRY_SAFE(list->head, next, node) { pkgconf_dependency_t *dep = node->data; pkgconf_node_delete(&dep->iter, list); pkgconf_dependency_unref(dep->owner, dep); } pkgconf_list_zero(list); } /* * !doc * * .. c:function:: void pkgconf_dependency_parse_str(pkgconf_list_t *deplist_head, const char *depends) * * Parse a dependency declaration into a dependency list. * Commas are counted as whitespace to allow for constructs such as ``@SUBSTVAR@, zlib`` being processed * into ``, zlib``. * * :param pkgconf_client_t* client: The client object that owns the package this dependency list belongs to. * :param pkgconf_list_t* deplist_head: The dependency list to populate with dependency nodes. * :param char* depends: The dependency data to parse. * :param uint flags: Any flags to attach to the dependency nodes. * :return: nothing */ void pkgconf_dependency_parse_str(pkgconf_client_t *client, pkgconf_list_t *deplist_head, const char *depends, unsigned int flags) { parse_state_t state = OUTSIDE_MODULE; pkgconf_pkg_comparator_t compare = PKGCONF_CMP_ANY; char cmpname[PKGCONF_ITEM_SIZE]; char buf[PKGCONF_BUFSIZE]; size_t package_sz = 0, version_sz = 0; char *start = buf; char *ptr = buf; char *vstart = NULL; char *package = NULL, *version = NULL; char *cnameptr = cmpname; char *cnameend = cmpname + PKGCONF_ITEM_SIZE - 1; memset(cmpname, '\0', sizeof cmpname); pkgconf_strlcpy(buf, depends, sizeof buf); pkgconf_strlcat(buf, " ", sizeof buf); while (*ptr) { switch (state) { case OUTSIDE_MODULE: if (!PKGCONF_IS_MODULE_SEPARATOR(*ptr)) state = INSIDE_MODULE_NAME; break; case INSIDE_MODULE_NAME: if (isspace((unsigned char)*ptr)) { const char *sptr = ptr; while (*sptr && isspace((unsigned char)*sptr)) sptr++; if (*sptr == '\0') state = OUTSIDE_MODULE; else if (PKGCONF_IS_MODULE_SEPARATOR(*sptr)) state = OUTSIDE_MODULE; else if (PKGCONF_IS_OPERATOR_CHAR(*sptr)) state = BEFORE_OPERATOR; else state = OUTSIDE_MODULE; } else if (PKGCONF_IS_MODULE_SEPARATOR(*ptr)) state = OUTSIDE_MODULE; else if (*(ptr + 1) == '\0') { ptr++; state = OUTSIDE_MODULE; } if (state != INSIDE_MODULE_NAME && start != ptr) { char *iter = start; while (PKGCONF_IS_MODULE_SEPARATOR(*iter)) iter++; package = iter; package_sz = ptr - iter; start = ptr; } if (state == OUTSIDE_MODULE) { pkgconf_dependency_addraw(client, deplist_head, package, package_sz, NULL, 0, compare, flags); compare = PKGCONF_CMP_ANY; package_sz = 0; } break; case BEFORE_OPERATOR: if (PKGCONF_IS_OPERATOR_CHAR(*ptr)) { state = INSIDE_OPERATOR; if (cnameptr < cnameend) *cnameptr++ = *ptr; } break; case INSIDE_OPERATOR: if (!PKGCONF_IS_OPERATOR_CHAR(*ptr)) { state = AFTER_OPERATOR; compare = pkgconf_pkg_comparator_lookup_by_name(cmpname); } else if (cnameptr < cnameend) *cnameptr++ = *ptr; break; case AFTER_OPERATOR: if (!isspace((unsigned char)*ptr)) { vstart = ptr; state = INSIDE_VERSION; } break; case INSIDE_VERSION: if (PKGCONF_IS_MODULE_SEPARATOR(*ptr) || *(ptr + 1) == '\0') { version = vstart; version_sz = ptr - vstart; state = OUTSIDE_MODULE; pkgconf_dependency_addraw(client, deplist_head, package, package_sz, version, version_sz, compare, flags); compare = PKGCONF_CMP_ANY; cnameptr = cmpname; memset(cmpname, 0, sizeof cmpname); package_sz = 0; } if (state == OUTSIDE_MODULE) start = ptr; break; } ptr++; } } /* * !doc * * .. c:function:: void pkgconf_dependency_parse(const pkgconf_client_t *client, pkgconf_pkg_t *pkg, pkgconf_list_t *deplist, const char *depends) * * Preprocess dependency data and then process that dependency declaration into a dependency list. * Commas are counted as whitespace to allow for constructs such as ``@SUBSTVAR@, zlib`` being processed * into ``, zlib``. * * :param pkgconf_client_t* client: The client object that owns the package this dependency list belongs to. * :param pkgconf_pkg_t* pkg: The package object that owns this dependency list. * :param pkgconf_list_t* deplist: The dependency list to populate with dependency nodes. * :param char* depends: The dependency data to parse. * :param uint flags: Any flags to attach to the dependency nodes. * :return: nothing */ void pkgconf_dependency_parse(pkgconf_client_t *client, pkgconf_pkg_t *pkg, pkgconf_list_t *deplist, const char *depends, unsigned int flags) { char *kvdepends = pkgconf_tuple_parse(client, &pkg->vars, depends, pkg->flags); pkgconf_dependency_parse_str(client, deplist, kvdepends, flags); free(kvdepends); } /* * !doc * * .. c:function:: pkgconf_dependency_t *pkgconf_dependency_copy(pkgconf_client_t *client, const pkgconf_dependency_t *dep) * * Copies a dependency node to a new one. * * :param pkgconf_client_t* client: The client object that will own this dependency. * :param pkgconf_dependency_t* dep: The dependency node to copy. * :return: a pointer to a new dependency node, else NULL */ pkgconf_dependency_t * pkgconf_dependency_copy(pkgconf_client_t *client, const pkgconf_dependency_t *dep) { pkgconf_dependency_t *new_dep; new_dep = calloc(sizeof(pkgconf_dependency_t), 1); new_dep->package = strdup(dep->package); if (dep->version != NULL) new_dep->version = strdup(dep->version); new_dep->compare = dep->compare; new_dep->flags = dep->flags; new_dep->owner = client; new_dep->refcount = 0; if (dep->match != NULL) new_dep->match = pkgconf_pkg_ref(client, dep->match); return pkgconf_dependency_ref(client, new_dep); }
1644b927a775d1afb797c07b4547bc3c5ad6bde7
f7dc806f341ef5dbb0e11252a4693003a66853d5
/thirdparty/harfbuzz/src/hb-cairo.h
21e284c8f93a68a1e979d466d9f92778e008569f
[ "MIT", "OFL-1.1", "JSON", "LicenseRef-scancode-nvidia-2002", "BSD-3-Clause", "Zlib", "MPL-2.0", "CC0-1.0", "BSL-1.0", "Libpng", "Apache-2.0", "LicenseRef-scancode-public-domain", "Unlicense", "LicenseRef-scancode-free-unknown", "CC-BY-4.0", "Bison-exception-2.2", "LicenseRef-scancode-other-permissive", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-unicode", "BSD-2-Clause", "FTL", "GPL-3.0-or-later", "Bitstream-Vera", "MIT-Modern-Variant" ]
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
3,097
h
hb-cairo.h
/* * Copyright © 2022 Red Hat, Inc. * * This is part of HarfBuzz, a text shaping library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Red Hat Author(s): Matthias Clasen */ #ifndef HB_CAIRO_H #define HB_CAIRO_H #include "hb.h" #include <cairo.h> HB_BEGIN_DECLS HB_EXTERN cairo_font_face_t * hb_cairo_font_face_create_for_font (hb_font_t *font); HB_EXTERN hb_font_t * hb_cairo_font_face_get_font (cairo_font_face_t *font_face); HB_EXTERN cairo_font_face_t * hb_cairo_font_face_create_for_face (hb_face_t *face); HB_EXTERN hb_face_t * hb_cairo_font_face_get_face (cairo_font_face_t *font_face); /** * hb_cairo_font_init_func_t: * @font: The #hb_font_t being created * @scaled_font: The respective #cairo_scaled_font_t * @user_data: User data accompanying this method * * The type of a virtual method to be called when a cairo * face created using hb_cairo_font_face_create_for_face() * creates an #hb_font_t for a #cairo_scaled_font_t. * * Return value: the #hb_font_t value to use; in most cases same as @font * * Since: 7.0.0 */ typedef hb_font_t * (*hb_cairo_font_init_func_t) (hb_font_t *font, cairo_scaled_font_t *scaled_font, void *user_data); HB_EXTERN void hb_cairo_font_face_set_font_init_func (cairo_font_face_t *font_face, hb_cairo_font_init_func_t func, void *user_data, hb_destroy_func_t destroy); HB_EXTERN hb_font_t * hb_cairo_scaled_font_get_font (cairo_scaled_font_t *scaled_font); HB_EXTERN void hb_cairo_font_face_set_scale_factor (cairo_font_face_t *font_face, unsigned int scale_factor); HB_EXTERN unsigned int hb_cairo_font_face_get_scale_factor (cairo_font_face_t *font_face); HB_EXTERN void hb_cairo_glyphs_from_buffer (hb_buffer_t *buffer, hb_bool_t utf8_clusters, double x_scale_factor, double y_scale_factor, double x, double y, const char *utf8, int utf8_len, cairo_glyph_t **glyphs, unsigned int *num_glyphs, cairo_text_cluster_t **clusters, unsigned int *num_clusters, cairo_text_cluster_flags_t *cluster_flags); HB_END_DECLS #endif /* HB_CAIRO_H */
941fff5dae3213d95860688ec42fb71bccea3a6b
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
/PWGCF/FLOW/macros/runFlowAnalysisOnTheFly.C
7d21f2ebd538cb464be9f940dd0a48caa9d45b7a
[]
permissive
alisw/AliPhysics
91bf1bd01ab2af656a25ff10b25e618a63667d3e
5df28b2b415e78e81273b0d9bf5c1b99feda3348
refs/heads/master
2023-08-31T20:41:44.927176
2023-08-31T14:51:12
2023-08-31T14:51:12
61,661,378
129
1,150
BSD-3-Clause
2023-09-14T18:48:45
2016-06-21T19:31:29
C++
UTF-8
C
false
false
31,416
c
runFlowAnalysisOnTheFly.C
// Settings for the simulation of events 'on the fly': // a) Determine how many events you want to create; // b) Set random or same seed for random generator; // c) Determine multiplicites of events; // d) Parametrize the phi distribution; // d1) Enable/disable uniform event-wise fluctuations of v2; // d2) Enable/diable pt dependence of v2; // e) Parametrize the pt distribution; // f) Determine how many times each sampled particle will be taken (simulating nonflow); // g) Configure detector's: // g1) acceptance; // g2) efficiency; // h) Decide which flow analysis methods you will use; // i) Define simple cuts for Reference Particle (RP) selection; // j) Define simple cuts for Particle of Interest (POI) selection; // k) Define the ranges for two subevents separated with eta gap (needed only for SP method); // l) Enable/disable usage of particle weights. // a) Determine how many events you want to create: Int_t iNevts = 1000; // total statistics // b) Set random or same seed for random generator: Bool_t bSameSeed = kFALSE; // if kTRUE, the created events are the same when re-doing flow analysis 'on the fly' // c) Determine multiplicites of events: // Remark 1: Multiplicity M for each event is sampled uniformly from interval iMinMult <= M < iMaxMult; // Remark 2: For constant M of e.g. 500 for each event, set iMinMult = 500 and iMaxMult = 501. Int_t iMinMult = 500; // uniformly sampled multiplicity is >= iMinMult Int_t iMaxMult = 501; // uniformly sampled multiplicity is < iMaxMult // d) Parametrize the phi distribution: // Remark 1: Hardwired is Fourier-like distribution f(phi) = (1/2pi)(1+sum_{n=1}^{4} 2v_n cos[n(phi-rp)]), // where reaction plane (rp) is sampled uniformly for each event from interval [0,2pi] Double_t dV1 = 0.0; // constant harmonic v1 Double_t dV2 = 0.05; // constant harmonic v2 Double_t dV3 = 0.0; // constant harmonic v3 Double_t dV4 = 0.0; // constant harmonic v4 Double_t dV5 = 0.0; // constant harmonic v5 Double_t dV6 = 0.0; // constant harmonic v6 // Remark 2: By default all harmonics are constant for each event and for each particle. However, for v2 // the uniform event-wise fluctuations or pt dependence can be enabled: // d1) Enable/disable uniform event-wise fluctuations of v2: Bool_t bUniformFluctuationsV2 = kFALSE; // enable uniform event-wise flow fluctuations (set than also dMinV2 and dMaxV2 bellow) Double_t dMinV2 = 0.04; // lower boundary on v2, when bUniformFluctuationsV2 = kTRUE Double_t dMaxV2 = 0.06; // upper boundary on v2, when bUniformFluctuationsV2 = kTRUE // d2) Enable/disable pt dependence of v2: Bool_t bPtDependentV2 = kFALSE; // enable pt dependence of v2 (set then also dV2vsPtMax and dV2vsPtCutOff bellow) Double_t dV2vsPtCutOff = 2.0; // up to pt = dV2vsPtCutOff v2 is growing linearly as a function of pt Double_t dV2vsPtMax = 0.20; // for pt >= dV2vsPtCutOff, v2(pt) = dV2vsPtMax // e) Parametrize the pt distribution: // Remark: Hardwired is Boltzmann distribution f(pt) = pt*exp[-sqrt(dMass^2+pt^2)/dT] Double_t dMass = 0.13957; // mass in GeV/c^2 (e.g. m_{pions} = 0.13957) Double_t dTemperature = 0.44; // "temperature" in GeV/c (increase this parameter to get more high pt particles) // f) Determine how many times each sampled particle will be taken in the analysis (simulating nonflow): Int_t nTimes = 1; // e.g. for nTimes = 2, strong 2-particle nonflow correlations are introduced // g1) Configure detector's acceptance: Bool_t uniformAcceptance = kTRUE; // if kTRUE: detectors has uniform azimuthal acceptance. // if kFALSE: you will simulate detector with non-uniform acceptance in one or // two sectors. For each sector you specify phiMin, phiMax and probability p. // Then all particles emitted in direction phiMin < phi < phiMax will be taken // with probability p. If p = 0, that sector is completely blocked. Set bellow // phiMin1, phiMax1, p1 for the first sector and phiMin2, phiMax2, p2 for the second // sector. If you set phiMin2 = phiMax2 = p2 = 0, only first non-uniform sector is // simulated. // 1st non-uniform sector: Double_t phiMin1 = 60; // first non-uniform sector starts at this azimuth (in degrees) Double_t phiMax1 = 120; // first non-uniform sector ends at this azimuth (in degrees) Double_t p1 = 0.5; // probablitity that particles emitted in [phiMin1,phiMax1] are taken // 2nd non-uniform sector: Double_t phiMin2 = 0.; // first non-uniform sector starts at this azimuth (in degrees) Double_t phiMax2 = 0.; // first non-uniform sector ends at this azimuth (in degrees) Double_t p2 = 0.; // probablitity that particles emitted in [phiMin2,phiMax2] are taken // g2) Configure detector's efficiency: Bool_t uniformEfficiency = kTRUE; // if kTRUE: detectors has uniform pT efficiency // if kFALSE: you will simulate detector with non-uniform pT efficiency. // Then all particles emitted in ptMin <= pt < ptMax will be taken // with probability p, to be specified in lines just below. Double_t ptMin = 0.8; // non-uniform efficiency vs pT starts at pT = fPtMin Double_t ptMax = 1.2; // non-uniform efficiency vs pT ends at pT = fPtMax Double_t p = 0.5; // probablitity that particles emitted in [ptMin,ptMax> are taken // h) Decide which flow analysis methods you will use: Bool_t MCEP = kTRUE; // Monte Carlo Event Plane Bool_t SP = kTRUE; // Scalar Product (a.k.a 'flow analysis with eta gaps') Bool_t GFC = kTRUE; // Generating Function Cumulants Bool_t QC = kTRUE; // Q-cumulants Bool_t FQD = kTRUE; // Fitted q-distribution Bool_t LYZ1SUM = kTRUE; // Lee-Yang Zero (sum generating function), first pass over the data Bool_t LYZ1PROD = kTRUE; // Lee-Yang Zero (product generating function), first pass over the data Bool_t LYZ2SUM = kFALSE; // Lee-Yang Zero (sum generating function), second pass over the data Bool_t LYZ2PROD = kFALSE; // Lee-Yang Zero (product generating function), second pass over the data Bool_t LYZEP = kFALSE; // Lee-Yang Zero Event Plane Bool_t MH = kFALSE; // Mixed Harmonics (used for strong parity violation studies) Bool_t NL = kFALSE; // Nested Loops (neeed for debugging, only for developers) Bool_t MPC = kTRUE; // Multi-particle correlations (NEW!) // i) Define simple cuts for Reference Particle (RP) selection: Double_t ptMinRP = 0.0; // in GeV Double_t ptMaxRP = 10.0; // in GeV Double_t etaMinRP = -1.; Double_t etaMaxRP = 1.; Double_t phiMinRP = 0.0; // in degrees Double_t phiMaxRP = 360.0; // in degrees Bool_t bUseChargeRP = kFALSE; // if kFALSE, RPs with both sign of charges are taken Int_t chargeRP = 1; // +1 or -1 // j) Define simple cuts for Particle of Interest (POI) selection: Double_t ptMinPOI = 0.0; // in GeV Double_t ptMaxPOI = 10.0; // in GeV Double_t etaMinPOI = -1.; // Double_t etaMaxPOI = 1.; Double_t phiMinPOI = 0.0; // in degrees Double_t phiMaxPOI = 360.0; // in degrees Bool_t bUseChargePOI = kFALSE; // if kFALSE, POIs with both sign of charges are taken Int_t chargePOI = -1; // +1 or -1 // k) Define the ranges for two subevents separated with eta gap (needed only for SP method): Double_t etaMinA = -0.8; // minimum eta of subevent A Double_t etaMaxA = -0.5; // maximum eta of subevent A Double_t etaMinB = 0.5; // minimum eta of subevent B Double_t etaMaxB = 0.8; // maximum eta of subevent B // l) Enable/disable usage of particle weights: Bool_t usePhiWeights = kFALSE; // phi weights Bool_t usePtWeights = kFALSE; // pt weights Bool_t useEtaWeights = kFALSE; // eta weights enum anaModes {mLocal,mLocalSource,mLocalPAR}; // mLocal: Analyze data on your computer using aliroot // mLocalPAR: Analyze data on your computer using root + PAR files // mLocalSource: Analyze data on your computer using root + source files #include "TStopwatch.h" #include "TObjArray" #include "Riostream.h" #include "TFile.h" int runFlowAnalysisOnTheFly(Int_t mode=mLocal) { // Beging analysis 'on the fly'. // a) Formal necessities....; // b) Initialize the flow event maker 'on the fly'; // c) If enabled, access particle weights from external file; // d) Configure the flow analysis methods; // e) Simple cuts for RPs; // f) Simple cuts for POIs; // g) Create and analyse events 'on the fly'; // h) Create the output file and directory structure for the final results of all methods; // i) Calculate and store the final results of all methods. // a) Formal necessities....: CheckUserSettings(); WelcomeMessage(); TStopwatch timer; timer.Start(); LoadLibraries(mode); // b) Initialize the flow event maker 'on the fly': UInt_t uiSeed = 0; // if uiSeed is 0, the seed is determined uniquely in space and time via TUUID if(bSameSeed){uiSeed = 44;} AliFlowEventSimpleMakerOnTheFly* eventMakerOnTheFly = new AliFlowEventSimpleMakerOnTheFly(uiSeed); eventMakerOnTheFly->SetMinMult(iMinMult); eventMakerOnTheFly->SetMaxMult(iMaxMult); eventMakerOnTheFly->SetMass(dMass); eventMakerOnTheFly->SetTemperature(dTemperature); eventMakerOnTheFly->SetV1(dV1); eventMakerOnTheFly->SetV2(dV2); eventMakerOnTheFly->SetV3(dV3); eventMakerOnTheFly->SetV4(dV4); eventMakerOnTheFly->SetV5(dV5); eventMakerOnTheFly->SetV6(dV6); if(bUniformFluctuationsV2) { eventMakerOnTheFly->SetUniformFluctuationsV2(bUniformFluctuationsV2); eventMakerOnTheFly->SetMinV2(dMinV2); eventMakerOnTheFly->SetMaxV2(dMaxV2); } if(bPtDependentV2) { eventMakerOnTheFly->SetPtDependentV2(bPtDependentV2); eventMakerOnTheFly->SetV2vsPtCutOff(dV2vsPtCutOff); eventMakerOnTheFly->SetV2vsPtMax(dV2vsPtMax); } eventMakerOnTheFly->SetSubeventEtaRange(etaMinA,etaMaxA,etaMinB,etaMaxB); eventMakerOnTheFly->SetNTimes(nTimes); if(!uniformAcceptance) { eventMakerOnTheFly->SetUniformAcceptance(kFALSE); eventMakerOnTheFly->SetFirstSectorPhiMin(phiMin1); eventMakerOnTheFly->SetFirstSectorPhiMax(phiMax1); eventMakerOnTheFly->SetFirstSectorProbability(p1); eventMakerOnTheFly->SetSecondSectorPhiMin(phiMin2); eventMakerOnTheFly->SetSecondSectorPhiMax(phiMax2); eventMakerOnTheFly->SetSecondSectorProbability(p2); } if(!uniformEfficiency) { eventMakerOnTheFly->SetUniformEfficiency(kFALSE); eventMakerOnTheFly->SetPtMin(ptMin); eventMakerOnTheFly->SetPtMax(ptMax); eventMakerOnTheFly->SetPtProbability(p); } eventMakerOnTheFly->Init(); // c) If enabled, access particle weights from external file: TFile *fileWithWeights = NULL; TList *listWithWeights = NULL; if(usePhiWeights||usePtWeights||useEtaWeights) { fileWithWeights = TFile::Open("weights.root","READ"); if(fileWithWeights) { listWithWeights = (TList*)fileWithWeights->Get("weights"); } else { cout << " WARNING: the file <weights.root> with weights from the previous run was not found."<<endl; break; } } // end of if(usePhiWeights||usePtWeights||useEtaWeights) // d) Configure the flow analysis methods: AliFlowAnalysisWithQCumulants *qc = NULL; AliFlowAnalysisWithCumulants *gfc = NULL; AliFlowAnalysisWithFittingQDistribution *fqd = NULL; AliFlowAnalysisWithLeeYangZeros *lyz1sum = NULL; AliFlowAnalysisWithLeeYangZeros *lyz1prod = NULL; AliFlowAnalysisWithLeeYangZeros *lyz2sum = NULL; AliFlowAnalysisWithLeeYangZeros *lyz2prod = NULL; AliFlowAnalysisWithLYZEventPlane *lyzep = NULL; AliFlowAnalysisWithScalarProduct *sp = NULL; AliFlowAnalysisWithMixedHarmonics *mh = NULL; AliFlowAnalysisWithNestedLoops *nl = NULL; AliFlowAnalysisWithMCEventPlane *mcep = NULL; AliFlowAnalysisWithMultiparticleCorrelations *mpc = NULL; // MCEP = monte carlo event plane if(MCEP) { //AliFlowAnalysisWithMCEventPlane *mcep = new AliFlowAnalysisWithMCEventPlane(); mcep = new AliFlowAnalysisWithMCEventPlane(); mcep->SetHarmonic(2); // default is v2 mcep->Init(); } // end of if(MCEP) // SP = Scalar Product if(SP) { sp = new AliFlowAnalysisWithScalarProduct(); if(listWithWeights){sp->SetWeightsList(listWithWeights);} sp->SetUsePhiWeights(usePhiWeights); sp->SetHarmonic(2); sp->SetApplyCorrectionForNUA(kFALSE); sp->Init(); } // end of if(SP) // QC = Q-cumulants if(QC) { qc = new AliFlowAnalysisWithQCumulants(); if(listWithWeights){qc->SetWeightsList(listWithWeights);} if(usePhiWeights){qc->SetUsePhiWeights(usePhiWeights);} if(usePtWeights){qc->SetUsePtWeights(usePtWeights);} if(useEtaWeights){qc->SetUseEtaWeights(useEtaWeights);} qc->SetHarmonic(2); qc->SetCalculateDiffFlow(kTRUE); qc->SetCalculate2DDiffFlow(kFALSE); // vs (pt,eta) qc->SetApplyCorrectionForNUA(kFALSE); qc->SetFillMultipleControlHistograms(kFALSE); qc->SetMultiplicityWeight("combinations"); // default (other supported options are "unit" and "multiplicity") qc->SetCalculateCumulantsVsM(kFALSE); qc->SetCalculateAllCorrelationsVsM(kFALSE); // calculate all correlations in mixed harmonics "vs M" qc->SetnBinsMult(10000); qc->SetMinMult(0); qc->SetMaxMult(10000); qc->SetBookOnlyBasicCCH(kFALSE); // book only basic common control histograms qc->SetCalculateDiffFlowVsEta(kTRUE); // if you set kFALSE only differential flow vs pt is calculated qc->SetCalculateMixedHarmonics(kFALSE); // calculate all multi-partice mixed-harmonics correlators qc->Init(); } // end of if(QC) // GFC = Generating Function Cumulants if(GFC) { gfc = new AliFlowAnalysisWithCumulants(); if(listWithWeights){gfc->SetWeightsList(listWithWeights);} if(usePhiWeights){gfc->SetUsePhiWeights(usePhiWeights);} if(usePtWeights){gfc->SetUsePtWeights(usePtWeights);} if(useEtaWeights){gfc->SetUseEtaWeights(useEtaWeights);} // calculation vs multiplicity: gfc->SetCalculateVsMultiplicity(kFALSE); gfc->SetnBinsMult(10000); gfc->SetMinMult(0); gfc->SetMaxMult(10000); gfc->SetHarmonic(2); // tuning of interpolating parameters: gfc->SetTuneParameters(kFALSE); Double_t r0[10] = {1.8,1.9,2.0,2.1,2.2,2.3,2.4,2.5,2.6,2.7}; // up to 10 values allowed for(Int_t r=0;r<10;r++){gfc->SetTuningR0(r0[r],r);} gfc->Init(); } // end of if(GFC) // FQD = Fitting q-distribution if(FQD) { fqd = new AliFlowAnalysisWithFittingQDistribution(); if(listWithWeights){fqd->SetWeightsList(listWithWeights);} if(usePhiWeights){fqd->SetUsePhiWeights(usePhiWeights);} fqd->SetHarmonic(2); fqd->Init(); } // end of if(FQD) // LYZ1 = Lee-Yang Zeroes first run if(LYZ1SUM) { lyz1sum = new AliFlowAnalysisWithLeeYangZeros(); lyz1sum->SetFirstRun(kTRUE); lyz1sum->SetUseSum(kTRUE); lyz1sum->Init(); } // end of if(LYZ1SUM) if(LYZ1PROD) { lyz1prod = new AliFlowAnalysisWithLeeYangZeros(); lyz1prod->SetFirstRun(kTRUE); lyz1prod->SetUseSum(kFALSE); lyz1prod->Init(); } // end of if(LYZ1PROD) // LYZ2 = Lee-Yang Zeroes second run if(LYZ2SUM) { lyz2sum = new AliFlowAnalysisWithLeeYangZeros(); // read the input file from the first run TString inputFileNameLYZ2SUM = "outputLYZ1SUManalysis.root" ; TFile* inputFileLYZ2SUM = new TFile(inputFileNameLYZ2SUM.Data(),"READ"); if(!inputFileLYZ2SUM || inputFileLYZ2SUM->IsZombie()) { cerr<<" ERROR: To run LYZ2SUM you need the output file from LYZ1SUM. This file is not there! Please run LYZ1SUM first."<<endl; break; } else { TList* inputListLYZ2SUM = (TList*)inputFileLYZ2SUM->Get("cobjLYZ1SUM"); if(!inputListLYZ2SUM){cout<<"Input list LYZ2SUM is NULL pointer!"<<endl;break;} else { cout<<"LYZ2SUM input file/list read..."<<endl; lyz2sum->SetFirstRunList(inputListLYZ2SUM); lyz2sum->SetFirstRun(kFALSE); lyz2sum->SetUseSum(kTRUE); lyz2sum->Init(); } } } // end of if(LYZ2SUM) if(LYZ2PROD) { lyz2prod = new AliFlowAnalysisWithLeeYangZeros(); // read the input file from the first run TString inputFileNameLYZ2PROD = "outputLYZ1PRODanalysis.root" ; TFile* inputFileLYZ2PROD = new TFile(inputFileNameLYZ2PROD.Data(),"READ"); if(!inputFileLYZ2PROD || inputFileLYZ2PROD->IsZombie()) { cerr<<" ERROR: To run LYZ2PROD you need the output file from LYZ1PROD. This file is not there! Please run LYZ1PROD first."<<endl; break; } else { TList* inputListLYZ2PROD = (TList*)inputFileLYZ2PROD->Get("cobjLYZ1PROD"); if(!inputListLYZ2PROD){cout<<"Input list LYZ2PROD is NULL pointer!"<<endl;break;} else { cout<<"LYZ2PROD input file/list read..."<<endl; lyz2prod->SetFirstRunList(inputListLYZ2PROD); lyz2prod->SetFirstRun(kFALSE); lyz2prod->SetUseSum(kFALSE); lyz2prod->Init(); } } } // end of if(LYZ2PROD) // LYZEP = Lee-Yang Zeroes event plane if(LYZEP) { AliFlowLYZEventPlane *ep = new AliFlowLYZEventPlane() ; AliFlowAnalysisWithLYZEventPlane* lyzep = new AliFlowAnalysisWithLYZEventPlane(); // read the input file from the second lyz run TString inputFileNameLYZEP = "outputLYZ2SUManalysis.root" ; TFile* inputFileLYZEP = new TFile(inputFileNameLYZEP.Data(),"READ"); if(!inputFileLYZEP || inputFileLYZEP->IsZombie()) { cerr << " ERROR: To run LYZEP you need the output file from LYZ2SUM. This file is not there! Please run LYZ2SUM first." << endl ; break; } else { TList* inputListLYZEP = (TList*)inputFileLYZEP->Get("cobjLYZ2SUM"); if (!inputListLYZEP) {cout<<"Input list LYZEP is NULL pointer!"<<endl; break;} else { cout<<"LYZEP input file/list read..."<<endl; ep ->SetSecondRunList(inputListLYZEP); lyzep->SetSecondRunList(inputListLYZEP); ep ->Init(); lyzep->Init(); } } } // Mixed Harmonics: if(MH) { mh = new AliFlowAnalysisWithMixedHarmonics(); mh->SetHarmonic(1); // integer n in expression cos[n(2phi1-phi2-phi3)] = v2n*vn^2 mh->SetMinMultiplicity(100); mh->SetNoOfMultipicityBins(5); mh->SetMultipicityBinWidth(200); mh->Init(); } // end of if(MH) // NL = Nested Loops: if(NL) { nl = new AliFlowAnalysisWithNestedLoops(); nl->Init(); } // end of if(NL) // MPC = Multi-particle correlations if(MPC) { mpc = new AliFlowAnalysisWithMultiparticleCorrelations(); // Weights: //TFile *file = TFile::Open("weights.root","READ"); //TH1D *weightsHist = (TH1D*) file->FindObjectAny("Phi weights"); //mpc->SetPhiWeightsHist(weightsHist); // Control histograms: mpc->SetFillControlHistograms(kTRUE); mpc->SetFillKinematicsHist(kTRUE); // Q-vector: mpc->SetCalculateQvector(kTRUE); // Correlations: mpc->SetCalculateCorrelations(kTRUE); mpc->SetSkipZeroHarmonics(kTRUE); mpc->SetCalculateIsotropic(kTRUE); // Standard candles: mpc->SetCalculateStandardCandles(kTRUE); // Init: mpc->Init(); } // end of if(MPC) // e) Simple cuts for RPs: AliFlowTrackSimpleCuts *cutsRP = new AliFlowTrackSimpleCuts(); cutsRP->SetPtMax(ptMaxRP); cutsRP->SetPtMin(ptMinRP); cutsRP->SetEtaMax(etaMaxRP); cutsRP->SetEtaMin(etaMinRP); cutsRP->SetPhiMax(phiMaxRP*TMath::Pi()/180.); cutsRP->SetPhiMin(phiMinRP*TMath::Pi()/180.); if(bUseChargeRP){cutsRP->SetCharge(chargeRP);} // f) Simple cuts for POIs: AliFlowTrackSimpleCuts *cutsPOI = new AliFlowTrackSimpleCuts(); cutsPOI->SetPtMax(ptMaxPOI); cutsPOI->SetPtMin(ptMinPOI); cutsPOI->SetEtaMax(etaMaxPOI); cutsPOI->SetEtaMin(etaMinPOI); cutsPOI->SetPhiMax(phiMaxPOI*TMath::Pi()/180.); cutsPOI->SetPhiMin(phiMinPOI*TMath::Pi()/180.); if(bUseChargePOI){cutsPOI->SetCharge(chargePOI);} // g) Create and analyse events 'on the fly': for(Int_t i=0;i<iNevts;i++) { // Creating the event 'on the fly': AliFlowEventSimple *event = eventMakerOnTheFly->CreateEventOnTheFly(cutsRP,cutsPOI); // Passing the created event to flow analysis methods: if(MCEP){mcep->Make(event);} if(QC){qc->Make(event);} if(GFC){gfc->Make(event);} if(FQD){fqd->Make(event);} if(LYZ1SUM){lyz1sum->Make(event);} if(LYZ1PROD){lyz1prod->Make(event);} if(LYZ2SUM){lyz2sum->Make(event);} if(LYZ2PROD){lyz2prod->Make(event);} if(LYZEP){lyzep->Make(event,ep);} if(SP){sp->Make(event);} if(MH){mh->Make(event);} if(NL){nl->Make(event);} if(MPC){mpc->Make(event);} delete event; } // end of for(Int_t i=0;i<iNevts;i++) // h) Create the output file and directory structure for the final results of all methods: TString outputFileName = "AnalysisResults.root"; TFile *outputFile = new TFile(outputFileName.Data(),"RECREATE"); const Int_t nMethods = 13; TString method[nMethods] = {"MCEP","SP","GFC","QC","FQD","LYZ1SUM","LYZ1PROD","LYZ2SUM","LYZ2PROD","LYZEP","MH","NL","MPC"}; TDirectoryFile *dirFileFinal[nMethods] = {NULL}; TString fileName[nMethods]; for(Int_t i=0;i<nMethods;i++) { fileName[i]+="output"; fileName[i]+=method[i].Data(); fileName[i]+="analysis"; dirFileFinal[i] = new TDirectoryFile(fileName[i].Data(),fileName[i].Data()); } // i) Calculate and store the final results of all methods: if(MCEP){mcep->Finish();mcep->WriteHistograms(dirFileFinal[0]);} if(SP){sp->Finish();sp->WriteHistograms(dirFileFinal[1]);} if(GFC){gfc->Finish();gfc->WriteHistograms(dirFileFinal[2]);} if(QC){qc->Finish();qc->WriteHistograms(dirFileFinal[3]);} if(FQD){fqd->Finish();fqd->WriteHistograms(dirFileFinal[4]);} if(LYZ1SUM){lyz1sum->Finish();lyz1sum->WriteHistograms(dirFileFinal[5]);} if(LYZ1PROD){lyz1prod->Finish();lyz1prod->WriteHistograms(dirFileFinal[6]);} if(LYZ2SUM){lyz2sum->Finish();lyz2sum->WriteHistograms(dirFileFinal[7]);} if(LYZ2PROD){lyz2prod->Finish();lyz2prod->WriteHistograms(dirFileFinal[8]);} if(LYZEP){lyzep->Finish();lyzep->WriteHistograms(dirFileFinal[9]);} if(MH){mh->Finish();mh->WriteHistograms(dirFileFinal[10]);} if(NL){nl->Finish();nl->WriteHistograms(dirFileFinal[11]);} if(MPC){mpc->Finish();mpc->WriteHistograms(dirFileFinal[12]);} outputFile->Close(); delete outputFile; cout<<endl; cout<<endl; cout<<" ---- LANDED SUCCESSFULLY ---- "<<endl; cout<<endl; timer.Stop(); cout << endl; timer.Print(); } // end of int runFlowAnalysisOnTheFly(Int_t mode=mLocal) void SetupPar(char* pararchivename) { //Load par files, create analysis libraries //For testing, if par file already decompressed and modified //classes then do not decompress. TString cdir(Form("%s", gSystem->WorkingDirectory() )) ; TString parpar(Form("%s.par", pararchivename)) ; if ( gSystem->AccessPathName(parpar.Data()) ) { gSystem->ChangeDirectory(gSystem->Getenv("ALICE_PHYSICS")) ; TString processline(Form(".! make %s", parpar.Data())) ; gROOT->ProcessLine(processline.Data()) ; gSystem->ChangeDirectory(cdir) ; processline = Form(".! mv /tmp/%s .", parpar.Data()) ; gROOT->ProcessLine(processline.Data()) ; } if ( gSystem->AccessPathName(pararchivename) ) { TString processline = Form(".! tar xvzf %s",parpar.Data()) ; gROOT->ProcessLine(processline.Data()); } TString ocwd = gSystem->WorkingDirectory(); gSystem->ChangeDirectory(pararchivename); // check for BUILD.sh and execute if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) { printf("*******************************\n"); printf("*** Building PAR archive ***\n"); cout<<pararchivename<<endl; printf("*******************************\n"); if (gSystem->Exec("PROOF-INF/BUILD.sh")) { Error("runProcess","Cannot Build the PAR Archive! - Abort!"); return -1; } } // check for SETUP.C and execute if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) { printf("*******************************\n"); printf("*** Setup PAR archive ***\n"); cout<<pararchivename<<endl; printf("*******************************\n"); gROOT->Macro("PROOF-INF/SETUP.C"); } gSystem->ChangeDirectory(ocwd.Data()); printf("Current dir: %s\n", ocwd.Data()); } void CheckUserSettings() { // Check if user settings make sense before taking off. if(iNevts <= 0) { printf("\n WARNING: nEvts <= 0 !!!! Please check your settings before taking off.\n\n"); exit(0); } if(iMinMult < 0.) { printf("\n WARNING: iMinMult < 0 !!!! Please check your settings before taking off.\n\n"); exit(0); } if(iMaxMult <= 0.) { printf("\n WARNING: iMaxMult <= 0 !!!! Please check your settings before taking off.\n\n"); exit(0); } if(iMinMult >= iMaxMult) { printf("\n WARNING: iMinMult >= iMaxMult !!!! Please check your settings before taking off.\n\n"); exit(0); } if(dMass < 0.) { printf("\n WARNING: dMass < 0 !!!! Please check your settings before taking off.\n\n"); exit(0); } if(dTemperature <= 1e-44) { printf("\n WARNING: dTemperature <= 0 !!!! Please check your settings before taking off.\n\n"); exit(0); } if(TMath::Abs(dV1) > 0.5) { printf("\n WARNING: |dV1| > 0.5 !!!! Please check your settings before taking off.\n\n"); exit(0); } if(TMath::Abs(dV2) > 0.5) { printf("\n WARNING: |dV2| > 0.5 !!!! Please check your settings before taking off.\n\n"); exit(0); } if(TMath::Abs(dV3) > 0.5) { printf("\n WARNING: |dV3| > 0.5 !!!! Please check your settings before taking off.\n\n"); exit(0); } if(TMath::Abs(dV4) > 0.5) { printf("\n WARNING: |dV4| > 0.5 !!!! Please check your settings before taking off.\n\n"); exit(0); } if(TMath::Abs(dV5) > 0.5) { printf("\n WARNING: |dV5| > 0.5 !!!! Please check your settings before taking off.\n\n"); exit(0); } if(TMath::Abs(dV6) > 0.5) { printf("\n WARNING: |dV6| > 0.5 !!!! Please check your settings before taking off.\n\n"); exit(0); } if(LYZ1SUM && LYZ2SUM) { cout<<" WARNING: You cannot run LYZ1 and LYZ2 at the same time! LYZ2 needs the output from LYZ1."<<endl; exit(0); } if(LYZ1PROD && LYZ2PROD) { cout<<" WARNING: You cannot run LYZ1 and LYZ2 at the same time! LYZ2 needs the output from LYZ1."<<endl; exit(0); } if(LYZ2SUM && LYZEP) { cout<<" WARNING: You cannot run LYZ2 and LYZEP at the same time! LYZEP needs the output from LYZ2."<<endl; exit(0); } if(LYZ1SUM && LYZEP) { cout<<" WARNING: You cannot run LYZ1 and LYZEP at the same time! LYZEP needs the output from LYZ2."<<endl; exit(0); } if(!uniformAcceptance && phiMin1 > phiMax1) { cout<<" WARNING: You must have phiMin1 < phiMax1 !!!!"<<endl; exit(0); } if(!uniformAcceptance && !((TMath::Abs(phiMin2) < 1.e-44) && (TMath::Abs(phiMax2) < 1.e-44) && (TMath::Abs(p2) < 1.e-44)) && (phiMin2 < phiMax1 || phiMin2 > phiMax2)) { cout<<" WARNING: You must have phiMin2 > phiMax1 and phiMin2 < phiMax2 !!!!"<<endl; exit(0); } if((phiMin1 < 0 || phiMin1 > 360) || (phiMax1 < 0 || phiMax1 > 360) || (phiMin2 < 0 || phiMin2 > 360) || (phiMax2 < 0 || phiMax2 > 360) ) { cout<<" WARNING: You must take azimuthal angles from interval [0,360] !!!!"<<endl; exit(0); } if((p1 < 0 || p1 > 1) || (p2 < 0 || p2 > 1)) { cout<<" WARNING: you must take p1 and p2 from interval [0,1] !!!!"<<endl; exit(0); } if(bPtDependentV2 && bUniformFluctuationsV2) { cout<<" WARNING: Uniform fluctuations not supported for pt denependent v2 !!!!"<<endl; exit(0); } } // end of void CheckUserSettings() void WelcomeMessage() { // Welcome. cout<<endl; cout<<endl; cout<<" ---- ARE YOU READY TO FLY ? ---- "<<endl; cout<<endl; gSystem->Sleep(1544); cout<<endl; cout<<" ---- BEGIN FLOW ANALYSIS 'ON THE FLY' ---- "<<endl; cout<<endl; cout<<endl; gSystem->Sleep(1544); } // end of void WelcomeMessage() void LoadLibraries(const anaModes mode) { //-------------------------------------- // Load the needed libraries most of them already loaded by aliroot //-------------------------------------- //gSystem->Load("libTree"); gSystem->Load("libGeom"); gSystem->Load("libVMC"); gSystem->Load("libXMLIO"); gSystem->Load("libPhysics"); //---------------------------------------------------------- // >>>>>>>>>>> Local mode <<<<<<<<<<<<<< //---------------------------------------------------------- if (mode==mLocal) { //-------------------------------------------------------- // If you want to use already compiled libraries // in the aliroot distribution //-------------------------------------------------------- gSystem->Load("libSTEERBase"); gSystem->Load("libESD"); gSystem->Load("libAOD"); gSystem->Load("libANALYSIS"); gSystem->Load("libANALYSISalice"); gSystem->Load("libCORRFW"); cerr<<"libCORRFW loaded..."<<endl; gSystem->Load("libPWGflowBase"); cerr<<"libPWGflowBase loaded..."<<endl; gSystem->Load("libPWGflowTasks"); cerr<<"libPWGflowTasks loaded..."<<endl; } else if (mode == mLocalPAR) { //-------------------------------------------------------- //If you want to use root and par files from aliroot //-------------------------------------------------------- //If you want to use root and par files from aliroot //-------------------------------------------------------- SetupPar("STEERBase"); SetupPar("ESD"); SetupPar("AOD"); SetupPar("ANALYSIS"); SetupPar("ANALYSISalice"); SetupPar("PWG2AOD"); SetupPar("CORRFW"); SetupPar("PWGflowBase"); cerr<<"PWGflowBase.par loaded..."<<endl; SetupPar("PWGflowTasks"); cerr<<"PWGflowTasks.par loaded..."<<endl; } //--------------------------------------------------------- // <<<<<<<<<< Source mode >>>>>>>>>>>> //--------------------------------------------------------- else if (mode==mLocalSource) { // In root inline compile // Constants gROOT->LoadMacro("Base/AliFlowCommonConstants.cxx+"); gROOT->LoadMacro("Base/AliFlowLYZConstants.cxx+"); // Flow event gROOT->LoadMacro("Base/AliFlowVector.cxx+"); gROOT->LoadMacro("Base/AliFlowTrackSimple.cxx+"); gROOT->LoadMacro("Base/AliFlowTrackSimpleCuts.cxx+"); gROOT->LoadMacro("Base/AliFlowEventSimple.cxx+"); // Output histosgrams gROOT->LoadMacro("Base/AliFlowCommonHist.cxx+"); gROOT->LoadMacro("Base/AliFlowCommonHistResults.cxx+"); gROOT->LoadMacro("Base/AliFlowLYZHist1.cxx+"); gROOT->LoadMacro("Base/AliFlowLYZHist2.cxx+"); // Functions needed for various methods gROOT->LoadMacro("Base/AliCumulantsFunctions.cxx+"); gROOT->LoadMacro("Base/AliFlowLYZEventPlane.cxx+"); // Flow Analysis code for various methods gROOT->LoadMacro("Base/AliFlowAnalysisWithMCEventPlane.cxx+"); gROOT->LoadMacro("Base/AliFlowAnalysisWithScalarProduct.cxx+"); gROOT->LoadMacro("Base/AliFlowAnalysisWithLYZEventPlane.cxx+"); gROOT->LoadMacro("Base/AliFlowAnalysisWithLeeYangZeros.cxx+"); gROOT->LoadMacro("Base/AliFlowAnalysisWithCumulants.cxx+"); gROOT->LoadMacro("Base/AliFlowAnalysisWithQCumulants.cxx+"); gROOT->LoadMacro("Base/AliFlowAnalysisWithFittingQDistribution.cxx+"); gROOT->LoadMacro("Base/AliFlowAnalysisWithMixedHarmonics.cxx+"); gROOT->LoadMacro("Base/AliFlowAnalysisWithNestedLoops.cxx+"); // Class to fill the FlowEvent on the fly (generate Monte Carlo events) gROOT->LoadMacro("Base/AliFlowEventSimpleMakerOnTheFly.cxx+"); cout << "finished loading macros!" << endl; } }
078685cc942ee0ff4875e5bafd3a5698e6cfa50b
c8f7773f80acf75345af37c67f0d925cf0234118
/src/tir.h
03796d7c17797d0bfc0e434088a0879acbef9d3b
[ "MIT" ]
permissive
uglyDwarf/linuxtrack
14a8854b826d57fa28ca276ec6ba5c54a1ddaa31
fe9b98b51f6ee6521d38bd1f7edf84839227e588
refs/heads/master
2023-05-25T02:05:04.332165
2023-02-22T20:20:35
2023-02-22T20:20:35
39,029,490
156
35
MIT
2023-05-19T07:27:16
2015-07-13T18:21:31
C
UTF-8
C
false
false
420
h
tir.h
#ifndef TIR__H #define TIR__H #include <stdbool.h> /* extern bool open_tir(const char data_path[], bool force_fw_load, bool ir_on); extern bool pause_tir(); extern bool resume_tir(); extern bool read_frame(); extern bool close_tir(); extern void get_tir_info(); extern void switch_green(bool state); extern void switch_blue(bool state); extern void switch_reb(bool state); extern void switch_ir(bool state); */ #endif
990812a9d590e39adbbf2ae1523500fc068d31ce
42ab733e143d02091d13424fb4df16379d5bba0d
/third_party/libsdl2/src/thread/psp/SDL_syssem.c
0c364340929214777b0eeed9080867bd01f01fcc
[ "Apache-2.0", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference", "Zlib" ]
permissive
google/filament
11cd37ac68790fcf8b33416b7d8d8870e48181f0
0aa0efe1599798d887fa6e33c412c09e81bea1bf
refs/heads/main
2023-08-29T17:58:22.496956
2023-08-28T17:27:38
2023-08-28T17:27:38
143,455,116
16,631
1,961
Apache-2.0
2023-09-14T16:23:39
2018-08-03T17:26:00
C++
UTF-8
C
false
false
3,921
c
SDL_syssem.c
/* Simple DirectMedia Layer Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org> 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 "../../SDL_internal.h" #if SDL_THREAD_PSP /* Semaphore functions for the PSP. */ #include <stdio.h> #include <stdlib.h> #include "SDL_error.h" #include "SDL_thread.h" #include <pspthreadman.h> #include <pspkerror.h> struct SDL_semaphore { SceUID semid; }; /* Create a semaphore */ SDL_sem *SDL_CreateSemaphore(Uint32 initial_value) { SDL_sem *sem; sem = (SDL_sem *) malloc(sizeof(*sem)); if (sem != NULL) { /* TODO: Figure out the limit on the maximum value. */ sem->semid = sceKernelCreateSema("SDL sema", 0, initial_value, 255, NULL); if (sem->semid < 0) { SDL_SetError("Couldn't create semaphore"); free(sem); sem = NULL; } } else { SDL_OutOfMemory(); } return sem; } /* Free the semaphore */ void SDL_DestroySemaphore(SDL_sem *sem) { if (sem != NULL) { if (sem->semid > 0) { sceKernelDeleteSema(sem->semid); sem->semid = 0; } free(sem); } } /* TODO: This routine is a bit overloaded. * If the timeout is 0 then just poll the semaphore; if it's SDL_MUTEX_MAXWAIT, pass * NULL to sceKernelWaitSema() so that it waits indefinitely; and if the timeout * is specified, convert it to microseconds. */ int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout) { Uint32 *pTimeout; int res; if (sem == NULL) { SDL_SetError("Passed a NULL sem"); return 0; } if (timeout == 0) { res = sceKernelPollSema(sem->semid, 1); if (res < 0) { return SDL_MUTEX_TIMEDOUT; } return 0; } if (timeout == SDL_MUTEX_MAXWAIT) { pTimeout = NULL; } else { timeout *= 1000; /* Convert to microseconds. */ pTimeout = &timeout; } res = sceKernelWaitSema(sem->semid, 1, pTimeout); switch (res) { case SCE_KERNEL_ERROR_OK: return 0; case SCE_KERNEL_ERROR_WAIT_TIMEOUT: return SDL_MUTEX_TIMEDOUT; default: return SDL_SetError("sceKernelWaitSema() failed"); } } int SDL_SemTryWait(SDL_sem *sem) { return SDL_SemWaitTimeout(sem, 0); } int SDL_SemWait(SDL_sem *sem) { return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT); } /* Returns the current count of the semaphore */ Uint32 SDL_SemValue(SDL_sem *sem) { SceKernelSemaInfo info; if (sem == NULL) { SDL_SetError("Passed a NULL sem"); return 0; } if (sceKernelReferSemaStatus(sem->semid, &info) >= 0) { return info.currentCount; } return 0; } int SDL_SemPost(SDL_sem *sem) { int res; if (sem == NULL) { return SDL_SetError("Passed a NULL sem"); } res = sceKernelSignalSema(sem->semid, 1); if (res < 0) { return SDL_SetError("sceKernelSignalSema() failed"); } return 0; } #endif /* SDL_THREAD_PSP */ /* vim: ts=4 sw=4 */
585f7f514d2c5a0c7732d6eb61b271e4c28d4f42
f367e4b66a1ee42e85830b31df88f63723c36a47
/lib/monkey/mk_server/mk_http_thread.c
d3c606f3afefba635383eb66c43beac0668883ac
[ "Apache-2.0" ]
permissive
fluent/fluent-bit
06873e441162b92941024e9a7e9e8fc934150bf7
1a41f49dc2f3ae31a780caa9ffd6137b1d703065
refs/heads/master
2023-09-05T13:44:55.347372
2023-09-05T10:14:33
2023-09-05T10:14:33
29,933,948
4,907
1,565
Apache-2.0
2023-09-14T10:17:02
2015-01-27T20:41:52
C
UTF-8
C
false
false
8,397
c
mk_http_thread.c
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Monkey HTTP Server * ================== * Copyright 2001-2016 Monkey Software LLC <eduardo@monkey.io> * * 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 <monkey/mk_info.h> #include <monkey/mk_plugin.h> #include <monkey/mk_thread.h> #include <monkey/mk_net.h> #include <monkey/mk_vhost.h> #include <monkey/mk_http_thread.h> #include <stdlib.h> /* * libco do not support parameters in the entrypoint function due to the * complexity of implementation in terms of architecture and compiler, but * it provide a workaround using a global structure as a middle entry-point * that achieve the same stuff. */ struct mk_http_libco_params { int type; struct mk_vhost_handler *handler; struct mk_http_session *session; struct mk_http_request *request; int n_params; struct mk_list *params; struct mk_thread *th; }; pthread_once_t mk_http_thread_initialize_tls_once_flag = PTHREAD_ONCE_INIT; MK_TLS_DEFINE(struct mk_http_libco_params, mk_http_thread_libco_params); MK_TLS_DEFINE(struct mk_thread, mk_thread); /* This function could return NULL if the process runs out of memory, in that * case failure is imminent. */ static inline struct mk_http_libco_params *thread_get_libco_params() { struct mk_http_libco_params *libco_params; libco_params = MK_TLS_GET(mk_http_thread_libco_params); if (libco_params == NULL) { libco_params = mk_mem_alloc_z(sizeof(struct mk_http_libco_params)); if (libco_params == NULL) { mk_err("libco thread params could not be allocated."); } MK_TLS_SET(mk_http_thread_libco_params, libco_params); } return libco_params; } static void mk_http_thread_initialize_tls_once() { MK_TLS_INIT(mk_http_thread_libco_params); MK_TLS_INIT(mk_thread); } void mk_http_thread_initialize_tls() { pthread_once(&mk_http_thread_initialize_tls_once_flag, mk_http_thread_initialize_tls_once); } static inline void thread_cb_init_vars() { struct mk_http_libco_params *libco_params; struct mk_vhost_handler *handler; struct mk_http_session *session; struct mk_http_request *request; int close; int type; struct mk_http_thread *mth; struct mk_thread *th; libco_params = thread_get_libco_params(); type = libco_params->type; handler = libco_params->handler; session = libco_params->session; request = libco_params->request; th = libco_params->th; /* * Until this point the th->callee already set the variables, so we * wait until the core wanted to resume so we really trigger the * output callback. */ co_switch(th->caller); if (type == MK_HTTP_THREAD_LIB) { /* Invoke the handler callback */ handler->cb(request, handler->data); /* * Once the callback finished, we need to sanitize the connection * so other further requests can be processed. */ int ret; struct mk_sched_worker *sched; struct mk_channel *channel; channel = request->session->channel; sched = mk_sched_get_thread_conf(); MK_EVENT_NEW(channel->event); ret = mk_event_add(sched->loop, channel->fd, MK_EVENT_CONNECTION, MK_EVENT_READ, channel->event); if (ret == -1) { //return -1; } /* Save temporal session */ mth = request->thread; /* * Finalize request internally, if ret == -1 means we should * ask to shutdown the connection. */ ret = mk_http_request_end(session, session->server); if (ret == -1) { close = MK_TRUE; } else { close = MK_FALSE; } mk_http_thread_purge(mth, close); /* Return control to caller */ mk_thread_yield(th); } else if (type == MK_HTTP_THREAD_PLUGIN) { /* FIXME: call plugin handler callback with params */ } } static inline void thread_params_set(struct mk_thread *th, int type, struct mk_vhost_handler *handler, struct mk_http_session *session, struct mk_http_request *request, int n_params, struct mk_list *params) { struct mk_http_libco_params *libco_params; libco_params = thread_get_libco_params(); /* Callback parameters in order */ libco_params->type = type; libco_params->handler = handler; libco_params->session = session; libco_params->request = request; libco_params->n_params = n_params; libco_params->params = params; libco_params->th = th; co_switch(th->callee); } struct mk_http_thread *mk_http_thread_create(int type, struct mk_vhost_handler *handler, struct mk_http_session *session, struct mk_http_request *request, int n_params, struct mk_list *params) { size_t stack_size; struct mk_thread *th = NULL; struct mk_http_thread *mth; struct mk_sched_worker *sched; sched = mk_sched_get_thread_conf(); if (!sched) { return NULL; } th = mk_thread_new(sizeof(struct mk_http_thread), NULL); if (!th) { return NULL; } mth = (struct mk_http_thread *) MK_THREAD_DATA(th); if (!mth) { return NULL; } mth->session = session; mth->request = request; mth->parent = th; mth->close = MK_FALSE; request->thread = mth; mk_list_add(&mth->_head, &sched->threads); th->caller = co_active(); th->callee = co_create(MK_THREAD_STACK_SIZE, thread_cb_init_vars, &stack_size); #ifdef MK_HAVE_VALGRIND th->valgrind_stack_id = VALGRIND_STACK_REGISTER(th->callee, ((char *)th->callee) + stack_size); #endif /* Workaround for makecontext() */ thread_params_set(th, type, handler, session, request, n_params, params); return mth; } /* * Move a http thread context from sched->thread to sched->threads_purge list. * On this way the scheduler will release or reasign the resource later. */ int mk_http_thread_purge(struct mk_http_thread *mth, int close) { struct mk_sched_worker *sched; sched = mk_sched_get_thread_conf(); if (!sched) { return -1; } mth->close = close; mk_list_del(&mth->_head); mk_list_add(&mth->_head, &sched->threads_purge); return 0; } int mk_http_thread_destroy(struct mk_http_thread *mth) { struct mk_thread *th; /* Unlink from scheduler thread list */ mk_list_del(&mth->_head); /* release original memory context */ th = mth->parent; mth->session->channel->event->type = MK_EVENT_CONNECTION; mk_thread_destroy(th); return 0; } int mk_http_thread_event(struct mk_event *event) { struct mk_sched_conn *conn = (struct mk_sched_conn *) event; /* struct mk_thread *th; struct mk_http_thread *mth; th = conn->channel.thread; mth = (struct mk_http_thread *) MK_THREAD_DATA(th); */ mk_thread_resume(conn->channel.thread); return 0; } /* * Start the co-routine: invoke coroutine callback and start processing * data flush requests. */ int mk_http_thread_start(struct mk_http_thread *mth) { mk_http_thread_resume(mth); return 0; }
b900069342e2c6f541523bc33570b7cb818efaa6
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/frdm-k64f/board/board.c
ceda089bb156cd57ce1e25a5dd7fcee782947db9
[ "Apache-2.0", "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC", "LicenseRef-scancode-unknown-license-reference" ]
permissive
RT-Thread/rt-thread
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
3602f891211904a27dcbd51e5ba72fefce7326b2
refs/heads/master
2023-09-01T04:10:20.295801
2023-08-31T16:20:55
2023-08-31T16:20:55
7,408,108
9,599
5,805
Apache-2.0
2023-09-14T13:37:26
2013-01-02T14:49:21
C
UTF-8
C
false
false
1,816
c
board.c
/* * Copyright (c) 2006-2022, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * */ #include <rthw.h> #include <rtthread.h> #include "board.h" #include "drv_uart.h" #include "clock_config.h" /** * @addtogroup K64 */ /*@{*/ /******************************************************************************* * Function Name : NVIC_Configuration * Description : Configures Vector Table base location. * Input : None * Output : None * Return : None *******************************************************************************/ void NVIC_Configuration(void) { } /******************************************************************************* * Function Name : SysTick_Configuration * Description : Configures the SysTick for OS tick. * Input : None * Output : None * Return : None *******************************************************************************/ void SysTick_Configuration(void) { SystemCoreClockUpdate(); /* Update Core Clock Frequency */ SysTick_Config(SystemCoreClock/RT_TICK_PER_SECOND); /* Generate interrupt each 1 ms */ } /** * This is the timer interrupt service routine. * */ void SysTick_Handler(void) { /* enter interrupt */ rt_interrupt_enter(); rt_tick_increase(); /* leave interrupt */ rt_interrupt_leave(); } /** * This function will initial Tower board. */ void rt_hw_board_init() { /* NVIC Configuration */ NVIC_Configuration(); BOARD_BootClockRUN(); /* Configure the SysTick */ SysTick_Configuration(); rt_hw_uart_init(); #if defined(RT_USING_CONSOLE) && defined(RT_USING_DEVICE) rt_console_set_device(CONSOLE_DEVICE); #endif } /*@}*/
2b28798f5806f559fc9d28a2bd09ae5532ed8207
aa3befea459382dc5c01c925653d54f435b3fb0f
/arch/hc/src/common/hc_internal.h
b47d8f092b92eab4a944caa8b7ee2530899a5b8a
[ "MIT-open-group", "BSD-3-Clause", "HPND-sell-variant", "BSD-4-Clause-UC", "LicenseRef-scancode-warranty-disclaimer", "MIT-0", "LicenseRef-scancode-bsd-atmel", "LicenseRef-scancode-gary-s-brown", "LicenseRef-scancode-proprietary-license", "SunPro", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "LicenseRef-scancode-other-permissive", "HPND", "ISC", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "GPL-1.0-or-later", "CC-BY-2.0", "CC-BY-4.0" ]
permissive
apache/nuttx
14519a7bff4a87935d94fb8fb2b19edb501c7cec
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
refs/heads/master
2023-08-25T06:55:45.822534
2023-08-23T16:03:31
2023-08-24T21:25:47
228,103,273
407
241
Apache-2.0
2023-09-14T18:26:05
2019-12-14T23:27:55
C
UTF-8
C
false
false
6,228
h
hc_internal.h
/**************************************************************************** * arch/hc/src/common/hc_internal.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_HC_SRC_COMMON_UP_INTERNAL_H #define __ARCH_HC_SRC_COMMON_UP_INTERNAL_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #ifndef __ASSEMBLY__ # include <nuttx/compiler.h> # include <nuttx/irq.h> # include <stdint.h> #endif /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* Determine which (if any) console driver to use. If a console is enabled * and no other console device is specified, then a serial console is * assumed. */ #ifndef CONFIG_DEV_CONSOLE # undef USE_SERIALDRIVER # undef USE_EARLYSERIALINIT #else # if defined(CONFIG_CONSOLE_SYSLOG) # undef USE_SERIALDRIVER # undef USE_EARLYSERIALINIT # else # define USE_SERIALDRIVER 1 # define USE_EARLYSERIALINIT 1 # endif #endif /* If some other device is used as the console, then the serial driver may * still be needed. Let's assume that if the upper half serial driver is * built, then the lower half will also be needed. There is no need for * the early serial initialization in this case. */ #if !defined(USE_SERIALDRIVER) && defined(CONFIG_STANDARD_SERIAL) # define USE_SERIALDRIVER 1 #endif /* Check if an interrupt stack size is configured */ #ifndef CONFIG_ARCH_INTERRUPTSTACK # define CONFIG_ARCH_INTERRUPTSTACK 0 #endif /* The CPU12 stack should be aligned at half-word (2 byte) boundaries. If * necessary frame_size must be rounded up to the next boundary */ #define STACK_ALIGNMENT 2 /* Stack alignment macros */ #define STACK_ALIGN_MASK (STACK_ALIGNMENT - 1) #define STACK_ALIGN_DOWN(a) ((a) & ~STACK_ALIGN_MASK) #define STACK_ALIGN_UP(a) (((a) + STACK_ALIGN_MASK) & ~STACK_ALIGN_MASK) #define getreg8(a) (*(volatile uint8_t *)(a)) #define putreg8(v,a) (*(volatile uint8_t *)(a) = (v)) #define getreg16(a) (*(volatile uint16_t *)(a)) #define putreg16(v,a) (*(volatile uint16_t *)(a) = (v)) #define getreg32(a) (*(volatile uint32_t *)(a)) #define putreg32(v,a) (*(volatile uint32_t *)(a) = (v)) /* Macros to handle saving and restore interrupt state. In the current CPU12 * model, the state is copied from the stack to the TCB, but only * a referenced is passed to get the state from the TCB. */ #define hc_savestate(regs) hc_copystate(regs, (uint8_t*)g_current_regs) #define hc_restorestate(regs) (g_current_regs = regs) /**************************************************************************** * Public Types ****************************************************************************/ #ifndef __ASSEMBLY__ typedef void (*up_vector_t)(void); #endif /**************************************************************************** * Public Data ****************************************************************************/ #ifndef __ASSEMBLY__ /* This is the beginning of heap as provided from processor-specific logic. * This is the first address in RAM after the loaded program+bss+idle stack. * The end of the heap is CONFIG_RAM_END */ extern uint16_t g_idle_topstack; /* Address of the saved user stack pointer */ #if CONFIG_ARCH_INTERRUPTSTACK > 1 extern uint8_t g_intstackalloc[]; extern uint8_t g_intstacktop[]; #endif /**************************************************************************** * Inline Functions ****************************************************************************/ /**************************************************************************** * Public Functions Prototypes ****************************************************************************/ /* Atomic modification of registers */ void modifyreg8(unsigned int addr, uint8_t clearbits, uint8_t setbits); void modifyreg16(unsigned int addr, uint16_t clearbits, uint16_t setbits); void modifyreg32(unsigned int addr, uint32_t clearbits, uint32_t setbits); /* Context switching functions */ void hc_copystate(uint8_t *dest, uint8_t *src); void hc_decodeirq(uint8_t *regs); void hc_fullcontextrestore(uint8_t *restoreregs) noreturn_function; void hc_switchcontext(uint8_t *saveregs, uint8_t *restoreregs); /* Interrupt handling */ uint8_t *hc_doirq(int irq, uint8_t *regs); /* Signal handling */ void hc_sigdeliver(void); /* Debug output */ #ifdef USE_EARLYSERIALINIT void hc_earlyserialinit(void); #endif #ifdef USE_SERIALDRIVER void hc_serialinit(void); #endif void hc_lowputc(char ch); void hc_lowputs(const char *str); /* Memory configuration */ #if CONFIG_MM_REGIONS > 1 void hc_addregion(void); #else # define hc_addregion() #endif /* Sub-system/driver initialization */ #ifdef CONFIG_ARCH_DMA void weak_function hc_dma_initialize(void); #endif #if defined(CONFIG_NET) && !defined(CONFIG_NETDEV_LATEINIT) void hc_netinitialize(void); #else # define hc_netinitialize() #endif #ifdef CONFIG_USBDEV void hc_usbinitialize(void); void hc_usbuninitialize(void); #else # define hc_usbinitialize() # define hc_usbuninitialize() #endif #endif /* __ASSEMBLY__ */ #endif /* __ARCH_HC_SRC_COMMON_UP_INTERNAL_H */
0c889f5aa66ad56b227444f88b45879ea83537aa
aec185afb47e7b20615e5d9d872f3912137528f1
/jitterbuffer/abstract_jb.c
c4b600d647576570891a262eb8245422a8c0f783
[]
no_license
voipmonitor/sniffer
f5e15e70526c1fabe48d385fe5ec917b9eada62b
162d45491d2b110bdbadfc8a8ac6c44aa44493f0
refs/heads/master
2023-08-19T05:23:19.837497
2023-06-22T15:02:07
2023-06-22T15:02:07
18,056,680
204
99
null
2022-09-17T02:23:50
2014-03-24T08:57:35
C++
UTF-8
C
false
false
33,175
c
abstract_jb.c
/* * abstract_jb: common implementation-independent jitterbuffer stuff * * Copyright (C) 2005, Attractel OOD * * Contributors: * Slav Klenov <slav@securax.org> * * See http://www.asterisk.org for more information about * the Asterisk project. Please do not directly contact * any of the maintainers of this project for assistance; * the project provides a web site, mailing lists and IRC * channels for your use. * * This program is free software, distributed under the terms of * the GNU General Public License Version 2. See the LICENSE file * at the top of the source tree. * * A license has been granted to Digium (via disclaimer) for the use of * this code. */ /*! \file * * \brief Common implementation-independent jitterbuffer stuff. * * \author Slav Klenov <slav@securax.org> */ #include "asterisk.h" #include <stdio.h> #include <stdlib.h> #include <syslog.h> #include "asterisk/frame.h" #include "asterisk/channel.h" #include "asterisk/logger.h" #include "asterisk/term.h" #include "asterisk/options.h" #include "asterisk/utils.h" #include "asterisk/time.h" #include "asterisk/abstract_jb.h" #include "fixedjitterbuf.h" #include "jitterbuf.h" #include "../codecs.h" #include "../common.h" #define JB_LONGMAX 2147483647L #define ONLY_RAW 0 extern struct sVerbose sverb; /*! \brief On and Off plc*/ extern int opt_disableplc ; extern int opt_fix_packetization_in_create_audio; extern int opt_ignore_mos_degradation_for_contiguous_packet_loss_greater_than; /*! Internal jb flags */ enum { JB_USE = (1 << 0), JB_TIMEBASE_INITIALIZED = (1 << 1), JB_CREATED = (1 << 2) }; /* Hooks for the abstract jb implementation */ /*! \brief Create */ typedef void * (*jb_create_impl)(struct ast_jb_conf *general_config, long resynch_threshold, struct ast_channel *channel); /*! \brief Destroy */ typedef void (*jb_destroy_impl)(void *jb); /*! \brief Put first frame */ typedef int (*jb_put_first_impl)(void *jb, struct ast_frame *fin, long now); /*! \brief Put frame */ typedef int (*jb_put_impl)(void *jb, struct ast_frame *fin, long now); /*! \brief Get frame for now */ typedef int (*jb_get_impl)(void *jb, struct ast_frame **fout, long now, long interpl); /*! \brief Get next */ typedef long (*jb_next_impl)(void *jb); /*! \brief Remove first frame */ typedef int (*jb_remove_impl)(void *jb, struct ast_frame **fout); /*! \brief Force resynch */ typedef void (*jb_force_resynch_impl)(void *jb); /*! \brief Empty and reset jb */ typedef void (*jb_empty_and_reset_impl)(void *jb); /*! * \brief Jitterbuffer implementation private struct. */ struct ast_jb_impl { char name[AST_JB_IMPL_NAME_SIZE]; jb_create_impl create; jb_destroy_impl destroy; jb_put_first_impl put_first; jb_put_impl put; jb_get_impl get; jb_next_impl next; jb_remove_impl remove; jb_force_resynch_impl force_resync; jb_empty_and_reset_impl empty_and_reset; }; extern void fifobuff_add(void *fifo_buff, const char *data, unsigned int datalen); //extern void test_raw(const char *descr, const char *data, unsigned int datalen); extern void save_rtp_energylevels(void *rtp_stream, void *data, int datalen, int codec); /* Implementation functions */ /* fixed */ static void * jb_create_fixed(struct ast_jb_conf *general_config, long resynch_threshold, struct ast_channel *chan); static void jb_destroy_fixed(void *jb); static int jb_put_first_fixed(void *jb, struct ast_frame *fin, long now); static int jb_put_fixed(void *jb, struct ast_frame *fin, long now); static int jb_get_fixed(void *jb, struct ast_frame **fout, long now, long interpl); static long jb_next_fixed(void *jb); static int jb_remove_fixed(void *jb, struct ast_frame **fout); static void jb_force_resynch_fixed(void *jb); static void jb_empty_and_reset_fixed(void *jb); /* adaptive */ static void * jb_create_adaptive(struct ast_jb_conf *general_config, long resynch_threshold, struct ast_channel *chan); static void jb_destroy_adaptive(void *jb); static int jb_put_first_adaptive(void *jb, struct ast_frame *fin, long now); static int jb_put_adaptive(void *jb, struct ast_frame *fin, long now); static int jb_get_adaptive(void *jb, struct ast_frame **fout, long now, long interpl); static long jb_next_adaptive(void *jb); static int jb_remove_adaptive(void *jb, struct ast_frame **fout); static void jb_force_resynch_adaptive(void *jb); static void jb_empty_and_reset_adaptive(void *jb); /* Available jb implementations */ static struct ast_jb_impl avail_impl[] = { { .name = "fixed", .create = jb_create_fixed, .destroy = jb_destroy_fixed, .put_first = jb_put_first_fixed, .put = jb_put_fixed, .get = jb_get_fixed, .next = jb_next_fixed, .remove = jb_remove_fixed, .force_resync = jb_force_resynch_fixed, .empty_and_reset = jb_empty_and_reset_fixed, }, { .name = "adaptive", .create = jb_create_adaptive, .destroy = jb_destroy_adaptive, .put_first = jb_put_first_adaptive, .put = jb_put_adaptive, .get = jb_get_adaptive, .next = jb_next_adaptive, .remove = jb_remove_adaptive, .force_resync = jb_force_resynch_adaptive, .empty_and_reset = jb_empty_and_reset_adaptive, } }; //static int default_impl = 1; /*! Abstract return codes */ enum { JB_IMPL_OK, JB_IMPL_DROP, JB_IMPL_INTERP, JB_IMPL_NOFRAME, JB_IMPL_ERROR }; /* Translations between impl and abstract return codes */ static int fixed_to_abstract_code[] = {JB_IMPL_OK, JB_IMPL_DROP, JB_IMPL_INTERP, JB_IMPL_NOFRAME, JB_IMPL_ERROR}; static int adaptive_to_abstract_code[] = {JB_IMPL_OK, JB_IMPL_NOFRAME, JB_IMPL_NOFRAME, JB_IMPL_INTERP, JB_IMPL_DROP, JB_IMPL_OK}; /* JB_GET actions (used only for the frames log) */ static char *jb_get_actions[] = {"Delivered", "Dropped", "Interpolated", "No"}; /*! \brief Macros for the frame log files */ #define printf(...) do { \ if (jb->logfile) { \ if(sverb.jitter) fprintf(jb->logfile, __VA_ARGS__); \ fflush(jb->logfile); \ } \ } while (0) //#define if(sverb.jitter) fprintf(...) if (sverb.jitter) { if(sverb.jitter) fprintf(__VA_ARGS__); } /* Internal utility functions */ static void jb_choose_impl(struct ast_channel *chan); static void jb_get_and_deliver(struct ast_channel *chan, struct timeval *mynow); static int create_jb(struct ast_channel *chan, struct ast_frame *first_frame, struct timeval *mynow); static long get_now(struct ast_jb *jb, struct timeval *tv, struct timeval *mynow); /* Interface ast jb functions impl */ static void jb_choose_impl(struct ast_channel *chan) { struct ast_jb *jb = &chan->jb; struct ast_jb_conf *jbconf = &jb->conf; struct ast_jb_impl *test_impl; int i, avail_impl_count = sizeof(avail_impl) / sizeof(avail_impl[0]); //jb->impl = &avail_impl[default_impl]; jb->impl = &avail_impl[chan->jitter_impl]; if (ast_strlen_zero(jbconf->impl)) return; for (i = 0; i < avail_impl_count; i++) { test_impl = &avail_impl[i]; if (!strcasecmp(jbconf->impl, test_impl->name)) { jb->impl = test_impl; return; } } } int ast_jb_test(struct ast_channel *c0) { struct ast_jb *jb0 = &c0->jb; return ast_test_flag(jb0, JB_CREATED); } int ast_jb_do_usecheck(struct ast_channel *c0, struct timeval *ts) { struct ast_jb *jb0 = &c0->jb; int c0_jb_timebase_initialized = ast_test_flag(jb0, JB_TIMEBASE_INITIALIZED); int c0_jb_created = ast_test_flag(jb0, JB_CREATED); int inuse = 0; /* Determine whether audio going to c0 needs a jitter buffer */ ast_set_flag(jb0, JB_USE); if (!c0_jb_timebase_initialized) { //gettimeofday(&jb0->timebase, NULL); memcpy(&jb0->timebase, ts, sizeof(struct timeval)); ast_set_flag(jb0, JB_TIMEBASE_INITIALIZED); } if (!c0_jb_created) { jb_choose_impl(c0); } inuse = 1; /* Determine whether audio going to c1 needs a jitter buffer */ /* if (((!c1_wants_jitter && c0_creates_jitter) || (c1_force_jb && c0_creates_jitter)) && c1_jb_enabled) { ast_set_flag(jb1, JB_USE); if (!c1_jb_timebase_initialized) { if (c0_jb_timebase_initialized) { memcpy(&jb1->timebase, &jb0->timebase, sizeof(struct timeval)); } else { gettimeofday(&jb1->timebase, NULL); } ast_set_flag(jb1, JB_TIMEBASE_INITIALIZED); } if (!c1_jb_created) { jb_choose_impl(c1); } inuse = 1; } */ return inuse; } int ast_jb_put(struct ast_channel *chan, struct ast_frame *f, struct timeval *mynow) { struct ast_jb *jb = &chan->jb; struct ast_jb_impl *jbimpl = jb->impl; void *jbobj = jb->jbobj; struct ast_frame *frr; long now = 0; int rslt; // if (!ast_test_flag(jb, JB_USE)) // return -1; if (f->frametype != AST_FRAME_VOICE) { if (f->frametype == AST_FRAME_DTMF && ast_test_flag(jb, JB_CREATED)) { if(sverb.jitter) fprintf(stdout, "JB_PUT[%p] {now=%ld}: Received DTMF frame.\n", jb, now); /* this is causing drops if RAW data is recording. deactivate it. Hope it will not cause problems (tested on previously recorded DTMF pcap patterns and it is the same) //if(sverb.jitter) fprintf(stdout, "JB_PUT {now=%ld}: Received DTMF frame. Force resynching jb...\n", now); if(ast_test_flag(jb, JB_CREATED)) { jbimpl->force_resync(jbobj); } */ chan->prev_frame_is_dtmf = 1; } return -1; } if (chan->resync && f->marker) { if(sverb.jitter) fprintf(stdout, "JB_PUT[%p] {now=%ld}: marker bit set, Force resynching jb...\n", jb, now); if(ast_test_flag(jb, JB_CREATED)) { jbimpl->force_resync(jbobj); } } /* We consider an enabled jitterbuffer should receive frames with valid timing info. */ if (f->len < 2 || f->ts < 0) { if(sverb.jitter) fprintf(stdout, "recieved frame with invalid timing info: " "has_timing_info=%d, len=%ld, ts=%ld, src=%s\n", ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO), f->len, f->ts, f->src); return -1; } frr = ast_frdup(f); if (!frr) { if(sverb.jitter) fprintf(stdout, "Failed to isolate frame for the jitterbuffer on channel\n"); return -1; } if (!ast_test_flag(jb, JB_CREATED)) { if (create_jb(chan, frr, mynow)) { ast_frfree(frr); /* Disable the jitterbuffer */ ast_clear_flag(jb, JB_USE); return -1; } ast_set_flag(jb, JB_CREATED); return 0; } else { //fprintf(stdout, "mynow [%u][%u], tb [%u][%u] tvdiff[%u] seq[%u]\n", mynow->tv_sec, mynow->tv_usec, jb->timebase.tv_sec, jb->timebase.tv_usec, ast_tvdiff_ms(*mynow, jb->timebase), frr->seqno); now = get_now(jb, NULL, mynow); rslt = jbimpl->put(jbobj, frr, now); if(frr->frametype != AST_FRAME_DTMF) { chan->prev_frame_is_dtmf = 0; } if (rslt != JB_IMPL_OK) { if(sverb.jitter) fprintf(stdout, "JB_PUT[%p] {now=%ld}: Dropped frame with ts=%ld and len=%ld and seq=%d\n", jb, now, frr->ts, frr->len, frr->seqno); ast_frfree(frr); /*return -1;*/ /* TODO: Check this fix - should return 0 here, because the dropped frame shouldn't be delivered at all */ return 0; } jb->next = jbimpl->next(jbobj); if(sverb.jitter) fprintf(stdout, "JB_PUT[%p] {now=%ld}: Queued frame with ts=%ld and len=%ld and seq=%d\n", jb, now, frr->ts, frr->len, frr->seqno); return 0; } } void ast_jb_get_and_deliver(struct ast_channel *c0, struct timeval *mynow) { struct ast_jb *jb0 = &c0->jb; int c0_use_jb = ast_test_flag(jb0, JB_USE); int c0_jb_is_created = ast_test_flag(jb0, JB_CREATED); if (c0_use_jb && c0_jb_is_created) { if(mynow->tv_sec < c0->jb.timebase.tv_sec || (mynow->tv_sec == c0->jb.timebase.tv_sec && mynow->tv_usec < c0->jb.timebase.tv_usec)) { syslog(LOG_NOTICE, "warning - mynow < c0->jb.timebase in ast_jb_get_and_deliver - ignored"); } else { jb_get_and_deliver(c0, mynow); } } } void jb_fixed_flush_deliver(struct ast_channel *chan) { struct ast_jb *jb = &chan->jb; struct ast_frame *f; struct fixed_jb_frame ff; short int stmp; if(!(struct fixed_jb*)jb->jbobj) { return; } while ( fixed_jb_flush((struct fixed_jb*)jb->jbobj, &ff)) { f = ff.data; if(!f->ignore && (chan->rawstream || chan->audiobuf) && (chan->codec != 13 && chan->codec != 19)) { //write frame to file stmp = (short int)f->datalen; if(CODEC_LEN && (chan->codec == PAYLOAD_G72218 || chan->codec == PAYLOAD_G722112 || chan->codec == PAYLOAD_G722116 || chan->codec == PAYLOAD_G722124 || chan->codec == PAYLOAD_G722132 || chan->codec == PAYLOAD_G722148 || chan->codec == PAYLOAD_OPUS8 || chan->codec == PAYLOAD_OPUS12 || chan->codec == PAYLOAD_OPUS16 || chan->codec == PAYLOAD_OPUS24 || chan->codec == PAYLOAD_OPUS48 || chan->codec == PAYLOAD_ISAC16 || chan->codec == PAYLOAD_ISAC32 || chan->codec == PAYLOAD_SILK || chan->codec == PAYLOAD_SILK8 || chan->codec == PAYLOAD_SILK12 || chan->codec == PAYLOAD_SILK16 || chan->codec == PAYLOAD_SILK24 || chan->codec == PAYLOAD_SPEEX || chan->codec == PAYLOAD_G723 || chan->codec == PAYLOAD_G729 || chan->codec == PAYLOAD_GSM || chan->codec == PAYLOAD_AMR || chan->codec == PAYLOAD_AMRWB || chan->codec == PAYLOAD_EVS)) { if(chan->rawstream) { #if ONLY_RAW == 0 fwrite(&stmp, 1, sizeof(short int), chan->rawstream); // write packet len #endif } } if(chan->rawstream) fwrite(f->data, 1, f->datalen, chan->rawstream); if(chan->audiobuf) fifobuff_add(chan->audiobuf, f->data, f->datalen); //test_raw("flush", f->data, f->datalen); //save last frame if(!chan->lastbuf) { chan->lastbufsize = f->datalen > 1600 ? f->datalen : 1600; chan->lastbuf = (char*)ast_malloc(chan->lastbufsize); } else if(chan->lastbufsize < f->datalen) { ast_free(chan->lastbuf); chan->lastbufsize = f->datalen; chan->lastbuf = (char*)ast_malloc(chan->lastbufsize); } memcpy(chan->lastbuf, f->data, f->datalen); chan->lastbuflen = f->datalen; } if(!f->ignore && chan->enable_save_energylevels && chan->rtp_stream && (chan->codec == 0 || chan->codec == 8)) { save_rtp_energylevels(chan->rtp_stream, f->data, f->datalen, chan->codec); chan->last_datalen_energylevels = f->datalen; } ast_frfree(f); } } void save_empty_frame(struct ast_channel *chan) { if((chan->rawstream || chan->audiobuf) && (chan->codec != 13 && chan->codec != 19)) { int i; //write frame to file if(chan->codec == PAYLOAD_G72218 || chan->codec == PAYLOAD_G722112 || chan->codec == PAYLOAD_G722116 || chan->codec == PAYLOAD_G722124 || chan->codec == PAYLOAD_G722132 || chan->codec == PAYLOAD_G722148 || chan->codec == PAYLOAD_OPUS8 || chan->codec == PAYLOAD_OPUS12 || chan->codec == PAYLOAD_OPUS16 || chan->codec == PAYLOAD_OPUS24 || chan->codec == PAYLOAD_OPUS48 || chan->codec == PAYLOAD_ISAC16 || chan->codec == PAYLOAD_ISAC32 || chan->codec == PAYLOAD_SILK || chan->codec == PAYLOAD_SILK8 || chan->codec == PAYLOAD_SILK12 || chan->codec == PAYLOAD_SILK16 || chan->codec == PAYLOAD_SILK24 || chan->codec == PAYLOAD_SPEEX || chan->codec == PAYLOAD_G723 || chan->codec == PAYLOAD_G729 || chan->codec == PAYLOAD_GSM || chan->codec == PAYLOAD_AMR || chan->codec == PAYLOAD_AMRWB || chan->codec == PAYLOAD_EVS) { if(chan->codec == PAYLOAD_G723) { #if ONLY_RAW == 0 short int zero = 0; for(i = 1; (i * 30) <= chan->packetization; i++) { if(chan->rawstream) fwrite(&zero, 1, sizeof(short int), chan->rawstream); // write zero packet if(chan->audiobuf) fifobuff_add(chan->audiobuf,(const char*)(&zero), sizeof(short int)); //test_raw("empty frame", (const char*)(&zero), sizeof(short int)); } #endif } else if(chan->codec == PAYLOAD_G729) { short int zero = 0; for(i = 1; (i * 10) <= chan->packetization; i++) { if(chan->rawstream) fwrite(&zero, 1, sizeof(short int), chan->rawstream); // write zero packet if(chan->audiobuf) fifobuff_add(chan->audiobuf,(const char*)(&zero), sizeof(short int)); //test_raw("empty frame", (const char*)(&zero), sizeof(short int)); } } else { short int zero = 0; for(i = 1; (i * 20) <= chan->packetization ; i++) { if(chan->rawstream) fwrite(&zero, 1, sizeof(short int), chan->rawstream); // write zero packet if(chan->audiobuf) fifobuff_add(chan->audiobuf,(const char*)(&zero), sizeof(short int)); //test_raw("empty frame", (const char*)(&zero), sizeof(short int)); } } } else { // write previouse frame (better than zero frame), but only once unsigned pcm_datalen = 0; if(chan->codec == PAYLOAD_PCMA || chan->codec == PAYLOAD_PCMU) { pcm_datalen = 8000 * chan->packetization / 1000;; } if(chan->lastbuflen && opt_disableplc == 0 && (!opt_fix_packetization_in_create_audio || !(chan->codec == PAYLOAD_PCMA || chan->codec == PAYLOAD_PCMU) || chan->lastbuflen == pcm_datalen)) { if(chan->rawstream) fwrite(chan->lastbuf, 1, chan->lastbuflen, chan->rawstream); if(chan->audiobuf) fifobuff_add(chan->audiobuf,chan->lastbuf, chan->lastbuflen); //test_raw("empty frame", chan->lastbuf, chan->lastbuflen); chan->lastbuflen = 0; } else { // write empty frame if(chan->codec == PAYLOAD_PCMA || chan->codec == PAYLOAD_PCMU) { unsigned char zero = chan->codec == PAYLOAD_PCMA ? 213 : 255; for(i = 0; i < (opt_fix_packetization_in_create_audio ? pcm_datalen : chan->last_datalen); i++) { if(chan->rawstream) fwrite(&zero, 1, 1, chan->rawstream); if(chan->audiobuf) fifobuff_add(chan->audiobuf,(const char*)(&zero), sizeof(char)); //test_raw("empty frame", (const char*)(&zero), sizeof(char)); } } else { unsigned short int zero = chan->codec == PAYLOAD_G722 ? 65535 : 32767; short int zero_audiobuff = 0; for(i = 0; i < chan->last_datalen / 2; i++) { if(chan->rawstream) fwrite(&zero, 2, 1, chan->rawstream); if(chan->audiobuf) fifobuff_add(chan->audiobuf,(const char*)(&zero_audiobuff), sizeof(char)); //test_raw("empty frame", (const char*)(&zero_audiobuff), sizeof(char)); } } } } } if(chan->enable_save_energylevels && chan->rtp_stream && (chan->codec == 0 || chan->codec == 8) && (chan->last_datalen_energylevels > 0 || chan->last_datalen > 0)) { save_rtp_energylevels(chan->rtp_stream, NULL, 0, chan->codec); } } static void jb_get_and_deliver(struct ast_channel *chan, struct timeval *mynow) { struct ast_jb *jb = &chan->jb; struct ast_jb_impl *jbimpl = jb->impl; void *jbobj = jb->jbobj; //struct ast_frame *f, finterp = { .frametype = AST_FRAME_VOICE, }; struct ast_frame *f; long now; int interpolation_len, res; short int stmp; //int res2; int i; now = get_now(jb, NULL, mynow); jb->next = jbimpl->next(jbobj); //if jb-next return JB_LONGMAX it means the buffer is empty //if (now < jb->next && jb->next != JB_LONGMAX) { if (jb->next == JB_LONGMAX) { //adaptive jitterbuffer is empty - interpolate frame save_empty_frame(chan); interpolation_len = chan->packetization; if(sverb.jitter) fprintf(stdout, "\tJB_GET[%p] {now=%ld next=%ld}: Interpolated frame with len=%d\n", jb, now, jb->next, interpolation_len); chan->last_loss_burst++; return; } else if (now < jb->next ) { // here we are buffering frames if(sverb.jitter) fprintf(stdout, "\tJB_GET[%p] {now=%ld}: now < next=%ld (still buffering)\n", jb, now, jb->next); save_empty_frame(chan); return; } while (now >= jb->next) { //interpolation_len = ast_codec_interp_len(jb->last_format); interpolation_len = chan->packetization; res = jbimpl->get(jbobj, &f, now, interpolation_len); switch(res) { case JB_IMPL_OK: if(f->skip) { save_empty_frame(chan); if(sverb.jitter) fprintf(stdout, "\tJB_GET[%p] {now=%ld}: Skip frame\n", jb, now); ast_frfree(f); break; } if(f->ignore) { break; } /* deliver the frame */ if((chan->rawstream || chan->audiobuf) && f->data && f->datalen > 0 && (chan->codec != 13 && chan->codec != 19)) { //write frame to file stmp = (short int)f->datalen; if(chan->codec == PAYLOAD_G72218 || chan->codec == PAYLOAD_G722112 || chan->codec == PAYLOAD_G722116 || chan->codec == PAYLOAD_G722124 || chan->codec == PAYLOAD_G722132 || chan->codec == PAYLOAD_G722148 || chan->codec == PAYLOAD_OPUS8 || chan->codec == PAYLOAD_OPUS12 || chan->codec == PAYLOAD_OPUS16 || chan->codec == PAYLOAD_OPUS24 || chan->codec == PAYLOAD_OPUS48 || chan->codec == PAYLOAD_ISAC16 || chan->codec == PAYLOAD_ISAC32 || chan->codec == PAYLOAD_SILK || chan->codec == PAYLOAD_SILK8 || chan->codec == PAYLOAD_SILK12 || chan->codec == PAYLOAD_SILK16 || chan->codec == PAYLOAD_SILK24 || chan->codec == PAYLOAD_SPEEX || chan->codec == PAYLOAD_G723 || chan->codec == PAYLOAD_G729 || chan->codec == PAYLOAD_GSM || chan->codec == PAYLOAD_AMR || chan->codec == PAYLOAD_AMRWB || chan->codec == PAYLOAD_EVS) { #if ONLY_RAW == 0 if(chan->rawstream) { fwrite(&stmp, 1, sizeof(short int), chan->rawstream); // write packet len } #endif } if(chan->rawstream) fwrite(f->data, 1, f->datalen, chan->rawstream); if(chan->audiobuf) { fifobuff_add(chan->audiobuf, f->data, f->datalen); } if(opt_fix_packetization_in_create_audio && (chan->codec == PAYLOAD_PCMA || chan->codec == PAYLOAD_PCMU)) { unsigned pcm_datalen = 8000 * chan->packetization / 1000; if(pcm_datalen > f->datalen) { unsigned char zero = chan->codec == PAYLOAD_PCMA ? 213 : 255; for(i = 0; i < (pcm_datalen - f->datalen); i++) { if(chan->rawstream) fwrite(&zero, 1, 1, chan->rawstream); if(chan->audiobuf) fifobuff_add(chan->audiobuf,(const char*)(&zero), sizeof(char)); } } } //test_raw("get", f->data, f->datalen); //save last frame if(!chan->lastbuf) { chan->lastbufsize = f->datalen > 1600 ? f->datalen : 1600; chan->lastbuf = (char*)ast_malloc(chan->lastbufsize); } else if(chan->lastbufsize < f->datalen) { ast_free(chan->lastbuf); chan->lastbufsize = f->datalen; chan->lastbuf = (char*)ast_malloc(chan->lastbufsize); } memcpy(chan->lastbuf, f->data, f->datalen); chan->lastbuflen = f->datalen; } if(chan->enable_save_energylevels && chan->rtp_stream && f->data && f->datalen > 0 && (chan->codec == 0 || chan->codec == 8)) { save_rtp_energylevels(chan->rtp_stream, f->data, f->datalen, chan->codec); chan->last_datalen_energylevels = f->datalen; } if(sverb.jitter) fprintf(stdout, "\tJB_GET[%p] {now=%ld}: %s frame with ts=%ld and len=%ld and seq=%d\n", jb, now, jb_get_actions[res], f->ts, f->len, f->seqno); /* if frame is marked do not put previous interpolated frames to statistics * also if there is no seqno gaps between frames and time differs * and also if there was dtmf last time * */ if( !(((f->seqno - chan->last_seqno) == 1) && (abs(f->ts - chan->last_ms) > (chan->packetization))) && !f->marker && chan->last_loss_burst > 0 && chan->last_loss_burst < opt_ignore_mos_degradation_for_contiguous_packet_loss_greater_than && f->lastframetype == AST_FRAME_VOICE // if the lastframetype was no frame voice(for example dtmf), do not count packet loss //&& !(chan->codec == PAYLOAD_AMR && f->datalen2 <= 7) // if AMR frame is VAD frame do not count interpolated frames // && !(chan->codec == PAYLOAD_G729 && f->datalen2 <= 12) // if g729 frame is CNG frame do not count interpolated frames ) { while(chan->last_loss_burst > 128) { chan->loss[127]++; if(sverb.jitter) fprintf(stdout, "\tSAVING chan->loss[128] packetization[%d]\n", chan->packetization); chan->last_loss_burst -= 128; } chan->loss[chan->last_loss_burst]++; if(sverb.jitter) fprintf(stdout, "\tSAVING chan->loss[%d] = %d packetization[%d]\n", chan->last_loss_burst, chan->loss[chan->last_loss_burst], chan->packetization); } chan->last_loss_burst = 0; chan->last_seqno = f->seqno; chan->last_ms = f->ts; ast_frfree(f); break; case JB_IMPL_DROP: save_empty_frame(chan); if(sverb.jitter) fprintf(stdout, "\tJB_GET[%p] {now=%ld}: %s frame with ts=%ld and len=%ld seq=%d\n", jb, now, jb_get_actions[res], f->ts, f->len, f->seqno); ast_frfree(f); chan->last_loss_burst++; break; case JB_IMPL_INTERP: /* interpolate a frame */ save_empty_frame(chan); if(sverb.jitter) fprintf(stdout, "\tJB_GET[%p] {now=%ld}: Interpolated frame with len=%d\n", jb, now, interpolation_len); chan->last_loss_burst++; break; case JB_IMPL_NOFRAME: save_empty_frame(chan); if(sverb.jitter) fprintf(stdout, "JB_IMPL_NOFRAME is retuned from the %s jb when now=%ld >= next=%ld, jbnext=%ld!\n", jbimpl->name, now, jb->next, jbimpl->next(jbobj)); if(sverb.jitter) fprintf(stdout, "\tJB_GET[%p] {now=%ld}: No frame for now!?\n", jb, now); chan->last_loss_burst++; return; case JB_IMPL_ERROR: return; default: if(sverb.jitter) fprintf(stdout, "This should never happen!\n"); ast_assert("JB type unknown" == NULL); break; } jb->next = jbimpl->next(jbobj); } } static int create_jb(struct ast_channel *chan, struct ast_frame *frr, struct timeval *mynow) { struct ast_jb *jb = &chan->jb; struct ast_jb_conf *jbconf = &jb->conf; struct ast_jb_impl *jbimpl = jb->impl; void *jbobj; long now; int res; jbobj = jb->jbobj = jbimpl->create(jbconf, jbconf->resync_threshold, chan); if (!jbobj) { if(sverb.jitter) fprintf(stdout, "Failed to create jitterbuffer on channel\n"); return -1; } now = get_now(jb, NULL, mynow); res = jbimpl->put_first(jbobj, frr, now); /* The result of putting the first frame should not differ from OK. However, its possible some implementations (i.e. adaptive's when resynch_threshold is specified) to drop it. */ if (res != JB_IMPL_OK) { if(sverb.jitter) fprintf(stdout, "Failed to put first frame in the jitterbuffer on channel\n"); /* jbimpl->destroy(jbobj); return -1; */ } /* Init next */ jb->next = jbimpl->next(jbobj); /* Init last format for a first time. */ jb->last_format = frr->subclass; if (ast_test_flag(jbconf, AST_JB_LOG)) { if (res == JB_IMPL_OK) { if(sverb.jitter) fprintf(stdout, "JB_PUT_FIRST {now=%ld}: Queued frame with ts=%ld and len=%ld\n", now, frr->ts, frr->len); } else { if(sverb.jitter) fprintf(stdout, "JB_PUT_FIRST {now=%ld}: Dropped frame with ts=%ld and len=%ld seq=%d\n", now, frr->ts, frr->len, frr->seqno); } } //if (option_verbose > 2) if(sverb.jitter) fprintf(stdout, "%s jitterbuffer[%p] created on channel\n", jbimpl->name, jb); /* Free the frame if it has not been queued in the jb */ if (res != JB_IMPL_OK) ast_frfree(frr); return 0; } void ast_jb_destroy(struct ast_channel *chan) { if(chan->lastbuf) { ast_free(chan->lastbuf); chan->lastbuf = NULL; chan->lastbufsize = 0; chan->lastbuflen = 0; chan->last_datalen_energylevels = 0; } struct ast_jb *jb = &chan->jb; struct ast_jb_impl *jbimpl = jb->impl; void *jbobj = jb->jbobj; struct ast_frame *f; if (jb->logfile) { fclose(jb->logfile); jb->logfile = NULL; } if (ast_test_flag(jb, JB_CREATED)) { /* Remove and free all frames still queued in jb */ while (jbimpl->remove(jbobj, &f) == JB_IMPL_OK) { ast_frfree(f); } jbimpl->destroy(jbobj); jb->jbobj = NULL; ast_clear_flag(jb, JB_CREATED); if(sverb.jitter) fprintf(stdout, "%s jitterbuffer destroyed on channel\n", jbimpl->name); } ast_clear_flag(jb, JB_TIMEBASE_INITIALIZED); } static long get_now(struct ast_jb *jb, struct timeval *tv, struct timeval *mynow) { struct timeval now; if (!tv) { tv = &now; memcpy(tv, mynow, sizeof(struct timeval)); //gettimeofday(tv, NULL); } return ast_tvdiff_ms(*tv, jb->timebase); } int ast_jb_read_conf(struct ast_jb_conf *conf, char *varname, char *value) { int prefixlen = sizeof(AST_JB_CONF_PREFIX) - 1; char *name; int tmp; if (strncasecmp(AST_JB_CONF_PREFIX, varname, prefixlen)) return -1; name = varname + prefixlen; if (!strcasecmp(name, AST_JB_CONF_ENABLE)) { ast_set2_flag(conf, ast_true(value), AST_JB_ENABLED); } else if (!strcasecmp(name, AST_JB_CONF_FORCE)) { ast_set2_flag(conf, ast_true(value), AST_JB_FORCED); } else if (!strcasecmp(name, AST_JB_CONF_MAX_SIZE)) { if ((tmp = atoi(value)) > 0) conf->max_size = tmp; } else if (!strcasecmp(name, AST_JB_CONF_RESYNCH_THRESHOLD)) { if ((tmp = atoi(value)) > 0) conf->resync_threshold = tmp; } else if (!strcasecmp(name, AST_JB_CONF_IMPL)) { if (!ast_strlen_zero(value)) snprintf(conf->impl, sizeof(conf->impl), "%s", value); } else if (!strcasecmp(name, AST_JB_CONF_LOG)) { ast_set2_flag(conf, ast_true(value), AST_JB_LOG); } else { return -1; } return 0; } void ast_jb_configure(struct ast_channel *chan, const struct ast_jb_conf *conf) { memcpy(&chan->jb.conf, conf, sizeof(*conf)); } void ast_jb_get_config(const struct ast_channel *chan, struct ast_jb_conf *conf) { memcpy(conf, &chan->jb.conf, sizeof(*conf)); } void ast_jb_empty_and_reset(struct ast_channel *c0) { struct ast_jb *jb0 = &c0->jb; int c0_use_jb = ast_test_flag(jb0, JB_USE); int c0_jb_is_created = ast_test_flag(jb0, JB_CREATED); if (c0_use_jb && c0_jb_is_created && jb0->impl->empty_and_reset) { jb0->impl->empty_and_reset(jb0->jbobj); } } /* Implementation functions */ /* fixed */ static void * jb_create_fixed(struct ast_jb_conf *general_config, long resynch_threshold, struct ast_channel *chan) { struct fixed_jb_conf conf; //conf.jbsize = general_config->max_size; //conf.resync_threshold = resynch_threshold; conf.jbsize = chan->jitter_max; conf.resync_threshold = chan->jitter_resync_threshold; return fixed_jb_new(&conf, chan); } static void jb_destroy_fixed(void *jb) { struct fixed_jb *fixedjb = (struct fixed_jb *) jb; /* destroy the jb */ fixed_jb_destroy(fixedjb); } static int jb_put_first_fixed(void *jb, struct ast_frame *fin, long now) { struct fixed_jb *fixedjb = (struct fixed_jb *) jb; int res; res = fixed_jb_put_first(fixedjb, fin, fin->len, fin->ts, now, fin->marker); return fixed_to_abstract_code[res]; } static int jb_put_fixed(void *jb, struct ast_frame *fin, long now) { struct fixed_jb *fixedjb = (struct fixed_jb *) jb; int res; res = fixed_jb_put(fixedjb, fin, fin->len, fin->ts, now, fin->marker); return fixed_to_abstract_code[res]; } static int jb_get_fixed(void *jb, struct ast_frame **fout, long now, long interpl) { struct fixed_jb *fixedjb = (struct fixed_jb *) jb; struct fixed_jb_frame frame; int res; res = fixed_jb_get(fixedjb, &frame, now, interpl); *fout = frame.data; return fixed_to_abstract_code[res]; } static long jb_next_fixed(void *jb) { struct fixed_jb *fixedjb = (struct fixed_jb *) jb; return fixed_jb_next(fixedjb); } static int jb_remove_fixed(void *jb, struct ast_frame **fout) { struct fixed_jb *fixedjb = (struct fixed_jb *) jb; struct fixed_jb_frame frame; int res; res = fixed_jb_remove(fixedjb, &frame); *fout = frame.data; return fixed_to_abstract_code[res]; } static void jb_force_resynch_fixed(void *jb) { struct fixed_jb *fixedjb = (struct fixed_jb *) jb; fixed_jb_set_force_resynch(fixedjb); } static void jb_empty_and_reset_fixed(void *jb) { struct fixed_jb *fixedjb = jb; struct fixed_jb_frame f; while (fixed_jb_remove(fixedjb, &f) == FIXED_JB_OK) { ast_frfree(f.data); } } /* adaptive */ static void *jb_create_adaptive(struct ast_jb_conf *general_config, long resynch_threshold, struct ast_channel *chan) { jb_conf jbconf; jitterbuf *adaptivejb; adaptivejb = jb_new(); if (adaptivejb) { //jbconf.max_jitterbuf = general_config->max_size; //jbconf.resync_threshold = general_config->resync_threshold; //jbconf.max_contig_interp = 10; jbconf.max_jitterbuf = chan->jitter_max; jbconf.resync_threshold = chan->jitter_resync_threshold; jbconf.max_contig_interp = 10; jb_setconf(adaptivejb, &jbconf); } return adaptivejb; } static void jb_destroy_adaptive(void *jb) { jitterbuf *adaptivejb = (jitterbuf *) jb; jb_destroy(adaptivejb); } static int jb_put_first_adaptive(void *jb, struct ast_frame *fin, long now) { return jb_put_adaptive(jb, fin, now); } static int jb_put_adaptive(void *jb, struct ast_frame *fin, long now) { jitterbuf *adaptivejb = (jitterbuf *) jb; int res; res = jb_put(adaptivejb, fin, JB_TYPE_VOICE, fin->len, fin->ts, now); return adaptive_to_abstract_code[res]; } static int jb_get_adaptive(void *jb, struct ast_frame **fout, long now, long interpl) { jitterbuf *adaptivejb = (jitterbuf *) jb; jb_frame frame; int res; res = jb_get(adaptivejb, &frame, now, interpl); *fout = frame.data; return adaptive_to_abstract_code[res]; } static long jb_next_adaptive(void *jb) { jitterbuf *adaptivejb = (jitterbuf *) jb; return jb_next(adaptivejb); } static int jb_remove_adaptive(void *jb, struct ast_frame **fout) { jitterbuf *adaptivejb = (jitterbuf *) jb; jb_frame frame; int res; res = jb_getall(adaptivejb, &frame); *fout = frame.data; return adaptive_to_abstract_code[res]; } static void jb_force_resynch_adaptive(void *jb) { jb_empty_and_reset_adaptive(jb); } static void jb_empty_and_reset_adaptive(void *jb) { jitterbuf *adaptivejb = jb; jb_frame f; while (jb_getall(adaptivejb, &f) == JB_OK) { ast_frfree(f.data); } jb_reset(adaptivejb); }
9da6f4d697c29205061782301443100133be61d7
95ae7dfa9ee578f1b24a65986ff78bf77ceca0c5
/Engine/lib/curl/docs/examples/multi-event.c
4f61f5e4bee5f14a2b6be332811553fcef14c7e7
[ "curl", "MIT", "LicenseRef-scancode-unknown" ]
permissive
TorqueGameEngines/Torque3D
4e1f6a05cc0928980c8c7c20bcdd680eaa6dcee8
a445a4364664e299196bd551d213844486080145
refs/heads/development
2023-09-03T12:40:40.658487
2023-08-24T14:44:43
2023-08-24T14:44:43
267,440,108
1,192
178
MIT
2023-09-13T14:28:16
2020-05-27T22:35:54
C++
UTF-8
C
false
false
6,193
c
multi-event.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * SPDX-License-Identifier: curl * ***************************************************************************/ /* <DESC> * multi_socket API using libevent * </DESC> */ #include <stdio.h> #include <stdlib.h> #include <event2/event.h> #include <curl/curl.h> struct event_base *base; CURLM *curl_handle; struct event *timeout; typedef struct curl_context_s { struct event *event; curl_socket_t sockfd; } curl_context_t; static void curl_perform(int fd, short event, void *arg); static curl_context_t *create_curl_context(curl_socket_t sockfd) { curl_context_t *context; context = (curl_context_t *) malloc(sizeof(*context)); context->sockfd = sockfd; context->event = event_new(base, sockfd, 0, curl_perform, context); return context; } static void destroy_curl_context(curl_context_t *context) { event_del(context->event); event_free(context->event); free(context); } static void add_download(const char *url, int num) { char filename[50]; FILE *file; CURL *handle; snprintf(filename, 50, "%d.download", num); file = fopen(filename, "wb"); if(!file) { fprintf(stderr, "Error opening %s\n", filename); return; } handle = curl_easy_init(); curl_easy_setopt(handle, CURLOPT_WRITEDATA, file); curl_easy_setopt(handle, CURLOPT_PRIVATE, file); curl_easy_setopt(handle, CURLOPT_URL, url); curl_multi_add_handle(curl_handle, handle); fprintf(stderr, "Added download %s -> %s\n", url, filename); } static void check_multi_info(void) { char *done_url; CURLMsg *message; int pending; CURL *easy_handle; FILE *file; while((message = curl_multi_info_read(curl_handle, &pending))) { switch(message->msg) { case CURLMSG_DONE: /* Do not use message data after calling curl_multi_remove_handle() and curl_easy_cleanup(). As per curl_multi_info_read() docs: "WARNING: The data the returned pointer points to will not survive calling curl_multi_cleanup, curl_multi_remove_handle or curl_easy_cleanup." */ easy_handle = message->easy_handle; curl_easy_getinfo(easy_handle, CURLINFO_EFFECTIVE_URL, &done_url); curl_easy_getinfo(easy_handle, CURLINFO_PRIVATE, &file); printf("%s DONE\n", done_url); curl_multi_remove_handle(curl_handle, easy_handle); curl_easy_cleanup(easy_handle); if(file) { fclose(file); } break; default: fprintf(stderr, "CURLMSG default\n"); break; } } } static void curl_perform(int fd, short event, void *arg) { int running_handles; int flags = 0; curl_context_t *context; if(event & EV_READ) flags |= CURL_CSELECT_IN; if(event & EV_WRITE) flags |= CURL_CSELECT_OUT; context = (curl_context_t *) arg; curl_multi_socket_action(curl_handle, context->sockfd, flags, &running_handles); check_multi_info(); } static void on_timeout(evutil_socket_t fd, short events, void *arg) { int running_handles; curl_multi_socket_action(curl_handle, CURL_SOCKET_TIMEOUT, 0, &running_handles); check_multi_info(); } static int start_timeout(CURLM *multi, long timeout_ms, void *userp) { if(timeout_ms < 0) { evtimer_del(timeout); } else { if(timeout_ms == 0) timeout_ms = 1; /* 0 means directly call socket_action, but we will do it in a bit */ struct timeval tv; tv.tv_sec = timeout_ms / 1000; tv.tv_usec = (timeout_ms % 1000) * 1000; evtimer_del(timeout); evtimer_add(timeout, &tv); } return 0; } static int handle_socket(CURL *easy, curl_socket_t s, int action, void *userp, void *socketp) { curl_context_t *curl_context; int events = 0; switch(action) { case CURL_POLL_IN: case CURL_POLL_OUT: case CURL_POLL_INOUT: curl_context = socketp ? (curl_context_t *) socketp : create_curl_context(s); curl_multi_assign(curl_handle, s, (void *) curl_context); if(action != CURL_POLL_IN) events |= EV_WRITE; if(action != CURL_POLL_OUT) events |= EV_READ; events |= EV_PERSIST; event_del(curl_context->event); event_assign(curl_context->event, base, curl_context->sockfd, events, curl_perform, curl_context); event_add(curl_context->event, NULL); break; case CURL_POLL_REMOVE: if(socketp) { event_del(((curl_context_t*) socketp)->event); destroy_curl_context((curl_context_t*) socketp); curl_multi_assign(curl_handle, s, NULL); } break; default: abort(); } return 0; } int main(int argc, char **argv) { if(argc <= 1) return 0; if(curl_global_init(CURL_GLOBAL_ALL)) { fprintf(stderr, "Could not init curl\n"); return 1; } base = event_base_new(); timeout = evtimer_new(base, on_timeout, NULL); curl_handle = curl_multi_init(); curl_multi_setopt(curl_handle, CURLMOPT_SOCKETFUNCTION, handle_socket); curl_multi_setopt(curl_handle, CURLMOPT_TIMERFUNCTION, start_timeout); while(argc-- > 1) { add_download(argv[argc], argc); } event_base_dispatch(base); curl_multi_cleanup(curl_handle); event_free(timeout); event_base_free(base); libevent_global_shutdown(); curl_global_cleanup(); return 0; }
2dbf493acb94ba41db91bec4c05a6de2116c496e
e19509bd2548f173aa492d7498812afa28fcfbb5
/src/plist/dir.c
737be0a072a28991d5075ca1adf1504eb075e283
[ "BSD-2-Clause" ]
permissive
stsaz/fmedia
ef28a25e88ef50411014cfc7faef8813a67cf486
6f6d05fde4a6eba2f1fa0d9e194cd2b405258c3e
refs/heads/master
2023-08-19T20:30:03.512098
2023-07-24T16:37:33
2023-07-24T16:37:33
36,122,394
194
28
BSD-2-Clause
2022-07-19T15:09:24
2015-05-23T12:32:52
C
UTF-8
C
false
false
5,135
c
dir.c
/** Directory input. Copyright (c) 2019 Simon Zolin */ #include <fmedia.h> #include <util/path.h> #include <FFOS/dirscan.h> extern const fmed_core *core; extern const fmed_queue *qu; extern int plist_fullname(fmed_filt *d, const ffstr *name, ffstr *dst); int dir_conf(fmed_conf_ctx *ctx); static int dir_open_r(const char *dirname, fmed_filt *d); typedef struct dirconf_t { byte expand; } dirconf_t; static dirconf_t dirconf; static const fmed_conf_arg dir_conf_args[] = { { "expand", FMC_BOOL8, FMC_O(dirconf_t, expand) }, {} }; int dir_conf(fmed_conf_ctx *ctx) { dirconf.expand = 1; fmed_conf_addctx(ctx, &dirconf, dir_conf_args); return 0; } static void* dir_open(fmed_filt *d) { ffdirscan dr = {}; const char *fn, *dirname; fmed_que_entry e, *first, *cur; if (FMED_PNULL == (dirname = d->track->getvalstr(d->trk, "input"))) return NULL; if (dirconf.expand) { dir_open_r(dirname, d); return FMED_FILT_DUMMY; } if (0 != ffdirscan_open(&dr, dirname, 0)) { syserrlog(core, d->trk, "dir", "%s", ffdir_open_S); return NULL; } first = (void*)fmed_getval("queue_item"); cur = first; while (NULL != (fn = ffdirscan_next(&dr))) { ffmem_zero_obj(&e); char *fullname = ffsz_allocfmt("%s/%s", dirname, fn); ffstr_setz(&e.url, fullname); void *prev = cur; cur = (void*)qu->cmdv(FMED_QUE_ADDAFTER, &e, prev); ffmem_free(fullname); qu->cmdv(FMED_QUE_COPYTRACKPROPS, cur, prev); } ffdirscan_close(&dr); qu->cmd(FMED_QUE_RM, first); return FMED_FILT_DUMMY; } /** 'include' filter matches files only. 'exclude' filter matches files & directories. Return TRUE if filename matches user's filename wildcards. */ static ffbool file_matches(fmed_filt *d, const char *fn, ffbool dir) { size_t fnlen = ffsz_len(fn); const ffstr *wc; ffbool ok = 1; if (!dir) { ok = (d->include_files.len == 0); FFARR_WALKT(&d->include_files, wc, ffstr) { if (0 == ffs_wildcard(wc->ptr, wc->len, fn, fnlen, FFS_WC_ICASE)) { ok = 1; break; } } if (!ok) return 0; } FFARR_WALKT(&d->exclude_files, wc, ffstr) { if (0 == ffs_wildcard(wc->ptr, wc->len, fn, fnlen, FFS_WC_ICASE)) { ok = 0; break; } } return ok; } struct dir_ent { char *dir; ffchain_item sib; }; /* . Scan directory . Add files to queue; gather all directories into chain . Get next directory from chain and scan it; new directories will be added after this directory Example: .: (dir1) (dir2) file dir1: (dir1/dir11) dir1/file dir1/dir11/file dir2: dir2/file */ static int dir_open_r(const char *dirname, fmed_filt *d) { ffdirscan dr = {}; const char *fn; fmed_que_entry e, *first, *prev_qent; fffileinfo fi; ffchain chain; ffchain_item *lprev, *lcur; struct dir_ent *de; ffchain mblocks; ffmblk *mblk; ffchain_item *it; char *fullname = NULL; ffchain_init(&mblocks); ffchain_init(&chain); lprev = ffchain_sentl(&chain); lcur = lprev; first = (void*)fmed_getval("queue_item"); prev_qent = first; for (;;) { dbglog(core, d->trk, NULL, "scanning %s", dirname); if (0 != ffdirscan_open(&dr, dirname, 0)) { syserrlog(core, d->trk, NULL, "%s: %s", ffdir_open_S, dirname); goto next; } while (NULL != (fn = ffdirscan_next(&dr))) { ffmem_free(fullname); fullname = ffsz_allocfmt("%s/%s", dirname, fn); if (0 != fffile_infofn(fullname, &fi)) { syserrlog(core, d->trk, NULL, "%s: %s", fffile_info_S, fullname); continue; } if (!file_matches(d, fn, fffile_isdir(fffile_infoattr(&fi)))) continue; if (fffile_isdir(fffile_infoattr(&fi))) { mblk = ffmblk_chain_last(&mblocks); if (mblk == NULL || ffarr_unused(&mblk->buf) == 0) { // allocate a new block with fixed size = 4kb if (NULL == (mblk = ffmblk_chain_push(&mblocks)) || NULL == ffarr_allocT(&mblk->buf, 4096 / sizeof(struct dir_ent), struct dir_ent)) { syserrlog(core, d->trk, NULL, "%s", ffmem_alloc_S); goto end; } } de = ffarr_pushT(&mblk->buf, struct dir_ent); if (NULL == (de->dir = ffsz_alcopyz(fullname))) { syserrlog(core, d->trk, NULL, "%s", ffmem_alloc_S); goto end; } ffchain_append(&de->sib, lprev); lprev = &de->sib; continue; } ffmem_zero_obj(&e); ffstr_setz(&e.url, fullname); void *cur = (void*)qu->cmdv(FMED_QUE_ADDAFTER | FMED_QUE_MORE, &e, prev_qent); qu->cmdv(FMED_QUE_COPYTRACKPROPS, cur, prev_qent); prev_qent = cur; } ffdirscan_close(&dr); ffmem_zero_obj(&dr); next: lcur = lcur->next; if (lcur == ffchain_sentl(&chain)) break; de = FF_GETPTR(struct dir_ent, sib, lcur); dirname = de->dir; lprev = lcur; } end: qu->cmd2(FMED_QUE_ADD | FMED_QUE_ADD_DONE, NULL, 0); ffdirscan_close(&dr); FFCHAIN_FOR(&mblocks, it) { mblk = FF_GETPTR(ffmblk, sib, it); it = it->next; FFARR_WALKT(&mblk->buf, de, struct dir_ent) { ffmem_safefree(de->dir); } ffmblk_free(mblk); } qu->cmd(FMED_QUE_RM, first); ffmem_free(fullname); return 0; } static void dir_close(void *ctx) { } static int dir_process(void *ctx, fmed_filt *d) { return FMED_RFIN; } const fmed_filter fmed_dir_input = { dir_open, dir_process, dir_close };
99203acbe4e9ba0c57382a8fd4da29837479c2a2
d9e96244515264268d6078650fa707f34d94ee7a
/Working/Game/xleres/Deferred/resolvertshadows.h
43a809c45b77f4726390e041dd3b5b07e87bc8e8
[ "MIT" ]
permissive
xlgames-inc/XLE
45c89537c10561e216367a2e3bcd7d1c92b1b039
69cc4f2aa4faf12ed15bb4291c6992c83597899c
refs/heads/master
2022-06-29T17:16:11.491925
2022-05-04T00:29:28
2022-05-04T00:29:28
29,281,799
396
102
null
2016-01-04T13:35:59
2015-01-15T05:07:55
C++
UTF-8
C
false
false
6,067
h
resolvertshadows.h
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #if !defined(RESOLVE_RT_SHADOWS_H) #define RESOLVE_RT_SHADOWS_H #define OPTIMISED_TRI 1 struct RTSListNode { uint next; uint triIndex; }; struct RTSTriangle { #if (OPTIMISED_TRI==1) float2 a, v0, v1; float d00, d01, d11, invDenom; float3 depths; #else float4 corners[3]; #endif }; Texture2D<uint> RTSListsHead; StructuredBuffer<RTSListNode> RTSLinkedLists; ByteAddressBuffer RTSTriangles; RTSTriangle GetTriangle(uint index) { // Our "RTSTriangles" buffer is written by a // stream output shader (so it is really a vertex buffer) // Because it is a vertex buffer, we can't bind it as // a structured buffer -- it can only be a byte address buffer. // As a result, we need a bit of decompression work... #if (OPTIMISED_TRI==1) uint base = index * 52; RTSTriangle result; result.a.x = asfloat(RTSTriangles.Load(base+ 0)); result.a.y = asfloat(RTSTriangles.Load(base+ 4)); result.v0.x = asfloat(RTSTriangles.Load(base+ 8)); result.v0.y = asfloat(RTSTriangles.Load(base+12)); result.v1.x = asfloat(RTSTriangles.Load(base+16)); result.v1.y = asfloat(RTSTriangles.Load(base+20)); result.d00 = asfloat(RTSTriangles.Load(base+24)); result.d01 = asfloat(RTSTriangles.Load(base+28)); result.d11 = asfloat(RTSTriangles.Load(base+32)); result.invDenom = asfloat(RTSTriangles.Load(base+36)); result.depths.x = asfloat(RTSTriangles.Load(base+40)); result.depths.y = asfloat(RTSTriangles.Load(base+44)); result.depths.z = asfloat(RTSTriangles.Load(base+48)); #else uint base = index * 4 * 3 * 4; RTSTriangle result; result.corners[0].x = asfloat(RTSTriangles.Load(base+ 0)); result.corners[0].y = asfloat(RTSTriangles.Load(base+ 4)); result.corners[0].z = asfloat(RTSTriangles.Load(base+ 8)); result.corners[0].w = asfloat(RTSTriangles.Load(base+12)); result.corners[1].x = asfloat(RTSTriangles.Load(base+16)); result.corners[1].y = asfloat(RTSTriangles.Load(base+20)); result.corners[1].z = asfloat(RTSTriangles.Load(base+24)); result.corners[1].w = asfloat(RTSTriangles.Load(base+28)); result.corners[2].x = asfloat(RTSTriangles.Load(base+32)); result.corners[2].y = asfloat(RTSTriangles.Load(base+36)); result.corners[2].z = asfloat(RTSTriangles.Load(base+40)); result.corners[2].w = asfloat(RTSTriangles.Load(base+44)); #endif return result; } float DirSign2D(float2 p1, float2 p2, float2 p3) { return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y); } bool IsPointInTri2D(float2 pt, float2 a, float2 b, float2 c) { bool t0 = DirSign2D(pt, a, b) < 0.0f; bool t1 = DirSign2D(pt, b, c) < 0.0f; bool t2 = DirSign2D(pt, c, a) < 0.0f; return ((t0 == t1) && (t1 == t2)); } float3 Barycentric2D(float2 pt, float2 a, float2 b, float2 c) { // precalculate { float2 v0 = b - a, v1 = c - a; float d00 = dot(v0, v0); float d01 = dot(v0, v1); float d11 = dot(v1, v1); float invDenom = 1.0 / (d00 * d11 - d01 * d01); // } float2 v2 = pt - a; float d20 = dot(v2, v0); float d21 = dot(v2, v1); float3 result; result.x = (d11 * d20 - d01 * d21) * invDenom; result.y = (d00 * d21 - d01 * d20) * invDenom; result.z = 1.0f - result.x - result.y; return result; } float3 Barycentric2D(float2 pt, RTSTriangle tri) { float2 v2 = pt - tri.a; float d20 = dot(v2, tri.v0); float d21 = dot(v2, tri.v1); float3 result; result.x = (tri.d11 * d20 - tri.d01 * d21) * tri.invDenom; result.y = (tri.d00 * d21 - tri.d01 * d20) * tri.invDenom; result.z = 1.0f - result.x - result.y; return result; } bool IsShadowedByTriangle(float3 postDivideCoord, uint triIndex) { // note -- we could maybe do a rejection with IsPointInTri2D // before calculating the barycentric coords... that // rejection maybe slightly faster... But would still // have to do the full barycentric calculation anyway. // It's hard to guess what would be the most efficient. #if (OPTIMISED_TRI==1) RTSTriangle tri = GetTriangle(triIndex); float3 bary = Barycentric2D(postDivideCoord.xy, tri); bool baryTest = max(max(1.f-bary.x, 1.f-bary.y), 1.f-bary.z) <= 1.f; #else RTSTriangle tri = GetTriangle(triIndex); float2 A = tri.corners[0].xy / tri.corners[0].w; float2 B = tri.corners[1].xy / tri.corners[1].w; float2 C = tri.corners[2].xy / tri.corners[2].w; float3 bary = Barycentric2D(postDivideCoord.xy, A, B, C); bool baryTest = max(max(1.f-bary.x, 1.f-bary.y), 1.f-bary.z) <= 1.f; #endif if (baryTest) { #if (OPTIMISED_TRI==1) float d = dot(bary.zxy, tri.depths); #else float d = dot(bary.zxy, float3( tri.corners[0].z/tri.corners[0].w, tri.corners[1].z/tri.corners[1].w, tri.corners[2].z/tri.corners[2].w)); #endif return d < (postDivideCoord.z - 2e-5f); } return false; } float ResolveRTShadows(float3 postDivideCoord, int2 randomizerValue) { uint2 dims; RTSListsHead.GetDimensions(dims.x, dims.y); float2 texCoords = float2(0.5f + 0.5f * postDivideCoord.x, 0.5f - 0.5f * postDivideCoord.y); uint2 gridIndex = uint2(texCoords.xy * dims); // todo -- check min/max here uint i = RTSListsHead[gridIndex]; while (i!=0) { if (IsShadowedByTriangle(postDivideCoord, RTSLinkedLists[i-1].triIndex)) return 0.f; i = RTSLinkedLists[i-1].next; } return 1.f; } #endif
1a557ecf88e639b61459110b3aaa7391e6c4e72a
100d31faf4b459bafe51a7f1cc3cbbe694011f91
/examples/libc/ctype/nonspacing.h
63899d15c5fbd9833b4cd239761f8599d65f6ce4
[ "CC0-1.0" ]
permissive
embeddedartistry/embedded-resources
aabbc962ab9354f773caadae5e3945e5c4e364bf
1b25c30902fd34a69ed1001af741d564e8df0df1
refs/heads/master
2023-04-29T22:08:01.069233
2023-04-21T03:32:28
2023-04-21T16:25:23
76,132,197
569
412
CC0-1.0
2023-04-21T16:25:24
2016-12-10T19:11:21
Makefile
UTF-8
C
false
false
6,765
h
nonspacing.h
16, 16, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 16, 16, 32, 16, 16, 16, 33, 34, 35, 36, 37, 38, 39, 16, 16, 40, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 41, 42, 16, 16, 43, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 44, 16, 45, 46, 47, 48, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 49, 16, 16, 50, 51, 16, 52, 16, 16, 16, 16, 16, 16, 16, 16, 53, 16, 16, 16, 16, 16, 54, 55, 16, 16, 16, 16, 56, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 57, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 58, 59, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 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, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 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, 248, 3, 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, 254, 255, 255, 255, 255, 191, 182, 0, 0, 0, 0, 0, 0, 0, 31, 0, 255, 7, 0, 0, 0, 0, 0, 248, 255, 255, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 191, 159, 61, 0, 0, 0, 128, 2, 0, 0, 0, 255, 255, 255, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 255, 1, 0, 0, 0, 0, 0, 0, 248, 15, 0, 0, 0, 192, 251, 239, 62, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 255, 255, 127, 7, 0, 0, 0, 0, 0, 0, 20, 254, 33, 254, 0, 12, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 16, 30, 32, 0, 0, 12, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 16, 134, 57, 2, 0, 0, 0, 35, 0, 6, 0, 0, 0, 0, 0, 0, 16, 190, 33, 0, 0, 12, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 144, 30, 32, 64, 0, 12, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 1, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 193, 61, 96, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 144, 64, 48, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 32, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 92, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 242, 7, 128, 127, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 242, 27, 0, 63, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 160, 2, 0, 0, 0, 0, 0, 0, 254, 127, 223, 224, 255, 254, 255, 255, 255, 31, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 224, 253, 102, 0, 0, 0, 195, 1, 0, 30, 0, 100, 32, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 224, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 0, 0, 0, 28, 0, 0, 0, 12, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 176, 63, 64, 254, 15, 32, 0, 0, 0, 0, 0, 56, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 135, 1, 4, 14, 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, 128, 1, 0, 0, 0, 0, 0, 0, 64, 127, 229, 31, 248, 159, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 208, 23, 4, 0, 0, 0, 0, 248, 15, 0, 3, 0, 0, 0, 60, 11, 0, 0, 0, 0, 0, 0, 64, 163, 3, 0, 0, 0, 0, 0, 0, 240, 207, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 247, 255, 253, 33, 16, 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, 255, 255, 255, 255, 127, 0, 0, 240, 0, 248, 0, 0, 0, 124, 0, 0, 0, 0, 0, 0, 31, 252, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 1, 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, 128, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 0, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 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, 128, 247, 63, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 68, 8, 0, 0, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 255, 255, 3, 0, 0, 0, 0, 0, 192, 63, 0, 0, 128, 255, 3, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 200, 19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 126, 102, 0, 8, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 157, 193, 2, 0, 0, 0, 0, 48, 64, 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, 32, 33, 0, 0, 0, 0, 0, 64, 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, 255, 255, 0, 0, 127, 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, 128, 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, 14, 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, 32, 110, 240, 0, 0, 0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 255, 127, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 120, 38, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 128, 239, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 192, 127, 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, 40, 191, 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, 128, 7, 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, 128, 3, 248, 255, 231, 15, 0, 0, 0, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
ca798984b913e00a849f341d96ed4259e893d7f2
2d11442aa09b51e10c245ee2b64231aeb051744f
/platforms/unix/npsqueak/include/npupp.h
780d1cd9526037fb80162113b7540c4df5c3de5d
[ "MIT" ]
permissive
OpenSmalltalk/opensmalltalk-vm
622b01c10017a93fdff4f1ef2188c45342384c78
330d6779ad2ecbce1f07131f53d75cd168165f0b
refs/heads/Cog
2023-09-04T05:36:54.320281
2023-08-17T11:32:52
2023-08-31T12:26:44
59,481,716
556
153
NOASSERTION
2023-06-19T19:58:13
2016-05-23T12:40:27
C
UTF-8
C
false
false
31,691
h
npupp.h
/* -*- Mode: C; tab-width: 4; -*- */ /* * npupp.h $Revision: 1.3 $ * function call mecahnics needed by platform specific glue code. */ #ifndef _NPUPP_H_ #define _NPUPP_H_ #ifndef GENERATINGCFM #define GENERATINGCFM 0 #endif #ifndef _NPAPI_H_ #include "npapi.h" #endif #include "jri.h" /****************************************************************************************** plug-in function table macros for each function in and out of the plugin API we define typedef NPP_FooUPP #define NewNPP_FooProc #define CallNPP_FooProc for mac, define the UPP magic for PPC/68K calling *******************************************************************************************/ /* NPP_Initialize */ #if GENERATINGCFM typedef UniversalProcPtr NPP_InitializeUPP; enum { uppNPP_InitializeProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(0)) | RESULT_SIZE(SIZE_CODE(0)) }; #define NewNPP_InitializeProc(FUNC) \ (NPP_InitializeUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPP_InitializeProcInfo, GetCurrentArchitecture()) #define CallNPP_InitializeProc(FUNC) \ (void)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPP_InitializeProcInfo) #else typedef void (*NPP_InitializeUPP)(void); #define NewNPP_InitializeProc(FUNC) \ ((NPP_InitializeUPP) (FUNC)) #define CallNPP_InitializeProc(FUNC) \ (*(FUNC))() #endif /* NPP_Shutdown */ #if GENERATINGCFM typedef UniversalProcPtr NPP_ShutdownUPP; enum { uppNPP_ShutdownProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(0)) | RESULT_SIZE(SIZE_CODE(0)) }; #define NewNPP_ShutdownProc(FUNC) \ (NPP_ShutdownUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPP_ShutdownProcInfo, GetCurrentArchitecture()) #define CallNPP_ShutdownProc(FUNC) \ (void)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPP_ShutdownProcInfo) #else typedef void (*NPP_ShutdownUPP)(void); #define NewNPP_ShutdownProc(FUNC) \ ((NPP_ShutdownUPP) (FUNC)) #define CallNPP_ShutdownProc(FUNC) \ (*(FUNC))() #endif /* NPP_New */ #if GENERATINGCFM typedef UniversalProcPtr NPP_NewUPP; enum { uppNPP_NewProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPMIMEType))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(uint16))) | STACK_ROUTINE_PARAMETER(4, SIZE_CODE(sizeof(int16))) | STACK_ROUTINE_PARAMETER(5, SIZE_CODE(sizeof(char **))) | STACK_ROUTINE_PARAMETER(6, SIZE_CODE(sizeof(char **))) | STACK_ROUTINE_PARAMETER(7, SIZE_CODE(sizeof(NPSavedData *))) | RESULT_SIZE(SIZE_CODE(sizeof(NPError))) }; #define NewNPP_NewProc(FUNC) \ (NPP_NewUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPP_NewProcInfo, GetCurrentArchitecture()) #define CallNPP_NewProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7) \ (NPError)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPP_NewProcInfo, \ (ARG1), (ARG2), (ARG3), (ARG4), (ARG5), (ARG6), (ARG7)) #else typedef NPError (*NPP_NewUPP)(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved); #define NewNPP_NewProc(FUNC) \ ((NPP_NewUPP) (FUNC)) #define CallNPP_NewProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7) \ (*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4), (ARG5), (ARG6), (ARG7)) #endif /* NPP_Destroy */ #if GENERATINGCFM typedef UniversalProcPtr NPP_DestroyUPP; enum { uppNPP_DestroyProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPSavedData **))) | RESULT_SIZE(SIZE_CODE(sizeof(NPError))) }; #define NewNPP_DestroyProc(FUNC) \ (NPP_DestroyUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPP_DestroyProcInfo, GetCurrentArchitecture()) #define CallNPP_DestroyProc(FUNC, ARG1, ARG2) \ (NPError)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPP_DestroyProcInfo, (ARG1), (ARG2)) #else typedef NPError (*NPP_DestroyUPP)(NPP instance, NPSavedData** save); #define NewNPP_DestroyProc(FUNC) \ ((NPP_DestroyUPP) (FUNC)) #define CallNPP_DestroyProc(FUNC, ARG1, ARG2) \ (*(FUNC))((ARG1), (ARG2)) #endif /* NPP_SetWindow */ #if GENERATINGCFM typedef UniversalProcPtr NPP_SetWindowUPP; enum { uppNPP_SetWindowProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPWindow *))) | RESULT_SIZE(SIZE_CODE(sizeof(NPError))) }; #define NewNPP_SetWindowProc(FUNC) \ (NPP_SetWindowUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPP_SetWindowProcInfo, GetCurrentArchitecture()) #define CallNPP_SetWindowProc(FUNC, ARG1, ARG2) \ (NPError)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPP_SetWindowProcInfo, (ARG1), (ARG2)) #else typedef NPError (*NPP_SetWindowUPP)(NPP instance, NPWindow* window); #define NewNPP_SetWindowProc(FUNC) \ ((NPP_SetWindowUPP) (FUNC)) #define CallNPP_SetWindowProc(FUNC, ARG1, ARG2) \ (*(FUNC))((ARG1), (ARG2)) #endif /* NPP_NewStream */ #if GENERATINGCFM typedef UniversalProcPtr NPP_NewStreamUPP; enum { uppNPP_NewStreamProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPMIMEType))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(NPStream *))) | STACK_ROUTINE_PARAMETER(4, SIZE_CODE(sizeof(NPBool))) | STACK_ROUTINE_PARAMETER(5, SIZE_CODE(sizeof(uint16 *))) | RESULT_SIZE(SIZE_CODE(sizeof(NPError))) }; #define NewNPP_NewStreamProc(FUNC) \ (NPP_NewStreamUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPP_NewStreamProcInfo, GetCurrentArchitecture()) #define CallNPP_NewStreamProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5) \ (NPError)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPP_NewStreamProcInfo, (ARG1), (ARG2), (ARG3), (ARG4), (ARG5)) #else typedef NPError (*NPP_NewStreamUPP)(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype); #define NewNPP_NewStreamProc(FUNC) \ ((NPP_NewStreamUPP) (FUNC)) #define CallNPP_NewStreamProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5) \ (*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4), (ARG5)) #endif /* NPP_DestroyStream */ #if GENERATINGCFM typedef UniversalProcPtr NPP_DestroyStreamUPP; enum { uppNPP_DestroyStreamProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPStream *))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(NPReason))) | RESULT_SIZE(SIZE_CODE(sizeof(NPError))) }; #define NewNPP_DestroyStreamProc(FUNC) \ (NPP_DestroyStreamUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPP_DestroyStreamProcInfo, GetCurrentArchitecture()) #define CallNPP_DestroyStreamProc(FUNC, NPParg, NPStreamPtr, NPReasonArg) \ (NPError)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPP_DestroyStreamProcInfo, (NPParg), (NPStreamPtr), (NPReasonArg)) #else typedef NPError (*NPP_DestroyStreamUPP)(NPP instance, NPStream* stream, NPReason reason); #define NewNPP_DestroyStreamProc(FUNC) \ ((NPP_DestroyStreamUPP) (FUNC)) #define CallNPP_DestroyStreamProc(FUNC, NPParg, NPStreamPtr, NPReasonArg) \ (*(FUNC))((NPParg), (NPStreamPtr), (NPReasonArg)) #endif /* NPP_WriteReady */ #if GENERATINGCFM typedef UniversalProcPtr NPP_WriteReadyUPP; enum { uppNPP_WriteReadyProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPStream *))) | RESULT_SIZE(SIZE_CODE(sizeof(int32))) }; #define NewNPP_WriteReadyProc(FUNC) \ (NPP_WriteReadyUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPP_WriteReadyProcInfo, GetCurrentArchitecture()) #define CallNPP_WriteReadyProc(FUNC, NPParg, NPStreamPtr) \ (int32)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPP_WriteReadyProcInfo, (NPParg), (NPStreamPtr)) #else typedef int32 (*NPP_WriteReadyUPP)(NPP instance, NPStream* stream); #define NewNPP_WriteReadyProc(FUNC) \ ((NPP_WriteReadyUPP) (FUNC)) #define CallNPP_WriteReadyProc(FUNC, NPParg, NPStreamPtr) \ (*(FUNC))((NPParg), (NPStreamPtr)) #endif /* NPP_Write */ #if GENERATINGCFM typedef UniversalProcPtr NPP_WriteUPP; enum { uppNPP_WriteProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPStream *))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(int32))) | STACK_ROUTINE_PARAMETER(4, SIZE_CODE(sizeof(int32))) | STACK_ROUTINE_PARAMETER(5, SIZE_CODE(sizeof(void*))) | RESULT_SIZE(SIZE_CODE(sizeof(int32))) }; #define NewNPP_WriteProc(FUNC) \ (NPP_WriteUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPP_WriteProcInfo, GetCurrentArchitecture()) #define CallNPP_WriteProc(FUNC, NPParg, NPStreamPtr, offsetArg, lenArg, bufferPtr) \ (int32)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPP_WriteProcInfo, (NPParg), (NPStreamPtr), (offsetArg), (lenArg), (bufferPtr)) #else typedef int32 (*NPP_WriteUPP)(NPP instance, NPStream* stream, int32 offset, int32 len, void* buffer); #define NewNPP_WriteProc(FUNC) \ ((NPP_WriteUPP) (FUNC)) #define CallNPP_WriteProc(FUNC, NPParg, NPStreamPtr, offsetArg, lenArg, bufferPtr) \ (*(FUNC))((NPParg), (NPStreamPtr), (offsetArg), (lenArg), (bufferPtr)) #endif /* NPP_StreamAsFile */ #if GENERATINGCFM typedef UniversalProcPtr NPP_StreamAsFileUPP; enum { uppNPP_StreamAsFileProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPStream *))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(const char *))) | RESULT_SIZE(SIZE_CODE(0)) }; #define NewNPP_StreamAsFileProc(FUNC) \ (NPP_StreamAsFileUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPP_StreamAsFileProcInfo, GetCurrentArchitecture()) #define CallNPP_StreamAsFileProc(FUNC, ARG1, ARG2, ARG3) \ (void)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPP_StreamAsFileProcInfo, (ARG1), (ARG2), (ARG3)) #else typedef void (*NPP_StreamAsFileUPP)(NPP instance, NPStream* stream, const char* fname); #define NewNPP_StreamAsFileProc(FUNC) \ ((NPP_StreamAsFileUPP) (FUNC)) #define CallNPP_StreamAsFileProc(FUNC, ARG1, ARG2, ARG3) \ (*(FUNC))((ARG1), (ARG2), (ARG3)) #endif /* NPP_Print */ #if GENERATINGCFM typedef UniversalProcPtr NPP_PrintUPP; enum { uppNPP_PrintProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPPrint *))) | RESULT_SIZE(SIZE_CODE(0)) }; #define NewNPP_PrintProc(FUNC) \ (NPP_PrintUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPP_PrintProcInfo, GetCurrentArchitecture()) #define CallNPP_PrintProc(FUNC, NPParg, voidPtr) \ (void)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPP_PrintProcInfo, (NPParg), (voidPtr)) #else typedef void (*NPP_PrintUPP)(NPP instance, NPPrint* platformPrint); #define NewNPP_PrintProc(FUNC) \ ((NPP_PrintUPP) (FUNC)) #define CallNPP_PrintProc(FUNC, NPParg, NPPrintArg) \ (*(FUNC))((NPParg), (NPPrintArg)) #endif /* NPP_HandleEvent */ #if GENERATINGCFM typedef UniversalProcPtr NPP_HandleEventUPP; enum { uppNPP_HandleEventProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(void *))) | RESULT_SIZE(SIZE_CODE(sizeof(int16))) }; #define NewNPP_HandleEventProc(FUNC) \ (NPP_HandleEventUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPP_HandleEventProcInfo, GetCurrentArchitecture()) #define CallNPP_HandleEventProc(FUNC, NPParg, voidPtr) \ (int16)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPP_HandleEventProcInfo, (NPParg), (voidPtr)) #else typedef int16 (*NPP_HandleEventUPP)(NPP instance, void* event); #define NewNPP_HandleEventProc(FUNC) \ ((NPP_HandleEventUPP) (FUNC)) #define CallNPP_HandleEventProc(FUNC, NPParg, voidPtr) \ (*(FUNC))((NPParg), (voidPtr)) #endif /* NPP_URLNotify */ #if GENERATINGCFM typedef UniversalProcPtr NPP_URLNotifyUPP; enum { uppNPP_URLNotifyProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(const char*))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(NPReason))) | STACK_ROUTINE_PARAMETER(4, SIZE_CODE(sizeof(void*))) | RESULT_SIZE(SIZE_CODE(SIZE_CODE(0))) }; #define NewNPP_URLNotifyProc(FUNC) \ (NPP_URLNotifyUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPP_URLNotifyProcInfo, GetCurrentArchitecture()) #define CallNPP_URLNotifyProc(FUNC, ARG1, ARG2, ARG3, ARG4) \ (void)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPP_URLNotifyProcInfo, (ARG1), (ARG2), (ARG3), (ARG4)) #else typedef void (*NPP_URLNotifyUPP)(NPP instance, const char* url, NPReason reason, void* notifyData); #define NewNPP_URLNotifyProc(FUNC) \ ((NPP_URLNotifyUPP) (FUNC)) #define CallNPP_URLNotifyProc(FUNC, ARG1, ARG2, ARG3, ARG4) \ (*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4)) #endif /* * Netscape entry points */ #ifdef XP_UNIX /* NPN_GetValue */ #if GENERATINGCFM typedef UniversalProcPtr NPN_GetValueUPP; enum { uppNPN_GetValueProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPNVariable))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(void *))) | RESULT_SIZE(SIZE_CODE(sizeof(NPError))) }; #define NewNPN_GetValueProc(FUNC) \ (NPN_GetValueUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_GetValueProcInfo, GetCurrentArchitecture()) #define CallNPN_GetURNotifyLProc(FUNC, ARG1, ARG2, ARG3) \ (NPError)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_GetValueProcInfo, (ARG1), (ARG2), (ARG3)) #else typedef NPError (*NPN_GetValueUPP)(NPP instance, NPNVariable variable, void *ret_alue); #define NewNPN_GetValueProc(FUNC) \ ((NPN_GetValueUPP) (FUNC)) #define CallNPN_GetValueProc(FUNC, ARG1, ARG2, ARG3) \ (*(FUNC))((ARG1), (ARG2), (ARG3)) #endif #endif /* XP_UNIX */ /* NPN_GetUrlNotify */ #if GENERATINGCFM typedef UniversalProcPtr NPN_GetURLNotifyUPP; enum { uppNPN_GetURLNotifyProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(const char*))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(const char*))) | STACK_ROUTINE_PARAMETER(4, SIZE_CODE(sizeof(void*))) | RESULT_SIZE(SIZE_CODE(sizeof(NPError))) }; #define NewNPN_GetURLNotifyProc(FUNC) \ (NPN_GetURLNotifyUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_GetURLNotifyProcInfo, GetCurrentArchitecture()) #define CallNPN_GetURLNotifyProc(FUNC, ARG1, ARG2, ARG3, ARG4) \ (NPError)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_GetURLNotifyProcInfo, (ARG1), (ARG2), (ARG3), (ARG4)) #else typedef NPError (*NPN_GetURLNotifyUPP)(NPP instance, const char* url, const char* window, void* notifyData); #define NewNPN_GetURLNotifyProc(FUNC) \ ((NPN_GetURLNotifyUPP) (FUNC)) #define CallNPN_GetURLNotifyProc(FUNC, ARG1, ARG2, ARG3, ARG4) \ (*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4)) #endif /* NPN_PostUrlNotify */ #if GENERATINGCFM typedef UniversalProcPtr NPN_PostURLNotifyUPP; enum { uppNPN_PostURLNotifyProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(const char*))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(const char*))) | STACK_ROUTINE_PARAMETER(4, SIZE_CODE(sizeof(uint32))) | STACK_ROUTINE_PARAMETER(5, SIZE_CODE(sizeof(const char*))) | STACK_ROUTINE_PARAMETER(6, SIZE_CODE(sizeof(NPBool))) | STACK_ROUTINE_PARAMETER(7, SIZE_CODE(sizeof(void*))) | RESULT_SIZE(SIZE_CODE(sizeof(NPError))) }; #define NewNPN_PostURLNotifyProc(FUNC) \ (NPN_PostURLNotifyUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_PostURLNotifyProcInfo, GetCurrentArchitecture()) #define CallNPN_PostURLNotifyProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7) \ (NPError)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_PostURLNotifyProcInfo, (ARG1), (ARG2), (ARG3), (ARG4), (ARG5), (ARG6), (ARG7)) #else typedef NPError (*NPN_PostURLNotifyUPP)(NPP instance, const char* url, const char* window, uint32 len, const char* buf, NPBool file, void* notifyData); #define NewNPN_PostURLNotifyProc(FUNC) \ ((NPN_PostURLNotifyUPP) (FUNC)) #define CallNPN_PostURLNotifyProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7) \ (*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4), (ARG5), (ARG6), (ARG7)) #endif /* NPN_GetUrl */ #if GENERATINGCFM typedef UniversalProcPtr NPN_GetURLUPP; enum { uppNPN_GetURLProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(const char*))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(const char*))) | RESULT_SIZE(SIZE_CODE(sizeof(NPError))) }; #define NewNPN_GetURLProc(FUNC) \ (NPN_GetURLUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_GetURLProcInfo, GetCurrentArchitecture()) #define CallNPN_GetURLProc(FUNC, ARG1, ARG2, ARG3) \ (NPError)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_GetURLProcInfo, (ARG1), (ARG2), (ARG3)) #else typedef NPError (*NPN_GetURLUPP)(NPP instance, const char* url, const char* window); #define NewNPN_GetURLProc(FUNC) \ ((NPN_GetURLUPP) (FUNC)) #define CallNPN_GetURLProc(FUNC, ARG1, ARG2, ARG3) \ (*(FUNC))((ARG1), (ARG2), (ARG3)) #endif /* NPN_PostUrl */ #if GENERATINGCFM typedef UniversalProcPtr NPN_PostURLUPP; enum { uppNPN_PostURLProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(const char*))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(const char*))) | STACK_ROUTINE_PARAMETER(4, SIZE_CODE(sizeof(uint32))) | STACK_ROUTINE_PARAMETER(5, SIZE_CODE(sizeof(const char*))) | STACK_ROUTINE_PARAMETER(6, SIZE_CODE(sizeof(NPBool))) | RESULT_SIZE(SIZE_CODE(sizeof(NPError))) }; #define NewNPN_PostURLProc(FUNC) \ (NPN_PostURLUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_PostURLProcInfo, GetCurrentArchitecture()) #define CallNPN_PostURLProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6) \ (NPError)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_PostURLProcInfo, (ARG1), (ARG2), (ARG3), (ARG4), (ARG5), (ARG6)) #else typedef NPError (*NPN_PostURLUPP)(NPP instance, const char* url, const char* window, uint32 len, const char* buf, NPBool file); #define NewNPN_PostURLProc(FUNC) \ ((NPN_PostURLUPP) (FUNC)) #define CallNPN_PostURLProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6) \ (*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4), (ARG5), (ARG6)) #endif /* NPN_RequestRead */ #if GENERATINGCFM typedef UniversalProcPtr NPN_RequestReadUPP; enum { uppNPN_RequestReadProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPStream *))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPByteRange *))) | RESULT_SIZE(SIZE_CODE(sizeof(NPError))) }; #define NewNPN_RequestReadProc(FUNC) \ (NPN_RequestReadUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_RequestReadProcInfo, GetCurrentArchitecture()) #define CallNPN_RequestReadProc(FUNC, stream, range) \ (NPError)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_RequestReadProcInfo, (stream), (range)) #else typedef NPError (*NPN_RequestReadUPP)(NPStream* stream, NPByteRange* rangeList); #define NewNPN_RequestReadProc(FUNC) \ ((NPN_RequestReadUPP) (FUNC)) #define CallNPN_RequestReadProc(FUNC, stream, range) \ (*(FUNC))((stream), (range)) #endif /* NPN_NewStream */ #if GENERATINGCFM typedef UniversalProcPtr NPN_NewStreamUPP; enum { uppNPN_NewStreamProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPMIMEType))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(const char *))) | STACK_ROUTINE_PARAMETER(4, SIZE_CODE(sizeof(NPStream **))) | RESULT_SIZE(SIZE_CODE(sizeof(NPError))) }; #define NewNPN_NewStreamProc(FUNC) \ (NPN_NewStreamUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_NewStreamProcInfo, GetCurrentArchitecture()) #define CallNPN_NewStreamProc(FUNC, npp, type, window, stream) \ (NPError)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_NewStreamProcInfo, (npp), (type), (window), (stream)) #else typedef NPError (*NPN_NewStreamUPP)(NPP instance, NPMIMEType type, const char* window, NPStream** stream); #define NewNPN_NewStreamProc(FUNC) \ ((NPN_NewStreamUPP) (FUNC)) #define CallNPN_NewStreamProc(FUNC, npp, type, window, stream) \ (*(FUNC))((npp), (type), (window), (stream)) #endif /* NPN_Write */ #if GENERATINGCFM typedef UniversalProcPtr NPN_WriteUPP; enum { uppNPN_WriteProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPStream *))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(int32))) | STACK_ROUTINE_PARAMETER(4, SIZE_CODE(sizeof(void*))) | RESULT_SIZE(SIZE_CODE(sizeof(int32))) }; #define NewNPN_WriteProc(FUNC) \ (NPN_WriteUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_WriteProcInfo, GetCurrentArchitecture()) #define CallNPN_WriteProc(FUNC, npp, stream, len, buffer) \ (int32)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_WriteProcInfo, (npp), (stream), (len), (buffer)) #else typedef int32 (*NPN_WriteUPP)(NPP instance, NPStream* stream, int32 len, void* buffer); #define NewNPN_WriteProc(FUNC) \ ((NPN_WriteUPP) (FUNC)) #define CallNPN_WriteProc(FUNC, npp, stream, len, buffer) \ (*(FUNC))((npp), (stream), (len), (buffer)) #endif /* NPN_DestroyStream */ #if GENERATINGCFM typedef UniversalProcPtr NPN_DestroyStreamUPP; enum { uppNPN_DestroyStreamProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP ))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPStream *))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(NPReason))) | RESULT_SIZE(SIZE_CODE(sizeof(NPError))) }; #define NewNPN_DestroyStreamProc(FUNC) \ (NPN_DestroyStreamUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_DestroyStreamProcInfo, GetCurrentArchitecture()) #define CallNPN_DestroyStreamProc(FUNC, npp, stream, reason) \ (NPError)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_DestroyStreamProcInfo, (npp), (stream), (reason)) #else typedef NPError (*NPN_DestroyStreamUPP)(NPP instance, NPStream* stream, NPReason reason); #define NewNPN_DestroyStreamProc(FUNC) \ ((NPN_DestroyStreamUPP) (FUNC)) #define CallNPN_DestroyStreamProc(FUNC, npp, stream, reason) \ (*(FUNC))((npp), (stream), (reason)) #endif /* NPN_Status */ #if GENERATINGCFM typedef UniversalProcPtr NPN_StatusUPP; enum { uppNPN_StatusProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(char *))) }; #define NewNPN_StatusProc(FUNC) \ (NPN_StatusUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_StatusProcInfo, GetCurrentArchitecture()) #define CallNPN_StatusProc(FUNC, npp, msg) \ (void)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_StatusProcInfo, (npp), (msg)) #else typedef void (*NPN_StatusUPP)(NPP instance, const char* message); #define NewNPN_StatusProc(FUNC) \ ((NPN_StatusUPP) (FUNC)) #define CallNPN_StatusProc(FUNC, npp, msg) \ (*(FUNC))((npp), (msg)) #endif /* NPN_UserAgent */ #if GENERATINGCFM typedef UniversalProcPtr NPN_UserAgentUPP; enum { uppNPN_UserAgentProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | RESULT_SIZE(SIZE_CODE(sizeof(const char *))) }; #define NewNPN_UserAgentProc(FUNC) \ (NPN_UserAgentUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_UserAgentProcInfo, GetCurrentArchitecture()) #define CallNPN_UserAgentProc(FUNC, ARG1) \ (const char*)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_UserAgentProcInfo, (ARG1)) #else typedef const char* (*NPN_UserAgentUPP)(NPP instance); #define NewNPN_UserAgentProc(FUNC) \ ((NPN_UserAgentUPP) (FUNC)) #define CallNPN_UserAgentProc(FUNC, ARG1) \ (*(FUNC))((ARG1)) #endif /* NPN_MemAlloc */ #if GENERATINGCFM typedef UniversalProcPtr NPN_MemAllocUPP; enum { uppNPN_MemAllocProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(uint32))) | RESULT_SIZE(SIZE_CODE(sizeof(void *))) }; #define NewNPN_MemAllocProc(FUNC) \ (NPN_MemAllocUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_MemAllocProcInfo, GetCurrentArchitecture()) #define CallNPN_MemAllocProc(FUNC, ARG1) \ (void*)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_MemAllocProcInfo, (ARG1)) #else typedef void* (*NPN_MemAllocUPP)(uint32 size); #define NewNPN_MemAllocProc(FUNC) \ ((NPN_MemAllocUPP) (FUNC)) #define CallNPN_MemAllocProc(FUNC, ARG1) \ (*(FUNC))((ARG1)) #endif /* NPN__MemFree */ #if GENERATINGCFM typedef UniversalProcPtr NPN_MemFreeUPP; enum { uppNPN_MemFreeProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(void *))) }; #define NewNPN_MemFreeProc(FUNC) \ (NPN_MemFreeUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_MemFreeProcInfo, GetCurrentArchitecture()) #define CallNPN_MemFreeProc(FUNC, ARG1) \ (void)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_MemFreeProcInfo, (ARG1)) #else typedef void (*NPN_MemFreeUPP)(void* ptr); #define NewNPN_MemFreeProc(FUNC) \ ((NPN_MemFreeUPP) (FUNC)) #define CallNPN_MemFreeProc(FUNC, ARG1) \ (*(FUNC))((ARG1)) #endif /* NPN_MemFlush */ #if GENERATINGCFM typedef UniversalProcPtr NPN_MemFlushUPP; enum { uppNPN_MemFlushProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(uint32))) | RESULT_SIZE(SIZE_CODE(sizeof(uint32))) }; #define NewNPN_MemFlushProc(FUNC) \ (NPN_MemFlushUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_MemFlushProcInfo, GetCurrentArchitecture()) #define CallNPN_MemFlushProc(FUNC, ARG1) \ (uint32)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_MemFlushProcInfo, (ARG1)) #else typedef uint32 (*NPN_MemFlushUPP)(uint32 size); #define NewNPN_MemFlushProc(FUNC) \ ((NPN_MemFlushUPP) (FUNC)) #define CallNPN_MemFlushProc(FUNC, ARG1) \ (*(FUNC))((ARG1)) #endif /* NPN_ReloadPlugins */ #if GENERATINGCFM typedef UniversalProcPtr NPN_ReloadPluginsUPP; enum { uppNPN_ReloadPluginsProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPBool))) | RESULT_SIZE(SIZE_CODE(0)) }; #define NewNPN_ReloadPluginsProc(FUNC) \ (NPN_ReloadPluginsUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_ReloadPluginsProcInfo, GetCurrentArchitecture()) #define CallNPN_ReloadPluginsProc(FUNC, ARG1) \ (void)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_ReloadPluginsProcInfo, (ARG1)) #else typedef void (*NPN_ReloadPluginsUPP)(NPBool reloadPages); #define NewNPN_ReloadPluginsProc(FUNC) \ ((NPN_ReloadPluginsUPP) (FUNC)) #define CallNPN_ReloadPluginsProc(FUNC, ARG1) \ (*(FUNC))((ARG1)) #endif /* NPN_GetJavaEnv */ #if GENERATINGCFM typedef UniversalProcPtr NPN_GetJavaEnvUPP; enum { uppNPN_GetJavaEnvProcInfo = kThinkCStackBased | RESULT_SIZE(SIZE_CODE(sizeof(JRIEnv*))) }; #define NewNPN_GetJavaEnvProc(FUNC) \ (NPN_GetJavaEnvUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_GetJavaEnvProcInfo, GetCurrentArchitecture()) #define CallNPN_GetJavaEnvProc(FUNC) \ (JRIEnv*)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_GetJavaEnvProcInfo) #else typedef JRIEnv* (*NPN_GetJavaEnvUPP)(void); #define NewNPN_GetJavaEnvProc(FUNC) \ ((NPN_GetJavaEnvUPP) (FUNC)) #define CallNPN_GetJavaEnvProc(FUNC) \ (*(FUNC))() #endif /* NPN_GetJavaPeer */ #if GENERATINGCFM typedef UniversalProcPtr NPN_GetJavaPeerUPP; enum { uppNPN_GetJavaPeerProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPP))) | RESULT_SIZE(SIZE_CODE(sizeof(jref))) }; #define NewNPN_GetJavaPeerProc(FUNC) \ (NPN_GetJavaPeerUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPN_GetJavaPeerProcInfo, GetCurrentArchitecture()) #define CallNPN_GetJavaPeerProc(FUNC, ARG1) \ (jref)CallUniversalProc((UniversalProcPtr)(FUNC), uppNPN_GetJavaPeerProcInfo, (ARG1)) #else typedef jref (*NPN_GetJavaPeerUPP)(NPP instance); #define NewNPN_GetJavaPeerProc(FUNC) \ ((NPN_GetJavaPeerUPP) (FUNC)) #define CallNPN_GetJavaPeerProc(FUNC, ARG1) \ (*(FUNC))((ARG1)) #endif /****************************************************************************************** * The actual plugin function table definitions *******************************************************************************************/ typedef struct _NPPluginFuncs { uint16 size; uint16 version; NPP_NewUPP newp; NPP_DestroyUPP destroy; NPP_SetWindowUPP setwindow; NPP_NewStreamUPP newstream; NPP_DestroyStreamUPP destroystream; NPP_StreamAsFileUPP asfile; NPP_WriteReadyUPP writeready; NPP_WriteUPP write; NPP_PrintUPP print; NPP_HandleEventUPP event; NPP_URLNotifyUPP urlnotify; JRIGlobalRef javaClass; } NPPluginFuncs; typedef struct _NPNetscapeFuncs { uint16 size; uint16 version; NPN_GetURLUPP geturl; NPN_PostURLUPP posturl; NPN_RequestReadUPP requestread; NPN_NewStreamUPP newstream; NPN_WriteUPP write; NPN_DestroyStreamUPP destroystream; NPN_StatusUPP status; NPN_UserAgentUPP uagent; NPN_MemAllocUPP memalloc; NPN_MemFreeUPP memfree; NPN_MemFlushUPP memflush; NPN_ReloadPluginsUPP reloadplugins; NPN_GetJavaEnvUPP getJavaEnv; NPN_GetJavaPeerUPP getJavaPeer; NPN_GetURLNotifyUPP geturlnotify; NPN_PostURLNotifyUPP posturlnotify; #ifdef XP_UNIX NPN_GetValueUPP getvalue; #endif /* XP_UNIX */ } NPNetscapeFuncs; #ifdef XP_MAC /****************************************************************************************** * Mac platform-specific plugin glue stuff *******************************************************************************************/ /* * Main entry point of the plugin. * This routine will be called when the plugin is loaded. The function * tables are passed in and the plugin fills in the NPPluginFuncs table * and NPPShutdownUPP for Netscape's use. */ #if GENERATINGCFM typedef UniversalProcPtr NPP_MainEntryUPP; enum { uppNPP_MainEntryProcInfo = kThinkCStackBased | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(NPNetscapeFuncs*))) | STACK_ROUTINE_PARAMETER(2, SIZE_CODE(sizeof(NPPluginFuncs*))) | STACK_ROUTINE_PARAMETER(3, SIZE_CODE(sizeof(NPP_ShutdownUPP*))) | RESULT_SIZE(SIZE_CODE(sizeof(NPError))) }; #define NewNPP_MainEntryProc(FUNC) \ (NPP_MainEntryUPP) NewRoutineDescriptor((ProcPtr)(FUNC), uppNPP_MainEntryProcInfo, GetCurrentArchitecture()) #define CallNPP_MainEntryProc(FUNC, netscapeFunc, pluginFunc, shutdownUPP) \ CallUniversalProc((UniversalProcPtr)(FUNC), (ProcInfoType)uppNPP_MainEntryProcInfo, (netscapeFunc), (pluginFunc), (shutdownUPP)) #else typedef NPError (*NPP_MainEntryUPP)(NPNetscapeFuncs*, NPPluginFuncs*, NPP_ShutdownUPP*); #define NewNPP_MainEntryProc(FUNC) \ ((NPP_MainEntryUPP) (FUNC)) #define CallNPP_MainEntryProc(FUNC, netscapeFunc, pluginFunc, shutdownUPP) \ (*(FUNC))((netscapeFunc), (pluginFunc), (shutdownUPP)) #endif #endif /* MAC */ #ifdef _WINDOWS #ifdef __cplusplus extern "C" { #endif /* plugin meta member functions */ NPError WINAPI NP_GetEntryPoints(NPPluginFuncs* pFuncs); NPError WINAPI NP_Initialize(NPNetscapeFuncs* pFuncs); NPError WINAPI NP_Shutdown(); #ifdef __cplusplus } #endif #endif /* _WINDOWS */ #ifdef XP_UNIX #ifdef __cplusplus extern "C" { #endif /* plugin meta member functions */ char* NP_GetMIMEDescription(void); NPError NP_Initialize(NPNetscapeFuncs*, NPPluginFuncs*); NPError NP_Shutdown(void); #ifdef __cplusplus } #endif #endif /* XP_UNIX */ #endif /* _NPUPP_H_ */
74647e22e824d99d0df4f844510084e53252e539
487c8455b34e2b312da42bf8a43162aa5c5027df
/Target/Demo/TRICORE_TC3_TC375_Lite_Kit_ADS/Boot/Libraries/iLLD/TC37A/Tricore/Sent/Sent/IfxSent_Sent.h
b2d420862dbd2231733a5a859972815caee62a84
[]
no_license
feaser/openblt
bf3a72e7beb998cb635a67db85fa68100d048bb8
57b517eabeb37d945606e18736e106bde34010bc
refs/heads/master
2023-08-31T23:54:09.030534
2023-07-07T10:29:56
2023-07-07T10:29:56
102,110,352
534
236
null
2023-09-14T11:11:56
2017-09-01T12:26:08
C
UTF-8
C
false
false
31,999
h
IfxSent_Sent.h
/** * \file IfxSent_Sent.h * \brief SENT SENT details * \ingroup IfxLld_Sent * * \version iLLD_1_0_1_12_0_1 * \copyright Copyright (c) 2019 Infineon Technologies AG. All rights reserved. * * * * IMPORTANT NOTICE * * Use of this file is subject to the terms of use agreed between (i) you or * the company in which ordinary course of business you are acting and (ii) * Infineon Technologies AG or its licensees. If and as long as no such terms * of use are agreed, use of this file is subject to following: * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, must * be included in all copies of the Software, in whole or in part, and all * derivative works of the Software, unless such copies or derivative works are * solely in the form of machine-executable object code generated by a source * language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * * * \defgroup IfxLld_Sent_Sent_Usage How to use the SENT Interface driver? * \ingroup IfxLld_Sent * * This SENT interface driver provides functions to communicate with external sensors. * * \section IfxLld_Sent_Sent_Preparation Preparation * \subsection IfxLld_Sent_Sent_Include Include Files * * Include following header file into your C code: * \code * #include <Sent/Sent/IfxSent_Sent.h> * * \endcode * * \subsection IfxLld_Sent_Sent_Variables Variables * * Declare SENT module and channel handles as global variables in your C code. * If multiple SENT channels should be serviced, it makes sense to declare the SENT channel handle as an array: * \code * #define TESTED_SENT_CHANNELS 3 * * static IfxSent_Sent sent; * static IfxSent_Sent_Channel sentChannel[TESTED_SENT_CHANNELS]; * \endcode * * \subsection IfxLld_Sent_Sent_Interrupt Interrupt Handler Installation * * See also \ref IfxLld_Cpu_Irq_Usage * * Define priorities for the Interrrupt handler. This is normally done in the Ifx_IntPrioDef.h file: * \code * #define IFX_INTPRIO_SENT_CHANNEL 1 * \endcode * * Add the interrupt service routine to your C code. It has to call the SENT interrupt handler by passing the SENT channel handle: * \code * void SentInterruptHandler(IfxSent_Sent_Channel *channel); * * IFX_INTERRUPT(sentChannelISR, 0, IFX_INTPRIO_SENT_CHANNEL) * { * int i; * * for(i=0; i<TESTED_SENT_CHANNELS; ++i) * { * SentInterruptHandler(&sentChannel[i]); * } * } * \endcode * * Note: the SentInterruptHandler function is not part of the interface driver, but has to be * implemented in the application. A template can be found below under \ref IfxLld_Sent_Sent_ISR * * Finally install the interrupt handlers in your initialisation function: * \code * // install interrupt handler * IfxCpu_Irq_installInterruptHandler(&sentChannelISR, IFX_INTPRIO_SENT_CHANNEL); * IfxCpu_enableInterrupts(); * \endcode * * * \subsection IfxLld_Sent_Sent_Init Module Initialisation * * The module initialisation can be done in the same function. * Here an example for SENT and SPC mode: * * \code * // create module config * IfxSent_Sent_Config sentConfig; * IfxSent_Sent_initModuleConfig(&sentConfig, &MODULE_SENT); * * // initialize module * //IfxSent_Sent sent; // defined globally * IfxSent_Sent_initModule(&sent, &sentConfig); * \endcode * * \subsection IfxLld_Sent_Sent_InitChannel Channel Initialisation * After the module has been initialized, one or more SENT channels can be configured. * * Here an example for three SENT channels in SENT and SPC mode: * \code * // create channel config * IfxSent_Sent_ChannelConfig sentChannelConfig; * IfxSent_Sent_initChannelConfig(&sentChannelConfig, &sent); * * // define tUnit of the external sensor * sentChannelConfig.tUnit = 3.0E-6; * * // ISR priorities and interrupt target * sentChannelConfig.interrupt.priority = IFX_INTPRIO_SENT_CHANNEL; * sentChannelConfig.interrupt.isrProvider = IfxCpu_Irq_getTos(IfxCpu_getCoreIndex()); * * int i; * for(i=0; i<TESTED_SENT_CHANNELS; ++i) * { * // pin configuration * const IfxSent_Sent_Pins sentPins[TESTED_SENT_CHANNELS] = * { * { // Channel 0 * &IfxSent_SENT0C_P02_8_IN, IfxPort_InputMode_noPullDevice, // SENT input * &IfxSent_SPC0_P00_1_OUT, IfxPort_OutputMode_openDrain, // SENT output * IfxPort_PadDriver_cmosAutomotiveSpeed1 * }, * * { // Channel 1 * &IfxSent_SENT1C_P02_7_IN, IfxPort_InputMode_noPullDevice, // SENT input * &IfxSent_SPC1_P02_7_OUT, IfxPort_OutputMode_openDrain, // SENT output * IfxPort_PadDriver_cmosAutomotiveSpeed1 * }, * * { // Channel 2 * &IfxSent_SENT2C_P02_6_IN, IfxPort_InputMode_noPullDevice, // SENT input * &IfxSent_SPC2_P00_3_OUT, IfxPort_OutputMode_openDrain, // SENT output * IfxPort_PadDriver_cmosAutomotiveSpeed1 * }, * }; * * sentChannelConfig.pins = &sentPins[i]; * * // set channel * sentChannelConfig.channelId = (IfxSent_ChannelId)i; * * // initialize channel * IfxSent_Sent_initChannel(&sentChannel[i], &sentChannelConfig); * } * \endcode * * \subsection IfxLld_Sent_Sent_ISR Interrupt Service Handler * The ISR has to be implemented in the application. Following template can be used * to react on the events: * * \code * void SentInterruptHandler(IfxSent_Sent_Channel *channel) * { * Ifx_SENT_CH_INTSTAT interruptStatus = IfxSent_Sent_getAndClearInterruptStatus(channel); * * if( interruptStatus.U ) * { * // check for error conditions * if (interruptStatus.U & IFXSENT_INTERRUPT_STATUS_ERROR_FLAGS) * { * // * Receive Buffer Overflow * // * This bit is set after a frame has been received while the old one was * // * not read from RDRx. I.e. the kernel wants to set any of the two * // * interrupts RSI and RDI and finds any of these two interrupts already * // * set. The old data is overwritten by the new data. * // * * if (interruptStatus.B.RBI) * { * // insert your error handling code here * __debug(); * } * * // * Transmit Buffer Underflow * // * This bit is set after data has been completely transferred (PLEN * // * exceeded) and no new data was written to SCRx. * // * * if (interruptStatus.B.TBI) * { * // insert your error handling code here * __debug(); * } * * // * Frequency Range Error * // * This bit is set after a Synchronization / Calibration pulse was * // * received that deviates more than +- 25% from the nominal value. * // * The referring data is ignored. * // * * if (interruptStatus.B.FRI) * { * // insert your error handling code here * __debug(); * } * * // * Frequency Drift Error * // * This bit is set after a subsequent Synchronization / Calibration * // * pulse was received that deviates more than 1.5625% (1/64) from its * // * predecessor. * // * * if (interruptStatus.B.FDI) * { * // insert your error handling code here * __debug(); * } * * // * Wrong Number of Nibbles * // * This bit is set after a more nibbles have been received than expected * // * or a Synchronization / Calibration Pulse is received too early thus * // * too few nibbles have been received * // * * if (interruptStatus.B.NNI) * { * // insert your error handling code here * __debug(); * } * * // * Nibbles Value out of Range * // * This bit is set after a too long or too short nibble pulse has been * // * received. I.e. value < 0 or value > 15. * // * * if (interruptStatus.B.NVI) * { * // insert your error handling code here * __debug(); * } * * // * CRC Error * // * This bit is set if the CRC check fails. * // * * if (interruptStatus.B.CRCI) * { * // insert your error handling code here * __debug(); * } * * // * Wrong Status and Communication Nibble Error * // * In standard Serial Frame Mode (RCR.ESF is cleared), this bit is set * // * if the Status and Communication nibble shows a start bit in a frame * // * other than frame number n x 16. * // * In Extended Serial Frame Mode this bit is without function. * // * * if (interruptStatus.B.WSI) * { * // insert your error handling code here * __debug(); * } * * // * Serial Data CRC Error * // * This bit is set if the CRC of the serial message fails. * // * In Extended Serial Message Format, this includes a check of the Serial * // * Communication Nibble for correct 0 values of bit 3 in frames 7, 13 and 18. * // * * if (interruptStatus.B.SCRI) * { * // insert your error handling code here * __debug(); * } * * // * Watch Dog Error * // * This bit is set if the Watch Dog Timer of the channel expires. * // * * if (interruptStatus.B.WDI) * { * // insert your error handling code here * __debug(); * } * } * * // transaction events * * // * Receive Data * // * RDI is activated when a received frame is moved to a Receive Data * // * Register RDR. Both RDI and RSI will be issued together in normal use * // * cases where the frame size is not bigger than 8 nibbles and CRC is * // * correct or not checked (if RCRx.CDIS is cleared). * // * * if (interruptStatus.B.RDI) * { * // * Ignore RDI bit, useful only when Frame Length is greater than * // * 8 nibbles since it can indicate that end of frame * // * * } * * // * Receive Success * // * This bit is set at the successfully received end of a frame. * // * Depending on bit RCRx.CDIS this indicates a successful check of the CRC. * // * * if (interruptStatus.B.RSI) * { * // here you could handle the incoming frame: * IfxSent_Sent_Frame frame; * IfxSent_Sent_readChannelSerialDataFrame(channel, &frame); * * // do something with the incoming data * } * * // * Transfer Data * // * This bit is set after the trigger condition was detected. Data to be * // * transferred has been moved internally. Thus a new value can be written * // * to SCRx. This can be used for back to back transfers. * // * * if (interruptStatus.B.TDI) * { * } * * // * Serial Data Received * // * This bit is set after all serial data bits have been received via the * // * Status and Communication nibble. Depending on bit RCRx.SCDIS this * // * indicates a successful check of the CRC. * // * * if (interruptStatus.B.SDI) * { * // here you could handle the incoming message: * * // decode incoming message * IfxSent_Sent_SerialMessageFrame message; * IfxSent_Sent_readChannelSerialMessageFrame(channel, &message); * * // do something with the incoming message * } * } * } * \endcode * * \subsection IfxLld_Sent_Sent_Frame Frame Decoding * Following code snippet shows, how incoming data of a TLE4998S device can be decoded: * * \code * static void parseSensorData(IfxSent_Sent_Frame *frame) * { * uint32 data = frame->data; * uint8 statusNibble = frame->statusNibble; * * // select B range [mT] * const uint8 rangeValTable[4] = { 200, 100, 50, 0 }; * uint8 rangeVal = rangeValTable[statusNibble & 3]; * * uint16 hallVal = (short)((((data & 0xFFFF) * rangeVal) / 0x7FFF) - rangeVal); * uint16 temperature = ((short)((data >> 16) & 0x00FF) - 55); * * // do something with the values here... * } * \endcode * * \defgroup IfxLld_Sent_Sent Interface Driver * \ingroup IfxLld_Sent * \defgroup IfxLld_Sent_Sent_Structures Data Structures * \ingroup IfxLld_Sent_Sent * \defgroup IfxLld_Sent_Sent_Module Module Functions * \ingroup IfxLld_Sent_Sent * \defgroup IfxLld_Sent_Sent_Channel Channel Functions * \ingroup IfxLld_Sent_Sent */ #ifndef IFXSENT_SENT_H #define IFXSENT_SENT_H 1 /******************************************************************************/ /*----------------------------------Includes----------------------------------*/ /******************************************************************************/ #include "Scu/Std/IfxScuWdt.h" #include "Sent/Std/IfxSent.h" #include "Cpu/Irq/IfxCpu_Irq.h" /******************************************************************************/ /*-----------------------------Data Structures--------------------------------*/ /******************************************************************************/ /** \addtogroup IfxLld_Sent_Sent_Structures * \{ */ /** \brief Specifies the Interrupt type enables structure */ typedef struct { uint8 receiveDataInterrupt; /**< \brief Specifies receive data interrupt enable */ uint8 receiveSuccessInterrupt; /**< \brief Specifies receive success interrupt enable */ uint8 receiveBufferOverflowInterrupt; /**< \brief Specifies receive buffer overflow interrupt enable */ uint8 transferDataInterrupt; /**< \brief Specifies transfer data interrupt enable */ uint8 transferBufferUnderflowInterrupt; /**< \brief Specifies transfer buffer underflow interrupt enable */ uint8 serialDataReceiveInterrupt; /**< \brief Specifies serial data interrupt enable */ uint8 watchdogErrorInterrupt; /**< \brief Specifies watchdog error interrupt enable */ uint8 serialDataCrcErrorInterrupt; /**< \brief Specifies serial data CRC error interrupt enable */ uint8 wrongStatusNibbleErrorInterrupt; /**< \brief Specifies wrong status nibble error interrupt enable */ uint8 crcErrorInterrupt; /**< \brief Specifies CRC error interrupt enable */ uint8 nibblesValueOutOfRangeErrorInterrupt; /**< \brief Specifies nibble value out of range error interrupt enable */ uint8 nibblesWrongErrorInterrupt; /**< \brief Specifies nibbles wrong error interrupt enable */ uint8 frequencyDriftErrorInterrupt; /**< \brief Specifies frequency drift error interrupt enable */ uint8 frequencyRangeErrorInterrupt; /**< \brief Specifies frequency not in the range error interrupt enable */ } IfxSent_Sent_Enable; /** \} */ /** \addtogroup IfxLld_Sent_Sent_Structures * \{ */ /** \brief Specifies SENT handle structure */ typedef struct { Ifx_SENT *sent; /**< \brief Specifies pointer to SENT registers */ } IfxSent_Sent; /** \brief Specifies interrupt flags union . In addition it allows to write and read to/from all flags as once via the ALL member. */ typedef union { uint32 ALL; /**< \brief Specifies to write and read to/from all flags as once via the ALL member. */ IfxSent_Sent_Enable enable; /**< \brief Structure contains the interrupt flags */ } IfxSent_Sent_EnabledInterrupts; /** \brief Specifies the input output control properties */ typedef struct { boolean inputPulsePolarityHigh; /**< \brief Specifies the polarity of input of each channel */ boolean outputPulsePolarityHigh; /**< \brief Specifies the polarity of input of each channel */ boolean edgeCounterCleared; /**< \brief Specifies the edge counter reset */ boolean glitchFallingCleared; /**< \brief Specifies the glitch falling edge clear */ boolean glitchRisingCleared; /**< \brief Specifies the glitch rising edge clear */ boolean triggerMonitorCleared; /**< \brief Specifies the trigger monitor reset */ IfxSent_DigitalGlitchesLength digitalGlitchFilterDepth; /**< \brief Specifies the Digital Glitch Filter depth for input signal delay */ IfxSent_ExternalTrigger externalTrigger; /**< \brief Specifies the external trigger line source */ } IfxSent_Sent_InputOutputControl; /** \brief Specifies the interrupt control properties */ typedef struct { uint16 priority; /**< \brief Specifies the interrupt priority. Always 1 since all interrupts are handled at a time */ IfxSrc_Tos isrProvider; /**< \brief Specifies the interrupt service provider. CPU or DMA. */ } IfxSent_Sent_Interrupt; /** \brief Specifies the interrupt control properties structure */ typedef struct { IfxSent_InterruptNodePointer receiveSuccessInterruptNode; /**< \brief Specifies the interrupt node for rsi request */ IfxSent_InterruptNodePointer receiveDataInterruptNode; /**< \brief Specifies the interrupt node for rdi request */ IfxSent_InterruptNodePointer receiveBufferOverflowInterruptNode; /**< \brief Specifies the interrupt node for rbi request */ IfxSent_InterruptNodePointer transferDataInterruptNode; /**< \brief Specifies the interrupt node for tdi request */ IfxSent_InterruptNodePointer transferBufferUnderflowInterruptNode; /**< \brief Specifies the interrupt node for tbi request */ IfxSent_InterruptNodePointer errorInterruptNode; /**< \brief Specifies the interrupt node for erri request */ IfxSent_InterruptNodePointer serialDataReceiveInterruptNode; /**< \brief Specifies the interrupt node for sdi request */ IfxSent_InterruptNodePointer watchdogErrorInterruptNode; /**< \brief Specifies the interrupt node for wdi request */ } IfxSent_Sent_InterruptNodeControl; /** \brief Specifies the received nibbles control properties */ typedef struct { IfxSent_Nibble nibblePointer0; /**< \brief Specifies the received nibble0 control */ IfxSent_Nibble nibblePointer1; /**< \brief Specifies the received nibble1 control */ IfxSent_Nibble nibblePointer2; /**< \brief Specifies the received nibble2 control */ IfxSent_Nibble nibblePointer3; /**< \brief Specifies the received nibble3 control */ IfxSent_Nibble nibblePointer4; /**< \brief Specifies the received nibble4 control */ IfxSent_Nibble nibblePointer5; /**< \brief Specifies the received nibble5 control */ IfxSent_Nibble nibblePointer6; /**< \brief Specifies the received nibble6 control */ IfxSent_Nibble nibblePointer7; /**< \brief Specifies the received nibble7 control */ } IfxSent_Sent_NibbleControl; /** \brief Specifies the pins configuration for SENT channel */ typedef struct { IFX_CONST IfxSent_Sent_In *in; /**< \brief Specifies input pin configuration */ IfxPort_InputMode inMode; /**< \brief Specifies input pin mode */ IFX_CONST IfxSent_Spc_Out *out; /**< \brief Specifies output pin configuration */ IfxPort_OutputMode outMode; /**< \brief Specifies output pin mode */ IfxPort_PadDriver pinDriver; /**< \brief Pad driver mode definition */ } IfxSent_Sent_Pins; /** \brief Specifies the receive control properties */ typedef struct { boolean crcModeDisabled; /**< \brief Specifies the CRC mode disabled mode */ boolean crcMethodDisabled; /**< \brief Specifies the CRC with zero nibbles disabled or enabled */ boolean alternateCrcSelected; /**< \brief Specifies the CRC is calculated for both fast and serial messages */ boolean serialDataProcessingEnabled; /**< \brief Specifies the serial data processing mode */ boolean serialDataDisabledCrcDisabled; /**< \brief Specifies the CRC disable for serial data disabled mode */ boolean statusNibbleEnabled; /**< \brief Specifies the status nibble to include in CRC */ boolean driftErrorsDisabled; /**< \brief Specifies the drift errors enabled or disabled */ boolean endPulseIgnored; /**< \brief Specifies the pause pulse during synchronization */ boolean suspendTriggered; /**< \brief Specifies the suspend trigger disables the channel or not */ uint8 frameLength; /**< \brief Specifies frame length in nibbles */ IfxSent_FrameCheckMode frameCheckMode; /**< \brief Specifies the frame check mode for valid frame */ IfxSent_ExtendedSerialFrameMode extendedSerialFrameMode; /**< \brief Specifies the extended serial frame mode */ boolean frequencyDriftCheckEnabled; /**< \brief Specifies the frequency drift check based on frame length is enable or disable */ } IfxSent_Sent_ReceiveControl; /** \brief Specifies the SPC channel properties structure */ typedef struct { uint8 pulseLength; /**< \brief Specifies the pulse length in ticktimes */ uint8 pulseDelayLength; /**< \brief Specifies the pulse delay length */ IfxSent_TriggerSource triggerSource; /**< \brief Specifies the trigger source and mode */ IfxSent_TimeBase timeBase; /**< \brief Specifies the pulse time base */ IfxSent_SpcMode spcMode; /**< \brief Specifies the SENT SPC operational mode */ } IfxSent_Sent_TransmitControl; /** \} */ /** \addtogroup IfxLld_Sent_Sent_Structures * \{ */ /** \brief Specifies the SENT Channel handle structure */ typedef struct { IfxSent_Sent *driver; /**< \brief Specifies the pointer to SENT module handler */ Ifx_SENT_CH *channel; /**< \brief Specifies the pointer SENT channel registers */ IfxSent_ChannelId channelId; /**< \brief Specifies the SENT channel number */ } IfxSent_Sent_Channel; /** \brief Specifies the SENT Channel configuration structure */ typedef struct { IfxSent_Sent *driver; /**< \brief Specifies the pointer to SENT module handler */ uint16 watchDogTimerLimit; /**< \brief Speciifes the enabled interrupts for each Channel */ IfxSent_ChannelId channelId; /**< \brief Specifies the SENT channel number */ IfxSent_Sent_InputOutputControl inputOutputControl; /**< \brief Specifies the input output controllable properties */ IfxSent_Sent_ReceiveControl receiveControl; /**< \brief Specifies the receive control properties */ IfxSent_Sent_TransmitControl transmitControl; /**< \brief Specifies the transmit control properties */ IfxSent_Sent_InterruptNodeControl interuptNodeControl; /**< \brief Specifies the interrupt control properties structure */ IFX_CONST IfxSent_Sent_Pins *pins; /**< \brief Specifies the pins configuration for SENT channel */ float32 tUnit; /**< \brief desired unit time (f_tick), e.g. 3E-6 for 3 uS */ IfxSent_Sent_NibbleControl nibbleControl; /**< \brief Specifies the received nibbles control properties */ IfxSent_Sent_Interrupt interrupt; /**< \brief Specifies the interrupt control properties structure */ boolean spcModeOn; /**< \brief Specifies the SENT SPC mode enable/disable */ IfxSent_Sent_EnabledInterrupts enabledInterrupts; } IfxSent_Sent_ChannelConfig; /** \brief Specifies the SENT module configuration structure */ typedef struct { Ifx_SENT *module; /**< \brief Specifies pointer to SENT registers */ boolean sleepModeEnabled; /**< \brief Specifies SENT enable/disable */ uint32 timeStampPreDivider; /**< \brief Specifies the pre-divider to get clock in time stamp */ } IfxSent_Sent_Config; /** \brief Specifies the frame configuration structure for a channel */ typedef struct { uint32 data; /**< \brief Contains the data from last received frame */ uint32 timeStamp; /**< \brief Contains the timestamp of last received frame */ uint8 statusNibble; /**< \brief Contains the status and communication Nibble of last received frame */ } IfxSent_Sent_Frame; /** \brief Specifies received message frame */ typedef struct { uint8 crc; /**< \brief Contains the received CRC value */ uint8 messageId; /**< \brief Contains the received message ID value */ uint16 serialData; /**< \brief Contains the received serial data value */ IfxSent_ConfigBit configBit; /**< \brief Contains the received configuration bit value */ } IfxSent_Sent_SerialMessageFrame; /** \} */ /** \addtogroup IfxLld_Sent_Sent_Module * \{ */ /******************************************************************************/ /*-------------------------Global Function Prototypes-------------------------*/ /******************************************************************************/ /** \brief Reset the SENT module * \param driver pointer to the SENT module handler * \return None */ IFX_EXTERN void IfxSent_Sent_deInitModule(IfxSent_Sent *driver); /** \brief Initialise the SENT with the supplied configureation * \param driver pointer to the SENT module handler * \param config pointer to the SENT module configuration * \return TRUE if valid configuration otherwise FALSE * * Usage example: see \ref IfxLld_Sent_Sent_Usage * */ IFX_EXTERN boolean IfxSent_Sent_initModule(IfxSent_Sent *driver, const IfxSent_Sent_Config *config); /** \brief Initialise buffer with default SENT configuration * \param config pointer to the SENT module configuration * \param sent base address of the SENT register space * \return None * * Usage example: see \ref IfxLld_Sent_Sent_Usage * */ IFX_EXTERN void IfxSent_Sent_initModuleConfig(IfxSent_Sent_Config *config, Ifx_SENT *sent); /** \} */ /** \addtogroup IfxLld_Sent_Sent_Channel * \{ */ /******************************************************************************/ /*-------------------------Inline Function Prototypes-------------------------*/ /******************************************************************************/ /** \brief Copies the current interrupt flags into the Ifx_SENT_CH_INTSTAT structure, and clears the flags in hardware. * * This function should be used in an ISR to retrieve the events which triggered the interrupt. * \param channel Specifies the SENT Channel handle structure * \return Interrupt flags which have been cleared. * * Usage example: see \ref IfxLld_Sent_Sent_Usage * */ IFX_INLINE Ifx_SENT_CH_INTSTAT IfxSent_Sent_getAndClearInterruptStatus(IfxSent_Sent_Channel *channel); /******************************************************************************/ /*-------------------------Global Function Prototypes-------------------------*/ /******************************************************************************/ /** \brief Initialize the channel with the supplied configuration * \param channel pointer to the SENT channel * \param config pointer to the SENT channel configuration * \return TRUE if valid configuration otherwise FALSE * * Usage example: see \ref IfxLld_Sent_Sent_Usage * */ IFX_EXTERN boolean IfxSent_Sent_initChannel(IfxSent_Sent_Channel *channel, const IfxSent_Sent_ChannelConfig *config); /** \brief Initialise channel buffer with default SENT channel configuration * \param config pointer to the SENT channel configuration * \param driver pointer to the SENT module handler * \return None * * Usage example: see \ref IfxLld_Sent_Sent_Usage * */ IFX_EXTERN void IfxSent_Sent_initChannelConfig(IfxSent_Sent_ChannelConfig *config, IfxSent_Sent *driver); /** \brief Reads the nibbles recieved in the Data register * \param channel SENT Channel whose data has to be read * \param frame Data read from the SENT Channel * \return TRUE if data received otherwise false * * Usage example: see \ref IfxLld_Sent_Sent_Usage * */ IFX_EXTERN boolean IfxSent_Sent_readChannelSerialDataFrame(IfxSent_Sent_Channel *channel, IfxSent_Sent_Frame *frame); /** \brief reads the Serial data recieved and collected over several SENT frames * \param channel reads the Serial data recieved and collected over several SENT frames * \param message Data pointer pointing to the serial data read from the SENT Channel * \return TRUE if serial message received otherwise false * * Usage example: see \ref IfxLld_Sent_Sent_Usage * */ IFX_EXTERN boolean IfxSent_Sent_readChannelSerialMessageFrame(IfxSent_Sent_Channel *channel, IfxSent_Sent_SerialMessageFrame *message); /** \} */ /******************************************************************************/ /*---------------------Inline Function Implementations------------------------*/ /******************************************************************************/ IFX_INLINE Ifx_SENT_CH_INTSTAT IfxSent_Sent_getAndClearInterruptStatus(IfxSent_Sent_Channel *channel) { return IfxSent_getAndClearInterruptStatus(channel->driver->sent, channel->channelId); } #endif /* IFXSENT_SENT_H */
f85462b2e6e0e783083d133031af04dfeffdc383
c9bc99866cfab223c777cfb741083be3e9439d81
/product/sgm776/scp_ramfw/config_system_power.c
ad29403dabe25c19590d6bedb571e4d1a5ed1bd7
[ "BSD-3-Clause" ]
permissive
ARM-software/SCP-firmware
4738ca86ce42d82588ddafc2226a1f353ff2c797
f6bcca436768359ffeadd84d65e8ea0c3efc7ef1
refs/heads/master
2023-09-01T16:13:36.962036
2023-08-17T13:00:20
2023-08-31T07:43:37
134,399,880
211
165
NOASSERTION
2023-09-13T14:27:10
2018-05-22T10:35:56
C
UTF-8
C
false
false
3,527
c
config_system_power.c
/* * Arm SCP/MCP Software * Copyright (c) 2017-2021, Arm Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include "config_ppu_v1.h" #include <mod_power_domain.h> #include <mod_ppu_v1.h> #include <mod_sgm776_system.h> #include <mod_system_power.h> #include <fwk_element.h> #include <fwk_id.h> #include <fwk_macros.h> #include <fwk_module.h> #include <fwk_module_idx.h> #include <fmw_cmsis.h> #include <stdint.h> /* * The DPU/GPU/VPU PPUs in this list are there as a temporary workaround, until * Linux supports handling these domains on its own. */ static const struct mod_system_power_ext_ppu_config ext_ppus[] = { { .ppu_id = FWK_ID_ELEMENT_INIT( FWK_MODULE_IDX_PPU_V1, PPU_V1_ELEMENT_IDX_DPUTOP), .api_id = FWK_ID_API_INIT(FWK_MODULE_IDX_PPU_V1, MOD_PPU_V1_API_IDX_POWER_DOMAIN_DRIVER), }, { .ppu_id = FWK_ID_ELEMENT_INIT( FWK_MODULE_IDX_PPU_V1, PPU_V1_ELEMENT_IDX_GPUTOP), .api_id = FWK_ID_API_INIT(FWK_MODULE_IDX_PPU_V1, MOD_PPU_V1_API_IDX_POWER_DOMAIN_DRIVER), }, { .ppu_id = FWK_ID_ELEMENT_INIT( FWK_MODULE_IDX_PPU_V1, PPU_V1_ELEMENT_IDX_VPUTOP), .api_id = FWK_ID_API_INIT(FWK_MODULE_IDX_PPU_V1, MOD_PPU_V1_API_IDX_POWER_DOMAIN_DRIVER), }, }; static const uint8_t system_power_to_sys_ppu0_state[] = { [MOD_PD_STATE_ON] = (uint8_t)MOD_PD_STATE_ON, [MOD_SYSTEM_POWER_POWER_STATE_SLEEP0] = (uint8_t)MOD_PD_STATE_OFF, [MOD_PD_STATE_OFF] = (uint8_t)MOD_PD_STATE_OFF, }; static const uint8_t system_power_to_sys_ppu1_state[] = { [MOD_PD_STATE_ON] = (uint8_t)MOD_PD_STATE_ON, [MOD_SYSTEM_POWER_POWER_STATE_SLEEP0] = (uint8_t)MOD_PD_STATE_ON, [MOD_PD_STATE_OFF] = (uint8_t)MOD_PD_STATE_OFF, }; static const struct fwk_element system_power_element_table[] = { [0] = { .name = "SYS-PPU-0", .data = &((struct mod_system_power_dev_config) { .sys_ppu_id = FWK_ID_ELEMENT_INIT(FWK_MODULE_IDX_PPU_V1, PPU_V1_ELEMENT_IDX_SYS0), .api_id = FWK_ID_API_INIT(FWK_MODULE_IDX_PPU_V1, 0), .sys_state_table = system_power_to_sys_ppu0_state, }), }, [1] = { .name = "SYS-PPU-1", .data = &((struct mod_system_power_dev_config) { .sys_ppu_id = FWK_ID_ELEMENT_INIT(FWK_MODULE_IDX_PPU_V1, PPU_V1_ELEMENT_IDX_SYS1), .api_id = FWK_ID_API_INIT(FWK_MODULE_IDX_PPU_V1, 0), .sys_state_table = system_power_to_sys_ppu1_state, }), }, [2] = { 0 }, /* Termination description */ }; static const struct fwk_element *system_power_get_element_table( fwk_id_t module_id) { return system_power_element_table; } const struct fwk_module_config config_system_power = { .data = &(struct mod_system_power_config){ .soc_wakeup_irq = SOC_WAKEUP0_IRQ, .ext_ppus = ext_ppus, .ext_ppus_count = FWK_ARRAY_SIZE(ext_ppus), .driver_id = FWK_ID_MODULE_INIT(FWK_MODULE_IDX_SGM776_SYSTEM), .driver_api_id = FWK_ID_API_INIT( FWK_MODULE_IDX_SGM776_SYSTEM, MOD_SGM776_SYSTEM_API_IDX_SYSTEM_POWER_DRIVER), .initial_system_power_state = MOD_PD_STATE_ON, }, .elements = FWK_MODULE_DYNAMIC_ELEMENTS(system_power_get_element_table), };
c61cd89bc631e85d94a42c9f97f4128625ef45d5
1661c43eaf9e44dfe7cce269cfaae62e336036f1
/blink/rde.h
9ca9410a921e476d0faafb7c6c5fa9ae501a3e48
[]
permissive
jart/blink
3354eaf084e3e85a50372f1a93fc75ff2b9488b1
312a027d0908c1b1f9d1e9ebba837da569606b82
refs/heads/master
2023-08-31T21:30:40.551686
2023-08-22T15:42:44
2023-08-22T15:42:44
561,183,031
6,089
192
ISC
2023-08-22T15:42:46
2022-11-03T06:07:09
C
UTF-8
C
false
false
2,407
h
rde.h
#ifndef BLINK_RDE_H_ #define BLINK_RDE_H_ #define kRexbRmMask 000000003600 #define RexbRm(x) ((x & kRexbRmMask) >> 007) #define kRexrRegMask 000000000017 #define RexrReg(x) ((x & kRexrRegMask) >> 000) #define kOplengthMask 00007400000000000000000 #define Oplength(x) ((x & kOplengthMask) >> 065) #define kRegRexbSrmMask 00000170000 #define RexbSrm(x) ((x & kRegRexbSrmMask) >> 014) #define Rex(x) ((x & 000000000020) >> 004) #define Osz(x) ((x & 000000000040) >> 005) #define Asz(x) ((x & 000010000000) >> 025) #define Srm(x) ((x & 000000070000) >> 014) #define Rexr(x) ((x & 000000000010) >> 003) #define Rexw(x) ((x & 000000000100) >> 006) #define Rexx(x) ((x & 000000400000) >> 021) #define Rexb(x) ((x & 000000002000) >> 012) #define Sego(x) ((x & 000007000000) >> 022) #define Ymm(x) ((x & 010000000000) >> 036) #define RegLog2(x) ((x & 006000000000) >> 034) #define ModrmRm(x) ((x & 000000001600) >> 007) #define ModrmReg(x) ((x & 000000000007) >> 000) #define ModrmSrm(x) ((x & 000000070000) >> 014) #define ModrmMod(x) ((x & 000060000000) >> 026) #define RexRexr(x) ((x & 000000000037) >> 000) #define RexRexb(x) ((x & 000000007600) >> 007) #define RexRexbSrm(x) ((x & 000000370000) >> 014) #define Modrm(x) (ModrmMod(x) << 6 | ModrmReg(x) << 3 | ModrmRm(x)) #define SibBase(x) ((x & 00000000000340000000000) >> 040) #define SibIndex(x) ((x & 00000000003400000000000) >> 043) #define SibScale(x) ((x & 00000000014000000000000) >> 046) #define Opcode(x) ((x & 00000007760000000000000) >> 050) #define Opmap(x) ((x & 00000070000000000000000) >> 060) #define Mopcode(x) ((x & 00000077760000000000000) >> 050) #define Rep(x) ((x & 00000300000000000000000) >> 063) #define WordLog2(x) ((x & 00030000000000000000000) >> 071) #define Vreg(x) ((x & 01700000000000000000000) >> 074) #define Bite(x) (~ModrmSrm(x) & 1) #define RexbBase(x) (Rexb(x) << 3 | SibBase(x)) #define IsByteOp(x) (~Srm(rde) & 1) #define SibExists(x) (ModrmRm(x) == 4) #define IsModrmRegister(x) (ModrmMod(x) == 3) #define SibHasIndex(x) (SibIndex(x) != 4 || Rexx(x)) #define SibHasBase(x) (SibBase(x) != 5 || ModrmMod(x)) #define SibIsAbsolute(x) (!SibHasBase(x) && !SibHasIndex(x)) #define IsRipRelative(x) (Eamode(x) && ModrmRm(x) == 5 && !ModrmMod(x)) #endif /* BLINK_RDE_H_ */
5e05c7d7586fd79af3e11592c3144e4adcc49ac9
ce99bd11ca505967277f4689c621479c1987698e
/assets/obseg/prop/propExplosionDetailsRecords-eu.inc.c
c6e3a2bdc0c32b129d7755f569568fd23631b354
[]
no_license
n64decomp/007
5951258890f15431f273e1503674c5e0402c66e0
c46751089ddc18b12ef7a45b6a3e03de2054c422
refs/heads/master
2022-11-08T23:34:54.021033
2022-10-29T14:41:01
2022-10-29T14:41:01
241,212,109
359
48
null
2020-11-21T23:30:31
2020-02-17T21:31:00
C
UTF-8
C
false
false
8,546
c
propExplosionDetailsRecords-eu.inc.c
struct ExplosionDetailsRecordEuList object_explosion_details = { { 0x06, 0x06, 0x05, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x00, 0x02, 0x02, 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x07, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x0f, 0x0f, 0x07, 0x06, 0x06, 0x04, 0x04, 0x06, 0x04, 0x02, 0x09, 0x09, 0x03, 0x04, 0x04, 0x04, 0x04, 0x0b, 0x0b, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x00, 0x06, 0x07, 0x07, 0x07, 0x07, 0x00, 0x07, 0x06, 0x03, 0x03, 0x05, 0x07, 0x04, 0x06, 0x08, 0x04, 0x04, 0x04, 0x03, 0x03, 0x03, 0x0f, 0x00, 0x04, 0x00, 0x00, 0x00, 0x06, 0x05, 0x05, 0x08, 0x04, 0x03, 0x03, 0x08, 0x0d, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x03, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0d, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x07, 0x00, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x09, 0x0d, 0x00, 0xff, /* align padding? */ 0x00, 0x00, 0x00 }, { {0x315c, 0x7b6c, 0xdbff, 0x5126, 0xfb59, 0x7ca7}, {0x2afe, 0xcb3e, 0x73f4, 0x278f, 0x6d3a, 0x44c8}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0xb9b0, 0x3eba, 0xad62, 0x75c8, 0xb70f, 0xf06e}, {0x17d9, 0xdfcc, 0x57cd, 0x8254, 0x7345, 0xe011}, {0x3779, 0xed72, 0x688d, 0xf67b, 0x37e5, 0x4f89}, {0xe277, 0x0474, 0xdd1e, 0x0c48, 0x486c, 0xf87d}, {0x7c3f, 0x16bc, 0x44a9, 0x1a58, 0xe412, 0x9297}, {0x3dc2, 0x16b6, 0xe30d, 0xbcab, 0xc592, 0xf9b5}, {0x719c, 0x7024, 0x9ee0, 0xc175, 0xa5dd, 0xc933}, {0x8e16, 0xbbca, 0x05c0, 0x1a73, 0x81be, 0xf821}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x2716, 0xf544, 0x0d35, 0xc20e, 0x83d7, 0x7d73}, {0x81a1, 0xb772, 0x1b57, 0x437a, 0x85fa, 0xb6c1}, {0x27eb, 0x5a7a, 0xbd1a, 0x27eb, 0x5a7a, 0xbd1a}, {0x98de, 0x8c36, 0xddd5, 0xf74b, 0x4f0a, 0x1f14}, {0x34f5, 0xf199, 0xa9f2, 0x3d27, 0xc707, 0xb9ad}, {0x678f, 0xdb91, 0x2a2e, 0x8d91, 0x6eee, 0x925e}, {0xd82f, 0xf4d7, 0x546f, 0xd6c7, 0x87d9, 0x0143}, {0x100e, 0xadf2, 0x1fdd, 0x45f1, 0x4772, 0xf8c6}, {0xef0b, 0x71bb, 0xb7f7, 0xbfa3, 0x03b8, 0xe44e}, {0xdfd1, 0x676a, 0x8597, 0xe8ac, 0xe210, 0x9a4d}, {0xab48, 0xdd9b, 0x4343, 0x04b8, 0x0dcc, 0x3b3d}, {0x836b, 0x6bbf, 0x9dbb, 0x3db7, 0x5957, 0x7341}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0xb1cc, 0x19e2, 0x0ea5, 0xb1cc, 0x19e2, 0x0ea5}, {0xf093, 0xb2df, 0x1409, 0x271e, 0xe0b3, 0x418a}, {0x3ac2, 0x0102, 0xbf01, 0x3ac2, 0x0102, 0xbf01}, {0x3ac6, 0xe449, 0xa56e, 0xa4cf, 0xeda0, 0x1719}, {0x9bcf, 0xc333, 0x6384, 0x4298, 0xd455, 0x7bfa}, {0x839e, 0x0ba7, 0x1466, 0xdb6d, 0xd1b3, 0x1233}, {0x3f67, 0x7a70, 0x83de, 0x7052, 0x07d2, 0x36ff}, {0xa409, 0x692d, 0xe286, 0xc63c, 0x82d0, 0x5d07}, {0xd6ca, 0x1866, 0x839c, 0xbc6a, 0x86ad, 0x4dc6}, {0x96fc, 0xa1ef, 0xa9e6, 0xb9d2, 0xa3c5, 0xa045}, {0x7d2b, 0xe7dc, 0x55db, 0x378e, 0x4765, 0xb09c}, {0xe2af, 0x2d43, 0x71fe, 0xe390, 0x93b3, 0x57e3}, {0x9367, 0x098a, 0x3b68, 0xd6f8, 0x4eaf, 0x7b83}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x993d, 0xa2b2, 0x5028, 0x825e, 0x25b8, 0xd8ef}, {0x6553, 0x024d, 0xfd22, 0xd469, 0x18e4, 0x32f6}, {0xf742, 0x0cb5, 0x8ed2, 0x6021, 0x6ad5, 0xaa88}, {0x06d8, 0x82ef, 0x5b19, 0x4147, 0x5ae1, 0x374e}, {0x284d, 0x3e7c, 0x9330, 0xcf1e, 0x013f, 0x4e29}, {0xe339, 0xc0b6, 0xe5fc, 0x7054, 0x83a8, 0xc118}, {0xb49f, 0x0002, 0x4ef6, 0x8849, 0x0002, 0x070b}, {0x2d56, 0xa1ee, 0x4105, 0x8ae6, 0x6a2a, 0x60dd}, {0x79b2, 0xbc78, 0xb9b9, 0xc76a, 0x97a1, 0x3da3}, {0x3292, 0xddc3, 0x9265, 0x12a6, 0xe935, 0xb9bc}, {0x04db, 0x3cfd, 0xdb5c, 0x3b29, 0x50b7, 0x83d1}, {0xbe64, 0x08ad, 0x150d, 0x6aed, 0x542e, 0x63b3}, {0xd7e5, 0x1369, 0x5acc, 0x535a, 0x2105, 0x1bf7}, {0x7222, 0x3cee, 0x1a15, 0x122a, 0xadec, 0x5ef3}, {0x927f, 0x10b0, 0x5125, 0x7f4e, 0xbbc5, 0x8088}, {0xe89d, 0x7502, 0x9003, 0x469d, 0x19f0, 0xa5e6}, {0x3771, 0xc002, 0x80ff, 0xdbf6, 0x1705, 0x497a}, {0xa954, 0xafde, 0xbb6c, 0xd4a6, 0x9883, 0xfa27}, {0xde9f, 0xcef0, 0x6346, 0x80fb, 0xa382, 0x14d1}, {0x448e, 0xd4cc, 0xc1b5, 0x442f, 0xc1d1, 0xee05}, {0xc7c0, 0xf918, 0x095e, 0xece2, 0x06d4, 0xc64d}, {0xc491, 0x16ec, 0xdea7, 0x5a19, 0x9de7, 0xff28}, {0xe889, 0x2da6, 0x2775, 0x153c, 0xbae6, 0xcb1b}, {0x2d56, 0xa1ee, 0x4105, 0x8ae6, 0x6a2a, 0x60dd}, {0xe5e6, 0x8fb7, 0xd5fe, 0xe959, 0xd656, 0xfb82}, {0x5876, 0x3a4f, 0xd115, 0xa10d, 0x265d, 0x2c02}, {0x787e, 0xc128, 0xd96a, 0x60c9, 0x18e7, 0x99ad}, {0x879a, 0x90e4, 0xc20f, 0x35fe, 0xc807, 0x91d8}, {0x40ae, 0x62b6, 0xd240, 0xac8d, 0x47c5, 0x17d1}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x15c6, 0xb37d, 0x118a, 0x4e61, 0x5d02, 0x7d50}, {0x15c6, 0xb37d, 0x118a, 0x4e61, 0x5d02, 0x7d50}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x2469, 0x8ae5, 0x524f, 0xe5f6, 0xbe4a, 0xc865}, {0x2957, 0x1b22, 0x27c7, 0x9663, 0x0ddf, 0x411f}, {0x15c6, 0xb37d, 0x118a, 0x4e61, 0x5d02, 0x7d50}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0xf8f4, 0xf1e0, 0x473f, 0x41dd, 0xa510, 0xc9c6}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x7a51, 0x2382, 0x9b36, 0x29e5, 0x5921, 0x017a}, {0x8666, 0x3dd9, 0xe619, 0x6134, 0xcc94, 0x1a5c}, {0x7f39, 0x31c5, 0x9ac3, 0x70ab, 0x0551, 0xb069}, {0xd727, 0x7ab2, 0x786b, 0xf5ad, 0x3fc4, 0xd6ce}, {0x4548, 0xd59e, 0x1edc, 0xe88d, 0xe9e4, 0xaf76}, {0x262f, 0x491b, 0xfd57, 0x6715, 0xe7ed, 0x2626}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0xbcae, 0x0bd1, 0x0ff7, 0x3a30, 0x7240, 0x83b7}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0xb2c6, 0x170a, 0x0a23, 0x6bbe, 0xb593, 0x82db}, {0x275b, 0x8ad3, 0x002c, 0x27b5, 0x8ad3, 0x002c}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x33a1, 0x8a01, 0x4d42, 0xd9cb, 0xb865, 0xb336}, {0x8c06, 0x78fc, 0x8f9a, 0x4df5, 0x4d53, 0x22f9}, {0x99e9, 0x0107, 0xef5e, 0x0560, 0xe6df, 0x4b36}, {0x31e7, 0x0023, 0xb2ae, 0xa2d7, 0xe540, 0x90b2}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, {0x33a1, 0x8a01, 0x4d42, 0xd9cb, 0xb865, 0xb336}, {0x33a1, 0x8a01, 0x4d42, 0xd9cb, 0xb865, 0xb336}, {0x33a1, 0x8a01, 0x4d42, 0xd9cb, 0xb865, 0xb336}, {0x33a1, 0x8a01, 0x4d42, 0xd9cb, 0xb865, 0xb336}, {0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff} } };
878f7c7ef869f7baaf5afd2163bdc9a76f72c06c
eecd5e4c50d8b78a769bcc2675250576bed34066
/src/ts/tutorials/ex18.c
88e4fb1abd12bf8ccae3b61572ef0f5ee45dfc0c
[ "BSD-2-Clause" ]
permissive
petsc/petsc
3b1a04fea71858e0292f9fd4d04ea11618c50969
9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9
refs/heads/main
2023-08-17T20:51:16.507070
2023-08-17T16:08:06
2023-08-17T16:08:06
8,691,401
341
169
NOASSERTION
2023-03-29T11:02:58
2013-03-10T20:55:21
C
UTF-8
C
false
false
59,796
c
ex18.c
static char help[] = "Hybrid Finite Element-Finite Volume Example.\n"; /*F Here we are advecting a passive tracer in a harmonic velocity field, defined by a forcing function $f$: \begin{align} -\Delta \mathbf{u} + f &= 0 \\ \frac{\partial\phi}{\partial t} + \nabla\cdot \phi \mathbf{u} &= 0 \end{align} F*/ #include <petscdmplex.h> #include <petscds.h> #include <petscts.h> #include <petsc/private/dmpleximpl.h> /* For DotD */ typedef enum { VEL_ZERO, VEL_CONSTANT, VEL_HARMONIC, VEL_SHEAR } VelocityDistribution; typedef enum { ZERO, CONSTANT, GAUSSIAN, TILTED, DELTA } PorosityDistribution; static PetscErrorCode constant_u_2d(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *); /* FunctionalFunc - Calculates the value of a functional of the solution at a point Input Parameters: + dm - The DM . time - The TS time . x - The coordinates of the evaluation point . u - The field values at point x - ctx - A user context, or NULL Output Parameter: . f - The value of the functional at point x */ typedef PetscErrorCode (*FunctionalFunc)(DM, PetscReal, const PetscReal *, const PetscScalar *, PetscReal *, void *); typedef struct _n_Functional *Functional; struct _n_Functional { char *name; FunctionalFunc func; void *ctx; PetscInt offset; Functional next; }; typedef struct { /* Problem definition */ PetscBool useFV; /* Use a finite volume scheme for advection */ PetscErrorCode (*initialGuess[2])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx); VelocityDistribution velocityDist; PorosityDistribution porosityDist; PetscReal inflowState; PetscReal source[3]; /* Monitoring */ PetscInt numMonitorFuncs, maxMonitorFunc; Functional *monitorFuncs; PetscInt errorFunctional; Functional functionalRegistry; } AppCtx; static AppCtx *globalUser; static PetscErrorCode ProcessOptions(MPI_Comm comm, AppCtx *options) { const char *velocityDist[4] = {"zero", "constant", "harmonic", "shear"}; const char *porosityDist[5] = {"zero", "constant", "gaussian", "tilted", "delta"}; PetscInt vd, pd, d; PetscBool flg; PetscFunctionBeginUser; options->useFV = PETSC_FALSE; options->velocityDist = VEL_HARMONIC; options->porosityDist = ZERO; options->inflowState = -2.0; options->numMonitorFuncs = 0; options->source[0] = 0.5; options->source[1] = 0.5; options->source[2] = 0.5; PetscOptionsBegin(comm, "", "Magma Dynamics Options", "DMPLEX"); PetscCall(PetscOptionsBool("-use_fv", "Use the finite volume method for advection", "ex18.c", options->useFV, &options->useFV, NULL)); vd = options->velocityDist; PetscCall(PetscOptionsEList("-velocity_dist", "Velocity distribution type", "ex18.c", velocityDist, 4, velocityDist[options->velocityDist], &vd, NULL)); options->velocityDist = (VelocityDistribution)vd; pd = options->porosityDist; PetscCall(PetscOptionsEList("-porosity_dist", "Initial porosity distribution type", "ex18.c", porosityDist, 5, porosityDist[options->porosityDist], &pd, NULL)); options->porosityDist = (PorosityDistribution)pd; PetscCall(PetscOptionsReal("-inflow_state", "The inflow state", "ex18.c", options->inflowState, &options->inflowState, NULL)); d = 2; PetscCall(PetscOptionsRealArray("-source_loc", "The source location", "ex18.c", options->source, &d, &flg)); PetscCheck(!flg || d == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Must give dim coordinates for the source location, not %" PetscInt_FMT, d); PetscOptionsEnd(); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode ProcessMonitorOptions(MPI_Comm comm, AppCtx *options) { Functional func; char *names[256]; PetscInt f; PetscFunctionBeginUser; PetscOptionsBegin(comm, "", "Simulation Monitor Options", "DMPLEX"); options->numMonitorFuncs = PETSC_STATIC_ARRAY_LENGTH(names); PetscCall(PetscOptionsStringArray("-monitor", "List of functionals to monitor", "", names, &options->numMonitorFuncs, NULL)); PetscCall(PetscMalloc1(options->numMonitorFuncs, &options->monitorFuncs)); for (f = 0; f < options->numMonitorFuncs; ++f) { for (func = options->functionalRegistry; func; func = func->next) { PetscBool match; PetscCall(PetscStrcasecmp(names[f], func->name, &match)); if (match) break; } PetscCheck(func, comm, PETSC_ERR_USER, "No known functional '%s'", names[f]); options->monitorFuncs[f] = func; /* Jed inserts a de-duplication of functionals here */ PetscCall(PetscFree(names[f])); } /* Find out the maximum index of any functional computed by a function we will be calling (even if we are not using it) */ options->maxMonitorFunc = -1; for (func = options->functionalRegistry; func; func = func->next) { for (f = 0; f < options->numMonitorFuncs; ++f) { Functional call = options->monitorFuncs[f]; if (func->func == call->func && func->ctx == call->ctx) options->maxMonitorFunc = PetscMax(options->maxMonitorFunc, func->offset); } } PetscOptionsEnd(); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode FunctionalRegister(Functional *functionalRegistry, const char name[], PetscInt *offset, FunctionalFunc func, void *ctx) { Functional *ptr, f; PetscInt lastoffset = -1; PetscFunctionBeginUser; for (ptr = functionalRegistry; *ptr; ptr = &(*ptr)->next) lastoffset = (*ptr)->offset; PetscCall(PetscNew(&f)); PetscCall(PetscStrallocpy(name, &f->name)); f->offset = lastoffset + 1; f->func = func; f->ctx = ctx; f->next = NULL; *ptr = f; *offset = f->offset; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode FunctionalDestroy(Functional *link) { Functional next, l; PetscFunctionBeginUser; if (!link) PetscFunctionReturn(PETSC_SUCCESS); l = *link; *link = NULL; for (; l; l = next) { next = l->next; PetscCall(PetscFree(l->name)); PetscCall(PetscFree(l)); } PetscFunctionReturn(PETSC_SUCCESS); } static void f0_zero_u(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]) { PetscInt comp; for (comp = 0; comp < dim; ++comp) f0[comp] = u[comp]; } static void f0_constant_u(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]) { PetscScalar wind[3] = {0.0, 0.0, 0.0}; PetscInt comp; PetscCallAbort(PETSC_COMM_SELF, constant_u_2d(dim, t, x, Nf, wind, NULL)); for (comp = 0; comp < dim && comp < 3; ++comp) f0[comp] = u[comp] - wind[comp]; } static void f1_constant_u(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f1[]) { PetscInt comp; for (comp = 0; comp < dim * dim; ++comp) f1[comp] = 0.0; } static void g0_constant_uu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]) { PetscInt d; for (d = 0; d < dim; ++d) g0[d * dim + d] = 1.0; } static void g0_constant_pp(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]) { g0[0] = 1.0; } static void f0_lap_u(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]) { PetscInt comp; for (comp = 0; comp < dim; ++comp) f0[comp] = 4.0; } static void f1_lap_u(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f1[]) { PetscInt comp, d; for (comp = 0; comp < dim; ++comp) { for (d = 0; d < dim; ++d) f1[comp * dim + d] = u_x[comp * dim + d]; } } static void f0_lap_periodic_u(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]) { f0[0] = -PetscSinReal(2.0 * PETSC_PI * x[0]); f0[1] = 2.0 * PETSC_PI * x[1] * PetscCosReal(2.0 * PETSC_PI * x[0]); } static void f0_lap_doubly_periodic_u(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]) { f0[0] = -2.0 * PetscSinReal(2.0 * PETSC_PI * x[0]) * PetscCosReal(2.0 * PETSC_PI * x[1]); f0[1] = 2.0 * PetscSinReal(2.0 * PETSC_PI * x[1]) * PetscCosReal(2.0 * PETSC_PI * x[0]); } void g3_uu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g3[]) { const PetscInt Ncomp = dim; PetscInt compI, d; for (compI = 0; compI < Ncomp; ++compI) { for (d = 0; d < dim; ++d) g3[((compI * Ncomp + compI) * dim + d) * dim + d] = 1.0; } } /* \frac{\partial\phi}{\partial t} + \nabla\phi \cdot \mathbf{u} + \phi \nabla \cdot \mathbf{u} = 0 */ static void f0_advection(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]) { PetscInt d; f0[0] = u_t[dim]; for (d = 0; d < dim; ++d) f0[0] += u[dim] * u_x[d * dim + d] + u_x[dim * dim + d] * u[d]; } static void f1_advection(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f1[]) { PetscInt d; for (d = 0; d < dim; ++d) f1[0] = 0.0; } void g0_adv_pp(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]) { PetscInt d; g0[0] = u_tShift; for (d = 0; d < dim; ++d) g0[0] += u_x[d * dim + d]; } void g1_adv_pp(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g1[]) { PetscInt d; for (d = 0; d < dim; ++d) g1[d] = u[d]; } void g0_adv_pu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]) { PetscInt d; for (d = 0; d < dim; ++d) g0[0] += u_x[dim * dim + d]; } void g1_adv_pu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g1[]) { PetscInt d; for (d = 0; d < dim; ++d) g1[d * dim + d] = u[dim]; } static void riemann_advection(PetscInt dim, PetscInt Nf, const PetscReal *qp, const PetscReal *n, const PetscScalar *uL, const PetscScalar *uR, PetscInt numConstants, const PetscScalar constants[], PetscScalar *flux, void *ctx) { PetscReal wind[3] = {0.0, 1.0, 0.0}; PetscReal wn = DMPlex_DotRealD_Internal(PetscMin(dim, 3), wind, n); flux[0] = (wn > 0 ? uL[dim] : uR[dim]) * wn; } static void riemann_coupled_advection(PetscInt dim, PetscInt Nf, const PetscReal *qp, const PetscReal *n, const PetscScalar *uL, const PetscScalar *uR, PetscInt numConstants, const PetscScalar constants[], PetscScalar *flux, void *ctx) { PetscReal wn = DMPlex_DotD_Internal(dim, uL, n); #if 1 flux[0] = (wn > 0 ? uL[dim] : uR[dim]) * wn; #else /* if (fabs(uL[0] - wind[0]) > 1.0e-7 || fabs(uL[1] - wind[1]) > 1.0e-7) PetscPrintf(PETSC_COMM_SELF, "wind (%g, %g) uL (%g, %g) uR (%g, %g)\n", wind[0], wind[1], uL[0], uL[1], uR[0], uR[1]); */ /* Smear it out */ flux[0] = 0.5 * ((uL[dim] + uR[dim]) + (uL[dim] - uR[dim]) * tanh(1.0e5 * wn)) * wn; #endif } static PetscErrorCode zero_u_2d(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) { u[0] = 0.0; u[1] = 0.0; return PETSC_SUCCESS; } static PetscErrorCode constant_u_2d(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) { u[0] = 0.0; u[1] = 1.0; return PETSC_SUCCESS; } /* Coordinates of the point which was at x at t = 0 */ static PetscErrorCode constant_x_2d(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) { const PetscReal t = *((PetscReal *)ctx); u[0] = x[0]; u[1] = x[1] + t; #if 0 PetscCall(DMLocalizeCoordinate(globalUser->dm, u, PETSC_FALSE, u)); #else u[1] = u[1] - (int)PetscRealPart(u[1]); #endif return PETSC_SUCCESS; } /* In 2D we use the exact solution: u = x^2 + y^2 v = 2 x^2 - 2xy phi = h(x + y + (u + v) t) f_x = f_y = 4 so that -\Delta u + f = <-4, -4> + <4, 4> = 0 {\partial\phi}{\partial t} - \nabla\cdot \phi u = 0 h_t(x + y + (u + v) t) - u . grad phi - phi div u = u h' + v h' - u h_x - v h_y = 0 We will conserve phi since \nabla \cdot u = 2x - 2x = 0 Also try h((x + ut)^2 + (y + vt)^2), so that h_t((x + ut)^2 + (y + vt)^2) - u . grad phi - phi div u = 2 h' (u (x + ut) + v (y + vt)) - u h_x - v h_y = 2 h' (u (x + ut) + v (y + vt)) - u h' 2 (x + u t) - v h' 2 (y + vt) = 2 h' (u (x + ut) + v (y + vt) - u (x + u t) - v (y + vt)) = 0 */ static PetscErrorCode quadratic_u_2d(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) { u[0] = x[0] * x[0] + x[1] * x[1]; u[1] = 2.0 * x[0] * x[0] - 2.0 * x[0] * x[1]; return PETSC_SUCCESS; } /* In 2D we use the exact, periodic solution: u = sin(2 pi x)/4 pi^2 v = -y cos(2 pi x)/2 pi phi = h(x + y + (u + v) t) f_x = -sin(2 pi x) f_y = 2 pi y cos(2 pi x) so that -\Delta u + f = <sin(2pi x), -2pi y cos(2pi x)> + <-sin(2pi x), 2pi y cos(2pi x)> = 0 We will conserve phi since \nabla \cdot u = cos(2pi x)/2pi - cos(2pi x)/2pi = 0 */ static PetscErrorCode periodic_u_2d(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) { u[0] = PetscSinReal(2.0 * PETSC_PI * x[0]) / PetscSqr(2.0 * PETSC_PI); u[1] = -x[1] * PetscCosReal(2.0 * PETSC_PI * x[0]) / (2.0 * PETSC_PI); return PETSC_SUCCESS; } /* In 2D we use the exact, doubly periodic solution: u = sin(2 pi x) cos(2 pi y)/4 pi^2 v = -sin(2 pi y) cos(2 pi x)/4 pi^2 phi = h(x + y + (u + v) t) f_x = -2sin(2 pi x) cos(2 pi y) f_y = 2sin(2 pi y) cos(2 pi x) so that -\Delta u + f = <2 sin(2pi x) cos(2pi y), -2 sin(2pi y) cos(2pi x)> + <-2 sin(2pi x) cos(2pi y), 2 sin(2pi y) cos(2pi x)> = 0 We will conserve phi since \nabla \cdot u = cos(2pi x) cos(2pi y)/2pi - cos(2pi y) cos(2pi x)/2pi = 0 */ static PetscErrorCode doubly_periodic_u_2d(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) { u[0] = PetscSinReal(2.0 * PETSC_PI * x[0]) * PetscCosReal(2.0 * PETSC_PI * x[1]) / PetscSqr(2.0 * PETSC_PI); u[1] = -PetscSinReal(2.0 * PETSC_PI * x[1]) * PetscCosReal(2.0 * PETSC_PI * x[0]) / PetscSqr(2.0 * PETSC_PI); return PETSC_SUCCESS; } static PetscErrorCode shear_bc(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) { u[0] = x[1] - 0.5; u[1] = 0.0; return PETSC_SUCCESS; } static PetscErrorCode initialVelocity(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) { PetscInt d; for (d = 0; d < dim; ++d) u[d] = 0.0; return PETSC_SUCCESS; } static PetscErrorCode zero_phi(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) { u[0] = 0.0; return PETSC_SUCCESS; } static PetscErrorCode constant_phi(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) { u[0] = 1.0; return PETSC_SUCCESS; } static PetscErrorCode delta_phi_2d(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) { PetscReal x0[2]; PetscScalar xn[2]; x0[0] = globalUser->source[0]; x0[1] = globalUser->source[1]; PetscCall(constant_x_2d(dim, time, x0, Nf, xn, ctx)); { const PetscReal xi = x[0] - PetscRealPart(xn[0]); const PetscReal eta = x[1] - PetscRealPart(xn[1]); const PetscReal r2 = xi * xi + eta * eta; u[0] = r2 < 1.0e-7 ? 1.0 : 0.0; } return PETSC_SUCCESS; } /* Gaussian blob, initially centered on (0.5, 0.5) xi = x(t) - x0, eta = y(t) - y0 where x(t), y(t) are the integral curves of v(t), dx/dt . grad f = v . f Check: constant v(t) = {v0, w0}, x(t) = {x0 + v0 t, y0 + w0 t} v0 f_x + w0 f_y = v . f */ static PetscErrorCode gaussian_phi_2d(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) { const PetscReal x0[2] = {0.5, 0.5}; const PetscReal sigma = 1.0 / 6.0; PetscScalar xn[2]; PetscCall(constant_x_2d(dim, time, x0, Nf, xn, ctx)); { /* const PetscReal xi = x[0] + (sin(2.0*PETSC_PI*x[0])/(4.0*PETSC_PI*PETSC_PI))*t - x0[0]; */ /* const PetscReal eta = x[1] + (-x[1]*cos(2.0*PETSC_PI*x[0])/(2.0*PETSC_PI))*t - x0[1]; */ const PetscReal xi = x[0] - PetscRealPart(xn[0]); const PetscReal eta = x[1] - PetscRealPart(xn[1]); const PetscReal r2 = xi * xi + eta * eta; u[0] = PetscExpReal(-r2 / (2.0 * sigma * sigma)) / (sigma * PetscSqrtReal(2.0 * PETSC_PI)); } return PETSC_SUCCESS; } static PetscErrorCode tilted_phi_2d(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) { PetscReal x0[3]; const PetscReal wind[3] = {0.0, 1.0, 0.0}; const PetscReal t = *((PetscReal *)ctx); DMPlex_WaxpyD_Internal(2, -t, wind, x, x0); if (x0[1] > 0) u[0] = 1.0 * x[0] + 3.0 * x[1]; else u[0] = -2.0; /* Inflow state */ return PETSC_SUCCESS; } static PetscErrorCode tilted_phi_coupled_2d(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) { PetscReal ur[3]; PetscReal x0[3]; const PetscReal t = *((PetscReal *)ctx); ur[0] = PetscRealPart(u[0]); ur[1] = PetscRealPart(u[1]); ur[2] = PetscRealPart(u[2]); DMPlex_WaxpyD_Internal(2, -t, ur, x, x0); if (x0[1] > 0) u[0] = 1.0 * x[0] + 3.0 * x[1]; else u[0] = -2.0; /* Inflow state */ return PETSC_SUCCESS; } static PetscErrorCode advect_inflow(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *xI, PetscScalar *xG, void *ctx) { AppCtx *user = (AppCtx *)ctx; PetscFunctionBeginUser; xG[0] = user->inflowState; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode advect_outflow(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *xI, PetscScalar *xG, void *ctx) { PetscFunctionBeginUser; //xG[0] = xI[dim]; xG[0] = xI[2]; PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode ExactSolution(DM dm, PetscReal time, const PetscReal *x, PetscScalar *u, void *ctx) { AppCtx *user = (AppCtx *)ctx; PetscInt dim; PetscFunctionBeginUser; PetscCall(DMGetDimension(dm, &dim)); switch (user->porosityDist) { case TILTED: if (user->velocityDist == VEL_ZERO) PetscCall(tilted_phi_2d(dim, time, x, 2, u, (void *)&time)); else PetscCall(tilted_phi_coupled_2d(dim, time, x, 2, u, (void *)&time)); break; case GAUSSIAN: PetscCall(gaussian_phi_2d(dim, time, x, 2, u, (void *)&time)); break; case DELTA: PetscCall(delta_phi_2d(dim, time, x, 2, u, (void *)&time)); break; default: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Unknown solution type"); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode Functional_Error(DM dm, PetscReal time, const PetscReal *x, const PetscScalar *y, PetscReal *f, void *ctx) { AppCtx *user = (AppCtx *)ctx; PetscScalar yexact[3] = {0, 0, 0}; PetscFunctionBeginUser; PetscCall(ExactSolution(dm, time, x, yexact, ctx)); f[user->errorFunctional] = PetscAbsScalar(y[0] - yexact[0]); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode CreateMesh(MPI_Comm comm, AppCtx *user, DM *dm) { PetscFunctionBeginUser; PetscCall(DMCreate(comm, dm)); PetscCall(DMSetType(*dm, DMPLEX)); PetscCall(DMSetFromOptions(*dm)); PetscCall(DMViewFromOptions(*dm, NULL, "-orig_dm_view")); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode SetupBC(DM dm, AppCtx *user) { PetscErrorCode (*exactFuncs[2])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx); DMBoundaryType bdt[3] = {DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE}; PetscDS prob; DMLabel label; PetscBool check; PetscInt dim, n = 3; const char *prefix; PetscFunctionBeginUser; PetscCall(PetscObjectGetOptionsPrefix((PetscObject)dm, &prefix)); PetscCall(PetscOptionsGetEnumArray(NULL, prefix, "-dm_plex_box_bd", DMBoundaryTypes, (PetscEnum *)bdt, &n, NULL)); PetscCall(DMGetDimension(dm, &dim)); /* Set initial guesses and exact solutions */ switch (dim) { case 2: user->initialGuess[0] = initialVelocity; switch (user->porosityDist) { case ZERO: user->initialGuess[1] = zero_phi; break; case CONSTANT: user->initialGuess[1] = constant_phi; break; case GAUSSIAN: user->initialGuess[1] = gaussian_phi_2d; break; case DELTA: user->initialGuess[1] = delta_phi_2d; break; case TILTED: if (user->velocityDist == VEL_ZERO) user->initialGuess[1] = tilted_phi_2d; else user->initialGuess[1] = tilted_phi_coupled_2d; break; } break; default: SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_SUP, "Dimension %" PetscInt_FMT " not supported", dim); } exactFuncs[0] = user->initialGuess[0]; exactFuncs[1] = user->initialGuess[1]; switch (dim) { case 2: switch (user->velocityDist) { case VEL_ZERO: exactFuncs[0] = zero_u_2d; break; case VEL_CONSTANT: exactFuncs[0] = constant_u_2d; break; case VEL_HARMONIC: switch (bdt[0]) { case DM_BOUNDARY_PERIODIC: switch (bdt[1]) { case DM_BOUNDARY_PERIODIC: exactFuncs[0] = doubly_periodic_u_2d; break; default: exactFuncs[0] = periodic_u_2d; break; } break; default: exactFuncs[0] = quadratic_u_2d; break; } break; case VEL_SHEAR: exactFuncs[0] = shear_bc; break; default: SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "Invalid dimension %" PetscInt_FMT, dim); } break; default: SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_SUP, "Dimension %" PetscInt_FMT " not supported", dim); } { PetscBool isImplicit = PETSC_FALSE; PetscCall(PetscOptionsHasName(NULL, "", "-use_implicit", &isImplicit)); if (user->velocityDist == VEL_CONSTANT && !isImplicit) user->initialGuess[0] = exactFuncs[0]; } PetscCall(PetscOptionsHasName(NULL, NULL, "-dmts_check", &check)); if (check) { user->initialGuess[0] = exactFuncs[0]; user->initialGuess[1] = exactFuncs[1]; } /* Set BC */ PetscCall(DMGetDS(dm, &prob)); PetscCall(DMGetLabel(dm, "marker", &label)); PetscCall(PetscDSSetExactSolution(prob, 0, exactFuncs[0], user)); PetscCall(PetscDSSetExactSolution(prob, 1, exactFuncs[1], user)); if (label) { const PetscInt id = 1; PetscCall(DMAddBoundary(dm, DM_BC_ESSENTIAL, "wall", label, 1, &id, 0, 0, NULL, (void (*)(void))exactFuncs[0], NULL, user, NULL)); } PetscCall(DMGetLabel(dm, "Face Sets", &label)); if (label && user->useFV) { const PetscInt inflowids[] = {100, 200, 300}, outflowids[] = {101}; PetscCall(DMAddBoundary(dm, DM_BC_NATURAL_RIEMANN, "inflow", label, PETSC_STATIC_ARRAY_LENGTH(inflowids), inflowids, 1, 0, NULL, (void (*)(void))advect_inflow, NULL, user, NULL)); PetscCall(DMAddBoundary(dm, DM_BC_NATURAL_RIEMANN, "outflow", label, PETSC_STATIC_ARRAY_LENGTH(outflowids), outflowids, 1, 0, NULL, (void (*)(void))advect_outflow, NULL, user, NULL)); } PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode SetupProblem(DM dm, AppCtx *user) { DMBoundaryType bdt[3] = {DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE}; PetscDS prob; PetscInt n = 3; const char *prefix; PetscFunctionBeginUser; PetscCall(PetscObjectGetOptionsPrefix((PetscObject)dm, &prefix)); PetscCall(PetscOptionsGetEnumArray(NULL, prefix, "-dm_plex_box_bd", DMBoundaryTypes, (PetscEnum *)bdt, &n, NULL)); PetscCall(DMGetDS(dm, &prob)); switch (user->velocityDist) { case VEL_ZERO: PetscCall(PetscDSSetResidual(prob, 0, f0_zero_u, f1_constant_u)); break; case VEL_CONSTANT: PetscCall(PetscDSSetResidual(prob, 0, f0_constant_u, f1_constant_u)); PetscCall(PetscDSSetJacobian(prob, 0, 0, g0_constant_uu, NULL, NULL, NULL)); PetscCall(PetscDSSetJacobian(prob, 1, 1, g0_constant_pp, NULL, NULL, NULL)); break; case VEL_HARMONIC: switch (bdt[0]) { case DM_BOUNDARY_PERIODIC: switch (bdt[1]) { case DM_BOUNDARY_PERIODIC: PetscCall(PetscDSSetResidual(prob, 0, f0_lap_doubly_periodic_u, f1_lap_u)); break; default: PetscCall(PetscDSSetResidual(prob, 0, f0_lap_periodic_u, f1_lap_u)); break; } break; default: PetscCall(PetscDSSetResidual(prob, 0, f0_lap_u, f1_lap_u)); break; } PetscCall(PetscDSSetJacobian(prob, 0, 0, NULL, NULL, NULL, g3_uu)); break; case VEL_SHEAR: PetscCall(PetscDSSetResidual(prob, 0, f0_zero_u, f1_lap_u)); PetscCall(PetscDSSetJacobian(prob, 0, 0, NULL, NULL, NULL, g3_uu)); break; } PetscCall(PetscDSSetResidual(prob, 1, f0_advection, f1_advection)); PetscCall(PetscDSSetJacobian(prob, 1, 1, g0_adv_pp, g1_adv_pp, NULL, NULL)); PetscCall(PetscDSSetJacobian(prob, 1, 0, g0_adv_pu, g1_adv_pu, NULL, NULL)); if (user->velocityDist == VEL_ZERO) PetscCall(PetscDSSetRiemannSolver(prob, 1, riemann_advection)); else PetscCall(PetscDSSetRiemannSolver(prob, 1, riemann_coupled_advection)); PetscCall(FunctionalRegister(&user->functionalRegistry, "Error", &user->errorFunctional, Functional_Error, user)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode SetupDiscretization(DM dm, AppCtx *user) { DM cdm = dm; PetscQuadrature q; PetscFE fe[2]; PetscFV fv; MPI_Comm comm; PetscInt dim; PetscFunctionBeginUser; /* Create finite element */ PetscCall(PetscObjectGetComm((PetscObject)dm, &comm)); PetscCall(DMGetDimension(dm, &dim)); PetscCall(PetscFECreateDefault(comm, dim, dim, PETSC_FALSE, "velocity_", PETSC_DEFAULT, &fe[0])); PetscCall(PetscObjectSetName((PetscObject)fe[0], "velocity")); PetscCall(PetscFECreateDefault(comm, dim, 1, PETSC_FALSE, "porosity_", PETSC_DEFAULT, &fe[1])); PetscCall(PetscFECopyQuadrature(fe[0], fe[1])); PetscCall(PetscObjectSetName((PetscObject)fe[1], "porosity")); PetscCall(PetscFVCreate(PetscObjectComm((PetscObject)dm), &fv)); PetscCall(PetscObjectSetName((PetscObject)fv, "porosity")); PetscCall(PetscFVSetFromOptions(fv)); PetscCall(PetscFVSetNumComponents(fv, 1)); PetscCall(PetscFVSetSpatialDimension(fv, dim)); PetscCall(PetscFEGetQuadrature(fe[0], &q)); PetscCall(PetscFVSetQuadrature(fv, q)); PetscCall(DMSetField(dm, 0, NULL, (PetscObject)fe[0])); if (user->useFV) PetscCall(DMSetField(dm, 1, NULL, (PetscObject)fv)); else PetscCall(DMSetField(dm, 1, NULL, (PetscObject)fe[1])); PetscCall(DMCreateDS(dm)); PetscCall(SetupProblem(dm, user)); /* Set discretization and boundary conditions for each mesh */ while (cdm) { PetscCall(DMCopyDisc(dm, cdm)); PetscCall(DMGetCoarseDM(cdm, &cdm)); /* Coordinates were never localized for coarse meshes */ if (cdm) PetscCall(DMLocalizeCoordinates(cdm)); } PetscCall(PetscFEDestroy(&fe[0])); PetscCall(PetscFEDestroy(&fe[1])); PetscCall(PetscFVDestroy(&fv)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode CreateDM(MPI_Comm comm, AppCtx *user, DM *dm) { PetscFunctionBeginUser; PetscCall(CreateMesh(comm, user, dm)); /* Handle refinement, etc. */ PetscCall(DMSetFromOptions(*dm)); /* Construct ghost cells */ if (user->useFV) { DM gdm; PetscCall(DMPlexConstructGhostCells(*dm, NULL, NULL, &gdm)); PetscCall(DMDestroy(dm)); *dm = gdm; } /* Localize coordinates */ PetscCall(DMLocalizeCoordinates(*dm)); PetscCall(PetscObjectSetName((PetscObject)(*dm), "Mesh")); PetscCall(DMViewFromOptions(*dm, NULL, "-dm_view")); /* Setup problem */ PetscCall(SetupDiscretization(*dm, user)); /* Setup BC */ PetscCall(SetupBC(*dm, user)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode SetInitialConditionFVM(DM dm, Vec X, PetscInt field, PetscErrorCode (*func)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void *ctx) { PetscDS prob; DM dmCell; Vec cellgeom; const PetscScalar *cgeom; PetscScalar *x; PetscInt dim, Nf, cStart, cEnd, c; PetscFunctionBeginUser; PetscCall(DMGetDS(dm, &prob)); PetscCall(DMGetDimension(dm, &dim)); PetscCall(PetscDSGetNumFields(prob, &Nf)); PetscCall(DMPlexGetGeometryFVM(dm, NULL, &cellgeom, NULL)); PetscCall(VecGetDM(cellgeom, &dmCell)); PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd)); PetscCall(VecGetArrayRead(cellgeom, &cgeom)); PetscCall(VecGetArray(X, &x)); for (c = cStart; c < cEnd; ++c) { PetscFVCellGeom *cg; PetscScalar *xc; PetscCall(DMPlexPointLocalRead(dmCell, c, cgeom, &cg)); PetscCall(DMPlexPointGlobalFieldRef(dm, c, field, x, &xc)); if (xc) PetscCall((*func)(dim, 0.0, cg->centroid, Nf, xc, ctx)); } PetscCall(VecRestoreArrayRead(cellgeom, &cgeom)); PetscCall(VecRestoreArray(X, &x)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode MonitorFunctionals(TS ts, PetscInt stepnum, PetscReal time, Vec X, void *ctx) { AppCtx *user = (AppCtx *)ctx; char *ftable = NULL; DM dm; PetscSection s; Vec cellgeom; const PetscScalar *x; PetscScalar *a; PetscReal *xnorms; PetscInt pStart, pEnd, p, Nf, f; PetscFunctionBeginUser; PetscCall(VecViewFromOptions(X, (PetscObject)ts, "-view_solution")); PetscCall(VecGetDM(X, &dm)); PetscCall(DMPlexGetGeometryFVM(dm, NULL, &cellgeom, NULL)); PetscCall(DMGetLocalSection(dm, &s)); PetscCall(PetscSectionGetNumFields(s, &Nf)); PetscCall(PetscSectionGetChart(s, &pStart, &pEnd)); PetscCall(PetscCalloc1(Nf * 2, &xnorms)); PetscCall(VecGetArrayRead(X, &x)); for (p = pStart; p < pEnd; ++p) { for (f = 0; f < Nf; ++f) { PetscInt dof, cdof, d; PetscCall(PetscSectionGetFieldDof(s, p, f, &dof)); PetscCall(PetscSectionGetFieldConstraintDof(s, p, f, &cdof)); PetscCall(DMPlexPointGlobalFieldRead(dm, p, f, x, &a)); /* TODO Use constrained indices here */ for (d = 0; d < dof - cdof; ++d) xnorms[f * 2 + 0] = PetscMax(xnorms[f * 2 + 0], PetscAbsScalar(a[d])); for (d = 0; d < dof - cdof; ++d) xnorms[f * 2 + 1] += PetscAbsScalar(a[d]); } } PetscCall(VecRestoreArrayRead(X, &x)); if (stepnum >= 0) { /* No summary for final time */ DM dmCell, *fdm; Vec *fv; const PetscScalar *cgeom; PetscScalar **fx; PetscReal *fmin, *fmax, *fint, *ftmp, t; PetscInt cStart, cEnd, c, fcount, f, num; size_t ftableused, ftablealloc; /* Functionals have indices after registering, this is an upper bound */ fcount = user->numMonitorFuncs; PetscCall(PetscMalloc4(fcount, &fmin, fcount, &fmax, fcount, &fint, fcount, &ftmp)); PetscCall(PetscMalloc3(fcount, &fdm, fcount, &fv, fcount, &fx)); for (f = 0; f < fcount; ++f) { PetscSection fs; const char *name = user->monitorFuncs[f]->name; fmin[f] = PETSC_MAX_REAL; fmax[f] = PETSC_MIN_REAL; fint[f] = 0; /* Make monitor vecs */ PetscCall(DMClone(dm, &fdm[f])); PetscCall(DMGetOutputSequenceNumber(dm, &num, &t)); PetscCall(DMSetOutputSequenceNumber(fdm[f], num, t)); PetscCall(PetscSectionClone(s, &fs)); PetscCall(PetscSectionSetFieldName(fs, 0, NULL)); PetscCall(PetscSectionSetFieldName(fs, 1, name)); PetscCall(DMSetLocalSection(fdm[f], fs)); PetscCall(PetscSectionDestroy(&fs)); PetscCall(DMGetGlobalVector(fdm[f], &fv[f])); PetscCall(PetscObjectSetName((PetscObject)fv[f], name)); PetscCall(VecGetArray(fv[f], &fx[f])); } PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd)); PetscCall(VecGetDM(cellgeom, &dmCell)); PetscCall(VecGetArrayRead(cellgeom, &cgeom)); PetscCall(VecGetArrayRead(X, &x)); for (c = cStart; c < cEnd; ++c) { PetscFVCellGeom *cg; PetscScalar *cx; PetscCall(DMPlexPointLocalRead(dmCell, c, cgeom, &cg)); PetscCall(DMPlexPointGlobalFieldRead(dm, c, 1, x, &cx)); if (!cx) continue; /* not a global cell */ for (f = 0; f < user->numMonitorFuncs; ++f) { Functional func = user->monitorFuncs[f]; PetscScalar *fxc; PetscCall(DMPlexPointGlobalFieldRef(dm, c, 1, fx[f], &fxc)); /* I need to make it easier to get interpolated values here */ PetscCall((*func->func)(dm, time, cg->centroid, cx, ftmp, func->ctx)); fxc[0] = ftmp[user->monitorFuncs[f]->offset]; } for (f = 0; f < fcount; ++f) { fmin[f] = PetscMin(fmin[f], ftmp[f]); fmax[f] = PetscMax(fmax[f], ftmp[f]); fint[f] += cg->volume * ftmp[f]; } } PetscCall(VecRestoreArrayRead(cellgeom, &cgeom)); PetscCall(VecRestoreArrayRead(X, &x)); PetscCall(MPIU_Allreduce(MPI_IN_PLACE, fmin, fcount, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)ts))); PetscCall(MPIU_Allreduce(MPI_IN_PLACE, fmax, fcount, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)ts))); PetscCall(MPIU_Allreduce(MPI_IN_PLACE, fint, fcount, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)ts))); /* Output functional data */ ftablealloc = fcount * 100; ftableused = 0; PetscCall(PetscCalloc1(ftablealloc, &ftable)); for (f = 0; f < user->numMonitorFuncs; ++f) { Functional func = user->monitorFuncs[f]; PetscInt id = func->offset; char newline[] = "\n"; char buffer[256], *p, *prefix; size_t countused, len; /* Create string with functional outputs */ if (f % 3) { PetscCall(PetscArraycpy(buffer, " ", 2)); p = buffer + 2; } else if (f) { PetscCall(PetscArraycpy(buffer, newline, sizeof(newline) - 1)); p = buffer + sizeof(newline) - 1; } else { p = buffer; } PetscCall(PetscSNPrintfCount(p, sizeof buffer - (p - buffer), "%12s [%12.6g,%12.6g] int %12.6g", &countused, func->name, (double)fmin[id], (double)fmax[id], (double)fint[id])); countused += p - buffer; /* reallocate */ if (countused > ftablealloc - ftableused - 1) { char *ftablenew; ftablealloc = 2 * ftablealloc + countused; PetscCall(PetscMalloc1(ftablealloc, &ftablenew)); PetscCall(PetscArraycpy(ftablenew, ftable, ftableused)); PetscCall(PetscFree(ftable)); ftable = ftablenew; } PetscCall(PetscArraycpy(ftable + ftableused, buffer, countused)); ftableused += countused; ftable[ftableused] = 0; /* Output vecs */ PetscCall(VecRestoreArray(fv[f], &fx[f])); PetscCall(PetscStrlen(func->name, &len)); PetscCall(PetscMalloc1(len + 2, &prefix)); PetscCall(PetscStrncpy(prefix, func->name, len + 2)); PetscCall(PetscStrlcat(prefix, "_", len + 2)); PetscCall(PetscObjectSetOptionsPrefix((PetscObject)fv[f], prefix)); PetscCall(VecViewFromOptions(fv[f], NULL, "-vec_view")); PetscCall(PetscFree(prefix)); PetscCall(DMRestoreGlobalVector(fdm[f], &fv[f])); PetscCall(DMDestroy(&fdm[f])); } PetscCall(PetscFree4(fmin, fmax, fint, ftmp)); PetscCall(PetscFree3(fdm, fv, fx)); PetscCall(PetscPrintf(PetscObjectComm((PetscObject)ts), "% 3" PetscInt_FMT " time %8.4g |x| (", stepnum, (double)time)); for (f = 0; f < Nf; ++f) { if (f > 0) PetscCall(PetscPrintf(PetscObjectComm((PetscObject)ts), ", ")); PetscCall(PetscPrintf(PetscObjectComm((PetscObject)ts), "%8.4g", (double)xnorms[f * 2 + 0])); } PetscCall(PetscPrintf(PetscObjectComm((PetscObject)ts), ") |x|_1 (")); for (f = 0; f < Nf; ++f) { if (f > 0) PetscCall(PetscPrintf(PetscObjectComm((PetscObject)ts), ", ")); PetscCall(PetscPrintf(PetscObjectComm((PetscObject)ts), "%8.4g", (double)xnorms[f * 2 + 1])); } PetscCall(PetscPrintf(PetscObjectComm((PetscObject)ts), ") %s\n", ftable ? ftable : "")); PetscCall(PetscFree(ftable)); } PetscCall(PetscFree(xnorms)); PetscFunctionReturn(PETSC_SUCCESS); } int main(int argc, char **argv) { MPI_Comm comm; TS ts; DM dm; Vec u; AppCtx user; PetscReal t0, t = 0.0; void *ctxs[2]; ctxs[0] = &t; ctxs[1] = &t; PetscFunctionBeginUser; PetscCall(PetscInitialize(&argc, &argv, (char *)0, help)); comm = PETSC_COMM_WORLD; user.functionalRegistry = NULL; globalUser = &user; PetscCall(ProcessOptions(comm, &user)); PetscCall(TSCreate(comm, &ts)); PetscCall(TSSetType(ts, TSBEULER)); PetscCall(CreateDM(comm, &user, &dm)); PetscCall(TSSetDM(ts, dm)); PetscCall(ProcessMonitorOptions(comm, &user)); PetscCall(DMCreateGlobalVector(dm, &u)); PetscCall(PetscObjectSetName((PetscObject)u, "solution")); if (user.useFV) { PetscBool isImplicit = PETSC_FALSE; PetscCall(PetscOptionsHasName(NULL, "", "-use_implicit", &isImplicit)); if (isImplicit) { PetscCall(DMTSSetIFunctionLocal(dm, DMPlexTSComputeIFunctionFEM, &user)); PetscCall(DMTSSetIJacobianLocal(dm, DMPlexTSComputeIJacobianFEM, &user)); } PetscCall(DMTSSetBoundaryLocal(dm, DMPlexTSComputeBoundary, &user)); PetscCall(DMTSSetRHSFunctionLocal(dm, DMPlexTSComputeRHSFunctionFVM, &user)); } else { PetscCall(DMTSSetBoundaryLocal(dm, DMPlexTSComputeBoundary, &user)); PetscCall(DMTSSetIFunctionLocal(dm, DMPlexTSComputeIFunctionFEM, &user)); PetscCall(DMTSSetIJacobianLocal(dm, DMPlexTSComputeIJacobianFEM, &user)); } if (user.useFV) PetscCall(TSMonitorSet(ts, MonitorFunctionals, &user, NULL)); PetscCall(TSSetMaxSteps(ts, 1)); PetscCall(TSSetMaxTime(ts, 2.0)); PetscCall(TSSetTimeStep(ts, 0.01)); PetscCall(TSSetExactFinalTime(ts, TS_EXACTFINALTIME_STEPOVER)); PetscCall(TSSetFromOptions(ts)); PetscCall(DMProjectFunction(dm, 0.0, user.initialGuess, ctxs, INSERT_VALUES, u)); if (user.useFV) PetscCall(SetInitialConditionFVM(dm, u, 1, user.initialGuess[1], ctxs[1])); PetscCall(VecViewFromOptions(u, NULL, "-init_vec_view")); PetscCall(TSGetTime(ts, &t)); t0 = t; PetscCall(DMTSCheckFromOptions(ts, u)); PetscCall(TSSolve(ts, u)); PetscCall(TSGetTime(ts, &t)); if (t > t0) PetscCall(DMTSCheckFromOptions(ts, u)); PetscCall(VecViewFromOptions(u, NULL, "-sol_vec_view")); { PetscReal ftime; PetscInt nsteps; TSConvergedReason reason; PetscCall(TSGetSolveTime(ts, &ftime)); PetscCall(TSGetStepNumber(ts, &nsteps)); PetscCall(TSGetConvergedReason(ts, &reason)); PetscCall(PetscPrintf(PETSC_COMM_WORLD, "%s at time %g after %" PetscInt_FMT " steps\n", TSConvergedReasons[reason], (double)ftime, nsteps)); } PetscCall(VecDestroy(&u)); PetscCall(DMDestroy(&dm)); PetscCall(TSDestroy(&ts)); PetscCall(PetscFree(user.monitorFuncs)); PetscCall(FunctionalDestroy(&user.functionalRegistry)); PetscCall(PetscFinalize()); return 0; } /*TEST testset: args: -dm_plex_simplex 0 -dm_plex_box_faces 3,3,3 # 2D harmonic velocity, no porosity test: suffix: p1p1 requires: !complex !single args: -velocity_petscspace_degree 1 -porosity_petscspace_degree 1 -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -pc_factor_shift_type nonzero -ts_monitor -snes_error_if_not_converged -ksp_error_if_not_converged -dmts_check test: suffix: p1p1_xper requires: !complex !single args: -dm_refine 1 -dm_plex_box_bd periodic,none -velocity_petscspace_degree 1 -porosity_petscspace_degree 1 -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -pc_type lu -pc_factor_shift_type nonzero -ksp_rtol 1.0e-8 -ts_monitor -snes_error_if_not_converged -ksp_error_if_not_converged -dmts_check test: suffix: p1p1_xper_ref requires: !complex !single args: -dm_refine 2 -dm_plex_box_bd periodic,none -velocity_petscspace_degree 1 -porosity_petscspace_degree 1 -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -pc_type lu -pc_factor_shift_type nonzero -ksp_rtol 1.0e-8 -ts_monitor -snes_error_if_not_converged -ksp_error_if_not_converged -dmts_check test: suffix: p1p1_xyper requires: !complex !single args: -dm_refine 1 -dm_plex_box_bd periodic,periodic -velocity_petscspace_degree 1 -porosity_petscspace_degree 1 -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -pc_type lu -pc_factor_shift_type nonzero -ksp_rtol 1.0e-8 -ts_monitor -snes_error_if_not_converged -ksp_error_if_not_converged -dmts_check test: suffix: p1p1_xyper_ref requires: !complex !single args: -dm_refine 2 -dm_plex_box_bd periodic,periodic -velocity_petscspace_degree 1 -porosity_petscspace_degree 1 -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -pc_type lu -pc_factor_shift_type nonzero -ksp_rtol 1.0e-8 -ts_monitor -snes_error_if_not_converged -ksp_error_if_not_converged -dmts_check test: suffix: p2p1 requires: !complex !single args: -velocity_petscspace_degree 2 -porosity_petscspace_degree 1 -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -ts_monitor -snes_error_if_not_converged -ksp_error_if_not_converged -dmts_check test: suffix: p2p1_xyper requires: !complex !single args: -dm_refine 1 -dm_plex_box_bd periodic,periodic -velocity_petscspace_degree 2 -porosity_petscspace_degree 1 -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -pc_type lu -pc_factor_shift_type nonzero -ksp_rtol 1.0e-8 -ts_monitor -snes_error_if_not_converged -ksp_error_if_not_converged -dmts_check test: suffix: adv_1 requires: !complex !single args: -use_fv -velocity_dist zero -porosity_dist tilted -ts_type ssp -ts_max_time 2.0 -ts_max_steps 1000 -ts_dt 0.993392 -bc_inflow 1,2,4 -bc_outflow 3 -ts_view -dm_view test: suffix: adv_2 requires: !complex TODO: broken memory corruption args: -use_fv -velocity_dist zero -porosity_dist tilted -ts_type beuler -ts_max_time 2.0 -ts_max_steps 1000 -ts_dt 0.993392 -bc_inflow 3,4 -bc_outflow 1,2 -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -ksp_max_it 100 -ts_view -dm_view -snes_converged_reason -ksp_converged_reason test: suffix: adv_3 requires: !complex TODO: broken memory corruption args: -dm_plex_box_bd periodic,none -use_fv -velocity_dist zero -porosity_dist tilted -ts_type beuler -ts_max_time 2.0 -ts_max_steps 1000 -ts_dt 0.993392 -bc_inflow 3 -bc_outflow 1 -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -ksp_max_it 100 -ts_view -dm_view -snes_converged_reason test: suffix: adv_3_ex requires: !complex args: -dm_plex_box_bd periodic,none -use_fv -velocity_dist zero -porosity_dist tilted -ts_type ssp -ts_max_time 2.0 -ts_max_steps 1000 -ts_dt 0.1 -bc_inflow 3 -bc_outflow 1 -snes_fd_color -ksp_max_it 100 -ts_view -dm_view test: suffix: adv_4 requires: !complex TODO: broken memory corruption args: -use_fv -velocity_dist zero -porosity_dist tilted -ts_type beuler -ts_max_time 2.0 -ts_max_steps 1000 -ts_dt 0.993392 -bc_inflow 3 -bc_outflow 1 -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -ksp_max_it 100 -ts_view -dm_view -snes_converged_reason # 2D Advection, box, delta test: suffix: adv_delta_yper_0 requires: !complex TODO: broken args: -dm_plex_box_bd none,periodic -use_fv -velocity_dist constant -porosity_dist delta -inflow_state 0.0 -ts_type euler -ts_max_time 5.0 -ts_max_steps 20 -ts_dt 0.333333 -bc_inflow 2 -bc_outflow 4 -ts_view -dm_view -monitor Error test: suffix: adv_delta_yper_1 requires: !complex TODO: broken args: -dm_plex_box_bd none,periodic -use_fv -velocity_dist constant -porosity_dist delta -inflow_state 0.0 -ts_type euler -ts_max_time 5.0 -ts_max_steps 40 -ts_dt 0.166666 -bc_inflow 2 -bc_outflow 4 -ts_view -dm_view -monitor Error -dm_refine 1 -source_loc 0.416666,0.416666 test: suffix: adv_delta_yper_2 requires: !complex TODO: broken args: -dm_plex_box_bd none,periodic -use_fv -velocity_dist constant -porosity_dist delta -inflow_state 0.0 -ts_type euler -ts_max_time 5.0 -ts_max_steps 80 -ts_dt 0.083333 -bc_inflow 2 -bc_outflow 4 -ts_view -dm_view -monitor Error -dm_refine 2 -source_loc 0.458333,0.458333 test: suffix: adv_delta_yper_fim_0 requires: !complex TODO: broken args: -dm_plex_box_bd none,periodic -use_fv -use_implicit -velocity_petscspace_degree 0 -velocity_dist constant -porosity_dist delta -inflow_state 0.0 -ts_type mimex -ts_max_time 5.0 -ts_max_steps 20 -ts_dt 0.333333 -bc_inflow 2 -bc_outflow 4 -ts_view -monitor Error -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -mat_coloring_greedy_symmetric 0 -snes_rtol 1.0e-7 -pc_type lu -snes_converged_reason test: suffix: adv_delta_yper_fim_1 requires: !complex TODO: broken args: -dm_plex_box_bd none,periodic -use_fv -use_implicit -velocity_petscspace_degree 1 -velocity_dist constant -porosity_dist delta -inflow_state 0.0 -ts_type mimex -ts_max_time 5.0 -ts_max_steps 20 -ts_dt 0.333333 -bc_inflow 2 -bc_outflow 4 -ts_view -monitor Error -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -mat_coloring_greedy_symmetric 0 -snes_rtol 1.0e-7 -pc_type lu -snes_converged_reason -snes_linesearch_type basic test: suffix: adv_delta_yper_fim_2 requires: !complex TODO: broken args: -dm_plex_box_bd none,periodic -use_fv -use_implicit -velocity_petscspace_degree 2 -velocity_dist constant -porosity_dist delta -inflow_state 0.0 -ts_type mimex -ts_max_time 5.0 -ts_max_steps 20 -ts_dt 0.333333 -bc_inflow 2 -bc_outflow 4 -ts_view -monitor Error -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -mat_coloring_greedy_symmetric 0 -snes_rtol 1.0e-7 -pc_type lu -snes_converged_reason -snes_linesearch_type basic test: suffix: adv_delta_yper_im_0 requires: !complex TODO: broken args: -dm_plex_box_bd none,periodic -use_fv -use_implicit -velocity_petscspace_degree 0 -velocity_dist constant -porosity_dist delta -inflow_state 0.0 -ts_type mimex -ts_mimex_version 0 -ts_max_time 5.0 -ts_max_steps 20 -ts_dt 0.333333 -bc_inflow 2 -bc_outflow 4 -ts_view -monitor Error -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -snes_rtol 1.0e-7 -pc_type lu -snes_converged_reason test: suffix: adv_delta_yper_im_1 requires: !complex TODO: broken args: -dm_plex_box_bd none,periodic -use_fv -use_implicit -velocity_petscspace_degree 0 -velocity_dist constant -porosity_dist delta -inflow_state 0.0 -ts_type mimex -ts_mimex_version 0 -ts_max_time 5.0 -ts_max_steps 40 -ts_dt 0.166666 -bc_inflow 2 -bc_outflow 4 -ts_view -monitor Error -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -snes_rtol 1.0e-7 -pc_type lu -snes_converged_reason -dm_refine 1 -source_loc 0.416666,0.416666 test: suffix: adv_delta_yper_im_2 requires: !complex TODO: broken args: -dm_plex_box_bd none,periodic -use_fv -use_implicit -velocity_petscspace_degree 0 -velocity_dist constant -porosity_dist delta -inflow_state 0.0 -ts_type mimex -ts_mimex_version 0 -ts_max_time 5.0 -ts_max_steps 80 -ts_dt 0.083333 -bc_inflow 2 -bc_outflow 4 -ts_view -monitor Error -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -snes_rtol 1.0e-7 -pc_type lu -snes_converged_reason -dm_refine 2 -source_loc 0.458333,0.458333 test: suffix: adv_delta_yper_im_3 requires: !complex TODO: broken args: -dm_plex_box_bd none,periodic -use_fv -use_implicit -velocity_petscspace_degree 1 -velocity_dist constant -porosity_dist delta -inflow_state 0.0 -ts_type mimex -ts_mimex_version 0 -ts_max_time 5.0 -ts_max_steps 20 -ts_dt 0.333333 -bc_inflow 2 -bc_outflow 4 -ts_view -monitor Error -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -snes_rtol 1.0e-7 -pc_type lu -snes_converged_reason # I believe the nullspace is sin(pi y) test: suffix: adv_delta_yper_im_4 requires: !complex TODO: broken args: -dm_plex_box_bd none,periodic -use_fv -use_implicit -velocity_petscspace_degree 1 -velocity_dist constant -porosity_dist delta -inflow_state 0.0 -ts_type mimex -ts_mimex_version 0 -ts_max_time 5.0 -ts_max_steps 40 -ts_dt 0.166666 -bc_inflow 2 -bc_outflow 4 -ts_view -monitor Error -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -snes_rtol 1.0e-7 -pc_type lu -snes_converged_reason -dm_refine 1 -source_loc 0.416666,0.416666 test: suffix: adv_delta_yper_im_5 requires: !complex TODO: broken args: -dm_plex_box_bd none,periodic -use_fv -use_implicit -velocity_petscspace_degree 1 -velocity_dist constant -porosity_dist delta -inflow_state 0.0 -ts_type mimex -ts_mimex_version 0 -ts_max_time 5.0 -ts_max_steps 80 -ts_dt 0.083333 -bc_inflow 2 -bc_outflow 4 -ts_view -monitor Error -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -snes_rtol 1.0e-7 -pc_type lu -snes_converged_reason -dm_refine 2 -source_loc 0.458333,0.458333 test: suffix: adv_delta_yper_im_6 requires: !complex TODO: broken args: -dm_plex_box_bd none,periodic -use_fv -use_implicit -velocity_petscspace_degree 2 -velocity_dist constant -porosity_dist delta -inflow_state 0.0 -ts_type mimex -ts_max_time 5.0 -ts_max_steps 20 -ts_dt 0.333333 -bc_inflow 2 -bc_outflow 4 -ts_view -monitor Error -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -snes_rtol 1.0e-7 -pc_type svd -snes_converged_reason # 2D Advection, magma benchmark 1 test: suffix: adv_delta_shear_im_0 requires: !complex TODO: broken args: -dm_plex_box_bd periodic,none -dm_refine 2 -use_fv -use_implicit -velocity_petscspace_degree 1 -velocity_dist shear -porosity_dist delta -inflow_state 0.0 -ts_type mimex -ts_max_time 5.0 -ts_max_steps 20 -ts_dt 0.333333 -bc_inflow 1,3 -ts_view -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -snes_rtol 1.0e-7 -pc_type lu -snes_converged_reason -source_loc 0.458333,0.708333 # 2D Advection, box, gaussian test: suffix: adv_gauss requires: !complex TODO: broken args: -use_fv -velocity_dist constant -porosity_dist gaussian -inflow_state 0.0 -ts_type ssp -ts_max_time 2.0 -ts_max_steps 100 -ts_dt 0.01 -bc_inflow 1 -bc_outflow 3 -ts_view -dm_view test: suffix: adv_gauss_im requires: !complex TODO: broken args: -use_fv -use_implicit -velocity_dist constant -porosity_dist gaussian -inflow_state 0.0 -ts_type beuler -ts_max_time 2.0 -ts_max_steps 100 -ts_dt 0.01 -bc_inflow 1 -bc_outflow 3 -ts_view -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -snes_rtol 1.0e-7 test: suffix: adv_gauss_im_1 requires: !complex TODO: broken args: -use_fv -use_implicit -velocity_petscspace_degree 1 -velocity_dist constant -porosity_dist gaussian -inflow_state 0.0 -ts_type beuler -ts_max_time 2.0 -ts_max_steps 100 -ts_dt 0.01 -bc_inflow 1 -bc_outflow 3 -ts_view -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -snes_rtol 1.0e-7 test: suffix: adv_gauss_im_2 requires: !complex TODO: broken args: -use_fv -use_implicit -velocity_petscspace_degree 2 -velocity_dist constant -porosity_dist gaussian -inflow_state 0.0 -ts_type beuler -ts_max_time 2.0 -ts_max_steps 100 -ts_dt 0.01 -bc_inflow 1 -bc_outflow 3 -ts_view -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -snes_rtol 1.0e-7 test: suffix: adv_gauss_corner requires: !complex TODO: broken args: -use_fv -velocity_dist constant -porosity_dist gaussian -inflow_state 0.0 -ts_type ssp -ts_max_time 2.0 -ts_max_steps 100 -ts_dt 0.01 -bc_inflow 1 -bc_outflow 2 -ts_view -dm_view # 2D Advection+Harmonic 12- test: suffix: adv_harm_0 requires: !complex TODO: broken memory corruption args: -velocity_petscspace_degree 2 -use_fv -velocity_dist harmonic -porosity_dist gaussian -ts_type beuler -ts_max_time 2.0 -ts_max_steps 1000 -ts_dt 0.993392 -bc_inflow 1,2,4 -bc_outflow 3 -use_implicit -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -ksp_max_it 100 -ts_view -dm_view -snes_converged_reason -ksp_converged_reason -snes_monitor -dmts_check # Must check that FV BCs propagate to coarse meshes # Must check that FV BC ids propagate to coarse meshes # Must check that FE+FV BCs work at the same time # 2D Advection, matching wind in ex11 8-11 # NOTE implicit solves are limited by accuracy of FD Jacobian test: suffix: adv_0 requires: !complex !single exodusii args: -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside-quad.exo -use_fv -velocity_dist zero -porosity_dist tilted -ts_type ssp -ts_max_time 2.0 -ts_max_steps 1000 -ts_dt 0.993392 -ts_view -dm_view test: suffix: adv_0_im requires: !complex exodusii TODO: broken memory corruption args: -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside-quad.exo -use_fv -use_implicit -velocity_dist zero -porosity_dist tilted -ts_type beuler -ts_max_time 2.0 -ts_max_steps 1000 -ts_dt 0.993392 -ts_view -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -pc_type lu test: suffix: adv_0_im_2 requires: !complex exodusii TODO: broken args: -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside-quad.exo -use_fv -use_implicit -velocity_dist constant -porosity_dist tilted -ts_type beuler -ts_max_time 2.0 -ts_max_steps 1000 -ts_dt 0.993392 -ts_view -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -pc_type lu -snes_rtol 1.0e-7 test: suffix: adv_0_im_3 requires: !complex exodusii TODO: broken args: -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside-quad.exo -use_fv -use_implicit -velocity_petscspace_degree 1 -velocity_dist constant -porosity_dist tilted -ts_type beuler -ts_max_time 2.0 -ts_max_steps 1000 -ts_dt 0.993392 -ts_view -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -pc_type svd -snes_rtol 1.0e-7 test: suffix: adv_0_im_4 requires: !complex exodusii TODO: broken args: -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside-quad.exo -use_fv -use_implicit -velocity_petscspace_degree 2 -velocity_dist constant -porosity_dist tilted -ts_type beuler -ts_max_time 2.0 -ts_max_steps 1000 -ts_dt 0.993392 -ts_view -dm_view -snes_fd_color -snes_fd_color_use_mat -mat_coloring_type greedy -pc_type svd -snes_rtol 1.0e-7 # 2D Advection, misc TEST*/
46119d74ba2e605fad6c197a36ade21dcd3a16f5
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/bluetrum/libraries/hal_drivers/drv_usart.c
ea190324ca0ff6fbc0896e3364edbea1c050a007
[ "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
8,383
c
drv_usart.c
/* * Copyright (c) 2020-2021, Bluetrum Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2020-11-20 greedyhao first version */ #include "board.h" #include "drv_usart.h" #include "api_huart.h" #ifdef RT_USING_SERIAL //#define DRV_DEBUG #define LOG_TAG "drv.usart" #include <drv_log.h> #undef RT_SERIAL_USING_DMA enum { #ifdef BSP_USING_UART0 UART0_INDEX, #endif #ifdef BSP_USING_UART1 UART1_INDEX, #endif #ifdef BSP_USING_UART2 UART2_INDEX, #endif }; static struct ab32_uart_config uart_config[] = { #ifdef BSP_USING_UART0 { .name = "uart0", .instance = UART0_BASE, .mode = UART_MODE_TX_RX | UART_MODE_1LINE, .fifo_size = BSP_UART0_FIFO_SIZE, }, #endif #ifdef BSP_USING_UART1 { .name = "uart1", .instance = UART1_BASE, .mode = UART_MODE_TX_RX, .fifo_size = BSP_UART1_FIFO_SIZE, }, #endif #ifdef BSP_USING_UART2 { .name = "uart2", .instance = UART2_BASE, .mode = UART_MODE_TX_RX, .fifo_size = BSP_UART2_FIFO_SIZE, } #endif }; static struct ab32_uart uart_obj[sizeof(uart_config) / sizeof(uart_config[0])] = {0}; #ifdef HUART_ENABLE static rt_uint8_t huart_dma[512]; #endif static rt_err_t ab32_configure(struct rt_serial_device *serial, struct serial_configure *cfg) { struct ab32_uart *uart; RT_ASSERT(serial != RT_NULL); RT_ASSERT(cfg != RT_NULL); uart = rt_container_of(serial, struct ab32_uart, serial); uart->handle.instance = uart->config->instance; uart->handle.init.baud = cfg->baud_rate; uart->handle.init.mode = uart->config->mode; switch (cfg->data_bits) { case DATA_BITS_8: uart->handle.init.word_len = UART_WORDLENGTH_8B; break; case DATA_BITS_9: uart->handle.init.word_len = UART_WORDLENGTH_9B; break; default: uart->handle.init.word_len = UART_WORDLENGTH_8B; break; } switch (cfg->stop_bits) { case STOP_BITS_1: uart->handle.init.stop_bits = UART_STOPBITS_1; break; case STOP_BITS_2: uart->handle.init.stop_bits = UART_STOPBITS_2; break; default: uart->handle.init.stop_bits = UART_STOPBITS_1; break; } #ifdef RT_SERIAL_USING_DMA uart->dma_rx.last_index = 0; #endif if (!uart->uart_dma_flag) { hal_uart_init(&uart->handle); } #ifdef HUART_ENABLE else { huart_init_do(HUART_TR_PB3, HUART_TR_PB4, uart->handle.init.baud, huart_dma, 512); } #endif return RT_EOK; } static rt_err_t ab32_control(struct rt_serial_device *serial, int cmd, void *arg) { struct ab32_uart *uart; #ifdef RT_SERIAL_USING_DMA rt_ubase_t ctrl_arg = (rt_ubase_t)arg; #endif RT_ASSERT(serial != RT_NULL); uart = rt_container_of(serial, struct ab32_uart, serial); switch (cmd) { /* disable interrupt */ case RT_DEVICE_CTRL_CLR_INT: hal_uart_control(uart->handle.instance, UART_RXIT_ENABLE, HAL_DISABLE); break; /* enable interrupt */ case RT_DEVICE_CTRL_SET_INT: hal_uart_clrflag(uart->handle.instance, UART_FLAG_RXPND); hal_uart_control(uart->handle.instance, UART_RXIT_ENABLE, HAL_ENABLE); break; case RT_DEVICE_CTRL_CLOSE: hal_uart_deinit(uart->handle.instance); break; } return RT_EOK; } static int ab32_putc(struct rt_serial_device *serial, char ch) { struct ab32_uart *uart; RT_ASSERT(serial != RT_NULL); uart = rt_container_of(serial, struct ab32_uart, serial); if (!uart->uart_dma_flag) { hal_uart_clrflag(uart->handle.instance, UART_FLAG_TXPND); hal_uart_write(uart->handle.instance, ch); while(hal_uart_getflag(uart->handle.instance, UART_FLAG_TXPND) == 0); } #ifdef HUART_ENABLE else { huart_putchar(ch); } #endif return 1; } static int ab32_getc(struct rt_serial_device *serial) { int ch; struct ab32_uart *uart; RT_ASSERT(serial != RT_NULL); uart = rt_container_of(serial, struct ab32_uart, serial); ch = -1; switch ((rt_uint32_t)(uart->handle.instance)) { case (rt_uint32_t)UART0_BASE: if (uart->rx_idx != uart->rx_idx_prev) { ch = (int)(uart->rx_buf[uart->rx_idx_prev++ % 10]); } break; case (rt_uint32_t)UART1_BASE: #ifdef HUART_ENABLE if ((uart->uart_dma_flag) && (huart_get_rxcnt())) { ch = huart_getchar(); } else #endif { if (uart->rx_idx != uart->rx_idx_prev) { ch = (int)(uart->rx_buf[uart->rx_idx_prev++ % 10]); } } break; case (rt_uint32_t)UART2_BASE: if (uart->rx_idx != uart->rx_idx_prev) { ch = (int)(uart->rx_buf[uart->rx_idx_prev++ % 10]); } break; default: break; } return ch; } static rt_ssize_t ab32_dma_transmit(struct rt_serial_device *serial, rt_uint8_t *buf, rt_size_t size, int direction) { return -1; } void uart0_irq_process(void) { rt_hw_serial_isr(&(uart_obj[UART0_INDEX].serial), RT_SERIAL_EVENT_RX_IND); } #ifdef BSP_USING_UART1 void uart1_irq_process(void) { rt_hw_serial_isr(&(uart_obj[UART1_INDEX].serial), RT_SERIAL_EVENT_RX_IND); } #endif #ifdef BSP_USING_UART2 void uart2_irq_process(void) { rt_hw_serial_isr(&(uart_obj[UART2_INDEX].serial), RT_SERIAL_EVENT_RX_IND); } #endif rt_section(".irq.usart") static void uart_isr(int vector, void *param) { rt_interrupt_enter(); #ifdef BSP_USING_UART0 if(hal_uart_getflag(UART0_BASE, UART_FLAG_RXPND)) //RX one byte finish { uart_obj[0].rx_buf[uart_obj[0].rx_idx++ % 10] = hal_uart_read(UART0_BASE); hal_uart_clrflag(UART0_BASE, UART_FLAG_RXPND); uart0_irq_post(); } #endif #ifdef BSP_USING_UART1 if(hal_uart_getflag(UART1_BASE, UART_FLAG_RXPND)) //RX one byte finish { uart_obj[1].rx_buf[uart_obj[1].rx_idx++ % 10] = hal_uart_read(UART1_BASE); hal_uart_clrflag(UART1_BASE, UART_FLAG_RXPND); uart1_irq_post(); } #endif #ifdef BSP_USING_UART2 if(hal_uart_getflag(UART2_BASE, UART_FLAG_RXPND)) //RX one byte finish { uart_obj[2].rx_buf[uart_obj[2].rx_idx++ % 10] = hal_uart_read(UART2_BASE); hal_uart_clrflag(UART2_BASE, UART_FLAG_RXPND); uart2_irq_post(); } #endif rt_interrupt_leave(); } #ifdef HUART_ENABLE rt_section(".irq.huart") void huart_timer_isr(void) { huart_if_rx_ovflow(); if (0 == huart_get_rxcnt()) { return; } uart1_irq_post(); } #else rt_section(".irq.huart") void huart_timer_isr(void) { } #endif static const struct rt_uart_ops ab32_uart_ops = { .configure = ab32_configure, .control = ab32_control, .putc = ab32_putc, .getc = ab32_getc, .dma_transmit = ab32_dma_transmit }; int rt_hw_usart_init(void) { rt_size_t obj_num = sizeof(uart_obj) / sizeof(struct ab32_uart); struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT; rt_err_t result = 0; rt_hw_interrupt_install(IRQ_UART0_2_VECTOR, uart_isr, RT_NULL, "ut_isr"); for (int i = 0; i < obj_num; i++) { /* init UART object */ uart_obj[i].config = &uart_config[i]; uart_obj[i].rx_idx = 0; uart_obj[i].rx_idx_prev = 0; uart_obj[i].serial.ops = &ab32_uart_ops; uart_obj[i].serial.config = config; uart_obj[i].serial.config.baud_rate = 1500000; uart_obj[i].rx_buf = rt_malloc(uart_config[i].fifo_size); if (uart_obj[i].rx_buf == RT_NULL) { LOG_E("uart%d malloc failed!", i); continue; } /* register UART device */ result = rt_hw_serial_register(&uart_obj[i].serial, uart_obj[i].config->name, RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX | RT_DEVICE_FLAG_INT_TX | uart_obj[i].uart_dma_flag , RT_NULL); RT_ASSERT(result == RT_EOK); } return result; } #endif
bd1abb1525ae557e350aa14dc9919e48b791706e
dcc65ef9fbeea547abc5f6809e2c22dbdc3eb0e9
/pyeda/boolalg/picosatmodule.c
a9fb297520f369ac9589dc18fd2c1c2764fdab2c
[ "BSD-2-Clause" ]
permissive
cjdrake/pyeda
60cbb1966edf6388111eb626999f35d0dec68fd1
56fc29d71a6645e18dd37f5f03c8206a4c83ab29
refs/heads/main
2023-08-31T11:34:58.882973
2023-08-30T00:32:34
2023-08-30T00:32:34
4,689,577
257
49
BSD-2-Clause
2023-08-30T00:32:40
2012-06-17T04:18:44
Python
UTF-8
C
false
false
17,727
c
picosatmodule.c
/* ** Filename: picosatmodule.c ** ** Interface to PicoSAT SAT solver C extension ** ** Constants: ** VERSION ** COPYRIGHT ** ** Exceptions: ** Error ** ** Interface Functions: ** satisfy_one ** satisfy_all */ #include <Python.h> #include <math.h> /* abs */ #include <stdbool.h> /* bool, false, true */ #include "picosat.h" /* ** Python exception definition: picosat.Error */ PyDoc_STRVAR(Error_doc, "PicoSAT Error"); static PyObject *Error; /* Pass these functions to picosat_minit to use Python's memory manager. */ inline static void * _pymalloc(void *pmgr, size_t nbytes) { return PyMem_Malloc(nbytes); } inline static void * _pyrealloc(void *pmgr, void *p, size_t old, size_t new) { return PyMem_Realloc(p, new); } inline static void _pyfree(void *pmgr, void *p, size_t nbytes) { PyMem_Free(p); } static bool _add_clause(PicoSAT *picosat, PyObject *clause) { int nvars = picosat_variables(picosat); PyObject *iter; PyObject *pylit; long lit; iter = PyObject_GetIter(clause); if (iter == NULL) return false; while ((pylit = PyIter_Next(iter)) != 0) { if (!PyLong_Check(pylit)) { PyErr_SetString(PyExc_TypeError, "expected clause literal to be an int"); Py_DECREF(pylit); Py_DECREF(iter); return false; } lit = PyLong_AsLong(pylit); if (lit == 0 || abs(lit) > nvars) { PyErr_Format( PyExc_ValueError, "expected clause literal in range [-%d, 0), (0, %d], got: %ld", nvars, nvars, lit ); Py_DECREF(pylit); Py_DECREF(iter); return false; } /* Add clause literal */ picosat_add(picosat, lit); Py_DECREF(pylit); } /* for pylit in iter */ Py_DECREF(iter); if (PyErr_Occurred()) return false; /* Terminate clause */ picosat_add(picosat, 0); return true; } /* ** Add all clause literals to a PicoSAT instance. ** ** Returns ** ------- ** false : Exception ** true : Success */ static bool _add_clauses(PicoSAT *picosat, PyObject *clauses) { PyObject *iter; PyObject *clause; iter = PyObject_GetIter(clauses); if (iter == NULL) return false; while ((clause = PyIter_Next(iter)) != 0) { if (!_add_clause(picosat, clause)) { Py_DECREF(clause); Py_DECREF(iter); return false; } Py_DECREF(clause); } Py_DECREF(iter); if (PyErr_Occurred()) return false; return true; } /* ** Add all assumptions to a PicoSAT instance. ** ** Returns: ** false : Exception ** true : Success */ static bool _add_assumptions(PicoSAT *picosat, PyObject *assumptions) { PyObject *iter; PyObject *pylit; int lit; iter = PyObject_GetIter(assumptions); if (iter == NULL) return false; while ((pylit = PyIter_Next(iter)) != 0) { if (!PyLong_Check(pylit)) { PyErr_SetString(PyExc_TypeError, "expected assumption literal to be an int"); Py_DECREF(pylit); Py_DECREF(iter); return false; } lit = PyLong_AsLong(pylit); if (lit == 0) { PyErr_SetString(PyExc_ValueError, "expected nonzero assumption literal"); Py_DECREF(pylit); Py_DECREF(iter); return false; } /* Add assumption literal */ picosat_assume(picosat, lit); Py_DECREF(pylit); } /* for pylit in iter */ Py_DECREF(iter); if (PyErr_Occurred()) return false; return true; } /* ** Retrieve a solution from PicoSAT, and convert it to a Python tuple. ** Return NULL if an error happens. ** ** The tuple items map to Boolean values as follows: ** -1 : 0 ** 0 : unknown ** 1 : 1 */ static PyObject * _get_soln(PicoSAT *picosat) { int i; int nvars; PyObject *pytuple, *pylong; nvars = picosat_variables(picosat); pytuple = PyTuple_New(nvars); if (pytuple == NULL) goto error; for (i = 1; i <= nvars; i++) { pylong = PyLong_FromLong((long) picosat_deref(picosat, i)); if (pylong == NULL) goto decref_pytuple; if (PyTuple_SetItem(pytuple, i - 1, pylong) < 0) goto decref_pylong; } /* Success! */ return pytuple; decref_pylong: Py_DECREF(pylong); decref_pytuple: Py_DECREF(pytuple); error: return NULL; } /* ** Add the inverse of the current solution to the clauses. ** Prevents repetition when finding all solutions. ** ** NOTE: Copied from PicoSAT "app.c". */ static int _block_soln(PicoSAT *picosat, signed char *soln) { int i; int nvars; nvars = picosat_variables(picosat); for (i = 1; i <= nvars; i++) soln[i] = (picosat_deref(picosat, i) > 0) ? 1 : -1; for (i = 1; i <= nvars; i++) picosat_add(picosat, (soln[i] < 0) ? i : -i); picosat_add(picosat, 0); return 1; } /* ** Python function definition: picosat.satisfy_one() */ PyDoc_STRVAR(_satisfy_one_docstring, "\n\ If the input CNF is satisfiable, return a satisfying input point.\n\ A contradiction will return None.\n\ \n\ Parameters\n\ ----------\n\ nvars : posint\n\ Number of variables in the CNF\n\ \n\ clauses : iter of iter of (nonzero) int\n\ The CNF clauses\n\ \n\ assumptions : iter of (nonzero) int\n\ Add assumptions (unit clauses) to the CNF\n\ \n\ verbosity : int, optional\n\ Set verbosity level. A verbosity level of 1 and above prints more and\n\ more detailed progress reports to stdout.\n\ \n\ default_phase : {0, 1, 2, 3}\n\ Set default initial phase:\n\ 0 = false\n\ 1 = true\n\ 2 = Jeroslow-Wang (default)\n\ 3 = random\n\ \n\ progagation_limit : int\n\ Set a limit on the number of propagations. A negative value sets no\n\ propagation limit.\n\ \n\ decision_limit : int\n\ Set a limit on the number of decisions. A negative value sets no\n\ decision limit.\n\ \n\ seed : int\n\ Set a seed for PicoSAT's random number generator.\n\ Defaults to 1.\n\ \n\ Returns\n\ -------\n\ tuple of {-1, 0, 1}\n\ -1 : zero\n\ 0 : dont-care\n\ 1 : one\n\ " ); static PyObject * _satisfy_one(PyObject *self, PyObject *args, PyObject *kwargs) { static char *keywords[] = { "nvars", "clauses", "assumptions", "verbosity", "default_phase", "propagation_limit", "decision_limit", "seed", NULL }; /* PicoSAT instance */ PicoSAT *picosat; /* PicoSAT input parameters */ int nvars = 0; PyObject *clauses; PyObject *assumptions = NULL; int verbosity = 0; int default_phase = 2; /* Jeroslow-Wang */ int propagation_limit = -1; int decision_limit = -1; unsigned seed = 1; /* PicoSAT return value */ int result; /* Python return value */ PyObject *pyret = NULL; if (!PyArg_ParseTupleAndKeywords( args, kwargs, "iO|OiiiiI:satisfy_one", keywords, &nvars, &clauses, &assumptions, &verbosity, &default_phase, &propagation_limit, &decision_limit, &seed)) goto done; if (nvars < 0) { PyErr_Format(PyExc_ValueError, "expected nvars >= 0, got: %d", nvars); goto done; } if (default_phase < 0 || default_phase > 3) { PyErr_Format(PyExc_ValueError, "expected default_phase in {0, 1, 2, 3}, got: %d", default_phase); goto done; } picosat = picosat_minit(NULL, _pymalloc, _pyrealloc, _pyfree); if (picosat == NULL) { PyErr_SetString(Error, "could not initialize PicoSAT"); goto done; } picosat_set_verbosity(picosat, verbosity); picosat_set_global_default_phase(picosat, default_phase); picosat_set_propagation_limit(picosat, propagation_limit); picosat_set_seed(picosat, seed); picosat_adjust(picosat, nvars); if (!_add_clauses(picosat, clauses)) goto reset_picosat; if (assumptions != NULL && assumptions != Py_None) { if (!_add_assumptions(picosat, assumptions)) goto reset_picosat; } /* Do the damn thing */ Py_BEGIN_ALLOW_THREADS result = picosat_sat(picosat, decision_limit); Py_END_ALLOW_THREADS /* Prepare Python return value */ if (result == PICOSAT_UNSATISFIABLE) { picosat_reset(picosat); Py_RETURN_NONE; } else if (result == PICOSAT_SATISFIABLE) { /* Might be NULL */ pyret = _get_soln(picosat); } else if (result == PICOSAT_UNKNOWN) { PyErr_SetString(Error, "PicoSAT returned UNKNOWN"); } else { PyErr_Format(Error, "PicoSAT returned: %d", result); } reset_picosat: picosat_reset(picosat); done: return pyret; } /* ** Python iterator definition: picosat.satisfy_all() */ PyDoc_STRVAR(_satisfy_all_docstring, "\n\ Iterate through all satisfying input points.\n\ \n\ Parameters\n\ ----------\n\ nvars : posint\n\ Number of variables in the CNF\n\ \n\ clauses : iter of iter of (nonzero) int\n\ The CNF clauses\n\ \n\ verbosity : int, optional\n\ Set verbosity level. A verbosity level of 1 and above prints more and\n\ more detailed progress reports to stdout.\n\ \n\ default_phase : {0, 1, 2, 3}\n\ Set default initial phase:\n\ 0 = false\n\ 1 = true\n\ 2 = Jeroslow-Wang (default)\n\ 3 = random\n\ \n\ progagation_limit : int\n\ Set a limit on the number of propagations. A negative value sets no\n\ propagation limit.\n\ \n\ seed : int\n\ Set a seed for PicoSAT's random number generator.\n\ Defaults to 1.\n\ \n\ decision_limit : int\n\ Set a limit on the number of decisions. A negative value sets no\n\ decision limit.\n\ \n\ Returns\n\ -------\n\ iter of tuple of {-1, 0, 1}\n\ -1 : zero\n\ 0 : dont-care\n\ 1 : one\n\ " ); /* satisfy_all state */ typedef struct { PyObject_HEAD PicoSAT *picosat; int decision_limit; signed char *soln; } _satisfy_all_state; /* satisfy_all.tp_new */ static PyObject * _satisfy_all_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs) { static char *keywords[] = { "nvars", "clauses", "verbosity", "default_phase", "propagation_limit", "decision_limit", "seed", NULL }; /* PicoSAT instance */ PicoSAT *picosat; /* PicoSAT input parameters */ int nvars = 0; PyObject *clauses; int verbosity = 0; int default_phase = 2; /* Jeroslow-Wang */ int propagation_limit = -1; int decision_limit = -1; unsigned seed = 1; /* Python return value */ _satisfy_all_state *state; if (!PyArg_ParseTupleAndKeywords( args, kwargs, "iO|iiiiI:satisfy_all", keywords, &nvars, &clauses, &verbosity, &default_phase, &propagation_limit, &decision_limit, &seed)) goto error; if (nvars < 0) { PyErr_Format(PyExc_ValueError, "expected nvars >= 0, got: %d", nvars); goto error; } if (default_phase < 0 || default_phase > 3) { PyErr_Format(PyExc_ValueError, "expected default_phase in {0, 1, 2, 3}, got: %d", default_phase); goto error; } picosat = picosat_minit(NULL, _pymalloc, _pyrealloc, _pyfree); if (picosat == NULL) { PyErr_SetString(Error, "could not initialize PicoSAT"); goto error; } picosat_set_verbosity(picosat, verbosity); picosat_set_global_default_phase(picosat, default_phase); picosat_set_propagation_limit(picosat, propagation_limit); picosat_set_seed(picosat, seed); picosat_adjust(picosat, nvars); if (!_add_clauses(picosat, clauses)) goto reset_picosat; /* Initialize iterator state */ state = (_satisfy_all_state *) cls->tp_alloc(cls, 0); if (state == NULL) goto reset_picosat; state->picosat = picosat; state->decision_limit = decision_limit; state->soln = PyMem_Malloc(nvars + 1); if (state->soln == NULL) { PyErr_NoMemory(); goto reset_picosat; } /* Success! */ return (PyObject *) state; reset_picosat: picosat_reset(picosat); error: return NULL; } /* satisfy_all.tp_dealloc */ static void _satisfy_all_dealloc(_satisfy_all_state *state) { PyMem_Free(state->soln); picosat_reset(state->picosat); Py_TYPE(state)->tp_free(state); } /* satisfy_all.tp_iternext */ static PyObject * _satisfy_all_next(_satisfy_all_state *state) { PyObject *pysoln; /* PicoSAT return value */ int result; /* Python return value */ PyObject *pyret = NULL; /* Do the damn thing */ Py_BEGIN_ALLOW_THREADS result = picosat_sat(state->picosat, state->decision_limit); Py_END_ALLOW_THREADS /* Prepare Python return value */ if (result == PICOSAT_UNSATISFIABLE) { /* No solution */ } else if (result == PICOSAT_SATISFIABLE) { /* Might be NULL */ pysoln = _get_soln(state->picosat); if (pysoln != NULL) { _block_soln(state->picosat, state->soln); pyret = pysoln; } } else if (result == PICOSAT_UNKNOWN) { /* No more solutions */ } else { PyErr_Format(Error, "PicoSAT returned: %d", result); } return pyret; } /* SatisfyAll.__class__ */ static PyTypeObject SatisfyAll_T = { PyVarObject_HEAD_INIT(NULL, 0) "satisfy_all", /* tp_name */ sizeof(_satisfy_all_state), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor) _satisfy_all_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ _satisfy_all_docstring, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc) _satisfy_all_next, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ (newfunc) _satisfy_all_new, /* tp_new */ }; /* ** picosat module definition */ PyDoc_STRVAR(m_doc, "\n\ Interface to PicoSAT SAT solver C extension\n\ \n\ Constants:\n\ VERSION\n\ COPYRIGHT\n\ \n\ Exceptions:\n\ Error\n\ \n\ Interface Functions:\n\ satisfy_one\n\ satisfy_all\n\ " ); static PyMethodDef m_methods[] = { {"satisfy_one", (PyCFunction) _satisfy_one, METH_VARARGS | METH_KEYWORDS, _satisfy_one_docstring}, /* sentinel */ {NULL, NULL, 0, NULL} }; static PyModuleDef _module = { PyModuleDef_HEAD_INIT, "picosat", /* m_name */ m_doc, /* m_doc */ -1, /* m_size */ m_methods, /* m_methods */ }; PyMODINIT_FUNC PyInit_picosat(void) { PyObject *m; /* Create module */ m = PyModule_Create(&_module); if (m == NULL) goto error; /* Create picosat.VERSION */ if (PyModule_AddStringConstant(m, "VERSION", "960") < 0) goto error; /* Create picosat.COPYRIGHT */ if (PyModule_AddStringConstant(m, "COPYRIGHT", picosat_copyright()) < 0) goto error; /* Create picosat.Error */ Error = PyErr_NewExceptionWithDoc("picosat.Error", Error_doc, NULL, NULL); if (Error == NULL) goto error; Py_INCREF(Error); if (PyModule_AddObject(m, "Error", Error) < 0) goto decref_Error; /* Create picosat.satisfy_all */ if (PyType_Ready(&SatisfyAll_T) < 0) goto decref_Error; Py_INCREF((PyObject *) &SatisfyAll_T); if (PyModule_AddObject(m, "satisfy_all", (PyObject *) &SatisfyAll_T) < 0) goto decref_satisfy_all; /* Success! */ return m; /* Error! */ decref_satisfy_all: Py_DECREF((PyObject *) &SatisfyAll_T); decref_Error: Py_DECREF(Error); error: return NULL; }
58432beff5b7e3be2491bcac492b06d3b08e3efb
8886361e436c7598419f444a52ae587bf94b1fbe
/tests/test_lazychunk_memcpyed.c
d409bb532b801b2a3dba8ba1daad540a5564e308
[ "BSD-3-Clause" ]
permissive
Blosc/c-blosc2
d4b69bf735e1440ea1d7e147f434b488f975c8d4
6bbade9e13bd166ea0189f8c3b6253c9bbe9bb54
refs/heads/main
2023-08-31T15:47:35.224132
2023-08-31T03:01:37
2023-08-31T06:01:40
40,355,993
358
85
NOASSERTION
2023-09-12T09:26:36
2015-08-07T10:51:35
C
UTF-8
C
false
false
4,031
c
test_lazychunk_memcpyed.c
/* Copyright (c) 2021 The Blosc Development Team <blosc@blosc.org> https://blosc.org License: BSD 3-Clause (see LICENSE.txt) See LICENSE.txt for details about copyright and rights to use. */ #include <stdio.h> #include "test_common.h" int tests_run = 0; static char* test_lazy_chunk_memcpyed(void) { int cbytes, nbytes; blosc2_cparams cparams = BLOSC2_CPARAMS_DEFAULTS; cparams.typesize = 1; blosc2_storage storage = {.urlpath="update.b2frame", .contiguous=false, .cparams=&cparams}; blosc2_remove_dir(storage.urlpath); blosc2_schunk *sc = blosc2_schunk_new(&storage); uint8_t buffer_b[] = {1}; int32_t chunk_size = sc->typesize + BLOSC2_MAX_OVERHEAD; uint8_t *chunk = malloc(chunk_size); cbytes = blosc2_compress_ctx(sc->cctx, buffer_b, sc->typesize, chunk, chunk_size); mu_assert("ERROR: cbytes are incorrect", cbytes == 33); nbytes = blosc2_decompress_ctx(sc->dctx, chunk, chunk_size, buffer_b, sc->typesize); mu_assert("ERROR: nbytes are incorrect", nbytes == 1); blosc2_schunk_append_chunk(sc, chunk, false); uint8_t *chunk2; bool needs_free; int32_t chunk2_size = blosc2_schunk_get_chunk(sc, 0, &chunk2, &needs_free); nbytes = blosc2_decompress_ctx(sc->dctx, chunk2, chunk2_size, buffer_b, sc->typesize); mu_assert("ERROR: nbytes are incorrect", nbytes == 1); if (needs_free) { free(chunk2); } nbytes = blosc2_schunk_decompress_chunk(sc, 0, buffer_b, sc->typesize); mu_assert("ERROR: nbytes are incorrect", nbytes == 1); blosc2_remove_dir(storage.urlpath); return 0; } static char* test_lazy_chunk_memcpyed_nofilter(void) { int chunk_nitems = 2000; int blocksize = 2000 - sizeof(int32_t) * 4; // make it not a multiple of chunk_nitems int cbytes, nbytes; blosc2_cparams cparams = BLOSC2_CPARAMS_DEFAULTS; cparams.filters[BLOSC_LAST_FILTER] = BLOSC_NOFILTER; cparams.blocksize = blocksize; cparams.typesize = sizeof(int32_t); blosc2_storage storage = {.urlpath="memcpyed_nofilter.b2frame", .contiguous=false, .cparams=&cparams}; blosc2_remove_dir(storage.urlpath); blosc2_schunk *sc = blosc2_schunk_new(&storage); int32_t chunk_size = chunk_nitems * sc->typesize; int32_t *buffer_b = malloc(chunk_size); for (int i = 0; i < chunk_nitems; i++) { buffer_b[i] = i; } int dest_size = chunk_size + BLOSC2_MAX_OVERHEAD; uint8_t *chunk = malloc(dest_size); cbytes = blosc2_compress_ctx(sc->cctx, buffer_b, chunk_size, chunk, dest_size); mu_assert("ERROR: cbytes are incorrect", cbytes == dest_size); // incompressible data nbytes = blosc2_decompress_ctx(sc->dctx, chunk, dest_size, buffer_b, chunk_size); mu_assert("ERROR: nbytes are incorrect", nbytes == chunk_size); blosc2_schunk_append_chunk(sc, chunk, false); uint8_t *chunk2; bool needs_free; int32_t chunk2_size = blosc2_schunk_get_chunk(sc, 0, &chunk2, &needs_free); nbytes = blosc2_decompress_ctx(sc->dctx, chunk2, chunk2_size, buffer_b, chunk_size); mu_assert("ERROR: nbytes are incorrect", nbytes == chunk_size); if (needs_free) { free(chunk2); } nbytes = blosc2_schunk_decompress_chunk(sc, 0, buffer_b, chunk_size); mu_assert("ERROR: nbytes are incorrect", nbytes == chunk_size); // Retrieve the last item using the lazy_chunk mechanism int32_t last_item; blosc2_schunk_get_slice_buffer(sc, chunk_nitems - 1, chunk_nitems, &last_item); mu_assert("ERROR: last value is incorrect", last_item == chunk_nitems - 1); blosc2_remove_dir(storage.urlpath); return 0; } static char *all_tests(void) { mu_run_test(test_lazy_chunk_memcpyed); mu_run_test(test_lazy_chunk_memcpyed_nofilter); return EXIT_SUCCESS; } int main(void) { char *result; install_blosc_callback_test(); /* optionally install callback test */ blosc2_init(); /* Run all the suite */ result = all_tests(); if (result != EXIT_SUCCESS) { printf(" (%s)\n", result); } else { printf(" ALL TESTS PASSED"); } printf("\tTests run: %d\n", tests_run); blosc2_destroy(); return result != EXIT_SUCCESS; }
e3c7443219c355b677320498099add9477ae1777
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
/lang/php56/patches/patch-ext_standard_basic__functions.c
6bc67dd864cee047f3d68a7735dbc9a292a541d7
[]
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
553
c
patch-ext_standard_basic__functions.c
$NetBSD: patch-ext_standard_basic__functions.c,v 1.1 2014/11/24 15:37:08 taca Exp $ Work around VAX FP lack of INF --- ext/standard/basic_functions.c.orig 2014-11-12 13:52:21.000000000 +0000 +++ ext/standard/basic_functions.c @@ -3489,7 +3489,7 @@ PHPAPI double php_get_nan(void) /* {{{ * PHPAPI double php_get_inf(void) /* {{{ */ { -#if HAVE_HUGE_VAL_INF +#if defined(HAVE_HUGE_VAL_INF) || defined(__vax__) return HUGE_VAL; #elif defined(__i386__) || defined(_X86_) || defined(ALPHA) || defined(_ALPHA) || defined(__alpha) double val = 0.0;
cd71d195356623030f731e94f6d6e4e24c4f7a96
f3eed0234b4d0ad2bbb2abd700cf1e2c7a0e8a1d
/AKWF-c/AKWF_eorgan/AKWF_eorgan_0055.h
989c991e2176e26e5384e7fb7d1646b01d88d203
[ "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,686
h
AKWF_eorgan_0055.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_eorgan_0055 256 samples +-----------------------------------------------------------------------------------------------------------------+ | ** *** *** *** | | ** *** ** *** | | ** ** ** ** | | ** ** ** ** | | ** ** *** ** | |** ** ** ** | |* *** *** ** | | ****** * ****** | | ** *** **** *| | ** *** ** **| | ** *** *** ** | | ** ** ** ** | | ** ** ** ** | | *** *** ** ** | | ** *** *** *** | +-----------------------------------------------------------------------------------------------------------------+ */ const uint16_t AKWF_eorgan_0055 [] = { 33270, 35304, 37367, 39420, 41441, 43425, 45371, 47255, 49092, 50845, 52541, 54139, 55667, 57083, 58418, 59636, 60758, 61755, 62651, 63417, 64076, 64605, 65020, 65307, 65481, 65529, 65463, 65278, 64984, 64580, 64070, 63463, 62756, 61964, 61085, 60133, 59107, 58021, 56878, 55688, 54455, 53192, 51906, 50605, 49294, 47985, 46685, 45405, 44147, 42922, 41739, 40602, 39523, 38503, 37551, 36673, 35873, 35156, 34527, 33990, 33546, 33201, 32956, 32810, 32768, 32826, 32987, 33247, 33607, 34064, 34615, 35257, 35986, 36796, 37684, 38645, 39671, 40758, 41896, 43085, 44307, 45565, 46841, 48143, 49437, 50773, 52116, 53381, 54635, 55846, 57021, 58143, 59209, 60207, 61136, 61985, 62748, 63423, 63998, 64475, 64844, 65105, 65251, 65282, 65193, 64986, 64660, 64210, 63640, 62949, 62142, 61217, 60178, 59030, 57775, 56417, 54963, 53418, 51786, 50076, 48293, 46443, 44538, 42584, 40585, 38554, 36498, 34427, 32349, 30271, 28202, 26153, 24130, 22143, 20201, 18310, 16479, 14716, 13025, 11418, 9897, 8468, 7140, 5913, 4796, 3789, 2897, 2120, 1465, 930, 515, 222, 49, 0, 62, 243, 535, 936, 1444, 2049, 2754, 3544, 4420, 5371, 6396, 7481, 8624, 9812, 11045, 12305, 13600, 14965, 16279, 17586, 18888, 20166, 21424, 22646, 23829, 24962, 26043, 27058, 28010, 28885, 29685, 30399, 31026, 31559, 32001, 32343, 32585, 32729, 32768, 32707, 32544, 32279, 31918, 31458, 30905, 30261, 29530, 28718, 27826, 26864, 25836, 24748, 23607, 22420, 21193, 19936, 18656, 17360, 16055, 14756, 13464, 12188, 10938, 9723, 8550, 7425, 6362, 5359, 4431, 3577, 2813, 2136, 1559, 1080, 709, 445, 299, 262, 351, 552, 879, 1324, 1893, 2580, 3386, 4308, 5342, 6492, 7739, 9100, 10545, 12098, 13717, 15437, 17205, 19069, 20954, 22933, 24899, 26967, 28970, 31134, };
af4746217b9669ba9c3147c45f2c70a15b9645d3
2c442009e26dbe3f8189e5590378dfa4a32442c4
/log.c
c40a9a9a5064332f02882c8066f35083b2acd480
[]
no_license
devnoname120/vitabright
7405e7206ac1b1b480bd232faa622d652e06996e
dd2d75c8705a43b9976a3855b79d6a18d1f9ce7b
refs/heads/master
2022-05-29T08:44:00.456223
2022-03-18T14:36:19
2022-03-18T14:36:19
87,748,262
132
13
null
2022-03-16T18:50:18
2017-04-09T23:56:29
C
UTF-8
C
false
false
488
c
log.c
#include "log.h" #include <psp2kern/io/fcntl.h> extern int ksceIoMkdir(const char *, int); void log_reset() { ksceIoMkdir(LOG_PATH, 6); SceUID fd = ksceIoOpen(LOG_FILE, SCE_O_WRONLY | SCE_O_CREAT | SCE_O_TRUNC, 6); if (fd < 0) return; ksceIoClose(fd); } void log_write(const char *buffer, size_t length) { SceUID fd = ksceIoOpen(LOG_FILE, SCE_O_WRONLY | SCE_O_CREAT | SCE_O_APPEND, 6); if (fd < 0) return; ksceIoWrite(fd, buffer, length); ksceIoClose(fd); }
30282945e0507851f16f5d09ff3ddc6054dc91df
03666e5f961946fc1a0ac67781ac1425562ef0d7
/src/avt/IVP/avtStateRecorderIntegralCurve.C
fab6ca51216ad05e6f692fdc03ecf3f8630ad748
[ "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
21,563
c
avtStateRecorderIntegralCurve.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. // ************************************************************************* // // avtStateRecorderIntegralCurve.C // // ************************************************************************* // #include <avtStateRecorderIntegralCurve.h> #include <list> #include <cmath> #include <cassert> #include <iostream> #include <limits> #include <ImproperUseException.h> #include <DebugStream.h> #include <avtVector.h> #include <algorithm> #include <avtParallel.h> // **************************************************************************** // Method: avtStateRecorderIntegralCurve constructor // // Programmer: Hank Childs // Creation: June 4, 2010 // // **************************************************************************** avtStateRecorderIntegralCurve::avtStateRecorderIntegralCurve( unsigned int mask, const avtIVPSolver* model, Direction dir, const double& t_start, const avtVector &p_start, const avtVector &v_start, int ID) : avtIntegralCurve(model, dir, t_start, p_start, v_start, ID), historyMask(mask) { time = 0.0; distance = 0.0; sequenceCnt = 0; _serializeFlags = SERIALIZE_NO_OPT; // The data variable will always be the after the secondary variables. if( historyMask & SAMPLE_VARIABLE ) { if( historyMask & SAMPLE_SECONDARY5 ) variableIndex = 6; else if( historyMask & SAMPLE_SECONDARY4 ) variableIndex = 5; else if( historyMask & SAMPLE_SECONDARY3 ) variableIndex = 4; else if( historyMask & SAMPLE_SECONDARY2 ) variableIndex = 3; else if( historyMask & SAMPLE_SECONDARY1 ) variableIndex = 2; else if( historyMask & SAMPLE_SECONDARY0 ) variableIndex = 1; else variableIndex = 0; } else variableIndex = 0; } // **************************************************************************** // Method: avtStateRecorderIntegralCurve constructor // // Programmer: Hank Childs // Creation: June 4, 2010 // // **************************************************************************** avtStateRecorderIntegralCurve::avtStateRecorderIntegralCurve() { time = 0.0; distance = 0.0; sequenceCnt = 0; _serializeFlags = SERIALIZE_NO_OPT; historyMask = 0; } // **************************************************************************** // Method: avtStateRecorderIntegralCurve destructor // // Programmer: Hank Childs // Creation: June 4, 2010 // // **************************************************************************** avtStateRecorderIntegralCurve::~avtStateRecorderIntegralCurve() { } // **************************************************************************** // Method: avtStateRecorderIntegralCurve::RecordStep // // Purpose: // Records a sample from the current step at the specified time. // // Programmer: Christoph Garth // Creation: July 22, 2010 // // Modifications: // // Dave Pugmire, Tue Sep 28 10:39:11 EDT 2010 // If step is with tolerance of previous step, just overwrite the previous step. // // Dave Pugmire, Fri Jan 28 14:49:50 EST 2011 // Add scalar2 // // **************************************************************************** void avtStateRecorderIntegralCurve::RecordStep(const avtIVPField* field, const avtIVPStep& step, bool firstStep) { avtVector p = step.GetP(time); if( historyMask & SAMPLE_TIME ) history.push_back( time ); if( historyMask & SAMPLE_POSITION ) { history.push_back( p.x ); history.push_back( p.y ); history.push_back( p.z ); } if( historyMask & SAMPLE_VELOCITY ) { // Do not call as it can give inaccurate results. Use the // field directly. // avtVector v = step.GetV( time ); avtVector v; (*field)( time, p, v ); history.push_back( v.x ); history.push_back( v.y ); history.push_back( v.z ); } if( historyMask & SAMPLE_VORTICITY ) history.push_back( field->ComputeVorticity( time, p ) ); if( historyMask & SAMPLE_ARCLENGTH ) history.push_back( distance ); if (historyMask & SAMPLE_DOM_VISIT) { double val = 0.0; //First step gets recorded with two samples. Seed point, and first step. //Set the number of visits to 1. size_t nSamp = GetNumberOfSamples(); if (nSamp == 0 || nSamp == 1) val = 1.0; else { Sample prevSamp = GetSample(nSamp-1); val = prevSamp.numDomainsVisited; //First step in a domain, increment the val. if (firstStep) val = val + 1; } history.push_back(val); } if( historyMask & SAMPLE_VARIABLE ) history.push_back( field->ComputeScalarVariable( variableIndex, time, p ) ); if( historyMask & SAMPLE_SECONDARY0 ) history.push_back( field->ComputeScalarVariable( 0, time, p ) ); if( historyMask & SAMPLE_SECONDARY1 ) history.push_back( field->ComputeScalarVariable( 1, time, p ) ); if( historyMask & SAMPLE_SECONDARY2 ) history.push_back( field->ComputeScalarVariable( 2, time, p ) ); if( historyMask & SAMPLE_SECONDARY3 ) history.push_back( field->ComputeScalarVariable( 3, time, p ) ); if( historyMask & SAMPLE_SECONDARY4 ) history.push_back( field->ComputeScalarVariable( 4, time, p ) ); if( historyMask & SAMPLE_SECONDARY5 ) history.push_back( field->ComputeScalarVariable( 5, time, p ) ); } // **************************************************************************** // Method: avtStateRecorderIntegralCurve::AnalyzeStep // // Purpose: // Analyzes the current step. // // Programmer: Hank Childs // Creation: June 4, 2010 // // Modifications: // // Hank Childs, Fri Oct 8 23:30:27 PDT 2010 // Move termination criteria into derived types. // // Hank Childs, Sun Dec 5 10:18:13 PST 2010 // Pass the avtIVPField to CheckForTermination. // // Hank Childs, Mon Mar 12 16:28:33 PDT 2012 // Make sure last step is always recorded. Previous logic would lead to a // missing step if termination occurred somewhere outside this loop. // Props to Christoph Garth for eyeballing this. // // Hank Childs, Sun Apr 1 10:35:48 PDT 2012 // Change status to use new TERMINATED designation. // // **************************************************************************** void avtStateRecorderIntegralCurve::AnalyzeStep( avtIVPStep& step, avtIVPField* field, bool firstStep) { if (history.empty()) { // Record the first position of the step. time = step.GetT0(); RecordStep( field, step, false ); } if (CheckForTermination(step, field)) status.SetTerminationMet(); // These must be called after CheckForTermination, because // CheckForTermination will modify the step if it goes beyond the // termination criteria. (Example: integral curve will split a // step if it is terminating by distance.) time = step.GetT1(); distance += step.GetLength(); RecordStep( field, step, firstStep ); } // **************************************************************************** // Method: avtStateRecorderIntegralCurve::GetSampleStride() // // Purpose: // Returns the stride between consecutive samples. // // Programmer: Christoph Garth // Creation: July 14, 2010 // // Modifications: // // Dave Pugmire, Fri Jan 28 14:49:50 EST 2011 // Add scalar2 // // **************************************************************************** size_t avtStateRecorderIntegralCurve::GetSampleStride() const { size_t stride = 0; #define TEST_AND_INCREMENT( f, n ) \ if( historyMask & f ) \ { stride += n; } TEST_AND_INCREMENT( SAMPLE_TIME, 1 ); TEST_AND_INCREMENT( SAMPLE_POSITION, 3 ); TEST_AND_INCREMENT( SAMPLE_VELOCITY, 3 ); TEST_AND_INCREMENT( SAMPLE_VORTICITY, 1 ); TEST_AND_INCREMENT( SAMPLE_ARCLENGTH, 1 ); TEST_AND_INCREMENT( SAMPLE_DOM_VISIT, 1 ); TEST_AND_INCREMENT( SAMPLE_VARIABLE, 1 ); TEST_AND_INCREMENT( SAMPLE_SECONDARY0, 1 ); TEST_AND_INCREMENT( SAMPLE_SECONDARY1, 1 ); TEST_AND_INCREMENT( SAMPLE_SECONDARY2, 1 ); TEST_AND_INCREMENT( SAMPLE_SECONDARY3, 1 ); TEST_AND_INCREMENT( SAMPLE_SECONDARY4, 1 ); TEST_AND_INCREMENT( SAMPLE_SECONDARY5, 1 ); #undef TEST_AND_INCREMENT return stride; }; size_t avtStateRecorderIntegralCurve::GetSampleIndex(const Attribute &attr) const { size_t idx = 0; #define TEST_AND_INCREMENT(f, n) \ if (historyMask & f) \ { \ if (f == attr) \ { return idx; } \ else \ { idx += n; } \ } TEST_AND_INCREMENT(SAMPLE_TIME, 1); TEST_AND_INCREMENT(SAMPLE_POSITION, 3); TEST_AND_INCREMENT(SAMPLE_VELOCITY, 3); TEST_AND_INCREMENT(SAMPLE_VORTICITY, 1); TEST_AND_INCREMENT(SAMPLE_ARCLENGTH, 1); TEST_AND_INCREMENT(SAMPLE_DOM_VISIT, 1); TEST_AND_INCREMENT(SAMPLE_VARIABLE, 1); TEST_AND_INCREMENT(SAMPLE_SECONDARY0, 1); TEST_AND_INCREMENT(SAMPLE_SECONDARY1, 1); TEST_AND_INCREMENT(SAMPLE_SECONDARY2, 1); TEST_AND_INCREMENT(SAMPLE_SECONDARY3, 1); TEST_AND_INCREMENT(SAMPLE_SECONDARY4, 1); TEST_AND_INCREMENT(SAMPLE_SECONDARY5, 1); #undef TEST_AND_INCREMENT EXCEPTION1(ImproperUseException, "Invalid attribute to avtStateRecorderIntegralCurve::GetSampleIndex"); } // **************************************************************************** // Method: avtStateRecorderIntegralCurve::GetSample() // // Purpose: // Returns a sample from the integral curve. // // Programmer: Christoph Garth // Creation: July 14, 2010 // // Modifications: // // Dave Pugmire, Fri Jan 28 14:49:50 EST 2011 // Add scalar2 // // **************************************************************************** avtStateRecorderIntegralCurve::Sample avtStateRecorderIntegralCurve::GetSample( size_t n ) const { std::vector<double>::const_iterator m = history.begin() + n*GetSampleStride(); Sample s; if( historyMask & SAMPLE_TIME ) s.time = *(m++); else s.time = 0; if( historyMask & SAMPLE_POSITION ) { s.position.x = *(m++); s.position.y = *(m++); s.position.z = *(m++); } else s.position = avtVector(0,0,0); if( historyMask & SAMPLE_VELOCITY ) { s.velocity.x = *(m++); s.velocity.y = *(m++); s.velocity.z = *(m++); } else s.velocity = avtVector(0,0,0); if( historyMask & SAMPLE_VORTICITY ) s.vorticity = *(m++); else s.vorticity = 0; if( historyMask & SAMPLE_ARCLENGTH ) s.arclength = *(m++); else s.arclength = 0; if (historyMask & SAMPLE_DOM_VISIT) s.numDomainsVisited = *(m++); else s.numDomainsVisited = 0.0; if( historyMask & SAMPLE_VARIABLE ) s.variable = *(m++); else s.variable = 0; if( historyMask & SAMPLE_SECONDARY0 ) s.secondarys[0] = *(m++); else s.secondarys[0] = 0; if( historyMask & SAMPLE_SECONDARY1 ) s.secondarys[1] = *(m++); else s.secondarys[1] = 0; if( historyMask & SAMPLE_SECONDARY2 ) s.secondarys[2] = *(m++); else s.secondarys[2] = 0; if( historyMask & SAMPLE_SECONDARY3 ) s.secondarys[3] = *(m++); else s.secondarys[3] = 0; if( historyMask & SAMPLE_SECONDARY4 ) s.secondarys[4] = *(m++); else s.secondarys[4] = 0; if( historyMask & SAMPLE_SECONDARY5 ) s.secondarys[5] = *(m++); else s.secondarys[5] = 0; return s; } // **************************************************************************** // Method: avtStateRecorderIntegralCurve::GetNumberOfSamples() // // Purpose: // Returns the number of history samples. // // Programmer: Christoph Garth // Creation: July 14, 2010 // // **************************************************************************** size_t avtStateRecorderIntegralCurve::GetNumberOfSamples() const { return history.size() / GetSampleStride(); } // **************************************************************************** // Method: avtStateRecorderIntegralCurve::Finalize // // Purpose: // Finalize a curve after being sent to another processor. // // Programmer: Hank Childs // Creation: June 4, 2010 // // **************************************************************************** void avtStateRecorderIntegralCurve::Finalize() { if (historyMask & SAMPLE_DOM_VISIT) { size_t nSamp = GetNumberOfSamples(); if (nSamp > 0) { double val = GetSample(nSamp-1).numDomainsVisited; for (size_t i = 0; i < nSamp; i++) history[i*GetSampleStride() + GetSampleIndex(SAMPLE_DOM_VISIT)] = val; } } } // **************************************************************************** // Method: avtStateRecorderIntegralCurve::Serialize // // Purpose: // Serializes a curve so it can be sent to another processor. // // Programmer: Hank Childs // Creation: June 4, 2010 // // Modifications: // // Hank Childs, Tue Jun 8 09:30:45 CDT 2010 // Add portions for sequence tracking, which were previously in the base // class. // // Dave Pugmire, Mon Sep 20 14:51:50 EDT 2010 // Serialize the distance field. // // David Camp, Wed Mar 7 10:43:07 PST 2012 // Added a Serialize flag to the arguments. This is to support the restore // ICs code. // // **************************************************************************** void avtStateRecorderIntegralCurve::Serialize(MemStream::Mode mode, MemStream &buff, avtIVPSolver *solver, SerializeFlags serializeFlags) { // Have the base class serialize its part avtIntegralCurve::Serialize(mode, buff, solver, serializeFlags); buff.io(mode, time); buff.io(mode, distance); buff.io(mode, historyMask); unsigned long saveSerializeFlags = serializeFlags | _serializeFlags; buff.io(mode, saveSerializeFlags); if (DebugStream::Level5()) { debug5<<" avtStateRecorderIntegralCurve::Serialize "<<(mode==MemStream::READ?"READ":"WRITE")<<" saveSerializeFlags= "<<saveSerializeFlags<<endl; } // R/W the steps. if (saveSerializeFlags & SERIALIZE_STEPS) buff.io(mode, history); if (saveSerializeFlags & SERIALIZE_INC_SEQ) { if (mode == MemStream::WRITE) { long seqCnt = sequenceCnt+1; buff.io(mode, seqCnt); } else buff.io(mode, sequenceCnt); } else buff.io(mode, sequenceCnt); if (DebugStream::Level5()) { debug5 << "DONE: avtStateRecorderIntegralCurve::Serialize. sz= "<<buff.len() << endl; } } // **************************************************************************** // Method: avtStateRecorderIntegralCurve::MergeIntegralCurveSequence // // Purpose: // Merge a vector of curve sequences into a single curve. // This is destructive, extra curves are deleted. // // Programmer: Dave Pugmire // Creation: September 24, 2009 // // Modifications: // // Dave Pugmire, Tue Feb 23 09:42:25 EST 2010 // Sorting can be done independant of curve direction. Changed curve // step from list to vector. // // David Camp, Fri Jul 29 06:55:39 PDT 2011 // Added code to send the ending setting, IC status, domain, ivp. // The pathlines need this information. // // **************************************************************************** avtIntegralCurve * avtStateRecorderIntegralCurve::MergeIntegralCurveSequence(std::vector<avtIntegralCurve *> &v2) { if( v2.empty() ) return NULL; size_t vSize = v2.size(); if( vSize == 1 ) return v2[0]; std::vector<avtStateRecorderIntegralCurve *> v( vSize ); for( size_t i=0 ; i<vSize; ++i ) { v[i] = dynamic_cast<avtStateRecorderIntegralCurve*>( v2[i] ); assert( v[i] != NULL ); } // sort the curves by id and sequence number, in ascending order std::sort( v.begin(), v.end(), avtStateRecorderIntegralCurve::IdSeqCompare ); // find the combined history size size_t combinedHistorySize = 0; vSize = v.size(); // This should be the same size as v2 for( size_t i=0; i < vSize; ++i ) { combinedHistorySize += v[i]->history.size(); // sanity check: make sure all ids are the same assert( v[i]->id == v[0]->id ); } //If use color by 'domains visited' we need to increment the pieces. if (historyMask & SAMPLE_DOM_VISIT) { double lastVal = 0.0; for (size_t i = 0; i < vSize; i++) lastVal += v[i]->GetSample(v[i]->GetNumberOfSamples()-1).numDomainsVisited; for (size_t i = 0; i < vSize; i++) { size_t nSamp = v[i]->GetNumberOfSamples(); for (size_t j = 0; j < nSamp; j++) v[i]->history[j*GetSampleStride() + GetSampleIndex(SAMPLE_DOM_VISIT)] = lastVal; } } // Get the values from the last curve in the sequence and store // them with the first curve. // Get the values from the child class v[0]->MergeIntegralCurve( v[vSize-1] ); // Get the values from the base class v[0]->time = v[vSize-1]->time; v[0]->distance = v[vSize-1]->distance; v[0]->status = v[vSize-1]->status; v[0]->blockList = v[vSize-1]->blockList; avtIVPSolver *tmpSolver = v[0]->ivp; v[0]->ivp = v[vSize-1]->ivp; v[vSize-1]->ivp = tmpSolver; // The curve pieces are now in sorted order. Merge the histories // from each curve in the sequence; merge by appending to the // first curve's history. Finally delete the curve. v[0]->history.reserve( combinedHistorySize ); for( size_t i=1; i < vSize; i++ ) { v[0]->history.insert( v[0]->history.end(), v[i]->history.begin(), v[i]->history.end() ); delete v[i]; } v2.clear(); return v[0]; } // **************************************************************************** // Method: avtStateRecorderIntegralCurve::LessThan // // Purpose: // Performs a LessThan operation, used when doing parallel communication // and needing to sort curves. // // Programmer: Hank Childs // Creation: December 6, 2011 // // **************************************************************************** bool avtStateRecorderIntegralCurve::LessThan(const avtIntegralCurve *ic) const { return IdSeqCompare(this, ic); } // **************************************************************************** // Method: avtStateRecorderIntegralCurve::IdSeqCompare // // Purpose: // Sort curves by id, then sequence number. // // Programmer: Dave Pugmire // Creation: September 24, 2009 // // Modifications: // // **************************************************************************** bool avtStateRecorderIntegralCurve::IdSeqCompare(const avtIntegralCurve *icA, const avtIntegralCurve *icB) { avtStateRecorderIntegralCurve *sicA = (avtStateRecorderIntegralCurve *) icA; avtStateRecorderIntegralCurve *sicB = (avtStateRecorderIntegralCurve *) icB; if (sicA->id == sicB->id) return sicA->sequenceCnt < sicB->sequenceCnt; return sicA->id < sicB->id; } // **************************************************************************** // Method: avtStateRecorderIntegralCurve::IdRevSeqCompare // // Purpose: // Sort curves by id, then reverse sequence number. // // Programmer: Dave Pugmire // Creation: September 24, 2009 // // Modifications: // // **************************************************************************** bool avtStateRecorderIntegralCurve::IdRevSeqCompare(const avtIntegralCurve *icA, const avtIntegralCurve *icB) { avtStateRecorderIntegralCurve *sicA = (avtStateRecorderIntegralCurve *) icA; avtStateRecorderIntegralCurve *sicB = (avtStateRecorderIntegralCurve *) icB; if (sicA->id == sicB->id) return sicA->sequenceCnt > sicB->sequenceCnt; return sicA->id < sicB->id; } // **************************************************************************** // Method: avtStateRecorderIntegralCurve::SameCurve // // Purpose: // Checks to see if two curves are the same. // // Programmer: Hank Childs // Creation: June 8, 2010 // // **************************************************************************** bool avtStateRecorderIntegralCurve::SameCurve(avtIntegralCurve *ic) { avtStateRecorderIntegralCurve *sic = (avtStateRecorderIntegralCurve *) ic; return (id == sic->id) && (sequenceCnt == sic->sequenceCnt); }
9980eb2ddfb2bd6770393942dfe1e544245daa7f
bb82a5f977bef455714c16e24e2d8254e2d0faa5
/src/vendor/duktape-2.7.0/extras/logging/duk_logging.c
0f367d20ab3496ca3b53e5fb8a102747f411d6b0
[ "Unlicense", "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
pqrs-org/Karabiner-Elements
4ae307d82f8b67547c161c7d46d2083a0fd07630
d05057d7c769e2ff35638282e888a6d5eca566be
refs/heads/main
2023-09-01T03:11:08.474417
2023-09-01T00:44:19
2023-09-01T00:44:19
63,037,806
8,197
389
Unlicense
2023-09-01T00:11:00
2016-07-11T04:57:55
C++
UTF-8
C
false
false
12,351
c
duk_logging.c
/* * Logging support */ #include <stdio.h> #include <string.h> #include <stdarg.h> #include "duktape.h" #include "duk_logging.h" #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || \ defined(WIN64) || defined(_WIN64) || defined(__WIN64__) /* Suppress warnings about plain fopen() etc. */ #define _CRT_SECURE_NO_WARNINGS #if defined(_MSC_VER) && (_MSC_VER < 1900) /* Workaround for snprintf() missing in older MSVC versions. * Note that _snprintf() may not NUL terminate the string, but * this difference does not matter here as a NUL terminator is * always explicitly added. */ #define snprintf _snprintf #endif #endif #if defined(__GNUC__) && !defined(__clang__) #if __GNUC__ >= 7 #define DUK__LOGGING_GCC_PRAGMAS #endif #endif #if defined(DUK__LOGGING_GCC_PRAGMAS) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-truncation" #endif /* XXX: uses stderr always for now, configurable? */ #define DUK_LOGGING_FLUSH /* Duktape 1.x: flush stderr */ /* 3-letter log level strings. */ static const char duk__log_level_strings[] = { 'T', 'R', 'C', 'D', 'B', 'G', 'I', 'N', 'F', 'W', 'R', 'N', 'E', 'R', 'R', 'F', 'T', 'L' }; /* Log method names. */ static const char *duk__log_method_names[] = { "trace", "debug", "info", "warn", "error", "fatal" }; /* Constructor. */ static duk_ret_t duk__logger_constructor(duk_context *ctx) { duk_idx_t nargs; /* Calling as a non-constructor is not meaningful. */ if (!duk_is_constructor_call(ctx)) { return DUK_RET_TYPE_ERROR; } nargs = duk_get_top(ctx); duk_set_top(ctx, 1); duk_push_this(ctx); /* [ name this ] */ if (nargs == 0) { /* Automatic defaulting of logger name from caller. This * would work poorly with tail calls, but constructor calls * are currently never tail calls, so tail calls are not an * issue now. */ duk_inspect_callstack_entry(ctx, -2); if (duk_is_object(ctx, -1)) { if (duk_get_prop_string(ctx, -1, "function")) { if (duk_get_prop_string(ctx, -1, "fileName")) { if (duk_is_string(ctx, -1)) { duk_replace(ctx, 0); } } } } /* Leave values on stack on purpose, ignored below. */ /* Stripping the filename might be a good idea * ("/foo/bar/quux.js" -> logger name "quux"), * but now used verbatim. */ } /* The stack is unbalanced here on purpose; we only rely on the * initial two values: [ name this ]. */ if (duk_is_string(ctx, 0)) { duk_dup(ctx, 0); duk_put_prop_string(ctx, 1, "n"); } else { /* Don't set 'n' at all, inherited value is used as name. * * A natural extension would be to allow an object argument * for extensible parameters, i.e. * new Duktape.Logger({ name: 'foo', ... }) */ } duk_compact(ctx, 1); return 0; /* keep default instance */ } /* Default function to format objects. Tries to use toLogString() but falls * back to toString(). Any errors are propagated out without catching. */ static duk_ret_t duk__logger_prototype_fmt(duk_context *ctx) { if (duk_get_prop_string(ctx, 0, "toLogString")) { /* [ arg toLogString ] */ duk_dup(ctx, 0); duk_call_method(ctx, 0); /* [ arg result ] */ return 1; } /* [ arg undefined ] */ duk_pop(ctx); duk_to_string(ctx, 0); return 1; } /* Default function to write a formatted log line. Writes to stderr, * appending a newline to the log line. * * The argument is a buffer; avoid coercing the buffer to a string to * avoid string table traffic. */ static duk_ret_t duk__logger_prototype_raw(duk_context *ctx) { const char *data; duk_size_t data_len; data = (const char *) duk_require_buffer_data(ctx, 0, &data_len); fwrite((const void *) data, 1, data_len, stderr); fputc((int) '\n', stderr); #if defined(DUK_LOGGING_FLUSH) fflush(stderr); #endif return 0; } /* Log frontend shared helper, magic value indicates log level. Provides * frontend functions: trace(), debug(), info(), warn(), error(), fatal(). * This needs to have small footprint, reasonable performance, minimal * memory churn, etc. */ static duk_ret_t duk__logger_prototype_log_shared(duk_context *ctx) { duk_double_t now; duk_time_components comp; duk_small_int_t entry_lev; duk_small_int_t logger_lev; duk_int_t nargs; duk_int_t i; duk_size_t tot_len; const duk_uint8_t *arg_str; duk_size_t arg_len; duk_uint8_t *buf, *p; const duk_uint8_t *q; duk_uint8_t date_buf[32]; /* maximum format length is 24+1 (NUL), round up. */ duk_size_t date_len; duk_small_int_t rc; /* XXX: sanitize to printable (and maybe ASCII) */ /* XXX: better multiline */ /* * Logger arguments are: * * magic: log level (0-5) * this: logger * stack: plain log args * * We want to minimize memory churn so a two-pass approach * is used: first pass formats arguments and computes final * string length, second pass copies strings into a buffer * allocated directly with the correct size. If the backend * function plays nice, it won't coerce the buffer to a string * (and thus intern it). */ entry_lev = duk_get_current_magic(ctx); if (entry_lev < DUK_LOG_TRACE || entry_lev > DUK_LOG_FATAL) { /* Should never happen, check just in case. */ return 0; } nargs = duk_get_top(ctx); /* [ arg1 ... argN this ] */ /* * Log level check */ duk_push_this(ctx); duk_get_prop_string(ctx, -1, "l"); logger_lev = (duk_small_int_t) duk_get_int(ctx, -1); if (entry_lev < logger_lev) { return 0; } /* log level could be popped but that's not necessary */ now = duk_get_now(ctx); duk_time_to_components(ctx, now, &comp); (void) snprintf((char *) date_buf, sizeof(date_buf), "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", (int) comp.year, (int) comp.month + 1, (int) comp.day, (int) comp.hours, (int) comp.minutes, (int) comp.seconds, (int) comp.milliseconds); date_buf[sizeof(date_buf) - 1] = 0; date_len = strlen((const char *) date_buf); duk_get_prop_string(ctx, -2, "n"); duk_to_string(ctx, -1); /* [ arg1 ... argN this loggerLevel loggerName ] */ /* * Pass 1 */ /* Line format: <time> <entryLev> <loggerName>: <msg> */ tot_len = 0; tot_len += 3 + /* separators: space, space, colon */ 3 + /* level string */ date_len + /* time */ duk_get_length(ctx, -1); /* loggerName */ for (i = 0; i < nargs; i++) { /* When formatting an argument to a string, errors may happen from multiple * causes. In general we want to catch obvious errors like a toLogString() * throwing an error, but we don't currently try to catch every possible * error. In particular, internal errors (like out of memory or stack) are * not caught. Also, we expect Error toString() to not throw an error. */ if (duk_is_object(ctx, i)) { /* duk_pcall_prop() may itself throw an error, but we're content * in catching the obvious errors (like toLogString() throwing an * error). */ duk_push_string(ctx, "fmt"); duk_dup(ctx, i); /* [ arg1 ... argN this loggerLevel loggerName 'fmt' arg ] */ /* call: this.fmt(arg) */ rc = duk_pcall_prop(ctx, -5 /*obj_index*/, 1 /*nargs*/); if (rc) { /* Keep the error as the result (coercing it might fail below, * but we don't catch that now). */ ; } duk_replace(ctx, i); } (void) duk_to_lstring(ctx, i, &arg_len); tot_len++; /* sep (even before first one) */ tot_len += arg_len; } /* * Pass 2 */ /* XXX: Here it'd be nice if we didn't need to allocate a new fixed * buffer for every write. This would be possible if raw() took a * buffer and a length. We could then use a preallocated buffer for * most log writes and request raw() to write a partial buffer. */ buf = (duk_uint8_t *) duk_push_fixed_buffer(ctx, tot_len); p = buf; memcpy((void *) p, (const void *) date_buf, (size_t) date_len); p += date_len; *p++ = (duk_uint8_t) ' '; q = (const duk_uint8_t *) duk__log_level_strings + (entry_lev * 3); memcpy((void *) p, (const void *) q, (size_t) 3); p += 3; *p++ = (duk_uint8_t) ' '; arg_str = (const duk_uint8_t *) duk_get_lstring(ctx, -2, &arg_len); memcpy((void *) p, (const void *) arg_str, (size_t) arg_len); p += arg_len; *p++ = (duk_uint8_t) ':'; for (i = 0; i < nargs; i++) { *p++ = (duk_uint8_t) ' '; arg_str = (const duk_uint8_t *) duk_get_lstring(ctx, i, &arg_len); memcpy((void *) p, (const void *) arg_str, (size_t) arg_len); p += arg_len; } /* [ arg1 ... argN this loggerLevel loggerName buffer ] */ /* Call this.raw(msg); look up through the instance allows user to override * the raw() function in the instance or in the prototype for maximum * flexibility. */ duk_push_string(ctx, "raw"); duk_dup(ctx, -2); /* [ arg1 ... argN this loggerLevel loggerName buffer 'raw' buffer ] */ duk_call_prop(ctx, -6, 1); /* this.raw(buffer) */ return 0; } void duk_log_va(duk_context *ctx, duk_int_t level, const char *fmt, va_list ap) { if (level < 0) { level = 0; } else if (level > (int) (sizeof(duk__log_method_names) / sizeof(const char *)) - 1) { level = (int) (sizeof(duk__log_method_names) / sizeof(const char *)) - 1; } duk_push_global_stash(ctx); duk_get_prop_string(ctx, -1, "\xff" "logger:constructor"); /* fixed at init time */ duk_get_prop_string(ctx, -1, "clog"); duk_get_prop_string(ctx, -1, duk__log_method_names[level]); duk_dup(ctx, -2); duk_push_vsprintf(ctx, fmt, ap); /* [ ... stash Logger clog logfunc clog(=this) msg ] */ duk_call_method(ctx, 1 /*nargs*/); /* [ ... stash Logger clog res ] */ duk_pop_n(ctx, 4); } void duk_log(duk_context *ctx, duk_int_t level, const char *fmt, ...) { va_list ap; va_start(ap, fmt); duk_log_va(ctx, level, fmt, ap); va_end(ap); } void duk_logging_init(duk_context *ctx, duk_uint_t flags) { /* XXX: Add .name property for logger functions (useful for stack traces if they throw). */ (void) flags; duk_eval_string(ctx, "(function(cons,prot){" "Object.defineProperty(Duktape,'Logger',{value:cons,writable:true,configurable:true});" "Object.defineProperty(cons,'prototype',{value:prot});" "Object.defineProperty(cons,'clog',{value:new Duktape.Logger('C'),writable:true,configurable:true});" "});"); duk_push_c_function(ctx, duk__logger_constructor, DUK_VARARGS /*nargs*/); /* Duktape.Logger */ duk_push_object(ctx); /* Duktape.Logger.prototype */ /* [ ... func Duktape.Logger Duktape.Logger.prototype ] */ duk_push_string(ctx, "name"); duk_push_string(ctx, "Logger"); duk_def_prop(ctx, -4, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_FORCE); duk_dup_top(ctx); duk_put_prop_string(ctx, -2, "constructor"); duk_push_int(ctx, 2); duk_put_prop_string(ctx, -2, "l"); duk_push_string(ctx, "anon"); duk_put_prop_string(ctx, -2, "n"); duk_push_c_function(ctx, duk__logger_prototype_fmt, 1 /*nargs*/); duk_put_prop_string(ctx, -2, "fmt"); duk_push_c_function(ctx, duk__logger_prototype_raw, 1 /*nargs*/); duk_put_prop_string(ctx, -2, "raw"); duk_push_c_function(ctx, duk__logger_prototype_log_shared, DUK_VARARGS /*nargs*/); duk_set_magic(ctx, -1, 0); /* magic=0: trace */ duk_put_prop_string(ctx, -2, "trace"); duk_push_c_function(ctx, duk__logger_prototype_log_shared, DUK_VARARGS /*nargs*/); duk_set_magic(ctx, -1, 1); /* magic=1: debug */ duk_put_prop_string(ctx, -2, "debug"); duk_push_c_function(ctx, duk__logger_prototype_log_shared, DUK_VARARGS /*nargs*/); duk_set_magic(ctx, -1, 2); /* magic=2: info */ duk_put_prop_string(ctx, -2, "info"); duk_push_c_function(ctx, duk__logger_prototype_log_shared, DUK_VARARGS /*nargs*/); duk_set_magic(ctx, -1, 3); /* magic=3: warn */ duk_put_prop_string(ctx, -2, "warn"); duk_push_c_function(ctx, duk__logger_prototype_log_shared, DUK_VARARGS /*nargs*/); duk_set_magic(ctx, -1, 4); /* magic=4: error */ duk_put_prop_string(ctx, -2, "error"); duk_push_c_function(ctx, duk__logger_prototype_log_shared, DUK_VARARGS /*nargs*/); duk_set_magic(ctx, -1, 5); /* magic=5: fatal */ duk_put_prop_string(ctx, -2, "fatal"); /* [ ... func Duktape.Logger Duktape.Logger.prototype ] */ /* XXX: when using ROM built-ins, "Duktape" is read-only by default so * setting Duktape.Logger will now fail. */ /* [ ... func Duktape.Logger Duktape.Logger.prototype ] */ duk_call(ctx, 2); duk_pop(ctx); } #if defined(DUK__LOGGING_GCC_PRAGMAS) #pragma GCC diagnostic pop #endif
9aa9c59fbb60aa62e3adae0c5835940710ff94a9
f3eed0234b4d0ad2bbb2abd700cf1e2c7a0e8a1d
/AKWF-c/AKWF_0018/AKWF_1732.h
374f95f46462b35cd0abc2624e88567186907845
[ "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,672
h
AKWF_1732.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_1732 256 samples +-----------------------------------------------------------------------------------------------------------------+ | *** ***** *** | |** *** ********** ********* | |* ** *** ********************* *** | | ** ** ** *| | * ** ** *| | ** ** ** * | | * * * * | | * ** ** * | | * * * ** | | * * ** * | | * * * ** | | * * * * | | * * * * | | *** ** | | ** ** | +-----------------------------------------------------------------------------------------------------------------+ */ const uint16_t AKWF_1732 [] = { 32937, 34035, 35141, 36099, 36974, 37726, 38408, 38984, 39500, 39928, 40310, 40616, 40885, 41092, 41272, 41401, 41511, 41580, 41632, 41657, 41667, 41656, 41636, 41602, 41558, 41507, 41449, 41388, 41319, 41252, 41180, 41112, 41040, 40971, 40902, 40836, 40773, 40714, 40654, 40602, 40552, 40506, 40465, 40430, 40398, 40371, 40349, 40333, 40321, 40315, 40313, 40317, 40326, 40340, 40358, 40383, 40411, 40445, 40481, 40524, 40569, 40619, 40671, 40727, 40785, 40847, 40908, 40970, 41033, 41096, 41158, 41214, 41273, 41320, 41367, 41399, 41431, 41442, 41449, 41429, 41403, 41342, 41269, 41156, 41024, 40842, 40629, 40365, 40052, 39681, 39247, 38745, 38159, 37503, 36736, 35898, 34924, 33872, 32661, 31373, 29900, 28354, 26607, 24792, 22767, 20692, 18404, 16086, 13571, 11056, 8365, 5720, 2893, 507, 2313, 5102, 7537, 10122, 12459, 14849, 17005, 19157, 21078, 22960, 24625, 26225, 27623, 28944, 30088, 31143, 32053, 32870, 33565, 34175, 34688, 35121, 35479, 35764, 35995, 36159, 36287, 36356, 36401, 36397, 36378, 36319, 36252, 36152, 36050, 35923, 35796, 35654, 35510, 35357, 35206, 35051, 34898, 34746, 34595, 34449, 34308, 34168, 34037, 33912, 33792, 33682, 33576, 33481, 33391, 33312, 33243, 33180, 33128, 33084, 33050, 33026, 33011, 33007, 33009, 33024, 33047, 33079, 33119, 33172, 33231, 33300, 33378, 33465, 33558, 33663, 33772, 33889, 34012, 34142, 34277, 34417, 34562, 34709, 34861, 35010, 35165, 35314, 35465, 35604, 35747, 35872, 35998, 36099, 36196, 36264, 36321, 36343, 36345, 36303, 36233, 36113, 35948, 35727, 35444, 35096, 34668, 34170, 33566, 32888, 32081, 31194, 30151, 29030, 27730, 26354, 24781, 23139, 21291, 19391, 17281, 15141, 12802, 10467, 7954, 5489, 2840, 635, 2615, 5591, 8199, 10968, 13477, 16055, 18375, 20713, 22797, 24867, 26687, 28479, 30022, 31552, };
74e1a34685e1309a085bf455e49a0fc1c2eddfe2
d579699e6728aa74084f8cc4dc435007b9f523a8
/tests/regression-tests/expected-outputs/OSX/o4/branch/branch/branch.c
00f273b30b99982c76c3b5995ce225ec6d878cbc
[ "BSD-3-Clause" ]
permissive
BoomerangDecompiler/boomerang
b3c6b4e88c152ac6d437f3dd3640fd9ffa157cb6
411041305f90d1d7c994f67255b5c03ea8666e60
refs/heads/develop
2023-08-31T03:50:56.112711
2020-12-28T12:11:55
2020-12-28T17:38:56
7,819,729
281
41
NOASSERTION
2020-12-27T17:59:52
2013-01-25T12:26:59
C++
UTF-8
C
false
false
973
c
branch.c
int main(int argc, char *argv[]); /** address: 0x00001b78 */ int main(int argc, char *argv[]) { __size32 g3; // r3 int local0; // m[g1 - 32] unsigned int local1; // m[g1 - 28] scanf("%d", &local0); scanf("%d", &local1); if (local0 == 5) { puts("Equal"); } if (local0 != 5) { puts("Not Equal"); } if (5 > local0) { puts("Greater"); } if (5 <= local0) { puts("Less or Equal"); } if (5 >= local0) { puts("Greater or Equal"); } if (5 < local0) { puts("Less"); } if (5 > local1) { puts("Greater Unsigned"); } if (5 <= local1) { puts("Less or Equal Unsigned"); } if (5 >= local1) { puts("Carry Clear"); } if (5 < local1) { puts("Carry Set"); } if (5 >= local0) { puts("Minus"); } g3 = 5 - local0; if (5 < local0) { g3 = puts("Plus"); } return g3; }
c7edd1c7359484029a17a6b752c024d3efd39ba2
9f7ec7effeaf801272b7c828558ebb4004b32874
/textproc/meilisearch/files/patch-cargo-crates_libmimalloc-sys-0.1.32_c__src_mimalloc_src_prim_unix_prim.c
d50b72658bd0ff42ec73f866a69026650f6e0c36
[ "BSD-2-Clause" ]
permissive
pfsense/FreeBSD-ports
d8aaf577d45734949723d83717d6bef5d205a164
53c9359a71bd1d4e6388c387396f865547fd8ad3
refs/heads/devel
2023-08-30T06:06:08.365016
2023-08-25T21:11:27
2023-08-25T21:11:27
41,116,288
504
917
NOASSERTION
2023-09-10T22:37:25
2015-08-20T20:02:11
null
UTF-8
C
false
false
891
c
patch-cargo-crates_libmimalloc-sys-0.1.32_c__src_mimalloc_src_prim_unix_prim.c
--- cargo-crates/libmimalloc-sys-0.1.32/c_src/mimalloc/src/prim/unix/prim.c.orig 2023-06-07 23:03:09 UTC +++ cargo-crates/libmimalloc-sys-0.1.32/c_src/mimalloc/src/prim/unix/prim.c @@ -169,7 +169,7 @@ static void* unix_mmap_prim(void* addr, size_t size, s p = mmap(addr, size, protect_flags, flags | MAP_ALIGNED(n), fd, 0); if (p==MAP_FAILED || !_mi_is_aligned(p,try_alignment)) { int err = errno; - _mi_warning_message("unable to directly request aligned OS memory (error: %d (0x%x), size: 0x%zx bytes, alignment: 0x%zx, hint address: %p)\n", err, err, size, try_alignment, hint); + _mi_warning_message("unable to directly request aligned OS memory (error: %d (0x%x), size: 0x%zx bytes, alignment: 0x%zx, hint address: %p)\n", err, err, size, try_alignment, addr); } if (p!=MAP_FAILED) return p; // fall back to regular mmap
b0b0ff3ed8340f14a39e4729417dbe5dbfd57b16
eecd5e4c50d8b78a769bcc2675250576bed34066
/src/ts/tutorials/ex16fwd.c
a1d9d46577f95d693f36d5f44e249f4287c5c800
[ "BSD-2-Clause" ]
permissive
petsc/petsc
3b1a04fea71858e0292f9fd4d04ea11618c50969
9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9
refs/heads/main
2023-08-17T20:51:16.507070
2023-08-17T16:08:06
2023-08-17T16:08:06
8,691,401
341
169
NOASSERTION
2023-03-29T11:02:58
2013-03-10T20:55:21
C
UTF-8
C
false
false
8,936
c
ex16fwd.c
static char help[] = "Performs adjoint sensitivity analysis for the van der Pol equation.\n\ Input parameters include:\n\ -mu : stiffness parameter\n\n"; /* ------------------------------------------------------------------------ This program solves the van der Pol equation y'' - \mu (1-y^2)*y' + y = 0 (1) on the domain 0 <= x <= 1, with the boundary conditions y(0) = 2, y'(0) = 0, and computes the sensitivities of the final solution w.r.t. initial conditions and parameter \mu with an explicit Runge-Kutta method and its discrete tangent linear model. Notes: This code demonstrates the TSForward interface to a system of ordinary differential equations (ODEs) in the form of u_t = f(u,t). (1) can be turned into a system of first order ODEs [ y' ] = [ z ] [ z' ] [ \mu (1 - y^2) z - y ] which then we can write as a vector equation [ u_1' ] = [ u_2 ] (2) [ u_2' ] [ \mu (1 - u_1^2) u_2 - u_1 ] which is now in the form of u_t = F(u,t). The user provides the right-hand-side function [ f(u,t) ] = [ u_2 ] [ \mu (1 - u_1^2) u_2 - u_1 ] the Jacobian function df [ 0 ; 1 ] -- = [ ] du [ -2 \mu u_1*u_2 - 1; \mu (1 - u_1^2) ] and the JacobainP (the Jacobian w.r.t. parameter) function df [ 0; 0; 0 ] --- = [ ] d\mu [ 0; 0; (1 - u_1^2) u_2 ] ------------------------------------------------------------------------- */ #include <petscts.h> #include <petscmat.h> typedef struct _n_User *User; struct _n_User { PetscReal mu; PetscReal next_output; PetscReal tprev; }; /* User-defined routines */ static PetscErrorCode RHSFunction(TS ts, PetscReal t, Vec X, Vec F, void *ctx) { User user = (User)ctx; PetscScalar *f; const PetscScalar *x; PetscFunctionBeginUser; PetscCall(VecGetArrayRead(X, &x)); PetscCall(VecGetArray(F, &f)); f[0] = x[1]; f[1] = user->mu * (1. - x[0] * x[0]) * x[1] - x[0]; PetscCall(VecRestoreArrayRead(X, &x)); PetscCall(VecRestoreArray(F, &f)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode RHSJacobian(TS ts, PetscReal t, Vec X, Mat A, Mat B, void *ctx) { User user = (User)ctx; PetscReal mu = user->mu; PetscInt rowcol[] = {0, 1}; PetscScalar J[2][2]; const PetscScalar *x; PetscFunctionBeginUser; PetscCall(VecGetArrayRead(X, &x)); J[0][0] = 0; J[1][0] = -2. * mu * x[1] * x[0] - 1.; J[0][1] = 1.0; J[1][1] = mu * (1.0 - x[0] * x[0]); PetscCall(MatSetValues(A, 2, rowcol, 2, rowcol, &J[0][0], INSERT_VALUES)); PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY)); PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY)); if (A != B) { PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY)); PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY)); } PetscCall(VecRestoreArrayRead(X, &x)); PetscFunctionReturn(PETSC_SUCCESS); } static PetscErrorCode RHSJacobianP(TS ts, PetscReal t, Vec X, Mat A, void *ctx) { PetscInt row[] = {0, 1}, col[] = {2}; PetscScalar J[2][1]; const PetscScalar *x; PetscFunctionBeginUser; PetscCall(VecGetArrayRead(X, &x)); J[0][0] = 0; J[1][0] = (1. - x[0] * x[0]) * x[1]; PetscCall(VecRestoreArrayRead(X, &x)); PetscCall(MatSetValues(A, 2, row, 1, col, &J[0][0], INSERT_VALUES)); PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY)); PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY)); PetscFunctionReturn(PETSC_SUCCESS); } /* Monitor timesteps and use interpolation to output at integer multiples of 0.1 */ static PetscErrorCode Monitor(TS ts, PetscInt step, PetscReal t, Vec X, void *ctx) { const PetscScalar *x; PetscReal tfinal, dt, tprev; User user = (User)ctx; PetscFunctionBeginUser; PetscCall(TSGetTimeStep(ts, &dt)); PetscCall(TSGetMaxTime(ts, &tfinal)); PetscCall(TSGetPrevTime(ts, &tprev)); PetscCall(VecGetArrayRead(X, &x)); PetscCall(PetscPrintf(PETSC_COMM_WORLD, "[%.1f] %" PetscInt_FMT " TS %.6f (dt = %.6f) X % 12.6e % 12.6e\n", (double)user->next_output, step, (double)t, (double)dt, (double)PetscRealPart(x[0]), (double)PetscRealPart(x[1]))); PetscCall(PetscPrintf(PETSC_COMM_WORLD, "t %.6f (tprev = %.6f) \n", (double)t, (double)tprev)); PetscCall(VecRestoreArrayRead(X, &x)); PetscFunctionReturn(PETSC_SUCCESS); } int main(int argc, char **argv) { TS ts; /* nonlinear solver */ Vec x; /* solution, residual vectors */ Mat A; /* Jacobian matrix */ Mat Jacp; /* JacobianP matrix */ PetscInt steps; PetscReal ftime = 0.5; PetscBool monitor = PETSC_FALSE; PetscScalar *x_ptr; PetscMPIInt size; struct _n_User user; Mat sp; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Initialize program - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscFunctionBeginUser; PetscCall(PetscInitialize(&argc, &argv, NULL, help)); PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size)); PetscCheck(size == 1, PETSC_COMM_WORLD, PETSC_ERR_WRONG_MPI_SIZE, "This is a uniprocessor example only!"); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Set runtime options - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ user.mu = 1; user.next_output = 0.0; PetscCall(PetscOptionsGetReal(NULL, NULL, "-mu", &user.mu, NULL)); PetscCall(PetscOptionsGetBool(NULL, NULL, "-monitor", &monitor, NULL)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create necessary matrix and vectors, solve same ODE on every process - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(MatCreate(PETSC_COMM_WORLD, &A)); PetscCall(MatSetSizes(A, PETSC_DECIDE, PETSC_DECIDE, 2, 2)); PetscCall(MatSetFromOptions(A)); PetscCall(MatSetUp(A)); PetscCall(MatCreateVecs(A, &x, NULL)); PetscCall(MatCreate(PETSC_COMM_WORLD, &Jacp)); PetscCall(MatSetSizes(Jacp, PETSC_DECIDE, PETSC_DECIDE, 2, 3)); PetscCall(MatSetFromOptions(Jacp)); PetscCall(MatSetUp(Jacp)); PetscCall(MatCreateDense(PETSC_COMM_WORLD, PETSC_DECIDE, PETSC_DECIDE, 2, 3, NULL, &sp)); PetscCall(MatZeroEntries(sp)); PetscCall(MatShift(sp, 1.0)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create timestepping solver context - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(TSCreate(PETSC_COMM_WORLD, &ts)); PetscCall(TSSetType(ts, TSRK)); PetscCall(TSSetRHSFunction(ts, NULL, RHSFunction, &user)); /* Set RHS Jacobian for the adjoint integration */ PetscCall(TSSetRHSJacobian(ts, A, A, RHSJacobian, &user)); PetscCall(TSSetMaxTime(ts, ftime)); PetscCall(TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP)); if (monitor) PetscCall(TSMonitorSet(ts, Monitor, &user, NULL)); PetscCall(TSForwardSetSensitivities(ts, 3, sp)); PetscCall(TSSetRHSJacobianP(ts, Jacp, RHSJacobianP, &user)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Set initial conditions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(VecGetArray(x, &x_ptr)); x_ptr[0] = 2; x_ptr[1] = 0.66666654321; PetscCall(VecRestoreArray(x, &x_ptr)); PetscCall(TSSetTimeStep(ts, .001)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Set runtime options - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(TSSetFromOptions(ts)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Solve nonlinear system - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(TSSolve(ts, x)); PetscCall(TSGetSolveTime(ts, &ftime)); PetscCall(TSGetStepNumber(ts, &steps)); PetscCall(PetscPrintf(PETSC_COMM_WORLD, "mu %g, steps %" PetscInt_FMT ", ftime %g\n", (double)user.mu, steps, (double)ftime)); PetscCall(VecView(x, PETSC_VIEWER_STDOUT_WORLD)); PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n forward sensitivity: d[y(tf) z(tf)]/d[y0 z0 mu]\n")); PetscCall(MatView(sp, PETSC_VIEWER_STDOUT_WORLD)); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Free work space. All PETSc objects should be destroyed when they are no longer needed. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscCall(MatDestroy(&A)); PetscCall(MatDestroy(&Jacp)); PetscCall(VecDestroy(&x)); PetscCall(MatDestroy(&sp)); PetscCall(TSDestroy(&ts)); PetscCall(PetscFinalize()); return 0; } /*TEST test: args: -monitor 0 -ts_adapt_type none TEST*/
cfaab4f39f2aeb952a3d3cae0986870fdc9bd23c
d8fbc197e4fb03e0f083291ec92b75542bcb4917
/src/crt/geometry/collision_detection.c
a44ddb34f03a352925dfb9433647816476a056a0
[]
no_license
hujianzhe/util
b7576091b9d1daa4e3b7f2e8d3be85501c7877a5
146f6c2395c6d8da7383a41d35ebc8190ba8ea02
refs/heads/master
2023-08-18T13:00:57.886249
2023-08-15T08:57:33
2023-08-15T08:57:33
112,769,785
162
55
null
2020-06-09T16:03:15
2017-12-01T17:49:43
C
UTF-8
C
false
false
38,113
c
collision_detection.c
// // Created by hujianzhe // #include "../../../inc/crt/math.h" #include "../../../inc/crt/math_vec3.h" #include "../../../inc/crt/geometry/line_segment.h" #include "../../../inc/crt/geometry/plane.h" #include "../../../inc/crt/geometry/sphere.h" #include "../../../inc/crt/geometry/aabb.h" #include "../../../inc/crt/geometry/obb.h" #include "../../../inc/crt/geometry/triangle.h" #include "../../../inc/crt/geometry/collision_intersect.h" #include "../../../inc/crt/geometry/collision_detection.h" #include <stddef.h> extern int mathSegmentIntersectPlane(const float ls[2][3], const float plane_v[3], const float plane_normal[3], float p[3]); extern int mathSphereIntersectSegment(const float o[3], float radius, const float ls[2][3], float p[3]); extern int mathSphereIntersectPlane(const float o[3], float radius, const float plane_v[3], const float plane_normal[3], float new_o[3], float* new_r); extern int mathOBBIntersectSegment(const GeometryOBB_t* obb, const float ls[2][3]); extern int mathSphereIntersectOBB(const float o[3], float radius, const GeometryOBB_t* obb); /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// static CCTResult_t* copy_result(CCTResult_t* dst, CCTResult_t* src) { if (dst == src) { return dst; } dst->distance = src->distance; dst->hit_point_cnt = src->hit_point_cnt; if (src->hit_point_cnt > 0) { mathVec3Copy(dst->hit_point, src->hit_point); } mathVec3Copy(dst->hit_normal, src->hit_normal); return dst; } static CCTResult_t* set_result(CCTResult_t* result, float distance, const float hit_normal[3]) { result->distance = distance; result->hit_point_cnt = -1; if (hit_normal) { mathVec3Copy(result->hit_normal, hit_normal); } else { mathVec3Set(result->hit_normal, 0.0f, 0.0f, 0.0f); } return result; } static CCTResult_t* add_result_hit_point(CCTResult_t* result, const float p[3]) { mathVec3Copy(result->hit_point, p); result->hit_point_cnt = 1; return result; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// static CCTResult_t* mathRaycastSegment(const float o[3], const float dir[3], const float ls[2][3], CCTResult_t* result) { float v0[3], v1[3], N[3], dot, d; mathVec3Sub(v0, ls[0], o); mathVec3Sub(v1, ls[1], o); mathVec3Cross(N, v0, v1); if (mathVec3IsZero(N)) { dot = mathVec3Dot(v0, v1); if (dot <= 0.0f) { set_result(result, 0.0f, dir); add_result_hit_point(result, o); return result; } mathVec3Cross(N, dir, v0); if (!mathVec3IsZero(N)) { return NULL; } dot = mathVec3Dot(dir, v0); if (dot < 0.0f) { return NULL; } if (mathVec3LenSq(v0) < mathVec3LenSq(v1)) { d = mathVec3Dot(v0, dir); set_result(result, d, dir); add_result_hit_point(result, v0); } else { d = mathVec3Dot(v1, dir); set_result(result, d, dir); add_result_hit_point(result, v1); } return result; } else { float lsdir[3], p[3], op[3]; dot = mathVec3Dot(N, dir); if (dot < -CCT_EPSILON || dot > CCT_EPSILON) { return NULL; } mathVec3Sub(lsdir, ls[1], ls[0]); mathVec3Normalized(lsdir, lsdir); mathPointProjectionLine(o, ls[0], lsdir, p); if (!mathProjectionRay(o, p, dir, &d, op)) { return NULL; } mathVec3Copy(p, o); mathVec3AddScalar(p, dir, d); mathVec3Sub(v0, ls[0], p); mathVec3Sub(v1, ls[1], p); dot = mathVec3Dot(v0, v1); if (dot > 0.0f) { return NULL; } set_result(result, d, op); add_result_hit_point(result, p); return result; } } static CCTResult_t* mathRaycastPlane(const float o[3], const float dir[3], const float plane_v[3], const float plane_n[3], CCTResult_t* result) { float d, cos_theta; mathPointProjectionPlane(o, plane_v, plane_n, NULL, &d); if (fcmpf(d, 0.0f, CCT_EPSILON) == 0) { set_result(result, 0.0f, dir); add_result_hit_point(result, o); return result; } cos_theta = mathVec3Dot(dir, plane_n); if (fcmpf(cos_theta, 0.0f, CCT_EPSILON) == 0) { return NULL; } d /= cos_theta; if (d < 0.0f) { return NULL; } set_result(result, d, plane_n); add_result_hit_point(result, o); mathVec3AddScalar(result->hit_point, dir, d); return result; } static CCTResult_t* mathRaycastPolygen(const float o[3], const float dir[3], const GeometryPolygen_t* polygen, CCTResult_t* result) { CCTResult_t* p_result; int i; float dot; if (!mathRaycastPlane(o, dir, polygen->v[polygen->v_indices[0]], polygen->normal, result)) { return NULL; } if (result->distance > 0.0f) { return mathPolygenHasPoint(polygen, result->hit_point) ? result : NULL; } dot = mathVec3Dot(dir, polygen->normal); if (dot < -CCT_EPSILON || dot > CCT_EPSILON) { return NULL; } p_result = NULL; for (i = 0; i < polygen->v_indices_cnt; ) { CCTResult_t result_temp; float edge[2][3]; mathVec3Copy(edge[0], polygen->v[polygen->v_indices[i++]]); mathVec3Copy(edge[1], polygen->v[polygen->v_indices[i >= polygen->v_indices_cnt ? 0 : i]]); if (!mathRaycastSegment(o, dir, (const float(*)[3])edge, &result_temp)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(result, &result_temp); } } return p_result; } static CCTResult_t* mathRaycastOBB(const float o[3], const float dir[3], const GeometryOBB_t* obb, CCTResult_t* result) { if (mathOBBHasPoint(obb, o)) { set_result(result, 0.0f, dir); add_result_hit_point(result, o); return result; } else { CCTResult_t *p_result = NULL; int i; for (i = 0; i < 6; ++i) { CCTResult_t result_temp; GeometryRect_t rect; mathOBBPlaneRect(obb, i, &rect); if (!mathRaycastPlane(o, dir, rect.o, rect.normal, &result_temp)) { continue; } if (!mathRectHasPoint(&rect, result_temp.hit_point)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { copy_result(result, &result_temp); p_result = result; } } return p_result; } } static CCTResult_t* mathRaycastAABB(const float o[3], const float dir[3], const float aabb_o[3], const float aabb_half[3], CCTResult_t* result) { GeometryOBB_t obb; mathOBBFromAABB(&obb, aabb_o, aabb_half); return mathRaycastOBB(o, dir, &obb, result); } static CCTResult_t* mathRaycastSphere(const float o[3], const float dir[3], const float sp_o[3], float sp_radius, CCTResult_t* result) { float dr2, oc2, dir_d; float oc[3]; float radius2 = sp_radius * sp_radius; mathVec3Sub(oc, sp_o, o); oc2 = mathVec3LenSq(oc); if (oc2 <= radius2) { set_result(result, 0.0f, dir); add_result_hit_point(result, o); return result; } dir_d = mathVec3Dot(dir, oc); if (dir_d <= CCT_EPSILON) { return NULL; } dr2 = oc2 - dir_d * dir_d; if (dr2 > radius2) { return NULL; } dir_d -= sqrtf(radius2 - dr2); set_result(result, dir_d, NULL); add_result_hit_point(result, o); mathVec3AddScalar(result->hit_point, dir, dir_d); mathVec3Sub(result->hit_normal, result->hit_point, sp_o); mathVec3MultiplyScalar(result->hit_normal, result->hit_normal, 1.0f / sp_radius); return result; } static CCTResult_t* mathSegmentcastPlane(const float ls[2][3], const float dir[3], const float vertice[3], const float normal[3], CCTResult_t* result) { float p[3]; int res = mathSegmentIntersectPlane(ls, vertice, normal, p); if (2 == res) { set_result(result, 0.0f, dir); return result; } else if (1 == res) { set_result(result, 0.0f, normal); add_result_hit_point(result, p); return result; } else { float d[2], min_d; float cos_theta = mathVec3Dot(normal, dir); if (fcmpf(cos_theta, 0.0f, CCT_EPSILON) == 0) { return NULL; } mathPointProjectionPlane(ls[0], vertice, normal, NULL, &d[0]); mathPointProjectionPlane(ls[1], vertice, normal, NULL, &d[1]); if (fcmpf(d[0], d[1], CCT_EPSILON) == 0) { min_d = d[0]; min_d /= cos_theta; if (min_d < 0.0f) { return NULL; } set_result(result, min_d, normal); } else { const float *p = NULL; if (d[0] > 0.0f) { if (d[0] < d[1]) { min_d = d[0]; p = ls[0]; } else { min_d = d[1]; p = ls[1]; } } else { if (d[0] < d[1]) { min_d = d[1]; p = ls[1]; } else { min_d = d[0]; p = ls[0]; } } min_d /= cos_theta; if (min_d < 0.0f) { return NULL; } set_result(result, min_d, normal); add_result_hit_point(result, p); mathVec3AddScalar(result->hit_point, dir, min_d); } return result; } } static CCTResult_t* mathSegmentcastSegment(const float ls1[2][3], const float dir[3], const float ls2[2][3], CCTResult_t* result) { int line_mask; float p[3]; int res = mathSegmentIntersectSegment(ls1, ls2, p, &line_mask); if (GEOMETRY_SEGMENT_CONTACT == res) { set_result(result, 0.0f, dir); add_result_hit_point(result, p); return result; } else if (GEOMETRY_SEGMENT_OVERLAP == res) { set_result(result, 0.0f, dir); return result; } else if (GEOMETRY_LINE_PARALLEL == line_mask) { CCTResult_t* p_result = NULL; float neg_dir[3]; int i; for (i = 0; i < 2; ++i) { CCTResult_t result_temp; if (!mathRaycastSegment(ls1[i], dir, ls2, &result_temp)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(p_result, &result_temp); } } if (p_result) { p_result->hit_point_cnt = -1; return p_result; } mathVec3Negate(neg_dir, dir); for (i = 0; i < 2; ++i) { CCTResult_t result_temp; if (!mathRaycastSegment(ls2[i], neg_dir, ls1, &result_temp)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(p_result, &result_temp); } } if (p_result) { p_result->hit_point_cnt = -1; } return p_result; } else if (GEOMETRY_LINE_CROSS == line_mask) { CCTResult_t* p_result = NULL; float neg_dir[3]; int i; for (i = 0; i < 2; ++i) { CCTResult_t result_temp; if (!mathRaycastSegment(ls1[i], dir, ls2, &result_temp)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(p_result, &result_temp); } } mathVec3Negate(neg_dir, dir); for (i = 0; i < 2; ++i) { CCTResult_t result_temp; if (!mathRaycastSegment(ls2[i], neg_dir, ls1, &result_temp)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(p_result, &result_temp); mathVec3Copy(p_result->hit_point, ls2[i]); } } return p_result; } else if (GEOMETRY_LINE_OVERLAP == line_mask) { float v[3], N[3], closest_p[2][3], dot; mathVec3Sub(v, ls1[1], ls1[0]); mathVec3Cross(N, v, dir); if (!mathVec3IsZero(N)) { return NULL; } mathSegmentClosestSegmentVertice(ls1, ls2, closest_p); mathVec3Sub(v, closest_p[1], closest_p[0]); dot = mathVec3Dot(v, dir); if (dot < 0.0f) { return NULL; } set_result(result, dot, dir); add_result_hit_point(result, closest_p[1]); return result; } else { float N[3], v[3], neg_dir[3]; mathVec3Sub(v, ls1[1], ls1[0]); mathVec3Cross(N, v, dir); if (mathVec3IsZero(N)) { return NULL; } mathVec3Normalized(N, N); if (!mathSegmentIntersectPlane(ls2, ls1[0], N, v)) { return NULL; } mathVec3Negate(neg_dir, dir); if (!mathRaycastSegment(v, neg_dir, ls1, result)) { return NULL; } mathVec3Copy(result->hit_point, v); return result; } } static CCTResult_t* mathSegmentcastOBB(const float ls[2][3], const float dir[3], const GeometryOBB_t* obb, CCTResult_t* result) { if (mathOBBIntersectSegment(obb, ls)) { set_result(result, 0.0f, dir); return result; } else { CCTResult_t* p_result = NULL; int i; float v[8][3]; mathOBBVertices(obb, v); for (i = 0; i < sizeof(Box_Edge_Indices) / sizeof(Box_Edge_Indices[0]); i += 2) { float edge[2][3]; CCTResult_t result_temp; mathVec3Copy(edge[0], v[Box_Edge_Indices[i]]); mathVec3Copy(edge[1], v[Box_Edge_Indices[i+1]]); if (!mathSegmentcastSegment(ls, dir, (const float(*)[3])edge, &result_temp)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(p_result, &result_temp); } } for (i = 0; i < 2; ++i) { CCTResult_t result_temp; if (!mathRaycastOBB(ls[i], dir, obb, &result_temp)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(p_result, &result_temp); } } return p_result; } } static CCTResult_t* mathOBBcastSegment(const GeometryOBB_t* obb, const float dir[3], const float ls[2][3], CCTResult_t* result) { float neg_dir[3]; mathVec3Negate(neg_dir, dir); if (!mathSegmentcastOBB(ls, neg_dir, obb, result)) { return NULL; } if (result->hit_point_cnt > 0) { mathVec3AddScalar(result->hit_point, dir, result->distance); } return result; } static CCTResult_t* mathSegmentcastAABB(const float ls[2][3], const float dir[3], const float o[3], const float half[3], CCTResult_t* result) { GeometryOBB_t obb; mathOBBFromAABB(&obb, o, half); return mathSegmentcastOBB(ls, dir, &obb, result); } static CCTResult_t* mathAABBcastSegment(const float o[3], const float half[3], const float dir[3], const float ls[2][3], CCTResult_t* result) { float neg_dir[3]; mathVec3Negate(neg_dir, dir); if (!mathSegmentcastAABB(ls, neg_dir, o, half, result)) { return NULL; } if (result->hit_point_cnt > 0) { mathVec3AddScalar(result->hit_point, dir, result->distance); } return result; } static CCTResult_t* mathSegmentcastPolygen(const float ls[2][3], const float dir[3], const GeometryPolygen_t* polygen, CCTResult_t* result) { CCTResult_t *p_result; int i; if (!mathSegmentcastPlane(ls, dir, polygen->v[polygen->v_indices[0]], polygen->normal, result)) { return NULL; } if (result->hit_point_cnt > 0) { if (mathPolygenHasPoint(polygen, result->hit_point)) { return result; } } else { for (i = 0; i < 2; ++i) { float test_p[3]; mathVec3Copy(test_p, ls[i]); mathVec3AddScalar(test_p, dir, result->distance); if (mathPolygenHasPoint(polygen, test_p)) { return result; } } } p_result = NULL; for (i = 0; i < polygen->v_indices_cnt; ) { CCTResult_t result_temp; float edge[2][3]; mathVec3Copy(edge[0], polygen->v[polygen->v_indices[i++]]); mathVec3Copy(edge[1], polygen->v[polygen->v_indices[i >= polygen->v_indices_cnt ? 0 : i]]); if (!mathSegmentcastSegment(ls, dir, (const float(*)[3])edge, &result_temp)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(result, &result_temp); } } return p_result; } static CCTResult_t* mathPolygencastSegment(const GeometryPolygen_t* polygen, const float dir[3], const float ls[2][3], CCTResult_t* result) { float neg_dir[3]; mathVec3Negate(neg_dir, dir); if (!mathSegmentcastPolygen(ls, neg_dir, polygen, result)) { return NULL; } if (result->hit_point_cnt > 0) { mathVec3AddScalar(result->hit_point, dir, result->distance); } return result; } static CCTResult_t* mathSegmentcastSphere(const float ls[2][3], const float dir[3], const float center[3], float radius, CCTResult_t* result) { float p[3]; int c = mathSphereIntersectSegment(center, radius, ls, p); if (1 == c) { set_result(result, 0.0f, dir); add_result_hit_point(result, p); return result; } else if (2 == c) { set_result(result, 0.0f, dir); return result; } else { CCTResult_t results[2]; float lsdir[3], N[3]; mathVec3Sub(lsdir, ls[1], ls[0]); mathVec3Cross(N, lsdir, dir); if (mathVec3IsZero(N)) { if (!mathRaycastSphere(ls[0], dir, center, radius, &results[0])) { return NULL; } if (!mathRaycastSphere(ls[1], dir, center, radius, &results[1])) { return NULL; } copy_result(result, results[0].distance < results[1].distance ? &results[0] : &results[1]); return result; } else { CCTResult_t* p_result; int i, res; float circle_o[3], circle_radius; mathVec3Normalized(N, N); res = mathSphereIntersectPlane(center, radius, ls[0], N, circle_o, &circle_radius); if (res) { float plo[3], p[3]; mathVec3Normalized(lsdir, lsdir); mathPointProjectionLine(circle_o, ls[0], lsdir, p); mathVec3Sub(plo, circle_o, p); res = fcmpf(mathVec3LenSq(plo), circle_radius * circle_radius, 0.0f); if (res >= 0) { float new_ls[2][3], d; if (res > 0) { float cos_theta = mathVec3Dot(plo, dir); if (cos_theta <= CCT_EPSILON) { return NULL; } d = mathVec3Normalized(plo, plo); cos_theta = mathVec3Dot(plo, dir); d -= circle_radius; mathVec3AddScalar(p, plo, d); d /= cos_theta; mathVec3AddScalar(mathVec3Copy(new_ls[0], ls[0]), dir, d); mathVec3AddScalar(mathVec3Copy(new_ls[1], ls[1]), dir, d); } else { d = 0.0f; mathVec3Copy(new_ls[0], ls[0]); mathVec3Copy(new_ls[1], ls[1]); } if (mathSegmentHasPoint((const float(*)[3])new_ls, p)) { set_result(result, d, plo); add_result_hit_point(result, p); return result; } } p_result = NULL; for (i = 0; i < 2; ++i) { if (!mathRaycastSphere(ls[i], dir, center, radius, &results[i])) { continue; } if (!p_result || p_result->distance > results[i].distance) { p_result = &results[i]; } } if (p_result) { copy_result(result, p_result); return result; } } return NULL; } } } static CCTResult_t* mathSpherecastSegment(const float o[3], const float radius, const float dir[3], const float ls[2][3], CCTResult_t* result) { float neg_dir[3]; mathVec3Negate(neg_dir, dir); if (!mathSegmentcastSphere(ls, neg_dir, o, radius, result)) { return NULL; } if (result->hit_point_cnt > 0) { mathVec3AddScalar(result->hit_point, dir, result->distance); } return result; } static CCTResult_t* mathPolygencastPlane(const GeometryPolygen_t* polygen, const float dir[3], const float plane_v[3], const float plane_n[3], CCTResult_t* result) { int i, has_gt0 = 0, has_le0 = 0, idx_min = -1; float min_d, dot; for (i = 0; i < polygen->v_indices_cnt; ++i) { int cmp; float d; mathPointProjectionPlane(polygen->v[polygen->v_indices[i]], plane_v, plane_n, NULL, &d); cmp = fcmpf(d, 0.0f, CCT_EPSILON); if (cmp > 0) { if (has_le0) { set_result(result, 0.0f, dir); return result; } has_gt0 = 1; } else if (cmp < 0) { if (has_gt0) { set_result(result, 0.0f, dir); return result; } has_le0 = 1; } if (!i || fabsf(min_d) > fabsf(d)) { min_d = d; idx_min = i; } else if (fabsf(min_d) >= fabsf(d) - CCT_EPSILON) { idx_min = -1; } } dot = mathVec3Dot(dir, plane_n); if (dot <= CCT_EPSILON && dot >= -CCT_EPSILON) { return NULL; } min_d /= dot; if (min_d < 0.0f) { return NULL; } set_result(result, min_d, plane_n); if (idx_min >= 0) { add_result_hit_point(result, polygen->v[polygen->v_indices[idx_min]]); mathVec3AddScalar(result->hit_point, dir, min_d); } return result; } static CCTResult_t* mathPolygencastPolygen(const GeometryPolygen_t* polygen1, const float dir[3], const GeometryPolygen_t* polygen2, CCTResult_t* result) { CCTResult_t* p_result; int i, flag; float neg_dir[3]; flag = mathPlaneIntersectPlane(polygen1->v[polygen1->v_indices[0]], polygen1->normal, polygen2->v[polygen2->v_indices[0]], polygen2->normal); if (0 == flag) { float d, dot; mathPointProjectionPlane(polygen1->v[polygen1->v_indices[0]], polygen2->v[polygen2->v_indices[0]], polygen2->normal, NULL, &d); dot = mathVec3Dot(dir, polygen2->normal); if (fcmpf(dot, 0.0f, CCT_EPSILON) == 0) { return NULL; } d /= dot; if (d < 0.0f) { return NULL; } } p_result = NULL; for (i = 0; i < polygen1->v_indices_cnt; ) { CCTResult_t result_temp; float edge[2][3]; mathVec3Copy(edge[0], polygen1->v[polygen1->v_indices[i++]]); mathVec3Copy(edge[1], polygen1->v[polygen1->v_indices[i >= polygen1->v_indices_cnt ? 0 : i]]); if (!mathSegmentcastPolygen((const float(*)[3])edge, dir, polygen2, &result_temp)) { continue; } if (result_temp.distance <= 0.0f) { return set_result(result, 0.0f, result_temp.hit_normal); } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(result, &result_temp); } } mathVec3Negate(neg_dir, dir); for (i = 0; i < polygen2->v_indices_cnt; ) { CCTResult_t result_temp; float edge[2][3]; mathVec3Copy(edge[0], polygen2->v[polygen2->v_indices[i++]]); mathVec3Copy(edge[1], polygen2->v[polygen2->v_indices[i >= polygen2->v_indices_cnt ? 0 : i]]); if (!mathSegmentcastPolygen((const float(*)[3])edge, neg_dir, polygen1, &result_temp)) { continue; } if (result_temp.distance <= 0.0f) { return set_result(result, 0.0f, result_temp.hit_normal); } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(result, &result_temp); } } if (p_result) { p_result->hit_point_cnt = -1; } return p_result; } static CCTResult_t* mathBoxCastPlane(const float v[8][3], const float dir[3], const float plane_v[3], const float plane_n[3], CCTResult_t* result) { CCTResult_t* p_result = NULL; int i, unhit = 0; for (i = 0; i < 8; ++i) { int cmp; CCTResult_t result_temp; if (!mathRaycastPlane(v[i], dir, plane_v, plane_n, &result_temp)) { if (p_result) { set_result(result, 0.0f, plane_n); return result; } unhit = 1; continue; } if (unhit) { set_result(result, 0.0f, plane_n); return result; } if (!p_result) { copy_result(result, &result_temp); p_result = result; continue; } cmp = fcmpf(p_result->distance, result_temp.distance, CCT_EPSILON); if (cmp < 0) { continue; } if (0 == cmp) { p_result->hit_point_cnt = -1; continue; } copy_result(result, &result_temp); } return p_result; } static CCTResult_t* mathOBBcastPlane(const GeometryOBB_t* obb, const float dir[3], const float plane_v[3], const float plane_n[3], CCTResult_t* result) { float v[8][3]; mathOBBVertices(obb, v); return mathBoxCastPlane((const float(*)[3])v, dir, plane_v, plane_n, result); } static CCTResult_t* mathAABBcastPlane(const float o[3], const float half[3], const float dir[3], const float plane_v[3], const float plane_n[3], CCTResult_t* result) { float v[8][3]; mathAABBVertices(o, half, v); return mathBoxCastPlane((const float(*)[3])v, dir, plane_v, plane_n, result); } static CCTResult_t* mathAABBcastAABB(const float o1[3], const float half1[3], const float dir[3], const float o2[3], const float half2[3], CCTResult_t* result) { if (mathAABBIntersectAABB(o1, half1, o2, half2)) { set_result(result, 0.0f, dir); return result; } else { CCTResult_t *p_result = NULL; int i; float v1[6][3], v2[6][3]; mathAABBPlaneVertices(o1, half1, v1); mathAABBPlaneVertices(o2, half2, v2); for (i = 0; i < 6; ++i) { float new_o1[3]; CCTResult_t result_temp; if (i & 1) { if (!mathRaycastPlane(v1[i], dir, v2[i-1], AABB_Plane_Normal[i], &result_temp)) { continue; } } else { if (!mathRaycastPlane(v1[i], dir, v2[i+1], AABB_Plane_Normal[i], &result_temp)) { continue; } } mathVec3Copy(new_o1, o1); mathVec3AddScalar(new_o1, dir, result_temp.distance); if (!mathAABBIntersectAABB(new_o1, half1, o2, half2)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(p_result, &result_temp); } } if (p_result) { p_result->hit_point_cnt = -1; } return p_result; } } static CCTResult_t* mathOBBcastPolygen(const GeometryOBB_t* obb, const float dir[3], const GeometryPolygen_t* polygen, CCTResult_t* result) { int i; float v[8][3], neg_dir[3]; CCTResult_t *p_result; mathOBBVertices(obb, v); if (!mathBoxCastPlane((const float(*)[3])v, dir, polygen->v[polygen->v_indices[0]], polygen->normal, result)) { return NULL; } if (result->hit_point_cnt > 0) { if (mathPolygenHasPoint(polygen, result->hit_point)) { return result; } } else if (result->distance != 0.0f) { for (i = 0; i < 8; ++i) { float test_p[3]; mathVec3Copy(test_p, v[i]); mathVec3AddScalar(test_p, dir, result->distance); if (mathPolygenHasPoint(polygen, test_p)) { return result; } } } p_result = NULL; mathVec3Negate(neg_dir, dir); for (i = 0; i < polygen->v_indices_cnt; ) { CCTResult_t result_temp; float edge[2][3]; mathVec3Copy(edge[0], polygen->v[polygen->v_indices[i++]]); mathVec3Copy(edge[1], polygen->v[polygen->v_indices[i >= polygen->v_indices_cnt ? 0 : i]]); if (!mathSegmentcastOBB((const float(*)[3])edge, neg_dir, obb, &result_temp)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(p_result, &result_temp); } } if (p_result && p_result->hit_point_cnt > 0) { mathVec3AddScalar(p_result->hit_point, dir, p_result->distance); } return p_result; } static CCTResult_t* mathPolygencastOBB(const GeometryPolygen_t* polygen, const float dir[3], const GeometryOBB_t* obb, CCTResult_t* result) { float neg_dir[3]; mathVec3Negate(neg_dir, dir); if (!mathOBBcastPolygen(obb, neg_dir, polygen, result)) { return NULL; } if (result->hit_point_cnt > 0) { mathVec3AddScalar(result->hit_point, dir, result->distance); } return result; } static CCTResult_t* mathAABBcastPolygen(const float o[3], const float half[3], const float dir[3], const GeometryPolygen_t* polygen, CCTResult_t* result) { GeometryOBB_t obb; mathOBBFromAABB(&obb, o, half); return mathOBBcastPolygen(&obb, dir, polygen, result); } static CCTResult_t* mathPolygencastAABB(const GeometryPolygen_t* polygen, const float dir[3], const float o[3], const float half[3], CCTResult_t* result) { float neg_dir[3]; mathVec3Negate(neg_dir, dir); if (!mathAABBcastPolygen(o, half, neg_dir, polygen, result)) { return NULL; } if (result->hit_point_cnt > 0) { mathVec3AddScalar(result->hit_point, dir, result->distance); } return result; } static CCTResult_t* mathOBBcastOBB(const GeometryOBB_t* obb1, const float dir[3], const GeometryOBB_t* obb2, CCTResult_t* result) { int i; CCTResult_t* p_result; if (mathOBBIntersectOBB(obb1, obb2)) { set_result(result, 0.0f, dir); return result; } p_result = NULL; for (i = 0; i < 6; ++i) { float p[4][3]; CCTResult_t result_temp; GeometryRect_t rect; GeometryPolygen_t polygen; mathOBBPlaneRect(obb1, i, &rect); mathRectToPolygen(&rect, &polygen, p); if (!mathPolygencastOBB(&polygen, dir, obb2, &result_temp)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(result, &result_temp); } } return p_result; } static CCTResult_t* mathSpherecastPlane(const float o[3], float radius, const float dir[3], const float plane_v[3], const float plane_n[3], CCTResult_t* result) { int res; float dn, d; mathPointProjectionPlane(o, plane_v, plane_n, NULL, &dn); res = fcmpf(dn * dn, radius * radius, 0.0f); if (res < 0) { set_result(result, 0.0f, dir); return result; } else if (0 == res) { set_result(result, 0.0f, dir); add_result_hit_point(result, o); mathVec3AddScalar(result->hit_point, plane_n, dn); return result; } else { float dn_abs, cos_theta = mathVec3Dot(plane_n, dir); if (cos_theta <= CCT_EPSILON && cos_theta >= -CCT_EPSILON) { return NULL; } d = dn / cos_theta; if (d < 0.0f) { return NULL; } dn_abs = (dn >= 0.0f ? dn : -dn); d -= radius / dn_abs * d; set_result(result, d, plane_n); add_result_hit_point(result, o); mathVec3AddScalar(result->hit_point, dir, d); mathVec3AddScalar(result->hit_point, plane_n, dn >= 0.0f ? radius : -radius); return result; } } static CCTResult_t* mathSpherecastSphere(const float o1[3], float r1, const float dir[3], const float o2[3], float r2, CCTResult_t* result) { if (!mathRaycastSphere(o1, dir, o2, r1 + r2, result)) { return NULL; } mathVec3Sub(result->hit_normal, result->hit_point, o2); mathVec3Normalized(result->hit_normal, result->hit_normal); mathVec3AddScalar(result->hit_point, result->hit_normal, -r1); return result; } static CCTResult_t* mathSpherecastOBB(const float o[3], float radius, const float dir[3], const GeometryOBB_t* obb, CCTResult_t* result) { if (mathSphereIntersectOBB(o, radius, obb)) { set_result(result, 0.0f, dir); return result; } else { CCTResult_t* p_result = NULL; float v[8][3], neg_dir[3]; int i; for (i = 0; i < 6; ++i) { CCTResult_t result_temp; GeometryRect_t rect; mathOBBPlaneRect(obb, i, &rect); if (!mathSpherecastPlane(o, radius, dir, rect.o, rect.normal, &result_temp)) { continue; } if (fcmpf(result_temp.distance, 0.0f, CCT_EPSILON) == 0) { continue; } if (!mathRectHasPoint(&rect, result_temp.hit_point)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(p_result, &result_temp); } } if (p_result) { return p_result; } mathOBBVertices(obb, v); mathVec3Negate(neg_dir, dir); for (i = 0; i < sizeof(Box_Edge_Indices) / sizeof(Box_Edge_Indices[0]); i += 2) { float edge[2][3]; CCTResult_t result_temp; mathVec3Copy(edge[0], v[Box_Edge_Indices[i]]); mathVec3Copy(edge[1], v[Box_Edge_Indices[i+1]]); if (!mathSegmentcastSphere((const float(*)[3])edge, neg_dir, o, radius, &result_temp)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(p_result, &result_temp); } } return p_result; } } static CCTResult_t* mathOBBcastSphere(const GeometryOBB_t* obb, const float dir[3], const float o[3], float radius, CCTResult_t* result) { float neg_dir[3]; mathVec3Negate(neg_dir, dir); if (!mathSpherecastOBB(o, radius, neg_dir, obb, result)) { return NULL; } if (result->hit_point_cnt > 0) { mathVec3AddScalar(result->hit_point, dir, result->distance); } return result; } static CCTResult_t* mathSpherecastAABB(const float o[3], float radius, const float dir[3], const float center[3], const float half[3], CCTResult_t* result) { GeometryOBB_t obb; mathOBBFromAABB(&obb, center, half); return mathSpherecastOBB(o, radius, dir, &obb, result); } static CCTResult_t* mathAABBcastSphere(const float center[3], const float half[3], const float dir[3], const float o[3], float radius, CCTResult_t* result) { float neg_dir[3]; mathVec3Negate(neg_dir, dir); if (!mathSpherecastAABB(o, radius, neg_dir, center, half, result)) { return NULL; } if (result->hit_point_cnt > 0) { mathVec3AddScalar(result->hit_point, dir, result->distance); } return result; } static CCTResult_t* mathSpherecastPolygen(const float o[3], float radius, const float dir[3], const GeometryPolygen_t* polygen, CCTResult_t* result) { int i; CCTResult_t *p_result = NULL; float neg_dir[3]; if (!mathSpherecastPlane(o, radius, dir, polygen->v[polygen->v_indices[0]], polygen->normal, result)) { return NULL; } if (result->hit_point_cnt > 0) { if (mathPolygenHasPoint(polygen, result->hit_point)) { return result; } } p_result = NULL; mathVec3Negate(neg_dir, dir); for (i = 0; i < polygen->v_indices_cnt; ) { CCTResult_t result_temp; float edge[2][3]; mathVec3Copy(edge[0], polygen->v[polygen->v_indices[i++]]); mathVec3Copy(edge[1], polygen->v[polygen->v_indices[i >= polygen->v_indices_cnt ? 0 : i]]); if (!mathSegmentcastSphere((const float(*)[3])edge, neg_dir, o, radius, &result_temp)) { continue; } if (!p_result || p_result->distance > result_temp.distance) { p_result = result; copy_result(result, &result_temp); } } if (p_result) { mathVec3AddScalar(p_result->hit_point, dir, p_result->distance); } return p_result; } static CCTResult_t* mathPolygencastSphere(const GeometryPolygen_t* polygen, const float dir[3], const float o[3], float radius, CCTResult_t* result) { float neg_dir[3]; mathVec3Negate(neg_dir, dir); if (!mathSpherecastPolygen(o, radius, dir, polygen, result)) { return NULL; } if (result->hit_point_cnt > 0) { mathVec3AddScalar(result->hit_point, dir, result->distance); } return result; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// #ifdef __cplusplus extern "C" { #endif CCTResult_t* mathCollisionBodyCast(const GeometryBodyRef_t* one, const float dir[3], const GeometryBodyRef_t* two, CCTResult_t* result) { if (one->data == two->data || mathVec3IsZero(dir)) { return NULL; } if (GEOMETRY_BODY_POINT == one->type) { switch (two->type) { case GEOMETRY_BODY_AABB: { return mathRaycastAABB(one->point, dir, two->aabb->o, two->aabb->half, result); } case GEOMETRY_BODY_OBB: { return mathRaycastOBB(one->point, dir, two->obb, result); } case GEOMETRY_BODY_SPHERE: { return mathRaycastSphere(one->point, dir, two->sphere->o, two->sphere->radius, result); } case GEOMETRY_BODY_PLANE: { return mathRaycastPlane(one->point, dir, two->plane->v, two->plane->normal, result); } case GEOMETRY_BODY_SEGMENT: { return mathRaycastSegment(one->point, dir, two->segment->v, result); } case GEOMETRY_BODY_POLYGEN: { return mathRaycastPolygen(one->point, dir, two->polygen, result); } } } else if (GEOMETRY_BODY_SEGMENT == one->type) { switch (two->type) { case GEOMETRY_BODY_SEGMENT: { return mathSegmentcastSegment(one->segment->v, dir, two->segment->v, result); } case GEOMETRY_BODY_PLANE: { return mathSegmentcastPlane(one->segment->v, dir, two->plane->v, two->plane->normal, result); } case GEOMETRY_BODY_OBB: { return mathSegmentcastOBB(one->segment->v, dir, two->obb, result); } case GEOMETRY_BODY_AABB: { return mathSegmentcastAABB(one->segment->v, dir, two->aabb->o, two->aabb->half, result); } case GEOMETRY_BODY_SPHERE: { return mathSegmentcastSphere(one->segment->v, dir, two->sphere->o, two->sphere->radius, result); } case GEOMETRY_BODY_POLYGEN: { return mathSegmentcastPolygen(one->segment->v, dir, two->polygen, result); } } } else if (GEOMETRY_BODY_AABB == one->type) { switch (two->type) { case GEOMETRY_BODY_AABB: { return mathAABBcastAABB(one->aabb->o, one->aabb->half, dir, two->aabb->o, two->aabb->half, result); } case GEOMETRY_BODY_OBB: { GeometryOBB_t obb1; mathOBBFromAABB(&obb1, one->aabb->o, one->aabb->half); return mathOBBcastOBB(&obb1, dir, two->obb, result); } case GEOMETRY_BODY_SPHERE: { return mathAABBcastSphere(one->aabb->o, one->aabb->half, dir, two->sphere->o, two->sphere->radius, result); } case GEOMETRY_BODY_PLANE: { return mathAABBcastPlane(one->aabb->o, one->aabb->half, dir, two->plane->v, two->plane->normal, result); } case GEOMETRY_BODY_SEGMENT: { return mathAABBcastSegment(one->aabb->o, one->aabb->half, dir, two->segment->v, result); } case GEOMETRY_BODY_POLYGEN: { return mathAABBcastPolygen(one->aabb->o, one->aabb->half, dir, two->polygen, result); } } } else if (GEOMETRY_BODY_SPHERE == one->type) { switch (two->type) { case GEOMETRY_BODY_OBB: { return mathSpherecastOBB(one->sphere->o, one->sphere->radius, dir, two->obb, result); } case GEOMETRY_BODY_AABB: { return mathSpherecastAABB(one->sphere->o, one->sphere->radius, dir, two->aabb->o, two->aabb->half, result); } case GEOMETRY_BODY_SPHERE: { return mathSpherecastSphere(one->sphere->o, one->sphere->radius, dir, two->sphere->o, two->sphere->radius, result); } case GEOMETRY_BODY_PLANE: { return mathSpherecastPlane(one->sphere->o, one->sphere->radius, dir, two->plane->v, two->plane->normal, result); } case GEOMETRY_BODY_SEGMENT: { return mathSpherecastSegment(one->sphere->o, one->sphere->radius, dir, two->segment->v, result); } case GEOMETRY_BODY_POLYGEN: { return mathSpherecastPolygen(one->sphere->o, one->sphere->radius, dir, two->polygen, result); } } } else if (GEOMETRY_BODY_POLYGEN == one->type) { switch (two->type) { case GEOMETRY_BODY_SEGMENT: { return mathPolygencastSegment(one->polygen, dir, two->segment->v, result); } case GEOMETRY_BODY_PLANE: { return mathPolygencastPlane(one->polygen, dir, two->plane->v, two->plane->normal, result); } case GEOMETRY_BODY_SPHERE: { return mathPolygencastSphere(one->polygen, dir, two->sphere->o, two->sphere->radius, result); } case GEOMETRY_BODY_OBB: { return mathPolygencastOBB(one->polygen, dir, two->obb, result); } case GEOMETRY_BODY_AABB: { return mathPolygencastAABB(one->polygen, dir, two->aabb->o, two->aabb->half, result); } case GEOMETRY_BODY_POLYGEN: { return mathPolygencastPolygen(one->polygen, dir, two->polygen, result); } } } else if (GEOMETRY_BODY_OBB == one->type) { switch (two->type) { case GEOMETRY_BODY_SEGMENT: { return mathOBBcastSegment(one->obb, dir, two->segment->v, result); } case GEOMETRY_BODY_PLANE: { return mathOBBcastPlane(one->obb, dir, two->plane->v, two->plane->normal, result); } case GEOMETRY_BODY_SPHERE: { return mathOBBcastSphere(one->obb, dir, two->sphere->o, two->sphere->radius, result); } case GEOMETRY_BODY_OBB: { return mathOBBcastOBB(one->obb, dir, two->obb, result); } case GEOMETRY_BODY_AABB: { GeometryOBB_t obb2; mathOBBFromAABB(&obb2, two->aabb->o, two->aabb->half); return mathOBBcastOBB(one->obb, dir, &obb2, result); } case GEOMETRY_BODY_POLYGEN: { return mathOBBcastPolygen(one->obb, dir, two->polygen, result); } } } return NULL; } #ifdef __cplusplus } #endif
dbd6112ac25c1c02a9bc17e20d61935bf9bdfb7d
ec6a71b57ebe88538269197fd16bede6bc2062ae
/erts/emulator/beam/erl_db_util.c
29a3912a3b7c5d0fba97c50ba3145878efdff80c
[ "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
166,928
c
erl_db_util.c
/* * %CopyrightBegin% * * Copyright Ericsson AB 1998-2023. 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% */ /* * Common utilities for the different types of db tables. * Mostly matching etc. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "sys.h" #include "erl_vm.h" #include "global.h" #include "erl_process.h" #include "error.h" #define ERTS_WANT_DB_INTERNAL__ #include "erl_db.h" #include "bif.h" #include "big.h" #include "erl_binary.h" #include "erl_map.h" #include "erl_thr_progress.h" #include "erl_proc_sig_queue.h" #include "erl_global_literals.h" #include "erl_db_util.h" /* ** Flags for the guard bif's */ /* These are offsets from the DCOMP_* value */ #define DBIF_GUARD 1 #define DBIF_BODY 0 /* These are the DBIF flag bits corresponding to the DCOMP_* value. * If a bit is set, the BIF is allowed in that context. */ #define DBIF_TABLE_GUARD (1 << (DCOMP_TABLE + DBIF_GUARD)) #define DBIF_TABLE_BODY (1 << (DCOMP_TABLE + DBIF_BODY)) #define DBIF_TRACE_GUARD (1 << (DCOMP_TRACE + DBIF_GUARD)) #define DBIF_TRACE_BODY (1 << (DCOMP_TRACE + DBIF_BODY)) #define DBIF_ALL \ DBIF_TABLE_GUARD | DBIF_TABLE_BODY | DBIF_TRACE_GUARD | DBIF_TRACE_BODY #define HEAP_XTRA 100 /* ** Some convenience macros for stacks (DMC == db_match_compile) */ #define DMC_DEFAULT_SIZE 25 #define DMC_STACK_TYPE(Type) DMC_##Type##_stack #define DMC_DECLARE_STACK_TYPE(Type) \ typedef struct DMC_STACK_TYPE(Type) { \ int pos; \ int siz; \ int bytes; \ Type *data; \ Type def[DMC_DEFAULT_SIZE]; \ } DMC_STACK_TYPE(Type) typedef int Dummy; DMC_DECLARE_STACK_TYPE(Dummy); static void dmc_stack_grow(DMC_Dummy_stack* s) { int was_bytes = s->bytes; s->siz *= 2; s->bytes *= 2; if (s->data == s->def) { s->data = erts_alloc(ERTS_ALC_T_DB_MC_STK, s->bytes); sys_memcpy(s->data, s->def, was_bytes); } else { s->data = erts_realloc(ERTS_ALC_T_DB_MC_STK, s->data, s->bytes); } } #define DMC_INIT_STACK(Name) do { \ (Name).pos = 0; \ (Name).siz = DMC_DEFAULT_SIZE; \ (Name).bytes = sizeof((Name).def); \ (Name).data = (Name).def; \ } while (0) #define DMC_STACK_DATA(Name) (Name).data #define DMC_STACK_NUM(Name) (Name).pos #define DMC_PUSH(On, What) \ do { \ if ((On).pos >= (On).siz) \ dmc_stack_grow((DMC_Dummy_stack*)&(On)); \ (On).data[(On).pos++] = What; \ } while (0) #define DMC_PUSH2(On, A, B) \ do { \ if ((On).pos+1 >= (On).siz) \ dmc_stack_grow((DMC_Dummy_stack*)&(On)); \ (On).data[(On).pos++] = A; \ (On).data[(On).pos++] = B; \ } while (0) #define DMC_POP(From) (From).data[--(From).pos] #define DMC_TOP(From) (From).data[(From).pos - 1] #define DMC_EMPTY(Name) ((Name).pos == 0) #define DMC_PEEK(On, At) (On).data[At] #define DMC_POKE(On, At, Value) ((On).data[At] = (Value)) #define DMC_CLEAR(Name) (Name).pos = 0 #define DMC_FREE(Name) \ do { \ if ((Name).def != (Name).data) \ erts_free(ERTS_ALC_T_DB_MC_STK, (Name).data); \ } while (0) #define add_dmc_err(EINFO, STR, VAR, TERM, SEV) \ vadd_dmc_err(EINFO, SEV, VAR, STR, TERM) #define ERTS_DB_STACK_MARGIN (sizeof(void *)*1024) static int stack_guard_downwards(char *limit) { char c; ASSERT(limit); return erts_check_below_limit(&c, limit + ERTS_DB_STACK_MARGIN); } static int stack_guard_upwards(char *limit) { char c; ASSERT(limit); return erts_check_above_limit(&c, limit - ERTS_DB_STACK_MARGIN); } static int (*stack_guard)(char *) = NULL; static ERTS_INLINE Process * get_proc(Process *cp, Uint32 cp_locks, Eterm id, Uint32 id_locks) { Process *proc = erts_pid2proc(cp, cp_locks, id, id_locks); if (!proc && is_atom(id)) proc = erts_whereis_process(cp, cp_locks, id, id_locks, 0); return proc; } static Eterm set_tracee_flags(Process *tracee_p, ErtsTracer tracer, Uint d_flags, Uint e_flags) { Eterm ret; Uint flags; if (ERTS_TRACER_IS_NIL(tracer)) { flags = ERTS_TRACE_FLAGS(tracee_p) & ~TRACEE_FLAGS; } else { flags = ((ERTS_TRACE_FLAGS(tracee_p) & ~d_flags) | e_flags); if (! flags) tracer = erts_tracer_nil; } ret = ((!ERTS_TRACER_COMPARE(ERTS_TRACER(tracee_p),tracer) || ERTS_TRACE_FLAGS(tracee_p) != flags) ? am_true : am_false); erts_tracer_replace(&tracee_p->common, tracer); ERTS_TRACE_FLAGS(tracee_p) = flags; return ret; } /* ** Assuming all locks on tracee_p on entry ** ** Changes ERTS_TRACE_FLAGS(tracee_p) and ERTS_TRACER_PROC(tracee_p) ** according to input disable/enable flags and tracer. ** ** Returns am_true|am_false on success, am_true if value changed, ** returns fail_term on failure. Fails if tracer pid or port is invalid. */ static Eterm set_match_trace(Process *tracee_p, Eterm fail_term, ErtsTracer tracer, Uint d_flags, Uint e_flags) { ERTS_LC_ASSERT( ERTS_PROC_LOCKS_ALL == erts_proc_lc_my_proc_locks(tracee_p) || erts_thr_progress_is_blocking()); if (ERTS_TRACER_IS_NIL(tracer) || erts_is_tracer_enabled(tracer, &tracee_p->common)) return set_tracee_flags(tracee_p, tracer, d_flags, e_flags); return fail_term; } /* ** ** Types and enum's (compiled matches) ** */ /* ** match VM instructions */ typedef enum { matchArray, /* Only when parameter is an array (DCOMP_TRACE) */ matchArrayBind, /* ------------- " ------------ */ matchTuple, matchPushT, matchPushL, matchPushM, matchPop, matchSwap, matchBind, matchCmp, matchEqBin, matchEqFloat, matchEqBig, matchEqRef, matchEq, matchList, matchMap, matchKey, matchSkip, matchPushC, matchConsA, /* Car is below Cdr */ matchConsB, /* Cdr is below Car (unusual) */ matchMkTuple, matchMkFlatMap, matchMkHashMap, matchCall0, matchCall1, matchCall2, matchCall3, matchPushV, matchPushVResult, /* First variable reference in result */ matchPushExpr, /* Push the whole expression we're matching ('$_') */ matchPushArrayAsList, /* Only when parameter is an Array and not an erlang term (DCOMP_TRACE) */ matchPushArrayAsListU, /* As above but unknown size */ matchTrue, matchOr, matchAnd, matchOrElse, matchAndAlso, matchJump, matchSelf, matchWaste, matchReturn, matchProcessDump, matchDisplay, matchIsSeqTrace, matchSetSeqToken, matchGetSeqToken, matchSetReturnTrace, matchSetExceptionTrace, matchCatch, matchEnableTrace, matchDisableTrace, matchEnableTrace2, matchDisableTrace2, matchTryMeElse, matchCaller, matchHalt, matchSilent, matchSetSeqTokenFake, matchTrace2, matchTrace3, matchCallerLine, matchCurrentStacktrace } MatchOps; /* ** Guard bif's */ typedef struct dmc_guard_bif { Eterm name; /* atom */ void *biff; /* BIF_RETTYPE (*biff)(); */ int arity; Uint32 flags; } DMCGuardBif; /* ** Error information (for lint) */ /* ** Type declarations for stacks */ DMC_DECLARE_STACK_TYPE(Eterm); DMC_DECLARE_STACK_TYPE(UWord); DMC_DECLARE_STACK_TYPE(unsigned); /* ** Data about the heap during compilation */ typedef struct DMCVariable { int is_bound; int is_in_body; } DMCVariable; typedef struct DMCHeap { int size; DMCVariable vars_def[DMC_DEFAULT_SIZE]; DMCVariable* vars; int vars_used; } DMCHeap; /* ** Return values from sub compilation steps (guard compilation) */ typedef enum dmc_ret { retOk, retFail, retRestart } DMCRet; /* ** Diverse context information */ typedef struct dmc_context { int stack_need; int stack_used; ErlHeapFragment *save; ErlHeapFragment *copy; Eterm *matchexpr; Eterm *guardexpr; Eterm *bodyexpr; int num_match; int current_match; Uint cflags; int is_guard; /* 1 if in guard, 0 if in body */ int special; /* 1 if the head in the match was a single expression */ DMCErrInfo *err_info; char *stack_limit; Uint freason; } DMCContext; /* ** ** Global variables ** */ /* ** Internal */ /* ** The pseudo process used by the VM (pam). */ #define ERTS_DEFAULT_MS_HEAP_SIZE 128 /* Runtime info about a $-variable */ typedef struct MatchVariable { Eterm term; #ifdef DEBUG Process* proc; #endif } MatchVariable; typedef struct { Process process; union { Eterm* heap; MatchVariable* variables; /* first on "heap" */ }u; Eterm default_heap[ERTS_DEFAULT_MS_HEAP_SIZE]; } ErtsMatchPseudoProcess; static erts_tsd_key_t match_pseudo_process_key; static ERTS_INLINE void cleanup_match_pseudo_process(ErtsMatchPseudoProcess *mpsp, int keep_heap) { if (mpsp->process.mbuf || mpsp->process.off_heap.first) { erts_cleanup_empty_process(&mpsp->process); } #ifdef DEBUG else { erts_debug_verify_clean_empty_process(&mpsp->process); } #endif if (!keep_heap) { if (mpsp->u.heap != mpsp->default_heap) { /* Have to be done *after* call to erts_cleanup_empty_process() */ erts_free(ERTS_ALC_T_DB_MS_RUN_HEAP, (void *) mpsp->u.heap); mpsp->u.heap = mpsp->default_heap; } #ifdef DEBUG else { int i; for (i = 0; i < ERTS_DEFAULT_MS_HEAP_SIZE; i++) { #if defined(ARCH_64) mpsp->default_heap[i] = (Eterm) 0xdeadbeefdeadbeef; #else mpsp->default_heap[i] = (Eterm) 0xdeadbeef; #endif } } #endif } } static ErtsMatchPseudoProcess * create_match_pseudo_process(void) { ErtsMatchPseudoProcess *mpsp; mpsp = (ErtsMatchPseudoProcess *)erts_alloc(ERTS_ALC_T_DB_MS_PSDO_PROC, sizeof(ErtsMatchPseudoProcess)); erts_init_empty_process(&mpsp->process); mpsp->u.heap = mpsp->default_heap; return mpsp; } static ERTS_INLINE ErtsMatchPseudoProcess * get_match_pseudo_process(Process *c_p, Uint heap_size) { ErtsMatchPseudoProcess *mpsp; ErtsSchedulerData *esdp; esdp = c_p ? c_p->scheduler_data : erts_get_scheduler_data(); mpsp = esdp ? esdp->match_pseudo_process : (ErtsMatchPseudoProcess*) erts_tsd_get(match_pseudo_process_key); if (mpsp) { ASSERT(mpsp == erts_tsd_get(match_pseudo_process_key)); ASSERT(mpsp->process.scheduler_data == esdp); cleanup_match_pseudo_process(mpsp, 0); } else { ASSERT(erts_tsd_get(match_pseudo_process_key) == NULL); mpsp = create_match_pseudo_process(); if (esdp) { esdp->match_pseudo_process = (void *) mpsp; } mpsp->process.scheduler_data = esdp; erts_tsd_set(match_pseudo_process_key, (void *) mpsp); } if (heap_size > ERTS_DEFAULT_MS_HEAP_SIZE*sizeof(Eterm)) { mpsp->u.heap = (Eterm*) erts_alloc(ERTS_ALC_T_DB_MS_RUN_HEAP, heap_size); } else { ASSERT(mpsp->u.heap == mpsp->default_heap); } return mpsp; } static void destroy_match_pseudo_process(void) { ErtsMatchPseudoProcess *mpsp; mpsp = (ErtsMatchPseudoProcess *)erts_tsd_get(match_pseudo_process_key); if (mpsp) { cleanup_match_pseudo_process(mpsp, 0); erts_free(ERTS_ALC_T_DB_MS_PSDO_PROC, (void *) mpsp); erts_tsd_set(match_pseudo_process_key, (void *) NULL); } } static void match_pseudo_process_init(void) { erts_tsd_key_create(&match_pseudo_process_key, "erts_match_pseudo_process_key"); erts_thr_install_exit_handler(destroy_match_pseudo_process); } void erts_match_set_release_result(Process* c_p) { (void) get_match_pseudo_process(c_p, 0); /* Clean it up */ } /* The trace control word. */ static erts_atomic32_t trace_control_word; /* This needs to be here, before the bif table... */ static Eterm db_set_trace_control_word_fake_1(BIF_ALIST_1); static Eterm db_length_1(BIF_ALIST_1); /* ** The table of callable bif's, i e guard bif's and ** some special animals that can provide us with trace ** information. This array is sorted on init. */ static DMCGuardBif guard_tab[] = { { am_is_atom, &is_atom_1, 1, DBIF_ALL }, { am_is_float, &is_float_1, 1, DBIF_ALL }, { am_is_integer, &is_integer_1, 1, DBIF_ALL }, { am_is_list, &is_list_1, 1, DBIF_ALL }, { am_is_number, &is_number_1, 1, DBIF_ALL }, { am_is_pid, &is_pid_1, 1, DBIF_ALL }, { am_is_port, &is_port_1, 1, DBIF_ALL }, { am_is_reference, &is_reference_1, 1, DBIF_ALL }, { am_is_tuple, &is_tuple_1, 1, DBIF_ALL }, { am_is_map, &is_map_1, 1, DBIF_ALL }, { am_is_binary, &is_binary_1, 1, DBIF_ALL }, { am_is_bitstring, &is_bitstring_1, 1, DBIF_ALL }, { am_is_boolean, &is_boolean_1, 1, DBIF_ALL }, { am_is_function, &is_function_1, 1, DBIF_ALL }, { am_is_function, &is_function_2, 2, DBIF_ALL }, { am_is_record, &is_record_3, 3, DBIF_ALL }, { am_abs, &abs_1, 1, DBIF_ALL }, { am_element, &element_2, 2, DBIF_ALL }, { am_hd, &hd_1, 1, DBIF_ALL }, { am_length, &db_length_1, 1, DBIF_ALL }, { am_max, &max_2, 2, DBIF_ALL }, { am_min, &min_2, 2, DBIF_ALL }, { am_node, &node_1, 1, DBIF_ALL }, { am_node, &node_0, 0, DBIF_ALL }, { am_round, &round_1, 1, DBIF_ALL }, { am_size, &size_1, 1, DBIF_ALL }, { am_map_size, &map_size_1, 1, DBIF_ALL }, { am_map_get, &map_get_2, 2, DBIF_ALL }, { am_is_map_key, &is_map_key_2, 2, DBIF_ALL }, { am_bit_size, &bit_size_1, 1, DBIF_ALL }, { am_byte_size, &byte_size_1, 1, DBIF_ALL }, { am_tuple_size, &tuple_size_1, 1, DBIF_ALL }, { am_binary_part, &binary_part_2, 2, DBIF_ALL }, { am_binary_part, &binary_part_3, 3, DBIF_ALL }, { am_tl, &tl_1, 1, DBIF_ALL }, { am_trunc, &trunc_1, 1, DBIF_ALL }, { am_float, &float_1, 1, DBIF_ALL }, { am_ceil, &ceil_1, 1, DBIF_ALL }, { am_floor, &floor_1, 1, DBIF_ALL }, { am_Plus, &splus_1, 1, DBIF_ALL }, { am_Minus, &sminus_1, 1, DBIF_ALL }, { am_Plus, &splus_2, 2, DBIF_ALL }, { am_Minus, &sminus_2, 2, DBIF_ALL }, { am_Times, &stimes_2, 2, DBIF_ALL }, { am_Div, &div_2, 2, DBIF_ALL }, { am_div, &intdiv_2, 2, DBIF_ALL }, { am_rem, &rem_2, 2, DBIF_ALL }, { am_band, &band_2, 2, DBIF_ALL }, { am_bor, &bor_2, 2, DBIF_ALL }, { am_bxor, &bxor_2, 2, DBIF_ALL }, { am_bnot, &bnot_1, 1, DBIF_ALL }, { am_bsl, &bsl_2, 2, DBIF_ALL }, { am_bsr, &bsr_2, 2, DBIF_ALL }, { am_Gt, &sgt_2, 2, DBIF_ALL }, { am_Ge, &sge_2, 2, DBIF_ALL }, { am_Lt, &slt_2, 2, DBIF_ALL }, { am_Le, &sle_2, 2, DBIF_ALL }, { am_Eq, &seq_2, 2, DBIF_ALL }, { am_Eqeq, &seqeq_2, 2, DBIF_ALL }, { am_Neq, &sneq_2, 2, DBIF_ALL }, { am_Neqeq, &sneqeq_2, 2, DBIF_ALL }, { am_not, &not_1, 1, DBIF_ALL }, { am_xor, &xor_2, 2, DBIF_ALL }, { am_get_tcw, &db_get_trace_control_word_0, 0, DBIF_TRACE_GUARD | DBIF_TRACE_BODY }, { am_set_tcw, &db_set_trace_control_word_1, 1, DBIF_TRACE_BODY }, { am_set_tcw_fake, &db_set_trace_control_word_fake_1, 1, DBIF_TRACE_BODY } }; /* ** Exported */ Eterm db_am_eot; /* Atom '$end_of_table' */ /* ** Forward decl's */ /* ** ... forwards for compiled matches */ /* Utility code */ static DMCGuardBif *dmc_lookup_bif(Eterm t, int arity); #ifdef DMC_DEBUG static Eterm dmc_lookup_bif_reversed(void *f); #endif static int cmp_uint(void *a, void *b); static int cmp_guard_bif(void *a, void *b); static int match_compact(ErlHeapFragment *expr, DMCErrInfo *err_info); static Uint my_size_object(Eterm t, int is_hashmap_node); static Eterm my_copy_struct(Eterm t, Eterm **hp, ErlOffHeap* off_heap, int); /* Guard subroutines */ static void dmc_rearrange_constants(DMCContext *context, DMC_STACK_TYPE(UWord) *text, int textpos, Eterm *p, Uint nelems); static DMCRet dmc_array(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm *p, Uint nelems, int *constant); /* Guard compilation */ static void do_emit_constant(DMCContext *context, DMC_STACK_TYPE(UWord) *text, Eterm t); static DMCRet dmc_list(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant); static DMCRet dmc_tuple(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant); static DMCRet dmc_map(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant); static DMCRet dmc_variable(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant); static DMCRet dmc_fun(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant); static DMCRet dmc_expr(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant); static DMCRet compile_guard_expr(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t); /* match expression subroutines */ static DMCRet dmc_one_term(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(Eterm) *stack, DMC_STACK_TYPE(UWord) *text, Eterm c); static Eterm dmc_private_copy(DMCContext *context, Eterm c); #ifdef DMC_DEBUG static int test_disassemble_next = 0; void db_match_dis(Binary *prog); #define TRACE erts_fprintf(stderr,"Trace: %s:%d\n",__FILE__,__LINE__) #define FENCE_PATTERN_SIZE (1*sizeof(Uint)) #define FENCE_PATTERN 0xDEADBEEFUL #else #define TRACE /* Nothing */ #define FENCE_PATTERN_SIZE 0 #endif static void vadd_dmc_err(DMCErrInfo*, DMCErrorSeverity, int var, const char *str, ...); static Eterm dpm_array_to_list(Process *psp, Eterm *arr, int arity); static Eterm match_spec_test(Process *p, Eterm against, Eterm spec, int trace); static Eterm seq_trace_fake(Process *p, Eterm arg1); /* ** Interface routines. */ /* ** Pseudo BIF:s to be callable from the PAM VM. */ BIF_RETTYPE db_get_trace_control_word(Process *p) { Uint32 tcw = (Uint32) erts_atomic32_read_acqb(&trace_control_word); BIF_RET(erts_make_integer((Uint) tcw, p)); } BIF_RETTYPE db_get_trace_control_word_0(BIF_ALIST_0) { BIF_RET(db_get_trace_control_word(BIF_P)); } BIF_RETTYPE db_set_trace_control_word(Process *p, Eterm new) { Uint val; Uint32 old_tcw; if (!term_to_Uint(new, &val)) BIF_ERROR(p, BADARG); if (val != ((Uint32)val)) BIF_ERROR(p, BADARG); old_tcw = (Uint32) erts_atomic32_xchg_relb(&trace_control_word, (erts_aint32_t) val); BIF_RET(erts_make_integer((Uint) old_tcw, p)); } BIF_RETTYPE db_set_trace_control_word_1(BIF_ALIST_1) { BIF_RET(db_set_trace_control_word(BIF_P, BIF_ARG_1)); } /* * Implementation of length/1 for match specs (non-trapping). */ static Eterm db_length_1(BIF_ALIST_1) { Eterm list; Uint i; list = BIF_ARG_1; i = 0; while (is_list(list)) { i++; list = CDR(list_val(list)); } if (is_not_nil(list)) { BIF_ERROR(BIF_P, BADARG); } BIF_RET(make_small(i)); } static Eterm db_set_trace_control_word_fake_1(BIF_ALIST_1) { Process *p = BIF_P; Eterm new = BIF_ARG_1; Uint val; if (!term_to_Uint(new, &val)) BIF_ERROR(p, BADARG); if (val != ((Uint32)val)) BIF_ERROR(p, BADARG); BIF_RET(db_get_trace_control_word(p)); } /* ** The API used by the tracer (declared in global.h): */ /* ** Matchexpr is a list of tuples containing match-code, i e: ** ** Matchexpr = [{Pattern, Guards, Body}, ...] ** Pattern = [ PatternExpr , ...] ** PatternExpr = Constant | PatternTuple | PatternList | Variable ** Constant = Any erlang term ** PatternTuple = { PatternExpr ... } ** PatternList = [ PatternExpr ] ** Variable = '$' ++ <number> ** Guards = [Guard ...] ** Guard = {GuardFunc, GuardExpr, ...} ** GuardExpr = BoundVariable | Guard | GuardList | GuardTuple | ConstExpr ** BoundVariable = Variable (existing in Pattern) ** GuardList = [ GuardExpr , ... ] ** GuardTuple = {{ GuardExpr, ... }} ** ConstExpr = {const, Constant} ** GuardFunc = is_list | .... | element | ... ** Body = [ BodyExpr, ... ] ** BodyExpr = GuardExpr | { BodyFunc, GuardExpr, ... } ** BodyFunc = return_trace | seq_trace | trace | ... ** - or something like that... */ Eterm erts_match_set_get_source(Binary *mpsp) { MatchProg *prog = Binary2MatchProg(mpsp); return prog->saved_program; } /* This one is for the tracing */ Binary *erts_match_set_compile(Process *p, Eterm matchexpr, Eterm MFA, Uint *freasonp) { Binary *bin; Uint sz; Eterm *hp; Uint flags; switch (MFA) { case am_receive: flags = DCOMP_TRACE; break; case am_send: flags = DCOMP_TRACE | DCOMP_ALLOW_TRACE_OPS; break; default: flags = DCOMP_TRACE | DCOMP_CALL_TRACE | DCOMP_ALLOW_TRACE_OPS; } bin = db_match_set_compile(p, matchexpr, flags, freasonp); if (bin != NULL) { MatchProg *prog = Binary2MatchProg(bin); sz = size_object(matchexpr); prog->saved_program_buf = new_message_buffer(sz); hp = prog->saved_program_buf->mem; prog->saved_program = copy_struct(matchexpr, sz, &hp, &(prog->saved_program_buf->off_heap)); } return bin; } Binary *db_match_set_compile(Process *p, Eterm matchexpr, Uint flags, Uint *freasonp) { Eterm l; Eterm t; Eterm l2; Eterm *tp; Eterm *hp; int n = 0; int num_heads; int i; Binary *mps = NULL; int compiled = 0; Eterm *matches,*guards, *bodies; Eterm *buff; Eterm sbuff[15]; *freasonp = BADARG; if (!is_list(matchexpr)) return NULL; num_heads = 0; for (l = matchexpr; is_list(l); l = CDR(list_val(l))) ++num_heads; if (l != NIL) /* proper list... */ return NULL; if (num_heads > 5) { buff = erts_alloc(ERTS_ALC_T_DB_TMP, sizeof(Eterm) * num_heads * 3); } else { buff = sbuff; } matches = buff; guards = buff + num_heads; bodies = buff + (num_heads * 2); i = 0; for (l = matchexpr; is_list(l); l = CDR(list_val(l))) { t = CAR(list_val(l)); if (!is_tuple(t) || (tp = tuple_val(t))[0] != make_arityval(3)) { goto error; } if (!(flags & DCOMP_TRACE) || (!is_list(tp[1]) && !is_nil(tp[1]))) { t = tp[1]; } else { /* This is when tracing, the parameter is a list, that I convert to a tuple and that is matched against an array (strange, but gives the semantics of matching against a parameter list) */ n = 0; for (l2 = tp[1]; is_list(l2); l2 = CDR(list_val(l2))) { ++n; } if (l2 != NIL) { goto error; } if (n == 0) { t = ERTS_GLOBAL_LIT_EMPTY_TUPLE; } else { hp = HAlloc(p, n + 1); t = make_tuple(hp); *hp++ = make_arityval((Uint) n); l2 = tp[1]; while (n--) { *hp++ = CAR(list_val(l2)); l2 = CDR(list_val(l2)); } } } matches[i] = t; guards[i] = tp[2]; bodies[i] = tp[3]; ++i; } if ((mps = db_match_compile(matches, guards, bodies, num_heads, flags, NULL, freasonp)) == NULL) { goto error; } compiled = 1; if (buff != sbuff) { erts_free(ERTS_ALC_T_DB_TMP, buff); } return mps; error: if (compiled) { erts_bin_free(mps); } if (buff != sbuff) { erts_free(ERTS_ALC_T_DB_TMP, buff); } return NULL; } /* * Compare a matching term 'a' with a constructing term 'b' for equality. * * Returns true if 'b' is guaranteed to always construct * the same term as 'a' has matched. */ static int db_match_eq_body(Eterm a, Eterm b, int const_mode) { DECLARE_ESTACK(s); Uint arity; Eterm *ap, *bp; const Eterm CONST_MODE_OFF = THE_NON_VALUE; while (1) { switch(b & _TAG_PRIMARY_MASK) { case TAG_PRIMARY_LIST: if (!is_list(a)) return 0; ESTACK_PUSH2(s, CDR(list_val(a)), CDR(list_val(b))); a = CAR(list_val(a)); b = CAR(list_val(b)); continue; /* loop without pop */ case TAG_PRIMARY_BOXED: if (is_tuple(b)) { bp = tuple_val(b); if (!const_mode) { if (bp[0] == make_arityval(1) && is_tuple(bp[1])) { b = bp[1]; /* double-tuple syntax */ } else if (bp[0] == make_arityval(2) && bp[1] == am_const) { ESTACK_PUSH(s, CONST_MODE_OFF); const_mode = 1; /* {const, term()} syntax */ b = bp[2]; continue; /* loop without pop */ } else return 0; /* function call or invalid tuple syntax */ } if (!is_tuple(a)) return 0; ap = tuple_val(a); bp = tuple_val(b); if (ap[0] != bp[0]) return 0; arity = arityval(ap[0]); if (arity > 0) { a = *(++ap); b = *(++bp); while(--arity) { ESTACK_PUSH2(s, *(++ap), *(++bp)); } continue; /* loop without pop */ } } else if (is_map(b)) { /* We don't know what other pairs the matched map may contain */ return 0; } else if (!eq(a,b)) /* other boxed */ return 0; break; case TAG_PRIMARY_IMMED1: if (a != b || a == am_Underscore || a == am_DollarDollar || a == am_DollarUnderscore || (const_mode && db_is_variable(a) >= 0)) { return 0; } break; default: erts_exit(ERTS_ABORT_EXIT, "db_compare: " "Bad object on ESTACK: 0x%bex\n", b); } pop_next: if (ESTACK_ISEMPTY(s)) break; /* done */ b = ESTACK_POP(s); if (b == CONST_MODE_OFF) { ASSERT(const_mode); const_mode = 0; goto pop_next; } a = ESTACK_POP(s); } DESTROY_ESTACK(s); return 1; } /* This is used by select_replace */ int db_match_keeps_key(int keypos, Eterm match, Eterm guard, Eterm body) { Eterm match_key; Eterm* body_list; Eterm single_body_term; Eterm* single_body_term_tpl; Eterm single_body_subterm; Eterm single_body_subterm_key; Eterm* single_body_subterm_key_tpl; int const_mode; if (!is_list(body)) { return 0; } body_list = list_val(body); if (CDR(body_list) != NIL) { return 0; } single_body_term = CAR(body_list); if (single_body_term == am_DollarUnderscore) { /* same tuple is returned */ return 1; } if (!is_tuple(single_body_term)) { return 0; } match_key = db_getkey(keypos, match); if (!is_value(match_key)) { // can't get key out of match return 0; } single_body_term_tpl = tuple_val(single_body_term); if (single_body_term_tpl[0] == make_arityval(2) && single_body_term_tpl[1] == am_const) { /* {const, {"ets-tuple constant"}} */ single_body_subterm = single_body_term_tpl[2]; const_mode = 1; } else if (*single_body_term_tpl == make_arityval(1)) { /* {{"ets-tuple construction"}} */ single_body_subterm = single_body_term_tpl[1]; const_mode = 0; } else { /* not a tuple construction */ return 0; } single_body_subterm_key = db_getkey(keypos, single_body_subterm); if (!is_value(single_body_subterm_key)) { // can't get key out of single body subterm return 0; } if (db_match_eq_body(match_key, single_body_subterm_key, const_mode)) { /* tuple with same key is returned */ return 1; } if (const_mode) { /* constant key did not match */ return 0; } if (!is_tuple(single_body_subterm_key)) { /* can't possibly be an element instruction */ return 0; } single_body_subterm_key_tpl = tuple_val(single_body_subterm_key); if (single_body_subterm_key_tpl[0] == make_arityval(3) && single_body_subterm_key_tpl[1] == am_element && single_body_subterm_key_tpl[3] == am_DollarUnderscore && single_body_subterm_key_tpl[2] == make_small(keypos)) { /* {element, KeyPos, '$_'} */ return 1; } return 0; } static Eterm db_match_set_lint(Process *p, Eterm matchexpr, Uint flags) { Eterm l; Eterm t; Eterm l2; Eterm *tp; Eterm *hp; DMCErrInfo *err_info = db_new_dmc_err_info(); Eterm ret; int n = 0; int num_heads; Binary *mp; Eterm *matches,*guards, *bodies; Eterm sbuff[15]; Eterm *buff = sbuff; int i; Uint freason = BADARG; if (!is_list(matchexpr)) { add_dmc_err(err_info, "Match programs are not in a list.", -1, 0UL, dmcError); goto done; } num_heads = 0; for (l = matchexpr; is_list(l); l = CDR(list_val(l))) ++num_heads; if (l != NIL) { /* proper list... */ add_dmc_err(err_info, "Match programs are not in a proper list.", -1, 0UL, dmcError); goto done; } if (num_heads > 5) { buff = erts_alloc(ERTS_ALC_T_DB_TMP, sizeof(Eterm) * num_heads * 3); } matches = buff; guards = buff + num_heads; bodies = buff + (num_heads * 2); i = 0; for (l = matchexpr; is_list(l); l = CDR(list_val(l))) { t = CAR(list_val(l)); if (!is_tuple(t) || (tp = tuple_val(t))[0] != make_arityval(3)) { add_dmc_err(err_info, "Match program part is not a tuple of " "arity 3.", -1, 0UL, dmcError); goto done; } if (!(flags & DCOMP_TRACE) || (!is_list(tp[1]) && !is_nil(tp[1]))) { t = tp[1]; } else { n = 0; for (l2 = tp[1]; is_list(l2); l2 = CDR(list_val(l2))) { ++n; } if (l2 != NIL) { add_dmc_err(err_info, "Match expression part %T is not a " "proper list.", -1, tp[1], dmcError); goto done; } if (n == 0) { t = ERTS_GLOBAL_LIT_EMPTY_TUPLE; } else { hp = HAlloc(p, n + 1); t = make_tuple(hp); *hp++ = make_arityval((Uint) n); l2 = tp[1]; while (n--) { *hp++ = CAR(list_val(l2)); l2 = CDR(list_val(l2)); } } } matches[i] = t; guards[i] = tp[2]; bodies[i] = tp[3]; ++i; } mp = db_match_compile(matches, guards, bodies, num_heads, flags, err_info, &freason); if (mp != NULL) { erts_bin_free(mp); } done: ret = db_format_dmc_err_info(p, err_info); db_free_dmc_err_info(err_info); if (buff != sbuff) { erts_free(ERTS_ALC_T_DB_TMP, buff); } return ret; } /* Returns * am_false if no match or * if {message,false} has been called, * am_true if {message,_} has NOT been called or * if {message,true} has been called, * Msg if {message,Msg} has been called. * * If return value is_not_immed * then erts_match_set_release_result_trace() must be called to release it. */ Eterm erts_match_set_run_trace(Process *c_p, Process *self, Binary *mpsp, Eterm *args, int num_args, enum erts_pam_run_flags in_flags, Uint32 *return_flags) { Eterm ret; ret = db_prog_match(c_p, self, mpsp, NIL, args, num_args, in_flags, return_flags); ASSERT(!(is_non_value(ret) && *return_flags)); if (is_non_value(ret) || ret == am_false) { erts_match_set_release_result(c_p); return am_false; } if (is_immed(ret)) erts_match_set_release_result(c_p); return ret; } static Eterm erts_match_set_run_ets(Process *p, Binary *mpsp, Eterm args, int num_args, Uint32 *return_flags) { Eterm ret; ret = db_prog_match(p, p, mpsp, args, NULL, num_args, ERTS_PAM_COPY_RESULT, return_flags); #if defined(HARDDEBUG) if (is_non_value(ret)) { erts_fprintf(stderr, "Failed\n"); } else { erts_fprintf(stderr, "Returning : %T\n", ret); } #endif return ret; /* Returns * THE_NON_VALUE if no match * am_false if {message,false} has been called, * am_true if {message,_} has not been called or * if {message,true} has been called, * Msg if {message,Msg} has been called. */ } /* ** API Used by other erl_db modules. */ void db_initialize_util(void){ char c; qsort(guard_tab, sizeof(guard_tab) / sizeof(DMCGuardBif), sizeof(DMCGuardBif), (int (*)(const void *, const void *)) &cmp_guard_bif); match_pseudo_process_init(); erts_atomic32_init_nob(&trace_control_word, 0); if (erts_check_if_stack_grows_downwards(&c)) stack_guard = stack_guard_downwards; else stack_guard = stack_guard_upwards; } Eterm db_getkey(int keypos, Eterm obj) { if (is_tuple(obj)) { Eterm *tptr = tuple_val(obj); if (arityval(*tptr) >= keypos) return *(tptr + keypos); } return THE_NON_VALUE; } /* ** Matching compiled (executed by "Pam" :-) */ /* ** The actual compiling of the match expression and the guards */ Binary *db_match_compile(Eterm *matchexpr, Eterm *guards, Eterm *body, int num_progs, Uint flags, DMCErrInfo *err_info, Uint *freasonp) { DMCHeap heap; DMC_STACK_TYPE(Eterm) stack; DMC_STACK_TYPE(UWord) text; DMCContext context; MatchProg *ret = NULL; Eterm t; Uint i; Uint num_iters; int structure_checked; DMCRet res; int current_try_label; Binary *bp = NULL; unsigned clause_start; context.stack_limit = (char *) erts_get_stacklimit(); context.freason = BADARG; DMC_INIT_STACK(stack); DMC_INIT_STACK(text); context.stack_need = context.stack_used = 0; context.save = context.copy = NULL; context.num_match = num_progs; context.matchexpr = matchexpr; context.guardexpr = guards; context.bodyexpr = body; context.err_info = err_info; context.cflags = flags; heap.size = DMC_DEFAULT_SIZE; heap.vars = heap.vars_def; /* ** Compile the match expression */ restart: heap.vars_used = 0; for (context.current_match = 0; context.current_match < num_progs; ++context.current_match) { /* This loop is long, too long */ sys_memset(heap.vars, 0, heap.size * sizeof(*heap.vars)); t = context.matchexpr[context.current_match]; context.stack_used = 0; structure_checked = 0; if (context.current_match < num_progs - 1) { DMC_PUSH(text,matchTryMeElse); current_try_label = DMC_STACK_NUM(text); DMC_PUSH(text,0); } else { current_try_label = -1; } clause_start = DMC_STACK_NUM(text); /* the "special" test needs it */ DMC_PUSH(stack,NIL); for (;;) { switch (t & _TAG_PRIMARY_MASK) { case TAG_PRIMARY_BOXED: if (is_flatmap(t)) { num_iters = flatmap_get_size(flatmap_val(t)); if (!structure_checked) { DMC_PUSH2(text, matchMap, num_iters); } structure_checked = 0; for (i = 0; i < num_iters; ++i) { Eterm key = flatmap_get_keys(flatmap_val(t))[i]; if (db_is_variable(key) >= 0) { if (context.err_info) { add_dmc_err(context.err_info, "Variable found in map key.", -1, 0UL, dmcError); } goto error; } else if (key == am_Underscore) { if (context.err_info) { add_dmc_err(context.err_info, "Underscore found in map key.", -1, 0UL, dmcError); } goto error; } DMC_PUSH2(text, matchKey, dmc_private_copy(&context, key)); { int old_stack = ++(context.stack_used); Eterm value = flatmap_get_values(flatmap_val(t))[i]; res = dmc_one_term(&context, &heap, &stack, &text, value); ASSERT(res != retFail); if (res == retRestart) { goto restart; } if (old_stack != context.stack_used) { ASSERT(old_stack + 1 == context.stack_used); DMC_PUSH(text, matchSwap); } if (context.stack_used > context.stack_need) { context.stack_need = context.stack_used; } DMC_PUSH(text, matchPop); --(context.stack_used); } } break; } if (is_hashmap(t)) { DECLARE_WSTACK(wstack); Eterm *kv; num_iters = hashmap_size(t); if (!structure_checked) { DMC_PUSH2(text, matchMap, num_iters); } structure_checked = 0; hashmap_iterator_init(&wstack, t, 0); while ((kv=hashmap_iterator_next(&wstack)) != NULL) { Eterm key = CAR(kv); Eterm value = CDR(kv); if (db_is_variable(key) >= 0) { if (context.err_info) { add_dmc_err(context.err_info, "Variable found in map key.", -1, 0UL, dmcError); } DESTROY_WSTACK(wstack); goto error; } else if (key == am_Underscore) { if (context.err_info) { add_dmc_err(context.err_info, "Underscore found in map key.", -1, 0UL, dmcError); } DESTROY_WSTACK(wstack); goto error; } DMC_PUSH2(text, matchKey, dmc_private_copy(&context, key)); { int old_stack = ++(context.stack_used); res = dmc_one_term(&context, &heap, &stack, &text, value); ASSERT(res != retFail); if (res == retRestart) { DESTROY_WSTACK(wstack); goto restart; } if (old_stack != context.stack_used) { ASSERT(old_stack + 1 == context.stack_used); DMC_PUSH(text, matchSwap); } if (context.stack_used > context.stack_need) { context.stack_need = context.stack_used; } DMC_PUSH(text, matchPop); --(context.stack_used); } } DESTROY_WSTACK(wstack); break; } if (!is_tuple(t)) { goto simple_term; } num_iters = arityval(*tuple_val(t)); if (!structure_checked) { /* i.e. we did not pop it */ DMC_PUSH2(text, matchTuple, num_iters); } structure_checked = 0; for (i = 1; i <= num_iters; ++i) { if ((res = dmc_one_term(&context, &heap, &stack, &text, tuple_val(t)[i])) != retOk) { if (res == retRestart) { goto restart; /* restart the surrounding loop */ } else goto error; } } break; case TAG_PRIMARY_LIST: if (!structure_checked) { DMC_PUSH(text, matchList); } structure_checked = 0; /* Whatever it is, we did not pop it */ if ((res = dmc_one_term(&context, &heap, &stack, &text, CAR(list_val(t)))) != retOk) { if (res == retRestart) { goto restart; } else goto error; } t = CDR(list_val(t)); continue; default: /* Nil and non proper tail end's or single terms as match expressions */ simple_term: structure_checked = 0; if ((res = dmc_one_term(&context, &heap, &stack, &text, t)) != retOk) { if (res == retRestart) { goto restart; } else goto error; } break; } /* The *program's* stack just *grows* while we are traversing one composite data structure, we can check the stack usage here */ if (context.stack_used > context.stack_need) context.stack_need = context.stack_used; /* We are at the end of one composite data structure, pop sub structures and emit a matchPop instruction (or break) */ if ((t = DMC_POP(stack)) == NIL) { break; } else { DMC_PUSH(text, matchPop); structure_checked = 1; /* * Checked with matchPushT * or matchPushL */ --(context.stack_used); } } /* ** There is one single top variable in the match expression ** iff the text is two Uint's and the single instruction ** is 'matchBind' or it is only a skip. */ context.special = (DMC_STACK_NUM(text) == 2 + clause_start && DMC_PEEK(text,clause_start) == matchBind) || (DMC_STACK_NUM(text) == 1 + clause_start && DMC_PEEK(text, clause_start) == matchSkip); if (flags & DCOMP_TRACE) { if (context.special) { if (DMC_PEEK(text, clause_start) == matchBind) { DMC_POKE(text, clause_start, matchArrayBind); } } else { ASSERT(DMC_STACK_NUM(text) >= 1); if (DMC_PEEK(text, clause_start) != matchTuple) { /* If it isn't "special" and the argument is not a tuple, the expression is not valid when matching an array*/ if (context.err_info) { add_dmc_err(context.err_info, "Match head is invalid in " "this context.", -1, 0UL, dmcError); } goto error; } DMC_POKE(text, clause_start, matchArray); } } /* ** ... and the guards */ context.is_guard = 1; if (compile_guard_expr (&context, &heap, &text, context.guardexpr[context.current_match]) != retOk) goto error; context.is_guard = 0; if ((context.cflags & DCOMP_TABLE) && !is_list(context.bodyexpr[context.current_match])) { if (context.err_info) { add_dmc_err(context.err_info, "Body clause does not return " "anything.", -1, 0UL, dmcError); } goto error; } if (compile_guard_expr (&context, &heap, &text, context.bodyexpr[context.current_match]) != retOk) goto error; /* * The compilation does not bail out when error information * is requested, so we need to detect that here... */ if (context.err_info != NULL && (context.err_info)->error_added) { goto error; } /* If the matchprogram comes here, the match is successful */ DMC_PUSH(text,matchHalt); /* Fill in try-me-else label if there is one. */ if (current_try_label >= 0) { DMC_POKE(text, current_try_label, DMC_STACK_NUM(text)); } } /* for (context.current_match = 0 ...) */ /* ** Done compiling ** Allocate enough space for the program, ** heap size is in 'heap_used', stack size is in 'stack_need' ** and text size is simply DMC_STACK_NUM(text). ** The "program memory" is allocated like this: ** text ----> +-------------+ ** | | ** .......... ** +-------------+ ** ** The heap-eheap-stack block of a MatchProg is nowadays allocated ** when the match program is run (see db_prog_match()). ** ** heap ----> +-------------+ ** .......... ** eheap ---> + + ** .......... ** stack ---> + + ** .......... ** +-------------+ ** The stack is expected to grow towards *higher* addresses. ** A special case is when the match expression is a single binding ** (i.e '$1'). */ bp = erts_create_magic_binary(((sizeof(MatchProg) - sizeof(UWord)) + (DMC_STACK_NUM(text) * sizeof(UWord))), erts_db_match_prog_destructor); ret = Binary2MatchProg(bp); ret->saved_program_buf = NULL; ret->saved_program = NIL; ret->term_save = context.save; ret->num_bindings = heap.vars_used; sys_memcpy(ret->text, DMC_STACK_DATA(text), DMC_STACK_NUM(text) * sizeof(UWord)); ret->stack_offset = heap.vars_used*sizeof(MatchVariable) + FENCE_PATTERN_SIZE; ret->heap_size = ret->stack_offset + context.stack_need * sizeof(Eterm*) + FENCE_PATTERN_SIZE; #ifdef DMC_DEBUG ret->prog_end = ret->text + DMC_STACK_NUM(text); #endif /* * Fall through to cleanup code, but context.save should not be free'd */ context.save = NULL; error: /* Here is were we land when compilation failed. */ if (context.save != NULL) { free_message_buffer(context.save); context.save = NULL; } DMC_FREE(stack); DMC_FREE(text); if (context.copy != NULL) free_message_buffer(context.copy); if (heap.vars != heap.vars_def) erts_free(ERTS_ALC_T_DB_MS_CMPL_HEAP, (void *) heap.vars); *freasonp = context.freason; return bp; } /* ** Free a match program (in a binary) */ int erts_db_match_prog_destructor(Binary *bprog) { MatchProg *prog; if (bprog == NULL) return 1; prog = Binary2MatchProg(bprog); if (prog->term_save != NULL) { free_message_buffer(prog->term_save); } if (prog->saved_program_buf != NULL) free_message_buffer(prog->saved_program_buf); return 1; } void erts_match_prog_foreach_offheap(Binary *bprog, void (*func)(ErlOffHeap *, void *), void *arg) { MatchProg *prog; ErlHeapFragment *tmp; if (bprog == NULL) return; prog = Binary2MatchProg(bprog); tmp = prog->term_save; while (tmp) { (*func)(&(tmp->off_heap), arg); tmp = tmp->next; } if (prog->saved_program_buf) (*func)(&(prog->saved_program_buf->off_heap), arg); } /* ** This is not the most efficient way to do it, but it's a rare ** and not especially nice case when this is used. */ static Eterm dpm_array_to_list(Process *psp, Eterm *arr, int arity) { Eterm *hp = HAllocX(psp, arity * 2, HEAP_XTRA); Eterm ret = NIL; while (--arity >= 0) { ret = CONS(hp, arr[arity], ret); hp += 2; } return ret; } /* ** Execution of the match program, this is Pam. ** May return THE_NON_VALUE, which is a bailout. ** the parameter 'arity' is only used if 'term' is actually an array, ** i.e. 'DCOMP_TRACE' was specified */ Eterm db_prog_match(Process *c_p, Process *self, Binary *bprog, Eterm term, Eterm *termp, int arity, enum erts_pam_run_flags in_flags, Uint32 *return_flags) { MatchProg *prog = Binary2MatchProg(bprog); const Eterm *ep, *tp, **sp; Eterm t; Eterm *esp; MatchVariable* variables; const ErtsCodeMFA *cp; FunctionInfo fi; const UWord *pc = prog->text; Eterm *ehp; Eterm ret; Uint n; int i; unsigned do_catch; ErtsMatchPseudoProcess *mpsp; Process *psp; Process* build_proc; Process *tmpp; Process *current_scheduled; ErtsSchedulerData *esdp; BIF_RETTYPE (*bif)(BIF_ALIST); Eterm bif_args[3]; int fail_label; #ifdef DEBUG Eterm *orig_esp; #endif #ifdef DMC_DEBUG Uint *heap_fence; Uint *stack_fence; Uint save_op; #endif /* DMC_DEBUG */ ERTS_UNDEF(n,0); ERTS_UNDEF(current_scheduled,NULL); ASSERT(c_p || !(in_flags & ERTS_PAM_COPY_RESULT)); mpsp = get_match_pseudo_process(c_p, prog->heap_size); psp = &mpsp->process; /* We need to lure the scheduler into believing in the pseudo process, because of floating point exceptions. Do *after* mpsp is set!!! */ esdp = erts_get_scheduler_data(); if (esdp) current_scheduled = esdp->current_process; /* SMP: psp->scheduler_data is set by get_match_pseudo_process */ #ifdef DMC_DEBUG save_op = 0; heap_fence = (Eterm*)((char*) mpsp->u.heap + prog->stack_offset) - 1; stack_fence = (Eterm*)((char*) mpsp->u.heap + prog->heap_size) - 1; *heap_fence = FENCE_PATTERN; *stack_fence = FENCE_PATTERN; #endif /* DMC_DEBUG */ #ifdef HARDDEBUG #define FAIL() {erts_printf("Fail line %d\n",__LINE__); goto fail;} #else #define FAIL() goto fail #endif #define FAIL_TERM am_EXIT /* The term to set as return when bif fails and do_catch != 0 */ *return_flags = 0U; variables = mpsp->u.variables; restart: ep = &term; esp = (Eterm*)((char*)mpsp->u.heap + prog->stack_offset); sp = (const Eterm **)esp; ret = am_true; do_catch = 0; fail_label = -1; build_proc = psp; if (esdp) esdp->current_process = psp; #ifdef DEBUG orig_esp = esp; ASSERT(variables == mpsp->u.variables); for (i=0; i<prog->num_bindings; i++) { variables[i].term = THE_NON_VALUE; variables[i].proc = NULL; } #endif for (;;) { #ifdef DMC_DEBUG if (*heap_fence != FENCE_PATTERN) { erts_exit(ERTS_ABORT_EXIT, "Heap fence overwritten in db_prog_match after op " "0x%08x, overwritten with 0x%08x.", save_op, *heap_fence); } if (*stack_fence != FENCE_PATTERN) { erts_exit(ERTS_ABORT_EXIT, "Stack fence overwritten in db_prog_match after op " "0x%08x, overwritten with 0x%08x.", save_op, *stack_fence); } save_op = *pc; #endif switch (*pc++) { case matchTryMeElse: ASSERT(fail_label == -1); fail_label = *pc++; break; case matchArray: /* only when DCOMP_TRACE, is always first instruction. */ n = *pc++; if ((int) n != arity) FAIL(); ep = termp; break; case matchArrayBind: /* When the array size is unknown. */ ASSERT(termp || arity==0); n = *pc++; variables[n].term = dpm_array_to_list(psp, termp, arity); break; case matchTuple: /* *ep is a tuple of arity n */ if (!is_tuple(*ep)) FAIL(); ep = tuple_val(*ep); n = *pc++; if (arityval(*ep) != n) FAIL(); ++ep; break; case matchPushT: /* *ep is a tuple of arity n, push ptr to first element */ if (!is_tuple(*ep)) FAIL(); tp = tuple_val(*ep); n = *pc++; if (arityval(*tp) != n) FAIL(); *sp++ = tp + 1; ++ep; break; case matchList: if (!is_list(*ep)) FAIL(); ep = list_val(*ep); break; case matchPushL: if (!is_list(*ep)) FAIL(); *sp++ = list_val(*ep); ++ep; break; case matchMap: if (!is_map(*ep)) { FAIL(); } n = *pc++; if (is_flatmap(*ep)) { if (flatmap_get_size(flatmap_val(*ep)) < n) { FAIL(); } } else { ASSERT(is_hashmap(*ep)); if (hashmap_size(*ep) < n) { FAIL(); } } ep = flatmap_val(*ep); break; case matchPushM: if (!is_map(*ep)) { FAIL(); } n = *pc++; if (is_flatmap(*ep)) { if (flatmap_get_size(flatmap_val(*ep)) < n) { FAIL(); } } else { ASSERT(is_hashmap(*ep)); if (hashmap_size(*ep) < n) { FAIL(); } } *sp++ = flatmap_val(*ep++); break; case matchKey: t = (Eterm) *pc++; tp = erts_maps_get(t, make_boxed(ep)); if (!tp) { FAIL(); } *sp++ = ep; ep = tp; break; case matchPop: ep = *(--sp); break; case matchSwap: tp = sp[-1]; sp[-1] = sp[-2]; sp[-2] = tp; break; case matchBind: n = *pc++; variables[n].term = *ep++; break; case matchCmp: n = *pc++; if (!EQ(variables[n].term, *ep)) FAIL(); ++ep; break; case matchEqBin: t = (Eterm) *pc++; if (!EQ(t,*ep)) FAIL(); ++ep; break; case matchEqFloat: if (!is_float(*ep)) FAIL(); if (sys_memcmp(float_val(*ep) + 1, pc, sizeof(double))) FAIL(); pc += sizeof(double) / sizeof(*pc); ++ep; break; case matchEqRef: { Eterm* epc = (Eterm*)pc; if (!is_ref(*ep)) FAIL(); if (!EQ(make_internal_ref(epc), *ep)) { FAIL(); } i = thing_arityval(*epc); pc += i+1; ++ep; break; } case matchEqBig: if (!is_big(*ep)) FAIL(); tp = big_val(*ep); { Eterm *epc = (Eterm *) pc; if (*tp != *epc) FAIL(); i = BIG_ARITY(epc); pc += i+1; while(i--) { if (*++tp != *++epc) { FAIL(); } } } ++ep; break; case matchEq: t = (Eterm) *pc++; ASSERT(is_immed(t)); if (t != *ep++) FAIL(); break; case matchSkip: ++ep; break; /* * Here comes guard & body instructions */ case matchPushC: /* Push constant */ if ((in_flags & ERTS_PAM_COPY_RESULT) && do_catch && !is_immed(*pc)) { *esp++ = copy_object(*pc++, c_p); } else { *esp++ = *pc++; } break; case matchConsA: ehp = HAllocX(build_proc, 2, HEAP_XTRA); CDR(ehp) = *--esp; CAR(ehp) = esp[-1]; esp[-1] = make_list(ehp); break; case matchConsB: ehp = HAllocX(build_proc, 2, HEAP_XTRA); CAR(ehp) = *--esp; CDR(ehp) = esp[-1]; esp[-1] = make_list(ehp); break; case matchMkTuple: n = *pc++; if (n == 0) { t = ERTS_GLOBAL_LIT_EMPTY_TUPLE; *esp++ = t; } else { ehp = HAllocX(build_proc, n+1, HEAP_XTRA); t = make_tuple(ehp); *ehp++ = make_arityval(n); while (n--) { *ehp++ = *--esp; } *esp++ = t; } break; case matchMkFlatMap: n = *pc++; ehp = HAllocX(build_proc, MAP_HEADER_FLATMAP_SZ + n, HEAP_XTRA); t = *--esp; { flatmap_t *m = (flatmap_t *)ehp; m->thing_word = MAP_HEADER_FLATMAP; m->size = n; m->keys = t; } t = make_flatmap(ehp); ehp += MAP_HEADER_FLATMAP_SZ; while (n--) { *ehp++ = *--esp; } erts_usort_flatmap((flatmap_t*)flatmap_val(t)); *esp++ = t; break; case matchMkHashMap: n = *pc++; esp -= 2*n; ehp = HAllocX(build_proc, 2*n, HEAP_XTRA); { ErtsHeapFactory factory; Uint ix; for (ix = 0; ix < 2*n; ix++){ ehp[ix] = esp[ix]; } erts_factory_proc_init(&factory, build_proc); t = erts_hashmap_from_array(&factory, ehp, n, 0); erts_factory_close(&factory); /* There were duplicate keys in hashmap so we may have to recreate the hashmap as a flatmap */ if (hashmap_size(t) <= MAP_SMALL_MAP_LIMIT) { DECLARE_WSTACK(wstack); Eterm *kv; Eterm *ks; Eterm *vs; flatmap_t *mp; Eterm keys, *hp; Uint n = hashmap_size(t); erts_factory_proc_init(&factory, build_proc); /* build flat structure */ hp = erts_produce_heap(&factory, 3 + (n==0 ? 0 : 1) + (2 * n), 0); if (n == 0) { keys = ERTS_GLOBAL_LIT_EMPTY_TUPLE; } else { keys = make_tuple(hp); *hp++ = make_arityval(n); } ks = hp; hp += n; mp = (flatmap_t*)hp; hp += MAP_HEADER_FLATMAP_SZ; vs = hp; mp->thing_word = MAP_HEADER_FLATMAP; mp->size = n; mp->keys = keys; hashmap_iterator_init(&wstack, t, 0); while ((kv=hashmap_iterator_next(&wstack)) != NULL) { ASSERT(n != 0); *ks++ = CAR(kv); *vs++ = CDR(kv); } /* it cannot have multiple keys */ erts_validate_and_sort_flatmap(mp); t = make_flatmap(mp); DESTROY_WSTACK(wstack); erts_factory_close(&factory); } } *esp++ = t; break; case matchCall0: bif = (BIF_RETTYPE (*)(BIF_ALIST)) *pc++; t = (*bif)(build_proc, bif_args, NULL); if (is_non_value(t)) { if (do_catch) t = FAIL_TERM; else FAIL(); } *esp++ = t; break; case matchCall1: bif = (BIF_RETTYPE (*)(BIF_ALIST)) *pc++; t = (*bif)(build_proc, esp-1, NULL); if (is_non_value(t)) { if (do_catch) t = FAIL_TERM; else FAIL(); } esp[-1] = t; break; case matchCall2: bif = (BIF_RETTYPE (*)(BIF_ALIST)) *pc++; bif_args[0] = esp[-1]; bif_args[1] = esp[-2]; t = (*bif)(build_proc, bif_args, NULL); if (is_non_value(t)) { if (do_catch) t = FAIL_TERM; else FAIL(); } --esp; esp[-1] = t; break; case matchCall3: bif = (BIF_RETTYPE (*)(BIF_ALIST)) *pc++; bif_args[0] = esp[-1]; bif_args[1] = esp[-2]; bif_args[2] = esp[-3]; t = (*bif)(build_proc, bif_args, NULL); if (is_non_value(t)) { if (do_catch) t = FAIL_TERM; else FAIL(); } esp -= 2; esp[-1] = t; break; case matchPushVResult: if (!(in_flags & ERTS_PAM_COPY_RESULT)) goto case_matchPushV; /* Build copy on callers heap */ n = *pc++; ASSERT(is_value(variables[n].term)); ASSERT(!variables[n].proc); variables[n].term = copy_object_x(variables[n].term, c_p, HEAP_XTRA); *esp++ = variables[n].term; #ifdef DEBUG variables[n].proc = c_p; #endif break; case matchPushV: case_matchPushV: n = *pc++; ASSERT(is_value(variables[n].term)); *esp++ = variables[n].term; break; case matchPushExpr: if (in_flags & ERTS_PAM_COPY_RESULT) { Uint sz; Eterm* top; sz = size_object(term); top = HAllocX(build_proc, sz, HEAP_XTRA); if (in_flags & ERTS_PAM_CONTIGUOUS_TUPLE) { ASSERT(is_tuple(term)); *esp++ = make_tuple(copy_shallow(tuple_val(term), sz, &top, &MSO(build_proc))); } else { *esp++ = copy_struct(term, sz, &top, &MSO(build_proc)); } } else { *esp++ = term; } break; case matchPushArrayAsList: n = arity; /* Only happens when 'term' is an array */ tp = termp; ehp = HAllocX(build_proc, n*2, HEAP_XTRA); *esp++ = make_list(ehp); while (n--) { *ehp++ = *tp++; *ehp = make_list(ehp + 1); ehp++; /* As pointed out by Mikael Pettersson the expression (*ehp++ = make_list(ehp + 1)) that I previously had written here has undefined behaviour. */ } ehp[-1] = NIL; break; case matchPushArrayAsListU: /* This instruction is NOT efficient. */ *esp++ = dpm_array_to_list(build_proc, termp, arity); break; case matchTrue: if (*--esp != am_true) FAIL(); break; case matchOr: n = *pc++; t = am_false; while (n--) { if (*--esp == am_true) { t = am_true; } else if (*esp != am_false) { esp -= n; if (do_catch) { t = FAIL_TERM; break; } else { FAIL(); } } } *esp++ = t; break; case matchAnd: n = *pc++; t = am_true; while (n--) { if (*--esp == am_false) { t = am_false; } else if (*esp != am_true) { esp -= n; if (do_catch) { t = FAIL_TERM; break; } else { FAIL(); } } } *esp++ = t; break; case matchOrElse: n = *pc++; if (*--esp == am_true) { ++esp; pc += n; } else if (*esp != am_false) { if (do_catch) { *esp++ = FAIL_TERM; pc += n; } else { FAIL(); } } break; case matchAndAlso: n = *pc++; if (*--esp == am_false) { esp++; pc += n; } else if (*esp != am_true) { if (do_catch) { *esp++ = FAIL_TERM; pc += n; } else { FAIL(); } } break; case matchJump: n = *pc++; pc += n; break; case matchSelf: *esp++ = self->common.id; break; case matchWaste: --esp; break; case matchReturn: ret = *--esp; break; case matchProcessDump: { erts_dsprintf_buf_t *dsbufp = erts_create_tmp_dsbuf(0); ASSERT(c_p == self); print_process_info(ERTS_PRINT_DSBUF, (void *) dsbufp, c_p, ERTS_PROC_LOCK_MAIN); *esp++ = new_binary(build_proc, (byte *)dsbufp->str, dsbufp->str_len); erts_destroy_tmp_dsbuf(dsbufp); break; } case matchDisplay: /* Debugging, not for production! */ erts_printf("%T\n", esp[-1]); esp[-1] = am_true; break; case matchSetReturnTrace: *return_flags |= MATCH_SET_RETURN_TRACE; *esp++ = am_true; break; case matchSetExceptionTrace: *return_flags |= MATCH_SET_EXCEPTION_TRACE; *esp++ = am_true; break; case matchIsSeqTrace: ASSERT(c_p == self); if (have_seqtrace(SEQ_TRACE_TOKEN(c_p))) *esp++ = am_true; else *esp++ = am_false; break; case matchSetSeqToken: ASSERT(c_p == self); t = erts_seq_trace(c_p, esp[-1], esp[-2], 0); if (is_non_value(t)) { esp[-2] = FAIL_TERM; } else { esp[-2] = t; } --esp; break; case matchSetSeqTokenFake: ASSERT(c_p == self); t = seq_trace_fake(c_p, esp[-1]); if (is_non_value(t)) { esp[-2] = FAIL_TERM; } else { esp[-2] = t; } --esp; break; case matchGetSeqToken: ASSERT(c_p == self); if (have_no_seqtrace(SEQ_TRACE_TOKEN(c_p))) *esp++ = NIL; else { Eterm token; Uint token_sz; ASSERT(SEQ_TRACE_TOKEN_ARITY(c_p) == 5); ASSERT(is_immed(SEQ_TRACE_TOKEN_FLAGS(c_p))); ASSERT(is_immed(SEQ_TRACE_TOKEN_SERIAL(c_p))); ASSERT(is_immed(SEQ_TRACE_TOKEN_LASTCNT(c_p))); token = SEQ_TRACE_TOKEN(c_p); token_sz = size_object(token); ehp = HAllocX(build_proc, token_sz, HEAP_XTRA); *esp++ = copy_struct(token, token_sz, &ehp, &MSO(build_proc)); } break; case matchEnableTrace: ASSERT(c_p == self); if ( (n = erts_trace_flag2bit(esp[-1]))) { erts_proc_lock(c_p, ERTS_PROC_LOCKS_ALL_MINOR); set_tracee_flags(c_p, ERTS_TRACER(c_p), 0, n); erts_proc_unlock(c_p, ERTS_PROC_LOCKS_ALL_MINOR); esp[-1] = am_true; } else { esp[-1] = FAIL_TERM; } break; case matchEnableTrace2: ASSERT(c_p == self); n = erts_trace_flag2bit((--esp)[-1]); esp[-1] = FAIL_TERM; if (n) { if ( (tmpp = get_proc(c_p, ERTS_PROC_LOCK_MAIN, esp[0], ERTS_PROC_LOCKS_ALL))) { /* Always take over the tracer of the current process */ set_tracee_flags(tmpp, ERTS_TRACER(c_p), 0, n); if (tmpp == c_p) erts_proc_unlock(tmpp, ERTS_PROC_LOCKS_ALL_MINOR); else erts_proc_unlock(tmpp, ERTS_PROC_LOCKS_ALL); esp[-1] = am_true; } } break; case matchDisableTrace: ASSERT(c_p == self); if ( (n = erts_trace_flag2bit(esp[-1]))) { erts_proc_lock(c_p, ERTS_PROC_LOCKS_ALL_MINOR); set_tracee_flags(c_p, ERTS_TRACER(c_p), n, 0); erts_proc_unlock(c_p, ERTS_PROC_LOCKS_ALL_MINOR); esp[-1] = am_true; } else { esp[-1] = FAIL_TERM; } break; case matchDisableTrace2: ASSERT(c_p == self); n = erts_trace_flag2bit((--esp)[-1]); esp[-1] = FAIL_TERM; if (n) { if ( (tmpp = get_proc(c_p, ERTS_PROC_LOCK_MAIN, esp[0], ERTS_PROC_LOCKS_ALL))) { /* Always take over the tracer of the current process */ set_tracee_flags(tmpp, ERTS_TRACER(c_p), n, 0); if (tmpp == c_p) erts_proc_unlock(tmpp, ERTS_PROC_LOCKS_ALL_MINOR); else erts_proc_unlock(tmpp, ERTS_PROC_LOCKS_ALL); esp[-1] = am_true; } } break; case matchCaller: ASSERT(c_p == self); /* Note that we can't use `erts_inspect_frame` here as the top of * the stack could point at something other than a frame. */ if (erts_frame_layout == ERTS_FRAME_LAYOUT_RA) { t = c_p->stop[0]; } else { ASSERT(erts_frame_layout == ERTS_FRAME_LAYOUT_FP_RA); t = c_p->stop[1]; } if (is_not_CP(t)) { *esp++ = am_undefined; } else if (!(cp = erts_find_function_from_pc(cp_val(t)))) { *esp++ = am_undefined; } else { ehp = HAllocX(build_proc, 4, HEAP_XTRA); *esp++ = make_tuple(ehp); ehp[0] = make_arityval(3); ehp[1] = cp->module; ehp[2] = cp->function; ehp[3] = make_small((Uint) cp->arity); } break; case matchCallerLine: ASSERT(c_p == self); /* Note that we can't use `erts_inspect_frame` here as the top of * the stack could point at something other than a frame. */ if (erts_frame_layout == ERTS_FRAME_LAYOUT_RA) { t = c_p->stop[0]; } else { ASSERT(erts_frame_layout == ERTS_FRAME_LAYOUT_FP_RA); t = c_p->stop[1]; } if (is_not_CP(t)) { *esp++ = am_undefined; break; } erts_lookup_function_info(&fi, cp_val(t), 1); if (!fi.mfa) { *esp++ = am_undefined; } else { if (fi.loc == LINE_INVALID_LOCATION) { ehp = HAllocX(build_proc, 5, HEAP_XTRA); } else { ehp = HAllocX(build_proc, 8, HEAP_XTRA); } *esp++ = make_tuple(ehp); ehp[0] = make_arityval(4); ehp[1] = fi.mfa->module; ehp[2] = fi.mfa->function; ehp[3] = make_small((Uint) fi.mfa->arity); if (fi.loc == LINE_INVALID_LOCATION) { ehp[4] = am_undefined; } else { ehp[4] = make_tuple(&ehp[5]); ehp[5] = make_arityval(2); ehp[6] = fi.fname_ptr[LOC_FILE(fi.loc)]; ehp[7] = make_small(LOC_LINE(fi.loc)); } } break; case matchCurrentStacktrace: { Uint sz; Uint heap_size; Eterm mfa; Eterm res; struct StackTrace *s; int depth; FunctionInfo* stk; FunctionInfo* stkp; ASSERT(c_p == self); depth = unsigned_val(esp[-1]); esp--; sz = offsetof(struct StackTrace, trace) + sizeof(ErtsCodePtr) * depth; s = (struct StackTrace *) erts_alloc(ERTS_ALC_T_TMP, sz); s->depth = 0; s->pc = NULL; erts_save_stacktrace(c_p, s, depth); depth = s->depth; stk = stkp = (FunctionInfo *) erts_alloc(ERTS_ALC_T_TMP, depth*sizeof(FunctionInfo)); heap_size = 0; for (i = 0; i < depth; i++) { erts_lookup_function_info(stkp, s->trace[i], 1); if (stkp->mfa) { heap_size += stkp->needed + 2; stkp++; } } res = NIL; if (heap_size > 0) { int count = stkp - stk; ASSERT(count > 0 && count <= MAX_BACKTRACE_SIZE); ehp = HAllocX(build_proc, heap_size, HEAP_XTRA); for (i = count - 1; i >= 0; i--) { ehp = erts_build_mfa_item(&stk[i], ehp, am_true, &mfa, NIL); res = CONS(ehp, mfa, res); ehp += 2; } } *esp++ = res; erts_free(ERTS_ALC_T_TMP, stk); erts_free(ERTS_ALC_T_TMP, s); break; } case matchSilent: ASSERT(c_p == self); --esp; if (in_flags & ERTS_PAM_IGNORE_TRACE_SILENT) break; if (*esp == am_true) { erts_proc_lock(c_p, ERTS_PROC_LOCKS_ALL_MINOR); ERTS_TRACE_FLAGS(c_p) |= F_TRACE_SILENT; erts_proc_unlock(c_p, ERTS_PROC_LOCKS_ALL_MINOR); } else if (*esp == am_false) { erts_proc_lock(c_p, ERTS_PROC_LOCKS_ALL_MINOR); ERTS_TRACE_FLAGS(c_p) &= ~F_TRACE_SILENT; erts_proc_unlock(c_p, ERTS_PROC_LOCKS_ALL_MINOR); } break; case matchTrace2: ASSERT(c_p == self); { /* disable enable */ Uint d_flags = 0, e_flags = 0; /* process trace flags */ ErtsTracer tracer = erts_tracer_nil; /* XXX Atomicity note: Not fully atomic. Default tracer * is sampled from current process but applied to * tracee and tracer later after releasing main * locks on current process, so ERTS_TRACER_PROC(c_p) * may actually have changed when tracee and tracer * gets updated. I do not think nobody will notice. * It is just the default value that is not fully atomic. * and the real argument settable from match spec * {trace,[],[{{tracer,Tracer}}]} is much, much older. */ int cputs = 0; erts_tracer_update(&tracer, ERTS_TRACER(c_p)); if (! erts_trace_flags(esp[-1], &d_flags, &tracer, &cputs) || ! erts_trace_flags(esp[-2], &e_flags, &tracer, &cputs) || cputs ) { (--esp)[-1] = FAIL_TERM; ERTS_TRACER_CLEAR(&tracer); break; } erts_proc_lock(c_p, ERTS_PROC_LOCKS_ALL_MINOR); (--esp)[-1] = set_match_trace(c_p, FAIL_TERM, tracer, d_flags, e_flags); erts_proc_unlock(c_p, ERTS_PROC_LOCKS_ALL_MINOR); ERTS_TRACER_CLEAR(&tracer); } break; case matchTrace3: ASSERT(c_p == self); { /* disable enable */ Uint d_flags = 0, e_flags = 0; /* process trace flags */ ErtsTracer tracer = erts_tracer_nil; /* XXX Atomicity note. Not fully atomic. See above. * Above it could possibly be solved, but not here. */ int cputs = 0; Eterm tracee = (--esp)[0]; erts_tracer_update(&tracer, ERTS_TRACER(c_p)); if (! erts_trace_flags(esp[-1], &d_flags, &tracer, &cputs) || ! erts_trace_flags(esp[-2], &e_flags, &tracer, &cputs) || cputs || ! (tmpp = get_proc(c_p, ERTS_PROC_LOCK_MAIN, tracee, ERTS_PROC_LOCKS_ALL))) { (--esp)[-1] = FAIL_TERM; ERTS_TRACER_CLEAR(&tracer); break; } if (tmpp == c_p) { (--esp)[-1] = set_match_trace(c_p, FAIL_TERM, tracer, d_flags, e_flags); erts_proc_unlock(c_p, ERTS_PROC_LOCKS_ALL_MINOR); } else { erts_proc_unlock(c_p, ERTS_PROC_LOCK_MAIN); (--esp)[-1] = set_match_trace(tmpp, FAIL_TERM, tracer, d_flags, e_flags); erts_proc_unlock(tmpp, ERTS_PROC_LOCKS_ALL); erts_proc_lock(c_p, ERTS_PROC_LOCK_MAIN); } ERTS_TRACER_CLEAR(&tracer); } break; case matchCatch: /* Match success, now build result */ do_catch = 1; if (in_flags & ERTS_PAM_COPY_RESULT) { build_proc = c_p; if (esdp) esdp->current_process = c_p; } break; case matchHalt: goto success; default: erts_exit(ERTS_ERROR_EXIT, "Internal error: unexpected opcode in match program."); } } fail: *return_flags = 0U; if (fail_label >= 0) { /* We failed during a "TryMeElse", lets restart, with the next match program */ pc = (prog->text) + fail_label; cleanup_match_pseudo_process(mpsp, 1); goto restart; } ret = THE_NON_VALUE; success: ASSERT(ret == THE_NON_VALUE || esp == orig_esp); #ifdef DMC_DEBUG if (*heap_fence != FENCE_PATTERN) { erts_exit(ERTS_ABORT_EXIT, "Heap fence overwritten in db_prog_match after op " "0x%08x, overwritten with 0x%08x.", save_op, *heap_fence); } if (*stack_fence != FENCE_PATTERN) { erts_exit(ERTS_ABORT_EXIT, "Stack fence overwritten in db_prog_match after op " "0x%08x, overwritten with 0x%08x.", save_op, *stack_fence); } #endif if (esdp) esdp->current_process = current_scheduled; return ret; #undef FAIL #undef FAIL_TERM } DMCErrInfo *db_new_dmc_err_info(void) { DMCErrInfo *ret = erts_alloc(ERTS_ALC_T_DB_DMC_ERR_INFO, sizeof(DMCErrInfo)); ret->var_trans = NULL; ret->num_trans = 0; ret->error_added = 0; ret->first = NULL; return ret; } Eterm db_format_dmc_err_info(Process *p, DMCErrInfo *ei) { int sl; int vnum; DMCError *tmp; Eterm *shp; Eterm ret = NIL; Eterm tlist, tpl, sev; char buff[DMC_ERR_STR_LEN + 20 /* for the number */]; for (tmp = ei->first; tmp != NULL; tmp = tmp->next) { if (tmp->variable >= 0 && tmp->variable < ei->num_trans && ei->var_trans != NULL) { vnum = (int) ei->var_trans[tmp->variable]; } else { vnum = tmp->variable; } if (vnum >= 0) erts_snprintf(buff,sizeof(buff)+20,tmp->error_string, vnum); else sys_strcpy(buff,tmp->error_string); sl = sys_strlen(buff); shp = HAlloc(p, sl * 2 + 5); sev = (tmp->severity == dmcWarning) ? am_warning : am_error; tlist = buf_to_intlist(&shp, buff, sl, NIL); tpl = TUPLE2(shp, sev, tlist); shp += 3; ret = CONS(shp, tpl, ret); shp += 2; } return ret; } void db_free_dmc_err_info(DMCErrInfo *ei){ while (ei->first != NULL) { DMCError *ll = ei->first->next; erts_free(ERTS_ALC_T_DB_DMC_ERROR, ei->first); ei->first = ll; } if (ei->var_trans) erts_free(ERTS_ALC_T_DB_TRANS_TAB, ei->var_trans); erts_free(ERTS_ALC_T_DB_DMC_ERR_INFO, ei); } /* Calculate integer addition: counter+incr. ** Store bignum in *hpp and increase *hpp accordingly. ** *hpp is assumed to be large enough to hold the result. */ Eterm db_add_counter(Eterm** hpp, Wterm counter, Eterm incr) { DeclareTmpHeapNoproc(big_tmp,2); Eterm res; Sint ires; Wterm arg1; Wterm arg2; if (is_both_small(counter,incr)) { ires = signed_val(counter) + signed_val(incr); if (IS_SSMALL(ires)) { return make_small(ires); } else { res = small_to_big(ires, *hpp); ASSERT(BIG_NEED_SIZE(big_size(res))==2); *hpp += 2; return res; } } else { UseTmpHeapNoproc(2); switch(NUMBER_CODE(counter, incr)) { case SMALL_BIG: arg1 = small_to_big(signed_val(counter), big_tmp); arg2 = incr; break; case BIG_SMALL: arg1 = counter; arg2 = small_to_big(signed_val(incr), big_tmp); break; case BIG_BIG: arg1 = incr; arg2 = counter; break; default: UnUseTmpHeapNoproc(2); return THE_NON_VALUE; } res = big_plus(arg1, arg2, *hpp); if (is_big(res)) { *hpp += BIG_NEED_SIZE(big_size(res)); } UnUseTmpHeapNoproc(2); return res; } } /* Must be called to read elements after db_lookup_dbterm. ** Will decompress if needed. */ Wterm db_do_read_element(DbUpdateHandle* handle, Sint position) { Eterm elem = handle->dbterm->tpl[position]; if (!is_header(elem)) { return elem; } ASSERT(((DbTableCommon*)handle->tb)->compress); ASSERT(!(handle->flags & DB_MUST_RESIZE)); handle->dbterm = db_alloc_tmp_uncompressed(&handle->tb->common, handle->dbterm); handle->flags |= DB_MUST_RESIZE; return handle->dbterm->tpl[position]; } /* ** Update one element: ** handle: Initialized by db_lookup_dbterm() ** position: The tuple position of the elements to be updated. ** newval: The new value of the element. ** Can not fail. */ void db_do_update_element(DbUpdateHandle* handle, Sint position, Eterm newval) { Eterm oldval = handle->dbterm->tpl[position]; Eterm* newp; Eterm* oldp; Uint newval_sz; Uint oldval_sz; if (is_both_immed(newval,oldval)) { handle->dbterm->tpl[position] = newval; #ifdef DEBUG_CLONE if (handle->dbterm->debug_clone) { handle->dbterm->debug_clone[position] = newval; } #endif return; } if (!(handle->flags & DB_MUST_RESIZE)) { if (handle->tb->common.compress) { handle->dbterm = db_alloc_tmp_uncompressed(&handle->tb->common, handle->dbterm); handle->flags |= DB_MUST_RESIZE; oldval = handle->dbterm->tpl[position]; } else { if (is_boxed(newval)) { newp = boxed_val(newval); switch (*newp & _TAG_HEADER_MASK) { case _TAG_HEADER_POS_BIG: case _TAG_HEADER_NEG_BIG: case _TAG_HEADER_FLOAT: case _TAG_HEADER_HEAP_BIN: newval_sz = header_arity(*newp) + 1; if (is_boxed(oldval)) { oldp = boxed_val(oldval); switch (*oldp & _TAG_HEADER_MASK) { case _TAG_HEADER_POS_BIG: case _TAG_HEADER_NEG_BIG: case _TAG_HEADER_FLOAT: case _TAG_HEADER_HEAP_BIN: oldval_sz = header_arity(*oldp) + 1; if (oldval_sz == newval_sz) { /* "self contained" terms of same size, do memcpy */ sys_memcpy(oldp, newp, newval_sz*sizeof(Eterm)); return; } goto both_size_set; } } goto new_size_set; } } } } /* Not possible for simple memcpy or dbterm is already non-contiguous, */ /* need to realloc... */ newval_sz = is_immed(newval) ? 0 : size_object(newval); new_size_set: oldval_sz = is_immed(oldval) ? 0 : size_object(oldval); both_size_set: handle->new_size = handle->new_size - oldval_sz + newval_sz; /* * Write new value in old dbterm, finalize will make a flat copy. */ if (!(handle->flags & DB_MUST_RESIZE)) { const size_t nbytes = (arityval(handle->dbterm->tpl[0]) + 1) * sizeof(Eterm); /* * First time here. Save the original tuple array in order to make * fast size calculations of untouched elements. */ ASSERT(!handle->tb->common.compress); ASSERT(!handle->old_tpl); if (nbytes > sizeof(handle->old_tpl_dflt)) { handle->old_tpl = erts_alloc(ERTS_ALC_T_TMP, nbytes); } else { handle->old_tpl = handle->old_tpl_dflt; } sys_memcpy(handle->old_tpl, handle->dbterm->tpl, nbytes); handle->flags |= DB_MUST_RESIZE; } ASSERT(!!handle->old_tpl != !!handle->tb->common.compress); handle->dbterm->tpl[position] = newval; } static ERTS_INLINE byte* db_realloc_term(DbTableCommon* tb, void* old, Uint old_sz, Uint new_sz, Uint offset) { byte* ret; if (erts_ets_realloc_always_moves) { ret = erts_db_alloc(ERTS_ALC_T_DB_TERM, (DbTable*)tb, new_sz); sys_memcpy(ret, old, offset); erts_db_free(ERTS_ALC_T_DB_TERM, (DbTable*)tb, old, old_sz); } else { ret = erts_db_realloc(ERTS_ALC_T_DB_TERM, (DbTable*)tb, old, old_sz, new_sz); } return ret; } /* Allocated size of a compressed dbterm */ static ERTS_INLINE Uint db_alloced_size_comp(DbTerm* obj) { return obj->tpl[arityval(*obj->tpl) + 1]; } void db_free_term(DbTable *tb, void* basep, Uint offset) { DbTerm* db = (DbTerm*) ((byte*)basep + offset); Uint size; if (tb->common.compress) { db_cleanup_offheap_comp(db); size = db_alloced_size_comp(db); } else { erts_cleanup_offheap_list(db->first_oh); size = offset + offsetof(DbTerm,tpl) + db->size*sizeof(Eterm); } erts_db_free(ERTS_ALC_T_DB_TERM, tb, basep, size); } Uint db_term_size(DbTable *tb, void* basep, Uint offset) { DbTerm* db = (DbTerm*) ((byte*)basep + offset); if (tb->common.compress) { return db_alloced_size_comp(db); } else { return offset + offsetof(DbTerm,tpl) + db->size*sizeof(Eterm); } } void db_free_term_no_tab(int compress, void* basep, Uint offset) { DbTerm* db = (DbTerm*) ((byte*)basep + offset); Uint size; if (compress) { db_cleanup_offheap_comp(db); size = db_alloced_size_comp(db); } else { erts_cleanup_offheap_list(db->first_oh); size = offset + offsetof(DbTerm,tpl) + db->size*sizeof(Eterm); } erts_db_free(ERTS_ALC_T_DB_TERM, NULL, basep, size); } static ERTS_INLINE Uint align_up(Uint value, Uint pow2) { ASSERT((pow2 & (pow2-1)) == 0); return (value + (pow2-1)) & ~(pow2-1); } /* Compressed size of an uncompressed term */ static Uint db_size_dbterm_comp(int keypos, Eterm obj) { Eterm* tpl = tuple_val(obj); int i; Uint size = sizeof(DbTerm) + arityval(*tpl) * sizeof(Eterm) + sizeof(Uint); /* "alloc_size" */ for (i = arityval(*tpl); i>0; i--) { if (i != keypos && is_not_immed(tpl[i])) { size += erts_encode_ext_size_ets(tpl[i]); } } size += size_object(tpl[keypos]) * sizeof(Eterm); return align_up(size, sizeof(Uint)); } /* Conversion between top tuple element and pointer to compressed data */ static ERTS_INLINE Eterm ext2elem(Eterm* tpl, byte* ext) { return (((Uint)(ext - (byte*)tpl)) << _TAG_PRIMARY_SIZE) | TAG_PRIMARY_HEADER; } static ERTS_INLINE byte* elem2ext(Eterm* tpl, Uint ix) { ASSERT(is_header(tpl[ix])); return (byte*)tpl + (tpl[ix] >> _TAG_PRIMARY_SIZE); } static void* copy_to_comp(int keypos, Eterm obj, DbTerm* dest, Uint alloc_size) { ErlOffHeap tmp_offheap; Eterm* src = tuple_val(obj); Eterm* tpl = dest->tpl; Eterm key = src[keypos]; int arity = arityval(src[0]); union { Eterm* ep; byte* cp; UWord ui; }top; int i; top.ep = tpl+ 1 + arity + 1; tpl[0] = src[0]; tpl[arity + 1] = alloc_size; tmp_offheap.first = NULL; tpl[keypos] = copy_struct(key, size_object(key), &top.ep, &tmp_offheap); dest->first_oh = tmp_offheap.first; for (i=1; i<=arity; i++) { if (i != keypos) { if (is_immed(src[i])) { tpl[i] = src[i]; } else { tpl[i] = ext2elem(tpl, top.cp); top.cp = erts_encode_ext_ets(src[i], top.cp, &dest->first_oh); } } } #ifdef DEBUG_CLONE { Eterm* dbg_top = erts_alloc(ERTS_ALC_T_DB_TERM, dest->size * sizeof(Eterm)); dest->debug_clone = dbg_top; tmp_offheap.first = dest->first_oh; copy_struct(obj, dest->size, &dbg_top, &tmp_offheap); dest->first_oh = tmp_offheap.first; ASSERT(dbg_top == dest->debug_clone + dest->size); } #endif return top.cp; } static ERTS_INLINE Eterm copy_ets_element(Eterm obj, int sz, Eterm **hpp, ErlOffHeap *off_heap) { #ifdef DEBUG const Eterm* const hp_start = *hpp; #endif Eterm copy; if (sz == 0) { ASSERT(is_immed(obj) || obj == ERTS_GLOBAL_LIT_EMPTY_TUPLE); return obj; } ASSERT(is_not_immed(obj)); if (is_list(obj) && is_immed(CAR(list_val(obj)))) { /* copy_struct() would put this last, but we need the top term to be first in block */ Eterm* src = list_val(obj); Eterm* dst = *hpp; CAR(dst) = CAR(src); *hpp += 2; CDR(dst) = copy_struct(CDR(src), sz-2, hpp, off_heap); copy = make_list(dst); } else { copy = copy_struct(obj, sz, hpp, off_heap); } ASSERT(ptr_val(copy) == hp_start); return copy; } /* ** Copy the object into a possibly new DbTerm, ** offset is the offset of the DbTerm from the start ** of the allocated structure, The possibly realloced and copied ** structure is returned. Make sure (((char *) old) - offset) is a ** pointer to a ERTS_ALC_T_DB_TERM allocated data area. */ void* db_store_term(DbTableCommon *tb, DbTerm* old, Uint offset, Eterm obj) { byte* basep; DbTerm* newp; Eterm* top; Eterm* source_ptr; Eterm* dest_ptr; int arity, i, size; ErlOffHeap tmp_offheap; Uint elem_sizes_dflt[8]; Uint* elem_sizes = elem_sizes_dflt; /* Calculate sizes of all elements and total size */ source_ptr = tuple_val(obj); arity = arityval(*source_ptr); if (arity > sizeof(elem_sizes_dflt) / sizeof(elem_sizes_dflt[0])) { elem_sizes = erts_alloc(ERTS_ALC_T_TMP, arity * sizeof(*elem_sizes)); } size = arity + 1; for (i = 0; i < arity; i++) { elem_sizes[i] = size_object(source_ptr[i+1]); size += elem_sizes[i]; } if (old != 0) { basep = ((byte*) old) - offset; erts_cleanup_offheap_list(old->first_oh); if (size == old->size) { newp = old; } else { Uint new_sz = offset + sizeof(DbTerm) + sizeof(Eterm)*(size-1); Uint old_sz = offset + sizeof(DbTerm) + sizeof(Eterm)*(old->size-1); basep = db_realloc_term(tb, basep, old_sz, new_sz, offset); newp = (DbTerm*) (basep + offset); } } else { basep = erts_db_alloc(ERTS_ALC_T_DB_TERM, (DbTable *)tb, (offset + sizeof(DbTerm) + sizeof(Eterm)*(size-1))); newp = (DbTerm*) (basep + offset); } /* * Do the actual copy. Lay out elements in order after the top tuple. * This is relied upon by db_copy_element_from_ets. */ newp->size = size; top = newp->tpl; tmp_offheap.first = NULL; *top++ = *source_ptr++; // copy the header dest_ptr = top + arity; for (i = 0; i < arity; ++i) { *top++ = copy_ets_element(source_ptr[i], elem_sizes[i], &dest_ptr, &tmp_offheap); } newp->first_oh = tmp_offheap.first; #ifdef DEBUG_CLONE newp->debug_clone = NULL; #endif if (elem_sizes != elem_sizes_dflt) erts_free(ERTS_ALC_T_TMP, elem_sizes); return basep; } void* db_store_term_comp(DbTableCommon *tb, /* May be NULL */ int keypos, DbTerm* old, Uint offset,Eterm obj) { Uint new_sz = offset + db_size_dbterm_comp(keypos, obj); byte* basep; DbTerm* newp; byte* top; ASSERT(tb == NULL || tb->compress); if (old != 0) { Uint old_sz = db_alloced_size_comp(old); db_cleanup_offheap_comp(old); basep = ((byte*) old) - offset; if (new_sz == old_sz) { newp = old; } else { basep = db_realloc_term(tb, basep, old_sz, new_sz, offset); newp = (DbTerm*) (basep + offset); } } else { basep = erts_db_alloc(ERTS_ALC_T_DB_TERM, (DbTable*)tb, new_sz); newp = (DbTerm*) (basep + offset); } newp->size = size_object(obj); top = copy_to_comp(keypos, obj, newp, new_sz); ASSERT(top <= basep + new_sz); (void)top; /* ToDo: Maybe realloc if ((basep+new_sz) - top) > WASTED_SPACE_LIMIT */ return basep; } static Uint db_element_size(DbTerm *obj, Eterm* tpl, Uint pos); void db_finalize_resize(DbUpdateHandle* handle, Uint offset) { DbTable* tbl = handle->tb; DbTerm* newDbTerm; Uint alloc_sz = offset + (tbl->common.compress ? db_size_dbterm_comp(tbl->common.keypos, make_tuple(handle->dbterm->tpl)) : sizeof(DbTerm)+sizeof(Eterm)*(handle->new_size-1)); byte* newp = erts_db_alloc(ERTS_ALC_T_DB_TERM, tbl, alloc_sz); byte* oldp = *(handle->bp); ASSERT(handle->flags & DB_MUST_RESIZE); sys_memcpy(newp, oldp, offset); /* copy only hash/tree header */ *(handle->bp) = newp; newDbTerm = (DbTerm*) (newp + offset); newDbTerm->size = handle->new_size; #ifdef DEBUG_CLONE newDbTerm->debug_clone = NULL; #endif /* make a flat copy */ if (tbl->common.compress) { copy_to_comp(tbl->common.keypos, make_tuple(handle->dbterm->tpl), newDbTerm, alloc_sz); db_free_tmp_uncompressed(handle->dbterm); } else { ErlOffHeap tmp_offheap; DbTerm* src = handle->dbterm; const Uint arity = arityval(src->tpl[0]); Eterm* top = &newDbTerm->tpl[arity+1]; int i; ASSERT(handle->old_tpl); tmp_offheap.first = NULL; newDbTerm->tpl[0] = src->tpl[0]; for (i = 1; i <= arity; ++i) { Uint sz; if (is_immed(src->tpl[i])) { newDbTerm->tpl[i] = src->tpl[i]; } else { if (src->tpl[i] != handle->old_tpl[i]) { sz = size_object(src->tpl[i]); } else { sz = db_element_size(src, handle->old_tpl, i); } newDbTerm->tpl[i] = copy_ets_element(src->tpl[i], sz, &top, &tmp_offheap); } } ASSERT((byte*)top == (newp + alloc_sz)); newDbTerm->first_oh = tmp_offheap.first; if (handle->old_tpl != handle->old_tpl_dflt) erts_free(ERTS_ALC_T_TMP, handle->old_tpl); } } Eterm db_copy_from_comp(DbTableCommon* tb, DbTerm* bp, Eterm** hpp, ErlOffHeap* off_heap) { Eterm* hp = *hpp; int i, arity = arityval(bp->tpl[0]); ErtsHeapFactory factory; hp[0] = bp->tpl[0]; *hpp += arity + 1; hp[tb->keypos] = copy_struct(bp->tpl[tb->keypos], size_object(bp->tpl[tb->keypos]), hpp, off_heap); erts_factory_static_init(&factory, *hpp, bp->size - (arity+1), off_heap); for (i=arity; i>0; i--) { if (i != tb->keypos) { if (is_immed(bp->tpl[i])) { hp[i] = bp->tpl[i]; } else { hp[i] = erts_decode_ext_ets(&factory, elem2ext(bp->tpl, i)); } } } *hpp = factory.hp; erts_factory_close(&factory); ASSERT((*hpp - hp) <= bp->size); #ifdef DEBUG_CLONE ASSERT(EQ(make_tuple(hp),make_tuple(bp->debug_clone))); #endif return make_tuple(hp); } Eterm db_copy_element_from_ets(DbTableCommon *tb, Process *p, DbTerm *obj, Uint pos, Eterm **hpp, Uint extra) { if (is_immed(obj->tpl[pos])) { *hpp = HAlloc(p, extra); return obj->tpl[pos]; } if (tb->compress) { if (pos == tb->keypos) { Uint sz = size_object(obj->tpl[pos]); *hpp = HAlloc(p, sz + extra); return copy_struct(obj->tpl[pos], sz, hpp, &MSO(p)); } else { byte *ext = elem2ext(obj->tpl, pos); Sint sz = erts_decode_ext_size_ets(ext, db_alloced_size_comp(obj)) + extra; Eterm copy; ErtsHeapFactory factory; erts_factory_proc_prealloc_init(&factory, p, sz); copy = erts_decode_ext_ets(&factory, ext); *hpp = erts_produce_heap(&factory, extra, 0); erts_factory_close(&factory); #ifdef DEBUG_CLONE ASSERT(EQ(copy, obj->debug_clone[pos])); #endif return copy; } } else { Uint sz = db_element_size(obj, obj->tpl, pos); *hpp = HAlloc(p, sz + extra); return copy_shallow_obj(obj->tpl[pos], sz, hpp, &MSO(p)); } } /* * Return the size of an element of an uncompressed ETS record. * Relies on each element of the ETS record being laid out contiguously, * and starting with the top term. */ static Uint db_element_size(DbTerm *obj, Eterm* tpl, Uint pos) { Eterm *start_ptr; Eterm *end_ptr; Eterm elem; Uint arity, i, sz; elem = tpl[pos]; if (is_zero_sized(elem)) return 0; ASSERT(is_boxed(elem) || is_list(elem)); start_ptr = ptr_val(elem); ASSERT(!erts_is_literal(elem, start_ptr)); arity = arityval(tpl[0]); for (i = pos + 1; i <= arity; ++i) { elem = tpl[i]; if (!is_zero_sized(elem)) { ASSERT(is_boxed(elem) || is_list(elem)); end_ptr = ptr_val(elem); ASSERT(!erts_is_literal(elem, end_ptr)); goto done; } } end_ptr = obj->tpl + obj->size; done: sz = end_ptr - start_ptr; ASSERT(sz == size_object(tpl[pos])); return sz; } /* Our own "cleanup_offheap" * as ProcBin and ErtsMRefThing may be unaligned in compressed terms */ void db_cleanup_offheap_comp(DbTerm* obj) { union erl_off_heap_ptr u; union erts_tmp_aligned_offheap tmp; for (u.hdr = obj->first_oh; u.hdr; u.hdr = u.hdr->next) { erts_align_offheap(&u, &tmp); switch (thing_subtag(u.hdr->thing_word)) { case REFC_BINARY_SUBTAG: erts_bin_release(u.pb->val); break; case FUN_SUBTAG: /* We _KNOW_ that this is a local fun, otherwise it would not * be part of the off-heap list. */ ASSERT(is_local_fun(u.fun)); if (erts_refc_dectest(&u.fun->entry.fun->refc, 0) == 0) { erts_erase_fun_entry(u.fun->entry.fun); } break; case REF_SUBTAG: ASSERT(is_magic_ref_thing(u.hdr)); erts_bin_release((Binary *)u.mref->mb); break; default: ASSERT(is_external_header(u.hdr->thing_word)); erts_deref_node_entry(u.ext->node, make_boxed(u.ep)); break; } } #ifdef DEBUG_CLONE if (obj->debug_clone != NULL) { erts_free(ERTS_ALC_T_DB_TERM, obj->debug_clone); obj->debug_clone = NULL; } #endif } int db_eq_comp(DbTableCommon* tb, Eterm a, DbTerm* b) { ErlOffHeap tmp_offheap; Eterm* allocp; Eterm* hp; Eterm tmp_b; int is_eq; ASSERT(tb->compress); hp = allocp = erts_alloc(ERTS_ALC_T_TMP, b->size*sizeof(Eterm)); tmp_offheap.first = NULL; tmp_b = db_copy_from_comp(tb, b, &hp, &tmp_offheap); is_eq = eq(a,tmp_b); erts_cleanup_offheap(&tmp_offheap); erts_free(ERTS_ALC_T_TMP, allocp); return is_eq; } /* ** Check if object represents a "match" variable ** i.e and atom $N where N is an integer ** */ int db_is_variable(Eterm obj) { byte *b; int n; int N; if (is_not_atom(obj)) return -1; b = atom_tab(atom_val(obj))->name; if ((n = atom_tab(atom_val(obj))->len) < 2) return -1; if (*b++ != '$') return -1; n--; /* Handle first digit */ if (*b == '0') return (n == 1) ? 0 : -1; if (*b >= '1' && *b <= '9') N = *b++ - '0'; else return -1; n--; while(n--) { if (*b >= '0' && *b <= '9') { N = N*10 + (*b - '0'); b++; } else return -1; } return N; } /* check if node is (or contains) a map * return 1 if node contains a map * return 0 otherwise */ int db_has_map(Eterm node) { DECLARE_ESTACK(s); ESTACK_PUSH(s,node); while (!ESTACK_ISEMPTY(s)) { node = ESTACK_POP(s); if (is_list(node)) { while (is_list(node)) { ESTACK_PUSH(s,CAR(list_val(node))); node = CDR(list_val(node)); } ESTACK_PUSH(s,node); /* Non wellformed list or [] */ } else if (is_tuple(node)) { Eterm *tuple = tuple_val(node); int arity = arityval(*tuple); while(arity--) { ESTACK_PUSH(s,*(++tuple)); } } else if is_map(node) { DESTROY_ESTACK(s); return 1; } } DESTROY_ESTACK(s); return 0; } /* check if obj is (or contains) a variable */ /* return 1 if obj contains a variable or underscore */ /* return 0 if obj is fully ground */ int db_has_variable(Eterm node) { DECLARE_ESTACK(s); ESTACK_PUSH(s,node); while (!ESTACK_ISEMPTY(s)) { node = ESTACK_POP(s); switch(node & _TAG_PRIMARY_MASK) { case TAG_PRIMARY_LIST: while (is_list(node)) { ESTACK_PUSH(s,CAR(list_val(node))); node = CDR(list_val(node)); } ESTACK_PUSH(s,node); /* Non wellformed list or [] */ break; case TAG_PRIMARY_BOXED: if (is_tuple(node)) { Eterm *tuple = tuple_val(node); int arity = arityval(*tuple); while(arity--) { ESTACK_PUSH(s,*(++tuple)); } } else if (is_flatmap(node)) { Eterm *values = flatmap_get_values(flatmap_val(node)); Uint size = flatmap_get_size(flatmap_val(node)); ESTACK_PUSH(s, ((flatmap_t *) flatmap_val(node))->keys); while (size--) { ESTACK_PUSH(s, *(values++)); } } else if (is_map(node)) { /* other map-nodes or map-heads */ Eterm *ptr = hashmap_val(node); int i = hashmap_bitcount(MAP_HEADER_VAL(*ptr)); ptr += MAP_HEADER_ARITY(*ptr); while(i--) { ESTACK_PUSH(s, *++ptr); } } break; case TAG_PRIMARY_IMMED1: if (node == am_Underscore || db_is_variable(node) >= 0) { DESTROY_ESTACK(s); return 1; } break; } } DESTROY_ESTACK(s); return 0; } /* ** Local (static) utilities. */ /* *************************************************************************** ** Compiled matches *************************************************************************** */ /* ** Utility to add an error */ static void vadd_dmc_err(DMCErrInfo *err_info, DMCErrorSeverity severity, int variable, const char *str, ...) { DMCError *e; va_list args; va_start(args, str); /* Linked in in reverse order, to ease the formatting */ e = erts_alloc(ERTS_ALC_T_DB_DMC_ERROR, sizeof(DMCError)); erts_vsnprintf(e->error_string, DMC_ERR_STR_LEN, str, args); e->variable = variable; e->severity = severity; e->next = err_info->first; #ifdef HARDDEBUG erts_fprintf(stderr,"add_dmc_err: %s\n",e->error_string); #endif err_info->first = e; if (severity >= dmcError) err_info->error_added = 1; va_end(args); } /* ** Handle one term in the match expression (not the guard) */ static DMCRet dmc_one_term(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(Eterm) *stack, DMC_STACK_TYPE(UWord) *text, Eterm c) { Sint n; Eterm *hp; Uint sz, sz2, sz3; Uint i, j; switch (c & _TAG_PRIMARY_MASK) { case TAG_PRIMARY_IMMED1: if ((n = db_is_variable(c)) >= 0) { /* variable */ if (n >= heap->size) { /* ** Ouch, big integer in match variable. */ Eterm *save_hp; ASSERT(heap->vars == heap->vars_def); sz = sz2 = sz3 = 0; for (j = 0; j < context->num_match; ++j) { sz += size_object(context->matchexpr[j]); sz2 += size_object(context->guardexpr[j]); sz3 += size_object(context->bodyexpr[j]); } context->copy = new_message_buffer(sz + sz2 + sz3 + context->num_match); save_hp = hp = context->copy->mem; hp += context->num_match; for (j = 0; j < context->num_match; ++j) { context->matchexpr[j] = copy_struct(context->matchexpr[j], size_object(context->matchexpr[j]), &hp, &(context->copy->off_heap)); context->guardexpr[j] = copy_struct(context->guardexpr[j], size_object(context->guardexpr[j]), &hp, &(context->copy->off_heap)); context->bodyexpr[j] = copy_struct(context->bodyexpr[j], size_object(context->bodyexpr[j]), &hp, &(context->copy->off_heap)); } for (j = 0; j < context->num_match; ++j) { /* the actual expressions can be atoms in their selves, place them first */ *save_hp++ = context->matchexpr[j]; } heap->size = match_compact(context->copy, context->err_info); for (j = 0; j < context->num_match; ++j) { /* restore the match terms, as they may be atoms that changed */ context->matchexpr[j] = context->copy->mem[j]; } heap->vars = erts_alloc(ERTS_ALC_T_DB_MS_CMPL_HEAP, heap->size*sizeof(DMCVariable)); sys_memset(heap->vars, 0, heap->size * sizeof(DMCVariable)); DMC_CLEAR(*stack); /*DMC_PUSH(*stack,NIL);*/ DMC_CLEAR(*text); return retRestart; } if (heap->vars[n].is_bound) { DMC_PUSH2(*text, matchCmp, n); } else { /* Not bound, bind! */ if (n >= heap->vars_used) heap->vars_used = n + 1; DMC_PUSH2(*text, matchBind, n); heap->vars[n].is_bound = 1; } } else if (c == am_Underscore) { DMC_PUSH(*text, matchSkip); } else { /* Any immediate value */ DMC_PUSH2(*text, matchEq, (Uint) c); } break; case TAG_PRIMARY_LIST: DMC_PUSH(*text, matchPushL); ++(context->stack_used); DMC_PUSH(*stack, c); break; case TAG_PRIMARY_BOXED: { Eterm hdr = *boxed_val(c); switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) { case (_TAG_HEADER_ARITYVAL >> _TAG_PRIMARY_SIZE): n = arityval(*tuple_val(c)); DMC_PUSH2(*text, matchPushT, n); ++(context->stack_used); DMC_PUSH(*stack, c); break; case (_TAG_HEADER_MAP >> _TAG_PRIMARY_SIZE): if (is_flatmap(c)) n = flatmap_get_size(flatmap_val(c)); else n = hashmap_size(c); DMC_PUSH2(*text, matchPushM, n); ++(context->stack_used); DMC_PUSH(*stack, c); break; case (_TAG_HEADER_REF >> _TAG_PRIMARY_SIZE): { Eterm* ref_val = internal_ref_val(c); DMC_PUSH(*text, matchEqRef); n = thing_arityval(ref_val[0]); for (i = 0; i <= n; ++i) { DMC_PUSH(*text, ref_val[i]); } break; } case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE): case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE): { Eterm* bval = big_val(c); n = thing_arityval(bval[0]); DMC_PUSH(*text, matchEqBig); for (i = 0; i <= n; ++i) { DMC_PUSH(*text, (Uint) bval[i]); } break; } case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE): DMC_PUSH2(*text, matchEqFloat, (Uint) float_val(c)[1]); #ifdef ARCH_32 DMC_PUSH(*text, (Uint) float_val(c)[2]); #endif break; default: /* BINARY, FUN, VECTOR, or EXTERNAL */ DMC_PUSH2(*text, matchEqBin, dmc_private_copy(context, c)); break; } break; } default: erts_exit(ERTS_ERROR_EXIT, "db_match_compile: " "Bad object on heap: 0x%bex\n", c); } return retOk; } /* ** Make a private copy of a term in a context. */ static Eterm dmc_private_copy(DMCContext *context, Eterm c) { if (is_immed(c)) { return c; } else { Uint n = size_object(c); ErlHeapFragment *tmp_mb = new_message_buffer(n); Eterm *hp = tmp_mb->mem; Eterm copy = copy_struct(c, n, &hp, &(tmp_mb->off_heap)); tmp_mb->next = context->save; context->save = tmp_mb; return copy; } } /* ** Match guard compilation */ static void do_emit_constant(DMCContext *context, DMC_STACK_TYPE(UWord) *text, Eterm t) { int sz; ErlHeapFragment *emb; Eterm *hp; Eterm tmp; if (is_immed(t)) { tmp = t; } else { sz = my_size_object(t, 0); if (sz) { emb = new_message_buffer(sz); hp = emb->mem; tmp = my_copy_struct(t,&hp,&(emb->off_heap), 0); emb->next = context->save; context->save = emb; } else { /* must be {const, Immed} or the empty tuple*/ ASSERT(is_tuple_arity(t,2) && tuple_val(t)[1] == am_const); ASSERT(is_tuple_arity(tuple_val(t)[2],0) || is_immed(tuple_val(t)[2])); tmp = tuple_val(t)[2]; } } DMC_PUSH2(*text, matchPushC, (Uint)tmp); if (++context->stack_used > context->stack_need) context->stack_need = context->stack_used; } #define RETURN_ERROR_X(VAR, ContextP, ConstantF, String, ARG) \ (((ContextP)->err_info != NULL) \ ? ((ConstantF) = 0, \ vadd_dmc_err((ContextP)->err_info, dmcError, VAR, String, ARG), \ retOk) \ : retFail) #define RETURN_ERROR(String, ContextP, ConstantF) \ return RETURN_ERROR_X(-1, ContextP, ConstantF, String, 0) #define RETURN_VAR_ERROR(String, N, ContextP, ConstantF) \ return RETURN_ERROR_X(N, ContextP, ConstantF, String, 0) #define RETURN_TERM_ERROR(String, T, ContextP, ConstantF) \ return RETURN_ERROR_X(-1, ContextP, ConstantF, String, T) #define WARNING(String, ContextP) \ add_dmc_err((ContextP)->err_info, String, -1, 0UL, dmcWarning) #define VAR_WARNING(String, N, ContextP) \ add_dmc_err((ContextP)->err_info, String, N, 0UL, dmcWarning) #define TERM_WARNING(String, T, ContextP) \ add_dmc_err((ContextP)->err_info, String, -1, T, dmcWarning) static DMCRet dmc_list(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { int c1; int c2; int ret; if ((ret = dmc_expr(context, heap, text, CAR(list_val(t)), &c1)) != retOk) return ret; if ((ret = dmc_expr(context, heap, text, CDR(list_val(t)), &c2)) != retOk) return ret; if (c1 && c2) { *constant = 1; return retOk; } *constant = 0; if (!c1) { /* The CAR is not a constant, so if the CDR is, we just push it, otherwise it is already pushed. */ if (c2) do_emit_constant(context, text, CDR(list_val(t))); DMC_PUSH(*text, matchConsA); } else { /* !c2 && c1 */ do_emit_constant(context, text, CAR(list_val(t))); DMC_PUSH(*text, matchConsB); } --context->stack_used; /* Two objects on stack becomes one */ return retOk; } static void dmc_rearrange_constants(DMCContext *context, DMC_STACK_TYPE(UWord) *text, int textpos, Eterm *p, Uint nelems) { DMC_STACK_TYPE(UWord) instr_save; Uint i; DMC_INIT_STACK(instr_save); while (DMC_STACK_NUM(*text) > textpos) { DMC_PUSH(instr_save, DMC_POP(*text)); } for (i = nelems; i--;) { do_emit_constant(context, text, p[i]); } while(!DMC_EMPTY(instr_save)) { DMC_PUSH(*text, DMC_POP(instr_save)); } DMC_FREE(instr_save); } static DMCRet dmc_array(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm *p, Uint nelems, int *constant) { int all_constant = 1; int textpos = DMC_STACK_NUM(*text); int preventive_bumps = 0; Uint i; /* ** We remember where we started to layout code, ** assume all is constant and back up and restart if not so. ** The array should be laid out with the last element first, ** so we can memcpy it to the eheap. */ for (i = nelems; i--;) { DMCRet ret; int c; ret = dmc_expr(context, heap, text, p[i], &c); if (ret != retOk) { return ret; } if (!c && all_constant) { all_constant = 0; if (i < nelems - 1) { /* Revert preventive stack bumps as they will now be done again * for real by do_emit_constant() */ context->stack_used -= preventive_bumps; dmc_rearrange_constants(context, text, textpos, p + i + 1, nelems - i - 1); } } else if (c) { if (all_constant) { /* * OTP-17379: * All constants so far, but do preventive stack bumps * as the constants may later be converted to matchPushC * by dmc_rearrange_constants above. * Otherwise dmc_expr() may do incorrect stack depth estimation * when it emits instructions for the first non-constant. */ ++context->stack_used; ++preventive_bumps; } else { do_emit_constant(context, text, p[i]); } } } if (all_constant) { /* Preventive stack bumps not needed */ context->stack_used -= preventive_bumps; } *constant = all_constant; return retOk; } static DMCRet dmc_tuple(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { int all_constant; Eterm *p = tuple_val(t); Uint nelems = arityval(*p); DMCRet ret; ret = dmc_array(context, heap, text, p + 1, nelems, &all_constant); if (ret != retOk) { return ret; } if (all_constant) { *constant = 1; return retOk; } DMC_PUSH2(*text, matchMkTuple, nelems); context->stack_used -= (nelems - 1); *constant = 0; return retOk; } /* * For maps we only expand the values of the map. The keys remain as they are. * So the map #{ {const,a} => {const,b} } will be transformed to #{ {const,a} => b }. */ static DMCRet dmc_map(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { int nelems; int constant_values, constant_keys; DMCRet ret; if (is_flatmap(t)) { flatmap_t *m = (flatmap_t *)flatmap_val(t); Eterm *values = flatmap_get_values(m); int textpos = DMC_STACK_NUM(*text); int stackpos = context->stack_used; nelems = flatmap_get_size(m); if ((ret = dmc_array(context, heap, text, values, nelems, &constant_values)) != retOk) { return ret; } if ((ret = dmc_tuple(context, heap, text, m->keys, &constant_keys)) != retOk) { return ret; } if (constant_values && constant_keys) { *constant = 1; return retOk; } /* If all values were constants, then nothing was emitted by the first dmc_array, so we reset the pc and emit all values as constants and then re-emit the keys. */ if (constant_values) { DMC_STACK_NUM(*text) = textpos; context->stack_used = stackpos; ASSERT(!constant_keys); for (int i = nelems; i--;) { do_emit_constant(context, text, values[i]); } dmc_tuple(context, heap, text, m->keys, &constant_keys); } else if (constant_keys) { Eterm *p = tuple_val(m->keys); Uint nelems = arityval(*p); ASSERT(!constant_values); p++; for (int i = nelems; i--;) do_emit_constant(context, text, p[i]); DMC_PUSH2(*text, matchMkTuple, nelems); context->stack_used -= nelems - 1; } DMC_PUSH2(*text, matchMkFlatMap, nelems); context->stack_used -= nelems; /* n values + 1 key-tuple => 1 map */ *constant = 0; return retOk; } else { DECLARE_WSTACK(wstack); Eterm *kv; int c; int textpos = DMC_STACK_NUM(*text); int stackpos = context->stack_used; ASSERT(is_hashmap(t)); hashmap_iterator_init(&wstack, t, 1); constant_values = 1; nelems = hashmap_size(t); /* Check if all keys and values are constants */ while ((kv=hashmap_iterator_prev(&wstack)) != NULL && constant_values) { if ((ret = dmc_expr(context, heap, text, CAR(kv), &c)) != retOk) { DESTROY_WSTACK(wstack); return ret; } if (!c) constant_values = 0; if ((ret = dmc_expr(context, heap, text, CDR(kv), &c)) != retOk) { DESTROY_WSTACK(wstack); return ret; } if (!c) constant_values = 0; } if (constant_values) { ASSERT(DMC_STACK_NUM(*text) == textpos); *constant = 1; DESTROY_WSTACK(wstack); return retOk; } /* reset the program to the original position and re-emit everything */ DMC_STACK_NUM(*text) = textpos; context->stack_used = stackpos; *constant = 0; hashmap_iterator_init(&wstack, t, 1); while ((kv=hashmap_iterator_prev(&wstack)) != NULL) { /* push key */ if ((ret = dmc_expr(context, heap, text, CAR(kv), &c)) != retOk) { DESTROY_WSTACK(wstack); return ret; } if (c) { do_emit_constant(context, text, CAR(kv)); } /* push value */ if ((ret = dmc_expr(context, heap, text, CDR(kv), &c)) != retOk) { DESTROY_WSTACK(wstack); return ret; } if (c) { do_emit_constant(context, text, CDR(kv)); } } DMC_PUSH2(*text, matchMkHashMap, nelems); context->stack_used -= 2*nelems - 1; /* n keys & values => 1 map */ DESTROY_WSTACK(wstack); return retOk; } } static DMCRet dmc_whole_expression(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { if (context->cflags & DCOMP_TRACE) { /* Hmmm, convert array to list... */ if (context->special) { DMC_PUSH(*text, matchPushArrayAsListU); } else { ASSERT(is_tuple(context->matchexpr [context->current_match])); DMC_PUSH(*text, matchPushArrayAsList); } } else { DMC_PUSH(*text, matchPushExpr); } ++context->stack_used; if (context->stack_used > context->stack_need) context->stack_need = context->stack_used; *constant = 0; return retOk; } /* Figure out which PushV instruction to use. */ static void dmc_add_pushv_variant(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Uint n) { DMCVariable* v = &heap->vars[n]; MatchOps instr = matchPushV; ASSERT(n < heap->vars_used && v->is_bound); if (!context->is_guard) { if(!v->is_in_body) { instr = matchPushVResult; v->is_in_body = 1; } } DMC_PUSH(*text, instr); DMC_PUSH(*text, n); } static DMCRet dmc_variable(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Uint n = db_is_variable(t); if (n >= heap->vars_used || !heap->vars[n].is_bound) { RETURN_VAR_ERROR("Variable $%%d is unbound.", n, context, *constant); } dmc_add_pushv_variant(context, heap, text, n); ++context->stack_used; if (context->stack_used > context->stack_need) context->stack_need = context->stack_used; *constant = 0; return retOk; } static DMCRet dmc_all_bindings(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { int i; DMC_PUSH(*text, matchPushC); DMC_PUSH(*text, NIL); for (i = heap->vars_used - 1; i >= 0; --i) { if (heap->vars[i].is_bound) { dmc_add_pushv_variant(context, heap, text, i); DMC_PUSH(*text, matchConsB); } } ++context->stack_used; if ((context->stack_used + 1) > context->stack_need) context->stack_need = (context->stack_used + 1); *constant = 0; return retOk; } static DMCRet dmc_const(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { if (tuple_val(t)[0] != make_arityval(2)) { RETURN_TERM_ERROR("Special form 'const' called with more than one " "argument in %T.", t, context, *constant); } *constant = 1; return retOk; } static DMCRet dmc_and(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); Uint a = arityval(*p); DMCRet ret; int i; int c; if (a < 2) { RETURN_TERM_ERROR("Special form 'and' called without arguments " "in %T.", t, context, *constant); } *constant = 0; for (i = a; i > 1; --i) { if ((ret = dmc_expr(context, heap, text, p[i], &c)) != retOk) return ret; if (c) do_emit_constant(context, text, p[i]); } DMC_PUSH(*text, matchAnd); DMC_PUSH(*text, (Uint) a - 1); context->stack_used -= (a - 2); return retOk; } static DMCRet dmc_or(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); Uint a = arityval(*p); DMCRet ret; int i; int c; if (a < 2) { RETURN_TERM_ERROR("Special form 'or' called without arguments " "in %T.", t, context, *constant); } *constant = 0; for (i = a; i > 1; --i) { if ((ret = dmc_expr(context, heap, text, p[i], &c)) != retOk) return ret; if (c) do_emit_constant(context, text, p[i]); } DMC_PUSH(*text, matchOr); DMC_PUSH(*text, (Uint) a - 1); context->stack_used -= (a - 2); return retOk; } static DMCRet dmc_andalso(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); Uint a = arityval(*p); DMCRet ret; int i; int c; Uint lbl; Uint lbl_next; Uint lbl_val; if (a < 2) { RETURN_TERM_ERROR("Special form 'andalso' called without" " arguments " "in %T.", t, context, *constant); } *constant = 0; lbl = 0; for (i = 2; i <= a; ++i) { if ((ret = dmc_expr(context, heap, text, p[i], &c)) != retOk) return ret; if (c) do_emit_constant(context, text, p[i]); if (i == a) { DMC_PUSH(*text, matchJump); } else { DMC_PUSH(*text, matchAndAlso); } DMC_PUSH(*text, lbl); lbl = DMC_STACK_NUM(*text)-1; --(context->stack_used); } DMC_PUSH(*text, matchPushC); DMC_PUSH(*text, am_true); lbl_val = DMC_STACK_NUM(*text); while (lbl) { lbl_next = DMC_PEEK(*text, lbl); DMC_POKE(*text, lbl, lbl_val-lbl-1); lbl = lbl_next; } if (++context->stack_used > context->stack_need) context->stack_need = context->stack_used; return retOk; } static DMCRet dmc_orelse(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); Uint a = arityval(*p); DMCRet ret; int i; int c; Uint lbl; Uint lbl_next; Uint lbl_val; if (a < 2) { RETURN_TERM_ERROR("Special form 'orelse' called without arguments " "in %T.", t, context, *constant); } *constant = 0; lbl = 0; for (i = 2; i <= a; ++i) { if ((ret = dmc_expr(context, heap, text, p[i], &c)) != retOk) return ret; if (c) do_emit_constant(context, text, p[i]); if (i == a) { DMC_PUSH(*text, matchJump); } else { DMC_PUSH(*text, matchOrElse); } DMC_PUSH(*text, lbl); lbl = DMC_STACK_NUM(*text)-1; --(context->stack_used); } DMC_PUSH(*text, matchPushC); DMC_PUSH(*text, am_false); lbl_val = DMC_STACK_NUM(*text); while (lbl) { lbl_next = DMC_PEEK(*text, lbl); DMC_POKE(*text, lbl, lbl_val-lbl-1); lbl = lbl_next; } if (++context->stack_used > context->stack_need) context->stack_need = context->stack_used; return retOk; } static DMCRet dmc_message(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); DMCRet ret; int c; if (!(context->cflags & DCOMP_TRACE)) { RETURN_ERROR("Special form 'message' used in wrong dialect.", context, *constant); } if (context->is_guard) { RETURN_ERROR("Special form 'message' called in guard context.", context, *constant); } if (p[0] != make_arityval(2)) { RETURN_TERM_ERROR("Special form 'message' called with wrong " "number of arguments in %T.", t, context, *constant); } *constant = 0; if ((ret = dmc_expr(context, heap, text, p[2], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[2]); } DMC_PUSH(*text, matchReturn); DMC_PUSH(*text, matchPushC); DMC_PUSH(*text, am_true); /* Push as much as we remove, stack_need is untouched */ return retOk; } static DMCRet dmc_self(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); if (p[0] != make_arityval(1)) { RETURN_TERM_ERROR("Special form 'self' called with arguments " "in %T.", t, context, *constant); } *constant = 0; DMC_PUSH(*text, matchSelf); if (++context->stack_used > context->stack_need) context->stack_need = context->stack_used; return retOk; } static DMCRet dmc_return_trace(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); if (!(context->cflags & DCOMP_TRACE)) { RETURN_ERROR("Special form 'return_trace' used in wrong dialect.", context, *constant); } if (context->is_guard) { RETURN_ERROR("Special form 'return_trace' called in " "guard context.", context, *constant); } if (p[0] != make_arityval(1)) { RETURN_TERM_ERROR("Special form 'return_trace' called with " "arguments in %T.", t, context, *constant); } *constant = 0; DMC_PUSH(*text, matchSetReturnTrace); /* Pushes 'true' on the stack */ if (++context->stack_used > context->stack_need) context->stack_need = context->stack_used; return retOk; } static DMCRet dmc_exception_trace(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); if (!(context->cflags & DCOMP_TRACE)) { RETURN_ERROR("Special form 'exception_trace' used in wrong dialect.", context, *constant); } if (context->is_guard) { RETURN_ERROR("Special form 'exception_trace' called in " "guard context.", context, *constant); } if (p[0] != make_arityval(1)) { RETURN_TERM_ERROR("Special form 'exception_trace' called with " "arguments in %T.", t, context, *constant); } *constant = 0; DMC_PUSH(*text, matchSetExceptionTrace); /* Pushes 'true' on the stack */ if (++context->stack_used > context->stack_need) context->stack_need = context->stack_used; return retOk; } static int check_trace(const char* op, DMCContext *context, int *constant, int need_cflags, int allow_in_guard, DMCRet* retp) { if (!(context->cflags & DCOMP_TRACE)) { *retp = RETURN_ERROR_X(-1, context, *constant, "Special form '%s' " "used in wrong dialect.", op); return 0; } if ((context->cflags & need_cflags) != need_cflags) { *retp = RETURN_ERROR_X(-1, context, *constant, "Special form '%s' " "not allow for this trace event.", op); return 0; } if (context->is_guard && !allow_in_guard) { *retp = RETURN_ERROR_X(-1, context, *constant, "Special form '%s' " "called in guard context.", op); return 0; } return 1; } static DMCRet dmc_is_seq_trace(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); DMCRet ret; if (!check_trace("is_seq_trace", context, constant, DCOMP_ALLOW_TRACE_OPS, 1, &ret)) return ret; if (p[0] != make_arityval(1)) { RETURN_TERM_ERROR("Special form 'is_seq_trace' called with " "arguments in %T.", t, context, *constant); } *constant = 0; DMC_PUSH(*text, matchIsSeqTrace); /* Pushes 'true' or 'false' on the stack */ if (++context->stack_used > context->stack_need) context->stack_need = context->stack_used; return retOk; } static DMCRet dmc_set_seq_token(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); DMCRet ret; int c; if (!check_trace("set_seq_trace", context, constant, DCOMP_ALLOW_TRACE_OPS, 0, &ret)) return ret; if (p[0] != make_arityval(3)) { RETURN_TERM_ERROR("Special form 'set_seq_token' called with wrong " "number of arguments in %T.", t, context, *constant); } *constant = 0; if ((ret = dmc_expr(context, heap, text, p[3], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[3]); } if ((ret = dmc_expr(context, heap, text, p[2], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[2]); } if (context->cflags & DCOMP_FAKE_DESTRUCTIVE) { DMC_PUSH(*text, matchSetSeqTokenFake); } else { DMC_PUSH(*text, matchSetSeqToken); } --context->stack_used; /* Remove two and add one */ return retOk; } static DMCRet dmc_get_seq_token(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); DMCRet ret; if (!check_trace("get_seq_token", context, constant, DCOMP_ALLOW_TRACE_OPS, 0, &ret)) return ret; if (p[0] != make_arityval(1)) { RETURN_TERM_ERROR("Special form 'get_seq_token' called with " "arguments in %T.", t, context, *constant); } *constant = 0; DMC_PUSH(*text, matchGetSeqToken); if (++context->stack_used > context->stack_need) context->stack_need = context->stack_used; return retOk; } static DMCRet dmc_display(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); DMCRet ret; int c; if (!(context->cflags & DCOMP_TRACE)) { RETURN_ERROR("Special form 'display' used in wrong dialect.", context, *constant); } if (context->is_guard) { RETURN_ERROR("Special form 'display' called in guard context.", context, *constant); } if (p[0] != make_arityval(2)) { RETURN_TERM_ERROR("Special form 'display' called with wrong " "number of arguments in %T.", t, context, *constant); } *constant = 0; if ((ret = dmc_expr(context, heap, text, p[2], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[2]); } DMC_PUSH(*text, matchDisplay); /* Push as much as we remove, stack_need is untouched */ return retOk; } static DMCRet dmc_process_dump(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); DMCRet ret; if (!check_trace("process_dump", context, constant, DCOMP_ALLOW_TRACE_OPS, 0, &ret)) return ret; if (p[0] != make_arityval(1)) { RETURN_TERM_ERROR("Special form 'process_dump' called with " "arguments in %T.", t, context, *constant); } *constant = 0; DMC_PUSH(*text, matchProcessDump); /* Creates binary */ if (++context->stack_used > context->stack_need) context->stack_need = context->stack_used; return retOk; } static DMCRet dmc_enable_trace(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); Uint a = arityval(*p); DMCRet ret; int c; if (!check_trace("enable_trace", context, constant, DCOMP_ALLOW_TRACE_OPS, 0, &ret)) return ret; switch (a) { case 2: *constant = 0; if ((ret = dmc_expr(context, heap, text, p[2], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[2]); } DMC_PUSH(*text, matchEnableTrace); /* Push as much as we remove, stack_need is untouched */ break; case 3: *constant = 0; if ((ret = dmc_expr(context, heap, text, p[3], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[3]); } if ((ret = dmc_expr(context, heap, text, p[2], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[2]); } DMC_PUSH(*text, matchEnableTrace2); --context->stack_used; /* Remove two and add one */ break; default: RETURN_TERM_ERROR("Special form 'enable_trace' called with wrong " "number of arguments in %T.", t, context, *constant); } return retOk; } static DMCRet dmc_disable_trace(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); Uint a = arityval(*p); DMCRet ret; int c; if (!check_trace("disable_trace", context, constant, DCOMP_ALLOW_TRACE_OPS, 0, &ret)) return ret; switch (a) { case 2: *constant = 0; if ((ret = dmc_expr(context, heap, text, p[2], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[2]); } DMC_PUSH(*text, matchDisableTrace); /* Push as much as we remove, stack_need is untouched */ break; case 3: *constant = 0; if ((ret = dmc_expr(context, heap, text, p[3], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[3]); } if ((ret = dmc_expr(context, heap, text, p[2], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[2]); } DMC_PUSH(*text, matchDisableTrace2); --context->stack_used; /* Remove two and add one */ break; default: RETURN_TERM_ERROR("Special form 'disable_trace' called with wrong " "number of arguments in %T.", t, context, *constant); } return retOk; } static DMCRet dmc_trace(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); Uint a = arityval(*p); DMCRet ret; int c; if (!check_trace("trace", context, constant, DCOMP_ALLOW_TRACE_OPS, 0, &ret)) return ret; switch (a) { case 3: *constant = 0; if ((ret = dmc_expr(context, heap, text, p[3], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[3]); } if ((ret = dmc_expr(context, heap, text, p[2], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[2]); } DMC_PUSH(*text, matchTrace2); --context->stack_used; /* Remove two and add one */ break; case 4: *constant = 0; if ((ret = dmc_expr(context, heap, text, p[4], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[4]); } if ((ret = dmc_expr(context, heap, text, p[3], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[3]); } if ((ret = dmc_expr(context, heap, text, p[2], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[2]); } DMC_PUSH(*text, matchTrace3); context->stack_used -= 2; /* Remove three and add one */ break; default: RETURN_TERM_ERROR("Special form 'trace' called with wrong " "number of arguments in %T.", t, context, *constant); } return retOk; } static DMCRet dmc_caller(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); DMCRet ret; if (!check_trace("caller", context, constant, (DCOMP_CALL_TRACE|DCOMP_ALLOW_TRACE_OPS), 0, &ret)) return ret; if (p[0] != make_arityval(1)) { RETURN_TERM_ERROR("Special form 'caller' called with " "arguments in %T.", t, context, *constant); } *constant = 0; DMC_PUSH(*text, matchCaller); /* Creates binary */ if (++context->stack_used > context->stack_need) context->stack_need = context->stack_used; return retOk; } static DMCRet dmc_caller_line(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); DMCRet ret; if (!check_trace("caller_line", context, constant, (DCOMP_CALL_TRACE|DCOMP_ALLOW_TRACE_OPS), 0, &ret)) return ret; if (p[0] != make_arityval(1)) { RETURN_TERM_ERROR("Special form 'caller_line' called with " "arguments in %T.", t, context, *constant); } *constant = 0; DMC_PUSH(*text, matchCallerLine); /* Creates binary */ if (++context->stack_used > context->stack_need) context->stack_need = context->stack_used; return retOk; } static DMCRet dmc_current_stacktrace(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); Uint a = arityval(*p); DMCRet ret; int depth; if (!check_trace("current_stacktrace", context, constant, (DCOMP_CALL_TRACE|DCOMP_ALLOW_TRACE_OPS), 0, &ret)) return ret; switch (a) { case 1: *constant = 0; do_emit_constant(context, text, make_small(erts_backtrace_depth)); DMC_PUSH(*text, matchCurrentStacktrace); break; case 2: *constant = 0; if (!is_small(p[2])) { RETURN_ERROR("Special form 'current_stacktrace' called with non " "small argument.", context, *constant); } depth = signed_val(p[2]); if (depth < 0) { RETURN_ERROR("Special form 'current_stacktrace' called with " "negative integer argument.", context, *constant); } if (depth > erts_backtrace_depth) { p[2] = make_small(erts_backtrace_depth); } do_emit_constant(context, text, p[2]); DMC_PUSH(*text, matchCurrentStacktrace); break; default: RETURN_TERM_ERROR("Special form 'current_stacktrace' called with wrong " "number of arguments in %T.", t, context, *constant); } return retOk; } static DMCRet dmc_silent(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); DMCRet ret; int c; if (!check_trace("silent", context, constant, DCOMP_ALLOW_TRACE_OPS, 0, &ret)) return ret; if (p[0] != make_arityval(2)) { RETURN_TERM_ERROR("Special form 'silent' called with wrong " "number of arguments in %T.", t, context, *constant); } *constant = 0; if ((ret = dmc_expr(context, heap, text, p[2], &c)) != retOk) { return ret; } if (c) { do_emit_constant(context, text, p[2]); } DMC_PUSH(*text, matchSilent); DMC_PUSH(*text, matchPushC); DMC_PUSH(*text, am_true); /* Push as much as we remove, stack_need is untouched */ return retOk; } static DMCRet dmc_fun(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { Eterm *p = tuple_val(t); Uint a = arityval(*p); int c; int i; DMCRet ret; DMCGuardBif *b; /* Special forms. */ switch (p[1]) { case am_const: return dmc_const(context, heap, text, t, constant); case am_and: return dmc_and(context, heap, text, t, constant); case am_or: return dmc_or(context, heap, text, t, constant); case am_andalso: case am_andthen: return dmc_andalso(context, heap, text, t, constant); case am_orelse: return dmc_orelse(context, heap, text, t, constant); case am_self: return dmc_self(context, heap, text, t, constant); case am_message: return dmc_message(context, heap, text, t, constant); case am_is_seq_trace: return dmc_is_seq_trace(context, heap, text, t, constant); case am_set_seq_token: return dmc_set_seq_token(context, heap, text, t, constant); case am_get_seq_token: return dmc_get_seq_token(context, heap, text, t, constant); case am_return_trace: return dmc_return_trace(context, heap, text, t, constant); case am_exception_trace: return dmc_exception_trace(context, heap, text, t, constant); case am_display: return dmc_display(context, heap, text, t, constant); case am_process_dump: return dmc_process_dump(context, heap, text, t, constant); case am_enable_trace: return dmc_enable_trace(context, heap, text, t, constant); case am_disable_trace: return dmc_disable_trace(context, heap, text, t, constant); case am_trace: return dmc_trace(context, heap, text, t, constant); case am_caller: return dmc_caller(context, heap, text, t, constant); case am_caller_line: return dmc_caller_line(context, heap, text, t, constant); case am_current_stacktrace: return dmc_current_stacktrace(context, heap, text, t, constant); case am_silent: return dmc_silent(context, heap, text, t, constant); case am_set_tcw: if (context->cflags & DCOMP_FAKE_DESTRUCTIVE) { b = dmc_lookup_bif(am_set_tcw_fake, ((int) a) - 1); } else { b = dmc_lookup_bif(p[1], ((int) a) - 1); } break; default: b = dmc_lookup_bif(p[1], ((int) a) - 1); } if (b == NULL) { if (context->err_info != NULL) { /* Ugly, should define a better RETURN_TERM_ERROR interface... */ char buff[100]; erts_snprintf(buff, sizeof(buff), "Function %%T/%d does_not_exist.", (int)a - 1); RETURN_TERM_ERROR(buff, p[1], context, *constant); } else { return retFail; } } ASSERT(b->arity == ((int) a) - 1); if (! (b->flags & (1 << ((context->cflags & DCOMP_DIALECT_MASK) + (context->is_guard ? DBIF_GUARD : DBIF_BODY))))) { /* Body clause used in wrong context. */ if (context->err_info != NULL) { /* Ugly, should define a better RETURN_TERM_ERROR interface... */ char buff[100]; erts_snprintf(buff, sizeof(buff), "Function %%T/%d cannot be called in this context.", (int)a - 1); RETURN_TERM_ERROR(buff, p[1], context, *constant); } else { return retFail; } } *constant = 0; for (i = a; i > 1; --i) { if ((ret = dmc_expr(context, heap, text, p[i], &c)) != retOk) return ret; if (c) do_emit_constant(context, text, p[i]); } switch (b->arity) { case 0: DMC_PUSH(*text, matchCall0); break; case 1: DMC_PUSH(*text, matchCall1); break; case 2: DMC_PUSH(*text, matchCall2); break; case 3: DMC_PUSH(*text, matchCall3); break; default: erts_exit(ERTS_ERROR_EXIT,"ets:match() internal error, " "guard with more than 3 arguments."); } DMC_PUSH(*text, (UWord) b->biff); context->stack_used -= (((int) a) - 2); if (context->stack_used > context->stack_need) context->stack_need = context->stack_used; return retOk; } static DMCRet dmc_expr(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm t, int *constant) { DMCRet ret; Eterm tmp; Eterm *p; if (stack_guard(context->stack_limit)) { context->freason = SYSTEM_LIMIT; RETURN_TERM_ERROR("Excessive nesting; system limit reached near: %T", t, context, *constant); } switch (t & _TAG_PRIMARY_MASK) { case TAG_PRIMARY_LIST: if ((ret = dmc_list(context, heap, text, t, constant)) != retOk) return ret; break; case TAG_PRIMARY_BOXED: if (is_map(t)) { return dmc_map(context, heap, text, t, constant); } if (!is_tuple(t)) { goto simple_term; } p = tuple_val(t); #ifdef HARDDEBUG erts_fprintf(stderr,"%d %d %d %d\n",arityval(*p),is_tuple(tmp = p[1]), is_atom(p[1]),db_is_variable(p[1])); #endif if (p[0] == make_arityval(1) && is_tuple(tmp = p[1])) { if ((ret = dmc_tuple(context, heap, text, tmp, constant)) != retOk) return ret; } else if (arityval(*p) >= 1 && is_atom(p[1]) && !(db_is_variable(p[1]) >= 0)) { if ((ret = dmc_fun(context, heap, text, t, constant)) != retOk) return ret; } else RETURN_TERM_ERROR("%T is neither a function call, nor a tuple " "(tuples are written {{ ... }}).", t, context, *constant); break; case TAG_PRIMARY_IMMED1: if (db_is_variable(t) >= 0) { if ((ret = dmc_variable(context, heap, text, t, constant)) != retOk) return ret; break; } else if (t == am_DollarUnderscore) { if ((ret = dmc_whole_expression(context, heap, text, t, constant)) != retOk) return ret; break; } else if (t == am_DollarDollar) { if ((ret = dmc_all_bindings(context, heap, text, t, constant)) != retOk) return ret; break; } /* Fall through */ default: simple_term: *constant = 1; } return retOk; } static DMCRet compile_guard_expr(DMCContext *context, DMCHeap *heap, DMC_STACK_TYPE(UWord) *text, Eterm l) { DMCRet ret; int constant; Eterm t; if (l != NIL) { if (!is_list(l)) RETURN_ERROR("Match expression is not a list.", context, constant); if (!(context->is_guard)) { DMC_PUSH(*text, matchCatch); } while (is_list(l)) { constant = 0; t = CAR(list_val(l)); if ((ret = dmc_expr(context, heap, text, t, &constant)) != retOk) return ret; if (constant) { do_emit_constant(context, text, t); } l = CDR(list_val(l)); if (context->is_guard) { DMC_PUSH(*text,matchTrue); } else { DMC_PUSH(*text,matchWaste); } --context->stack_used; } if (l != NIL) RETURN_ERROR("Match expression is not a proper list.", context, constant); if (!(context->is_guard) && (context->cflags & DCOMP_TABLE)) { ASSERT(matchWaste == DMC_TOP(*text)); (void) DMC_POP(*text); DMC_PUSH(*text, matchReturn); /* Same impact on stack as matchWaste */ } } return retOk; } /* ** Match compilation utility code */ /* ** Handling of bif's in match guard expressions */ static DMCGuardBif *dmc_lookup_bif(Eterm t, int arity) { /* ** Place for optimization, bsearch is slower than inlining it... */ DMCGuardBif node = {0,NULL,0}; node.name = t; node.arity = arity; return bsearch(&node, guard_tab, sizeof(guard_tab) / sizeof(DMCGuardBif), sizeof(DMCGuardBif), (int (*)(const void *, const void *)) &cmp_guard_bif); } #ifdef DMC_DEBUG static Eterm dmc_lookup_bif_reversed(void *f) { int i; for (i = 0; i < (sizeof(guard_tab) / sizeof(DMCGuardBif)); ++i) if (f == guard_tab[i].biff) return guard_tab[i].name; return am_undefined; } #endif /* For sorting. */ static int cmp_uint(void *a, void *b) { if (*((unsigned *)a) < *((unsigned *)b)) return -1; else return (*((unsigned *)a) > *((unsigned *)b)); } static int cmp_guard_bif(void *a, void *b) { int ret; if (( ret = ((int) atom_val(((DMCGuardBif *) a)->name)) - ((int) atom_val(((DMCGuardBif *) b)->name)) ) == 0) { ret = ((DMCGuardBif *) a)->arity - ((DMCGuardBif *) b)->arity; } return ret; } /* ** Compact the variables in a match expression i e make {$1, $100, $1000} ** become {$0,$1,$2}. */ static int match_compact(ErlHeapFragment *expr, DMCErrInfo *err_info) { int i, j, a, n, x; DMC_STACK_TYPE(unsigned) heap; Eterm *p; char buff[25] = "$"; /* large enough for 64 bit to */ int ret; DMC_INIT_STACK(heap); p = expr->mem; i = expr->used_size; while (i--) { if (is_thing(*p)) { a = thing_arityval(*p); ASSERT(a <= i); i -= a; p += a; } else if (is_atom(*p) && (n = db_is_variable(*p)) >= 0) { x = DMC_STACK_NUM(heap); for (j = 0; j < x && DMC_PEEK(heap,j) != n; ++j) ; if (j == x) DMC_PUSH(heap,n); } ++p; } qsort(DMC_STACK_DATA(heap), DMC_STACK_NUM(heap), sizeof(unsigned), (int (*)(const void *, const void *)) &cmp_uint); if (err_info != NULL) { /* lint needs a translation table */ err_info->var_trans = erts_alloc(ERTS_ALC_T_DB_TRANS_TAB, sizeof(unsigned)*DMC_STACK_NUM(heap)); sys_memcpy(err_info->var_trans, DMC_STACK_DATA(heap), DMC_STACK_NUM(heap) * sizeof(unsigned)); err_info->num_trans = DMC_STACK_NUM(heap); } p = expr->mem; i = expr->used_size; while (i--) { if (is_thing(*p)) { a = thing_arityval(*p); i -= a; p += a; } else if (is_atom(*p) && (n = db_is_variable(*p)) >= 0) { x = DMC_STACK_NUM(heap); #ifdef HARDDEBUG erts_fprintf(stderr, "%T"); #endif for (j = 0; j < x && DMC_PEEK(heap,j) != n; ++j) ; ASSERT(j < x); erts_snprintf(buff+1, sizeof(buff) - 1, "%u", (unsigned) j); /* Yes, writing directly into terms, they ARE off heap */ *p = erts_atom_put((byte *) buff, sys_strlen(buff), ERTS_ATOM_ENC_LATIN1, 1); } ++p; } ret = DMC_STACK_NUM(heap); DMC_FREE(heap); return ret; } /* ** Simple size object that takes care of function calls and constant tuples */ static Uint my_size_object(Eterm t, int is_hashmap_node) { Uint sum = 0; Eterm *p; switch (t & _TAG_PRIMARY_MASK) { case TAG_PRIMARY_LIST: sum += 2 + my_size_object(CAR(list_val(t)), 0) + my_size_object(CDR(list_val(t)), 0); break; case TAG_PRIMARY_BOXED: if (is_tuple(t)) { Eterm* tpl = tuple_val(t); Uint i,n; if (is_hashmap_node) { /* hashmap collision node, no matchspec syntax here */ } else if (tpl[0] == make_arityval(1) && is_tuple(tpl[1])) { tpl = tuple_val(tpl[1]); } else if (tpl[0] == make_arityval(2) && tpl[1] == am_const) { sum += size_object(tuple_val(t)[2]); break; } else { erts_exit(ERTS_ERROR_EXIT,"Internal error, sizing unrecognized object in " "(d)ets:match compilation."); } n = arityval(tpl[0]); sum += 1 + n; for (i = 1; i <= n; ++i) sum += my_size_object(tpl[i], 0); break; } else if (is_map(t)) { if (is_flatmap(t)) { Uint n; flatmap_t *mp; mp = (flatmap_t*)flatmap_val(t); /* Calculate size of keys */ p = tuple_val(mp->keys); n = arityval(p[0]); sum += 1 + n; for (int i = 1; i <= n; ++i) sum += my_size_object(p[i], 0); /* Calculate size of values */ p = (Eterm *)mp; n = flatmap_get_size(mp); sum += n + 3; p += 3; /* hdr + size + keys words */ while (n--) { sum += my_size_object(*p++, 0); } } else { Eterm *head = (Eterm *)hashmap_val(t); Eterm hdr = *head; Uint sz; sz = hashmap_bitcount(MAP_HEADER_VAL(hdr)); sum += 1 + sz + header_arity(hdr); head += 1 + header_arity(hdr); while(sz-- > 0) { sum += my_size_object(head[sz], 1); } } break; } /* fall through */ default: sum += size_object(t); break; } return sum; } static Eterm my_copy_struct(Eterm t, Eterm **hp, ErlOffHeap* off_heap, int is_hashmap_node) { Eterm ret = NIL, a, b; Eterm *p; Uint sz; switch (t & _TAG_PRIMARY_MASK) { case TAG_PRIMARY_LIST: a = my_copy_struct(CAR(list_val(t)), hp, off_heap, 0); b = my_copy_struct(CDR(list_val(t)), hp, off_heap, 0); ret = CONS(*hp, a, b); *hp += 2; break; case TAG_PRIMARY_BOXED: if (is_tuple(t)) { Eterm* tpl = tuple_val(t); Uint i,n; Eterm *savep; if (is_hashmap_node) { /* hashmap collision node, no matchspec syntax here */ } else if (tpl[0] == make_arityval(1) && is_tuple(tpl[1])) { /* A {{...}} expression */ tpl = tuple_val(tpl[1]); } else if (tpl[0] == make_arityval(2) && tpl[1] == am_const) { /* A {const, XXX} expression */ b = tpl[2]; sz = size_object(b); ret = copy_struct(b,sz,hp,off_heap); break; } else { erts_exit(ERTS_ERROR_EXIT, "Trying to constant-copy non constant expression " "0x%bex in (d)ets:match compilation.", t); } n = arityval(tpl[0]); if (n == 0) { ret = ERTS_GLOBAL_LIT_EMPTY_TUPLE; } else { savep = *hp; ret = make_tuple(savep); *hp += n + 1; *savep++ = tpl[0]; for(i = 1; i <= n; ++i) *savep++ = my_copy_struct(tpl[i], hp, off_heap, 0); } } else if (is_map(t)) { if (is_flatmap(t)) { Uint i,n; flatmap_t *mp; Eterm *savep; Eterm keys; mp = (flatmap_t*)flatmap_val(t); /* Copy keys */ p = tuple_val(mp->keys); n = arityval(p[0]); if (n == 0) { keys = ERTS_GLOBAL_LIT_EMPTY_TUPLE; } else { savep = *hp; keys = make_tuple(savep); *hp += n + 1; *savep++ = make_arityval(n); for(i = 1; i <= n; ++i) *savep++ = my_copy_struct(p[i], hp, off_heap, 0); } savep = *hp; ret = make_flatmap(savep); n = flatmap_get_size(mp); p = (Eterm *)mp; *hp += n + 3; *savep++ = mp->thing_word; *savep++ = mp->size; *savep++ = keys; p += 3; /* hdr + size + keys words */ for (i = 0; i < n; i++) *savep++ = my_copy_struct(p[i], hp, off_heap, 0); erts_usort_flatmap((flatmap_t*)flatmap_val(ret)); } else { Eterm *head = hashmap_val(t); Eterm hdr = *head; Uint sz; Eterm *savep = *hp; sz = hashmap_bitcount(MAP_HEADER_VAL(hdr)); *hp += 1 + sz + header_arity(hdr); ret = make_hashmap(savep); *savep++ = *head++; /* map header */ if (header_arity(hdr) == 1) *savep++ = *head++; /* map size */ for (int i = 0; i < sz; i++) { *savep++ = my_copy_struct(head[i],hp,off_heap, 1); } } } else { sz = size_object(t); ret = copy_struct(t,sz,hp,off_heap); } break; default: ret = t; } return ret; } /* ** Compiled match bif interface */ /* ** erlang:match_spec_test(MatchAgainst, MatchSpec, Type) -> ** {ok, Return, Flags, Errors} | {error, Errors} ** MatchAgainst -> if Type == trace: list() else tuple() ** MatchSpec -> MatchSpec with body corresponding to Type ** Type -> trace | table (only trace implemented in R5C) ** Return -> if Type == trace TraceReturn else {BodyReturn, VariableBindings} ** TraceReturn -> {true | false | term()} ** BodyReturn -> term() ** VariableBindings -> [term(), ...] ** Errors -> [OneError, ...] ** OneError -> {error, string()} | {warning, string()} ** Flags -> [Flag, ...] ** Flag -> return_trace (currently only flag) */ BIF_RETTYPE match_spec_test_3(BIF_ALIST_3) { Eterm res; #ifdef DMC_DEBUG if (BIF_ARG_3 == ERTS_MAKE_AM("dis")) { test_disassemble_next = 1; BIF_RET(am_true); } else #endif if (BIF_ARG_3 == am_trace) { res = match_spec_test(BIF_P, BIF_ARG_1, BIF_ARG_2, 1); if (is_value(res)) { BIF_RET(res); } } else if (BIF_ARG_3 == am_table) { res = match_spec_test(BIF_P, BIF_ARG_1, BIF_ARG_2, 0); if (is_value(res)) { BIF_RET(res); } } BIF_ERROR(BIF_P, BADARG); } static Eterm match_spec_test(Process *p, Eterm against, Eterm spec, int trace) { Eterm lint_res; Binary *mps; Eterm res; Eterm ret; Eterm flg; Eterm *hp; Uint32 ret_flags; Uint sz; Eterm save_cp; Uint freason; if (trace && !(is_list(against) || against == NIL)) { return THE_NON_VALUE; } if (trace) { const Uint cflags = (DCOMP_TRACE | DCOMP_FAKE_DESTRUCTIVE | DCOMP_CALL_TRACE | DCOMP_ALLOW_TRACE_OPS); lint_res = db_match_set_lint(p, spec, cflags); mps = db_match_set_compile(p, spec, cflags, &freason); } else { const Uint cflags = (DCOMP_TABLE | DCOMP_FAKE_DESTRUCTIVE); lint_res = db_match_set_lint(p, spec, cflags); mps = db_match_set_compile(p, spec, cflags, &freason); } if (mps == NULL) { hp = HAlloc(p,3); ret = TUPLE2(hp, am_error, lint_res); } else { #ifdef DMC_DEBUG if (test_disassemble_next) { test_disassemble_next = 0; db_match_dis(mps); } #endif /* DMC_DEBUG */ if (trace) { Eterm *arr = NULL; int n = 0; if (is_list(against)) { Eterm l = against; do { ++n; l = CDR(list_val(l)); } while (is_list(l)); arr = erts_alloc(ERTS_ALC_T_DB_TMP, sizeof(Eterm) * n); l = against; n = 0; do { arr[n] = CAR(list_val(l)); ++n; l = CDR(list_val(l)); } while (is_list(l)); } save_cp = p->stop[0]; p->stop[0] = NIL; res = erts_match_set_run_trace(p, p, mps, arr, n, ERTS_PAM_COPY_RESULT|ERTS_PAM_IGNORE_TRACE_SILENT, &ret_flags); p->stop[0] = save_cp; if (arr) erts_free(ERTS_ALC_T_DB_TMP, arr); } else { res = erts_match_set_run_ets(p, mps, against, 0, &ret_flags); } /* We are in the context of a BIF, {caller} should return 'undefined' */ if (is_non_value(res)) { res = am_false; } sz = 0; if (ret_flags & MATCH_SET_EXCEPTION_TRACE) sz += 2; if (ret_flags & MATCH_SET_RETURN_TRACE) sz += 2; hp = HAlloc(p, 5 + sz); flg = NIL; if (ret_flags & MATCH_SET_EXCEPTION_TRACE) { flg = CONS(hp, am_exception_trace, flg); hp += 2; } if (ret_flags & MATCH_SET_RETURN_TRACE) { flg = CONS(hp, am_return_trace, flg); hp += 2; } erts_bin_free(mps); ret = TUPLE4(hp, am_ok, res, flg, lint_res); } return ret; } static Eterm seq_trace_fake(Process *p, Eterm arg1) { Eterm result = erl_seq_trace_info(p, arg1); if (!is_non_value(result) && is_tuple(result) && *tuple_val(result) == 2) { return (tuple_val(result))[2]; } return result; } DbTerm* db_alloc_tmp_uncompressed(DbTableCommon* tb, DbTerm* org) { ErlOffHeap tmp_offheap; DbTerm* res = erts_alloc(ERTS_ALC_T_TMP, sizeof(DbTerm) + org->size*sizeof(Eterm)); Eterm* hp = res->tpl; tmp_offheap.first = NULL; db_copy_from_comp(tb, org, &hp, &tmp_offheap); res->first_oh = tmp_offheap.first; res->size = org->size; #ifdef DEBUG_CLONE res->debug_clone = NULL; #endif return res; } void db_free_tmp_uncompressed(DbTerm* obj) { erts_cleanup_offheap_list(obj->first_oh); #ifdef DEBUG_CLONE ASSERT(obj->debug_clone == NULL); #endif erts_free(ERTS_ALC_T_TMP, obj); } Eterm db_match_dbterm_uncompressed(DbTableCommon* tb, Process* c_p, Binary* bprog, DbTerm* obj, enum erts_pam_run_flags flags) { Uint32 dummy; Eterm res; res = db_prog_match(c_p, c_p, bprog, make_tuple(obj->tpl), NULL, 0, flags|ERTS_PAM_CONTIGUOUS_TUPLE, &dummy); return res; } Eterm db_match_dbterm(DbTableCommon* tb, Process* c_p, Binary* bprog, DbTerm* obj, enum erts_pam_run_flags flags) { Eterm res; if (tb->compress) { obj = db_alloc_tmp_uncompressed(tb, obj); } res = db_match_dbterm_uncompressed(tb, c_p, bprog, obj, flags); if (tb->compress) { db_free_tmp_uncompressed(obj); } return res; } #ifdef DMC_DEBUG /* ** Disassemble match program */ void db_match_dis(Binary *bp) { MatchProg *prog = Binary2MatchProg(bp); UWord *t = prog->text; Uint n; Eterm p; int first; ErlHeapFragment *tmp; while (t < prog->prog_end) { switch (*t) { case matchTryMeElse: ++t; n = *t; ++t; erts_printf("TryMeElse\t%beu\n", n); break; case matchArray: ++t; n = *t; ++t; erts_printf("Array\t%beu\n", n); break; case matchArrayBind: ++t; n = *t; ++t; erts_printf("ArrayBind\t%beu\n", n); break; case matchTuple: ++t; n = *t; ++t; erts_printf("Tuple\t%beu\n", n); break; case matchMap: ++t; n = *t; ++t; erts_printf("Map\t%beu\n", n); break; case matchKey: ++t; p = (Eterm) *t; ++t; erts_printf("Key\t%p (%T)\n", t, p); break; case matchPushT: ++t; n = *t; ++t; erts_printf("PushT\t%beu\n", n); break; case matchPushL: ++t; erts_printf("PushL\n"); break; case matchPushM: ++t; n = *t; ++t; erts_printf("PushM\t%beu\n", n); break; case matchPop: ++t; erts_printf("Pop\n"); break; case matchSwap: ++t; erts_printf("Swap\n"); break; case matchBind: ++t; n = *t; ++t; erts_printf("Bind\t%beu\n", n); break; case matchCmp: ++t; n = *t; ++t; erts_printf("Cmp\t%beu\n", n); break; case matchEqBin: ++t; p = (Eterm) *t; ++t; erts_printf("EqBin\t%p (%T)\n", t, p); break; case matchEqRef: ++t; { Uint32 *num; int ri; if (is_ordinary_ref_thing(t)) { ErtsORefThing *rt = (ErtsORefThing *) t; num = rt->num; t += ERTS_REF_THING_SIZE; } else if (is_pid_ref_thing(t)) { ErtsPRefThing *prt = (ErtsPRefThing *) t; num = prt->num; t += ERTS_PID_REF_THING_SIZE; } else { ErtsMRefThing *mrt = (ErtsMRefThing *) t; ASSERT(is_magic_ref_thing(t)); num = mrt->mb->refn; t += ERTS_MAGIC_REF_THING_SIZE; } erts_printf("EqRef\t(%d) {", (int) ERTS_REF_NUMBERS); first = 1; for (ri = 0; ri < ERTS_REF_NUMBERS; ++ri) { if (first) first = 0; else erts_printf(", "); #if defined(ARCH_64) erts_printf("0x%016bex", num[ri]); #else erts_printf("0x%08bex", num[ri]); #endif } } erts_printf("}\n"); break; case matchEqBig: ++t; n = thing_arityval(*t); { Eterm *et = (Eterm *) t; t += n+1; erts_printf("EqBig\t(%d) {", (int) n); first = 1; ++n; while (n--) { if (first) first = 0; else erts_printf(", "); #if defined(ARCH_64) erts_printf("0x%016bex", *et); #else erts_printf("0x%08bex", *et); #endif ++et; } } erts_printf("}\n"); break; case matchEqFloat: ++t; { double num; sys_memcpy(&num,t,sizeof(double)); t += sizeof(double) / sizeof(*t); erts_printf("EqFloat\t%f\n", num); } break; case matchEq: ++t; p = (Eterm) *t; ++t; erts_printf("Eq \t%T\n", p); break; case matchList: ++t; erts_printf("List\n"); break; case matchHalt: ++t; erts_printf("Halt\n"); break; case matchSkip: ++t; erts_printf("Skip\n"); break; case matchPushC: ++t; p = (Eterm) *t; ++t; erts_printf("PushC\t%T\n", p); break; case matchConsA: ++t; erts_printf("ConsA\n"); break; case matchConsB: ++t; erts_printf("ConsB\n"); break; case matchMkTuple: ++t; n = *t; ++t; erts_printf("MkTuple\t%beu\n", n); break; case matchMkFlatMap: ++t; n = *t; ++t; erts_printf("MkFlatMap\t%beu\n", n); break; case matchMkHashMap: ++t; n = *t; ++t; erts_printf("MkHashMap\t%beu\n", n); break; case matchOr: ++t; n = *t; ++t; erts_printf("Or\t%beu\n", n); break; case matchAnd: ++t; n = *t; ++t; erts_printf("And\t%beu\n", n); break; case matchOrElse: ++t; n = *t; ++t; erts_printf("OrElse\t%beu\n", n); break; case matchAndAlso: ++t; n = *t; ++t; erts_printf("AndAlso\t%beu\n", n); break; case matchCall0: ++t; p = dmc_lookup_bif_reversed((void *) *t); ++t; erts_printf("Call0\t%T\n", p); break; case matchCall1: ++t; p = dmc_lookup_bif_reversed((void *) *t); ++t; erts_printf("Call1\t%T\n", p); break; case matchCall2: ++t; p = dmc_lookup_bif_reversed((void *) *t); ++t; erts_printf("Call2\t%T\n", p); break; case matchCall3: ++t; p = dmc_lookup_bif_reversed((void *) *t); ++t; erts_printf("Call3\t%T\n", p); break; case matchPushV: ++t; n = (Uint) *t; ++t; erts_printf("PushV\t%beu\n", n); break; case matchPushVResult: n = (Uint) *++t; ++t; erts_printf("PushVResult\t%beu\n", n); break; case matchTrue: ++t; erts_printf("True\n"); break; case matchPushExpr: ++t; erts_printf("PushExpr\n"); break; case matchPushArrayAsList: ++t; erts_printf("PushArrayAsList\n"); break; case matchPushArrayAsListU: ++t; erts_printf("PushArrayAsListU\n"); break; case matchSelf: ++t; erts_printf("Self\n"); break; case matchWaste: ++t; erts_printf("Waste\n"); break; case matchReturn: ++t; erts_printf("Return\n"); break; case matchProcessDump: ++t; erts_printf("ProcessDump\n"); break; case matchDisplay: ++t; erts_printf("Display\n"); break; case matchIsSeqTrace: ++t; erts_printf("IsSeqTrace\n"); break; case matchSetSeqToken: ++t; erts_printf("SetSeqToken\n"); break; case matchSetSeqTokenFake: ++t; erts_printf("SetSeqTokenFake\n"); break; case matchGetSeqToken: ++t; erts_printf("GetSeqToken\n"); break; case matchSetReturnTrace: ++t; erts_printf("SetReturnTrace\n"); break; case matchSetExceptionTrace: ++t; erts_printf("SetReturnTrace\n"); break; case matchCatch: ++t; erts_printf("Catch\n"); break; case matchEnableTrace: ++t; erts_printf("EnableTrace\n"); break; case matchDisableTrace: ++t; erts_printf("DisableTrace\n"); break; case matchEnableTrace2: ++t; erts_printf("EnableTrace2\n"); break; case matchDisableTrace2: ++t; erts_printf("DisableTrace2\n"); break; case matchTrace2: ++t; erts_printf("Trace2\n"); break; case matchTrace3: ++t; erts_printf("Trace3\n"); break; case matchCaller: ++t; erts_printf("Caller\n"); break; case matchCallerLine: ++t; erts_printf("CallerLine\n"); break; case matchCurrentStacktrace: ++t; erts_printf("CurrentStacktrace\n"); break; default: erts_printf("??? (0x%bpx)\n", *t); ++t; break; } } erts_printf("\n\nterm_save: {"); first = 1; for (tmp = prog->term_save; tmp; tmp = tmp->next) { if (first) first = 0; else erts_printf(", "); erts_printf("%p", tmp); } erts_printf("}\n"); erts_printf("num_bindings: %d\n", prog->num_bindings); erts_printf("heap_size: %beu\n", prog->heap_size); erts_printf("stack_offset: %beu\n", prog->stack_offset); erts_printf("text: %p\n", prog->text); erts_printf("stack_size: %d (words)\n", prog->heap_size-prog->stack_offset); } #endif /* DMC_DEBUG */
884e3610abc3fc6069d5346a623d080207b929a2
8a51a96f61699f0318315ccc89cef39f6866f2b5
/src/include/storage/s_lock.h
c9fa84cc43c9dc27b55525694fb6668d8877e5ac
[ "PostgreSQL" ]
permissive
postgres/postgres
979febf2b41c00090d1256228f768f33e7ef3b6f
b5934bfd6071fed3a38cea0cfaa93afda63d9c0c
refs/heads/master
2023-08-31T00:10:01.373472
2023-08-30T23:07:48
2023-08-30T23:07:48
927,442
13,691
4,807
NOASSERTION
2023-09-09T13:59:15
2010-09-21T11:35:45
C
UTF-8
C
false
false
25,834
h
s_lock.h
/*------------------------------------------------------------------------- * * s_lock.h * Hardware-dependent implementation of spinlocks. * * NOTE: none of the macros in this file are intended to be called directly. * Call them through the hardware-independent macros in spin.h. * * The following hardware-dependent macros must be provided for each * supported platform: * * void S_INIT_LOCK(slock_t *lock) * Initialize a spinlock (to the unlocked state). * * int S_LOCK(slock_t *lock) * Acquire a spinlock, waiting if necessary. * Time out and abort() if unable to acquire the lock in a * "reasonable" amount of time --- typically ~ 1 minute. * Should return number of "delays"; see s_lock.c * * void S_UNLOCK(slock_t *lock) * Unlock a previously acquired lock. * * bool S_LOCK_FREE(slock_t *lock) * Tests if the lock is free. Returns true if free, false if locked. * This does *not* change the state of the lock. * * void SPIN_DELAY(void) * Delay operation to occur inside spinlock wait loop. * * Note to implementors: there are default implementations for all these * macros at the bottom of the file. Check if your platform can use * these or needs to override them. * * Usually, S_LOCK() is implemented in terms of even lower-level macros * TAS() and TAS_SPIN(): * * int TAS(slock_t *lock) * Atomic test-and-set instruction. Attempt to acquire the lock, * but do *not* wait. Returns 0 if successful, nonzero if unable * to acquire the lock. * * int TAS_SPIN(slock_t *lock) * Like TAS(), but this version is used when waiting for a lock * previously found to be contended. By default, this is the * same as TAS(), but on some architectures it's better to poll a * contended lock using an unlocked instruction and retry the * atomic test-and-set only when it appears free. * * TAS() and TAS_SPIN() are NOT part of the API, and should never be called * directly. * * CAUTION: on some platforms TAS() and/or TAS_SPIN() may sometimes report * failure to acquire a lock even when the lock is not locked. For example, * on Alpha TAS() will "fail" if interrupted. Therefore a retry loop must * always be used, even if you are certain the lock is free. * * It is the responsibility of these macros to make sure that the compiler * does not re-order accesses to shared memory to precede the actual lock * acquisition, or follow the lock release. Prior to PostgreSQL 9.5, this * was the caller's responsibility, which meant that callers had to use * volatile-qualified pointers to refer to both the spinlock itself and the * shared data being accessed within the spinlocked critical section. This * was notationally awkward, easy to forget (and thus error-prone), and * prevented some useful compiler optimizations. For these reasons, we * now require that the macros themselves prevent compiler re-ordering, * so that the caller doesn't need to take special precautions. * * On platforms with weak memory ordering, the TAS(), TAS_SPIN(), and * S_UNLOCK() macros must further include hardware-level memory fence * instructions to prevent similar re-ordering at the hardware level. * TAS() and TAS_SPIN() must guarantee that loads and stores issued after * the macro are not executed until the lock has been obtained. Conversely, * S_UNLOCK() must guarantee that loads and stores issued before the macro * have been executed before the lock is released. * * On most supported platforms, TAS() uses a tas() function written * in assembly language to execute a hardware atomic-test-and-set * instruction. Equivalent OS-supplied mutex routines could be used too. * * If no system-specific TAS() is available (ie, HAVE_SPINLOCKS is not * defined), then we fall back on an emulation that uses SysV semaphores * (see spin.c). This emulation will be MUCH MUCH slower than a proper TAS() * implementation, because of the cost of a kernel call per lock or unlock. * An old report is that Postgres spends around 40% of its time in semop(2) * when using the SysV semaphore code. * * * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/include/storage/s_lock.h * *------------------------------------------------------------------------- */ #ifndef S_LOCK_H #define S_LOCK_H #ifdef FRONTEND #error "s_lock.h may not be included from frontend code" #endif #ifdef HAVE_SPINLOCKS /* skip spinlocks if requested */ #if defined(__GNUC__) || defined(__INTEL_COMPILER) /************************************************************************* * All the gcc inlines * Gcc consistently defines the CPU as __cpu__. * Other compilers use __cpu or __cpu__ so we test for both in those cases. */ /*---------- * Standard gcc asm format (assuming "volatile slock_t *lock"): __asm__ __volatile__( " instruction \n" " instruction \n" " instruction \n" : "=r"(_res), "+m"(*lock) // return register, in/out lock value : "r"(lock) // lock pointer, in input register : "memory", "cc"); // show clobbered registers here * The output-operands list (after first colon) should always include * "+m"(*lock), whether or not the asm code actually refers to this * operand directly. This ensures that gcc believes the value in the * lock variable is used and set by the asm code. Also, the clobbers * list (after third colon) should always include "memory"; this prevents * gcc from thinking it can cache the values of shared-memory fields * across the asm code. Add "cc" if your asm code changes the condition * code register, and also list any temp registers the code uses. *---------- */ #ifdef __i386__ /* 32-bit i386 */ #define HAS_TEST_AND_SET typedef unsigned char slock_t; #define TAS(lock) tas(lock) static __inline__ int tas(volatile slock_t *lock) { slock_t _res = 1; /* * Use a non-locking test before asserting the bus lock. Note that the * extra test appears to be a small loss on some x86 platforms and a small * win on others; it's by no means clear that we should keep it. * * When this was last tested, we didn't have separate TAS() and TAS_SPIN() * macros. Nowadays it probably would be better to do a non-locking test * in TAS_SPIN() but not in TAS(), like on x86_64, but no-one's done the * testing to verify that. Without some empirical evidence, better to * leave it alone. */ __asm__ __volatile__( " cmpb $0,%1 \n" " jne 1f \n" " lock \n" " xchgb %0,%1 \n" "1: \n" : "+q"(_res), "+m"(*lock) : /* no inputs */ : "memory", "cc"); return (int) _res; } #define SPIN_DELAY() spin_delay() static __inline__ void spin_delay(void) { /* * This sequence is equivalent to the PAUSE instruction ("rep" is * ignored by old IA32 processors if the following instruction is * not a string operation); the IA-32 Architecture Software * Developer's Manual, Vol. 3, Section 7.7.2 describes why using * PAUSE in the inner loop of a spin lock is necessary for good * performance: * * The PAUSE instruction improves the performance of IA-32 * processors supporting Hyper-Threading Technology when * executing spin-wait loops and other routines where one * thread is accessing a shared lock or semaphore in a tight * polling loop. When executing a spin-wait loop, the * processor can suffer a severe performance penalty when * exiting the loop because it detects a possible memory order * violation and flushes the core processor's pipeline. The * PAUSE instruction provides a hint to the processor that the * code sequence is a spin-wait loop. The processor uses this * hint to avoid the memory order violation and prevent the * pipeline flush. In addition, the PAUSE instruction * de-pipelines the spin-wait loop to prevent it from * consuming execution resources excessively. */ __asm__ __volatile__( " rep; nop \n"); } #endif /* __i386__ */ #ifdef __x86_64__ /* AMD Opteron, Intel EM64T */ #define HAS_TEST_AND_SET typedef unsigned char slock_t; #define TAS(lock) tas(lock) /* * On Intel EM64T, it's a win to use a non-locking test before the xchg proper, * but only when spinning. * * See also Implementing Scalable Atomic Locks for Multi-Core Intel(tm) EM64T * and IA32, by Michael Chynoweth and Mary R. Lee. As of this writing, it is * available at: * http://software.intel.com/en-us/articles/implementing-scalable-atomic-locks-for-multi-core-intel-em64t-and-ia32-architectures */ #define TAS_SPIN(lock) (*(lock) ? 1 : TAS(lock)) static __inline__ int tas(volatile slock_t *lock) { slock_t _res = 1; __asm__ __volatile__( " lock \n" " xchgb %0,%1 \n" : "+q"(_res), "+m"(*lock) : /* no inputs */ : "memory", "cc"); return (int) _res; } #define SPIN_DELAY() spin_delay() static __inline__ void spin_delay(void) { /* * Adding a PAUSE in the spin delay loop is demonstrably a no-op on * Opteron, but it may be of some use on EM64T, so we keep it. */ __asm__ __volatile__( " rep; nop \n"); } #endif /* __x86_64__ */ /* * On ARM and ARM64, we use __sync_lock_test_and_set(int *, int) if available. * * We use the int-width variant of the builtin because it works on more chips * than other widths. */ #if defined(__arm__) || defined(__arm) || defined(__aarch64__) #ifdef HAVE_GCC__SYNC_INT32_TAS #define HAS_TEST_AND_SET #define TAS(lock) tas(lock) typedef int slock_t; static __inline__ int tas(volatile slock_t *lock) { return __sync_lock_test_and_set(lock, 1); } #define S_UNLOCK(lock) __sync_lock_release(lock) /* * Using an ISB instruction to delay in spinlock loops appears beneficial on * high-core-count ARM64 processors. It seems mostly a wash for smaller gear, * and ISB doesn't exist at all on pre-v7 ARM chips. */ #if defined(__aarch64__) #define SPIN_DELAY() spin_delay() static __inline__ void spin_delay(void) { __asm__ __volatile__( " isb; \n"); } #endif /* __aarch64__ */ #endif /* HAVE_GCC__SYNC_INT32_TAS */ #endif /* __arm__ || __arm || __aarch64__ */ /* S/390 and S/390x Linux (32- and 64-bit zSeries) */ #if defined(__s390__) || defined(__s390x__) #define HAS_TEST_AND_SET typedef unsigned int slock_t; #define TAS(lock) tas(lock) static __inline__ int tas(volatile slock_t *lock) { int _res = 0; __asm__ __volatile__( " cs %0,%3,0(%2) \n" : "+d"(_res), "+m"(*lock) : "a"(lock), "d"(1) : "memory", "cc"); return _res; } #endif /* __s390__ || __s390x__ */ #if defined(__sparc__) /* Sparc */ /* * Solaris has always run sparc processors in TSO (total store) mode, but * linux didn't use to and the *BSDs still don't. So, be careful about * acquire/release semantics. The CPU will treat superfluous members as * NOPs, so it's just code space. */ #define HAS_TEST_AND_SET typedef unsigned char slock_t; #define TAS(lock) tas(lock) static __inline__ int tas(volatile slock_t *lock) { slock_t _res; /* * See comment in src/backend/port/tas/sunstudio_sparc.s for why this * uses "ldstub", and that file uses "cas". gcc currently generates * sparcv7-targeted binaries, so "cas" use isn't possible. */ __asm__ __volatile__( " ldstub [%2], %0 \n" : "=r"(_res), "+m"(*lock) : "r"(lock) : "memory"); #if defined(__sparcv7) || defined(__sparc_v7__) /* * No stbar or membar available, luckily no actually produced hardware * requires a barrier. */ #elif defined(__sparcv8) || defined(__sparc_v8__) /* stbar is available (and required for both PSO, RMO), membar isn't */ __asm__ __volatile__ ("stbar \n":::"memory"); #else /* * #LoadStore (RMO) | #LoadLoad (RMO) together are the appropriate acquire * barrier for sparcv8+ upwards. */ __asm__ __volatile__ ("membar #LoadStore | #LoadLoad \n":::"memory"); #endif return (int) _res; } #if defined(__sparcv7) || defined(__sparc_v7__) /* * No stbar or membar available, luckily no actually produced hardware * requires a barrier. We fall through to the default gcc definition of * S_UNLOCK in this case. */ #elif defined(__sparcv8) || defined(__sparc_v8__) /* stbar is available (and required for both PSO, RMO), membar isn't */ #define S_UNLOCK(lock) \ do \ { \ __asm__ __volatile__ ("stbar \n":::"memory"); \ *((volatile slock_t *) (lock)) = 0; \ } while (0) #else /* * #LoadStore (RMO) | #StoreStore (RMO, PSO) together are the appropriate * release barrier for sparcv8+ upwards. */ #define S_UNLOCK(lock) \ do \ { \ __asm__ __volatile__ ("membar #LoadStore | #StoreStore \n":::"memory"); \ *((volatile slock_t *) (lock)) = 0; \ } while (0) #endif #endif /* __sparc__ */ /* PowerPC */ #if defined(__ppc__) || defined(__powerpc__) || defined(__ppc64__) || defined(__powerpc64__) #define HAS_TEST_AND_SET typedef unsigned int slock_t; #define TAS(lock) tas(lock) /* On PPC, it's a win to use a non-locking test before the lwarx */ #define TAS_SPIN(lock) (*(lock) ? 1 : TAS(lock)) /* * The second operand of addi can hold a constant zero or a register number, * hence constraint "=&b" to avoid allocating r0. "b" stands for "address * base register"; most operands having this register-or-zero property are * address bases, e.g. the second operand of lwax. * * NOTE: per the Enhanced PowerPC Architecture manual, v1.0 dated 7-May-2002, * an isync is a sufficient synchronization barrier after a lwarx/stwcx loop. * But if the spinlock is in ordinary memory, we can use lwsync instead for * better performance. * * Ordinarily, we'd code the branches here using GNU-style local symbols, that * is "1f" referencing "1:" and so on. But some people run gcc on AIX with * IBM's assembler as backend, and IBM's assembler doesn't do local symbols. * So hand-code the branch offsets; fortunately, all PPC instructions are * exactly 4 bytes each, so it's not too hard to count. */ static __inline__ int tas(volatile slock_t *lock) { slock_t _t; int _res; __asm__ __volatile__( " lwarx %0,0,%3,1 \n" " cmpwi %0,0 \n" " bne $+16 \n" /* branch to li %1,1 */ " addi %0,%0,1 \n" " stwcx. %0,0,%3 \n" " beq $+12 \n" /* branch to lwsync */ " li %1,1 \n" " b $+12 \n" /* branch to end of asm sequence */ " lwsync \n" " li %1,0 \n" : "=&b"(_t), "=r"(_res), "+m"(*lock) : "r"(lock) : "memory", "cc"); return _res; } /* * PowerPC S_UNLOCK is almost standard but requires a "sync" instruction. * But we can use lwsync instead for better performance. */ #define S_UNLOCK(lock) \ do \ { \ __asm__ __volatile__ (" lwsync \n" ::: "memory"); \ *((volatile slock_t *) (lock)) = 0; \ } while (0) #endif /* powerpc */ #if defined(__mips__) && !defined(__sgi) /* non-SGI MIPS */ #define HAS_TEST_AND_SET typedef unsigned int slock_t; #define TAS(lock) tas(lock) /* * Original MIPS-I processors lacked the LL/SC instructions, but if we are * so unfortunate as to be running on one of those, we expect that the kernel * will handle the illegal-instruction traps and emulate them for us. On * anything newer (and really, MIPS-I is extinct) LL/SC is the only sane * choice because any other synchronization method must involve a kernel * call. Unfortunately, many toolchains still default to MIPS-I as the * codegen target; if the symbol __mips shows that that's the case, we * have to force the assembler to accept LL/SC. * * R10000 and up processors require a separate SYNC, which has the same * issues as LL/SC. */ #if __mips < 2 #define MIPS_SET_MIPS2 " .set mips2 \n" #else #define MIPS_SET_MIPS2 #endif static __inline__ int tas(volatile slock_t *lock) { volatile slock_t *_l = lock; int _res; int _tmp; __asm__ __volatile__( " .set push \n" MIPS_SET_MIPS2 " .set noreorder \n" " .set nomacro \n" " ll %0, %2 \n" " or %1, %0, 1 \n" " sc %1, %2 \n" " xori %1, 1 \n" " or %0, %0, %1 \n" " sync \n" " .set pop " : "=&r" (_res), "=&r" (_tmp), "+R" (*_l) : /* no inputs */ : "memory"); return _res; } /* MIPS S_UNLOCK is almost standard but requires a "sync" instruction */ #define S_UNLOCK(lock) \ do \ { \ __asm__ __volatile__( \ " .set push \n" \ MIPS_SET_MIPS2 \ " .set noreorder \n" \ " .set nomacro \n" \ " sync \n" \ " .set pop " \ : /* no outputs */ \ : /* no inputs */ \ : "memory"); \ *((volatile slock_t *) (lock)) = 0; \ } while (0) #endif /* __mips__ && !__sgi */ #if defined(__hppa) || defined(__hppa__) /* HP PA-RISC */ /* * HP's PA-RISC * * Because LDCWX requires a 16-byte-aligned address, we declare slock_t as a * 16-byte struct. The active word in the struct is whichever has the aligned * address; the other three words just sit at -1. */ #define HAS_TEST_AND_SET typedef struct { int sema[4]; } slock_t; #define TAS_ACTIVE_WORD(lock) ((volatile int *) (((uintptr_t) (lock) + 15) & ~15)) static __inline__ int tas(volatile slock_t *lock) { volatile int *lockword = TAS_ACTIVE_WORD(lock); int lockval; /* * The LDCWX instruction atomically clears the target word and * returns the previous value. Hence, if the instruction returns * 0, someone else has already acquired the lock before we tested * it (i.e., we have failed). * * Notice that this means that we actually clear the word to set * the lock and set the word to clear the lock. This is the * opposite behavior from the SPARC LDSTUB instruction. For some * reason everything that H-P does is rather baroque... * * For details about the LDCWX instruction, see the "Precision * Architecture and Instruction Reference Manual" (09740-90014 of June * 1987), p. 5-38. */ __asm__ __volatile__( " ldcwx 0(0,%2),%0 \n" : "=r"(lockval), "+m"(*lockword) : "r"(lockword) : "memory"); return (lockval == 0); } #define S_UNLOCK(lock) \ do { \ __asm__ __volatile__("" : : : "memory"); \ *TAS_ACTIVE_WORD(lock) = -1; \ } while (0) #define S_INIT_LOCK(lock) \ do { \ volatile slock_t *lock_ = (lock); \ lock_->sema[0] = -1; \ lock_->sema[1] = -1; \ lock_->sema[2] = -1; \ lock_->sema[3] = -1; \ } while (0) #define S_LOCK_FREE(lock) (*TAS_ACTIVE_WORD(lock) != 0) #endif /* __hppa || __hppa__ */ /* * If we have no platform-specific knowledge, but we found that the compiler * provides __sync_lock_test_and_set(), use that. Prefer the int-width * version over the char-width version if we have both, on the rather dubious * grounds that that's known to be more likely to work in the ARM ecosystem. * (But we dealt with ARM above.) */ #if !defined(HAS_TEST_AND_SET) #if defined(HAVE_GCC__SYNC_INT32_TAS) #define HAS_TEST_AND_SET #define TAS(lock) tas(lock) typedef int slock_t; static __inline__ int tas(volatile slock_t *lock) { return __sync_lock_test_and_set(lock, 1); } #define S_UNLOCK(lock) __sync_lock_release(lock) #elif defined(HAVE_GCC__SYNC_CHAR_TAS) #define HAS_TEST_AND_SET #define TAS(lock) tas(lock) typedef char slock_t; static __inline__ int tas(volatile slock_t *lock) { return __sync_lock_test_and_set(lock, 1); } #define S_UNLOCK(lock) __sync_lock_release(lock) #endif /* HAVE_GCC__SYNC_INT32_TAS */ #endif /* !defined(HAS_TEST_AND_SET) */ /* * Default implementation of S_UNLOCK() for gcc/icc. * * Note that this implementation is unsafe for any platform that can reorder * a memory access (either load or store) after a following store. That * happens not to be possible on x86 and most legacy architectures (some are * single-processor!), but many modern systems have weaker memory ordering. * Those that do must define their own version of S_UNLOCK() rather than * relying on this one. */ #if !defined(S_UNLOCK) #define S_UNLOCK(lock) \ do { __asm__ __volatile__("" : : : "memory"); *(lock) = 0; } while (0) #endif #endif /* defined(__GNUC__) || defined(__INTEL_COMPILER) */ /* * --------------------------------------------------------------------- * Platforms that use non-gcc inline assembly: * --------------------------------------------------------------------- */ #if !defined(HAS_TEST_AND_SET) /* We didn't trigger above, let's try here */ #if defined(_AIX) /* AIX */ /* * AIX (POWER) */ #define HAS_TEST_AND_SET #include <sys/atomic_op.h> typedef int slock_t; #define TAS(lock) _check_lock((slock_t *) (lock), 0, 1) #define S_UNLOCK(lock) _clear_lock((slock_t *) (lock), 0) #endif /* _AIX */ /* These are in sunstudio_(sparc|x86).s */ #if defined(__SUNPRO_C) && (defined(__i386) || defined(__x86_64__) || defined(__sparc__) || defined(__sparc)) #define HAS_TEST_AND_SET #if defined(__i386) || defined(__x86_64__) || defined(__sparcv9) || defined(__sparcv8plus) typedef unsigned int slock_t; #else typedef unsigned char slock_t; #endif extern slock_t pg_atomic_cas(volatile slock_t *lock, slock_t with, slock_t cmp); #define TAS(a) (pg_atomic_cas((a), 1, 0) != 0) #endif #ifdef _MSC_VER typedef LONG slock_t; #define HAS_TEST_AND_SET #define TAS(lock) (InterlockedCompareExchange(lock, 1, 0)) #define SPIN_DELAY() spin_delay() /* If using Visual C++ on Win64, inline assembly is unavailable. * Use a _mm_pause intrinsic instead of rep nop. */ #if defined(_WIN64) static __forceinline void spin_delay(void) { _mm_pause(); } #else static __forceinline void spin_delay(void) { /* See comment for gcc code. Same code, MASM syntax */ __asm rep nop; } #endif #include <intrin.h> #pragma intrinsic(_ReadWriteBarrier) #define S_UNLOCK(lock) \ do { _ReadWriteBarrier(); (*(lock)) = 0; } while (0) #endif #endif /* !defined(HAS_TEST_AND_SET) */ /* Blow up if we didn't have any way to do spinlocks */ #ifndef HAS_TEST_AND_SET #error PostgreSQL does not have native spinlock support on this platform. To continue the compilation, rerun configure using --disable-spinlocks. However, performance will be poor. Please report this to pgsql-bugs@lists.postgresql.org. #endif #else /* !HAVE_SPINLOCKS */ /* * Fake spinlock implementation using semaphores --- slow and prone * to fall foul of kernel limits on number of semaphores, so don't use this * unless you must! The subroutines appear in spin.c. */ typedef int slock_t; extern bool s_lock_free_sema(volatile slock_t *lock); extern void s_unlock_sema(volatile slock_t *lock); extern void s_init_lock_sema(volatile slock_t *lock, bool nested); extern int tas_sema(volatile slock_t *lock); #define S_LOCK_FREE(lock) s_lock_free_sema(lock) #define S_UNLOCK(lock) s_unlock_sema(lock) #define S_INIT_LOCK(lock) s_init_lock_sema(lock, false) #define TAS(lock) tas_sema(lock) #endif /* HAVE_SPINLOCKS */ /* * Default Definitions - override these above as needed. */ #if !defined(S_LOCK) #define S_LOCK(lock) \ (TAS(lock) ? s_lock((lock), __FILE__, __LINE__, __func__) : 0) #endif /* S_LOCK */ #if !defined(S_LOCK_FREE) #define S_LOCK_FREE(lock) (*(lock) == 0) #endif /* S_LOCK_FREE */ #if !defined(S_UNLOCK) /* * Our default implementation of S_UNLOCK is essentially *(lock) = 0. This * is unsafe if the platform can reorder a memory access (either load or * store) after a following store; platforms where this is possible must * define their own S_UNLOCK. But CPU reordering is not the only concern: * if we simply defined S_UNLOCK() as an inline macro, the compiler might * reorder instructions from inside the critical section to occur after the * lock release. Since the compiler probably can't know what the external * function s_unlock is doing, putting the same logic there should be adequate. * A sufficiently-smart globally optimizing compiler could break that * assumption, though, and the cost of a function call for every spinlock * release may hurt performance significantly, so we use this implementation * only for platforms where we don't know of a suitable intrinsic. For the * most part, those are relatively obscure platform/compiler combinations to * which the PostgreSQL project does not have access. */ #define USE_DEFAULT_S_UNLOCK extern void s_unlock(volatile slock_t *lock); #define S_UNLOCK(lock) s_unlock(lock) #endif /* S_UNLOCK */ #if !defined(S_INIT_LOCK) #define S_INIT_LOCK(lock) S_UNLOCK(lock) #endif /* S_INIT_LOCK */ #if !defined(SPIN_DELAY) #define SPIN_DELAY() ((void) 0) #endif /* SPIN_DELAY */ #if !defined(TAS) extern int tas(volatile slock_t *lock); /* in port/.../tas.s, or * s_lock.c */ #define TAS(lock) tas(lock) #endif /* TAS */ #if !defined(TAS_SPIN) #define TAS_SPIN(lock) TAS(lock) #endif /* TAS_SPIN */ extern PGDLLIMPORT slock_t dummy_spinlock; /* * Platform-independent out-of-line support routines */ extern int s_lock(volatile slock_t *lock, const char *file, int line, const char *func); /* Support for dynamic adjustment of spins_per_delay */ #define DEFAULT_SPINS_PER_DELAY 100 extern void set_spins_per_delay(int shared_spins_per_delay); extern int update_spins_per_delay(int shared_spins_per_delay); /* * Support for spin delay which is useful in various places where * spinlock-like procedures take place. */ typedef struct { int spins; int delays; int cur_delay; const char *file; int line; const char *func; } SpinDelayStatus; static inline void init_spin_delay(SpinDelayStatus *status, const char *file, int line, const char *func) { status->spins = 0; status->delays = 0; status->cur_delay = 0; status->file = file; status->line = line; status->func = func; } #define init_local_spin_delay(status) init_spin_delay(status, __FILE__, __LINE__, __func__) extern void perform_spin_delay(SpinDelayStatus *status); extern void finish_spin_delay(SpinDelayStatus *status); #endif /* S_LOCK_H */
d6053a65156be26b0de398d519fc325ba4ed25d8
9ceacf33fd96913cac7ef15492c126d96cae6911
/usr.sbin/hostapd/apme.c
d478eac7c5da8dfbf96d708951078a79879b0a81
[]
no_license
openbsd/src
ab97ef834fd2d5a7f6729814665e9782b586c130
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
refs/heads/master
2023-09-02T18:54:56.624627
2023-09-02T15:16:12
2023-09-02T15:16:12
66,966,208
3,394
1,235
null
2023-08-08T02:42:25
2016-08-30T18:18:25
C
UTF-8
C
false
false
12,374
c
apme.c
/* $OpenBSD: apme.c,v 1.17 2019/05/10 01:29:31 guenther Exp $ */ /* * Copyright (c) 2004, 2005 Reyk Floeter <reyk@openbsd.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/param.h> /* roundup isclr */ #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/uio.h> #include <net/if.h> #include <net/if_media.h> #include <net/if_arp.h> #include <net/if_llc.h> #include <net/bpf.h> #include <netinet/in.h> #include <netinet/if_ether.h> #include <arpa/inet.h> #include <net80211/ieee80211_radiotap.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <limits.h> #include "hostapd.h" #include "iapp.h" void hostapd_apme_frame(struct hostapd_apme *, u_int8_t *, u_int); void hostapd_apme_hopper(int, short, void *); int hostapd_apme_add(struct hostapd_config *cfg, const char *name) { struct hostapd_apme *apme; if (hostapd_apme_lookup(cfg, name) != NULL) return (EEXIST); if ((apme = (struct hostapd_apme *) calloc(1, sizeof(struct hostapd_apme))) == NULL) return (ENOMEM); if (strlcpy(apme->a_iface, name, sizeof(apme->a_iface)) >= sizeof(apme->a_iface)) { free(apme); return (EINVAL); } apme->a_cfg = cfg; apme->a_chanavail = NULL; TAILQ_INSERT_TAIL(&cfg->c_apmes, apme, a_entries); hostapd_log(HOSTAPD_LOG_DEBUG, "%s: Host AP interface added", apme->a_iface); return (0); } int hostapd_apme_deauth(struct hostapd_apme *apme) { struct hostapd_config *cfg = (struct hostapd_config *)apme->a_cfg; struct hostapd_iapp *iapp = &cfg->c_iapp; u_int8_t buf[sizeof(struct ieee80211_frame) + sizeof(u_int16_t)]; struct ieee80211_frame *wh; bzero(&buf, sizeof(buf)); wh = (struct ieee80211_frame *)&buf[0]; wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_DEAUTH; wh->i_fc[1] = IEEE80211_FC1_DIR_NODS; memset(&wh->i_addr1, 0xff, IEEE80211_ADDR_LEN); bcopy(apme->a_bssid, wh->i_addr2, IEEE80211_ADDR_LEN); bcopy(apme->a_bssid, wh->i_addr3, IEEE80211_ADDR_LEN); *(u_int16_t *)(wh + 1) = htole16(IEEE80211_REASON_AUTH_EXPIRE); if (write(apme->a_raw, buf, sizeof(buf)) == -1) { hostapd_log(HOSTAPD_LOG_VERBOSE, "%s/%s: failed to deauthenticate all stations: %s", iapp->i_iface, apme->a_iface, strerror(errno)); return (EIO); } hostapd_log(HOSTAPD_LOG_VERBOSE, "%s/%s: deauthenticated all stations", apme->a_iface, iapp->i_iface); return (0); } struct hostapd_apme * hostapd_apme_lookup(struct hostapd_config *cfg, const char *name) { struct hostapd_apme *apme; TAILQ_FOREACH(apme, &cfg->c_apmes, a_entries) { if (strcmp(name, apme->a_iface) == 0) return (apme); } return (NULL); } struct hostapd_apme * hostapd_apme_addhopper(struct hostapd_config *cfg, const char *name) { struct hostapd_apme *apme; if ((apme = hostapd_apme_lookup(cfg, name)) == NULL) return (NULL); if (apme->a_chanavail != NULL) return (NULL); apme->a_curchan = IEEE80211_CHAN_MAX; apme->a_maxchan = roundup(IEEE80211_CHAN_MAX, NBBY); if ((apme->a_chanavail = (u_int8_t *) calloc(apme->a_maxchan, sizeof(u_int8_t))) == NULL) return (NULL); memset(apme->a_chanavail, 0xff, apme->a_maxchan * sizeof(u_int8_t)); (void)strlcpy(apme->a_chanreq.i_name, apme->a_iface, IFNAMSIZ); return (apme); } void hostapd_apme_sethopper(struct hostapd_apme *apme, int now) { struct hostapd_config *cfg = (struct hostapd_config *)apme->a_cfg; struct timeval tv; bzero(&tv, sizeof(tv)); if (!now) bcopy(&cfg->c_apme_hopdelay, &tv, sizeof(tv)); if (!evtimer_initialized(&apme->a_chanev)) evtimer_set(&apme->a_chanev, hostapd_apme_hopper, apme); if (evtimer_add(&apme->a_chanev, &tv) == -1) hostapd_fatal("failed to add hopper event"); } void hostapd_apme_hopper(int fd, short sig, void *arg) { struct hostapd_apme *apme = (struct hostapd_apme *)arg; struct hostapd_config *cfg = (struct hostapd_config *)apme->a_cfg; int ret; if (apme->a_curchan >= IEEE80211_CHAN_MAX) apme->a_curchan = 0; do { if (apme->a_curchan >= IEEE80211_CHAN_MAX) return; apme->a_curchan %= IEEE80211_CHAN_MAX; apme->a_curchan++; } while (isclr(apme->a_chanavail, apme->a_curchan)); apme->a_chanreq.i_channel = apme->a_curchan; if ((ret = ioctl(cfg->c_apme_ctl, SIOCS80211CHANNEL, &apme->a_chanreq)) != 0) { hostapd_apme_sethopper(apme, 1); return; } hostapd_log(HOSTAPD_LOG_DEBUG, "[priv]: %s setting to channel %d", apme->a_iface, apme->a_curchan); hostapd_apme_sethopper(apme, 0); } void hostapd_apme_term(struct hostapd_apme *apme) { struct hostapd_config *cfg = (struct hostapd_config *)apme->a_cfg; /* Remove the channel hopper, if active */ if (apme->a_chanavail != NULL) { (void)event_del(&apme->a_chanev); free(apme->a_chanavail); apme->a_chanavail = NULL; } /* Kick a specified Host AP interface */ (void)event_del(&apme->a_ev); if (close(apme->a_raw)) hostapd_fatal("failed to close: %s\n", strerror(errno)); TAILQ_REMOVE(&cfg->c_apmes, apme, a_entries); /* Remove all dynamic roaming addresses */ if (cfg->c_flags & HOSTAPD_CFG_F_PRIV) hostapd_roaming_term(apme); hostapd_log(HOSTAPD_LOG_DEBUG, "%s: Host AP interface removed", apme->a_iface); free(apme); } void hostapd_apme_input(int fd, short sig, void *arg) { struct hostapd_apme *apme = (struct hostapd_apme *)arg; u_int8_t buf[IAPP_MAXSIZE], *bp, *ep; struct bpf_hdr *bph; ssize_t len; /* Ignore invalid signals */ if (sig != EV_READ) return; bzero(&buf, sizeof(buf)); if ((len = read(fd, buf, sizeof(buf))) < (ssize_t)sizeof(struct ieee80211_frame)) return; /* * Loop through each frame. */ bp = (u_int8_t *)&buf; ep = bp + len; while (bp < ep) { register u_int caplen, hdrlen; bph = (struct bpf_hdr *)bp; caplen = bph->bh_caplen; hdrlen = bph->bh_hdrlen; /* Process frame */ hostapd_apme_frame(apme, bp + hdrlen, caplen); bp += BPF_WORDALIGN(caplen + hdrlen); } } int hostapd_apme_output(struct hostapd_apme *apme, struct hostapd_ieee80211_frame *frame) { struct iovec iov[2]; int iovcnt; struct ieee80211_frame wh; bzero(&wh, sizeof(wh)); switch (frame->i_fc[1] & IEEE80211_FC1_DIR_MASK) { case IEEE80211_FC1_DIR_NODS: bcopy(frame->i_from, wh.i_addr2, IEEE80211_ADDR_LEN); bcopy(frame->i_to, wh.i_addr1, IEEE80211_ADDR_LEN); bcopy(frame->i_bssid, wh.i_addr3, IEEE80211_ADDR_LEN); break; case IEEE80211_FC1_DIR_TODS: bcopy(frame->i_from, wh.i_addr2, IEEE80211_ADDR_LEN); bcopy(frame->i_to, wh.i_addr3, IEEE80211_ADDR_LEN); bcopy(frame->i_bssid, wh.i_addr1, IEEE80211_ADDR_LEN); break; case IEEE80211_FC1_DIR_FROMDS: bcopy(frame->i_from, wh.i_addr3, IEEE80211_ADDR_LEN); bcopy(frame->i_to, wh.i_addr1, IEEE80211_ADDR_LEN); bcopy(frame->i_bssid, wh.i_addr2, IEEE80211_ADDR_LEN); break; default: case IEEE80211_FC1_DIR_DSTODS: return (EINVAL); } wh.i_fc[0] = IEEE80211_FC0_VERSION_0 | frame->i_fc[0]; wh.i_fc[1] = frame->i_fc[1]; bcopy(frame->i_dur, wh.i_dur, sizeof(wh.i_dur)); bcopy(frame->i_seq, wh.i_seq, sizeof(wh.i_seq)); iovcnt = 1; iov[0].iov_base = &wh; iov[0].iov_len = sizeof(struct ieee80211_frame); if (frame->i_data != NULL && frame->i_data_len > 0) { iovcnt = 2; iov[1].iov_base = frame->i_data; iov[1].iov_len = frame->i_data_len; } if (writev(apme->a_raw, iov, iovcnt) == -1) return (errno); return (0); } int hostapd_apme_offset(struct hostapd_apme *apme, u_int8_t *buf, const u_int len) { struct hostapd_config *cfg = (struct hostapd_config *)apme->a_cfg; struct ieee80211_radiotap_header *rh; u_int rh_len; if (cfg->c_apme_dlt == DLT_IEEE802_11) return (0); else if (cfg->c_apme_dlt != DLT_IEEE802_11_RADIO) return (-1); if (len < sizeof(struct ieee80211_radiotap_header)) return (-1); rh = (struct ieee80211_radiotap_header*)buf; rh_len = letoh16(rh->it_len); if (rh->it_version != 0) return (-1); if (len <= rh_len) return (-1); return ((int)rh_len); } void hostapd_apme_frame(struct hostapd_apme *apme, u_int8_t *buf, u_int len) { struct hostapd_config *cfg = (struct hostapd_config *)apme->a_cfg; struct hostapd_iapp *iapp = &cfg->c_iapp; struct hostapd_apme *other_apme; struct hostapd_node node; struct ieee80211_frame *wh; int offset; if ((offset = hostapd_apme_offset(apme, buf, len)) < 0) return; wh = (struct ieee80211_frame *)(buf + offset); /* Ignore short frames or fragments */ if (len < sizeof(struct ieee80211_frame)) return; /* Handle received frames */ if ((hostapd_handle_input(apme, buf, len) == (HOSTAPD_FRAME_F_RET_SKIP >> HOSTAPD_FRAME_F_RET_S)) || cfg->c_flags & HOSTAPD_CFG_F_IAPP_PASSIVE) return; /* * Only accept local association response frames, ... */ if (!((wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_NODS && (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_MGT && (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_ASSOC_RESP)) return; /* * ...sent by the Host AP (addr2) to our BSSID (addr3) */ if (bcmp(wh->i_addr2, apme->a_bssid, IEEE80211_ADDR_LEN) != 0 || bcmp(wh->i_addr3, apme->a_bssid, IEEE80211_ADDR_LEN) != 0) return; cfg->c_stats.cn_rx_apme++; /* * Double-check if the station got associated to our Host AP */ bcopy(wh->i_addr1, node.ni_macaddr, IEEE80211_ADDR_LEN); if (hostapd_priv_apme_getnode(apme, &node) != 0) { hostapd_log(HOSTAPD_LOG_DEBUG, "%s: invalid association from %s on the Host AP", apme->a_iface, etheraddr_string(wh->i_addr1)); return; } cfg->c_stats.cn_tx_apme++; /* * Delete node on other attached Host APs */ TAILQ_FOREACH(other_apme, &cfg->c_apmes, a_entries) { if (apme == other_apme) continue; if (iapp->i_flags & HOSTAPD_IAPP_F_ROAMING) (void)hostapd_roaming_del(other_apme, &node); if (hostapd_apme_delnode(other_apme, &node) == 0) cfg->c_stats.cn_tx_apme++; } if (iapp->i_flags & HOSTAPD_IAPP_F_ROAMING) (void)hostapd_roaming_add(apme, &node); (void)hostapd_iapp_add_notify(apme, &node); } void hostapd_apme_init(struct hostapd_apme *apme) { struct hostapd_config *cfg = (struct hostapd_config *)apme->a_cfg; u_int i, dlt; struct ifreq ifr; apme->a_raw = hostapd_bpf_open(O_RDWR); apme->a_rawlen = IAPP_MAXSIZE; if (ioctl(apme->a_raw, BIOCSBLEN, &apme->a_rawlen) == -1) hostapd_fatal("failed to set BPF buffer len \"%s\": %s\n", apme->a_iface, strerror(errno)); i = 1; if (ioctl(apme->a_raw, BIOCIMMEDIATE, &i) == -1) hostapd_fatal("failed to set BPF immediate mode on \"%s\": " "%s\n", apme->a_iface, strerror(errno)); bzero(&ifr, sizeof(struct ifreq)); (void)strlcpy(ifr.ifr_name, apme->a_iface, sizeof(ifr.ifr_name)); /* This may fail, ignore it */ (void)ioctl(apme->a_raw, BIOCPROMISC, NULL); /* Associate the wireless network interface to the BPF descriptor */ if (ioctl(apme->a_raw, BIOCSETIF, &ifr) == -1) hostapd_fatal("failed to set BPF interface \"%s\": %s\n", apme->a_iface, strerror(errno)); dlt = cfg->c_apme_dlt; if (ioctl(apme->a_raw, BIOCSDLT, &dlt) == -1) hostapd_fatal("failed to set BPF link type on \"%s\": %s\n", apme->a_iface, strerror(errno)); /* Lock the BPF descriptor, no further configuration */ if (ioctl(apme->a_raw, BIOCLOCK, NULL) == -1) hostapd_fatal("failed to lock BPF interface on \"%s\": %s\n", apme->a_iface, strerror(errno)); } int hostapd_apme_addnode(struct hostapd_apme *apme, struct hostapd_node *node) { return (hostapd_priv_apme_setnode(apme, node, 1)); } int hostapd_apme_delnode(struct hostapd_apme *apme, struct hostapd_node *node) { return (hostapd_priv_apme_setnode(apme, node, 0)); }
734e7e227b9a8076370acd14d61f2b007dd54072
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/security/openvas/files/patch-src_openvas.c
cf3bb71d80269074c5461608187a9d9ecd05f1b3
[ "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
804
c
patch-src_openvas.c
--- src/openvas.c 2022-07-31 21:26:36.888737000 -0500 +++ src/openvas.c 2022-07-31 21:28:05.607778000 -0500 @@ -44,7 +44,7 @@ #include "sighand.h" /* for openvas_signal */ #include "utils.h" /* for store_file */ -#include <bsd/unistd.h> /* for proctitle_init */ +#include <unistd.h> /* for proctitle_init */ #include <errno.h> /* for errno() */ #include <fcntl.h> /* for open() */ #include <gcrypt.h> /* for gcry_control */ @@ -468,11 +468,19 @@ * @param argv Argument vector. */ int +#if defined(__FreeBSD__) +openvas (int argc, char *argv[]) + +{ + int err; +#else openvas (int argc, char *argv[], char *env[]) + { int err; setproctitle_init (argc, argv, env); +#endif gcrypt_init (); static gboolean display_version = FALSE;
d24769fe4ab5093762454d8fc17f8364a7f6745e
29f2c40392489fc1656010f2c9b384fd0b090847
/play/tests/micro/infinite-6.c
c27ff04ee27eb94361f9906f01ef0bcc5bae2eb0
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
seahorn/seahorn
6498777c0d12716379035c0bc102b9baec6f28f9
2bab7831960766a0a16f149adcdce55f0651eb8f
refs/heads/main
2023-08-25T13:51:48.354660
2023-08-11T00:48:27
2023-08-14T16:43:13
31,487,486
423
126
NOASSERTION
2023-09-08T21:30:09
2015-03-01T05:08:17
C
UTF-8
C
false
false
377
c
infinite-6.c
extern int __VERIFIER_NONDET(); extern void __VERIFIER_assume(int); extern void __VERIFIER_error(void); void assert (int v) {if (!v) __VERIFIER_error ();} int main(){ int x=0; int y=0; while (__VERIFIER_NONDET()) { if (__VERIFIER_NONDET()) { x = x+1; y = y+2; } else{ x = x+2; y = y+1; } } assert (x>=0); return 42; }
aecfcdea8d7ff4d5b47f5b59373468e883084c9e
ecea7c1f53661a57736d9b3f6deec97712ff22fc
/SecurityExploits/Apache/Struts/CVE-2018-11776/struts-attacker/src/utils.h
5f3da5f3b11d897defe659f5f7a67fcdd6a5f0a0
[ "MIT" ]
permissive
github/securitylab
088d785622a1a1e86fa171f9296d2a66542bc88f
80e2d6abadad8cb77e8c9f659e32eaee6b3a98ed
refs/heads/main
2023-09-03T04:21:06.795016
2023-07-06T15:31:30
2023-07-06T15:31:30
221,101,274
1,079
225
MIT
2023-08-16T16:41:27
2019-11-12T01:14:24
C
UTF-8
C
false
false
127
h
utils.h
int escape_forward_slash(char* dst, size_t dstlen, const char* src); int urlencode(char* dst, size_t dstlen, const char* src);
dd171c272323cc82aacf22e6706a4901f8df636f
aa3befea459382dc5c01c925653d54f435b3fb0f
/boards/arm/sam34/flipnclick-sam3x/src/sam_spi0.c
585b4cb5f555ebfc01f227ad33791fd2c47d8dfb
[ "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
7,329
c
sam_spi0.c
/**************************************************************************** * boards/arm/sam34/flipnclick-sam3x/src/sam_spi0.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include <stdbool.h> #include <assert.h> #include <debug.h> #include <errno.h> #include <nuttx/spi/spi.h> #include <arch/board/board.h> #include "arm_internal.h" #include "chip.h" #include "sam_gpio.h" #include "sam_spi.h" #include "flipnclick-sam3x.h" #ifdef CONFIG_SAM34_SPI0 /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: sam_spidev_initialize * * Description: * Called to configure SPI chip select GPIO pins for the SAM4E-EK board. * ****************************************************************************/ void weak_function sam_spidev_initialize(void) { #ifdef HAVE_SSD1306 /* Configure the SSD1306 chip select and command/data GPIOs */ sam_configgpio(GPIO_SSD1306_CS); sam_configgpio(GPIO_SSD1306_DC); #endif } /**************************************************************************** * Name: sam_spi0select, sam_spi0status, and sam_spic0mddata * * Description: * These external functions must be provided by board-specific logic. * They include: * * o sam_spi0select is a functions tomanage the board-specific chip selects * o sam_spi0status and sam_spic0mddata: Implementations of the status * and cmddata methods of the SPI interface defined by struct spi_ops_ * (see include/nuttx/spi/spi.h). All other methods including * sam_spibus_initialize()) are provided by common SAM3/4 logic. * * To use this common SPI logic on your board: * * 1. Provide logic in sam_boardinitialize() to configure SPI chip select * pins. * 2. Provide sam_spi0select() and sam_spi0status() functions in your * board- specific logic. These functions will perform chip selection * and status operations using GPIOs in the way your board is * configured. * 2. If CONFIG_SPI_CMDDATA is defined in the NuttX configuration, provide * sam_spic0mddata() functions in your board-specific logic. This * function will perform cmd/data selection operations using GPIOs in * the way your board is configured. * 3. Add a call to sam_spibus_initialize() in your low level application * initialization logic * 4. The handle returned by sam_spibus_initialize() may then be used to * bind the SPI driver to higher level logic (e.g., calling * mmcsd_spislotinitialize(), for example, will bind the SPI driver to * the SPI MMC/SD driver). * ****************************************************************************/ /**************************************************************************** * Name: sam_spi0select * * Description: * PIO chip select pins may be programmed by the board specific logic in * one of two different ways. First, the pins may be programmed as SPI * peripherals. In that case, the pins are completely controlled by the * SPI driver. This method still needs to be provided, but it may be only * a stub. * * An alternative way to program the PIO chip select pins is as a normal * GPIO output. In that case, the automatic control of the CS pins is * bypassed and this function must provide control of the chip select. * NOTE: In this case, the GPIO output pin does *not* have to be the * same as the NPCS pin normal associated with the chip select number. * * Input Parameters: * devid - Identifies the (logical) device * selected - TRUE:Select the device, FALSE:De-select the device * * Returned Value: * None * ****************************************************************************/ void sam_spi0select(uint32_t devid, bool selected) { spiinfo("devid: %08x CS: %s\n", (unsigned int)devid, selected ? "assert" : "de-assert"); #ifdef HAVE_SSD1306 if (devid == SPIDEV_DISPLAY(0)) { /* Low: the display is selected * High: the display is deselected */ sam_gpiowrite(GPIO_SSD1306_CS, !selected); } #endif } /**************************************************************************** * Name: sam_spi0status * * Description: * Return status information associated with the SPI device. * * Input Parameters: * devid - Identifies the (logical) device * * Returned Value: * Bit-encoded SPI status (see include/nuttx/spi/spi.h. * ****************************************************************************/ uint8_t sam_spi0status(struct spi_dev_s *dev, uint32_t devid) { spiinfo("Returning nothing\n"); return 0; } /**************************************************************************** * Name: sam_spi0cmddata * * Description: * Some SPI devices require an additional control to determine if the SPI * data being sent is a command or is data. If CONFIG_SPI_CMDDATA then * this function will be called to different be command and data transfers. * * This is often needed, for example, by LCD drivers. Some LCD hardware * may be configured to use 9-bit data transfers with the 9th bit * indicating command or data. That same hardware may be configurable, * instead, to use 8-bit data but to require an additional, board- * specific PIO control to distinguish command and data. This function * would be needed in that latter case. * * Input Parameters: * dev - SPI device info * devid - Identifies the (logical) device * * Returned Value: * Zero on success; a negated errno on failure. * ****************************************************************************/ #ifdef CONFIG_SPI_CMDDATA int sam_spi0cmddata(struct spi_dev_s *dev, uint32_t devid, bool cmd) { spiinfo("devid: %08x %s\n", (unsigned int)devid, cmd ? "cmd" : "data"); #ifdef HAVE_SSD1306 if (devid == SPIDEV_DISPLAY(0)) { /* High: the inputs are treated as display data. * Low: the inputs are transferred to the command registers. */ sam_gpiowrite(GPIO_SSD1306_DC, !cmd); } #endif return 0; } #endif #endif /* CONFIG_SAM34_SPI0 */
9c5fb43838c0de1d94f9163ead339fa2ecf939f7
0744dcc5394cebf57ebcba343747af6871b67017
/external/mosquitto/handle_disconnect.c
e5191b2200f17fa44fea67a37bb205e7740b4041
[ "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
1,656
c
handle_disconnect.c
/* Copyright (c) 2009-2020 Roger Light <roger@atchoo.org> All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include <stdio.h> #include <string.h> #include "logging_mosq.h" #include "mqtt_protocol.h" #include "memory_mosq.h" #include "net_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "read_handle.h" #include "send_mosq.h" #include "util_mosq.h" int handle__disconnect(struct mosquitto *mosq) { int rc; uint8_t reason_code; mosquitto_property *properties = NULL; if(!mosq){ return MOSQ_ERR_INVAL; } if(mosq->protocol != mosq_p_mqtt5){ return MOSQ_ERR_PROTOCOL; } if(mosq->in_packet.command != CMD_DISCONNECT){ return MOSQ_ERR_MALFORMED_PACKET; } rc = packet__read_byte(&mosq->in_packet, &reason_code); if(rc) return rc; if(mosq->in_packet.remaining_length > 2){ rc = property__read_all(CMD_DISCONNECT, &mosq->in_packet, &properties); if(rc) return rc; mosquitto_property_free_all(&properties); } log__printf(mosq, MOSQ_LOG_DEBUG, "Received DISCONNECT (%d)", reason_code); do_client_disconnect(mosq, reason_code, properties); mosquitto_property_free_all(&properties); return MOSQ_ERR_SUCCESS; }
c676fbe944a2a282f4f5daf66f39ece8bad0bda3
fd6ba461ff7746a5d152576930add08ebfcbb975
/addons/geometry/geometry.h
18c9295566878eb7f48f00e0564f5c6e8011981a
[ "Apache-2.0", "Zlib" ]
permissive
rbdl/rbdl
658d3b07e420642dd9c9b1106daff24fd43e526f
cbd9371ce822eeea1f0a880d57f71a4c60bc9b8a
refs/heads/master
2023-07-06T02:54:35.529726
2023-06-25T11:11:42
2023-06-25T11:11:42
208,891,294
449
141
NOASSERTION
2023-09-13T16:09:26
2019-09-16T20:24:46
C++
UTF-8
C
false
false
300
h
geometry.h
/* * * Copyright (c) 2016 Matthew Millard <millard.matthew@gmail.com> * * Licensed under the zlib license. See LICENSE for more details. */ #ifndef GEOMETRY_H_ #define GEOMETRY_H_ #include "Function.h" #include "SegmentedQuinticBezierToolkit.h" #include "SmoothSegmentedFunction.h" #endif
e5ca6424290d55d6ce75b4ad6191fb3f7de870ab
f7dc806f341ef5dbb0e11252a4693003a66853d5
/thirdparty/freetype/include/freetype/internal/services/svpscmap.h
6e599f3aabe402cd3904c81c8ffd2a7f40178fa3
[ "GPL-2.0-only", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown", "LicenseRef-scancode-unknown-license-reference", "Zlib", "BSD-3-Clause", "MIT", "GPL-3.0-only", "GPL-1.0-or-later", "FTL", "LicenseRef-scancode-warranty-disclaimer", "OFL-1.1", "JSON", "LicenseRef-scancode-nvidia-2002", "MPL-2.0", "CC0-1.0", "BSL-1.0", "Libpng", "Apache-2.0", "Unlicense", "LicenseRef-scancode-free-unknown", "CC-BY-4.0", "Bison-exception-2.2", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unicode", "BSD-2-Clause", "GPL-3.0-or-later", "Bitstream-Vera", "MIT-Modern-Variant" ]
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
4,272
h
svpscmap.h
/**************************************************************************** * * svpscmap.h * * The FreeType PostScript charmap service (specification). * * Copyright (C) 2003-2023 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef SVPSCMAP_H_ #define SVPSCMAP_H_ #include <freetype/internal/ftobjs.h> FT_BEGIN_HEADER #define FT_SERVICE_ID_POSTSCRIPT_CMAPS "postscript-cmaps" /* * Adobe glyph name to unicode value. */ typedef FT_UInt32 (*PS_Unicode_ValueFunc)( const char* glyph_name ); /* * Macintosh name id to glyph name. `NULL` if invalid index. */ typedef const char* (*PS_Macintosh_NameFunc)( FT_UInt name_index ); /* * Adobe standard string ID to glyph name. `NULL` if invalid index. */ typedef const char* (*PS_Adobe_Std_StringsFunc)( FT_UInt string_index ); /* * Simple unicode -> glyph index charmap built from font glyph names table. */ typedef struct PS_UniMap_ { FT_UInt32 unicode; /* bit 31 set: is glyph variant */ FT_UInt glyph_index; } PS_UniMap; typedef struct PS_UnicodesRec_* PS_Unicodes; typedef struct PS_UnicodesRec_ { FT_CMapRec cmap; FT_UInt num_maps; PS_UniMap* maps; } PS_UnicodesRec; /* * A function which returns a glyph name for a given index. Returns * `NULL` if invalid index. */ typedef const char* (*PS_GetGlyphNameFunc)( FT_Pointer data, FT_UInt string_index ); /* * A function used to release the glyph name returned by * PS_GetGlyphNameFunc, when needed */ typedef void (*PS_FreeGlyphNameFunc)( FT_Pointer data, const char* name ); typedef FT_Error (*PS_Unicodes_InitFunc)( FT_Memory memory, PS_Unicodes unicodes, FT_UInt num_glyphs, PS_GetGlyphNameFunc get_glyph_name, PS_FreeGlyphNameFunc free_glyph_name, FT_Pointer glyph_data ); typedef FT_UInt (*PS_Unicodes_CharIndexFunc)( PS_Unicodes unicodes, FT_UInt32 unicode ); typedef FT_UInt (*PS_Unicodes_CharNextFunc)( PS_Unicodes unicodes, FT_UInt32 *unicode ); FT_DEFINE_SERVICE( PsCMaps ) { PS_Unicode_ValueFunc unicode_value; PS_Unicodes_InitFunc unicodes_init; PS_Unicodes_CharIndexFunc unicodes_char_index; PS_Unicodes_CharNextFunc unicodes_char_next; PS_Macintosh_NameFunc macintosh_name; PS_Adobe_Std_StringsFunc adobe_std_strings; const unsigned short* adobe_std_encoding; const unsigned short* adobe_expert_encoding; }; #define FT_DEFINE_SERVICE_PSCMAPSREC( class_, \ unicode_value_, \ unicodes_init_, \ unicodes_char_index_, \ unicodes_char_next_, \ macintosh_name_, \ adobe_std_strings_, \ adobe_std_encoding_, \ adobe_expert_encoding_ ) \ static const FT_Service_PsCMapsRec class_ = \ { \ unicode_value_, unicodes_init_, \ unicodes_char_index_, unicodes_char_next_, macintosh_name_, \ adobe_std_strings_, adobe_std_encoding_, adobe_expert_encoding_ \ }; /* */ FT_END_HEADER #endif /* SVPSCMAP_H_ */ /* END */
2557cf64eb770d416684df5fa6f90db4265aac86
e8b04bef9aa1ac8e2c109dd315f133c8f4d28ae6
/src/ode/ode/src/joints/joint_internal.h
4909f10bedb0409b6aa2e27ffa165ebad788cd90
[ "BSD-3-Clause", "LGPL-2.1-only", "LGPL-2.0-or-later", "LicenseRef-scancode-unknown-license-reference", "Zlib", "Apache-2.0" ]
permissive
cyberbotics/webots
f075dacf4067e8dcebbfd89e8690df8525f6d745
8aba6eaae76989facf3442305c8089d3cc366bcf
refs/heads/master
2023-08-31T09:41:13.205940
2023-08-18T10:48:30
2023-08-18T10:48:30
156,228,018
2,495
1,525
Apache-2.0
2023-08-28T16:30:33
2018-11-05T14:09:10
C++
UTF-8
C
false
false
2,912
h
joint_internal.h
/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: russ@q12.org Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ #ifndef _ODE_JOINT_INTERNAL_H_ #define _ODE_JOINT_INTERNAL_H_ #include <ode/rotation.h> #include <ode/objects.h> #include "matrix.h" #include "odemath.h" #define checktype(j,t) dUASSERT(j->type() == dJointType##t, \ "joint type is not " #t) void setBall( dxJoint *joint, dReal fps, dReal erp, const dxJoint::Info2Descr *info, dVector3 anchor1, dVector3 anchor2 ); void setBall2( dxJoint *joint, dReal fps, dReal erp, const dxJoint::Info2Descr *info, dVector3 anchor1, dVector3 anchor2, dVector3 axis, dReal erp1 ); void setAnchors( dxJoint *j, dReal x, dReal y, dReal z, dVector3 anchor1, dVector3 anchor2 ); void getAnchor( dxJoint *j, dVector3 result, dVector3 anchor1 ); void getAnchor2( dxJoint *j, dVector3 result, dVector3 anchor2 ); void setAxes( dxJoint *j, dReal x, dReal y, dReal z, dVector3 axis1, dVector3 axis2 ); void getAxis( dxJoint *j, dVector3 result, dVector3 axis1 ); void getAxis2( dxJoint *j, dVector3 result, dVector3 axis2 ); dReal getHingeAngle( dxBody *body1, dxBody *body2, dVector3 axis, dQuaternion q_initial ); dReal getHingeAngleFromRelativeQuat( dQuaternion qrel, dVector3 axis ); void setFixedOrientation( dxJoint *joint, dReal fps, dReal erp, const dxJoint::Info2Descr *info, dQuaternion qrel, int start_row ); #endif
d23fac49c9672d068ae42dee4e6b2e623197bf52
0744dcc5394cebf57ebcba343747af6871b67017
/os/board/rtl8730e/src/component/soc/amebad2/fwlib/ap_peripheral/ameba_delay.c
e396bdc2c76826eded6beefb199910c82c70964a
[ "GPL-1.0-or-later", "BSD-3-Clause", "ISC", "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", "Apache-2.0" ]
permissive
Samsung/TizenRT
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
refs/heads/master
2023-08-31T08:59:33.327998
2023-08-08T06:09:20
2023-08-31T04:38:20
82,517,252
590
719
Apache-2.0
2023-09-14T06:54:49
2017-02-20T04:38:30
C
UTF-8
C
false
false
1,784
c
ameba_delay.c
/** ****************************************************************************** * @file rtl8721d_delay.c * @author * @version V1.0.0 * @date 2016-05-17 * @brief This file provides firmware functions to manage the following * functionalities of the systimer & delay: * - DelayUs * - DelayMs ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "ameba_soc.h" #include "arch_timer.h" #if defined ( __ICCARM__ ) #define DelayCheck() \ do { \ __asm volatile("nop;"); \ } while (0) #else #define DelayCheck() \ do { \ __asm__ __volatile__("nop;"); \ } while (0) #endif /** * @brief Delay x us. * @param us: delay time, unit is us */ void DelayUs(u32 us) { uint64_t cntvct; /*check if arch timer is still close, open it */ if ((SYSCFG_CHIPType_Get() == CHIP_TYPE_RTLSIM) || !(arm_arch_timer_check_enable())) { arm_arch_timer_enable(1); } if (SYSCFG_CHIPType_Get() == CHIP_TYPE_FPGA) { cntvct = (uint64_t)(arm_arch_timer_count() + 12.5 * us); //12.5M clock } else { cntvct = (uint64_t)(arm_arch_timer_count() + 50 * us); //50M clock } while (arm_arch_timer_count() < cntvct) { DelayCheck(); } } /** * @brief Delay x ms. * @param ms: delay time, unit is ms */ void DelayMs(u32 ms) { DelayUs(ms * 1000); } /******************* (C) COPYRIGHT 2016 Realtek Semiconductor *****END OF FILE****/
2741208cdf29a825953745dc6adc9b4b18167714
24acbcc7b5ad20d2cea61b2b2b8190befe7f5bce
/Code/Sorting/Ints/countingSort.c
641b6e4b7154a17ba1634393741d1c5b359442cd
[ "MIT" ]
permissive
heineman/algorithms-nutshell-2ed
a08e2136fb3f9199e119a8aebca1be09a02b86f4
6bdaf7ee2878f69a2df00ae7a3274f5d43d24605
refs/heads/master
2022-09-04T20:53:52.422824
2021-12-29T02:34:44
2021-12-29T02:34:44
43,086,309
577
226
null
null
null
null
UTF-8
C
false
false
593
c
countingSort.c
/** * @file countingSort.c Implementation of CountingSort over integer array * * @brief * Implementation of counting-sort using integer array where each element * is drawn from the range [0,k). * * @author George Heineman * @date 6/15/08 */ #include <stdlib.h> /** Sort the n elements in ar, drawn from the values [0,k). */ void countingSort (int *ar, int n, int k) { int i, idx = 0; int *B = calloc (k, sizeof (int)); for (i = 0; i < n; i++) { B[ar[i]]++; } for (i = 0; i < k; i++) { while (B[i]-- > 0) { ar[idx++] = i; } } free(B); }
04244b00d8a009d214442201717ae1bc015cdb5e
b9dc55919b29da24c24f8ee367c5618c9532f56f
/Code_source/shared/aubio/build/src/config.h
67272302458a8cb9b29453008f92e2e8f56384ab
[ "WTFPL", "LicenseRef-scancode-unknown-license-reference", "GPL-3.0-only" ]
permissive
porres/pd-else
075e8b7ac7a78f442055fbd30d6602cae49c887e
b30e8c13c88bb9752c08f78514d64c6206d6678b
refs/heads/master
2023-08-18T22:26:31.120893
2023-08-18T00:46:59
2023-08-18T00:46:59
56,870,805
238
42
WTFPL
2023-09-12T15:55:56
2016-04-22T16:45:29
C
UTF-8
C
false
false
814
h
config.h
/* WARNING! All changes made to this file will be lost! */ #ifndef W_SRC_CONFIG_H_WAF #define W_SRC_CONFIG_H_WAF #define HAVE_STDLIB_H 1 #define HAVE_STDIO_H 1 #define HAVE_MATH_H 1 #define HAVE_STRING_H 1 #define HAVE_ERRNO_H 1 #define HAVE_LIMITS_H 1 #define HAVE_STDARG_H 1 #define HAVE_GETOPT_H 1 #define HAVE_UNISTD_H 1 #define NDEBUG 1 #define HAVE_SOURCE_APPLE_AUDIO 1 #define HAVE_SINK_APPLE_AUDIO 1 #define HAVE_ACCELERATE 1 #define HAVE_C99_VARARGS_MACROS 1 #define HAVE_SNDFILE 1 #define HAVE_SAMPLERATE 1 #define HAVE_RUBBERBAND 1 #define HAVE_AVCODEC 1 #define HAVE_AVFORMAT 1 #define HAVE_AVUTIL 1 #define HAVE_SWRESAMPLE 1 #define HAVE_LIBAV 1 #define HAVE_VORBISENC 1 #define HAVE_FLAC 1 #define HAVE_WAVREAD 1 #define HAVE_WAVWRITE 1 #define HAVE_MEMCPY_HACKS 1 #endif /* W_SRC_CONFIG_H_WAF */
623bf0d9efab7b842f6a036eaf7cd4d9a041c695
44bf3ced806bcd72fc2476cd15c7143b6fc81dcc
/src/blend2d/codec/pngcodec_p.h
8c3eb6f96e31ee2786d5b257929415f8dc422e2e
[ "Zlib" ]
permissive
blend2d/blend2d
9bc48e614a0f1cda65cb0ceaafda709d4453ad85
99fc3aa9a1d113e913df67166d40d2a81bef1dcb
refs/heads/master
2023-08-30T03:10:19.645400
2023-08-28T11:40:00
2023-08-28T11:40:00
16,447,163
1,305
112
Zlib
2023-05-01T08:16:41
2014-02-02T02:01:04
C++
UTF-8
C
false
false
2,409
h
pngcodec_p.h
// This file is part of Blend2D project <https://blend2d.com> // // See blend2d.h or LICENSE.md for license and copyright information // SPDX-License-Identifier: Zlib #ifndef BLEND2D_CODEC_PNGCODEC_P_H_INCLUDED #define BLEND2D_CODEC_PNGCODEC_P_H_INCLUDED #include "../api-internal_p.h" #include "../image_p.h" #include "../imagecodec.h" #include "../imagedecoder.h" #include "../imageencoder.h" #include "../pixelconverter.h" #include "../runtime_p.h" //! \cond INTERNAL //! \addtogroup blend2d_codec_impl //! \{ enum BLPngDecoderStatusFlags : uint32_t { BL_PNG_DECODER_STATUS_SEEN_IHDR = 0x00000001u, BL_PNG_DECODER_STATUS_SEEN_IDAT = 0x00000002u, BL_PNG_DECODER_STATUS_SEEN_IEND = 0x00000004u, BL_PNG_DECODER_STATUS_SEEN_PLTE = 0x00000010u, BL_PNG_DECODER_STATUS_SEEN_tRNS = 0x00000020u, BL_PNG_DECODER_STATUS_SEEN_CgBI = 0x00000040u }; enum BLPngColorType : uint32_t { //! Each pixel is a grayscale sample (1/2/4/8/16-bits per sample). BL_PNG_COLOR_TYPE0_LUM = 0, //! Each pixel is an RGB triple (8/16-bits per sample). BL_PNG_COLOR_TYPE2_RGB = 2, //! Each pixel is a palette index (1/2/4/8 bits per sample). BL_PNG_COLOR_TYPE3_PAL = 3, //! Each pixel is a grayscale+alpha sample (8/16-bits per sample). BL_PNG_COLOR_TYPE4_LUMA = 4, //! Each pixel is an RGBA quad (8/16 bits per sample). BL_PNG_COLOR_TYPE6_RGBA = 6 }; enum PngFilterType : uint32_t { BL_PNG_FILTER_TYPE_NONE = 0, BL_PNG_FILTER_TYPE_SUB = 1, BL_PNG_FILTER_TYPE_UP = 2, BL_PNG_FILTER_TYPE_AVG = 3, BL_PNG_FILTER_TYPE_PAETH = 4, BL_PNG_FILTER_TYPE_COUNT = 5, //! Synthetic filter used only by Blend2D's reverse-filter implementation. BL_PNG_FILTER_TYPE_AVG0 = 5 }; struct BLPngDecoderImpl : public BLImageDecoderImpl { //! Decoder image information. BLImageInfo imageInfo; //! Decoder status flags. uint32_t statusFlags; //! Color type. uint8_t colorType; //! Depth (depth per one sample). uint8_t sampleDepth; //! Number of samples (1, 2, 3, 4). uint8_t sampleCount; //! Contains "CgBI" chunk before "IHDR" and other violations. uint8_t cgbi; }; struct BLPngEncoderImpl : public BLImageEncoderImpl { uint8_t compressionLevel; }; struct BLPngCodecImpl : public BLImageCodecImpl {}; BL_HIDDEN void blPngCodecOnInit(BLRuntimeContext* rt, BLArray<BLImageCodec>* codecs) noexcept; //! \} //! \endcond #endif // BLEND2D_CODEC_PNGCODEC_P_H_INCLUDED
a782b8b847f77f0341c792be258b5137c6aab1b3
0744dcc5394cebf57ebcba343747af6871b67017
/external/iotjs/deps/jerry/jerry-core/ecma/builtin-objects/ecma-builtin-number-prototype.c
d7d71fa5c4d2e591e58cc98b3cca02a61ca70db1
[ "LicenseRef-scancode-dco-1.1", "Apache-2.0", "MIT" ]
permissive
Samsung/TizenRT
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
refs/heads/master
2023-08-31T08:59:33.327998
2023-08-08T06:09:20
2023-08-31T04:38:20
82,517,252
590
719
Apache-2.0
2023-09-14T06:54:49
2017-02-20T04:38:30
C
UTF-8
C
false
false
33,507
c
ecma-builtin-number-prototype.c
/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <math.h> #include "ecma-alloc.h" #include "ecma-builtins.h" #include "ecma-conversion.h" #include "ecma-exceptions.h" #include "ecma-gc.h" #include "ecma-globals.h" #include "ecma-helpers.h" #include "ecma-objects.h" #include "ecma-string-object.h" #include "ecma-try-catch-macro.h" #include "jrt.h" #include "jrt-libc-includes.h" #ifndef CONFIG_DISABLE_NUMBER_BUILTIN #define ECMA_BUILTINS_INTERNAL #include "ecma-builtins-internal.h" #define BUILTIN_INC_HEADER_NAME "ecma-builtin-number-prototype.inc.h" #define BUILTIN_UNDERSCORED_ID number_prototype #include "ecma-builtin-internal-routines-template.inc.h" /** \addtogroup ecma ECMA * @{ * * \addtogroup ecmabuiltins * @{ * * \addtogroup numberprototype ECMA Number.prototype object built-in * @{ */ /** * Helper for stringifying numbers * * @return the length of the generated string representation */ static lit_utf8_size_t ecma_builtin_number_prototype_helper_to_string (lit_utf8_byte_t *digits_p, /**< number as string in decimal form */ lit_utf8_size_t num_digits, /**< length of the string representation */ int32_t exponent, /**< decimal exponent */ lit_utf8_byte_t *to_digits_p, /**< [out] buffer to write */ lit_utf8_size_t to_num_digits) /**< requested number of digits */ { lit_utf8_byte_t *p = to_digits_p; if (exponent <= 0) { /* Add zero to the integer part. */ *p++ = '0'; to_num_digits--; if (to_num_digits > 0) { *p++ = '.'; /* Add leading zeros to the fraction part. */ for (int i = 0; i < -exponent && to_num_digits > 0; i++) { *p++ = '0'; to_num_digits--; } } } else { /* Add significant digits of the integer part. */ lit_utf8_size_t to_copy = JERRY_MIN (num_digits, to_num_digits); to_copy = JERRY_MIN (to_copy, (lit_utf8_size_t) exponent); memmove (p, digits_p, (size_t) to_copy); p += to_copy; to_num_digits -= to_copy; digits_p += to_copy; num_digits -= to_copy; exponent -= (int32_t) to_copy; /* Add zeros before decimal point. */ while (exponent > 0 && to_num_digits > 0) { JERRY_ASSERT (num_digits == 0); *p++ = '0'; to_num_digits--; exponent--; } if (to_num_digits > 0) { *p++ = '.'; } } if (to_num_digits > 0) { /* Add significant digits of the fraction part. */ lit_utf8_size_t to_copy = JERRY_MIN (num_digits, to_num_digits); memmove (p, digits_p, (size_t) to_copy); p += to_copy; to_num_digits -= to_copy; /* Add trailing zeros. */ while (to_num_digits > 0) { *p++ = '0'; to_num_digits--; } } return (lit_utf8_size_t) (p - to_digits_p); } /* ecma_builtin_number_prototype_helper_to_string */ static inline lit_utf8_size_t __attr_always_inline___ ecma_builtin_binary_floating_number_to_string (lit_utf8_byte_t *digits_p, /**< number as string * in binary-floating point number */ lit_utf8_size_t num_digits, /**< length of the string representation */ int32_t exponent, /**< decimal exponent */ lit_utf8_byte_t *to_digits_p, /**< [out] buffer to write */ lit_utf8_size_t to_num_digits) /**< requested number of digits */ { lit_utf8_byte_t *p = to_digits_p; /* Add significant digits of the decimal part. */ while (exponent > 0) { *p++ = *digits_p++; exponent--; to_num_digits--; } if (to_num_digits > 0) { *p++ = '.'; } if (to_num_digits > 0) { /* Add significant digits of the fraction part. */ while (to_num_digits > 0) { *p++ = num_digits == 1 ? '0' : *digits_p++; to_num_digits--; } } return (lit_utf8_size_t) (p - to_digits_p); } /* ecma_builtin_binary_floating_number_to_string */ /** * Helper for rounding numbers * * @return rounded number */ static inline lit_utf8_size_t __attr_always_inline___ ecma_builtin_number_prototype_helper_round (lit_utf8_byte_t *digits_p, /**< [in,out] number as a string in decimal * form */ lit_utf8_size_t num_digits, /**< length of the string representation */ int32_t round_num, /**< number of digits to keep */ int32_t *exponent_p, /**< [in, out] decimal exponent */ bool zero) /**< true if digits_p represents zero */ { if (round_num < 1) { return 0; } if ((lit_utf8_size_t) round_num >= num_digits || zero) { return num_digits; } if (digits_p[round_num] >= '5') { digits_p[round_num] = '0'; int i = 1; /* Handle carry number. */ for (; i <= round_num; i++) { if (++digits_p[round_num - i] <= '9') { break; } digits_p[round_num - i] = '0'; } /* Prepend highest digit */ if (i > round_num) { memmove (digits_p + 1, digits_p, num_digits); digits_p[0] = '1'; *exponent_p += 1; } } return (lit_utf8_size_t) round_num; } /* ecma_builtin_number_prototype_helper_round */ /** * The Number.prototype object's 'toString' routine * * See also: * ECMA-262 v5, 15.7.4.2 * * @return ecma value * Returned value must be freed with ecma_free_value. */ static ecma_value_t ecma_builtin_number_prototype_object_to_string (ecma_value_t this_arg, /**< this argument */ const ecma_value_t *arguments_list_p, /**< arguments list */ ecma_length_t arguments_list_len) /**< number of arguments */ { ecma_value_t ret_value = ecma_make_simple_value (ECMA_SIMPLE_VALUE_EMPTY); ECMA_TRY_CATCH (this_value, ecma_builtin_number_prototype_object_value_of (this_arg), ret_value); ecma_number_t this_arg_number = ecma_get_number_from_value (this_value); if (arguments_list_len == 0 || ecma_number_is_nan (this_arg_number) || ecma_number_is_infinity (this_arg_number) || ecma_number_is_zero (this_arg_number) || (arguments_list_len > 0 && ecma_is_value_undefined (arguments_list_p[0]))) { ecma_string_t *ret_str_p = ecma_new_ecma_string_from_number (this_arg_number); ret_value = ecma_make_string_value (ret_str_p); } else { static const lit_utf8_byte_t digit_chars[36] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; ECMA_OP_TO_NUMBER_TRY_CATCH (arg_num, arguments_list_p[0], ret_value); uint32_t radix = ecma_number_to_uint32 (arg_num); if (radix < 2 || radix > 36) { ret_value = ecma_raise_range_error (ECMA_ERR_MSG ("Radix must be between 2 and 36.")); } else if (radix == 10) { ecma_string_t *ret_str_p = ecma_new_ecma_string_from_number (this_arg_number); ret_value = ecma_make_string_value (ret_str_p); } else { int buff_size = 0; bool is_number_negative = false; if (ecma_number_is_negative (this_arg_number)) { /* ecma_number_to_decimal can't handle negative numbers, so we get rid of the sign. */ this_arg_number = -this_arg_number; is_number_negative = true; /* Add space for the sign in the result. */ buff_size += 1; } /* Decompose the number. */ lit_utf8_byte_t digits[ECMA_MAX_CHARS_IN_STRINGIFIED_NUMBER]; int32_t exponent; lit_utf8_size_t digit_count = ecma_number_to_decimal (this_arg_number, digits, &exponent); /* * The 'exponent' given by 'ecma_number_to_decimal' specifies where the decimal point is located * compared to the first digit in 'digits'. * For example: 120 -> '12', exp: 3 and 0.012 -> '12', exp: -1 * We convert it to be location of the decimal point compared to the last digit of 'digits': * 120 -> 12 * 10^1 and 0.012 -> 12 * 10^-3 */ exponent = exponent - (int32_t) digit_count; /* 'magnitude' will be the magnitude of the number in the specific radix. */ int magnitude; int required_digits; if (exponent >= 0) { /* * If the exponent is non-negative that means we won't have a fractional part, and can calculate * exactly how many digits we will have. This could be done via a mathematic formula, but in rare * cases that can cause incorrect results due to precision issues, so we use a loop instead. */ magnitude = 0; double counter = this_arg_number; while (counter >= radix) { counter /= radix; magnitude++; } /* * The magnitude will only tell us how many digits we have after the first one, so we add one extra. * In this case we won't be needing a radix point, so we don't need to worry about space for it. */ required_digits = magnitude + 1; } else { /* * We can't know exactly how many digits we will need, since the number may be non-terminating in the * new radix, so we will have to estimate it. We do this by first calculating how many zeros we will * need in the specific radix before we hit a significant digit. This is calculated from the decimal * exponent, which we negate so that we get a positive number in the end. */ magnitude = (int) floor ((log (10) / log (radix)) * -exponent); /* * We also need to add space for significant digits. The worst case is radix == 2, since this will * require the most digits. In this case, the upper limit to the number of significant digits we can have is * ECMA_NUMBER_FRACTION_WIDTH + 1. This should be sufficient for any number. */ required_digits = magnitude + ECMA_NUMBER_FRACTION_WIDTH + 1; /* * We add an exta slot for the radix point. It is also likely that we will need extra space for a * leading zero before the radix point. It's better to add space for that here as well, even if we may not * need it, since later we won't be able to do so. */ buff_size += 2; } /* * Here we normalize the number so that it is as close to 0 as possible, which will prevent us from losing * precision in case of extreme numbers when we later split the number into integer and fractional parts. * This has to be done in the specific radix, otherwise it messes up the result, so we use magnitude instead. */ if (exponent > 0) { for (int i = 0; i < magnitude; i++) { this_arg_number /= (ecma_number_t) radix; } } else if (exponent < 0) { for (int i = 0; i < magnitude; i++) { this_arg_number *= (ecma_number_t) radix; } } /* Split the number into an integer and a fractional part, since we have to handle them separately. */ uint64_t whole = (uint64_t) this_arg_number; ecma_number_t fraction = this_arg_number - (ecma_number_t) whole; bool should_round = false; if (!ecma_number_is_zero (fraction) && exponent >= 0) { /* * If the exponent is non-negative, and we get a non-zero fractional part, that means * the normalization might have introduced a small error, in which case we have to correct it by rounding. * We'll add one extra significant digit which we will later use to round. */ required_digits += 1; should_round = true; } /* Get the total required buffer size and allocate the buffer. */ buff_size += required_digits; JMEM_DEFINE_LOCAL_ARRAY (buff, buff_size, lit_utf8_byte_t); int buff_index = 0; /* Calculate digits for whole part. */ while (whole > 0) { JERRY_ASSERT (buff_index < buff_size && buff_index < required_digits); buff[buff_index++] = (lit_utf8_byte_t) (whole % radix); whole /= radix; } /* The digits are backwards, we need to reverse them. */ for (int i = 0; i < buff_index / 2; i++) { lit_utf8_byte_t swap = buff[i]; buff[i] = buff[buff_index - i - 1]; buff[buff_index - i - 1] = swap; } /* * Calculate where we have to put the radix point relative to the beginning of * the new digits. If the exponent is non-negative this will be right after the number. */ int point = exponent >= 0 ? magnitude + 1: buff_index - magnitude; if (point < 0) { /* * In this case the radix point will be before the first digit, * so we need to leave space for leading zeros. */ JERRY_ASSERT (exponent < 0); required_digits += point; } JERRY_ASSERT (required_digits <= buff_size); /* Calculate digits for fractional part. */ while (buff_index < required_digits) { fraction *= (ecma_number_t) radix; lit_utf8_byte_t digit = (lit_utf8_byte_t) floor (fraction); buff[buff_index++] = digit; fraction -= (ecma_number_t) floor (fraction); } if (should_round) { /* Consume last digit for rounding. */ buff_index--; if (buff[buff_index] > radix / 2) { /* We should be rounding up. */ buff[buff_index - 1]++; /* Propagate carry forward in the digits. */ for (int i = buff_index - 1; i > 0 && buff[i] >= radix; i--) { buff[i] = (lit_utf8_byte_t) (buff[i] - radix); buff[i - 1]++; } if (buff[0] >= radix) { /* * Carry propagated over the whole number, we need to add a new leading digit. * We can use the place of the original rounded digit, we just need to shift everything * right by one. */ memmove (buff + 1, buff, (size_t) buff_index); buff_index++; buff[0] = 1; } } } /* Remove trailing zeros. */ while (buff_index - 1 > point && buff[buff_index - 1] == 0) { buff_index--; } /* Add leading zeros in case place of radix point is negative. */ if (point <= 0) { /* We will have 'point' amount of zeros after the radix point, and +1 before. */ int zero_count = -point + 1; memmove (buff + zero_count, buff, (size_t) buff_index); buff_index += zero_count; for (int i = 0; i < zero_count; i++) { buff[i] = 0; } /* We now need to place the radix point after the first zero. */ point = 1; } /* Convert digits to characters. */ for (int i = 0; i < buff_index; i++) { buff[i] = digit_chars[buff[i]]; } /* Place radix point to the required position. */ if (point < buff_index) { memmove (buff + point + 1, buff + point, (size_t) (buff_index - point)); buff[point] = '.'; buff_index++; } /* Add negative sign if necessary. */ if (is_number_negative) { memmove (buff + 1, buff, (size_t) buff_index); buff[0] = '-'; buff_index++; } JERRY_ASSERT (buff_index <= buff_size); ecma_string_t *str_p = ecma_new_ecma_string_from_utf8 (buff, (lit_utf8_size_t) buff_index); ret_value = ecma_make_string_value (str_p); JMEM_FINALIZE_LOCAL_ARRAY (buff); } ECMA_OP_TO_NUMBER_FINALIZE (arg_num); } ECMA_FINALIZE (this_value); return ret_value; } /* ecma_builtin_number_prototype_object_to_string */ /** * The Number.prototype object's 'toLocaleString' routine * * See also: * ECMA-262 v5, 15.7.4.3 * * @return ecma value * Returned value must be freed with ecma_free_value. */ static ecma_value_t ecma_builtin_number_prototype_object_to_locale_string (ecma_value_t this_arg) /**< this argument */ { return ecma_builtin_number_prototype_object_to_string (this_arg, NULL, 0); } /* ecma_builtin_number_prototype_object_to_locale_string */ /** * The Number.prototype object's 'valueOf' routine * * See also: * ECMA-262 v5, 15.7.4.4 * * @return ecma value * Returned value must be freed with ecma_free_value. */ static ecma_value_t ecma_builtin_number_prototype_object_value_of (ecma_value_t this_arg) /**< this argument */ { if (ecma_is_value_number (this_arg)) { return ecma_copy_value (this_arg); } else if (ecma_is_value_object (this_arg)) { ecma_object_t *object_p = ecma_get_object_from_value (this_arg); if (ecma_object_class_is (object_p, LIT_MAGIC_STRING_NUMBER_UL)) { ecma_extended_object_t *ext_object_p = (ecma_extended_object_t *) object_p; JERRY_ASSERT (ecma_is_value_number (ext_object_p->u.class_prop.u.value)); return ecma_copy_value (ext_object_p->u.class_prop.u.value); } } return ecma_raise_type_error (ECMA_ERR_MSG ("Argument 'this' is not a Number or a Number object.")); } /* ecma_builtin_number_prototype_object_value_of */ /** * The Number.prototype object's 'toFixed' routine * * See also: * ECMA-262 v5, 15.7.4.5 * * @return ecma value * Returned value must be freed with ecma_free_value. */ static ecma_value_t ecma_builtin_number_prototype_object_to_fixed (ecma_value_t this_arg, /**< this argument */ ecma_value_t arg) /**< routine's argument */ { ecma_value_t ret_value = ecma_make_simple_value (ECMA_SIMPLE_VALUE_EMPTY); ECMA_TRY_CATCH (this_value, ecma_builtin_number_prototype_object_value_of (this_arg), ret_value); ecma_number_t this_num = ecma_get_number_from_value (this_value); ECMA_OP_TO_NUMBER_TRY_CATCH (arg_num, arg, ret_value); /* 2. */ if (arg_num <= -1 || arg_num >= 21) { ret_value = ecma_raise_range_error (ECMA_ERR_MSG ("Fraction digits must be between 0 and 20.")); } else { /* 4. */ if (ecma_number_is_nan (this_num)) { ecma_string_t *nan_str_p = ecma_get_magic_string (LIT_MAGIC_STRING_NAN); ret_value = ecma_make_string_value (nan_str_p); } else { /* 6. */ bool is_negative = false; if (ecma_number_is_negative (this_num)) { is_negative = ecma_number_is_zero (this_num) ? false : true; this_num *= -1; } /* We handle infinities separately. */ if (ecma_number_is_infinity (this_num)) { ecma_string_t *infinity_str_p = ecma_get_magic_string (LIT_MAGIC_STRING_INFINITY_UL); if (is_negative) { ecma_string_t *neg_str_p = ecma_new_ecma_string_from_utf8 ((const lit_utf8_byte_t *) "-", 1); ecma_string_t *neg_inf_str_p = ecma_concat_ecma_strings (neg_str_p, infinity_str_p); ecma_deref_ecma_string (infinity_str_p); ecma_deref_ecma_string (neg_str_p); ret_value = ecma_make_string_value (neg_inf_str_p); } else { ret_value = ecma_make_string_value (infinity_str_p); } } else { /* Get the parameters of the number if non-zero. */ lit_utf8_byte_t digits[ECMA_MAX_CHARS_IN_STRINGIFIED_NUMBER]; lit_utf8_size_t num_digits; int32_t exponent; int32_t frac_digits = ecma_number_to_int32 (arg_num); if (!ecma_number_is_zero (this_num)) { num_digits = ecma_number_to_binary_floating_point_number (this_num, digits, &exponent); } else { for (int32_t i = 0; i <= frac_digits; i++) { digits[i] = '0'; } num_digits = (lit_utf8_size_t) frac_digits + 1; exponent = 1; } /* 7. */ if (exponent > 21) { ret_value = ecma_builtin_number_prototype_object_to_string (this_arg, NULL, 0); } /* 8. */ else { /* 1. */ num_digits = ecma_builtin_number_prototype_helper_round (digits, num_digits + 1, exponent + frac_digits, &exponent, ecma_number_is_zero (this_num) ? true : false); /* Buffer that is used to construct the string. */ int buffer_size = (exponent > 0) ? exponent + frac_digits + 2 : frac_digits + 3; if (is_negative) { buffer_size++; } JERRY_ASSERT (buffer_size > 0); JMEM_DEFINE_LOCAL_ARRAY (buff, buffer_size, lit_utf8_byte_t); lit_utf8_byte_t *p = buff; if (is_negative) { *p++ = '-'; } lit_utf8_size_t to_num_digits = ((exponent > 0) ? (lit_utf8_size_t) (exponent + frac_digits) : (lit_utf8_size_t) (frac_digits + 1)); p += ecma_builtin_binary_floating_number_to_string (digits, num_digits, exponent, p, to_num_digits); JERRY_ASSERT (p - buff < buffer_size); /* String terminator. */ *p = 0; ecma_string_t *str = ecma_new_ecma_string_from_utf8 (buff, (lit_utf8_size_t) (p - buff)); ret_value = ecma_make_string_value (str); JMEM_FINALIZE_LOCAL_ARRAY (buff); } } } } ECMA_OP_TO_NUMBER_FINALIZE (arg_num); ECMA_FINALIZE (this_value); return ret_value; } /* ecma_builtin_number_prototype_object_to_fixed */ /** * The Number.prototype object's 'toExponential' routine * * See also: * ECMA-262 v5, 15.7.4.6 * * @return ecma value * Returned value must be freed with ecma_free_value. */ static ecma_value_t ecma_builtin_number_prototype_object_to_exponential (ecma_value_t this_arg, /**< this argument */ ecma_value_t arg) /**< routine's argument */ { ecma_value_t ret_value = ecma_make_simple_value (ECMA_SIMPLE_VALUE_EMPTY); /* 1. */ ECMA_TRY_CATCH (this_value, ecma_builtin_number_prototype_object_value_of (this_arg), ret_value); ecma_number_t this_num = ecma_get_number_from_value (this_value); ECMA_OP_TO_NUMBER_TRY_CATCH (arg_num, arg, ret_value); /* 7. */ if (arg_num <= -1.0 || arg_num >= 21.0) { ret_value = ecma_raise_range_error (ECMA_ERR_MSG ("Fraction digits must be between 0 and 20.")); } else { /* 3. */ if (ecma_number_is_nan (this_num)) { ecma_string_t *nan_str_p = ecma_get_magic_string (LIT_MAGIC_STRING_NAN); ret_value = ecma_make_string_value (nan_str_p); } else { /* 5. */ bool is_negative = false; if (ecma_number_is_negative (this_num) && !ecma_number_is_zero (this_num)) { is_negative = true; this_num *= -1; } /* 6. */ if (ecma_number_is_infinity (this_num)) { ecma_string_t *infinity_str_p = ecma_get_magic_string (LIT_MAGIC_STRING_INFINITY_UL); if (is_negative) { ecma_string_t *neg_str_p = ecma_get_magic_string (LIT_MAGIC_STRING_MINUS_CHAR); ecma_string_t *neg_inf_str_p = ecma_concat_ecma_strings (neg_str_p, infinity_str_p); ecma_deref_ecma_string (infinity_str_p); ecma_deref_ecma_string (neg_str_p); ret_value = ecma_make_string_value (neg_inf_str_p); } else { ret_value = ecma_make_string_value (infinity_str_p); } } else { /* Get the parameters of the number if non zero. */ lit_utf8_byte_t digits[ECMA_MAX_CHARS_IN_STRINGIFIED_NUMBER]; lit_utf8_size_t num_digits; int32_t exponent; if (!ecma_number_is_zero (this_num)) { num_digits = ecma_number_to_decimal (this_num, digits, &exponent); } else { digits[0] = '0'; num_digits = 1; exponent = 1; } int32_t frac_digits; if (ecma_is_value_undefined (arg)) { frac_digits = (int32_t) num_digits - 1; } else { frac_digits = ecma_number_to_int32 (arg_num); } num_digits = ecma_builtin_number_prototype_helper_round (digits, num_digits, frac_digits + 1, &exponent, false); /* frac_digits + 2 characters for number, 5 characters for exponent, 1 for \0. */ int buffer_size = frac_digits + 2 + 5 + 1; if (is_negative) { /* +1 character for sign. */ buffer_size++; } JMEM_DEFINE_LOCAL_ARRAY (buff, buffer_size, lit_utf8_byte_t); lit_utf8_byte_t *actual_char_p = buff; if (is_negative) { *actual_char_p++ = '-'; } actual_char_p += ecma_builtin_number_prototype_helper_to_string (digits, num_digits, 1, actual_char_p, (lit_utf8_size_t) (frac_digits + 1)); *actual_char_p++ = 'e'; exponent--; if (exponent < 0) { exponent *= -1; *actual_char_p++ = '-'; } else { *actual_char_p++ = '+'; } /* Add exponent digits. */ actual_char_p += ecma_uint32_to_utf8_string ((uint32_t) exponent, actual_char_p, 3); JERRY_ASSERT (actual_char_p - buff < buffer_size); *actual_char_p = '\0'; ecma_string_t *str = ecma_new_ecma_string_from_utf8 (buff, (lit_utf8_size_t) (actual_char_p - buff)); ret_value = ecma_make_string_value (str); JMEM_FINALIZE_LOCAL_ARRAY (buff); } } } ECMA_OP_TO_NUMBER_FINALIZE (arg_num); ECMA_FINALIZE (this_value); return ret_value; } /* ecma_builtin_number_prototype_object_to_exponential */ /** * The Number.prototype object's 'toPrecision' routine * * See also: * ECMA-262 v5, 15.7.4.7 * * @return ecma value * Returned value must be freed with ecma_free_value. */ static ecma_value_t ecma_builtin_number_prototype_object_to_precision (ecma_value_t this_arg, /**< this argument */ ecma_value_t arg) /**< routine's argument */ { ecma_value_t ret_value = ecma_make_simple_value (ECMA_SIMPLE_VALUE_EMPTY); /* 1. */ ECMA_TRY_CATCH (this_value, ecma_builtin_number_prototype_object_value_of (this_arg), ret_value); ecma_number_t this_num = ecma_get_number_from_value (this_value); /* 2. */ if (ecma_is_value_undefined (arg)) { ret_value = ecma_builtin_number_prototype_object_to_string (this_arg, NULL, 0); } else { /* 3. */ ECMA_OP_TO_NUMBER_TRY_CATCH (arg_num, arg, ret_value); /* 4. */ if (ecma_number_is_nan (this_num)) { ecma_string_t *nan_str_p = ecma_get_magic_string (LIT_MAGIC_STRING_NAN); ret_value = ecma_make_string_value (nan_str_p); } else { /* 6. */ bool is_negative = false; if (ecma_number_is_negative (this_num) && !ecma_number_is_zero (this_num)) { is_negative = true; this_num *= -1; } /* 7. */ if (ecma_number_is_infinity (this_num)) { ecma_string_t *infinity_str_p = ecma_get_magic_string (LIT_MAGIC_STRING_INFINITY_UL); if (is_negative) { ecma_string_t *neg_str_p = ecma_get_magic_string (LIT_MAGIC_STRING_MINUS_CHAR); ecma_string_t *neg_inf_str_p = ecma_concat_ecma_strings (neg_str_p, infinity_str_p); ecma_deref_ecma_string (infinity_str_p); ecma_deref_ecma_string (neg_str_p); ret_value = ecma_make_string_value (neg_inf_str_p); } else { ret_value = ecma_make_string_value (infinity_str_p); } } /* 8. */ else if (arg_num < 1.0 || arg_num >= 22.0) { ret_value = ecma_raise_range_error (ECMA_ERR_MSG ("Precision must be between 1 and 21.")); } else { /* Get the parameters of the number if non-zero. */ lit_utf8_byte_t digits[ECMA_MAX_CHARS_IN_STRINGIFIED_NUMBER]; lit_utf8_size_t num_digits; int32_t exponent; if (!ecma_number_is_zero (this_num)) { num_digits = ecma_number_to_decimal (this_num, digits, &exponent); } else { digits[0] = '0'; num_digits = 1; exponent = 1; } int32_t precision = ecma_number_to_int32 (arg_num); num_digits = ecma_builtin_number_prototype_helper_round (digits, num_digits, precision, &exponent, false); int buffer_size; if (exponent < -5 || exponent > precision) { /* Exponential notation, precision + 1 digits for number, 5 for exponent, 1 for \0 */ buffer_size = precision + 1 + 5 + 1; } else if (exponent <= 0) { /* Fixed notation, -exponent + 2 digits for leading zeros, precision digits, 1 for \0 */ buffer_size = -exponent + 2 + precision + 1; } else { /* Fixed notation, precision + 1 digits for number, 1 for \0 */ buffer_size = precision + 1 + 1; } if (is_negative) { buffer_size++; } JMEM_DEFINE_LOCAL_ARRAY (buff, buffer_size, lit_utf8_byte_t); lit_utf8_byte_t *actual_char_p = buff; if (is_negative) { *actual_char_p++ = '-'; } /* 10.c, Exponential notation.*/ if (exponent < -5 || exponent > precision) { actual_char_p += ecma_builtin_number_prototype_helper_to_string (digits, num_digits, 1, actual_char_p, (lit_utf8_size_t) precision); *actual_char_p++ = 'e'; exponent--; if (exponent < 0) { exponent *= -1; *actual_char_p++ = '-'; } else { *actual_char_p++ = '+'; } /* Add exponent digits. */ actual_char_p += ecma_uint32_to_utf8_string ((uint32_t) exponent, actual_char_p, 3); } /* Fixed notation. */ else { lit_utf8_size_t to_num_digits = ((exponent <= 0) ? (lit_utf8_size_t) (1 - exponent + precision) : (lit_utf8_size_t) precision); actual_char_p += ecma_builtin_number_prototype_helper_to_string (digits, num_digits, exponent, actual_char_p, to_num_digits); } JERRY_ASSERT (actual_char_p - buff < buffer_size); *actual_char_p = '\0'; ecma_string_t *str_p = ecma_new_ecma_string_from_utf8 (buff, (lit_utf8_size_t) (actual_char_p - buff)); ret_value = ecma_make_string_value (str_p); JMEM_FINALIZE_LOCAL_ARRAY (buff); } } ECMA_OP_TO_NUMBER_FINALIZE (arg_num); } ECMA_FINALIZE (this_value); return ret_value; } /* ecma_builtin_number_prototype_object_to_precision */ /** * @} * @} * @} */ #endif /* !CONFIG_DISABLE_NUMBER_BUILTIN */
f5bd3fd73924f4d6208053a0d4900e8d541fd355
0ba2e5061577f6286ff9265ef1df9aca96769445
/cryptography/blowfish/C/blowfish_test.c
0f0aa3876557e4f35df49fa66345b8182ff78823
[ "CC0-1.0" ]
permissive
ZoranPandovski/al-go-rithms
68d5d02f80a61de9baf8e50a81a52e7d0b3983a0
4ae6ba54e90af14af236e03e435eb0402dcac787
refs/heads/master
2023-09-04T16:04:04.321676
2023-06-06T15:22:16
2023-06-06T15:22:16
93,438,176
1,421
2,445
CC0-1.0
2023-06-15T14:24:28
2017-06-05T19:20:20
Jupyter Notebook
UTF-8
C
false
false
2,633
c
blowfish_test.c
/********************************************************************* * Filename: blowfish_test.c * Author: Brad Conte (brad AT bradconte.com) * Copyright: * Disclaimer: This code is presented "as is" without any guarantees. * Details: Performs known-answer tests on the corresponding Blowfish implementation. These tests do not encompass the full range of available test vectors, however, if the tests pass it is very, very likely that the code is correct and was compiled properly. This code also serves as example usage of the functions. *********************************************************************/ /*************************** HEADER FILES ***************************/ #include <stdio.h> #include <memory.h> #include "blowfish.h" /*********************** FUNCTION DEFINITIONS ***********************/ int blowfish_test() { BYTE key1[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; BYTE key2[8] = {0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff}; BYTE key3[24] = {0xF0,0xE1,0xD2,0xC3,0xB4,0xA5,0x96,0x87, 0x78,0x69,0x5A,0x4B,0x3C,0x2D,0x1E,0x0F, 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; BYTE p1[BLOWFISH_BLOCK_SIZE] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; BYTE p2[BLOWFISH_BLOCK_SIZE] = {0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff}; BYTE p3[BLOWFISH_BLOCK_SIZE] = {0xFE,0xDC,0xBA,0x98,0x76,0x54,0x32,0x10}; BYTE c1[BLOWFISH_BLOCK_SIZE] = {0x4e,0xf9,0x97,0x45,0x61,0x98,0xdd,0x78}; BYTE c2[BLOWFISH_BLOCK_SIZE] = {0x51,0x86,0x6f,0xd5,0xb8,0x5e,0xcb,0x8a}; BYTE c3[BLOWFISH_BLOCK_SIZE] = {0x05,0x04,0x4b,0x62,0xfa,0x52,0xd0,0x80}; BYTE enc_buf[BLOWFISH_BLOCK_SIZE]; BLOWFISH_KEY key; int pass = 1; // Test vector 1. blowfish_key_setup(key1, &key, BLOWFISH_BLOCK_SIZE); blowfish_encrypt(p1, enc_buf, &key); pass = pass && !memcmp(c1, enc_buf, BLOWFISH_BLOCK_SIZE); blowfish_decrypt(c1, enc_buf, &key); pass = pass && !memcmp(p1, enc_buf, BLOWFISH_BLOCK_SIZE); // Test vector 2. blowfish_key_setup(key2, &key, BLOWFISH_BLOCK_SIZE); blowfish_encrypt(p2, enc_buf, &key); pass = pass && !memcmp(c2, enc_buf, BLOWFISH_BLOCK_SIZE); blowfish_decrypt(c2, enc_buf, &key); pass = pass && !memcmp(p2, enc_buf, BLOWFISH_BLOCK_SIZE); // Test vector 3. blowfish_key_setup(key3, &key, 24); blowfish_encrypt(p3, enc_buf, &key); pass = pass && !memcmp(c3, enc_buf, BLOWFISH_BLOCK_SIZE); blowfish_decrypt(c3, enc_buf, &key); pass = pass && !memcmp(p3, enc_buf, BLOWFISH_BLOCK_SIZE); return(pass); } int main() { printf("Blowfish tests: %s\n", blowfish_test() ? "SUCCEEDED" : "FAILED"); return(0); }
b297f881cb2985bc7a3e9f26eae0654f4882cc40
dd6bdce2131e1f608ae711be1426765c9db44122
/src/daemon/modules/container/container_gc/containers_gc.c
9feb6d3c4de6ab2960dd868682b8f03f35a99a85
[]
no_license
openeuler-mirror/iSulad
df3b7bdd285e3ed0e2b572ec02c3cef8a80fa8a9
1faaae7ee243bc8b9484ede632302a3cd4bc8670
refs/heads/master
2023-09-01T04:07:42.243619
2023-08-26T01:28:08
2023-08-26T01:28:08
246,005,159
350
25
null
null
null
null
UTF-8
C
false
false
16,005
c
containers_gc.c
/****************************************************************************** * Copyright (c) Huawei Technologies Co., Ltd. 2017-2019. All rights reserved. * iSulad licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR * PURPOSE. * See the Mulan PSL v2 for more details. * Author: tanyifeng * Create: 2017-11-22 * Description: provide container gc functions ******************************************************************************/ #include "containers_gc.h" #include <unistd.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <isula_libutils/container_config_v2.h> #include <isula_libutils/host_config.h> #include <isula_libutils/json_common.h> #include <limits.h> #include <signal.h> #include <stdint.h> #include <stdio.h> #include <sys/prctl.h> #include "constants.h" #include "isulad_config.h" #include "isula_libutils/container_garbage_config.h" #include "isula_libutils/log.h" #include "utils.h" #include "service_container_api.h" #include "container_api.h" #include "runtime_api.h" #include "restartmanager.h" #include "utils_file.h" #include "utils_timestamp.h" static containers_gc_t g_gc_containers; /* gc containers lock */ static void gc_containers_lock() { if (pthread_mutex_lock(&(g_gc_containers.mutex)) != 0) { ERROR("Failed to lock garbage containers list"); } } /* gc containers unlock */ static void gc_containers_unlock() { if (pthread_mutex_unlock(&(g_gc_containers.mutex)) != 0) { ERROR("Failed to unlock garbage containers list"); } } #define GCCONFIGJSON "garbage.json" /* save gc config */ static int save_gc_config(const char *json_gc_config) { int ret = 0; int nret; char filename[PATH_MAX] = { 0 }; char *rootpath = NULL; int fd = -1; rootpath = conf_get_isulad_rootdir(); if (rootpath == NULL) { ERROR("Root path is NULL"); ret = -1; goto out; } nret = snprintf(filename, sizeof(filename), "%s/%s", rootpath, GCCONFIGJSON); if (nret < 0 || (size_t)nret >= sizeof(filename)) { ERROR("Failed to print string"); ret = -1; goto out; } fd = util_open(filename, O_CREAT | O_TRUNC | O_CLOEXEC | O_WRONLY, CONFIG_FILE_MODE); if (fd == -1) { ERROR("Create file %s failed: %s", filename, strerror(errno)); ret = -1; goto out; } nret = util_write_nointr(fd, json_gc_config, strlen(json_gc_config)); if (nret < 0 || (size_t)nret != strlen(json_gc_config)) { ERROR("write %s failed: %s", filename, strerror(errno)); ret = -1; } close(fd); out: free(rootpath); return ret; } /* gc save containers config */ static int gc_save_containers_config(const container_garbage_config *saves) { int ret = 0; parser_error err = NULL; char *json_gc_config = NULL; if (saves == NULL) { return -1; } json_gc_config = container_garbage_config_generate_json(saves, NULL, &err); if (json_gc_config == NULL) { ERROR("Failed to generate container gc config json string:%s", err ? err : " "); ret = -1; goto out; } ret = save_gc_config(json_gc_config); if (ret != 0) { ERROR("Failed to save container gc config json to file"); ret = -1; goto out; } out: free(json_gc_config); free(err); return ret; } /* notes: this function must be called with gc_containers_lock */ static int gc_containers_to_disk() { int ret = 0; size_t size = 0; struct linked_list *it = NULL; struct linked_list *next = NULL; container_garbage_config_gc_containers_element **conts = NULL; container_garbage_config saves = { 0 }; size = linked_list_len(&g_gc_containers.containers_list); if (size != 0) { size_t i = 0; if (size > SIZE_MAX / sizeof(container_garbage_config_gc_containers_element *)) { ERROR("Garbage collection list is too long!"); return -1; } conts = util_common_calloc_s(sizeof(container_garbage_config_gc_containers_element *) * size); if (conts == NULL) { ERROR("Out of memory"); return -1; } linked_list_for_each_safe(it, &g_gc_containers.containers_list, next) { conts[i] = (container_garbage_config_gc_containers_element *)it->elem; i++; } } saves.gc_containers_len = size; saves.gc_containers = conts; ret = gc_save_containers_config(&saves); free(conts); return ret; } /* gc is gc progress */ bool gc_is_gc_progress(const char *id) { bool ret = false; struct linked_list *it = NULL; struct linked_list *next = NULL; container_garbage_config_gc_containers_element *cont = NULL; gc_containers_lock(); linked_list_for_each_safe(it, &g_gc_containers.containers_list, next) { cont = (container_garbage_config_gc_containers_element *)it->elem; if (strcmp(id, cont->id) == 0) { ret = true; break; } } gc_containers_unlock(); return ret; } /* gc add container */ int gc_add_container(const char *id, const char *runtime, const pid_ppid_info_t *pid_info) { struct linked_list *newnode = NULL; container_garbage_config_gc_containers_element *gc_cont = NULL; if (pid_info == NULL) { CRIT("Invalid inputs for add garbage collector."); return -1; } EVENT("Event: {Object: GC, Type: Add container %s with pid %u into garbage collector}", id, pid_info->pid); newnode = util_common_calloc_s(sizeof(struct linked_list)); if (newnode == NULL) { CRIT("Memory allocation error."); return -1; } gc_cont = util_common_calloc_s(sizeof(container_garbage_config_gc_containers_element)); if (gc_cont == NULL) { CRIT("Memory allocation error."); free(newnode); return -1; } gc_cont->id = util_strdup_s(id); gc_cont->runtime = util_strdup_s(runtime); gc_cont->pid = pid_info->pid; gc_cont->start_time = pid_info->start_time; gc_cont->ppid = pid_info->ppid; gc_cont->p_start_time = pid_info->pstart_time; gc_containers_lock(); linked_list_add_elem(newnode, gc_cont); linked_list_add_tail(&g_gc_containers.containers_list, newnode); (void)gc_containers_to_disk(); gc_containers_unlock(); return 0; } /* read gc config */ container_garbage_config *read_gc_config() { int nret; char filename[PATH_MAX] = { 0x00 }; parser_error err = NULL; container_garbage_config *gcconfig = NULL; char *rootpath = NULL; rootpath = conf_get_isulad_rootdir(); if (rootpath == NULL) { ERROR("Root path is NULL"); goto out; } nret = snprintf(filename, sizeof(filename), "%s/%s", rootpath, GCCONFIGJSON); if (nret < 0 || (size_t)nret >= sizeof(filename)) { ERROR("Failed to print string"); goto out; } gcconfig = container_garbage_config_parse_file(filename, NULL, &err); if (gcconfig == NULL) { INFO("Failed to parse gc config file:%s", err); goto out; } out: free(err); free(rootpath); return gcconfig; } /* gc restore */ int gc_restore() { int ret = 0; size_t i = 0; container_garbage_config *gcconfig = NULL; struct linked_list *newnode = NULL; gcconfig = read_gc_config(); if (gcconfig == NULL) { goto out; } gc_containers_lock(); for (i = 0; i < gcconfig->gc_containers_len; i++) { newnode = util_common_calloc_s(sizeof(struct linked_list)); if (newnode == NULL) { gc_containers_unlock(); CRIT("Memory allocation error, failed to restore garbage collector."); ret = -1; goto out; } linked_list_add_elem(newnode, gcconfig->gc_containers[i]); linked_list_add_tail(&g_gc_containers.containers_list, newnode); gcconfig->gc_containers[i] = NULL; } gcconfig->gc_containers_len = 0; (void)gc_containers_to_disk(); gc_containers_unlock(); out: free_container_garbage_config(gcconfig); return ret; } /* apply restart policy after gc */ static void apply_auto_remove_after_gc(const char *id) { container_t *cont = NULL; cont = containers_store_get(id); if (cont == NULL) { INFO("Container '%s' already removed", id); goto out; } if (container_is_running(cont->state)) { INFO("container %s already running, skip apply auto remove after gc", id); goto out; } if (cont->hostconfig != NULL && cont->hostconfig->auto_remove_bak) { (void)set_container_to_removal(cont); (void)delete_container(cont, true); } out: container_unref(cont); return; } /* apply restart policy after gc */ static void apply_restart_policy_after_gc(const char *id) { container_t *cont = NULL; char *started_at = NULL; bool should_restart = false; uint64_t timeout; uint32_t exit_code; bool has_been_manually_stopped = false; cont = containers_store_get(id); if (cont == NULL) { INFO("Container '%s' already removed", id); goto out; } container_lock(cont); if (container_is_running(cont->state)) { INFO("container %s already running, skip apply restart policy after gc", id); goto unlock_out; } started_at = container_state_get_started_at(cont->state); exit_code = container_state_get_exitcode(cont->state); has_been_manually_stopped = container_state_get_has_been_manual_stopped(cont->state); should_restart = restart_manager_should_restart(id, exit_code, has_been_manually_stopped, util_time_seconds_since(started_at), &timeout); free(started_at); if (should_restart) { container_state_increase_restart_count(cont->state); container_state_set_restarting(cont->state, (int)exit_code); INFO("Try to restart container %s after %.2fs", id, (double)timeout / Time_Second); (void)container_restart_in_thread(id, timeout, (int)exit_code); if (container_state_to_disk(cont)) { ERROR("Failed to save container \"%s\" to disk", id); goto unlock_out; } } unlock_out: container_unlock(cont); out: container_unref(cont); return; } static void gc_monitor_process(const char *id, pid_t pid, unsigned long long start_time) { INFO("Received garbage collector monitor of %s with pid %d", id, pid); if (util_process_alive(pid, start_time)) { int ret = kill(pid, SIGKILL); if (ret < 0 && errno != ESRCH) { ERROR("Can not kill monitor process (pid=%d) with SIGKILL", pid); } } } static void add_to_list_tail_to_retry_gc(struct linked_list *it) { gc_containers_lock(); linked_list_del(it); linked_list_add_tail(&g_gc_containers.containers_list, it); gc_containers_unlock(); } static int do_runtime_resume_container(const container_t *cont) { int ret = 0; rt_resume_params_t params = { 0 }; const char *id = cont->common_config->id; params.rootpath = cont->root_path; if (runtime_resume(id, cont->runtime, &params)) { ERROR("Failed to resume container:%s", id); ret = -1; goto out; } container_state_reset_paused(cont->state); if (container_state_to_disk(cont)) { ERROR("Failed to save container \"%s\" to disk", id); ret = -1; goto out; } out: return ret; } static void try_to_resume_container(const char *id, const char *runtime) { int ret = 0; container_t *cont = NULL; if (id == NULL || runtime == NULL) { ERROR("Invalid input arguments"); goto out; } cont = containers_store_get(id); if (cont == NULL) { WARN("No such container:%s", id); goto out; } ret = do_runtime_resume_container(cont); if (ret != 0) { ERROR("try to runtime resume failed"); goto out; } out: container_unref(cont); } static void gc_container_process(struct linked_list *it) { int ret = 0; int pid = 0; unsigned long long start_time = 0; char *runtime = NULL; char *id = NULL; container_garbage_config_gc_containers_element *gc_cont = NULL; gc_cont = (container_garbage_config_gc_containers_element *)it->elem; id = gc_cont->id; runtime = gc_cont->runtime; pid = gc_cont->pid; start_time = gc_cont->start_time; if (util_process_alive(pid, start_time) == false) { ret = clean_container_resource(id, runtime, pid); if (ret != 0) { WARN("Failed to clean resources of container %s", id); add_to_list_tail_to_retry_gc(it); return; } /* remove container from gc list */ gc_containers_lock(); linked_list_del(it); (void)gc_containers_to_disk(); gc_containers_unlock(); EVENT("Event: {Object: GC, Type: Delete container %s with pid %u from garbage collector}", id, pid); /* apply restart policy for the container after gc */ apply_restart_policy_after_gc(id); apply_auto_remove_after_gc(id); free_container_garbage_config_gc_containers_element(gc_cont); free(it); } else { try_to_resume_container(id, runtime); ret = kill(pid, SIGKILL); if (ret < 0 && errno != ESRCH) { ERROR("Can not kill process (pid=%d) with SIGKILL for container %s", pid, id); } add_to_list_tail_to_retry_gc(it); } } static void do_gc_container(struct linked_list *it) { container_garbage_config_gc_containers_element *gc_cont = NULL; gc_cont = (container_garbage_config_gc_containers_element *)it->elem; gc_monitor_process(gc_cont->id, gc_cont->ppid, gc_cont->p_start_time); gc_container_process(it); return; } static void *gchandler(void *arg) { int ret = 0; struct linked_list *it = NULL; ret = pthread_detach(pthread_self()); if (ret != 0) { CRIT("Set thread detach fail"); goto error; } prctl(PR_SET_NAME, "Garbage_collector"); for (;;) { gc_containers_lock(); if (linked_list_empty(&g_gc_containers.containers_list)) { gc_containers_unlock(); goto wait_continue; } it = linked_list_first_node(&g_gc_containers.containers_list); gc_containers_unlock(); do_gc_container(it); wait_continue: util_usleep_nointerupt(100 * 1000); /* wait 100 millisecond to check next gc container */ } error: return NULL; } /* new gchandler */ int new_gchandler() { int ret = -1; linked_list_init(&(g_gc_containers.containers_list)); ret = pthread_mutex_init(&(g_gc_containers.mutex), NULL); if (ret != 0) { CRIT("Mutex initialization failed"); goto out; } INFO("Restoring garbage collector..."); if (gc_restore()) { ERROR("Failed to restore garbage collector"); pthread_mutex_destroy(&(g_gc_containers.mutex)); goto out; } ret = 0; out: return ret; } /* start gchandler */ int start_gchandler() { int ret = -1; pthread_t a_thread; INFO("Starting garbage collector..."); ret = pthread_create(&a_thread, NULL, gchandler, NULL); if (ret != 0) { CRIT("Thread creation failed"); goto out; } ret = 0; out: return ret; } bool container_is_in_gc_progress(const char *id) { if (id == NULL) { return false; } return gc_is_gc_progress(id); }
c7620a6dcaf2690891a89364f3402ce11b9c977c
9e9858f53eef684140d7274987606a44d3077eaa
/inc/nnom_local.h
35845a564101c964ae1e4cfbb7b2754468e77f2b
[ "Apache-2.0" ]
permissive
majianjia/nnom
1b8d11bd0d9c9c179ac0a9106879f0af7235c648
f5dae9307bf8dd4644210117ff0b2b34b34ac777
refs/heads/master
2023-08-11T14:23:34.514766
2023-05-16T01:52:33
2023-05-16T01:52:33
166,869,630
767
216
Apache-2.0
2023-05-16T01:52:35
2019-01-21T19:38:30
C
UTF-8
C
false
false
46,543
h
nnom_local.h
/* * Copyright (c) 2018-2020 * Jianjia Ma * majianjia@live.com * * SPDX-License-Identifier: Apache-2.0 * * Notice: * Code in this file inlcudes derivative works from CMSIS, which is released under alternative license. * Please check the LICENSE file for detial. * * Change Logs: * Date Author Notes * 2019-02-05 Jianjia Ma The first version * 2019-03-19 Jianjia Ma Local C implementation partly from CMSIS-NN */ #ifndef __NNOM_LOCAL_H__ #define __NNOM_LOCAL_H__ #ifdef __cplusplus extern "C" { #endif #include "stdint.h" #include "nnom_port.h" #ifdef ARM_NN_TRUNCATE #define NNOM_TRUNCATE #endif // SSAT implementation with C code #ifndef __NNOM_SSAT static inline int __NNOM_SSAT(int32_t value, int32_t bit) { int32_t min = -(1<<(bit-1)); int32_t max = (1<<(bit-1)) - 1; if (value < min) return min; else if (value > max) return max; else return value; } #endif // USAT implementation with C code #ifndef __NNOM_USAT static inline int __NNOM_USAT(int32_t value, int32_t bit) { int32_t max = (1<<(bit-1)) - 1; if (value < 0) return 0; else if (value > max) return max; else return value; } #endif #define MAX(A, B) ((A) > (B) ? (A) : (B)) #define MIN(A, B) ((A) < (B) ? (A) : (B)) // Those functions/tables below are partially modifed from CMSIS-NN lib // https://github.com/ARM-software/CMSIS_5 // void local_avepool_q7_HWC(const q7_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t padding_x, // padding sizes const uint16_t padding_y, // padding sizes const uint16_t stride_x, // stride const uint16_t stride_y, // stride const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H const uint16_t output_shift, // output right shift q7_t *bufferA, // a buffer for local storage, NULL by now q7_t *Im_out); void local_avepool_q7_CHW(const q7_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t padding_x, // padding sizes const uint16_t padding_y, // padding sizes const uint16_t stride_x, // stride const uint16_t stride_y, // stride const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H const uint16_t output_shift, // output right shift q7_t *bufferA, // a buffer for local storage, NULL by now q7_t *Im_out); // modified from CMSIS-NN test_ref void local_maxpool_q7_HWC(const q7_t * Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t padding_x, // padding sizes const uint16_t padding_y, // padding sizes const uint16_t stride_x, // stride const uint16_t stride_y, // stride const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H q7_t * bufferA, // a buffer for local storage, NULL by now q7_t * Im_out); void local_maxpool_q7_CHW(const q7_t * Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t padding_x, // padding sizes const uint16_t padding_y, // padding sizes const uint16_t stride_x, // stride const uint16_t stride_y, // stride const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H q7_t * bufferA, // a buffer for local storage, NULL by now q7_t * Im_out); void local_sumpool_q7_HWC(const q7_t * Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t padding_x, // padding sizes const uint16_t padding_y, // padding sizes const uint16_t stride_x, // stride const uint16_t stride_y, // stride const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H q7_t * bufferA, // a buffer for local storage, size = 4*output_size q7_t * Im_out); void local_sumpool_q7_CHW(const q7_t * Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t padding_x, // padding sizes const uint16_t padding_y, // padding sizes const uint16_t stride_x, // stride const uint16_t stride_y, // stride const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H q7_t * bufferA, // a buffer for local storage, size = 4*output_size q7_t * Im_out); // customised up sample pooling void local_up_sampling_q7_HWC(const q7_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H q7_t *bufferA, // NULL q7_t *Im_out); void local_up_sampling_q7_CHW(const q7_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H q7_t *bufferA, // NULL q7_t *Im_out); void local_convolve_HWC_q7_nonsquare(const q7_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const q7_t *wt, // kernel weights const uint16_t ch_im_out, // number of filters, i.e., output image channels const uint16_t dim_kernel_x, // filter kernel size x const uint16_t dim_kernel_y, // filter kernel size y const uint16_t padding_x, // padding sizes x const uint16_t padding_y, // padding sizes y const uint16_t stride_x, // stride x const uint16_t stride_y, // stride y const uint16_t dilation_x, // dilation x const uint16_t dilation_y, // dilation y const q7_t *bias, // bias const nnom_qformat_param_t *bias_shift, // bias shifts const nnom_qformat_param_t *out_shift, // output shift const nnom_qtype_t q_type, // per channel or per tensor q7_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y, // output image dimension y q15_t *bufferA, //buffer space for input q7_t *bufferB //buffer space for output ); void local_convolve_CHW_q7_nonsquare(const q7_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const q7_t *wt, // kernel weights const uint16_t ch_im_out, // number of filters, i.e., output image channels const uint16_t dim_kernel_x, // filter kernel size x const uint16_t dim_kernel_y, // filter kernel size y const uint16_t padding_x, // padding sizes x const uint16_t padding_y, // padding sizes y const uint16_t stride_x, // stride x const uint16_t stride_y, // stride y const uint16_t dilation_x, // dilation x const uint16_t dilation_y, // dilation y const q7_t *bias, // bias const nnom_qformat_param_t *bias_shift, // bias shifts const nnom_qformat_param_t *out_shift, // output shift const nnom_qtype_t q_type, // per channel or per tensor q7_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y, // output image dimension y q15_t *bufferA, //buffer space for input q7_t *bufferB //buffer space for output ); void local_conv_trans_HWC_q7_nonsquare(const int8_t * Im_in, const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const q7_t *wt, // kernel weights const uint16_t ch_im_out, // number of filters, i.e., output image channels const uint16_t dim_kernel_x, // filter kernel size x const uint16_t dim_kernel_y, // filter kernel size y const uint16_t padding_x, // padding sizes x const uint16_t padding_y, // padding sizes y const uint16_t stride_x, // stride x const uint16_t stride_y, // stride y const uint16_t dilation_x, // dilation x const uint16_t dilation_y, // dilation y const q7_t *bias, // bias const uint16_t bias_shift, const uint16_t out_shift, q7_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y, // output image dimension y q15_t *bufferA, //buffer space for input q7_t *bufferB //buffer space for output ); void local_depthwise_separable_conv_HWC_q7_nonsquare(const q7_t *Im_in,// input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const q7_t *wt, // kernel weights const uint16_t ch_im_out, // number of filters, i.e., output image channels const uint16_t dim_kernel_x, // filter kernel size x const uint16_t dim_kernel_y, // filter kernel size y const uint16_t padding_x, // padding sizes x const uint16_t padding_y, // padding sizes y const uint16_t stride_x, // stride x const uint16_t stride_y, // stride y const uint16_t dilation_x, // dilation x const uint16_t dilation_y, // dilation y const q7_t *bias, // bias const nnom_qformat_param_t *bias_shift, // bias shifts const nnom_qformat_param_t *out_shift, // output shift const nnom_qtype_t q_type, // per channel or per tensor q7_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y, // output image dimension y q15_t *bufferA, //buffer space for input q7_t *bufferB //buffer space for output ); void local_depthwise_separable_conv_CHW_q7_nonsquare(const q7_t *Im_in,// input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const q7_t *wt, // kernel weights const uint16_t ch_im_out, // number of filters, i.e., output image channels const uint16_t dim_kernel_x, // filter kernel size x const uint16_t dim_kernel_y, // filter kernel size y const uint16_t padding_x, // padding sizes x const uint16_t padding_y, // padding sizes y const uint16_t stride_x, // stride x const uint16_t stride_y, // stride y const uint16_t dilation_x, // dilation x const uint16_t dilation_y, // dilation y const q7_t *bias, // bias const nnom_qformat_param_t *bias_shift, // bias shifts const nnom_qformat_param_t *out_shift, // output shift const nnom_qtype_t q_type, // per channel or per tensor q7_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y, // output image dimension y q15_t *bufferA, //buffer space for input q7_t *bufferB //buffer space for output ); void local_zero_padding_HWC_q7(const q7_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const uint16_t padding_top, // padding sizes y const uint16_t padding_bottom, // padding sizes y const uint16_t padding_left, // padding sizes x const uint16_t padding_right, // padding sizes x q7_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y); // output image dimension y void local_zero_padding_CHW_q7(const q7_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const uint16_t padding_top, // padding sizes y const uint16_t padding_bottom, // padding sizes y const uint16_t padding_left, // padding sizes x const uint16_t padding_right, // padding sizes x q7_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y); // output image dimension y void local_cropping_HWC_q7(const q7_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const uint16_t padding_top, // padding sizes y const uint16_t padding_bottom, // padding sizes y const uint16_t padding_left, // padding sizes x const uint16_t padding_right, // padding sizes x q7_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y); // output image dimension y void local_cropping_CHW_q7(const q7_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const uint16_t padding_top, // padding sizes y const uint16_t padding_bottom, // padding sizes y const uint16_t padding_left, // padding sizes x const uint16_t padding_right, // padding sizes x q7_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y); // output image dimension y void local_fully_connected_q7_opt(const q7_t * pV, // pointer to vector const q7_t * pM, // pointer to matrix const uint16_t dim_vec, // length of the vector const uint16_t num_of_rows, // numCol of A const uint16_t bias_shift, // amount of left-shift for bias const uint16_t out_shift, // amount of right-shift for output const q7_t * bias, q7_t * pOut, // output operand q15_t * vec_buffer); void local_fully_connected_q7(const q7_t * pV, // pointer to vector const q7_t * pM, // pointer to matrix const uint16_t dim_vec, // length of the vector const uint16_t num_of_rows, // numCol of A const uint16_t bias_shift, // amount of left-shift for bias const uint16_t out_shift, // amount of right-shift for output const q7_t * bias, q7_t * pOut, // output operand q15_t * vec_buffer); // matrix dot, // it takes reorderd weight as input, (see dense layer for detail. this is basiclly a dense opt without bias) void local_dot_q7_opt(const q7_t *pV, // pointer to vector const q7_t *pM, // pointer to matrix const uint16_t dim_vec, // length of the vector const uint16_t num_of_rows, // numCol of A const uint16_t out_shift, // amount of right-shift for output q7_t *pOut); // result buffer void local_dot_q7(const q7_t *pV, // pointer to vector const q7_t *pM, // pointer to matrix const uint16_t dim_vec, // length of the vector const uint16_t num_of_rows, // numCol of A const uint16_t out_shift, // amount of right-shift for output q7_t *pOut); // output operand) // softmax void local_softmax_q7(const q7_t * vec_in, const uint32_t dim_vec, q7_t * p_out); // sigmoid void local_sigmoid_q7(q7_t * data, uint32_t size, int16_t int_width); // tanh void local_tanh_q7(q7_t * data, uint32_t size, int16_t int_width); // relu void local_relu_q7(q7_t * data, uint32_t size); // leaky relu void local_leaky_relu_q7(q7_t *data, q7_t alpha, uint32_t size); // alpha in q7 format with dec_bit=7 // max and threshold has the same Q format with the activation void local_adv_relu_q7(q7_t *data, q7_t alpha, q7_t max, q7_t threshold, uint32_t size); // hard sigmoid, // y=-1 if x < -2.5 // y=1 if x > 2.5 // otherwise y = 0.2 * x + 0.5 (y=0.20315 * x + 0.5) void local_hard_sigmoid_q7(q7_t *data, uint32_t size, int16_t dec_bit); // hard tanh // y=-1 if x < -1 // y=1 if x > 1 // otherwise y = x void local_hard_tanh_q7(q7_t *data, uint32_t size, int16_t dec_bit); // matrix ops void local_mult_q7(q7_t * pSrcA, q7_t * pSrcB, q7_t * pDst, const uint16_t out_shift, uint32_t blockSize); // add void local_add_q7(q7_t * pSrcA, q7_t * pSrcB, q7_t * pDst, const uint16_t out_shift, uint32_t blockSize); // sub void local_sub_q7(q7_t * pSrcA, q7_t * pSrcB, q7_t * pDst, const uint16_t out_shift, uint32_t blockSize); // take multiple blocks (>2) as input void local_multiple_add_q7( q7_t *p_dst, const int16_t out_shift, uint32_t block_size, uint32_t num_block, q7_t **p_src); void local_multiple_mult_q7( q7_t *p_dst, const int16_t out_shift, uint32_t block_size, uint32_t num_block, q7_t **p_src); void local_multiple_sub_q7( q7_t *p_dst, const int16_t out_shift, uint32_t block_size, uint32_t num_block, q7_t **p_src); // Below tables credit to CMSIS // For more info. check CMSIS-NN lib // https://github.com/ARM-software/CMSIS_5/blob/develop/CMSIS/NN/Source/NNSupportFunctions/arm_nntables.c static const q7_t nnom_sigmoid_table_q7[256] = { 0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x53, 0x55, 0x57, 0x59, 0x5a, 0x5c, 0x5e, 0x5f, 0x61, 0x62, 0x63, 0x65, 0x66, 0x67, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x72, 0x73, 0x74, 0x74, 0x75, 0x76, 0x76, 0x77, 0x77, 0x78, 0x78, 0x79, 0x79, 0x7a, 0x7a, 0x7a, 0x7b, 0x7b, 0x7b, 0x7c, 0x7c, 0x7c, 0x7c, 0x7c, 0x7d, 0x7d, 0x7d, 0x7d, 0x7d, 0x7e, 0x7e, 0x7e, 0x7e, 0x7e, 0x7e, 0x7e, 0x7e, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x07, 0x07, 0x08, 0x08, 0x09, 0x09, 0x0a, 0x0a, 0x0b, 0x0c, 0x0c, 0x0d, 0x0e, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x19, 0x1a, 0x1b, 0x1d, 0x1e, 0x1f, 0x21, 0x22, 0x24, 0x26, 0x27, 0x29, 0x2b, 0x2d, 0x2e, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e, }; static const q7_t nnom_tanh_table_q7[256] = { 0x00, 0x08, 0x10, 0x18, 0x1f, 0x27, 0x2e, 0x35, 0x3b, 0x41, 0x47, 0x4c, 0x51, 0x56, 0x5a, 0x5e, 0x61, 0x65, 0x68, 0x6a, 0x6d, 0x6f, 0x71, 0x72, 0x74, 0x75, 0x76, 0x78, 0x78, 0x79, 0x7a, 0x7b, 0x7b, 0x7c, 0x7c, 0x7d, 0x7d, 0x7e, 0x7e, 0x7e, 0x7e, 0x7e, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x82, 0x82, 0x82, 0x82, 0x82, 0x83, 0x83, 0x84, 0x84, 0x85, 0x85, 0x86, 0x87, 0x88, 0x88, 0x8a, 0x8b, 0x8c, 0x8e, 0x8f, 0x91, 0x93, 0x96, 0x98, 0x9b, 0x9f, 0xa2, 0xa6, 0xaa, 0xaf, 0xb4, 0xb9, 0xbf, 0xc5, 0xcb, 0xd2, 0xd9, 0xe1, 0xe8, 0xf0, 0xf8, }; // ------------ 16bit ops -------------------- void local_avepool_q15_HWC(const q15_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t padding_x, // padding sizes const uint16_t padding_y, // padding sizes const uint16_t stride_x, // stride const uint16_t stride_y, // stride const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H const uint16_t output_shift, // output right shift q7_t *bufferA, // a buffer for local storage, NULL by now q15_t *Im_out); void local_avepool_q15_CHW(const q15_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t padding_x, // padding sizes const uint16_t padding_y, // padding sizes const uint16_t stride_x, // stride const uint16_t stride_y, // stride const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H const uint16_t output_shift, // output right shift q7_t *bufferA, // a buffer for local storage, NULL by now q15_t *Im_out); void local_maxpool_q15_HWC(const q15_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t padding_x, // padding sizes const uint16_t padding_y, // padding sizes const uint16_t stride_x, // stride const uint16_t stride_y, // stride const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H q7_t *bufferA, // a buffer for local storage, NULL by now q15_t *Im_out); void local_maxpool_q15_CHW(const q15_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t padding_x, // padding sizes const uint16_t padding_y, // padding sizes const uint16_t stride_x, // stride const uint16_t stride_y, // stride const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H q7_t *bufferA, // a buffer for local storage, NULL by now q15_t *Im_out); void local_sumpool_q15_HWC(const q15_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t padding_x, // padding sizes const uint16_t padding_y, // padding sizes const uint16_t stride_x, // stride const uint16_t stride_y, // stride const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H const uint16_t output_shift, // output right shift q7_t *bufferA, // a buffer for local storage, size = 4*output_size q15_t *Im_out); void local_sumpool_q15_CHW(const q15_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t padding_x, // padding sizes const uint16_t padding_y, // padding sizes const uint16_t stride_x, // stride const uint16_t stride_y, // stride const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H const uint16_t output_shift, // output right shift q7_t *bufferA, // a buffer for local storage, size = 4*output_size q15_t *Im_out); void local_up_sampling_q15_HWC(const q15_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H q7_t *bufferA, // a buffer for local storage, NULL by now q15_t *Im_out); void local_up_sampling_q15_CHW(const q15_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimension x or W const uint16_t dim_im_in_y, // input image dimension y or H const uint16_t ch_im_in, // number of input image channels const uint16_t dim_kernel_x, // window kernel size const uint16_t dim_kernel_y, // window kernel size const uint16_t dim_im_out_x, // output image dimension x or W const uint16_t dim_im_out_y, // output image dimension y or H q7_t *bufferA, // a buffer for local storage, NULL by now q15_t *Im_out); void local_convolve_HWC_q15_nonsquare(const q15_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const q7_t *wt, // kernel weights const uint16_t ch_im_out, // number of filters, i.e., output image channels const uint16_t dim_kernel_x, // filter kernel size x const uint16_t dim_kernel_y, // filter kernel size y const uint16_t padding_x, // padding sizes x const uint16_t padding_y, // padding sizes y const uint16_t stride_x, // stride x const uint16_t stride_y, // stride y const uint16_t dilation_x, // dilation x const uint16_t dilation_y, // dilation y const q7_t *bias, // bias const nnom_qformat_param_t *bias_shift, // bias shifts const nnom_qformat_param_t *out_shift, // output shift const nnom_qtype_t q_type, // per channel or per tensor q15_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y, // output image dimension y q15_t *bufferA, //buffer space for input q7_t *bufferB //buffer space for output ); void local_convolve_CHW_q15_nonsquare(const q15_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const q7_t *wt, // kernel weights const uint16_t ch_im_out, // number of filters, i.e., output image channels const uint16_t dim_kernel_x, // filter kernel size x const uint16_t dim_kernel_y, // filter kernel size y const uint16_t padding_x, // padding sizes x const uint16_t padding_y, // padding sizes y const uint16_t stride_x, // stride x const uint16_t stride_y, // stride y const uint16_t dilation_x, // dilation x const uint16_t dilation_y, // dilation y const q7_t *bias, // bias const nnom_qformat_param_t *bias_shift, // bias shifts const nnom_qformat_param_t *out_shift, // output shift const nnom_qtype_t q_type, // per channel or per tensor q15_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y, // output image dimension y q15_t *bufferA, //buffer space for input q7_t *bufferB //buffer space for output ); void local_conv_trans_HWC_q15_nonsquare(const int8_t * Im_in, const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const q7_t *wt, // kernel weights const uint16_t ch_im_out, // number of filters, i.e., output image channels const uint16_t dim_kernel_x, // filter kernel size x const uint16_t dim_kernel_y, // filter kernel size y const uint16_t padding_x, // padding sizes x const uint16_t padding_y, // padding sizes y const uint16_t stride_x, // stride x const uint16_t stride_y, // stride y const uint16_t dilation_x, // dilation x const uint16_t dilation_y, // dilation y const q7_t *bias, // bias const uint16_t bias_shift, const uint16_t out_shift, q15_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y, // output image dimension y q15_t *bufferA, //buffer space for input q7_t *bufferB //buffer space for output ); void local_depthwise_separable_conv_HWC_q15_nonsquare(const q15_t *Im_in,// input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const q7_t *wt, // kernel weights const uint16_t ch_im_out, // number of filters, i.e., output image channels const uint16_t dim_kernel_x, // filter kernel size x const uint16_t dim_kernel_y, // filter kernel size y const uint16_t padding_x, // padding sizes x const uint16_t padding_y, // padding sizes y const uint16_t stride_x, // stride x const uint16_t stride_y, // stride y const uint16_t dilation_x, // dilation x const uint16_t dilation_y, // dilation y const q7_t *bias, // bias const nnom_qformat_param_t *bias_shift, // bias shifts const nnom_qformat_param_t *out_shift, // output shift const nnom_qtype_t q_type, // per channel or per tensor q15_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y, // output image dimension y q15_t *bufferA, //buffer space for input q7_t *bufferB //buffer space for output ); void local_depthwise_separable_conv_CHW_q15_nonsquare(const q15_t *Im_in,// input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const q7_t *wt, // kernel weights const uint16_t ch_im_out, // number of filters, i.e., output image channels const uint16_t dim_kernel_x, // filter kernel size x const uint16_t dim_kernel_y, // filter kernel size y const uint16_t padding_x, // padding sizes x const uint16_t padding_y, // padding sizes y const uint16_t stride_x, // stride x const uint16_t stride_y, // stride y const uint16_t dilation_x, // dilation x const uint16_t dilation_y, // dilation y const q7_t *bias, // bias const nnom_qformat_param_t *bias_shift, // bias shifts const nnom_qformat_param_t *out_shift, // output shift const nnom_qtype_t q_type, // per channel or per tensor q15_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y, // output image dimension y q15_t *bufferA, //buffer space for input q7_t *bufferB //buffer space for output ); void local_zero_padding_HWC_q15(const q15_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const uint16_t padding_top, // padding sizes y const uint16_t padding_bottom, // padding sizes y const uint16_t padding_left, // padding sizes x const uint16_t padding_right, // padding sizes x q15_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y); // output image dimension y void local_zero_padding_CHW_q15(const q15_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const uint16_t padding_top, // padding sizes y const uint16_t padding_bottom, // padding sizes y const uint16_t padding_left, // padding sizes x const uint16_t padding_right, // padding sizes x q15_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y); // output image dimension y void local_cropping_HWC_q15(const q15_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const uint16_t padding_top, // padding sizes y const uint16_t padding_bottom, // padding sizes y const uint16_t padding_left, // padding sizes x const uint16_t padding_right, // padding sizes x q15_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y); // output image dimension y void local_cropping_CHW_q15(const q15_t *Im_in, // input image const uint16_t dim_im_in_x, // input image dimention x const uint16_t dim_im_in_y, // input image dimention y const uint16_t ch_im_in, // number of input image channels const uint16_t padding_top, // padding sizes y const uint16_t padding_bottom, // padding sizes y const uint16_t padding_left, // padding sizes x const uint16_t padding_right, // padding sizes x q15_t *Im_out, // output image const uint16_t dim_im_out_x, // output image dimension x const uint16_t dim_im_out_y); // output image dimension y void local_dot_q15(const q15_t *pV, // pointer to vector const q15_t *pM, // pointer to matrix const uint16_t dim_vec, // length of the vector const uint16_t num_of_rows, // numCol of A const uint16_t out_shift, // amount of right-shift for output q15_t *pOut); // output operand) void local_dot_q15_opt(const q15_t * pV, const q15_t * pM, const uint16_t dim_vec, const uint16_t num_of_rows, const uint16_t out_shift, q15_t * pOut); // original implementation // this support none bias, the it will perform like a dot. // set the `bias=NULL` to work void local_fully_connected_mat_q7_vec_q15(const q15_t * pV, // pointer to vector const q7_t * pM, // pointer to matrix const uint16_t dim_vec, // length of the vector const uint16_t num_of_rows, // numCol of A const uint16_t bias_shift, // amount of left-shift for bias const uint16_t out_shift, // amount of right-shift for output const q7_t * bias, // bias q15_t * pOut, // output q15_t * vec_buffer); // not used but to keep the interface same as the ARM's version // work on recorder matrix // this support none bias, set the bias=NULL to work void local_fully_connected_mat_q7_vec_q15_opt(const q15_t * pV, const q7_t * pM, const uint16_t dim_vec, const uint16_t num_of_rows, const uint16_t bias_shift, const uint16_t out_shift, const q7_t * bias, q15_t * pOut, q15_t * vec_buffer); // matrix operation Q15 void local_multiple_add_q15( q15_t *p_dst, const int16_t out_shift, uint32_t block_size, uint32_t num_block, q15_t **p_src); void local_multiple_mult_q15( q15_t *p_dst, const int16_t out_shift, uint32_t block_size, uint32_t num_block, q15_t **p_src); void local_multiple_sub_q15( q15_t *p_dst, const int16_t out_shift, uint32_t block_size, uint32_t num_block, q15_t **p_src); void local_mult_q15(q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, const uint16_t out_shift, uint32_t blockSize); // add void local_add_q15(q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, const uint16_t out_shift, uint32_t blockSize); // sub void local_sub_q15(q15_t * pSrcA, q15_t * pSrcB, q15_t * pDst, const uint16_t out_shift, uint32_t blockSize); // Convert Q7 to Q15 void local_q7_to_q15_no_shift(const q7_t *src, q15_t *des, uint32_t size); void local_q7_to_q15(const q7_t *src, q15_t *des, uint32_t size); // q15 shift to q7 void local_q15_to_q7(const q15_t *src, q7_t *des, uint32_t shift, uint32_t size); // y = 1 - x void local_1_minor_z_q15(q15_t *src, q15_t *des, uint16_t dec_bit, uint32_t size); void local_softmax_q15(const q15_t * vec_in, const uint16_t dim_vec, q15_t * p_out); void local_hard_sigmoid_q15(q15_t *data, uint32_t size, int16_t dec_bit); void local_hard_tanh_q15(q15_t *data, uint32_t size, int16_t dec_bit); void local_relu_q15(q15_t *data, uint32_t size); void local_leaky_relu_q15(q15_t *data, q7_t alpha, uint32_t size); void local_adv_relu_q15(q15_t *data, q7_t negative_slope, q15_t max, q15_t threshold, uint32_t size); void local_sigmoid_q15(q15_t * data, uint32_t size, uint16_t int_width); void local_tanh_q15(q15_t * data, uint32_t size, uint16_t int_width); static const q15_t nnom_sigmoid_table_q15[256] = { 0x4000, 0x4200, 0x43ff, 0x45fc, 0x47f5, 0x49eb, 0x4bdc, 0x4dc8, 0x4fad, 0x518a, 0x5360, 0x552c, 0x56ef, 0x58a8, 0x5a57, 0x5bfb, 0x5d93, 0x5f20, 0x60a1, 0x6216, 0x637f, 0x64db, 0x662b, 0x676f, 0x68a6, 0x69d2, 0x6af1, 0x6c05, 0x6d0d, 0x6e09, 0x6efb, 0x6fe2, 0x70be, 0x7190, 0x7258, 0x7316, 0x73cc, 0x7478, 0x751b, 0x75b7, 0x764a, 0x76d6, 0x775b, 0x77d8, 0x784f, 0x78c0, 0x792a, 0x798f, 0x79ee, 0x7a48, 0x7a9d, 0x7aed, 0x7b39, 0x7b80, 0x7bc4, 0x7c03, 0x7c3f, 0x7c78, 0x7cad, 0x7ce0, 0x7d0f, 0x7d3c, 0x7d66, 0x7d8d, 0x7db3, 0x7dd6, 0x7df7, 0x7e16, 0x7e33, 0x7e4f, 0x7e69, 0x7e81, 0x7e98, 0x7eae, 0x7ec2, 0x7ed5, 0x7ee7, 0x7ef8, 0x7f08, 0x7f17, 0x7f25, 0x7f32, 0x7f3e, 0x7f4a, 0x7f55, 0x7f5f, 0x7f69, 0x7f72, 0x7f7b, 0x7f83, 0x7f8a, 0x7f91, 0x7f98, 0x7f9e, 0x7fa4, 0x7faa, 0x7faf, 0x7fb4, 0x7fb8, 0x7fbd, 0x7fc1, 0x7fc5, 0x7fc8, 0x7fcc, 0x7fcf, 0x7fd2, 0x7fd5, 0x7fd7, 0x7fda, 0x7fdc, 0x7fde, 0x7fe0, 0x7fe2, 0x7fe4, 0x7fe6, 0x7fe7, 0x7fe9, 0x7fea, 0x7feb, 0x7fed, 0x7fee, 0x7fef, 0x7ff0, 0x7ff1, 0x7ff2, 0x7ff3, 0x7ff4, 0x7ff4, 0x000b, 0x000c, 0x000c, 0x000d, 0x000e, 0x000f, 0x0010, 0x0011, 0x0012, 0x0013, 0x0015, 0x0016, 0x0017, 0x0019, 0x001a, 0x001c, 0x001e, 0x0020, 0x0022, 0x0024, 0x0026, 0x0029, 0x002b, 0x002e, 0x0031, 0x0034, 0x0038, 0x003b, 0x003f, 0x0043, 0x0048, 0x004c, 0x0051, 0x0056, 0x005c, 0x0062, 0x0068, 0x006f, 0x0076, 0x007d, 0x0085, 0x008e, 0x0097, 0x00a1, 0x00ab, 0x00b6, 0x00c2, 0x00ce, 0x00db, 0x00e9, 0x00f8, 0x0108, 0x0119, 0x012b, 0x013e, 0x0152, 0x0168, 0x017f, 0x0197, 0x01b1, 0x01cd, 0x01ea, 0x0209, 0x022a, 0x024d, 0x0273, 0x029a, 0x02c4, 0x02f1, 0x0320, 0x0353, 0x0388, 0x03c1, 0x03fd, 0x043c, 0x0480, 0x04c7, 0x0513, 0x0563, 0x05b8, 0x0612, 0x0671, 0x06d6, 0x0740, 0x07b1, 0x0828, 0x08a5, 0x092a, 0x09b6, 0x0a49, 0x0ae5, 0x0b88, 0x0c34, 0x0cea, 0x0da8, 0x0e70, 0x0f42, 0x101e, 0x1105, 0x11f7, 0x12f3, 0x13fb, 0x150f, 0x162e, 0x175a, 0x1891, 0x19d5, 0x1b25, 0x1c81, 0x1dea, 0x1f5f, 0x20e0, 0x226d, 0x2405, 0x25a9, 0x2758, 0x2911, 0x2ad4, 0x2ca0, 0x2e76, 0x3053, 0x3238, 0x3424, 0x3615, 0x380b, 0x3a04, 0x3c01, 0x3e00, }; static const q15_t nnom_tanh_table_q15[256] = { 0x0000, 0x07fd, 0x0feb, 0x17b9, 0x1f59, 0x26bf, 0x2ddf, 0x34ae, 0x3b27, 0x4142, 0x46fd, 0x4c56, 0x514d, 0x55e2, 0x5a1a, 0x5df6, 0x617c, 0x64b0, 0x6797, 0x6a37, 0x6c95, 0x6eb5, 0x709e, 0x7254, 0x73dc, 0x753a, 0x7672, 0x7788, 0x787f, 0x795b, 0x7a1e, 0x7acb, 0x7b65, 0x7bee, 0x7c66, 0x7cd1, 0x7d30, 0x7d84, 0x7dce, 0x7e0f, 0x7e49, 0x7e7d, 0x7eaa, 0x7ed2, 0x7ef5, 0x7f14, 0x7f30, 0x7f48, 0x7f5e, 0x7f71, 0x7f82, 0x7f91, 0x7f9e, 0x7fa9, 0x7fb3, 0x7fbc, 0x7fc4, 0x7fcb, 0x7fd1, 0x7fd7, 0x7fdc, 0x7fe0, 0x7fe4, 0x7fe7, 0x7fea, 0x7fed, 0x7fef, 0x7ff1, 0x7ff3, 0x7ff4, 0x7ff6, 0x7ff7, 0x7ff8, 0x7ff9, 0x7ffa, 0x7ffa, 0x7ffb, 0x7ffc, 0x7ffc, 0x7ffd, 0x7ffd, 0x7ffd, 0x7ffe, 0x7ffe, 0x7ffe, 0x7ffe, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x7fff, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8001, 0x8001, 0x8001, 0x8001, 0x8001, 0x8001, 0x8001, 0x8001, 0x8001, 0x8002, 0x8002, 0x8002, 0x8002, 0x8003, 0x8003, 0x8003, 0x8004, 0x8004, 0x8005, 0x8006, 0x8006, 0x8007, 0x8008, 0x8009, 0x800a, 0x800c, 0x800d, 0x800f, 0x8011, 0x8013, 0x8016, 0x8019, 0x801c, 0x8020, 0x8024, 0x8029, 0x802f, 0x8035, 0x803c, 0x8044, 0x804d, 0x8057, 0x8062, 0x806f, 0x807e, 0x808f, 0x80a2, 0x80b8, 0x80d0, 0x80ec, 0x810b, 0x812e, 0x8156, 0x8183, 0x81b7, 0x81f1, 0x8232, 0x827c, 0x82d0, 0x832f, 0x839a, 0x8412, 0x849b, 0x8535, 0x85e2, 0x86a5, 0x8781, 0x8878, 0x898e, 0x8ac6, 0x8c24, 0x8dac, 0x8f62, 0x914b, 0x936b, 0x95c9, 0x9869, 0x9b50, 0x9e84, 0xa20a, 0xa5e6, 0xaa1e, 0xaeb3, 0xb3aa, 0xb903, 0xbebe, 0xc4d9, 0xcb52, 0xd221, 0xd941, 0xe0a7, 0xe847, 0xf015, 0xf803, }; #ifdef __cplusplus } #endif #endif /* __NNOM_LOCAL_H__ */
2ca1660e52dcd85a0745438175a4cba713ceb2e6
010279e2ba272d09e9d2c4e903722e5faba2cf7a
/contrib/libs/lcms2/include/lcms2_plugin.h
906defb52118d6b42baa613d9019dc76faadf9d9
[ "Apache-2.0", "LicenseRef-scancode-free-unknown", "MIT" ]
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
31,568
h
lcms2_plugin.h
//--------------------------------------------------------------------------------- // // Little Color Management System // Copyright (c) 1998-2023 Marti Maria Saguer // // 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. // //--------------------------------------------------------------------------------- // // This is the plug-in header file. Normal LittleCMS clients should not use it. // It is provided for plug-in writers that may want to access the support // functions to do low level operations. All plug-in related structures // are defined here. Including this file forces to include the standard API too. #ifndef _lcms_plugin_H // Deal with Microsoft's attempt at deprecating C standard runtime functions #ifdef _MSC_VER # if (_MSC_VER >= 1400) # ifndef _CRT_SECURE_NO_DEPRECATE # define _CRT_SECURE_NO_DEPRECATE # endif # ifndef _CRT_SECURE_NO_WARNINGS # define _CRT_SECURE_NO_WARNINGS # endif # endif #endif #ifndef _lcms2_H #include "lcms2.h" #endif // We need some standard C functions. #include <stdlib.h> #include <math.h> #include <stdarg.h> #include <memory.h> #include <string.h> #ifndef CMS_USE_CPP_API # ifdef __cplusplus extern "C" { # endif #endif // Vector & Matrix operations ----------------------------------------------------------------------- // Axis of the matrix/array. No specific meaning at all. #define VX 0 #define VY 1 #define VZ 2 // Vectors typedef struct { cmsFloat64Number n[3]; } cmsVEC3; // 3x3 Matrix typedef struct { cmsVEC3 v[3]; } cmsMAT3; CMSAPI void CMSEXPORT _cmsVEC3init(cmsVEC3* r, cmsFloat64Number x, cmsFloat64Number y, cmsFloat64Number z); CMSAPI void CMSEXPORT _cmsVEC3minus(cmsVEC3* r, const cmsVEC3* a, const cmsVEC3* b); CMSAPI void CMSEXPORT _cmsVEC3cross(cmsVEC3* r, const cmsVEC3* u, const cmsVEC3* v); CMSAPI cmsFloat64Number CMSEXPORT _cmsVEC3dot(const cmsVEC3* u, const cmsVEC3* v); CMSAPI cmsFloat64Number CMSEXPORT _cmsVEC3length(const cmsVEC3* a); CMSAPI cmsFloat64Number CMSEXPORT _cmsVEC3distance(const cmsVEC3* a, const cmsVEC3* b); CMSAPI void CMSEXPORT _cmsMAT3identity(cmsMAT3* a); CMSAPI cmsBool CMSEXPORT _cmsMAT3isIdentity(const cmsMAT3* a); CMSAPI void CMSEXPORT _cmsMAT3per(cmsMAT3* r, const cmsMAT3* a, const cmsMAT3* b); CMSAPI cmsBool CMSEXPORT _cmsMAT3inverse(const cmsMAT3* a, cmsMAT3* b); CMSAPI cmsBool CMSEXPORT _cmsMAT3solve(cmsVEC3* x, cmsMAT3* a, cmsVEC3* b); CMSAPI void CMSEXPORT _cmsMAT3eval(cmsVEC3* r, const cmsMAT3* a, const cmsVEC3* v); // MD5 low level ------------------------------------------------------------------------------------- CMSAPI cmsHANDLE CMSEXPORT cmsMD5alloc(cmsContext ContextID); CMSAPI void CMSEXPORT cmsMD5add(cmsHANDLE Handle, const cmsUInt8Number* buf, cmsUInt32Number len); CMSAPI void CMSEXPORT cmsMD5finish(cmsProfileID* ProfileID, cmsHANDLE Handle); // Error logging ------------------------------------------------------------------------------------- CMSAPI void CMSEXPORT cmsSignalError(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *ErrorText, ...); // Memory management ---------------------------------------------------------------------------------- CMSAPI void* CMSEXPORT _cmsMalloc(cmsContext ContextID, cmsUInt32Number size); CMSAPI void* CMSEXPORT _cmsMallocZero(cmsContext ContextID, cmsUInt32Number size); CMSAPI void* CMSEXPORT _cmsCalloc(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size); CMSAPI void* CMSEXPORT _cmsRealloc(cmsContext ContextID, void* Ptr, cmsUInt32Number NewSize); CMSAPI void CMSEXPORT _cmsFree(cmsContext ContextID, void* Ptr); CMSAPI void* CMSEXPORT _cmsDupMem(cmsContext ContextID, const void* Org, cmsUInt32Number size); // I/O handler ---------------------------------------------------------------------------------- struct _cms_io_handler { void* stream; // Associated stream, which is implemented differently depending on media. cmsContext ContextID; cmsUInt32Number UsedSpace; cmsUInt32Number ReportedSize; char PhysicalFile[cmsMAX_PATH]; cmsUInt32Number (* Read)(struct _cms_io_handler* iohandler, void *Buffer, cmsUInt32Number size, cmsUInt32Number count); cmsBool (* Seek)(struct _cms_io_handler* iohandler, cmsUInt32Number offset); cmsBool (* Close)(struct _cms_io_handler* iohandler); cmsUInt32Number (* Tell)(struct _cms_io_handler* iohandler); cmsBool (* Write)(struct _cms_io_handler* iohandler, cmsUInt32Number size, const void* Buffer); }; // Endianness adjust functions CMSAPI cmsUInt16Number CMSEXPORT _cmsAdjustEndianess16(cmsUInt16Number Word); CMSAPI cmsUInt32Number CMSEXPORT _cmsAdjustEndianess32(cmsUInt32Number Value); CMSAPI void CMSEXPORT _cmsAdjustEndianess64(cmsUInt64Number* Result, cmsUInt64Number* QWord); // Helper IO functions CMSAPI cmsBool CMSEXPORT _cmsReadUInt8Number(cmsIOHANDLER* io, cmsUInt8Number* n); CMSAPI cmsBool CMSEXPORT _cmsReadUInt16Number(cmsIOHANDLER* io, cmsUInt16Number* n); CMSAPI cmsBool CMSEXPORT _cmsReadUInt32Number(cmsIOHANDLER* io, cmsUInt32Number* n); CMSAPI cmsBool CMSEXPORT _cmsReadFloat32Number(cmsIOHANDLER* io, cmsFloat32Number* n); CMSAPI cmsBool CMSEXPORT _cmsReadUInt64Number(cmsIOHANDLER* io, cmsUInt64Number* n); CMSAPI cmsBool CMSEXPORT _cmsRead15Fixed16Number(cmsIOHANDLER* io, cmsFloat64Number* n); CMSAPI cmsBool CMSEXPORT _cmsReadXYZNumber(cmsIOHANDLER* io, cmsCIEXYZ* XYZ); CMSAPI cmsBool CMSEXPORT _cmsReadUInt16Array(cmsIOHANDLER* io, cmsUInt32Number n, cmsUInt16Number* Array); CMSAPI cmsBool CMSEXPORT _cmsWriteUInt8Number(cmsIOHANDLER* io, cmsUInt8Number n); CMSAPI cmsBool CMSEXPORT _cmsWriteUInt16Number(cmsIOHANDLER* io, cmsUInt16Number n); CMSAPI cmsBool CMSEXPORT _cmsWriteUInt32Number(cmsIOHANDLER* io, cmsUInt32Number n); CMSAPI cmsBool CMSEXPORT _cmsWriteFloat32Number(cmsIOHANDLER* io, cmsFloat32Number n); CMSAPI cmsBool CMSEXPORT _cmsWriteUInt64Number(cmsIOHANDLER* io, cmsUInt64Number* n); CMSAPI cmsBool CMSEXPORT _cmsWrite15Fixed16Number(cmsIOHANDLER* io, cmsFloat64Number n); CMSAPI cmsBool CMSEXPORT _cmsWriteXYZNumber(cmsIOHANDLER* io, const cmsCIEXYZ* XYZ); CMSAPI cmsBool CMSEXPORT _cmsWriteUInt16Array(cmsIOHANDLER* io, cmsUInt32Number n, const cmsUInt16Number* Array); // ICC base tag typedef struct { cmsTagTypeSignature sig; cmsInt8Number reserved[4]; } _cmsTagBase; // Type base helper functions CMSAPI cmsTagTypeSignature CMSEXPORT _cmsReadTypeBase(cmsIOHANDLER* io); CMSAPI cmsBool CMSEXPORT _cmsWriteTypeBase(cmsIOHANDLER* io, cmsTagTypeSignature sig); // Alignment functions CMSAPI cmsBool CMSEXPORT _cmsReadAlignment(cmsIOHANDLER* io); CMSAPI cmsBool CMSEXPORT _cmsWriteAlignment(cmsIOHANDLER* io); // To deal with text streams. 2K at most CMSAPI cmsBool CMSEXPORT _cmsIOPrintf(cmsIOHANDLER* io, const char* frm, ...); // Fixed point helper functions CMSAPI cmsFloat64Number CMSEXPORT _cms8Fixed8toDouble(cmsUInt16Number fixed8); CMSAPI cmsUInt16Number CMSEXPORT _cmsDoubleTo8Fixed8(cmsFloat64Number val); CMSAPI cmsFloat64Number CMSEXPORT _cms15Fixed16toDouble(cmsS15Fixed16Number fix32); CMSAPI cmsS15Fixed16Number CMSEXPORT _cmsDoubleTo15Fixed16(cmsFloat64Number v); // Date/time helper functions CMSAPI void CMSEXPORT _cmsEncodeDateTimeNumber(cmsDateTimeNumber *Dest, const struct tm *Source); CMSAPI void CMSEXPORT _cmsDecodeDateTimeNumber(const cmsDateTimeNumber *Source, struct tm *Dest); //---------------------------------------------------------------------------------------------------------- // Shared callbacks for user data typedef void (* _cmsFreeUserDataFn)(cmsContext ContextID, void* Data); typedef void* (* _cmsDupUserDataFn)(cmsContext ContextID, const void* Data); //---------------------------------------------------------------------------------------------------------- // Plug-in foundation #define cmsPluginMagicNumber 0x61637070 // 'acpp' #define cmsPluginMemHandlerSig 0x6D656D48 // 'memH' #define cmsPluginInterpolationSig 0x696E7048 // 'inpH' #define cmsPluginParametricCurveSig 0x70617248 // 'parH' #define cmsPluginFormattersSig 0x66726D48 // 'frmH #define cmsPluginTagTypeSig 0x74797048 // 'typH' #define cmsPluginTagSig 0x74616748 // 'tagH' #define cmsPluginRenderingIntentSig 0x696E7448 // 'intH' #define cmsPluginMultiProcessElementSig 0x6D706548 // 'mpeH' #define cmsPluginOptimizationSig 0x6F707448 // 'optH' #define cmsPluginTransformSig 0x7A666D48 // 'xfmH' #define cmsPluginMutexSig 0x6D747A48 // 'mtxH' #define cmsPluginParalellizationSig 0x70726C48 // 'prlH typedef struct _cmsPluginBaseStruct { cmsUInt32Number Magic; // 'acpp' signature cmsUInt32Number ExpectedVersion; // Expected version of LittleCMS cmsUInt32Number Type; // Type of plug-in struct _cmsPluginBaseStruct* Next; // For multiple plugin definition. NULL for end of list. } cmsPluginBase; // Maximum number of types in a plugin array #define MAX_TYPES_IN_LCMS_PLUGIN 20 //---------------------------------------------------------------------------------------------------------- // Memory handler. Each new plug-in type replaces current behaviour typedef void* (* _cmsMallocFnPtrType)(cmsContext ContextID, cmsUInt32Number size); typedef void (* _cmsFreeFnPtrType)(cmsContext ContextID, void *Ptr); typedef void* (* _cmsReallocFnPtrType)(cmsContext ContextID, void* Ptr, cmsUInt32Number NewSize); typedef void* (* _cmsMalloZerocFnPtrType)(cmsContext ContextID, cmsUInt32Number size); typedef void* (* _cmsCallocFnPtrType)(cmsContext ContextID, cmsUInt32Number num, cmsUInt32Number size); typedef void* (* _cmsDupFnPtrType)(cmsContext ContextID, const void* Org, cmsUInt32Number size); typedef struct { cmsPluginBase base; // Required _cmsMallocFnPtrType MallocPtr; _cmsFreeFnPtrType FreePtr; _cmsReallocFnPtrType ReallocPtr; // Optional _cmsMalloZerocFnPtrType MallocZeroPtr; _cmsCallocFnPtrType CallocPtr; _cmsDupFnPtrType DupPtr; } cmsPluginMemHandler; // ------------------------------------------------------------------------------------------------------------------ // Interpolation. 16 bits and floating point versions. struct _cms_interp_struc; // Interpolation callbacks // 16 bits forward interpolation. This function performs precision-limited linear interpolation // and is supposed to be quite fast. Implementation may be tetrahedral or trilinear, and plug-ins may // choose to implement any other interpolation algorithm. typedef void (* _cmsInterpFn16)(CMSREGISTER const cmsUInt16Number Input[], CMSREGISTER cmsUInt16Number Output[], CMSREGISTER const struct _cms_interp_struc* p); // Floating point forward interpolation. Full precision interpolation using floats. This is not a // time critical function. Implementation may be tetrahedral or trilinear, and plug-ins may // choose to implement any other interpolation algorithm. typedef void (* _cmsInterpFnFloat)(cmsFloat32Number const Input[], cmsFloat32Number Output[], const struct _cms_interp_struc* p); // This type holds a pointer to an interpolator that can be either 16 bits or float typedef union { _cmsInterpFn16 Lerp16; // Forward interpolation in 16 bits _cmsInterpFnFloat LerpFloat; // Forward interpolation in floating point } cmsInterpFunction; // Flags for interpolator selection #define CMS_LERP_FLAGS_16BITS 0x0000 // The default #define CMS_LERP_FLAGS_FLOAT 0x0001 // Requires different implementation #define CMS_LERP_FLAGS_TRILINEAR 0x0100 // Hint only #define MAX_INPUT_DIMENSIONS 15 typedef struct _cms_interp_struc { // Used on all interpolations. Supplied by lcms2 when calling the interpolation function cmsContext ContextID; // The calling thread cmsUInt32Number dwFlags; // Keep original flags cmsUInt32Number nInputs; // != 1 only in 3D interpolation cmsUInt32Number nOutputs; // != 1 only in 3D interpolation cmsUInt32Number nSamples[MAX_INPUT_DIMENSIONS]; // Valid on all kinds of tables cmsUInt32Number Domain[MAX_INPUT_DIMENSIONS]; // Domain = nSamples - 1 cmsUInt32Number opta[MAX_INPUT_DIMENSIONS]; // Optimization for 3D CLUT. This is the number of nodes premultiplied for each // dimension. For example, in 7 nodes, 7, 7^2 , 7^3, 7^4, etc. On non-regular // Samplings may vary according of the number of nodes for each dimension. const void *Table; // Points to the actual interpolation table cmsInterpFunction Interpolation; // Points to the function to do the interpolation } cmsInterpParams; // Interpolators factory typedef cmsInterpFunction (* cmsInterpFnFactory)(cmsUInt32Number nInputChannels, cmsUInt32Number nOutputChannels, cmsUInt32Number dwFlags); // The plug-in typedef struct { cmsPluginBase base; // Points to a user-supplied function which implements the factory cmsInterpFnFactory InterpolatorsFactory; } cmsPluginInterpolation; //---------------------------------------------------------------------------------------------------------- // Parametric curves. A negative type means same function but analytically inverted. Max. number of params is 10 // Evaluator callback for user-supplied parametric curves. May implement more than one type typedef cmsFloat64Number (* cmsParametricCurveEvaluator)(cmsInt32Number Type, const cmsFloat64Number Params[10], cmsFloat64Number R); // Plug-in may implement an arbitrary number of parametric curves typedef struct { cmsPluginBase base; cmsUInt32Number nFunctions; // Number of supported functions cmsUInt32Number FunctionTypes[MAX_TYPES_IN_LCMS_PLUGIN]; // The identification types cmsUInt32Number ParameterCount[MAX_TYPES_IN_LCMS_PLUGIN]; // Number of parameters for each function cmsParametricCurveEvaluator Evaluator; // The evaluator } cmsPluginParametricCurves; //---------------------------------------------------------------------------------------------------------- // Formatters. This plug-in adds new handlers, replacing them if they already exist. Formatters dealing with // cmsFloat32Number (bps = 4) or double (bps = 0) types are requested via FormatterFloat callback. Others come across // Formatter16 callback struct _cmstransform_struct; typedef cmsUInt8Number* (* cmsFormatter16)(CMSREGISTER struct _cmstransform_struct* CMMcargo, CMSREGISTER cmsUInt16Number Values[], CMSREGISTER cmsUInt8Number* Buffer, CMSREGISTER cmsUInt32Number Stride); typedef cmsUInt8Number* (* cmsFormatterFloat)(struct _cmstransform_struct* CMMcargo, cmsFloat32Number Values[], cmsUInt8Number* Buffer, cmsUInt32Number Stride); // This type holds a pointer to a formatter that can be either 16 bits or cmsFloat32Number typedef union { cmsFormatter16 Fmt16; cmsFormatterFloat FmtFloat; } cmsFormatter; #define CMS_PACK_FLAGS_16BITS 0x0000 #define CMS_PACK_FLAGS_FLOAT 0x0001 typedef enum { cmsFormatterInput=0, cmsFormatterOutput=1 } cmsFormatterDirection; typedef cmsFormatter (* cmsFormatterFactory)(cmsUInt32Number Type, // Specific type, i.e. TYPE_RGB_8 cmsFormatterDirection Dir, cmsUInt32Number dwFlags); // precision // Plug-in may implement an arbitrary number of formatters typedef struct { cmsPluginBase base; cmsFormatterFactory FormattersFactory; } cmsPluginFormatters; //---------------------------------------------------------------------------------------------------------- // Tag type handler. Each type is free to return anything it wants, and it is up to the caller to // know in advance what is the type contained in the tag. typedef struct _cms_typehandler_struct { cmsTagTypeSignature Signature; // The signature of the type // Allocates and reads items void * (* ReadPtr)(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag); // Writes n Items cmsBool (* WritePtr)(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems); // Duplicate an item or array of items void* (* DupPtr)(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n); // Free all resources void (* FreePtr)(struct _cms_typehandler_struct* self, void *Ptr); // Additional parameters used by the calling thread cmsContext ContextID; cmsUInt32Number ICCVersion; } cmsTagTypeHandler; // Each plug-in implements a single type typedef struct { cmsPluginBase base; cmsTagTypeHandler Handler; } cmsPluginTagType; //---------------------------------------------------------------------------------------------------------- // This is the tag plugin, which identifies tags. For writing, a pointer to function is provided. // This function should return the desired type for this tag, given the version of profile // and the data being serialized. typedef struct { cmsUInt32Number ElemCount; // If this tag needs an array, how many elements should keep // For reading. cmsUInt32Number nSupportedTypes; // In how many types this tag can come (MAX_TYPES_IN_LCMS_PLUGIN maximum) cmsTagTypeSignature SupportedTypes[MAX_TYPES_IN_LCMS_PLUGIN]; // For writing cmsTagTypeSignature (* DecideType)(cmsFloat64Number ICCVersion, const void *Data); } cmsTagDescriptor; // Plug-in implements a single tag typedef struct { cmsPluginBase base; cmsTagSignature Signature; cmsTagDescriptor Descriptor; } cmsPluginTag; //---------------------------------------------------------------------------------------------------------- // Custom intents. This function should join all profiles specified in the array in // a single LUT. Any custom intent in the chain redirects to custom function. If more than // one custom intent is found, the one located first is invoked. Usually users should use only one // custom intent, so mixing custom intents in same multiprofile transform is not supported. typedef cmsPipeline* (* cmsIntentFn)( cmsContext ContextID, cmsUInt32Number nProfiles, cmsUInt32Number Intents[], cmsHPROFILE hProfiles[], cmsBool BPC[], cmsFloat64Number AdaptationStates[], cmsUInt32Number dwFlags); // Each plug-in defines a single intent number. typedef struct { cmsPluginBase base; cmsUInt32Number Intent; cmsIntentFn Link; char Description[256]; } cmsPluginRenderingIntent; // The default ICC intents (perceptual, saturation, rel.col and abs.col) CMSAPI cmsPipeline* CMSEXPORT _cmsDefaultICCintents(cmsContext ContextID, cmsUInt32Number nProfiles, cmsUInt32Number Intents[], cmsHPROFILE hProfiles[], cmsBool BPC[], cmsFloat64Number AdaptationStates[], cmsUInt32Number dwFlags); //---------------------------------------------------------------------------------------------------------- // Pipelines, Multi Process Elements. typedef void (* _cmsStageEvalFn) (const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage* mpe); typedef void*(* _cmsStageDupElemFn) (cmsStage* mpe); typedef void (* _cmsStageFreeElemFn) (cmsStage* mpe); // This function allocates a generic MPE CMSAPI cmsStage* CMSEXPORT _cmsStageAllocPlaceholder(cmsContext ContextID, cmsStageSignature Type, cmsUInt32Number InputChannels, cmsUInt32Number OutputChannels, _cmsStageEvalFn EvalPtr, // Points to fn that evaluates the element (always in floating point) _cmsStageDupElemFn DupElemPtr, // Points to a fn that duplicates the stage _cmsStageFreeElemFn FreePtr, // Points to a fn that sets the element free void* Data); // A generic pointer to whatever memory needed by the element typedef struct { cmsPluginBase base; cmsTagTypeHandler Handler; } cmsPluginMultiProcessElement; // Data kept in "Element" member of cmsStage // Curves typedef struct { cmsUInt32Number nCurves; cmsToneCurve** TheCurves; } _cmsStageToneCurvesData; // Matrix typedef struct { cmsFloat64Number* Double; // floating point for the matrix cmsFloat64Number* Offset; // The offset } _cmsStageMatrixData; // CLUT typedef struct { union { // Can have only one of both representations at same time cmsUInt16Number* T; // Points to the table 16 bits table cmsFloat32Number* TFloat; // Points to the cmsFloat32Number table } Tab; cmsInterpParams* Params; cmsUInt32Number nEntries; cmsBool HasFloatValues; } _cmsStageCLutData; //---------------------------------------------------------------------------------------------------------- // Optimization. Using this plug-in, additional optimization strategies may be implemented. // The function should return TRUE if any optimization is done on the LUT, this terminates // the optimization search. Or FALSE if it is unable to optimize and want to give a chance // to the rest of optimizers. typedef cmsBool (* _cmsOPToptimizeFn)(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags); // Pipeline Evaluator (in 16 bits) typedef void (* _cmsPipelineEval16Fn)(CMSREGISTER const cmsUInt16Number In[], CMSREGISTER cmsUInt16Number Out[], const void* Data); // Pipeline Evaluator (in floating point) typedef void (* _cmsPipelineEvalFloatFn)(const cmsFloat32Number In[], cmsFloat32Number Out[], const void* Data); // This function may be used to set the optional evaluator and a block of private data. If private data is being used, an optional // duplicator and free functions should also be specified in order to duplicate the LUT construct. Use NULL to inhibit such functionality. CMSAPI void CMSEXPORT _cmsPipelineSetOptimizationParameters(cmsPipeline* Lut, _cmsPipelineEval16Fn Eval16, void* PrivateData, _cmsFreeUserDataFn FreePrivateDataFn, _cmsDupUserDataFn DupPrivateDataFn); typedef struct { cmsPluginBase base; // Optimize entry point _cmsOPToptimizeFn OptimizePtr; } cmsPluginOptimization; //---------------------------------------------------------------------------------------------------------- // Full xform typedef struct { cmsUInt32Number BytesPerLineIn; cmsUInt32Number BytesPerLineOut; cmsUInt32Number BytesPerPlaneIn; cmsUInt32Number BytesPerPlaneOut; } cmsStride; typedef void (* _cmsTransformFn)(struct _cmstransform_struct *CMMcargo, // Legacy function, handles just ONE scanline. const void* InputBuffer, void* OutputBuffer, cmsUInt32Number Size, cmsUInt32Number Stride); // Stride in bytes to the next plane in planar formats typedef void (*_cmsTransform2Fn)(struct _cmstransform_struct *CMMcargo, const void* InputBuffer, void* OutputBuffer, cmsUInt32Number PixelsPerLine, cmsUInt32Number LineCount, const cmsStride* Stride); typedef cmsBool (* _cmsTransformFactory)(_cmsTransformFn* xform, void** UserData, _cmsFreeUserDataFn* FreePrivateDataFn, cmsPipeline** Lut, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags); typedef cmsBool (* _cmsTransform2Factory)(_cmsTransform2Fn* xform, void** UserData, _cmsFreeUserDataFn* FreePrivateDataFn, cmsPipeline** Lut, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags); // Retrieve user data as specified by the factory CMSAPI void CMSEXPORT _cmsSetTransformUserData(struct _cmstransform_struct *CMMcargo, void* ptr, _cmsFreeUserDataFn FreePrivateDataFn); CMSAPI void * CMSEXPORT _cmsGetTransformUserData(struct _cmstransform_struct *CMMcargo); // Retrieve formatters CMSAPI void CMSEXPORT _cmsGetTransformFormatters16 (struct _cmstransform_struct *CMMcargo, cmsFormatter16* FromInput, cmsFormatter16* ToOutput); CMSAPI void CMSEXPORT _cmsGetTransformFormattersFloat(struct _cmstransform_struct *CMMcargo, cmsFormatterFloat* FromInput, cmsFormatterFloat* ToOutput); // Retrieve original flags CMSAPI cmsUInt32Number CMSEXPORT _cmsGetTransformFlags(struct _cmstransform_struct* CMMcargo); typedef struct { cmsPluginBase base; // Transform entry point union { _cmsTransformFactory legacy_xform; _cmsTransform2Factory xform; } factories; } cmsPluginTransform; //---------------------------------------------------------------------------------------------------------- // Mutex typedef void* (* _cmsCreateMutexFnPtrType)(cmsContext ContextID); typedef void (* _cmsDestroyMutexFnPtrType)(cmsContext ContextID, void* mtx); typedef cmsBool (* _cmsLockMutexFnPtrType)(cmsContext ContextID, void* mtx); typedef void (* _cmsUnlockMutexFnPtrType)(cmsContext ContextID, void* mtx); typedef struct { cmsPluginBase base; _cmsCreateMutexFnPtrType CreateMutexPtr; _cmsDestroyMutexFnPtrType DestroyMutexPtr; _cmsLockMutexFnPtrType LockMutexPtr; _cmsUnlockMutexFnPtrType UnlockMutexPtr; } cmsPluginMutex; CMSAPI void* CMSEXPORT _cmsCreateMutex(cmsContext ContextID); CMSAPI void CMSEXPORT _cmsDestroyMutex(cmsContext ContextID, void* mtx); CMSAPI cmsBool CMSEXPORT _cmsLockMutex(cmsContext ContextID, void* mtx); CMSAPI void CMSEXPORT _cmsUnlockMutex(cmsContext ContextID, void* mtx); //---------------------------------------------------------------------------------------------------------- // Parallelization CMSAPI _cmsTransform2Fn CMSEXPORT _cmsGetTransformWorker(struct _cmstransform_struct* CMMcargo); CMSAPI cmsInt32Number CMSEXPORT _cmsGetTransformMaxWorkers(struct _cmstransform_struct* CMMcargo); CMSAPI cmsUInt32Number CMSEXPORT _cmsGetTransformWorkerFlags(struct _cmstransform_struct* CMMcargo); // Let's plug-in to guess the best number of workers #define CMS_GUESS_MAX_WORKERS -1 typedef struct { cmsPluginBase base; cmsInt32Number MaxWorkers; // Number of starts to do as maximum cmsUInt32Number WorkerFlags; // Reserved _cmsTransform2Fn SchedulerFn; // callback to setup functions } cmsPluginParalellization; #ifndef CMS_USE_CPP_API # ifdef __cplusplus } # endif #endif #define _lcms_plugin_H #endif
86779202e20d2aa143dffbf9a36e228f450a88e6
8551168c7b71c31eebad0f9b0c71eebbcc743000
/src/include/game/gfxreplace.h
892f1fff3f386df6e8a002059ec9e2c953d8c650
[ "MIT" ]
permissive
n64decomp/perfect_dark
0db80e8ecba74741b959962e55c835a91c920f44
0235a971d6fb1a0d4421856d5a65aa8067bd4658
refs/heads/master
2023-08-31T04:27:53.864767
2023-08-29T11:36:58
2023-08-29T11:36:58
241,214,589
452
47
MIT
2023-08-21T08:53:40
2020-02-17T21:46:45
C
UTF-8
C
false
false
259
h
gfxreplace.h
#ifndef IN_GAME_GFXREPLACE_H #define IN_GAME_GFXREPLACE_H #include <ultra64.h> #include "data.h" #include "types.h" void gfxReplaceGbiCommands(Gfx *gdl, Gfx *endgdl, s32 type); void gfxReplaceGbiCommandsRecursively(struct roomblock *arg0, s32 type); #endif
d796326744132408cf9bff8268cb675fec55a82b
7b92efd7dfb60d9b0a498871d5ffa699d0cf7d9e
/src/modules/gfx_lorenz.c
91992fc2ea962c92516b8f17965f6f6ae3c8c77d
[ "ISC" ]
permissive
shinyblink/sled
854499be7c589b2d705050b41b8324ed66948e45
9d8e60ccbf6d8a30db83f41a8a4435d4c6b317a1
refs/heads/master
2023-07-24T08:30:03.348039
2023-07-08T14:00:54
2023-07-08T22:17:15
115,367,599
107
20
ISC
2023-07-08T22:17:17
2017-12-25T23:06:04
C
UTF-8
C
false
false
4,043
c
gfx_lorenz.c
// Lorenz System // // Copyright (c) 2022, Olaf "Brolf" Pichler <brolf@magheute.net> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <types.h> #include <matrix.h> #include <timers.h> #include <stddef.h> #include <random.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <mathey.h> #include <stdio.h> #define FPS 60 #define FRAMETIME (T_SECOND / FPS) #define FRAMES (TIME_LONG * FPS) static int modno; static unsigned int frame; static oscore_time nexttick; static float delta0; static RGB white = RGB(255, 255, 255); #define P_MAX 15 #define DELTA_T 0.001 typedef vec3 Point; static Point p[P_MAX]; static const float rho = 28.0; static const float sigma = 10.0; static const float beta = 8.0 / 3.0; // Rotations speed in rpm static unsigned int rotate_rpm = 9; static unsigned int xmax; static unsigned int ymax; static const unsigned int frame_xmax = 32; static const unsigned int frame_ymax = 32; int init(int moduleno, char* argstr) { if (matrix_getx() < 64) return 1; if (matrix_gety() < 64) return 1; xmax = matrix_getx(); ymax = matrix_gety(); modno = moduleno; frame = 0; delta0 = 2 * M_PI * rand()/(float)(RAND_MAX); for (int i = 0; i<P_MAX; i++) { p[i].x = rand()/(float)(RAND_MAX)*10.; p[i].y = rand()/(float)(RAND_MAX)*10.; p[i].z = rand()/(float)(RAND_MAX)*10.; } return 0; } void reset(int _modno) { rotate_rpm = randn(3)*3; delta0 = 2 * M_PI * rand()/(float)(RAND_MAX); printf("\nrpm: %i delta0: %f\n",rotate_rpm, delta0); nexttick = udate(); frame = 0; } static void lorenz_int( Point* p, float delta_t) { float dx = sigma * (p->y - p->x); float dy = p->x * (rho - p->z) - p->y; float dz = p->x* p->y - beta * p->z; p->x = p->x + delta_t * dx; p->y = p->y + delta_t * dy; p->z = p->z + delta_t * dz; } int draw(int _modno, int argc, char* argv[]) { for (int x = 0; x < matrix_getx(); x++ ) { for ( int y = 0; y < matrix_gety(); y++ ) { RGB c = matrix_get(x,y); c.red *= 0.99; c.green *= 0.9; c.blue *= 0.8; matrix_set(x,y,c); } } for (int l = 0; l < 10; l++) { for (int i = 0; i < P_MAX; i++) { lorenz_int(&p[i], DELTA_T); float scale; if (rotate_rpm == 0){ scale = 0.0; } else { scale = ((frame % (FPS * 60 / rotate_rpm )) / (FPS * 60.0 / rotate_rpm)); } float delta = delta0 + 2 * M_PI * scale; while (delta < -M_PI) delta += 2 * M_PI; while (delta > M_PI) delta -= 2 * M_PI; float x = p[i].x * cos(delta) - p[i].y * sin(delta); float y = p[i].x * sin(delta) + p[i].y * cos(delta); x = x * (xmax/frame_xmax/2) + xmax/2; y = y * (ymax/frame_ymax/2) + ymax/2; if (x < 0) continue; if (y < 0) continue; if (x >= xmax) continue; if (y >= ymax) continue; matrix_set(x, y, white); } } matrix_render(); if (frame >= FRAMES) { frame = 0; return 1; } frame++; nexttick += FRAMETIME; timer_add(nexttick, modno, 0, NULL); return 0; } void deinit(int _modno) {}
4db90265100bcd45ca6e6ce76a235b9c025632c6
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/SimG4Core/CheckSecondary/test/PlotMultiplicity.C
0c539f64c533bd1032ec999d81fa90e979b2c394
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
C
false
false
26,887
c
PlotMultiplicity.C
#include <iostream> #include <vector> #include <string> #include <map> int mstyle[15] = { 29, 29, 20, 21, 20, 21, 22, 21, 22, 20, 21, 22, 20, 20, 21}; int mcolor[15] = { 1, 1, 3, 3, 4, 4, 4, 7, 7, 7, 2, 2, 2, 28, 28}; float msiz[15] = {1.4,1.4,1.1,1.1,1.1,1.1,1.4,1.1,1.4,1.1,1.1,1.4,1.1,1.1,1.1}; int lcolor[15] = { 1, 1, 3, 3, 4, 4, 4, 7, 7, 7, 2, 2, 2, 28, 28}; int lstyle[15] = { 1, 1, 1, 2, 1, 2, 3, 2, 3, 1, 3, 2, 1, 1, 2}; int lwidth[15] = { 1, 1, 1, 2, 1, 2, 2, 2, 2, 1, 2, 2, 1, 1, 2}; void plotMomentum(char target[6], char list[20], char ene[6], char part[4], char dir[12]="histo", char g4ver[20]="G4.9.1.p01") { setStyle(); gStyle->SetOptLogy(1); std::vector<std::string> types = typesOld(); int energy = atoi(ene); char ofile[100]; sprintf (ofile, "%s/histo_%s%s_%s_%sGeV.root", dir, target, list, part, ene); std::cout << "Input file " << ofile << "\n"; TFile *fout = TFile::Open(ofile); fout->cd(); char name[160], title[160], ctype[20], ytitle[20], cname[160]; TH1F *hiParticle[5][20]; for (unsigned int ii=0; ii<=(types.size()); ii++) { if (ii == 0) sprintf (ctype, "All Particles"); else sprintf (ctype, "%s", types[ii-1].c_str()); for (unsigned int jj=0; jj<5; jj++) { sprintf (name, "Particle%i_KE%s%s%sGeV(%s)",jj,target, list, ene, ctype); hiParticle[jj][ii] = (TH1F*)fout->FindObjectAny(name); hiParticle[jj][ii]->SetFillColor(30); } } TCanvas *c[5]; for (unsigned int jj=0; jj<2; jj++) { hiParticle[jj][11]->Rebin(25); hiParticle[jj][12]->Rebin(25); hiParticle[jj][13]->Rebin(25); sprintf(cname, "c_%s%s%sGeV_nucleons_particle%i", target, list, ene, jj); c[jj] = new TCanvas(cname, cname, 800, 800); c[jj]->Divide(2,2); c[jj]->cd(1); hiParticle[jj][11]->Draw(); c[jj]->cd(2); hiParticle[jj][12]->Draw(); c[jj]->cd(3); hiParticle[jj][13]->Draw(); c[jj]->cd(4); hiParticle[jj][14]->Draw(); } } void plotParticles(char target[6], char list[20], char ene[6], char part[4], char dir[12]="histo", char g4ver[20]="G4.9.1.p01") { gStyle->SetOptLogy(1); gStyle->SetTitleX(.1); gStyle->SetTitleY(.9); std::vector<std::string> types = types(); char ofile[100]; sprintf (ofile, "%s/histo_%s%s_%s_%sGeV.root", dir, target, list, part, ene); std::cout << "Input file " << ofile << "\n"; TFile *fout = TFile::Open(ofile); fout->cd(); char ctype[20], title[160], cname[160]; sprintf(ctype,"Ions"); TH1F *hProton[2], *hNeutron[2], *hHeavy[2], *hIon[2]; TH1F *hProton_1[2], *hNeutron_1[2], *hHeavy_1[2], *hIon_1[2]; for (int i=0; i<2; i++) { sprintf(title, "proton%i_%s%s%sGeV(%s)", i, target, list, ene, ctype); hProton[i] = (TH1F*)fout->FindObjectAny(title); sprintf(title, "proton%i_%s%s%sGeV", i, target, list, ene); hProton[i]->SetName(title); hProton[i]->SetTitle(title); hProton_1[i] = (TH1F*) hProton[i]->Clone(); sprintf(title, "new_%s", title); hProton_1[i]->SetName(title); sprintf(title, "neutron%i_%s%s%sGeV(%s)", i, target, list, ene, ctype); hNeutron[i] = (TH1F*)fout->FindObjectAny(title); sprintf(title, "neutron%i_%s%s%sGeV", i, target, list, ene); hNeutron[i]->SetName(title); hNeutron[i]->SetTitle(title); hNeutron_1[i] = (TH1F*) hNeutron[i]->Clone(); sprintf(title, "new_%s", title); hNeutron_1[i]->SetName(title); sprintf(title, "heavy%i_%s%s%sGeV(%s)", i, target, list, ene, ctype); hHeavy[i] = (TH1F*)fout->FindObjectAny(title); sprintf(title, "heavy%i_%s%s%sGeV", i, target, list, ene); hHeavy[i]->SetName(title); hHeavy[i]->SetTitle(title); hHeavy_1[i] = (TH1F*) hHeavy[i]->Clone(); sprintf(title, "new_%s", title); hHeavy_1[i]->SetName(title); sprintf(title, "ion%i_%s%s%sGeV(%s)", i, target, list, ene, ctype); hIon[i] = (TH1F*)fout->FindObjectAny(title); sprintf(title, "ion%i_%s%s%sGeV", i, target, list, ene); hIon[i]->SetName(title); hIon[i]->SetTitle(title); hIon_1[i] = (TH1F*) hIon[i]->Clone(); sprintf(title, "new_%s", title); hIon_1[i]->SetName(title); } int energy = atoi(ene); std::cout << "Energy " << energy << "\n"; if (energy>=10) { hProton[0]->Rebin(5); hProton[1]->Rebin(5); hProton_1[0]->GetXaxis()->SetRangeUser(0.0, 5.0); hProton_1[1]->GetXaxis()->SetRangeUser(0.0, 2.5); hNeutron[0]->Rebin(5); hNeutron[1]->Rebin(5); hNeutron_1[0]->GetXaxis()->SetRangeUser(0.0, 5.0); hNeutron_1[1]->GetXaxis()->SetRangeUser(0.0, 2.5); hHeavy[0]->Rebin(5); hHeavy[1]->Rebin(5); hHeavy_1[0]->GetXaxis()->SetRangeUser(0.0, 5.0); hHeavy_1[1]->GetXaxis()->SetRangeUser(0.0, 5.0); hIon[0]->GetXaxis()->SetRangeUser(0.0, 0.03); hIon[1]->GetXaxis()->SetRangeUser(0.0, 0.03); } else { hProton_1[0]->GetXaxis()->SetRangeUser(0.0, 1.0); hProton_1[1]->GetXaxis()->SetRangeUser(0.0, 0.5); hNeutron_1[0]->GetXaxis()->SetRangeUser(0.0, 1.0); hNeutron_1[1]->GetXaxis()->SetRangeUser(0.0, 0.5); hHeavy_1[0]->GetXaxis()->SetRangeUser(0.0, 5.0); hHeavy_1[1]->GetXaxis()->SetRangeUser(0.0, 5.0); hIon[0]->Rebin(5); hIon[1]->Rebin(5); hIon[0]->GetXaxis()->SetRangeUser(0.0, 1.5); hIon[1]->GetXaxis()->SetRangeUser(0.0, 1.5); } for (int i=0; i<2; i++) { hProton[i]->SetFillColor(30); hNeutron[i]->SetFillColor(30); hHeavy[i]->SetFillColor(30); hIon[i]->SetFillColor(30); hProton_1[i]->SetFillColor(30); hNeutron_1[i]->SetFillColor(30); hHeavy_1[i]->SetFillColor(30); hIon_1[i]->SetFillColor(30); hProton[i]->GetXaxis()->SetRangeUser(0.0, energy); hNeutron[i]->GetXaxis()->SetRangeUser(0.0, energy); hHeavy[i]->GetXaxis()->SetRangeUser(0.0, energy); } sprintf(cname, "c_%s%s%sGeV_protons", target, list, ene); TCanvas *cc4 = new TCanvas(cname, cname, 800, 800); cc4->Divide(2,2); cc4->cd(1); hProton[0]->Draw(); cc4->cd(2); hProton_1[0]->Draw(); cc4->cd(3); hProton[1]->Draw(); cc4->cd(4); hProton_1[1]->Draw(); sprintf(cname, "c_%s%s%sGeV_neutrons", target, list, ene); TCanvas *cc5 = new TCanvas(cname, cname, 800, 800); cc5->Divide(2,2); cc5->cd(1); hNeutron[0]->Draw(); cc5->cd(2); hNeutron_1[0]->Draw(); cc5->cd(3); hNeutron[1]->Draw(); cc5->cd(4); hNeutron_1[1]->Draw(); sprintf(cname, "c_%s%s%sGeV_Heavy", target, list, ene); TCanvas *cc6 = new TCanvas(cname, cname, 800, 800); cc6->Divide(2,2); cc6->cd(1); hHeavy[0]->Draw(); cc6->cd(2); hHeavy_1[0]->Draw(); cc6->cd(3); hHeavy[1]->Draw(); cc6->cd(4); hHeavy_1[1]->Draw(); sprintf(cname, "c_%s%s%sGeV_Ion", target, list, ene); TCanvas *cc7 = new TCanvas(cname, cname, 800, 500); cc7->Divide(2,1); cc7->cd(1); hIon[0]->Draw(); cc7->cd(2); hIon[1]->Draw(); } void plotMultiplicity(char target[6], char list[20], char part[4], int ymax=25, char dir[12]="histo", char g4ver[20]="G4.9.1.p01", bool flag=true) { setStyle(); gStyle->SetOptTitle(0); char name[1024], sym[10]; if (part=="pim") sprintf(sym, "#pi^{-}"); else if (part=="pip") sprintf(sym, "#pi^{+}"); else sprintf(sym, "p"); std::map<string, double> means_300=getMean(target,list,part,"300.0","Multi",dir); std::map<string, double> means_200=getMean(target,list,part,"200.0","Multi",dir); std::map<string, double> means_150=getMean(target,list,part,"150.0","Multi",dir); std::map<string, double> means_100=getMean(target,list,part,"100.0","Multi",dir); std::map<string, double> means_50 =getMean(target,list,part,"50.0", "Multi",dir); std::map<string, double> means_30 =getMean(target,list,part,"30.0", "Multi",dir); std::map<string, double> means_20 =getMean(target,list,part,"20.0", "Multi",dir); std::map<string, double> means_15 =getMean(target,list,part,"15.0", "Multi",dir); std::map<string, double> means_9 =getMean(target,list,part,"9.0", "Multi",dir); std::map<string, double> means_7 =getMean(target,list,part,"7.0", "Multi",dir); std::map<string, double> means_5 =getMean(target,list,part,"5.0", "Multi",dir); std::map<string, double> means_3 =getMean(target,list,part,"3.0", "Multi",dir); std::map<string, double> means_2 =getMean(target,list,part,"2.0", "Multi",dir); std::map<string, double> means_1 =getMean(target,list,part,"1.0", "Multi",dir); if (flag) { std::map<string, double> means_10 =getMean(target,list,part,"10.0", "Multi",dir); std::map<string, double> means_8 =getMean(target,list,part,"8.0", "Multi",dir); std::map<string, double> means_6 =getMean(target,list,part,"6.0", "Multi",dir); std::map<string, double> means_4 =getMean(target,list,part,"4.0", "Multi",dir); } char ctype[20]; std::vector<std::string> types = types(); std::vector<std::string> typeOld = typesOld(); // std::cout << "Number of types: " << types.size() << "\n"; TGraph *gr[20]; TLegend *leg = new TLegend(0.45, 0.53, 0.90, 0.90); char hdr[160]; sprintf(hdr, "%s+%s (%s-%s)", sym, target, g4ver, list); leg->SetHeader(hdr); leg->SetFillColor(10); leg->SetMargin(0.45); leg->SetTextSize(.027); sprintf(name, "c_%s_%sMultiplicity_%s", part,target,list); TCanvas *cc = new TCanvas(name, name, 700, 700); for (unsigned int ii=0; ii<=(types.size()); ii++) { if (ii == 0) sprintf (ctype, "All Particles"); else sprintf (ctype, "%s", typeOld[ii-1].c_str()); // std::cout<<"ii "<<ii<<" ctype "<<ctype<<std::endl; string a(ctype); double vx[18], vy[18]; int np=0; vx[np] = 300.0; vy[np] = means_300[a]; np++; vx[np] = 200.0; vy[np] = means_200[a]; np++; vx[np] = 150.0; vy[np] = means_150[a]; np++; vx[np] = 100.0; vy[np] = means_100[a]; np++; vx[np] = 50.0; vy[np] = means_50[a]; np++; vx[np] = 30.0; vy[np] = means_30[a]; np++; vx[np] = 20.0; vy[np] = means_20[a]; np++; vx[np] = 15.0; vy[np] = means_15[a]; np++; if (flag) { vx[np] = 10.0; vy[np] = means_10[a]; np++;} vx[np] = 9.0; vy[np] = means_9[a]; np++; if (flag) { vx[np] = 8.0; vy[np] = means_8[a]; np++;} vx[np] = 7.0; vy[np] = means_7[a]; np++; if (flag) { vx[np] = 6.0; vy[np] = means_6[a]; np++;} vx[np] = 5.0; vy[np] = means_5[a]; np++; if (flag && part != "pro") { vx[np] = 4.0; vy[np] = means_4[a]; np++;} vx[np] = 3.0; vy[np] = means_3[a]; np++; vx[np] = 2.0; vy[np] = means_2[a]; np++; vx[np] = 1.0; vy[np] = means_1[a]; np++; if (ii > 20 ) { std::cout << ctype; for (int ix=0; ix<np; ix++) std::cout << " " << vx[ix] << " " << vy[ix]; std::cout << "\n"; } gPad->SetLogx(1); gPad->SetGridx(1); gPad->SetGridy(1); gr[ii] = new TGraph(np, vx,vy); sprintf(name, "Multiplicity of secondaries %s-%s (%s %s)", sym, target, g4ver, list); gr[ii]->SetTitle(name); gr[ii]->GetXaxis()->SetTitle("Beam Momentum (GeV)"); gr[ii]->GetYaxis()->SetTitle("Average Multiplicity"); gr[ii]->SetMarkerStyle(mstyle[ii]); gr[ii]->SetMarkerSize(msiz[ii]); gr[ii]->SetMarkerColor(mcolor[ii]); gr[ii]->SetLineColor(lcolor[ii]); gr[ii]->SetLineStyle(lstyle[ii]); gr[ii]->SetLineWidth(lwidth[ii]); gr[ii]->GetYaxis()->SetRangeUser(-0.2, ymax); if (ii>1) { sprintf (ctype, "%s", types[ii-1].c_str()); leg->AddEntry(gr[ii], ctype, "lP"); } if (ii==2) gr[ii]->Draw("APl"); else if (ii>2) gr[ii]->Draw("Pl"); } leg->Draw("same"); } void plotMultiplicity(char target[6], char list[20], char ene[6], char part[4], char dir[12]="histo", char g4ver[20]="G4.9.1.p01") { setStyle(); gStyle->SetOptTitle(0); char name[1024], sym[10]; if (part=="pim") sprintf(sym, "#pi^{-}"); else if (part=="pip") sprintf(sym, "#pi^{+}"); else sprintf(sym, "p"); std::vector<std::string> typeOld = typesOld(); int energy = atoi(ene); char ofile[100]; sprintf (ofile, "%s/histo_%s%s_%s_%sGeV.root", dir, target, list, part, ene); std::cout << "Input file " << ofile << "\n"; TFile *fout = TFile::Open(ofile); fout->cd(); char name[160], title[160], ctype[20], ytitle[20], cname[160]; TH1I *hiMulti[20]; for (unsigned int ii=0; ii<=(typeOld.size()); ii++) { if (ii == 0) sprintf (ctype, "All Particles"); else sprintf (ctype, "%s", typeOld[ii-1].c_str()); sprintf (name, "Multi%s%s%sGeV(%s)", target, list, ene, ctype); hiMulti[ii] = (TH1I*)fout->FindObjectAny(name); // std::cout << ii << " (" << ctype << ") " << name << " " << hiMulti[ii] << "\n"; } TCanvas *c[20]; std::vector<std::string> types = types(); for (unsigned int ii=0; ii<types.size(); ii++) { if (ii == 0) sprintf (ctype, "All Particles"); else sprintf (ctype, "%s", types[ii-1].c_str()); sprintf (cname, "Multiplicity (%s)", ctype); hiMulti[ii]->GetXaxis()->SetTitle(cname); hiMulti[ii]->SetMarkerStyle(mstyle[ii]); hiMulti[ii]->SetMarkerSize(msiz[ii]); hiMulti[ii]->SetMarkerColor(mcolor[ii]); hiMulti[ii]->SetLineColor(lcolor[ii]); hiMulti[ii]->SetLineStyle(lstyle[ii]); hiMulti[ii]->SetLineWidth(lwidth[ii]); sprintf(cname, "c_%s%s_%s_%sGeV_Multiplicity(%s)", target, list, part, ene, ctype); c[ii] = new TCanvas(cname, cname, 800, 500); hiMulti[ii]->Draw(); TLegend *leg = new TLegend(0.35, 0.80, 0.8, 0.87); char hdr[160]; sprintf(hdr, "%s+%s at %s GeV (%s-%s)", sym, target, ene, g4ver, list); leg->SetHeader(hdr); leg->SetFillColor(10); leg->SetMargin(0.45); leg->SetTextSize(.036); leg->Draw("same"); } } void plotTotalKE(char target[6], char list[20], char part[4], char dir[12]="histo", char g4ver[20]="G4.9.1.p01", bool flag=true) { setStyle(); gStyle->SetOptTitle(0); char name[1024]; char sym[10]; if (part=="pim") sprintf(sym, "#pi^{-}"); else if (part=="pip") sprintf(sym, "#pi^{+}"); else sprintf(sym, "p"); std::map<string, double> means_300=getMean(target,list,part,"300.0","TotalKE",dir); std::map<string, double> means_200=getMean(target,list,part,"200.0","TotalKE",dir); std::map<string, double> means_150=getMean(target,list,part,"150.0","TotalKE",dir); std::map<string, double> means_100=getMean(target,list,part,"100.0","TotalKE",dir); std::map<string, double> means_50 =getMean(target,list,part,"50.0", "TotalKE",dir); std::map<string, double> means_30 =getMean(target,list,part,"30.0", "TotalKE",dir); std::map<string, double> means_20 =getMean(target,list,part,"20.0", "TotalKE",dir); std::map<string, double> means_15 =getMean(target,list,part,"15.0", "TotalKE",dir); std::map<string, double> means_9 =getMean(target,list,part,"9.0", "TotalKE",dir); std::map<string, double> means_7 =getMean(target,list,part,"7.0", "TotalKE",dir); std::map<string, double> means_5 =getMean(target,list,part,"5.0", "TotalKE",dir); std::map<string, double> means_3 =getMean(target,list,part,"3.0", "TotalKE",dir); std::map<string, double> means_2 =getMean(target,list,part,"2.0", "TotalKE",dir); std::map<string, double> means_1 =getMean(target,list,part,"1.0", "TotalKE",dir); if (flag) { std::map<string, double> means_10 =getMean(target,list,part,"10.0", "TotalKE",dir); std::map<string, double> means_8 =getMean(target,list,part,"8.0", "TotalKE",dir); std::map<string, double> means_6 =getMean(target,list,part,"6.0", "TotalKE",dir); std::map<string, double> means_4 =getMean(target,list,part,"4.0", "TotalKE",dir); } char ctype[20]; std::vector<std::string> types = types(); std::vector<std::string> typeOld = typesOld(); // std::cout << "Number of types " << types.size() << "\n"; TGraph *gr[20]; TLegend *leg = new TLegend(0.55, 0.45, 0.9, 0.80); char hdr[160]; sprintf(hdr, "%s+%s (%s-%s)", sym, target, g4ver, list); leg->SetHeader(hdr); leg->SetFillColor(10); leg->SetMargin(0.45); leg->SetTextSize(.02); sprintf(name, "c_%s_%s_totalKE_%s", part,target,list); TCanvas *cc = new TCanvas(name, name, 700, 700); for (unsigned int ii=0; ii<=(types.size()); ii++) { if (ii == 0) sprintf (ctype, "All Particles"); else sprintf (ctype, "%s", typeOld[ii-1].c_str()); string a(ctype); // std::cout<<a<<" "<< means_300[a]<<std::endl; double vx[18], vy[18]; int np=0; vx[np] = 300.0; vy[np] = means_300[a]; np++; vx[np] = 200.0; vy[np] = means_200[a]; np++; vx[np] = 150.0; vy[np] = means_150[a]; np++; vx[np] = 100.0; vy[np] = means_100[a]; np++; vx[np] = 50.0; vy[np] = means_50[a]; np++; vx[np] = 30.0; vy[np] = means_30[a]; np++; vx[np] = 20.0; vy[np] = means_20[a]; np++; vx[np] = 15.0; vy[np] = means_15[a]; np++; if (flag) { vx[np] = 10.0; vy[np] = means_10[a]; np++;} vx[np] = 9.0; vy[np] = means_9[a]; np++; if (flag) { vx[np] = 8.0; vy[np] = means_8[a]; np++;} vx[np] = 7.0; vy[np] = means_7[a]; np++; if (flag) { vx[np] = 6.0; vy[np] = means_6[a]; np++;} vx[np] = 5.0; vy[np] = means_5[a]; np++; if (flag && part != "pro") { vx[np] = 4.0; vy[np] = means_4[a]; np++;} vx[np] = 3.0; vy[np] = means_3[a]; np++; vx[np] = 2.0; vy[np] = means_2[a]; np++; vx[np] = 1.0; vy[np] = means_1[a]; np++; for (int i=0; i<np; i++) vy[i] = vy[i]/vx[i]; gPad->SetLogx(1); gPad->SetGridx(1); gPad->SetGridy(1); gr[ii] = new TGraph(np, vx,vy); sprintf(name, "KE carried by secondaries in %s-%s (%s)", sym, target, list); gr[ii]->SetTitle(name); gr[ii]->GetXaxis()->SetTitle("Beam Momentum (GeV)"); gr[ii]->GetYaxis()->SetTitle("Mean Total KE/Beam Momentum"); gr[ii]->SetMarkerStyle(mstyle[ii]); gr[ii]->SetMarkerSize(msiz[ii]); gr[ii]->SetMarkerColor(mcolor[ii]); gr[ii]->SetLineColor(lcolor[ii]); gr[ii]->SetLineStyle(lstyle[ii]); gr[ii]->SetLineWidth(lwidth[ii]); gr[ii]->GetYaxis()->SetRangeUser(-0.02, 1.0); if (ii!= 0) sprintf (ctype, "%s", types[ii-1].c_str()); if (ii!= 1) leg->AddEntry(gr[ii], ctype, "lP"); if (ii==0) gr[ii]->Draw("APl"); else if (ii>1) gr[ii]->Draw("Pl"); } leg->Draw("same"); } void plotKE(char target[6], char list[20], char ene[6], char part[4], int typ=0, char dir[12]="histo", char g4ver[20]="G4.9.1.p01") { setStyle(); gStyle->SetOptTitle(0); gStyle->SetOptLogy(1); char name[1024]; char sym[10]; if (part=="pim") sprintf(sym, "#pi^{-}"); else if (part=="pip") sprintf(sym, "#pi^{+}"); else sprintf(sym, "p"); std::vector<std::string> typeOld = typesOld(); int energy = atoi(ene); int bins=energy/4; float ener = energy; std::cout << "Energy " << ener << "\n"; char ofile[100]; sprintf (ofile, "%s/histo_%s%s_%s_%sGeV.root", dir, target, list, part, ene); std::cout << "Input file " << ofile << "\n"; TFile *fout = TFile::Open(ofile); fout->cd(); char name[160], title[160], ctype[20], ytitle[20], cname[160], pre[10]; TH1F *hiKE[20]; if (typ == 0) sprintf (pre, "KE2"); else sprintf (pre, "TotalKE"); for (unsigned int ii=0; ii<=(typeOld.size()); ii++) { if (ii == 0) sprintf (ctype, "All Particles"); else sprintf (ctype, "%s", typeOld[ii-1].c_str()); sprintf (name, "%s%s%s%sGeV(%s)", pre, target, list, ene, ctype); hiKE[ii] = (TH1F*)fout->FindObjectAny(name); // std::cout << ii << " (" << ctype << ") " << name << " " << hiKE[ii] <<"\n"; } TCanvas *c[25]; std::vector<std::string> types = types(); for (unsigned int ii=0; ii<types.size(); ii++) { if (ii == 0) sprintf (ctype, "All Particles"); else sprintf (ctype, "%s", types[ii-1].c_str()); if (typ == 0) sprintf (cname, "Kinetic Energy of %s (GeV)", ctype); else sprintf (cname, "Total Kinetic Energy of %s (GeV)", ctype); hiKE[ii]->GetXaxis()->SetTitle(cname); hiKE[ii]->SetMarkerStyle(mstyle[ii]); hiKE[ii]->SetMarkerSize(msiz[ii]); hiKE[ii]->SetMarkerColor(mcolor[ii]); hiKE[ii]->SetLineColor(lcolor[ii]); hiKE[ii]->SetLineStyle(lstyle[ii]); hiKE[ii]->SetLineWidth(lwidth[ii]); if (bins > 0) hiKE[ii]->Rebin(bins); hiKE[ii]->GetXaxis()->SetRangeUser(0.0, ener); sprintf(cname, "c_%s%s_%s_%sGeV_%s(%s)", target,list,part,ene,pre,ctype); c[ii] = new TCanvas(cname, cname, 800, 500); hiKE[ii]->Draw(); TLegend *leg = new TLegend(0.35, 0.80, 0.8, 0.87); char hdr[160]; sprintf(hdr, "%s+%s at %s GeV (%s-%s)", sym, target, ene, g4ver, list); leg->SetHeader(hdr); leg->SetFillColor(10); leg->SetMargin(0.45); leg->SetTextSize(.036); leg->Draw("same"); } TLegend *leg1 = new TLegend(0.50, 0.75, 0.90, 0.90); if (typ == 0) sprintf (cname, "Kinetic Energy (GeV)"); else sprintf (cname, "Total Kinetic Energy (GeV)"); hiKE[6]->GetXaxis()->SetTitle(cname); char hdr[160]; sprintf(hdr, "%s+%s at %s GeV (%s-%s)", sym, target, ene, g4ver, list); leg1->SetHeader(hdr); leg1->SetFillColor(10); leg1->SetMargin(0.45); sprintf(cname, "c_%s%s_%s_%sGeV_%s(Pion)", target,list,part,ene,pre); leg1->SetTextSize(.030); c[19] = new TCanvas(cname, cname, 800, 500); hiKE[6]->Draw(); sprintf (ctype, "%s", types[5].c_str()); leg1->AddEntry(hiKE[6], ctype, "l"); hiKE[5]->Draw("same"); sprintf (ctype, "%s", types[4].c_str()); leg1->AddEntry(hiKE[5], ctype, "l"); hiKE[4]->Draw("same"); sprintf (ctype, "%s", types[3].c_str()); leg1->AddEntry(hiKE[4], ctype, "l"); leg->Draw("same"); TLegend *leg2 = new TLegend(0.50, 0.75, 0.90, 0.90); if (typ == 0) sprintf (cname, "Kinetic Energy (GeV)"); else sprintf (cname, "Total Kinetic Energy (GeV)"); hiKE[7]->GetXaxis()->SetTitle(cname); sprintf(hdr, "%s+%s at %s GeV (%s-%s)", sym, target, ene, g4ver, list); leg2->SetHeader(hdr); leg2->SetFillColor(10); leg2->SetMargin(0.45); sprintf(cname, "c_%s%s_%s_%sGeV_%s(Kaon)", target,list,part,ene,pre); leg2->SetTextSize(.030); c[20] = new TCanvas(cname, cname, 800, 500); hiKE[7]->Draw(); sprintf (ctype, "%s", types[6].c_str()); leg2->AddEntry(hiKE[7], ctype, "l"); hiKE[8]->Draw("same"); sprintf (ctype, "%s", types[7].c_str()); leg2->AddEntry(hiKE[8], ctype, "l"); hiKE[9]->Draw("same"); sprintf (ctype, "%s", types[8].c_str()); leg2->AddEntry(hiKE[9], ctype, "l"); leg2->Draw("same"); TLegend *leg3 = new TLegend(0.50, 0.75, 0.90, 0.90); if (typ == 0) sprintf (cname, "Kinetic Energy (GeV)"); else sprintf (cname, "Total Kinetic Energy (GeV)"); hiKE[12]->GetXaxis()->SetTitle(cname); sprintf(hdr, "%s+%s at %s GeV (%s-%s)", sym, target, ene, g4ver, list); leg3->SetHeader(hdr); leg3->SetFillColor(10); leg3->SetMargin(0.45); sprintf(cname, "c_%s%s_%s_%sGeV_%s(Nucleon)", target,list,part,ene,pre); leg3->SetTextSize(.030); c[21] = new TCanvas(cname, cname, 800, 500); hiKE[12]->Draw(); sprintf (ctype, "%s", types[11].c_str()); leg3->AddEntry(hiKE[12], ctype, "l"); hiKE[11]->Draw("same"); sprintf (ctype, "%s", types[10].c_str()); leg3->AddEntry(hiKE[11], ctype, "l"); leg3->Draw("same"); } void printMeans(std::map<string, double> means) { std::map<string, double>::iterator iter; for( iter = means.begin(); iter != means.end(); iter++ ) { std::cout << (*iter).first << " " << (*iter).second << "\n"; } } std::map<string, double> getMean(char target[6], char list[20], char part[5], char ene[6], char ctyp0[10]="Multi", char dir[12]="histo") { std::vector<std::string> types = typesOld(); std::map<string, double> means; char ofile[100]; sprintf (ofile, "%s/histo_%s%s_%s_%sGeV.root", dir, target, list, part, ene); std::cout << "Input File: " << ofile << "\n"; TFile *fout = TFile::Open(ofile); fout->cd(); TH1I *hi[20]; char name[160], title[160], ctype[20]; for (unsigned int ii=0; ii<=(types.size()); ii++) { if (ii == 0) sprintf (ctype, "All Particles"); else sprintf (ctype, "%s", types[ii-1].c_str()); sprintf (name, "%s%s%s%sGeV(%s)", ctyp0, target, list, ene, ctype); hi[ii] = (TH1I*)fout->FindObjectAny(name); // std::cout << "Histo " << ii << " Name " << name << " " << hi[ii] << " " << hi[ii]->GetMean() << "\n"; string a(ctype); means[a] = hi[ii]->GetMean(); } // printMeans(means); return means; } std::vector<std::string> types() { std::vector<string> tmp; tmp.push_back("Photon/Neutrino"); // 1 tmp.push_back("e^{-}"); // 2 tmp.push_back("e^{+}"); // 3 tmp.push_back("#pi^{0}"); // 4 tmp.push_back("#pi^{-}"); // 5 tmp.push_back("#pi^{+}"); // 6 tmp.push_back("K^{-}"); // 7 tmp.push_back("K^{+}"); // 8 tmp.push_back("K^{0}"); // 9 tmp.push_back("AntiProton"); // 10 tmp.push_back("p"); // 11 tmp.push_back("n"); // 12 tmp.push_back("Heavy Hadrons"); // 13 tmp.push_back("Ions"); // 14 return tmp; } std::vector<std::string> typesOld() { std::vector<string> tmp; tmp.push_back("Photon/Neutrino"); // 1 tmp.push_back("Electron"); // 2 tmp.push_back("Positron"); // 3 tmp.push_back("Pizero"); // 4 tmp.push_back("Piminus"); // 5 tmp.push_back("Piplus"); // 6 tmp.push_back("Kminus"); // 7 tmp.push_back("Kiplus"); // 8 tmp.push_back("Kzero"); // 9 tmp.push_back("AntiProton"); // 10 tmp.push_back("Proton"); // 11 tmp.push_back("Neutron/AntiNeutron"); // 12 tmp.push_back("Heavy Hadrons"); // 13 tmp.push_back("Ions"); // 14 return tmp; } std::vector<double> massScan() { std::vector<double> tmp; tmp.push_back(0.01); tmp.push_back(1.00); tmp.push_back(135.0); tmp.push_back(140.0); tmp.push_back(495.0); tmp.push_back(500.0); tmp.push_back(938.5); tmp.push_back(940.0); tmp.push_back(1850.0); std::cout << tmp.size() << " Mass regions for prtaicles: "; for (unsigned int i=0; i<tmp.size(); i++) { std::cout << tmp[i]; if (i == tmp.size()-1) std::cout << " MeV\n"; else std::cout << ", "; } return tmp; } void setStyle() { gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(kWhite); gStyle->SetPadColor(kWhite); gStyle->SetFrameBorderMode(0); gStyle->SetFrameBorderSize(1); gStyle->SetFrameFillColor(0); gStyle->SetFrameFillStyle(0); gStyle->SetFrameLineColor(1); gStyle->SetFrameLineStyle(1); gStyle->SetFrameLineWidth(1); gStyle->SetTitleOffset(1.2,"Y"); gStyle->SetOptStat(0); gStyle->SetLegendBorderSize(1); }
30e4e9fc76a8a808defcbbafc54b9198814f588f
ecce427678ecff2a93a47f3b1b664202c7d27617
/levels/bits/areas/1/27/collision.inc.c
be82522d9f71cb2db0e2f0933c45b31c72ffdbb4
[]
no_license
sm64pc/sm64ex
ecf37f31b3f7426c4874254660d856030d789714
54cd27ccee45a2403b45f07a00d6043c51149969
refs/heads/nightly
2023-08-11T12:14:34.424168
2023-07-01T11:45:50
2023-07-01T11:45:50
262,091,731
795
238
null
2023-07-01T11:45:51
2020-05-07T15:43:27
C
UTF-8
C
false
false
2,957
c
collision.inc.c
// 0x0701AE5C - 0x0701B0D2 const Collision bits_seg7_collision_0701AE5C[] = { COL_INIT(), COL_VERTEX_INIT(0x24), COL_VERTEX(614, 51, 216), COL_VERTEX(819, 51, 216), COL_VERTEX(307, 51, 779), COL_VERTEX(614, 205, 216), COL_VERTEX(819, 205, 216), COL_VERTEX(973, 205, -193), COL_VERTEX(973, 51, -193), COL_VERTEX(1382, 51, -193), COL_VERTEX(1382, 51, 216), COL_VERTEX(1024, 51, 779), COL_VERTEX(1024, 205, 779), COL_VERTEX(1382, 205, -193), COL_VERTEX(-1381, 205, -193), COL_VERTEX(-972, 51, -193), COL_VERTEX(-1381, 51, 216), COL_VERTEX(-818, 205, 216), COL_VERTEX(-972, 205, -193), COL_VERTEX(-613, 205, 216), COL_VERTEX(-1381, 205, 216), COL_VERTEX(-1023, 205, 779), COL_VERTEX(-101, 205, 164), COL_VERTEX(-306, 205, 779), COL_VERTEX(307, 205, 779), COL_VERTEX(102, 205, 164), COL_VERTEX(1382, 205, 216), COL_VERTEX(307, 205, -551), COL_VERTEX(307, 51, -551), COL_VERTEX(-306, 205, -551), COL_VERTEX(-613, 51, 216), COL_VERTEX(-1023, 51, 779), COL_VERTEX(102, 51, 164), COL_VERTEX(-101, 51, 164), COL_VERTEX(-1381, 51, -193), COL_VERTEX(-818, 51, 216), COL_VERTEX(-306, 51, 779), COL_VERTEX(-306, 51, -551), COL_TRI_INIT(SURFACE_DEFAULT, 67), COL_TRI(0, 1, 2), COL_TRI(3, 4, 1), COL_TRI(3, 1, 0), COL_TRI(1, 4, 5), COL_TRI(1, 5, 6), COL_TRI(1, 6, 7), COL_TRI(1, 7, 8), COL_TRI(1, 8, 9), COL_TRI(1, 9, 2), COL_TRI(10, 5, 4), COL_TRI(10, 4, 3), COL_TRI(10, 11, 5), COL_TRI(5, 7, 6), COL_TRI(12, 13, 32), COL_TRI(12, 16, 13), COL_TRI(13, 16, 15), COL_TRI(13, 15, 33), COL_TRI(14, 13, 33), COL_TRI(14, 32, 13), COL_TRI(15, 16, 19), COL_TRI(16, 18, 19), COL_TRI(16, 12, 18), COL_TRI(12, 32, 14), COL_TRI(12, 14, 18), COL_TRI(15, 17, 28), COL_TRI(15, 28, 33), COL_TRI(17, 15, 19), COL_TRI(18, 14, 29), COL_TRI(19, 18, 29), COL_TRI(19, 21, 20), COL_TRI(17, 19, 20), COL_TRI(20, 21, 34), COL_TRI(21, 19, 29), COL_TRI(21, 29, 34), COL_TRI(20, 34, 31), COL_TRI(20, 23, 27), COL_TRI(20, 27, 17), COL_TRI(22, 23, 30), COL_TRI(23, 20, 31), COL_TRI(23, 31, 30), COL_TRI(23, 10, 3), COL_TRI(23, 3, 27), COL_TRI(23, 22, 10), COL_TRI(22, 30, 2), COL_TRI(7, 24, 8), COL_TRI(24, 10, 9), COL_TRI(10, 22, 2), COL_TRI(10, 2, 9), COL_TRI(10, 24, 11), COL_TRI(24, 9, 8), COL_TRI(7, 11, 24), COL_TRI(3, 25, 27), COL_TRI(3, 26, 25), COL_TRI(3, 0, 26), COL_TRI(27, 25, 26), COL_TRI(27, 26, 35), COL_TRI(27, 35, 28), COL_TRI(27, 28, 17), COL_TRI(28, 35, 26), COL_TRI(29, 28, 26), COL_TRI(29, 14, 28), COL_TRI(0, 2, 30), COL_TRI(26, 0, 30), COL_TRI(31, 29, 26), COL_TRI(26, 30, 31), COL_TRI(31, 34, 29), COL_TRI(5, 11, 7), COL_TRI_STOP(), COL_END(), };
f0e6c7577d63763c3836d7b95d80205c26f615ce
65089dbc386e1184983c15fe3a2282763ae65960
/gear-lib/libposix/MsvcLibX/src/getcwd.c
22146b30243bad212e22caefe9ac5a405696817f
[ "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
gozfree/gear-lib
9f4db1bce799ded1cf1f3411cb51bdfbcbe7c7bc
bffbfd25af4ff7b04ebfafdab391b55270b0273e
refs/heads/master
2023-08-14T16:01:29.449910
2023-07-24T16:08:47
2023-07-24T16:09:41
40,359,871
1,771
488
MIT
2023-05-27T11:08:46
2015-08-07T12:41:05
C
UTF-8
C
false
false
7,927
c
getcwd.c
/*****************************************************************************\ * * * Filename getcwd.c * * * * Description: WIN32 port of standard C library's getcwd() * * * * Notes: * * * * History: * * 2014-02-28 JFL Created this module. * * 2014-07-02 JFL Added support for pathnames >= 260 characters. * * 2017-10-04 JFL Fixed support for pathnames >= 260 characters. * * 2018-04-25 JFL Added routine getcwdW(). * * Use the locally managed cur. dir. for paths > 260 bytes. * * * * ?Copyright 2016 Hewlett Packard Enterprise Development LP * * Licensed under the Apache 2.0 license - www.apache.org/licenses/LICENSE-2.0 * \*****************************************************************************/ #define _UTF8_LIB_SOURCE /* Generate the UTF-8 version of routines */ /* Microsoft C libraries include files */ #include <errno.h> #include <stdio.h> #include <string.h> /* MsvcLibX library extensions */ #include <unistd.h> #include "debugm.h" #if defined(_MSDOS) /* DOS own getcwd() is OK. */ #endif /* defined(_MSDOS) */ #ifdef _WIN32 #include <windows.h> /*---------------------------------------------------------------------------*\ * * | Function: getcwdW / getcwdM / getcwdA / getcwdU | | | | Description: Get the current directory, in UTF-16 / MBCS / ANSI / UTF-8| | | | Parameters: char *buf Buffer for the output | | size_t bufSize Buffer size | | | | Returns: The converted string size. -1=error, and errno set. | | | | Notes: The getcwd macro references either getcwdA or getcwdU. | | | | Contrary to most other WIN32 APIs, SetCurrentDirectoryW() | | does NOT allow extending the path length beyond 260 bytes | | by prepending a \\?\ prefix. | | https://stackoverflow.com/a/44519069/2215591 | | | | In Windows 10 version 1607 and later, this can be fixed | | by using a manifest defining longPathAware=true, AND | | by setting the registry value LongPathsEnabled to 1 in | | HKLM\SYSTEM\CurrentControlSet\Control\FileSystem. | | Using both lifts the 260-bytes WIN32 APIs limitation. | | | | If support for long path lengths in older versions of | | Windows is desired (XP to 8), then avoid using chdir() or | | SetCurrentDirectoryW(). | | | | As a weak workaround, for paths longer than 260 bytes, | | the chdir routine locally manages the current directory. | | No attempt is made to manage multiple drive-specific | | current directories, as the goal is Unix-compatibility, | | not Windows compatibility. | | | | History: | | 2014-02-28 JFL Created this routine | | 2014-07-02 JFL Added support for pathnames >= 260 characters. | | 2017-10-03 JFL Removed the dependency on PATH_MAX and fixed size buffers.| | Added routine getcwdM, called by getcwdA and getcwdU. | | 2017-10-04 JFL Remove the long pathname prefix, if any. | | 2018-04-25 JFL Added routine getcwdW(), and use it in getcwdM(). | | Use the locally managed cur. dir. for paths > 260 bytes. | | Bugfix: Must test for \\?\UNC\ before testing for \\?\. | * * \*---------------------------------------------------------------------------*/ extern WCHAR *pwszLongCurrentDir; /* Locally managed CD, defined in chdir.c */ WCHAR *getcwdW(WCHAR *pwBuf, size_t dwBufSize) { DWORD dwSize; WCHAR *pwDir; int iAlloc = FALSE; /* TRUE if pwBuf allocated here */ int iReAlloc = FALSE; /* TRUE if pwBuf should be reallocated in the end */ DEBUG_CODE( WCHAR *pwszWhere = L"Windows"; ) DEBUG_ENTER(("getcwd(0x%p, %Iu);\n", pwBuf, dwBufSize)); if (!pwBuf) { iAlloc = TRUE; if (!dwBufSize) { iReAlloc = TRUE; dwBufSize = WIDE_PATH_MAX; } pwBuf = malloc(dwBufSize * sizeof(WCHAR)); if (!pwBuf) return NULL; } if (pwszLongCurrentDir) { /* If we manage the CD locally */ dwSize = lstrlenW(pwszLongCurrentDir); /* Then copy that CD */ if (dwSize < dwBufSize) { lstrcpyW(pwBuf, pwszLongCurrentDir); } else { dwSize += 1; /* Buffer size needed */ } DEBUG_CODE( pwszWhere = L"MsvcLibX"; ) } else { /* Else ask Windows' */ dwSize = GetCurrentDirectoryW((DWORD)dwBufSize, pwBuf); } if (dwSize > dwBufSize) { /* The buffer is too small. dwSize = the size needed */ DEBUG_LEAVE(("return NULL; // Error: The buffer is too small. %d bytes needed.\n", dwSize)); getcwdW_failed: errno = Win32ErrorToErrno(); if (iAlloc) free(pwBuf); return NULL; } if (!dwSize) { DEBUG_LEAVE(("return NULL; // Error: GetCurrentDirectoryW() Failed\n")); goto getcwdW_failed; } /* Remove the long pathname prefix, if any */ pwDir = pwBuf; if (!strncmpW(pwBuf, L"\\\\?\\UNC\\", 8)) { pwDir += 6; /* Remove the '\\?\UNC\' prefix, except for the final two characters */ dwSize -= 6; *pwDir = L'\\'; /* Change the 'C' to '\', so that the output begins by '\\server\share' */ } else if (!strncmpW(pwBuf, L"\\\\?\\", 4)) { pwDir += 4; dwSize -= 4; } if (pwDir > pwBuf) memmove(pwBuf, pwDir, (dwSize+1) * sizeof(WCHAR)); /* Cleanup and return */ if (iReAlloc) { WCHAR *pwBuf2 = realloc(pwBuf, (dwSize + 1) * sizeof(WCHAR)); if (pwBuf2) pwBuf = pwBuf2; } DEBUG_WLEAVE((L"return \"%s\"; // [%s]\n", pwBuf, pwszWhere)); return pwBuf; } char *getcwdM(char *buf, size_t bufSize, UINT cp) { int n; WCHAR *pwDir; if (!buf) { errno = EINVAL; return NULL; } pwDir = getcwdW(NULL, 0); if (!pwDir) return NULL; /* Copy the pathname to the output buffer */ n = WideCharToMultiByte(cp, /* CodePage, (CP_ACP, CP_OEMCP, CP_UTF8, ...) */ 0, /* dwFlags, */ pwDir, /* lpWideCharStr, */ -1, /* cchWideChar, -1=NUL-terminated string */ buf, /* lpMultiByteStr, */ (int)bufSize, /* cbMultiByte, */ NULL, /* lpDefaultChar, */ NULL /* lpUsedDefaultChar */ ); free(pwDir); if (!n) { errno = Win32ErrorToErrno(); DEBUG_PRINTF(("getcwd(0x%p, %d); // Error: WideCharToMultiByte() Failed\n", buf, bufSize)); return NULL; } DEBUG_PRINTF(("getcwd(0x%p, %d); // \"%s\"\n", buf, bufSize, buf)); return buf; } char *getcwdA(char *buf, size_t bufSize) { return getcwdM(buf, bufSize, CP_ACP); } char *getcwdU(char *buf, size_t bufSize) { return getcwdM(buf, bufSize, CP_UTF8); } char *_getdcwdM(int iDrive, char *buf, int iBuflen, UINT cp) { char *pBuf; int iDrive0 = _getdrive(); if (iDrive && (iDrive != iDrive0)) _chdrive(iDrive); pBuf = getcwdM(buf, iBuflen, cp); if (iDrive && (iDrive != iDrive0)) _chdrive(iDrive0); DEBUG_CODE( if (pBuf) { DEBUG_PRINTF(("_getdcwd(%d, 0x%p, %d); // \"%s\"\n", iDrive, buf, iBuflen, pBuf)); } else { DEBUG_PRINTF(("_getdcwd(%d, 0x%p, %d); // Failed\n", iDrive, buf, iBuflen)); } ) return pBuf; } char *_getdcwdA(int iDrive, char *buf, int iBuflen) { return _getdcwdM(iDrive, buf, iBuflen, CP_ACP); } char *_getdcwdU(int iDrive, char *buf, int iBuflen) { return _getdcwdM(iDrive, buf, iBuflen, CP_UTF8); } #endif /* _WIN32 */
ea209c68be37201446d2022cc33d1eac6f4298af
79e0f8e5d93c3c9b80c680721609b71177e1d18b
/ngx_rtmp_handshake.c
409d9a0dd656418c755928384871a9c6dc68cff4
[ "BSD-2-Clause" ]
permissive
sergey-dryabzhinsky/nginx-rtmp-module
e4a0cee65cfaed78772fdd52bad889b2aff146d0
f9217ba07545583a46821175c2f8c08db03e5e83
refs/heads/dev
2022-12-23T04:55:44.369985
2022-05-15T11:54:40
2022-05-15T11:54:40
38,456,945
1,059
310
BSD-2-Clause
2022-12-09T10:31:02
2015-07-02T21:06:29
C
UTF-8
C
false
false
16,976
c
ngx_rtmp_handshake.c
/* * Copyright (C) Roman Arutyunyan */ #include <ngx_config.h> #include <ngx_core.h> #include "ngx_rtmp.h" #include <openssl/hmac.h> #include <openssl/sha.h> static void ngx_rtmp_handshake_send(ngx_event_t *wev); static void ngx_rtmp_handshake_recv(ngx_event_t *rev); static void ngx_rtmp_handshake_done(ngx_rtmp_session_t *s); /* RTMP handshake : * * =peer1= =peer2= * challenge ----> (.....[digest1]......) ----> 1537 bytes * response <---- (...........[digest2]) <---- 1536 bytes * * * - both packets contain random bytes except for digests * - digest1 position is calculated on random packet bytes * - digest2 is always at the end of the packet * * digest1: HMAC_SHA256(packet, peer1_partial_key) * digest2: HMAC_SHA256(packet, HMAC_SHA256(digest1, peer2_full_key)) */ /* Handshake keys */ static u_char ngx_rtmp_server_key[] = { 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ', 'F', 'l', 'a', 's', 'h', ' ', 'M', 'e', 'd', 'i', 'a', ' ', 'S', 'e', 'r', 'v', 'e', 'r', ' ', '0', '0', '1', 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02, 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8, 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE }; static u_char ngx_rtmp_client_key[] = { 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ', 'F', 'l', 'a', 's', 'h', ' ', 'P', 'l', 'a', 'y', 'e', 'r', ' ', '0', '0', '1', 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02, 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8, 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE }; static const u_char ngx_rtmp_server_version[4] = { 0x0D, 0x0E, 0x0A, 0x0D }; static const u_char ngx_rtmp_client_version[4] = { 0x0C, 0x00, 0x0D, 0x0E }; #define NGX_RTMP_HANDSHAKE_KEYLEN SHA256_DIGEST_LENGTH #define NGX_RTMP_HANDSHAKE_BUFSIZE 1537 #define NGX_RTMP_HANDSHAKE_SERVER_RECV_CHALLENGE 1 #define NGX_RTMP_HANDSHAKE_SERVER_SEND_CHALLENGE 2 #define NGX_RTMP_HANDSHAKE_SERVER_SEND_RESPONSE 3 #define NGX_RTMP_HANDSHAKE_SERVER_RECV_RESPONSE 4 #define NGX_RTMP_HANDSHAKE_SERVER_DONE 5 #define NGX_RTMP_HANDSHAKE_CLIENT_SEND_CHALLENGE 6 #define NGX_RTMP_HANDSHAKE_CLIENT_RECV_CHALLENGE 7 #define NGX_RTMP_HANDSHAKE_CLIENT_RECV_RESPONSE 8 #define NGX_RTMP_HANDSHAKE_CLIENT_SEND_RESPONSE 9 #define NGX_RTMP_HANDSHAKE_CLIENT_DONE 10 static ngx_str_t ngx_rtmp_server_full_key = { sizeof(ngx_rtmp_server_key), ngx_rtmp_server_key }; static ngx_str_t ngx_rtmp_server_partial_key = { 36, ngx_rtmp_server_key }; static ngx_str_t ngx_rtmp_client_full_key = { sizeof(ngx_rtmp_client_key), ngx_rtmp_client_key }; static ngx_str_t ngx_rtmp_client_partial_key = { 30, ngx_rtmp_client_key }; static ngx_int_t ngx_rtmp_make_digest(ngx_str_t *key, ngx_buf_t *src, u_char *skip, u_char *dst, ngx_log_t *log) { static HMAC_CTX *hmac; unsigned int len; if (hmac == NULL) { #if OPENSSL_VERSION_NUMBER < 0x10100000L static HMAC_CTX shmac; hmac = &shmac; HMAC_CTX_init(hmac); #else hmac = HMAC_CTX_new(); if (hmac == NULL) { return NGX_ERROR; } #endif } HMAC_Init_ex(hmac, key->data, key->len, EVP_sha256(), NULL); if (skip && src->pos <= skip && skip <= src->last) { if (skip != src->pos) { HMAC_Update(hmac, src->pos, skip - src->pos); } if (src->last != skip + NGX_RTMP_HANDSHAKE_KEYLEN) { HMAC_Update(hmac, skip + NGX_RTMP_HANDSHAKE_KEYLEN, src->last - skip - NGX_RTMP_HANDSHAKE_KEYLEN); } } else { HMAC_Update(hmac, src->pos, src->last - src->pos); } HMAC_Final(hmac, dst, &len); return NGX_OK; } static ngx_int_t ngx_rtmp_find_digest(ngx_buf_t *b, ngx_str_t *key, size_t base, ngx_log_t *log) { size_t n, offs; u_char digest[NGX_RTMP_HANDSHAKE_KEYLEN]; u_char *p; offs = 0; for (n = 0; n < 4; ++n) { offs += b->pos[base + n]; } offs = (offs % 728) + base + 4; p = b->pos + offs; if (ngx_rtmp_make_digest(key, b, p, digest, log) != NGX_OK) { return NGX_ERROR; } if (ngx_memcmp(digest, p, NGX_RTMP_HANDSHAKE_KEYLEN) == 0) { return offs; } return NGX_ERROR; } static ngx_int_t ngx_rtmp_write_digest(ngx_buf_t *b, ngx_str_t *key, size_t base, ngx_log_t *log) { size_t n, offs; u_char *p; offs = 0; for (n = 8; n < 12; ++n) { offs += b->pos[base + n]; } offs = (offs % 728) + base + 12; p = b->pos + offs; if (ngx_rtmp_make_digest(key, b, p, p, log) != NGX_OK) { return NGX_ERROR; } return NGX_OK; } static void ngx_rtmp_fill_random_buffer(ngx_buf_t *b) { for (; b->last != b->end; ++b->last) { *b->last = (u_char) rand(); } } static ngx_buf_t * ngx_rtmp_alloc_handshake_buffer(ngx_rtmp_session_t *s) { ngx_rtmp_core_srv_conf_t *cscf; ngx_chain_t *cl; ngx_buf_t *b; ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->connection->log, 0, "handshake: allocating buffer"); cscf = ngx_rtmp_get_module_srv_conf(s, ngx_rtmp_core_module); if (cscf->free_hs) { cl = cscf->free_hs; b = cl->buf; cscf->free_hs = cl->next; ngx_free_chain(cscf->pool, cl); } else { b = ngx_pcalloc(cscf->pool, sizeof(ngx_buf_t)); if (b == NULL) { return NULL; } b->memory = 1; b->start = ngx_pcalloc(cscf->pool, NGX_RTMP_HANDSHAKE_BUFSIZE); if (b->start == NULL) { return NULL; } b->end = b->start + NGX_RTMP_HANDSHAKE_BUFSIZE; } b->pos = b->last = b->start; return b; } void ngx_rtmp_free_handshake_buffers(ngx_rtmp_session_t *s) { ngx_rtmp_core_srv_conf_t *cscf; ngx_chain_t *cl; if (s->hs_buf == NULL) { return; } cscf = ngx_rtmp_get_module_srv_conf(s, ngx_rtmp_core_module); cl = ngx_alloc_chain_link(cscf->pool); if (cl == NULL) { return; } cl->buf = s->hs_buf; cl->next = cscf->free_hs; cscf->free_hs = cl; s->hs_buf = NULL; } static ngx_int_t ngx_rtmp_handshake_create_challenge(ngx_rtmp_session_t *s, const u_char version[4], ngx_str_t *key) { ngx_buf_t *b; b = s->hs_buf; b->last = b->pos = b->start; *b->last++ = '\x03'; b->last = ngx_rtmp_rcpymem(b->last, &s->epoch, 4); b->last = ngx_cpymem(b->last, version, 4); ngx_rtmp_fill_random_buffer(b); ++b->pos; if (ngx_rtmp_write_digest(b, key, 0, s->connection->log) != NGX_OK) { return NGX_ERROR; } --b->pos; return NGX_OK; } static ngx_int_t ngx_rtmp_handshake_parse_challenge(ngx_rtmp_session_t *s, ngx_str_t *peer_key, ngx_str_t *key) { ngx_buf_t *b; u_char *p; ngx_int_t offs; b = s->hs_buf; if (*b->pos != '\x03') { ngx_log_error(NGX_LOG_INFO, s->connection->log, 0, "handshake: unexpected RTMP version: %i", (ngx_int_t)*b->pos); return NGX_ERROR; } ++b->pos; s->peer_epoch = 0; ngx_rtmp_rmemcpy(&s->peer_epoch, b->pos, 4); p = b->pos + 4; ngx_log_debug5(NGX_LOG_DEBUG_RTMP, s->connection->log, 0, "handshake: peer version=%i.%i.%i.%i epoch=%uD", (ngx_int_t)p[3], (ngx_int_t)p[2], (ngx_int_t)p[1], (ngx_int_t)p[0], (uint32_t)s->peer_epoch); if (*(uint32_t *)p == 0) { s->hs_old = 1; return NGX_OK; } offs = ngx_rtmp_find_digest(b, peer_key, 772, s->connection->log); if (offs == NGX_ERROR) { offs = ngx_rtmp_find_digest(b, peer_key, 8, s->connection->log); } if (offs == NGX_ERROR) { ngx_log_error(NGX_LOG_INFO, s->connection->log, 0, "handshake: digest not found"); s->hs_old = 1; return NGX_OK; } ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->connection->log, 0, "handshake: digest found at pos=%i", offs); b->pos += offs; b->last = b->pos + NGX_RTMP_HANDSHAKE_KEYLEN; s->hs_digest = ngx_palloc(s->connection->pool, NGX_RTMP_HANDSHAKE_KEYLEN); if (ngx_rtmp_make_digest(key, b, NULL, s->hs_digest, s->connection->log) != NGX_OK) { return NGX_ERROR; } return NGX_OK; } static ngx_int_t ngx_rtmp_handshake_create_response(ngx_rtmp_session_t *s) { ngx_buf_t *b; u_char *p; ngx_str_t key; b = s->hs_buf; b->pos = b->last = b->start + 1; ngx_rtmp_fill_random_buffer(b); if (s->hs_digest) { p = b->last - NGX_RTMP_HANDSHAKE_KEYLEN; key.data = s->hs_digest; key.len = NGX_RTMP_HANDSHAKE_KEYLEN; if (ngx_rtmp_make_digest(&key, b, p, p, s->connection->log) != NGX_OK) { return NGX_ERROR; } } return NGX_OK; } static void ngx_rtmp_handshake_done(ngx_rtmp_session_t *s) { ngx_rtmp_free_handshake_buffers(s); ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->connection->log, 0, "handshake: done"); if (ngx_rtmp_fire_event(s, NGX_RTMP_HANDSHAKE_DONE, NULL, NULL) != NGX_OK) { ngx_rtmp_finalize_session(s); return; } ngx_rtmp_cycle(s); } static void ngx_rtmp_handshake_recv(ngx_event_t *rev) { ssize_t n; ngx_connection_t *c; ngx_rtmp_session_t *s; ngx_buf_t *b; c = rev->data; s = c->data; if (c->destroyed) { return; } if (rev->timedout) { ngx_log_error(NGX_LOG_INFO, c->log, NGX_ETIMEDOUT, "handshake: recv: client timed out"); c->timedout = 1; ngx_rtmp_finalize_session(s); return; } if (rev->timer_set) { ngx_del_timer(rev); } b = s->hs_buf; while (b->last != b->end) { n = c->recv(c, b->last, b->end - b->last); if (n == NGX_ERROR || n == 0) { ngx_rtmp_finalize_session(s); return; } if (n == NGX_AGAIN) { ngx_add_timer(rev, s->timeout); if (ngx_handle_read_event(c->read, 0) != NGX_OK) { ngx_rtmp_finalize_session(s); } return; } b->last += n; } if (rev->active) { ngx_del_event(rev, NGX_READ_EVENT, 0); } ++s->hs_stage; ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->connection->log, 0, "handshake: stage %ui", s->hs_stage); switch (s->hs_stage) { case NGX_RTMP_HANDSHAKE_SERVER_SEND_CHALLENGE: if (ngx_rtmp_handshake_parse_challenge(s, &ngx_rtmp_client_partial_key, &ngx_rtmp_server_full_key) != NGX_OK) { ngx_log_error(NGX_LOG_INFO, c->log, 0, "handshake: error parsing challenge"); ngx_rtmp_finalize_session(s); return; } if (s->hs_old) { ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->connection->log, 0, "handshake: old-style challenge"); s->hs_buf->pos = s->hs_buf->start; s->hs_buf->last = s->hs_buf->end; } else if (ngx_rtmp_handshake_create_challenge(s, ngx_rtmp_server_version, &ngx_rtmp_server_partial_key) != NGX_OK) { ngx_log_error(NGX_LOG_INFO, c->log, 0, "handshake: error creating challenge"); ngx_rtmp_finalize_session(s); return; } ngx_rtmp_handshake_send(c->write); break; case NGX_RTMP_HANDSHAKE_SERVER_DONE: ngx_rtmp_handshake_done(s); break; case NGX_RTMP_HANDSHAKE_CLIENT_RECV_RESPONSE: if (ngx_rtmp_handshake_parse_challenge(s, &ngx_rtmp_server_partial_key, &ngx_rtmp_client_full_key) != NGX_OK) { ngx_log_error(NGX_LOG_INFO, c->log, 0, "handshake: error parsing challenge"); ngx_rtmp_finalize_session(s); return; } s->hs_buf->pos = s->hs_buf->last = s->hs_buf->start + 1; ngx_rtmp_handshake_recv(c->read); break; case NGX_RTMP_HANDSHAKE_CLIENT_SEND_RESPONSE: if (ngx_rtmp_handshake_create_response(s) != NGX_OK) { ngx_log_error(NGX_LOG_INFO, c->log, 0, "handshake: response error"); ngx_rtmp_finalize_session(s); return; } ngx_rtmp_handshake_send(c->write); break; } } static void ngx_rtmp_handshake_send(ngx_event_t *wev) { ngx_int_t n; ngx_connection_t *c; ngx_rtmp_session_t *s; ngx_buf_t *b; c = wev->data; s = c->data; if (c->destroyed) { return; } if (wev->timedout) { ngx_log_error(NGX_LOG_INFO, c->log, NGX_ETIMEDOUT, "handshake: send: client timed out"); c->timedout = 1; ngx_rtmp_finalize_session(s); return; } if (wev->timer_set) { ngx_del_timer(wev); } b = s->hs_buf; while(b->pos != b->last) { n = c->send(c, b->pos, b->last - b->pos); if (n == NGX_ERROR) { ngx_rtmp_finalize_session(s); return; } if (n == NGX_AGAIN || n == 0) { ngx_add_timer(c->write, s->timeout); if (ngx_handle_write_event(c->write, 0) != NGX_OK) { ngx_rtmp_finalize_session(s); } return; } b->pos += n; } if (wev->active) { ngx_del_event(wev, NGX_WRITE_EVENT, 0); } ++s->hs_stage; ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->connection->log, 0, "handshake: stage %ui", s->hs_stage); switch (s->hs_stage) { case NGX_RTMP_HANDSHAKE_SERVER_SEND_RESPONSE: if (s->hs_old) { ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->connection->log, 0, "handshake: old-style response"); s->hs_buf->pos = s->hs_buf->start + 1; s->hs_buf->last = s->hs_buf->end; } else if (ngx_rtmp_handshake_create_response(s) != NGX_OK) { ngx_log_error(NGX_LOG_INFO, c->log, 0, "handshake: response error"); ngx_rtmp_finalize_session(s); return; } ngx_rtmp_handshake_send(wev); break; case NGX_RTMP_HANDSHAKE_SERVER_RECV_RESPONSE: s->hs_buf->pos = s->hs_buf->last = s->hs_buf->start + 1; ngx_rtmp_handshake_recv(c->read); break; case NGX_RTMP_HANDSHAKE_CLIENT_RECV_CHALLENGE: s->hs_buf->pos = s->hs_buf->last = s->hs_buf->start; ngx_rtmp_handshake_recv(c->read); break; case NGX_RTMP_HANDSHAKE_CLIENT_DONE: ngx_rtmp_handshake_done(s); break; } } void ngx_rtmp_handshake(ngx_rtmp_session_t *s) { ngx_connection_t *c; c = s->connection; c->read->handler = ngx_rtmp_handshake_recv; c->write->handler = ngx_rtmp_handshake_send; ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->connection->log, 0, "handshake: start server handshake"); s->hs_buf = ngx_rtmp_alloc_handshake_buffer(s); s->hs_stage = NGX_RTMP_HANDSHAKE_SERVER_RECV_CHALLENGE; ngx_rtmp_handshake_recv(c->read); } void ngx_rtmp_client_handshake(ngx_rtmp_session_t *s, unsigned async) { ngx_connection_t *c; c = s->connection; c->read->handler = ngx_rtmp_handshake_recv; c->write->handler = ngx_rtmp_handshake_send; ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->connection->log, 0, "handshake: start client handshake"); s->hs_buf = ngx_rtmp_alloc_handshake_buffer(s); s->hs_stage = NGX_RTMP_HANDSHAKE_CLIENT_SEND_CHALLENGE; if (ngx_rtmp_handshake_create_challenge(s, ngx_rtmp_client_version, &ngx_rtmp_client_partial_key) != NGX_OK) { ngx_rtmp_finalize_session(s); return; } if (async) { ngx_add_timer(c->write, s->timeout); if (ngx_handle_write_event(c->write, 0) != NGX_OK) { ngx_rtmp_finalize_session(s); } return; } ngx_rtmp_handshake_send(c->write); }
23dd8b18167888b1ca52157ae139b72da2195124
eb4d06c58aa902fe06055327b90b99a6dacb2ebc
/OHMySQL/lib/MySQL.xcframework/ios-arm64/MySQL.framework/Headers/pfs_statement_provider.h
a547028598f1378ed3cb6d1bd18664181a3466f9
[ "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-mysql-linking-exception-2018", "Universal-FOSS-exception-1.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
oleghnidets/OHMySQL
5c3741afdd866910b473cc267749e017af1900ed
c6afc83187d9527933de016438024f8472aff768
refs/heads/master
2023-07-24T12:03:42.077178
2023-07-07T20:46:40
2023-07-07T20:46:40
41,176,216
250
53
MIT
2023-02-21T20:34:01
2015-08-21T20:31:41
C
UTF-8
C
false
false
6,038
h
pfs_statement_provider.h
/* Copyright (c) 2012, 2022, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef PFS_STATEMENT_PROVIDER_H #define PFS_STATEMENT_PROVIDER_H /** @file include/pfs_statement_provider.h Performance schema instrumentation (declarations). */ #include <sys/types.h> /* HAVE_PSI_*_INTERFACE */ #include "my_psi_config.h" // IWYU pragma: keep #ifdef HAVE_PSI_STATEMENT_INTERFACE #if defined(MYSQL_SERVER) || defined(PFS_DIRECT_CALL) #ifndef MYSQL_DYNAMIC_PLUGIN #ifndef WITH_LOCK_ORDER #include "my_inttypes.h" #include "my_macros.h" #include "mysql/psi/psi_statement.h" #include "sql/sql_digest.h" struct PSI_digest_locker; struct sql_digest_storage; #define PSI_STATEMENT_CALL(M) pfs_##M##_vc #define PSI_DIGEST_CALL(M) pfs_##M##_vc #define PSI_PS_CALL(M) pfs_##M##_vc void pfs_register_statement_vc(const char *category, PSI_statement_info *info, int count); PSI_statement_locker *pfs_get_thread_statement_locker_vc( PSI_statement_locker_state *state, PSI_statement_key key, const void *charset, PSI_sp_share *sp_share); PSI_statement_locker *pfs_refine_statement_vc(PSI_statement_locker *locker, PSI_statement_key key); void pfs_start_statement_vc(PSI_statement_locker *locker, const char *db, uint db_len, const char *src_file, uint src_line); void pfs_set_statement_text_vc(PSI_statement_locker *locker, const char *text, uint text_len); void pfs_set_statement_query_id_vc(PSI_statement_locker *locker, ulonglong count); void pfs_set_statement_lock_time_vc(PSI_statement_locker *locker, ulonglong count); void pfs_set_statement_rows_sent_vc(PSI_statement_locker *locker, ulonglong count); void pfs_set_statement_rows_examined_vc(PSI_statement_locker *locker, ulonglong count); void pfs_inc_statement_created_tmp_disk_tables_vc(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_created_tmp_tables_vc(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_select_full_join_vc(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_select_full_range_join_vc(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_select_range_vc(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_select_range_check_vc(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_select_scan_vc(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_sort_merge_passes_vc(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_sort_range_vc(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_sort_rows_vc(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_sort_scan_vc(PSI_statement_locker *locker, ulong count); void pfs_set_statement_no_index_used_vc(PSI_statement_locker *locker); void pfs_set_statement_no_good_index_used_vc(PSI_statement_locker *locker); void pfs_set_statement_secondary_engine_vc(PSI_statement_locker *locker, bool secondary); void pfs_end_statement_vc(PSI_statement_locker *locker, void *stmt_da); PSI_prepared_stmt *pfs_create_prepared_stmt_vc(void *identity, uint stmt_id, PSI_statement_locker *locker, const char *stmt_name, size_t stmt_name_length, const char *sql_text, size_t sql_text_length); void pfs_destroy_prepared_stmt_vc(PSI_prepared_stmt *prepared_stmt); void pfs_reprepare_prepared_stmt_vc(PSI_prepared_stmt *prepared_stmt); void pfs_execute_prepared_stmt_vc(PSI_statement_locker *locker, PSI_prepared_stmt *ps); void pfs_set_prepared_stmt_text_vc(PSI_prepared_stmt *prepared_stmt, const char *text, uint text_len); void pfs_set_prepared_stmt_secondary_engine_vc(PSI_prepared_stmt *prepared_stmt, bool secondary); PSI_digest_locker *pfs_digest_start_vc(PSI_statement_locker *locker); void pfs_digest_end_vc(PSI_digest_locker *locker, const sql_digest_storage *digest); #endif /* WITH_LOCK_ORDER */ #endif /* MYSQL_DYNAMIC_PLUGIN */ #endif /* MYSQL_SERVER || PFS_DIRECT_CALL */ #endif /* HAVE_PSI_STATEMENT_INTERFACE */ #endif
ccc9452400760d8611f1b70840a5cbfdd44b34e6
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/u-boot_new/include/ata.h
9d6f59c97bfaae7ea8482eb03468533465901d9c
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "GPL-2.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
9,916
h
ata.h
/* * (C) Copyright 2000 * Wolfgang Denk, DENX Software Engineering, wd@denx.de. * * SPDX-License-Identifier: GPL-2.0+ */ /* * Most of the following information was derived from the document * "Information Technology - AT Attachment-3 Interface (ATA-3)" * which can be found at: * http://www.dt.wdc.com/ata/ata-3/ata3r5v.zip * ftp://poctok.iae.nsk.su/pub/asm/Documents/IDE/ATA3R5V.ZIP * ftp://ftp.fee.vutbr.cz/pub/doc/io/ata/ata-3/ata3r5v.zip */ #ifndef _ATA_H #define _ATA_H #include <libata.h> /* Register addressing depends on the hardware design; for instance, * 8-bit (register) and 16-bit (data) accesses might use different * address spaces. This is implemented by the following definitions. */ #ifndef CONFIG_SYS_ATA_STRIDE #define CONFIG_SYS_ATA_STRIDE 1 #endif #define ATA_IO_DATA(x) (CONFIG_SYS_ATA_DATA_OFFSET+((x) * CONFIG_SYS_ATA_STRIDE)) #define ATA_IO_REG(x) (CONFIG_SYS_ATA_REG_OFFSET +((x) * CONFIG_SYS_ATA_STRIDE)) #define ATA_IO_ALT(x) (CONFIG_SYS_ATA_ALT_OFFSET +((x) * CONFIG_SYS_ATA_STRIDE)) /* * I/O Register Descriptions */ #define ATA_DATA_REG ATA_IO_DATA(0) #define ATA_ERROR_REG ATA_IO_REG(1) #define ATA_SECT_CNT ATA_IO_REG(2) #define ATA_SECT_NUM ATA_IO_REG(3) #define ATA_CYL_LOW ATA_IO_REG(4) #define ATA_CYL_HIGH ATA_IO_REG(5) #define ATA_DEV_HD ATA_IO_REG(6) #define ATA_COMMAND ATA_IO_REG(7) #define ATA_DATA_EVEN ATA_IO_REG(8) #define ATA_DATA_ODD ATA_IO_REG(9) #define ATA_STATUS ATA_COMMAND #define ATA_DEV_CTL ATA_IO_ALT(6) #define ATA_LBA_LOW ATA_SECT_NUM #define ATA_LBA_MID ATA_CYL_LOW #define ATA_LBA_HIGH ATA_CYL_HIGH #define ATA_LBA_SEL ATA_DEV_CTL /* * Status register bits */ #define ATA_STAT_BUSY 0x80 /* Device Busy */ #define ATA_STAT_READY 0x40 /* Device Ready */ #define ATA_STAT_FAULT 0x20 /* Device Fault */ #define ATA_STAT_SEEK 0x10 /* Device Seek Complete */ #define ATA_STAT_DRQ 0x08 /* Data Request (ready) */ #define ATA_STAT_CORR 0x04 /* Corrected Data Error */ #define ATA_STAT_INDEX 0x02 /* Vendor specific */ #define ATA_STAT_ERR 0x01 /* Error */ /* * Device / Head Register Bits */ #ifndef ATA_DEVICE #define ATA_DEVICE(x) ((x & 1)<<4) #endif /* ATA_DEVICE */ #define ATA_LBA 0xE0 /* * ATA Commands (only mandatory commands listed here) */ #define ATA_CMD_READ 0x20 /* Read Sectors (with retries) */ #define ATA_CMD_READN 0x21 /* Read Sectors ( no retries) */ #define ATA_CMD_WRITE 0x30 /* Write Sectores (with retries)*/ #define ATA_CMD_WRITEN 0x31 /* Write Sectors ( no retries)*/ #define ATA_CMD_VRFY 0x40 /* Read Verify (with retries) */ #define ATA_CMD_VRFYN 0x41 /* Read verify ( no retries) */ #define ATA_CMD_SEEK 0x70 /* Seek */ #define ATA_CMD_DIAG 0x90 /* Execute Device Diagnostic */ #define ATA_CMD_INIT 0x91 /* Initialize Device Parameters */ #define ATA_CMD_RD_MULT 0xC4 /* Read Multiple */ #define ATA_CMD_WR_MULT 0xC5 /* Write Multiple */ #define ATA_CMD_SETMULT 0xC6 /* Set Multiple Mode */ #define ATA_CMD_RD_DMA 0xC8 /* Read DMA (with retries) */ #define ATA_CMD_RD_DMAN 0xC9 /* Read DMS ( no retries) */ #define ATA_CMD_WR_DMA 0xCA /* Write DMA (with retries) */ #define ATA_CMD_WR_DMAN 0xCB /* Write DMA ( no retires) */ #define ATA_CMD_IDENT 0xEC /* Identify Device */ #define ATA_CMD_SETF 0xEF /* Set Features */ #define ATA_CMD_CHK_PWR 0xE5 /* Check Power Mode */ #define ATA_CMD_READ_EXT 0x24 /* Read Sectors (with retries) with 48bit addressing */ #define ATA_CMD_WRITE_EXT 0x34 /* Write Sectores (with retries) with 48bit addressing */ #define ATA_CMD_VRFY_EXT 0x42 /* Read Verify (with retries) with 48bit addressing */ #define ATA_CMD_FLUSH 0xE7 /* Flush drive cache */ #define ATA_CMD_FLUSH_EXT 0xEA /* Flush drive cache, with 48bit addressing */ /* * ATAPI Commands */ #define ATAPI_CMD_IDENT 0xA1 /* Identify AT Atachment Packed Interface Device */ #define ATAPI_CMD_PACKET 0xA0 /* Packed Command */ #define ATAPI_CMD_INQUIRY 0x12 #define ATAPI_CMD_REQ_SENSE 0x03 #define ATAPI_CMD_READ_CAP 0x25 #define ATAPI_CMD_START_STOP 0x1B #define ATAPI_CMD_READ_12 0xA8 #define ATA_GET_ERR() inb(ATA_STATUS) #define ATA_GET_STAT() inb(ATA_STATUS) #define ATA_OK_STAT(stat,good,bad) (((stat)&((good)|(bad)))==(good)) #define ATA_BAD_R_STAT (ATA_STAT_BUSY | ATA_STAT_ERR) #define ATA_BAD_W_STAT (ATA_BAD_R_STAT | ATA_STAT_FAULT) #define ATA_BAD_STAT (ATA_BAD_R_STAT | ATA_STAT_DRQ) #define ATA_DRIVE_READY (ATA_READY_STAT | ATA_STAT_SEEK) #define ATA_DATA_READY (ATA_STAT_DRQ) #define ATA_BLOCKSIZE 512 /* bytes */ #define ATA_BLOCKSHIFT 9 /* 2 ^ ATA_BLOCKSIZESHIFT = 512 */ #define ATA_SECTORWORDS (512 / sizeof(unsigned long)) #ifndef ATA_RESET_TIME #define ATA_RESET_TIME 60 /* spec allows up to 31 seconds */ #endif /* ------------------------------------------------------------------------- */ /* * structure returned by ATA_CMD_IDENT, as per ANSI ATA2 rev.2f spec */ typedef struct hd_driveid { unsigned short config; /* lots of obsolete bit flags */ unsigned short cyls; /* "physical" cyls */ unsigned short reserved2; /* reserved (word 2) */ unsigned short heads; /* "physical" heads */ unsigned short track_bytes; /* unformatted bytes per track */ unsigned short sector_bytes; /* unformatted bytes per sector */ unsigned short sectors; /* "physical" sectors per track */ unsigned short vendor0; /* vendor unique */ unsigned short vendor1; /* vendor unique */ unsigned short vendor2; /* vendor unique */ unsigned char serial_no[20]; /* 0 = not_specified */ unsigned short buf_type; unsigned short buf_size; /* 512 byte increments; 0 = not_specified */ unsigned short ecc_bytes; /* for r/w long cmds; 0 = not_specified */ unsigned char fw_rev[8]; /* 0 = not_specified */ unsigned char model[40]; /* 0 = not_specified */ unsigned char max_multsect; /* 0=not_implemented */ unsigned char vendor3; /* vendor unique */ unsigned short dword_io; /* 0=not_implemented; 1=implemented */ unsigned char vendor4; /* vendor unique */ unsigned char capability; /* bits 0:DMA 1:LBA 2:IORDYsw 3:IORDYsup*/ unsigned short reserved50; /* reserved (word 50) */ unsigned char vendor5; /* vendor unique */ unsigned char tPIO; /* 0=slow, 1=medium, 2=fast */ unsigned char vendor6; /* vendor unique */ unsigned char tDMA; /* 0=slow, 1=medium, 2=fast */ unsigned short field_valid; /* bits 0:cur_ok 1:eide_ok */ unsigned short cur_cyls; /* logical cylinders */ unsigned short cur_heads; /* logical heads */ unsigned short cur_sectors; /* logical sectors per track */ unsigned short cur_capacity0; /* logical total sectors on drive */ unsigned short cur_capacity1; /* (2 words, misaligned int) */ unsigned char multsect; /* current multiple sector count */ unsigned char multsect_valid; /* when (bit0==1) multsect is ok */ unsigned int lba_capacity; /* total number of sectors */ unsigned short dma_1word; /* single-word dma info */ unsigned short dma_mword; /* multiple-word dma info */ unsigned short eide_pio_modes; /* bits 0:mode3 1:mode4 */ unsigned short eide_dma_min; /* min mword dma cycle time (ns) */ unsigned short eide_dma_time; /* recommended mword dma cycle time (ns) */ unsigned short eide_pio; /* min cycle time (ns), no IORDY */ unsigned short eide_pio_iordy; /* min cycle time (ns), with IORDY */ unsigned short words69_70[2]; /* reserved words 69-70 */ unsigned short words71_74[4]; /* reserved words 71-74 */ unsigned short queue_depth; /* */ unsigned short words76_79[4]; /* reserved words 76-79 */ unsigned short major_rev_num; /* */ unsigned short minor_rev_num; /* */ unsigned short command_set_1; /* bits 0:Smart 1:Security 2:Removable 3:PM */ unsigned short command_set_2; /* bits 14:Smart Enabled 13:0 zero 10:lba48 support*/ unsigned short cfsse; /* command set-feature supported extensions */ unsigned short cfs_enable_1; /* command set-feature enabled */ unsigned short cfs_enable_2; /* command set-feature enabled */ unsigned short csf_default; /* command set-feature default */ unsigned short dma_ultra; /* */ unsigned short word89; /* reserved (word 89) */ unsigned short word90; /* reserved (word 90) */ unsigned short CurAPMvalues; /* current APM values */ unsigned short word92; /* reserved (word 92) */ unsigned short hw_config; /* hardware config */ unsigned short words94_99[6];/* reserved words 94-99 */ /*unsigned long long lba48_capacity; /--* 4 16bit values containing lba 48 total number of sectors */ unsigned short lba48_capacity[4]; /* 4 16bit values containing lba 48 total number of sectors */ unsigned short words104_125[22];/* reserved words 104-125 */ unsigned short last_lun; /* reserved (word 126) */ unsigned short word127; /* reserved (word 127) */ unsigned short dlf; /* device lock function * 15:9 reserved * 8 security level 1:max 0:high * 7:6 reserved * 5 enhanced erase * 4 expire * 3 frozen * 2 locked * 1 en/disabled * 0 capability */ unsigned short csfo; /* current set features options * 15:4 reserved * 3 auto reassign * 2 reverting * 1 read-look-ahead * 0 write cache */ unsigned short words130_155[26];/* reserved vendor words 130-155 */ unsigned short word156; unsigned short words157_159[3];/* reserved vendor words 157-159 */ unsigned short words160_162[3];/* reserved words 160-162 */ unsigned short cf_advanced_caps; unsigned short words164_255[92];/* reserved words 164-255 */ } hd_driveid_t; /* * PIO Mode Configuration * * See ATA-3 (AT Attachment-3 Interface) documentation, Figure 14 / Table 21 */ typedef struct { unsigned int t_setup; /* Setup Time in [ns] or clocks */ unsigned int t_length; /* Length Time in [ns] or clocks */ unsigned int t_hold; /* Hold Time in [ns] or clocks */ } pio_config_t; #define IDE_MAX_PIO_MODE 4 /* max suppurted PIO mode */ /* ------------------------------------------------------------------------- */ #endif /* _ATA_H */
4ee289bc8f9b54d393d981f94a83068b47515e68
3cd3872acbc8b1a79a70b89b2fd58a171e7adc82
/vp8/common/reconintra.h
029ac00a24bf1487c679e79f3f947543a34f0511
[]
permissive
webmproject/libvpx
58ab97861063cb521ec0d00ef9cb222ca97873b1
6fd360c684736e351160b131827dfbb207841164
refs/heads/main
2023-04-09T15:32:34.688724
2023-04-07T22:19:18
2023-04-07T22:19:18
22,927,608
889
376
BSD-3-Clause
2023-03-24T13:37:34
2014-08-13T19:03:21
C
UTF-8
C
false
false
1,174
h
reconintra.h
/* * Copyright (c) 2010 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE 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. */ #ifndef VPX_VP8_COMMON_RECONINTRA_H_ #define VPX_VP8_COMMON_RECONINTRA_H_ #include "vp8/common/blockd.h" #ifdef __cplusplus extern "C" { #endif void vp8_build_intra_predictors_mby_s(MACROBLOCKD *x, unsigned char *yabove_row, unsigned char *yleft, int left_stride, unsigned char *ypred_ptr, int y_stride); void vp8_build_intra_predictors_mbuv_s( MACROBLOCKD *x, unsigned char *uabove_row, unsigned char *vabove_row, unsigned char *uleft, unsigned char *vleft, int left_stride, unsigned char *upred_ptr, unsigned char *vpred_ptr, int pred_stride); void vp8_init_intra_predictors(void); #ifdef __cplusplus } // extern "C" #endif #endif // VPX_VP8_COMMON_RECONINTRA_H_
2a2f80c89c0f2af7b05f0a957d917e1cd157d373
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/ThirdParty/PhysX/APEX_1.4/shared/external/include/DirEntry.h
64fd54cb01af6341409ab216defd4ce8648ef6ff
[ "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
877
h
DirEntry.h
/* * Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. */ #ifndef DIR_ENTRY_INCLUDE_H #define DIR_ENTRY_INCLUDE_H #include "PxPreprocessor.h" #if PX_WINDOWS_FAMILY #include "windows/DirEntry.h" #elif PX_XBOXONE #include "xboxone/DirEntry.h" #elif (PX_LINUX_FAMILY || PX_APPLE_FAMILY || PX_ANDROID) #include "linux/DirEntry.h" #elif PX_PS4 #include "ps4/DirEntry.h" #elif PX_NX #include "nx/DirEntry.h" #else #error "Platform not supported!" #endif #endif // DIR_ENTRY_INCLUDE_H
f9d7fd1a284fcbbfa5ede7f12883e91035304162
f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab
/net/tnftp/files/src/cmds.c
97ffc6752773776c251ef7c65c4929f5e20c098f
[ "BSD-3-Clause", "BSD-4-Clause" ]
permissive
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
58,148
c
cmds.c
/* $NetBSD: cmds.c,v 1.11 2015/10/04 14:44:07 tnn Exp $ */ /* from NetBSD: cmds.c,v 1.135 2012/12/22 16:57:09 christos Exp */ /*- * Copyright (c) 1996-2009 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Luke Mewburn. * * This code is derived from software contributed to The NetBSD Foundation * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility, * NASA Ames Research Center. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1985, 1989, 1993, 1994 * The Regents of the University of California. 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 University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Copyright (C) 1997 and 1998 WIDE Project. * 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 project 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 PROJECT 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 PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "tnftp.h" #if 0 /* tnftp */ #include <sys/cdefs.h> #ifndef lint #if 0 static char sccsid[] = "@(#)cmds.c 8.6 (Berkeley) 10/9/94"; #else __RCSID(" NetBSD: cmds.c,v 1.135 2012/12/22 16:57:09 christos Exp "); #endif #endif /* not lint */ /* * FTP User Program -- Command Routines. */ #include <sys/types.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/wait.h> #include <arpa/ftp.h> #include <ctype.h> #include <err.h> #include <errno.h> #include <glob.h> #include <limits.h> #include <netdb.h> #include <paths.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #endif /* tnftp */ #include "ftp_var.h" #include "version.h" static struct types { const char *t_name; const char *t_mode; int t_type; const char *t_arg; } types[] = { { "ascii", "A", TYPE_A, 0 }, { "binary", "I", TYPE_I, 0 }, { "image", "I", TYPE_I, 0 }, { "ebcdic", "E", TYPE_E, 0 }, { "tenex", "L", TYPE_L, bytename }, { NULL, NULL, 0, NULL } }; static sigjmp_buf jabort; static int confirm(const char *, const char *); __dead static void mintr(int); static void mabort(const char *); static void set_type(const char *); static const char *doprocess(char *, size_t, const char *, int, int, int); static const char *domap(char *, size_t, const char *); static const char *docase(char *, size_t, const char *); static const char *dotrans(char *, size_t, const char *); /* * Confirm if "cmd" is to be performed upon "file". * If "file" is NULL, generate a "Continue with" prompt instead. */ static int confirm(const char *cmd, const char *file) { const char *errormsg; char cline[BUFSIZ]; const char *promptleft, *promptright; if (!interactive || confirmrest) return (1); if (file == NULL) { promptleft = "Continue with"; promptright = cmd; } else { promptleft = cmd; promptright = file; } while (1) { fprintf(ttyout, "%s %s [anpqy?]? ", promptleft, promptright); (void)fflush(ttyout); if (get_line(stdin, cline, sizeof(cline), &errormsg) < 0) { mflag = 0; fprintf(ttyout, "%s; %s aborted\n", errormsg, cmd); return (0); } switch (tolower((unsigned char)*cline)) { case 'a': confirmrest = 1; fprintf(ttyout, "Prompting off for duration of %s.\n", cmd); break; case 'p': interactive = 0; fputs("Interactive mode: off.\n", ttyout); break; case 'q': mflag = 0; fprintf(ttyout, "%s aborted.\n", cmd); /* FALLTHROUGH */ case 'n': return (0); case '?': fprintf(ttyout, " confirmation options:\n" "\ta answer `yes' for the duration of %s\n" "\tn answer `no' for this file\n" "\tp turn off `prompt' mode\n" "\tq stop the current %s\n" "\ty answer `yes' for this file\n" "\t? this help list\n", cmd, cmd); continue; /* back to while(1) */ } return (1); } /* NOTREACHED */ } /* * Set transfer type. */ void settype(int argc, char *argv[]) { struct types *p; if (argc == 0 || argc > 2) { const char *sep; UPRINTF("usage: %s [", argv[0]); sep = " "; for (p = types; p->t_name; p++) { fprintf(ttyout, "%s%s", sep, p->t_name); sep = " | "; } fputs(" ]\n", ttyout); code = -1; return; } if (argc < 2) { fprintf(ttyout, "Using %s mode to transfer files.\n", typename); code = 0; return; } set_type(argv[1]); } void set_type(const char *ttype) { struct types *p; int comret; for (p = types; p->t_name; p++) if (strcmp(ttype, p->t_name) == 0) break; if (p->t_name == 0) { fprintf(ttyout, "%s: unknown mode.\n", ttype); code = -1; return; } if ((p->t_arg != NULL) && (*(p->t_arg) != '\0')) comret = command("TYPE %s %s", p->t_mode, p->t_arg); else comret = command("TYPE %s", p->t_mode); if (comret == COMPLETE) { (void)strlcpy(typename, p->t_name, sizeof(typename)); curtype = type = p->t_type; } } /* * Internal form of settype; changes current type in use with server * without changing our notion of the type for data transfers. * Used to change to and from ascii for listings. */ void changetype(int newtype, int show) { struct types *p; int comret, oldverbose = verbose; if (newtype == 0) newtype = TYPE_I; if (newtype == curtype) return; if (ftp_debug == 0 && show == 0) verbose = 0; for (p = types; p->t_name; p++) if (newtype == p->t_type) break; if (p->t_name == 0) { errx(1, "changetype: unknown type %d", newtype); } if (newtype == TYPE_L && bytename[0] != '\0') comret = command("TYPE %s %s", p->t_mode, bytename); else comret = command("TYPE %s", p->t_mode); if (comret == COMPLETE) curtype = newtype; verbose = oldverbose; } /* * Set binary transfer type. */ /*VARARGS*/ void setbinary(int argc, char *argv[]) { if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } set_type("binary"); } /* * Set ascii transfer type. */ /*VARARGS*/ void setascii(int argc, char *argv[]) { if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } set_type("ascii"); } /* * Set tenex transfer type. */ /*VARARGS*/ void settenex(int argc, char *argv[]) { if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } set_type("tenex"); } /* * Set file transfer mode. */ /*ARGSUSED*/ void setftmode(int argc, char *argv[]) { if (argc != 2) { UPRINTF("usage: %s mode-name\n", argv[0]); code = -1; return; } fprintf(ttyout, "We only support %s mode, sorry.\n", modename); code = -1; } /* * Set file transfer format. */ /*ARGSUSED*/ void setform(int argc, char *argv[]) { if (argc != 2) { UPRINTF("usage: %s format\n", argv[0]); code = -1; return; } fprintf(ttyout, "We only support %s format, sorry.\n", formname); code = -1; } /* * Set file transfer structure. */ /*ARGSUSED*/ void setstruct(int argc, char *argv[]) { if (argc != 2) { UPRINTF("usage: %s struct-mode\n", argv[0]); code = -1; return; } fprintf(ttyout, "We only support %s structure, sorry.\n", structname); code = -1; } /* * Send a single file. */ void put(int argc, char *argv[]) { char buf[MAXPATHLEN]; const char *cmd; int loc = 0; char *locfile; const char *remfile; if (argc == 2) { argc++; argv[2] = argv[1]; loc++; } if (argc == 0 || (argc == 1 && !another(&argc, &argv, "local-file"))) goto usage; if ((argc < 3 && !another(&argc, &argv, "remote-file")) || argc > 3) { usage: UPRINTF("usage: %s local-file [remote-file]\n", argv[0]); code = -1; return; } if ((locfile = globulize(argv[1])) == NULL) { code = -1; return; } remfile = argv[2]; if (loc) /* If argv[2] is a copy of the old argv[1], update it */ remfile = locfile; cmd = (argv[0][0] == 'a') ? "APPE" : ((sunique) ? "STOU" : "STOR"); remfile = doprocess(buf, sizeof(buf), remfile, 0, loc && ntflag, loc && mapflag); sendrequest(cmd, locfile, remfile, locfile != argv[1] || remfile != argv[2]); free(locfile); } static const char * doprocess(char *dst, size_t dlen, const char *src, int casef, int transf, int mapf) { if (casef) src = docase(dst, dlen, src); if (transf) src = dotrans(dst, dlen, src); if (mapf) src = domap(dst, dlen, src); return src; } /* * Send multiple files. */ void mput(int argc, char *argv[]) { int i; sigfunc oldintr; int ointer; const char *tp; if (argc == 0 || (argc == 1 && !another(&argc, &argv, "local-files"))) { UPRINTF("usage: %s local-files\n", argv[0]); code = -1; return; } mflag = 1; oldintr = xsignal(SIGINT, mintr); if (sigsetjmp(jabort, 1)) mabort(argv[0]); if (proxy) { char *cp; while ((cp = remglob(argv, 0, NULL)) != NULL) { if (*cp == '\0' || !connected) { mflag = 0; continue; } if (mflag && confirm(argv[0], cp)) { char buf[MAXPATHLEN]; tp = doprocess(buf, sizeof(buf), cp, mcase, ntflag, mapflag); sendrequest((sunique) ? "STOU" : "STOR", cp, tp, cp != tp || !interactive); if (!mflag && fromatty) { ointer = interactive; interactive = 1; if (confirm(argv[0], NULL)) { mflag++; } interactive = ointer; } } } goto cleanupmput; } for (i = 1; i < argc && connected; i++) { char **cpp; glob_t gl; int flags; if (!doglob) { if (mflag && confirm(argv[0], argv[i])) { char buf[MAXPATHLEN]; tp = doprocess(buf, sizeof(buf), argv[i], 0, ntflag, mapflag); sendrequest((sunique) ? "STOU" : "STOR", argv[i], tp, tp != argv[i] || !interactive); if (!mflag && fromatty) { ointer = interactive; interactive = 1; if (confirm(argv[0], NULL)) { mflag++; } interactive = ointer; } } continue; } memset(&gl, 0, sizeof(gl)); flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE; if (glob(argv[i], flags, NULL, &gl) || gl.gl_pathc == 0) { warnx("Glob pattern `%s' not found", argv[i]); globfree(&gl); continue; } for (cpp = gl.gl_pathv; cpp && *cpp != NULL && connected; cpp++) { if (mflag && confirm(argv[0], *cpp)) { char buf[MAXPATHLEN]; tp = *cpp; tp = doprocess(buf, sizeof(buf), *cpp, 0, ntflag, mapflag); sendrequest((sunique) ? "STOU" : "STOR", *cpp, tp, *cpp != tp || !interactive); if (!mflag && fromatty) { ointer = interactive; interactive = 1; if (confirm(argv[0], NULL)) { mflag++; } interactive = ointer; } } } globfree(&gl); } cleanupmput: (void)xsignal(SIGINT, oldintr); mflag = 0; } void reget(int argc, char *argv[]) { (void)getit(argc, argv, 1, restart_point ? "r+" : "a"); } void get(int argc, char *argv[]) { (void)getit(argc, argv, 0, restart_point ? "r+" : "w"); } /* * Receive one file. * If restartit is 1, restart the xfer always. * If restartit is -1, restart the xfer only if the remote file is newer. */ int getit(int argc, char *argv[], int restartit, const char *gmode) { int loc, rval; char *remfile, *olocfile; const char *locfile; char buf[MAXPATHLEN]; loc = rval = 0; if (argc == 2) { argc++; argv[2] = argv[1]; loc++; } if (argc == 0 || (argc == 1 && !another(&argc, &argv, "remote-file"))) goto usage; if ((argc < 3 && !another(&argc, &argv, "local-file")) || argc > 3) { usage: UPRINTF("usage: %s remote-file [local-file]\n", argv[0]); code = -1; return (0); } remfile = argv[1]; if ((olocfile = globulize(argv[2])) == NULL) { code = -1; return (0); } locfile = doprocess(buf, sizeof(buf), olocfile, loc && mcase, loc && ntflag, loc && mapflag); if (restartit) { struct stat stbuf; int ret; if (! features[FEAT_REST_STREAM]) { fprintf(ttyout, "Restart is not supported by the remote server.\n"); return (0); } ret = stat(locfile, &stbuf); if (restartit == 1) { if (ret < 0) { if (errno != ENOENT) { warn("Can't stat `%s'", locfile); goto freegetit; } restart_point = 0; } else restart_point = stbuf.st_size; } else { if (ret == 0) { time_t mtime; mtime = remotemodtime(argv[1], 0); if (mtime == -1) goto freegetit; if (stbuf.st_mtime >= mtime) { rval = 1; goto freegetit; } } } } recvrequest("RETR", locfile, remfile, gmode, remfile != argv[1] || locfile != argv[2], loc); restart_point = 0; freegetit: (void)free(olocfile); return (rval); } /* ARGSUSED */ static void mintr(int signo) { alarmtimer(0); if (fromatty) write(fileno(ttyout), "\n", 1); siglongjmp(jabort, 1); } static void mabort(const char *cmd) { int ointer, oconf; if (mflag && fromatty) { ointer = interactive; oconf = confirmrest; interactive = 1; confirmrest = 0; if (confirm(cmd, NULL)) { interactive = ointer; confirmrest = oconf; return; } interactive = ointer; confirmrest = oconf; } mflag = 0; } /* * Get multiple files. */ void mget(int argc, char *argv[]) { sigfunc oldintr; int ointer; char *cp; const char *tp; int volatile restartit; if (argc == 0 || (argc == 1 && !another(&argc, &argv, "remote-files"))) { UPRINTF("usage: %s remote-files\n", argv[0]); code = -1; return; } mflag = 1; restart_point = 0; restartit = 0; if (strcmp(argv[0], "mreget") == 0) { if (! features[FEAT_REST_STREAM]) { fprintf(ttyout, "Restart is not supported by the remote server.\n"); return; } restartit = 1; } oldintr = xsignal(SIGINT, mintr); if (sigsetjmp(jabort, 1)) mabort(argv[0]); while ((cp = remglob(argv, proxy, NULL)) != NULL) { char buf[MAXPATHLEN]; if (*cp == '\0' || !connected) { mflag = 0; continue; } if (! mflag) continue; if (! fileindir(cp, localcwd)) { fprintf(ttyout, "Skipping non-relative filename `%s'\n", cp); continue; } if (!confirm(argv[0], cp)) continue; tp = doprocess(buf, sizeof(buf), cp, mcase, ntflag, mapflag); if (restartit) { struct stat stbuf; if (stat(tp, &stbuf) == 0) restart_point = stbuf.st_size; else warn("Can't stat `%s'", tp); } recvrequest("RETR", tp, cp, restart_point ? "r+" : "w", tp != cp || !interactive, 1); restart_point = 0; if (!mflag && fromatty) { ointer = interactive; interactive = 1; if (confirm(argv[0], NULL)) mflag++; interactive = ointer; } } (void)xsignal(SIGINT, oldintr); mflag = 0; } /* * Read list of filenames from a local file and get those */ void fget(int argc, char *argv[]) { const char *gmode; FILE *fp; char buf[MAXPATHLEN], cmdbuf[MAX_C_NAME]; if (argc != 2) { UPRINTF("usage: %s localfile\n", argv[0]); code = -1; return; } fp = fopen(argv[1], "r"); if (fp == NULL) { fprintf(ttyout, "Can't open source file %s\n", argv[1]); code = -1; return; } (void)strlcpy(cmdbuf, "get", sizeof(cmdbuf)); argv[0] = cmdbuf; gmode = restart_point ? "r+" : "w"; while (get_line(fp, buf, sizeof(buf), NULL) >= 0) { if (buf[0] == '\0') continue; argv[1] = buf; (void)getit(argc, argv, 0, gmode); } fclose(fp); } const char * onoff(int val) { return (val ? "on" : "off"); } /* * Show status. */ /*ARGSUSED*/ void status(int argc, char *argv[]) { if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } #ifndef NO_STATUS if (connected) fprintf(ttyout, "Connected %sto %s.\n", connected == -1 ? "and logged in" : "", hostname); else fputs("Not connected.\n", ttyout); if (!proxy) { pswitch(1); if (connected) { fprintf(ttyout, "Connected for proxy commands to %s.\n", hostname); } else { fputs("No proxy connection.\n", ttyout); } pswitch(0); } fprintf(ttyout, "Gate ftp: %s, server %s, port %s.\n", onoff(gatemode), *gateserver ? gateserver : "(none)", gateport); fprintf(ttyout, "Passive mode: %s; fallback to active mode: %s.\n", onoff(passivemode), onoff(activefallback)); fprintf(ttyout, "Mode: %s; Type: %s; Form: %s; Structure: %s.\n", modename, typename, formname, structname); fprintf(ttyout, "Verbose: %s; Bell: %s; Prompting: %s; Globbing: %s.\n", onoff(verbose), onoff(bell), onoff(interactive), onoff(doglob)); fprintf(ttyout, "Store unique: %s; Receive unique: %s.\n", onoff(sunique), onoff(runique)); fprintf(ttyout, "Preserve modification times: %s.\n", onoff(preserve)); fprintf(ttyout, "Case: %s; CR stripping: %s.\n", onoff(mcase), onoff(crflag)); if (ntflag) { fprintf(ttyout, "Ntrans: (in) %s (out) %s\n", ntin, ntout); } else { fputs("Ntrans: off.\n", ttyout); } if (mapflag) { fprintf(ttyout, "Nmap: (in) %s (out) %s\n", mapin, mapout); } else { fputs("Nmap: off.\n", ttyout); } fprintf(ttyout, "Hash mark printing: %s; Mark count: %d; Progress bar: %s.\n", onoff(hash), mark, onoff(progress)); fprintf(ttyout, "Get transfer rate throttle: %s; maximum: %d; increment %d.\n", onoff(rate_get), rate_get, rate_get_incr); fprintf(ttyout, "Put transfer rate throttle: %s; maximum: %d; increment %d.\n", onoff(rate_put), rate_put, rate_put_incr); fprintf(ttyout, "Socket buffer sizes: send %d, receive %d.\n", sndbuf_size, rcvbuf_size); fprintf(ttyout, "Use of PORT cmds: %s.\n", onoff(sendport)); fprintf(ttyout, "Use of EPSV/EPRT cmds for IPv4: %s%s.\n", onoff(epsv4), epsv4bad ? " (disabled for this connection)" : ""); fprintf(ttyout, "Use of EPSV/EPRT cmds for IPv6: %s%s.\n", onoff(epsv6), epsv6bad ? " (disabled for this connection)" : ""); fprintf(ttyout, "Command line editing: %s.\n", #ifdef NO_EDITCOMPLETE "support not compiled in" #else /* !def NO_EDITCOMPLETE */ onoff(editing) #endif /* !def NO_EDITCOMPLETE */ ); if (macnum > 0) { int i; fputs("Macros:\n", ttyout); for (i=0; i<macnum; i++) { fprintf(ttyout, "\t%s\n", macros[i].mac_name); } } #endif /* !def NO_STATUS */ fprintf(ttyout, "Version: %s %s\n", FTP_PRODUCT, FTP_VERSION); code = 0; } /* * Toggle a variable */ int togglevar(int argc, char *argv[], int *var, const char *mesg) { if (argc == 1) { *var = !*var; } else if (argc == 2 && strcasecmp(argv[1], "on") == 0) { *var = 1; } else if (argc == 2 && strcasecmp(argv[1], "off") == 0) { *var = 0; } else { UPRINTF("usage: %s [ on | off ]\n", argv[0]); return (-1); } if (mesg) fprintf(ttyout, "%s %s.\n", mesg, onoff(*var)); return (*var); } /* * Set beep on cmd completed mode. */ /*VARARGS*/ void setbell(int argc, char *argv[]) { code = togglevar(argc, argv, &bell, "Bell mode"); } /* * Set command line editing */ /*VARARGS*/ void setedit(int argc, char *argv[]) { #ifdef NO_EDITCOMPLETE if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } if (verbose) fputs("Editing support not compiled in; ignoring command.\n", ttyout); #else /* !def NO_EDITCOMPLETE */ code = togglevar(argc, argv, &editing, "Editing mode"); controlediting(); #endif /* !def NO_EDITCOMPLETE */ } /* * Turn on packet tracing. */ /*VARARGS*/ void settrace(int argc, char *argv[]) { code = togglevar(argc, argv, &trace, "Packet tracing"); } /* * Toggle hash mark printing during transfers, or set hash mark bytecount. */ /*VARARGS*/ void sethash(int argc, char *argv[]) { if (argc == 1) hash = !hash; else if (argc != 2) { UPRINTF("usage: %s [ on | off | bytecount ]\n", argv[0]); code = -1; return; } else if (strcasecmp(argv[1], "on") == 0) hash = 1; else if (strcasecmp(argv[1], "off") == 0) hash = 0; else { int nmark; nmark = strsuftoi(argv[1]); if (nmark < 1) { fprintf(ttyout, "mark: bad bytecount value `%s'.\n", argv[1]); code = -1; return; } mark = nmark; hash = 1; } fprintf(ttyout, "Hash mark printing %s", onoff(hash)); if (hash) fprintf(ttyout, " (%d bytes/hash mark)", mark); fputs(".\n", ttyout); if (hash) progress = 0; code = hash; } /* * Turn on printing of server echo's. */ /*VARARGS*/ void setverbose(int argc, char *argv[]) { code = togglevar(argc, argv, &verbose, "Verbose mode"); } /* * Toggle PORT/LPRT cmd use before each data connection. */ /*VARARGS*/ void setport(int argc, char *argv[]) { code = togglevar(argc, argv, &sendport, "Use of PORT/LPRT cmds"); } /* * Toggle transfer progress bar. */ /*VARARGS*/ void setprogress(int argc, char *argv[]) { code = togglevar(argc, argv, &progress, "Progress bar"); if (progress) hash = 0; } /* * Turn on interactive prompting during mget, mput, and mdelete. */ /*VARARGS*/ void setprompt(int argc, char *argv[]) { code = togglevar(argc, argv, &interactive, "Interactive mode"); } /* * Toggle gate-ftp mode, or set gate-ftp server */ /*VARARGS*/ void setgate(int argc, char *argv[]) { static char gsbuf[MAXHOSTNAMELEN]; if (argc == 0 || argc > 3) { UPRINTF( "usage: %s [ on | off | gateserver [port] ]\n", argv[0]); code = -1; return; } else if (argc < 2) { gatemode = !gatemode; } else { if (argc == 2 && strcasecmp(argv[1], "on") == 0) gatemode = 1; else if (argc == 2 && strcasecmp(argv[1], "off") == 0) gatemode = 0; else { if (argc == 3) gateport = ftp_strdup(argv[2]); (void)strlcpy(gsbuf, argv[1], sizeof(gsbuf)); gateserver = gsbuf; gatemode = 1; } } if (gatemode && (gateserver == NULL || *gateserver == '\0')) { fprintf(ttyout, "Disabling gate-ftp mode - no gate-ftp server defined.\n"); gatemode = 0; } else { fprintf(ttyout, "Gate ftp: %s, server %s, port %s.\n", onoff(gatemode), *gateserver ? gateserver : "(none)", gateport); } code = gatemode; } /* * Toggle metacharacter interpretation on local file names. */ /*VARARGS*/ void setglob(int argc, char *argv[]) { code = togglevar(argc, argv, &doglob, "Globbing"); } /* * Toggle preserving modification times on retrieved files. */ /*VARARGS*/ void setpreserve(int argc, char *argv[]) { code = togglevar(argc, argv, &preserve, "Preserve modification times"); } /* * Set debugging mode on/off and/or set level of debugging. */ /*VARARGS*/ void setdebug(int argc, char *argv[]) { if (argc == 0 || argc > 2) { UPRINTF("usage: %s [ on | off | debuglevel ]\n", argv[0]); code = -1; return; } else if (argc == 2) { if (strcasecmp(argv[1], "on") == 0) ftp_debug = 1; else if (strcasecmp(argv[1], "off") == 0) ftp_debug = 0; else { int val; val = strsuftoi(argv[1]); if (val < 0) { fprintf(ttyout, "%s: bad debugging value.\n", argv[1]); code = -1; return; } ftp_debug = val; } } else ftp_debug = !ftp_debug; if (ftp_debug) options |= SO_DEBUG; else options &= ~SO_DEBUG; fprintf(ttyout, "Debugging %s (ftp_debug=%d).\n", onoff(ftp_debug), ftp_debug); code = ftp_debug > 0; } /* * Set current working directory on remote machine. */ void cd(int argc, char *argv[]) { int r; if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "remote-directory"))) { UPRINTF("usage: %s remote-directory\n", argv[0]); code = -1; return; } r = command("CWD %s", argv[1]); if (r == ERROR && code == 500) { if (verbose) fputs("CWD command not recognized, trying XCWD.\n", ttyout); r = command("XCWD %s", argv[1]); } if (r == COMPLETE) { dirchange = 1; updateremotecwd(); } } /* * Set current working directory on local machine. */ void lcd(int argc, char *argv[]) { char *locdir; code = -1; if (argc == 1) { argc++; argv[1] = localhome; } if (argc != 2) { UPRINTF("usage: %s [local-directory]\n", argv[0]); return; } if ((locdir = globulize(argv[1])) == NULL) return; if (chdir(locdir) == -1) warn("Can't chdir `%s'", locdir); else { updatelocalcwd(); if (localcwd[0]) { fprintf(ttyout, "Local directory now: %s\n", localcwd); code = 0; } else { fprintf(ttyout, "Unable to determine local directory\n"); } } (void)free(locdir); } /* * Delete a single file. */ void delete(int argc, char *argv[]) { if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "remote-file"))) { UPRINTF("usage: %s remote-file\n", argv[0]); code = -1; return; } if (command("DELE %s", argv[1]) == COMPLETE) dirchange = 1; } /* * Delete multiple files. */ void mdelete(int argc, char *argv[]) { sigfunc oldintr; int ointer; char *cp; if (argc == 0 || (argc == 1 && !another(&argc, &argv, "remote-files"))) { UPRINTF("usage: %s [remote-files]\n", argv[0]); code = -1; return; } mflag = 1; oldintr = xsignal(SIGINT, mintr); if (sigsetjmp(jabort, 1)) mabort(argv[0]); while ((cp = remglob(argv, 0, NULL)) != NULL) { if (*cp == '\0') { mflag = 0; continue; } if (mflag && confirm(argv[0], cp)) { if (command("DELE %s", cp) == COMPLETE) dirchange = 1; if (!mflag && fromatty) { ointer = interactive; interactive = 1; if (confirm(argv[0], NULL)) { mflag++; } interactive = ointer; } } } (void)xsignal(SIGINT, oldintr); mflag = 0; } /* * Rename a remote file. */ void renamefile(int argc, char *argv[]) { if (argc == 0 || (argc == 1 && !another(&argc, &argv, "from-name"))) goto usage; if ((argc < 3 && !another(&argc, &argv, "to-name")) || argc > 3) { usage: UPRINTF("usage: %s from-name to-name\n", argv[0]); code = -1; return; } if (command("RNFR %s", argv[1]) == CONTINUE && command("RNTO %s", argv[2]) == COMPLETE) dirchange = 1; } /* * Get a directory listing of remote files. * Supports being invoked as: * cmd runs * --- ---- * dir, ls LIST * mlsd MLSD * nlist NLST * pdir, pls LIST |$PAGER * pmlsd MLSD |$PAGER */ void ls(int argc, char *argv[]) { const char *cmd; char *remdir, *locbuf; const char *locfile; int pagecmd, mlsdcmd; remdir = NULL; locbuf = NULL; locfile = "-"; pagecmd = mlsdcmd = 0; /* * the only commands that start with `p' are * the `pager' versions. */ if (argv[0][0] == 'p') pagecmd = 1; if (strcmp(argv[0] + pagecmd , "mlsd") == 0) { if (! features[FEAT_MLST]) { fprintf(ttyout, "MLSD is not supported by the remote server.\n"); return; } mlsdcmd = 1; } if (argc == 0) goto usage; if (mlsdcmd) cmd = "MLSD"; else if (strcmp(argv[0] + pagecmd, "nlist") == 0) cmd = "NLST"; else cmd = "LIST"; if (argc > 1) remdir = argv[1]; if (argc > 2) locfile = argv[2]; if (argc > 3 || ((pagecmd | mlsdcmd) && argc > 2)) { usage: if (pagecmd || mlsdcmd) UPRINTF("usage: %s [remote-path]\n", argv[0]); else UPRINTF("usage: %s [remote-path [local-file]]\n", argv[0]); code = -1; goto freels; } if (pagecmd) { const char *p; size_t len; p = getoptionvalue("pager"); if (EMPTYSTRING(p)) p = DEFAULTPAGER; len = strlen(p) + 2; locbuf = ftp_malloc(len); locbuf[0] = '|'; (void)strlcpy(locbuf + 1, p, len - 1); locfile = locbuf; } else if ((strcmp(locfile, "-") != 0) && *locfile != '|') { if ((locbuf = globulize(locfile)) == NULL || !confirm("output to local-file:", locbuf)) { code = -1; goto freels; } locfile = locbuf; } recvrequest(cmd, locfile, remdir, "w", 0, 0); freels: if (locbuf) (void)free(locbuf); } /* * Get a directory listing of multiple remote files. */ void mls(int argc, char *argv[]) { sigfunc oldintr; int ointer, i; int volatile dolist; char * volatile dest, *odest; const char *lmode; if (argc == 0) goto usage; if (argc < 2 && !another(&argc, &argv, "remote-files")) goto usage; if (argc < 3 && !another(&argc, &argv, "local-file")) { usage: UPRINTF("usage: %s remote-files local-file\n", argv[0]); code = -1; return; } odest = dest = argv[argc - 1]; argv[argc - 1] = NULL; if (strcmp(dest, "-") && *dest != '|') if (((dest = globulize(dest)) == NULL) || !confirm("output to local-file:", dest)) { code = -1; return; } dolist = strcmp(argv[0], "mls"); mflag = 1; oldintr = xsignal(SIGINT, mintr); if (sigsetjmp(jabort, 1)) mabort(argv[0]); for (i = 1; mflag && i < argc-1 && connected; i++) { lmode = (i == 1) ? "w" : "a"; recvrequest(dolist ? "LIST" : "NLST", dest, argv[i], lmode, 0, 0); if (!mflag && fromatty) { ointer = interactive; interactive = 1; if (confirm(argv[0], NULL)) { mflag++; } interactive = ointer; } } (void)xsignal(SIGINT, oldintr); mflag = 0; if (dest != odest) /* free up after globulize() */ free(dest); } /* * Do a shell escape */ /*ARGSUSED*/ void shell(int argc, char *argv[]) { pid_t pid; sigfunc oldintr; char shellnam[MAXPATHLEN]; const char *shellp, *namep; int wait_status; if (argc == 0) { UPRINTF("usage: %s [command [args]]\n", argv[0]); code = -1; return; } oldintr = xsignal(SIGINT, SIG_IGN); if ((pid = fork()) == 0) { for (pid = 3; pid < 20; pid++) (void)close(pid); (void)xsignal(SIGINT, SIG_DFL); shellp = getenv("SHELL"); if (shellp == NULL) shellp = _PATH_BSHELL; namep = strrchr(shellp, '/'); if (namep == NULL) namep = shellp; else namep++; (void)strlcpy(shellnam, namep, sizeof(shellnam)); if (ftp_debug) { fputs(shellp, ttyout); putc('\n', ttyout); } if (argc > 1) { execl(shellp, shellnam, "-c", altarg, (char *)0); } else { execl(shellp, shellnam, (char *)0); } warn("Can't execute `%s'", shellp); code = -1; exit(1); } if (pid > 0) while (wait(&wait_status) != pid) ; (void)xsignal(SIGINT, oldintr); if (pid == -1) { warn("Can't fork a subshell; try again later"); code = -1; } else code = 0; } /* * Send new user information (re-login) */ void user(int argc, char *argv[]) { char *password; char emptypass[] = ""; int n, aflag = 0; if (argc == 0) goto usage; if (argc < 2) (void)another(&argc, &argv, "username"); if (argc < 2 || argc > 4) { usage: UPRINTF("usage: %s username [password [account]]\n", argv[0]); code = -1; return; } n = command("USER %s", argv[1]); if (n == CONTINUE) { if (argc < 3) { password = getpass("Password: "); if (password == NULL) password = emptypass; } else { password = argv[2]; } n = command("PASS %s", password); memset(password, 0, strlen(password)); } if (n == CONTINUE) { aflag++; if (argc < 4) { password = getpass("Account: "); if (password == NULL) password = emptypass; } else { password = argv[3]; } n = command("ACCT %s", password); memset(password, 0, strlen(password)); } if (n != COMPLETE) { fputs("Login failed.\n", ttyout); return; } if (!aflag && argc == 4) { password = argv[3]; (void)command("ACCT %s", password); memset(password, 0, strlen(password)); } connected = -1; getremoteinfo(); } /* * Print working directory on remote machine. */ /*VARARGS*/ void pwd(int argc, char *argv[]) { code = -1; if (argc != 1) { UPRINTF("usage: %s\n", argv[0]); return; } if (! remotecwd[0]) updateremotecwd(); if (! remotecwd[0]) fprintf(ttyout, "Unable to determine remote directory\n"); else { fprintf(ttyout, "Remote directory: %s\n", remotecwd); code = 0; } } /* * Print working directory on local machine. */ void lpwd(int argc, char *argv[]) { code = -1; if (argc != 1) { UPRINTF("usage: %s\n", argv[0]); return; } if (! localcwd[0]) updatelocalcwd(); if (! localcwd[0]) fprintf(ttyout, "Unable to determine local directory\n"); else { fprintf(ttyout, "Local directory: %s\n", localcwd); code = 0; } } /* * Make a directory. */ void makedir(int argc, char *argv[]) { int r; if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "directory-name"))) { UPRINTF("usage: %s directory-name\n", argv[0]); code = -1; return; } r = command("MKD %s", argv[1]); if (r == ERROR && code == 500) { if (verbose) fputs("MKD command not recognized, trying XMKD.\n", ttyout); r = command("XMKD %s", argv[1]); } if (r == COMPLETE) dirchange = 1; } /* * Remove a directory. */ void removedir(int argc, char *argv[]) { int r; if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "directory-name"))) { UPRINTF("usage: %s directory-name\n", argv[0]); code = -1; return; } r = command("RMD %s", argv[1]); if (r == ERROR && code == 500) { if (verbose) fputs("RMD command not recognized, trying XRMD.\n", ttyout); r = command("XRMD %s", argv[1]); } if (r == COMPLETE) dirchange = 1; } /* * Send a line, verbatim, to the remote machine. */ void quote(int argc, char *argv[]) { if (argc == 0 || (argc == 1 && !another(&argc, &argv, "command line to send"))) { UPRINTF("usage: %s line-to-send\n", argv[0]); code = -1; return; } quote1("", argc, argv); } /* * Send a SITE command to the remote machine. The line * is sent verbatim to the remote machine, except that the * word "SITE" is added at the front. */ void site(int argc, char *argv[]) { if (argc == 0 || (argc == 1 && !another(&argc, &argv, "arguments to SITE command"))){ UPRINTF("usage: %s line-to-send\n", argv[0]); code = -1; return; } quote1("SITE ", argc, argv); } /* * Turn argv[1..argc) into a space-separated string, then prepend initial text. * Send the result as a one-line command and get response. */ void quote1(const char *initial, int argc, char *argv[]) { int i; char buf[BUFSIZ]; /* must be >= sizeof(line) */ (void)strlcpy(buf, initial, sizeof(buf)); for (i = 1; i < argc; i++) { (void)strlcat(buf, argv[i], sizeof(buf)); if (i < (argc - 1)) (void)strlcat(buf, " ", sizeof(buf)); } if (command("%s", buf) == PRELIM) { while (getreply(0) == PRELIM) continue; } dirchange = 1; } void do_chmod(int argc, char *argv[]) { if (argc == 0 || (argc == 1 && !another(&argc, &argv, "mode"))) goto usage; if ((argc < 3 && !another(&argc, &argv, "remote-file")) || argc > 3) { usage: UPRINTF("usage: %s mode remote-file\n", argv[0]); code = -1; return; } (void)command("SITE CHMOD %s %s", argv[1], argv[2]); } #define COMMAND_1ARG(argc, argv, cmd) \ if (argc == 1) \ command(cmd); \ else \ command(cmd " %s", argv[1]) void do_umask(int argc, char *argv[]) { int oldverbose = verbose; if (argc == 0) { UPRINTF("usage: %s [umask]\n", argv[0]); code = -1; return; } verbose = 1; COMMAND_1ARG(argc, argv, "SITE UMASK"); verbose = oldverbose; } void idlecmd(int argc, char *argv[]) { int oldverbose = verbose; if (argc < 1 || argc > 2) { UPRINTF("usage: %s [seconds]\n", argv[0]); code = -1; return; } verbose = 1; COMMAND_1ARG(argc, argv, "SITE IDLE"); verbose = oldverbose; } /* * Ask the other side for help. */ void rmthelp(int argc, char *argv[]) { int oldverbose = verbose; if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } verbose = 1; COMMAND_1ARG(argc, argv, "HELP"); verbose = oldverbose; } /* * Terminate session and exit. * May be called with 0, NULL. */ /*VARARGS*/ void quit(int argc, char *argv[]) { /* this may be called with argc == 0, argv == NULL */ if (argc == 0 && argv != NULL) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } if (connected) disconnect(0, NULL); pswitch(1); if (connected) disconnect(0, NULL); exit(0); } /* * Terminate session, but don't exit. * May be called with 0, NULL. */ void disconnect(int argc, char *argv[]) { /* this may be called with argc == 0, argv == NULL */ if (argc == 0 && argv != NULL) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } if (!connected) return; (void)command("QUIT"); cleanuppeer(); } void account(int argc, char *argv[]) { char *ap; char emptypass[] = ""; if (argc == 0 || argc > 2) { UPRINTF("usage: %s [password]\n", argv[0]); code = -1; return; } else if (argc == 2) ap = argv[1]; else { ap = getpass("Account:"); if (ap == NULL) ap = emptypass; } (void)command("ACCT %s", ap); memset(ap, 0, strlen(ap)); } sigjmp_buf abortprox; void proxabort(int notused) { sigint_raised = 1; alarmtimer(0); if (!proxy) { pswitch(1); } if (connected) { proxflag = 1; } else { proxflag = 0; } pswitch(0); siglongjmp(abortprox, 1); } void doproxy(int argc, char *argv[]) { struct cmd *c; int cmdpos; sigfunc oldintr; char cmdbuf[MAX_C_NAME]; if (argc == 0 || (argc == 1 && !another(&argc, &argv, "command"))) { UPRINTF("usage: %s command\n", argv[0]); code = -1; return; } c = getcmd(argv[1]); if (c == (struct cmd *) -1) { fputs("?Ambiguous command.\n", ttyout); code = -1; return; } if (c == 0) { fputs("?Invalid command.\n", ttyout); code = -1; return; } if (!c->c_proxy) { fputs("?Invalid proxy command.\n", ttyout); code = -1; return; } if (sigsetjmp(abortprox, 1)) { code = -1; return; } oldintr = xsignal(SIGINT, proxabort); pswitch(1); if (c->c_conn && !connected) { fputs("Not connected.\n", ttyout); pswitch(0); (void)xsignal(SIGINT, oldintr); code = -1; return; } cmdpos = strcspn(line, " \t"); if (cmdpos > 0) /* remove leading "proxy " from input buffer */ memmove(line, line + cmdpos + 1, strlen(line) - cmdpos + 1); (void)strlcpy(cmdbuf, c->c_name, sizeof(cmdbuf)); argv[1] = cmdbuf; (*c->c_handler)(argc-1, argv+1); if (connected) { proxflag = 1; } else { proxflag = 0; } pswitch(0); (void)xsignal(SIGINT, oldintr); } void setcase(int argc, char *argv[]) { code = togglevar(argc, argv, &mcase, "Case mapping"); } /* * convert the given name to lower case if it's all upper case, into * a static buffer which is returned to the caller */ static const char * docase(char *dst, size_t dlen, const char *src) { size_t i; int dochange = 1; for (i = 0; src[i] != '\0' && i < dlen - 1; i++) { dst[i] = src[i]; if (islower((unsigned char)dst[i])) dochange = 0; } dst[i] = '\0'; if (dochange) { for (i = 0; dst[i] != '\0'; i++) if (isupper((unsigned char)dst[i])) dst[i] = tolower((unsigned char)dst[i]); } return dst; } void setcr(int argc, char *argv[]) { code = togglevar(argc, argv, &crflag, "Carriage Return stripping"); } void setntrans(int argc, char *argv[]) { if (argc == 0 || argc > 3) { UPRINTF("usage: %s [inchars [outchars]]\n", argv[0]); code = -1; return; } if (argc == 1) { ntflag = 0; fputs("Ntrans off.\n", ttyout); code = ntflag; return; } ntflag++; code = ntflag; (void)strlcpy(ntin, argv[1], sizeof(ntin)); if (argc == 2) { ntout[0] = '\0'; return; } (void)strlcpy(ntout, argv[2], sizeof(ntout)); } static const char * dotrans(char *dst, size_t dlen, const char *src) { const char *cp1; char *cp2 = dst; size_t i, ostop; for (ostop = 0; *(ntout + ostop) && ostop < 16; ostop++) continue; for (cp1 = src; *cp1; cp1++) { int found = 0; for (i = 0; *(ntin + i) && i < 16; i++) { if (*cp1 == *(ntin + i)) { found++; if (i < ostop) { *cp2++ = *(ntout + i); if (cp2 - dst >= (ptrdiff_t)(dlen - 1)) goto out; } break; } } if (!found) { *cp2++ = *cp1; } } out: *cp2 = '\0'; return dst; } void setnmap(int argc, char *argv[]) { char *cp; if (argc == 1) { mapflag = 0; fputs("Nmap off.\n", ttyout); code = mapflag; return; } if (argc == 0 || (argc < 3 && !another(&argc, &argv, "mapout")) || argc > 3) { UPRINTF("usage: %s [mapin mapout]\n", argv[0]); code = -1; return; } mapflag = 1; code = 1; cp = strchr(altarg, ' '); if (proxy) { while(*++cp == ' ') continue; altarg = cp; cp = strchr(altarg, ' '); } *cp = '\0'; (void)strlcpy(mapin, altarg, MAXPATHLEN); while (*++cp == ' ') continue; (void)strlcpy(mapout, cp, MAXPATHLEN); } static const char * domap(char *dst, size_t dlen, const char *src) { const char *cp1 = src; char *cp2 = mapin; const char *tp[9], *te[9]; int i, toks[9], toknum = 0, match = 1; for (i=0; i < 9; ++i) { toks[i] = 0; } while (match && *cp1 && *cp2) { switch (*cp2) { case '\\': if (*++cp2 != *cp1) { match = 0; } break; case '$': if (*(cp2+1) >= '1' && (*cp2+1) <= '9') { if (*cp1 != *(++cp2+1)) { toks[toknum = *cp2 - '1']++; tp[toknum] = cp1; while (*++cp1 && *(cp2+1) != *cp1); te[toknum] = cp1; } cp2++; break; } /* FALLTHROUGH */ default: if (*cp2 != *cp1) { match = 0; } break; } if (match && *cp1) { cp1++; } if (match && *cp2) { cp2++; } } if (!match && *cp1) /* last token mismatch */ { toks[toknum] = 0; } cp2 = dst; *cp2 = '\0'; cp1 = mapout; while (*cp1) { match = 0; switch (*cp1) { case '\\': if (*(cp1 + 1)) { *cp2++ = *++cp1; } break; case '[': LOOP: if (*++cp1 == '$' && isdigit((unsigned char)*(cp1+1))) { if (*++cp1 == '0') { const char *cp3 = src; while (*cp3) { *cp2++ = *cp3++; } match = 1; } else if (toks[toknum = *cp1 - '1']) { const char *cp3 = tp[toknum]; while (cp3 != te[toknum]) { *cp2++ = *cp3++; } match = 1; } } else { while (*cp1 && *cp1 != ',' && *cp1 != ']') { if (*cp1 == '\\') { cp1++; } else if (*cp1 == '$' && isdigit((unsigned char)*(cp1+1))) { if (*++cp1 == '0') { const char *cp3 = src; while (*cp3) { *cp2++ = *cp3++; } } else if (toks[toknum = *cp1 - '1']) { const char *cp3=tp[toknum]; while (cp3 != te[toknum]) { *cp2++ = *cp3++; } } } else if (*cp1) { *cp2++ = *cp1++; } } if (!*cp1) { fputs( "nmap: unbalanced brackets.\n", ttyout); return (src); } match = 1; cp1--; } if (match) { while (*++cp1 && *cp1 != ']') { if (*cp1 == '\\' && *(cp1 + 1)) { cp1++; } } if (!*cp1) { fputs( "nmap: unbalanced brackets.\n", ttyout); return (src); } break; } switch (*++cp1) { case ',': goto LOOP; case ']': break; default: cp1--; goto LOOP; } break; case '$': if (isdigit((unsigned char)*(cp1 + 1))) { if (*++cp1 == '0') { const char *cp3 = src; while (*cp3) { *cp2++ = *cp3++; } } else if (toks[toknum = *cp1 - '1']) { const char *cp3 = tp[toknum]; while (cp3 != te[toknum]) { *cp2++ = *cp3++; } } break; } /* intentional drop through */ default: *cp2++ = *cp1; break; } cp1++; } *cp2 = '\0'; return *dst ? dst : src; } void setpassive(int argc, char *argv[]) { if (argc == 1) { passivemode = !passivemode; activefallback = passivemode; } else if (argc != 2) { passiveusage: UPRINTF("usage: %s [ on | off | auto ]\n", argv[0]); code = -1; return; } else if (strcasecmp(argv[1], "on") == 0) { passivemode = 1; activefallback = 0; } else if (strcasecmp(argv[1], "off") == 0) { passivemode = 0; activefallback = 0; } else if (strcasecmp(argv[1], "auto") == 0) { passivemode = 1; activefallback = 1; } else goto passiveusage; fprintf(ttyout, "Passive mode: %s; fallback to active mode: %s.\n", onoff(passivemode), onoff(activefallback)); code = passivemode; } void setepsv4(int argc, char *argv[]) { code = togglevar(argc, argv, &epsv4, verbose ? "EPSV/EPRT on IPv4" : NULL); epsv4bad = 0; } void setepsv6(int argc, char *argv[]) { code = togglevar(argc, argv, &epsv6, verbose ? "EPSV/EPRT on IPv6" : NULL); epsv6bad = 0; } void setepsv(int argc, char*argv[]) { setepsv4(argc,argv); setepsv6(argc,argv); } void setsunique(int argc, char *argv[]) { code = togglevar(argc, argv, &sunique, "Store unique"); } void setrunique(int argc, char *argv[]) { code = togglevar(argc, argv, &runique, "Receive unique"); } int parserate(int argc, char *argv[], int cmdlineopt) { int dir, max, incr, showonly; sigfunc oldusr1, oldusr2; if (argc > 4 || (argc < (cmdlineopt ? 3 : 2))) { usage: if (cmdlineopt) UPRINTF( "usage: %s (all|get|put),maximum-bytes[,increment-bytes]]\n", argv[0]); else UPRINTF( "usage: %s (all|get|put) [maximum-bytes [increment-bytes]]\n", argv[0]); return -1; } dir = max = incr = showonly = 0; #define RATE_GET 1 #define RATE_PUT 2 #define RATE_ALL (RATE_GET | RATE_PUT) if (strcasecmp(argv[1], "all") == 0) dir = RATE_ALL; else if (strcasecmp(argv[1], "get") == 0) dir = RATE_GET; else if (strcasecmp(argv[1], "put") == 0) dir = RATE_PUT; else goto usage; if (argc >= 3) { if ((max = strsuftoi(argv[2])) < 0) goto usage; } else showonly = 1; if (argc == 4) { if ((incr = strsuftoi(argv[3])) <= 0) goto usage; } else incr = DEFAULTINCR; oldusr1 = xsignal(SIGUSR1, SIG_IGN); oldusr2 = xsignal(SIGUSR2, SIG_IGN); if (dir & RATE_GET) { if (!showonly) { rate_get = max; rate_get_incr = incr; } if (!cmdlineopt || verbose) fprintf(ttyout, "Get transfer rate throttle: %s; maximum: %d; increment %d.\n", onoff(rate_get), rate_get, rate_get_incr); } if (dir & RATE_PUT) { if (!showonly) { rate_put = max; rate_put_incr = incr; } if (!cmdlineopt || verbose) fprintf(ttyout, "Put transfer rate throttle: %s; maximum: %d; increment %d.\n", onoff(rate_put), rate_put, rate_put_incr); } (void)xsignal(SIGUSR1, oldusr1); (void)xsignal(SIGUSR2, oldusr2); return 0; } void setrate(int argc, char *argv[]) { code = parserate(argc, argv, 0); } /* change directory to parent directory */ void cdup(int argc, char *argv[]) { int r; if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } r = command("CDUP"); if (r == ERROR && code == 500) { if (verbose) fputs("CDUP command not recognized, trying XCUP.\n", ttyout); r = command("XCUP"); } if (r == COMPLETE) { dirchange = 1; updateremotecwd(); } } /* * Restart transfer at specific point */ void restart(int argc, char *argv[]) { if (argc == 0 || argc > 2) { UPRINTF("usage: %s [restart-point]\n", argv[0]); code = -1; return; } if (! features[FEAT_REST_STREAM]) { fprintf(ttyout, "Restart is not supported by the remote server.\n"); return; } if (argc == 2) { off_t rp; char *ep; rp = STRTOLL(argv[1], &ep, 10); if (rp < 0 || *ep != '\0') fprintf(ttyout, "restart: Invalid offset `%s'\n", argv[1]); else restart_point = rp; } if (restart_point == 0) fputs("No restart point defined.\n", ttyout); else fprintf(ttyout, "Restarting at " LLF " for next get, put or append\n", (LLT)restart_point); } /* * Show remote system type */ void syst(int argc, char *argv[]) { int oldverbose = verbose; if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } verbose = 1; /* If we aren't verbose, this doesn't do anything! */ (void)command("SYST"); verbose = oldverbose; } void macdef(int argc, char *argv[]) { char *tmp; int c; if (argc == 0) goto usage; if (macnum == 16) { fputs("Limit of 16 macros have already been defined.\n", ttyout); code = -1; return; } if ((argc < 2 && !another(&argc, &argv, "macro name")) || argc > 2) { usage: UPRINTF("usage: %s macro_name\n", argv[0]); code = -1; return; } if (interactive) fputs( "Enter macro line by line, terminating it with a null line.\n", ttyout); (void)strlcpy(macros[macnum].mac_name, argv[1], sizeof(macros[macnum].mac_name)); if (macnum == 0) macros[macnum].mac_start = macbuf; else macros[macnum].mac_start = macros[macnum - 1].mac_end + 1; tmp = macros[macnum].mac_start; while (tmp != macbuf+4096) { if ((c = getchar()) == EOF) { fputs("macdef: end of file encountered.\n", ttyout); code = -1; return; } if ((*tmp = c) == '\n') { if (tmp == macros[macnum].mac_start) { macros[macnum++].mac_end = tmp; code = 0; return; } if (*(tmp-1) == '\0') { macros[macnum++].mac_end = tmp - 1; code = 0; return; } *tmp = '\0'; } tmp++; } while (1) { while ((c = getchar()) != '\n' && c != EOF) /* LOOP */; if (c == EOF || getchar() == '\n') { fputs("Macro not defined - 4K buffer exceeded.\n", ttyout); code = -1; return; } } } /* * Get size of file on remote machine */ void sizecmd(int argc, char *argv[]) { off_t size; if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "remote-file"))) { UPRINTF("usage: %s remote-file\n", argv[0]); code = -1; return; } size = remotesize(argv[1], 1); if (size != -1) fprintf(ttyout, "%s\t" LLF "\n", argv[1], (LLT)size); code = (size > 0); } /* * Get last modification time of file on remote machine */ void modtime(int argc, char *argv[]) { time_t mtime; if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "remote-file"))) { UPRINTF("usage: %s remote-file\n", argv[0]); code = -1; return; } mtime = remotemodtime(argv[1], 1); if (mtime != -1) fprintf(ttyout, "%s\t%s", argv[1], rfc2822time(localtime(&mtime))); code = (mtime > 0); } /* * Show status on remote machine */ void rmtstatus(int argc, char *argv[]) { if (argc == 0) { UPRINTF("usage: %s [remote-file]\n", argv[0]); code = -1; return; } COMMAND_1ARG(argc, argv, "STAT"); } /* * Get file if modtime is more recent than current file */ void newer(int argc, char *argv[]) { if (getit(argc, argv, -1, "w")) fprintf(ttyout, "Local file \"%s\" is newer than remote file \"%s\".\n", argv[2], argv[1]); } /* * Display one local file through $PAGER. */ void lpage(int argc, char *argv[]) { size_t len; const char *p; char *pager, *locfile; if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "local-file"))) { UPRINTF("usage: %s local-file\n", argv[0]); code = -1; return; } if ((locfile = globulize(argv[1])) == NULL) { code = -1; return; } p = getoptionvalue("pager"); if (EMPTYSTRING(p)) p = DEFAULTPAGER; len = strlen(p) + strlen(locfile) + 2; pager = ftp_malloc(len); (void)strlcpy(pager, p, len); (void)strlcat(pager, " ", len); (void)strlcat(pager, locfile, len); system(pager); code = 0; (void)free(pager); (void)free(locfile); } /* * Display one remote file through $PAGER. */ void page(int argc, char *argv[]) { int ohash, orestart_point, overbose; size_t len; const char *p; char *pager; if (argc == 0 || argc > 2 || (argc == 1 && !another(&argc, &argv, "remote-file"))) { UPRINTF("usage: %s remote-file\n", argv[0]); code = -1; return; } p = getoptionvalue("pager"); if (EMPTYSTRING(p)) p = DEFAULTPAGER; len = strlen(p) + 2; pager = ftp_malloc(len); pager[0] = '|'; (void)strlcpy(pager + 1, p, len - 1); ohash = hash; orestart_point = restart_point; overbose = verbose; hash = restart_point = verbose = 0; recvrequest("RETR", pager, argv[1], "r+", 1, 0); hash = ohash; restart_point = orestart_point; verbose = overbose; (void)free(pager); } /* * Set the socket send or receive buffer size. */ void setxferbuf(int argc, char *argv[]) { int size, dir; if (argc != 2) { usage: UPRINTF("usage: %s size\n", argv[0]); code = -1; return; } if (strcasecmp(argv[0], "sndbuf") == 0) dir = RATE_PUT; else if (strcasecmp(argv[0], "rcvbuf") == 0) dir = RATE_GET; else if (strcasecmp(argv[0], "xferbuf") == 0) dir = RATE_ALL; else goto usage; if ((size = strsuftoi(argv[1])) == -1) goto usage; if (size == 0) { fprintf(ttyout, "%s: size must be positive.\n", argv[0]); goto usage; } if (dir & RATE_PUT) sndbuf_size = size; if (dir & RATE_GET) rcvbuf_size = size; fprintf(ttyout, "Socket buffer sizes: send %d, receive %d.\n", sndbuf_size, rcvbuf_size); code = 0; } /* * Set or display options (defaults are provided by various env vars) */ void setoption(int argc, char *argv[]) { struct option *o; code = -1; if (argc == 0 || (argc != 1 && argc != 3)) { UPRINTF("usage: %s [option value]\n", argv[0]); return; } #define OPTIONINDENT ((int) sizeof("https_proxy")) if (argc == 1) { for (o = optiontab; o->name != NULL; o++) { fprintf(ttyout, "%-*s\t%s\n", OPTIONINDENT, o->name, o->value ? o->value : ""); } } else { set_option(argv[1], argv[2], 1); } code = 0; } void set_option(const char * option, const char * value, int doverbose) { struct option *o; o = getoption(option); if (o == NULL) { fprintf(ttyout, "No such option `%s'.\n", option); return; } FREEPTR(o->value); o->value = ftp_strdup(value); if (verbose && doverbose) fprintf(ttyout, "Setting `%s' to `%s'.\n", o->name, o->value); } /* * Unset an option */ void unsetoption(int argc, char *argv[]) { struct option *o; code = -1; if (argc == 0 || argc != 2) { UPRINTF("usage: %s option\n", argv[0]); return; } o = getoption(argv[1]); if (o == NULL) { fprintf(ttyout, "No such option `%s'.\n", argv[1]); return; } FREEPTR(o->value); fprintf(ttyout, "Unsetting `%s'.\n", o->name); code = 0; } /* * Display features supported by the remote host. */ void feat(int argc, char *argv[]) { int oldverbose = verbose; if (argc == 0) { UPRINTF("usage: %s\n", argv[0]); code = -1; return; } if (! features[FEAT_FEAT]) { fprintf(ttyout, "FEAT is not supported by the remote server.\n"); return; } verbose = 1; /* If we aren't verbose, this doesn't do anything! */ (void)command("FEAT"); verbose = oldverbose; } void mlst(int argc, char *argv[]) { int oldverbose = verbose; if (argc < 1 || argc > 2) { UPRINTF("usage: %s [remote-path]\n", argv[0]); code = -1; return; } if (! features[FEAT_MLST]) { fprintf(ttyout, "MLST is not supported by the remote server.\n"); return; } verbose = 1; /* If we aren't verbose, this doesn't do anything! */ COMMAND_1ARG(argc, argv, "MLST"); verbose = oldverbose; } void opts(int argc, char *argv[]) { int oldverbose = verbose; if (argc < 2 || argc > 3) { UPRINTF("usage: %s command [options]\n", argv[0]); code = -1; return; } if (! features[FEAT_FEAT]) { fprintf(ttyout, "OPTS is not supported by the remote server.\n"); return; } verbose = 1; /* If we aren't verbose, this doesn't do anything! */ if (argc == 2) command("OPTS %s", argv[1]); else command("OPTS %s %s", argv[1], argv[2]); verbose = oldverbose; }
f53caa67c3c297c01cac0fd9c1776c1ddc90842c
67801a1568b81ea5e45ed534301cd35949066e6d
/src/registers/timers/tmr3.c
3832e922d4c0280bc8493ea505dda349a3cb304c
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
fossasia/pslab-firmware
dcb8e570d162c0ef24cdedf43483c706bc736259
c93ac629442315c1430120b7ab3c0026d03e3503
refs/heads/main
2023-07-22T18:22:30.827478
2023-07-05T05:32:15
2023-07-05T05:38:34
86,472,725
2,212
89
Apache-2.0
2023-09-14T20:36:23
2017-03-28T14:53:27
C
UTF-8
C
false
false
1,107
c
tmr3.c
#include <stdio.h> #include "tmr3.h" void TMR3_Initialize(void) { // Clear timer 3 register TMR3 = 0x00; TMR3HLD = 0x00; //Period = 0 s; Frequency = 64000000 Hz; PR4 0; PR3 = 0x00; // Stops timer T3CONbits.TON = 0; // Continues module operation in Idle mode T3CONbits.TSIDL = 0; // Gated time accumulation is disabled T3CONbits.TGATE = 0; // Timer4 Input Clock Pre scale Select bits as 1:1 T3CONbits.TCKPS = 0b00; // Internal clock (FP) T3CONbits.TCS = 0; // Disable interrupts _T3IE = 0; _T3IF = 0; } void TMR3_Period16BitSet(uint16_t value) { /* Update the counter values */ PR3 = value; } uint16_t TMR3_Period16BitGet(void) { return (PR3); } void TMR3_Counter16BitSet(uint16_t value) { /* Update the counter values */ TMR3 = value; } uint16_t TMR3_Counter16BitGet(void) { return (TMR3); } uint16_t TMR3_Carry16BitGet(void) { return TMR3HLD; } void TMR3_Start(void) { /* Start the Timer */ T3CONbits.TON = 1; } void TMR3_Stop(void) { /* Stop the Timer */ T3CONbits.TON = false; }
edda8bcd3c51a175017e3ec65ccf80c441cd5b04
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/u-boot_new/drivers/video/ipu_regs.h
21e9c99e0e637b68e1c834e16189f7694d72b961
[ "GPL-2.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
10,162
h
ipu_regs.h
/* * Porting to u-boot: * * (C) Copyright 2010 * Stefano Babic, DENX Software Engineering, sbabic@denx.de * * Linux IPU driver for MX51: * * (C) Copyright 2005-2009 Freescale Semiconductor, Inc. * * SPDX-License-Identifier: GPL-2.0+ */ #ifndef __IPU_REGS_INCLUDED__ #define __IPU_REGS_INCLUDED__ #define IPU_DISP0_BASE 0x00000000 #define IPU_MCU_T_DEFAULT 8 #define IPU_DISP1_BASE (IPU_MCU_T_DEFAULT << 25) #define IPU_CM_REG_BASE 0x00000000 #define IPU_STAT_REG_BASE 0x00000200 #define IPU_IDMAC_REG_BASE 0x00008000 #define IPU_ISP_REG_BASE 0x00010000 #define IPU_DP_REG_BASE 0x00018000 #define IPU_IC_REG_BASE 0x00020000 #define IPU_IRT_REG_BASE 0x00028000 #define IPU_CSI0_REG_BASE 0x00030000 #define IPU_CSI1_REG_BASE 0x00038000 #define IPU_DI0_REG_BASE 0x00040000 #define IPU_DI1_REG_BASE 0x00048000 #define IPU_SMFC_REG_BASE 0x00050000 #define IPU_DC_REG_BASE 0x00058000 #define IPU_DMFC_REG_BASE 0x00060000 #define IPU_VDI_REG_BASE 0x00680000 #if defined(CONFIG_MX51) || defined(CONFIG_MX53) #define IPU_CPMEM_REG_BASE 0x01000000 #define IPU_LUT_REG_BASE 0x01020000 #define IPU_SRM_REG_BASE 0x01040000 #define IPU_TPM_REG_BASE 0x01060000 #define IPU_DC_TMPL_REG_BASE 0x01080000 #define IPU_ISP_TBPR_REG_BASE 0x010C0000 #elif defined(CONFIG_MX6) #define IPU_CPMEM_REG_BASE 0x00100000 #define IPU_LUT_REG_BASE 0x00120000 #define IPU_SRM_REG_BASE 0x00140000 #define IPU_TPM_REG_BASE 0x00160000 #define IPU_DC_TMPL_REG_BASE 0x00180000 #define IPU_ISP_TBPR_REG_BASE 0x001C0000 #endif #define IPU_CTRL_BASE_ADDR (IPU_SOC_BASE_ADDR + IPU_SOC_OFFSET) extern u32 *ipu_dc_tmpl_reg; #define DC_EVT_NF 0 #define DC_EVT_NL 1 #define DC_EVT_EOF 2 #define DC_EVT_NFIELD 3 #define DC_EVT_EOL 4 #define DC_EVT_EOFIELD 5 #define DC_EVT_NEW_ADDR 6 #define DC_EVT_NEW_CHAN 7 #define DC_EVT_NEW_DATA 8 #define DC_EVT_NEW_ADDR_W_0 0 #define DC_EVT_NEW_ADDR_W_1 1 #define DC_EVT_NEW_CHAN_W_0 2 #define DC_EVT_NEW_CHAN_W_1 3 #define DC_EVT_NEW_DATA_W_0 4 #define DC_EVT_NEW_DATA_W_1 5 #define DC_EVT_NEW_ADDR_R_0 6 #define DC_EVT_NEW_ADDR_R_1 7 #define DC_EVT_NEW_CHAN_R_0 8 #define DC_EVT_NEW_CHAN_R_1 9 #define DC_EVT_NEW_DATA_R_0 10 #define DC_EVT_NEW_DATA_R_1 11 /* Software reset for ipu */ #define SW_IPU_RST 8 enum { IPU_CONF_DP_EN = 0x00000020, IPU_CONF_DI0_EN = 0x00000040, IPU_CONF_DI1_EN = 0x00000080, IPU_CONF_DMFC_EN = 0x00000400, IPU_CONF_DC_EN = 0x00000200, DI0_COUNTER_RELEASE = 0x01000000, DI1_COUNTER_RELEASE = 0x02000000, DI_DW_GEN_ACCESS_SIZE_OFFSET = 24, DI_DW_GEN_COMPONENT_SIZE_OFFSET = 16, DI_GEN_DI_CLK_EXT = 0x100000, DI_GEN_POLARITY_1 = 0x00000001, DI_GEN_POLARITY_2 = 0x00000002, DI_GEN_POLARITY_3 = 0x00000004, DI_GEN_POLARITY_4 = 0x00000008, DI_GEN_POLARITY_5 = 0x00000010, DI_GEN_POLARITY_6 = 0x00000020, DI_GEN_POLARITY_7 = 0x00000040, DI_GEN_POLARITY_8 = 0x00000080, DI_GEN_POL_CLK = 0x20000, DI_POL_DRDY_DATA_POLARITY = 0x00000080, DI_POL_DRDY_POLARITY_15 = 0x00000010, DI_VSYNC_SEL_OFFSET = 13, DC_WR_CH_CONF_FIELD_MODE = 0x00000200, DC_WR_CH_CONF_PROG_TYPE_OFFSET = 5, DC_WR_CH_CONF_PROG_TYPE_MASK = 0x000000E0, DC_WR_CH_CONF_PROG_DI_ID = 0x00000004, DC_WR_CH_CONF_PROG_DISP_ID_OFFSET = 3, DC_WR_CH_CONF_PROG_DISP_ID_MASK = 0x00000018, DP_COM_CONF_FG_EN = 0x00000001, DP_COM_CONF_GWSEL = 0x00000002, DP_COM_CONF_GWAM = 0x00000004, DP_COM_CONF_GWCKE = 0x00000008, DP_COM_CONF_CSC_DEF_MASK = 0x00000300, DP_COM_CONF_CSC_DEF_OFFSET = 8, DP_COM_CONF_CSC_DEF_FG = 0x00000300, DP_COM_CONF_CSC_DEF_BG = 0x00000200, DP_COM_CONF_CSC_DEF_BOTH = 0x00000100, DP_COM_CONF_GAMMA_EN = 0x00001000, DP_COM_CONF_GAMMA_YUV_EN = 0x00002000, }; enum di_pins { DI_PIN11 = 0, DI_PIN12 = 1, DI_PIN13 = 2, DI_PIN14 = 3, DI_PIN15 = 4, DI_PIN16 = 5, DI_PIN17 = 6, DI_PIN_CS = 7, DI_PIN_SER_CLK = 0, DI_PIN_SER_RS = 1, }; enum di_sync_wave { DI_SYNC_NONE = -1, DI_SYNC_CLK = 0, DI_SYNC_INT_HSYNC = 1, DI_SYNC_HSYNC = 2, DI_SYNC_VSYNC = 3, DI_SYNC_DE = 5, }; struct ipu_cm { u32 conf; u32 sisg_ctrl0; u32 sisg_ctrl1; u32 sisg_set[6]; u32 sisg_clear[6]; u32 int_ctrl[15]; u32 sdma_event[10]; u32 srm_pri1; u32 srm_pri2; u32 fs_proc_flow[3]; u32 fs_disp_flow[2]; u32 skip; u32 disp_alt_conf; u32 disp_gen; u32 disp_alt[4]; u32 snoop; u32 mem_rst; u32 pm; u32 gpr; u32 reserved0[26]; u32 ch_db_mode_sel[2]; u32 reserved1[4]; u32 alt_ch_db_mode_sel[2]; u32 reserved2[2]; u32 ch_trb_mode_sel[2]; }; struct ipu_idmac { u32 conf; u32 ch_en[2]; u32 sep_alpha; u32 alt_sep_alpha; u32 ch_pri[2]; u32 wm_en[2]; u32 lock_en[2]; u32 sub_addr[5]; u32 bndm_en[2]; u32 sc_cord[2]; u32 reserved[44]; u32 ch_busy[2]; }; struct ipu_com_async { u32 com_conf_async; u32 graph_wind_ctrl_async; u32 fg_pos_async; u32 cur_pos_async; u32 cur_map_async; u32 gamma_c_async[8]; u32 gamma_s_async[4]; u32 dp_csca_async[4]; u32 dp_csc_async[2]; }; struct ipu_dp { u32 com_conf_sync; u32 graph_wind_ctrl_sync; u32 fg_pos_sync; u32 cur_pos_sync; u32 cur_map_sync; u32 gamma_c_sync[8]; u32 gamma_s_sync[4]; u32 csca_sync[4]; u32 csc_sync[2]; u32 cur_pos_alt; struct ipu_com_async async[2]; }; struct ipu_di { u32 general; u32 bs_clkgen0; u32 bs_clkgen1; u32 sw_gen0[9]; u32 sw_gen1[9]; u32 sync_as; u32 dw_gen[12]; u32 dw_set[48]; u32 stp_rep[4]; u32 stp_rep9; u32 ser_conf; u32 ssc; u32 pol; u32 aw0; u32 aw1; u32 scr_conf; u32 stat; }; struct ipu_stat { u32 int_stat[15]; u32 cur_buf[2]; u32 alt_cur_buf_0; u32 alt_cur_buf_1; u32 srm_stat; u32 proc_task_stat; u32 disp_task_stat; u32 triple_cur_buf[4]; u32 ch_buf0_rdy[2]; u32 ch_buf1_rdy[2]; u32 alt_ch_buf0_rdy[2]; u32 alt_ch_buf1_rdy[2]; u32 ch_buf2_rdy[2]; }; struct ipu_dc_ch { u32 wr_ch_conf; u32 wr_ch_addr; u32 rl[5]; }; struct ipu_dc { struct ipu_dc_ch dc_ch0_1_2[3]; u32 cmd_ch_conf_3; u32 cmd_ch_conf_4; struct ipu_dc_ch dc_ch5_6[2]; struct ipu_dc_ch dc_ch8; u32 rl6_ch_8; struct ipu_dc_ch dc_ch9; u32 rl6_ch_9; u32 gen; u32 disp_conf1[4]; u32 disp_conf2[4]; u32 di0_conf[2]; u32 di1_conf[2]; u32 dc_map_ptr[15]; u32 dc_map_val[12]; u32 udge[16]; u32 lla[2]; u32 r_lla[2]; u32 wr_ch_addr_5_alt; u32 stat; }; struct ipu_dmfc { u32 rd_chan; u32 wr_chan; u32 wr_chan_def; u32 dp_chan; u32 dp_chan_def; u32 general[2]; u32 ic_ctrl; u32 wr_chan_alt; u32 wr_chan_def_alt; u32 general1_alt; u32 stat; }; #define IPU_CM_REG ((struct ipu_cm *)(IPU_CTRL_BASE_ADDR + \ IPU_CM_REG_BASE)) #define IPU_CONF (&IPU_CM_REG->conf) #define IPU_SRM_PRI1 (&IPU_CM_REG->srm_pri1) #define IPU_SRM_PRI2 (&IPU_CM_REG->srm_pri2) #define IPU_FS_PROC_FLOW1 (&IPU_CM_REG->fs_proc_flow[0]) #define IPU_FS_PROC_FLOW2 (&IPU_CM_REG->fs_proc_flow[1]) #define IPU_FS_PROC_FLOW3 (&IPU_CM_REG->fs_proc_flow[2]) #define IPU_FS_DISP_FLOW1 (&IPU_CM_REG->fs_disp_flow[0]) #define IPU_DISP_GEN (&IPU_CM_REG->disp_gen) #define IPU_MEM_RST (&IPU_CM_REG->mem_rst) #define IPU_GPR (&IPU_CM_REG->gpr) #define IPU_CHA_DB_MODE_SEL(ch) (&IPU_CM_REG->ch_db_mode_sel[ch / 32]) #define IPU_STAT ((struct ipu_stat *)(IPU_CTRL_BASE_ADDR + \ IPU_STAT_REG_BASE)) #define IPU_CHA_CUR_BUF(ch) (&IPU_STAT->cur_buf[ch / 32]) #define IPU_CHA_BUF0_RDY(ch) (&IPU_STAT->ch_buf0_rdy[ch / 32]) #define IPU_CHA_BUF1_RDY(ch) (&IPU_STAT->ch_buf1_rdy[ch / 32]) #define IPU_INT_CTRL(n) (&IPU_CM_REG->int_ctrl[(n) - 1]) #define IDMAC_REG ((struct ipu_idmac *)(IPU_CTRL_BASE_ADDR + \ IPU_IDMAC_REG_BASE)) #define IDMAC_CONF (&IDMAC_REG->conf) #define IDMAC_CHA_EN(ch) (&IDMAC_REG->ch_en[ch / 32]) #define IDMAC_CHA_PRI(ch) (&IDMAC_REG->ch_pri[ch / 32]) #define DI_REG(di) ((struct ipu_di *)(IPU_CTRL_BASE_ADDR + \ ((di == 1) ? IPU_DI1_REG_BASE : \ IPU_DI0_REG_BASE))) #define DI_GENERAL(di) (&DI_REG(di)->general) #define DI_BS_CLKGEN0(di) (&DI_REG(di)->bs_clkgen0) #define DI_BS_CLKGEN1(di) (&DI_REG(di)->bs_clkgen1) #define DI_SW_GEN0(di, gen) (&DI_REG(di)->sw_gen0[gen - 1]) #define DI_SW_GEN1(di, gen) (&DI_REG(di)->sw_gen1[gen - 1]) #define DI_STP_REP(di, gen) (&DI_REG(di)->stp_rep[(gen - 1) / 2]) #define DI_SYNC_AS_GEN(di) (&DI_REG(di)->sync_as) #define DI_DW_GEN(di, gen) (&DI_REG(di)->dw_gen[gen]) #define DI_DW_SET(di, gen, set) (&DI_REG(di)->dw_set[gen + 12 * set]) #define DI_POL(di) (&DI_REG(di)->pol) #define DI_SCR_CONF(di) (&DI_REG(di)->scr_conf) #define DMFC_REG ((struct ipu_dmfc *)(IPU_CTRL_BASE_ADDR + \ IPU_DMFC_REG_BASE)) #define DMFC_WR_CHAN (&DMFC_REG->wr_chan) #define DMFC_WR_CHAN_DEF (&DMFC_REG->wr_chan_def) #define DMFC_DP_CHAN (&DMFC_REG->dp_chan) #define DMFC_DP_CHAN_DEF (&DMFC_REG->dp_chan_def) #define DMFC_GENERAL1 (&DMFC_REG->general[0]) #define DMFC_IC_CTRL (&DMFC_REG->ic_ctrl) #define DC_REG ((struct ipu_dc *)(IPU_CTRL_BASE_ADDR + \ IPU_DC_REG_BASE)) #define DC_MAP_CONF_PTR(n) (&DC_REG->dc_map_ptr[n / 2]) #define DC_MAP_CONF_VAL(n) (&DC_REG->dc_map_val[n / 2]) static inline struct ipu_dc_ch *dc_ch_offset(int ch) { switch (ch) { case 0: case 1: case 2: return &DC_REG->dc_ch0_1_2[ch]; case 5: case 6: return &DC_REG->dc_ch5_6[ch - 5]; case 8: return &DC_REG->dc_ch8; case 9: return &DC_REG->dc_ch9; default: printf("%s: invalid channel %d\n", __func__, ch); return NULL; } } #define DC_RL_CH(ch, evt) (&dc_ch_offset(ch)->rl[evt / 2]) #define DC_WR_CH_CONF(ch) (&dc_ch_offset(ch)->wr_ch_conf) #define DC_WR_CH_ADDR(ch) (&dc_ch_offset(ch)->wr_ch_addr) #define DC_WR_CH_CONF_1 DC_WR_CH_CONF(1) #define DC_WR_CH_CONF_5 DC_WR_CH_CONF(5) #define DC_GEN (&DC_REG->gen) #define DC_DISP_CONF2(disp) (&DC_REG->disp_conf2[disp]) #define DC_STAT (&DC_REG->stat) #define DP_SYNC 0 #define DP_ASYNC0 0x60 #define DP_ASYNC1 0xBC #define DP_REG ((struct ipu_dp *)(IPU_CTRL_BASE_ADDR + \ IPU_DP_REG_BASE)) #define DP_COM_CONF() (&DP_REG->com_conf_sync) #define DP_GRAPH_WIND_CTRL() (&DP_REG->graph_wind_ctrl_sync) #define DP_CSC_A_0() (&DP_REG->csca_sync[0]) #define DP_CSC_A_1() (&DP_REG->csca_sync[1]) #define DP_CSC_A_2() (&DP_REG->csca_sync[2]) #define DP_CSC_A_3() (&DP_REG->csca_sync[3]) #define DP_CSC_0() (&DP_REG->csc_sync[0]) #define DP_CSC_1() (&DP_REG->csc_sync[1]) /* DC template opcodes */ #define WROD(lf) (0x18 | (lf << 1)) #endif
a5fddacb8673a00ca39d7867b4bdb7c1244b3b67
cb9ab2e6b33f0befa99543c9501108641501500e
/IsoLib/vvc_base/src/vvc_demux_main.c
2e0232f61bd1290cbdeb9cad3681a57914477569
[]
no_license
MPEGGroup/isobmff
3401d5022d9bf0bfe3fc860c8fe53e83b66021d2
2a0e1a3690efb4553defca31caf347013f1eb9e1
refs/heads/master
2023-08-10T19:09:28.069852
2022-11-08T15:18:52
2022-11-08T15:18:52
118,715,054
101
37
null
2023-08-30T18:48:42
2018-01-24T05:07:44
C
UTF-8
C
false
false
10,927
c
vvc_demux_main.c
/* This software module was originally developed by Apple Computer, Inc. in the course of development of MPEG-4. This software module is an implementation of a part of one or more MPEG-4 tools as specified by MPEG-4. ISO/IEC gives users of MPEG-4 free license to this software module or modifications thereof for use in hardware or software products claiming conformance to MPEG-4. Those intending to use this software module in hardware or software products are advised that its use may infringe existing patents. The original developer of this software module and his/her company, the subsequent editors and their companies, and ISO/IEC have no liability for use of this software module or modifications thereof in an implementation. Copyright is not released for non MPEG-4 conforming products. Apple Computer, Inc. retains full right to use the code for its own purpose, assign or donate the code to a third party and to inhibit third parties from using the code for non MPEG-4 conforming products. This copyright notice must be included in all copies or derivative works. Copyright (c) 1999. */ /* Created for Nokia FAVS project by Tampere University of Technology */ #include <math.h> #include <string.h> #include "ISOMovies.h" #include "vvc_structures.h" #include "vvc.h" #include "vvc_tools.h" MP4_EXTERN(MP4Err) ISOGetVVCSampleDescriptionPS(MP4Handle sampleEntryH, MP4Handle ps, u32 where, u32 index); MP4_EXTERN(MP4Err) ISOGetGroupDescription(MP4Media media, u32 groupType, u32 index, MP4Handle description); MP4_EXTERN(MP4Err) MP4MediaTimeToSampleNum(MP4Media theMedia, u64 mediaTime, u32 *outSampleNum, u64 *outSampleCTS, u64 *outSampleDTS, s32 *outSampleDuration); MP4_EXTERN(ISOErr) ISOGetVVCSubpicSampleDescription(MP4Handle sampleEntryH, u32 *dataReferenceIndex, u32 *length_size); MP4Err writeVvccNalus(FILE *out, ISOHandle sampleEntryH) { MP4Err err = MP4NoErr; const char syncCode[] = "\0\0\0\1"; const char syncCode2[] = "\0\0\1"; ISOHandle spsHandle = NULL; ISOHandle vpsHandle = NULL; ISOHandle ppsHandle = NULL; ISOHandle opiHandle = NULL; ISOHandle dciHandle = NULL; ISOHandle apsHandle[10]; ISOHandle seiHandle[10]; u32 ui, num_nalu = 0, aps_count = 0, sei_count = 0; u32 sampleSize; s32 i; err = ISOGetVVCNaluNums(sampleEntryH, VVC_NALU_VPS, &num_nalu); if(err) goto bail; if(num_nalu) { err = ISONewHandle(1, &vpsHandle); if(err) goto bail; err = ISOGetVVCSampleDescriptionPS(sampleEntryH, vpsHandle, VVC_NALU_VPS, 1); if(err) goto bail; err = ISOGetHandleSize(vpsHandle, &sampleSize); if(err) goto bail; fwrite(&syncCode, 4, 1, out); fwrite(*vpsHandle, sampleSize, 1, out); } err = ISONewHandle(1, &spsHandle); err = ISONewHandle(1, &ppsHandle); if(err) goto bail; err = ISOGetVVCSampleDescriptionPS(sampleEntryH, spsHandle, VVC_NALU_SPS, 1); if(err) goto bail; err = ISOGetHandleSize(spsHandle, &sampleSize); if(err) goto bail; fwrite(&syncCode, 4, 1, out); fwrite(*spsHandle, sampleSize, 1, out); err = ISOGetVVCSampleDescriptionPS(sampleEntryH, ppsHandle, VVC_NALU_PPS, 1); if(err) goto bail; err = ISOGetHandleSize(ppsHandle, &sampleSize); if(err) goto bail; fwrite(&syncCode, 4, 1, out); fwrite(*ppsHandle, sampleSize, 1, out); err = ISOGetVVCNaluNums(sampleEntryH, VVC_NALU_OPI, &num_nalu); if(err) goto bail; if(num_nalu) { err = ISONewHandle(1, &opiHandle); if(err) goto bail; err = ISOGetVVCSampleDescriptionPS(sampleEntryH, opiHandle, VVC_NALU_OPI, 1); if(err) goto bail; err = ISOGetHandleSize(opiHandle, &sampleSize); if(err) goto bail; fwrite(&syncCode2, 3, 1, out); fwrite(*opiHandle, sampleSize, 1, out); } err = ISOGetVVCNaluNums(sampleEntryH, VVC_NALU_DCI, &num_nalu); if(err) goto bail; if(num_nalu) { err = ISONewHandle(1, &dciHandle); if(err) goto bail; err = ISOGetVVCSampleDescriptionPS(sampleEntryH, dciHandle, VVC_NALU_DCI, 1); if(err) goto bail; err = ISOGetHandleSize(dciHandle, &sampleSize); if(err) goto bail; fwrite(&syncCode, 4, 1, out); fwrite(&syncCode2, 3, 1, out); fwrite(*dciHandle, sampleSize, 1, out); } err = ISOGetVVCNaluNums(sampleEntryH, VVC_NALU_PREFIX_SEI, &sei_count); if(err) goto bail; for(ui = 0; ui < sei_count; ui++) { err = ISONewHandle(1, &seiHandle[ui]); if(err) goto bail; err = ISOGetVVCSampleDescriptionPS(sampleEntryH, seiHandle[ui], VVC_NALU_PREFIX_SEI, ui + 1); if(err) goto bail; } if(sei_count) { for(ui = 0; ui < sei_count; ui++) { err = ISOGetHandleSize(seiHandle[ui], &sampleSize); if(err) goto bail; fwrite(&syncCode2, 3, 1, out); fwrite(*seiHandle[ui], sampleSize, 1, out); } } err = ISOGetVVCNaluNums(sampleEntryH, VVC_NALU_PREFIX_APS, &aps_count); if(err) goto bail; for(ui = 0; ui < aps_count; ui++) { err = ISONewHandle(1, &apsHandle[ui]); if(err) goto bail; err = ISOGetVVCSampleDescriptionPS(sampleEntryH, apsHandle[ui], VVC_NALU_PREFIX_APS, ui + 1); if(err) goto bail; } if(aps_count) { for(ui = 0; ui < aps_count; ui++) { err = ISOGetHandleSize(apsHandle[ui], &sampleSize); if(err) goto bail; fwrite(&syncCode, 4, 1, out); fwrite(*apsHandle[ui], sampleSize, 1, out); } } err = ISODisposeHandle(spsHandle); err = ISODisposeHandle(ppsHandle); if(vpsHandle) err = ISODisposeHandle(vpsHandle); if(dciHandle) err = ISODisposeHandle(dciHandle); if(opiHandle) err = ISODisposeHandle(opiHandle); for(i = aps_count - 1; i >= 0; i--) err = ISODisposeHandle(apsHandle[i]); for(i = sei_count - 1; i >= 0; i--) err = ISODisposeHandle(seiHandle[i]); bail: return err; } ISOErr playMyMovie(struct ParamStruct *parameters, char *filename) { s32 i; u32 trackNumber; ISOErr err; u32 handlerType; ISOMovie moov; ISOTrack trak; u32 trackCount = 0; u32 trackGroups = 0; u32 trackGroupID = 0; u32 mediaTimeScale = 0; u32 totalSamples = 0; u64 duration = 0; ISOMedia media; ISOTrackReader reader; ISOHandle sampleH; ISOHandle decoderConfigH; s32 alst_start = -1; const char syncCodeZeroByte[] = "\0\0\0\1"; const char syncCode[] = "\0\0\1"; char *outSampleName = malloc(128); ISOHandle sampleEntryH; err = ISONewHandle(1, &sampleEntryH); if (err) goto bail; err = ISOOpenMovieFile(&moov, filename, MP4OpenMovieDebug); if(err) goto bail; err = MP4GetMovieTrackCount(moov, &trackCount); if (err) goto bail; printf("trackCount: %d\r\n", trackCount); /* Loop all the tracks in the container, starting from 1 */ for (trackNumber = 1; trackNumber < trackCount + 1; trackNumber++) { FILE *out; MP4GenericAtom subs = NULL; u32 sampleSize; u32 alst_target = 0; u32 pics_rasl_skipped = 0; u32 pics_start_skipped = 0; u32 pics_written = 0; sprintf(outSampleName, "out_track_%d.266", trackNumber); out = fopen(outSampleName, "wb"); printf("Track ID %d\r\n", trackNumber); err = ISOGetMovieIndTrack(moov, trackNumber, &trak); /* Check if track group box exists and print the group if found */ MP4_EXTERN(MP4Err) MP4GetTrackGroup(MP4Track theTrack, u32 groupType, u32 *outGroupId); if (MP4GetTrackGroup(trak, MP4_FOUR_CHAR_CODE('a', 'l', 't', 'e'), &trackGroupID) == MP4NoErr) { printf("Found trackGroup (Group ID: %d)\r\n", trackGroupID); } u32 refcount = 0; MP4GetTrackReferenceCount(trak, MP4_FOUR_CHAR_CODE('s', 'u', 'b', 'p'), &refcount); MP4GetTrackReferenceCount(trak, MP4_FOUR_CHAR_CODE('r', 'e', 'c', 'r'), &refcount); // get track reference ISOTrack reftrak; MP4GetTrackReference(trak, MP4_FOUR_CHAR_CODE('s', 'u', 'b', 'p'), 1, &reftrak); MP4GetTrackReference(trak, MP4_FOUR_CHAR_CODE('r', 'e', 'c', 'r'), 1, &reftrak); err = ISOGetTrackMedia(trak, &media); if (err) goto bail; err = ISOGetMediaHandlerDescription(media, &handlerType, NULL); if (err) goto bail; //err = ISONewHandle(0, &decoderConfigH); if (err) goto bail; err = ISOCreateTrackReader(trak, &reader); if (err) goto bail; err = ISONewHandle(0, &sampleH); if (err) goto bail; /* Get sample description from the trak */ err = MP4TrackReaderGetCurrentSampleDescription(reader, sampleEntryH); if (err) goto bail; // only call when first track? u32 configsize; MP4GetHandleSize(sampleEntryH, &configsize); err = ISONewHandle(configsize, &decoderConfigH); if(err) goto bail; memcpy((*decoderConfigH), (*sampleEntryH), configsize); MP4GetHandleSize(decoderConfigH, &configsize); err = writeVvccNalus(out, sampleEntryH); if(err) goto bail; ISOGetMediaTimeScale(media, &mediaTimeScale); ISOGetMediaSampleCount(media, &totalSamples); ISOGetMediaDuration(media, &duration); printf("numberofSamples %u, duration: %llu\r\n", totalSamples, duration); for(i = 1;; i++) { /* play every frame */ u32 unitSize; s32 cts; s32 dts; u32 sampleFlags; static u32 roll_count = 0; err = MP4TrackReaderGetNextAccessUnit(reader, sampleH, &unitSize, &sampleFlags, &cts, &dts); if(err) { if(err == ISOEOF) err = ISONoErr; break; } u32 sampleSize = 0; u32 sampleOffsetBytes = 0; u8 nalType = 0; MP4GetHandleSize(sampleH, &sampleSize); while(sampleOffsetBytes < sampleSize) { u32 boxSize = GET32(*sampleH + sampleOffsetBytes); u32 byteoffset = 4; // sample nalType = ((u8 *)(*sampleH + sampleOffsetBytes + 4))[1] >> 3; printf("Out NAL type: %d\r\n", nalType); fwrite(&syncCode[0], 3, 1, out); fwrite(*sampleH + sampleOffsetBytes + byteoffset, boxSize, 1, out); sampleOffsetBytes += boxSize + byteoffset; } pics_written++; } fclose(out); err = ISODisposeHandle(sampleH); //err = ISODisposeHandle(decoderConfigH); err = ISODisposeTrackReader(reader); } free(outSampleName); err = ISODisposeHandle(decoderConfigH); err = ISODisposeMovie(moov); bail: return err; } int cleanParameters(struct ParamStruct *parameters) { u32 i; if (parameters->inputCount) { for (i = 0; i < parameters->inputCount; i++) { free(parameters->inputs[i]); } free(parameters->inputs); } free(parameters->output); if (parameters->trackGroupCount) { for (i = 0; i < parameters->trackGroupCount; i++) { free(parameters->trackGroups[i]); } free(parameters->trackGroups); } return 1; } int main(int argc, char* argv[]) { struct ParamStruct parameters; memset(&parameters, 0, sizeof(struct ParamStruct)); parseInput(argc, argv, &parameters); /* We need inputs */ if (!parameters.inputCount) { fprintf(stderr, "Usage: vvc_demuxer -i <inputFile>\r\n"); fprintf(stderr, " --input, -i <filename>: Input file\r\n"); //fprintf(stderr, " --seek,-s <frame> seek to frame\r\n"); exit(1); } playMyMovie(&parameters, parameters.inputs[0]); cleanParameters(&parameters); return 1; }
8109bf5cd7f465a8f8d0513e2e304f3026e48e37
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/libc/nt/enum/rdw.h
d2afcdb23360b7b0afaaf4c26a48d3174b02b47c
[ "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
574
h
rdw.h
#ifndef COSMOPOLITAN_LIBC_NT_ENUM_RDW_H_ #define COSMOPOLITAN_LIBC_NT_ENUM_RDW_H_ #define kNtRdwInvalidate 0x0001 #define kNtRdwInternalpaint 0x0002 #define kNtRdwErase 0x0004 #define kNtRdwValidate 0x0008 #define kNtRdwNointernalpaint 0x0010 #define kNtRdwNoerase 0x0020 #define kNtRdwNochildren 0x0040 #define kNtRdwAllchildren 0x0080 #define kNtRdwUpdatenow 0x0100 #define kNtRdwErasenow 0x0200 #define kNtRdwFrame 0x0400 #define kNtRdwNoframe 0x0800 #endif /* COSMOPOLITAN_LIBC_NT_ENUM_RDW_H_ */
724b511cd7799e745d2ab3e1ed2cc6c3d1da2a0a
7f6c235b0598353549959c18f69eefd20b766907
/libsrc/target/zx/fcntl/plus3/opendir.c
f385287ab9dbeb4c20f6cb515b9bfcb29883a342
[ "ClArtistic" ]
permissive
z88dk/z88dk
46dfd4905f36d99333173cadd0a660839befc9f0
8b07f37cc43c5d9ffe69b563c80763491d8faff7
refs/heads/master
2023-09-04T19:29:49.254958
2023-09-03T20:51:24
2023-09-03T20:51:24
54,035,569
820
263
NOASSERTION
2023-09-05T11:09:04
2016-03-16T13:48:16
Assembly
UTF-8
C
false
false
2,301
c
opendir.c
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <dirent.h> #define DIR_CACHE_SIZE 4 // This is never exposed out of the library struct DIR { char wildcard[17]; uint8_t buf_posn; uint8_t buf_available; uint8_t count; uint8_t buffer[DIR_CACHE_SIZE+1][13]; }; static int getmore(DIR *dir); static int readblock(void *ptr) __z88dk_fastcall __naked; const char wildcard[] = "*.*\xff"; extern DIR mydir; DIR * opendir (const char *dirname) { DIR *dir = &mydir; strcpy(dir->wildcard, dirname); strcat(dir->wildcard, wildcard); memset(dir->buffer, 0, sizeof(dir->buffer)); dir->count = 0; dir->buf_available = DIR_CACHE_SIZE; // Fake a number getmore(dir); return dir; } struct dirent *readdir(DIR *dir) { static struct dirent dirent; again: if ( dir->buf_posn <= dir->buf_available ) { // Populate the dirent uint8_t *entry = (uint8_t *)dir->buffer[dir->buf_posn++]; uint8_t *ptr = (uint8_t *)&dirent.d_name[0]; int i; for ( i = 0; i < 11; i++ ) { uint8_t c = entry[i]; if ( c == ' ' ) continue; if ( i == 8 ) *ptr++ = '.'; *ptr++ = c & 127; } *ptr = 0; dirent.d_ino = dir->count++; return &dirent; } if ( getmore(dir) == 0 ) return NULL; goto again; } int closedir(DIR *dir) { return 0; } static int getmore(DIR *dir) { // Copy the last directory entry into the first position if ( dir->buf_available != DIR_CACHE_SIZE ) return 0; memcpy(&dir->buffer[0], &dir->buffer[DIR_CACHE_SIZE - 1], 13); dir->buf_posn = 1; dir->buf_available = readblock(dir); return dir->buf_available; } static int readblock(void *ptr) __z88dk_fastcall __naked { #asm INCLUDE "target/zx/def/p3dos.def" EXTERN dodos getmore: ; hl = DIR push ix ;save callers ld d,h ;de = filename ld e,l ld bc,20 add hl,bc ;Points to buffer ex de,hl ld b,DIR_CACHE_SIZE + 1 ; number of entries in the buffer ld c,1 ; include system files ld ix, DOS_CATALOG call dodos pop ix ld hl,0 ret nc ;Dos error ld l,b dec l ret SECTION bss_driver _mydir: defs 85 #endasm }