max_stars_repo_path
stringlengths
5
126
max_stars_repo_name
stringlengths
8
65
max_stars_count
float64
0
34.4k
id
stringlengths
5
7
content
stringlengths
58
511k
score
float64
0.38
1
label
stringclasses
3 values
linsched-linsched-alpha/drivers/usb/serial/iuu_phoenix.c
usenixatc2021/SoftRefresh_Scheduling
0
1626672
/* * Infinity Unlimited USB Phoenix driver * * Copyright (C) 2010 <NAME> (<EMAIL>) * Copyright (C) 2007 <NAME> (<EMAIL>) * * Original code taken from iuutool (Copyright (C) 2006 <NAME>) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * And tested with help of WB Electronics * */ #include <linux/kernel.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <linux/serial.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/spinlock.h> #include <linux/uaccess.h> #include <linux/usb.h> #include <linux/usb/serial.h> #include "iuu_phoenix.h" #include <linux/random.h> #ifdef CONFIG_USB_SERIAL_DEBUG static bool debug = 1; #else static bool debug; #endif /* * Version Information */ #define DRIVER_VERSION "v0.12" #define DRIVER_DESC "Infinity USB Unlimited Phoenix driver" static const struct usb_device_id id_table[] = { {USB_DEVICE(IUU_USB_VENDOR_ID, IUU_USB_PRODUCT_ID)}, {} /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, id_table); static struct usb_driver iuu_driver = { .name = "iuu_phoenix", .probe = usb_serial_probe, .disconnect = usb_serial_disconnect, .id_table = id_table, .no_dynamic_id = 1, }; /* turbo parameter */ static int boost = 100; static int clockmode = 1; static int cdmode = 1; static int iuu_cardin; static int iuu_cardout; static bool xmas; static int vcc_default = 5; static void read_rxcmd_callback(struct urb *urb); struct iuu_private { spinlock_t lock; /* store irq state */ wait_queue_head_t delta_msr_wait; u8 line_status; int tiostatus; /* store IUART SIGNAL for tiocmget call */ u8 reset; /* if 1 reset is needed */ int poll; /* number of poll */ u8 *writebuf; /* buffer for writing to device */ int writelen; /* num of byte to write to device */ u8 *buf; /* used for initialize speed */ u8 *dbgbuf; /* debug buffer */ u8 len; int vcc; /* vcc (either 3 or 5 V) */ u32 baud; u32 boost; u32 clk; }; static void iuu_free_buf(struct iuu_private *priv) { kfree(priv->buf); kfree(priv->dbgbuf); kfree(priv->writebuf); } static int iuu_alloc_buf(struct iuu_private *priv) { priv->buf = kzalloc(256, GFP_KERNEL); priv->dbgbuf = kzalloc(256, GFP_KERNEL); priv->writebuf = kzalloc(256, GFP_KERNEL); if (!priv->buf || !priv->dbgbuf || !priv->writebuf) { iuu_free_buf(priv); dbg("%s problem allocation buffer", __func__); return -ENOMEM; } dbg("%s - Privates buffers allocation success", __func__); return 0; } static int iuu_startup(struct usb_serial *serial) { struct iuu_private *priv; priv = kzalloc(sizeof(struct iuu_private), GFP_KERNEL); dbg("%s- priv allocation success", __func__); if (!priv) return -ENOMEM; if (iuu_alloc_buf(priv)) { kfree(priv); return -ENOMEM; } priv->vcc = vcc_default; spin_lock_init(&priv->lock); init_waitqueue_head(&priv->delta_msr_wait); usb_set_serial_port_data(serial->port[0], priv); return 0; } /* Release function */ static void iuu_release(struct usb_serial *serial) { struct usb_serial_port *port = serial->port[0]; struct iuu_private *priv = usb_get_serial_port_data(port); if (!port) return; dbg("%s", __func__); if (priv) { iuu_free_buf(priv); dbg("%s - I will free all", __func__); usb_set_serial_port_data(port, NULL); dbg("%s - priv is not anymore in port structure", __func__); kfree(priv); dbg("%s priv is now kfree", __func__); } } static int iuu_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) { struct usb_serial_port *port = tty->driver_data; struct iuu_private *priv = usb_get_serial_port_data(port); unsigned long flags; /* FIXME: locking on tiomstatus */ dbg("%s (%d) msg : SET = 0x%04x, CLEAR = 0x%04x ", __func__, port->number, set, clear); spin_lock_irqsave(&priv->lock, flags); if ((set & TIOCM_RTS) && !(priv->tiostatus == TIOCM_RTS)) { dbg("%s TIOCMSET RESET called !!!", __func__); priv->reset = 1; } if (set & TIOCM_RTS) priv->tiostatus = TIOCM_RTS; spin_unlock_irqrestore(&priv->lock, flags); return 0; } /* This is used to provide a carrier detect mechanism * When a card is present, the response is 0x00 * When no card , the reader respond with TIOCM_CD * This is known as CD autodetect mechanism */ static int iuu_tiocmget(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct iuu_private *priv = usb_get_serial_port_data(port); unsigned long flags; int rc; spin_lock_irqsave(&priv->lock, flags); rc = priv->tiostatus; spin_unlock_irqrestore(&priv->lock, flags); return rc; } static void iuu_rxcmd(struct urb *urb) { struct usb_serial_port *port = urb->context; int result; int status = urb->status; dbg("%s - enter", __func__); if (status) { dbg("%s - status = %d", __func__, status); /* error stop all */ return; } memset(port->write_urb->transfer_buffer, IUU_UART_RX, 1); usb_fill_bulk_urb(port->write_urb, port->serial->dev, usb_sndbulkpipe(port->serial->dev, port->bulk_out_endpointAddress), port->write_urb->transfer_buffer, 1, read_rxcmd_callback, port); result = usb_submit_urb(port->write_urb, GFP_ATOMIC); } static int iuu_reset(struct usb_serial_port *port, u8 wt) { struct iuu_private *priv = usb_get_serial_port_data(port); int result; char *buf_ptr = port->write_urb->transfer_buffer; dbg("%s - enter", __func__); /* Prepare the reset sequence */ *buf_ptr++ = IUU_RST_SET; *buf_ptr++ = IUU_DELAY_MS; *buf_ptr++ = wt; *buf_ptr = IUU_RST_CLEAR; /* send the sequence */ usb_fill_bulk_urb(port->write_urb, port->serial->dev, usb_sndbulkpipe(port->serial->dev, port->bulk_out_endpointAddress), port->write_urb->transfer_buffer, 4, iuu_rxcmd, port); result = usb_submit_urb(port->write_urb, GFP_ATOMIC); priv->reset = 0; return result; } /* Status Function * Return value is * 0x00 = no card * 0x01 = smartcard * 0x02 = sim card */ static void iuu_update_status_callback(struct urb *urb) { struct usb_serial_port *port = urb->context; struct iuu_private *priv = usb_get_serial_port_data(port); u8 *st; int status = urb->status; dbg("%s - enter", __func__); if (status) { dbg("%s - status = %d", __func__, status); /* error stop all */ return; } st = urb->transfer_buffer; dbg("%s - enter", __func__); if (urb->actual_length == 1) { switch (st[0]) { case 0x1: priv->tiostatus = iuu_cardout; break; case 0x0: priv->tiostatus = iuu_cardin; break; default: priv->tiostatus = iuu_cardin; } } iuu_rxcmd(urb); } static void iuu_status_callback(struct urb *urb) { struct usb_serial_port *port = urb->context; int result; int status = urb->status; dbg("%s - status = %d", __func__, status); usb_fill_bulk_urb(port->read_urb, port->serial->dev, usb_rcvbulkpipe(port->serial->dev, port->bulk_in_endpointAddress), port->read_urb->transfer_buffer, 256, iuu_update_status_callback, port); result = usb_submit_urb(port->read_urb, GFP_ATOMIC); } static int iuu_status(struct usb_serial_port *port) { int result; dbg("%s - enter", __func__); memset(port->write_urb->transfer_buffer, IUU_GET_STATE_REGISTER, 1); usb_fill_bulk_urb(port->write_urb, port->serial->dev, usb_sndbulkpipe(port->serial->dev, port->bulk_out_endpointAddress), port->write_urb->transfer_buffer, 1, iuu_status_callback, port); result = usb_submit_urb(port->write_urb, GFP_ATOMIC); return result; } static int bulk_immediate(struct usb_serial_port *port, u8 *buf, u8 count) { int status; struct usb_serial *serial = port->serial; int actual = 0; dbg("%s - enter", __func__); /* send the data out the bulk port */ status = usb_bulk_msg(serial->dev, usb_sndbulkpipe(serial->dev, port->bulk_out_endpointAddress), buf, count, &actual, HZ * 1); if (status != IUU_OPERATION_OK) dbg("%s - error = %2x", __func__, status); else dbg("%s - write OK !", __func__); return status; } static int read_immediate(struct usb_serial_port *port, u8 *buf, u8 count) { int status; struct usb_serial *serial = port->serial; int actual = 0; dbg("%s - enter", __func__); /* send the data out the bulk port */ status = usb_bulk_msg(serial->dev, usb_rcvbulkpipe(serial->dev, port->bulk_in_endpointAddress), buf, count, &actual, HZ * 1); if (status != IUU_OPERATION_OK) dbg("%s - error = %2x", __func__, status); else dbg("%s - read OK !", __func__); return status; } static int iuu_led(struct usb_serial_port *port, unsigned int R, unsigned int G, unsigned int B, u8 f) { int status; u8 *buf; buf = kmalloc(8, GFP_KERNEL); if (!buf) return -ENOMEM; dbg("%s - enter", __func__); buf[0] = IUU_SET_LED; buf[1] = R & 0xFF; buf[2] = (R >> 8) & 0xFF; buf[3] = G & 0xFF; buf[4] = (G >> 8) & 0xFF; buf[5] = B & 0xFF; buf[6] = (B >> 8) & 0xFF; buf[7] = f; status = bulk_immediate(port, buf, 8); kfree(buf); if (status != IUU_OPERATION_OK) dbg("%s - led error status = %2x", __func__, status); else dbg("%s - led OK !", __func__); return IUU_OPERATION_OK; } static void iuu_rgbf_fill_buffer(u8 *buf, u8 r1, u8 r2, u8 g1, u8 g2, u8 b1, u8 b2, u8 freq) { *buf++ = IUU_SET_LED; *buf++ = r1; *buf++ = r2; *buf++ = g1; *buf++ = g2; *buf++ = b1; *buf++ = b2; *buf = freq; } static void iuu_led_activity_on(struct urb *urb) { struct usb_serial_port *port = urb->context; int result; char *buf_ptr = port->write_urb->transfer_buffer; *buf_ptr++ = IUU_SET_LED; if (xmas == 1) { get_random_bytes(buf_ptr, 6); *(buf_ptr+7) = 1; } else { iuu_rgbf_fill_buffer(buf_ptr, 255, 255, 0, 0, 0, 0, 255); } usb_fill_bulk_urb(port->write_urb, port->serial->dev, usb_sndbulkpipe(port->serial->dev, port->bulk_out_endpointAddress), port->write_urb->transfer_buffer, 8 , iuu_rxcmd, port); result = usb_submit_urb(port->write_urb, GFP_ATOMIC); } static void iuu_led_activity_off(struct urb *urb) { struct usb_serial_port *port = urb->context; int result; char *buf_ptr = port->write_urb->transfer_buffer; if (xmas == 1) { iuu_rxcmd(urb); return; } else { *buf_ptr++ = IUU_SET_LED; iuu_rgbf_fill_buffer(buf_ptr, 0, 0, 255, 255, 0, 0, 255); } usb_fill_bulk_urb(port->write_urb, port->serial->dev, usb_sndbulkpipe(port->serial->dev, port->bulk_out_endpointAddress), port->write_urb->transfer_buffer, 8 , iuu_rxcmd, port); result = usb_submit_urb(port->write_urb, GFP_ATOMIC); } static int iuu_clk(struct usb_serial_port *port, int dwFrq) { int status; struct iuu_private *priv = usb_get_serial_port_data(port); int Count = 0; u8 FrqGenAdr = 0x69; u8 DIV = 0; /* 8bit */ u8 XDRV = 0; /* 8bit */ u8 PUMP = 0; /* 3bit */ u8 PBmsb = 0; /* 2bit */ u8 PBlsb = 0; /* 8bit */ u8 PO = 0; /* 1bit */ u8 Q = 0; /* 7bit */ /* 24bit = 3bytes */ unsigned int P = 0; unsigned int P2 = 0; int frq = (int)dwFrq; dbg("%s - enter", __func__); if (frq == 0) { priv->buf[Count++] = IUU_UART_WRITE_I2C; priv->buf[Count++] = FrqGenAdr << 1; priv->buf[Count++] = 0x09; priv->buf[Count++] = 0x00; status = bulk_immediate(port, (u8 *) priv->buf, Count); if (status != 0) { dbg("%s - write error ", __func__); return status; } } else if (frq == 3579000) { DIV = 100; P = 1193; Q = 40; XDRV = 0; } else if (frq == 3680000) { DIV = 105; P = 161; Q = 5; XDRV = 0; } else if (frq == 6000000) { DIV = 66; P = 66; Q = 2; XDRV = 0x28; } else { unsigned int result = 0; unsigned int tmp = 0; unsigned int check; unsigned int check2; char found = 0x00; unsigned int lQ = 2; unsigned int lP = 2055; unsigned int lDiv = 4; for (lQ = 2; lQ <= 47 && !found; lQ++) for (lP = 2055; lP >= 8 && !found; lP--) for (lDiv = 4; lDiv <= 127 && !found; lDiv++) { tmp = (12000000 / lDiv) * (lP / lQ); if (abs((int)(tmp - frq)) < abs((int)(frq - result))) { check2 = (12000000 / lQ); if (check2 < 250000) continue; check = (12000000 / lQ) * lP; if (check > 400000000) continue; if (check < 100000000) continue; if (lDiv < 4 || lDiv > 127) continue; result = tmp; P = lP; DIV = lDiv; Q = lQ; if (result == frq) found = 0x01; } } } P2 = ((P - PO) / 2) - 4; DIV = DIV; PUMP = 0x04; PBmsb = (P2 >> 8 & 0x03); PBlsb = P2 & 0xFF; PO = (P >> 10) & 0x01; Q = Q - 2; priv->buf[Count++] = IUU_UART_WRITE_I2C; /* 0x4C */ priv->buf[Count++] = FrqGenAdr << 1; priv->buf[Count++] = 0x09; priv->buf[Count++] = 0x20; /* Adr = 0x09 */ priv->buf[Count++] = IUU_UART_WRITE_I2C; /* 0x4C */ priv->buf[Count++] = FrqGenAdr << 1; priv->buf[Count++] = 0x0C; priv->buf[Count++] = DIV; /* Adr = 0x0C */ priv->buf[Count++] = IUU_UART_WRITE_I2C; /* 0x4C */ priv->buf[Count++] = FrqGenAdr << 1; priv->buf[Count++] = 0x12; priv->buf[Count++] = XDRV; /* Adr = 0x12 */ priv->buf[Count++] = IUU_UART_WRITE_I2C; /* 0x4C */ priv->buf[Count++] = FrqGenAdr << 1; priv->buf[Count++] = 0x13; priv->buf[Count++] = 0x6B; /* Adr = 0x13 */ priv->buf[Count++] = IUU_UART_WRITE_I2C; /* 0x4C */ priv->buf[Count++] = FrqGenAdr << 1; priv->buf[Count++] = 0x40; priv->buf[Count++] = (0xC0 | ((PUMP & 0x07) << 2)) | (PBmsb & 0x03); /* Adr = 0x40 */ priv->buf[Count++] = IUU_UART_WRITE_I2C; /* 0x4C */ priv->buf[Count++] = FrqGenAdr << 1; priv->buf[Count++] = 0x41; priv->buf[Count++] = PBlsb; /* Adr = 0x41 */ priv->buf[Count++] = IUU_UART_WRITE_I2C; /* 0x4C */ priv->buf[Count++] = FrqGenAdr << 1; priv->buf[Count++] = 0x42; priv->buf[Count++] = Q | (((PO & 0x01) << 7)); /* Adr = 0x42 */ priv->buf[Count++] = IUU_UART_WRITE_I2C; /* 0x4C */ priv->buf[Count++] = FrqGenAdr << 1; priv->buf[Count++] = 0x44; priv->buf[Count++] = (char)0xFF; /* Adr = 0x44 */ priv->buf[Count++] = IUU_UART_WRITE_I2C; /* 0x4C */ priv->buf[Count++] = FrqGenAdr << 1; priv->buf[Count++] = 0x45; priv->buf[Count++] = (char)0xFE; /* Adr = 0x45 */ priv->buf[Count++] = IUU_UART_WRITE_I2C; /* 0x4C */ priv->buf[Count++] = FrqGenAdr << 1; priv->buf[Count++] = 0x46; priv->buf[Count++] = 0x7F; /* Adr = 0x46 */ priv->buf[Count++] = IUU_UART_WRITE_I2C; /* 0x4C */ priv->buf[Count++] = FrqGenAdr << 1; priv->buf[Count++] = 0x47; priv->buf[Count++] = (char)0x84; /* Adr = 0x47 */ status = bulk_immediate(port, (u8 *) priv->buf, Count); if (status != IUU_OPERATION_OK) dbg("%s - write error ", __func__); return status; } static int iuu_uart_flush(struct usb_serial_port *port) { int i; int status; u8 rxcmd = IUU_UART_RX; struct iuu_private *priv = usb_get_serial_port_data(port); dbg("%s - enter", __func__); if (iuu_led(port, 0xF000, 0, 0, 0xFF) < 0) return -EIO; for (i = 0; i < 2; i++) { status = bulk_immediate(port, &rxcmd, 1); if (status != IUU_OPERATION_OK) { dbg("%s - uart_flush_write error", __func__); return status; } status = read_immediate(port, &priv->len, 1); if (status != IUU_OPERATION_OK) { dbg("%s - uart_flush_read error", __func__); return status; } if (priv->len > 0) { dbg("%s - uart_flush datalen is : %i ", __func__, priv->len); status = read_immediate(port, priv->buf, priv->len); if (status != IUU_OPERATION_OK) { dbg("%s - uart_flush_read error", __func__); return status; } } } dbg("%s - uart_flush_read OK!", __func__); iuu_led(port, 0, 0xF000, 0, 0xFF); return status; } static void read_buf_callback(struct urb *urb) { struct usb_serial_port *port = urb->context; unsigned char *data = urb->transfer_buffer; struct tty_struct *tty; int status = urb->status; dbg("%s - status = %d", __func__, status); if (status) { if (status == -EPROTO) { /* reschedule needed */ } return; } dbg("%s - %i chars to write", __func__, urb->actual_length); tty = tty_port_tty_get(&port->port); if (data == NULL) dbg("%s - data is NULL !!!", __func__); if (tty && urb->actual_length && data) { tty_insert_flip_string(tty, data, urb->actual_length); tty_flip_buffer_push(tty); } tty_kref_put(tty); iuu_led_activity_on(urb); } static int iuu_bulk_write(struct usb_serial_port *port) { struct iuu_private *priv = usb_get_serial_port_data(port); unsigned long flags; int result; int i; int buf_len; char *buf_ptr = port->write_urb->transfer_buffer; dbg("%s - enter", __func__); spin_lock_irqsave(&priv->lock, flags); *buf_ptr++ = IUU_UART_ESC; *buf_ptr++ = IUU_UART_TX; *buf_ptr++ = priv->writelen; memcpy(buf_ptr, priv->writebuf, priv->writelen); buf_len = priv->writelen; priv->writelen = 0; spin_unlock_irqrestore(&priv->lock, flags); if (debug == 1) { for (i = 0; i < buf_len; i++) sprintf(priv->dbgbuf + i*2 , "%02X", priv->writebuf[i]); priv->dbgbuf[buf_len+i*2] = 0; dbg("%s - writing %i chars : %s", __func__, buf_len, priv->dbgbuf); } usb_fill_bulk_urb(port->write_urb, port->serial->dev, usb_sndbulkpipe(port->serial->dev, port->bulk_out_endpointAddress), port->write_urb->transfer_buffer, buf_len + 3, iuu_rxcmd, port); result = usb_submit_urb(port->write_urb, GFP_ATOMIC); usb_serial_port_softint(port); return result; } static int iuu_read_buf(struct usb_serial_port *port, int len) { int result; dbg("%s - enter", __func__); usb_fill_bulk_urb(port->read_urb, port->serial->dev, usb_rcvbulkpipe(port->serial->dev, port->bulk_in_endpointAddress), port->read_urb->transfer_buffer, len, read_buf_callback, port); result = usb_submit_urb(port->read_urb, GFP_ATOMIC); return result; } static void iuu_uart_read_callback(struct urb *urb) { struct usb_serial_port *port = urb->context; struct iuu_private *priv = usb_get_serial_port_data(port); unsigned long flags; int status = urb->status; int error = 0; int len = 0; unsigned char *data = urb->transfer_buffer; priv->poll++; dbg("%s - enter", __func__); if (status) { dbg("%s - status = %d", __func__, status); /* error stop all */ return; } if (data == NULL) dbg("%s - data is NULL !!!", __func__); if (urb->actual_length == 1 && data != NULL) len = (int) data[0]; if (urb->actual_length > 1) { dbg("%s - urb->actual_length = %i", __func__, urb->actual_length); error = 1; return; } /* if len > 0 call readbuf */ if (len > 0 && error == 0) { dbg("%s - call read buf - len to read is %i ", __func__, len); status = iuu_read_buf(port, len); return; } /* need to update status ? */ if (priv->poll > 99) { status = iuu_status(port); priv->poll = 0; return; } /* reset waiting ? */ if (priv->reset == 1) { status = iuu_reset(port, 0xC); return; } /* Writebuf is waiting */ spin_lock_irqsave(&priv->lock, flags); if (priv->writelen > 0) { spin_unlock_irqrestore(&priv->lock, flags); status = iuu_bulk_write(port); return; } spin_unlock_irqrestore(&priv->lock, flags); /* if nothing to write call again rxcmd */ dbg("%s - rxcmd recall", __func__); iuu_led_activity_off(urb); } static int iuu_uart_write(struct tty_struct *tty, struct usb_serial_port *port, const u8 *buf, int count) { struct iuu_private *priv = usb_get_serial_port_data(port); unsigned long flags; dbg("%s - enter", __func__); if (count > 256) return -ENOMEM; spin_lock_irqsave(&priv->lock, flags); /* fill the buffer */ memcpy(priv->writebuf + priv->writelen, buf, count); priv->writelen += count; spin_unlock_irqrestore(&priv->lock, flags); return count; } static void read_rxcmd_callback(struct urb *urb) { struct usb_serial_port *port = urb->context; int result; int status = urb->status; dbg("%s - status = %d", __func__, status); if (status) { /* error stop all */ return; } usb_fill_bulk_urb(port->read_urb, port->serial->dev, usb_rcvbulkpipe(port->serial->dev, port->bulk_in_endpointAddress), port->read_urb->transfer_buffer, 256, iuu_uart_read_callback, port); result = usb_submit_urb(port->read_urb, GFP_ATOMIC); dbg("%s - submit result = %d", __func__, result); } static int iuu_uart_on(struct usb_serial_port *port) { int status; u8 *buf; buf = kmalloc(sizeof(u8) * 4, GFP_KERNEL); if (!buf) return -ENOMEM; buf[0] = IUU_UART_ENABLE; buf[1] = (u8) ((IUU_BAUD_9600 >> 8) & 0x00FF); buf[2] = (u8) (0x00FF & IUU_BAUD_9600); buf[3] = (u8) (0x0F0 & IUU_ONE_STOP_BIT) | (0x07 & IUU_PARITY_EVEN); status = bulk_immediate(port, buf, 4); if (status != IUU_OPERATION_OK) { dbg("%s - uart_on error", __func__); goto uart_enable_failed; } /* iuu_reset() the card after iuu_uart_on() */ status = iuu_uart_flush(port); if (status != IUU_OPERATION_OK) dbg("%s - uart_flush error", __func__); uart_enable_failed: kfree(buf); return status; } /* Diables the IUU UART (a.k.a. the Phoenix voiderface) */ static int iuu_uart_off(struct usb_serial_port *port) { int status; u8 *buf; buf = kmalloc(1, GFP_KERNEL); if (!buf) return -ENOMEM; buf[0] = IUU_UART_DISABLE; status = bulk_immediate(port, buf, 1); if (status != IUU_OPERATION_OK) dbg("%s - uart_off error", __func__); kfree(buf); return status; } static int iuu_uart_baud(struct usb_serial_port *port, u32 baud_base, u32 *actual, u8 parity) { int status; u32 baud; u8 *dataout; u8 DataCount = 0; u8 T1Frekvens = 0; u8 T1reload = 0; unsigned int T1FrekvensHZ = 0; dbg("%s - enter baud_base=%d", __func__, baud_base); dataout = kmalloc(sizeof(u8) * 5, GFP_KERNEL); if (!dataout) return -ENOMEM; /*baud = (((priv->clk / 35) * baud_base) / 100000); */ baud = baud_base; if (baud < 1200 || baud > 230400) { kfree(dataout); return IUU_INVALID_PARAMETER; } if (baud > 977) { T1Frekvens = 3; T1FrekvensHZ = 500000; } if (baud > 3906) { T1Frekvens = 2; T1FrekvensHZ = 2000000; } if (baud > 11718) { T1Frekvens = 1; T1FrekvensHZ = 6000000; } if (baud > 46875) { T1Frekvens = 0; T1FrekvensHZ = 24000000; } T1reload = 256 - (u8) (T1FrekvensHZ / (baud * 2)); /* magic number here: ENTER_FIRMWARE_UPDATE; */ dataout[DataCount++] = IUU_UART_ESC; /* magic number here: CHANGE_BAUD; */ dataout[DataCount++] = IUU_UART_CHANGE; dataout[DataCount++] = T1Frekvens; dataout[DataCount++] = T1reload; *actual = (T1FrekvensHZ / (256 - T1reload)) / 2; switch (parity & 0x0F) { case IUU_PARITY_NONE: dataout[DataCount++] = 0x00; break; case IUU_PARITY_EVEN: dataout[DataCount++] = 0x01; break; case IUU_PARITY_ODD: dataout[DataCount++] = 0x02; break; case IUU_PARITY_MARK: dataout[DataCount++] = 0x03; break; case IUU_PARITY_SPACE: dataout[DataCount++] = 0x04; break; default: kfree(dataout); return IUU_INVALID_PARAMETER; break; } switch (parity & 0xF0) { case IUU_ONE_STOP_BIT: dataout[DataCount - 1] |= IUU_ONE_STOP_BIT; break; case IUU_TWO_STOP_BITS: dataout[DataCount - 1] |= IUU_TWO_STOP_BITS; break; default: kfree(dataout); return IUU_INVALID_PARAMETER; break; } status = bulk_immediate(port, dataout, DataCount); if (status != IUU_OPERATION_OK) dbg("%s - uart_off error", __func__); kfree(dataout); return status; } static void iuu_set_termios(struct tty_struct *tty, struct usb_serial_port *port, struct ktermios *old_termios) { const u32 supported_mask = CMSPAR|PARENB|PARODD; struct iuu_private *priv = usb_get_serial_port_data(port); unsigned int cflag = tty->termios->c_cflag; int status; u32 actual; u32 parity; int csize = CS7; int baud; u32 newval = cflag & supported_mask; /* Just use the ospeed. ispeed should be the same. */ baud = tty->termios->c_ospeed; dbg("%s - enter c_ospeed or baud=%d", __func__, baud); /* compute the parity parameter */ parity = 0; if (cflag & CMSPAR) { /* Using mark space */ if (cflag & PARODD) parity |= IUU_PARITY_SPACE; else parity |= IUU_PARITY_MARK; } else if (!(cflag & PARENB)) { parity |= IUU_PARITY_NONE; csize = CS8; } else if (cflag & PARODD) parity |= IUU_PARITY_ODD; else parity |= IUU_PARITY_EVEN; parity |= (cflag & CSTOPB ? IUU_TWO_STOP_BITS : IUU_ONE_STOP_BIT); /* set it */ status = iuu_uart_baud(port, baud * priv->boost / 100, &actual, parity); /* set the termios value to the real one, so the user now what has * changed. We support few fields so its easies to copy the old hw * settings back over and then adjust them */ if (old_termios) tty_termios_copy_hw(tty->termios, old_termios); if (status != 0) /* Set failed - return old bits */ return; /* Re-encode speed, parity and csize */ tty_encode_baud_rate(tty, baud, baud); tty->termios->c_cflag &= ~(supported_mask|CSIZE); tty->termios->c_cflag |= newval | csize; } static void iuu_close(struct usb_serial_port *port) { /* iuu_led (port,255,0,0,0); */ struct usb_serial *serial; serial = port->serial; if (!serial) return; dbg("%s - port %d", __func__, port->number); iuu_uart_off(port); if (serial->dev) { /* free writebuf */ /* shutdown our urbs */ dbg("%s - shutting down urbs", __func__); usb_kill_urb(port->write_urb); usb_kill_urb(port->read_urb); usb_kill_urb(port->interrupt_in_urb); iuu_led(port, 0, 0, 0xF000, 0xFF); } } static void iuu_init_termios(struct tty_struct *tty) { dbg("%s - enter", __func__); *(tty->termios) = tty_std_termios; tty->termios->c_cflag = CLOCAL | CREAD | CS8 | B9600 | TIOCM_CTS | CSTOPB | PARENB; tty->termios->c_ispeed = 9600; tty->termios->c_ospeed = 9600; tty->termios->c_lflag = 0; tty->termios->c_oflag = 0; tty->termios->c_iflag = 0; } static int iuu_open(struct tty_struct *tty, struct usb_serial_port *port) { struct usb_serial *serial = port->serial; u8 *buf; int result; int baud; u32 actual; struct iuu_private *priv = usb_get_serial_port_data(port); baud = tty->termios->c_ospeed; tty->termios->c_ispeed = baud; /* Re-encode speed */ tty_encode_baud_rate(tty, baud, baud); dbg("%s - port %d, baud %d", __func__, port->number, baud); usb_clear_halt(serial->dev, port->write_urb->pipe); usb_clear_halt(serial->dev, port->read_urb->pipe); buf = kmalloc(10, GFP_KERNEL); if (buf == NULL) return -ENOMEM; priv->poll = 0; /* initialize writebuf */ #define FISH(a, b, c, d) do { \ result = usb_control_msg(port->serial->dev, \ usb_rcvctrlpipe(port->serial->dev, 0), \ b, a, c, d, buf, 1, 1000); \ dbg("0x%x:0x%x:0x%x:0x%x %d - %x", a, b, c, d, result, \ buf[0]); } while (0); #define SOUP(a, b, c, d) do { \ result = usb_control_msg(port->serial->dev, \ usb_sndctrlpipe(port->serial->dev, 0), \ b, a, c, d, NULL, 0, 1000); \ dbg("0x%x:0x%x:0x%x:0x%x %d", a, b, c, d, result); } while (0) /* This is not UART related but IUU USB driver related or something */ /* like that. Basically no IUU will accept any commands from the USB */ /* host unless it has received the following message */ /* sprintf(buf ,"%c%c%c%c",0x03,0x02,0x02,0x0); */ SOUP(0x03, 0x02, 0x02, 0x0); kfree(buf); iuu_led(port, 0xF000, 0xF000, 0, 0xFF); iuu_uart_on(port); if (boost < 100) boost = 100; priv->boost = boost; priv->baud = baud; switch (clockmode) { case 2: /* 3.680 Mhz */ priv->clk = IUU_CLK_3680000; iuu_clk(port, IUU_CLK_3680000 * boost / 100); result = iuu_uart_baud(port, baud * boost / 100, &actual, IUU_PARITY_EVEN); break; case 3: /* 6.00 Mhz */ iuu_clk(port, IUU_CLK_6000000 * boost / 100); priv->clk = IUU_CLK_6000000; /* Ratio of 6000000 to 3500000 for baud 9600 */ result = iuu_uart_baud(port, 16457 * boost / 100, &actual, IUU_PARITY_EVEN); break; default: /* 3.579 Mhz */ iuu_clk(port, IUU_CLK_3579000 * boost / 100); priv->clk = IUU_CLK_3579000; result = iuu_uart_baud(port, baud * boost / 100, &actual, IUU_PARITY_EVEN); } /* set the cardin cardout signals */ switch (cdmode) { case 0: iuu_cardin = 0; iuu_cardout = 0; break; case 1: iuu_cardin = TIOCM_CD; iuu_cardout = 0; break; case 2: iuu_cardin = 0; iuu_cardout = TIOCM_CD; break; case 3: iuu_cardin = TIOCM_DSR; iuu_cardout = 0; break; case 4: iuu_cardin = 0; iuu_cardout = TIOCM_DSR; break; case 5: iuu_cardin = TIOCM_CTS; iuu_cardout = 0; break; case 6: iuu_cardin = 0; iuu_cardout = TIOCM_CTS; break; case 7: iuu_cardin = TIOCM_RNG; iuu_cardout = 0; break; case 8: iuu_cardin = 0; iuu_cardout = TIOCM_RNG; } iuu_uart_flush(port); dbg("%s - initialization done", __func__); memset(port->write_urb->transfer_buffer, IUU_UART_RX, 1); usb_fill_bulk_urb(port->write_urb, port->serial->dev, usb_sndbulkpipe(port->serial->dev, port->bulk_out_endpointAddress), port->write_urb->transfer_buffer, 1, read_rxcmd_callback, port); result = usb_submit_urb(port->write_urb, GFP_KERNEL); if (result) { dev_err(&port->dev, "%s - failed submitting read urb," " error %d\n", __func__, result); iuu_close(port); } else { dbg("%s - rxcmd OK", __func__); } return result; } /* how to change VCC */ static int iuu_vcc_set(struct usb_serial_port *port, unsigned int vcc) { int status; u8 *buf; buf = kmalloc(5, GFP_KERNEL); if (!buf) return -ENOMEM; dbg("%s - enter", __func__); buf[0] = IUU_SET_VCC; buf[1] = vcc & 0xFF; buf[2] = (vcc >> 8) & 0xFF; buf[3] = (vcc >> 16) & 0xFF; buf[4] = (vcc >> 24) & 0xFF; status = bulk_immediate(port, buf, 5); kfree(buf); if (status != IUU_OPERATION_OK) dbg("%s - vcc error status = %2x", __func__, status); else dbg("%s - vcc OK !", __func__); return status; } /* * Sysfs Attributes */ static ssize_t show_vcc_mode(struct device *dev, struct device_attribute *attr, char *buf) { struct usb_serial_port *port = to_usb_serial_port(dev); struct iuu_private *priv = usb_get_serial_port_data(port); return sprintf(buf, "%d\n", priv->vcc); } static ssize_t store_vcc_mode(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct usb_serial_port *port = to_usb_serial_port(dev); struct iuu_private *priv = usb_get_serial_port_data(port); unsigned long v; if (strict_strtoul(buf, 10, &v)) { dev_err(dev, "%s - vcc_mode: %s is not a unsigned long\n", __func__, buf); goto fail_store_vcc_mode; } dbg("%s: setting vcc_mode = %ld", __func__, v); if ((v != 3) && (v != 5)) { dev_err(dev, "%s - vcc_mode %ld is invalid\n", __func__, v); } else { iuu_vcc_set(port, v); priv->vcc = v; } fail_store_vcc_mode: return count; } static DEVICE_ATTR(vcc_mode, S_IRUSR | S_IWUSR, show_vcc_mode, store_vcc_mode); static int iuu_create_sysfs_attrs(struct usb_serial_port *port) { dbg("%s", __func__); return device_create_file(&port->dev, &dev_attr_vcc_mode); } static int iuu_remove_sysfs_attrs(struct usb_serial_port *port) { dbg("%s", __func__); device_remove_file(&port->dev, &dev_attr_vcc_mode); return 0; } /* * End Sysfs Attributes */ static struct usb_serial_driver iuu_device = { .driver = { .owner = THIS_MODULE, .name = "iuu_phoenix", }, .id_table = id_table, .usb_driver = &iuu_driver, .num_ports = 1, .bulk_in_size = 512, .bulk_out_size = 512, .port_probe = iuu_create_sysfs_attrs, .port_remove = iuu_remove_sysfs_attrs, .open = iuu_open, .close = iuu_close, .write = iuu_uart_write, .read_bulk_callback = iuu_uart_read_callback, .tiocmget = iuu_tiocmget, .tiocmset = iuu_tiocmset, .set_termios = iuu_set_termios, .init_termios = iuu_init_termios, .attach = iuu_startup, .release = iuu_release, }; static int __init iuu_init(void) { int retval; retval = usb_serial_register(&iuu_device); if (retval) goto failed_usb_serial_register; retval = usb_register(&iuu_driver); if (retval) goto failed_usb_register; printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":" DRIVER_DESC "\n"); return 0; failed_usb_register: usb_serial_deregister(&iuu_device); failed_usb_serial_register: return retval; } static void __exit iuu_exit(void) { usb_deregister(&iuu_driver); usb_serial_deregister(&iuu_device); } module_init(iuu_init); module_exit(iuu_exit); MODULE_AUTHOR("<NAME> <EMAIL>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); MODULE_VERSION(DRIVER_VERSION); module_param(debug, bool, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug, "Debug enabled or not"); module_param(xmas, bool, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(xmas, "Xmas colors enabled or not"); module_param(boost, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(boost, "Card overclock boost (in percent 100-500)"); module_param(clockmode, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(clockmode, "Card clock mode (1=3.579 MHz, 2=3.680 MHz, " "3=6 Mhz)"); module_param(cdmode, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(cdmode, "Card detect mode (0=none, 1=CD, 2=!CD, 3=DSR, " "4=!DSR, 5=CTS, 6=!CTS, 7=RING, 8=!RING)"); module_param(vcc_default, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(vcc_default, "Set default VCC (either 3 for 3.3V or 5 " "for 5V). Default to 5.");
0.996094
high
JFilewraper/JCompressfile.h
WhiteGroup/JAV-AV-Engine
15
1659440
<reponame>WhiteGroup/JAV-AV-Engine #ifndef JCOMPRESSFILEH #define JCOMPRESSFILEH #include "Jfile.h" #include "IUnCompersser.h" class JCompressFile : public JFile { public : JCompressFile(); void SetCompressor(IUnCompersser *inposIUnCompersser); JString GetDisplayName () ; void SetDisplayName (JString i_strDisplayName) ; void GetShortName(JString &o_strShortPath , UINT32 MaxLenght) ; BOOLEAN Close(); BOOLEAN CloseHandle(); void SetFileAsVirus(); void SetFileAsWorm(); ~JCompressFile(); #ifdef JFILEKERNEL BOOLEAN OpenTempFile(JString &Name); static BOOLEAN DeleteForTemp(JString &Name); #endif private : JString m_strDisPlayName ; IUnCompersser *posIUnCompersser; BOOLEAN bIsInfected, bIsWorm; }; #endif
0.949219
high
src/libraries/ut/sg_uridispatch_sync.c
avar/veracity
2
25472
/* Copyright 2010 SourceGear, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @file sg_uridispatch_log.c */ #include <sg.h> #include "sg_uridispatch_private_typedefs.h" #include "sg_uridispatch_private_prototypes.h" ////////////////////////////////////////////////////////////////// typedef struct { SG_string* pstrRequestBody; SG_repo* pRepo; } _POST_sync_request_body_state; static void _POST_sync_request_body_state__free(SG_context* pCtx, _POST_sync_request_body_state* pState) { if (pState) { SG_STRING_NULLFREE(pCtx, pState->pstrRequestBody); SG_REPO_NULLFREE(pCtx, pState->pRepo); SG_NULLFREE(pCtx, pState); } } #define _POST_SYNC_REQUEST_BODY_STATE__NULLFREE(pCtx,p) SG_STATEMENT(SG_context__push_level(pCtx); _POST_sync_request_body_state__free(pCtx,p); SG_context__pop_level(pCtx); p=NULL;) ////////////////////////////////////////////////////////////////// static void _POST_sync_request_body__chunk(SG_context* pCtx, _response_handle** ppResponseHandle, SG_byte* pBuffer, SG_uint32 bufferLength, void* pState) { SG_string* pstrRequestBody = ((_POST_sync_request_body_state*)pState)->pstrRequestBody; SG_UNUSED(ppResponseHandle); SG_ERR_CHECK_RETURN( SG_string__append__buf_len(pCtx, pstrRequestBody, pBuffer, bufferLength) ); } static void _POST_sync_request_body__aborted(SG_context* pCtx, void *pState) { _POST_SYNC_REQUEST_BODY_STATE__NULLFREE(pCtx, pState); } static void _POST_sync_request_body__finish(SG_context* pCtx, const SG_audit* pAudit, void* pVoidState, _response_handle ** ppResponseHandle) { _POST_sync_request_body_state* pRequestState = (_POST_sync_request_body_state*)pVoidState; SG_vhash* pvhRequest = NULL; SG_pathname* pPathTemp = NULL; char* pszFragballName = NULL; SG_vhash* pvhStatus = NULL; SG_pathname* pPathFragball = NULL; SG_UNUSED(pAudit); if (pRequestState->pstrRequestBody) SG_ERR_CHECK( SG_vhash__alloc__from_json(pCtx, &pvhRequest, SG_string__sz(pRequestState->pstrRequestBody)) ); SG_ERR_CHECK( SG_pathname__alloc__user_temp_directory(pCtx, &pPathTemp) ); // TODO: what's the right path? Not user temp. SG_ERR_CHECK( SG_server__pull_request_fragball(pCtx, pRequestState->pRepo, pvhRequest, pPathTemp, &pszFragballName, &pvhStatus) ); SG_ERR_CHECK( SG_pathname__alloc__pathname_sz(pCtx, &pPathFragball, pPathTemp, (const char*)pszFragballName) ); SG_ERR_CHECK( _create_response_handle_for_file(pCtx, SG_HTTP_STATUS_OK, SG_contenttype__fragball, &pPathFragball, SG_TRUE, ppResponseHandle) ); /* fall through */ fail: _POST_SYNC_REQUEST_BODY_STATE__NULLFREE(pCtx, pRequestState); SG_VHASH_NULLFREE(pCtx, pvhRequest); SG_PATHNAME_NULLFREE(pCtx, pPathTemp); SG_NULLFREE(pCtx, pszFragballName); SG_VHASH_NULLFREE(pCtx, pvhStatus); SG_PATHNAME_NULLFREE(pCtx, pPathFragball); } /** * Handle a POST to /repos/<descriptor>/sync. * * This handles two things: * * 1) A fragball request (typically for pull or clone) * - will always have an "application/fragball" Accept header * - will have either: * - a zero-length message body, indicating a request for the leaves of every DAG * - a jsonified vhash in the message body, whose format is described by SG_server__pull_request_fragball * * 2) A push_begin request * - will always have an "application/json" Accept header * - will always have an empty message body */ static void _POST_sync(SG_context* pCtx, _request_headers * pRequestHeaders, const char* pszRepoDescriptorName, SG_repo** ppRepo, _request_handle ** ppRequestHandle, _response_handle** ppResponseHandle) { _POST_sync_request_body_state* pState = NULL; SG_server* pServer = NULL; const char* pszPushId = NULL; SG_string* pstrResponse = NULL; if (pRequestHeaders->accept == SG_contenttype__fragball) { SG_ERR_CHECK( SG_alloc1(pCtx, pState) ); pState->pRepo = *ppRepo; if (pRequestHeaders->contentLength > 0) { // A fragball was requested with specifics. // Fetch the fragball's specs. if (pRequestHeaders->contentLength > SG_STRING__MAX_LENGTH_IN_BYTES) SG_ERR_THROW_RETURN(SG_ERR_URI_HTTP_413_REQUEST_ENTITY_TOO_LARGE); SG_ERR_CHECK( SG_STRING__ALLOC__RESERVE(pCtx, &pState->pstrRequestBody, (SG_uint32)pRequestHeaders->contentLength) ); SG_ERR_CHECK( _request_handle__alloc(pCtx, ppRequestHandle, pRequestHeaders, _POST_sync_request_body__chunk, _POST_sync_request_body__finish, _POST_sync_request_body__aborted, pState) ); } else { // The default fragball was requested. SG_ERR_CHECK( _POST_sync_request_body__finish(pCtx, NULL, pState, ppResponseHandle) ); } *ppRepo = NULL; pState = NULL; } else if (pRequestHeaders->accept == SG_contenttype__json) { // A push_begin request was made. SG_ERR_CHECK( SG_server__alloc(pCtx, &pServer) ); // Tell the server we're about to push. We get back a push ID, which we'll send back to our requester. SG_ERR_CHECK( SG_server__push_begin(pCtx, pServer, pszRepoDescriptorName, &pszPushId) ); // TODO: This isn't actually json. // Return the push id. SG_ERR_CHECK( SG_STRING__ALLOC__SZ(pCtx, &pstrResponse, pszPushId) ); SG_ERR_CHECK( _create_response_handle_for_string(pCtx, SG_HTTP_STATUS_OK, SG_contenttype__json, &pstrResponse, ppResponseHandle) ); SG_REPO_NULLFREE(pCtx, *ppRepo); *ppRepo = NULL; } else SG_ERR_THROW2(SG_ERR_URI_HTTP_400_BAD_REQUEST, (pCtx, "Missing or invalid Accept header.")); /* fall through */ fail: if (pState && SG_context__has_err(pCtx)) pState->pRepo = NULL; // Repo's not ours to free if we're going to return an error. _POST_SYNC_REQUEST_BODY_STATE__NULLFREE(pCtx, pState); SG_SERVER_NULLFREE(pCtx, pServer); SG_NULLFREE(pCtx, pszPushId); SG_STRING_NULLFREE(pCtx, pstrResponse); } ////////////////////////////////////////////////////////////////////////// static void _DELETE_pushid(SG_context* pCtx, _request_headers * pRequestHeaders, SG_repo** ppRepo, const char* pszPushId, _request_handle ** ppRequestHandle, _response_handle** ppResponseHandle) { SG_server* pServer = NULL; SG_UNUSED(pRequestHeaders); SG_UNUSED(ppRequestHandle); SG_ERR_CHECK( SG_server__alloc(pCtx, &pServer) ); SG_ERR_CHECK( SG_server__push_end(pCtx, pServer, pszPushId) ); SG_ERR_CHECK( _response_handle__alloc(pCtx, ppResponseHandle, SG_HTTP_STATUS_OK, NULL, 0, NULL, NULL, NULL, NULL) ); SG_REPO_NULLFREE(pCtx, *ppRepo); /* fall through */ fail: SG_SERVER_NULLFREE(pCtx, pServer); } ////////////////////////////////////////////////////////////////////////// typedef struct { char bufFragballFilename[SG_TID_MAX_BUFFER_LENGTH]; SG_file* pFileFragball; char* pszPushId; } _POST_pushid_request_body_state; static void _POST_pushid_request_body_state__free(SG_context* pCtx, _POST_pushid_request_body_state* pState) { if (pState) { SG_FILE_NULLCLOSE(pCtx, pState->pFileFragball); SG_NULLFREE(pCtx, pState->pszPushId); SG_NULLFREE(pCtx, pState); } } #define _POST_PUSHID_REQUEST_BODY_STATE__NULLFREE(pCtx,p) SG_STATEMENT(SG_context__push_level(pCtx); _POST_pushid_request_body_state__free(pCtx,p); SG_context__pop_level(pCtx); p=NULL;) static void _POST_pushid_request_body__chunk(SG_context* pCtx, _response_handle** ppResponseHandle, SG_byte* pBuffer, SG_uint32 bufferLength, void* pState) { SG_file* pFileFragball = ((_POST_pushid_request_body_state*)pState)->pFileFragball; SG_uint32 lenWritten; SG_UNUSED(ppResponseHandle); SG_ERR_CHECK_RETURN( SG_file__write(pCtx, pFileFragball, bufferLength, (const SG_byte*)pBuffer, &lenWritten) ); if (lenWritten != bufferLength) SG_ERR_THROW_RETURN(SG_ERR_INCOMPLETEWRITE); } static void _POST_pushid_request_body__aborted(SG_context* pCtx, void *pState) { _POST_PUSHID_REQUEST_BODY_STATE__NULLFREE(pCtx, pState); } static void _POST_pushid_request_body__finish(SG_context* pCtx, const SG_audit* pAudit, void* pVoidState, _response_handle ** ppResponseHandle) { _POST_pushid_request_body_state* pState = (_POST_pushid_request_body_state*)pVoidState; SG_server* pServer = NULL; SG_vhash* pvhAddResult = NULL; SG_string* pstrResponse = NULL; SG_UNUSED(pAudit); SG_ERR_CHECK( SG_server__alloc(pCtx, &pServer) ); SG_ERR_CHECK( SG_server__push_add(pCtx, pServer, pState->pszPushId, (const char*)pState->bufFragballFilename, &pvhAddResult) ); SG_ERR_CHECK( SG_STRING__ALLOC(pCtx, &pstrResponse) ); SG_ERR_CHECK( SG_vhash__to_json(pCtx, pvhAddResult, pstrResponse) ); SG_ERR_CHECK( _create_response_handle_for_string(pCtx, SG_HTTP_STATUS_OK, SG_contenttype__json, &pstrResponse, ppResponseHandle) ); /* fall through */ fail: _POST_PUSHID_REQUEST_BODY_STATE__NULLFREE(pCtx, pState); SG_STRING_NULLFREE(pCtx, pstrResponse); SG_SERVER_NULLFREE(pCtx, pServer); SG_VHASH_NULLFREE(pCtx, pvhAddResult); } static void _push_commit(SG_context* pCtx, const char* pszPushId, _response_handle** ppResponseHandle) { SG_server* pServer = NULL; SG_vhash* pvhCommitResult = NULL; SG_string* pstrResponse = NULL; SG_ERR_CHECK( SG_server__alloc(pCtx, &pServer) ); SG_ERR_CHECK( SG_server__push_commit(pCtx, pServer, pszPushId, &pvhCommitResult) ); SG_ERR_CHECK( SG_STRING__ALLOC(pCtx, &pstrResponse) ); SG_ERR_CHECK( SG_vhash__to_json(pCtx, pvhCommitResult, pstrResponse) ); SG_ERR_CHECK( _create_response_handle_for_string(pCtx, SG_HTTP_STATUS_OK, SG_contenttype__json, &pstrResponse, ppResponseHandle) ); /* fall through */ fail: SG_STRING_NULLFREE(pCtx, pstrResponse); SG_SERVER_NULLFREE(pCtx, pServer); SG_VHASH_NULLFREE(pCtx, pvhCommitResult); } static void _POST_pushid(SG_context* pCtx, _request_headers * pRequestHeaders, SG_repo** ppRepo, const char* pszPushId, _request_handle ** ppRequestHandle, _response_handle** ppResponseHandle) { SG_staging* pStaging = NULL; const SG_pathname* pStagingPathname = NULL; SG_pathname* pPathFragball = NULL; _POST_pushid_request_body_state* pRequestState = NULL; if (pRequestHeaders->contentLength == 0) { // push commit SG_ERR_CHECK( _push_commit(pCtx, pszPushId, ppResponseHandle) ); } else { // push add SG_ERR_CHECK( SG_alloc1(pCtx, pRequestState) ); SG_ERR_CHECK( SG_strdup(pCtx, pszPushId, &pRequestState->pszPushId) ); SG_ERR_CHECK( SG_tid__generate(pCtx, pRequestState->bufFragballFilename, SG_TID_MAX_BUFFER_LENGTH) ); SG_ERR_CHECK( SG_staging__open(pCtx, pszPushId, &pStaging) ); SG_ERR_CHECK( SG_staging__get_pathname(pCtx, pStaging, &pStagingPathname) ); SG_ERR_CHECK( SG_pathname__alloc__pathname_sz(pCtx, &pPathFragball, pStagingPathname, pRequestState->bufFragballFilename) ); SG_ERR_CHECK( SG_file__open__pathname(pCtx, pPathFragball, SG_FILE_CREATE_NEW | SG_FILE_WRONLY, 0644, &pRequestState->pFileFragball) ); SG_ERR_CHECK( _request_handle__alloc(pCtx, ppRequestHandle, pRequestHeaders, _POST_pushid_request_body__chunk, _POST_pushid_request_body__finish, _POST_pushid_request_body__aborted, pRequestState) ); pRequestState = NULL; } SG_REPO_NULLFREE(pCtx, *ppRepo); /* fall through */ fail: SG_STAGING_NULLFREE(pCtx, pStaging); SG_PATHNAME_NULLFREE(pCtx, pPathFragball); _POST_PUSHID_REQUEST_BODY_STATE__NULLFREE(pCtx, pRequestState); } ////////////////////////////////////////////////////////////////////////// static void _GET_pushid(SG_context* pCtx, _request_headers * pRequestHeaders, SG_repo** ppRepo, const char* pszPushId, _request_handle ** ppRequestHandle, _response_handle** ppResponseHandle) { SG_staging* pStaging = NULL; SG_vhash* pvhStatus = NULL; SG_string* pstrResponse = NULL; SG_UNUSED(pRequestHeaders); SG_UNUSED(ppRequestHandle); SG_ERR_CHECK( SG_staging__open(pCtx, pszPushId, &pStaging) ); SG_ERR_CHECK( SG_staging__check_status(pCtx, pStaging, SG_TRUE, SG_TRUE, SG_TRUE, SG_TRUE, SG_TRUE, &pvhStatus) ); SG_ERR_CHECK( SG_STRING__ALLOC(pCtx, &pstrResponse) ); SG_ERR_CHECK( SG_vhash__to_json(pCtx, pvhStatus, pstrResponse) ); SG_ERR_CHECK( _create_response_handle_for_string(pCtx, SG_HTTP_STATUS_OK, SG_contenttype__json, &pstrResponse, ppResponseHandle) ); SG_REPO_NULLFREE(pCtx, *ppRepo); pstrResponse = NULL; /* fall through */ fail: SG_STAGING_NULLFREE(pCtx, pStaging); SG_VHASH_NULLFREE(pCtx, pvhStatus); SG_STRING_NULLFREE(pCtx, pstrResponse); } ////////////////////////////////////////////////////////////////////////// static void _dispatch__sync__pushid(SG_context * pCtx, _request_headers * pRequestHeaders, SG_repo ** ppRepo, // On success we've taken ownership and nulled the caller's copy. const char ** ppUriSubstrings, SG_uint32 uriSubstringsCount, _request_handle ** ppRequestHandle, _response_handle ** ppResponseHandle) { const char* pszPushId = ppUriSubstrings[0]; if( uriSubstringsCount != 1 || (uriSubstringsCount==1 && eq(ppUriSubstrings[0],"")) ) SG_ERR_THROW_RETURN(SG_ERR_URI_HTTP_404_NOT_FOUND); if (eq(pRequestHeaders->pRequestMethod, "DELETE")) SG_ERR_CHECK_RETURN( _DELETE_pushid(pCtx, pRequestHeaders, ppRepo, pszPushId, ppRequestHandle, ppResponseHandle) ); else if (eq(pRequestHeaders->pRequestMethod, "POST")) SG_ERR_CHECK_RETURN( _POST_pushid(pCtx, pRequestHeaders, ppRepo, pszPushId, ppRequestHandle, ppResponseHandle) ); else if (eq(pRequestHeaders->pRequestMethod, "GET")) SG_ERR_CHECK_RETURN( _GET_pushid(pCtx, pRequestHeaders, ppRepo, pszPushId, ppRequestHandle, ppResponseHandle) ); else SG_ERR_THROW_RETURN(SG_ERR_URI_HTTP_405_METHOD_NOT_ALLOWED); } void _dispatch__sync(SG_context * pCtx, _request_headers * pRequestHeaders, const char* pszRepoDescriptorName, SG_repo ** ppRepo, // On success we've taken ownership and nulled the caller's copy. const char ** ppUriSubstrings, SG_uint32 uriSubstringsCount, _request_handle ** ppRequestHandle, _response_handle ** ppResponseHandle) { if( uriSubstringsCount == 0) { if (eq(pRequestHeaders->pRequestMethod, "POST")) SG_ERR_CHECK_RETURN( _POST_sync(pCtx, pRequestHeaders, pszRepoDescriptorName, ppRepo, ppRequestHandle, ppResponseHandle) ); else SG_ERR_THROW_RETURN(SG_ERR_URI_HTTP_405_METHOD_NOT_ALLOWED); } else if (uriSubstringsCount == 1 && !eq(ppUriSubstrings[0],"")) _dispatch__sync__pushid(pCtx, pRequestHeaders, ppRepo, ppUriSubstrings, uriSubstringsCount, ppRequestHandle, ppResponseHandle); else SG_ERR_THROW_RETURN(SG_ERR_URI_HTTP_404_NOT_FOUND); }
1
high
control/switchcasenuevo.c
irmalg/C
0
58240
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <windows.h> int main() { int opcion; float n1, n2, resultado; printf("Elige una opcion:\n"); printf("\t 1.- Suma:\n"); printf("\t 2.- Resta:\n"); printf("\t 3.- Multiplicacion:\n"); printf("\t 4.- Division:\n"); printf("\t 5.- Potencia:\n"); printf("\t 6.- Raiz cuadrada:\n"); printf("\t 7.- Salir:\n"); scanf("%d",&opcion); system("cls"); if(opcion==6){ printf("\n Dame el numero: "); scanf("%f", &n1); } else if(opcion>=7){ } else{ printf("\n Dame el primer numero: "); scanf("%f", &n1); printf("\n Dame el segundo numero: "); scanf("%f", &n2); } switch(opcion) { case 1: resultado = n1 + n2; printf("El resultado es: %f", resultado); break; case 2: resultado = n1 - n2; printf("El resultado es: %f", resultado); break; case 3: resultado = n1 * n2; printf("El resultado es: %f", resultado); break; case 4: if(n2==0) { printf("La operacion entre 0 no esta definida"); } else{ resultado = n1 / n2; printf("El resultado es: %f", resultado); } break; case 5: resultado = pow(n1,n2); printf("El resultado es: %f", resultado); break; case 6: if(n1 < 0){ printf("No esta definida"); } else{ resultado = sqrt(n1); printf("El resultado es: %f", resultado); } break; case 7: printf("Salir"); break; default: printf("No esta puesta correctamente la opcion\n"); exit(0); } printf("\nFin de Switch\n"); return 0; }
0.578125
high
PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoEventCutCentrality.h
mkofarag/AliPhysics
0
91008
<reponame>mkofarag/AliPhysics<gh_stars>0 /// /// \file AliFemtoEventCutCentrality.h /// #pragma once #ifndef ALIFEMTOEVENTCUTCENTRALITY_H #define ALIFEMTOEVENTCUTCENTRALITY_H #include "AliFemtoEventCut.h" #include "AliLog.h" #include <utility> // std::pair #include "AliFemtoConfigObject.h" /// \class AliFemtoEventCutCentrality /// \brief Event cut based on the determined event centrality /// /// Cuts cuts on event centrality, z-vertex position, and event plane angle (Ψ-EP) /// /// \author <NAME>, The Ohio State University <<EMAIL>> /// class AliFemtoEventCutCentrality : public AliFemtoEventCut { public: /// Enumerated type used to select the centrality algorithm. /// Look at :class:`AliFemtoEvent` for more information. /// enum CentralityType { kV0 , kV0A , kV0C , kZNA , kZNC , kCL1 , kCL0 , kTKL , kFMD , kTrk , kCND , kNPA , kSPD1 , kUNKNOWN = -9999 }; struct Parameters { CentralityType centrality_type; std::pair<double, double> centrality_range; std::pair<double, double> vertex_z_range; std::pair<double, double> psi_ep_range; int select_trigger; Parameters(); Parameters(AliFemtoConfigObject&); // Parameters(const AliFemtoConfigObject &); operator AliFemtoEventCutCentrality() const { return AliFemtoEventCutCentrality(*this); } }; public: /// Default Constructor /// /// Uses the 'V0' event centrality calculation and wide ranges to /// allow all events. /// AliFemtoEventCutCentrality(); /// Copy Constructor - Copies the parameters but NOT number of events /// which have passed /// AliFemtoEventCutCentrality(const AliFemtoEventCutCentrality& c); /// Parameter Constructor AliFemtoEventCutCentrality(const Parameters &); /// Build AliFemtoConfigObject AliFemtoConfigObject GetConfigObject() const; AliFemtoConfigObject* GetConfigObjectPtr() const; /// Assignment Operator - Copies the parameters and RESETS the number /// of events to 0 /// AliFemtoEventCutCentrality& operator=(const AliFemtoEventCutCentrality& c); /// Set min and max acceptable event centrality void SetCentralityRange(const float lo, const float hi); /// Set min and max acceptable vertex z-coordinate void SetZPosRange(const float lo, const float hi); /// Set the min and max allowed event reaction plane angle void SetEPVZERO(const float lo, const float hi); /// Number of events passed ULong_t NEventsPassed() const; /// Number of events failed ULong_t NEventsFailed() const; /// Set centrality type using the enum void SetCentralityType(const CentralityType); /// Set centrality type by string identification (case-insensitive). /// If string is unknown, a warning will be printed and no modification /// to the cut will be made. /// void SetCentralityType(const TString& typestr); void SetTriggerSelection(int trig); ///< Set the trigger cluster virtual TList* AppendSettings(TList*, const TString& prefix="") const; virtual AliFemtoString Report(); virtual bool Pass(const AliFemtoEvent* event); bool PassCentrality(const AliFemtoEvent* event) const; bool PassVertex(const AliFemtoEvent* event) const; bool PassEventPlane(const AliFemtoEvent* event) const; bool PassTrigger(const AliFemtoEvent* event) const; virtual AliFemtoEventCut* Clone() const; /// Return the centrality of the event based on whatever algorithm is /// selected by the CentralityType member. /// float GetCentrality(const AliFemtoEvent*) const; /// Function returnting whether first parameter is within the bounds /// set by the second parameter template <typename RangeType> static bool within_range(float, const RangeType&); /// static CentralityType CentralityTypeFromName(const TString &); std::string CentralityTypeName(const CentralityType) const; protected: typedef std::pair<float, float> Range_t; CentralityType fCentralityType; ///< Selects which centrality calculation algorithm to use Range_t fEventCentrality; ///< range of centrality Range_t fVertZPos; ///< range of z-position of vertex Range_t fPsiEP; ///< range of event plane angle int fSelectTrigger; ///< If set, only given triggers will be selected ULong_t fNEventsPassed; ///< Number of events checked by this cut that passed ULong_t fNEventsFailed; ///< Number of events checked by this cut that failed private: /// Return the name of the class - required for use with AliWarning TString ClassName() { return "AliFemtoEventCutCentrality"; } }; inline void AliFemtoEventCutCentrality::SetCentralityType(const CentralityType type) { fCentralityType = type; } inline void AliFemtoEventCutCentrality::SetCentralityType(const TString& typestr) { auto type = CentralityTypeFromName(typestr); SetCentralityType(type); } inline AliFemtoEventCutCentrality::CentralityType AliFemtoEventCutCentrality::CentralityTypeFromName(const TString &typestr) { TString t = typestr; t.ToLower(); CentralityType type = t == "v0" ? kV0 : t == "v0m" ? kV0A : t == "v0a" ? kV0A : t == "v0c" ? kV0C : t == "zna" ? kZNA : t == "znc" ? kZNC : t == "cl0" ? kCL0 : t == "cl1" ? kCL1 : t == "tkl" ? kTKL : t == "fmd" ? kFMD : t == "trk" ? kTrk : t == "cnd" ? kCND : t == "npa" ? kNPA : t == "spd1" ? kSPD1 : kUNKNOWN; // if (type == BAD_STRING) { // AliWarning("Bad centrality type string: '" + typestr + "'"); // } return type; } inline std::string AliFemtoEventCutCentrality::CentralityTypeName(const CentralityType type) const { #define CASE(val, name) case val: return name; switch (type) { CASE(kV0, "V0") CASE(kV0A, "V0A") CASE(kV0C, "V0C") CASE(kZNA, "ZNA") CASE(kZNC, "ZNC") CASE(kCL0, "CL0") CASE(kCL1, "CL1") CASE(kTKL, "TKL") CASE(kFMD, "FMD") CASE(kTrk, "TRK") CASE(kCND, "CND") CASE(kNPA, "NPA") CASE(kSPD1, "SPD1") default: break; } #undef CASE return "UNKNOWN"; } inline void AliFemtoEventCutCentrality::SetCentralityRange(const float lo, const float hi) { fEventCentrality = std::make_pair(lo, hi); } inline void AliFemtoEventCutCentrality::SetZPosRange(const float lo, const float hi) { fVertZPos = std::make_pair(lo, hi); } inline void AliFemtoEventCutCentrality::SetEPVZERO(const float lo, const float hi) { fPsiEP = std::make_pair(lo, hi); } inline ULong_t AliFemtoEventCutCentrality::NEventsPassed() const { return fNEventsPassed; } inline ULong_t AliFemtoEventCutCentrality::NEventsFailed() const { return fNEventsFailed; } inline void AliFemtoEventCutCentrality::SetTriggerSelection(int trig) { fSelectTrigger = trig; } inline AliFemtoEventCut* AliFemtoEventCutCentrality::Clone() const { return new AliFemtoEventCutCentrality(*this); } inline AliFemtoEventCutCentrality::AliFemtoEventCutCentrality(const AliFemtoEventCutCentrality& c): AliFemtoEventCut(c) , fCentralityType(c.fCentralityType) , fEventCentrality(c.fEventCentrality) , fVertZPos(c.fVertZPos) , fPsiEP(c.fPsiEP) , fSelectTrigger(c.fSelectTrigger) , fNEventsPassed(0) , fNEventsFailed(0) { } inline AliFemtoEventCutCentrality& AliFemtoEventCutCentrality::operator=(const AliFemtoEventCutCentrality& c) { if (this != &c) { AliFemtoEventCut::operator=(c); fCentralityType = c.fCentralityType; fSelectTrigger = c.fSelectTrigger; fEventCentrality = c.fEventCentrality; fVertZPos = c.fVertZPos; fPsiEP = c.fPsiEP; fNEventsPassed = 0; fNEventsFailed = 0; } return *this; } inline float AliFemtoEventCutCentrality::GetCentrality(const AliFemtoEvent *ev) const { switch (fCentralityType) { case kV0: return ev->CentralityV0(); case kV0A: return ev->CentralityV0A(); case kV0C: return ev->CentralityV0C(); case kZNA: return ev->CentralityZNA(); case kZNC: return ev->CentralityZNC(); case kCL1: return ev->CentralityCL1(); case kCL0: return ev->CentralityCL0(); case kTKL: return ev->CentralityTKL(); case kFMD: return ev->CentralityFMD(); case kTrk: return ev->CentralityTrk(); case kCND: return ev->CentralityCND(); case kNPA: return ev->CentralityNPA(); case kSPD1: return ev->CentralitySPD1(); default: return -1.0; } } template <typename RangeType> inline bool AliFemtoEventCutCentrality::within_range(float val, const RangeType &range) { return (std::get<0>(range) <= val) && (val < std::get<1>(range)); } inline bool AliFemtoEventCutCentrality::PassCentrality(const AliFemtoEvent* event) const { return within_range(GetCentrality(event), fEventCentrality); } inline bool AliFemtoEventCutCentrality::PassVertex(const AliFemtoEvent* event) const { return within_range(event->PrimVertPos().z(), fVertZPos); } inline bool AliFemtoEventCutCentrality::PassEventPlane(const AliFemtoEvent* event) const { return within_range(event->ReactionPlaneAngle(), fPsiEP); } inline bool AliFemtoEventCutCentrality::PassTrigger(const AliFemtoEvent* event) const { return (fSelectTrigger == 0) || (event->TriggerCluster() == fSelectTrigger); } #endif
0.992188
high
src/s_cmp.c
Argonne-National-Laboratory/ENPEP-windows
0
123776
/******************************************************************* COPYRIGHT NOTIFICATION ******************************************************************** Copyright © 2021, UChicago Argonne, LLC All Rights Reserved Software Name: ENPEP- Balance By: Argonne National Laboratory OPEN SOURCE LICENSE ******************************************************************** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. ******************************************************************** DISCLAIMER 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 "f2c.h" #include <stdio.h> #include <string.h> #include <malloc.h> extern FILE *fp21; /* compare two strings */ void cmc_dbg(void){}; #ifdef KR_headers integer s_cmp(a0, b0, la, lb) char *a0, *b0; ftnlen la, lb; #else integer s_cmp(char *a0, char *b0, ftnlen la, ftnlen lb) #endif { register unsigned char *a, *aend, *b, *bend; int i; char *pad_a0; integer retval; retval = 0; pad_a0 = (char *) calloc((la+1), sizeof(char) ); if (pad_a0 == NULL) {fprintf(fp21, "error allocating pad_a0\n");exit(0);} /* the for loop has been modified as indicated - Prakash */ for(i=0; i< la; i++){ /*for(i=0; i< strlen(a0); i++){ */ pad_a0[i] = a0[i]; } for(i=strlen(a0); i< la; i++){ pad_a0[i] = ' '; } pad_a0[la] = '\0'; a = (unsigned char *)pad_a0; b = (unsigned char *)b0; aend = a + la; bend = b + lb; if(la <= lb) { while(a < aend) if(*a != *b){ retval = ( *a - *b ); break; } else { ++a; ++b; } while(b < bend) if(*b != ' '){ retval = ( ' ' - *b ); break; } else ++b; } else { while(b < bend) if(*a == *b) { ++a; ++b; } else{ retval = ( *a - *b ); break; } while(a < aend) if(*a != ' '){ retval = (*a - ' '); break;} else ++a; } free(pad_a0); return(retval); }
0.945313
high
iOSLHQProject/Classes/LHQControllers/Mine/LHQMeViewVC.h
MrHqLin/iOSLHQProject
0
4890096
// // LHQMeViewVC.h // iOSLHQProject // // Created by LIN on 2018/11/6. // Copyright © 2018年 water. All rights reserved. // #import "LHQTableViewVC.h" #import "LHQStaticTableVC.h" NS_ASSUME_NONNULL_BEGIN @interface LHQMeViewVC : LHQStaticTableVC @end NS_ASSUME_NONNULL_END
0.494141
high
src/util/blob.h
grantae/blob
2
4922864
<filename>src/util/blob.h #ifndef UTIL_BLOB_H #define UTIL_BLOB_H #include "util/container.h" #include "util/fixed_types.h" #include <initializer_list> #include <functional> #include <string> #include <memory> namespace Util { /* A "blob" is a collection of bytes which can contain any type of data. The Blob class acts as a container for and pointer to its underlying data. Blobs can be created as subsets of other Blobs without copying any portion of the underlying data. Blobs can be created and deleted without affecting other blobs, even when they share the same data. The primary motivation for the Blob class is to be able to work on several portions of a large piece of data without ever needing to copy the data and without needing to think about memory management. The following is a summary of the features and behavior of Blobs: - A Blob is read-only, and a MutableBlob is readable and writeable. - If a Blob is created from a raw pointer to data, the data will be copied. Otherwise if it's created from another Blob then none of the underlying data will be copied. - Blobs can be created as arbitrary subsets of existing Blobs without copying any underlying data. - The deletion of any Blob cannot affect any other Blob, even when Blobs are subsets of other Blobs and share the same underlying data. Underlying Blob data is freed automatically when all Blobs which refer to it are deleted. - A MutableBlob is the only object that can modify an instance of underlying data. MutableBlobs cannot be copied or created from MutableBlobs, but Blobs can be created from MutableBlobs (they are single-writer, multiple-reader). A MutableBlob always allocates and copies data instead of sharing with existing Blobs. - Blobs support clearing their data upon deallocation. This is enabled by setting the 'ScrubType' to something other than 'NONE' upon construction. All Blobs which are created from existing Blobs inherit this property. */ class Blob { public: enum class ScrubType { NONE, ZEROS }; enum class CompareType { DEFAULT, CONST }; enum class Comparison { EQ, NE }; typedef std::function<bool(const Blob &a, const Blob &b)> Comparator; typedef std::function<std::unique_ptr<std::string>(const Byte *data, U64 size)> Encoder; typedef std::function<std::unique_ptr<Blob>(const Byte *data, U64 size)> Decoder; public: Blob(U64 size = 0, ScrubType scrubType = ScrubType::NONE, CompareType compareType = CompareType::DEFAULT); Blob(const Byte *stream, U64 size, ScrubType scrubType = ScrubType::NONE, CompareType compareType = CompareType::DEFAULT); Blob(const char *stream, U64 size, ScrubType scrubType = ScrubType::NONE, CompareType compareType = CompareType::DEFAULT); Blob(const Blob &other, U64 size, U64 offset = 0); Blob(const Byte *data, U64 size, Decoder decoder); Blob(const std::string &data); Blob(const std::string &data, Decoder decoder); Blob(std::initializer_list<Blob> blobs, ScrubType scrubType = ScrubType::NONE, CompareType compareType = CompareType::DEFAULT); Blob(const Blob &) = default; Blob(Blob &&) = default; Blob &operator=(const Blob &) = default; Blob &operator=(Blob &&) = default; bool operator==(const Blob &other) const; bool operator!=(const Blob &other) const; const Byte &operator[](U64 index) const; Comparison compare(const Blob &other, CompareType compareType); void dataIs(const Byte *stream, U64 size, ScrubType scrubType = ScrubType::NONE, CompareType compareType = CompareType::DEFAULT); void dataIs(const char *stream, U64 size, ScrubType scrubType = ScrubType::NONE, CompareType compareType = CompareType::DEFAULT); void dataIsNull(); const Byte *data() const; std::unique_ptr<std::string> data(Encoder encoder) const; U64 size() const; ScrubType scrubType() const; CompareType compareType() const; protected: static Container::ScrubType scrubberForType(ScrubType scrubType); static Comparator comparatorForType(CompareType compareType); std::shared_ptr<Container> container_; ScrubType scrubType_; CompareType compareType_; Comparator comparator_; const Byte *data_; U64 size_; }; class MutableBlob : public Blob { public: MutableBlob(U64 size, ScrubType scrubType = ScrubType::NONE, CompareType compareType = CompareType::DEFAULT); MutableBlob(const Byte *stream, U64 size, ScrubType scrubType = ScrubType::NONE, CompareType compareType = CompareType::DEFAULT); MutableBlob(const Blob &other, ScrubType scrubType = ScrubType::NONE, CompareType compareType = CompareType::DEFAULT); MutableBlob(const MutableBlob &) = delete; MutableBlob(MutableBlob &&) = default; MutableBlob &operator=(const MutableBlob &) = delete; MutableBlob &operator=(MutableBlob &&) = default; Byte &operator[](U64 index); Byte *data(); }; } // namespace Util #endif // UTIL_BLOB_H
0.996094
high
src/nm_main_loop.h
meissel/nemu
155
4955632
#ifndef NM_MAIN_LOOP_H_ #define NM_MAIN_LOOP_H_ void nm_start_main_loop(void); #endif /* NM_MAIN_LOOP_H_ */ /* vim:set ts=4 sw=4: */
0.878906
low
ModelViewer/CropVectorsPage.h
scharlton2/modelviewer-mf6
1
4988400
#if !defined(AFX_CROPVECTORSPAGE_H__2447BF73_04BC_40D3_B68F_5B93BC61F475__INCLUDED_) #define AFX_CROPVECTORSPAGE_H__2447BF73_04BC_40D3_B68F_5B93BC61F475__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // CropVectorsPage.h : header file // class CMvDoc; class CVectorDlg; ///////////////////////////////////////////////////////////////////////////// // CCropVectorsPage dialog class CCropVectorsPage : public CPropertyPage { DECLARE_DYNCREATE(CCropVectorsPage) // Construction public: double m_XDelta; double m_XMax; double m_XMin; double m_YDelta; double m_YMax; double m_YMin; double m_ZDelta; double m_ZMax; double m_ZMin; int m_CropAngle; void OnDefault(); void Activate(BOOL b); void Reinitialize(); void Apply(); BOOL CustomUpdateData(BOOL b); CCropVectorsPage(); ~CCropVectorsPage(); CMvDoc* m_pDoc; // Dialog Data //{{AFX_DATA(CCropVectorsPage) enum { IDD = IDD_CROP_VECTORS }; // NOTE - ClassWizard will add data members here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_DATA // Overrides // ClassWizard generate virtual function overrides //{{AFX_VIRTUAL(CCropVectorsPage) public: protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // CVectorDlg *m_Parent; BOOL m_ExchangeData; BOOL m_IsActive; // Implementation protected: // Generated message map functions //{{AFX_MSG(CCropVectorsPage) afx_msg void OnDeltaposXminSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposXmaxSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposYminSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposYmaxSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposZminSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposZmaxSpin(NMHDR* pNMHDR, LRESULT* pResult); virtual BOOL OnInitDialog(); afx_msg void OnDeltaposCropAngleSpin(NMHDR* pNMHDR, LRESULT* pResult); //}}AFX_MSG DECLARE_MESSAGE_MAP() void AssignDefaultValues(); }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CROPVECTORSPAGE_H__2447BF73_04BC_40D3_B68F_5B93BC61F475__INCLUDED_)
0.929688
high
atmel/avr/classes/acb_2.h
gotnone/hwa
0
6554536
<reponame>gotnone/hwa /* * This file is part of the HWA project. * Copyright (c) 2012,2015 <NAME>. * All rights reserved. Read LICENSE.TXT for details. */ /** * @file * @brief Analog Comparator */ /** * @page atmelavr_acb * @section atmelavr_acb_act Actions * * <br> * `configure`: * * __Note__ When the analog comparator shares the analog multiplexer output * with the ADC, the ADC must be turned off for the analog comparator to be able * to use the analog multiplexer output. * * @code * hwa( configure, acmp0, * * [ edge, falling * | rising * | both, ] * * [ positive_input, HW_PIN(ain0) * | bandgap, ] * * [ negative_input, HW_PIN(ain1) * | HW_PIN(adc0..3) ] ); * @endcode */ /* * NOTE: another solution could be the creation of an object `admux0` for * the analog multiplexer that's shared between the ADC and the ACMP but the * ADC and ACMP can not use the analog multiplexer at the same time. Then, it * seems acceptable to make the configuration instructions of the ADC or the * ACMP drive the analog multiplexer transparently. */ #define hwa_configure__acb , _hwa_cfacb /* Optionnal parameter `edge` */ #define _hw_acb_edge_falling , 2 /* ACIS */ #define _hw_acb_edge_rising , 3 #define _hw_acb_edge_both , 0 #define _hwa_cfacb(o,a,k,...) \ do { \ HW_Y(_hwa_cfacb_xedge_,_hw_is_edge_##k)(o,k,__VA_ARGS__,,); \ } while(0) #define _hwa_cfacb_xedge_1(o,k,v,...) \ HW_Y(_hwa_cfacb_vedge_,_hw_acb_edge_##v)(o,v,__VA_ARGS__) #define _hwa_cfacb_vedge_0(o,v,...) \ HW_E_AVL(edge, v, falling | rising | both) #define _hwa_cfacb_vedge_1(o,v,k,...) \ _hwa_write(o,acis, HW_A1(_hw_acb_edge_##v)); \ HW_G2(_hwa_cfacb_xposin,HW_IS(positive_input,k))(o,k,__VA_ARGS__) #define _hwa_cfacb_xedge_0(o,k,...) \ HW_G2(_hwa_cfacb_xposin,HW_IS(positive_input,k))(o,k,__VA_ARGS__) /* Optionnal parameter `positive_input` */ #define _hwa_cfacb_xposin_1(o,k,v,...) \ HW_Y(_hwa_cfacb_vposin_bandgap_,_hw_is_bandgap_##v)(o,v,__VA_ARGS__) #define _hwa_cfacb_vposin_bandgap_1(o,v,k,...) \ _hwa_write(o,acbg,1); \ HW_G2(_hwa_cfacb_xnegin,HW_IS(negative_input,k))(o,k,__VA_ARGS__) #define _hwa_cfacb_vposin_bandgap_0(o,v,k,...) \ if ( HW_ADDRESS(v)==HW_ADDRESS(HW_PIN(ain0)) ) \ _hwa_write(o,acbg,0); \ else \ HWA_ERR("`positive_input` can be `HW_PIN(ain0) | bandgap`, but not `"#v"`."); \ HW_G2(_hwa_cfacb_xnegin,HW_IS(negative_input,k))(o,k,__VA_ARGS__) #define _hwa_cfacb_xposin_0(o,k,...) \ HW_G2(_hwa_cfacb_xnegin,HW_IS(negative_input,k))(o,k,__VA_ARGS__) /* Optionnal parameter `negative_input` */ #define _hwa_cfacb_xnegin_0(o,...) HW_EOL(__VA_ARGS__) #define _hwa_cfacb_xnegin_1(o,k,v,...) \ if ( HW_ADDRESS(v)==HW_ADDRESS(HW_PIN(ain1)) ) { \ _hwa_write(o,acme,0); \ } else { \ _hwa_write(o,acme,1); \ _hwa_write(o,aden,0); \ if ( HW_ADDRESS(v) == HW_ADDRESS( HW_PIN(adc0) ) ) \ _hwa_write(o,admux, 0); \ else if ( HW_ADDRESS(v) == HW_ADDRESS( HW_PIN(adc1) ) ) \ _hwa_write(o,admux, 1); \ else if ( HW_ADDRESS(v) == HW_ADDRESS( HW_PIN(adc2) ) ) \ _hwa_write(o,admux, 2); \ else if ( HW_ADDRESS(v) == HW_ADDRESS( HW_PIN(adc3) ) ) \ _hwa_write(o,admux, 3); \ else \ HWA_ERR("`negative_input` can be `HW_PIN(ain1)`, or any analog input pin, but not `"#v"`."); \ } \ HW_EOL(__VA_ARGS__) #define hw_power__acb , _hw_power #define hwa_power__acb , _hwa_power /******************************************************************************* * * * Context management * * * *******************************************************************************/ #define _hwa_setup__acb(o,a) _hwa_setup_r( o, csr ) #define _hwa_init__acb(o,a) _hwa_init_r( o, csr, 0x00 ) #define _hwa_commit__acb(o,a) _hwa_commit_r( o, csr ) /** * @page atmelavr_acb * @section atmelavr_acb_internals Internals * * Class `_acb` objects hold the following hardware registers: * * * `csr`: control/status register * * that hold the following logical registers: * * * `acme`: analog comparator multiplexer enabled * * `aden`: A/D converter enable * * `admux`: analog multiplexer input select * * `acd` : analog comparator disable (power management) * * `acbg` : analog comparator bandgap select * * `aco` : analog comparator output * * `if` : analog comparator interrupt flag * * `ie` : analog comparator interrupt enable * * `acic` : analog comparator input capture enable * * `acis` : analog comparator interrupt mode select */
0.894531
high
uri.h
gonzus/pizza
0
6587304
<filename>uri.h #ifndef URI_H_ #define URI_H_ /* * URI encoding and decoding using Slice and Buffer */ #include "buffer.h" int uri_decode(Slice encoded, Buffer *decoded); int uri_encode(Slice decoded, Buffer *encoded); #endif
0.980469
high
c/src/sfork.c
catern/sfork
27
8020072
#define _GNU_SOURCE #include <sys/types.h> #include <sys/signal.h> #include <unistd.h> #include <stdint.h> #include <sched.h> #include <setjmp.h> __thread void* sfork_stack_pointer = NULL; /* Pass the stack pointer as an argument so we don't have to access * thread local storage from assembly */ int sfork_asm_clone(void **stack_pointer_p, unsigned long flags, void *child_stack, int *ptid, int *ctid, unsigned long newtls); int sfork_asm_exit(void **stack_pointer_p, int status); int sfork_asm_execveat(void **stack_pointer_p, int dirfd, const char* pathname, char *const argv[], char *const envp[], int flags); int sfork_clone(unsigned long flags, void *child_stack, int *ptid, int *ctid, unsigned long newtls) { /* calling sfork_asm_clone without CLONE_VFORK will break, so we force it on. */ return sfork_asm_clone(&sfork_stack_pointer, flags|CLONE_VFORK, child_stack, ptid, ctid, newtls); }; int sfork() { return sfork_clone(CLONE_VFORK|CLONE_VM|SIGCHLD, NULL, NULL, NULL, 0); }; int sfork_exit(int status) { return sfork_asm_exit(&sfork_stack_pointer, status); }; int sfork_execveat(int dirfd, const char* pathname, char *const argv[], char *const envp[], int flags) { return sfork_asm_execveat(&sfork_stack_pointer, dirfd, pathname, argv, envp, flags); }
0.984375
high
src/Materiel/grovepi.h
lilian59480/Caeli
0
8052840
<reponame>lilian59480/Caeli // Copyright Dexter Industries, 2016 // http://dexterindustries.com/grovepi #ifndef GROVEPI_H #define GROVEPI_H #include <stdio.h> #include <stdlib.h> #include <string.h> //#include <linux/i2c.h> #include <unistd.h> #include <linux/i2c-dev.h> #include <fcntl.h> #include <string.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <stdbool.h> #include <stdint.h> #define G_INPUT 0 #define G_OUTPUT 1 #define G_LOW false #define G_HIGH true void SMBusName (char* smbus_name); // default address of GrovePi set as default argument bool initGrovePi(); void setGrovePiAddress (uint8_t addr); bool writeBlock (uint8_t command, uint8_t pin_number, uint8_t opt1, uint8_t opt2); bool writeByte (uint8_t byte_val); bool readBlock (uint8_t* data_block); uint8_t readByte(); void delay (unsigned int milliseconds); bool pinMode (uint8_t pin, uint8_t mode); bool digitalWrite (uint8_t pin, bool value); uint8_t digitalRead (uint8_t pin); bool analogWrite (uint8_t pin, uint8_t value); int analogRead (uint8_t pin); int ultrasonicRead (uint8_t pin); #endif
0.957031
high
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.dg/ucnid-6.c
best08618/asylo
7
6418832
<gh_stars>1-10 /* { dg-do run } */ /* { dg-xfail-if "" { "powerpc-ibm-aix*" } { "*" } { "" } } */ /* { dg-skip-if "" { ! ucn } { "*" } { "" } } */ /* { dg-options "-std=c99 -save-temps -g" } */ void abort (void); int \u00C0(void) { return 1; } int \u00C1(void) { return 2; } int \U000000C2(void) { return 3; } int wh\u00ff(void) { return 4; } int a\u00c4b\u0441\U000003b4e(void) { return 5; } int main (void) { if (\u00C0() != 1) abort (); if (\u00c1() != 2) abort (); if (\u00C2() != 3) abort (); if (wh\u00ff() != 4) abort (); if (a\u00c4b\u0441\U000003b4e() != 5) abort (); return 0; }
0.859375
high
include/external/seqarrayvector/seqarrayvector.h
eth-cscs/PASC_inference
8
6451600
<reponame>eth-cscs/PASC_inference<filename>include/external/seqarrayvector/seqarrayvector.h #ifndef PASC_SEQARRAYVECTOR_H #define PASC_SEQARRAYVECTOR_H #include "pascinference.h" /* the seqarrayvector variant of general.h */ #include "external/seqarrayvector/common/common.h" #include "external/seqarrayvector/algebra/algebra.h" #endif
0.710938
low
cyclone_objects/binaries/control/rminus.c
ishankumarkaler/pd-cyclone
153
6484368
// Copyright (c) 2016 Porres. #include "m_pd.h" #include <common/api.h> typedef struct _rminus { t_object x_ob; t_float x_f1; t_float x_f2; } t_rminus; static t_class *rminus_class; static void rminus_bang(t_rminus *x) { outlet_float(((t_object *)x)->ob_outlet, x->x_f2 - x->x_f1); } static void rminus_float(t_rminus *x, t_float f) { outlet_float(((t_object *)x)->ob_outlet, x->x_f2 - (x->x_f1 = f)); } static void *rminus_new(t_floatarg f) { t_rminus *x = (t_rminus *)pd_new(rminus_class); floatinlet_new((t_object *)x, &x->x_f2); outlet_new((t_object *)x, &s_float); x->x_f1 = 0; x->x_f2 = f; return (x); } CYCLONE_OBJ_API void rminus_setup(void) { rminus_class = class_new(gensym("rminus"), (t_newmethod)rminus_new, 0, sizeof(t_rminus), 0, A_DEFFLOAT, 0); class_addbang(rminus_class, rminus_bang); class_addfloat(rminus_class, rminus_float); }
0.988281
high
src/yars/configuration/data/DataRecording.h
kzahedi/YARS
4
6517136
<gh_stars>1-10 #ifndef __DATA_RECORDING_H__ #define __DATA_RECORDING_H__ # define YARS_STRING_RECORDING (char*)"recording" # define YARS_STRING_RECORDING_DEFINITION (char*)"recording_definition" #include <yars/configuration/data/DataNode.h> #include <yars/configuration/data/DataParameter.h> #include <yars/configuration/data/DataActuator.h> #include <yars/types/Matrix.h> #include <yars/types/Domain.h> #include <map> #include <vector> #include <string> typedef __Domain<unsigned long> RecordingInterval; using namespace std; class DataRecording : public DataNode, public std::vector<RecordingInterval> { public: DataRecording(DataNode *parent); virtual ~DataRecording() { }; static void createXsd(XsdSpecification *spec); void add(DataParseElement *element); void resetTo(const DataRecording*); DataRecording* copy(); // returns true if current time step is within a recoding interval bool record(); }; #endif // __DATA_RECORDING_H__
0.976563
high
include/rapidschema/concepts/unique_json_types.h
ledergec/rapidschema
3
3349744
<gh_stars>1-10 // Copyright (C) 2019 <NAME> #ifndef INCLUDE_RAPIDSCHEMA_CONCEPTS_UNIQUE_JSON_TYPES_H_ #define INCLUDE_RAPIDSCHEMA_CONCEPTS_UNIQUE_JSON_TYPES_H_ #ifdef RAPIDSCHEMA_WITH_CONCEPTS #include "rapidschema/meta/json_type_set.h" namespace rapidschema { /// \brief Concept checking whether the all the types in the pack are unique. template<typename ... T> concept bool UniqueJsonTypes = internal::JsonTypeSet<T...>::Unique(); } // namespace rapidschema #endif #endif // INCLUDE_RAPIDSCHEMA_CONCEPTS_UNIQUE_JSON_TYPES_H_
0.980469
high
c-program/003process/p_execlp.c
aiter/cs
0
3382512
#include <unistd.h> #include <stdlib.h> #include <stdio.h> int main() { printf("Running ps with execlp\n"); execlp("ps", "ps", "ax", 0); // 不执行下面的逻辑 printf("Done\n"); exit(0); }
0.96875
low
CoX/CoX_Peripheral/CoX_Peripheral_KLx/testframe/test.c
coocox/cox
58
4815280
<reponame>coocox/cox //***************************************************************************** // //! \file test.c //! \brief Tests support code. //! \version 1.0 //! \date 5/19/2011 //! \author CooCox //! \copy //! //! Copyright (c) 2009-2011 CooCox. All rights reserved. // //***************************************************************************** #include "test.h" #include "testcase.h" #ifdef ENHANCE_MODE // // the following const value only used in TestAssert function // #define FSM_BEGIN 0 #define FSM_END 1 #define FSM_CHAR 2 #define FSM_DISPATCH 3 #define NEW_LINE \ "------------------------------------------------------------------------------" typedef void (* VirtualIoPort)(char); // // private function // static uint32 NumToStr (uint32 Num, uint32 Base, uint8 *Buffer, uint32 BufferSize); static uint32 PrintDec (VirtualIoPort pIOPutChar, void * pParam); static uint32 PrintHex (VirtualIoPort pIOPutChar, void * pParam); static uint32 PrintStr (VirtualIoPort pIOPutChar, void * pParam); static uint32 Print (VirtualIoPort pIoPutchar, const char * pcMsg, va_list VarPara); static void BufWrite (char ch); // // Public function // uint32 FILE_Print (const char * pcMsg, ...); uint32 UART_Print (const char * pcMsg, ...); void _TestAssert (const char * pcMsg, ...); #else static void PrintN(unsigned long n); static void Print(char* pcMsg); static void PrintLine(char* pcMsg); static void PrintNewLine(void); static void PrintTokens(void); #endif static void ClearTokens(void); static void ExecuteTest(const tTestCase *psTest); static xtBoolean _TestFail(void); static xtBoolean g_bLocalFail, g_bGlobalFail; // // tokens buffer // static char g_pcTokensBuffer[TEST_TOKENS_MAX_NUM]; // // error string buffer // static char g_pcErrorInfoBuffer[TEST_ERROR_BUF_SIZE]; // // Error Info Buffer Index // static unsigned long ErrorBufIndex; // // current point of the token buffer // static char *g_pcTok; #ifndef ENHANCE_MODE //***************************************************************************** // //! \brief Prints a decimal unsigned number. //! //! \param n is the number to be printed //! //! \details Prints a decimal unsigned number. //! //! \return None. // //***************************************************************************** static void PrintN(unsigned long n) { char buf[16], *p; if (n == 0) { TestIOPut('0'); } else { p = buf; while (n != 0) { *p++ = (n % 10) + '0'; n /= 10; } while (p > buf) TestIOPut(*--p); } } //***************************************************************************** // //! \brief Prints a line without final end-of-line. //! //! \param pcMsg is the message to print //! //! \details Prints a line without final end-of-line. //! //! \return None. // //***************************************************************************** static void Print(char *pcMsg) { while (*pcMsg != '\0') { TestIOPut(*pcMsg++); } } //***************************************************************************** // //! \brief Prints a line. //! //! \param pcMsg is the message to print //! //! \details Prints a line. //! //! \return None. // //***************************************************************************** static void PrintLine(char *pcMsg) { Print(pcMsg); TestIOPut('\r'); TestIOPut('\n'); } //***************************************************************************** // //! \brief Prints a line of "---". //! //! \param None //! //! \return None. // //***************************************************************************** static void PrintNewLine(void) { unsigned int i; for (i = 0; i < 76; i++) { TestIOPut('-'); } TestIOPut('\r'); TestIOPut('\n'); } #endif //***************************************************************************** // //! \brief clear the token buffer //! //! \param None //! //! \return None. // //***************************************************************************** static void ClearTokens(void) { g_pcTok = g_pcTokensBuffer; } #ifndef ENHANCE_MODE //***************************************************************************** // //! \brief Print the tokens. //! //! \param None //! //! //! \return None. // //***************************************************************************** static void PrintTokens(void) { char *pcToken = g_pcTokensBuffer; while (pcToken < g_pcTok) { TestIOPut(*pcToken++); } } #endif //***************************************************************************** // //! \brief Emits a token into the tokens buffer. //! //! \param token is a char to be emit into the buffer //! //! \return None. // //***************************************************************************** void TestEmitToken(char cToken) { TestDisableIRQ(); if(g_pcTok < (g_pcTokensBuffer + TEST_TOKENS_MAX_NUM) ) { *g_pcTok++ = cToken; } TestEnableIRQ(); } #ifndef ENHANCE_MODE //***************************************************************************** // //! \brief Clear Error info buffer. //! //! \param None. //! //! \return None. // //***************************************************************************** static void TestErrorInfoClear(void) { int i = 0; while(i < TEST_ERROR_BUF_SIZE) { g_pcErrorInfoBuffer[i++] = '\0'; } } //***************************************************************************** // //! \brief store the error message. //! //! \param pcMessage is the point of the error message. //! //! \return None. // //***************************************************************************** static void TestErrorInfoStore(char *pcMessage) { int i = 0; while((i < TEST_ERROR_BUF_SIZE-1) && g_pcErrorInfoBuffer[i] != '\0') { i++; } while ((*pcMessage != '\0') && (i < TEST_ERROR_BUF_SIZE-1)) { g_pcErrorInfoBuffer[i++] = *pcMessage++; } g_pcErrorInfoBuffer[i] = '\0'; } //***************************************************************************** // //! \brief store the error message. //! //! \param n is a number. //! //! \return None. // //***************************************************************************** static void TestErrorInfoStoreNumber(unsigned long n) { char buf[16], *p; int i = 0; while((i < TEST_ERROR_BUF_SIZE-1) && g_pcErrorInfoBuffer[i] != '\0') { i++; } if (n == 0 && (i < TEST_ERROR_BUF_SIZE-1)) { g_pcErrorInfoBuffer[i++] = '0'; } else { p = buf; while (n != 0) { *p++ = (n % 10) + '0'; n /= 10; } while (p > buf) { g_pcErrorInfoBuffer[i++] = *--p; } } g_pcErrorInfoBuffer[i] = '\0'; } #endif //***************************************************************************** // //! \brief set the global value of error flag. //! //! \return None. // //***************************************************************************** static xtBoolean _TestFail(void) { g_bLocalFail = xtrue; g_bGlobalFail = xtrue; return xtrue; } #ifndef ENHANCE_MODE //***************************************************************************** // //! \brief Test assertion. //! //! \param pcFile is the current file name. usually is \b __FILE__ //! \param ulLine is the current line number. usually is \b __LINE__ //! \param bCondition is the checking expr. \b xtrue, \bxfalse //! \param pcMsg failure message //! //! \details The TestAssert macro, which does the actual assertion checking. //! //! \return None. // //***************************************************************************** xtBoolean _TestAssert(char* pcFile, unsigned long ulLine, xtBoolean bCondition, char * pcMsg) { if (bCondition == xfalse) { TestErrorInfoClear(); TestErrorInfoStore("\r\nFile:\t"); TestErrorInfoStore(pcFile); TestErrorInfoStore("\r\nLine:\t"); TestErrorInfoStoreNumber(ulLine); TestErrorInfoStore("\r\nError:\t"); TestErrorInfoStore(pcMsg); return _TestFail(); } return xfalse; } #endif //***************************************************************************** // //! \brief Test sequence assertion. //! //! \param pcExpected is the expect token seq. //! \param ulDelay wait delay time //! //! \details Test sequence assertion. //! \note If ulDelay is -1,then this will not break until sequence token is //! finished! if ulDelay is not -1,then it will be wait delay time.ulDelay //! is 0,show that there will be no delay! //! //! \return None. // //***************************************************************************** xtBoolean _TestAssertSequenceBreak(char *pcExpected, unsigned long ulDelay) { char *cp = g_pcTokensBuffer; unsigned long ulTemp = ulDelay; do { while (cp < g_pcTok) { if (*cp++ != *pcExpected++) { return _TestFail(); } } SysCtlDelay(1); if (*pcExpected == '\0') { ClearTokens(); return xfalse; } if (ulDelay == 0xFFFFFFFF) { ulTemp = 1; } else if(ulDelay != 0) { ulTemp--; } } while(ulTemp); return _TestFail(); } //***************************************************************************** // //! \brief Execute the test. //! //! \param psTest is the point of the test case. //! //! \details Test suite execution. //! //! \return None. // //***************************************************************************** static void ExecuteTest(const tTestCase *psTest) { // // Initialization // ClearTokens(); g_bLocalFail = xfalse; if (psTest->Setup != 0) { psTest->Setup(); } psTest->Execute(); if (psTest->TearDown != 0) { psTest->TearDown(); } } #ifndef ENHANCE_MODE //***************************************************************************** // //! \brief Test execution thread function. //! //! \param None //! //! \details Test execution thread function. //! //! \return The test result xtrue or xfalse. // //***************************************************************************** xtBoolean TestMain(void) { int i, j; TestIOInit(); PrintLine(""); PrintLine("*** CooCox CoIDE components test suites"); PrintLine("***"); #ifdef TEST_COMPONENTS_NAME Print("*** Components: "); PrintLine(TEST_COMPONENTS_NAME); #endif #ifdef TEST_COMPONENTS_VERSION Print("*** Version: "); PrintLine(TEST_COMPONENTS_VERSION); #endif #ifdef TEST_BOARD_NAME Print("*** Test Board: "); PrintLine(TEST_BOARD_NAME); #endif PrintLine(""); g_bGlobalFail = xfalse; i = 0; while (g_psPatterns[i]) { j = 0; while (g_psPatterns[i][j]) { PrintNewLine(); Print("--- Test Case "); PrintN(i + 1); Print("."); PrintN(j + 1); Print(" ("); Print(g_psPatterns[i][j]->GetTest()); PrintLine(")"); ExecuteTest(g_psPatterns[i][j]); if (g_bLocalFail == xtrue) { Print("--- Result: FAILURE "); PrintLine(""); // //printf error information // Print(g_pcErrorInfoBuffer); PrintLine(""); if (g_pcTokensBuffer < g_pcTok) { Print(" The tokens in buffer is: "); PrintTokens(); PrintLine(""); } } else { PrintLine("--- Result: SUCCESS "); } j++; } i++; } PrintNewLine(); PrintLine(""); Print("Final result: "); if (g_bGlobalFail == xtrue) PrintLine("FAILURE"); else PrintLine("SUCCESS"); return g_bGlobalFail; } #endif // // Enhance Mode // #ifdef ENHANCE_MODE static uint32 NumToStr(uint32 Num, uint32 Base, uint8 *Buffer, uint32 BufferSize) { uint32 tmpNum = Num; uint32 index = 0; uint32 Strlen = 0; const uint8 * NumStr = (uint8 *)"0123456789ABCDEF"; if((Buffer == NULL) || (BufferSize == 0)) { Strlen = 0; return (Strlen); } if(tmpNum == 0) { *Buffer = '0'; *(Buffer+1) = '\0'; Strlen = 1; return (Strlen); } while(tmpNum) { tmpNum /= Base; index++; } Strlen = index; if(Strlen > (BufferSize-1)) { Strlen = 0; return (Strlen); } *(Buffer + index) = '\0'; tmpNum = Num; while(tmpNum) { --index; *(Buffer + index) = (uint8)*(tmpNum%Base + NumStr); tmpNum /= Base; } return (Strlen); } static uint32 PrintDec(VirtualIoPort pIOPutChar, void * pParam) { #define BUF_SIZE 16 uint32 i = 0; uint32 NumOfChar = 0; uint32 DecValue = 0; uint8 Buf[BUF_SIZE] = {0}; // // check the argument // if(NULL == pParam) { return NumOfChar; } DecValue = (uint32)pParam; // // Clear the memory // for(i = 0; i < BUF_SIZE; i++) { Buf[i] = '\0'; } // // Convert num to dec format // NumToStr(DecValue, 10, &Buf[0], BUF_SIZE); // // Output String to IO port,and count the num of chars // for(i = 0; (i < BUF_SIZE) && ('\0' != Buf[i]); i++) { (*pIOPutChar)(Buf[i]); NumOfChar++; } return NumOfChar; #undef BUF_SIZE } static uint32 PrintStr(VirtualIoPort pIOPutChar, void * pParam) { uint32 NumOfChar = 0; uint8 *pStr = 0; // // Check the argument // if(NULL == pParam) { return NumOfChar; } pStr = (uint8 *) pParam; // // Output the string and count the number of char // while(*pStr) { NumOfChar++; (*pIOPutChar)(*pStr++); } return NumOfChar; } static uint32 PrintHex(VirtualIoPort pIOPutChar, void * pParam) { #define BUF_SIZE 16 uint32 i = 0; uint32 NumOfChar = 0; uint32 HexValue = 0; uint8 Buf[BUF_SIZE] = {'0','X'}; // // check the argument // if(NULL == pParam) { return NumOfChar; } HexValue = (uint32)pParam; // // Clear the memory, expect the first two value('0','X') // for(i = 2; i < BUF_SIZE; i++) { Buf[i] = '\0'; } // // Convert num to hex format // NumToStr(HexValue, 16, &Buf[2], (BUF_SIZE-2)); // // Output String to IO port,and count the num of chars // for(i = 0; (i < BUF_SIZE) && ('\0' != Buf[i]); i++) { (*pIOPutChar)(Buf[i]); NumOfChar++; } return NumOfChar; #undef BUF_SIZE } uint32 Print(VirtualIoPort pIoPutchar, const char * pcMsg, va_list VarPara) { uint8 Token = 0; uint32 NumOfChar = 0; const char * pStr = pcMsg; uint32 FSM_Status = FSM_BEGIN; // //vaild pointer, return 0 // if(NULL == pStr) { return 0; } // // use FSM(Fimit state Machine) to deal string // while(1) { switch(FSM_Status) { case FSM_BEGIN: { Token = *pStr; if('\0' == Token) { FSM_Status = FSM_END; } else if('%' == Token) { pStr += 1; FSM_Status = FSM_DISPATCH; } else { FSM_Status = FSM_CHAR; } break; } case FSM_CHAR: { (*pIoPutchar)(*pStr++); NumOfChar++; FSM_Status = FSM_BEGIN; break; } case FSM_DISPATCH: { Token = *pStr++; FSM_Status = FSM_BEGIN; switch(Token) { case 'x': case 'X': { uint32 InputPara = 0; InputPara = va_arg(VarPara, uint32); NumOfChar += PrintHex(pIoPutchar, (void *)InputPara); break; } case 'd': { uint32 InputPara = 0; InputPara = va_arg(VarPara, uint32); NumOfChar += PrintDec(pIoPutchar, (void *)InputPara); break; } case 's': { uint8 *InputPara = 0; InputPara = va_arg(VarPara, uint8 *); NumOfChar += PrintStr(pIoPutchar, (void *)InputPara); break; } // // If you want to add new function, add your code here // for example: you can add %p feature in ErrorPrint // for you can print the address of varilable // // case 'p': // { // //your code is here // // uint8 *InputPara = 0; // InputPara = va_arg(pVar, uint8 *); // NumOfChar += PrintPointer(pIoPutchar, (void *)InputPara); // break; // } // default: { (*pIoPutchar)(Token); NumOfChar++; break; } } break; } case FSM_END: { va_end(pVar); return NumOfChar; } } } } static void BufWrite(char ch) { if(ErrorBufIndex < TEST_ERROR_BUF_SIZE) { g_pcErrorInfoBuffer[ErrorBufIndex++] = ch; } } uint32 FILE_Print(const char * pcMsg, ...) { uint32 count = 0; va_list InputVar; va_start(InputVar, pcMsg); count = Print(BufWrite, pcMsg, InputVar); va_end(InputVar); return count; } uint32 UART_Print(const char * pcMsg, ...) { uint32 count = 0; va_list InputVar; va_start(InputVar, pcMsg); count = Print(TestIOPut, pcMsg, InputVar); va_end(InputVar); return count; } void _TestAssert(const char * pcMsg, ...) { va_list InputVar; ErrorBufIndex = 0; memset(g_pcErrorInfoBuffer, '\0', TEST_ERROR_BUF_SIZE); va_start(InputVar, pcMsg); Print(BufWrite, pcMsg, InputVar); va_end(InputVar); _TestFail(); } //***************************************************************************** // //! \brief Test execution thread function. //! //! \param None //! //! \details Test execution thread function. //! //! \return The test result xtrue or xfalse. // //***************************************************************************** xtBoolean TestMain(void) { uint32 i = 0; uint32 j = 0; TestIOInit(); UART_Print("\r\n*** CooCox CoIDE components test suites\r\n"); #ifdef TEST_COMPONENTS_NAME UART_Print("*** Components: %s\r\n", TEST_COMPONENTS_NAME); #endif #ifdef TEST_COMPONENTS_VERSION UART_Print("*** Version : %s\r\n", TEST_COMPONENTS_VERSION); #endif #ifdef TEST_BOARD_NAME UART_Print("*** Test Board: %s\r\n", TEST_BOARD_NAME); #endif g_bGlobalFail = xfalse; i = 0; while (g_psPatterns[i]) { j = 0; while (g_psPatterns[i][j]) { UART_Print("%s\r\n--- Test Case %d.%d", NEW_LINE, i+1, j+1); UART_Print("(%s)\r\n", g_psPatterns[i][j]->GetTest()); ExecuteTest(g_psPatterns[i][j]); if (g_bLocalFail == xtrue) { UART_Print("--- Result: FAILURE \r\n%s\r\n", g_pcErrorInfoBuffer); if (g_pcTokensBuffer < g_pcTok) { UART_Print(" The tokens in buffer is: %s\r\n", g_pcTokensBuffer); } } else { UART_Print("--- Result: SUCCESS \r\n"); } j++; } i++; } if (g_bGlobalFail == xtrue) { UART_Print("%s\r\nFinal result: FAILURE\r\n", NEW_LINE); } else { UART_Print("%s\r\nFinal result: SUCCESS\r\n", NEW_LINE); } return g_bGlobalFail; } #endif
0.996094
high
admin/wmi/wbem/providers/win32provider/providers/pagefile.h
npocmaka/Windows-Server-2003
17
4848048
//================================================================= // // PageFile.h -- PageFile property set provider // // Copyright (c) 1996-2001 Microsoft Corporation, All Rights Reserved // // Revisions: 08/01/96 a-jmoon Created // 03/01/99 a-peterc Cleanup // //================================================================= // Property set identification //============================ #define PROPSET_NAME_PageFile L"Win32_PageFile" #define PAGEFILE_REGISTRY_KEY _T("System\\CurrentControlSet\\Control\\Session Manager\\Memory Management") #define PAGING_FILES _T("PagingFiles") // corresponds to info found in NT registry class PageFileInstance { public: CHString name; UINT min; UINT max; public: PageFileInstance(); }; // twenty six possible drive letters, twenty six possible page files... #define PageFileInstanceArray PageFileInstance * class PageFile : public CCIMDataFile { private: HRESULT GetPageFileData( CInstance *a_pInst, bool a_fValidate ) ; HRESULT GetAllPageFileData( MethodContext *a_pMethodContext ) ; // NT only DWORD GetPageFileInstances( PageFileInstanceArray a_instArray ) ; HRESULT PutPageFileInstances( PageFileInstanceArray a_instArray, DWORD a_dwCount ) ; protected: // Overridable function inherited from CCIMLogicalFile needs to // implement this here since this class is derived from CCimDataFile // (both C++ and MOF derivation). CCimDataFile calls IsOneOfMe. // The most derived instance will be called. If not implemented here, // CCimDataFile will be used, which will commit for datafiles. // However, If CCimDataFile does not return FALSE from its IsOneOfMe, // which it won't do if not implemented here, all data files // will be assigned to this class. virtual BOOL IsOneOfMe(LPWIN32_FIND_DATA a_pstFindData, LPCTSTR a_tstrFullPathName); public: // Constructor/destructor //======================= PageFile( LPCWSTR name, LPCWSTR pszNamespace ) ; ~PageFile() ; // Functions provide properties with current values //================================================= virtual HRESULT EnumerateInstances( MethodContext *a_pMethodContext, long a_pInst = 0L ) ; virtual HRESULT GetObject( CInstance *a_pInst, long a_lFlags, CFrameworkQuery& pQuery ) ; virtual HRESULT ExecQuery(MethodContext* pMethodContext, CFrameworkQuery& pQuery, long lFlags = 0L); // NT ONLY virtual HRESULT PutInstance( const CInstance &a_pInst, long a_lFlags = 0L ) ; virtual HRESULT DeleteInstance( const CInstance &a_pInst, long a_lFlags = 0L ) ; } ;
0.988281
high
light.h
bajabob/CSCE-441-Project-5
0
214384
<reponame>bajabob/CSCE-441-Project-5 #ifndef LIGHT_H_ #define LIGHT_H_ #include <armadillo> using arma::vec; using arma::fvec; class light{ public: light(const vec &position, const fvec &color, const double &diffuse) : position(position), color(color), diffuse(diffuse) {} vec get_position() const{ return position; } fvec get_color() const{ return color; } double get_diffuse() const{ return diffuse; } private: vec position; fvec color; double diffuse; }; #endif /* LIGHT_H_ */
0.828125
high
lib/libc/mingw/libsrc/atsmedia-uuid.c
aruniiird/zig
12,718
247152
<gh_stars>1000+ /* from atsmedia.h */ #define INITGUID #include <basetyps.h> DEFINE_GUID(BDANETWORKTYPE_ATSC, 0x71985F51, 0x1CA1, 0x11D3, 0x9C, 0xC8, 0x0, 0xC0, 0x4F, 0x79, 0x71, 0xE0);
0.777344
low
vmdir/server/include/vmacl.h
slachiewicz/lightwave
1
279920
/* * Copyright © 2012-2015 VMware, Inc. 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. */ /* * Module Name: Directory Schema * * Filename: vmacl.h * * Abstract: * * ACL api * */ #ifndef __VIDRACL_H__ #define __VIDRACL_H__ #ifdef __cplusplus extern "C" { #endif #define VMDIR_LEADING_ORGANIZATION_O "o=" #define VMDIR_LEADING_ORGANIZATION_DC "dc=" #define VMDIR_PARTS_ORGANIZATION_O ",o=" #define VMDIR_PARTS_ORGANIZATION_DC ",dc=" #define VMDIR_DEFAULT_SD_RELATIVE_SIZE 512 #define VMDIR_ACCESS_DENIED_ERROR_MSG "Insufficient access, access denied" #define VMDIR_SD_CREATION_ERROR_MSG "Security descriptor creation failed" /* Access Mask bits: // 4 bits - Generic Access Rights (given in request) // 2 bits - Unused // 2 bits - Special Access Rights // 3 bits - Unused // 5 bits - Standard Access Rights // 16 bits - Specific Access Rights */ // SJ-TBD: Following definitions should really be picked from lw/security-types.h #define ADS_RIGHT_DELETE 0x10000 #define ADS_RIGHT_READ_CONTROL 0x20000 #define ADS_RIGHT_WRITE_DAC 0x40000 #define ADS_RIGHT_WRITE_OWNER 0x80000 #define ADS_RIGHT_SYNCHRONIZE 0x100000 #define ADS_RIGHT_ACCESS_SYSTEM_SECURITY 0x1000000 #define ADS_RIGHT_GENERIC_READ 0x80000000 #define ADS_RIGHT_GENERIC_WRITE 0x40000000 #define ADS_RIGHT_GENERIC_EXECUTE 0x20000000 #define ADS_RIGHT_GENERIC_ALL 0x10000000 #define ADS_RIGHT_DS_CREATE_CHILD 0x1 #define ADS_RIGHT_DS_DELETE_CHILD 0x2 #define ADS_RIGHT_ACTRL_DS_LIST 0x4 #define ADS_RIGHT_DS_SELF 0x8 #define ADS_RIGHT_DS_READ_PROP 0x10 #define ADS_RIGHT_DS_WRITE_PROP 0x20 #define ADS_RIGHT_DS_DELETE_TREE 0x40 #define ADS_RIGHT_DS_LIST_OBJECT 0x80 #define ADS_RIGHT_DS_CONTROL_ACCESS 0x100 // // Specific Access Rights for Directory Entry // // read access within the context of entry, in other words, its attributes #define VMDIR_RIGHT_DS_READ_PROP ADS_RIGHT_DS_READ_PROP // write access within the context of entry, in other words, its attributes #define VMDIR_RIGHT_DS_WRITE_PROP ADS_RIGHT_DS_WRITE_PROP // write access in order to add child entry in a container entry #define VMDIR_RIGHT_DS_CREATE_CHILD ADS_RIGHT_DS_CREATE_CHILD // write access in order to delete child entry in a container entry #define VMDIR_RIGHT_DS_DELETE_CHILD ADS_RIGHT_DS_DELETE_CHILD #define VMDIR_ENTRY_GENERIC_EXECUTE ADS_RIGHT_GENERIC_EXECUTE #define VMDIR_ENTRY_ALL_ACCESS (VMDIR_RIGHT_DS_READ_PROP | VMDIR_RIGHT_DS_WRITE_PROP | \ VMDIR_RIGHT_DS_CREATE_CHILD | VMDIR_RIGHT_DS_DELETE_CHILD | \ VMDIR_ENTRY_GENERIC_EXECUTE) // Well-know Local SIDs (should be obsolete shortly) #define VMDIR_DEFAULT_ADMIN_SID "S-1-7-32-500" #define VMDIR_DEFAULT_BUILTIN_ADMINISTRATORS_GROUP_SID "S-1-7-32-544" #define VMDIR_DEFAULT_BUILTIN_USERS_GROUP_SID "S-1-7-32-545" #define VMDIR_EVERY_ONE_GROUP_SID "S-1-1-0" // Well-known RIDs #define VMDIR_DOMAIN_USER_RID_ADMIN 500 // Administrator user #define VMDIR_DOMAIN_ALIAS_RID_ADMINS 544 // BUILTIN\Administrators group #define VMDIR_DOMAIN_ALIAS_RID_USERS 545 // BUILTIN\Users group // Rids higher than this '999' are not "well-known" // For instance, regular users/groups) #define VMDIR_DOMAIN_USER_RID_MAX 999 // Pre-defined GUID used to construct domainSid for host instance // metadata before Replication can be setup // For instance, (1) dc=com and (2) dc=vmwhost,dc=com // (the host instance created by running vdcpromo the first time) #define VMDIR_GUID_STRING_FOR_ROOT_DOMAIN "00000000-0000-0001-8888-000000000000" #define VMDIR_RID_STACK_SEPARATOR ':' typedef struct _VDIR_DOMAIN_SID_GEN_STATE { PSTR pszDomainDn; // in order to search with a given DN PSTR pszDomainSid; // comparably to domainSid DWORD dwDomainRidSeqence; DWORD dwCount; LW_HASHTABLE_NODE Node; } VDIR_DOMAIN_SID_GEN_STATE, *PVDIR_DOMAIN_SID_GEN_STATE; typedef struct _VDIR_SID_GEN_STATE { // NOTE: order of fields MUST stay in sync with struct initializer... PVMDIR_MUTEX mutex; PLW_HASHTABLE pHashtable; PVDIR_THREAD_INFO pRIDSyncThr; PVMDIR_TSSTACK pStack; } VDIR_SID_GEN_STATE, *PVDIR_SID_GEN_STATE; extern VDIR_SID_GEN_STATE gSidGenState; // objectSid.c DWORD VmDirAdvanceDomainRID( DWORD dwCnt ); DWORD VmDirGenerateObjectSid( PVDIR_ENTRY pEntry, PSTR * ppszObjectSid ); DWORD VmDirIsDomainObjectWithEntry( PVDIR_ENTRY pEntry, PBOOLEAN pbIsDomainObject ); DWORD VmDirInternalRemoveOrgConfig( PVDIR_OPERATION pOperation, PSTR pszDomainDN ); PCSTR VmDirFindDomainDN( PCSTR pszObjectDN ); DWORD VmDirGenerateWellknownSid( PCSTR pszDomainDN, DWORD dwWellKnowRid, PSTR* ppszAdminSid ); DWORD VmDirFindDomainSidRid( PCSTR pszObjectSid, PSTR* ppszDomainSid, PDWORD pdwRid ); DWORD VmDirGetSidGenStateIfDomain_inlock( PCSTR pszObjectDN, PSTR pszGuid, /* optional Guid used to generate sid */ PVDIR_DOMAIN_SID_GEN_STATE* ppDomainState ); // libmain.c DWORD VmDirVmAclInit( VOID ); VOID VmDirVmAclShutdown( VOID ); // acl.c DWORD VmDirSrvCreateAccessTokenWithEntry( PVDIR_ENTRY pEntry, PACCESS_TOKEN* ppToken, PSTR* ppszObjectSid /* Optional */ ); DWORD VmDirSrvAccessCheck( PVDIR_OPERATION pOperation, /* optional */ PVDIR_ACCESS_INFO pAccessInfo, PVDIR_ENTRY pEntry, ACCESS_MASK AccessDesired ); VOID VmDirAclCtxContentFree( PVDIR_ACL_CTX pAclCtx ); DWORD VmDirSrvCreateDefaultSecDescRel( PSTR pszSystemAdministratorDn, PSTR pszAdminsGroupSid, PSECURITY_DESCRIPTOR_RELATIVE* ppSecDescRel, PULONG pulSecDescLength, PSECURITY_INFORMATION pSecInfo ); DWORD VmDirGetObjectSidFromDn( PSTR pszObjectDn, PSID* ppSid ); VOID VmDirFreeAbsoluteSecurityDescriptor( PSECURITY_DESCRIPTOR_ABSOLUTE *ppSecDesc ); DWORD VmDirSrvAccessCheckIsAdminRole( PVDIR_OPERATION pOperation, /* Optional */ PCSTR pszNormTargetDN, /* Mandatory */ PVDIR_ACCESS_INFO pAccessInfo, /* Mandatory */ PBOOLEAN pbIsAdminRole ); BOOLEAN VmDirIsFailedAccessInfo( PVDIR_ACCESS_INFO pAccessInfo ); // security.c DWORD VmDirGetSecurityInformationFromSD( PSECURITY_DESCRIPTOR_RELATIVE pSecDesc, PSECURITY_INFORMATION pSecInfo ); DWORD VmDirGetSecurityDescriptorForDn( PSTR pszObjectDn, SECURITY_INFORMATION SecurityInformation, PSECURITY_DESCRIPTOR_RELATIVE* ppSecDesc, PULONG pulSecDescLength ); DWORD VmDirGetSecurityDescriptorForEntry( PVDIR_ENTRY pEntry, SECURITY_INFORMATION SecurityInformation, PSECURITY_DESCRIPTOR_RELATIVE* ppSecDesc, PULONG pulSecDescLength ); DWORD VmDirSetSecurityDescriptorForDn( PSTR pszObjectDn, SECURITY_INFORMATION SecurityInformation, PSECURITY_DESCRIPTOR_RELATIVE pSecDescRel, ULONG ulSecDescRel ); DWORD VmDirSetSecurityDescriptorForEntry( PVDIR_ENTRY pEntry, SECURITY_INFORMATION SecurityInformation, PSECURITY_DESCRIPTOR_RELATIVE pSecDescRel, ULONG ulSecDescRel ); #ifdef __cplusplus } #endif #endif /* __VIDRACL_H__ */
0.996094
high
text/library/gpuimageplus/src/main/jni/include/cgeGLFunctions.h
qwertyezi/test
0
312688
<filename>text/library/gpuimageplus/src/main/jni/include/cgeGLFunctions.h /* * cgeGLFunctions.h * * Created on: 2013-12-5 * Author: <NAME> * Mail: <EMAIL> */ #ifndef _CGEGLFUNCTIONS_H_ #define _CGEGLFUNCTIONS_H_ #include "cgeCommonDefine.h" #include <cassert> #if defined(_CGE_DISABLE_GLOBALCONTEXT_) && _CGE_DISABLE_GLOBALCONTEXT_ #define CGE_ENABLE_GLOBAL_GLCONTEXT(...) #define CGE_DISABLE_GLOBAL_GLCONTEXT(...) #else #define CGE_ENABLE_GLOBAL_GLCONTEXT(...) cgeEnableGlobalGLContext() #define CGE_DISABLE_GLOBAL_GLCONTEXT(...) cgeDisableGlobalGLContext() #endif namespace CGE { #if !(defined(_CGE_DISABLE_GLOBALCONTEXT_) && _CGE_DISABLE_GLOBALCONTEXT_) typedef bool (*CGEEnableGLContextFunction)(void*); typedef bool (*CGEDisableGLContextFunction)(void*); void cgeSetGLContextEnableFunction(CGEEnableGLContextFunction func, void* param); void cgeSetGLContextDisableFunction(CGEDisableGLContextFunction func, void* param); void* cgeGetGLEnableParam(); void* cgeGetGLDisableParam(); void cgeStopGlobalGLEnableFunction(); void cgeRestoreGlobalGLEnableFunction(); void cgeEnableGlobalGLContext(); void cgeDisableGlobalGLContext(); #endif // CGEBufferLoadFun 的返回值将作为 CGEBufferUnloadFun 的第一个参数 // CGEBufferLoadFun 的参数 arg 将作为 CGEBufferUnloadFun 的第二个参数 typedef void* (*CGEBufferLoadFun)(const char* sourceName, void** bufferData, GLint* w, GLint* h, CGEBufferFormat* fmt, void* arg); typedef bool (*CGEBufferUnloadFun)(void* arg1, void* arg2); //加载纹理回调, 注, 为了保持接口简洁性, 回调返回的纹理单元将由调用者负责释放 //返回的纹理不应该为 glDeleteTextures 无法处理的特殊纹理类型. typedef GLuint (*CGETextureLoadFun)(const char* sourceName, GLint* w, GLint* h, void* arg); //You can set a common function for loading textures void cgeSetCommonLoadFunction(CGEBufferLoadFun fun, void* arg); void cgeSetCommonUnloadFunction(CGEBufferUnloadFun fun, void* arg); void* cgeLoadResourceCommon(const char* sourceName, void** bufferData, GLint* w, GLint* h, GLenum* format, GLenum* type); CGEBufferLoadFun cgeGetCommonLoadFunc(); void* cgeGetCommonLoadArg(); bool cgeUnloadResourceCommon(void* bufferArg); CGEBufferUnloadFun cgeGetCommonUnloadFunc(); void* cgeGetCommonUnloadArg(); char* cgeGetScaledBufferInSize(const void* buffer, int& w, int& h, int channel, int maxSizeX, int maxSizeY); char* cgeGetScaledBufferOutofSize(const void* buffer, int& w, int& h, int channel, int minSizeX, int minSizeY); inline GLint cgeGetMaxTextureSize() { GLint n; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &n); return n-1; } class SharedTexture { public: SharedTexture() : m_textureID(0), m_refCount(nullptr), width(0), height(0) {} SharedTexture(GLuint textureID, int w, int h); SharedTexture(const SharedTexture& other) : m_textureID(0), m_refCount(nullptr) { *this = other; } ~SharedTexture(); inline SharedTexture& operator =(const SharedTexture& other) { assert(this != &other && other.m_textureID != 0); if(m_refCount != nullptr && --*m_refCount <= 0) { clear(); } m_textureID = other.m_textureID; m_refCount = other.m_refCount; if (m_refCount) { ++*m_refCount; CGE_LOG_INFO("CGESharedTexture assgin: textureID %d, refCount: %d\n", m_textureID, *m_refCount); } width = other.width; height = other.height; return *this; } inline GLuint texID() const { return m_textureID; } inline void bindToIndex(GLint index) const { glActiveTexture(GL_TEXTURE0 + index); glBindTexture(GL_TEXTURE_2D, m_textureID); } void forceRelease(bool bDelTexture); //特殊用法, 与 forceRelease 配对使用 inline void forceAssignTextureID(GLuint texID) { m_textureID = texID; } public: int width; //public, for easy accessing. int height; protected: void clear(); private: GLuint m_textureID; mutable int* m_refCount; }; class FrameBuffer { public: FrameBuffer() { glGenFramebuffers(1, &m_framebuffer); } ~FrameBuffer() { glDeleteFramebuffers(1, &m_framebuffer); } inline void bind() const { glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer); } inline void bindTexture2D(const SharedTexture& texture, GLenum attachment = GL_COLOR_ATTACHMENT0) const { bindTexture2D(texture.texID(), texture.width, texture.height, attachment); } inline void bindTexture2D(const SharedTexture& texture, GLsizei x, GLsizei y, GLsizei w, GLsizei h, GLenum attachment = GL_COLOR_ATTACHMENT0) const { bindTexture2D(texture.texID(), x, y, w, h, attachment); } inline void bindTexture2D(GLuint texID, GLsizei w, GLsizei h, GLenum attachment = GL_COLOR_ATTACHMENT0) const { bindTexture2D(texID, 0, 0, w, h, attachment); } inline void bindTexture2D(GLuint texID, GLenum attachment = GL_COLOR_ATTACHMENT0) const { bind(); glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, texID, 0); CGE_LOG_CODE( if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { CGE_LOG_ERROR("CGE::FrameBuffer::bindTexture2D - Frame buffer is not valid!"); } ) } inline void bindTexture2D(GLuint texID, GLsizei x, GLsizei y, GLsizei w, GLsizei h, GLenum attachment = GL_COLOR_ATTACHMENT0) const { bindTexture2D(texID, attachment); glViewport(x, y, w, h); } inline GLuint getID() { return m_framebuffer; } private: GLuint m_framebuffer; }; struct CGESizei { CGESizei(): width(0), height(0) {} CGESizei(int w, int h) : width(w), height(h) {} void set(int w, int h) { width = w; height = h; } bool operator ==(const CGESizei &other) const { return width == other.width && height == other.height; } bool operator !=(const CGESizei &other) const { return width != other.width || height != other.height; } GLint width; GLint height; }; struct CGESizef { CGESizef() : width(0.0f), height(0.0f) {} CGESizef(float w, float h) : width(w), height(h) {} void set(float w, float h) { width = w; height = h; } GLfloat width; GLfloat height; }; #ifndef CGE_MIN template<typename Type> inline Type CGE_MIN(Type a, Type b) { return a < b ? a : b; } #endif #ifndef CGE_MAX template<typename Type> inline Type CGE_MAX(Type a, Type b) { return a > b ? a : b; } #endif #ifndef CGE_MID template<typename Type> inline Type CGE_MID(Type n, Type vMin, Type vMax) { if(n < vMin) n = vMin; else if(n > vMax) n = vMax; return n; } #endif #ifndef CGE_MIX template<typename OpType, typename MixType> inline auto CGE_MIX(OpType a, OpType b, MixType value) -> decltype(a - a * value + b * value) { return a - a * value + b * value; } #endif struct CGELuminance { enum { CalcPrecision = 16 }; enum { Weight = (1<<CalcPrecision) }; enum { RWeight = int(0.299*Weight), GWeight = int(0.587*Weight), BWeight = int(0.114*Weight) }; static inline int RGB888(int r, int g, int b) { return (r * RWeight + g * GWeight + b * BWeight) >> CalcPrecision; } //color 从低位到高位的顺序为r-g-b, 传参时需要注意大小端问题 static inline int RGB565(unsigned short color) { const int r = (color & 31) << 3; const int g = ((color >> 5) & 63) << 2; const int b = ((color >> 11) & 31) << 3; return RGB888(r, g, b); } }; } ////////////////////////////////////////////////////////////////////////// #include <vector> #include <ctime> #include <memory> #include "cgeShaderFunctions.h" #include "cgeImageHandler.h" #include "CGEImageFilter.h" #endif /* _CGEGLFUNCTIONS_H_ */
0.996094
high
mcu/tty/rpc.h
somebyte/S32K144ZENKIT
3
1878824
/* * rpc.h * * Created on: Feb 20, 2021 * Author: somebyte */ #ifndef RPC_RPC_H_ #define RPC_RPC_H_ #include "cmdtree.h" typedef int (*extra_ptr_t)(void); /* ROOT of command tree */ extern cmdtree_ptr_t proctree_ptr; cmdtree_ptr_t proctree_init (); void proctree_reset (); int callproc (const char* instruction); /* virtual methods */ extern extra_ptr_t extra_proctree; extern extra_ptr_t extra_help; #endif /* RPC_RPC_H_ */
0.75
high
tools/Debugging Tools for Windows/winext/manifest/com.h
labh-dot/VisualStudio
2,630
1911592
<filename>tools/Debugging Tools for Windows/winext/manifest/com.h category ComponentObjectModel: interface IUnknown { HRESULT QueryInterface( [IID] REFIID iid, [out] COM_INTERFACE_PTR* ppvObject ); ULONG AddRef(); ULONG Release(); }; typedef IUnknown* LPUNKNOWN; interface IClassFactory : IUnknown { HRESULT CreateInstance( IUnknown * pUnkOuter, [IID] REFIID riid, [out] COM_INTERFACE_PTR* ppvObject ); HRESULT LockServer( BOOL fLock ); }; interface IDispatch : IUnknown { HRESULT GetTypeInfoCount( UINT pctinfo ); HRESULT GetTypeInfo( UINT iTInfo, LCID lcid, LPVOID ppTInfo ); HRESULT GetIDsOfNames( REFIID riid, LPOLECHAR* rgszNames, UINT cNames, LCID lcid, [out] DISPID* rgDispId ); HRESULT Invoke( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pDispParams, VARIANT* pVarResult, EXCEPINFO* pExcepInfo, UINT* puArgErr ); }; interface IPersist : IUnknown { HRESULT GetClassID( [out] CLSID *pClassID //Pointer to CLSID of object ); }; interface IPersistFile : IPersist { HRESULT IsDirty(); HRESULT Load( LPCOLESTR pszFileName, //Pointer to absolute path of the file to open DWORD dwMode //Specifies the access mode from the STGM enumeration ); HRESULT Save( LPCOLESTR pszFileName, //Pointer to absolute path of the file //where the object is saved BOOL fRemember //Specifies whether the file is to be the //current working file or not ); HRESULT SaveCompleted( LPCOLESTR pszFileName //Pointer to absolute path of the file //where the object was saved ); HRESULT GetCurFile( LPOLESTR *ppszFileName //Pointer to the path for the current file //or the default save prompt ); }; typedef VOID DVTARGETDEVICE; typedef LPVOID CONTINUEPROC; typedef LPVOID IAdviseSink; interface IViewObject : IUnknown { HRESULT Draw ( [in] DWORD dwDrawAspect, [in] LONG lindex, [in] void * pvAspect, [in] DVTARGETDEVICE *ptd, [in] HDC hdcTargetDev, [in] HDC hdcDraw, [in] LPCRECTL lprcBounds, [in] LPCRECTL lprcWBounds, [in] CONTINUEPROC ContinueProc, [in] ULONG_PTR dwContinue ); HRESULT GetColorSet ( [in] DWORD dwDrawAspect, [in] LONG lindex, [in] void *pvAspect, [in] DVTARGETDEVICE *ptd, [in] HDC hicTargetDev, [out] LOGPALETTE **ppColorSet ); HRESULT Freeze ( [in] DWORD dwDrawAspect, [in] LONG lindex, [in] void *pvAspect, [out] DWORD *pdwFreeze ); HRESULT Unfreeze ( [in] DWORD dwFreeze ); HRESULT SetAdvise ( [in] DWORD aspects, [in] DWORD advf, [in] IAdviseSink *pAdvSink ); HRESULT GetAdvise ( [out] DWORD *pAspects, [out] DWORD *pAdvf, [out] IAdviseSink **ppAdvSink ); }; interface IViewObject2 : IViewObject { HRESULT GetExtent ( [in] DWORD dwDrawAspect, [in] LONG lindex, [in] DVTARGETDEVICE* ptd, [out] LPSIZEL lpsizel ); }; typedef struct tagExtentInfo { ULONG cb; DWORD dwExtentMode; SIZEL sizelProposed; } DVEXTENTINFO; interface IViewObjectEx : IViewObject2 { HRESULT GetRect( [in] DWORD dwAspect, [out] LPRECTL pRect ); HRESULT GetViewStatus( [out] DWORD * pdwStatus ); HRESULT QueryHitPoint( [in] DWORD dwAspect, [in] LPCRECT pRectBounds, [in] POINT ptlLoc, [in] LONG lCloseHint, [out] DWORD * pHitResult ); HRESULT QueryHitRect( [in] DWORD dwAspect, [in] LPCRECT pRectBounds, [in] LPCRECT pRectLoc, [in] LONG lCloseHint, [out] DWORD * pHitResult ); HRESULT GetNaturalExtent ( [in] DWORD dwAspect, [in] LONG lindex, [in] DVTARGETDEVICE * ptd, [in] HDC hicTargetDev, [in] DVEXTENTINFO * pExtentInfo, [out] LPSIZEL pSizel ); }; // We can't log IMalloc because it is a global object. // It causes recursion problems in LogProcessHook because // StringFromCLSID uses the global interface. /* interface IMalloc : IUnknown { PVOID Alloc( SIZE_T cb ); PVOID Realloc( PVOID pv, SIZE_T cb ); VOID Free( PVOID pv); SIZE_T GetSize( PVOID pv ); int DidAlloc( PVOID pv ); VOID HeapMinimize(); }; */
0.996094
high
json_api/stringify/jss_object.h
heradon/shima
3
1944360
#ifndef JSS_OBJECT_H_INCLUDED #define JSS_OBJECT_H_INCLUDED #include "jss_core.h" #include "jss_check.h" #include <vector> #include <string> namespace JSON { namespace Internal { template <typename Type, class = typename std::enable_if <std::is_class <Type>::value>::type > class is_js_object { class yes { char m;}; class no { yes m[2];}; struct BaseMixin { std::string CLASS_STRINGIFY_FUNCTION_NAME(StringificationOptions){ return {}; } }; struct Base : public Type, public BaseMixin {}; template <typename T, T t> class Helper{}; template <typename U> static no deduce(U*, Helper<std::string (BaseMixin::*)(StringificationOptions), &U::CLASS_STRINGIFY_FUNCTION_NAME>* = 0); static yes deduce(...); public: static const bool value = sizeof(yes) == sizeof(deduce((Base*)(0))); }; } namespace Internal { template <typename T, class = typename std::enable_if<Internal::is_js_object<T>::value>::type > std::ostream& operator << (std::ostream& os, T const& object) { os << '{' << object.CLASS_STRINGIFY_FUNCTION_NAME(DEFAULT_OPTIONS) << '}'; return os; } } template <typename T, class = typename std::enable_if<std::is_class<T>::value>::type, class = typename std::enable_if<Internal::is_js_object<T>::value>::type > std::string js_stringify(std::string const& name, T const& value, StringificationOptions const& options = DEFAULT_OPTIONS) { using namespace Internal; std::stringstream sstr; WRITE_NAME(sstr); //! if you get an error here, your provided js_stringify functions is not const //! or if you used BOOST_FUSION_ADAPT_STRUCT, your adaption is incorrect sstr << value; return sstr.str(); } std::string js_make_object(std::vector <std::string> const& elements, StringificationOptions const& options = DEFAULT_OPTIONS); } #endif // JSS_OBJECT_H_INCLUDED
0.992188
high
Source/IGSIOCommon/vtkIGSIOTrackedFrameList.h
markasselin/IGSIO
0
1977128
/*=Plus=header=begin====================================================== Program: Plus Copyright (c) Laboratory for Percutaneous Surgery. All rights reserved. See License.txt for details. =========================================================Plus=header=end*/ #ifndef __vtkIGSIOTrackedFrameList_h #define __vtkIGSIOTrackedFrameList_h #include "vtkigsiocommon_export.h" #include "igsioVideoFrame.h" // for US_IMAGE_ORIENTATION #include "vtkObject.h" #include <deque> class vtkXMLDataElement; class igsioTrackedFrame; class vtkMatrix4x4; /*! \class vtkIGSIOTrackedFrameList \brief Stores a list of tracked frames (image + pose information) Validation threshold values: If the threshold==0 it means that no checking is needed (the frame is always accepted). If the threshold>0 then the frame is considered valid only if the position/angle difference compared to all previously acquired frames is larger than the position/angle minimum value and the translation/rotation speed is lower than the maximum allowed translation/rotation. \ingroup PlusLibCommon */ class VTKIGSIOCOMMON_EXPORT vtkIGSIOTrackedFrameList : public vtkObject { public: typedef std::deque<igsioTrackedFrame*> TrackedFrameListType; static vtkIGSIOTrackedFrameList* New(); vtkTypeMacro(vtkIGSIOTrackedFrameList, vtkObject); virtual void PrintSelf(ostream& os, vtkIndent indent) VTK_OVERRIDE; /*! Action performed after AddTrackedFrame got invalid frame. Invalid frame can be a TrackedFrame if the validation requirement didn't meet the expectation. */ enum InvalidFrameAction { ADD_INVALID_FRAME_AND_REPORT_ERROR = 0, /*!< Add invalid frame to the list and report an error */ ADD_INVALID_FRAME, /*!< Add invalid frame to the list wihout notification */ SKIP_INVALID_FRAME_AND_REPORT_ERROR, /*!< Skip invalid frame and report an error */ SKIP_INVALID_FRAME /*!< Skip invalid frame wihout notification */ }; /*! Add tracked frame to container. If the frame is invalid then it may not actually add it to the list. */ virtual igsioStatus AddTrackedFrame(igsioTrackedFrame* trackedFrame, InvalidFrameAction action = ADD_INVALID_FRAME_AND_REPORT_ERROR); /*! Add tracked frame to container by taking ownership of the passed pointer. If the frame is invalid then it may not actually add it to the list (it will be deleted immediately). */ virtual igsioStatus TakeTrackedFrame(igsioTrackedFrame* trackedFrame, InvalidFrameAction action = ADD_INVALID_FRAME_AND_REPORT_ERROR); /*! Add all frames from a tracked frame list to the container. It adds all invalid frames as well, but an error is reported. */ virtual igsioStatus AddTrackedFrameList(vtkIGSIOTrackedFrameList* inTrackedFrameList, InvalidFrameAction action = ADD_INVALID_FRAME_AND_REPORT_ERROR); /*! Get tracked frame from container */ virtual igsioTrackedFrame* GetTrackedFrame(int frameNumber); virtual igsioTrackedFrame* GetTrackedFrame(unsigned int frameNumber); /*! Get number of tracked frames */ virtual unsigned int GetNumberOfTrackedFrames(); virtual unsigned int Size(); /*! Get the tracked frame list */ TrackedFrameListType GetTrackedFrameList(); /* Retrieve the latest timestamp in the tracked frame list */ double GetMostRecentTimestamp(); /*! Remove a tracked frame from the list and free up memory \param frameNumber Index of tracked frame to remove (from 0 to NumberOfFrames-1) */ virtual igsioStatus RemoveTrackedFrame(int frameNumber); /*! Remove a range of tracked frames from the list and free up memory \param frameNumberFrom First frame to be removed (inclusive) \param frameNumberTo Last frame to be removed (inclusive) */ virtual igsioStatus RemoveTrackedFrameRange(unsigned int frameNumberFrom, unsigned int frameNumberTo); /*! Clear tracked frame list and free memory */ virtual void Clear(); /*! Set the number of following unique frames needed in the tracked frame list */ vtkSetMacro(NumberOfUniqueFrames, int); /*! Get the number of following unique frames needed in the tracked frame list */ vtkGetMacro(NumberOfUniqueFrames, int); /*! Set the threshold of acceptable speed of position change */ vtkSetMacro(MinRequiredTranslationDifferenceMm, double); /*!Get the threshold of acceptable speed of position change */ vtkGetMacro(MinRequiredTranslationDifferenceMm, double); /*! Set the threshold of acceptable speed of orientation change in degrees */ vtkSetMacro(MinRequiredAngleDifferenceDeg, double); /*! Get the threshold of acceptable speed of orientation change in degrees */ vtkGetMacro(MinRequiredAngleDifferenceDeg, double); /*! Set the maximum allowed translation speed in mm/sec */ vtkSetMacro(MaxAllowedTranslationSpeedMmPerSec, double); /*! Get the maximum allowed translation speed in mm/sec */ vtkGetMacro(MaxAllowedTranslationSpeedMmPerSec, double); /*! Set the maximum allowed rotation speed in degree/sec */ vtkSetMacro(MaxAllowedRotationSpeedDegPerSec, double); /*! Get the maximum allowed rotation speed in degree/sec */ vtkGetMacro(MaxAllowedRotationSpeedDegPerSec, double); /*! Set validation requirements \sa TrackedFrameValidationRequirements */ vtkSetMacro(ValidationRequirements, long); /*! Get validation requirements \sa TrackedFrameValidationRequirements */ vtkGetMacro(ValidationRequirements, long); /*! Set frame transform name used for transform validation */ void SetFrameTransformNameForValidation(const igsioTransformName& aTransformName) { this->FrameTransformNameForValidation = aTransformName; } /*! Get frame transform name used for transform validation */ igsioTransformName GetFrameTransformNameForValidation(); /*! Get tracked frame scalar size in bits */ virtual int GetNumberOfBitsPerScalar(); /*! Get tracked frame pixel size in bits (scalar size * number of scalar components) */ virtual int GetNumberOfBitsPerPixel(); /*! Get tracked frame pixel type */ igsioCommon::VTKScalarPixelType GetPixelType(); /*! Get number of components */ int GetNumberOfScalarComponents(); /*! Get tracked frame image orientation */ US_IMAGE_ORIENTATION GetImageOrientation(); /*! Get tracked frame image type */ US_IMAGE_TYPE GetImageType(); /*! Get tracked frame image size*/ igsioStatus GetFrameSize(FrameSizeType& outFrameSize); /* Get tracked frame encoding */ igsioStatus GetEncodingFourCC(std::string& encoding); /*! Get the value of the custom field. If we couldn't find it, return NULL */ virtual const char* GetCustomString(const char* fieldName); virtual std::string GetCustomString(const std::string& fieldName) const; virtual std::string GetFrameField(const std::string& fieldName) const; /*! Set custom string value to \c fieldValue. If \c fieldValue is NULL then the field is deleted. */ virtual igsioStatus SetCustomString(const char* fieldName, const char* fieldValue, igsioFrameFieldFlags flags = FRAMEFIELD_NONE); virtual igsioStatus SetCustomString(const std::string& fieldName, const std::string& fieldValue, igsioFrameFieldFlags flags = FRAMEFIELD_NONE); virtual igsioStatus SetFrameField(const std::string& fieldName, const std::string& fieldValue, igsioFrameFieldFlags flags = FRAMEFIELD_NONE); /*! Get the custom transformation matrix from metafile by frame transform name * It will search for a field like: Seq_Frame[frameNumber]_[frameTransformName] * Return false if the the field is missing */ virtual igsioStatus GetCustomTransform(const char* frameTransformName, vtkMatrix4x4* transformMatrix) const; virtual igsioStatus GetTransform(const igsioTransformName& name, vtkMatrix4x4& outMatrix) const; /*! Get the custom transformation matrix from metafile by frame transform name * It will search for a field like: Seq_Frame[frameNumber]_[frameTransformName] * Return false if the the field is missing */ virtual igsioStatus GetCustomTransform(const char* frameTransformName, double* transformMatrix) const; virtual igsioStatus GetTransform(const igsioTransformName& name, double* outMatrix) const; /*! Set the custom transformation matrix from metafile by frame transform name * It will search for a field like: Seq_Frame[frameNumber]_[frameTransformName] */ virtual igsioStatus SetCustomTransform(const char* frameTransformName, vtkMatrix4x4* transformMatrix); virtual igsioStatus SetTransform(const igsioTransformName& frameTransformName, const vtkMatrix4x4& transformMatrix); /*! Set the custom transformation matrix from metafile by frame transform name * It will search for a field like: Seq_Frame[frameNumber]_[frameTransformName] */ virtual igsioStatus SetCustomTransform(const char* frameTransformName, double* transformMatrix); virtual igsioStatus SetTransform(const igsioTransformName& frameTransformName, double* transformMatrix); /*! Get custom field name list */ void GetCustomFieldNameList(std::vector<std::string>& fieldNames); /*! Get global transform (stored in the Offset and TransformMatrix fields) */ igsioStatus GetGlobalTransform(vtkMatrix4x4* globalTransform); /*! Set global transform (stored in the Offset and TransformMatrix fields) */ igsioStatus SetGlobalTransform(vtkMatrix4x4* globalTransform); /*! Verify properties of a tracked frame list. If the tracked frame list pointer is invalid or the expected properties (image orientation, type) are different from the actual values then the method returns with failure. It is a static method so that the validity of the pointer can be easily checked as well. */ static igsioStatus VerifyProperties(vtkIGSIOTrackedFrameList* trackedFrameList, US_IMAGE_ORIENTATION expectedOrientation, US_IMAGE_TYPE expectedType); /*! Return true if the list contains at least one valid image frame */ bool IsContainingValidImageData(); /*! Implement support for C++11 ranged for loops */ TrackedFrameListType::iterator begin(); TrackedFrameListType::iterator end(); TrackedFrameListType::const_iterator begin() const; TrackedFrameListType::const_iterator end() const; TrackedFrameListType::reverse_iterator rbegin(); TrackedFrameListType::reverse_iterator rend(); TrackedFrameListType::const_reverse_iterator rbegin() const; TrackedFrameListType::const_reverse_iterator rend() const; protected: vtkIGSIOTrackedFrameList(); virtual ~vtkIGSIOTrackedFrameList(); /*! Perform validation on a tracked frame . If any of the requested requirement is not fulfilled then the validation fails. \param trackedFrame Input tracked frame \return True if the frame is valid \sa TrackedFrameValidationRequirements */ virtual bool ValidateData(igsioTrackedFrame* trackedFrame); bool ValidateTimestamp(igsioTrackedFrame* trackedFrame); bool ValidateTransform(igsioTrackedFrame* trackedFrame); bool ValidateStatus(igsioTrackedFrame* trackedFrame); bool ValidateEncoderPosition(igsioTrackedFrame* trackedFrame); bool ValidateSpeed(igsioTrackedFrame* trackedFrame); TrackedFrameListType TrackedFrameList; igsioFieldMapType CustomFields; int NumberOfUniqueFrames; /*! Validation threshold value */ double MinRequiredTranslationDifferenceMm; /*! Validation threshold value */ double MinRequiredAngleDifferenceDeg; /*! Validation threshold value */ double MaxAllowedTranslationSpeedMmPerSec; /*! Validation threshold value */ double MaxAllowedRotationSpeedDegPerSec; long ValidationRequirements; igsioTransformName FrameTransformNameForValidation; private: vtkIGSIOTrackedFrameList(const vtkIGSIOTrackedFrameList&); void operator=(const vtkIGSIOTrackedFrameList&); }; /// Implement support for C++11 ranged for loops VTKIGSIOCOMMON_EXPORT vtkIGSIOTrackedFrameList::TrackedFrameListType::iterator begin(vtkIGSIOTrackedFrameList& list); VTKIGSIOCOMMON_EXPORT vtkIGSIOTrackedFrameList::TrackedFrameListType::iterator end(vtkIGSIOTrackedFrameList& list); VTKIGSIOCOMMON_EXPORT vtkIGSIOTrackedFrameList::TrackedFrameListType::const_iterator begin(const vtkIGSIOTrackedFrameList& list); VTKIGSIOCOMMON_EXPORT vtkIGSIOTrackedFrameList::TrackedFrameListType::const_iterator end(const vtkIGSIOTrackedFrameList& list); VTKIGSIOCOMMON_EXPORT vtkIGSIOTrackedFrameList::TrackedFrameListType::reverse_iterator rbegin(vtkIGSIOTrackedFrameList& list); VTKIGSIOCOMMON_EXPORT vtkIGSIOTrackedFrameList::TrackedFrameListType::reverse_iterator rend(vtkIGSIOTrackedFrameList& list); VTKIGSIOCOMMON_EXPORT vtkIGSIOTrackedFrameList::TrackedFrameListType::const_reverse_iterator rbegin(const vtkIGSIOTrackedFrameList& list); VTKIGSIOCOMMON_EXPORT vtkIGSIOTrackedFrameList::TrackedFrameListType::const_reverse_iterator rend(const vtkIGSIOTrackedFrameList& list); #endif
0.996094
high
src/Window.h
Df458/DFEngine-Old-
0
343120
<gh_stars>0 #ifndef DF_WINDOW #define DF_WINDOW #include "Util.h" #include "SingleContainer.h" namespace df { void KeyInputCallback(GLFWwindow*, int, int, int, int); void MouseInputCallback(GLFWwindow*, int, int, int); class Window : public SingleContainer { public: Window(); ~Window(); std::string getTitle() { return title; } bool setTitle(std::string n_title) { if(init) { title = n_title; glfwSetWindowTitle(window, title.c_str()); } return init; } bool exists() { return init; } void prepareForDrawing() { glfwMakeContextCurrent(window); } Widget* getChild() { return child; } virtual Vec2d calculatePosition(Widget*) { return Vec2d(0, requestSize().y); } virtual Vec2d calculateSize(Widget*) { int width; int height; glfwGetFramebufferSize(window, &width, &height); return Vec2d(width, height); } virtual Vec2d requestSize() { int width; int height; glfwGetFramebufferSize(window, &width, &height); return Vec2d(width, height); } virtual Vec2d requestPosition() { return Vec2d(0, 0); } virtual void keyEvent(int key, int scancode, int action, int modifiers) { if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); SingleContainer::keyEvent(key, scancode, action, modifiers); } virtual void mouseEvent(Vec2d position, int button, int action, int modifiers) { SingleContainer::mouseEvent(position, button, action, modifiers); } void run(float delta_time); protected: bool init = false; GLFWwindow* window = NULL; std::string title = ""; }; } #endif
0.984375
high
src/builtin/set/my_unset/my_unset.c
BourgeoisBenjamin/EPITECH_PSU_42sh_2018
0
375888
<reponame>BourgeoisBenjamin/EPITECH_PSU_42sh_2018 /* ** EPITECH PROJECT, 2019 ** 42SH ** File description: ** my_unset */ #include "shell.h" int delete_element(t_variable *var, t_info *shell) { t_variable *tmp; free(var->name); free_array(var->arg); if (!var->prev && !var->next) { free(var); shell->variable = NULL; return (EXIT_SUCCESS); } tmp = var; if (var->prev) var->prev->next = var->next; if (var->next) { var->next->prev = var->prev; var = var->next; } else var = var->prev; free(tmp); for (; var->prev; var = var->prev); shell->variable = var; return (EXIT_SUCCESS); } int delete_variable(t_info *shell, char *str) { t_variable *var = shell->variable; for (; var && strcmp(var->name, str); var = var->next); if (!var) return (EXIT_SUCCESS); return (delete_element(var, shell)); } int my_unset(t_info *shell, t_command *command) { for (int i = 1; command->tab_command[i]; i++) delete_variable(shell, command->tab_command[i]); return (EXIT_SUCCESS); }
0.855469
high
PrivateFrameworks/Safari/SiriSuggestionsStartPageExploreViewController.h
phatblat/macOSPrivateFrameworks
17
1808656
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSViewController.h" #import "CollectionViewPlusDelegate.h" #import "NSCollectionViewDataSource.h" #import "NSCollectionViewDelegate.h" #import "SiriSuggestionsStartPageExploreViewItemDelegate.h" #import "SiriSuggestionsStartPageItemHostedViewControllerProtocol.h" @class BackgroundColorView, CollectionViewPlus, ForYouRecommendationMediator, NSMapTable, NSMutableArray, NSString, NSView, WBSSiteMetadataManager; __attribute__((visibility("hidden"))) @interface SiriSuggestionsStartPageExploreViewController : NSViewController <CollectionViewPlusDelegate, NSCollectionViewDelegate, NSCollectionViewDataSource, SiriSuggestionsStartPageExploreViewItemDelegate, SiriSuggestionsStartPageItemHostedViewControllerProtocol> { CollectionViewPlus *_collectionView; NSMutableArray *_currentRecommendations; WBSSiteMetadataManager *_siteMetadataManager; NSMapTable *_recommendationMetadataTokens; BackgroundColorView *_welcomeView; BOOL _isVisible; BOOL _hasContentToDisplay; BOOL _usesPrivateBrowsing; BOOL _usesCompactAppearance; ForYouRecommendationMediator *_recommendationMediator; } @property(retain, nonatomic) ForYouRecommendationMediator *recommendationMediator; // @synthesize recommendationMediator=_recommendationMediator; @property(nonatomic) BOOL usesCompactAppearance; // @synthesize usesCompactAppearance=_usesCompactAppearance; @property(nonatomic) BOOL usesPrivateBrowsing; // @synthesize usesPrivateBrowsing=_usesPrivateBrowsing; @property(nonatomic) BOOL hasContentToDisplay; // @synthesize hasContentToDisplay=_hasContentToDisplay; - (void).cxx_destruct; @property(readonly, nonatomic) double collapsedHeight; @property(readonly, nonatomic) double expandedHeight; - (void)willReuseItem:(id)arg1; - (void)didSelectItem:(id)arg1 withEvent:(id)arg2; - (void)didPerformContextMenuShowingEventForItem:(id)arg1 withEvent:(id)arg2; - (void)_updateImageForRecommendation:(id)arg1; - (void)_scheduleRecommendationUpdate:(id)arg1; - (void)_scheduleHandoffApplicationUpdate:(id)arg1; - (void)_navigateToRecommendation:(id)arg1 withPolicy:(long long)arg2; - (struct TabPlacementHint)_tabPlacementHint; - (id)_debugToolTipForRecommendation:(id)arg1; - (id)_enqueueTouchIconRequestForRecommendationItem:(id)arg1 title:(id)arg2 url:(id)arg3; - (id)_enqueueLeadImageRequestForRecommendationItem:(id)arg1 title:(id)arg2 url:(id)arg3; - (id)_enqueueSiteMetadataRequestForRecommendationItem:(id)arg1 title:(id)arg2 url:(id)arg3; - (unsigned long long)_numberOfTimesWelcomeViewHasBeenShown; - (void)_incrementWelcomeViewTimesShownCounterIfApplicableBy:(unsigned long long)arg1; - (BOOL)_shouldShowWelcomeView; - (void)_didSelectWelcomeViewCloseButton:(id)arg1; - (void)_uninstallWelcomeView; - (id)_welcomeString; - (void)_installWelcomeView; - (void)_fetchHandoffResult; - (unsigned long long)_existingHandoffRecommendationIndex; - (void)_updateRecommendationsForTopics:(id)arg1; - (void)reloadData; - (long long)collectionView:(id)arg1 numberOfItemsInSection:(long long)arg2; - (id)collectionView:(id)arg1 itemForRepresentedObjectAtIndexPath:(id)arg2; @property(readonly, nonatomic) BOOL supportsCollapsing; @property(readonly, nonatomic) BOOL isPerformingSizingAnimation; - (void)_cleanUp; - (void)dealloc; - (void)viewWillDisappear; - (void)viewDidAppear; - (void)viewDidLayout; - (void)viewDidLoad; - (void)loadView; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly, nonatomic) NSString *identifier; @property(retain, nonatomic) NSView *leadingAccessoryView; @property(readonly) Class superclass; @property(readonly, nonatomic) NSString *title; @end
0.980469
high
executor/operator/ref/kernel/add_n/ref_addn_uint8.c
wangshankun/Tengine_Atlas
25
1841424
static int ref_addn_uint8(uint8_t** input, uint8_t* output, const ref_addn_param* param) { int input_size = param->input_size; int in_num = param->in_num; float* out_f32 = ( float* )malloc(input_size); memset(out_f32, 0, input_size); for(int i = 0; i < in_num; ++i) { uint8_t* input_data = input[i]; float input_scale = param->in_scale[i]; int zero_point = param->in_zero[i]; for(int j = 0; j < input_size; ++j) { out_f32[j] += (input_data[j] * input_scale + zero_point); } } for(int j = 0; j < input_size; ++j) { int s32_out = round(out_f32[j] / param->out_scale) + param->out_zero; if(s32_out > 255) s32_out = 255; if(s32_out < 0) s32_out = 0; output[j] = s32_out; } free(out_f32); out_f32 = NULL; return 0; }
0.992188
high
RenderSystems/Direct3D11/include/OgreD3D11HardwareBufferManager.h
FreeNightKnight/ogre-next
0
8074032
<filename>RenderSystems/Direct3D11/include/OgreD3D11HardwareBufferManager.h<gh_stars>0 /* ----------------------------------------------------------------------------- This source file is part of OGRE-Next (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 <NAME> Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 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 __D3D11HARWAREBUFFERMANAGER_H__ #define __D3D11HARWAREBUFFERMANAGER_H__ #include "OgreD3D11Prerequisites.h" #include "OgreHardwareBufferManager.h" namespace Ogre { namespace v1 { /** Implementation of HardwareBufferManager for D3D11. */ class _OgreD3D11Export D3D11HardwareBufferManagerBase final : public HardwareBufferManagerBase { protected: D3D11Device &mlpD3DDevice; public: D3D11HardwareBufferManagerBase( D3D11Device &device ); ~D3D11HardwareBufferManagerBase(); /// Creates a vertex buffer HardwareVertexBufferSharedPtr createVertexBuffer( size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer = false ) override; /// Creates a stream output vertex buffer HardwareVertexBufferSharedPtr createStreamOutputVertexBuffer( size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer = false ); /// Create a hardware vertex buffer HardwareIndexBufferSharedPtr createIndexBuffer( HardwareIndexBuffer::IndexType itype, size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer = false ) override; }; /// D3D11HardwareBufferManagerBase as a Singleton class _OgreD3D11Export D3D11HardwareBufferManager final : public HardwareBufferManager { public: D3D11HardwareBufferManager( D3D11Device &device ) : HardwareBufferManager( OGRE_NEW D3D11HardwareBufferManagerBase( device ) ) { } ~D3D11HardwareBufferManager() override { OGRE_DELETE mImpl; } }; } // namespace v1 } // namespace Ogre #endif
0.996094
high
src/Storages/RedisStreams/Buffer_fwd.h
tchepavel/ClickHouse
0
8106800
<gh_stars>0 #pragma once #include <memory> namespace DB { class ReadBufferFromRedisStreams; class WriteBufferToRedisStreams; using ConsumerBufferPtr = std::shared_ptr<ReadBufferFromRedisStreams>; using ProducerBufferPtr = std::shared_ptr<WriteBufferToRedisStreams>; }
0.984375
high
src/pidspace.c
earlchew/pidspace
0
8139568
/* -*- c-basic-offset:4; indent-tabs-mode:nil -*- vi: set sw=4 et: */ /* // Copyright (c) 2022, <NAME> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the names of the authors of source code nor the names // of the contributors to the source code 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 EARL CHEW 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 <ctype.h> #include <err.h> #include <errno.h> #include <getopt.h> #include <poll.h> #include <pwd.h> #include <sched.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <sys/capability.h> #include <sys/fsuid.h> #include <sys/fcntl.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/signalfd.h> #include <sys/types.h> #include <sys/wait.h> /* -------------------------------------------------------------------------- */ #define ARRAYSIZE(x) (sizeof((x))/sizeof((x)[0])) /* -------------------------------------------------------------------------- */ struct Tty { pid_t mPgid; int mFd; }; struct Parent { struct { pid_t mPid; int mSyncRd; int mSyncWr; } mChild; }; struct Child { char **mCmd; sigset_t mInheritedSet; struct { pid_t mPgid; pid_t mSid; int mSyncRd; int mSyncWr; } mParent; }; struct Service { struct Parent mParent; struct Child mChild; struct Tty mTty; }; /* -------------------------------------------------------------------------- */ #if __GLIBC__ < 2 || __GLIBC__ == 2 && __GLIBC_MINOR__ < 32 static const char * sigabbrev_np(int aSigNo) { const char *abbrev = 0; switch (aSigNo) { case SIGHUP: abbrev = "HUP"; break; case SIGINT: abbrev = "INT"; break; case SIGQUIT: abbrev = "QUIT"; break; case SIGILL: abbrev = "ILL"; break; case SIGTRAP: abbrev = "TRAP"; break; case SIGABRT: abbrev = "ABRT"; break; case SIGFPE: abbrev = "FPE"; break; case SIGKILL: abbrev = "KILL"; break; case SIGBUS: abbrev = "BUS"; break; case SIGSYS: abbrev = "SYS"; break; case SIGSEGV: abbrev = "SEGV"; break; case SIGPIPE: abbrev = "PIPE"; break; case SIGALRM: abbrev = "ALRM"; break; case SIGTERM: abbrev = "TERM"; break; case SIGURG: abbrev = "URG"; break; case SIGSTOP: abbrev = "STOP"; break; case SIGTSTP: abbrev = "TSTP"; break; case SIGCONT: abbrev = "CONT"; break; case SIGCHLD: abbrev = "CHLD"; break; case SIGTTIN: abbrev = "TTIN"; break; case SIGTTOU: abbrev = "TTOU"; break; case SIGPOLL: abbrev = "POLL"; break; case SIGXCPU: abbrev = "XCPU"; break; case SIGXFSZ: abbrev = "XFSZ"; break; case SIGVTALRM: abbrev = "VTALRM"; break; case SIGPROF: abbrev = "PROF"; break; case SIGUSR1: abbrev = "USR1"; break; case SIGUSR2: abbrev = "USR2"; break; case SIGWINCH: abbrev = "WINCH"; break; } return abbrev; } #endif /* -------------------------------------------------------------------------- */ static void die(const char *aFmt, ...) { if (aFmt) { va_list argp; va_start(argp, aFmt); if (errno) vwarn(aFmt, argp); else vwarnx(aFmt, argp); va_end(argp); } exit(127); } /* -------------------------------------------------------------------------- */ static int sDebug; static long sPPid; static struct option sOptions[] = { { "debug", no_argument, 0, 'd' }, { "ppid", required_argument, 0, 'P' }, }; /* -------------------------------------------------------------------------- */ static struct timespec sEpoch; static void debug_(unsigned aLineNo, const char *aFmt, ...) { static char *debugBufPtr; static size_t debugBufLen; static FILE *debugFile; if (!debugFile) { debugFile = open_memstream(&debugBufPtr, &debugBufLen); if (!debugFile) die("Unable to create debug stream"); } struct timespec time; if (clock_gettime(CLOCK_MONOTONIC, &time)) die("Unable to read clock"); long milliseconds = (time.tv_sec - sEpoch.tv_sec) * 1000 + (time.tv_nsec - sEpoch.tv_nsec) / 1000000; long minutes = milliseconds / (60 * 1000); milliseconds %= (60 * 1000); long seconds = milliseconds / 1000; milliseconds %= 1000; va_list argp; va_start(argp, aFmt); fprintf(debugFile, "%s: [%ld:%02ld.%03ld] %d %u - ", program_invocation_short_name, minutes, seconds, milliseconds, getpid(), aLineNo); vfprintf(debugFile, aFmt, argp); fputc('\n', debugFile); fflush(debugFile); fwrite(debugBufPtr, debugBufLen, 1, stderr); rewind(debugFile); va_end(argp); } #define DEBUG(...) \ if (!sDebug) ; else do debug_(__LINE__, __VA_ARGS__); while (0) /* -------------------------------------------------------------------------- */ static void usage(void) { fprintf( stderr, "usage: %s [--debug] [--ppid PPID] -- cmd ...\n", program_invocation_short_name); die(0); } /* -------------------------------------------------------------------------- */ static long strtowhole(const char *aString) { int rc = -1; long number = 0; if (isdigit((unsigned char) *aString)) { char *endPtr; errno = 0; number = strtol(aString, &endPtr, 10); if ('0' == *aString) { const char *lastPtr = endPtr; if (1 != lastPtr - aString) errno = EINVAL; } if (!*endPtr && !errno) rc = 0; } return rc ? -1 : number; } /* -------------------------------------------------------------------------- */ static void verify_privileged_role() { cap_flag_value_t capValue; cap_t capSet = cap_get_proc(); if (!capSet) die("Unable to query process capabilities"); if (cap_get_flag(capSet, CAP_SYS_ADMIN, CAP_PERMITTED, &capValue)) die("Unable to query process CAP_SYS_ADMIN"); if (CAP_CLEAR != capValue) { cap_value_t setCaps[] = { CAP_SYS_ADMIN }; if (cap_set_flag( capSet, CAP_EFFECTIVE, ARRAYSIZE(setCaps), setCaps, CAP_SET)) die("Unable to set process CAP_SYS_ADMIN"); } else { uid_t euid = geteuid(); if (0 != euid) { struct passwd *passwd = getpwuid(euid); if (passwd) die("Expected CAP_SYS_ADMIN or root instead of %s", passwd->pw_name); else die("Expected CAP_SYS_ADMIN or root instead of uid %d", euid); } } cap_free(capSet); } /* -------------------------------------------------------------------------- */ static pid_t foreground(int aTtyFd, int aPgid) { pid_t fgPgid = 0; if (-1 != aTtyFd) { fgPgid = tcgetpgrp(aTtyFd); if (-1 == fgPgid) die("Unable to query foreground pgid"); if (-1 != aPgid) { if (fgPgid != getpgrp()) { fgPgid = 0; } else { DEBUG("Foreground pgid %d", aPgid); if (tcsetpgrp(aTtyFd, aPgid)) die("Unable to configure foreground pgid %d", aPgid); } } } return fgPgid; } /* -------------------------------------------------------------------------- */ static pid_t privileged(struct Service *aService, int argc, char **argv) { /***************************************************************** * Place this function as close to the head of the source file * * as possible to reduce the chance that it will call additional * * functions while running at elevated privilege. * *****************************************************************/ if (clock_gettime(CLOCK_MONOTONIC, &sEpoch)) die("Unable to initialise clock"); /* When run as setuid, glibc and musl ensure that stdin, stdout, * and stderr, are valid file descriptors open to /dev/null, * or /dev/full. Do the same here to cover the case where * the program is not run setuid. */ static const char sDevNull[] = "/dev/null"; static const char sDevFull[] = "/dev/full"; if (-1 == dup2(STDIN_FILENO, STDIN_FILENO)) { if (EBADF != errno || STDIN_FILENO != open(sDevFull, O_RDONLY)) die("Unable to initialise stdin"); } if (-1 == dup2(STDOUT_FILENO, STDOUT_FILENO)) { if (EBADF != errno || STDOUT_FILENO != open(sDevNull, O_WRONLY)) die("Unable to initialise stdout"); } if (-1 == dup2(STDERR_FILENO, STDERR_FILENO)) { if (EBADF != errno || STDERR_FILENO != open(sDevNull, O_WRONLY)) die("Unable to initialise stdout"); } /* Either skip the first argument and point at the first * argument, or point at the trailing null pointer. * * http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2354.htm * * - argv[argc] shall be a null pointer. */ while (1) { int opt = getopt_long(argc, argv, "+dP:", sOptions, 0); if (-1 == opt) break; switch (opt) { case '?': usage(); break; case 'd': sDebug =1; break; case 'P': { sPPid = strtowhole(optarg); pid_t ppid = sPPid; if (-1 == sPPid || ppid != sPPid) die("Unable to parse parent pid %s", optarg); if (!sPPid) die("Invalid parent pid %s", optarg); break; } } } if (optind >= argc) usage(); aService->mChild.mCmd = &argv[optind]; /* Use of CLONE_NEWPID, CLONE_NEWNS, and mount(2), require that the caller * be privileged, or have CAP_SYSADMIN capability. */ verify_privileged_role(); /* Use a pair of pipes to synchronise the prctl(2) actions in the child. * This is required because the child inhabits a new pid namespace, * resulting in its getppid(2) invocations always returning 0. * * The process running as pid 1 in the new namespace cannot be * terminated with a signal sent from within the new namespace * itself. Allow it to use a sync pipe to request the parent * to terminate it with a specific signal. */ int childSync[2]; if (pipe2(childSync, O_CLOEXEC)) die("Unable to create child sync pipe"); int parentSync[2]; if (pipe2(parentSync, O_CLOEXEC)) die("Unable to create parent sync pipe"); /* If not running as a session leader, find the controlling terminal, * and interrogate it for the foreground process group. The controlling * terminal is later used to determine if parent or child belong to * the foreground process group. The foreground process group is * recorded so that it can be restored on exit. * * The parent does not function as a job control shell, even if * running as a session leader. Because of this, ignore the controlling * terminal even if it exists. Presently no attempt is used to detach * from the controlling terminal using TIOCNOTTY. */ pid_t selfPgid = getpgrp(); pid_t selfSid = getsid(0); DEBUG("Process pgid %d sid %d", selfPgid, selfSid); pid_t fgPgid = 0; int ttyFd = -1; if (selfPgid != selfSid) { char *ttyName = ctermid(0); ttyFd = open(ttyName, O_RDONLY | O_CLOEXEC); if (-1 == ttyFd) { if (ENXIO != errno) die("Unable to open %s", ttyName); } else { fgPgid = foreground(ttyFd, -1); DEBUG( "Controlling terminal %s foreground pgid %d", ttyName, fgPgid); } } aService->mTty.mFd = ttyFd; aService->mTty.mPgid = fgPgid; /* Save the signal mask to be restored when running the command, * and block all signals until signal propagation is properly * configured. */ sigset_t fillSet; if (sigfillset(&fillSet)) die("Unable to initialise blocking signal set"); if (sigprocmask(SIG_BLOCK, &fillSet, &aService->mChild.mInheritedSet)) die("Unable to configure blocking signal set"); /* After blocking SIGCHLD so as not to miss any deliveries, reap any * zombie children transferred across the execve(2) that started this * program. Children that become zombies later will be noticed via SIGCHLD. */ pid_t zombiePid; do { zombiePid = waitpid(0, 0, WNOHANG); if (-1 == zombiePid) { if (ECHILD != errno) die("Unable to reap zombie children"); zombiePid = 0; } if (zombiePid) DEBUG("Zombie pid %d", zombiePid); } while (zombiePid); /* Fork the child process in a new pid namespace. Remember that * CLONE_NEWPID affects subsequent fork(2), and does not change * the pid namespace of the caller. */ if (unshare(CLONE_NEWPID)) die("Unable to unshare pid namespace"); pid_t childPid = fork(); if (-1 == childPid) die("Unable to fork child"); if (childPid) { if (setpgid(childPid, childPid)) die("Unable to configure pgid %d", childPid); aService->mParent.mChild.mPid = childPid; aService->mParent.mChild.mSyncRd = childSync[0]; aService->mParent.mChild.mSyncWr = parentSync[1]; close(childSync[1]); close(parentSync[0]); } else { aService->mChild.mParent.mSyncWr = childSync[1]; aService->mChild.mParent.mSyncRd = parentSync[0]; aService->mChild.mParent.mPgid = selfPgid; aService->mChild.mParent.mSid = selfSid; close(childSync[0]); close(parentSync[1]); /* The child process inherits the controlling terminal of its * parent. Place the child process in its own process group * so that it will only receive signals purposefully sent * from the parent. */ if (setpgid(0, 0)) die("Unable to configure pgid %d", getpid()); /* Mount a new /proc in a new mount namespace to reflect the * new pid namespace. Constrain the propagation to avoid affecting * the mount points in the parent namespace. */ if (unshare(CLONE_NEWNS)) die("Unable to unshare mount namespace"); const char procMount[] = "/proc"; const char procFS[] = "proc"; if (mount(0, procMount, 0, MS_REC|MS_PRIVATE, 0)) die("Unable to change proc filesystem propagation"); if (mount(0, procMount, procFS, MS_NOSUID|MS_NOEXEC|MS_NODEV, 0)) die("Unable to mount /proc"); } return childPid; } /* -------------------------------------------------------------------------- */ static void pdeathsig(pid_t aParentPid) { int killSig; if (-1 == aParentPid) { if (prctl(PR_GET_PDEATHSIG, &killSig, 0, 0, 0)) die("Unable to get pdeathsig"); if (!killSig) die("Unconfigured pdeathsig"); } else { killSig = SIGKILL; if (prctl(PR_SET_PDEATHSIG, killSig, 0, 0, 0)) die("Unable to set pdeathsig"); if (!aParentPid || getppid() == aParentPid) killSig = 0; } /* When killed from its own pid namespace, only those signals that * are handled will be delivered by the kernel the init pid 1 process. * This means that signals that are set to SIG_DFL will not be delivered, * and consequentially there is no way for the init pid 1 process to * terminate itself with any signal. * * Since this function is only called when PDEATHSIG was set too late, * and the parent has already terminated, the exit status is likely * not very interesting to any reaper. Thus it is is not vital to * duplicate the termination signal, and a simple exit(3) suffices. * * The same reasoning applies to all other cases where the child loses * the parent before PDEATHSIG is configured. */ if (killSig) exit(128 + killSig); } /* -------------------------------------------------------------------------- */ static int read_byte(int aFd) { int byte = -1; char buf[1]; ssize_t readBytes = read(aFd, buf, 1); if (-1 != readBytes) { if (readBytes) byte = (unsigned char) buf[0]; else errno = 0; } /* Return the non-negative byte, or -1 with zero errno * to indicate eof, and a non-zero errno for other error cases. */ return byte; } /* -------------------------------------------------------------------------- */ static int wait_child(int aFd) { return read_byte(aFd); } /* -------------------------------------------------------------------------- */ static void dispatch_parent(int aFd, int aSignal) { while (1) { /* Write a single byte to allow the parent to recognise * the synchronisation state from the child. */ char buf[1] = { aSignal }; ssize_t wroteBytes = write(aFd, buf, 1); if (wroteBytes) break; if (-1 == wroteBytes) { if (EINTR != errno) die("Unable to dispatch parent"); } } } /* -------------------------------------------------------------------------- */ static void dispatch_child(int aFd) { while (1) { /* Write a single byte to allow the child to differentiate * between two cases: * * a. The parent terminates before writing * b. The parent terminates after writing */ char buf[1] = { 0 }; ssize_t wroteBytes = write(aFd, buf, 1); if (wroteBytes) break; if (-1 == wroteBytes) { if (EPIPE == errno) break; if (EINTR != errno) die("Unable to dispatch child"); } } } /* -------------------------------------------------------------------------- */ static int wait_parent(int aFd) { int parentReady = -1; /* Read a single byte from the parent to differentiate * between two cases: * * a. The parent terminates before writing * b. The parent terminates after writing */ do { int readByte = read_byte(aFd); if (-1 == readByte) { if (EINTR != errno) break; } else { parentReady = readByte; break; } } while (-1 == parentReady); return parentReady; } /* -------------------------------------------------------------------------- */ static void stop(int aSignal, int aSigWrFd, pid_t aPid, int aTtyFd) { DEBUG("Stop %s", sigabbrev_np(aSignal)); pid_t selfPid = getpid(); int stopSig = aSignal; int contSig = SIGCONT; if (-1 == aSigWrFd) { /* The parent process should stop when it detects the child * stopping, and this should only occur after the child has * requested that it be stopped. When this occurs, the parent * should use SIGSTOP to stop the child, and then react to * child stopping. */ if (SIGSTOP != stopSig) die("Unexpected stop %s", sigabbrev_np(stopSig)); if (kill(selfPid, stopSig)) die("Unable to kill pid %d using %s", selfPid, sigabbrev_np(stopSig)); /* The process will be suspended at this point until continued. * When continued, execution will restart, and SIGCONT queued * for processing. */ } else { DEBUG("Dispatch %s", sigabbrev_np(stopSig)); dispatch_parent(aSigWrFd, stopSig); /* The process willl be stopped by its parent. Eventually * the parent will will also send SIGCONT to restart * the process. Use sigwaitinfo(2) to detect the SIGCONT * sent by the parent. */ sigset_t contSigSet; if (sigemptyset(&contSigSet)) die("Unable to initialise continuation signal set"); if (sigaddset(&contSigSet, contSig)) die("Unable to exclude %s from continuation signal set", sigabbrev_np(contSig)); DEBUG("Waiting for %s", sigabbrev_np(contSig)); while (-1 == sigwaitinfo(&contSigSet, 0)) { if (EINTR != errno) die("Unable to continue pid %d using %s", selfPid, sigabbrev_np(contSig)); } /* Before processing SIGCONT, set the foreground * process group if configured to avoid missing * any job control signals. */ foreground(aTtyFd, aPid); /* The SIGCONT sent by the parent is no longer pending, and * is no longer queued for processing. Since the signal * is considered delivered, handle it here by sending it * to the child process group. */ DEBUG("Waking pgid %d with %s", aPid, sigabbrev_np(contSig)); if (killpg(aPid, contSig)) { if (ESRCH != errno) die("Unable to resume process %d", aPid); } } } /* -------------------------------------------------------------------------- */ static void terminate(int aSigWrFd, int aSignal) { DEBUG("Terminate %s", sigabbrev_np(aSignal)); pid_t selfPid = getpid(); sigset_t sigSet; if (sigprocmask(SIG_SETMASK, 0, &sigSet)) die("Unable to query signal mask"); if (sigdelset(&sigSet, aSignal)) die("Unable to remove %s from signal mask", sigabbrev_np(aSignal)); if (SIGKILL != aSignal && SIGSTOP != aSignal) { if (SIG_ERR == signal(aSignal, SIG_DFL)) die("Unable to reconfigure handler for %s", sigabbrev_np(aSignal)); } if (sigprocmask(SIG_SETMASK, &sigSet, 0)) die("Unable to unblock %s from signal mask", sigabbrev_np(aSignal)); if (-1 == aSigWrFd) { kill(selfPid, aSignal); die("Unable to kill pid %d using %s", selfPid, sigabbrev_np(aSignal)); } else { DEBUG("Dispatch %s", sigabbrev_np(aSignal)); dispatch_parent(aSigWrFd, aSignal); do sigsuspend(&sigSet); while (EINTR == errno); die("Unable to terminate pid %d using %s", selfPid, sigabbrev_np(aSignal)); } } /* -------------------------------------------------------------------------- */ static int reap_process(int aSigWrFd, pid_t aPid, int aStatus, int aSignal, pid_t aFgPgid) { if (aFgPgid) { DEBUG("Restoring foreground pgid %d", aFgPgid); /* Be aware that the original process group might no longer be * available, Check the common case where the parent is launched * from a job control shell. */ if (tcsetpgrp(STDIN_FILENO, aFgPgid)) if (ESRCH != errno || aFgPgid != getpgrp()) die("Unable to restore foreground pgid %d", aFgPgid); } int termSig = aSignal; if (!termSig) { if (WIFSIGNALED(aStatus)) termSig = WTERMSIG(aStatus); } if (termSig) { DEBUG("Terminating pid %d with %s", aPid, sigabbrev_np(termSig)); terminate(aSigWrFd, termSig); } int exitCode = WEXITSTATUS(aStatus); DEBUG("Exiting pid %d with %d", aPid, exitCode); return exitCode; } /* -------------------------------------------------------------------------- */ static int handle_signal(int aFd, pid_t aPid, int aTtyFd) { int sigPid = -1; struct signalfd_siginfo sigInfo; if (sizeof(sigInfo) == read(aFd, &sigInfo, sizeof(sigInfo))) { DEBUG("Caught %s code %d", sigabbrev_np(sigInfo.ssi_signo), sigInfo.ssi_code); /* Caught signals are propagated to the child. No attempt is made * to handle the signals locally until waitpid(2) detects that * they have caused the child to change state. */ if (SIGCHLD == sigInfo.ssi_signo) { sigPid = sigInfo.ssi_pid; DEBUG("SIGCHLD pid %d", sigPid); } else { sigPid = 0; int sendSig = 0; if (SI_KERNEL == sigInfo.ssi_code) { sendSig = sigInfo.ssi_signo; } else if (SI_USER == sigInfo.ssi_code) { /* To avoid sending the child a signal that it already * knows about, only propagate signals to the child that * were sent by another party. */ if (sigInfo.ssi_pid != aPid) sendSig = sigInfo.ssi_signo; } if (sendSig) { /* To mimic the shell, job control signals are sent to the * entire child process group, whereas termination signals * are sent to the child process alone and rely on the * fact that the fate of the process hierarchy is tied * to the pid 1 process. */ switch (sendSig) { default: DEBUG("Sending %s to pid %d", sigabbrev_np(sendSig), aPid); if (kill(aPid, sendSig)) { if (ESRCH != errno) die("Unable to propagate %s to pid %d", sigabbrev_np(sendSig), aPid); } break; case SIGCONT: case SIGTSTP: /* Job control related signals require a propagation * of the foreground process group, along with the * signal itself. */ foreground(aTtyFd, aPid); /* Fall through */ case SIGINT: DEBUG("Sending %s to pgid %d", sigabbrev_np(sendSig), aPid); if (killpg(aPid, sendSig)) { if (ESRCH != errno) die("Unable to propagate %s to pgid %d", sigabbrev_np(sendSig), aPid); } break; } } } } return sigPid; } /* -------------------------------------------------------------------------- */ static int configure_signal() { static const int handleSignals[] = { SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGCHLD, SIGTSTP, SIGCONT, }; sigset_t sigSet; if (sigfillset(&sigSet)) die("Unable to initialise full signal set"); if (sigprocmask(SIG_SETMASK, &sigSet, 0)) die("Unable to block signals for signalfd"); if (sigemptyset(&sigSet)) die("Unable to initialise empty signal set"); for (size_t ix = 0; ix < ARRAYSIZE(handleSignals); ++ix) { int signal = handleSignals[ix]; const char *signalName = sigabbrev_np(signal); if (sigaddset(&sigSet, signal)) die("Unable to add %s to signal set", signalName); } return signalfd(-1, &sigSet, SFD_CLOEXEC); } /* -------------------------------------------------------------------------- */ static int handle_request(int aFd, int aPid, int aTtyFd) { /* Handle a signal request sent from the child to the parent. Remember * that the child runs as pid 1 in the new pid namespace, and so will only * receive signals that it is prepared to handle, or signals * that cannot be ignored (ie SIGKILL, and SIGSTOP). * * Signal requests are sent for stopping or terminating, so always * choose to send either SIGKILL or SIGSTOP no matter what the * requested signal. * * Note that it is impossible for a stopped child to send a * continuation request. */ int req = wait_child(aFd); if (-1 != req) { int reqSig = req; switch (reqSig) { default: reqSig = SIGKILL; DEBUG("Terminating pid %d with %s", aPid, sigabbrev_np(reqSig)); break; case SIGTTIN: case SIGTTOU: if (foreground(aTtyFd, aPid)) { reqSig = SIGCONT; DEBUG("Resuming pid %d with %s", aPid, sigabbrev_np(reqSig)); req = 0; break; } /* Fall through */ case SIGSTOP: case SIGTSTP: reqSig = SIGSTOP; DEBUG("Stopping pid %d with %s", aPid, sigabbrev_np(reqSig)); req = 0; break; } if (kill(aPid, reqSig)) { if (ESRCH != errno) die("Unable to kill pid %d using %s", aPid, sigabbrev_np(reqSig)); } } return req; } /* -------------------------------------------------------------------------- */ static int wait_process( int aSigRdFd, int aSigWrFd, pid_t aChildPid, int aTtyFd, pid_t aFgPgid) { int sigFd = configure_signal(); if (-1 == sigFd) die("Unable to create signalfd"); int waitStatus = 0; int termSig = 0; struct pollfd pollFds[2] = { { .fd = sigFd, .events = POLL_IN, }, { .fd = aSigRdFd, .events = POLL_IN, }, }; while (1) { int numFds = poll(pollFds, ARRAYSIZE(pollFds), -1); if (-1 == numFds) { if (EINTR != errno) die("Unable to poll"); continue; } if (pollFds[0].revents & (POLLIN | POLLHUP)) { int sigPid = handle_signal(sigFd, aChildPid, aTtyFd); if (-1 == sigPid) { if (EINTR != errno) die("Unable to handle signal"); } else if (sigPid) { pid_t waitPid = waitpid( sigPid, &waitStatus, WNOHANG | WUNTRACED); if (-1 == waitPid) { if (EINTR != errno) die("Unable to wait for children"); } else if (waitPid) { DEBUG("Wait pid %d status 0x%x", waitPid, waitStatus); if (aChildPid == waitPid) { if (!WIFSTOPPED(waitStatus)) break; stop( WSTOPSIG(waitStatus), aSigWrFd, aChildPid, aTtyFd); } } } } if (pollFds[1].revents & (POLLIN | POLLHUP)) { int sigRequest = handle_request(aSigRdFd, aChildPid, aTtyFd); if (-1 == sigRequest) { if (errno) { if (EINTR != errno) die("Unable to read signal request"); } else { DEBUG("Signal request pipe closed"); pollFds[1].fd = -1; } } else if (sigRequest) { termSig = sigRequest; int waitPid; do waitPid = waitpid(aChildPid, &waitStatus, 0); while (-1 == waitPid && EINTR == errno); if (waitPid != aChildPid) die("Unable to wait for pid %d", aChildPid); break; } } } if (termSig) DEBUG("Reaped pid %d with %s", aChildPid, sigabbrev_np(termSig)); return reap_process(aSigWrFd, aChildPid, waitStatus, termSig, aFgPgid); } /* -------------------------------------------------------------------------- */ static void drop_stdio(int aTtyFd) { static const char sDevNull[] = "/dev/null"; int devNullFd = open(sDevNull, O_RDWR); if (STDIN_FILENO == aTtyFd || STDOUT_FILENO == aTtyFd) die("Unexpected controlling terminal %d", aTtyFd); int stdinFd = devNullFd; if (-1 != aTtyFd) stdinFd = aTtyFd; if (-1 == dup2(stdinFd, STDIN_FILENO)) die("Unable to drop stdin"); if (-1 == dup2(devNullFd, STDOUT_FILENO)) die("Unable to drop stdout"); if (STDIN_FILENO != devNullFd && STDOUT_FILENO != devNullFd) close(devNullFd); } /* -------------------------------------------------------------------------- */ static void run_init_pid1(int aChildFd, pid_t aChildPid, int aTtyFd) { pid_t selfPid = getpid(); pid_t parentPid = getppid(); if (1 != selfPid) die("Child unexpectedly running as pid %d", selfPid); if (0 != parentPid) die("Parent unexpectedly detected as pid %d", parentPid); /* The init pid 1 process is treated specially by the kernel because * it is marked with SIGNAL_UNKILLABLE. This causes the kernel to * skip delivery of all, except SIGSTOP and SIGKILL that have * been generated internally or delivered from an ancestor namespace. * * In summary: * * o SIGKILL and SIGSTOP from any ancestor pid namespace will be delivered * o SIGKILL and SIGSTOP from within the new pid namespace is ignored, * including from the process itself, irrespective of privilege * o SIGTERM, etc, are delivered only if handled */ exit(wait_process(-1, aChildFd, aChildPid, aTtyFd, 0)); } /* -------------------------------------------------------------------------- */ static void drop_privileges() { /* Drop privileges, after PDEATHSIG is configured, to avoid * taking unintended actions. * * Drop CAP_SYS_ADMIN capability from the permitted and * effective sets. Leave the capability in the other * sets, in particular the inheritable set, so that later * execve(2) can raise privileges again. */ cap_t capSet = cap_get_proc(); if (!capSet) die("Unable to query process capabilities"); cap_value_t clearCaps[] = { CAP_SYS_ADMIN }; cap_flag_t capSets[] = { CAP_EFFECTIVE, CAP_PERMITTED }; for (unsigned cx = 0; cx < ARRAYSIZE(capSets); ++cx) { if (cap_set_flag( capSet, capSets[cx], ARRAYSIZE(clearCaps), clearCaps, CAP_CLEAR)) die("Unable to clear process CAP_SYS_ADMIN"); } if (cap_set_proc(capSet)) die("Unable to configure process capabilities"); for (unsigned cx = 0; cx < ARRAYSIZE(capSets); ++cx) { if (cap_set_flag( capSet, capSets[cx], ARRAYSIZE(clearCaps), clearCaps, CAP_SET)) die("Unable to clear process CAP_SYS_ADMIN"); } errno = 0; if (!cap_set_proc(capSet)) die("Unexpected escalation of process capabilies"); cap_free(capSet); /* Forcing real, effective, and saved uids and gids to match the values * of the user invoking the process. * * This is important to allow an unprivileged kill(2) to deliver a * signal to this process running as pid 1. * * The supplementary group list inherited by the process remains unchanged. */ const gid_t gid = getgid(); const uid_t uid = getuid(); if (setresgid(gid, gid, gid)) die("Unable to set gid"); if (setresuid(uid, uid, uid)) die("Unable to set uid"); uid_t ruid_, * const ruid = &ruid_; uid_t euid_, * const euid = &euid_; uid_t suid_, * const suid = &suid_; if (getresuid(ruid, euid, suid)) die("Unable to query process uid"); if (uid != *ruid || uid != *euid || uid != *suid) die("Mismatched uid %d ruid %d euid %d suid %d", uid, ruid, euid, suid); gid_t rgid_, * const rgid = &rgid_; gid_t egid_, * const egid = &egid_; gid_t sgid_, * const sgid = &sgid_; if (getresgid(rgid, egid, sgid)) die("Unable to query process gid"); if (gid != *rgid || gid != *egid || gid != *sgid) die("Mismatched gid %d rgid %d egid %d sgid %d", gid, *rgid, *egid, *sgid); gid_t fsgid_ = setfsgid(-1), * const fsgid = &fsgid_; uid_t fsuid_ = setfsuid(-1), * const fsuid = &fsuid_; if (gid != *fsgid) die("Unexpected filesystem gid %d", *fsgid); if (uid != *fsuid) die("Unexpected filesystem uid %d", fsuid); if (uid) { errno = 0; if (!setreuid(-1, 0) || !setregid(-1, 0) || !setreuid(0, -1) || !setregid(0, -1)) die("Unexpected privilege escalation"); } errno = 0; if (!unshare(CLONE_NEWPID)) die("Unexpected unshare privilege escalation"); /* Now that privileges have been dropped, allow user core dumps which * have the side-effect of reconfiguring the ownership of /proc/pid. */ if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0)) die("Unable to enable core dumps"); } /* -------------------------------------------------------------------------- */ static void verify_unprivileged_role() { uid_t uid = getuid(); gid_t gid = getgid(); uid_t euid = geteuid(); gid_t egid = getegid(); if (uid != euid || gid != egid) die("Unexpected effective uid %d gid %d", euid, egid); uid_t fsuid = setfsuid(-1); gid_t fsgid = setfsgid(-1); if (uid != fsuid || gid != fsgid) die("Unexpected fsuid %d fsgid %d", fsuid, fsgid); } /* -------------------------------------------------------------------------- */ static int run_parent(struct Tty *aTty, struct Parent *aParent) { /* If there is a pid to match with getppid(2), then tie its fate * together with the parent. */ if (-1 != sPPid) { DEBUG("Checking parent pid %ld", sPPid); pdeathsig(sPPid); } /* Avoid holding references to stdin and stdout, leaving only * the grandchild to hold references. */ int ttyFd = aTty->mFd; drop_stdio(ttyFd); if (-1 != ttyFd) { close(ttyFd); ttyFd = STDIN_FILENO; } /* Ignore SIGPIPE so that write(2) errors will return EPIPE, rather * than terminating the caller. Prefer EPIPE since the writing loop * already has to handle other kinds of failure, and when invoked * from a shell, to avoid showing users confusing "Broken pipe" messages. */ if (SIG_ERR == signal(SIGPIPE, SIG_IGN)) die("Unable to ignore SIGPIPE"); /* Do not send a heartbeat to the child until after the child has * configured PDEATHSIG. This allows the child to detect the * case where the parent terminates prematurely. */ int syncReq; while (1) { syncReq = wait_child(aParent->mChild.mSyncRd); if (-1 != syncReq) break; if (EINTR != errno) { /* If the child terminates prematurely, no data will be read. * In this case, pretend that the child actually sent the * expected synchronisation value, and fall through to * waiting for the child process. */ if (!errno) syncReq = 0; break; } } if (0 != syncReq) die("Unable to synchronise with pid namespace %d", syncReq); /* Now that the child has configured PDEATHSIG (or terminated) * send a heartbeat to the child to show that the parent has * not terminated. This allows the child to detect that the * parent termination did not race it configuring PDEATHSIG. * * If the child itself terminated prematurely, fall through * to wait for the termination status. */ foreground(ttyFd, aParent->mChild.mPid); dispatch_child(aParent->mChild.mSyncWr); close(aParent->mChild.mSyncWr); return wait_process( aParent->mChild.mSyncRd, -1, aParent->mChild.mPid, ttyFd, aTty->mPgid); } /* -------------------------------------------------------------------------- */ static void run_child(struct Tty *aTty, struct Child *aChild) { /* Security modules will reset PDEATHSIG when privileges * change, so delay configuring PDEATHSIG until after uid and * gid are modified. * * When configuring PDDEATHSIG, getppid(2) does not convey * any useful information because it always returns zero * reflecting the fact that the parent lives in a different * pid namespace. * * Instead signal via mParent.mSyncWr to trigger the parent to * send a heartbeat back to the child. */ pdeathsig(0); dispatch_parent(aChild->mParent.mSyncWr, 0); /* Read the heartbeat from the parent. Lack of a heartbeat means * that the parent terminated just before PDEATHSIG was configured. */ if (wait_parent(aChild->mParent.mSyncRd)) pdeathsig(-1); close(aChild->mParent.mSyncRd); int grandChildSync[2]; if (pipe2(grandChildSync, O_CLOEXEC)) die("Unable to create grandchild sync pipe"); int grandChildSidSync[2]; if (pipe2(grandChildSidSync, O_CLOEXEC)) die("Unable to create grandchild sid sync pipe"); /* Not all commands are capable of running as pid 1, because they * get confused by seeing adopted child processes they did * not fork. For this reason, fork a grandchild to execute the command. */ pid_t childPid = getpid(); pid_t grandChildPid = fork(); if (-1 == grandChildPid) die("Unable to fork grandchild"); /* The child runs as the pid 1 root process in the new pid namespace, * leaving the grandchild to execute the command. */ if (grandChildPid) { /* The child was configured as process group leader above, and * the parent, child, and grandchild, all belong to the same * session with the same controlling terminal. * * Importantly, the child and grandchild have non-zero pgid * in the new pid namespace. * * Force the grandchild to be a process group leader to ensure * that it can be controlled as a separate foreground process group. * If the parent was a session leader, ensure that the grandchild is * also a session leader and that getsid(2) will report a non-zero * value. * * This has the consequence that neither the child, nor the * grandchild, can later be made session leaders since setsid(2) * requires that the caller cannot be a process group leader. * * It is important that process groups of both the child and * grandchild are not orphaned otherwise job control * signals SIGTSTP, SIGTTOU, and SIGTTIN, will be ignored. * * Posix says: * * A process that is a member of an orphaned process group * shall not be allowed to stop in response to the SIGTSTP, * SIGTTIN, or SIGTTOU signals. In cases where delivery of * one of these signals would stop such a process, the signal * shall be discarded. */ close(grandChildSidSync[1]); if (aChild->mParent.mSid == aChild->mParent.mPgid) { wait_child(grandChildSidSync[0]); } else { if (setpgid(grandChildPid, grandChildPid)) die("Unable to configure pgid %d", grandChildPid); } close(grandChildSidSync[0]); /* Avoid holding references to stdin and stdout, leaving only * the grandchild to hold references. * * Note also that the process might have a controlling terminal, but * have might also have been started as a background task. If * running as a foreground task, set the grandchild as the foreground * process group. */ int ttyFd = aTty->mFd; drop_stdio(ttyFd); if (-1 != ttyFd) { close(ttyFd); ttyFd = STDIN_FILENO; } foreground(ttyFd, grandChildPid); close(grandChildSync[0]); dispatch_child(grandChildSync[1]); close(grandChildSync[1]); run_init_pid1(aChild->mParent.mSyncWr, grandChildPid, ttyFd); } /* If the parent was placed in its own session, place the grandchild * in its own session to ensure that getsid(2) returns a non-zero * value in the new pid namespace. */ close(grandChildSidSync[0]); if (aChild->mParent.mSid == aChild->mParent.mPgid) { if (-1 == setsid()) die("Unable to create new session sid %d", getpid()); dispatch_parent(grandChildSidSync[1], 0); } close(grandChildSidSync[1]); close(aTty->mFd); close(aChild->mParent.mSyncWr); /* The child, and grandchild run in the same pid namespace, so the * outcome from getppid(2) is meaningful when configuring PDEATHSIG. */ pdeathsig(childPid); close(grandChildSync[1]); if (wait_parent(grandChildSync[0])) pdeathsig(-1); close(grandChildSync[0]); if (sigprocmask(SIG_SETMASK, &aChild->mInheritedSet, 0)) die("Unable to restore inherited signal mask"); DEBUG("Execute %s", *aChild->mCmd); execvp(*aChild->mCmd, aChild->mCmd); die("Unable to execute %s", *aChild->mCmd); } /* -------------------------------------------------------------------------- */ int main(int argc, char **argv) { /* PRIVILEGED */ struct Service service; /* PRIVILEGED */ /* PRIVILEGED */ pid_t childPid = privileged(&service, argc, argv); /* PRIVILEGED */ /* PRIVILEGED */ drop_privileges(); /* All the code beyond thing point runs at reduced privilege. * Explicitly verify that the process is not running with * elevated privileges. */ verify_unprivileged_role(); /* The child process is runs in the new pid nammespace, and will * follow up to run the target command. The parent waits for the * child to terminate, and also handles requests from the child * to send a termination signal. */ if (!childPid) run_child(&service.mTty, &service.mChild); return run_parent(&service.mTty, &service.mParent); } /* -------------------------------------------------------------------------- */
0.996094
high
Headers/Frameworks/Ozone/OZBorderedView.h
CommandPost/FinalCutProFrameworks
3
8172336
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 11 2021 20:53:35). // // Copyright (C) 1997-2019 <NAME>. // #import <AppKit/NSView.h> @class NSColor; @interface OZBorderedView : NSView { BOOL _topBorder; BOOL _bottomBorder; BOOL _leftBorder; BOOL _rightBorder; NSColor *_backgroundColor; } @property(retain, nonatomic) NSColor *backgroundColor; // @synthesize backgroundColor=_backgroundColor; @property(nonatomic) BOOL rightBorder; // @synthesize rightBorder=_rightBorder; @property(nonatomic) BOOL leftBorder; // @synthesize leftBorder=_leftBorder; @property(nonatomic) BOOL bottomBorder; // @synthesize bottomBorder=_bottomBorder; @property(nonatomic) BOOL topBorder; // @synthesize topBorder=_topBorder; - (void)drawRect:(struct CGRect)arg1; - (id)borderColor; - (void)dealloc; @end
0.578125
medium
sys/arch/evbarm/include/intr.h
calmsacibis995/minix
0
3405224
<reponame>calmsacibis995/minix<gh_stars>0 /* $NetBSD: intr.h,v 1.26 2014/03/13 23:48:38 matt Exp $ */ /* * Copyright (c) 2001, 2003 Wasabi Systems, Inc. * All rights reserved. * * Written by <NAME> for Wasabi Systems, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed for the NetBSD Project by * Wasabi Systems, Inc. * 4. The name of Wasabi Systems, Inc. may not be used to endorse * or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _EVBARM_INTR_H_ #define _EVBARM_INTR_H_ #ifdef _KERNEL /* Interrupt priority "levels". */ #define IPL_NONE 0 /* nothing */ #define IPL_SOFTCLOCK 1 /* clock */ #define IPL_SOFTBIO 2 /* block I/O */ #define IPL_SOFTNET 3 /* software network interrupt */ #define IPL_SOFTSERIAL 4 /* software serial interrupt */ #define IPL_VM 5 /* memory allocation */ #define IPL_SCHED 6 /* clock interrupt */ #define IPL_HIGH 7 /* everything */ #define NIPL 8 /* Interrupt sharing types. */ #define IST_NONE 0 /* none */ #define IST_PULSE 1 /* pulsed */ #define IST_EDGE 2 /* edge-triggered */ #define IST_LEVEL 3 /* level-triggered */ #define IST_LEVEL_LOW IST_LEVEL #define IST_LEVEL_HIGH 4 #define IST_EDGE_FALLING IST_EDGE #define IST_EDGE_RISING 5 #define IST_EDGE_BOTH 6 #define IST_SOFT 7 #define IST_MPSAFE 0x100 /* interrupt is MPSAFE */ #ifndef _LOCORE #include <sys/queue.h> #if defined(_LKM) int _splraise(int); int _spllower(int); void splx(int); #else /* _LKM */ #include "opt_arm_intr_impl.h" #if defined(ARM_INTR_IMPL) /* * Each board needs to define the following functions: * * int _splraise(int); * int _spllower(int); * void splx(int); * * These may be defined as functions, static inline functions, or macros, * but there must be a _spllower() and splx() defined as functions callable * from assembly language (for cpu_switch()). However, since it's quite * useful to be able to inline splx(), you could do something like the * following: * * in <boardtype>_intr.h: * static inline int * boardtype_splx(int spl) * {...} * * #define splx(nspl) boardtype_splx(nspl) * ... * and in boardtype's machdep code: * * ... * #undef splx * int * splx(int spl) * { * return boardtype_splx(spl); * } */ #include ARM_INTR_IMPL #else /* ARM_INTR_IMPL */ #error ARM_INTR_IMPL not defined. #endif /* ARM_INTR_IMPL */ #endif /* _LKM */ typedef uint8_t ipl_t; typedef struct { ipl_t _ipl; } ipl_cookie_t; static inline ipl_cookie_t makeiplcookie(ipl_t ipl) { return (ipl_cookie_t){._ipl = ipl}; } static inline int splraiseipl(ipl_cookie_t icookie) { return _splraise(icookie._ipl); } #define spl0() _spllower(IPL_NONE) #include <sys/spl.h> #endif /* ! _LOCORE */ #endif /* _KERNEL */ #endif /* _EVBARM_INTR_H_ */
0.988281
high
processor/pa/armSemiHost.c
brandonhamilton/MURACsim
3
3437992
/* * Copyright (c) 2005-2011 Imperas Software Ltd., www.imperas.com * * YOUR ACCESS TO THE INFORMATION IN THIS MODEL IS CONDITIONAL * UPON YOUR ACCEPTANCE THAT YOU WILL NOT USE OR PERMIT OTHERS * TO USE THE INFORMATION FOR THE PURPOSES OF DETERMINING WHETHER * IMPLEMENTATIONS OF THE ARM ARCHITECTURE INFRINGE ANY THIRD * PARTY PATENTS. * * THE LICENSE BELOW EXTENDS ONLY TO USE OF THE SOFTWARE FOR * MODELING PURPOSES AND SHALL NOT BE CONSTRUED AS GRANTING * A LICENSE TO CREATE A HARDWARE IMPLEMENTATION OF THE * FUNCTIONALITY OF THE SOFTWARE LICENSED HEREUNDER. * YOU MAY USE THE SOFTWARE SUBJECT TO THE LICENSE TERMS BELOW * PROVIDED THAT YOU ENSURE THAT THIS NOTICE IS REPLICATED UNMODIFIED * AND IN ITS ENTIRETY IN ALL DISTRIBUTIONS OF THE SOFTWARE, * MODIFIED OR UNMODIFIED, IN SOURCE CODE OR IN BINARY FORM. * * Licensed under an Imperas Modfied 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.ovpworld.org/licenses/OVP_MODIFIED_1.0_APACHE_OPEN_SOURCE_LICENSE_2.0.pdf * * 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. * */ // VMI header files #include "vmi/vmiTypes.h" #include "vmi/vmiMessage.h" #include "vmi/vmiMt.h" // model header files #include "armFunctions.h" #include "armRegisters.h" #include "armStructure.h" // // Prefix for messages from this module // #define CPU_PREFIX "ARM_SEMIHOST" // // Return processor endianness // inline static memEndian getEndian(armP arm) { return armGetEndian((vmiProcessorP)arm, False); } // // Morph return from an opaque intercepted function // VMI_INT_RETURN_FN(armIntReturnCB) { vmimtUncondJumpReg(0, ARM_REG(ARM_REG_LR), VMI_NOREG, vmi_JH_RETURN); } // // This callback should create code to assign function result to the standard // return result register // VMI_INT_RESULT_FN(armIntResultCB) { vmimtMoveRR(32, ARM_REG(0), VMI_FUNCRESULT); } // // This callback should create code to push 32-bit function parameter 'paramNum' // static Uns32 push4ByteArg(vmiProcessorP processor, Uns32 paramNum) { if(paramNum<=3) { // argument in a register vmimtArgReg(32, ARM_REG(paramNum)); } else { // argument on the stack armP arm = (armP)processor; // fetch into a temporary vmimtLoadRRO( 32, // destBits 32, // memBits (paramNum-4)*4, // offset ARM_TEMP(0), // destination (rd) ARM_REG(ARM_REG_SP), // stack address (ra) getEndian(arm), // endian False, // signExtend False // checkAlign ); // push temporary argument vmimtArgReg(32, ARM_TEMP(0)); } return paramNum+1; } // // This callback should create code to push 64-bit function parameter 'paramNum' // static Uns32 push8ByteArg(vmiProcessorP processor, Uns32 paramNum) { paramNum += push4ByteArg(processor, paramNum); paramNum += push4ByteArg(processor, paramNum); return paramNum; } // // This callback should create code to push address function parameter 'paramNum' // static Uns32 pushAddressArg(vmiProcessorP processor, Uns32 paramNum) { if(paramNum<=3) { // argument in a register vmimtArgRegSimAddress(32, ARM_REG(paramNum)); } else { // argument on the stack armP arm = (armP)processor; // fetch into a temporary vmimtLoadRRO( 32, // destBits 32, // memBits (paramNum-4)*4, // offset ARM_TEMP(0), // destination (rd) ARM_REG(ARM_REG_SP), // stack address (ra) getEndian(arm), // endian False, // signExtend False // checkAlign ); // push temporary argument vmimtArgRegSimAddress(32, ARM_TEMP(0)); } return paramNum+1; } // // This callback should create code to push function arguments prior to an // Imperas standard intercept // VMI_INT_PAR_FN(armIntParCB) { Uns32 paramNum = 0; char ch; while((ch=*format++)) { switch(ch) { case '4': paramNum = push4ByteArg(processor, paramNum); break; case '8': paramNum = push8ByteArg(processor, paramNum); break; case 'a': paramNum = pushAddressArg(processor, paramNum); break; default: VMI_ABORT("Unrecognised format character '%c'", ch); } } }
0.996094
high
ColdKeySwift/simulatorHelper.c
BitGo/coldkey-ios
0
3470760
// // simulatorHelper.c // ColdKeySwift // // Created by <NAME> on 8/4/15. // Copyright (c) 2015 BitGo, Inc. All rights reserved. // #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> FILE *fopen$UNIX2003( const char *filename, const char *mode ) { return fopen(filename, mode); } int fputs$UNIX2003(const char *res1, FILE *res2){ return fputs(res1,res2); } int nanosleep$UNIX2003(int val){ return usleep(val); } char* strerror$UNIX2003(int errornum){ return strerror(errornum); } double strtod$UNIX2003(const char *nptr, char **endptr){ return strtod(nptr, endptr); } size_t fwrite$UNIX2003( const void *a, size_t b, size_t c, FILE *d ) { return fwrite(a, b, c, d); }
0.964844
high
Cinegy.Srt.Wrapper/Cinegy.Srt.Wrapper.h
Cinegy/Cinegy.SRT
16
3503528
// Cinegy.Srt.Wrapper.h #pragma once using namespace System; using namespace msclr::interop; namespace Cinegy { namespace Srt { public delegate void OnDataEventHandler(const char* data, size_t dataSize); public ref class SrtReceiver { public: //Helper(void); void SrtReceiver::Run(); void SrtReceiver::Stop(); int GetPort() { return _port; }; void SetPort(int value) { _port = value; } void SetHostname(String^ value) { _strHostname = _strHostname->Copy(value); } String^ GetHostname() { return _strHostname; } event OnDataEventHandler ^ OnDataReceived; private: int _port; String^ _strHostname; void FireOnDataEvent(const char* data, size_t size) { OnDataReceived(data, size); } }; } }
0.992188
high
task_0.c
zappitec/ZOS
0
6603048
#include <stdio.h> #include <stdbool.h> #include <time.h> #include "zos.h" #include "tasks.h" extern volatile int sw1; extern volatile int sw2; extern volatile int sw3; float time_from(float start) { return ((float)clock()-start)/CLOCKS_PER_SEC; } ZOS_TASK_START(task_0) //declare local variables: static float start; static float end; static int i; //end local variables, Task initialization: ZOS_TASKINIT //initialize local variables if needed: start = (float)clock(); //end initialization printf("Task0 - BLK0\n"); //block0 ZOS_WAITFOR(sw1) //printf("tsk0 cond 1 satisfied -"); printf("Task0 - BLK1\n"); //block1 ZOS_WAITFOR(sw2) //printf("tsk0 cond 2 satisfied -"); printf("Task0 - BLK2\n"); //block2 start = (float)clock(); ZOS_WAITFOR(time_from(start)>1) printf("Task0: After wait\n"); printf("Task0: Clock: %f\n",time_from(start)); //printf("tsk0 cond 3 satisfied -"); printf("Task0 - BLK3\n"); //block3 ZOS_TASK_END
0.585938
high
qtlib/commonutil.h
ericosur/myqt
0
6635816
#ifndef __COMMON_UTIL_H__ #define __COMMON_UTIL_H__ #include <QString> #include <QByteArray> #include <QFile> #include <QDebug> #include <QTime> #include <QCoreApplication> #include <stdio.h> #include <iostream> bool writeStringToFile(const QString& str, const QString& fn); bool writeByteArrayToFile(const QByteArray& arr, const QString& fn); bool readFileToByteArray(QByteArray& arr, const QString& fn); #if QT_VERSION >= 0x050500 extern bool g_messageVerbose; void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg); #endif #endif // __COMMON_UTIL_H__
0.96875
high
ios/Classes/TiMapModule.h
justingreerbbi/Ti.MapPlus
0
6668584
<reponame>justingreerbbi/Ti.MapPlus<gh_stars>0 /** * Appcelerator Titanium Mobile * Copyright (c) 2009-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #import "TiModule.h" #define MAKE_IOS7_SYSTEM_PROP(name,map) \ -(NSNumber*)name \ {\ if (![TiUtils isIOS7OrGreater]) {\ const char *propName = #name;\ [TiMapModule logAddedIniOS7Warning:[NSString stringWithUTF8String:propName]];\ return nil;\ }\ return [NSNumber numberWithInt:map];\ }\ @interface TiMapModule : TiModule { UIColor *colorRed; } +(void)logAddedIniOS7Warning:(NSString*)name; @property(nonatomic,readonly) NSNumber *STANDARD_TYPE; @property(nonatomic,readonly) NSNumber *NORMAL_TYPE; // For parity with Android @property(nonatomic,readonly) NSNumber *SATELLITE_TYPE; @property(nonatomic,readonly) NSNumber *HYBRID_TYPE; #ifdef __IPHONE_9_0 @property(nonatomic,readonly) NSNumber *HYBRID_FLYOVER_TYPE; @property(nonatomic,readonly) NSNumber *SATELLITE_FLYOVER_TYPE; #endif @property(nonatomic,readonly) NSNumber *ANNOTATION_RED; @property(nonatomic,readonly) NSNumber *ANNOTATION_GREEN; @property(nonatomic,readonly) NSNumber *ANNOTATION_PURPLE; @property(nonatomic,readonly) NSNumber *ANNOTATION_DRAG_STATE_NONE; @property(nonatomic,readonly) NSNumber *ANNOTATION_DRAG_STATE_START; @property(nonatomic,readonly) NSNumber *ANNOTATION_DRAG_STATE_DRAG; @property(nonatomic,readonly) NSNumber *ANNOTATION_DRAG_STATE_CANCEL; @property(nonatomic,readonly) NSNumber *ANNOTATION_DRAG_STATE_END; @end
0.960938
high
opencpu/mc60e/SDK/cloud/entity/gitwizs/src/gitwizs_cloud.c
Wiz-IO/framework-wizio-gsm
1
6701352
#include "custom_feature_def.h" #ifdef __OCPU_SMART_CLOUD_SUPPORT__ #ifdef __GITWIZS_SOLUTION__ #include "cloud.h" #include "gagent.h" #include "hal_socket.h" #include "adapter.h" #include "mqttxpg.h" #include "utils.h" s32 g_cloud_task_id; //cloud task entry for cloud interactive void gagent_cloud_task(s32 taskId) { ST_MSG msg; g_cloud_task_id = taskId; APP_DEBUG("cloud task is running\r\n"); while (TRUE) { Adapter_GetMsg(&msg); switch(msg.message) { case MSG_ID_GPRS_OK_HINT: //login to http server APP_DEBUG("begin to logging http server\r\n"); Adapter_Login_Gservice_Init(); break; case MSG_ID_CLOUD_CONFIG: Cloud_ConfigDataHandle(PGC); break; case MSG_ID_MQTT_CONFIG: //login to mqtt server APP_DEBUG("begin to logging mqtt server\r\n"); Adapter_Login_MQTT_Init(); break; case MSG_ID_MQTT_READY: Cloud_M2MDataHandle(PGC); break; case MSG_ID_PING_REQUEST: MQTT_HeartbeatTime(); break; case MSG_ID_CLOUD_SEND_DATA: if(PGC->rtinfo.waninfo.mqttstatus == MQTT_STATUS_RUNNING) { // Adapter_Memcpy(PGC->rtinfo.Cloud_Txbuf,PGC->rtinfo.Rxbuf,sizeof(packet)); Cloud_SendData(PGC,(ppacket)msg.param1,(((ppacket)msg.param1)->pend)-(((ppacket)msg.param1)->ppayload) ); APP_DEBUG("ReSetpacket Type : CLOUD_DATA_OUT \r\n"); PGC->rtinfo.Cloud_Txbuf->type = SetPacketType(PGC->rtinfo.Cloud_Txbuf->type, CLOUD_DATA_OUT, 0); } else { APP_DEBUG("MQTT is not ready,so pls check....\r\n"); } break; default: break; } } } #endif #endif
0.597656
high
include/UnigineDecals.h
CleoBeldia/CalmWood-CPP
2
6734120
/* Copyright (C) 2005-2020, UNIGINE. All rights reserved. * * This file is a part of the UNIGINE 2.11.0.1 SDK. * * Your use and / or redistribution of this software in source and / or * binary form, with or without modification, is subject to: (i) your * ongoing acceptance of and compliance with the terms and conditions of * the UNIGINE License Agreement; and (ii) your inclusion of this notice * in any version of this software that you use or redistribute. * A copy of the UNIGINE License Agreement is available by contacting * UNIGINE. at http://unigine.com/ */ // DO NOT EDIT DIRECTLY. This is an auto-generated file. Your changes will be lost. #pragma once #include "UnigineMaterial.h" #include "UnigineNode.h" #include "UnigineMesh.h" namespace Unigine { ////////////////////////////////////////////////////////////////////////// class UNIGINE_API Decal : public Node { public: static bool convertible(Node *node) { return node && node->isDecal(); } void setLifeTime(float time); float getLifeTime() const; void setFadeTime(float time); float getFadeTime() const; void setInitTime(float time); float getInitTime() const; Ptr<Material> getMaterialInherit() const; const char *getMaterialName() const; int setMaterial(const char *name); int setMaterial(const UGUID & guid); int setMaterial(const Ptr<Material> &mat); Ptr<Material> getMaterial() const; void setMaxFadeDistance(float distance); float getMaxFadeDistance() const; void setMaxVisibleDistance(float distance); float getMaxVisibleDistance() const; void setMinFadeDistance(float distance); float getMinFadeDistance() const; void setMinVisibleDistance(float distance); float getMinVisibleDistance() const; void setTexCoord(const Math::vec4 &coord); Math::vec4 getTexCoord() const; void setViewportMask(int mask); int getViewportMask() const; void setIntersectionMask(int mask); int getIntersectionMask() const; int isMaterialInherited() const; int isTerrainHole() const; int inside(const Math::vec3 &p); }; typedef Ptr<Decal> DecalPtr; ////////////////////////////////////////////////////////////////////////// class UNIGINE_API DecalMesh : public Decal { public: static int type() { return Node::DECAL_MESH; } static bool convertible(Node *node) { return (node && node->getType() == type()); } static Ptr<DecalMesh> create(const Ptr<Mesh> &mesh, float radius, const char *material_name); static Ptr<DecalMesh> create(const char *mesh_path, float radius, const char *material_name); void setMeshName(const char *path, bool force_load); void setMeshName(const char *name); const char *getMeshName() const; int setMesh(const Ptr<Mesh> &mesh, bool unique = true); int getMesh(const Ptr<Mesh> &mesh) const; void setRadius(float radius); float getRadius() const; void loadMesh(const char *path, bool unique = false); int saveMesh(const char *path) const; }; typedef Ptr<DecalMesh> DecalMeshPtr; ////////////////////////////////////////////////////////////////////////// class UNIGINE_API DecalOrtho : public Decal { public: static int type() { return Node::DECAL_ORTHO; } static bool convertible(Node *node) { return (node && node->getType() == type()); } static Ptr<DecalOrtho> create(float radius, float width, float height, const char *material); void setHeight(float height); float getHeight() const; void setRadius(float radius); float getRadius() const; void setWidth(float width); float getWidth() const; void setZNear(float znear); float getZNear() const; Math::mat4 getProjection() const; }; typedef Ptr<DecalOrtho> DecalOrthoPtr; ////////////////////////////////////////////////////////////////////////// class UNIGINE_API DecalProj : public Decal { public: static int type() { return Node::DECAL_PROJ; } static bool convertible(Node *node) { return (node && node->getType() == type()); } static Ptr<DecalProj> create(float radius, float fov, float aspect, const char *name); void setAspect(float aspect); float getAspect() const; void setFov(float fov); float getFov() const; void setRadius(float radius); float getRadius() const; void setZNear(float znear); float getZNear() const; Math::mat4 getProjection() const; }; typedef Ptr<DecalProj> DecalProjPtr; } // namespace Unigine
1
high
WebKit/Source/WebCore/html/parser/HTMLToken.h
JavaScriptTesting/LJS
1
3566712
/* * Copyright (C) 2010 Google, Inc. 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 APPLE INC. ``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 APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef HTMLToken_h #define HTMLToken_h #include "MarkupTokenBase.h" namespace WebCore { class HTMLTokenTypes { public: enum Type { Uninitialized, DOCTYPE, StartTag, EndTag, Comment, Character, EndOfFile, }; class DoctypeData : public DoctypeDataBase { WTF_MAKE_NONCOPYABLE(DoctypeData); public: DoctypeData() : m_forceQuirks(false) { } bool m_forceQuirks; }; }; class HTMLToken : public MarkupTokenBase<HTMLTokenTypes, HTMLTokenTypes::DoctypeData> { public: void appendToName(UChar character) { ASSERT(m_type == HTMLTokenTypes::StartTag || m_type == HTMLTokenTypes::EndTag || m_type == HTMLTokenTypes::DOCTYPE); MarkupTokenBase<HTMLTokenTypes, HTMLTokenTypes::DoctypeData>::appendToName(character); } const DataVector& name() const { ASSERT(m_type == HTMLTokenTypes::StartTag || m_type == HTMLTokenTypes::EndTag || m_type == HTMLTokenTypes::DOCTYPE); return MarkupTokenBase<HTMLTokenTypes, HTMLTokenTypes::DoctypeData>::name(); } bool forceQuirks() const { ASSERT(m_type == HTMLTokenTypes::DOCTYPE); return m_doctypeData->m_forceQuirks; } void setForceQuirks() { ASSERT(m_type == HTMLTokenTypes::DOCTYPE); m_doctypeData->m_forceQuirks = true; } }; class AtomicHTMLToken : public AtomicMarkupTokenBase<HTMLToken> { WTF_MAKE_NONCOPYABLE(AtomicHTMLToken); public: AtomicHTMLToken(HTMLToken& token) : AtomicMarkupTokenBase<HTMLToken>(&token) { } AtomicHTMLToken(HTMLTokenTypes::Type type, AtomicString name, PassRefPtr<NamedNodeMap> attributes = 0) : AtomicMarkupTokenBase<HTMLToken>(type, name, attributes) { } bool forceQuirks() const { ASSERT(m_type == HTMLTokenTypes::DOCTYPE); return m_doctypeData->m_forceQuirks; } }; } #endif
0.996094
high
src/codec_utils/RRC/SIB6.c
wineslab/colosseum-scope-e2
1
3599480
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "NR-RRC-Definitions" * found in "../../../rrc_15.5.1_asn.asn1" * `asn1c -D ./rrc_out_hlal -fcompound-names -fno-include-deps -findirect-choice -gen-PER -no-gen-example` */ #include "SIB6.h" static int memb_messageIdentifier_constraint_1(const asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { const BIT_STRING_t *st = (const BIT_STRING_t *)sptr; size_t size; if(!sptr) { ASN__CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } if(st->size > 0) { /* Size in bits */ size = 8 * st->size - (st->bits_unused & 0x07); } else { size = 0; } if((size == 16)) { /* Constraint check succeeded */ return 0; } else { ASN__CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } static int memb_serialNumber_constraint_1(const asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { const BIT_STRING_t *st = (const BIT_STRING_t *)sptr; size_t size; if(!sptr) { ASN__CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } if(st->size > 0) { /* Size in bits */ size = 8 * st->size - (st->bits_unused & 0x07); } else { size = 0; } if((size == 16)) { /* Constraint check succeeded */ return 0; } else { ASN__CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } static int memb_warningType_constraint_1(const asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { const OCTET_STRING_t *st = (const OCTET_STRING_t *)sptr; size_t size; if(!sptr) { ASN__CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } size = st->size; if((size == 2)) { /* Constraint check succeeded */ return 0; } else { ASN__CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } static asn_oer_constraints_t asn_OER_memb_messageIdentifier_constr_2 CC_NOTUSED = { { 0, 0 }, 16 /* (SIZE(16..16)) */}; static asn_per_constraints_t asn_PER_memb_messageIdentifier_constr_2 CC_NOTUSED = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 0, 0, 16, 16 } /* (SIZE(16..16)) */, 0, 0 /* No PER value map */ }; static asn_oer_constraints_t asn_OER_memb_serialNumber_constr_3 CC_NOTUSED = { { 0, 0 }, 16 /* (SIZE(16..16)) */}; static asn_per_constraints_t asn_PER_memb_serialNumber_constr_3 CC_NOTUSED = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 0, 0, 16, 16 } /* (SIZE(16..16)) */, 0, 0 /* No PER value map */ }; static asn_oer_constraints_t asn_OER_memb_warningType_constr_4 CC_NOTUSED = { { 0, 0 }, 2 /* (SIZE(2..2)) */}; static asn_per_constraints_t asn_PER_memb_warningType_constr_4 CC_NOTUSED = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 0, 0, 2, 2 } /* (SIZE(2..2)) */, 0, 0 /* No PER value map */ }; asn_TYPE_member_t asn_MBR_SIB6_1[] = { { ATF_NOFLAGS, 0, offsetof(struct SIB6, messageIdentifier), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_BIT_STRING, 0, { &asn_OER_memb_messageIdentifier_constr_2, &asn_PER_memb_messageIdentifier_constr_2, memb_messageIdentifier_constraint_1 }, 0, 0, /* No default value */ "messageIdentifier" }, { ATF_NOFLAGS, 0, offsetof(struct SIB6, serialNumber), (ASN_TAG_CLASS_CONTEXT | (1 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_BIT_STRING, 0, { &asn_OER_memb_serialNumber_constr_3, &asn_PER_memb_serialNumber_constr_3, memb_serialNumber_constraint_1 }, 0, 0, /* No default value */ "serialNumber" }, { ATF_NOFLAGS, 0, offsetof(struct SIB6, warningType), (ASN_TAG_CLASS_CONTEXT | (2 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_OCTET_STRING, 0, { &asn_OER_memb_warningType_constr_4, &asn_PER_memb_warningType_constr_4, memb_warningType_constraint_1 }, 0, 0, /* No default value */ "warningType" }, { ATF_POINTER, 1, offsetof(struct SIB6, lateNonCriticalExtension), (ASN_TAG_CLASS_CONTEXT | (3 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_OCTET_STRING, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "lateNonCriticalExtension" }, }; static const int asn_MAP_SIB6_oms_1[] = { 3 }; static const ber_tlv_tag_t asn_DEF_SIB6_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static const asn_TYPE_tag2member_t asn_MAP_SIB6_tag2el_1[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* messageIdentifier */ { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* serialNumber */ { (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 }, /* warningType */ { (ASN_TAG_CLASS_CONTEXT | (3 << 2)), 3, 0, 0 } /* lateNonCriticalExtension */ }; asn_SEQUENCE_specifics_t asn_SPC_SIB6_specs_1 = { sizeof(struct SIB6), offsetof(struct SIB6, _asn_ctx), asn_MAP_SIB6_tag2el_1, 4, /* Count of tags in the map */ asn_MAP_SIB6_oms_1, /* Optional members */ 1, 0, /* Root/Additions */ 4, /* First extension addition */ }; asn_TYPE_descriptor_t asn_DEF_SIB6 = { "SIB6", "SIB6", &asn_OP_SEQUENCE, asn_DEF_SIB6_tags_1, sizeof(asn_DEF_SIB6_tags_1) /sizeof(asn_DEF_SIB6_tags_1[0]), /* 1 */ asn_DEF_SIB6_tags_1, /* Same as above */ sizeof(asn_DEF_SIB6_tags_1) /sizeof(asn_DEF_SIB6_tags_1[0]), /* 1 */ { 0, 0, SEQUENCE_constraint }, asn_MBR_SIB6_1, 4, /* Elements count */ &asn_SPC_SIB6_specs_1 /* Additional specs */ };
0.917969
high
C/useafterfree/sbrk.c
mudongliang/Language_Programming
0
5032248
/************************************************************************* > File Name: sbrk.c > Author: mudongliang > Mail: <EMAIL> > Created Time: Mon 23 Nov 2015 03:51:48 PM CST ************************************************************************/ #include<stdio.h> #include<unistd.h> #include<sys/types.h> int main() { void *curr_brk, *tmp_brk = NULL; printf("Welcome to sbrk example : %d\n", getpid()); tmp_brk = curr_brk = sbrk(0); printf("Program Break Location1: %p\n", curr_brk); getchar(); brk(curr_brk+0x1000); curr_brk = sbrk(0); printf("Program break Location2: %p\n", curr_brk); getchar(); brk(tmp_brk); curr_brk = sbrk(0); printf("Program break Location3: %p\n", curr_brk); getchar(); return 0; }
0.5
low
ProtoMsg/stdafx.h
EvanGertis/Dev_RisLib
0
5065016
<gh_stars>0 // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once //#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers //#include <windows.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <stdlib.h> #include "prnPrint.h" #include "my_functions.h" #include "risPortableCalls.h" // TODO: reference additional headers your program requires here
0.839844
low
control/async.c
NLAFET/plasma
9
5097808
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * **/ #include "plasma_async.h" #include "plasma_internal.h" #include <stdlib.h> /******************************************************************************/ int plasma_request_fail(plasma_sequence_t *sequence, plasma_request_t *request, int status) { sequence->request = request; sequence->status = status; request->status = status; return status; } /******************************************************************************/ int plasma_sequence_create(plasma_sequence_t **sequence) { *sequence = (plasma_sequence_t*)malloc(sizeof(plasma_sequence_t)); if (*sequence == NULL) { plasma_error("malloc() failed"); return PlasmaErrorOutOfMemory; } (*sequence)->status = PlasmaSuccess; return PlasmaSuccess; } /******************************************************************************/ int plasma_sequence_destroy(plasma_sequence_t *sequence) { free(sequence); return PlasmaSuccess; }
0.992188
high
Source/Framework/Core/Components/TeCSphereCollider.h
fabsgc/TweedeFrameworkRedux
57
5130576
#pragma once #include "TeCorePrerequisites.h" #include "Physics/TeSphereCollider.h" #include "Components/TeCCollider.h" namespace te { /** * @copydoc SphereCollider * * @note Wraps SphereCollider as a Component. */ class TE_CORE_EXPORT CSphereCollider : public CCollider { public: CSphereCollider(const HSceneObject& parent, float radius = 1.0f); /** Return Component type */ static UINT32 GetComponentType() { return TID_CSphereCollider; } /** @copydoc Component::Clone */ void Clone(const HSphereCollider& c); /** @copydoc SphereCollider::SetRadius */ void SetRadius(float radius); /** @copydoc SphereCollider::GetRadius */ float GetRadius() const { return _radius; } protected: friend class SceneObject; /** @copydoc CCollider::CreateInternal */ SPtr<Collider> CreateInternal() override; /** @copydoc CCollider::RestoreInternal */ void RestoreInternal() override; /** Returns the box collider that this component wraps. */ SphereCollider* _getInternal() const { return static_cast<SphereCollider*>(_internal.get()); } protected: CSphereCollider(); // Serialization only protected: float _radius = 1.0f; }; }
0.996094
high
tests/tile_bitmap_to_tile.c
sadistech/nesromtool2
3
5163344
#include "nrt.h" #include <assert.h> int main() { nrt_tile *tile = NRT_TILE_ALLOC; nrt_tile_bitmap *bitmap = NRT_TILE_BITMAP_ALLOC; assert(tile); assert(bitmap); char pixels[] = { 1, 1, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; memcpy(bitmap->pixels, pixels, NRT_TILE_WIDTH_PX * NRT_TILE_HEIGHT_PX); char expected_chan_a[NRT_TILE_CHANNEL_SIZE]; char expected_chan_b[NRT_TILE_CHANNEL_SIZE]; expected_chan_a[0] = 0b11110000; expected_chan_a[1] = 0b00000000; expected_chan_a[2] = 0b11110000; expected_chan_a[3] = 0b00000000; expected_chan_a[4] = 0b11110000; expected_chan_a[5] = 0b00000000; expected_chan_a[6] = 0b11110000; expected_chan_a[7] = 0b00000000; expected_chan_b[0] = 0b00111100; expected_chan_b[1] = 0b00000000; expected_chan_b[2] = 0b00111100; expected_chan_b[3] = 0b00000000; expected_chan_b[4] = 0b00111100; expected_chan_b[5] = 0b00000000; expected_chan_b[6] = 0b00111100; expected_chan_b[7] = 0b00000000; nrt_bitmap_to_tile(bitmap, tile); assert( memcmp(tile->chan_a, expected_chan_a, NRT_TILE_CHANNEL_SIZE) == 0 ); assert( memcmp(tile->chan_b, expected_chan_b, NRT_TILE_CHANNEL_SIZE) == 0 ); }
0.992188
high
src/cacheproxy/http/regex.h
bestofsong/ss-cache-proxy
0
5196112
// // Created by wansong on 11/03/2018. // #ifndef CACHE_PROXY_REGEX_H #define CACHE_PROXY_REGEX_H namespace smartstudy { const std::regex &get_http_field_re(); } #endif //CACHE_PROXY_REGEX_H
0.585938
high
healthViewController.h
yfhlearnios/000
0
562448
<filename>healthViewController.h // // healthViewController.h // iLife // // Created by mirror on 16/4/27. // Copyright © 2016年 Mirror. All rights reserved. // #import <UIKit/UIKit.h> @interface healthViewController : UIViewController @end
0.482422
low
Program_Linelance/Code/src/func_ReadSensorLineData.c
vladubase/Line-Follower-Robot
0
595216
<gh_stars>0 /**** * @name Linelance_linefollower * @file func_ReadSensorLineData.c * * @author Uladzislau 'vladubase' Dubatouka * <<EMAIL>> * @version V1.0 * @date 13-February-2021 * @link https://github.com/vladubase/Linelance * *****/ /************************************** Includes **************************************/ #include "func_ReadSensorLineData.h" /************************************** Function **************************************/ void ReadSensorLineData (void) { /* * @brief This function save valeus from sensors to the array line_data. */ // DEFINITION OF VARIABLES extern bool line_data[]; uint8_t i = 0; // char port_num[1]; // char port_state[1]; // FUNCTION // USART1_SendString ("\n\n"); for (i = 0; i < 8; i++) { // Write data from PA0 to PA7. line_data[i] = ((GPIOA->IDR) & (1 << i)); // sprintf (port_num, "%u", i); // USART1_SendString ("PORT "); // USART1_SendString (port_num); // USART1_SendString (", VALUE "); // sprintf (port_state, "%u", line_data[i]); // USART1_SendString (port_state); // USART1_SendString ("\r\n"); } }
0.714844
high
headers/os/package/GlobalWritableFileInfo.h
Kirishikesan/haiku
1,338
2027984
<reponame>Kirishikesan/haiku<gh_stars>1000+ /* * Copyright 2013, Haiku, Inc. * Distributed under the terms of the MIT License. */ #ifndef _PACKAGE__GLOBAL_WRITABLE_FILE_INFO_H_ #define _PACKAGE__GLOBAL_WRITABLE_FILE_INFO_H_ #include <package/WritableFileUpdateType.h> #include <String.h> namespace BPackageKit { namespace BHPKG { struct BGlobalWritableFileInfoData; } class BGlobalWritableFileInfo { public: BGlobalWritableFileInfo(); BGlobalWritableFileInfo( const BHPKG::BGlobalWritableFileInfoData& infoData); BGlobalWritableFileInfo(const BString& path, BWritableFileUpdateType updateType, bool isDirectory); ~BGlobalWritableFileInfo(); status_t InitCheck() const; const BString& Path() const; bool IsIncluded() const; BWritableFileUpdateType UpdateType() const; bool IsDirectory() const; void SetTo(const BString& path, BWritableFileUpdateType updateType, bool isDirectory); private: BString fPath; BWritableFileUpdateType fUpdateType; bool fIsDirectory; }; } // namespace BPackageKit #endif // _PACKAGE__GLOBAL_WRITABLE_FILE_INFO_H_
0.996094
high
srclua5/il_glcanvas.c
phasis68/iup_mac
5
2060752
<gh_stars>1-10 /****************************************************************************** * Automatically generated file (iuplua5). Please don't change anything. * *****************************************************************************/ #include <stdlib.h> #include <lua.h> #include <lauxlib.h> #include "iup.h" #include "iuplua.h" #include "iupgl.h" #include "il.h" static int glcanvas_action(Ihandle *self, int p0, int p1) { lua_State *L = iuplua_call_start(self, "action"); lua_pushnumber(L, p0); lua_pushnumber(L, p1); return iuplua_call(L, 2); } static int GLCanvas(lua_State *L) { Ihandle *ih = IupGLCanvas(NULL); iuplua_plugstate(L, ih); iuplua_pushihandle_raw(L, ih); return 1; } void iuplua_glcanvasfuncs_open(lua_State *L); int iupglcanvaslua_open(lua_State * L) { iuplua_register(L, GLCanvas, "GLCanvas"); iuplua_register_cb(L, "ACTION", (lua_CFunction)glcanvas_action, "glcanvas"); iuplua_glcanvasfuncs_open(L); #ifdef IUPLUA_USELOH #ifdef TEC_BIGENDIAN #ifdef TEC_64 #include "loh/glcanvas_be64.loh" #else #include "loh/glcanvas_be32.loh" #endif #else #ifdef TEC_64 #ifdef WIN64 #include "loh/glcanvas_le64w.loh" #else #include "loh/glcanvas_le64.loh" #endif #else #include "loh/glcanvas.loh" #endif #endif #else iuplua_dofile(L, "glcanvas.lua"); #endif return 0; } int iupgllua_open(lua_State * L) { if (iuplua_opencall_internal(L)) IupGLCanvasOpen(); iuplua_changeEnv(L); iupglcanvaslua_open(L); iuplua_returnEnv(L); return 0; } /* obligatory to use require"iupluagl" */ int luaopen_iupluagl(lua_State* L) { return iupgllua_open(L); } /* obligatory to use require"iupluagl51" */ int luaopen_iupluagl51(lua_State* L) { return iupgllua_open(L); }
0.761719
high
lib/libsnn/src/sn1en.c
brucelilly/quickselect
1
6760008
<gh_stars>1-10 /* *INDENT-OFF* */ /*INDENT OFF*/ /* Description: sn1en - powers of ten */ /****************************************************************************** * This software is covered by the zlib/libpng license. * The zlib/libpng license is a recognized open source license by * the Open Source Initiative: http://opensource.org/licenses/Zlib * The zlib/libpng license is a recognized "free" software license by * the Free Software Foundation: https://directory.fsf.org/wiki/License:Zlib ******************************************************************************* ******************* Copyright notice (part of the license) ******************** * $Id: ~|^` @(#) sn1en.c copyright 2011 - 2017 <NAME>. \ sn1en.c $ * 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. ****************************** (end of license) ******************************/ /* $Id: ~|^` @(#) This is sn1en.c version 2.6 2017-01-16T00:32:49Z. \ $ */ /* You may send bug reports to <EMAIL> with subject "snn" */ /*****************************************************************************/ /* maintenance note: master file /src/relaymail/lib/libsnn/src/s.sn1en.c */ /********************** Long description and rationale: *********************** * sn1en returns a power of ten: * * double sn1en(int n); * * N.B. the function name contains the numeral one, not the letter ell. ******************************************************************************/ /* ID_STRING_PREFIX file name and COPYRIGHT_DATE are constant, other components are version control fields */ #undef ID_STRING_PREFIX #undef SOURCE_MODULE #undef MODULE_VERSION #undef MODULE_DATE #undef COPYRIGHT_HOLDER #undef COPYRIGHT_DATE #define ID_STRING_PREFIX "$Id: sn1en.c ~|^` @(#)" #define SOURCE_MODULE "sn1en.c" #define MODULE_VERSION "2.6" #define MODULE_DATE "2017-01-16T00:32:49Z" #define COPYRIGHT_HOLDER "<NAME>" #define COPYRIGHT_DATE "2011 - 2017" /* Minimum _XOPEN_SOURCE version for C99 (else compilers on illumos have a tantrum) */ #if defined(__STDC__) && ( __STDC_VERSION__ >= 199901L) # define MIN_XOPEN_SOURCE_VERSION 600 #else # define MIN_XOPEN_SOURCE_VERSION 500 #endif /* feature test macros defined before any header files are included */ #ifndef _XOPEN_SOURCE # define _XOPEN_SOURCE 500 #endif #if defined(_XOPEN_SOURCE) && ( _XOPEN_SOURCE < MIN_XOPEN_SOURCE_VERSION ) # undef _XOPEN_SOURCE # define _XOPEN_SOURCE MIN_XOPEN_SOURCE_VERSION #endif #ifndef __EXTENSIONS__ # define __EXTENSIONS__ 1 #endif /*INDENT ON*/ /* *INDENT-ON* */ /* local header files */ #include "snn.h" /* header file for public definitions and declarations */ #include "zz_build_str.h" /* build_id build_strings_registered copyright_id register_build_strings */ /* system header files needed for code which are not included with declaration header */ #include <ctype.h> /* isalnum */ #include <stdlib.h> /* NULL */ #include <string.h> /* strrchr */ #include <syslog.h> /* LOG_* */ /* static data and function definitions */ static char sn1en_initialized = (char)0; static const char *filenamebuf = __FILE__ ; static const char *source_file = NULL; /* powers of ten */ /* pcc is very picky about parentheses in the following macro */ #define SNN_POW10_OFFSET (0-(SNN_MIN_POW10)) /* 10^N = snn_pow10[N+SNN_POW10_OFFSET] */ static double snn_pow10[] = { 1.0e-323, 1.0e-322, 1.0e-321, 1.0e-320, 1.0e-319, 1.0e-318, 1.0e-317, 1.0e-316, 1.0e-315, 1.0e-314, 1.0e-313, 1.0e-312, 1.0e-311, 1.0e-310, 1.0e-309, 1.0e-308, 1.0e-307, 1.0e-306, 1.0e-305, 1.0e-304, 1.0e-303, 1.0e-302, 1.0e-301, 1.0e-300, 1.0e-299, 1.0e-298, 1.0e-297, 1.0e-296, 1.0e-295, 1.0e-294, 1.0e-293, 1.0e-292, 1.0e-291, 1.0e-290, 1.0e-289, 1.0e-288, 1.0e-287, 1.0e-286, 1.0e-285, 1.0e-284, 1.0e-283, 1.0e-282, 1.0e-281, 1.0e-280, 1.0e-279, 1.0e-278, 1.0e-277, 1.0e-276, 1.0e-275, 1.0e-274, 1.0e-273, 1.0e-272, 1.0e-271, 1.0e-270, 1.0e-269, 1.0e-268, 1.0e-267, 1.0e-266, 1.0e-265, 1.0e-264, 1.0e-263, 1.0e-262, 1.0e-261, 1.0e-260, 1.0e-259, 1.0e-258, 1.0e-257, 1.0e-256, 1.0e-255, 1.0e-254, 1.0e-253, 1.0e-252, 1.0e-251, 1.0e-250, 1.0e-249, 1.0e-248, 1.0e-247, 1.0e-246, 1.0e-245, 1.0e-244, 1.0e-243, 1.0e-242, 1.0e-241, 1.0e-240, 1.0e-239, 1.0e-238, 1.0e-237, 1.0e-236, 1.0e-235, 1.0e-234, 1.0e-233, 1.0e-232, 1.0e-231, 1.0e-230, 1.0e-229, 1.0e-228, 1.0e-227, 1.0e-226, 1.0e-225, 1.0e-224, 1.0e-223, 1.0e-222, 1.0e-221, 1.0e-220, 1.0e-219, 1.0e-218, 1.0e-217, 1.0e-216, 1.0e-215, 1.0e-214, 1.0e-213, 1.0e-212, 1.0e-211, 1.0e-210, 1.0e-209, 1.0e-208, 1.0e-207, 1.0e-206, 1.0e-205, 1.0e-204, 1.0e-203, 1.0e-202, 1.0e-201, 1.0e-200, 1.0e-199, 1.0e-198, 1.0e-197, 1.0e-196, 1.0e-195, 1.0e-194, 1.0e-193, 1.0e-192, 1.0e-191, 1.0e-190, 1.0e-189, 1.0e-188, 1.0e-187, 1.0e-186, 1.0e-185, 1.0e-184, 1.0e-183, 1.0e-182, 1.0e-181, 1.0e-180, 1.0e-179, 1.0e-178, 1.0e-177, 1.0e-176, 1.0e-175, 1.0e-174, 1.0e-173, 1.0e-172, 1.0e-171, 1.0e-170, 1.0e-169, 1.0e-168, 1.0e-167, 1.0e-166, 1.0e-165, 1.0e-164, 1.0e-163, 1.0e-162, 1.0e-161, 1.0e-160, 1.0e-159, 1.0e-158, 1.0e-157, 1.0e-156, 1.0e-155, 1.0e-154, 1.0e-153, 1.0e-152, 1.0e-151, 1.0e-150, 1.0e-149, 1.0e-148, 1.0e-147, 1.0e-146, 1.0e-145, 1.0e-144, 1.0e-143, 1.0e-142, 1.0e-141, 1.0e-140, 1.0e-139, 1.0e-138, 1.0e-137, 1.0e-136, 1.0e-135, 1.0e-134, 1.0e-133, 1.0e-132, 1.0e-131, 1.0e-130, 1.0e-129, 1.0e-128, 1.0e-127, 1.0e-126, 1.0e-125, 1.0e-124, 1.0e-123, 1.0e-122, 1.0e-121, 1.0e-120, 1.0e-119, 1.0e-118, 1.0e-117, 1.0e-116, 1.0e-115, 1.0e-114, 1.0e-113, 1.0e-112, 1.0e-111, 1.0e-110, 1.0e-109, 1.0e-108, 1.0e-107, 1.0e-106, 1.0e-105, 1.0e-104, 1.0e-103, 1.0e-102, 1.0e-101, 1.0e-100, 1.0e-99, 1.0e-98, 1.0e-97, 1.0e-96, 1.0e-95, 1.0e-94, 1.0e-93, 1.0e-92, 1.0e-91, 1.0e-90, 1.0e-89, 1.0e-88, 1.0e-87, 1.0e-86, 1.0e-85, 1.0e-84, 1.0e-83, 1.0e-82, 1.0e-81, 1.0e-80, 1.0e-79, 1.0e-78, 1.0e-77, 1.0e-76, 1.0e-75, 1.0e-74, 1.0e-73, 1.0e-72, 1.0e-71, 1.0e-70, 1.0e-69, 1.0e-68, 1.0e-67, 1.0e-66, 1.0e-65, 1.0e-64, 1.0e-63, 1.0e-62, 1.0e-61, 1.0e-60, 1.0e-59, 1.0e-58, 1.0e-57, 1.0e-56, 1.0e-55, 1.0e-54, 1.0e-53, 1.0e-52, 1.0e-51, 1.0e-50, 1.0e-49, 1.0e-48, 1.0e-47, 1.0e-46, 1.0e-45, 1.0e-44, 1.0e-43, 1.0e-42, 1.0e-41, 1.0e-40, 1.0e-39, 1.0e-38, 1.0e-37, 1.0e-36, 1.0e-35, 1.0e-34, 1.0e-33, 1.0e-32, 1.0e-31, 1.0e-30, 1.0e-29, 1.0e-28, 1.0e-27, 1.0e-26, 1.0e-25, 1.0e-24, 1.0e-23, 1.0e-22, 1.0e-21, 1.0e-20, 1.0e-19, 1.0e-18, 1.0e-17, 1.0e-16, 1.0e-15, 1.0e-14, 1.0e-13, 1.0e-12, 1.0e-11, 1.0e-10, 1.0e-9, 1.0e-8, 1.0e-7, 1.0e-6, 1.0e-5, 1.0e-4, 1.0e-3, 1.0e-2, 1.0e-1, 1.0, 1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5, 1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10, 1.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15, 1.0e16, 1.0e17, 1.0e18, 1.0e19, 1.0e20, 1.0e21, 1.0e22, 1.0e23, 1.0e24, 1.0e25, 1.0e26, 1.0e27, 1.0e28, 1.0e29, 1.0e30, 1.0e31, 1.0e32, 1.0e33, 1.0e34, 1.0e35, 1.0e36, 1.0e37, 1.0e38, 1.0e39, 1.0e40, 1.0e41, 1.0e42, 1.0e43, 1.0e44, 1.0e45, 1.0e46, 1.0e47, 1.0e48, 1.0e49, 1.0e50, 1.0e51, 1.0e52, 1.0e53, 1.0e54, 1.0e55, 1.0e56, 1.0e57, 1.0e58, 1.0e59, 1.0e60, 1.0e61, 1.0e62, 1.0e63, 1.0e64, 1.0e65, 1.0e66, 1.0e67, 1.0e68, 1.0e69, 1.0e70, 1.0e71, 1.0e72, 1.0e73, 1.0e74, 1.0e75, 1.0e76, 1.0e77, 1.0e78, 1.0e79, 1.0e80, 1.0e81, 1.0e82, 1.0e83, 1.0e84, 1.0e85, 1.0e86, 1.0e87, 1.0e88, 1.0e89, 1.0e90, 1.0e91, 1.0e92, 1.0e93, 1.0e94, 1.0e95, 1.0e96, 1.0e97, 1.0e98, 1.0e99, 1.0e100, 1.0e101, 1.0e102, 1.0e103, 1.0e104, 1.0e105, 1.0e106, 1.0e107, 1.0e108, 1.0e109, 1.0e110, 1.0e111, 1.0e112, 1.0e113, 1.0e114, 1.0e115, 1.0e116, 1.0e117, 1.0e118, 1.0e119, 1.0e120, 1.0e121, 1.0e122, 1.0e123, 1.0e124, 1.0e125, 1.0e126, 1.0e127, 1.0e128, 1.0e129, 1.0e130, 1.0e131, 1.0e132, 1.0e133, 1.0e134, 1.0e135, 1.0e136, 1.0e137, 1.0e138, 1.0e139, 1.0e140, 1.0e141, 1.0e142, 1.0e143, 1.0e144, 1.0e145, 1.0e146, 1.0e147, 1.0e148, 1.0e149, 1.0e150, 1.0e151, 1.0e152, 1.0e153, 1.0e154, 1.0e155, 1.0e156, 1.0e157, 1.0e158, 1.0e159, 1.0e160, 1.0e161, 1.0e162, 1.0e163, 1.0e164, 1.0e165, 1.0e166, 1.0e167, 1.0e168, 1.0e169, 1.0e170, 1.0e171, 1.0e172, 1.0e173, 1.0e174, 1.0e175, 1.0e176, 1.0e177, 1.0e178, 1.0e179, 1.0e180, 1.0e181, 1.0e182, 1.0e183, 1.0e184, 1.0e185, 1.0e186, 1.0e187, 1.0e188, 1.0e189, 1.0e190, 1.0e191, 1.0e192, 1.0e193, 1.0e194, 1.0e195, 1.0e196, 1.0e197, 1.0e198, 1.0e199, 1.0e200, 1.0e201, 1.0e202, 1.0e203, 1.0e204, 1.0e205, 1.0e206, 1.0e207, 1.0e208, 1.0e209, 1.0e210, 1.0e211, 1.0e212, 1.0e213, 1.0e214, 1.0e215, 1.0e216, 1.0e217, 1.0e218, 1.0e219, 1.0e220, 1.0e221, 1.0e222, 1.0e223, 1.0e224, 1.0e225, 1.0e226, 1.0e227, 1.0e228, 1.0e229, 1.0e230, 1.0e231, 1.0e232, 1.0e233, 1.0e234, 1.0e235, 1.0e236, 1.0e237, 1.0e238, 1.0e239, 1.0e240, 1.0e241, 1.0e242, 1.0e243, 1.0e244, 1.0e245, 1.0e246, 1.0e247, 1.0e248, 1.0e249, 1.0e250, 1.0e251, 1.0e252, 1.0e253, 1.0e254, 1.0e255, 1.0e256, 1.0e257, 1.0e258, 1.0e259, 1.0e260, 1.0e261, 1.0e262, 1.0e263, 1.0e264, 1.0e265, 1.0e266, 1.0e267, 1.0e268, 1.0e269, 1.0e270, 1.0e271, 1.0e272, 1.0e273, 1.0e274, 1.0e275, 1.0e276, 1.0e277, 1.0e278, 1.0e279, 1.0e280, 1.0e281, 1.0e282, 1.0e283, 1.0e284, 1.0e285, 1.0e286, 1.0e287, 1.0e288, 1.0e289, 1.0e290, 1.0e291, 1.0e292, 1.0e293, 1.0e294, 1.0e295, 1.0e296, 1.0e297, 1.0e298, 1.0e299, 1.0e300, 1.0e301, 1.0e302, 1.0e303, 1.0e304, 1.0e305, 1.0e306, 1.0e307, 1.0e308, }; static void initialize_sn1en(void) { const char *s; s = strrchr(filenamebuf, '/'); if (NULL == s) s = filenamebuf; sn1en_initialized = register_build_strings(NULL, &source_file, s); } /* return a power of ten repeated multiplication or division by 10 accumulates errors exp10 a.k.a. pow10 is a gnu extension requiring a double argument, math.h, and -lm this function does not require math.h or -lm or proprietary "extensions" */ /* calls: sn1en_initialize */ /* called by: snn_sf_double, initialize_snn, int_d, d_int_d, snmagnitude */ double sn1en(int n, void (*f)(int, void *, const char *, ...), void *log_arg) { #ifndef PP__FUNCTION__ static const char __func__[] = "sn1en"; #endif if ((unsigned char)0U == sn1en_initialized) initialize_sn1en(); /* limits on the range of a double */ if (SNN_MAX_POW10 < n) { if (NULL != f) { f(LOG_WARNING, log_arg, "%s: %s line %d: supplied exponent %d being reduced to maximum value %d", __func__, source_file, __LINE__, n, SNN_MAX_POW10); } n = SNN_MAX_POW10; } else if (SNN_MIN_POW10 > n) { if (NULL != f) { f(LOG_WARNING, log_arg, "%s: %s line %d: supplied exponent %d being increased to minimum value %d", __func__, source_file, __LINE__, n, SNN_MIN_POW10); } n = SNN_MIN_POW10; } return snn_pow10[n+SNN_POW10_OFFSET]; }
0.765625
high
src/Vector2.h
rcabot/codscape
0
6792776
<gh_stars>0 #pragma once class Vector2 { public: Vector2(); Vector2(int x, int y); int x{}; int y{}; Vector2 operator+(const Vector2& other) const; long hash() const; float distance(const Vector2 other) const; };
0.988281
high
jat/targets/arm/cbuild/config.h
jallib/jallib
28
8225544
<filename>jat/targets/arm/cbuild/config.h // setup of oscillator. #define FOSC 14745600 /* External clock input frequency (must be between 10 MHz and 25 MHz) */ #define USE_PLL 1 /* 0 = do not use on-chip PLL, 1 = use on-chip PLL) */ #define PLL_MUL 4 /* PLL multiplication factor (1 to 32) */ #define PLL_DIV 2 /* PLL division factor (1, 2, 4, or 8) */
0.539063
low
src/core/timer.h
kcjulio/ffpic
0
8258312
<filename>src/core/timer.h /* src/core/timer.h MIT License Copyright (c) 2021 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef TIMER0_H #define TIMER0_H /* Enable Timer 0 Overflow Interrupt */ #define _TIMER0_INT // Comment this line to disable Timer 0 interrupts extern uint8_t tmr0_reg; enum _TMR0_Edge { T0SE_LOW_TO_HIGH = 0, T0SE_HIGH_TO_LOW }; enum _TMRO_Mode { TIMER_MODE = 0, COUNTER_MODE }; enum _TMR0_PS { PS_TMR0_1TO2 = 0, PS_TMR0_1TO4, PS_TMR0_1TO8, PS_TMR0_1TO16, PS_TMR0_1TO32, PS_TMR0_1TO64, PS_TMR0_1TO128, PS_TMR0_1TO256 }; enum _TMR0_PSA { PSA_TIMER = 0, PSA_WDT }; #define TIMER0_Edge(e) OPTION_REGbits.T0SE = e #define TIMER0_Load(v) TMR0 = tmr0_reg = v #define TIMER0_Overflow() INTCONbits.T0IF #define TIMER0_Prescaler(p) OPTION_REG = (OPTION_REG & 0xF8) | p #define TIMER0_Reset() \ TMR0 = tmr0_reg; \ INTCONbits.T0IF = 0 /* Function Prototypes */ void TIMER0_Init(uint8_t mode, uint8_t psa); /* Notes: Timer 0 Overflow Period and Frequency equations: T = (256 - TMR0) * tmr0_prescaler * (1 / (F_CPU / 4)) Solving for tmr0_prescaler: tmr0_prescaler = T / (256 - TMR0) * (1 / (F_CPU / 4)) Solving for TMR0: 256 - TMR0 = T / (tmr0_prescaler * (1 / (F_CPU / 4))) - TMR0 = (T / (tmr0_prescaler * (1 / (F_CPU / 4)))) - 256 TMR0 = 256 - (T / (tmr0_prescaler * (1 / (F_CPU / 4)))) Frequency equation: f = 1 / T */ #endif
0.976563
high
menu/menumgr.c
deimon777/Final-C
0
424464
<reponame>deimon777/Final-C<gh_stars>0 #include <stdio.h> #include "mydefs.h" #include "screen.h" #include "menumgr.h" /*funciones*/ #define XMENU 10 #define YMENU 5 /**/ #define XIN 10 #define YIN 15 /**/ #define XSTATUS XIN+16 #define YSTATUS YIN /* Static functions */ static unsigned show_menu(MENU *p, int begchar) { unsigned i; clrscr(); gotoxy(10, 10); for (i = 0; p->text != NULL ; ++p, ++i) { gotoxy(XMENU, YMENU + i); printf("%c.-%s\n", begchar + i, p->text); } return i; } static unsigned get_option(unsigned size, int begchar) { unsigned opt; gotoxy(XIN, YIN); printf("%s", OPCION); do { opt = getchar() - begchar; if (opt >= size) putchar('\a'); } while (opt >= size); return opt; } //static void sak(void) { gotoxy(XSTATUS, YSTATUS); printf("%s", OPRIMA_UNA_TECLA); getchar(); } /* Public functions */ void do_menu(MENU *p, int begchar) { int size; unsigned opt; clrscr(); size = show_menu(p, begchar); opt = get_option(size, begchar); clrscr(); if ((*(p + opt)->func)()) sak(); }
0.380859
medium
harfang/engine/picking_helper.h
harfang3dadmin/harfang3d
43
457232
<gh_stars>10-100 // HARFANG(R) Copyright (C) 2021 <NAME>, NWNC HARFANG. Released under GPL/LGPL/Commercial Licence, see licence.txt for details. #pragma once #include <bgfx/bgfx.h> #include <vector> namespace hg { struct PickingResults { int width{}, height{}; uint32_t result_frame{}; std::vector<uint8_t> color_data, depth_data; }; class PickingHelper { public: ~PickingHelper(); void Create(int width, int height); void Destroy(); bgfx::FrameBufferHandle GetFramebuffer() const { return fb; } void Readback(bgfx::ViewId &view_id, PickingResults &res) const; private: int width{}, height{}; bgfx::TextureHandle color = BGFX_INVALID_HANDLE, depth = BGFX_INVALID_HANDLE; bgfx::FrameBufferHandle fb = BGFX_INVALID_HANDLE; bgfx::TextureHandle color_read = BGFX_INVALID_HANDLE, depth_read = BGFX_INVALID_HANDLE; }; } // namespace hg
0.996094
high
3dEngine/src/resources/Resource.h
petitg1987/urchinEngine
18
490000
#pragma once #include <string> namespace urchin { class Resource { public: virtual ~Resource() = default; const std::string& getId() const; void setId(const std::string&); const std::string& getName() const; void setName(const std::string&); private: std::string id; std::string name; }; }
0.980469
high
components/config/include/AppConfig.h
mohamed-elsabagh/blue-scanner-advertiser
0
522768
/*---------------------------------------------------------------------------/ / APPConfig - Application Ver 1.00 /---------------------------------------------------------------------------*/ #ifndef _APP_CONFIG_H #define _APP_CONFIG_H #define _APPConfig 100 /* Revision ID */ /*---------------------------------------------------------------------------/ / Function Configurations /---------------------------------------------------------------------------*/ #define DEBUG 1 /* This option Enables the debug interface. */ #define MICRO_BUFFER_SIZE 32 #define MINI_BUFFER_SIZE 64 #define TINY_BUFFER_SIZE 128 #define SMALL_BUFFER_SIZE 256 #define MEDIUM_BUFFER_SIZE 512 #define BIG_BUFFER_SIZE 1024 #define LARGE_BUFFER_SIZE 2048 #define MASSIVE_BUFFER_SIZE 4096 #define ENORMUS_BUFFER_SIZE 8192 /* Those options specify the size of the buffers used between different / interfaces. */ #define SPECIAL_CAHARACTER ';' /* This is special character that indicates end of data portion when more / than interface are trying to communicate with each others. */ #define osPriorityIdle configMAX_PRIORITIES - 6 #define osPriorityLow configMAX_PRIORITIES - 5 #define osPriorityBelowNormal configMAX_PRIORITIES - 4 #define osPriorityNormal configMAX_PRIORITIES - 3 #define osPriorityAboveNormal configMAX_PRIORITIES - 2 #define osPriorityHigh configMAX_PRIORITIES - 1 #define osPriorityRealtime configMAX_PRIORITIES - 0 #define CONFIG_SET_RAW_ADV_DATA 1 #define BLE_BUFFER_SIZE 10 #endif
0.738281
high
networking/Dispatcher/msort_helper.c
J-Gravity/J-GravityDispatcher
8
8288752
<gh_stars>1-10 #include <stdlib.h> #include <string.h> #include <pthread.h> #include "msort.h" void bsort(msort_param_t params) { uint64_t pivot; size_t i; size_t l; t_sortbod *sorts = (t_sortbod*)(params.sorts); size_t end = params.end; size_t start = params.start; if (start >= end) return ; i = start; pivot = sorts[(start + (end - start) / 2)].morton; l = end; while (i <= l) { //if i < pivot i++; while (mcmp(sorts[i], pivot) == -1) i++; //if l >= pivot l--; while (mcmp(sorts[l], pivot) == 1) l--; if (i >= l) break ; msort_swap(&sorts[i], &sorts[l]); } msort_param_t param1; param1.start = start; param1.end = l; param1.sorts = sorts; msort_param_t param2; param2.start = (l + 1); param2.end = end; param2.sorts = sorts; if (semval(mphore) > 0 && (l - start) > THREAD_THRESHOLD) { sem_wait(mphore); pthread_t tid1;; pthread_create(&tid1, NULL, qmsort, &param1); } else { bsort(param1); } if (semval(mphore) > 0 && (end - l) > THREAD_THRESHOLD) { sem_wait(mphore); pthread_t tid2; pthread_create(&tid2, NULL, qmsort, &param2); } else { bsort(param2); } return ; }
0.498047
high
internal/ccall/glcomp/glcompmouse.h
edamato/go-graphviz
343
8321520
<filename>internal/ccall/glcomp/glcompmouse.h<gh_stars>100-1000 /* $Id$Revision: */ /* vim:set shiftwidth=4 ts=8: */ /************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ *************************************************************************/ #ifndef GLCOMPMOUSE_H #define GLCOMPMOUSE_H #include "glcompdefs.h" #ifdef __cplusplus extern "C" { #endif /*events*/ extern void glCompMouseInit(glCompMouse * m); extern void glCompClick(glCompObj * o, GLfloat x, GLfloat y, glMouseButtonType t); extern void glCompDoubleClick(glCompObj * obj, GLfloat x, GLfloat y, glMouseButtonType t); extern void glCompMouseDown(glCompObj * obj, GLfloat x, GLfloat y, glMouseButtonType t); extern void glCompMouseIn(glCompObj * obj, GLfloat x, GLfloat y); extern void glCompMouseOut(glCompObj * obj, GLfloat x, GLfloat y); extern void glCompMouseOver(glCompObj * obj, GLfloat x, GLfloat y); extern void glCompMouseUp(glCompObj * obj, GLfloat x, GLfloat y, glMouseButtonType t); extern void glCompMouseDrag(glCompObj * obj, GLfloat dx, GLfloat dy, glMouseButtonType t); #ifdef __cplusplus } #endif #endif
0.949219
high
corrdim.c
ramansbach/cluster_analysis
0
8354288
<reponame>ramansbach/cluster_analysis<gh_stars>0 void corrdim ( double * epss, double * ce, double * distsq, int Nepss, int Nd2) { int i,k; for (i = 0; i < Nd2; i++) { for (k = 0; k < Nepss; k++) { if (distsq[i] <= epss[k]*epss[k]) { ce[k]++; } } } }
0.494141
high
06_IPC_Synchronization/exercises/semcli.c
StoyanovBG/LinuxSystemProgramming
7
8387056
<gh_stars>1-10 #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/sem.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "semtypes.h" int main(int argc, char * argv[]) { struct memory_block * mblock; struct sembuf buf[2]; // Semaphore key key_t key = ftok(FTOK_FILE, 1); if (key == -1) { printf("Failed to generate unique key. Server compiler with a wrong name?\n"); return EXIT_FAILURE; // -1 } // Shared Memory Identifier int shmid = shmget(key, sizeof(struct memory_block), 0666); if (shmid == -1) { printf("Server is not running!\n"); return EXIT_FAILURE; // -1 } // Semaphore Identifier int semid = semget(key, 2, 0666); buf[0].sem_num = 0; buf[0].sem_flg = SEM_UNDO; buf[1].sem_num = 1; buf[1].sem_flg = SEM_UNDO; mblock = (struct memory_block *) shmat(shmid, 0, 0); buf[1].sem_op = -1; // While not receive 'q' while (strcmp("q\n", mblock->string) != 0) { int i = 0; semop(semid, (struct sembuf*) &buf[1], 1); printf("Server sends %s\n", mblock->string); while ((i < (MAXLEN - 1)) && ((mblock->string[i++] = getchar()) != '\n') ); mblock->string[i] = 0; buf[0].sem_op = 1; buf[1].sem_op = -1; semop(semid, (struct sembuf*) &buf, 1); } // Exit and free memory resourses printf("Client exits\n"); shmdt((void *) mblock); return EXIT_SUCCESS; // 1 }
0.75
high
observation/VerifiableMessageQueryParams.h
fmidev/smartmet-engine-observation
0
2086600
<gh_stars>0 #pragma once #include "DBRegistryConfig.h" #include "QueryParamsBase.h" #include <boost/assign.hpp> #include <list> #include <map> #include <string> #include <unordered_map> #include <vector> namespace SmartMet { namespace Engine { namespace Observation { /** * @brief The class implements special parameter * capabilities to fetch IWXXM data. * * The class is designed to relay parameters and * some additional guidance to VerifiableMessageQuery * class where those are used in SQL statement contruction. */ class VerifiableMessageQueryParams : public QueryParamsBase { public: /** * @brief The enum defines keywords that restricts * (or widens) the way of use of parameters. */ enum Restriction : int { RETURN_ONLY_LATEST }; using NameType = DBRegistryConfig::NameType; using StationIdType = NameType; using StationIdVectorType = std::vector<StationIdType>; using SelectNameType = DBRegistryConfig::NameType; using SelectNameListType = std::list<SelectNameType>; using TableNameType = DBRegistryConfig::NameType; explicit VerifiableMessageQueryParams(const std::shared_ptr<DBRegistryConfig> dbrConfig); ~VerifiableMessageQueryParams(); VerifiableMessageQueryParams &operator=(const VerifiableMessageQueryParams &other) = delete; VerifiableMessageQueryParams(const VerifiableMessageQueryParams &other) = delete; /** * @brief Add name used in SQL select statement. * @param selectName Name of the column in database. * @retval true Input parameter name is added and is a valid name. * @retval false Input parameter name is not a valid name. */ bool addSelectName(const std::string &selectName); /** * @brief Add a station identifier (e.g. EFHK) */ void addStationId(const std::string &stationId); /** * @brief Get the list reference for select names added into. * @return Reference to the select name list or an empty list. */ const SelectNameListType *getSelectNameList() const; /** * @brief Get the reference for the station identifier vector. * @return Reference to the station identifier vector. */ StationIdVectorType *getStationIdVector() const; /** * @brief Get a table name. * @return The table name of the object or empty string if the name is * missing. */ TableNameType getTableName() const; /** * @brief Get method name to retrieve data as an other type. * E.g. XML data as a CLOB value. * @param Select name to search the method. * @return Name of a method or empty value. */ NameType getSelectNameMethod(const NameType &name) const; /** * @brief Test if a restriction is set on. * @retval true Restriction is set on. * @retval false Restriction is off. */ bool isRestriction(int id) const; /** * @brief Set the restriction on. */ // FIXME!! replace the method with setRestriction(int id) void setReturnOnlyLatest(); private: std::shared_ptr<DBRegistryConfig> m_dbrConfig; StationIdVectorType *m_stationIdVector; NamesAllowed *m_namesAllowed; std::unordered_map<int, bool> m_restrictionMap; }; } // namespace Observation } // namespace Engine } // namespace SmartMet
0.996094
high
getpasswd.c
electrorys/libcrypt
0
2119368
#include <stdio.h> #include <string.h> #include <unistd.h> #include <termios.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include "getpasswd.h" size_t getpasswd(struct getpasswd_state *getps) { char c; int tty_opened = 0, x; int clear; struct termios s, t; size_t l, echolen = 0; if (!getps) return ((size_t)-1); /* * Both stdin and stderr point to same fd. This cannot happen. * This only means that getps was memzero'd. * Do not blame user for that, just fix it. */ if ((getps->fd == 0 && getps->efd == 0) || getps->efd == -1) getps->efd = 2; if (getps->fd == -1) { if ((getps->fd = open("/dev/tty", O_RDONLY|O_NOCTTY)) == -1) getps->fd = 0; else tty_opened = 1; } memset(&t, 0, sizeof(struct termios)); memset(&s, 0, sizeof(struct termios)); if (tcgetattr(getps->fd, &t) == -1) { getps->error = errno; return ((size_t)-1); } s = t; if (getps->sanetty) memcpy(getps->sanetty, &s, sizeof(struct termios)); cfmakeraw(&t); t.c_iflag |= ICRNL; if (tcsetattr(getps->fd, TCSANOW, &t) == -1) { getps->error = errno; return ((size_t)-1); } if (getps->echo) { echolen = strlen(getps->echo); if (write(getps->efd, getps->echo, echolen) == -1) { getps->error = errno; l = ((size_t)-1); goto _xerr; } } l = 0; x = 0; memset(getps->passwd, 0, getps->pwlen); while (1) { clear = 1; if (read(getps->fd, &c, sizeof(char)) == -1) { getps->error = errno; l = ((size_t)-1); goto _xerr; } if (getps->charfilter) { x = getps->charfilter(getps, c, l); if (x == 0) { clear = 0; goto _newl; } else if (x == 2) continue; else if (x == 3) goto _erase; else if (x == 4) goto _delete; else if (x == 5) break; else if (x == 6) { clear = 0; l = getps->retn; memset(getps->passwd, 0, getps->pwlen); goto _err; } } if (l >= getps->pwlen && (getps->flags & GETP_WAITFILL)) clear = 0; if (c == '\x7f' || (c == '\x08' && !(getps->flags & GETP_NOINTERP))) { /* Backspace / ^H */ _erase: if (l == 0) continue; clear = 0; l--; if (!(getps->flags & GETP_NOECHO)) { if (write(getps->efd, "\x08\033[1X", sizeof("\x08\033[1X")-1) == -1) { getps->error = errno; l = ((size_t)-1); goto _xerr; } } } else if (!(getps->flags & GETP_NOINTERP) && (c == '\x15' || c == '\x17')) { /* ^U / ^W */ _delete: clear = 0; l = 0; memset(getps->passwd, 0, getps->pwlen); if (write(getps->efd, "\033[2K\033[0G", sizeof("\033[2K\033[0G")-1) == -1) { getps->error = errno; l = ((size_t)-1); goto _xerr; } if (getps->echo) { if (write(getps->efd, getps->echo, echolen) == -1) { getps->error = errno; l = ((size_t)-1); goto _xerr; } } } _newl: if (c == '\n' || c == '\r' || (!(getps->flags & GETP_NOINTERP) && c == '\x04')) break; if (clear) { *(getps->passwd+l) = c; l++; if (!(getps->flags & GETP_NOECHO)) { if (getps->maskchar && write(getps->efd, &getps->maskchar, sizeof(char)) == -1) { getps->error = errno; l = ((size_t)-1); goto _xerr; } } } if (l >= getps->pwlen && !(getps->flags & GETP_WAITFILL)) break; }; _err: if (write(getps->efd, "\r\n", sizeof("\r\n")-1) == -1) { getps->error = errno; l = ((size_t)-1); } if (x != 6) *(getps->passwd+l) = 0; _xerr: if (tcsetattr(getps->fd, TCSANOW, &s) == -1) { if (getps->error == 0) { getps->error = errno; l = ((size_t)-1); } } if (tty_opened) close(getps->fd); return l; }
0.988281
high
eglibc-2.15/sysdeps/unix/sysv/sigaction.c
huhong789/shortcut
47
2152136
<filename>eglibc-2.15/sysdeps/unix/sysv/sigaction.c<gh_stars>10-100 /* Copyright (C) 1992,1994,1995,1996,1997,2002 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <sysdep.h> #include <errno.h> #include <stddef.h> #include <signal.h> /* If ACT is not NULL, change the action for SIG to *ACT. If OACT is not NULL, put the old action for SIG in *OACT. */ int __sigaction (sig, act, oact) int sig; const struct sigaction *act; struct sigaction *oact; { sighandler_t handler; int save; if (sig <= 0 || sig >= NSIG) { __set_errno (EINVAL); return -1; } if (act == NULL) { if (oact == NULL) return 0; /* Race condition, but this is the only way to do it. */ handler = signal (sig, SIG_IGN); if (handler == SIG_ERR) return -1; save = errno; (void) signal (sig, handler); __set_errno (save); } else { int i; if (act->sa_flags != 0) { unimplemented: __set_errno (ENOSYS); return -1; } for (i = 1; i < NSIG; ++i) if (__sigismember (&act->sa_mask, i)) goto unimplemented; handler = signal (sig, act->sa_handler); if (handler == SIG_ERR) return -1; } if (oact != NULL) { oact->sa_handler = handler; __sigemptyset (&oact->sa_mask); oact->sa_flags = 0; } return 0; } libc_hidden_def (__sigaction) weak_alias (__sigaction, sigaction)
0.980469
high
iphone/Maps/Core/Storage/MWMStorage.h
seckalou/fonekk_pub
1
2184904
<filename>iphone/Maps/Core/Storage/MWMStorage.h #include "storage/storage_defines.hpp" @interface MWMStorage : NSObject + (void)downloadNode:(storage::CountryId const &)countryId onSuccess:(MWMVoidBlock)onSuccess onCancel:(MWMVoidBlock)onCancel; + (void)retryDownloadNode:(storage::CountryId const &)countryId; + (void)updateNode:(storage::CountryId const &)countryId onCancel:(MWMVoidBlock)onCancel; + (void)deleteNode:(storage::CountryId const &)countryId; + (void)cancelDownloadNode:(storage::CountryId const &)countryId; + (void)showNode:(storage::CountryId const &)countryId; + (void)downloadNodes:(storage::CountriesVec const &)countryIds onSuccess:(MWMVoidBlock)onSuccess onCancel:(MWMVoidBlock)onCancel; @end
0.847656
high
source/ccsp/components/include/dslh_hco_interface.h
lgirdk/ccsp-common-library
4
3617672
<gh_stars>1-10 /* * If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2015 RDK Management * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /********************************************************************** Copyright [2014] [Cisco Systems, 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. **********************************************************************/ /********************************************************************** module: dslh_hco_interface.h For DSL Home Model Implementation (DSLH), BroadWay Service Delivery System --------------------------------------------------------------- description: This wrapper file defines all the platform-independent functions and macros for the Dslh Helper Container Object. --------------------------------------------------------------- environment: platform independent --------------------------------------------------------------- author: <NAME> --------------------------------------------------------------- revision: 10/20/05 initial revision. **********************************************************************/ #ifndef _DSLH_HCO_INTERFACE_ #define _DSLH_HCO_INTERFACE_ /* * This object is derived a virtual base object defined by the underlying framework. We include the * interface header files of the base object here to shield other objects from knowing the derived * relationship between this object and its base class. */ #include "ansc_oco_interface.h" #include "ansc_oco_external_api.h" /*********************************************************** PLATFORM INDEPENDENT OBJECT CONTAINER OBJECT DEFINITION ***********************************************************/ /* * Define some const values that will be used in the object mapper object definition. */ #define DSLH_HELPER_CONTAINER_NAME "dslhHelpContainer" #define DSLH_HELPER_CONTAINER_OID ANSC_OBJECT_OID_NULL #define DSLH_HELPER_CONTAINER_TYPE ANSC_OBJECT_TYPE_NULL /* * Since we write all kernel modules in C (due to better performance and lack of compiler support), * we have to simulate the C++ object by encapsulating a set of functions inside a data structure. */ typedef ANSC_HANDLE (*PFN_DSLHHCO_GET_CONTEXT) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_DSLHHCO_SET_CONTEXT) ( ANSC_HANDLE hThisObject, ANSC_HANDLE hContext ); typedef ANSC_HANDLE (*PFN_DSLHHCO_GET_IF) ( ANSC_HANDLE hThisObject ); typedef ANSC_HANDLE (*PFN_DSLHHCO_GET_CARRIER) ( ANSC_HANDLE hThisObject, ANSC_HANDLE hSessionContext ); typedef ANSC_STATUS (*PFN_DSLHHCO_SET_CARRIER) ( ANSC_HANDLE hThisObject, ANSC_HANDLE hSessionContext, ANSC_HANDLE hCarrier, ULONG ulSize ); /* * As a standard practice, we encapsulate all functional and feature objects inside an Object * Container Object so it will function as a black-box implementation when we have to integrate * an Ansc component with other systems. However, that's not the only reason why we need to * define the Container Object: we also use container as the building block for constructing * larger systems. */ #define DSLH_HELPER_CONTAINER_CLASS_CONTENT \ /* duplication of the base object class content */ \ ANSC_OBJECT_CONTAINER_CLASS_CONTENT \ /* start of object class content */ \ /* end of object class content */ \ typedef struct _DSLH_HELPER_CONTAINER_OBJECT { DSLH_HELPER_CONTAINER_CLASS_CONTENT } DSLH_HELPER_CONTAINER_OBJECT, *PDSLH_HELPER_CONTAINER_OBJECT; #define ACCESS_DSLH_HELPER_CONTAINER_OBJECT(p) \ ACCESS_CONTAINER(p, DSLH_HELPER_CONTAINER_OBJECT, Linkage) #endif
0.996094
high
tests/MathTestUtils.h
tvogiannou/ctrigrid
0
3650440
#pragma once #include <ctrigrid/Vector3.h> #include <ctrigrid/Vector4.h> #include <gtest/gtest.h> namespace mathtests { struct Utils { static void CheckValues(const ctrigrid::Vector3& v, float expX, float expY, float expZ) { EXPECT_FLOAT_EQ(v.x, expX); EXPECT_FLOAT_EQ(v.y, expY); EXPECT_FLOAT_EQ(v.z, expZ); EXPECT_FLOAT_EQ(v.m_elems[0], expX); EXPECT_FLOAT_EQ(v.m_elems[1], expY); EXPECT_FLOAT_EQ(v.m_elems[2], expZ); } static void CheckValues(const ctrigrid::Vector3& v1, const ctrigrid::Vector3& v2) { EXPECT_FLOAT_EQ(v1.x, v2.x); EXPECT_FLOAT_EQ(v1.y, v2.y); EXPECT_FLOAT_EQ(v1.z, v2.z); EXPECT_FLOAT_EQ(v1.m_elems[0], v2.m_elems[0]); EXPECT_FLOAT_EQ(v1.m_elems[1], v2.m_elems[1]); EXPECT_FLOAT_EQ(v1.m_elems[2], v2.m_elems[2]); } static void CheckValues(const ctrigrid::Vector3& v1, const ctrigrid::Vector3& v2, float tolerance) { EXPECT_NEAR(v1.x, v2.x, tolerance); EXPECT_NEAR(v1.y, v2.y, tolerance); EXPECT_NEAR(v1.z, v2.z, tolerance); EXPECT_NEAR(v1.m_elems[0], v2.m_elems[0], tolerance); EXPECT_NEAR(v1.m_elems[1], v2.m_elems[1], tolerance); EXPECT_NEAR(v1.m_elems[2], v2.m_elems[2], tolerance); } static void CheckValues(const ctrigrid::Vector4& v, float expX, float expY, float expZ, float expW) { EXPECT_FLOAT_EQ(v.x, expX); EXPECT_FLOAT_EQ(v.y, expY); EXPECT_FLOAT_EQ(v.z, expZ); EXPECT_FLOAT_EQ(v.w, expW); EXPECT_FLOAT_EQ(v.m_elems[0], expX); EXPECT_FLOAT_EQ(v.m_elems[1], expY); EXPECT_FLOAT_EQ(v.m_elems[2], expZ); EXPECT_FLOAT_EQ(v.m_elems[3], expW); } static void CheckValues(const ctrigrid::Vector4& v1, const ctrigrid::Vector4& v2) { EXPECT_FLOAT_EQ(v1.x, v2.x); EXPECT_FLOAT_EQ(v1.y, v2.y); EXPECT_FLOAT_EQ(v1.z, v2.z); EXPECT_FLOAT_EQ(v1.w, v2.w); EXPECT_FLOAT_EQ(v1.m_elems[0], v2.m_elems[0]); EXPECT_FLOAT_EQ(v1.m_elems[1], v2.m_elems[1]); EXPECT_FLOAT_EQ(v1.m_elems[2], v2.m_elems[2]); EXPECT_FLOAT_EQ(v1.m_elems[3], v2.m_elems[3]); } }; }
0.996094
high
XHDemo/XHDemo/General/Tools/GMUtils/GMUtils.h
moxuyou/XHDemo
4
3683208
<gh_stars>1-10 // // GMUtils.h // moxuyou_Base // // Created by moxuyou on 2016/12/13. // Copyright © 2016年 moxuyou. All rights reserved. // #import <Foundation/Foundation.h> @interface GMUtils : NSObject + (NSString *)version; @end
0.742188
high
BSP/src/drivers/timer_drv.c
cprates/lpc1768
0
3715976
<gh_stars>0 /** * @file timer_drv.c * @brief Generic Timer driver * @version 1.0 * @date 15 Jun. 2017 * **/ #include <limits.h> #include "drivers/timer_drv.h" #include "drivers/common.h" unsigned int calc_prescaler_value(unsigned int frequency) { unsigned int retVal = SystemCoreClock / (frequency * 1.0); return retVal; } void TIMER0_Init(unsigned int frequency) { SET_TIMER0_POWER_ON; RESET_TIMER0; SET_TIMER0_DISABLED; // same clck as the CPU SET_PERIPHERAL_CLOCK_MODE(0, TIMER0_CLOCK_MODE_SHIFT, CLOCK_MODE_SAME_AS_CCLOCK); // SET_TIMER0_MODE(TIMER_MODE_TIMER); LPC_TIM0->PR = calc_prescaler_value(frequency) - 1; // UNRESET_TIMER0; SET_TIMER0_ENABLED; } unsigned int TIMER0_GetValue(void) { return LPC_TIM0->TC; } unsigned int TIMER0_Elapse(unsigned int lastRead) { unsigned int currVal = TIMER0_GetValue(); unsigned int elapsed; if(currVal < lastRead) { currVal = currVal + (UINT_MAX - lastRead); } else { elapsed = currVal - lastRead; } return elapsed + 1; }
0.976563
high
System/Library/PrivateFrameworks/ToneKit.framework/TKTonePickerTableView.h
lechium/iOS1351Headers
2
4547361
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, October 27, 2021 at 3:18:19 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/ToneKit.framework/ToneKit * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>. */ #import <UIKitCore/UITableView.h> @protocol TKTonePickerTableViewLayoutMarginsObserver, TKTonePickerTableViewSeparatorObserver; @interface TKTonePickerTableView : UITableView { id<TKTonePickerTableViewLayoutMarginsObserver> _layoutMarginsObserver; id<TKTonePickerTableViewSeparatorObserver> _separatorObserver; } @property (assign,nonatomic,__weak) id<TKTonePickerTableViewLayoutMarginsObserver> layoutMarginsObserver; //@synthesize layoutMarginsObserver=_layoutMarginsObserver - In the implementation block @property (assign,nonatomic,__weak) id<TKTonePickerTableViewSeparatorObserver> separatorObserver; //@synthesize separatorObserver=_separatorObserver - In the implementation block -(void)layoutSubviews; -(void)layoutMarginsDidChange; -(void)setSeparatorColor:(id)arg1 ; -(id<TKTonePickerTableViewLayoutMarginsObserver>)layoutMarginsObserver; -(id<TKTonePickerTableViewSeparatorObserver>)separatorObserver; -(void)_handleSeparatorColorDidChange; -(void)setLayoutMarginsObserver:(id<TKTonePickerTableViewLayoutMarginsObserver>)arg1 ; -(void)setSeparatorObserver:(id<TKTonePickerTableViewSeparatorObserver>)arg1 ; @end
0.503906
high
riscv-tools/riscv-tests/benchmarks/qsort/qsort_main.c
TKNopro/risc-v
2,123
4580129
<reponame>TKNopro/risc-v<filename>riscv-tools/riscv-tests/benchmarks/qsort/qsort_main.c // See LICENSE for license details. //************************************************************************** // Quicksort benchmark //-------------------------------------------------------------------------- // // This benchmark uses quicksort to sort an array of integers. The // implementation is largely adapted from Numerical Recipes for C. The // input data (and reference data) should be generated using the // qsort_gendata.pl perl script and dumped to a file named // dataset1.h. #include "util.h" #include <string.h> #include <assert.h> // The INSERTION_THRESHOLD is the size of the subarray when the // algorithm switches to using an insertion sort instead of // quick sort. #define INSERTION_THRESHOLD 10 // NSTACK is the required auxiliary storage. // It must be at least 2*lg(DATA_SIZE) #define NSTACK 50 //-------------------------------------------------------------------------- // Input/Reference Data #define type int #include "dataset1.h" // Swap macro for swapping two values. #define SWAP(a,b) do { typeof(a) temp=(a);(a)=(b);(b)=temp; } while (0) #define SWAP_IF_GREATER(a, b) do { if ((a) > (b)) SWAP(a, b); } while (0) //-------------------------------------------------------------------------- // Quicksort function static void insertion_sort(size_t n, type arr[]) { type *i, *j; type value; for (i = arr+1; i < arr+n; i++) { value = *i; j = i; while (value < *(j-1)) { *j = *(j-1); if (--j == arr) break; } *j = value; } } static void selection_sort(size_t n, type arr[]) { for (type* i = arr; i < arr+n-1; i++) for (type* j = i+1; j < arr+n; j++) SWAP_IF_GREATER(*i, *j); } void sort(size_t n, type arr[]) { type* ir = arr+n; type* l = arr+1; type* stack[NSTACK]; type** stackp = stack; for (;;) { // Insertion sort when subarray small enough. if ( ir-l < INSERTION_THRESHOLD ) { insertion_sort(ir - l + 1, l - 1); if ( stackp == stack ) break; // Pop stack and begin a new round of partitioning. ir = *stackp--; l = *stackp--; } else { // Choose median of left, center, and right elements as // partitioning element a. Also rearrange so that a[l-1] <= a[l] <= a[ir-]. SWAP(arr[((l-arr) + (ir-arr))/2-1], l[0]); SWAP_IF_GREATER(l[-1], ir[-1]); SWAP_IF_GREATER(l[0], ir[-1]); SWAP_IF_GREATER(l[-1], l[0]); // Initialize pointers for partitioning. type* i = l+1; type* j = ir; // Partitioning element. type a = l[0]; for (;;) { // Beginning of innermost loop. while (*i++ < a); // Scan up to find element > a. while (*(j-- - 2) > a); // Scan down to find element < a. if (j < i) break; // Pointers crossed. Partitioning complete. SWAP(i[-1], j[-1]); // Exchange elements. } // End of innermost loop. // Insert partitioning element. l[0] = j[-1]; j[-1] = a; stackp += 2; // Push pointers to larger subarray on stack, // process smaller subarray immediately. if ( ir-i+1 >= j-l ) { stackp[0] = ir; stackp[-1] = i; ir = j-1; } else { stackp[0] = j-1; stackp[-1] = l; l = i; } } } } //-------------------------------------------------------------------------- // Main int main( int argc, char* argv[] ) { #if PREALLOCATE // If needed we preallocate everything in the caches sort(DATA_SIZE, verify_data); if (verify(DATA_SIZE, input_data, input_data)) return 1; #endif // Do the sort setStats(1); sort( DATA_SIZE, input_data ); setStats(0); // Check the results return verify( DATA_SIZE, input_data, verify_data ); }
0.996094
high
ul_exec_libc.c
mgood7123/userlandexec
1
6012897
<gh_stars>1-10 // #include <libstatic/libstatic.h> #include <errno.h> // extern long errno; #define PGSZ 0x1000 #include <elf.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <sys/syscall.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/mman.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <limits.h> #include <assert.h> #include <string.h> #include <errno.h> #include <libgen.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> extern char **environ; // "look deep into yourself, Clarice" -- <NAME> char findyourself_save_pwd[PATH_MAX]; char findyourself_save_argv0[PATH_MAX]; char findyourself_save_path[PATH_MAX]; char findyourself_path_separator='/'; char findyourself_path_separator_as_string[2]="/"; char findyourself_path_list_separator[8]=":"; // could be ":; " char findyourself_debug=0; int findyourself_initialized=0; void findyourself_init(char *argv0) { getcwd(findyourself_save_pwd, sizeof(findyourself_save_pwd)); strncpy(findyourself_save_argv0, argv0, sizeof(findyourself_save_argv0)); findyourself_save_argv0[sizeof(findyourself_save_argv0)-1]=0; strncpy(findyourself_save_path, getenv("PATH"), sizeof(findyourself_save_path)); findyourself_save_path[sizeof(findyourself_save_path)-1]=0; findyourself_initialized=1; } int find_yourself(char *result, size_t size_of_result) { char newpath[PATH_MAX+256]; char newpath2[PATH_MAX+256]; assert(findyourself_initialized); result[0]=0; if(findyourself_save_argv0[0]==findyourself_path_separator) { if(findyourself_debug) printf(" absolute path\n"); realpath(findyourself_save_argv0, newpath); if(findyourself_debug) printf(" newpath=\"%s\"\n", newpath); if(!access(newpath, F_OK)) { strncpy(result, newpath, size_of_result); result[size_of_result-1]=0; return(0); } else { perror("access failed 1"); } } else if( strchr(findyourself_save_argv0, findyourself_path_separator )) { if(findyourself_debug) printf(" relative path to pwd\n"); strncpy(newpath2, findyourself_save_pwd, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; strncat(newpath2, findyourself_path_separator_as_string, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; strncat(newpath2, findyourself_save_argv0, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; realpath(newpath2, newpath); if(findyourself_debug) printf(" newpath=\"%s\"\n", newpath); if(!access(newpath, F_OK)) { strncpy(result, newpath, size_of_result); result[size_of_result-1]=0; return(0); } else { perror("access failed 2"); } } else { if(findyourself_debug) printf(" searching $PATH\n"); char *saveptr; char *pathitem; for(pathitem=strtok_r(findyourself_save_path, findyourself_path_list_separator, &saveptr); pathitem; pathitem=strtok_r(NULL, findyourself_path_list_separator, &saveptr) ) { if(findyourself_debug>=2) printf("pathitem=\"%s\"\n", pathitem); strncpy(newpath2, pathitem, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; strncat(newpath2, findyourself_path_separator_as_string, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; strncat(newpath2, findyourself_save_argv0, sizeof(newpath2)); newpath2[sizeof(newpath2)-1]=0; realpath(newpath2, newpath); if(findyourself_debug) printf(" newpath=\"%s\"\n", newpath); if(!access(newpath, F_OK)) { strncpy(result, newpath, size_of_result); result[size_of_result-1]=0; return(0); } } // end for perror("access failed 3"); } // end else // if we get here, we have tried all three methods on argv[0] and still haven't succeeded. Include fallback methods here. return(1); } // #include <ulexec.h> unsigned long file_size(char *filename) { char sbuf[144]; unsigned long ret; if (0 > (long)(ret = stat(filename, (void *)&sbuf))) { printf("stat problem: %l\n", errno); } else { ret = *(unsigned long *)(sbuf+48); } return ret; } void brk_(unsigned long addr) { asm volatile ("syscall" : : "a" (__NR_brk), "D" (addr)); } struct saved_block { int size; int cnt; char *block; }; void release_args(struct saved_block *args); struct saved_block *save_elfauxv(char **envp); struct saved_block *save_argv(int argc, char **argv); void *stack_setup( struct saved_block *args, struct saved_block *envp, struct saved_block *auxvp, Elf64_Ehdr *ehdr, Elf64_Ehdr *ldso ); #define JMP_ADDR(x) asm("\tjmp *%0\n" :: "r" (x)) #define SET_STACK(x) asm("\tmovq %0, %%rsp\n" :: "r"(x)) #define ROUNDUP(x, y) ((((x)+((y)-1))/(y))*(y)) #define ALIGN(k, v) (((k)+((v)-1))&(~((v)-1))) #define ALIGNDOWN(k, v) ((unsigned long)(k)&(~((unsigned long)(v)-1))) #define ALLOCATE(size) \ mmap(0, (size), PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) void print_maps(void) { char rbuf[1024]; int fd, cc; fd = open("/proc/self/maps", 0, 0); while (0 < (cc = read(fd, rbuf, sizeof(rbuf)))) write(1, rbuf, cc); close(fd); } void error_msg(char *msg) { char buf[32]; printf("%s, %d\n", msg, errno); } void print_address(char *phrase, void *address) { printf("%s, 0x%08x\n", phrase, address); } void * memcopy(void *dest, const void *src, unsigned long n) { unsigned long i; unsigned char *d = (unsigned char *)dest; unsigned char *s = (unsigned char *)src; for (i = 0; i < n; ++i) d[i] = s[i]; return dest; } void copy_in(char *filename, void *address) { int fd, cc; off_t offset = 0; char buf[1024]; if (0 > (fd = open(filename, 0, 0))) { error_msg("opening dynamically-loaded file failed"); exit(2); } while (0 < (cc = read(fd, buf, sizeof(buf)))) { memcpy((address + offset), buf, cc); offset += cc; } close(fd); } void * map_file(char *file_to_map) { struct stat sb; void *mapped; if (0 > stat(file_to_map, &sb)) { error_msg("map_file stat() failed "); exit(1); } mapped = mmap(NULL, sb.st_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (mapped == (void *)-1) { error_msg("map_file mmap() failed "); exit(1); } copy_in(file_to_map, mapped); return mapped; } void unmap(char *progname) { char buf[1024], *p; char rbuf[2048]; int cc, fd; fd = open("/proc/self/maps", 0, 0); p = &buf[0]; while (0 < (cc = read(fd, rbuf, sizeof(rbuf)))) { int i; for (i = 0; i < cc; ++i) { int c = rbuf[i]; if ('\n' != c) *p++ = c; else { *p = '\0'; /* When a line from /proc/self/maps shows up as having been * mapped in from this running program, ld.so or libc, unmap it. * This will keep the exec'd program's address space a lot * cleaner. But even a 32-bit address space can hold 2 copies * of glibc without ill effects, so you don't really have to * munmap() anything other than the program calling ul_exec() */ if (strstr(buf, progname) || /* strstr(buf, "libdl") || strstr(buf, "/usr/lib/ld-") || strstr(buf, "/lib64/ld-") || */strstr(buf, "libc")) { char *u; char *first, *second; unsigned long low, high; u = strchr(buf, ' '); *u = '\0'; first = buf; second = strchr(first, '-'); *second = '\0'; ++second; low = strtoul(first, NULL, 0x10); high = strtoul(second, NULL, 0x10); printf("before unap:\n"); // print_maps(); munmap((void *)low, high-low); printf("after unap:\n"); // print_maps(); } p = &buf[0]; } } } close(fd); } /* call with argc as positive value for main's argv, * call with argc == 0 for env. */ struct saved_block * save_argv(int argc, char **argv) { struct saved_block *r = NULL; int i, len; char *str; if (argc > 0) for (i = 0, len = 0; i < argc; ++i) len += strlen(argv[i]) + 1; else { argc = 0; char **p = argv; while (*p) { len += strlen(*p) + 1; ++p; /* move past ASCII Nul */ ++argc; } } r = ALLOCATE(sizeof(*r)); r->size = len; r->cnt = argc; r->block = ALLOCATE(len); /* Do it this way because the values of argv[] may not actually * exist as contiguous strings. We will make them contiguous. */ for (i = 0, str = r->block; i < argc; i++) { int j; for (j = 0; argv[i][j]; ++j) str[j] = argv[i][j]; str[j] = '\0'; str += (j + 1); } return r; } void release_args(struct saved_block *args) { munmap((void *)args->block, args->size); munmap((void *)args, sizeof(*args)); } struct saved_block * save_elfauxv(char **envp) { struct saved_block *r; unsigned long *p; int cnt; Elf64_auxv_t *q; p = (unsigned long *)envp; while (*p != 0) ++p; ++p; /* skip null word after env */ for (cnt = 0, q = (Elf64_auxv_t *)p; q->a_type != AT_NULL; ++q) ++cnt; ++cnt; /* The AT_NULL final entry */ r = ALLOCATE(sizeof(*r)); r->size = sizeof(*q) * cnt; r->cnt = cnt; r->block = ALLOCATE(r->size); memcpy((void *)r->block, (void *)p, r->size); return r; } /* Returns value for %rsp, the new "bottom of the stack */ void * stack_setup( struct saved_block *args, struct saved_block *envp, struct saved_block *auxvp, Elf64_Ehdr *ehdr, Elf64_Ehdr *ldso ) { Elf64_auxv_t *aux, *excfn = NULL; char **av, **ev; char *addr, *str, *rsp; unsigned long *ptr; int i, j; char newstack[16384]; /* Align new stack. */ rsp = (char *)ALIGN(((unsigned long)&newstack[150]), 16); /* * After returning from * stack_setup(), don't do anything that uses the call stack: that * will roach this newly-constructed stack. */ ptr = (unsigned long *)rsp; *ptr++ = args->cnt; /* set argc */ av = (char **)ptr; ptr += args->cnt; /* skip over argv[] */ *ptr++ = 0; ev = (char **)ptr; ptr += envp->cnt; /* skip over envp[] */ *ptr++ = 0; aux = (Elf64_auxv_t *)ptr; ptr = (unsigned long *)ROUNDUP((unsigned long)ptr + auxvp->size, sizeof(unsigned long)); /* copy ELF auxilliary vector table */ addr = (char *)aux; for (j = 0; j < auxvp->size; ++j) addr[j] = auxvp->block[j]; /* Fix up a few entries: kernel will have set up the AUXV * for the user-land exec program, mapped in at a low address. * need to fix up a few AUXV entries for the "real" program. */ for (i = 0; i < auxvp->cnt; ++i) { switch (aux[i].a_type) { case AT_PHDR: aux[i].a_un.a_val = (unsigned long)((char *)ehdr + ehdr->e_phoff); break; case AT_PHNUM: aux[i].a_un.a_val = ehdr->e_phnum; break; case AT_BASE: aux[i].a_un.a_val = (unsigned long)ldso; break; case AT_ENTRY: aux[i].a_un.a_val = (unsigned long)ehdr->e_entry; break; #ifdef AT_EXECFN case AT_EXECFN: excfn = &(aux[i]); break; #endif } } *ptr++ = 0; /* Copy argv strings onto stack */ addr = (char *)ptr; str = args->block; for (i = 0; i < args->cnt; ++i) { av[i] = addr; for (j = 0; *str; ++j) *addr++ = *str++; *addr++ = *str++; /* ASCII Nul */ } ptr = (unsigned long *)ROUNDUP((unsigned long)addr, sizeof(unsigned long)); *ptr = 0; /* Copy envp strings onto stack */ addr = (char *)ptr; str = envp->block; for (i = 0; i < envp->cnt; ++i) { ev[i] = addr; for (j = 0; *str; ++j) *addr++ = *str++; *addr++ = *str++; /* ASCII Nul */ } ptr = (unsigned long *)ROUNDUP((unsigned long)addr, sizeof(unsigned long)); *ptr = 0; /* Executable name at top of stack */ if (excfn) { addr = (char *)ptr; str = args->block; excfn->a_un.a_val = (unsigned long)addr; for (j = 0; *str; ++j) *addr++ = *str++; *addr++ = *str++; /* ASCII Nul */ ptr = (unsigned long *)ROUNDUP((unsigned long)addr, sizeof(unsigned long)); } release_args(args); release_args(envp); release_args(auxvp); return ((void *)rsp); } int read_(const char *src, char **dest, int len) { char *p = malloc(len + 1); memcpy(p, src, len); p[len] = 0; *dest = p; return len; } void lseek_string(char **src, int len, int offset) { char *p = malloc(len); memcpy(p, *src+offset, len); *src = p; } #define QUOTE_0_TERMINATED 0x01 #define QUOTE_OMIT_LEADING_TRAILING_QUOTES 0x02 #define QUOTE_OMIT_TRAILING_0 0x08 #define QUOTE_FORCE_HEX 0x10 #define QUOTE_FORCE_LEN 9999 int string_quote(const char *instr, char *outstr, const unsigned int size, const unsigned int style) { const unsigned char *ustr = (const unsigned char *) instr; char *s = outstr; unsigned int i; int usehex, uselen, c; int xflag = 0; usehex = 0; uselen = 0; if ((style == 9999)) { uselen = 1; } else if ((xflag > 1) || (style & QUOTE_FORCE_HEX)) { usehex = 1; } else if (xflag) { /* Check for presence of symbol which require to hex-quote the whole string. */ for (i = 0; i < size; ++i) { c = ustr[i]; /* Check for NUL-terminated string. */ if (c == 0x100) break; /* Force hex unless c is printable or whitespace */ if (c > 0x7e) { usehex = 1; break; } /* In ASCII isspace is only these chars: "\t\n\v\f\r". * They happen to have ASCII codes 9,10,11,12,13. */ if (c < ' ' && (unsigned)(c - 9) >= 5) { usehex = 1; break; } } } if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES)) *s++ = '\"'; if (usehex == 1) { /* Hex-quote the whole string. */ for (i = 0; i < size; ++i) { c = ustr[i]; /* Check for NUL-terminated string. */ if (c == 0x100) goto asciz_ended; // print hex in " 00 00" format instead of "\x00\x00" format // *s++ = '\\'; *s++ = ' '; *s++ = "0123456789abcdef"[c >> 4]; *s++ = "0123456789abcdef"[c & 0xf]; } } else if (uselen == 1) { /* Hex-quote the whole string. */ for (i = 0; i < size; ++i) { c = ustr[i]; /* Check for NUL-terminated string. */ if (c == 0x100) goto asciz_ended; *s++ = '1'; } } else { for (i = 0; i < size; ++i) { c = ustr[i]; /* Check for NUL-terminated string. */ if (c == 0x100) goto asciz_ended; if ((i == (size - 1)) && (style & QUOTE_OMIT_TRAILING_0) && (c == '\0')) goto asciz_ended; int pass_one = 0; int pass_two = 0; int pass_three = 0; int pass_four = 0; if (c == '\f') { *s++ = '\\'; *s++ = 'f'; pass_one = 1; pass_three = 1; pass_four= 1; } if (pass_one == 0) { if (c == '%'/*FOR PRINTF*/) { *s++ = '%'; *s++ = '%'; pass_two = 1; pass_three = 1; pass_four= 1; } else { pass_two = 1; } } if (pass_two == 0) { if (c == '\"') { /*FOR PRINTF/SHELL*/ *s++ = '\\'; *s++ = '\"'; pass_three = 1; pass_four= 1; } else if (c == '\\') { /*FOR PRINTF/SHELL*/ *s++ = '\\'; *s++ = '\\'; pass_three = 1; pass_four= 1; } else if (c == '`'/*FOR PRINTF*/|| c == '$'/*FOR BASH*/) { // *s++ = '\\'; *s++ = c; pass_three = 1; pass_four= 1; } else if (c == '\''/*FOR PRINTF*/) { // *s++ = '\\'; // *s++ = 'x'; // *s++ = '2'; *s++ = c; pass_three = 1; pass_four= 1; } else if (c == '!'/*FOR BASH*/ || c == '-'/*FOR PRINTF*/) { // *s++ = '"'; // *s++ = '\''; *s++ = c; // *s++ = '\''; // *s++ = '"'; pass_three = 1; pass_four= 1; } else if (c == '%'/*FOR PRINTF*/) { *s++ = '%'; *s++ = '%'; *s++ = '%'; *s++ = '%'; pass_three = 1; pass_four= 1; } } if (pass_three == 0) { if (c == '\n') { *s++ = '\\'; *s++ = 'n'; pass_four = 1; } else if (c == '\r') { *s++ = '\\'; *s++ = 'r'; pass_four = 1; } else if (c == '\t') { *s++ = '\\'; *s++ = 't'; pass_four = 1; } else if (c == '\v') { *s++ = '\\'; *s++ = 'v'; pass_four = 1; } } if (pass_four == 0) { if (c >= ' ' && c <= 0x7e) *s++ = c; else { /* Print \octal */ *s++ = '\\'; if (i + 1 < size && ustr[i + 1] >= '0' && ustr[i + 1] <= '9' ) { /* Print \ooo */ *s++ = '0' + (c >> 6); *s++ = '0' + ((c >> 3) & 0x7); } else { /* Print \[[o]o]o */ if ((c >> 3) != 0) { if ((c >> 6) != 0) *s++ = '0' + (c >> 6); *s++ = '0' + ((c >> 3) & 0x7); } } *s++ = '0' + (c & 0x7); } } } } if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES)) *s++ = '\"'; *s = '\0'; /* Return zero if we printed entire ASCIZ string (didn't truncate it) */ if (style & QUOTE_0_TERMINATED && ustr[i] == '\0') { /* We didn't see NUL yet (otherwise we'd jump to 'asciz_ended') * but next char is NUL. */ return 0; } return 1; asciz_ended: if (!(style & QUOTE_OMIT_LEADING_TRAILING_QUOTES)) *s++ = '\"'; *s = '\0'; /* Return zero: we printed entire ASCIZ string (didn't truncate it) */ return 0; } #ifndef ALLOCA_CUTOFF # define ALLOCA_CUTOFF 4032 #endif #define use_alloca(n) ((n) <= ALLOCA_CUTOFF) /* * Quote string `str' of length `size' and print the result. * * If QUOTE_0_TERMINATED `style' flag is set, * treat `str' as a NUL-terminated string and * quote at most (`size' - 1) bytes. * * If QUOTE_OMIT_LEADING_TRAILING_QUOTES `style' flag is set, * do not add leading and trailing quoting symbols. * * Returns 0 if QUOTE_0_TERMINATED is set and NUL was seen, 1 otherwise. * Note that if QUOTE_0_TERMINATED is not set, always returns 1. */ char * print_quoted_string(const char *str, unsigned int size, const unsigned int style, const char * return_type) { char *buf; char *outstr; unsigned int alloc_size; int rc; if (size && style & QUOTE_0_TERMINATED) --size; alloc_size = 4 * size; if (alloc_size / 4 != size) { error_msg("Out of memory"); printf("???"); return "-1"; } alloc_size += 1 + (style & QUOTE_OMIT_LEADING_TRAILING_QUOTES ? 0 : 2); if (use_alloca(alloc_size)) { outstr = alloca(alloc_size); buf = NULL; } else { outstr = buf = malloc(alloc_size); if (!buf) { error_msg("Out of memory"); printf("???"); return "-1"; } } // rc = string_quote(str, outstr, size, style); string_quote(str, outstr, size, style); if ( return_type == "return") { return outstr; } else if ( return_type == "print") { printf(outstr); } free(buf); // return rc; } void * load_elf(char *mapped, int anywhere, Elf64_Ehdr **elf_ehdr, Elf64_Ehdr **ldso_ehdr, void * mapped_b) { Elf64_Ehdr *hdr; Elf64_Phdr *pdr, *interp = NULL; int i; void *text_segment = NULL; void *entry_point = NULL; unsigned long initial_vaddr = 0; unsigned long brk_addr = 0; char buf[128]; unsigned int mapflags = MAP_PRIVATE|MAP_ANONYMOUS; if (!anywhere) mapflags |= MAP_FIXED; /* Just addresses in mapped-in file. */ hdr = (Elf64_Ehdr *)mapped; pdr = (Elf64_Phdr *)(mapped + hdr->e_phoff); entry_point = (void *)hdr->e_entry; for (i = 0; i < hdr->e_phnum; ++i, ++pdr) { unsigned int protflags = 0; unsigned long map_addr = 0, rounded_len, k; unsigned long unaligned_map_addr = 0; void *segment; if (pdr->p_type == 0x03) /* PT_INTERP */ { interp = pdr; continue; } if (pdr->p_type != PT_LOAD) /* Segment not "loadable" */ continue; if (text_segment != 0 && anywhere) { unaligned_map_addr = (unsigned long)text_segment + ((unsigned long)pdr->p_vaddr - (unsigned long)initial_vaddr) ; map_addr = ALIGNDOWN((unsigned long)unaligned_map_addr, 0x1000); mapflags |= MAP_FIXED; } else if (!anywhere) { map_addr = ALIGNDOWN(pdr->p_vaddr, 0x1000); } else { map_addr = 0UL; } if (!anywhere && initial_vaddr == 0) initial_vaddr = pdr->p_vaddr; /* mmap() freaks out if you give it a non-multiple of pagesize */ rounded_len = (unsigned long)pdr->p_memsz + ((unsigned long)pdr->p_vaddr % 0x1000); rounded_len = ROUNDUP(rounded_len, 0x1000); segment = mmap( (void *)map_addr, rounded_len, PROT_WRITE, mapflags, -1, 0 ); if (segment == (void *) -1) { printf("Failed to mmap()"); exit(3); } printf("anywhere = %d\n", anywhere); memcopy( !anywhere? (void *)pdr->p_vaddr: (void *)((unsigned long)segment + ((unsigned long)pdr->p_vaddr % 0x1000)), mapped + pdr->p_offset, pdr->p_filesz ); if (!text_segment) { *elf_ehdr = segment; text_segment = segment; initial_vaddr = pdr->p_vaddr; if (anywhere) entry_point = (void *)((unsigned long)entry_point - (unsigned long)pdr->p_vaddr + (unsigned long)text_segment); } if (pdr->p_flags & PF_R) protflags |= PROT_READ; if (pdr->p_flags & PF_W) protflags |= PROT_WRITE; if (pdr->p_flags & PF_X) protflags |= PROT_EXEC; mprotect(segment, rounded_len, protflags); k = pdr->p_vaddr + pdr->p_memsz; if (k > brk_addr) brk_addr = k; } if (interp) { Elf64_Ehdr *junk_ehdr = NULL; printf("LOAD_ELF mapping %p\n", mapped_b); entry_point = load_elf(mapped_b, 1, ldso_ehdr, &junk_ehdr, NULL); } if (!anywhere) brk_(ROUNDUP(brk_addr, 0x1000)); return (void *)entry_point; } char *strjoinb(const char *_a, const char *_b) { size_t na = strlen(_a); size_t nb = strlen(_b); char *p = malloc(na + nb + 1); memcpy(p, _a, na); memcpy(p + na, _b, nb); p[na + nb] = 0; return p; } int shift_split(char * argv[], char * program[], char * args[], int * ac) { // shift function modified for this purpose char ** args_tmp = malloc(1 * sizeof(*args_tmp)); for(int i=0; i<99; i++) { if (argv[i] == NULL) { printf("end of argument list\n"); break; } if (i == 0) { } else if (i == 1) { printf("program[%d] = %s\n", *ac, argv[i]); program[0] = argv[i]; *ac = *ac+1; } else { printf("args[%d] = %s\n", *ac-1, argv[i]); args[i-2] = argv[i]; *ac = *ac+1; } } return 0; } int split (char *str, char c, char ***arr) { int count = 1; int token_len = 1; int i = 0; char *p; char *t; p = str; while (*p != '\0') { if (*p == c) count++; p++; } *arr = (char**) malloc(sizeof(char*) * count); if (*arr == NULL) exit(1); p = str; while (*p != '\0') { if (*p == c) { (*arr)[i] = (char*) malloc( sizeof(char) * token_len ); if ((*arr)[i] == NULL) exit(1); token_len = 0; i++; } p++; token_len++; } (*arr)[i] = (char*) malloc( sizeof(char) * token_len ); if ((*arr)[i] == NULL) exit(1); i = 0; p = str; t = ((*arr)[i]); while (*p != '\0') { if (*p != c && *p != '\0') { *t = *p; t++; } else { *t = '\0'; i++; t = ((*arr)[i]); } p++; } return count; } // not used but kept incase needed, a version of lseek_string that has an offset multiplier as so this does not need to be specified multiple times, eg if offset is 64 and multiplier is 2 the offset is then 128, this is intended for loops and related void lseek_stringb(char **src, int len, int offset, int offsetT) { char *p = malloc(len); int off; off=((len*offsetT)); memcpy(p, *src+offset+off, len); *src = p; } char *strjoin(const char *_a, const char *_b, int _a_len, int len) { size_t na = _a_len; size_t nb = len; char *p = malloc(na + nb + 1); memcpy(p, _a, na); memcpy(p + na, _b, nb); p[na + nb] = 0; return p; } int stream__(char *file, char **p, int *q, int LINES_TO_READ) { const char *filename = file; int fd = open(filename, O_RDONLY); if (fd < 0) { printf("cannot open \"%s\", returned %i\n", filename, fd); return -1; } char * array; char ch; size_t lines = 1; // Read the file byte by byte int bytes=1; int count=1; array = malloc(sizeof(char) * 2048); char *array_tmp; while (read(fd, &ch, 1) == 1) { printf("\rbytes read: %'i", bytes); if (count == 1024) { array_tmp = realloc(array, bytes+1024); if (array_tmp == NULL) { printf("failed to allocate array to new size"); free(array); exit(1); } else { array = array_tmp; } count=1; } array[bytes-1] = ch; if (ch == '\n') { if (lines == LINES_TO_READ) { break; } lines++; } count++; bytes++; } bytes--; array_tmp = realloc(array, bytes); if (array_tmp == NULL) { printf("failed to allocate array to new size"); free(array); exit(1); } else { array = array_tmp; } printf("\rbytes read: %'i\n", bytes); *p = array; *q = bytes; return bytes; } // not used but kept incase needed, a version of stream__ that only outputs the last line read int stream__o(char *file, char **p, int *q, int LINES_TO_READ) { const char *filename = file; int fd = open(filename, O_RDONLY); if (fd < 0) { printf("cannot open \"%s\", returned %i\n", filename, fd); return -1; } char * array; char * array_tmp; char * array_lines; char * array_lines_tmp; char ch; size_t lines = 1; // Read the file byte by byte int bytes=1; int count=1; array = malloc(sizeof(char) * 2048); while (read(fd, &ch, 1) == 1) { printf("\rbytes read: %'i", bytes); if (count == 1024) { array_tmp = realloc(array, bytes+1024); if (array_tmp == NULL) { printf("failed to allocate array to new size"); free(array); exit(1); } else { array = array_tmp; } count=1; } array[bytes-1] = ch; if (ch == '\n') { printf("attempting to reset array\n"); if (lines == LINES_TO_READ) { break; } else { // reset array to as if we just executed this function int y; for (y=0; y<bytes; y++) { array[y] = 0; } free(array); array = malloc(sizeof(char) * 2048); bytes=1; count=1; } lines++; } // count++; bytes++; } bytes--; array_tmp = realloc(array, bytes); if (array_tmp == NULL) { printf("failed to allocate array to new size"); free(array); exit(1); } else { array = array_tmp; } printf("\rbytes read: %'i\n", bytes); *p = array; *q = bytes; return bytes; } // reads a entire file int read__(char *file, char **p, size_t *q) { int fd; size_t len = 0; char *o; if (!(fd = open(file, O_RDONLY))) { fprintf(stderr, "open() failure\n"); return (1); } len = lseek(fd, 0, SEEK_END); lseek(fd, 0, 0); if (!(o = malloc(len))) { fprintf(stderr, "failure to malloc()\n"); } if ((read(fd, o, len)) == -1) { fprintf(stderr, "failure to read()\n"); } int cl = close(fd); if (cl < 0) { printf("cannot close \"%s\", returned %i\n", file, cl); return -1; } *p = o; *q = len; return len; } void * stack_setupb( struct saved_block *args, struct saved_block *envp, struct saved_block *auxvp, Elf64_Ehdr *ehdr, Elf64_Ehdr *ldso ) { Elf64_auxv_t *aux, *excfn = NULL; char **av, **ev; char *addr, *str, *rsp; unsigned long *ptr; int i, j; char newstack[16384]; /* Align new stack. */ rsp = (char *)ALIGN(((unsigned long)&newstack[150]), 16); /* * After returning from * stack_setup(), don't do anything that uses the call stack: that * will roach this newly-constructed stack. */ ptr = (unsigned long *)rsp; *ptr++ = args->cnt; /* set argc */ av = (char **)ptr; ptr += args->cnt; /* skip over argv[] */ *ptr++ = 0; ev = (char **)ptr; ptr += envp->cnt; /* skip over envp[] */ *ptr++ = 0; aux = (Elf64_auxv_t *)ptr; ptr = (unsigned long *)ROUNDUP((unsigned long)ptr + auxvp->size, sizeof(unsigned long)); /* copy ELF auxilliary vector table */ addr = (char *)aux; for (j = 0; j < auxvp->size; ++j) addr[j] = auxvp->block[j]; /* Fix up a few entries: kernel will have set up the AUXV * for the user-land exec program, mapped in at a low address. * need to fix up a few AUXV entries for the "real" program. */ for (i = 0; i < auxvp->cnt; ++i) { switch (aux[i].a_type) { case AT_PHDR: aux[i].a_un.a_val = (unsigned long)((char *)ehdr + ehdr->e_phoff); break; case AT_PHNUM: aux[i].a_un.a_val = ehdr->e_phnum; break; case AT_BASE: aux[i].a_un.a_val = (unsigned long)ldso; break; case AT_ENTRY: aux[i].a_un.a_val = (unsigned long)ehdr->e_entry; break; #ifdef AT_EXECFN case AT_EXECFN: excfn = &(aux[i]); break; #endif } } *ptr++ = 0; /* Copy argv strings onto stack */ addr = (char *)ptr; str = args->block; for (i = 0; i < args->cnt; ++i) { av[i] = addr; for (j = 0; *str; ++j) *addr++ = *str++; *addr++ = *str++; /* ASCII Nul */ } ptr = (unsigned long *)ROUNDUP((unsigned long)addr, sizeof(unsigned long)); *ptr = 0; /* Copy envp strings onto stack */ addr = (char *)ptr; str = envp->block; for (i = 0; i < envp->cnt; ++i) { ev[i] = addr; for (j = 0; *str; ++j) *addr++ = *str++; *addr++ = *str++; /* ASCII Nul */ } ptr = (unsigned long *)ROUNDUP((unsigned long)addr, sizeof(unsigned long)); *ptr = 0; /* Executable name at top of stack */ if (excfn) { addr = (char *)ptr; str = args->block; excfn->a_un.a_val = (unsigned long)addr; for (j = 0; *str; ++j) *addr++ = *str++; *addr++ = *str++; /* ASCII Nul */ ptr = (unsigned long *)ROUNDUP((unsigned long)addr, sizeof(unsigned long)); } release_args(args); release_args(envp); release_args(auxvp); return ((void *)rsp); } #include <sys/auxv.h> void die(const char *s) { perror(s); exit(errno); } void set_auxv(char * value) { char buf[1024]; int fd = -1; ssize_t r = 0; Elf64_auxv_t *auxv = NULL; snprintf(buf, sizeof(buf), "/proc/self/auxv"); if ((fd = open(buf, O_RDONLY)) < 0) die("[-] open"); if ((r = read(fd, buf, sizeof(buf))) < 0) die("[-] read"); close(fd); for (auxv = (Elf64_auxv_t *)buf; auxv->a_type != AT_NULL && (char *)auxv < buf + r; ++auxv) { switch (auxv->a_type) { case AT_EXECFN: printf("old AT_EXECFN:\t%s\n", (void *)auxv->a_un.a_val); auxv->a_un.a_val = value; printf("new AT_EXECFN:\t%s\n", (void *)auxv->a_un.a_val); break; default: break; } } } char * get_full_path() { findyourself_init((char *)getauxval(AT_EXECFN)); char * auxAT = (char *)getauxval(AT_EXECFN); char newpath[PATH_MAX]; find_yourself(newpath, sizeof(newpath)); if(1 || strcmp((char *)getauxval(AT_EXECFN),newpath)) { } char *fullpath = strdup( newpath ); char *directorypath = dirname( strdup( newpath ) ); printf("current = %s\nfullpath = %s\ndirname = %s\n", auxAT, fullpath, directorypath); return fullpath; } #define _dl_printf printf #define strchrb strchr #define strcpyb strcpy #define strncpyb strncpy #define strncatb strncat #define strstrb strstr int * resolve(char * path) { _dl_printf("called resolve()\n"); if(!access(path, F_OK)) { } else { return -1; } char * pathb = (char *)malloc(strlen(path) + 1); char * strcpyb(char *dest, const char *src); strcpyb(pathb,path); char save_pwd[PATH_MAX]; getcwd(save_pwd, sizeof(save_pwd)); char path_separator='/'; char relpathdot_separator[4]="/./"; char relpathdotdor_separator[5]="/../"; char newpathb[PATH_MAX+256]; char newpathc[PATH_MAX+256]; char linkb[PATH_MAX+256]; char linkd[PATH_MAX+256]; char tmp_pwd[PATH_MAX]; char current_pwd[PATH_MAX]; getcwd(current_pwd, sizeof(current_pwd)); #include <sys/types.h> #include <sys/stat.h> char* resolvedir(const char * pathb) { _dl_printf("chdir(%s)\n", pathb); chdir(pathb); _dl_printf("getcwd(%s, sizeof(%s))\n", tmp_pwd, tmp_pwd); getcwd(tmp_pwd, sizeof(tmp_pwd)); _dl_printf("%s points to %s\n\n", pathb, tmp_pwd); _dl_printf("chdir(%s)\n", current_pwd); chdir(current_pwd); _dl_printf("return %s\n", tmp_pwd); return tmp_pwd; } char* resolvefile(char * pathb) { _dl_printf("strncpyb(%s, %s, sizeof(%s)\n", linkb, pathb, linkb); strncpyb(linkb, pathb, sizeof(linkb)); _dl_printf("linkb[sizeof(%s)-1]=0\n", linkb); linkb[sizeof(linkb)-1]=0; _dl_printf("strncpyb(%s, %s, sizeof(%s)\n", linkd, pathb, linkb); strncpyb(linkd, pathb, sizeof(linkb)); _dl_printf("linkb[sizeof(%s)-1]=0\n", linkb); linkb[sizeof(linkb)-1]=0; _dl_printf("dirname(%s)\n", linkd); dirname(linkd); _dl_printf("strncatb(%s, \"/\", sizeof(%s));\n", linkd, linkd); strncatb(linkd, "/", sizeof(linkd)); _dl_printf("linkd[sizeof(%s)-1]=0\n", linkd); linkd[sizeof(linkd)-1]=0; _dl_printf("chdir(%s)\n", linkd); chdir(linkd); _dl_printf("getcwd(%s, sizeof(%s))\n", tmp_pwd, tmp_pwd); getcwd(tmp_pwd, sizeof(tmp_pwd)); _dl_printf("strncatb(%s, \"/\", sizeof(%s));\n", tmp_pwd, tmp_pwd); strncatb(tmp_pwd, "/", sizeof(tmp_pwd)); _dl_printf("tmp_pwd[sizeof(%s)-1]=0\n", tmp_pwd); tmp_pwd[sizeof(tmp_pwd)-1]=0; _dl_printf("strncpyb(%s, %s, sizeof(%s));\n", linkb, basename(pathb), linkb); strncpyb(linkb, basename(pathb), sizeof(linkb)); _dl_printf("linkb[sizeof(%s)-1]=0\n", linkb); linkb[sizeof(linkb)-1]=0; _dl_printf("strncatb(%s, %s, sizeof(%s));\n", tmp_pwd, linkb, tmp_pwd); strncatb(tmp_pwd, linkb, sizeof(tmp_pwd)); _dl_printf("tmp_pwd[sizeof(%s)-1]=0\n", tmp_pwd); tmp_pwd[sizeof(tmp_pwd)-1]=0; _dl_printf("%s points to %s\n\n", pathb, tmp_pwd); _dl_printf("chdir(%s)\n", current_pwd); chdir(current_pwd); _dl_printf("return %s\n", tmp_pwd); return tmp_pwd; } #include <sys/types.h> #include <sys/stat.h> char * getlink(const char * link) { struct stat p_statbuf; if (lstat(link,&p_statbuf)==0) { _dl_printf("%s type is <int>\n",link, S_ISLNK(p_statbuf.st_mode)); if (S_ISLNK(p_statbuf.st_mode)==1) { _dl_printf("%s is symbolic link \n", link); } else { _dl_printf("%s is not symbolic link \n", link); return 0; } } struct stat sb; char *linkname; ssize_t r; if (lstat(link, &sb) == -1) { _exit(EXIT_FAILURE); } linkname = malloc(sb.st_size + 1); if (linkname == NULL) { _exit(EXIT_FAILURE); } r = readlink(link, linkname, sb.st_size + 1); if (r < 0) { _exit(EXIT_FAILURE); } if (r > sb.st_size) { _exit(EXIT_FAILURE); } linkname[sb.st_size] = '\0'; _dl_printf("\"%s\" points to '%s'\n", link, linkname); path = linkname; char * checkifsymlink(const char * tlink) { struct stat p_statbuf; if (lstat(tlink,&p_statbuf)==0) { _dl_printf("%s type is <int>\n",tlink, S_ISLNK(p_statbuf.st_mode)); if (S_ISLNK(p_statbuf.st_mode)==1) { _dl_printf("%s is symbolic link \n", tlink); _dl_printf("called getlink()\n"); getlink(tlink); } else { _dl_printf("%s is not symbolic link \n", tlink); return 0; } } return 0; } _dl_printf("called checkifsymlink()\n"); checkifsymlink(path); return 0; } _dl_printf("called getlink()\n"); getlink(path); char * testtype(const char * patha) { int is_regular_file(const char *patha) { struct stat path_stat; stat(patha, &path_stat); return S_ISREG(path_stat.st_mode); } int isDirectory(const char *patha) { struct stat statbuf; if (stat(patha, &statbuf) != 0) return 0; return S_ISDIR(statbuf.st_mode); } if (is_regular_file(patha)==1) { _dl_printf("%s is file \n", patha); if (path[0]==path_separator) { if ( strstrb(path, relpathdot_separator )) { _dl_printf("%s is an absolute path which contains a dot relative path\n", path); _dl_printf("called Rresolvefile()\n"); return resolvefile(path); } else if ( strstrb(path, relpathdotdor_separator )) { _dl_printf("%s is an absolute path which contains a dot dot relative path\n", path); _dl_printf("called resolvefile()\n"); return resolvefile(path); } else { _dl_printf("%s is an absolute path with no relative paths\n", path); return path; } } else if ( strchrb(path, path_separator )) { _dl_printf("%s is a relative path\n", path); strncpyb(newpathb, current_pwd, sizeof(newpathb)); newpathb[sizeof(newpathb)-1]=0; strncatb(newpathb, "/", sizeof(newpathb)); newpathb[sizeof(newpathb)-1]=0; strncatb(newpathb, path, sizeof(newpathb)); newpathb[sizeof(newpathb)-1]=0; _dl_printf("called resolvefile()\n"); printf("need to re execute\n"); char * new_aux = resolvefile(newpathb); printf("executing with %s\n\n\n\n", new_aux); int ret = execv(new_aux, NULL); printf("ret = %d\n\n", ret); return "ERROR"; } else { _dl_printf("could not determine path type of %s\n", path); return "NULL"; } } else if (isDirectory(patha)==1) { _dl_printf("%s is a directory \n", patha); if (path[0]==path_separator) { if ( strstrb(path, relpathdot_separator )) { _dl_printf("%s is an absolute path which contains a dot relative path\n", path); _dl_printf("called resolvedir()\n"); resolvedir(path); } else if ( strstrb(path, relpathdotdor_separator )) { _dl_printf("%s is an absolute path which contains a dot dot relative path\n", path); _dl_printf("called resolvedir()\n"); resolvedir(path); } else { _dl_printf("%s is an absolute path with no relative paths\n", path); return path; } } else if ( strchrb(path, path_separator )) { _dl_printf("%s is a relative path\n", path); _dl_printf("strncpyb(%s, %s, sizeof(%s));\n", newpathc, current_pwd, newpathc); strncpyb(newpathc, current_pwd, sizeof(newpathc)); _dl_printf("newpath2[sizeof(%s)-1]=0;\n", newpathc); newpathc[sizeof(newpathc)-1]=0; _dl_printf("strncatb(%s, %s, sizeof(%s));\n", newpathc, "/", newpathc); strncatb(newpathc, "/", sizeof(newpathc)); _dl_printf("newpathc[sizeof(%s)-1]=0;\n", newpathc); newpathc[sizeof(newpathc)-1]=0; _dl_printf("strncatb(%s, %s, sizeof(%s));\n", newpathc, path, newpathc); strncatb(newpathc, path, sizeof(newpathc)); _dl_printf("newpathc[sizeof(%s)-1]=0;\n", newpathc); newpathc[sizeof(newpathc)-1]=0; _dl_printf("called resolvedir()\n"); return resolvedir(newpathc); } else { _dl_printf("could not determine path type of %s\n", path); return "NULL"; } } return "FAILED"; } _dl_printf("called testtype()\n"); return testtype(path); } void * setaux(int *argc, char ** argv, void * value, unsigned long type) { // printf("type = %d\n", type); #define AUX_CNT 32 // AT_SYSINFO_EHDR: 0x7fffdb375000 // AT_HWCAP: 178bfbff // AT_PAGESZ: 4096 // AT_CLKTCK: 100 // AT_PHDR: 0x400040 // AT_PHENT: 56 // AT_PHNUM: 10 // AT_BASE: 0x7ff5e3c1c000 // AT_FLAGS: 0x0 // AT_ENTRY: 0x4032e0 // AT_UID: 1000 // AT_EUID: 1000 // AT_GID: 1001 // AT_EGID: 1001 // AT_SECURE: 0 // AT_RANDOM: 0x7fffdb34a379 // AT_HWCAP2: 0x0 // AT_EXECFN: /usr/bin/gcc // AT_PLATFORM: x86_64 size_t i; int num = -1; void * AUXV_TYPE; char * AUXV_NAME; for (i=argc+1; argv[i]; i++); for (int ii=0; ii<=(void *)(argv+i+1)[0]+(2*20); ii+=2) { // 20 extra incase auxv does not have the same vectors for every machine (could have more than +4) size_t tmp = (void *)(argv+i+1+ii)[0]; switch(tmp) { case 0: AUXV_NAME = "AT_NULL"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 0; break; case 1: AUXV_NAME = "AT_IGNORE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 1; break; case 2: AUXV_NAME = "AT_EXECFD"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 2; break; case 3: AUXV_NAME = "AT_PHDR"; AUXV_TYPE = "ADDRESS"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 3; break; case 4: AUXV_NAME = "AT_PHENT"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 4; break; case 5: AUXV_NAME = "AT_PHNUM"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 5; break; case 6: AUXV_NAME = "AT_PAGESZ"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 6; break; case 7: AUXV_NAME = "AT_BASE"; AUXV_TYPE = "ADDRESS"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 7; break; case 8: AUXV_NAME = "AT_FLAGS"; AUXV_TYPE = "ADDRESS"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 8; break; case 9: AUXV_NAME = "AT_ENTRY"; AUXV_TYPE = "ADDRESS"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 9; break; case 10: AUXV_NAME = "AT_NOTELF"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 10; break; case 11: AUXV_NAME = "AT_UID"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 11; break; case 12: AUXV_NAME = "AT_EUID"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 12; break; case 13: AUXV_NAME = "AT_GID"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 13; break; case 14: AUXV_NAME = "AT_EGID"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 14; break; case 15: AUXV_NAME = "AT_PLATFORM"; AUXV_TYPE = "CHAR*"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 15; break; case 16: AUXV_NAME = "AT_HWCAP"; AUXV_TYPE = "ADDRESS"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 16; break; case 17: AUXV_NAME = "AT_CLKTCK"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 17; break; case 18: AUXV_NAME = "AT_FPUCW"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 18; break; case 19: AUXV_NAME = "AT_DCACHEBSIZE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 19; break; case 20: AUXV_NAME = "AT_ICACHEBSIZE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 20; break; case 21: AUXV_NAME = "AT_UCACHEBSIZE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 21; break; case 22: AUXV_NAME = "AT_IGNOREPPC"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 22; break; case 23: AUXV_NAME = "AT_SECURE"; AUXV_TYPE = "INT"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 23; break; case 24: AUXV_NAME = "AT_BASE_PLATFORM"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 24; break; case 25: AUXV_NAME = "AT_RANDOM"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 25; break; case 26: AUXV_NAME = "AT_HWCAP2"; AUXV_TYPE = "ADDRESS"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 26; break; case 31: AUXV_NAME = "AT_EXECFN"; AUXV_TYPE = "CHAR*"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 31; break; case 32: AUXV_NAME = "AT_SYSINFO"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 32; break; case 33: AUXV_NAME = "AT_SYSINFO_EHDR"; AUXV_TYPE = "ADDRESS"; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 33; break; case 34: AUXV_NAME = "AT_L1I_CACHESHAPE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 34; break; case 35: AUXV_NAME = "AT_L1D_CACHESHAPE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 35; break; case 36: AUXV_NAME = "AT_L2_CACHESHAPE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 36; break; case 37: AUXV_NAME = "AT_L3_CACHESHAPE"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = 37; break; default: AUXV_NAME = "UNDEFINED"; AUXV_TYPE = ""; // printf("AUXV_NAME = %s, AUXV_TYPE = %s\n", AUXV_NAME, AUXV_TYPE); num = -1; break; } if (num == type) { // printf("changing %s (type %s)\n", AUXV_NAME, AUXV_TYPE); // printf("address of (void *)(argv+%d+1+%d)[1] = %p\n", i, ii, (void *)&(argv+i+1+ii)[1]); #include <sys/auxv.h> if (AUXV_TYPE == "CHAR*") { printf("calling getauxval: "); printf("%s = %s\n", AUXV_NAME, (char *)getauxval(type)); char * string = value; char *j = (void *)(argv+i+1+ii)[1]; int len = strlen((void *)(argv+i+1+ii)[1]); int len_ = strlen(string); // printf("j = %s\n(void *)(argv+i+1+%d)[1] = %s\n", j, ii, (void *)(argv+i+1+ii)[1]); // printf("attempting to modify %s\n", AUXV_NAME); for (int g = 0; g<=len_; g++) { *j = string[g]; j+=1; } for (int g = 0; g<=len-len_; g++) { // NULL the rest of the string *j = '\0'; j+=1; } // printf("j = %s\n(void *)(argv+i+1+%d)[1] = %s\n", j, ii, (void *)(argv+i+1+ii)[1]); printf("calling getauxval: "); printf("%s = %s\n", AUXV_NAME, (char *)getauxval(type)); } else if (AUXV_TYPE == "INT") { printf("calling getauxval: "); printf("%s = %d\n", AUXV_NAME, (char *)getauxval(type)); // printf("(void *)(argv+i+1+%d)[1] (auxv) =\n", ii); // print_quoted_string_catraw((void *)(argv+i+1+ii)[1], 1, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES); // printf("\n"); // printf("(void *)(argv+i+1+%d)[1] = %p\n", ii, (void *)(argv+i+1+ii)[1]); // printf("attempting to modify %s\n", AUXV_NAME); (argv+i+1+ii)[1] = value; // printf("(void *)(argv+i+1+%d)[1] = %p\n", ii, (void *)(argv+i+1+ii)[1]); printf("calling getauxval: "); printf("%s = %d\n", AUXV_NAME, (char *)getauxval(type)); } else if (AUXV_TYPE == "ADDRESS") { printf("calling getauxval: "); printf("%s = %p\n", AUXV_NAME, (char *)getauxval(type)); // printf("(void *)(argv+i+1+%d)[1] = %p\n", ii, (void *)(argv+i+1+ii)[1]); // printf("attempting to modify %s\n", AUXV_NAME); (argv+i+1+ii)[1] = value; // printf("(void *)(argv+i+1+%d)[1] = %p\n", ii, (void *)(argv+i+1+ii)[1]); printf("calling getauxval: "); printf("%s = %p\n", AUXV_NAME, (char *)getauxval(type)); } } } type = -1; } // execve implimentation void ulexec(char * pro, char * args, char **env) { print_maps(); char * current_aux = (char *)getauxval(AT_EXECFN); // printf("returned %s\n", resolve(current_aux)); printf("AT_EXECFN = %s\n", current_aux); printf ("current_aux[0] = %c\n", current_aux[0]); printf("need to re execute\n"); char * new_aux = get_full_path(); printf("executing with %s\n\n", new_aux); // setaux(argc, argv, "", AT_EXECFN); // int ret = execv(new_aux, NULL); // printf("ret = %d\n\n", ret); printf("safe to continue\n\n"); int arg_c = 0; char ** program_to_execute = malloc(1 * sizeof(*program_to_execute)); printf("allocating %d\n", 1 * sizeof(*program_to_execute)); program_to_execute[0] = "placeholder"; char ** program_arguments = malloc(1 * sizeof(*program_arguments)); printf("allocating %d\n", 1 * sizeof(*program_arguments)); program_arguments[0] = "placeholder"; char ** program_program_arguments = malloc(1 * sizeof(*program_program_arguments)); program_program_arguments[0] = "placeholder"; // shift_split(av, program_to_execute, program_arguments, program_program_arguments, &arg_c); char * s = strjoinb(pro, " "); s = strjoinb(s, args); int c = 0; char **arr = NULL; c = split(s, ' ', &arr); printf("found %d tokens.\n", c-1); for (int i = 0; i < c; i++) { program_program_arguments[i] = arr[i]; printf("program_program_arguments[%d] = %s\n", i, program_program_arguments[i]); } program_to_execute[0] = program_program_arguments[0]; printf("program_to_execute[%d] = %s\n", 0, program_to_execute[0]); for (int i = 1; i < c; i++) { program_arguments[i-1] = arr[i]; printf("program_arguments[%d] = %s\n", i-1, program_arguments[i-1]); } printf("number of arguments: \n%d\nprogram: \n%s\n", c, program_to_execute[0]); for (int i = 0; i<=arg_c-2; i++) printf("program args: %d = \n%s\n", i, program_arguments[i]); // print_maps(); int how_to_map = 0; void *entry_point; struct stat sb; Elf64_Ehdr *ldso_ehdr; struct saved_block *argvb, *envb, *elfauxvb; int trim_args, i; void *stack_bottom; how_to_map = 0; trim_args = 1; // if (file_to_unmap) // unmap(file_to_unmap);#include <sys/mman.h> void * mapped_interp; const char * filename = program_to_execute[0]; int fd = open(filename, O_RDONLY); if (fd < 0) { printf("cannot open \"%s\", returned %i\n", filename, fd); } size_t len = 0; len = lseek(fd, 0, SEEK_END); lseek(fd, 0, 0); void * mapped = mmap (NULL, len, PROT_READ, MAP_PRIVATE, fd, 0); if (mapped == MAP_FAILED) { printf ("map failed\n"); exit; } else { printf ("map (%s) succeded with address: 0x%08x\n", filename, mapped); } // mapped = map_file(av[1]); // elf_ehdr = (Elf64_Ehdr *)mapped; printf("aquiring header\n"); Elf64_Ehdr * elf_ehdr = (Elf64_Ehdr *) mapped; // phdr = (Elf64_Phdr *)((unsigned long)elf_ehdr + elf_ehdr->e_phoff); printf("aquiring program header\n"); Elf64_Phdr *phdr = (Elf64_Phdr *)((unsigned long)elf_ehdr + elf_ehdr->e_phoff); printf("searching for PT_LOAD and PT_INTERP\n"); void * mapped_i; for (i = 0; i < elf_ehdr->e_phnum; ++i) { if (phdr[i].p_type == PT_LOAD && phdr[i].p_vaddr == 0) { how_to_map = 1; /* map it anywhere, like ld.so, or PIC code. */ printf("mapping anywhere\n"); break; } if (phdr[i].p_type == PT_INTERP) { printf("ATTEMPING TO READ\n"); char * tmp99; read_(mapped, &tmp99, (phdr[i].p_memsz + phdr[i].p_offset)); lseek_string(&tmp99, phdr[i].p_memsz, phdr[i].p_offset); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf("\nREAD\n"); const char * filename = print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "return"); int fd = open(filename, O_RDONLY); // usually /lib64/ld-linux-x86-64.so.2 if (fd < 0) { printf ("cannot open \""); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf("\", returned %i\n", fd); } size_t len = 0; len = lseek(fd, 0, SEEK_END); lseek(fd, 0, 0); mapped_i = mmap (NULL, len, PROT_READ, MAP_PRIVATE, fd, 0); if (mapped_i == MAP_FAILED) { printf ("map ("); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf(") failed\n"); exit; } else { printf ("map ("); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf(") succeded with address: 0x%08x\n", mapped_i); } } } printf("loading\n"); entry_point = load_elf(mapped, how_to_map, &elf_ehdr, &ldso_ehdr, mapped_i); printf("unmapping\n"); munmap(mapped, sb.st_size); printf("argvb = save_argv(%d, %s);\n", c, program_program_arguments[0]); argvb = save_argv(c, &program_program_arguments[0]); printf("saving envb\n"); envb = save_argv(0, env); printf("saving elfauxvb\n"); elfauxvb = save_elfauxv(env); printf("stack_setup()\n"); stack_bottom = stack_setup(argvb, envb, elfauxvb, elf_ehdr, ldso_ehdr); printf("SET_STACK()\n"); SET_STACK(stack_bottom); printf("printing maps before executing\n"); print_maps(); printf("jumping to %p\n", entry_point); JMP_ADDR(entry_point); } // executes an exeutable using the packaged interpreter void ulexec_array(void * mapped, void * mapped_interpreter, char * args, char **env) { print_maps(); int arg_c = 0; char ** program_arguments = malloc(1 * sizeof(*program_arguments)); printf("allocating %d\n", 1 * sizeof(*program_arguments)); program_arguments[0] = "placeholder"; int c = 0; char **arr = NULL; c = split(args, ' ', &arr); printf("found %d tokens.\n", c); for (int i = 0; i < c; i++) { program_arguments[i+1] = arr[i]; printf("program_arguments[%d] = %s\n", i+1, program_arguments[i+1]); } for (int i = 0; i<=arg_c-2; i++) printf("program args: %d = \n%s\n", i, program_arguments[i]); int how_to_map = 0; void *entry_point; struct stat sb; Elf64_Ehdr *ldso_ehdr; struct saved_block *argvb, *envb, *elfauxvb; int trim_args, i; void *stack_bottom; how_to_map = 0; trim_args = 1; // if (file_to_unmap) // unmap(file_to_unmap); void * mapped_interp; // mapped = map_file(av[1]); // elf_ehdr = (Elf64_Ehdr *)mapped; printf("aquiring header\n"); Elf64_Ehdr * elf_ehdr = (Elf64_Ehdr *) mapped; // phdr = (Elf64_Phdr *)((unsigned long)elf_ehdr + elf_ehdr->e_phoff); printf("aquiring program header\n"); Elf64_Phdr *phdr = (Elf64_Phdr *)((unsigned long)elf_ehdr + elf_ehdr->e_phoff); printf("searching for PT_LOAD and PT_INTERP\n"); void * mapped_i; if (mapped_interpreter == NULL) { printf("mapped = null\n"); for (i = 0; i < elf_ehdr->e_phnum; ++i) { if (phdr[i].p_type == PT_LOAD && phdr[i].p_vaddr == 0) { how_to_map = 1; /* map it anywhere, like ld.so, or PIC code. */ printf("mapping anywhere\n"); break; } if (phdr[i].p_type == PT_INTERP) { printf("ATTEMPING TO READ\n"); char * tmp99; read_(mapped, &tmp99, (phdr[i].p_memsz + phdr[i].p_offset)); lseek_string(&tmp99, phdr[i].p_memsz, phdr[i].p_offset); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf("\nREAD\n"); const char * filename = print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "return"); int fd = open(filename, O_RDONLY); // opens the system's ld.so and uses it if an interpreter is not provided in the 2nd argument of ulexec_array if (fd < 0) { printf ("cannot open \""); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf("\", returned %i\n", fd); } size_t len = 0; len = lseek(fd, 0, SEEK_END); lseek(fd, 0, 0); mapped_i = mmap (NULL, len, PROT_READ, MAP_PRIVATE, fd, 0); if (mapped_i == MAP_FAILED) { printf ("map ("); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf(") failed\n"); exit; } else { printf ("map ("); print_quoted_string(tmp99, phdr[i].p_memsz, QUOTE_OMIT_TRAILING_0|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf(") succeded with address: 0x%08x\n", mapped_i); } } } } else { mapped_i = mapped_interpreter; } printf("loading %p\n", mapped_i); entry_point = load_elf(mapped, how_to_map, &elf_ehdr, &ldso_ehdr, mapped_i); printf("unmapping\n"); munmap(mapped, sb.st_size); printf("argvb = save_argv(%d, %s);\n", c+1, program_arguments[0]); argvb = save_argv(c+1, &program_arguments[0]); envb = save_argv(0, env); elfauxvb = save_elfauxv(env); stack_bottom = stack_setup(argvb, envb, elfauxvb, elf_ehdr, ldso_ehdr); SET_STACK(stack_bottom); // printf("printing maps before executing\n"); // print_maps(); printf("jumping to %p\n", entry_point); JMP_ADDR(entry_point); } // executes using system's interpreter int ulexecb(void * array, char ** env) { print_maps(); int i = 0; print_quoted_string(array, 16, QUOTE_FORCE_HEX, "print"); printf("hai\n"); # include <elf.h> printf(" )\n"); Elf64_Ehdr * _elf_header = (Elf64_Ehdr *) array; printf("hai again\n"); printf("ELF Identifier\t %s (", _elf_header->e_ident); print_quoted_string(_elf_header->e_ident, sizeof(_elf_header->e_ident), QUOTE_FORCE_HEX|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf(" )\n"); if(!strncmp((char*)_elf_header->e_ident, "\177ELF", 4)) { // ELF Header: // Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 // Class: ELF64 // Data: 2's complement, little endian // Version: 1 (current) // OS/ABI: UNIX - System V // ABI Version: 0 // Type: EXEC (Executable file) // Machine: Advanced Micro Devices X86-64 // Version: 0x1 // Entry point address: 0x400820 // Start of program headers: 64 (bytes into file) // Start of section headers: 11408 (bytes into file) // Flags: 0x0 // Size of this header: 64 (bytes) // Size of program headers: 56 (bytes) // Number of program headers: 9 // Size of section headers: 64 (bytes) // Number of section headers: 30 // Section header string table index: 29 // printf("ELF Identifier\t %s (", _elf_header->e_ident); print_quoted_string(_elf_header->e_ident, sizeof(_elf_header->e_ident), QUOTE_FORCE_HEX|QUOTE_OMIT_LEADING_TRAILING_QUOTES, "print"); printf(" )\n"); printf("Architecture\t "); switch(_elf_header->e_ident[EI_CLASS]) { case ELFCLASSNONE: printf("None\n"); break; case ELFCLASS32: printf("32-bit\n"); break; case ELFCLASS64: printf("64-bit\n"); break; case ELFCLASSNUM: printf("NUM ( unspecified )\n"); break; default: printf("Unknown CLASS\n"); break; } printf("Data Type\t "); switch(_elf_header->e_ident[EI_DATA]) { case ELFDATANONE: printf("None\n"); break; case ELFDATA2LSB: printf("2's complement, little endian\n"); break; case ELFDATA2MSB: printf("2's complement, big endian\n"); break; case ELFDATANUM: printf("NUM ( unspecified )\n"); break; default: printf("Unknown \n"); break; } printf("Version\t\t "); switch(_elf_header->e_ident[EI_VERSION]) { case EV_NONE: printf("None\n"); break; case EV_CURRENT: printf("Current\n"); break; case EV_NUM: printf("NUM ( Unspecified )\n"); break; default: printf("Unknown \n"); break; } printf("OS ABI\t\t "); switch(_elf_header->e_ident[EI_OSABI]) { case ELFOSABI_NONE: printf("UNIX System V ABI\n"); break; // case ELFOSABI_SYSV: // printf("SYSV\n"); // break; // case ELFOSABI_HPUX: printf("HP-UX\n"); break; case ELFOSABI_NETBSD: printf("NetBSD\n"); break; case ELFOSABI_GNU: printf("GNU\n"); break; // case ELFOSABI_LINUX: // printf("Linux\n"); // break; // case ELFOSABI_SOLARIS: printf("Sun Solaris\n"); break; case ELFOSABI_AIX: printf("ABM AIX\n"); break; case ELFOSABI_FREEBSD: printf("FreeBSD\n"); break; case ELFOSABI_TRU64: printf("Compaq Tru64\n"); break; case ELFOSABI_MODESTO: printf("Novell Modesto\n"); break; case ELFOSABI_OPENBSD: printf("OpenBSD\n"); break; // case ELFOSABI_ARM_AEABI: // printf("ARM EABI\n"); // break; case ELFOSABI_ARM: printf("ARM\n"); break; case ELFOSABI_STANDALONE: printf("Standalone (embedded) application\n"); break; default: printf("Unknown \n"); break; } printf("File Type\t "); switch(_elf_header->e_type) { case ET_NONE: printf("None\n"); break; case ET_REL: printf("Relocatable file\n"); break; case ET_EXEC: printf("Executable file\n"); break; case ET_DYN: printf("Shared object file\n"); break; case ET_CORE: printf("Core file\n"); break; case ET_NUM: printf("Number of defined types\n"); break; case ET_LOOS: printf("OS-specific range start\n"); break; case ET_HIOS: printf("OS-specific range end\n"); break; case ET_LOPROC: printf("Processor-specific range start\n"); break; case ET_HIPROC: printf("Processor-specific range end\n"); break; default: printf("Unknown \n"); break; } printf("Machine\t\t "); switch(_elf_header->e_machine) { case EM_NONE: printf("None\n"); break; case EM_386: printf("INTEL x86\n"); break; case EM_X86_64: printf("AMD x86-64 architecture\n"); break; case EM_ARM: printf("ARM\n"); break; default: printf("Unknown\n"); break; } /* Entry point */ int entry=_elf_header->e_entry; printf("Entry point\t 0x%08x Step 3. and jump to e_entry\n", _elf_header->e_entry); /* ELF header size in bytes */ printf("ELF header size\t 0x%08x\n", _elf_header->e_ehsize); /* Program Header */ printf("Program Header\t 0x%08x (%d entries with a total of %d bytes)\n", _elf_header->e_phoff, _elf_header->e_phnum, _elf_header->e_phentsize ); // for static, obtain the following: everything in the structure Elf64_Phdr, then `, PT_LOAD, PT_DYNAMIC, then e_entry Elf64_Phdr *elf_program_header = (Elf64_Phdr *)((unsigned long)_elf_header + _elf_header->e_phoff); char * exe = ""; int lenexe = 0; int lentotal = 0; for (i = 0; i < _elf_header->e_phnum; ++i) { // printf("dl_iterate_phdr =\n"); // dl_iterate_phdr(callback, NULL); printf("p_type;\t\t\t/* Segment type */\t\t= "); switch(elf_program_header[i].p_type) { case PT_NULL: printf("PT_NULL\t\t/* Program header table entry unused */\n"); break; case PT_LOAD: printf("PT_LOAD\t\t/* Loadable program segment */ Step 2. then parse and process all PT_LOAD segments\n"); break; case PT_DYNAMIC: printf("PT_DYNAMIC\t\t/* Dynamic linking information */ Step 2.5 keep in mind that static-PIE binaries are dynamic ELF objects though, so to load those you need to parse the PT_DYNAMIC stuff\n"); break; case PT_INTERP: printf("PT_INTERP\t\t/* Program interpreter */\n"); break; case PT_NOTE: printf("PT_NOTE\t\t/* Auxiliary information */\n"); break; case PT_SHLIB: printf("PT_SHLIB\t\t/* Reserved */\n"); break; case PT_PHDR: printf("PT_PHDR\t\t/* Entry for header table itself */ Step 1. if the first entry is a PT_PHDR, use that as the program header table\n"); break; case PT_TLS: printf("PT_TLS\t\t/* Thread-local storage segment */\n"); break; case PT_NUM: printf("PT_NUM\t\t/* Number of defined types */\n"); break; case PT_LOOS: printf("PT_LOOS\t\t/* Start of OS-specific */\n"); break; case PT_GNU_EH_FRAME: printf("PT_GNU_EH_FRAME\t/* GCC .eh_frame_hdr segment */\n"); break; case PT_GNU_STACK: printf("PT_GNU_STACK\t\t/* Indicates stack executability */\n"); break; case PT_GNU_RELRO: printf("PT_GNU_RELRO\t\t/* Read-only after relocation */\n"); break; case PT_SUNWBSS: printf("PT_SUNWBSS\t\t/* Sun Specific segment */\n"); break; case PT_SUNWSTACK: printf("PT_SUNWSTACK\t\t/* Stack segment */\n"); break; case PT_HIOS: printf("PT_HIOS\t\t/* End of OS-specific */\n"); break; case PT_LOPROC: printf("PT_LOPROC\t\t/* Start of processor-specific */\n"); break; case PT_HIPROC: printf("PT_HIPROC\t\t/* End of processor-specific */\n"); break; default: printf("Unknown\n"); break; } // read_pload (dst address in memory, how many bytes to read, offset in the file) read_pload(ph->p_paddr, ph->p_memsz, ph->p_offset); char * tmp99; if (elf_program_header[i].p_type == PT_LOAD) { lentotal = lentotal + elf_program_header[i].p_memsz; exe = strjoin(exe, tmp99, lenexe, lentotal); // print_quoted_string(exe, lentotal, 0, "print"); printf("\n"); lenexe = lentotal; } else { printf("ATTEMPING TO READ\n"); read_(array, &tmp99, (elf_program_header[i].p_memsz + elf_program_header[i].p_offset)); lseek_string(&tmp99, elf_program_header[i].p_memsz, elf_program_header[i].p_offset); print_quoted_string(tmp99, elf_program_header[i].p_memsz, 0, "print"); printf("\nREAD\n"); } // could this [ // read_pload (dst address in memory, how many bytes to read, offset in the file) read_pload(ph->p_paddr, ph->p_memsz, ph->p_offset); ] be shortened to [ read_pload(mapped_file, ph->p_memsz, (ph->p_paddr + ph->p_offset); ] ? https://stackoverflow.com/a/29326748/8680581 printf("p_flags;\t\t/* Segment flags */\t\t= 0x%08x\np_offset;\t\t/* Segment file offset */\t= 0x%08x\np_vaddr;\t\t/* Segment virtual address */\t= 0x%08x\np_paddr;\t\t/* Segment physical address */\t= 0x%08x\np_filesz;\t\t/* Segment size in file */\t= 0x%08x\np_memsz;\t\t/* Segment size in memory */\t= 0x%08x\np_align;\t\t/* Segment alignment */\t\t= 0x%08x\n\n\n", elf_program_header[i].p_flags, elf_program_header[i].p_offset, elf_program_header[i].p_vaddr, elf_program_header[i].p_paddr, elf_program_header[i].p_filesz, elf_program_header[i].p_memsz, elf_program_header[i].p_align); printf("p_flags = 0x%08x, p_offset = 0x%08x, p_vaddr = 0x%08x, p_paddr = 0x%08x, p_filesz = 0x%08x, p_memsz = 0x%08x, p_align = 0x%08x\n\n\n", elf_program_header[i].p_flags, elf_program_header[i].p_offset, elf_program_header[i].p_vaddr, elf_program_header[i].p_paddr, elf_program_header[i].p_filesz, elf_program_header[i].p_memsz, elf_program_header[i].p_align); } // rest MAY be irrelivant for static executable execution // printf("Section Header\t \ _elf_header->e_shstrndx 0x%08x (\ _elf_header->e_shnum = %d entries with a total of \ _elf_header->e_shentsize = %d (should match %d) bytes, offset is \ _elf_header->e_shoff = 0x%08x)\n",\ _elf_header->e_shstrndx,\ _elf_header->e_shnum,\ _elf_header->e_shentsize,\ sizeof(Elf64_Shdr),\ _elf_header->e_shoff,\ (char *)array + _elf_header->e_shoff\ ); Elf64_Shdr *_symbol_table; // read section header table void read_section_header_table_(const char * arrayb, Elf64_Ehdr * eh, Elf64_Shdr * sh_table[]) { *sh_table = (Elf64_Shdr *)(arrayb + eh->e_shoff); if(!_symbol_table) { printf("Failed to read table\n"); } } char * read_section_(char * ar, Elf64_Shdr sh) { char * buff = (char *)(ar + sh.sh_offset); return buff ; } char * print_section_headers_(char * sourcePtr, Elf64_Ehdr * eh, Elf64_Shdr sh_table[]) { printf ("\n"); printf("eh->e_shstrndx = 0x%x\n", eh->e_shstrndx); char * sh_str; sh_str = read_section_(sourcePtr, sh_table[eh->e_shstrndx]); // will fail untill section header table can be read printf("\t========================================"); printf("========================================\n"); printf("\tidx offset load-addr size algn type flags section\n"); printf("\t========================================"); printf("========================================\n"); for(i=0; i<eh->e_shnum; i++) { // will fail untill section header table can be read printf("\t%03d ", i); printf("0x%08x ", _symbol_table[i].sh_offset); // p_offset printf("0x%08x ", _symbol_table[i].sh_addr); // p_paddr or p_vaddr printf("0x%08x ", _symbol_table[i].sh_size); // p_filesz or p_memsz printf("%4d ", _symbol_table[i].sh_addralign); // p_align // for some reason sh_flags ans sh_type are swiched around printf("0x%08x ", _symbol_table[i].sh_flags); // p_flags printf("0x%08x ", _symbol_table[i].sh_type); // Unknown printf("%s\t", (sh_str + sh_table[i].sh_name)); printf("\n"); } printf("\t========================================"); printf("========================================\n"); printf("\n"); } void print_symbol_table(char * arrayc, Elf64_Ehdr eh, Elf64_Shdr sh_table[], uint64_t symbol_table) { char *str_tbl; Elf64_Sym* sym_tbl; uint64_t i, symbol_count; sym_tbl = (Elf64_Sym*)read_section_(arrayc, sh_table[symbol_table]); /* Read linked string-table * Section containing the string table having names of * symbols of this section */ uint64_t str_tbl_ndx = sh_table[symbol_table].sh_link; printf("str_tbl_ndx = 0x%x\n", str_tbl_ndx); str_tbl = read_section_(arrayc, sh_table[str_tbl_ndx]); symbol_count = (sh_table[symbol_table].sh_size/sizeof(Elf64_Sym)); printf("%d symbols\n", symbol_count); for(i=0; i< symbol_count; i++) { printf("PART0 sym_tbl[i].st_value = 0x%08x\n", sym_tbl[i].st_value); printf("PART1 ELF64_ST_BIND(sym_tbl[%d].st_info) = 0x%02x\n", i, ELF64_ST_BIND(sym_tbl[i].st_info)); printf("PART2 ELF64_ST_TYPE(sym_tbl[%d].st_info) = 0x%02x\n", i, ELF64_ST_TYPE(sym_tbl[i].st_info)); printf("PART3 (str_tbl + sym_tbl[%d].st_name) = %s\n\n", i, (str_tbl + sym_tbl[i].st_name)); } } void print_symbols(char * arrayd, Elf64_Ehdr * eh, Elf64_Shdr sh_table[]) { for(i=0; i<eh->e_shnum; i++) { if ((sh_table[i].sh_type==SHT_SYMTAB) || (sh_table[i].sh_type==SHT_DYNSYM)) { printf("\n[Section %03d]", i); print_symbol_table(arrayd, *eh, sh_table, i); } } } // // ## dynamic // p_flags; /* Segment flags */ = 0x00000006 // p_offset; /* Segment file offset */ = 0x00003e20 // p_vaddr; /* Segment virtual address */ = 0x00603e20 // p_paddr; /* Segment physical address */ = 0x00603e20 // p_filesz; /* Segment size in file */ = 0x000001d0 // p_memsz; /* Segment size in memory */ = 0x000001d0 // p_align; /* Segment alignment */ = 0x00000008 // // 021 0x00003e20 0x00603e20 0x000001d0 8 0x00000006 0x00000003 .dynamic read_section_header_table_(array, _elf_header, &_symbol_table); print_section_headers_(array, _elf_header, _symbol_table); /* Symbol tables : * _symbol_table[i].sh_type * |`- SHT_SYMTAB * `- SHT_DYNSYM */ print_symbols(array, _elf_header, _symbol_table); // fd2 = open(pwd, O_RDWR|O_SYNC|O_CREAT); print_maps(); ulexec_array(array, NULL, "-l", env); return 1; } else { printf("ELFMAGIC mismatch!\n"); /* Not ELF file */ return 0; } printf("\n"); // OBJECT END exit(0); }
0.773438
low
Raven.CppClient/ServerOperationExecutor.h
mlawsonca/ravendb-cpp-client
3
6045665
<gh_stars>1-10 #pragma once #include "ClusterRequestExecutor.h" #include "DocumentStore.h" #include "IVoidServerOperation.h" #include "Operation.h" namespace ravendb::client::serverwide::operations { class ServerOperationExecutor { private: std::weak_ptr<ServerOperationExecutor> _weak_this; const std::shared_ptr<http::ClusterRequestExecutor> _request_executor; private: explicit ServerOperationExecutor(std::shared_ptr<documents::DocumentStore> store); public: ~ServerOperationExecutor(); static std::shared_ptr<ServerOperationExecutor> create(std::shared_ptr<documents::DocumentStore> store); void send(const IVoidServerOperation& operation); template<typename TResult> std::shared_ptr<TResult> send(const IServerOperation<TResult>& operation); std::unique_ptr<documents::operations::Operation> send_async(const IServerOperation<documents::operations::OperationIdResult>& operation); void close(); }; template <typename TResult> std::shared_ptr<TResult> ServerOperationExecutor::send(const IServerOperation<TResult>& operation) { auto command = operation.get_command(_request_executor->get_conventions()); _request_executor->execute(*command); return command->get_result(); } }
0.992188
high
Middlewares/ST/BlueNRG-MS/profiles/Peripheral/Inc/phone_alert_client.h
STMicroelectronics/fp-sns-flight1
0
7745201
/** ****************************************************************************** * @file phonealert_client.h * @author AMS - HEA&RF BU * @brief Header file for the phone alert client profile ****************************************************************************** * @attention * * Copyright (c) 2014 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ #ifndef _PHONE_ALERT_CLIENT_H_ #define _PHONE_ALERT_CLIENT_H_ /********************************************************************************** * Macros **********************************************************************************/ /* value definitions for ringer setting characteristic */ #define RINGER_SILENT (0x00) #define RINGER_NORMAL (0x01) /* value definitions for ringer control point characteristic */ #define SILENT_MODE (0x01) #define MUTE_ONCE (0x02) #define CANCEL_SILENT_MODE (0x03) /* value definitions for alert status characteristic * If the bits specified below are not set, it * implies that the corresponding state is not * active */ #define RINGER_STATE_ACTIVE (0x01) #define VIBRATOR_STATE_ACTIVE (0x02) #define DISPLAY_ALERT_ACTIVE (0x04) /* error codes for phone client */ #define PHONE_ALERT_SERVICE_NOT_FOUND (0x01) #define PHONE_ALERT_STATUS_CHARAC_NOT_FOUND (0x02) #define RINGER_CNTRL_POINT_CHARAC_NOT_FOUND (0x03) #define RINGER_SETTING_CHARAC_NOT_FOUND (0x04) #define PHONE_ALERT_STATUS_DESC_NOT_FOUND (0x05) #define RINGER_CNTRL_POINT_DESC_NOT_FOUND (0x06) #define RINGER_SETTING_DESC_NOT_FOUND (0x07) /********************************************************************************** * Function Prototypes **********************************************************************************/ /** * PAC_Init * * @param[in] FindMeTargetcb : callback function to be called * by the profile to notify the application of events * * Initializes the Phone Alert Status profile for client role */ tBleStatus PAC_Init(BLE_CALLBACK_FUNCTION_TYPE phoneAlertClientcb); /** * PAC_Add_Device_To_WhiteList * * @param[in] bdAddr : address of the peer device * that has to be added to the whitelist */ tBleStatus PAC_Add_Device_To_WhiteList(uint8_t* bdAddr); /** * PAC_Advertize * * This function puts the device into * discoverable mode if it is in the * proper state to do so */ tBleStatus PAC_Advertize(void); /** * PAC_Configure_Ringer * * @param[in] ringerMode : the ringer mode to be set\n * SILENT_MODE (0x01)\n * MUTE_ONCE (0x02)\n * CANCEL_SILENT_MODE (0x03) * * Starts a write without response GATT procedure * to write the ringer mode command to the phone alert server * * @return returns BLE_STATUS_SUCCESS if the parameters * are valid and the procedure has been started else * returns error codes */ tBleStatus PAC_Configure_Ringer(uint8_t ringerMode); /** * PAC_Read_AlertStatus * * When this function is called by the application, * the profile starts a gatt procedure to read the * characteristic value. The value read will be retuned * via the event to the application. * * @return returns BLE_STATUS_SUCCESS if the procedure * was started successfully */ tBleStatus PAC_Read_AlertStatus(void); /** * PAC_Read_RingerSetting * * When this function is called by the application, * the profile starts a gatt procedure to read the * characteristic value. The value read will be returned * via the event to the application. * * @return returns BLE_STATUS_SUCCESS if the procedure * was started successfully */ tBleStatus PAC_Read_RingerSetting(void); /** * PACProfile_StateMachine * * @param[in] None * * PAC profile's state machine: to be called on application main loop. */ tBleStatus PACProfile_StateMachine(void); /** * PAC_Disable_ALert_Status_Notification * * @param[in] None * * Disable the Alert Status Notification */ void PAC_Disable_ALert_Status_Notification(void); /** * PAC_Disable_Ringer_Status_Notification * * @param[in] None * * Disable the Ringer Status Notification */ void PAC_Disable_Ringer_Status_Notification(void); #endif /* _PHONE_ALERT_CLIENT_H_ */
0.996094
high
asmtests/generatedfiles/ssse3.h
helloguo/intrinsictests
1
7777969
// This file is generated from testsgenerator.py // The first loop runs the intrinsic for 1000000 * 5 times. Assume it takes time1 // The second loop runs the intrinsic for 1000000 * 105 times. Assume it takes time2 // The return value is the execution time for 1000000 * 100 times, which equals (time2 - time1) #include <time.h> #include <iostream> void __declspec(noinline) __cdecl run_palignr_xmm1xmm21_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 }; } void __declspec(noinline) __cdecl run_palignr_xmm1xmm21_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 palignr xmm1, xmm2, 1 }; } void test_palignr_xmm1xmm21() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_palignr_xmm1xmm21_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_palignr_xmm1xmm21_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "palignr takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_phaddd_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_phaddd_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 phaddd xmm1, xmm2 }; } void test_phaddd_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_phaddd_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_phaddd_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "phaddd takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_phaddw_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_phaddw_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 phaddw xmm1, xmm2 }; } void test_phaddw_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_phaddw_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_phaddw_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "phaddw takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_phaddsw_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_phaddsw_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 phaddsw xmm1, xmm2 }; } void test_phaddsw_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_phaddsw_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_phaddsw_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "phaddsw takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_phsubd_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_phsubd_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 phsubd xmm1, xmm2 }; } void test_phsubd_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_phsubd_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_phsubd_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "phsubd takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_phsubw_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_phsubw_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 phsubw xmm1, xmm2 }; } void test_phsubw_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_phsubw_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_phsubw_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "phsubw takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_phsubsw_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_phsubsw_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 phsubsw xmm1, xmm2 }; } void test_phsubsw_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_phsubsw_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_phsubsw_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "phsubsw takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_pmaddubsw_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_pmaddubsw_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 pmaddubsw xmm1, xmm2 }; } void test_pmaddubsw_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_pmaddubsw_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_pmaddubsw_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "pmaddubsw takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_pmulhrsw_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_pmulhrsw_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 pmulhrsw xmm1, xmm2 }; } void test_pmulhrsw_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_pmulhrsw_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_pmulhrsw_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "pmulhrsw takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_pshufb_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_pshufb_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 pshufb xmm1, xmm2 }; } void test_pshufb_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_pshufb_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_pshufb_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "pshufb takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_psignb_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_psignb_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 psignb xmm1, xmm2 }; } void test_psignb_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_psignb_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_psignb_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "psignb takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_psignd_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_psignd_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 psignd xmm1, xmm2 }; } void test_psignd_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_psignd_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_psignd_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "psignd takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_psignw_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_psignw_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 psignw xmm1, xmm2 }; } void test_psignw_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_psignw_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_psignw_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "psignw takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_pabsb_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_pabsb_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 pabsb xmm1, xmm2 }; } void test_pabsb_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_pabsb_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_pabsb_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "pabsb takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_pabsd_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_pabsd_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 pabsd xmm1, xmm2 }; } void test_pabsd_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_pabsd_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_pabsd_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "pabsd takes "<< clk << std::endl; } void __declspec(noinline) __cdecl run_pabsw_xmm1xmm2_5_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 }; } void __declspec(noinline) __cdecl run_pabsw_xmm1xmm2_105_times(int * addr) { __asm { mov eax, addr movdqu xmm0, XMMWORD PTR[eax] movdqu xmm1, xmm0 movdqu xmm2, xmm0 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 pabsw xmm1, xmm2 }; } void test_pabsw_xmm1xmm2() { int foo [4] = {10, 20, 30, 40}; clock_t t1 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_pabsw_xmm1xmm2_5_times(foo); } clock_t t2 = clock(); for (int iterator = 0; iterator < 1000000; iterator++) { run_pabsw_xmm1xmm2_105_times(foo); } clock_t t3 = clock(); clock_t clk = (t3 - t2) - (t2 - t1); std::cout << "pabsw takes "<< clk << std::endl; } void run_all_ssse3_tests() { test_palignr_xmm1xmm21(); test_phaddd_xmm1xmm2(); test_phaddw_xmm1xmm2(); test_phaddsw_xmm1xmm2(); test_phsubd_xmm1xmm2(); test_phsubw_xmm1xmm2(); test_phsubsw_xmm1xmm2(); test_pmaddubsw_xmm1xmm2(); test_pmulhrsw_xmm1xmm2(); test_pshufb_xmm1xmm2(); test_psignb_xmm1xmm2(); test_psignd_xmm1xmm2(); test_psignw_xmm1xmm2(); test_pabsb_xmm1xmm2(); test_pabsd_xmm1xmm2(); test_pabsw_xmm1xmm2(); }
0.800781
high
src/renderer/dx/ScreenPixelShader.h
tjrileywisc/terminal
34,359
1410737
<reponame>tjrileywisc/terminal #pragma once #if !TIL_FEATURE_DXENGINESHADERSUPPORT_ENABLED constexpr std::string_view retroPixelShaderString{ "" }; #else constexpr std::string_view retroPixelShaderString{ R"( // The original retro pixel shader Texture2D shaderTexture; SamplerState samplerState; cbuffer PixelShaderSettings { float Time; float Scale; float2 Resolution; float4 Background; }; #define SCANLINE_FACTOR 0.5 #define SCALED_SCANLINE_PERIOD Scale #define SCALED_GAUSSIAN_SIGMA (2.0*Scale) static const float M_PI = 3.14159265f; float Gaussian2D(float x, float y, float sigma) { return 1/(sigma*sqrt(2*M_PI)) * exp(-0.5*(x*x + y*y)/sigma/sigma); } float4 Blur(Texture2D input, float2 tex_coord, float sigma) { uint width, height; shaderTexture.GetDimensions(width, height); float texelWidth = 1.0f/width; float texelHeight = 1.0f/height; float4 color = { 0, 0, 0, 0 }; int sampleCount = 13; for (int x = 0; x < sampleCount; x++) { float2 samplePos = { 0, 0 }; samplePos.x = tex_coord.x + (x - sampleCount/2) * texelWidth; for (int y = 0; y < sampleCount; y++) { samplePos.y = tex_coord.y + (y - sampleCount/2) * texelHeight; if (samplePos.x <= 0 || samplePos.y <= 0 || samplePos.x >= width || samplePos.y >= height) continue; color += input.Sample(samplerState, samplePos) * Gaussian2D((x - sampleCount/2), (y - sampleCount/2), sigma); } } return color; } float SquareWave(float y) { return 1 - (floor(y / SCALED_SCANLINE_PERIOD) % 2) * SCANLINE_FACTOR; } float4 Scanline(float4 color, float4 pos) { float wave = SquareWave(pos.y); // TODO:GH#3929 make this configurable. // Remove the && false to draw scanlines everywhere. if (length(color.rgb) < 0.2 && false) { return color + wave*0.1; } else { return color * wave; } } float4 main(float4 pos : SV_POSITION, float2 tex : TEXCOORD) : SV_TARGET { Texture2D input = shaderTexture; // TODO:GH#3930 Make these configurable in some way. float4 color = input.Sample(samplerState, tex); color += Blur(input, tex, SCALED_GAUSSIAN_SIGMA)*0.3; color = Scanline(color, pos); return color; } )" }; #endif
0.996094
high
clither/include/clither/argv.h
TheComet93/clither
1
1443505
struct arg_obj_t { char run_game; char show_help; char is_server; }; struct arg_obj_t* argv_parse(int argc, char** argv); void argv_free(struct arg_obj_t* argv);
0.902344
high
Labyrint/labyball/Classes/Native/Mono_Security_Mono_Security_Protocol_Tls_ClientCon3677726556MethodDeclarations.h
mimietti/Labyball
0
1476273
<filename>Labyrint/labyball/Classes/Native/Mono_Security_Mono_Security_Protocol_Tls_ClientCon3677726556MethodDeclarations.h #pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include <assert.h> #include <exception> // Mono.Security.Protocol.Tls.ClientContext struct ClientContext_t3677726556; // Mono.Security.Protocol.Tls.SslClientStream struct SslClientStream_t1178954575; // System.String struct String_t; // System.Security.Cryptography.X509Certificates.X509CertificateCollection struct X509CertificateCollection_t2200082950; #include "codegen/il2cpp-codegen.h" #include "Mono_Security_Mono_Security_Protocol_Tls_SslClient1178954575.h" #include "Mono_Security_Mono_Security_Protocol_Tls_SecurityP4015394186.h" #include "mscorlib_System_String968488902.h" #include "System_System_Security_Cryptography_X509Certificat2200082950.h" // System.Void Mono.Security.Protocol.Tls.ClientContext::.ctor(Mono.Security.Protocol.Tls.SslClientStream,Mono.Security.Protocol.Tls.SecurityProtocolType,System.String,System.Security.Cryptography.X509Certificates.X509CertificateCollection) extern "C" void ClientContext__ctor_m483520879 (ClientContext_t3677726556 * __this, SslClientStream_t1178954575 * ___stream0, int32_t ___securityProtocolType1, String_t* ___targetHost2, X509CertificateCollection_t2200082950 * ___clientCertificates3, const MethodInfo* method) IL2CPP_METHOD_ATTR; // Mono.Security.Protocol.Tls.SslClientStream Mono.Security.Protocol.Tls.ClientContext::get_SslStream() extern "C" SslClientStream_t1178954575 * ClientContext_get_SslStream_m714880213 (ClientContext_t3677726556 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Int16 Mono.Security.Protocol.Tls.ClientContext::get_ClientHelloProtocol() extern "C" int16_t ClientContext_get_ClientHelloProtocol_m3083636780 (ClientContext_t3677726556 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void Mono.Security.Protocol.Tls.ClientContext::set_ClientHelloProtocol(System.Int16) extern "C" void ClientContext_set_ClientHelloProtocol_m31446181 (ClientContext_t3677726556 * __this, int16_t ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void Mono.Security.Protocol.Tls.ClientContext::Clear() extern "C" void ClientContext_Clear_m2709420165 (ClientContext_t3677726556 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
0.972656
high
aula1/2 - variaveis.c
Jefferson-Bueno-Da-Silva/aulas_praticas_fabio
0
1509041
<reponame>Jefferson-Bueno-Da-Silva/aulas_praticas_fabio #include <stdio.h> #include <stdlib.h> int main() { int x = 99, y = 10; //soma subtração //y = x + 10 - 2; //multiplicação //y = x * 2; //divisão //y = x / 2; //atribulador equivalente a y = y +2; //pode ser usado com outros operadores +, -, *, /. y += 2; printf("O valor é: %d\n", y); system("PAUSE"); return 0; }
0.609375
high
src/script_context.h
wjkemp/agamemnon
0
1541809
/* Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SCRIPT_CONTEXT_H #define SCRIPT_CONTEXT_H #include "memory_region.h" #include "variable.h" #include <map> class script_context { public: ~script_context(); void add_memory_region(memory_region* region); memory_region* get_memory_region(const std::string& name) const; void set_variable(const variable& variable); uint64_t resolve_value(const std::string& value) const; private: std::map<std::string, memory_region*> _memory_regions; std::map<std::string, variable> _variables; }; #endif
0.992188
high
RealFluid/src/Core/Physics/Models/Environment.h
cypherix93/cse328-project
0
1574577
#include "Velocity.h" extern float DT; extern float VISCOSITY; extern float ATM_PRESSURE; extern Velocity GRAVITY;
0.773438
high
webserver.c
superhit0/webcserver
0
3140785
<reponame>superhit0/webcserver #include <stdio.h> #include <time.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #define MAXLINE 256 #define MAXSIZE 512 void error(const char *msg) { perror(msg); exit(1); } loadpage(int newsd,char *page) { int fsize,i=0,c; char out_buf[MAXSIZE]; fsize = 0; FILE *fp; fp=fopen(page,"r"); while ((c = getc(fp)) != EOF) {fsize++;} write(newsd, "Content-length: ", 16); bzero(out_buf,MAXSIZE); sprintf(out_buf,"%d",fsize); write(newsd, out_buf, strlen(out_buf)); write(newsd, "\n\n", 2); printf("%d",fsize); fp = fopen(page,"r"); bzero(out_buf,MAXSIZE); while((c = getc(fp)) != EOF) { if(i==511) { out_buf[i]=c; write(newsd, out_buf, strlen(out_buf)); printf("%c",c); bzero(out_buf,MAXSIZE); i=-1; } else { out_buf[i]=c; printf("%c",c); } i++; } if(c==EOF&&i!=0) { write(newsd, out_buf, strlen(out_buf)); } fclose(fp); } /* CHILD PROCEDURE, WHICH ACTUALLY DOES THE FILE TRANSFER */ doftp(int newsd) { char fname[MAXLINE]; FILE *fp; bzero(fname,MAXLINE); strcpy(fname,"index.html"); /* IF SERVER CANT OPEN FILE THEN INFORM CLIENT OF THIS AND TERMINATE */ //printf("%s",fname); if((fp = fopen(fname,"r")) == NULL) /*cant open file*/ { write(newsd, "HTTP/1.1 404 NOT FOUND\n", 23); write(newsd, "Content-Type: application/x-php\n", 24); strcpy(fname,"404.php"); } else { write(newsd, "HTTP/1.1 200 OK\n", 16); write(newsd, "Content-Type: text/html\n", 24); } loadpage(newsd,fname); printf("server: FILE TRANSFER COMPLETE on socket %d\n",newsd); fclose(fp); close(newsd); } int main(int argc, char *argv[]) { time_t mytime; int pid; int sockfd, newsockfd, portno; socklen_t clilen; char buffer[256]; struct sockaddr_in serv_addr, cli_addr; int n; if (argc < 2) { fprintf(stderr,"ERROR, no port provided\n"); exit(1); } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); portno = atoi(argv[1]); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding"); listen(sockfd,5); clilen = sizeof(cli_addr); while(1){ newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept"); bzero(buffer,256); pid=fork(); if(pid==0){ n = read(newsockfd,buffer,255); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %s\n",buffer); /*bzero(buffer,256); strcpy(buffer,"Current Time: "); mytime = time(NULL); strcat(buffer,ctime(&mytime));*/ /*n = write(newsockfd,buffer ,strlen(buffer)); if (n < 0) error("ERROR writing to socket");*/ doftp(newsockfd); close(newsockfd); exit(0); } else { close(newsockfd); } } close(sockfd); return 0; }
0.871094
high
gldata.h
songtianyi/MotionPlayer
4
3173553
<filename>gldata.h /** * gldata.h * * Copyright (c) 2013, Dalian Nationalities University. All Rights Reserved. * <NAME> <<EMAIL>> * * You can use this file in your project, but do not redistribute it and/or modify * it. * */ #ifndef GLDATA_H #define GLDATA_H #include <string.h> #include <qstring.h> #include <qinputdialog.h> #include <qlineedit.h> /*this is my include directory, you can change it to yours*/ #include "I:\MotionCapture\project\lib\CordAnm.h" #include "I:\MotionCapture\project\lib\CASEParser.h" #include "I:\MotionCapture\project\lib\CBVHParser.h" #include "I:\MotionCapture\project\lib\GLPOS.h" #include "I:\MotionCapture\project\lib\CVector3f.h" #include "I:\MotionCapture\project\lib\TRCParser.h" #include "I:\MotionCapture\project\lib\def.h" class GLData { public: GLData(); ~GLData(); void process(const char *dir,QString suffix); void destroy(); void init(); public: bool valid;//it is valid when data are set int frameNum; int boneNum; int *parent_of; CVector3f *data; //play QString objectName; int curr;//curr_frame bool pause;//pause = true float root_offset[3];//root pos offset x y z }; #endif // GLDATA_H
0.898438
high
editor/echo/Editor/Modules/build/mac_build_settings.h
Texas-C/echo
675
4606321
<reponame>Texas-C/echo<gh_stars>100-1000 #pragma once #include "build_settings.h" namespace Echo { class MacBuildSettings : public BuildSettings { ECHO_SINGLETON_CLASS(MacBuildSettings, BuildSettings) public: MacBuildSettings(); virtual ~MacBuildSettings(); // instance static MacBuildSettings* instance(); // build virtual void build() override; // get name virtual const char* getPlatformName() const override { return "Mac"; } // platform thumbnail virtual ImagePtr getPlatformThumbnail() const override; // icon res path void setIconRes(const ResourcePath& path); const ResourcePath& getIconRes() { return m_iconRes; } // set output directory virtual void setOutputDir(const String& outputDir) override; // get final result path virtual String getFinalResultPath() override; // identifier void setIdentifier(const String& identifier) { m_identifier = identifier; } String getIdentifier() const; // version void setVersion(const String& version) { m_version = version; } const String& getVersion() const { return m_version; } // project name String getProjectName() const; // app name void setAppName(const String& appName) { m_appName = appName; } String getAppName() const; private: // output directory bool prepare(); // copy void copySrc(); void copyRes(); // replace void replaceIcon(); // write void writeModuleConfig(); void writeInfoPlist(); void writeCMakeList(); private: String m_rootDir; String m_projectDir; String m_outputDir; String m_solutionDir; String m_appName; ResourcePath m_iconRes = ResourcePath("Res://icon.png", ".png"); String m_identifier; String m_version = "1.0.0"; }; }
0.996094
high
src/Receiver/receptionDonnes.h
fblondiaux/LINGI1341-1er_projet
1
4639089
#include "../FormatSegments/packet_interface.h" #include <stdio.h> #include <netinet/in.h> /* * sockaddr_in6 */ #include <sys/types.h> /* Taille maximale de Window */ #define MAX_WINDOW_SIZE 31 typedef enum { INGNORE = 0, /* A ete ignore */ S_ACK, /* Necessite l'envoye d'un ack*/ S_NACK, /* Necessite l'envoye d'un nack */ } selectiveRepeat_status_code; struct buffer{ int seqnum; pkt_t* data; struct buffer* next; }; /* * Prends un pointeur vers une structure en argument et * insère la structure pkt au bon endroit * */ void insertStruct(struct buffer* str); /* * TraitementRecu recupere le buffer du socket, le decode, et réagit en conscéquence. * @buf: char* en provenance du socket * @taille : taille de buf * Post ACK contient, si il y en à un, le nack ou ack à renvoyer. * pré SizeACK = contient la taille de ACK. * Retourne si le segment est ignoré ou si il faut renvoyer un ack/nack */ selectiveRepeat_status_code traitementRecu(char* buf, int taille, char* ACK, size_t* SizeACK, const int file); void receptionDonnes( int sfd, int file);
0.980469
high
src/Broker.h
ayourtch/uTT
10
3005041
<gh_stars>1-10 #ifndef BROKER_H #define BROKER_H extern int REDIS; #include "uSockets/Berkeley.h" #include "uSockets/Epoll.h" #include <functional> #include <string_view> namespace uTT { class Passive; class Active; class Redis; class Connection : private uS::Berkeley<uS::Epoll>::Socket { private: void connect(std::string_view name); int sends = 0, corked = 0; Connection(uS::Berkeley<uS::Epoll> *context); public: using uS::Berkeley<uS::Epoll>::Socket::getUserData; void subscribe(std::string_view topic); void publish(std::string_view topic, std::string_view message); void close(); friend class Node; friend class Redis; friend class Passive; friend class Active; }; class Node : private uS::Berkeley<uS::Epoll> { private: uS::Epoll loop; std::function<void(Connection *)> connAckHandler; std::function<void(Connection *)> subAckHandler; std::function<void(Connection *, std::string_view, std::string_view)> publishHandler; public: Node(); void connect(std::string uri); void listen(); void run(); void close(); // these are all client-only void onConnected(std::function<void(Connection *)> callback); void onSubscribed(std::function<void(Connection *)> callback); void onMessage(std::function<void(Connection *, std::string_view topic, std::string_view message)> callback); friend class Connection; friend class Redis; friend class Passive; }; } #endif // BROKER_H
0.992188
high
YubiKit/YubiKit/Sessions/Shared/Requests/OATH/YKFKeyOATHListRequest.h
mattmaddux/yubikit-ios
2
3037809
<reponame>mattmaddux/yubikit-ios // Copyright 2018-2019 Yubico AB // // 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. #import <Foundation/Foundation.h> #import "YKFKeyOATHRequest.h" NS_ASSUME_NONNULL_BEGIN /*! @class YKFKeyOATHListRequest @abstract Request for listing all OATH credentials saved on the key. This request maps to the LIST command from YOATH protocol: https://developers.yubico.com/OATH/YKOATH_Protocol.html @note This request does not calculate the credentials. To calculate credentials use either Calculate or Calculate All requests. */ @interface YKFKeyOATHListRequest: YKFKeyOATHRequest @end NS_ASSUME_NONNULL_END
0.972656
high
base/include/material_manager.h
snowzurfer/vulkan-forward-plus
3
3070577
#ifndef VKS_MATERIALMANAGER #define VKS_MATERIALMANAGER #include <EASTL/string.h> #include <EASTL/hash_map.h> #include <EASTL/vector.h> #include <unordered_map> #include <material.h> #include <material_instance.h> namespace vks { class VulkanDevice; class VulkanBuffer; class MaterialManager { public: MaterialManager(); Material *CreateMaterial( const VulkanDevice &device, eastl::unique_ptr<MaterialBuilder> builder); void RegisterMaterialName(const eastl::string &name); MaterialInstance *CreateMaterialInstance( const VulkanDevice &device, const MaterialInstanceBuilder &builder); const MaterialInstance &GetMaterialInstance(const eastl::string &name) const; const MaterialInstance &GetMaterialInstance(uint32_t index) const; const Material *GetMaterial(const eastl::string &name) const; uint32_t GetMaterialInstancesCount() const; void GetMaterialConstantsBuffer(const VulkanDevice &device, VulkanBuffer &buffer) const; eastl::vector<MaterialConstants> GetMaterialConstants() const; void ReloadAllShaders(const VulkanDevice &device); /** * @brief Get all the descriptor infos of a given type of texture for all the * existing textures. * * @param texture_type Type of texture (eg. diffuse, specular, etc) * @param descs Vector where the descriptors are returned */ void GetDescriptorImageInfosByType( const MatTextureType texture_type, eastl::vector<VkDescriptorImageInfo> &descs); void Shutdown(const VulkanDevice &device); private: // List of all materials typedef eastl::hash_map<eastl::string, eastl::unique_ptr<Material>> NameMaterialMap; NameMaterialMap materials_map_; eastl::hash_map<eastl::string, bool> registered_names_; // List of all material instances typedef eastl::hash_map<eastl::string, MaterialInstance *> NameMaterialInstMap; NameMaterialInstMap material_instances_map_; eastl::vector<MaterialInstance> material_instances_; }; // class MaterialManager } // namespace vks #endif
0.996094
high
Archived/v1/WCDistractionFreeXcodePlugin/Headers/PlugIns/IDESceneKitEditor/SKEAnimationEditor.h
wokalski/Distraction-Free-Xcode-plugin
25
3103345
<filename>Archived/v1/WCDistractionFreeXcodePlugin/Headers/PlugIns/IDESceneKitEditor/SKEAnimationEditor.h // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" @interface SKEAnimationEditor : NSObject { } + (id)animationWithPresetName:(unsigned long long)arg1; + (struct CGPath *)createPiecewiseLinearCurveWithAnimation:(id)arg1; + (struct CGPath *)createCubicBezierCurveFromCatmullRomCurve:(id)arg1; + (id)catmullRomCurveFromCubicBezierCurveWithPoint0:(struct CGPoint)arg1 controlPoint0:(struct CGPoint)arg2 controlPoint1Pre:(struct CGPoint)arg3 point1:(struct CGPoint)arg4 controlPoint1Post:(struct CGPoint)arg5 controlPoint2:(struct CGPoint)arg6 point2:(struct CGPoint)arg7; + (id)catmullRomCurveFromCubicBezierCurveWithPoint0:(struct CGPoint)arg1 controlPoint0:(struct CGPoint)arg2 controlPoint1:(struct CGPoint)arg3 point1:(struct CGPoint)arg4; @end
0.597656
high
Krispy/src/Krispy.h
Dallin343/GameEngine
0
4669489
// // Created by dallin on 8/11/20. // #pragma once #pragma mark --Base-- #include "Krispy/Core/Base.h" #pragma mark -- --Debug #include "Krispy/Debug/Debuggable.h" #include "Krispy/Debug/Instrumentor.h" #pragma mark --Core-- #include "Krispy/Core/Application.h" #include "Krispy/Core/Layer.h" #include "Krispy/Core/Log.h" #include "Krispy/Core/Timestep.h" #include "Krispy/Core/Input.h" #pragma mark -- --Controllers #include "Krispy/Core/OrthographicCameraController.h" #pragma mark -- --Inputs #include "Krispy/Core/Input.h" #include "Krispy/Core/KeyCodes.h" #include "Krispy/Core/MouseCodes.h" #pragma mark --Events-- #include "Krispy/Events/KeyEvent.h" #include "Krispy/Events/MouseEvent.h" #include "Krispy/Events/ApplicationEvent.h" #pragma mark --ImGui-- #include "Krispy/ImGui/ImGuiLayer.h" #pragma mark --Renderer-- #include "Krispy/Renderer/Renderer.h" #include "Krispy/Renderer/Renderer2D.h" #include "Krispy/Renderer/RenderCommand.h" #include "Krispy/Renderer/Buffer.h" #include "Krispy/Renderer/Shader.h" #include "Krispy/Renderer/Texture.h" #include "Krispy/Renderer/VertexArray.h" #include "Krispy/Materials/Material.h" #pragma mark -- --Cameras #include "Krispy/Renderer/OrthographicCamera.h"
0.976563
high