code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/*************************************************************************** * * $Id: lexer.h 152 2010-10-10 14:17:37Z Michael.McTernan $ * * Extra lexer/scanner API functions. * Copyright (C) 2010 Michael C McTernan, Michael.McTernan.2001@cs.bris.ac.uk * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA ***************************************************************************/ #ifndef MSCGEN_LEXER_H #define MSCGEN_LEXER_H /***************************************************************************** * Header Files *****************************************************************************/ #include "mscgen_bool.h" /***************************************************************************** * Preprocessor Macros & Constants *****************************************************************************/ /***************************************************************************** * Typedefs *****************************************************************************/ /***************************************************************************** * Global Variable Declarations *****************************************************************************/ /***************************************************************************** * Global Function Declarations *****************************************************************************/ #ifdef __cplusplus extern "C" { #endif Boolean lex_getutf8(void); #ifdef __cplusplus } #endif unsigned long lex_getlinenum(void); char *lex_getline(void); void lex_destroy(void); void lex_resetparser(void); #endif /* MSCGEN_LEXER_H */ /* END OF FILE */
ellert/doxygen
libmscgen/mscgen_lexer.h
C
gpl-2.0
2,348
</form> <!-- /form-end --> </div><!-- /spyropress-panel -->
profiks/wordpress
wp-content/themes/vernum/framework/admin/panel/panel_end.php
PHP
gpl-2.0
67
/* * Low-Level PCI Access for i386 machines * * Copyright 1993, 1994 Drew Eckhardt * Visionary Computing * (Unix and Linux consulting and custom programming) * Drew@Colorado.EDU * +1 (303) 786-7975 * * Drew's work was sponsored by: * iX Multiuser Multitasking Magazine * Hannover, Germany * hm@ix.de * * Copyright 1997--2000 Martin Mares <mj@ucw.cz> * * For more information, please consult the following manuals (look at * http://www.pcisig.com/ for how to get them): * * PCI BIOS Specification * PCI Local Bus Specification * PCI to PCI Bridge Specification * PCI System Design Guide * * * CHANGELOG : * Jun 17, 1994 : Modified to accommodate the broken pre-PCI BIOS SPECIFICATION * Revision 2.0 present on <thys@dennis.ee.up.ac.za>'s ASUS mainboard. * * Jan 5, 1995 : Modified to probe PCI hardware at boot time by Frederic * Potter, potter@cao-vlsi.ibp.fr * * Jan 10, 1995 : Modified to store the information about configured pci * devices into a list, which can be accessed via /proc/pci by * Curtis Varner, cvarner@cs.ucr.edu * * Jan 12, 1995 : CPU-PCI bridge optimization support by Frederic Potter. * Alpha version. Intel & UMC chipset support only. * * Apr 16, 1995 : Source merge with the DEC Alpha PCI support. Most of the code * moved to drivers/pci/pci.c. * * Dec 7, 1996 : Added support for direct configuration access of boards * with Intel compatible access schemes (tsbogend@alpha.franken.de) * * Feb 3, 1997 : Set internal functions to static, save/restore flags * avoid dead locks reading broken PCI BIOS, werner@suse.de * * Apr 26, 1997 : Fixed case when there is BIOS32, but not PCI BIOS * (mj@atrey.karlin.mff.cuni.cz) * * May 7, 1997 : Added some missing cli()'s. [mj] * * Jun 20, 1997 : Corrected problems in "conf1" type accesses. * (paubert@iram.es) * * Aug 2, 1997 : Split to PCI BIOS handling and direct PCI access parts * and cleaned it up... Martin Mares <mj@atrey.karlin.mff.cuni.cz> * * Feb 6, 1998 : No longer using BIOS to find devices and device classes. [mj] * * May 1, 1998 : Support for peer host bridges. [mj] * * Jun 19, 1998 : Changed to use spinlocks, so that PCI configuration space * can be accessed from interrupts even on SMP systems. [mj] * * August 1998 : Better support for peer host bridges and more paranoid * checks for direct hardware access. Ugh, this file starts to look as * a large gallery of common hardware bug workarounds (watch the comments) * -- the PCI specs themselves are sane, but most implementors should be * hit hard with \hammer scaled \magstep5. [mj] * * Jan 23, 1999 : More improvements to peer host bridge logic. i450NX fixup. [mj] * * Feb 8, 1999 : Added UM8886BF I/O address fixup. [mj] * * August 1999 : New resource management and configuration access stuff. [mj] * * Sep 19, 1999 : Use PCI IRQ routing tables for detection of peer host bridges. * Based on ideas by Chris Frantz and David Hinds. [mj] * * Sep 28, 1999 : Handle unreported/unassigned IRQs. Thanks to Shuu Yamaguchi * for a lot of patience during testing. [mj] * * Oct 8, 1999 : Split to pci-i386.c, pci-pc.c and pci-visws.c. [mj] */ #include <linux/types.h> #include <linux/kernel.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/ioport.h> #include <linux/errno.h> #include "pci-i386.h" void pcibios_update_resource(struct pci_dev *dev, struct resource *root, struct resource *res, int resource) { u32 new, check; int reg; new = res->start | (res->flags & PCI_REGION_FLAG_MASK); if (resource < 6) { reg = PCI_BASE_ADDRESS_0 + 4*resource; } else if (resource == PCI_ROM_RESOURCE) { res->flags |= PCI_ROM_ADDRESS_ENABLE; new |= PCI_ROM_ADDRESS_ENABLE; reg = dev->rom_base_reg; } else { /* Somebody might have asked allocation of a non-standard resource */ return; } pci_write_config_dword(dev, reg, new); pci_read_config_dword(dev, reg, &check); if ((new ^ check) & ((new & PCI_BASE_ADDRESS_SPACE_IO) ? PCI_BASE_ADDRESS_IO_MASK : PCI_BASE_ADDRESS_MEM_MASK)) { printk(KERN_ERR "PCI: Error while updating region " "%s/%d (%08x != %08x)\n", dev->slot_name, resource, new, check); } } /* * We need to avoid collisions with `mirrored' VGA ports * and other strange ISA hardware, so we always want the * addresses to be allocated in the 0x000-0x0ff region * modulo 0x400. * * Why? Because some silly external IO cards only decode * the low 10 bits of the IO address. The 0x00-0xff region * is reserved for motherboard devices that decode all 16 * bits, so it's ok to allocate at, say, 0x2800-0x28ff, * but we want to try to avoid allocating at 0x2900-0x2bff * which might have be mirrored at 0x0100-0x03ff.. */ void pcibios_align_resource(void *data, struct resource *res, unsigned long size) { if (res->flags & IORESOURCE_IO) { unsigned long start = res->start; if (start & 0x300) { start = (start + 0x3ff) & ~0x3ff; res->start = start; } } } /* * Handle resources of PCI devices. If the world were perfect, we could * just allocate all the resource regions and do nothing more. It isn't. * On the other hand, we cannot just re-allocate all devices, as it would * require us to know lots of host bridge internals. So we attempt to * keep as much of the original configuration as possible, but tweak it * when it's found to be wrong. * * Known BIOS problems we have to work around: * - I/O or memory regions not configured * - regions configured, but not enabled in the command register * - bogus I/O addresses above 64K used * - expansion ROMs left enabled (this may sound harmless, but given * the fact the PCI specs explicitly allow address decoders to be * shared between expansion ROMs and other resource regions, it's * at least dangerous) * * Our solution: * (1) Allocate resources for all buses behind PCI-to-PCI bridges. * This gives us fixed barriers on where we can allocate. * (2) Allocate resources for all enabled devices. If there is * a collision, just mark the resource as unallocated. Also * disable expansion ROMs during this step. * (3) Try to allocate resources for disabled devices. If the * resources were assigned correctly, everything goes well, * if they weren't, they won't disturb allocation of other * resources. * (4) Assign new addresses to resources which were either * not configured at all or misconfigured. If explicitly * requested by the user, configure expansion ROM address * as well. */ static void __init pcibios_allocate_bus_resources(struct list_head *bus_list) { struct list_head *ln; struct pci_bus *bus; struct pci_dev *dev; int idx; struct resource *r, *pr; /* Depth-First Search on bus tree */ for (ln=bus_list->next; ln != bus_list; ln=ln->next) { bus = pci_bus_b(ln); if ((dev = bus->self)) { for (idx = PCI_BRIDGE_RESOURCES; idx < PCI_NUM_RESOURCES; idx++) { r = &dev->resource[idx]; if (!r->start) continue; pr = pci_find_parent_resource(dev, r); if (!pr || request_resource(pr, r) < 0) printk(KERN_ERR "PCI: Cannot allocate resource region %d of bridge %s\n", idx, dev->slot_name); } } pcibios_allocate_bus_resources(&bus->children); } } static void __init pcibios_allocate_resources(int pass) { struct pci_dev *dev; int idx, disabled; u16 command; struct resource *r, *pr; pci_for_each_dev(dev) { pci_read_config_word(dev, PCI_COMMAND, &command); for(idx = 0; idx < 6; idx++) { r = &dev->resource[idx]; if (r->parent) /* Already allocated */ continue; if (!r->start) /* Address not assigned at all */ continue; if (r->flags & IORESOURCE_IO) disabled = !(command & PCI_COMMAND_IO); else disabled = !(command & PCI_COMMAND_MEMORY); if (pass == disabled) { DBG("PCI: Resource %08lx-%08lx (f=%lx, d=%d, p=%d)\n", r->start, r->end, r->flags, disabled, pass); pr = pci_find_parent_resource(dev, r); if (!pr || request_resource(pr, r) < 0) { printk(KERN_ERR "PCI: Cannot allocate resource region %d of device %s\n", idx, dev->slot_name); /* We'll assign a new address later */ r->end -= r->start; r->start = 0; } } } if (!pass) { r = &dev->resource[PCI_ROM_RESOURCE]; if (r->flags & PCI_ROM_ADDRESS_ENABLE) { /* Turn the ROM off, leave the resource region, but keep it unregistered. */ u32 reg; DBG("PCI: Switching off ROM of %s\n", dev->slot_name); r->flags &= ~PCI_ROM_ADDRESS_ENABLE; pci_read_config_dword(dev, dev->rom_base_reg, &reg); pci_write_config_dword(dev, dev->rom_base_reg, reg & ~PCI_ROM_ADDRESS_ENABLE); } } } } static void __init pcibios_assign_resources(void) { struct pci_dev *dev; int idx; struct resource *r; pci_for_each_dev(dev) { int class = dev->class >> 8; /* Don't touch classless devices and host bridges */ if (!class || class == PCI_CLASS_BRIDGE_HOST) continue; for(idx=0; idx<6; idx++) { r = &dev->resource[idx]; /* * Don't touch IDE controllers and I/O ports of video cards! */ if ((class == PCI_CLASS_STORAGE_IDE && idx < 4) || (class == PCI_CLASS_DISPLAY_VGA && (r->flags & IORESOURCE_IO))) continue; /* * We shall assign a new address to this resource, either because * the BIOS forgot to do so or because we have decided the old * address was unusable for some reason. */ if (!r->start && r->end) pci_assign_resource(dev, idx); } if (pci_probe & PCI_ASSIGN_ROMS) { r = &dev->resource[PCI_ROM_RESOURCE]; r->end -= r->start; r->start = 0; if (r->end) pci_assign_resource(dev, PCI_ROM_RESOURCE); } } } void __init pcibios_resource_survey(void) { DBG("PCI: Allocating resources\n"); pcibios_allocate_bus_resources(&pci_root_buses); pcibios_allocate_resources(0); pcibios_allocate_resources(1); pcibios_assign_resources(); } int pcibios_enable_resources(struct pci_dev *dev) { u16 cmd, old_cmd; int idx; struct resource *r; pci_read_config_word(dev, PCI_COMMAND, &cmd); old_cmd = cmd; for(idx=0; idx<6; idx++) { r = &dev->resource[idx]; if (!r->start && r->end) { printk(KERN_ERR "PCI: Device %s not available because of resource collisions\n", dev->slot_name); return -EINVAL; } if (r->flags & IORESOURCE_IO) cmd |= PCI_COMMAND_IO; if (r->flags & IORESOURCE_MEM) cmd |= PCI_COMMAND_MEMORY; } if (dev->resource[PCI_ROM_RESOURCE].start) cmd |= PCI_COMMAND_MEMORY; if (cmd != old_cmd) { printk("PCI: Enabling device %s (%04x -> %04x)\n", dev->slot_name, old_cmd, cmd); pci_write_config_word(dev, PCI_COMMAND, cmd); } return 0; } /* * If we set up a device for bus mastering, we need to check the latency * timer as certain crappy BIOSes forget to set it properly. */ unsigned int pcibios_max_latency = 255; void pcibios_set_master(struct pci_dev *dev) { u8 lat; pci_read_config_byte(dev, PCI_LATENCY_TIMER, &lat); if (lat < 16) lat = (64 <= pcibios_max_latency) ? 64 : pcibios_max_latency; else if (lat > pcibios_max_latency) lat = pcibios_max_latency; else return; printk("PCI: Setting latency timer of device %s to %d\n", dev->slot_name, lat); pci_write_config_byte(dev, PCI_LATENCY_TIMER, lat); } int pci_mmap_page_range(struct pci_dev *dev, struct vm_area_struct *vma, enum pci_mmap_state mmap_state, int write_combine) { unsigned long prot; /* I/O space cannot be accessed via normal processor loads and * stores on this platform. */ if (mmap_state == pci_mmap_io) return -EINVAL; /* Leave vm_pgoff as-is, the PCI space address is the physical * address on this platform. */ vma->vm_flags |= (VM_SHM | VM_LOCKED | VM_IO); prot = pgprot_val(vma->vm_page_prot); if (boot_cpu_data.x86 > 3) prot |= _PAGE_PCD | _PAGE_PWT; vma->vm_page_prot = __pgprot(prot); /* Write-combine setting is ignored, it is changed via the mtrr * interfaces on this platform. */ if (remap_page_range(vma->vm_start, vma->vm_pgoff << PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot)) return -EAGAIN; return 0; }
alexbousso/kernel_2.4.18-14
arch/i386/kernel/pci-i386.c
C
gpl-2.0
12,154
<? /************************************************************************************************************************/ /*********************************** INICIO DE LA PAGINA E INICIO DE SESION ******************************************/ /************************************************************************************************************************/ session_start(); if((!array_key_exists("ls_database",$_SESSION))||(!array_key_exists("ls_hostname",$_SESSION))||(!array_key_exists("ls_gestor",$_SESSION))||(!array_key_exists("ls_login",$_SESSION))) { print "<script language=JavaScript>"; print "opener.location.href='../sigesp_conexion.php';"; print "close();"; print "</script>"; } $la_datemp=$_SESSION["la_empresa"]; ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Edici&oacute;n de Factura</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script type="text/javascript" language="JavaScript1.2" src="js/number_format.js"></script> <link href="../shared/css/cabecera.css" rel="stylesheet" type="text/css"> <link href="../shared/css/tablas.css" rel="stylesheet" type="text/css"> <link href="../shared/css/general.css" rel="stylesheet" type="text/css"> <link href="../shared/css/ventanas.css" rel="stylesheet" type="text/css"> <link href="../shared/js/css_intra/datepickercontrol.css" rel="stylesheet" type="text/css"> <!-- para icono de fecha --> <script type="text/javascript" language="JavaScript1.2" src="js/stm31.js"></script> <script type="text/javascript" language="JavaScript1.2" src="../shared/js/disabled_keys.js"></script> <script language="javascript"> if(document.all) { //ie document.onkeydown = function(){ if(window.event && (window.event.keyCode == 122 || window.event.keyCode == 116 || window.event.ctrlKey)) { window.event.keyCode = 505; } if(window.event.keyCode == 505){ return false;} } } </script> <script type="text/javascript" language="JavaScript1.2" src="js/validaciones.js"></script> <style type="text/css"> <!-- a:link { color: #006699; } a:visited { color: #006699; } a:hover { color: #006699; } a:active { color: #006699#006699; } .style6 {color: #000000} --> </style></head> <body> <form name="form1" method="post" action=""> <input type="hidden" name="campo" id="campo" value="<? print $ls_campo;?>" > <input type="hidden" name="orden" id="orden" value="<? print $ls_orden;?>"> <? /************************************************************************************************************************/ /******************************** LIBRERIAS *************************************************************************/ /************************************************************************************************************************/ require_once("../shared/class_folder/sigesp_include.php"); require_once("../shared/class_folder/class_mensajes.php"); require_once("../shared/class_folder/class_sql.php"); require_once("../shared/class_folder/class_funciones.php"); require_once("class_folder/sigesp_sfc_class_utilidades.php"); require_once("../shared/class_folder/class_datastore.php"); require_once("class_folder/sigesp_sfc_c_secuencia.php"); $io_datastore= new class_datastore(); $io_utilidad = new sigesp_sfc_class_utilidades(); $io_include=new sigesp_include(); $io_connect=$io_include->uf_conectar(); $io_msg=new class_mensajes(); $io_sql=new class_sql($io_connect); $io_data=new class_datastore(); $io_funcion=new class_funciones(); $ls_codemp=$la_datemp["codemp"]; $io_secuencia=new sigesp_sfc_c_secuencia(); $ls_sercon=$_SESSION["ls_sercon"]; $ls_nroconaux=$_GET["ls_nrocontrol"]; //$ls_nrocontrolaux=$io_funcion->uf_cerosizquierda($ls_nroconaux,16); //print $ls_nroconaux; $ls_nrofacturaaux=$_GET["ls_nrofactura"]; /**************************************************************************************************************************/ /************************** SUBMIT ***********************************************************************************/ /**************************************************************************************************************************/ if(array_key_exists("operacion",$_POST)) { $ls_operacion=$_POST["operacion"]; $ls_numfac=$_POST["numfac"]; $ls_nrofactura=$_POST["numfac"]; //print $ls_nrofactura; $ls_correlativo=$_POST["correlativo"]; $ls_nrocon=$_POS["nrocontrol"]; $ls_correlativocon=$_POST["correlativocon"]; //print $ls_correlativocon; $lb_valido=$_POST["validofac"]; $lb_valido2=$_POST["validocon"]; } /************************************************************************************************************************/ /*************************** NO SUBMIT ********************************************************************************/ /************************************************************************************************************************/ else { $ls_operacion=""; $ls_numfac=""; $ls_nrofactura=$_GET["ls_nrofactura"]; $ls_correlativo=''; $ls_nrocon=$_GET["ls_nrocontrol"]; $ls_correlativocon=''; $lb_valido=""; $lb_valido2=""; } /************************************************************************************************************************/ /*************************** TABLA DREAMWEAVER ************************************************************************/ /************************************************************************************************************************/ ?> <p align="center"> <input name="operacion" type="hidden" id="operacion" value="<? print $ls_operacion?>"> </p> <table width="500" border="0" align="center" cellpadding="1" cellspacing="1"> <tr> <td width="496" colspan="2" class="titulo-celda">Cat&aacute;logo de Devolucion </td> </tr> </table> <br> <table width="804" border="0" cellpadding="0" cellspacing="0" class="formato-blanco" align="center"> <td>&nbsp;</td> <td>&nbsp;</td> <tr> <td width="56"><div align="right">Nro. Control </div></td> <td width="598"><input name="numcontrol" type="text" style="font-size:36px; background-color:#FF0000" id="numcontrol" size="30" maxlength="35" value="<? print $ls_nrocon ?>" readonly></td> </tr> <tr> <td> <br> <br> </td> </tr> <tr> <td width="56"><div align="right">Nuevo Numero Control</div></td> <td width="598"><input name="correlativocon" type="text" style="font-size:36px; background-color:#FF0000" id="correlativocon" size="15" maxlength="25" value="<? print $ls_correlativocon ?>" onKeyPress=return(currencyFormat(this,'.',',',event))> <a href="javascript:ue_validarnrocontrol('<?php print $ls_correlativocon ?>');"><img src="../shared/imagebank/tools15/aprobado.gif" alt="Validar" width="15" height="15" border="0">Verfificar Nro. Control </a></td> </tr> <tr> <td> <br> <br> </td> </tr> <tr> <td width="56"><div align="right">Nro. Devolucion </div></td> <td width="598"><input name="numfac" type="text" style="font-size:36px; background-color:#FF0000" id="numfac" size="30" maxlength="25" value="<? print $ls_nrofactura ?>" readonly></td> </tr> <tr> <td> <br> <br> </td> </tr> <tr> <td> <br> </td> </tr> <tr> <td width="56"><div align="right">Nuevo Numero Devolucion</div></td> <td width="598"><input name="correlativo" type="text" style="font-size:36px; background-color:#FF0000" id="correlativo" size="15" maxlength="25" value="<? print $ls_correlativo ?>"> <a href="javascript:ue_validarnro('<?php print $ls_correlativo ?>');"><img src="../shared/imagebank/tools15/aprobado.gif" alt="Validar" width="15" height="15" border="0">Verfificar Nro. Factura </a></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td width="63"><a href="javascript:ue_aceptar();"><img src="../shared/imagebank/tools15/aprobado.gif" width="15" height="15" border="0" >Aceptar</a></td> <td width="85"><a href="javascript:ue_cancelar('<?php print $ls_nrofactura ?>');"><img src="../shared/imagebank/tools15/eliminar.gif" width="15" height="15" border="0">Cancelar</a></td> </tr> </table> <br> <?php if($ls_operacion=="BUSCAR") { $ls_codusu=$_SESSION["la_logusr"]; $ls_codcaj=$_SESSION["ls_codcaj"]; // $ls_prefijo=$_SESSION["ls_prefac"]; $ls_serie=$_SESSION["ls_serfac"]; $ls_nrocon=$_POST["numcontrol"]; $ls_prefijo=$_SESSION["ls_predev"];; // var_dump($_SESSION); //$io_secuencia->uf_obtener_secuencia($ls_codcaj."fac",&$ls_secuencia); //print $ls_correlativo; if ($ls_correlativo<>'') { $ls_correlativoaux=$io_funcion->uf_cerosizquierda($ls_correlativo,16); $ls_nrofactura=$io_secuencia->uf_crear_codigo($ls_prefijo,$ls_serie,$ls_correlativoaux); // print $ls_nrofactura; } ?> <script> numfac='<?php print $ls_nrofactura;?>'; //alert (numfac); document.form1.numfac.value=numfac; numcontrol='<?php print $ls_nrocon;?>'; //alert (numcontrol); document.form1.numcontrol.value=numcontrol; </script> <?php $ls_cadena=" SELECT coddev FROM sfc_devolucion WHERE coddev='".$ls_nrofactura."' "; // print $ls_cadena; $lb_valido=false; $rs_datauni=$io_sql->select($ls_cadena); if($rs_datauni==false&&($io_sql->message!="")) { //$io_msg->message("Nro. Valido"); $lb_valido=false; } else { if($row=$io_sql->fetch_row($rs_datauni)) { $lb_valido=false; $io_msg->message("Nro. devolucion existente, verifique Nro."); } else { $lb_valido=true; $io_msg->message("Nro. devolucion valido"); } } ?> <input name="validofac" type="hidden" id="validofac" value="<? print $lb_valido?>"> <?php } elseif($ls_operacion=="BUSCARCONTROL") { $ls_nrocon=$_POST["numcontrol"]; //var_dump($_POST); //print $ls_operacion.$ls_nrocon; $ls_seriecon=$_SESSION["ls_sercon"]; //$io_secuencia->uf_obtener_secuencia($ls_codcaj."fac",&$ls_secuencia); if ($ls_correlativocon<>'') { //print $ls_correlativocon; $ls_correlativoconaux=$io_funcion->uf_cerosizquierda($ls_correlativocon,16); $ls_nrocon=$io_secuencia->uf_crear_codigo("",$ls_seriecon,$ls_correlativoconaux); //print $ls_nrocon; } //print $ls_nrocon; ?> <script> numcontrol='<?php print $ls_nrocon;?>'; //alert (numcontrol); document.form1.numcontrol.value=numcontrol; </script> <?php $ls_nroconntrolaux=$_SESSION["ls_sercon"]."-".$ls_nrocon; $ls_cadena=" SELECT numcon FROM sfc_devolucion WHERE numcon= '".$ls_nroconntrolaux."' "; //print $ls_cadena; $lb_valido2=false; $rs_datauni=$io_sql->select($ls_cadena); if($rs_datauni==false&&($io_sql->message!="")) { //$io_msg->message("Nro. Valido"); $lb_valido2=false; } else { if($row=$io_sql->fetch_row($rs_datauni)) { $lb_valido2=false; $io_msg->message("Nro. Control existe, verifique Nro."); } else { $lb_valido2=true; $io_msg->message("Nro. Control valido"); } } ?> <input name="validocon" type="hidden" id="validocon" value="<? print $lb_valido2?>"> <?php } ?> </div> </form> <p>&nbsp;</p> <p>&nbsp;</p> </body> <script language="JavaScript"> /**********************************************************************************************************/ /********************************************* RUTINAS JAVASCRIPT *****************************************/ /**********************************************************************************************************/ function ue_cancelar(numfac) { //opener.ue_cargarnrofactura(numfac); close(); } function ue_aceptar() { f=document.form1; nro_valido='<? print $lb_valido; ?>'; controlvalido='<? print $lb_valido2; ?>'; // alert(nro_valido); // alert(controlvalido); numfac='<? print $ls_nrofactura; ?>'; correlativo='<? print $ls_correlativo; ?>'; numcontrol='<? print $ls_nrocon; ?>'; correlativocon='<? print $ls_correlativocon; ?>'; if (nro_valido==1 && controlvalido==1) { //alert (numfac); //alert(nro_valido==true && controlvalido==true); if(confirm("�Est� seguro de que ese es el correlativo que corresponde a la Devolucion es? "+numfac+" Y Numero de Control: "+numcontrol)) { //alert ('paso'); valido=true; valido2=true; opener.document.getElementById('txtcoddev').value=numfac; opener.document.getElementById('txtnumcont').value=numcontrol; close(); } else { valido=false; valido2=false; } } else { if (nro_valido=="") { alert ('Debe colocar un Nro. de Devolucion Valido'); f.numfac.value='<? print $_GET["ls_nrofactura"] ?>'; f.action="sigesp_cat_editar.php"; f.submit(); } if (controlvalido=="") { alert ('Debe colocar un Nro. de Control Valido'); f.numcontrol.value='<? print $_GET["ls_nrocon"] ?>'; f.action="sigesp_cat_editar.php"; f.submit(); } } } function ue_validarnro() { f=document.form1; f.operacion.value="BUSCAR"; f.action="sigesp_cat_editar.php"; f.submit(); } function ue_validarnrocontrol() { f=document.form1; // alert(f.numcontrol.value); f.operacion.value="BUSCARCONTROL"; f.action="sigesp_cat_editar.php"; f.submit(); } function currencyFormat(fld, milSep, decSep, e) { milSep=""; decSep=""; var sep = 0; var key = ''; var i = j = 0; var len = len2 = 0; var strCheck = '0123456789'; var aux = aux2 = ''; var whichCode = (window.Event) ? e.which : e.keyCode; if (whichCode == 13) return true; // Enter if (whichCode == 8) return true; // Backspace <- if (whichCode == 127) return true; // Suprimir -Del key = String.fromCharCode(whichCode); // Get key value from key code if (strCheck.indexOf(key) == -1) return false; // Not a valid key len = fld.value.length; for(i = 0; i < len; i++) if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break; aux = ''; for(; i < len; i++) if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i); aux += key; len = aux.length; if (len == 0) fld.value = ''; if (len == 1) fld.value = '0'+ decSep + '0' + aux; if (len == 2) fld.value = '0'+ decSep + aux; if (len > 2) { aux2 = ''; for (j = 0, i = len - 3; i >= 0; i--) { if (j == 3) { aux2 += milSep; j = 0; } aux2 += aux.charAt(i); j++; } fld.value = ''; len2 = aux2.length; for (i = len2 - 1; i >= 0; i--) fld.value += aux2.charAt(i); fld.value += decSep + aux.substr(len - 2, len); } return false; } </script> <script language="javascript" src="../shared/js/js_intra/datepickercontrol.js"></script> </html>
omerta/huayra
sfc/sigesp_cat_editar.php
PHP
gpl-2.0
15,315
#!/bin/sh # Copyright (c) 2003, Intel Corporation. All rights reserved. # Created by: salwan.searty REMOVE-THIS AT intel DOT com # This file is licensed under the GPL license. For the full content # of this license, see the COPYING file at the top level of this # source tree. # # Test various methods of adding invalid signals to sigrelse(). # conformance/interfaces/sigrelse/3-core-buildonly.test 1
ycui1984/posixtestsuite
posixtestsuite/conformance/interfaces/sigrelse/3-1.sh
Shell
gpl-2.0
408
/* * $Id: unix.h,v 1.23 2010-04-12 14:28:47 franklahm Exp $ */ #ifndef AFPD_UNIX_H #define AFPD_UNIX_H #ifdef HAVE_SYS_CDEFS_H #include <sys/cdefs.h> #endif /* HAVE_SYS_CDEFS_H */ #include <netatalk/endian.h> #include "config.h" #include "volume.h" #if defined( sun ) && !defined( __svr4__ ) #ifdef i386 typedef int mode_t; #endif /*i386*/ #endif /*sun __svr4__*/ #if defined(HAVE_SYS_VFS_H) || defined( sun ) || defined( ibm032 ) #include <sys/vfs.h> #endif /* HAVE_SYS_VFS_H || sun || ibm032 */ #if defined(_IBMR2) || defined(HAVE_STATFS_H) #include <sys/statfs.h> /* this might not be right. */ #define f_mntfromname f_fname #endif /* _IBMR2 || HAVE_STATFS_H */ #if defined(TRU64) #define f_frsize f_fsize #else /* TRU64 */ /* temp fix, was: defined(HAVE_SYS_STATVFS) || defined(__svr4__) */ #if defined(__svr4__) || (defined(__NetBSD__) && (__NetBSD_Version__ >= 200040000)) #include <sys/statvfs.h> #define statfs statvfs #else /* HAVE_SYS_STATVFS || __svr4__ */ #define f_frsize f_bsize #endif /* USE_STATVFS_H */ #endif /* TRU64 */ #if defined(__svr4__) || defined(HAVE_SYS_MNTTAB_H) #include <sys/mnttab.h> #endif /* __svr4__ || HAVE_SYS_MNTTAB_H */ #if defined(__DragonFly__) #define dqblk ufs_dqblk #endif #if defined(HAVE_SYS_MOUNT_H) || defined(BSD4_4) || \ defined(linux) || defined(ultrix) #include <sys/mount.h> #endif /* HAVE_SYS_MOUNT_H || BSD4_4 || linux || ultrix */ #if defined(linux) || defined(HAVE_MNTENT_H) #include <mntent.h> #endif /* linux || HAVE_MNTENT_H */ #ifndef NO_QUOTA_SUPPORT #if !(defined(__svr4__) || defined(HAVE_DQB_BTIMELIMIT)) #define dqb_btimelimit dqb_btime #endif /* ! __svr4__ || HAVE_DQB_BTIMELIMIT */ #if defined(linux) || defined(ultrix) || defined(HAVE_QUOTA_H) #ifndef NEED_QUOTACTL_WRAPPER /*#include <sys/quota.h>*/ /*long quotactl (int, const char *, unsigned int, caddr_t); */ /* extern long quotactl (int, const char *, long, caddr_t); */ #else /* ! NEED_QUOTACTL_WRAPPER */ #include <asm/types.h> #include <asm/unistd.h> #include <linux/quota.h> #endif /* ! NEED_QUOTACTL_WRAPPER */ #endif /* linux || ultrix || HAVE_QUOTA_H */ #ifdef __svr4__ #include <sys/fs/ufs_quota.h> #endif /* __svr4__ */ #ifdef BSD4_4 #include <ufs/ufs/quota.h> #endif /* BSD4_4 */ #ifdef HAVE_UFS_QUOTA_H #include <ufs/quota.h> #endif /* HAVE_UFS_QUOTA_H */ #ifdef _IBMR2 #include <jfs/quota.h> #endif /* _IBMR2 */ #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include "directory.h" #if defined (linux) #define MAXQUOTAS 2 /* definitions from sys/quota.h */ #define USRQUOTA 0 /* element used for user quotas */ #define GRPQUOTA 1 /* element used for group quotas */ /* * Command definitions for the 'quotactl' system call. * The commands are broken into a main command defined below * and a subcommand that is used to convey the type of * quota that is being manipulated (see above). */ #define SUBCMDMASK 0x00ff #define SUBCMDSHIFT 8 #define QCMD(cmd, type) (((cmd) << SUBCMDSHIFT) | ((type) & SUBCMDMASK)) /* declare an internal version of the quota block struct */ typedef u_int64_t qsize_t; /* Type in which we store size limitations */ typedef u_int32_t qid_t; /* Type in which we store ids in memory */ struct dqblk { qsize_t bsize; qsize_t dqb_ihardlimit; /* absolute limit on allocated inodes */ qsize_t dqb_isoftlimit; /* preferred inode limit */ qsize_t dqb_curinodes; /* current # allocated inodes */ qsize_t dqb_bhardlimit; /* absolute limit on disk blks alloc */ qsize_t dqb_bsoftlimit; /* preferred limit on disk blks */ qsize_t dqb_curblocks; /* current block count */ time_t dqb_btime; /* time limit for excessive disk use */ time_t dqb_itime; /* time limit for excessive inode use */ }; /* API v1 command definitions */ #define Q_V1_GETQUOTA 0x0300 #define Q_V1_SYNC 0x0600 #define Q_V1_SETQLIM 0x0700 #define Q_V1_GETSTATS 0x0800 /* API v2 command definitions */ #define Q_V2_SYNC 0x0600 #define Q_V2_SETQLIM 0x0700 #define Q_V2_GETQUOTA 0x0D00 #define Q_V2_GETSTATS 0x1100 /* proc API command definitions */ #define Q_V3_SYNC 0x800001 #define Q_V3_GETQUOTA 0x800007 #define Q_V3_SETQUOTA 0x800008 /* Interface versions */ #define IFACE_UNSET 0 #define IFACE_VFSOLD 1 #define IFACE_VFSV0 2 #define IFACE_GENERIC 3 #define DEV_QBSIZE 1024 struct dqblk_v3 { u_int64_t dqb_bhardlimit; u_int64_t dqb_bsoftlimit; u_int64_t dqb_curspace; u_int64_t dqb_ihardlimit; u_int64_t dqb_isoftlimit; u_int64_t dqb_curinodes; u_int64_t dqb_btime; u_int64_t dqb_itime; u_int32_t dqb_valid; }; struct dqblk_v2 { unsigned int dqb_ihardlimit; unsigned int dqb_isoftlimit; unsigned int dqb_curinodes; unsigned int dqb_bhardlimit; unsigned int dqb_bsoftlimit; qsize_t dqb_curspace; time_t dqb_btime; time_t dqb_itime; }; struct dqstats_v2 { u_int32_t lookups; u_int32_t drops; u_int32_t reads; u_int32_t writes; u_int32_t cache_hits; u_int32_t allocated_dquots; u_int32_t free_dquots; u_int32_t syncs; u_int32_t version; }; struct dqblk_v1 { u_int32_t dqb_bhardlimit; u_int32_t dqb_bsoftlimit; u_int32_t dqb_curblocks; u_int32_t dqb_ihardlimit; u_int32_t dqb_isoftlimit; u_int32_t dqb_curinodes; time_t dqb_btime; time_t dqb_itime; }; extern long quotactl (unsigned int, const char *, int, caddr_t); #endif /* linux */ extern int getnfsquota (struct vol *, const int, const u_int32_t, struct dqblk *); extern int uquota_getvolspace (struct vol *, VolSpace *, VolSpace *, const u_int32_t); #endif /* NO_QUOTA_SUPPORT */ extern struct afp_options default_options; extern int gmem (const gid_t); extern int setdeskmode (const mode_t); extern int setdirunixmode (const struct vol *, const char *, mode_t); extern int setdirmode (const struct vol *, const char *, mode_t); extern int setdeskowner (const uid_t, const gid_t); extern int setdirowner (const struct vol *, const char *, const uid_t, const gid_t); extern int setfilunixmode (const struct vol *, struct path*, const mode_t); extern int setfilowner (const struct vol *, const uid_t, const gid_t, struct path*); extern void accessmode (char *, struct maccess *, struct dir *, struct stat *); #ifdef AFS #define accessmode afsmode #endif #endif /* UNIX_H */
knu/netatalk
etc/afpd/unix.h
C
gpl-2.0
6,410
/* * drivers/cpufreq/cpufreq_ondemandx.c * * Copyright (C) 2001 Russell King * (C) 2003 Venkatesh Pallipadi <venkatesh.pallipadi@intel.com>. * Jun Nakajima <jun.nakajima@intel.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/cpufreq.h> #include <linux/cpu.h> #include <linux/jiffies.h> #include <linux/kernel_stat.h> #include <linux/mutex.h> #include <linux/hrtimer.h> #include <linux/tick.h> #include <linux/ktime.h> #include <linux/sched.h> #include <linux/earlysuspend.h> /* * dbs is used in this file as a shortform for demandbased switching * It helps to keep variable names smaller, simpler */ #define DEF_FREQUENCY_DOWN_DIFFERENTIAL (10) #define DEF_FREQUENCY_UP_THRESHOLD (80) #define DEF_SAMPLING_DOWN_FACTOR (1) #define MAX_SAMPLING_DOWN_FACTOR (100000) #define MICRO_FREQUENCY_DOWN_DIFFERENTIAL (3) #define MICRO_FREQUENCY_UP_THRESHOLD (95) #define MICRO_FREQUENCY_MIN_SAMPLE_RATE (10000) #define MIN_FREQUENCY_UP_THRESHOLD (11) #define MAX_FREQUENCY_UP_THRESHOLD (100) /* * The polling frequency of this governor depends on the capability of * the processor. Default polling frequency is 1000 times the transition * latency of the processor. The governor will work on any processor with * transition latency <= 10mS, using appropriate sampling * rate. * For CPUs with transition latency > 10mS (mostly drivers with CPUFREQ_ETERNAL) * this governor will not work. * All times here are in uS. */ #define MIN_SAMPLING_RATE_RATIO (2) static unsigned int min_sampling_rate; static unsigned int suspendfreq = 345600; #define LATENCY_MULTIPLIER (1000) #define MIN_LATENCY_MULTIPLIER (100) #define TRANSITION_LATENCY_LIMIT (10 * 1000 * 1000) static void do_dbs_timer(struct work_struct *work); static int cpufreq_governor_dbs(struct cpufreq_policy *policy, unsigned int event); #ifndef CONFIG_CPU_FREQ_DEFAULT_GOV_ONDEMANDX static #endif struct cpufreq_governor cpufreq_gov_ondemandx = { .name = "ondemandX", .governor = cpufreq_governor_dbs, .max_transition_latency = TRANSITION_LATENCY_LIMIT, .owner = THIS_MODULE, }; /* Sampling types */ enum {DBS_NORMAL_SAMPLE, DBS_SUB_SAMPLE}; struct cpu_dbs_info_s { cputime64_t prev_cpu_idle; cputime64_t prev_cpu_iowait; cputime64_t prev_cpu_wall; cputime64_t prev_cpu_nice; struct cpufreq_policy *cur_policy; struct delayed_work work; struct cpufreq_frequency_table *freq_table; unsigned int freq_lo; unsigned int freq_lo_jiffies; unsigned int freq_hi_jiffies; unsigned int rate_mult; int cpu; unsigned int sample_type:1; /* * percpu mutex that serializes governor limit change with * do_dbs_timer invocation. We do not want do_dbs_timer to run * when user is changing the governor or limits. */ struct mutex timer_mutex; }; static DEFINE_PER_CPU(struct cpu_dbs_info_s, od_cpu_dbs_info); static unsigned int dbs_enable=0; /* number of CPUs using this policy */ // used for imoseyon's mods static unsigned int suspended = 0; static void ondemandx_suspend(int suspend) { struct cpu_dbs_info_s *dbs_info = &per_cpu(od_cpu_dbs_info, smp_processor_id()); if (dbs_enable==0) return; if (!suspend) { // resume at max speed: suspended = 0; __cpufreq_driver_target(dbs_info->cur_policy, dbs_info->cur_policy->max, CPUFREQ_RELATION_L); pr_info("[imoseyon] ondemandx awake at %d\n", dbs_info->cur_policy->cur); } else { suspended = 1; // let's give it a little breathing room __cpufreq_driver_target(dbs_info->cur_policy, suspendfreq, CPUFREQ_RELATION_H); pr_info("[imoseyon] ondemandx suspended at %d\n", dbs_info->cur_policy->cur); } } static void ondemandx_early_suspend(struct early_suspend *handler) { ondemandx_suspend(1); } static void ondemandx_late_resume(struct early_suspend *handler) { ondemandx_suspend(0); } static struct early_suspend ondemandx_power_suspend = { .suspend = ondemandx_early_suspend, .resume = ondemandx_late_resume, .level = EARLY_SUSPEND_LEVEL_DISABLE_FB + 1, }; /* * dbs_mutex protects dbs_enable in governor start/stop. */ static DEFINE_MUTEX(dbs_mutex); static struct dbs_tuners { unsigned int sampling_rate; unsigned int up_threshold; unsigned int down_differential; unsigned int ignore_nice; unsigned int sampling_down_factor; unsigned int powersave_bias; unsigned int io_is_busy; } dbs_tuners_ins = { .up_threshold = DEF_FREQUENCY_UP_THRESHOLD, .sampling_down_factor = DEF_SAMPLING_DOWN_FACTOR, .down_differential = DEF_FREQUENCY_DOWN_DIFFERENTIAL, .ignore_nice = 0, .powersave_bias = 0, }; static inline cputime64_t get_cpu_idle_time_jiffy(unsigned int cpu, cputime64_t *wall) { cputime64_t idle_time; cputime64_t cur_wall_time; cputime64_t busy_time; cur_wall_time = jiffies64_to_cputime64(get_jiffies_64()); busy_time = cputime64_add(kstat_cpu(cpu).cpustat.user, kstat_cpu(cpu).cpustat.system); busy_time = cputime64_add(busy_time, kstat_cpu(cpu).cpustat.irq); busy_time = cputime64_add(busy_time, kstat_cpu(cpu).cpustat.softirq); busy_time = cputime64_add(busy_time, kstat_cpu(cpu).cpustat.steal); busy_time = cputime64_add(busy_time, kstat_cpu(cpu).cpustat.nice); idle_time = cputime64_sub(cur_wall_time, busy_time); if (wall) *wall = (cputime64_t)jiffies_to_usecs(cur_wall_time); return (cputime64_t)jiffies_to_usecs(idle_time); } static inline cputime64_t get_cpu_idle_time(unsigned int cpu, cputime64_t *wall) { u64 idle_time = get_cpu_idle_time_us(cpu, wall); if (idle_time == -1ULL) return get_cpu_idle_time_jiffy(cpu, wall); return idle_time; } static inline cputime64_t get_cpu_iowait_time(unsigned int cpu, cputime64_t *wall) { u64 iowait_time = get_cpu_iowait_time_us(cpu, wall); if (iowait_time == -1ULL) return 0; return iowait_time; } /* * Find right freq to be set now with powersave_bias on. * Returns the freq_hi to be used right now and will set freq_hi_jiffies, * freq_lo, and freq_lo_jiffies in percpu area for averaging freqs. */ static unsigned int powersave_bias_target(struct cpufreq_policy *policy, unsigned int freq_next, unsigned int relation) { unsigned int freq_req, freq_reduc, freq_avg; unsigned int freq_hi, freq_lo; unsigned int index = 0; unsigned int jiffies_total, jiffies_hi, jiffies_lo; struct cpu_dbs_info_s *dbs_info = &per_cpu(od_cpu_dbs_info, policy->cpu); if (!dbs_info->freq_table) { dbs_info->freq_lo = 0; dbs_info->freq_lo_jiffies = 0; return freq_next; } cpufreq_frequency_table_target(policy, dbs_info->freq_table, freq_next, relation, &index); freq_req = dbs_info->freq_table[index].frequency; freq_reduc = freq_req * dbs_tuners_ins.powersave_bias / 1000; freq_avg = freq_req - freq_reduc; /* Find freq bounds for freq_avg in freq_table */ index = 0; cpufreq_frequency_table_target(policy, dbs_info->freq_table, freq_avg, CPUFREQ_RELATION_H, &index); freq_lo = dbs_info->freq_table[index].frequency; index = 0; cpufreq_frequency_table_target(policy, dbs_info->freq_table, freq_avg, CPUFREQ_RELATION_L, &index); freq_hi = dbs_info->freq_table[index].frequency; /* Find out how long we have to be in hi and lo freqs */ if (freq_hi == freq_lo) { dbs_info->freq_lo = 0; dbs_info->freq_lo_jiffies = 0; return freq_lo; } jiffies_total = usecs_to_jiffies(dbs_tuners_ins.sampling_rate); jiffies_hi = (freq_avg - freq_lo) * jiffies_total; jiffies_hi += ((freq_hi - freq_lo) / 2); jiffies_hi /= (freq_hi - freq_lo); jiffies_lo = jiffies_total - jiffies_hi; dbs_info->freq_lo = freq_lo; dbs_info->freq_lo_jiffies = jiffies_lo; dbs_info->freq_hi_jiffies = jiffies_hi; return freq_hi; } static void ondemandx_powersave_bias_init_cpu(int cpu) { struct cpu_dbs_info_s *dbs_info = &per_cpu(od_cpu_dbs_info, cpu); dbs_info->freq_table = cpufreq_frequency_get_table(cpu); dbs_info->freq_lo = 0; } static void ondemandx_powersave_bias_init(void) { int i; for_each_online_cpu(i) { ondemandx_powersave_bias_init_cpu(i); } } /************************** sysfs interface ************************/ static ssize_t show_sampling_rate_min(struct kobject *kobj, struct attribute *attr, char *buf) { return sprintf(buf, "%u\n", min_sampling_rate); } define_one_global_ro(sampling_rate_min); /* cpufreq_ondemandx Governor Tunables */ #define show_one(file_name, object) \ static ssize_t show_##file_name \ (struct kobject *kobj, struct attribute *attr, char *buf) \ { \ return sprintf(buf, "%u\n", dbs_tuners_ins.object); \ } show_one(sampling_rate, sampling_rate); show_one(io_is_busy, io_is_busy); show_one(up_threshold, up_threshold); show_one(down_differential, down_differential); show_one(sampling_down_factor, sampling_down_factor); show_one(ignore_nice_load, ignore_nice); show_one(powersave_bias, powersave_bias); static ssize_t store_sampling_rate(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; int ret; ret = sscanf(buf, "%u", &input); if (ret != 1) return -EINVAL; dbs_tuners_ins.sampling_rate = max(input, min_sampling_rate); return count; } static ssize_t store_io_is_busy(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; int ret; ret = sscanf(buf, "%u", &input); if (ret != 1) return -EINVAL; dbs_tuners_ins.io_is_busy = !!input; return count; } static ssize_t store_up_threshold(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; int ret; ret = sscanf(buf, "%u", &input); if (ret != 1 || input > MAX_FREQUENCY_UP_THRESHOLD || input < MIN_FREQUENCY_UP_THRESHOLD) { return -EINVAL; } dbs_tuners_ins.up_threshold = input; return count; } static ssize_t store_sampling_down_factor(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input, j; int ret; ret = sscanf(buf, "%u", &input); if (ret != 1 || input > MAX_SAMPLING_DOWN_FACTOR || input < 1) return -EINVAL; dbs_tuners_ins.sampling_down_factor = input; /* Reset down sampling multiplier in case it was active */ for_each_online_cpu(j) { struct cpu_dbs_info_s *dbs_info; dbs_info = &per_cpu(od_cpu_dbs_info, j); dbs_info->rate_mult = 1; } return count; } static ssize_t store_ignore_nice_load(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; int ret; unsigned int j; ret = sscanf(buf, "%u", &input); if (ret != 1) return -EINVAL; if (input > 1) input = 1; if (input == dbs_tuners_ins.ignore_nice) { /* nothing to do */ return count; } dbs_tuners_ins.ignore_nice = input; /* we need to re-evaluate prev_cpu_idle */ for_each_online_cpu(j) { struct cpu_dbs_info_s *dbs_info; dbs_info = &per_cpu(od_cpu_dbs_info, j); dbs_info->prev_cpu_idle = get_cpu_idle_time(j, &dbs_info->prev_cpu_wall); if (dbs_tuners_ins.ignore_nice) dbs_info->prev_cpu_nice = kstat_cpu(j).cpustat.nice; } return count; } static ssize_t store_powersave_bias(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; int ret; ret = sscanf(buf, "%u", &input); if (ret != 1) return -EINVAL; if (input > 1000) input = 1000; dbs_tuners_ins.powersave_bias = input; ondemandx_powersave_bias_init(); return count; } static ssize_t store_down_differential(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; int ret; ret = sscanf(buf, "%u", &input); if (ret != 1) return -EINVAL; if (input > 30) input = 30; if (input < 0) input = 0; mutex_lock(&dbs_mutex); dbs_tuners_ins.down_differential = input; mutex_unlock(&dbs_mutex); return count; } define_one_global_rw(sampling_rate); define_one_global_rw(io_is_busy); define_one_global_rw(up_threshold); define_one_global_rw(down_differential); define_one_global_rw(sampling_down_factor); define_one_global_rw(ignore_nice_load); define_one_global_rw(powersave_bias); static struct attribute *dbs_attributes[] = { &sampling_rate_min.attr, &sampling_rate.attr, &up_threshold.attr, &down_differential.attr, &sampling_down_factor.attr, &ignore_nice_load.attr, &powersave_bias.attr, &io_is_busy.attr, NULL }; static struct attribute_group dbs_attr_group = { .attrs = dbs_attributes, .name = "ondemandx", }; /************************** sysfs end ************************/ static void dbs_freq_increase(struct cpufreq_policy *p, unsigned int freq) { if (dbs_tuners_ins.powersave_bias) freq = powersave_bias_target(p, freq, CPUFREQ_RELATION_H); else if (p->cur == p->max) return; if (suspended && freq > suspendfreq) { freq = suspendfreq; __cpufreq_driver_target(p, freq, CPUFREQ_RELATION_H); } else __cpufreq_driver_target(p, freq, dbs_tuners_ins.powersave_bias ? CPUFREQ_RELATION_L : CPUFREQ_RELATION_H); } static void dbs_check_cpu(struct cpu_dbs_info_s *this_dbs_info) { unsigned int max_load_freq; struct cpufreq_policy *policy; unsigned int j; this_dbs_info->freq_lo = 0; policy = this_dbs_info->cur_policy; /* * Every sampling_rate, we check, if current idle time is less * than 20% (default), then we try to increase frequency * Every sampling_rate, we look for a the lowest * frequency which can sustain the load while keeping idle time over * 30%. If such a frequency exist, we try to decrease to this frequency. * * Any frequency increase takes it to the maximum frequency. * Frequency reduction happens at minimum steps of * 5% (default) of current frequency */ /* Get Absolute Load - in terms of freq */ max_load_freq = 0; for_each_cpu(j, policy->cpus) { struct cpu_dbs_info_s *j_dbs_info; cputime64_t cur_wall_time, cur_idle_time, cur_iowait_time; unsigned int idle_time, wall_time, iowait_time; unsigned int load, load_freq; int freq_avg; j_dbs_info = &per_cpu(od_cpu_dbs_info, j); cur_idle_time = get_cpu_idle_time(j, &cur_wall_time); cur_iowait_time = get_cpu_iowait_time(j, &cur_wall_time); wall_time = (unsigned int) cputime64_sub(cur_wall_time, j_dbs_info->prev_cpu_wall); j_dbs_info->prev_cpu_wall = cur_wall_time; idle_time = (unsigned int) cputime64_sub(cur_idle_time, j_dbs_info->prev_cpu_idle); j_dbs_info->prev_cpu_idle = cur_idle_time; iowait_time = (unsigned int) cputime64_sub(cur_iowait_time, j_dbs_info->prev_cpu_iowait); j_dbs_info->prev_cpu_iowait = cur_iowait_time; if (dbs_tuners_ins.ignore_nice) { cputime64_t cur_nice; unsigned long cur_nice_jiffies; cur_nice = cputime64_sub(kstat_cpu(j).cpustat.nice, j_dbs_info->prev_cpu_nice); /* * Assumption: nice time between sampling periods will * be less than 2^32 jiffies for 32 bit sys */ cur_nice_jiffies = (unsigned long) cputime64_to_jiffies64(cur_nice); j_dbs_info->prev_cpu_nice = kstat_cpu(j).cpustat.nice; idle_time += jiffies_to_usecs(cur_nice_jiffies); } /* * For the purpose of ondemandx, waiting for disk IO is an * indication that you're performance critical, and not that * the system is actually idle. So subtract the iowait time * from the cpu idle time. */ if (dbs_tuners_ins.io_is_busy && idle_time >= iowait_time) idle_time -= iowait_time; if (unlikely(!wall_time || wall_time < idle_time)) continue; load = 100 * (wall_time - idle_time) / wall_time; freq_avg = __cpufreq_driver_getavg(policy, j); if (freq_avg <= 0) freq_avg = policy->cur; load_freq = load * freq_avg; if (load_freq > max_load_freq) max_load_freq = load_freq; } /* Check for frequency increase */ if (max_load_freq > dbs_tuners_ins.up_threshold * policy->cur) { /* If switching to max speed, apply sampling_down_factor */ if (policy->cur < policy->max) this_dbs_info->rate_mult = dbs_tuners_ins.sampling_down_factor; dbs_freq_increase(policy, policy->max); return; } /* Check for frequency decrease */ /* if we cannot reduce the frequency anymore, break out early */ if (policy->cur == policy->min) return; /* * The optimal frequency is the frequency that is the lowest that * can support the current CPU usage without triggering the up * policy. To be safe, we focus 10 points under the threshold. */ if (max_load_freq < (dbs_tuners_ins.up_threshold - dbs_tuners_ins.down_differential) * policy->cur) { unsigned int freq_next; freq_next = max_load_freq / (dbs_tuners_ins.up_threshold - dbs_tuners_ins.down_differential); /* No longer fully busy, reset rate_mult */ this_dbs_info->rate_mult = 1; if (freq_next < policy->min) freq_next = policy->min; if (!dbs_tuners_ins.powersave_bias) { __cpufreq_driver_target(policy, freq_next, CPUFREQ_RELATION_L); } else { int freq = powersave_bias_target(policy, freq_next, CPUFREQ_RELATION_L); __cpufreq_driver_target(policy, freq, CPUFREQ_RELATION_L); } } } static void do_dbs_timer(struct work_struct *work) { struct cpu_dbs_info_s *dbs_info = container_of(work, struct cpu_dbs_info_s, work.work); unsigned int cpu = dbs_info->cpu; int sample_type = dbs_info->sample_type; int delay; mutex_lock(&dbs_info->timer_mutex); /* Common NORMAL_SAMPLE setup */ dbs_info->sample_type = DBS_NORMAL_SAMPLE; if (!dbs_tuners_ins.powersave_bias || sample_type == DBS_NORMAL_SAMPLE) { dbs_check_cpu(dbs_info); if (dbs_info->freq_lo) { /* Setup timer for SUB_SAMPLE */ dbs_info->sample_type = DBS_SUB_SAMPLE; delay = dbs_info->freq_hi_jiffies; } else { /* We want all CPUs to do sampling nearly on * same jiffy */ delay = usecs_to_jiffies(dbs_tuners_ins.sampling_rate * dbs_info->rate_mult); if (num_online_cpus() > 1) delay -= jiffies % delay; } } else { if (!suspended) __cpufreq_driver_target(dbs_info->cur_policy, dbs_info->freq_lo, CPUFREQ_RELATION_H); delay = dbs_info->freq_lo_jiffies; } schedule_delayed_work_on(cpu, &dbs_info->work, delay); mutex_unlock(&dbs_info->timer_mutex); } static inline void dbs_timer_init(struct cpu_dbs_info_s *dbs_info) { /* We want all CPUs to do sampling nearly on same jiffy */ int delay = usecs_to_jiffies(dbs_tuners_ins.sampling_rate); if (num_online_cpus() > 1) delay -= jiffies % delay; dbs_info->sample_type = DBS_NORMAL_SAMPLE; INIT_DELAYED_WORK_DEFERRABLE(&dbs_info->work, do_dbs_timer); schedule_delayed_work_on(dbs_info->cpu, &dbs_info->work, delay); } static inline void dbs_timer_exit(struct cpu_dbs_info_s *dbs_info) { cancel_delayed_work_sync(&dbs_info->work); } /* * Not all CPUs want IO time to be accounted as busy; this dependson how * efficient idling at a higher frequency/voltage is. * Pavel Machek says this is not so for various generations of AMD and old * Intel systems. * Mike Chan (androidlcom) calis this is also not true for ARM. * Because of this, whitelist specific known (series) of CPUs by default, and * leave all others up to the user. */ static int should_io_be_busy(void) { #if defined(CONFIG_X86) /* * For Intel, Core 2 (model 15) andl later have an efficient idle. */ if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL && boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model >= 15) return 1; #endif return 0; } static int cpufreq_governor_dbs(struct cpufreq_policy *policy, unsigned int event) { unsigned int cpu = policy->cpu; struct cpu_dbs_info_s *this_dbs_info; unsigned int j; int rc; this_dbs_info = &per_cpu(od_cpu_dbs_info, cpu); switch (event) { case CPUFREQ_GOV_START: if ((!cpu_online(cpu)) || (!policy->cur)) return -EINVAL; mutex_lock(&dbs_mutex); dbs_enable++; for_each_cpu(j, policy->cpus) { struct cpu_dbs_info_s *j_dbs_info; j_dbs_info = &per_cpu(od_cpu_dbs_info, j); j_dbs_info->cur_policy = policy; j_dbs_info->prev_cpu_idle = get_cpu_idle_time(j, &j_dbs_info->prev_cpu_wall); if (dbs_tuners_ins.ignore_nice) { j_dbs_info->prev_cpu_nice = kstat_cpu(j).cpustat.nice; } } this_dbs_info->cpu = cpu; this_dbs_info->rate_mult = 1; ondemandx_powersave_bias_init_cpu(cpu); /* * Start the timerschedule work, when this governor * is used for first time */ if (dbs_enable == 1) { unsigned int latency; rc = sysfs_create_group(cpufreq_global_kobject, &dbs_attr_group); if (rc) { mutex_unlock(&dbs_mutex); return rc; } /* policy latency is in nS. Convert it to uS first */ latency = policy->cpuinfo.transition_latency / 1000; if (latency == 0) latency = 1; /* Bring kernel and HW constraints together */ min_sampling_rate = max(min_sampling_rate, MIN_LATENCY_MULTIPLIER * latency); dbs_tuners_ins.sampling_rate = max(min_sampling_rate, latency * LATENCY_MULTIPLIER); dbs_tuners_ins.io_is_busy = should_io_be_busy(); } mutex_unlock(&dbs_mutex); mutex_init(&this_dbs_info->timer_mutex); dbs_timer_init(this_dbs_info); register_early_suspend(&ondemandx_power_suspend); pr_info("[imoseyon] ondemandx active\n"); break; case CPUFREQ_GOV_STOP: dbs_timer_exit(this_dbs_info); mutex_lock(&dbs_mutex); mutex_destroy(&this_dbs_info->timer_mutex); dbs_enable--; mutex_unlock(&dbs_mutex); if (!dbs_enable) sysfs_remove_group(cpufreq_global_kobject, &dbs_attr_group); unregister_early_suspend(&ondemandx_power_suspend); pr_info("[imoseyon] ondemandx inactive\n"); break; case CPUFREQ_GOV_LIMITS: mutex_lock(&this_dbs_info->timer_mutex); if (policy->max < this_dbs_info->cur_policy->cur) __cpufreq_driver_target(this_dbs_info->cur_policy, policy->max, CPUFREQ_RELATION_H); else if (policy->min > this_dbs_info->cur_policy->cur) __cpufreq_driver_target(this_dbs_info->cur_policy, policy->min, CPUFREQ_RELATION_L); mutex_unlock(&this_dbs_info->timer_mutex); break; } return 0; } static int __init cpufreq_gov_dbs_init(void) { cputime64_t wall; u64 idle_time; int cpu = get_cpu(); idle_time = get_cpu_idle_time_us(cpu, &wall); put_cpu(); if (idle_time != -1ULL) { /* Idle micro accounting is supported. Use finer thresholds */ dbs_tuners_ins.up_threshold = MICRO_FREQUENCY_UP_THRESHOLD; dbs_tuners_ins.down_differential = MICRO_FREQUENCY_DOWN_DIFFERENTIAL; /* * In no_hz/micro accounting case we set the minimum frequency * not depending on HZ, but fixed (very low). The deferred * timer might skip some samples if idle/sleeping as needed. */ min_sampling_rate = MICRO_FREQUENCY_MIN_SAMPLE_RATE; } else { /* For correct statistics, we need 10 ticks for each measure */ min_sampling_rate = MIN_SAMPLING_RATE_RATIO * jiffies_to_usecs(10); } pr_info("[imoseyon] ondemandx enter\n"); return cpufreq_register_governor(&cpufreq_gov_ondemandx); } static void __exit cpufreq_gov_dbs_exit(void) { pr_info("[imoseyon] ondemandx exit\n"); cpufreq_unregister_governor(&cpufreq_gov_ondemandx); } MODULE_AUTHOR("Venkatesh Pallipadi <venkatesh.pallipadi@intel.com>"); MODULE_AUTHOR("Alexey Starikovskiy <alexey.y.starikovskiy@intel.com>"); MODULE_DESCRIPTION("'cpufreq_ondemandx' - A dynamic cpufreq governor for " "Low Latency Frequency Transition capable processors"); MODULE_LICENSE("GPL"); #ifdef CONFIG_CPU_FREQ_DEFAULT_GOV_ONDEMANDX fs_initcall(cpufreq_gov_dbs_init); #else module_init(cpufreq_gov_dbs_init); #endif module_exit(cpufreq_gov_dbs_exit);
tuxkids/kernel_cyanogen_gio
drivers/cpufreq/cpufreq_ondemandx.c
C
gpl-2.0
22,712
require File.dirname(__FILE__) + '/../test_helper' module ::FixtureReplacement attributes_for :gender do |g| g.sex = "male" end attributes_for :user do |u| u.username = scott u.key = "something" u.gender = new_gender end private def scott "Scott Taylor" end end class UserTest < Test::Unit::TestCase def setup extend FixtureReplacement end def test_true_should_be_true assert_equal true, true end def test_be_able_to_create_with_create_user assert_equal create_user.class, User end def test_user_has_default_gender_with_create_user assert create_user.gender.kind_of?(Gender) assert_equal create_user.gender.sex, "male" end def test_user_has_default_gender_with_new_user assert new_user.gender.kind_of?(Gender) assert_equal new_user.gender.sex, "male" end def test_create_user_should_have_user_key_something assert_equal create_user.key, "something" end def test_new_user_should_have_user_key_something assert_equal new_user.key, "something" end def test_testcase_should_not_raise_an_error_when_sending_new_user assert self.send(:new_user) end end
systemsbiology/slimseq
vendor/plugins/fixturereplacement/test/unit/user_test.rb
Ruby
gpl-2.0
1,165
<?php /** * @package EasySocial * @copyright Copyright (C) 2010 - 2014 Stack Ideas Sdn Bhd. All rights reserved. * @license Proprietary Use License http://stackideas.com/licensing.html * @author Stack Ideas Sdn Bhd */ defined( '_JEXEC' ) or die( 'Unauthorized Access' ); ?> EasySocial.require() .script( 'admin/grid/grid' ) .done(function($) { $( '[data-table-grid]' ).implement( EasySocial.Controller.Grid ); });
cuongnd/banhangonline88_joomla
administrator/components/com_easysocial/themes/default/themes/default.js
JavaScript
gpl-2.0
422
<?php /** * The template for displaying Author archive pages. * */ global $wp_query; get_header(); $header_style = ot_get_option('ut_global_headline_style'); ?> <div class="grid-container"> <div id="primary" class="grid-parent grid-100 tablet-grid-100 mobile-grid-100"> <?php if ( have_posts() ) : ?> <?php /* Queue the first post, that way we know * what author we're dealing with (if that is the case). * * We reset this later so we can run the loop * properly with a call to rewind_posts(). */ the_post(); ?> <!-- page header --> <div class="grid-70 prefix-15 mobile-grid-100 tablet-grid-100"> <header class="page-header <?php echo $header_style;?>"> <h1 class="page-title"><span><?php printf( __( 'All posts by %s', 'unitedthemes' ), '<span class="vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . '" title="' . esc_attr( get_the_author() ) . '" rel="me">' . get_the_author() . '</a></span>' ); ?></span></h1> </header> </div><!-- .page-header --> <?php /* Since we called the_post() above, we need to * rewind the loop back to the beginning that way * we can run the loop properly, in full. */ rewind_posts(); ?> <?php endif; ?> <?php if ( have_posts() ) : ?> <?php /* The loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part('partials/content', get_post_format() ); ?> <?php endwhile; ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> </div><!-- .grid-parent grid-100 tablet-grid-100 mobile-grid-100 --> </div><!-- .grid-container --> <?php if( $wp_query->max_num_pages > 1 ) : ?> <div id="ut-blog-navigation"> <div class="grid-container"> <div class="grid-100 tablet-grid-100 mobile-grid-100"> <?php if ( have_posts() ) : ?> <?php unitedthemes_content_nav( 'nav-below' ); ?> <?php endif; ?> </div><!-- .grid-100 --> </div><!-- .grid-container --> </div><!-- #ut-blog-navigation --> <?php endif; ?> <?php get_footer(); ?>
robertjmcinnis/motus-strength
wp-content/themes/brooklyn/author.php
PHP
gpl-2.0
2,347
'''OpenGL extension NV.transform_feedback This module customises the behaviour of the OpenGL.raw.GL.NV.transform_feedback to provide a more Python-friendly API Overview (from the spec) This extension provides a new mode to the GL, called transform feedback, which records vertex attributes of the primitives processed by the GL. The selected attributes are written into buffer objects, and can be written with each attribute in a separate buffer object or with all attributes interleaved into a single buffer object. If a geometry program or shader is active, the primitives recorded are those emitted by the geometry program. Otherwise, transform feedback captures primitives whose vertex are transformed by a vertex program or shader, or by fixed-function vertex processing. In either case, the primitives captured are those generated prior to clipping. Transform feedback mode is capable of capturing transformed vertex data generated by fixed-function vertex processing, outputs from assembly vertex or geometry programs, or varying variables emitted from GLSL vertex or geometry shaders. The vertex data recorded in transform feedback mode is stored into buffer objects as an array of vertex attributes. The regular representation and the use of buffer objects allows the recorded data to be processed directly by the GL without requiring CPU intervention to copy data. In particular, transform feedback data can be used for vertex arrays (via vertex buffer objects), as the source for pixel data (via pixel buffer objects), as program constant data (via the NV_parameter_buffer_object or EXT_bindable_uniform extension), or via any other extension that makes use of buffer objects. This extension introduces new query object support to allow transform feedback mode to operate asynchronously. Query objects allow applications to determine when transform feedback results are complete, as well as the number of primitives processed and written back to buffer objects while in transform feedback mode. This extension also provides a new rasterizer discard enable, which allows applications to use transform feedback to capture vertex attributes without rendering anything. The official definition of this extension is available here: http://www.opengl.org/registry/specs/NV/transform_feedback.txt ''' from OpenGL import platform, constants, constant, arrays from OpenGL import extensions, wrapper from OpenGL.GL import glget import ctypes from OpenGL.raw.GL.NV.transform_feedback import * ### END AUTOGENERATED SECTION
D4wN/brickv
src/build_data/windows/OpenGL/GL/NV/transform_feedback.py
Python
gpl-2.0
2,570
#!/usr/bin/env python print(CurrentScript().arguments)
dthain/cctools
weaver/src/examples/arguments.py
Python
gpl-2.0
56
/* Test mpf_trunc, mpf_ceil, mpf_floor. Copyright 2001, 2002 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP 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 MP 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 MP Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include "gmp.h" #include "gmp-impl.h" #include "tests.h" void check_print (mpf_srcptr src, mpf_srcptr got, mpf_srcptr want) { mp_trace_base = 16; mpf_trace ("src ", src); mpf_trace ("got ", got); mpf_trace ("want", want); printf ("got size=%d exp=%ld\n", SIZ(got), EXP(got)); mpn_trace (" limbs=", PTR(got), (mp_size_t) ABSIZ(got)); printf ("want size=%d exp=%ld\n", SIZ(want), EXP(want)); mpn_trace (" limbs=", PTR(want), (mp_size_t) ABSIZ(want)); } void check_one (mpf_srcptr src, mpf_srcptr trunc, mpf_srcptr ceil, mpf_srcptr floor) { mpf_t got; mpf_init2 (got, mpf_get_prec (trunc)); ASSERT_ALWAYS (PREC(got) == PREC(trunc)); ASSERT_ALWAYS (PREC(got) == PREC(ceil)); ASSERT_ALWAYS (PREC(got) == PREC(floor)); #define CHECK_SEP(name, fun, want) \ mpf_set_ui (got, 54321L); /* initial junk */ \ fun (got, src); \ MPF_CHECK_FORMAT (got); \ if (mpf_cmp (got, want) != 0) \ { \ printf ("%s wrong\n", name); \ check_print (src, got, want); \ abort (); \ } CHECK_SEP ("mpf_trunc", mpf_trunc, trunc); CHECK_SEP ("mpf_ceil", mpf_ceil, ceil); CHECK_SEP ("mpf_floor", mpf_floor, floor); #define CHECK_INPLACE(name, fun, want) \ mpf_set (got, src); \ fun (got, got); \ MPF_CHECK_FORMAT (got); \ if (mpf_cmp (got, want) != 0) \ { \ printf ("%s wrong\n", name); \ check_print (src, got, want); \ abort (); \ } CHECK_INPLACE ("mpf_trunc", mpf_trunc, trunc); /* Can't do these unconditionally in case truncation by mpf_set strips some low non-zero limbs which would have rounded the result. */ if (ABSIZ(src) <= PREC(trunc)+1) { CHECK_INPLACE ("mpf_ceil", mpf_ceil, ceil); CHECK_INPLACE ("mpf_floor", mpf_floor, floor); } mpf_clear (got); } void check_all (mpf_ptr src, mpf_ptr trunc, mpf_ptr ceil, mpf_ptr floor) { /* some of these values are generated with direct field assignments */ MPF_CHECK_FORMAT (src); MPF_CHECK_FORMAT (trunc); MPF_CHECK_FORMAT (ceil); MPF_CHECK_FORMAT (floor); check_one (src, trunc, ceil, floor); mpf_neg (src, src); mpf_neg (trunc, trunc); mpf_neg (ceil, ceil); mpf_neg (floor, floor); check_one (src, trunc, floor, ceil); } void check_various (void) { mpf_t src, trunc, ceil, floor; int n, i; mpf_init2 (src, 512L); mpf_init2 (trunc, 256L); mpf_init2 (ceil, 256L); mpf_init2 (floor, 256L); /* 0 */ mpf_set_ui (src, 0L); mpf_set_ui (trunc, 0L); mpf_set_ui (ceil, 0L); mpf_set_ui (floor, 0L); check_all (src, trunc, ceil, floor); /* 1 */ mpf_set_ui (src, 1L); mpf_set_ui (trunc, 1L); mpf_set_ui (ceil, 1L); mpf_set_ui (floor, 1L); check_all (src, trunc, ceil, floor); /* 2^1024 */ mpf_set_ui (src, 1L); mpf_mul_2exp (src, src, 1024L); mpf_set (trunc, src); mpf_set (ceil, src); mpf_set (floor, src); check_all (src, trunc, ceil, floor); /* 1/2^1024, fraction only */ mpf_set_ui (src, 1L); mpf_div_2exp (src, src, 1024L); mpf_set_si (trunc, 0L); mpf_set_si (ceil, 1L); mpf_set_si (floor, 0L); check_all (src, trunc, ceil, floor); /* 1/2 */ mpf_set_ui (src, 1L); mpf_div_2exp (src, src, 1L); mpf_set_si (trunc, 0L); mpf_set_si (ceil, 1L); mpf_set_si (floor, 0L); check_all (src, trunc, ceil, floor); /* 123+1/2^64 */ mpf_set_ui (src, 1L); mpf_div_2exp (src, src, 64L); mpf_add_ui (src, src, 123L); mpf_set_si (trunc, 123L); mpf_set_si (ceil, 124L); mpf_set_si (floor, 123L); check_all (src, trunc, ceil, floor); /* integer of full prec+1 limbs, unchanged */ n = PREC(trunc)+1; ASSERT_ALWAYS (n <= PREC(src)+1); EXP(src) = n; SIZ(src) = n; for (i = 0; i < SIZ(src); i++) PTR(src)[i] = i+100; mpf_set (trunc, src); mpf_set (ceil, src); mpf_set (floor, src); check_all (src, trunc, ceil, floor); /* full prec+1 limbs, 1 trimmed for integer */ n = PREC(trunc)+1; ASSERT_ALWAYS (n <= PREC(src)+1); EXP(src) = n-1; SIZ(src) = n; for (i = 0; i < SIZ(src); i++) PTR(src)[i] = i+200; EXP(trunc) = n-1; SIZ(trunc) = n-1; for (i = 0; i < SIZ(trunc); i++) PTR(trunc)[i] = i+201; mpf_set (floor, trunc); mpf_add_ui (ceil, trunc, 1L); check_all (src, trunc, ceil, floor); /* prec+3 limbs, 2 trimmed for size */ n = PREC(trunc)+3; ASSERT_ALWAYS (n <= PREC(src)+1); EXP(src) = n; SIZ(src) = n; for (i = 0; i < SIZ(src); i++) PTR(src)[i] = i+300; EXP(trunc) = n; SIZ(trunc) = n-2; for (i = 0; i < SIZ(trunc); i++) PTR(trunc)[i] = i+302; mpf_set (floor, trunc); mpf_set (ceil, trunc); PTR(ceil)[0]++; check_all (src, trunc, ceil, floor); /* prec+4 limbs, 2 trimmed for size, 1 trimmed for integer */ n = PREC(trunc)+4; ASSERT_ALWAYS (n <= PREC(src)+1); EXP(src) = n-1; SIZ(src) = n; for (i = 0; i < SIZ(src); i++) PTR(src)[i] = i+400; EXP(trunc) = n-1; SIZ(trunc) = n-3; for (i = 0; i < SIZ(trunc); i++) PTR(trunc)[i] = i+403; mpf_set (floor, trunc); mpf_set (ceil, trunc); PTR(ceil)[0]++; check_all (src, trunc, ceil, floor); /* F.F, carry out of ceil */ EXP(src) = 1; SIZ(src) = 2; PTR(src)[0] = GMP_NUMB_MAX; PTR(src)[1] = GMP_NUMB_MAX; EXP(trunc) = 1; SIZ(trunc) = 1; PTR(trunc)[0] = GMP_NUMB_MAX; mpf_set (floor, trunc); EXP(ceil) = 2; SIZ(ceil) = 1; PTR(ceil)[0] = 1; check_all (src, trunc, ceil, floor); /* FF.F, carry out of ceil */ EXP(src) = 2; SIZ(src) = 3; PTR(src)[0] = GMP_NUMB_MAX; PTR(src)[1] = GMP_NUMB_MAX; PTR(src)[2] = GMP_NUMB_MAX; EXP(trunc) = 2; SIZ(trunc) = 2; PTR(trunc)[0] = GMP_NUMB_MAX; PTR(trunc)[1] = GMP_NUMB_MAX; mpf_set (floor, trunc); EXP(ceil) = 3; SIZ(ceil) = 1; PTR(ceil)[0] = 1; check_all (src, trunc, ceil, floor); mpf_clear (src); mpf_clear (trunc); mpf_clear (ceil); mpf_clear (floor); } int main (void) { tests_start (); check_various (); tests_end (); exit (0); }
DDTChen/CookieVLC
vlc/contrib/android/gmp/tests/mpf/t-trunc.c
C
gpl-2.0
7,157
/* * Copyright 2004 Martin Fuchs * * Pass on icon notification messages to the systray implementation * in the currently running shell. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "precomp.h" WINE_DEFAULT_DEBUG_CHANNEL(shell); /* copy data structure for tray notifications */ typedef struct TrayNotifyCDS_Dummy { DWORD cookie; DWORD notify_code; DWORD nicon_data[1]; // placeholder for NOTIFYICONDATA structure } TrayNotifyCDS_Dummy; /* The only difference between Shell_NotifyIconA and Shell_NotifyIconW is the call to SendMessageA/W. */ static BOOL SHELL_NotifyIcon(DWORD dwMessage, void* pnid, HWND nid_hwnd, DWORD nid_size, BOOL unicode) { HWND hwnd; COPYDATASTRUCT data; BOOL ret = FALSE; int len = FIELD_OFFSET(TrayNotifyCDS_Dummy, nicon_data) + nid_size; TrayNotifyCDS_Dummy* pnotify_data = (TrayNotifyCDS_Dummy*) alloca(len); pnotify_data->cookie = 1; pnotify_data->notify_code = dwMessage; memcpy(&pnotify_data->nicon_data, pnid, nid_size); data.dwData = 1; data.cbData = len; data.lpData = pnotify_data; for(hwnd = 0; (hwnd = FindWindowExW(0, hwnd, L"Shell_TrayWnd", NULL)); ) if ((unicode ? SendMessageW : SendMessageA)(hwnd, WM_COPYDATA, (WPARAM)nid_hwnd, (LPARAM)&data)) ret = TRUE; return ret; } /************************************************************************* * Shell_NotifyIcon [SHELL32.296] * Shell_NotifyIconA [SHELL32.297] */ BOOL WINAPI Shell_NotifyIconA(DWORD dwMessage, PNOTIFYICONDATAA pnid) { DWORD cbSize; /* Validate the cbSize as Windows XP does */ if (pnid->cbSize != NOTIFYICONDATAA_V1_SIZE && pnid->cbSize != NOTIFYICONDATAA_V2_SIZE && pnid->cbSize != sizeof(NOTIFYICONDATAA)) { WARN("Invalid cbSize (%d) - using only Win95 fields (size=%d)\n", pnid->cbSize, NOTIFYICONDATAA_V1_SIZE); cbSize = NOTIFYICONDATAA_V1_SIZE; } else cbSize = pnid->cbSize; return SHELL_NotifyIcon(dwMessage, pnid, pnid->hWnd, cbSize, FALSE); } /************************************************************************* * Shell_NotifyIconW [SHELL32.298] */ BOOL WINAPI Shell_NotifyIconW(DWORD dwMessage, PNOTIFYICONDATAW pnid) { DWORD cbSize; /* Validate the cbSize so that WM_COPYDATA doesn't crash the application */ if (pnid->cbSize != NOTIFYICONDATAW_V1_SIZE && pnid->cbSize != NOTIFYICONDATAW_V2_SIZE && pnid->cbSize != sizeof(NOTIFYICONDATAW)) { WARN("Invalid cbSize (%d) - using only Win95 fields (size=%d)\n", pnid->cbSize, NOTIFYICONDATAW_V1_SIZE); cbSize = NOTIFYICONDATAA_V1_SIZE; } else cbSize = pnid->cbSize; return SHELL_NotifyIcon(dwMessage, pnid, pnid->hWnd, cbSize, TRUE); }
rickerliang/reactos-mirror2
dll/win32/shell32/systray.cpp
C++
gpl-2.0
3,535
<?php /** * --------------------------------------------------------------------- * GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2015-2018 Teclib' and contributors. * * http://glpi-project.org * * based on GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2003-2014 by the INDEPNET Development Team. * * --------------------------------------------------------------------- * * LICENSE * * This file is part of GLPI. * * GLPI 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. * * GLPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GLPI. If not, see <http://www.gnu.org/licenses/>. * --------------------------------------------------------------------- */ /** * @since 0.85 */ use Glpi\Event; if (!defined('GLPI_ROOT')) { include ('../inc/includes.php'); } $link = new Change_User(); $item = new Change(); Session ::checkLoginUser(); Html::popHeader(__('Email followup'), $_SERVER['PHP_SELF']); if (isset($_POST["update"])) { $link->check($_POST["id"], UPDATE); $link->update($_POST); echo "<script type='text/javascript' >\n"; echo "window.parent.location.reload();"; echo "</script>"; } else if (isset($_POST['delete'])) { $link->check($_POST['id'], DELETE); $link->delete($_POST); Event::log($link->fields['changes_id'], "change", 4, "maintain", //TRANS: %s is the user login sprintf(__('%s deletes an actor'), $_SESSION["glpiname"])); if ($item->can($link->fields["changes_id"], READ)) { Html::redirect(Change::getFormURLWithID($link->fields['changes_id'])); } Session::addMessageAfterRedirect(__('You have been redirected because you no longer have access to this item'), true, ERROR); Html::redirect($CFG_GLPI["root_doc"]."/front/change.php"); } else if (isset($_GET["id"])) { $link->showUserNotificationForm($_GET["id"]); } else { Html::displayErrorAndDie('Lost'); } Html::popFooter();
tsmr/glpi
front/change_user.form.php
PHP
gpl-2.0
2,430
/* sound/soc/samsung/ac97.c * * ALSA SoC Audio Layer - S3C AC97 Controller driver * Evolved from s3c2443-ac97.c * * Copyright (c) 2010 Samsung Electronics Co. Ltd * Author: Jaswinder Singh <jassisinghbrar@gmail.com> * Credits: Graeme Gregory, Sean Choi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/io.h> #include <linux/delay.h> #include <linux/clk.h> #include <linux/module.h> #include <sound/soc.h> #include "regs-ac97.h" #include <linux/platform_data/asoc-s3c.h> #include "dma.h" #define AC_CMD_ADDR(x) (x << 16) #define AC_CMD_DATA(x) (x & 0xffff) #define S3C_AC97_DAI_PCM 0 #define S3C_AC97_DAI_MIC 1 struct s3c_ac97_info { struct clk *ac97_clk; void __iomem *regs; struct mutex lock; struct completion done; }; static struct s3c_ac97_info s3c_ac97; static struct snd_dmaengine_dai_dma_data s3c_ac97_pcm_out = { .addr_width = 4, }; static struct snd_dmaengine_dai_dma_data s3c_ac97_pcm_in = { .addr_width = 4, }; static struct snd_dmaengine_dai_dma_data s3c_ac97_mic_in = { .addr_width = 4, }; static void s3c_ac97_activate(struct snd_ac97 *ac97) { u32 ac_glbctrl, stat; stat = readl(s3c_ac97.regs + S3C_AC97_GLBSTAT) & 0x7; if (stat == S3C_AC97_GLBSTAT_MAINSTATE_ACTIVE) return; /* Return if already active */ reinit_completion(&s3c_ac97.done); ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL); ac_glbctrl = S3C_AC97_GLBCTRL_ACLINKON; writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL); msleep(1); ac_glbctrl |= S3C_AC97_GLBCTRL_TRANSFERDATAENABLE; writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL); msleep(1); ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL); ac_glbctrl |= S3C_AC97_GLBCTRL_CODECREADYIE; writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL); if (!wait_for_completion_timeout(&s3c_ac97.done, HZ)) pr_err("AC97: Unable to activate!"); } static unsigned short s3c_ac97_read(struct snd_ac97 *ac97, unsigned short reg) { u32 ac_glbctrl, ac_codec_cmd; u32 stat, addr, data; mutex_lock(&s3c_ac97.lock); s3c_ac97_activate(ac97); reinit_completion(&s3c_ac97.done); ac_codec_cmd = readl(s3c_ac97.regs + S3C_AC97_CODEC_CMD); ac_codec_cmd = S3C_AC97_CODEC_CMD_READ | AC_CMD_ADDR(reg); writel(ac_codec_cmd, s3c_ac97.regs + S3C_AC97_CODEC_CMD); udelay(50); ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL); ac_glbctrl |= S3C_AC97_GLBCTRL_CODECREADYIE; writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL); if (!wait_for_completion_timeout(&s3c_ac97.done, HZ)) pr_err("AC97: Unable to read!"); stat = readl(s3c_ac97.regs + S3C_AC97_STAT); addr = (stat >> 16) & 0x7f; data = (stat & 0xffff); if (addr != reg) pr_err("ac97: req addr = %02x, rep addr = %02x\n", reg, addr); mutex_unlock(&s3c_ac97.lock); return (unsigned short)data; } static void s3c_ac97_write(struct snd_ac97 *ac97, unsigned short reg, unsigned short val) { u32 ac_glbctrl, ac_codec_cmd; mutex_lock(&s3c_ac97.lock); s3c_ac97_activate(ac97); reinit_completion(&s3c_ac97.done); ac_codec_cmd = readl(s3c_ac97.regs + S3C_AC97_CODEC_CMD); ac_codec_cmd = AC_CMD_ADDR(reg) | AC_CMD_DATA(val); writel(ac_codec_cmd, s3c_ac97.regs + S3C_AC97_CODEC_CMD); udelay(50); ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL); ac_glbctrl |= S3C_AC97_GLBCTRL_CODECREADYIE; writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL); if (!wait_for_completion_timeout(&s3c_ac97.done, HZ)) pr_err("AC97: Unable to write!"); ac_codec_cmd = readl(s3c_ac97.regs + S3C_AC97_CODEC_CMD); ac_codec_cmd |= S3C_AC97_CODEC_CMD_READ; writel(ac_codec_cmd, s3c_ac97.regs + S3C_AC97_CODEC_CMD); mutex_unlock(&s3c_ac97.lock); } static void s3c_ac97_cold_reset(struct snd_ac97 *ac97) { pr_debug("AC97: Cold reset\n"); writel(S3C_AC97_GLBCTRL_COLDRESET, s3c_ac97.regs + S3C_AC97_GLBCTRL); msleep(1); writel(0, s3c_ac97.regs + S3C_AC97_GLBCTRL); msleep(1); } static void s3c_ac97_warm_reset(struct snd_ac97 *ac97) { u32 stat; stat = readl(s3c_ac97.regs + S3C_AC97_GLBSTAT) & 0x7; if (stat == S3C_AC97_GLBSTAT_MAINSTATE_ACTIVE) return; /* Return if already active */ pr_debug("AC97: Warm reset\n"); writel(S3C_AC97_GLBCTRL_WARMRESET, s3c_ac97.regs + S3C_AC97_GLBCTRL); msleep(1); writel(0, s3c_ac97.regs + S3C_AC97_GLBCTRL); msleep(1); s3c_ac97_activate(ac97); } static irqreturn_t s3c_ac97_irq(int irq, void *dev_id) { u32 ac_glbctrl, ac_glbstat; ac_glbstat = readl(s3c_ac97.regs + S3C_AC97_GLBSTAT); if (ac_glbstat & S3C_AC97_GLBSTAT_CODECREADY) { ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL); ac_glbctrl &= ~S3C_AC97_GLBCTRL_CODECREADYIE; writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL); complete(&s3c_ac97.done); } ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL); ac_glbctrl |= (1<<30); /* Clear interrupt */ writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL); return IRQ_HANDLED; } static struct snd_ac97_bus_ops s3c_ac97_ops = { .read = s3c_ac97_read, .write = s3c_ac97_write, .warm_reset = s3c_ac97_warm_reset, .reset = s3c_ac97_cold_reset, }; static int s3c_ac97_trigger(struct snd_pcm_substream *substream, int cmd, struct snd_soc_dai *dai) { u32 ac_glbctrl; ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL); if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) ac_glbctrl &= ~S3C_AC97_GLBCTRL_PCMINTM_MASK; else ac_glbctrl &= ~S3C_AC97_GLBCTRL_PCMOUTTM_MASK; switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) ac_glbctrl |= S3C_AC97_GLBCTRL_PCMINTM_DMA; else ac_glbctrl |= S3C_AC97_GLBCTRL_PCMOUTTM_DMA; break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: break; } writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL); return 0; } static int s3c_ac97_mic_trigger(struct snd_pcm_substream *substream, int cmd, struct snd_soc_dai *dai) { u32 ac_glbctrl; ac_glbctrl = readl(s3c_ac97.regs + S3C_AC97_GLBCTRL); ac_glbctrl &= ~S3C_AC97_GLBCTRL_MICINTM_MASK; switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: ac_glbctrl |= S3C_AC97_GLBCTRL_MICINTM_DMA; break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: break; } writel(ac_glbctrl, s3c_ac97.regs + S3C_AC97_GLBCTRL); return 0; } static const struct snd_soc_dai_ops s3c_ac97_dai_ops = { .trigger = s3c_ac97_trigger, }; static const struct snd_soc_dai_ops s3c_ac97_mic_dai_ops = { .trigger = s3c_ac97_mic_trigger, }; static int s3c_ac97_dai_probe(struct snd_soc_dai *dai) { snd_soc_dai_init_dma_data(dai, &s3c_ac97_pcm_out, &s3c_ac97_pcm_in); return 0; } static int s3c_ac97_mic_dai_probe(struct snd_soc_dai *dai) { snd_soc_dai_init_dma_data(dai, NULL, &s3c_ac97_mic_in); return 0; } static struct snd_soc_dai_driver s3c_ac97_dai[] = { [S3C_AC97_DAI_PCM] = { .name = "samsung-ac97", .bus_control = true, .playback = { .stream_name = "AC97 Playback", .channels_min = 2, .channels_max = 2, .rates = SNDRV_PCM_RATE_8000_48000, .formats = SNDRV_PCM_FMTBIT_S16_LE,}, .capture = { .stream_name = "AC97 Capture", .channels_min = 2, .channels_max = 2, .rates = SNDRV_PCM_RATE_8000_48000, .formats = SNDRV_PCM_FMTBIT_S16_LE,}, .probe = s3c_ac97_dai_probe, .ops = &s3c_ac97_dai_ops, }, [S3C_AC97_DAI_MIC] = { .name = "samsung-ac97-mic", .bus_control = true, .capture = { .stream_name = "AC97 Mic Capture", .channels_min = 1, .channels_max = 1, .rates = SNDRV_PCM_RATE_8000_48000, .formats = SNDRV_PCM_FMTBIT_S16_LE,}, .probe = s3c_ac97_mic_dai_probe, .ops = &s3c_ac97_mic_dai_ops, }, }; static const struct snd_soc_component_driver s3c_ac97_component = { .name = "s3c-ac97", }; static int s3c_ac97_probe(struct platform_device *pdev) { struct resource *mem_res, *irq_res; struct s3c_audio_pdata *ac97_pdata; int ret; ac97_pdata = pdev->dev.platform_data; if (!ac97_pdata || !ac97_pdata->cfg_gpio) { dev_err(&pdev->dev, "cfg_gpio callback not provided!\n"); return -EINVAL; } /* Check for availability of necessary resource */ irq_res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); if (!irq_res) { dev_err(&pdev->dev, "AC97 IRQ not provided!\n"); return -ENXIO; } mem_res = platform_get_resource(pdev, IORESOURCE_MEM, 0); s3c_ac97.regs = devm_ioremap_resource(&pdev->dev, mem_res); if (IS_ERR(s3c_ac97.regs)) return PTR_ERR(s3c_ac97.regs); s3c_ac97_pcm_out.filter_data = ac97_pdata->dma_playback; s3c_ac97_pcm_out.addr = mem_res->start + S3C_AC97_PCM_DATA; s3c_ac97_pcm_in.filter_data = ac97_pdata->dma_capture; s3c_ac97_pcm_in.addr = mem_res->start + S3C_AC97_PCM_DATA; s3c_ac97_mic_in.filter_data = ac97_pdata->dma_capture_mic; s3c_ac97_mic_in.addr = mem_res->start + S3C_AC97_MIC_DATA; init_completion(&s3c_ac97.done); mutex_init(&s3c_ac97.lock); s3c_ac97.ac97_clk = devm_clk_get(&pdev->dev, "ac97"); if (IS_ERR(s3c_ac97.ac97_clk)) { dev_err(&pdev->dev, "ac97 failed to get ac97_clock\n"); ret = -ENODEV; goto err2; } clk_prepare_enable(s3c_ac97.ac97_clk); if (ac97_pdata->cfg_gpio(pdev)) { dev_err(&pdev->dev, "Unable to configure gpio\n"); ret = -EINVAL; goto err3; } ret = request_irq(irq_res->start, s3c_ac97_irq, 0, "AC97", NULL); if (ret < 0) { dev_err(&pdev->dev, "ac97: interrupt request failed.\n"); goto err4; } ret = snd_soc_set_ac97_ops(&s3c_ac97_ops); if (ret != 0) { dev_err(&pdev->dev, "Failed to set AC'97 ops: %d\n", ret); goto err4; } ret = devm_snd_soc_register_component(&pdev->dev, &s3c_ac97_component, s3c_ac97_dai, ARRAY_SIZE(s3c_ac97_dai)); if (ret) goto err5; ret = samsung_asoc_dma_platform_register(&pdev->dev, ac97_pdata->dma_filter, NULL, NULL); if (ret) { dev_err(&pdev->dev, "failed to get register DMA: %d\n", ret); goto err5; } return 0; err5: free_irq(irq_res->start, NULL); err4: err3: clk_disable_unprepare(s3c_ac97.ac97_clk); err2: snd_soc_set_ac97_ops(NULL); return ret; } static int s3c_ac97_remove(struct platform_device *pdev) { struct resource *irq_res; irq_res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); if (irq_res) free_irq(irq_res->start, NULL); clk_disable_unprepare(s3c_ac97.ac97_clk); snd_soc_set_ac97_ops(NULL); return 0; } static struct platform_driver s3c_ac97_driver = { .probe = s3c_ac97_probe, .remove = s3c_ac97_remove, .driver = { .name = "samsung-ac97", }, }; module_platform_driver(s3c_ac97_driver); MODULE_AUTHOR("Jaswinder Singh, <jassisinghbrar@gmail.com>"); MODULE_DESCRIPTION("AC97 driver for the Samsung SoC"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:samsung-ac97");
AndyLavr/Aspire-SW5-012_Kernel_4.8
sound/soc/samsung/ac97.c
C
gpl-2.0
10,915
/* * drivers/video/chipsfb.c -- frame buffer device for * Chips & Technologies 65550 chip. * * Copyright (C) 1998-2002 Paul Mackerras * * This file is derived from the Powermac "chips" driver: * Copyright (C) 1997 Fabio Riccardi. * And from the frame buffer device for Open Firmware-initialized devices: * Copyright (C) 1997 Geert Uytterhoeven. * * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of this archive for * more details. */ #include <linux/config.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/tty.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/fb.h> #include <linux/init.h> #include <linux/pci.h> #include <asm/io.h> #ifdef CONFIG_PMAC_BACKLIGHT #include <asm/backlight.h> #endif #ifdef CONFIG_PMAC_PBOOK #include <linux/adb.h> #include <linux/pmu.h> #endif /* * Since we access the display with inb/outb to fixed port numbers, * we can only handle one 6555x chip. -- paulus */ static struct fb_info chipsfb_info; #define write_ind(num, val, ap, dp) do { \ outb((num), (ap)); outb((val), (dp)); \ } while (0) #define read_ind(num, var, ap, dp) do { \ outb((num), (ap)); var = inb((dp)); \ } while (0) /* extension registers */ #define write_xr(num, val) write_ind(num, val, 0x3d6, 0x3d7) #define read_xr(num, var) read_ind(num, var, 0x3d6, 0x3d7) /* flat panel registers */ #define write_fr(num, val) write_ind(num, val, 0x3d0, 0x3d1) #define read_fr(num, var) read_ind(num, var, 0x3d0, 0x3d1) /* CRTC registers */ #define write_cr(num, val) write_ind(num, val, 0x3d4, 0x3d5) #define read_cr(num, var) read_ind(num, var, 0x3d4, 0x3d5) /* graphics registers */ #define write_gr(num, val) write_ind(num, val, 0x3ce, 0x3cf) #define read_gr(num, var) read_ind(num, var, 0x3ce, 0x3cf) /* sequencer registers */ #define write_sr(num, val) write_ind(num, val, 0x3c4, 0x3c5) #define read_sr(num, var) read_ind(num, var, 0x3c4, 0x3c5) /* attribute registers - slightly strange */ #define write_ar(num, val) do { \ inb(0x3da); write_ind(num, val, 0x3c0, 0x3c0); \ } while (0) #define read_ar(num, var) do { \ inb(0x3da); read_ind(num, var, 0x3c0, 0x3c1); \ } while (0) #ifdef CONFIG_PMAC_PBOOK static unsigned char *save_framebuffer; int chips_sleep_notify(struct pmu_sleep_notifier *self, int when); static struct pmu_sleep_notifier chips_sleep_notifier = { chips_sleep_notify, SLEEP_LEVEL_VIDEO, }; #endif /* * Exported functions */ int chips_init(void); static int chipsfb_pci_init(struct pci_dev *dp, const struct pci_device_id *); static int chipsfb_check_var(struct fb_var_screeninfo *var, struct fb_info *info); static int chipsfb_set_par(struct fb_info *info); static int chipsfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue, u_int transp, struct fb_info *info); static int chipsfb_blank(int blank, struct fb_info *info); static struct fb_ops chipsfb_ops = { .owner = THIS_MODULE, .fb_check_var = chipsfb_check_var, .fb_set_par = chipsfb_set_par, .fb_setcolreg = chipsfb_setcolreg, .fb_blank = chipsfb_blank, .fb_fillrect = cfb_fillrect, .fb_copyarea = cfb_copyarea, .fb_imageblit = cfb_imageblit, .fb_cursor = soft_cursor, }; static int chipsfb_check_var(struct fb_var_screeninfo *var, struct fb_info *info) { if (var->xres > 800 || var->yres > 600 || var->xres_virtual > 800 || var->yres_virtual > 600 || (var->bits_per_pixel != 8 && var->bits_per_pixel != 16) || var->nonstd || (var->vmode & FB_VMODE_MASK) != FB_VMODE_NONINTERLACED) return -EINVAL; var->xres = var->xres_virtual = 800; var->yres = var->yres_virtual = 600; return 0; } static int chipsfb_set_par(struct fb_info *info) { if (info->var.bits_per_pixel == 16) { write_cr(0x13, 200); // Set line length (doublewords) write_xr(0x81, 0x14); // 15 bit (555) color mode write_xr(0x82, 0x00); // Disable palettes write_xr(0x20, 0x10); // 16 bit blitter mode info->fix.line_length = 800*2; info->fix.visual = FB_VISUAL_TRUECOLOR; info->var.red.offset = 10; info->var.green.offset = 5; info->var.blue.offset = 0; info->var.red.length = info->var.green.length = info->var.blue.length = 5; } else { /* p->var.bits_per_pixel == 8 */ write_cr(0x13, 100); // Set line length (doublewords) write_xr(0x81, 0x12); // 8 bit color mode write_xr(0x82, 0x08); // Graphics gamma enable write_xr(0x20, 0x00); // 8 bit blitter mode info->fix.line_length = 800; info->fix.visual = FB_VISUAL_PSEUDOCOLOR; info->var.red.offset = info->var.green.offset = info->var.blue.offset = 0; info->var.red.length = info->var.green.length = info->var.blue.length = 8; } return 0; } static int chipsfb_blank(int blank, struct fb_info *info) { #ifdef CONFIG_PMAC_BACKLIGHT // used to disable backlight only for blank > 1, but it seems // useful at blank = 1 too (saves battery, extends backlight life) set_backlight_enable(!blank); #endif /* CONFIG_PMAC_BACKLIGHT */ return 1; /* get fb_blank to set the colormap to all black */ } static int chipsfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue, u_int transp, struct fb_info *info) { if (regno > 255) return 1; red >>= 8; green >>= 8; blue >>= 8; outb(regno, 0x3c8); udelay(1); outb(red, 0x3c9); outb(green, 0x3c9); outb(blue, 0x3c9); return 0; } struct chips_init_reg { unsigned char addr; unsigned char data; }; #define N_ELTS(x) (sizeof(x) / sizeof(x[0])) static struct chips_init_reg chips_init_sr[] = { { 0x00, 0x03 }, { 0x01, 0x01 }, { 0x02, 0x0f }, { 0x04, 0x0e } }; static struct chips_init_reg chips_init_gr[] = { { 0x05, 0x00 }, { 0x06, 0x0d }, { 0x08, 0xff } }; static struct chips_init_reg chips_init_ar[] = { { 0x10, 0x01 }, { 0x12, 0x0f }, { 0x13, 0x00 } }; static struct chips_init_reg chips_init_cr[] = { { 0x00, 0x7f }, { 0x01, 0x63 }, { 0x02, 0x63 }, { 0x03, 0x83 }, { 0x04, 0x66 }, { 0x05, 0x10 }, { 0x06, 0x72 }, { 0x07, 0x3e }, { 0x08, 0x00 }, { 0x09, 0x40 }, { 0x0c, 0x00 }, { 0x0d, 0x00 }, { 0x10, 0x59 }, { 0x11, 0x0d }, { 0x12, 0x57 }, { 0x13, 0x64 }, { 0x14, 0x00 }, { 0x15, 0x57 }, { 0x16, 0x73 }, { 0x17, 0xe3 }, { 0x18, 0xff }, { 0x30, 0x02 }, { 0x31, 0x02 }, { 0x32, 0x02 }, { 0x33, 0x02 }, { 0x40, 0x00 }, { 0x41, 0x00 }, { 0x40, 0x80 } }; static struct chips_init_reg chips_init_fr[] = { { 0x01, 0x02 }, { 0x03, 0x08 }, { 0x04, 0x81 }, { 0x05, 0x21 }, { 0x08, 0x0c }, { 0x0a, 0x74 }, { 0x0b, 0x11 }, { 0x10, 0x0c }, { 0x11, 0xe0 }, /* { 0x12, 0x40 }, -- 3400 needs 40, 2400 needs 48, no way to tell */ { 0x20, 0x63 }, { 0x21, 0x68 }, { 0x22, 0x19 }, { 0x23, 0x7f }, { 0x24, 0x68 }, { 0x26, 0x00 }, { 0x27, 0x0f }, { 0x30, 0x57 }, { 0x31, 0x58 }, { 0x32, 0x0d }, { 0x33, 0x72 }, { 0x34, 0x02 }, { 0x35, 0x22 }, { 0x36, 0x02 }, { 0x37, 0x00 } }; static struct chips_init_reg chips_init_xr[] = { { 0xce, 0x00 }, /* set default memory clock */ { 0xcc, 0x43 }, /* memory clock ratio */ { 0xcd, 0x18 }, { 0xce, 0xa1 }, { 0xc8, 0x84 }, { 0xc9, 0x0a }, { 0xca, 0x00 }, { 0xcb, 0x20 }, { 0xcf, 0x06 }, { 0xd0, 0x0e }, { 0x09, 0x01 }, { 0x0a, 0x02 }, { 0x0b, 0x01 }, { 0x20, 0x00 }, { 0x40, 0x03 }, { 0x41, 0x01 }, { 0x42, 0x00 }, { 0x80, 0x82 }, { 0x81, 0x12 }, { 0x82, 0x08 }, { 0xa0, 0x00 }, { 0xa8, 0x00 } }; static void __init chips_hw_init(void) { int i; for (i = 0; i < N_ELTS(chips_init_xr); ++i) write_xr(chips_init_xr[i].addr, chips_init_xr[i].data); outb(0x29, 0x3c2); /* set misc output reg */ for (i = 0; i < N_ELTS(chips_init_sr); ++i) write_sr(chips_init_sr[i].addr, chips_init_sr[i].data); for (i = 0; i < N_ELTS(chips_init_gr); ++i) write_gr(chips_init_gr[i].addr, chips_init_gr[i].data); for (i = 0; i < N_ELTS(chips_init_ar); ++i) write_ar(chips_init_ar[i].addr, chips_init_ar[i].data); for (i = 0; i < N_ELTS(chips_init_cr); ++i) write_cr(chips_init_cr[i].addr, chips_init_cr[i].data); for (i = 0; i < N_ELTS(chips_init_fr); ++i) write_fr(chips_init_fr[i].addr, chips_init_fr[i].data); } static struct fb_fix_screeninfo chipsfb_fix __initdata = { .id = "C&T 65550", .type = FB_TYPE_PACKED_PIXELS, .visual = FB_VISUAL_PSEUDOCOLOR, .accel = FB_ACCEL_NONE, .line_length = 800, // FIXME: Assumes 1MB frame buffer, but 65550 supports 1MB or 2MB. // * "3500" PowerBook G3 (the original PB G3) has 2MB. // * 2400 has 1MB composed of 2 Mitsubishi M5M4V4265CTP DRAM chips. // Motherboard actually supports 2MB -- there are two blank locations // for a second pair of DRAMs. (Thanks, Apple!) // * 3400 has 1MB (I think). Don't know if it's expandable. // -- Tim Seufert .smem_len = 0x100000, /* 1MB */ }; static struct fb_var_screeninfo chipsfb_var __initdata = { .xres = 800, .yres = 600, .xres_virtual = 800, .yres_virtual = 600, .bits_per_pixel = 8, .red = { .length = 8 }, .green = { .length = 8 }, .blue = { .length = 8 }, .height = -1, .width = -1, .vmode = FB_VMODE_NONINTERLACED, .pixclock = 10000, .left_margin = 16, .right_margin = 16, .upper_margin = 16, .lower_margin = 16, .hsync_len = 8, .vsync_len = 8, }; static void __init init_chips(struct fb_info *p, unsigned long addr) { p->fix = chipsfb_fix; p->fix.smem_start = addr; p->var = chipsfb_var; p->fbops = &chipsfb_ops; p->flags = FBINFO_DEFAULT; fb_alloc_cmap(&p->cmap, 256, 0); if (register_framebuffer(p) < 0) { printk(KERN_ERR "C&T 65550 framebuffer failed to register\n"); return; } printk(KERN_INFO "fb%d: Chips 65550 frame buffer (%dK RAM detected)\n", p->node, p->fix.smem_len / 1024); chips_hw_init(); } static int __devinit chipsfb_pci_init(struct pci_dev *dp, const struct pci_device_id *ent) { struct fb_info *p = &chipsfb_info; unsigned long addr, size; unsigned short cmd; if ((dp->resource[0].flags & IORESOURCE_MEM) == 0) return -ENODEV; addr = pci_resource_start(dp, 0); size = pci_resource_len(dp, 0); if (addr == 0) return -ENODEV; if (p->screen_base != 0) return -EBUSY; if (!request_mem_region(addr, size, "chipsfb")) return -EBUSY; #ifdef __BIG_ENDIAN addr += 0x800000; // Use big-endian aperture #endif /* we should use pci_enable_device here, but, the device doesn't declare its I/O ports in its BARs so pci_enable_device won't turn on I/O responses */ pci_read_config_word(dp, PCI_COMMAND, &cmd); cmd |= 3; /* enable memory and IO space */ pci_write_config_word(dp, PCI_COMMAND, cmd); #ifdef CONFIG_PMAC_BACKLIGHT /* turn on the backlight */ set_backlight_enable(1); #endif /* CONFIG_PMAC_BACKLIGHT */ p->screen_base = __ioremap(addr, 0x200000, _PAGE_NO_CACHE); if (p->screen_base == NULL) { release_mem_region(addr, size); return -ENOMEM; } init_chips(p, addr); #ifdef CONFIG_PMAC_PBOOK pmu_register_sleep_notifier(&chips_sleep_notifier); #endif /* CONFIG_PMAC_PBOOK */ /* Clear the entire framebuffer */ memset(p->screen_base, 0, 0x100000); pci_set_drvdata(dp, p); return 0; } static void __devexit chipsfb_remove(struct pci_dev *dp) { struct fb_info *p = pci_get_drvdata(dp); if (p != &chipsfb_info || p->screen_base == NULL) return; unregister_framebuffer(p); iounmap(p->screen_base); p->screen_base = NULL; release_mem_region(pci_resource_start(dp, 0), pci_resource_len(dp, 0)); #ifdef CONFIG_PMAC_PBOOK pmu_unregister_sleep_notifier(&chips_sleep_notifier); #endif /* CONFIG_PMAC_PBOOK */ } static struct pci_device_id chipsfb_pci_tbl[] = { { PCI_VENDOR_ID_CT, PCI_DEVICE_ID_CT_65550, PCI_ANY_ID, PCI_ANY_ID }, { 0 } }; MODULE_DEVICE_TABLE(pci, chipsfb_pci_tbl); static struct pci_driver chipsfb_driver = { .name = "chipsfb", .id_table = chipsfb_pci_tbl, .probe = chipsfb_pci_init, .remove = __devexit_p(chipsfb_remove), }; int __init chips_init(void) { if (fb_get_options("chipsfb", NULL)) return -ENODEV; return pci_module_init(&chipsfb_driver); } module_init(chips_init); static void __exit chipsfb_exit(void) { pci_unregister_driver(&chipsfb_driver); } #ifdef CONFIG_PMAC_PBOOK /* * Save the contents of the frame buffer when we go to sleep, * and restore it when we wake up again. */ int chips_sleep_notify(struct pmu_sleep_notifier *self, int when) { struct fb_info *p = &chipsfb_info; int nb = p->var.yres * p->fix.line_length; if (p->screen_base == NULL) return PBOOK_SLEEP_OK; switch (when) { case PBOOK_SLEEP_REQUEST: save_framebuffer = vmalloc(nb); if (save_framebuffer == NULL) return PBOOK_SLEEP_REFUSE; break; case PBOOK_SLEEP_REJECT: if (save_framebuffer) { vfree(save_framebuffer); save_framebuffer = NULL; } break; case PBOOK_SLEEP_NOW: chipsfb_blank(1, p); if (save_framebuffer) memcpy(save_framebuffer, p->screen_base, nb); break; case PBOOK_WAKE: if (save_framebuffer) { memcpy(p->screen_base, save_framebuffer, nb); vfree(save_framebuffer); save_framebuffer = NULL; } chipsfb_blank(0, p); break; } return PBOOK_SLEEP_OK; } #endif /* CONFIG_PMAC_PBOOK */ MODULE_LICENSE("GPL");
dduval/kernel-rhel4
drivers/video/chipsfb.c
C
gpl-2.0
13,132
<?php /* class pluginbuddy_filesystem * @author Dustin Bolton * * Handles interfacing with the file system. */ class pb_backupbuddy_filesystem { // ********** PUBLIC PROPERTIES ********** // ********** PRIVATE PROPERTIES ********** // ********** FUNCTIONS ********** /* pluginbuddy_filesystem->__construct() * * Default constructor. * * @return null */ function __construct() { } // End __construct(). /* pb_backupbuddy::$filesystem->mkdir() * * mkdir that defaults to recursive behaviour. 99% of the time this is what we want. * * @param $pathname string Path to create. * @param $mode int Default: 0777. See PHP's mkdir() function for details. * @param $recursive boolean Default: true. See PHP's mkdir() function for details. * @return boolean Returns TRUE on success or FALSE on failure. */ public static function mkdir( $pathname, $mode = 0777, $recursive = true) { return @mkdir( $pathname, $mode, $recursive ); } // End mkdir(). /* pluginbuddy_filesystem->unlink_recursive() * * Unlink a directory recursively. Files all files and directories within. USE WITH CAUTION. * * @param string $dir Directory to delete -- all contents within, subdirectories, files, etc will be permanently deleted. * @return boolean True on success; else false. */ function unlink_recursive( $dir ) { if ( defined( 'PB_DEMO_MODE' ) ) { return false; } if ( !file_exists( $dir ) ) { return true; } if ( !is_dir( $dir ) || is_link( $dir ) ) { return unlink($dir); } foreach ( scandir( $dir ) as $item ) { if ( $item == '.' || $item == '..' ) { continue; } if ( !$this->unlink_recursive( $dir . "/" . $item ) ) { @chmod( $dir . "/" . $item, 0777 ); if ( !$this->unlink_recursive( $dir . "/" . $item ) ) { return false; } } } return @rmdir($dir); } // End unlink_recursive(). /** * pluginbuddy_filesystem->deepglob() * * Like the glob() function except walks down into paths to create a full listing of all results in the directory and all subdirectories. * This is essentially a recursive glob() although it does not use recursion to perform this. * * @param string $dir Path to pass to glob and walk through. * @return array Returns array of all matches found. */ function deepglob( $dir ) { $items = glob( $dir . '/*' ); for ( $i = 0; $i < count( $items ); $i++ ) { if ( is_dir( $items[$i] ) ) { $add = glob( $items[$i] . '/*' ); $items = array_merge( $items, $add ); } } return $items; } // End deepglob(). function recursive_copy( $src, $dst ) { //pb_backupbuddy::status( 'details', 'Copying `' . $src . '` to `' . $dst . '`.' ); if ( is_dir( $src ) ) { pb_backupbuddy::status( 'details', 'Copying directory `' . $src . '` to `' . $dst . '` recursively.' ); @$this->mkdir( $dst, 0777 ); $files = scandir($src); foreach ( $files as $file ) { if ($file != "." && $file != "..") { $this->recursive_copy("$src/$file", "$dst/$file"); } } } elseif ( file_exists( $src ) ) { @copy( $src, $dst ); // Todo: should this need suppression? Media copying was throwing $dst is directory errors. } } // RH added; from Chris? /* public function custom_copy( $source, $destination, $args = array() ) { $default_args = array( 'max_depth' => 100, 'folder_mode' => 0755, 'file_mode' => 0744, 'ignore_files' => array(), ); $args = array_merge( $default_args, $args ); return $this->_custom_copy( $source, $destination, $args ); } // End custom_copy(). private function _custom_copy( $source, $destination, $args, $depth = 0 ) { if ( $depth > $args['max_depth'] ) return true; if ( in_array( basename( $source ), $args[ 'ignore_files' ] ) ) return true; if ( is_file( $source ) ) { if ( is_dir( $destination ) || preg_match( '|/$|', $destination ) ) { $destination = preg_replace( '|/+$|', '', $destination ); $destination = "$destination/" . basename( $source ); } if ( false === $this->mkdir( dirname( $destination ), $args['folder_mode'] ) ) return false; if ( false === @copy( $source, $destination ) ) return false; @chmod( $destination, $args['file_mode'] ); return true; } else if ( is_dir( $source ) || preg_match( '|/\*$|', $source ) ) { if ( preg_match( '|/\*$|', $source ) ) $source = preg_replace( '|/\*$|', '', $source ); else if ( preg_match( '|/$|', $destination ) ) $destination = $destination . basename( $source ); $destination = preg_replace( '|/$|', '', $destination ); $files = array_diff( array_merge( glob( $source . '/.*' ), glob( $source . '/*' ) ), array( $source . '/.', $source . '/..' ) ); if ( false === @mkdir( $destination ) ) return false; $result = true; foreach ( (array) $files as $file ) { if ( false === $this->_custom_copy( $file, "$destination/", $args, $depth + 1 ) ) $result = false; } return $result; } return false; } // End _copy(). */ // todo: document // $exclusions is never modified so just use PHP's copy on modify default behaviour for memory management. /* function_name() * * function description * @param array/bool Array of directory paths to exclude. If true then this directory is excluded so no need to check with exclusion directory. * @return array array( TOTAL_DIRECTORY_SIZE, TOTAL_SIZE_WITH_EXCLUSIONS_TAKEN_INTO_ACCOUNT, OBJECTS_FOUND, OBJECTS_FOUND_WITH_EXCLUSIONS ) */ function dir_size_map( $dir, $base, $exclusions, &$dir_array ) { $dir = rtrim( $dir, '/\\' ); // Force no trailing slash. if( !is_dir( $dir ) ) { return 0; } $ret = 0; $ret_with_exclusions = 0; $ret_objects = 0; $ret_objects_with_exclusions = 0; $exclusions_result = $exclusions; $sub = @opendir( $dir ); if ( false === $sub ) { // Cannot access. pb_backupbuddy::alert( 'Error #568385: Unable to access directory: `' . $dir . '`. Verify proper permissions.', true ); return 0; } else { while( $file = readdir( $sub ) ) { $exclusions_result = $exclusions; $dir_path = '/' . str_replace( $base, '', $dir . '/' . $file ) . '/'; //str_replace( $base, '', $dir . $file . '/' ); if ( ( $file == '.' ) || ( $file == '..' ) ) { // Do nothing. } elseif ( is_dir( $dir . '/' . $file ) ) { // DIRECTORY. if ( ( $exclusions === true ) || self::in_array_substr( $exclusions, $dir_path, '/' ) ) { $exclusions_result = true; } $result = $this->dir_size_map( $dir . '/' . $file . '/', $base, $exclusions, $dir_array ); $this_size = $result[0]; $this_objects = $result[2]; if ( $exclusions_result === true ) { // If excluding then wipe excluded value. $this_size_with_exclusions = false; $this_objects_with_exclusions = 0; } else { $this_size_with_exclusions = $result[1]; // / 1048576 ); $this_objects_with_exclusions = $result[3]; // / 1048576 ); } $dir_array[ $dir_path ] = array( $this_size, $this_size_with_exclusions, $this_objects, $this_objects_with_exclusions ); // $dir_array[ DIRECTORY_PATH ] = DIRECTORY_SIZE; $ret += $this_size; $ret_objects += $this_objects; $ret_with_exclusions += $this_size_with_exclusions; $ret_objects_with_exclusions += $this_objects_with_exclusions; unset( $file ); } else { // FILE. $stats = @stat( $dir . '/' . $file ); if ( is_array( $stats ) ) { $ret += $stats['size']; $ret_objects++; if ( ( $exclusions !== true ) && !in_array( $dir_path, $exclusions ) ) { // Not excluding. $ret_with_exclusions += $stats['size']; $ret_objects_with_exclusions++; } } unset( $file ); } } closedir( $sub ); unset( $sub ); return array( $ret, $ret_with_exclusions, $ret_objects, $ret_objects_with_exclusions ); } } // End dir_size_map(). public static function in_array_substr( $haystack, $needle, $trailing = '' ) { foreach( $haystack as $hay ) { if ( ( $hay . $trailing ) == substr( $needle . $trailing, 0, strlen( $hay . $trailing ) ) ) { //echo $needle . '~' . $hay . '<br>'; return true; } } return false; } public function exit_code_lookup( $code ) { switch( (string)$code ) { case '0': return 'Command completed & returned normally.'; break; case '127': return 'Command not found.'; break; case '152': return 'SIGXCPU 152; CPU time limit exceeded.'; break; case '153': return 'SIGXFSZ 153; File size limit exceeded. Verify enough free space exists & filesystem max size not exceeded.'; break; case '158': return 'SIGXCPU 158; CPU time limit exceeded.'; break; case '159': return 'SIGXFSZ 159; File size limit exceeded. Verify enough free space exists & filesystem max size not exceeded.'; break; default: return '-No information available for this exit code- See: https://wiki.ncsa.illinois.edu/display/MRDPUB/Batch+Exit+Codes '; break; } } // Newest to oldest. function glob_by_date( $pattern ) { $file_array = array(); $glob_result = glob( $pattern ); if ( ! is_array( $glob_result ) ) { $glob_result = array(); } foreach ( $glob_result as $filename ) { $ctime = filectime( $filename ); while( isset( $file_array[$ctime] ) ) { // Avoid collisions. $ctime = $ctime + 0.1; } $file_array[$ctime] = $filename; // or just $filename } krsort( $file_array ); return $file_array; } // End glob_by_date(). } // End class pluginbuddy_settings. ?>
jaystonez/jjj
wp-content/plugins/new plugs/backupbuddy/pluginbuddy/classes/filesystem.php
PHP
gpl-2.0
9,764
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Various checks and message functions used on index page. * * @package PhpMyAdmin-Setup */ if (!defined('PHPMYADMIN')) { exit; } /** * Initializes message list * * @return void */ function messages_begin() { if (! isset($_SESSION['messages']) || !is_array($_SESSION['messages'])) { $_SESSION['messages'] = array('error' => array(), 'notice' => array()); } else { // reset message states foreach ($_SESSION['messages'] as &$messages) { foreach ($messages as &$msg) { $msg['fresh'] = false; $msg['active'] = false; } } } } /** * Adds a new message to message list * * @param string $type one of: notice, error * @param string $id unique message identifier * @param string $title language string id (in $str array) * @param string $message message text * * @return void */ function messages_set($type, $id, $title, $message) { $fresh = ! isset($_SESSION['messages'][$type][$id]); $_SESSION['messages'][$type][$id] = array( 'fresh' => $fresh, 'active' => true, 'title' => $title, 'message' => $message); } /** * Cleans up message list * * @return void */ function messages_end() { foreach ($_SESSION['messages'] as &$messages) { $remove_ids = array(); foreach ($messages as $id => &$msg) { if ($msg['active'] == false) { $remove_ids[] = $id; } } foreach ($remove_ids as $id) { unset($messages[$id]); } } } /** * Prints message list, must be called after messages_end() * * @return void */ function messages_show_html() { $old_ids = array(); foreach ($_SESSION['messages'] as $type => $messages) { foreach ($messages as $id => $msg) { echo '<div class="' . $type . '" id="' . $id . '">' . '<h4>' . $msg['title'] . '</h4>' . $msg['message'] . '</div>'; if (!$msg['fresh'] && $type != 'error') { $old_ids[] = $id; } } } echo "\n" . '<script type="text/javascript">'; foreach ($old_ids as $id) { echo "\nhiddenMessages.push('$id');"; } echo "\n</script>\n"; } /** * Checks for newest phpMyAdmin version and sets result as a new notice * * @return void */ function PMA_version_check() { // version check messages should always be visible so let's make // a unique message id each time we run it $message_id = uniqid('version_check'); // wait 3s at most for server response, it's enough to get information // from a working server $connection_timeout = 3; $url = 'http://phpmyadmin.net/home_page/version.json'; $context = stream_context_create( array( 'http' => array('timeout' => $connection_timeout) ) ); $data = @file_get_contents($url, null, $context); if ($data === false) { if (function_exists('curl_init')) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, $connection_timeout); $data = curl_exec($ch); curl_close($ch); } else { messages_set( 'error', $message_id, __('Version check'), __('Neither URL wrapper nor CURL is available. Version check is not possible.') ); return; } } if (empty($data)) { messages_set( 'error', $message_id, __('Version check'), __('Reading of version failed. Maybe you\'re offline or the upgrade server does not respond.') ); return; } $data_list = json_decode($data); $releases = $data_list->releases; $latestCompatible = PMA_Util::getLatestCompatibleVersion($releases); if ($latestCompatible != null) { $version = $latestCompatible['version']; $date = $latestCompatible['date']; } else { return; } $version_upstream = version_to_int($version); if ($version_upstream === false) { messages_set( 'error', $message_id, __('Version check'), __('Got invalid version string from server') ); return; } $version_local = version_to_int($GLOBALS['PMA_Config']->get('PMA_VERSION')); if ($version_local === false) { messages_set( 'error', $message_id, __('Version check'), __('Unparsable version string') ); return; } if ($version_upstream > $version_local) { $version = htmlspecialchars($version); $date = htmlspecialchars($date); messages_set( 'notice', $message_id, __('Version check'), sprintf(__('A newer version of phpMyAdmin is available and you should consider upgrading. The newest version is %s, released on %s.'), $version, $date) ); } else { if ($version_local % 100 == 0) { messages_set( 'notice', $message_id, __('Version check'), PMA_sanitize(sprintf(__('You are using Git version, run [kbd]git pull[/kbd] :-)[br]The latest stable version is %s, released on %s.'), $version, $date)) ); } else { messages_set( 'notice', $message_id, __('Version check'), __('No newer stable version is available') ); } } } /** * Calculates numerical equivalent of phpMyAdmin version string * * @param string $version version * * @return mixed false on failure, integer on success */ function version_to_int($version) { $matches = array(); if (!preg_match('/^(\d+)\.(\d+)\.(\d+)((\.|-(pl|rc|dev|beta|alpha))(\d+)?(-dev)?)?$/', $version, $matches)) { return false; } if (!empty($matches[6])) { switch ($matches[6]) { case 'pl': $added = 60; break; case 'rc': $added = 30; break; case 'beta': $added = 20; break; case 'alpha': $added = 10; break; case 'dev': $added = 0; break; default: messages_set( 'notice', 'version_match', __('Version check'), 'Unknown version part: ' . htmlspecialchars($matches[6]) ); $added = 0; break; } } else { $added = 50; // for final } if (!empty($matches[7])) { $added = $added + $matches[7]; } return $matches[1] * 1000000 + $matches[2] * 10000 + $matches[3] * 100 + $added; } /** * Checks whether config file is readable/writable * * @param bool &$is_readable * @param bool &$is_writable * @param bool &$file_exists * * @return void */ function check_config_rw(&$is_readable, &$is_writable, &$file_exists) { $file_path = ConfigFile::getInstance()->getFilePath(); $file_dir = dirname($file_path); $is_readable = true; $is_writable = is_dir($file_dir); if (SETUP_DIR_WRITABLE) { $is_writable = $is_writable && is_writable($file_dir); } $file_exists = file_exists($file_path); if ($file_exists) { $is_readable = is_readable($file_path); $is_writable = $is_writable && is_writable($file_path); } } /** * Performs various compatibility, security and consistency checks on current config * * Outputs results to message list, must be called between messages_begin() * and messages_end() * * @return void */ function perform_config_checks() { $cf = ConfigFile::getInstance(); $blowfish_secret = $cf->get('blowfish_secret'); $blowfish_secret_set = false; $cookie_auth_used = false; $strAllowArbitraryServerWarning = __('This %soption%s should be disabled as it allows attackers to bruteforce login to any MySQL server. If you feel this is necessary, use %strusted proxies list%s. However, IP-based protection may not be reliable if your IP belongs to an ISP where thousands of users, including you, are connected to.'); $strAllowArbitraryServerWarning = sprintf($strAllowArbitraryServerWarning, '[a@?page=form&amp;formset=Features#tab_Security]', '[/a]', '[a@?page=form&amp;formset=Features#tab_Security]', '[/a]'); $strBlowfishSecretMsg = __('You didn\'t have blowfish secret set and have enabled cookie authentication, so a key was automatically generated for you. It is used to encrypt cookies; you don\'t need to remember it.'); $strBZipDumpWarning = __('%sBzip2 compression and decompression%s requires functions (%s) which are unavailable on this system.'); $strBZipDumpWarning = sprintf($strBZipDumpWarning, '[a@?page=form&amp;formset=Features#tab_Import_export]', '[/a]', '%s'); $strDirectoryNotice = __('This value should be double checked to ensure that this directory is neither world accessible nor readable or writable by other users on your server.'); $strForceSSLNotice = __('This %soption%s should be enabled if your web server supports it.'); $strForceSSLNotice = sprintf($strForceSSLNotice, '[a@?page=form&amp;formset=Features#tab_Security]', '[/a]'); $strGZipDumpWarning = __('%sGZip compression and decompression%s requires functions (%s) which are unavailable on this system.'); $strGZipDumpWarning = sprintf($strGZipDumpWarning, '[a@?page=form&amp;formset=Features#tab_Import_export]', '[/a]', '%s'); $strLoginCookieValidityWarning = __('%sLogin cookie validity%s greater than 1440 seconds may cause random session invalidation if %ssession.gc_maxlifetime%s is lower than its value (currently %d).'); $strLoginCookieValidityWarning = sprintf($strLoginCookieValidityWarning, '[a@?page=form&amp;formset=Features#tab_Security]', '[/a]', '[a@' . PMA_getPHPDocLink('session.configuration.php#ini.session.gc-maxlifetime') . ']', '[/a]', ini_get('session.gc_maxlifetime')); $strLoginCookieValidityWarning2 = __('%sLogin cookie validity%s should be set to 1800 seconds (30 minutes) at most. Values larger than 1800 may pose a security risk such as impersonation.'); $strLoginCookieValidityWarning2 = sprintf($strLoginCookieValidityWarning2, '[a@?page=form&amp;formset=Features#tab_Security]', '[/a]'); $strLoginCookieValidityWarning3 = __('If using cookie authentication and %sLogin cookie store%s is not 0, %sLogin cookie validity%s must be set to a value less or equal to it.'); $strLoginCookieValidityWarning3 = sprintf($strLoginCookieValidityWarning3, '[a@?page=form&amp;formset=Features#tab_Security]', '[/a]', '[a@?page=form&amp;formset=Features#tab_Security]', '[/a]'); $strSecurityInfoMsg = __('If you feel this is necessary, use additional protection settings - %shost authentication%s settings and %strusted proxies list%s. However, IP-based protection may not be reliable if your IP belongs to an ISP where thousands of users, including you, are connected to.'); $strSecurityInfoMsg = sprintf($strSecurityInfoMsg, '[a@?page=servers&amp;mode=edit&amp;id=%1$d#tab_Server_config]', '[/a]', '[a@?page=form&amp;formset=Features#tab_Security]', '[/a]'); $strServerAuthConfigMsg = __('You set the [kbd]config[/kbd] authentication type and included username and password for auto-login, which is not a desirable option for live hosts. Anyone who knows or guesses your phpMyAdmin URL can directly access your phpMyAdmin panel. Set %sauthentication type%s to [kbd]cookie[/kbd] or [kbd]http[/kbd].'); $strServerAuthConfigMsg = sprintf($strServerAuthConfigMsg, '[a@?page=servers&amp;mode=edit&amp;id=%1$d#tab_Server]', '[/a]'); $strZipDumpExportWarning = __('%sZip compression%s requires functions (%s) which are unavailable on this system.'); $strZipDumpExportWarning = sprintf($strZipDumpExportWarning, '[a@?page=form&amp;formset=Features#tab_Import_export]', '[/a]', '%s'); $strZipDumpImportWarning = __('%sZip decompression%s requires functions (%s) which are unavailable on this system.'); $strZipDumpImportWarning = sprintf($strZipDumpImportWarning, '[a@?page=form&amp;formset=Features#tab_Import_export]', '[/a]', '%s'); for ($i = 1, $server_cnt = $cf->getServerCount(); $i <= $server_cnt; $i++) { $cookie_auth_server = ($cf->getValue("Servers/$i/auth_type") == 'cookie'); $cookie_auth_used |= $cookie_auth_server; $server_name = $cf->getServerName($i); if ($server_name == 'localhost') { $server_name .= " [$i]"; } $server_name = htmlspecialchars($server_name); if ($cookie_auth_server && $blowfish_secret === null) { $blowfish_secret = uniqid('', true); $blowfish_secret_set = true; $cf->set('blowfish_secret', $blowfish_secret); } // // $cfg['Servers'][$i]['ssl'] // should be enabled if possible // if (!$cf->getValue("Servers/$i/ssl")) { $title = PMA_lang(PMA_lang_name('Servers/1/ssl')) . " ($server_name)"; messages_set( 'notice', "Servers/$i/ssl", $title, __('You should use SSL connections if your database server supports it.') ); } // // $cfg['Servers'][$i]['extension'] // warn about using 'mysql' // if ($cf->getValue("Servers/$i/extension") == 'mysql') { $title = PMA_lang(PMA_lang_name('Servers/1/extension')) . " ($server_name)"; messages_set( 'notice', "Servers/$i/extension", $title, __('You should use mysqli for performance reasons.') ); } // // $cfg['Servers'][$i]['auth_type'] // warn about full user credentials if 'auth_type' is 'config' // if ($cf->getValue("Servers/$i/auth_type") == 'config' && $cf->getValue("Servers/$i/user") != '' && $cf->getValue("Servers/$i/password") != '' ) { $title = PMA_lang(PMA_lang_name('Servers/1/auth_type')) . " ($server_name)"; messages_set( 'notice', "Servers/$i/auth_type", $title, PMA_lang($strServerAuthConfigMsg, $i) . ' ' . PMA_lang($strSecurityInfoMsg, $i) ); } // // $cfg['Servers'][$i]['AllowRoot'] // $cfg['Servers'][$i]['AllowNoPassword'] // serious security flaw // if ($cf->getValue("Servers/$i/AllowRoot") && $cf->getValue("Servers/$i/AllowNoPassword") ) { $title = PMA_lang(PMA_lang_name('Servers/1/AllowNoPassword')) . " ($server_name)"; messages_set( 'notice', "Servers/$i/AllowNoPassword", $title, __('You allow for connecting to the server without a password.') . ' ' . PMA_lang($strSecurityInfoMsg, $i) ); } } // // $cfg['blowfish_secret'] // it's required for 'cookie' authentication // if ($cookie_auth_used) { if ($blowfish_secret_set) { // 'cookie' auth used, blowfish_secret was generated messages_set( 'notice', 'blowfish_secret_created', PMA_lang(PMA_lang_name('blowfish_secret')), $strBlowfishSecretMsg ); } else { $blowfish_warnings = array(); // check length if (strlen($blowfish_secret) < 8) { // too short key $blowfish_warnings[] = __('Key is too short, it should have at least 8 characters.'); } // check used characters $has_digits = (bool) preg_match('/\d/', $blowfish_secret); $has_chars = (bool) preg_match('/\S/', $blowfish_secret); $has_nonword = (bool) preg_match('/\W/', $blowfish_secret); if (!$has_digits || !$has_chars || !$has_nonword) { $blowfish_warnings[] = PMA_lang(__('Key should contain letters, numbers [em]and[/em] special characters.')); } if (!empty($blowfish_warnings)) { messages_set( 'error', 'blowfish_warnings' . count($blowfish_warnings), PMA_lang(PMA_lang_name('blowfish_secret')), implode('<br />', $blowfish_warnings) ); } } } // // $cfg['ForceSSL'] // should be enabled if possible // if (!$cf->getValue('ForceSSL')) { messages_set( 'notice', 'ForceSSL', PMA_lang(PMA_lang_name('ForceSSL')), PMA_lang($strForceSSLNotice) ); } // // $cfg['AllowArbitraryServer'] // should be disabled // if ($cf->getValue('AllowArbitraryServer')) { messages_set( 'notice', 'AllowArbitraryServer', PMA_lang(PMA_lang_name('AllowArbitraryServer')), PMA_lang($strAllowArbitraryServerWarning) ); } // // $cfg['LoginCookieValidity'] // value greater than session.gc_maxlifetime will cause // random session invalidation after that time if ($cf->getValue('LoginCookieValidity') > 1440 || $cf->getValue('LoginCookieValidity') > ini_get('session.gc_maxlifetime') ) { $message_type = $cf->getValue('LoginCookieValidity') > ini_get('session.gc_maxlifetime') ? 'error' : 'notice'; messages_set( $message_type, 'LoginCookieValidity', PMA_lang(PMA_lang_name('LoginCookieValidity')), PMA_lang($strLoginCookieValidityWarning) ); } // // $cfg['LoginCookieValidity'] // should be at most 1800 (30 min) // if ($cf->getValue('LoginCookieValidity') > 1800) { messages_set( 'notice', 'LoginCookieValidity', PMA_lang(PMA_lang_name('LoginCookieValidity')), PMA_lang($strLoginCookieValidityWarning2) ); } // // $cfg['LoginCookieValidity'] // $cfg['LoginCookieStore'] // LoginCookieValidity must be less or equal to LoginCookieStore // if ($cf->getValue('LoginCookieStore') != 0 && $cf->getValue('LoginCookieValidity') > $cf->getValue('LoginCookieStore') ) { messages_set( 'error', 'LoginCookieValidity', PMA_lang(PMA_lang_name('LoginCookieValidity')), PMA_lang($strLoginCookieValidityWarning3) ); } // // $cfg['SaveDir'] // should not be world-accessible // if ($cf->getValue('SaveDir') != '') { messages_set( 'notice', 'SaveDir', PMA_lang(PMA_lang_name('SaveDir')), PMA_lang($strDirectoryNotice) ); } // // $cfg['TempDir'] // should not be world-accessible // if ($cf->getValue('TempDir') != '') { messages_set( 'notice', 'TempDir', PMA_lang(PMA_lang_name('TempDir')), PMA_lang($strDirectoryNotice) ); } // // $cfg['GZipDump'] // requires zlib functions // if ($cf->getValue('GZipDump') && (@!function_exists('gzopen') || @!function_exists('gzencode')) ) { messages_set( 'error', 'GZipDump', PMA_lang(PMA_lang_name('GZipDump')), PMA_lang($strGZipDumpWarning, 'gzencode') ); } // // $cfg['BZipDump'] // requires bzip2 functions // if ($cf->getValue('BZipDump') && (!@function_exists('bzopen') || !@function_exists('bzcompress')) ) { $functions = @function_exists('bzopen') ? '' : 'bzopen'; $functions .= @function_exists('bzcompress') ? '' : ($functions ? ', ' : '') . 'bzcompress'; messages_set( 'error', 'BZipDump', PMA_lang(PMA_lang_name('BZipDump')), PMA_lang($strBZipDumpWarning, $functions) ); } // // $cfg['ZipDump'] // requires zip_open in import // if ($cf->getValue('ZipDump') && !@function_exists('zip_open')) { messages_set( 'error', 'ZipDump_import', PMA_lang(PMA_lang_name('ZipDump')), PMA_lang($strZipDumpImportWarning, 'zip_open') ); } // // $cfg['ZipDump'] // requires gzcompress in export // if ($cf->getValue('ZipDump') && !@function_exists('gzcompress')) { messages_set( 'error', 'ZipDump_export', PMA_lang(PMA_lang_name('ZipDump')), PMA_lang($strZipDumpExportWarning, 'gzcompress') ); } } ?>
alexbraga/phpmyadmin
setup/lib/index.lib.php
PHP
gpl-2.0
21,302
using System.Collections.Generic; using MrCMS.Services; namespace MrCMS.Web.Apps.MobileFriendlyNavigation.Services { public class MobileFriendlyNavigationStylesheets : IAppStylesheetList { public IEnumerable<string> UIStylesheets { get { yield return @"~/Apps/MobileFriendlyNavigation/Content/Styles/mobileFriendlyNavigation.css"; } } public IEnumerable<string> AdminStylesheets { get { yield break; } } } }
MrCMS/Mobile-Friendly-Navigation
Services/MobileFriendlyNavigationStylesheets.cs
C#
gpl-2.0
496
/* * Copyright (c) 2001-2002 by David Brownell * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __LINUX_EHCI_HCD_H #define __LINUX_EHCI_HCD_H /* definitions used for the EHCI driver */ /* ehci_hcd->lock guards shared data against other CPUs: * ehci_hcd: async, reclaim, periodic (and shadow), ... * hcd_dev: ep[] * ehci_qh: qh_next, qtd_list * ehci_qtd: qtd_list * * Also, hold this lock when talking to HC registers or * when updating hw_* fields in shared qh/qtd/... structures. */ #define EHCI_MAX_ROOT_PORTS 15 /* see HCS_N_PORTS */ struct ehci_hcd { /* one per controller */ spinlock_t lock; /* async schedule support */ struct ehci_qh *async; struct ehci_qh *reclaim; int reclaim_ready; /* periodic schedule support */ #define DEFAULT_I_TDPS 1024 /* some HCs can do less */ unsigned periodic_size; u32 *periodic; /* hw periodic table */ dma_addr_t periodic_dma; unsigned i_thresh; /* uframes HC might cache */ union ehci_shadow *pshadow; /* mirror hw periodic table */ int next_uframe; /* scan periodic, start here */ unsigned periodic_urbs; /* how many urbs scheduled? */ /* deferred work from IRQ, etc */ struct tasklet_struct tasklet; /* per root hub port */ unsigned long reset_done [EHCI_MAX_ROOT_PORTS]; /* glue to PCI and HCD framework */ struct usb_hcd hcd; struct ehci_caps *caps; struct ehci_regs *regs; u32 hcs_params; /* cached register copy */ /* per-HC memory pools (could be per-PCI-bus, but ...) */ struct pci_pool *qh_pool; /* qh per active urb */ struct pci_pool *qtd_pool; /* one or more per qh */ struct pci_pool *itd_pool; /* itd per iso urb */ struct pci_pool *sitd_pool; /* sitd per split iso urb */ }; /* unwrap an HCD pointer to get an EHCI_HCD pointer */ #define hcd_to_ehci(hcd_ptr) list_entry(hcd_ptr, struct ehci_hcd, hcd) /* NOTE: urb->transfer_flags expected to not use this bit !!! */ #define EHCI_STATE_UNLINK 0x8000 /* urb being unlinked */ /*-------------------------------------------------------------------------*/ /* EHCI register interface, corresponds to EHCI Revision 0.95 specification */ /* Section 2.2 Host Controller Capability Registers */ struct ehci_caps { u8 length; /* CAPLENGTH - size of this struct */ u8 reserved; /* offset 0x1 */ u16 hci_version; /* HCIVERSION - offset 0x2 */ u32 hcs_params; /* HCSPARAMS - offset 0x4 */ #define HCS_DEBUG_PORT(p) (((p)>>20)&0xf) /* bits 23:20, debug port? */ #define HCS_INDICATOR(p) ((p)&(1 << 16)) /* true: has port indicators */ #define HCS_N_CC(p) (((p)>>12)&0xf) /* bits 15:12, #companion HCs */ #define HCS_N_PCC(p) (((p)>>8)&0xf) /* bits 11:8, ports per CC */ #define HCS_PORTROUTED(p) ((p)&(1 << 7)) /* true: port routing */ #define HCS_PPC(p) ((p)&(1 << 4)) /* true: port power control */ #define HCS_N_PORTS(p) (((p)>>0)&0xf) /* bits 3:0, ports on HC */ u32 hcc_params; /* HCCPARAMS - offset 0x8 */ #define HCC_EXT_CAPS(p) (((p)>>8)&0xff) /* for pci extended caps */ #define HCC_ISOC_CACHE(p) ((p)&(1 << 7)) /* true: can cache isoc frame */ #define HCC_ISOC_THRES(p) (((p)>>4)&0x7) /* bits 6:4, uframes cached */ #define HCC_CANPARK(p) ((p)&(1 << 2)) /* true: can park on async qh */ #define HCC_PGM_FRAMELISTLEN(p) ((p)&(1 << 1)) /* true: periodic_size changes*/ #define HCC_64BIT_ADDR(p) ((p)&(1)) /* true: can use 64-bit addr */ u8 portroute [8]; /* nibbles for routing - offset 0xC */ } __attribute__ ((packed)); /* Section 2.3 Host Controller Operational Registers */ struct ehci_regs { /* USBCMD: offset 0x00 */ u32 command; /* 23:16 is r/w intr rate, in microframes; default "8" == 1/msec */ #define CMD_PARK (1<<11) /* enable "park" on async qh */ #define CMD_PARK_CNT(c) (((c)>>8)&3) /* how many transfers to park for */ #define CMD_LRESET (1<<7) /* partial reset (no ports, etc) */ #define CMD_IAAD (1<<6) /* "doorbell" interrupt async advance */ #define CMD_ASE (1<<5) /* async schedule enable */ #define CMD_PSE (1<<4) /* periodic schedule enable */ /* 3:2 is periodic frame list size */ #define CMD_RESET (1<<1) /* reset HC not bus */ #define CMD_RUN (1<<0) /* start/stop HC */ /* USBSTS: offset 0x04 */ u32 status; #define STS_ASS (1<<15) /* Async Schedule Status */ #define STS_PSS (1<<14) /* Periodic Schedule Status */ #define STS_RECL (1<<13) /* Reclamation */ #define STS_HALT (1<<12) /* Not running (any reason) */ /* some bits reserved */ /* these STS_* flags are also intr_enable bits (USBINTR) */ #define STS_IAA (1<<5) /* Interrupted on async advance */ #define STS_FATAL (1<<4) /* such as some PCI access errors */ #define STS_FLR (1<<3) /* frame list rolled over */ #define STS_PCD (1<<2) /* port change detect */ #define STS_ERR (1<<1) /* "error" completion (overflow, ...) */ #define STS_INT (1<<0) /* "normal" completion (short, ...) */ /* USBINTR: offset 0x08 */ u32 intr_enable; /* FRINDEX: offset 0x0C */ u32 frame_index; /* current microframe number */ /* CTRLDSSEGMENT: offset 0x10 */ u32 segment; /* address bits 63:32 if needed */ /* PERIODICLISTBASE: offset 0x14 */ u32 frame_list; /* points to periodic list */ /* ASYNCICLISTADDR: offset 0x18 */ u32 async_next; /* address of next async queue head */ u32 reserved [9]; /* CONFIGFLAG: offset 0x40 */ u32 configured_flag; #define FLAG_CF (1<<0) /* true: we'll support "high speed" */ /* PORTSC: offset 0x44 */ u32 port_status [0]; /* up to N_PORTS */ /* 31:23 reserved */ #define PORT_WKOC_E (1<<22) /* wake on overcurrent (enable) */ #define PORT_WKDISC_E (1<<21) /* wake on disconnect (enable) */ #define PORT_WKCONN_E (1<<20) /* wake on connect (enable) */ /* 19:16 for port testing */ /* 15:14 for using port indicator leds (if HCS_INDICATOR allows) */ #define PORT_OWNER (1<<13) /* true: companion hc owns this port */ #define PORT_POWER (1<<12) /* true: has power (see PPC) */ #define PORT_USB11(x) (((x)&(3<<10))==(1<<10)) /* USB 1.1 device */ /* 11:10 for detecting lowspeed devices (reset vs release ownership) */ /* 9 reserved */ #define PORT_RESET (1<<8) /* reset port */ #define PORT_SUSPEND (1<<7) /* suspend port */ #define PORT_RESUME (1<<6) /* resume it */ #define PORT_OCC (1<<5) /* over current change */ #define PORT_OC (1<<4) /* over current active */ #define PORT_PEC (1<<3) /* port enable change */ #define PORT_PE (1<<2) /* port enable */ #define PORT_CSC (1<<1) /* connect status change */ #define PORT_CONNECT (1<<0) /* device connected */ } __attribute__ ((packed)); /*-------------------------------------------------------------------------*/ #define QTD_NEXT(dma) cpu_to_le32((u32)dma) /* * EHCI Specification 0.95 Section 3.5 * QTD: describe data transfer components (buffer, direction, ...) * See Fig 3-6 "Queue Element Transfer Descriptor Block Diagram". * * These are associated only with "QH" (Queue Head) structures, * used with control, bulk, and interrupt transfers. */ struct ehci_qtd { /* first part defined by EHCI spec */ u32 hw_next; /* see EHCI 3.5.1 */ u32 hw_alt_next; /* see EHCI 3.5.2 */ u32 hw_token; /* see EHCI 3.5.3 */ #define QTD_TOGGLE (1 << 31) /* data toggle */ #define QTD_LENGTH(tok) (((tok)>>16) & 0x7fff) #define QTD_IOC (1 << 15) /* interrupt on complete */ #define QTD_CERR(tok) (((tok)>>10) & 0x3) #define QTD_PID(tok) (((tok)>>8) & 0x3) #define QTD_STS_ACTIVE (1 << 7) /* HC may execute this */ #define QTD_STS_HALT (1 << 6) /* halted on error */ #define QTD_STS_DBE (1 << 5) /* data buffer error (in HC) */ #define QTD_STS_BABBLE (1 << 4) /* device was babbling (qtd halted) */ #define QTD_STS_XACT (1 << 3) /* device gave illegal response */ #define QTD_STS_MMF (1 << 2) /* incomplete split transaction */ #define QTD_STS_STS (1 << 1) /* split transaction state */ #define QTD_STS_PING (1 << 0) /* issue PING? */ u32 hw_buf [5]; /* see EHCI 3.5.4 */ u32 hw_buf_hi [5]; /* Appendix B */ /* the rest is HCD-private */ dma_addr_t qtd_dma; /* qtd address */ struct list_head qtd_list; /* sw qtd list */ /* dma same in urb's qtds, except 1st control qtd (setup buffer) */ struct urb *urb; /* qtd's urb */ dma_addr_t buf_dma; /* buffer address */ size_t length; /* length of buffer */ } __attribute__ ((aligned (32))); /*-------------------------------------------------------------------------*/ /* type tag from {qh,itd,sitd,fstn}->hw_next */ #define Q_NEXT_TYPE(dma) ((dma) & __constant_cpu_to_le32 (3 << 1)) /* values for that type tag */ #define Q_TYPE_ITD __constant_cpu_to_le32 (0 << 1) #define Q_TYPE_QH __constant_cpu_to_le32 (1 << 1) #define Q_TYPE_SITD __constant_cpu_to_le32 (2 << 1) #define Q_TYPE_FSTN __constant_cpu_to_le32 (3 << 1) /* next async queue entry, or pointer to interrupt/periodic QH */ #define QH_NEXT(dma) (cpu_to_le32(((u32)dma)&~0x01f)|Q_TYPE_QH) /* for periodic/async schedules and qtd lists, mark end of list */ #define EHCI_LIST_END __constant_cpu_to_le32(1) /* "null pointer" to hw */ /* * Entries in periodic shadow table are pointers to one of four kinds * of data structure. That's dictated by the hardware; a type tag is * encoded in the low bits of the hardware's periodic schedule. Use * Q_NEXT_TYPE to get the tag. * * For entries in the async schedule, the type tag always says "qh". */ union ehci_shadow { struct ehci_qh *qh; /* Q_TYPE_QH */ struct ehci_itd *itd; /* Q_TYPE_ITD */ struct ehci_sitd *sitd; /* Q_TYPE_SITD */ struct ehci_fstn *fstn; /* Q_TYPE_FSTN */ void *ptr; }; /*-------------------------------------------------------------------------*/ /* * EHCI Specification 0.95 Section 3.6 * QH: describes control/bulk/interrupt endpoints * See Fig 3-7 "Queue Head Structure Layout". * * These appear in both the async and (for interrupt) periodic schedules. */ struct ehci_qh { /* first part defined by EHCI spec */ u32 hw_next; /* see EHCI 3.6.1 */ u32 hw_info1; /* see EHCI 3.6.2 */ #define QH_HEAD 0x00008000 u32 hw_info2; /* see EHCI 3.6.2 */ u32 hw_current; /* qtd list - see EHCI 3.6.4 */ /* qtd overlay (hardware parts of a struct ehci_qtd) */ u32 hw_qtd_next; u32 hw_alt_next; u32 hw_token; u32 hw_buf [5]; u32 hw_buf_hi [5]; /* the rest is HCD-private */ dma_addr_t qh_dma; /* address of qh */ union ehci_shadow qh_next; /* ptr to qh; or periodic */ struct list_head qtd_list; /* sw qtd list */ atomic_t refcount; unsigned short usecs; /* intr bandwidth */ short qh_state; #define QH_STATE_LINKED 1 /* HC sees this */ #define QH_STATE_UNLINK 2 /* HC may still see this */ #define QH_STATE_IDLE 3 /* HC doesn't see this */ #ifdef EHCI_SOFT_RETRIES int retries; #endif } __attribute__ ((aligned (32))); /*-------------------------------------------------------------------------*/ /* * EHCI Specification 0.95 Section 3.3 * Fig 3-4 "Isochronous Transaction Descriptor (iTD)" * * Schedule records for high speed iso xfers */ struct ehci_itd { /* first part defined by EHCI spec */ u32 hw_next; /* see EHCI 3.3.1 */ u32 hw_transaction [8]; /* see EHCI 3.3.2 */ #define EHCI_ISOC_ACTIVE (1<<31) /* activate transfer this slot */ #define EHCI_ISOC_BUF_ERR (1<<30) /* Data buffer error */ #define EHCI_ISOC_BABBLE (1<<29) /* babble detected */ #define EHCI_ISOC_XACTERR (1<<28) /* XactErr - transaction error */ #define EHCI_ITD_LENGTH(tok) (((tok)>>16) & 0x7fff) #define EHCI_ITD_IOC (1 << 15) /* interrupt on complete */ u32 hw_bufp [7]; /* see EHCI 3.3.3 */ u32 hw_bufp_hi [7]; /* Appendix B */ /* the rest is HCD-private */ dma_addr_t itd_dma; /* for this itd */ union ehci_shadow itd_next; /* ptr to periodic q entry */ struct urb *urb; struct list_head itd_list; /* list of urb frames' itds */ dma_addr_t buf_dma; /* frame's buffer address */ /* for now, only one hw_transaction per itd */ u32 transaction; u16 index; /* in urb->iso_frame_desc */ u16 uframe; /* in periodic schedule */ u16 usecs; } __attribute__ ((aligned (32))); /*-------------------------------------------------------------------------*/ /* * EHCI Specification 0.95 Section 3.4 * siTD, aka split-transaction isochronous Transfer Descriptor * ... describe low/full speed iso xfers through TT in hubs * see Figure 3-5 "Split-transaction Isochronous Transaction Descriptor (siTD) */ struct ehci_sitd { /* first part defined by EHCI spec */ u32 hw_next; /* uses bit field macros above - see EHCI 0.95 Table 3-8 */ u32 hw_fullspeed_ep; /* see EHCI table 3-9 */ u32 hw_uframe; /* see EHCI table 3-10 */ u32 hw_tx_results1; /* see EHCI table 3-11 */ u32 hw_tx_results2; /* see EHCI table 3-12 */ u32 hw_tx_results3; /* see EHCI table 3-12 */ u32 hw_backpointer; /* see EHCI table 3-13 */ u32 hw_buf_hi [2]; /* Appendix B */ /* the rest is HCD-private */ dma_addr_t sitd_dma; union ehci_shadow sitd_next; /* ptr to periodic q entry */ struct urb *urb; dma_addr_t buf_dma; /* buffer address */ } __attribute__ ((aligned (32))); /*-------------------------------------------------------------------------*/ /* * EHCI Specification 0.96 Section 3.7 * Periodic Frame Span Traversal Node (FSTN) * * Manages split interrupt transactions (using TT) that span frame boundaries * into uframes 0/1; see 4.12.2.2. In those uframes, a "save place" FSTN * makes the HC jump (back) to a QH to scan for fs/ls QH completions until * it hits a "restore" FSTN; then it returns to finish other uframe 0/1 work. */ struct ehci_fstn { u32 hw_next; /* any periodic q entry */ u32 hw_prev; /* qh or EHCI_LIST_END */ /* the rest is HCD-private */ dma_addr_t fstn_dma; union ehci_shadow fstn_next; /* ptr to periodic q entry */ } __attribute__ ((aligned (32))); #endif /* __LINUX_EHCI_HCD_H */
robacklin/celinux
drivers/usb/hcd/ehci.h
C
gpl-2.0
14,662
#include <linux/etherdevice.h> #include <net/ieee80211_crypt.h> #include "hostap_80211.h" #include "hostap.h" #include "hostap_ap.h" /* See IEEE 802.1H for LLC/SNAP encapsulation/decapsulation */ /* Ethernet-II snap header (RFC1042 for most EtherTypes) */ static unsigned char rfc1042_header[] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 }; /* Bridge-Tunnel header (for EtherTypes ETH_P_AARP and ETH_P_IPX) */ static unsigned char bridge_tunnel_header[] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0xf8 }; /* No encapsulation header if EtherType < 0x600 (=length) */ void hostap_dump_rx_80211(const char *name, struct sk_buff *skb, struct hostap_80211_rx_status *rx_stats) { struct ieee80211_hdr_4addr *hdr; u16 fc; DECLARE_MAC_BUF(mac); hdr = (struct ieee80211_hdr_4addr *) skb->data; printk(KERN_DEBUG "%s: RX signal=%d noise=%d rate=%d len=%d " "jiffies=%ld\n", name, rx_stats->signal, rx_stats->noise, rx_stats->rate, skb->len, jiffies); if (skb->len < 2) return; fc = le16_to_cpu(hdr->frame_ctl); printk(KERN_DEBUG " FC=0x%04x (type=%d:%d)%s%s", fc, WLAN_FC_GET_TYPE(fc) >> 2, WLAN_FC_GET_STYPE(fc) >> 4, fc & IEEE80211_FCTL_TODS ? " [ToDS]" : "", fc & IEEE80211_FCTL_FROMDS ? " [FromDS]" : ""); if (skb->len < IEEE80211_DATA_HDR3_LEN) { printk("\n"); return; } printk(" dur=0x%04x seq=0x%04x\n", le16_to_cpu(hdr->duration_id), le16_to_cpu(hdr->seq_ctl)); printk(KERN_DEBUG " A1=%s", print_mac(mac, hdr->addr1)); printk(" A2=%s", print_mac(mac, hdr->addr2)); printk(" A3=%s", print_mac(mac, hdr->addr3)); if (skb->len >= 30) printk(" A4=%s", print_mac(mac, hdr->addr4)); printk("\n"); } /* Send RX frame to netif with 802.11 (and possible prism) header. * Called from hardware or software IRQ context. */ int prism2_rx_80211(struct net_device *dev, struct sk_buff *skb, struct hostap_80211_rx_status *rx_stats, int type) { struct hostap_interface *iface; local_info_t *local; int hdrlen, phdrlen, head_need, tail_need; u16 fc; int prism_header, ret; struct ieee80211_hdr_4addr *fhdr; iface = netdev_priv(dev); local = iface->local; dev->last_rx = jiffies; if (dev->type == ARPHRD_IEEE80211_PRISM) { if (local->monitor_type == PRISM2_MONITOR_PRISM) { prism_header = 1; phdrlen = sizeof(struct linux_wlan_ng_prism_hdr); } else { /* local->monitor_type == PRISM2_MONITOR_CAPHDR */ prism_header = 2; phdrlen = sizeof(struct linux_wlan_ng_cap_hdr); } } else { prism_header = 0; phdrlen = 0; } fhdr = (struct ieee80211_hdr_4addr *) skb->data; fc = le16_to_cpu(fhdr->frame_ctl); if (type == PRISM2_RX_MGMT && (fc & IEEE80211_FCTL_VERS)) { printk(KERN_DEBUG "%s: dropped management frame with header " "version %d\n", dev->name, fc & IEEE80211_FCTL_VERS); dev_kfree_skb_any(skb); return 0; } hdrlen = hostap_80211_get_hdrlen(fc); /* check if there is enough room for extra data; if not, expand skb * buffer to be large enough for the changes */ head_need = phdrlen; tail_need = 0; #ifdef PRISM2_ADD_BOGUS_CRC tail_need += 4; #endif /* PRISM2_ADD_BOGUS_CRC */ head_need -= skb_headroom(skb); tail_need -= skb_tailroom(skb); if (head_need > 0 || tail_need > 0) { if (pskb_expand_head(skb, head_need > 0 ? head_need : 0, tail_need > 0 ? tail_need : 0, GFP_ATOMIC)) { printk(KERN_DEBUG "%s: prism2_rx_80211 failed to " "reallocate skb buffer\n", dev->name); dev_kfree_skb_any(skb); return 0; } } /* We now have an skb with enough head and tail room, so just insert * the extra data */ #ifdef PRISM2_ADD_BOGUS_CRC memset(skb_put(skb, 4), 0xff, 4); /* Prism2 strips CRC */ #endif /* PRISM2_ADD_BOGUS_CRC */ if (prism_header == 1) { struct linux_wlan_ng_prism_hdr *hdr; hdr = (struct linux_wlan_ng_prism_hdr *) skb_push(skb, phdrlen); memset(hdr, 0, phdrlen); hdr->msgcode = LWNG_CAP_DID_BASE; hdr->msglen = sizeof(*hdr); memcpy(hdr->devname, dev->name, sizeof(hdr->devname)); #define LWNG_SETVAL(f,i,s,l,d) \ hdr->f.did = LWNG_CAP_DID_BASE | (i << 12); \ hdr->f.status = s; hdr->f.len = l; hdr->f.data = d LWNG_SETVAL(hosttime, 1, 0, 4, jiffies); LWNG_SETVAL(mactime, 2, 0, 4, rx_stats->mac_time); LWNG_SETVAL(channel, 3, 1 /* no value */, 4, 0); LWNG_SETVAL(rssi, 4, 1 /* no value */, 4, 0); LWNG_SETVAL(sq, 5, 1 /* no value */, 4, 0); LWNG_SETVAL(signal, 6, 0, 4, rx_stats->signal); LWNG_SETVAL(noise, 7, 0, 4, rx_stats->noise); LWNG_SETVAL(rate, 8, 0, 4, rx_stats->rate / 5); LWNG_SETVAL(istx, 9, 0, 4, 0); LWNG_SETVAL(frmlen, 10, 0, 4, skb->len - phdrlen); #undef LWNG_SETVAL } else if (prism_header == 2) { struct linux_wlan_ng_cap_hdr *hdr; hdr = (struct linux_wlan_ng_cap_hdr *) skb_push(skb, phdrlen); memset(hdr, 0, phdrlen); hdr->version = htonl(LWNG_CAPHDR_VERSION); hdr->length = htonl(phdrlen); hdr->mactime = __cpu_to_be64(rx_stats->mac_time); hdr->hosttime = __cpu_to_be64(jiffies); hdr->phytype = htonl(4); /* dss_dot11_b */ hdr->channel = htonl(local->channel); hdr->datarate = htonl(rx_stats->rate); hdr->antenna = htonl(0); /* unknown */ hdr->priority = htonl(0); /* unknown */ hdr->ssi_type = htonl(3); /* raw */ hdr->ssi_signal = htonl(rx_stats->signal); hdr->ssi_noise = htonl(rx_stats->noise); hdr->preamble = htonl(0); /* unknown */ hdr->encoding = htonl(1); /* cck */ } ret = skb->len - phdrlen; skb->dev = dev; skb_reset_mac_header(skb); skb_pull(skb, hdrlen); if (prism_header) skb_pull(skb, phdrlen); skb->pkt_type = PACKET_OTHERHOST; skb->protocol = __constant_htons(ETH_P_802_2); memset(skb->cb, 0, sizeof(skb->cb)); netif_rx(skb); return ret; } /* Called only as a tasklet (software IRQ) */ static void monitor_rx(struct net_device *dev, struct sk_buff *skb, struct hostap_80211_rx_status *rx_stats) { struct net_device_stats *stats; int len; len = prism2_rx_80211(dev, skb, rx_stats, PRISM2_RX_MONITOR); stats = hostap_get_stats(dev); stats->rx_packets++; stats->rx_bytes += len; } /* Called only as a tasklet (software IRQ) */ static struct prism2_frag_entry * prism2_frag_cache_find(local_info_t *local, unsigned int seq, unsigned int frag, u8 *src, u8 *dst) { struct prism2_frag_entry *entry; int i; for (i = 0; i < PRISM2_FRAG_CACHE_LEN; i++) { entry = &local->frag_cache[i]; if (entry->skb != NULL && time_after(jiffies, entry->first_frag_time + 2 * HZ)) { printk(KERN_DEBUG "%s: expiring fragment cache entry " "seq=%u last_frag=%u\n", local->dev->name, entry->seq, entry->last_frag); dev_kfree_skb(entry->skb); entry->skb = NULL; } if (entry->skb != NULL && entry->seq == seq && (entry->last_frag + 1 == frag || frag == -1) && memcmp(entry->src_addr, src, ETH_ALEN) == 0 && memcmp(entry->dst_addr, dst, ETH_ALEN) == 0) return entry; } return NULL; } /* Called only as a tasklet (software IRQ) */ static struct sk_buff * prism2_frag_cache_get(local_info_t *local, struct ieee80211_hdr_4addr *hdr) { struct sk_buff *skb = NULL; u16 sc; unsigned int frag, seq; struct prism2_frag_entry *entry; sc = le16_to_cpu(hdr->seq_ctl); frag = WLAN_GET_SEQ_FRAG(sc); seq = WLAN_GET_SEQ_SEQ(sc) >> 4; if (frag == 0) { /* Reserve enough space to fit maximum frame length */ skb = dev_alloc_skb(local->dev->mtu + sizeof(struct ieee80211_hdr_4addr) + 8 /* LLC */ + 2 /* alignment */ + 8 /* WEP */ + ETH_ALEN /* WDS */); if (skb == NULL) return NULL; entry = &local->frag_cache[local->frag_next_idx]; local->frag_next_idx++; if (local->frag_next_idx >= PRISM2_FRAG_CACHE_LEN) local->frag_next_idx = 0; if (entry->skb != NULL) dev_kfree_skb(entry->skb); entry->first_frag_time = jiffies; entry->seq = seq; entry->last_frag = frag; entry->skb = skb; memcpy(entry->src_addr, hdr->addr2, ETH_ALEN); memcpy(entry->dst_addr, hdr->addr1, ETH_ALEN); } else { /* received a fragment of a frame for which the head fragment * should have already been received */ entry = prism2_frag_cache_find(local, seq, frag, hdr->addr2, hdr->addr1); if (entry != NULL) { entry->last_frag = frag; skb = entry->skb; } } return skb; } /* Called only as a tasklet (software IRQ) */ static int prism2_frag_cache_invalidate(local_info_t *local, struct ieee80211_hdr_4addr *hdr) { u16 sc; unsigned int seq; struct prism2_frag_entry *entry; sc = le16_to_cpu(hdr->seq_ctl); seq = WLAN_GET_SEQ_SEQ(sc) >> 4; entry = prism2_frag_cache_find(local, seq, -1, hdr->addr2, hdr->addr1); if (entry == NULL) { printk(KERN_DEBUG "%s: could not invalidate fragment cache " "entry (seq=%u)\n", local->dev->name, seq); return -1; } entry->skb = NULL; return 0; } static struct hostap_bss_info *__hostap_get_bss(local_info_t *local, u8 *bssid, u8 *ssid, size_t ssid_len) { struct list_head *ptr; struct hostap_bss_info *bss; list_for_each(ptr, &local->bss_list) { bss = list_entry(ptr, struct hostap_bss_info, list); if (memcmp(bss->bssid, bssid, ETH_ALEN) == 0 && (ssid == NULL || (ssid_len == bss->ssid_len && memcmp(ssid, bss->ssid, ssid_len) == 0))) { list_move(&bss->list, &local->bss_list); return bss; } } return NULL; } static struct hostap_bss_info *__hostap_add_bss(local_info_t *local, u8 *bssid, u8 *ssid, size_t ssid_len) { struct hostap_bss_info *bss; if (local->num_bss_info >= HOSTAP_MAX_BSS_COUNT) { bss = list_entry(local->bss_list.prev, struct hostap_bss_info, list); list_del(&bss->list); local->num_bss_info--; } else { bss = (struct hostap_bss_info *) kmalloc(sizeof(*bss), GFP_ATOMIC); if (bss == NULL) return NULL; } memset(bss, 0, sizeof(*bss)); memcpy(bss->bssid, bssid, ETH_ALEN); memcpy(bss->ssid, ssid, ssid_len); bss->ssid_len = ssid_len; local->num_bss_info++; list_add(&bss->list, &local->bss_list); return bss; } static void __hostap_expire_bss(local_info_t *local) { struct hostap_bss_info *bss; while (local->num_bss_info > 0) { bss = list_entry(local->bss_list.prev, struct hostap_bss_info, list); if (!time_after(jiffies, bss->last_update + 60 * HZ)) break; list_del(&bss->list); local->num_bss_info--; kfree(bss); } } /* Both IEEE 802.11 Beacon and Probe Response frames have similar structure, so * the same routine can be used to parse both of them. */ static void hostap_rx_sta_beacon(local_info_t *local, struct sk_buff *skb, int stype) { struct hostap_ieee80211_mgmt *mgmt; int left, chan = 0; u8 *pos; u8 *ssid = NULL, *wpa = NULL, *rsn = NULL; size_t ssid_len = 0, wpa_len = 0, rsn_len = 0; struct hostap_bss_info *bss; if (skb->len < IEEE80211_MGMT_HDR_LEN + sizeof(mgmt->u.beacon)) return; mgmt = (struct hostap_ieee80211_mgmt *) skb->data; pos = mgmt->u.beacon.variable; left = skb->len - (pos - skb->data); while (left >= 2) { if (2 + pos[1] > left) return; /* parse failed */ switch (*pos) { case WLAN_EID_SSID: ssid = pos + 2; ssid_len = pos[1]; break; case WLAN_EID_GENERIC: if (pos[1] >= 4 && pos[2] == 0x00 && pos[3] == 0x50 && pos[4] == 0xf2 && pos[5] == 1) { wpa = pos; wpa_len = pos[1] + 2; } break; case WLAN_EID_RSN: rsn = pos; rsn_len = pos[1] + 2; break; case WLAN_EID_DS_PARAMS: if (pos[1] >= 1) chan = pos[2]; break; } left -= 2 + pos[1]; pos += 2 + pos[1]; } if (wpa_len > MAX_WPA_IE_LEN) wpa_len = MAX_WPA_IE_LEN; if (rsn_len > MAX_WPA_IE_LEN) rsn_len = MAX_WPA_IE_LEN; if (ssid_len > sizeof(bss->ssid)) ssid_len = sizeof(bss->ssid); spin_lock(&local->lock); bss = __hostap_get_bss(local, mgmt->bssid, ssid, ssid_len); if (bss == NULL) bss = __hostap_add_bss(local, mgmt->bssid, ssid, ssid_len); if (bss) { bss->last_update = jiffies; bss->count++; bss->capab_info = le16_to_cpu(mgmt->u.beacon.capab_info); if (wpa) { memcpy(bss->wpa_ie, wpa, wpa_len); bss->wpa_ie_len = wpa_len; } else bss->wpa_ie_len = 0; if (rsn) { memcpy(bss->rsn_ie, rsn, rsn_len); bss->rsn_ie_len = rsn_len; } else bss->rsn_ie_len = 0; bss->chan = chan; } __hostap_expire_bss(local); spin_unlock(&local->lock); } static int hostap_rx_frame_mgmt(local_info_t *local, struct sk_buff *skb, struct hostap_80211_rx_status *rx_stats, u16 type, u16 stype) { if (local->iw_mode == IW_MODE_MASTER) { hostap_update_sta_ps(local, (struct ieee80211_hdr_4addr *) skb->data); } if (local->hostapd && type == IEEE80211_FTYPE_MGMT) { if (stype == IEEE80211_STYPE_BEACON && local->iw_mode == IW_MODE_MASTER) { struct sk_buff *skb2; /* Process beacon frames also in kernel driver to * update STA(AP) table statistics */ skb2 = skb_clone(skb, GFP_ATOMIC); if (skb2) hostap_rx(skb2->dev, skb2, rx_stats); } /* send management frames to the user space daemon for * processing */ local->apdevstats.rx_packets++; local->apdevstats.rx_bytes += skb->len; if (local->apdev == NULL) return -1; prism2_rx_80211(local->apdev, skb, rx_stats, PRISM2_RX_MGMT); return 0; } if (local->iw_mode == IW_MODE_MASTER) { if (type != IEEE80211_FTYPE_MGMT && type != IEEE80211_FTYPE_CTL) { printk(KERN_DEBUG "%s: unknown management frame " "(type=0x%02x, stype=0x%02x) dropped\n", skb->dev->name, type >> 2, stype >> 4); return -1; } hostap_rx(skb->dev, skb, rx_stats); return 0; } else if (type == IEEE80211_FTYPE_MGMT && (stype == IEEE80211_STYPE_BEACON || stype == IEEE80211_STYPE_PROBE_RESP)) { hostap_rx_sta_beacon(local, skb, stype); return -1; } else if (type == IEEE80211_FTYPE_MGMT && (stype == IEEE80211_STYPE_ASSOC_RESP || stype == IEEE80211_STYPE_REASSOC_RESP)) { /* Ignore (Re)AssocResp silently since these are not currently * needed but are still received when WPA/RSN mode is enabled. */ return -1; } else { printk(KERN_DEBUG "%s: hostap_rx_frame_mgmt: dropped unhandled" " management frame in non-Host AP mode (type=%d:%d)\n", skb->dev->name, type >> 2, stype >> 4); return -1; } } /* Called only as a tasklet (software IRQ) */ static struct net_device *prism2_rx_get_wds(local_info_t *local, u8 *addr) { struct hostap_interface *iface = NULL; struct list_head *ptr; read_lock_bh(&local->iface_lock); list_for_each(ptr, &local->hostap_interfaces) { iface = list_entry(ptr, struct hostap_interface, list); if (iface->type == HOSTAP_INTERFACE_WDS && memcmp(iface->u.wds.remote_addr, addr, ETH_ALEN) == 0) break; iface = NULL; } read_unlock_bh(&local->iface_lock); return iface ? iface->dev : NULL; } static int hostap_rx_frame_wds(local_info_t *local, struct ieee80211_hdr_4addr *hdr, u16 fc, struct net_device **wds) { DECLARE_MAC_BUF(mac); /* FIX: is this really supposed to accept WDS frames only in Master * mode? What about Repeater or Managed with WDS frames? */ if ((fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) != (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS) && (local->iw_mode != IW_MODE_MASTER || !(fc & IEEE80211_FCTL_TODS))) return 0; /* not a WDS frame */ /* Possible WDS frame: either IEEE 802.11 compliant (if FromDS) * or own non-standard frame with 4th address after payload */ if (memcmp(hdr->addr1, local->dev->dev_addr, ETH_ALEN) != 0 && (hdr->addr1[0] != 0xff || hdr->addr1[1] != 0xff || hdr->addr1[2] != 0xff || hdr->addr1[3] != 0xff || hdr->addr1[4] != 0xff || hdr->addr1[5] != 0xff)) { /* RA (or BSSID) is not ours - drop */ PDEBUG(DEBUG_EXTRA2, "%s: received WDS frame with " "not own or broadcast %s=%s\n", local->dev->name, fc & IEEE80211_FCTL_FROMDS ? "RA" : "BSSID", print_mac(mac, hdr->addr1)); return -1; } /* check if the frame came from a registered WDS connection */ *wds = prism2_rx_get_wds(local, hdr->addr2); if (*wds == NULL && fc & IEEE80211_FCTL_FROMDS && (local->iw_mode != IW_MODE_INFRA || !(local->wds_type & HOSTAP_WDS_AP_CLIENT) || memcmp(hdr->addr2, local->bssid, ETH_ALEN) != 0)) { /* require that WDS link has been registered with TA or the * frame is from current AP when using 'AP client mode' */ PDEBUG(DEBUG_EXTRA, "%s: received WDS[4 addr] frame " "from unknown TA=%s\n", local->dev->name, print_mac(mac, hdr->addr2)); if (local->ap && local->ap->autom_ap_wds) hostap_wds_link_oper(local, hdr->addr2, WDS_ADD); return -1; } if (*wds && !(fc & IEEE80211_FCTL_FROMDS) && local->ap && hostap_is_sta_assoc(local->ap, hdr->addr2)) { /* STA is actually associated with us even though it has a * registered WDS link. Assume it is in 'AP client' mode. * Since this is a 3-addr frame, assume it is not (bogus) WDS * frame and process it like any normal ToDS frame from * associated STA. */ *wds = NULL; } return 0; } static int hostap_is_eapol_frame(local_info_t *local, struct sk_buff *skb) { struct net_device *dev = local->dev; u16 fc, ethertype; struct ieee80211_hdr_4addr *hdr; u8 *pos; if (skb->len < 24) return 0; hdr = (struct ieee80211_hdr_4addr *) skb->data; fc = le16_to_cpu(hdr->frame_ctl); /* check that the frame is unicast frame to us */ if ((fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) == IEEE80211_FCTL_TODS && memcmp(hdr->addr1, dev->dev_addr, ETH_ALEN) == 0 && memcmp(hdr->addr3, dev->dev_addr, ETH_ALEN) == 0) { /* ToDS frame with own addr BSSID and DA */ } else if ((fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) == IEEE80211_FCTL_FROMDS && memcmp(hdr->addr1, dev->dev_addr, ETH_ALEN) == 0) { /* FromDS frame with own addr as DA */ } else return 0; if (skb->len < 24 + 8) return 0; /* check for port access entity Ethernet type */ pos = skb->data + 24; ethertype = (pos[6] << 8) | pos[7]; if (ethertype == ETH_P_PAE) return 1; return 0; } /* Called only as a tasklet (software IRQ) */ static int hostap_rx_frame_decrypt(local_info_t *local, struct sk_buff *skb, struct ieee80211_crypt_data *crypt) { struct ieee80211_hdr_4addr *hdr; int res, hdrlen; if (crypt == NULL || crypt->ops->decrypt_mpdu == NULL) return 0; hdr = (struct ieee80211_hdr_4addr *) skb->data; hdrlen = hostap_80211_get_hdrlen(le16_to_cpu(hdr->frame_ctl)); if (local->tkip_countermeasures && strcmp(crypt->ops->name, "TKIP") == 0) { if (net_ratelimit()) { printk(KERN_DEBUG "%s: TKIP countermeasures: dropped " "received packet from " MAC_FMT "\n", local->dev->name, hdr->addr2[0], hdr->addr2[1], hdr->addr2[2], hdr->addr2[3], hdr->addr2[4], hdr->addr2[5]); } return -1; } atomic_inc(&crypt->refcnt); res = crypt->ops->decrypt_mpdu(skb, hdrlen, crypt->priv); atomic_dec(&crypt->refcnt); if (res < 0) { printk(KERN_DEBUG "%s: decryption failed (SA=" MAC_FMT ") res=%d\n", local->dev->name, hdr->addr2[0], hdr->addr2[1], hdr->addr2[2], hdr->addr2[3], hdr->addr2[4], hdr->addr2[5], res); local->comm_tallies.rx_discards_wep_undecryptable++; return -1; } return res; } /* Called only as a tasklet (software IRQ) */ static int hostap_rx_frame_decrypt_msdu(local_info_t *local, struct sk_buff *skb, int keyidx, struct ieee80211_crypt_data *crypt) { struct ieee80211_hdr_4addr *hdr; int res, hdrlen; DECLARE_MAC_BUF(mac); if (crypt == NULL || crypt->ops->decrypt_msdu == NULL) return 0; hdr = (struct ieee80211_hdr_4addr *) skb->data; hdrlen = hostap_80211_get_hdrlen(le16_to_cpu(hdr->frame_ctl)); atomic_inc(&crypt->refcnt); res = crypt->ops->decrypt_msdu(skb, keyidx, hdrlen, crypt->priv); atomic_dec(&crypt->refcnt); if (res < 0) { printk(KERN_DEBUG "%s: MSDU decryption/MIC verification failed" " (SA=%s keyidx=%d)\n", local->dev->name, print_mac(mac, hdr->addr2), keyidx); return -1; } return 0; } /* All received frames are sent to this function. @skb contains the frame in * IEEE 802.11 format, i.e., in the format it was sent over air. * This function is called only as a tasklet (software IRQ). */ void hostap_80211_rx(struct net_device *dev, struct sk_buff *skb, struct hostap_80211_rx_status *rx_stats) { struct hostap_interface *iface; local_info_t *local; struct ieee80211_hdr_4addr *hdr; size_t hdrlen; u16 fc, type, stype, sc; struct net_device *wds = NULL; struct net_device_stats *stats; unsigned int frag; u8 *payload; struct sk_buff *skb2 = NULL; u16 ethertype; int frame_authorized = 0; int from_assoc_ap = 0; u8 dst[ETH_ALEN]; u8 src[ETH_ALEN]; struct ieee80211_crypt_data *crypt = NULL; void *sta = NULL; int keyidx = 0; iface = netdev_priv(dev); local = iface->local; iface->stats.rx_packets++; iface->stats.rx_bytes += skb->len; /* dev is the master radio device; change this to be the default * virtual interface (this may be changed to WDS device below) */ dev = local->ddev; iface = netdev_priv(dev); hdr = (struct ieee80211_hdr_4addr *) skb->data; stats = hostap_get_stats(dev); if (skb->len < 10) goto rx_dropped; fc = le16_to_cpu(hdr->frame_ctl); type = WLAN_FC_GET_TYPE(fc); stype = WLAN_FC_GET_STYPE(fc); sc = le16_to_cpu(hdr->seq_ctl); frag = WLAN_GET_SEQ_FRAG(sc); hdrlen = hostap_80211_get_hdrlen(fc); /* Put this code here so that we avoid duplicating it in all * Rx paths. - Jean II */ #ifdef IW_WIRELESS_SPY /* defined in iw_handler.h */ /* If spy monitoring on */ if (iface->spy_data.spy_number > 0) { struct iw_quality wstats; wstats.level = rx_stats->signal; wstats.noise = rx_stats->noise; wstats.updated = IW_QUAL_LEVEL_UPDATED | IW_QUAL_NOISE_UPDATED | IW_QUAL_QUAL_INVALID | IW_QUAL_DBM; /* Update spy records */ wireless_spy_update(dev, hdr->addr2, &wstats); } #endif /* IW_WIRELESS_SPY */ hostap_update_rx_stats(local->ap, hdr, rx_stats); if (local->iw_mode == IW_MODE_MONITOR) { monitor_rx(dev, skb, rx_stats); return; } if (local->host_decrypt) { int idx = 0; if (skb->len >= hdrlen + 3) idx = skb->data[hdrlen + 3] >> 6; crypt = local->crypt[idx]; sta = NULL; /* Use station specific key to override default keys if the * receiver address is a unicast address ("individual RA"). If * bcrx_sta_key parameter is set, station specific key is used * even with broad/multicast targets (this is against IEEE * 802.11, but makes it easier to use different keys with * stations that do not support WEP key mapping). */ if (!(hdr->addr1[0] & 0x01) || local->bcrx_sta_key) (void) hostap_handle_sta_crypto(local, hdr, &crypt, &sta); /* allow NULL decrypt to indicate an station specific override * for default encryption */ if (crypt && (crypt->ops == NULL || crypt->ops->decrypt_mpdu == NULL)) crypt = NULL; if (!crypt && (fc & IEEE80211_FCTL_PROTECTED)) { #if 0 /* This seems to be triggered by some (multicast?) * frames from other than current BSS, so just drop the * frames silently instead of filling system log with * these reports. */ printk(KERN_DEBUG "%s: WEP decryption failed (not set)" " (SA=" MAC_FMT ")\n", local->dev->name, hdr->addr2[0], hdr->addr2[1], hdr->addr2[2], hdr->addr2[3], hdr->addr2[4], hdr->addr2[5]); #endif local->comm_tallies.rx_discards_wep_undecryptable++; goto rx_dropped; } } if (type != IEEE80211_FTYPE_DATA) { if (type == IEEE80211_FTYPE_MGMT && stype == IEEE80211_STYPE_AUTH && fc & IEEE80211_FCTL_PROTECTED && local->host_decrypt && (keyidx = hostap_rx_frame_decrypt(local, skb, crypt)) < 0) { printk(KERN_DEBUG "%s: failed to decrypt mgmt::auth " "from " MAC_FMT "\n", dev->name, hdr->addr2[0], hdr->addr2[1], hdr->addr2[2], hdr->addr2[3], hdr->addr2[4], hdr->addr2[5]); /* TODO: could inform hostapd about this so that it * could send auth failure report */ goto rx_dropped; } if (hostap_rx_frame_mgmt(local, skb, rx_stats, type, stype)) goto rx_dropped; else goto rx_exit; } /* Data frame - extract src/dst addresses */ if (skb->len < IEEE80211_DATA_HDR3_LEN) goto rx_dropped; switch (fc & (IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS)) { case IEEE80211_FCTL_FROMDS: memcpy(dst, hdr->addr1, ETH_ALEN); memcpy(src, hdr->addr3, ETH_ALEN); break; case IEEE80211_FCTL_TODS: memcpy(dst, hdr->addr3, ETH_ALEN); memcpy(src, hdr->addr2, ETH_ALEN); break; case IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS: if (skb->len < IEEE80211_DATA_HDR4_LEN) goto rx_dropped; memcpy(dst, hdr->addr3, ETH_ALEN); memcpy(src, hdr->addr4, ETH_ALEN); break; case 0: memcpy(dst, hdr->addr1, ETH_ALEN); memcpy(src, hdr->addr2, ETH_ALEN); break; } if (hostap_rx_frame_wds(local, hdr, fc, &wds)) goto rx_dropped; if (wds) { skb->dev = dev = wds; stats = hostap_get_stats(dev); } if (local->iw_mode == IW_MODE_MASTER && !wds && (fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) == IEEE80211_FCTL_FROMDS && local->stadev && memcmp(hdr->addr2, local->assoc_ap_addr, ETH_ALEN) == 0) { /* Frame from BSSID of the AP for which we are a client */ skb->dev = dev = local->stadev; stats = hostap_get_stats(dev); from_assoc_ap = 1; } dev->last_rx = jiffies; if ((local->iw_mode == IW_MODE_MASTER || local->iw_mode == IW_MODE_REPEAT) && !from_assoc_ap) { switch (hostap_handle_sta_rx(local, dev, skb, rx_stats, wds != NULL)) { case AP_RX_CONTINUE_NOT_AUTHORIZED: frame_authorized = 0; break; case AP_RX_CONTINUE: frame_authorized = 1; break; case AP_RX_DROP: goto rx_dropped; case AP_RX_EXIT: goto rx_exit; } } /* Nullfunc frames may have PS-bit set, so they must be passed to * hostap_handle_sta_rx() before being dropped here. */ if (stype != IEEE80211_STYPE_DATA && stype != IEEE80211_STYPE_DATA_CFACK && stype != IEEE80211_STYPE_DATA_CFPOLL && stype != IEEE80211_STYPE_DATA_CFACKPOLL) { if (stype != IEEE80211_STYPE_NULLFUNC) printk(KERN_DEBUG "%s: RX: dropped data frame " "with no data (type=0x%02x, subtype=0x%02x)\n", dev->name, type >> 2, stype >> 4); goto rx_dropped; } /* skb: hdr + (possibly fragmented, possibly encrypted) payload */ if (local->host_decrypt && (fc & IEEE80211_FCTL_PROTECTED) && (keyidx = hostap_rx_frame_decrypt(local, skb, crypt)) < 0) goto rx_dropped; hdr = (struct ieee80211_hdr_4addr *) skb->data; /* skb: hdr + (possibly fragmented) plaintext payload */ if (local->host_decrypt && (fc & IEEE80211_FCTL_PROTECTED) && (frag != 0 || (fc & IEEE80211_FCTL_MOREFRAGS))) { int flen; struct sk_buff *frag_skb = prism2_frag_cache_get(local, hdr); if (!frag_skb) { printk(KERN_DEBUG "%s: Rx cannot get skb from " "fragment cache (morefrag=%d seq=%u frag=%u)\n", dev->name, (fc & IEEE80211_FCTL_MOREFRAGS) != 0, WLAN_GET_SEQ_SEQ(sc) >> 4, frag); goto rx_dropped; } flen = skb->len; if (frag != 0) flen -= hdrlen; if (frag_skb->tail + flen > frag_skb->end) { printk(KERN_WARNING "%s: host decrypted and " "reassembled frame did not fit skb\n", dev->name); prism2_frag_cache_invalidate(local, hdr); goto rx_dropped; } if (frag == 0) { /* copy first fragment (including full headers) into * beginning of the fragment cache skb */ skb_copy_from_linear_data(skb, skb_put(frag_skb, flen), flen); } else { /* append frame payload to the end of the fragment * cache skb */ skb_copy_from_linear_data_offset(skb, hdrlen, skb_put(frag_skb, flen), flen); } dev_kfree_skb(skb); skb = NULL; if (fc & IEEE80211_FCTL_MOREFRAGS) { /* more fragments expected - leave the skb in fragment * cache for now; it will be delivered to upper layers * after all fragments have been received */ goto rx_exit; } /* this was the last fragment and the frame will be * delivered, so remove skb from fragment cache */ skb = frag_skb; hdr = (struct ieee80211_hdr_4addr *) skb->data; prism2_frag_cache_invalidate(local, hdr); } /* skb: hdr + (possible reassembled) full MSDU payload; possibly still * encrypted/authenticated */ if (local->host_decrypt && (fc & IEEE80211_FCTL_PROTECTED) && hostap_rx_frame_decrypt_msdu(local, skb, keyidx, crypt)) goto rx_dropped; hdr = (struct ieee80211_hdr_4addr *) skb->data; if (crypt && !(fc & IEEE80211_FCTL_PROTECTED) && !local->open_wep) { if (local->ieee_802_1x && hostap_is_eapol_frame(local, skb)) { /* pass unencrypted EAPOL frames even if encryption is * configured */ PDEBUG(DEBUG_EXTRA2, "%s: RX: IEEE 802.1X - passing " "unencrypted EAPOL frame\n", local->dev->name); } else { printk(KERN_DEBUG "%s: encryption configured, but RX " "frame not encrypted (SA=" MAC_FMT ")\n", local->dev->name, hdr->addr2[0], hdr->addr2[1], hdr->addr2[2], hdr->addr2[3], hdr->addr2[4], hdr->addr2[5]); goto rx_dropped; } } if (local->drop_unencrypted && !(fc & IEEE80211_FCTL_PROTECTED) && !hostap_is_eapol_frame(local, skb)) { if (net_ratelimit()) { printk(KERN_DEBUG "%s: dropped unencrypted RX data " "frame from " MAC_FMT " (drop_unencrypted=1)\n", dev->name, hdr->addr2[0], hdr->addr2[1], hdr->addr2[2], hdr->addr2[3], hdr->addr2[4], hdr->addr2[5]); } goto rx_dropped; } /* skb: hdr + (possible reassembled) full plaintext payload */ payload = skb->data + hdrlen; ethertype = (payload[6] << 8) | payload[7]; /* If IEEE 802.1X is used, check whether the port is authorized to send * the received frame. */ if (local->ieee_802_1x && local->iw_mode == IW_MODE_MASTER) { if (ethertype == ETH_P_PAE) { PDEBUG(DEBUG_EXTRA2, "%s: RX: IEEE 802.1X frame\n", dev->name); if (local->hostapd && local->apdev) { /* Send IEEE 802.1X frames to the user * space daemon for processing */ prism2_rx_80211(local->apdev, skb, rx_stats, PRISM2_RX_MGMT); local->apdevstats.rx_packets++; local->apdevstats.rx_bytes += skb->len; goto rx_exit; } } else if (!frame_authorized) { printk(KERN_DEBUG "%s: dropped frame from " "unauthorized port (IEEE 802.1X): " "ethertype=0x%04x\n", dev->name, ethertype); goto rx_dropped; } } /* convert hdr + possible LLC headers into Ethernet header */ if (skb->len - hdrlen >= 8 && ((memcmp(payload, rfc1042_header, 6) == 0 && ethertype != ETH_P_AARP && ethertype != ETH_P_IPX) || memcmp(payload, bridge_tunnel_header, 6) == 0)) { /* remove RFC1042 or Bridge-Tunnel encapsulation and * replace EtherType */ skb_pull(skb, hdrlen + 6); memcpy(skb_push(skb, ETH_ALEN), src, ETH_ALEN); memcpy(skb_push(skb, ETH_ALEN), dst, ETH_ALEN); } else { __be16 len; /* Leave Ethernet header part of hdr and full payload */ skb_pull(skb, hdrlen); len = htons(skb->len); memcpy(skb_push(skb, 2), &len, 2); memcpy(skb_push(skb, ETH_ALEN), src, ETH_ALEN); memcpy(skb_push(skb, ETH_ALEN), dst, ETH_ALEN); } if (wds && ((fc & (IEEE80211_FCTL_TODS | IEEE80211_FCTL_FROMDS)) == IEEE80211_FCTL_TODS) && skb->len >= ETH_HLEN + ETH_ALEN) { /* Non-standard frame: get addr4 from its bogus location after * the payload */ skb_copy_from_linear_data_offset(skb, skb->len - ETH_ALEN, skb->data + ETH_ALEN, ETH_ALEN); skb_trim(skb, skb->len - ETH_ALEN); } stats->rx_packets++; stats->rx_bytes += skb->len; if (local->iw_mode == IW_MODE_MASTER && !wds && local->ap->bridge_packets) { if (dst[0] & 0x01) { /* copy multicast frame both to the higher layers and * to the wireless media */ local->ap->bridged_multicast++; skb2 = skb_clone(skb, GFP_ATOMIC); if (skb2 == NULL) printk(KERN_DEBUG "%s: skb_clone failed for " "multicast frame\n", dev->name); } else if (hostap_is_sta_authorized(local->ap, dst)) { /* send frame directly to the associated STA using * wireless media and not passing to higher layers */ local->ap->bridged_unicast++; skb2 = skb; skb = NULL; } } if (skb2 != NULL) { /* send to wireless media */ skb2->dev = dev; skb2->protocol = __constant_htons(ETH_P_802_3); skb_reset_mac_header(skb2); skb_reset_network_header(skb2); /* skb2->network_header += ETH_HLEN; */ dev_queue_xmit(skb2); } if (skb) { skb->protocol = eth_type_trans(skb, dev); memset(skb->cb, 0, sizeof(skb->cb)); netif_rx(skb); } rx_exit: if (sta) hostap_handle_sta_release(sta); return; rx_dropped: dev_kfree_skb(skb); stats->rx_dropped++; goto rx_exit; } EXPORT_SYMBOL(hostap_80211_rx);
namgk/kernel-tut
drivers/net/wireless/hostap/hostap_80211_rx.c
C
gpl-2.0
32,866
--ダイガスタ・スフィアード function c29552709.initial_effect(c) --synchro summon aux.AddSynchroProcedure(c,nil,aux.NonTuner(Card.IsSetCard,0x10),1) c:EnableReviveLimit() --to hand local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(29552709,0)) e1:SetCategory(CATEGORY_TOHAND) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetCondition(c29552709.condition) e1:SetTarget(c29552709.target) e1:SetOperation(c29552709.operation) c:RegisterEffect(e1) --reflect local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetRange(LOCATION_MZONE) e2:SetTargetRange(LOCATION_MZONE,0) e2:SetCode(EFFECT_REFLECT_BATTLE_DAMAGE) e2:SetTarget(c29552709.reftg) e2:SetValue(1) c:RegisterEffect(e2) --indes local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e3:SetValue(1) c:RegisterEffect(e3) end function c29552709.reftg(e,c) return c:IsSetCard(0x10) end function c29552709.condition(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsSummonType(SUMMON_TYPE_SYNCHRO) end function c29552709.filter(c) return c:IsSetCard(0x10) and c:IsAbleToHand() end function c29552709.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c29552709.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c29552709.filter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectTarget(tp,c29552709.filter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0) end function c29552709.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SendtoHand(tc,nil,REASON_EFFECT) end end
mercury233/ygopro-scripts
c29552709.lua
Lua
gpl-2.0
1,832
<?php /* Written by Chris Jean for iThemes.com Version 3.0.0 Version History See history.txt */ if ( ! class_exists( 'LayoutModuleContent' ) ) { class LayoutModuleContent extends LayoutModule { var $_name = ''; var $_var = 'content'; var $_description = ''; var $_max = 1; var $_editor_width = 450; function LayoutModuleContent() { $this->_name = _x( 'Content', 'module', 'it-l10n-Builder-Madison' ); $this->_description = __( 'This module adds a place for the content to render. Most layouts will have this module.', 'it-l10n-Builder-Madison' ); $this->LayoutModule(); } function _render( $fields ) { if ( ! function_exists( 'dynamic_loop' ) || ! dynamic_loop() ) do_action( 'builder_layout_engine_render_content' ); } } new LayoutModuleContent(); }
jimrucinski/Vine
wp-content/updraft/themes-old/Builder-Madison/lib/builder-core/lib/layout-engine/modules/content/module.php
PHP
gpl-2.0
809
/** * Copyright (C) 2012-2015 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public * License version 2 and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. */ package org.n52.sos.request.operator; import java.util.Collections; import java.util.Set; import org.n52.sos.ds.AbstractDescribeSensorDAO; import org.n52.sos.ogc.ows.CompositeOwsException; import org.n52.sos.ogc.ows.OwsExceptionReport; import org.n52.sos.ogc.sos.Sos2Constants; import org.n52.sos.ogc.sos.SosConstants; import org.n52.sos.request.DescribeSensorRequest; import org.n52.sos.response.DescribeSensorResponse; import org.n52.sos.util.SosHelper; public class AqdDescribeSensorOperatorV10 extends AbstractAqdRequestOperator<AbstractDescribeSensorDAO, DescribeSensorRequest, DescribeSensorResponse> { private static final String OPERATION_NAME = SosConstants.Operations.DescribeSensor .name(); public AqdDescribeSensorOperatorV10() { super(OPERATION_NAME, DescribeSensorRequest.class); } @Override public Set<String> getConformanceClasses() { return Collections.emptySet(); } @Override public DescribeSensorResponse receive(DescribeSensorRequest request) throws OwsExceptionReport { return (DescribeSensorResponse) changeResponseServiceVersion(getDao() .getSensorDescription( (DescribeSensorRequest) changeRequestServiceVersion(request))); } @Override protected void checkParameters(DescribeSensorRequest request) throws OwsExceptionReport { CompositeOwsException exceptions = new CompositeOwsException(); try { checkServiceParameter(request.getService()); } catch (OwsExceptionReport owse) { exceptions.add(owse); } try { checkSingleVersionParameter(request); } catch (OwsExceptionReport owse) { exceptions.add(owse); } try { checkProcedureID(request.getProcedure(), SosConstants.DescribeSensorParams.procedure.name()); } catch (OwsExceptionReport owse) { exceptions.add(owse); } try { SosHelper.checkProcedureDescriptionFormat( request.getProcedureDescriptionFormat(), SosConstants.SOS, Sos2Constants.SERVICEVERSION); } catch (OwsExceptionReport owse) { exceptions.add(owse); } // if (sosRequest.isSetValidTime()) { // exceptions.add(new // OptionNotSupportedException().at(Sos2Constants.DescribeSensorParams.validTime) // .withMessage("The requested parameter is not supported by this server!")); // } checkExtensions(request, exceptions); exceptions.throwIfNotEmpty(); } }
nuest/SOS
extensions/aqd/operation/src/main/java/org/n52/sos/request/operator/AqdDescribeSensorOperatorV10.java
Java
gpl-2.0
3,618
<?php namespace Drupal\Core\Field; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\TypedData\ComplexDataInterface; /** * Interface for entity field items. * * Entity field items are typed data objects containing the field values, i.e. * implementing the ComplexDataInterface. * * When implementing this interface which extends Traversable, make sure to list * IteratorAggregate or Iterator before this interface in the implements clause. * * @see \Drupal\Core\Field\FieldItemListInterface * @see \Drupal\Core\Field\FieldItemBase * @ingroup field_types */ interface FieldItemInterface extends ComplexDataInterface { /** * Defines field item properties. * * Properties that are required to constitute a valid, non-empty item should * be denoted with \Drupal\Core\TypedData\DataDefinition::setRequired(). * * @return \Drupal\Core\TypedData\DataDefinitionInterface[] * An array of property definitions of contained properties, keyed by * property name. * * @see \Drupal\Core\Field\BaseFieldDefinition */ public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition); /** * Returns the name of the main property, if any. * * Some field items consist mainly of one main property, e.g. the value of a * text field or the target_id of an entity reference. If the field item has * no main property, the method returns NULL. * * @return string|null * The name of the value property, or NULL if there is none. * * @see \Drupal\Core\Field\BaseFieldDefinition */ public static function mainPropertyName(); /** * Returns the schema for the field. * * This method is static because the field schema information is needed on * creation of the field. FieldItemInterface objects instantiated at that * time are not reliable as field settings might be missing. * * Computed fields having no schema should return an empty array. * * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $field_definition * The field definition. * * @return array * An empty array if there is no schema, or an associative array with the * following key/value pairs: * - columns: An array of Schema API column specifications, keyed by column * name. The columns need to be a subset of the properties defined in * propertyDefinitions(). The 'not null' property is ignored if present, * as it is determined automatically by the storage controller depending * on the table layout and the property definitions. It is recommended to * avoid having the column definitions depend on field settings when * possible. No assumptions should be made on how storage engines * internally use the original column name to structure their storage. * - unique keys: (optional) An array of Schema API unique key definitions. * Only columns that appear in the 'columns' array are allowed. * - indexes: (optional) An array of Schema API index definitions. Only * columns that appear in the 'columns' array are allowed. Those indexes * will be used as default indexes. Field definitions can specify * additional indexes or, at their own risk, modify the default indexes * specified by the field-type module. Some storage engines might not * support indexes. * - foreign keys: (optional) An array of Schema API foreign key * definitions. Note, however, that the field data is not necessarily * stored in SQL. Also, the possible usage is limited, as you cannot * specify another field as related, only existing SQL tables, * such as {taxonomy_term_data}. */ public static function schema(FieldStorageDefinitionInterface $field_definition); /** * Gets the entity that field belongs to. * * @return \Drupal\Core\Entity\FieldableEntityInterface * The entity object. */ public function getEntity(); /** * Gets the langcode of the field values held in the object. * * @return string * The langcode. */ public function getLangcode(); /** * Gets the field definition. * * @return \Drupal\Core\Field\FieldDefinitionInterface * The field definition. */ public function getFieldDefinition(); /** * Magic method: Gets a property value. * * @param string $property_name * The name of the property to get; e.g., 'title' or 'name'. * * @return mixed * The property value. * * @throws \InvalidArgumentException * If a not existing property is accessed. */ public function __get($property_name); /** * Magic method: Sets a property value. * * @param string $property_name * The name of the property to set; e.g., 'title' or 'name'. * @param mixed $value * The value to set, or NULL to unset the property. Optionally, a typed * data object implementing Drupal\Core\TypedData\TypedDataInterface may be * passed instead of a plain value. * * @throws \InvalidArgumentException * If a not existing property is set. */ public function __set($property_name, $value); /** * Magic method: Determines whether a property is set. * * @param string $property_name * The name of the property to get; e.g., 'title' or 'name'. * * @return bool * Returns TRUE if the property exists and is set, FALSE otherwise. */ public function __isset($property_name); /** * Magic method: Unsets a property. * * @param string $property_name * The name of the property to get; e.g., 'title' or 'name'. */ public function __unset($property_name); /** * Returns a renderable array for a single field item. * * @param string|array $display_options * Can be either the name of a view mode, or an array of display settings. * See EntityViewBuilderInterface::viewField() for more information. * * @return array * A renderable array for the field item. * * @see \Drupal\Core\Entity\EntityViewBuilderInterface::viewField() * @see \Drupal\Core\Entity\EntityViewBuilderInterface::viewFieldItem() * @see \Drupal\Core\Field\FieldItemListInterface::view() */ public function view($display_options = []); /** * Defines custom presave behavior for field values. * * This method is called during the process of saving an entity, just before * values are written into storage. When storing a new entity, its identifier * will not be available yet. This should be used to massage item property * values or perform any other operation that needs to happen before values * are stored. For instance this is the proper phase to auto-create a new * entity for an entity reference field item, because this way it will be * possible to store the referenced entity identifier. */ public function preSave(); /** * Defines custom post-save behavior for field values. * * This method is called during the process of saving an entity, just after * values are written into storage. This is useful mostly when the business * logic to be implemented always requires the entity identifier, even when * storing a new entity. For instance, when implementing circular entity * references, the referenced entity will be created on pre-save with a dummy * value for the referring entity identifier, which will be updated with the * actual one on post-save. * * In the rare cases where item properties depend on the entity identifier, * massaging logic will have to be implemented on post-save and returning TRUE * will allow them to be rewritten to the storage with the updated values. * * @param bool $update * Specifies whether the entity is being updated or created. * * @return bool * Whether field items should be rewritten to the storage as a consequence * of the logic implemented by the custom behavior. */ public function postSave($update); /** * Defines custom delete behavior for field values. * * This method is called during the process of deleting an entity, just before * values are deleted from storage. */ public function delete(); /** * Defines custom revision delete behavior for field values. * * This method is called from during the process of deleting an entity * revision, just before the field values are deleted from storage. It is only * called for entity types that support revisioning. */ public function deleteRevision(); /** * Generates placeholder field values. * * Useful when populating site with placeholder content during site building * or profiling. * * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The field definition. * * @return array * An associative array of values. */ public static function generateSampleValue(FieldDefinitionInterface $field_definition); /** * Defines the storage-level settings for this plugin. * * @return array * A list of default settings, keyed by the setting name. */ public static function defaultStorageSettings(); /** * Defines the field-level settings for this plugin. * * @return array * A list of default settings, keyed by the setting name. */ public static function defaultFieldSettings(); /** * Returns a settings array that can be stored as a configuration value. * * For all use cases where field settings are stored and managed as * configuration, this method is used to map from the field type's * representation of its settings to a representation compatible with * deployable configuration. This includes: * - Array keys at any depth must not contain a ".". * - Ideally, array keys at any depth are either numeric or can be enumerated * as a "mapping" within the configuration schema. While not strictly * required, this simplifies configuration translation UIs, configuration * migrations between Drupal versions, and other use cases. * - To support configuration deployments, references to content entities * must use UUIDs rather than local IDs. * * An example of a conversion between representations might be an * "allowed_values" setting that's structured by the field type as a * \Drupal\Core\TypedData\OptionsProviderInterface::getPossibleOptions() * result (i.e., values as keys and labels as values). For such a use case, * in order to comply with the above, this method could convert that * representation to a numerically indexed array whose values are sub-arrays * with the schema definable keys of "value" and "label". * * @param array $settings * The field's settings in the field type's canonical representation. * * @return array * An array (either the unmodified $settings or a modified representation) * that is suitable for storing as a deployable configuration value. * * @see \Drupal\Core\Config\Config::set() */ public static function storageSettingsToConfigData(array $settings); /** * Returns a settings array in the field type's canonical representation. * * This function does the inverse of static::storageSettingsToConfigData(). It's * called when loading a field's settings from a configuration object. * * @param array $settings * The field's settings, as it is stored within a configuration object. * * @return array * The settings, in the representation expected by the field type and code * that interacts with it. * * @see \Drupal\Core\Field\FieldItemInterface::storageSettingsToConfigData() */ public static function storageSettingsFromConfigData(array $settings); /** * Returns a settings array that can be stored as a configuration value. * * Same as static::storageSettingsToConfigData(), but for the field's settings. * * @param array $settings * The field's settings in the field type's canonical representation. * * @return array * An array (either the unmodified $settings or a modified representation) * that is suitable for storing as a deployable configuration value. * * @see \Drupal\Core\Field\FieldItemInterface::storageSettingsToConfigData() */ public static function fieldSettingsToConfigData(array $settings); /** * Returns a settings array in the field type's canonical representation. * * This function does the inverse of static::fieldSettingsToConfigData(). * It's called when loading a field's settings from a configuration * object. * * @param array $settings * The field's settings, as it is stored within a configuration * object. * * @return array * The field settings, in the representation expected by the field type * and code that interacts with it. * * @see \Drupal\Core\Field\FieldItemInterface::fieldSettingsToConfigData() */ public static function fieldSettingsFromConfigData(array $settings); /** * Returns a form for the storage-level settings. * * Invoked from \Drupal\field_ui\Form\FieldStorageConfigEditForm to allow * administrators to configure storage-level settings. * * Field storage might reject settings changes that affect the field * storage schema if the storage already has data. When the $has_data * parameter is TRUE, the form should not allow changing the settings that * take part in the schema() method. It is recommended to set #access to * FALSE on the corresponding elements. * * @param array $form * The form where the settings form is being included in. * @param \Drupal\Core\Form\FormStateInterface $form_state * The form state of the (entire) configuration form. * @param bool $has_data * TRUE if the field already has data, FALSE if not. * * @return array * The form definition for the field settings. */ public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data); /** * Returns a form for the field-level settings. * * Invoked from \Drupal\field_ui\Form\FieldConfigEditForm to allow * administrators to configure field-level settings. * * @param array $form * The form where the settings form is being included in. * @param \Drupal\Core\Form\FormStateInterface $form_state * The form state of the (entire) configuration form. * * @return array * The form definition for the field settings. */ public function fieldSettingsForm(array $form, FormStateInterface $form_state); /** * Calculates dependencies for field items. * * Dependencies are saved in the field configuration entity and are used to * determine configuration synchronization order. For example, if the field * type's default value is a content entity, this method should return an * array of dependencies listing the content entities. * * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The field definition. * * @return array * An array of dependencies grouped by type (config, content, module, * theme). For example: * @code * array( * 'config' => array('user.role.anonymous', 'user.role.authenticated'), * 'content' => array('node:article:f0a189e6-55fb-47fb-8005-5bef81c44d6d'), * 'module' => array('node', 'user'), * 'theme' => array('seven'), * ); * @endcode * * @see \Drupal\Core\Config\Entity\ConfigDependencyManager * @see \Drupal\Core\Config\Entity\ConfigEntityInterface::getConfigDependencyName() */ public static function calculateDependencies(FieldDefinitionInterface $field_definition); /** * Calculates dependencies for field items on the storage level. * * Dependencies are saved in the field storage configuration entity and are * used to determine configuration synchronization order. For example, if the * field type storage depends on a particular entity type, this method should * return an array of dependencies listing the module that provides the entity * type. * * Dependencies returned from this method are stored in field storage * configuration and are always considered hard dependencies. If the * dependency is removed the field storage configuration must be deleted. * * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $field_storage_definition * The field storage definition. * * @return array * An array of dependencies grouped by type (config, content, module, * theme). For example: * @code * [ * 'config' => ['user.role.anonymous', 'user.role.authenticated'], * 'content' => ['node:article:f0a189e6-55fb-47fb-8005-5bef81c44d6d'], * 'module' => ['node', 'user'], * 'theme' => ['seven'], * ]; * @endcode * * @see \Drupal\Core\Config\Entity\ConfigDependencyManager * @see \Drupal\Core\Config\Entity\ConfigEntityInterface::getConfigDependencyName() */ public static function calculateStorageDependencies(FieldStorageDefinitionInterface $field_storage_definition); /** * Informs the plugin that a dependency of the field will be deleted. * * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The field definition. * @param array $dependencies * An array of dependencies that will be deleted keyed by dependency type. * Dependency types are, for example, entity, module and theme. * * @return bool * TRUE if the field definition has been changed as a result, FALSE if not. * * @see \Drupal\Core\Config\ConfigEntityInterface::onDependencyRemoval() */ public static function onDependencyRemoval(FieldDefinitionInterface $field_definition, array $dependencies); }
maskedjellybean/tee-prop
web/core/lib/Drupal/Core/Field/FieldItemInterface.php
PHP
gpl-2.0
17,834
/** * The abbr dialog definition. * * Created out of the CKEditor Plugin SDK: * http://docs.ckeditor.com/#!/guide/plugin_sdk_sample_1 */ // Our dialog definition. CKEDITOR.dialog.add( 'map_sc_generatorDialog', function( editor ) { return { // Basic properties of the dialog window: title, minimum size. title: 'Map Shortcode Generator', minWidth: 400, minHeight: 300, // Dialog window contents definition. contents: [ { // Definition of the Basic Settings dialog tab (page). id: 'tab-settings', label: 'Map Settings', // The tab contents. elements: [ { // Text input for map url. type: 'textarea', id: 'map-url', label: 'Map Embed Code', // Validation checking whether the field is not empty. validate: CKEDITOR.dialog.validate.notEmpty( "Map URL field cannot be empty" ) }, { // Select input for map size(height). type: 'select', id: 'map-size', label: 'Map Size', items: [ [ 'Small', 'small' ], [ 'Medium', 'medium' ], [ 'Large', 'large' ] ], 'default': 'small', }, ] }, ], // This method is invoked once a user clicks the OK button, confirming the dialog. onOk: function() { // The context of this function is the dialog object itself. // http://docs.ckeditor.com/#!/api/CKEDITOR.dialog var dialog = this; // Get Fields var mapURL = dialog.getValueOf( 'tab-settings', 'map-url' ); var url; var re1='.*?'; // Non-greedy match on filler var re2='((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s"]*))'; // HTTP URL 1 var p = new RegExp(re1+re2,["i"]); var m = p.exec(mapURL); if (m == undefined) { url = mapURL; } else { url = httpurl1=m[1]; } // Map size var mapSize = dialog.getValueOf( 'tab-settings', 'map-size' ); editor.insertHtml( '[map size="' + mapSize + '"]' + url + '[/map]'); } }; });
alexfinnarn/express
modules/custom/cu_shortcodes_wysiwyg/plugins/map_sc_generator/dialogs/map_sc_generator.js
JavaScript
gpl-2.0
1,946
/* * Advanced Linux Sound Architecture Control Program - Parse initialization files * Copyright (c) by Jaroslav Kysela <perex@perex.cz>, * Greg Kroah-Hartman <greg@kroah.com>, * Kay Sievers <kay.sievers@vrfy.org> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <stdlib.h> #include <stdio.h> #include <stddef.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <ctype.h> #include <errno.h> #include <fnmatch.h> #include <sys/stat.h> #include <sys/un.h> #include <sys/wait.h> #include <sys/select.h> #include <sys/types.h> #include <dirent.h> #include <math.h> #include <alsa/asoundlib.h> #include "aconfig.h" #include "alsactl.h" #include "list.h" #define PATH_SIZE 512 #define NAME_SIZE 128 #define EJUSTRETURN 0x7fffffff enum key_op { KEY_OP_UNSET, KEY_OP_MATCH, KEY_OP_NOMATCH, KEY_OP_ADD, KEY_OP_ASSIGN, KEY_OP_ASSIGN_FINAL }; struct pair { char *key; char *value; struct pair *next; }; struct space { struct pair *pairs; char *rootdir; char *go_to; char *program_result; const char *filename; int linenum; int log_run; int exit_code; int quit; unsigned int ctl_id_changed; snd_hctl_t *ctl_handle; snd_ctl_card_info_t *ctl_card_info; snd_ctl_elem_id_t *ctl_id; snd_ctl_elem_info_t *ctl_info; snd_ctl_elem_value_t *ctl_value; }; static void Perror(struct space *space, const char *fmt, ...) { va_list arg; va_start(arg, fmt); fprintf(stderr, "%s:%i: ", space->filename, space->linenum); vfprintf(stderr, fmt, arg); putc('\n', stderr); va_end(arg); } #include "init_sysdeps.c" #include "init_utils_string.c" #include "init_utils_run.c" #include "init_sysfs.c" static void free_space(struct space *space) { struct pair *pair = space->pairs; struct pair *next = pair; while (next) { pair = next; next = pair->next; free(pair->value); free(pair->key); free(pair); } space->pairs = NULL; if (space->ctl_value) { snd_ctl_elem_value_free(space->ctl_value); space->ctl_value = NULL; } if (space->ctl_info) { snd_ctl_elem_info_free(space->ctl_info); space->ctl_info = NULL; } if (space->ctl_id) { snd_ctl_elem_id_free(space->ctl_id); space->ctl_id = NULL; } if (space->ctl_card_info) { snd_ctl_card_info_free(space->ctl_card_info); space->ctl_card_info = NULL; } if (space->ctl_handle) { snd_hctl_close(space->ctl_handle); space->ctl_handle = NULL; } if (space->rootdir) free(space->rootdir); if (space->program_result) free(space->program_result); if (space->go_to) free(space->go_to); free(space); } static struct pair *value_find(struct space *space, const char *key) { struct pair *pair = space->pairs; while (pair && strcmp(pair->key, key) != 0) pair = pair->next; return pair; } static int value_set(struct space *space, const char *key, const char *value) { struct pair *pair; pair = value_find(space, key); if (pair) { free(pair->value); pair->value = strdup(value); if (pair->value == NULL) return -ENOMEM; } else { pair = malloc(sizeof(struct pair)); if (pair == NULL) return -ENOMEM; pair->key = strdup(key); if (pair->key == NULL) { free(pair); return -ENOMEM; } pair->value = strdup(value); if (pair->value == NULL) { free(pair->key); free(pair); return -ENOMEM; } pair->next = space->pairs; space->pairs = pair; } return 0; } static int init_space(struct space **space, int card) { struct space *res; char device[16]; int err; res = calloc(1, sizeof(struct space)); if (res == NULL) return -ENOMEM; res->ctl_id_changed = ~0; res->linenum = -1; sprintf(device, "hw:%u", card); err = snd_hctl_open(&res->ctl_handle, device, 0); if (err < 0) goto error; err = snd_hctl_load(res->ctl_handle); if (err < 0) goto error; err = snd_ctl_card_info_malloc(&res->ctl_card_info); if (err < 0) goto error; err = snd_ctl_card_info(snd_hctl_ctl(res->ctl_handle), res->ctl_card_info); if (err < 0) goto error; err = snd_ctl_elem_id_malloc(&res->ctl_id); if (err < 0) goto error; err = snd_ctl_elem_info_malloc(&res->ctl_info); if (err < 0) goto error; err = snd_ctl_elem_value_malloc(&res->ctl_value); if (err < 0) goto error; *space = res; return 0; error: free_space(res); return err; } static const char *cardinfo_get(struct space *space, const char *attr) { if (strncasecmp(attr, "CARD", 4) == 0) { static char res[16]; sprintf(res, "%u", snd_ctl_card_info_get_card(space->ctl_card_info)); return res; } if (strncasecmp(attr, "ID", 2) == 0) return snd_ctl_card_info_get_id(space->ctl_card_info); if (strncasecmp(attr, "DRIVER", 6) == 0) return snd_ctl_card_info_get_driver(space->ctl_card_info); if (strncasecmp(attr, "NAME", 4) == 0) return snd_ctl_card_info_get_name(space->ctl_card_info); if (strncasecmp(attr, "LONGNAME", 8) == 0) return snd_ctl_card_info_get_longname(space->ctl_card_info); if (strncasecmp(attr, "MIXERNAME", 9) == 0) return snd_ctl_card_info_get_mixername(space->ctl_card_info); if (strncasecmp(attr, "COMPONENTS", 10) == 0) return snd_ctl_card_info_get_components(space->ctl_card_info); Perror(space, "unknown cardinfo{} attribute '%s'", attr); return NULL; } static int check_id_changed(struct space *space, unsigned int what) { snd_hctl_elem_t *elem; int err; if ((space->ctl_id_changed & what & 1) != 0) { snd_ctl_elem_id_set_numid(space->ctl_id, 0); elem = snd_hctl_find_elem(space->ctl_handle, space->ctl_id); if (!elem) return -ENOENT; err = snd_hctl_elem_info(elem, space->ctl_info); if (err == 0) space->ctl_id_changed &= ~1; return err; } if ((space->ctl_id_changed & what & 2) != 0) { snd_ctl_elem_id_set_numid(space->ctl_id, 0); elem = snd_hctl_find_elem(space->ctl_handle, space->ctl_id); if (!elem) return -ENOENT; err = snd_hctl_elem_read(elem, space->ctl_value); if (err == 0) space->ctl_id_changed &= ~2; return err; } return 0; } static const char *get_ctl_value(struct space *space) { snd_ctl_elem_type_t type; unsigned int idx, count; static char res[1024], tmp[16]; static const char hex[] = "0123456789abcdef"; char *pos; const char *pos1; type = snd_ctl_elem_info_get_type(space->ctl_info); count = snd_ctl_elem_info_get_count(space->ctl_info); res[0] = '\0'; switch (type) { case SND_CTL_ELEM_TYPE_BOOLEAN: for (idx = 0; idx < count; idx++) { if (idx > 0) strlcat(res, ",", sizeof(res)); strlcat(res, snd_ctl_elem_value_get_boolean(space->ctl_value, idx) ? "on" : "off", sizeof(res)); } break; case SND_CTL_ELEM_TYPE_INTEGER: for (idx = 0; idx < count; idx++) { if (idx > 0) strlcat(res, ",", sizeof(res)); snprintf(tmp, sizeof(tmp), "%li", snd_ctl_elem_value_get_integer(space->ctl_value, idx)); strlcat(res, tmp, sizeof(res)); } break; case SND_CTL_ELEM_TYPE_INTEGER64: for (idx = 0; idx < count; idx++) { if (idx > 0) strlcat(res, ",", sizeof(res)); snprintf(tmp, sizeof(tmp), "%lli", snd_ctl_elem_value_get_integer64(space->ctl_value, idx)); strlcat(res, tmp, sizeof(res)); } break; case SND_CTL_ELEM_TYPE_ENUMERATED: for (idx = 0; idx < count; idx++) { if (idx > 0) strlcat(res, ",", sizeof(res)); snprintf(tmp, sizeof(tmp), "%u", snd_ctl_elem_value_get_enumerated(space->ctl_value, idx)); strlcat(res, tmp, sizeof(res)); } break; case SND_CTL_ELEM_TYPE_BYTES: case SND_CTL_ELEM_TYPE_IEC958: if (type == SND_CTL_ELEM_TYPE_IEC958) count = sizeof(snd_aes_iec958_t); if (count > (sizeof(res)-1)/2) count = (sizeof(res)-1/2); pos = res; pos1 = snd_ctl_elem_value_get_bytes(space->ctl_value); while (count > 0) { idx = *pos1++; *pos++ = hex[idx >> 4]; *pos++ = hex[idx & 0x0f]; count++; } *pos++ = '\0'; break; default: Perror(space, "unknown element type '%i'", type); return NULL; } return res; } /* Function to convert from percentage to volume. val = percentage */ #define convert_prange1(val, min, max) \ ceil((val) * ((max) - (min)) * 0.01 + (min)) static int set_ctl_value(struct space *space, const char *value, int all) { snd_ctl_elem_type_t type; unsigned int idx, idx2, count, items; const char *pos, *pos2; snd_hctl_elem_t *elem; int val; long lval; type = snd_ctl_elem_info_get_type(space->ctl_info); count = snd_ctl_elem_info_get_count(space->ctl_info); switch (type) { case SND_CTL_ELEM_TYPE_BOOLEAN: for (idx = 0; idx < count; idx++) { while (*value == ' ') value++; if (*value == '\0') goto missing; val = strncasecmp(value, "true", 4) == 0 || strncasecmp(value, "yes", 3) == 0 || strncasecmp(value, "on", 2) == 0 || strncasecmp(value, "1", 1) == 0; snd_ctl_elem_value_set_boolean(space->ctl_value, idx, val); if (all) continue; pos = strchr(value, ','); value = pos ? pos + 1 : value + strlen(value) - 1; } break; case SND_CTL_ELEM_TYPE_INTEGER: for (idx = 0; idx < count; idx++) { while (*value == ' ') value++; pos = strchr(value, ','); if (pos) *(char *)pos = '\0'; remove_trailing_chars((char *)value, ' '); items = pos ? pos - value : strlen(value); if (items > 1 && value[items-1] == '%') { val = convert_prange1(strtol(value, NULL, 0), snd_ctl_elem_info_get_min(space->ctl_info), snd_ctl_elem_info_get_max(space->ctl_info)); snd_ctl_elem_value_set_integer(space->ctl_value, idx, val); } else if (items > 2 && value[items-2] == 'd' && value[items-1] == 'B') { val = strtol(value, NULL, 0) * 100; if ((pos2 = strchr(value, '.')) != NULL) { if (isdigit(*(pos2-1)) && isdigit(*(pos2-2))) { if (val < 0) val -= strtol(pos2 + 1, NULL, 0); else val += strtol(pos2 + 1, NULL, 0); } else if (isdigit(*(pos2-1))) { if (val < 0) val -= strtol(pos2 + 1, NULL, 0) * 10; else val += strtol(pos2 + 1, NULL, 0) * 10; } } val = snd_ctl_convert_from_dB(snd_hctl_ctl(space->ctl_handle), space->ctl_id, val, &lval, -1); if (val < 0) { dbg("unable to convert dB value '%s' to internal integer range", value); return val; } snd_ctl_elem_value_set_integer(space->ctl_value, idx, lval); } else { snd_ctl_elem_value_set_integer(space->ctl_value, idx, strtol(value, NULL, 0)); } if (all) continue; value = pos ? pos + 1 : value + strlen(value) - 1; } break; case SND_CTL_ELEM_TYPE_INTEGER64: for (idx = 0; idx < count; idx++) { while (*value == ' ') value++; snd_ctl_elem_value_set_integer64(space->ctl_value, idx, strtoll(value, NULL, 0)); if (all) continue; pos = strchr(value, ','); value = pos ? pos + 1 : value + strlen(value) - 1; } break; case SND_CTL_ELEM_TYPE_ENUMERATED: for (idx = 0; idx < count; idx++) { while (*value == ' ') value++; pos = strchr(value, ','); if (isdigit(value[0]) || value[0] == '-') { snd_ctl_elem_value_set_enumerated(space->ctl_value, idx, strtol(value, NULL, 0)); } else { if (pos) *(char *)pos = '\0'; remove_trailing_chars((char *)value, ' '); items = snd_ctl_elem_info_get_items(space->ctl_info); for (idx2 = 0; idx2 < items; idx2++) { snd_ctl_elem_info_set_item(space->ctl_info, idx2); elem = snd_hctl_find_elem(space->ctl_handle, space->ctl_id); if (elem == NULL) return -ENOENT; val = snd_hctl_elem_info(elem, space->ctl_info); if (val < 0) return val; if (strcasecmp(snd_ctl_elem_info_get_item_name(space->ctl_info), value) == 0) { snd_ctl_elem_value_set_enumerated(space->ctl_value, idx, idx2); break; } } if (idx2 >= items) { Perror(space, "wrong enum identifier '%s'", value); return -EINVAL; } } if (all) continue; value = pos ? pos + 1 : value + strlen(value) - 1; } break; case SND_CTL_ELEM_TYPE_BYTES: case SND_CTL_ELEM_TYPE_IEC958: if (type == SND_CTL_ELEM_TYPE_IEC958) count = sizeof(snd_aes_iec958_t); while (*value == ' ') value++; if (strlen(value) != count * 2) { Perror(space, "bad ctl value hexa length (should be %u bytes)", count); return -EINVAL; } for (idx = 0; idx < count; idx += 2) { val = hextodigit(*(value++)) << 4; val |= hextodigit(*(value++)); if (val > 255) { Perror(space, "bad ctl hexa value"); return -EINVAL; } snd_ctl_elem_value_set_byte(space->ctl_value, idx, val); } break; default: Perror(space, "unknown element type '%i'", type); return -EINVAL; } return 0; missing: printf("%i %i\n", type, count); Perror(space, "missing some ctl values (line %i)", space->linenum); return -EINVAL; } static int do_match(const char *key, enum key_op op, const char *key_value, const char *value) { int match; if (value == NULL) return 0; dbg("match %s '%s' <-> '%s'", key, key_value, value); match = fnmatch(key_value, value, 0) == 0; if (match && op == KEY_OP_MATCH) { dbg("%s is true (matching value)", key); return 1; } if (!match && op == KEY_OP_NOMATCH) { dbg("%s is true (non-matching value)", key); return 1; } dbg("%s is false", key); return 0; } static int ctl_match(snd_ctl_elem_id_t *pattern, snd_ctl_elem_id_t *id) { if (snd_ctl_elem_id_get_interface(pattern) != -1 && snd_ctl_elem_id_get_interface(pattern) != snd_ctl_elem_id_get_interface(id)) return 0; if (snd_ctl_elem_id_get_device(pattern) != -1 && snd_ctl_elem_id_get_device(pattern) != snd_ctl_elem_id_get_device(id)) return 0; if (snd_ctl_elem_id_get_subdevice(pattern) != -1 && snd_ctl_elem_id_get_subdevice(pattern) != snd_ctl_elem_id_get_subdevice(id)) return 0; if (snd_ctl_elem_id_get_index(pattern) != -1 && snd_ctl_elem_id_get_index(pattern) != snd_ctl_elem_id_get_index(id)) return 0; if (fnmatch(snd_ctl_elem_id_get_name(pattern), snd_ctl_elem_id_get_name(id), 0) != 0) return 0; return 1; } static const char *elemid_get(struct space *space, const char *attr) { long long val; snd_ctl_elem_type_t type; static char res[256]; if (strncasecmp(attr, "numid", 5) == 0) { val = snd_ctl_elem_id_get_numid(space->ctl_id); goto value; } if (strncasecmp(attr, "iface", 5) == 0 || strncasecmp(attr, "interface", 9) == 0) return snd_ctl_elem_iface_name(snd_ctl_elem_id_get_interface(space->ctl_id)); if (strncasecmp(attr, "device", 6) == 0) { val = snd_ctl_elem_id_get_device(space->ctl_id); goto value; } if (strncasecmp(attr, "subdev", 6) == 0) { val = snd_ctl_elem_id_get_subdevice(space->ctl_id); goto value; } if (strncasecmp(attr, "name", 4) == 0) return snd_ctl_elem_id_get_name(space->ctl_id); if (strncasecmp(attr, "index", 5) == 0) { val = snd_ctl_elem_id_get_index(space->ctl_id); goto value; } if (strncasecmp(attr, "type", 4) == 0) { if (check_id_changed(space, 1)) return NULL; return snd_ctl_elem_type_name(snd_ctl_elem_info_get_type(space->ctl_info)); } if (strncasecmp(attr, "attr", 4) == 0) { if (check_id_changed(space, 1)) return NULL; res[0] = '\0'; if (snd_ctl_elem_info_is_readable(space->ctl_info)) strcat(res, "r"); if (snd_ctl_elem_info_is_writable(space->ctl_info)) strcat(res, "w"); if (snd_ctl_elem_info_is_volatile(space->ctl_info)) strcat(res, "v"); if (snd_ctl_elem_info_is_inactive(space->ctl_info)) strcat(res, "i"); if (snd_ctl_elem_info_is_locked(space->ctl_info)) strcat(res, "l"); if (snd_ctl_elem_info_is_tlv_readable(space->ctl_info)) strcat(res, "R"); if (snd_ctl_elem_info_is_tlv_writable(space->ctl_info)) strcat(res, "W"); if (snd_ctl_elem_info_is_tlv_commandable(space->ctl_info)) strcat(res, "C"); if (snd_ctl_elem_info_is_owner(space->ctl_info)) strcat(res, "o"); if (snd_ctl_elem_info_is_user(space->ctl_info)) strcat(res, "u"); return res; } if (strncasecmp(attr, "owner", 5) == 0) { if (check_id_changed(space, 1)) return NULL; val = snd_ctl_elem_info_get_owner(space->ctl_info); goto value; } if (strncasecmp(attr, "count", 5) == 0) { if (check_id_changed(space, 1)) return NULL; val = snd_ctl_elem_info_get_count(space->ctl_info); goto value; } if (strncasecmp(attr, "min", 3) == 0) { if (check_id_changed(space, 1)) return NULL; type = snd_ctl_elem_info_get_type(space->ctl_info); if (type == SND_CTL_ELEM_TYPE_INTEGER64) val = snd_ctl_elem_info_get_min64(space->ctl_info); else if (type == SND_CTL_ELEM_TYPE_INTEGER) val = snd_ctl_elem_info_get_min(space->ctl_info); else goto empty; goto value; } if (strncasecmp(attr, "max", 3) == 0) { if (check_id_changed(space, 1)) return NULL; type = snd_ctl_elem_info_get_type(space->ctl_info); if (type == SND_CTL_ELEM_TYPE_INTEGER64) val = snd_ctl_elem_info_get_max64(space->ctl_info); else if (type == SND_CTL_ELEM_TYPE_INTEGER) val = snd_ctl_elem_info_get_max(space->ctl_info); else goto empty; goto value; } if (strncasecmp(attr, "step", 3) == 0) { if (check_id_changed(space, 1)) return NULL; type = snd_ctl_elem_info_get_type(space->ctl_info); if (type == SND_CTL_ELEM_TYPE_INTEGER64) val = snd_ctl_elem_info_get_step64(space->ctl_info); else if (type == SND_CTL_ELEM_TYPE_INTEGER) val = snd_ctl_elem_info_get_step(space->ctl_info); else goto empty; goto value; } if (strncasecmp(attr, "items", 5) == 0) { if (check_id_changed(space, 1)) return NULL; if (snd_ctl_elem_info_get_type(space->ctl_info) == SND_CTL_ELEM_TYPE_ENUMERATED) val = snd_ctl_elem_info_get_items(space->ctl_info); else { empty: res[0] = '\0'; return res; } goto value; } if (strncasecmp(attr, "value", 5) == 0) { if (check_id_changed(space, 3)) return NULL; return get_ctl_value(space); } if (strncasecmp(attr, "dBmin", 5) == 0) { long min, max; if (check_id_changed(space, 1)) return NULL; if (snd_ctl_get_dB_range(snd_hctl_ctl(space->ctl_handle), space->ctl_id, &min, &max) < 0) goto empty; val = min; dbvalue: sprintf(res, "%li.%02idB", (long)(val / 100), (int)abs(val % 100)); return res; } if (strncasecmp(attr, "dBmax", 5) == 0) { long min, max; if (check_id_changed(space, 1)) return NULL; if (snd_ctl_get_dB_range(snd_hctl_ctl(space->ctl_handle), space->ctl_id, &min, &max) < 0) goto empty; val = max; goto dbvalue; } if (strncasecmp(attr, "enums", 5) == 0) { unsigned int idx, items; snd_hctl_elem_t *elem; if (check_id_changed(space, 1)) return NULL; if (snd_ctl_elem_info_get_type(space->ctl_info) != SND_CTL_ELEM_TYPE_ENUMERATED) goto empty; items = snd_ctl_elem_info_get_items(space->ctl_info); strcpy(res, "|"); for (idx = 0; idx < items; idx++) { snd_ctl_elem_info_set_item(space->ctl_info, idx); elem = snd_hctl_find_elem(space->ctl_handle, space->ctl_id); if (elem == NULL) break; if (snd_hctl_elem_info(elem, space->ctl_info) < 0) break; strlcat(res, snd_ctl_elem_info_get_item_name(space->ctl_info), sizeof(res)); strlcat(res, "|", sizeof(res)); } return res; } if (strncasecmp(attr, "do_search", 9) == 0) { int err, index = 0; snd_hctl_elem_t *elem; snd_ctl_elem_id_t *id; char *pos = strchr(attr, ' '); if (pos) index = strtol(pos, NULL, 0); err = snd_ctl_elem_id_malloc(&id); if (err < 0) return NULL; elem = snd_hctl_first_elem(space->ctl_handle); while (elem) { snd_hctl_elem_get_id(elem, id); if (!ctl_match(space->ctl_id, id)) goto next_search; if (index > 0) { index--; goto next_search; } strcpy(res, "1"); snd_ctl_elem_id_copy(space->ctl_id, id); snd_ctl_elem_id_free(id); dbg("do_ctl_search found a control"); return res; next_search: elem = snd_hctl_elem_next(elem); } snd_ctl_elem_id_free(id); strcpy(res, "0"); return res; } if (strncasecmp(attr, "do_count", 8) == 0) { int err, index = 0; snd_hctl_elem_t *elem; snd_ctl_elem_id_t *id; err = snd_ctl_elem_id_malloc(&id); if (err < 0) return NULL; elem = snd_hctl_first_elem(space->ctl_handle); while (elem) { snd_hctl_elem_get_id(elem, id); if (ctl_match(space->ctl_id, id)) index++; elem = snd_hctl_elem_next(elem); } snd_ctl_elem_id_free(id); sprintf(res, "%u", index); dbg("do_ctl_count found %s controls", res); return res; } Perror(space, "unknown ctl{} attribute '%s'", attr); return NULL; value: sprintf(res, "%lli", val); return res; } static int elemid_set(struct space *space, const char *attr, const char *value) { unsigned int val; void (*fcn)(snd_ctl_elem_id_t *, unsigned int); snd_ctl_elem_iface_t iface; int err; if (strncasecmp(attr, "numid", 5) == 0) { fcn = snd_ctl_elem_id_set_numid; goto value; } if (strncasecmp(attr, "iface", 5) == 0 || strncasecmp(attr, "interface", 9) == 0 || strncasecmp(attr, "reset", 5) == 0 || strncasecmp(attr, "search", 6) == 0) { if (strlen(value) == 0 && strncasecmp(attr, "search", 6) == 0) { iface = 0; goto search; } for (iface = 0; iface <= SND_CTL_ELEM_IFACE_LAST; iface++) { if (strcasecmp(value, snd_ctl_elem_iface_name(iface)) == 0) { if (strncasecmp(attr, "reset", 5) == 0) snd_ctl_elem_id_clear(space->ctl_id); if (strncasecmp(attr, "search", 5) == 0) { search: snd_ctl_elem_id_clear(space->ctl_id); /* -1 means all */ snd_ctl_elem_id_set_interface(space->ctl_id, -1); snd_ctl_elem_id_set_device(space->ctl_id, -1); snd_ctl_elem_id_set_subdevice(space->ctl_id, -1); snd_ctl_elem_id_set_name(space->ctl_id, "*"); snd_ctl_elem_id_set_index(space->ctl_id, -1); if (strlen(value) == 0) return 0; } snd_ctl_elem_id_set_interface(space->ctl_id, iface); space->ctl_id_changed = ~0; return 0; } } Perror(space, "unknown control interface name '%s'", value); return -EINVAL; } if (strncasecmp(attr, "device", 6) == 0) { fcn = snd_ctl_elem_id_set_device; goto value; } if (strncasecmp(attr, "subdev", 6) == 0) { fcn = snd_ctl_elem_id_set_subdevice; goto value; } if (strncasecmp(attr, "name", 4) == 0) { snd_ctl_elem_id_set_name(space->ctl_id, value); space->ctl_id_changed = ~0; return 0; } if (strncasecmp(attr, "index", 5) == 0) { fcn = snd_ctl_elem_id_set_index; goto value; } if (strncasecmp(attr, "values", 6) == 0 || strncasecmp(attr, "value", 5) == 0) { err = check_id_changed(space, 1); if (err < 0) { Perror(space, "control element not found"); return err; } err = set_ctl_value(space, value, strncasecmp(attr, "values", 6) == 0); if (err < 0) { space->ctl_id_changed |= 2; } else { space->ctl_id_changed &= ~2; snd_ctl_elem_value_set_id(space->ctl_value, space->ctl_id); err = snd_ctl_elem_write(snd_hctl_ctl(space->ctl_handle), space->ctl_value); if (err < 0) { Perror(space, "value write error: %s", snd_strerror(err)); return err; } } return err; } Perror(space, "unknown CTL{} attribute '%s'", attr); return -EINVAL; value: val = (unsigned int)strtol(value, NULL, 0); fcn(space->ctl_id, val); space->ctl_id_changed = ~0; return 0; } static int get_key(char **line, char **key, enum key_op *op, char **value) { char *linepos; char *temp; linepos = *line; if (linepos == NULL && linepos[0] == '\0') return -EINVAL; /* skip whitespace */ while (isspace(linepos[0]) || linepos[0] == ',') linepos++; /* get the key */ if (linepos[0] == '\0') return -EINVAL; *key = linepos; while (1) { linepos++; if (linepos[0] == '\0') return -1; if (isspace(linepos[0])) break; if (linepos[0] == '=') break; if (linepos[0] == '+') break; if (linepos[0] == '!') break; if (linepos[0] == ':') break; } /* remember end of key */ temp = linepos; /* skip whitespace after key */ while (isspace(linepos[0])) linepos++; if (linepos[0] == '\0') return -EINVAL; /* get operation type */ if (linepos[0] == '=' && linepos[1] == '=') { *op = KEY_OP_MATCH; linepos += 2; dbg("operator=match"); } else if (linepos[0] == '!' && linepos[1] == '=') { *op = KEY_OP_NOMATCH; linepos += 2; dbg("operator=nomatch"); } else if (linepos[0] == '+' && linepos[1] == '=') { *op = KEY_OP_ADD; linepos += 2; dbg("operator=add"); } else if (linepos[0] == '=') { *op = KEY_OP_ASSIGN; linepos++; dbg("operator=assign"); } else if (linepos[0] == ':' && linepos[1] == '=') { *op = KEY_OP_ASSIGN_FINAL; linepos += 2; dbg("operator=assign_final"); } else return -EINVAL; /* terminate key */ temp[0] = '\0'; dbg("key='%s'", *key); /* skip whitespace after operator */ while (isspace(linepos[0])) linepos++; if (linepos[0] == '\0') return -EINVAL; /* get the value*/ if (linepos[0] != '"') return -EINVAL; linepos++; *value = linepos; while (1) { temp = strchr(linepos, '"'); if (temp && temp[-1] == '\\') { linepos = temp + 1; continue; } break; } if (!temp) return -EINVAL; temp[0] = '\0'; temp++; dbg("value='%s'", *value); /* move line to next key */ *line = temp; return 0; } /* extract possible KEY{attr} */ static char *get_key_attribute(struct space *space, char *str, char *res, size_t ressize) { char *pos; char *attr; attr = strchr(str, '{'); if (attr != NULL) { attr++; pos = strchr(attr, '}'); if (pos == NULL) { Perror(space, "missing closing brace for format"); return NULL; } pos[0] = '\0'; strlcpy(res, attr, ressize); pos[0] = '}'; dbg("attribute='%s'", res); return res; } return NULL; } /* extract possible {attr} and move str behind it */ static char *get_format_attribute(struct space *space, char **str) { char *pos; char *attr = NULL; if (*str[0] == '{') { pos = strchr(*str, '}'); if (pos == NULL) { Perror(space, "missing closing brace for format"); return NULL; } pos[0] = '\0'; attr = *str+1; *str = pos+1; dbg("attribute='%s', str='%s'", attr, *str); } return attr; } /* extract possible format length and move str behind it*/ static int get_format_len(struct space *space, char **str) { int num; char *tail; if (isdigit(*str[0])) { num = (int) strtoul(*str, &tail, 10); if (num > 0) { *str = tail; dbg("format length=%i", num); return num; } else { Perror(space, "format parsing error '%s'", *str); } } return -1; } static void apply_format(struct space *space, char *string, size_t maxsize) { char temp[PATH_SIZE]; char temp2[PATH_SIZE]; char *head, *tail, *pos, *cpos, *attr, *rest; struct pair *pair; int len; int i; int count; enum subst_type { SUBST_UNKNOWN, SUBST_CARDINFO, SUBST_CTL, SUBST_RESULT, SUBST_ATTR, SUBST_SYSFSROOT, SUBST_ENV, SUBST_CONFIG, }; static const struct subst_map { char *name; char fmt; enum subst_type type; } map[] = { { .name = "cardinfo", .fmt = 'i', .type = SUBST_CARDINFO }, { .name = "ctl", .fmt = 'C', .type = SUBST_CTL }, { .name = "result", .fmt = 'c', .type = SUBST_RESULT }, { .name = "attr", .fmt = 's', .type = SUBST_ATTR }, { .name = "sysfsroot", .fmt = 'r', .type = SUBST_SYSFSROOT }, { .name = "env", .fmt = 'E', .type = SUBST_ENV }, { .name = "config", .fmt = 'g', .type = SUBST_CONFIG }, { NULL, '\0', 0 } }; enum subst_type type; const struct subst_map *subst; head = string; while (1) { len = -1; while (head[0] != '\0') { if (head[0] == '$') { /* substitute named variable */ if (head[1] == '\0') break; if (head[1] == '$') { strlcpy(temp, head+2, sizeof(temp)); strlcpy(head+1, temp, maxsize); head++; continue; } head[0] = '\0'; for (subst = map; subst->name; subst++) { if (strncasecmp(&head[1], subst->name, strlen(subst->name)) == 0) { type = subst->type; tail = head + strlen(subst->name)+1; dbg("will substitute format name '%s'", subst->name); goto found; } } } else if (head[0] == '%') { /* substitute format char */ if (head[1] == '\0') break; if (head[1] == '%') { strlcpy(temp, head+2, sizeof(temp)); strlcpy(head+1, temp, maxsize); head++; continue; } head[0] = '\0'; tail = head+1; len = get_format_len(space, &tail); for (subst = map; subst->name; subst++) { if (tail[0] == subst->fmt) { type = subst->type; tail++; dbg("will substitute format char '%c'", subst->fmt); goto found; } } } head++; } break; found: attr = get_format_attribute(space, &tail); strlcpy(temp, tail, sizeof(temp)); dbg("format=%i, string='%s', tail='%s'", type ,string, tail); switch (type) { case SUBST_CARDINFO: if (attr == NULL) Perror(space, "missing identification parametr for cardinfo"); else { const char *value = cardinfo_get(space, attr); if (value == NULL) break; strlcat(string, value, maxsize); dbg("substitute cardinfo{%s} '%s'", attr, value); } break; case SUBST_CTL: if (attr == NULL) Perror(space, "missing identification parametr for ctl"); else { const char *value = elemid_get(space, attr); if (value == NULL) break; strlcat(string, value, maxsize); dbg("substitute ctl{%s} '%s'", attr, value); } break; case SUBST_RESULT: if (space->program_result == NULL) break; /* get part part of the result string */ i = 0; if (attr != NULL) i = strtoul(attr, &rest, 10); if (i > 0) { dbg("request part #%d of result string", i); cpos = space->program_result; while (--i) { while (cpos[0] != '\0' && !isspace(cpos[0])) cpos++; while (isspace(cpos[0])) cpos++; } if (i > 0) { Perror(space, "requested part of result string not found"); break; } strlcpy(temp2, cpos, sizeof(temp2)); /* %{2+}c copies the whole string from the second part on */ if (rest[0] != '+') { cpos = strchr(temp2, ' '); if (cpos) cpos[0] = '\0'; } strlcat(string, temp2, maxsize); dbg("substitute part of result string '%s'", temp2); } else { strlcat(string, space->program_result, maxsize); dbg("substitute result string '%s'", space->program_result); } break; case SUBST_ATTR: if (attr == NULL) Perror(space, "missing file parameter for attr"); else { const char *value = NULL; size_t size; pair = value_find(space, "sysfs_device"); if (pair == NULL) break; value = sysfs_attr_get_value(pair->value, attr); if (value == NULL) break; /* strip trailing whitespace and replace untrusted characters of sysfs value */ size = strlcpy(temp2, value, sizeof(temp2)); if (size >= sizeof(temp2)) size = sizeof(temp2)-1; while (size > 0 && isspace(temp2[size-1])) temp2[--size] = '\0'; count = replace_untrusted_chars(temp2); if (count > 0) Perror(space, "%i untrusted character(s) replaced" , count); strlcat(string, temp2, maxsize); dbg("substitute sysfs value '%s'", temp2); } break; case SUBST_SYSFSROOT: strlcat(string, sysfs_path, maxsize); dbg("substitute sysfs_path '%s'", sysfs_path); break; case SUBST_ENV: if (attr == NULL) { dbg("missing attribute"); break; } pos = getenv(attr); if (pos == NULL) { dbg("env '%s' not available", attr); break; } dbg("substitute env '%s=%s'", attr, pos); strlcat(string, pos, maxsize); break; case SUBST_CONFIG: if (attr == NULL) { dbg("missing attribute"); break; } pair = value_find(space, attr); if (pair == NULL) break; strlcat(string, pair->value, maxsize); break; default: Perror(space, "unknown substitution type=%i", type); break; } /* possibly truncate to format-char specified length */ if (len != -1) { head[len] = '\0'; dbg("truncate to %i chars, subtitution string becomes '%s'", len, head); } strlcat(string, temp, maxsize); } /* unescape strings */ head = tail = string; while (*head != '\0') { if (*head == '\\') { head++; if (*head == '\0') break; switch (*head) { case 'a': *tail++ = '\a'; break; case 'b': *tail++ = '\b'; break; case 'n': *tail++ = '\n'; break; case 'r': *tail++ = '\r'; break; case 't': *tail++ = '\t'; break; case 'v': *tail++ = '\v'; break; case '\\': *tail++ = '\\'; break; default: *tail++ = *head; break; } head++; continue; } if (*head) *tail++ = *head++; } *tail = 0; } static int run_program1(struct space *space, const char *command0, char *result, size_t ressize, size_t *reslen, int log) { if (strncmp(command0, "__ctl_search", 12) == 0) { const char *res = elemid_get(space, "do_search"); if (res == NULL || strcmp(res, "1") != 0) return EXIT_FAILURE; return EXIT_SUCCESS; } if (strncmp(command0, "__ctl_count", 11) == 0) { const char *res = elemid_get(space, "do_count"); if (res == NULL || strcmp(res, "0") == 0) return EXIT_FAILURE; strlcpy(result, res, ressize); return EXIT_SUCCESS; } Perror(space, "unknown buildin command '%s'", command0); return EXIT_FAILURE; } static int parse(struct space *space, const char *filename); static char *new_root_dir(const char *filename) { char *res, *tmp; res = strdup(filename); if (res) { tmp = strrchr(res, '/'); if (tmp) *tmp = '\0'; } dbg("new_root_dir '%s' '%s'", filename, res); return res; } /* return non-zero if the file name has the extension ".conf" */ static int conf_name_filter(const struct dirent *d) { char *ext = strrchr(d->d_name, '.'); return ext && !strcmp(ext, ".conf"); } static int parse_line(struct space *space, char *line, size_t linesize) { char *linepos; char *key, *value, *attr, *temp; struct pair *pair; enum key_op op; int err = 0, count; char string[PATH_SIZE]; char result[PATH_SIZE]; linepos = line; while (*linepos != '\0') { op = KEY_OP_UNSET; err = get_key(&linepos, &key, &op, &value); if (err < 0) goto invalid; if (strncasecmp(key, "LABEL", 5) == 0) { if (op != KEY_OP_ASSIGN) { Perror(space, "invalid LABEL operation"); goto invalid; } if (space->go_to && strcmp(space->go_to, value) == 0) { free(space->go_to); space->go_to = NULL; } continue; } if (space->go_to) { dbg("skip (GOTO '%s')", space->go_to); break; /* not for us */ } if (strncasecmp(key, "CTL{", 4) == 0) { attr = get_key_attribute(space, key + 3, string, sizeof(string)); if (attr == NULL) { Perror(space, "error parsing CTL attribute"); goto invalid; } if (op == KEY_OP_ASSIGN) { strlcpy(result, value, sizeof(result)); apply_format(space, result, sizeof(result)); dbg("ctl assign: '%s' '%s'", value, attr); err = elemid_set(space, attr, result); if (space->program_result) { free(space->program_result); space->program_result = NULL; } snprintf(string, sizeof(string), "%i", err); space->program_result = strdup(string); err = 0; if (space->program_result == NULL) break; } else if (op == KEY_OP_MATCH || op == KEY_OP_NOMATCH) { if (strncmp(attr, "write", 5) == 0) { strlcpy(result, value, sizeof(result)); apply_format(space, result, sizeof(result)); dbg("ctl write: '%s' '%s'", value, attr); err = elemid_set(space, "values", result); if (err == 0 && op == KEY_OP_NOMATCH) break; if (err != 0 && op == KEY_OP_MATCH) break; } else { temp = (char *)elemid_get(space, attr); dbg("ctl match: '%s' '%s' '%s'", attr, value, temp); if (!do_match(key, op, value, temp)) break; } } else { Perror(space, "invalid CTL{} operation"); goto invalid; } continue; } if (strcasecmp(key, "RESULT") == 0) { if (op == KEY_OP_MATCH || op == KEY_OP_NOMATCH) { if (!do_match(key, op, value, space->program_result)) break; } else if (op == KEY_OP_ASSIGN) { if (space->program_result) { free(space->program_result); space->program_result = NULL; } strlcpy(string, value, sizeof(string)); apply_format(space, string, sizeof(string)); space->program_result = strdup(string); if (space->program_result == NULL) break; } else { Perror(space, "invalid RESULT operation"); goto invalid; } continue; } if (strcasecmp(key, "PROGRAM") == 0) { if (op == KEY_OP_UNSET) continue; strlcpy(string, value, sizeof(string)); apply_format(space, string, sizeof(string)); if (space->program_result) { free(space->program_result); space->program_result = NULL; } if (run_program(space, string, result, sizeof(result), NULL, space->log_run) != 0) { dbg("PROGRAM '%s' is false", string); if (op != KEY_OP_NOMATCH) break; } else { remove_trailing_chars(result, '\n'); count = replace_untrusted_chars(result); if (count) info("%i untrusted character(s) replaced", count); dbg("PROGRAM '%s' result is '%s'", string, result); space->program_result = strdup(result); if (space->program_result == NULL) break; dbg("PROGRAM returned successful"); if (op == KEY_OP_NOMATCH) break; } dbg("PROGRAM key is true"); continue; } if (strncasecmp(key, "CARDINFO{", 9) == 0) { attr = get_key_attribute(space, key + 8, string, sizeof(string)); if (attr == NULL) { Perror(space, "error parsing CARDINFO attribute"); goto invalid; } if (op == KEY_OP_MATCH || op == KEY_OP_NOMATCH) { dbg("cardinfo: '%s' '%s'", value, attr); temp = (char *)cardinfo_get(space, attr); if (!do_match(key, op, value, temp)) break; } else { Perror(space, "invalid CARDINFO{} operation"); goto invalid; } continue; } if (strncasecmp(key, "ATTR{", 5) == 0) { attr = get_key_attribute(space, key + 4, string, sizeof(string)); if (attr == NULL) { Perror(space, "error parsing ATTR attribute"); goto invalid; } if (op == KEY_OP_MATCH || op == KEY_OP_NOMATCH) { pair = value_find(space, "sysfs_device"); if (pair == NULL) break; dbg("sysfs_attr: '%s' '%s'", pair->value, attr); temp = sysfs_attr_get_value(pair->value, attr); if (!do_match(key, op, value, temp)) break; } else { Perror(space, "invalid ATTR{} operation"); goto invalid; } continue; } if (strncasecmp(key, "ENV{", 4) == 0) { attr = get_key_attribute(space, key + 3, string, sizeof(string)); if (attr == NULL) { Perror(space, "error parsing ENV attribute"); goto invalid; } if (op == KEY_OP_MATCH || op == KEY_OP_NOMATCH) { temp = getenv(attr); dbg("env: '%s' '%s'", attr, temp); if (!do_match(key, op, value, temp)) break; } else if (op == KEY_OP_ASSIGN || op == KEY_OP_ASSIGN_FINAL) { strlcpy(result, value, sizeof(result)); apply_format(space, result, sizeof(result)); dbg("env set: '%s' '%s'", attr, result); if (setenv(attr, result, op == KEY_OP_ASSIGN_FINAL)) break; } else { Perror(space, "invalid ENV{} operation"); goto invalid; } continue; } if (strcasecmp(key, "GOTO") == 0) { if (op != KEY_OP_ASSIGN) { Perror(space, "invalid GOTO operation"); goto invalid; } space->go_to = strdup(value); if (space->go_to == NULL) { err = -ENOMEM; break; } continue; } if (strcasecmp(key, "INCLUDE") == 0) { char *rootdir, *go_to; const char *filename; struct stat st; int linenum; if (op != KEY_OP_ASSIGN) { Perror(space, "invalid INCLUDE operation"); goto invalid; } if (value[0] == '/') strlcpy(string, value, sizeof(string)); else { strlcpy(string, space->rootdir, sizeof(string)); strlcat(string, "/", sizeof(string)); strlcat(string, value, sizeof(string)); } rootdir = space->rootdir; go_to = space->go_to; filename = space->filename; linenum = space->linenum; if (stat(string, &st)) { Perror(space, "invalid filename '%s'", string); continue; } if (S_ISDIR(st.st_mode)) { struct dirent **list; int i, num; num = scandir(string, &list, conf_name_filter, alphasort); if (num < 0) { Perror(space, "invalid directory '%s'", string); continue; } count = strlen(string); for (i = 0; i < num; i++) { string[count] = '\0'; strlcat(string, "/", sizeof(string)); strlcat(string, list[i]->d_name, sizeof(string)); space->go_to = NULL; space->rootdir = new_root_dir(string); free(list[i]); if (space->rootdir) { err = parse(space, string); free(space->rootdir); } else err = -ENOMEM; if (space->go_to) { Perror(space, "unterminated GOTO '%s'", space->go_to); free(space->go_to); } if (err) break; } free(list); } else { space->go_to = NULL; space->rootdir = new_root_dir(string); if (space->rootdir) { err = parse(space, string); free(space->rootdir); } else err = -ENOMEM; if (space->go_to) { Perror(space, "unterminated GOTO '%s'", space->go_to); free(space->go_to); } } space->go_to = go_to; space->rootdir = rootdir; space->filename = filename; space->linenum = linenum; if (space->quit) break; if (err) break; continue; } if (strncasecmp(key, "ACCESS", 6) == 0) { if (op == KEY_OP_MATCH || op == KEY_OP_NOMATCH) { if (value[0] == '$') { strlcpy(string, value, sizeof(string)); apply_format(space, string, sizeof(string)); if (string[0] == '/') goto __access1; } if (value[0] != '/') { strlcpy(string, space->rootdir, sizeof(string)); strlcat(string, "/", sizeof(string)); strlcat(string, value, sizeof(string)); } else { strlcpy(string, value, sizeof(string)); } apply_format(space, string, sizeof(string)); __access1: count = access(string, F_OK); dbg("access(%s) = %i (%s)", string, count, value); if (op == KEY_OP_MATCH && count != 0) break; if (op == KEY_OP_NOMATCH && count == 0) break; } else { Perror(space, "invalid ACCESS operation"); goto invalid; } continue; } if (strncasecmp(key, "PRINT", 5) == 0) { if (op != KEY_OP_ASSIGN) { Perror(space, "invalid PRINT operation"); goto invalid; } strlcpy(string, value, sizeof(string)); apply_format(space, string, sizeof(string)); fwrite(string, strlen(string), 1, stdout); continue; } if (strncasecmp(key, "ERROR", 5) == 0) { if (op != KEY_OP_ASSIGN) { Perror(space, "invalid ERROR operation"); goto invalid; } strlcpy(string, value, sizeof(string)); apply_format(space, string, sizeof(string)); fwrite(string, strlen(string), 1, stderr); continue; } if (strncasecmp(key, "EXIT", 4) == 0) { if (op != KEY_OP_ASSIGN) { Perror(space, "invalid EXIT operation"); goto invalid; } strlcpy(string, value, sizeof(string)); apply_format(space, string, sizeof(string)); if (strcmp(string, "return") == 0) return -EJUSTRETURN; space->exit_code = strtol(string, NULL, 0); space->quit = 1; break; } if (strncasecmp(key, "CONFIG{", 7) == 0) { attr = get_key_attribute(space, key + 6, string, sizeof(string)); if (attr == NULL) { Perror(space, "error parsing CONFIG attribute"); goto invalid; } strlcpy(result, value, sizeof(result)); apply_format(space, result, sizeof(result)); if (op == KEY_OP_ASSIGN) { err = value_set(space, attr, result); dbg("CONFIG{%s}='%s'", attr, result); break; } else if (op == KEY_OP_MATCH || op == KEY_OP_NOMATCH) { pair = value_find(space, attr); if (pair == NULL) break; if (!do_match(key, op, result, pair->value)) break; } else { Perror(space, "invalid CONFIG{} operation"); goto invalid; } } Perror(space, "unknown key '%s'", key); } return err; invalid: Perror(space, "invalid rule"); return -EINVAL; } static int parse(struct space *space, const char *filename) { char *buf, *bufline, *line; size_t bufsize, pos, count, linesize; unsigned int linenum, i, j, linenum_adj; int err; dbg("start of file '%s'", filename); if (file_map(filename, &buf, &bufsize) != 0) { err = errno; error("Unable to open file '%s': %s", filename, strerror(err)); return -err; } err = 0; pos = 0; linenum = 0; linesize = 128; line = malloc(linesize); if (line == NULL) return -ENOMEM; space->filename = filename; while (!err && pos < bufsize && !space->quit) { count = line_width(buf, bufsize, pos); bufline = buf + pos; pos += count + 1; linenum++; /* skip whitespaces */ while (count > 0 && isspace(bufline[0])) { bufline++; count--; } if (count == 0) continue; /* comment check */ if (bufline[0] == '#') continue; if (count > linesize - 1) { free(line); linesize = (count + 127 + 1) & ~127; if (linesize > 2048) { error("file %s, line %i too long", filename, linenum); err = -EINVAL; break; } line = malloc(linesize); if (line == NULL) { err = -EINVAL; break; } } /* skip backslash and newline from multiline rules */ linenum_adj = 0; for (i = j = 0; i < count; i++) { if (bufline[i] == '\\' && bufline[i+1] == '\n') { linenum_adj++; continue; } line[j++] = bufline[i]; } line[j] = '\0'; dbg("read (%i) '%s'", linenum, line); space->linenum = linenum; err = parse_line(space, line, linesize); if (err == -EJUSTRETURN) { err = 0; break; } linenum += linenum_adj; } free(line); space->filename = NULL; space->linenum = -1; file_unmap(buf, bufsize); dbg("end of file '%s'", filename); return err ? err : -abs(space->exit_code); } int init(const char *filename, const char *cardname) { struct space *space; int err = 0, card, first; sysfs_init(); if (!cardname) { first = 1; card = -1; while (1) { if (snd_card_next(&card) < 0) break; if (card < 0) { if (first) { error("No soundcards found..."); return -ENODEV; } break; } first = 0; err = init_space(&space, card); if (err == 0) { space->rootdir = new_root_dir(filename); if (space->rootdir != NULL) err = parse(space, filename); free_space(space); } if (err < 0) break; } } else { card = snd_card_get_index(cardname); if (card < 0) { error("Cannot find soundcard '%s'...", cardname); goto error; } memset(&space, 0, sizeof(space)); err = init_space(&space, card); if (err == 0) { space->rootdir = new_root_dir(filename); if (space->rootdir != NULL) err = parse(space, filename); free_space(space); } } error: sysfs_cleanup(); return err; }
ccrome/alsa-utils-dev
alsactl/init_parse.c
C
gpl-2.0
47,335
from __future__ import absolute_import class DummyException(Exception): pass def import_global( name, modules=None, exceptions=DummyException, locals_=None, globals_=None, level=-1): '''Import the requested items into the global scope WARNING! this method _will_ overwrite your global scope If you have a variable named "path" and you call import_global('sys') it will be overwritten with sys.path Args: name (str): the name of the module to import, e.g. sys modules (str): the modules to import, use None for everything exception (Exception): the exception to catch, e.g. ImportError `locals_`: the `locals()` method (in case you need a different scope) `globals_`: the `globals()` method (in case you need a different scope) level (int): the level to import from, this can be used for relative imports ''' frame = None try: # If locals_ or globals_ are not given, autodetect them by inspecting # the current stack if locals_ is None or globals_ is None: import inspect frame = inspect.stack()[1][0] if locals_ is None: locals_ = frame.f_locals if globals_ is None: globals_ = frame.f_globals try: name = name.split('.') # Relative imports are supported (from .spam import eggs) if not name[0]: name = name[1:] level = 1 # raise IOError((name, level)) module = __import__( name=name[0] or '.', globals=globals_, locals=locals_, fromlist=name[1:], level=max(level, 0), ) # Make sure we get the right part of a dotted import (i.e. # spam.eggs should return eggs, not spam) try: for attr in name[1:]: module = getattr(module, attr) except AttributeError: raise ImportError('No module named ' + '.'.join(name)) # If no list of modules is given, autodetect from either __all__ # or a dir() of the module if not modules: modules = getattr(module, '__all__', dir(module)) else: modules = set(modules).intersection(dir(module)) # Add all items in modules to the global scope for k in set(dir(module)).intersection(modules): if k and k[0] != '_': globals_[k] = getattr(module, k) except exceptions as e: return e finally: # Clean up, just to be sure del name, modules, exceptions, locals_, globals_, frame
samowitsch/bCNC
bCNC/lib/python_utils/import_.py
Python
gpl-2.0
2,797
#include <linux/config.h> #include <linux/kernel.h> #include <linux/interrupt.h> #include <linux/list.h> #include <linux/string.h> #include "../gpio/gpio.h" #include "base_gpio_8972b.h" #ifdef CONFIG_RTK_VOIP_GPIO_IPP_8972B_V00 #define IPPHONE_PIN_HOOK GPIO_ID(GPIO_PORT_E,6) //input #define INTERRUPT_HOOK #else #define IPPHONE_PIN_HOOK GPIO_ID(GPIO_PORT_B,4) //input //#define INTERRUPT_HOOK #endif /************************* IP phone hook detection ****************************************/ void ipphone_hook_interrupt( int enable ) { #if defined( IPPHONE_PIN_HOOK ) && defined( INTERRUPT_HOOK ) const enum GPIO_INTERRUPT_TYPE int_type = ( enable ? GPIO_INT_BOTH_EDGE : GPIO_INT_DISABLE ); _rtl8972B_initGpioPin( IPPHONE_PIN_HOOK, GPIO_CONT_GPIO, GPIO_DIR_IN, int_type ); #endif } void init_ipphone_hook_detect( void ) { #ifdef IPPHONE_PIN_HOOK #ifdef INTERRUPT_HOOK ipphone_hook_interrupt( 1 ); #else _rtl8972B_initGpioPin( IPPHONE_PIN_HOOK, GPIO_CONT_GPIO, GPIO_DIR_IN, GPIO_INT_DISABLE ); #endif #endif } //return value 0->on-hook, 1->off-hook unsigned char iphone_hook_detect( void ) { uint32 data; #ifdef CONFIG_RTK_VOIP_GPIO_IPP_8972B_V00 #ifdef IPPHONE_PIN_HOOK _rtl8972B_getGpioDataBit( IPPHONE_PIN_HOOK, &data ); #else extern unsigned char ALC5621_GetGpioStatus( void ); data = ( ALC5621_GetGpioStatus() ? 1 : 0 ); #endif #else _rtl8972B_getGpioDataBit( IPPHONE_PIN_HOOK, &data ); #endif //printk( "HOOK:%d\n", data ); #if 0 // debug use only return ( unsigned char )data; #else return ( unsigned char )( !data ); #endif }
ysleu/RTL8685
uClinux-dist/linux-2.6.x/rtk_voip-single_cpu/voip_drivers/iphone/base_gpio_8972b.c
C
gpl-2.0
1,576
<?php /** * Copyright © 2015 Magento. All rights reserved. * See COPYING.txt for license details. */ /** * Customer Widget Form Boolean Element Block * * @author Magento Core Team <core@magentocommerce.com> */ namespace Magento\Customer\Block\Adminhtml\Form\Element; class Boolean extends \Magento\Framework\Data\Form\Element\Select { /** * Prepare default SELECT values * @return void */ protected function _construct() { parent::_construct(); $this->setValues([['label' => __('No'), 'value' => '0'], ['label' => __('Yes'), 'value' => 1]]); } }
FPLD/project0
vendor/magento/module-customer/Block/Adminhtml/Form/Element/Boolean.php
PHP
gpl-2.0
608
<?php /** * Post functions and post utility function. * * @package WordPress * @subpackage Post * @since 1.5.0 */ // // Post Type Registration // /** * Creates the initial post types when 'init' action is fired. * * @since 2.9.0 */ function create_initial_post_types() { register_post_type( 'post', array( 'labels' => array( 'name_admin_bar' => _x( 'Post', 'add new on admin bar' ), ), 'public' => true, '_builtin' => true, /* internal use only. don't use this when registering your own post type. */ '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */ 'capability_type' => 'post', 'map_meta_cap' => true, 'hierarchical' => false, 'rewrite' => false, 'query_var' => false, 'delete_with_user' => true, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ), ) ); register_post_type( 'page', array( 'labels' => array( 'name_admin_bar' => _x( 'Page', 'add new on admin bar' ), ), 'public' => true, 'publicly_queryable' => false, '_builtin' => true, /* internal use only. don't use this when registering your own post type. */ '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */ 'capability_type' => 'page', 'map_meta_cap' => true, 'hierarchical' => true, 'rewrite' => false, 'query_var' => false, 'delete_with_user' => true, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes', 'custom-fields', 'comments', 'revisions' ), ) ); register_post_type( 'attachment', array( 'labels' => array( 'name' => _x('Media', 'post type general name'), 'name_admin_bar' => _x( 'Media', 'add new from admin bar' ), 'add_new' => _x( 'Add New', 'add new media' ), 'edit_item' => __( 'Edit Media' ), 'view_item' => __( 'View Attachment Page' ), ), 'public' => true, 'show_ui' => true, '_builtin' => true, /* internal use only. don't use this when registering your own post type. */ '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */ 'capability_type' => 'post', 'capabilities' => array( 'create_posts' => 'upload_files', ), 'map_meta_cap' => true, 'hierarchical' => false, 'rewrite' => false, 'query_var' => false, 'show_in_nav_menus' => false, 'delete_with_user' => true, 'supports' => array( 'title', 'author', 'comments' ), ) ); register_post_type( 'revision', array( 'labels' => array( 'name' => __( 'Revisions' ), 'singular_name' => __( 'Revision' ), ), 'public' => false, '_builtin' => true, /* internal use only. don't use this when registering your own post type. */ '_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */ 'capability_type' => 'post', 'map_meta_cap' => true, 'hierarchical' => false, 'rewrite' => false, 'query_var' => false, 'can_export' => false, 'delete_with_user' => true, 'supports' => array( 'author' ), ) ); register_post_type( 'nav_menu_item', array( 'labels' => array( 'name' => __( 'Navigation Menu Items' ), 'singular_name' => __( 'Navigation Menu Item' ), ), 'public' => false, '_builtin' => true, /* internal use only. don't use this when registering your own post type. */ 'hierarchical' => false, 'rewrite' => false, 'delete_with_user' => false, 'query_var' => false, ) ); register_post_status( 'publish', array( 'label' => _x( 'Published', 'post' ), 'public' => true, '_builtin' => true, /* internal use only. */ 'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ), ) ); register_post_status( 'future', array( 'label' => _x( 'Scheduled', 'post' ), 'protected' => true, '_builtin' => true, /* internal use only. */ 'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ), ) ); register_post_status( 'draft', array( 'label' => _x( 'Draft', 'post' ), 'protected' => true, '_builtin' => true, /* internal use only. */ 'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ), ) ); register_post_status( 'pending', array( 'label' => _x( 'Pending', 'post' ), 'protected' => true, '_builtin' => true, /* internal use only. */ 'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ), ) ); register_post_status( 'private', array( 'label' => _x( 'Private', 'post' ), 'private' => true, '_builtin' => true, /* internal use only. */ 'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ), ) ); register_post_status( 'trash', array( 'label' => _x( 'Trash', 'post' ), 'internal' => true, '_builtin' => true, /* internal use only. */ 'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ), 'show_in_admin_status_list' => true, ) ); register_post_status( 'auto-draft', array( 'label' => 'auto-draft', 'internal' => true, '_builtin' => true, /* internal use only. */ ) ); register_post_status( 'inherit', array( 'label' => 'inherit', 'internal' => true, '_builtin' => true, /* internal use only. */ 'exclude_from_search' => false, ) ); } add_action( 'init', 'create_initial_post_types', 0 ); // highest priority /** * Retrieve attached file path based on attachment ID. * * You can optionally send it through the 'get_attached_file' filter, but by * default it will just return the file path unfiltered. * * The function works by getting the single post meta name, named * '_wp_attached_file' and returning it. This is a convenience function to * prevent looking up the meta name and provide a mechanism for sending the * attached filename through a filter. * * @since 2.0.0 * @uses apply_filters() Calls 'get_attached_file' on file path and attachment ID. * * @param int $attachment_id Attachment ID. * @param bool $unfiltered Whether to apply filters. * @return string|bool The file path to the attached file, or false if the attachment does not exist. */ function get_attached_file( $attachment_id, $unfiltered = false ) { $file = get_post_meta( $attachment_id, '_wp_attached_file', true ); // If the file is relative, prepend upload dir if ( $file && 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) ) $file = $uploads['basedir'] . "/$file"; if ( $unfiltered ) return $file; return apply_filters( 'get_attached_file', $file, $attachment_id ); } /** * Update attachment file path based on attachment ID. * * Used to update the file path of the attachment, which uses post meta name * '_wp_attached_file' to store the path of the attachment. * * @since 2.1.0 * @uses apply_filters() Calls 'update_attached_file' on file path and attachment ID. * * @param int $attachment_id Attachment ID * @param string $file File path for the attachment * @return bool True on success, false on failure. */ function update_attached_file( $attachment_id, $file ) { if ( !get_post( $attachment_id ) ) return false; $file = apply_filters( 'update_attached_file', $file, $attachment_id ); if ( $file = _wp_relative_upload_path( $file ) ) return update_post_meta( $attachment_id, '_wp_attached_file', $file ); else return delete_post_meta( $attachment_id, '_wp_attached_file' ); } /** * Return relative path to an uploaded file. * * The path is relative to the current upload dir. * * @since 2.9.0 * @uses apply_filters() Calls '_wp_relative_upload_path' on file path. * * @param string $path Full path to the file * @return string relative path on success, unchanged path on failure. */ function _wp_relative_upload_path( $path ) { $new_path = $path; $uploads = wp_upload_dir(); if ( 0 === strpos( $new_path, $uploads['basedir'] ) ) { $new_path = str_replace( $uploads['basedir'], '', $new_path ); $new_path = ltrim( $new_path, '/' ); } return apply_filters( '_wp_relative_upload_path', $new_path, $path ); } /** * Retrieve all children of the post parent ID. * * Normally, without any enhancements, the children would apply to pages. In the * context of the inner workings of WordPress, pages, posts, and attachments * share the same table, so therefore the functionality could apply to any one * of them. It is then noted that while this function does not work on posts, it * does not mean that it won't work on posts. It is recommended that you know * what context you wish to retrieve the children of. * * Attachments may also be made the child of a post, so if that is an accurate * statement (which needs to be verified), it would then be possible to get * all of the attachments for a post. Attachments have since changed since * version 2.5, so this is most likely unaccurate, but serves generally as an * example of what is possible. * * The arguments listed as defaults are for this function and also of the * {@link get_posts()} function. The arguments are combined with the * get_children defaults and are then passed to the {@link get_posts()} * function, which accepts additional arguments. You can replace the defaults in * this function, listed below and the additional arguments listed in the * {@link get_posts()} function. * * The 'post_parent' is the most important argument and important attention * needs to be paid to the $args parameter. If you pass either an object or an * integer (number), then just the 'post_parent' is grabbed and everything else * is lost. If you don't specify any arguments, then it is assumed that you are * in The Loop and the post parent will be grabbed for from the current post. * * The 'post_parent' argument is the ID to get the children. The 'numberposts' * is the amount of posts to retrieve that has a default of '-1', which is * used to get all of the posts. Giving a number higher than 0 will only * retrieve that amount of posts. * * The 'post_type' and 'post_status' arguments can be used to choose what * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress * post types are 'post', 'pages', and 'attachments'. The 'post_status' * argument will accept any post status within the write administration panels. * * @see get_posts() Has additional arguments that can be replaced. * @internal Claims made in the long description might be inaccurate. * * @since 2.0.0 * * @param mixed $args Optional. User defined arguments for replacing the defaults. * @param string $output Optional. Constant for return type, either OBJECT (default), ARRAY_A, ARRAY_N. * @return array|bool False on failure and the type will be determined by $output parameter. */ function get_children($args = '', $output = OBJECT) { $kids = array(); if ( empty( $args ) ) { if ( isset( $GLOBALS['post'] ) ) { $args = array('post_parent' => (int) $GLOBALS['post']->post_parent ); } else { return $kids; } } elseif ( is_object( $args ) ) { $args = array('post_parent' => (int) $args->post_parent ); } elseif ( is_numeric( $args ) ) { $args = array('post_parent' => (int) $args); } $defaults = array( 'numberposts' => -1, 'post_type' => 'any', 'post_status' => 'any', 'post_parent' => 0, ); $r = wp_parse_args( $args, $defaults ); $children = get_posts( $r ); if ( !$children ) return $kids; update_post_cache($children); foreach ( $children as $key => $child ) $kids[$child->ID] = $children[$key]; if ( $output == OBJECT ) { return $kids; } elseif ( $output == ARRAY_A ) { foreach ( (array) $kids as $kid ) $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]); return $weeuns; } elseif ( $output == ARRAY_N ) { foreach ( (array) $kids as $kid ) $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID])); return $babes; } else { return $kids; } } /** * Get extended entry info (<!--more-->). * * There should not be any space after the second dash and before the word * 'more'. There can be text or space(s) after the word 'more', but won't be * referenced. * * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before * the <code><!--more--></code>. The 'extended' key has the content after the * <code><!--more--></code> comment. The 'more_text' key has the custom "Read More" text. * * @since 1.0.0 * * @param string $post Post content. * @return array Post before ('main'), after ('extended'), and custom readmore ('more_text'). */ function get_extended($post) { //Match the new style more links if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) { list($main, $extended) = explode($matches[0], $post, 2); $more_text = $matches[1]; } else { $main = $post; $extended = ''; $more_text = ''; } // ` leading and trailing whitespace $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main); $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended); $more_text = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $more_text); return array( 'main' => $main, 'extended' => $extended, 'more_text' => $more_text ); } /** * Retrieves post data given a post ID or post object. * * See {@link sanitize_post()} for optional $filter values. Also, the parameter * $post, must be given as a variable, since it is passed by reference. * * @since 1.5.1 * @uses $wpdb * @link http://codex.wordpress.org/Function_Reference/get_post * * @param int|object $post Post ID or post object. Optional, default is the current post from the loop. * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N. * @param string $filter Optional, default is raw. * @return WP_Post|null WP_Post on success or null on failure */ function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) { if ( empty( $post ) && isset( $GLOBALS['post'] ) ) $post = $GLOBALS['post']; if ( is_a( $post, 'WP_Post' ) ) { $_post = $post; } elseif ( is_object( $post ) ) { if ( empty( $post->filter ) ) { $_post = sanitize_post( $post, 'raw' ); $_post = new WP_Post( $_post ); } elseif ( 'raw' == $post->filter ) { $_post = new WP_Post( $post ); } else { $_post = WP_Post::get_instance( $post->ID ); } } else { $_post = WP_Post::get_instance( $post ); } if ( ! $_post ) return null; $_post = $_post->filter( $filter ); if ( $output == ARRAY_A ) return $_post->to_array(); elseif ( $output == ARRAY_N ) return array_values( $_post->to_array() ); return $_post; } /** * WordPress Post class. * * @since 3.5.0 * */ final class WP_Post { /** * * @var int */ public $ID; /** * * @var int */ public $post_author = 0; /** * * @var string */ public $post_date = '0000-00-00 00:00:00'; /** * * @var string */ public $post_date_gmt = '0000-00-00 00:00:00'; /** * * @var string */ public $post_content = ''; /** * * @var string */ public $post_title = ''; /** * * @var string */ public $post_excerpt = ''; /** * * @var string */ public $post_status = 'publish'; /** * * @var string */ public $comment_status = 'open'; /** * * @var string */ public $ping_status = 'open'; /** * * @var string */ public $post_password = ''; /** * * @var string */ public $post_name = ''; /** * * @var string */ public $to_ping = ''; /** * * @var string */ public $pinged = ''; /** * * @var string */ public $post_modified = '0000-00-00 00:00:00'; /** * * @var string */ public $post_modified_gmt = '0000-00-00 00:00:00'; /** * * @var string */ public $post_content_filtered = ''; /** * * @var int */ public $post_parent = 0; /** * * @var string */ public $guid = ''; /** * * @var int */ public $menu_order = 0; /** * * @var string */ public $post_type = 'post'; /** * * @var string */ public $post_mime_type = ''; /** * * @var int */ public $comment_count = 0; /** * * @var string */ public $filter; /** * Private variable used by post formats to cache parsed content. * * @since 3.6.0 * * @var array * @access private */ public $format_content; public static function get_instance( $post_id ) { global $wpdb; $post_id = (int) $post_id; if ( ! $post_id ) return false; $_post = wp_cache_get( $post_id, 'posts' ); if ( ! $_post ) { $_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post_id ) ); if ( ! $_post ) return false; $_post = sanitize_post( $_post, 'raw' ); wp_cache_add( $_post->ID, $_post, 'posts' ); } elseif ( empty( $_post->filter ) ) { $_post = sanitize_post( $_post, 'raw' ); } return new WP_Post( $_post ); } public function __construct( $post ) { foreach ( get_object_vars( $post ) as $key => $value ) $this->$key = $value; } public function __isset( $key ) { if ( 'ancestors' == $key ) return true; if ( 'page_template' == $key ) return ( 'page' == $this->post_type ); if ( 'post_category' == $key ) return true; if ( 'tags_input' == $key ) return true; return metadata_exists( 'post', $this->ID, $key ); } public function __get( $key ) { if ( 'page_template' == $key && $this->__isset( $key ) ) { return get_post_meta( $this->ID, '_wp_page_template', true ); } if ( 'post_category' == $key ) { if ( is_object_in_taxonomy( $this->post_type, 'category' ) ) $terms = get_the_terms( $this, 'category' ); if ( empty( $terms ) ) return array(); return wp_list_pluck( $terms, 'term_id' ); } if ( 'tags_input' == $key ) { if ( is_object_in_taxonomy( $this->post_type, 'post_tag' ) ) $terms = get_the_terms( $this, 'post_tag' ); if ( empty( $terms ) ) return array(); return wp_list_pluck( $terms, 'name' ); } // Rest of the values need filtering if ( 'ancestors' == $key ) $value = get_post_ancestors( $this ); else $value = get_post_meta( $this->ID, $key, true ); if ( $this->filter ) $value = sanitize_post_field( $key, $value, $this->ID, $this->filter ); return $value; } public function filter( $filter ) { if ( $this->filter == $filter ) return $this; if ( $filter == 'raw' ) return self::get_instance( $this->ID ); return sanitize_post( $this, $filter ); } public function to_array() { $post = get_object_vars( $this ); foreach ( array( 'ancestors', 'page_template', 'post_category', 'tags_input' ) as $key ) { if ( $this->__isset( $key ) ) $post[ $key ] = $this->__get( $key ); } return $post; } } /** * Retrieve ancestors of a post. * * @since 2.5.0 * * @param int|object $post Post ID or post object * @return array Ancestor IDs or empty array if none are found. */ function get_post_ancestors( $post ) { $post = get_post( $post ); if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID ) return array(); $ancestors = array(); $id = $ancestors[] = $post->post_parent; while ( $ancestor = get_post( $id ) ) { // Loop detection: If the ancestor has been seen before, break. if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors ) ) break; $id = $ancestors[] = $ancestor->post_parent; } return $ancestors; } /** * Retrieve data from a post field based on Post ID. * * Examples of the post field will be, 'post_type', 'post_status', 'post_content', * etc and based off of the post object property or key names. * * The context values are based off of the taxonomy filter functions and * supported values are found within those functions. * * @since 2.3.0 * @uses sanitize_post_field() See for possible $context values. * * @param string $field Post field name. * @param int|object $post Post ID or post object. * @param string $context Optional. How to filter the field. Default is 'display'. * @return string The value of the post field on success, empty string on failure. */ function get_post_field( $field, $post, $context = 'display' ) { $post = get_post( $post ); if ( !$post ) return ''; if ( !isset($post->$field) ) return ''; return sanitize_post_field($field, $post->$field, $post->ID, $context); } /** * Retrieve the mime type of an attachment based on the ID. * * This function can be used with any post type, but it makes more sense with * attachments. * * @since 2.0.0 * * @param int $ID Optional. Post ID. Default is the current post from the loop. * @return string|bool The mime type on success, false on failure. */ function get_post_mime_type($ID = '') { $post = get_post($ID); if ( is_object($post) ) return $post->post_mime_type; return false; } /** * Retrieve the post status based on the Post ID. * * If the post ID is of an attachment, then the parent post status will be given * instead. * * @since 2.0.0 * * @param int $ID Optional. Post ID. Default is the current post from the loop. * @return string|bool Post status on success, false on failure. */ function get_post_status($ID = '') { $post = get_post($ID); if ( !is_object($post) ) return false; if ( 'attachment' == $post->post_type ) { if ( 'private' == $post->post_status ) return 'private'; // Unattached attachments are assumed to be published if ( ( 'inherit' == $post->post_status ) && ( 0 == $post->post_parent) ) return 'publish'; // Inherit status from the parent if ( $post->post_parent && ( $post->ID != $post->post_parent ) ) return get_post_status($post->post_parent); } return $post->post_status; } /** * Retrieve all of the WordPress supported post statuses. * * Posts have a limited set of valid status values, this provides the * post_status values and descriptions. * * @since 2.5.0 * * @return array List of post statuses. */ function get_post_statuses() { $status = array( 'draft' => __('Draft'), 'pending' => __('Pending Review'), 'private' => __('Private'), 'publish' => __('Published') ); return $status; } /** * Retrieve all of the WordPress support page statuses. * * Pages have a limited set of valid status values, this provides the * post_status values and descriptions. * * @since 2.5.0 * * @return array List of page statuses. */ function get_page_statuses() { $status = array( 'draft' => __('Draft'), 'private' => __('Private'), 'publish' => __('Published') ); return $status; } /** * Register a post status. Do not use before init. * * A simple function for creating or modifying a post status based on the * parameters given. The function will accept an array (second optional * parameter), along with a string for the post status name. * * * Optional $args contents: * * label - A descriptive name for the post status marked for translation. Defaults to $post_status. * public - Whether posts of this status should be shown in the front end of the site. Defaults to true. * exclude_from_search - Whether to exclude posts with this post status from search results. Defaults to false. * show_in_admin_all_list - Whether to include posts in the edit listing for their post type * show_in_admin_status_list - Show in the list of statuses with post counts at the top of the edit * listings, e.g. All (12) | Published (9) | My Custom Status (2) ... * * Arguments prefixed with an _underscore shouldn't be used by plugins and themes. * * @package WordPress * @subpackage Post * @since 3.0.0 * @uses $wp_post_statuses Inserts new post status object into the list * * @param string $post_status Name of the post status. * @param array|string $args See above description. */ function register_post_status($post_status, $args = array()) { global $wp_post_statuses; if (!is_array($wp_post_statuses)) $wp_post_statuses = array(); // Args prefixed with an underscore are reserved for internal use. $defaults = array( 'label' => false, 'label_count' => false, 'exclude_from_search' => null, '_builtin' => false, 'public' => null, 'internal' => null, 'protected' => null, 'private' => null, 'publicly_queryable' => null, 'show_in_admin_status_list' => null, 'show_in_admin_all_list' => null, ); $args = wp_parse_args($args, $defaults); $args = (object) $args; $post_status = sanitize_key($post_status); $args->name = $post_status; if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private ) $args->internal = true; if ( null === $args->public ) $args->public = false; if ( null === $args->private ) $args->private = false; if ( null === $args->protected ) $args->protected = false; if ( null === $args->internal ) $args->internal = false; if ( null === $args->publicly_queryable ) $args->publicly_queryable = $args->public; if ( null === $args->exclude_from_search ) $args->exclude_from_search = $args->internal; if ( null === $args->show_in_admin_all_list ) $args->show_in_admin_all_list = !$args->internal; if ( null === $args->show_in_admin_status_list ) $args->show_in_admin_status_list = !$args->internal; if ( false === $args->label ) $args->label = $post_status; if ( false === $args->label_count ) $args->label_count = array( $args->label, $args->label ); $wp_post_statuses[$post_status] = $args; return $args; } /** * Retrieve a post status object by name * * @package WordPress * @subpackage Post * @since 3.0.0 * @uses $wp_post_statuses * @see register_post_status * @see get_post_statuses * * @param string $post_status The name of a registered post status * @return object A post status object */ function get_post_status_object( $post_status ) { global $wp_post_statuses; if ( empty($wp_post_statuses[$post_status]) ) return null; return $wp_post_statuses[$post_status]; } /** * Get a list of all registered post status objects. * * @package WordPress * @subpackage Post * @since 3.0.0 * @uses $wp_post_statuses * @see register_post_status * @see get_post_status_object * * @param array|string $args An array of key => value arguments to match against the post status objects. * @param string $output The type of output to return, either post status 'names' or 'objects'. 'names' is the default. * @param string $operator The logical operation to perform. 'or' means only one element * from the array needs to match; 'and' means all elements must match. The default is 'and'. * @return array A list of post status names or objects */ function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) { global $wp_post_statuses; $field = ('names' == $output) ? 'name' : false; return wp_filter_object_list($wp_post_statuses, $args, $operator, $field); } /** * Whether the post type is hierarchical. * * A false return value might also mean that the post type does not exist. * * @since 3.0.0 * @see get_post_type_object * * @param string $post_type Post type name * @return bool Whether post type is hierarchical. */ function is_post_type_hierarchical( $post_type ) { if ( ! post_type_exists( $post_type ) ) return false; $post_type = get_post_type_object( $post_type ); return $post_type->hierarchical; } /** * Checks if a post type is registered. * * @since 3.0.0 * @uses get_post_type_object() * * @param string $post_type Post type name * @return bool Whether post type is registered. */ function post_type_exists( $post_type ) { return (bool) get_post_type_object( $post_type ); } /** * Retrieve the post type of the current post or of a given post. * * @since 2.1.0 * * @param int|object $post Optional. Post ID or post object. Default is the current post from the loop. * @return string|bool Post type on success, false on failure. */ function get_post_type( $post = null ) { if ( $post = get_post( $post ) ) return $post->post_type; return false; } /** * Retrieve a post type object by name * * @package WordPress * @subpackage Post * @since 3.0.0 * @uses $wp_post_types * @see register_post_type * @see get_post_types * * @param string $post_type The name of a registered post type * @return object A post type object */ function get_post_type_object( $post_type ) { global $wp_post_types; if ( empty($wp_post_types[$post_type]) ) return null; return $wp_post_types[$post_type]; } /** * Get a list of all registered post type objects. * * @package WordPress * @subpackage Post * @since 2.9.0 * @uses $wp_post_types * @see register_post_type * * @param array|string $args An array of key => value arguments to match against the post type objects. * @param string $output The type of output to return, either post type 'names' or 'objects'. 'names' is the default. * @param string $operator The logical operation to perform. 'or' means only one element * from the array needs to match; 'and' means all elements must match. The default is 'and'. * @return array A list of post type names or objects */ function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) { global $wp_post_types; $field = ('names' == $output) ? 'name' : false; return wp_filter_object_list($wp_post_types, $args, $operator, $field); } /** * Register a post type. Do not use before init. * * A function for creating or modifying a post type based on the * parameters given. The function will accept an array (second optional * parameter), along with a string for the post type name. * * Optional $args contents: * * - label - Name of the post type shown in the menu. Usually plural. If not set, labels['name'] will be used. * - labels - An array of labels for this post type. * * If not set, post labels are inherited for non-hierarchical types and page labels for hierarchical ones. * * You can see accepted values in {@link get_post_type_labels()}. * - description - A short descriptive summary of what the post type is. Defaults to blank. * - public - Whether a post type is intended for use publicly either via the admin interface or by front-end users. * * Defaults to false. * * While the default settings of exclude_from_search, publicly_queryable, show_ui, and show_in_nav_menus are * inherited from public, each does not rely on this relationship and controls a very specific intention. * - exclude_from_search - Whether to exclude posts with this post type from front end search results. * * If not set, the opposite of public's current value is used. * - publicly_queryable - Whether queries can be performed on the front end for the post type as part of parse_request(). * * ?post_type={post_type_key} * * ?{post_type_key}={single_post_slug} * * ?{post_type_query_var}={single_post_slug} * * If not set, the default is inherited from public. * - show_ui - Whether to generate a default UI for managing this post type in the admin. * * If not set, the default is inherited from public. * - show_in_nav_menus - Makes this post type available for selection in navigation menus. * * If not set, the default is inherited from public. * - show_in_menu - Where to show the post type in the admin menu. * * If true, the post type is shown in its own top level menu. * * If false, no menu is shown * * If a string of an existing top level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post type will * be placed as a sub menu of that. * * show_ui must be true. * * If not set, the default is inherited from show_ui * - show_in_admin_bar - Makes this post type available via the admin bar. * * If not set, the default is inherited from show_in_menu * - menu_position - The position in the menu order the post type should appear. * * show_in_menu must be true * * Defaults to null, which places it at the bottom of its area. * - menu_icon - The url to the icon to be used for this menu. Defaults to use the posts icon. * - capability_type - The string to use to build the read, edit, and delete capabilities. Defaults to 'post'. * * May be passed as an array to allow for alternative plurals when using this argument as a base to construct the * capabilities, e.g. array('story', 'stories'). * - capabilities - Array of capabilities for this post type. * * By default the capability_type is used as a base to construct capabilities. * * You can see accepted values in {@link get_post_type_capabilities()}. * - map_meta_cap - Whether to use the internal default meta capability handling. Defaults to false. * - hierarchical - Whether the post type is hierarchical (e.g. page). Defaults to false. * - supports - An alias for calling add_post_type_support() directly. Defaults to title and editor. * * See {@link add_post_type_support()} for documentation. * - register_meta_box_cb - Provide a callback function that will be called when setting up the * meta boxes for the edit form. Do remove_meta_box() and add_meta_box() calls in the callback. * - taxonomies - An array of taxonomy identifiers that will be registered for the post type. * * Default is no taxonomies. * * Taxonomies can be registered later with register_taxonomy() or register_taxonomy_for_object_type(). * - has_archive - True to enable post type archives. Default is false. * * Will generate the proper rewrite rules if rewrite is enabled. * - rewrite - Triggers the handling of rewrites for this post type. Defaults to true, using $post_type as slug. * * To prevent rewrite, set to false. * * To specify rewrite rules, an array can be passed with any of these keys * * 'slug' => string Customize the permastruct slug. Defaults to $post_type key * * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true. * * 'feeds' => bool Should a feed permastruct be built for this post type. Inherits default from has_archive. * * 'pages' => bool Should the permastruct provide for pagination. Defaults to true. * * 'ep_mask' => const Assign an endpoint mask. * * If not specified and permalink_epmask is set, inherits from permalink_epmask. * * If not specified and permalink_epmask is not set, defaults to EP_PERMALINK * - query_var - Sets the query_var key for this post type. Defaults to $post_type key * * If false, a post type cannot be loaded at ?{query_var}={post_slug} * * If specified as a string, the query ?{query_var_string}={post_slug} will be valid. * - can_export - Allows this post type to be exported. Defaults to true. * - delete_with_user - Whether to delete posts of this type when deleting a user. * * If true, posts of this type belonging to the user will be moved to trash when then user is deleted. * * If false, posts of this type belonging to the user will *not* be trashed or deleted. * * If not set (the default), posts are trashed if post_type_supports('author'). Otherwise posts are not trashed or deleted. * - _builtin - true if this post type is a native or "built-in" post_type. THIS IS FOR INTERNAL USE ONLY! * - _edit_link - URL segement to use for edit link of this post type. THIS IS FOR INTERNAL USE ONLY! * * @since 2.9.0 * @uses $wp_post_types Inserts new post type object into the list * * @param string $post_type Post type key, must not exceed 20 characters * @param array|string $args See optional args description above. * @return object|WP_Error the registered post type object, or an error object */ function register_post_type( $post_type, $args = array() ) { global $wp_post_types, $wp_rewrite, $wp; if ( !is_array($wp_post_types) ) $wp_post_types = array(); // Args prefixed with an underscore are reserved for internal use. $defaults = array( 'labels' => array(), 'description' => '', 'publicly_queryable' => null, 'exclude_from_search' => null, 'capability_type' => 'post', 'capabilities' => array(), 'map_meta_cap' => null, '_builtin' => false, '_edit_link' => 'post.php?post=%d', 'hierarchical' => false, 'public' => false, 'rewrite' => true, 'has_archive' => false, 'query_var' => true, 'supports' => array(), 'register_meta_box_cb' => null, 'taxonomies' => array(), 'show_ui' => null, 'menu_position' => null, 'menu_icon' => null, 'can_export' => true, 'show_in_nav_menus' => null, 'show_in_menu' => null, 'show_in_admin_bar' => null, 'delete_with_user' => null, ); $args = wp_parse_args($args, $defaults); $args = (object) $args; $post_type = sanitize_key($post_type); $args->name = $post_type; if ( strlen( $post_type ) > 20 ) return new WP_Error( 'post_type_too_long', __( 'Post types cannot exceed 20 characters in length' ) ); // If not set, default to the setting for public. if ( null === $args->publicly_queryable ) $args->publicly_queryable = $args->public; // If not set, default to the setting for public. if ( null === $args->show_ui ) $args->show_ui = $args->public; // If not set, default to the setting for show_ui. if ( null === $args->show_in_menu || ! $args->show_ui ) $args->show_in_menu = $args->show_ui; // If not set, default to the whether the full UI is shown. if ( null === $args->show_in_admin_bar ) $args->show_in_admin_bar = true === $args->show_in_menu; // Whether to show this type in nav-menus.php. Defaults to the setting for public. if ( null === $args->show_in_nav_menus ) $args->show_in_nav_menus = $args->public; // If not set, default to true if not public, false if public. if ( null === $args->exclude_from_search ) $args->exclude_from_search = !$args->public; // Back compat with quirky handling in version 3.0. #14122 if ( empty( $args->capabilities ) && null === $args->map_meta_cap && in_array( $args->capability_type, array( 'post', 'page' ) ) ) $args->map_meta_cap = true; if ( null === $args->map_meta_cap ) $args->map_meta_cap = false; $args->cap = get_post_type_capabilities( $args ); unset($args->capabilities); if ( is_array( $args->capability_type ) ) $args->capability_type = $args->capability_type[0]; if ( ! empty($args->supports) ) { add_post_type_support($post_type, $args->supports); unset($args->supports); } elseif ( false !== $args->supports ) { // Add default features add_post_type_support($post_type, array('title', 'editor')); } if ( false !== $args->query_var && !empty($wp) ) { if ( true === $args->query_var ) $args->query_var = $post_type; else $args->query_var = sanitize_title_with_dashes($args->query_var); $wp->add_query_var($args->query_var); } if ( false !== $args->rewrite && ( is_admin() || '' != get_option('permalink_structure') ) ) { if ( ! is_array( $args->rewrite ) ) $args->rewrite = array(); if ( empty( $args->rewrite['slug'] ) ) $args->rewrite['slug'] = $post_type; if ( ! isset( $args->rewrite['with_front'] ) ) $args->rewrite['with_front'] = true; if ( ! isset( $args->rewrite['pages'] ) ) $args->rewrite['pages'] = true; if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive ) $args->rewrite['feeds'] = (bool) $args->has_archive; if ( ! isset( $args->rewrite['ep_mask'] ) ) { if ( isset( $args->permalink_epmask ) ) $args->rewrite['ep_mask'] = $args->permalink_epmask; else $args->rewrite['ep_mask'] = EP_PERMALINK; } if ( $args->hierarchical ) add_rewrite_tag("%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name="); else add_rewrite_tag("%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name="); if ( $args->has_archive ) { $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive; if ( $args->rewrite['with_front'] ) $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug; else $archive_slug = $wp_rewrite->root . $archive_slug; add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' ); if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) { $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')'; add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' ); add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' ); } if ( $args->rewrite['pages'] ) add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' ); } add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $args->rewrite ); } if ( $args->register_meta_box_cb ) add_action('add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1); $args->labels = get_post_type_labels( $args ); $args->label = $args->labels->name; $wp_post_types[$post_type] = $args; add_action( 'future_' . $post_type, '_future_post_hook', 5, 2 ); foreach ( $args->taxonomies as $taxonomy ) { register_taxonomy_for_object_type( $taxonomy, $post_type ); } do_action( 'registered_post_type', $post_type, $args ); return $args; } /** * Builds an object with all post type capabilities out of a post type object * * Post type capabilities use the 'capability_type' argument as a base, if the * capability is not set in the 'capabilities' argument array or if the * 'capabilities' argument is not supplied. * * The capability_type argument can optionally be registered as an array, with * the first value being singular and the second plural, e.g. array('story, 'stories') * Otherwise, an 's' will be added to the value for the plural form. After * registration, capability_type will always be a string of the singular value. * * By default, seven keys are accepted as part of the capabilities array: * * - edit_post, read_post, and delete_post are meta capabilities, which are then * generally mapped to corresponding primitive capabilities depending on the * context, which would be the post being edited/read/deleted and the user or * role being checked. Thus these capabilities would generally not be granted * directly to users or roles. * * - edit_posts - Controls whether objects of this post type can be edited. * - edit_others_posts - Controls whether objects of this type owned by other users * can be edited. If the post type does not support an author, then this will * behave like edit_posts. * - publish_posts - Controls publishing objects of this post type. * - read_private_posts - Controls whether private objects can be read. * * These four primitive capabilities are checked in core in various locations. * There are also seven other primitive capabilities which are not referenced * directly in core, except in map_meta_cap(), which takes the three aforementioned * meta capabilities and translates them into one or more primitive capabilities * that must then be checked against the user or role, depending on the context. * * - read - Controls whether objects of this post type can be read. * - delete_posts - Controls whether objects of this post type can be deleted. * - delete_private_posts - Controls whether private objects can be deleted. * - delete_published_posts - Controls whether published objects can be deleted. * - delete_others_posts - Controls whether objects owned by other users can be * can be deleted. If the post type does not support an author, then this will * behave like delete_posts. * - edit_private_posts - Controls whether private objects can be edited. * - edit_published_posts - Controls whether published objects can be edited. * * These additional capabilities are only used in map_meta_cap(). Thus, they are * only assigned by default if the post type is registered with the 'map_meta_cap' * argument set to true (default is false). * * @see map_meta_cap() * @since 3.0.0 * * @param object $args Post type registration arguments * @return object object with all the capabilities as member variables */ function get_post_type_capabilities( $args ) { if ( ! is_array( $args->capability_type ) ) $args->capability_type = array( $args->capability_type, $args->capability_type . 's' ); // Singular base for meta capabilities, plural base for primitive capabilities. list( $singular_base, $plural_base ) = $args->capability_type; $default_capabilities = array( // Meta capabilities 'edit_post' => 'edit_' . $singular_base, 'read_post' => 'read_' . $singular_base, 'delete_post' => 'delete_' . $singular_base, // Primitive capabilities used outside of map_meta_cap(): 'edit_posts' => 'edit_' . $plural_base, 'edit_others_posts' => 'edit_others_' . $plural_base, 'publish_posts' => 'publish_' . $plural_base, 'read_private_posts' => 'read_private_' . $plural_base, ); // Primitive capabilities used within map_meta_cap(): if ( $args->map_meta_cap ) { $default_capabilities_for_mapping = array( 'read' => 'read', 'delete_posts' => 'delete_' . $plural_base, 'delete_private_posts' => 'delete_private_' . $plural_base, 'delete_published_posts' => 'delete_published_' . $plural_base, 'delete_others_posts' => 'delete_others_' . $plural_base, 'edit_private_posts' => 'edit_private_' . $plural_base, 'edit_published_posts' => 'edit_published_' . $plural_base, ); $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping ); } $capabilities = array_merge( $default_capabilities, $args->capabilities ); // Post creation capability simply maps to edit_posts by default: if ( ! isset( $capabilities['create_posts'] ) ) $capabilities['create_posts'] = $capabilities['edit_posts']; // Remember meta capabilities for future reference. if ( $args->map_meta_cap ) _post_type_meta_capabilities( $capabilities ); return (object) $capabilities; } /** * Stores or returns a list of post type meta caps for map_meta_cap(). * * @since 3.1.0 * @access private */ function _post_type_meta_capabilities( $capabilities = null ) { static $meta_caps = array(); if ( null === $capabilities ) return $meta_caps; foreach ( $capabilities as $core => $custom ) { if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) ) $meta_caps[ $custom ] = $core; } } /** * Builds an object with all post type labels out of a post type object * * Accepted keys of the label array in the post type object: * - name - general name for the post type, usually plural. The same and overridden by $post_type_object->label. Default is Posts/Pages * - singular_name - name for one object of this post type. Default is Post/Page * - add_new - Default is Add New for both hierarchical and non-hierarchical types. When internationalizing this string, please use a {@link http://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context gettext context} matching your post type. Example: <code>_x('Add New', 'product');</code> * - add_new_item - Default is Add New Post/Add New Page * - edit_item - Default is Edit Post/Edit Page * - new_item - Default is New Post/New Page * - view_item - Default is View Post/View Page * - search_items - Default is Search Posts/Search Pages * - not_found - Default is No posts found/No pages found * - not_found_in_trash - Default is No posts found in Trash/No pages found in Trash * - parent_item_colon - This string isn't used on non-hierarchical types. In hierarchical ones the default is Parent Page: * - all_items - String for the submenu. Default is All Posts/All Pages * - menu_name - Default is the same as <code>name</code> * * Above, the first default value is for non-hierarchical post types (like posts) and the second one is for hierarchical post types (like pages). * * @since 3.0.0 * @param object $post_type_object * @return object object with all the labels as member variables */ function get_post_type_labels( $post_type_object ) { $nohier_vs_hier_defaults = array( 'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ), 'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ), 'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ), 'add_new_item' => array( __('Add New Post'), __('Add New Page') ), 'edit_item' => array( __('Edit Post'), __('Edit Page') ), 'new_item' => array( __('New Post'), __('New Page') ), 'view_item' => array( __('View Post'), __('View Page') ), 'search_items' => array( __('Search Posts'), __('Search Pages') ), 'not_found' => array( __('No posts found.'), __('No pages found.') ), 'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ), 'parent_item_colon' => array( null, __('Parent Page:') ), 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) ) ); $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name']; $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults ); $post_type = $post_type_object->name; return apply_filters( "post_type_labels_{$post_type}", $labels ); } /** * Builds an object with custom-something object (post type, taxonomy) labels out of a custom-something object * * @access private * @since 3.0.0 */ function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) { if ( isset( $object->label ) && empty( $object->labels['name'] ) ) $object->labels['name'] = $object->label; if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) ) $object->labels['singular_name'] = $object->labels['name']; if ( ! isset( $object->labels['name_admin_bar'] ) ) $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name; if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) ) $object->labels['menu_name'] = $object->labels['name']; if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) ) $object->labels['all_items'] = $object->labels['menu_name']; foreach ( $nohier_vs_hier_defaults as $key => $value ) $defaults[$key] = $object->hierarchical ? $value[1] : $value[0]; $labels = array_merge( $defaults, $object->labels ); return (object)$labels; } /** * Adds submenus for post types. * * @access private * @since 3.1.0 */ function _add_post_type_submenus() { foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) { $ptype_obj = get_post_type_object( $ptype ); // Submenus only. if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true ) continue; add_submenu_page( $ptype_obj->show_in_menu, $ptype_obj->labels->name, $ptype_obj->labels->all_items, $ptype_obj->cap->edit_posts, "edit.php?post_type=$ptype" ); } } add_action( 'admin_menu', '_add_post_type_submenus' ); /** * Register support of certain features for a post type. * * All features are directly associated with a functional area of the edit screen, such as the * editor or a meta box: 'title', 'editor', 'comments', 'revisions', 'trackbacks', 'author', * 'excerpt', 'page-attributes', 'thumbnail', and 'custom-fields'. * * Additionally, the 'revisions' feature dictates whether the post type will store revisions, * and the 'comments' feature dictates whether the comments count will show on the edit screen. * * @since 3.0.0 * @param string $post_type The post type for which to add the feature * @param string|array $feature the feature being added, can be an array of feature strings or a single string */ function add_post_type_support( $post_type, $feature ) { global $_wp_post_type_features; $features = (array) $feature; foreach ($features as $feature) { if ( func_num_args() == 2 ) $_wp_post_type_features[$post_type][$feature] = true; else $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 ); } } /** * Remove support for a feature from a post type. * * @since 3.0.0 * @param string $post_type The post type for which to remove the feature * @param string $feature The feature being removed */ function remove_post_type_support( $post_type, $feature ) { global $_wp_post_type_features; if ( isset( $_wp_post_type_features[$post_type][$feature] ) ) unset( $_wp_post_type_features[$post_type][$feature] ); } /** * Get all the post type features * * @since 3.4.0 * @param string $post_type The post type * @return array */ function get_all_post_type_supports( $post_type ) { global $_wp_post_type_features; if ( isset( $_wp_post_type_features[$post_type] ) ) return $_wp_post_type_features[$post_type]; return array(); } /** * Checks a post type's support for a given feature * * @since 3.0.0 * @param string $post_type The post type being checked * @param string $feature the feature being checked * @return boolean */ function post_type_supports( $post_type, $feature ) { global $_wp_post_type_features; return ( isset( $_wp_post_type_features[$post_type][$feature] ) ); } /** * Updates the post type for the post ID. * * The page or post cache will be cleaned for the post ID. * * @since 2.5.0 * * @uses $wpdb * * @param int $post_id Post ID to change post type. Not actually optional. * @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to * name a few. * @return int Amount of rows changed. Should be 1 for success and 0 for failure. */ function set_post_type( $post_id = 0, $post_type = 'post' ) { global $wpdb; $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db'); $return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) ); clean_post_cache( $post_id ); return $return; } /** * Retrieve list of latest posts or posts matching criteria. * * The defaults are as follows: * 'numberposts' - Default is 5. Total number of posts to retrieve. * 'offset' - Default is 0. See {@link WP_Query::query()} for more. * 'category' - What category to pull the posts from. * 'orderby' - Default is 'post_date'. How to order the posts. * 'order' - Default is 'DESC'. The order to retrieve the posts. * 'include' - See {@link WP_Query::query()} for more. * 'exclude' - See {@link WP_Query::query()} for more. * 'meta_key' - See {@link WP_Query::query()} for more. * 'meta_value' - See {@link WP_Query::query()} for more. * 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few. * 'post_parent' - The parent of the post or post type. * 'post_status' - Default is 'publish'. Post status to retrieve. * * @since 1.2.0 * @uses $wpdb * @uses WP_Query::query() See for more default arguments and information. * @link http://codex.wordpress.org/Template_Tags/get_posts * * @param array $args Optional. Overrides defaults. * @return array List of posts. */ function get_posts($args = null) { $defaults = array( 'numberposts' => 5, 'offset' => 0, 'category' => 0, 'orderby' => 'post_date', 'order' => 'DESC', 'include' => array(), 'exclude' => array(), 'meta_key' => '', 'meta_value' =>'', 'post_type' => 'post', 'suppress_filters' => true ); $r = wp_parse_args( $args, $defaults ); if ( empty( $r['post_status'] ) ) $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish'; if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) ) $r['posts_per_page'] = $r['numberposts']; if ( ! empty($r['category']) ) $r['cat'] = $r['category']; if ( ! empty($r['include']) ) { $incposts = wp_parse_id_list( $r['include'] ); $r['posts_per_page'] = count($incposts); // only the number of posts included $r['post__in'] = $incposts; } elseif ( ! empty($r['exclude']) ) $r['post__not_in'] = wp_parse_id_list( $r['exclude'] ); $r['ignore_sticky_posts'] = true; $r['no_found_rows'] = true; $get_posts = new WP_Query; return $get_posts->query($r); } // // Post meta functions // /** * Add meta data field to a post. * * Post meta data is called "Custom Fields" on the Administration Screen. * * @since 1.5.0 * @uses $wpdb * @link http://codex.wordpress.org/Function_Reference/add_post_meta * * @param int $post_id Post ID. * @param string $meta_key Metadata name. * @param mixed $meta_value Metadata value. * @param bool $unique Optional, default is false. Whether the same key should not be added. * @return int|bool Meta ID on success, false on failure. */ function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) { // make sure meta is added to the post, not a revision if ( $the_post = wp_is_post_revision($post_id) ) $post_id = $the_post; return add_metadata('post', $post_id, $meta_key, $meta_value, $unique); } /** * Remove metadata matching criteria from a post. * * You can match based on the key, or key and value. Removing based on key and * value, will keep from removing duplicate metadata with the same key. It also * allows removing all metadata matching key, if needed. * * @since 1.5.0 * @uses $wpdb * @link http://codex.wordpress.org/Function_Reference/delete_post_meta * * @param int $post_id post ID * @param string $meta_key Metadata name. * @param mixed $meta_value Optional. Metadata value. * @return bool True on success, false on failure. */ function delete_post_meta($post_id, $meta_key, $meta_value = '') { // make sure meta is added to the post, not a revision if ( $the_post = wp_is_post_revision($post_id) ) $post_id = $the_post; return delete_metadata('post', $post_id, $meta_key, $meta_value); } /** * Retrieve post meta field for a post. * * @since 1.5.0 * @uses $wpdb * @link http://codex.wordpress.org/Function_Reference/get_post_meta * * @param int $post_id Post ID. * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys. * @param bool $single Whether to return a single value. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single * is true. */ function get_post_meta($post_id, $key = '', $single = false) { return get_metadata('post', $post_id, $key, $single); } /** * Update post meta field based on post ID. * * Use the $prev_value parameter to differentiate between meta fields with the * same key and post ID. * * If the meta field for the post does not exist, it will be added. * * @since 1.5.0 * @uses $wpdb * @link http://codex.wordpress.org/Function_Reference/update_post_meta * * @param int $post_id Post ID. * @param string $meta_key Metadata key. * @param mixed $meta_value Metadata value. * @param mixed $prev_value Optional. Previous value to check before removing. * @return bool True on success, false on failure. */ function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') { // make sure meta is added to the post, not a revision if ( $the_post = wp_is_post_revision($post_id) ) $post_id = $the_post; return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value); } /** * Delete everything from post meta matching meta key. * * @since 2.3.0 * @uses $wpdb * * @param string $post_meta_key Key to search for when deleting. * @return bool Whether the post meta key was deleted from the database */ function delete_post_meta_by_key($post_meta_key) { return delete_metadata( 'post', null, $post_meta_key, '', true ); } /** * Retrieve post meta fields, based on post ID. * * The post meta fields are retrieved from the cache where possible, * so the function is optimized to be called more than once. * * @since 1.2.0 * @link http://codex.wordpress.org/Function_Reference/get_post_custom * * @param int $post_id Post ID. * @return array */ function get_post_custom( $post_id = 0 ) { $post_id = absint( $post_id ); if ( ! $post_id ) $post_id = get_the_ID(); return get_post_meta( $post_id ); } /** * Retrieve meta field names for a post. * * If there are no meta fields, then nothing (null) will be returned. * * @since 1.2.0 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys * * @param int $post_id post ID * @return array|null Either array of the keys, or null if keys could not be retrieved. */ function get_post_custom_keys( $post_id = 0 ) { $custom = get_post_custom( $post_id ); if ( !is_array($custom) ) return; if ( $keys = array_keys($custom) ) return $keys; } /** * Retrieve values for a custom post field. * * The parameters must not be considered optional. All of the post meta fields * will be retrieved and only the meta field key values returned. * * @since 1.2.0 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values * * @param string $key Meta field key. * @param int $post_id Post ID * @return array Meta field values. */ function get_post_custom_values( $key = '', $post_id = 0 ) { if ( !$key ) return null; $custom = get_post_custom($post_id); return isset($custom[$key]) ? $custom[$key] : null; } /** * Check if post is sticky. * * Sticky posts should remain at the top of The Loop. If the post ID is not * given, then The Loop ID for the current post will be used. * * @since 2.7.0 * * @param int $post_id Optional. Post ID. * @return bool Whether post is sticky. */ function is_sticky( $post_id = 0 ) { $post_id = absint( $post_id ); if ( ! $post_id ) $post_id = get_the_ID(); $stickies = get_option( 'sticky_posts' ); if ( ! is_array( $stickies ) ) return false; if ( in_array( $post_id, $stickies ) ) return true; return false; } /** * Sanitize every post field. * * If the context is 'raw', then the post object or array will get minimal santization of the int fields. * * @since 2.3.0 * @uses sanitize_post_field() Used to sanitize the fields. * * @param object|WP_Post|array $post The Post Object or Array * @param string $context Optional, default is 'display'. How to sanitize post fields. * @return object|WP_Post|array The now sanitized Post Object or Array (will be the same type as $post) */ function sanitize_post($post, $context = 'display') { if ( is_object($post) ) { // Check if post already filtered for this context if ( isset($post->filter) && $context == $post->filter ) return $post; if ( !isset($post->ID) ) $post->ID = 0; foreach ( array_keys(get_object_vars($post)) as $field ) $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context); $post->filter = $context; } else { // Check if post already filtered for this context if ( isset($post['filter']) && $context == $post['filter'] ) return $post; if ( !isset($post['ID']) ) $post['ID'] = 0; foreach ( array_keys($post) as $field ) $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context); $post['filter'] = $context; } return $post; } /** * Sanitize post field based on context. * * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display' * when calling filters. * * @since 2.3.0 * @uses apply_filters() Calls 'edit_$field' and '{$field_no_prefix}_edit_pre' passing $value and * $post_id if $context == 'edit' and field name prefix == 'post_'. * * @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'. * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'. * @uses apply_filters() Calls '{$field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'. * * @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything * other than 'raw', 'edit' and 'db' and field name prefix == 'post_'. * @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw', * 'edit' and 'db' and field name prefix != 'post_'. * * @param string $field The Post Object field name. * @param mixed $value The Post Object value. * @param int $post_id Post ID. * @param string $context How to sanitize post fields. Looks for 'raw', 'edit', 'db', 'display', * 'attribute' and 'js'. * @return mixed Sanitized value. */ function sanitize_post_field($field, $value, $post_id, $context) { $int_fields = array('ID', 'post_parent', 'menu_order'); if ( in_array($field, $int_fields) ) $value = (int) $value; // Fields which contain arrays of ints. $array_int_fields = array( 'ancestors' ); if ( in_array($field, $array_int_fields) ) { $value = array_map( 'absint', $value); return $value; } if ( 'raw' == $context ) return $value; $prefixed = false; if ( false !== strpos($field, 'post_') ) { $prefixed = true; $field_no_prefix = str_replace('post_', '', $field); } if ( 'edit' == $context ) { $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password'); if ( $prefixed ) { $value = apply_filters("edit_{$field}", $value, $post_id); // Old school $value = apply_filters("{$field_no_prefix}_edit_pre", $value, $post_id); } else { $value = apply_filters("edit_post_{$field}", $value, $post_id); } if ( in_array($field, $format_to_edit) ) { if ( 'post_content' == $field ) $value = format_to_edit($value, user_can_richedit()); else $value = format_to_edit($value); } else { $value = esc_attr($value); } } else if ( 'db' == $context ) { if ( $prefixed ) { $value = apply_filters("pre_{$field}", $value); $value = apply_filters("{$field_no_prefix}_save_pre", $value); } else { $value = apply_filters("pre_post_{$field}", $value); $value = apply_filters("{$field}_pre", $value); } } else { // Use display filters by default. if ( $prefixed ) $value = apply_filters($field, $value, $post_id, $context); else $value = apply_filters("post_{$field}", $value, $post_id, $context); } if ( 'attribute' == $context ) $value = esc_attr($value); else if ( 'js' == $context ) $value = esc_js($value); return $value; } /** * Make a post sticky. * * Sticky posts should be displayed at the top of the front page. * * @since 2.7.0 * * @param int $post_id Post ID. */ function stick_post($post_id) { $stickies = get_option('sticky_posts'); if ( !is_array($stickies) ) $stickies = array($post_id); if ( ! in_array($post_id, $stickies) ) $stickies[] = $post_id; update_option('sticky_posts', $stickies); } /** * Unstick a post. * * Sticky posts should be displayed at the top of the front page. * * @since 2.7.0 * * @param int $post_id Post ID. */ function unstick_post($post_id) { $stickies = get_option('sticky_posts'); if ( !is_array($stickies) ) return; if ( ! in_array($post_id, $stickies) ) return; $offset = array_search($post_id, $stickies); if ( false === $offset ) return; array_splice($stickies, $offset, 1); update_option('sticky_posts', $stickies); } /** * Count number of posts of a post type and is user has permissions to view. * * This function provides an efficient method of finding the amount of post's * type a blog has. Another method is to count the amount of items in * get_posts(), but that method has a lot of overhead with doing so. Therefore, * when developing for 2.5+, use this function instead. * * The $perm parameter checks for 'readable' value and if the user can read * private posts, it will display that for the user that is signed in. * * @since 2.5.0 * @link http://codex.wordpress.org/Template_Tags/wp_count_posts * * @param string $type Optional. Post type to retrieve count * @param string $perm Optional. 'readable' or empty. * @return object Number of posts for each status */ function wp_count_posts( $type = 'post', $perm = '' ) { global $wpdb; $user = wp_get_current_user(); $cache_key = $type; $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s"; if ( 'readable' == $perm && is_user_logged_in() ) { $post_type_object = get_post_type_object($type); if ( !current_user_can( $post_type_object->cap->read_private_posts ) ) { $cache_key .= '_' . $perm . '_' . $user->ID; $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))"; } } $query .= ' GROUP BY post_status'; $count = wp_cache_get($cache_key, 'counts'); if ( false !== $count ) return $count; $count = $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A ); $stats = array(); foreach ( get_post_stati() as $state ) $stats[$state] = 0; foreach ( (array) $count as $row ) $stats[$row['post_status']] = $row['num_posts']; $stats = (object) $stats; wp_cache_set($cache_key, $stats, 'counts'); return $stats; } /** * Count number of attachments for the mime type(s). * * If you set the optional mime_type parameter, then an array will still be * returned, but will only have the item you are looking for. It does not give * you the number of attachments that are children of a post. You can get that * by counting the number of children that post has. * * @since 2.5.0 * * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns. * @return array Number of posts for each mime type. */ function wp_count_attachments( $mime_type = '' ) { global $wpdb; $and = wp_post_mime_type_where( $mime_type ); $count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' $and GROUP BY post_mime_type", ARRAY_A ); $stats = array(); foreach( (array) $count as $row ) { $stats[$row['post_mime_type']] = $row['num_posts']; } $stats['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and"); return (object) $stats; } /** * Get default post mime types * * @since 2.9.0 * * @return array */ function get_post_mime_types() { $post_mime_types = array( // array( adj, noun ) 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')), 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')), 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')), ); return apply_filters('post_mime_types', $post_mime_types); } /** * Check a MIME-Type against a list. * * If the wildcard_mime_types parameter is a string, it must be comma separated * list. If the real_mime_types is a string, it is also comma separated to * create the list. * * @since 2.5.0 * * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or * flash (same as *flash*). * @param string|array $real_mime_types post_mime_type values * @return array array(wildcard=>array(real types)) */ function wp_match_mime_types($wildcard_mime_types, $real_mime_types) { $matches = array(); if ( is_string($wildcard_mime_types) ) $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types)); if ( is_string($real_mime_types) ) $real_mime_types = array_map('trim', explode(',', $real_mime_types)); $wild = '[-._a-z0-9]*'; foreach ( (array) $wildcard_mime_types as $type ) { $type = str_replace('*', $wild, $type); $patternses[1][$type] = "^$type$"; if ( false === strpos($type, '/') ) { $patternses[2][$type] = "^$type/"; $patternses[3][$type] = $type; } } asort($patternses); foreach ( $patternses as $patterns ) foreach ( $patterns as $type => $pattern ) foreach ( (array) $real_mime_types as $real ) if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) ) $matches[$type][] = $real; return $matches; } /** * Convert MIME types into SQL. * * @since 2.5.0 * * @param string|array $post_mime_types List of mime types or comma separated string of mime types. * @param string $table_alias Optional. Specify a table alias, if needed. * @return string The SQL AND clause for mime searching. */ function wp_post_mime_type_where($post_mime_types, $table_alias = '') { $where = ''; $wildcards = array('', '%', '%/%'); if ( is_string($post_mime_types) ) $post_mime_types = array_map('trim', explode(',', $post_mime_types)); foreach ( (array) $post_mime_types as $mime_type ) { $mime_type = preg_replace('/\s/', '', $mime_type); $slashpos = strpos($mime_type, '/'); if ( false !== $slashpos ) { $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos)); $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1)); if ( empty($mime_subgroup) ) $mime_subgroup = '*'; else $mime_subgroup = str_replace('/', '', $mime_subgroup); $mime_pattern = "$mime_group/$mime_subgroup"; } else { $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type); if ( false === strpos($mime_pattern, '*') ) $mime_pattern .= '/*'; } $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern); if ( in_array( $mime_type, $wildcards ) ) return ''; if ( false !== strpos($mime_pattern, '%') ) $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'"; else $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'"; } if ( !empty($wheres) ) $where = ' AND (' . join(' OR ', $wheres) . ') '; return $where; } /** * Trashes or deletes a post or page. * * When the post and page is permanently deleted, everything that is tied to it is deleted also. * This includes comments, post meta fields, and terms associated with the post. * * The post or page is moved to trash instead of permanently deleted unless trash is * disabled, item is already in the trash, or $force_delete is true. * * @since 1.0.0 * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'. * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'. * @uses wp_delete_attachment() if post type is 'attachment'. * @uses wp_trash_post() if item should be trashed. * * @param int $postid Post ID. * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false. * @return mixed False on failure */ function wp_delete_post( $postid = 0, $force_delete = false ) { global $wpdb; if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) ) return $post; if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS ) return wp_trash_post($postid); if ( $post->post_type == 'attachment' ) return wp_delete_attachment( $postid, $force_delete ); do_action('before_delete_post', $postid); delete_post_meta($postid,'_wp_trash_meta_status'); delete_post_meta($postid,'_wp_trash_meta_time'); wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type)); $parent_data = array( 'post_parent' => $post->post_parent ); $parent_where = array( 'post_parent' => $postid ); if ( is_post_type_hierarchical( $post->post_type ) ) { // Point children of this page to its parent, also clean the cache of affected children $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type ); $children = $wpdb->get_results( $children_query ); $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) ); } if ( 'page' == $post->post_type) { // if the page is defined in option page_on_front or post_for_posts, // adjust the corresponding options if ( get_option('page_on_front') == $postid ) { update_option('show_on_front', 'posts'); delete_option('page_on_front'); } if ( get_option('page_for_posts') == $postid ) { delete_option('page_for_posts'); } } else { unstick_post($postid); } // Do raw query. wp_get_post_revisions() is filtered $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) ); // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up. foreach ( $revision_ids as $revision_id ) wp_delete_post_revision( $revision_id ); // Point all attachments to this post up one level $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) ); $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid )); foreach ( $comment_ids as $comment_id ) wp_delete_comment( $comment_id, true ); $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid )); foreach ( $post_meta_ids as $mid ) delete_metadata_by_mid( 'post', $mid ); do_action( 'delete_post', $postid ); $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) ); do_action( 'deleted_post', $postid ); clean_post_cache( $post ); if ( is_post_type_hierarchical( $post->post_type ) && $children ) { foreach ( $children as $child ) clean_post_cache( $child ); } wp_clear_scheduled_hook('publish_future_post', array( $postid ) ); do_action('after_delete_post', $postid); return $post; } /** * Moves a post or page to the Trash * * If trash is disabled, the post or page is permanently deleted. * * @since 2.9.0 * @uses do_action() on 'trash_post' before trashing * @uses do_action() on 'trashed_post' after trashing * @uses wp_delete_post() if trash is disabled * * @param int $post_id Post ID. * @return mixed False on failure */ function wp_trash_post($post_id = 0) { if ( !EMPTY_TRASH_DAYS ) return wp_delete_post($post_id, true); if ( !$post = get_post($post_id, ARRAY_A) ) return $post; if ( $post['post_status'] == 'trash' ) return false; do_action('wp_trash_post', $post_id); add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']); add_post_meta($post_id,'_wp_trash_meta_time', time()); $post['post_status'] = 'trash'; wp_insert_post($post); wp_trash_post_comments($post_id); do_action('trashed_post', $post_id); return $post; } /** * Restores a post or page from the Trash * * @since 2.9.0 * @uses do_action() on 'untrash_post' before undeletion * @uses do_action() on 'untrashed_post' after undeletion * * @param int $post_id Post ID. * @return mixed False on failure */ function wp_untrash_post($post_id = 0) { if ( !$post = get_post($post_id, ARRAY_A) ) return $post; if ( $post['post_status'] != 'trash' ) return false; do_action('untrash_post', $post_id); $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true); $post['post_status'] = $post_status; delete_post_meta($post_id, '_wp_trash_meta_status'); delete_post_meta($post_id, '_wp_trash_meta_time'); wp_insert_post($post); wp_untrash_post_comments($post_id); do_action('untrashed_post', $post_id); return $post; } /** * Moves comments for a post to the trash * * @since 2.9.0 * @uses do_action() on 'trash_post_comments' before trashing * @uses do_action() on 'trashed_post_comments' after trashing * * @param int|object $post Post ID or object. * @return mixed False on failure */ function wp_trash_post_comments($post = null) { global $wpdb; $post = get_post($post); if ( empty($post) ) return; $post_id = $post->ID; do_action('trash_post_comments', $post_id); $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) ); if ( empty($comments) ) return; // Cache current status for each comment $statuses = array(); foreach ( $comments as $comment ) $statuses[$comment->comment_ID] = $comment->comment_approved; add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses); // Set status for all comments to post-trashed $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id)); clean_comment_cache( array_keys($statuses) ); do_action('trashed_post_comments', $post_id, $statuses); return $result; } /** * Restore comments for a post from the trash * * @since 2.9.0 * @uses do_action() on 'untrash_post_comments' before trashing * @uses do_action() on 'untrashed_post_comments' after trashing * * @param int|object $post Post ID or object. * @return mixed False on failure */ function wp_untrash_post_comments($post = null) { global $wpdb; $post = get_post($post); if ( empty($post) ) return; $post_id = $post->ID; $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true); if ( empty($statuses) ) return true; do_action('untrash_post_comments', $post_id); // Restore each comment to its original status $group_by_status = array(); foreach ( $statuses as $comment_id => $comment_status ) $group_by_status[$comment_status][] = $comment_id; foreach ( $group_by_status as $status => $comments ) { // Sanity check. This shouldn't happen. if ( 'post-trashed' == $status ) $status = '0'; $comments_in = implode( "', '", $comments ); $wpdb->query( "UPDATE $wpdb->comments SET comment_approved = '$status' WHERE comment_ID IN ('" . $comments_in . "')" ); } clean_comment_cache( array_keys($statuses) ); delete_post_meta($post_id, '_wp_trash_meta_comments_status'); do_action('untrashed_post_comments', $post_id); } /** * Retrieve the list of categories for a post. * * Compatibility layer for themes and plugins. Also an easy layer of abstraction * away from the complexity of the taxonomy layer. * * @since 2.1.0 * * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here. * * @param int $post_id Optional. The Post ID. * @param array $args Optional. Overwrite the defaults. * @return array */ function wp_get_post_categories( $post_id = 0, $args = array() ) { $post_id = (int) $post_id; $defaults = array('fields' => 'ids'); $args = wp_parse_args( $args, $defaults ); $cats = wp_get_object_terms($post_id, 'category', $args); return $cats; } /** * Retrieve the tags for a post. * * There is only one default for this function, called 'fields' and by default * is set to 'all'. There are other defaults that can be overridden in * {@link wp_get_object_terms()}. * * @package WordPress * @subpackage Post * @since 2.3.0 * * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here * * @param int $post_id Optional. The Post ID * @param array $args Optional. Overwrite the defaults * @return array List of post tags. */ function wp_get_post_tags( $post_id = 0, $args = array() ) { return wp_get_post_terms( $post_id, 'post_tag', $args); } /** * Retrieve the terms for a post. * * There is only one default for this function, called 'fields' and by default * is set to 'all'. There are other defaults that can be overridden in * {@link wp_get_object_terms()}. * * @package WordPress * @subpackage Post * @since 2.8.0 * * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here * * @param int $post_id Optional. The Post ID * @param string $taxonomy The taxonomy for which to retrieve terms. Defaults to post_tag. * @param array $args Optional. Overwrite the defaults * @return array List of post tags. */ function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) { $post_id = (int) $post_id; $defaults = array('fields' => 'all'); $args = wp_parse_args( $args, $defaults ); $tags = wp_get_object_terms($post_id, $taxonomy, $args); return $tags; } /** * Retrieve number of recent posts. * * @since 1.0.0 * @uses wp_parse_args() * @uses get_posts() * * @param string $deprecated Deprecated. * @param array $args Optional. Overrides defaults. * @param string $output Optional. * @return unknown. */ function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) { if ( is_numeric( $args ) ) { _deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) ); $args = array( 'numberposts' => absint( $args ) ); } // Set default arguments $defaults = array( 'numberposts' => 10, 'offset' => 0, 'category' => 0, 'orderby' => 'post_date', 'order' => 'DESC', 'include' => '', 'exclude' => '', 'meta_key' => '', 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private', 'suppress_filters' => true ); $r = wp_parse_args( $args, $defaults ); $results = get_posts( $r ); // Backward compatibility. Prior to 3.1 expected posts to be returned in array if ( ARRAY_A == $output ){ foreach( $results as $key => $result ) { $results[$key] = get_object_vars( $result ); } return $results ? $results : array(); } return $results ? $results : false; } /** * Insert a post. * * If the $postarr parameter has 'ID' set to a value, then post will be updated. * * You can set the post date manually, by setting the values for 'post_date' * and 'post_date_gmt' keys. You can close the comments or open the comments by * setting the value for 'comment_status' key. * * The defaults for the parameter $postarr are: * 'post_status' - Default is 'draft'. * 'post_type' - Default is 'post'. * 'post_author' - Default is current user ID ($user_ID). The ID of the user who added the post. * 'ping_status' - Default is the value in 'default_ping_status' option. * Whether the attachment can accept pings. * 'post_parent' - Default is 0. Set this for the post it belongs to, if any. * 'menu_order' - Default is 0. The order it is displayed. * 'to_ping' - Whether to ping. * 'pinged' - Default is empty string. * 'post_password' - Default is empty string. The password to access the attachment. * 'guid' - Global Unique ID for referencing the attachment. * 'post_content_filtered' - Post content filtered. * 'post_excerpt' - Post excerpt. * * @since 1.0.0 * @uses $wpdb * @uses $user_ID * @uses do_action() Calls 'pre_post_update' on post ID if this is an update. * @uses do_action() Calls 'edit_post' action on post ID and post data if this is an update. * @uses do_action() Calls 'save_post' and 'wp_insert_post' on post id and post data just before returning. * @uses apply_filters() Calls 'wp_insert_post_data' passing $data, $postarr prior to database update or insert. * @uses wp_transition_post_status() * * @param array $postarr Elements that make up post to insert. * @param bool $wp_error Optional. Allow return of WP_Error on failure. * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success. */ function wp_insert_post($postarr, $wp_error = false) { global $wpdb, $user_ID; $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'post_content' => '', 'post_title' => ''); $postarr = wp_parse_args($postarr, $defaults); unset( $postarr[ 'filter' ] ); $postarr = sanitize_post($postarr, 'db'); // export array as variables extract($postarr, EXTR_SKIP); // Are we updating or creating? $post_ID = 0; $update = false; if ( ! empty( $ID ) ) { $update = true; // Get the post ID and GUID $post_ID = $ID; $post_before = get_post( $post_ID ); if ( is_null( $post_before ) ) { if ( $wp_error ) return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) ); return 0; } $guid = get_post_field( 'guid', $post_ID ); $previous_status = get_post_field('post_status', $ID); } else { $previous_status = 'new'; } $maybe_empty = ! $post_content && ! $post_title && ! $post_excerpt && post_type_supports( $post_type, 'editor' ) && post_type_supports( $post_type, 'title' ) && post_type_supports( $post_type, 'excerpt' ); if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) { if ( $wp_error ) return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) ); else return 0; } if ( empty($post_type) ) $post_type = 'post'; if ( empty($post_status) ) $post_status = 'draft'; if ( !empty($post_category) ) $post_category = array_filter($post_category); // Filter out empty terms // Make sure we set a valid category. if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) { // 'post' requires at least one category. if ( 'post' == $post_type && 'auto-draft' != $post_status ) $post_category = array( get_option('default_category') ); else $post_category = array(); } if ( empty($post_author) ) $post_author = $user_ID; // Don't allow contributors to set the post slug for pending review posts if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) ) $post_name = ''; // Create a valid post name. Drafts and pending posts are allowed to have an empty // post name. if ( empty($post_name) ) { if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) $post_name = sanitize_title($post_title); else $post_name = ''; } else { // On updates, we need to check to see if it's using the old, fixed sanitization context. $check_name = sanitize_title( $post_name, '', 'old-save' ); if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $ID ) == $check_name ) $post_name = $check_name; else // new post, or slug has changed. $post_name = sanitize_title($post_name); } // If the post date is empty (due to having been new or a draft) and status is not 'draft' or 'pending', set date to now if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date ) $post_date = current_time('mysql'); // validate the date $mm = substr( $post_date, 5, 2 ); $jj = substr( $post_date, 8, 2 ); $aa = substr( $post_date, 0, 4 ); $valid_date = wp_checkdate( $mm, $jj, $aa, $post_date ); if ( !$valid_date ) { if ( $wp_error ) return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) ); else return 0; } if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) { if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) $post_date_gmt = get_gmt_from_date($post_date); else $post_date_gmt = '0000-00-00 00:00:00'; } if ( $update || '0000-00-00 00:00:00' == $post_date ) { $post_modified = current_time( 'mysql' ); $post_modified_gmt = current_time( 'mysql', 1 ); } else { $post_modified = $post_date; $post_modified_gmt = $post_date_gmt; } if ( 'publish' == $post_status ) { $now = gmdate('Y-m-d H:i:59'); if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) ) $post_status = 'future'; } elseif( 'future' == $post_status ) { $now = gmdate('Y-m-d H:i:59'); if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) ) $post_status = 'publish'; } if ( empty($comment_status) ) { if ( $update ) $comment_status = 'closed'; else $comment_status = get_option('default_comment_status'); } if ( empty($ping_status) ) $ping_status = get_option('default_ping_status'); if ( isset($to_ping) ) $to_ping = sanitize_trackback_urls( $to_ping ); else $to_ping = ''; if ( ! isset($pinged) ) $pinged = ''; if ( isset($post_parent) ) $post_parent = (int) $post_parent; else $post_parent = 0; // Check the post_parent to see if it will cause a hierarchy loop $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr ); if ( isset($menu_order) ) $menu_order = (int) $menu_order; else $menu_order = 0; if ( !isset($post_password) || 'private' == $post_status ) $post_password = ''; $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent); // expected_slashed (everything!) $data = compact( array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'guid' ) ); $data = apply_filters('wp_insert_post_data', $data, $postarr); $data = wp_unslash( $data ); $where = array( 'ID' => $post_ID ); if ( $update ) { do_action( 'pre_post_update', $post_ID, $data ); if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) { if ( $wp_error ) return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error); else return 0; } } else { if ( isset($post_mime_type) ) $data['post_mime_type'] = wp_unslash( $post_mime_type ); // This isn't in the update // If there is a suggested ID, use it if not already present if ( !empty($import_id) ) { $import_id = (int) $import_id; if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) { $data['ID'] = $import_id; } } if ( false === $wpdb->insert( $wpdb->posts, $data ) ) { if ( $wp_error ) return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error); else return 0; } $post_ID = (int) $wpdb->insert_id; // use the newly generated $post_ID $where = array( 'ID' => $post_ID ); } if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) { $data['post_name'] = sanitize_title($data['post_title'], $post_ID); $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where ); } if ( is_object_in_taxonomy($post_type, 'category') ) wp_set_post_categories( $post_ID, $post_category ); if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') ) wp_set_post_tags( $post_ID, $tags_input ); // new-style support for all custom taxonomies if ( !empty($tax_input) ) { foreach ( $tax_input as $taxonomy => $tags ) { $taxonomy_obj = get_taxonomy($taxonomy); if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical. $tags = array_filter($tags); if ( current_user_can($taxonomy_obj->cap->assign_terms) ) wp_set_post_terms( $post_ID, $tags, $taxonomy ); } } $current_guid = get_post_field( 'guid', $post_ID ); // Set GUID if ( !$update && '' == $current_guid ) $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where ); clean_post_cache( $post_ID ); $post = get_post($post_ID); if ( !empty($page_template) && 'page' == $data['post_type'] ) { $post->page_template = $page_template; $page_templates = wp_get_theme()->get_page_templates(); if ( 'default' != $page_template && ! isset( $page_templates[ $page_template ] ) ) { if ( $wp_error ) return new WP_Error('invalid_page_template', __('The page template is invalid.')); else return 0; } update_post_meta($post_ID, '_wp_page_template', $page_template); } wp_transition_post_status($data['post_status'], $previous_status, $post); if ( $update ) { do_action('edit_post', $post_ID, $post); $post_after = get_post($post_ID); do_action( 'post_updated', $post_ID, $post_after, $post_before); } do_action('save_post', $post_ID, $post); do_action('wp_insert_post', $post_ID, $post); return $post_ID; } /** * Update a post with new post data. * * The date does not have to be set for drafts. You can set the date and it will * not be overridden. * * @since 1.0.0 * * @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not. * @param bool $wp_error Optional. Allow return of WP_Error on failure. * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success. */ function wp_update_post( $postarr = array(), $wp_error = false ) { if ( is_object($postarr) ) { // non-escaped post was passed $postarr = get_object_vars($postarr); $postarr = wp_slash($postarr); } // First, get all of the original fields $post = get_post($postarr['ID'], ARRAY_A); if ( is_null( $post ) ) { if ( $wp_error ) return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) ); return 0; } // Escape data pulled from DB. $post = wp_slash($post); // Passed post category list overwrites existing category list if not empty. if ( isset($postarr['post_category']) && is_array($postarr['post_category']) && 0 != count($postarr['post_category']) ) $post_cats = $postarr['post_category']; else $post_cats = $post['post_category']; // Drafts shouldn't be assigned a date unless explicitly done so by the user if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) && ('0000-00-00 00:00:00' == $post['post_date_gmt']) ) $clear_date = true; else $clear_date = false; // Merge old and new fields with new fields overwriting old ones. $postarr = array_merge($post, $postarr); $postarr['post_category'] = $post_cats; if ( $clear_date ) { $postarr['post_date'] = current_time('mysql'); $postarr['post_date_gmt'] = ''; } if ($postarr['post_type'] == 'attachment') return wp_insert_attachment($postarr); return wp_insert_post( $postarr, $wp_error ); } /** * Publish a post by transitioning the post status. * * @since 2.1.0 * @uses $wpdb * @uses do_action() Calls 'edit_post', 'save_post', and 'wp_insert_post' on post_id and post data. * * @param int|object $post Post ID or object. */ function wp_publish_post( $post ) { global $wpdb; if ( ! $post = get_post( $post ) ) return; if ( 'publish' == $post->post_status ) return; $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) ); clean_post_cache( $post->ID ); $old_status = $post->post_status; $post->post_status = 'publish'; wp_transition_post_status( 'publish', $old_status, $post ); do_action( 'edit_post', $post->ID, $post ); do_action( 'save_post', $post->ID, $post ); do_action( 'wp_insert_post', $post->ID, $post ); } /** * Publish future post and make sure post ID has future post status. * * Invoked by cron 'publish_future_post' event. This safeguard prevents cron * from publishing drafts, etc. * * @since 2.5.0 * * @param int $post_id Post ID. * @return null Nothing is returned. Which can mean that no action is required or post was published. */ function check_and_publish_future_post($post_id) { $post = get_post($post_id); if ( empty($post) ) return; if ( 'future' != $post->post_status ) return; $time = strtotime( $post->post_date_gmt . ' GMT' ); if ( $time > time() ) { // Uh oh, someone jumped the gun! wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) ); return; } return wp_publish_post($post_id); } /** * Computes a unique slug for the post, when given the desired slug and some post details. * * @since 2.8.0 * * @global wpdb $wpdb * @global WP_Rewrite $wp_rewrite * @param string $slug the desired slug (post_name) * @param integer $post_ID * @param string $post_status no uniqueness checks are made if the post is still draft or pending * @param string $post_type * @param integer $post_parent * @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix) */ function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) { if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) || ( 'inherit' == $post_status && 'revision' == $post_type ) ) return $slug; global $wpdb, $wp_rewrite; $original_slug = $slug; $feeds = $wp_rewrite->feeds; if ( ! is_array( $feeds ) ) $feeds = array(); $hierarchical_post_types = get_post_types( array('hierarchical' => true) ); if ( 'attachment' == $post_type ) { // Attachment slugs must be unique across all types. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1"; $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) ); if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) { $suffix = 2; do { $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix"; $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID ) ); $suffix++; } while ( $post_name_check ); $slug = $alt_post_name; } } elseif ( in_array( $post_type, $hierarchical_post_types ) ) { if ( 'nav_menu_item' == $post_type ) return $slug; // Page slugs must be unique within their own trees. Pages are in a separate // namespace than posts so page slugs are allowed to overlap post slugs. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( '" . implode( "', '", esc_sql( $hierarchical_post_types ) ) . "' ) AND ID != %d AND post_parent = %d LIMIT 1"; $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID, $post_parent ) ); if ( $post_name_check || in_array( $slug, $feeds ) || preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug ) || apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent ) ) { $suffix = 2; do { $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix"; $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID, $post_parent ) ); $suffix++; } while ( $post_name_check ); $slug = $alt_post_name; } } else { // Post slugs must be unique across all posts. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1"; $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) ); if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) { $suffix = 2; do { $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix"; $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) ); $suffix++; } while ( $post_name_check ); $slug = $alt_post_name; } } return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ); } /** * Truncates a post slug. * * @since 3.6.0 * @access private * @uses utf8_uri_encode() Makes sure UTF-8 characters are properly cut and encoded. * * @param string $slug The slug to truncate. * @param int $length Max length of the slug. * @return string The truncated slug. */ function _truncate_post_slug( $slug, $length = 200 ) { if ( strlen( $slug ) > $length ) { $decoded_slug = urldecode( $slug ); if ( $decoded_slug === $slug ) $slug = substr( $slug, 0, $length ); else $slug = utf8_uri_encode( $decoded_slug, $length ); } return rtrim( $slug, '-' ); } /** * Adds tags to a post. * * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true. * * @package WordPress * @subpackage Post * @since 2.3.0 * * @param int $post_id Post ID * @param string $tags The tags to set for the post, separated by commas. * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise */ function wp_add_post_tags($post_id = 0, $tags = '') { return wp_set_post_tags($post_id, $tags, true); } /** * Set the tags for a post. * * @since 2.3.0 * @uses wp_set_object_terms() Sets the tags for the post. * * @param int $post_id Post ID. * @param string $tags The tags to set for the post, separated by commas. * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags. * @return mixed Array of affected term IDs. WP_Error or false on failure. */ function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) { return wp_set_post_terms( $post_id, $tags, 'post_tag', $append); } /** * Set the terms for a post. * * @since 2.8.0 * @uses wp_set_object_terms() Sets the tags for the post. * * @param int $post_id Post ID. * @param string $tags The tags to set for the post, separated by commas. * @param string $taxonomy Taxonomy name. Defaults to 'post_tag'. * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags. * @return mixed Array of affected term IDs. WP_Error or false on failure. */ function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) { $post_id = (int) $post_id; if ( !$post_id ) return false; if ( empty($tags) ) $tags = array(); if ( ! is_array( $tags ) ) { $comma = _x( ',', 'tag delimiter' ); if ( ',' !== $comma ) $tags = str_replace( $comma, ',', $tags ); $tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) ); } // Hierarchical taxonomies must always pass IDs rather than names so that children with the same // names but different parents aren't confused. if ( is_taxonomy_hierarchical( $taxonomy ) ) { $tags = array_unique( array_map( 'intval', $tags ) ); } return wp_set_object_terms( $post_id, $tags, $taxonomy, $append ); } /** * Set categories for a post. * * If the post categories parameter is not set, then the default category is * going used. * * @since 2.1.0 * * @param int $post_ID Post ID. * @param array $post_categories Optional. List of categories. * @return bool|mixed */ function wp_set_post_categories($post_ID = 0, $post_categories = array()) { $post_ID = (int) $post_ID; $post_type = get_post_type( $post_ID ); $post_status = get_post_status( $post_ID ); // If $post_categories isn't already an array, make it one: if ( !is_array($post_categories) || empty($post_categories) ) { if ( 'post' == $post_type && 'auto-draft' != $post_status ) $post_categories = array( get_option('default_category') ); else $post_categories = array(); } else if ( 1 == count($post_categories) && '' == reset($post_categories) ) { return true; } return wp_set_post_terms($post_ID, $post_categories, 'category'); } /** * Transition the post status of a post. * * Calls hooks to transition post status. * * The first is 'transition_post_status' with new status, old status, and post data. * * The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the * $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the * post data. * * The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status * parameter and POSTTYPE is post_type post data. * * @since 2.3.0 * @link http://codex.wordpress.org/Post_Status_Transitions * * @uses do_action() Calls 'transition_post_status' on $new_status, $old_status and * $post if there is a status change. * @uses do_action() Calls '{$old_status}_to_{$new_status}' on $post if there is a status change. * @uses do_action() Calls '{$new_status}_{$post->post_type}' on post ID and $post. * * @param string $new_status Transition to this post status. * @param string $old_status Previous post status. * @param object $post Post data. */ function wp_transition_post_status($new_status, $old_status, $post) { do_action('transition_post_status', $new_status, $old_status, $post); do_action("{$old_status}_to_{$new_status}", $post); do_action("{$new_status}_{$post->post_type}", $post->ID, $post); } // // Trackback and ping functions // /** * Add a URL to those already pung. * * @since 1.5.0 * @uses $wpdb * * @param int $post_id Post ID. * @param string $uri Ping URI. * @return int How many rows were updated. */ function add_ping($post_id, $uri) { global $wpdb; $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id )); $pung = trim($pung); $pung = preg_split('/\s/', $pung); $pung[] = $uri; $new = implode("\n", $pung); $new = apply_filters('add_ping', $new); // expected_slashed ($new) $new = wp_unslash($new); return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) ); } /** * Retrieve enclosures already enclosed for a post. * * @since 1.5.0 * @uses $wpdb * * @param int $post_id Post ID. * @return array List of enclosures */ function get_enclosed($post_id) { $custom_fields = get_post_custom( $post_id ); $pung = array(); if ( !is_array( $custom_fields ) ) return $pung; foreach ( $custom_fields as $key => $val ) { if ( 'enclosure' != $key || !is_array( $val ) ) continue; foreach( $val as $enc ) { $enclosure = explode( "\n", $enc ); $pung[] = trim( $enclosure[ 0 ] ); } } $pung = apply_filters('get_enclosed', $pung, $post_id); return $pung; } /** * Retrieve URLs already pinged for a post. * * @since 1.5.0 * @uses $wpdb * * @param int $post_id Post ID. * @return array */ function get_pung($post_id) { global $wpdb; $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id )); $pung = trim($pung); $pung = preg_split('/\s/', $pung); $pung = apply_filters('get_pung', $pung); return $pung; } /** * Retrieve URLs that need to be pinged. * * @since 1.5.0 * @uses $wpdb * * @param int $post_id Post ID * @return array */ function get_to_ping($post_id) { global $wpdb; $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id )); $to_ping = sanitize_trackback_urls( $to_ping ); $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY); $to_ping = apply_filters('get_to_ping', $to_ping); return $to_ping; } /** * Do trackbacks for a list of URLs. * * @since 1.0.0 * * @param string $tb_list Comma separated list of URLs * @param int $post_id Post ID */ function trackback_url_list($tb_list, $post_id) { if ( ! empty( $tb_list ) ) { // get post data $postdata = get_post($post_id, ARRAY_A); // import postdata as variables extract($postdata, EXTR_SKIP); // form an excerpt $excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content); if (strlen($excerpt) > 255) { $excerpt = substr($excerpt,0,252) . '&hellip;'; } $trackback_urls = explode(',', $tb_list); foreach( (array) $trackback_urls as $tb_url) { $tb_url = trim($tb_url); trackback($tb_url, wp_unslash($post_title), $excerpt, $post_id); } } } // // Page functions // /** * Get a list of page IDs. * * @since 2.0.0 * @uses $wpdb * * @return array List of page IDs. */ function get_all_page_ids() { global $wpdb; $page_ids = wp_cache_get('all_page_ids', 'posts'); if ( ! is_array( $page_ids ) ) { $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'"); wp_cache_add('all_page_ids', $page_ids, 'posts'); } return $page_ids; } /** * Retrieves page data given a page ID or page object. * * Use get_post() instead of get_page(). * * @since 1.5.1 * @deprecated 3.5.0 * * @param mixed $page Page object or page ID. Passed by reference. * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N. * @param string $filter How the return value should be filtered. * @return WP_Post|null WP_Post on success or null on failure */ function get_page( $page, $output = OBJECT, $filter = 'raw') { return get_post( $page, $output, $filter ); } /** * Retrieves a page given its path. * * @since 2.1.0 * @uses $wpdb * * @param string $page_path Page path * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT. * @param string $post_type Optional. Post type. Default page. * @return WP_Post|null WP_Post on success or null on failure */ function get_page_by_path($page_path, $output = OBJECT, $post_type = 'page') { global $wpdb; $page_path = rawurlencode(urldecode($page_path)); $page_path = str_replace('%2F', '/', $page_path); $page_path = str_replace('%20', ' ', $page_path); $parts = explode( '/', trim( $page_path, '/' ) ); $parts = esc_sql( $parts ); $parts = array_map( 'sanitize_title_for_query', $parts ); $in_string = "'". implode( "','", $parts ) . "'"; $post_type_sql = esc_sql( $post_type ); $pages = $wpdb->get_results( "SELECT ID, post_name, post_parent, post_type FROM $wpdb->posts WHERE post_name IN ($in_string) AND (post_type = '$post_type_sql' OR post_type = 'attachment')", OBJECT_K ); $revparts = array_reverse( $parts ); $foundid = 0; foreach ( (array) $pages as $page ) { if ( $page->post_name == $revparts[0] ) { $count = 0; $p = $page; while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) { $count++; $parent = $pages[ $p->post_parent ]; if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] ) break; $p = $parent; } if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) { $foundid = $page->ID; if ( $page->post_type == $post_type ) break; } } } if ( $foundid ) return get_post( $foundid, $output ); return null; } /** * Retrieve a page given its title. * * @since 2.1.0 * @uses $wpdb * * @param string $page_title Page title * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT. * @param string $post_type Optional. Post type. Default page. * @return WP_Post|null WP_Post on success or null on failure */ function get_page_by_title($page_title, $output = OBJECT, $post_type = 'page' ) { global $wpdb; $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $page_title, $post_type ) ); if ( $page ) return get_post( $page, $output ); return null; } /** * Retrieve child pages from list of pages matching page ID. * * Matches against the pages parameter against the page ID. Also matches all * children for the same to retrieve all children of a page. Does not make any * SQL queries to get the children. * * @since 1.5.1 * * @param int $page_id Page ID. * @param array $pages List of pages' objects. * @return array */ function get_page_children($page_id, $pages) { $page_list = array(); foreach ( (array) $pages as $page ) { if ( $page->post_parent == $page_id ) { $page_list[] = $page; if ( $children = get_page_children($page->ID, $pages) ) $page_list = array_merge($page_list, $children); } } return $page_list; } /** * Order the pages with children under parents in a flat list. * * It uses auxiliary structure to hold parent-children relationships and * runs in O(N) complexity * * @since 2.0.0 * * @param array $pages Posts array. * @param int $page_id Parent page ID. * @return array A list arranged by hierarchy. Children immediately follow their parents. */ function get_page_hierarchy( &$pages, $page_id = 0 ) { if ( empty( $pages ) ) { $result = array(); return $result; } $children = array(); foreach ( (array) $pages as $p ) { $parent_id = intval( $p->post_parent ); $children[ $parent_id ][] = $p; } $result = array(); _page_traverse_name( $page_id, $children, $result ); return $result; } /** * function to traverse and return all the nested children post names of a root page. * $children contains parent-children relations * * @since 2.9.0 */ function _page_traverse_name( $page_id, &$children, &$result ){ if ( isset( $children[ $page_id ] ) ){ foreach( (array)$children[ $page_id ] as $child ) { $result[ $child->ID ] = $child->post_name; _page_traverse_name( $child->ID, $children, $result ); } } } /** * Builds URI for a page. * * Sub pages will be in the "directory" under the parent page post name. * * @since 1.5.0 * * @param mixed $page Page object or page ID. * @return string Page URI. */ function get_page_uri($page) { $page = get_post( $page ); $uri = $page->post_name; foreach ( $page->ancestors as $parent ) { $uri = get_post( $parent )->post_name . "/" . $uri; } return $uri; } /** * Retrieve a list of pages. * * The defaults that can be overridden are the following: 'child_of', * 'sort_order', 'sort_column', 'post_title', 'hierarchical', 'exclude', * 'include', 'meta_key', 'meta_value','authors', 'number', and 'offset'. * * @since 1.5.0 * @uses $wpdb * * @param mixed $args Optional. Array or string of options that overrides defaults. * @return array List of pages matching defaults or $args */ function get_pages($args = '') { global $wpdb; $pages = false; $defaults = array( 'child_of' => 0, 'sort_order' => 'ASC', 'sort_column' => 'post_title', 'hierarchical' => 1, 'exclude' => array(), 'include' => array(), 'meta_key' => '', 'meta_value' => '', 'authors' => '', 'parent' => -1, 'exclude_tree' => '', 'number' => '', 'offset' => 0, 'post_type' => 'page', 'post_status' => 'publish', ); $r = wp_parse_args( $args, $defaults ); extract( $r, EXTR_SKIP ); $number = (int) $number; $offset = (int) $offset; // Make sure the post type is hierarchical $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) ); if ( !in_array( $post_type, $hierarchical_post_types ) ) return $pages; // Make sure we have a valid post status if ( !is_array( $post_status ) ) $post_status = explode( ',', $post_status ); if ( array_diff( $post_status, get_post_stati() ) ) return $pages; // $args can be whatever, only use the args defined in defaults to compute the key $key = md5( serialize( compact(array_keys($defaults)) ) ); $last_changed = wp_cache_get( 'last_changed', 'posts' ); if ( ! $last_changed ) { $last_changed = microtime(); wp_cache_set( 'last_changed', $last_changed, 'posts' ); } $cache_key = "get_pages:$key:$last_changed"; if ( $cache = wp_cache_get( $cache_key, 'posts' ) ) { // Convert to WP_Post instances $pages = array_map( 'get_post', $cache ); $pages = apply_filters('get_pages', $pages, $r); return $pages; } if ( !is_array($cache) ) $cache = array(); $inclusions = ''; if ( !empty($include) ) { $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include $parent = -1; $exclude = ''; $meta_key = ''; $meta_value = ''; $hierarchical = false; $incpages = wp_parse_id_list( $include ); if ( ! empty( $incpages ) ) { foreach ( $incpages as $incpage ) { if (empty($inclusions)) $inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage); else $inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage); } } } if (!empty($inclusions)) $inclusions .= ')'; $exclusions = ''; if ( !empty($exclude) ) { $expages = wp_parse_id_list( $exclude ); if ( ! empty( $expages ) ) { foreach ( $expages as $expage ) { if (empty($exclusions)) $exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage); else $exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage); } } } if (!empty($exclusions)) $exclusions .= ')'; $author_query = ''; if (!empty($authors)) { $post_authors = preg_split('/[\s,]+/',$authors); if ( ! empty( $post_authors ) ) { foreach ( $post_authors as $post_author ) { //Do we have an author id or an author login? if ( 0 == intval($post_author) ) { $post_author = get_user_by('login', $post_author); if ( empty($post_author) ) continue; if ( empty($post_author->ID) ) continue; $post_author = $post_author->ID; } if ( '' == $author_query ) $author_query = $wpdb->prepare(' post_author = %d ', $post_author); else $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author); } if ( '' != $author_query ) $author_query = " AND ($author_query)"; } } $join = ''; $where = "$exclusions $inclusions "; if ( '' !== $meta_key || '' !== $meta_value ) { $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )"; // meta_key and meta_value might be slashed $meta_key = wp_unslash($meta_key); $meta_value = wp_unslash($meta_value); if ( '' !== $meta_key ) $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key); if ( '' !== $meta_value ) $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value); } if ( $parent >= 0 ) $where .= $wpdb->prepare(' AND post_parent = %d ', $parent); if ( 1 == count( $post_status ) ) { $where_post_type = $wpdb->prepare( "post_type = %s AND post_status = %s", $post_type, array_shift( $post_status ) ); } else { $post_status = implode( "', '", $post_status ); $where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $post_type ); } $orderby_array = array(); $allowed_keys = array('author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified', 'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent', 'ID', 'rand', 'comment_count'); foreach ( explode( ',', $sort_column ) as $orderby ) { $orderby = trim( $orderby ); if ( !in_array( $orderby, $allowed_keys ) ) continue; switch ( $orderby ) { case 'menu_order': break; case 'ID': $orderby = "$wpdb->posts.ID"; break; case 'rand': $orderby = 'RAND()'; break; case 'comment_count': $orderby = "$wpdb->posts.comment_count"; break; default: if ( 0 === strpos( $orderby, 'post_' ) ) $orderby = "$wpdb->posts." . $orderby; else $orderby = "$wpdb->posts.post_" . $orderby; } $orderby_array[] = $orderby; } $sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title"; $sort_order = strtoupper( $sort_order ); if ( '' !== $sort_order && !in_array( $sort_order, array( 'ASC', 'DESC' ) ) ) $sort_order = 'ASC'; $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where "; $query .= $author_query; $query .= " ORDER BY " . $sort_column . " " . $sort_order ; if ( !empty($number) ) $query .= ' LIMIT ' . $offset . ',' . $number; $pages = $wpdb->get_results($query); if ( empty($pages) ) { $pages = apply_filters('get_pages', array(), $r); return $pages; } // Sanitize before caching so it'll only get done once $num_pages = count($pages); for ($i = 0; $i < $num_pages; $i++) { $pages[$i] = sanitize_post($pages[$i], 'raw'); } // Update cache. update_post_cache( $pages ); if ( $child_of || $hierarchical ) $pages = get_page_children($child_of, $pages); if ( !empty($exclude_tree) ) { $exclude = (int) $exclude_tree; $children = get_page_children($exclude, $pages); $excludes = array(); foreach ( $children as $child ) $excludes[] = $child->ID; $excludes[] = $exclude; $num_pages = count($pages); for ( $i = 0; $i < $num_pages; $i++ ) { if ( in_array($pages[$i]->ID, $excludes) ) unset($pages[$i]); } } $page_structure = array(); foreach ( $pages as $page ) $page_structure[] = $page->ID; wp_cache_set( $cache_key, $page_structure, 'posts' ); // Convert to WP_Post instances $pages = array_map( 'get_post', $pages ); $pages = apply_filters('get_pages', $pages, $r); return $pages; } // // Attachment functions // /** * Check if the attachment URI is local one and is really an attachment. * * @since 2.0.0 * * @param string $url URL to check * @return bool True on success, false on failure. */ function is_local_attachment($url) { if (strpos($url, home_url()) === false) return false; if (strpos($url, home_url('/?attachment_id=')) !== false) return true; if ( $id = url_to_postid($url) ) { $post = get_post($id); if ( 'attachment' == $post->post_type ) return true; } return false; } /** * Insert an attachment. * * If you set the 'ID' in the $object parameter, it will mean that you are * updating and attempt to update the attachment. You can also set the * attachment name or title by setting the key 'post_name' or 'post_title'. * * You can set the dates for the attachment manually by setting the 'post_date' * and 'post_date_gmt' keys' values. * * By default, the comments will use the default settings for whether the * comments are allowed. You can close them manually or keep them open by * setting the value for the 'comment_status' key. * * The $object parameter can have the following: * 'post_status' - Default is 'draft'. Can not be overridden, set the same as parent post. * 'post_type' - Default is 'post', will be set to attachment. Can not override. * 'post_author' - Default is current user ID. The ID of the user, who added the attachment. * 'ping_status' - Default is the value in default ping status option. Whether the attachment * can accept pings. * 'post_parent' - Default is 0. Can use $parent parameter or set this for the post it belongs * to, if any. * 'menu_order' - Default is 0. The order it is displayed. * 'to_ping' - Whether to ping. * 'pinged' - Default is empty string. * 'post_password' - Default is empty string. The password to access the attachment. * 'guid' - Global Unique ID for referencing the attachment. * 'post_content_filtered' - Attachment post content filtered. * 'post_excerpt' - Attachment excerpt. * * @since 2.0.0 * @uses $wpdb * @uses $user_ID * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update. * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update. * * @param string|array $object Arguments to override defaults. * @param string $file Optional filename. * @param int $parent Parent post ID. * @return int Attachment ID. */ function wp_insert_attachment($object, $file = false, $parent = 0) { global $wpdb, $user_ID; $defaults = array('post_status' => 'inherit', 'post_type' => 'post', 'post_author' => $user_ID, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'post_title' => '', 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'context' => ''); $object = wp_parse_args($object, $defaults); if ( !empty($parent) ) $object['post_parent'] = $parent; unset( $object[ 'filter' ] ); $object = sanitize_post($object, 'db'); // export array as variables extract($object, EXTR_SKIP); if ( empty($post_author) ) $post_author = $user_ID; $post_type = 'attachment'; if ( ! in_array( $post_status, array( 'inherit', 'private' ) ) ) $post_status = 'inherit'; if ( !empty($post_category) ) $post_category = array_filter($post_category); // Filter out empty terms // Make sure we set a valid category. if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) { $post_category = array(); } // Are we updating or creating? if ( !empty($ID) ) { $update = true; $post_ID = (int) $ID; } else { $update = false; $post_ID = 0; } // Create a valid post name. if ( empty($post_name) ) $post_name = sanitize_title($post_title); else $post_name = sanitize_title($post_name); // expected_slashed ($post_name) $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent); if ( empty($post_date) ) $post_date = current_time('mysql'); if ( empty($post_date_gmt) ) $post_date_gmt = current_time('mysql', 1); if ( empty($post_modified) ) $post_modified = $post_date; if ( empty($post_modified_gmt) ) $post_modified_gmt = $post_date_gmt; if ( empty($comment_status) ) { if ( $update ) $comment_status = 'closed'; else $comment_status = get_option('default_comment_status'); } if ( empty($ping_status) ) $ping_status = get_option('default_ping_status'); if ( isset($to_ping) ) $to_ping = preg_replace('|\s+|', "\n", $to_ping); else $to_ping = ''; if ( isset($post_parent) ) $post_parent = (int) $post_parent; else $post_parent = 0; if ( isset($menu_order) ) $menu_order = (int) $menu_order; else $menu_order = 0; if ( !isset($post_password) ) $post_password = ''; if ( ! isset($pinged) ) $pinged = ''; // expected_slashed (everything!) $data = compact( array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid' ) ); $data = wp_unslash( $data ); if ( $update ) { $wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) ); } else { // If there is a suggested ID, use it if not already present if ( !empty($import_id) ) { $import_id = (int) $import_id; if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) { $data['ID'] = $import_id; } } $wpdb->insert( $wpdb->posts, $data ); $post_ID = (int) $wpdb->insert_id; } if ( empty($post_name) ) { $post_name = sanitize_title($post_title, $post_ID); $wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) ); } if ( is_object_in_taxonomy($post_type, 'category') ) wp_set_post_categories( $post_ID, $post_category ); if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') ) wp_set_post_tags( $post_ID, $tags_input ); // support for all custom taxonomies if ( !empty($tax_input) ) { foreach ( $tax_input as $taxonomy => $tags ) { $taxonomy_obj = get_taxonomy($taxonomy); if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical. $tags = array_filter($tags); if ( current_user_can($taxonomy_obj->cap->assign_terms) ) wp_set_post_terms( $post_ID, $tags, $taxonomy ); } } if ( $file ) update_attached_file( $post_ID, $file ); clean_post_cache( $post_ID ); if ( ! empty( $context ) ) add_post_meta( $post_ID, '_wp_attachment_context', $context, true ); if ( $update) { do_action('edit_attachment', $post_ID); } else { do_action('add_attachment', $post_ID); } return $post_ID; } /** * Trashes or deletes an attachment. * * When an attachment is permanently deleted, the file will also be removed. * Deletion removes all post meta fields, taxonomy, comments, etc. associated * with the attachment (except the main post). * * The attachment is moved to the trash instead of permanently deleted unless trash * for media is disabled, item is already in the trash, or $force_delete is true. * * @since 2.0.0 * @uses $wpdb * @uses do_action() Calls 'delete_attachment' hook on Attachment ID. * * @param int $post_id Attachment ID. * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false. * @return mixed False on failure. Post data on success. */ function wp_delete_attachment( $post_id, $force_delete = false ) { global $wpdb; if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) ) return $post; if ( 'attachment' != $post->post_type ) return false; if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status ) return wp_trash_post( $post_id ); delete_post_meta($post_id, '_wp_trash_meta_status'); delete_post_meta($post_id, '_wp_trash_meta_time'); $meta = wp_get_attachment_metadata( $post_id ); $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true ); $file = get_attached_file( $post_id ); $intermediate_sizes = array(); foreach ( get_intermediate_image_sizes() as $size ) { if ( $intermediate = image_get_intermediate_size( $post_id, $size ) ) $intermediate_sizes[] = $intermediate; } if ( is_multisite() ) delete_transient( 'dirsize_cache' ); do_action('delete_attachment', $post_id); wp_delete_object_term_relationships($post_id, array('category', 'post_tag')); wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type)); delete_metadata( 'post', null, '_thumbnail_id', $post_id, true ); // delete all for any posts. $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id )); foreach ( $comment_ids as $comment_id ) wp_delete_comment( $comment_id, true ); $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id )); foreach ( $post_meta_ids as $mid ) delete_metadata_by_mid( 'post', $mid ); do_action( 'delete_post', $post_id ); $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) ); do_action( 'deleted_post', $post_id ); $uploadpath = wp_upload_dir(); if ( ! empty($meta['thumb']) ) { // Don't delete the thumb if another attachment uses it if (! $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $meta['thumb'] . '%', $post_id)) ) { $thumbfile = str_replace(basename($file), $meta['thumb'], $file); $thumbfile = apply_filters('wp_delete_file', $thumbfile); @ unlink( path_join($uploadpath['basedir'], $thumbfile) ); } } // remove intermediate and backup images if there are any foreach ( $intermediate_sizes as $intermediate ) { $intermediate_file = apply_filters( 'wp_delete_file', $intermediate['path'] ); @ unlink( path_join($uploadpath['basedir'], $intermediate_file) ); } if ( is_array($backup_sizes) ) { foreach ( $backup_sizes as $size ) { $del_file = path_join( dirname($meta['file']), $size['file'] ); $del_file = apply_filters('wp_delete_file', $del_file); @ unlink( path_join($uploadpath['basedir'], $del_file) ); } } $file = apply_filters('wp_delete_file', $file); if ( ! empty($file) ) @ unlink($file); clean_post_cache( $post ); return $post; } /** * Retrieve attachment meta field for attachment ID. * * @since 2.1.0 * * @param int $post_id Attachment ID * @param bool $unfiltered Optional, default is false. If true, filters are not run. * @return string|bool Attachment meta field. False on failure. */ function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) { $post_id = (int) $post_id; if ( !$post = get_post( $post_id ) ) return false; $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true ); if ( $unfiltered ) return $data; return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID ); } /** * Update metadata for an attachment. * * @since 2.1.0 * * @param int $post_id Attachment ID. * @param array $data Attachment data. * @return int */ function wp_update_attachment_metadata( $post_id, $data ) { $post_id = (int) $post_id; if ( !$post = get_post( $post_id ) ) return false; if ( $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID ) ) return update_post_meta( $post->ID, '_wp_attachment_metadata', $data ); else return delete_post_meta( $post->ID, '_wp_attachment_metadata' ); } /** * Retrieve the URL for an attachment. * * @since 2.1.0 * * @param int $post_id Attachment ID. * @return string */ function wp_get_attachment_url( $post_id = 0 ) { $post_id = (int) $post_id; if ( !$post = get_post( $post_id ) ) return false; if ( 'attachment' != $post->post_type ) return false; $url = ''; if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location elseif ( false !== strpos($file, 'wp-content/uploads') ) $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 ); else $url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir. } } if ( empty($url) ) //If any of the above options failed, Fallback on the GUID as used pre-2.7, not recommended to rely upon this. $url = get_the_guid( $post->ID ); $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID ); if ( empty( $url ) ) return false; return $url; } /** * Retrieve thumbnail for an attachment. * * @since 2.1.0 * * @param int $post_id Attachment ID. * @return mixed False on failure. Thumbnail file path on success. */ function wp_get_attachment_thumb_file( $post_id = 0 ) { $post_id = (int) $post_id; if ( !$post = get_post( $post_id ) ) return false; if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) ) return false; $file = get_attached_file( $post->ID ); if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) ) return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID ); return false; } /** * Retrieve URL for an attachment thumbnail. * * @since 2.1.0 * * @param int $post_id Attachment ID * @return string|bool False on failure. Thumbnail URL on success. */ function wp_get_attachment_thumb_url( $post_id = 0 ) { $post_id = (int) $post_id; if ( !$post = get_post( $post_id ) ) return false; if ( !$url = wp_get_attachment_url( $post->ID ) ) return false; $sized = image_downsize( $post_id, 'thumbnail' ); if ( $sized ) return $sized[0]; if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) ) return false; $url = str_replace(basename($url), basename($thumb), $url); return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID ); } /** * Check if the attachment is an image. * * @since 2.1.0 * * @param int $post_id Attachment ID * @return bool */ function wp_attachment_is_image( $post_id = 0 ) { $post_id = (int) $post_id; if ( !$post = get_post( $post_id ) ) return false; if ( !$file = get_attached_file( $post->ID ) ) return false; $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false; $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' ); if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) ) return true; return false; } /** * Retrieve the icon for a MIME type. * * @since 2.1.0 * * @param string|int $mime MIME type or attachment ID. * @return string|bool */ function wp_mime_type_icon( $mime = 0 ) { if ( !is_numeric($mime) ) $icon = wp_cache_get("mime_type_icon_$mime"); $post_id = 0; if ( empty($icon) ) { $post_mimes = array(); if ( is_numeric($mime) ) { $mime = (int) $mime; if ( $post = get_post( $mime ) ) { $post_id = (int) $post->ID; $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid); if ( !empty($ext) ) { $post_mimes[] = $ext; if ( $ext_type = wp_ext2type( $ext ) ) $post_mimes[] = $ext_type; } $mime = $post->post_mime_type; } else { $mime = 0; } } else { $post_mimes[] = $mime; } $icon_files = wp_cache_get('icon_files'); if ( !is_array($icon_files) ) { $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' ); $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') ); $dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) ); $icon_files = array(); while ( $dirs ) { $keys = array_keys( $dirs ); $dir = array_shift( $keys ); $uri = array_shift($dirs); if ( $dh = opendir($dir) ) { while ( false !== $file = readdir($dh) ) { $file = basename($file); if ( substr($file, 0, 1) == '.' ) continue; if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) { if ( is_dir("$dir/$file") ) $dirs["$dir/$file"] = "$uri/$file"; continue; } $icon_files["$dir/$file"] = "$uri/$file"; } closedir($dh); } } wp_cache_add( 'icon_files', $icon_files, 'default', 600 ); } // Icon basename - extension = MIME wildcard foreach ( $icon_files as $file => $uri ) $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file]; if ( ! empty($mime) ) { $post_mimes[] = substr($mime, 0, strpos($mime, '/')); $post_mimes[] = substr($mime, strpos($mime, '/') + 1); $post_mimes[] = str_replace('/', '_', $mime); } $matches = wp_match_mime_types(array_keys($types), $post_mimes); $matches['default'] = array('default'); foreach ( $matches as $match => $wilds ) { if ( isset($types[$wilds[0]])) { $icon = $types[$wilds[0]]; if ( !is_numeric($mime) ) wp_cache_add("mime_type_icon_$mime", $icon); break; } } } return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type. } /** * Checked for changed slugs for published post objects and save the old slug. * * The function is used when a post object of any type is updated, * by comparing the current and previous post objects. * * If the slug was changed and not already part of the old slugs then it will be * added to the post meta field ('_wp_old_slug') for storing old slugs for that * post. * * The most logically usage of this function is redirecting changed post objects, so * that those that linked to an changed post will be redirected to the new post. * * @since 2.1.0 * * @param int $post_id Post ID. * @param object $post The Post Object * @param object $post_before The Previous Post Object * @return int Same as $post_id */ function wp_check_for_changed_slugs($post_id, $post, $post_before) { // dont bother if it hasnt changed if ( $post->post_name == $post_before->post_name ) return; // we're only concerned with published, non-hierarchical objects if ( $post->post_status != 'publish' || is_post_type_hierarchical( $post->post_type ) ) return; $old_slugs = (array) get_post_meta($post_id, '_wp_old_slug'); // if we haven't added this old slug before, add it now if ( !empty( $post_before->post_name ) && !in_array($post_before->post_name, $old_slugs) ) add_post_meta($post_id, '_wp_old_slug', $post_before->post_name); // if the new slug was used previously, delete it from the list if ( in_array($post->post_name, $old_slugs) ) delete_post_meta($post_id, '_wp_old_slug', $post->post_name); } /** * Retrieve the private post SQL based on capability. * * This function provides a standardized way to appropriately select on the * post_status of a post type. The function will return a piece of SQL code * that can be added to a WHERE clause; this SQL is constructed to allow all * published posts, and all private posts to which the user has access. * * @since 2.2.0 * * @uses $user_ID * * @param string $post_type currently only supports 'post' or 'page'. * @return string SQL code that can be added to a where clause. */ function get_private_posts_cap_sql( $post_type ) { return get_posts_by_author_sql( $post_type, false ); } /** * Retrieve the post SQL based on capability, author, and type. * * @see get_private_posts_cap_sql() for full description. * * @since 3.0.0 * @param string $post_type Post type. * @param bool $full Optional. Returns a full WHERE statement instead of just an 'andalso' term. * @param int $post_author Optional. Query posts having a single author ID. * @param bool $public_only Optional. Only return public posts. Skips cap checks for $current_user. Default is false. * @return string SQL WHERE code that can be added to a query. */ function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) { global $user_ID, $wpdb; // Private posts $post_type_obj = get_post_type_object( $post_type ); if ( ! $post_type_obj ) return $full ? 'WHERE 1 = 0' : ' 1 = 0 '; // This hook is deprecated. Why you'd want to use it, I dunno. if ( ! $cap = apply_filters( 'pub_priv_sql_capability', '' ) ) $cap = $post_type_obj->cap->read_private_posts; if ( $full ) { if ( null === $post_author ) { $sql = $wpdb->prepare( 'WHERE post_type = %s AND ', $post_type ); } else { $sql = $wpdb->prepare( 'WHERE post_author = %d AND post_type = %s AND ', $post_author, $post_type ); } } else { $sql = ''; } $sql .= "(post_status = 'publish'"; // Only need to check the cap if $public_only is false if ( false === $public_only ) { if ( current_user_can( $cap ) ) { // Does the user have the capability to view private posts? Guess so. $sql .= " OR post_status = 'private'"; } elseif ( is_user_logged_in() ) { // Users can view their own private posts. $id = (int) $user_ID; if ( null === $post_author || ! $full ) { $sql .= " OR post_status = 'private' AND post_author = $id"; } elseif ( $id == (int) $post_author ) { $sql .= " OR post_status = 'private'"; } // else none } // else none } $sql .= ')'; return $sql; } /** * Retrieve the date that the last post was published. * * The server timezone is the default and is the difference between GMT and * server time. The 'blog' value is the date when the last post was posted. The * 'gmt' is when the last post was posted in GMT formatted date. * * @since 0.71 * * @uses apply_filters() Calls 'get_lastpostdate' filter * * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'. * @return string The date of the last post. */ function get_lastpostdate($timezone = 'server') { return apply_filters( 'get_lastpostdate', _get_last_post_time( $timezone, 'date' ), $timezone ); } /** * Retrieve last post modified date depending on timezone. * * The server timezone is the default and is the difference between GMT and * server time. The 'blog' value is just when the last post was modified. The * 'gmt' is when the last post was modified in GMT time. * * @since 1.2.0 * @uses apply_filters() Calls 'get_lastpostmodified' filter * * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'. * @return string The date the post was last modified. */ function get_lastpostmodified($timezone = 'server') { $lastpostmodified = _get_last_post_time( $timezone, 'modified' ); $lastpostdate = get_lastpostdate($timezone); if ( $lastpostdate > $lastpostmodified ) $lastpostmodified = $lastpostdate; return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone ); } /** * Retrieve latest post date data based on timezone. * * @access private * @since 3.1.0 * * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'. * @param string $field Field to check. Can be 'date' or 'modified'. * @return string The date. */ function _get_last_post_time( $timezone, $field ) { global $wpdb; if ( !in_array( $field, array( 'date', 'modified' ) ) ) return false; $timezone = strtolower( $timezone ); $key = "lastpost{$field}:$timezone"; $date = wp_cache_get( $key, 'timeinfo' ); if ( !$date ) { $add_seconds_server = date('Z'); $post_types = get_post_types( array( 'public' => true ) ); array_walk( $post_types, array( &$wpdb, 'escape_by_ref' ) ); $post_types = "'" . implode( "', '", $post_types ) . "'"; switch ( $timezone ) { case 'gmt': $date = $wpdb->get_var("SELECT post_{$field}_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1"); break; case 'blog': $date = $wpdb->get_var("SELECT post_{$field} FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1"); break; case 'server': $date = $wpdb->get_var("SELECT DATE_ADD(post_{$field}_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1"); break; } if ( $date ) wp_cache_set( $key, $date, 'timeinfo' ); } return $date; } /** * Updates posts in cache. * * @package WordPress * @subpackage Cache * @since 1.5.1 * * @param array $posts Array of post objects */ function update_post_cache( &$posts ) { if ( ! $posts ) return; foreach ( $posts as $post ) wp_cache_add( $post->ID, $post, 'posts' ); } /** * Will clean the post in the cache. * * Cleaning means delete from the cache of the post. Will call to clean the term * object cache associated with the post ID. * * This function not run if $_wp_suspend_cache_invalidation is not empty. See * wp_suspend_cache_invalidation(). * * @package WordPress * @subpackage Cache * @since 2.0.0 * * @uses do_action() Calls 'clean_post_cache' on $id before adding children (if any). * * @param int|object $post Post ID or object to remove from the cache */ function clean_post_cache( $post ) { global $_wp_suspend_cache_invalidation, $wpdb; if ( ! empty( $_wp_suspend_cache_invalidation ) ) return; $post = get_post( $post ); if ( empty( $post ) ) return; wp_cache_delete( $post->ID, 'posts' ); wp_cache_delete( $post->ID, 'post_meta' ); clean_object_term_cache( $post->ID, $post->post_type ); wp_cache_delete( 'wp_get_archives', 'general' ); do_action( 'clean_post_cache', $post->ID, $post ); if ( is_post_type_hierarchical( $post->post_type ) ) wp_cache_delete( 'get_pages', 'posts' ); if ( 'page' == $post->post_type ) { wp_cache_delete( 'all_page_ids', 'posts' ); do_action( 'clean_page_cache', $post->ID ); } wp_cache_set( 'last_changed', microtime(), 'posts' ); } /** * Call major cache updating functions for list of Post objects. * * @package WordPress * @subpackage Cache * @since 1.5.0 * * @uses $wpdb * @uses update_post_cache() * @uses update_object_term_cache() * @uses update_postmeta_cache() * * @param array $posts Array of Post objects * @param string $post_type The post type of the posts in $posts. Default is 'post'. * @param bool $update_term_cache Whether to update the term cache. Default is true. * @param bool $update_meta_cache Whether to update the meta cache. Default is true. */ function update_post_caches(&$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true) { // No point in doing all this work if we didn't match any posts. if ( !$posts ) return; update_post_cache($posts); $post_ids = array(); foreach ( $posts as $post ) $post_ids[] = $post->ID; if ( ! $post_type ) $post_type = 'any'; if ( $update_term_cache ) { if ( is_array($post_type) ) { $ptypes = $post_type; } elseif ( 'any' == $post_type ) { // Just use the post_types in the supplied posts. foreach ( $posts as $post ) $ptypes[] = $post->post_type; $ptypes = array_unique($ptypes); } else { $ptypes = array($post_type); } if ( ! empty($ptypes) ) update_object_term_cache($post_ids, $ptypes); } if ( $update_meta_cache ) update_postmeta_cache($post_ids); } /** * Updates metadata cache for list of post IDs. * * Performs SQL query to retrieve the metadata for the post IDs and updates the * metadata cache for the posts. Therefore, the functions, which call this * function, do not need to perform SQL queries on their own. * * @package WordPress * @subpackage Cache * @since 2.1.0 * * @uses $wpdb * * @param array $post_ids List of post IDs. * @return bool|array Returns false if there is nothing to update or an array of metadata. */ function update_postmeta_cache($post_ids) { return update_meta_cache('post', $post_ids); } /** * Will clean the attachment in the cache. * * Cleaning means delete from the cache. Optionally will clean the term * object cache associated with the attachment ID. * * This function will not run if $_wp_suspend_cache_invalidation is not empty. See * wp_suspend_cache_invalidation(). * * @package WordPress * @subpackage Cache * @since 3.0.0 * * @uses do_action() Calls 'clean_attachment_cache' on $id. * * @param int $id The attachment ID in the cache to clean * @param bool $clean_terms optional. Whether to clean terms cache */ function clean_attachment_cache($id, $clean_terms = false) { global $_wp_suspend_cache_invalidation; if ( !empty($_wp_suspend_cache_invalidation) ) return; $id = (int) $id; wp_cache_delete($id, 'posts'); wp_cache_delete($id, 'post_meta'); if ( $clean_terms ) clean_object_term_cache($id, 'attachment'); do_action('clean_attachment_cache', $id); } // // Hooks // /** * Hook for managing future post transitions to published. * * @since 2.3.0 * @access private * @uses $wpdb * @uses do_action() Calls 'private_to_published' on post ID if this is a 'private_to_published' call. * @uses wp_clear_scheduled_hook() with 'publish_future_post' and post ID. * * @param string $new_status New post status * @param string $old_status Previous post status * @param object $post Object type containing the post information */ function _transition_post_status($new_status, $old_status, $post) { global $wpdb; if ( $old_status != 'publish' && $new_status == 'publish' ) { // Reset GUID if transitioning to publish and it is empty if ( '' == get_the_guid($post->ID) ) $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) ); do_action('private_to_published', $post->ID); // Deprecated, use private_to_publish } // If published posts changed clear the lastpostmodified cache if ( 'publish' == $new_status || 'publish' == $old_status) { foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) { wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' ); wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' ); } } // Always clears the hook in case the post status bounced from future to draft. wp_clear_scheduled_hook('publish_future_post', array( $post->ID ) ); } /** * Hook used to schedule publication for a post marked for the future. * * The $post properties used and must exist are 'ID' and 'post_date_gmt'. * * @since 2.3.0 * @access private * * @param int $deprecated Not used. Can be set to null. Never implemented. * Not marked as deprecated with _deprecated_argument() as it conflicts with * wp_transition_post_status() and the default filter for _future_post_hook(). * @param object $post Object type containing the post information */ function _future_post_hook( $deprecated, $post ) { wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) ); wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT') , 'publish_future_post', array( $post->ID ) ); } /** * Hook to schedule pings and enclosures when a post is published. * * @since 2.3.0 * @access private * @uses XMLRPC_REQUEST and WP_IMPORTING constants. * @uses do_action() Calls 'xmlrpc_publish_post' on post ID if XMLRPC_REQUEST is defined. * * @param int $post_id The ID in the database table of the post being published */ function _publish_post_hook($post_id) { if ( defined('XMLRPC_REQUEST') ) do_action('xmlrpc_publish_post', $post_id); if ( defined('WP_IMPORTING') ) return; if ( get_option('default_pingback_flag') ) add_post_meta( $post_id, '_pingme', '1' ); add_post_meta( $post_id, '_encloseme', '1' ); wp_schedule_single_event(time(), 'do_pings'); } /** * Returns the post's parent's post_ID * * @since 3.1.0 * * @param int $post_id * * @return int|bool false on error */ function wp_get_post_parent_id( $post_ID ) { $post = get_post( $post_ID ); if ( !$post || is_wp_error( $post ) ) return false; return (int) $post->post_parent; } /** * Checks the given subset of the post hierarchy for hierarchy loops. * Prevents loops from forming and breaks those that it finds. * * Attached to the wp_insert_post_parent filter. * * @since 3.1.0 * @uses wp_find_hierarchy_loop() * * @param int $post_parent ID of the parent for the post we're checking. * @param int $post_ID ID of the post we're checking. * * @return int The new post_parent for the post. */ function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) { // Nothing fancy here - bail if ( !$post_parent ) return 0; // New post can't cause a loop if ( empty( $post_ID ) ) return $post_parent; // Can't be its own parent if ( $post_parent == $post_ID ) return 0; // Now look for larger loops if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) ) return $post_parent; // No loop // Setting $post_parent to the given value causes a loop if ( isset( $loop[$post_ID] ) ) return 0; // There's a loop, but it doesn't contain $post_ID. Break the loop. foreach ( array_keys( $loop ) as $loop_member ) wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) ); return $post_parent; } /** * Sets a post thumbnail. * * @since 3.1.0 * * @param int|object $post Post ID or object where thumbnail should be attached. * @param int $thumbnail_id Thumbnail to attach. * @return bool True on success, false on failure. */ function set_post_thumbnail( $post, $thumbnail_id ) { $post = get_post( $post ); $thumbnail_id = absint( $thumbnail_id ); if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) { if ( $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) ) return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id ); else return delete_post_meta( $post->ID, '_thumbnail_id' ); } return false; } /** * Removes a post thumbnail. * * @since 3.3.0 * * @param int|object $post Post ID or object where thumbnail should be removed from. * @return bool True on success, false on failure. */ function delete_post_thumbnail( $post ) { $post = get_post( $post ); if ( $post ) return delete_post_meta( $post->ID, '_thumbnail_id' ); return false; } /** * Deletes auto-drafts for new posts that are > 7 days old * * @since 3.4.0 */ function wp_delete_auto_drafts() { global $wpdb; // Cleanup old auto-drafts more than 7 days old $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" ); foreach ( (array) $old_posts as $delete ) wp_delete_post( $delete, true ); // Force delete } /** * Update the custom taxonomies' term counts when a post's status is changed. For example, default posts term counts (for custom taxonomies) don't include private / draft posts. * * @access private * @param string $new_status * @param string $old_status * @param object $post * @since 3.3.0 */ function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) { // Update counts for the post's terms. foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) { $tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) ); wp_update_term_count( $tt_ids, $taxonomy ); } } /** * Adds any posts from the given ids to the cache that do not already exist in cache * * @since 3.4.0 * * @access private * * @param array $post_ids ID list * @param bool $update_term_cache Whether to update the term cache. Default is true. * @param bool $update_meta_cache Whether to update the meta cache. Default is true. */ function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) { global $wpdb; $non_cached_ids = _get_non_cached_ids( $ids, 'posts' ); if ( !empty( $non_cached_ids ) ) { $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", join( ",", $non_cached_ids ) ) ); update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache ); } }
siliconpoetry/ic
wp-includes/post.php
PHP
gpl-2.0
166,082
const u32 MicroCode[] __attribute__ ((aligned (8))) = { 0x7801698,0x7801548,0xa613fc8,0x0000000,0x6800008,0x7c01548,0xa60c018,0x4000658, 0xc7817c0,0x6804049,0x7801b8a,0x48ff28a,0x540328a,0x2009289,0x700024a,0x91832ca, 0xa60c08b,0x780174c,0x7c0178c,0x780178b,0x2c0b30b,0x7c0178b,0x2c0b30b,0x95e128b, 0x740024a,0xaa0c008,0x6800049,0x6800089,0x700024a,0x780000b,0xa8182ca,0x740024b, 0x7800809,0x97082c9,0x78009c9,0x96082c9,0x609c10b,0x40012c8,0x609c00b,0x8007401, 0x649c00b,0xa6fc00b,0x0000000,0x649c10b,0x910828b,0x7c001ca,0x900828b,0x7c0020a, 0x649c20b,0x7c0014b,0x92102cb,0x7c0018b,0xc004100,0x0000000,0x78011c8,0xa630148, 0x7801548,0xa628008,0x6800008,0x7c01c88,0x7c01cc8,0x7c01d08,0xc007bc0,0x0000000, 0x6800008,0x7c000c8,0x7c00108,0xc004000,0x0000000,0xa24200b,0x910820b,0xbe32008, 0x780154b,0xaa0c00b,0x68000cb,0x680010b,0x680004a,0x340a20a,0x6bfffc8,0x300a20a, 0x70002c8,0x2808288,0x74002c8,0xc7eec40,0x809ca07,0x7c01bc9,0x7c01c4a,0x7801548, 0xa62c008,0x900820b,0x7c020c8,0x7800248,0xa60c008,0x6800048,0x7c015c8,0x6800008, 0x7c00248,0x78015c8,0x7c02108,0xc011680,0x0000000,0xc010200,0x0000000,0x7801708, 0xaa08088,0xc780980,0x78011c9,0xaa20149,0x7801189,0xaa18009,0x0000000,0xfc01240, 0xaa0c009,0xc00bb40,0x0000000,0xc070bc0,0x80c2301,0xc070c40,0x0000000,0x401a205, 0x7800ec9,0x2008248,0x7c01b08,0x7800f48,0xaa40008,0x680000a,0xc070900,0x80c2301, 0xaa30045,0x9402285,0xc070800,0x80c2301,0xc070880,0x0000000,0x94c4285,0xc0706c0, 0x80c2301,0xc070740,0x0000000,0x9444285,0x60c310a,0xc7eddc0,0x809ca05,0xaa08148, 0xc781240,0xaa4c019,0xc0074c0,0x7801808,0x7801548,0xaa3c008,0x7802108,0xaa34008, 0x7801588,0xaa0c008,0x7901488,0x7901408,0x6bfffc9,0xa807248,0x7801bc9,0x78020c8, 0x4c80208,0x7400248,0x4001249,0x7c01bc9,0xfc01200,0xaa10008,0x7801a16,0xc00bec0, 0x6808011,0xaa18019,0x6808008,0x7801bca,0x7801a13,0xc009cc0,0x6800012,0x7800e48, 0x4000248,0xaa34008,0x6094209,0xc06fbc0,0x80c2301,0x9484245,0xc06fb00,0x80c2301, 0x9504245,0x6094209,0x680c008,0x6094008,0xc011bc0,0x7801a0a,0x6494008,0x9c08248, 0x6094008,0x7801188,0xaa38008,0x0000000,0x78011c8,0xa61c148,0x0000000,0xfc01200, 0x7c01a88,0xfc01200,0xc780180,0x7c01ac8,0xfc01200,0xaa0c008,0xc00a400,0x0000000, 0x7800d48,0xaa18008,0x6800c09,0xc06f3c0,0x80c2301,0x9402245,0x60c2109,0xc7fe700, 0x0000000,0xaa68019,0xc006d40,0x0000000,0xc007040,0x6808008,0x7c02088,0x7801bc8, 0x4020208,0xc007b80,0x7c01c08,0x7801548,0xaa3c008,0x7802108,0xaa34008,0x7801588, 0xaa0c008,0x7901488,0x7901408,0x6bfffc9,0xa807248,0x7801bc9,0x78020c8,0x4c80208, 0x7400248,0x4001249,0x7c01bc9,0xfc01200,0xaa10008,0x7801a16,0xc00ab00,0x6808011, 0xaa44019,0x7801548,0xaa3c008,0x7802108,0xaa34008,0x7801588,0xaa0c008,0x79014c8, 0x7901448,0x6bfffc9,0xa807248,0x7801c09,0x78020c8,0x4c80208,0x7400248,0x4001249, 0x7c01c09,0xfc01200,0xaa24008,0x7801c08,0x7c01bc8,0x7801a56,0xc00a500,0x6808811, 0x7801c08,0x4420208,0x7c01bc8,0xaa34019,0x6808008,0x7801bca,0x7801a13,0xc008240, 0x6800012,0x6808808,0x7801c0a,0x7801a53,0xc008100,0x6800212,0xc0088c0,0x6808808, 0x7800e88,0xa60c088,0x6800009,0x6815409,0x9402248,0xa644048,0x6094209,0xc06dec0, 0x80c2301,0x9484245,0xc06de00,0x80c2301,0x9504245,0x6094209,0x680c008,0x6094008, 0xc00fec0,0x7801a0a,0x680d808,0x6094008,0xc00fdc0,0x7801a4a,0xc7fe200,0x0000000, 0x7801548,0xaa0c008,0x6804049,0x6806049,0x6800008,0x780020a,0x7400248,0xd07ffca, 0x4008249,0xcc00000,0x0000000,0xc000d40,0x6a0200b,0x649cd09,0xa226009,0x67f2909, 0xa21c049,0xc06eec0,0x0000000,0x67f2609,0x93e1249,0xaaf0009,0x0000000,0x6808009, 0x680900a,0x680000c,0x7801548,0xaa0c008,0x6804048,0x6806048,0x700020d,0xa20c04d, 0x914238d,0xc780240,0xaa0c00e,0xc780300,0x0000000,0xa25200b,0xc000d00,0x94082cc, 0xc780440,0x7c01b8b,0x740028c,0x400128a,0x740024c,0xc780300,0x4001249,0xaa2808e, 0xa61004e,0x904438d,0x740028c,0x400128a,0xaa1400e,0x0000000,0x740024c,0xc780080, 0x4001249,0x780020d,0x440134d,0x4008208,0xb8e234c,0x400130c,0xcc00000,0x0000000, 0x7801188,0xa60c008,0xcc00000,0x980b38b,0x7801548,0xaa0c008,0x68000c8,0x6800108, 0x78009cc,0x400130c,0x7000209,0x680000a,0xa21c049,0x5801249,0xb8fe30a,0x400128a, 0xc780000,0xcc00000,0x0000000,0x95082ca,0x680004c,0x340c28c,0x7000209,0x2c09309, 0xcc00000,0x7400209,0x649c80e,0x93e13ce,0xaa1800f,0x91083ce,0xaa1000f,0x44013cf, 0x950838f,0x609c80e,0x780118e,0xaa1000e,0x680000e,0xc780480,0x7c0214e,0x649c80e, 0x93e13ce,0xa61000f,0x680000e,0xc780300,0x7c0214e,0x780154e,0xa62400e,0x649c80e, 0x91083ce,0xa6e400f,0x90083ce,0x950838f,0x609c80e,0x680004e,0x7c0214e,0x6a0000e, 0x60c3d0e,0x4401388,0x91083cb,0x740038f,0x400138e,0x6810010,0x7801191,0xaa3c011, 0x6bfffd1,0x4c0c410,0x7800151,0x7800192,0x9610452,0xe0003d1,0x7801552,0xaa0c012, 0x649d612,0x649d712,0xf000440,0xf0103c0,0x970844f,0x2011491,0x64c3d0f,0x91613cf, 0xa6f800f,0x0000000,0x60c3811,0x7801891,0x94c2411,0x7400390,0xc009080,0x0000000, 0x7800290,0x69fff8f,0xa81640f,0x780170f,0xa62c08f,0x780154f,0xaa1000f,0x69fffcf, 0xa80e40f,0xc7803c0,0xa80e40f,0x7c00292,0x69fff8f,0xc7802c0,0x7c0028f,0x69fffcf, 0xa80640f,0x91e13d0,0xaa0c00f,0x6c00010,0x6ffffd0,0xb403412,0x680004f,0x7c0214f, 0x4000812,0x7000390,0x780214f,0x952140f,0x780170f,0x958340f,0xb004452,0x9c10210, 0x9810210,0x4000811,0x7400390,0x80c3000,0x60c3220,0x60c3212,0x60c3211,0x7801850, 0xa610090,0x400138e,0xc780180,0x400138e,0x7400392,0x9210492,0x400138e,0x7400392, 0xa610090,0x400138e,0xc780180,0x400138e,0x7400391,0x9210451,0x400138e,0x7400391, 0x400138e,0x7801810,0x7400390,0x6806010,0xb40c40e,0x440638e,0x6804010,0x240e40e, 0x580238e,0x6802bd0,0x200e40e,0x7801210,0x7400390,0x7801250,0x400138e,0x7400390, 0x7801551,0xaa10011,0x900844b,0x7800212,0x2011491,0x5402451,0x649c612,0x2011491, 0x4000491,0x4001451,0x9508491,0x9608491,0x609b212,0x609b012,0x609b112,0x4001411, 0x4002451,0x9508411,0x609dc10,0xcc00000,0x0000000,0x7801548,0xaa0c008,0xcc00000, 0x0000000,0x680000f,0xc000340,0x680400b,0x4000512,0x7800089,0x780000a,0xa405289, 0x680004f,0xc000180,0x680600b,0xa6c8012,0xa6c4014,0xcc00000,0x0000000,0x6800012, 0x6bfffca,0x6dfffca,0x7800213,0x6bfffcd,0x400134d,0xb41b4cd,0x400038d,0x400044e, 0x540338e,0x200e2ce,0x400138e,0x700038c,0xa21004c,0x9c0c00c,0xc7ffd80,0x740038c, 0x914224c,0xa6cc049,0x910130c,0xaa0c00c,0x400138e,0x400238e,0x400130e,0x700038e, 0x700030c,0x961038c,0xb0ea38a,0x0000000,0x6800052,0x400028e,0xc7ff980,0x4000411, 0xaa0c012,0xc00a740,0x0000000,0xcc00000,0x0000000,0x680004c,0x780090b,0x340c2cc, 0x6808009,0x7801bcf,0xb8033c9,0xcc00000,0x0000000,0x780154b,0xaa0c00b,0x680400b, 0x680600b,0x700024a,0x540328a,0x200a2ca,0x400628a,0x700028a,0xb00320a,0x4000349, 0x240a30a,0x400134d,0xb4113cd,0x700034e,0x540338e,0x200e2ce,0x400638e,0x700038e, 0xb00320e,0x0000000,0x240e30e,0xb4f638a,0x0000000,0x400028e,0x700024e,0x7000350, 0x740034e,0xc7ffc00,0x7400250,0x4001249,0xb8e53c9,0xcc00000,0x0000000,0x6808009, 0x7801bca,0x240a24a,0x78009c9,0xac0324a,0xcc00000,0x0000000,0xc07f3c0,0x7801808, 0x6808009,0x78009ca,0x2009289,0xcc00000,0x7c01bc9,0x6808009,0x7801bcf,0x780154b, 0xaa0c00b,0x680400b,0x680600b,0x700024a,0x540328a,0x200a2ca,0x400128a,0x700028c, 0x910130c,0xaa0c00c,0x400128a,0x400228a,0x400130a,0x700028a,0x700030c,0x961028c, 0x4000349,0x400134d,0xb4163cd,0x700034e,0x540338e,0x200e2ce,0x400138e,0x700038c, 0x910130c,0xaa0c00c,0x400138e,0x400238e,0x400130e,0x700038e,0x700030c,0x961038c, 0xb4f138a,0x0000000,0x400028e,0x700024e,0x7000350,0x740034e,0xc7ffac0,0x7400250, 0xb00380a,0x0000000,0x4001208,0x4001249,0xb8d73c9,0xcc00000,0x0000000,0x6808809, 0x680800a,0x7802088,0x4401208,0xb806288,0x700020b,0x740024b,0x4001249,0xc7fff00, 0x4401208,0x7802088,0x7801bca,0xb406288,0x700020b,0x740024b,0x4001249,0xc7fff00, 0x4001208,0x6808009,0x7801bca,0x7802088,0xb406288,0x700020b,0x740024b,0x4001249, 0xc7fff00,0x4001208,0x6808808,0x780208a,0x402028a,0xb406288,0x700020b,0x740024b, 0x4001249,0xc7fff00,0x4001208,0xcc00000,0x0000000,0xa23600e,0x487f38e,0x400040e, 0x54013d0,0x200f40f,0x40103cf,0x60c240f,0x540830c,0x9405310,0x540338e,0x6804010, 0xc7802c0,0x200e40e,0x201044e,0x54013d0,0x200f40f,0x40103cf,0x60c240f,0x540830c, 0x9405310,0x540338e,0x200e34e,0x400138e,0x7000390,0x60c2210,0x90c23d0,0xaa0c0cf, 0x0000000,0x40013cf,0x94a230f,0x400138e,0x700038f,0x400138e,0x7000390,0x96103d0, 0x60c220f,0x400138e,0x700038f,0x400138e,0x7000390,0x96103d0,0xcc00000,0x60c220f, 0x680000b,0x680000c,0x6800011,0x780154d,0xaa1000d,0x680400d,0x680600d,0x7800211, 0xb40d288,0xac0c4cb,0xc07f2c0,0x700020e,0x90023cb,0xa6140cf,0x58023cb,0x200f48f, 0x60c240f,0x60c220c,0x40012cb,0xc7ffd40,0x4001208,0xa2280cb,0x580234b,0x200d48d, 0x60c240d,0x90022cb,0x680010d,0x240b2cd,0x54032cb,0x340c2cc,0x60c220c,0xcc00000, 0x0000000,0x7000208,0x5403208,0x7801549,0xaa0c009,0x6804009,0x6806009,0x2008248, 0x700020f,0x90043cf,0x7800151,0x7800192,0x9610452,0xe0003d1,0x7801552,0xaa0c012, 0x649d612,0x649d712,0xf000440,0xf0103c0,0x970844f,0x2011491,0x5803451,0x4001208, 0x700020f,0x90c23cf,0x97c244f,0x60c3911,0xcc00000,0x0000000,0xc065100,0x80c2301, 0xaa20005,0xae18185,0xa610045,0xc0001c0,0x0000000,0xc7ffe40,0xc780000,0xc780000, 0xcc00000,0x0000000,0xc064e00,0x80c2301,0xa608019,0xcc00000,0x4001205,0x7801809, 0x6800055,0x780090f,0x34153d5,0xb403209,0x2410209,0x2010550,0x7801888,0xb610088, 0x0000000,0x2010250,0x4001410,0x6800009,0x780020f,0x780154b,0xaa0c00b,0x680400b, 0x680600b,0x5403289,0x200a2ca,0x400128a,0x700028c,0xa21034c,0x400528a,0x700028c, 0xa80540c,0x4001249,0xb8f73c9,0xcc00000,0x0000000,0x440528a,0x700028c,0x9c0c0cc, 0x9c0c08c,0x9c0c00c,0x740028c,0x440128a,0x700028c,0x481f30c,0x7801548,0xaa0c008, 0x68000c8,0x6800108,0x680004a,0x340a30a,0x6bfffcc,0x300a30a,0x7000209,0x2809289, 0xcc00000,0x7400209,0x7c02191,0x7801810,0x6bfffd2,0x7801553,0xaa0c013,0x6804013, 0x6806013,0xc063e40,0x80c2301,0xaa400c5,0xae38145,0xa610005,0xc0003c0,0x0000000, 0xc7ffe40,0xa610045,0xc000980,0x0000000,0xc7ffd40,0xa610145,0xc000b40,0x0000000, 0xc7ffc40,0xc780000,0xc780000,0xcc00000,0x0000000,0xc063940,0x80c2301,0xaa5c019, 0x4001205,0x6800055,0x7800909,0x3415255,0xb403210,0x2410210,0x2010550,0x4000510, 0x7802188,0x7801bc9,0xb40c248,0x700020a,0xbe1a00a,0x540328a,0x200a4ca,0x400628a, 0x700028a,0xa80350a,0xc7ffe00,0x4001208,0xc000800,0x0000000,0xcc00000,0x0000000, 0xc063280,0x80c2301,0xaaf0019,0x4001205,0x6800055,0x7800909,0x3415255,0x2010210, 0xb8e7550,0xc7ff980,0x2410550,0xc062fc0,0x80c2301,0xaa34019,0x4001205,0x2012212, 0xa628012,0x7802188,0x7801bc9,0xb407248,0x700020a,0xbe0e00a,0xc7fff40,0x4001208, 0xc000100,0x0000000,0xcc00000,0x0000000,0x7801bcb,0x700020f,0xb00644b,0x440130b, 0x700030c,0x74002cc,0xc7fff00,0x44012cb,0x740044f,0x4001451,0x4000251,0x4000291, 0x780218b,0x200b58b,0x40012cb,0xac072ca,0x700028c,0xa8fe3cc,0x400128a,0x740024c, 0xc7ffec0,0x4001249,0x7801bc9,0x4001249,0xcc00000,0x7c01bc9,0xc780000,0x0000000, 0x780094f,0x460040f,0xc480900,0x780098f,0x6800050,0x34173d0,0x5801597,0x7801c95, 0x7801ccf,0x961054f,0x7801d13,0x7801914,0xb4054d4,0x240f513,0xb80758f,0xc780180, 0x20155d5,0x240f4d4,0xb00358f,0xc780080,0x24155d5,0x40004d4,0x780118f,0xaa1400f, 0x58103d5,0x7c01c95,0x7c01ccf,0x7c01d13,0x7801854,0xaa100d4,0x20124d5,0xc780bc0, 0x4000452,0x780194f,0x7801990,0x96103d0,0xc780a80,0x20113d2,0x780090f,0x6800050, 0x34173d0,0x78011cf,0xa61c14f,0x680000f,0x7c01d4f,0x7c01d8f,0x7c01dcf,0x7c01f8f, 0x7c01fcf,0x7801d56,0x7801d95,0x7801dcf,0x961054f,0x7801814,0xb403594,0x0000000, 0x20155d5,0x780094f,0x460240f,0xc5000c0,0xc780000,0x0000000,0x78011cf,0xa61014f, 0x6800012,0xc780280,0x6800011,0x2013515,0x54014d3,0x780118f,0xa60c00f,0x0000000, 0x44014d3,0x4000493,0x4000453,0x7c01d95,0x58103d5,0x7c01dcf,0xb803452,0x4000412, 0x4000411,0x7c01e10,0x58103d0,0x7c01e4f,0x7c01e92,0x58103d2,0x7c01ecf,0x7c01f11, 0x58103d1,0x7c01f4f,0x7801814,0xcc00000,0x7c01d54,0x7801188,0xaa1c008,0x6808008, 0x78009c9,0x4001249,0x2009209,0x7801bc8,0xb403248,0xcc00000,0x0000000,0x6808009, 0x7801bcf,0x780154b,0xaa0c00b,0x680400b,0x680600b,0x700024a,0x400040a,0x540328a, 0x200a2ca,0x400628a,0x700028a,0x780180c,0xb00530a,0x680004c,0x7800912,0x340c48c, 0x240a30a,0x4000349,0x400134d,0xb4123cd,0x700034e,0x400044e,0x540338e,0x200e2ce, 0x400638e,0x700038e,0x780180c,0xb00530e,0x680004c,0x7800912,0x340c48c,0x240e30e, 0xb0f238a,0x0000000,0x400028e,0xc7ffbc0,0x4000411,0xc000100,0x780154f,0xcc00000, 0x0000000,0xaa0c00f,0x680400b,0x680600b,0x5403390,0x200e2ce,0x400138e,0x700038c, 0xbe0804c,0xa24830c,0x9c0c0cc,0x9c0c08c,0x9c0c00c,0x740038c,0x440138e,0x700038c, 0x481f30c,0xaa0c00f,0x68000c8,0x6800108,0x680004a,0x340a30a,0x6bfffcc,0x300a30a, 0x7000209,0x2809289,0x7400209,0xcc00000,0x0000000,0x6809008,0x78001c9,0x2009209, 0x7801c48,0x2412248,0xb60c052,0xcc00000,0x0000000,0x6809009,0x7801c4f,0x780154b, 0xaa0c00b,0x680400b,0x680600b,0x700024a,0x400040a,0x540328a,0x200a2ca,0x400128a, 0x700028c,0x91424cc,0xa60c053,0xa21804c,0x0000000,0x4001249,0xb8f53c9,0xcc00000, 0x0000000,0x910130c,0xaa0c00c,0x400128a,0x400228a,0x400130a,0x700028a,0x700030c, 0x961028c,0x4000349,0x400134d,0xb4173cd,0x700034e,0x400044e,0x540338e,0x200e2ce, 0x400138e,0x700038c,0x91424cc,0xa6dc053,0xbed804c,0x910130c,0xaa0c00c,0x400138e, 0x400238e,0x400130e,0x700038e,0x700030c,0x961038c,0xb0ed38a,0x0000000,0x400028e, 0xc7ffa80,0x4000411,0xc000100,0x780154f,0xc7ff180,0x4401492,0x6800011,0xaa0c00f, 0x680400b,0x680600b,0x5403390,0x200e2ce,0x400138e,0x700038d,0x400030d,0x980d2cd, 0x9c0d28d,0x9c0d0cd,0x9c0d08d,0x9c0d00d,0x740038d,0xa21c30c,0x980d00d,0x740038d, 0x6800051,0x440138e,0x700038c,0x481f30c,0x94c240f,0x780070b,0x74002d0,0x40012cb, 0x68006cc,0xb80330b,0x0000000,0x68002cb,0x78006cc,0xa40c30b,0x0000000,0x649c70c, 0xaa0c00c,0xc05fd80,0x0000000,0x649c00c,0xaa0c00c,0xc7ffe80,0x0000000,0xc060800, 0x0000000,0xcc00000,0x7c0070b,0x680000b,0x400128a,0xfc01200,0xaa20048,0x680004c, 0x6494208,0x9084208,0x340c20c,0x540830c,0xc780340,0x609410c,0xc05db00,0x80c2301, 0xc05db80,0x0000000,0x4000305,0xc05d9c0,0x80c2301,0xc05da40,0x0000000,0x950914c, 0x6094105,0xfc01200,0xaa24048,0x680004c,0x6494208,0x9104208,0x340c20c,0x540830c, 0x609410c,0xc780600,0x609410c,0xc05d5c0,0x80c2301,0xc05d640,0x0000000,0x4000305, 0xc05d480,0x80c2301,0xc05d500,0x0000000,0x950914c,0x6094105,0xc05d300,0x80c2301, 0xc05d380,0x0000000,0x4000305,0xc05d1c0,0x80c2301,0xc05d240,0x0000000,0x950914c, 0x6094105,0x40012cb,0xb8cb28b,0xcc00000,0x0000000,0x0000000,0x0000000 };
erdoukki/linux-amlogic
drivers/amlogic/amports/m6tvd/ucode/h264_4k2k/h264mmc_linux_single.h
C
gpl-2.0
14,409
<?php # Lifter010: TODO $fields = Request::getArray('fields'); $order = Request::getArray('order'); ?> <tr> <td><?= htmlReady($name) ?> <? if ($required) : ?><span style="color: red; font-size: 1.6em">*</span><? endif ?></td> <td> <input type="text" size="3" name="order[<?= $id ?>]" value="<?= (int) (($order && isset($order[$id])) ? $order[$id] : @$rule['order'][$id]) ?>"> </td> <td> <input type="hidden" name="fields[<?= $id ?>]" value="0" /> <input type="checkbox" name="fields[<?= $id ?>]" value="1" <?= (($fields && isset($fields[$id])) ? $fields[$id] : @$rule['attributes'][$id]) ? 'checked="checked"' : '' ?> /> </td> </tr>
kurvenschubser/studip-hks
app/views/admin/specification/_field.php
PHP
gpl-2.0
730
/* * Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Thunder_Bluff SD%Complete: 100 SDComment: Quest support: 925 SDCategory: Thunder Bluff EndScriptData */ #include "ScriptPCH.h" /*##### # npc_cairne_bloodhoof ######*/ #define SPELL_BERSERKER_CHARGE 16636 #define SPELL_CLEAVE 16044 #define SPELL_MORTAL_STRIKE 16856 #define SPELL_THUNDERCLAP 23931 #define SPELL_UPPERCUT 22916 #define GOSSIP_HCB "I know this is rather silly but a young ward who is a bit shy would like your hoofprint." //TODO: verify abilities/timers class npc_cairne_bloodhoof : public CreatureScript { public: npc_cairne_bloodhoof() : CreatureScript("npc_cairne_bloodhoof") { } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*uiSender*/, uint32 uiAction) { player->PlayerTalkClass->ClearMenus(); if (uiAction == GOSSIP_SENDER_INFO) { player->CastSpell(player, 23123, false); player->SEND_GOSSIP_MENU(7014, creature->GetGUID()); } return true; } bool OnGossipHello(Player* player, Creature* creature) { if (creature->isQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); if (player->GetQuestStatus(925) == QUEST_STATUS_INCOMPLETE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HCB, GOSSIP_SENDER_MAIN, GOSSIP_SENDER_INFO); player->SEND_GOSSIP_MENU(7013, creature->GetGUID()); return true; } CreatureAI* GetAI(Creature* creature) const { return new npc_cairne_bloodhoofAI (creature); } struct npc_cairne_bloodhoofAI : public ScriptedAI { npc_cairne_bloodhoofAI(Creature* c) : ScriptedAI(c) {} uint32 BerserkerCharge_Timer; uint32 Cleave_Timer; uint32 MortalStrike_Timer; uint32 Thunderclap_Timer; uint32 Uppercut_Timer; void Reset() { BerserkerCharge_Timer = 30000; Cleave_Timer = 5000; MortalStrike_Timer = 10000; Thunderclap_Timer = 15000; Uppercut_Timer = 10000; } void EnterCombat(Unit* /*who*/) {} void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (BerserkerCharge_Timer <= diff) { Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0); if (target) DoCast(target, SPELL_BERSERKER_CHARGE); BerserkerCharge_Timer = 25000; } else BerserkerCharge_Timer -= diff; if (Uppercut_Timer <= diff) { DoCast(me->getVictim(), SPELL_UPPERCUT); Uppercut_Timer = 20000; } else Uppercut_Timer -= diff; if (Thunderclap_Timer <= diff) { DoCast(me->getVictim(), SPELL_THUNDERCLAP); Thunderclap_Timer = 15000; } else Thunderclap_Timer -= diff; if (MortalStrike_Timer <= diff) { DoCast(me->getVictim(), SPELL_MORTAL_STRIKE); MortalStrike_Timer = 15000; } else MortalStrike_Timer -= diff; if (Cleave_Timer <= diff) { DoCast(me->getVictim(), SPELL_CLEAVE); Cleave_Timer = 7000; } else Cleave_Timer -= diff; DoMeleeAttackIfReady(); } }; }; void AddSC_thunder_bluff() { new npc_cairne_bloodhoof(); }
InkVisible/Jzy-Blizzlike
src/server/scripts/Kalimdor/thunder_bluff.cpp
C++
gpl-2.0
4,425
/* * Xtensa ISA: * http://www.tensilica.com/products/literature-docs/documentation/xtensa-isa-databook.htm * * Copyright (c) 2011, Max Filippov, Open Source and Linux Lab. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Open Source and Linux Lab nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include "cpu.h" #include "exec/exec-all.h" #include "disas/disas.h" #include "tcg-op.h" #include "qemu/log.h" #include "sysemu/sysemu.h" #include "exec/cpu_ldst.h" #include "exec/helper-proto.h" #include "exec/helper-gen.h" #include "trace-tcg.h" typedef struct DisasContext { const XtensaConfig *config; TranslationBlock *tb; uint32_t pc; uint32_t next_pc; int cring; int ring; uint32_t lbeg; uint32_t lend; TCGv_i32 litbase; int is_jmp; int singlestep_enabled; bool sar_5bit; bool sar_m32_5bit; bool sar_m32_allocated; TCGv_i32 sar_m32; uint32_t ccount_delta; unsigned used_window; bool debug; bool icount; TCGv_i32 next_icount; unsigned cpenable; } DisasContext; static TCGv_ptr cpu_env; static TCGv_i32 cpu_pc; static TCGv_i32 cpu_R[16]; static TCGv_i32 cpu_FR[16]; static TCGv_i32 cpu_SR[256]; static TCGv_i32 cpu_UR[256]; #include "exec/gen-icount.h" typedef struct XtensaReg { const char *name; uint64_t opt_bits; enum { SR_R = 1, SR_W = 2, SR_X = 4, SR_RW = 3, SR_RWX = 7, } access; } XtensaReg; #define XTENSA_REG_ACCESS(regname, opt, acc) { \ .name = (regname), \ .opt_bits = XTENSA_OPTION_BIT(opt), \ .access = (acc), \ } #define XTENSA_REG(regname, opt) XTENSA_REG_ACCESS(regname, opt, SR_RWX) #define XTENSA_REG_BITS_ACCESS(regname, opt, acc) { \ .name = (regname), \ .opt_bits = (opt), \ .access = (acc), \ } #define XTENSA_REG_BITS(regname, opt) \ XTENSA_REG_BITS_ACCESS(regname, opt, SR_RWX) static const XtensaReg sregnames[256] = { [LBEG] = XTENSA_REG("LBEG", XTENSA_OPTION_LOOP), [LEND] = XTENSA_REG("LEND", XTENSA_OPTION_LOOP), [LCOUNT] = XTENSA_REG("LCOUNT", XTENSA_OPTION_LOOP), [SAR] = XTENSA_REG_BITS("SAR", XTENSA_OPTION_ALL), [BR] = XTENSA_REG("BR", XTENSA_OPTION_BOOLEAN), [LITBASE] = XTENSA_REG("LITBASE", XTENSA_OPTION_EXTENDED_L32R), [SCOMPARE1] = XTENSA_REG("SCOMPARE1", XTENSA_OPTION_CONDITIONAL_STORE), [ACCLO] = XTENSA_REG("ACCLO", XTENSA_OPTION_MAC16), [ACCHI] = XTENSA_REG("ACCHI", XTENSA_OPTION_MAC16), [MR] = XTENSA_REG("MR0", XTENSA_OPTION_MAC16), [MR + 1] = XTENSA_REG("MR1", XTENSA_OPTION_MAC16), [MR + 2] = XTENSA_REG("MR2", XTENSA_OPTION_MAC16), [MR + 3] = XTENSA_REG("MR3", XTENSA_OPTION_MAC16), [WINDOW_BASE] = XTENSA_REG("WINDOW_BASE", XTENSA_OPTION_WINDOWED_REGISTER), [WINDOW_START] = XTENSA_REG("WINDOW_START", XTENSA_OPTION_WINDOWED_REGISTER), [PTEVADDR] = XTENSA_REG("PTEVADDR", XTENSA_OPTION_MMU), [RASID] = XTENSA_REG("RASID", XTENSA_OPTION_MMU), [ITLBCFG] = XTENSA_REG("ITLBCFG", XTENSA_OPTION_MMU), [DTLBCFG] = XTENSA_REG("DTLBCFG", XTENSA_OPTION_MMU), [IBREAKENABLE] = XTENSA_REG("IBREAKENABLE", XTENSA_OPTION_DEBUG), [CACHEATTR] = XTENSA_REG("CACHEATTR", XTENSA_OPTION_CACHEATTR), [ATOMCTL] = XTENSA_REG("ATOMCTL", XTENSA_OPTION_ATOMCTL), [IBREAKA] = XTENSA_REG("IBREAKA0", XTENSA_OPTION_DEBUG), [IBREAKA + 1] = XTENSA_REG("IBREAKA1", XTENSA_OPTION_DEBUG), [DBREAKA] = XTENSA_REG("DBREAKA0", XTENSA_OPTION_DEBUG), [DBREAKA + 1] = XTENSA_REG("DBREAKA1", XTENSA_OPTION_DEBUG), [DBREAKC] = XTENSA_REG("DBREAKC0", XTENSA_OPTION_DEBUG), [DBREAKC + 1] = XTENSA_REG("DBREAKC1", XTENSA_OPTION_DEBUG), [CONFIGID0] = XTENSA_REG_BITS_ACCESS("CONFIGID0", XTENSA_OPTION_ALL, SR_R), [EPC1] = XTENSA_REG("EPC1", XTENSA_OPTION_EXCEPTION), [EPC1 + 1] = XTENSA_REG("EPC2", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EPC1 + 2] = XTENSA_REG("EPC3", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EPC1 + 3] = XTENSA_REG("EPC4", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EPC1 + 4] = XTENSA_REG("EPC5", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EPC1 + 5] = XTENSA_REG("EPC6", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EPC1 + 6] = XTENSA_REG("EPC7", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [DEPC] = XTENSA_REG("DEPC", XTENSA_OPTION_EXCEPTION), [EPS2] = XTENSA_REG("EPS2", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EPS2 + 1] = XTENSA_REG("EPS3", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EPS2 + 2] = XTENSA_REG("EPS4", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EPS2 + 3] = XTENSA_REG("EPS5", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EPS2 + 4] = XTENSA_REG("EPS6", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EPS2 + 5] = XTENSA_REG("EPS7", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [CONFIGID1] = XTENSA_REG_BITS_ACCESS("CONFIGID1", XTENSA_OPTION_ALL, SR_R), [EXCSAVE1] = XTENSA_REG("EXCSAVE1", XTENSA_OPTION_EXCEPTION), [EXCSAVE1 + 1] = XTENSA_REG("EXCSAVE2", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EXCSAVE1 + 2] = XTENSA_REG("EXCSAVE3", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EXCSAVE1 + 3] = XTENSA_REG("EXCSAVE4", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EXCSAVE1 + 4] = XTENSA_REG("EXCSAVE5", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EXCSAVE1 + 5] = XTENSA_REG("EXCSAVE6", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [EXCSAVE1 + 6] = XTENSA_REG("EXCSAVE7", XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT), [CPENABLE] = XTENSA_REG("CPENABLE", XTENSA_OPTION_COPROCESSOR), [INTSET] = XTENSA_REG_ACCESS("INTSET", XTENSA_OPTION_INTERRUPT, SR_RW), [INTCLEAR] = XTENSA_REG_ACCESS("INTCLEAR", XTENSA_OPTION_INTERRUPT, SR_W), [INTENABLE] = XTENSA_REG("INTENABLE", XTENSA_OPTION_INTERRUPT), [PS] = XTENSA_REG_BITS("PS", XTENSA_OPTION_ALL), [VECBASE] = XTENSA_REG("VECBASE", XTENSA_OPTION_RELOCATABLE_VECTOR), [EXCCAUSE] = XTENSA_REG("EXCCAUSE", XTENSA_OPTION_EXCEPTION), [DEBUGCAUSE] = XTENSA_REG_ACCESS("DEBUGCAUSE", XTENSA_OPTION_DEBUG, SR_R), [CCOUNT] = XTENSA_REG("CCOUNT", XTENSA_OPTION_TIMER_INTERRUPT), [PRID] = XTENSA_REG_ACCESS("PRID", XTENSA_OPTION_PROCESSOR_ID, SR_R), [ICOUNT] = XTENSA_REG("ICOUNT", XTENSA_OPTION_DEBUG), [ICOUNTLEVEL] = XTENSA_REG("ICOUNTLEVEL", XTENSA_OPTION_DEBUG), [EXCVADDR] = XTENSA_REG("EXCVADDR", XTENSA_OPTION_EXCEPTION), [CCOMPARE] = XTENSA_REG("CCOMPARE0", XTENSA_OPTION_TIMER_INTERRUPT), [CCOMPARE + 1] = XTENSA_REG("CCOMPARE1", XTENSA_OPTION_TIMER_INTERRUPT), [CCOMPARE + 2] = XTENSA_REG("CCOMPARE2", XTENSA_OPTION_TIMER_INTERRUPT), [MISC] = XTENSA_REG("MISC0", XTENSA_OPTION_MISC_SR), [MISC + 1] = XTENSA_REG("MISC1", XTENSA_OPTION_MISC_SR), [MISC + 2] = XTENSA_REG("MISC2", XTENSA_OPTION_MISC_SR), [MISC + 3] = XTENSA_REG("MISC3", XTENSA_OPTION_MISC_SR), }; static const XtensaReg uregnames[256] = { [THREADPTR] = XTENSA_REG("THREADPTR", XTENSA_OPTION_THREAD_POINTER), [FCR] = XTENSA_REG("FCR", XTENSA_OPTION_FP_COPROCESSOR), [FSR] = XTENSA_REG("FSR", XTENSA_OPTION_FP_COPROCESSOR), }; void xtensa_translate_init(void) { static const char * const regnames[] = { "ar0", "ar1", "ar2", "ar3", "ar4", "ar5", "ar6", "ar7", "ar8", "ar9", "ar10", "ar11", "ar12", "ar13", "ar14", "ar15", }; static const char * const fregnames[] = { "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15", }; int i; cpu_env = tcg_global_reg_new_ptr(TCG_AREG0, "env"); cpu_pc = tcg_global_mem_new_i32(TCG_AREG0, offsetof(CPUXtensaState, pc), "pc"); for (i = 0; i < 16; i++) { cpu_R[i] = tcg_global_mem_new_i32(TCG_AREG0, offsetof(CPUXtensaState, regs[i]), regnames[i]); } for (i = 0; i < 16; i++) { cpu_FR[i] = tcg_global_mem_new_i32(TCG_AREG0, offsetof(CPUXtensaState, fregs[i]), fregnames[i]); } for (i = 0; i < 256; ++i) { if (sregnames[i].name) { cpu_SR[i] = tcg_global_mem_new_i32(TCG_AREG0, offsetof(CPUXtensaState, sregs[i]), sregnames[i].name); } } for (i = 0; i < 256; ++i) { if (uregnames[i].name) { cpu_UR[i] = tcg_global_mem_new_i32(TCG_AREG0, offsetof(CPUXtensaState, uregs[i]), uregnames[i].name); } } } static inline bool option_bits_enabled(DisasContext *dc, uint64_t opt) { return xtensa_option_bits_enabled(dc->config, opt); } static inline bool option_enabled(DisasContext *dc, int opt) { return xtensa_option_enabled(dc->config, opt); } static void init_litbase(DisasContext *dc) { if (dc->tb->flags & XTENSA_TBFLAG_LITBASE) { dc->litbase = tcg_temp_local_new_i32(); tcg_gen_andi_i32(dc->litbase, cpu_SR[LITBASE], 0xfffff000); } } static void reset_litbase(DisasContext *dc) { if (dc->tb->flags & XTENSA_TBFLAG_LITBASE) { tcg_temp_free(dc->litbase); } } static void init_sar_tracker(DisasContext *dc) { dc->sar_5bit = false; dc->sar_m32_5bit = false; dc->sar_m32_allocated = false; } static void reset_sar_tracker(DisasContext *dc) { if (dc->sar_m32_allocated) { tcg_temp_free(dc->sar_m32); } } static void gen_right_shift_sar(DisasContext *dc, TCGv_i32 sa) { tcg_gen_andi_i32(cpu_SR[SAR], sa, 0x1f); if (dc->sar_m32_5bit) { tcg_gen_discard_i32(dc->sar_m32); } dc->sar_5bit = true; dc->sar_m32_5bit = false; } static void gen_left_shift_sar(DisasContext *dc, TCGv_i32 sa) { TCGv_i32 tmp = tcg_const_i32(32); if (!dc->sar_m32_allocated) { dc->sar_m32 = tcg_temp_local_new_i32(); dc->sar_m32_allocated = true; } tcg_gen_andi_i32(dc->sar_m32, sa, 0x1f); tcg_gen_sub_i32(cpu_SR[SAR], tmp, dc->sar_m32); dc->sar_5bit = false; dc->sar_m32_5bit = true; tcg_temp_free(tmp); } static void gen_advance_ccount_cond(DisasContext *dc) { if (dc->ccount_delta > 0) { TCGv_i32 tmp = tcg_const_i32(dc->ccount_delta); gen_helper_advance_ccount(cpu_env, tmp); tcg_temp_free(tmp); } } static void gen_advance_ccount(DisasContext *dc) { gen_advance_ccount_cond(dc); dc->ccount_delta = 0; } static void reset_used_window(DisasContext *dc) { dc->used_window = 0; } static void gen_exception(DisasContext *dc, int excp) { TCGv_i32 tmp = tcg_const_i32(excp); gen_advance_ccount(dc); gen_helper_exception(cpu_env, tmp); tcg_temp_free(tmp); } static void gen_exception_cause(DisasContext *dc, uint32_t cause) { TCGv_i32 tpc = tcg_const_i32(dc->pc); TCGv_i32 tcause = tcg_const_i32(cause); gen_advance_ccount(dc); gen_helper_exception_cause(cpu_env, tpc, tcause); tcg_temp_free(tpc); tcg_temp_free(tcause); if (cause == ILLEGAL_INSTRUCTION_CAUSE || cause == SYSCALL_CAUSE) { dc->is_jmp = DISAS_UPDATE; } } static void gen_exception_cause_vaddr(DisasContext *dc, uint32_t cause, TCGv_i32 vaddr) { TCGv_i32 tpc = tcg_const_i32(dc->pc); TCGv_i32 tcause = tcg_const_i32(cause); gen_advance_ccount(dc); gen_helper_exception_cause_vaddr(cpu_env, tpc, tcause, vaddr); tcg_temp_free(tpc); tcg_temp_free(tcause); } static void gen_debug_exception(DisasContext *dc, uint32_t cause) { TCGv_i32 tpc = tcg_const_i32(dc->pc); TCGv_i32 tcause = tcg_const_i32(cause); gen_advance_ccount(dc); gen_helper_debug_exception(cpu_env, tpc, tcause); tcg_temp_free(tpc); tcg_temp_free(tcause); if (cause & (DEBUGCAUSE_IB | DEBUGCAUSE_BI | DEBUGCAUSE_BN)) { dc->is_jmp = DISAS_UPDATE; } } static void gen_check_privilege(DisasContext *dc) { if (dc->cring) { gen_exception_cause(dc, PRIVILEGED_CAUSE); dc->is_jmp = DISAS_UPDATE; } } static void gen_check_cpenable(DisasContext *dc, unsigned cp) { if (option_enabled(dc, XTENSA_OPTION_COPROCESSOR) && !(dc->cpenable & (1 << cp))) { gen_exception_cause(dc, COPROCESSOR0_DISABLED + cp); dc->is_jmp = DISAS_UPDATE; } } static void gen_jump_slot(DisasContext *dc, TCGv dest, int slot) { tcg_gen_mov_i32(cpu_pc, dest); gen_advance_ccount(dc); if (dc->icount) { tcg_gen_mov_i32(cpu_SR[ICOUNT], dc->next_icount); } if (dc->singlestep_enabled) { gen_exception(dc, EXCP_DEBUG); } else { if (slot >= 0) { tcg_gen_goto_tb(slot); tcg_gen_exit_tb((uintptr_t)dc->tb + slot); } else { tcg_gen_exit_tb(0); } } dc->is_jmp = DISAS_UPDATE; } static void gen_jump(DisasContext *dc, TCGv dest) { gen_jump_slot(dc, dest, -1); } static void gen_jumpi(DisasContext *dc, uint32_t dest, int slot) { TCGv_i32 tmp = tcg_const_i32(dest); if (((dc->tb->pc ^ dest) & TARGET_PAGE_MASK) != 0) { slot = -1; } gen_jump_slot(dc, tmp, slot); tcg_temp_free(tmp); } static void gen_callw_slot(DisasContext *dc, int callinc, TCGv_i32 dest, int slot) { TCGv_i32 tcallinc = tcg_const_i32(callinc); tcg_gen_deposit_i32(cpu_SR[PS], cpu_SR[PS], tcallinc, PS_CALLINC_SHIFT, PS_CALLINC_LEN); tcg_temp_free(tcallinc); tcg_gen_movi_i32(cpu_R[callinc << 2], (callinc << 30) | (dc->next_pc & 0x3fffffff)); gen_jump_slot(dc, dest, slot); } static void gen_callw(DisasContext *dc, int callinc, TCGv_i32 dest) { gen_callw_slot(dc, callinc, dest, -1); } static void gen_callwi(DisasContext *dc, int callinc, uint32_t dest, int slot) { TCGv_i32 tmp = tcg_const_i32(dest); if (((dc->tb->pc ^ dest) & TARGET_PAGE_MASK) != 0) { slot = -1; } gen_callw_slot(dc, callinc, tmp, slot); tcg_temp_free(tmp); } static bool gen_check_loop_end(DisasContext *dc, int slot) { if (option_enabled(dc, XTENSA_OPTION_LOOP) && !(dc->tb->flags & XTENSA_TBFLAG_EXCM) && dc->next_pc == dc->lend) { int label = gen_new_label(); gen_advance_ccount(dc); tcg_gen_brcondi_i32(TCG_COND_EQ, cpu_SR[LCOUNT], 0, label); tcg_gen_subi_i32(cpu_SR[LCOUNT], cpu_SR[LCOUNT], 1); gen_jumpi(dc, dc->lbeg, slot); gen_set_label(label); gen_jumpi(dc, dc->next_pc, -1); return true; } return false; } static void gen_jumpi_check_loop_end(DisasContext *dc, int slot) { if (!gen_check_loop_end(dc, slot)) { gen_jumpi(dc, dc->next_pc, slot); } } static void gen_brcond(DisasContext *dc, TCGCond cond, TCGv_i32 t0, TCGv_i32 t1, uint32_t offset) { int label = gen_new_label(); gen_advance_ccount(dc); tcg_gen_brcond_i32(cond, t0, t1, label); gen_jumpi_check_loop_end(dc, 0); gen_set_label(label); gen_jumpi(dc, dc->pc + offset, 1); } static void gen_brcondi(DisasContext *dc, TCGCond cond, TCGv_i32 t0, uint32_t t1, uint32_t offset) { TCGv_i32 tmp = tcg_const_i32(t1); gen_brcond(dc, cond, t0, tmp, offset); tcg_temp_free(tmp); } static bool gen_check_sr(DisasContext *dc, uint32_t sr, unsigned access) { if (!xtensa_option_bits_enabled(dc->config, sregnames[sr].opt_bits)) { if (sregnames[sr].name) { qemu_log("SR %s is not configured\n", sregnames[sr].name); } else { qemu_log("SR %d is not implemented\n", sr); } gen_exception_cause(dc, ILLEGAL_INSTRUCTION_CAUSE); return false; } else if (!(sregnames[sr].access & access)) { static const char * const access_text[] = { [SR_R] = "rsr", [SR_W] = "wsr", [SR_X] = "xsr", }; assert(access < ARRAY_SIZE(access_text) && access_text[access]); qemu_log("SR %s is not available for %s\n", sregnames[sr].name, access_text[access]); gen_exception_cause(dc, ILLEGAL_INSTRUCTION_CAUSE); return false; } return true; } static void gen_rsr_ccount(DisasContext *dc, TCGv_i32 d, uint32_t sr) { gen_advance_ccount(dc); tcg_gen_mov_i32(d, cpu_SR[sr]); } static void gen_rsr_ptevaddr(DisasContext *dc, TCGv_i32 d, uint32_t sr) { tcg_gen_shri_i32(d, cpu_SR[EXCVADDR], 10); tcg_gen_or_i32(d, d, cpu_SR[sr]); tcg_gen_andi_i32(d, d, 0xfffffffc); } static void gen_rsr(DisasContext *dc, TCGv_i32 d, uint32_t sr) { static void (* const rsr_handler[256])(DisasContext *dc, TCGv_i32 d, uint32_t sr) = { [CCOUNT] = gen_rsr_ccount, [PTEVADDR] = gen_rsr_ptevaddr, }; if (rsr_handler[sr]) { rsr_handler[sr](dc, d, sr); } else { tcg_gen_mov_i32(d, cpu_SR[sr]); } } static void gen_wsr_lbeg(DisasContext *dc, uint32_t sr, TCGv_i32 s) { gen_helper_wsr_lbeg(cpu_env, s); gen_jumpi_check_loop_end(dc, 0); } static void gen_wsr_lend(DisasContext *dc, uint32_t sr, TCGv_i32 s) { gen_helper_wsr_lend(cpu_env, s); gen_jumpi_check_loop_end(dc, 0); } static void gen_wsr_sar(DisasContext *dc, uint32_t sr, TCGv_i32 s) { tcg_gen_andi_i32(cpu_SR[sr], s, 0x3f); if (dc->sar_m32_5bit) { tcg_gen_discard_i32(dc->sar_m32); } dc->sar_5bit = false; dc->sar_m32_5bit = false; } static void gen_wsr_br(DisasContext *dc, uint32_t sr, TCGv_i32 s) { tcg_gen_andi_i32(cpu_SR[sr], s, 0xffff); } static void gen_wsr_litbase(DisasContext *dc, uint32_t sr, TCGv_i32 s) { tcg_gen_andi_i32(cpu_SR[sr], s, 0xfffff001); /* This can change tb->flags, so exit tb */ gen_jumpi_check_loop_end(dc, -1); } static void gen_wsr_acchi(DisasContext *dc, uint32_t sr, TCGv_i32 s) { tcg_gen_ext8s_i32(cpu_SR[sr], s); } static void gen_wsr_windowbase(DisasContext *dc, uint32_t sr, TCGv_i32 v) { gen_helper_wsr_windowbase(cpu_env, v); reset_used_window(dc); } static void gen_wsr_windowstart(DisasContext *dc, uint32_t sr, TCGv_i32 v) { tcg_gen_andi_i32(cpu_SR[sr], v, (1 << dc->config->nareg / 4) - 1); reset_used_window(dc); } static void gen_wsr_ptevaddr(DisasContext *dc, uint32_t sr, TCGv_i32 v) { tcg_gen_andi_i32(cpu_SR[sr], v, 0xffc00000); } static void gen_wsr_rasid(DisasContext *dc, uint32_t sr, TCGv_i32 v) { gen_helper_wsr_rasid(cpu_env, v); /* This can change tb->flags, so exit tb */ gen_jumpi_check_loop_end(dc, -1); } static void gen_wsr_tlbcfg(DisasContext *dc, uint32_t sr, TCGv_i32 v) { tcg_gen_andi_i32(cpu_SR[sr], v, 0x01130000); } static void gen_wsr_ibreakenable(DisasContext *dc, uint32_t sr, TCGv_i32 v) { gen_helper_wsr_ibreakenable(cpu_env, v); gen_jumpi_check_loop_end(dc, 0); } static void gen_wsr_atomctl(DisasContext *dc, uint32_t sr, TCGv_i32 v) { tcg_gen_andi_i32(cpu_SR[sr], v, 0x3f); } static void gen_wsr_ibreaka(DisasContext *dc, uint32_t sr, TCGv_i32 v) { unsigned id = sr - IBREAKA; if (id < dc->config->nibreak) { TCGv_i32 tmp = tcg_const_i32(id); gen_helper_wsr_ibreaka(cpu_env, tmp, v); tcg_temp_free(tmp); gen_jumpi_check_loop_end(dc, 0); } } static void gen_wsr_dbreaka(DisasContext *dc, uint32_t sr, TCGv_i32 v) { unsigned id = sr - DBREAKA; if (id < dc->config->ndbreak) { TCGv_i32 tmp = tcg_const_i32(id); gen_helper_wsr_dbreaka(cpu_env, tmp, v); tcg_temp_free(tmp); } } static void gen_wsr_dbreakc(DisasContext *dc, uint32_t sr, TCGv_i32 v) { unsigned id = sr - DBREAKC; if (id < dc->config->ndbreak) { TCGv_i32 tmp = tcg_const_i32(id); gen_helper_wsr_dbreakc(cpu_env, tmp, v); tcg_temp_free(tmp); } } static void gen_wsr_cpenable(DisasContext *dc, uint32_t sr, TCGv_i32 v) { tcg_gen_andi_i32(cpu_SR[sr], v, 0xff); /* This can change tb->flags, so exit tb */ gen_jumpi_check_loop_end(dc, -1); } static void gen_wsr_intset(DisasContext *dc, uint32_t sr, TCGv_i32 v) { tcg_gen_andi_i32(cpu_SR[sr], v, dc->config->inttype_mask[INTTYPE_SOFTWARE]); gen_helper_check_interrupts(cpu_env); gen_jumpi_check_loop_end(dc, 0); } static void gen_wsr_intclear(DisasContext *dc, uint32_t sr, TCGv_i32 v) { TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_andi_i32(tmp, v, dc->config->inttype_mask[INTTYPE_EDGE] | dc->config->inttype_mask[INTTYPE_NMI] | dc->config->inttype_mask[INTTYPE_SOFTWARE]); tcg_gen_andc_i32(cpu_SR[INTSET], cpu_SR[INTSET], tmp); tcg_temp_free(tmp); gen_helper_check_interrupts(cpu_env); } static void gen_wsr_intenable(DisasContext *dc, uint32_t sr, TCGv_i32 v) { tcg_gen_mov_i32(cpu_SR[sr], v); gen_helper_check_interrupts(cpu_env); gen_jumpi_check_loop_end(dc, 0); } static void gen_wsr_ps(DisasContext *dc, uint32_t sr, TCGv_i32 v) { uint32_t mask = PS_WOE | PS_CALLINC | PS_OWB | PS_UM | PS_EXCM | PS_INTLEVEL; if (option_enabled(dc, XTENSA_OPTION_MMU)) { mask |= PS_RING; } tcg_gen_andi_i32(cpu_SR[sr], v, mask); reset_used_window(dc); gen_helper_check_interrupts(cpu_env); /* This can change mmu index and tb->flags, so exit tb */ gen_jumpi_check_loop_end(dc, -1); } static void gen_wsr_icount(DisasContext *dc, uint32_t sr, TCGv_i32 v) { if (dc->icount) { tcg_gen_mov_i32(dc->next_icount, v); } else { tcg_gen_mov_i32(cpu_SR[sr], v); } } static void gen_wsr_icountlevel(DisasContext *dc, uint32_t sr, TCGv_i32 v) { tcg_gen_andi_i32(cpu_SR[sr], v, 0xf); /* This can change tb->flags, so exit tb */ gen_jumpi_check_loop_end(dc, -1); } static void gen_wsr_ccompare(DisasContext *dc, uint32_t sr, TCGv_i32 v) { uint32_t id = sr - CCOMPARE; if (id < dc->config->nccompare) { uint32_t int_bit = 1 << dc->config->timerint[id]; gen_advance_ccount(dc); tcg_gen_mov_i32(cpu_SR[sr], v); tcg_gen_andi_i32(cpu_SR[INTSET], cpu_SR[INTSET], ~int_bit); gen_helper_check_interrupts(cpu_env); } } static void gen_wsr(DisasContext *dc, uint32_t sr, TCGv_i32 s) { static void (* const wsr_handler[256])(DisasContext *dc, uint32_t sr, TCGv_i32 v) = { [LBEG] = gen_wsr_lbeg, [LEND] = gen_wsr_lend, [SAR] = gen_wsr_sar, [BR] = gen_wsr_br, [LITBASE] = gen_wsr_litbase, [ACCHI] = gen_wsr_acchi, [WINDOW_BASE] = gen_wsr_windowbase, [WINDOW_START] = gen_wsr_windowstart, [PTEVADDR] = gen_wsr_ptevaddr, [RASID] = gen_wsr_rasid, [ITLBCFG] = gen_wsr_tlbcfg, [DTLBCFG] = gen_wsr_tlbcfg, [IBREAKENABLE] = gen_wsr_ibreakenable, [ATOMCTL] = gen_wsr_atomctl, [IBREAKA] = gen_wsr_ibreaka, [IBREAKA + 1] = gen_wsr_ibreaka, [DBREAKA] = gen_wsr_dbreaka, [DBREAKA + 1] = gen_wsr_dbreaka, [DBREAKC] = gen_wsr_dbreakc, [DBREAKC + 1] = gen_wsr_dbreakc, [CPENABLE] = gen_wsr_cpenable, [INTSET] = gen_wsr_intset, [INTCLEAR] = gen_wsr_intclear, [INTENABLE] = gen_wsr_intenable, [PS] = gen_wsr_ps, [ICOUNT] = gen_wsr_icount, [ICOUNTLEVEL] = gen_wsr_icountlevel, [CCOMPARE] = gen_wsr_ccompare, [CCOMPARE + 1] = gen_wsr_ccompare, [CCOMPARE + 2] = gen_wsr_ccompare, }; if (wsr_handler[sr]) { wsr_handler[sr](dc, sr, s); } else { tcg_gen_mov_i32(cpu_SR[sr], s); } } static void gen_wur(uint32_t ur, TCGv_i32 s) { switch (ur) { case FCR: gen_helper_wur_fcr(cpu_env, s); break; case FSR: tcg_gen_andi_i32(cpu_UR[ur], s, 0xffffff80); break; default: tcg_gen_mov_i32(cpu_UR[ur], s); break; } } static void gen_load_store_alignment(DisasContext *dc, int shift, TCGv_i32 addr, bool no_hw_alignment) { if (!option_enabled(dc, XTENSA_OPTION_UNALIGNED_EXCEPTION)) { tcg_gen_andi_i32(addr, addr, ~0 << shift); } else if (option_enabled(dc, XTENSA_OPTION_HW_ALIGNMENT) && no_hw_alignment) { int label = gen_new_label(); TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_andi_i32(tmp, addr, ~(~0 << shift)); tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, label); gen_exception_cause_vaddr(dc, LOAD_STORE_ALIGNMENT_CAUSE, addr); gen_set_label(label); tcg_temp_free(tmp); } } static void gen_waiti(DisasContext *dc, uint32_t imm4) { TCGv_i32 pc = tcg_const_i32(dc->next_pc); TCGv_i32 intlevel = tcg_const_i32(imm4); gen_advance_ccount(dc); gen_helper_waiti(cpu_env, pc, intlevel); tcg_temp_free(pc); tcg_temp_free(intlevel); } static void gen_window_check1(DisasContext *dc, unsigned r1) { if (dc->tb->flags & XTENSA_TBFLAG_EXCM) { return; } if (option_enabled(dc, XTENSA_OPTION_WINDOWED_REGISTER) && r1 / 4 > dc->used_window) { int label = gen_new_label(); TCGv_i32 ws = tcg_temp_new_i32(); dc->used_window = r1 / 4; tcg_gen_deposit_i32(ws, cpu_SR[WINDOW_START], cpu_SR[WINDOW_START], dc->config->nareg / 4, dc->config->nareg / 4); tcg_gen_shr_i32(ws, ws, cpu_SR[WINDOW_BASE]); tcg_gen_andi_i32(ws, ws, (2 << (r1 / 4)) - 2); tcg_gen_brcondi_i32(TCG_COND_EQ, ws, 0, label); { TCGv_i32 pc = tcg_const_i32(dc->pc); TCGv_i32 w = tcg_const_i32(r1 / 4); gen_advance_ccount_cond(dc); gen_helper_window_check(cpu_env, pc, w); tcg_temp_free(w); tcg_temp_free(pc); } gen_set_label(label); tcg_temp_free(ws); } } static void gen_window_check2(DisasContext *dc, unsigned r1, unsigned r2) { gen_window_check1(dc, r1 > r2 ? r1 : r2); } static void gen_window_check3(DisasContext *dc, unsigned r1, unsigned r2, unsigned r3) { gen_window_check2(dc, r1, r2 > r3 ? r2 : r3); } static TCGv_i32 gen_mac16_m(TCGv_i32 v, bool hi, bool is_unsigned) { TCGv_i32 m = tcg_temp_new_i32(); if (hi) { (is_unsigned ? tcg_gen_shri_i32 : tcg_gen_sari_i32)(m, v, 16); } else { (is_unsigned ? tcg_gen_ext16u_i32 : tcg_gen_ext16s_i32)(m, v); } return m; } static inline unsigned xtensa_op0_insn_len(unsigned op0) { return op0 >= 8 ? 2 : 3; } static void disas_xtensa_insn(CPUXtensaState *env, DisasContext *dc) { #define HAS_OPTION_BITS(opt) do { \ if (!option_bits_enabled(dc, opt)) { \ qemu_log("Option is not enabled %s:%d\n", \ __FILE__, __LINE__); \ goto invalid_opcode; \ } \ } while (0) #define HAS_OPTION(opt) HAS_OPTION_BITS(XTENSA_OPTION_BIT(opt)) #define TBD() qemu_log("TBD(pc = %08x): %s:%d\n", dc->pc, __FILE__, __LINE__) #define RESERVED() do { \ qemu_log("RESERVED(pc = %08x, %02x%02x%02x): %s:%d\n", \ dc->pc, b0, b1, b2, __FILE__, __LINE__); \ goto invalid_opcode; \ } while (0) #ifdef TARGET_WORDS_BIGENDIAN #define OP0 (((b0) & 0xf0) >> 4) #define OP1 (((b2) & 0xf0) >> 4) #define OP2 ((b2) & 0xf) #define RRR_R ((b1) & 0xf) #define RRR_S (((b1) & 0xf0) >> 4) #define RRR_T ((b0) & 0xf) #else #define OP0 (((b0) & 0xf)) #define OP1 (((b2) & 0xf)) #define OP2 (((b2) & 0xf0) >> 4) #define RRR_R (((b1) & 0xf0) >> 4) #define RRR_S (((b1) & 0xf)) #define RRR_T (((b0) & 0xf0) >> 4) #endif #define RRR_X ((RRR_R & 0x4) >> 2) #define RRR_Y ((RRR_T & 0x4) >> 2) #define RRR_W (RRR_R & 0x3) #define RRRN_R RRR_R #define RRRN_S RRR_S #define RRRN_T RRR_T #define RRI4_R RRR_R #define RRI4_S RRR_S #define RRI4_T RRR_T #ifdef TARGET_WORDS_BIGENDIAN #define RRI4_IMM4 ((b2) & 0xf) #else #define RRI4_IMM4 (((b2) & 0xf0) >> 4) #endif #define RRI8_R RRR_R #define RRI8_S RRR_S #define RRI8_T RRR_T #define RRI8_IMM8 (b2) #define RRI8_IMM8_SE ((((b2) & 0x80) ? 0xffffff00 : 0) | RRI8_IMM8) #ifdef TARGET_WORDS_BIGENDIAN #define RI16_IMM16 (((b1) << 8) | (b2)) #else #define RI16_IMM16 (((b2) << 8) | (b1)) #endif #ifdef TARGET_WORDS_BIGENDIAN #define CALL_N (((b0) & 0xc) >> 2) #define CALL_OFFSET ((((b0) & 0x3) << 16) | ((b1) << 8) | (b2)) #else #define CALL_N (((b0) & 0x30) >> 4) #define CALL_OFFSET ((((b0) & 0xc0) >> 6) | ((b1) << 2) | ((b2) << 10)) #endif #define CALL_OFFSET_SE \ (((CALL_OFFSET & 0x20000) ? 0xfffc0000 : 0) | CALL_OFFSET) #define CALLX_N CALL_N #ifdef TARGET_WORDS_BIGENDIAN #define CALLX_M ((b0) & 0x3) #else #define CALLX_M (((b0) & 0xc0) >> 6) #endif #define CALLX_S RRR_S #define BRI12_M CALLX_M #define BRI12_S RRR_S #ifdef TARGET_WORDS_BIGENDIAN #define BRI12_IMM12 ((((b1) & 0xf) << 8) | (b2)) #else #define BRI12_IMM12 ((((b1) & 0xf0) >> 4) | ((b2) << 4)) #endif #define BRI12_IMM12_SE (((BRI12_IMM12 & 0x800) ? 0xfffff000 : 0) | BRI12_IMM12) #define BRI8_M BRI12_M #define BRI8_R RRI8_R #define BRI8_S RRI8_S #define BRI8_IMM8 RRI8_IMM8 #define BRI8_IMM8_SE RRI8_IMM8_SE #define RSR_SR (b1) uint8_t b0 = cpu_ldub_code(env, dc->pc); uint8_t b1 = cpu_ldub_code(env, dc->pc + 1); uint8_t b2 = 0; unsigned len = xtensa_op0_insn_len(OP0); static const uint32_t B4CONST[] = { 0xffffffff, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 16, 32, 64, 128, 256 }; static const uint32_t B4CONSTU[] = { 32768, 65536, 2, 3, 4, 5, 6, 7, 8, 10, 12, 16, 32, 64, 128, 256 }; switch (len) { case 2: HAS_OPTION(XTENSA_OPTION_CODE_DENSITY); break; case 3: b2 = cpu_ldub_code(env, dc->pc + 2); break; default: RESERVED(); } dc->next_pc = dc->pc + len; switch (OP0) { case 0: /*QRST*/ switch (OP1) { case 0: /*RST0*/ switch (OP2) { case 0: /*ST0*/ if ((RRR_R & 0xc) == 0x8) { HAS_OPTION(XTENSA_OPTION_BOOLEAN); } switch (RRR_R) { case 0: /*SNM0*/ switch (CALLX_M) { case 0: /*ILL*/ gen_exception_cause(dc, ILLEGAL_INSTRUCTION_CAUSE); break; case 1: /*reserved*/ RESERVED(); break; case 2: /*JR*/ switch (CALLX_N) { case 0: /*RET*/ case 2: /*JX*/ gen_window_check1(dc, CALLX_S); gen_jump(dc, cpu_R[CALLX_S]); break; case 1: /*RETWw*/ HAS_OPTION(XTENSA_OPTION_WINDOWED_REGISTER); { TCGv_i32 tmp = tcg_const_i32(dc->pc); gen_advance_ccount(dc); gen_helper_retw(tmp, cpu_env, tmp); gen_jump(dc, tmp); tcg_temp_free(tmp); } break; case 3: /*reserved*/ RESERVED(); break; } break; case 3: /*CALLX*/ gen_window_check2(dc, CALLX_S, CALLX_N << 2); switch (CALLX_N) { case 0: /*CALLX0*/ { TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_mov_i32(tmp, cpu_R[CALLX_S]); tcg_gen_movi_i32(cpu_R[0], dc->next_pc); gen_jump(dc, tmp); tcg_temp_free(tmp); } break; case 1: /*CALLX4w*/ case 2: /*CALLX8w*/ case 3: /*CALLX12w*/ HAS_OPTION(XTENSA_OPTION_WINDOWED_REGISTER); { TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_mov_i32(tmp, cpu_R[CALLX_S]); gen_callw(dc, CALLX_N, tmp); tcg_temp_free(tmp); } break; } break; } break; case 1: /*MOVSPw*/ HAS_OPTION(XTENSA_OPTION_WINDOWED_REGISTER); gen_window_check2(dc, RRR_T, RRR_S); { TCGv_i32 pc = tcg_const_i32(dc->pc); gen_advance_ccount(dc); gen_helper_movsp(cpu_env, pc); tcg_gen_mov_i32(cpu_R[RRR_T], cpu_R[RRR_S]); tcg_temp_free(pc); } break; case 2: /*SYNC*/ switch (RRR_T) { case 0: /*ISYNC*/ break; case 1: /*RSYNC*/ break; case 2: /*ESYNC*/ break; case 3: /*DSYNC*/ break; case 8: /*EXCW*/ HAS_OPTION(XTENSA_OPTION_EXCEPTION); break; case 12: /*MEMW*/ break; case 13: /*EXTW*/ break; case 15: /*NOP*/ break; default: /*reserved*/ RESERVED(); break; } break; case 3: /*RFEIx*/ switch (RRR_T) { case 0: /*RFETx*/ HAS_OPTION(XTENSA_OPTION_EXCEPTION); switch (RRR_S) { case 0: /*RFEx*/ gen_check_privilege(dc); tcg_gen_andi_i32(cpu_SR[PS], cpu_SR[PS], ~PS_EXCM); gen_helper_check_interrupts(cpu_env); gen_jump(dc, cpu_SR[EPC1]); break; case 1: /*RFUEx*/ RESERVED(); break; case 2: /*RFDEx*/ gen_check_privilege(dc); gen_jump(dc, cpu_SR[ dc->config->ndepc ? DEPC : EPC1]); break; case 4: /*RFWOw*/ case 5: /*RFWUw*/ HAS_OPTION(XTENSA_OPTION_WINDOWED_REGISTER); gen_check_privilege(dc); { TCGv_i32 tmp = tcg_const_i32(1); tcg_gen_andi_i32( cpu_SR[PS], cpu_SR[PS], ~PS_EXCM); tcg_gen_shl_i32(tmp, tmp, cpu_SR[WINDOW_BASE]); if (RRR_S == 4) { tcg_gen_andc_i32(cpu_SR[WINDOW_START], cpu_SR[WINDOW_START], tmp); } else { tcg_gen_or_i32(cpu_SR[WINDOW_START], cpu_SR[WINDOW_START], tmp); } gen_helper_restore_owb(cpu_env); gen_helper_check_interrupts(cpu_env); gen_jump(dc, cpu_SR[EPC1]); tcg_temp_free(tmp); } break; default: /*reserved*/ RESERVED(); break; } break; case 1: /*RFIx*/ HAS_OPTION(XTENSA_OPTION_HIGH_PRIORITY_INTERRUPT); if (RRR_S >= 2 && RRR_S <= dc->config->nlevel) { gen_check_privilege(dc); tcg_gen_mov_i32(cpu_SR[PS], cpu_SR[EPS2 + RRR_S - 2]); gen_helper_check_interrupts(cpu_env); gen_jump(dc, cpu_SR[EPC1 + RRR_S - 1]); } else { qemu_log("RFI %d is illegal\n", RRR_S); gen_exception_cause(dc, ILLEGAL_INSTRUCTION_CAUSE); } break; case 2: /*RFME*/ TBD(); break; default: /*reserved*/ RESERVED(); break; } break; case 4: /*BREAKx*/ HAS_OPTION(XTENSA_OPTION_DEBUG); if (dc->debug) { gen_debug_exception(dc, DEBUGCAUSE_BI); } break; case 5: /*SYSCALLx*/ HAS_OPTION(XTENSA_OPTION_EXCEPTION); switch (RRR_S) { case 0: /*SYSCALLx*/ gen_exception_cause(dc, SYSCALL_CAUSE); break; case 1: /*SIMCALL*/ if (semihosting_enabled) { gen_check_privilege(dc); gen_helper_simcall(cpu_env); } else { qemu_log("SIMCALL but semihosting is disabled\n"); gen_exception_cause(dc, ILLEGAL_INSTRUCTION_CAUSE); } break; default: RESERVED(); break; } break; case 6: /*RSILx*/ HAS_OPTION(XTENSA_OPTION_INTERRUPT); gen_check_privilege(dc); gen_window_check1(dc, RRR_T); tcg_gen_mov_i32(cpu_R[RRR_T], cpu_SR[PS]); tcg_gen_andi_i32(cpu_SR[PS], cpu_SR[PS], ~PS_INTLEVEL); tcg_gen_ori_i32(cpu_SR[PS], cpu_SR[PS], RRR_S); gen_helper_check_interrupts(cpu_env); gen_jumpi_check_loop_end(dc, 0); break; case 7: /*WAITIx*/ HAS_OPTION(XTENSA_OPTION_INTERRUPT); gen_check_privilege(dc); gen_waiti(dc, RRR_S); break; case 8: /*ANY4p*/ case 9: /*ALL4p*/ case 10: /*ANY8p*/ case 11: /*ALL8p*/ HAS_OPTION(XTENSA_OPTION_BOOLEAN); { const unsigned shift = (RRR_R & 2) ? 8 : 4; TCGv_i32 mask = tcg_const_i32( ((1 << shift) - 1) << RRR_S); TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_and_i32(tmp, cpu_SR[BR], mask); if (RRR_R & 1) { /*ALL*/ tcg_gen_addi_i32(tmp, tmp, 1 << RRR_S); } else { /*ANY*/ tcg_gen_add_i32(tmp, tmp, mask); } tcg_gen_shri_i32(tmp, tmp, RRR_S + shift); tcg_gen_deposit_i32(cpu_SR[BR], cpu_SR[BR], tmp, RRR_T, 1); tcg_temp_free(mask); tcg_temp_free(tmp); } break; default: /*reserved*/ RESERVED(); break; } break; case 1: /*AND*/ gen_window_check3(dc, RRR_R, RRR_S, RRR_T); tcg_gen_and_i32(cpu_R[RRR_R], cpu_R[RRR_S], cpu_R[RRR_T]); break; case 2: /*OR*/ gen_window_check3(dc, RRR_R, RRR_S, RRR_T); tcg_gen_or_i32(cpu_R[RRR_R], cpu_R[RRR_S], cpu_R[RRR_T]); break; case 3: /*XOR*/ gen_window_check3(dc, RRR_R, RRR_S, RRR_T); tcg_gen_xor_i32(cpu_R[RRR_R], cpu_R[RRR_S], cpu_R[RRR_T]); break; case 4: /*ST1*/ switch (RRR_R) { case 0: /*SSR*/ gen_window_check1(dc, RRR_S); gen_right_shift_sar(dc, cpu_R[RRR_S]); break; case 1: /*SSL*/ gen_window_check1(dc, RRR_S); gen_left_shift_sar(dc, cpu_R[RRR_S]); break; case 2: /*SSA8L*/ gen_window_check1(dc, RRR_S); { TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_shli_i32(tmp, cpu_R[RRR_S], 3); gen_right_shift_sar(dc, tmp); tcg_temp_free(tmp); } break; case 3: /*SSA8B*/ gen_window_check1(dc, RRR_S); { TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_shli_i32(tmp, cpu_R[RRR_S], 3); gen_left_shift_sar(dc, tmp); tcg_temp_free(tmp); } break; case 4: /*SSAI*/ { TCGv_i32 tmp = tcg_const_i32( RRR_S | ((RRR_T & 1) << 4)); gen_right_shift_sar(dc, tmp); tcg_temp_free(tmp); } break; case 6: /*RER*/ TBD(); break; case 7: /*WER*/ TBD(); break; case 8: /*ROTWw*/ HAS_OPTION(XTENSA_OPTION_WINDOWED_REGISTER); gen_check_privilege(dc); { TCGv_i32 tmp = tcg_const_i32( RRR_T | ((RRR_T & 8) ? 0xfffffff0 : 0)); gen_helper_rotw(cpu_env, tmp); tcg_temp_free(tmp); reset_used_window(dc); } break; case 14: /*NSAu*/ HAS_OPTION(XTENSA_OPTION_MISC_OP_NSA); gen_window_check2(dc, RRR_S, RRR_T); gen_helper_nsa(cpu_R[RRR_T], cpu_R[RRR_S]); break; case 15: /*NSAUu*/ HAS_OPTION(XTENSA_OPTION_MISC_OP_NSA); gen_window_check2(dc, RRR_S, RRR_T); gen_helper_nsau(cpu_R[RRR_T], cpu_R[RRR_S]); break; default: /*reserved*/ RESERVED(); break; } break; case 5: /*TLB*/ HAS_OPTION_BITS( XTENSA_OPTION_BIT(XTENSA_OPTION_MMU) | XTENSA_OPTION_BIT(XTENSA_OPTION_REGION_PROTECTION) | XTENSA_OPTION_BIT(XTENSA_OPTION_REGION_TRANSLATION)); gen_check_privilege(dc); gen_window_check2(dc, RRR_S, RRR_T); { TCGv_i32 dtlb = tcg_const_i32((RRR_R & 8) != 0); switch (RRR_R & 7) { case 3: /*RITLB0*/ /*RDTLB0*/ gen_helper_rtlb0(cpu_R[RRR_T], cpu_env, cpu_R[RRR_S], dtlb); break; case 4: /*IITLB*/ /*IDTLB*/ gen_helper_itlb(cpu_env, cpu_R[RRR_S], dtlb); /* This could change memory mapping, so exit tb */ gen_jumpi_check_loop_end(dc, -1); break; case 5: /*PITLB*/ /*PDTLB*/ tcg_gen_movi_i32(cpu_pc, dc->pc); gen_helper_ptlb(cpu_R[RRR_T], cpu_env, cpu_R[RRR_S], dtlb); break; case 6: /*WITLB*/ /*WDTLB*/ gen_helper_wtlb( cpu_env, cpu_R[RRR_T], cpu_R[RRR_S], dtlb); /* This could change memory mapping, so exit tb */ gen_jumpi_check_loop_end(dc, -1); break; case 7: /*RITLB1*/ /*RDTLB1*/ gen_helper_rtlb1(cpu_R[RRR_T], cpu_env, cpu_R[RRR_S], dtlb); break; default: tcg_temp_free(dtlb); RESERVED(); break; } tcg_temp_free(dtlb); } break; case 6: /*RT0*/ gen_window_check2(dc, RRR_R, RRR_T); switch (RRR_S) { case 0: /*NEG*/ tcg_gen_neg_i32(cpu_R[RRR_R], cpu_R[RRR_T]); break; case 1: /*ABS*/ { TCGv_i32 zero = tcg_const_i32(0); TCGv_i32 neg = tcg_temp_new_i32(); tcg_gen_neg_i32(neg, cpu_R[RRR_T]); tcg_gen_movcond_i32(TCG_COND_GE, cpu_R[RRR_R], cpu_R[RRR_T], zero, cpu_R[RRR_T], neg); tcg_temp_free(neg); tcg_temp_free(zero); } break; default: /*reserved*/ RESERVED(); break; } break; case 7: /*reserved*/ RESERVED(); break; case 8: /*ADD*/ gen_window_check3(dc, RRR_R, RRR_S, RRR_T); tcg_gen_add_i32(cpu_R[RRR_R], cpu_R[RRR_S], cpu_R[RRR_T]); break; case 9: /*ADD**/ case 10: case 11: gen_window_check3(dc, RRR_R, RRR_S, RRR_T); { TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_shli_i32(tmp, cpu_R[RRR_S], OP2 - 8); tcg_gen_add_i32(cpu_R[RRR_R], tmp, cpu_R[RRR_T]); tcg_temp_free(tmp); } break; case 12: /*SUB*/ gen_window_check3(dc, RRR_R, RRR_S, RRR_T); tcg_gen_sub_i32(cpu_R[RRR_R], cpu_R[RRR_S], cpu_R[RRR_T]); break; case 13: /*SUB**/ case 14: case 15: gen_window_check3(dc, RRR_R, RRR_S, RRR_T); { TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_shli_i32(tmp, cpu_R[RRR_S], OP2 - 12); tcg_gen_sub_i32(cpu_R[RRR_R], tmp, cpu_R[RRR_T]); tcg_temp_free(tmp); } break; } break; case 1: /*RST1*/ switch (OP2) { case 0: /*SLLI*/ case 1: gen_window_check2(dc, RRR_R, RRR_S); tcg_gen_shli_i32(cpu_R[RRR_R], cpu_R[RRR_S], 32 - (RRR_T | ((OP2 & 1) << 4))); break; case 2: /*SRAI*/ case 3: gen_window_check2(dc, RRR_R, RRR_T); tcg_gen_sari_i32(cpu_R[RRR_R], cpu_R[RRR_T], RRR_S | ((OP2 & 1) << 4)); break; case 4: /*SRLI*/ gen_window_check2(dc, RRR_R, RRR_T); tcg_gen_shri_i32(cpu_R[RRR_R], cpu_R[RRR_T], RRR_S); break; case 6: /*XSR*/ if (gen_check_sr(dc, RSR_SR, SR_X)) { TCGv_i32 tmp = tcg_temp_new_i32(); if (RSR_SR >= 64) { gen_check_privilege(dc); } gen_window_check1(dc, RRR_T); tcg_gen_mov_i32(tmp, cpu_R[RRR_T]); gen_rsr(dc, cpu_R[RRR_T], RSR_SR); gen_wsr(dc, RSR_SR, tmp); tcg_temp_free(tmp); } break; /* * Note: 64 bit ops are used here solely because SAR values * have range 0..63 */ #define gen_shift_reg(cmd, reg) do { \ TCGv_i64 tmp = tcg_temp_new_i64(); \ tcg_gen_extu_i32_i64(tmp, reg); \ tcg_gen_##cmd##_i64(v, v, tmp); \ tcg_gen_trunc_i64_i32(cpu_R[RRR_R], v); \ tcg_temp_free_i64(v); \ tcg_temp_free_i64(tmp); \ } while (0) #define gen_shift(cmd) gen_shift_reg(cmd, cpu_SR[SAR]) case 8: /*SRC*/ gen_window_check3(dc, RRR_R, RRR_S, RRR_T); { TCGv_i64 v = tcg_temp_new_i64(); tcg_gen_concat_i32_i64(v, cpu_R[RRR_T], cpu_R[RRR_S]); gen_shift(shr); } break; case 9: /*SRL*/ gen_window_check2(dc, RRR_R, RRR_T); if (dc->sar_5bit) { tcg_gen_shr_i32(cpu_R[RRR_R], cpu_R[RRR_T], cpu_SR[SAR]); } else { TCGv_i64 v = tcg_temp_new_i64(); tcg_gen_extu_i32_i64(v, cpu_R[RRR_T]); gen_shift(shr); } break; case 10: /*SLL*/ gen_window_check2(dc, RRR_R, RRR_S); if (dc->sar_m32_5bit) { tcg_gen_shl_i32(cpu_R[RRR_R], cpu_R[RRR_S], dc->sar_m32); } else { TCGv_i64 v = tcg_temp_new_i64(); TCGv_i32 s = tcg_const_i32(32); tcg_gen_sub_i32(s, s, cpu_SR[SAR]); tcg_gen_andi_i32(s, s, 0x3f); tcg_gen_extu_i32_i64(v, cpu_R[RRR_S]); gen_shift_reg(shl, s); tcg_temp_free(s); } break; case 11: /*SRA*/ gen_window_check2(dc, RRR_R, RRR_T); if (dc->sar_5bit) { tcg_gen_sar_i32(cpu_R[RRR_R], cpu_R[RRR_T], cpu_SR[SAR]); } else { TCGv_i64 v = tcg_temp_new_i64(); tcg_gen_ext_i32_i64(v, cpu_R[RRR_T]); gen_shift(sar); } break; #undef gen_shift #undef gen_shift_reg case 12: /*MUL16U*/ HAS_OPTION(XTENSA_OPTION_16_BIT_IMUL); gen_window_check3(dc, RRR_R, RRR_S, RRR_T); { TCGv_i32 v1 = tcg_temp_new_i32(); TCGv_i32 v2 = tcg_temp_new_i32(); tcg_gen_ext16u_i32(v1, cpu_R[RRR_S]); tcg_gen_ext16u_i32(v2, cpu_R[RRR_T]); tcg_gen_mul_i32(cpu_R[RRR_R], v1, v2); tcg_temp_free(v2); tcg_temp_free(v1); } break; case 13: /*MUL16S*/ HAS_OPTION(XTENSA_OPTION_16_BIT_IMUL); gen_window_check3(dc, RRR_R, RRR_S, RRR_T); { TCGv_i32 v1 = tcg_temp_new_i32(); TCGv_i32 v2 = tcg_temp_new_i32(); tcg_gen_ext16s_i32(v1, cpu_R[RRR_S]); tcg_gen_ext16s_i32(v2, cpu_R[RRR_T]); tcg_gen_mul_i32(cpu_R[RRR_R], v1, v2); tcg_temp_free(v2); tcg_temp_free(v1); } break; default: /*reserved*/ RESERVED(); break; } break; case 2: /*RST2*/ if (OP2 >= 8) { gen_window_check3(dc, RRR_R, RRR_S, RRR_T); } if (OP2 >= 12) { HAS_OPTION(XTENSA_OPTION_32_BIT_IDIV); int label = gen_new_label(); tcg_gen_brcondi_i32(TCG_COND_NE, cpu_R[RRR_T], 0, label); gen_exception_cause(dc, INTEGER_DIVIDE_BY_ZERO_CAUSE); gen_set_label(label); } switch (OP2) { #define BOOLEAN_LOGIC(fn, r, s, t) \ do { \ HAS_OPTION(XTENSA_OPTION_BOOLEAN); \ TCGv_i32 tmp1 = tcg_temp_new_i32(); \ TCGv_i32 tmp2 = tcg_temp_new_i32(); \ \ tcg_gen_shri_i32(tmp1, cpu_SR[BR], s); \ tcg_gen_shri_i32(tmp2, cpu_SR[BR], t); \ tcg_gen_##fn##_i32(tmp1, tmp1, tmp2); \ tcg_gen_deposit_i32(cpu_SR[BR], cpu_SR[BR], tmp1, r, 1); \ tcg_temp_free(tmp1); \ tcg_temp_free(tmp2); \ } while (0) case 0: /*ANDBp*/ BOOLEAN_LOGIC(and, RRR_R, RRR_S, RRR_T); break; case 1: /*ANDBCp*/ BOOLEAN_LOGIC(andc, RRR_R, RRR_S, RRR_T); break; case 2: /*ORBp*/ BOOLEAN_LOGIC(or, RRR_R, RRR_S, RRR_T); break; case 3: /*ORBCp*/ BOOLEAN_LOGIC(orc, RRR_R, RRR_S, RRR_T); break; case 4: /*XORBp*/ BOOLEAN_LOGIC(xor, RRR_R, RRR_S, RRR_T); break; #undef BOOLEAN_LOGIC case 8: /*MULLi*/ HAS_OPTION(XTENSA_OPTION_32_BIT_IMUL); tcg_gen_mul_i32(cpu_R[RRR_R], cpu_R[RRR_S], cpu_R[RRR_T]); break; case 10: /*MULUHi*/ case 11: /*MULSHi*/ HAS_OPTION(XTENSA_OPTION_32_BIT_IMUL_HIGH); { TCGv lo = tcg_temp_new(); if (OP2 == 10) { tcg_gen_mulu2_i32(lo, cpu_R[RRR_R], cpu_R[RRR_S], cpu_R[RRR_T]); } else { tcg_gen_muls2_i32(lo, cpu_R[RRR_R], cpu_R[RRR_S], cpu_R[RRR_T]); } tcg_temp_free(lo); } break; case 12: /*QUOUi*/ tcg_gen_divu_i32(cpu_R[RRR_R], cpu_R[RRR_S], cpu_R[RRR_T]); break; case 13: /*QUOSi*/ case 15: /*REMSi*/ { int label1 = gen_new_label(); int label2 = gen_new_label(); tcg_gen_brcondi_i32(TCG_COND_NE, cpu_R[RRR_S], 0x80000000, label1); tcg_gen_brcondi_i32(TCG_COND_NE, cpu_R[RRR_T], 0xffffffff, label1); tcg_gen_movi_i32(cpu_R[RRR_R], OP2 == 13 ? 0x80000000 : 0); tcg_gen_br(label2); gen_set_label(label1); if (OP2 == 13) { tcg_gen_div_i32(cpu_R[RRR_R], cpu_R[RRR_S], cpu_R[RRR_T]); } else { tcg_gen_rem_i32(cpu_R[RRR_R], cpu_R[RRR_S], cpu_R[RRR_T]); } gen_set_label(label2); } break; case 14: /*REMUi*/ tcg_gen_remu_i32(cpu_R[RRR_R], cpu_R[RRR_S], cpu_R[RRR_T]); break; default: /*reserved*/ RESERVED(); break; } break; case 3: /*RST3*/ switch (OP2) { case 0: /*RSR*/ if (gen_check_sr(dc, RSR_SR, SR_R)) { if (RSR_SR >= 64) { gen_check_privilege(dc); } gen_window_check1(dc, RRR_T); gen_rsr(dc, cpu_R[RRR_T], RSR_SR); } break; case 1: /*WSR*/ if (gen_check_sr(dc, RSR_SR, SR_W)) { if (RSR_SR >= 64) { gen_check_privilege(dc); } gen_window_check1(dc, RRR_T); gen_wsr(dc, RSR_SR, cpu_R[RRR_T]); } break; case 2: /*SEXTu*/ HAS_OPTION(XTENSA_OPTION_MISC_OP_SEXT); gen_window_check2(dc, RRR_R, RRR_S); { int shift = 24 - RRR_T; if (shift == 24) { tcg_gen_ext8s_i32(cpu_R[RRR_R], cpu_R[RRR_S]); } else if (shift == 16) { tcg_gen_ext16s_i32(cpu_R[RRR_R], cpu_R[RRR_S]); } else { TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_shli_i32(tmp, cpu_R[RRR_S], shift); tcg_gen_sari_i32(cpu_R[RRR_R], tmp, shift); tcg_temp_free(tmp); } } break; case 3: /*CLAMPSu*/ HAS_OPTION(XTENSA_OPTION_MISC_OP_CLAMPS); gen_window_check2(dc, RRR_R, RRR_S); { TCGv_i32 tmp1 = tcg_temp_new_i32(); TCGv_i32 tmp2 = tcg_temp_new_i32(); TCGv_i32 zero = tcg_const_i32(0); tcg_gen_sari_i32(tmp1, cpu_R[RRR_S], 24 - RRR_T); tcg_gen_xor_i32(tmp2, tmp1, cpu_R[RRR_S]); tcg_gen_andi_i32(tmp2, tmp2, 0xffffffff << (RRR_T + 7)); tcg_gen_sari_i32(tmp1, cpu_R[RRR_S], 31); tcg_gen_xori_i32(tmp1, tmp1, 0xffffffff >> (25 - RRR_T)); tcg_gen_movcond_i32(TCG_COND_EQ, cpu_R[RRR_R], tmp2, zero, cpu_R[RRR_S], tmp1); tcg_temp_free(tmp1); tcg_temp_free(tmp2); tcg_temp_free(zero); } break; case 4: /*MINu*/ case 5: /*MAXu*/ case 6: /*MINUu*/ case 7: /*MAXUu*/ HAS_OPTION(XTENSA_OPTION_MISC_OP_MINMAX); gen_window_check3(dc, RRR_R, RRR_S, RRR_T); { static const TCGCond cond[] = { TCG_COND_LE, TCG_COND_GE, TCG_COND_LEU, TCG_COND_GEU }; tcg_gen_movcond_i32(cond[OP2 - 4], cpu_R[RRR_R], cpu_R[RRR_S], cpu_R[RRR_T], cpu_R[RRR_S], cpu_R[RRR_T]); } break; case 8: /*MOVEQZ*/ case 9: /*MOVNEZ*/ case 10: /*MOVLTZ*/ case 11: /*MOVGEZ*/ gen_window_check3(dc, RRR_R, RRR_S, RRR_T); { static const TCGCond cond[] = { TCG_COND_EQ, TCG_COND_NE, TCG_COND_LT, TCG_COND_GE, }; TCGv_i32 zero = tcg_const_i32(0); tcg_gen_movcond_i32(cond[OP2 - 8], cpu_R[RRR_R], cpu_R[RRR_T], zero, cpu_R[RRR_S], cpu_R[RRR_R]); tcg_temp_free(zero); } break; case 12: /*MOVFp*/ case 13: /*MOVTp*/ HAS_OPTION(XTENSA_OPTION_BOOLEAN); gen_window_check2(dc, RRR_R, RRR_S); { TCGv_i32 zero = tcg_const_i32(0); TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_andi_i32(tmp, cpu_SR[BR], 1 << RRR_T); tcg_gen_movcond_i32(OP2 & 1 ? TCG_COND_NE : TCG_COND_EQ, cpu_R[RRR_R], tmp, zero, cpu_R[RRR_S], cpu_R[RRR_R]); tcg_temp_free(tmp); tcg_temp_free(zero); } break; case 14: /*RUR*/ gen_window_check1(dc, RRR_R); { int st = (RRR_S << 4) + RRR_T; if (uregnames[st].name) { tcg_gen_mov_i32(cpu_R[RRR_R], cpu_UR[st]); } else { qemu_log("RUR %d not implemented, ", st); TBD(); } } break; case 15: /*WUR*/ gen_window_check1(dc, RRR_T); if (uregnames[RSR_SR].name) { gen_wur(RSR_SR, cpu_R[RRR_T]); } else { qemu_log("WUR %d not implemented, ", RSR_SR); TBD(); } break; } break; case 4: /*EXTUI*/ case 5: gen_window_check2(dc, RRR_R, RRR_T); { int shiftimm = RRR_S | ((OP1 & 1) << 4); int maskimm = (1 << (OP2 + 1)) - 1; TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_shri_i32(tmp, cpu_R[RRR_T], shiftimm); tcg_gen_andi_i32(cpu_R[RRR_R], tmp, maskimm); tcg_temp_free(tmp); } break; case 6: /*CUST0*/ RESERVED(); break; case 7: /*CUST1*/ RESERVED(); break; case 8: /*LSCXp*/ switch (OP2) { case 0: /*LSXf*/ case 1: /*LSXUf*/ case 4: /*SSXf*/ case 5: /*SSXUf*/ HAS_OPTION(XTENSA_OPTION_FP_COPROCESSOR); gen_window_check2(dc, RRR_S, RRR_T); gen_check_cpenable(dc, 0); { TCGv_i32 addr = tcg_temp_new_i32(); tcg_gen_add_i32(addr, cpu_R[RRR_S], cpu_R[RRR_T]); gen_load_store_alignment(dc, 2, addr, false); if (OP2 & 0x4) { tcg_gen_qemu_st32(cpu_FR[RRR_R], addr, dc->cring); } else { tcg_gen_qemu_ld32u(cpu_FR[RRR_R], addr, dc->cring); } if (OP2 & 0x1) { tcg_gen_mov_i32(cpu_R[RRR_S], addr); } tcg_temp_free(addr); } break; default: /*reserved*/ RESERVED(); break; } break; case 9: /*LSC4*/ gen_window_check2(dc, RRR_S, RRR_T); switch (OP2) { case 0: /*L32E*/ HAS_OPTION(XTENSA_OPTION_WINDOWED_REGISTER); gen_check_privilege(dc); { TCGv_i32 addr = tcg_temp_new_i32(); tcg_gen_addi_i32(addr, cpu_R[RRR_S], (0xffffffc0 | (RRR_R << 2))); tcg_gen_qemu_ld32u(cpu_R[RRR_T], addr, dc->ring); tcg_temp_free(addr); } break; case 4: /*S32E*/ HAS_OPTION(XTENSA_OPTION_WINDOWED_REGISTER); gen_check_privilege(dc); { TCGv_i32 addr = tcg_temp_new_i32(); tcg_gen_addi_i32(addr, cpu_R[RRR_S], (0xffffffc0 | (RRR_R << 2))); tcg_gen_qemu_st32(cpu_R[RRR_T], addr, dc->ring); tcg_temp_free(addr); } break; default: RESERVED(); break; } break; case 10: /*FP0*/ HAS_OPTION(XTENSA_OPTION_FP_COPROCESSOR); switch (OP2) { case 0: /*ADD.Sf*/ gen_check_cpenable(dc, 0); gen_helper_add_s(cpu_FR[RRR_R], cpu_env, cpu_FR[RRR_S], cpu_FR[RRR_T]); break; case 1: /*SUB.Sf*/ gen_check_cpenable(dc, 0); gen_helper_sub_s(cpu_FR[RRR_R], cpu_env, cpu_FR[RRR_S], cpu_FR[RRR_T]); break; case 2: /*MUL.Sf*/ gen_check_cpenable(dc, 0); gen_helper_mul_s(cpu_FR[RRR_R], cpu_env, cpu_FR[RRR_S], cpu_FR[RRR_T]); break; case 4: /*MADD.Sf*/ gen_check_cpenable(dc, 0); gen_helper_madd_s(cpu_FR[RRR_R], cpu_env, cpu_FR[RRR_R], cpu_FR[RRR_S], cpu_FR[RRR_T]); break; case 5: /*MSUB.Sf*/ gen_check_cpenable(dc, 0); gen_helper_msub_s(cpu_FR[RRR_R], cpu_env, cpu_FR[RRR_R], cpu_FR[RRR_S], cpu_FR[RRR_T]); break; case 8: /*ROUND.Sf*/ case 9: /*TRUNC.Sf*/ case 10: /*FLOOR.Sf*/ case 11: /*CEIL.Sf*/ case 14: /*UTRUNC.Sf*/ gen_window_check1(dc, RRR_R); gen_check_cpenable(dc, 0); { static const unsigned rounding_mode_const[] = { float_round_nearest_even, float_round_to_zero, float_round_down, float_round_up, [6] = float_round_to_zero, }; TCGv_i32 rounding_mode = tcg_const_i32( rounding_mode_const[OP2 & 7]); TCGv_i32 scale = tcg_const_i32(RRR_T); if (OP2 == 14) { gen_helper_ftoui(cpu_R[RRR_R], cpu_FR[RRR_S], rounding_mode, scale); } else { gen_helper_ftoi(cpu_R[RRR_R], cpu_FR[RRR_S], rounding_mode, scale); } tcg_temp_free(rounding_mode); tcg_temp_free(scale); } break; case 12: /*FLOAT.Sf*/ case 13: /*UFLOAT.Sf*/ gen_window_check1(dc, RRR_S); gen_check_cpenable(dc, 0); { TCGv_i32 scale = tcg_const_i32(-RRR_T); if (OP2 == 13) { gen_helper_uitof(cpu_FR[RRR_R], cpu_env, cpu_R[RRR_S], scale); } else { gen_helper_itof(cpu_FR[RRR_R], cpu_env, cpu_R[RRR_S], scale); } tcg_temp_free(scale); } break; case 15: /*FP1OP*/ switch (RRR_T) { case 0: /*MOV.Sf*/ gen_check_cpenable(dc, 0); tcg_gen_mov_i32(cpu_FR[RRR_R], cpu_FR[RRR_S]); break; case 1: /*ABS.Sf*/ gen_check_cpenable(dc, 0); gen_helper_abs_s(cpu_FR[RRR_R], cpu_FR[RRR_S]); break; case 4: /*RFRf*/ gen_window_check1(dc, RRR_R); gen_check_cpenable(dc, 0); tcg_gen_mov_i32(cpu_R[RRR_R], cpu_FR[RRR_S]); break; case 5: /*WFRf*/ gen_window_check1(dc, RRR_S); gen_check_cpenable(dc, 0); tcg_gen_mov_i32(cpu_FR[RRR_R], cpu_R[RRR_S]); break; case 6: /*NEG.Sf*/ gen_check_cpenable(dc, 0); gen_helper_neg_s(cpu_FR[RRR_R], cpu_FR[RRR_S]); break; default: /*reserved*/ RESERVED(); break; } break; default: /*reserved*/ RESERVED(); break; } break; case 11: /*FP1*/ HAS_OPTION(XTENSA_OPTION_FP_COPROCESSOR); #define gen_compare(rel, br, a, b) \ do { \ TCGv_i32 bit = tcg_const_i32(1 << br); \ \ gen_check_cpenable(dc, 0); \ gen_helper_##rel(cpu_env, bit, cpu_FR[a], cpu_FR[b]); \ tcg_temp_free(bit); \ } while (0) switch (OP2) { case 1: /*UN.Sf*/ gen_compare(un_s, RRR_R, RRR_S, RRR_T); break; case 2: /*OEQ.Sf*/ gen_compare(oeq_s, RRR_R, RRR_S, RRR_T); break; case 3: /*UEQ.Sf*/ gen_compare(ueq_s, RRR_R, RRR_S, RRR_T); break; case 4: /*OLT.Sf*/ gen_compare(olt_s, RRR_R, RRR_S, RRR_T); break; case 5: /*ULT.Sf*/ gen_compare(ult_s, RRR_R, RRR_S, RRR_T); break; case 6: /*OLE.Sf*/ gen_compare(ole_s, RRR_R, RRR_S, RRR_T); break; case 7: /*ULE.Sf*/ gen_compare(ule_s, RRR_R, RRR_S, RRR_T); break; #undef gen_compare case 8: /*MOVEQZ.Sf*/ case 9: /*MOVNEZ.Sf*/ case 10: /*MOVLTZ.Sf*/ case 11: /*MOVGEZ.Sf*/ gen_window_check1(dc, RRR_T); gen_check_cpenable(dc, 0); { static const TCGCond cond[] = { TCG_COND_EQ, TCG_COND_NE, TCG_COND_LT, TCG_COND_GE, }; TCGv_i32 zero = tcg_const_i32(0); tcg_gen_movcond_i32(cond[OP2 - 8], cpu_FR[RRR_R], cpu_R[RRR_T], zero, cpu_FR[RRR_S], cpu_FR[RRR_R]); tcg_temp_free(zero); } break; case 12: /*MOVF.Sf*/ case 13: /*MOVT.Sf*/ HAS_OPTION(XTENSA_OPTION_BOOLEAN); gen_check_cpenable(dc, 0); { TCGv_i32 zero = tcg_const_i32(0); TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_andi_i32(tmp, cpu_SR[BR], 1 << RRR_T); tcg_gen_movcond_i32(OP2 & 1 ? TCG_COND_NE : TCG_COND_EQ, cpu_FR[RRR_R], tmp, zero, cpu_FR[RRR_S], cpu_FR[RRR_R]); tcg_temp_free(tmp); tcg_temp_free(zero); } break; default: /*reserved*/ RESERVED(); break; } break; default: /*reserved*/ RESERVED(); break; } break; case 1: /*L32R*/ gen_window_check1(dc, RRR_T); { TCGv_i32 tmp = tcg_const_i32( ((dc->tb->flags & XTENSA_TBFLAG_LITBASE) ? 0 : ((dc->pc + 3) & ~3)) + (0xfffc0000 | (RI16_IMM16 << 2))); if (dc->tb->flags & XTENSA_TBFLAG_LITBASE) { tcg_gen_add_i32(tmp, tmp, dc->litbase); } tcg_gen_qemu_ld32u(cpu_R[RRR_T], tmp, dc->cring); tcg_temp_free(tmp); } break; case 2: /*LSAI*/ #define gen_load_store(type, shift) do { \ TCGv_i32 addr = tcg_temp_new_i32(); \ gen_window_check2(dc, RRI8_S, RRI8_T); \ tcg_gen_addi_i32(addr, cpu_R[RRI8_S], RRI8_IMM8 << shift); \ if (shift) { \ gen_load_store_alignment(dc, shift, addr, false); \ } \ tcg_gen_qemu_##type(cpu_R[RRI8_T], addr, dc->cring); \ tcg_temp_free(addr); \ } while (0) switch (RRI8_R) { case 0: /*L8UI*/ gen_load_store(ld8u, 0); break; case 1: /*L16UI*/ gen_load_store(ld16u, 1); break; case 2: /*L32I*/ gen_load_store(ld32u, 2); break; case 4: /*S8I*/ gen_load_store(st8, 0); break; case 5: /*S16I*/ gen_load_store(st16, 1); break; case 6: /*S32I*/ gen_load_store(st32, 2); break; #define gen_dcache_hit_test(w, shift) do { \ TCGv_i32 addr = tcg_temp_new_i32(); \ TCGv_i32 res = tcg_temp_new_i32(); \ gen_window_check1(dc, RRI##w##_S); \ tcg_gen_addi_i32(addr, cpu_R[RRI##w##_S], \ RRI##w##_IMM##w << shift); \ tcg_gen_qemu_ld8u(res, addr, dc->cring); \ tcg_temp_free(addr); \ tcg_temp_free(res); \ } while (0) #define gen_dcache_hit_test4() gen_dcache_hit_test(4, 4) #define gen_dcache_hit_test8() gen_dcache_hit_test(8, 2) case 7: /*CACHEc*/ if (RRI8_T < 8) { HAS_OPTION(XTENSA_OPTION_DCACHE); } switch (RRI8_T) { case 0: /*DPFRc*/ gen_window_check1(dc, RRI8_S); break; case 1: /*DPFWc*/ gen_window_check1(dc, RRI8_S); break; case 2: /*DPFROc*/ gen_window_check1(dc, RRI8_S); break; case 3: /*DPFWOc*/ gen_window_check1(dc, RRI8_S); break; case 4: /*DHWBc*/ gen_dcache_hit_test8(); break; case 5: /*DHWBIc*/ gen_dcache_hit_test8(); break; case 6: /*DHIc*/ gen_check_privilege(dc); gen_dcache_hit_test8(); break; case 7: /*DIIc*/ gen_check_privilege(dc); gen_window_check1(dc, RRI8_S); break; case 8: /*DCEc*/ switch (OP1) { case 0: /*DPFLl*/ HAS_OPTION(XTENSA_OPTION_DCACHE_INDEX_LOCK); gen_check_privilege(dc); gen_dcache_hit_test4(); break; case 2: /*DHUl*/ HAS_OPTION(XTENSA_OPTION_DCACHE_INDEX_LOCK); gen_check_privilege(dc); gen_dcache_hit_test4(); break; case 3: /*DIUl*/ HAS_OPTION(XTENSA_OPTION_DCACHE_INDEX_LOCK); gen_check_privilege(dc); gen_window_check1(dc, RRI4_S); break; case 4: /*DIWBc*/ HAS_OPTION(XTENSA_OPTION_DCACHE); gen_check_privilege(dc); gen_window_check1(dc, RRI4_S); break; case 5: /*DIWBIc*/ HAS_OPTION(XTENSA_OPTION_DCACHE); gen_check_privilege(dc); gen_window_check1(dc, RRI4_S); break; default: /*reserved*/ RESERVED(); break; } break; #undef gen_dcache_hit_test #undef gen_dcache_hit_test4 #undef gen_dcache_hit_test8 #define gen_icache_hit_test(w, shift) do { \ TCGv_i32 addr = tcg_temp_new_i32(); \ gen_window_check1(dc, RRI##w##_S); \ tcg_gen_movi_i32(cpu_pc, dc->pc); \ tcg_gen_addi_i32(addr, cpu_R[RRI##w##_S], \ RRI##w##_IMM##w << shift); \ gen_helper_itlb_hit_test(cpu_env, addr); \ tcg_temp_free(addr); \ } while (0) #define gen_icache_hit_test4() gen_icache_hit_test(4, 4) #define gen_icache_hit_test8() gen_icache_hit_test(8, 2) case 12: /*IPFc*/ HAS_OPTION(XTENSA_OPTION_ICACHE); gen_window_check1(dc, RRI8_S); break; case 13: /*ICEc*/ switch (OP1) { case 0: /*IPFLl*/ HAS_OPTION(XTENSA_OPTION_ICACHE_INDEX_LOCK); gen_check_privilege(dc); gen_icache_hit_test4(); break; case 2: /*IHUl*/ HAS_OPTION(XTENSA_OPTION_ICACHE_INDEX_LOCK); gen_check_privilege(dc); gen_icache_hit_test4(); break; case 3: /*IIUl*/ HAS_OPTION(XTENSA_OPTION_ICACHE_INDEX_LOCK); gen_check_privilege(dc); gen_window_check1(dc, RRI4_S); break; default: /*reserved*/ RESERVED(); break; } break; case 14: /*IHIc*/ HAS_OPTION(XTENSA_OPTION_ICACHE); gen_icache_hit_test8(); break; case 15: /*IIIc*/ HAS_OPTION(XTENSA_OPTION_ICACHE); gen_check_privilege(dc); gen_window_check1(dc, RRI8_S); break; default: /*reserved*/ RESERVED(); break; } break; #undef gen_icache_hit_test #undef gen_icache_hit_test4 #undef gen_icache_hit_test8 case 9: /*L16SI*/ gen_load_store(ld16s, 1); break; #undef gen_load_store case 10: /*MOVI*/ gen_window_check1(dc, RRI8_T); tcg_gen_movi_i32(cpu_R[RRI8_T], RRI8_IMM8 | (RRI8_S << 8) | ((RRI8_S & 0x8) ? 0xfffff000 : 0)); break; #define gen_load_store_no_hw_align(type) do { \ TCGv_i32 addr = tcg_temp_local_new_i32(); \ gen_window_check2(dc, RRI8_S, RRI8_T); \ tcg_gen_addi_i32(addr, cpu_R[RRI8_S], RRI8_IMM8 << 2); \ gen_load_store_alignment(dc, 2, addr, true); \ tcg_gen_qemu_##type(cpu_R[RRI8_T], addr, dc->cring); \ tcg_temp_free(addr); \ } while (0) case 11: /*L32AIy*/ HAS_OPTION(XTENSA_OPTION_MP_SYNCHRO); gen_load_store_no_hw_align(ld32u); /*TODO acquire?*/ break; case 12: /*ADDI*/ gen_window_check2(dc, RRI8_S, RRI8_T); tcg_gen_addi_i32(cpu_R[RRI8_T], cpu_R[RRI8_S], RRI8_IMM8_SE); break; case 13: /*ADDMI*/ gen_window_check2(dc, RRI8_S, RRI8_T); tcg_gen_addi_i32(cpu_R[RRI8_T], cpu_R[RRI8_S], RRI8_IMM8_SE << 8); break; case 14: /*S32C1Iy*/ HAS_OPTION(XTENSA_OPTION_CONDITIONAL_STORE); gen_window_check2(dc, RRI8_S, RRI8_T); { int label = gen_new_label(); TCGv_i32 tmp = tcg_temp_local_new_i32(); TCGv_i32 addr = tcg_temp_local_new_i32(); TCGv_i32 tpc; tcg_gen_mov_i32(tmp, cpu_R[RRI8_T]); tcg_gen_addi_i32(addr, cpu_R[RRI8_S], RRI8_IMM8 << 2); gen_load_store_alignment(dc, 2, addr, true); gen_advance_ccount(dc); tpc = tcg_const_i32(dc->pc); gen_helper_check_atomctl(cpu_env, tpc, addr); tcg_gen_qemu_ld32u(cpu_R[RRI8_T], addr, dc->cring); tcg_gen_brcond_i32(TCG_COND_NE, cpu_R[RRI8_T], cpu_SR[SCOMPARE1], label); tcg_gen_qemu_st32(tmp, addr, dc->cring); gen_set_label(label); tcg_temp_free(tpc); tcg_temp_free(addr); tcg_temp_free(tmp); } break; case 15: /*S32RIy*/ HAS_OPTION(XTENSA_OPTION_MP_SYNCHRO); gen_load_store_no_hw_align(st32); /*TODO release?*/ break; #undef gen_load_store_no_hw_align default: /*reserved*/ RESERVED(); break; } break; case 3: /*LSCIp*/ switch (RRI8_R) { case 0: /*LSIf*/ case 4: /*SSIf*/ case 8: /*LSIUf*/ case 12: /*SSIUf*/ HAS_OPTION(XTENSA_OPTION_FP_COPROCESSOR); gen_window_check1(dc, RRI8_S); gen_check_cpenable(dc, 0); { TCGv_i32 addr = tcg_temp_new_i32(); tcg_gen_addi_i32(addr, cpu_R[RRI8_S], RRI8_IMM8 << 2); gen_load_store_alignment(dc, 2, addr, false); if (RRI8_R & 0x4) { tcg_gen_qemu_st32(cpu_FR[RRI8_T], addr, dc->cring); } else { tcg_gen_qemu_ld32u(cpu_FR[RRI8_T], addr, dc->cring); } if (RRI8_R & 0x8) { tcg_gen_mov_i32(cpu_R[RRI8_S], addr); } tcg_temp_free(addr); } break; default: /*reserved*/ RESERVED(); break; } break; case 4: /*MAC16d*/ HAS_OPTION(XTENSA_OPTION_MAC16); { enum { MAC16_UMUL = 0x0, MAC16_MUL = 0x4, MAC16_MULA = 0x8, MAC16_MULS = 0xc, MAC16_NONE = 0xf, } op = OP1 & 0xc; bool is_m1_sr = (OP2 & 0x3) == 2; bool is_m2_sr = (OP2 & 0xc) == 0; uint32_t ld_offset = 0; if (OP2 > 9) { RESERVED(); } switch (OP2 & 2) { case 0: /*MACI?/MACC?*/ is_m1_sr = true; ld_offset = (OP2 & 1) ? -4 : 4; if (OP2 >= 8) { /*MACI/MACC*/ if (OP1 == 0) { /*LDINC/LDDEC*/ op = MAC16_NONE; } else { RESERVED(); } } else if (op != MAC16_MULA) { /*MULA.*.*.LDINC/LDDEC*/ RESERVED(); } break; case 2: /*MACD?/MACA?*/ if (op == MAC16_UMUL && OP2 != 7) { /*UMUL only in MACAA*/ RESERVED(); } break; } if (op != MAC16_NONE) { if (!is_m1_sr) { gen_window_check1(dc, RRR_S); } if (!is_m2_sr) { gen_window_check1(dc, RRR_T); } } { TCGv_i32 vaddr = tcg_temp_new_i32(); TCGv_i32 mem32 = tcg_temp_new_i32(); if (ld_offset) { gen_window_check1(dc, RRR_S); tcg_gen_addi_i32(vaddr, cpu_R[RRR_S], ld_offset); gen_load_store_alignment(dc, 2, vaddr, false); tcg_gen_qemu_ld32u(mem32, vaddr, dc->cring); } if (op != MAC16_NONE) { TCGv_i32 m1 = gen_mac16_m( is_m1_sr ? cpu_SR[MR + RRR_X] : cpu_R[RRR_S], OP1 & 1, op == MAC16_UMUL); TCGv_i32 m2 = gen_mac16_m( is_m2_sr ? cpu_SR[MR + 2 + RRR_Y] : cpu_R[RRR_T], OP1 & 2, op == MAC16_UMUL); if (op == MAC16_MUL || op == MAC16_UMUL) { tcg_gen_mul_i32(cpu_SR[ACCLO], m1, m2); if (op == MAC16_UMUL) { tcg_gen_movi_i32(cpu_SR[ACCHI], 0); } else { tcg_gen_sari_i32(cpu_SR[ACCHI], cpu_SR[ACCLO], 31); } } else { TCGv_i32 lo = tcg_temp_new_i32(); TCGv_i32 hi = tcg_temp_new_i32(); tcg_gen_mul_i32(lo, m1, m2); tcg_gen_sari_i32(hi, lo, 31); if (op == MAC16_MULA) { tcg_gen_add2_i32(cpu_SR[ACCLO], cpu_SR[ACCHI], cpu_SR[ACCLO], cpu_SR[ACCHI], lo, hi); } else { tcg_gen_sub2_i32(cpu_SR[ACCLO], cpu_SR[ACCHI], cpu_SR[ACCLO], cpu_SR[ACCHI], lo, hi); } tcg_gen_ext8s_i32(cpu_SR[ACCHI], cpu_SR[ACCHI]); tcg_temp_free_i32(lo); tcg_temp_free_i32(hi); } tcg_temp_free(m1); tcg_temp_free(m2); } if (ld_offset) { tcg_gen_mov_i32(cpu_R[RRR_S], vaddr); tcg_gen_mov_i32(cpu_SR[MR + RRR_W], mem32); } tcg_temp_free(vaddr); tcg_temp_free(mem32); } } break; case 5: /*CALLN*/ switch (CALL_N) { case 0: /*CALL0*/ tcg_gen_movi_i32(cpu_R[0], dc->next_pc); gen_jumpi(dc, (dc->pc & ~3) + (CALL_OFFSET_SE << 2) + 4, 0); break; case 1: /*CALL4w*/ case 2: /*CALL8w*/ case 3: /*CALL12w*/ HAS_OPTION(XTENSA_OPTION_WINDOWED_REGISTER); gen_window_check1(dc, CALL_N << 2); gen_callwi(dc, CALL_N, (dc->pc & ~3) + (CALL_OFFSET_SE << 2) + 4, 0); break; } break; case 6: /*SI*/ switch (CALL_N) { case 0: /*J*/ gen_jumpi(dc, dc->pc + 4 + CALL_OFFSET_SE, 0); break; case 1: /*BZ*/ gen_window_check1(dc, BRI12_S); { static const TCGCond cond[] = { TCG_COND_EQ, /*BEQZ*/ TCG_COND_NE, /*BNEZ*/ TCG_COND_LT, /*BLTZ*/ TCG_COND_GE, /*BGEZ*/ }; gen_brcondi(dc, cond[BRI12_M & 3], cpu_R[BRI12_S], 0, 4 + BRI12_IMM12_SE); } break; case 2: /*BI0*/ gen_window_check1(dc, BRI8_S); { static const TCGCond cond[] = { TCG_COND_EQ, /*BEQI*/ TCG_COND_NE, /*BNEI*/ TCG_COND_LT, /*BLTI*/ TCG_COND_GE, /*BGEI*/ }; gen_brcondi(dc, cond[BRI8_M & 3], cpu_R[BRI8_S], B4CONST[BRI8_R], 4 + BRI8_IMM8_SE); } break; case 3: /*BI1*/ switch (BRI8_M) { case 0: /*ENTRYw*/ HAS_OPTION(XTENSA_OPTION_WINDOWED_REGISTER); { TCGv_i32 pc = tcg_const_i32(dc->pc); TCGv_i32 s = tcg_const_i32(BRI12_S); TCGv_i32 imm = tcg_const_i32(BRI12_IMM12); gen_advance_ccount(dc); gen_helper_entry(cpu_env, pc, s, imm); tcg_temp_free(imm); tcg_temp_free(s); tcg_temp_free(pc); reset_used_window(dc); } break; case 1: /*B1*/ switch (BRI8_R) { case 0: /*BFp*/ case 1: /*BTp*/ HAS_OPTION(XTENSA_OPTION_BOOLEAN); { TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_andi_i32(tmp, cpu_SR[BR], 1 << RRI8_S); gen_brcondi(dc, BRI8_R == 1 ? TCG_COND_NE : TCG_COND_EQ, tmp, 0, 4 + RRI8_IMM8_SE); tcg_temp_free(tmp); } break; case 8: /*LOOP*/ case 9: /*LOOPNEZ*/ case 10: /*LOOPGTZ*/ HAS_OPTION(XTENSA_OPTION_LOOP); gen_window_check1(dc, RRI8_S); { uint32_t lend = dc->pc + RRI8_IMM8 + 4; TCGv_i32 tmp = tcg_const_i32(lend); tcg_gen_subi_i32(cpu_SR[LCOUNT], cpu_R[RRI8_S], 1); tcg_gen_movi_i32(cpu_SR[LBEG], dc->next_pc); gen_helper_wsr_lend(cpu_env, tmp); tcg_temp_free(tmp); if (BRI8_R > 8) { int label = gen_new_label(); tcg_gen_brcondi_i32( BRI8_R == 9 ? TCG_COND_NE : TCG_COND_GT, cpu_R[RRI8_S], 0, label); gen_jumpi(dc, lend, 1); gen_set_label(label); } gen_jumpi(dc, dc->next_pc, 0); } break; default: /*reserved*/ RESERVED(); break; } break; case 2: /*BLTUI*/ case 3: /*BGEUI*/ gen_window_check1(dc, BRI8_S); gen_brcondi(dc, BRI8_M == 2 ? TCG_COND_LTU : TCG_COND_GEU, cpu_R[BRI8_S], B4CONSTU[BRI8_R], 4 + BRI8_IMM8_SE); break; } break; } break; case 7: /*B*/ { TCGCond eq_ne = (RRI8_R & 8) ? TCG_COND_NE : TCG_COND_EQ; switch (RRI8_R & 7) { case 0: /*BNONE*/ /*BANY*/ gen_window_check2(dc, RRI8_S, RRI8_T); { TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_and_i32(tmp, cpu_R[RRI8_S], cpu_R[RRI8_T]); gen_brcondi(dc, eq_ne, tmp, 0, 4 + RRI8_IMM8_SE); tcg_temp_free(tmp); } break; case 1: /*BEQ*/ /*BNE*/ case 2: /*BLT*/ /*BGE*/ case 3: /*BLTU*/ /*BGEU*/ gen_window_check2(dc, RRI8_S, RRI8_T); { static const TCGCond cond[] = { [1] = TCG_COND_EQ, [2] = TCG_COND_LT, [3] = TCG_COND_LTU, [9] = TCG_COND_NE, [10] = TCG_COND_GE, [11] = TCG_COND_GEU, }; gen_brcond(dc, cond[RRI8_R], cpu_R[RRI8_S], cpu_R[RRI8_T], 4 + RRI8_IMM8_SE); } break; case 4: /*BALL*/ /*BNALL*/ gen_window_check2(dc, RRI8_S, RRI8_T); { TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_and_i32(tmp, cpu_R[RRI8_S], cpu_R[RRI8_T]); gen_brcond(dc, eq_ne, tmp, cpu_R[RRI8_T], 4 + RRI8_IMM8_SE); tcg_temp_free(tmp); } break; case 5: /*BBC*/ /*BBS*/ gen_window_check2(dc, RRI8_S, RRI8_T); { #ifdef TARGET_WORDS_BIGENDIAN TCGv_i32 bit = tcg_const_i32(0x80000000); #else TCGv_i32 bit = tcg_const_i32(0x00000001); #endif TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_andi_i32(tmp, cpu_R[RRI8_T], 0x1f); #ifdef TARGET_WORDS_BIGENDIAN tcg_gen_shr_i32(bit, bit, tmp); #else tcg_gen_shl_i32(bit, bit, tmp); #endif tcg_gen_and_i32(tmp, cpu_R[RRI8_S], bit); gen_brcondi(dc, eq_ne, tmp, 0, 4 + RRI8_IMM8_SE); tcg_temp_free(tmp); tcg_temp_free(bit); } break; case 6: /*BBCI*/ /*BBSI*/ case 7: gen_window_check1(dc, RRI8_S); { TCGv_i32 tmp = tcg_temp_new_i32(); tcg_gen_andi_i32(tmp, cpu_R[RRI8_S], #ifdef TARGET_WORDS_BIGENDIAN 0x80000000 >> (((RRI8_R & 1) << 4) | RRI8_T)); #else 0x00000001 << (((RRI8_R & 1) << 4) | RRI8_T)); #endif gen_brcondi(dc, eq_ne, tmp, 0, 4 + RRI8_IMM8_SE); tcg_temp_free(tmp); } break; } } break; #define gen_narrow_load_store(type) do { \ TCGv_i32 addr = tcg_temp_new_i32(); \ gen_window_check2(dc, RRRN_S, RRRN_T); \ tcg_gen_addi_i32(addr, cpu_R[RRRN_S], RRRN_R << 2); \ gen_load_store_alignment(dc, 2, addr, false); \ tcg_gen_qemu_##type(cpu_R[RRRN_T], addr, dc->cring); \ tcg_temp_free(addr); \ } while (0) case 8: /*L32I.Nn*/ gen_narrow_load_store(ld32u); break; case 9: /*S32I.Nn*/ gen_narrow_load_store(st32); break; #undef gen_narrow_load_store case 10: /*ADD.Nn*/ gen_window_check3(dc, RRRN_R, RRRN_S, RRRN_T); tcg_gen_add_i32(cpu_R[RRRN_R], cpu_R[RRRN_S], cpu_R[RRRN_T]); break; case 11: /*ADDI.Nn*/ gen_window_check2(dc, RRRN_R, RRRN_S); tcg_gen_addi_i32(cpu_R[RRRN_R], cpu_R[RRRN_S], RRRN_T ? RRRN_T : -1); break; case 12: /*ST2n*/ gen_window_check1(dc, RRRN_S); if (RRRN_T < 8) { /*MOVI.Nn*/ tcg_gen_movi_i32(cpu_R[RRRN_S], RRRN_R | (RRRN_T << 4) | ((RRRN_T & 6) == 6 ? 0xffffff80 : 0)); } else { /*BEQZ.Nn*/ /*BNEZ.Nn*/ TCGCond eq_ne = (RRRN_T & 4) ? TCG_COND_NE : TCG_COND_EQ; gen_brcondi(dc, eq_ne, cpu_R[RRRN_S], 0, 4 + (RRRN_R | ((RRRN_T & 3) << 4))); } break; case 13: /*ST3n*/ switch (RRRN_R) { case 0: /*MOV.Nn*/ gen_window_check2(dc, RRRN_S, RRRN_T); tcg_gen_mov_i32(cpu_R[RRRN_T], cpu_R[RRRN_S]); break; case 15: /*S3*/ switch (RRRN_T) { case 0: /*RET.Nn*/ gen_jump(dc, cpu_R[0]); break; case 1: /*RETW.Nn*/ HAS_OPTION(XTENSA_OPTION_WINDOWED_REGISTER); { TCGv_i32 tmp = tcg_const_i32(dc->pc); gen_advance_ccount(dc); gen_helper_retw(tmp, cpu_env, tmp); gen_jump(dc, tmp); tcg_temp_free(tmp); } break; case 2: /*BREAK.Nn*/ HAS_OPTION(XTENSA_OPTION_DEBUG); if (dc->debug) { gen_debug_exception(dc, DEBUGCAUSE_BN); } break; case 3: /*NOP.Nn*/ break; case 6: /*ILL.Nn*/ gen_exception_cause(dc, ILLEGAL_INSTRUCTION_CAUSE); break; default: /*reserved*/ RESERVED(); break; } break; default: /*reserved*/ RESERVED(); break; } break; default: /*reserved*/ RESERVED(); break; } if (dc->is_jmp == DISAS_NEXT) { gen_check_loop_end(dc, 0); } dc->pc = dc->next_pc; return; invalid_opcode: qemu_log("INVALID(pc = %08x)\n", dc->pc); gen_exception_cause(dc, ILLEGAL_INSTRUCTION_CAUSE); #undef HAS_OPTION } static inline unsigned xtensa_insn_len(CPUXtensaState *env, DisasContext *dc) { uint8_t b0 = cpu_ldub_code(env, dc->pc); return xtensa_op0_insn_len(OP0); } static void check_breakpoint(CPUXtensaState *env, DisasContext *dc) { CPUState *cs = CPU(xtensa_env_get_cpu(env)); CPUBreakpoint *bp; if (unlikely(!QTAILQ_EMPTY(&cs->breakpoints))) { QTAILQ_FOREACH(bp, &cs->breakpoints, entry) { if (bp->pc == dc->pc) { tcg_gen_movi_i32(cpu_pc, dc->pc); gen_exception(dc, EXCP_DEBUG); dc->is_jmp = DISAS_UPDATE; } } } } static void gen_ibreak_check(CPUXtensaState *env, DisasContext *dc) { unsigned i; for (i = 0; i < dc->config->nibreak; ++i) { if ((env->sregs[IBREAKENABLE] & (1 << i)) && env->sregs[IBREAKA + i] == dc->pc) { gen_debug_exception(dc, DEBUGCAUSE_IB); break; } } } static inline void gen_intermediate_code_internal(XtensaCPU *cpu, TranslationBlock *tb, bool search_pc) { CPUState *cs = CPU(cpu); CPUXtensaState *env = &cpu->env; DisasContext dc; int insn_count = 0; int j, lj = -1; uint16_t *gen_opc_end = tcg_ctx.gen_opc_buf + OPC_MAX_SIZE; int max_insns = tb->cflags & CF_COUNT_MASK; uint32_t pc_start = tb->pc; uint32_t next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE; if (max_insns == 0) { max_insns = CF_COUNT_MASK; } dc.config = env->config; dc.singlestep_enabled = cs->singlestep_enabled; dc.tb = tb; dc.pc = pc_start; dc.ring = tb->flags & XTENSA_TBFLAG_RING_MASK; dc.cring = (tb->flags & XTENSA_TBFLAG_EXCM) ? 0 : dc.ring; dc.lbeg = env->sregs[LBEG]; dc.lend = env->sregs[LEND]; dc.is_jmp = DISAS_NEXT; dc.ccount_delta = 0; dc.debug = tb->flags & XTENSA_TBFLAG_DEBUG; dc.icount = tb->flags & XTENSA_TBFLAG_ICOUNT; dc.cpenable = (tb->flags & XTENSA_TBFLAG_CPENABLE_MASK) >> XTENSA_TBFLAG_CPENABLE_SHIFT; init_litbase(&dc); init_sar_tracker(&dc); reset_used_window(&dc); if (dc.icount) { dc.next_icount = tcg_temp_local_new_i32(); } gen_tb_start(); if (tb->flags & XTENSA_TBFLAG_EXCEPTION) { tcg_gen_movi_i32(cpu_pc, dc.pc); gen_exception(&dc, EXCP_DEBUG); } do { check_breakpoint(env, &dc); if (search_pc) { j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf; if (lj < j) { lj++; while (lj < j) { tcg_ctx.gen_opc_instr_start[lj++] = 0; } } tcg_ctx.gen_opc_pc[lj] = dc.pc; tcg_ctx.gen_opc_instr_start[lj] = 1; tcg_ctx.gen_opc_icount[lj] = insn_count; } if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP | CPU_LOG_TB_OP_OPT))) { tcg_gen_debug_insn_start(dc.pc); } ++dc.ccount_delta; if (insn_count + 1 == max_insns && (tb->cflags & CF_LAST_IO)) { gen_io_start(); } if (dc.icount) { int label = gen_new_label(); tcg_gen_addi_i32(dc.next_icount, cpu_SR[ICOUNT], 1); tcg_gen_brcondi_i32(TCG_COND_NE, dc.next_icount, 0, label); tcg_gen_mov_i32(dc.next_icount, cpu_SR[ICOUNT]); if (dc.debug) { gen_debug_exception(&dc, DEBUGCAUSE_IC); } gen_set_label(label); } if (dc.debug) { gen_ibreak_check(env, &dc); } disas_xtensa_insn(env, &dc); ++insn_count; if (dc.icount) { tcg_gen_mov_i32(cpu_SR[ICOUNT], dc.next_icount); } if (cs->singlestep_enabled) { tcg_gen_movi_i32(cpu_pc, dc.pc); gen_exception(&dc, EXCP_DEBUG); break; } } while (dc.is_jmp == DISAS_NEXT && insn_count < max_insns && dc.pc < next_page_start && dc.pc + xtensa_insn_len(env, &dc) <= next_page_start && tcg_ctx.gen_opc_ptr < gen_opc_end); reset_litbase(&dc); reset_sar_tracker(&dc); if (dc.icount) { tcg_temp_free(dc.next_icount); } if (tb->cflags & CF_LAST_IO) { gen_io_end(); } if (dc.is_jmp == DISAS_NEXT) { gen_jumpi(&dc, dc.pc, 0); } gen_tb_end(tb, insn_count); *tcg_ctx.gen_opc_ptr = INDEX_op_end; #ifdef DEBUG_DISAS if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) { qemu_log("----------------\n"); qemu_log("IN: %s\n", lookup_symbol(pc_start)); log_target_disas(env, pc_start, dc.pc - pc_start, 0); qemu_log("\n"); } #endif if (search_pc) { j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf; memset(tcg_ctx.gen_opc_instr_start + lj + 1, 0, (j - lj) * sizeof(tcg_ctx.gen_opc_instr_start[0])); } else { tb->size = dc.pc - pc_start; tb->icount = insn_count; } } void gen_intermediate_code(CPUXtensaState *env, TranslationBlock *tb) { gen_intermediate_code_internal(xtensa_env_get_cpu(env), tb, false); } void gen_intermediate_code_pc(CPUXtensaState *env, TranslationBlock *tb) { gen_intermediate_code_internal(xtensa_env_get_cpu(env), tb, true); } void xtensa_cpu_dump_state(CPUState *cs, FILE *f, fprintf_function cpu_fprintf, int flags) { XtensaCPU *cpu = XTENSA_CPU(cs); CPUXtensaState *env = &cpu->env; int i, j; cpu_fprintf(f, "PC=%08x\n\n", env->pc); for (i = j = 0; i < 256; ++i) { if (xtensa_option_bits_enabled(env->config, sregnames[i].opt_bits)) { cpu_fprintf(f, "%12s=%08x%c", sregnames[i].name, env->sregs[i], (j++ % 4) == 3 ? '\n' : ' '); } } cpu_fprintf(f, (j % 4) == 0 ? "\n" : "\n\n"); for (i = j = 0; i < 256; ++i) { if (xtensa_option_bits_enabled(env->config, uregnames[i].opt_bits)) { cpu_fprintf(f, "%s=%08x%c", uregnames[i].name, env->uregs[i], (j++ % 4) == 3 ? '\n' : ' '); } } cpu_fprintf(f, (j % 4) == 0 ? "\n" : "\n\n"); for (i = 0; i < 16; ++i) { cpu_fprintf(f, " A%02d=%08x%c", i, env->regs[i], (i % 4) == 3 ? '\n' : ' '); } cpu_fprintf(f, "\n"); for (i = 0; i < env->config->nareg; ++i) { cpu_fprintf(f, "AR%02d=%08x%c", i, env->phys_regs[i], (i % 4) == 3 ? '\n' : ' '); } if (xtensa_option_enabled(env->config, XTENSA_OPTION_FP_COPROCESSOR)) { cpu_fprintf(f, "\n"); for (i = 0; i < 16; ++i) { cpu_fprintf(f, "F%02d=%08x (%+10.8e)%c", i, float32_val(env->fregs[i]), *(float *)&env->fregs[i], (i % 2) == 1 ? '\n' : ' '); } } } void restore_state_to_opc(CPUXtensaState *env, TranslationBlock *tb, int pc_pos) { env->pc = tcg_ctx.gen_opc_pc[pc_pos]; }
noelbk/qemu
target-xtensa/translate.c
C
gpl-2.0
105,242
/* $Id$ */ /** @file * IPRT - Internal Header for RTDbgMod and the associated interpreters. */ /* * Copyright (C) 2008-2012 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ #ifndef ___internal_dbgmod_h #define ___internal_dbgmod_h #include <iprt/types.h> #include <iprt/critsect.h> #include <iprt/ldr.h> /* for PFNRTLDRENUMDBG */ #include "internal/magics.h" RT_C_DECLS_BEGIN /** @addtogroup grp_rt_dbgmod * @internal * @{ */ /** Pointer to the internal module structure. */ typedef struct RTDBGMODINT *PRTDBGMODINT; /** * Virtual method table for executable image interpreters. */ typedef struct RTDBGMODVTIMG { /** Magic number (RTDBGMODVTIMG_MAGIC). */ uint32_t u32Magic; /** Reserved. */ uint32_t fReserved; /** The name of the interpreter. */ const char *pszName; /** * Try open the image. * * This combines probing and opening. * * @returns IPRT status code. No informational returns defined. * * @param pMod Pointer to the module that is being opened. * * The RTDBGMOD::pszDbgFile member will point to * the filename of any debug info we're aware of * on input. Also, or alternatively, it is expected * that the interpreter will look for debug info in * the executable image file when present and that it * may ask the image interpreter for this when it's * around. * * Upon successful return the method is expected to * initialize pImgOps and pvImgPriv. * @param enmArch The desired architecture. */ DECLCALLBACKMEMBER(int, pfnTryOpen)(PRTDBGMODINT pMod, RTLDRARCH enmArch); /** * Close the interpreter, freeing all associated resources. * * The caller sets the pDbgOps and pvDbgPriv RTDBGMOD members * to NULL upon return. * * @param pMod Pointer to the module structure. */ DECLCALLBACKMEMBER(int, pfnClose)(PRTDBGMODINT pMod); /** * Enumerate the debug info contained in the executable image. * * Identical to RTLdrEnumDbgInfo. * * @returns IPRT status code or whatever pfnCallback returns. * * @param pMod Pointer to the module structure. * @param pfnCallback The callback function. Ignore the module * handle argument! * @param pvUser The user argument. */ DECLCALLBACKMEMBER(int, pfnEnumDbgInfo)(PRTDBGMODINT pMod, PFNRTLDRENUMDBG pfnCallback, void *pvUser); /** * Enumerate the segments in the executable image. * * Identical to RTLdrEnumSegments. * * @returns IPRT status code or whatever pfnCallback returns. * * @param pMod Pointer to the module structure. * @param pfnCallback The callback function. Ignore the module * handle argument! * @param pvUser The user argument. */ DECLCALLBACKMEMBER(int, pfnEnumSegments)(PRTDBGMODINT pMod, PFNRTLDRENUMSEGS pfnCallback, void *pvUser); /** * Enumerates the symbols exported by the module. * * @returns iprt status code, which might have been returned by pfnCallback. * @param pMod Pointer to the module structure. * @param fFlags Flags indicating what to return and such. * @param BaseAddress The image base addressto use when calculating the * symbol values. * @param pfnCallback The callback function which each symbol is to be fed * to. * @param pvUser User argument to pass to the enumerator. */ DECLCALLBACKMEMBER(int, pfnEnumSymbols)(PRTDBGMODINT pMod, uint32_t fFlags, RTLDRADDR BaseAddress, PFNRTLDRENUMSYMS pfnCallback, void *pvUser); /** * Gets the size of the loaded image. * * Identical to RTLdrSize. * * @returns The size in bytes, RTUINTPTR_MAX on failure. * * @param pMod Pointer to the module structure. */ DECLCALLBACKMEMBER(RTUINTPTR, pfnImageSize)(PRTDBGMODINT pMod); /** * Converts a link address to a segment:offset address (RVA included). * * @returns IPRT status code. * * @param pMod Pointer to the module structure. * @param LinkAddress The link address to convert. * @param piSeg The segment index. * @param poffSeg Where to return the segment offset. */ DECLCALLBACKMEMBER(int, pfnLinkAddressToSegOffset)(PRTDBGMODINT pMod, RTLDRADDR LinkAddress, PRTDBGSEGIDX piSeg, PRTLDRADDR poffSeg); /** * Converts an image relative virtual address to a segment:offset. * * @returns IPRT status code. * * @param pMod Pointer to the loader module structure. * @param Rva The RVA to convert. * @param piSeg The segment index. * @param poffSeg Where to return the segment offset. */ DECLCALLBACKMEMBER(int, pfnRvaToSegOffset)(PRTDBGMODINT pMod, RTLDRADDR Rva, uint32_t *piSeg, PRTLDRADDR poffSeg); /** * Creates a read-only mapping of a part of the image file. * * @returns IPRT status code and *ppvMap set on success. * * @param pMod Pointer to the module structure. * @param iDbgInfo The debug info ordinal number if the request * corresponds exactly to a debug info part from * pfnEnumDbgInfo. Otherwise, pass UINT32_MAX. * @param off The offset into the image file. * @param cb The number of bytes to map. * @param ppvMap Where to return the mapping address on success. * * @remarks Fixups will only be applied if @a iDbgInfo is specified. */ DECLCALLBACKMEMBER(int, pfnMapPart)(PRTDBGMODINT pMod, uint32_t iDbgInfo, RTFOFF off, size_t cb, void const **ppvMap); /** * Unmaps memory previously mapped by pfnMapPart. * * @returns IPRT status code, *ppvMap set to NULL on success. * * @param pMod Pointer to the module structure. * @param cb The size of the mapping. * @param ppvMap The mapping address on input, NULL on * successful return. */ DECLCALLBACKMEMBER(int, pfnUnmapPart)(PRTDBGMODINT pMod, size_t cb, void const **ppvMap); /** * Reads data from the image file. * * @returns IPRT status code, *ppvMap set to NULL on success. * * @param pMod Pointer to the module structure. * @param iDbgInfoHint The debug info ordinal number hint, pass UINT32_MAX * if not know or sure. * @param off The offset into the image file. * @param pvBuf The buffer to read into. * @param cb The number of bytes to read. */ DECLCALLBACKMEMBER(int, pfnReadAt)(PRTDBGMODINT pMod, uint32_t iDbgInfoHint, RTFOFF off, void *pvBuf, size_t cb); /** * Gets the image format. * * @returns Valid image format on success, RTLDRFMT_INVALID if not supported. * @param pMod Pointer to the module structure. */ DECLCALLBACKMEMBER(RTLDRFMT, pfnGetFormat)(PRTDBGMODINT pMod); /** * Gets the image architecture. * * @returns Valid image architecutre on success, RTLDRARCH_WHATEVER if not * supported. * @param pMod Pointer to the module structure. */ DECLCALLBACKMEMBER(RTLDRARCH, pfnGetArch)(PRTDBGMODINT pMod); /** * Generic method for querying image properties. * * @returns IPRT status code. * @param pMod Pointer to the module structure. * @param enmLdrProp The property to query. * @param pvBuf Pointer to the return buffer. * @param cbBuf The size of the return buffer. * @sa RTLdrQueryProp */ DECLCALLBACKMEMBER(int, pfnQueryProp)(PRTDBGMODINT pMod, RTLDRPROP enmProp, void *pvBuf, size_t cbBuf); /** For catching initialization errors (RTDBGMODVTIMG_MAGIC). */ uint32_t u32EndMagic; } RTDBGMODVTIMG; /** Pointer to a const RTDBGMODVTIMG. */ typedef RTDBGMODVTIMG const *PCRTDBGMODVTIMG; /** * Virtual method table for debug info interpreters. */ typedef struct RTDBGMODVTDBG { /** Magic number (RTDBGMODVTDBG_MAGIC). */ uint32_t u32Magic; /** Mask of supported debug info types, see grp_rt_dbg_type. * Used to speed up the search for a suitable interpreter. */ uint32_t fSupports; /** The name of the interpreter. */ const char *pszName; /** * Try open the image. * * This combines probing and opening. * * @returns IPRT status code. No informational returns defined. * * @param pMod Pointer to the module that is being opened. * * The RTDBGMOD::pszDbgFile member will point to * the filename of any debug info we're aware of * on input. Also, or alternatively, it is expected * that the interpreter will look for debug info in * the executable image file when present and that it * may ask the image interpreter for this when it's * around. * * Upon successful return the method is expected to * initialize pDbgOps and pvDbgPriv. * @param enmArch The desired architecture. */ DECLCALLBACKMEMBER(int, pfnTryOpen)(PRTDBGMODINT pMod, RTLDRARCH enmArch); /** * Close the interpreter, freeing all associated resources. * * The caller sets the pDbgOps and pvDbgPriv RTDBGMOD members * to NULL upon return. * * @param pMod Pointer to the module structure. */ DECLCALLBACKMEMBER(int, pfnClose)(PRTDBGMODINT pMod); /** * Converts an image relative virtual address address to a segmented address. * * @returns Segment index on success, NIL_RTDBGSEGIDX on failure. * @param pMod Pointer to the module structure. * @param uRva The image relative address to convert. * @param poffSeg Where to return the segment offset. Optional. */ DECLCALLBACKMEMBER(RTDBGSEGIDX, pfnRvaToSegOff)(PRTDBGMODINT pMod, RTUINTPTR uRva, PRTUINTPTR poffSeg); /** * Image size when mapped if segments are mapped adjacently. * * For ELF, PE, and Mach-O images this is (usually) a natural query, for LX and * NE and such it's a bit odder and the answer may not make much sense for them. * * @returns Image mapped size. * @param pMod Pointer to the module structure. */ DECLCALLBACKMEMBER(RTUINTPTR, pfnImageSize)(PRTDBGMODINT pMod); /** * Adds a segment to the module (optional). * * @returns IPRT status code. * @retval VERR_NOT_SUPPORTED if the interpreter doesn't support this feature. * @retval VERR_DBG_SEGMENT_INDEX_CONFLICT if the segment index exists already. * * @param pMod Pointer to the module structure. * @param uRva The segment image relative address. * @param cb The segment size. * @param pszName The segment name. * @param cchName The length of the segment name. * @param fFlags Segment flags. * @param piSeg The segment index or NIL_RTDBGSEGIDX on input. * The assigned segment index on successful return. * Optional. */ DECLCALLBACKMEMBER(int, pfnSegmentAdd)(PRTDBGMODINT pMod, RTUINTPTR uRva, RTUINTPTR cb, const char *pszName, size_t cchName, uint32_t fFlags, PRTDBGSEGIDX piSeg); /** * Gets the segment count. * * @returns Number of segments. * @retval NIL_RTDBGSEGIDX if unknown. * * @param pMod Pointer to the module structure. */ DECLCALLBACKMEMBER(RTDBGSEGIDX, pfnSegmentCount)(PRTDBGMODINT pMod); /** * Gets information about a segment. * * @returns IPRT status code. * @retval VERR_DBG_INVALID_SEGMENT_INDEX if iSeg is too high. * * @param pMod Pointer to the module structure. * @param iSeg The segment. * @param pSegInfo Where to store the segment information. */ DECLCALLBACKMEMBER(int, pfnSegmentByIndex)(PRTDBGMODINT pMod, RTDBGSEGIDX iSeg, PRTDBGSEGMENT pSegInfo); /** * Adds a symbol to the module (optional). * * @returns IPRT code. * @retval VERR_NOT_SUPPORTED if the interpreter doesn't support this feature. * * @param pMod Pointer to the module structure. * @param pszSymbol The symbol name. * @param cchSymbol The length for the symbol name. * @param iSeg The segment number (0-based). RTDBGMOD_SEG_RVA can be used. * @param off The offset into the segment. * @param cb The area covered by the symbol. 0 is fine. * @param fFlags Flags. * @param piOrdinal Where to return the symbol ordinal on success. If the * interpreter doesn't do ordinals, this will be set to * UINT32_MAX. Optional */ DECLCALLBACKMEMBER(int, pfnSymbolAdd)(PRTDBGMODINT pMod, const char *pszSymbol, size_t cchSymbol, uint32_t iSeg, RTUINTPTR off, RTUINTPTR cb, uint32_t fFlags, uint32_t *piOrdinal); /** * Gets the number of symbols in the module. * * This is used for figuring out the max value to pass to pfnSymbolByIndex among * other things. * * @returns The number of symbols, UINT32_MAX if not known/supported. * * @param pMod Pointer to the module structure. */ DECLCALLBACKMEMBER(uint32_t, pfnSymbolCount)(PRTDBGMODINT pMod); /** * Queries symbol information by ordinal number. * * @returns IPRT status code. * @retval VINF_SUCCESS on success, no informational status code. * @retval VERR_DBG_NO_SYMBOLS if there aren't any symbols. * @retval VERR_NOT_SUPPORTED if lookup by ordinal is not supported. * @retval VERR_SYMBOL_NOT_FOUND if there is no symbol at that index. * * @param pMod Pointer to the module structure. * @param iOrdinal The symbol ordinal number. * @param pSymInfo Where to store the symbol information. */ DECLCALLBACKMEMBER(int, pfnSymbolByOrdinal)(PRTDBGMODINT pMod, uint32_t iOrdinal, PRTDBGSYMBOL pSymInfo); /** * Queries symbol information by symbol name. * * @returns IPRT status code. * @retval VINF_SUCCESS on success, no informational status code. * @retval VERR_DBG_NO_SYMBOLS if there aren't any symbols. * @retval VERR_SYMBOL_NOT_FOUND if no suitable symbol was found. * * @param pMod Pointer to the module structure. * @param pszSymbol The symbol name. * @param cchSymbol The length of the symbol name. * @param pSymInfo Where to store the symbol information. */ DECLCALLBACKMEMBER(int, pfnSymbolByName)(PRTDBGMODINT pMod, const char *pszSymbol, size_t cchSymbol, PRTDBGSYMBOL pSymInfo); /** * Queries symbol information by address. * * The returned symbol is what the debug info interpreter considers the symbol * most applicable to the specified address. This usually means a symbol with an * address equal or lower than the requested. * * @returns IPRT status code. * @retval VINF_SUCCESS on success, no informational status code. * @retval VERR_DBG_NO_SYMBOLS if there aren't any symbols. * @retval VERR_SYMBOL_NOT_FOUND if no suitable symbol was found. * * @param pMod Pointer to the module structure. * @param iSeg The segment number (0-based) or RTDBGSEGIDX_ABS. * @param off The offset into the segment. * @param fFlags Symbol search flags, see RTDBGSYMADDR_FLAGS_XXX. * @param poffDisp Where to store the distance between the specified address * and the returned symbol. Optional. * @param pSymInfo Where to store the symbol information. */ DECLCALLBACKMEMBER(int, pfnSymbolByAddr)(PRTDBGMODINT pMod, uint32_t iSeg, RTUINTPTR off, uint32_t fFlags, PRTINTPTR poffDisp, PRTDBGSYMBOL pSymInfo); /** * Adds a line number to the module (optional). * * @returns IPRT status code. * @retval VERR_NOT_SUPPORTED if the interpreter doesn't support this feature. * * @param pMod Pointer to the module structure. * @param pszFile The filename. * @param cchFile The length of the filename. * @param uLineNo The line number. * @param iSeg The segment number (0-based). * @param off The offset into the segment. * @param piOrdinal Where to return the line number ordinal on success. If * the interpreter doesn't do ordinals, this will be set to * UINT32_MAX. Optional */ DECLCALLBACKMEMBER(int, pfnLineAdd)(PRTDBGMODINT pMod, const char *pszFile, size_t cchFile, uint32_t uLineNo, uint32_t iSeg, RTUINTPTR off, uint32_t *piOrdinal); /** * Gets the number of line numbers in the module. * * @returns The number or UINT32_MAX if not known/supported. * * @param pMod Pointer to the module structure. */ DECLCALLBACKMEMBER(uint32_t, pfnLineCount)(PRTDBGMODINT pMod); /** * Queries line number information by ordinal number. * * @returns IPRT status code. * @retval VINF_SUCCESS on success, no informational status code. * @retval VERR_DBG_NO_LINE_NUMBERS if there aren't any line numbers. * @retval VERR_DBG_LINE_NOT_FOUND if there is no line number with that * ordinal. * * @param pMod Pointer to the module structure. * @param iOrdinal The line number ordinal number. * @param pLineInfo Where to store the information about the line number. */ DECLCALLBACKMEMBER(int, pfnLineByOrdinal)(PRTDBGMODINT pMod, uint32_t iOrdinal, PRTDBGLINE pLineInfo); /** * Queries line number information by address. * * @returns IPRT status code. * @retval VINF_SUCCESS on success, no informational status code. * @retval VERR_DBG_NO_LINE_NUMBERS if there aren't any line numbers. * @retval VERR_DBG_LINE_NOT_FOUND if no suitable line number was found. * * @param pMod Pointer to the module structure. * @param iSeg The segment number (0-based) or RTDBGSEGIDX_ABS. * @param off The offset into the segment. * @param poffDisp Where to store the distance between the specified address * and the returned line number. Optional. * @param pLineInfo Where to store the information about the closest line * number. */ DECLCALLBACKMEMBER(int, pfnLineByAddr)(PRTDBGMODINT pMod, uint32_t iSeg, RTUINTPTR off, PRTINTPTR poffDisp, PRTDBGLINE pLineInfo); /** For catching initialization errors (RTDBGMODVTDBG_MAGIC). */ uint32_t u32EndMagic; } RTDBGMODVTDBG; /** Pointer to a const RTDBGMODVTDBG. */ typedef RTDBGMODVTDBG const *PCRTDBGMODVTDBG; /** * Deferred loading callback. * * @returns IPRT status code. On success the necessary method tables should be * installed in @a pMod. * @param pMod Pointer to the debug module structure. * @param pDeferred The deferred load data. */ typedef DECLCALLBACK(int) FNRTDBGMODDEFERRED(PRTDBGMODINT pMod, struct RTDBGMODDEFERRED *pDeferred); /** Pointer to a deferred loading callback. */ typedef FNRTDBGMODDEFERRED *PFNRTDBGMODDEFERRED; /** * Structure pointed to by pvDbgPriv and/or pvImgPriv when * g_rtDbgModVtDbgDeferred and/or g_rtDbgModVtImgDeferred are being used. */ typedef struct RTDBGMODDEFERRED { /** The image size. * Deferred loading is almost pointless without knowing the module size, as * it cannot be mapped (correctly) without it. */ RTUINTPTR cbImage; /** Reference counter. */ uint32_t volatile cRefs; /** The configuration instance (referenced), can be NIL. */ RTDBGCFG hDbgCfg; /** Performs deferred loading of the module. */ PFNRTDBGMODDEFERRED pfnDeferred; /** Callback specific data. */ union { struct { /** The time/date stamp of the executable image and codeview file. */ uint32_t uTimestamp; } PeImage, OldCodeView; struct { /** The PDB uuid. */ RTUUID Uuid; /** The PDB age. */ uint32_t uAge; } NewCodeview; struct { /** The CRC-32 value found in the .gnu_debuglink section. */ uint32_t uCrc32; } GnuDebugLink; struct { /** The image UUID. */ RTUUID Uuid; /** Image architecture. */ RTLDRARCH enmArch; /** Number of segment mappings. */ uint32_t cSegs; /** Segment mappings. */ RTDBGSEGMENT aSegs[1]; } MachO; } u; } RTDBGMODDEFERRED; /** Pointer to the deferred loading data. */ typedef RTDBGMODDEFERRED *PRTDBGMODDEFERRED; /** * Debug module structure. */ typedef struct RTDBGMODINT { /** Magic value (RTDBGMOD_MAGIC). */ uint32_t u32Magic; /** The number of reference there are to this module. * This is used to perform automatic cleanup and sharing. */ uint32_t volatile cRefs; /** The module tag. */ uint64_t uTag; /** When set, the loading of the image and debug info (including locating any * external files), will not have taken place yet. */ uint32_t fDeferred : 1; /** Set if deferred loading failed. */ uint32_t fDeferredFailed : 1; /** Set if the debug info is based on image exports and segments. */ uint32_t fExports : 1; /** Alignment padding. */ uint32_t fPadding1 : 29; #if ARCH_BITS == 64 uint32_t u32Padding2; #endif /** The module name (short). */ char const *pszName; /** The image file specified by the user. Can be NULL. */ char const *pszImgFileSpecified; /** The module filename. Can be NULL. */ char const *pszImgFile; /** The debug info file (if external). Can be NULL. */ char const *pszDbgFile; /** The method table for the executable image interpreter. */ PCRTDBGMODVTIMG pImgVt; /** Pointer to the private data of the executable image interpreter. */ void *pvImgPriv; /** The method table for the debug info interpreter. */ PCRTDBGMODVTDBG pDbgVt; /** Pointer to the private data of the debug info interpreter. */ void *pvDbgPriv; /** Critical section serializing access to the module. */ RTCRITSECT CritSect; } RTDBGMODINT; /** Pointer to an debug module structure. */ typedef RTDBGMODINT *PRTDBGMODINT; extern DECLHIDDEN(RTSTRCACHE) g_hDbgModStrCache; extern DECLHIDDEN(RTDBGMODVTDBG const) g_rtDbgModVtDbgCodeView; extern DECLHIDDEN(RTDBGMODVTDBG const) g_rtDbgModVtDbgDwarf; extern DECLHIDDEN(RTDBGMODVTDBG const) g_rtDbgModVtDbgNm; #ifdef RT_OS_WINDOWS extern DECLHIDDEN(RTDBGMODVTDBG const) g_rtDbgModVtDbgDbgHelp; #endif extern DECLHIDDEN(RTDBGMODVTDBG const) g_rtDbgModVtDbgDeferred; extern DECLHIDDEN(RTDBGMODVTDBG const) g_rtDbgModVtDbgContainer; extern DECLHIDDEN(RTDBGMODVTIMG const) g_rtDbgModVtImgLdr; extern DECLHIDDEN(RTDBGMODVTIMG const) g_rtDbgModVtImgDeferred; DECLHIDDEN(int) rtDbgModContainerCreate(PRTDBGMODINT pMod, RTUINTPTR cbSeg); DECLHIDDEN(int) rtDbgModContainer_SymbolRemoveAll(PRTDBGMODINT pMod); DECLHIDDEN(int) rtDbgModContainer_LineRemoveAll(PRTDBGMODINT pMod); DECLHIDDEN(int) rtDbgModContainer_RemoveAll(PRTDBGMODINT pMod); DECLHIDDEN(int) rtDbgModCreateForExports(PRTDBGMODINT pDbgMod); DECLHIDDEN(int) rtDbgModDeferredCreate(PRTDBGMODINT pDbgMod, PFNRTDBGMODDEFERRED pfnDeferred, RTUINTPTR cbImage, RTDBGCFG hDbgCfg, size_t cbDeferred, PRTDBGMODDEFERRED *ppDeferred); DECLHIDDEN(int) rtDbgModLdrOpenFromHandle(PRTDBGMODINT pDbgMod, RTLDRMOD hLdrMod); /** @} */ RT_C_DECLS_END #endif
mirror/vbox
src/VBox/Runtime/include/internal/dbgmod.h
C
gpl-2.0
26,363
// VAST ads plugin // Sponsored by Minoto Video // 2013/02/01 0.5 research // 2013/02/09 1.5 build loading mechanism // 2013/02/10 2.5 events to play preroll, skip function, start/end calls, \ // 2013/02/11 2 click events // ---- // 2013/02/23 3.5 split into a generic pre-roll plugin (function($) { // on time insert into head $('head').append($('<style>' + '.' + t.options.classPrefix + 'ads a {' + ' display: block; ' + ' position: absolute;' + ' right: 0;' + ' top: 0;' + ' width: 100%; ' + ' height: 100%; ' + ' display: block; ' + '}' + '.' + t.options.classPrefix + 'ads .' + t.options.classPrefix + 'ads-skip-block {' + ' display: block; ' + ' position: absolute;' + ' right: 0;' + ' top: 0;' + ' padding: 10px; ' + ' background: #000; ' + ' background: rgba(0,0,0,0.5); ' + ' color: #fff; ' + '}' + '.' + t.options.classPrefix + 'ads .' + t.options.classPrefix + 'ads-skip-button {' + ' cursor: pointer; ' + '}' + '.' + t.options.classPrefix + 'ads .' + t.options.classPrefix + 'ads-skip-button:hover {' + ' text-decoration: underline; ' + '}' + '</style>')); $.extend(mejs.MepDefaults, { // URL to a media file adsPrerollMediaUrl: [], // URL for lcicking ad adsPrerollAdUrl: [], // if true, allows user to skip the pre-roll ad adsPrerollAdEnableSkip: false, // if adsPrerollAdEnableSkip=true and this is a positive number, it will only allow skipping after the time has elasped adsPrerollAdSkipSeconds: -1, // keep track of the index for the preroll ads to be able to show more than one preroll. Used for // VAST3.0 Adpods indexPreroll: 0, }); $.extend(MediaElementPlayer.prototype, { // allows other plugins to all this one adsLoaded: false, // prevents playback in until async ad data is ready (e.g. VAST) adsDataIsLoading: false, // stores the main media URL when an ad is playing adsCurrentMediaUrl: '', adsCurrentMediaDuration: 0, // true when the user clicks play for the first time, or if autoplay is set adsPlayerHasStarted: false, buildads: function(player, controls, layers, media) { var t = this; if (t.adsLoaded) { return; } else { t.adsLoaded = true; } // add layer for ad links and skipping player.adsLayer = $('<div class="' + t.options.classPrefix + 'layer ' + t.options.classPrefix + 'overlay ' + t.options.classPrefix + 'ads">' + '<a href="#" target="_blank">&nbsp;</a>' + '<div class="' + t.options.classPrefix + 'ads-skip-block">' + '<span class="' + t.options.classPrefix + 'ads-skip-message"></span>' + '<span class="' + t.options.classPrefix + 'ads-skip-button">' + mejs.i18n.t('mejs.ad-skip') + '&raquo;' + '</span>' + '</div>' + '</div>') .insertBefore( layers.find('.' + t.options.classPrefix + 'overlay-play') ) .hide(); player.adsLayer.find('a') .on('click', $.proxy(t.adsAdClick, t) ); player.adsSkipBlock = player.adsLayer.find('.' + t.options.classPrefix + 'ads-skip-block') .hide(); player.adsSkipMessage = player.adsLayer.find('.' + t.options.classPrefix + 'ads-skip-message') .hide(); player.adsSkipButton = player.adsLayer.find('.' + t.options.classPrefix + 'ads-skip-button') .on('click', $.proxy(t.adsSkipClick, t)); // create proxies (only needed for events we want to remove later) t.adsMediaTryingToStartProxy = $.proxy(t.adsMediaTryingToStart, t); t.adsPrerollStartedProxy = $.proxy(t.adsPrerollStarted, t); t.adsPrerollMetaProxy = $.proxy(t.adsPrerollMeta, t); t.adsPrerollUpdateProxy = $.proxy(t.adsPrerollUpdate, t); t.adsPrerollEndedProxy = $.proxy(t.adsPrerollEnded, t); // check for start t.media.addEventListener('play', t.adsMediaTryingToStartProxy ); t.media.addEventListener('playing', t.adsMediaTryingToStartProxy ); t.media.addEventListener('canplay', t.adsMediaTryingToStartProxy ); t.media.addEventListener('loadedmetadata', t.adsMediaTryingToStartProxy ); if (t.options.indexPreroll < t.options.adsPrerollMediaUrl.length) { t.adsStartPreroll(); } }, adsMediaTryingToStart: function() { var t = this; // make sure to pause until the ad data is loaded if (t.adsDataIsLoading && !t.media.paused) { t.media.pause(); } t.adsPlayerHasStarted = true; }, adsStartPreroll: function() { var t = this; t.media.addEventListener('loadedmetadata', t.adsPrerollMetaProxy ); t.media.addEventListener('playing', t.adsPrerollStartedProxy ); t.media.addEventListener('ended', t.adsPrerollEndedProxy ); t.media.addEventListener('timeupdate', t.adsPrerollUpdateProxy ); // change URLs to the preroll ad. Only save the video to be shown on first // ad showing. if (t.options.indexPreroll === 0) { t.adsCurrentMediaUrl = t.media.src; t.adsCurrentMediaDuration = t.media.duration; } t.media.setSrc(t.options.adsPrerollMediaUrl[t.options.indexPreroll]); t.media.load(); // if autoplay was on, or if the user pressed play // while the ad data was still loading, then start the ad right away if (t.adsPlayerHasStarted) { t.media.play(); } }, adsPrerollMeta: function() { var t = this, newDuration = 0 ; // if duration has been set, show that if (t.options.duration > 0) { newDuration = t.options.duration; } else if (!isNaN(t.adsCurrentMediaDuration)) { newDuration = t.adsCurrentMediaDuration; } setTimeout(function() { t.controls.find('.' + t.options.classPrefix + 'duration').html( mejs.Utility.secondsToTimeCode(newDuration, t.options.alwaysShowHours) ); }, 250); }, adsPrerollStarted: function() { var t = this; t.media.removeEventListener('playing', t.adsPrerollStartedProxy); // turn off controls until the preroll is done t.disableControls(); // enable clicking through t.adsLayer.show(); if (t.options.adsPrerollAdUrl[t.options.indexPreroll] !== '') { t.adsLayer.find('a').attr('href', t.options.adsPrerollAdUrl[t.options.indexPreroll]); } else { t.adsLayer.find('a').attr('href', '#'); t.adsLayer.find('a').attr('target', ''); } // possibly allow the skip button to work if (t.options.adsPrerollAdEnableSkip) { t.adsSkipBlock.show(); if (t.options.adsPrerollAdSkipSeconds > 0) { t.adsSkipMessage.html( mejs.i18n.t('mejs.ad-skip-info').replace('%1', t.options.adsPrerollAdSkipSeconds.toString()) ).show(); t.adsSkipButton.hide(); } else { t.adsSkipMessage.hide(); t.adsSkipButton.show(); } } else { t.adsSkipBlock.hide(); } // send click events t.container.trigger('mejsprerollstarted'); }, adsPrerollUpdate: function() { var t = this; if (t.options.adsPrerollAdEnableSkip && t.options.adsPrerollAdSkipSeconds > 0) { // update message if (t.media.currentTime > t.options.adsPrerollAdSkipSeconds) { t.adsSkipButton.show(); t.adsSkipMessage.hide(); } else { t.adsSkipMessage.html(mejs.i18n.t('mejs.ad-skip-info').replace('%1', Math.round( t.options.adsPrerollAdSkipSeconds - t.media.currentTime ).toString()) ); } } t.container.trigger('mejsprerolltimeupdate'); }, adsPrerollEnded: function() { var t = this; t.container.trigger('mejsprerollended'); t.options.indexPreroll++; if (t.options.indexPreroll < t.options.adsPrerollMediaUrl.length) { t.adsStartPreroll(); } else { t.adRestoreMainMedia(); } }, adRestoreMainMedia: function() { var t = this; t.media.setSrc(t.adsCurrentMediaUrl); setTimeout(function() { t.media.load(); t.media.play(); }, 10); t.enableControls(); t.adsLayer.hide(); t.media.removeEventListener('ended', t.adsPrerollEndedProxy); t.media.removeEventListener('loadedmetadata', t.adsPrerollMetaProxy); t.media.removeEventListener('timeupdate', t.adsPrerollUpdateProxy); t.container.trigger('mejsprerollmainstarted'); }, adsAdClick: function(e) { var t = this; if (t.media.paused) { t.media.play(); } else { t.media.pause(); } t.container.trigger('mejsprerolladsclicked'); }, adsSkipClick: function() { var t = this; t.container.trigger('mejsprerollskipclicked'); t.container.trigger('mejsprerollended'); t.options.indexPreroll++; if (t.options.indexPreroll < t.options.adsPrerollMediaUrl.length) { t.adsStartPreroll(); } else { t.adRestoreMainMedia(); } }, // tells calling function if ads have finished running prerollAdsFinished: function() { var t = this; return t.options.indexPreroll === t.options.adsPrerollMediaUrl.length; }, // fires off fake XHR requests adsLoadUrl: function(url) { var img = new Image(), rnd = Math.round(Math.random()*100000); img.src = url + ((url.indexOf('?') > 0) ? '&' : '?') + 'random' + rnd + '=' + rnd; img.loaded = function() { img = null; }; } }); })(mejs.$);
carleton/reasoncms
www/mediaelement/src/js/mediaelementplayer-feature-ads.js
JavaScript
gpl-2.0
8,971
<?php if(isset($vars['Path'])) $Path = $vars['Path']; else $vars['Path'] = $Path = $vars['Query']; $info = Info::getInfos($Path); $o = genericClass::createInstance($info['Module'], $info['ObjectType']); $o->setView(); $vars['identifier'] = $info['Module'] . $info['ObjectType']; $vars['ObjectClass'] = $o->getObjectClass(); $vars['ObjectType'] = $info['ObjectType']; $vars['Module'] = $info['Module']; $vars['ObjectType'] = $info['ObjectType']; $temp = $o->getElementsByAttribute('', '', true); $fields = Array(); foreach($temp as $k => $field) { $fields[$field['name']] = $field; } $vars['fields'] = $fields; if(is_object(Sys::$CurrentMenu)) $vars['CurrentUrl'] = Sys::getMenu($info['Module'] . '/' . $info['ObjectType']); else $vars['CurrentUrl'] = $Path; if(!isset($info['ObjectType'])) { $tab = explode('/', $info['Query']); array_push($tab, 'Form'); } else { $tab = array($info['Module'], $info['ObjectType'], 'Form'); } $vars['tempContext'] = isset($_GET['tempContext']) && $_GET['tempContext']; $vars['Annee'] = Cadref::$Annee; $vars['Type'] = 'Inscription'; ?>
MAN-IN-WAN/Kob-Eye
Skins/AngularAdmin/Modules/Cadref/Default/PublicListInscr.twig.php
PHP
gpl-2.0
1,076
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.6"/> <title>CORE POS - IS4C: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { if ($('.searchresults').length > 0) { searchBox.DOMSearchField().focus(); } }); </script> <link rel="search" href="search-opensearch.php?v=opensearch.xml" type="application/opensearchdescription+xml" title="CORE POS - IS4C"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">CORE POS - IS4C </div> <div id="projectbrief">The CORE POS front end</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <div class="left"> <form id="FSearchBox" action="search.php" method="get"> <img id="MSearchSelect" src="search/mag.png" alt=""/> <input type="text" id="MSearchField" name="query" value="Search" size="20" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)"/> </form> </div><div class="right"></div> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><b>COREPOS</b></li><li class="navelem"><b>pos</b></li><li class="navelem"><b>lib</b></li><li class="navelem"><b>Tenders</b></li><li class="navelem"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_rebate_check_tender.html">RebateCheckTender</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">COREPOS\pos\lib\Tenders\RebateCheckTender Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_rebate_check_tender.html">COREPOS\pos\lib\Tenders\RebateCheckTender</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$amount</b> (defined in <a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a>)</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>$change_string</b> (defined in <a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a>)</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$change_type</b> (defined in <a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a>)</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>$max_limit</b> (defined in <a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a>)</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$min_limit</b> (defined in <a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a>)</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>$name_string</b> (defined in <a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a>)</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$tender_code</b> (defined in <a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a>)</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html#ad33d3a5b4e90701aa575fbe20d060fed">__construct</a>($code, $amt)</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>add</b>() (defined in <a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_rebate_check_tender.html">COREPOS\pos\lib\Tenders\RebateCheckTender</a>)</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_rebate_check_tender.html">COREPOS\pos\lib\Tenders\RebateCheckTender</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>allowDefault</b>() (defined in <a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_rebate_check_tender.html">COREPOS\pos\lib\Tenders\RebateCheckTender</a>)</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_rebate_check_tender.html">COREPOS\pos\lib\Tenders\RebateCheckTender</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html#a29ea225534c708cdce38440e57943de1">changeMsg</a>()</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html#a29f5ab0227663acbe446cbe7d2f44106">changeType</a>()</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>defaultPrompt</b>() (defined in <a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_rebate_check_tender.html">COREPOS\pos\lib\Tenders\RebateCheckTender</a>)</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_rebate_check_tender.html">COREPOS\pos\lib\Tenders\RebateCheckTender</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html#afdcfb30ea0c5dcf8d490981f09dd6a00">defaultTotal</a>()</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html#af7c81e86bd2f79c8ba2715ddf703385b">disabledPrompt</a>()</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_rebate_check_tender.html#af660854fc3ee96c4b2add887b3eb91d1">errorCheck</a>()</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_rebate_check_tender.html">COREPOS\pos\lib\Tenders\RebateCheckTender</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>frankingPrompt</b>() (defined in <a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a>)</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_tender_module.html">COREPOS\pos\lib\Tenders\TenderModule</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_rebate_check_tender.html#ae6fc85ecbd9d34b152848b3d9be5ba61">preReqCheck</a>()</td><td class="entry"><a class="el" href="class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_rebate_check_tender.html">COREPOS\pos\lib\Tenders\RebateCheckTender</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Fri Sep 2 2016 11:30:51 for CORE POS - IS4C by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.6 </small></address> </body> </html>
hayes042/IS4C
documentation/doxy/output/is4c-nf/html/class_c_o_r_e_p_o_s_1_1pos_1_1lib_1_1_tenders_1_1_rebate_check_tender-members.html
HTML
gpl-2.0
11,367
/* Copyright (c) 2000, 2001, 2005-2007 MySQL AB 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include "myisamdef.h" /* Read first row through a specfic key */ int mi_rfirst(MI_INFO *info, uchar *buf, int inx) { DBUG_ENTER("mi_rfirst"); info->lastpos= HA_OFFSET_ERROR; info->update|= HA_STATE_PREV_FOUND; DBUG_RETURN(mi_rnext(info,buf,inx)); } /* mi_rfirst */
Abner-Sun/vx_mysql5.1_git
storage/myisam/mi_rfirst.c
C
gpl-2.0
997
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * ROUTE - implementation of the IP router. * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Alan Cox, <gw4pts@gw4pts.ampr.org> * Linus Torvalds, <Linus.Torvalds@helsinki.fi> * Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru> * * Fixes: * Alan Cox : Verify area fixes. * Alan Cox : cli() protects routing changes * Rui Oliveira : ICMP routing table updates * (rco@di.uminho.pt) Routing table insertion and update * Linus Torvalds : Rewrote bits to be sensible * Alan Cox : Added BSD route gw semantics * Alan Cox : Super /proc >4K * Alan Cox : MTU in route table * Alan Cox : MSS actually. Also added the window * clamper. * Sam Lantinga : Fixed route matching in rt_del() * Alan Cox : Routing cache support. * Alan Cox : Removed compatibility cruft. * Alan Cox : RTF_REJECT support. * Alan Cox : TCP irtt support. * Jonathan Naylor : Added Metric support. * Miquel van Smoorenburg : BSD API fixes. * Miquel van Smoorenburg : Metrics. * Alan Cox : Use __u32 properly * Alan Cox : Aligned routing errors more closely with BSD * our system is still very different. * Alan Cox : Faster /proc handling * Alexey Kuznetsov : Massive rework to support tree based routing, * routing caches and better behaviour. * * Olaf Erb : irtt wasn't being copied right. * Bjorn Ekwall : Kerneld route support. * Alan Cox : Multicast fixed (I hope) * Pavel Krauz : Limited broadcast fixed * Mike McLagan : Routing by source * Alexey Kuznetsov : End of old history. Split to fib.c and * route.c and rewritten from scratch. * Andi Kleen : Load-limit warning messages. * Vitaly E. Lavrov : Transparent proxy revived after year coma. * Vitaly E. Lavrov : Race condition in ip_route_input_slow. * Tobias Ringstrom : Uninitialized res.type in ip_route_output_slow. * Vladimir V. Ivanov : IP rule info (flowid) is really useful. * Marc Boucher : routing by fwmark * Robert Olsson : Added rt_cache statistics * Arnaldo C. Melo : Convert proc stuff to seq_file * Eric Dumazet : hashed spinlocks and rt_check_expire() fixes. * Ilia Sotnikov : Ignore TOS on PMTUD and Redirect * Ilia Sotnikov : Removed TOS from hash calculations * * 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. */ #define pr_fmt(fmt) "IPv4: " fmt #include <linux/module.h> #include <asm/uaccess.h> #include <linux/bitops.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/string.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/errno.h> #include <linux/in.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/proc_fs.h> #include <linux/init.h> #include <linux/skbuff.h> #include <linux/inetdevice.h> #include <linux/igmp.h> #include <linux/pkt_sched.h> #include <linux/mroute.h> #include <linux/netfilter_ipv4.h> #include <linux/random.h> #include <linux/rcupdate.h> #include <linux/times.h> #include <linux/slab.h> #include <linux/jhash.h> #include <net/dst.h> #include <net/dst_metadata.h> #include <net/net_namespace.h> #include <net/protocol.h> #include <net/ip.h> #include <net/route.h> #include <net/inetpeer.h> #include <net/sock.h> #include <net/ip_fib.h> #include <net/arp.h> #include <net/tcp.h> #include <net/icmp.h> #include <net/xfrm.h> #include <net/lwtunnel.h> #include <net/netevent.h> #include <net/rtnetlink.h> #ifdef CONFIG_SYSCTL #include <linux/sysctl.h> #include <linux/kmemleak.h> #endif #include <net/secure_seq.h> #include <net/ip_tunnels.h> #include <net/l3mdev.h> #define RT_FL_TOS(oldflp4) \ ((oldflp4)->flowi4_tos & (IPTOS_RT_MASK | RTO_ONLINK)) #define RT_GC_TIMEOUT (300*HZ) static int ip_rt_max_size; static int ip_rt_redirect_number __read_mostly = 9; static int ip_rt_redirect_load __read_mostly = HZ / 50; static int ip_rt_redirect_silence __read_mostly = ((HZ / 50) << (9 + 1)); static int ip_rt_error_cost __read_mostly = HZ; static int ip_rt_error_burst __read_mostly = 5 * HZ; static int ip_rt_mtu_expires __read_mostly = 10 * 60 * HZ; static int ip_rt_min_pmtu __read_mostly = 512 + 20 + 20; static int ip_rt_min_advmss __read_mostly = 256; static int ip_rt_gc_timeout __read_mostly = RT_GC_TIMEOUT; /* * Interface to generic destination cache. */ static struct dst_entry *ipv4_dst_check(struct dst_entry *dst, u32 cookie); static unsigned int ipv4_default_advmss(const struct dst_entry *dst); static unsigned int ipv4_mtu(const struct dst_entry *dst); static struct dst_entry *ipv4_negative_advice(struct dst_entry *dst); static void ipv4_link_failure(struct sk_buff *skb); static void ip_rt_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu); static void ip_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb); static void ipv4_dst_destroy(struct dst_entry *dst); static u32 *ipv4_cow_metrics(struct dst_entry *dst, unsigned long old) { WARN_ON(1); return NULL; } static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst, struct sk_buff *skb, const void *daddr); static struct dst_ops ipv4_dst_ops = { .family = AF_INET, .check = ipv4_dst_check, .default_advmss = ipv4_default_advmss, .mtu = ipv4_mtu, .cow_metrics = ipv4_cow_metrics, .destroy = ipv4_dst_destroy, .negative_advice = ipv4_negative_advice, .link_failure = ipv4_link_failure, .update_pmtu = ip_rt_update_pmtu, .redirect = ip_do_redirect, .local_out = __ip_local_out, .neigh_lookup = ipv4_neigh_lookup, }; #define ECN_OR_COST(class) TC_PRIO_##class const __u8 ip_tos2prio[16] = { TC_PRIO_BESTEFFORT, ECN_OR_COST(BESTEFFORT), TC_PRIO_BESTEFFORT, ECN_OR_COST(BESTEFFORT), TC_PRIO_BULK, ECN_OR_COST(BULK), TC_PRIO_BULK, ECN_OR_COST(BULK), TC_PRIO_INTERACTIVE, ECN_OR_COST(INTERACTIVE), TC_PRIO_INTERACTIVE, ECN_OR_COST(INTERACTIVE), TC_PRIO_INTERACTIVE_BULK, ECN_OR_COST(INTERACTIVE_BULK), TC_PRIO_INTERACTIVE_BULK, ECN_OR_COST(INTERACTIVE_BULK) }; EXPORT_SYMBOL(ip_tos2prio); static DEFINE_PER_CPU(struct rt_cache_stat, rt_cache_stat); #define RT_CACHE_STAT_INC(field) raw_cpu_inc(rt_cache_stat.field) #ifdef CONFIG_PROC_FS static void *rt_cache_seq_start(struct seq_file *seq, loff_t *pos) { if (*pos) return NULL; return SEQ_START_TOKEN; } static void *rt_cache_seq_next(struct seq_file *seq, void *v, loff_t *pos) { ++*pos; return NULL; } static void rt_cache_seq_stop(struct seq_file *seq, void *v) { } static int rt_cache_seq_show(struct seq_file *seq, void *v) { if (v == SEQ_START_TOKEN) seq_printf(seq, "%-127s\n", "Iface\tDestination\tGateway \tFlags\t\tRefCnt\tUse\t" "Metric\tSource\t\tMTU\tWindow\tIRTT\tTOS\tHHRef\t" "HHUptod\tSpecDst"); return 0; } static const struct seq_operations rt_cache_seq_ops = { .start = rt_cache_seq_start, .next = rt_cache_seq_next, .stop = rt_cache_seq_stop, .show = rt_cache_seq_show, }; static int rt_cache_seq_open(struct inode *inode, struct file *file) { return seq_open(file, &rt_cache_seq_ops); } static const struct file_operations rt_cache_seq_fops = { .owner = THIS_MODULE, .open = rt_cache_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static void *rt_cpu_seq_start(struct seq_file *seq, loff_t *pos) { int cpu; if (*pos == 0) return SEQ_START_TOKEN; for (cpu = *pos-1; cpu < nr_cpu_ids; ++cpu) { if (!cpu_possible(cpu)) continue; *pos = cpu+1; return &per_cpu(rt_cache_stat, cpu); } return NULL; } static void *rt_cpu_seq_next(struct seq_file *seq, void *v, loff_t *pos) { int cpu; for (cpu = *pos; cpu < nr_cpu_ids; ++cpu) { if (!cpu_possible(cpu)) continue; *pos = cpu+1; return &per_cpu(rt_cache_stat, cpu); } return NULL; } static void rt_cpu_seq_stop(struct seq_file *seq, void *v) { } static int rt_cpu_seq_show(struct seq_file *seq, void *v) { struct rt_cache_stat *st = v; if (v == SEQ_START_TOKEN) { seq_printf(seq, "entries in_hit in_slow_tot in_slow_mc in_no_route in_brd in_martian_dst in_martian_src out_hit out_slow_tot out_slow_mc gc_total gc_ignored gc_goal_miss gc_dst_overflow in_hlist_search out_hlist_search\n"); return 0; } seq_printf(seq,"%08x %08x %08x %08x %08x %08x %08x %08x " " %08x %08x %08x %08x %08x %08x %08x %08x %08x \n", dst_entries_get_slow(&ipv4_dst_ops), 0, /* st->in_hit */ st->in_slow_tot, st->in_slow_mc, st->in_no_route, st->in_brd, st->in_martian_dst, st->in_martian_src, 0, /* st->out_hit */ st->out_slow_tot, st->out_slow_mc, 0, /* st->gc_total */ 0, /* st->gc_ignored */ 0, /* st->gc_goal_miss */ 0, /* st->gc_dst_overflow */ 0, /* st->in_hlist_search */ 0 /* st->out_hlist_search */ ); return 0; } static const struct seq_operations rt_cpu_seq_ops = { .start = rt_cpu_seq_start, .next = rt_cpu_seq_next, .stop = rt_cpu_seq_stop, .show = rt_cpu_seq_show, }; static int rt_cpu_seq_open(struct inode *inode, struct file *file) { return seq_open(file, &rt_cpu_seq_ops); } static const struct file_operations rt_cpu_seq_fops = { .owner = THIS_MODULE, .open = rt_cpu_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #ifdef CONFIG_IP_ROUTE_CLASSID static int rt_acct_proc_show(struct seq_file *m, void *v) { struct ip_rt_acct *dst, *src; unsigned int i, j; dst = kcalloc(256, sizeof(struct ip_rt_acct), GFP_KERNEL); if (!dst) return -ENOMEM; for_each_possible_cpu(i) { src = (struct ip_rt_acct *)per_cpu_ptr(ip_rt_acct, i); for (j = 0; j < 256; j++) { dst[j].o_bytes += src[j].o_bytes; dst[j].o_packets += src[j].o_packets; dst[j].i_bytes += src[j].i_bytes; dst[j].i_packets += src[j].i_packets; } } seq_write(m, dst, 256 * sizeof(struct ip_rt_acct)); kfree(dst); return 0; } static int rt_acct_proc_open(struct inode *inode, struct file *file) { return single_open(file, rt_acct_proc_show, NULL); } static const struct file_operations rt_acct_proc_fops = { .owner = THIS_MODULE, .open = rt_acct_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #endif static int __net_init ip_rt_do_proc_init(struct net *net) { struct proc_dir_entry *pde; pde = proc_create("rt_cache", S_IRUGO, net->proc_net, &rt_cache_seq_fops); if (!pde) goto err1; pde = proc_create("rt_cache", S_IRUGO, net->proc_net_stat, &rt_cpu_seq_fops); if (!pde) goto err2; #ifdef CONFIG_IP_ROUTE_CLASSID pde = proc_create("rt_acct", 0, net->proc_net, &rt_acct_proc_fops); if (!pde) goto err3; #endif return 0; #ifdef CONFIG_IP_ROUTE_CLASSID err3: remove_proc_entry("rt_cache", net->proc_net_stat); #endif err2: remove_proc_entry("rt_cache", net->proc_net); err1: return -ENOMEM; } static void __net_exit ip_rt_do_proc_exit(struct net *net) { remove_proc_entry("rt_cache", net->proc_net_stat); remove_proc_entry("rt_cache", net->proc_net); #ifdef CONFIG_IP_ROUTE_CLASSID remove_proc_entry("rt_acct", net->proc_net); #endif } static struct pernet_operations ip_rt_proc_ops __net_initdata = { .init = ip_rt_do_proc_init, .exit = ip_rt_do_proc_exit, }; static int __init ip_rt_proc_init(void) { return register_pernet_subsys(&ip_rt_proc_ops); } #else static inline int ip_rt_proc_init(void) { return 0; } #endif /* CONFIG_PROC_FS */ static inline bool rt_is_expired(const struct rtable *rth) { return rth->rt_genid != rt_genid_ipv4(dev_net(rth->dst.dev)); } void rt_cache_flush(struct net *net) { rt_genid_bump_ipv4(net); } static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst, struct sk_buff *skb, const void *daddr) { struct net_device *dev = dst->dev; const __be32 *pkey = daddr; const struct rtable *rt; struct neighbour *n; rt = (const struct rtable *) dst; if (rt->rt_gateway) pkey = (const __be32 *) &rt->rt_gateway; else if (skb) pkey = &ip_hdr(skb)->daddr; n = __ipv4_neigh_lookup(dev, *(__force u32 *)pkey); if (n) return n; return neigh_create(&arp_tbl, pkey, dev); } #define IP_IDENTS_SZ 2048u static atomic_t *ip_idents __read_mostly; static u32 *ip_tstamps __read_mostly; /* In order to protect privacy, we add a perturbation to identifiers * if one generator is seldom used. This makes hard for an attacker * to infer how many packets were sent between two points in time. */ u32 ip_idents_reserve(u32 hash, int segs) { u32 *p_tstamp = ip_tstamps + hash % IP_IDENTS_SZ; atomic_t *p_id = ip_idents + hash % IP_IDENTS_SZ; u32 old = ACCESS_ONCE(*p_tstamp); u32 now = (u32)jiffies; u32 delta = 0; if (old != now && cmpxchg(p_tstamp, old, now) == old) delta = prandom_u32_max(now - old); return atomic_add_return(segs + delta, p_id) - segs; } EXPORT_SYMBOL(ip_idents_reserve); void __ip_select_ident(struct net *net, struct iphdr *iph, int segs) { static u32 ip_idents_hashrnd __read_mostly; u32 hash, id; net_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd)); hash = jhash_3words((__force u32)iph->daddr, (__force u32)iph->saddr, iph->protocol ^ net_hash_mix(net), ip_idents_hashrnd); id = ip_idents_reserve(hash, segs); iph->id = htons(id); } EXPORT_SYMBOL(__ip_select_ident); static void __build_flow_key(struct flowi4 *fl4, const struct sock *sk, const struct iphdr *iph, int oif, u8 tos, u8 prot, u32 mark, int flow_flags) { if (sk) { const struct inet_sock *inet = inet_sk(sk); oif = sk->sk_bound_dev_if; mark = sk->sk_mark; tos = RT_CONN_FLAGS(sk); prot = inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol; } flowi4_init_output(fl4, oif, mark, tos, RT_SCOPE_UNIVERSE, prot, flow_flags, iph->daddr, iph->saddr, 0, 0); } static void build_skb_flow_key(struct flowi4 *fl4, const struct sk_buff *skb, const struct sock *sk) { const struct iphdr *iph = ip_hdr(skb); int oif = skb->dev->ifindex; u8 tos = RT_TOS(iph->tos); u8 prot = iph->protocol; u32 mark = skb->mark; __build_flow_key(fl4, sk, iph, oif, tos, prot, mark, 0); } static void build_sk_flow_key(struct flowi4 *fl4, const struct sock *sk) { const struct inet_sock *inet = inet_sk(sk); const struct ip_options_rcu *inet_opt; __be32 daddr = inet->inet_daddr; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; flowi4_init_output(fl4, sk->sk_bound_dev_if, sk->sk_mark, RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE, inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol, inet_sk_flowi_flags(sk), daddr, inet->inet_saddr, 0, 0); rcu_read_unlock(); } static void ip_rt_build_flow_key(struct flowi4 *fl4, const struct sock *sk, const struct sk_buff *skb) { if (skb) build_skb_flow_key(fl4, skb, sk); else build_sk_flow_key(fl4, sk); } static inline void rt_free(struct rtable *rt) { call_rcu(&rt->dst.rcu_head, dst_rcu_free); } static DEFINE_SPINLOCK(fnhe_lock); static void fnhe_flush_routes(struct fib_nh_exception *fnhe) { struct rtable *rt; rt = rcu_dereference(fnhe->fnhe_rth_input); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_input, NULL); rt_free(rt); } rt = rcu_dereference(fnhe->fnhe_rth_output); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_output, NULL); rt_free(rt); } } static struct fib_nh_exception *fnhe_oldest(struct fnhe_hash_bucket *hash) { struct fib_nh_exception *fnhe, *oldest; oldest = rcu_dereference(hash->chain); for (fnhe = rcu_dereference(oldest->fnhe_next); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (time_before(fnhe->fnhe_stamp, oldest->fnhe_stamp)) oldest = fnhe; } fnhe_flush_routes(oldest); return oldest; } static inline u32 fnhe_hashfun(__be32 daddr) { static u32 fnhe_hashrnd __read_mostly; u32 hval; net_get_random_once(&fnhe_hashrnd, sizeof(fnhe_hashrnd)); hval = jhash_1word((__force u32) daddr, fnhe_hashrnd); return hash_32(hval, FNHE_HASH_SHIFT); } static void fill_route_from_fnhe(struct rtable *rt, struct fib_nh_exception *fnhe) { rt->rt_pmtu = fnhe->fnhe_pmtu; rt->dst.expires = fnhe->fnhe_expires; if (fnhe->fnhe_gw) { rt->rt_flags |= RTCF_REDIRECTED; rt->rt_gateway = fnhe->fnhe_gw; rt->rt_uses_gateway = 1; } } static void update_or_create_fnhe(struct fib_nh *nh, __be32 daddr, __be32 gw, u32 pmtu, unsigned long expires) { struct fnhe_hash_bucket *hash; struct fib_nh_exception *fnhe; struct rtable *rt; unsigned int i; int depth; u32 hval = fnhe_hashfun(daddr); spin_lock_bh(&fnhe_lock); hash = rcu_dereference(nh->nh_exceptions); if (!hash) { hash = kzalloc(FNHE_HASH_SIZE * sizeof(*hash), GFP_ATOMIC); if (!hash) goto out_unlock; rcu_assign_pointer(nh->nh_exceptions, hash); } hash += hval; depth = 0; for (fnhe = rcu_dereference(hash->chain); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (fnhe->fnhe_daddr == daddr) break; depth++; } if (fnhe) { if (gw) fnhe->fnhe_gw = gw; if (pmtu) { fnhe->fnhe_pmtu = pmtu; fnhe->fnhe_expires = max(1UL, expires); } /* Update all cached dsts too */ rt = rcu_dereference(fnhe->fnhe_rth_input); if (rt) fill_route_from_fnhe(rt, fnhe); rt = rcu_dereference(fnhe->fnhe_rth_output); if (rt) fill_route_from_fnhe(rt, fnhe); } else { if (depth > FNHE_RECLAIM_DEPTH) fnhe = fnhe_oldest(hash); else { fnhe = kzalloc(sizeof(*fnhe), GFP_ATOMIC); if (!fnhe) goto out_unlock; fnhe->fnhe_next = hash->chain; rcu_assign_pointer(hash->chain, fnhe); } fnhe->fnhe_genid = fnhe_genid(dev_net(nh->nh_dev)); fnhe->fnhe_daddr = daddr; fnhe->fnhe_gw = gw; fnhe->fnhe_pmtu = pmtu; fnhe->fnhe_expires = expires; /* Exception created; mark the cached routes for the nexthop * stale, so anyone caching it rechecks if this exception * applies to them. */ rt = rcu_dereference(nh->nh_rth_input); if (rt) rt->dst.obsolete = DST_OBSOLETE_KILL; for_each_possible_cpu(i) { struct rtable __rcu **prt; prt = per_cpu_ptr(nh->nh_pcpu_rth_output, i); rt = rcu_dereference(*prt); if (rt) rt->dst.obsolete = DST_OBSOLETE_KILL; } } fnhe->fnhe_stamp = jiffies; out_unlock: spin_unlock_bh(&fnhe_lock); } static void __ip_do_redirect(struct rtable *rt, struct sk_buff *skb, struct flowi4 *fl4, bool kill_route) { __be32 new_gw = icmp_hdr(skb)->un.gateway; __be32 old_gw = ip_hdr(skb)->saddr; struct net_device *dev = skb->dev; struct in_device *in_dev; struct fib_result res; struct neighbour *n; struct net *net; switch (icmp_hdr(skb)->code & 7) { case ICMP_REDIR_NET: case ICMP_REDIR_NETTOS: case ICMP_REDIR_HOST: case ICMP_REDIR_HOSTTOS: break; default: return; } if (rt->rt_gateway != old_gw) return; in_dev = __in_dev_get_rcu(dev); if (!in_dev) return; net = dev_net(dev); if (new_gw == old_gw || !IN_DEV_RX_REDIRECTS(in_dev) || ipv4_is_multicast(new_gw) || ipv4_is_lbcast(new_gw) || ipv4_is_zeronet(new_gw)) goto reject_redirect; if (!IN_DEV_SHARED_MEDIA(in_dev)) { if (!inet_addr_onlink(in_dev, new_gw, old_gw)) goto reject_redirect; if (IN_DEV_SEC_REDIRECTS(in_dev) && ip_fib_check_default(new_gw, dev)) goto reject_redirect; } else { if (inet_addr_type(net, new_gw) != RTN_UNICAST) goto reject_redirect; } n = __ipv4_neigh_lookup(rt->dst.dev, new_gw); if (!n) n = neigh_create(&arp_tbl, &new_gw, rt->dst.dev); if (!IS_ERR(n)) { if (!(n->nud_state & NUD_VALID)) { neigh_event_send(n, NULL); } else { if (fib_lookup(net, fl4, &res, 0) == 0) { struct fib_nh *nh = &FIB_RES_NH(res); update_or_create_fnhe(nh, fl4->daddr, new_gw, 0, jiffies + ip_rt_gc_timeout); } if (kill_route) rt->dst.obsolete = DST_OBSOLETE_KILL; call_netevent_notifiers(NETEVENT_NEIGH_UPDATE, n); } neigh_release(n); } return; reject_redirect: #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev)) { const struct iphdr *iph = (const struct iphdr *) skb->data; __be32 daddr = iph->daddr; __be32 saddr = iph->saddr; net_info_ratelimited("Redirect from %pI4 on %s about %pI4 ignored\n" " Advised path = %pI4 -> %pI4\n", &old_gw, dev->name, &new_gw, &saddr, &daddr); } #endif ; } static void ip_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb) { struct rtable *rt; struct flowi4 fl4; const struct iphdr *iph = (const struct iphdr *) skb->data; int oif = skb->dev->ifindex; u8 tos = RT_TOS(iph->tos); u8 prot = iph->protocol; u32 mark = skb->mark; rt = (struct rtable *) dst; __build_flow_key(&fl4, sk, iph, oif, tos, prot, mark, 0); __ip_do_redirect(rt, skb, &fl4, true); } static struct dst_entry *ipv4_negative_advice(struct dst_entry *dst) { struct rtable *rt = (struct rtable *)dst; struct dst_entry *ret = dst; if (rt) { if (dst->obsolete > 0) { ip_rt_put(rt); ret = NULL; } else if ((rt->rt_flags & RTCF_REDIRECTED) || rt->dst.expires) { ip_rt_put(rt); ret = NULL; } } return ret; } /* * Algorithm: * 1. The first ip_rt_redirect_number redirects are sent * with exponential backoff, then we stop sending them at all, * assuming that the host ignores our redirects. * 2. If we did not see packets requiring redirects * during ip_rt_redirect_silence, we assume that the host * forgot redirected route and start to send redirects again. * * This algorithm is much cheaper and more intelligent than dumb load limiting * in icmp.c. * * NOTE. Do not forget to inhibit load limiting for redirects (redundant) * and "frag. need" (breaks PMTU discovery) in icmp.c. */ void ip_rt_send_redirect(struct sk_buff *skb) { struct rtable *rt = skb_rtable(skb); struct in_device *in_dev; struct inet_peer *peer; struct net *net; int log_martians; int vif; rcu_read_lock(); in_dev = __in_dev_get_rcu(rt->dst.dev); if (!in_dev || !IN_DEV_TX_REDIRECTS(in_dev)) { rcu_read_unlock(); return; } log_martians = IN_DEV_LOG_MARTIANS(in_dev); vif = l3mdev_master_ifindex_rcu(rt->dst.dev); rcu_read_unlock(); net = dev_net(rt->dst.dev); peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, vif, 1); if (!peer) { icmp_send(skb, ICMP_REDIRECT, ICMP_REDIR_HOST, rt_nexthop(rt, ip_hdr(skb)->daddr)); return; } /* No redirected packets during ip_rt_redirect_silence; * reset the algorithm. */ if (time_after(jiffies, peer->rate_last + ip_rt_redirect_silence)) peer->rate_tokens = 0; /* Too many ignored redirects; do not send anything * set dst.rate_last to the last seen redirected packet. */ if (peer->rate_tokens >= ip_rt_redirect_number) { peer->rate_last = jiffies; goto out_put_peer; } /* Check for load limit; set rate_last to the latest sent * redirect. */ if (peer->rate_tokens == 0 || time_after(jiffies, (peer->rate_last + (ip_rt_redirect_load << peer->rate_tokens)))) { __be32 gw = rt_nexthop(rt, ip_hdr(skb)->daddr); icmp_send(skb, ICMP_REDIRECT, ICMP_REDIR_HOST, gw); peer->rate_last = jiffies; ++peer->rate_tokens; #ifdef CONFIG_IP_ROUTE_VERBOSE if (log_martians && peer->rate_tokens == ip_rt_redirect_number) net_warn_ratelimited("host %pI4/if%d ignores redirects for %pI4 to %pI4\n", &ip_hdr(skb)->saddr, inet_iif(skb), &ip_hdr(skb)->daddr, &gw); #endif } out_put_peer: inet_putpeer(peer); } static int ip_error(struct sk_buff *skb) { struct in_device *in_dev = __in_dev_get_rcu(skb->dev); struct rtable *rt = skb_rtable(skb); struct inet_peer *peer; unsigned long now; struct net *net; bool send; int code; /* IP on this device is disabled. */ if (!in_dev) goto out; net = dev_net(rt->dst.dev); if (!IN_DEV_FORWARD(in_dev)) { switch (rt->dst.error) { case EHOSTUNREACH: IP_INC_STATS_BH(net, IPSTATS_MIB_INADDRERRORS); break; case ENETUNREACH: IP_INC_STATS_BH(net, IPSTATS_MIB_INNOROUTES); break; } goto out; } switch (rt->dst.error) { case EINVAL: default: goto out; case EHOSTUNREACH: code = ICMP_HOST_UNREACH; break; case ENETUNREACH: code = ICMP_NET_UNREACH; IP_INC_STATS_BH(net, IPSTATS_MIB_INNOROUTES); break; case EACCES: code = ICMP_PKT_FILTERED; break; } peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, l3mdev_master_ifindex(skb->dev), 1); send = true; if (peer) { now = jiffies; peer->rate_tokens += now - peer->rate_last; if (peer->rate_tokens > ip_rt_error_burst) peer->rate_tokens = ip_rt_error_burst; peer->rate_last = now; if (peer->rate_tokens >= ip_rt_error_cost) peer->rate_tokens -= ip_rt_error_cost; else send = false; inet_putpeer(peer); } if (send) icmp_send(skb, ICMP_DEST_UNREACH, code, 0); out: kfree_skb(skb); return 0; } static void __ip_rt_update_pmtu(struct rtable *rt, struct flowi4 *fl4, u32 mtu) { struct dst_entry *dst = &rt->dst; struct fib_result res; if (dst_metric_locked(dst, RTAX_MTU)) return; if (ipv4_mtu(dst) < mtu) return; if (mtu < ip_rt_min_pmtu) mtu = ip_rt_min_pmtu; if (rt->rt_pmtu == mtu && time_before(jiffies, dst->expires - ip_rt_mtu_expires / 2)) return; rcu_read_lock(); if (fib_lookup(dev_net(dst->dev), fl4, &res, 0) == 0) { struct fib_nh *nh = &FIB_RES_NH(res); update_or_create_fnhe(nh, fl4->daddr, 0, mtu, jiffies + ip_rt_mtu_expires); } rcu_read_unlock(); } static void ip_rt_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu) { struct rtable *rt = (struct rtable *) dst; struct flowi4 fl4; ip_rt_build_flow_key(&fl4, sk, skb); __ip_rt_update_pmtu(rt, &fl4, mtu); } void ipv4_update_pmtu(struct sk_buff *skb, struct net *net, u32 mtu, int oif, u32 mark, u8 protocol, int flow_flags) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; if (!mark) mark = IP4_REPLY_MARK(net, skb->mark); __build_flow_key(&fl4, NULL, iph, oif, RT_TOS(iph->tos), protocol, mark, flow_flags); rt = __ip_route_output_key(net, &fl4); if (!IS_ERR(rt)) { __ip_rt_update_pmtu(rt, &fl4, mtu); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_update_pmtu); static void __ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(&fl4, sk, iph, 0, 0, 0, 0, 0); if (!fl4.flowi4_mark) fl4.flowi4_mark = IP4_REPLY_MARK(sock_net(sk), skb->mark); rt = __ip_route_output_key(sock_net(sk), &fl4); if (!IS_ERR(rt)) { __ip_rt_update_pmtu(rt, &fl4, mtu); ip_rt_put(rt); } } void ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; struct dst_entry *odst = NULL; bool new = false; bh_lock_sock(sk); if (!ip_sk_accept_pmtu(sk)) goto out; odst = sk_dst_get(sk); if (sock_owned_by_user(sk) || !odst) { __ipv4_sk_update_pmtu(skb, sk, mtu); goto out; } __build_flow_key(&fl4, sk, iph, 0, 0, 0, 0, 0); rt = (struct rtable *)odst; if (odst->obsolete && !odst->ops->check(odst, 0)) { rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) goto out; new = true; } __ip_rt_update_pmtu((struct rtable *) rt->dst.path, &fl4, mtu); if (!dst_check(&rt->dst, 0)) { if (new) dst_release(&rt->dst); rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) goto out; new = true; } if (new) sk_dst_set(sk, &rt->dst); out: bh_unlock_sock(sk); dst_release(odst); } EXPORT_SYMBOL_GPL(ipv4_sk_update_pmtu); void ipv4_redirect(struct sk_buff *skb, struct net *net, int oif, u32 mark, u8 protocol, int flow_flags) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(&fl4, NULL, iph, oif, RT_TOS(iph->tos), protocol, mark, flow_flags); rt = __ip_route_output_key(net, &fl4); if (!IS_ERR(rt)) { __ip_do_redirect(rt, skb, &fl4, false); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_redirect); void ipv4_sk_redirect(struct sk_buff *skb, struct sock *sk) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(&fl4, sk, iph, 0, 0, 0, 0, 0); rt = __ip_route_output_key(sock_net(sk), &fl4); if (!IS_ERR(rt)) { __ip_do_redirect(rt, skb, &fl4, false); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_sk_redirect); static struct dst_entry *ipv4_dst_check(struct dst_entry *dst, u32 cookie) { struct rtable *rt = (struct rtable *) dst; /* All IPV4 dsts are created with ->obsolete set to the value * DST_OBSOLETE_FORCE_CHK which forces validation calls down * into this function always. * * When a PMTU/redirect information update invalidates a route, * this is indicated by setting obsolete to DST_OBSOLETE_KILL or * DST_OBSOLETE_DEAD by dst_free(). */ if (dst->obsolete != DST_OBSOLETE_FORCE_CHK || rt_is_expired(rt)) return NULL; return dst; } static void ipv4_link_failure(struct sk_buff *skb) { struct rtable *rt; icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, 0); rt = skb_rtable(skb); if (rt) dst_set_expires(&rt->dst, 0); } static int ip_rt_bug(struct net *net, struct sock *sk, struct sk_buff *skb) { pr_debug("%s: %pI4 -> %pI4, %s\n", __func__, &ip_hdr(skb)->saddr, &ip_hdr(skb)->daddr, skb->dev ? skb->dev->name : "?"); kfree_skb(skb); WARN_ON(1); return 0; } /* We do not cache source address of outgoing interface, because it is used only by IP RR, TS and SRR options, so that it out of fast path. BTW remember: "addr" is allowed to be not aligned in IP options! */ void ip_rt_get_source(u8 *addr, struct sk_buff *skb, struct rtable *rt) { __be32 src; if (rt_is_output_route(rt)) src = ip_hdr(skb)->saddr; else { struct fib_result res; struct flowi4 fl4; struct iphdr *iph; iph = ip_hdr(skb); memset(&fl4, 0, sizeof(fl4)); fl4.daddr = iph->daddr; fl4.saddr = iph->saddr; fl4.flowi4_tos = RT_TOS(iph->tos); fl4.flowi4_oif = rt->dst.dev->ifindex; fl4.flowi4_iif = skb->dev->ifindex; fl4.flowi4_mark = skb->mark; rcu_read_lock(); if (fib_lookup(dev_net(rt->dst.dev), &fl4, &res, 0) == 0) src = FIB_RES_PREFSRC(dev_net(rt->dst.dev), res); else src = inet_select_addr(rt->dst.dev, rt_nexthop(rt, iph->daddr), RT_SCOPE_UNIVERSE); rcu_read_unlock(); } memcpy(addr, &src, 4); } #ifdef CONFIG_IP_ROUTE_CLASSID static void set_class_tag(struct rtable *rt, u32 tag) { if (!(rt->dst.tclassid & 0xFFFF)) rt->dst.tclassid |= tag & 0xFFFF; if (!(rt->dst.tclassid & 0xFFFF0000)) rt->dst.tclassid |= tag & 0xFFFF0000; } #endif static unsigned int ipv4_default_advmss(const struct dst_entry *dst) { unsigned int advmss = dst_metric_raw(dst, RTAX_ADVMSS); if (advmss == 0) { advmss = max_t(unsigned int, dst->dev->mtu - 40, ip_rt_min_advmss); if (advmss > 65535 - 40) advmss = 65535 - 40; } return advmss; } static unsigned int ipv4_mtu(const struct dst_entry *dst) { const struct rtable *rt = (const struct rtable *) dst; unsigned int mtu = rt->rt_pmtu; if (!mtu || time_after_eq(jiffies, rt->dst.expires)) mtu = dst_metric_raw(dst, RTAX_MTU); if (mtu) return mtu; mtu = dst->dev->mtu; if (unlikely(dst_metric_locked(dst, RTAX_MTU))) { if (rt->rt_uses_gateway && mtu > 576) mtu = 576; } return min_t(unsigned int, mtu, IP_MAX_MTU); } static struct fib_nh_exception *find_exception(struct fib_nh *nh, __be32 daddr) { struct fnhe_hash_bucket *hash = rcu_dereference(nh->nh_exceptions); struct fib_nh_exception *fnhe; u32 hval; if (!hash) return NULL; hval = fnhe_hashfun(daddr); for (fnhe = rcu_dereference(hash[hval].chain); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (fnhe->fnhe_daddr == daddr) return fnhe; } return NULL; } static bool rt_bind_exception(struct rtable *rt, struct fib_nh_exception *fnhe, __be32 daddr) { bool ret = false; spin_lock_bh(&fnhe_lock); if (daddr == fnhe->fnhe_daddr) { struct rtable __rcu **porig; struct rtable *orig; int genid = fnhe_genid(dev_net(rt->dst.dev)); if (rt_is_input_route(rt)) porig = &fnhe->fnhe_rth_input; else porig = &fnhe->fnhe_rth_output; orig = rcu_dereference(*porig); if (fnhe->fnhe_genid != genid) { fnhe->fnhe_genid = genid; fnhe->fnhe_gw = 0; fnhe->fnhe_pmtu = 0; fnhe->fnhe_expires = 0; fnhe_flush_routes(fnhe); orig = NULL; } fill_route_from_fnhe(rt, fnhe); if (!rt->rt_gateway) rt->rt_gateway = daddr; if (!(rt->dst.flags & DST_NOCACHE)) { rcu_assign_pointer(*porig, rt); if (orig) rt_free(orig); ret = true; } fnhe->fnhe_stamp = jiffies; } spin_unlock_bh(&fnhe_lock); return ret; } static bool rt_cache_route(struct fib_nh *nh, struct rtable *rt) { struct rtable *orig, *prev, **p; bool ret = true; if (rt_is_input_route(rt)) { p = (struct rtable **)&nh->nh_rth_input; } else { p = (struct rtable **)raw_cpu_ptr(nh->nh_pcpu_rth_output); } orig = *p; prev = cmpxchg(p, orig, rt); if (prev == orig) { if (orig) rt_free(orig); } else ret = false; return ret; } struct uncached_list { spinlock_t lock; struct list_head head; }; static DEFINE_PER_CPU_ALIGNED(struct uncached_list, rt_uncached_list); static void rt_add_uncached_list(struct rtable *rt) { struct uncached_list *ul = raw_cpu_ptr(&rt_uncached_list); rt->rt_uncached_list = ul; spin_lock_bh(&ul->lock); list_add_tail(&rt->rt_uncached, &ul->head); spin_unlock_bh(&ul->lock); } static void ipv4_dst_destroy(struct dst_entry *dst) { struct rtable *rt = (struct rtable *) dst; if (!list_empty(&rt->rt_uncached)) { struct uncached_list *ul = rt->rt_uncached_list; spin_lock_bh(&ul->lock); list_del(&rt->rt_uncached); spin_unlock_bh(&ul->lock); } } void rt_flush_dev(struct net_device *dev) { struct net *net = dev_net(dev); struct rtable *rt; int cpu; for_each_possible_cpu(cpu) { struct uncached_list *ul = &per_cpu(rt_uncached_list, cpu); spin_lock_bh(&ul->lock); list_for_each_entry(rt, &ul->head, rt_uncached) { if (rt->dst.dev != dev) continue; rt->dst.dev = net->loopback_dev; dev_hold(rt->dst.dev); dev_put(dev); } spin_unlock_bh(&ul->lock); } } static bool rt_cache_valid(const struct rtable *rt) { return rt && rt->dst.obsolete == DST_OBSOLETE_FORCE_CHK && !rt_is_expired(rt); } static void rt_set_nexthop(struct rtable *rt, __be32 daddr, const struct fib_result *res, struct fib_nh_exception *fnhe, struct fib_info *fi, u16 type, u32 itag) { bool cached = false; if (fi) { struct fib_nh *nh = &FIB_RES_NH(*res); if (nh->nh_gw && nh->nh_scope == RT_SCOPE_LINK) { rt->rt_gateway = nh->nh_gw; rt->rt_uses_gateway = 1; } dst_init_metrics(&rt->dst, fi->fib_metrics, true); #ifdef CONFIG_IP_ROUTE_CLASSID rt->dst.tclassid = nh->nh_tclassid; #endif rt->dst.lwtstate = lwtstate_get(nh->nh_lwtstate); if (unlikely(fnhe)) cached = rt_bind_exception(rt, fnhe, daddr); else if (!(rt->dst.flags & DST_NOCACHE)) cached = rt_cache_route(nh, rt); if (unlikely(!cached)) { /* Routes we intend to cache in nexthop exception or * FIB nexthop have the DST_NOCACHE bit clear. * However, if we are unsuccessful at storing this * route into the cache we really need to set it. */ rt->dst.flags |= DST_NOCACHE; if (!rt->rt_gateway) rt->rt_gateway = daddr; rt_add_uncached_list(rt); } } else rt_add_uncached_list(rt); #ifdef CONFIG_IP_ROUTE_CLASSID #ifdef CONFIG_IP_MULTIPLE_TABLES set_class_tag(rt, res->tclassid); #endif set_class_tag(rt, itag); #endif } static struct rtable *rt_dst_alloc(struct net_device *dev, unsigned int flags, u16 type, bool nopolicy, bool noxfrm, bool will_cache) { struct rtable *rt; rt = dst_alloc(&ipv4_dst_ops, dev, 1, DST_OBSOLETE_FORCE_CHK, (will_cache ? 0 : (DST_HOST | DST_NOCACHE)) | (nopolicy ? DST_NOPOLICY : 0) | (noxfrm ? DST_NOXFRM : 0)); if (rt) { rt->rt_genid = rt_genid_ipv4(dev_net(dev)); rt->rt_flags = flags; rt->rt_type = type; rt->rt_is_input = 0; rt->rt_iif = 0; rt->rt_pmtu = 0; rt->rt_gateway = 0; rt->rt_uses_gateway = 0; rt->rt_table_id = 0; INIT_LIST_HEAD(&rt->rt_uncached); rt->dst.output = ip_output; if (flags & RTCF_LOCAL) rt->dst.input = ip_local_deliver; } return rt; } /* called in rcu_read_lock() section */ static int ip_route_input_mc(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev, int our) { struct rtable *rth; struct in_device *in_dev = __in_dev_get_rcu(dev); unsigned int flags = RTCF_MULTICAST; u32 itag = 0; int err; /* Primary sanity checks. */ if (!in_dev) return -EINVAL; if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr) || skb->protocol != htons(ETH_P_IP)) goto e_inval; if (ipv4_is_loopback(saddr) && !IN_DEV_ROUTE_LOCALNET(in_dev)) goto e_inval; if (ipv4_is_zeronet(saddr)) { if (!ipv4_is_local_multicast(daddr)) goto e_inval; } else { err = fib_validate_source(skb, saddr, 0, tos, 0, dev, in_dev, &itag); if (err < 0) goto e_err; } if (our) flags |= RTCF_LOCAL; rth = rt_dst_alloc(dev_net(dev)->loopback_dev, flags, RTN_MULTICAST, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, false); if (!rth) goto e_nobufs; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->dst.output = ip_rt_bug; rth->rt_is_input= 1; #ifdef CONFIG_IP_MROUTE if (!ipv4_is_local_multicast(daddr) && IN_DEV_MFORWARD(in_dev)) rth->dst.input = ip_mr_input; #endif RT_CACHE_STAT_INC(in_slow_mc); skb_dst_set(skb, &rth->dst); return 0; e_nobufs: return -ENOBUFS; e_inval: return -EINVAL; e_err: return err; } static void ip_handle_martian_source(struct net_device *dev, struct in_device *in_dev, struct sk_buff *skb, __be32 daddr, __be32 saddr) { RT_CACHE_STAT_INC(in_martian_src); #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev) && net_ratelimit()) { /* * RFC1812 recommendation, if source is martian, * the only hint is MAC header. */ pr_warn("martian source %pI4 from %pI4, on dev %s\n", &daddr, &saddr, dev->name); if (dev->hard_header_len && skb_mac_header_was_set(skb)) { print_hex_dump(KERN_WARNING, "ll header: ", DUMP_PREFIX_OFFSET, 16, 1, skb_mac_header(skb), dev->hard_header_len, true); } } #endif } static void ip_del_fnhe(struct fib_nh *nh, __be32 daddr) { struct fnhe_hash_bucket *hash; struct fib_nh_exception *fnhe, __rcu **fnhe_p; u32 hval = fnhe_hashfun(daddr); spin_lock_bh(&fnhe_lock); hash = rcu_dereference_protected(nh->nh_exceptions, lockdep_is_held(&fnhe_lock)); hash += hval; fnhe_p = &hash->chain; fnhe = rcu_dereference_protected(*fnhe_p, lockdep_is_held(&fnhe_lock)); while (fnhe) { if (fnhe->fnhe_daddr == daddr) { rcu_assign_pointer(*fnhe_p, rcu_dereference_protected( fnhe->fnhe_next, lockdep_is_held(&fnhe_lock))); fnhe_flush_routes(fnhe); kfree_rcu(fnhe, rcu); break; } fnhe_p = &fnhe->fnhe_next; fnhe = rcu_dereference_protected(fnhe->fnhe_next, lockdep_is_held(&fnhe_lock)); } spin_unlock_bh(&fnhe_lock); } /* called in rcu_read_lock() section */ static int __mkroute_input(struct sk_buff *skb, const struct fib_result *res, struct in_device *in_dev, __be32 daddr, __be32 saddr, u32 tos) { struct fib_nh_exception *fnhe; struct rtable *rth; int err; struct in_device *out_dev; bool do_cache; u32 itag = 0; /* get a working reference to the output device */ out_dev = __in_dev_get_rcu(FIB_RES_DEV(*res)); if (!out_dev) { net_crit_ratelimited("Bug in ip_route_input_slow(). Please report.\n"); return -EINVAL; } err = fib_validate_source(skb, saddr, daddr, tos, FIB_RES_OIF(*res), in_dev->dev, in_dev, &itag); if (err < 0) { ip_handle_martian_source(in_dev->dev, in_dev, skb, daddr, saddr); goto cleanup; } do_cache = res->fi && !itag; if (out_dev == in_dev && err && IN_DEV_TX_REDIRECTS(out_dev) && skb->protocol == htons(ETH_P_IP) && (IN_DEV_SHARED_MEDIA(out_dev) || inet_addr_onlink(out_dev, saddr, FIB_RES_GW(*res)))) IPCB(skb)->flags |= IPSKB_DOREDIRECT; if (skb->protocol != htons(ETH_P_IP)) { /* Not IP (i.e. ARP). Do not create route, if it is * invalid for proxy arp. DNAT routes are always valid. * * Proxy arp feature have been extended to allow, ARP * replies back to the same interface, to support * Private VLAN switch technologies. See arp.c. */ if (out_dev == in_dev && IN_DEV_PROXY_ARP_PVLAN(in_dev) == 0) { err = -EINVAL; goto cleanup; } } fnhe = find_exception(&FIB_RES_NH(*res), daddr); if (do_cache) { if (fnhe) { rth = rcu_dereference(fnhe->fnhe_rth_input); if (rth && rth->dst.expires && time_after(jiffies, rth->dst.expires)) { ip_del_fnhe(&FIB_RES_NH(*res), daddr); fnhe = NULL; } else { goto rt_cache; } } rth = rcu_dereference(FIB_RES_NH(*res).nh_rth_input); rt_cache: if (rt_cache_valid(rth)) { skb_dst_set_noref(skb, &rth->dst); goto out; } } rth = rt_dst_alloc(out_dev->dev, 0, res->type, IN_DEV_CONF_GET(in_dev, NOPOLICY), IN_DEV_CONF_GET(out_dev, NOXFRM), do_cache); if (!rth) { err = -ENOBUFS; goto cleanup; } rth->rt_is_input = 1; if (res->table) rth->rt_table_id = res->table->tb_id; RT_CACHE_STAT_INC(in_slow_tot); rth->dst.input = ip_forward; rt_set_nexthop(rth, daddr, res, fnhe, res->fi, res->type, itag); if (lwtunnel_output_redirect(rth->dst.lwtstate)) { rth->dst.lwtstate->orig_output = rth->dst.output; rth->dst.output = lwtunnel_output; } if (lwtunnel_input_redirect(rth->dst.lwtstate)) { rth->dst.lwtstate->orig_input = rth->dst.input; rth->dst.input = lwtunnel_input; } skb_dst_set(skb, &rth->dst); out: err = 0; cleanup: return err; } #ifdef CONFIG_IP_ROUTE_MULTIPATH /* To make ICMP packets follow the right flow, the multipath hash is * calculated from the inner IP addresses in reverse order. */ static int ip_multipath_icmp_hash(struct sk_buff *skb) { const struct iphdr *outer_iph = ip_hdr(skb); struct icmphdr _icmph; const struct icmphdr *icmph; struct iphdr _inner_iph; const struct iphdr *inner_iph; if (unlikely((outer_iph->frag_off & htons(IP_OFFSET)) != 0)) goto standard_hash; icmph = skb_header_pointer(skb, outer_iph->ihl * 4, sizeof(_icmph), &_icmph); if (!icmph) goto standard_hash; if (icmph->type != ICMP_DEST_UNREACH && icmph->type != ICMP_REDIRECT && icmph->type != ICMP_TIME_EXCEEDED && icmph->type != ICMP_PARAMETERPROB) { goto standard_hash; } inner_iph = skb_header_pointer(skb, outer_iph->ihl * 4 + sizeof(_icmph), sizeof(_inner_iph), &_inner_iph); if (!inner_iph) goto standard_hash; return fib_multipath_hash(inner_iph->daddr, inner_iph->saddr); standard_hash: return fib_multipath_hash(outer_iph->saddr, outer_iph->daddr); } #endif /* CONFIG_IP_ROUTE_MULTIPATH */ static int ip_mkroute_input(struct sk_buff *skb, struct fib_result *res, const struct flowi4 *fl4, struct in_device *in_dev, __be32 daddr, __be32 saddr, u32 tos) { #ifdef CONFIG_IP_ROUTE_MULTIPATH if (res->fi && res->fi->fib_nhs > 1) { int h; if (unlikely(ip_hdr(skb)->protocol == IPPROTO_ICMP)) h = ip_multipath_icmp_hash(skb); else h = fib_multipath_hash(saddr, daddr); fib_select_multipath(res, h); } #endif /* create a routing cache entry */ return __mkroute_input(skb, res, in_dev, daddr, saddr, tos); } /* * NOTE. We drop all the packets that has local source * addresses, because every properly looped back packet * must have correct destination already attached by output routine. * * Such approach solves two big problems: * 1. Not simplex devices are handled properly. * 2. IP spoofing attempts are filtered with 100% of guarantee. * called with rcu_read_lock() */ static int ip_route_input_slow(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev) { struct fib_result res; struct in_device *in_dev = __in_dev_get_rcu(dev); struct ip_tunnel_info *tun_info; struct flowi4 fl4; unsigned int flags = 0; u32 itag = 0; struct rtable *rth; int err = -EINVAL; struct net *net = dev_net(dev); bool do_cache; /* IP on this device is disabled. */ if (!in_dev) goto out; /* Check for the most weird martians, which can be not detected by fib_lookup. */ tun_info = skb_tunnel_info(skb); if (tun_info && !(tun_info->mode & IP_TUNNEL_INFO_TX)) fl4.flowi4_tun_key.tun_id = tun_info->key.tun_id; else fl4.flowi4_tun_key.tun_id = 0; skb_dst_drop(skb); if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr)) goto martian_source; res.fi = NULL; res.table = NULL; if (ipv4_is_lbcast(daddr) || (saddr == 0 && daddr == 0)) goto brd_input; /* Accept zero addresses only to limited broadcast; * I even do not know to fix it or not. Waiting for complains :-) */ if (ipv4_is_zeronet(saddr)) goto martian_source; if (ipv4_is_zeronet(daddr)) goto martian_destination; /* Following code try to avoid calling IN_DEV_NET_ROUTE_LOCALNET(), * and call it once if daddr or/and saddr are loopback addresses */ if (ipv4_is_loopback(daddr)) { if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net)) goto martian_destination; } else if (ipv4_is_loopback(saddr)) { if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net)) goto martian_source; } /* * Now we are ready to route packet. */ fl4.flowi4_oif = 0; fl4.flowi4_iif = l3mdev_fib_oif_rcu(dev); fl4.flowi4_mark = skb->mark; fl4.flowi4_tos = tos; fl4.flowi4_scope = RT_SCOPE_UNIVERSE; fl4.flowi4_flags = 0; fl4.daddr = daddr; fl4.saddr = saddr; err = fib_lookup(net, &fl4, &res, 0); if (err != 0) { if (!IN_DEV_FORWARD(in_dev)) err = -EHOSTUNREACH; goto no_route; } if (res.type == RTN_BROADCAST) goto brd_input; if (res.type == RTN_LOCAL) { err = fib_validate_source(skb, saddr, daddr, tos, 0, dev, in_dev, &itag); if (err < 0) goto martian_source; goto local_input; } if (!IN_DEV_FORWARD(in_dev)) { err = -EHOSTUNREACH; goto no_route; } if (res.type != RTN_UNICAST) goto martian_destination; err = ip_mkroute_input(skb, &res, &fl4, in_dev, daddr, saddr, tos); out: return err; brd_input: if (skb->protocol != htons(ETH_P_IP)) goto e_inval; if (!ipv4_is_zeronet(saddr)) { err = fib_validate_source(skb, saddr, 0, tos, 0, dev, in_dev, &itag); if (err < 0) goto martian_source; } flags |= RTCF_BROADCAST; res.type = RTN_BROADCAST; RT_CACHE_STAT_INC(in_brd); local_input: do_cache = false; if (res.fi) { if (!itag) { rth = rcu_dereference(FIB_RES_NH(res).nh_rth_input); if (rt_cache_valid(rth)) { skb_dst_set_noref(skb, &rth->dst); err = 0; goto out; } do_cache = true; } } rth = rt_dst_alloc(net->loopback_dev, flags | RTCF_LOCAL, res.type, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, do_cache); if (!rth) goto e_nobufs; rth->dst.output= ip_rt_bug; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->rt_is_input = 1; if (res.table) rth->rt_table_id = res.table->tb_id; RT_CACHE_STAT_INC(in_slow_tot); if (res.type == RTN_UNREACHABLE) { rth->dst.input= ip_error; rth->dst.error= -err; rth->rt_flags &= ~RTCF_LOCAL; } if (do_cache) { if (unlikely(!rt_cache_route(&FIB_RES_NH(res), rth))) { rth->dst.flags |= DST_NOCACHE; rt_add_uncached_list(rth); } } skb_dst_set(skb, &rth->dst); err = 0; goto out; no_route: RT_CACHE_STAT_INC(in_no_route); res.type = RTN_UNREACHABLE; res.fi = NULL; res.table = NULL; goto local_input; /* * Do not cache martian addresses: they should be logged (RFC1812) */ martian_destination: RT_CACHE_STAT_INC(in_martian_dst); #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev)) net_warn_ratelimited("martian destination %pI4 from %pI4, dev %s\n", &daddr, &saddr, dev->name); #endif e_inval: err = -EINVAL; goto out; e_nobufs: err = -ENOBUFS; goto out; martian_source: ip_handle_martian_source(dev, in_dev, skb, daddr, saddr); goto out; } int ip_route_input_noref(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev) { int res; rcu_read_lock(); /* Multicast recognition logic is moved from route cache to here. The problem was that too many Ethernet cards have broken/missing hardware multicast filters :-( As result the host on multicasting network acquires a lot of useless route cache entries, sort of SDR messages from all the world. Now we try to get rid of them. Really, provided software IP multicast filter is organized reasonably (at least, hashed), it does not result in a slowdown comparing with route cache reject entries. Note, that multicast routers are not affected, because route cache entry is created eventually. */ if (ipv4_is_multicast(daddr)) { struct in_device *in_dev = __in_dev_get_rcu(dev); if (in_dev) { int our = ip_check_mc_rcu(in_dev, daddr, saddr, ip_hdr(skb)->protocol); if (our #ifdef CONFIG_IP_MROUTE || (!ipv4_is_local_multicast(daddr) && IN_DEV_MFORWARD(in_dev)) #endif ) { int res = ip_route_input_mc(skb, daddr, saddr, tos, dev, our); rcu_read_unlock(); return res; } } rcu_read_unlock(); return -EINVAL; } res = ip_route_input_slow(skb, daddr, saddr, tos, dev); rcu_read_unlock(); return res; } EXPORT_SYMBOL(ip_route_input_noref); /* called with rcu_read_lock() */ static struct rtable *__mkroute_output(const struct fib_result *res, const struct flowi4 *fl4, int orig_oif, struct net_device *dev_out, unsigned int flags) { struct fib_info *fi = res->fi; struct fib_nh_exception *fnhe; struct in_device *in_dev; u16 type = res->type; struct rtable *rth; bool do_cache; in_dev = __in_dev_get_rcu(dev_out); if (!in_dev) return ERR_PTR(-EINVAL); if (likely(!IN_DEV_ROUTE_LOCALNET(in_dev))) if (ipv4_is_loopback(fl4->saddr) && !(dev_out->flags & IFF_LOOPBACK)) return ERR_PTR(-EINVAL); if (ipv4_is_lbcast(fl4->daddr)) type = RTN_BROADCAST; else if (ipv4_is_multicast(fl4->daddr)) type = RTN_MULTICAST; else if (ipv4_is_zeronet(fl4->daddr)) return ERR_PTR(-EINVAL); if (dev_out->flags & IFF_LOOPBACK) flags |= RTCF_LOCAL; do_cache = true; if (type == RTN_BROADCAST) { flags |= RTCF_BROADCAST | RTCF_LOCAL; fi = NULL; } else if (type == RTN_MULTICAST) { flags |= RTCF_MULTICAST | RTCF_LOCAL; if (!ip_check_mc_rcu(in_dev, fl4->daddr, fl4->saddr, fl4->flowi4_proto)) flags &= ~RTCF_LOCAL; else do_cache = false; /* If multicast route do not exist use * default one, but do not gateway in this case. * Yes, it is hack. */ if (fi && res->prefixlen < 4) fi = NULL; } else if ((type == RTN_LOCAL) && (orig_oif != 0) && (orig_oif != dev_out->ifindex)) { /* For local routes that require a particular output interface * we do not want to cache the result. Caching the result * causes incorrect behaviour when there are multiple source * addresses on the interface, the end result being that if the * intended recipient is waiting on that interface for the * packet he won't receive it because it will be delivered on * the loopback interface and the IP_PKTINFO ipi_ifindex will * be set to the loopback interface as well. */ fi = NULL; } fnhe = NULL; do_cache &= fi != NULL; if (do_cache) { struct rtable __rcu **prth; struct fib_nh *nh = &FIB_RES_NH(*res); fnhe = find_exception(nh, fl4->daddr); if (fnhe) { prth = &fnhe->fnhe_rth_output; rth = rcu_dereference(*prth); if (rth && rth->dst.expires && time_after(jiffies, rth->dst.expires)) { ip_del_fnhe(nh, fl4->daddr); fnhe = NULL; } else { goto rt_cache; } } if (unlikely(fl4->flowi4_flags & FLOWI_FLAG_KNOWN_NH && !(nh->nh_gw && nh->nh_scope == RT_SCOPE_LINK))) { do_cache = false; goto add; } prth = raw_cpu_ptr(nh->nh_pcpu_rth_output); rth = rcu_dereference(*prth); rt_cache: if (rt_cache_valid(rth)) { dst_hold(&rth->dst); return rth; } } add: rth = rt_dst_alloc(dev_out, flags, type, IN_DEV_CONF_GET(in_dev, NOPOLICY), IN_DEV_CONF_GET(in_dev, NOXFRM), do_cache); if (!rth) return ERR_PTR(-ENOBUFS); rth->rt_iif = orig_oif ? : 0; if (res->table) rth->rt_table_id = res->table->tb_id; RT_CACHE_STAT_INC(out_slow_tot); if (flags & (RTCF_BROADCAST | RTCF_MULTICAST)) { if (flags & RTCF_LOCAL && !(dev_out->flags & IFF_LOOPBACK)) { rth->dst.output = ip_mc_output; RT_CACHE_STAT_INC(out_slow_mc); } #ifdef CONFIG_IP_MROUTE if (type == RTN_MULTICAST) { if (IN_DEV_MFORWARD(in_dev) && !ipv4_is_local_multicast(fl4->daddr)) { rth->dst.input = ip_mr_input; rth->dst.output = ip_mc_output; } } #endif } rt_set_nexthop(rth, fl4->daddr, res, fnhe, fi, type, 0); if (lwtunnel_output_redirect(rth->dst.lwtstate)) rth->dst.output = lwtunnel_output; return rth; } /* * Major route resolver routine. */ struct rtable *__ip_route_output_key_hash(struct net *net, struct flowi4 *fl4, int mp_hash) { struct net_device *dev_out = NULL; __u8 tos = RT_FL_TOS(fl4); unsigned int flags = 0; struct fib_result res; struct rtable *rth; int orig_oif; int err = -ENETUNREACH; res.tclassid = 0; res.fi = NULL; res.table = NULL; orig_oif = fl4->flowi4_oif; fl4->flowi4_iif = LOOPBACK_IFINDEX; fl4->flowi4_tos = tos & IPTOS_RT_MASK; fl4->flowi4_scope = ((tos & RTO_ONLINK) ? RT_SCOPE_LINK : RT_SCOPE_UNIVERSE); rcu_read_lock(); if (fl4->saddr) { rth = ERR_PTR(-EINVAL); if (ipv4_is_multicast(fl4->saddr) || ipv4_is_lbcast(fl4->saddr) || ipv4_is_zeronet(fl4->saddr)) goto out; /* I removed check for oif == dev_out->oif here. It was wrong for two reasons: 1. ip_dev_find(net, saddr) can return wrong iface, if saddr is assigned to multiple interfaces. 2. Moreover, we are allowed to send packets with saddr of another iface. --ANK */ if (fl4->flowi4_oif == 0 && (ipv4_is_multicast(fl4->daddr) || ipv4_is_lbcast(fl4->daddr))) { /* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */ dev_out = __ip_dev_find(net, fl4->saddr, false); if (!dev_out) goto out; /* Special hack: user can direct multicasts and limited broadcast via necessary interface without fiddling with IP_MULTICAST_IF or IP_PKTINFO. This hack is not just for fun, it allows vic,vat and friends to work. They bind socket to loopback, set ttl to zero and expect that it will work. From the viewpoint of routing cache they are broken, because we are not allowed to build multicast path with loopback source addr (look, routing cache cannot know, that ttl is zero, so that packet will not leave this host and route is valid). Luckily, this hack is good workaround. */ fl4->flowi4_oif = dev_out->ifindex; goto make_route; } if (!(fl4->flowi4_flags & FLOWI_FLAG_ANYSRC)) { /* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */ if (!__ip_dev_find(net, fl4->saddr, false)) goto out; } } if (fl4->flowi4_oif) { dev_out = dev_get_by_index_rcu(net, fl4->flowi4_oif); rth = ERR_PTR(-ENODEV); if (!dev_out) goto out; /* RACE: Check return value of inet_select_addr instead. */ if (!(dev_out->flags & IFF_UP) || !__in_dev_get_rcu(dev_out)) { rth = ERR_PTR(-ENETUNREACH); goto out; } if (ipv4_is_local_multicast(fl4->daddr) || ipv4_is_lbcast(fl4->daddr) || fl4->flowi4_proto == IPPROTO_IGMP) { if (!fl4->saddr) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_LINK); goto make_route; } if (!fl4->saddr) { if (ipv4_is_multicast(fl4->daddr)) fl4->saddr = inet_select_addr(dev_out, 0, fl4->flowi4_scope); else if (!fl4->daddr) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_HOST); } rth = l3mdev_get_rtable(dev_out, fl4); if (rth) goto out; } if (!fl4->daddr) { fl4->daddr = fl4->saddr; if (!fl4->daddr) fl4->daddr = fl4->saddr = htonl(INADDR_LOOPBACK); dev_out = net->loopback_dev; fl4->flowi4_oif = LOOPBACK_IFINDEX; res.type = RTN_LOCAL; flags |= RTCF_LOCAL; goto make_route; } err = fib_lookup(net, fl4, &res, 0); if (err) { res.fi = NULL; res.table = NULL; if (fl4->flowi4_oif && !netif_index_is_l3_master(net, fl4->flowi4_oif)) { /* Apparently, routing tables are wrong. Assume, that the destination is on link. WHY? DW. Because we are allowed to send to iface even if it has NO routes and NO assigned addresses. When oif is specified, routing tables are looked up with only one purpose: to catch if destination is gatewayed, rather than direct. Moreover, if MSG_DONTROUTE is set, we send packet, ignoring both routing tables and ifaddr state. --ANK We could make it even if oif is unknown, likely IPv6, but we do not. */ if (fl4->saddr == 0) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_LINK); res.type = RTN_UNICAST; goto make_route; } rth = ERR_PTR(err); goto out; } if (res.type == RTN_LOCAL) { if (!fl4->saddr) { if (res.fi->fib_prefsrc) fl4->saddr = res.fi->fib_prefsrc; else fl4->saddr = fl4->daddr; } dev_out = net->loopback_dev; fl4->flowi4_oif = dev_out->ifindex; flags |= RTCF_LOCAL; goto make_route; } fib_select_path(net, &res, fl4, mp_hash); dev_out = FIB_RES_DEV(res); fl4->flowi4_oif = dev_out->ifindex; make_route: rth = __mkroute_output(&res, fl4, orig_oif, dev_out, flags); out: rcu_read_unlock(); return rth; } EXPORT_SYMBOL_GPL(__ip_route_output_key_hash); static struct dst_entry *ipv4_blackhole_dst_check(struct dst_entry *dst, u32 cookie) { return NULL; } static unsigned int ipv4_blackhole_mtu(const struct dst_entry *dst) { unsigned int mtu = dst_metric_raw(dst, RTAX_MTU); return mtu ? : dst->dev->mtu; } static void ipv4_rt_blackhole_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu) { } static void ipv4_rt_blackhole_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb) { } static u32 *ipv4_rt_blackhole_cow_metrics(struct dst_entry *dst, unsigned long old) { return NULL; } static struct dst_ops ipv4_dst_blackhole_ops = { .family = AF_INET, .check = ipv4_blackhole_dst_check, .mtu = ipv4_blackhole_mtu, .default_advmss = ipv4_default_advmss, .update_pmtu = ipv4_rt_blackhole_update_pmtu, .redirect = ipv4_rt_blackhole_redirect, .cow_metrics = ipv4_rt_blackhole_cow_metrics, .neigh_lookup = ipv4_neigh_lookup, }; struct dst_entry *ipv4_blackhole_route(struct net *net, struct dst_entry *dst_orig) { struct rtable *ort = (struct rtable *) dst_orig; struct rtable *rt; rt = dst_alloc(&ipv4_dst_blackhole_ops, NULL, 1, DST_OBSOLETE_NONE, 0); if (rt) { struct dst_entry *new = &rt->dst; new->__use = 1; new->input = dst_discard; new->output = dst_discard_out; new->dev = ort->dst.dev; if (new->dev) dev_hold(new->dev); rt->rt_is_input = ort->rt_is_input; rt->rt_iif = ort->rt_iif; rt->rt_pmtu = ort->rt_pmtu; rt->rt_genid = rt_genid_ipv4(net); rt->rt_flags = ort->rt_flags; rt->rt_type = ort->rt_type; rt->rt_gateway = ort->rt_gateway; rt->rt_uses_gateway = ort->rt_uses_gateway; INIT_LIST_HEAD(&rt->rt_uncached); dst_free(new); } dst_release(dst_orig); return rt ? &rt->dst : ERR_PTR(-ENOMEM); } struct rtable *ip_route_output_flow(struct net *net, struct flowi4 *flp4, const struct sock *sk) { struct rtable *rt = __ip_route_output_key(net, flp4); if (IS_ERR(rt)) return rt; if (flp4->flowi4_proto) rt = (struct rtable *)xfrm_lookup_route(net, &rt->dst, flowi4_to_flowi(flp4), sk, 0); return rt; } EXPORT_SYMBOL_GPL(ip_route_output_flow); static int rt_fill_info(struct net *net, __be32 dst, __be32 src, u32 table_id, struct flowi4 *fl4, struct sk_buff *skb, u32 portid, u32 seq, int event, int nowait, unsigned int flags) { struct rtable *rt = skb_rtable(skb); struct rtmsg *r; struct nlmsghdr *nlh; unsigned long expires = 0; u32 error; u32 metrics[RTAX_MAX]; nlh = nlmsg_put(skb, portid, seq, event, sizeof(*r), flags); if (!nlh) return -EMSGSIZE; r = nlmsg_data(nlh); r->rtm_family = AF_INET; r->rtm_dst_len = 32; r->rtm_src_len = 0; r->rtm_tos = fl4->flowi4_tos; r->rtm_table = table_id < 256 ? table_id : RT_TABLE_COMPAT; if (nla_put_u32(skb, RTA_TABLE, table_id)) goto nla_put_failure; r->rtm_type = rt->rt_type; r->rtm_scope = RT_SCOPE_UNIVERSE; r->rtm_protocol = RTPROT_UNSPEC; r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED; if (rt->rt_flags & RTCF_NOTIFY) r->rtm_flags |= RTM_F_NOTIFY; if (IPCB(skb)->flags & IPSKB_DOREDIRECT) r->rtm_flags |= RTCF_DOREDIRECT; if (nla_put_in_addr(skb, RTA_DST, dst)) goto nla_put_failure; if (src) { r->rtm_src_len = 32; if (nla_put_in_addr(skb, RTA_SRC, src)) goto nla_put_failure; } if (rt->dst.dev && nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex)) goto nla_put_failure; #ifdef CONFIG_IP_ROUTE_CLASSID if (rt->dst.tclassid && nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid)) goto nla_put_failure; #endif if (!rt_is_input_route(rt) && fl4->saddr != src) { if (nla_put_in_addr(skb, RTA_PREFSRC, fl4->saddr)) goto nla_put_failure; } if (rt->rt_uses_gateway && nla_put_in_addr(skb, RTA_GATEWAY, rt->rt_gateway)) goto nla_put_failure; expires = rt->dst.expires; if (expires) { unsigned long now = jiffies; if (time_before(now, expires)) expires -= now; else expires = 0; } memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics)); if (rt->rt_pmtu && expires) metrics[RTAX_MTU - 1] = rt->rt_pmtu; if (rtnetlink_put_metrics(skb, metrics) < 0) goto nla_put_failure; if (fl4->flowi4_mark && nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark)) goto nla_put_failure; error = rt->dst.error; if (rt_is_input_route(rt)) { #ifdef CONFIG_IP_MROUTE if (ipv4_is_multicast(dst) && !ipv4_is_local_multicast(dst) && IPV4_DEVCONF_ALL(net, MC_FORWARDING)) { int err = ipmr_get_route(net, skb, fl4->saddr, fl4->daddr, r, nowait, portid); if (err <= 0) { if (!nowait) { if (err == 0) return 0; goto nla_put_failure; } else { if (err == -EMSGSIZE) goto nla_put_failure; error = err; } } } else #endif if (nla_put_u32(skb, RTA_IIF, skb->dev->ifindex)) goto nla_put_failure; } if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0) goto nla_put_failure; nlmsg_end(skb, nlh); return 0; nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh) { struct net *net = sock_net(in_skb->sk); struct rtmsg *rtm; struct nlattr *tb[RTA_MAX+1]; struct rtable *rt = NULL; struct flowi4 fl4; __be32 dst = 0; __be32 src = 0; u32 iif; int err; int mark; struct sk_buff *skb; u32 table_id = RT_TABLE_MAIN; err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy); if (err < 0) goto errout; rtm = nlmsg_data(nlh); skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (!skb) { err = -ENOBUFS; goto errout; } /* Reserve room for dummy headers, this skb can pass through good chunk of routing engine. */ skb_reset_mac_header(skb); skb_reset_network_header(skb); /* Bugfix: need to give ip_route_input enough of an IP header to not gag. */ ip_hdr(skb)->protocol = IPPROTO_ICMP; skb_reserve(skb, MAX_HEADER + sizeof(struct iphdr)); src = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0; dst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0; iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0; mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0; memset(&fl4, 0, sizeof(fl4)); fl4.daddr = dst; fl4.saddr = src; fl4.flowi4_tos = rtm->rtm_tos; fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0; fl4.flowi4_mark = mark; if (netif_index_is_l3_master(net, fl4.flowi4_oif)) fl4.flowi4_flags = FLOWI_FLAG_L3MDEV_SRC | FLOWI_FLAG_SKIP_NH_OIF; if (iif) { struct net_device *dev; dev = __dev_get_by_index(net, iif); if (!dev) { err = -ENODEV; goto errout_free; } skb->protocol = htons(ETH_P_IP); skb->dev = dev; skb->mark = mark; local_bh_disable(); err = ip_route_input(skb, dst, src, rtm->rtm_tos, dev); local_bh_enable(); rt = skb_rtable(skb); if (err == 0 && rt->dst.error) err = -rt->dst.error; } else { rt = ip_route_output_key(net, &fl4); err = 0; if (IS_ERR(rt)) err = PTR_ERR(rt); } if (err) goto errout_free; skb_dst_set(skb, &rt->dst); if (rtm->rtm_flags & RTM_F_NOTIFY) rt->rt_flags |= RTCF_NOTIFY; if (rtm->rtm_flags & RTM_F_LOOKUP_TABLE) table_id = rt->rt_table_id; err = rt_fill_info(net, dst, src, table_id, &fl4, skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWROUTE, 0, 0); if (err < 0) goto errout_free; err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); errout: return err; errout_free: kfree_skb(skb); goto errout; } void ip_rt_multicast_event(struct in_device *in_dev) { rt_cache_flush(dev_net(in_dev->dev)); } #ifdef CONFIG_SYSCTL static int ip_rt_gc_interval __read_mostly = 60 * HZ; static int ip_rt_gc_min_interval __read_mostly = HZ / 2; static int ip_rt_gc_elasticity __read_mostly = 8; static int ipv4_sysctl_rtcache_flush(struct ctl_table *__ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { struct net *net = (struct net *)__ctl->extra1; if (write) { rt_cache_flush(net); fnhe_genid_bump(net); return 0; } return -EINVAL; } static struct ctl_table ipv4_route_table[] = { { .procname = "gc_thresh", .data = &ipv4_dst_ops.gc_thresh, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "max_size", .data = &ip_rt_max_size, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { /* Deprecated. Use gc_min_interval_ms */ .procname = "gc_min_interval", .data = &ip_rt_gc_min_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "gc_min_interval_ms", .data = &ip_rt_gc_min_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_ms_jiffies, }, { .procname = "gc_timeout", .data = &ip_rt_gc_timeout, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "gc_interval", .data = &ip_rt_gc_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "redirect_load", .data = &ip_rt_redirect_load, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "redirect_number", .data = &ip_rt_redirect_number, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "redirect_silence", .data = &ip_rt_redirect_silence, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "error_cost", .data = &ip_rt_error_cost, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "error_burst", .data = &ip_rt_error_burst, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "gc_elasticity", .data = &ip_rt_gc_elasticity, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "mtu_expires", .data = &ip_rt_mtu_expires, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "min_pmtu", .data = &ip_rt_min_pmtu, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "min_adv_mss", .data = &ip_rt_min_advmss, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { } }; static struct ctl_table ipv4_route_flush_table[] = { { .procname = "flush", .maxlen = sizeof(int), .mode = 0200, .proc_handler = ipv4_sysctl_rtcache_flush, }, { }, }; static __net_init int sysctl_route_net_init(struct net *net) { struct ctl_table *tbl; tbl = ipv4_route_flush_table; if (!net_eq(net, &init_net)) { tbl = kmemdup(tbl, sizeof(ipv4_route_flush_table), GFP_KERNEL); if (!tbl) goto err_dup; /* Don't export sysctls to unprivileged users */ if (net->user_ns != &init_user_ns) tbl[0].procname = NULL; } tbl[0].extra1 = net; net->ipv4.route_hdr = register_net_sysctl(net, "net/ipv4/route", tbl); if (!net->ipv4.route_hdr) goto err_reg; return 0; err_reg: if (tbl != ipv4_route_flush_table) kfree(tbl); err_dup: return -ENOMEM; } static __net_exit void sysctl_route_net_exit(struct net *net) { struct ctl_table *tbl; tbl = net->ipv4.route_hdr->ctl_table_arg; unregister_net_sysctl_table(net->ipv4.route_hdr); BUG_ON(tbl == ipv4_route_flush_table); kfree(tbl); } static __net_initdata struct pernet_operations sysctl_route_ops = { .init = sysctl_route_net_init, .exit = sysctl_route_net_exit, }; #endif static __net_init int rt_genid_init(struct net *net) { atomic_set(&net->ipv4.rt_genid, 0); atomic_set(&net->fnhe_genid, 0); get_random_bytes(&net->ipv4.dev_addr_genid, sizeof(net->ipv4.dev_addr_genid)); return 0; } static __net_initdata struct pernet_operations rt_genid_ops = { .init = rt_genid_init, }; static int __net_init ipv4_inetpeer_init(struct net *net) { struct inet_peer_base *bp = kmalloc(sizeof(*bp), GFP_KERNEL); if (!bp) return -ENOMEM; inet_peer_base_init(bp); net->ipv4.peers = bp; return 0; } static void __net_exit ipv4_inetpeer_exit(struct net *net) { struct inet_peer_base *bp = net->ipv4.peers; net->ipv4.peers = NULL; inetpeer_invalidate_tree(bp); kfree(bp); } static __net_initdata struct pernet_operations ipv4_inetpeer_ops = { .init = ipv4_inetpeer_init, .exit = ipv4_inetpeer_exit, }; #ifdef CONFIG_IP_ROUTE_CLASSID struct ip_rt_acct __percpu *ip_rt_acct __read_mostly; #endif /* CONFIG_IP_ROUTE_CLASSID */ int __init ip_rt_init(void) { int rc = 0; int cpu; ip_idents = kmalloc(IP_IDENTS_SZ * sizeof(*ip_idents), GFP_KERNEL); if (!ip_idents) panic("IP: failed to allocate ip_idents\n"); prandom_bytes(ip_idents, IP_IDENTS_SZ * sizeof(*ip_idents)); ip_tstamps = kcalloc(IP_IDENTS_SZ, sizeof(*ip_tstamps), GFP_KERNEL); if (!ip_tstamps) panic("IP: failed to allocate ip_tstamps\n"); for_each_possible_cpu(cpu) { struct uncached_list *ul = &per_cpu(rt_uncached_list, cpu); INIT_LIST_HEAD(&ul->head); spin_lock_init(&ul->lock); } #ifdef CONFIG_IP_ROUTE_CLASSID ip_rt_acct = __alloc_percpu(256 * sizeof(struct ip_rt_acct), __alignof__(struct ip_rt_acct)); if (!ip_rt_acct) panic("IP: failed to allocate ip_rt_acct\n"); #endif ipv4_dst_ops.kmem_cachep = kmem_cache_create("ip_dst_cache", sizeof(struct rtable), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); ipv4_dst_blackhole_ops.kmem_cachep = ipv4_dst_ops.kmem_cachep; if (dst_entries_init(&ipv4_dst_ops) < 0) panic("IP: failed to allocate ipv4_dst_ops counter\n"); if (dst_entries_init(&ipv4_dst_blackhole_ops) < 0) panic("IP: failed to allocate ipv4_dst_blackhole_ops counter\n"); ipv4_dst_ops.gc_thresh = ~0; ip_rt_max_size = INT_MAX; devinet_init(); ip_fib_init(); if (ip_rt_proc_init()) pr_err("Unable to create route proc files\n"); #ifdef CONFIG_XFRM xfrm_init(); xfrm4_init(); #endif rtnl_register(PF_INET, RTM_GETROUTE, inet_rtm_getroute, NULL, NULL); #ifdef CONFIG_SYSCTL register_pernet_subsys(&sysctl_route_ops); #endif register_pernet_subsys(&rt_genid_ops); register_pernet_subsys(&ipv4_inetpeer_ops); return rc; } #ifdef CONFIG_SYSCTL /* * We really need to sanitize the damn ipv4 init order, then all * this nonsense will go away. */ void __init ip_static_sysctl_init(void) { register_net_sysctl(&init_net, "net/ipv4/route", ipv4_route_table); } #endif
UnicronNL/vyos-kernel-clearfog
net/ipv4/route.c
C
gpl-2.0
72,697
/* Copyright (c) 2009-2012, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #ifndef __LINUX_MSM_CAMERA_H #define __LINUX_MSM_CAMERA_H #ifdef MSM_CAMERA_BIONIC #include <sys/types.h> #endif #include <linux/types.h> #include <linux/ioctl.h> #ifdef __KERNEL__ #include <linux/cdev.h> #endif #ifdef MSM_CAMERA_GCC #include <time.h> #else #include <linux/time.h> #endif #include <linux/ion.h> #define BIT(nr) (1UL << (nr)) #define MSM_CAM_IOCTL_MAGIC 'm' #define MSM_CAM_IOCTL_GET_SENSOR_INFO \ _IOR(MSM_CAM_IOCTL_MAGIC, 1, struct msm_camsensor_info *) #define MSM_CAM_IOCTL_REGISTER_PMEM \ _IOW(MSM_CAM_IOCTL_MAGIC, 2, struct msm_pmem_info *) #define MSM_CAM_IOCTL_UNREGISTER_PMEM \ _IOW(MSM_CAM_IOCTL_MAGIC, 3, unsigned) #define MSM_CAM_IOCTL_CTRL_COMMAND \ _IOW(MSM_CAM_IOCTL_MAGIC, 4, struct msm_ctrl_cmd *) #define MSM_CAM_IOCTL_CONFIG_VFE \ _IOW(MSM_CAM_IOCTL_MAGIC, 5, struct msm_camera_vfe_cfg_cmd *) #define MSM_CAM_IOCTL_GET_STATS \ _IOR(MSM_CAM_IOCTL_MAGIC, 6, struct msm_camera_stats_event_ctrl *) #define MSM_CAM_IOCTL_GETFRAME \ _IOR(MSM_CAM_IOCTL_MAGIC, 7, struct msm_camera_get_frame *) #define MSM_CAM_IOCTL_ENABLE_VFE \ _IOW(MSM_CAM_IOCTL_MAGIC, 8, struct camera_enable_cmd *) #define MSM_CAM_IOCTL_CTRL_CMD_DONE \ _IOW(MSM_CAM_IOCTL_MAGIC, 9, struct camera_cmd *) #define MSM_CAM_IOCTL_CONFIG_CMD \ _IOW(MSM_CAM_IOCTL_MAGIC, 10, struct camera_cmd *) #define MSM_CAM_IOCTL_DISABLE_VFE \ _IOW(MSM_CAM_IOCTL_MAGIC, 11, struct camera_enable_cmd *) #define MSM_CAM_IOCTL_PAD_REG_RESET2 \ _IOW(MSM_CAM_IOCTL_MAGIC, 12, struct camera_enable_cmd *) #define MSM_CAM_IOCTL_VFE_APPS_RESET \ _IOW(MSM_CAM_IOCTL_MAGIC, 13, struct camera_enable_cmd *) #define MSM_CAM_IOCTL_RELEASE_FRAME_BUFFER \ _IOW(MSM_CAM_IOCTL_MAGIC, 14, struct camera_enable_cmd *) #define MSM_CAM_IOCTL_RELEASE_STATS_BUFFER \ _IOW(MSM_CAM_IOCTL_MAGIC, 15, struct msm_stats_buf *) #define MSM_CAM_IOCTL_AXI_CONFIG \ _IOW(MSM_CAM_IOCTL_MAGIC, 16, struct msm_camera_vfe_cfg_cmd *) #define MSM_CAM_IOCTL_GET_PICTURE \ _IOW(MSM_CAM_IOCTL_MAGIC, 17, struct msm_frame *) #define MSM_CAM_IOCTL_SET_CROP \ _IOW(MSM_CAM_IOCTL_MAGIC, 18, struct crop_info *) #define MSM_CAM_IOCTL_PICT_PP \ _IOW(MSM_CAM_IOCTL_MAGIC, 19, uint8_t *) #define MSM_CAM_IOCTL_PICT_PP_DONE \ _IOW(MSM_CAM_IOCTL_MAGIC, 20, struct msm_snapshot_pp_status *) #define MSM_CAM_IOCTL_SENSOR_IO_CFG \ _IOW(MSM_CAM_IOCTL_MAGIC, 21, struct sensor_cfg_data *) #define MSM_CAM_IOCTL_FLASH_LED_CFG \ _IOW(MSM_CAM_IOCTL_MAGIC, 22, unsigned *) #define MSM_CAM_IOCTL_UNBLOCK_POLL_FRAME \ _IO(MSM_CAM_IOCTL_MAGIC, 23) #define MSM_CAM_IOCTL_CTRL_COMMAND_2 \ _IOW(MSM_CAM_IOCTL_MAGIC, 24, struct msm_ctrl_cmd *) #define MSM_CAM_IOCTL_AF_CTRL \ _IOR(MSM_CAM_IOCTL_MAGIC, 25, struct msm_ctrl_cmt_t *) #define MSM_CAM_IOCTL_AF_CTRL_DONE \ _IOW(MSM_CAM_IOCTL_MAGIC, 26, struct msm_ctrl_cmt_t *) #define MSM_CAM_IOCTL_CONFIG_VPE \ _IOW(MSM_CAM_IOCTL_MAGIC, 27, struct msm_camera_vpe_cfg_cmd *) #define MSM_CAM_IOCTL_AXI_VPE_CONFIG \ _IOW(MSM_CAM_IOCTL_MAGIC, 28, struct msm_camera_vpe_cfg_cmd *) #define MSM_CAM_IOCTL_STROBE_FLASH_CFG \ _IOW(MSM_CAM_IOCTL_MAGIC, 29, uint32_t *) #define MSM_CAM_IOCTL_STROBE_FLASH_CHARGE \ _IOW(MSM_CAM_IOCTL_MAGIC, 30, uint32_t *) #define MSM_CAM_IOCTL_STROBE_FLASH_RELEASE \ _IO(MSM_CAM_IOCTL_MAGIC, 31) #define MSM_CAM_IOCTL_FLASH_CTRL \ _IOW(MSM_CAM_IOCTL_MAGIC, 32, struct flash_ctrl_data *) #define MSM_CAM_IOCTL_ERROR_CONFIG \ _IOW(MSM_CAM_IOCTL_MAGIC, 33, uint32_t *) #define MSM_CAM_IOCTL_ABORT_CAPTURE \ _IO(MSM_CAM_IOCTL_MAGIC, 34) #define MSM_CAM_IOCTL_SET_FD_ROI \ _IOW(MSM_CAM_IOCTL_MAGIC, 35, struct fd_roi_info *) #define MSM_CAM_IOCTL_GET_CAMERA_INFO \ _IOR(MSM_CAM_IOCTL_MAGIC, 36, struct msm_camera_info *) #define MSM_CAM_IOCTL_UNBLOCK_POLL_PIC_FRAME \ _IO(MSM_CAM_IOCTL_MAGIC, 37) #define MSM_CAM_IOCTL_RELEASE_PIC_BUFFER \ _IOW(MSM_CAM_IOCTL_MAGIC, 38, struct camera_enable_cmd *) #define MSM_CAM_IOCTL_PUT_ST_FRAME \ _IOW(MSM_CAM_IOCTL_MAGIC, 39, struct msm_camera_st_frame *) #define MSM_CAM_IOCTL_V4L2_EVT_NOTIFY \ _IOR(MSM_CAM_IOCTL_MAGIC, 40, struct v4l2_event *) #define MSM_CAM_IOCTL_SET_MEM_MAP_INFO \ _IOR(MSM_CAM_IOCTL_MAGIC, 41, struct msm_mem_map_info *) #define MSM_CAM_IOCTL_ACTUATOR_IO_CFG \ _IOW(MSM_CAM_IOCTL_MAGIC, 42, struct msm_actuator_cfg_data *) #define MSM_CAM_IOCTL_MCTL_POST_PROC \ _IOW(MSM_CAM_IOCTL_MAGIC, 43, struct msm_mctl_post_proc_cmd *) #define MSM_CAM_IOCTL_RESERVE_FREE_FRAME \ _IOW(MSM_CAM_IOCTL_MAGIC, 44, struct msm_cam_evt_divert_frame *) #define MSM_CAM_IOCTL_RELEASE_FREE_FRAME \ _IOR(MSM_CAM_IOCTL_MAGIC, 45, struct msm_cam_evt_divert_frame *) #define MSM_CAM_IOCTL_PICT_PP_DIVERT_DONE \ _IOR(MSM_CAM_IOCTL_MAGIC, 46, struct msm_pp_frame *) #define MSM_CAM_IOCTL_SENSOR_V4l2_S_CTRL \ _IOR(MSM_CAM_IOCTL_MAGIC, 47, struct v4l2_control) #define MSM_CAM_IOCTL_SENSOR_V4l2_QUERY_CTRL \ _IOR(MSM_CAM_IOCTL_MAGIC, 48, struct v4l2_queryctrl) #define MSM_CAM_IOCTL_GET_KERNEL_SYSTEM_TIME \ _IOW(MSM_CAM_IOCTL_MAGIC, 49, struct timeval *) #define MSM_CAM_IOCTL_SET_VFE_OUTPUT_TYPE \ _IOW(MSM_CAM_IOCTL_MAGIC, 50, uint32_t *) #define MSM_CAM_IOCTL_MCTL_DIVERT_DONE \ _IOR(MSM_CAM_IOCTL_MAGIC, 51, struct msm_cam_evt_divert_frame *) #define MSM_CAM_IOCTL_GET_ACTUATOR_INFO \ _IOW(MSM_CAM_IOCTL_MAGIC, 52, struct msm_actuator_cfg_data *) #define MSM_CAM_IOCTL_EEPROM_IO_CFG \ _IOW(MSM_CAM_IOCTL_MAGIC, 53, struct msm_eeprom_cfg_data *) #define MSM_CAM_IOCTL_ISPIF_IO_CFG \ _IOR(MSM_CAM_IOCTL_MAGIC, 54, struct ispif_cfg_data *) struct msm_mctl_pp_cmd { int32_t id; uint16_t length; void *value; }; struct msm_mctl_post_proc_cmd { int32_t type; struct msm_mctl_pp_cmd cmd; }; #define MSM_CAMERA_LED_OFF 0 #define MSM_CAMERA_LED_LOW 1 #define MSM_CAMERA_LED_HIGH 2 #define MSM_CAMERA_LED_INIT 3 #define MSM_CAMERA_LED_RELEASE 4 #define MSM_CAMERA_STROBE_FLASH_NONE 0 #define MSM_CAMERA_STROBE_FLASH_XENON 1 #define MSM_MAX_CAMERA_SENSORS 5 #define MAX_SENSOR_NAME 32 #define MAX_CAM_NAME_SIZE 32 #define MAX_ACT_MOD_NAME_SIZE 32 #define MAX_ACT_NAME_SIZE 32 #define NUM_ACTUATOR_DIR 2 #define MAX_ACTUATOR_SCENARIO 8 #define MAX_ACTUATOR_REGION 5 #define MAX_ACTUATOR_INIT_SET 12 #define MAX_ACTUATOR_TYPE_SIZE 32 #define MAX_ACTUATOR_REG_TBL_SIZE 8 #define MSM_MAX_CAMERA_CONFIGS 2 #define PP_SNAP 0x01 #define PP_RAW_SNAP ((0x01)<<1) #define PP_PREV ((0x01)<<2) #define PP_THUMB ((0x01)<<3) #define PP_MASK (PP_SNAP|PP_RAW_SNAP|PP_PREV|PP_THUMB) #define MSM_CAM_CTRL_CMD_DONE 0 #define MSM_CAM_SENSOR_VFE_CMD 1 /* Should be same as VIDEO_MAX_PLANES in videodev2.h */ #define MAX_PLANES 8 /***************************************************** * structure *****************************************************/ /* define five type of structures for userspace <==> kernel * space communication: * command 1 - 2 are from userspace ==> kernel * command 3 - 4 are from kernel ==> userspace * * 1. control command: control command(from control thread), * control status (from config thread); */ struct msm_ctrl_cmd { uint16_t type; uint16_t length; void *value; uint16_t status; uint32_t timeout_ms; int resp_fd; /* FIXME: to be used by the kernel, pass-through for now */ int vnode_id; /* video dev id. Can we overload resp_fd? */ int queue_idx; uint32_t evt_id; uint32_t stream_type; /* used to pass value to qcamera server */ int config_ident; /*used as identifier for config node*/ }; struct msm_cam_evt_msg { unsigned short type; /* 1 == event (RPC), 0 == message (adsp) */ unsigned short msg_id; unsigned int len; /* size in, number of bytes out */ uint32_t frame_id; void *data; struct timespec timestamp; }; struct msm_pp_frame_sp { /* phy addr of the buffer */ unsigned long phy_addr; uint32_t y_off; uint32_t cbcr_off; /* buffer length */ uint32_t length; int32_t fd; uint32_t addr_offset; /* mapped addr */ unsigned long vaddr; }; struct msm_pp_frame_mp { /* phy addr of the plane */ unsigned long phy_addr; /* offset of plane data */ uint32_t data_offset; /* plane length */ uint32_t length; int32_t fd; uint32_t addr_offset; /* mapped addr */ unsigned long vaddr; }; struct msm_pp_frame { uint32_t handle; /* stores vb cookie */ uint32_t frame_id; unsigned short buf_idx; int path; unsigned short image_type; unsigned short num_planes; /* 1 for sp */ struct timeval timestamp; union { struct msm_pp_frame_sp sp; struct msm_pp_frame_mp mp[MAX_PLANES]; }; int node_type; }; struct msm_cam_evt_divert_frame { unsigned short image_mode; unsigned short op_mode; unsigned short inst_idx; unsigned short node_idx; struct msm_pp_frame frame; int do_pp; }; struct msm_mctl_pp_cmd_ack_event { uint32_t cmd; /* VPE_CMD_ZOOM? */ int status; /* 0 done, < 0 err */ uint32_t cookie; /* daemon's cookie */ }; struct msm_mctl_pp_event_info { int32_t event; union { struct msm_mctl_pp_cmd_ack_event ack; }; }; struct msm_isp_event_ctrl { unsigned short resptype; union { struct msm_cam_evt_msg isp_msg; struct msm_ctrl_cmd ctrl; struct msm_cam_evt_divert_frame div_frame; struct msm_mctl_pp_event_info pp_event_info; } isp_data; }; #define MSM_CAM_RESP_CTRL 0 #define MSM_CAM_RESP_STAT_EVT_MSG 1 #define MSM_CAM_RESP_STEREO_OP_1 2 #define MSM_CAM_RESP_STEREO_OP_2 3 #define MSM_CAM_RESP_V4L2 4 #define MSM_CAM_RESP_DIV_FRAME_EVT_MSG 5 #define MSM_CAM_RESP_DONE_EVENT 6 #define MSM_CAM_RESP_MCTL_PP_EVENT 7 #define MSM_CAM_RESP_MAX 8 #define MSM_CAM_APP_NOTIFY_EVENT 0 #define MSM_CAM_APP_NOTIFY_ERROR_EVENT 1 /* this one is used to send ctrl/status up to config thread */ struct msm_stats_event_ctrl { /* 0 - ctrl_cmd from control thread, * 1 - stats/event kernel, * 2 - V4L control or read request */ int resptype; int timeout_ms; struct msm_ctrl_cmd ctrl_cmd; /* struct vfe_event_t stats_event; */ struct msm_cam_evt_msg stats_event; }; /* 2. config command: config command(from config thread); */ struct msm_camera_cfg_cmd { /* what to config: * 1 - sensor config, 2 - vfe config */ uint16_t cfg_type; /* sensor config type */ uint16_t cmd_type; uint16_t queue; uint16_t length; void *value; }; #define CMD_GENERAL 0 #define CMD_AXI_CFG_OUT1 1 #define CMD_AXI_CFG_SNAP_O1_AND_O2 2 #define CMD_AXI_CFG_OUT2 3 #define CMD_PICT_T_AXI_CFG 4 #define CMD_PICT_M_AXI_CFG 5 #define CMD_RAW_PICT_AXI_CFG 6 #define CMD_FRAME_BUF_RELEASE 7 #define CMD_PREV_BUF_CFG 8 #define CMD_SNAP_BUF_RELEASE 9 #define CMD_SNAP_BUF_CFG 10 #define CMD_STATS_DISABLE 11 #define CMD_STATS_AEC_AWB_ENABLE 12 #define CMD_STATS_AF_ENABLE 13 #define CMD_STATS_AEC_ENABLE 14 #define CMD_STATS_AWB_ENABLE 15 #define CMD_STATS_ENABLE 16 #define CMD_STATS_AXI_CFG 17 #define CMD_STATS_AEC_AXI_CFG 18 #define CMD_STATS_AF_AXI_CFG 19 #define CMD_STATS_AWB_AXI_CFG 20 #define CMD_STATS_RS_AXI_CFG 21 #define CMD_STATS_CS_AXI_CFG 22 #define CMD_STATS_IHIST_AXI_CFG 23 #define CMD_STATS_SKIN_AXI_CFG 24 #define CMD_STATS_BUF_RELEASE 25 #define CMD_STATS_AEC_BUF_RELEASE 26 #define CMD_STATS_AF_BUF_RELEASE 27 #define CMD_STATS_AWB_BUF_RELEASE 28 #define CMD_STATS_RS_BUF_RELEASE 29 #define CMD_STATS_CS_BUF_RELEASE 30 #define CMD_STATS_IHIST_BUF_RELEASE 31 #define CMD_STATS_SKIN_BUF_RELEASE 32 #define UPDATE_STATS_INVALID 33 #define CMD_AXI_CFG_SNAP_GEMINI 34 #define CMD_AXI_CFG_SNAP 35 #define CMD_AXI_CFG_PREVIEW 36 #define CMD_AXI_CFG_VIDEO 37 #define CMD_STATS_IHIST_ENABLE 38 #define CMD_STATS_RS_ENABLE 39 #define CMD_STATS_CS_ENABLE 40 #define CMD_VPE 41 #define CMD_AXI_CFG_VPE 42 #define CMD_AXI_CFG_ZSL 43 #define CMD_AXI_CFG_SNAP_VPE 44 #define CMD_AXI_CFG_SNAP_THUMB_VPE 45 #define CMD_CONFIG_PING_ADDR 46 #define CMD_CONFIG_PONG_ADDR 47 #define CMD_CONFIG_FREE_BUF_ADDR 48 #define CMD_AXI_CFG_ZSL_ALL_CHNLS 49 #define CMD_AXI_CFG_VIDEO_ALL_CHNLS 50 #define CMD_VFE_BUFFER_RELEASE 51 #define CMD_VFE_PROCESS_IRQ 52 #define CMD_AXI_CFG_PRIM BIT(8) #define CMD_AXI_CFG_PRIM_ALL_CHNLS BIT(9) #define CMD_AXI_CFG_SEC BIT(10) #define CMD_AXI_CFG_SEC_ALL_CHNLS BIT(11) #define CMD_AXI_CFG_TERT1 BIT(12) #define CMD_AXI_CFG_TERT2 BIT(13) /* vfe config command: config command(from config thread)*/ struct msm_vfe_cfg_cmd { int cmd_type; uint16_t length; void *value; }; struct msm_vpe_cfg_cmd { int cmd_type; uint16_t length; void *value; }; #define MAX_CAMERA_ENABLE_NAME_LEN 32 struct camera_enable_cmd { char name[MAX_CAMERA_ENABLE_NAME_LEN]; }; #define MSM_PMEM_OUTPUT1 0 #define MSM_PMEM_OUTPUT2 1 #define MSM_PMEM_OUTPUT1_OUTPUT2 2 #define MSM_PMEM_THUMBNAIL 3 #define MSM_PMEM_MAINIMG 4 #define MSM_PMEM_RAW_MAINIMG 5 #define MSM_PMEM_AEC_AWB 6 #define MSM_PMEM_AF 7 #define MSM_PMEM_AEC 8 #define MSM_PMEM_AWB 9 #define MSM_PMEM_RS 10 #define MSM_PMEM_CS 11 #define MSM_PMEM_IHIST 12 #define MSM_PMEM_SKIN 13 #define MSM_PMEM_VIDEO 14 #define MSM_PMEM_PREVIEW 15 #define MSM_PMEM_VIDEO_VPE 16 #define MSM_PMEM_C2D 17 #define MSM_PMEM_MAINIMG_VPE 18 #define MSM_PMEM_THUMBNAIL_VPE 19 #define MSM_PMEM_MAX 20 #define STAT_AEAW 0 #define STAT_AEC 1 #define STAT_AF 2 #define STAT_AWB 3 #define STAT_RS 4 #define STAT_CS 5 #define STAT_IHIST 6 #define STAT_SKIN 7 #define STAT_MAX 8 #define FRAME_PREVIEW_OUTPUT1 0 #define FRAME_PREVIEW_OUTPUT2 1 #define FRAME_SNAPSHOT 2 #define FRAME_THUMBNAIL 3 #define FRAME_RAW_SNAPSHOT 4 #define FRAME_MAX 5 struct msm_pmem_info { int type; int fd; void *vaddr; uint32_t offset; uint32_t len; uint32_t y_off; uint32_t cbcr_off; uint32_t planar0_off; uint32_t planar1_off; uint32_t planar2_off; uint8_t active; }; struct outputCfg { uint32_t height; uint32_t width; uint32_t window_height_firstline; uint32_t window_height_lastline; }; #define VIDEO_NODE 0 #define MCTL_NODE 1 #define OUTPUT_1 0 #define OUTPUT_2 1 #define OUTPUT_1_AND_2 2 /* snapshot only */ #define OUTPUT_1_AND_3 3 /* video */ #define CAMIF_TO_AXI_VIA_OUTPUT_2 4 #define OUTPUT_1_AND_CAMIF_TO_AXI_VIA_OUTPUT_2 5 #define OUTPUT_2_AND_CAMIF_TO_AXI_VIA_OUTPUT_1 6 #define OUTPUT_1_2_AND_3 7 #define OUTPUT_ALL_CHNLS 8 #define OUTPUT_VIDEO_ALL_CHNLS 9 #define OUTPUT_ZSL_ALL_CHNLS 10 #define LAST_AXI_OUTPUT_MODE_ENUM = OUTPUT_ZSL_ALL_CHNLS #define OUTPUT_PRIM BIT(8) #define OUTPUT_PRIM_ALL_CHNLS BIT(9) #define OUTPUT_SEC BIT(10) #define OUTPUT_SEC_ALL_CHNLS BIT(11) #define OUTPUT_TERT1 BIT(12) #define OUTPUT_TERT2 BIT(13) #define MSM_FRAME_PREV_1 0 #define MSM_FRAME_PREV_2 1 #define MSM_FRAME_ENC 2 #define OUTPUT_TYPE_P BIT(0) #define OUTPUT_TYPE_T BIT(1) #define OUTPUT_TYPE_S BIT(2) #define OUTPUT_TYPE_V BIT(3) #define OUTPUT_TYPE_L BIT(4) #define OUTPUT_TYPE_ST_L BIT(5) #define OUTPUT_TYPE_ST_R BIT(6) #define OUTPUT_TYPE_ST_D BIT(7) #define OUTPUT_TYPE_R BIT(8) #define OUTPUT_TYPE_R1 BIT(9) struct fd_roi_info { void *info; int info_len; }; struct msm_mem_map_info { uint32_t cookie; uint32_t length; uint32_t mem_type; }; #define MSM_MEM_MMAP 0 #define MSM_MEM_USERPTR 1 #define MSM_PLANE_MAX 8 #define MSM_PLANE_Y 0 #define MSM_PLANE_UV 1 struct msm_frame { struct timespec ts; int path; int type; unsigned long buffer; uint32_t phy_offset; uint32_t y_off; uint32_t cbcr_off; uint32_t planar0_off; uint32_t planar1_off; uint32_t planar2_off; int fd; void *cropinfo; int croplen; uint32_t error_code; struct fd_roi_info roi_info; uint32_t frame_id; int stcam_quality_ind; uint32_t stcam_conv_value; struct ion_allocation_data ion_alloc; struct ion_fd_data fd_data; int ion_dev_fd; }; enum msm_st_frame_packing { SIDE_BY_SIDE_HALF, SIDE_BY_SIDE_FULL, TOP_DOWN_HALF, TOP_DOWN_FULL, }; struct msm_st_crop { uint32_t in_w; uint32_t in_h; uint32_t out_w; uint32_t out_h; }; struct msm_st_half { uint32_t buf_p0_off; uint32_t buf_p1_off; uint32_t buf_p0_stride; uint32_t buf_p1_stride; uint32_t pix_x_off; uint32_t pix_y_off; struct msm_st_crop stCropInfo; }; struct msm_st_frame { struct msm_frame buf_info; int type; enum msm_st_frame_packing packing; struct msm_st_half L; struct msm_st_half R; int frame_id; }; #define MSM_CAMERA_ERR_MASK (0xFFFFFFFF & 1) struct stats_buff { unsigned long buff; int fd; }; struct msm_stats_buf { uint8_t awb_ymin; struct stats_buff aec; struct stats_buff awb; struct stats_buff af; struct stats_buff ihist; struct stats_buff rs; struct stats_buff cs; struct stats_buff skin; int type; uint32_t status_bits; unsigned long buffer; int fd; int length; struct ion_handle *handle; uint32_t frame_id; }; #define MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT 0 /* video capture mode in VIDIOC_S_PARM */ #define MSM_V4L2_EXT_CAPTURE_MODE_PREVIEW \ (MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT+1) /* extendedmode for video recording in VIDIOC_S_PARM */ #define MSM_V4L2_EXT_CAPTURE_MODE_VIDEO \ (MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT+2) /* extendedmode for the full size main image in VIDIOC_S_PARM */ #define MSM_V4L2_EXT_CAPTURE_MODE_MAIN (MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT+3) /* extendedmode for the thumb nail image in VIDIOC_S_PARM */ #define MSM_V4L2_EXT_CAPTURE_MODE_THUMBNAIL \ (MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT+4) #define MSM_V4L2_EXT_CAPTURE_MODE_RAW \ (MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT+5) #define MSM_V4L2_EXT_CAPTURE_MODE_RDI \ (MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT+6) #define MSM_V4L2_EXT_CAPTURE_MODE_RDI1 \ (MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT+7) #define MSM_V4L2_EXT_CAPTURE_MODE_RDI2 \ (MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT+8) /* */ #if 1 #define MSM_V4L2_EXT_CAPTURE_MODE_V2X_LIVESHOT \ (MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT+9) #define MSM_V4L2_EXT_CAPTURE_MODE_MAX (MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT+10) #else #define MSM_V4L2_EXT_CAPTURE_MODE_MAX (MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT+9) #endif /* */ #define MSM_V4L2_PID_MOTION_ISO V4L2_CID_PRIVATE_BASE #define MSM_V4L2_PID_EFFECT (V4L2_CID_PRIVATE_BASE+1) #define MSM_V4L2_PID_HJR (V4L2_CID_PRIVATE_BASE+2) #define MSM_V4L2_PID_LED_MODE (V4L2_CID_PRIVATE_BASE+3) #define MSM_V4L2_PID_PREP_SNAPSHOT (V4L2_CID_PRIVATE_BASE+4) #define MSM_V4L2_PID_EXP_METERING (V4L2_CID_PRIVATE_BASE+5) #define MSM_V4L2_PID_ISO (V4L2_CID_PRIVATE_BASE+6) #define MSM_V4L2_PID_CAM_MODE (V4L2_CID_PRIVATE_BASE+7) #define MSM_V4L2_PID_LUMA_ADAPTATION (V4L2_CID_PRIVATE_BASE+8) #define MSM_V4L2_PID_BEST_SHOT (V4L2_CID_PRIVATE_BASE+9) #define MSM_V4L2_PID_FOCUS_MODE (V4L2_CID_PRIVATE_BASE+10) #define MSM_V4L2_PID_BL_DETECTION (V4L2_CID_PRIVATE_BASE+11) #define MSM_V4L2_PID_SNOW_DETECTION (V4L2_CID_PRIVATE_BASE+12) #define MSM_V4L2_PID_CTRL_CMD (V4L2_CID_PRIVATE_BASE+13) #define MSM_V4L2_PID_EVT_SUB_INFO (V4L2_CID_PRIVATE_BASE+14) #define MSM_V4L2_PID_STROBE_FLASH (V4L2_CID_PRIVATE_BASE+15) #define MSM_V4L2_PID_MMAP_ENTRY (V4L2_CID_PRIVATE_BASE+16) #define MSM_V4L2_PID_MMAP_INST (V4L2_CID_PRIVATE_BASE+17) #define MSM_V4L2_PID_PP_PLANE_INFO (V4L2_CID_PRIVATE_BASE+18) #define MSM_V4L2_PID_MAX MSM_V4L2_PID_PP_PLANE_INFO /* camera operation mode for video recording - two frame output queues */ #define MSM_V4L2_CAM_OP_DEFAULT 0 /* camera operation mode for video recording - two frame output queues */ #define MSM_V4L2_CAM_OP_PREVIEW (MSM_V4L2_CAM_OP_DEFAULT+1) /* camera operation mode for video recording - two frame output queues */ #define MSM_V4L2_CAM_OP_VIDEO (MSM_V4L2_CAM_OP_DEFAULT+2) /* camera operation mode for standard shapshot - two frame output queues */ #define MSM_V4L2_CAM_OP_CAPTURE (MSM_V4L2_CAM_OP_DEFAULT+3) /* camera operation mode for zsl shapshot - three output queues */ #define MSM_V4L2_CAM_OP_ZSL (MSM_V4L2_CAM_OP_DEFAULT+4) /* camera operation mode for raw snapshot - one frame output queue */ #define MSM_V4L2_CAM_OP_RAW (MSM_V4L2_CAM_OP_DEFAULT+5) /* camera operation mode for jpeg snapshot - one frame output queue */ #define MSM_V4L2_CAM_OP_JPEG_CAPTURE (MSM_V4L2_CAM_OP_DEFAULT+6) #define MSM_V4L2_VID_CAP_TYPE 0 #define MSM_V4L2_STREAM_ON 1 #define MSM_V4L2_STREAM_OFF 2 #define MSM_V4L2_SNAPSHOT 3 #define MSM_V4L2_QUERY_CTRL 4 #define MSM_V4L2_GET_CTRL 5 #define MSM_V4L2_SET_CTRL 6 #define MSM_V4L2_QUERY 7 #define MSM_V4L2_GET_CROP 8 #define MSM_V4L2_SET_CROP 9 #define MSM_V4L2_OPEN 10 #define MSM_V4L2_CLOSE 11 #define MSM_V4L2_SET_CTRL_CMD 12 #define MSM_V4L2_EVT_SUB_MASK 13 #define MSM_V4L2_MAX 14 #define V4L2_CAMERA_EXIT 43 struct crop_info { void *info; int len; }; struct msm_postproc { int ftnum; struct msm_frame fthumnail; int fmnum; struct msm_frame fmain; }; struct msm_snapshot_pp_status { void *status; }; #define CFG_SET_MODE 0 #define CFG_SET_EFFECT 1 #define CFG_START 2 #define CFG_PWR_UP 3 #define CFG_PWR_DOWN 4 #define CFG_WRITE_EXPOSURE_GAIN 5 #define CFG_SET_DEFAULT_FOCUS 6 #define CFG_MOVE_FOCUS 7 #define CFG_REGISTER_TO_REAL_GAIN 8 #define CFG_REAL_TO_REGISTER_GAIN 9 #define CFG_SET_FPS 10 #define CFG_SET_PICT_FPS 11 #define CFG_SET_BRIGHTNESS 12 #define CFG_SET_CONTRAST 13 #define CFG_SET_ZOOM 14 #define CFG_SET_EXPOSURE_MODE 15 #define CFG_SET_WB 16 #define CFG_SET_ANTIBANDING 17 #define CFG_SET_EXP_GAIN 18 #define CFG_SET_PICT_EXP_GAIN 19 #define CFG_SET_LENS_SHADING 20 #define CFG_GET_PICT_FPS 21 #define CFG_GET_PREV_L_PF 22 #define CFG_GET_PREV_P_PL 23 #define CFG_GET_PICT_L_PF 24 #define CFG_GET_PICT_P_PL 25 #define CFG_GET_AF_MAX_STEPS 26 #define CFG_GET_PICT_MAX_EXP_LC 27 #define CFG_SEND_WB_INFO 28 #define CFG_SENSOR_INIT 29 #define CFG_GET_3D_CALI_DATA 30 #define CFG_GET_CALIB_DATA 31 #define CFG_GET_OUTPUT_INFO 32 #define CFG_GET_EEPROM_INFO 33 #define CFG_GET_EEPROM_DATA 34 #define CFG_SET_ACTUATOR_INFO 35 #define CFG_GET_ACTUATOR_INFO 36 /* TBD: QRD */ #define CFG_SET_SATURATION 37 #define CFG_SET_SHARPNESS 38 #define CFG_SET_TOUCHAEC 39 #define CFG_SET_AUTO_FOCUS 40 #define CFG_SET_AUTOFLASH 41 #define CFG_SET_EXPOSURE_COMPENSATION 42 #define CFG_SET_ISO 43 #define CFG_START_STREAM 44 #define CFG_STOP_STREAM 45 #define CFG_GET_CSI_PARAMS 46 /* */ #define CFG_SET_AEC_ROI_PARAMS 47 /* */ #define CFG_GET_SOC_SNAPSHOT_DATA 48 #define CFG_MAX 49 //48 // 47 /* */ /* */ #define MOVE_NEAR 0 #define MOVE_FAR 1 #define SENSOR_PREVIEW_MODE 0 #define SENSOR_SNAPSHOT_MODE 1 #define SENSOR_RAW_SNAPSHOT_MODE 2 #define SENSOR_HFR_60FPS_MODE 3 #define SENSOR_HFR_90FPS_MODE 4 #define SENSOR_HFR_120FPS_MODE 5 #define SENSOR_QTR_SIZE 0 #define SENSOR_FULL_SIZE 1 #define SENSOR_QVGA_SIZE 2 #define SENSOR_INVALID_SIZE 3 #define CAMERA_EFFECT_OFF 0 #define CAMERA_EFFECT_MONO 1 #define CAMERA_EFFECT_NEGATIVE 2 #define CAMERA_EFFECT_SOLARIZE 3 #define CAMERA_EFFECT_SEPIA 4 #define CAMERA_EFFECT_POSTERIZE 5 #define CAMERA_EFFECT_WHITEBOARD 6 #define CAMERA_EFFECT_BLACKBOARD 7 #define CAMERA_EFFECT_AQUA 8 #define CAMERA_EFFECT_EMBOSS 9 #define CAMERA_EFFECT_SKETCH 10 #define CAMERA_EFFECT_NEON 11 #define CAMERA_EFFECT_MAX 12 /* QRD */ #define CAMERA_EFFECT_BW 10 #define CAMERA_EFFECT_BLUISH 12 #define CAMERA_EFFECT_REDDISH 13 #define CAMERA_EFFECT_GREENISH 14 /* QRD */ #define CAMERA_ANTIBANDING_OFF 0 #define CAMERA_ANTIBANDING_50HZ 2 #define CAMERA_ANTIBANDING_60HZ 1 #define CAMERA_ANTIBANDING_AUTO 3 #define CAMERA_CONTRAST_LV0 0 #define CAMERA_CONTRAST_LV1 1 #define CAMERA_CONTRAST_LV2 2 #define CAMERA_CONTRAST_LV3 3 #define CAMERA_CONTRAST_LV4 4 #define CAMERA_CONTRAST_LV5 5 #define CAMERA_CONTRAST_LV6 6 #define CAMERA_CONTRAST_LV7 7 #define CAMERA_CONTRAST_LV8 8 #define CAMERA_CONTRAST_LV9 9 #define CAMERA_BRIGHTNESS_LV0 0 #define CAMERA_BRIGHTNESS_LV1 1 #define CAMERA_BRIGHTNESS_LV2 2 #define CAMERA_BRIGHTNESS_LV3 3 #define CAMERA_BRIGHTNESS_LV4 4 #define CAMERA_BRIGHTNESS_LV5 5 #define CAMERA_BRIGHTNESS_LV6 6 #define CAMERA_BRIGHTNESS_LV7 7 #define CAMERA_BRIGHTNESS_LV8 8 #define CAMERA_SATURATION_LV0 0 #define CAMERA_SATURATION_LV1 1 #define CAMERA_SATURATION_LV2 2 #define CAMERA_SATURATION_LV3 3 #define CAMERA_SATURATION_LV4 4 #define CAMERA_SATURATION_LV5 5 #define CAMERA_SATURATION_LV6 6 #define CAMERA_SATURATION_LV7 7 #define CAMERA_SATURATION_LV8 8 #define CAMERA_SHARPNESS_LV0 0 #define CAMERA_SHARPNESS_LV1 3 #define CAMERA_SHARPNESS_LV2 6 #define CAMERA_SHARPNESS_LV3 9 #define CAMERA_SHARPNESS_LV4 12 #define CAMERA_SHARPNESS_LV5 15 #define CAMERA_SHARPNESS_LV6 18 #define CAMERA_SHARPNESS_LV7 21 #define CAMERA_SHARPNESS_LV8 24 #define CAMERA_SHARPNESS_LV9 27 #define CAMERA_SHARPNESS_LV10 30 #define CAMERA_SETAE_AVERAGE 0 #define CAMERA_SETAE_CENWEIGHT 1 #define CAMERA_WB_AUTO 1 /* This list must match aeecamera.h */ #define CAMERA_WB_CUSTOM 2 #define CAMERA_WB_INCANDESCENT 3 #define CAMERA_WB_FLUORESCENT 4 #define CAMERA_WB_DAYLIGHT 5 #define CAMERA_WB_CLOUDY_DAYLIGHT 6 #define CAMERA_WB_TWILIGHT 7 #define CAMERA_WB_SHADE 8 #define CAMERA_EXPOSURE_COMPENSATION_LV0 12 #define CAMERA_EXPOSURE_COMPENSATION_LV1 6 #define CAMERA_EXPOSURE_COMPENSATION_LV2 0 #define CAMERA_EXPOSURE_COMPENSATION_LV3 -6 #define CAMERA_EXPOSURE_COMPENSATION_LV4 -12 enum msm_v4l2_saturation_level { MSM_V4L2_SATURATION_L0, MSM_V4L2_SATURATION_L1, MSM_V4L2_SATURATION_L2, MSM_V4L2_SATURATION_L3, MSM_V4L2_SATURATION_L4, MSM_V4L2_SATURATION_L5, MSM_V4L2_SATURATION_L6, MSM_V4L2_SATURATION_L7, MSM_V4L2_SATURATION_L8, MSM_V4L2_SATURATION_L9, MSM_V4L2_SATURATION_L10, }; enum msm_v4l2_contrast_level { MSM_V4L2_CONTRAST_L0, MSM_V4L2_CONTRAST_L1, MSM_V4L2_CONTRAST_L2, MSM_V4L2_CONTRAST_L3, MSM_V4L2_CONTRAST_L4, MSM_V4L2_CONTRAST_L5, MSM_V4L2_CONTRAST_L6, MSM_V4L2_CONTRAST_L7, MSM_V4L2_CONTRAST_L8, MSM_V4L2_CONTRAST_L9, MSM_V4L2_CONTRAST_L10, }; enum msm_v4l2_exposure_level { // #ifdef CONFIG_MACH_LGE MSM_V4L2_EXPOSURE_N6, MSM_V4L2_EXPOSURE_N5, MSM_V4L2_EXPOSURE_N4, MSM_V4L2_EXPOSURE_N3, #endif // MSM_V4L2_EXPOSURE_N2, MSM_V4L2_EXPOSURE_N1, MSM_V4L2_EXPOSURE_D, MSM_V4L2_EXPOSURE_P1, MSM_V4L2_EXPOSURE_P2, // #ifdef CONFIG_MACH_LGE MSM_V4L2_EXPOSURE_P3, MSM_V4L2_EXPOSURE_P4, MSM_V4L2_EXPOSURE_P5, MSM_V4L2_EXPOSURE_P6, #endif // }; enum msm_v4l2_sharpness_level { MSM_V4L2_SHARPNESS_L0, MSM_V4L2_SHARPNESS_L1, MSM_V4L2_SHARPNESS_L2, MSM_V4L2_SHARPNESS_L3, MSM_V4L2_SHARPNESS_L4, MSM_V4L2_SHARPNESS_L5, MSM_V4L2_SHARPNESS_L6, }; enum msm_v4l2_expo_metering_mode { MSM_V4L2_EXP_FRAME_AVERAGE, MSM_V4L2_EXP_CENTER_WEIGHTED, MSM_V4L2_EXP_SPOT_METERING, }; enum msm_v4l2_iso_mode { MSM_V4L2_ISO_AUTO = 0, MSM_V4L2_ISO_DEBLUR, MSM_V4L2_ISO_100, MSM_V4L2_ISO_200, MSM_V4L2_ISO_400, MSM_V4L2_ISO_800, MSM_V4L2_ISO_1600, }; enum msm_v4l2_wb_mode { MSM_V4L2_WB_OFF, MSM_V4L2_WB_AUTO , MSM_V4L2_WB_CUSTOM, MSM_V4L2_WB_INCANDESCENT, MSM_V4L2_WB_FLUORESCENT, MSM_V4L2_WB_DAYLIGHT, MSM_V4L2_WB_CLOUDY_DAYLIGHT, }; enum msm_v4l2_special_effect { MSM_V4L2_EFFECT_OFF, MSM_V4L2_EFFECT_MONO, MSM_V4L2_EFFECT_NEGATIVE, MSM_V4L2_EFFECT_SOLARIZE, MSM_V4L2_EFFECT_SEPIA, MSM_V4L2_EFFECT_POSTERAIZE, MSM_V4L2_EFFECT_WHITEBOARD, MSM_V4L2_EFFECT_BLACKBOARD, MSM_V4L2_EFFECT_AQUA, MSM_V4L2_EFFECT_EMBOSS, MSM_V4L2_EFFECT_SKETCH, MSM_V4L2_EFFECT_NEON, MSM_V4L2_EFFECT_MAX, }; enum msm_v4l2_power_line_frequency { MSM_V4L2_POWER_LINE_OFF, MSM_V4L2_POWER_LINE_60HZ, MSM_V4L2_POWER_LINE_50HZ, MSM_V4L2_POWER_LINE_AUTO, }; /* */ enum msm_v4l2_night_mode { MSM_V4L2_NIGHT_MODE_OFF = 0, // CAMERA_BESTSHOT_OFF (@camera.h) MSM_V4L2_NIGHT_MODE_ON = 6, // CAMERA_BESTSHOT_NIGHT (@camera.h) }; /* */ /* */ enum msm_v4l2_fps_range { MSM_V4L2_FPS_15_15, MSM_V4L2_FPS_7P5_30, MSM_V4L2_FPS_10_30, MSM_V4L2_FPS_15_30, MSM_V4L2_FPS_20_30, MSM_V4L2_FPS_24_30, MSM_V4L2_FPS_30_30, }; /* */ // enum msm_v4l2_bestshot_mode { MSM_V4L2_BESTSHOT_OFF = 0, MSM_V4L2_BESTSHOT_AUTO = 1, MSM_V4L2_BESTSHOT_LANDSCAPE = 2, MSM_V4L2_BESTSHOT_SNOW = 3, MSM_V4L2_BESTSHOT_BEACH = 4, MSM_V4L2_BESTSHOT_SUNSET = 5, MSM_V4L2_BESTSHOT_NIGHT = 6, MSM_V4L2_BESTSHOT_PORTRAIT = 7, MSM_V4L2_BESTSHOT_BACKLIGHT = 8, MSM_V4L2_BESTSHOT_SPORTS = 9, MSM_V4L2_BESTSHOT_ANTISHAKE, MSM_V4L2_BESTSHOT_FLOWERS, MSM_V4L2_BESTSHOT_CANDLELIGHT, MSM_V4L2_BESTSHOT_FIREWORKS, MSM_V4L2_BESTSHOT_PARTY, MSM_V4L2_BESTSHOT_NIGHT_PORTRAIT, MSM_V4L2_BESTSHOT_THEATRE, MSM_V4L2_BESTSHOT_ACTION, MSM_V4L2_BESTSHOT_AR, MSM_V4L2_BESTSHOT_MAX }; // #define CAMERA_ISO_TYPE_AUTO 0 #define CAMEAR_ISO_TYPE_HJR 1 #define CAMEAR_ISO_TYPE_100 2 #define CAMERA_ISO_TYPE_200 3 #define CAMERA_ISO_TYPE_400 4 #define CAMEAR_ISO_TYPE_800 5 #define CAMERA_ISO_TYPE_1600 6 struct sensor_pict_fps { uint16_t prevfps; uint16_t pictfps; }; /* */ struct snapshot_soc_data_cfg { uint32_t iso_speed; uint32_t exposure_time; }; /* */ struct exp_gain_cfg { uint16_t gain; uint32_t line; }; struct focus_cfg { int32_t steps; int dir; }; struct fps_cfg { uint16_t f_mult; uint16_t fps_div; uint32_t pict_fps_div; }; struct wb_info_cfg { uint16_t red_gain; uint16_t green_gain; uint16_t blue_gain; }; struct sensor_3d_exp_cfg { uint16_t gain; uint32_t line; uint16_t r_gain; uint16_t b_gain; uint16_t gr_gain; uint16_t gb_gain; uint16_t gain_adjust; }; struct sensor_3d_cali_data_t{ unsigned char left_p_matrix[3][4][8]; unsigned char right_p_matrix[3][4][8]; unsigned char square_len[8]; unsigned char focal_len[8]; unsigned char pixel_pitch[8]; uint16_t left_r; uint16_t left_b; uint16_t left_gb; uint16_t left_af_far; uint16_t left_af_mid; uint16_t left_af_short; uint16_t left_af_5um; uint16_t left_af_50up; uint16_t left_af_50down; uint16_t right_r; uint16_t right_b; uint16_t right_gb; uint16_t right_af_far; uint16_t right_af_mid; uint16_t right_af_short; uint16_t right_af_5um; uint16_t right_af_50up; uint16_t right_af_50down; }; struct sensor_init_cfg { uint8_t prev_res; uint8_t pict_res; }; //Start :randy@qualcomm.com for calibration 2012.04.15 #define ROLLOFF_CALDATA_SIZE (17 * 13) typedef struct { unsigned short mesh_rolloff_table_size; // TableSize uint8_t r_gain[ROLLOFF_CALDATA_SIZE]; // RGain uint8_t gr_gain[ROLLOFF_CALDATA_SIZE]; // GRGain uint8_t gb_gain[ROLLOFF_CALDATA_SIZE]; // GBGain uint8_t b_gain[ROLLOFF_CALDATA_SIZE]; // BGain uint8_t red_ref[17]; } rolloff_caldata_array_type; struct sensor_calib_data { /* Color Related Measurements */ uint16_t r_over_g; uint16_t b_over_g; uint16_t gr_over_gb; /* Lens Related Measurements */ uint16_t macro_2_inf; uint16_t inf_2_macro; uint16_t stroke_amt; uint16_t af_pos_1m; uint16_t af_pos_inf; /* Lens Shading Calibration Data */ rolloff_caldata_array_type rolloff; }; //End :randy@qualcomm.com for calibration 2012.04.15 enum msm_sensor_resolution_t { MSM_SENSOR_RES_FULL, MSM_SENSOR_RES_QTR, MSM_SENSOR_RES_2, MSM_SENSOR_RES_3, MSM_SENSOR_RES_4, MSM_SENSOR_RES_5, MSM_SENSOR_RES_6, MSM_SENSOR_RES_7, MSM_SENSOR_INVALID_RES, }; struct msm_sensor_output_info_t { uint16_t x_output; uint16_t y_output; uint16_t line_length_pclk; uint16_t frame_length_lines; uint32_t vt_pixel_clk; uint32_t op_pixel_clk; uint16_t binning_factor; }; struct sensor_output_info_t { struct msm_sensor_output_info_t *output_info; uint16_t num_info; }; struct mirror_flip { int32_t x_mirror; int32_t y_flip; }; struct cord { uint32_t x; uint32_t y; }; struct msm_eeprom_data_t { void *eeprom_data; uint16_t index; }; struct msm_camera_csid_vc_cfg { uint8_t cid; uint8_t dt; uint8_t decode_format; }; struct csi_lane_params_t { uint8_t csi_lane_assign; uint8_t csi_lane_mask; uint8_t csi_if; uint8_t csid_core; uint32_t csid_version; }; #define CSI_EMBED_DATA 0x12 #define CSI_RESERVED_DATA_0 0x13 #define CSI_YUV422_8 0x1E #define CSI_RAW8 0x2A #define CSI_RAW10 0x2B #define CSI_RAW12 0x2C #define CSI_DECODE_6BIT 0 #define CSI_DECODE_8BIT 1 #define CSI_DECODE_10BIT 2 #define CSI_DECODE_DPCM_10_8_10 5 #define ISPIF_STREAM(intf, action) (((intf)<<ISPIF_S_STREAM_SHIFT)+(action)) #define ISPIF_ON_FRAME_BOUNDARY (0x01 << 0) #define ISPIF_OFF_FRAME_BOUNDARY (0x01 << 1) #define ISPIF_OFF_IMMEDIATELY (0x01 << 2) #define ISPIF_S_STREAM_SHIFT 4 #define PIX_0 (0x01 << 0) #define RDI_0 (0x01 << 1) #define PIX_1 (0x01 << 2) #define RDI_1 (0x01 << 3) #define PIX_2 (0x01 << 4) #define RDI_2 (0x01 << 5) enum msm_ispif_intftype { PIX0, RDI0, PIX1, RDI1, PIX2, RDI2, INTF_MAX, }; enum msm_ispif_vc { VC0, VC1, VC2, VC3, }; enum msm_ispif_cid { CID0, CID1, CID2, CID3, CID4, CID5, CID6, CID7, CID8, CID9, CID10, CID11, CID12, CID13, CID14, CID15, }; struct msm_ispif_params { uint8_t intftype; uint16_t cid_mask; uint8_t csid; }; struct msm_ispif_params_list { uint32_t len; struct msm_ispif_params params[4]; }; enum ispif_cfg_type_t { ISPIF_INIT, ISPIF_SET_CFG, ISPIF_SET_ON_FRAME_BOUNDARY, ISPIF_SET_OFF_FRAME_BOUNDARY, ISPIF_SET_OFF_IMMEDIATELY, ISPIF_RELEASE, }; struct ispif_cfg_data { enum ispif_cfg_type_t cfgtype; union { uint32_t csid_version; int cmd; struct msm_ispif_params_list ispif_params; } cfg; }; struct sensor_cfg_data { int cfgtype; int mode; int rs; uint8_t max_steps; union { int8_t effect; uint8_t lens_shading; uint16_t prevl_pf; uint16_t prevp_pl; uint16_t pictl_pf; uint16_t pictp_pl; uint32_t pict_max_exp_lc; uint16_t p_fps; uint8_t iso_type; struct sensor_init_cfg init_info; struct sensor_pict_fps gfps; struct exp_gain_cfg exp_gain; struct focus_cfg focus; struct fps_cfg fps; struct wb_info_cfg wb_info; struct sensor_3d_exp_cfg sensor_3d_exp; struct sensor_calib_data calib_info; struct sensor_output_info_t output_info; struct msm_eeprom_data_t eeprom_data; struct csi_lane_params_t csi_lane_params; /* QRD */ uint16_t antibanding; uint8_t contrast; uint8_t saturation; uint8_t sharpness; int8_t brightness; int ae_mode; uint8_t wb_val; int8_t exp_compensation; struct cord aec_cord; int is_autoflash; struct mirror_flip mirror_flip; /* */ int32_t aec_roi_pos; /* */ /* */ struct snapshot_soc_data_cfg snapshot_data; /* */ } cfg; }; struct damping_params_t { uint32_t damping_step; uint32_t damping_delay; uint32_t hw_params; }; enum actuator_type { ACTUATOR_VCM, ACTUATOR_PIEZO, }; enum msm_actuator_data_type { MSM_ACTUATOR_BYTE_DATA = 1, MSM_ACTUATOR_WORD_DATA, }; enum msm_actuator_addr_type { MSM_ACTUATOR_BYTE_ADDR = 1, MSM_ACTUATOR_WORD_ADDR, }; enum msm_actuator_write_type { MSM_ACTUATOR_WRITE_HW_DAMP, MSM_ACTUATOR_WRITE_DAC, }; struct msm_actuator_reg_params_t { enum msm_actuator_write_type reg_write_type; uint32_t hw_mask; uint16_t reg_addr; uint16_t hw_shift; uint16_t data_shift; }; struct reg_settings_t { uint16_t reg_addr; uint16_t reg_data; }; struct region_params_t { /* [0] = ForwardDirection Macro boundary [1] = ReverseDirection Inf boundary */ uint16_t step_bound[2]; uint16_t code_per_step; }; struct msm_actuator_move_params_t { int8_t dir; int8_t sign_dir; int16_t dest_step_pos; int32_t num_steps; struct damping_params_t *ringing_params; }; struct msm_actuator_tuning_params_t { int16_t initial_code; uint16_t pwd_step; uint16_t region_size; uint32_t total_steps; struct region_params_t *region_params; }; struct msm_actuator_params_t { enum actuator_type act_type; uint8_t reg_tbl_size; uint16_t data_size; uint16_t init_setting_size; uint32_t i2c_addr; enum msm_actuator_addr_type i2c_addr_type; enum msm_actuator_data_type i2c_data_type; struct msm_actuator_reg_params_t *reg_tbl_params; struct reg_settings_t *init_settings; }; struct msm_actuator_set_info_t { struct msm_actuator_params_t actuator_params; struct msm_actuator_tuning_params_t af_tuning_params; }; struct msm_actuator_get_info_t { uint32_t focal_length_num; uint32_t focal_length_den; uint32_t f_number_num; uint32_t f_number_den; uint32_t f_pix_num; uint32_t f_pix_den; uint32_t total_f_dist_num; uint32_t total_f_dist_den; uint32_t hor_view_angle_num; uint32_t hor_view_angle_den; uint32_t ver_view_angle_num; uint32_t ver_view_angle_den; }; enum af_camera_name { ACTUATOR_MAIN_CAM_0, ACTUATOR_MAIN_CAM_1, ACTUATOR_MAIN_CAM_2, ACTUATOR_MAIN_CAM_3, ACTUATOR_MAIN_CAM_4, ACTUATOR_MAIN_CAM_5, ACTUATOR_MAIN_CAM_6, ACTUATOR_WEB_CAM_0, ACTUATOR_WEB_CAM_1, ACTUATOR_WEB_CAM_2, }; struct msm_actuator_cfg_data { int cfgtype; uint8_t is_af_supported; union { struct msm_actuator_move_params_t move; struct msm_actuator_set_info_t set_info; struct msm_actuator_get_info_t get_info; enum af_camera_name cam_name; } cfg; }; struct msm_eeprom_support { uint16_t is_supported; uint16_t size; uint16_t index; uint16_t qvalue; }; struct msm_calib_wb { uint16_t r_over_g; uint16_t b_over_g; uint16_t gr_over_gb; }; struct msm_calib_af { uint16_t macro_dac; uint16_t inf_dac; uint16_t start_dac; }; struct msm_calib_lsc { uint16_t r_gain[221]; uint16_t b_gain[221]; uint16_t gr_gain[221]; uint16_t gb_gain[221]; }; struct pixel_t { int x; int y; }; struct msm_calib_dpc { uint16_t validcount; struct pixel_t snapshot_coord[128]; struct pixel_t preview_coord[128]; struct pixel_t video_coord[128]; }; struct msm_camera_eeprom_info_t { struct msm_eeprom_support af; struct msm_eeprom_support wb; struct msm_eeprom_support lsc; struct msm_eeprom_support dpc; }; struct msm_eeprom_cfg_data { int cfgtype; uint8_t is_eeprom_supported; union { struct msm_eeprom_data_t get_data; struct msm_camera_eeprom_info_t get_info; } cfg; }; struct sensor_large_data { int cfgtype; union { struct sensor_3d_cali_data_t sensor_3d_cali_data; } data; }; enum sensor_type_t { BAYER, YUV, JPEG_SOC, }; enum flash_type { LED_FLASH, STROBE_FLASH, }; enum strobe_flash_ctrl_type { STROBE_FLASH_CTRL_INIT, STROBE_FLASH_CTRL_CHARGE, STROBE_FLASH_CTRL_RELEASE }; struct strobe_flash_ctrl_data { enum strobe_flash_ctrl_type type; int charge_en; }; struct msm_camera_info { int num_cameras; uint8_t has_3d_support[MSM_MAX_CAMERA_SENSORS]; uint8_t is_internal_cam[MSM_MAX_CAMERA_SENSORS]; uint32_t s_mount_angle[MSM_MAX_CAMERA_SENSORS]; const char *video_dev_name[MSM_MAX_CAMERA_SENSORS]; enum sensor_type_t sensor_type[MSM_MAX_CAMERA_SENSORS]; }; struct msm_cam_config_dev_info { int num_config_nodes; const char *config_dev_name[MSM_MAX_CAMERA_CONFIGS]; int config_dev_id[MSM_MAX_CAMERA_CONFIGS]; }; struct msm_mctl_node_info { int num_mctl_nodes; const char *mctl_node_name[MSM_MAX_CAMERA_SENSORS]; }; struct flash_ctrl_data { int flashtype; union { int led_state; struct strobe_flash_ctrl_data strobe_ctrl; } ctrl_data; }; #define GET_NAME 0 #define GET_PREVIEW_LINE_PER_FRAME 1 #define GET_PREVIEW_PIXELS_PER_LINE 2 #define GET_SNAPSHOT_LINE_PER_FRAME 3 #define GET_SNAPSHOT_PIXELS_PER_LINE 4 #define GET_SNAPSHOT_FPS 5 #define GET_SNAPSHOT_MAX_EP_LINE_CNT 6 struct msm_camsensor_info { char name[MAX_SENSOR_NAME]; uint8_t flash_enabled; uint8_t strobe_flash_enabled; uint8_t actuator_enabled; uint8_t ispif_supported; int8_t total_steps; uint8_t support_3d; enum flash_type flashtype; enum sensor_type_t sensor_type; uint32_t pxlcode; /* enum v4l2_mbus_pixelcode */ uint32_t camera_type; /* msm_camera_type */ int mount_angle; uint32_t max_width; uint32_t max_height; }; #define V4L2_SINGLE_PLANE 0 #define V4L2_MULTI_PLANE_Y 0 #define V4L2_MULTI_PLANE_CBCR 1 #define V4L2_MULTI_PLANE_CB 1 #define V4L2_MULTI_PLANE_CR 2 struct plane_data { int plane_id; uint32_t offset; unsigned long size; }; struct img_plane_info { uint32_t width; uint32_t height; uint32_t pixelformat; uint8_t buffer_type; /*Single/Multi planar*/ uint8_t output_port; uint32_t ext_mode; uint8_t num_planes; struct plane_data plane[MAX_PLANES]; uint32_t sp_y_offset; uint8_t vpe_can_use; }; #define QCAMERA_NAME "qcamera" #define QCAMERA_DEVICE_GROUP_ID 1 #define QCAMERA_VNODE_GROUP_ID 2 #define MSM_CAM_V4L2_IOCTL_GET_CAMERA_INFO \ _IOWR('V', BASE_VIDIOC_PRIVATE + 1, struct msm_camera_v4l2_ioctl_t *) #define MSM_CAM_V4L2_IOCTL_GET_CONFIG_INFO \ _IOWR('V', BASE_VIDIOC_PRIVATE + 2, struct msm_camera_v4l2_ioctl_t *) #define MSM_CAM_V4L2_IOCTL_GET_MCTL_INFO \ _IOWR('V', BASE_VIDIOC_PRIVATE + 3, struct msm_camera_v4l2_ioctl_t *) #define MSM_CAM_V4L2_IOCTL_CTRL_CMD_DONE \ _IOWR('V', BASE_VIDIOC_PRIVATE + 4, struct msm_camera_v4l2_ioctl_t *) #define MSM_CAM_V4L2_IOCTL_GET_EVENT_PAYLOAD \ _IOWR('V', BASE_VIDIOC_PRIVATE + 5, struct msm_camera_v4l2_ioctl_t *) #define MSM_CAM_IOCTL_SEND_EVENT \ _IOWR('V', BASE_VIDIOC_PRIVATE + 6, struct v4l2_event) struct msm_camera_v4l2_ioctl_t { void __user *ioctl_ptr; }; #endif /* __LINUX_MSM_CAMERA_H */
chijure/phoenix_v1
include/media/msm_camera.h
C
gpl-2.0
43,609
<?php /* * Фронтенд для взаимодействия с EasyPay * на базе протокола: http://store.nightfly.biz/st/1461842084/EasyPay.Provider.3.1.pdf * * Проверить можно тут: http://provider.easysoft.com.ua/ */ // подключаем API OpenPayz include ("../../libs/api.openpayz.php"); //debug mode define('DEBUG_MODE', 0); //transaction storage path define('TRANSACTION_PATH', './tmp/'); //Error codes define('NO_SUCH_USER', '-1'); define('ERROR_PAYMENT', '-2'); define('TRANSACTION_EXISTS', '-3'); define('TRANSACTION_NOT_EXIST', '-4'); define('BAD_CHECKSUM', '-5'); /** * Returns all user RealNames * * @return array */ function ep_UserGetAllRealnames() { $query_fio = "SELECT * from `realname`"; $allfioz = simple_queryall($query_fio); $fioz = array(); if (!empty($allfioz)) { foreach ($allfioz as $ia => $eachfio) { $fioz[$eachfio['login']] = $eachfio['realname']; } } return($fioz); } /** * Check is transaction unique? * * @param $hash - hash string to check * @return bool/int */ function ep_GetTransaction($transactionIdRaw) { if (file_exists(TRANSACTION_PATH . $transactionIdRaw)) { return (true); } else { return (false); } } /** * Gets existing transaction date * * @param $id - existing transaction id * @return bool/datetime */ function ep_GetTransactionTime($id) { $id = vf($id, 3); $query = "SELECT `date` from `op_transactions` WHERE `id`='" . $id . "'"; $data = simple_query($query); if (!empty($data)) { return ($data['date']); } else { return (false); } } /** * Saves unprocessed transaction for further usage & returns its ID * * @param array $data Request data * * @return string */ function ep_SaveTransaction($data) { $result = false; $fileName = $data['Payment']['OrderId']; $toSave = serialize($data); if (file_exists(TRANSACTION_PATH)) { file_put_contents(TRANSACTION_PATH . $fileName, $toSave); if (file_exists(TRANSACTION_PATH . $fileName)) { $result = $fileName; } else { die('No write permissions to ' . TRANSACTION_PATH . ' directory'); } } else { mkdir(TRANSACTION_PATH); if (!file_exists(TRANSACTION_PATH)) { die('No directory write permissions!'); } else { file_put_contents(TRANSACTION_PATH . $fileName, $toSave); if (file_exists(TRANSACTION_PATH . $fileName)) { $result = $fileName; } else { die('No write permissions to ' . TRANSACTION_PATH . ' directory'); } } } return ($result); } /** * Returns transaction data by its ID * * @param string $transactionId * * @return array */ function ep_GetTransactionData($transactionId) { $result = array(); if (file_exists(TRANSACTION_PATH . $transactionId)) { $raw = file_get_contents(TRANSACTION_PATH . $transactionId); $result = unserialize($raw); } return ($result); } /** * Check is transaction unique? * * @param $hash - hash string to check * @return bool/int */ function ep_CheckTransactionUnique($hash) { $hash = mysql_real_escape_string($hash); $query = "SELECT `id` from `op_transactions` WHERE `hash`='" . $hash . "'"; $data = simple_query($query); if (empty($data)) { return (true); } else { return (false); } } //catch POST request //deprecated in PHP 5.6 //$xml = $HTTP_RAW_POST_DATA; $xml = file_get_contents('php://input'); $rawXml = xml2array($xml); //debug mode logging if (!empty($rawXml)) { if (DEBUG_MODE) { $debugSave = print_r($rawXml, true); file_put_contents('debug.log', $debugSave, FILE_APPEND | LOCK_EX); } } //check request validity if (!empty($rawXml)) { if (isset($rawXml['Request'])) { //определяем тип запроса if (isset($rawXml['Request']['Check'])) { // // проверка пользователя // $allcustomers = op_CustomersGetAll(); $checkCustomerId = $rawXml['Request']['Check']['Account']; if (isset($allcustomers[$checkCustomerId])) { @$userlogin = $allcustomers[$checkCustomerId]; $allrealnames = ep_UserGetAllRealnames(); $reply = ' <Response> <StatusCode>0</StatusCode> <StatusDetail>Ok</StatusDetail> <DateTime>' . date("Y-m-d\TH:i:s") . '</DateTime> <AccountInfo> <Name>' . @$allrealnames[$userlogin] . '</Name> </AccountInfo> </Response> '; $reply = trim($reply); die($reply); } else { $reply = ' <Response> <StatusCode>' . NO_SUCH_USER . '</StatusCode> <StatusDetail>User not found</StatusDetail> </Response> '; $reply = trim($reply); die($reply); } } // // creating unprocessed transaction in TRANSACTION_PATH // if (isset($rawXml['Request']['Payment'])) { $allcustomers = op_CustomersGetAll(); $paymentCustomerId = mysql_real_escape_string($rawXml['Request']['Payment']['Account']); $transactionIdRaw = $rawXml['Request']['Payment']['OrderId']; if (isset($allcustomers[$paymentCustomerId])) { if (!ep_GetTransaction($transactionIdRaw)) { $newTransactionId = ep_SaveTransaction($rawXml['Request']); $reply = ' <Response> <StatusCode>0</StatusCode> <StatusDetail>Order Created</StatusDetail> <DateTime>' . date("Y-m-d\TH:i:s") . '</DateTime> <PaymentId>' . $newTransactionId . '</PaymentId> </Response> '; $reply = trim($reply); die($reply); } else { //уже есть такая транзакцийка $reply = ' <Response> <StatusCode>' . TRANSACTION_EXISTS . '</StatusCode> <StatusDetail>Duplicate transaction</StatusDetail> <DateTime>' . date("Y-m-d\TH:i:s") . '</DateTime> <PaymentId>' . ep_GetTransaction($transactionIdRaw) . '</PaymentId> </Response> '; $reply = trim($reply); die($reply); } } else { $reply = ' <Response> <StatusCode>' . NO_SUCH_USER . '</StatusCode> <StatusDetail>No such user</StatusDetail> <DateTime>' . date("Y-m-d\TH:i:s") . '</DateTime> <PaymentId>' . ep_GetTransaction($transactionIdRaw) . '</PaymentId> </Response> '; $reply = trim($reply); die($reply); } } // // Transaction confirmation // if (isset($rawXml['Request']['Confirm'])) { $checkPaymentID = mysql_real_escape_string($rawXml['Request']['Confirm']['PaymentId']); $transactionDataRaw = ep_GetTransactionData($checkPaymentID); @$transactionDate = $transactionDataRaw['DateTime']; if ($transactionDate) { $hashClean = mysql_real_escape_string($transactionDataRaw['Payment']['OrderId']); $hash = 'EP_' . $hashClean; $summ = mysql_real_escape_string($transactionDataRaw['Payment']['Amount']); $paymentCustomerId = mysql_real_escape_string($transactionDataRaw['Payment']['Account']); if (ep_CheckTransactionUnique($hash)) { //really processin cash & openpayz transaction op_TransactionAdd($hash, $summ, $paymentCustomerId, 'EASYPAY', 'no debug info'); op_ProcessHandlers(); } $reply = ' <Response> <StatusCode>0</StatusCode> <StatusDetail>Transaction Ok</StatusDetail> <DateTime>' . date("Y-m-d\TH:i:s") . '</DateTime> <OrderDate>' . $transactionDate . '</OrderDate> </Response> '; $reply = trim($reply); die($reply); } else { //нету такой транзакции $reply = ' <Response> <StatusCode>' . TRANSACTION_NOT_EXIST . '</StatusCode> <StatusDetail>No existing transaction</StatusDetail> <DateTime>' . date("Y-m-d\TH:i:s") . '</DateTime> <PaymentId>' . $checkPaymentID . '</PaymentId> </Response> '; $reply = trim($reply); die($reply); } } } // // Transaction cancel dummy reply // if (isset($rawXml['Request']['Cancel'])) { $curDate = date("Y-m-d\TH:i:s"); $reply = '<Response> <StatusCode>' . ERROR_PAYMENT . '</StatusCode> <StatusDetail>Transaction destroyed</StatusDetail> <DateTime>' . $curDate . '</DateTime> <CancelDate>' . $curDate . '</CancelDate> </Response>'; $reply = trim($reply); die($reply); } } else { die('EMPTY_POST_DATA'); } ?>
pautiina/Ubilling
openpayz/frontend/easypay/index.php
PHP
gpl-2.0
9,959
/* * Copyright (c) 2009-2010 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package jme3test.audio; import com.jme3.app.SimpleApplication; import com.jme3.asset.plugins.UrlLocator; import com.jme3.audio.AudioNode; public class TestMusicStreaming extends SimpleApplication { public static void main(String[] args){ TestMusicStreaming test = new TestMusicStreaming(); test.start(); } @Override public void simpleInitApp(){ assetManager.registerLocator("http://www.vorbis.com/music/", UrlLocator.class); AudioNode audioSource = new AudioNode(assetManager, "Lumme-Badloop.ogg", true); audioSource.play(); } @Override public void simpleUpdate(float tpf){} }
rex-xxx/mt6572_x201
external/jmonkeyengine/engine/src/test/jme3test/audio/TestMusicStreaming.java
Java
gpl-2.0
2,229
<?php namespace Laminas\Feed\Reader\Extension\Atom; use DateTime; use DOMDocument; use DOMElement; use DOMNodeList; use Laminas\Feed\Reader; use Laminas\Feed\Reader\Collection; use Laminas\Feed\Reader\Extension; use Laminas\Feed\Uri; use stdClass; use function array_key_exists; use function count; use function is_string; use function preg_replace; use function strlen; use function trim; use function version_compare; use const PHP_VERSION; class Entry extends Extension\AbstractEntry { /** * Get the specified author * * @param int $index * @return null|string */ public function getAuthor($index = 0) { $authors = $this->getAuthors(); return isset($authors[$index]) && is_string($authors[$index]) ? $authors[$index] : null; } /** * Get an array with feed authors * * @return Collection\Author */ public function getAuthors() { if (array_key_exists('authors', $this->data)) { return $this->data['authors']; } $authors = []; $list = $this->getXpath()->query($this->getXpathPrefix() . '//atom:author'); if (! $list instanceof DOMNodeList || ! $list->length) { /** * TODO: Limit query to feed level els only! */ $list = $this->getXpath()->query('//atom:author'); } if ($list instanceof DOMNodeList && $list->length) { foreach ($list as $author) { $author = $this->getAuthorFromElement($author); if (! empty($author)) { $authors[] = $author; } } } if (count($authors) === 0) { $authors = new Collection\Author(); } else { $authors = new Collection\Author( Reader\Reader::arrayUnique($authors) ); } $this->data['authors'] = $authors; return $this->data['authors']; } /** * Get the entry content * * @return string */ public function getContent() { if (array_key_exists('content', $this->data)) { return $this->data['content']; } $content = null; $el = $this->getXpath()->query($this->getXpathPrefix() . '/atom:content'); if ($el->length > 0) { $el = $el->item(0); $type = $el->getAttribute('type'); switch ($type) { case '': case 'text': case 'text/plain': case 'html': case 'text/html': $content = $el->nodeValue; break; case 'xhtml': $this->getXpath()->registerNamespace('xhtml', 'http://www.w3.org/1999/xhtml'); $xhtml = $this->getXpath() ->query($this->getXpathPrefix() . '/atom:content/xhtml:div') ->item(0); $d = new DOMDocument('1.0', $this->getEncoding()); $deep = version_compare(PHP_VERSION, '7', 'ge') ? 1 : true; $xhtmls = $d->importNode($xhtml, $deep); $d->appendChild($xhtmls); $content = $this->collectXhtml( $d->saveXML(), $d->lookupPrefix('http://www.w3.org/1999/xhtml') ); break; } } if (! $content) { $content = $this->getDescription(); } $this->data['content'] = trim($content ?? ''); return $this->data['content']; } /** * Parse out XHTML to remove the namespacing * * @param string $xhtml * @param string $prefix * @return mixed */ protected function collectXhtml($xhtml, $prefix) { if (! empty($prefix)) { $prefix .= ':'; } $matches = [ '/<\?xml[^<]*>[^<]*<' . $prefix . 'div[^>]*>/', '/<\/' . $prefix . 'div>\s*$/', ]; $xhtml = preg_replace($matches, '', $xhtml); if (! empty($prefix)) { $xhtml = preg_replace('/(<[\/]?)' . $prefix . '([a-zA-Z]+)/', '$1$2', $xhtml); } return $xhtml; } /** * Get the entry creation date * * @return null|DateTime */ public function getDateCreated() { if (array_key_exists('datecreated', $this->data)) { return $this->data['datecreated']; } $date = null; if ($this->getAtomType() === Reader\Reader::TYPE_ATOM_03) { $dateCreated = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:created)'); } else { $dateCreated = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:published)'); } if ($dateCreated) { $date = new DateTime($dateCreated); } $this->data['datecreated'] = $date; return $this->data['datecreated']; } /** * Get the entry modification date * * @return null|DateTime */ public function getDateModified() { if (array_key_exists('datemodified', $this->data)) { return $this->data['datemodified']; } $date = null; if ($this->getAtomType() === Reader\Reader::TYPE_ATOM_03) { $dateModified = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:modified)'); } else { $dateModified = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:updated)'); } if ($dateModified) { $date = new DateTime($dateModified); } $this->data['datemodified'] = $date; return $this->data['datemodified']; } /** * Get the entry description * * @return string */ public function getDescription() { if (array_key_exists('description', $this->data)) { return $this->data['description']; } $description = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:summary)'); if (! $description) { $description = null; } $this->data['description'] = $description; return $this->data['description']; } /** * Get the entry enclosure * * @return null|object{href: string, length: int, type: string} */ public function getEnclosure() { if (array_key_exists('enclosure', $this->data)) { return $this->data['enclosure']; } $enclosure = null; $nodeList = $this->getXpath()->query($this->getXpathPrefix() . '/atom:link[@rel="enclosure"]'); if ($nodeList instanceof DOMNodeList && $nodeList->length > 0) { /** @var DOMElement $node */ $node = $nodeList->item(0); $enclosure = new stdClass(); $enclosure->url = $node->getAttribute('href'); $enclosure->length = $node->getAttribute('length'); $enclosure->type = $node->getAttribute('type'); } $this->data['enclosure'] = $enclosure; return $this->data['enclosure']; } /** * Get the entry ID * * @return string */ public function getId() { if (array_key_exists('id', $this->data)) { return $this->data['id']; } $id = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:id)'); if (! $id) { if ($this->getPermalink()) { $id = $this->getPermalink(); } elseif ($this->getTitle()) { $id = $this->getTitle(); } else { $id = null; } } $this->data['id'] = $id; return $this->data['id']; } /** * Get the base URI of the feed (if set). * * @return null|string */ public function getBaseUrl() { if (array_key_exists('baseUrl', $this->data)) { return $this->data['baseUrl']; } $baseUrl = $this->getXpath()->evaluate( 'string(' . $this->getXpathPrefix() . '/@xml:base[1])' ); if (! $baseUrl) { $baseUrl = $this->getXpath()->evaluate('string(//@xml:base[1])'); } if (! $baseUrl) { $baseUrl = null; } $this->data['baseUrl'] = $baseUrl; return $this->data['baseUrl']; } /** * Get a specific link * * @param int $index * @return null|string */ public function getLink($index = 0) { if (! array_key_exists('links', $this->data)) { $this->getLinks(); } return isset($this->data['links']) && is_string($this->data['links']) ? $this->data['links'] : null; } /** * Get all links * * @return array */ public function getLinks() { if (array_key_exists('links', $this->data)) { return $this->data['links']; } $links = []; $list = $this->getXpath()->query( $this->getXpathPrefix() . '//atom:link[@rel="alternate"]/@href|' . $this->getXpathPrefix() . '//atom:link[not(@rel)]/@href' ); if ($list instanceof DOMNodeList && $list->length) { foreach ($list as $link) { $links[] = $this->absolutiseUri($link->value); } } $this->data['links'] = $links; return $this->data['links']; } /** * Get a permalink to the entry * * @return string */ public function getPermalink() { $permalink = $this->getLink(0); return is_string($permalink) ? $permalink : ''; } /** * Get the entry title * * @return string */ public function getTitle() { if (array_key_exists('title', $this->data)) { return $this->data['title']; } $title = $this->getXpath()->evaluate('string(' . $this->getXpathPrefix() . '/atom:title)'); if (! is_string($title)) { $title = null; } $this->data['title'] = $title; return $this->data['title']; } /** * Get the number of comments/replies for current entry * * @return int */ public function getCommentCount() { if (array_key_exists('commentcount', $this->data)) { return $this->data['commentcount']; } $count = null; $this->getXpath()->registerNamespace('thread10', 'http://purl.org/syndication/thread/1.0'); $list = $this->getXpath()->query( $this->getXpathPrefix() . '//atom:link[@rel="replies"]/@thread10:count' ); if ($list instanceof DOMNodeList && $list->length) { $count = $list->item(0)->value; } $this->data['commentcount'] = $count; return $this->data['commentcount']; } /** * Returns a URI pointing to the HTML page where comments can be made on this entry * * @return string */ public function getCommentLink() { if (array_key_exists('commentlink', $this->data)) { return $this->data['commentlink']; } $link = null; $list = $this->getXpath()->query( $this->getXpathPrefix() . '//atom:link[@rel="replies" and @type="text/html"]/@href' ); if ($list instanceof DOMNodeList && $list->length) { $link = $list->item(0)->value; $link = $this->absolutiseUri($link); } $this->data['commentlink'] = $link; return $this->data['commentlink']; } /** * Returns a URI pointing to a feed of all comments for this entry * * @param string $type * @return string */ public function getCommentFeedLink($type = 'atom') { if (array_key_exists('commentfeedlink', $this->data)) { return $this->data['commentfeedlink']; } $link = null; $list = $this->getXpath()->query( $this->getXpathPrefix() . '//atom:link[@rel="replies" and @type="application/' . $type . '+xml"]/@href' ); if ($list instanceof DOMNodeList && $list->length) { $link = $list->item(0)->value; $link = $this->absolutiseUri($link); } $this->data['commentfeedlink'] = $link; return $this->data['commentfeedlink']; } /** * Get all categories * * @return Collection\Category */ public function getCategories() { if (array_key_exists('categories', $this->data)) { return $this->data['categories']; } if ($this->getAtomType() === Reader\Reader::TYPE_ATOM_10) { $list = $this->getXpath()->query($this->getXpathPrefix() . '//atom:category'); } else { /** * Since Atom 0.3 did not support categories, it would have used the * Dublin Core extension. However there is a small possibility Atom 0.3 * may have been retrofitted to use Atom 1.0 instead. */ $this->getXpath()->registerNamespace('atom10', Reader\Reader::NAMESPACE_ATOM_10); $list = $this->getXpath()->query($this->getXpathPrefix() . '//atom10:category'); } if ($list instanceof DOMNodeList && $list->length) { $categoryCollection = new Collection\Category(); foreach ($list as $category) { $categoryCollection[] = [ 'term' => $category->getAttribute('term'), 'scheme' => $category->getAttribute('scheme'), 'label' => $category->getAttribute('label'), ]; } } else { return new Collection\Category(); } $this->data['categories'] = $categoryCollection; return $this->data['categories']; } /** * Get source feed metadata from the entry * * @return null|Reader\Feed\Atom\Source */ public function getSource() { if (array_key_exists('source', $this->data)) { return $this->data['source']; } $source = null; // TODO: Investigate why _getAtomType() fails here. Is it even needed? if ($this->getType() === Reader\Reader::TYPE_ATOM_10) { $list = $this->getXpath()->query($this->getXpathPrefix() . '/atom:source[1]'); if ($list instanceof DOMNodeList && $list->length) { $element = $list->item(0); $source = new Reader\Feed\Atom\Source($element, $this->getXpathPrefix()); } } $this->data['source'] = $source; return $this->data['source']; } /** * Attempt to absolutise the URI, i.e. if a relative URI apply the * xml:base value as a prefix to turn into an absolute URI. * * @param string $link * @return null|string */ protected function absolutiseUri($link) { if (! Uri::factory($link)->isAbsolute()) { if ($this->getBaseUrl() !== null) { $link = $this->getBaseUrl() . $link; if (! Uri::factory($link)->isValid()) { $link = null; } } } return $link; } /** * Get an author entry * * @return array<string,null|string>|null * @psalm-return array{email?: null|string, name?: null|string, uri?: null|string}|null */ protected function getAuthorFromElement(DOMElement $element) { $author = []; $emailNode = $element->getElementsByTagName('email'); $nameNode = $element->getElementsByTagName('name'); $uriNode = $element->getElementsByTagName('uri'); if ($emailNode->length && strlen($emailNode->item(0)->nodeValue) > 0) { $author['email'] = $emailNode->item(0)->nodeValue; } if ($nameNode->length && strlen($nameNode->item(0)->nodeValue) > 0) { $author['name'] = $nameNode->item(0)->nodeValue; } if ($uriNode->length && strlen($uriNode->item(0)->nodeValue) > 0) { $author['uri'] = $uriNode->item(0)->nodeValue; } if (empty($author)) { return; } return $author; } /** * Register the default namespaces for the current feed format */ protected function registerNamespaces() { switch ($this->getAtomType()) { case Reader\Reader::TYPE_ATOM_03: $this->getXpath()->registerNamespace('atom', Reader\Reader::NAMESPACE_ATOM_03); break; default: $this->getXpath()->registerNamespace('atom', Reader\Reader::NAMESPACE_ATOM_10); break; } } /** * Detect the presence of any Atom namespaces in use * * @return null|string */ protected function getAtomType() { $dom = $this->getDomDocument(); $prefixAtom03 = $dom->lookupPrefix(Reader\Reader::NAMESPACE_ATOM_03); $prefixAtom10 = $dom->lookupPrefix(Reader\Reader::NAMESPACE_ATOM_10); if ( $dom->isDefaultNamespace(Reader\Reader::NAMESPACE_ATOM_03) || ! empty($prefixAtom03) ) { return Reader\Reader::TYPE_ATOM_03; } if ( $dom->isDefaultNamespace(Reader\Reader::NAMESPACE_ATOM_10) || ! empty($prefixAtom10) ) { return Reader\Reader::TYPE_ATOM_10; } return null; } }
tobiasbuhrer/tobiasb
vendor/laminas/laminas-feed/src/Reader/Extension/Atom/Entry.php
PHP
gpl-2.0
17,863
// license:BSD-3-Clause // copyright-holders:Mike Coates /************************************************************************** Gorf/Votrax SC-01 Emulator Mike@Dissfulfils.co.uk Modified to match phonemes to words Ajudd@quantime.co.uk ************************************************************************** gorf_sh_w - Write data to votrax port gorf_sh_status - Return busy status (-1 = busy) gorf_port_2_r - Returns status of voice port gorf_sh_ update- Null **************************************************************************/ #include "emu.h" #include "cpu/z80/z80.h" #include "includes/astrocde.h" #include "audio/gorf.h" /**************************************************************************** * 64 Phonemes - currently 1 sample per phoneme, will be combined sometime! ****************************************************************************/ static const char *const PhonemeTable[65] = { "EH3","EH2","EH1","PA0","DT" ,"A1" ,"A2" ,"ZH", "AH2","I3" ,"I2" ,"I1" ,"M" ,"N" ,"B" ,"V", "CH" ,"SH" ,"Z" ,"AW1","NG" ,"AH1","OO1","OO", "L" ,"K" ,"J" ,"H" ,"G" ,"F" ,"D" ,"S", "A" ,"AY" ,"Y1" ,"UH3","AH" ,"P" ,"O" ,"I", "U" ,"Y" ,"T" ,"R" ,"E" ,"W" ,"AE" ,"AE1", "AW2","UH2","UH1","UH" ,"O2" ,"O1" ,"IU" ,"U1", "THV","TH" ,"ER" ,"EH" ,"E1" ,"AW" ,"PA1","STOP", nullptr }; static const char *const GorfWordTable[] = { "A2AYY1","A2E1","UH1GEH1I3N","AE1EH2M","AEM", "AE1EH3ND","UH1NAH2I1YLA2SHUH2N","AH2NUHTHER","AH1NUHTHVRR", "AH1R","UHR","UH1VEH1EH3NNDJER","BAEEH3D","BAEEH1D","BE", "BEH3EH1N","buht","BUH1DTTEH2NN","KUHDEH2T", "KAE1NUH1T","KAE1EH3PTI3N", "KRAH2UH3NI3KUH3O2LZ","KO1UH3I3E1N","KO1UH3I3E1NS", "KERNAH2L","KAH1NCHEHSNEHS","DE1FEH1NDER", "DE1STRO1I1Y","DE1STRO1I1Y1D", "DU1UM","DRAW1S","EHMPAH2I3YR","EHND", "EH1NEH1MY","EH1SKA1E1P","FLEHGSHIP", "FOR","GUH1LAEKTI1K", "DJEH2NERUH3L","GDTO1O1RRFF","GDTO1RFYA2N","GDTO1RFE1EH2N","GDTO1RFYA2NS", "HAH1HAH1HAH1HAH1","hahaher.wav","HUHRDER", "HAE1EH3V","HI1TI1NG","AH1I1Y", "AH1I1Y1","I1MPAH1SI1BL", "IN*","INSERT","I1S","LI1V","LAWNG","MEE1T","MUU1V", "MAH2I1Y","MAH2I3Y","NIR","NEHKST","NUH3AH2YS","NO", "NAH1O1U1W","PA1","PLA1AYER","PRE1PAE1ER","PRI1SI3NEH3RS", "PRUH2MOTEH3D","POO1IUSH","RO1U1BAH1T","RO1U1BAH1TS", "RO1U1BAH1UH3TS","SEK", "SHIP","SHAH1UH3T","SUHM","SPA2I3YS","PA0", "SERVAH2I1Y1VUH3L","TAK","THVUH","THVUH1", "THUH","TAH1EH3YM","TU","TIUU1", "UH2NBE1AYTUH3BUH3L", "WORAYY1EH3R","WORAYY1EH3RS","WI1L", "Y1I3U1","YIUU1U1","YI1U1U1","Y1IUU1U1","Y1I1U1U1","YOR","YU1O1RSEH1LF","s.wav", "FO1R","FO2R","WIL","GDTO1RVYA2N", "KO1UH3I3AYNN", "UH1TAEEH3K","BAH2I3Y1T","KAH1NKER","DYVAH1U1ER","DUHST","GAE1LUH1KSY","GAH1EH3T", "PAH1I1R","TRAH2I1Y","SU1PRE1N","AWL","HA2AYL", "EH1MPAH1I1R", nullptr }; #define num_samples (sizeof(GorfWordTable)/sizeof(char *)) const char *const gorf_sample_names[] = { "*gorf","a","a","again","am","am","and","anhilatn", "another","another","are","are", "avenger","bad","bad","be", "been","but","button","cadet", "cannot","captain","chronicl","coin","coins","colonel", "consciou","defender","destroy","destroyd", "doom","draws","empire","end", "enemy","escape","flagship","for","galactic", "general","gorf","gorphian","gorphian","gorphins", "hahahahu","hahaher","harder","have", "hitting","i","i","impossib","in","insert", "is","live","long","meet","move", "my","my", "near","next","nice","no", "now","pause","player","prepare","prisonrs", "promoted","push","robot","robots","robots", "seek","ship","shot","some","space","spause", "survival","take","the","the","the","time", "to","to","unbeatab", "warrior","warriors","will", "you","you","you","you","your","your","yourself", "s","for","for","will","gorph", // Missing Samples "coin", "attack","bite","conquer","devour","dust", "galaxy","got","power","try","supreme","all", "hail","emperor", nullptr }; READ8_MEMBER( astrocde_state::gorf_speech_r ) { UINT8 data = offset >> 8; #if USE_FAKE_VOTRAX int Phoneme, Intonation; int i = 0; offset &= 0xff; m_totalword_ptr = m_totalword; Phoneme = data & 0x3F; Intonation = data >> 6; logerror("Date : %d Speech : %s at intonation %d\n",Phoneme, PhonemeTable[Phoneme],Intonation); if(Phoneme==63) { m_samples->stop(0); if (strlen(m_totalword)>2) logerror("Clearing sample %s\n",m_totalword); m_totalword[0] = 0; /* Clear the total word stack */ return data; } /* Phoneme to word translation */ if (*(m_totalword) == 0) { strcpy(m_totalword,PhonemeTable[Phoneme]); /* Copy over the first phoneme */ if (m_plural != 0) { logerror("found a possible plural at %d\n",m_plural-1); if (!strcmp("S",m_totalword)) { /* Plural check */ m_samples->start(0, num_samples-2); /* play the sample at position of word */ m_samples->set_frequency(0, 11025); /* play at correct rate */ m_totalword[0] = 0; /* Clear the total word stack */ m_oldword[0] = 0; /* Clear the total word stack */ return data; } else { m_plural=0; } } } else strcat(m_totalword,PhonemeTable[Phoneme]); /* Copy over the first phoneme */ logerror("Total word = %s\n",m_totalword); for (i=0; GorfWordTable[i]; i++) { if (!strcmp(GorfWordTable[i],m_totalword)) { /* Scan the word (sample) table for the complete word */ if ((!strcmp("GDTO1RFYA2N",m_totalword)) || (!strcmp("RO1U1BAH1T",m_totalword)) || (!strcmp("KO1UH3I3E1N",m_totalword)) || (!strcmp("WORAYY1EH3R",m_totalword)) || (!strcmp("IN",m_totalword)) ) { /* May be m_plural */ m_plural=i+1; strcpy(m_oldword,m_totalword); logerror("Storing sample position %d and copying string %s\n",m_plural,m_oldword); } else { m_plural=0; } m_samples->start(0, i); /* play the sample at position of word */ m_samples->set_frequency(0, 11025); /* play at correct rate */ logerror("Playing sample %d",i); m_totalword[0] = 0; /* Clear the total word stack */ return data; } } #else m_votrax->inflection_w(space, 0, data >> 6); m_votrax->write(space, 0, data); #endif /* Note : We should really also use volume in this as well as frequency */ return data; /* Return nicely */ } CUSTOM_INPUT_MEMBER( astrocde_state::gorf_speech_status_r ) { #if USE_FAKE_VOTRAX return !m_samples->playing(0); #else return m_votrax->request(); #endif }
h0tw1r3/mame
src/mame/audio/gorf.cpp
C++
gpl-2.0
6,511
/* * RFC 1321 compliant MD5 implementation, * by Christophe Devine <devine@cr0.net>; * this program is licensed under the GPL. */ /* Modified October 3, 2003, to remove testing code, and add include of "types.h". -Xodnizel */ #include <string.h> #include "inttypes.h" #include "md5.h" #define GET_UINT32(n,b,i) \ { \ (n) = ( (uint32_t) (b)[(i) + 3] << 24 ) \ | ( (uint32_t) (b)[(i) + 2] << 16 ) \ | ( (uint32_t) (b)[(i) + 1] << 8 ) \ | ( (uint32_t) (b)[(i) ] ); \ } #define PUT_UINT32(n,b,i) \ { \ (b)[(i) ] = (uint8_t) ( (n) ); \ (b)[(i) + 1] = (uint8_t) ( (n) >> 8 ); \ (b)[(i) + 2] = (uint8_t) ( (n) >> 16 ); \ (b)[(i) + 3] = (uint8_t) ( (n) >> 24 ); \ } void sal_md5_starts( struct sal_md5_context *ctx ) { ctx->total[0] = 0; ctx->total[1] = 0; ctx->state[0] = 0x67452301; ctx->state[1] = 0xEFCDAB89; ctx->state[2] = 0x98BADCFE; ctx->state[3] = 0x10325476; } void sal_md5_process( struct sal_md5_context *ctx, uint8_t data[64] ) { uint32_t A, B, C, D, X[16]; GET_UINT32( X[0], data, 0 ); GET_UINT32( X[1], data, 4 ); GET_UINT32( X[2], data, 8 ); GET_UINT32( X[3], data, 12 ); GET_UINT32( X[4], data, 16 ); GET_UINT32( X[5], data, 20 ); GET_UINT32( X[6], data, 24 ); GET_UINT32( X[7], data, 28 ); GET_UINT32( X[8], data, 32 ); GET_UINT32( X[9], data, 36 ); GET_UINT32( X[10], data, 40 ); GET_UINT32( X[11], data, 44 ); GET_UINT32( X[12], data, 48 ); GET_UINT32( X[13], data, 52 ); GET_UINT32( X[14], data, 56 ); GET_UINT32( X[15], data, 60 ); #define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) #define P(a,b,c,d,k,s,t) \ { \ a += F(b,c,d) + X[k] + t; a = S(a,s) + b; \ } A = ctx->state[0]; B = ctx->state[1]; C = ctx->state[2]; D = ctx->state[3]; #define F(x,y,z) (z ^ (x & (y ^ z))) P( A, B, C, D, 0, 7, 0xD76AA478 ); P( D, A, B, C, 1, 12, 0xE8C7B756 ); P( C, D, A, B, 2, 17, 0x242070DB ); P( B, C, D, A, 3, 22, 0xC1BDCEEE ); P( A, B, C, D, 4, 7, 0xF57C0FAF ); P( D, A, B, C, 5, 12, 0x4787C62A ); P( C, D, A, B, 6, 17, 0xA8304613 ); P( B, C, D, A, 7, 22, 0xFD469501 ); P( A, B, C, D, 8, 7, 0x698098D8 ); P( D, A, B, C, 9, 12, 0x8B44F7AF ); P( C, D, A, B, 10, 17, 0xFFFF5BB1 ); P( B, C, D, A, 11, 22, 0x895CD7BE ); P( A, B, C, D, 12, 7, 0x6B901122 ); P( D, A, B, C, 13, 12, 0xFD987193 ); P( C, D, A, B, 14, 17, 0xA679438E ); P( B, C, D, A, 15, 22, 0x49B40821 ); #undef F #define F(x,y,z) (y ^ (z & (x ^ y))) P( A, B, C, D, 1, 5, 0xF61E2562 ); P( D, A, B, C, 6, 9, 0xC040B340 ); P( C, D, A, B, 11, 14, 0x265E5A51 ); P( B, C, D, A, 0, 20, 0xE9B6C7AA ); P( A, B, C, D, 5, 5, 0xD62F105D ); P( D, A, B, C, 10, 9, 0x02441453 ); P( C, D, A, B, 15, 14, 0xD8A1E681 ); P( B, C, D, A, 4, 20, 0xE7D3FBC8 ); P( A, B, C, D, 9, 5, 0x21E1CDE6 ); P( D, A, B, C, 14, 9, 0xC33707D6 ); P( C, D, A, B, 3, 14, 0xF4D50D87 ); P( B, C, D, A, 8, 20, 0x455A14ED ); P( A, B, C, D, 13, 5, 0xA9E3E905 ); P( D, A, B, C, 2, 9, 0xFCEFA3F8 ); P( C, D, A, B, 7, 14, 0x676F02D9 ); P( B, C, D, A, 12, 20, 0x8D2A4C8A ); #undef F #define F(x,y,z) (x ^ y ^ z) P( A, B, C, D, 5, 4, 0xFFFA3942 ); P( D, A, B, C, 8, 11, 0x8771F681 ); P( C, D, A, B, 11, 16, 0x6D9D6122 ); P( B, C, D, A, 14, 23, 0xFDE5380C ); P( A, B, C, D, 1, 4, 0xA4BEEA44 ); P( D, A, B, C, 4, 11, 0x4BDECFA9 ); P( C, D, A, B, 7, 16, 0xF6BB4B60 ); P( B, C, D, A, 10, 23, 0xBEBFBC70 ); P( A, B, C, D, 13, 4, 0x289B7EC6 ); P( D, A, B, C, 0, 11, 0xEAA127FA ); P( C, D, A, B, 3, 16, 0xD4EF3085 ); P( B, C, D, A, 6, 23, 0x04881D05 ); P( A, B, C, D, 9, 4, 0xD9D4D039 ); P( D, A, B, C, 12, 11, 0xE6DB99E5 ); P( C, D, A, B, 15, 16, 0x1FA27CF8 ); P( B, C, D, A, 2, 23, 0xC4AC5665 ); #undef F #define F(x,y,z) (y ^ (x | ~z)) P( A, B, C, D, 0, 6, 0xF4292244 ); P( D, A, B, C, 7, 10, 0x432AFF97 ); P( C, D, A, B, 14, 15, 0xAB9423A7 ); P( B, C, D, A, 5, 21, 0xFC93A039 ); P( A, B, C, D, 12, 6, 0x655B59C3 ); P( D, A, B, C, 3, 10, 0x8F0CCC92 ); P( C, D, A, B, 10, 15, 0xFFEFF47D ); P( B, C, D, A, 1, 21, 0x85845DD1 ); P( A, B, C, D, 8, 6, 0x6FA87E4F ); P( D, A, B, C, 15, 10, 0xFE2CE6E0 ); P( C, D, A, B, 6, 15, 0xA3014314 ); P( B, C, D, A, 13, 21, 0x4E0811A1 ); P( A, B, C, D, 4, 6, 0xF7537E82 ); P( D, A, B, C, 11, 10, 0xBD3AF235 ); P( C, D, A, B, 2, 15, 0x2AD7D2BB ); P( B, C, D, A, 9, 21, 0xEB86D391 ); #undef F ctx->state[0] += A; ctx->state[1] += B; ctx->state[2] += C; ctx->state[3] += D; } void sal_md5_update( struct sal_md5_context *ctx, uint8_t *input, uint32_t length ) { uint32_t left, fill; if( ! length ) return; left = ( ctx->total[0] >> 3 ) & 0x3F; fill = 64 - left; ctx->total[0] += length << 3; ctx->total[1] += length >> 29; ctx->total[0] &= 0xFFFFFFFF; ctx->total[1] += ctx->total[0] < ( length << 3 ); if( left && length >= fill ) { memcpy( (void *) (ctx->buffer + left), (void *) input, fill ); sal_md5_process( ctx, ctx->buffer ); length -= fill; input += fill; left = 0; } while( length >= 64 ) { sal_md5_process( ctx, input ); length -= 64; input += 64; } if( length ) { memcpy( (void *) (ctx->buffer + left), (void *) input, length ); } } static uint8_t md5_padding[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; void sal_md5_finish( struct sal_md5_context *ctx, uint8_t digest[16] ) { uint32_t last, padn; uint8_t msglen[8]; PUT_UINT32( ctx->total[0], msglen, 0 ); PUT_UINT32( ctx->total[1], msglen, 4 ); last = ( ctx->total[0] >> 3 ) & 0x3F; padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last ); sal_md5_update( ctx, md5_padding, padn ); sal_md5_update( ctx, msglen, 8 ); PUT_UINT32( ctx->state[0], digest, 0 ); PUT_UINT32( ctx->state[1], digest, 4 ); PUT_UINT32( ctx->state[2], digest, 8 ); PUT_UINT32( ctx->state[3], digest, 12 ); }
puchiedarcy/fceuxd
src/~attic/sexyal/md5.c
C
gpl-2.0
6,702
/* * linux/arch/arm/mach-pxa/leds-trizeps4.c * * Author: Jürgen Schindele * Created: 20 02, 2006 * Copyright: Jürgen Schindele * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/init.h> #include <asm/hardware.h> #include <asm/system.h> #include <asm/types.h> #include <asm/leds.h> #include <asm/arch/pxa-regs.h> #include <asm/arch/pxa2xx-gpio.h> #include <asm/arch/trizeps4.h> #include "leds.h" #define LED_STATE_ENABLED 1 #define LED_STATE_CLAIMED 2 #define SYS_BUSY 0x01 #define HEARTBEAT 0x02 #define BLINK 0x04 static unsigned int led_state; static unsigned int hw_led_state; void trizeps4_leds_event(led_event_t evt) { unsigned long flags; local_irq_save(flags); switch (evt) { case led_start: hw_led_state = 0; pxa_gpio_mode( GPIO_SYS_BUSY_LED | GPIO_OUT); /* LED1 */ pxa_gpio_mode( GPIO_HEARTBEAT_LED | GPIO_OUT); /* LED2 */ led_state = LED_STATE_ENABLED; break; case led_stop: led_state &= ~LED_STATE_ENABLED; break; case led_claim: led_state |= LED_STATE_CLAIMED; hw_led_state = 0; break; case led_release: led_state &= ~LED_STATE_CLAIMED; hw_led_state = 0; break; #ifdef CONFIG_LEDS_TIMER case led_timer: hw_led_state ^= HEARTBEAT; break; #endif #ifdef CONFIG_LEDS_CPU case led_idle_start: hw_led_state &= ~SYS_BUSY; break; case led_idle_end: hw_led_state |= SYS_BUSY; break; #endif case led_halted: break; case led_green_on: hw_led_state |= BLINK; break; case led_green_off: hw_led_state &= ~BLINK; break; case led_amber_on: break; case led_amber_off: break; case led_red_on: break; case led_red_off: break; default: break; } if (led_state & LED_STATE_ENABLED) { switch (hw_led_state) { case 0: GPSR(GPIO_SYS_BUSY_LED) |= GPIO_bit(GPIO_SYS_BUSY_LED); GPSR(GPIO_HEARTBEAT_LED) |= GPIO_bit(GPIO_HEARTBEAT_LED); break; case 1: GPCR(GPIO_SYS_BUSY_LED) |= GPIO_bit(GPIO_SYS_BUSY_LED); GPSR(GPIO_HEARTBEAT_LED) |= GPIO_bit(GPIO_HEARTBEAT_LED); break; case 2: GPSR(GPIO_SYS_BUSY_LED) |= GPIO_bit(GPIO_SYS_BUSY_LED); GPCR(GPIO_HEARTBEAT_LED) |= GPIO_bit(GPIO_HEARTBEAT_LED); break; case 3: GPCR(GPIO_SYS_BUSY_LED) |= GPIO_bit(GPIO_SYS_BUSY_LED); GPCR(GPIO_HEARTBEAT_LED) |= GPIO_bit(GPIO_HEARTBEAT_LED); break; } } else { /* turn all off */ GPSR(GPIO_SYS_BUSY_LED) |= GPIO_bit(GPIO_SYS_BUSY_LED); GPSR(GPIO_HEARTBEAT_LED) |= GPIO_bit(GPIO_HEARTBEAT_LED); } local_irq_restore(flags); }
janrinze/loox7xxport
arch/arm/mach-pxa/leds-trizeps4.c
C
gpl-2.0
2,648
/* Branch trace support for GDB, the GNU debugger. Copyright (C) 2013-2015 Free Software Foundation, Inc. Contributed by Intel Corp. <markus.t.metzger@intel.com>. This file is part of GDB. 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BTRACE_H #define BTRACE_H /* Branch tracing (btrace) is a per-thread control-flow execution trace of the inferior. For presentation purposes, the branch trace is represented as a list of sequential control-flow blocks, one such list per thread. */ #include "btrace-common.h" #include "target/waitstatus.h" /* For enum target_stop_reason. */ #include "common/enum-flags.h" #if defined (HAVE_LIBIPT) # include <intel-pt.h> #endif struct thread_info; struct btrace_function; /* A coarse instruction classification. */ enum btrace_insn_class { /* The instruction is something not listed below. */ BTRACE_INSN_OTHER, /* The instruction is a function call. */ BTRACE_INSN_CALL, /* The instruction is a function return. */ BTRACE_INSN_RETURN, /* The instruction is an unconditional jump. */ BTRACE_INSN_JUMP }; /* Instruction flags. */ enum btrace_insn_flag { /* The instruction has been executed speculatively. */ BTRACE_INSN_FLAG_SPECULATIVE = (1 << 0) }; DEF_ENUM_FLAGS_TYPE (enum btrace_insn_flag, btrace_insn_flags); /* A branch trace instruction. This represents a single instruction in a branch trace. */ struct btrace_insn { /* The address of this instruction. */ CORE_ADDR pc; /* The size of this instruction in bytes. */ gdb_byte size; /* The instruction class of this instruction. */ enum btrace_insn_class iclass; /* A bit vector of BTRACE_INSN_FLAGS. */ btrace_insn_flags flags; }; /* A vector of branch trace instructions. */ typedef struct btrace_insn btrace_insn_s; DEF_VEC_O (btrace_insn_s); /* A doubly-linked list of branch trace function segments. */ struct btrace_func_link { struct btrace_function *prev; struct btrace_function *next; }; /* Flags for btrace function segments. */ enum btrace_function_flag { /* The 'up' link interpretation. If set, it points to the function segment we returned to. If clear, it points to the function segment we called from. */ BFUN_UP_LINKS_TO_RET = (1 << 0), /* The 'up' link points to a tail call. This obviously only makes sense if bfun_up_links_to_ret is clear. */ BFUN_UP_LINKS_TO_TAILCALL = (1 << 1) }; DEF_ENUM_FLAGS_TYPE (enum btrace_function_flag, btrace_function_flags); /* Decode errors for the BTS recording format. */ enum btrace_bts_error { /* The instruction trace overflowed the end of the trace block. */ BDE_BTS_OVERFLOW = 1, /* The instruction size could not be determined. */ BDE_BTS_INSN_SIZE }; /* Decode errors for the Intel(R) Processor Trace recording format. */ enum btrace_pt_error { /* The user cancelled trace processing. */ BDE_PT_USER_QUIT = 1, /* Tracing was temporarily disabled. */ BDE_PT_DISABLED, /* Trace recording overflowed. */ BDE_PT_OVERFLOW /* Negative numbers are used by the decoder library. */ }; /* A branch trace function segment. This represents a function segment in a branch trace, i.e. a consecutive number of instructions belonging to the same function. In case of decode errors, we add an empty function segment to indicate the gap in the trace. We do not allow function segments without instructions otherwise. */ struct btrace_function { /* The full and minimal symbol for the function. Both may be NULL. */ struct minimal_symbol *msym; struct symbol *sym; /* The previous and next segment belonging to the same function. If a function calls another function, the former will have at least two segments: one before the call and another after the return. */ struct btrace_func_link segment; /* The previous and next function in control flow order. */ struct btrace_func_link flow; /* The directly preceding function segment in a (fake) call stack. */ struct btrace_function *up; /* The instructions in this function segment. The instruction vector will be empty if the function segment represents a decode error. */ VEC (btrace_insn_s) *insn; /* The error code of a decode error that led to a gap. Must be zero unless INSN is empty; non-zero otherwise. */ int errcode; /* The instruction number offset for the first instruction in this function segment. If INSN is empty this is the insn_offset of the succeding function segment in control-flow order. */ unsigned int insn_offset; /* The function number in control-flow order. If INSN is empty indicating a gap in the trace due to a decode error, we still count the gap as a function. */ unsigned int number; /* The function level in a back trace across the entire branch trace. A caller's level is one lower than the level of its callee. Levels can be negative if we see returns for which we have not seen the corresponding calls. The branch trace thread information provides a fixup to normalize function levels so the smallest level is zero. */ int level; /* A bit-vector of btrace_function_flag. */ btrace_function_flags flags; }; /* A branch trace instruction iterator. */ struct btrace_insn_iterator { /* The branch trace function segment containing the instruction. Will never be NULL. */ const struct btrace_function *function; /* The index into the function segment's instruction vector. */ unsigned int index; }; /* A branch trace function call iterator. */ struct btrace_call_iterator { /* The branch trace information for this thread. Will never be NULL. */ const struct btrace_thread_info *btinfo; /* The branch trace function segment. This will be NULL for the iterator pointing to the end of the trace. */ const struct btrace_function *function; }; /* Branch trace iteration state for "record instruction-history". */ struct btrace_insn_history { /* The branch trace instruction range from BEGIN (inclusive) to END (exclusive) that has been covered last time. */ struct btrace_insn_iterator begin; struct btrace_insn_iterator end; }; /* Branch trace iteration state for "record function-call-history". */ struct btrace_call_history { /* The branch trace function range from BEGIN (inclusive) to END (exclusive) that has been covered last time. */ struct btrace_call_iterator begin; struct btrace_call_iterator end; }; /* Branch trace thread flags. */ enum btrace_thread_flag { /* The thread is to be stepped forwards. */ BTHR_STEP = (1 << 0), /* The thread is to be stepped backwards. */ BTHR_RSTEP = (1 << 1), /* The thread is to be continued forwards. */ BTHR_CONT = (1 << 2), /* The thread is to be continued backwards. */ BTHR_RCONT = (1 << 3), /* The thread is to be moved. */ BTHR_MOVE = (BTHR_STEP | BTHR_RSTEP | BTHR_CONT | BTHR_RCONT), /* The thread is to be stopped. */ BTHR_STOP = (1 << 4) }; DEF_ENUM_FLAGS_TYPE (enum btrace_thread_flag, btrace_thread_flags); #if defined (HAVE_LIBIPT) /* A packet. */ struct btrace_pt_packet { /* The offset in the trace stream. */ uint64_t offset; /* The decode error code. */ enum pt_error_code errcode; /* The decoded packet. Only valid if ERRCODE == pte_ok. */ struct pt_packet packet; }; /* Define functions operating on a vector of packets. */ typedef struct btrace_pt_packet btrace_pt_packet_s; DEF_VEC_O (btrace_pt_packet_s); #endif /* defined (HAVE_LIBIPT) */ /* Branch trace iteration state for "maintenance btrace packet-history". */ struct btrace_maint_packet_history { /* The branch trace packet range from BEGIN (inclusive) to END (exclusive) that has been covered last time. */ unsigned int begin; unsigned int end; }; /* Branch trace maintenance information per thread. This information is used by "maintenance btrace" commands. */ struct btrace_maint_info { /* Most information is format-specific. The format can be found in the BTRACE.DATA.FORMAT field of each thread. */ union { /* BTRACE.DATA.FORMAT == BTRACE_FORMAT_BTS */ struct { /* The packet history iterator. We are iterating over BTRACE.DATA.FORMAT.VARIANT.BTS.BLOCKS. */ struct btrace_maint_packet_history packet_history; } bts; #if defined (HAVE_LIBIPT) /* BTRACE.DATA.FORMAT == BTRACE_FORMAT_PT */ struct { /* A vector of decoded packets. */ VEC (btrace_pt_packet_s) *packets; /* The packet history iterator. We are iterating over the above PACKETS vector. */ struct btrace_maint_packet_history packet_history; } pt; #endif /* defined (HAVE_LIBIPT) */ } variant; }; /* Branch trace information per thread. This represents the branch trace configuration as well as the entry point into the branch trace data. For the latter, it also contains the index into an array of branch trace blocks used for iterating though the branch trace blocks of a thread. */ struct btrace_thread_info { /* The target branch trace information for this thread. This contains the branch trace configuration as well as any target-specific information necessary for implementing branch tracing on the underlying architecture. */ struct btrace_target_info *target; /* The raw branch trace data for the below branch trace. */ struct btrace_data data; /* The current branch trace for this thread (both inclusive). The last instruction of END is the current instruction, which is not part of the execution history. Both will be NULL if there is no branch trace available. If there is branch trace available, both will be non-NULL. */ struct btrace_function *begin; struct btrace_function *end; /* The function level offset. When added to each function's LEVEL, this normalizes the function levels such that the smallest level becomes zero. */ int level; /* The number of gaps in the trace. */ unsigned int ngaps; /* A bit-vector of btrace_thread_flag. */ btrace_thread_flags flags; /* The instruction history iterator. */ struct btrace_insn_history *insn_history; /* The function call history iterator. */ struct btrace_call_history *call_history; /* The current replay position. NULL if not replaying. Gaps are skipped during replay, so REPLAY always points to a valid instruction. */ struct btrace_insn_iterator *replay; /* Why the thread stopped, if we need to track it. */ enum target_stop_reason stop_reason; /* Maintenance information. */ struct btrace_maint_info maint; }; /* Enable branch tracing for a thread. */ extern void btrace_enable (struct thread_info *tp, const struct btrace_config *conf); /* Get the branch trace configuration for a thread. Return NULL if branch tracing is not enabled for that thread. */ extern const struct btrace_config * btrace_conf (const struct btrace_thread_info *); /* Disable branch tracing for a thread. This will also delete the current branch trace data. */ extern void btrace_disable (struct thread_info *); /* Disable branch tracing for a thread during teardown. This is similar to btrace_disable, except that it will use target_teardown_btrace instead of target_disable_btrace. */ extern void btrace_teardown (struct thread_info *); /* Fetch the branch trace for a single thread. */ extern void btrace_fetch (struct thread_info *); /* Clear the branch trace for a single thread. */ extern void btrace_clear (struct thread_info *); /* Clear the branch trace for all threads when an object file goes away. */ extern void btrace_free_objfile (struct objfile *); /* Parse a branch trace xml document XML into DATA. */ extern void parse_xml_btrace (struct btrace_data *data, const char *xml); /* Parse a branch trace configuration xml document XML into CONF. */ extern void parse_xml_btrace_conf (struct btrace_config *conf, const char *xml); /* Dereference a branch trace instruction iterator. Return a pointer to the instruction the iterator points to. May return NULL if the iterator points to a gap in the trace. */ extern const struct btrace_insn * btrace_insn_get (const struct btrace_insn_iterator *); /* Return the instruction number for a branch trace iterator. Returns one past the maximum instruction number for the end iterator. Returns zero if the iterator does not point to a valid instruction. */ extern unsigned int btrace_insn_number (const struct btrace_insn_iterator *); /* Initialize a branch trace instruction iterator to point to the begin/end of the branch trace. Throws an error if there is no branch trace. */ extern void btrace_insn_begin (struct btrace_insn_iterator *, const struct btrace_thread_info *); extern void btrace_insn_end (struct btrace_insn_iterator *, const struct btrace_thread_info *); /* Increment/decrement a branch trace instruction iterator by at most STRIDE instructions. Return the number of instructions by which the instruction iterator has been advanced. Returns zero, if the operation failed or STRIDE had been zero. */ extern unsigned int btrace_insn_next (struct btrace_insn_iterator *, unsigned int stride); extern unsigned int btrace_insn_prev (struct btrace_insn_iterator *, unsigned int stride); /* Compare two branch trace instruction iterators. Return a negative number if LHS < RHS. Return zero if LHS == RHS. Return a positive number if LHS > RHS. */ extern int btrace_insn_cmp (const struct btrace_insn_iterator *lhs, const struct btrace_insn_iterator *rhs); /* Find an instruction in the function branch trace by its number. If the instruction is found, initialize the branch trace instruction iterator to point to this instruction and return non-zero. Return zero otherwise. */ extern int btrace_find_insn_by_number (struct btrace_insn_iterator *, const struct btrace_thread_info *, unsigned int number); /* Dereference a branch trace call iterator. Return a pointer to the function the iterator points to or NULL if the interator points past the end of the branch trace. */ extern const struct btrace_function * btrace_call_get (const struct btrace_call_iterator *); /* Return the function number for a branch trace call iterator. Returns one past the maximum function number for the end iterator. Returns zero if the iterator does not point to a valid function. */ extern unsigned int btrace_call_number (const struct btrace_call_iterator *); /* Initialize a branch trace call iterator to point to the begin/end of the branch trace. Throws an error if there is no branch trace. */ extern void btrace_call_begin (struct btrace_call_iterator *, const struct btrace_thread_info *); extern void btrace_call_end (struct btrace_call_iterator *, const struct btrace_thread_info *); /* Increment/decrement a branch trace call iterator by at most STRIDE function segments. Return the number of function segments by which the call iterator has been advanced. Returns zero, if the operation failed or STRIDE had been zero. */ extern unsigned int btrace_call_next (struct btrace_call_iterator *, unsigned int stride); extern unsigned int btrace_call_prev (struct btrace_call_iterator *, unsigned int stride); /* Compare two branch trace call iterators. Return a negative number if LHS < RHS. Return zero if LHS == RHS. Return a positive number if LHS > RHS. */ extern int btrace_call_cmp (const struct btrace_call_iterator *lhs, const struct btrace_call_iterator *rhs); /* Find a function in the function branch trace by its NUMBER. If the function is found, initialize the branch trace call iterator to point to this function and return non-zero. Return zero otherwise. */ extern int btrace_find_call_by_number (struct btrace_call_iterator *, const struct btrace_thread_info *, unsigned int number); /* Set the branch trace instruction history from BEGIN (inclusive) to END (exclusive). */ extern void btrace_set_insn_history (struct btrace_thread_info *, const struct btrace_insn_iterator *begin, const struct btrace_insn_iterator *end); /* Set the branch trace function call history from BEGIN (inclusive) to END (exclusive). */ extern void btrace_set_call_history (struct btrace_thread_info *, const struct btrace_call_iterator *begin, const struct btrace_call_iterator *end); /* Determine if branch tracing is currently replaying TP. */ extern int btrace_is_replaying (struct thread_info *tp); /* Return non-zero if the branch trace for TP is empty; zero otherwise. */ extern int btrace_is_empty (struct thread_info *tp); /* Create a cleanup for DATA. */ extern struct cleanup *make_cleanup_btrace_data (struct btrace_data *data); #endif /* BTRACE_H */
DSMan195276/protura-binutils
gdb/btrace.h
C
gpl-2.0
17,609
/* $Id: optimN_mex.c 2644 2009-01-23 13:01:50Z john $ */ /* (c) John Ashburner (2007) */ #include "mex.h" #include <math.h> #include "optimN.h" static void fmg_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int nd, i; int dm[4]; int cyc=1, nit=1, rtype=0; float *A, *b, *x, *scratch; static double param[6] = {1.0, 1.0, 1.0, 1.0, 0.0, 0.0}; double scal[256]; if ((nrhs!=3 && nrhs!=4) || nlhs>1) mexErrMsgTxt("Incorrect usage"); if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) mexErrMsgTxt("Data must be numeric, real, full and single"); if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsSingle(prhs[1])) mexErrMsgTxt("Data must be numeric, real, full and single"); nd = mxGetNumberOfDimensions(prhs[1]); if (nd>4) mexErrMsgTxt("Wrong number of dimensions."); for(i=0; i<nd; i++) dm[i] = mxGetDimensions(prhs[1])[i]; for(i=nd; i<4; i++) dm[i] = 1; nd = mxGetNumberOfDimensions(prhs[0]); if (nd>4) mexErrMsgTxt("Wrong number of dimensions."); if ((nd==4) && (mxGetDimensions(prhs[0])[3] != (dm[3]*(dm[3]+1))/2)) mexErrMsgTxt("Incompatible 4th dimension (must be (n*(n+1))/2)."); if (nd>3) nd=3; for(i=0; i<nd; i++) if (mxGetDimensions(prhs[0])[i] != dm[i]) mexErrMsgTxt("Incompatible dimensions."); for(i=nd; i<3; i++) if (dm[i] != 1) mexErrMsgTxt("Incompatible dimensions."); if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxIsSparse(prhs[2]) || !mxIsDouble(prhs[2])) mexErrMsgTxt("Data must be numeric, real, full and double"); if (mxGetNumberOfElements(prhs[2]) != 9) mexErrMsgTxt("Third argument should contain rtype, vox1, vox2, vox3, param1, param2, param3, ncycles and relax-its."); rtype = (int)(mxGetPr(prhs[2])[0]); param[0] = 1/mxGetPr(prhs[2])[1]; param[1] = 1/mxGetPr(prhs[2])[2]; param[2] = 1/mxGetPr(prhs[2])[3]; param[3] = mxGetPr(prhs[2])[4]; param[4] = mxGetPr(prhs[2])[5]; param[5] = mxGetPr(prhs[2])[6]; cyc = mxGetPr(prhs[2])[7]; nit = (int)(mxGetPr(prhs[2])[8]); if (nrhs==4) { double *s; if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) || mxIsSparse(prhs[3]) || !mxIsDouble(prhs[3])) mexErrMsgTxt("Data must be numeric, real, full and double"); if (mxGetNumberOfElements(prhs[3]) != dm[3]) mexErrMsgTxt("Incompatible number of scales."); s = (double *)mxGetPr(prhs[3]); for(i=0; i< dm[3]; i++) scal[i] = s[i]; } else { for(i=0; i<dm[3]; i++) scal[i] = 1.0; } plhs[0] = mxCreateNumericArray(4,(unsigned int *)dm, mxSINGLE_CLASS, mxREAL); A = (float *)mxGetPr(prhs[0]); b = (float *)mxGetPr(prhs[1]); x = (float *)mxGetPr(plhs[0]); scratch = (float *)mxCalloc(fmg_scratchsize((int *)dm),sizeof(float)); fmg((int *)dm, A, b, rtype, param, scal, cyc, nit, x, scratch); mxFree((void *)scratch); } static void vel2mom_mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int nd, i; int dm[4]; int rtype = 0; static double param[] = {1.0, 1.0, 1.0, 1.0, 0.0, 0.0}; double scal[256]; if ((nrhs!=2 && nrhs!=3) || nlhs>1) mexErrMsgTxt("Incorrect usage"); if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsSingle(prhs[0])) mexErrMsgTxt("Data must be numeric, real, full and single"); nd = mxGetNumberOfDimensions(prhs[0]); if (nd>4) mexErrMsgTxt("Wrong number of dimensions."); for(i=0; i<nd; i++) dm[i] = mxGetDimensions(prhs[0])[i]; for(i=nd; i<4; i++) dm[i] = 1; if (mxGetNumberOfElements(prhs[1]) != 7) mexErrMsgTxt("Parameters should contain rtype, vox1, vox2, vox3, param1, param2 and param3."); rtype = (int)(mxGetPr(prhs[1])[0]); param[0] = 1/mxGetPr(prhs[1])[1]; param[1] = 1/mxGetPr(prhs[1])[2]; param[2] = 1/mxGetPr(prhs[1])[3]; param[3] = mxGetPr(prhs[1])[4]; param[4] = mxGetPr(prhs[1])[5]; param[5] = mxGetPr(prhs[1])[6]; if (nrhs==3) { double *s; if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) || mxIsSparse(prhs[2]) || !mxIsDouble(prhs[2])) mexErrMsgTxt("Data must be numeric, real, full and double"); if (mxGetNumberOfElements(prhs[2]) != dm[3]) mexErrMsgTxt("Incompatible number of scales."); s = (double *)mxGetPr(prhs[2]); for(i=0; i< dm[3]; i++) scal[i] = s[i]; } else { for(i=0; i<dm[3]; i++) scal[i] = 1.0; } plhs[0] = mxCreateNumericArray(nd, (unsigned int *)dm, mxSINGLE_CLASS, mxREAL); if (rtype==1) LtLf_me((int *)dm, (float *)mxGetPr(prhs[0]), param, scal, (float *)mxGetPr(plhs[0])); else if (rtype==2) LtLf_be((int *)dm, (float *)mxGetPr(prhs[0]), param, scal, (float *)mxGetPr(plhs[0])); else mexErrMsgTxt("Regularisation type not recognised."); } #include<string.h> void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if ((nrhs>=1) && mxIsChar(prhs[0])) { int buflen; char *fnc_str; buflen = mxGetNumberOfElements(prhs[0]); fnc_str = (char *)mxCalloc(buflen+1,sizeof(mxChar)); mxGetString(prhs[0],fnc_str,buflen+1); if (!strcmp(fnc_str,"vel2mom")) { mxFree(fnc_str); vel2mom_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); } else if (!strcmp(fnc_str,"fmg") || !strcmp(fnc_str,"FMG")) { mxFree(fnc_str); fmg_mexFunction(nlhs, plhs, nrhs-1, &prhs[1]); } else { mxFree(fnc_str); mexErrMsgTxt("Option not recognised."); } } else { fmg_mexFunction(nlhs, plhs, nrhs, prhs); } }
neurodebian/spm8
toolbox/DARTEL/optimN_mex.c
C
gpl-2.0
5,959
# -*- coding: iso-8859-1 -*- """ crypto.cipher.rijndael Rijndael encryption algorithm This byte oriented implementation is intended to closely match FIPS specification for readability. It is not implemented for performance. Copyright © (c) 2002 by Paul A. Lambert Read LICENSE.txt for license information. 2002-06-01 """ from crypto.cipher.base import BlockCipher, padWithPadLen, noPadding class Rijndael(BlockCipher): """ Rijndael encryption algorithm """ def __init__(self, key = None, padding = padWithPadLen(), keySize=16, blockSize=16 ): self.name = 'RIJNDAEL' self.keySize = keySize self.strength = keySize*8 self.blockSize = blockSize # blockSize is in bytes self.padding = padding # change default to noPadding() to get normal ECB behavior assert( keySize%4==0 and NrTable[4].has_key(keySize/4)),'key size must be 16,20,24,29 or 32 bytes' assert( blockSize%4==0 and NrTable.has_key(blockSize/4)), 'block size must be 16,20,24,29 or 32 bytes' self.Nb = self.blockSize/4 # Nb is number of columns of 32 bit words self.Nk = keySize/4 # Nk is the key length in 32-bit words self.Nr = NrTable[self.Nb][self.Nk] # The number of rounds (Nr) is a function of # the block (Nb) and key (Nk) sizes. if key != None: self.setKey(key) def setKey(self, key): """ Set a key and generate the expanded key """ assert( len(key) == (self.Nk*4) ), 'Key length must be same as keySize parameter' self.__expandedKey = keyExpansion(self, key) self.reset() # BlockCipher.reset() def encryptBlock(self, plainTextBlock): """ Encrypt a block, plainTextBlock must be a array of bytes [Nb by 4] """ self.state = self._toBlock(plainTextBlock) AddRoundKey(self, self.__expandedKey[0:self.Nb]) for round in range(1,self.Nr): #for round = 1 step 1 to Nr–1 SubBytes(self) ShiftRows(self) MixColumns(self) AddRoundKey(self, self.__expandedKey[round*self.Nb:(round+1)*self.Nb]) SubBytes(self) ShiftRows(self) AddRoundKey(self, self.__expandedKey[self.Nr*self.Nb:(self.Nr+1)*self.Nb]) return self._toBString(self.state) def decryptBlock(self, encryptedBlock): """ decrypt a block (array of bytes) """ self.state = self._toBlock(encryptedBlock) AddRoundKey(self, self.__expandedKey[self.Nr*self.Nb:(self.Nr+1)*self.Nb]) for round in range(self.Nr-1,0,-1): InvShiftRows(self) InvSubBytes(self) AddRoundKey(self, self.__expandedKey[round*self.Nb:(round+1)*self.Nb]) InvMixColumns(self) InvShiftRows(self) InvSubBytes(self) AddRoundKey(self, self.__expandedKey[0:self.Nb]) return self._toBString(self.state) def _toBlock(self, bs): """ Convert binary string to array of bytes, state[col][row]""" assert ( len(bs) == 4*self.Nb ), 'Rijndarl blocks must be of size blockSize' return [[ord(bs[4*i]),ord(bs[4*i+1]),ord(bs[4*i+2]),ord(bs[4*i+3])] for i in range(self.Nb)] def _toBString(self, block): """ Convert block (array of bytes) to binary string """ l = [] for col in block: for rowElement in col: l.append(chr(rowElement)) return ''.join(l) #------------------------------------- """ Number of rounds Nr = NrTable[Nb][Nk] Nb Nk=4 Nk=5 Nk=6 Nk=7 Nk=8 ------------------------------------- """ NrTable = {4: {4:10, 5:11, 6:12, 7:13, 8:14}, 5: {4:11, 5:11, 6:12, 7:13, 8:14}, 6: {4:12, 5:12, 6:12, 7:13, 8:14}, 7: {4:13, 5:13, 6:13, 7:13, 8:14}, 8: {4:14, 5:14, 6:14, 7:14, 8:14}} #------------------------------------- def keyExpansion(algInstance, keyString): """ Expand a string of size keySize into a larger array """ Nk, Nb, Nr = algInstance.Nk, algInstance.Nb, algInstance.Nr # for readability key = [ord(byte) for byte in keyString] # convert string to list w = [[key[4*i],key[4*i+1],key[4*i+2],key[4*i+3]] for i in range(Nk)] for i in range(Nk,Nb*(Nr+1)): temp = w[i-1] # a four byte column if (i%Nk) == 0 : temp = temp[1:]+[temp[0]] # RotWord(temp) temp = [ Sbox[byte] for byte in temp ] temp[0] ^= Rcon[i/Nk] elif Nk > 6 and i%Nk == 4 : temp = [ Sbox[byte] for byte in temp ] # SubWord(temp) w.append( [ w[i-Nk][byte]^temp[byte] for byte in range(4) ] ) return w Rcon = (0,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36, # note extra '0' !!! 0x6c,0xd8,0xab,0x4d,0x9a,0x2f,0x5e,0xbc,0x63,0xc6, 0x97,0x35,0x6a,0xd4,0xb3,0x7d,0xfa,0xef,0xc5,0x91) #------------------------------------- def AddRoundKey(algInstance, keyBlock): """ XOR the algorithm state with a block of key material """ for column in range(algInstance.Nb): for row in range(4): algInstance.state[column][row] ^= keyBlock[column][row] #------------------------------------- def SubBytes(algInstance): for column in range(algInstance.Nb): for row in range(4): algInstance.state[column][row] = Sbox[algInstance.state[column][row]] def InvSubBytes(algInstance): for column in range(algInstance.Nb): for row in range(4): algInstance.state[column][row] = InvSbox[algInstance.state[column][row]] Sbox = (0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5, 0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76, 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0, 0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0, 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc, 0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15, 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a, 0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75, 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0, 0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84, 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b, 0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf, 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85, 0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8, 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5, 0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2, 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17, 0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73, 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88, 0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb, 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c, 0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79, 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9, 0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08, 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6, 0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a, 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e, 0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e, 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94, 0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf, 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68, 0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16) InvSbox = (0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38, 0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb, 0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87, 0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb, 0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d, 0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e, 0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2, 0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25, 0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16, 0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92, 0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda, 0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84, 0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a, 0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06, 0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02, 0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b, 0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea, 0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73, 0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85, 0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e, 0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89, 0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b, 0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20, 0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4, 0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31, 0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f, 0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d, 0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef, 0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0, 0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61, 0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26, 0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d) #------------------------------------- """ For each block size (Nb), the ShiftRow operation shifts row i by the amount Ci. Note that row 0 is not shifted. Nb C1 C2 C3 ------------------- """ shiftOffset = { 4 : ( 0, 1, 2, 3), 5 : ( 0, 1, 2, 3), 6 : ( 0, 1, 2, 3), 7 : ( 0, 1, 2, 4), 8 : ( 0, 1, 3, 4) } def ShiftRows(algInstance): tmp = [0]*algInstance.Nb # list of size Nb for r in range(1,4): # row 0 reamains unchanged and can be skipped for c in range(algInstance.Nb): tmp[c] = algInstance.state[(c+shiftOffset[algInstance.Nb][r]) % algInstance.Nb][r] for c in range(algInstance.Nb): algInstance.state[c][r] = tmp[c] def InvShiftRows(algInstance): tmp = [0]*algInstance.Nb # list of size Nb for r in range(1,4): # row 0 reamains unchanged and can be skipped for c in range(algInstance.Nb): tmp[c] = algInstance.state[(c+algInstance.Nb-shiftOffset[algInstance.Nb][r]) % algInstance.Nb][r] for c in range(algInstance.Nb): algInstance.state[c][r] = tmp[c] #------------------------------------- def MixColumns(a): Sprime = [0,0,0,0] for j in range(a.Nb): # for each column Sprime[0] = mul(2,a.state[j][0])^mul(3,a.state[j][1])^mul(1,a.state[j][2])^mul(1,a.state[j][3]) Sprime[1] = mul(1,a.state[j][0])^mul(2,a.state[j][1])^mul(3,a.state[j][2])^mul(1,a.state[j][3]) Sprime[2] = mul(1,a.state[j][0])^mul(1,a.state[j][1])^mul(2,a.state[j][2])^mul(3,a.state[j][3]) Sprime[3] = mul(3,a.state[j][0])^mul(1,a.state[j][1])^mul(1,a.state[j][2])^mul(2,a.state[j][3]) for i in range(4): a.state[j][i] = Sprime[i] def InvMixColumns(a): """ Mix the four bytes of every column in a linear way This is the opposite operation of Mixcolumn """ Sprime = [0,0,0,0] for j in range(a.Nb): # for each column Sprime[0] = mul(0x0E,a.state[j][0])^mul(0x0B,a.state[j][1])^mul(0x0D,a.state[j][2])^mul(0x09,a.state[j][3]) Sprime[1] = mul(0x09,a.state[j][0])^mul(0x0E,a.state[j][1])^mul(0x0B,a.state[j][2])^mul(0x0D,a.state[j][3]) Sprime[2] = mul(0x0D,a.state[j][0])^mul(0x09,a.state[j][1])^mul(0x0E,a.state[j][2])^mul(0x0B,a.state[j][3]) Sprime[3] = mul(0x0B,a.state[j][0])^mul(0x0D,a.state[j][1])^mul(0x09,a.state[j][2])^mul(0x0E,a.state[j][3]) for i in range(4): a.state[j][i] = Sprime[i] #------------------------------------- def mul(a, b): """ Multiply two elements of GF(2^m) needed for MixColumn and InvMixColumn """ if (a !=0 and b!=0): return Alogtable[(Logtable[a] + Logtable[b])%255] else: return 0 Logtable = ( 0, 0, 25, 1, 50, 2, 26, 198, 75, 199, 27, 104, 51, 238, 223, 3, 100, 4, 224, 14, 52, 141, 129, 239, 76, 113, 8, 200, 248, 105, 28, 193, 125, 194, 29, 181, 249, 185, 39, 106, 77, 228, 166, 114, 154, 201, 9, 120, 101, 47, 138, 5, 33, 15, 225, 36, 18, 240, 130, 69, 53, 147, 218, 142, 150, 143, 219, 189, 54, 208, 206, 148, 19, 92, 210, 241, 64, 70, 131, 56, 102, 221, 253, 48, 191, 6, 139, 98, 179, 37, 226, 152, 34, 136, 145, 16, 126, 110, 72, 195, 163, 182, 30, 66, 58, 107, 40, 84, 250, 133, 61, 186, 43, 121, 10, 21, 155, 159, 94, 202, 78, 212, 172, 229, 243, 115, 167, 87, 175, 88, 168, 80, 244, 234, 214, 116, 79, 174, 233, 213, 231, 230, 173, 232, 44, 215, 117, 122, 235, 22, 11, 245, 89, 203, 95, 176, 156, 169, 81, 160, 127, 12, 246, 111, 23, 196, 73, 236, 216, 67, 31, 45, 164, 118, 123, 183, 204, 187, 62, 90, 251, 96, 177, 134, 59, 82, 161, 108, 170, 85, 41, 157, 151, 178, 135, 144, 97, 190, 220, 252, 188, 149, 207, 205, 55, 63, 91, 209, 83, 57, 132, 60, 65, 162, 109, 71, 20, 42, 158, 93, 86, 242, 211, 171, 68, 17, 146, 217, 35, 32, 46, 137, 180, 124, 184, 38, 119, 153, 227, 165, 103, 74, 237, 222, 197, 49, 254, 24, 13, 99, 140, 128, 192, 247, 112, 7) Alogtable= ( 1, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53, 95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170, 229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49, 83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205, 76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136, 131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154, 181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163, 254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160, 251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65, 195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117, 159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128, 155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84, 252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202, 69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14, 18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23, 57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1)
felipenaselva/felipe.repository
script.module.cryptopy/lib/crypto/cipher/rijndael.py
Python
gpl-2.0
14,723
#ifndef _SLHC_H #define _SLHC_H /* * Definitions for tcp compression routines. * * $Header: /usr/local/cvsroot/ctd/FA5A320LINUX26_Kernel/include/net/slhc_vj.h,v 1.3 2006/04/18 08:05:17 ijsung Exp $ * * Copyright (c) 1989 Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Berkeley. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Van Jacobson (van@helios.ee.lbl.gov), Dec 31, 1989: * - Initial distribution. * * * modified for KA9Q Internet Software Package by * Katie Stevens (dkstevens@ucdavis.edu) * University of California, Davis * Computing Services * - 01-31-90 initial adaptation * * - Feb 1991 Bill_Simpson@um.cc.umich.edu * variable number of conversation slots * allow zero or one slots * separate routines * status display */ /* * Compressed packet format: * * The first octet contains the packet type (top 3 bits), TCP * 'push' bit, and flags that indicate which of the 4 TCP sequence * numbers have changed (bottom 5 bits). The next octet is a * conversation number that associates a saved IP/TCP header with * the compressed packet. The next two octets are the TCP checksum * from the original datagram. The next 0 to 15 octets are * sequence number changes, one change per bit set in the header * (there may be no changes and there are two special cases where * the receiver implicitly knows what changed -- see below). * * There are 5 numbers which can change (they are always inserted * in the following order): TCP urgent pointer, window, * acknowledgment, sequence number and IP ID. (The urgent pointer * is different from the others in that its value is sent, not the * change in value.) Since typical use of SLIP links is biased * toward small packets (see comments on MTU/MSS below), changes * use a variable length coding with one octet for numbers in the * range 1 - 255 and 3 octets (0, MSB, LSB) for numbers in the * range 256 - 65535 or 0. (If the change in sequence number or * ack is more than 65535, an uncompressed packet is sent.) */ /* * Packet types (must not conflict with IP protocol version) * * The top nibble of the first octet is the packet type. There are * three possible types: IP (not proto TCP or tcp with one of the * control flags set); uncompressed TCP (a normal IP/TCP packet but * with the 8-bit protocol field replaced by an 8-bit connection id -- * this type of packet syncs the sender & receiver); and compressed * TCP (described above). * * LSB of 4-bit field is TCP "PUSH" bit (a worthless anachronism) and * is logically part of the 4-bit "changes" field that follows. Top * three bits are actual packet type. For backward compatibility * and in the interest of conserving bits, numbers are chosen so the * IP protocol version number (4) which normally appears in this nibble * means "IP packet". */ #include <linux/ip.h> #include <linux/tcp.h> /* SLIP compression masks for len/vers byte */ #define SL_TYPE_IP 0x40 #define SL_TYPE_UNCOMPRESSED_TCP 0x70 #define SL_TYPE_COMPRESSED_TCP 0x80 #define SL_TYPE_ERROR 0x00 /* Bits in first octet of compressed packet */ #define NEW_C 0x40 /* flag bits for what changed in a packet */ #define NEW_I 0x20 #define NEW_S 0x08 #define NEW_A 0x04 #define NEW_W 0x02 #define NEW_U 0x01 /* reserved, special-case values of above */ #define SPECIAL_I (NEW_S|NEW_W|NEW_U) /* echoed interactive traffic */ #define SPECIAL_D (NEW_S|NEW_A|NEW_W|NEW_U) /* unidirectional data */ #define SPECIALS_MASK (NEW_S|NEW_A|NEW_W|NEW_U) #define TCP_PUSH_BIT 0x10 /* * data type and sizes conversion assumptions: * * VJ code KA9Q style generic * u_char byte_t unsigned char 8 bits * u_short int16 unsigned short 16 bits * u_int int16 unsigned short 16 bits * u_long unsigned long unsigned long 32 bits * int int32 long 32 bits */ typedef __u8 byte_t; typedef __u32 int32; /* * "state" data for each active tcp conversation on the wire. This is * basically a copy of the entire IP/TCP header from the last packet * we saw from the conversation together with a small identifier * the transmit & receive ends of the line use to locate saved header. */ struct cstate { byte_t cs_this; /* connection id number (xmit) */ struct cstate *next; /* next in ring (xmit) */ struct iphdr cs_ip; /* ip/tcp hdr from most recent packet */ struct tcphdr cs_tcp; unsigned char cs_ipopt[64]; unsigned char cs_tcpopt[64]; int cs_hsize; }; #define NULLSLSTATE (struct cstate *)0 /* * all the state data for one serial line (we need one of these per line). */ struct slcompress { struct cstate *tstate; /* transmit connection states (array)*/ struct cstate *rstate; /* receive connection states (array)*/ byte_t tslot_limit; /* highest transmit slot id (0-l)*/ byte_t rslot_limit; /* highest receive slot id (0-l)*/ byte_t xmit_oldest; /* oldest xmit in ring */ byte_t xmit_current; /* most recent xmit id */ byte_t recv_current; /* most recent rcvd id */ byte_t flags; #define SLF_TOSS 0x01 /* tossing rcvd frames until id received */ int32 sls_o_nontcp; /* outbound non-TCP packets */ int32 sls_o_tcp; /* outbound TCP packets */ int32 sls_o_uncompressed; /* outbound uncompressed packets */ int32 sls_o_compressed; /* outbound compressed packets */ int32 sls_o_searches; /* searches for connection state */ int32 sls_o_misses; /* times couldn't find conn. state */ int32 sls_i_uncompressed; /* inbound uncompressed packets */ int32 sls_i_compressed; /* inbound compressed packets */ int32 sls_i_error; /* inbound error packets */ int32 sls_i_tossed; /* inbound packets tossed because of error */ int32 sls_i_runt; int32 sls_i_badcheck; }; #define NULLSLCOMPR (struct slcompress *)0 /* In slhc.c: */ struct slcompress *slhc_init(int rslots, int tslots); void slhc_free(struct slcompress *comp); int slhc_compress(struct slcompress *comp, unsigned char *icp, int isize, unsigned char *ocp, unsigned char **cpp, int compress_cid); int slhc_uncompress(struct slcompress *comp, unsigned char *icp, int isize); int slhc_remember(struct slcompress *comp, unsigned char *icp, int isize); int slhc_toss(struct slcompress *comp); #endif /* _SLHC_H */
fedya/aircam-openwrt
build_dir/toolchain-arm_v5te_gcc-linaro_uClibc-0.9.32_eabi/linux-2.6.28.fa2/include/net/slhc_vj.h
C
gpl-2.0
6,844
/* Cache handling for passwd lookup. Copyright (C) 1998-2017 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <drepper@cygnus.com>, 1998. 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; version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include <alloca.h> #include <assert.h> #include <errno.h> #include <error.h> #include <libintl.h> #include <pwd.h> #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <sys/mman.h> #include <sys/socket.h> #include <stackinfo.h> #include "nscd.h" #include "dbg_log.h" #ifdef HAVE_SENDFILE # include <kernel-features.h> #endif /* This is the standard reply in case the service is disabled. */ static const pw_response_header disabled = { .version = NSCD_VERSION, .found = -1, .pw_name_len = 0, .pw_passwd_len = 0, .pw_uid = -1, .pw_gid = -1, .pw_gecos_len = 0, .pw_dir_len = 0, .pw_shell_len = 0 }; /* This is the struct describing how to write this record. */ const struct iovec pwd_iov_disabled = { .iov_base = (void *) &disabled, .iov_len = sizeof (disabled) }; /* This is the standard reply in case we haven't found the dataset. */ static const pw_response_header notfound = { .version = NSCD_VERSION, .found = 0, .pw_name_len = 0, .pw_passwd_len = 0, .pw_uid = -1, .pw_gid = -1, .pw_gecos_len = 0, .pw_dir_len = 0, .pw_shell_len = 0 }; static time_t cache_addpw (struct database_dyn *db, int fd, request_header *req, const void *key, struct passwd *pwd, uid_t owner, struct hashentry *const he, struct datahead *dh, int errval) { bool all_written = true; ssize_t total; time_t t = time (NULL); /* We allocate all data in one memory block: the iov vector, the response header and the dataset itself. */ struct dataset { struct datahead head; pw_response_header resp; char strdata[0]; } *dataset; assert (offsetof (struct dataset, resp) == offsetof (struct datahead, data)); time_t timeout = MAX_TIMEOUT_VALUE; if (pwd == NULL) { if (he != NULL && errval == EAGAIN) { /* If we have an old record available but cannot find one now because the service is not available we keep the old record and make sure it does not get removed. */ if (reload_count != UINT_MAX && dh->nreloads == reload_count) /* Do not reset the value if we never not reload the record. */ dh->nreloads = reload_count - 1; /* Reload with the same time-to-live value. */ timeout = dh->timeout = t + db->postimeout; total = 0; } else { /* We have no data. This means we send the standard reply for this case. */ total = sizeof (notfound); if (fd != -1 && TEMP_FAILURE_RETRY (send (fd, &notfound, total, MSG_NOSIGNAL)) != total) all_written = false; /* If we have a transient error or cannot permanently store the result, so be it. */ if (errno == EAGAIN || __builtin_expect (db->negtimeout == 0, 0)) { /* Mark the old entry as obsolete. */ if (dh != NULL) dh->usable = false; } else if ((dataset = mempool_alloc (db, (sizeof (struct dataset) + req->key_len), 1)) != NULL) { timeout = datahead_init_neg (&dataset->head, (sizeof (struct dataset) + req->key_len), total, db->negtimeout); /* This is the reply. */ memcpy (&dataset->resp, &notfound, total); /* Copy the key data. */ char *key_copy = memcpy (dataset->strdata, key, req->key_len); /* If necessary, we also propagate the data to disk. */ if (db->persistent) { // XXX async OK? uintptr_t pval = (uintptr_t) dataset & ~pagesize_m1; msync ((void *) pval, ((uintptr_t) dataset & pagesize_m1) + sizeof (struct dataset) + req->key_len, MS_ASYNC); } (void) cache_add (req->type, key_copy, req->key_len, &dataset->head, true, db, owner, he == NULL); pthread_rwlock_unlock (&db->lock); /* Mark the old entry as obsolete. */ if (dh != NULL) dh->usable = false; } } } else { /* Determine the I/O structure. */ size_t pw_name_len = strlen (pwd->pw_name) + 1; size_t pw_passwd_len = strlen (pwd->pw_passwd) + 1; size_t pw_gecos_len = strlen (pwd->pw_gecos) + 1; size_t pw_dir_len = strlen (pwd->pw_dir) + 1; size_t pw_shell_len = strlen (pwd->pw_shell) + 1; char *cp; const size_t key_len = strlen (key); const size_t buf_len = 3 * sizeof (pwd->pw_uid) + key_len + 1; char *buf = alloca (buf_len); ssize_t n; /* We need this to insert the `byuid' entry. */ int key_offset; n = snprintf (buf, buf_len, "%d%c%n%s", pwd->pw_uid, '\0', &key_offset, (char *) key) + 1; total = (offsetof (struct dataset, strdata) + pw_name_len + pw_passwd_len + pw_gecos_len + pw_dir_len + pw_shell_len); /* If we refill the cache, first assume the reconrd did not change. Allocate memory on the cache since it is likely discarded anyway. If it turns out to be necessary to have a new record we can still allocate real memory. */ bool alloca_used = false; dataset = NULL; if (he == NULL) { /* Prevent an INVALIDATE request from pruning the data between the two calls to cache_add. */ if (db->propagate) pthread_mutex_lock (&db->prune_run_lock); dataset = (struct dataset *) mempool_alloc (db, total + n, 1); } if (dataset == NULL) { if (he == NULL && db->propagate) pthread_mutex_unlock (&db->prune_run_lock); /* We cannot permanently add the result in the moment. But we can provide the result as is. Store the data in some temporary memory. */ dataset = (struct dataset *) alloca (total + n); /* We cannot add this record to the permanent database. */ alloca_used = true; } timeout = datahead_init_pos (&dataset->head, total + n, total - offsetof (struct dataset, resp), he == NULL ? 0 : dh->nreloads + 1, db->postimeout); dataset->resp.version = NSCD_VERSION; dataset->resp.found = 1; dataset->resp.pw_name_len = pw_name_len; dataset->resp.pw_passwd_len = pw_passwd_len; dataset->resp.pw_uid = pwd->pw_uid; dataset->resp.pw_gid = pwd->pw_gid; dataset->resp.pw_gecos_len = pw_gecos_len; dataset->resp.pw_dir_len = pw_dir_len; dataset->resp.pw_shell_len = pw_shell_len; cp = dataset->strdata; /* Copy the strings over into the buffer. */ cp = mempcpy (cp, pwd->pw_name, pw_name_len); cp = mempcpy (cp, pwd->pw_passwd, pw_passwd_len); cp = mempcpy (cp, pwd->pw_gecos, pw_gecos_len); cp = mempcpy (cp, pwd->pw_dir, pw_dir_len); cp = mempcpy (cp, pwd->pw_shell, pw_shell_len); /* Finally the stringified UID value. */ memcpy (cp, buf, n); char *key_copy = cp + key_offset; assert (key_copy == (char *) rawmemchr (cp, '\0') + 1); assert (cp == dataset->strdata + total - offsetof (struct dataset, strdata)); /* Now we can determine whether on refill we have to create a new record or not. */ if (he != NULL) { assert (fd == -1); if (dataset->head.allocsize == dh->allocsize && dataset->head.recsize == dh->recsize && memcmp (&dataset->resp, dh->data, dh->allocsize - offsetof (struct dataset, resp)) == 0) { /* The data has not changed. We will just bump the timeout value. Note that the new record has been allocated on the stack and need not be freed. */ dh->timeout = dataset->head.timeout; ++dh->nreloads; } else { /* We have to create a new record. Just allocate appropriate memory and copy it. */ struct dataset *newp = (struct dataset *) mempool_alloc (db, total + n, 1); if (newp != NULL) { /* Adjust pointer into the memory block. */ cp = (char *) newp + (cp - (char *) dataset); key_copy = (char *) newp + (key_copy - (char *) dataset); dataset = memcpy (newp, dataset, total + n); alloca_used = false; } /* Mark the old record as obsolete. */ dh->usable = false; } } else { /* We write the dataset before inserting it to the database since while inserting this thread might block and so would unnecessarily let the receiver wait. */ assert (fd != -1); #ifdef HAVE_SENDFILE if (__builtin_expect (db->mmap_used, 1) && !alloca_used) { assert (db->wr_fd != -1); assert ((char *) &dataset->resp > (char *) db->data); assert ((char *) dataset - (char *) db->head + total <= (sizeof (struct database_pers_head) + db->head->module * sizeof (ref_t) + db->head->data_size)); ssize_t written = sendfileall (fd, db->wr_fd, (char *) &dataset->resp - (char *) db->head, dataset->head.recsize); if (written != dataset->head.recsize) { # ifndef __ASSUME_SENDFILE if (written == -1 && errno == ENOSYS) goto use_write; # endif all_written = false; } } else # ifndef __ASSUME_SENDFILE use_write: # endif #endif if (writeall (fd, &dataset->resp, dataset->head.recsize) != dataset->head.recsize) all_written = false; } /* Add the record to the database. But only if it has not been stored on the stack. */ if (! alloca_used) { /* If necessary, we also propagate the data to disk. */ if (db->persistent) { // XXX async OK? uintptr_t pval = (uintptr_t) dataset & ~pagesize_m1; msync ((void *) pval, ((uintptr_t) dataset & pagesize_m1) + total + n, MS_ASYNC); } /* NB: in the following code we always must add the entry marked with FIRST first. Otherwise we end up with dangling "pointers" in case a latter hash entry cannot be added. */ bool first = true; /* If the request was by UID, add that entry first. */ if (req->type == GETPWBYUID) { if (cache_add (GETPWBYUID, cp, key_offset, &dataset->head, true, db, owner, he == NULL) < 0) goto out; first = false; } /* If the key is different from the name add a separate entry. */ else if (strcmp (key_copy, dataset->strdata) != 0) { if (cache_add (GETPWBYNAME, key_copy, key_len + 1, &dataset->head, true, db, owner, he == NULL) < 0) goto out; first = false; } /* We have to add the value for both, byname and byuid. */ if ((req->type == GETPWBYNAME || db->propagate) && __builtin_expect (cache_add (GETPWBYNAME, dataset->strdata, pw_name_len, &dataset->head, first, db, owner, he == NULL) == 0, 1)) { if (req->type == GETPWBYNAME && db->propagate) (void) cache_add (GETPWBYUID, cp, key_offset, &dataset->head, false, db, owner, false); } out: pthread_rwlock_unlock (&db->lock); if (he == NULL && db->propagate) pthread_mutex_unlock (&db->prune_run_lock); } } if (__builtin_expect (!all_written, 0) && debug_level > 0) { char buf[256]; dbg_log (_("short write in %s: %s"), __FUNCTION__, strerror_r (errno, buf, sizeof (buf))); } return timeout; } union keytype { void *v; uid_t u; }; static int lookup (int type, union keytype key, struct passwd *resultbufp, char *buffer, size_t buflen, struct passwd **pwd) { if (type == GETPWBYNAME) return __getpwnam_r (key.v, resultbufp, buffer, buflen, pwd); else return __getpwuid_r (key.u, resultbufp, buffer, buflen, pwd); } static time_t addpwbyX (struct database_dyn *db, int fd, request_header *req, union keytype key, const char *keystr, uid_t c_uid, struct hashentry *he, struct datahead *dh) { /* Search for the entry matching the key. Please note that we don't look again in the table whether the dataset is now available. We simply insert it. It does not matter if it is in there twice. The pruning function only will look at the timestamp. */ size_t buflen = 1024; char *buffer = (char *) alloca (buflen); struct passwd resultbuf; struct passwd *pwd; bool use_malloc = false; int errval = 0; if (__glibc_unlikely (debug_level > 0)) { if (he == NULL) dbg_log (_("Haven't found \"%s\" in password cache!"), keystr); else dbg_log (_("Reloading \"%s\" in password cache!"), keystr); } while (lookup (req->type, key, &resultbuf, buffer, buflen, &pwd) != 0 && (errval = errno) == ERANGE) { errno = 0; if (__glibc_unlikely (buflen > 32768)) { char *old_buffer = buffer; buflen *= 2; buffer = (char *) realloc (use_malloc ? buffer : NULL, buflen); if (buffer == NULL) { /* We ran out of memory. We cannot do anything but sending a negative response. In reality this should never happen. */ pwd = NULL; buffer = old_buffer; /* We set the error to indicate this is (possibly) a temporary error and that it does not mean the entry is not available at all. */ errval = EAGAIN; break; } use_malloc = true; } else /* Allocate a new buffer on the stack. If possible combine it with the previously allocated buffer. */ buffer = (char *) extend_alloca (buffer, buflen, 2 * buflen); } /* Add the entry to the cache. */ time_t timeout = cache_addpw (db, fd, req, keystr, pwd, c_uid, he, dh, errval); if (use_malloc) free (buffer); return timeout; } void addpwbyname (struct database_dyn *db, int fd, request_header *req, void *key, uid_t c_uid) { union keytype u = { .v = key }; addpwbyX (db, fd, req, u, key, c_uid, NULL, NULL); } time_t readdpwbyname (struct database_dyn *db, struct hashentry *he, struct datahead *dh) { request_header req = { .type = GETPWBYNAME, .key_len = he->len }; union keytype u = { .v = db->data + he->key }; return addpwbyX (db, -1, &req, u, db->data + he->key, he->owner, he, dh); } void addpwbyuid (struct database_dyn *db, int fd, request_header *req, void *key, uid_t c_uid) { char *ep; uid_t uid = strtoul ((char *) key, &ep, 10); if (*(char *) key == '\0' || *ep != '\0') /* invalid numeric uid */ { if (debug_level > 0) dbg_log (_("Invalid numeric uid \"%s\"!"), (char *) key); errno = EINVAL; return; } union keytype u = { .u = uid }; addpwbyX (db, fd, req, u, key, c_uid, NULL, NULL); } time_t readdpwbyuid (struct database_dyn *db, struct hashentry *he, struct datahead *dh) { char *ep; uid_t uid = strtoul (db->data + he->key, &ep, 10); /* Since the key has been added before it must be OK. */ assert (*(db->data + he->key) != '\0' && *ep == '\0'); request_header req = { .type = GETPWBYUID, .key_len = he->len }; union keytype u = { .u = uid }; return addpwbyX (db, -1, &req, u, db->data + he->key, he->owner, he, dh); }
NicoleRobin/glibc
nscd/pwdcache.c
C
gpl-2.0
15,680
<?php foreach ($rows[0] as $key => $value) { $rows_d[] = array(array('header' => 1, 'data' => $header[$key]), $value); } print theme('table',null,$rows_d); ?>
Br3nda/Archimedes
profiles/archimedes/themes/archimedes/templates/views-view-table--host_glance.tpl.php
PHP
gpl-2.0
169
/****************************************************************************** * * Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * ******************************************************************************/ #ifndef __RTL8188E_CMD_H__ #define __RTL8188E_CMD_H__ #if 0 enum cmd_msg_element_id { NONE_CMDMSG_EID, AP_OFFLOAD_EID = 0, SET_PWRMODE_EID = 1, JOINBSS_RPT_EID = 2, RSVD_PAGE_EID = 3, RSSI_4_EID = 4, RSSI_SETTING_EID = 5, MACID_CONFIG_EID = 6, MACID_PS_MODE_EID = 7, P2P_PS_OFFLOAD_EID = 8, SELECTIVE_SUSPEND_ROF_CMD = 9, P2P_PS_CTW_CMD_EID = 32, MAX_CMDMSG_EID }; #else typedef enum _RTL8188E_H2C_CMD_ID { //Class Common H2C_COM_RSVD_PAGE =0x00, H2C_COM_MEDIA_STATUS_RPT =0x01, H2C_COM_SCAN =0x02, H2C_COM_KEEP_ALIVE =0x03, H2C_COM_DISCNT_DECISION =0x04, #ifndef CONFIG_WOWLAN H2C_COM_WWLAN =0x05, #endif H2C_COM_INIT_OFFLOAD =0x06, H2C_COM_REMOTE_WAKE_CTL =0x07, H2C_COM_AP_OFFLOAD =0x08, H2C_COM_BCN_RSVD_PAGE =0x09, H2C_COM_PROB_RSP_RSVD_PAGE =0x0A, //Class PS H2C_PS_PWR_MODE =0x20, H2C_PS_TUNE_PARA =0x21, H2C_PS_TUNE_PARA_2 =0x22, H2C_PS_LPS_PARA =0x23, H2C_PS_P2P_OFFLOAD =0x24, //Class DM H2C_DM_MACID_CFG =0x40, H2C_DM_TXBF =0x41, //Class BT H2C_BT_COEX_MASK =0x60, H2C_BT_COEX_GPIO_MODE =0x61, H2C_BT_DAC_SWING_VAL =0x62, H2C_BT_PSD_RST =0x63, //Class Remote WakeUp #ifdef CONFIG_WOWLAN H2C_COM_WWLAN =0x80, H2C_COM_REMOTE_WAKE_CTRL =0x81, #endif //Class H2C_RESET_TSF =0xc0, }RTL8188E_H2C_CMD_ID; #endif struct cmd_msg_parm { u8 eid; //element id u8 sz; // sz u8 buf[6]; }; enum{ PWRS }; typedef struct _SETPWRMODE_PARM { u8 Mode;//0:Active,1:LPS,2:WMMPS //u8 RLBM:4;//0:Min,1:Max,2: User define u8 SmartPS_RLBM;//LPS=0:PS_Poll,1:PS_Poll,2:NullData,WMM=0:PS_Poll,1:NullData u8 AwakeInterval; // unit: beacon interval u8 bAllQueueUAPSD; u8 PwrState;//AllON(0x0c),RFON(0x04),RFOFF(0x00) } SETPWRMODE_PARM, *PSETPWRMODE_PARM; struct H2C_SS_RFOFF_PARAM{ u8 ROFOn; // 1: on, 0:off u16 gpio_period; // unit: 1024 us }__attribute__ ((packed)); typedef struct JOINBSSRPT_PARM_88E{ u8 OpMode; // RT_MEDIA_STATUS #ifdef CONFIG_WOWLAN u8 MacID; // MACID #endif //CONFIG_WOWLAN }JOINBSSRPT_PARM_88E, *PJOINBSSRPT_PARM_88E; typedef struct _RSVDPAGE_LOC_88E { u8 LocProbeRsp; u8 LocPsPoll; u8 LocNullData; u8 LocQosNull; u8 LocBTQosNull; } RSVDPAGE_LOC_88E, *PRSVDPAGE_LOC_88E; // host message to firmware cmd void rtl8188e_set_FwPwrMode_cmd(PADAPTER padapter, u8 Mode); void rtl8188e_set_FwJoinBssReport_cmd(PADAPTER padapter, u8 mstatus); u8 rtl8188e_set_rssi_cmd(PADAPTER padapter, u8 *param); u8 rtl8188e_set_raid_cmd(PADAPTER padapter, u32 mask); void rtl8188e_Add_RateATid(PADAPTER padapter, u32 bitmap, u8* arg, u8 rssi_level); //u8 rtl8192c_set_FwSelectSuspend_cmd(PADAPTER padapter, u8 bfwpoll, u16 period); #ifdef CONFIG_P2P void rtl8188e_set_p2p_ps_offload_cmd(PADAPTER padapter, u8 p2p_ps_state); #endif //CONFIG_P2P void CheckFwRsvdPageContent(PADAPTER padapter); void rtl8188e_set_FwMediaStatus_cmd(PADAPTER padapter, u16 mstatus_rpt ); #ifdef CONFIG_TSF_RESET_OFFLOAD //u8 rtl8188e_reset_tsf(_adapter *padapter, u8 reset_port); int reset_tsf(PADAPTER Adapter, u8 reset_port ); #endif // CONFIG_TSF_RESET_OFFLOAD #ifdef CONFIG_WOWLAN typedef struct _SETWOWLAN_PARM{ u8 mode; u8 gpio_index; u8 gpio_duration; u8 second_mode; u8 reserve; }SETWOWLAN_PARM, *PSETWOWLAN_PARM; #define FW_WOWLAN_FUN_EN BIT(0) #define FW_WOWLAN_PATTERN_MATCH BIT(1) #define FW_WOWLAN_MAGIC_PKT BIT(2) #define FW_WOWLAN_UNICAST BIT(3) #define FW_WOWLAN_ALL_PKT_DROP BIT(4) #define FW_WOWLAN_GPIO_ACTIVE BIT(5) #define FW_WOWLAN_REKEY_WAKEUP BIT(6) #define FW_WOWLAN_DEAUTH_WAKEUP BIT(7) #define FW_WOWLAN_GPIO_WAKEUP_EN BIT(0) #define FW_FW_PARSE_MAGIC_PKT BIT(1) #define FW_REMOTE_WAKE_CTRL_EN BIT(0) #define FW_REALWOWLAN_EN BIT(5) void rtl8188es_set_wowlan_cmd(_adapter* padapter, u8 enable); void SetFwRelatedForWoWLAN8188ES(_adapter* padapter, u8 bHostIsGoingtoSleep); #endif//CONFIG_WOWLAN #endif//__RTL8188E_CMD_H__
francescosganga/remixos-kernel
drivers/staging/rtl8812au/include/rtl8188e_cmd.h
C
gpl-2.0
4,786
ALTER TABLE db_version CHANGE COLUMN required_14003_01_mangos_world_safe_locs_facing required_14005_01_mangos_dbscript_priority_miliseconds bit; ALTER TABLE dbscripts_on_creature_death ADD COLUMN priority INT(11) UNSIGNED NOT NULL DEFAULT '0' AFTER delay; ALTER TABLE dbscripts_on_creature_movement ADD COLUMN priority INT(11) UNSIGNED NOT NULL DEFAULT '0' AFTER delay; ALTER TABLE dbscripts_on_event ADD COLUMN priority INT(11) UNSIGNED NOT NULL DEFAULT '0' AFTER delay; ALTER TABLE dbscripts_on_go_template_use ADD COLUMN priority INT(11) UNSIGNED NOT NULL DEFAULT '0' AFTER delay; ALTER TABLE dbscripts_on_go_use ADD COLUMN priority INT(11) UNSIGNED NOT NULL DEFAULT '0' AFTER delay; ALTER TABLE dbscripts_on_gossip ADD COLUMN priority INT(11) UNSIGNED NOT NULL DEFAULT '0' AFTER delay; ALTER TABLE dbscripts_on_quest_end ADD COLUMN priority INT(11) UNSIGNED NOT NULL DEFAULT '0' AFTER delay; ALTER TABLE dbscripts_on_quest_start ADD COLUMN priority INT(11) UNSIGNED NOT NULL DEFAULT '0' AFTER delay; ALTER TABLE dbscripts_on_spell ADD COLUMN priority INT(11) UNSIGNED NOT NULL DEFAULT '0' AFTER delay; ALTER TABLE dbscripts_on_relay ADD COLUMN priority INT(11) UNSIGNED NOT NULL DEFAULT '0' AFTER delay; UPDATE dbscripts_on_creature_death SET delay=delay*1000; UPDATE dbscripts_on_creature_movement SET delay=delay*1000; UPDATE dbscripts_on_event SET delay=delay*1000; UPDATE dbscripts_on_go_template_use SET delay=delay*1000; UPDATE dbscripts_on_go_use SET delay=delay*1000; UPDATE dbscripts_on_gossip SET delay=delay*1000; UPDATE dbscripts_on_quest_end SET delay=delay*1000; UPDATE dbscripts_on_quest_start SET delay=delay*1000; UPDATE dbscripts_on_spell SET delay=delay*1000; UPDATE dbscripts_on_relay SET delay=delay*1000;
spkansas/mangos-wotlk
sql/updates/mangos/14005_01_mangos_dbscript_priority_miliseconds.sql
SQL
gpl-2.0
1,734
<?php class ControllerExtensionOpenbayEbayProfile extends Controller { private $error = array(); public function profileAll() { $data = $this->load->language('extension/openbay/ebay_profile'); $this->load->model('extension/openbay/ebay_profile'); $this->document->setTitle($data['heading_title']); $this->document->addScript('view/javascript/openbay/js/faq.js'); if (isset($this->session->data['error'])) { $data['error_warning'] = $this->session->data['error']; unset($this->session->data['error']); } else { $data['error_warning'] = ''; } if (isset($this->session->data['success'])) { $data['success'] = $this->session->data['success']; unset($this->session->data['success']); } else { $data['success'] = ''; } $data['add'] = $this->url->link('extension/openbay/ebay_profile/add', 'user_token=' . $this->session->data['user_token']); $data['types'] = $this->model_extension_openbay_ebay_profile->getTypes(); $data['profiles'] = $this->model_extension_openbay_ebay_profile->getAll(); $data['user_token'] = $this->session->data['user_token']; $data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token']), 'text' => $this->language->get('text_home'), ); $data['breadcrumbs'][] = array( 'href' => $this->url->link('marketplace/openbay', 'user_token=' . $this->session->data['user_token']), 'text' => $this->language->get('text_openbay'), ); $data['breadcrumbs'][] = array( 'href' => $this->url->link('extension/openbay/ebay', 'user_token=' . $this->session->data['user_token']), 'text' => $this->language->get('text_ebay'), ); $data['breadcrumbs'][] = array( 'href' => $this->url->link('extension/openbay/ebay_profile/profileAll', 'user_token=' . $this->session->data['user_token']), 'text' => $this->language->get('heading_title'), ); $data['header'] = $this->load->controller('common/header'); $data['column_left'] = $this->load->controller('common/column_left'); $data['footer'] = $this->load->controller('common/footer'); $this->response->setOutput($this->load->view('extension/openbay/ebay_profile_list', $data)); } public function add() { $this->load->model('extension/openbay/ebay_profile'); $data = $this->load->language('extension/openbay/ebay_profile'); $data['btn_save'] = $this->url->link('extension/openbay/ebay_profile/add', 'user_token=' . $this->session->data['user_token']); $data['cancel'] = $this->url->link('extension/openbay/ebay_profile/profileAll', 'user_token=' . $this->session->data['user_token']); if (!isset($this->request->post['step1'])) { if ($this->request->post && $this->profileValidate()) { $this->session->data['success'] = $data['text_added']; $this->model_extension_openbay_ebay_profile->add($this->request->post); $this->response->redirect($this->url->link('extension/openbay/ebay_profile/profileAll', 'user_token=' . $this->session->data['user_token'])); } } $this->profileForm($data); } public function delete() { $this->load->model('extension/openbay/ebay_profile'); if (!$this->user->hasPermission('modify', 'extension/openbay/ebay_profile')) { $this->error['warning'] = $this->language->get('error_permission'); } else { if (isset($this->request->get['ebay_profile_id'])) { $this->model_extension_openbay_ebay_profile->delete($this->request->get['ebay_profile_id']); } } $this->response->redirect($this->url->link('extension/openbay/ebay_profile/profileAll', 'user_token=' . $this->session->data['user_token'])); } public function edit() { $this->load->model('extension/openbay/ebay_profile'); $data = $this->load->language('extension/openbay/ebay_profile'); if ($this->request->post && $this->profileValidate()) { $this->session->data['success'] = $data['text_updated']; $this->model_extension_openbay_ebay_profile->edit($this->request->post['ebay_profile_id'], $this->request->post); $this->response->redirect($this->url->link('extension/openbay/ebay_profile/profileAll', 'user_token=' . $this->session->data['user_token'])); } $this->profileForm($data); } public function profileForm($data) { $this->load->model('extension/openbay/ebay'); $this->load->model('extension/openbay/ebay_template'); $data['user_token'] = $this->session->data['user_token']; $data['shipping_international_zones'] = $this->model_extension_openbay_ebay->getShippingLocations(); $data['templates'] = $this->model_extension_openbay_ebay_template->getAll(); $data['types'] = $this->model_extension_openbay_ebay_profile->getTypes(); $setting = array(); $setting['returns'] = $this->openbay->ebay->getSetting('returns'); $setting['dispatch_times'] = $this->openbay->ebay->getSetting('dispatch_time_max'); $setting['countries'] = $this->openbay->ebay->getSetting('countries'); $setting['shipping_types'] = $this->openbay->ebay->getSetting('shipping_types'); $setting['listing_restrictions'] = $this->openbay->ebay->getSetting('listing_restrictions'); if (empty($setting['dispatch_times']) || empty($setting['countries']) || empty($setting['returns'])){ $this->session->data['warning'] = $this->language->get('error_missing_settings'); $this->response->redirect($this->url->link('extension/openbay/ebay/syncronise', 'user_token=' . $this->session->data['user_token'])); } if (is_array($setting['dispatch_times'])) { ksort($setting['dispatch_times']); } if (is_array($setting['countries'])) { ksort($setting['countries']); } $data['setting'] = $setting; if (isset($this->error['warning'])) { $data['error_warning'] = $this->error['warning']; } else { $data['error_warning'] = ''; } $profile_info = array(); if (isset($this->request->get['ebay_profile_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) { $profile_info = $this->model_extension_openbay_ebay_profile->get($this->request->get['ebay_profile_id']); $data['text_manage'] = $this->language->get('text_edit'); $data['action'] = $this->url->link('extension/openbay/ebay_profile/edit', 'user_token=' . $this->session->data['user_token']); } else { $data['action'] = $this->url->link('extension/openbay/ebay_profile/add', 'user_token=' . $this->session->data['user_token']); $data['text_manage'] = $this->language->get('text_add'); } if (isset($this->request->post['type'])) { $type = $this->request->post['type']; } else { $type = $profile_info['type']; } if (!array_key_exists($type, $data['types'])) { $this->session->data['error'] = $data['error_no_template']; $this->response->redirect($this->url->link('extension/openbay/ebay_profile/profilAall', 'user_token=' . $this->session->data['user_token'])); } $this->document->addScript('view/javascript/openbay/js/faq.js'); $data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token']), 'text' => $this->language->get('text_home'), ); $data['breadcrumbs'][] = array( 'href' => $this->url->link('marketplace/openbay', 'user_token=' . $this->session->data['user_token']), 'text' => $this->language->get('text_openbay'), ); $data['breadcrumbs'][] = array( 'href' => $this->url->link('extension/openbay/ebay', 'user_token=' . $this->session->data['user_token']), 'text' => $this->language->get('text_ebay'), ); $data['breadcrumbs'][] = array( 'href' => $this->url->link('extension/openbay/ebay_profile/profileAll', 'user_token=' . $this->session->data['user_token']), 'text' => $this->language->get('heading_title') ); if (isset($this->request->post['default'])) { $data['default'] = $this->request->post['default']; } elseif (!empty($profile_info)) { $data['default'] = $profile_info['default']; } else { $data['default'] = 0; } if (isset($this->request->post['name'])) { $data['name'] = $this->request->post['name']; } elseif (!empty($profile_info)) { $data['name'] = $profile_info['name']; } else { $data['name'] = ''; } if (isset($this->request->post['description'])) { $data['description'] = $this->request->post['description']; } elseif (!empty($profile_info)) { $data['description'] = $profile_info['description']; } else { $data['description'] = ''; } if (isset($this->request->post['type'])) { $data['type'] = $this->request->post['type']; } else { $data['type'] = $profile_info['type']; } if (isset($this->request->get['ebay_profile_id'])) { $data['ebay_profile_id'] = (int)$this->request->get['ebay_profile_id']; } else { $data['ebay_profile_id'] = ''; } if (isset($this->request->post['data'])) { $data['data'] = $this->request->post['data']; } elseif (!empty($profile_info)) { $data['data'] = $profile_info['data']; } else { $data['data'] = ''; } if ($type == 0) { $data['zones'] = $this->model_extension_openbay_ebay->getShippingLocations(); $data['data']['national']['calculated']['types'] = $this->model_extension_openbay_ebay->getShippingService(0, 'calculated'); $data['data']['international']['calculated']['types'] = $this->model_extension_openbay_ebay->getShippingService(1, 'calculated'); $data['data']['national']['flat']['types'] = $this->model_extension_openbay_ebay->getShippingService(0, 'flat'); $data['data']['international']['flat']['types'] = $this->model_extension_openbay_ebay->getShippingService(1, 'flat'); $data['data']['national']['calculated']['count'] = isset($data['data']['national']['calculated']['service_id']) ? max(array_keys($data['data']['national']['calculated']['service_id']))+1 : 0; $data['data']['national']['flat']['count'] = isset($data['data']['national']['flat']['service_id']) ? max(array_keys($data['data']['national']['flat']['service_id']))+1 : 0; $data['data']['international']['calculated']['count'] = isset($data['data']['international']['calculated']['service_id']) ? max(array_keys($data['data']['international']['calculated']['service_id']))+1 : 0; $data['data']['international']['flat']['count'] = isset($data['data']['international']['flat']['service_id']) ? max(array_keys($data['data']['international']['flat']['service_id']))+1 : 0; $payment_types = $this->model_extension_openbay_ebay->getPaymentTypes(); $data['cod_surcharge'] = 0; foreach($payment_types as $payment) { if ($payment['ebay_name'] == 'COD') { $data['cod_surcharge'] = 1; } } if (!isset($data['data']['national']['shipping_type'])) { $data['data']['national']['shipping_type'] = 'flat'; } if (!isset($data['data']['international']['shipping_type'])) { $data['data']['international']['shipping_type'] = 'flat'; } $data['html_national_flat'] = $this->load->view('extension/openbay/ebay_profile_shipping_national_flat', $data); $data['html_international_flat'] = $this->load->view('extension/openbay/ebay_profile_shipping_international_flat', $data); $data['html_national_calculated'] = $this->load->view('extension/openbay/ebay_profile_shipping_national_calculated', $data); $data['html_international_calculated'] = $this->load->view('extension/openbay/ebay_profile_shipping_international_calculated', $data); } $data['cancel'] = $this->url->link('extension/openbay/ebay_profile/profileAll', 'user_token=' . $this->session->data['user_token']); $this->document->setTitle($data['heading_title']); $data['header'] = $this->load->controller('common/header'); $data['column_left'] = $this->load->controller('common/column_left'); $data['footer'] = $this->load->controller('common/footer'); $this->response->setOutput($this->load->view($data['types'][$type]['template'], $data)); } public function profileGet() { $this->load->model('extension/openbay/ebay_profile'); $this->load->model('extension/openbay/ebay'); $this->load->language('extension/openbay/ebay_profile'); $profile_info = $this->model_extension_openbay_ebay_profile->get($this->request->get['ebay_profile_id']); $data = array(); if ($profile_info['type'] == 0) { $data['data'] = $profile_info['data']; $data['data']['national']['calculated']['types'] = $this->model_extension_openbay_ebay->getShippingService(0, 'calculated'); $data['data']['international']['calculated']['types'] = $this->model_extension_openbay_ebay->getShippingService(1, 'calculated'); $data['data']['national']['flat']['types'] = $this->model_extension_openbay_ebay->getShippingService(0, 'flat'); $data['data']['international']['flat']['types'] = $this->model_extension_openbay_ebay->getShippingService(1, 'flat'); $data['data']['national']['calculated']['count'] = isset($data['data']['national']['calculated']['service_id']) ? max(array_keys($data['data']['national']['calculated']['service_id']))+1 : 0; $data['data']['national']['flat']['count'] = isset($data['data']['national']['flat']['service_id']) ? max(array_keys($data['data']['national']['flat']['service_id']))+1 : 0; $data['data']['international']['calculated']['count'] = isset($data['data']['international']['calculated']['service_id']) ? max(array_keys($data['data']['international']['calculated']['service_id']))+1 : 0; $data['data']['international']['flat']['count'] = isset($data['data']['international']['flat']['service_id']) ? max(array_keys($data['data']['international']['flat']['service_id']))+1 : 0; $data['zones'] = $this->model_extension_openbay_ebay->getShippingLocations(); $data['text_shipping_service'] = $this->language->get('text_shipping_service'); $data['text_shipping_first'] = $this->language->get('text_shipping_first'); $data['button_delete'] = $this->language->get('button_delete'); $data['text_shipping_zones'] = $this->language->get('text_shipping_zones'); $data['text_shipping_worldwide'] = $this->language->get('text_shipping_worldwide'); $data['text_shipping_add'] = $this->language->get('text_shipping_add'); $data['text_cod_surcharge'] = $this->language->get('text_cod_surcharge'); $payment_types = $this->model_extension_openbay_ebay->getPaymentTypes(); $data['cod_surcharge'] = 0; if (!empty($payment_types)) { foreach($payment_types as $payment) { if ($payment['ebay_name'] == 'COD') { $data['cod_surcharge'] = 1; } } } $return['national']['type'] = $data['data']['national']['shipping_type']; $return['international']['type'] = $data['data']['international']['shipping_type']; $return['national_flat_count'] = (int)$data['data']['national']['flat']['count']; $return['national_flat'] = $this->load->view('extension/openbay/ebay_profile_shipping_national_flat', $data); $return['international_flat_count'] = (int)$data['data']['international']['flat']['count']; $return['international_flat'] = $this->load->view('extension/openbay/ebay_profile_shipping_international_flat', $data); $return['national_calculated_count'] = (int)$data['data']['national']['calculated']['count']; $return['national_calculated'] = $this->load->view('extension/openbay/ebay_profile_shipping_national_calculated', $data); $return['international_calculated_count'] = (int)$data['data']['international']['flat']['count']; $return['international_calculated'] = $this->load->view('extension/openbay/ebay_profile_shipping_international_calculated', $data); $profile_info['html'] = $return; } $this->response->addHeader('Content-Type: application/json'); $this->response->setOutput(json_encode($profile_info)); } private function profileValidate() { if (!$this->user->hasPermission('modify', 'extension/openbay/ebay_profile')) { $this->error['warning'] = $this->language->get('error_permission'); } if ($this->request->post['name'] == '') { $this->error['name'] = $this->language->get('error_name'); } return !$this->error; } }
openbaypro/OpenBay-Pro
upload/admin/controller/extension/openbay/ebay_profile.php
PHP
gpl-3.0
16,243
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * Distributed under the Boost Software License, Version 1.0. (See # * accompanying file LICENSE_1_0.txt or copy at # * http://www.boost.org/LICENSE_1_0.txt) # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # include <boost/preprocessor/logical.hpp> # include <libs/preprocessor/test/test.h> BEGIN BOOST_PP_NOT(0) == 1 END BEGIN BOOST_PP_NOT(2) == 0 END BEGIN BOOST_PP_AND(0, 0) == 0 END BEGIN BOOST_PP_AND(0, 3) == 0 END BEGIN BOOST_PP_AND(4, 0) == 0 END BEGIN BOOST_PP_AND(5, 6) == 1 END BEGIN BOOST_PP_OR(0, 0) == 0 END BEGIN BOOST_PP_OR(0, 7) == 1 END BEGIN BOOST_PP_OR(8, 0) == 1 END BEGIN BOOST_PP_OR(9, 1) == 1 END BEGIN BOOST_PP_XOR(0, 0) == 0 END BEGIN BOOST_PP_XOR(0, 2) == 1 END BEGIN BOOST_PP_XOR(3, 0) == 1 END BEGIN BOOST_PP_XOR(4, 5) == 0 END BEGIN BOOST_PP_NOR(0, 0) == 1 END BEGIN BOOST_PP_NOR(0, 6) == 0 END BEGIN BOOST_PP_NOR(7, 0) == 0 END BEGIN BOOST_PP_NOR(8, 9) == 0 END
cppisfun/GameEngine
foreign/boost/libs/preprocessor/test/logical.cpp
C++
gpl-3.0
1,330
/* Credits Originally based on Edgar Toernig's Minimalistic cooperative multitasking http://www.goron.de/~froese/ reorg by Steve Dekorte and Chis Double Symbian and Cygwin support by Chis Double Linux/PCC, Linux/Opteron, Irix and FreeBSD/Alpha, ucontext support by Austin Kurahone FreeBSD/Intel support by Faried Nawaz Mingw support by Pit Capitain Visual C support by Daniel Vollmer Solaris support by Manpreet Singh Fibers support by Jonas Eschenburg Ucontext arg support by Olivier Ansaldi Ucontext x86-64 support by James Burgess and Jonathan Wright Russ Cox for the newer portable ucontext implementions. Notes This is the system dependent coro code. Setup a jmp_buf so when we longjmp, it will invoke 'func' using 'stack'. Important: 'func' must not return! Usually done by setting the program counter and stack pointer of a new, empty stack. If you're adding a new platform, look in the setjmp.h for PC and SP members of the stack structure If you don't see those members, Kentaro suggests writting a simple test app that calls setjmp and dumps out the contents of the jmp_buf. (The PC and SP should be in jmp_buf->__jmpbuf). Using something like GDB to be able to peek into register contents right before the setjmp occurs would be helpful also. */ #include "Base.h" #include "Coro.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stddef.h> #ifndef __WIN32 #include "taskimpl.h" #endif #ifdef USE_VALGRIND #include <valgrind/valgrind.h> #define STACK_REGISTER(coro) \ { \ Coro *c = (coro); \ c->valgrindStackId = VALGRIND_STACK_REGISTER( \ c->stack, \ c->stack + c->requestedStackSize); \ } #define STACK_DEREGISTER(coro) \ VALGRIND_STACK_DEREGISTER((coro)->valgrindStackId) #else #define STACK_REGISTER(coro) #define STACK_DEREGISTER(coro) #endif typedef struct CallbackBlock { void *context; CoroStartCallback *func; } CallbackBlock; static CallbackBlock globalCallbackBlock; Coro *Coro_new(void) { Coro *self = (Coro *)io_calloc(1, sizeof(Coro)); self->requestedStackSize = CORO_DEFAULT_STACK_SIZE; self->allocatedStackSize = 0; #ifdef USE_FIBERS self->fiber = NULL; #else self->stack = NULL; #endif return self; } void Coro_allocStackIfNeeded(Coro *self) { if (self->stack && self->requestedStackSize < self->allocatedStackSize) { io_free(self->stack); self->stack = NULL; self->requestedStackSize = 0; } if (!self->stack) { self->stack = (void *)io_calloc(1, self->requestedStackSize + 16); self->allocatedStackSize = self->requestedStackSize; //printf("Coro_%p allocating stack size %i\n", (void *)self, self->requestedStackSize); STACK_REGISTER(self); } } void Coro_free(Coro *self) { #ifdef USE_FIBERS // If this coro has a fiber, delete it. // Don't delete the main fiber. We don't want to commit suicide. if (self->fiber && !self->isMain) { DeleteFiber(self->fiber); } #else STACK_DEREGISTER(self); #endif if (self->stack) { io_free(self->stack); } //printf("Coro_%p io_free\n", (void *)self); io_free(self); } // stack void *Coro_stack(Coro *self) { return self->stack; } size_t Coro_stackSize(Coro *self) { return self->requestedStackSize; } void Coro_setStackSize_(Coro *self, size_t sizeInBytes) { self->requestedStackSize = sizeInBytes; //self->stack = (void *)io_realloc(self->stack, sizeInBytes); //printf("Coro_%p io_reallocating stack size %i\n", (void *)self, sizeInBytes); } #if __GNUC__ == 4 uint8_t *Coro_CurrentStackPointer(void) __attribute__ ((noinline)); #endif uint8_t *Coro_CurrentStackPointer(void) { uint8_t a; uint8_t *b = &a; // to avoid compiler warning about unused variables return b; } size_t Coro_bytesLeftOnStack(Coro *self) { unsigned char dummy; ptrdiff_t p1 = (ptrdiff_t)(&dummy); ptrdiff_t p2 = (ptrdiff_t)Coro_CurrentStackPointer(); int stackMovesUp = p2 > p1; ptrdiff_t start = ((ptrdiff_t)self->stack); ptrdiff_t end = start + self->requestedStackSize; if (stackMovesUp) // like x86 { return end - p1; } else // like OSX on PPC { return p1 - start; } } int Coro_stackSpaceAlmostGone(Coro *self) { return Coro_bytesLeftOnStack(self) < CORO_STACK_SIZE_MIN; } /* Functions inlined sometimes and sometimes not by mingw and creating undefined reference problem */ #define GetCurrentFiber() ((PVOID)__readfsdword(0x10)) void Coro_initializeMainCoro(Coro *self) { self->isMain = 1; #ifdef USE_FIBERS // We must convert the current thread into a fiber if it hasn't already been done. if ((LPVOID) 0x1e00 == GetCurrentFiber()) // value returned when not a fiber { // Make this thread a fiber and set its data field to the main coro's address ConvertThreadToFiber(self); } // Make the main coro represent the current fiber self->fiber = GetCurrentFiber(); #endif } #undef GetCurrentFiber void Coro_startCoro_(Coro *self, Coro *other, void *context, CoroStartCallback *callback) { CallbackBlock sblock; CallbackBlock *block = &sblock; //CallbackBlock *block = malloc(sizeof(CallbackBlock)); // memory leak block->context = context; block->func = callback; Coro_allocStackIfNeeded(other); Coro_setup(other, block); Coro_switchTo_(self, other); } /* void Coro_startCoro_(Coro *self, Coro *other, void *context, CoroStartCallback *callback) { globalCallbackBlock.context = context; globalCallbackBlock.func = callback; Coro_allocStackIfNeeded(other); Coro_setup(other, &globalCallbackBlock); Coro_switchTo_(self, other); } */ #if defined(USE_UCONTEXT) && defined(__x86_64__) void Coro_StartWithArg(unsigned int hiArg, unsigned int loArg) { CallbackBlock *block = (CallbackBlock*)(((long long)hiArg << 32) | (long long)loArg); (block->func)(block->context); printf("Scheduler error: returned from coro start function\n"); exit(-1); } /* void Coro_Start(void) { CallbackBlock block = globalCallbackBlock; unsigned int hiArg = (unsigned int)(((long long)&block) >> 32); unsigned int loArg = (unsigned int)(((long long)&block) & 0xFFFFFFFF); Coro_StartWithArg(hiArg, loArg); } */ #else void Coro_StartWithArg(CallbackBlock *block) { (block->func)(block->context); printf("Scheduler error: returned from coro start function\n"); exit(-1); } void Coro_Start(void) { CallbackBlock block = globalCallbackBlock; Coro_StartWithArg(&block); } #endif // -------------------------------------------------------------------- void Coro_UnsupportedPlatformError(void) { printf("Io Scheduler error: no Coro_setupJmpbuf entry for this platform\n."); exit(1); } void Coro_switchTo_(Coro *self, Coro *next) { (void) self; #if defined(__SYMBIAN32__) ProcessUIEvent(); #elif defined(USE_FIBERS) SwitchToFiber(next->fiber); #elif defined(USE_UCONTEXT) swapcontext(&self->env, &next->env); #elif defined(USE_SETJMP) if (setjmp(self->env) == 0) { longjmp(next->env, 1); } #endif } // ---- setup ------------------------------------------ #if defined(USE_SETJMP) && defined(__x86_64__) void Coro_setup(Coro *self, void *arg) { /* since ucontext seems to be broken on amg64 */ setjmp(self->env); /* This is probably not nice in that it deals directly with * something with __ in front of it. * * Anyhow, Coro.h makes the member env of a struct Coro a * jmp_buf. A jmp_buf, as defined in the amd64 setjmp.h * is an array of one struct that wraps the actual __jmp_buf type * which is the array of longs (on a 64 bit machine) that * the programmer below expected. This struct begins with * the __jmp_buf array of longs, so I think it was supposed * to work like he originally had it, but for some reason * it didn't. I don't know why. * - Bryce Schroeder, 16 December 2006 * * Explaination of `magic' numbers: 6 is the stack pointer * (RSP, the 64 bit equivalent of ESP), 7 is the program counter. * This information came from this file on my Gentoo linux * amd64 computer: * /usr/include/gento-multilib/amd64/bits/setjmp.h * Which was ultimatly included from setjmp.h in /usr/include. */ self->env[0].__jmpbuf[6] = ((unsigned long)(Coro_stack(self))); self->env[0].__jmpbuf[7] = ((long)Coro_Start); } #elif defined(HAS_UCONTEXT_ON_PRE_SOLARIS_10) typedef void (*makecontext_func)(void); void Coro_setup(Coro *self, void *arg) { ucontext_t *ucp = (ucontext_t *) &self->env; getcontext(ucp); ucp->uc_stack.ss_sp = Coro_stack(self) + Coro_stackSize(self) - 8; ucp->uc_stack.ss_size = Coro_stackSize(self); ucp->uc_stack.ss_flags = 0; ucp->uc_link = NULL; makecontext(ucp, (makecontext_func)Coro_StartWithArg, 1, arg); } #elif defined(USE_UCONTEXT) typedef void (*makecontext_func)(void); void Coro_setup(Coro *self, void *arg) { ucontext_t *ucp = (ucontext_t *) &self->env; getcontext(ucp); ucp->uc_stack.ss_sp = Coro_stack(self); ucp->uc_stack.ss_size = Coro_stackSize(self); #if !defined(__APPLE__) ucp->uc_stack.ss_flags = 0; ucp->uc_link = NULL; #endif #if defined(__x86_64__) unsigned int hiArg = (unsigned int)((long long)arg >> 32); unsigned int loArg = (unsigned int)((long long)arg & 0xFFFFFFFF); makecontext(ucp, (makecontext_func)Coro_StartWithArg, 2, hiArg, loArg); #else makecontext(ucp, (makecontext_func)Coro_StartWithArg, 1, arg); #endif } #elif defined(USE_FIBERS) void Coro_setup(Coro *self, void *arg) { // If this coro was recycled and already has a fiber, delete it. // Don't delete the main fiber. We don't want to commit suicide. if (self->fiber && !self->isMain) { DeleteFiber(self->fiber); } self->fiber = CreateFiber(Coro_stackSize(self), (LPFIBER_START_ROUTINE)Coro_StartWithArg, (LPVOID)arg); if (!self->fiber) { DWORD err = GetLastError(); exit(err); } } #elif defined(__CYGWIN__) #define buf (self->env) void Coro_setup(Coro *self, void *arg) { setjmp(buf); buf[7] = (long)(Coro_stack(self) + Coro_stackSize(self) - 16); buf[8] = (long)Coro_Start; globalCallbackBlock.context=((CallbackBlock*)arg)->context; globalCallbackBlock.func=((CallbackBlock*)arg)->func; } #elif defined(__SYMBIAN32__) void Coro_setup(Coro *self, void *arg) { /* setjmp/longjmp is flakey under Symbian. If the setjmp is done inside the call then a crash occurs. Inlining it here solves the problem */ setjmp(self->env); self->env[0] = 0; self->env[1] = 0; self->env[2] = 0; self->env[3] = (unsigned long)(Coro_stack(self)) + Coro_stackSize(self) - 64; self->env[9] = (long)Coro_Start; self->env[8] = self->env[3] + 32; } #elif defined(_BSD_PPC_SETJMP_H_) #define buf (self->env) #define setjmp _setjmp #define longjmp _longjmp void Coro_setup(Coro *self, void *arg) { size_t *sp = (size_t *)(((intptr_t)Coro_stack(self) + Coro_stackSize(self) - 64 + 15) & ~15); setjmp(buf); //printf("self = %p\n", self); //printf("sp = %p\n", sp); buf[0] = (long)sp; buf[21] = (long)Coro_Start; globalCallbackBlock.context=((CallbackBlock*)arg)->context; globalCallbackBlock.func=((CallbackBlock*)arg)->func; //sp[-4] = (size_t)self; // for G5 10.3 //sp[-6] = (size_t)self; // for G4 10.4 //printf("self = %p\n", (void *)self); //printf("sp = %p\n", sp); } /* void Coro_setup(Coro *self, void *arg) { size_t *sp = (size_t *)(((intptr_t)Coro_stack(self) + Coro_stackSize(self) - 64 + 15) & ~15); setjmp(buf); //printf("self = %p\n", self); //printf("sp = %p\n", sp); buf[0] = (long)sp; buf[21] = (long)Coro_Start; //sp[-4] = (size_t)self; // for G5 10.3 //sp[-6] = (size_t)self; // for G4 10.4 //printf("self = %p\n", (void *)self); //printf("sp = %p\n", sp); } */ #elif defined(__DragonFly__) #define buf (self->env) void Coro_setup(Coro *self, void *arg) { void *stack = Coro_stack(self); size_t stacksize = Coro_stackSize(self); void *func = (void *)Coro_Start; setjmp(buf); buf->_jb[2] = (long)(stack + stacksize); buf->_jb[0] = (long)func; return; } #elif defined(__arm__) // contributed by Peter van Hardenberg #define buf (self->env) void Coro_setup(Coro *self, void *arg) { setjmp(buf); buf[8] = (int)Coro_stack(self) + (int)Coro_stackSize(self) - 16; buf[9] = (int)Coro_Start; } #else #error "Coro.c Error: Coro_setup() function needs to be defined for this platform." #endif // old code /* // APPLE coros are handled by PortableUContext now #elif defined(_BSD_PPC_SETJMP_H_) #define buf (self->env) #define setjmp _setjmp #define longjmp _longjmp void Coro_setup(Coro *self, void *arg) { size_t *sp = (size_t *)(((intptr_t)Coro_stack(self) + Coro_stackSize(self) - 64 + 15) & ~15); setjmp(buf); //printf("self = %p\n", self); //printf("sp = %p\n", sp); buf[0] = (int)sp; buf[21] = (int)Coro_Start; //sp[-4] = (size_t)self; // for G5 10.3 //sp[-6] = (size_t)self; // for G4 10.4 //printf("self = %p\n", (void *)self); //printf("sp = %p\n", sp); } #elif defined(_BSD_I386_SETJMP_H) #define buf (self->env) void Coro_setup(Coro *self, void *arg) { size_t *sp = (size_t *)((intptr_t)Coro_stack(self) + Coro_stackSize(self)); setjmp(buf); buf[9] = (int)(sp); // esp buf[12] = (int)Coro_Start; // eip //buf[8] = 0; // ebp } */ /* Solaris supports ucontext - so we don't need this stuff anymore void Coro_setup(Coro *self, void *arg) { // this bit goes before the setjmp call // Solaris 9 Sparc with GCC #if defined(__SVR4) && defined (__sun) #if defined(_JBLEN) && (_JBLEN == 12) && defined(__sparc) #if defined(_LP64) || defined(_I32LPx) #define JBTYPE long JBTYPE x; #else #define JBTYPE int JBTYPE x; asm("ta 3"); // flush register window #endif #define SUN_STACK_END_INDEX 1 #define SUN_PROGRAM_COUNTER 2 #define SUN_STACK_START_INDEX 3 // Solaris 9 i386 with GCC #elif defined(_JBLEN) && (_JBLEN == 10) && defined(__i386) #if defined(_LP64) || defined(_I32LPx) #define JBTYPE long JBTYPE x; #else #define JBTYPE int JBTYPE x; #endif #define SUN_PROGRAM_COUNTER 5 #define SUN_STACK_START_INDEX 3 #define SUN_STACK_END_INDEX 4 #endif #endif */ /* Irix supports ucontext - so we don't need this stuff anymore #elif defined(sgi) && defined(_IRIX4_SIGJBLEN) // Irix/SGI void Coro_setup(Coro *self, void *arg) { setjmp(buf); buf[JB_SP] = (__uint64_t)((char *)stack + stacksize - 8); buf[JB_PC] = (__uint64_t)Coro_Start; } */ /* Linux supports ucontext - so we don't need this stuff anymore #elif defined(linux) // Various flavors of Linux. #if defined(JB_GPR1) // Linux/PPC buf->__jmpbuf[JB_GPR1] = ((int) stack + stacksize - 64 + 15) & ~15; buf->__jmpbuf[JB_LR] = (int) Coro_Start; return; #elif defined(JB_RBX) // Linux/Opteron buf->__jmpbuf[JB_RSP] = (long int )stack + stacksize; buf->__jmpbuf[JB_PC] = Coro_Start; return; #elif defined(JB_SP) // Linux/x86 with glibc2 buf->__jmpbuf[JB_SP] = (int)stack + stacksize; buf->__jmpbuf[JB_PC] = (int)Coro_StartWithArg; // Push the argument on the stack (stack grows downwards) // note: stack is stacksize + 16 bytes long ((int *)stack)[stacksize/sizeof(int) + 1] = (int)self; return; #elif defined(_I386_JMP_BUF_H) // x86-linux with libc5 buf->__sp = (int)stack + stacksize; buf->__pc = Coro_Start; return; #elif defined(__JMP_BUF_SP) // arm-linux on the sharp zauras buf->__jmpbuf[__JMP_BUF_SP] = (int)stack + stacksize; buf->__jmpbuf[__JMP_BUF_SP+1] = (int)Coro_Start; return; #else */ /* Windows supports fibers - so we don't need this stuff anymore #elif defined(__MINGW32__) void Coro_setup(Coro *self, void *arg) { setjmp(buf); buf[4] = (int)((unsigned char *)stack + stacksize - 16); // esp buf[5] = (int)Coro_Start; // eip } #elif defined(_MSC_VER) void Coro_setup(Coro *self, void *arg) { setjmp(buf); // win32 visual c // should this be the same as __MINGW32__? buf[4] = (int)((unsigned char *)stack + stacksize - 16); // esp buf[5] = (int)Coro_Start; // eip } */ /* FreeBSD supports ucontext - so we don't need this stuff anymore #elif defined(__FreeBSD__) // FreeBSD. #if defined(_JBLEN) && (_JBLEN == 81) // FreeBSD/Alpha buf->_jb[2] = (long)Coro_Start; // sc_pc buf->_jb[26+4] = (long)Coro_Start; // sc_regs[R_RA] buf->_jb[27+4] = (long)Coro_Start; // sc_regs[R_T12] buf->_jb[30+4] = (long)(stack + stacksize); // sc_regs[R_SP] return; #elif defined(_JBLEN) // FreeBSD on IA32 buf->_jb[2] = (long)(stack + stacksize); buf->_jb[0] = (long)Coro_Start; return; #else Coro_UnsupportedPlatformError(); #endif */ /* NetBSD supports ucontext - so we don't need this stuff anymore #elif defined(__NetBSD__) void Coro_setup(Coro *self, void *arg) { setjmp(buf); #if defined(_JB_ATTRIBUTES) // NetBSD i386 buf[2] = (long)(stack + stacksize); buf[0] = (long)Coro_Start; #else Coro_UnsupportedPlatformError(); #endif } */ /* Sun supports ucontext - so we don't need this stuff anymore // Solaris supports ucontext - so we don't need this stuff anymore void Coro_setup(Coro *self, void *arg) { // this bit goes before the setjmp call // Solaris 9 Sparc with GCC #if defined(__SVR4) && defined (__sun) #if defined(_JBLEN) && (_JBLEN == 12) && defined(__sparc) #if defined(_LP64) || defined(_I32LPx) #define JBTYPE long JBTYPE x; #else #define JBTYPE int JBTYPE x; asm("ta 3"); // flush register window #endif #define SUN_STACK_END_INDEX 1 #define SUN_PROGRAM_COUNTER 2 #define SUN_STACK_START_INDEX 3 // Solaris 9 i386 with GCC #elif defined(_JBLEN) && (_JBLEN == 10) && defined(__i386) #if defined(_LP64) || defined(_I32LPx) #define JBTYPE long JBTYPE x; #else #define JBTYPE int JBTYPE x; #endif #define SUN_PROGRAM_COUNTER 5 #define SUN_STACK_START_INDEX 3 #define SUN_STACK_END_INDEX 4 #endif #endif #elif defined(__SVR4) && defined(__sun) // Solaris #if defined(SUN_PROGRAM_COUNTER) // SunOS 9 buf[SUN_PROGRAM_COUNTER] = (JBTYPE)Coro_Start; x = (JBTYPE)stack; while ((x % 8) != 0) x --; // align on an even boundary buf[SUN_STACK_START_INDEX] = (JBTYPE)x; x = (JBTYPE)((JBTYPE)stack-stacksize / 2 + 15); while ((x % 8) != 0) x ++; // align on an even boundary buf[SUN_STACK_END_INDEX] = (JBTYPE)x; */
turbedi/pokemon-online
src/libraries/Utilities/coro/Coro.c
C
gpl-3.0
18,692
<ul class="toc"> <% _.each(items, function(item) { %> <li class="toc-item<% if (item.id === app.views.navigationView.currentNavigationItem.id) { print(" active"); } %>"> <a data-section-id="<%= item.id %>" href="javascript:;"> <div class="toc-item-thumbnail"> <% if (item.get('thumbnail')) { %> <img src="<%= item.get('thumbnail') %>"> <% } %> </div> <div class="toc-item-text"> <h4><%= item.get('title') %></h4> <% if (item.get('subtitle')) { %> <h5><%= item.get('subtitle') %></h5> <% } %> </div> </a> <hr> </li> <% }); %> </ul>
IMAmuseum/OSCI-Toolkit-Frontend
dist/themes/Simple_Horizontal/templates/toolbar-toc.tpl.html
HTML
gpl-3.0
598
--[[ This file is part of Ice Lua Components. Ice Lua Components is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Ice Lua Components 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 Ice Lua Components. If not, see <http://www.gnu.org/licenses/>. ]] -- boo ~Dany0 DEUCE_NAME = server_config.deucename or "Deuce" function name_generate() local i local max_id = 0 for i=1,players.max do if players[i] ~= nil then local deuceid = tonumber(string.sub(players[i].name or "", string.len(DEUCE_NAME) + 1) or 0) if deuceid == max_id then max_id = deuceid + 1 end end end return DEUCE_NAME..max_id end
fkaa/iceball
pkg/iceball/deucenamegen/main.lua
Lua
gpl-3.0
1,117
package fr.neamar.kiss; import android.app.Activity; /** * An empty activity used for changing Android's Default Launcher */ public class DummyActivity extends Activity{ }
ilmich/KISS
app/src/main/java/fr/neamar/kiss/DummyActivity.java
Java
gpl-3.0
177
#define yy_create_buffer vs10__create_buffer #define yy_delete_buffer vs10__delete_buffer #define yy_scan_buffer vs10__scan_buffer #define yy_scan_string vs10__scan_string #define yy_scan_bytes vs10__scan_bytes #define yy_flex_debug vs10__flex_debug #define yy_init_buffer vs10__init_buffer #define yy_flush_buffer vs10__flush_buffer #define yy_load_buffer_state vs10__load_buffer_state #define yy_switch_to_buffer vs10__switch_to_buffer #define yyin vs10_in #define yyleng vs10_leng #define yylex vs10_lex #define yyout vs10_out #define yyrestart vs10_restart #define yytext vs10_text #define yywrap vs10_wrap #line 20 "_vs1.0_lexer.cpp" /* A lexical scanner generated by flex */ /* Scanner skeleton version: * $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.91 96/09/10 16:58:48 vern Exp $ */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #include <stdio.h> #include <errno.h> /* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */ #ifdef c_plusplus #ifndef __cplusplus #define __cplusplus #endif #endif #ifdef __cplusplus #include <stdlib.h> #ifndef _WIN32 #include <unistd.h> #endif /* Use prototypes in function declarations. */ #define YY_USE_PROTOS /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ #if __STDC__ #define YY_USE_PROTOS #define YY_USE_CONST #endif /* __STDC__ */ #endif /* ! __cplusplus */ #ifdef __TURBOC__ #pragma warn -rch #pragma warn -use #include <io.h> #include <stdlib.h> #define YY_USE_CONST #define YY_USE_PROTOS #endif #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif #ifdef YY_USE_PROTOS #define YY_PROTO(proto) proto #else #define YY_PROTO(proto) () #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart( yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #define YY_BUF_SIZE 16384 typedef struct yy_buffer_state *YY_BUFFER_STATE; extern int yyleng; extern FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* The funky do-while in the following #define is used to turn the definition * int a single C statement (which needs a semi-colon terminator). This * avoids problems with code like: * * if ( condition_holds ) * yyless( 5 ); * else * do_something_else(); * * Prior to using the do-while the compiler would get upset at the * "else" because it interpreted the "if" statement as being all * done when it reached the ';' after the yyless() call. */ /* Return all but the first 'n' matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ *yy_cp = yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yy_c_buf_p = yy_cp = yy_bp + n - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yytext_ptr ) /* The following is because we cannot portably get our hands on size_t * (without autoconf's help, which isn't available because we want * flex-generated scanners to compile on their own). */ typedef unsigned int yy_size_t; struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; static YY_BUFFER_STATE yy_current_buffer = 0; /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". */ #define YY_CURRENT_BUFFER yy_current_buffer /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; static int yy_n_chars; /* number of characters read into yy_ch_buf */ int yyleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = (char *) 0; static int yy_init = 1; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow yywrap()'s to do buffer switches * instead of setting up a fresh yyin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; void yyrestart YY_PROTO(( FILE *input_file )); void yy_switch_to_buffer YY_PROTO(( YY_BUFFER_STATE new_buffer )); void yy_load_buffer_state YY_PROTO(( void )); YY_BUFFER_STATE yy_create_buffer YY_PROTO(( FILE *file, int size )); void yy_delete_buffer YY_PROTO(( YY_BUFFER_STATE b )); void yy_init_buffer YY_PROTO(( YY_BUFFER_STATE b, FILE *file )); void yy_flush_buffer YY_PROTO(( YY_BUFFER_STATE b )); #define YY_FLUSH_BUFFER yy_flush_buffer( yy_current_buffer ) YY_BUFFER_STATE yy_scan_buffer YY_PROTO(( char *base, yy_size_t size )); YY_BUFFER_STATE yy_scan_string YY_PROTO(( yyconst char *yy_str )); YY_BUFFER_STATE yy_scan_bytes YY_PROTO(( yyconst char *bytes, int len )); static void *yy_flex_alloc YY_PROTO(( yy_size_t )); static void *yy_flex_realloc YY_PROTO(( void *, yy_size_t )); static void yy_flex_free YY_PROTO(( void * )); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! yy_current_buffer ) \ yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ yy_current_buffer->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! yy_current_buffer ) \ yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ yy_current_buffer->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (yy_current_buffer->yy_at_bol) #define YY_USES_REJECT typedef unsigned char YY_CHAR; FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; typedef int yy_state_type; extern char *yytext; #define yytext_ptr yytext static yy_state_type yy_get_previous_state YY_PROTO(( void )); static yy_state_type yy_try_NUL_trans YY_PROTO(( yy_state_type current_state )); static int yy_get_next_buffer YY_PROTO(( void )); static void yy_fatal_error YY_PROTO(( yyconst char msg[] )); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yytext_ptr = yy_bp; \ yyleng = (int) (yy_cp - yy_bp); \ yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yy_c_buf_p = yy_cp; #define YY_NUM_RULES 72 #define YY_END_OF_BUFFER 73 static yyconst short int yy_acclist[406] = { 0, 2, 2, 56, 56, 46, 46, 31, 31, 29, 29, 73, 69, 71, 72, 64, 69, 71, 72, 66, 69, 72, 71, 72, 71, 72, 63, 71, 72, 63, 71, 72, 37, 63, 71, 72, 63, 71, 72, 36, 71, 72, 13, 71, 72, 62, 71, 72, 62, 63, 71, 72, 62, 71, 72, 62, 71, 72, 62, 71, 72, 62, 71, 72, 62, 71, 72, 64, 69, 71, 72, 16, 63, 71, 72, 72, 72, 22, 65, 72, 21, 72, 23, 72, 72, 34, 72, 72, 20, 72, 68, 70, 72, 68, 72, 70, 72, 67, 70, 72, 2, 72, 1, 72, 41, 72, 41, 42, 72, 56, 72, 56, 72, 57, 72, 56, 72, 56, 72, 56, 72, 50, 72, 46, 50, 72, 49, 72, 48, 72, 50, 72, 47, 50, 72, 72, 72, 59, 72, 72, 72, 61, 72, 72, 40, 72, 40, 62, 72, 39, 40, 62, 72, 45, 72, 44, 45, 72, 43, 45, 72, 72, 27, 72, 31, 72, 31, 72, 32, 72, 31, 72, 29, 72, 30, 72, 51, 72, 64, 15, 17, 14, 36, 13, 62, 62, 3, 62, 6, 62, 62, 62, 62, 62, 5, 62, 4, 62, 62, 64, 16, 16, 19, 34, 20, 67, 2, 1, 41, 56, 56, 56, 56, 17, 56, 56, 54, 56, 50, 46, 50, 47, 50, 47, 50, 47, 59, 61, 60, 61, 39, 39, 39, 62, 44, 27, 31, 31, 31, 31, 29, 51, 53, 51, 51, 14, 12, 12, 62, 3, 12, 3, 12, 6, 12, 6, 12, 8, 62, 62, 62, 62, 7, 62, 5, 12, 5, 12, 4, 12, 4, 12, 16, 56, 39, 62, 31, 31, 31, 52, 3, 3, 6, 6, 8, 12, 8, 12, 9, 62, 10, 62, 11, 62, 7, 12, 7, 12, 5, 5, 4, 4, 55, 56, 38, 39, 62, 31, 31, 26, 8, 8, 9, 12, 9, 12, 10, 12, 10, 12, 11, 12, 11, 12, 7, 7, 55, 56, 56, 55, 56, 58, 59, 38, 39, 38, 39, 26, 31, 31, 26, 26, 28, 9, 9, 10, 10, 11, 11, 35, 55, 56, 55, 56, 55, 56, 55, 56, 26, 31, 31, 26, 31, 28, 31, 26, 26, 26, 28, 28, 24, 35, 35, 55, 56, 55, 56, 26, 31, 26, 31, 26, 31, 28, 31, 31, 28, 31, 33, 26, 28, 28, 28, 25, 26, 31, 28, 31, 28, 31, 28, 31, 28, 18, 28, 31 } ; static yyconst short int yy_accept[330] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 9, 10, 11, 11, 11, 12, 15, 19, 22, 24, 26, 29, 32, 36, 39, 42, 45, 48, 52, 55, 58, 61, 64, 67, 71, 75, 76, 77, 80, 82, 84, 85, 87, 88, 90, 93, 95, 97, 100, 102, 104, 106, 109, 111, 113, 115, 117, 119, 121, 123, 126, 128, 130, 132, 135, 136, 137, 139, 140, 141, 143, 144, 146, 149, 153, 155, 158, 161, 162, 164, 166, 168, 170, 172, 174, 176, 178, 179, 179, 179, 179, 179, 179, 180, 181, 182, 183, 184, 185, 186, 188, 190, 191, 192, 193, 194, 196, 198, 199, 200, 201, 202, 202, 203, 203, 204, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 215, 216, 217, 218, 219, 221, 223, 225, 226, 226, 227, 227, 227, 227, 227, 228, 228, 230, 231, 232, 234, 235, 235, 236, 237, 238, 239, 240, 241, 243, 244, 244, 244, 245, 245, 245, 245, 245, 245, 245, 246, 247, 249, 251, 253, 255, 257, 259, 260, 261, 262, 264, 266, 268, 270, 272, 272, 273, 274, 274, 276, 277, 278, 279, 279, 280, 280, 280, 280, 280, 280, 280, 281, 282, 283, 284, 286, 288, 290, 292, 294, 296, 298, 299, 300, 301, 302, 302, 304, 304, 307, 308, 309, 309, 310, 310, 310, 310, 310, 311, 312, 314, 316, 318, 320, 322, 324, 325, 326, 326, 328, 329, 331, 331, 333, 335, 337, 339, 340, 340, 341, 341, 342, 343, 343, 343, 343, 344, 345, 346, 347, 348, 349, 350, 352, 354, 356, 358, 360, 361, 363, 365, 365, 366, 367, 368, 369, 369, 370, 371, 371, 371, 372, 373, 375, 377, 379, 381, 383, 385, 386, 388, 389, 390, 391, 392, 393, 394, 394, 396, 398, 400, 402, 403, 404, 406, 406 } ; static yyconst int yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 4, 5, 4, 6, 4, 4, 7, 8, 9, 10, 11, 6, 12, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 4, 15, 6, 4, 6, 4, 4, 16, 16, 16, 17, 16, 18, 16, 16, 16, 16, 16, 16, 16, 16, 16, 19, 16, 16, 16, 20, 16, 16, 16, 16, 16, 16, 6, 21, 6, 4, 22, 4, 23, 16, 24, 25, 26, 27, 28, 16, 29, 16, 16, 30, 31, 32, 33, 16, 16, 34, 35, 36, 37, 38, 39, 39, 39, 39, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 } ; static yyconst int yy_meta[40] = { 0, 1, 2, 3, 1, 1, 1, 2, 1, 1, 1, 4, 1, 1, 5, 1, 5, 5, 5, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 } ; static yyconst short int yy_base[369] = { 0, 0, 38, 764, 763, 761, 760, 759, 758, 757, 756, 755, 754, 753, 752, 48, 69, 751, 750, 39, 84, 86, 90, 93, 107, 41, 95, 44, 80, 122, 0, 112, 160, 749, 748, 163, 167, 747, 746, 740, 739, 746, 767, 100, 767, 767, 148, 767, 173, 767, 53, 731, 0, 722, 0, 157, 164, 163, 170, 173, 186, 187, 740, 767, 767, 767, 767, 739, 767, 738, 767, 767, 767, 767, 0, 737, 767, 0, 0, 718, 191, 767, 185, 195, 178, 0, 736, 767, 767, 724, 725, 732, 198, 767, 199, 200, 767, 201, 767, 0, 211, 767, 732, 767, 730, 767, 0, 213, 767, 706, 0, 767, 217, 221, 705, 704, 175, 201, 232, 767, 767, 0, 715, 0, 234, 0, 237, 239, 241, 243, 245, 255, 268, 270, 277, 281, 726, 272, 724, 767, 723, 767, 722, 767, 0, 721, 767, 0, 702, 285, 283, 228, 701, 291, 767, 43, 0, 719, 709, 708, 0, 715, 767, 293, 222, 295, 206, 767, 208, 767, 298, 767, 300, 715, 713, 767, 0, 303, 689, 232, 0, 308, 711, 700, 709, 294, 679, 683, 674, 683, 282, 683, 0, 767, 0, 314, 767, 322, 767, 324, 328, 330, 332, 339, 334, 767, 341, 767, 692, 703, 297, 82, 345, 672, 668, 675, 692, 767, 661, 659, 651, 644, 640, 630, 355, 767, 357, 767, 360, 767, 366, 368, 370, 372, 767, 374, 767, 376, 767, 254, 378, 379, 383, 629, 606, 599, 381, 603, 598, 593, 558, 395, 767, 398, 767, 400, 767, 402, 767, 404, 767, 502, 406, 374, 396, 410, 767, 412, 767, 416, 453, 439, 420, 445, 336, 421, 452, 423, 395, 422, 767, 435, 767, 437, 767, 439, 430, 431, 434, 454, 446, 403, 351, 458, 408, 413, 417, 449, 461, 376, 453, 353, 343, 314, 475, 767, 466, 480, 457, 471, 475, 483, 309, 476, 311, 479, 484, 487, 490, 250, 162, 491, 494, 495, 498, 499, 115, 502, 767, 517, 522, 527, 532, 537, 542, 547, 552, 557, 562, 567, 572, 577, 582, 587, 592, 95, 89, 597, 602, 607, 40, 612, 617, 622, 627, 632, 637, 642, 647, 652, 657, 662, 667, 672, 677, 682, 687, 692, 697 } ; static yyconst short int yy_def[369] = { 0, 328, 1, 329, 329, 330, 330, 330, 330, 330, 330, 331, 331, 332, 332, 333, 333, 334, 334, 335, 335, 336, 336, 337, 337, 338, 338, 339, 339, 328, 29, 340, 340, 341, 341, 342, 342, 343, 343, 330, 330, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 344, 345, 346, 345, 345, 345, 345, 345, 328, 328, 347, 328, 328, 328, 328, 348, 328, 349, 328, 328, 328, 328, 350, 351, 328, 352, 352, 353, 353, 328, 353, 353, 353, 354, 354, 328, 328, 354, 355, 356, 356, 328, 356, 357, 328, 357, 328, 346, 346, 328, 328, 328, 358, 328, 359, 359, 328, 359, 360, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 361, 328, 344, 345, 346, 345, 345, 345, 345, 345, 345, 345, 345, 345, 328, 328, 328, 347, 328, 348, 328, 349, 328, 350, 351, 328, 352, 353, 353, 353, 353, 353, 353, 328, 353, 354, 354, 355, 355, 362, 356, 328, 356, 356, 356, 357, 328, 357, 328, 328, 328, 346, 328, 358, 328, 359, 359, 359, 359, 360, 328, 328, 328, 363, 328, 328, 328, 328, 328, 328, 328, 361, 328, 346, 328, 328, 328, 328, 345, 345, 345, 345, 345, 328, 328, 328, 328, 328, 328, 353, 356, 346, 359, 359, 359, 363, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 345, 345, 345, 328, 328, 328, 328, 328, 328, 328, 353, 356, 346, 359, 359, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 353, 353, 364, 356, 328, 328, 328, 359, 359, 328, 328, 328, 365, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 364, 364, 364, 364, 359, 359, 366, 359, 328, 365, 365, 365, 328, 328, 367, 328, 328, 328, 328, 328, 364, 364, 366, 366, 366, 359, 359, 368, 328, 365, 367, 367, 367, 328, 328, 366, 368, 368, 368, 367, 328, 368, 0, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328 } ; static yyconst short int yy_nxt[807] = { 0, 42, 43, 44, 45, 46, 47, 47, 47, 47, 48, 47, 49, 50, 51, 52, 53, 53, 53, 53, 53, 45, 54, 55, 56, 53, 53, 53, 53, 53, 53, 53, 53, 57, 58, 53, 53, 53, 59, 53, 60, 63, 78, 92, 93, 144, 63, 96, 61, 71, 71, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 120, 73, 149, 97, 121, 94, 210, 73, 71, 71, 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 96, 73, 162, 63, 78, 80, 81, 73, 63, 80, 81, 125, 86, 87, 92, 93, 82, 124, 97, 113, 82, 88, 114, 89, 83, 90, 86, 87, 83, 84, 241, 102, 63, 84, 326, 88, 103, 89, 94, 90, 98, 98, 63, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 99, 99, 99, 99, 99, 98, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 100, 102, 63, 326, 107, 108, 103, 109, 107, 108, 126, 109, 115, 116, 118, 119, 117, 127, 125, 128, 129, 130, 131, 132, 125, 125, 133, 135, 137, 119, 114, 125, 150, 152, 125, 136, 153, 154, 149, 163, 162, 162, 167, 169, 188, 149, 189, 134, 167, 155, 169, 149, 170, 171, 177, 149, 151, 178, 181, 182, 168, 168, 113, 164, 162, 114, 168, 190, 168, 183, 165, 184, 191, 118, 119, 193, 193, 185, 195, 196, 197, 198, 193, 193, 193, 193, 193, 193, 149, 172, 126, 319, 127, 165, 199, 194, 193, 193, 194, 155, 194, 214, 194, 215, 194, 261, 194, 239, 203, 204, 205, 206, 207, 137, 119, 200, 194, 201, 193, 193, 202, 132, 135, 133, 150, 114, 153, 154, 208, 194, 136, 194, 153, 154, 163, 162, 182, 162, 194, 170, 171, 170, 171, 149, 177, 149, 221, 178, 151, 181, 182, 149, 314, 222, 185, 224, 225, 149, 164, 211, 183, 313, 184, 226, 227, 228, 229, 240, 185, 193, 193, 193, 193, 193, 193, 235, 236, 199, 212, 320, 233, 234, 237, 238, 319, 194, 170, 171, 296, 194, 297, 194, 203, 194, 301, 230, 224, 225, 226, 227, 194, 251, 252, 309, 231, 310, 232, 253, 254, 255, 256, 257, 258, 259, 260, 235, 236, 237, 238, 262, 265, 266, 272, 242, 267, 268, 264, 194, 300, 194, 263, 194, 264, 273, 149, 274, 251, 252, 149, 279, 280, 281, 282, 283, 284, 259, 260, 262, 287, 314, 288, 265, 266, 267, 268, 292, 289, 290, 263, 303, 264, 272, 298, 279, 280, 296, 149, 297, 291, 315, 292, 297, 273, 299, 274, 300, 281, 282, 283, 284, 304, 305, 287, 306, 288, 288, 287, 290, 288, 302, 289, 289, 285, 301, 289, 307, 154, 274, 291, 311, 292, 296, 298, 297, 294, 317, 287, 318, 288, 309, 312, 310, 313, 299, 289, 300, 304, 305, 306, 293, 288, 307, 154, 321, 311, 310, 289, 309, 323, 310, 324, 315, 287, 297, 288, 312, 317, 313, 318, 325, 289, 318, 317, 321, 318, 310, 323, 327, 324, 324, 323, 325, 324, 318, 327, 285, 324, 62, 62, 62, 62, 62, 63, 63, 63, 63, 63, 67, 67, 67, 67, 67, 69, 69, 69, 69, 69, 74, 74, 74, 74, 74, 75, 75, 75, 75, 75, 77, 77, 77, 77, 77, 79, 79, 79, 79, 79, 85, 85, 85, 85, 85, 91, 91, 91, 91, 91, 95, 95, 95, 95, 95, 101, 101, 101, 101, 101, 104, 104, 104, 104, 104, 106, 106, 106, 106, 106, 110, 110, 110, 110, 110, 123, 123, 278, 123, 123, 138, 138, 138, 138, 138, 140, 140, 140, 140, 140, 142, 142, 142, 142, 142, 145, 145, 145, 145, 145, 147, 277, 147, 147, 147, 148, 148, 276, 148, 148, 156, 156, 275, 271, 156, 159, 159, 270, 159, 159, 161, 161, 161, 161, 161, 166, 166, 166, 166, 166, 174, 174, 174, 174, 174, 176, 176, 269, 176, 176, 180, 180, 250, 180, 180, 192, 192, 249, 192, 192, 160, 160, 248, 160, 160, 216, 216, 216, 216, 216, 286, 286, 247, 286, 286, 295, 295, 246, 295, 295, 308, 308, 245, 308, 308, 316, 316, 217, 316, 316, 322, 322, 244, 322, 322, 243, 215, 209, 239, 223, 220, 219, 218, 189, 217, 184, 182, 213, 175, 173, 162, 160, 160, 157, 149, 149, 146, 143, 141, 139, 209, 122, 187, 186, 179, 175, 173, 162, 160, 158, 157, 149, 146, 143, 141, 139, 125, 122, 328, 112, 112, 111, 111, 105, 105, 76, 76, 70, 70, 68, 68, 66, 66, 65, 65, 64, 64, 63, 63, 41, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328 } ; static yyconst short int yy_chk[807] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 19, 19, 25, 25, 350, 19, 27, 2, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 50, 15, 155, 27, 50, 25, 155, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 28, 16, 211, 20, 20, 21, 21, 16, 20, 22, 22, 346, 23, 23, 26, 26, 21, 345, 28, 43, 22, 23, 43, 23, 21, 23, 24, 24, 22, 21, 211, 31, 31, 22, 326, 24, 31, 24, 26, 24, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 32, 32, 320, 35, 35, 32, 35, 36, 36, 55, 36, 46, 46, 48, 48, 46, 56, 55, 57, 57, 57, 57, 58, 57, 56, 59, 60, 61, 61, 60, 58, 80, 82, 59, 60, 83, 83, 84, 92, 92, 94, 95, 97, 116, 82, 116, 59, 166, 84, 168, 80, 100, 100, 107, 83, 80, 107, 112, 112, 95, 97, 113, 92, 164, 113, 166, 117, 168, 112, 94, 112, 117, 118, 118, 124, 124, 112, 126, 126, 127, 127, 128, 128, 129, 129, 130, 130, 151, 100, 126, 319, 127, 164, 128, 124, 131, 131, 126, 151, 127, 179, 128, 179, 129, 239, 130, 239, 131, 132, 132, 133, 133, 137, 137, 129, 131, 130, 134, 134, 130, 132, 135, 133, 150, 135, 149, 149, 134, 132, 135, 133, 153, 153, 163, 163, 185, 165, 134, 170, 170, 172, 172, 150, 177, 149, 190, 177, 150, 181, 181, 153, 314, 190, 185, 195, 195, 210, 163, 165, 181, 312, 181, 197, 197, 199, 199, 210, 181, 200, 200, 201, 201, 202, 202, 204, 204, 199, 172, 303, 203, 203, 206, 206, 302, 199, 212, 212, 274, 200, 274, 201, 203, 202, 301, 200, 224, 224, 226, 226, 203, 228, 228, 292, 201, 292, 202, 230, 230, 231, 231, 232, 232, 233, 233, 235, 235, 237, 237, 240, 241, 241, 246, 212, 242, 242, 263, 230, 299, 231, 240, 232, 240, 246, 263, 246, 251, 251, 240, 253, 253, 255, 255, 257, 257, 259, 259, 262, 264, 294, 264, 265, 265, 267, 267, 291, 264, 269, 262, 278, 262, 272, 275, 279, 279, 295, 262, 295, 269, 296, 269, 296, 272, 275, 272, 275, 281, 281, 283, 283, 285, 285, 286, 287, 286, 287, 288, 290, 288, 277, 286, 287, 285, 276, 288, 289, 289, 273, 290, 293, 290, 297, 298, 297, 271, 300, 289, 300, 289, 308, 293, 308, 293, 298, 289, 298, 304, 304, 306, 270, 306, 307, 307, 309, 311, 309, 306, 310, 313, 310, 313, 315, 307, 315, 307, 311, 316, 311, 316, 317, 307, 317, 318, 321, 318, 321, 322, 323, 322, 323, 324, 325, 324, 325, 327, 261, 327, 329, 329, 329, 329, 329, 330, 330, 330, 330, 330, 331, 331, 331, 331, 331, 332, 332, 332, 332, 332, 333, 333, 333, 333, 333, 334, 334, 334, 334, 334, 335, 335, 335, 335, 335, 336, 336, 336, 336, 336, 337, 337, 337, 337, 337, 338, 338, 338, 338, 338, 339, 339, 339, 339, 339, 340, 340, 340, 340, 340, 341, 341, 341, 341, 341, 342, 342, 342, 342, 342, 343, 343, 343, 343, 343, 344, 344, 250, 344, 344, 347, 347, 347, 347, 347, 348, 348, 348, 348, 348, 349, 349, 349, 349, 349, 351, 351, 351, 351, 351, 352, 249, 352, 352, 352, 353, 353, 248, 353, 353, 354, 354, 247, 245, 354, 355, 355, 244, 355, 355, 356, 356, 356, 356, 356, 357, 357, 357, 357, 357, 358, 358, 358, 358, 358, 359, 359, 243, 359, 359, 360, 360, 223, 360, 360, 361, 361, 222, 361, 361, 362, 362, 221, 362, 362, 363, 363, 363, 363, 363, 364, 364, 220, 364, 364, 365, 365, 219, 365, 365, 366, 366, 218, 366, 366, 367, 367, 216, 367, 367, 368, 368, 215, 368, 368, 214, 213, 209, 208, 191, 189, 188, 187, 186, 184, 183, 182, 178, 174, 173, 161, 159, 158, 157, 152, 148, 145, 142, 140, 138, 136, 122, 115, 114, 109, 104, 102, 91, 90, 89, 86, 79, 75, 69, 67, 62, 53, 51, 41, 40, 39, 38, 37, 34, 33, 18, 17, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328 } ; static yy_state_type yy_state_buf[YY_BUF_SIZE + 2], *yy_state_ptr; static char *yy_full_match; static int yy_lp; #define REJECT \ { \ *yy_cp = yy_hold_char; /* undo effects of setting up yytext */ \ yy_cp = yy_full_match; /* restore poss. backed-over text */ \ ++yy_lp; \ goto find_rule; \ } #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET char *yytext; #line 1 "vs1.0_tokens.l" #define INITIAL 0 #define INCLUDE 1 #define DEFINE 2 #define DEFSTR 3 #define DEFSPACE 4 #define SKIPLINE 5 #define EATCOMMENT 6 #define EATSTRING 7 #define SAVELINE 8 #define MACRONAME 9 #define MACROBODY 10 #define MACROPARM 11 #define EATMACRO 12 #define EATDEFINE 13 #define MODIFIER 14 #define MACROPARMSTART 15 #define IFDEFNAME 16 #define IFDEFBODY 17 #define ENDMACRO 18 #define MACROPARMEND 19 #line 8 "vs1.0_tokens.l" #include <stdarg.h> #include <stdlib.h> #ifdef _WIN32 #include <io.h> # ifdef __GNUC__ # include <sys/types.h> # include <ctype.h> # endif #else #include <sys/types.h> #include <ctype.h> #define _stat stat #define _open open #define _O_RDONLY O_RDONLY #define _fstat fstat #define _close close #define stricmp strcasecmp #endif #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include "macro.h" #include "nvparse_errors.h" #include "vs1.0_inst_list.h" #include "_vs1.0_parser.h" #define yylineno line_number #include "nvparse_externs.h" #define YY_NO_UNPUT int line_incr; void LexError(const char *format, ...); void LexWarning(const char *format, ...); char *ReadTextFile(const char * filename); unsigned int MakeRegisterMask(char *findName); unsigned int FindSwizzleValue(char *swizzleText); enum ERROR_VALUES { ERROR_NONE = 0, ERROR_MEMORY_ALLOC, ERROR_FILE_OPEN, ERROR_UNSUCCESSFUL_ASSEMBLE, ERROR_TOO_MANY_PARMS, ERROR_DEST_WRITE, ERROR_LIST_OPEN, ERROR_DEST_OPEN, ERROR_NO_ARGUMENTS, ERROR_MACRO_OVERRUN }; //extern void GenSwitchFileNames(char *fileName); //extern unsigned int gLinesAssembled; unsigned int gLinesAssembled; #define YY_INPUT(buf,result,max_size) \ { \ int c = *myin++; \ result = (c == 0) ? YY_NULL : (buf[0] = c, 1); \ } #define SAFEDELETEARRAY(x) if ((x) != NULL) \ delete [] (x) #define SAFEFREE(x) if ((x) != NULL) \ free((x)) #define MAXREPLACESTRING 255 char gReplaceText[MAXREPLACESTRING+1]; // // forward prototypes for macro functions // void MacroIncFunction(char *, unsigned int *, char **); void MacroDecFunction(char *, unsigned int *, char **); void MacroAddFunction(char *, unsigned int *, char **); void MacroSubFunction(char *, unsigned int *, char **); MACROFUNCTIONS gMacroFunctions[] = { { "inc(", MacroIncFunction }, { "dec(", MacroDecFunction }, { "add(", MacroAddFunction }, { "sub(", MacroSubFunction } }; #define NUM_MACRO_FUNCTIONS (sizeof(gMacroFunctions) / sizeof(MACROFUNCTIONS)) #define MAX_INCLUDE_DEPTH 1024 typedef struct INCLUDEINFO { char *fileName; unsigned int lineNo; YY_BUFFER_STATE buffer; MACROENTRY *lastInvokeMacro; // save off in case nested macros. MACROENTRY *lastParseMacro; // recursive macros MACROTEXT *lastMacroLineParse; // save off for recursive lines of macros working on. bool lastbInsideMacro; // save off for recursive macros bool lastbInsideDefine; // save off for recursive macros/defines bool lastbInsideInclude; bool lastbProcessingIFDEF; // save off #define information // FILE *fileHandle; char *prevString; char *nextString; } INCLUDEINFO; INCLUDEINFO gIncludeStack[MAX_INCLUDE_DEPTH]; int gIncludeStackIndex = 0; IFDEFINFO gIfDefStack[MAX_IFDEF_DEPTH]; int gIfDefStackIndex = 0; unsigned int &base_linenumber = gIncludeStack[0].lineNo; bool gbInsideInclude = false; bool gbProcessingBuiltIn = false; bool gbProcessingDefine = false; unsigned int gCountParen = 0; bool gbProcessingIFDEF = false; bool gbIFDEF = false; bool gbCompareDefine = false; unsigned int gIfDefStartLine; MACROENTRY *gLastMacro; MACROENTRY *gInvokeMacro; MACROENTRY *gTempMacro; // until all the parameters are read MACROENTRY *FindMacro(char *macroName); MACROENTRY *FindNMacro(char *macroName, unsigned int sLen); MACROFUNCTIONPTR gMacroCallFunction; const char *builtInMacros = "macro m3x2 reg1, reg2, reg3\n" " dp3 %reg1.x, %reg2, %reg3\n" " dp3 %reg1.y, %reg2, %inc(%reg3)\n" "endm"; // // local prototypes // void CleanUp(); void ReplaceMacroParms(char *srcLine, char *destLine, MACROENTRY *srcParms, MACROENTRY *invParms); MACROTEXT *SaveMacroText(char *srcText, MACROTEXT *lastMacroText); void FreeMacroEntry(MACROENTRY *macEntry); void EndMacroParms(); char *FindAlphaNum(char *srcStr, unsigned int *sLen); void DebugUnhandledState(); unsigned int gCommentStartLine; unsigned int gMacroStartLine; char *gCurFileName = NULL; #define MAXSAVELINE 4095 char gSaveLine[MAXSAVELINE+1]; char gMacroLine[MAXSAVELINE+1]; #if 1 #ifdef _DEBUG #define ECHO DebugUnhandledState(); #else #define ECHO #endif #endif bool gbInsideMacro = false; // flag if we are doing a macro replace or not. bool gbTempInsideMacro = false; unsigned int gInvokeState = INITIAL; MACROENTRY *gParseMacro; // which source macro entry we are using MACROENTRY *gTempParseMacro; // temporary holder until parameters are received. MACROTEXT *gMacroLineParse; // which line we are currently parsing inside the macro invocation enum OPCODETYPE { TYPE_NONE = 0, TYPE_VERTEX_SHADER = 1, TYPE_PIXEL_SHADER = 2 }; typedef struct OPCODEMAP { const char *string; // string for opcode int tokenName; // name of the corresponding token int numArguments; // number of arguments for opcode float version; // minimum version supported in. int opcodeTypeFlags; // whether opcode can be used in vertex shader or pixel shader bool opcodeModify; // if opcode modifiers can be used bool textureOpcode; // only outputs to the texture unit } OPCODEMAP; #ifndef TRUE #define TRUE true #endif #ifndef FALSE #define FALSE false #endif OPCODEMAP theOpcodes[] = { { "add", ADD_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, { "dp3", DP3_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, { "dp4", DP4_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "dst", DST_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "exp", EXP_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "expp", EXPP_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "frc", FRC_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "lit", LIT_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "log", LOG_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "logp", LOGP_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "m3x2", M3X2_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "m3x3", M3X3_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "m3x4", M3X4_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "m4x3", M4X3_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "m4x4", M4X4_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "mad", MAD_INSTR, 4, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, { "max", MAX_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "min", MIN_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "mov", MOV_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, { "mul", MUL_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, { "nop", NOP_INSTR, 0, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, { "rcp", RCP_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "rsq", RSQ_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "sge", SGE_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "slt", SLT_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, { "sub", SUB_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, }; #define NUMOPCODES (sizeof(theOpcodes) / sizeof(OPCODEMAP)) OPCODEMAP *FindOpcode(char *findName); #line 993 "_vs1.0_lexer.cpp" /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap YY_PROTO(( void )); #else extern int yywrap YY_PROTO(( void )); #endif #endif #ifndef YY_NO_UNPUT static void yyunput YY_PROTO(( int c, char *buf_ptr )); #endif #ifndef yytext_ptr static void yy_flex_strncpy YY_PROTO(( char *, yyconst char *, int )); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen YY_PROTO(( yyconst char * )); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput YY_PROTO(( void )); #else static int input YY_PROTO(( void )); #endif #endif #if YY_STACK_USED static int yy_start_stack_ptr = 0; static int yy_start_stack_depth = 0; static int *yy_start_stack = 0; #ifndef YY_NO_PUSH_STATE static void yy_push_state YY_PROTO(( int new_state )); #endif #ifndef YY_NO_POP_STATE static void yy_pop_state YY_PROTO(( void )); #endif #ifndef YY_NO_TOP_STATE static int yy_top_state YY_PROTO(( void )); #endif #else #define YY_NO_PUSH_STATE 1 #define YY_NO_POP_STATE 1 #define YY_NO_TOP_STATE 1 #endif #ifdef YY_MALLOC_DECL YY_MALLOC_DECL #else #if __STDC__ #ifndef __cplusplus #include <stdlib.h> #endif #else /* Just try to get by without declaring the routines. This will fail * miserably on non-ANSI systems for which sizeof(size_t) != sizeof(int) * or sizeof(void*) != sizeof(int). */ #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #define YY_READ_BUF_SIZE 8192 #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO (void) fwrite( yytext, yyleng, 1, yyout ) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( yy_current_buffer->yy_is_interactive ) \ { \ int c = '*', n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ } #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL int yylex YY_PROTO(( void )) #endif /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ if ( yyleng > 0 ) \ yy_current_buffer->yy_at_bol = \ (yytext[yyleng - 1] == '\n'); \ YY_USER_ACTION YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; #line 261 "vs1.0_tokens.l" #line 1161 "_vs1.0_lexer.cpp" if ( yy_init ) { yy_init = 0; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yy_start ) yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! yy_current_buffer ) yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); yy_load_buffer_state(); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = yy_c_buf_p; /* Support of yytext. */ *yy_cp = yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yy_start; yy_current_state += YY_AT_BOL(); yy_state_ptr = yy_state_buf; *yy_state_ptr++ = yy_current_state; yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 329 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; *yy_state_ptr++ = yy_current_state; ++yy_cp; } while ( yy_base[yy_current_state] != 767 ); yy_find_action: yy_current_state = *--yy_state_ptr; yy_lp = yy_accept[yy_current_state]; find_rule: /* we branch to this label when backing up */ for ( ; ; ) /* until we find what rule we matched */ { if ( yy_lp && yy_lp < yy_accept[yy_current_state + 1] ) { yy_act = yy_acclist[yy_lp]; { yy_full_match = yy_cp; break; } } --yy_cp; yy_current_state = *--yy_state_ptr; yy_lp = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 1: YY_RULE_SETUP #line 263 "vs1.0_tokens.l" { gbProcessingDefine = false; gSaveLine[0] = '\0'; strncat(gSaveLine, yytext, MAXSAVELINE); // GenDebugLine(); if (gbProcessingIFDEF && (gbCompareDefine != gbIFDEF)) { BEGIN(IFDEFBODY); } else { BEGIN(INITIAL); } yyless(0); } YY_BREAK case 2: YY_RULE_SETUP #line 279 "vs1.0_tokens.l" { gbProcessingDefine = false; gSaveLine[0] = '\0'; strncat(gSaveLine, yytext, MAXSAVELINE); // GenDebugLine(); if (gbProcessingIFDEF && (gbCompareDefine != gbIFDEF)) { BEGIN(IFDEFBODY); } else { BEGIN(INITIAL); } yyless(0); } YY_BREAK case 3: YY_RULE_SETUP #line 295 "vs1.0_tokens.l" { // fprintf( stderr, "%s", yytext ); vs10_lval.reg.type = TYPE_ADDRESS_REG; vs10_lval.reg.index = atoi(&yytext[1]); if ( yytext[yyleng-1] == '\n' ) line_incr = 1; return REGISTER; } YY_BREAK case 4: YY_RULE_SETUP #line 304 "vs1.0_tokens.l" { // fprintf( stderr, "%s", yytext ); vs10_lval.reg.type = TYPE_VERTEX_ATTRIB_REG; vs10_lval.reg.index = atoi(&yytext[1]); if ( yytext[yyleng-1] == '\n' ) line_incr = 1; return REGISTER; } YY_BREAK case 5: YY_RULE_SETUP #line 313 "vs1.0_tokens.l" { // fprintf( stderr, "%s", yytext ); vs10_lval.reg.type = TYPE_TEMPORARY_REG; vs10_lval.reg.index = atoi(&yytext[1]); if ( yytext[yyleng-1] == '\n' ) line_incr = 1; return REGISTER; } YY_BREAK case 6: YY_RULE_SETUP #line 322 "vs1.0_tokens.l" { // fprintf( stderr, "%s", yytext ); vs10_lval.reg.type = TYPE_CONSTANT_MEM_REG; vs10_lval.reg.index = atoi(&yytext[1]); if ( yytext[yyleng-1] == '\n' ) line_incr = 1; return REGISTER; } YY_BREAK case 7: YY_RULE_SETUP #line 331 "vs1.0_tokens.l" { // fprintf( stderr, "%s", yytext ); vs10_lval.reg.type = TYPE_TEXTURE_RESULT_REG; vs10_lval.reg.index = atoi(&yytext[2]); if ( yytext[yyleng-1] == '\n' ) line_incr = 1; return REGISTER; } YY_BREAK case 8: YY_RULE_SETUP #line 340 "vs1.0_tokens.l" { // fprintf( stderr, "%s", yytext ); vs10_lval.reg.type = TYPE_COLOR_RESULT_REG; vs10_lval.reg.index = atoi(&yytext[2]); if ( yytext[yyleng-1] == '\n' ) line_incr = 1; return REGISTER; } YY_BREAK case 9: YY_RULE_SETUP #line 349 "vs1.0_tokens.l" { // fprintf( stderr, "%s", yytext ); vs10_lval.reg.type = TYPE_FOG_RESULT_REG; if ( yytext[yyleng-1] == '\n' ) line_incr = 1; return REGISTER; } YY_BREAK case 10: YY_RULE_SETUP #line 357 "vs1.0_tokens.l" { // fprintf( stderr, "%s", yytext ); vs10_lval.reg.type = TYPE_POSITION_RESULT_REG; if ( yytext[yyleng-1] == '\n' ) line_incr = 1; return REGISTER; } YY_BREAK case 11: YY_RULE_SETUP #line 365 "vs1.0_tokens.l" { // fprintf( stderr, "%s", yytext ); vs10_lval.reg.type = TYPE_POINTS_RESULT_REG; if ( yytext[yyleng-1] == '\n' ) line_incr = 1; return REGISTER; } YY_BREAK case 12: YY_RULE_SETUP #line 373 "vs1.0_tokens.l" { unsigned int offset; offset = strcspn(yytext, " \t\n_"); yyless(offset); OPCODEMAP *opcodeMap = FindOpcode(yytext); if ( opcodeMap != NULL ) { // fprintf( stderr, "%s\t", opcodeMap->string ); return( opcodeMap->tokenName ); } else { gTempParseMacro = FindMacro(yytext); if (gTempParseMacro != NULL) { if (gIncludeStackIndex >= MAX_INCLUDE_DEPTH ) { LexError("macros nested too deeply"); exit( 1 ); } if (gTempParseMacro->firstMacroLines != NULL) { gTempMacro = (MACROENTRY *)malloc(sizeof(MACROENTRY)); if (gTempMacro == NULL) { LexError("Out of memory allocating MACROENTRY structure.\n"); } else { gTempMacro->next = NULL; gTempMacro->prev = NULL; gTempMacro->macroName = NULL; gTempMacro->firstMacroParms = NULL; gTempMacro->lastMacroParms = NULL; gTempMacro->firstMacroLines = NULL; gTempMacro->lastMacroLines = NULL; gTempMacro->numParms = 0; gTempMacro->nLines = 0; gbTempInsideMacro = true; // flag we are currently doing a macro replace. gInvokeState = YYSTATE; if (gTempParseMacro->numParms > 0) { BEGIN(MACROPARMSTART); } else { EndMacroParms(); gbTempInsideMacro = false; // no longer waiting for macro invocation } } } } else { // fprintf( stderr, "Opcode: \"%s\" not found\n", yytext ); REJECT; } } //unsigned int offset; // //INSTRMAP *opcodeMap; // //offset = strcspn(yytext, " \t\n_"); //yyless(offset); //opcodeMap = FindInstruction(yytext); //if (opcodeMap == NULL) //{ // REJECT; //} // //yylval.opcodeInfo.opcodeMap = opcodeMap; // //return OPCODE; } YY_BREAK case 13: YY_RULE_SETUP #line 460 "vs1.0_tokens.l" { // fprintf( stderr, "%s", yytext ); char *cmt = new char[yyleng+1]; strncpy( cmt, yytext, yyleng ); cmt[0] = '#'; cmt[yyleng] = '\0'; vs10_lval.comment = cmt; return COMMENT; } YY_BREAK case 14: YY_RULE_SETUP #line 470 "vs1.0_tokens.l" { // fprintf( stderr, "%s", yytext ); char *cmt = new char[yyleng+1]; strncpy( cmt+1, yytext+1, yyleng-1 ); cmt[0] = '#'; cmt[1] = ' '; cmt[yyleng] = '\0'; vs10_lval.comment = cmt; return COMMENT; } YY_BREAK case 15: YY_RULE_SETUP #line 481 "vs1.0_tokens.l" { fprintf( stderr, "COISSUE found\n" ); yyless(yyleng-1); //return COISSUE; } YY_BREAK case 16: YY_RULE_SETUP #line 487 "vs1.0_tokens.l" { fprintf( stderr, "COISSUE found\n" ); //return COISSUE; } YY_BREAK case 17: YY_RULE_SETUP #line 492 "vs1.0_tokens.l" { gCommentStartLine = yylineno; yyless(0); BEGIN(EATCOMMENT); } YY_BREAK case 18: YY_RULE_SETUP #line 498 "vs1.0_tokens.l" { BEGIN(INCLUDE); } YY_BREAK case 19: YY_RULE_SETUP #line 502 "vs1.0_tokens.l" { /* got the include file name */ // FILE *newyyin; char *newyyin; char incFileName[1024]; unsigned long sLen; bool validFileName; if ( gIncludeStackIndex >= MAX_INCLUDE_DEPTH ) { LexError("Includes nested too deeply, aborting\n"); exit( 1 ); } // GenDebugLine(); // GenListString(); yylineno++; gLinesAssembled++; validFileName = true; // zap "" and <> if ((yytext[0] == '"') || (yytext[0] == '<')) { char *endQuote; endQuote = strchr(&yytext[1], yytext[0]); sLen = (endQuote - yytext)-1; if (endQuote == NULL) { LexError("Unable to open include file %s\n", incFileName); BEGIN(INITIAL); validFileName = false; } else { incFileName[0] ='\0'; strncat(incFileName, &yytext[1], sLen); } } else { strcpy(incFileName, yytext); } if (validFileName) { sLen = strlen(incFileName); if ((incFileName[sLen-1] == '"') || (incFileName[sLen-1] == '>')) { incFileName[sLen-1] = '\0'; } newyyin = ReadTextFile( incFileName ); // newyyin = fopen( incFileName, "r" ); if ( ! newyyin ) { LexError("Unable to open include file %s\n", incFileName); BEGIN(SAVELINE); } else { gIncludeStack[gIncludeStackIndex].fileName = gCurFileName; gIncludeStack[gIncludeStackIndex].lineNo = yylineno; // gIncludeStack[gIncludeStackIndex].fileHandle = yyin; gIncludeStack[gIncludeStackIndex].prevString = myin; gIncludeStack[gIncludeStackIndex].nextString = newyyin; gIncludeStack[gIncludeStackIndex].lastInvokeMacro = gInvokeMacro; gIncludeStack[gIncludeStackIndex].lastParseMacro = gParseMacro; gIncludeStack[gIncludeStackIndex].lastMacroLineParse = gMacroLineParse; gIncludeStack[gIncludeStackIndex].lastbInsideMacro = gbInsideMacro; gIncludeStack[gIncludeStackIndex].lastbInsideInclude = gbInsideInclude; gIncludeStack[gIncludeStackIndex].buffer = YY_CURRENT_BUFFER; gIncludeStack[gIncludeStackIndex].lastbProcessingIFDEF = gbProcessingIFDEF; gIncludeStackIndex++; gbProcessingIFDEF = false; gCurFileName = strdup(incFileName); // yyin = newyyin; myin = newyyin; // GenSwitchFileNames(gCurFileName); yylineno = 1; yy_switch_to_buffer(yy_create_buffer( yyin, YY_BUF_SIZE ) ); gbInsideInclude = true; BEGIN(SAVELINE); } } } YY_BREAK case YY_STATE_EOF(EATCOMMENT): #line 597 "vs1.0_tokens.l" { LexError("End of file reached before end of comment started on line %d.\n", gCommentStartLine); BEGIN(INITIAL); } YY_BREAK case 20: YY_RULE_SETUP #line 602 "vs1.0_tokens.l" { char *endComment; unsigned int keepSize; strcpy(gSaveLine, yytext); endComment = strstr(yytext, "*/"); char *cmt; if (endComment != NULL) { keepSize = (endComment - yytext+2); yyless(keepSize); BEGIN(INITIAL); if ( yytext[0] == '/' && yytext[1] == '*' ) { cmt = new char[yyleng]; strncpy( cmt+3, yytext+2, yyleng-2 ); cmt[0] = '#'; cmt[1] = ' '; cmt[2] = ' '; cmt[yyleng-1] = '\0'; } else { cmt = new char[yyleng]; strncpy( cmt+1, yytext, yyleng-2 ); cmt[0] = '#'; cmt[yyleng-1] = '\0'; } vs10_lval.comment = cmt; return COMMENT; } else { // GenDebugLine(); // GenListString(); gLinesAssembled++; yylineno++; if ( yytext[0] == '/' && yytext[1] == '*' ) { cmt = new char[yyleng+2]; strncpy( cmt+3, yytext+2, yyleng-2 ); cmt[0] = '#'; cmt[1] = ' '; cmt[2] = ' '; cmt[yyleng+1] = '\0'; } else { cmt = new char[yyleng+2]; strncpy( cmt+1, yytext, yyleng ); cmt[0] = '#'; cmt[yyleng+1] = '\0'; } vs10_lval.comment = cmt; return COMMENT; } } YY_BREAK case YY_STATE_EOF(DEFSTR): #line 663 "vs1.0_tokens.l" { LexError("#define was incomplete before end of file\n"); BEGIN(INITIAL); } YY_BREAK case YY_STATE_EOF(DEFINE): #line 668 "vs1.0_tokens.l" { LexError("#define was incomplete before end of file\n"); BEGIN(INITIAL); } YY_BREAK case YY_STATE_EOF(DEFSPACE): #line 673 "vs1.0_tokens.l" { LexError("#define was incomplete before end of file\n"); BEGIN(INITIAL); } YY_BREAK case YY_STATE_EOF(INCLUDE): #line 678 "vs1.0_tokens.l" { LexError("#include was incomplete before end of file\n"); BEGIN(INITIAL); } YY_BREAK case YY_STATE_EOF(MACROBODY): #line 683 "vs1.0_tokens.l" { LexError("End of file reached before end of #define or endm was found, macro started on line %d.\n", gMacroStartLine); BEGIN(INITIAL); } YY_BREAK case YY_STATE_EOF(IFDEFBODY): #line 688 "vs1.0_tokens.l" { LexError("End of file reached before #endif found, macro started on line %d.\n", gIfDefStartLine); BEGIN(INITIAL); } YY_BREAK case 21: YY_RULE_SETUP #line 693 "vs1.0_tokens.l" { LexError("#define was incomplete before end of line\n"); BEGIN(SAVELINE); // GenDebugLine(); // GenListString(); gLinesAssembled++; yylineno++; } YY_BREAK case 22: YY_RULE_SETUP #line 702 "vs1.0_tokens.l" { LexError("#define was incomplete before end of line\n"); BEGIN(SAVELINE); // GenDebugLine(); // GenListString(); gLinesAssembled++; yylineno++; } YY_BREAK case 23: YY_RULE_SETUP #line 711 "vs1.0_tokens.l" { LexError("#define was incomplete before end of line\n"); BEGIN(SAVELINE); // GenDebugLine(); // GenListString(); gLinesAssembled++; yylineno++; } YY_BREAK case 24: YY_RULE_SETUP #line 720 "vs1.0_tokens.l" { if (gIfDefStackIndex >= MAX_IFDEF_DEPTH) { LexError("Out of stack space for #ifdef, aborting.\n"); exit( 1 ); } else { gIfDefStack[gIfDefStackIndex].lastbProcessingIFDEF = gbProcessingIFDEF; gIfDefStack[gIfDefStackIndex].lastbIFDEF = gbIFDEF; gIfDefStack[gIfDefStackIndex].lastbCompareDefine = gbCompareDefine; gIfDefStack[gIfDefStackIndex].lastIfDefStartLine = gIfDefStartLine; gIfDefStackIndex++; gIfDefStartLine = yylineno; gbCompareDefine = true; BEGIN(IFDEFNAME); } } YY_BREAK case 25: YY_RULE_SETUP #line 740 "vs1.0_tokens.l" { if (gIfDefStackIndex >= MAX_IFDEF_DEPTH) { LexError("Out of stack space for #ifdef, aborting.\n"); exit( 1 ); } else { gIfDefStack[gIfDefStackIndex].lastbProcessingIFDEF = gbProcessingIFDEF; gIfDefStack[gIfDefStackIndex].lastbIFDEF = gbIFDEF; gIfDefStack[gIfDefStackIndex].lastbCompareDefine = gbCompareDefine; gIfDefStack[gIfDefStackIndex].lastIfDefStartLine = gIfDefStartLine; gIfDefStackIndex++; gIfDefStartLine = yylineno; gbCompareDefine = false; BEGIN(IFDEFNAME); } } YY_BREAK case 26: YY_RULE_SETUP #line 760 "vs1.0_tokens.l" { if (!gbProcessingIFDEF) { LexError("Unexpected #else found at line %d, skipping.\n", yylineno); } else { gbCompareDefine = !gbCompareDefine; BEGIN(INITIAL); } } YY_BREAK case 27: YY_RULE_SETUP #line 772 "vs1.0_tokens.l" { char *defineName; unsigned int sLen; defineName = FindAlphaNum(yytext, &sLen); if (defineName == NULL) { defineName = strdup(yytext); defineName[yyleng-1] = '\0'; // kill \n LexWarning("Mangled name (%s) for #ifdef, assuming not defined.\n", defineName); free(defineName); gbIFDEF = false; } else { if (FindNMacro(defineName, sLen) != NULL) { gbIFDEF = true; } else { gbIFDEF = false; } } gbProcessingIFDEF = true; if (gbIFDEF != gbCompareDefine) { BEGIN(IFDEFBODY); } else { BEGIN(SAVELINE); } // GenDebugLine(); // GenListString(); gLinesAssembled++; yylineno++; } YY_BREAK case 28: YY_RULE_SETUP #line 814 "vs1.0_tokens.l" { if (!gbProcessingIFDEF) { LexError("Unexpected #endif found at line %d, skipping.\n", yylineno); } else { gIfDefStackIndex--; gbProcessingIFDEF = gIfDefStack[gIfDefStackIndex].lastbProcessingIFDEF; gbIFDEF = gIfDefStack[gIfDefStackIndex].lastbIFDEF; gbCompareDefine = gIfDefStack[gIfDefStackIndex].lastbCompareDefine; gIfDefStartLine = gIfDefStack[gIfDefStackIndex].lastIfDefStartLine; } if (YYSTATE == IFDEFBODY) { strncpy(gSaveLine, yytext, MAXSAVELINE); } BEGIN(ENDMACRO); } YY_BREAK case 29: YY_RULE_SETUP #line 838 "vs1.0_tokens.l" { LexWarning("Garbage at end of #endif or endm will be ignored.\n"); } YY_BREAK case 30: YY_RULE_SETUP #line 842 "vs1.0_tokens.l" { BEGIN(SAVELINE); return '\n'; } YY_BREAK case YY_STATE_EOF(ENDMACRO): #line 847 "vs1.0_tokens.l" { BEGIN(INITIAL); } YY_BREAK case 31: YY_RULE_SETUP #line 851 "vs1.0_tokens.l" { // eat line, because we are not in a TRUE #ifdef, or FALSE #ifndef strncpy(gSaveLine, yytext, MAXSAVELINE); } YY_BREAK case 32: YY_RULE_SETUP #line 856 "vs1.0_tokens.l" { strcat(gSaveLine, yytext); // GenDebugLine(); // GenListString(); yylineno++; gLinesAssembled++; } YY_BREAK case 33: YY_RULE_SETUP #line 864 "vs1.0_tokens.l" { gbProcessingDefine = true; gMacroStartLine = yylineno; gCountParen = 0; BEGIN(MACRONAME); } YY_BREAK case 34: YY_RULE_SETUP #line 871 "vs1.0_tokens.l" { BEGIN(SAVELINE); // GenDebugLine(); // GenListString(); gLinesAssembled++; yylineno++; } YY_BREAK case 35: YY_RULE_SETUP #line 879 "vs1.0_tokens.l" { // unsigned int majorVersion; // unsigned int minorVersion; // int minorOffset; // // // majorVersion = (unsigned int)(atoi(&yytext[3])); // // skip "ps." + second '.' // minorOffset = strcspn(&yytext[3], ".")+4; // minorVersion = (unsigned int)(atoi(&yytext[minorOffset])); // yylval.ival = D3DVS_VERSION(majorVersion, minorVersion); // // fprintf( stderr, "%s", yytext ); if ( yytext[yyleng-1] == '\n' ) line_incr = 1; return VERTEX_SHADER; } YY_BREAK case 36: YY_RULE_SETUP #line 898 "vs1.0_tokens.l" { // fprintf( stderr, "%s", yytext ); vs10_lval.ival = atoi(yytext); return INTVAL; } YY_BREAK case 37: YY_RULE_SETUP #line 905 "vs1.0_tokens.l" { BEGIN(MODIFIER); //fprintf( stderr, "." ); return yytext[0]; } YY_BREAK case 38: YY_RULE_SETUP #line 911 "vs1.0_tokens.l" { // fprintf( stderr, "%s", yytext ); BEGIN(INITIAL); vs10_lval.mask[0] = tolower(yytext[0]); vs10_lval.mask[1] = tolower(yytext[1]); vs10_lval.mask[2] = tolower(yytext[2]); vs10_lval.mask[3] = tolower(yytext[3]); if ( yytext[yyleng-1] == '\n' ) line_incr = 1; return XYZW_MODIFIER; #if 0 char temp[6]; temp[0] = '\0'; strncat(temp, yytext, 4); strlwr(temp); vs10_lval.lval = FindSwizzleValue(temp); BEGIN(INITIAL); return SWIZZLE_MODIFIER; #endif } YY_BREAK case 39: YY_RULE_SETUP #line 939 "vs1.0_tokens.l" { // fprintf( stderr, "%s", yytext ); BEGIN(INITIAL); int validLen = strspn(yytext, "xyzw"); int i; for ( i = 0; i < validLen; i++ ) vs10_lval.mask[i] = tolower( yytext[i] ); while ( i < 4 ) { vs10_lval.mask[i] = 0; i++; } if ( yytext[yyleng-1] == '\n' ) line_incr = 1; return XYZW_MODIFIER; #if 0 //char temp[6]; char *temp = new char[6]; unsigned int registerMask; unsigned int validLen; temp[0] = '\0'; validLen = strspn(yytext, "xyzw"); strncat(temp, yytext, validLen); for ( int i = 0; i < validLen; i++ ) temp[i] = tolower( temp[i] ); registerMask = MakeRegisterMask(temp); if (registerMask != 0) { //vs10_lval.sval = temp; vs10_lval.lval = registerMask; BEGIN(INITIAL); return XYZW_MODIFIER; } else { //vs10_lval.sval = temp; vs10_lval.lval = FindSwizzleValue(temp); BEGIN(INITIAL); return SWIZZLE_MODIFIER; } #endif } YY_BREAK case 40: YY_RULE_SETUP #line 988 "vs1.0_tokens.l" { BEGIN(INITIAL); yyless(0); } YY_BREAK case 41: YY_RULE_SETUP #line 993 "vs1.0_tokens.l" { /* setup and save off #define/macro name */ if (FindMacro(yytext) != NULL) { LexWarning("Redefinition of #define/macro %s, ignoring.\n", yytext); if (gbProcessingDefine) { BEGIN(EATDEFINE); } else { BEGIN(EATMACRO); } } else { BEGIN(MACROPARMSTART); // %%%%% This should be setup to use memory pools gTempMacro = (MACROENTRY *)malloc(sizeof(MACROENTRY)); if (gTempMacro == NULL) { LexError("Out of memory for macro table.\n"); if (gbProcessingDefine) { BEGIN(EATDEFINE); } else { BEGIN(EATMACRO); } } else { gTempMacro->prev = gLastMacro; gTempMacro->next = NULL; gTempMacro->firstMacroParms = NULL; gTempMacro->lastMacroParms = NULL; gTempMacro->firstMacroLines = NULL; gTempMacro->lastMacroLines = NULL; gTempMacro->numParms = 0; gTempMacro->bIsDefine = gbProcessingDefine; gTempMacro->nLines = 0; if (gCurFileName != NULL) { gTempMacro->fileName = strdup(gCurFileName); } else { gTempMacro->fileName = NULL; } gTempMacro->lineNo = yylineno; /* %%%%% this should be set up in memory pools. */ gTempMacro->macroName = (char *)malloc(strlen(yytext)+1); if (gTempMacro->macroName == NULL) { LexError("Out of memory for string table.\n"); SAFEFREE(gTempMacro); if (gbProcessingDefine) { BEGIN(EATDEFINE); } else { BEGIN(EATMACRO); } } else { strcpy(gTempMacro->macroName, yytext); } } } } YY_BREAK case 42: YY_RULE_SETUP #line 1072 "vs1.0_tokens.l" { LexError("No macro name specified, skipping macro definition.\n"); SAFEFREE(gTempMacro->fileName); SAFEFREE(gTempMacro); if (gbProcessingDefine) { BEGIN(EATDEFINE); } else { BEGIN(EATMACRO); } // GenDebugLine(); // GenListString(); gLinesAssembled++; yylineno++; } YY_BREAK case 43: YY_RULE_SETUP #line 1091 "vs1.0_tokens.l" { gCountParen++; } YY_BREAK case 44: YY_RULE_SETUP #line 1095 "vs1.0_tokens.l" {} YY_BREAK case 45: YY_RULE_SETUP #line 1097 "vs1.0_tokens.l" { if (gbProcessingDefine && (gCountParen == 0)) { EndMacroParms(); } else { BEGIN(MACROPARM); } yyless(0); } YY_BREAK case 46: YY_RULE_SETUP #line 1109 "vs1.0_tokens.l" { if ((gCountParen == 0) && gbProcessingDefine) { EndMacroParms(); } } YY_BREAK case 47: YY_RULE_SETUP #line 1116 "vs1.0_tokens.l" { if (gCountParen == 0) { EndMacroParms(); } } YY_BREAK case 48: YY_RULE_SETUP #line 1123 "vs1.0_tokens.l" {} YY_BREAK case YY_STATE_EOF(MACROPARM): #line 1125 "vs1.0_tokens.l" { EndMacroParms(); // GenDebugLine(); // GenListString(); yylineno++; gLinesAssembled++; BEGIN(INITIAL); } YY_BREAK case 49: YY_RULE_SETUP #line 1134 "vs1.0_tokens.l" { if (gbProcessingDefine && (gCountParen > 0)) { LexError("Malformed #define, skipping.\n"); BEGIN(SAVELINE); } else { EndMacroParms(); // GenDebugLine(); // GenListString(); yylineno++; gLinesAssembled++; if (gbProcessingDefine) { gbProcessingDefine = false; BEGIN(SAVELINE); } } } YY_BREAK case 50: YY_RULE_SETUP #line 1156 "vs1.0_tokens.l" { MACROTEXT *tMacro; char *macroParmEnd; unsigned int startOffset; unsigned int leftParenCount; unsigned int rightParenCount; // sheesh, we gotta count the parenthesis.... macroParmEnd = yytext; leftParenCount = 0; rightParenCount = 0; while (*macroParmEnd) { if (*macroParmEnd == ')') { rightParenCount++; } if (*macroParmEnd == '(') { leftParenCount++; } macroParmEnd++; } // if we found the last right parenthesis. if (rightParenCount == leftParenCount+1) { // find if we got the last parenthesis on this line macroParmEnd = strrchr(yytext, ')'); yyless((macroParmEnd - yytext)); BEGIN(MACROPARMEND); } startOffset = strspn(yytext, " \t"); tMacro = SaveMacroText(&yytext[startOffset], gTempMacro->lastMacroParms); if (tMacro == NULL) { LexError("Out of memory for string table for macro parameter(s).\n"); FreeMacroEntry(gTempMacro); BEGIN(EATMACRO); } else { // if first one wasn't set then set it if (gTempMacro->firstMacroParms == NULL) { gTempMacro->firstMacroParms = tMacro; } gTempMacro->lastMacroParms = tMacro; gTempMacro->numParms++; } } YY_BREAK case 51: YY_RULE_SETUP #line 1215 "vs1.0_tokens.l" { if (!gbProcessingDefine && !gbTempInsideMacro) { LexError("Malformed macro, skipping.\n"); BEGIN(EATMACRO); } else { gCountParen--; // we can get multiple \n's here while (yytext[yyleng-2] == '\n') { yyleng--; } yyless(yyleng); // if there isn't a \n on this line, macro starts on this line, // not next, like in a macro definition if (yytext[yyleng-1] != '\n') { EndMacroParms(); } else { if (yytext[yyleng-1] == '\n') { gTempMacro->lineNo++; } // count this line gTempMacro->nLines++; // GenDebugLine(); // GenListString(); EndMacroParms(); if (!gbInsideMacro) { yylineno++; } gLinesAssembled++; } } } YY_BREAK case 52: YY_RULE_SETUP #line 1260 "vs1.0_tokens.l" { if (!gbProcessingDefine && !gbTempInsideMacro) { LexError("Malformed macro, skipping.\n"); BEGIN(EATMACRO); } else { // no matter what count this line gTempMacro->nLines++; gCountParen--; EndMacroParms(); if (!gbInsideMacro) { yylineno++; } gLinesAssembled++; } } YY_BREAK case 53: YY_RULE_SETUP #line 1282 "vs1.0_tokens.l" { if (!gbProcessingDefine && !gbTempInsideMacro) { LexError("Malformed macro, skipping.\n"); BEGIN(EATMACRO); } else { gCountParen--; if (gCountParen == 0) { // no matter what count this line gTempMacro->nLines++; EndMacroParms(); if (!gbInsideMacro) { yylineno++; } gLinesAssembled++; } else { REJECT; } } } YY_BREAK case 54: YY_RULE_SETUP #line 1310 "vs1.0_tokens.l" { MACROTEXT *tMacro; unsigned int copyLen; char *endLine; gSaveLine[0] ='\0'; endLine = strchr(yytext, '\\'); copyLen = (endLine - yytext); if (copyLen > MAXSAVELINE) { copyLen = MAXSAVELINE; } strncat(gSaveLine, yytext, copyLen); strcat(gSaveLine, "\n"); tMacro = SaveMacroText(gSaveLine, gLastMacro->lastMacroLines); if (tMacro == NULL) { LexError("Out of memory for string table for macro parameter(s).\n"); BEGIN(EATDEFINE); } else { gLastMacro->nLines++; // if first one wasn't set then set it if (gLastMacro->firstMacroLines == NULL) { gLastMacro->firstMacroLines = tMacro; } gLastMacro->lastMacroLines = tMacro; } // GenDebugLine(); // GenListString(); yylineno++; gLinesAssembled++; } YY_BREAK case 55: YY_RULE_SETUP #line 1349 "vs1.0_tokens.l" { strncpy(gSaveLine, yytext, MAXSAVELINE); if (gbProcessingDefine) { LexError("Malformed #define, skipping.\n"); } BEGIN(ENDMACRO); } YY_BREAK case 56: YY_RULE_SETUP #line 1360 "vs1.0_tokens.l" { MACROTEXT *tMacro; // check if processing #define and only one line, if not then append \n if (!gbProcessingDefine || (gLastMacro->nLines >= 1)) { gSaveLine[0] = '\0'; strncat(gSaveLine, yytext, MAXSAVELINE); strcat(gSaveLine, "\n"); tMacro = SaveMacroText(gSaveLine, gLastMacro->lastMacroLines); gLastMacro->nLines++; } else if (gLastMacro->numParms > 0) // check if parameters were there { // if so, we need the '\n' appended gMacroLine[0] = '\0'; strncat(gMacroLine, yytext, MAXSAVELINE); strcat(gMacroLine, "\n"); tMacro = SaveMacroText(gMacroLine, gLastMacro->lastMacroLines); gLastMacro->nLines++; } else // straight no newline macro replace { tMacro = SaveMacroText(yytext, gLastMacro->lastMacroLines); } if (tMacro == NULL) { LexError("Out of memory for string table for macro parameter(s).\n"); BEGIN(EATMACRO); } else { // if first one wasn't set then set it if (gLastMacro->firstMacroLines == NULL) { gLastMacro->firstMacroLines = tMacro; } gLastMacro->lastMacroLines = tMacro; } } YY_BREAK case 57: YY_RULE_SETUP #line 1403 "vs1.0_tokens.l" { MACROTEXT *tMacro; // GenDebugLine(); // GenListString(); yylineno++; gLinesAssembled++; if (gbProcessingDefine) { gbProcessingDefine = false; BEGIN(SAVELINE); } else { // this means \n by itself inside macro body if (((yylineno-1) - gLastMacro->lineNo) != gLastMacro->nLines) { strcpy(gMacroLine, "\n"); tMacro = SaveMacroText(gMacroLine, gLastMacro->lastMacroLines); gLastMacro->nLines++; if (tMacro == NULL) { LexError("Out of memory for string table for macro parameter(s).\n"); BEGIN(EATMACRO); } else { // if first one wasn't set then set it if (gLastMacro->firstMacroLines == NULL) { gLastMacro->firstMacroLines = tMacro; } gLastMacro->lastMacroLines = tMacro; } } } } YY_BREAK case 58: YY_RULE_SETUP #line 1443 "vs1.0_tokens.l" { BEGIN(SAVELINE); // GenDebugLine(); // GenListString(); gLinesAssembled++; yylineno++; } YY_BREAK case 59: YY_RULE_SETUP #line 1451 "vs1.0_tokens.l" { strncpy(gSaveLine, yytext, MAXSAVELINE); // GenDebugLine(); // GenListString(); gLinesAssembled++; yylineno++; } YY_BREAK case 60: YY_RULE_SETUP #line 1459 "vs1.0_tokens.l" { strncpy(gSaveLine, yytext, MAXSAVELINE); // GenDebugLine(); // GenListString(); gLinesAssembled++; yylineno++; } YY_BREAK case 61: YY_RULE_SETUP #line 1467 "vs1.0_tokens.l" { strncpy(gSaveLine, yytext, MAXSAVELINE); // GenDebugLine(); // GenListString(); gLinesAssembled++; yylineno++; BEGIN(SAVELINE); } YY_BREAK case 62: YY_RULE_SETUP #line 1476 "vs1.0_tokens.l" { gTempParseMacro = FindMacro(yytext); if (gTempParseMacro != NULL) { if (gIncludeStackIndex >= MAX_INCLUDE_DEPTH ) { LexError("macros nested too deeply"); exit( 1 ); } if (gTempParseMacro->firstMacroLines != NULL) { gTempMacro = (MACROENTRY *)malloc(sizeof(MACROENTRY)); if (gTempMacro == NULL) { LexError("Out of memory allocating MACROENTRY structure.\n"); } else { gTempMacro->next = NULL; gTempMacro->prev = NULL; gTempMacro->macroName = NULL; gTempMacro->firstMacroParms = NULL; gTempMacro->lastMacroParms = NULL; gTempMacro->firstMacroLines = NULL; gTempMacro->lastMacroLines = NULL; gTempMacro->numParms = 0; gTempMacro->nLines = 0; gbTempInsideMacro = true; // flag we are currently doing a macro replace. gInvokeState = YYSTATE; if (gTempParseMacro->numParms > 0) { BEGIN(MACROPARMSTART); } else { EndMacroParms(); gbTempInsideMacro = false; // no longer waiting for macro invocation } } } } else { BEGIN(INITIAL); REJECT; } } YY_BREAK case 63: YY_RULE_SETUP #line 1530 "vs1.0_tokens.l" { // fprintf( stderr, "%c ", yytext[0] ); return yytext[0]; } YY_BREAK case 64: YY_RULE_SETUP #line 1536 "vs1.0_tokens.l" {} YY_BREAK case 65: YY_RULE_SETUP #line 1538 "vs1.0_tokens.l" { LexError("Didn't find label string for #define.\n"); BEGIN(SAVELINE); // return '\n'; } YY_BREAK case 66: YY_RULE_SETUP #line 1544 "vs1.0_tokens.l" { //fprintf(stderr, "\n"); // line_incr = 1; line_incr++; BEGIN(SAVELINE); return '\n'; } YY_BREAK case 67: YY_RULE_SETUP #line 1552 "vs1.0_tokens.l" { BEGIN(INITIAL); // fprintf( stderr, "%s", yytext ); if (yyleng == 1) return yytext[0]; else LexError("Unrecognized Token: %s\n", yytext); return UNKNOWN_STRING; } YY_BREAK case 68: YY_RULE_SETUP #line 1562 "vs1.0_tokens.l" { // vs10_lval.ival = yytext[0]; LexError("Illegal character: %d decimal.\n", yytext[0]); return(ILLEGAL); } YY_BREAK case 69: YY_RULE_SETUP #line 1568 "vs1.0_tokens.l" { // vs10_lval.ival = yytext[0]; LexError("Illegal character: %d decimal.\n", yytext[0]); return(ILLEGAL); } YY_BREAK case 70: YY_RULE_SETUP #line 1574 "vs1.0_tokens.l" { return yytext[0]; } YY_BREAK case 71: YY_RULE_SETUP #line 1578 "vs1.0_tokens.l" { BEGIN(EATSTRING); yyless(0); } YY_BREAK case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(SKIPLINE): case YY_STATE_EOF(EATSTRING): case YY_STATE_EOF(SAVELINE): case YY_STATE_EOF(MACRONAME): case YY_STATE_EOF(EATMACRO): case YY_STATE_EOF(EATDEFINE): case YY_STATE_EOF(MODIFIER): case YY_STATE_EOF(MACROPARMSTART): case YY_STATE_EOF(IFDEFNAME): case YY_STATE_EOF(MACROPARMEND): #line 1583 "vs1.0_tokens.l" { bool wasInMacro; bool oneLiner; char *macroText; wasInMacro = gbInsideMacro; oneLiner = false; // if we are inside the macro then do next line until their are no more if (gbInsideMacro) { oneLiner = (gParseMacro->nLines == 0); // free the temporary parameter replaced line we were working on. // get next line in macro text, if any gMacroLineParse = gMacroLineParse->next; // more lines to parse? if (gMacroLineParse != NULL) { macroText = gMacroLine; // if no replacement text, just use source line if (gParseMacro->firstMacroParms == NULL) { macroText = gMacroLineParse->macroText; } else { // replace the macro parameters ReplaceMacroParms(gMacroLineParse->macroText, gMacroLine, gParseMacro, gInvokeMacro); } // if (gExpandMacros) // { // strcpy(gSaveLine, macroText); // } BEGIN(INITIAL); // and lex it. yy_scan_string(macroText); } else { // no more lines in this macro, so free the working macro SAFEFREE(gInvokeMacro); // shut off flag for inside a macro replacement state. gbInsideMacro = false; } } if (gbProcessingIFDEF && !wasInMacro) { LexError("End of file reached before #endif found, macro started on line %d.\n", gIfDefStartLine); } if (!gbInsideMacro) { if ( gIncludeStackIndex == 0 ) { if (!gbProcessingBuiltIn) CleanUp(); return 0; // return TOKEN_EOF; } else { yy_delete_buffer( YY_CURRENT_BUFFER ); SAFEFREE(gCurFileName); // SAFEDELETE(myin); // SAFECLOSE(yyin); } gIncludeStackIndex--; SAFEDELETEARRAY( gIncludeStack[gIncludeStackIndex].nextString ); yy_switch_to_buffer(gIncludeStack[gIncludeStackIndex].buffer ); gCurFileName = gIncludeStack[gIncludeStackIndex].fileName; // yyin = gIncludeStack[gIncludeStackIndex].fileHandle; myin = gIncludeStack[gIncludeStackIndex].prevString; yylineno = gIncludeStack[gIncludeStackIndex].lineNo; gInvokeMacro = gIncludeStack[gIncludeStackIndex].lastInvokeMacro; gParseMacro = gIncludeStack[gIncludeStackIndex].lastParseMacro; gMacroLineParse = gIncludeStack[gIncludeStackIndex].lastMacroLineParse; gbInsideInclude = gIncludeStack[gIncludeStackIndex].lastbInsideInclude; gbInsideMacro = gIncludeStack[gIncludeStackIndex].lastbInsideMacro; gbProcessingIFDEF = gIncludeStack[gIncludeStackIndex].lastbProcessingIFDEF; if (!gbInsideMacro && !oneLiner) { // GenSwitchFileNames(gCurFileName); BEGIN(SAVELINE); } else { BEGIN(INITIAL); } // gSaveLine was last line saved, before macro invocation if (wasInMacro && !gbInsideMacro && !oneLiner) { // GenDebugLine(); // GenListString(); gLinesAssembled++; yylineno++; } } } YY_BREAK case 72: YY_RULE_SETUP #line 1692 "vs1.0_tokens.l" ECHO; YY_BREAK #line 2919 "_vs1.0_lexer.cpp" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between yy_current_buffer and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yy_n_chars = yy_current_buffer->yy_n_chars; yy_current_buffer->yy_input_file = yyin; yy_current_buffer->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yy_c_buf_p <= &yy_current_buffer->yy_ch_buf[yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yy_c_buf_p = yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state(); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yy_c_buf_p; goto yy_find_action; } } else switch ( yy_get_next_buffer() ) { case EOB_ACT_END_OF_FILE: { yy_did_buffer_switch_on_eof = 0; if ( yywrap() ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yy_c_buf_p = yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yy_c_buf_p = yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state(); yy_cp = yy_c_buf_p; yy_bp = yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yy_c_buf_p = &yy_current_buffer->yy_ch_buf[yy_n_chars]; yy_current_state = yy_get_previous_state(); yy_cp = yy_c_buf_p; yy_bp = yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer() { register char *dest = yy_current_buffer->yy_ch_buf; register char *source = yytext_ptr; register int number_to_move, i; int ret_val; if ( yy_c_buf_p > &yy_current_buffer->yy_ch_buf[yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( yy_current_buffer->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yy_c_buf_p - yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) (yy_c_buf_p - yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ yy_current_buffer->yy_n_chars = yy_n_chars = 0; else { int num_to_read = yy_current_buffer->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ #ifdef YY_USES_REJECT YY_FATAL_ERROR( "input buffer overflow, can't enlarge buffer because scanner uses REJECT" ); #else /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = yy_current_buffer; int yy_c_buf_p_offset = (int) (yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yy_flex_realloc( (void *) b->yy_ch_buf, b->yy_buf_size + 2 ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = yy_current_buffer->yy_buf_size - number_to_move - 1; #endif } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&yy_current_buffer->yy_ch_buf[number_to_move]), yy_n_chars, num_to_read ); yy_current_buffer->yy_n_chars = yy_n_chars; } if ( yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart( yyin ); } else { ret_val = EOB_ACT_LAST_MATCH; yy_current_buffer->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; yy_n_chars += number_to_move; yy_current_buffer->yy_ch_buf[yy_n_chars] = YY_END_OF_BUFFER_CHAR; yy_current_buffer->yy_ch_buf[yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yytext_ptr = &yy_current_buffer->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state() { register yy_state_type yy_current_state; register char *yy_cp; yy_current_state = yy_start; yy_current_state += YY_AT_BOL(); yy_state_ptr = yy_state_buf; *yy_state_ptr++ = yy_current_state; for ( yy_cp = yytext_ptr + YY_MORE_ADJ; yy_cp < yy_c_buf_p; ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 4); while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 329 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; *yy_state_ptr++ = yy_current_state; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ #ifdef YY_USE_PROTOS static yy_state_type yy_try_NUL_trans( yy_state_type yy_current_state ) #else static yy_state_type yy_try_NUL_trans( yy_current_state ) yy_state_type yy_current_state; #endif { register int yy_is_jam; register YY_CHAR yy_c = 4; while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 329 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 328); if ( ! yy_is_jam ) *yy_state_ptr++ = yy_current_state; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #ifdef YY_USE_PROTOS static void yyunput( int c, register char *yy_bp ) #else static void yyunput( c, yy_bp ) int c; register char *yy_bp; #endif { register char *yy_cp = yy_c_buf_p; /* undo effects of setting up yytext */ *yy_cp = yy_hold_char; if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) { /* need to shift things up to make room */ /* +2 for EOB chars. */ register int number_to_move = yy_n_chars + 2; register char *dest = &yy_current_buffer->yy_ch_buf[ yy_current_buffer->yy_buf_size + 2]; register char *source = &yy_current_buffer->yy_ch_buf[number_to_move]; while ( source > yy_current_buffer->yy_ch_buf ) *--dest = *--source; yy_cp += (int) (dest - source); yy_bp += (int) (dest - source); yy_current_buffer->yy_n_chars = yy_n_chars = yy_current_buffer->yy_buf_size; if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) YY_FATAL_ERROR( "flex scanner push-back overflow" ); } *--yy_cp = (char) c; yytext_ptr = yy_bp; yy_hold_char = *yy_cp; yy_c_buf_p = yy_cp; } #endif /* ifndef YY_NO_UNPUT */ #ifdef __cplusplus static int yyinput() #else static int input() #endif { int c; *yy_c_buf_p = yy_hold_char; if ( *yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yy_c_buf_p < &yy_current_buffer->yy_ch_buf[yy_n_chars] ) /* This was really a NUL. */ *yy_c_buf_p = '\0'; else { /* need more input */ int offset = yy_c_buf_p - yytext_ptr; ++yy_c_buf_p; switch ( yy_get_next_buffer() ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart( yyin ); /* fall through */ case EOB_ACT_END_OF_FILE: { if ( yywrap() ) return EOF; if ( ! yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: yy_c_buf_p = yytext_ptr + offset; break; } } } c = *(unsigned char *) yy_c_buf_p; /* cast for 8-bit char's */ *yy_c_buf_p = '\0'; /* preserve yytext */ yy_hold_char = *++yy_c_buf_p; yy_current_buffer->yy_at_bol = (c == '\n'); return c; } #ifdef YY_USE_PROTOS void yyrestart( FILE *input_file ) #else void yyrestart( input_file ) FILE *input_file; #endif { if ( ! yy_current_buffer ) yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); yy_init_buffer( yy_current_buffer, input_file ); yy_load_buffer_state(); } #ifdef YY_USE_PROTOS void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer ) #else void yy_switch_to_buffer( new_buffer ) YY_BUFFER_STATE new_buffer; #endif { if ( yy_current_buffer == new_buffer ) return; if ( yy_current_buffer ) { /* Flush out information for old buffer. */ *yy_c_buf_p = yy_hold_char; yy_current_buffer->yy_buf_pos = yy_c_buf_p; yy_current_buffer->yy_n_chars = yy_n_chars; } yy_current_buffer = new_buffer; yy_load_buffer_state(); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ yy_did_buffer_switch_on_eof = 1; } #ifdef YY_USE_PROTOS void yy_load_buffer_state( void ) #else void yy_load_buffer_state() #endif { yy_n_chars = yy_current_buffer->yy_n_chars; yytext_ptr = yy_c_buf_p = yy_current_buffer->yy_buf_pos; yyin = yy_current_buffer->yy_input_file; yy_hold_char = *yy_c_buf_p; } #ifdef YY_USE_PROTOS YY_BUFFER_STATE yy_create_buffer( FILE *file, int size ) #else YY_BUFFER_STATE yy_create_buffer( file, size ) FILE *file; int size; #endif { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yy_flex_alloc( b->yy_buf_size + 2 ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer( b, file ); return b; } #ifdef YY_USE_PROTOS void yy_delete_buffer( YY_BUFFER_STATE b ) #else void yy_delete_buffer( b ) YY_BUFFER_STATE b; #endif { if ( ! b ) return; if ( b == yy_current_buffer ) yy_current_buffer = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) yy_flex_free( (void *) b->yy_ch_buf ); yy_flex_free( (void *) b ); } #ifndef _WIN32 #include <unistd.h> #else #ifndef YY_ALWAYS_INTERACTIVE #ifndef YY_NEVER_INTERACTIVE extern int isatty YY_PROTO(( int )); #endif #endif #endif #ifdef YY_USE_PROTOS void yy_init_buffer( YY_BUFFER_STATE b, FILE *file ) #else void yy_init_buffer( b, file ) YY_BUFFER_STATE b; FILE *file; #endif { yy_flush_buffer( b ); b->yy_input_file = file; b->yy_fill_buffer = 1; #if YY_ALWAYS_INTERACTIVE b->yy_is_interactive = 1; #else #if YY_NEVER_INTERACTIVE b->yy_is_interactive = 0; #else b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; #endif #endif } #ifdef YY_USE_PROTOS void yy_flush_buffer( YY_BUFFER_STATE b ) #else void yy_flush_buffer( b ) YY_BUFFER_STATE b; #endif { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == yy_current_buffer ) yy_load_buffer_state(); } #ifndef YY_NO_SCAN_BUFFER #ifdef YY_USE_PROTOS YY_BUFFER_STATE yy_scan_buffer( char *base, yy_size_t size ) #else YY_BUFFER_STATE yy_scan_buffer( base, size ) char *base; yy_size_t size; #endif { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer( b ); return b; } #endif #ifndef YY_NO_SCAN_STRING #ifdef YY_USE_PROTOS YY_BUFFER_STATE yy_scan_string( yyconst char *yy_str ) #else YY_BUFFER_STATE yy_scan_string( yy_str ) yyconst char *yy_str; #endif { int len; for ( len = 0; yy_str[len]; ++len ) ; return yy_scan_bytes( yy_str, len ); } #endif #ifndef YY_NO_SCAN_BYTES #ifdef YY_USE_PROTOS YY_BUFFER_STATE yy_scan_bytes( yyconst char *bytes, int len ) #else YY_BUFFER_STATE yy_scan_bytes( bytes, len ) yyconst char *bytes; int len; #endif { YY_BUFFER_STATE b; char *buf; yy_size_t n; int i; /* Get memory for full buffer, including space for trailing EOB's. */ n = len + 2; buf = (char *) yy_flex_alloc( n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); for ( i = 0; i < len; ++i ) buf[i] = bytes[i]; buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer( buf, n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #endif #ifndef YY_NO_PUSH_STATE #ifdef YY_USE_PROTOS static void yy_push_state( int new_state ) #else static void yy_push_state( new_state ) int new_state; #endif { if ( yy_start_stack_ptr >= yy_start_stack_depth ) { yy_size_t new_size; yy_start_stack_depth += YY_START_STACK_INCR; new_size = yy_start_stack_depth * sizeof( int ); if ( ! yy_start_stack ) yy_start_stack = (int *) yy_flex_alloc( new_size ); else yy_start_stack = (int *) yy_flex_realloc( (void *) yy_start_stack, new_size ); if ( ! yy_start_stack ) YY_FATAL_ERROR( "out of memory expanding start-condition stack" ); } yy_start_stack[yy_start_stack_ptr++] = YY_START; BEGIN(new_state); } #endif #ifndef YY_NO_POP_STATE static void yy_pop_state() { if ( --yy_start_stack_ptr < 0 ) YY_FATAL_ERROR( "start-condition stack underflow" ); BEGIN(yy_start_stack[yy_start_stack_ptr]); } #endif #ifndef YY_NO_TOP_STATE static int yy_top_state() { return yy_start_stack[yy_start_stack_ptr - 1]; } #endif #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif #ifdef YY_USE_PROTOS static void yy_fatal_error( yyconst char msg[] ) #else static void yy_fatal_error( msg ) char msg[]; #endif { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ yytext[yyleng] = yy_hold_char; \ yy_c_buf_p = yytext + n; \ yy_hold_char = *yy_c_buf_p; \ *yy_c_buf_p = '\0'; \ yyleng = n; \ } \ while ( 0 ) /* Internal utility routines. */ #ifndef yytext_ptr #ifdef YY_USE_PROTOS static void yy_flex_strncpy( char *s1, yyconst char *s2, int n ) #else static void yy_flex_strncpy( s1, s2, n ) char *s1; yyconst char *s2; int n; #endif { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN #ifdef YY_USE_PROTOS static int yy_flex_strlen( yyconst char *s ) #else static int yy_flex_strlen( s ) yyconst char *s; #endif { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif #ifdef YY_USE_PROTOS static void *yy_flex_alloc( yy_size_t size ) #else static void *yy_flex_alloc( size ) yy_size_t size; #endif { return (void *) malloc( size ); } #ifdef YY_USE_PROTOS static void *yy_flex_realloc( void *ptr, yy_size_t size ) #else static void *yy_flex_realloc( ptr, size ) void *ptr; yy_size_t size; #endif { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } #ifdef YY_USE_PROTOS static void yy_flex_free( void *ptr ) #else static void yy_flex_free( ptr ) void *ptr; #endif { free( ptr ); } #if YY_MAIN int main() { yylex(); return 0; } #endif #line 1692 "vs1.0_tokens.l" //===================================================================== // Function: FindNMacro // Description: Look through macros and see if it had been predefined // Parameters: findName = name to lookup // sLen = # characters valid in source (findName) // Returns: MACROENTRY * = pointer to macro entry if found //===================================================================== MACROENTRY *FindNMacro(char *findName, unsigned int sLen) { MACROENTRY *curEntry; curEntry = gLastMacro; while (curEntry != NULL) { if (strlen(curEntry->macroName) == sLen) { if (!strncmp(curEntry->macroName, findName, sLen)) { break; } } curEntry = curEntry->prev; } return curEntry; } //===================================================================== // Function: FindMacro // Description: Look through macros and see if it had been predefined // Parameters: findName = name to lookup // Returns: MACROENTRY * = pointer to macro entry if found //===================================================================== MACROENTRY *FindMacro(char *findName) { MACROENTRY *curEntry; curEntry = gLastMacro; while (curEntry != NULL) { if (!strcmp(curEntry->macroName, findName)) { break; } curEntry = curEntry->prev; } return curEntry; } //===================================================================== // Function: CleanUp // Description: Clean up the #define strings // Parameters: . // Returns: . //===================================================================== void CleanUp() { void *tPtr; // free up the macros that were alloced while (gLastMacro != NULL) { FreeMacroEntry(gLastMacro); tPtr = gLastMacro; gLastMacro = gLastMacro->prev; SAFEFREE(tPtr); } } //===================================================================== // Function: FreeMacroEntry // Description: Frees up the macro entry data, (parms, lines of text) // Parameters: macEntry = pointer to the MACROENTRY structure // Returns: . //===================================================================== void FreeMacroEntry(MACROENTRY *macEntry) { MACROTEXT *tText; MACROTEXT *tNext; SAFEFREE(macEntry->macroName); SAFEFREE(macEntry->fileName); // free the macro lines that were alloced tText = macEntry->lastMacroLines; while (tText != NULL) { tNext = tText->prev; SAFEFREE(tText); tText = tNext; } // free the text of the macro parms that were alloced tText = macEntry->lastMacroParms; while (tText != NULL) { tNext = tText->prev; SAFEFREE(tText); tText = tNext; } } //===================================================================== // Function: CheckMacroFunctions // Description: Find if this text is a builtin macro function // Parameters: lookString = non-null terminated string of possible // and if found set global macro function call // Returns: . //===================================================================== void CheckMacroFunctions(char *lookString, unsigned int *recognizedLen, char **invString) { unsigned int i; unsigned int sLen; for (i=0; i< NUM_MACRO_FUNCTIONS; i++) { sLen = strlen(gMacroFunctions[i].name); if (!strncmp(gMacroFunctions[i].name, lookString, sLen)) { gMacroCallFunction = gMacroFunctions[i].function; *recognizedLen = sLen; *invString = NULL; return; } } } //===================================================================== // Function: FindAlphaNum // Description: Find a whole alpha numeric string, ie consists of // [A-Za-z0-9_] only // Parameters: srcStr = source string to search through. // sLen = unsinged int pointer to length of string found // Returns: pointer to found start of string. // NULL if none. //===================================================================== char *FindAlphaNum(char *srcStr, unsigned int *sLen) { char curChar; char *foundStr; while (*srcStr != '\0') { curChar = toupper(*srcStr); if ((curChar >= 'A') && (curChar <= 'Z')) break; if ((curChar >= '0') && (curChar <='9')) break; if (curChar == '_') break; srcStr++; } if (*srcStr == '\0') { return NULL; } foundStr = srcStr; *sLen = 0; // now search for end of string of [A-Za-z0-9_] while (*srcStr != '\0') { curChar = toupper(*srcStr); if ((curChar < 'A') || (curChar > 'Z')) { if ((curChar < '0') || (curChar > '9')) { if (curChar != '_') break; } } (*sLen)++; srcStr++; } return foundStr; } //===================================================================== // Function: FindDefineParm // Description: Find if the MACROENTRY->macroText linked list contains // replaceable parameters. // Parameters: srcParms = pointer to MACROENTRY structure for source // parameters // invParms = MACROENTRY pointer to invocation parameters // lookString = non-null terminated string of possible // replaceable string // recognizedLen = replacement string matched length // invString = invocation string to replace with // Returns: pointer to first character found in lookstring //===================================================================== char *FindDefineParm(MACROENTRY *srcParms, MACROENTRY *invParms, char *lookString, unsigned int *recognizedLen, char **invString) { MACROTEXT *srcText; MACROTEXT *invText; char *checkStr; unsigned int checkLen = 0; unsigned int sLen; checkStr = lookString; *invString = NULL; // first search for first [A-Za-z0-9_] only string checkStr = FindAlphaNum(lookString, &checkLen); while (checkStr != NULL) { // check all the #define parameters for match srcText = srcParms->firstMacroParms; invText = invParms->firstMacroParms; while (srcText) { sLen = strlen(srcText->macroText); // lengths should match if (sLen == checkLen) { if (!strncmp(checkStr, srcText->macroText, checkLen)) { // it matched so return replacement text *invString = invText->macroText; // and length that we recognized *recognizedLen = checkLen; return checkStr; } } srcText = srcText->next; invText = invText->next; } // not found yet, so go to next string. checkStr = FindAlphaNum(checkStr+checkLen, &checkLen); } return NULL; } //===================================================================== // Function: FindReplaceParm // Description: Find if the MACROENTRY->macroText linked list contains // a replaceable parameters. // Parameters: srcParms = pointer to MACROENTRY structure for source // parameters // invParms = MACROENTRY pointer to invocation parameters // lookString = non-null terminated string of possible // replaceable string // recognizedLen = replacement string matched length // invString = invocation string to replace with // Returns: . //===================================================================== void FindReplaceParm(MACROENTRY *srcParms, MACROENTRY *invParms, char *lookString, unsigned int *recognizedLen, char **invString) { unsigned int sLen; MACROTEXT *srcText; MACROTEXT *invText; *recognizedLen = 0; *invString = NULL; srcText = srcParms->firstMacroParms; invText = invParms->firstMacroParms; if (srcText != NULL) { // go until srcText # strings ends while (srcText != NULL) { sLen = strlen(srcText->macroText); if (!strncmp(srcText->macroText, lookString, sLen)) { // found it so return src, replacement string *recognizedLen = strlen(srcText->macroText); *invString = invText->macroText; // call function macro if it was invoked prior. if (gMacroCallFunction != NULL) { gMacroCallFunction(lookString, recognizedLen, invString); gMacroCallFunction = NULL; } return; } srcText = srcText->next; invText = invText->next; } } // ok, it wasn't found, look through builtin macro functions CheckMacroFunctions(lookString, recognizedLen, invString); } //===================================================================== // Function: ReplaceMacroParms // Description: Replace macro parameters when macro was defined, with // those specified on the macro invocation line // Parameters: srcLine = source line to replace src macro parms with // destLine = destination line save to. // invocation macro parameters. // parseMacro = currently parsing macro entry // invParms = invocation macro entry // Returns: . //===================================================================== void ReplaceMacroParms(char *srcLine, char *destLine, MACROENTRY *srcParms, MACROENTRY *invParms) { char *findReplace; char *invString; unsigned int sLen; unsigned int dLen; unsigned int copyLen; unsigned int subLen; unsigned int recognizedLen; destLine[0]= '\0'; sLen = strlen(srcLine); dLen = 0; while (sLen > 0) { // strtok might work better except it modifies the string, so // kind of do my own.... if (!srcParms->bIsDefine) { findReplace = strchr(srcLine, '%'); if (findReplace != NULL) { // bypass % sign in findReplacement findReplace++; // figure out length of source before % copyLen = (findReplace - srcLine)-1; // check if there is a replacement string FindReplaceParm(srcParms, invParms, findReplace, &recognizedLen, &invString); } else { strcat(destLine, srcLine); return; } } else { findReplace = FindDefineParm(srcParms, invParms, srcLine, &recognizedLen, &invString); if (findReplace != NULL) { // figure out length of source before % copyLen = findReplace - srcLine; } else { strcat(destLine, srcLine); return; } } if (invString != NULL) { // figure out how much we are going to substitute subLen = strlen(invString); } else { subLen = 0; } if ((dLen + copyLen + subLen) > MAXSAVELINE) { LexError("Macro string overrun.\n"); CleanUp(); exit(ERROR_MACRO_OVERRUN); } if (copyLen > 0) { strncat(destLine, srcLine, copyLen); dLen += copyLen; } srcLine += copyLen; sLen -= copyLen; // in macro so skip % part of variable if (!srcParms->bIsDefine) { // skip %, also srcLine++; sLen--; } if (invString != NULL) { strcat(destLine, invString); dLen += strlen(invString); } srcLine += recognizedLen; sLen -= recognizedLen; } } //===================================================================== // Function: SaveMacroText // Description: Adds a string to a linked list of MACROTEXT structures // Parameters: srcText = pointer to source text to save // lastMacroText = last allocated, or NULL // Returns: newly allocated MACROTEXT structure, or NULL //===================================================================== MACROTEXT *SaveMacroText(char *srcText, MACROTEXT *lastMacroText) { MACROTEXT *curMacroText; curMacroText = (MACROTEXT *)malloc(sizeof(MACROTEXT)); if (curMacroText == NULL) { return NULL; } else { // no next entry but set up previous with previously alloced macro parameter curMacroText->next = NULL; curMacroText->prev = lastMacroText; // if the macroParm pointer is null then we are the first allocated // so if not set the last one allocate next pointer to newly allocated structure if (lastMacroText != NULL) { lastMacroText->next = curMacroText; } /* %%%%% this should be set up in memory pools. */ curMacroText->macroText = strdup(srcText); if (curMacroText->macroText == NULL) { SAFEFREE(curMacroText); return NULL; } } return curMacroText; } //===================================================================== // Function: ParseBuiltInMacroParms // Description: parse parameters of string and fill in MACROENTRY // structure. // Parameters: parsedMacro = pointer to MACROENTRY structure that gets // filled in with parameter pointers and count // parmStr = string to parse parameters from // Returns: false if error //===================================================================== bool ParseBuiltInMacroParms(MACROENTRY *parsedMacro, char *parmStr) { char *endStr; char *foundParm; MACROTEXT *prevMT; MACROTEXT *curMT; parsedMacro->numParms = 0; parsedMacro->firstMacroParms = NULL; foundParm = strdup(parmStr); if (foundParm == NULL) { LexError("Out of memory parsing bultin macro parameters.\n"); return false; } // assume a ')' is on the end. endStr = strrchr(foundParm, ')'); if (endStr == NULL) { LexWarning("Ending parenthesis not found for macro %s.\n", parsedMacro->macroName); endStr = foundParm + strlen(foundParm); } prevMT = NULL; // strip out and separate parameters while (foundParm < endStr) { // allocate a macro text structure curMT = (MACROTEXT *)malloc(sizeof(MACROTEXT)); if (curMT == NULL) { free(parmStr); LexError("Out of memory parsing bultin macro parameters.\n"); return false; } curMT->next = NULL; curMT->prev = prevMT; parsedMacro->numParms++; if (prevMT != NULL) { prevMT->next = curMT; } else { parsedMacro->firstMacroParms = curMT; } curMT->macroText = foundParm; // search for next parameters, delimited by comma foundParm = strchr(foundParm, ','); if (foundParm == NULL) { foundParm = endStr; *foundParm = '\0'; } else { // skip comma *foundParm = '\0'; foundParm++; } prevMT = curMT; } return true; } //===================================================================== // Function: MacroMathFunction // Description: Comes here after macro replacement is done to perform // some mathematic function on parameter (macro replacement // string (ie, register)) // Parameters: invMacro = macroentry pointer containing macro information // recognizedLen = # characters recoginized so far // invStr = invoked replacement string so far // mathStr = "-", "+", etc for mathematic function // Returns: new recognizedLen, invStr, with incremented # //===================================================================== void MacroMathFunction(MACROENTRY *invMacro, unsigned int *recognizedLen, char **invStr, const char *mathStr) { char *numStartStr; unsigned int sLen; char numberStr[256]; unsigned int number = 0; char *operand; // verify enough paramters to complete operation if (invMacro->numParms != 2) { LexError("Two parameters are required for %s macro\n", invMacro->macroName); return; } // get second macro parm, which is add by amount. operand = invMacro->firstMacroParms->next->macroText; // first find inner most bracket if any numStartStr = strrchr(*invStr, ']'); if (numStartStr == NULL) { numStartStr = strrchr(*invStr, ')'); } if (numStartStr != NULL) { if ((strlen(*invStr)+strlen(operand)+1) > MAXREPLACESTRING) { LexError("Out of Temporary string replacement memory inside builtin macro %s\n", invMacro->macroName); } else { sLen = (numStartStr - *invStr); gReplaceText[0] = '\0'; strncat(gReplaceText, *invStr, sLen); strcat(gReplaceText, mathStr); strcat(gReplaceText, operand); strcat(gReplaceText, numStartStr); *invStr = gReplaceText; } } else { numStartStr = strpbrk(*invStr, "0123456789"); if (numStartStr != NULL) { // put up to number we found sLen = numStartStr - *invStr; if (sLen > MAXREPLACESTRING) goto ErrOut; gReplaceText[0] = '\0'; strncat(gReplaceText, *invStr, sLen); switch (mathStr[0]) { case '-': number = atoi(numStartStr)-atoi(operand); break; case '+': number = atoi(numStartStr)+atoi(operand); break; } sprintf(numberStr, "%d", number); if ((strlen(gReplaceText) + strlen(numberStr)) > MAXREPLACESTRING) goto ErrOut; strcat(gReplaceText, numberStr); while ((*numStartStr != '\0') && (*numStartStr >= '0' && *numStartStr <= '9')) numStartStr++; if ((strlen(gReplaceText) + strlen(numStartStr)) > MAXREPLACESTRING) goto ErrOut; strcat(gReplaceText, numStartStr); *invStr = gReplaceText; } else { if ((strlen(*invStr)+strlen(operand)+1) > MAXREPLACESTRING) { LexError("Out of Temporary string replacement memory inside builtin macro %s\n", invMacro->macroName); } else { sprintf(gReplaceText, "%s%s%s", *invStr, mathStr, operand); *invStr = gReplaceText; } } } return; ErrOut: LexError("Out of Temporary string replacement memory inside builtin macro %s\n", invMacro->macroName); // skip ')' (*recognizedLen)++; } //===================================================================== // Function: MacroIncFunction // Description: Comes here after macro replacement is done to increment // macro replacement string (ie, register) // Parameters: lookStr = string after '(', so we can get parameters // recognizedLen = # characters recoginized so far // invStr = invoked replacement string so far // Returns: new recognizedLen, invStr, with incremented # //===================================================================== void MacroIncFunction(char *lookStr, unsigned int *recognizedLen, char **invStr) { MACROENTRY tMEntry; MACROTEXT parm1; MACROTEXT parm2; tMEntry.macroName = (char *)"%inc()"; tMEntry.numParms = 2; tMEntry.firstMacroParms = &parm1; parm1.prev = NULL; parm1.next = &parm2; parm1.macroText = *invStr; parm2.prev = &parm1; parm2.next = NULL; parm2.macroText = (char *)"1"; MacroMathFunction(&tMEntry, recognizedLen, invStr, "+"); // skip ')' (*recognizedLen)++; } //===================================================================== // Function: MacroDecFunction // Description: Comes here after macro replacement is done to decrement // macro replacement string (ie, register) // Parameters: lookStr = string after '(', so we can get parameters // recognizedLen = # characters recoginized so far // invStr = invoked replacement string so far // Returns: new recognizedLen, invStr, with decremented # //===================================================================== void MacroDecFunction(char *lookStr, unsigned int *recognizedLen, char **invStr) { MACROENTRY tMEntry; MACROTEXT parm1; MACROTEXT parm2; tMEntry.macroName = (char *)"%dec()"; tMEntry.numParms = 2; tMEntry.firstMacroParms = &parm1; parm1.prev = NULL; parm1.next = &parm2; parm1.macroText = *invStr; parm2.prev = &parm1; parm2.next = NULL; parm2.macroText = (char *)"1"; MacroMathFunction(&tMEntry, recognizedLen, invStr, "-"); // skip ')' (*recognizedLen)++; } //===================================================================== // Function: MacroAddFunction // Description: Comes here after macro replacement is done to add // macro replacement string (ie, register) // Parameters: lookStr = string after '(', so we can get parameters // recognizedLen = # characters recoginized so far // invStr = invoked replacement string so far // Returns: new recognizedLen, invStr, with incremented # //===================================================================== void MacroAddFunction(char *lookStr, unsigned int *recognizedLen, char **invStr) { MACROENTRY tMEntry; MACROTEXT *curMT; MACROTEXT *nextMT; unsigned int i; tMEntry.macroName = (char *)"%add()"; if (strlen(lookStr) > MAXREPLACESTRING) { LexError("Out of Temporary string replacement memory inside builtin macro %add()\n"); return; } if (ParseBuiltInMacroParms(&tMEntry, lookStr)) { MacroMathFunction(&tMEntry, recognizedLen, invStr, "+"); // skip ',' strlen(parm2)+ ')' (*recognizedLen) += strlen(tMEntry.firstMacroParms->next->macroText)+2; } curMT = tMEntry.firstMacroParms; // in this case only one string was allocated free(curMT->macroText); for (i=0; i<tMEntry.numParms; i++) { nextMT = curMT->next; free(curMT); curMT = nextMT; } } //===================================================================== // Function: MacroSubFunction // Description: Comes here after macro replacement is done to subtract // macro replacement string (ie, register) // Parameters: invParms, parameters that macro was invoked with // recognizedLen = # characters recoginized so far // invStr = invoked replacement string so far // Returns: new recognizedLen, invStr, with incremented # //===================================================================== void MacroSubFunction(char *lookStr, unsigned int *recognizedLen, char **invStr) { MACROENTRY tMEntry; MACROTEXT *curMT; MACROTEXT *nextMT; unsigned int i; tMEntry.macroName = (char *)"%sub()"; if (ParseBuiltInMacroParms(&tMEntry, lookStr)) { MacroMathFunction(&tMEntry, recognizedLen, invStr, "-"); // skip ',' strlen(parm2)+ ')' (*recognizedLen) += strlen(tMEntry.firstMacroParms->next->macroText)+2; } curMT = tMEntry.firstMacroParms; // in this case only one string was allocated free(curMT->macroText); for (i=0; i<tMEntry.numParms; i++) { nextMT = curMT->next; free(curMT); curMT = nextMT; } } //===================================================================== // Function: EndMacroParms // Description: Does update and cleanup one end of macro parameters // is reached // Parameters: . // Returns: . //===================================================================== void EndMacroParms() { char *curFileName; char *macroFileName; char tempStr[1024]; char *macroText; if (gbTempInsideMacro) { if (gTempParseMacro->numParms != gTempMacro->numParms) { LexError("Macro invocation number of parameters do not match macro definition, skipping\n"); BEGIN(INITIAL); SAFEFREE(gTempMacro); } else { // we got all the parameters for the MACRO invocation, so start inside // the macro now, by saving off current state on stack gIncludeStack[gIncludeStackIndex].lineNo = yylineno; gIncludeStack[gIncludeStackIndex].fileName = gCurFileName; // gIncludeStack[gIncludeStackIndex].fileHandle = yyin; //fprintf( stderr, "Chris fix this code with myin stuff\n" ); gIncludeStack[gIncludeStackIndex].prevString = myin; gIncludeStack[gIncludeStackIndex].nextString = NULL; gIncludeStack[gIncludeStackIndex].lastInvokeMacro = gInvokeMacro; gIncludeStack[gIncludeStackIndex].lastParseMacro = gParseMacro; gIncludeStack[gIncludeStackIndex].lastMacroLineParse = gMacroLineParse; gIncludeStack[gIncludeStackIndex].lastbInsideMacro = gbInsideMacro; gIncludeStack[gIncludeStackIndex].lastbInsideInclude = gbInsideInclude; gIncludeStack[gIncludeStackIndex].buffer = YY_CURRENT_BUFFER; gIncludeStack[gIncludeStackIndex].lastbProcessingIFDEF = gbProcessingIFDEF; gIncludeStackIndex++; gParseMacro = gTempParseMacro; gInvokeMacro = gTempMacro; gbInsideMacro = gbTempInsideMacro; gbTempInsideMacro = false; // yyin = NULL; myin = NULL; curFileName = gCurFileName; if (curFileName == NULL) curFileName = (char *)""; macroFileName = gParseMacro->fileName; if (macroFileName == NULL) macroFileName = (char *)""; sprintf(tempStr, "%s(%d) : References ->\n%s", curFileName, yylineno, macroFileName); gCurFileName = strdup(tempStr); gMacroLineParse = gParseMacro->firstMacroLines; macroText = gMacroLine; // if no replacement text, just use source line if (gParseMacro->firstMacroParms == NULL) { macroText = gMacroLineParse->macroText; } else { // replace the macro parameters ReplaceMacroParms(gMacroLineParse->macroText, gMacroLine, gParseMacro, gInvokeMacro); } yylineno = gParseMacro->lineNo; if (gParseMacro->nLines >= 1) { strcpy(gSaveLine, macroText); } // if (gExpandMacros && (gParseMacro->nLines >= 1)) // { // // in case there is anything there dump it out // GenDebugLine(); // GenListString(); // if (gInvokeMacro->nLines >= 1) // GenSwitchFileNames(macroFileName); // } BEGIN(gInvokeState); yy_scan_string(macroText); gInvokeState = INITIAL; } } else { if (gLastMacro != NULL) { gLastMacro->next = gTempMacro; } gLastMacro = gTempMacro; BEGIN(MACROBODY); } } //===================================================================== // Function: FindSwizzleValue // Description: see if valid swizzle value and return the bits // Parameters: swizzleTex = pointer to characters to analyze // Returns: unsigned int = bits for swizzle values, or 0 for error //===================================================================== unsigned int FindSwizzleValue(char *swizzleText) { unsigned int swizzleBits; unsigned int sLen; unsigned int i; unsigned int lastMask; sLen = strlen(swizzleText); swizzleBits = 0; lastMask = 0; for (i=0; i<sLen; i++) { switch (swizzleText[i]) { case 'x': swizzleBits |= (WRITEMASK_X << (4*(3-i))); lastMask = WRITEMASK_X; break; case 'y': swizzleBits |= (WRITEMASK_Y << (4*(3-i))); lastMask = WRITEMASK_Y; break; case 'z': swizzleBits |= (WRITEMASK_Z << (4*(3-i))); lastMask = WRITEMASK_Z; break; case 'w': swizzleBits |= (WRITEMASK_W << (4*(3-i))); lastMask = WRITEMASK_W; break; } } for (; i<4; i++) { swizzleBits |= (lastMask << (4*(3-i))); } return swizzleBits; } #if 0 unsigned int FindSwizzleValue(char *swizzleText) { DWORD swizzleBits; DWORD sLen; DWORD i; DWORD lastIndex; sLen = strlen(swizzleText); swizzleBits = 0; lastIndex = 0; for (i=0; i<sLen; i++) { switch (swizzleText[i]) { case 'x': swizzleBits |= (0 << (D3DVS_SWIZZLE_SHIFT + (i * 2))); lastIndex = 0; break; case 'y': swizzleBits |= (1 << (D3DVS_SWIZZLE_SHIFT + (i * 2))); lastIndex = 1; break; case 'z': swizzleBits |= (2 << (D3DVS_SWIZZLE_SHIFT + (i * 2))); lastIndex = 2; break; case 'w': swizzleBits |= (3 << (D3DVS_SWIZZLE_SHIFT + (i * 2))); lastIndex = 3; break; } } for (; i<4; i++) { swizzleBits |= (lastIndex << (D3DVS_SWIZZLE_SHIFT + (i * 2))); } return swizzleBits; } #endif //===================================================================== // Function: FindRegisterMask // Description: Look through register mask strings // Parameters: findName = name to lookup // Returns: unsigned int with token value //===================================================================== unsigned int MakeRegisterMask(char *findName) { unsigned int regMask; char *findFirst; regMask = 0; findFirst = strchr(findName, 'x'); if (findFirst != NULL) { if (strchr(findFirst+1, 'x') != NULL) { return 0; } regMask |= WRITEMASK_X; } findFirst = strchr(findName, 'y'); if (findFirst != NULL) { regMask |= WRITEMASK_Y; // invalide write mask, must be swizzle if (strchr(findFirst+1, 'x') != NULL) { return 0; } if (strchr(findFirst+1, 'y') != NULL) { return 0; } } findFirst = strchr(findName, 'z'); if (findFirst != NULL) { regMask |= WRITEMASK_Z; if (strchr(findFirst+1, 'x') != NULL) { return 0; } if (strchr(findFirst+1, 'y') != NULL) { return 0; } if (strchr(findFirst+1, 'z') != NULL) { return 0; } } findFirst = strchr(findName, 'w'); if (findFirst != NULL) { regMask |= WRITEMASK_W; if (strchr(findFirst+1, 'x') != NULL) { return 0; } if (strchr(findFirst+1, 'y') != NULL) { return 0; } if (strchr(findFirst+1, 'z') != NULL) { return 0; } if (strchr(findFirst+1, 'w') != NULL) { return 0; } } return regMask; } //===================================================================== // Function: LexError // Description: output an error to the stdout // Parameters: typical printf like format // Returns: . //===================================================================== void LexError(const char *format, ...) { char errstring[4096]; va_list marker; // fprintf( stderr,"(%d) : Error : ", yylineno); if ( gbInsideInclude ) { sprintf( errstring, "%s", gCurFileName ); sprintf( errstring+strlen(errstring),"(%d) : Error : ", yylineno); } else { sprintf( errstring,"(%d) : Error : ", yylineno); } va_start(marker, format); // vprintf(format, marker); vsprintf(errstring+strlen(errstring), format, marker); va_end(marker); errors.set( errstring ); } //===================================================================== // Function: LexWarning // Description: output a warning to the stdout // Parameters: typical printf like format // Returns: . //===================================================================== void LexWarning(const char *format, ...) { char errstring[4096]; va_list marker; // fprintf( stderr,"(%d) : warning : ", yylineno); if ( gbInsideInclude ) sprintf( errstring, "%s", gCurFileName ); sprintf( errstring+strlen(errstring),"(%d) : Warning : ", yylineno); // sprintf( errstring,"(%d) : Warning : ", yylineno); va_start(marker, format); // vprintf(format, marker); vsprintf(errstring+strlen(errstring), format, marker); va_end(marker); errors.set( errstring ); } //===================================================================== // Function: DebugUnhandledState // Description: Come here in debug mode, when a state isn't handled // for the Lexer // Parameters: . // Returns: . //===================================================================== void DebugUnhandledState() { fprintf( stderr,"Unhandled state reached, with %s text.\n", yytext); } //===================================================================== // Function: FindOpcode // Description: Look through opcodes and see if in the table // Parameters: findName = name to lookup // Returns: OPCODEMAP * = pointer to opcode map entry, if found //===================================================================== OPCODEMAP *FindOpcode(char *findName) { unsigned i; // just do linear search for now for (i=0; i<NUMOPCODES; i++) { if (!stricmp(theOpcodes[i].string, findName)) { return &theOpcodes[i]; } } return NULL; } char *ReadTextFile(const char * filename) { char path[3][32] = { ".\0", "../../data/programs\0", "../../../data/programs\0" }; char name[8192]; int i; if (!filename) return 0; struct _stat status; int found = 0; for ( i = 0; i < 3; i++ ) { sprintf( name, "%s/%s", path[i], filename ); int fh = ::_open(name, _O_RDONLY); if(fh != -1) { int result = _fstat( fh, &status ); if( result != 0 ) { fprintf( stderr, "An fstat error occurred.\n" ); break; } ::_close( fh ); found = i+1; break; } } if ( 0 == found ) { fprintf(stderr,"Cannot open \"%s\" for stat read!\n", filename); return NULL; } long size = status.st_size; char * buf = new char[size+1]; FILE *fp = 0; if (!(fp = fopen(name, "r"))) { fprintf(stderr,"Cannot open \"%s\" for read!\n", name); return NULL; } int bytes; bytes = fread(buf, 1, size, fp); buf[bytes] = 0; fclose(fp); return buf; } bool vs10_init_more(); bool vs10_init(char* inputString) { BEGIN(SAVELINE); myin = inputString; line_incr = 0; return vs10_init_more(); } #ifndef vs10_wrap int vs10_wrap(void) { return(1); } #endif
GDevs/mission-farpoint
ogre/RenderSystems/GL/src/nvparse/_vs1.0_lexer.cpp
C++
gpl-3.0
127,015
<?php /* TVI * Copyright (C) 2015 Florian HENRY <florian.henry@open-concept.pro> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /** * \file tvi/ajax/list.php * \brief File to return datables output */ if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); require '../main.inc.php'; require DOL_DOCUMENT_ROOT.'/loan/class/loanschedule.class.php'; $mens=GETPOST('mens'); $capital=GETPOST('capital'); $rate=GETPOST('rate'); $echance=GETPOST('echeance'); $nbterm=GETPOST('nbterm'); top_httphead(); $output=array(); $object = new LoanSchedule($db); $int = ($capital*($rate/12)); $int = round($int,2,PHP_ROUND_HALF_UP); $cap_rest = round($capital - ($mens-$int),2,PHP_ROUND_HALF_UP); $output[$echance]=array('cap_rest'=>$cap_rest,'cap_rest_str'=>price($cap_rest),'interet'=>$int,'interet_str'=>price($int,0,'',1),'mens'=>$mens); $echance++; $capital=$cap_rest; while ($echance<=$nbterm) { $mens = round($object->calc_mens($capital,$rate,$nbterm-$echance+1),2,PHP_ROUND_HALF_UP); $int = ($capital*($rate/12)); $int = round($int,2,PHP_ROUND_HALF_UP); $cap_rest = round($capital - ($mens-$int),2,PHP_ROUND_HALF_UP); $output[$echance]=array('cap_rest'=>$cap_rest,'cap_rest_str'=>price($cap_rest),'interet'=>$int,'interet_str'=>price($int,0,'',1),'mens'=>$mens); $capital=$cap_rest; $echance++; } echo json_encode($output);
tomours/dolibarr
htdocs/loan/calcmens.php
PHP
gpl-3.0
2,177
/* pins_arduino.h - Pin definition functions for Arduino Part of Arduino - http://www.arduino.cc/ Copyright (c) 2007 David A. Mellis This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: wiring.h 249 2007-02-03 16:52:51Z mellis $ */ #ifndef Pins_Arduino_h #define Pins_Arduino_h #include <avr/pgmspace.h> #define NUM_DIGITAL_PINS 20 #define NUM_ANALOG_INPUTS 6 #define analogInputToDigitalPin(p) ((p < 6) ? (p) + 14 : -1) #if defined(__AVR_ATmega8__) #define digitalPinHasPWM(p) ((p) == 9 || (p) == 10 || (p) == 11) #else #define digitalPinHasPWM(p) ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11) #endif static const uint8_t SS = 10; static const uint8_t MOSI = 11; static const uint8_t MISO = 12; static const uint8_t SCK = 13; static const uint8_t SDA = 18; static const uint8_t SCL = 19; static const uint8_t LED_BUILTIN = 13; static const uint8_t A0 = 14; static const uint8_t A1 = 15; static const uint8_t A2 = 16; static const uint8_t A3 = 17; static const uint8_t A4 = 18; static const uint8_t A5 = 19; static const uint8_t A6 = 20; static const uint8_t A7 = 21; #define digitalPinToPCICR(p) (((p) >= 0 && (p) <= 21) ? (&PCICR) : ((uint8_t *)0)) #define digitalPinToPCICRbit(p) (((p) <= 7) ? 2 : (((p) <= 13) ? 0 : 1)) #define digitalPinToPCMSK(p) (((p) <= 7) ? (&PCMSK2) : (((p) <= 13) ? (&PCMSK0) : (((p) <= 21) ? (&PCMSK1) : ((uint8_t *)0)))) #define digitalPinToPCMSKbit(p) (((p) <= 7) ? (p) : (((p) <= 13) ? ((p) - 8) : ((p) - 14))) #ifdef ARDUINO_MAIN // On the Arduino board, digital pins are also used // for the analog output (software PWM). Analog input // pins are a separate set. // ATMEL ATMEGA8 & 168 / ARDUINO // // +-\/-+ // PC6 1| |28 PC5 (AI 5) // (D 0) PD0 2| |27 PC4 (AI 4) // (D 1) PD1 3| |26 PC3 (AI 3) // (D 2) PD2 4| |25 PC2 (AI 2) // PWM+ (D 3) PD3 5| |24 PC1 (AI 1) // (D 4) PD4 6| |23 PC0 (AI 0) // VCC 7| |22 GND // GND 8| |21 AREF // PB6 9| |20 AVCC // PB7 10| |19 PB5 (D 13) // PWM+ (D 5) PD5 11| |18 PB4 (D 12) // PWM+ (D 6) PD6 12| |17 PB3 (D 11) PWM // (D 7) PD7 13| |16 PB2 (D 10) PWM // (D 8) PB0 14| |15 PB1 (D 9) PWM // +----+ // // (PWM+ indicates the additional PWM pins on the ATmega168.) // ATMEL ATMEGA1280 / ARDUINO // // 0-7 PE0-PE7 works // 8-13 PB0-PB5 works // 14-21 PA0-PA7 works // 22-29 PH0-PH7 works // 30-35 PG5-PG0 works // 36-43 PC7-PC0 works // 44-51 PJ7-PJ0 works // 52-59 PL7-PL0 works // 60-67 PD7-PD0 works // A0-A7 PF0-PF7 // A8-A15 PK0-PK7 // these arrays map port names (e.g. port B) to the // appropriate addresses for various functions (e.g. reading // and writing) const uint16_t PROGMEM port_to_mode_PGM[] = { NOT_A_PORT, NOT_A_PORT, (uint16_t) &DDRB, (uint16_t) &DDRC, (uint16_t) &DDRD, }; const uint16_t PROGMEM port_to_output_PGM[] = { NOT_A_PORT, NOT_A_PORT, (uint16_t) &PORTB, (uint16_t) &PORTC, (uint16_t) &PORTD, }; const uint16_t PROGMEM port_to_input_PGM[] = { NOT_A_PORT, NOT_A_PORT, (uint16_t) &PINB, (uint16_t) &PINC, (uint16_t) &PIND, }; const uint8_t PROGMEM digital_pin_to_port_PGM[] = { PD, /* 0 */ PD, PD, PD, PD, PD, PD, PD, PB, /* 8 */ PB, PB, PB, PB, PB, PC, /* 14 */ PC, PC, PC, PC, PC, PB, /* 20 */ PB /* 21 */ }; const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] = { _BV(0), /* 0, port D */ _BV(1), _BV(2), _BV(3), _BV(4), _BV(5), _BV(6), _BV(7), _BV(0), /* 8, port B */ _BV(1), _BV(2), _BV(3), _BV(4), _BV(5), _BV(0), /* 14, port C */ _BV(1), _BV(2), _BV(3), _BV(4), _BV(5), _BV(6), /* 20 */ _BV(7), /* 21 */ }; const uint8_t PROGMEM digital_pin_to_timer_PGM[] = { NOT_ON_TIMER, /* 0 - port D */ NOT_ON_TIMER, NOT_ON_TIMER, // on the ATmega168, digital pin 3 has hardware pwm #if defined(__AVR_ATmega8__) NOT_ON_TIMER, #else TIMER2B, #endif NOT_ON_TIMER, // on the ATmega168, digital pins 5 and 6 have hardware pwm #if defined(__AVR_ATmega8__) NOT_ON_TIMER, NOT_ON_TIMER, #else TIMER0B, TIMER0A, #endif NOT_ON_TIMER, NOT_ON_TIMER, /* 8 - port B */ TIMER1A, TIMER1B, #if defined(__AVR_ATmega8__) TIMER2, #else TIMER2A, #endif NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, /* 14 - port C */ NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, }; #endif #endif
javastraat/ijduino_developer
hardware/pins_arduino.h
C
gpl-3.0
5,129
<?php /* + ----------------------------------------------------------------------------+ | e107 website system | | Copyright (C) 2001-2002 Steve Dunstan (jalist@e107.org) | Copyright (C) 2008-2010 e107 Inc (e107.org) | | Links plugin - help | | Released under the terms and conditions of the | GNU General Public License (http://gnu.org). | | $URL: https://e107.svn.sourceforge.net/svnroot/e107/trunk/e107_0.7/e107_plugins/links_page/e_help.php $ | $Revision: 11758 $ | $Id: e_help.php 11758 2010-09-07 12:18:00Z e107steved $ | $Author: e107steved $ +----------------------------------------------------------------------------+ */ if (!defined('e107_INIT')) { exit; } include_lan(e_PLUGIN.'links_page/languages/'.e_LANGUAGE.'_help.php'); if(!e_QUERY){ $text = LAN_ADMIN_HELP_1; }else{ if(e_QUERY){ $qs = explode(".", e_QUERY); if(is_numeric($qs[0])){ $from = array_shift($qs); }else{ $from = "0"; } } //##### LINK -------------------------------------------------- //manage Link items if($qs[0] == "link" && !isset($qs[1]) ){ $text = LAN_ADMIN_HELP_3; //edit }elseif($qs[0] == "link" && $qs[1] == "edit" && is_numeric($qs[2]) ){ $text = LAN_ADMIN_HELP_9; //view links in cat }elseif($qs[0] == "link" && $qs[1] == "view" && (is_numeric($qs[2]) || $qs[2] == "all") ){ $text = LAN_ADMIN_HELP_8; //create }elseif($qs[0] == "link" && $qs[1] == "create" && !isset($qs[2])){ $text = LAN_ADMIN_HELP_4; //create/post submitted }elseif($qs[0] == "link" && $qs[1] == "sn" && is_numeric($qs[2])){ $text = LAN_ADMIN_HELP_10; //##### SUBMITTED -------------------------------------------------- }elseif($qs[0] == "sn" && !isset($qs[1]) ){ $text = LAN_ADMIN_HELP_5; //##### OPTION -------------------------------------------------- }elseif($qs[0] == "opt" && !isset($qs[1]) ){ $text = LAN_ADMIN_HELP_6; //##### CATEGORY -------------------------------------------------- }elseif($qs[0] == "cat" && $qs[1] == "create" ){ $text = LAN_ADMIN_HELP_2; }elseif($qs[0] == "cat" && $qs[1] == "edit" && is_numeric($qs[2]) ){ $text = LAN_ADMIN_HELP_7; } } $ns -> tablerender(LAN_ADMIN_HELP_0, $text); ?>
kazancevsm/r107
0.1.5/plugins/links_page/e_help.php
PHP
gpl-3.0
2,203
var group__dma__mburst = [ [ "DMA_SxCR_MBURST_INCR16", "group__dma__mburst.html#gadaf6b33ae31b2cbde69244c3c0f441e8", null ], [ "DMA_SxCR_MBURST_INCR4", "group__dma__mburst.html#ga1d161291aabb811293bc78a8f9c30736", null ], [ "DMA_SxCR_MBURST_INCR8", "group__dma__mburst.html#ga8c35dd793bc079a92b3ec71d534b0cc8", null ], [ "DMA_SxCR_MBURST_SINGLE", "group__dma__mburst.html#gab2c82f24a4c949ffc18f882da93fda10", null ] ];
Aghosh993/TARS_codebase
libopencm3/doc/stm32l1/html/group__dma__mburst.js
JavaScript
gpl-3.0
434
/*global define*/ define([ '../Core/Color', '../Core/defined', '../Core/defineProperties', '../Core/Event', './createPropertyDescriptor', './Property' ], function( Color, defined, defineProperties, Event, createPropertyDescriptor, Property) { "use strict"; var defaultColor = Color.WHITE; var defaultOutlineColor = Color.BLACK; var defaultOutlineWidth = 0.0; /** * A {@link MaterialProperty} that maps to polyline outline {@link Material} uniforms. * @alias PolylineOutlineMaterialProperty * @constructor */ var PolylineOutlineMaterialProperty = function() { this._definitionChanged = new Event(); this._color = undefined; this._colorSubscription = undefined; this._outlineColor = undefined; this._outlineColorSubscription = undefined; this._outlineWidth = undefined; this._outlineWidthSubscription = undefined; }; defineProperties(PolylineOutlineMaterialProperty.prototype, { /** * Gets a value indicating if this property is constant. A property is considered * constant if getValue always returns the same result for the current definition. * @memberof PolylineOutlineMaterialProperty.prototype * * @type {Boolean} * @readonly */ isConstant : { get : function() { return Property.isConstant(this._color) && Property.isConstant(this._outlineColor) && Property.isConstant(this._outlineWidth); } }, /** * Gets the event that is raised whenever the definition of this property changes. * The definition is considered to have changed if a call to getValue would return * a different result for the same time. * @memberof PolylineOutlineMaterialProperty.prototype * * @type {Event} * @readonly */ definitionChanged : { get : function() { return this._definitionChanged; } }, /** * Gets or sets {@link Color} property which determines the polyline's color. * @memberof PolylineOutlineMaterialProperty.prototype * @type {Property} * @default new ConstantProperty(Color.WHITE) */ color : createPropertyDescriptor('color'), /** * Gets or sets the {@link Color} property which determines the polyline's outline color. * @memberof PolylineOutlineMaterialProperty.prototype * @type {Property} * @default new ConstantProperty(Color.BLACK) */ outlineColor : createPropertyDescriptor('outlineColor'), /** * Gets or sets the numberic property which determines the polyline's outline width. * @memberof PolylineOutlineMaterialProperty.prototype * @type {Property} * @default new ConstantProperty(0) */ outlineWidth : createPropertyDescriptor('outlineWidth') }); /** * Gets the {@link Material} type at the provided time. * * @param {JulianDate} time The time for which to retrieve the type. * @returns {String} The type of material. */ PolylineOutlineMaterialProperty.prototype.getType = function(time) { return 'PolylineOutline'; }; /** * Gets the value of the property at the provided time. * * @param {JulianDate} time The time for which to retrieve the value. * @param {Object} [result] The object to store the value into, if omitted, a new instance is created and returned. * @returns {Object} The modified result parameter or a new instance if the result parameter was not supplied. */ PolylineOutlineMaterialProperty.prototype.getValue = function(time, result) { if (!defined(result)) { result = {}; } result.color = Property.getValueOrClonedDefault(this._color, time, defaultColor, result.color); result.outlineColor = Property.getValueOrClonedDefault(this._outlineColor, time, defaultOutlineColor, result.outlineColor); result.outlineWidth = Property.getValueOrDefault(this._outlineWidth, time, defaultOutlineWidth); return result; }; /** * Compares this property to the provided property and returns * <code>true</code> if they are equal, <code>false</code> otherwise. * * @param {Property} [other] The other property. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise. */ PolylineOutlineMaterialProperty.prototype.equals = function(other) { return this === other || // (other instanceof PolylineOutlineMaterialProperty && // Property.equals(this._color, other._color) && // Property.equals(this._outlineColor, other._outlineColor) && // Property.equals(this._outlineWidth, other._outlineWidth)); }; /** * @private */ PolylineOutlineMaterialProperty.prototype._raiseDefinitionChanged = function(){ this._definitionChanged.raiseEvent(this); }; return PolylineOutlineMaterialProperty; });
rbensa01/Cesium-ESIPE-Project-District
projet/cesium/Source/DataSources/PolylineOutlineMaterialProperty.js
JavaScript
gpl-3.0
5,290
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.mina.filter.codec.statemachine; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; /** * {@link ProtocolDecoder} which uses a {@link DecodingState} to decode data. * Use a {@link DecodingStateMachine} as {@link DecodingState} to create * a state machine which can decode your protocol. * <p> * NOTE: This is a stateful decoder. You should create one instance per session. * </p> * * @author <a href="http://mina.apache.org">Apache MINA Project</a> */ public class DecodingStateProtocolDecoder implements ProtocolDecoder { private final DecodingState state; private final Queue<IoBuffer> undecodedBuffers = new ConcurrentLinkedQueue<IoBuffer>(); private IoSession session; /** * Creates a new instance using the specified {@link DecodingState} * instance. * * @param state the {@link DecodingState}. * @throws IllegalArgumentException if the specified state is <code>null</code>. */ public DecodingStateProtocolDecoder(DecodingState state) { if (state == null) { throw new IllegalArgumentException("state"); } this.state = state; } /** * {@inheritDoc} */ public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { if (this.session == null) { this.session = session; } else if (this.session != session) { throw new IllegalStateException(getClass().getSimpleName() + " is a stateful decoder. " + "You have to create one per session."); } undecodedBuffers.offer(in); for (;;) { IoBuffer b = undecodedBuffers.peek(); if (b == null) { break; } int oldRemaining = b.remaining(); state.decode(b, out); int newRemaining = b.remaining(); if (newRemaining != 0) { if (oldRemaining == newRemaining) { throw new IllegalStateException(DecodingState.class.getSimpleName() + " must " + "consume at least one byte per decode()."); } } else { undecodedBuffers.poll(); } } } /** * {@inheritDoc} */ public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception { state.finishDecode(out); } /** * {@inheritDoc} */ public void dispose(IoSession session) throws Exception { // Do nothing } }
DL7AD/SSR-Receiver
src/org/apache/mina/filter/codec/statemachine/DecodingStateProtocolDecoder.java
Java
gpl-3.0
3,613
/* * This file is part of wxSmith plugin for Code::Blocks Studio * Copyright (C) 2006-2007 Bartlomiej Swiecki * * wxSmith 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 3 of the License, or * (at your option) any later version. * * wxSmith is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with wxSmith. If not, see <http://www.gnu.org/licenses/>. * * $Revision$ * $Id$ * $HeadURL$ */ #ifndef WXSCOLOURPROPERTY_H #define WXSCOLOURPROPERTY_H #include "../../properties/wxsproperties.h" #include "../wxscodercontext.h" #include <wx/dialog.h> #if wxCHECK_VERSION(2, 9, 0) #include <wx/propgrid/editors.h> #else #include <wx/propgrid/propdev.h> #endif #include <wx/propgrid/advprops.h> #define wxsCOLOUR_DEFAULT (wxPG_COLOUR_CUSTOM - 1) /** \brief Class handling colour data for wxSmith */ class wxsColourData: public wxColourPropertyValue { public: wxsColourData(wxUint32 type, const wxColour &colour): wxColourPropertyValue(type,colour) {} wxsColourData(wxUint32 type = wxsCOLOUR_DEFAULT): wxColourPropertyValue(type) {} wxsColourData(const wxColour &colour): wxColourPropertyValue(colour) {} wxsColourData(const wxColourPropertyValue& cp): wxColourPropertyValue(cp) {} /** \brief Getting wxColour object from wxColourPropertyValue * \return wxColour class, if wxColour.Ok() will return false, default colour was used */ wxColour GetColour(); /** \brief Getting code building colour * \return code with colour or empty string if there's default colour */ wxString BuildCode(wxsCoderContext* Context); }; /** \brief Colour property - property used for handling wxColour property * * This property uses wxColourPropertyValue to keep data * */ class wxsColourProperty: public wxsProperty { public: /** \brief Ctor * \param PGName name of property in Property Grid * \param DataName name of property in data stuctures * \param ValueOffset offset of wxColourPropertyValue member (taken from wxsOFFSET macro) * \param Priority priority of this property */ wxsColourProperty( const wxString& PGName, const wxString& DataName, long ValueOffset, int Priority=100); /** \brief Returning type name */ virtual const wxString GetTypeName() { return _T("wxsColour"); } /** \brief Getting wxColour object from wxColourPropertyValue * \return wxColour class, if wxColour.Ok() will return false, default colour was used */ static wxColour GetColour(const wxColourPropertyValue& value); /** \brief Getting code building colour * \return code with colour or empty string if there's default colour */ static wxString GetColourCode(const wxColourPropertyValue& value,wxsCodingLang Language); protected: virtual void PGCreate(wxsPropertyContainer* Object,wxPropertyGridManager* Grid,wxPGId Parent); virtual bool PGRead(wxsPropertyContainer* Object,wxPropertyGridManager* Grid, wxPGId Id,long Index); virtual bool PGWrite(wxsPropertyContainer* Object,wxPropertyGridManager* Grid, wxPGId Id,long Index); virtual bool XmlRead(wxsPropertyContainer* Object,TiXmlElement* Element); virtual bool XmlWrite(wxsPropertyContainer* Object,TiXmlElement* Element); virtual bool PropStreamRead(wxsPropertyContainer* Object,wxsPropertyStream* Stream); virtual bool PropStreamWrite(wxsPropertyContainer* Object,wxsPropertyStream* Stream); private: long ValueOffset; }; /** \addtogroup ext_properties_macros * \{ */ /** \brief Macro automatically declaring colour property * \param ClassName name of class holding this property * \param VarName name of wxsColourData variable inside class * \param PGName name used in property grid * \param DataName name used in Xml / Data Streams */ #define WXS_COLOUR(ClassName,VarName,PGName,DataName) \ { static wxsColourProperty _Property(PGName,DataName,wxsOFFSET(ClassName,VarName)); \ Property(_Property); } /** \brief Macro automatically declaring colour property with custom priority * \param ClassName name of class holding this property * \param VarName name of wxsColourData variable inside class * \param PGName name used in property grid * \param DataName name used in Xml / Data Streams * \param Priority priority of this property */ #define WXS_COLOUR_P(ClassName,VarName,PGName,DataName,Priority) \ { static wxsColourProperty _Property(PGName,DataName,wxsOFFSET(ClassName,VarName),Priority); \ Property(_Property); } /** \} */ #endif
SaturnSDK/Saturn-SDK-IDE
src/plugins/contrib/wxSmith/wxwidgets/properties/wxscolourproperty.h
C
gpl-3.0
5,120
/* * hostapd / EAP-pwd (RFC 5931) server * Copyright (c) 2010, Dan Harkins <dharkins@lounge.org> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "includes.h" #include "common.h" #include "crypto/sha256.h" #include "crypto/ms_funcs.h" #include "crypto/crypto.h" #include "eap_server/eap_i.h" #include "eap_common/eap_pwd_common.h" struct eap_pwd_data { enum { PWD_ID_Req, PWD_Commit_Req, PWD_Confirm_Req, SUCCESS, FAILURE } state; u8 *id_peer; size_t id_peer_len; u8 *id_server; size_t id_server_len; u8 *password; size_t password_len; int password_hash; u8 *salt; size_t salt_len; u32 token; u16 group_num; u8 password_prep; EAP_PWD_group *grp; struct wpabuf *inbuf; size_t in_frag_pos; struct wpabuf *outbuf; size_t out_frag_pos; size_t mtu; struct crypto_bignum *k; struct crypto_bignum *private_value; struct crypto_bignum *peer_scalar; struct crypto_bignum *my_scalar; struct crypto_ec_point *my_element; struct crypto_ec_point *peer_element; u8 my_confirm[SHA256_MAC_LEN]; u8 msk[EAP_MSK_LEN]; u8 emsk[EAP_EMSK_LEN]; u8 session_id[1 + SHA256_MAC_LEN]; }; static const char * eap_pwd_state_txt(int state) { switch (state) { case PWD_ID_Req: return "PWD-ID-Req"; case PWD_Commit_Req: return "PWD-Commit-Req"; case PWD_Confirm_Req: return "PWD-Confirm-Req"; case SUCCESS: return "SUCCESS"; case FAILURE: return "FAILURE"; default: return "PWD-Unk"; } } static void eap_pwd_state(struct eap_pwd_data *data, int state) { wpa_printf(MSG_DEBUG, "EAP-pwd: %s -> %s", eap_pwd_state_txt(data->state), eap_pwd_state_txt(state)); data->state = state; } static void * eap_pwd_init(struct eap_sm *sm) { struct eap_pwd_data *data; if (sm->user == NULL || sm->user->password == NULL || sm->user->password_len == 0) { wpa_printf(MSG_INFO, "EAP-PWD (server): Password is not " "configured"); return NULL; } data = os_zalloc(sizeof(*data)); if (data == NULL) return NULL; data->group_num = sm->pwd_group; wpa_printf(MSG_DEBUG, "EAP-pwd: Selected group number %d", data->group_num); data->state = PWD_ID_Req; data->id_server = (u8 *) os_strdup("server"); if (data->id_server) data->id_server_len = os_strlen((char *) data->id_server); data->password = os_malloc(sm->user->password_len); if (data->password == NULL) { wpa_printf(MSG_INFO, "EAP-PWD: Memory allocation password " "fail"); bin_clear_free(data->id_server, data->id_server_len); os_free(data); return NULL; } data->password_len = sm->user->password_len; os_memcpy(data->password, sm->user->password, data->password_len); data->password_hash = sm->user->password_hash; data->salt_len = sm->user->salt_len; if (data->salt_len) { data->salt = os_memdup(sm->user->salt, sm->user->salt_len); if (!data->salt) { wpa_printf(MSG_INFO, "EAP-pwd: Memory allocation of salt failed"); bin_clear_free(data->id_server, data->id_server_len); bin_clear_free(data->password, data->password_len); os_free(data); return NULL; } } data->in_frag_pos = data->out_frag_pos = 0; data->inbuf = data->outbuf = NULL; /* use default MTU from RFC 5931 if not configured otherwise */ data->mtu = sm->fragment_size > 0 ? sm->fragment_size : 1020; return data; } static void eap_pwd_reset(struct eap_sm *sm, void *priv) { struct eap_pwd_data *data = priv; crypto_bignum_deinit(data->private_value, 1); crypto_bignum_deinit(data->peer_scalar, 1); crypto_bignum_deinit(data->my_scalar, 1); crypto_bignum_deinit(data->k, 1); crypto_ec_point_deinit(data->my_element, 1); crypto_ec_point_deinit(data->peer_element, 1); bin_clear_free(data->id_peer, data->id_peer_len); bin_clear_free(data->id_server, data->id_server_len); bin_clear_free(data->password, data->password_len); bin_clear_free(data->salt, data->salt_len); if (data->grp) { crypto_ec_deinit(data->grp->group); crypto_ec_point_deinit(data->grp->pwe, 1); os_free(data->grp); } wpabuf_free(data->inbuf); wpabuf_free(data->outbuf); bin_clear_free(data, sizeof(*data)); } static void eap_pwd_build_id_req(struct eap_sm *sm, struct eap_pwd_data *data, u8 id) { wpa_printf(MSG_DEBUG, "EAP-pwd: ID/Request"); /* * if we're fragmenting then we already have an id request, just return */ if (data->out_frag_pos) return; data->outbuf = wpabuf_alloc(sizeof(struct eap_pwd_id) + data->id_server_len); if (data->outbuf == NULL) { eap_pwd_state(data, FAILURE); return; } if (os_get_random((u8 *) &data->token, sizeof(data->token)) < 0) { wpabuf_free(data->outbuf); data->outbuf = NULL; eap_pwd_state(data, FAILURE); return; } wpa_hexdump_key(MSG_DEBUG, "EAP-pwd (server): password", data->password, data->password_len); if (data->salt_len) wpa_hexdump(MSG_DEBUG, "EAP-pwd (server): salt", data->salt, data->salt_len); /* * If this is a salted password then figure out how it was hashed * based on the length. */ if (data->salt_len) { switch (data->password_len) { case 20: data->password_prep = EAP_PWD_PREP_SSHA1; break; case 32: data->password_prep = EAP_PWD_PREP_SSHA256; break; case 64: data->password_prep = EAP_PWD_PREP_SSHA512; break; default: wpa_printf(MSG_INFO, "EAP-pwd (server): bad size %d for salted password", (int) data->password_len); eap_pwd_state(data, FAILURE); return; } } else { /* Otherwise, figure out whether it's MS hashed or plain */ data->password_prep = data->password_hash ? EAP_PWD_PREP_MS : EAP_PWD_PREP_NONE; } wpabuf_put_be16(data->outbuf, data->group_num); wpabuf_put_u8(data->outbuf, EAP_PWD_DEFAULT_RAND_FUNC); wpabuf_put_u8(data->outbuf, EAP_PWD_DEFAULT_PRF); wpabuf_put_data(data->outbuf, &data->token, sizeof(data->token)); wpabuf_put_u8(data->outbuf, data->password_prep); wpabuf_put_data(data->outbuf, data->id_server, data->id_server_len); } static void eap_pwd_build_commit_req(struct eap_sm *sm, struct eap_pwd_data *data, u8 id) { struct crypto_bignum *mask = NULL; u8 *scalar, *element; size_t prime_len, order_len; wpa_printf(MSG_DEBUG, "EAP-pwd: Commit/Request"); /* * if we're fragmenting then we already have an commit request, just * return */ if (data->out_frag_pos) return; prime_len = crypto_ec_prime_len(data->grp->group); order_len = crypto_ec_order_len(data->grp->group); data->private_value = crypto_bignum_init(); data->my_element = crypto_ec_point_init(data->grp->group); data->my_scalar = crypto_bignum_init(); mask = crypto_bignum_init(); if (!data->private_value || !data->my_element || !data->my_scalar || !mask) { wpa_printf(MSG_INFO, "EAP-PWD (server): scalar allocation " "fail"); goto fin; } if (eap_pwd_get_rand_mask(data->grp, data->private_value, mask, data->my_scalar) < 0) goto fin; if (crypto_ec_point_mul(data->grp->group, data->grp->pwe, mask, data->my_element) < 0) { wpa_printf(MSG_INFO, "EAP-PWD (server): element allocation " "fail"); eap_pwd_state(data, FAILURE); goto fin; } if (crypto_ec_point_invert(data->grp->group, data->my_element) < 0) { wpa_printf(MSG_INFO, "EAP-PWD (server): element inversion " "fail"); goto fin; } data->outbuf = wpabuf_alloc(2 * prime_len + order_len + (data->salt ? 1 + data->salt_len : 0)); if (data->outbuf == NULL) goto fin; /* If we're doing salted password prep, add the salt */ if (data->salt_len) { wpabuf_put_u8(data->outbuf, data->salt_len); wpabuf_put_data(data->outbuf, data->salt, data->salt_len); } /* We send the element as (x,y) followed by the scalar */ element = wpabuf_put(data->outbuf, 2 * prime_len); scalar = wpabuf_put(data->outbuf, order_len); crypto_bignum_to_bin(data->my_scalar, scalar, order_len, order_len); if (crypto_ec_point_to_bin(data->grp->group, data->my_element, element, element + prime_len) < 0) { wpa_printf(MSG_INFO, "EAP-PWD (server): point assignment " "fail"); goto fin; } fin: crypto_bignum_deinit(mask, 1); if (data->outbuf == NULL) eap_pwd_state(data, FAILURE); } static void eap_pwd_build_confirm_req(struct eap_sm *sm, struct eap_pwd_data *data, u8 id) { struct crypto_hash *hash = NULL; u8 conf[SHA256_MAC_LEN], *cruft = NULL, *ptr; u16 grp; size_t prime_len, order_len; wpa_printf(MSG_DEBUG, "EAP-pwd: Confirm/Request"); /* * if we're fragmenting then we already have an confirm request, just * return */ if (data->out_frag_pos) return; prime_len = crypto_ec_prime_len(data->grp->group); order_len = crypto_ec_order_len(data->grp->group); /* Each component of the cruft will be at most as big as the prime */ cruft = os_malloc(prime_len * 2); if (!cruft) { wpa_printf(MSG_INFO, "EAP-PWD (server): debug allocation " "fail"); goto fin; } /* * commit is H(k | server_element | server_scalar | peer_element | * peer_scalar | ciphersuite) */ hash = eap_pwd_h_init(); if (hash == NULL) goto fin; /* * Zero the memory each time because this is mod prime math and some * value may start with a few zeros and the previous one did not. * * First is k */ crypto_bignum_to_bin(data->k, cruft, prime_len, prime_len); eap_pwd_h_update(hash, cruft, prime_len); /* server element: x, y */ if (crypto_ec_point_to_bin(data->grp->group, data->my_element, cruft, cruft + prime_len) < 0) { wpa_printf(MSG_INFO, "EAP-PWD (server): confirm point " "assignment fail"); goto fin; } eap_pwd_h_update(hash, cruft, prime_len * 2); /* server scalar */ crypto_bignum_to_bin(data->my_scalar, cruft, order_len, order_len); eap_pwd_h_update(hash, cruft, order_len); /* peer element: x, y */ if (crypto_ec_point_to_bin(data->grp->group, data->peer_element, cruft, cruft + prime_len) < 0) { wpa_printf(MSG_INFO, "EAP-PWD (server): confirm point " "assignment fail"); goto fin; } eap_pwd_h_update(hash, cruft, prime_len * 2); /* peer scalar */ crypto_bignum_to_bin(data->peer_scalar, cruft, order_len, order_len); eap_pwd_h_update(hash, cruft, order_len); /* ciphersuite */ grp = htons(data->group_num); os_memset(cruft, 0, prime_len); ptr = cruft; os_memcpy(ptr, &grp, sizeof(u16)); ptr += sizeof(u16); *ptr = EAP_PWD_DEFAULT_RAND_FUNC; ptr += sizeof(u8); *ptr = EAP_PWD_DEFAULT_PRF; ptr += sizeof(u8); eap_pwd_h_update(hash, cruft, ptr - cruft); /* all done with the random function */ eap_pwd_h_final(hash, conf); hash = NULL; os_memcpy(data->my_confirm, conf, SHA256_MAC_LEN); data->outbuf = wpabuf_alloc(SHA256_MAC_LEN); if (data->outbuf == NULL) goto fin; wpabuf_put_data(data->outbuf, conf, SHA256_MAC_LEN); fin: bin_clear_free(cruft, prime_len * 2); if (data->outbuf == NULL) eap_pwd_state(data, FAILURE); eap_pwd_h_final(hash, NULL); } static struct wpabuf * eap_pwd_build_req(struct eap_sm *sm, void *priv, u8 id) { struct eap_pwd_data *data = priv; struct wpabuf *req; u8 lm_exch; const u8 *buf; u16 totlen = 0; size_t len; /* * if we're buffering response fragments then just ACK */ if (data->in_frag_pos) { wpa_printf(MSG_DEBUG, "EAP-pwd: ACKing a fragment!!"); req = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_PWD, EAP_PWD_HDR_SIZE, EAP_CODE_REQUEST, id); if (req == NULL) { eap_pwd_state(data, FAILURE); return NULL; } switch (data->state) { case PWD_ID_Req: wpabuf_put_u8(req, EAP_PWD_OPCODE_ID_EXCH); break; case PWD_Commit_Req: wpabuf_put_u8(req, EAP_PWD_OPCODE_COMMIT_EXCH); break; case PWD_Confirm_Req: wpabuf_put_u8(req, EAP_PWD_OPCODE_CONFIRM_EXCH); break; default: eap_pwd_state(data, FAILURE); /* just to be sure */ wpabuf_free(req); return NULL; } return req; } /* * build the data portion of a request */ switch (data->state) { case PWD_ID_Req: eap_pwd_build_id_req(sm, data, id); lm_exch = EAP_PWD_OPCODE_ID_EXCH; break; case PWD_Commit_Req: eap_pwd_build_commit_req(sm, data, id); lm_exch = EAP_PWD_OPCODE_COMMIT_EXCH; break; case PWD_Confirm_Req: eap_pwd_build_confirm_req(sm, data, id); lm_exch = EAP_PWD_OPCODE_CONFIRM_EXCH; break; default: wpa_printf(MSG_INFO, "EAP-pwd: Unknown state %d in build_req", data->state); eap_pwd_state(data, FAILURE); lm_exch = 0; /* hush now, sweet compiler */ break; } if (data->state == FAILURE) return NULL; /* * determine whether that data needs to be fragmented */ len = wpabuf_len(data->outbuf) - data->out_frag_pos; if ((len + EAP_PWD_HDR_SIZE) > data->mtu) { len = data->mtu - EAP_PWD_HDR_SIZE; EAP_PWD_SET_MORE_BIT(lm_exch); /* * if this is the first fragment, need to set the M bit * and add the total length to the eap_pwd_hdr */ if (data->out_frag_pos == 0) { EAP_PWD_SET_LENGTH_BIT(lm_exch); totlen = wpabuf_len(data->outbuf) + EAP_PWD_HDR_SIZE + sizeof(u16); len -= sizeof(u16); wpa_printf(MSG_DEBUG, "EAP-pwd: Fragmenting output, " "total length = %d", totlen); } wpa_printf(MSG_DEBUG, "EAP-pwd: Send a %d byte fragment", (int) len); } /* * alloc an eap request and populate it with the data */ req = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_PWD, EAP_PWD_HDR_SIZE + len + (totlen ? sizeof(u16) : 0), EAP_CODE_REQUEST, id); if (req == NULL) { eap_pwd_state(data, FAILURE); return NULL; } wpabuf_put_u8(req, lm_exch); if (EAP_PWD_GET_LENGTH_BIT(lm_exch)) wpabuf_put_be16(req, totlen); buf = wpabuf_head_u8(data->outbuf); wpabuf_put_data(req, buf + data->out_frag_pos, len); data->out_frag_pos += len; /* * either not fragged or last fragment, either way free up the data */ if (data->out_frag_pos >= wpabuf_len(data->outbuf)) { wpabuf_free(data->outbuf); data->outbuf = NULL; data->out_frag_pos = 0; } return req; } static Boolean eap_pwd_check(struct eap_sm *sm, void *priv, struct wpabuf *respData) { struct eap_pwd_data *data = priv; const u8 *pos; size_t len; pos = eap_hdr_validate(EAP_VENDOR_IETF, EAP_TYPE_PWD, respData, &len); if (pos == NULL || len < 1) { wpa_printf(MSG_INFO, "EAP-pwd: Invalid frame"); return TRUE; } wpa_printf(MSG_DEBUG, "EAP-pwd: Received frame: exch = %d, len = %d", EAP_PWD_GET_EXCHANGE(*pos), (int) len); if (data->state == PWD_ID_Req && ((EAP_PWD_GET_EXCHANGE(*pos)) == EAP_PWD_OPCODE_ID_EXCH)) return FALSE; if (data->state == PWD_Commit_Req && ((EAP_PWD_GET_EXCHANGE(*pos)) == EAP_PWD_OPCODE_COMMIT_EXCH)) return FALSE; if (data->state == PWD_Confirm_Req && ((EAP_PWD_GET_EXCHANGE(*pos)) == EAP_PWD_OPCODE_CONFIRM_EXCH)) return FALSE; wpa_printf(MSG_INFO, "EAP-pwd: Unexpected opcode=%d in state=%d", *pos, data->state); return TRUE; } static void eap_pwd_process_id_resp(struct eap_sm *sm, struct eap_pwd_data *data, const u8 *payload, size_t payload_len) { struct eap_pwd_id *id; const u8 *password; size_t password_len; u8 pwhashhash[16]; int res; if (payload_len < sizeof(struct eap_pwd_id)) { wpa_printf(MSG_INFO, "EAP-pwd: Invalid ID response"); return; } id = (struct eap_pwd_id *) payload; if ((data->group_num != be_to_host16(id->group_num)) || (id->random_function != EAP_PWD_DEFAULT_RAND_FUNC) || (os_memcmp(id->token, (u8 *)&data->token, sizeof(data->token))) || (id->prf != EAP_PWD_DEFAULT_PRF) || (id->prep != data->password_prep)) { wpa_printf(MSG_INFO, "EAP-pwd: peer changed parameters"); eap_pwd_state(data, FAILURE); return; } if (data->id_peer || data->grp) { wpa_printf(MSG_INFO, "EAP-pwd: data was already allocated"); return; } data->id_peer = os_malloc(payload_len - sizeof(struct eap_pwd_id)); if (data->id_peer == NULL) { wpa_printf(MSG_INFO, "EAP-PWD: memory allocation id fail"); return; } data->id_peer_len = payload_len - sizeof(struct eap_pwd_id); os_memcpy(data->id_peer, id->identity, data->id_peer_len); wpa_hexdump_ascii(MSG_DEBUG, "EAP-PWD (server): peer sent id of", data->id_peer, data->id_peer_len); data->grp = get_eap_pwd_group(data->group_num); if (data->grp == NULL) { wpa_printf(MSG_INFO, "EAP-PWD: failed to allocate memory for " "group"); return; } /* * If it's PREP_MS then hash the password again, otherwise regardless * of the prep the client is doing, the password we have is the one to * use to generate the password element. */ if (data->password_prep == EAP_PWD_PREP_MS) { res = hash_nt_password_hash(data->password, pwhashhash); if (res) return; password = pwhashhash; password_len = sizeof(pwhashhash); } else { password = data->password; password_len = data->password_len; } res = compute_password_element(data->grp, data->group_num, password, password_len, data->id_server, data->id_server_len, data->id_peer, data->id_peer_len, (u8 *) &data->token); forced_memzero(pwhashhash, sizeof(pwhashhash)); if (res) { wpa_printf(MSG_INFO, "EAP-PWD (server): unable to compute " "PWE"); return; } wpa_printf(MSG_DEBUG, "EAP-PWD (server): computed %d bit PWE...", (int) crypto_ec_prime_len_bits(data->grp->group)); eap_pwd_state(data, PWD_Commit_Req); } static void eap_pwd_process_commit_resp(struct eap_sm *sm, struct eap_pwd_data *data, const u8 *payload, size_t payload_len) { const u8 *ptr; struct crypto_ec_point *K = NULL; int res = 0; size_t prime_len, order_len; wpa_printf(MSG_DEBUG, "EAP-pwd: Received commit response"); prime_len = crypto_ec_prime_len(data->grp->group); order_len = crypto_ec_order_len(data->grp->group); if (payload_len != 2 * prime_len + order_len) { wpa_printf(MSG_INFO, "EAP-pwd: Unexpected Commit payload length %u (expected %u)", (unsigned int) payload_len, (unsigned int) (2 * prime_len + order_len)); goto fin; } data->k = crypto_bignum_init(); K = crypto_ec_point_init(data->grp->group); if (!data->k || !K) { wpa_printf(MSG_INFO, "EAP-PWD (server): peer data allocation " "fail"); goto fin; } /* element, x then y, followed by scalar */ ptr = payload; data->peer_element = eap_pwd_get_element(data->grp, ptr); if (!data->peer_element) { wpa_printf(MSG_INFO, "EAP-PWD (server): setting peer element " "fail"); goto fin; } ptr += prime_len * 2; data->peer_scalar = eap_pwd_get_scalar(data->grp, ptr); if (!data->peer_scalar) { wpa_printf(MSG_INFO, "EAP-PWD (server): peer data allocation " "fail"); goto fin; } /* detect reflection attacks */ if (crypto_bignum_cmp(data->my_scalar, data->peer_scalar) == 0 || crypto_ec_point_cmp(data->grp->group, data->my_element, data->peer_element) == 0) { wpa_printf(MSG_INFO, "EAP-PWD (server): detected reflection attack!"); goto fin; } /* compute the shared key, k */ if ((crypto_ec_point_mul(data->grp->group, data->grp->pwe, data->peer_scalar, K) < 0) || (crypto_ec_point_add(data->grp->group, K, data->peer_element, K) < 0) || (crypto_ec_point_mul(data->grp->group, K, data->private_value, K) < 0)) { wpa_printf(MSG_INFO, "EAP-PWD (server): computing shared key " "fail"); goto fin; } /* * This check is strictly speaking just for the case where * co-factor > 1 but it was suggested that even though this is probably * never going to happen it is a simple and safe check "just to be * sure" so let's be safe. */ if (crypto_ec_point_is_at_infinity(data->grp->group, K)) { wpa_printf(MSG_INFO, "EAP-PWD (server): shared key point is " "at infinity"); goto fin; } if (crypto_ec_point_x(data->grp->group, K, data->k)) { wpa_printf(MSG_INFO, "EAP-PWD (server): unable to extract " "shared secret from secret point"); goto fin; } res = 1; fin: crypto_ec_point_deinit(K, 1); if (res) eap_pwd_state(data, PWD_Confirm_Req); else eap_pwd_state(data, FAILURE); } static void eap_pwd_process_confirm_resp(struct eap_sm *sm, struct eap_pwd_data *data, const u8 *payload, size_t payload_len) { struct crypto_hash *hash = NULL; u32 cs; u16 grp; u8 conf[SHA256_MAC_LEN], *cruft = NULL, *ptr; size_t prime_len, order_len; prime_len = crypto_ec_prime_len(data->grp->group); order_len = crypto_ec_order_len(data->grp->group); if (payload_len != SHA256_MAC_LEN) { wpa_printf(MSG_INFO, "EAP-pwd: Unexpected Confirm payload length %u (expected %u)", (unsigned int) payload_len, SHA256_MAC_LEN); goto fin; } /* build up the ciphersuite: group | random_function | prf */ grp = htons(data->group_num); ptr = (u8 *) &cs; os_memcpy(ptr, &grp, sizeof(u16)); ptr += sizeof(u16); *ptr = EAP_PWD_DEFAULT_RAND_FUNC; ptr += sizeof(u8); *ptr = EAP_PWD_DEFAULT_PRF; /* each component of the cruft will be at most as big as the prime */ cruft = os_malloc(prime_len * 2); if (!cruft) { wpa_printf(MSG_INFO, "EAP-PWD (peer): allocation fail"); goto fin; } /* * commit is H(k | peer_element | peer_scalar | server_element | * server_scalar | ciphersuite) */ hash = eap_pwd_h_init(); if (hash == NULL) goto fin; /* k */ crypto_bignum_to_bin(data->k, cruft, prime_len, prime_len); eap_pwd_h_update(hash, cruft, prime_len); /* peer element: x, y */ if (crypto_ec_point_to_bin(data->grp->group, data->peer_element, cruft, cruft + prime_len) < 0) { wpa_printf(MSG_INFO, "EAP-PWD (server): confirm point " "assignment fail"); goto fin; } eap_pwd_h_update(hash, cruft, prime_len * 2); /* peer scalar */ crypto_bignum_to_bin(data->peer_scalar, cruft, order_len, order_len); eap_pwd_h_update(hash, cruft, order_len); /* server element: x, y */ if (crypto_ec_point_to_bin(data->grp->group, data->my_element, cruft, cruft + prime_len) < 0) { wpa_printf(MSG_INFO, "EAP-PWD (server): confirm point " "assignment fail"); goto fin; } eap_pwd_h_update(hash, cruft, prime_len * 2); /* server scalar */ crypto_bignum_to_bin(data->my_scalar, cruft, order_len, order_len); eap_pwd_h_update(hash, cruft, order_len); /* ciphersuite */ eap_pwd_h_update(hash, (u8 *) &cs, sizeof(u32)); /* all done */ eap_pwd_h_final(hash, conf); hash = NULL; ptr = (u8 *) payload; if (os_memcmp_const(conf, ptr, SHA256_MAC_LEN)) { wpa_printf(MSG_INFO, "EAP-PWD (server): confirm did not " "verify"); goto fin; } wpa_printf(MSG_DEBUG, "EAP-pwd (server): confirm verified"); if (compute_keys(data->grp, data->k, data->peer_scalar, data->my_scalar, conf, data->my_confirm, &cs, data->msk, data->emsk, data->session_id) < 0) eap_pwd_state(data, FAILURE); else eap_pwd_state(data, SUCCESS); fin: bin_clear_free(cruft, prime_len * 2); eap_pwd_h_final(hash, NULL); } static void eap_pwd_process(struct eap_sm *sm, void *priv, struct wpabuf *respData) { struct eap_pwd_data *data = priv; const u8 *pos; size_t len; u8 lm_exch; u16 tot_len; pos = eap_hdr_validate(EAP_VENDOR_IETF, EAP_TYPE_PWD, respData, &len); if ((pos == NULL) || (len < 1)) { wpa_printf(MSG_INFO, "Bad EAP header! pos %s and len = %d", (pos == NULL) ? "is NULL" : "is not NULL", (int) len); return; } lm_exch = *pos; pos++; /* skip over the bits and the exch */ len--; /* * if we're fragmenting then this should be an ACK with no data, * just return and continue fragmenting in the "build" section above */ if (data->out_frag_pos) { if (len > 1) wpa_printf(MSG_INFO, "EAP-pwd: Bad response! " "Fragmenting but not an ACK"); else wpa_printf(MSG_DEBUG, "EAP-pwd: received ACK from " "peer"); return; } /* * if we're receiving fragmented packets then we need to buffer... * * the first fragment has a total length */ if (EAP_PWD_GET_LENGTH_BIT(lm_exch)) { if (len < 2) { wpa_printf(MSG_DEBUG, "EAP-pwd: Frame too short to contain Total-Length field"); return; } tot_len = WPA_GET_BE16(pos); wpa_printf(MSG_DEBUG, "EAP-pwd: Incoming fragments, total " "length = %d", tot_len); if (tot_len > 15000) return; if (data->inbuf) { wpa_printf(MSG_DEBUG, "EAP-pwd: Unexpected new fragment start when previous fragment is still in use"); return; } data->inbuf = wpabuf_alloc(tot_len); if (data->inbuf == NULL) { wpa_printf(MSG_INFO, "EAP-pwd: Out of memory to " "buffer fragments!"); return; } data->in_frag_pos = 0; pos += sizeof(u16); len -= sizeof(u16); } /* * the first and all intermediate fragments have the M bit set */ if (EAP_PWD_GET_MORE_BIT(lm_exch) || data->in_frag_pos) { if (!data->inbuf) { wpa_printf(MSG_DEBUG, "EAP-pwd: No buffer for reassembly"); eap_pwd_state(data, FAILURE); return; } if ((data->in_frag_pos + len) > wpabuf_size(data->inbuf)) { wpa_printf(MSG_DEBUG, "EAP-pwd: Buffer overflow " "attack detected! (%d+%d > %d)", (int) data->in_frag_pos, (int) len, (int) wpabuf_size(data->inbuf)); eap_pwd_state(data, FAILURE); return; } wpabuf_put_data(data->inbuf, pos, len); data->in_frag_pos += len; } if (EAP_PWD_GET_MORE_BIT(lm_exch)) { wpa_printf(MSG_DEBUG, "EAP-pwd: Got a %d byte fragment", (int) len); return; } /* * last fragment won't have the M bit set (but we're obviously * buffering fragments so that's how we know it's the last) */ if (data->in_frag_pos && data->inbuf) { pos = wpabuf_head_u8(data->inbuf); len = data->in_frag_pos; wpa_printf(MSG_DEBUG, "EAP-pwd: Last fragment, %d bytes", (int) len); } switch (EAP_PWD_GET_EXCHANGE(lm_exch)) { case EAP_PWD_OPCODE_ID_EXCH: eap_pwd_process_id_resp(sm, data, pos, len); break; case EAP_PWD_OPCODE_COMMIT_EXCH: eap_pwd_process_commit_resp(sm, data, pos, len); break; case EAP_PWD_OPCODE_CONFIRM_EXCH: eap_pwd_process_confirm_resp(sm, data, pos, len); break; } /* * if we had been buffering fragments, here's a great place * to clean up */ if (data->in_frag_pos) { wpabuf_free(data->inbuf); data->inbuf = NULL; data->in_frag_pos = 0; } } static u8 * eap_pwd_getkey(struct eap_sm *sm, void *priv, size_t *len) { struct eap_pwd_data *data = priv; u8 *key; if (data->state != SUCCESS) return NULL; key = os_memdup(data->msk, EAP_MSK_LEN); if (key == NULL) return NULL; *len = EAP_MSK_LEN; return key; } static u8 * eap_pwd_get_emsk(struct eap_sm *sm, void *priv, size_t *len) { struct eap_pwd_data *data = priv; u8 *key; if (data->state != SUCCESS) return NULL; key = os_memdup(data->emsk, EAP_EMSK_LEN); if (key == NULL) return NULL; *len = EAP_EMSK_LEN; return key; } static Boolean eap_pwd_is_success(struct eap_sm *sm, void *priv) { struct eap_pwd_data *data = priv; return data->state == SUCCESS; } static Boolean eap_pwd_is_done(struct eap_sm *sm, void *priv) { struct eap_pwd_data *data = priv; return (data->state == SUCCESS) || (data->state == FAILURE); } static u8 * eap_pwd_get_session_id(struct eap_sm *sm, void *priv, size_t *len) { struct eap_pwd_data *data = priv; u8 *id; if (data->state != SUCCESS) return NULL; id = os_memdup(data->session_id, 1 + SHA256_MAC_LEN); if (id == NULL) return NULL; *len = 1 + SHA256_MAC_LEN; return id; } int eap_server_pwd_register(void) { struct eap_method *eap; eap = eap_server_method_alloc(EAP_SERVER_METHOD_INTERFACE_VERSION, EAP_VENDOR_IETF, EAP_TYPE_PWD, "PWD"); if (eap == NULL) return -1; eap->init = eap_pwd_init; eap->reset = eap_pwd_reset; eap->buildReq = eap_pwd_build_req; eap->check = eap_pwd_check; eap->process = eap_pwd_process; eap->isDone = eap_pwd_is_done; eap->getKey = eap_pwd_getkey; eap->get_emsk = eap_pwd_get_emsk; eap->isSuccess = eap_pwd_is_success; eap->getSessionId = eap_pwd_get_session_id; return eap_server_method_register(eap); }
s0lst1c3/eaphammer
local/hostapd-eaphammer/src/eap_server/eap_server_pwd.c
C
gpl-3.0
27,805
/* A simple event-driven programming library. Originally I wrote this code * for the Jim's event-loop (Jim is a Tcl interpreter) but later translated * it in form of a library for easy reuse. * * Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <poll.h> #include <string.h> #include <time.h> #include <errno.h> #include "ae.h" #include "config.h" /* Include the best multiplexing layer supported by this system. * The following should be ordered by performances, descending. */ #ifdef HAVE_EVPORT #include "ae_evport.c" #else #ifdef HAVE_EPOLL #include "ae_epoll.c" #else #ifdef HAVE_KQUEUE #include "ae_kqueue.c" #else #include "ae_select.c" #endif #endif #endif aeEventLoop *aeCreateEventLoop(int setsize) { aeEventLoop *eventLoop; int i; if ((eventLoop = (aeEventLoop *)malloc(sizeof(*eventLoop))) == NULL) goto err; eventLoop->events = (aeFileEvent*)malloc(sizeof(aeFileEvent)*setsize); eventLoop->fired = (aeFiredEvent*)malloc(sizeof(aeFiredEvent)*setsize); if (eventLoop->events == NULL || eventLoop->fired == NULL) goto err; eventLoop->setsize = setsize; eventLoop->lastTime = time(NULL); eventLoop->timeEventHead = NULL; eventLoop->timeEventNextId = 0; eventLoop->stop = 0; eventLoop->maxfd = -1; eventLoop->beforesleep = NULL; if (aeApiCreate(eventLoop) == -1) goto err; /* Events with mask == AE_NONE are not set. So let's initialize the * vector with it. */ for (i = 0; i < setsize; i++) eventLoop->events[i].mask = AE_NONE; return eventLoop; err: if (eventLoop) { free(eventLoop->events); free(eventLoop->fired); free(eventLoop); } return NULL; } void aeDeleteEventLoop(aeEventLoop *eventLoop) { aeApiFree(eventLoop); free(eventLoop->events); free(eventLoop->fired); free(eventLoop); } void aeStop(aeEventLoop *eventLoop) { eventLoop->stop = 1; } int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask, aeFileProc *proc, void *clientData) { if (fd >= eventLoop->setsize) { errno = ERANGE; return AE_ERR; } aeFileEvent *fe = &eventLoop->events[fd]; if (aeApiAddEvent(eventLoop, fd, mask) == -1) return AE_ERR; fe->mask |= mask; if (mask & AE_READABLE) fe->rfileProc = proc; if (mask & AE_WRITABLE) fe->wfileProc = proc; fe->clientData = clientData; if (fd > eventLoop->maxfd) eventLoop->maxfd = fd; return AE_OK; } void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask) { if (fd >= eventLoop->setsize) return; aeFileEvent *fe = &eventLoop->events[fd]; if (fe->mask == AE_NONE) return; fe->mask = fe->mask & (~mask); if (fd == eventLoop->maxfd && fe->mask == AE_NONE) { /* Update the max fd */ int j; for (j = eventLoop->maxfd-1; j >= 0; j--) if (eventLoop->events[j].mask != AE_NONE) break; eventLoop->maxfd = j; } aeApiDelEvent(eventLoop, fd, mask); } int aeGetFileEvents(aeEventLoop *eventLoop, int fd) { if (fd >= eventLoop->setsize) return 0; aeFileEvent *fe = &eventLoop->events[fd]; return fe->mask; } static void aeGetTime(long *seconds, long *milliseconds) { struct timeval tv; gettimeofday(&tv, NULL); *seconds = tv.tv_sec; *milliseconds = tv.tv_usec/1000; } static void aeAddMillisecondsToNow(long long milliseconds, long *sec, long *ms) { long cur_sec, cur_ms, when_sec, when_ms; aeGetTime(&cur_sec, &cur_ms); when_sec = cur_sec + milliseconds/1000; when_ms = cur_ms + milliseconds%1000; if (when_ms >= 1000) { when_sec ++; when_ms -= 1000; } *sec = when_sec; *ms = when_ms; } long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds, aeTimeProc *proc, void *clientData, aeEventFinalizerProc *finalizerProc) { long long id = eventLoop->timeEventNextId++; aeTimeEvent *te; te = (aeTimeEvent *)malloc(sizeof(*te)); if (te == NULL) return AE_ERR; te->id = id; aeAddMillisecondsToNow(milliseconds,&te->when_sec,&te->when_ms); te->timeProc = proc; te->finalizerProc = finalizerProc; te->clientData = clientData; te->next = eventLoop->timeEventHead; eventLoop->timeEventHead = te; return id; } int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id) { aeTimeEvent *te, *prev = NULL; te = eventLoop->timeEventHead; while(te) { if (te->id == id) { if (prev == NULL) eventLoop->timeEventHead = te->next; else prev->next = te->next; if (te->finalizerProc) te->finalizerProc(eventLoop, te->clientData); free(te); return AE_OK; } prev = te; te = te->next; } return AE_ERR; /* NO event with the specified ID found */ } /* Search the first timer to fire. * This operation is useful to know how many time the select can be * put in sleep without to delay any event. * If there are no timers NULL is returned. * * Note that's O(N) since time events are unsorted. * Possible optimizations (not needed by Redis so far, but...): * 1) Insert the event in order, so that the nearest is just the head. * Much better but still insertion or deletion of timers is O(N). * 2) Use a skiplist to have this operation as O(1) and insertion as O(log(N)). */ static aeTimeEvent *aeSearchNearestTimer(aeEventLoop *eventLoop) { aeTimeEvent *te = eventLoop->timeEventHead; aeTimeEvent *nearest = NULL; while(te) { if (!nearest || te->when_sec < nearest->when_sec || (te->when_sec == nearest->when_sec && te->when_ms < nearest->when_ms)) nearest = te; te = te->next; } return nearest; } /* Process time events */ static int processTimeEvents(aeEventLoop *eventLoop) { int processed = 0; aeTimeEvent *te; long long maxId; time_t now = time(NULL); /* If the system clock is moved to the future, and then set back to the * right value, time events may be delayed in a random way. Often this * means that scheduled operations will not be performed soon enough. * * Here we try to detect system clock skews, and force all the time * events to be processed ASAP when this happens: the idea is that * processing events earlier is less dangerous than delaying them * indefinitely, and practice suggests it is. */ if (now < eventLoop->lastTime) { te = eventLoop->timeEventHead; while(te) { te->when_sec = 0; te = te->next; } } eventLoop->lastTime = now; te = eventLoop->timeEventHead; maxId = eventLoop->timeEventNextId-1; while(te) { long now_sec, now_ms; long long id; if (te->id > maxId) { te = te->next; continue; } aeGetTime(&now_sec, &now_ms); if (now_sec > te->when_sec || (now_sec == te->when_sec && now_ms >= te->when_ms)) { int retval; id = te->id; retval = te->timeProc(eventLoop, id, te->clientData); processed++; /* After an event is processed our time event list may * no longer be the same, so we restart from head. * Still we make sure to don't process events registered * by event handlers itself in order to don't loop forever. * To do so we saved the max ID we want to handle. * * FUTURE OPTIMIZATIONS: * Note that this is NOT great algorithmically. Redis uses * a single time event so it's not a problem but the right * way to do this is to add the new elements on head, and * to flag deleted elements in a special way for later * deletion (putting references to the nodes to delete into * another linked list). */ if (retval != AE_NOMORE) { aeAddMillisecondsToNow(retval,&te->when_sec,&te->when_ms); } else { aeDeleteTimeEvent(eventLoop, id); } te = eventLoop->timeEventHead; } else { te = te->next; } } return processed; } /* Process every pending time event, then every pending file event * (that may be registered by time event callbacks just processed). * Without special flags the function sleeps until some file event * fires, or when the next time event occurs (if any). * * If flags is 0, the function does nothing and returns. * if flags has AE_ALL_EVENTS set, all the kind of events are processed. * if flags has AE_FILE_EVENTS set, file events are processed. * if flags has AE_TIME_EVENTS set, time events are processed. * if flags has AE_DONT_WAIT set the function returns ASAP until all * the events that's possible to process without to wait are processed. * * The function returns the number of events processed. */ int aeProcessEvents(aeEventLoop *eventLoop, int flags) { int processed = 0, numevents; /* Nothing to do? return ASAP */ if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) return 0; /* Note that we want call select() even if there are no * file events to process as long as we want to process time * events, in order to sleep until the next time event is ready * to fire. */ if (eventLoop->maxfd != -1 || ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) { int j; aeTimeEvent *shortest = NULL; struct timeval tv, *tvp; if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT)) shortest = aeSearchNearestTimer(eventLoop); if (shortest) { long now_sec, now_ms; /* Calculate the time missing for the nearest * timer to fire. */ aeGetTime(&now_sec, &now_ms); tvp = &tv; tvp->tv_sec = shortest->when_sec - now_sec; if (shortest->when_ms < now_ms) { tvp->tv_usec = ((shortest->when_ms+1000) - now_ms)*1000; tvp->tv_sec --; } else { tvp->tv_usec = (shortest->when_ms - now_ms)*1000; } if (tvp->tv_sec < 0) tvp->tv_sec = 0; if (tvp->tv_usec < 0) tvp->tv_usec = 0; } else { /* If we have to check for events but need to return * ASAP because of AE_DONT_WAIT we need to set the timeout * to zero */ if (flags & AE_DONT_WAIT) { tv.tv_sec = tv.tv_usec = 0; tvp = &tv; } else { /* Otherwise we can block */ tvp = NULL; /* wait forever */ } } numevents = aeApiPoll(eventLoop, tvp); for (j = 0; j < numevents; j++) { aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd]; int mask = eventLoop->fired[j].mask; int fd = eventLoop->fired[j].fd; int rfired = 0; /* note the fe->mask & mask & ... code: maybe an already processed * event removed an element that fired and we still didn't * processed, so we check if the event is still valid. */ if (fe->mask & mask & AE_READABLE) { rfired = 1; fe->rfileProc(eventLoop,fd,fe->clientData,mask); } if (fe->mask & mask & AE_WRITABLE) { if (!rfired || fe->wfileProc != fe->rfileProc) fe->wfileProc(eventLoop,fd,fe->clientData,mask); } processed++; } } /* Check time events */ if (flags & AE_TIME_EVENTS) processed += processTimeEvents(eventLoop); return processed; /* return the number of processed file/time events */ } /* Wait for milliseconds until the given file descriptor becomes * writable/readable/exception */ int aeWait(int fd, int mask, long long milliseconds) { struct pollfd pfd; int retmask = 0, retval; memset(&pfd, 0, sizeof(pfd)); pfd.fd = fd; if (mask & AE_READABLE) pfd.events |= POLLIN; if (mask & AE_WRITABLE) pfd.events |= POLLOUT; if ((retval = poll(&pfd, 1, milliseconds))== 1) { if (pfd.revents & POLLIN) retmask |= AE_READABLE; if (pfd.revents & POLLOUT) retmask |= AE_WRITABLE; if (pfd.revents & POLLERR) retmask |= AE_WRITABLE; if (pfd.revents & POLLHUP) retmask |= AE_WRITABLE; return retmask; } else { return retval; } } void aeMain(aeEventLoop *eventLoop) { eventLoop->stop = 0; while (!eventLoop->stop) { if (eventLoop->beforesleep != NULL) eventLoop->beforesleep(eventLoop); aeProcessEvents(eventLoop, AE_ALL_EVENTS); } } char *aeGetApiName(void) { return aeApiName(); } void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep) { eventLoop->beforesleep = beforesleep; }
weim0000/RedisSentinelClient
cpp/src/ae.c
C
gpl-3.0
14,769
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.trial.distreporter}. """ from cStringIO import StringIO from twisted.trial._dist.distreporter import DistReporter from twisted.trial.unittest import TestCase from twisted.trial.reporter import TreeReporter class DistReporterTestCase(TestCase): """ Tests for L{DistReporter}. """ def setUp(self): self.stream = StringIO() self.distReporter = DistReporter(TreeReporter(self.stream)) self.test = TestCase() def test_startSuccessStop(self): """ Success output only gets sent to the stream after the test has stopped. """ self.distReporter.startTest(self.test) self.assertEqual(self.stream.getvalue(), "") self.distReporter.addSuccess(self.test) self.assertEqual(self.stream.getvalue(), "") self.distReporter.stopTest(self.test) self.assertNotEqual(self.stream.getvalue(), "") def test_startErrorStop(self): """ Error output only gets sent to the stream after the test has stopped. """ self.distReporter.startTest(self.test) self.assertEqual(self.stream.getvalue(), "") self.distReporter.addError(self.test, "error") self.assertEqual(self.stream.getvalue(), "") self.distReporter.stopTest(self.test) self.assertNotEqual(self.stream.getvalue(), "") def test_forwardedMethods(self): """ Calling methods of L{DistReporter} add calls to the running queue of the test. """ self.distReporter.startTest(self.test) self.distReporter.addFailure(self.test, "foo") self.distReporter.addError(self.test, "bar") self.distReporter.addSkip(self.test, "egg") self.distReporter.addUnexpectedSuccess(self.test, "spam") self.distReporter.addExpectedFailure(self.test, "err", "foo") self.assertEqual(len(self.distReporter.running[self.test.id()]), 6)
geodrinx/gearthview
ext-libs/twisted/trial/_dist/test/test_distreporter.py
Python
gpl-3.0
2,019
<!--[if IE 7]> <!DOCTYPE> <html lang="en"> <head> <![endif]--> <!--[if IE 8]> <!DOCTYPE> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/> <![endif]--> <![if gte IE 9]> <!DOCTYPE HTML> <html lang="en"> <head> <![endif]> <title>Chart 2D</title> <style type="text/css"> @import "../../../dojo/resources/dojo.css"; @import "../../../dijit/tests/css/dijitTests.css"; </style> <script type="text/javascript" src="../../../dojo/dojo.js" data-dojo-config="isDebug: true"></script> <script type="text/javascript"> dojo.require("dojox.charting.Chart"); dojo.require("dojox.charting.axis2d.Default"); dojo.require("dojox.charting.plot2d.Default"); dojo.require("dojox.charting.plot2d.Areas"); dojo.require("dojox.charting.plot2d.Markers"); dojo.require("dojox.charting.plot2d.MarkersOnly"); dojo.require("dojox.charting.plot2d.StackedLines"); dojo.require("dojox.charting.plot2d.StackedAreas"); dojo.require("dojox.charting.plot2d.Bars"); dojo.require("dojox.charting.plot2d.ClusteredBars"); dojo.require("dojox.charting.plot2d.StackedBars"); dojo.require("dojox.charting.plot2d.ClusteredColumns"); dojo.require("dojox.charting.plot2d.StackedColumns"); dojo.require("dojox.charting.plot2d.Bubble"); dojo.require("dojox.charting.plot2d.Grid"); dojo.require("dojox.charting.plot2d.Candlesticks"); dojo.require("dojox.charting.plot2d.OHLC"); dojo.require("dojox.charting.plot2d.Scatter"); dojo.require("dojox.charting.themes.Shrooms"); dojo.require("dojox.charting.themes.PlotKit.blue"); dojo.require("dojox.charting.themes.PlotKit.cyan"); dojo.require("dojox.charting.themes.PlotKit.green"); dojo.require("dojox.charting.themes.Ireland"); dojo.require("dojox.charting.themes.SageToLime"); dojo.require("dojox.charting.themes.Minty"); dojo.require("dojox.charting.themes.Tufte"); dojo.require("dojox.dtl"); dojo.require("dojox.dtl.Context"); charts = [ { description: "Clustered columns with positive and negative values, readable theme.", makeChart: function(node){ (new dojox.charting.Chart(node)). setTheme(dojox.charting.themes.Tufte). addAxis("x", { fixLower: "minor", fixUpper: "minor", natural: true }). addAxis("y", { vertical: true, fixLower: "major", fixUpper: "major", includeZero: true }). addPlot("default", { type: "ClusteredColumns", gap: 10 }). addSeries("Series A", [ 2, 1, 0.5, -1, -2 ] ). addSeries("Series B", [ -2, -1, -0.5, 1, 2 ] ). addSeries("Series C", [ 1, 0.5, -1, -2, -3 ] ). addSeries("Series D", [ 0.7, 1.5, -1.2, -1.25, 3 ] ). render(); } }, { description: "Bubble chart, green theme.", makeChart: function(node){ (new dojox.charting.Chart(node)). setTheme(dojox.charting.themes.SageToLime). addPlot("default", { type: "Bubble", shadow: {dx: 1, dy: 1, width: 2, color: [0, 0, 0, 0.3]} }). addAxis("x", { min: 0, max: 6, majorTick: { stroke: "black", length: 3 }, minorTick: { stroke: "gray", length: 3 } }). addAxis("y", { vertical: true, min: 0, max: 10, majorTick: { stroke: "black", length: 3 }, minorTick: { stroke: "gray", length: 3 } }). addSeries("Series A", [ { x: 0.5, y: 5, size: 1.4 }, { x: 1.5, y: 1.5, size: 4.5 }, { x: 2, y: 9, size:1.5 }, { x: 5, y: 0.3, size:0.8 } ]). addSeries("Series B", [ { x: 0.3, y: 8, size: 2.5 }, { x: 4, y: 6, size:1.1 }, { x: 5.5, y: 2, size: 3.2 } ]). render(); } }, { description: "Lines, calculated labels", makeChart: function(node){ (new dojox.charting.Chart(node)). addAxis("x", { majorLabels: true, minorLabels: true, includeZero: true, minorTicks: false, microTicks: false, majorTickStep: 2, htmlLabels: true, labelFunc: function(value){ return value + " s"; }, maxLabelSize: 30, fixUpper: "major", fixLower: "major", majorTick: { length: 3 } }). addAxis("y", { labelFunc: function(value){ return value + " thingers"; }, maxLabelSize: 50, vertical: true, // htmlLabels: false, microTicks: true, minorTicks: true, majorTick: { stroke: "black", length: 3 } }). addSeries("Series A", [ 1, 2, 1, 2, 1, 2, 1 ]). addSeries("Series B", [ 2, 1, 2, 1, 2, 1, 2 ]). render(); } }, { description: "Lines, pre-computed labels", makeChart: function(node){ (new dojox.charting.Chart(node)). addAxis("x", { majorLabels: true, minorLabels: true, includeZero: true, minorTicks: false, microTicks: false, majorTickStep: 2, labels: [ { value: 0, text: "nada" }, { value: 2, text: "2 units" }, { value: 4, text: "4 units" }, { value: 8, text: "2*4 units" } ], htmlLabels: true, fixUpper: "major", fixLower: "major", majorTick: { length: 3 } }). addAxis("y", { labels: [ { value: 0, text: "nada" }, { value: 1.1, text: "hrmm" }, { value: 1.2, text: "?" }, { value: 2, text: "2!" } ], vertical: true, // htmlLabels: false, microTicks: true, minorTicks: true, majorTick: { stroke: "black", length: 3 } }). addSeries("Series A", [ 1, 2, 1, 2, 1, 2, 1 ]). addSeries("Series B", [ 2, 1, 2, 1, 2, 1, 2 ]). render(); } }, { description: "Defaults: lines, no axes.", makeChart: function(node){ (new dojox.charting.Chart(node)). addSeries("Series A", [ 1, 2, 1, 2, 1, 2, 1 ]). addSeries("Series B", [ 2, 1, 2, 1, 2, 1, 2 ]). render(); } }, { description: "Defaults: lines, no axes, and custom strokes.", makeChart: function(node){ (new dojox.charting.Chart(node)). addSeries("Series A", [ 1, 2, 1, 2, 1, 2, 1 ], {stroke: "red"}). addSeries("Series B", [ 2, 1, 2, 1, 2, 1, 2 ], {stroke: "blue"}). render(); } }, { description: "Areas, Happy theme, no axes.", makeChart: function(node){ (new dojox.charting.Chart(node)). addPlot("default", {type: "Areas", tension:"X"}). setTheme(dojox.charting.themes.Shrooms). addSeries("Series A", [1, 2, 0.5, 1.5, 1, 2.8, 0.4]). addSeries("Series B", [2.6, 1.8, 2, 1, 1.4, 0.7, 2]). addSeries("Series C", [6.3, 1.8, 3, 0.5, 4.4, 2.7, 2]). render(); } }, { description: "Areas, no axes, custom strokes and fills.", makeChart: function(node){ (new dojox.charting.Chart(node)). addPlot("default", {type: "Areas"}). addSeries("Series A", [1, 2, 1, 2, 1, 2, 1], { stroke: {color: "red", width: 2 }, fill: "lightpink" } ). addSeries("Series B", [ 2, 1, 2, 1, 2, 1, 2 ], { stroke: { color: "blue", width: 2 }, fill: "lightblue" } ). render(); } }, { description: "Lines, axes, blue theme.", makeChart: function(node){ (new dojox.charting.Chart(node)). setTheme(dojox.charting.themes.PlotKit.blue). addAxis("x"). addAxis("y", {vertical: true}). addSeries("Series A", [1, 2, 1, 2, 1, 2, 1]). addSeries("Series B", [2, 1, 2, 1, 2, 1, 2]). render(); } }, { description: "Lines, axes (aligned on minor ticks), cyan theme.", makeChart: function(node){ (new dojox.charting.Chart(node)). setTheme(dojox.charting.themes.PlotKit.cyan). addAxis("x", { fixLower: "minor", fixUpper: "minor" }). addAxis("y", { vertical: true, fixLower: "minor", fixUpper: "minor" }). addSeries("Series A", [1, 2, 1, 2, 1, 2, 1]). addSeries("Series B", [2, 1, 2, 1, 2, 1, 2]). render(); } }, { description: "Lines, axes (aligned on major ticks), green theme.", makeChart: function(node){ (new dojox.charting.Chart(node)). setTheme(dojox.charting.themes.PlotKit.green). addAxis("x", { fixLower: "major", fixUpper: "major" }). addAxis("y", { vertical: true, fixLower: "major", fixUpper: "major" }). addSeries("Series A", [1, 2, 1, 2, 1, 2, 1]). addSeries("Series B", [2, 1, 2, 1, 2, 1, 2]). render(); } }, { description: "Lines and markers, no axes, purple theme, custom min/max.", makeChart: function(node){ (new dojox.charting.Chart(node)). setTheme(dojox.charting.themes.SageToLime). addPlot("default", {type: "Markers"}). addSeries("Series A", [1, 2, 1, 2, 1, 2, 1], {min: 0, max: 3}). addSeries("Series B", [2, 1, 2, 1, 2, 1, 2]). render(); } }, { description: "Markers only, no axes, custom theme, custom markers, custom min/max.", makeChart: function(node){ (new dojox.charting.Chart(node)). addPlot("default", { type: "MarkersOnly" }). addSeries("Series A", [ 1, 2, 1, 2, 1, 2, 1 ], { min: 0, max: 3, stroke: {color: "red", width: 2}, fill: "red", marker: "m-3,0 c0,-4 6,-4 6,0 m-6,0 c0,4 6,4 6,0" } ). addSeries("Series B", [ 2, 1, 2, 1, 2, 1, 2 ], { stroke: {color: "blue", width: 2}, fill: "blue", marker: "m-3,-3 l0,6 6,0 0,-6 z" } ). render(); } }, { description: "Lines and markers, shadows, no axes, custom theme, custom markers, custom min/max.", makeChart: function(node){ (new dojox.charting.Chart(node)). addPlot("default", { type: "Markers", shadow: {dx: 1, dy: 1, width: 2, color: [0, 0, 0, 0.3]} }). addSeries("Series A", [ 1, 2, 1, 2, 1, 2, 1 ], { min: 0, max: 3, stroke: {color: "red", width: 2, join: "round"}, fill: "red", marker: "m-3,0 c0,-4 6,-4 6,0 m-6,0 c0,4 6,4 6,0" } ). addSeries("Series B", [ 2, 1, 2, 1, 2, 1, 2 ], { stroke: {color: "blue", width: 2, join: "round"}, fill: "blue", marker: "m-3,-3 l0,6 6,0 0,-6 z" } ). render(); } }, { description: "Stacked lines, markers, shadows, no axes, custom strokes, fills, and markers.", makeChart: function(node){ (new dojox.charting.Chart(node)). addPlot("default", { type: "StackedLines", markers: true, tension:"S", shadow: {dx: 1, dy: 1, width: 2, color: [0, 0, 0, 0.3]} }). addSeries("Series A", [ 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6 ], { stroke: { color: "red", width: 2 }, fill: "lightpink", marker: "m-3,-3 l0,6 6,0 0,-6 z" } ). addSeries("Series B", [ 1, 1.6, 1.3, 1.4, 1.1, 1.5, 1.1 ], { stroke: { color: "blue", width: 2 }, fill: "lightblue", marker: "m-3,0 c0,-4 6,-4 6,0 m-6,0 c0,4 6,4 6,0" } ). addSeries("Series C", [ 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6 ], { stroke: { color: "green", width: 2 }, fill: "lightgreen", marker: "m0,-3 l3,3 -3,3 -3,-3 z" } ). render(); } }, { description: "Stacked areas, axes (aligned on major ticks), custom strokes and fills.", makeChart: function(node){ (new dojox.charting.Chart(node)). addAxis("x", {fixLower: "major", fixUpper: "major"}). addAxis("y", {vertical: true, fixLower: "major", fixUpper: "major", min: 0}). addPlot("default", { type: "StackedAreas", tension:"S" }). addSeries("Series A", [ -2, 1.1, 1.2, 1.3, 1.4, 1.5, -1.6 ], { stroke: {color: "red", width: 2}, fill: "lightpink" } ). addSeries("Series B", [ 1, 1.6, 1.3, 1.4, 1.1, 1.5, 1.1 ], { stroke: {color: "blue", width: 2}, fill: "lightblue" } ). addSeries("Series C", [ 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6 ], { stroke: {color: "green", width: 2}, fill: "lightgreen" } ). render(); } }, { description: "Candlesticks with gaps, custom strokes and fills, optional mid points.", makeChart: function(node){ (new dojox.charting.Chart(node)). addPlot("default", {type: "Candlesticks", gap: 1}). addAxis("x", {fixLower: "major", fixUpper: "major", includeZero: true}). addAxis("y", {vertical: true, fixLower: "major", fixUpper: "major", natural: true}). addSeries("Series A", [ { open: 20, close: 16, high: 22, low: 8 }, { open: 16, close: 22, high: 26, low: 6, mid: 18 }, { open: 22, close: 18, high: 22, low: 11, mid: 21 }, { open: 18, close: 29, high: 32, low: 14, mid: 27 }, { open: 29, close: 24, high: 29, low: 13, mid: 27 }, { open: 24, close: 8, high: 24, low: 5 }, { open: 8, close: 16, high: 22, low: 2 }, { open: 16, close: 12, high: 19, low: 7 }, { open: 12, close: 20, high: 22, low: 8 }, { open: 20, close: 16, high: 22, low: 8 }, { open: 16, close: 22, high: 26, low: 6, mid: 18 }, { open: 22, close: 18, high: 22, low: 11, mid: 21 }, { open: 18, close: 29, high: 32, low: 14, mid: 27 }, { open: 29, close: 24, high: 29, low: 13, mid: 27 }, { open: 24, close: 8, high: 24, low: 5 }, { open: 8, close: 16, high: 22, low: 2 }, { open: 16, close: 12, high: 19, low: 7 }, { open: 12, close: 20, high: 22, low: 8 }, { open: 20, close: 16, high: 22, low: 8 }, { open: 16, close: 22, high: 26, low: 6 }, { open: 22, close: 18, high: 22, low: 11 }, { open: 18, close: 29, high: 32, low: 14 }, { open: 29, close: 24, high: 29, low: 13 }, { open: 24, close: 8, high: 24, low: 5 }, { open: 8, close: 16, high: 22, low: 2 }, { open: 16, close: 12, high: 19, low: 7 }, { open: 12, close: 20, high: 22, low: 8 }, { open: 20, close: 16, high: 22, low: 8 } ], { stroke: { color: "green" }, fill: "lightgreen" } ). render(); } }, { description: "Open/High/Low/Close with gaps, custom strokes and fills.", makeChart: function(node){ (new dojox.charting.Chart(node)). addPlot("default", {type: "OHLC", gap: 2}). addAxis("x", {fixLower: "major", fixUpper: "major", includeZero: true}). addAxis("y", {vertical: true, fixLower: "major", fixUpper: "major", natural: true}). addSeries("Series A", [ { open: 20, close: 16, high: 22, low: 8 }, { open: 16, close: 22, high: 26, low: 6 }, { open: 22, close: 18, high: 22, low: 11 }, { open: 18, close: 29, high: 32, low: 14 }, { open: 29, close: 24, high: 29, low: 13 }, { open: 24, close: 8, high: 24, low: 5 }, { open: 8, close: 16, high: 22, low: 2 }, { open: 16, close: 12, high: 19, low: 7 }, { open: 12, close: 20, high: 22, low: 8 }, { open: 20, close: 16, high: 22, low: 8 }, { open: 16, close: 22, high: 26, low: 6 }, { open: 22, close: 18, high: 22, low: 11 }, { open: 18, close: 29, high: 32, low: 14 }, { open: 29, close: 24, high: 29, low: 13 }, { open: 24, close: 8, high: 24, low: 5 }, { open: 8, close: 16, high: 22, low: 2 }, { open: 16, close: 12, high: 19, low: 7 }, { open: 12, close: 20, high: 22, low: 8 }, { open: 20, close: 16, high: 22, low: 8 }, { open: 16, close: 22, high: 26, low: 6 }, { open: 22, close: 18, high: 22, low: 11 }, { open: 18, close: 29, high: 32, low: 14 }, { open: 29, close: 24, high: 29, low: 13 }, { open: 24, close: 8, high: 24, low: 5 }, { open: 8, close: 16, high: 22, low: 2 }, { open: 16, close: 12, high: 19, low: 7 }, { open: 12, close: 20, high: 22, low: 8 }, { open: 20, close: 16, high: 22, low: 8 } ], { stroke: { color: "blue" }, fill: "blue" } ). render(); } }, { description: "Columns, no axes, custom strokes and fills.", makeChart: function(node){ (new dojox.charting.Chart(node)). addPlot("default", {type: "Columns"}). addSeries("Series A", [ 1, 2, 3, 4, 5 ], { stroke: { color: "red" }, fill: "lightpink" }). addSeries("Series B", [ 5, 4, 3, 2, 1 ], { stroke: {color: "blue"}, fill: "lightblue" }). render(); } }, { description: "Columns with gaps beetwen them, vertical axis aligned on major ticks, custom strokes, fills.", makeChart: function(node){ (new dojox.charting.Chart(node)). addAxis("y", {vertical: true, fixLower: "major", fixUpper: "major"}). addPlot("default", {type: "Columns", gap: 2}). addSeries("Series A", [ 1, 2, 3, 4, 5 ], { stroke: {color: "red"}, fill: "lightpink" }). addSeries("Series B", [ 5, 4, 3, 2, 1 ], { stroke: {color: "blue"}, fill: "lightblue" }). render(); } }, { description: "Stacked columns, no axes, custom strokes and fills.", makeChart: function(node){ (new dojox.charting.Chart(node)). addPlot("default", {type: "StackedColumns"}). addSeries("Series A", [ 1, 2, 3, 4, 5 ], {stroke: { color: "red" }, fill: "lightpink" }). addSeries("Series B", [ 2, 1, 2, 1, 2 ], {stroke: { color: "blue" }, fill: "lightblue" }). render(); } }, { description: "Bars, axes aligned on major ticks, no minor ticks, custom strokes and fills.", makeChart: function(node){ (new dojox.charting.Chart(node)). addAxis("x", {fixLower: "major", fixUpper: "major", includeZero: true}). addAxis("y", {vertical: true, fixLower: "major", fixUpper: "major", natural: true}). addPlot("default", {type: "Bars"}). addSeries("Series A", [1, 2, 3, 4, 5], { stroke: {color: "red"}, fill: "lightpink" } ). addSeries("Series B", [5, 4, 3, 2, 1], { stroke: {color: "blue"}, fill: "lightblue" } ). render(); } }, { description: "Stacked bars, no axes, custom strokes and fills.", makeChart: function(node){ (new dojox.charting.Chart(node)). addPlot("default", {type: "StackedBars"}). addSeries("Series A", [ 1, 2, 3, 4, 5 ], { stroke: { color: "red" }, fill: "lightpink" }). addSeries("Series B", [ 2, 1, 2, 1, 2 ], { stroke: { color: "blue" }, fill: "lightblue" }). render(); } }, { description: "Clustered columns, custom axes, custom strokes, fills, and gap.", makeChart: function(node){ (new dojox.charting.Chart(node)). addAxis("x", { fixLower: "minor", fixUpper: "minor", natural: true }). addAxis("y", { vertical: true, fixLower: "major", fixUpper: "major", includeZero: true }). addPlot("default", {type: "ClusteredColumns", gap: 10}). addSeries("Series A", [ 1, 2, 3, 4, 5 ], { stroke: {color: "red"}, fill: "lightpink" } ). addSeries("Series B", [5, 4, 3, 2, 1], {stroke: {color: "blue"}, fill: "lightblue"}). render(); } }, { description: "Clustered bars, custom axes, custom strokes, fills, and gap.", makeChart: function(node){ (new dojox.charting.Chart(node)). addAxis("x", {fixLower: "major", fixUpper: "major", includeZero: true}). addAxis("y", {vertical: true, fixLower: "minor", fixUpper: "minor", natural: true}). addPlot("default", { type: "ClusteredBars", gap: 5 }). addSeries("Series A", [ 1, 2, 3, 4, 5 ], { stroke: { color: "red" }, fill: "lightpink" }). addSeries("Series B", [ 2, 1, 2, 1, 2 ], { stroke: { color: "blue" }, fill: "lightblue" }). render(); } }, { description: "Columns with gaps beetwen them, grids, custom strokes, fills, axes.", makeChart: function(node){ (new dojox.charting.Chart(node)). addAxis("x", { fixLower: "minor", fixUpper: "minor", natural: true }). addAxis("y", { vertical: true, fixLower: "major", fixUpper: "major", minorTicks: false, includeZero: true }). addPlot("front_grid", { type: "Grid", hMajorLines: true, vMajorLines: false }). addPlot("default", { type: "Columns", gap: 10 }). addPlot("back_grid", { type: "Grid", hMajorLines: false, vMajorLines: true }). addSeries("Series A", [ 1, 2, 3, 4, 5 ], { stroke: { color: "red" }, fill: "lightpink" } ). addSeries("Series B", [ 5, 4, 3, 2, 1 ], { stroke: { color: "blue" }, fill: "lightblue" } ). render(); } }, { description: "Columns with gaps beetwen them, grids, custom strokes, fills, axes, with min=0, max=8, and manually specified ticks on the vertical axis.", makeChart: function(node){ (new dojox.charting.Chart(node)). addAxis("x", {fixLower: "minor", fixUpper: "minor", natural: true}). addAxis("y", { vertical: true, fixLower: "major", fixUpper: "major", includeZero: true, min: 0, max: 8, minorLabels: false, majorTicks: true, minorTicks: true, microTicks: false, majorTickStep: 2, minorTickStep: 1, microTickStep: 0.5 }). addPlot("front_grid", { type: "Grid", hMajorLines: true, vMajorLines: false }). addPlot("default", {type: "Columns", gap: 10}). addPlot("back_grid", { type: "Grid", hMajorLines: false, vMajorLines: true }). addSeries("Series A", [ 1, 2, 3, 4, 5 ], { stroke: {color: "red"}, fill: "lightpink" } ). addSeries("Series B", [ 5, 4, 3, 2, 1 ], { stroke: {color: "blue"}, fill: "lightblue" } ). render(); } }, { description: "Columns with positive and negative values, axes, and grid.", makeChart: function(node){ (new dojox.charting.Chart(node)). addAxis("x"). addAxis("y", { vertical: true }). addPlot("default", { type: "Columns", gap: 10 }). addPlot("grid", { type: "Grid" }). addSeries("Series A", [ 2, 1, 0.5, -1, -2 ], { stroke: {color: "red"}, fill: "lightpink" } ). addSeries("Series B", [ -2, -1, -0.5, 1, 2 ], { stroke: {color: "blue"}, fill: "lightblue" } ). render(); } }, { description: "Clustered columns with positive and negative values, axes, and grid.", makeChart: function(node){ (new dojox.charting.Chart(node)). addAxis("x"). addAxis("y", { vertical: true }). addPlot("default", { type: "ClusteredColumns", gap: 10 }). addPlot("grid", { type: "Grid" }). addSeries("Series A", [ 2, 1, 0.5, -1, -2 ], { stroke: {color: "red"}, fill: "lightpink" } ). addSeries("Series B", [ -2, -1, -0.5, 1, 2 ], { stroke: {color: "blue"}, fill: "lightblue" } ). addSeries("Series C", [ 1, 0.5, -1, -2, -3 ], { stroke: {color: "green"}, fill: "lightgreen" } ). render(); } }, { description: "Bars with positive and negative values, axes, and grid.", makeChart: function(node){ (new dojox.charting.Chart(node)). addAxis("x"). addAxis("y", { vertical: true }). addPlot("default", { type: "Bars", gap: 10 }). addPlot("grid", { type: "Grid" }). addSeries("Series A", [ 2, 1, 0.5, -1, -2 ], { stroke: {color: "red"}, fill: "lightpink" } ). addSeries("Series B", [ -2, -1, -0.5, 1, 2 ], { stroke: {color: "blue"}, fill: "lightblue" } ). render(); } }, { description: "Clustered bars with positive and negative values, axes, and grid.", makeChart: function(node){ (new dojox.charting.Chart(node)). addAxis("x"). addAxis("y", { vertical: true }). addPlot("default", { type: "ClusteredBars", gap: 10 }). addPlot("grid", { type: "Grid" }). addSeries("Series A", [ 2, 1, 0.5, -1, -2 ], { stroke: { color: "red" }, fill: "lightpink" } ). addSeries("Series B", [ -2, -1, -0.5, 1, 2 ], { stroke: { color: "blue" }, fill: "lightblue" } ). addSeries("Series C", [ 1, 0.5, -1, -2, -3 ], { stroke: { color: "green" }, fill: "lightgreen" } ). render(); } }, { description: "Default lines with 2D data, custom axis, red theme.", makeChart: function(node){ (new dojox.charting.Chart(node)). setTheme(dojox.charting.themes.Minty). addAxis("x", { min: 0, max: 6, majorTick: { stroke: "black", length: 3 }, minorTick: { stroke: "gray", length: 3 } }). addAxis("y", { vertical: true, min: 0, max: 10, majorTick: { stroke: "black", length: 3 }, minorTick: { stroke: "gray", length: 3 } }). addSeries("Series A", [ { x: 0.5, y: 5 }, { x: 1.5, y: 1.5 }, { x: 2, y: 9 }, { x: 5, y: 0.3 } ]). addSeries("Series B", [ { x: 0.3, y: 8 }, { x: 4, y: 6 }, { x: 5.5, y: 2 } ]). render(); } }, { description: "Scatter chart, custom axis, purple theme.", makeChart: function(node){ (new dojox.charting.Chart(node)). setTheme(dojox.charting.themes.Ireland). addPlot("default", {type: "Scatter"}). addAxis("x", { min: 0, max: 6, majorTick: { stroke: "black", length: 3 }, minorTick: { stroke: "gray", length: 3 } }). addAxis("y", { vertical: true, min: 0, max: 10, majorTick: { stroke: "black", length: 3 }, minorTick: { stroke: "gray", length: 3 } }). addSeries("Series A", [ { x: 0.5, y: 5 }, { x: 1.5, y: 1.5 }, { x: 2, y: 9 }, { x: 5, y: 0.3 } ]). addSeries("Series B", [ { x: 0.3, y: 8 }, { x: 4, y: 6 }, { x: 5.5, y: 2 } ]). render(); } }, { description: "Markers, lines, 2D data, custom axis, blue theme.", makeChart: function(node){ (new dojox.charting.Chart(node)). setTheme(dojox.charting.themes.PlotKit.blue). addPlot("default", { type: "Default", lines: true, markers: true, tension: 2 }). addAxis("x", { min: 0, max: 6, majorTick: { stroke: "black", length: 3 }, minorTick: { stroke: "gray", length: 3 } }). addAxis("y", { vertical: true, min: 0, max: 10, majorTick: { stroke: "black", length: 3 }, minorTick: { stroke: "gray", length: 3 } }). addSeries("Series A", [ { x: 0.5, y: 5 }, { x: 1.5, y: 1.5 }, { x: 2, y: 9 }, { x: 5, y: 0.3 } ]). addSeries("Series B", [ { x: 0.3, y: 8 }, { x: 4, y: 6 }, { x: 5.5, y: 2 } ]). render(); } }, { description: "Markers, lines, 2D data, custom centered axis, blue theme.", makeChart: function(node){ (new dojox.charting.Chart(node)). setTheme(dojox.charting.themes.PlotKit.blue). addPlot("default", { type: "Default", lines: true, markers: true, tension: 2 }). addAxis("x", { min: 0, max: 6, majorTick: { stroke: "black", length: 3 }, minorTick: { stroke: "gray", length: 3 }, position: "center" }). addAxis("y", { vertical: true, min: 0, max: 10, majorTick: { stroke: "black", length: 3 }, minorTick: { stroke: "gray", length: 3 }, position: "center" }). addSeries("Series A", [ { x: 0.5, y: 5 }, { x: 1.5, y: 1.5 }, { x: 2, y: 9 }, { x: 5, y: 0.3 } ]). addSeries("Series B", [ { x: 0.3, y: 8 }, { x: 4, y: 6 }, { x: 5.5, y: 2 } ]). render(); } } ]; var now = function(){ return (new Date()).getTime(); }; dojo.addOnLoad(function(){ var defaultStyle = { width: "400px", height: "200px" }; var tmpl = new dojox.dtl.Template(dojo.byId("template").value); var context = new dojox.dtl.Context({ charts: charts }); dojo.byId("charts").innerHTML = tmpl.render(context); dojo.forEach(charts, function(item, idx){ var start = now(); var n = dojo.byId("chart_"+idx); dojo.style(n, item.style||defaultStyle); item.makeChart(n); console.debug((now()-start), "ms to create:", (idx+1)+":", item.description); }); }); </script> </head> <body> <textarea id="template" style="display: none;"> {% for item in charts %} <p>{{ forloop.counter }}: {{ item.description }}</p> <div id="chart_{{ forloop.counter0 }}"></div> {% endfor %} </textarea> <h1>Chart 2D</h1> <div id="charts"></div> </body> </html>
avz-cmf/zaboy-middleware
www/js/dojox/charting/tests/test_chart2d.html
HTML
gpl-3.0
29,360
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.4"/> <title>Xortify Honeypot PHP Library: Q:/@websites@/coop/labs/dev2/class/rest_wgetserialised.php File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Xortify Honeypot PHP Library &#160;<span id="projectnumber">4.11</span> </div> <div id="projectbrief">This project allow any mid level PHP Developer to incorportate Xortify Honeypot</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.4 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>Globals</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&#160;</span>Pages</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_9ca366adf01695ed51259fbc20e8b2c4.html">Q:</a></li><li class="navelem"><a class="el" href="dir_d26b8f7c222419eea24c3b4f4a071372.html">@websites@</a></li><li class="navelem"><a class="el" href="dir_351184f73991046526c460853182ff8c.html">coop</a></li><li class="navelem"><a class="el" href="dir_839a70f1ea90149a51684eb6902339cf.html">labs</a></li><li class="navelem"><a class="el" href="dir_1bbed270536b6684c594145068f6f228.html">dev2</a></li><li class="navelem"><a class="el" href="dir_4e1460ab54f4ac7b2053043bc274abe9.html">class</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#nested-classes">Data Structures</a> &#124; <a href="#var-members">Variables</a> </div> <div class="headertitle"> <div class="title">rest_wgetserialised.php File Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a> Data Structures</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_r_e_s_t___w_g_e_t_s_e_r_i_a_l_i_s_e_d_xortify_exchange.html">REST_WGETSERIALISEDXortifyExchange</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="var-members"></a> Variables</h2></td></tr> <tr class="memitem:a731f04083e48e3087b2f5cad38672473"><td class="memItemLeft" align="right" valign="top"><a class="el" href="index_8php.html#ae2ccdf355624402b65fc2226f2a661cd">if</a>(!defined('XORTIFY_REST_API')) <br class="typebreak"/> define('XORTIFY_REST_API'&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="rest__wgetserialised_8php.html#a731f04083e48e3087b2f5cad38672473">_RUN_XORTIFY_API_REST</a></td></tr> <tr class="separator:a731f04083e48e3087b2f5cad38672473"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a70ad743fdbf705daf2366b5cabf7a04d"><td class="memItemLeft" align="right" valign="top">const&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="rest__wgetserialised_8php.html#a70ad743fdbf705daf2366b5cabf7a04d">XOOPS_SERIAL_LIB</a> 'PHPSERIAL'</td></tr> <tr class="separator:a70ad743fdbf705daf2366b5cabf7a04d"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Variable Documentation</h2> <a class="anchor" id="a731f04083e48e3087b2f5cad38672473"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="index_8php.html#ae2ccdf355624402b65fc2226f2a661cd">if</a> (!defined('XORTIFY_REST_API')) define('XORTIFY_REST_API' _RUN_XORTIFY_API_REST</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="a70ad743fdbf705daf2366b5cabf7a04d"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">const XOOPS_SERIAL_LIB 'PHPSERIAL'</td> </tr> </table> </div><div class="memdoc"> </div> </div> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Wed Jul 17 2013 01:40:17 for Xortify Honeypot PHP Library by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.4 </small></address> </body> </html>
labscoop/xortify
trunk/PHP 5.x/docs/html/rest__wgetserialised_8php.html
HTML
gpl-3.0
8,104
#pragma once #include <AP_HAL/AP_HAL_Boards.h> #include <stdint.h> #include <AP_HAL/AP_HAL_Macros.h> #include <AP_HAL/Semaphores.h> #include "AP_HAL_VRBRAIN_Namespace.h" #include <pthread.h> class VRBRAIN::Semaphore : public AP_HAL::Semaphore { public: Semaphore() { pthread_mutex_init(&_lock, nullptr); } bool give(); bool take(uint32_t timeout_ms); bool take_nonblocking(); private: pthread_mutex_t _lock; };
tatsuy/ardupilot
libraries/AP_HAL_VRBRAIN/Semaphores.h
C
gpl-3.0
446
#ifndef _TIF_CONFIG_H_ #define _TIF_CONFIG_H_ /* Define to 1 if you have the <assert.h> header file. */ #define HAVE_ASSERT_H 1 /* Define to 1 if you have the <fcntl.h> header file. */ #define HAVE_FCNTL_H 1 /* Define as 0 or 1 according to the floating point format suported by the machine */ #define HAVE_IEEEFP 1 /* Define to 1 if you have the `jbg_newlen' function. */ #define HAVE_JBG_NEWLEN 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the <io.h> header file. */ #define HAVE_IO_H 1 /* Define to 1 if you have the <search.h> header file. */ #define HAVE_SEARCH_H 1 /* Define to 1 if you have the `setmode' function. */ #define HAVE_SETMODE 1 /* Define to 1 if you have the declaration of `optarg', and to 0 if you don't. */ #define HAVE_DECL_OPTARG 0 /* The size of a `int', as computed by sizeof. */ #define SIZEOF_INT 4 /* The size of a `long', as computed by sizeof. */ #define SIZEOF_LONG 4 /* Signed 64-bit type formatter */ #define TIFF_INT64_FORMAT "%I64d" /* Signed 64-bit type */ #define TIFF_INT64_T signed __int64 /* Unsigned 64-bit type formatter */ #define TIFF_UINT64_FORMAT "%I64u" /* Unsigned 64-bit type */ #define TIFF_UINT64_T unsigned __int64 #if _WIN64 /* Windows 64-bit build */ /* Pointer difference type */ # define TIFF_PTRDIFF_T TIFF_INT64_T /* The size of `size_t', as computed by sizeof. */ # define SIZEOF_SIZE_T 8 /* Size type formatter */ # define TIFF_SIZE_FORMAT TIFF_INT64_FORMAT /* Unsigned size type */ # define TIFF_SIZE_T TIFF_UINT64_T /* Signed size type formatter */ # define TIFF_SSIZE_FORMAT TIFF_INT64_FORMAT /* Signed size type */ # define TIFF_SSIZE_T TIFF_INT64_T #else /* Windows 32-bit build */ /* Pointer difference type */ # define TIFF_PTRDIFF_T signed int /* The size of `size_t', as computed by sizeof. */ # define SIZEOF_SIZE_T 4 /* Size type formatter */ # define TIFF_SIZE_FORMAT "%u" /* Size type formatter */ # define TIFF_SIZE_FORMAT "%u" /* Unsigned size type */ # define TIFF_SIZE_T unsigned int /* Signed size type formatter */ # define TIFF_SSIZE_FORMAT "%d" /* Signed size type */ # define TIFF_SSIZE_T signed int #endif /* Set the native cpu bit order */ #define HOST_FILLORDER FILLORDER_LSB2MSB /* Visual Studio 2015 / VC 14 / MSVC 19.00 finally has snprintf() */ #if defined(_MSC_VER) && _MSC_VER < 1900 #define snprintf _snprintf #else #define HAVE_SNPRINTF 1 #endif /* Define to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel and VAX). */ /* #undef WORDS_BIGENDIAN */ /* Define to `__inline__' or `__inline' if that's what the C compiler calls it, or to nothing if 'inline' is not supported under any name. */ #ifndef __cplusplus # ifndef inline # define inline __inline # endif #endif #define lfind _lfind #pragma warning(disable : 4996) /* function deprecation warnings */ #endif /* _TIF_CONFIG_H_ */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
sdottaka/freeimage
Source/LibTIFF4/tif_config.vc.h
C
gpl-3.0
3,284
<?php /** Copyright 2012 Nick Korbel This file is part of phpScheduleIt. phpScheduleIt 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 3 of the License, or (at your option) any later version. phpScheduleIt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with phpScheduleIt. If not, see <http://www.gnu.org/licenses/>. */ require_once(ROOT_DIR . 'Pages/Admin/ManageReservationsPage.php'); require_once(ROOT_DIR . 'Presenters/Admin/ManageReservationsPresenter.php'); class ScheduleAdminManageReservationsPage extends ManageReservationsPage { public function __construct() { parent::__construct(); $userRepository = new UserRepository(); $this->presenter = new ManageReservationsPresenter($this, new ScheduleAdminManageReservationsService(new ReservationViewRepository(), $userRepository), new ScheduleAdminScheduleRepository($userRepository, ServiceLocator::GetServer()->GetUserSession()), new ResourceAdminResourceRepository($userRepository, ServiceLocator::GetServer()->GetUserSession()), new AttributeService(new AttributeRepository())); } } ?>
msslava/reservationsystem
Pages/Admin/ScheduleAdminManageReservationsPage.php
PHP
gpl-3.0
1,459
url: http://sanskrit.jnu.ac.in/sandhi/viccheda.jsp?itext=६विशेषणमेव<html> <title>Sanskrit Sandhi Splitter at J.N.U. New Delhi</title> <META CONTENT='text/hetml CHARSET=UTF-8' HTTP-EQUIV='Content-Type'/> <META NAME="Author" CONTENT="Dr. Girish Nath Jha"> <META NAME="Keywords" CONTENT="Dr. Girish Nath Jha, Sachin, Diwakar Mishra, Sanskrit Computational Linguistics, Sanskrit informatics, Sanskrit computing, Sanskrit language processing, Sanskrit and computer, computer processing of sanskrit, subanta, tinanta, POS tagger, tagset, Indian languages, linguistics, amarakosha, amarakosa, Indian tradition, Indian heritage, Machine translation, AI, MT divergence, Sandhi, kridanta, taddhita, e-learning, corpus, etext, e-text, Sanskrit blog, Panini, Bhartrhari, Bhartrihari, Patanjali, karaka, mahabharata, ashtadhyayi, astadhyayi, indexer, indexing, lexical resources, Sanskrit, thesaurus, samasa, gender analysis in Sanskrit, Hindi, saHiT, language technology, NLP"> <META NAME="Description" CONTENT="Dr. Girish Nath Jha, Sachin, Diwakar Mishra, Sanskrit Computational Linguistics, Sanskrit informatics, Sanskrit computing, Sanskrit language processing, Sanskrit and computer, computer processing of sanskrit, subanta, tinanta, POS tagger, tagset, Indian languages, linguistics, amarakosha, amarakosa, Indian tradition, Indian heritage, Machine translation, AI, MT divergence, Sandhi, kridanta, taddhita, e-learning, corpus, etext, e-text, Sanskrit blog, Panini, Bhartrhari, Bhartrihari, Patanjali, karaka, mahabharata, ashtadhyayi, astadhyayi, indexer, indexing, lexical resources, Sanskrit, thesaurus, samasa, gender analysis in Sanskrit, Hindi, saHiT, language technology, NLP"> <head> <head> <style> <!-- div.Section1 {page:Section1;} --> </style> <head> <meta http-equiv=Content-Type content="text/html; charset=utf-8"> <script language="JavaScript" src=../js/menuitems.js></script> <script language="JavaScript" src="../js/mm_menu.js"></script> <meta name=Author content="Dr. Girish Nath Jha, JNU, New Delhi"> </head> <body lang=EN-US link=blue vlink=blue style='tab-interval:.5in'> <div class=Section1> <div align=center> <table border=1 cellspacing=0 cellpadding=0 width=802 style='width:601.5pt; border-collapse:collapse;border:none;mso-border-alt:outset navy .75pt'> <tr> <td width=800 style='width:600.0pt;border:inset navy .75pt;padding:.75pt .75pt .75pt .75pt'> <script language="JavaScript1.2">mmLoadMenus();</script> <img width=800 height=130 id="_x0000_i1028" src="../images/header1.jpg" border=0> </td> </tr> <tr> <td width=818 style='width:613.5pt;border:inset navy .75pt;border-top:none; mso-border-top-alt:inset navy .75pt;padding:.75pt .75pt .75pt .75pt'> <p align="center"><a href="../"><span style='text-decoration:none;text-underline: none'><img border=1 width=49 height=26 id="_x0000_i1037" src="../images/backtohome.jpg"></span></a><span style='text-underline: none'> </span><a href="javascript:;" onmouseover="MM_showMenu(window.mm_menu_0821171051_0,6,29,null,'image2')" onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline: none'><img border=1 id=image2 src="../images/lang_tool.jpg" name=image2 width="192" height="25"></span></a><span style='text-underline: none'> </span><a href="javascript:;" onmouseover="MM_showMenu(window.mm_menu_0821171909_0,6,29,null,'image3')" onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline: none'><img border=1 id=image3 src="../images/lexical.jpg" name=image3 width="137" height="25"></span></a><span style='text-underline: none'> </span><a href="javascript:;" onmouseover="MM_showMenu(window.mm_menu_0821171609_0,6,29,null,'image1')" onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline: none'><img border=1 id=image1 src="../images/elearning.jpg" name=image1 width="77" height="25"></span></a><span style='text-underline: none'> </span><a href="javascript:;" onmouseover="MM_showMenu(window.mm_menu_0821171809_0,6,29,null,'image4')" onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline: none'><img border=1 id=image4 src="../images/corpora.jpg" name=image4 width="105" height="26"></span></a><span style='text-underline: none'> </span><a href="javascript:;" onmouseover="MM_showMenu(window.mm_menu_0821171709_0,6,29,null,'image5')" onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline: none'><img border=1 id=image5 src="../images/rstudents.jpg" name=image5 width="125" height="26"></span></a><span style='text-underline: none'> </span> <a href="javascript:;" onmouseover="MM_showMenu(window.mm_menu_0821171409_0,6,29,null,'image6')" onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline: none'><img border=1 id=image6 src="../images/feedback.jpg" name=image6 width="80" height="25"></span></a><span style='text-underline: none'> </span> <!--- <a href="../user/feedback.jsp"><img border="1" src="../images/feedback.jpg" width="80" height="25"></a> ---> </td> </tr> <tr> <td width="800"> <p align="center"><font color="#FF9933"><span style='font-size:18.0pt; '><b>Sanskrit Sandhi Recognizer and Analyzer</b></span></font></p> The Sanskrit sandhi splitter (VOWEL SANDHI) was developed as part of M.Phil. research by <a href="mailto:sachin.jnu@gmail.com">Sachin Kumar</a> (M.Phil. 2005-2007), and <a href=mailto:diwakarmishra@gmail.com>Diwakar Mishra</a> (M.Phil. 2007-2009) under the supervision of <a href=http://www.jnu.ac.in/faculty/gnjha>Dr. Girish Nath Jha</a>. The coding for this application has been done by Dr. Girish Nath Jha and Diwakar Mishra. <!---Please send feedback to to <a href="mailto:girishj@mail.jnu.ac.in">Dr. Girish Nath Jha</A>--->The Devanagari input mechanism has been developed in Javascript by Satyendra Kumar Chaube, Dr. Girish Nath Jha and Dharm Singh Rathore. </center> <table border=0 width=100%> <tr> <td valign=top width=48%> <table> <tr> <td> <FORM METHOD=get ACTION=viccheda.jsp#results name="iform" accept-Charset="UTF-8"> <font size=2><b>Enter Sanskrit text for sandhi processing (संधि-विच्छेद हेतु पाठ्य दें) using adjacent keyboard OR Use our inbuilt <a href=../js/itrans.html target=_blank>iTRANS</a>-Devanagari unicode converter for fast typing<br> <a href=sandhitest.txt>examples</a> <TEXTAREA name=itext COLS=40 ROWS=9 onkeypress=checkKeycode(event) onkeyup=iu()> ६विशेषणमेव</TEXTAREA> </td> </tr> <tr> <td> <font color=red size=2>Run in debug mode</font> <input type=checkbox name="debug" value="ON"> <br> <input type=submit value="Click to sandhi-split (संधि-विच्छेद करें)"></span><br> </td> </tr> </table> </td> <td valign=top width=52%> <table> <tr> <td> <head> <SCRIPT language=JavaScript src="../js/devkb.js"></SCRIPT> <head> <TEXTAREA name=itrans rows=5 cols=10 style="display:none"></TEXTAREA> <INPUT name=lastChar type=hidden> <table border=2 style="background-color:#fff;"> <tbody> <tr > <td> <input type=button name="btn" style="width: 24px" value="&#x0905;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0906;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0907;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0908;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0909;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x090A;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x090F;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0910;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0913;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0914;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0905;&#x0902;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0905;&#x0903;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x090D;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0911;" onClick="keyboard(this.value)"> </td> </tr> <tr> <td> <input type=button name="btn" style="width: 24px" value="&#x094D;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x093E;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x093F;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0940;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0941;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0942;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0947;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0948;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x094B;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x094C;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0902;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0903;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0945;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0949;" onClick="keyboard(this.value)"> </td> </tr> <tr> <td> <input type=button name="btn" style="width: 24px" value="&#x0915;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0916;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0917;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0918;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0919;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x091A;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x091B;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x091C;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x091D;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x091E;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 100px" value="Backspace" onClick="BackSpace()"> </td> </tr> <tr> <td> <input type=button name="btn" style="width: 24px" value="+" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x091F;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0920;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0921;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0922;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0923;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value="&#x0924;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0925;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0926;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0927;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0928;" onClick="keyboard(this.value)"> </td> </tr> <tr> <td> <input type=button name="btn" style="width: 24px" value="/" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x092A;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x092B;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x092C;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x092D;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x092E;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value="&#x092F;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0930;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0932;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0935;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0964;" onClick="keyboard(this.value)"> </td> </tr> <tr> <td> <input type=button name="btn" style="width: 24px" value="*" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0936;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0937;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0938;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value="&#x090B;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x090C;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0943;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0944;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value="&#x0939;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value=""> <input type=button name="btn" style="width: 24px" value="&#x0965;" onClick="keyboard(this.value)"> </td> </tr> <tr> <td> <input type=button name="btn" style="width: 24px" value="&#x0924;&#x094D;&#x0930;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x091C;&#x094D;&#x091E;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0915;&#x094D;&#x0937;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x0936;&#x094D;&#x0930;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 200px" value="Space Bar" onClick="Space()"> <input type=button name="btn" style="width: 24px" value="&#x0901;" onClick="keyboard(this.value)"> <input type=button name="btn" style="width: 24px" value="&#x093C;" onClick="keyboard(this.value)"> </td> </tr> </tbody> </table> </td> </tr> </table> </td> </tr> <tr> </table> </form> <a name=results> <font size=4><b><u>Results</u></b></font> <br> <br> <font color=red> <br> <hr> <br> </body> </html>
sanskritiitd/sanskrit
uohCorpus.fil/uoh/uoh.filteredcorpus.txt_output/1-hetvabasa-ext.txt.out.dict_5651_jnu.html
HTML
gpl-3.0
16,541
/** * NUM2STR - Functions to handle the conversion of numeric vales to strings. * * @created 2014-12-18 * @author Neven Boyanov * @version 2016-04-17 (last modified) * * This is part of the Tinusaur/TinyAVRLib project. * * Copyright (c) 2016 Neven Boyanov, Tinusaur Team. All Rights Reserved. * Distributed as open source software under MIT License, see LICENSE.txt file. * Please, as a favor, retain the link http://tinusaur.org to The Tinusaur Project. * * Source code available at: https://bitbucket.org/tinusaur/tinyavrlib * */ // ============================================================================ #include "num2str.h" // ---------------------------------------------------------------------------- // NOTE: This implementation is borrowed from the LCDDDD library. // Original source code at: https://bitbucket.org/boyanov/avr/src/default/lcdddd/src/lcdddd/lcdddd.h uint8_t usint2decascii(uint16_t num, char *buffer) { const unsigned short powers[] = { 10000u, 1000u, 100u, 10u, 1u }; // The "const unsigned short" combination gives shortest code. char digit; // "digit" is stored in a char array, so it should be of type char. uint8_t digits = USINT2DECASCII_MAX_DIGITS - 1; for (uint8_t pos = 0; pos < 5; pos++) // "pos" is index in array, so should be of type int. { digit = 0; while (num >= powers[pos]) { digit++; num -= powers[pos]; } // ---- CHOOSE (1), (2) or (3) ---- // CHOICE (1) Fixed width, zero padded result. /* buffer[pos] = digit + '0'; // Convert to ASCII */ // CHOICE (2) Fixed width, zero padded result, digits offset. /* buffer[pos] = digit + '0'; // Convert to ASCII // Note: Determines the offset of the first significant digit. if (digits == -1 && digit != 0) digits = pos; // Note: Could be used for variable width, not padded, left aligned result. */ // CHOICE (3) Fixed width, space (or anything else) padded result, digits offset. // Note: Determines the offset of the first significant digit. // Note: Could be used for variable width, not padded, left aligned result. if (digits == USINT2DECASCII_MAX_DIGITS - 1) { if (digit == 0) { if (pos < USINT2DECASCII_MAX_DIGITS - 1) // Check position, so single "0" will be handled properly. digit = -16; // Use: "-16" for space (' '), "-3" for dash/minus ('-'), "0" for zero ('0'), etc. ... } else { digits = pos; } } buffer[pos] = digit + '0'; // Convert to ASCII } // NOTE: The resulting ascii text should not be terminated with '\0' here. // The provided buffer maybe part of a larger text in both directions. return digits; } // ---------------------------------------------------------------------------- // NOTE: The buffer should be always at least MAX_DIGITS in length - the function works with 16-bit numbers. uint8_t usint2binascii(uint16_t num, char *buffer) { uint16_t power = 0x8000; // This is the 1000 0000 0000 0000 binary number. char digit; // "digit" is stored in a char array, so it should be of type char. uint8_t digits = USINT2BINASCII_MAX_DIGITS - 1; for (uint8_t pos = 0; pos < USINT2BINASCII_MAX_DIGITS; pos++) { // "pos" is index in an array. digit = 0; if (num >= power) { digit++; num -= power; } // Fixed width, space ('0', or anything else) padded result, digits offset. // Note: Determines the offset of the first significant digit. // Note: Could be used for variable width, not padded, left aligned result. if (digits == USINT2BINASCII_MAX_DIGITS - 1) { if (digit == 0) { if (pos < USINT2BINASCII_MAX_DIGITS - 1) // Check position, so single "0" will be handled properly. digit = 0; // Use: "-16" for space (' '), "-3" for dash/minus ('-'), "0" for zero ('0'), etc. } else { digits = pos; } } buffer[pos] = digit + '0'; // Convert to ASCII power = power >> 1; } // NOTE: The resulting ascii text should not be terminated with '\0' here. // The provided buffer maybe part of a larger text in both directions. return digits; } // ============================================================================
ageek/arduino
misc/ssd1306-libs/v2/num2str.c
C
gpl-3.0
4,230
<!doctype html> <html> <title>link</title> <meta http-equiv="content-type" value="text/html;utf-8"> <link rel="stylesheet" type="text/css" href="../static/style.css"> <body> <div id="wrapper"> <h1><a href="../api/link.html">link</a></h1> <p>Symlink a package folder</p> <h2 id="SYNOPSIS">SYNOPSIS</h2> <pre><code>npm.command.link(callback) npm.command.link(packages, callback)</code></pre> <h2 id="DESCRIPTION">DESCRIPTION</h2> <p>Package linking is a two-step process.</p> <p>Without parameters, link will create a globally-installed symbolic link from <code>prefix/package-name</code> to the current folder.</p> <p>With a parameters, link will create a symlink from the local <code>node_modules</code> folder to the global symlink.</p> <p>When creating tarballs for <code>npm publish</code>, the linked packages are &quot;snapshotted&quot; to their current state by resolving the symbolic links.</p> <p>This is handy for installing your own stuff, so that you can work on it and test it iteratively without having to continually rebuild.</p> <p>For example:</p> <pre><code>npm.commands.link(cb) # creates global link from the cwd # (say redis package) npm.commands.link(&#39;redis&#39;, cb) # link-install the package</code></pre> <p>Now, any changes to the redis package will be reflected in the package in the current working directory</p> </div> <p id="footer">link &mdash; npm@1.1.71</p> <script> ;(function () { var wrapper = document.getElementById("wrapper") var els = Array.prototype.slice.call(wrapper.getElementsByTagName("*"), 0) .filter(function (el) { return el.parentNode === wrapper && el.tagName.match(/H[1-6]/) && el.id }) var l = 2 , toc = document.createElement("ul") toc.innerHTML = els.map(function (el) { var i = el.tagName.charAt(1) , out = "" while (i > l) { out += "<ul>" l ++ } while (i < l) { out += "</ul>" l -- } out += "<li><a href='#" + el.id + "'>" + ( el.innerText || el.text || el.innerHTML) + "</a>" return out }).join("\n") toc.id = "toc" document.body.appendChild(toc) })() </script> </body></html>
bfrgoncalves/Online-PhyloViZ
node_modules/l/node_modules/hook.io/node_modules/npm/html/api/link.html
HTML
gpl-3.0
2,173
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2018, Yanis Guenane <yanis+ansible@guenane.org> # (c) 2019, René Moser <mail@renemoser.net> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: vultr_ssh_key_info short_description: Get infos about the Vultr SSH keys available. description: - Get infos about SSH keys available. version_added: "2.9" author: - "Yanis Guenane (@Spredzy)" - "René Moser (@resmo)" extends_documentation_fragment: vultr ''' EXAMPLES = r''' - name: Get Vultr SSH keys infos vultr_ssh_key_info: register: result - name: Print the infos debug: var: result.vultr_ssh_key_info ''' RETURN = r''' --- vultr_api: description: Response from Vultr API with a few additions/modification returned: success type: complex contains: api_account: description: Account used in the ini file to select the key returned: success type: str sample: default api_timeout: description: Timeout used for the API requests returned: success type: int sample: 60 api_retries: description: Amount of max retries for the API requests returned: success type: int sample: 5 api_endpoint: description: Endpoint used for the API requests returned: success type: str sample: "https://api.vultr.com" vultr_ssh_key_info: description: Response from Vultr API as list returned: success type: complex contains: id: description: ID of the ssh key returned: success type: str sample: 5904bc6ed9234 name: description: Name of the ssh key returned: success type: str sample: my ssh key date_created: description: Date the ssh key was created returned: success type: str sample: "2017-08-26 12:47:48" ssh_key: description: SSH public key returned: success type: str sample: "ssh-rsa AA... someother@example.com" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.vultr import ( Vultr, vultr_argument_spec, ) class AnsibleVultrSSHKeyInfo(Vultr): def __init__(self, module): super(AnsibleVultrSSHKeyInfo, self).__init__(module, "vultr_ssh_key_info") self.returns = { 'SSHKEYID': dict(key='id'), 'name': dict(), 'ssh_key': dict(), 'date_created': dict(), } def get_sshkeys(self): return self.api_query(path="/v1/sshkey/list") def parse_keys_list(keys_list): if not keys_list: return [] return [key for id, key in keys_list.items()] def main(): argument_spec = vultr_argument_spec() module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) sshkey_info = AnsibleVultrSSHKeyInfo(module) result = sshkey_info.get_result(parse_keys_list(sshkey_info.get_sshkeys())) module.exit_json(**result) if __name__ == '__main__': main()
aperigault/ansible
lib/ansible/modules/cloud/vultr/vultr_ssh_key_info.py
Python
gpl-3.0
3,294
#ifndef OFFSET_TEST_H #define OFFSET_TEST_H #include <test/UnitTest.h> #include <test/UnitTestRunner.h> #include <util/misc/Offset.h> #include <util/global.h> using namespace Util; class OffsetTest : public UnitTest { public: class A { public: int x; bool f; virtual void action() {} void outputOffsets(std::ostream& out) { A a; out << "x " << memberOffset<A>(a, &A::x) << std::endl; out << "f " << memberOffset<A>(a, &A::f) << std::endl; } }; class B : public A { public: int y; virtual void action() {} void outputOffsets(std::ostream& out) { B b; out << "x " << memberOffset<A>(b, &A::x) << std::endl; out << "f " << memberOffset<A>(b, &A::f) << std::endl; out << "y " << memberOffset<B>(b, &B::y) << std::endl; out << "z " << memberOffset<B>(b, &B::w) << std::endl; } private: int w; }; class C : public B { public: int z; virtual void action() {} }; void setUp() {}; void tearDown() {}; void testMemberOffset1() { printMethod(TEST_FUNC); B b; std::cout << std::endl; std::cout << memberOffset<B>(b, &B::y) << std::endl; b.outputOffsets(std::cout); } void testMemberOffset2() { printMethod(TEST_FUNC); B b; std::cout << std::endl; std::cout << memberOffset<B>(b, &A::x) << std::endl; } void testBaseOffset() { printMethod(TEST_FUNC); B b; std::cout << std::endl; std::cout << baseOffset<B, A>(b) << std::endl; C c; std::cout << std::endl; std::cout << baseOffset<C, B>(c) << std::endl; } }; TEST_BEGIN(OffsetTest) TEST_ADD(OffsetTest, testMemberOffset1) TEST_ADD(OffsetTest, testMemberOffset2) TEST_ADD(OffsetTest, testBaseOffset) TEST_END(OffsetTest) #endif
polymer1/simpatico
src/util/tests/misc/OffsetTest.h
C
gpl-3.0
1,937
/* Copyright 2014 the unarr project authors (see AUTHORS file). License: LGPLv3 */ #include "tar.h" static bool tar_is_number(const char *data, size_t size) { size_t i; for (i = 0; i < size; i++) { if ((data[i] < '0' || '7' < data[i]) && data[i] != ' ' && data[i] != '\0') return false; } return true; } static uint64_t tar_parse_number(const char *data, size_t size) { uint64_t value = 0; size_t i; for (i = 0; i < size; i++) { if (data[i] == ' ' || data[i] == '\0') continue; if (data[i] < '0' || '7' < data[i]) break; value = value * 8 + (data[i] - '0'); } return value; } static bool tar_is_zeroed_block(const char *data) { size_t i; for (i = 0; i < TAR_BLOCK_SIZE; i++) { if (data[i] != 0) return false; } return true; } static bool ar_is_valid_utf8(const char *string) { const unsigned char *s; for (s = (const unsigned char *)string; *s; s++) { int skip = *s < 0x80 ? 0 : *s < 0xC0 ? -1 : *s < 0xE0 ? 1 : *s < 0xF0 ? 2 : *s < 0xF5 ? 3 : -1; if (skip < 0) return false; while (skip-- > 0) { if ((*++s & 0xC0) != 0x80) return false; } } return true; } bool tar_parse_header(ar_archive_tar *tar) { char data[TAR_BLOCK_SIZE]; uint32_t checksum; int32_t checksum2; size_t i; if (ar_read(tar->super.stream, data, sizeof(data)) != sizeof(data)) return false; if (tar_is_zeroed_block(data)) { free(tar->entry.name); memset(&tar->entry, 0, sizeof(tar->entry)); return true; } if (!tar_is_number(data + 124, 12) || !tar_is_number(data + 136, 12) || !tar_is_number(data + 148, 8)) return false; tar->entry.filesize = (size_t)tar_parse_number(data + 124, 12); tar->entry.mtime = (tar_parse_number(data + 136, 12) + 11644473600) * 10000000; tar->entry.checksum = (uint32_t)tar_parse_number(data + 148, 8); tar->entry.filetype = data[156]; free(tar->entry.name); tar->entry.name = NULL; if (tar->entry.filetype == TYPE_FILE_OLD) { i = 100; while (--i > 0 && data[i] == '\0'); if (data[i] == '/') tar->entry.filetype = TYPE_DIRECTORY; } tar->entry.is_ustar = memcmp(data + 257, "ustar\x0000", 8) == 0 && memcmp(data + 508, "tar\0", 4) != 0; if (tar->entry.filesize > (size_t)-1 - tar->super.entry_offset - 2 * TAR_BLOCK_SIZE) return false; checksum = 0; checksum2 = 0; memset(data + 148, ' ', 8); for (i = 0; i < sizeof(data); i++) { checksum += (unsigned char)data[i]; checksum2 += (signed char)data[i]; } if (checksum != (uint32_t)checksum2 && tar->entry.checksum == (uint32_t)checksum2) { log("Checksum was calculated using signed data"); tar->entry.checksum = checksum; } return tar->entry.checksum == checksum; } bool tar_handle_pax_extended(ar_archive *ar) { ar_archive_tar *tar = (ar_archive_tar *)ar; off64_t offset = ar->entry_offset; size_t size = tar->entry.filesize; char *data, *line; data = malloc(size); if (!data) { log("Ignoring PAX extended header on OOM"); return ar_parse_entry(ar); } if (!ar_entry_uncompress(ar, data, size) || !ar_parse_entry(ar)) { free(data); return false; } if (tar->last_seen_dir > offset) { free(data); return true; } line = data; while (line < data + size) { char *key, *value, *ptr; size_t length, max_size = line - data + size; ptr = memchr(line, '=', max_size); if (!ptr || *line < '1' || '9' < *line) { warn("Invalid PAX extended header record @%" PRIi64, offset); break; } value = ptr + 1; *ptr = '\0'; length = (size_t)strtoul(line, &ptr, 10); if (max_size < length || length <= (size_t)(value - line) || line[length - 1] != '\n' || *ptr != ' ') { warn("Invalid PAX extended header record @%" PRIi64, offset); break; } key = ptr + 1; line += length; line[-1] = '\0'; if (strcmp(key, "path") == 0) { ptr = malloc(strlen(value) + 1); if (ptr) { strcpy(ptr, value); free(tar->entry.name); tar->entry.name = ptr; } } else if (strcmp(key, "mtime") == 0) tar->entry.mtime = (time64_t)((strtod(value, &ptr) + 11644473600) * 10000000); else if (strcmp(key, "size") == 0) tar->entry.filesize = (size_t)strtoul(value, &ptr, 10); else log("Skipping value for %s", key); } free(data); tar_get_name(ar); ar->entry_offset = offset; ar->entry_size_uncompressed = tar->entry.filesize; ar->entry_filetime = tar->entry.mtime; return true; } bool tar_handle_gnu_longname(ar_archive *ar) { ar_archive_tar *tar = (ar_archive_tar *)ar; off64_t offset = ar->entry_offset; size_t size = tar->entry.filesize; char *longname; longname = malloc(size + 1); if (!longname || size == (size_t)-1) { log("Falling back to the short filename on OOM"); free(longname); return ar_parse_entry(ar); } if (!ar_entry_uncompress(ar, longname, size) || !ar_parse_entry(ar)) { free(longname); return false; } if (tar->last_seen_dir > offset) { free(longname); return true; } if (tar->entry.name) { log("Skipping GNU long filename in favor of PAX name"); free(longname); return true; } longname[size] = '\0'; ar->entry_offset = offset; /* name could be in any encoding, assume UTF-8 or whatever (DOS) */ if (ar_is_valid_utf8(longname)) { tar->entry.name = longname; } else { tar->entry.name = ar_conv_dos_to_utf8(longname); free(longname); } return true; } const char *tar_get_name(ar_archive *ar) { ar_archive_tar *tar = (ar_archive_tar *)ar; if (!tar->entry.name) { char *name; if (!ar_seek(ar->stream, ar->entry_offset, SEEK_SET)) return NULL; name = malloc(100 + 1); if (!name || ar_read(ar->stream, name, 100) != 100) { free(name); ar_seek(ar->stream, ar->entry_offset + TAR_BLOCK_SIZE, SEEK_SET); return NULL; } name[100] = '\0'; if (tar->entry.is_ustar) { char *prefixed = malloc(256 + 1); if (!ar_skip(ar->stream, 245) || ar_read(ar->stream, prefixed, 167) != 167) { free(name); free(prefixed); ar_seek(ar->stream, ar->entry_offset + TAR_BLOCK_SIZE, SEEK_SET); return NULL; } if (prefixed[0] != '\0') { prefixed[156] = '\0'; strcat(prefixed, "/"); strcat(prefixed, name); free(name); name = prefixed; prefixed = NULL; } free(prefixed); } else ar_skip(ar->stream, TAR_BLOCK_SIZE - 100); /* name could be in any encoding, assume UTF-8 or whatever (DOS) */ if (ar_is_valid_utf8(name)) { tar->entry.name = name; } else { tar->entry.name = ar_conv_dos_to_utf8(name); free(name); } /* normalize path separators */ if (tar->entry.name) { char *p = tar->entry.name; while ((p = strchr(p, '\\')) != NULL) { *p = '/'; } } } return tar->entry.name; }
ibb-zimmers/betsynetpdf
sumatrapdf/ext/unarr/tar/parse-tar.c
C
gpl-3.0
8,144
{{extend 'layout.html'}} <h2>{{=T( request.args(0).replace('_',' ').capitalize() )}}</h2> <div id="web2py_user_form"> {{ if request.args(0)=='login': if not 'register' in auth.settings.actions_disabled: form.add_button(T('Register'),URL(args='register', vars={'_next': request.vars._next} if request.vars._next else None),_class='btn') pass if not 'request_reset_password' in auth.settings.actions_disabled: form.add_button(T('Lost Password'),URL(args='request_reset_password'),_class='btn') pass pass =form }} </div> <script language="javascript"><!-- jQuery("#web2py_user_form input:visible:enabled:first").focus(); {{if request.args(0)=='register':}} web2py_validate_entropy(jQuery('#auth_user_password'),100); {{elif request.args(0)=='change_password':}} web2py_validate_entropy(jQuery('#no_table_new_password'),100); {{pass}} //--></script>
hiatobr/midiacapoeira
views/conteudo/videos_user.html
HTML
gpl-3.0
858
/** * This file is part of the Unit.js testing framework. * * (c) Nicolas Tallefourtane <dev@nicolab.net> * * For the full copyright and license information, please view * the LICENSE file distributed with this source code * or visit http://unitjs.com. * * @author Nicolas Tallefourtane <dev@nicolab.net> */ 'use strict'; var Noder = require('noder.io').Noder; var test = require('../../src'); var api = require('../../src/api'); describe('Unit.js', function() { it('inherits from `Noder`', function() { test .object(test) .isInstanceOf(Noder) .isInstanceOf(api.UnitJS) .isIdenticalTo(api) .function(test.constructor) .hasName('UnitJS') ; }); });
Geovo/turing_machine_simulator
node_modules/unit.js/test/node/index.js
JavaScript
gpl-3.0
724
/** * Copyright 2009-2012 tragicphantom * * This file is part of stdf4j. * * Stdf4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Stdf4j 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 stdf4j. If not, see <http://www.gnu.org/licenses/>. **/ package com.tragicphantom.stdf.tools.extract.output; import com.tragicphantom.stdf.Record; public interface OutputFormatter{ public void write(Record record) throws Exception; }
tehaxer/stdf4j
tools/extract/src/main/java/com/tragicphantom/stdf/tools/extract/output/OutputFormatter.java
Java
gpl-3.0
915
/* * Copyright (C) 2014 Vlad Mihalachi * * This file is part of Turbo Editor. * * Turbo Editor 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 3 of the License, or * (at your option) any later version. * * Turbo Editor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package sharedcode.turboeditor.util.systemui; import android.app.Activity; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.view.WindowManager; /** * Helper for controlling the visibility of the System UI across the various API levels. To use * this API, instantiate an instance of this class with the required level. The level specifies the * extent to which the System UI's visibility is changed when you call {@link #hide()} * or {@link #toggle()}. */ public final class SystemUiHelper { /** * In this level, the helper will toggle low profile mode. */ public static final int LEVEL_LOW_PROFILE = 0; /** * In this level, the helper will toggle the visibility of the status bar. * If there is a navigation bar, it will toggle low profile mode. */ public static final int LEVEL_HIDE_STATUS_BAR = 1; /** * In this level, the helper will toggle the visibility of the navigation bar * (if present and if possible) and status bar. In cases where the navigation * bar is present but cannot be hidden, it will toggle low profile mode. */ public static final int LEVEL_LEAN_BACK = 2; /** * In this level, the helper will toggle the visibility of the navigation bar * (if present and if possible) and status bar, in an immersive mode. This means that the app * will continue to receive all touch events. The user can reveal the system bars with an * inward swipe along the region where the system bars normally appear. * * <p>The {@link #FLAG_IMMERSIVE_STICKY} flag can be used to control how the system bars are * displayed. */ public static final int LEVEL_IMMERSIVE = 3; /** * When this flag is set, the * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN} * flag will be set on older devices, making the status bar "float" on top * of the activity layout. This is most useful when there are no controls at * the top of the activity layout. * <p> * This flag isn't used on newer devices because the <a * href="http://developer.android.com/design/patterns/actionbar.html">action * bar</a>, the most important structural element of an Android app, should * be visible and not obscured by the system UI. */ public static final int FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES = 0x1; /** * Used with {@link #LEVEL_IMMERSIVE}. When this flag is set, an inward swipe in the system * bars areas will cause the system bars to temporarily appear in a semi-transparent state, * but no flags are cleared, and your system UI visibility change listeners are not triggered. * The bars automatically hide again after a short delay, or if the user interacts with the * middle of the screen. */ public static final int FLAG_IMMERSIVE_STICKY = 0x2; private static final String LOG_TAG = SystemUiHelper.class.getSimpleName(); private final SystemUiHelperImpl mImpl; private final Handler mHandler; private final Runnable mHideRunnable; /** * Construct a new SystemUiHelper. * * @param activity The Activity who's system UI should be changed * @param level The level of hiding. Should be either {@link #LEVEL_LOW_PROFILE}, * {@link #LEVEL_HIDE_STATUS_BAR}, {@link #LEVEL_LEAN_BACK} or * {@link #LEVEL_IMMERSIVE} * @param flags Additional options. See {@link #FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES} and * {@link #FLAG_IMMERSIVE_STICKY} */ public SystemUiHelper(Activity activity, int level, int flags) { this(activity, level, flags, null); } /** * Construct a new SystemUiHelper. * * @param activity The Activity who's system UI should be changed * @param level The level of hiding. Should be either {@link #LEVEL_LOW_PROFILE}, * {@link #LEVEL_HIDE_STATUS_BAR}, {@link #LEVEL_LEAN_BACK} or * {@link #LEVEL_IMMERSIVE} * @param flags Additional options. See {@link #FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES} and * {@link #FLAG_IMMERSIVE_STICKY} * @param listener A listener which is called when the system visibility is changed */ public SystemUiHelper(Activity activity, int level, int flags, OnVisibilityChangeListener listener) { mHandler = new Handler(Looper.getMainLooper()); mHideRunnable = new HideRunnable(); // Create impl if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mImpl = new SystemUiHelperImplKK(activity, level, flags, listener); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { mImpl = new SystemUiHelperImplJB(activity, level, flags, listener); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { mImpl = new SystemUiHelperImplICS(activity, level, flags, listener); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mImpl = new SystemUiHelperImplHC(activity, level, flags, listener); } else { mImpl = new SystemUiHelperImplBase(activity, level, flags, listener); } } /** * @return true if the system UI is currently showing. What this means depends on the mode this * {@link android.example.android.systemuivis.SystemUiHelper} was instantiated with. */ public boolean isShowing() { return mImpl.isShowing(); } /** * Show the system UI. What this means depends on the mode this {@link android.example.android.systemuivis.SystemUiHelper} was * instantiated with. * * <p>Any currently queued delayed hide requests will be removed. */ public void show() { // Ensure that any currently queued hide calls are removed removeQueuedRunnables(); mImpl.show(); } /** * Hide the system UI. What this means depends on the mode this {@link android.example.android.systemuivis.SystemUiHelper} was * instantiated with. * * <p>Any currently queued delayed hide requests will be removed. */ public void hide() { // Ensure that any currently queued hide calls are removed removeQueuedRunnables(); mImpl.hide(); } /** * Request that the system UI is hidden after a delay. * * <p>Any currently queued delayed hide requests will be removed. * * @param delayMillis The delay (in milliseconds) until the Runnable * will be executed. */ public void delayHide(long delayMillis) { // Ensure that any currently queued hide calls are removed removeQueuedRunnables(); mHandler.postDelayed(mHideRunnable, delayMillis); } /** * Toggle whether the system UI is displayed. */ public void toggle() { if (mImpl.isShowing()) { mImpl.hide(); } else { mImpl.show(); } } private void removeQueuedRunnables() { // Ensure that any currently queued hide calls are removed mHandler.removeCallbacks(mHideRunnable); } /** * A callback interface used to listen for system UI visibility changes. */ public interface OnVisibilityChangeListener { /** * Called when the system UI visibility has changed. * * @param visible True if the system UI is visible. */ public void onVisibilityChange(boolean visible); } static abstract class SystemUiHelperImpl { final Activity mActivity; final int mLevel; final int mFlags; final OnVisibilityChangeListener mOnVisibilityChangeListener; boolean mIsShowing = true; SystemUiHelperImpl(Activity activity, int level, int flags, OnVisibilityChangeListener onVisibilityChangeListener) { mActivity = activity; mLevel = level; mFlags = flags; mOnVisibilityChangeListener = onVisibilityChangeListener; } abstract void show(); abstract void hide(); boolean isShowing() { return mIsShowing; } void setIsShowing(boolean isShowing) { mIsShowing = isShowing; if (mOnVisibilityChangeListener != null) { mOnVisibilityChangeListener.onVisibilityChange(mIsShowing); } } } /** * Base implementation. Used on API level 10 and below. */ static class SystemUiHelperImplBase extends SystemUiHelperImpl { SystemUiHelperImplBase(Activity activity, int level, int flags, OnVisibilityChangeListener onVisibilityChangeListener) { super(activity, level, flags, onVisibilityChangeListener); if ((mFlags & SystemUiHelper.FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES) != 0) { mActivity.getWindow().addFlags( WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } } @Override void show() { if (mLevel > SystemUiHelper.LEVEL_LOW_PROFILE) { mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); setIsShowing(true); } } @Override void hide() { if (mLevel > SystemUiHelper.LEVEL_LOW_PROFILE) { mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); setIsShowing(false); } } } private class HideRunnable implements Runnable { @Override public void run() { hide(); } } }
vmihalachi/turbo-editor
libraries/sharedCode/src/main/java/sharedcode/turboeditor/util/systemui/SystemUiHelper.java
Java
gpl-3.0
10,893
#include "pta.h" #include "asf_complex.h" #include "asf.h" fcpx *forward_fft(complexFloat *image, int line_count, int sample_count) { int i; // Allocate memory int size = line_count * sample_count; fcpx *in_cpx = (fcpx *) fftwf_malloc(sizeof(fcpx)*size); fcpx *fft_cpx = (fcpx *) fftwf_malloc(sizeof(fcpx)*size); // Fill in the values from internal complexFloat format for (i=0; i<size; i++) { in_cpx[i][0] = image[i].real; in_cpx[i][1] = image[i].imag; } // Do the forward FFT int flags = FFTW_DESTROY_INPUT + FFTW_ESTIMATE; fftwf_plan fw_plan = fftwf_plan_dft_2d(line_count, sample_count, in_cpx, fft_cpx, FFTW_FORWARD, flags); fftwf_execute(fw_plan); fftwf_destroy_plan(fw_plan); fftwf_free(in_cpx); return fft_cpx; } complexFloat *inverse_fft(fftwf_complex *fft_cpx, int line_count, int sample_count) { int i; // Allocate memory int size = line_count * sample_count; fcpx *out_cpx = (fcpx *) fftwf_malloc(sizeof(fcpx)*size); complexFloat *image = (complexFloat *) MALLOC(sizeof(complexFloat)*size); // Do the inverse FFT int flags = FFTW_DESTROY_INPUT + FFTW_ESTIMATE; fftwf_plan bw_plan = fftwf_plan_dft_2d(line_count, sample_count, fft_cpx, out_cpx, FFTW_BACKWARD, flags); fftwf_execute(bw_plan); fftwf_destroy_plan(bw_plan); fftwf_free(fft_cpx); // Fill in the values into internal complexFloat format for (i=0; i<size; i++) { image[i].real = out_cpx[i][0] / size; image[i].imag = out_cpx[i][1] / size; } return image; } fcpx *oversample(fcpx *in, int srcSize, int oversampling_factor) { int i, k; // Allocate memory for oversampled image int bigSize = srcSize * oversampling_factor; fcpx *out = (fcpx *) fftwf_malloc(sizeof(fcpx)*bigSize*bigSize); // Oversample // uppler left corner for (i=0; i<srcSize/2; i++) { for (k=0; k<srcSize/2; k++) out[i*bigSize+k][0] = in[i*srcSize+k][0]; out[i*bigSize+k][1] = in[i*srcSize+k][1]; } // upper right corner for (i=0; i<srcSize/2; i++) for (k=srcSize/2; k<srcSize; k++) { out[i*bigSize+bigSize-srcSize+k][0] = in[i*srcSize+k][0]; out[i*bigSize+bigSize-srcSize+k][1] = in[i*srcSize+k][1]; } // lower left corner for (i=srcSize/2; i<srcSize; i++) for (k=0; k<srcSize/2; k++) { out[(bigSize-srcSize+i)*bigSize+k][0] = in[i*srcSize+k][0]; out[(bigSize-srcSize+i)*bigSize+k][1] = in[i*srcSize+k][1]; } // lower right corner for (i=srcSize/2; i<srcSize; i++) { for (k=srcSize/2; k<srcSize; k++) out[(bigSize-srcSize+i)*bigSize+bigSize-srcSize+k][0] = in[i*srcSize+k][0]; out[(bigSize-srcSize+i)*bigSize+bigSize-srcSize+k][1] = in[i*srcSize+k][1]; } return(out); } void my_complex2polar(complexFloat *in, int line_count, int sample_count, float *amplitude, float *phase) { int i, k, index; for (i=0; i<line_count; i++) for (k=0; k<sample_count; k++) { index = i*sample_count+k; if (in[index].real!=0.0 || in[index].imag!=0.0) { amplitude[index] = sqrt(in[index].real*in[index].real + in[index].imag*in[index].imag); phase[index] = atan2(in[index].imag, in[index].real); } else { amplitude[index] = 0.0; phase[index] = 0.0; } } }
asfadmin/ASF_MapReady
src/pta/fftw.c
C
gpl-3.0
3,246
#include "stdafx.h" #include "HEOS.h" #include "../hardware/hardwaretypes.h" #include "../main/Helper.h" #include "../main/Logger.h" #include "../main/SQLHelper.h" #include "../notifications/NotificationHelper.h" #include "../main/WebServer.h" #include "../main/mainworker.h" #include "../main/localtime_r.h" #include "../main/EventSystem.h" #include "../webserver/cWebem.h" #include <iostream> #define DEBUG_LOGGING false #define RETRY_DELAY 30 CHEOS::CHEOS(const int ID, const std::string &IPAddress, const unsigned short usIPPort, const std::string &User, const std::string &Pwd, const int PollIntervalsec, const int PingTimeoutms) : m_IP(IPAddress), m_User(User), m_Pwd(Pwd) { m_HwdID = ID; m_bDoRestart = false; m_stoprequested = false; m_usIPPort = usIPPort; m_retrycntr = RETRY_DELAY; SetSettings(PollIntervalsec, PingTimeoutms); } CHEOS::~CHEOS(void) { } void CHEOS::ParseLine() { if (m_bufferpos<2) return; std::string sLine((char*)&m_buffer); try { Json::Reader jReader; Json::Value root; if (DEBUG_LOGGING) _log.Log(LOG_NORM, "DENON by HEOS: Handling message: '%s'.", sLine.c_str()); bool bRetVal = jReader.parse(sLine, root); if (!bRetVal) { _log.Log(LOG_ERROR, "DENON by HEOS: PARSE ERROR: '%s'", sLine.c_str()); } else { // HEOS generated messages if (root.isMember("heos")) { if (root["heos"].isMember("result")) { if (root["heos"]["result"] == "success") { if (root["heos"].isMember("command")) { if (root["heos"]["command"] == "system/heart_beat") { } else if (root["heos"]["command"] == "player/get_players") { if (root.isMember("payload")) { int key = 0; for( Json::ValueIterator itr = root["payload"].begin() ; itr != root["payload"].end() ; itr++ ) { if (root["payload"][key].isMember("name") && root["payload"][key].isMember("pid")) { std::string pid = boost::to_string(root["payload"][key]["pid"].asInt()); AddNode(root["payload"][key]["name"].asCString(), pid); } else { if (DEBUG_LOGGING) _log.Log(LOG_NORM, "DENON by HEOS: No players found."); } key++; } } else { if (DEBUG_LOGGING) _log.Log(LOG_NORM, "DENON by HEOS: No players found (No Payload)."); } } else if (root["heos"]["command"] == "player/get_play_state" || root["heos"]["command"] == "player/set_play_state") { if (root["heos"].isMember("message")) { std::vector<std::string> SplitMessage; StringSplit(root["heos"]["message"].asString(), "&", SplitMessage); if (SplitMessage.size() > 0) { std::vector<std::string> SplitMessagePlayer; StringSplit(SplitMessage[0], "=", SplitMessagePlayer); std::vector<std::string> SplitMessageState; StringSplit(SplitMessage[1], "=", SplitMessageState); std::string pid = SplitMessagePlayer[1]; std::string state = SplitMessageState[1]; _eMediaStatus nStatus = MSTAT_UNKNOWN; if (state == "play") nStatus = MSTAT_PLAYING; else if (state == "pause") nStatus = MSTAT_PAUSED; else if (state == "stop") nStatus = MSTAT_STOPPED; else nStatus = MSTAT_ON; std::string sStatus = ""; UpdateNodeStatus(pid, nStatus, sStatus); /* If playing request now playing information */ if (state == "play") { int PlayerID = atoi(pid.c_str()); SendCommand("getNowPlaying", PlayerID); } m_lastUpdate = 0; } } } else if (root["heos"]["command"] == "player/get_now_playing_media") { if (root["heos"].isMember("message")) { std::vector<std::string> SplitMessage; StringSplit(root["heos"]["message"].asString(), "=", SplitMessage); if (SplitMessage.size() > 0) { std::string sLabel = ""; std::string sStatus = ""; std::string pid = SplitMessage[1]; if (root.isMember("payload")) { std::string sTitle = ""; std::string sAlbum = ""; std::string sArtist = ""; std::string sStation = ""; sTitle = root["payload"]["song"].asString(); sAlbum = root["payload"]["album"].asString(); sArtist = root["payload"]["artist"].asString(); sStation = root["payload"]["station"].asString(); if(sStation != "") { sLabel = sArtist + " - " + sTitle + " - " + sStation; } else { sLabel = sArtist + " - " + sTitle; } } else { sLabel = "(empty playlist)"; } sStatus = sLabel; UpdateNodesStatus(pid, sStatus); m_lastUpdate = 0; } } } } } else { if (root["heos"].isMember("command")) { if (DEBUG_LOGGING) _log.Log(LOG_NORM, "DENON by HEOS: Failed: '%s'.", root["heos"]["command"].asCString()); } } } else { if (root["heos"].isMember("command")) { if (root["heos"]["command"] == "event/player_state_changed") { if (root["heos"].isMember("message")) { std::vector<std::string> SplitMessage; StringSplit(root["heos"]["message"].asString(), "&", SplitMessage); if (SplitMessage.size() > 0) { std::vector<std::string> SplitMessagePlayer; StringSplit(SplitMessage[0], "=", SplitMessagePlayer); std::vector<std::string> SplitMessageState; StringSplit(SplitMessage[1], "=", SplitMessageState); std::string pid = SplitMessagePlayer[1]; std::string state = SplitMessageState[1]; _eMediaStatus nStatus = MSTAT_UNKNOWN; if (state == "play") nStatus = MSTAT_PLAYING; else if (state == "pause") nStatus = MSTAT_PAUSED; else if (state == "stop") nStatus = MSTAT_STOPPED; else nStatus = MSTAT_ON; std::string sStatus = ""; UpdateNodeStatus(pid, nStatus, sStatus); /* If playing request now playing information */ if (state == "play") { int PlayerID = atoi(pid.c_str()); SendCommand("getNowPlaying", PlayerID); } m_lastUpdate = 0; } } } else if (root["heos"]["command"] == "event/players_changed") { SendCommand("getPlayers"); } else if (root["heos"]["command"] == "event/groups_changed") { SendCommand("getPlayers"); } else if (root["heos"]["command"] == "event/player_now_playing_changed") { std::vector<std::string> SplitMessage; StringSplit(root["heos"]["message"].asString(), "=", SplitMessage); if (SplitMessage.size() > 0) { std::string pid = SplitMessage[1]; int PlayerID = atoi(pid.c_str()); SendCommand("getPlayState", PlayerID); } } else if (root["heos"]["command"] == "event/player_mute_changed") { } else if (root["heos"]["command"] == "event/repeat_mode_changed") { } else if (root["heos"]["command"] == "event/shuffle_mode_changed") { } } } } else { if (DEBUG_LOGGING) _log.Log(LOG_NORM, "DENON by HEOS: Message not generated by HEOS System."); } } } catch (std::exception& e) { _log.Log(LOG_ERROR, "DENON by HEOS: Exception: %s", e.what()); } } void CHEOS::SendCommand(const std::string &command) { std::stringstream ssMessage; std::string sMessage; bool systemCall = false; // Register for change events if (command == "registerForEvents") { ssMessage << "heos://system/register_for_change_events?enable=on"; sMessage = ssMessage.str(); systemCall = true; } // Unregister for change events if (command == "unRegisterForEvents") { ssMessage << "heos://system/register_for_change_events?enable=off"; sMessage = ssMessage.str(); systemCall = true; } if (command == "heartbeat") { ssMessage << "heos://system/heart_beat"; sMessage = ssMessage.str(); systemCall = true; } if (command == "getPlayers") { ssMessage << "heos://player/get_players"; sMessage = ssMessage.str(); systemCall = true; } /* Group related commands */ if (command == "getGroups") { ssMessage << "heos://group/get_groups"; sMessage = ssMessage.str(); systemCall = true; } /* Process */ if (sMessage.length()) { if (WriteInt(sMessage)) { if (systemCall) { if (DEBUG_LOGGING) _log.Log(LOG_NORM, "HEOS by DENON: Sent command: '%s'.", sMessage.c_str()); } else { _log.Log(LOG_NORM, "HEOS by DENON: Sent command: '%s'.", sMessage.c_str()); } } } else { _log.Log(LOG_ERROR, "HEOS by DENON: Command: '%s'. Unknown command.", command.c_str()); } } void CHEOS::SendCommand(const std::string &command, const int iValue) { std::stringstream ssMessage; std::string sMessage; bool systemCall = false; if (command == "getPlayerInfo") { ssMessage << "heos://player/get_player_info?pid=" << iValue << ""; sMessage = ssMessage.str(); systemCall = true; } if (command == "getPlayState") { ssMessage << "heos://player/get_play_state?pid=" << iValue << ""; sMessage = ssMessage.str(); systemCall = true; } if (command == "setPlayStatePlay" || command == "play") { ssMessage << "heos://player/set_play_state?pid=" << iValue << "&state=play"; sMessage = ssMessage.str(); } if (command == "setPlayStatePause" || command == "pause") { ssMessage << "heos://player/set_play_state?pid=" << iValue << "&state=pause"; sMessage = ssMessage.str(); } if (command == "setPlayStateStop" || command == "stop") { ssMessage << "heos://player/set_play_state?pid=" << iValue << "&state=stop"; sMessage = ssMessage.str(); } if (command == "getNowPlaying") { ssMessage << "heos://player/get_now_playing_media?pid=" << iValue << ""; sMessage = ssMessage.str(); systemCall = true; } if (command == "getVolume") { ssMessage << "heos://player/get_volume?pid=" << iValue << ""; sMessage = ssMessage.str(); systemCall = true; } if (command == "setVolumeUp") { ssMessage << "heos://player/volume_up?pid=" << iValue << ""; sMessage = ssMessage.str(); } if (command == "setVolumeDown") { ssMessage << "heos://player/volume_down?pid=" << iValue << ""; sMessage = ssMessage.str(); } if (command == "getMute") { ssMessage << "heos://player/get_mute?pid=" << iValue << ""; sMessage = ssMessage.str(); systemCall = true; } if (command == "setMuteOn") { ssMessage << "heos://player/set_mute?pid=" << iValue << "&state=on"; sMessage = ssMessage.str(); } if (command == "setMuteOff") { ssMessage << "heos://player/set_mute?pid=" << iValue << "&state=off"; sMessage = ssMessage.str(); } if (command == "toggleMute") { ssMessage << "heos://player/toggle_mute?pid=" << iValue << ""; sMessage = ssMessage.str(); } if (command == "getPlayMode") { ssMessage << "heos://player/get_play_mode?pid=" << iValue << ""; sMessage = ssMessage.str(); systemCall = true; } /* Set playmode if (command == "setPlayMode") { ssMessage << "heos://player/volume_up?pid=" << iValue << ""; sMessage = ssMessage.str(); systemCall = true; } */ /* Queue related commands */ if (command == "getQueue") { ssMessage << "heos://player/get_queue?pid=" << iValue << ""; sMessage = ssMessage.str(); systemCall = true; } if (command == "playNext") { ssMessage << "heos://player/play_next?pid=" << iValue << ""; sMessage = ssMessage.str(); } if (command == "playPrev") { ssMessage << "heos://player/play_previous?pid=" << iValue << ""; sMessage = ssMessage.str(); } /* Process */ if (DEBUG_LOGGING) _log.Log(LOG_NORM, "DENON by HEOS: Debug: '%s'.", sMessage.c_str()); if (sMessage.length()) { if (WriteInt(sMessage)) { if (systemCall) { if (DEBUG_LOGGING) _log.Log(LOG_NORM, "HEOS by DENON: Sent command: '%s'.", sMessage.c_str()); } else { _log.Log(LOG_NORM, "HEOS by DENON: Sent command: '%s'.", sMessage.c_str()); } } else { if (DEBUG_LOGGING) _log.Log(LOG_NORM, "HEOS by DENON: Not Connected - Message not sent: '%s'.", sMessage.c_str()); } } else { _log.Log(LOG_ERROR, "HEOS by DENON: Command: '%s'. Unknown command.", command.c_str()); } } void CHEOS::Do_Work() { _log.Log(LOG_STATUS, "HEOS by DENON: Worker started..."); ReloadNodes(); bool bFirstTime=true; bool bCheckedForPlayers=false; int sec_counter = 25; m_lastUpdate = 25; while (!m_stoprequested) { sleep_seconds(1); sec_counter++; m_lastUpdate++; if (sec_counter % 12 == 0) { m_LastHeartbeat=mytime(NULL); } if (bFirstTime) { bFirstTime=false; connect(m_IP,m_usIPPort); } else { if ((m_bDoRestart) && (sec_counter % 30 == 0)) { connect(m_IP,m_usIPPort); } update(); if (mIsConnected) { if (!bCheckedForPlayers) { // Update all players and groups SendCommand("getPlayers"); bCheckedForPlayers = true; // Enable event changes SendCommand("registerForEvents"); } if (sec_counter % 30 == 0 && m_lastUpdate >= 30)//updates every 30 seconds { bFirstTime=false; std::vector<HEOSNode>::const_iterator itt; for (itt = m_nodes.begin(); itt != m_nodes.end(); ++itt) { SendCommand("getPlayState", itt->DevID); } } } } } _log.Log(LOG_STATUS, "HEOS by DENON: Worker stopped..."); } _eNotificationTypes CHEOS::NotificationType(_eMediaStatus nStatus) { switch (nStatus) { case MSTAT_OFF: return NTYPE_SWITCH_OFF; case MSTAT_ON: return NTYPE_SWITCH_ON; case MSTAT_PAUSED: return NTYPE_PAUSED; case MSTAT_STOPPED: return NTYPE_STOPPED; case MSTAT_PLAYING: return NTYPE_PLAYING; default: return NTYPE_SWITCH_OFF; } } bool CHEOS::StartHardware() { m_stoprequested=false; m_bDoRestart=false; //force connect the next first time m_retrycntr=RETRY_DELAY; m_bIsStarted=true; //Start worker thread m_thread = boost::shared_ptr<boost::thread>(new boost::thread(boost::bind(&CHEOS::Do_Work, this))); return (m_thread!=NULL); } bool CHEOS::StopHardware() { m_stoprequested=true; if (isConnected()) { try { disconnect(); } catch (...) { //Don't throw from a Stop command } } try { if (m_thread) { m_thread->join(); } } catch (...) { //Don't throw from a Stop command } m_bIsStarted=false; return true; } void CHEOS::OnConnect() { _log.Log(LOG_STATUS, "HEOS by DENON: Connected to: %s:%ld", m_IP.c_str(), m_usIPPort); m_bDoRestart=false; m_bIsStarted=true; m_bufferpos=0; sOnConnected(this); } void CHEOS::OnDisconnect() { _log.Log(LOG_STATUS, "HEOS by DENON: Disconnected"); } void CHEOS::OnData(const unsigned char *pData, size_t length) { boost::lock_guard<boost::mutex> l(readQueueMutex); ParseData(pData,length); } void CHEOS::OnError(const std::exception e) { _log.Log(LOG_ERROR, "HEOS by DENON: Error: %s",e.what()); } void CHEOS::OnError(const boost::system::error_code& error) { if ( (error == boost::asio::error::address_in_use) || (error == boost::asio::error::connection_refused) || (error == boost::asio::error::access_denied) || (error == boost::asio::error::host_unreachable) || (error == boost::asio::error::timed_out) ) { _log.Log(LOG_ERROR, "HEOS by DENON: Can not connect to: %s:%ld", m_IP.c_str(), m_usIPPort); } else if ( (error == boost::asio::error::eof) || (error == boost::asio::error::connection_reset) ) { _log.Log(LOG_STATUS, "HEOS by DENON: Connection reset!"); } else _log.Log(LOG_ERROR, "HEOS by DENON: %s", error.message().c_str()); } void CHEOS::ParseData(const unsigned char *pData, int Len) { int ii=0; while (ii<Len) { const unsigned char c = pData[ii]; if(c == 0x0d) { ii++; continue; } if(c == 0x0a || m_bufferpos == sizeof(m_buffer) - 1) { // discard newline, close string, parse line and clear it. if(m_bufferpos > 0) m_buffer[m_bufferpos] = 0; ParseLine(); m_bufferpos = 0; } else { m_buffer[m_bufferpos] = c; m_bufferpos++; } ii++; } } /* bool CHEOS::WriteInt(const unsigned char *pData, const unsigned char Len) { if (!mIsConnected) { return false; } write(pData, Len); return true; } */ bool CHEOS::WriteInt(const std::string &sendStr) { std::stringstream ssSend; std::string sSend; if (!mIsConnected) { return false; } ssSend << sendStr << "\r\n"; sSend = ssSend.str(); write((const unsigned char*)sSend.c_str(), sSend.size()); return true; } void CHEOS::UpdateNodeStatus(const std::string &DevID, const _eMediaStatus nStatus, const std::string &sStatus) { std::vector<std::vector<std::string> > result; time_t now = time(0); struct tm ltime; localtime_r(&now, &ltime); char szLastUpdate[40]; sprintf(szLastUpdate, "%04d-%02d-%02d %02d:%02d:%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday, ltime.tm_hour, ltime.tm_min, ltime.tm_sec); result = m_sql.safe_query("UPDATE DeviceStatus SET nValue=%d, sValue='%q', LastUpdate='%q' WHERE (HardwareID == %d) AND (DeviceID == '%q') AND (Unit == 1) AND (SwitchType == %d)", int(nStatus), sStatus.c_str(), szLastUpdate, m_HwdID, DevID.c_str(), STYPE_Media); } void CHEOS::UpdateNodesStatus(const std::string &DevID, const std::string &sStatus) { std::vector<std::vector<std::string> > result; time_t now = time(0); struct tm ltime; localtime_r(&now, &ltime); char szLastUpdate[40]; sprintf(szLastUpdate, "%04d-%02d-%02d %02d:%02d:%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday, ltime.tm_hour, ltime.tm_min, ltime.tm_sec); result = m_sql.safe_query("UPDATE DeviceStatus SET sValue='%q', LastUpdate='%q' WHERE (HardwareID == %d) AND (DeviceID == '%q') AND (Unit == 1) AND (SwitchType == %d)", sStatus.c_str(), szLastUpdate, m_HwdID, DevID.c_str(), STYPE_Media); } void CHEOS::AddNode(const std::string &Name, const std::string &PlayerID) { std::vector<std::vector<std::string> > result; result = m_sql.safe_query("SELECT ID FROM DeviceStatus WHERE (HardwareID==%d) AND (DeviceID=='%q')", m_HwdID, PlayerID.c_str()); if (result.size()>0) { int ID = atoi(result[0][0].c_str()); UpdateNode(ID, Name); return; } m_sql.safe_query( "INSERT INTO DeviceStatus (HardwareID, DeviceID, Unit, Type, SubType, SwitchType, Used, SignalLevel, BatteryLevel, Name, nValue, sValue) " "VALUES (%d, '%q', 1, %d, %d, %d, 1, 12, 255, '%q', 0, 'Unavailable')", m_HwdID, PlayerID.c_str(), int(pTypeLighting2), int(sTypeAC), int(STYPE_Media), Name.c_str()); ReloadNodes(); } void CHEOS::UpdateNode(const int ID, const std::string &Name) { m_sql.safe_query("UPDATE DeviceStatus SET Name='%q' WHERE (HardwareID==%d) AND (ID=='%d')", Name.c_str(), m_HwdID, ID); ReloadNodes(); } void CHEOS::SetSettings(const int PollIntervalsec, const int PingTimeoutms) { //Defaults m_iPollInterval = 30; m_iPingTimeoutms = 1000; if (PollIntervalsec > 1) m_iPollInterval = PollIntervalsec; if ((PingTimeoutms / 1000 < m_iPollInterval) && (PingTimeoutms != 0)) m_iPingTimeoutms = PingTimeoutms; } bool CHEOS::WriteToHardware(const char *pdata, const unsigned char length) { const tRBUF *pSen = reinterpret_cast<const tRBUF*>(pdata); unsigned char packettype = pSen->ICMND.packettype; if (packettype != pTypeLighting2) return false; long DevID = (pSen->LIGHTING2.id3 << 8) | pSen->LIGHTING2.id4; std::vector<HEOSNode>::const_iterator itt; for (itt = m_nodes.begin(); itt != m_nodes.end(); ++itt) { if (itt->DevID == DevID) { int iParam = pSen->LIGHTING2.level; std::string sParam; switch (pSen->LIGHTING2.cmnd) { case light2_sOn: SendCommand("setPlayStatePlay", itt->DevID); return true; case light2_sGroupOn: case light2_sOff: SendCommand("setPlayStateStop", itt->DevID); return true; case light2_sGroupOff: case gswitch_sPlay: SendCommand("getNowPlaying", itt->DevID); SendCommand("setPlayStatePlay", itt->DevID); return true; case gswitch_sPlayPlaylist: case gswitch_sPlayFavorites: case gswitch_sStop: SendCommand("setPlayStateStop", itt->DevID); return true; case gswitch_sPause: SendCommand("setPlayStatePause", itt->DevID); return true; case gswitch_sSetVolume: default: return true; } } } return false; } void CHEOS::ReloadNodes() { m_nodes.clear(); std::vector<std::vector<std::string> > result; result = m_sql.safe_query("SELECT ID,DeviceID, Name, nValue,sValue FROM DeviceStatus WHERE (HardwareID==%d)", m_HwdID); if (result.size() > 0) { _log.Log(LOG_STATUS, "DENON for HEOS: %i players found.", result.size()); std::vector<std::vector<std::string> >::const_iterator itt; for (itt = result.begin(); itt != result.end(); ++itt) { std::vector<std::string> sd = *itt; HEOSNode pnode; pnode.ID = atoi(sd[0].c_str()); pnode.DevID = atoi(sd[1].c_str()); pnode.Name = sd[2]; pnode.nStatus = (_eMediaStatus)atoi(sd[3].c_str()); pnode.sStatus = sd[4]; pnode.LastOK = mytime(NULL); m_nodes.push_back(pnode); } } else { _log.Log(LOG_ERROR, "DENON for HEOS: No players found."); } } //Webserver helpers namespace http { namespace server { void CWebServer::Cmd_HEOSSetMode(WebEmSession & session, const request& req, Json::Value &root) { if (session.rights != 2) { session.reply_status = reply::forbidden; return; //Only admin user allowed } std::string hwid = request::findValue(&req, "idx"); std::string mode1 = request::findValue(&req, "mode1"); std::string mode2 = request::findValue(&req, "mode2"); if ( (hwid == "") || (mode1 == "") || (mode2 == "") ) return; int iHardwareID = atoi(hwid.c_str()); CDomoticzHardwareBase *pBaseHardware = m_mainworker.GetHardware(iHardwareID); if (pBaseHardware == NULL) return; if (pBaseHardware->HwdType != HTYPE_HEOS) return; CHEOS *pHardware = reinterpret_cast<CHEOS*>(pBaseHardware); root["status"] = "OK"; root["title"] = "HEOSSetMode"; int iMode1 = atoi(mode1.c_str()); int iMode2 = atoi(mode2.c_str()); m_sql.safe_query("UPDATE Hardware SET Mode1=%d, Mode2=%d WHERE (ID == '%q')", iMode1, iMode2, hwid.c_str()); pHardware->SetSettings(iMode1, iMode2); } void CWebServer::Cmd_HEOSMediaCommand(WebEmSession & session, const request& req, Json::Value &root) { std::string sIdx = request::findValue(&req, "idx"); std::string sAction = request::findValue(&req, "action"); if (sIdx.empty()) return; int idx = atoi(sIdx.c_str()); root["status"] = "OK"; root["title"] = "HEOSMediaCommand"; std::vector<std::vector<std::string> > result; result = m_sql.safe_query("SELECT DS.SwitchType, DS.DeviceID, H.Type, H.ID FROM DeviceStatus DS, Hardware H WHERE (DS.ID=='%q') AND (DS.HardwareID == H.ID)", sIdx.c_str()); if (result.size() == 1) { _eSwitchType sType = (_eSwitchType)atoi(result[0][0].c_str()); int PlayerID = atoi(result[0][1].c_str()); _eHardwareTypes hType = (_eHardwareTypes)atoi(result[0][2].c_str()); int HwID = atoi(result[0][3].c_str()); // Is the device a media Player? if (sType == STYPE_Media) { switch (hType) { case HTYPE_HEOS: CDomoticzHardwareBase *pBaseHardware = m_mainworker.GetHardwareByIDType(result[0][3].c_str(), HTYPE_HEOS); if (pBaseHardware == NULL) return; CHEOS *pHEOS = reinterpret_cast<CHEOS*>(pBaseHardware); pHEOS->SendCommand(sAction, PlayerID); break; // put other players here ... } } } } } }
etamminga/domoticz
hardware/HEOS.cpp
C++
gpl-3.0
24,067
--- title: "Cohomología" lang: es category: es permalink: es/exposition_cohomology ident: exposition_cohomology parent: cohomology kind: unfinished mathjax: true layout: post type: post --- Cohomología
charlesp0096/beta_mathifold
_posts/es/2016-09-25-expo-cohomology.md
Markdown
gpl-3.0
207
(function($) { var $openDialog = null; var $background = null; var defaultOptions = { autoOpen:true, opacity:'0.3' }; function initialize() { if (!$background) { $background = $('<div />').css({ 'display':'none', 'position':'fixed', '_position':'absolute', 'left':'0', 'top':'0', 'width':'100%', 'height':'100%', 'background':'#000000', 'margin':'0', 'padding':'0', 'border':'0 none', 'z-index':'9000' }).appendTo('body').click(function(e) { if ($openDialog) methods.close.apply($openDialog) }); } } var methods = { init: function(options) { var opts = $.extend(defaultOptions, options); this.each(function() { var $this = $(this) var data = $this.data('dialog'); if (!data) { $this.data('dialog', opts); data = $this.data('dialog'); } }); if (opts.autoOpen) methods.open.apply(this); return this; }, open: function() { if ($openDialog) methods.close.apply($openDialog); return this.first().each(function() { var $this = $(this) var data = $this.data('dialog'); if (!data) data = defaultOptions; $background.css('opacity',data.opacity).fadeIn(500); $this.css('position','absolute').css('z-index','9900') .css('top', ($(window).height()/2-$this.height()/2)+'px') .css('left', ($(window).width()/2-$this.width()/2)+'px') .fadeIn(500); $openDialog = $this; $(window).bind('keypress.dialog', function(e) { if (e.keyCode == 27) methods.close.apply($openDialog); }); }); }, close: function() { $(window).unbind('.dialog'); this.hide(); if ($openDialog && $openDialog.filter(':visible').size() <= 0) { $background.hide(); $openDialog = null; } return this; } } $.fn.dialog = function(method) { initialize(); if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error( 'Method ' + method + ' does not exist on jQuery.dialog' ); } }; })(jQuery);
baracudakb/Legend
plugins/i18n_specialpages/js/jquery.dialog.js
JavaScript
gpl-3.0
2,335
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Section 8.1.1: Separating a point from a polyhedron</title> <link rel="canonical" href="http://cvxr.com/cvx/examples/cvxbook/Ch08_geometric_probs/html/separate_pt_poly.html"> <link rel="stylesheet" href="../../../examples.css" type="text/css"> </head> <body> <div id="header"> <h1>Section 8.1.1: Separating a point from a polyhedron</h1> Jump to:&nbsp;&nbsp;&nbsp;&nbsp; <a href="#source">Source code</a>&nbsp;&nbsp;&nbsp;&nbsp; <a href="#output">Text output</a> &nbsp;&nbsp;&nbsp;&nbsp; Plots &nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../index.html">Library index</a> </div> <div id="content"> <a id="source"></a> <pre class="codeinput"> <span class="comment">% Boyd &amp; Vandenberghe "Convex Optimization"</span> <span class="comment">% Joelle Skaf - 10/09/05</span> <span class="comment">%</span> <span class="comment">% The goal is to produce a hyperplane separating x0 and the polyhedron</span> <span class="comment">% defined as {x | Ax &lt;= b}</span> <span class="comment">% minimize mu'*x0 - b'*lambda</span> <span class="comment">% A'*lambda = mu</span> <span class="comment">% norm(mu)* &lt;= 1</span> <span class="comment">% lambda &gt;= 0</span> <span class="comment">% Input data</span> randn(<span class="string">'seed'</span>,0); n = 10; m = 2*n; x0 = randn(n,1); A = randn(m,n); b = rand(m,1); <span class="comment">% CVX solution</span> fprintf(1,<span class="string">'Finding a separating hyperplane between the 2 polyhedra...'</span>); cvx_begin <span class="string">quiet</span> variables <span class="string">muu(n)</span> <span class="string">lambda(m)</span> maximize ( muu'*x0 - b'*lambda ) A'*lambda == muu; norm(muu) &lt;= 1; lambda &gt;= 0; cvx_end fprintf(1,<span class="string">'Done! \n'</span>); <span class="comment">% Verification</span> disp(<span class="string">'------------------------------------------------------------------'</span>); disp(<span class="string">'Note that 0 is in {x | Ax &lt;= b} by construction...'</span> ); disp(<span class="string">'Verifying that x0 is separated from {x | Ax &lt;= b} i.e. mu^T*x0 &gt; 0'</span>); disp([<span class="string">' mu^T*x0 = '</span> num2str(muu'*x0) ]); </pre> <a id="output"></a> <pre class="codeoutput"> Finding a separating hyperplane between the 2 polyhedra...Done! ------------------------------------------------------------------ Note that 0 is in {x | Ax &lt;= b} by construction... Verifying that x0 is separated from {x | Ax &lt;= b} i.e. mu^T*x0 &gt; 0 mu^T*x0 = 2.7667 </pre> </div> </body> </html>
badrinarayan/astlinespec
redir/cvx/examples/cvxbook/Ch08_geometric_probs/html/separate_pt_poly.html
HTML
gpl-3.0
2,671
/* * uhub - A tiny ADC p2p connection hub * Copyright (C) 2007-2014, Jan Vidar Krey * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef HAVE_UHUB_CONFIG_TOKEN_H #define HAVE_UHUB_CONFIG_TOKEN_H struct cfg_tokens; struct cfg_tokens* cfg_tokenize(const char* line); void cfg_tokens_free(struct cfg_tokens*); int cfg_token_add(struct cfg_tokens*, char* new_token); size_t cfg_token_count(struct cfg_tokens*); char* cfg_token_get(struct cfg_tokens*, size_t offset); char* cfg_token_get_first(struct cfg_tokens*); char* cfg_token_get_next(struct cfg_tokens*); struct cfg_settings; struct cfg_settings* cfg_settings_split(const char* line); const char* cfg_settings_get_key(struct cfg_settings*); const char* cfg_settings_get_value(struct cfg_settings*); void cfg_settings_free(struct cfg_settings*); #endif /* HAVE_UHUB_CONFIG_TOKEN_H */
imobilis/uhub
src/util/config_token.h
C
gpl-3.0
1,457
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "shared.rsh" int32_t gWidth; int32_t gHeight; rs_allocation gIn; float gCoeffs[25]; uchar4 __attribute__((kernel)) convolve_U4(uint32_t x, uint32_t y) { uint32_t x0 = max((int32_t)x-2, 0); uint32_t x1 = max((int32_t)x-1, 0); uint32_t x2 = x; uint32_t x3 = min((int32_t)x+1, gWidth-1); uint32_t x4 = min((int32_t)x+2, gWidth-1); uint32_t y0 = max((int32_t)y-2, 0); uint32_t y1 = max((int32_t)y-1, 0); uint32_t y2 = y; uint32_t y3 = min((int32_t)y+1, gHeight-1); uint32_t y4 = min((int32_t)y+2, gHeight-1); float4 p0 = convert_float4(rsGetElementAt_uchar4(gIn, x0, y0)) * gCoeffs[0] + convert_float4(rsGetElementAt_uchar4(gIn, x1, y0)) * gCoeffs[1] + convert_float4(rsGetElementAt_uchar4(gIn, x2, y0)) * gCoeffs[2] + convert_float4(rsGetElementAt_uchar4(gIn, x3, y0)) * gCoeffs[3] + convert_float4(rsGetElementAt_uchar4(gIn, x4, y0)) * gCoeffs[4]; float4 p1 = convert_float4(rsGetElementAt_uchar4(gIn, x0, y1)) * gCoeffs[5] + convert_float4(rsGetElementAt_uchar4(gIn, x1, y1)) * gCoeffs[6] + convert_float4(rsGetElementAt_uchar4(gIn, x2, y1)) * gCoeffs[7] + convert_float4(rsGetElementAt_uchar4(gIn, x3, y1)) * gCoeffs[8] + convert_float4(rsGetElementAt_uchar4(gIn, x4, y1)) * gCoeffs[9]; float4 p2 = convert_float4(rsGetElementAt_uchar4(gIn, x0, y2)) * gCoeffs[10] + convert_float4(rsGetElementAt_uchar4(gIn, x1, y2)) * gCoeffs[11] + convert_float4(rsGetElementAt_uchar4(gIn, x2, y2)) * gCoeffs[12] + convert_float4(rsGetElementAt_uchar4(gIn, x3, y2)) * gCoeffs[13] + convert_float4(rsGetElementAt_uchar4(gIn, x4, y2)) * gCoeffs[14]; float4 p3 = convert_float4(rsGetElementAt_uchar4(gIn, x0, y3)) * gCoeffs[15] + convert_float4(rsGetElementAt_uchar4(gIn, x1, y3)) * gCoeffs[16] + convert_float4(rsGetElementAt_uchar4(gIn, x2, y3)) * gCoeffs[17] + convert_float4(rsGetElementAt_uchar4(gIn, x3, y3)) * gCoeffs[18] + convert_float4(rsGetElementAt_uchar4(gIn, x4, y3)) * gCoeffs[19]; float4 p4 = convert_float4(rsGetElementAt_uchar4(gIn, x0, y4)) * gCoeffs[20] + convert_float4(rsGetElementAt_uchar4(gIn, x1, y4)) * gCoeffs[21] + convert_float4(rsGetElementAt_uchar4(gIn, x2, y4)) * gCoeffs[22] + convert_float4(rsGetElementAt_uchar4(gIn, x3, y4)) * gCoeffs[23] + convert_float4(rsGetElementAt_uchar4(gIn, x4, y4)) * gCoeffs[24]; p0 = clamp(p0 + p1 + p2 + p3 + p4 + 0.5f, 0.f, 255.f); return convert_uchar4(p0); } uchar3 __attribute__((kernel)) convolve_U3(uint32_t x, uint32_t y) { uint32_t x0 = max((int32_t)x-2, 0); uint32_t x1 = max((int32_t)x-1, 0); uint32_t x2 = x; uint32_t x3 = min((int32_t)x+1, gWidth-1); uint32_t x4 = min((int32_t)x+2, gWidth-1); uint32_t y0 = max((int32_t)y-2, 0); uint32_t y1 = max((int32_t)y-1, 0); uint32_t y2 = y; uint32_t y3 = min((int32_t)y+1, gHeight-1); uint32_t y4 = min((int32_t)y+2, gHeight-1); float3 p0 = convert_float3(rsGetElementAt_uchar3(gIn, x0, y0)) * gCoeffs[0] + convert_float3(rsGetElementAt_uchar3(gIn, x1, y0)) * gCoeffs[1] + convert_float3(rsGetElementAt_uchar3(gIn, x2, y0)) * gCoeffs[2] + convert_float3(rsGetElementAt_uchar3(gIn, x3, y0)) * gCoeffs[3] + convert_float3(rsGetElementAt_uchar3(gIn, x4, y0)) * gCoeffs[4]; float3 p1 = convert_float3(rsGetElementAt_uchar3(gIn, x0, y1)) * gCoeffs[5] + convert_float3(rsGetElementAt_uchar3(gIn, x1, y1)) * gCoeffs[6] + convert_float3(rsGetElementAt_uchar3(gIn, x2, y1)) * gCoeffs[7] + convert_float3(rsGetElementAt_uchar3(gIn, x3, y1)) * gCoeffs[8] + convert_float3(rsGetElementAt_uchar3(gIn, x4, y1)) * gCoeffs[9]; float3 p2 = convert_float3(rsGetElementAt_uchar3(gIn, x0, y2)) * gCoeffs[10] + convert_float3(rsGetElementAt_uchar3(gIn, x1, y2)) * gCoeffs[11] + convert_float3(rsGetElementAt_uchar3(gIn, x2, y2)) * gCoeffs[12] + convert_float3(rsGetElementAt_uchar3(gIn, x3, y2)) * gCoeffs[13] + convert_float3(rsGetElementAt_uchar3(gIn, x4, y2)) * gCoeffs[14]; float3 p3 = convert_float3(rsGetElementAt_uchar3(gIn, x0, y3)) * gCoeffs[15] + convert_float3(rsGetElementAt_uchar3(gIn, x1, y3)) * gCoeffs[16] + convert_float3(rsGetElementAt_uchar3(gIn, x2, y3)) * gCoeffs[17] + convert_float3(rsGetElementAt_uchar3(gIn, x3, y3)) * gCoeffs[18] + convert_float3(rsGetElementAt_uchar3(gIn, x4, y3)) * gCoeffs[19]; float3 p4 = convert_float3(rsGetElementAt_uchar3(gIn, x0, y4)) * gCoeffs[20] + convert_float3(rsGetElementAt_uchar3(gIn, x1, y4)) * gCoeffs[21] + convert_float3(rsGetElementAt_uchar3(gIn, x2, y4)) * gCoeffs[22] + convert_float3(rsGetElementAt_uchar3(gIn, x3, y4)) * gCoeffs[23] + convert_float3(rsGetElementAt_uchar3(gIn, x4, y4)) * gCoeffs[24]; p0 = clamp(p0 + p1 + p2 + p3 + p4 + 0.5f, 0.f, 255.f); return convert_uchar3(p0); } uchar2 __attribute__((kernel)) convolve_U2(uint32_t x, uint32_t y) { uint32_t x0 = max((int32_t)x-2, 0); uint32_t x1 = max((int32_t)x-1, 0); uint32_t x2 = x; uint32_t x3 = min((int32_t)x+1, gWidth-1); uint32_t x4 = min((int32_t)x+2, gWidth-1); uint32_t y0 = max((int32_t)y-2, 0); uint32_t y1 = max((int32_t)y-1, 0); uint32_t y2 = y; uint32_t y3 = min((int32_t)y+1, gHeight-1); uint32_t y4 = min((int32_t)y+2, gHeight-1); float2 p0 = convert_float2(rsGetElementAt_uchar2(gIn, x0, y0)) * gCoeffs[0] + convert_float2(rsGetElementAt_uchar2(gIn, x1, y0)) * gCoeffs[1] + convert_float2(rsGetElementAt_uchar2(gIn, x2, y0)) * gCoeffs[2] + convert_float2(rsGetElementAt_uchar2(gIn, x3, y0)) * gCoeffs[3] + convert_float2(rsGetElementAt_uchar2(gIn, x4, y0)) * gCoeffs[4]; float2 p1 = convert_float2(rsGetElementAt_uchar2(gIn, x0, y1)) * gCoeffs[5] + convert_float2(rsGetElementAt_uchar2(gIn, x1, y1)) * gCoeffs[6] + convert_float2(rsGetElementAt_uchar2(gIn, x2, y1)) * gCoeffs[7] + convert_float2(rsGetElementAt_uchar2(gIn, x3, y1)) * gCoeffs[8] + convert_float2(rsGetElementAt_uchar2(gIn, x4, y1)) * gCoeffs[9]; float2 p2 = convert_float2(rsGetElementAt_uchar2(gIn, x0, y2)) * gCoeffs[10] + convert_float2(rsGetElementAt_uchar2(gIn, x1, y2)) * gCoeffs[11] + convert_float2(rsGetElementAt_uchar2(gIn, x2, y2)) * gCoeffs[12] + convert_float2(rsGetElementAt_uchar2(gIn, x3, y2)) * gCoeffs[13] + convert_float2(rsGetElementAt_uchar2(gIn, x4, y2)) * gCoeffs[14]; float2 p3 = convert_float2(rsGetElementAt_uchar2(gIn, x0, y3)) * gCoeffs[15] + convert_float2(rsGetElementAt_uchar2(gIn, x1, y3)) * gCoeffs[16] + convert_float2(rsGetElementAt_uchar2(gIn, x2, y3)) * gCoeffs[17] + convert_float2(rsGetElementAt_uchar2(gIn, x3, y3)) * gCoeffs[18] + convert_float2(rsGetElementAt_uchar2(gIn, x4, y3)) * gCoeffs[19]; float2 p4 = convert_float2(rsGetElementAt_uchar2(gIn, x0, y4)) * gCoeffs[20] + convert_float2(rsGetElementAt_uchar2(gIn, x1, y4)) * gCoeffs[21] + convert_float2(rsGetElementAt_uchar2(gIn, x2, y4)) * gCoeffs[22] + convert_float2(rsGetElementAt_uchar2(gIn, x3, y4)) * gCoeffs[23] + convert_float2(rsGetElementAt_uchar2(gIn, x4, y4)) * gCoeffs[24]; p0 = clamp(p0 + p1 + p2 + p3 + p4 + 0.5f, 0.f, 255.f); return convert_uchar2(p0); } uchar __attribute__((kernel)) convolve_U1(uint32_t x, uint32_t y) { uint32_t x0 = max((int32_t)x-2, 0); uint32_t x1 = max((int32_t)x-1, 0); uint32_t x2 = x; uint32_t x3 = min((int32_t)x+1, gWidth-1); uint32_t x4 = min((int32_t)x+2, gWidth-1); uint32_t y0 = max((int32_t)y-2, 0); uint32_t y1 = max((int32_t)y-1, 0); uint32_t y2 = y; uint32_t y3 = min((int32_t)y+1, gHeight-1); uint32_t y4 = min((int32_t)y+2, gHeight-1); float p0 = (float)(rsGetElementAt_uchar(gIn, x0, y0)) * gCoeffs[0] + (float)(rsGetElementAt_uchar(gIn, x1, y0)) * gCoeffs[1] + (float)(rsGetElementAt_uchar(gIn, x2, y0)) * gCoeffs[2] + (float)(rsGetElementAt_uchar(gIn, x3, y0)) * gCoeffs[3] + (float)(rsGetElementAt_uchar(gIn, x4, y0)) * gCoeffs[4]; float p1 = (float)(rsGetElementAt_uchar(gIn, x0, y1)) * gCoeffs[5] + (float)(rsGetElementAt_uchar(gIn, x1, y1)) * gCoeffs[6] + (float)(rsGetElementAt_uchar(gIn, x2, y1)) * gCoeffs[7] + (float)(rsGetElementAt_uchar(gIn, x3, y1)) * gCoeffs[8] + (float)(rsGetElementAt_uchar(gIn, x4, y1)) * gCoeffs[9]; float p2 = (float)(rsGetElementAt_uchar(gIn, x0, y2)) * gCoeffs[10] + (float)(rsGetElementAt_uchar(gIn, x1, y2)) * gCoeffs[11] + (float)(rsGetElementAt_uchar(gIn, x2, y2)) * gCoeffs[12] + (float)(rsGetElementAt_uchar(gIn, x3, y2)) * gCoeffs[13] + (float)(rsGetElementAt_uchar(gIn, x4, y2)) * gCoeffs[14]; float p3 = (float)(rsGetElementAt_uchar(gIn, x0, y3)) * gCoeffs[15] + (float)(rsGetElementAt_uchar(gIn, x1, y3)) * gCoeffs[16] + (float)(rsGetElementAt_uchar(gIn, x2, y3)) * gCoeffs[17] + (float)(rsGetElementAt_uchar(gIn, x3, y3)) * gCoeffs[18] + (float)(rsGetElementAt_uchar(gIn, x4, y3)) * gCoeffs[19]; float p4 = (float)(rsGetElementAt_uchar(gIn, x0, y4)) * gCoeffs[20] + (float)(rsGetElementAt_uchar(gIn, x1, y4)) * gCoeffs[21] + (float)(rsGetElementAt_uchar(gIn, x2, y4)) * gCoeffs[22] + (float)(rsGetElementAt_uchar(gIn, x3, y4)) * gCoeffs[23] + (float)(rsGetElementAt_uchar(gIn, x4, y4)) * gCoeffs[24]; return clamp(p0 + p1 + p2 + p3 + p4 + 0.5f, 0.f, 255.f); } float4 __attribute__((kernel)) convolve_F4(uint32_t x, uint32_t y) { uint32_t x0 = max((int32_t)x-2, 0); uint32_t x1 = max((int32_t)x-1, 0); uint32_t x2 = x; uint32_t x3 = min((int32_t)x+1, gWidth-1); uint32_t x4 = min((int32_t)x+2, gWidth-1); uint32_t y0 = max((int32_t)y-2, 0); uint32_t y1 = max((int32_t)y-1, 0); uint32_t y2 = y; uint32_t y3 = min((int32_t)y+1, gHeight-1); uint32_t y4 = min((int32_t)y+2, gHeight-1); float4 p0 = rsGetElementAt_float4(gIn, x0, y0) * gCoeffs[0] + rsGetElementAt_float4(gIn, x1, y0) * gCoeffs[1] + rsGetElementAt_float4(gIn, x2, y0) * gCoeffs[2] + rsGetElementAt_float4(gIn, x3, y0) * gCoeffs[3] + rsGetElementAt_float4(gIn, x4, y0) * gCoeffs[4]; float4 p1 = rsGetElementAt_float4(gIn, x0, y1) * gCoeffs[5] + rsGetElementAt_float4(gIn, x1, y1) * gCoeffs[6] + rsGetElementAt_float4(gIn, x2, y1) * gCoeffs[7] + rsGetElementAt_float4(gIn, x3, y1) * gCoeffs[8] + rsGetElementAt_float4(gIn, x4, y1) * gCoeffs[9]; float4 p2 = rsGetElementAt_float4(gIn, x0, y2) * gCoeffs[10] + rsGetElementAt_float4(gIn, x1, y2) * gCoeffs[11] + rsGetElementAt_float4(gIn, x2, y2) * gCoeffs[12] + rsGetElementAt_float4(gIn, x3, y2) * gCoeffs[13] + rsGetElementAt_float4(gIn, x4, y2) * gCoeffs[14]; float4 p3 = rsGetElementAt_float4(gIn, x0, y3) * gCoeffs[15] + rsGetElementAt_float4(gIn, x1, y3) * gCoeffs[16] + rsGetElementAt_float4(gIn, x2, y3) * gCoeffs[17] + rsGetElementAt_float4(gIn, x3, y3) * gCoeffs[18] + rsGetElementAt_float4(gIn, x4, y3) * gCoeffs[19]; float4 p4 = rsGetElementAt_float4(gIn, x0, y4) * gCoeffs[20] + rsGetElementAt_float4(gIn, x1, y4) * gCoeffs[21] + rsGetElementAt_float4(gIn, x2, y4) * gCoeffs[22] + rsGetElementAt_float4(gIn, x3, y4) * gCoeffs[23] + rsGetElementAt_float4(gIn, x4, y4) * gCoeffs[24]; return p0 + p1 + p2 + p3 + p4; } float3 __attribute__((kernel)) convolve_F3(uint32_t x, uint32_t y) { uint32_t x0 = max((int32_t)x-2, 0); uint32_t x1 = max((int32_t)x-1, 0); uint32_t x2 = x; uint32_t x3 = min((int32_t)x+1, gWidth-1); uint32_t x4 = min((int32_t)x+2, gWidth-1); uint32_t y0 = max((int32_t)y-2, 0); uint32_t y1 = max((int32_t)y-1, 0); uint32_t y2 = y; uint32_t y3 = min((int32_t)y+1, gHeight-1); uint32_t y4 = min((int32_t)y+2, gHeight-1); float3 p0 = rsGetElementAt_float3(gIn, x0, y0) * gCoeffs[0] + rsGetElementAt_float3(gIn, x1, y0) * gCoeffs[1] + rsGetElementAt_float3(gIn, x2, y0) * gCoeffs[2] + rsGetElementAt_float3(gIn, x3, y0) * gCoeffs[3] + rsGetElementAt_float3(gIn, x4, y0) * gCoeffs[4]; float3 p1 = rsGetElementAt_float3(gIn, x0, y1) * gCoeffs[5] + rsGetElementAt_float3(gIn, x1, y1) * gCoeffs[6] + rsGetElementAt_float3(gIn, x2, y1) * gCoeffs[7] + rsGetElementAt_float3(gIn, x3, y1) * gCoeffs[8] + rsGetElementAt_float3(gIn, x4, y1) * gCoeffs[9]; float3 p2 = rsGetElementAt_float3(gIn, x0, y2) * gCoeffs[10] + rsGetElementAt_float3(gIn, x1, y2) * gCoeffs[11] + rsGetElementAt_float3(gIn, x2, y2) * gCoeffs[12] + rsGetElementAt_float3(gIn, x3, y2) * gCoeffs[13] + rsGetElementAt_float3(gIn, x4, y2) * gCoeffs[14]; float3 p3 = rsGetElementAt_float3(gIn, x0, y3) * gCoeffs[15] + rsGetElementAt_float3(gIn, x1, y3) * gCoeffs[16] + rsGetElementAt_float3(gIn, x2, y3) * gCoeffs[17] + rsGetElementAt_float3(gIn, x3, y3) * gCoeffs[18] + rsGetElementAt_float3(gIn, x4, y3) * gCoeffs[19]; float3 p4 = rsGetElementAt_float3(gIn, x0, y4) * gCoeffs[20] + rsGetElementAt_float3(gIn, x1, y4) * gCoeffs[21] + rsGetElementAt_float3(gIn, x2, y4) * gCoeffs[22] + rsGetElementAt_float3(gIn, x3, y4) * gCoeffs[23] + rsGetElementAt_float3(gIn, x4, y4) * gCoeffs[24]; return p0 + p1 + p2 + p3 + p4; } float2 __attribute__((kernel)) convolve_F2(uint32_t x, uint32_t y) { uint32_t x0 = max((int32_t)x-2, 0); uint32_t x1 = max((int32_t)x-1, 0); uint32_t x2 = x; uint32_t x3 = min((int32_t)x+1, gWidth-1); uint32_t x4 = min((int32_t)x+2, gWidth-1); uint32_t y0 = max((int32_t)y-2, 0); uint32_t y1 = max((int32_t)y-1, 0); uint32_t y2 = y; uint32_t y3 = min((int32_t)y+1, gHeight-1); uint32_t y4 = min((int32_t)y+2, gHeight-1); float2 p0 = rsGetElementAt_float2(gIn, x0, y0) * gCoeffs[0] + rsGetElementAt_float2(gIn, x1, y0) * gCoeffs[1] + rsGetElementAt_float2(gIn, x2, y0) * gCoeffs[2] + rsGetElementAt_float2(gIn, x3, y0) * gCoeffs[3] + rsGetElementAt_float2(gIn, x4, y0) * gCoeffs[4]; float2 p1 = rsGetElementAt_float2(gIn, x0, y1) * gCoeffs[5] + rsGetElementAt_float2(gIn, x1, y1) * gCoeffs[6] + rsGetElementAt_float2(gIn, x2, y1) * gCoeffs[7] + rsGetElementAt_float2(gIn, x3, y1) * gCoeffs[8] + rsGetElementAt_float2(gIn, x4, y1) * gCoeffs[9]; float2 p2 = rsGetElementAt_float2(gIn, x0, y2) * gCoeffs[10] + rsGetElementAt_float2(gIn, x1, y2) * gCoeffs[11] + rsGetElementAt_float2(gIn, x2, y2) * gCoeffs[12] + rsGetElementAt_float2(gIn, x3, y2) * gCoeffs[13] + rsGetElementAt_float2(gIn, x4, y2) * gCoeffs[14]; float2 p3 = rsGetElementAt_float2(gIn, x0, y3) * gCoeffs[15] + rsGetElementAt_float2(gIn, x1, y3) * gCoeffs[16] + rsGetElementAt_float2(gIn, x2, y3) * gCoeffs[17] + rsGetElementAt_float2(gIn, x3, y3) * gCoeffs[18] + rsGetElementAt_float2(gIn, x4, y3) * gCoeffs[19]; float2 p4 = rsGetElementAt_float2(gIn, x0, y4) * gCoeffs[20] + rsGetElementAt_float2(gIn, x1, y4) * gCoeffs[21] + rsGetElementAt_float2(gIn, x2, y4) * gCoeffs[22] + rsGetElementAt_float2(gIn, x3, y4) * gCoeffs[23] + rsGetElementAt_float2(gIn, x4, y4) * gCoeffs[24]; return p0 + p1 + p2 + p3 + p4; } float __attribute__((kernel)) convolve_F1(uint32_t x, uint32_t y) { uint32_t x0 = max((int32_t)x-2, 0); uint32_t x1 = max((int32_t)x-1, 0); uint32_t x2 = x; uint32_t x3 = min((int32_t)x+1, gWidth-1); uint32_t x4 = min((int32_t)x+2, gWidth-1); uint32_t y0 = max((int32_t)y-2, 0); uint32_t y1 = max((int32_t)y-1, 0); uint32_t y2 = y; uint32_t y3 = min((int32_t)y+1, gHeight-1); uint32_t y4 = min((int32_t)y+2, gHeight-1); float p0 = rsGetElementAt_float(gIn, x0, y0) * gCoeffs[0] + rsGetElementAt_float(gIn, x1, y0) * gCoeffs[1] + rsGetElementAt_float(gIn, x2, y0) * gCoeffs[2] + rsGetElementAt_float(gIn, x3, y0) * gCoeffs[3] + rsGetElementAt_float(gIn, x4, y0) * gCoeffs[4]; float p1 = rsGetElementAt_float(gIn, x0, y1) * gCoeffs[5] + rsGetElementAt_float(gIn, x1, y1) * gCoeffs[6] + rsGetElementAt_float(gIn, x2, y1) * gCoeffs[7] + rsGetElementAt_float(gIn, x3, y1) * gCoeffs[8] + rsGetElementAt_float(gIn, x4, y1) * gCoeffs[9]; float p2 = rsGetElementAt_float(gIn, x0, y2) * gCoeffs[10] + rsGetElementAt_float(gIn, x1, y2) * gCoeffs[11] + rsGetElementAt_float(gIn, x2, y2) * gCoeffs[12] + rsGetElementAt_float(gIn, x3, y2) * gCoeffs[13] + rsGetElementAt_float(gIn, x4, y2) * gCoeffs[14]; float p3 = rsGetElementAt_float(gIn, x0, y3) * gCoeffs[15] + rsGetElementAt_float(gIn, x1, y3) * gCoeffs[16] + rsGetElementAt_float(gIn, x2, y3) * gCoeffs[17] + rsGetElementAt_float(gIn, x3, y3) * gCoeffs[18] + rsGetElementAt_float(gIn, x4, y3) * gCoeffs[19]; float p4 = rsGetElementAt_float(gIn, x0, y4) * gCoeffs[20] + rsGetElementAt_float(gIn, x1, y4) * gCoeffs[21] + rsGetElementAt_float(gIn, x2, y4) * gCoeffs[22] + rsGetElementAt_float(gIn, x3, y4) * gCoeffs[23] + rsGetElementAt_float(gIn, x4, y4) * gCoeffs[24]; return p0 + p1 + p2 + p3 + p4; }
s20121035/rk3288_android5.1_repo
cts/tests/tests/renderscript/src/android/renderscript/cts/intrinsic_convolve5x5.rs
Rust
gpl-3.0
19,242
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18034 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ScreenCapture.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("True")] public bool FirstRun { get { return ((bool)(this["FirstRun"])); } set { this["FirstRun"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string DefaultFolder { get { return ((string)(this["DefaultFolder"])); } set { this["DefaultFolder"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("True")] public bool CaptureMouse { get { return ((bool)(this["CaptureMouse"])); } set { this["CaptureMouse"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool CaptureClick { get { return ((bool)(this["CaptureClick"])); } set { this["CaptureClick"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool CaptureKeys { get { return ((bool)(this["CaptureKeys"])); } set { this["CaptureKeys"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("24")] public double FrameRate { get { return ((double)(this["FrameRate"])); } set { this["FrameRate"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("avi")] public string Container { get { return ((string)(this["Container"])); } set { this["Container"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool ShowConversionOnFinish { get { return ((bool)(this["ShowConversionOnFinish"])); } set { this["ShowConversionOnFinish"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("True")] public bool CanUpgrade { get { return ((bool)(this["CanUpgrade"])); } set { this["CanUpgrade"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool CaptureAudio { get { return ((bool)(this["CaptureAudio"])); } set { this["CaptureAudio"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("22050")] public int SampleRate { get { return ((int)(this["SampleRate"])); } set { this["SampleRate"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("Segoe UI, 30pt")] public global::System.Drawing.Font KeyboardFont { get { return ((global::System.Drawing.Font)(this["KeyboardFont"])); } set { this["KeyboardFont"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public global::System.Collections.Specialized.StringCollection LastAudioDevices { get { return ((global::System.Collections.Specialized.StringCollection)(this["LastAudioDevices"])); } set { this["LastAudioDevices"] = value; } } } }
tbayart/screencast-capture
Sources/Properties/Settings.Designer.cs
C#
gpl-3.0
6,944
.dijitRtl .soria .dijitEditorIcon {background-image: url('images/editor_rtl.gif');}.dijitRtl .soria .dijitDisabled .dijitEditorIcon {background-image: url('images/editorDisabled_rtl.gif');}.dijitRtl .soria .dijitToolbar .dijitToolbarSeparator {background-image: url('images/editor_rtl.gif');}
Emergen/zivios-panel
web/public/scripts/release/zvinstaller-0.6.6/dijit/themes/soria/Editor_rtl.css
CSS
gpl-3.0
292
//---------------------------------------------------------------------------- /** @file GoUctEstimatorStat.cpp See GoUctEstimatorStat.h */ //---------------------------------------------------------------------------- #include "SgSystem.h" #include "GoUctEstimatorStat.h" #include <boost/format.hpp> #include "GoModBoard.h" #include "GoUctSearch.h" #include "SgDebug.h" #include "SgUctTreeUtil.h" using boost::format; //---------------------------------------------------------------------------- void GoUctEstimatorStat::Compute(GoUctSearch& search, std::size_t trueValueMaxGames, std::size_t maxGames, std::size_t stepSize, const std::string& fileName) { double maxTime = std::numeric_limits<double>::max(); std::vector<SgUctMoveInfo> moves; search.GenerateAllMoves(moves); SgArray<SgUctValue,SG_PASS + 1> trueValues; for (size_t i = 0; i < moves.size(); ++i) { SgPoint p = moves[i].m_move; GoModBoard modBoard(search.Board()); modBoard.Board().Play(p); std::vector<SgMove> sequence; SgUctValue value = search.Search(SgUctValue(trueValueMaxGames), maxTime, sequence); trueValues[p] = SgUctSearch::InverseEstimate(value); modBoard.Board().Undo(); } search.StartSearch(); if (search.MpiSynchronizer()->IsRootProcess()) { std::ofstream out(fileName.c_str(), std::ios::app); for (size_t n = 0; n < maxGames; n += stepSize) { search.PlayGame(); for (size_t i = 0; i < moves.size(); ++i) { SgPoint p = moves[i].m_move; const SgUctTree& tree = search.Tree(); const SgUctNode* child = SgUctTreeUtil::FindChildWithMove(tree, tree.Root(), p); if (child == 0) continue; // Root may not have been expanded yet out << (format("%1$d\t" "%2$.2f\t" "%3$d\t" "%4$.2f\t" "%5$d\t" "%6$.2f\n" ) % n // 1 % trueValues[p] // 2 % child->MoveCount() // 3 % (child->HasMean() ? SgUctSearch::InverseEstimate(child->Mean()) : 0) // 4 % child->RaveCount() // 5 % (child->HasRaveValue() ? child->RaveValue() : 0) // 6 ); } } } search.EndSearch(); } //----------------------------------------------------------------------------
liushiwei/fuego
gouct/GoUctEstimatorStat.cpp
C++
gpl-3.0
2,701
/* const config = require('./config'); const Steam = require('steam'); const Dota2 = require('dota2'); const utility = require('./utility'); const async = require('async'); const convert64To32 = utility.convert64to32; const express = require('express'); const app = express(); const users = config.STEAM_USER.split(','); const passes = config.STEAM_PASS.split(','); const steamObj = {}; const accountToIdx = {}; const replayRequests = 0; const launch = new Date(); let launched = false; const a = []; const port = config.PORT || config.RETRIEVER_PORT; // create array of numbers from 0 to n const count = 0; while (a.length < users.length) a.push(a.length + 0); async.each(a, (i, cb) => { let dotaReady = false; const relationshipReady = false; const client = new Steam.SteamClient(); client.steamUser = new Steam.SteamUser(client); client.steamFriends = new Steam.SteamFriends(client); client.Dota2 = new Dota2.Dota2Client(client, false, false); const user = users[i]; const pass = passes[i]; const logOnDetails = { account_name: user, password: pass, }; client.connect(); client.on('connected', () => { console.log('[STEAM] Trying to log on with %s,%s', user, pass); client.steamUser.logOn(logOnDetails); client.once('error', (e) => { // reset console.log(e); console.log('reconnecting'); client.connect(); }); }); client.on('logOnResponse', (logonResp) => { if (logonResp.eresult !== Steam.EResult.OK) { // try logging on again return client.steamUser.logOn(logOnDetails); } console.log('[STEAM] Logged on %s', client.steamID); client.steamFriends.setPersonaName(client.steamID); steamObj[client.steamID] = client; client.Dota2.launch(); client.Dota2.once('ready', () => { // console.log("Dota 2 ready"); dotaReady = true; const dota = client.Dota2; dota.inviteToParty(utility.convert32to64(88367253).toString()); setTimeout(() => { console.log('lobby'); dota.leavePracticeLobby(); dota.on('practiceLobbyUpdate', (msg) => { console.log(msg); }); dota.createPracticeLobby(); }, 10000); cb(); }); client.once('loggedOff', () => { console.log('relogging'); client.steamUser.logOn(logOnDetails); }); }); }, () => { // start listening launched = true; const server = app.listen(port, () => { const host = server.address().address; console.log('[RETRIEVER] listening at http://%s:%s', host, port); }); app.get('/', (req, res, next) => {}); }); */
coreymaher/yasp
dev/lobby.js
JavaScript
gpl-3.0
2,616