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
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Oauth * @subpackage UnitTests * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ require_once 'Zend/Oauth/Signature/Plaintext.php'; /** * @category Zend * @package Zend_Oauth * @subpackage UnitTests * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Oauth * @group Zend_Oauth_Signature */ class Zend_Oauth_Signature_PlaintextTest extends PHPUnit_Framework_TestCase { public function testSignatureWithoutAccessSecretIsOnlyConsumerSecretString() { $params = array( 'oauth_version' => '1.0', 'oauth_consumer_key' => 'dpf43f3p2l4k3l03', 'oauth_signature_method' => 'PLAINTEXT', 'oauth_timestamp' => '1191242090', 'oauth_nonce' => 'hsu94j3884jdopsl', 'oauth_version' => '1.0' ); $signature = new Zend_Oauth_Signature_Plaintext('1234567890'); $this->assertEquals('1234567890&', $signature->sign($params)); } public function testSignatureWithAccessSecretIsConsumerAndAccessSecretStringsConcatWithAmp() { $params = array( 'oauth_version' => '1.0', 'oauth_consumer_key' => 'dpf43f3p2l4k3l03', 'oauth_signature_method' => 'PLAINTEXT', 'oauth_timestamp' => '1191242090', 'oauth_nonce' => 'hsu94j3884jdopsl', 'oauth_version' => '1.0' ); $signature = new Zend_Oauth_Signature_Plaintext('1234567890', '0987654321'); $this->assertEquals('1234567890&0987654321', $signature->sign($params)); } }
sandsmedia/zf
tests/Zend/Oauth/Oauth/Signature/PlaintextTest.php
PHP
bsd-3-clause
2,306
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * 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 Google Inc. 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. */ /** * @constructor * @param {!Element} relativeToElement * @param {!WebInspector.DialogDelegate} delegate */ WebInspector.Dialog = function(relativeToElement, delegate) { this._delegate = delegate; this._relativeToElement = relativeToElement; this._glassPane = new WebInspector.GlassPane(/** @type {!Document} */ (relativeToElement.ownerDocument)); WebInspector.GlassPane.DefaultFocusedViewStack.push(this); // Install glass pane capturing events. this._glassPane.element.tabIndex = 0; this._glassPane.element.addEventListener("focus", this._onGlassPaneFocus.bind(this), false); this._element = this._glassPane.element.createChild("div"); this._element.tabIndex = 0; this._element.addEventListener("focus", this._onFocus.bind(this), false); this._element.addEventListener("keydown", this._onKeyDown.bind(this), false); this._closeKeys = [ WebInspector.KeyboardShortcut.Keys.Enter.code, WebInspector.KeyboardShortcut.Keys.Esc.code, ]; delegate.show(this._element); this._position(); this._delegate.focus(); } /** * @return {?WebInspector.Dialog} */ WebInspector.Dialog.currentInstance = function() { return WebInspector.Dialog._instance; } /** * @param {!Element} relativeToElement * @param {!WebInspector.DialogDelegate} delegate */ WebInspector.Dialog.show = function(relativeToElement, delegate) { if (WebInspector.Dialog._instance) return; WebInspector.Dialog._instance = new WebInspector.Dialog(relativeToElement, delegate); } WebInspector.Dialog.hide = function() { if (!WebInspector.Dialog._instance) return; WebInspector.Dialog._instance._hide(); } WebInspector.Dialog.prototype = { focus: function() { this._element.focus(); }, _hide: function() { if (this._isHiding) return; this._isHiding = true; this._delegate.willHide(); delete WebInspector.Dialog._instance; WebInspector.GlassPane.DefaultFocusedViewStack.pop(); this._glassPane.dispose(); }, _onGlassPaneFocus: function(event) { this._hide(); }, _onFocus: function(event) { this._delegate.focus(); }, _position: function() { this._delegate.position(this._element, this._relativeToElement); }, _onKeyDown: function(event) { if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Tab.code) { event.preventDefault(); return; } if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Enter.code) this._delegate.onEnter(event); if (!event.handled && this._closeKeys.indexOf(event.keyCode) >= 0) { this._hide(); event.consume(true); } } }; /** * @constructor * @extends {WebInspector.Object} */ WebInspector.DialogDelegate = function() { /** @type {!Element} */ this.element; } WebInspector.DialogDelegate.prototype = { /** * @param {!Element} element */ show: function(element) { element.appendChild(this.element); this.element.classList.add("dialog-contents"); element.classList.add("dialog"); }, /** * @param {!Element} element * @param {!Element} relativeToElement */ position: function(element, relativeToElement) { var container = WebInspector.Dialog._modalHostView.element; var box = relativeToElement.boxInWindow(window).relativeToElement(container); var positionX = box.x + (relativeToElement.offsetWidth - element.offsetWidth) / 2; positionX = Number.constrain(positionX, 0, container.offsetWidth - element.offsetWidth); var positionY = box.y + (relativeToElement.offsetHeight - element.offsetHeight) / 2; positionY = Number.constrain(positionY, 0, container.offsetHeight - element.offsetHeight); element.style.position = "absolute"; element.positionAt(positionX, positionY, container); }, focus: function() { }, onEnter: function(event) { }, willHide: function() { }, __proto__: WebInspector.Object.prototype } /** @type {?WebInspector.View} */ WebInspector.Dialog._modalHostView = null; /** * @param {!WebInspector.View} view */ WebInspector.Dialog.setModalHostView = function(view) { WebInspector.Dialog._modalHostView = view; }; /** * FIXME: make utility method in Dialog, so clients use it instead of this getter. * Method should be like Dialog.showModalElement(position params, reposition callback). * @return {?WebInspector.View} */ WebInspector.Dialog.modalHostView = function() { return WebInspector.Dialog._modalHostView; }; WebInspector.Dialog.modalHostRepositioned = function() { if (WebInspector.Dialog._instance) WebInspector.Dialog._instance._position(); };
CTSRD-SOAAP/chromium-42.0.2311.135
third_party/WebKit/Source/devtools/front_end/ui/Dialog.js
JavaScript
bsd-3-clause
6,428
//===- ModuleFile.cpp - Module description --------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the ModuleFile class, which describes a module that // has been loaded from an AST file. // //===----------------------------------------------------------------------===// #include "clang/Serialization/ModuleFile.h" #include "ASTReaderInternals.h" #include "clang/Serialization/ContinuousRangeMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace serialization; using namespace reader; ModuleFile::~ModuleFile() { delete static_cast<ASTIdentifierLookupTable *>(IdentifierLookupTable); delete static_cast<HeaderFileInfoLookupTable *>(HeaderFileInfoTable); delete static_cast<ASTSelectorLookupTable *>(SelectorLookupTable); } template<typename Key, typename Offset, unsigned InitialCapacity> static void dumpLocalRemap(StringRef Name, const ContinuousRangeMap<Key, Offset, InitialCapacity> &Map) { if (Map.begin() == Map.end()) return; using MapType = ContinuousRangeMap<Key, Offset, InitialCapacity>; llvm::errs() << " " << Name << ":\n"; for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); I != IEnd; ++I) { llvm::errs() << " " << I->first << " -> " << I->second << "\n"; } } LLVM_DUMP_METHOD void ModuleFile::dump() { llvm::errs() << "\nModule: " << FileName << "\n"; if (!Imports.empty()) { llvm::errs() << " Imports: "; for (unsigned I = 0, N = Imports.size(); I != N; ++I) { if (I) llvm::errs() << ", "; llvm::errs() << Imports[I]->FileName; } llvm::errs() << "\n"; } // Remapping tables. llvm::errs() << " Base source location offset: " << SLocEntryBaseOffset << '\n'; dumpLocalRemap("Source location offset local -> global map", SLocRemap); llvm::errs() << " Base identifier ID: " << BaseIdentifierID << '\n' << " Number of identifiers: " << LocalNumIdentifiers << '\n'; dumpLocalRemap("Identifier ID local -> global map", IdentifierRemap); llvm::errs() << " Base macro ID: " << BaseMacroID << '\n' << " Number of macros: " << LocalNumMacros << '\n'; dumpLocalRemap("Macro ID local -> global map", MacroRemap); llvm::errs() << " Base submodule ID: " << BaseSubmoduleID << '\n' << " Number of submodules: " << LocalNumSubmodules << '\n'; dumpLocalRemap("Submodule ID local -> global map", SubmoduleRemap); llvm::errs() << " Base selector ID: " << BaseSelectorID << '\n' << " Number of selectors: " << LocalNumSelectors << '\n'; dumpLocalRemap("Selector ID local -> global map", SelectorRemap); llvm::errs() << " Base preprocessed entity ID: " << BasePreprocessedEntityID << '\n' << " Number of preprocessed entities: " << NumPreprocessedEntities << '\n'; dumpLocalRemap("Preprocessed entity ID local -> global map", PreprocessedEntityRemap); llvm::errs() << " Base type index: " << BaseTypeIndex << '\n' << " Number of types: " << LocalNumTypes << '\n'; dumpLocalRemap("Type index local -> global map", TypeRemap); llvm::errs() << " Base decl ID: " << BaseDeclID << '\n' << " Number of decls: " << LocalNumDecls << '\n'; dumpLocalRemap("Decl ID local -> global map", DeclRemap); }
endlessm/chromium-browser
third_party/llvm/clang/lib/Serialization/ModuleFile.cpp
C++
bsd-3-clause
3,727
/* * (C) Copyright David Brownell 2000-2002 * Copyright (c) 2005 MontaVista Software * * 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. * * Ported to 834x by Randy Vinson <rvinson@mvista.com> using code provided * by Hunter Wu. */ #include <linux/platform_device.h> #include <linux/fsl_devices.h> #include "ehci-fsl.h" /* FIXME: Power Managment is un-ported so temporarily disable it */ #undef CONFIG_PM /* PCI-based HCs are common, but plenty of non-PCI HCs are used too */ /* configure so an HC device and id are always provided */ /* always called with process context; sleeping is OK */ /** * usb_hcd_fsl_probe - initialize FSL-based HCDs * @drvier: Driver to be used for this HCD * @pdev: USB Host Controller being probed * Context: !in_interrupt() * * Allocates basic resources for this USB host controller. * */ int usb_hcd_fsl_probe(const struct hc_driver *driver, struct platform_device *pdev) { struct fsl_usb2_platform_data *pdata; struct usb_hcd *hcd; struct resource *res; int irq; int retval; unsigned int temp; pr_debug("initializing FSL-SOC USB Controller\n"); /* Need platform data for setup */ pdata = (struct fsl_usb2_platform_data *)pdev->dev.platform_data; if (!pdata) { dev_err(&pdev->dev, "No platform data for %s.\n", pdev->dev.bus_id); return -ENODEV; } /* * This is a host mode driver, verify that we're supposed to be * in host mode. */ if (!((pdata->operating_mode == FSL_USB2_DR_HOST) || (pdata->operating_mode == FSL_USB2_MPH_HOST))) { dev_err(&pdev->dev, "Non Host Mode configured for %s. Wrong driver linked.\n", pdev->dev.bus_id); return -ENODEV; } res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); if (!res) { dev_err(&pdev->dev, "Found HC with no IRQ. Check %s setup!\n", pdev->dev.bus_id); return -ENODEV; } irq = res->start; hcd = usb_create_hcd(driver, &pdev->dev, pdev->dev.bus_id); if (!hcd) { retval = -ENOMEM; goto err1; } res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "Found HC with no register addr. Check %s setup!\n", pdev->dev.bus_id); retval = -ENODEV; goto err2; } hcd->rsrc_start = res->start; hcd->rsrc_len = res->end - res->start + 1; if (!request_mem_region(hcd->rsrc_start, hcd->rsrc_len, driver->description)) { dev_dbg(&pdev->dev, "controller already in use\n"); retval = -EBUSY; goto err2; } hcd->regs = ioremap(hcd->rsrc_start, hcd->rsrc_len); if (hcd->regs == NULL) { dev_dbg(&pdev->dev, "error mapping memory\n"); retval = -EFAULT; goto err3; } /* Enable USB controller */ temp = in_be32(hcd->regs + 0x500); out_be32(hcd->regs + 0x500, temp | 0x4); /* Set to Host mode */ temp = in_le32(hcd->regs + 0x1a8); out_le32(hcd->regs + 0x1a8, temp | 0x3); retval = usb_add_hcd(hcd, irq, IRQF_SHARED); if (retval != 0) goto err4; return retval; err4: iounmap(hcd->regs); err3: release_mem_region(hcd->rsrc_start, hcd->rsrc_len); err2: usb_put_hcd(hcd); err1: dev_err(&pdev->dev, "init %s fail, %d\n", pdev->dev.bus_id, retval); return retval; } /* may be called without controller electrically present */ /* may be called with controller, bus, and devices active */ /** * usb_hcd_fsl_remove - shutdown processing for FSL-based HCDs * @dev: USB Host Controller being removed * Context: !in_interrupt() * * Reverses the effect of usb_hcd_fsl_probe(). * */ void usb_hcd_fsl_remove(struct usb_hcd *hcd, struct platform_device *pdev) { usb_remove_hcd(hcd); iounmap(hcd->regs); release_mem_region(hcd->rsrc_start, hcd->rsrc_len); usb_put_hcd(hcd); } static void mpc83xx_setup_phy(struct ehci_hcd *ehci, enum fsl_usb2_phy_modes phy_mode, unsigned int port_offset) { u32 portsc = 0; switch (phy_mode) { case FSL_USB2_PHY_ULPI: portsc |= PORT_PTS_ULPI; break; case FSL_USB2_PHY_SERIAL: portsc |= PORT_PTS_SERIAL; break; case FSL_USB2_PHY_UTMI_WIDE: portsc |= PORT_PTS_PTW; /* fall through */ case FSL_USB2_PHY_UTMI: portsc |= PORT_PTS_UTMI; break; case FSL_USB2_PHY_NONE: break; } ehci_writel(ehci, portsc, &ehci->regs->port_status[port_offset]); } static void mpc83xx_usb_setup(struct usb_hcd *hcd) { struct ehci_hcd *ehci = hcd_to_ehci(hcd); struct fsl_usb2_platform_data *pdata; void __iomem *non_ehci = hcd->regs; pdata = (struct fsl_usb2_platform_data *)hcd->self.controller-> platform_data; /* Enable PHY interface in the control reg. */ out_be32(non_ehci + FSL_SOC_USB_CTRL, 0x00000004); out_be32(non_ehci + FSL_SOC_USB_SNOOP1, 0x0000001b); #if defined(CONFIG_PPC32) && !defined(CONFIG_NOT_COHERENT_CACHE) /* * Turn on cache snooping hardware, since some PowerPC platforms * wholly rely on hardware to deal with cache coherent */ /* Setup Snooping for all the 4GB space */ /* SNOOP1 starts from 0x0, size 2G */ out_be32(non_ehci + FSL_SOC_USB_SNOOP1, 0x0 | SNOOP_SIZE_2GB); /* SNOOP2 starts from 0x80000000, size 2G */ out_be32(non_ehci + FSL_SOC_USB_SNOOP2, 0x80000000 | SNOOP_SIZE_2GB); #endif if (pdata->operating_mode == FSL_USB2_DR_HOST) mpc83xx_setup_phy(ehci, pdata->phy_mode, 0); if (pdata->operating_mode == FSL_USB2_MPH_HOST) { unsigned int chip, rev, svr; svr = mfspr(SPRN_SVR); chip = svr >> 16; rev = (svr >> 4) & 0xf; /* Deal with USB Erratum #14 on MPC834x Rev 1.0 & 1.1 chips */ if ((rev == 1) && (chip >= 0x8050) && (chip <= 0x8055)) ehci->has_fsl_port_bug = 1; if (pdata->port_enables & FSL_USB2_PORT0_ENABLED) mpc83xx_setup_phy(ehci, pdata->phy_mode, 0); if (pdata->port_enables & FSL_USB2_PORT1_ENABLED) mpc83xx_setup_phy(ehci, pdata->phy_mode, 1); } /* put controller in host mode. */ ehci_writel(ehci, 0x00000003, non_ehci + FSL_SOC_USB_USBMODE); out_be32(non_ehci + FSL_SOC_USB_PRICTRL, 0x0000000c); out_be32(non_ehci + FSL_SOC_USB_AGECNTTHRSH, 0x00000040); out_be32(non_ehci + FSL_SOC_USB_SICTRL, 0x00000001); } /* called after powerup, by probe or system-pm "wakeup" */ static int ehci_fsl_reinit(struct ehci_hcd *ehci) { mpc83xx_usb_setup(ehci_to_hcd(ehci)); ehci_port_power(ehci, 0); return 0; } /* called during probe() after chip reset completes */ static int ehci_fsl_setup(struct usb_hcd *hcd) { struct ehci_hcd *ehci = hcd_to_ehci(hcd); int retval; /* EHCI registers start at offset 0x100 */ ehci->caps = hcd->regs + 0x100; ehci->regs = hcd->regs + 0x100 + HC_LENGTH(ehci_readl(ehci, &ehci->caps->hc_capbase)); dbg_hcs_params(ehci, "reset"); dbg_hcc_params(ehci, "reset"); /* cache this readonly data; minimize chip reads */ ehci->hcs_params = ehci_readl(ehci, &ehci->caps->hcs_params); retval = ehci_halt(ehci); if (retval) return retval; /* data structure init */ retval = ehci_init(hcd); if (retval) return retval; ehci->is_tdi_rh_tt = 1; ehci->sbrn = 0x20; ehci_reset(ehci); retval = ehci_fsl_reinit(ehci); return retval; } static const struct hc_driver ehci_fsl_hc_driver = { .description = hcd_name, .product_desc = "Freescale On-Chip EHCI Host Controller", .hcd_priv_size = sizeof(struct ehci_hcd), /* * generic hardware linkage */ .irq = ehci_irq, .flags = HCD_USB2, /* * basic lifecycle operations */ .reset = ehci_fsl_setup, .start = ehci_run, #ifdef CONFIG_PM .suspend = ehci_bus_suspend, .resume = ehci_bus_resume, #endif .stop = ehci_stop, .shutdown = ehci_shutdown, /* * managing i/o requests and associated device resources */ .urb_enqueue = ehci_urb_enqueue, .urb_dequeue = ehci_urb_dequeue, .endpoint_disable = ehci_endpoint_disable, /* * scheduling support */ .get_frame_number = ehci_get_frame, /* * root hub support */ .hub_status_data = ehci_hub_status_data, .hub_control = ehci_hub_control, .bus_suspend = ehci_bus_suspend, .bus_resume = ehci_bus_resume, }; static int ehci_fsl_drv_probe(struct platform_device *pdev) { if (usb_disabled()) return -ENODEV; return usb_hcd_fsl_probe(&ehci_fsl_hc_driver, pdev); } static int ehci_fsl_drv_remove(struct platform_device *pdev) { struct usb_hcd *hcd = platform_get_drvdata(pdev); usb_hcd_fsl_remove(hcd, pdev); return 0; } MODULE_ALIAS("fsl-ehci"); static struct platform_driver ehci_fsl_driver = { .probe = ehci_fsl_drv_probe, .remove = ehci_fsl_drv_remove, .shutdown = usb_hcd_platform_shutdown, .driver = { .name = "fsl-ehci", }, };
ut-osa/laminar
linux-2.6.22.6/drivers/usb/host/ehci-fsl.c
C
bsd-3-clause
9,011
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- /* Copyright (c) 2007, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * 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 Google Inc. 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. * * --- * Author: Joi Sigurdsson * Author: Scott Francis * * Implementation of PreamblePatcher */ #include "preamble_patcher.h" #include "mini_disassembler.h" // compatibility shims #include "base/logging.h" // Definitions of assembly statements we need #define ASM_JMP32REL 0xE9 #define ASM_INT3 0xCC #define ASM_JMP32ABS_0 0xFF #define ASM_JMP32ABS_1 0x25 #define ASM_JMP8REL 0xEB #define ASM_JCC32REL_0 0x0F #define ASM_JCC32REL_1_MASK 0x80 #define ASM_NOP 0x90 // X64 opcodes #define ASM_REXW 0x48 #define ASM_MOVRAX_IMM 0xB8 #define ASM_JMP 0xFF #define ASM_JMP_RAX 0xE0 namespace sidestep { PreamblePatcher::PreamblePage* PreamblePatcher::preamble_pages_ = NULL; long PreamblePatcher::granularity_ = 0; long PreamblePatcher::pagesize_ = 0; bool PreamblePatcher::initialized_ = false; static const unsigned int kPreamblePageMagic = 0x4347414D; // "MAGC" // Handle a special case that we see with functions that point into an // IAT table (including functions linked statically into the // application): these function already starts with ASM_JMP32*. For // instance, malloc() might be implemented as a JMP to __malloc(). // This function follows the initial JMPs for us, until we get to the // place where the actual code is defined. If we get to STOP_BEFORE, // we return the address before stop_before. The stop_before_trampoline // flag is used in 64-bit mode. If true, we will return the address // before a trampoline is detected. Trampolines are defined as: // // nop // mov rax, <replacement_function> // jmp rax // // See PreamblePatcher::RawPatchWithStub for more information. void* PreamblePatcher::ResolveTargetImpl(unsigned char* target, unsigned char* stop_before, bool stop_before_trampoline) { if (target == NULL) return NULL; while (1) { unsigned char* new_target; if (target[0] == ASM_JMP32REL) { // target[1-4] holds the place the jmp goes to, but it's // relative to the next instruction. int relative_offset; // Windows guarantees int is 4 bytes SIDESTEP_ASSERT(sizeof(relative_offset) == 4); memcpy(reinterpret_cast<void*>(&relative_offset), reinterpret_cast<void*>(target + 1), 4); new_target = target + 5 + relative_offset; } else if (target[0] == ASM_JMP8REL) { // Visual Studio 7.1 implements new[] as an 8 bit jump to new signed char relative_offset; memcpy(reinterpret_cast<void*>(&relative_offset), reinterpret_cast<void*>(target + 1), 1); new_target = target + 2 + relative_offset; } else if (target[0] == ASM_JMP32ABS_0 && target[1] == ASM_JMP32ABS_1) { jmp32rel: // Visual studio seems to sometimes do it this way instead of the // previous way. Not sure what the rules are, but it was happening // with operator new in some binaries. void** new_target_v; if (kIs64BitBinary) { // In 64-bit mode JMPs are RIP-relative, not absolute int target_offset; memcpy(reinterpret_cast<void*>(&target_offset), reinterpret_cast<void*>(target + 2), 4); new_target_v = reinterpret_cast<void**>(target + target_offset + 6); } else { SIDESTEP_ASSERT(sizeof(new_target) == 4); memcpy(&new_target_v, reinterpret_cast<void*>(target + 2), 4); } new_target = reinterpret_cast<unsigned char*>(*new_target_v); } else if (kIs64BitBinary && target[0] == ASM_REXW && target[1] == ASM_JMP32ABS_0 && target[2] == ASM_JMP32ABS_1) { // in Visual Studio 2012 we're seeing jump like that: // rex.W jmpq *0x11d019(%rip) // // according to docs I have, rex prefix is actually unneeded and // can be ignored. I.e. docs say for jumps like that operand // already defaults to 64-bit. But clearly it breaks abs. jump // detection above and we just skip rex target++; goto jmp32rel; } else { break; } if (new_target == stop_before) break; if (stop_before_trampoline && *new_target == ASM_NOP && new_target[1] == ASM_REXW && new_target[2] == ASM_MOVRAX_IMM) break; target = new_target; } return target; } // Special case scoped_ptr to avoid dependency on scoped_ptr below. class DeleteUnsignedCharArray { public: DeleteUnsignedCharArray(unsigned char* array) : array_(array) { } ~DeleteUnsignedCharArray() { if (array_) { PreamblePatcher::FreePreambleBlock(array_); } } unsigned char* Release() { unsigned char* temp = array_; array_ = NULL; return temp; } private: unsigned char* array_; }; SideStepError PreamblePatcher::RawPatchWithStubAndProtections( void* target_function, void *replacement_function, unsigned char* preamble_stub, unsigned long stub_size, unsigned long* bytes_needed) { // We need to be able to write to a process-local copy of the first // MAX_PREAMBLE_STUB_SIZE bytes of target_function DWORD old_target_function_protect = 0; BOOL succeeded = ::VirtualProtect(reinterpret_cast<void*>(target_function), MAX_PREAMBLE_STUB_SIZE, PAGE_EXECUTE_READWRITE, &old_target_function_protect); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to make page containing target function " "copy-on-write."); return SIDESTEP_ACCESS_DENIED; } SideStepError error_code = RawPatchWithStub(target_function, replacement_function, preamble_stub, stub_size, bytes_needed); // Restore the protection of the first MAX_PREAMBLE_STUB_SIZE bytes of // pTargetFunction to what they were before we started goofing around. // We do this regardless of whether the patch succeeded or not. succeeded = ::VirtualProtect(reinterpret_cast<void*>(target_function), MAX_PREAMBLE_STUB_SIZE, old_target_function_protect, &old_target_function_protect); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to restore protection to target function."); // We must not return an error here because the function has // likely actually been patched, and returning an error might // cause our client code not to unpatch it. So we just keep // going. } if (SIDESTEP_SUCCESS != error_code) { // Testing RawPatchWithStub, above SIDESTEP_ASSERT(false); return error_code; } // Flush the instruction cache to make sure the processor doesn't execute the // old version of the instructions (before our patch). // // FlushInstructionCache is actually a no-op at least on // single-processor XP machines. I'm not sure why this is so, but // it is, yet I want to keep the call to the API here for // correctness in case there is a difference in some variants of // Windows/hardware. succeeded = ::FlushInstructionCache(::GetCurrentProcess(), target_function, MAX_PREAMBLE_STUB_SIZE); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to flush instruction cache."); // We must not return an error here because the function has actually // been patched, and returning an error would likely cause our client // code not to unpatch it. So we just keep going. } return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::RawPatch(void* target_function, void* replacement_function, void** original_function_stub) { if (!target_function || !replacement_function || !original_function_stub || (*original_function_stub) || target_function == replacement_function) { SIDESTEP_ASSERT(false && "Preconditions not met"); return SIDESTEP_INVALID_PARAMETER; } BOOL succeeded = FALSE; // First, deal with a special case that we see with functions that // point into an IAT table (including functions linked statically // into the application): these function already starts with // ASM_JMP32REL. For instance, malloc() might be implemented as a // JMP to __malloc(). In that case, we replace the destination of // the JMP (__malloc), rather than the JMP itself (malloc). This // way we get the correct behavior no matter how malloc gets called. void* new_target = ResolveTarget(target_function); if (new_target != target_function) { target_function = new_target; } // In 64-bit mode, preamble_stub must be within 2GB of target function // so that if target contains a jump, we can translate it. unsigned char* preamble_stub = AllocPreambleBlockNear(target_function); if (!preamble_stub) { SIDESTEP_ASSERT(false && "Unable to allocate preamble-stub."); return SIDESTEP_INSUFFICIENT_BUFFER; } // Frees the array at end of scope. DeleteUnsignedCharArray guard_preamble_stub(preamble_stub); SideStepError error_code = RawPatchWithStubAndProtections( target_function, replacement_function, preamble_stub, MAX_PREAMBLE_STUB_SIZE, NULL); if (SIDESTEP_SUCCESS != error_code) { SIDESTEP_ASSERT(false); return error_code; } // Flush the instruction cache to make sure the processor doesn't execute the // old version of the instructions (before our patch). // // FlushInstructionCache is actually a no-op at least on // single-processor XP machines. I'm not sure why this is so, but // it is, yet I want to keep the call to the API here for // correctness in case there is a difference in some variants of // Windows/hardware. succeeded = ::FlushInstructionCache(::GetCurrentProcess(), target_function, MAX_PREAMBLE_STUB_SIZE); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to flush instruction cache."); // We must not return an error here because the function has actually // been patched, and returning an error would likely cause our client // code not to unpatch it. So we just keep going. } SIDESTEP_LOG("PreamblePatcher::RawPatch successfully patched."); // detach the scoped pointer so the memory is not freed *original_function_stub = reinterpret_cast<void*>(guard_preamble_stub.Release()); return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::Unpatch(void* target_function, void* replacement_function, void* original_function_stub) { SIDESTEP_ASSERT(target_function && replacement_function && original_function_stub); if (!target_function || !replacement_function || !original_function_stub) { return SIDESTEP_INVALID_PARAMETER; } // Before unpatching, target_function should be a JMP to // replacement_function. If it's not, then either it's an error, or // we're falling into the case where the original instruction was a // JMP, and we patched the jumped_to address rather than the JMP // itself. (For instance, if malloc() is just a JMP to __malloc(), // we patched __malloc() and not malloc().) unsigned char* target = reinterpret_cast<unsigned char*>(target_function); target = reinterpret_cast<unsigned char*>( ResolveTargetImpl( target, reinterpret_cast<unsigned char*>(replacement_function), true)); // We should end at the function we patched. When we patch, we insert // a ASM_JMP32REL instruction, so look for that as a sanity check. if (target[0] != ASM_JMP32REL) { SIDESTEP_ASSERT(false && "target_function does not look like it was patched."); return SIDESTEP_INVALID_PARAMETER; } const unsigned int kRequiredTargetPatchBytes = 5; // We need to be able to write to a process-local copy of the first // kRequiredTargetPatchBytes bytes of target_function DWORD old_target_function_protect = 0; BOOL succeeded = ::VirtualProtect(reinterpret_cast<void*>(target), kRequiredTargetPatchBytes, PAGE_EXECUTE_READWRITE, &old_target_function_protect); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to make page containing target function " "copy-on-write."); return SIDESTEP_ACCESS_DENIED; } unsigned char* preamble_stub = reinterpret_cast<unsigned char*>( original_function_stub); // Disassemble the preamble of stub and copy the bytes back to target. // If we've done any conditional jumps in the preamble we need to convert // them back to the original REL8 jumps in the target. MiniDisassembler disassembler; unsigned int preamble_bytes = 0; unsigned int target_bytes = 0; while (target_bytes < kRequiredTargetPatchBytes) { unsigned int cur_bytes = 0; InstructionType instruction_type = disassembler.Disassemble(preamble_stub + preamble_bytes, cur_bytes); if (IT_JUMP == instruction_type) { unsigned int jump_bytes = 0; SideStepError jump_ret = SIDESTEP_JUMP_INSTRUCTION; if (IsNearConditionalJump(preamble_stub + preamble_bytes, cur_bytes) || IsNearRelativeJump(preamble_stub + preamble_bytes, cur_bytes) || IsNearAbsoluteCall(preamble_stub + preamble_bytes, cur_bytes) || IsNearRelativeCall(preamble_stub + preamble_bytes, cur_bytes)) { jump_ret = PatchNearJumpOrCall(preamble_stub + preamble_bytes, cur_bytes, target + target_bytes, &jump_bytes, MAX_PREAMBLE_STUB_SIZE); } if (jump_ret == SIDESTEP_JUMP_INSTRUCTION) { SIDESTEP_ASSERT(false && "Found unsupported jump instruction in stub!!"); return SIDESTEP_UNSUPPORTED_INSTRUCTION; } target_bytes += jump_bytes; } else if (IT_GENERIC == instruction_type) { if (IsMovWithDisplacement(preamble_stub + preamble_bytes, cur_bytes)) { unsigned int mov_bytes = 0; if (PatchMovWithDisplacement(preamble_stub + preamble_bytes, cur_bytes, target + target_bytes, &mov_bytes, MAX_PREAMBLE_STUB_SIZE) != SIDESTEP_SUCCESS) { SIDESTEP_ASSERT(false && "Found unsupported generic instruction in stub!!"); return SIDESTEP_UNSUPPORTED_INSTRUCTION; } } else { memcpy(reinterpret_cast<void*>(target + target_bytes), reinterpret_cast<void*>(reinterpret_cast<unsigned char*>( original_function_stub) + preamble_bytes), cur_bytes); target_bytes += cur_bytes; } } else { SIDESTEP_ASSERT(false && "Found unsupported instruction in stub!!"); return SIDESTEP_UNSUPPORTED_INSTRUCTION; } preamble_bytes += cur_bytes; } FreePreambleBlock(reinterpret_cast<unsigned char*>(original_function_stub)); // Restore the protection of the first kRequiredTargetPatchBytes bytes of // target to what they were before we started goofing around. succeeded = ::VirtualProtect(reinterpret_cast<void*>(target), kRequiredTargetPatchBytes, old_target_function_protect, &old_target_function_protect); // Flush the instruction cache to make sure the processor doesn't execute the // old version of the instructions (before our patch). // // See comment on FlushInstructionCache elsewhere in this file. succeeded = ::FlushInstructionCache(::GetCurrentProcess(), target, MAX_PREAMBLE_STUB_SIZE); if (!succeeded) { SIDESTEP_ASSERT(false && "Failed to flush instruction cache."); return SIDESTEP_UNEXPECTED; } SIDESTEP_LOG("PreamblePatcher::Unpatch successfully unpatched."); return SIDESTEP_SUCCESS; } void PreamblePatcher::Initialize() { if (!initialized_) { SYSTEM_INFO si = { 0 }; ::GetSystemInfo(&si); granularity_ = si.dwAllocationGranularity; pagesize_ = si.dwPageSize; initialized_ = true; } } unsigned char* PreamblePatcher::AllocPreambleBlockNear(void* target) { PreamblePage* preamble_page = preamble_pages_; while (preamble_page != NULL) { if (preamble_page->free_ != NULL) { __int64 val = reinterpret_cast<__int64>(preamble_page) - reinterpret_cast<__int64>(target); if ((val > 0 && val + pagesize_ <= INT_MAX) || (val < 0 && val >= INT_MIN)) { break; } } preamble_page = preamble_page->next_; } // The free_ member of the page is used to store the next available block // of memory to use or NULL if there are no chunks available, in which case // we'll allocate a new page. if (preamble_page == NULL || preamble_page->free_ == NULL) { // Create a new preamble page and initialize the free list preamble_page = reinterpret_cast<PreamblePage*>(AllocPageNear(target)); SIDESTEP_ASSERT(preamble_page != NULL && "Could not allocate page!"); void** pp = &preamble_page->free_; unsigned char* ptr = reinterpret_cast<unsigned char*>(preamble_page) + MAX_PREAMBLE_STUB_SIZE; unsigned char* limit = reinterpret_cast<unsigned char*>(preamble_page) + pagesize_; while (ptr < limit) { *pp = ptr; pp = reinterpret_cast<void**>(ptr); ptr += MAX_PREAMBLE_STUB_SIZE; } *pp = NULL; // Insert the new page into the list preamble_page->magic_ = kPreamblePageMagic; preamble_page->next_ = preamble_pages_; preamble_pages_ = preamble_page; } unsigned char* ret = reinterpret_cast<unsigned char*>(preamble_page->free_); preamble_page->free_ = *(reinterpret_cast<void**>(preamble_page->free_)); return ret; } void PreamblePatcher::FreePreambleBlock(unsigned char* block) { SIDESTEP_ASSERT(block != NULL); SIDESTEP_ASSERT(granularity_ != 0); uintptr_t ptr = reinterpret_cast<uintptr_t>(block); ptr -= ptr & (granularity_ - 1); PreamblePage* preamble_page = reinterpret_cast<PreamblePage*>(ptr); SIDESTEP_ASSERT(preamble_page->magic_ == kPreamblePageMagic); *(reinterpret_cast<void**>(block)) = preamble_page->free_; preamble_page->free_ = block; } void* PreamblePatcher::AllocPageNear(void* target) { MEMORY_BASIC_INFORMATION mbi = { 0 }; if (!::VirtualQuery(target, &mbi, sizeof(mbi))) { SIDESTEP_ASSERT(false && "VirtualQuery failed on target address"); return 0; } if (initialized_ == false) { PreamblePatcher::Initialize(); SIDESTEP_ASSERT(initialized_); } void* pv = NULL; unsigned char* allocation_base = reinterpret_cast<unsigned char*>( mbi.AllocationBase); __int64 i = 1; bool high_target = reinterpret_cast<__int64>(target) > UINT_MAX; while (pv == NULL) { __int64 val = reinterpret_cast<__int64>(allocation_base) - (i * granularity_); if (high_target && reinterpret_cast<__int64>(target) - val > INT_MAX) { // We're further than 2GB from the target break; } else if (val <= 0) { // Less than 0 break; } pv = ::VirtualAlloc(reinterpret_cast<void*>(allocation_base - (i++ * granularity_)), pagesize_, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); } // We couldn't allocate low, try to allocate high if (pv == NULL) { i = 1; // Round up to the next multiple of page granularity allocation_base = reinterpret_cast<unsigned char*>( (reinterpret_cast<__int64>(target) & (~(granularity_ - 1))) + granularity_); while (pv == NULL) { __int64 val = reinterpret_cast<__int64>(allocation_base) + (i * granularity_) - reinterpret_cast<__int64>(target); if (val > INT_MAX || val < 0) { // We're too far or we overflowed break; } pv = ::VirtualAlloc(reinterpret_cast<void*>(allocation_base + (i++ * granularity_)), pagesize_, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); } } return pv; } bool PreamblePatcher::IsShortConditionalJump( unsigned char* target, unsigned int instruction_size) { return (*(target) & 0x70) == 0x70 && instruction_size == 2; } bool PreamblePatcher::IsShortJump( unsigned char* target, unsigned int instruction_size) { return target[0] == 0xeb && instruction_size == 2; } bool PreamblePatcher::IsNearConditionalJump( unsigned char* target, unsigned int instruction_size) { return *(target) == 0xf && (*(target + 1) & 0x80) == 0x80 && instruction_size == 6; } bool PreamblePatcher::IsNearRelativeJump( unsigned char* target, unsigned int instruction_size) { return *(target) == 0xe9 && instruction_size == 5; } bool PreamblePatcher::IsNearAbsoluteCall( unsigned char* target, unsigned int instruction_size) { return *(target) == 0xff && (*(target + 1) & 0x10) == 0x10 && instruction_size == 6; } bool PreamblePatcher::IsNearRelativeCall( unsigned char* target, unsigned int instruction_size) { return *(target) == 0xe8 && instruction_size == 5; } bool PreamblePatcher::IsMovWithDisplacement( unsigned char* target, unsigned int instruction_size) { // In this case, the ModRM byte's mod field will be 0 and r/m will be 101b (5) return instruction_size == 7 && *target == 0x48 && *(target + 1) == 0x8b && (*(target + 2) >> 6) == 0 && (*(target + 2) & 0x7) == 5; } SideStepError PreamblePatcher::PatchShortConditionalJump( unsigned char* source, unsigned int instruction_size, unsigned char* target, unsigned int* target_bytes, unsigned int target_size) { // note: rel8 offset is signed. Thus we need to ask for signed char // to negative offsets right unsigned char* original_jump_dest = (source + 2) + static_cast<signed char>(source[1]); unsigned char* stub_jump_from = target + 6; __int64 fixup_jump_offset = original_jump_dest - stub_jump_from; if (fixup_jump_offset > INT_MAX || fixup_jump_offset < INT_MIN) { SIDESTEP_ASSERT(false && "Unable to fix up short jump because target" " is too far away."); return SIDESTEP_JUMP_INSTRUCTION; } *target_bytes = 6; if (target_size > *target_bytes) { // Convert the short jump to a near jump. // // 0f 8x xx xx xx xx = Jcc rel32off unsigned short jmpcode = ((0x80 | (source[0] & 0xf)) << 8) | 0x0f; memcpy(reinterpret_cast<void*>(target), reinterpret_cast<void*>(&jmpcode), 2); memcpy(reinterpret_cast<void*>(target + 2), reinterpret_cast<void*>(&fixup_jump_offset), 4); } return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::PatchShortJump( unsigned char* source, unsigned int instruction_size, unsigned char* target, unsigned int* target_bytes, unsigned int target_size) { // note: rel8 offset is _signed_. Thus we need signed char here. unsigned char* original_jump_dest = (source + 2) + static_cast<signed char>(source[1]); unsigned char* stub_jump_from = target + 5; __int64 fixup_jump_offset = original_jump_dest - stub_jump_from; if (fixup_jump_offset > INT_MAX || fixup_jump_offset < INT_MIN) { SIDESTEP_ASSERT(false && "Unable to fix up short jump because target" " is too far away."); return SIDESTEP_JUMP_INSTRUCTION; } *target_bytes = 5; if (target_size > *target_bytes) { // Convert the short jump to a near jump. // // e9 xx xx xx xx = jmp rel32off target[0] = 0xe9; memcpy(reinterpret_cast<void*>(target + 1), reinterpret_cast<void*>(&fixup_jump_offset), 4); } return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::PatchNearJumpOrCall( unsigned char* source, unsigned int instruction_size, unsigned char* target, unsigned int* target_bytes, unsigned int target_size) { SIDESTEP_ASSERT(instruction_size == 5 || instruction_size == 6); unsigned int jmp_offset_in_instruction = instruction_size == 5 ? 1 : 2; unsigned char* original_jump_dest = reinterpret_cast<unsigned char *>( reinterpret_cast<__int64>(source + instruction_size) + *(reinterpret_cast<int*>(source + jmp_offset_in_instruction))); unsigned char* stub_jump_from = target + instruction_size; __int64 fixup_jump_offset = original_jump_dest - stub_jump_from; if (fixup_jump_offset > INT_MAX || fixup_jump_offset < INT_MIN) { SIDESTEP_ASSERT(false && "Unable to fix up near jump because target" " is too far away."); return SIDESTEP_JUMP_INSTRUCTION; } if ((fixup_jump_offset < SCHAR_MAX && fixup_jump_offset > SCHAR_MIN)) { *target_bytes = 2; if (target_size > *target_bytes) { // If the new offset is in range, use a short jump instead of a near jump. if (source[0] == ASM_JCC32REL_0 && (source[1] & ASM_JCC32REL_1_MASK) == ASM_JCC32REL_1_MASK) { unsigned short jmpcode = (static_cast<unsigned char>( fixup_jump_offset) << 8) | (0x70 | (source[1] & 0xf)); memcpy(reinterpret_cast<void*>(target), reinterpret_cast<void*>(&jmpcode), 2); } else { target[0] = ASM_JMP8REL; target[1] = static_cast<unsigned char>(fixup_jump_offset); } } } else { *target_bytes = instruction_size; if (target_size > *target_bytes) { memcpy(reinterpret_cast<void*>(target), reinterpret_cast<void*>(source), jmp_offset_in_instruction); memcpy(reinterpret_cast<void*>(target + jmp_offset_in_instruction), reinterpret_cast<void*>(&fixup_jump_offset), 4); } } return SIDESTEP_SUCCESS; } SideStepError PreamblePatcher::PatchMovWithDisplacement( unsigned char* source, unsigned int instruction_size, unsigned char* target, unsigned int* target_bytes, unsigned int target_size) { SIDESTEP_ASSERT(instruction_size == 7); const int mov_offset_in_instruction = 3; // 0x48 0x8b 0x0d <offset> unsigned char* original_mov_dest = reinterpret_cast<unsigned char*>( reinterpret_cast<__int64>(source + instruction_size) + *(reinterpret_cast<int*>(source + mov_offset_in_instruction))); unsigned char* stub_mov_from = target + instruction_size; __int64 fixup_mov_offset = original_mov_dest - stub_mov_from; if (fixup_mov_offset > INT_MAX || fixup_mov_offset < INT_MIN) { SIDESTEP_ASSERT(false && "Unable to fix up near MOV because target is too far away."); return SIDESTEP_UNEXPECTED; } *target_bytes = instruction_size; if (target_size > *target_bytes) { memcpy(reinterpret_cast<void*>(target), reinterpret_cast<void*>(source), mov_offset_in_instruction); memcpy(reinterpret_cast<void*>(target + mov_offset_in_instruction), reinterpret_cast<void*>(&fixup_mov_offset), 4); } return SIDESTEP_SUCCESS; } }; // namespace sidestep
scheib/chromium
third_party/tcmalloc/vendor/src/windows/preamble_patcher.cc
C++
bsd-3-clause
29,199
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.5 // Package oracle contains the implementation of the oracle tool whose // command-line is provided by golang.org/x/tools/cmd/oracle. // // http://golang.org/s/oracle-design // http://golang.org/s/oracle-user-manual // package oracle // import "golang.org/x/tools/oracle" // This file defines oracle.Query, the entry point for the oracle tool. // The actual executable is defined in cmd/oracle. // TODO(adonovan): new queries // - show all statements that may update the selected lvalue // (local, global, field, etc). // - show all places where an object of type T is created // (&T{}, var t T, new(T), new(struct{array [3]T}), etc. import ( "fmt" "go/ast" "go/build" "go/parser" "go/token" "io" "path/filepath" "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/loader" "golang.org/x/tools/go/pointer" "golang.org/x/tools/go/ssa" "golang.org/x/tools/go/types" "golang.org/x/tools/oracle/serial" ) type printfFunc func(pos interface{}, format string, args ...interface{}) // queryResult is the interface of each query-specific result type. type queryResult interface { toSerial(res *serial.Result, fset *token.FileSet) display(printf printfFunc) } // A QueryPos represents the position provided as input to a query: // a textual extent in the program's source code, the AST node it // corresponds to, and the package to which it belongs. // Instances are created by parseQueryPos. type queryPos struct { fset *token.FileSet start, end token.Pos // source extent of query path []ast.Node // AST path from query node to root of ast.File exact bool // 2nd result of PathEnclosingInterval info *loader.PackageInfo // type info for the queried package (nil for fastQueryPos) } // TypeString prints type T relative to the query position. func (qpos *queryPos) typeString(T types.Type) string { return types.TypeString(T, types.RelativeTo(qpos.info.Pkg)) } // ObjectString prints object obj relative to the query position. func (qpos *queryPos) objectString(obj types.Object) string { return types.ObjectString(obj, types.RelativeTo(qpos.info.Pkg)) } // SelectionString prints selection sel relative to the query position. func (qpos *queryPos) selectionString(sel *types.Selection) string { return types.SelectionString(sel, types.RelativeTo(qpos.info.Pkg)) } // A Query specifies a single oracle query. type Query struct { Mode string // query mode ("callers", etc) Pos string // query position Build *build.Context // package loading configuration // pointer analysis options Scope []string // main packages in (*loader.Config).FromArgs syntax PTALog io.Writer // (optional) pointer-analysis log file Reflection bool // model reflection soundly (currently slow). // Populated during Run() Fset *token.FileSet result queryResult } // Serial returns an instance of serial.Result, which implements the // {xml,json}.Marshaler interfaces so that query results can be // serialized as JSON or XML. // func (q *Query) Serial() *serial.Result { resj := &serial.Result{Mode: q.Mode} q.result.toSerial(resj, q.Fset) return resj } // WriteTo writes the oracle query result res to out in a compiler diagnostic format. func (q *Query) WriteTo(out io.Writer) { printf := func(pos interface{}, format string, args ...interface{}) { fprintf(out, q.Fset, pos, format, args...) } q.result.display(printf) } // Run runs an oracle query and populates its Fset and Result. func Run(q *Query) error { switch q.Mode { case "callees": return callees(q) case "callers": return callers(q) case "callstack": return callstack(q) case "peers": return peers(q) case "pointsto": return pointsto(q) case "whicherrs": return whicherrs(q) case "definition": return definition(q) case "describe": return describe(q) case "freevars": return freevars(q) case "implements": return implements(q) case "referrers": return referrers(q) case "what": return what(q) default: return fmt.Errorf("invalid mode: %q", q.Mode) } } func setPTAScope(lconf *loader.Config, scope []string) error { if len(scope) == 0 { return fmt.Errorf("no packages specified for pointer analysis scope") } // Determine initial packages for PTA. args, err := lconf.FromArgs(scope, true) if err != nil { return err } if len(args) > 0 { return fmt.Errorf("surplus arguments: %q", args) } return nil } // Create a pointer.Config whose scope is the initial packages of lprog // and their dependencies. func setupPTA(prog *ssa.Program, lprog *loader.Program, ptaLog io.Writer, reflection bool) (*pointer.Config, error) { // TODO(adonovan): the body of this function is essentially // duplicated in all go/pointer clients. Refactor. // For each initial package (specified on the command line), // if it has a main function, analyze that, // otherwise analyze its tests, if any. var testPkgs, mains []*ssa.Package for _, info := range lprog.InitialPackages() { initialPkg := prog.Package(info.Pkg) // Add package to the pointer analysis scope. if initialPkg.Func("main") != nil { mains = append(mains, initialPkg) } else { testPkgs = append(testPkgs, initialPkg) } } if testPkgs != nil { if p := prog.CreateTestMainPackage(testPkgs...); p != nil { mains = append(mains, p) } } if mains == nil { return nil, fmt.Errorf("analysis scope has no main and no tests") } return &pointer.Config{ Log: ptaLog, Reflection: reflection, Mains: mains, }, nil } // importQueryPackage finds the package P containing the // query position and tells conf to import it. // It returns the package's path. func importQueryPackage(pos string, conf *loader.Config) (string, error) { fqpos, err := fastQueryPos(pos) if err != nil { return "", err // bad query } filename := fqpos.fset.File(fqpos.start).Name() // This will not work for ad-hoc packages // such as $GOROOT/src/net/http/triv.go. // TODO(adonovan): ensure we report a clear error. _, importPath, err := guessImportPath(filename, conf.Build) if err != nil { return "", err // can't find GOPATH dir } if importPath == "" { return "", fmt.Errorf("can't guess import path from %s", filename) } // Check that it's possible to load the queried package. // (e.g. oracle tests contain different 'package' decls in same dir.) // Keep consistent with logic in loader/util.go! cfg2 := *conf.Build cfg2.CgoEnabled = false bp, err := cfg2.Import(importPath, "", 0) if err != nil { return "", err // no files for package } switch pkgContainsFile(bp, filename) { case 'T': conf.ImportWithTests(importPath) case 'X': conf.ImportWithTests(importPath) importPath += "_test" // for TypeCheckFuncBodies case 'G': conf.Import(importPath) default: return "", fmt.Errorf("package %q doesn't contain file %s", importPath, filename) } conf.TypeCheckFuncBodies = func(p string) bool { return p == importPath } return importPath, nil } // pkgContainsFile reports whether file was among the packages Go // files, Test files, eXternal test files, or not found. func pkgContainsFile(bp *build.Package, filename string) byte { for i, files := range [][]string{bp.GoFiles, bp.TestGoFiles, bp.XTestGoFiles} { for _, file := range files { if sameFile(filepath.Join(bp.Dir, file), filename) { return "GTX"[i] } } } return 0 // not found } // ParseQueryPos parses the source query position pos and returns the // AST node of the loaded program lprog that it identifies. // If needExact, it must identify a single AST subtree; // this is appropriate for queries that allow fairly arbitrary syntax, // e.g. "describe". // func parseQueryPos(lprog *loader.Program, posFlag string, needExact bool) (*queryPos, error) { filename, startOffset, endOffset, err := parsePosFlag(posFlag) if err != nil { return nil, err } start, end, err := findQueryPos(lprog.Fset, filename, startOffset, endOffset) if err != nil { return nil, err } info, path, exact := lprog.PathEnclosingInterval(start, end) if path == nil { return nil, fmt.Errorf("no syntax here") } if needExact && !exact { return nil, fmt.Errorf("ambiguous selection within %s", astutil.NodeDescription(path[0])) } return &queryPos{lprog.Fset, start, end, path, exact, info}, nil } // ---------- Utilities ---------- // allowErrors causes type errors to be silently ignored. // (Not suitable if SSA construction follows.) func allowErrors(lconf *loader.Config) { ctxt := *lconf.Build // copy ctxt.CgoEnabled = false lconf.Build = &ctxt lconf.AllowErrors = true // AllErrors makes the parser always return an AST instead of // bailing out after 10 errors and returning an empty ast.File. lconf.ParserMode = parser.AllErrors lconf.TypeChecker.Error = func(err error) {} } // ptrAnalysis runs the pointer analysis and returns its result. func ptrAnalysis(conf *pointer.Config) *pointer.Result { result, err := pointer.Analyze(conf) if err != nil { panic(err) // pointer analysis internal error } return result } func unparen(e ast.Expr) ast.Expr { return astutil.Unparen(e) } // deref returns a pointer's element type; otherwise it returns typ. func deref(typ types.Type) types.Type { if p, ok := typ.Underlying().(*types.Pointer); ok { return p.Elem() } return typ } // fprintf prints to w a message of the form "location: message\n" // where location is derived from pos. // // pos must be one of: // - a token.Pos, denoting a position // - an ast.Node, denoting an interval // - anything with a Pos() method: // ssa.Member, ssa.Value, ssa.Instruction, types.Object, pointer.Label, etc. // - a QueryPos, denoting the extent of the user's query. // - nil, meaning no position at all. // // The output format is is compatible with the 'gnu' // compilation-error-regexp in Emacs' compilation mode. // TODO(adonovan): support other editors. // func fprintf(w io.Writer, fset *token.FileSet, pos interface{}, format string, args ...interface{}) { var start, end token.Pos switch pos := pos.(type) { case ast.Node: start = pos.Pos() end = pos.End() case token.Pos: start = pos end = start case interface { Pos() token.Pos }: start = pos.Pos() end = start case *queryPos: start = pos.start end = pos.end case nil: // no-op default: panic(fmt.Sprintf("invalid pos: %T", pos)) } if sp := fset.Position(start); start == end { // (prints "-: " for token.NoPos) fmt.Fprintf(w, "%s: ", sp) } else { ep := fset.Position(end) // The -1 below is a concession to Emacs's broken use of // inclusive (not half-open) intervals. // Other editors may not want it. // TODO(adonovan): add an -editor=vim|emacs|acme|auto // flag; auto uses EMACS=t / VIM=... / etc env vars. fmt.Fprintf(w, "%s:%d.%d-%d.%d: ", sp.Filename, sp.Line, sp.Column, ep.Line, ep.Column-1) } fmt.Fprintf(w, format, args...) io.WriteString(w, "\n") }
muzining/net
x/tools/oracle/oracle14.go
GO
bsd-3-clause
11,129
module ShowRepoEvents where import qualified Github.Issues.Events as Github import Data.List (intercalate) import Data.Maybe (fromJust) main = do possibleEvents <- Github.eventsForRepo "thoughtbot" "paperclip" case possibleEvents of (Left error) -> putStrLn $ "Error: " ++ show error (Right events) -> do putStrLn $ intercalate "\n" $ map formatEvent events formatEvent event = "Issue #" ++ issueNumber event ++ ": " ++ formatEvent' event (Github.eventType event) where formatEvent' event Github.Closed = "closed on " ++ createdAt event ++ " by " ++ loginName event ++ withCommitId event (\commitId -> " in the commit " ++ commitId) formatEvent' event Github.Reopened = "reopened on " ++ createdAt event ++ " by " ++ loginName event formatEvent' event Github.Subscribed = loginName event ++ " is subscribed to receive notifications" formatEvent' event Github.Unsubscribed = loginName event ++ " is unsubscribed from notifications" formatEvent' event Github.Merged = "merged by " ++ loginName event ++ " on " ++ createdAt event ++ (withCommitId event $ \commitId -> " in the commit " ++ commitId) formatEvent' event Github.Referenced = withCommitId event $ \commitId -> "referenced from " ++ commitId ++ " by " ++ loginName event formatEvent' event Github.Mentioned = loginName event ++ " was mentioned in the issue's body" formatEvent' event Github.Assigned = "assigned to " ++ loginName event ++ " on " ++ createdAt event loginName = Github.githubOwnerLogin . Github.eventActor createdAt = show . Github.fromGithubDate . Github.eventCreatedAt withCommitId event f = maybe "" f (Github.eventCommitId event) issueNumber = show . Github.issueNumber . fromJust . Github.eventIssue
bitemyapp/github
samples/Issues/Events/ShowRepoEvents.hs
Haskell
bsd-3-clause
1,783
/* Copyright (c) 2012 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ .model-track { -webkit-box-flex: 1; }
bpsinc-native/src_third_party_trace-viewer
trace_viewer/tracing/tracks/trace_model_track.css
CSS
bsd-3-clause
213
/* -*- buffer-read-only: t -*- * !!!!!!! DO NOT EDIT THIS FILE !!!!!!! * This file is built by regen/mk_PL_charclass.pl from property definitions * and lib/unicore/CaseFolding.txt. * Any changes made here will be lost! */ /* U+00 NUL */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+01 SOH */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+02 STX */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+03 ETX */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+04 EOT */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+05 ENQ */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+06 ACK */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+07 BEL */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+08 BS */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+09 HT */ _CC_BLANK_A|_CC_BLANK_L1|_CC_CNTRL_A|_CC_CNTRL_L1|_CC_PSXSPC_A|_CC_PSXSPC_L1|_CC_SPACE_A|_CC_SPACE_L1|_CC_QUOTEMETA, /* U+0A LF */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_PSXSPC_A|_CC_PSXSPC_L1|_CC_SPACE_A|_CC_SPACE_L1|_CC_QUOTEMETA, /* U+0B VT */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_PSXSPC_A|_CC_PSXSPC_L1|_CC_QUOTEMETA, /* U+0C FF */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_PSXSPC_A|_CC_PSXSPC_L1|_CC_SPACE_A|_CC_SPACE_L1|_CC_QUOTEMETA, /* U+0D CR */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_PSXSPC_A|_CC_PSXSPC_L1|_CC_SPACE_A|_CC_SPACE_L1|_CC_QUOTEMETA, /* U+0E SO */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+0F SI */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+10 DLE */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+11 DC1 */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+12 DC2 */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+13 DC3 */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+14 DC4 */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+15 NAK */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+16 SYN */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+17 ETB */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+18 CAN */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+19 EOM */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+1A SUB */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+1B ESC */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+1C FS */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+1D GS */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+1E RS */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+1F US */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+20 SPACE */ _CC_BLANK_A|_CC_BLANK_L1|_CC_CHARNAME_CONT|_CC_PRINT_A|_CC_PRINT_L1|_CC_PSXSPC_A|_CC_PSXSPC_L1|_CC_SPACE_A|_CC_SPACE_L1|_CC_QUOTEMETA, /* U+21 '!' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+22 '"' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+23 '#' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+24 '$' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+25 '%' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+26 '&' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+27 ''' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+28 '(' */ _CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+29 ')' */ _CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+2A '*' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+2B '+' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+2C ',' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+2D '-' */ _CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+2E '.' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+2F '/' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+30 '0' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_CHARNAME_CONT|_CC_DIGIT_A|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_OCTAL_A|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+31 '1' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_CHARNAME_CONT|_CC_DIGIT_A|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_OCTAL_A|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+32 '2' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_CHARNAME_CONT|_CC_DIGIT_A|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_OCTAL_A|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+33 '3' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_CHARNAME_CONT|_CC_DIGIT_A|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_OCTAL_A|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+34 '4' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_CHARNAME_CONT|_CC_DIGIT_A|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_OCTAL_A|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+35 '5' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_CHARNAME_CONT|_CC_DIGIT_A|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_OCTAL_A|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+36 '6' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_CHARNAME_CONT|_CC_DIGIT_A|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_OCTAL_A|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+37 '7' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_CHARNAME_CONT|_CC_DIGIT_A|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_OCTAL_A|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+38 '8' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_CHARNAME_CONT|_CC_DIGIT_A|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+39 '9' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_CHARNAME_CONT|_CC_DIGIT_A|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+3A ':' */ _CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+3B ';' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+3C '<' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+3D '=' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+3E '>' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+3F '?' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+40 '@' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+41 'A' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+42 'B' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+43 'C' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+44 'D' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+45 'E' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+46 'F' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+47 'G' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+48 'H' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+49 'I' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+4A 'J' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+4B 'K' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+4C 'L' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+4D 'M' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+4E 'N' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+4F 'O' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+50 'P' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+51 'Q' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+52 'R' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+53 'S' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+54 'T' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+55 'U' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+56 'V' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+57 'W' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+58 'X' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+59 'Y' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+5A 'Z' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_UPPER_A|_CC_UPPER_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+5B '[' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+5C '\' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+5D ']' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+5E '^' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+5F '_' */ _CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+60 '`' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+61 'a' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+62 'b' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+63 'c' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+64 'd' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+65 'e' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+66 'f' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1|_CC_XDIGIT_A, /* U+67 'g' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+68 'h' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+69 'i' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+6A 'j' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+6B 'k' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+6C 'l' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+6D 'm' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+6E 'n' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+6F 'o' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+70 'p' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+71 'q' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+72 'r' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+73 's' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+74 't' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+75 'u' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+76 'v' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+77 'w' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+78 'x' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+79 'y' */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+7A 'z' */ _CC_ALNUMC_A|_CC_ALNUMC_L1|_CC_ALPHA_A|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_A|_CC_GRAPH_L1|_CC_IDFIRST_A|_CC_IDFIRST_L1|_CC_LOWER_A|_CC_LOWER_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_WORDCHAR_A|_CC_WORDCHAR_L1, /* U+7B '{' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+7C '|' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+7D '}' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+7E '~' */ _CC_GRAPH_A|_CC_GRAPH_L1|_CC_PRINT_A|_CC_PRINT_L1|_CC_PUNCT_A|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+7F DEL */ _CC_CNTRL_A|_CC_CNTRL_L1|_CC_QUOTEMETA, /* U+80 PAD */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+81 HOP */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+82 BPH */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+83 NBH */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+84 IND */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+85 NEL */ _CC_CNTRL_L1|_CC_PSXSPC_L1|_CC_SPACE_L1|_CC_QUOTEMETA, /* U+86 SSA */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+87 ESA */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+88 HTS */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+89 HTJ */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+8A VTS */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+8B PLD */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+8C PLU */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+8D RI */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+8E SS2 */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+8F SS3 */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+90 DCS */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+91 PU1 */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+92 PU2 */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+93 STS */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+94 CCH */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+95 MW */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+96 SPA */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+97 EPA */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+98 SOS */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+99 SGC */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+9A SCI */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+9B CSI */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+9C ST */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+9D OSC */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+9E PM */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+9F APC */ _CC_CNTRL_L1|_CC_QUOTEMETA, /* U+A0 NO-BREAK SPACE */ _CC_BLANK_L1|_CC_CHARNAME_CONT|_CC_PRINT_L1|_CC_PSXSPC_L1|_CC_SPACE_L1|_CC_QUOTEMETA, /* U+A1 INVERTED EXCLAMATION MARK */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+A2 CENT SIGN */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_QUOTEMETA, /* U+A3 POUND SIGN */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_QUOTEMETA, /* U+A4 CURRENCY SIGN */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_QUOTEMETA, /* U+A5 YEN SIGN */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_QUOTEMETA, /* U+A6 BROKEN BAR */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_QUOTEMETA, /* U+A7 SECTION SIGN */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+A8 DIAERESIS */ _CC_GRAPH_L1|_CC_PRINT_L1, /* U+A9 COPYRIGHT SIGN */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_QUOTEMETA, /* U+AA FEMININE ORDINAL INDICATOR */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+AB LEFT-POINTING DOUBLE ANGLE QUOTATION MARK */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+AC NOT SIGN */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_QUOTEMETA, /* U+AD SOFT HYPHEN */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_QUOTEMETA, /* U+AE REGISTERED SIGN */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_QUOTEMETA, /* U+AF MACRON */ _CC_GRAPH_L1|_CC_PRINT_L1, /* U+B0 DEGREE SIGN */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_QUOTEMETA, /* U+B1 PLUS-MINUS SIGN */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_QUOTEMETA, /* U+B2 SUPERSCRIPT TWO */ _CC_GRAPH_L1|_CC_PRINT_L1, /* U+B3 SUPERSCRIPT THREE */ _CC_GRAPH_L1|_CC_PRINT_L1, /* U+B4 ACUTE ACCENT */ _CC_GRAPH_L1|_CC_PRINT_L1, /* U+B5 MICRO SIGN */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+B6 PILCROW SIGN */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+B7 MIDDLE DOT */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_PUNCT_L1, /* U+B8 CEDILLA */ _CC_GRAPH_L1|_CC_PRINT_L1, /* U+B9 SUPERSCRIPT ONE */ _CC_GRAPH_L1|_CC_PRINT_L1, /* U+BA MASCULINE ORDINAL INDICATOR */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+BB RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+BC VULGAR FRACTION ONE QUARTER */ _CC_GRAPH_L1|_CC_PRINT_L1, /* U+BD VULGAR FRACTION ONE HALF */ _CC_GRAPH_L1|_CC_PRINT_L1, /* U+BE VULGAR FRACTION THREE QUARTERS */ _CC_GRAPH_L1|_CC_PRINT_L1, /* U+BF INVERTED QUESTION MARK */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_PUNCT_L1|_CC_QUOTEMETA, /* U+C0 A WITH GRAVE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+C1 A WITH ACUTE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+C2 A WITH CIRCUMFLEX */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+C3 A WITH TILDE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+C4 A WITH DIAERESIS */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+C5 A WITH RING ABOVE */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+C6 AE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+C7 C WITH CEDILLA */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+C8 E WITH GRAVE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+C9 E WITH ACUTE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+CA E WITH CIRCUMFLEX */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+CB E WITH DIAERESIS */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+CC I WITH GRAVE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+CD I WITH ACUTE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+CE I WITH CIRCUMFLEX */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+CF I WITH DIAERESIS */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+D0 ETH */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+D1 N WITH TILDE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+D2 O WITH GRAVE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+D3 O WITH ACUTE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+D4 O WITH CIRCUMFLEX */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+D5 O WITH TILDE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+D6 O WITH DIAERESIS */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+D7 MULTIPLICATION SIGN */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_QUOTEMETA, /* U+D8 O WITH STROKE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+D9 U WITH GRAVE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+DA U WITH ACUTE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+DB U WITH CIRCUMFLEX */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+DC U WITH DIAERESIS */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+DD Y WITH ACUTE */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+DE THORN */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_PRINT_L1|_CC_UPPER_L1|_CC_WORDCHAR_L1, /* U+DF sharp s */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+E0 a with grave */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+E1 a with acute */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+E2 a with circumflex */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+E3 a with tilde */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+E4 a with diaeresis */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+E5 a with ring above */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+E6 ae */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+E7 c with cedilla */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+E8 e with grave */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+E9 e with acute */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+EA e with circumflex */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+EB e with diaeresis */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+EC i with grave */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+ED i with acute */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+EE i with circumflex */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+EF i with diaeresis */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+F0 eth */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+F1 n with tilde */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+F2 o with grave */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+F3 o with acute */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+F4 o with circumflex */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+F5 o with tilde */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+F6 o with diaeresis */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+F7 DIVISION SIGN */ _CC_GRAPH_L1|_CC_PRINT_L1|_CC_QUOTEMETA, /* U+F8 o with stroke */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+F9 u with grave */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+FA u with acute */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+FB u with circumflex */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+FC u with diaeresis */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+FD y with acute */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+FE thorn */ _CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* U+FF y with diaeresis */ _CC_NONLATIN1_FOLD|_CC_ALNUMC_L1|_CC_ALPHA_L1|_CC_CHARNAME_CONT|_CC_GRAPH_L1|_CC_IDFIRST_L1|_CC_LOWER_L1|_CC_PRINT_L1|_CC_WORDCHAR_L1, /* ex: set ro: */
Dokaponteam/ITF_Project
xampp/perl/lib/CORE/l1_char_class_tab.h
C
mit
32,627
var fs = require('fs') , child_process = require('child_process') , _glob = require('glob') , bunch = require('./bunch') ; exports.loadEnv = function loadEnv(env, cb) { var loaders = [] function load(name, cb) { fs.readFile(env[name], function(error, data) { env[name] = env[name].match(/.*\.json$/) ? JSON.parse(data) : data; cb(error, data) }) } for (var name in env) { loaders.push([load, name]) } bunch(loaders, cb) } exports.commandActor = function command(executable) { return function command(args, opts, cb) { if (!cb) { cb = opts; opts = {} } var cmd = child_process.spawn(executable, args, opts); function log(b) { console.log(b.toString()) } cmd.stdout.on('data', log); cmd.stderr.on('data', log); cmd.on('exit', function(code) { if (code) { cb(new Error(executable + ' exited with status ' + code)); } else { cb(); } }); return cmd; } } exports.jsonParse = function(str, cb) { try { cb(null, JSON.parse(str)); } catch (ex) { cb(ex); } } exports.jsonStringify = function(obj, cb) { try { cb(null, JSON.stringify(obj)); } catch (ex) { cb(ex); } } exports.glob = function glob(pattern, cb) { console.log('pattern', pattern); _glob(pattern, function(error, files) { cb(error, [files]); }); }
KhaosT/node_mdns
utils/lib/actors.js
JavaScript
mit
1,375
Function.prototype.bind = Function.prototype.bind || function (target) { var self = this; return function (args) { if (!(args instanceof Array)) { args = [args]; } self.apply(target, args); }; };
ThatSonnyD/brad-pitt-2048
tile-sets/brad pitt/js/bind_polyfill.js
JavaScript
mit
229
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if NET45 using System; using System.Runtime.InteropServices; namespace Microsoft.DotNet.PlatformAbstractions.Native { internal static partial class NativeMethods { public static class Unix { public unsafe static string GetUname() { // Utsname shouldn't be larger than 2K var buf = stackalloc byte[2048]; try { if (uname((IntPtr)buf) == 0) { return Marshal.PtrToStringAnsi((IntPtr)buf); } } catch (Exception ex) { throw new PlatformNotSupportedException("Error reading Unix name", ex); } throw new PlatformNotSupportedException("Unknown error reading Unix name"); } [DllImport("libc")] private static extern int uname(IntPtr utsname); } } } #endif
gkhanna79/core-setup
src/managed/Microsoft.DotNet.PlatformAbstractions/Native/NativeMethods.Unix.cs
C#
mit
1,173
from __future__ import print_function import soco """ Prints the name of each discovered player in the network. """ for zone in soco.discover(): print(zone.player_name)
dundeemt/SoCo
examples/commandline/discover.py
Python
mit
175
// DATA_TEMPLATE: js_data oTest.fnStart( "oLanguage.oPaginate" ); /* Note that the paging language information only has relevence in full numbers */ $(document).ready( function () { /* Check the default */ var oTable = $('#example').dataTable( { "aaData": gaaData, "sPaginationType": "full_numbers" } ); var oSettings = oTable.fnSettings(); oTest.fnTest( "oLanguage.oPaginate defaults", null, function () { var bReturn = oSettings.oLanguage.oPaginate.sFirst == "First" && oSettings.oLanguage.oPaginate.sPrevious == "Previous" && oSettings.oLanguage.oPaginate.sNext == "Next" && oSettings.oLanguage.oPaginate.sLast == "Last"; return bReturn; } ); oTest.fnTest( "oLanguage.oPaginate defaults are in the DOM", null, function () { var bReturn = $('#example_paginate .first').html() == "First" && $('#example_paginate .previous').html() == "Previous" && $('#example_paginate .next').html() == "Next" && $('#example_paginate .last').html() == "Last"; return bReturn; } ); oTest.fnTest( "oLanguage.oPaginate can be defined", function () { oSession.fnRestore(); oTable = $('#example').dataTable( { "aaData": gaaData, "sPaginationType": "full_numbers", "oLanguage": { "oPaginate": { "sFirst": "unit1", "sPrevious": "test2", "sNext": "unit3", "sLast": "test4" } } } ); oSettings = oTable.fnSettings(); }, function () { var bReturn = oSettings.oLanguage.oPaginate.sFirst == "unit1" && oSettings.oLanguage.oPaginate.sPrevious == "test2" && oSettings.oLanguage.oPaginate.sNext == "unit3" && oSettings.oLanguage.oPaginate.sLast == "test4"; return bReturn; } ); oTest.fnTest( "oLanguage.oPaginate definitions are in the DOM", null, function () { var bReturn = $('#example_paginate .first').html() == "unit1" && $('#example_paginate .previous').html() == "test2" && $('#example_paginate .next').html() == "unit3" && $('#example_paginate .last').html() == "test4"; return bReturn; } ); oTest.fnComplete(); } );
desarrollotissat/web-interface
web/js/DataTables-1.9.4/media/unit_testing/tests_onhold/2_js/oLanguage.oPaginate.js
JavaScript
mit
2,212
{% include vars.html %} <nav class="navbar navbar-full navbar-fixed-top navbar-dark"> <div class="container"> <a class="navbar-brand" href="{{url_base}}/"> {% include svg/logo-flow-nav.svg %} <span class="sr-only">Flow</span> </a> <div class="clearfix hidden-lg-up"> <button class="navbar-toggler float-xs-right" type="button" data-toggle="collapse" data-target="#navbar" aria-controls="exCollapsingNavbar2" aria-expanded="false" aria-label="Toggle navigation"> <!-- &#9776; --> </button> </div> <div class="collapse navbar-toggleable-md" id="navbar"> <ul class="nav navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{{url_base}}/docs/getting-started/">{{i18n.navbar_getting_started}}</a> </li> <li class="nav-item"> <a class="nav-link" href="{{url_base}}/docs/">{{i18n.navbar_documentation}}</a> </li> <li class="nav-item"> <a class="nav-link" href="{{base_url}}/try/">{{i18n.navbar_try}}</a> </li> <li class="nav-item"> <a class="nav-link" href="{{base_url}}/blog/">{{i18n.navbar_blog}}</a> </li> </ul> <ul class="nav navbar-nav float-lg-right"> {% assign path = page.url | split: '/' %} {% unless true || path[1] == 'blog' %} <li class="nav-item dropdown"> <a id="dropdownNavLanguage" class="nav-link dropdown-toggle" role="button" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {% include svg/icon-language.svg class="navbar-icon" %} <span class="navbar-language-label">{{lang.name}}</span> </a> <div class="dropdown-menu" aria-labelledby="dropdownNavLanguage"> {% for language in site.data.languages %} {% if language.enabled %} <a href="{{site.baseurl}}/{{language.tag}}/{{url_relative}}" class="dropdown-item{% if lang.tag == language.tag %} active{% endif %}" data-lang="{{language.accept_languages[0]}}"> {{language.name}} </a> {% endif %} {% endfor %} </div> </li> {% endunless %} <li class="nav-item"> <a class="nav-link" href="https://twitter.com/flowtype"> {% include svg/icon-twitter.svg class="navbar-icon" %} <span class="sr-only">{{i18n.navbar_twitter}}</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="http://stackoverflow.com/questions/tagged/flowtype"> {% include svg/icon-stackoverflow.svg class="navbar-icon" %} <span class="sr-only">{{i18n.navbar_stackoverflow}}</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="https://github.com/facebook/flow"> {% include svg/icon-github.svg class="navbar-icon" %} <span class="sr-only">{{i18n.navbar_github}}</span> </a> </li> </ul> </div> </div> </nav>
JonathanUsername/flow
website/_includes/navbar.html
HTML
mit
3,153
namespace Simple.Data.UnitTest { using System; using System.Collections.Generic; using NUnit.Framework; [TestFixture] public class AdapterFactoryTest { private static AdapterFactory CreateTarget() { return new CachingAdapterFactory(new StubComposer()); } [Test] [ExpectedException(typeof(ArgumentException))] public void CreateWithAnonymousObjectWithoutConnectionStringThrowsArgumentException() { CreateTarget().Create(new { X = "" }); } [Test] public void CreateWithName() { var actual = CreateTarget().Create("Stub", null); Assert.IsNotNull(actual); } } class StubComposer : Composer { public override T Compose<T>() { return (T) Create(); } public override T Compose<T>(string contractName) { return (T)Create(); } private object Create() { return new StubAdapter(); } } class StubAdapter : Adapter { public override IDictionary<string, object> GetKey(string tableName, IDictionary<string, object> record) { throw new NotImplementedException(); } public override IList<string> GetKeyNames(string tableName) { throw new NotImplementedException(); } public override IDictionary<string, object> Get(string tableName, params object[] keyValues) { throw new NotImplementedException(); } public override IEnumerable<IDictionary<string, object>> Find(string tableName, SimpleExpression criteria) { throw new NotImplementedException(); } public override IEnumerable<IDictionary<string, object>> RunQuery(SimpleQuery query, out IEnumerable<SimpleQueryClauseBase> unhandledClauses) { throw new NotImplementedException(); } public override IDictionary<string, object> Insert(string tableName, IDictionary<string, object> data, bool resultRequired) { throw new NotImplementedException(); } public override int Update(string tableName, IDictionary<string, object> data, SimpleExpression criteria) { throw new NotImplementedException(); } public override int Delete(string tableName, SimpleExpression criteria) { throw new NotImplementedException(); } public override IEnumerable<IEnumerable<IDictionary<string, object>>> RunQueries(SimpleQuery[] queries, List<IEnumerable<SimpleQueryClauseBase>> unhandledClauses) { throw new NotImplementedException(); } public override bool IsExpressionFunction(string functionName, params object[] args) { throw new NotImplementedException(); } } }
ronnyek/Simple.Data
Simple.Data.UnitTest/AdapterFactoryTest.cs
C#
mit
3,058
<div>Does not close properly<div>Nested same level as next div</div></div><div>Will be nested, but should be top level</div>
creationix/haml-js
test/div_nesting.html
HTML
mit
124
module.exports={title:"Google Hangouts",hex:"0C9D58",source:"https://material.google.com/resources/sticker-sheets-icons.html#sticker-sheets-icons-components",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Google Hangouts icon</title><path d="M12 0C6.2 0 1.5 4.7 1.5 10.5c0 5.5 5 10 10.5 10V24c6.35-3.1 10.5-8.2 10.5-13.5C22.5 4.7 17.8 0 12 0zm-.5 12c0 1.4-.9 2.5-2 2.5V12H7V7.5h4.5V12zm6 0c0 1.4-.9 2.5-2 2.5V12H13V7.5h4.5V12z"/></svg>'};
cdnjs/cdnjs
ajax/libs/simple-icons/1.9.28/googlehangouts.min.js
JavaScript
mit
474
/* * pci_irq.c - ACPI PCI Interrupt Routing ($Revision: 11 $) * * Copyright (C) 2001, 2002 Andy Grover <andrew.grover@intel.com> * Copyright (C) 2001, 2002 Paul Diefenbaugh <paul.s.diefenbaugh@intel.com> * Copyright (C) 2002 Dominik Brodowski <devel@brodo.de> * (c) Copyright 2008 Hewlett-Packard Development Company, L.P. * Bjorn Helgaas <bjorn.helgaas@hp.com> * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * 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. * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include <linux/dmi.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/types.h> #include <linux/spinlock.h> #include <linux/pm.h> #include <linux/pci.h> #include <linux/acpi.h> #include <linux/slab.h> #include <linux/interrupt.h> #define PREFIX "ACPI: " #define _COMPONENT ACPI_PCI_COMPONENT ACPI_MODULE_NAME("pci_irq"); struct acpi_prt_entry { struct acpi_pci_id id; u8 pin; acpi_handle link; u32 index; /* GSI, or link _CRS index */ }; static inline char pin_name(int pin) { return 'A' + pin - 1; } /* -------------------------------------------------------------------------- PCI IRQ Routing Table (PRT) Support -------------------------------------------------------------------------- */ /* http://bugzilla.kernel.org/show_bug.cgi?id=4773 */ static const struct dmi_system_id medion_md9580[] = { { .ident = "Medion MD9580-F laptop", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "MEDIONNB"), DMI_MATCH(DMI_PRODUCT_NAME, "A555"), }, }, { } }; /* http://bugzilla.kernel.org/show_bug.cgi?id=5044 */ static const struct dmi_system_id dell_optiplex[] = { { .ident = "Dell Optiplex GX1", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Dell Computer Corporation"), DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex GX1 600S+"), }, }, { } }; /* http://bugzilla.kernel.org/show_bug.cgi?id=10138 */ static const struct dmi_system_id hp_t5710[] = { { .ident = "HP t5710", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"), DMI_MATCH(DMI_PRODUCT_NAME, "hp t5000 series"), DMI_MATCH(DMI_BOARD_NAME, "098Ch"), }, }, { } }; struct prt_quirk { const struct dmi_system_id *system; unsigned int segment; unsigned int bus; unsigned int device; unsigned char pin; const char *source; /* according to BIOS */ const char *actual_source; }; #define PCI_INTX_PIN(c) (c - 'A' + 1) /* * These systems have incorrect _PRT entries. The BIOS claims the PCI * interrupt at the listed segment/bus/device/pin is connected to the first * link device, but it is actually connected to the second. */ static const struct prt_quirk prt_quirks[] = { { medion_md9580, 0, 0, 9, PCI_INTX_PIN('A'), "\\_SB_.PCI0.ISA_.LNKA", "\\_SB_.PCI0.ISA_.LNKB"}, { dell_optiplex, 0, 0, 0xd, PCI_INTX_PIN('A'), "\\_SB_.LNKB", "\\_SB_.LNKA"}, { hp_t5710, 0, 0, 1, PCI_INTX_PIN('A'), "\\_SB_.PCI0.LNK1", "\\_SB_.PCI0.LNK3"}, }; static void do_prt_fixups(struct acpi_prt_entry *entry, struct acpi_pci_routing_table *prt) { int i; const struct prt_quirk *quirk; for (i = 0; i < ARRAY_SIZE(prt_quirks); i++) { quirk = &prt_quirks[i]; /* All current quirks involve link devices, not GSIs */ if (dmi_check_system(quirk->system) && entry->id.segment == quirk->segment && entry->id.bus == quirk->bus && entry->id.device == quirk->device && entry->pin == quirk->pin && !strcmp(prt->source, quirk->source) && strlen(prt->source) >= strlen(quirk->actual_source)) { printk(KERN_WARNING PREFIX "firmware reports " "%04x:%02x:%02x PCI INT %c connected to %s; " "changing to %s\n", entry->id.segment, entry->id.bus, entry->id.device, pin_name(entry->pin), prt->source, quirk->actual_source); strcpy(prt->source, quirk->actual_source); } } } static int acpi_pci_irq_check_entry(acpi_handle handle, struct pci_dev *dev, int pin, struct acpi_pci_routing_table *prt, struct acpi_prt_entry **entry_ptr) { int segment = pci_domain_nr(dev->bus); int bus = dev->bus->number; int device = pci_ari_enabled(dev->bus) ? 0 : PCI_SLOT(dev->devfn); struct acpi_prt_entry *entry; if (((prt->address >> 16) & 0xffff) != device || prt->pin + 1 != pin) return -ENODEV; entry = kzalloc(sizeof(struct acpi_prt_entry), GFP_KERNEL); if (!entry) return -ENOMEM; /* * Note that the _PRT uses 0=INTA, 1=INTB, etc, while PCI uses * 1=INTA, 2=INTB. We use the PCI encoding throughout, so convert * it here. */ entry->id.segment = segment; entry->id.bus = bus; entry->id.device = (prt->address >> 16) & 0xFFFF; entry->pin = prt->pin + 1; do_prt_fixups(entry, prt); entry->index = prt->source_index; /* * Type 1: Dynamic * --------------- * The 'source' field specifies the PCI interrupt link device used to * configure the IRQ assigned to this slot|dev|pin. The 'source_index' * indicates which resource descriptor in the resource template (of * the link device) this interrupt is allocated from. * * NOTE: Don't query the Link Device for IRQ information at this time * because Link Device enumeration may not have occurred yet * (e.g. exists somewhere 'below' this _PRT entry in the ACPI * namespace). */ if (prt->source[0]) acpi_get_handle(handle, prt->source, &entry->link); /* * Type 2: Static * -------------- * The 'source' field is NULL, and the 'source_index' field specifies * the IRQ value, which is hardwired to specific interrupt inputs on * the interrupt controller. */ ACPI_DEBUG_PRINT_RAW((ACPI_DB_INFO, " %04x:%02x:%02x[%c] -> %s[%d]\n", entry->id.segment, entry->id.bus, entry->id.device, pin_name(entry->pin), prt->source, entry->index)); *entry_ptr = entry; return 0; } static int acpi_pci_irq_find_prt_entry(struct pci_dev *dev, int pin, struct acpi_prt_entry **entry_ptr) { acpi_status status; struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL }; struct acpi_pci_routing_table *entry; acpi_handle handle = NULL; if (dev->bus->bridge) handle = ACPI_HANDLE(dev->bus->bridge); if (!handle) return -ENODEV; /* 'handle' is the _PRT's parent (root bridge or PCI-PCI bridge) */ status = acpi_get_irq_routing_table(handle, &buffer); if (ACPI_FAILURE(status)) { kfree(buffer.pointer); return -ENODEV; } entry = buffer.pointer; while (entry && (entry->length > 0)) { if (!acpi_pci_irq_check_entry(handle, dev, pin, entry, entry_ptr)) break; entry = (struct acpi_pci_routing_table *) ((unsigned long)entry + entry->length); } kfree(buffer.pointer); return 0; } /* -------------------------------------------------------------------------- PCI Interrupt Routing Support -------------------------------------------------------------------------- */ #ifdef CONFIG_X86_IO_APIC extern int noioapicquirk; extern int noioapicreroute; static int bridge_has_boot_interrupt_variant(struct pci_bus *bus) { struct pci_bus *bus_it; for (bus_it = bus ; bus_it ; bus_it = bus_it->parent) { if (!bus_it->self) return 0; if (bus_it->self->irq_reroute_variant) return bus_it->self->irq_reroute_variant; } return 0; } /* * Some chipsets (e.g. Intel 6700PXH) generate a legacy INTx when the IRQ * entry in the chipset's IO-APIC is masked (as, e.g. the RT kernel does * during interrupt handling). When this INTx generation cannot be disabled, * we reroute these interrupts to their legacy equivalent to get rid of * spurious interrupts. */ static int acpi_reroute_boot_interrupt(struct pci_dev *dev, struct acpi_prt_entry *entry) { if (noioapicquirk || noioapicreroute) { return 0; } else { switch (bridge_has_boot_interrupt_variant(dev->bus)) { case 0: /* no rerouting necessary */ return 0; case INTEL_IRQ_REROUTE_VARIANT: /* * Remap according to INTx routing table in 6700PXH * specs, intel order number 302628-002, section * 2.15.2. Other chipsets (80332, ...) have the same * mapping and are handled here as well. */ dev_info(&dev->dev, "PCI IRQ %d -> rerouted to legacy " "IRQ %d\n", entry->index, (entry->index % 4) + 16); entry->index = (entry->index % 4) + 16; return 1; default: dev_warn(&dev->dev, "Cannot reroute IRQ %d to legacy " "IRQ: unknown mapping\n", entry->index); return -1; } } } #endif /* CONFIG_X86_IO_APIC */ static struct acpi_prt_entry *acpi_pci_irq_lookup(struct pci_dev *dev, int pin) { struct acpi_prt_entry *entry = NULL; struct pci_dev *bridge; u8 bridge_pin, orig_pin = pin; int ret; ret = acpi_pci_irq_find_prt_entry(dev, pin, &entry); if (!ret && entry) { #ifdef CONFIG_X86_IO_APIC acpi_reroute_boot_interrupt(dev, entry); #endif /* CONFIG_X86_IO_APIC */ ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Found %s[%c] _PRT entry\n", pci_name(dev), pin_name(pin))); return entry; } /* * Attempt to derive an IRQ for this device from a parent bridge's * PCI interrupt routing entry (eg. yenta bridge and add-in card bridge). */ bridge = dev->bus->self; while (bridge) { pin = pci_swizzle_interrupt_pin(dev, pin); if ((bridge->class >> 8) == PCI_CLASS_BRIDGE_CARDBUS) { /* PC card has the same IRQ as its cardbridge */ bridge_pin = bridge->pin; if (!bridge_pin) { ACPI_DEBUG_PRINT((ACPI_DB_INFO, "No interrupt pin configured for device %s\n", pci_name(bridge))); return NULL; } pin = bridge_pin; } ret = acpi_pci_irq_find_prt_entry(bridge, pin, &entry); if (!ret && entry) { ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Derived GSI for %s INT %c from %s\n", pci_name(dev), pin_name(orig_pin), pci_name(bridge))); return entry; } dev = bridge; bridge = dev->bus->self; } dev_warn(&dev->dev, "can't derive routing for PCI INT %c\n", pin_name(orig_pin)); return NULL; } #if IS_ENABLED(CONFIG_ISA) || IS_ENABLED(CONFIG_EISA) static int acpi_isa_register_gsi(struct pci_dev *dev) { u32 dev_gsi; /* Interrupt Line values above 0xF are forbidden */ if (dev->irq > 0 && (dev->irq <= 0xF) && acpi_isa_irq_available(dev->irq) && (acpi_isa_irq_to_gsi(dev->irq, &dev_gsi) == 0)) { dev_warn(&dev->dev, "PCI INT %c: no GSI - using ISA IRQ %d\n", pin_name(dev->pin), dev->irq); acpi_register_gsi(&dev->dev, dev_gsi, ACPI_LEVEL_SENSITIVE, ACPI_ACTIVE_LOW); return 0; } return -EINVAL; } #else static inline int acpi_isa_register_gsi(struct pci_dev *dev) { return -ENODEV; } #endif static inline bool acpi_pci_irq_valid(struct pci_dev *dev, u8 pin) { #ifdef CONFIG_X86 /* * On x86 irq line 0xff means "unknown" or "no connection" * (PCI 3.0, Section 6.2.4, footnote on page 223). */ if (dev->irq == 0xff) { dev->irq = IRQ_NOTCONNECTED; dev_warn(&dev->dev, "PCI INT %c: not connected\n", pin_name(pin)); return false; } #endif return true; } int acpi_pci_irq_enable(struct pci_dev *dev) { struct acpi_prt_entry *entry; int gsi; u8 pin; int triggering = ACPI_LEVEL_SENSITIVE; /* * On ARM systems with the GIC interrupt model, level interrupts * are always polarity high by specification; PCI legacy * IRQs lines are inverted before reaching the interrupt * controller and must therefore be considered active high * as default. */ int polarity = acpi_irq_model == ACPI_IRQ_MODEL_GIC ? ACPI_ACTIVE_HIGH : ACPI_ACTIVE_LOW; char *link = NULL; char link_desc[16]; int rc; pin = dev->pin; if (!pin) { ACPI_DEBUG_PRINT((ACPI_DB_INFO, "No interrupt pin configured for device %s\n", pci_name(dev))); return 0; } if (dev->irq_managed && dev->irq > 0) return 0; entry = acpi_pci_irq_lookup(dev, pin); if (!entry) { /* * IDE legacy mode controller IRQs are magic. Why do compat * extensions always make such a nasty mess. */ if (dev->class >> 8 == PCI_CLASS_STORAGE_IDE && (dev->class & 0x05) == 0) return 0; } if (entry) { if (entry->link) gsi = acpi_pci_link_allocate_irq(entry->link, entry->index, &triggering, &polarity, &link); else gsi = entry->index; } else gsi = -1; if (gsi < 0) { /* * No IRQ known to the ACPI subsystem - maybe the BIOS / * driver reported one, then use it. Exit in any case. */ if (!acpi_pci_irq_valid(dev, pin)) { kfree(entry); return 0; } if (acpi_isa_register_gsi(dev)) dev_warn(&dev->dev, "PCI INT %c: no GSI\n", pin_name(pin)); kfree(entry); return 0; } rc = acpi_register_gsi(&dev->dev, gsi, triggering, polarity); if (rc < 0) { dev_warn(&dev->dev, "PCI INT %c: failed to register GSI\n", pin_name(pin)); kfree(entry); return rc; } dev->irq = rc; dev->irq_managed = 1; if (link) snprintf(link_desc, sizeof(link_desc), " -> Link[%s]", link); else link_desc[0] = '\0'; dev_dbg(&dev->dev, "PCI INT %c%s -> GSI %u (%s, %s) -> IRQ %d\n", pin_name(pin), link_desc, gsi, (triggering == ACPI_LEVEL_SENSITIVE) ? "level" : "edge", (polarity == ACPI_ACTIVE_LOW) ? "low" : "high", dev->irq); kfree(entry); return 0; } void acpi_pci_irq_disable(struct pci_dev *dev) { struct acpi_prt_entry *entry; int gsi; u8 pin; pin = dev->pin; if (!pin || !dev->irq_managed || dev->irq <= 0) return; /* Keep IOAPIC pin configuration when suspending */ if (dev->dev.power.is_prepared) return; #ifdef CONFIG_PM if (dev->dev.power.runtime_status == RPM_SUSPENDING) return; #endif entry = acpi_pci_irq_lookup(dev, pin); if (!entry) return; if (entry->link) gsi = acpi_pci_link_free_irq(entry->link); else gsi = entry->index; kfree(entry); /* * TBD: It might be worth clearing dev->irq by magic constant * (e.g. PCI_UNDEFINED_IRQ). */ dev_dbg(&dev->dev, "PCI INT %c disabled\n", pin_name(pin)); if (gsi >= 0) { acpi_unregister_gsi(gsi); dev->irq_managed = 0; } }
Fe-Pi/linux
drivers/acpi/pci_irq.c
C
gpl-2.0
14,413
// This file is part of par2cmdline (a PAR 2.0 compatible file verification and // repair tool). See http://parchive.sourceforge.net for details of PAR 2.0. // // Copyright (c) 2003 Peter Brian Clements // // par2cmdline 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. // // par2cmdline 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 #ifndef __PAR1REPAIRERSOURCEFILE_H__ #define __PAR1REPAIRERSOURCEFILE_H__ // The Par1RepairerSourceFile object is used during verification and repair // to record details about a particular source file and the data blocks // for that file. class Par1RepairerSourceFile { public: // Construct the object and set the description and verification packets Par1RepairerSourceFile(PAR1FILEENTRY *fileentry, string searchpath); ~Par1RepairerSourceFile(void); string FileName(void) const {return filename;} u64 FileSize(void) const {return filesize;} const MD5Hash& HashFull(void) const {return hashfull;} const MD5Hash& Hash16k(void) const {return hash16k;} // Set/Get which DiskFile will contain the final repaired version of the file void SetTargetFile(DiskFile *diskfile); DiskFile* GetTargetFile(void) const; // Set/Get whether or not the target file actually exists void SetTargetExists(bool exists); bool GetTargetExists(void) const; // Set/Get which DiskFile contains a full undamaged version of the source file void SetCompleteFile(DiskFile *diskfile); DiskFile* GetCompleteFile(void) const; void SetTargetBlock(DiskFile *diskfile); DataBlock* SourceBlock(void) {return &sourceblock;} DataBlock* TargetBlock(void) {return &targetblock;} protected: string filename; u64 filesize; MD5Hash hashfull; MD5Hash hash16k; DataBlock sourceblock; DataBlock targetblock; bool targetexists; // Whether the target file exists DiskFile *targetfile; // The final version of the file DiskFile *completefile; // A complete version of the file }; #endif // __PAR1REPAIRERSOURCEFILE_H__
BlackIkeEagle/par2cmdline
src/par1repairersourcefile.h
C
gpl-2.0
2,641
<?php /** * @file * Contains \Drupal\Console\Generator\Generator. */ namespace Drupal\Console\Generator; use Drupal\Console\Helper\HelperTrait; use Drupal\Console\Style\DrupalStyle; class Generator { use HelperTrait; /** * @var array */ private $files; /** * @var bool */ private $learning = false; /** * @var array */ private $helperSet; /** * @var DrupalStyle $io */ protected $io; /** * @param string $template * @param string $target * @param array $parameters * @param null $flag * * @return bool */ protected function renderFile($template, $target, $parameters, $flag = null) { if (!is_dir(dirname($target))) { mkdir(dirname($target), 0777, true); } if (file_put_contents($target, $this->getRenderHelper()->render($template, $parameters), $flag)) { $this->files[] = str_replace($this->getDrupalHelper()->getRoot().'/', '', $target); return true; } return false; } /** * @param $helperSet */ public function setHelperSet($helperSet) { $this->helperSet = $helperSet; } /** * @return array */ public function getHelperSet() { return $this->helperSet; } /** * @return array */ public function getFiles() { return $this->files; } /** * @param $learning */ public function setLearning($learning) { $this->learning = $learning; } /** * @return bool */ public function isLearning() { return $this->learning; } /** * @param DrupalStyle $io */ public function setIo($io) { $this->io = $io; } }
sgrichards/BrightonDrupal
vendor/drupal/console/src/Generator/Generator.php
PHP
gpl-2.0
1,821
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef SHERLOCK_TATTOO_WIDGET_FILES_H #define SHERLOCK_TATTOO_WIDGET_FILES_H #include "common/scummsys.h" #include "sherlock/tattoo/widget_base.h" #include "sherlock/saveload.h" namespace Sherlock { class SherlockEngine; namespace Tattoo { enum FilesRenderMode { RENDER_ALL, RENDER_NAMES, RENDER_NAMES_AND_SCROLLBAR }; class WidgetFiles: public WidgetBase, public SaveManager { private: SherlockEngine *_vm; SaveMode _fileMode; int _selector, _oldSelector; /** * Render the dialog */ void render(FilesRenderMode mode); /** * Show the ScummVM Save Game dialog */ void showScummVMSaveDialog(); /** * Show the ScummVM Load Game dialog */ void showScummVMRestoreDialog(); /** * Prompt the user for a savegame name in the currently selected slot */ bool getFilename(); /** * Return the area of a widget that the scrollbar will be drawn in */ virtual Common::Rect getScrollBarBounds() const; public: WidgetFiles(SherlockEngine *vm, const Common::String &target); /** * Prompt the user whether to quit */ void show(SaveMode mode); /** * Handle event processing */ virtual void handleEvents(); }; } // End of namespace Tattoo } // End of namespace Sherlock #endif
alexbevi/scummvm
engines/sherlock/tattoo/widget_files.h
C
gpl-2.0
2,168
option( OKULAR_FORCE_DRM "Forces okular to check for DRM to decide if you can copy/print protected pdf. (default=no)" OFF ) if (OKULAR_FORCE_DRM) set(_OKULAR_FORCE_DRM 1) else (OKULAR_FORCE_DRM) set(_OKULAR_FORCE_DRM 0) endif (OKULAR_FORCE_DRM) # at the end, output the configuration configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/config-okular.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-okular.h )
igsor/okular
OkularConfigureChecks.cmake
CMake
gpl-2.0
420
/* Copyright (C) 2003-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Jakub Jelinek <jakub@redhat.com>, 2003. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <setjmp.h> #include <jmpbuf-offsets.h> #include <stdint.h> #include <unwind.h> #include <bits/wordsize.h> #include <sysdep.h> /* Test if longjmp to JMPBUF would unwind the frame containing a local variable at ADDRESS. */ #define _JMPBUF_UNWINDS(jmpbuf, address, demangle) \ ((void *) (address) < (void *) demangle ((jmpbuf)->__gregs[__JB_GPR15])) /* On s390{,x}, CFA is always 96 (resp. 160) bytes above actual %r15. */ #define _JMPBUF_CFA_UNWINDS_ADJ(_jmpbuf, _context, _adj) \ _JMPBUF_UNWINDS_ADJ (_jmpbuf, \ (void *) (_Unwind_GetCFA (_context) \ - 32 - 2 * __WORDSIZE), _adj) static inline uintptr_t __attribute__ ((unused)) _jmpbuf_sp (__jmp_buf regs) { void *sp = (void *) (uintptr_t) regs[0].__gregs[__JB_GPR15]; #ifdef PTR_DEMANGLE PTR_DEMANGLE (sp); #endif return (uintptr_t) sp; } #define _JMPBUF_UNWINDS_ADJ(_jmpbuf, _address, _adj) \ ((uintptr_t) (_address) - (_adj) < _jmpbuf_sp (_jmpbuf) - (_adj)) /* We use the normal longjmp for unwinding. */ #define __libc_unwind_longjmp(buf, val) __libc_longjmp (buf, val)
rbheromax/src_glibc
sysdeps/s390/jmpbuf-unwind.h
C
gpl-2.0
1,928
// { dg-do compile } // { dg-options "-O -w -Wno-psabi" } typedef int vec __attribute__((vector_size(32))); vec fn1() { vec x, zero{}; vec one = zero + 1; return x < zero ? one : zero; }
Gurgel100/gcc
gcc/testsuite/g++.dg/pr86159.C
C++
gpl-2.0
194
/** * Notification.js * * Released under LGPL License. * Copyright (c) 1999-2015 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * Creates a notification instance. * * @-x-less Notification.less * @class tinymce.ui.Notification * @extends tinymce.ui.Container * @mixes tinymce.ui.Movable */ define("tinymce/ui/Notification", [ "tinymce/ui/Control", "tinymce/ui/Movable", "tinymce/ui/Progress", "tinymce/util/Delay" ], function(Control, Movable, Progress, Delay) { return Control.extend({ Mixins: [Movable], Defaults: { classes: 'widget notification' }, init: function(settings) { var self = this; self._super(settings); if (settings.text) { self.text(settings.text); } if (settings.icon) { self.icon = settings.icon; } if (settings.color) { self.color = settings.color; } if (settings.type) { self.classes.add('notification-' + settings.type); } if (settings.timeout && (settings.timeout < 0 || settings.timeout > 0) && !settings.closeButton) { self.closeButton = false; } else { self.classes.add('has-close'); self.closeButton = true; } if (settings.progressBar) { self.progressBar = new Progress(); } self.on('click', function(e) { if (e.target.className.indexOf(self.classPrefix + 'close') != -1) { self.close(); } }); }, /** * Renders the control as a HTML string. * * @method renderHtml * @return {String} HTML representing the control. */ renderHtml: function() { var self = this, prefix = self.classPrefix, icon = '', closeButton = '', progressBar = '', notificationStyle = ''; if (self.icon) { icon = '<i class="' + prefix + 'ico' + ' ' + prefix + 'i-' + self.icon + '"></i>'; } if (self.color) { notificationStyle = ' style="background-color: ' + self.color + '"'; } if (self.closeButton) { closeButton = '<button type="button" class="' + prefix + 'close" aria-hidden="true">\u00d7</button>'; } if (self.progressBar) { progressBar = self.progressBar.renderHtml(); } return ( '<div id="' + self._id + '" class="' + self.classes + '"' + notificationStyle + ' role="presentation">' + icon + '<div class="' + prefix + 'notification-inner">' + self.state.get('text') + '</div>' + progressBar + closeButton + '</div>' ); }, postRender: function() { var self = this; Delay.setTimeout(function() { self.$el.addClass(self.classPrefix + 'in'); }); return self._super(); }, bindStates: function() { var self = this; self.state.on('change:text', function(e) { self.getEl().childNodes[1].innerHTML = e.value; }); if (self.progressBar) { self.progressBar.bindStates(); } return self._super(); }, close: function() { var self = this; if (!self.fire('close').isDefaultPrevented()) { self.remove(); } return self; }, /** * Repaints the control after a layout operation. * * @method repaint */ repaint: function() { var self = this, style, rect; style = self.getEl().style; rect = self._layoutRect; style.left = rect.x + 'px'; style.top = rect.y + 'px'; // Hardcoded arbitrary z-value because we want the // notifications under the other windows style.zIndex = 0xFFFF - 1; } }); });
luis-knd/technoMvc
views/tinymce/js/tinymce/classes/ui/Notification.js
JavaScript
gpl-2.0
3,429
<?php /** * Generic Slider super class. Extended by library specific classes. */ class MetaImageSlide extends MetaSlide { /** * Register slide type */ public function __construct() { add_filter( 'metaslider_get_image_slide', array( $this, 'get_slide' ), 10, 2 ); add_action( 'metaslider_save_image_slide', array( $this, 'save_slide' ), 5, 3 ); add_action( 'wp_ajax_create_image_slide', array( $this, 'ajax_create_slide' ) ); add_action( 'wp_ajax_resize_image_slide', array( $this, 'ajax_resize_slide' ) ); } /** * Create a new slide and echo the admin HTML */ public function ajax_create_slide() { // security check if ( !wp_verify_nonce( $_REQUEST['_wpnonce'], 'metaslider_addslide' ) ) { echo "<tr><td colspan='2'>" . __( "Security check failed. Refresh page and try again.", 'metaslider' ) . "</td></tr>"; die(); } $slider_id = absint( $_POST['slider_id'] ); $selection = $_POST['selection']; if ( is_array( $selection ) && count( $selection ) && $slider_id > 0 ) { foreach ( $selection as $slide_id ) { $this->set_slide( $slide_id ); $this->set_slider( $slider_id ); if ( $this->slide_exists_in_slideshow( $slider_id, $slide_id ) ) { echo "<tr><td colspan='2'>ID: {$slide_id} \"" . get_the_title( $slide_id ) . "\" - " . __( "Failed to add slide. Slide already exists in slideshow.", 'metaslider' ) . "</td></tr>"; } else if ( !$this->slide_is_unassigned_or_image_slide( $slider_id, $slide_id ) ) { echo "<tr><td colspan='2'>ID: {$slide_id} \"" . get_the_title( $slide_id ) . "\" - " . __( "Failed to add slide. Slide is not of type 'image'.", 'metaslider' ) . "</td></tr>"; }else { $this->tag_slide_to_slider(); $this->add_or_update_or_delete_meta( $slide_id, 'type', 'image' ); // override the width and height to kick off the AJAX image resizing on save $this->settings['width'] = 0; $this->settings['height'] = 0; echo $this->get_admin_slide(); } } } die(); } /** * Create a new slide and echo the admin HTML */ public function ajax_resize_slide() { check_admin_referer( 'metaslider_resize' ); $slider_id = absint( $_POST['slider_id'] ); $slide_id = absint( $_POST['slide_id'] ); $this->set_slide( $slide_id ); $this->set_slider( $slider_id ); $settings = get_post_meta( $slider_id, 'ml-slider_settings', true ); // create a copy of the correct sized image $imageHelper = new MetaSliderImageHelper( $slide_id, $settings['width'], $settings['height'], isset( $settings['smartCrop'] ) ? $settings['smartCrop'] : 'false', $this->use_wp_image_editor() ); $url = $imageHelper->get_image_url(); echo $url . " (" . $settings['width'] . 'x' . $settings['height'] . ")"; die(); } /** * Return the HTML used to display this slide in the admin screen * * @return string slide html */ protected function get_admin_slide() { // get some slide settings $imageHelper = new MetaSliderImageHelper( $this->slide->ID, 150, 150, 'false', $this->use_wp_image_editor() ); $thumb = $imageHelper->get_image_url(); $url = get_post_meta( $this->slide->ID, 'ml-slider_url', true ); $title = get_post_meta( $this->slide->ID, 'ml-slider_title', true ); $alt = get_post_meta( $this->slide->ID, '_wp_attachment_image_alt', true ); $target = get_post_meta( $this->slide->ID, 'ml-slider_new_window', true ) ? 'checked=checked' : ''; $caption = htmlentities( $this->slide->post_excerpt, ENT_QUOTES, 'UTF-8' ); // localisation $str_caption = __( "Caption", "metaslider" ); $str_new_window = __( "New Window", "metaslider" ); $str_url = __( "URL", "metaslider" ); $str_label = __( "Image Slide", "metaslider" ); $slide_label = apply_filters( "metaslider_image_slide_label", $str_label, $this->slide, $this->settings ); // slide row HTML $row = "<tr class='slide image flex responsive nivo coin'>"; $row .= " <td class='col-1'>"; $row .= " <div class='thumb' style='background-image: url({$thumb})'>"; $row .= " <a class='delete-slide confirm' href='?page=metaslider&amp;id={$this->slider->ID}&amp;deleteSlide={$this->slide->ID}'>x</a>"; $row .= " <span class='slide-details'>" . $slide_label . "</span>"; $row .= " </div>"; $row .= " </td>"; $row .= " <td class='col-2'>"; $row .= " <ul class='tabs'>"; $row .= " <li class='selected' rel='tab-1'>" . __( "General", "metaslider" ) . "</li>"; $row .= " <li rel='tab-2'>" . __( "SEO", "metaslider" ) . "</li>"; $row .= " </ul>"; $row .= " <div class='tabs-content'>"; $row .= " <div class='tab tab-1'>"; if ( !$this->is_valid_image() ) { $row .= "<div class='warning'>" . __( "Warning: Image data does not exist. Please re-upload the image.", "metaslider" ) . "</div>"; } $row .= " <textarea name='attachment[{$this->slide->ID}][post_excerpt]' placeholder='{$str_caption}'>{$caption}</textarea>"; $row .= " <input class='url' type='text' name='attachment[{$this->slide->ID}][url]' placeholder='{$str_url}' value='{$url}' />"; $row .= " <div class='new_window'>"; $row .= " <label>{$str_new_window}<input type='checkbox' name='attachment[{$this->slide->ID}][new_window]' {$target} /></label>"; $row .= " </div>"; $row .= " </div>"; $row .= " <div class='tab tab-2' style='display: none;'>"; $row .= " <div class='row'><label>" . __( "Image Title Text", "metaslider" ) . "</label></div>"; $row .= " <div class='row'><input type='text' size='50' name='attachment[{$this->slide->ID}][title]' value='{$title}' /></div>"; $row .= " <div class='row'><label>" . __( "Image Alt Text", "metaslider" ) . "</label></div>"; $row .= " <div class='row'><input type='text' size='50' name='attachment[{$this->slide->ID}][alt]' value='{$alt}' /></div>"; $row .= " </div>"; $row .= " </div>"; $row .= " <input type='hidden' name='attachment[{$this->slide->ID}][type]' value='image' />"; $row .= " <input type='hidden' class='menu_order' name='attachment[{$this->slide->ID}][menu_order]' value='{$this->slide->menu_order}' />"; $row .= " <input type='hidden' name='resize_slide_id' data-slide_id='{$this->slide->ID}' data-width='{$this->settings['width']}' data-height='{$this->settings['height']}' />"; $row .= " </td>"; $row .= "</tr>"; return $row; } /** * Check to see if metadata exists for this image. Assume the image is * valid if metadata and a size exists for it (generated during initial * upload to WordPress). * * @return bool, true if metadata and size exists. */ public function is_valid_image() { $meta = wp_get_attachment_metadata( $this->slide->ID ); return isset( $meta['width'], $meta['height'] ); } /** * Disable/enable image editor * * @return bool */ public function use_wp_image_editor() { return apply_filters( 'metaslider_use_image_editor', $this->is_valid_image() ); } /** * Returns the HTML for the public slide * * @return string slide html */ protected function get_public_slide() { // get the image url (and handle cropping) // disable wp_image_editor if metadata does not exist for the slide $imageHelper = new MetaSliderImageHelper( $this->slide->ID, $this->settings['width'], $this->settings['height'], isset( $this->settings['smartCrop'] ) ? $this->settings['smartCrop'] : 'false', $this->use_wp_image_editor() ); $thumb = $imageHelper->get_image_url(); // store the slide details $slide = array( 'id' => $this->slide->ID, 'url' => __( get_post_meta( $this->slide->ID, 'ml-slider_url', true ) ), 'title' => __( get_post_meta( $this->slide->ID, 'ml-slider_title', true ) ), 'target' => get_post_meta( $this->slide->ID, 'ml-slider_new_window', true ) ? '_blank' : '_self', 'src' => $thumb, 'thumb' => $thumb, // backwards compatibility with Vantage 'width' => $this->settings['width'], 'height' => $this->settings['height'], 'alt' => __( get_post_meta( $this->slide->ID, '_wp_attachment_image_alt', true ) ), 'caption' => __( html_entity_decode( do_shortcode( $this->slide->post_excerpt ), ENT_NOQUOTES, 'UTF-8' ) ), 'caption_raw' => __( do_shortcode( $this->slide->post_excerpt ) ), 'class' => "slider-{$this->slider->ID} slide-{$this->slide->ID}", 'rel' => "", 'data-thumb' => "" ); // fix slide URLs if ( strpos( $slide['url'], 'www.' ) === 0 ) { $slide['url'] = 'http://' . $slide['url']; } $slide = apply_filters( 'metaslider_image_slide_attributes', $slide, $this->slider->ID, $this->settings ); // return the slide HTML switch ( $this->settings['type'] ) { case "coin": return $this->get_coin_slider_markup( $slide ); case "flex": return $this->get_flex_slider_markup( $slide ); case "nivo": return $this->get_nivo_slider_markup( $slide ); case "responsive": return $this->get_responsive_slides_markup( $slide ); default: return $this->get_flex_slider_markup( $slide ); } } /** * Generate nivo slider markup * * @return string slide html */ private function get_nivo_slider_markup( $slide ) { $attributes = apply_filters( 'metaslider_nivo_slider_image_attributes', array( 'src' => $slide['src'], 'height' => $slide['height'], 'width' => $slide['width'], 'data-title' => htmlentities( $slide['caption_raw'], ENT_QUOTES, 'UTF-8' ), 'data-thumb' => $slide['data-thumb'], 'title' => $slide['title'], 'alt' => $slide['alt'], 'rel' => $slide['rel'], 'class' => $slide['class'] ), $slide, $this->slider->ID ); $html = $this->build_image_tag( $attributes ); $anchor_attributes = apply_filters( 'metaslider_nivo_slider_anchor_attributes', array( 'href' => $slide['url'], 'target' => $slide['target'] ), $slide, $this->slider->ID ); if ( strlen( $anchor_attributes['href'] ) ) { $html = $this->build_anchor_tag( $anchor_attributes, $html ); } return apply_filters( 'metaslider_image_nivo_slider_markup', $html, $slide, $this->settings ); } /** * Generate flex slider markup * * @return string slide html */ private function get_flex_slider_markup( $slide ) { $attributes = apply_filters( 'metaslider_flex_slider_image_attributes', array( 'src' => $slide['src'], 'height' => $slide['height'], 'width' => $slide['width'], 'alt' => $slide['alt'], 'rel' => $slide['rel'], 'class' => $slide['class'], 'title' => $slide['title'] ), $slide, $this->slider->ID ); $html = $this->build_image_tag( $attributes ); $anchor_attributes = apply_filters( 'metaslider_flex_slider_anchor_attributes', array( 'href' => $slide['url'], 'target' => $slide['target'] ), $slide, $this->slider->ID ); if ( strlen( $anchor_attributes['href'] ) ) { $html = $this->build_anchor_tag( $anchor_attributes, $html ); } // add caption if ( strlen( $slide['caption'] ) ) { $html .= '<div class="caption-wrap"><div class="caption">' . $slide['caption'] . '</div></div>'; } $thumb = isset( $slide['data-thumb'] ) && strlen( $slide['data-thumb'] ) ? " data-thumb=\"{$slide['data-thumb']}\"" : ""; $html = '<li style="display: none; float: left; width: 100%;"' . $thumb . '>' . $html . '</li>'; return apply_filters( 'metaslider_image_flex_slider_markup', $html, $slide, $this->settings ); } /** * Generate coin slider markup * * @return string slide html */ private function get_coin_slider_markup( $slide ) { $attributes = apply_filters( 'metaslider_coin_slider_image_attributes', array( 'src' => $slide['src'], 'height' => $slide['height'], 'width' => $slide['width'], 'alt' => $slide['alt'], 'rel' => $slide['rel'], 'class' => $slide['class'], 'title' => $slide['title'], 'style' => 'display: none;' ), $slide, $this->slider->ID ); $html = $this->build_image_tag( $attributes ); if ( strlen( $slide['caption'] ) ) { $html .= "<span>{$slide['caption']}</span>"; } $attributes = apply_filters( 'metaslider_coin_slider_anchor_attributes', array( 'href' => strlen( $slide['url'] ) ? $slide['url'] : 'javascript:void(0)' ), $slide, $this->slider->ID ); $html = $this->build_anchor_tag( $attributes, $html ); return apply_filters( 'metaslider_image_coin_slider_markup', $html, $slide, $this->settings ); } /** * Generate responsive slides markup * * @return string slide html */ private function get_responsive_slides_markup( $slide ) { $attributes = apply_filters( 'metaslider_responsive_slider_image_attributes', array( 'src' => $slide['src'], 'height' => $slide['height'], 'width' => $slide['width'], 'alt' => $slide['alt'], 'rel' => $slide['rel'], 'class' => $slide['class'], 'title' => $slide['title'] ), $slide, $this->slider->ID ); $html = $this->build_image_tag( $attributes ); if ( strlen( $slide['caption'] ) ) { $html .= '<div class="caption-wrap"><div class="caption">' . $slide['caption'] . '</div></div>'; } $anchor_attributes = apply_filters( 'metaslider_responsive_slider_anchor_attributes', array( 'href' => $slide['url'], 'target' => $slide['target'] ), $slide, $this->slider->ID ); if ( strlen( $anchor_attributes['href'] ) ) { $html = $this->build_anchor_tag( $anchor_attributes, $html ); } return apply_filters( 'metaslider_image_responsive_slider_markup', $html, $slide, $this->settings ); } /** * Save */ protected function save( $fields ) { // update the slide wp_update_post( array( 'ID' => $this->slide->ID, 'post_excerpt' => $fields['post_excerpt'], 'menu_order' => $fields['menu_order'] ) ); // store the URL as a meta field against the attachment $this->add_or_update_or_delete_meta( $this->slide->ID, 'url', $fields['url'] ); $this->add_or_update_or_delete_meta( $this->slide->ID, 'title', $fields['title'] ); if ( isset( $fields['alt'] ) ) { update_post_meta( $this->slide->ID, '_wp_attachment_image_alt', $fields['alt'] ); } // store the 'new window' setting $new_window = isset( $fields['new_window'] ) && $fields['new_window'] == 'on' ? 'true' : 'false'; $this->add_or_update_or_delete_meta( $this->slide->ID, 'new_window', $new_window ); } } ?>
jackcommon/vnusa
wp-content/plugins/ml-slider/inc/slide/metaslide.image.class.php
PHP
gpl-2.0
16,682
/* * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "classfile/symbolTable.hpp" #include "gc_implementation/parallelScavenge/cardTableExtension.hpp" #include "gc_implementation/parallelScavenge/gcTaskManager.hpp" #include "gc_implementation/parallelScavenge/generationSizer.hpp" #include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp" #include "gc_implementation/parallelScavenge/psAdaptiveSizePolicy.hpp" #include "gc_implementation/parallelScavenge/psMarkSweep.hpp" #include "gc_implementation/parallelScavenge/psParallelCompact.hpp" #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp" #include "gc_implementation/parallelScavenge/psTasks.hpp" #include "gc_implementation/shared/isGCActiveMark.hpp" #include "gc_implementation/shared/spaceDecorator.hpp" #include "gc_interface/gcCause.hpp" #include "memory/collectorPolicy.hpp" #include "memory/gcLocker.inline.hpp" #include "memory/referencePolicy.hpp" #include "memory/referenceProcessor.hpp" #include "memory/resourceArea.hpp" #include "oops/oop.inline.hpp" #include "oops/oop.psgc.inline.hpp" #include "runtime/biasedLocking.hpp" #include "runtime/fprofiler.hpp" #include "runtime/handles.inline.hpp" #include "runtime/threadCritical.hpp" #include "runtime/vmThread.hpp" #include "runtime/vm_operations.hpp" #include "services/memoryService.hpp" #include "utilities/stack.inline.hpp" HeapWord* PSScavenge::_to_space_top_before_gc = NULL; int PSScavenge::_consecutive_skipped_scavenges = 0; ReferenceProcessor* PSScavenge::_ref_processor = NULL; CardTableExtension* PSScavenge::_card_table = NULL; bool PSScavenge::_survivor_overflow = false; int PSScavenge::_tenuring_threshold = 0; HeapWord* PSScavenge::_young_generation_boundary = NULL; elapsedTimer PSScavenge::_accumulated_time; Stack<markOop> PSScavenge::_preserved_mark_stack; Stack<oop> PSScavenge::_preserved_oop_stack; CollectorCounters* PSScavenge::_counters = NULL; bool PSScavenge::_promotion_failed = false; // Define before use class PSIsAliveClosure: public BoolObjectClosure { public: void do_object(oop p) { assert(false, "Do not call."); } bool do_object_b(oop p) { return (!PSScavenge::is_obj_in_young((HeapWord*) p)) || p->is_forwarded(); } }; PSIsAliveClosure PSScavenge::_is_alive_closure; class PSKeepAliveClosure: public OopClosure { protected: MutableSpace* _to_space; PSPromotionManager* _promotion_manager; public: PSKeepAliveClosure(PSPromotionManager* pm) : _promotion_manager(pm) { ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity"); _to_space = heap->young_gen()->to_space(); assert(_promotion_manager != NULL, "Sanity"); } template <class T> void do_oop_work(T* p) { assert (!oopDesc::is_null(*p), "expected non-null ref"); assert ((oopDesc::load_decode_heap_oop_not_null(p))->is_oop(), "expected an oop while scanning weak refs"); // Weak refs may be visited more than once. if (PSScavenge::should_scavenge(p, _to_space)) { PSScavenge::copy_and_push_safe_barrier(_promotion_manager, p); } } virtual void do_oop(oop* p) { PSKeepAliveClosure::do_oop_work(p); } virtual void do_oop(narrowOop* p) { PSKeepAliveClosure::do_oop_work(p); } }; class PSEvacuateFollowersClosure: public VoidClosure { private: PSPromotionManager* _promotion_manager; public: PSEvacuateFollowersClosure(PSPromotionManager* pm) : _promotion_manager(pm) {} virtual void do_void() { assert(_promotion_manager != NULL, "Sanity"); _promotion_manager->drain_stacks(true); guarantee(_promotion_manager->stacks_empty(), "stacks should be empty at this point"); } }; class PSPromotionFailedClosure : public ObjectClosure { virtual void do_object(oop obj) { if (obj->is_forwarded()) { obj->init_mark(); } } }; class PSRefProcTaskProxy: public GCTask { typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask; ProcessTask & _rp_task; uint _work_id; public: PSRefProcTaskProxy(ProcessTask & rp_task, uint work_id) : _rp_task(rp_task), _work_id(work_id) { } private: virtual char* name() { return (char *)"Process referents by policy in parallel"; } virtual void do_it(GCTaskManager* manager, uint which); }; void PSRefProcTaskProxy::do_it(GCTaskManager* manager, uint which) { PSPromotionManager* promotion_manager = PSPromotionManager::gc_thread_promotion_manager(which); assert(promotion_manager != NULL, "sanity check"); PSKeepAliveClosure keep_alive(promotion_manager); PSEvacuateFollowersClosure evac_followers(promotion_manager); PSIsAliveClosure is_alive; _rp_task.work(_work_id, is_alive, keep_alive, evac_followers); } class PSRefEnqueueTaskProxy: public GCTask { typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask; EnqueueTask& _enq_task; uint _work_id; public: PSRefEnqueueTaskProxy(EnqueueTask& enq_task, uint work_id) : _enq_task(enq_task), _work_id(work_id) { } virtual char* name() { return (char *)"Enqueue reference objects in parallel"; } virtual void do_it(GCTaskManager* manager, uint which) { _enq_task.work(_work_id); } }; class PSRefProcTaskExecutor: public AbstractRefProcTaskExecutor { virtual void execute(ProcessTask& task); virtual void execute(EnqueueTask& task); }; void PSRefProcTaskExecutor::execute(ProcessTask& task) { GCTaskQueue* q = GCTaskQueue::create(); for(uint i=0; i<ParallelGCThreads; i++) { q->enqueue(new PSRefProcTaskProxy(task, i)); } ParallelTaskTerminator terminator( ParallelScavengeHeap::gc_task_manager()->workers(), (TaskQueueSetSuper*) PSPromotionManager::stack_array_depth()); if (task.marks_oops_alive() && ParallelGCThreads > 1) { for (uint j=0; j<ParallelGCThreads; j++) { q->enqueue(new StealTask(&terminator)); } } ParallelScavengeHeap::gc_task_manager()->execute_and_wait(q); } void PSRefProcTaskExecutor::execute(EnqueueTask& task) { GCTaskQueue* q = GCTaskQueue::create(); for(uint i=0; i<ParallelGCThreads; i++) { q->enqueue(new PSRefEnqueueTaskProxy(task, i)); } ParallelScavengeHeap::gc_task_manager()->execute_and_wait(q); } // This method contains all heap specific policy for invoking scavenge. // PSScavenge::invoke_no_policy() will do nothing but attempt to // scavenge. It will not clean up after failed promotions, bail out if // we've exceeded policy time limits, or any other special behavior. // All such policy should be placed here. // // Note that this method should only be called from the vm_thread while // at a safepoint! void PSScavenge::invoke() { assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint"); assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread"); assert(!Universe::heap()->is_gc_active(), "not reentrant"); ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity"); PSAdaptiveSizePolicy* policy = heap->size_policy(); IsGCActiveMark mark; bool scavenge_was_done = PSScavenge::invoke_no_policy(); PSGCAdaptivePolicyCounters* counters = heap->gc_policy_counters(); if (UsePerfData) counters->update_full_follows_scavenge(0); if (!scavenge_was_done || policy->should_full_GC(heap->old_gen()->free_in_bytes())) { if (UsePerfData) counters->update_full_follows_scavenge(full_follows_scavenge); GCCauseSetter gccs(heap, GCCause::_adaptive_size_policy); CollectorPolicy* cp = heap->collector_policy(); const bool clear_all_softrefs = cp->should_clear_all_soft_refs(); if (UseParallelOldGC) { PSParallelCompact::invoke_no_policy(clear_all_softrefs); } else { PSMarkSweep::invoke_no_policy(clear_all_softrefs); } } } // This method contains no policy. You should probably // be calling invoke() instead. bool PSScavenge::invoke_no_policy() { assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint"); assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread"); assert(_preserved_mark_stack.is_empty(), "should be empty"); assert(_preserved_oop_stack.is_empty(), "should be empty"); TimeStamp scavenge_entry; TimeStamp scavenge_midpoint; TimeStamp scavenge_exit; scavenge_entry.update(); if (GC_locker::check_active_before_gc()) { return false; } ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); GCCause::Cause gc_cause = heap->gc_cause(); assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity"); // Check for potential problems. if (!should_attempt_scavenge()) { return false; } bool promotion_failure_occurred = false; PSYoungGen* young_gen = heap->young_gen(); PSOldGen* old_gen = heap->old_gen(); PSPermGen* perm_gen = heap->perm_gen(); PSAdaptiveSizePolicy* size_policy = heap->size_policy(); heap->increment_total_collections(); AdaptiveSizePolicyOutput(size_policy, heap->total_collections()); if ((gc_cause != GCCause::_java_lang_system_gc) || UseAdaptiveSizePolicyWithSystemGC) { // Gather the feedback data for eden occupancy. young_gen->eden_space()->accumulate_statistics(); } if (ZapUnusedHeapArea) { // Save information needed to minimize mangling heap->record_gen_tops_before_GC(); } if (PrintHeapAtGC) { Universe::print_heap_before_gc(); } assert(!NeverTenure || _tenuring_threshold == markOopDesc::max_age + 1, "Sanity"); assert(!AlwaysTenure || _tenuring_threshold == 0, "Sanity"); size_t prev_used = heap->used(); assert(promotion_failed() == false, "Sanity"); // Fill in TLABs heap->accumulate_statistics_all_tlabs(); heap->ensure_parsability(true); // retire TLABs if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) { HandleMark hm; // Discard invalid handles created during verification gclog_or_tty->print(" VerifyBeforeGC:"); Universe::verify(true); } { ResourceMark rm; HandleMark hm; gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps); TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); TraceTime t1("GC", PrintGC, !PrintGCDetails, gclog_or_tty); TraceCollectorStats tcs(counters()); TraceMemoryManagerStats tms(false /* not full GC */,gc_cause); if (TraceGen0Time) accumulated_time()->start(); // Let the size policy know we're starting size_policy->minor_collection_begin(); // Verify the object start arrays. if (VerifyObjectStartArray && VerifyBeforeGC) { old_gen->verify_object_start_array(); perm_gen->verify_object_start_array(); } // Verify no unmarked old->young roots if (VerifyRememberedSets) { CardTableExtension::verify_all_young_refs_imprecise(); } if (!ScavengeWithObjectsInToSpace) { assert(young_gen->to_space()->is_empty(), "Attempt to scavenge with live objects in to_space"); young_gen->to_space()->clear(SpaceDecorator::Mangle); } else if (ZapUnusedHeapArea) { young_gen->to_space()->mangle_unused_area(); } save_to_space_top_before_gc(); NOT_PRODUCT(reference_processor()->verify_no_references_recorded()); COMPILER2_PRESENT(DerivedPointerTable::clear()); reference_processor()->enable_discovery(); reference_processor()->setup_policy(false); // We track how much was promoted to the next generation for // the AdaptiveSizePolicy. size_t old_gen_used_before = old_gen->used_in_bytes(); // For PrintGCDetails size_t young_gen_used_before = young_gen->used_in_bytes(); // Reset our survivor overflow. set_survivor_overflow(false); // We need to save the old/perm top values before // creating the promotion_manager. We pass the top // values to the card_table, to prevent it from // straying into the promotion labs. HeapWord* old_top = old_gen->object_space()->top(); HeapWord* perm_top = perm_gen->object_space()->top(); // Release all previously held resources gc_task_manager()->release_all_resources(); PSPromotionManager::pre_scavenge(); // We'll use the promotion manager again later. PSPromotionManager* promotion_manager = PSPromotionManager::vm_thread_promotion_manager(); { // TraceTime("Roots"); ParallelScavengeHeap::ParStrongRootsScope psrs; GCTaskQueue* q = GCTaskQueue::create(); for(uint i=0; i<ParallelGCThreads; i++) { q->enqueue(new OldToYoungRootsTask(old_gen, old_top, i)); } q->enqueue(new SerialOldToYoungRootsTask(perm_gen, perm_top)); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::universe)); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::jni_handles)); // We scan the thread roots in parallel Threads::create_thread_roots_tasks(q); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::object_synchronizer)); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::flat_profiler)); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::management)); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::system_dictionary)); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::jvmti)); q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::code_cache)); ParallelTaskTerminator terminator( gc_task_manager()->workers(), (TaskQueueSetSuper*) promotion_manager->stack_array_depth()); if (ParallelGCThreads>1) { for (uint j=0; j<ParallelGCThreads; j++) { q->enqueue(new StealTask(&terminator)); } } gc_task_manager()->execute_and_wait(q); } scavenge_midpoint.update(); // Process reference objects discovered during scavenge { reference_processor()->setup_policy(false); // not always_clear PSKeepAliveClosure keep_alive(promotion_manager); PSEvacuateFollowersClosure evac_followers(promotion_manager); if (reference_processor()->processing_is_mt()) { PSRefProcTaskExecutor task_executor; reference_processor()->process_discovered_references( &_is_alive_closure, &keep_alive, &evac_followers, &task_executor); } else { reference_processor()->process_discovered_references( &_is_alive_closure, &keep_alive, &evac_followers, NULL); } } // Enqueue reference objects discovered during scavenge. if (reference_processor()->processing_is_mt()) { PSRefProcTaskExecutor task_executor; reference_processor()->enqueue_discovered_references(&task_executor); } else { reference_processor()->enqueue_discovered_references(NULL); } if (!JavaObjectsInPerm) { // Unlink any dead interned Strings StringTable::unlink(&_is_alive_closure); // Process the remaining live ones PSScavengeRootsClosure root_closure(promotion_manager); StringTable::oops_do(&root_closure); } // Finally, flush the promotion_manager's labs, and deallocate its stacks. PSPromotionManager::post_scavenge(); promotion_failure_occurred = promotion_failed(); if (promotion_failure_occurred) { clean_up_failed_promotion(); if (PrintGC) { gclog_or_tty->print("--"); } } // Let the size policy know we're done. Note that we count promotion // failure cleanup time as part of the collection (otherwise, we're // implicitly saying it's mutator time). size_policy->minor_collection_end(gc_cause); if (!promotion_failure_occurred) { // Swap the survivor spaces. young_gen->eden_space()->clear(SpaceDecorator::Mangle); young_gen->from_space()->clear(SpaceDecorator::Mangle); young_gen->swap_spaces(); size_t survived = young_gen->from_space()->used_in_bytes(); size_t promoted = old_gen->used_in_bytes() - old_gen_used_before; size_policy->update_averages(_survivor_overflow, survived, promoted); // A successful scavenge should restart the GC time limit count which is // for full GC's. size_policy->reset_gc_overhead_limit_count(); if (UseAdaptiveSizePolicy) { // Calculate the new survivor size and tenuring threshold if (PrintAdaptiveSizePolicy) { gclog_or_tty->print("AdaptiveSizeStart: "); gclog_or_tty->stamp(); gclog_or_tty->print_cr(" collection: %d ", heap->total_collections()); if (Verbose) { gclog_or_tty->print("old_gen_capacity: %d young_gen_capacity: %d" " perm_gen_capacity: %d ", old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes(), perm_gen->capacity_in_bytes()); } } if (UsePerfData) { PSGCAdaptivePolicyCounters* counters = heap->gc_policy_counters(); counters->update_old_eden_size( size_policy->calculated_eden_size_in_bytes()); counters->update_old_promo_size( size_policy->calculated_promo_size_in_bytes()); counters->update_old_capacity(old_gen->capacity_in_bytes()); counters->update_young_capacity(young_gen->capacity_in_bytes()); counters->update_survived(survived); counters->update_promoted(promoted); counters->update_survivor_overflowed(_survivor_overflow); } size_t survivor_limit = size_policy->max_survivor_size(young_gen->max_size()); _tenuring_threshold = size_policy->compute_survivor_space_size_and_threshold( _survivor_overflow, _tenuring_threshold, survivor_limit); if (PrintTenuringDistribution) { gclog_or_tty->cr(); gclog_or_tty->print_cr("Desired survivor size %ld bytes, new threshold %d (max %d)", size_policy->calculated_survivor_size_in_bytes(), _tenuring_threshold, MaxTenuringThreshold); } if (UsePerfData) { PSGCAdaptivePolicyCounters* counters = heap->gc_policy_counters(); counters->update_tenuring_threshold(_tenuring_threshold); counters->update_survivor_size_counters(); } // Do call at minor collections? // Don't check if the size_policy is ready at this // level. Let the size_policy check that internally. if (UseAdaptiveSizePolicy && UseAdaptiveGenerationSizePolicyAtMinorCollection && ((gc_cause != GCCause::_java_lang_system_gc) || UseAdaptiveSizePolicyWithSystemGC)) { // Calculate optimial free space amounts assert(young_gen->max_size() > young_gen->from_space()->capacity_in_bytes() + young_gen->to_space()->capacity_in_bytes(), "Sizes of space in young gen are out-of-bounds"); size_t max_eden_size = young_gen->max_size() - young_gen->from_space()->capacity_in_bytes() - young_gen->to_space()->capacity_in_bytes(); size_policy->compute_generation_free_space(young_gen->used_in_bytes(), young_gen->eden_space()->used_in_bytes(), old_gen->used_in_bytes(), perm_gen->used_in_bytes(), young_gen->eden_space()->capacity_in_bytes(), old_gen->max_gen_size(), max_eden_size, false /* full gc*/, gc_cause, heap->collector_policy()); } // Resize the young generation at every collection // even if new sizes have not been calculated. This is // to allow resizes that may have been inhibited by the // relative location of the "to" and "from" spaces. // Resizing the old gen at minor collects can cause increases // that don't feed back to the generation sizing policy until // a major collection. Don't resize the old gen here. heap->resize_young_gen(size_policy->calculated_eden_size_in_bytes(), size_policy->calculated_survivor_size_in_bytes()); if (PrintAdaptiveSizePolicy) { gclog_or_tty->print_cr("AdaptiveSizeStop: collection: %d ", heap->total_collections()); } } // Update the structure of the eden. With NUMA-eden CPU hotplugging or offlining can // cause the change of the heap layout. Make sure eden is reshaped if that's the case. // Also update() will case adaptive NUMA chunk resizing. assert(young_gen->eden_space()->is_empty(), "eden space should be empty now"); young_gen->eden_space()->update(); heap->gc_policy_counters()->update_counters(); heap->resize_all_tlabs(); assert(young_gen->to_space()->is_empty(), "to space should be empty now"); } COMPILER2_PRESENT(DerivedPointerTable::update_pointers()); NOT_PRODUCT(reference_processor()->verify_no_references_recorded()); // Re-verify object start arrays if (VerifyObjectStartArray && VerifyAfterGC) { old_gen->verify_object_start_array(); perm_gen->verify_object_start_array(); } // Verify all old -> young cards are now precise if (VerifyRememberedSets) { // Precise verification will give false positives. Until this is fixed, // use imprecise verification. // CardTableExtension::verify_all_young_refs_precise(); CardTableExtension::verify_all_young_refs_imprecise(); } if (TraceGen0Time) accumulated_time()->stop(); if (PrintGC) { if (PrintGCDetails) { // Don't print a GC timestamp here. This is after the GC so // would be confusing. young_gen->print_used_change(young_gen_used_before); } heap->print_heap_change(prev_used); } // Track memory usage and detect low memory MemoryService::track_memory_usage(); heap->update_counters(); } if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) { HandleMark hm; // Discard invalid handles created during verification gclog_or_tty->print(" VerifyAfterGC:"); Universe::verify(false); } if (PrintHeapAtGC) { Universe::print_heap_after_gc(); } if (ZapUnusedHeapArea) { young_gen->eden_space()->check_mangled_unused_area_complete(); young_gen->from_space()->check_mangled_unused_area_complete(); young_gen->to_space()->check_mangled_unused_area_complete(); } scavenge_exit.update(); if (PrintGCTaskTimeStamps) { tty->print_cr("VM-Thread " INT64_FORMAT " " INT64_FORMAT " " INT64_FORMAT, scavenge_entry.ticks(), scavenge_midpoint.ticks(), scavenge_exit.ticks()); gc_task_manager()->print_task_time_stamps(); } #ifdef TRACESPINNING ParallelTaskTerminator::print_termination_counts(); #endif return !promotion_failure_occurred; } // This method iterates over all objects in the young generation, // unforwarding markOops. It then restores any preserved mark oops, // and clears the _preserved_mark_stack. void PSScavenge::clean_up_failed_promotion() { ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity"); assert(promotion_failed(), "Sanity"); PSYoungGen* young_gen = heap->young_gen(); { ResourceMark rm; // Unforward all pointers in the young gen. PSPromotionFailedClosure unforward_closure; young_gen->object_iterate(&unforward_closure); if (PrintGC && Verbose) { gclog_or_tty->print_cr("Restoring %d marks", _preserved_oop_stack.size()); } // Restore any saved marks. while (!_preserved_oop_stack.is_empty()) { oop obj = _preserved_oop_stack.pop(); markOop mark = _preserved_mark_stack.pop(); obj->set_mark(mark); } // Clear the preserved mark and oop stack caches. _preserved_mark_stack.clear(true); _preserved_oop_stack.clear(true); _promotion_failed = false; } // Reset the PromotionFailureALot counters. NOT_PRODUCT(Universe::heap()->reset_promotion_should_fail();) } // This method is called whenever an attempt to promote an object // fails. Some markOops will need preservation, some will not. Note // that the entire eden is traversed after a failed promotion, with // all forwarded headers replaced by the default markOop. This means // it is not neccessary to preserve most markOops. void PSScavenge::oop_promotion_failed(oop obj, markOop obj_mark) { _promotion_failed = true; if (obj_mark->must_be_preserved_for_promotion_failure(obj)) { // Should use per-worker private stakcs hetre rather than // locking a common pair of stacks. ThreadCritical tc; _preserved_oop_stack.push(obj); _preserved_mark_stack.push(obj_mark); } } bool PSScavenge::should_attempt_scavenge() { ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity"); PSGCAdaptivePolicyCounters* counters = heap->gc_policy_counters(); if (UsePerfData) { counters->update_scavenge_skipped(not_skipped); } PSYoungGen* young_gen = heap->young_gen(); PSOldGen* old_gen = heap->old_gen(); if (!ScavengeWithObjectsInToSpace) { // Do not attempt to promote unless to_space is empty if (!young_gen->to_space()->is_empty()) { _consecutive_skipped_scavenges++; if (UsePerfData) { counters->update_scavenge_skipped(to_space_not_empty); } return false; } } // Test to see if the scavenge will likely fail. PSAdaptiveSizePolicy* policy = heap->size_policy(); // A similar test is done in the policy's should_full_GC(). If this is // changed, decide if that test should also be changed. size_t avg_promoted = (size_t) policy->padded_average_promoted_in_bytes(); size_t promotion_estimate = MIN2(avg_promoted, young_gen->used_in_bytes()); bool result = promotion_estimate < old_gen->free_in_bytes(); if (PrintGCDetails && Verbose) { gclog_or_tty->print(result ? " do scavenge: " : " skip scavenge: "); gclog_or_tty->print_cr(" average_promoted " SIZE_FORMAT " padded_average_promoted " SIZE_FORMAT " free in old gen " SIZE_FORMAT, (size_t) policy->average_promoted_in_bytes(), (size_t) policy->padded_average_promoted_in_bytes(), old_gen->free_in_bytes()); if (young_gen->used_in_bytes() < (size_t) policy->padded_average_promoted_in_bytes()) { gclog_or_tty->print_cr(" padded_promoted_average is greater" " than maximum promotion = " SIZE_FORMAT, young_gen->used_in_bytes()); } } if (result) { _consecutive_skipped_scavenges = 0; } else { _consecutive_skipped_scavenges++; if (UsePerfData) { counters->update_scavenge_skipped(promoted_too_large); } } return result; } // Used to add tasks GCTaskManager* const PSScavenge::gc_task_manager() { assert(ParallelScavengeHeap::gc_task_manager() != NULL, "shouldn't return NULL"); return ParallelScavengeHeap::gc_task_manager(); } void PSScavenge::initialize() { // Arguments must have been parsed if (AlwaysTenure) { _tenuring_threshold = 0; } else if (NeverTenure) { _tenuring_threshold = markOopDesc::max_age + 1; } else { // We want to smooth out our startup times for the AdaptiveSizePolicy _tenuring_threshold = (UseAdaptiveSizePolicy) ? InitialTenuringThreshold : MaxTenuringThreshold; } ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity"); PSYoungGen* young_gen = heap->young_gen(); PSOldGen* old_gen = heap->old_gen(); PSPermGen* perm_gen = heap->perm_gen(); // Set boundary between young_gen and old_gen assert(perm_gen->reserved().end() <= old_gen->object_space()->bottom(), "perm above old"); assert(old_gen->reserved().end() <= young_gen->eden_space()->bottom(), "old above young"); _young_generation_boundary = young_gen->eden_space()->bottom(); // Initialize ref handling object for scavenging. MemRegion mr = young_gen->reserved(); _ref_processor = new ReferenceProcessor(mr, // span ParallelRefProcEnabled && (ParallelGCThreads > 1), // mt processing (int) ParallelGCThreads, // mt processing degree true, // mt discovery (int) ParallelGCThreads, // mt discovery degree true, // atomic_discovery NULL, // header provides liveness info false); // next field updates do not need write barrier // Cache the cardtable BarrierSet* bs = Universe::heap()->barrier_set(); assert(bs->kind() == BarrierSet::CardTableModRef, "Wrong barrier set kind"); _card_table = (CardTableExtension*)bs; _counters = new CollectorCounters("PSScavenge", 0); }
ikeji/openjdk7-hotspot
src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp
C++
gpl-2.0
30,816
<?PHP // THIS FILE IS DEPRECATED! PLEASE DO NOT MAKE CHANGES TO IT! // // IT IS USED ONLY FOR UPGRADES FROM BEFORE MOODLE 1.7, ALL // LATER CHANGES SHOULD USE upgrade.php IN THIS DIRECTORY. function wiki_upgrade($oldversion) { /// This function does anything necessary to upgrade /// older versions to match current functionality global $CFG, $db; if ($oldversion < 2004040200) { execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` DROP `allowstudentstowiki`'); } if ($oldversion < 2004040700) { execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` CHANGE `ewikiallowsafehtml` `htmlmode` TINYINT( 4 ) DEFAULT \'0\' NOT NULL'); } if ($oldversion < 2004042100) { execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` ADD `pagename` VARCHAR( 255 ) AFTER `summary`'); execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki_entries` CHANGE `name` `pagename` VARCHAR( 255 ) NOT NULL'); if ($wikis = get_records('wiki')) { foreach ($wikis as $wiki) { if (empty($wiki->pagename)) { set_field('wiki', 'pagename', $wiki->name, 'id', $wiki->id); } } } } if ($oldversion < 2004053100) { execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki` CHANGE `initialcontent` `initialcontent` VARCHAR( 255 ) NOT NULL DEFAULT \'\''); // Remove obsolete 'initialcontent' values. if ($wikis = get_records('wiki')) { foreach ($wikis as $wiki) { if (!empty($wiki->initialcontent)) { set_field('wiki', 'initialcontent', null, 'id', $wiki->id); } } } } if ($oldversion < 2004061300) { execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki`' .' ADD `setpageflags` TINYINT DEFAULT \'1\' NOT NULL AFTER `ewikiacceptbinary`,' .' ADD `strippages` TINYINT DEFAULT \'1\' NOT NULL AFTER `setpageflags`,' .' ADD `removepages` TINYINT DEFAULT \'1\' NOT NULL AFTER `strippages`,' .' ADD `revertchanges` TINYINT DEFAULT \'1\' NOT NULL AFTER `removepages`'); } if ($oldversion < 2004062400) { execute_sql('ALTER TABLE `'.$CFG->prefix.'wiki`' .' ADD `disablecamelcase` TINYINT DEFAULT \'0\' NOT NULL AFTER `ewikiacceptbinary`'); } if ($oldversion < 2004082200) { table_column('wiki_pages', '', 'userid', "integer", "10", "unsigned", "0", "not null", "author"); } if ($oldversion < 2004082303) { // Try to update userid for old records if ($pages = get_records('wiki_pages', 'userid', 0, 'pagename', 'lastmodified,author,pagename,version')) { foreach ($pages as $page) { $name = explode('(', $page->author); $name = trim($name[0]); $name = explode(' ', $name); $firstname = $name[0]; unset($name[0]); $lastname = trim(implode(' ', $name)); if ($user = get_record('user', 'firstname', $firstname, 'lastname', $lastname)) { set_field('wiki_pages', 'userid', $user->id, 'pagename', addslashes($page->pagename), 'version', $page->version); } } } } if ($oldversion < 2004111200) { execute_sql("ALTER TABLE {$CFG->prefix}wiki DROP INDEX course;",false); execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX course;",false); execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX userid;",false); execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX groupid;",false); execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX wikiid;",false); execute_sql("ALTER TABLE {$CFG->prefix}wiki_entries DROP INDEX pagename;",false); modify_database('','ALTER TABLE prefix_wiki ADD INDEX course (course);'); modify_database('','ALTER TABLE prefix_wiki_entries ADD INDEX course (course);'); modify_database('','ALTER TABLE prefix_wiki_entries ADD INDEX userid (userid);'); modify_database('','ALTER TABLE prefix_wiki_entries ADD INDEX groupid (groupid);'); modify_database('','ALTER TABLE prefix_wiki_entries ADD INDEX wikiid (wikiid);'); modify_database('','ALTER TABLE prefix_wiki_entries ADD INDEX pagename (pagename);'); } if ($oldversion < 2005022000) { // recreating the wiki_pages table completelly (missing id, bug 2608) if ($rows = count_records("wiki_pages")) { // we need to use the temp stuff modify_database("","CREATE TABLE `prefix_wiki_pages_tmp` ( `pagename` VARCHAR(160) NOT NULL, `version` INT(10) UNSIGNED NOT NULL DEFAULT 0, `flags` INT(10) UNSIGNED DEFAULT 0, `content` MEDIUMTEXT, `author` VARCHAR(100) DEFAULT 'ewiki', `userid` INT(10) UNSIGNED NOT NULL DEFAULT 0, `created` INT(10) UNSIGNED DEFAULT 0, `lastmodified` INT(10) UNSIGNED DEFAULT 0, `refs` MEDIUMTEXT, `meta` MEDIUMTEXT, `hits` INT(10) UNSIGNED DEFAULT 0, `wiki` INT(10) UNSIGNED NOT NULL);"); execute_sql("INSERT INTO {$CFG->prefix}wiki_pages_tmp (pagename, version, flags, content, author, userid, created, lastmodified, refs, meta, hits, wiki) SELECT pagename, version, flags, content, author, userid, created, lastmodified, refs, meta, hits, wiki FROM {$CFG->prefix}wiki_pages"); $insertafter = true; } execute_sql("DROP TABLE {$CFG->prefix}wiki_pages"); modify_database("","CREATE TABLE `prefix_wiki_pages` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `pagename` VARCHAR(160) NOT NULL, `version` INT(10) UNSIGNED NOT NULL DEFAULT 0, `flags` INT(10) UNSIGNED DEFAULT 0, `content` MEDIUMTEXT, `author` VARCHAR(100) DEFAULT 'ewiki', `userid` INT(10) UNSIGNED NOT NULL DEFAULT 0, `created` INT(10) UNSIGNED DEFAULT 0, `lastmodified` INT(10) UNSIGNED DEFAULT 0, `refs` MEDIUMTEXT, `meta` MEDIUMTEXT, `hits` INT(10) UNSIGNED DEFAULT 0, `wiki` INT(10) UNSIGNED NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `wiki_pages_uk` (`pagename`,`version`,`wiki`)) TYPE=MyISAM COMMENT='Holds the Wiki-Pages';"); if (!empty($insertafter)) { execute_sql("INSERT INTO {$CFG->prefix}wiki_pages (pagename, version, flags, content, author, userid, created, lastmodified, refs, meta, hits, wiki) SELECT pagename, version, flags, content, author, userid, created, lastmodified, refs, meta, hits, wiki FROM {$CFG->prefix}wiki_pages_tmp"); execute_sql("DROP TABLE {$CFG->prefix}wiki_pages_tmp"); } } if ($oldversion < 2006042800) { execute_sql("UPDATE {$CFG->prefix}wiki SET summary='' WHERE summary IS NULL"); table_column('wiki','summary','summary','text','','','','not null'); execute_sql("UPDATE {$CFG->prefix}wiki SET pagename='' WHERE pagename IS NULL"); table_column('wiki','pagename','pagename','varchar','255','','','not null'); execute_sql("UPDATE {$CFG->prefix}wiki SET initialcontent='' WHERE initialcontent IS NULL"); table_column('wiki','initialcontent','initialcontent','varchar','255','','','not null'); } if ($oldversion < 2006092502) { modify_database(""," CREATE TABLE prefix_wiki_locks ( id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, wikiid INT(10) UNSIGNED NOT NULL, pagename VARCHAR(160) NOT NULL DEFAULT '', lockedby INT(10) NOT NULL DEFAULT 0, lockedsince INT(10) NOT NULL DEFAULT 0, lockedseen INT(10) NOT NULL DEFAULT 0, PRIMARY KEY(id), UNIQUE INDEX wiki_locks_uk(wikiid,pagename), INDEX wiki_locks_ix(lockedseen) );"); } ////// DO NOT ADD NEW THINGS HERE!! USE upgrade.php and the lib/ddllib.php functions. return true; } ?>
xavilal/moodle
mod/wiki/db/mysql.php
PHP
gpl-3.0
8,723
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <title>com.qualcomm.robotcore.util</title> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="com.qualcomm.robotcore.util"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/qualcomm/robotcore/hardware/package-summary.html">Prev Package</a></li> <li><a href="../../../../org/firstinspires/ftc/robotcore/external/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/qualcomm/robotcore/util/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;com.qualcomm.robotcore.util</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html" title="class in com.qualcomm.robotcore.util">ElapsedTime</a></td> <td class="colLast"> <div class="block">The <a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html" title="class in com.qualcomm.robotcore.util"><code>ElapsedTime</code></a> class provides a simple handy timer to measure elapsed time intervals.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../com/qualcomm/robotcore/util/Range.html" title="class in com.qualcomm.robotcore.util">Range</a></td> <td class="colLast"> <div class="block">Utility class for performing range operations</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../com/qualcomm/robotcore/util/SerialNumber.html" title="class in com.qualcomm.robotcore.util">SerialNumber</a></td> <td class="colLast"> <div class="block">Instances of <a href="../../../../com/qualcomm/robotcore/util/SerialNumber.html" title="class in com.qualcomm.robotcore.util"><code>SerialNumber</code></a> represent serial numbers of devices on the USB bus.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../com/qualcomm/robotcore/util/TypeConversion.html" title="class in com.qualcomm.robotcore.util">TypeConversion</a></td> <td class="colLast"> <div class="block">Utility class for performing type conversions</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation"> <caption><span>Enum Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Enum</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.Resolution.html" title="enum in com.qualcomm.robotcore.util">ElapsedTime.Resolution</a></td> <td class="colLast"> <div class="block">An indicator of the resolution of a timer.</div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/qualcomm/robotcore/hardware/package-summary.html">Prev Package</a></li> <li><a href="../../../../org/firstinspires/ftc/robotcore/external/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/qualcomm/robotcore/util/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
lasarobotics/FTC5998-2016
ftc_app-master/doc/javadoc/com/qualcomm/robotcore/util/package-summary.html
HTML
gpl-3.0
6,375
/* aes256_dec.c */ /* This file is part of the AVR-Crypto-Lib. Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) 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/>. */ /** * \file aes256_dec.c * \email daniel.otte@rub.de * \author Daniel Otte * \date 2008-12-31 * \license GPLv3 or later * */ #include "aes.h" #include "aes_dec.h" void aes256_dec(void* buffer, aes256_ctx_t* ctx){ aes_decrypt_core(buffer, (aes_genctx_t*)ctx, 14); }
muccc/luftschleuse2
software/avr-crypto-lib/aes/aes256_dec.c
C
gpl-3.0
1,072
<p><b><img alt="" src="<?php echo $CFG->wwwroot; ?>/mod/turnitintool/icon.gif" />&nbsp;Turnitin Uppgifter&nbsp;-&nbsp;Uppgiftsdelar</b></p> <p>Bestämmer huruvida delarna av denna uppgift är namngivna delar eller om den här uppgiften är en portfoliouppgift.</p>
ctestlms/portal
mod/turnitintool/lang/sv_utf8/help/turnitintool/partnames.html
HTML
gpl-3.0
265
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Http * @subpackage UserAgent * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * Zend_Http_UserAgent_Features_Adapter_Interface */ require_once 'Zend/Http/UserAgent/Features/Adapter.php'; /** * Features adapter build with the Tera Wurfl Api * See installation instruction here : http://deviceatlas.com/licences * Download : http://deviceatlas.com/getAPI/php * * @package Zend_Http * @subpackage UserAgent * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Http_UserAgent_Features_Adapter_DeviceAtlas implements Zend_Http_UserAgent_Features_Adapter { /** * Get features from request * * @param array $request $_SERVER variable * @return array */ public static function getFromRequest($request, array $config) { if (!class_exists('Mobi_Mtld_DA_Api')) { if (!isset($config['deviceatlas'])) { require_once 'Zend/Http/UserAgent/Features/Exception.php'; throw new Zend_Http_UserAgent_Features_Exception('"DeviceAtlas" configuration is not defined'); } } $config = $config['deviceatlas']; if (!class_exists('Mobi_Mtld_DA_Api')) { if (empty($config['deviceatlas_lib_dir'])) { require_once 'Zend/Http/UserAgent/Features/Exception.php'; throw new Zend_Http_UserAgent_Features_Exception('The "deviceatlas_lib_dir" parameter is not defined'); } // Include the Device Atlas file from the specified lib_dir require_once ($config['deviceatlas_lib_dir'] . '/Mobi/Mtld/DA/Api.php'); } if (empty($config['deviceatlas_data'])) { require_once 'Zend/Http/UserAgent/Features/Exception.php'; throw new Zend_Http_UserAgent_Features_Exception('The "deviceatlas_data" parameter is not defined'); } //load the device data-tree : e.g. 'json/DeviceAtlas.json $tree = Mobi_Mtld_DA_Api::getTreeFromFile($config['deviceatlas_data']); $properties = Mobi_Mtld_DA_Api::getProperties($tree, $request['http_user_agent']); return $properties; } }
mindvalley/kensei
system/vendor/Zend/Http/UserAgent/Features/Adapter/DeviceAtlas.php
PHP
agpl-3.0
2,924
module RGen module MetamodelBuilder module DataTypes # An enum object is used to describe possible attribute values within a # MetamodelBuilder attribute definition. An attribute defined this way can only # take the values specified when creating the Enum object. # Literal values can only be symbols or true or false. # Optionally a name may be specified for the enum object. # # Examples: # # Enum.new(:name => "AnimalEnum", :literals => [:cat, :dog]) # Enum.new(:literals => [:cat, :dog]) # Enum.new([:cat, :dog]) # class Enum attr_reader :name, :literals # Creates a new named enum type object consisting of the elements passed as arguments. def initialize(params) MetamodelBuilder::ConstantOrderHelper.enumCreated(self) if params.is_a?(Array) @literals = params @name = "anonymous" elsif params.is_a?(Hash) raise StandardError.new("Hash entry :literals is missing") unless params[:literals] @literals = params[:literals] @name = params[:name] || "anonymous" else raise StandardError.new("Pass an Array or a Hash") end end # This method can be used to check if an object can be used as value for # variables having this enum object as type. def validLiteral?(l) literals.include?(l) end def literals_as_strings literals.collect do |l| if l.is_a?(Symbol) if l.to_s =~ /^\d|\W/ ":'"+l.to_s+"'" else ":"+l.to_s end elsif l.is_a?(TrueClass) || l.is_a?(FalseClass) l.to_s else raise StandardError.new("Literal values can only be symbols or true/false") end end end def to_s # :nodoc: name end end # Boolean is a predefined enum object having Ruby's true and false singletons # as possible values. Boolean = Enum.new(:name => "Boolean", :literals => [true, false]) # Long represents a 64-bit Integer # This constant is merely a marker for keeping this information in the Ruby version of the metamodel, # values of this type will always be instances of Integer or Bignum; # Setting it to a string value ensures that it responds to "to_s" which is used in the metamodel generator Long = "Long" end end end
nwops/puppet-retrospec
vendor/pup410/lib/puppet/vendor/rgen/lib/rgen/metamodel_builder/data_types.rb
Ruby
agpl-3.0
2,338
package com.puppycrawl.tools.checkstyle.checks.whitespace.emptylineseparator; public class InputEmptyLineSeparatorPrePreviousLineEmptiness { }
AkshitaKukreja30/checkstyle
src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/emptylineseparator/InputEmptyLineSeparatorPrePreviousLineEmptiness.java
Java
lgpl-2.1
146
package route53 import ( "net/url" "regexp" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol/restxml" ) func init() { initClient = func(c *client.Client) { c.Handlers.Build.PushBack(sanitizeURL) } initRequest = func(r *request.Request) { switch r.Operation.Name { case opChangeResourceRecordSets: r.Handlers.UnmarshalError.Remove(restxml.UnmarshalErrorHandler) r.Handlers.UnmarshalError.PushBack(unmarshalChangeResourceRecordSetsError) } } } var reSanitizeURL = regexp.MustCompile(`\/%2F\w+%2F`) func sanitizeURL(r *request.Request) { r.HTTPRequest.URL.RawPath = reSanitizeURL.ReplaceAllString(r.HTTPRequest.URL.RawPath, "/") // Update Path so that it reflects the cleaned RawPath updated, err := url.Parse(r.HTTPRequest.URL.RawPath) if err != nil { r.Error = awserr.New(request.ErrCodeSerialization, "failed to clean Route53 URL", err) return } // Take the updated path so the requests's URL Path has parity with RawPath. r.HTTPRequest.URL.Path = updated.Path }
kubernetes/kops
vendor/github.com/aws/aws-sdk-go/service/route53/customizations.go
GO
apache-2.0
1,121
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.upgrades; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.rest.ESRestTestCase; public abstract class AbstractRollingTestCase extends ESRestTestCase { protected enum ClusterType { OLD, MIXED, UPGRADED; public static ClusterType parse(String value) { switch (value) { case "old_cluster": return OLD; case "mixed_cluster": return MIXED; case "upgraded_cluster": return UPGRADED; default: throw new AssertionError("unknown cluster type: " + value); } } } protected static final ClusterType CLUSTER_TYPE = ClusterType.parse(System.getProperty("tests.rest.suite")); @Override protected final boolean preserveIndicesUponCompletion() { return true; } @Override protected final boolean preserveReposUponCompletion() { return true; } @Override protected final Settings restClientSettings() { return Settings.builder().put(super.restClientSettings()) // increase the timeout here to 90 seconds to handle long waits for a green // cluster health. the waits for green need to be longer than a minute to // account for delayed shards .put(ESRestTestCase.CLIENT_RETRY_TIMEOUT, "90s") .put(ESRestTestCase.CLIENT_SOCKET_TIMEOUT, "90s") .build(); } }
gfyoung/elasticsearch
qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/AbstractRollingTestCase.java
Java
apache-2.0
2,348
/* * Copyright 2015 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apiman.gateway.engine.es.beans; /** * Used to store a primitive value into the shared state ES document. * * @author eric.wittmann@redhat.com */ public class PrimitiveBean { private String value; private String type; /** * Constructor. */ public PrimitiveBean() { } /** * @return the value */ public String getValue() { return value; } /** * @param value the value to set */ public void setValue(String value) { this.value = value; } /** * @return the type */ public String getType() { return type; } /** * @param type the type to set */ public void setType(String type) { this.type = type; } }
jasonchaffee/apiman
gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/beans/PrimitiveBean.java
Java
apache-2.0
1,370
/* * 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.flink.test.operators; import org.apache.flink.api.common.functions.MapPartitionFunction; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.api.java.io.LocalCollectionOutputFormat; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.test.util.JavaProgramTestBase; import org.apache.flink.test.util.TestBaseUtils; import org.apache.flink.util.Collector; import java.util.ArrayList; import java.util.List; /** Integration tests for {@link MapPartitionFunction}. */ @SuppressWarnings("serial") public class MapPartitionITCase extends JavaProgramTestBase { private static final String IN = "1 1\n2 2\n2 8\n4 4\n4 4\n6 6\n7 7\n8 8\n" + "1 1\n2 2\n2 2\n4 4\n4 4\n6 3\n5 9\n8 8\n1 1\n2 2\n2 2\n3 0\n4 4\n" + "5 9\n7 7\n8 8\n1 1\n9 1\n5 9\n4 4\n4 4\n6 6\n7 7\n8 8\n"; private static final String RESULT = "1 11\n2 12\n4 14\n4 14\n1 11\n2 12\n2 12\n4 14\n4 14\n3 16\n1 11\n2 12\n2 12\n0 13\n4 14\n1 11\n4 14\n4 14\n"; private List<Tuple2<String, String>> input = new ArrayList<>(); private List<Tuple2<String, Integer>> expected = new ArrayList<>(); private List<Tuple2<String, Integer>> result = new ArrayList<>(); @Override protected void preSubmit() throws Exception { // create input for (String s : IN.split("\n")) { String[] fields = s.split(" "); input.add(new Tuple2<String, String>(fields[0], fields[1])); } // create expected for (String s : RESULT.split("\n")) { String[] fields = s.split(" "); expected.add(new Tuple2<String, Integer>(fields[0], Integer.parseInt(fields[1]))); } } @Override protected void postSubmit() { compareResultCollections( expected, result, new TestBaseUtils.TupleComparator<Tuple2<String, Integer>>()); } @Override protected void testProgram() throws Exception { ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); DataSet<Tuple2<String, String>> data = env.fromCollection(input); data.mapPartition(new TestMapPartition()) .output(new LocalCollectionOutputFormat<Tuple2<String, Integer>>(result)); env.execute(); } private static class TestMapPartition implements MapPartitionFunction<Tuple2<String, String>, Tuple2<String, Integer>> { @Override public void mapPartition( Iterable<Tuple2<String, String>> values, Collector<Tuple2<String, Integer>> out) { for (Tuple2<String, String> value : values) { String keyString = value.f0; String valueString = value.f1; int keyInt = Integer.parseInt(keyString); int valueInt = Integer.parseInt(valueString); if (keyInt + valueInt < 10) { out.collect(new Tuple2<String, Integer>(valueString, keyInt + 10)); } } } } }
kl0u/flink
flink-tests/src/test/java/org/apache/flink/test/operators/MapPartitionITCase.java
Java
apache-2.0
3,931
/* * Copyright (C) 2010-2101 Alibaba Group Holding Limited. * * 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. */ package com.alibaba.otter.node.etl.common.task; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import org.I0Itec.zkclient.exception.ZkInterruptedException; import org.apache.commons.lang.ClassUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.lang.math.RandomUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.otter.node.common.config.ConfigClientService; import com.alibaba.otter.node.etl.common.jmx.StageAggregationCollector; import com.alibaba.otter.node.etl.common.pipe.impl.RowDataPipeDelegate; import com.alibaba.otter.shared.arbitrate.ArbitrateEventService; import com.alibaba.otter.shared.arbitrate.model.TerminEventData; import com.alibaba.otter.shared.arbitrate.model.TerminEventData.TerminType; import com.alibaba.otter.shared.common.model.config.pipeline.Pipeline; /** * mainstem,select,extract,transform,load parent Thread. * * @author xiaoqing.zhouxq 2011-8-23 上午10:38:14 */ public abstract class GlobalTask extends Thread { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected volatile boolean running = true; protected Pipeline pipeline; protected Long pipelineId; protected ArbitrateEventService arbitrateEventService; protected RowDataPipeDelegate rowDataPipeDelegate; protected ExecutorService executorService; protected ConfigClientService configClientService; protected StageAggregationCollector stageAggregationCollector; protected Map<Long, Future> pendingFuture; public GlobalTask(Pipeline pipeline){ this(pipeline.getId()); this.pipeline = pipeline; } public GlobalTask(Long pipelineId){ this.pipelineId = pipelineId; setName(createTaskName(pipelineId, ClassUtils.getShortClassName(this.getClass()))); pendingFuture = new HashMap<Long, Future>(); } public void shutdown() { running = false; interrupt(); List<Future> cancelFutures = new ArrayList<Future>(); for (Map.Entry<Long, Future> entry : pendingFuture.entrySet()) { if (!entry.getValue().isDone()) { logger.warn("WARN ## Task future processId[{}] canceled!", entry.getKey()); cancelFutures.add(entry.getValue()); } } for (Future future : cancelFutures) { future.cancel(true); } pendingFuture.clear(); } protected void sendRollbackTermin(long pipelineId, Throwable exception) { sendRollbackTermin(pipelineId, ExceptionUtils.getFullStackTrace(exception)); } protected void sendRollbackTermin(long pipelineId, String message) { TerminEventData errorEventData = new TerminEventData(); errorEventData.setPipelineId(pipelineId); errorEventData.setType(TerminType.ROLLBACK); errorEventData.setCode("setl"); errorEventData.setDesc(message); arbitrateEventService.terminEvent().single(errorEventData); // 每次发送完报警后,sleep一段时间,继续做后面的事 try { Thread.sleep(3000 + RandomUtils.nextInt(3000)); } catch (InterruptedException e) { } } /** * 自动处理数据为null的情况,重新发一遍数据 */ protected void processMissData(long pipelineId, String message) { TerminEventData errorEventData = new TerminEventData(); errorEventData.setPipelineId(pipelineId); errorEventData.setType(TerminType.RESTART); errorEventData.setCode("setl"); errorEventData.setDesc(message); arbitrateEventService.terminEvent().single(errorEventData); } protected String createTaskName(long pipelineId, String taskName) { return new StringBuilder().append("pipelineId = ").append(pipelineId).append(",taskName = ").append(taskName).toString(); } protected boolean isProfiling() { return stageAggregationCollector.isProfiling(); } protected boolean isInterrupt(Throwable e) { if (!running) { return true; } if (e instanceof InterruptedException || e instanceof ZkInterruptedException) { return true; } if (ExceptionUtils.getRootCause(e) instanceof InterruptedException) { return true; } return false; } public Collection<Long> getPendingProcess() { List<Long> result = new ArrayList<Long>(pendingFuture.keySet()); Collections.sort(result); return result; } // ====================== setter / getter ========================= public void setArbitrateEventService(ArbitrateEventService arbitrateEventService) { this.arbitrateEventService = arbitrateEventService; } public void setRowDataPipeDelegate(RowDataPipeDelegate rowDataPipeDelegate) { this.rowDataPipeDelegate = rowDataPipeDelegate; } public void setExecutorService(ExecutorService executorService) { this.executorService = executorService; } public void setConfigClientService(ConfigClientService configClientService) { this.configClientService = configClientService; } public void setStageAggregationCollector(StageAggregationCollector stageAggregationCollector) { this.stageAggregationCollector = stageAggregationCollector; } }
alibaba/otter
node/etl/src/main/java/com/alibaba/otter/node/etl/common/task/GlobalTask.java
Java
apache-2.0
6,295
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #pragma once #include <map> #include <queue> #include <string> #include <thread> #include "port/port.h" #include "rocksdb/status.h" namespace rocksdb { class Env; class Logger; class SstFileManagerImpl; // DeleteScheduler allows the DB to enforce a rate limit on file deletion, // Instead of deleteing files immediately, files are moved to trash_dir // and deleted in a background thread that apply sleep penlty between deletes // if they are happening in a rate faster than rate_bytes_per_sec, // // Rate limiting can be turned off by setting rate_bytes_per_sec = 0, In this // case DeleteScheduler will delete files immediately. class DeleteScheduler { public: DeleteScheduler(Env* env, const std::string& trash_dir, int64_t rate_bytes_per_sec, Logger* info_log, SstFileManagerImpl* sst_file_manager); ~DeleteScheduler(); // Return delete rate limit in bytes per second int64_t GetRateBytesPerSecond() { return rate_bytes_per_sec_; } // Move file to trash directory and schedule it's deletion Status DeleteFile(const std::string& fname); // Wait for all files being deleteing in the background to finish or for // destructor to be called. void WaitForEmptyTrash(); // Return a map containing errors that happened in BackgroundEmptyTrash // file_path => error status std::map<std::string, Status> GetBackgroundErrors(); private: Status MoveToTrash(const std::string& file_path, std::string* path_in_trash); Status DeleteTrashFile(const std::string& path_in_trash, uint64_t* deleted_bytes); void BackgroundEmptyTrash(); Env* env_; // Path to the trash directory std::string trash_dir_; // Maximum number of bytes that should be deleted per second int64_t rate_bytes_per_sec_; // Mutex to protect queue_, pending_files_, bg_errors_, closing_ port::Mutex mu_; // Queue of files in trash that need to be deleted std::queue<std::string> queue_; // Number of files in trash that are waiting to be deleted int32_t pending_files_; // Errors that happened in BackgroundEmptyTrash (file_path => error) std::map<std::string, Status> bg_errors_; // Set to true in ~DeleteScheduler() to force BackgroundEmptyTrash to stop bool closing_; // Condition variable signaled in these conditions // - pending_files_ value change from 0 => 1 // - pending_files_ value change from 1 => 0 // - closing_ value is set to true port::CondVar cv_; // Background thread running BackgroundEmptyTrash std::unique_ptr<std::thread> bg_thread_; // Mutex to protect threads from file name conflicts port::Mutex file_move_mu_; Logger* info_log_; SstFileManagerImpl* sst_file_manager_; static const uint64_t kMicrosInSecond = 1000 * 1000LL; }; } // namespace rocksdb
kostub/dgraph
vendor/github.com/cockroachdb/c-rocksdb/internal/util/delete_scheduler.h
C
apache-2.0
3,104
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package system import ( "github.com/golang/glog" "k8s.io/kubernetes/pkg/util/errors" ) // Validator is the interface for all validators. type Validator interface { // Name is the name of the validator. Name() string // Validate is the validate function. Validate(SysSpec) error } // validators are all the validators. var validators = []Validator{ &OSValidator{}, &KernelValidator{}, &CgroupsValidator{}, &DockerValidator{}, } // Validate uses all validators to validate the system. func Validate() error { var errs []error spec := DefaultSysSpec for _, v := range validators { glog.Infof("Validating %s...", v.Name()) errs = append(errs, v.Validate(spec)) } return errors.NewAggregate(errs) }
rawlingsj/gofabric8
vendor/k8s.io/kubernetes/test/e2e_node/system/validators.go
GO
apache-2.0
1,288
package com.thinkaurelius.titan.hadoop.compat.h1; import com.thinkaurelius.titan.graphdb.configuration.TitanConstants; import com.thinkaurelius.titan.hadoop.config.job.JobClasspathConfigurer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.TaskInputOutputContext; import org.apache.hadoop.mrunit.mapreduce.MapReduceDriver; import com.thinkaurelius.titan.hadoop.HadoopGraph; import com.thinkaurelius.titan.hadoop.compat.HadoopCompat; import com.thinkaurelius.titan.hadoop.compat.HadoopCompiler; public class Hadoop1Compat implements HadoopCompat { static final String CFG_SPECULATIVE_MAPS = "mapred.map.tasks.speculative.execution"; static final String CFG_SPECULATIVE_REDUCES = "mapred.reduce.tasks.speculative.execution"; static final String CFG_JOB_JAR = "mapred.jar"; @Override public HadoopCompiler newCompiler(HadoopGraph g) { return new Hadoop1Compiler(g); } @Override public TaskAttemptContext newTask(Configuration c, TaskAttemptID t) { return new TaskAttemptContext(c, t); } @Override public String getSpeculativeMapConfigKey() { return CFG_SPECULATIVE_MAPS; } @Override public String getSpeculativeReduceConfigKey() { return CFG_SPECULATIVE_REDUCES; } @Override public String getMapredJarConfigKey() { return CFG_JOB_JAR; } @Override public void incrementContextCounter(TaskInputOutputContext context, Enum<?> counter, long incr) { context.getCounter(counter).increment(incr); } @Override public Configuration getContextConfiguration(TaskAttemptContext context) { return context.getConfiguration(); } @Override public long getCounter(MapReduceDriver counters, Enum<?> e) { return counters.getCounters().findCounter(e).getValue(); } @Override public JobClasspathConfigurer newMapredJarConfigurer(String mapredJarPath) { return new MapredJarConfigurer(mapredJarPath); } @Override public JobClasspathConfigurer newDistCacheConfigurer() { return new DistCacheConfigurer("titan-hadoop-core-" + TitanConstants.VERSION + ".jar"); } @Override public Configuration getJobContextConfiguration(JobContext context) { return context.getConfiguration(); } @Override public Configuration newImmutableConfiguration(Configuration base) { return new ImmutableConfiguration(base); } }
evanv/titan
titan-hadoop-parent/titan-hadoop-1/src/main/java/com/thinkaurelius/titan/hadoop/compat/h1/Hadoop1Compat.java
Java
apache-2.0
2,628
const path = require('path'); const fs = require('fs'); const EventEmitter = require('events').EventEmitter; const Shard = require('./Shard'); const Collection = require('../util/Collection'); const Util = require('../util/Util'); /** * This is a utility class that can be used to help you spawn shards of your client. Each shard is completely separate * from the other. The Shard Manager takes a path to a file and spawns it under the specified amount of shards safely. * If you do not select an amount of shards, the manager will automatically decide the best amount. * @extends {EventEmitter} */ class ShardingManager extends EventEmitter { /** * @param {string} file Path to your shard script file * @param {Object} [options] Options for the sharding manager * @param {number|string} [options.totalShards='auto'] Number of shards to spawn, or "auto" * @param {boolean} [options.respawn=true] Whether shards should automatically respawn upon exiting * @param {string[]} [options.shardArgs=[]] Arguments to pass to the shard script when spawning * @param {string} [options.token] Token to use for automatic shard count and passing to shards */ constructor(file, options = {}) { super(); options = Util.mergeDefault({ totalShards: 'auto', respawn: true, shardArgs: [], token: null, }, options); /** * Path to the shard script file * @type {string} */ this.file = file; if (!file) throw new Error('File must be specified.'); if (!path.isAbsolute(file)) this.file = path.resolve(process.cwd(), file); const stats = fs.statSync(this.file); if (!stats.isFile()) throw new Error('File path does not point to a file.'); /** * Amount of shards that this manager is going to spawn * @type {number|string} */ this.totalShards = options.totalShards; if (this.totalShards !== 'auto') { if (typeof this.totalShards !== 'number' || isNaN(this.totalShards)) { throw new TypeError('Amount of shards must be a number.'); } if (this.totalShards < 1) throw new RangeError('Amount of shards must be at least 1.'); if (this.totalShards !== Math.floor(this.totalShards)) { throw new RangeError('Amount of shards must be an integer.'); } } /** * Whether shards should automatically respawn upon exiting * @type {boolean} */ this.respawn = options.respawn; /** * An array of arguments to pass to shards * @type {string[]} */ this.shardArgs = options.shardArgs; /** * Token to use for obtaining the automatic shard count, and passing to shards * @type {?string} */ this.token = options.token ? options.token.replace(/^Bot\s*/i, '') : null; /** * A collection of shards that this manager has spawned * @type {Collection<number, Shard>} */ this.shards = new Collection(); } /** * Spawns a single shard. * @param {number} id The ID of the shard to spawn. **This is usually not necessary** * @returns {Promise<Shard>} */ createShard(id = this.shards.size) { const shard = new Shard(this, id, this.shardArgs); this.shards.set(id, shard); /** * Emitted upon launching a shard. * @event ShardingManager#launch * @param {Shard} shard Shard that was launched */ this.emit('launch', shard); return Promise.resolve(shard); } /** * Spawns multiple shards. * @param {number} [amount=this.totalShards] Number of shards to spawn * @param {number} [delay=7500] How long to wait in between spawning each shard (in milliseconds) * @returns {Promise<Collection<number, Shard>>} */ spawn(amount = this.totalShards, delay = 7500) { if (amount === 'auto') { return Util.fetchRecommendedShards(this.token).then(count => { this.totalShards = count; return this._spawn(count, delay); }); } else { if (typeof amount !== 'number' || isNaN(amount)) throw new TypeError('Amount of shards must be a number.'); if (amount < 1) throw new RangeError('Amount of shards must be at least 1.'); if (amount !== Math.floor(amount)) throw new TypeError('Amount of shards must be an integer.'); return this._spawn(amount, delay); } } /** * Actually spawns shards, unlike that poser above >:( * @param {number} amount Number of shards to spawn * @param {number} delay How long to wait in between spawning each shard (in milliseconds) * @returns {Promise<Collection<number, Shard>>} * @private */ _spawn(amount, delay) { return new Promise(resolve => { if (this.shards.size >= amount) throw new Error(`Already spawned ${this.shards.size} shards.`); this.totalShards = amount; this.createShard(); if (this.shards.size >= this.totalShards) { resolve(this.shards); return; } if (delay <= 0) { while (this.shards.size < this.totalShards) this.createShard(); resolve(this.shards); } else { const interval = setInterval(() => { this.createShard(); if (this.shards.size >= this.totalShards) { clearInterval(interval); resolve(this.shards); } }, delay); } }); } /** * Send a message to all shards. * @param {*} message Message to be sent to the shards * @returns {Promise<Shard[]>} */ broadcast(message) { const promises = []; for (const shard of this.shards.values()) promises.push(shard.send(message)); return Promise.all(promises); } /** * Evaluates a script on all shards, in the context of the Clients. * @param {string} script JavaScript to run on each shard * @returns {Promise<Array>} Results of the script execution */ broadcastEval(script) { const promises = []; for (const shard of this.shards.values()) promises.push(shard.eval(script)); return Promise.all(promises); } /** * Fetches a client property value of each shard. * @param {string} prop Name of the client property to get, using periods for nesting * @returns {Promise<Array>} * @example * manager.fetchClientValues('guilds.size') * .then(results => { * console.log(`${results.reduce((prev, val) => prev + val, 0)} total guilds`); * }) * .catch(console.error); */ fetchClientValues(prop) { if (this.shards.size === 0) return Promise.reject(new Error('No shards have been spawned.')); if (this.shards.size !== this.totalShards) return Promise.reject(new Error('Still spawning shards.')); const promises = []; for (const shard of this.shards.values()) promises.push(shard.fetchClientValue(prop)); return Promise.all(promises); } } module.exports = ShardingManager;
willkiller13/RivoBot
sharding/ShardingManager.js
JavaScript
apache-2.0
6,803
using System; using System.Collections.Generic; using System.Threading.Tasks; using Elasticsearch.Net; namespace Nest { public partial class ElasticClient { /// <inheritdoc /> public ISearchResponse<T> MoreLikeThis<T>(Func<MoreLikeThisDescriptor<T>, MoreLikeThisDescriptor<T>> mltSelector) where T : class { return this.Dispatcher.Dispatch<MoreLikeThisDescriptor<T>, MoreLikeThisRequestParameters, SearchResponse<T>>( mltSelector, (p, d) => { IMoreLikeThisRequest r = d; CopySearchRequestParameters(d); return this.RawDispatch.MltDispatch<SearchResponse<T>>(p, r.Search); } ); } /// <inheritdoc /> public ISearchResponse<T> MoreLikeThis<T>(IMoreLikeThisRequest moreLikeThisRequest) where T : class { return this.Dispatcher.Dispatch<IMoreLikeThisRequest, MoreLikeThisRequestParameters, SearchResponse<T>>( moreLikeThisRequest, (p, d) => { CopySearchRequestParameters(d); return this.RawDispatch.MltDispatch<SearchResponse<T>>(p, d.Search); } ); } /// <inheritdoc /> public Task<ISearchResponse<T>> MoreLikeThisAsync<T>(Func<MoreLikeThisDescriptor<T>, MoreLikeThisDescriptor<T>> mltSelector) where T : class { return this.Dispatcher.DispatchAsync<MoreLikeThisDescriptor<T>, MoreLikeThisRequestParameters, SearchResponse<T>, ISearchResponse<T>>( mltSelector, (p, d) => { IMoreLikeThisRequest r = d; CopySearchRequestParameters(d); return this.RawDispatch.MltDispatchAsync<SearchResponse<T>>(p, r.Search); } ); } /// <inheritdoc /> public Task<ISearchResponse<T>> MoreLikeThisAsync<T>(IMoreLikeThisRequest moreLikeThisRequest) where T : class { return this.Dispatcher.DispatchAsync<IMoreLikeThisRequest, MoreLikeThisRequestParameters, SearchResponse<T>, ISearchResponse<T>>( moreLikeThisRequest, (p, d) => { CopySearchRequestParameters(d); return this.RawDispatch.MltDispatchAsync<SearchResponse<T>>(p, d.Search); } ); } private static void CopySearchRequestParameters(IMoreLikeThisRequest request) { if (request.Search == null) return; request.RequestParameters.CopyQueryStringValuesFrom(request.Search.QueryString); } } }
joehmchan/elasticsearch-net
src/Nest/ElasticClient-MoreLikeThis.cs
C#
apache-2.0
2,228
/* * 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.flink.runtime.executiongraph; /** Base class for exceptions occurring in the {@link ExecutionGraph}. */ public class ExecutionGraphException extends Exception { private static final long serialVersionUID = -8253451032797220657L; public ExecutionGraphException(String message) { super(message); } public ExecutionGraphException(String message, Throwable cause) { super(message, cause); } public ExecutionGraphException(Throwable cause) { super(cause); } }
tillrohrmann/flink
flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/ExecutionGraphException.java
Java
apache-2.0
1,338
/* * 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.flink.runtime.rest.messages.job.metrics; /** Headers for aggregating job metrics. */ public class AggregatedJobMetricsHeaders extends AbstractAggregatedMetricsHeaders<AggregatedJobMetricsParameters> { private static final AggregatedJobMetricsHeaders INSTANCE = new AggregatedJobMetricsHeaders(); private AggregatedJobMetricsHeaders() {} @Override public String getTargetRestEndpointURL() { return "/jobs/metrics"; } @Override public AggregatedJobMetricsParameters getUnresolvedMessageParameters() { return new AggregatedJobMetricsParameters(); } public static AggregatedJobMetricsHeaders getInstance() { return INSTANCE; } @Override public String getDescription() { return "Provides access to aggregated job metrics."; } }
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/job/metrics/AggregatedJobMetricsHeaders.java
Java
apache-2.0
1,648
package featureflag_test import ( "errors" fakeflag "github.com/cloudfoundry/cli/cf/api/feature_flags/fakes" "github.com/cloudfoundry/cli/cf/command_registry" "github.com/cloudfoundry/cli/cf/configuration/core_config" testcmd "github.com/cloudfoundry/cli/testhelpers/commands" testconfig "github.com/cloudfoundry/cli/testhelpers/configuration" . "github.com/cloudfoundry/cli/testhelpers/matchers" testreq "github.com/cloudfoundry/cli/testhelpers/requirements" testterm "github.com/cloudfoundry/cli/testhelpers/terminal" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("enable-feature-flag command", func() { var ( ui *testterm.FakeUI requirementsFactory *testreq.FakeReqFactory configRepo core_config.Repository flagRepo *fakeflag.FakeFeatureFlagRepository deps command_registry.Dependency ) updateCommandDependency := func(pluginCall bool) { deps.Ui = ui deps.RepoLocator = deps.RepoLocator.SetFeatureFlagRepository(flagRepo) deps.Config = configRepo command_registry.Commands.SetCommand(command_registry.Commands.FindCommand("enable-feature-flag").SetDependency(deps, pluginCall)) } BeforeEach(func() { ui = &testterm.FakeUI{} configRepo = testconfig.NewRepositoryWithDefaults() requirementsFactory = &testreq.FakeReqFactory{LoginSuccess: true} flagRepo = &fakeflag.FakeFeatureFlagRepository{} }) runCommand := func(args ...string) bool { return testcmd.RunCliCommand("enable-feature-flag", args, requirementsFactory, updateCommandDependency, false) } Describe("requirements", func() { It("requires the user to be logged in", func() { requirementsFactory.LoginSuccess = false Expect(runCommand()).ToNot(HavePassedRequirements()) }) It("fails with usage if a single feature is not specified", func() { runCommand() Expect(ui.Outputs).To(ContainSubstrings( []string{"Incorrect Usage", "Requires an argument"}, )) }) }) Describe("when logged in", func() { BeforeEach(func() { flagRepo.UpdateReturns(nil) }) It("Sets the flag", func() { runCommand("user_org_creation") flag, set := flagRepo.UpdateArgsForCall(0) Expect(flag).To(Equal("user_org_creation")) Expect(set).To(BeTrue()) Expect(ui.Outputs).To(ContainSubstrings( []string{"Setting status of user_org_creation as my-user..."}, []string{"OK"}, []string{"Feature user_org_creation Enabled."}, )) }) Context("when an error occurs", func() { BeforeEach(func() { flagRepo.UpdateReturns(errors.New("An error occurred.")) }) It("fails with an error", func() { runCommand("i-dont-exist") Expect(ui.Outputs).To(ContainSubstrings( []string{"FAILED"}, []string{"An error occurred."}, )) }) }) }) })
Zouuup/cli
cf/commands/featureflag/enable_feature_flag_test.go
GO
apache-2.0
2,796
/* * Copyright (C) 2010-2101 Alibaba Group Holding Limited. * * 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. */ package com.alibaba.otter.node.etl.conflict.exception; import org.apache.commons.lang.exception.NestableRuntimeException; /** * @author jianghang 2012-4-12 下午02:59:12 * @version 4.0.2 */ public class ConflictException extends NestableRuntimeException { private static final long serialVersionUID = -7288830284122672209L; private String errorCode; private String errorDesc; public ConflictException(String errorCode){ super(errorCode); } public ConflictException(String errorCode, Throwable cause){ super(errorCode, cause); } public ConflictException(String errorCode, String errorDesc){ super(errorCode + ":" + errorDesc); } public ConflictException(String errorCode, String errorDesc, Throwable cause){ super(errorCode + ":" + errorDesc, cause); } public ConflictException(Throwable cause){ super(cause); } public String getErrorCode() { return errorCode; } public String getErrorDesc() { return errorDesc; } @Override public Throwable fillInStackTrace() { return this; } }
wangcan2014/otter
node/etl/src/main/java/com/alibaba/otter/node/etl/conflict/exception/ConflictException.java
Java
apache-2.0
1,785
package org.csstudio.swt.xygraph.util; import org.csstudio.swt.xygraph.figures.XYGraph; import org.eclipse.draw2d.FigureUtilities; import org.eclipse.draw2d.SWTGraphics; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Transform; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; public class SingleSourceHelperImpl extends SingleSourceHelper { @Override protected Cursor createInternalCursor(Display display, ImageData imageData, int width, int height, int style) { return new Cursor(display, imageData, width, height); } @Override protected Image createInternalVerticalTextImage(String text, Font font, RGB color, boolean upToDown) { final Dimension titleSize = FigureUtilities.getTextExtents(text, font); final int w = titleSize.height; final int h = titleSize.width + 1; Image image = new Image(Display.getCurrent(), w, h); final GC gc = new GC(image); final Color titleColor = new Color(Display.getCurrent(), color); RGB transparentRGB = new RGB(240, 240, 240); gc.setBackground(XYGraphMediaFactory.getInstance().getColor( transparentRGB)); gc.fillRectangle(image.getBounds()); gc.setForeground(titleColor); gc.setFont(font); final Transform tr = new Transform(Display.getCurrent()); if (!upToDown) { tr.translate(0, h); tr.rotate(-90); gc.setTransform(tr); } else { tr.translate(w, 0); tr.rotate(90); gc.setTransform(tr); } gc.drawText(text, 0, 0); tr.dispose(); gc.dispose(); final ImageData imageData = image.getImageData(); image.dispose(); titleColor.dispose(); imageData.transparentPixel = imageData.palette.getPixel(transparentRGB); image = new Image(Display.getCurrent(), imageData); return image; } @Override protected Image getInternalXYGraphSnapShot(XYGraph xyGraph) { Rectangle bounds = xyGraph.getBounds(); Image image = new Image(null, bounds.width + 6, bounds.height + 6); GC gc = new GC(image); SWTGraphics graphics = new SWTGraphics(gc); graphics.translate(-bounds.x + 3, -bounds.y + 3); graphics.setForegroundColor(xyGraph.getForegroundColor()); graphics.setBackgroundColor(xyGraph.getBackgroundColor()); xyGraph.paint(graphics); gc.dispose(); return image; } @Override protected String getInternalImageSavePath() { FileDialog dialog = new FileDialog(Display.getDefault().getShells()[0], SWT.SAVE); dialog.setFilterNames(new String[] { "PNG Files", "All Files (*.*)" }); dialog.setFilterExtensions(new String[] { "*.png", "*.*" }); // Windows String path = dialog.open(); return path; } }
jhshin9/scouter
scouter.client/src/org/csstudio/swt/xygraph/util/SingleSourceHelperImpl.java
Java
apache-2.0
3,045
# Using AOT compilation ## What is tfcompile? `tfcompile` is a standalone tool that ahead-of-time (AOT) compiles TensorFlow graphs into executable code. It can reduce total binary size, and also avoid some runtime overheads. A typical use-case of `tfcompile` is to compile an inference graph into executable code for mobile devices. The TensorFlow graph is normally executed by the TensorFlow runtime. This incurs some runtime overhead for execution of each node in the graph. This also leads to a larger total binary size, since the code for the TensorFlow runtime needs to be available, in addition to the graph itself. The executable code produced by `tfcompile` does not use the TensorFlow runtime, and only has dependencies on kernels that are actually used in the computation. The compiler is built on top of the XLA framework. The code bridging TensorFlow to the XLA framework resides under [tensorflow/compiler](https://www.tensorflow.org/code/tensorflow/compiler/), which also includes support for [just-in-time (JIT) compilation](jit.md) of TensorFlow graphs. ## What does tfcompile do? `tfcompile` takes a subgraph, identified by the TensorFlow concepts of feeds and fetches, and generates a function that implements that subgraph. The `feeds` are the input arguments for the function, and the `fetches` are the output arguments for the function. All inputs must be fully specified by the feeds; the resulting pruned subgraph cannot contain Placeholder or Variable nodes. It is common to specify all Placeholders and Variables as feeds, which ensures the resulting subgraph no longer contains these nodes. The generated function is packaged as a `cc_library`, with a header file exporting the function signature, and an object file containing the implementation. The user writes code to invoke the generated function as appropriate. ## Using tfcompile This section details high level steps for generating an executable binary with `tfcompile` from a TensorFlow subgraph. The steps are: * Step 1: Configure the subgraph to compile * Step 2: Use the `tf_library` build macro to compile the subgraph * Step 3: Write code to invoke the subgraph * Step 4: Create the final binary ### Step 1: Configure the subgraph to compile Identify the feeds and fetches that correspond to the input and output arguments for the generated function. Then configure the `feeds` and `fetches` in a [`tensorflow.tf2xla.Config`](https://www.tensorflow.org/code/tensorflow/compiler/tf2xla/tf2xla.proto) proto. ```textproto # Each feed is a positional input argument for the generated function. The order # of each entry matches the order of each input argument. Here “x_hold” and “y_hold” # refer to the names of placeholder nodes defined in the graph. feed { id { node_name: "x_hold" } shape { dim { size: 2 } dim { size: 3 } } } feed { id { node_name: "y_hold" } shape { dim { size: 3 } dim { size: 2 } } } # Each fetch is a positional output argument for the generated function. The order # of each entry matches the order of each output argument. Here “x_y_prod” # refers to the name of a matmul node defined in the graph. fetch { id { node_name: "x_y_prod" } } ``` ### Step 2: Use tf_library build macro to compile the subgraph This step converts the graph into a `cc_library` using the `tf_library` build macro. The `cc_library` consists of an object file containing the code generated from the graph, along with a header file that gives access to the generated code. `tf_library` utilizes `tfcompile` to compile the TensorFlow graph into executable code. ```build load("//tensorflow/compiler/aot:tfcompile.bzl", "tf_library") # Use the tf_library macro to compile your graph into executable code. tf_library( # name is used to generate the following underlying build rules: # <name> : cc_library packaging the generated header and object files # <name>_test : cc_test containing a simple test and benchmark # <name>_benchmark : cc_binary containing a stand-alone benchmark with minimal deps; # can be run on a mobile device name = "test_graph_tfmatmul", # cpp_class specifies the name of the generated C++ class, with namespaces allowed. # The class will be generated in the given namespace(s), or if no namespaces are # given, within the global namespace. cpp_class = "foo::bar::MatMulComp", # graph is the input GraphDef proto, by default expected in binary format. To # use the text format instead, just use the ‘.pbtxt’ suffix. A subgraph will be # created from this input graph, with feeds as inputs and fetches as outputs. # No Placeholder or Variable ops may exist in this subgraph. graph = "test_graph_tfmatmul.pb", # config is the input Config proto, by default expected in binary format. To # use the text format instead, use the ‘.pbtxt’ suffix. This is where the # feeds and fetches were specified above, in the previous step. config = "test_graph_tfmatmul.config.pbtxt", ) ``` > To generate the GraphDef proto (test_graph_tfmatmul.pb) for this example, run > [make_test_graphs.py](https://www.tensorflow.org/code/tensorflow/compiler/aot/tests/make_test_graphs.py) > and specify the output location with the --out_dir flag. Typical graphs contain [`Variables`](https://www.tensorflow.org/guide/variables) representing the weights that are learned via training, but `tfcompile` cannot compile a subgraph that contain `Variables`. The [freeze_graph.py](https://www.tensorflow.org/code/tensorflow/python/tools/freeze_graph.py) tool converts variables into constants, using values stored in a checkpoint file. As a convenience, the `tf_library` macro supports the `freeze_checkpoint` argument, which runs the tool. For more examples see [tensorflow/compiler/aot/tests/BUILD](https://www.tensorflow.org/code/tensorflow/compiler/aot/tests/BUILD). > Constants that show up in the compiled subgraph are compiled directly into the > generated code. To pass the constants into the generated function, rather than > having them compiled-in, simply pass them in as feeds. For details on the `tf_library` build macro, see [tfcompile.bzl](https://www.tensorflow.org/code/tensorflow/compiler/aot/tfcompile.bzl). For details on the underlying `tfcompile` tool, see [tfcompile_main.cc](https://www.tensorflow.org/code/tensorflow/compiler/aot/tfcompile_main.cc). ### Step 3: Write code to invoke the subgraph This step uses the header file (`test_graph_tfmatmul.h`) generated by the `tf_library` build macro in the previous step to invoke the generated code. The header file is located in the `bazel-genfiles` directory corresponding to the build package, and is named based on the name attribute set on the `tf_library` build macro. For example, the header generated for `test_graph_tfmatmul` would be `test_graph_tfmatmul.h`. Below is an abbreviated version of what is generated. The generated file, in `bazel-genfiles`, contains additional useful comments. ```c++ namespace foo { namespace bar { // MatMulComp represents a computation previously specified in a // TensorFlow graph, now compiled into executable code. class MatMulComp { public: // AllocMode controls the buffer allocation mode. enum class AllocMode { ARGS_RESULTS_AND_TEMPS, // Allocate arg, result and temp buffers RESULTS_AND_TEMPS_ONLY, // Only allocate result and temp buffers }; MatMulComp(AllocMode mode = AllocMode::ARGS_RESULTS_AND_TEMPS); ~MatMulComp(); // Runs the computation, with inputs read from arg buffers, and outputs // written to result buffers. Returns true on success and false on failure. bool Run(); // Arg methods for managing input buffers. Buffers are in row-major order. // There is a set of methods for each positional argument. void** args(); void set_arg0_data(float* data); float* arg0_data(); float& arg0(size_t dim0, size_t dim1); void set_arg1_data(float* data); float* arg1_data(); float& arg1(size_t dim0, size_t dim1); // Result methods for managing output buffers. Buffers are in row-major order. // Must only be called after a successful Run call. There is a set of methods // for each positional result. void** results(); float* result0_data(); float& result0(size_t dim0, size_t dim1); }; } // end namespace bar } // end namespace foo ``` The generated C++ class is called `MatMulComp` in the `foo::bar` namespace, because that was the `cpp_class` specified in the `tf_library` macro. All generated classes have a similar API, with the only difference being the methods to handle arg and result buffers. Those methods differ based on the number and types of the buffers, which were specified by the `feed` and `fetch` arguments to the `tf_library` macro. There are three types of buffers managed within the generated class: `args` representing the inputs, `results` representing the outputs, and `temps` representing temporary buffers used internally to perform the computation. By default, each instance of the generated class allocates and manages all of these buffers for you. The `AllocMode` constructor argument may be used to change this behavior. All buffers are aligned to 64-byte boundaries. The generated C++ class is just a wrapper around the low-level code generated by XLA. Example of invoking the generated function based on [`tfcompile_test.cc`](https://www.tensorflow.org/code/tensorflow/compiler/aot/tests/tfcompile_test.cc): ```c++ #define EIGEN_USE_THREADS #define EIGEN_USE_CUSTOM_THREAD_POOL #include <iostream> #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/compiler/aot/tests/test_graph_tfmatmul.h" // generated int main(int argc, char** argv) { Eigen::ThreadPool tp(2); // Size the thread pool as appropriate. Eigen::ThreadPoolDevice device(&tp, tp.NumThreads()); foo::bar::MatMulComp matmul; matmul.set_thread_pool(&device); // Set up args and run the computation. const float args[12] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::copy(args + 0, args + 6, matmul.arg0_data()); std::copy(args + 6, args + 12, matmul.arg1_data()); matmul.Run(); // Check result if (matmul.result0(0, 0) == 58) { std::cout << "Success" << std::endl; } else { std::cout << "Failed. Expected value 58 at 0,0. Got:" << matmul.result0(0, 0) << std::endl; } return 0; } ``` ### Step 4: Create the final binary This step combines the library generated by `tf_library` in step 2 and the code written in step 3 to create a final binary. Below is an example `bazel` BUILD file. ```build # Example of linking your binary # Also see //tensorflow/compiler/aot/tests/BUILD load("//tensorflow/compiler/aot:tfcompile.bzl", "tf_library") # The same tf_library call from step 2 above. tf_library( name = "test_graph_tfmatmul", ... ) # The executable code generated by tf_library can then be linked into your code. cc_binary( name = "my_binary", srcs = [ "my_code.cc", # include test_graph_tfmatmul.h to access the generated header ], deps = [ ":test_graph_tfmatmul", # link in the generated object file "//third_party/eigen3", ], linkopts = [ "-lpthread", ] ) ```
ghchinoy/tensorflow
tensorflow/compiler/xla/g3doc/tfcompile.md
Markdown
apache-2.0
11,297
<?php if (!defined('APPLICATION')) exit(); $Alt = FALSE; $Session = Gdn::Session(); $EditUser = $Session->CheckPermission('Garden.Users.Edit'); $DeleteUser = $Session->CheckPermission('Garden.Users.Delete'); foreach ($this->UserData->Result() as $User) { $Alt = $Alt ? FALSE : TRUE; ?> <tr id="<?php echo "UserID_{$User->UserID}"; ?>"<?php echo $Alt ? ' class="Alt"' : ''; ?>> <!-- <td class="CheckboxCell"><input type="checkbox" name="LogID[]" value="<?php echo $User->UserID; ?>" /></td>--> <td><strong><?php echo UserAnchor($User); ?></strong></td> <td class="Alt"><?php echo Gdn_Format::Email($User->Email); ?></td> <td style="max-width: 200px;"> <?php $Roles = GetValue('Roles', $User, array()); $RolesString = ''; if ($User->Banned && !in_array('Banned', $Roles)) { $RolesString = T('Banned'); } if ($User->Admin > 1) { $RolesString = ConcatSep(', ', $RolesString, T('System')); } foreach ($Roles as $RoleID => $RoleName) { $Query = http_build_query(array('Keywords' => $RoleName)); $RolesString = ConcatSep(', ', $RolesString, '<a href="'.Url('/user/browse?'.$Query).'">'.htmlspecialchars($RoleName).'</a>'); } echo $RolesString; ?> </td> <td class="Alt"><?php echo Gdn_Format::Date($User->DateFirstVisit, 'html'); ?></td> <td><?php echo Gdn_Format::Date($User->DateLastActive, 'html'); ?></td> <td><?php echo htmlspecialchars($User->LastIPAddress); ?></td> <?php $this->EventArgs['User'] = $User; $this->FireEvent('UserCell'); ?> <?php if ($EditUser || $DeleteUser) { ?> <td><?php if ($EditUser) echo Anchor(T('Edit'), '/user/edit/'.$User->UserID, 'Popup SmallButton'); if ($DeleteUser && $User->UserID != $Session->User->UserID) echo Anchor(T('Delete'), '/user/delete/'.$User->UserID, 'SmallButton'); $this->EventArguments['User'] = $User; $this->FireEvent('UserListOptions'); ?></td> <?php } ?> </tr> <?php }
ppazos/cabolabs-web-old
forum/applications/dashboard/views/user/users.php
PHP
apache-2.0
2,182
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1alpha1 // This file contains a collection of methods that can be used from go-restful to // generate Swagger API documentation for its models. Please read this PR for more // information on the implementation: https://github.com/emicklei/go-restful/pull/215 // // TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if // they are on one line! For multiple line or blocks that you want to ignore use ---. // Any context after a --- is ignored. // // Those methods can be generated by using hack/update-generated-swagger-docs.sh // AUTO-GENERATED FUNCTIONS START HERE var map_CertificateSigningRequest = map[string]string{ "": "Describes a certificate signing request", "spec": "The certificate request itself and any additional information.", "status": "Derived information about the request.", } func (CertificateSigningRequest) SwaggerDoc() map[string]string { return map_CertificateSigningRequest } var map_CertificateSigningRequestCondition = map[string]string{ "type": "request approval state, currently Approved or Denied.", "reason": "brief reason for the request state", "message": "human readable message with details about the request state", "lastUpdateTime": "timestamp for the last update to this condition", } func (CertificateSigningRequestCondition) SwaggerDoc() map[string]string { return map_CertificateSigningRequestCondition } var map_CertificateSigningRequestSpec = map[string]string{ "": "This information is immutable after the request is created. Only the Request and ExtraInfo fields can be set on creation, other fields are derived by Kubernetes and cannot be modified by users.", "request": "Base64-encoded PKCS#10 CSR data", "usages": "allowedUsages specifies a set of usage contexts the key will be valid for. See: https://tools.ietf.org/html/rfc5280#section-4.2.1.3\n https://tools.ietf.org/html/rfc5280#section-4.2.1.12", "username": "Information about the requesting user (if relevant) See user.Info interface for details", } func (CertificateSigningRequestSpec) SwaggerDoc() map[string]string { return map_CertificateSigningRequestSpec } var map_CertificateSigningRequestStatus = map[string]string{ "conditions": "Conditions applied to the request, such as approval or denial.", "certificate": "If request was approved, the controller will place the issued certificate here.", } func (CertificateSigningRequestStatus) SwaggerDoc() map[string]string { return map_CertificateSigningRequestStatus } // AUTO-GENERATED FUNCTIONS END HERE
thomasschickinger/kubernetes
staging/src/k8s.io/client-go/pkg/apis/certificates/v1alpha1/types_swagger_doc_generated.go
GO
apache-2.0
3,155
Namespace Microsoft.CodeAnalysis.VisualBasic Friend Partial Module ErrorFacts Public Function IsWarning(code as ERRID) As Boolean Select Case code Case ERRID.WRN_BadSwitch, ERRID.WRN_NoConfigInResponseFile, ERRID.WRN_IgnoreModuleManifest, ERRID.WRN_BadUILang, ERRID.WRN_UseOfObsoleteSymbol2, ERRID.WRN_InvalidOverrideDueToTupleNames2, ERRID.WRN_MustOverloadBase4, ERRID.WRN_OverrideType5, ERRID.WRN_MustOverride2, ERRID.WRN_DefaultnessShadowed4, ERRID.WRN_UseOfObsoleteSymbolNoMessage1, ERRID.WRN_AssemblyGeneration0, ERRID.WRN_AssemblyGeneration1, ERRID.WRN_ComClassNoMembers1, ERRID.WRN_SynthMemberShadowsMember5, ERRID.WRN_MemberShadowsSynthMember6, ERRID.WRN_SynthMemberShadowsSynthMember7, ERRID.WRN_UseOfObsoletePropertyAccessor3, ERRID.WRN_UseOfObsoletePropertyAccessor2, ERRID.WRN_FieldNotCLSCompliant1, ERRID.WRN_BaseClassNotCLSCompliant2, ERRID.WRN_ProcTypeNotCLSCompliant1, ERRID.WRN_ParamNotCLSCompliant1, ERRID.WRN_InheritedInterfaceNotCLSCompliant2, ERRID.WRN_CLSMemberInNonCLSType3, ERRID.WRN_NameNotCLSCompliant1, ERRID.WRN_EnumUnderlyingTypeNotCLS1, ERRID.WRN_NonCLSMemberInCLSInterface1, ERRID.WRN_NonCLSMustOverrideInCLSType1, ERRID.WRN_ArrayOverloadsNonCLS2, ERRID.WRN_RootNamespaceNotCLSCompliant1, ERRID.WRN_RootNamespaceNotCLSCompliant2, ERRID.WRN_GenericConstraintNotCLSCompliant1, ERRID.WRN_TypeNotCLSCompliant1, ERRID.WRN_OptionalValueNotCLSCompliant1, ERRID.WRN_CLSAttrInvalidOnGetSet, ERRID.WRN_TypeConflictButMerged6, ERRID.WRN_ShadowingGenericParamWithParam1, ERRID.WRN_CannotFindStandardLibrary1, ERRID.WRN_EventDelegateTypeNotCLSCompliant2, ERRID.WRN_DebuggerHiddenIgnoredOnProperties, ERRID.WRN_SelectCaseInvalidRange, ERRID.WRN_CLSEventMethodInNonCLSType3, ERRID.WRN_ExpectedInitComponentCall2, ERRID.WRN_NamespaceCaseMismatch3, ERRID.WRN_UndefinedOrEmptyNamespaceOrClass1, ERRID.WRN_UndefinedOrEmptyProjectNamespaceOrClass1, ERRID.WRN_IndirectRefToLinkedAssembly2, ERRID.WRN_DelaySignButNoKey, ERRID.WRN_UnimplementedCommandLineSwitch, ERRID.WRN_NoNonObsoleteConstructorOnBase3, ERRID.WRN_NoNonObsoleteConstructorOnBase4, ERRID.WRN_RequiredNonObsoleteNewCall3, ERRID.WRN_RequiredNonObsoleteNewCall4, ERRID.WRN_MissingAsClauseinOperator, ERRID.WRN_ConstraintsFailedForInferredArgs2, ERRID.WRN_ConditionalNotValidOnFunction, ERRID.WRN_UseSwitchInsteadOfAttribute, ERRID.WRN_TupleLiteralNameMismatch, ERRID.WRN_ReferencedAssemblyDoesNotHaveStrongName, ERRID.WRN_RecursiveAddHandlerCall, ERRID.WRN_ImplicitConversionCopyBack, ERRID.WRN_MustShadowOnMultipleInheritance2, ERRID.WRN_RecursiveOperatorCall, ERRID.WRN_ImplicitConversionSubst1, ERRID.WRN_LateBindingResolution, ERRID.WRN_ObjectMath1, ERRID.WRN_ObjectMath2, ERRID.WRN_ObjectAssumedVar1, ERRID.WRN_ObjectAssumed1, ERRID.WRN_ObjectAssumedProperty1, ERRID.WRN_UnusedLocal, ERRID.WRN_SharedMemberThroughInstance, ERRID.WRN_RecursivePropertyCall, ERRID.WRN_OverlappingCatch, ERRID.WRN_DefAsgUseNullRefByRef, ERRID.WRN_DuplicateCatch, ERRID.WRN_ObjectMath1Not, ERRID.WRN_BadChecksumValExtChecksum, ERRID.WRN_MultipleDeclFileExtChecksum, ERRID.WRN_BadGUIDFormatExtChecksum, ERRID.WRN_ObjectMathSelectCase, ERRID.WRN_EqualToLiteralNothing, ERRID.WRN_NotEqualToLiteralNothing, ERRID.WRN_UnusedLocalConst, ERRID.WRN_ComClassInterfaceShadows5, ERRID.WRN_ComClassPropertySetObject1, ERRID.WRN_DefAsgUseNullRef, ERRID.WRN_DefAsgNoRetValFuncRef1, ERRID.WRN_DefAsgNoRetValOpRef1, ERRID.WRN_DefAsgNoRetValPropRef1, ERRID.WRN_DefAsgUseNullRefByRefStr, ERRID.WRN_DefAsgUseNullRefStr, ERRID.WRN_StaticLocalNoInference, ERRID.WRN_InvalidAssemblyName, ERRID.WRN_XMLDocBadXMLLine, ERRID.WRN_XMLDocMoreThanOneCommentBlock, ERRID.WRN_XMLDocNotFirstOnLine, ERRID.WRN_XMLDocInsideMethod, ERRID.WRN_XMLDocParseError1, ERRID.WRN_XMLDocDuplicateXMLNode1, ERRID.WRN_XMLDocIllegalTagOnElement2, ERRID.WRN_XMLDocBadParamTag2, ERRID.WRN_XMLDocParamTagWithoutName, ERRID.WRN_XMLDocCrefAttributeNotFound1, ERRID.WRN_XMLMissingFileOrPathAttribute1, ERRID.WRN_XMLCannotWriteToXMLDocFile2, ERRID.WRN_XMLDocWithoutLanguageElement, ERRID.WRN_XMLDocReturnsOnWriteOnlyProperty, ERRID.WRN_XMLDocOnAPartialType, ERRID.WRN_XMLDocReturnsOnADeclareSub, ERRID.WRN_XMLDocStartTagWithNoEndTag, ERRID.WRN_XMLDocBadGenericParamTag2, ERRID.WRN_XMLDocGenericParamTagWithoutName, ERRID.WRN_XMLDocExceptionTagWithoutCRef, ERRID.WRN_XMLDocInvalidXMLFragment, ERRID.WRN_XMLDocBadFormedXML, ERRID.WRN_InterfaceConversion2, ERRID.WRN_LiftControlVariableLambda, ERRID.WRN_LambdaPassedToRemoveHandler, ERRID.WRN_LiftControlVariableQuery, ERRID.WRN_RelDelegatePassedToRemoveHandler, ERRID.WRN_AmbiguousCastConversion2, ERRID.WRN_VarianceDeclarationAmbiguous3, ERRID.WRN_ArrayInitNoTypeObjectAssumed, ERRID.WRN_TypeInferenceAssumed3, ERRID.WRN_VarianceConversionFailedOut6, ERRID.WRN_VarianceConversionFailedIn6, ERRID.WRN_VarianceIEnumerableSuggestion3, ERRID.WRN_VarianceConversionFailedTryOut4, ERRID.WRN_VarianceConversionFailedTryIn4, ERRID.WRN_IfNoTypeObjectAssumed, ERRID.WRN_IfTooManyTypesObjectAssumed, ERRID.WRN_ArrayInitTooManyTypesObjectAssumed, ERRID.WRN_LambdaNoTypeObjectAssumed, ERRID.WRN_LambdaTooManyTypesObjectAssumed, ERRID.WRN_MissingAsClauseinVarDecl, ERRID.WRN_MissingAsClauseinFunction, ERRID.WRN_MissingAsClauseinProperty, ERRID.WRN_ObsoleteIdentityDirectCastForValueType, ERRID.WRN_ImplicitConversion2, ERRID.WRN_MutableStructureInUsing, ERRID.WRN_MutableGenericStructureInUsing, ERRID.WRN_DefAsgNoRetValFuncVal1, ERRID.WRN_DefAsgNoRetValOpVal1, ERRID.WRN_DefAsgNoRetValPropVal1, ERRID.WRN_AsyncLacksAwaits, ERRID.WRN_AsyncSubCouldBeFunction, ERRID.WRN_UnobservedAwaitableExpression, ERRID.WRN_UnobservedAwaitableDelegate, ERRID.WRN_PrefixAndXmlnsLocalName, ERRID.WRN_UseValueForXmlExpression3, ERRID.WRN_ReturnTypeAttributeOnWriteOnlyProperty, ERRID.WRN_InvalidVersionFormat, ERRID.WRN_MainIgnored, ERRID.WRN_EmptyPrefixAndXmlnsLocalName, ERRID.WRN_DefAsgNoRetValWinRtEventVal1, ERRID.WRN_AssemblyAttributeFromModuleIsOverridden, ERRID.WRN_RefCultureMismatch, ERRID.WRN_ConflictingMachineAssembly, ERRID.WRN_PdbLocalNameTooLong, ERRID.WRN_PdbUsingNameTooLong, ERRID.WRN_XMLDocCrefToTypeParameter, ERRID.WRN_AnalyzerCannotBeCreated, ERRID.WRN_NoAnalyzerInAssembly, ERRID.WRN_UnableToLoadAnalyzer, ERRID.WRN_AttributeIgnoredWhenPublicSigning, ERRID.WRN_Experimental Return True Case Else Return False End Select End Function Public Function IsFatal(code as ERRID) As Boolean Select Case code Case ERRID.FTL_InvalidInputFileName Return True Case Else Return False End Select End Function Public Function IsInfo(code as ERRID) As Boolean Select Case code Case ERRID.INF_UnableToLoadSomeTypesInAnalyzer Return True Case Else Return False End Select End Function Public Function IsHidden(code as ERRID) As Boolean Select Case code Case ERRID.HDN_UnusedImportClause, ERRID.HDN_UnusedImportStatement Return True Case Else Return False End Select End Function End Module End Namespace
VSadov/roslyn
src/Compilers/VisualBasic/Portable/Generated/ErrorFacts.Generated.vb
Visual Basic
apache-2.0
10,820
<?php namespace yiiunit\extensions\authclient\oauth\signature; use yii\authclient\signature\RsaSha1; use yiiunit\extensions\authclient\TestCase; class RsaSha1Test extends TestCase { /** * Returns test public certificate string. * @return string public certificate string. */ protected function getTestPublicCertificate() { return '-----BEGIN CERTIFICATE----- MIIDJDCCAo2gAwIBAgIJALCFAl3nj1ibMA0GCSqGSIb3DQEBBQUAMIGqMQswCQYD VQQGEwJOTDESMBAGA1UECAwJQW1zdGVyZGFtMRIwEAYDVQQHDAlBbXN0ZXJkYW0x DzANBgNVBAoMBlBpbVRpbTEPMA0GA1UECwwGUGltVGltMSswKQYDVQQDDCJkZXY1 My5xdWFydHNvZnQuY29tL3BrbGltb3YvcGltdGltMSQwIgYJKoZIhvcNAQkBFhVw a2xpbW92QHF1YXJ0c29mdC5jb20wHhcNMTIxMTA2MTQxNjUzWhcNMTMxMTA2MTQx NjUzWjCBqjELMAkGA1UEBhMCTkwxEjAQBgNVBAgMCUFtc3RlcmRhbTESMBAGA1UE BwwJQW1zdGVyZGFtMQ8wDQYDVQQKDAZQaW1UaW0xDzANBgNVBAsMBlBpbVRpbTEr MCkGA1UEAwwiZGV2NTMucXVhcnRzb2Z0LmNvbS9wa2xpbW92L3BpbXRpbTEkMCIG CSqGSIb3DQEJARYVcGtsaW1vdkBxdWFydHNvZnQuY29tMIGfMA0GCSqGSIb3DQEB AQUAA4GNADCBiQKBgQDE0d63YwpBLxzxQAW887JALcGruAHkHu7Ui1oc7bCIMy+u d6rPgNmbFLw3GoGzQ8xhMmksZHsS07IfWRTDeisPHAqfgcApOZbyMyZUAL6+1ko4 xAIPnQSia7l8M4nWgtgqifDCbFKAoPXuWSrYDOFtgSkBLH5xYyFPRc04nnHpoQID AQABo1AwTjAdBgNVHQ4EFgQUE2oxXYDFRNtgvn8tyXldepRFWzYwHwYDVR0jBBgw FoAUE2oxXYDFRNtgvn8tyXldepRFWzYwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0B AQUFAAOBgQB1/S46dWBECaOs4byCysFhzXw8qx8znJkSZcIdDilmg1kkfusXKi2S DiiFw5gDrc6Qp6WtPmVhxHUWl6O5bOG8lG0Dcppeed9454CGvBShmYdwC6vk0s7/ gVdK2V4fYsUeT6u49ONshvJ/8xhHz2gGXeLWaqHwtK3Dl3S6TIDuoQ== -----END CERTIFICATE-----'; } /** * Returns test private certificate string. * @return string private certificate string. */ protected function getTestPrivateCertificate() { return '-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQDE0d63YwpBLxzxQAW887JALcGruAHkHu7Ui1oc7bCIMy+ud6rP gNmbFLw3GoGzQ8xhMmksZHsS07IfWRTDeisPHAqfgcApOZbyMyZUAL6+1ko4xAIP nQSia7l8M4nWgtgqifDCbFKAoPXuWSrYDOFtgSkBLH5xYyFPRc04nnHpoQIDAQAB AoGAPm1e2gYE86Xw5ShsaYFWcXrR6hiEKQoSsMG+hFxz2M97eTglqolw+/p4tHWo 2+ZORioKJ/V6//67iavkpRfz3dloUlNE9ZzlvqvPjHePt3BI22GI8D84dcqnxWW5 4okEAfDfXk2B4UNOpVNU5FZjg4XvBEbbhRVrsBWAPMduDX0CQQDtFgLLLWr50F3z lGuFy68Y1d01sZsyf7xUPaLcDWbrnVMIjZIs60BbLg9PZ6sYcwV2RwL/WaJU0Ap/ KKjHW51zAkEA1IWBicQtt6yGaUqydq+ifX8/odFjIrlZklwckLl65cImyxqDYMnA m+QdbZznSH96BHjduhJAEAtfYx5CVMrXmwJAHKiWedzpm3z2fmUoginW5pejf8QS UI5kQ4KX1yW/lSeVS+lhDBD73Im6zAxqADCXLm7zC87X8oybWDef/0kxxQJAebRX AalKMSRo+QVg/F0Kpenoa+f4aNtSc2GyriK6QbeU9b0iPZxsZBoXzD0NqlPucX8y IyvuagHJR379p4dePwJBAMCkYSATGdhYbeDfySWUro5K0QAvBNj8FuNJQ4rqUxz8 8b+OXIyd5WlmuDRTDGJBTxAYeaioTuMCFWaZm4jG0I4= -----END RSA PRIVATE KEY-----'; } // Tests : public function testGenerateSignature() { $signatureMethod = new RsaSha1(); $signatureMethod->setPrivateCertificate($this->getTestPrivateCertificate()); $signatureMethod->setPublicCertificate($this->getTestPublicCertificate()); $baseString = 'test_base_string'; $key = 'test_key'; $signature = $signatureMethod->generateSignature($baseString, $key); $this->assertNotEmpty($signature, 'Unable to generate signature!'); } /** * @depends testGenerateSignature */ public function testVerify() { $signatureMethod = new RsaSha1(); $signatureMethod->setPrivateCertificate($this->getTestPrivateCertificate()); $signatureMethod->setPublicCertificate($this->getTestPublicCertificate()); $baseString = 'test_base_string'; $key = 'test_key'; $signature = 'unsigned'; $this->assertFalse($signatureMethod->verify($signature, $baseString, $key), 'Unsigned signature is valid!'); $generatedSignature = $signatureMethod->generateSignature($baseString, $key); $this->assertTrue($signatureMethod->verify($generatedSignature, $baseString, $key), 'Generated signature is invalid!'); } public function testInitPrivateCertificate() { $signatureMethod = new RsaSha1(); $certificateFileName = __FILE__; $signatureMethod->privateCertificateFile = $certificateFileName; $this->assertEquals(file_get_contents($certificateFileName), $signatureMethod->getPrivateCertificate(), 'Unable to fetch private certificate from file!'); } public function testInitPublicCertificate() { $signatureMethod = new RsaSha1(); $certificateFileName = __FILE__; $signatureMethod->publicCertificateFile = $certificateFileName; $this->assertEquals(file_get_contents($certificateFileName), $signatureMethod->getPublicCertificate(), 'Unable to fetch public certificate from file!'); } }
ropik/yii2
tests/unit/extensions/authclient/signature/RsaSha1Test.php
PHP
bsd-3-clause
4,625
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <html> <head> <title>The Epytext Markup Language</title> <link rel="stylesheet" href="epydoc.css" type="text/css"/> </head> <!-- $Id: epytext.html 1211 2006-04-10 19:38:37Z edloper $ --> <body> <div class="body"> <h1>The Epytext Markup Language</h1> <a name="overview"/> <h2> 1. Overview </h2> <p> Epytext is a lightweight markup language for Python docstrings. The epytext markup language is used by epydoc to parse docstrings and create structured API documentation. Epytext markup is broken up into the following categories: </p> <ul> <li> <b><i>Block Structure</i></b> divides the docstring into nested blocks of text, such as paragraphs and lists. <ul> <li> <b><i>Basic Blocks</i></b> are the basic unit of block structure. </li> <li> <b><i>Hierarchical blocks</i></b> represent the nesting structure of the docstring. </li> </ul> </li> <li> <b><i>Inline Markup</i></b> marks regions of text within a basic block with properties, such as italics and hyperlinks. </li> </ul> <!-- =========== BLOCK STRUCTURE ============= --> <a name="block_structure"/> <h2> 2. Block Structure </h2> <p> Block structure is encoded using indentation, blank lines, and a handful of special character sequences. </p> <ul> <li> Indentation is used to encode the nesting structure of hierarchical blocks. The indentation of a line is defined as the number of leading spaces on that line; and the indentation of a block is typically the indentation of its first line. </li> <li> Blank lines are used to separate blocks. A blank line is a line that only contains whitespace. </li> <li> Special character sequences are used to mark the beginnings of some blocks. For example, "<code>-</code>" is used as a bullet for unordered list items, and "<code>&gt;&gt;&gt;</code>" is used to mark doctest blocks. </li> </ul> <p> The following sections describe how to use each type of block structure. </p> <a name="paragraph"/> <h3> 2.1. Paragraphs </h3> <p> A paragraph is the simplest type of basic block. It consists of one or more lines of text. Paragraphs must be left justified (i.e., every line must have the same indentation). The following example illustrates how paragraphs can be used: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" This is a paragraph. Paragraphs can span multiple lines, and can contain I{inline markup}. This is another paragraph. Paragraphs are separated by blank lines. """</code> <i>[...]</i> </pre> </td><td> <p> This is a paragraph. Paragraphs can span multiple lines, and contain <i>inline markup</i>. </p> <p> This is another paragraph. Paragraphs are separated from each other by blank lines. </p> </td></tr> </table> <a name="list"/> <h3> 2.2. Lists </h3> <p> Epytext supports both ordered and unordered lists. A list consists of one or more consecutive <i>list items</i> of the same type (ordered or unordered), with the same indentation. Each list item is marked by a <i>bullet</i>. The bullet for unordered list items is a single dash character ("<code>-</code>"). Bullets for ordered list items consist of a series of numbers followed by periods, such as "<code>12.</code>" or "<code>1.2.8.</code>". </p> <p> List items typically consist of a bullet followed by a space and a single paragraph. The paragraph may be indented more than the list item's bullet; often, the paragraph is intended two or three characters, so that its left margin lines up with the right side of the bullet. The following example illustrates a simple ordered list. </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" 1. This is an ordered list item. 2. This is a another ordered list item. 3. This is a third list item. Note that the paragraph may be indented more than the bullet. """</code> <i>[...]</i> </pre> </td><td> <ol> <li> This is an ordered list item. </li> <li> This is another ordered list item. </li> <li> This is a third list item. Note that the paragraph may be indented more than the bullet.</li> </td></tr> </table> <p> List items can contain more than one paragraph; and they can also contain sublists, literal blocks, and doctest blocks. All of the blocks contained by a list item must all have equal indentation, and that indentation must be greater than or equal to the indentation of the list item's bullet. If the first contained block is a paragraph, it may appear on the same line as the bullet, separated from the bullet by one or more spaces, as shown in the previous example. All other block types must follow on separate lines. </p> <p> Every list must be separated from surrounding blocks by indentation: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" This is a paragraph. 1. This is a list item. 2. This a second list item. - This is a sublist """</code> <i>[...]</i> </pre> </td><td> This is a paragraph. <ol> <li> This is a list item. </li> <li> This is a second list item. <ul><li>This is a sublist.</li></ul></li> </ol> </td></tr> </table> <p> Note that sublists must be separated from the blocks in their parent list item by indentation. In particular, the following docstring generates an error, since the sublist is not separated from the paragraph in its parent list item by indentation: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" 1. This is a list item. Its paragraph is indented 7 spaces. - This is a sublist. It is indented 7 spaces. """</code> <i>[...]</i> </pre> </td><td> <b>L5: Error: Lists must be indented.</b> </td></tr> </table> <p> The following example illustrates how lists can be used: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" This is a paragraph. 1. This is a list item. - This is a sublist. - The sublist contains two items. - The second item of the sublist has its own sublist. 2. This list item contains two paragraphs and a doctest block. &gt;&gt;&gt; print 'This is a doctest block' This is a doctest block This is the second paragraph. """</code> <i>[...]</i> </pre> </td><td> This is a paragraph. <ol> <li> This is a list item. </li> <ul> <li> This is a sublist. </li> <li> The sublist contains two items. </li> <ul> <li> The second item of the sublist has its own own sublist. </li> </ul> </ul> <li> This list item contains two paragraphs and a doctest block. <pre> <code class="prompt">&gt;&gt;&gt;</code> <code class="keyword">print</code> <code class="string">'This is a doctest block'</code> <code class="output">This is a doctest block</code></pre> <p> This is the second paragraph. </p> </li> </ol> </td></tr> </table> <p> Epytext will treat any line that begins with a bullet as a list item. If you want to include bullet-like text in a paragraph, then you must either ensure that it is not at the beginning of the line, or use <a href="#escaping">escaping</a> to prevent epytext from treating it as markup: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" This sentence ends with the number 1. Epytext can't tell if the "1." is a bullet or part of the paragraph, so it generates an error. """</code> <i>[...]</i> </pre> </td><td> <b> L4: Error: Lists must be indented. </b> </td></tr> <tr valign="top"><td> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" This sentence ends with the number 1. This sentence ends with the number E{1}. """</code> <i>[...]</i> </pre> </td><td> This sentence ends with the number 1. <p> This sentence ends with the number 1.</p> </td></tr> </table> <a name="section"/> <h3> 2.3. Sections </h3> <p> A section consists of a heading followed by one or more child blocks. </p> <ul> <li> The heading is a single underlined line of text. Top-level section headings are underlined with the "=" character; subsection headings are underlined with the "-" character; and subsubsection headings are underlined with the "~" character. The length of the underline must exactly match the length of the heading.</li> <li> The child blocks can be paragraphs, lists, literal blocks, doctest blocks, or sections. Each child must have equal indentation, and that indentation must be greater than or equal to the heading's indentation. </li> </ul> <p> The following example illustrates how sections can be used: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" This paragraph is not in any section. Section 1 ========= This is a paragraph in section 1. Section 1.1 ----------- This is a paragraph in section 1.1. Section 2 ========= This is a paragraph in section 2. """</code> <i>[...]</i> </pre> </td><td> <b><font size="+2">Section 1</font></b><br> This is a paragraph in section 1. <br><br> <b><font size="+1">Section 1.1</font></b><br> This is a paragraph in section 1.1. <br><br> <b><font size="+2">Section 2</font></b><br> This is a paragraph in section 2. </table> <a name="literal"/> <h3> 2.4. Literal Blocks </h3> <p> Literal blocks are used to represent "preformatted" text. Everything within a literal block should be displayed exactly as it appears in plaintext. In particular: </p> <ul> <li> Spaces and newlines are preserved. </li> <li> Text is shown in a monospaced font. </li> <li> Inline markup is not detected. </li> </ul> <p> Literal blocks are introduced by paragraphs ending in the special sequence "<code>::</code>". Literal blocks end at the first line whose indentation is equal to or less than that of the paragraph that introduces them. The following example shows how literal blocks can be used: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" The following is a literal block:: Literal / / Block This is a paragraph following the literal block. """</code> <i>[...]</i> </pre> </td><td> <p>The following is a literal block:</p> <pre> Literal / / Block </pre> <p>This is a paragraph following the literal block.</p> </table> <p> Literal blocks are indented relative to the paragraphs that introduce them; for example, in the previous example, the word "Literal" is displayed with four leading spaces, not eight. Also, note that the double colon ("<code>::</code>") that introduces the literal block is rendered as a single colon. </p> <a name="doctest"/> <h3> 2.5. Doctest Blocks </h3> <p> Doctest blocks contain examples consisting of Python expressions and their output. Doctest blocks can be used by the <a href="http://www.python.org/doc/current/lib/module-doctest.html">doctest</a> module to test the documented object. Doctest blocks begin with the special sequence "<code>&gt;&gt;&gt;</code>". Doctest blocks are delimited from surrounding blocks by blank lines. Doctest blocks may not contain blank lines. The following example shows how doctest blocks can be used: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" The following is a doctest block: &gt;&gt;&gt; print (1+3, ... 3+5) (4, 8) &gt;&gt;&gt; 'a-b-c-d-e'.split('-') ['a', 'b', 'c', 'd', 'e'] This is a paragraph following the doctest block. """</code> <i>[...]</i> </pre> </td><td> <p> The following is a doctest block: </p> <pre> <code class="prompt">&gt;&gt;&gt;</code> <code class="keyword">print</code> <code class="pycode">(1+3,</code> <code class="prompt">...</code> <code class="pycode">3+5)</code> <code class="output">(4, 8)</code> <code class="prompt">&gt;&gt;&gt;</code> <code class="string">'a-b-c-d-e'</code><code class="pycode">.split('-')</code> <code class="output">['a', 'b', 'c', 'd', 'e']</code> </pre> <p>This is a paragraph following the doctest block.</p> </table> <a name="fieldlist"/> <h3> 2.6. Fields </h3> <p> Fields are used to describe specific properties of a documented object. For example, fields can be used to define the parameters and return value of a function; the instance variables of a class; and the author of a module. Each field is marked by a <i>field tag</i>, which consist of an at sign ("<code>@</code>") followed by a <i>field name</i>, optionally followed by a space and a <i>field argument</i>, followed by a colon ("<code>:</code>"). For example, "<code>@return:</code>" and "<code>@param&nbsp;x:</code>" are field tags. </p> <p> Fields can contain paragraphs, lists, literal blocks, and doctest blocks. All of the blocks contained by a field must all have equal indentation, and that indentation must be greater than or equal to the indentation of the field's tag. If the first contained block is a paragraph, it may appear on the same line as the field tag, separated from the field tag by one or more spaces. All other block types must follow on separate lines. </p> <p> Fields must be placed at the end of the docstring, after the description of the object. Fields may be included in any order. </p> <p> Fields do not need to be separated from other blocks by a blank line. Any line that begins with a field tag followed by a space or newline is considered a field. </p> <p> The following example illustrates how fields can be used: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" <code class="field">@param x:</code> This is a description of the parameter x to a function. Note that the description is indented four spaces. <code class="field">@type x:</code> This is a description of x's type. <code class="field">@return:</code> This is a description of the function's return value. It contains two paragraphs. """</code> <i>[...]</i> </pre> </td><td> <dl><dt><b>Parameters:</b></dt> <dd><code><b>x</b></code> - This is a description of the parameter x to a function. Note that the description is indented four spaces. <br><i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (type=This is a description of x's type.)</i> </dd> </dl> <dl><dt><b>Returns:</b></dt> <dd> This is a description of the function's return value. <p>It contains two paragraphs.</p> </dd> </td></tr> </table> <p> For a list of the fields that are supported by epydoc, see the <a href="fields.html#fields">epydoc fields page</a>. <!-- =========== INLINE MARKUP ============= --> <a name="inline"/> <h2> 3. Inline Markup </h2> <p> Inline markup has the form "<i>x</i><code>{</code>...<code>}</code>", where "<i>x</i>" is a single capital letter that specifies how the text between the braces should be rendered. Inline markup is recognized within paragraphs and section headings. It is <i>not</i> recognized within literal and doctest blocks. Inline markup can contain multiple words, and can span multiple lines. Inline markup may be nested. </p> <p> A matching pair of curly braces is only interpreted as inline markup if the left brace is immediately preceeded by a capital letter. So in most cases, you can use curly braces in your text without any form of escaping. However, you <i>do</i> need to escape curly braces when: </p> <ol> <li> You want to include a single (un-matched) curly brace. <li> You want to preceed a matched pair of curly braces with a capital letter. </li> </ol> <p> Note that there is no valid Python expression where a pair of matched curly braces is immediately preceeded by a capital letter (except within string literals). In particular, you never need to escape braces when writing Python dictionaries. See <a href="#escaping">section 3.5</a> for a discussion of escaping. </p> <a name="basic_inline"/> <h3> 3.1. Basic Inline Markup </h3> <p> Epytext defines four types of inline markup that specify how text should be displayed: </p> <ul> <li> <code>I{</code>...<code>}</code>: Italicized text. </li> <li> <code>B{</code>...<code>}</code>: Bold-faced text. </li> <li> <code>C{</code>...<code>}</code>: Source code or a Python identifier. </li> <li> <code>M{</code>...<code>}</code>: A mathematical expression. </li> </ul> <p> By default, source code is rendered in a fixed width font; and mathematical expressions are rendered in italics. But those defaults may be changed by modifying the CSS stylesheet. The following example illustrates how the four basic markup types can be used: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" I{B{Inline markup} may be nested; and it may span} multiple lines. - I{Italicized text} - B{Bold-faced text} - C{Source code} - M{Math} Without the capital letter, matching braces are not interpreted as markup: C{my_dict={1:2, 3:4}}. """</code> <i>[...]</i> </pre> </td><td> <i><b>Inline markup</b> may be nested; and it may span</i> multiple lines. <ul> <li> <i>Italicized text</i> </li> <li> <b>Bold-faced text</b> </li> <li> <code>Source code</code> </li> <li> Math: <i>m*x+b</i> </li> </ul> Without the capital letter, matching braces are not interpreted as markup: <code>my_dict={1:2, 3:4}</code>. </td></tr> </table> <a name="urls"/> <h3> 3.2. URLs </h3> <p> The inline markup construct "<code>U{</code><i>text</i><code>&lt;</code><i>url</i><code>&gt;}</code>" is used to create links to external URLs and URIs. "<i>Text</i>" is the text that should be displayed for the link, and "<i>url</i>" is the target of the link. If you wish to use the URL as the text for the link, you can simply write "<code>U{</code><i>url</i><code>}</code>". Whitespace within URL targets is ignored. In particular, URL targets may be split over multiple lines. The following example illustrates how URLs can be used: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td rowspan="2"> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" - U{www.python.org} - U{http://www.python.org} - U{The epydoc homepage&lt;http:// epydoc.sourceforge.net&gt;} - U{The B{I{Python}} homepage &lt;www.python.org&gt;} - U{Edward Loper&lt;mailto:edloper@ gradient.cis.upenn.edu&gt;} """</code> <i>[...]</i> </pre> </td><td> <ul> <li> <a href="http://www.python.org">www.python.org</a> </li> <li> <a href="http://www.python.org">http://www.python.org</a> </li> <li> <a href="http://epydoc.sourceforge.net">The epydoc homepage</a> </li> <li> <a href="http://www.python.org">The <b><i>Python</i></b> homepage</a> </li> <li> <a href="mailto:edloper@gradient.cis.upenn.edu">Edward Loper</a> </li> </ul> </td></tr> </table> <a name="links"/> <h3> 3.3. Documentation Crossreference Links </h3> <p> The inline markup construct "<code>L{</code><i>text</i><code>&lt;</code><i>object</i><code>&gt;}</code>" is used to create links to the documentation for other Python objects. "<i>Text</i>" is the text that should be displayed for the link, and "<i>object</i>" is the name of the Python object that should be linked to. If you wish to use the name of the Python object as the text for the link, you can simply write "<code>L{</code><i>object</i><code>}</code>". Whitespace within object names is ignored. In particular, object names may be split over multiple lines. The following example illustrates how documentation crossreference links can be used: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td rowspan="2"> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" - L{x_transform} - L{search&lt;re.search&gt;} - L{The I{x-transform} function &lt;x_transform&gt;} """</code> <i>[...]</i> </pre> </td><td> <ul> <li> <a href="examples/example.html#x_intercept" ><code>x_transform</code></a></li> <li> <a href="examples/sre.html#search" ><code>search</code></a></li> <li> <a href="examples/example.html#x_intercept" ><code>The <i>x-transform</i> function</code></a></li> </ul> </td></tr> </table> <p> In order to find the object that corresponds to a given name, epydoc checks the following locations, in order: </p> <ol> <li> If the link is made from a class or method docstring, then epydoc checks for a method, instance variable, or class variable with the given name. </li> <li> Next, epydoc looks for an object with the given name in the current module. </li> <li> Epydoc then tries to import the given name as a module. If the current module is contained in a package, then epydoc will also try importing the given name from all packages containing the current module. </li> <li> Finally, epydoc tries to divide the given name into a module name and an object name, and to import the object from the module. If the current module is contained in a package, then epydoc will also try importing the module name from all packages containing the current module. </li> </ol> <p> If no object is found that corresponds with the given name, then epydoc issues a warning. </p> <a name="indexed"/> <h3> 3.4. Indexed Terms </h3> <p> Epydoc automatically creates an index of term definitions for the API documentation. The inline markup construct "<code>X{</code>...<code>}</code>" is used to mark terms for inclusion in the index. The term itself will be italicized; and a link will be created from the index page to the location of the term in the text. The following example illustrates how index terms can be used: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td rowspan="2"> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" An X{index term} is a term that should be included in the index. """</code> <i>[...]</i> </pre> </td><td> An <a name="index-index_term"/><i>index term</i> is a term that should be included in the index. </td></tr><tr><td> <table border="1" cellpadding="3" cellspacing="0" width="95%" class="grayf"> <tr> <th colspan="2" class="grayc">Index</th></tr> <tr><td width="15%">index&nbsp;term</td> <td><i><a href="#index-index_term">example</a></i></tr></td> <tr><td width="15%">x&nbsp;intercept</td> <td><i><a href="examples/example.html#index-x_intercept">x_intercept</a></i></tr></td> <tr><td width="15%">y&nbsp;intercept</td> <td><i><a href="examples/example.html#index-y_intercept">x_intercept</a></i></tr></td> </table> </td></tr> </table> <a name="symbols"/> <h3> 3.5. Symbols </h3> <p> Symbols are used to insert special characters in your documentation. A symbol has the form "<code>S{</code><i>code</i><code>}</code>", where <i>code</i> is a symbol code that specifies what character should be produced. The following example illustrates how symbols can be used to generate special characters: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td rowspan="2"> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" Symbols can be used in equations: - S{sum}S{alpha}/x S{<=} S{beta} S{<-} and S{larr} both give left arrows. Some other arrows are S{rarr}, S{uarr}, and S{darr}. """</code> <i>[...]</i> </pre> </td><td> <p>Symbols can be used in equations:</p> <ul><li>&sum;&alpha;/x &le; &beta;</li></ul> <p>&larr; and &larr; both give left arrows. Some other arrows are &rarr;, &uarr;, and &darr;.</p> </td></tr> </table> <p> Although symbols can be quite useful, you should keep in mind that they can make it harder to read your docstring in plaintext. In general, symbols should be used sparingly. For a complete list of the symbols that are currently supported, see the reference documentation for <a href="api/public/epydoc.markup.epytext-module.html#SYMBOLS" >epydoc.epytext.SYMBOLS</a>. </p> <a name="escaping"/> <h3> 3.6. Escaping </h3> <p> Escaping is used to write text that would otherwise be interpreted as epytext markup. Epytext was carefully constructed to minimize the need for this type of escaping; but sometimes, it is unavoidable. Escaped text has the form "<code>E{</code><i>code</i><code>}</code>", where <i>code</i> is an escape code that specifies what character should be produced. If the escape code is a single character (other than "<code>{</code>" or "<code>}</code>"), then that character is produced. For example, to begin a paragraph with a dash (which would normally signal a list item), write "<code>E{-}</code>". In addition, two special escape codes are defined: "<code>E{lb}</code>" produces a left curly brace ("<code>{</code>"); and "<code>E{rb}</code>" produces a right curly brace ("<code>}</code>"). The following example illustrates how escaping can be used: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td rowspan="2"> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" This paragraph ends with two colons, but does not introduce a literal blockE{:}E{:} E{-} This is not a list item. Escapes can be used to write unmatched curly braces: E{rb}E{lb} """</code> <i>[...]</i> </pre> </td><td> <p>This paragraph ends with two colons, but does not introduce a literal block::</p> <p>- This is not a list item.</p> <p>Escapes can be used to write unmatched curly braces: }{</p> </td></tr> </table> <a name="graphs"/> <h3> 3.7. Graphs </h3> <p> The inline markup construct "<code>G{</code><i>graphtype</i> <i>args...</i>}</code>" is used to insert automatically generated graphs. The following graphs generation constructions are currently defines:</p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="10%">Markup</th><th width="90%">Description</th></tr> <tr valign="top"> <td><pre>G{classtree <code class="user">classes...</code>}</pre></td> <td> Display a class hierarchy for the given class or classes (including all superclasses &amp; subclasses). If no class is specified, and the directive is used in a class's docstring, then that class's class hierarchy will be displayed. </td></tr> <tr valign="top"> <td><pre>G{packagetree <code class="user">modules...</code>}</pre></td> <td> Display a package hierarchy for the given module or modules (including all subpackages and submodules). If no module is specified, and the directive is used in a module's docstring, then that module's package hierarchy will be displayed. </td></tr> <tr valign="top"> <td><pre>G{impotgraph <code class="user">modules...</code>}</pre></td> <td> Display an import graph for the given module or modules. If no module is specified, and the directive is used in a module's docstring, then that module's import graph will be displayed. </td></tr> <tr valign="top"> <td><pre>G{callgraph <code class="user">functions...</code>}</pre></td> <td> Display a call graph for the given function or functions. If no function is specified, and the directive is used in a function's docstring, then that function's call graph will be displayed. </td></tr> </table> <!-- =========== CHARACTERS ============= --> <a name="characters"/> <h2> 4. Characters </h2> <a name="valid_characters"/> <h3> 4.1. Valid Characters </h3> <p> Valid characters for an epytext docstring are space ("\040"); newline ("\012"); and any letter, digit, or punctuation, as defined by the current locale. Control characters ("\000"-"\010" and "\013"-"\037") are not valid content characters. Tabs ("\011") are expanded to spaces, using the same algorithm used by the Python parser. Carridge-return/newline pairs ("\015\012") are converted to newlines. </p> <a name="content_characters"/> <h3> 4.2. Content Characters </h3> <p> Characters in a docstring that are not involved in markup are called <i>content characters</i>. Content characters are always displayed as-is. In particular, HTML codes are <i>not</i> passed through. For example, consider the following example: </p> <table border="1" cellspacing="0" cellpadding="3" width="95%"> <tr><th width="50%">Docstring Input</th><th width="50%">Rendered Output</th> <tr valign="top"><td> <pre> <code class="keyword">def</code> <code class="function">example</code>(): <code class="string">""" &lt;B&gt;test&lt;/B&gt; """</code> <i>[...]</i> </pre> </td><td> &lt;B&gt;test&lt;/B&gt; </table> <p> The docstring is rendered as "&lt;B&gt;test&lt;/B&gt;", and not as the word "test" in bold face. </p> <a name="whitespace"/> <h3> 4.3. Spaces and Newlines </h3> <p> In general, spaces and newlines within docstrings are treated as <i>soft spaces</i>. In other words, sequences of spaces and newlines (that do not contain a blank line) are rendered as a single space, and words may wrapped at spaces. However, within literal blocks and doctest blocks, spaces and newlines are preserved, and no word-wrapping occurs; and within URL targets and documentation link targets, whitespace is ignored. </p> <!-- =========== WARNINGS ============= --> <!-- (make sure this is consistant w/ the man page!!) --> <a name="warnings"/> <h2> 5. Warnings and Errors </h2> <p>If epydoc encounters an error while processing a docstring, it issues a warning message that describes the error, and attempts to continue generating documentation. Errors related to epytext are divided into three categories: </p> <ul> <li> <b>Epytext Warnings</b> are caused by epytext docstrings that contain questionable or suspicious markup. Epytext warnings do not prevent the docstring in question from being parsed. </li> <li> <b> Field Warnings</b> are caused by epytext docstrings containing invalid fields. The contents of the invalid field are generally ignored. </li> <li> <b>Epytext Errors</b> are caused by epytext docstrings that contain invalid markup. Whenever an epytext error is detected, the docstring in question is treated as a plaintext docstring. </li> </ul> <p> The following sections list and describe the warning messages that epydoc can generate. They are intended as a reference resource, which you can search for more information and possible causes if you encounter an error and do not understand it. These descriptions are also available in the <a href="epydoc-man.html#lbAH"><code>epydoc(1)</code> man page</a>. </p> <h3> 5.1. Epytext Warnings </h3> <ul> <li><b class="error">Possible mal-formatted field item.</b> <br /> Epytext detected a line that looks like a field item, but is not correctly formatted. This typically occurs when the trailing colon (<b>":"</b>) is not included in the field tag. <li><b class="error">Possible heading typo.</b> <br /> Epytext detected a pair of lines that looks like a heading, but the number of underline characters does not match the number of characters in the heading. The number of characters in these two lines must match exactly for them to be considered a heading. </ul> <h3> 5.2. Field Warnings </h3> <ul> <li><b class="error"><code>@param</code> for unknown parameter <i>param</i>.</b> <br /> A <code>@param</code> field was used to specify the type for a parameter that is not included in the function's signature. This is typically caused by a typo in the parameter name. <li><b class="error"><i>tag</i> did not expect an argument.</b> <br /> The field tag <i>tag</i> was used with an argument, but it does not take one. <li><b class="error"><i>tag</i> expected an argument.</b> <br /> The field tag <i>tag</i> was used without an argument, but it requires one. <li><b class="error"><code>@type</code> for unknown parameter <i>param</i>.</b> <br /> A <code>@type</code> field was used to specify the type for a parameter that is not included in the function's signature. This is typically caused by a typo in the parameter name. <li><b class="error"><code>@type</code> for unknown variable <i>var</i>.</b> <br /> A <code>@type</code> field was used to specify the type for a variable, but no other information is known about the variable. This is typically caused by a typo in the variable name. <li><b class="error">Unknown field tag <i>tag</i>.</b> <br /> A docstring contains a field with the unknown tag <i>tag</i>. <li><b class="error">Redefinition of <i>field</i>.</b> <br /> Multiple field tags define the value of <i>field</i> in the same docstring, but <i>field</i> can only take a single value. </ul> <h3> 5.3. Epytext Errors </h3> <ul> <li><b class="error">Bad link target.</b> <br /> The target specified for an inline link contruction (<code>L{...}</code>) is not well-formed. Link targets must be valid python identifiers. <li><b class="error">Bad uri target.</b> <br /> The target specified for an inline uri contruction (<code>U{...}</code>) is not well-formed. This typically occurs if inline markup is nested inside the URI target. <li><b class="error">Fields must be at the top level.</b> <br /> The list of fields (<code>@param</code>, etc.) is contained by some other block structure (such as a list or a section). <li><b class="error">Fields must be the final elements in an epytext string.</b> <br /> The list of fields (<code>@param</code>, etc.) is not at the end of a docstring. <li><b class="error">Headings must occur at top level.</b> <br /> The heading is contianed in some other block structure (such as a list). <li><b class="error">Improper doctest block indentation.</b> <br /> The doctest block dedents past the indentation of its initial prompt line. <li><b class="error">Improper heading indentation.</b> <br /> The heading for a section is not left-aligned with the paragraphs in the section that contains it. <li><b class="error">Improper paragraph indentation.</b> <br /> The paragraphs within a block are not left-aligned. This error is often generated when plaintext docstrings are parsed using epytext. <li><b class="error">Invalid escape.</b> <br /> An unknown escape sequence was used with the inline escape construction (<code>E{...}</code>). <li><b class="error">Lists must be indented.</b> <br /> An unindented line immediately following a paragraph starts with a list bullet. Epydoc is not sure whether you meant to start a new list item, or meant for a paragraph to include a word that looks like a bullet. If you intended the former, then indent the list. If you intended the latter, then change the word-wrapping of the paragraph, or escape the first character of the word that looks like a bullet. <li><b class="error">Unbalanced '{'.</b> <br /> The docstring contains unbalanced braces. Epytext requires that all braces must be balanced. To include a single unbalanced brace, use the escape sequences <code>E{lb}</code> (left brace) and <code>E{rb}</code> (right brace). <li><b class="error">Unbalanced '}'.</b> <br /> The docstring contains unbalanced braces. Epytext requires that all braces must be balanced. To include a single unbalanced brace, use the escape sequences <code>E{lb}</code> (left brace) and <code>E{rb}</code> (right brace). <li><b class="error">Unknown inline markup tag.</b> <br /> An unknown tag was used with the inline markup construction (<code><i>x</i>{...}</code>). <li><b class="error">Wrong underline character for heading.</b> <br /> The underline character used for this section heading does not indicate an appopriate section level. The "<code>=</code>" character should be used to underline sections; "<code>-</code>" for subsections; and "<code>~</code>" for subsubsections. </ul> </div> <table width="100%" class="navbox" cellpadding="1" cellspacing="0"> <tr> <a class="nav" href="index.html"> <td align="center" width="20%" class="nav"> <a class="nav" href="index.html"> Home</a></td></a> <a class="nav" href="installing.html"> <td align="center" width="20%" class="nav"> <a class="nav" href="installing.html"> Installing Epydoc</a></td></a> <a class="nav" href="using.html"> <td align="center" width="20%" class="nav"> <a class="nav" href="using.html"> Using Epydoc</a></td></a> <a class="nav" href="epytext.html"> <td align="center" width="20%" class="navselect" class="nav"> <a class="nav" href="epytext.html"> Epytext</a></td></a> <td align="center" width="20%" class="nav"> <A href="http://sourceforge.net/projects/epydoc"> <IMG src="sflogo.png" width="88" height="26" border="0" alt="SourceForge" align="top"/></A></td> </tr> </table> </body> </html>
regular/pyglet-avbin-optimizations
tools/epydoc/doc/epytext.html
HTML
bsd-3-clause
40,057
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime import itertools import os import re from importlib import import_module from django.apps import apps from django.conf import settings from django.contrib.admin.models import LogEntry from django.contrib.auth import REDIRECT_FIELD_NAME, SESSION_KEY from django.contrib.auth.forms import ( AuthenticationForm, PasswordChangeForm, SetPasswordForm, ) from django.contrib.auth.models import User from django.contrib.auth.tests.custom_user import CustomUser from django.contrib.auth.views import login as login_view, redirect_to_login from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.sites.requests import RequestSite from django.core import mail from django.core.urlresolvers import NoReverseMatch, reverse, reverse_lazy from django.db import connection from django.http import HttpRequest, QueryDict from django.middleware.csrf import CsrfViewMiddleware, get_token from django.test import ( TestCase, ignore_warnings, modify_settings, override_settings, ) from django.test.utils import patch_logger from django.utils.deprecation import RemovedInDjango110Warning from django.utils.encoding import force_text from django.utils.http import urlquote from django.utils.six.moves.urllib.parse import ParseResult, urlparse from django.utils.translation import LANGUAGE_SESSION_KEY from .models import UUIDUser from .settings import AUTH_TEMPLATES @override_settings( LANGUAGES=[ ('en', 'English'), ], LANGUAGE_CODE='en', TEMPLATES=AUTH_TEMPLATES, USE_TZ=False, PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF='auth_tests.urls', ) class AuthViewsTestCase(TestCase): """ Helper base class for all the follow test cases. """ @classmethod def setUpTestData(cls): cls.u1 = User.objects.create( password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='testclient', first_name='Test', last_name='Client', email='testclient@example.com', is_staff=False, is_active=True, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31) ) cls.u2 = User.objects.create( password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='inactive', first_name='Inactive', last_name='User', email='testclient2@example.com', is_staff=False, is_active=False, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31) ) cls.u3 = User.objects.create( password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='staff', first_name='Staff', last_name='Member', email='staffmember@example.com', is_staff=True, is_active=True, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31) ) cls.u4 = User.objects.create( password='', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='empty_password', first_name='Empty', last_name='Password', email='empty_password@example.com', is_staff=False, is_active=True, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31) ) cls.u5 = User.objects.create( password='$', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='unmanageable_password', first_name='Unmanageable', last_name='Password', email='unmanageable_password@example.com', is_staff=False, is_active=True, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31) ) cls.u6 = User.objects.create( password='foo$bar', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='unknown_password', first_name='Unknown', last_name='Password', email='unknown_password@example.com', is_staff=False, is_active=True, date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31) ) def login(self, username='testclient', password='password'): response = self.client.post('/login/', { 'username': username, 'password': password, }) self.assertIn(SESSION_KEY, self.client.session) return response def logout(self): response = self.client.get('/admin/logout/') self.assertEqual(response.status_code, 200) self.assertNotIn(SESSION_KEY, self.client.session) def assertFormError(self, response, error): """Assert that error is found in response.context['form'] errors""" form_errors = list(itertools.chain(*response.context['form'].errors.values())) self.assertIn(force_text(error), form_errors) def assertURLEqual(self, url, expected, parse_qs=False): """ Given two URLs, make sure all their components (the ones given by urlparse) are equal, only comparing components that are present in both URLs. If `parse_qs` is True, then the querystrings are parsed with QueryDict. This is useful if you don't want the order of parameters to matter. Otherwise, the query strings are compared as-is. """ fields = ParseResult._fields for attr, x, y in zip(fields, urlparse(url), urlparse(expected)): if parse_qs and attr == 'query': x, y = QueryDict(x), QueryDict(y) if x and y and x != y: self.fail("%r != %r (%s doesn't match)" % (url, expected, attr)) @override_settings(ROOT_URLCONF='django.contrib.auth.urls') class AuthViewNamedURLTests(AuthViewsTestCase): def test_named_urls(self): "Named URLs should be reversible" expected_named_urls = [ ('login', [], {}), ('logout', [], {}), ('password_change', [], {}), ('password_change_done', [], {}), ('password_reset', [], {}), ('password_reset_done', [], {}), ('password_reset_confirm', [], { 'uidb64': 'aaaaaaa', 'token': '1111-aaaaa', }), ('password_reset_complete', [], {}), ] for name, args, kwargs in expected_named_urls: try: reverse(name, args=args, kwargs=kwargs) except NoReverseMatch: self.fail("Reversal of url named '%s' failed with NoReverseMatch" % name) class PasswordResetTest(AuthViewsTestCase): def test_email_not_found(self): """If the provided email is not registered, don't raise any error but also don't send any email.""" response = self.client.get('/password_reset/') self.assertEqual(response.status_code, 200) response = self.client.post('/password_reset/', {'email': 'not_a_real_email@email.com'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 0) def test_email_found(self): "Email is sent if a valid email address is provided for password reset" response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertIn("http://", mail.outbox[0].body) self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email) # optional multipart text/html email has been added. Make sure original, # default functionality is 100% the same self.assertFalse(mail.outbox[0].message().is_multipart()) def test_extra_email_context(self): """ extra_email_context should be available in the email template context. """ response = self.client.post( '/password_reset_extra_email_context/', {'email': 'staffmember@example.com'}, ) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertIn('Email email context: "Hello!"', mail.outbox[0].body) def test_html_mail_template(self): """ A multipart email with text/plain and text/html is sent if the html_email_template parameter is passed to the view """ response = self.client.post('/password_reset/html_email_template/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0].message() self.assertEqual(len(message.get_payload()), 2) self.assertTrue(message.is_multipart()) self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain') self.assertEqual(message.get_payload(1).get_content_type(), 'text/html') self.assertNotIn('<html>', message.get_payload(0).get_payload()) self.assertIn('<html>', message.get_payload(1).get_payload()) def test_email_found_custom_from(self): "Email is sent if a valid email address is provided for password reset when a custom from_email is provided." response = self.client.post('/password_reset_from_email/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertEqual("staffmember@example.com", mail.outbox[0].from_email) @ignore_warnings(category=RemovedInDjango110Warning) @override_settings(ALLOWED_HOSTS=['adminsite.com']) def test_admin_reset(self): "If the reset view is marked as being for admin, the HTTP_HOST header is used for a domain override." response = self.client.post('/admin_password_reset/', {'email': 'staffmember@example.com'}, HTTP_HOST='adminsite.com' ) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertIn("http://adminsite.com", mail.outbox[0].body) self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email) # Skip any 500 handler action (like sending more mail...) @override_settings(DEBUG_PROPAGATE_EXCEPTIONS=True) def test_poisoned_http_host(self): "Poisoned HTTP_HOST headers can't be used for reset emails" # This attack is based on the way browsers handle URLs. The colon # should be used to separate the port, but if the URL contains an @, # the colon is interpreted as part of a username for login purposes, # making 'evil.com' the request domain. Since HTTP_HOST is used to # produce a meaningful reset URL, we need to be certain that the # HTTP_HOST header isn't poisoned. This is done as a check when get_host() # is invoked, but we check here as a practical consequence. with patch_logger('django.security.DisallowedHost', 'error') as logger_calls: response = self.client.post( '/password_reset/', {'email': 'staffmember@example.com'}, HTTP_HOST='www.example:dr.frankenstein@evil.tld' ) self.assertEqual(response.status_code, 400) self.assertEqual(len(mail.outbox), 0) self.assertEqual(len(logger_calls), 1) # Skip any 500 handler action (like sending more mail...) @override_settings(DEBUG_PROPAGATE_EXCEPTIONS=True) def test_poisoned_http_host_admin_site(self): "Poisoned HTTP_HOST headers can't be used for reset emails on admin views" with patch_logger('django.security.DisallowedHost', 'error') as logger_calls: response = self.client.post( '/admin_password_reset/', {'email': 'staffmember@example.com'}, HTTP_HOST='www.example:dr.frankenstein@evil.tld' ) self.assertEqual(response.status_code, 400) self.assertEqual(len(mail.outbox), 0) self.assertEqual(len(logger_calls), 1) def _test_confirm_start(self): # Start by creating the email self.client.post('/password_reset/', {'email': 'staffmember@example.com'}) self.assertEqual(len(mail.outbox), 1) return self._read_signup_email(mail.outbox[0]) def _read_signup_email(self, email): urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body) self.assertIsNotNone(urlmatch, "No URL found in sent email") return urlmatch.group(), urlmatch.groups()[0] def test_confirm_valid(self): url, path = self._test_confirm_start() response = self.client.get(path) # redirect to a 'complete' page: self.assertContains(response, "Please enter your new password") def test_confirm_invalid(self): url, path = self._test_confirm_start() # Let's munge the token in the path, but keep the same length, # in case the URLconf will reject a different length. path = path[:-5] + ("0" * 4) + path[-1] response = self.client.get(path) self.assertContains(response, "The password reset link was invalid") def test_confirm_invalid_user(self): # Ensure that we get a 200 response for a non-existent user, not a 404 response = self.client.get('/reset/123456/1-1/') self.assertContains(response, "The password reset link was invalid") def test_confirm_overflow_user(self): # Ensure that we get a 200 response for a base36 user id that overflows int response = self.client.get('/reset/zzzzzzzzzzzzz/1-1/') self.assertContains(response, "The password reset link was invalid") def test_confirm_invalid_post(self): # Same as test_confirm_invalid, but trying # to do a POST instead. url, path = self._test_confirm_start() path = path[:-5] + ("0" * 4) + path[-1] self.client.post(path, { 'new_password1': 'anewpassword', 'new_password2': ' anewpassword', }) # Check the password has not been changed u = User.objects.get(email='staffmember@example.com') self.assertTrue(not u.check_password("anewpassword")) def test_confirm_complete(self): url, path = self._test_confirm_start() response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'}) # Check the password has been changed u = User.objects.get(email='staffmember@example.com') self.assertTrue(u.check_password("anewpassword")) # Check we can't use the link again response = self.client.get(path) self.assertContains(response, "The password reset link was invalid") def test_confirm_different_passwords(self): url, path = self._test_confirm_start() response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'x'}) self.assertFormError(response, SetPasswordForm.error_messages['password_mismatch']) def test_reset_redirect_default(self): response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_reset/done/') def test_reset_custom_redirect(self): response = self.client.post('/password_reset/custom_redirect/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/custom/') def test_reset_custom_redirect_named(self): response = self.client.post('/password_reset/custom_redirect/named/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_reset/') def test_confirm_redirect_default(self): url, path = self._test_confirm_start() response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/reset/done/') def test_confirm_redirect_custom(self): url, path = self._test_confirm_start() path = path.replace('/reset/', '/reset/custom/') response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/custom/') def test_confirm_redirect_custom_named(self): url, path = self._test_confirm_start() path = path.replace('/reset/', '/reset/custom/named/') response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_reset/') def test_confirm_display_user_from_form(self): url, path = self._test_confirm_start() response = self.client.get(path) # #16919 -- The ``password_reset_confirm`` view should pass the user # object to the ``SetPasswordForm``, even on GET requests. # For this test, we render ``{{ form.user }}`` in the template # ``registration/password_reset_confirm.html`` so that we can test this. username = User.objects.get(email='staffmember@example.com').username self.assertContains(response, "Hello, %s." % username) # However, the view should NOT pass any user object on a form if the # password reset link was invalid. response = self.client.get('/reset/zzzzzzzzzzzzz/1-1/') self.assertContains(response, "Hello, .") @override_settings(AUTH_USER_MODEL='auth.CustomUser') class CustomUserPasswordResetTest(AuthViewsTestCase): user_email = 'staffmember@example.com' @classmethod def setUpTestData(cls): cls.u1 = CustomUser.custom_objects.create( password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), email='staffmember@example.com', is_active=True, is_admin=False, date_of_birth=datetime.date(1976, 11, 8) ) def _test_confirm_start(self): # Start by creating the email response = self.client.post('/password_reset/', {'email': self.user_email}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) return self._read_signup_email(mail.outbox[0]) def _read_signup_email(self, email): urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body) self.assertIsNotNone(urlmatch, "No URL found in sent email") return urlmatch.group(), urlmatch.groups()[0] def test_confirm_valid_custom_user(self): url, path = self._test_confirm_start() response = self.client.get(path) # redirect to a 'complete' page: self.assertContains(response, "Please enter your new password") # then submit a new password response = self.client.post(path, { 'new_password1': 'anewpassword', 'new_password2': 'anewpassword', }) self.assertRedirects(response, '/reset/done/') @override_settings(AUTH_USER_MODEL='auth.UUIDUser') class UUIDUserPasswordResetTest(CustomUserPasswordResetTest): def _test_confirm_start(self): # instead of fixture UUIDUser.objects.create_user( email=self.user_email, username='foo', password='foo', ) return super(UUIDUserPasswordResetTest, self)._test_confirm_start() class ChangePasswordTest(AuthViewsTestCase): def fail_login(self, password='password'): response = self.client.post('/login/', { 'username': 'testclient', 'password': password, }) self.assertFormError(response, AuthenticationForm.error_messages['invalid_login'] % { 'username': User._meta.get_field('username').verbose_name }) def logout(self): self.client.get('/logout/') def test_password_change_fails_with_invalid_old_password(self): self.login() response = self.client.post('/password_change/', { 'old_password': 'donuts', 'new_password1': 'password1', 'new_password2': 'password1', }) self.assertFormError(response, PasswordChangeForm.error_messages['password_incorrect']) def test_password_change_fails_with_mismatched_passwords(self): self.login() response = self.client.post('/password_change/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'donuts', }) self.assertFormError(response, SetPasswordForm.error_messages['password_mismatch']) def test_password_change_succeeds(self): self.login() self.client.post('/password_change/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'password1', }) self.fail_login() self.login(password='password1') def test_password_change_done_succeeds(self): self.login() response = self.client.post('/password_change/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'password1', }) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_change/done/') @override_settings(LOGIN_URL='/login/') def test_password_change_done_fails(self): response = self.client.get('/password_change/done/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/login/?next=/password_change/done/') def test_password_change_redirect_default(self): self.login() response = self.client.post('/password_change/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'password1', }) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_change/done/') def test_password_change_redirect_custom(self): self.login() response = self.client.post('/password_change/custom/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'password1', }) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/custom/') def test_password_change_redirect_custom_named(self): self.login() response = self.client.post('/password_change/custom/named/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'password1', }) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_reset/') @modify_settings(MIDDLEWARE_CLASSES={ 'append': 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', }) class SessionAuthenticationTests(AuthViewsTestCase): def test_user_password_change_updates_session(self): """ #21649 - Ensure contrib.auth.views.password_change updates the user's session auth hash after a password change so the session isn't logged out. """ self.login() response = self.client.post('/password_change/', { 'old_password': 'password', 'new_password1': 'password1', 'new_password2': 'password1', }) # if the hash isn't updated, retrieving the redirection page will fail. self.assertRedirects(response, '/password_change/done/') class LoginTest(AuthViewsTestCase): def test_current_site_in_context_after_login(self): response = self.client.get(reverse('login')) self.assertEqual(response.status_code, 200) if apps.is_installed('django.contrib.sites'): Site = apps.get_model('sites.Site') site = Site.objects.get_current() self.assertEqual(response.context['site'], site) self.assertEqual(response.context['site_name'], site.name) else: self.assertIsInstance(response.context['site'], RequestSite) self.assertIsInstance(response.context['form'], AuthenticationForm) def test_security_check(self, password='password'): login_url = reverse('login') # Those URLs should not pass the security check for bad_url in ('http://example.com', 'http:///example.com', 'https://example.com', 'ftp://exampel.com', '///example.com', '//example.com', 'javascript:alert("XSS")'): nasty_url = '%(url)s?%(next)s=%(bad_url)s' % { 'url': login_url, 'next': REDIRECT_FIELD_NAME, 'bad_url': urlquote(bad_url), } response = self.client.post(nasty_url, { 'username': 'testclient', 'password': password, }) self.assertEqual(response.status_code, 302) self.assertNotIn(bad_url, response.url, "%s should be blocked" % bad_url) # These URLs *should* still pass the security check for good_url in ('/view/?param=http://example.com', '/view/?param=https://example.com', '/view?param=ftp://exampel.com', 'view/?param=//example.com', 'https://testserver/', 'HTTPS://testserver/', '//testserver/', '/url%20with%20spaces/'): # see ticket #12534 safe_url = '%(url)s?%(next)s=%(good_url)s' % { 'url': login_url, 'next': REDIRECT_FIELD_NAME, 'good_url': urlquote(good_url), } response = self.client.post(safe_url, { 'username': 'testclient', 'password': password, }) self.assertEqual(response.status_code, 302) self.assertIn(good_url, response.url, "%s should be allowed" % good_url) def test_login_form_contains_request(self): # 15198 self.client.post('/custom_requestauth_login/', { 'username': 'testclient', 'password': 'password', }, follow=True) # the custom authentication form used by this login asserts # that a request is passed to the form successfully. def test_login_csrf_rotate(self, password='password'): """ Makes sure that a login rotates the currently-used CSRF token. """ # Do a GET to establish a CSRF token # TestClient isn't used here as we're testing middleware, essentially. req = HttpRequest() CsrfViewMiddleware().process_view(req, login_view, (), {}) # get_token() triggers CSRF token inclusion in the response get_token(req) resp = login_view(req) resp2 = CsrfViewMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None) token1 = csrf_cookie.coded_value # Prepare the POST request req = HttpRequest() req.COOKIES[settings.CSRF_COOKIE_NAME] = token1 req.method = "POST" req.POST = {'username': 'testclient', 'password': password, 'csrfmiddlewaretoken': token1} # Use POST request to log in SessionMiddleware().process_request(req) CsrfViewMiddleware().process_view(req, login_view, (), {}) req.META["SERVER_NAME"] = "testserver" # Required to have redirect work in login view req.META["SERVER_PORT"] = 80 resp = login_view(req) resp2 = CsrfViewMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None) token2 = csrf_cookie.coded_value # Check the CSRF token switched self.assertNotEqual(token1, token2) def test_session_key_flushed_on_login(self): """ To avoid reusing another user's session, ensure a new, empty session is created if the existing session corresponds to a different authenticated user. """ self.login() original_session_key = self.client.session.session_key self.login(username='staff') self.assertNotEqual(original_session_key, self.client.session.session_key) def test_session_key_flushed_on_login_after_password_change(self): """ As above, but same user logging in after a password change. """ self.login() original_session_key = self.client.session.session_key # If no password change, session key should not be flushed. self.login() self.assertEqual(original_session_key, self.client.session.session_key) user = User.objects.get(username='testclient') user.set_password('foobar') user.save() self.login(password='foobar') self.assertNotEqual(original_session_key, self.client.session.session_key) def test_login_session_without_hash_session_key(self): """ Session without django.contrib.auth.HASH_SESSION_KEY should login without an exception. """ user = User.objects.get(username='testclient') engine = import_module(settings.SESSION_ENGINE) session = engine.SessionStore() session[SESSION_KEY] = user.id session.save() original_session_key = session.session_key self.client.cookies[settings.SESSION_COOKIE_NAME] = original_session_key self.login() self.assertNotEqual(original_session_key, self.client.session.session_key) class LoginURLSettings(AuthViewsTestCase): """Tests for settings.LOGIN_URL.""" def assertLoginURLEquals(self, url, parse_qs=False): response = self.client.get('/login_required/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, url, parse_qs=parse_qs) @override_settings(LOGIN_URL='/login/') def test_standard_login_url(self): self.assertLoginURLEquals('/login/?next=/login_required/') @override_settings(LOGIN_URL='login') def test_named_login_url(self): self.assertLoginURLEquals('/login/?next=/login_required/') @override_settings(LOGIN_URL='http://remote.example.com/login') def test_remote_login_url(self): quoted_next = urlquote('http://testserver/login_required/') expected = 'http://remote.example.com/login?next=%s' % quoted_next self.assertLoginURLEquals(expected) @override_settings(LOGIN_URL='https:///login/') def test_https_login_url(self): quoted_next = urlquote('http://testserver/login_required/') expected = 'https:///login/?next=%s' % quoted_next self.assertLoginURLEquals(expected) @override_settings(LOGIN_URL='/login/?pretty=1') def test_login_url_with_querystring(self): self.assertLoginURLEquals('/login/?pretty=1&next=/login_required/', parse_qs=True) @override_settings(LOGIN_URL='http://remote.example.com/login/?next=/default/') def test_remote_login_url_with_next_querystring(self): quoted_next = urlquote('http://testserver/login_required/') expected = 'http://remote.example.com/login/?next=%s' % quoted_next self.assertLoginURLEquals(expected) @override_settings(LOGIN_URL=reverse_lazy('login')) def test_lazy_login_url(self): self.assertLoginURLEquals('/login/?next=/login_required/') class LoginRedirectUrlTest(AuthViewsTestCase): """Tests for settings.LOGIN_REDIRECT_URL.""" def assertLoginRedirectURLEqual(self, url): response = self.login() self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, url) def test_default(self): self.assertLoginRedirectURLEqual('/accounts/profile/') @override_settings(LOGIN_REDIRECT_URL='/custom/') def test_custom(self): self.assertLoginRedirectURLEqual('/custom/') @override_settings(LOGIN_REDIRECT_URL='password_reset') def test_named(self): self.assertLoginRedirectURLEqual('/password_reset/') @override_settings(LOGIN_REDIRECT_URL='http://remote.example.com/welcome/') def test_remote(self): self.assertLoginRedirectURLEqual('http://remote.example.com/welcome/') class RedirectToLoginTests(AuthViewsTestCase): """Tests for the redirect_to_login view""" @override_settings(LOGIN_URL=reverse_lazy('login')) def test_redirect_to_login_with_lazy(self): login_redirect_response = redirect_to_login(next='/else/where/') expected = '/login/?next=/else/where/' self.assertEqual(expected, login_redirect_response.url) @override_settings(LOGIN_URL=reverse_lazy('login')) def test_redirect_to_login_with_lazy_and_unicode(self): login_redirect_response = redirect_to_login(next='/else/where/झ/') expected = '/login/?next=/else/where/%E0%A4%9D/' self.assertEqual(expected, login_redirect_response.url) class LogoutTest(AuthViewsTestCase): def confirm_logged_out(self): self.assertNotIn(SESSION_KEY, self.client.session) def test_logout_default(self): "Logout without next_page option renders the default template" self.login() response = self.client.get('/logout/') self.assertContains(response, 'Logged out') self.confirm_logged_out() def test_14377(self): # Bug 14377 self.login() response = self.client.get('/logout/') self.assertIn('site', response.context) def test_logout_with_overridden_redirect_url(self): # Bug 11223 self.login() response = self.client.get('/logout/next_page/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/somewhere/') response = self.client.get('/logout/next_page/?next=/login/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/login/') self.confirm_logged_out() def test_logout_with_next_page_specified(self): "Logout with next_page option given redirects to specified resource" self.login() response = self.client.get('/logout/next_page/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/somewhere/') self.confirm_logged_out() def test_logout_with_redirect_argument(self): "Logout with query string redirects to specified resource" self.login() response = self.client.get('/logout/?next=/login/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/login/') self.confirm_logged_out() def test_logout_with_custom_redirect_argument(self): "Logout with custom query string redirects to specified resource" self.login() response = self.client.get('/logout/custom_query/?follow=/somewhere/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/somewhere/') self.confirm_logged_out() def test_logout_with_named_redirect(self): "Logout resolves names or URLs passed as next_page." self.login() response = self.client.get('/logout/next_page/named/') self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_reset/') self.confirm_logged_out() def test_security_check(self, password='password'): logout_url = reverse('logout') # Those URLs should not pass the security check for bad_url in ('http://example.com', 'http:///example.com', 'https://example.com', 'ftp://exampel.com', '///example.com', '//example.com', 'javascript:alert("XSS")'): nasty_url = '%(url)s?%(next)s=%(bad_url)s' % { 'url': logout_url, 'next': REDIRECT_FIELD_NAME, 'bad_url': urlquote(bad_url), } self.login() response = self.client.get(nasty_url) self.assertEqual(response.status_code, 302) self.assertNotIn(bad_url, response.url, "%s should be blocked" % bad_url) self.confirm_logged_out() # These URLs *should* still pass the security check for good_url in ('/view/?param=http://example.com', '/view/?param=https://example.com', '/view?param=ftp://exampel.com', 'view/?param=//example.com', 'https://testserver/', 'HTTPS://testserver/', '//testserver/', '/url%20with%20spaces/'): # see ticket #12534 safe_url = '%(url)s?%(next)s=%(good_url)s' % { 'url': logout_url, 'next': REDIRECT_FIELD_NAME, 'good_url': urlquote(good_url), } self.login() response = self.client.get(safe_url) self.assertEqual(response.status_code, 302) self.assertIn(good_url, response.url, "%s should be allowed" % good_url) self.confirm_logged_out() def test_logout_preserve_language(self): """Check that language stored in session is preserved after logout""" # Create a new session with language engine = import_module(settings.SESSION_ENGINE) session = engine.SessionStore() session[LANGUAGE_SESSION_KEY] = 'pl' session.save() self.client.cookies[settings.SESSION_COOKIE_NAME] = session.session_key self.client.get('/logout/') self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], 'pl') # Redirect in test_user_change_password will fail if session auth hash # isn't updated after password change (#21649) @modify_settings(MIDDLEWARE_CLASSES={ 'append': 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', }) @override_settings( PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF='auth_tests.urls_admin', ) class ChangelistTests(AuthViewsTestCase): def setUp(self): # Make me a superuser before logging in. User.objects.filter(username='testclient').update(is_staff=True, is_superuser=True) self.login() self.admin = User.objects.get(pk=self.u1.pk) def get_user_data(self, user): return { 'username': user.username, 'password': user.password, 'email': user.email, 'is_active': user.is_active, 'is_staff': user.is_staff, 'is_superuser': user.is_superuser, 'last_login_0': user.last_login.strftime('%Y-%m-%d'), 'last_login_1': user.last_login.strftime('%H:%M:%S'), 'initial-last_login_0': user.last_login.strftime('%Y-%m-%d'), 'initial-last_login_1': user.last_login.strftime('%H:%M:%S'), 'date_joined_0': user.date_joined.strftime('%Y-%m-%d'), 'date_joined_1': user.date_joined.strftime('%H:%M:%S'), 'initial-date_joined_0': user.date_joined.strftime('%Y-%m-%d'), 'initial-date_joined_1': user.date_joined.strftime('%H:%M:%S'), 'first_name': user.first_name, 'last_name': user.last_name, } # #20078 - users shouldn't be allowed to guess password hashes via # repeated password__startswith queries. def test_changelist_disallows_password_lookups(self): # A lookup that tries to filter on password isn't OK with patch_logger('django.security.DisallowedModelAdminLookup', 'error') as logger_calls: response = self.client.get(reverse('auth_test_admin:auth_user_changelist') + '?password__startswith=sha1$') self.assertEqual(response.status_code, 400) self.assertEqual(len(logger_calls), 1) def test_user_change_email(self): data = self.get_user_data(self.admin) data['email'] = 'new_' + data['email'] response = self.client.post( reverse('auth_test_admin:auth_user_change', args=(self.admin.pk,)), data ) self.assertRedirects(response, reverse('auth_test_admin:auth_user_changelist')) row = LogEntry.objects.latest('id') self.assertEqual(row.change_message, 'Changed email.') def test_user_not_change(self): response = self.client.post( reverse('auth_test_admin:auth_user_change', args=(self.admin.pk,)), self.get_user_data(self.admin) ) self.assertRedirects(response, reverse('auth_test_admin:auth_user_changelist')) row = LogEntry.objects.latest('id') self.assertEqual(row.change_message, 'No fields changed.') def test_user_change_password(self): user_change_url = reverse('auth_test_admin:auth_user_change', args=(self.admin.pk,)) password_change_url = reverse('auth_test_admin:auth_user_password_change', args=(self.admin.pk,)) response = self.client.get(user_change_url) # Test the link inside password field help_text. rel_link = re.search( r'you can change the password using <a href="([^"]*)">this form</a>', force_text(response.content) ).groups()[0] self.assertEqual( os.path.normpath(user_change_url + rel_link), os.path.normpath(password_change_url) ) response = self.client.post( password_change_url, { 'password1': 'password1', 'password2': 'password1', } ) self.assertRedirects(response, user_change_url) row = LogEntry.objects.latest('id') self.assertEqual(row.change_message, 'Changed password.') self.logout() self.login(password='password1') def test_user_change_different_user_password(self): u = User.objects.get(email='staffmember@example.com') response = self.client.post( reverse('auth_test_admin:auth_user_password_change', args=(u.pk,)), { 'password1': 'password1', 'password2': 'password1', } ) self.assertRedirects(response, reverse('auth_test_admin:auth_user_change', args=(u.pk,))) row = LogEntry.objects.latest('id') self.assertEqual(row.user_id, self.admin.pk) self.assertEqual(row.object_id, str(u.pk)) self.assertEqual(row.change_message, 'Changed password.') def test_password_change_bad_url(self): response = self.client.get(reverse('auth_test_admin:auth_user_password_change', args=('foobar',))) self.assertEqual(response.status_code, 404) @override_settings( AUTH_USER_MODEL='auth.UUIDUser', ROOT_URLCONF='auth_tests.urls_custom_user_admin', ) class UUIDUserTests(TestCase): def test_admin_password_change(self): u = UUIDUser.objects.create_superuser(username='uuid', email='foo@bar.com', password='test') self.assertTrue(self.client.login(username='uuid', password='test')) user_change_url = reverse('custom_user_admin:auth_uuiduser_change', args=(u.pk,)) response = self.client.get(user_change_url) self.assertEqual(response.status_code, 200) password_change_url = reverse('custom_user_admin:auth_user_password_change', args=(u.pk,)) response = self.client.get(password_change_url) self.assertEqual(response.status_code, 200) # A LogEntry is created with pk=1 which breaks a FK constraint on MySQL with connection.constraint_checks_disabled(): response = self.client.post(password_change_url, { 'password1': 'password1', 'password2': 'password1', }) self.assertRedirects(response, user_change_url) row = LogEntry.objects.latest('id') self.assertEqual(row.user_id, 1) # harcoded in CustomUserAdmin.log_change() self.assertEqual(row.object_id, str(u.pk)) self.assertEqual(row.change_message, 'Changed password.')
bikong2/django
tests/auth_tests/test_views.py
Python
bsd-3-clause
45,028
<d2-custom-data-entry-form custom-data-entry-form="customDataEntryForm"></d2-custom-data-entry-form>
minagri-rwanda/DHIS2-Agriculture
dhis-web/dhis-web-commons-resources/src/main/webapp/dhis-web-commons/angular-forms/custom-dataentry-form.html
HTML
bsd-3-clause
100
! This file is all about BACKSPACE ! { dg-do run } integer i, n, nr real x(10), y(10) ! PR libfortran/20068 open (20, status='scratch') write (20,*) 1 write (20,*) 2 write (20,*) 3 rewind (20) read (20,*) i if (i .ne. 1) call abort write (*,*) ' ' backspace (20) read (20,*) i if (i .ne. 1) call abort close (20) ! PR libfortran/20125 open (20, status='scratch') write (20,*) 7 backspace (20) read (20,*) i if (i .ne. 7) call abort close (20) open (20, status='scratch', form='unformatted') write (20) 8 backspace (20) read (20) i if (i .ne. 8) call abort close (20) ! PR libfortran/20471 do n = 1, 10 x(n) = sqrt(real(n)) end do open (3, form='unformatted', status='scratch') write (3) (x(n),n=1,10) backspace (3) rewind (3) read (3) (y(n),n=1,10) do n = 1, 10 if (abs(x(n)-y(n)) > 0.00001) call abort end do close (3) ! PR libfortran/20156 open (3, form='unformatted', status='scratch') do i = 1, 5 x(1) = i write (3) n, (x(n),n=1,10) end do nr = 0 rewind (3) 20 continue read (3,end=30,err=90) n, (x(n),n=1,10) nr = nr + 1 goto 20 30 continue if (nr .ne. 5) call abort do i = 1, nr+1 backspace (3) end do do i = 1, nr read(3,end=70,err=90) n, (x(n),n=1,10) if (abs(x(1) - i) .gt. 0.001) call abort end do close (3) stop 70 continue call abort 90 continue call abort end
shaotuanchen/sunflower_exp
tools/source/gcc-4.2.4/gcc/testsuite/gfortran.dg/backspace.f
FORTRAN
bsd-3-clause
1,676
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; const path = require('../fastpath'); const getPlatformExtension = require('./getPlatformExtension'); function getAssetDataFromName(filename, platforms) { const ext = path.extname(filename); const platformExt = getPlatformExtension(filename, platforms); let pattern = '@([\\d\\.]+)x'; if (platformExt != null) { pattern += '(\\.' + platformExt + ')?'; } pattern += '\\' + ext + '$'; const re = new RegExp(pattern); const match = filename.match(re); let resolution; if (!(match && match[1])) { resolution = 1; } else { resolution = parseFloat(match[1], 10); if (isNaN(resolution)) { resolution = 1; } } let assetName; if (match) { assetName = filename.replace(re, ext); } else if (platformExt != null) { assetName = filename.replace(new RegExp(`\\.${platformExt}\\${ext}`), ext); } else { assetName = filename; } return { resolution: resolution, assetName: assetName, type: ext.slice(1), name: path.basename(assetName, ext), platform: platformExt, }; } module.exports = getAssetDataFromName;
facebook/node-haste
src/lib/getAssetDataFromName.js
JavaScript
bsd-3-clause
1,418
var utils = require('../../lib/utils'); // if they agree to the ULA, notify hubspot, create a trial and send verification link module.exports = function trialSignup(request, reply) { var postToHubspot = request.server.methods.npme.sendData, getCustomer = request.server.methods.npme.getCustomer; var opts = {}; var data = { hs_context: { pageName: "enterprise-trial-signup", ipAddress: utils.getUserIP(request) }, // we can trust the email is fine because we've verified it in the show-ula handler email: request.payload.customer_email, }; postToHubspot(process.env.HUBSPOT_FORM_NPME_AGREED_ULA, data, function(er) { if (er) { request.logger.error('Could not hit ULA notification form on Hubspot'); request.logger.error(er); reply.view('errors/internal', opts).code(500); return; } getCustomer(data.email, function(err, customer) { if (err) { request.logger.error('Unknown problem with customer record'); request.logger.error(err); reply.view('errors/internal', opts).code(500); return; } if (!customer) { request.logger.error('Unable to locate customer error ' + data.email); reply.view('errors/internal', opts).code(500); return; } if (customer && customer.id + '' === request.payload.customer_id + '') { return createTrialAccount(request, reply, customer); } request.logger.error('Unable to verify customer record ', data.email); reply.view('errors/internal', opts).code(500); }); }); }; function createTrialAccount(request, reply, customer) { var createTrial = request.server.methods.npme.createTrial; var opts = {}; createTrial(customer, function(er, trial) { if (er) { request.logger.error('There was an error with creating a trial for ', customer.id); request.logger.error(er); reply.view('errors/internal', opts).code(500); return; } return sendVerificationEmail(request, reply, customer, trial); }); } function sendVerificationEmail(request, reply, customer, trial) { var opts = {}; var sendEmail = request.server.methods.email.send; var user = { name: customer.name, email: customer.email, verification_key: trial.verification_key }; sendEmail('npme-trial-verification', user, request.redis) .catch(function(er) { request.logger.error('Unable to send verification email to ', customer); request.logger.error(er); reply.view('errors/internal', opts).code(500); return; }) .then(function() { return reply.view('enterprise/thanks', opts); }); }
AgtLucas/newww
facets/enterprise/show-trial-signup.js
JavaScript
isc
2,680
using System; using System.Collections.Generic; using UIKit; using Foundation; using System.Reflection; namespace FontList.Code { /// <summary> /// Combined DataSource and Delegate for our UITableView /// </summary> public class NavItemTableSource : UITableViewSource { protected List<NavItemGroup> navItems; string cellIdentifier = "NavTableCellView"; UINavigationController navigationController; public NavItemTableSource (UINavigationController navigationController, List<NavItemGroup> items) { navItems = items; this.navigationController = navigationController; } /// <summary> /// Called by the TableView to determine how many sections(groups) there are. /// </summary> public override nint NumberOfSections (UITableView tableView) { return navItems.Count; } /// <summary> /// Called by the TableView to determine how many cells to create for that particular section. /// </summary> public override nint RowsInSection (UITableView tableview, nint section) { return navItems[(int)section].Items.Count; } /// <summary> /// Called by the TableView to retrieve the header text for the particular section(group) /// </summary> public override string TitleForHeader (UITableView tableView, nint section) { return navItems[(int)section].Name; } /// <summary> /// Called by the TableView to retrieve the footer text for the particular section(group) /// </summary> public override string TitleForFooter (UITableView tableView, nint section) { return navItems[(int)section].Footer; } /// <summary> /// Called by the TableView to actually build each cell. /// </summary> public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { NavItem navItem = this.navItems[indexPath.Section].Items[indexPath.Row]; var cell = tableView.DequeueReusableCell (this.cellIdentifier); if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, this.cellIdentifier); cell.Tag = Environment.TickCount; } //---- set the cell properties cell.TextLabel.Text = this.navItems[indexPath.Section].Items[indexPath.Row].Name; cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; if (navItem.Font != null) { cell.TextLabel.Font = navItem.Font; } return cell; } /// <summary> /// Is called when a row is selected /// </summary> public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { //---- get a reference to the nav item NavItem navItem = navItems[indexPath.Section].Items[indexPath.Row]; // if the nav item has a proper controller, push it on to the NavigationController // NOTE: we could also raise an event here, to loosely couple this, but isn't neccessary, // because we'll only ever use this this way if (navItem.Controller != null) { navigationController.PushViewController (navItem.Controller, true); // show the nav bar (we don't show it on the home page) navigationController.NavigationBarHidden = false; } else { if (navItem.ControllerType != null) { ConstructorInfo ctor = null; // if the nav item has constructor aguments if (navItem.ControllerConstructorArgs.Length > 0) { // look for the constructor ctor = navItem.ControllerType.GetConstructor (navItem.ControllerConstructorTypes); } else { // search for the default constructor ctor = navItem.ControllerType.GetConstructor (System.Type.EmptyTypes); } // if we found the constructor if (ctor != null) { UIViewController instance = null; if (navItem.ControllerConstructorArgs.Length > 0) { // instance the view controller instance = ctor.Invoke (navItem.ControllerConstructorArgs) as UIViewController; } else { // instance the view controller instance = ctor.Invoke (null) as UIViewController; } if (instance != null) { // save the object navItem.Controller = instance; // push the view controller onto the stack navigationController.PushViewController (navItem.Controller, true); } else { Console.WriteLine ("instance of view controller not created"); } } else { Console.WriteLine ("constructor not found"); } } } } } }
davidrynn/monotouch-samples
FontList/Code/NavItemTableSource.cs
C#
mit
4,333
var insert = require('./insert') var concat = require('concat-stream') insert('aggregate', [{ name: 'Squirtle', type: 'water' }, { name: 'Starmie', type: 'water' }, { name: 'Charmander', type: 'fire' }, { name: 'Lapras', type: 'water' }], function (db, t, done) { db.a.aggregate([{$group: {_id: '$type'}}, {$project: { _id: 0, foo: '$_id' }}], function (err, types) { console.log(err, types) var arr = types.map(function (x) {return x.foo}) console.log('arr', arr) t.equal(types.length, 2) console.log('here') t.notEqual(arr.indexOf('fire'), -1) console.log('there') t.notEqual(arr.indexOf('water'), -1) console.log('where') // test as a stream var strm = db.a.aggregate([{$group: {_id: '$type'}}, {$project: {_id: 0, foo: '$_id'}}]) strm.pipe(concat(function (types) { var arr = types.map(function (x) {return x.foo}) t.equal(types.length, 2) t.notEqual(arr.indexOf('fire'), -1) t.notEqual(arr.indexOf('water'), -1) t.end() })) strm.on('error', function (err) { // Aggregation cursors are only supported on mongodb 2.6+ // this shouldn't fail the tests for other versions of mongodb if (err.message === 'unrecognized field "cursor') t.ok(1) else t.fail(err) t.end() }) }) })
AMKohn/mongojs
test/test-aggregate-pipeline.js
JavaScript
mit
1,310
<?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use ArrayObject; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Cell\DataValidation; use PhpOffice\PhpSpreadsheet\Cell\Hyperlink; use PhpOffice\PhpSpreadsheet\Chart\Chart; use PhpOffice\PhpSpreadsheet\Collection\Cells; use PhpOffice\PhpSpreadsheet\Collection\CellsFactory; use PhpOffice\PhpSpreadsheet\Comment; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\IComparable; use PhpOffice\PhpSpreadsheet\NamedRange; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Style; class Worksheet implements IComparable { // Break types const BREAK_NONE = 0; const BREAK_ROW = 1; const BREAK_COLUMN = 2; // Sheet state const SHEETSTATE_VISIBLE = 'visible'; const SHEETSTATE_HIDDEN = 'hidden'; const SHEETSTATE_VERYHIDDEN = 'veryHidden'; /** * Maximum 31 characters allowed for sheet title. * * @var int */ const SHEET_TITLE_MAXIMUM_LENGTH = 31; /** * Invalid characters in sheet title. * * @var array */ private static $invalidCharacters = ['*', ':', '/', '\\', '?', '[', ']']; /** * Parent spreadsheet. * * @var Spreadsheet */ private $parent; /** * Collection of cells. * * @var Cells */ private $cellCollection; /** * Collection of row dimensions. * * @var RowDimension[] */ private $rowDimensions = []; /** * Default row dimension. * * @var RowDimension */ private $defaultRowDimension; /** * Collection of column dimensions. * * @var ColumnDimension[] */ private $columnDimensions = []; /** * Default column dimension. * * @var ColumnDimension */ private $defaultColumnDimension; /** * Collection of drawings. * * @var BaseDrawing[] */ private $drawingCollection; /** * Collection of Chart objects. * * @var Chart[] */ private $chartCollection = []; /** * Worksheet title. * * @var string */ private $title; /** * Sheet state. * * @var string */ private $sheetState; /** * Page setup. * * @var PageSetup */ private $pageSetup; /** * Page margins. * * @var PageMargins */ private $pageMargins; /** * Page header/footer. * * @var HeaderFooter */ private $headerFooter; /** * Sheet view. * * @var SheetView */ private $sheetView; /** * Protection. * * @var Protection */ private $protection; /** * Collection of styles. * * @var Style[] */ private $styles = []; /** * Conditional styles. Indexed by cell coordinate, e.g. 'A1'. * * @var array */ private $conditionalStylesCollection = []; /** * Is the current cell collection sorted already? * * @var bool */ private $cellCollectionIsSorted = false; /** * Collection of breaks. * * @var array */ private $breaks = []; /** * Collection of merged cell ranges. * * @var array */ private $mergeCells = []; /** * Collection of protected cell ranges. * * @var array */ private $protectedCells = []; /** * Autofilter Range and selection. * * @var AutoFilter */ private $autoFilter; /** * Freeze pane. * * @var null|string */ private $freezePane; /** * Default position of the right bottom pane. * * @var null|string */ private $topLeftCell; /** * Show gridlines? * * @var bool */ private $showGridlines = true; /** * Print gridlines? * * @var bool */ private $printGridlines = false; /** * Show row and column headers? * * @var bool */ private $showRowColHeaders = true; /** * Show summary below? (Row/Column outline). * * @var bool */ private $showSummaryBelow = true; /** * Show summary right? (Row/Column outline). * * @var bool */ private $showSummaryRight = true; /** * Collection of comments. * * @var Comment[] */ private $comments = []; /** * Active cell. (Only one!). * * @var string */ private $activeCell = 'A1'; /** * Selected cells. * * @var string */ private $selectedCells = 'A1'; /** * Cached highest column. * * @var string */ private $cachedHighestColumn = 'A'; /** * Cached highest row. * * @var int */ private $cachedHighestRow = 1; /** * Right-to-left? * * @var bool */ private $rightToLeft = false; /** * Hyperlinks. Indexed by cell coordinate, e.g. 'A1'. * * @var array */ private $hyperlinkCollection = []; /** * Data validation objects. Indexed by cell coordinate, e.g. 'A1'. * * @var array */ private $dataValidationCollection = []; /** * Tab color. * * @var Color */ private $tabColor; /** * Dirty flag. * * @var bool */ private $dirty = true; /** * Hash. * * @var string */ private $hash; /** * CodeName. * * @var string */ private $codeName; /** * Create a new worksheet. * * @param Spreadsheet $parent * @param string $pTitle */ public function __construct(Spreadsheet $parent = null, $pTitle = 'Worksheet') { // Set parent and title $this->parent = $parent; $this->setTitle($pTitle, false); // setTitle can change $pTitle $this->setCodeName($this->getTitle()); $this->setSheetState(self::SHEETSTATE_VISIBLE); $this->cellCollection = CellsFactory::getInstance($this); // Set page setup $this->pageSetup = new PageSetup(); // Set page margins $this->pageMargins = new PageMargins(); // Set page header/footer $this->headerFooter = new HeaderFooter(); // Set sheet view $this->sheetView = new SheetView(); // Drawing collection $this->drawingCollection = new \ArrayObject(); // Chart collection $this->chartCollection = new \ArrayObject(); // Protection $this->protection = new Protection(); // Default row dimension $this->defaultRowDimension = new RowDimension(null); // Default column dimension $this->defaultColumnDimension = new ColumnDimension(null); $this->autoFilter = new AutoFilter(null, $this); } /** * Disconnect all cells from this Worksheet object, * typically so that the worksheet object can be unset. */ public function disconnectCells() { if ($this->cellCollection !== null) { $this->cellCollection->unsetWorksheetCells(); $this->cellCollection = null; } // detach ourself from the workbook, so that it can then delete this worksheet successfully $this->parent = null; } /** * Code to execute when this worksheet is unset(). */ public function __destruct() { Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title); $this->disconnectCells(); } /** * Return the cell collection. * * @return Cells */ public function getCellCollection() { return $this->cellCollection; } /** * Get array of invalid characters for sheet title. * * @return array */ public static function getInvalidCharacters() { return self::$invalidCharacters; } /** * Check sheet code name for valid Excel syntax. * * @param string $pValue The string to check * * @throws Exception * * @return string The valid string */ private static function checkSheetCodeName($pValue) { $CharCount = Shared\StringHelper::countCharacters($pValue); if ($CharCount == 0) { throw new Exception('Sheet code name cannot be empty.'); } // Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'" if ((str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) || (Shared\StringHelper::substring($pValue, -1, 1) == '\'') || (Shared\StringHelper::substring($pValue, 0, 1) == '\'')) { throw new Exception('Invalid character found in sheet code name'); } // Enforce maximum characters allowed for sheet title if ($CharCount > self::SHEET_TITLE_MAXIMUM_LENGTH) { throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.'); } return $pValue; } /** * Check sheet title for valid Excel syntax. * * @param string $pValue The string to check * * @throws Exception * * @return string The valid string */ private static function checkSheetTitle($pValue) { // Some of the printable ASCII characters are invalid: * : / \ ? [ ] if (str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) { throw new Exception('Invalid character found in sheet title'); } // Enforce maximum characters allowed for sheet title if (Shared\StringHelper::countCharacters($pValue) > self::SHEET_TITLE_MAXIMUM_LENGTH) { throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet title.'); } return $pValue; } /** * Get a sorted list of all cell coordinates currently held in the collection by row and column. * * @param bool $sorted Also sort the cell collection? * * @return string[] */ public function getCoordinates($sorted = true) { if ($this->cellCollection == null) { return []; } if ($sorted) { return $this->cellCollection->getSortedCoordinates(); } return $this->cellCollection->getCoordinates(); } /** * Get collection of row dimensions. * * @return RowDimension[] */ public function getRowDimensions() { return $this->rowDimensions; } /** * Get default row dimension. * * @return RowDimension */ public function getDefaultRowDimension() { return $this->defaultRowDimension; } /** * Get collection of column dimensions. * * @return ColumnDimension[] */ public function getColumnDimensions() { return $this->columnDimensions; } /** * Get default column dimension. * * @return ColumnDimension */ public function getDefaultColumnDimension() { return $this->defaultColumnDimension; } /** * Get collection of drawings. * * @return BaseDrawing[] */ public function getDrawingCollection() { return $this->drawingCollection; } /** * Get collection of charts. * * @return Chart[] */ public function getChartCollection() { return $this->chartCollection; } /** * Add chart. * * @param Chart $pChart * @param null|int $iChartIndex Index where chart should go (0,1,..., or null for last) * * @return Chart */ public function addChart(Chart $pChart, $iChartIndex = null) { $pChart->setWorksheet($this); if ($iChartIndex === null) { $this->chartCollection[] = $pChart; } else { // Insert the chart at the requested index array_splice($this->chartCollection, $iChartIndex, 0, [$pChart]); } return $pChart; } /** * Return the count of charts on this worksheet. * * @return int The number of charts */ public function getChartCount() { return count($this->chartCollection); } /** * Get a chart by its index position. * * @param string $index Chart index position * * @return Chart|false */ public function getChartByIndex($index) { $chartCount = count($this->chartCollection); if ($chartCount == 0) { return false; } if ($index === null) { $index = --$chartCount; } if (!isset($this->chartCollection[$index])) { return false; } return $this->chartCollection[$index]; } /** * Return an array of the names of charts on this worksheet. * * @return string[] The names of charts */ public function getChartNames() { $chartNames = []; foreach ($this->chartCollection as $chart) { $chartNames[] = $chart->getName(); } return $chartNames; } /** * Get a chart by name. * * @param string $chartName Chart name * * @return Chart|false */ public function getChartByName($chartName) { $chartCount = count($this->chartCollection); if ($chartCount == 0) { return false; } foreach ($this->chartCollection as $index => $chart) { if ($chart->getName() == $chartName) { return $this->chartCollection[$index]; } } return false; } /** * Refresh column dimensions. * * @return Worksheet */ public function refreshColumnDimensions() { $currentColumnDimensions = $this->getColumnDimensions(); $newColumnDimensions = []; foreach ($currentColumnDimensions as $objColumnDimension) { $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension; } $this->columnDimensions = $newColumnDimensions; return $this; } /** * Refresh row dimensions. * * @return Worksheet */ public function refreshRowDimensions() { $currentRowDimensions = $this->getRowDimensions(); $newRowDimensions = []; foreach ($currentRowDimensions as $objRowDimension) { $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension; } $this->rowDimensions = $newRowDimensions; return $this; } /** * Calculate worksheet dimension. * * @return string String containing the dimension of this worksheet */ public function calculateWorksheetDimension() { // Return return 'A1' . ':' . $this->getHighestColumn() . $this->getHighestRow(); } /** * Calculate worksheet data dimension. * * @return string String containing the dimension of this worksheet that actually contain data */ public function calculateWorksheetDataDimension() { // Return return 'A1' . ':' . $this->getHighestDataColumn() . $this->getHighestDataRow(); } /** * Calculate widths for auto-size columns. * * @return Worksheet; */ public function calculateColumnWidths() { // initialize $autoSizes array $autoSizes = []; foreach ($this->getColumnDimensions() as $colDimension) { if ($colDimension->getAutoSize()) { $autoSizes[$colDimension->getColumnIndex()] = -1; } } // There is only something to do if there are some auto-size columns if (!empty($autoSizes)) { // build list of cells references that participate in a merge $isMergeCell = []; foreach ($this->getMergeCells() as $cells) { foreach (Coordinate::extractAllCellReferencesInRange($cells) as $cellReference) { $isMergeCell[$cellReference] = true; } } // loop through all cells in the worksheet foreach ($this->getCoordinates(false) as $coordinate) { $cell = $this->getCell($coordinate, false); if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) { //Determine if cell is in merge range $isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]); //By default merged cells should be ignored $isMergedButProceed = false; //The only exception is if it's a merge range value cell of a 'vertical' randge (1 column wide) if ($isMerged && $cell->isMergeRangeValueCell()) { $range = $cell->getMergeRange(); $rangeBoundaries = Coordinate::rangeDimension($range); if ($rangeBoundaries[0] == 1) { $isMergedButProceed = true; } } // Determine width if cell does not participate in a merge or does and is a value cell of 1-column wide range if (!$isMerged || $isMergedButProceed) { // Calculated value // To formatted string $cellValue = NumberFormat::toFormattedString( $cell->getCalculatedValue(), $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode() ); $autoSizes[$this->cellCollection->getCurrentColumn()] = max( (float) $autoSizes[$this->cellCollection->getCurrentColumn()], (float) Shared\Font::calculateColumnWidth( $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(), $cellValue, $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(), $this->getParent()->getDefaultStyle()->getFont() ) ); } } } // adjust column widths foreach ($autoSizes as $columnIndex => $width) { if ($width == -1) { $width = $this->getDefaultColumnDimension()->getWidth(); } $this->getColumnDimension($columnIndex)->setWidth($width); } } return $this; } /** * Get parent. * * @return Spreadsheet */ public function getParent() { return $this->parent; } /** * Re-bind parent. * * @param Spreadsheet $parent * * @return Worksheet */ public function rebindParent(Spreadsheet $parent) { if ($this->parent !== null) { $namedRanges = $this->parent->getNamedRanges(); foreach ($namedRanges as $namedRange) { $parent->addNamedRange($namedRange); } $this->parent->removeSheetByIndex( $this->parent->getIndex($this) ); } $this->parent = $parent; return $this; } /** * Get title. * * @return string */ public function getTitle() { return $this->title; } /** * Set title. * * @param string $pValue String containing the dimension of this worksheet * @param bool $updateFormulaCellReferences Flag indicating whether cell references in formulae should * be updated to reflect the new sheet name. * This should be left as the default true, unless you are * certain that no formula cells on any worksheet contain * references to this worksheet * @param bool $validate False to skip validation of new title. WARNING: This should only be set * at parse time (by Readers), where titles can be assumed to be valid. * * @return Worksheet */ public function setTitle($pValue, $updateFormulaCellReferences = true, $validate = true) { // Is this a 'rename' or not? if ($this->getTitle() == $pValue) { return $this; } // Old title $oldTitle = $this->getTitle(); if ($validate) { // Syntax check self::checkSheetTitle($pValue); if ($this->parent) { // Is there already such sheet name? if ($this->parent->sheetNameExists($pValue)) { // Use name, but append with lowest possible integer if (Shared\StringHelper::countCharacters($pValue) > 29) { $pValue = Shared\StringHelper::substring($pValue, 0, 29); } $i = 1; while ($this->parent->sheetNameExists($pValue . ' ' . $i)) { ++$i; if ($i == 10) { if (Shared\StringHelper::countCharacters($pValue) > 28) { $pValue = Shared\StringHelper::substring($pValue, 0, 28); } } elseif ($i == 100) { if (Shared\StringHelper::countCharacters($pValue) > 27) { $pValue = Shared\StringHelper::substring($pValue, 0, 27); } } } $pValue .= " $i"; } } } // Set title $this->title = $pValue; $this->dirty = true; if ($this->parent && $this->parent->getCalculationEngine()) { // New title $newTitle = $this->getTitle(); $this->parent->getCalculationEngine() ->renameCalculationCacheForWorksheet($oldTitle, $newTitle); if ($updateFormulaCellReferences) { ReferenceHelper::getInstance()->updateNamedFormulas($this->parent, $oldTitle, $newTitle); } } return $this; } /** * Get sheet state. * * @return string Sheet state (visible, hidden, veryHidden) */ public function getSheetState() { return $this->sheetState; } /** * Set sheet state. * * @param string $value Sheet state (visible, hidden, veryHidden) * * @return Worksheet */ public function setSheetState($value) { $this->sheetState = $value; return $this; } /** * Get page setup. * * @return PageSetup */ public function getPageSetup() { return $this->pageSetup; } /** * Set page setup. * * @param PageSetup $pValue * * @return Worksheet */ public function setPageSetup(PageSetup $pValue) { $this->pageSetup = $pValue; return $this; } /** * Get page margins. * * @return PageMargins */ public function getPageMargins() { return $this->pageMargins; } /** * Set page margins. * * @param PageMargins $pValue * * @return Worksheet */ public function setPageMargins(PageMargins $pValue) { $this->pageMargins = $pValue; return $this; } /** * Get page header/footer. * * @return HeaderFooter */ public function getHeaderFooter() { return $this->headerFooter; } /** * Set page header/footer. * * @param HeaderFooter $pValue * * @return Worksheet */ public function setHeaderFooter(HeaderFooter $pValue) { $this->headerFooter = $pValue; return $this; } /** * Get sheet view. * * @return SheetView */ public function getSheetView() { return $this->sheetView; } /** * Set sheet view. * * @param SheetView $pValue * * @return Worksheet */ public function setSheetView(SheetView $pValue) { $this->sheetView = $pValue; return $this; } /** * Get Protection. * * @return Protection */ public function getProtection() { return $this->protection; } /** * Set Protection. * * @param Protection $pValue * * @return Worksheet */ public function setProtection(Protection $pValue) { $this->protection = $pValue; $this->dirty = true; return $this; } /** * Get highest worksheet column. * * @param string $row Return the data highest column for the specified row, * or the highest column of any row if no row number is passed * * @return string Highest column name */ public function getHighestColumn($row = null) { if ($row == null) { return $this->cachedHighestColumn; } return $this->getHighestDataColumn($row); } /** * Get highest worksheet column that contains data. * * @param string $row Return the highest data column for the specified row, * or the highest data column of any row if no row number is passed * * @return string Highest column name that contains data */ public function getHighestDataColumn($row = null) { return $this->cellCollection->getHighestColumn($row); } /** * Get highest worksheet row. * * @param string $column Return the highest data row for the specified column, * or the highest row of any column if no column letter is passed * * @return int Highest row number */ public function getHighestRow($column = null) { if ($column == null) { return $this->cachedHighestRow; } return $this->getHighestDataRow($column); } /** * Get highest worksheet row that contains data. * * @param string $column Return the highest data row for the specified column, * or the highest data row of any column if no column letter is passed * * @return int Highest row number that contains data */ public function getHighestDataRow($column = null) { return $this->cellCollection->getHighestRow($column); } /** * Get highest worksheet column and highest row that have cell records. * * @return array Highest column name and highest row number */ public function getHighestRowAndColumn() { return $this->cellCollection->getHighestRowAndColumn(); } /** * Set a cell value. * * @param string $pCoordinate Coordinate of the cell, eg: 'A1' * @param mixed $pValue Value of the cell * * @return Worksheet */ public function setCellValue($pCoordinate, $pValue) { $this->getCell($pCoordinate)->setValue($pValue); return $this; } /** * Set a cell value by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param mixed $value Value of the cell * * @return Worksheet */ public function setCellValueByColumnAndRow($columnIndex, $row, $value) { $this->getCellByColumnAndRow($columnIndex, $row)->setValue($value); return $this; } /** * Set a cell value. * * @param string $pCoordinate Coordinate of the cell, eg: 'A1' * @param mixed $pValue Value of the cell * @param string $pDataType Explicit data type, see DataType::TYPE_* * * @return Worksheet */ public function setCellValueExplicit($pCoordinate, $pValue, $pDataType) { // Set value $this->getCell($pCoordinate)->setValueExplicit($pValue, $pDataType); return $this; } /** * Set a cell value by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param mixed $value Value of the cell * @param string $dataType Explicit data type, see DataType::TYPE_* * * @return Worksheet */ public function setCellValueExplicitByColumnAndRow($columnIndex, $row, $value, $dataType) { $this->getCellByColumnAndRow($columnIndex, $row)->setValueExplicit($value, $dataType); return $this; } /** * Get cell at a specific coordinate. * * @param string $pCoordinate Coordinate of the cell, eg: 'A1' * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't * already exist, or a null should be returned instead * * @throws Exception * * @return null|Cell Cell that was found/created or null */ public function getCell($pCoordinate, $createIfNotExists = true) { // Uppercase coordinate $pCoordinateUpper = strtoupper($pCoordinate); // Check cell collection if ($this->cellCollection->has($pCoordinateUpper)) { return $this->cellCollection->get($pCoordinateUpper); } // Worksheet reference? if (strpos($pCoordinate, '!') !== false) { $worksheetReference = self::extractSheetTitle($pCoordinate, true); return $this->parent->getSheetByName($worksheetReference[0])->getCell(strtoupper($worksheetReference[1]), $createIfNotExists); } // Named range? if ((!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate, $matches)) && (preg_match('/^' . Calculation::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $pCoordinate, $matches))) { $namedRange = NamedRange::resolveRange($pCoordinate, $this); if ($namedRange !== null) { $pCoordinate = $namedRange->getRange(); return $namedRange->getWorksheet()->getCell($pCoordinate, $createIfNotExists); } } if (Coordinate::coordinateIsRange($pCoordinate)) { throw new Exception('Cell coordinate can not be a range of cells.'); } elseif (strpos($pCoordinate, '$') !== false) { throw new Exception('Cell coordinate must not be absolute.'); } // Create new cell object, if required return $createIfNotExists ? $this->createNewCell($pCoordinateUpper) : null; } /** * Get cell at a specific coordinate by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't * already exist, or a null should be returned instead * * @return null|Cell Cell that was found/created or null */ public function getCellByColumnAndRow($columnIndex, $row, $createIfNotExists = true) { $columnLetter = Coordinate::stringFromColumnIndex($columnIndex); $coordinate = $columnLetter . $row; if ($this->cellCollection->has($coordinate)) { return $this->cellCollection->get($coordinate); } // Create new cell object, if required return $createIfNotExists ? $this->createNewCell($coordinate) : null; } /** * Create a new cell at the specified coordinate. * * @param string $pCoordinate Coordinate of the cell * * @return Cell Cell that was created */ private function createNewCell($pCoordinate) { $cell = new Cell(null, DataType::TYPE_NULL, $this); $this->cellCollection->add($pCoordinate, $cell); $this->cellCollectionIsSorted = false; // Coordinates $aCoordinates = Coordinate::coordinateFromString($pCoordinate); if (Coordinate::columnIndexFromString($this->cachedHighestColumn) < Coordinate::columnIndexFromString($aCoordinates[0])) { $this->cachedHighestColumn = $aCoordinates[0]; } if ($aCoordinates[1] > $this->cachedHighestRow) { $this->cachedHighestRow = $aCoordinates[1]; } // Cell needs appropriate xfIndex from dimensions records // but don't create dimension records if they don't already exist $rowDimension = $this->getRowDimension($aCoordinates[1], false); $columnDimension = $this->getColumnDimension($aCoordinates[0], false); if ($rowDimension !== null && $rowDimension->getXfIndex() > 0) { // then there is a row dimension with explicit style, assign it to the cell $cell->setXfIndex($rowDimension->getXfIndex()); } elseif ($columnDimension !== null && $columnDimension->getXfIndex() > 0) { // then there is a column dimension, assign it to the cell $cell->setXfIndex($columnDimension->getXfIndex()); } return $cell; } /** * Does the cell at a specific coordinate exist? * * @param string $pCoordinate Coordinate of the cell eg: 'A1' * * @throws Exception * * @return bool */ public function cellExists($pCoordinate) { // Worksheet reference? if (strpos($pCoordinate, '!') !== false) { $worksheetReference = self::extractSheetTitle($pCoordinate, true); return $this->parent->getSheetByName($worksheetReference[0])->cellExists(strtoupper($worksheetReference[1])); } // Named range? if ((!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate, $matches)) && (preg_match('/^' . Calculation::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $pCoordinate, $matches))) { $namedRange = NamedRange::resolveRange($pCoordinate, $this); if ($namedRange !== null) { $pCoordinate = $namedRange->getRange(); if ($this->getHashCode() != $namedRange->getWorksheet()->getHashCode()) { if (!$namedRange->getLocalOnly()) { return $namedRange->getWorksheet()->cellExists($pCoordinate); } throw new Exception('Named range ' . $namedRange->getName() . ' is not accessible from within sheet ' . $this->getTitle()); } } else { return false; } } // Uppercase coordinate $pCoordinate = strtoupper($pCoordinate); if (Coordinate::coordinateIsRange($pCoordinate)) { throw new Exception('Cell coordinate can not be a range of cells.'); } elseif (strpos($pCoordinate, '$') !== false) { throw new Exception('Cell coordinate must not be absolute.'); } // Cell exists? return $this->cellCollection->has($pCoordinate); } /** * Cell at a specific coordinate by using numeric cell coordinates exists? * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * * @return bool */ public function cellExistsByColumnAndRow($columnIndex, $row) { return $this->cellExists(Coordinate::stringFromColumnIndex($columnIndex) . $row); } /** * Get row dimension at a specific row. * * @param int $pRow Numeric index of the row * @param bool $create * * @return RowDimension */ public function getRowDimension($pRow, $create = true) { // Found $found = null; // Get row dimension if (!isset($this->rowDimensions[$pRow])) { if (!$create) { return null; } $this->rowDimensions[$pRow] = new RowDimension($pRow); $this->cachedHighestRow = max($this->cachedHighestRow, $pRow); } return $this->rowDimensions[$pRow]; } /** * Get column dimension at a specific column. * * @param string $pColumn String index of the column eg: 'A' * @param bool $create * * @return ColumnDimension */ public function getColumnDimension($pColumn, $create = true) { // Uppercase coordinate $pColumn = strtoupper($pColumn); // Fetch dimensions if (!isset($this->columnDimensions[$pColumn])) { if (!$create) { return null; } $this->columnDimensions[$pColumn] = new ColumnDimension($pColumn); if (Coordinate::columnIndexFromString($this->cachedHighestColumn) < Coordinate::columnIndexFromString($pColumn)) { $this->cachedHighestColumn = $pColumn; } } return $this->columnDimensions[$pColumn]; } /** * Get column dimension at a specific column by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * * @return ColumnDimension */ public function getColumnDimensionByColumn($columnIndex) { return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex)); } /** * Get styles. * * @return Style[] */ public function getStyles() { return $this->styles; } /** * Get style for cell. * * @param string $pCellCoordinate Cell coordinate (or range) to get style for, eg: 'A1' * * @throws Exception * * @return Style */ public function getStyle($pCellCoordinate) { // set this sheet as active $this->parent->setActiveSheetIndex($this->parent->getIndex($this)); // set cell coordinate as active $this->setSelectedCells(strtoupper($pCellCoordinate)); return $this->parent->getCellXfSupervisor(); } /** * Get conditional styles for a cell. * * @param string $pCoordinate eg: 'A1' * * @return Conditional[] */ public function getConditionalStyles($pCoordinate) { $pCoordinate = strtoupper($pCoordinate); if (!isset($this->conditionalStylesCollection[$pCoordinate])) { $this->conditionalStylesCollection[$pCoordinate] = []; } return $this->conditionalStylesCollection[$pCoordinate]; } /** * Do conditional styles exist for this cell? * * @param string $pCoordinate eg: 'A1' * * @return bool */ public function conditionalStylesExists($pCoordinate) { return isset($this->conditionalStylesCollection[strtoupper($pCoordinate)]); } /** * Removes conditional styles for a cell. * * @param string $pCoordinate eg: 'A1' * * @return Worksheet */ public function removeConditionalStyles($pCoordinate) { unset($this->conditionalStylesCollection[strtoupper($pCoordinate)]); return $this; } /** * Get collection of conditional styles. * * @return array */ public function getConditionalStylesCollection() { return $this->conditionalStylesCollection; } /** * Set conditional styles. * * @param string $pCoordinate eg: 'A1' * @param $pValue Conditional[] * * @return Worksheet */ public function setConditionalStyles($pCoordinate, $pValue) { $this->conditionalStylesCollection[strtoupper($pCoordinate)] = $pValue; return $this; } /** * Get style for cell by using numeric cell coordinates. * * @param int $columnIndex1 Numeric column coordinate of the cell * @param int $row1 Numeric row coordinate of the cell * @param null|int $columnIndex2 Numeric column coordinate of the range cell * @param null|int $row2 Numeric row coordinate of the range cell * * @return Style */ public function getStyleByColumnAndRow($columnIndex1, $row1, $columnIndex2 = null, $row2 = null) { if ($columnIndex2 !== null && $row2 !== null) { $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2; return $this->getStyle($cellRange); } return $this->getStyle(Coordinate::stringFromColumnIndex($columnIndex1) . $row1); } /** * Duplicate cell style to a range of cells. * * Please note that this will overwrite existing cell styles for cells in range! * * @param Style $pCellStyle Cell style to duplicate * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * * @throws Exception * * @return Worksheet */ public function duplicateStyle(Style $pCellStyle, $pRange) { // Add the style to the workbook if necessary $workbook = $this->parent; if ($existingStyle = $this->parent->getCellXfByHashCode($pCellStyle->getHashCode())) { // there is already such cell Xf in our collection $xfIndex = $existingStyle->getIndex(); } else { // we don't have such a cell Xf, need to add $workbook->addCellXf($pCellStyle); $xfIndex = $pCellStyle->getIndex(); } // Calculate range outer borders list($rangeStart, $rangeEnd) = Coordinate::rangeBoundaries($pRange . ':' . $pRange); // Make sure we can loop upwards on rows and columns if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { $tmp = $rangeStart; $rangeStart = $rangeEnd; $rangeEnd = $tmp; } // Loop through cells and apply styles for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { $this->getCell(Coordinate::stringFromColumnIndex($col) . $row)->setXfIndex($xfIndex); } } return $this; } /** * Duplicate conditional style to a range of cells. * * Please note that this will overwrite existing cell styles for cells in range! * * @param Conditional[] $pCellStyle Cell style to duplicate * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * * @throws Exception * * @return Worksheet */ public function duplicateConditionalStyle(array $pCellStyle, $pRange = '') { foreach ($pCellStyle as $cellStyle) { if (!($cellStyle instanceof Conditional)) { throw new Exception('Style is not a conditional style'); } } // Calculate range outer borders list($rangeStart, $rangeEnd) = Coordinate::rangeBoundaries($pRange . ':' . $pRange); // Make sure we can loop upwards on rows and columns if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { $tmp = $rangeStart; $rangeStart = $rangeEnd; $rangeEnd = $tmp; } // Loop through cells and apply styles for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { $this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $pCellStyle); } } return $this; } /** * Set break on a cell. * * @param string $pCoordinate Cell coordinate (e.g. A1) * @param int $pBreak Break type (type of Worksheet::BREAK_*) * * @throws Exception * * @return Worksheet */ public function setBreak($pCoordinate, $pBreak) { // Uppercase coordinate $pCoordinate = strtoupper($pCoordinate); if ($pCoordinate != '') { if ($pBreak == self::BREAK_NONE) { if (isset($this->breaks[$pCoordinate])) { unset($this->breaks[$pCoordinate]); } } else { $this->breaks[$pCoordinate] = $pBreak; } } else { throw new Exception('No cell coordinate specified.'); } return $this; } /** * Set break on a cell by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param int $break Break type (type of Worksheet::BREAK_*) * * @return Worksheet */ public function setBreakByColumnAndRow($columnIndex, $row, $break) { return $this->setBreak(Coordinate::stringFromColumnIndex($columnIndex) . $row, $break); } /** * Get breaks. * * @return array[] */ public function getBreaks() { return $this->breaks; } /** * Set merge on a cell range. * * @param string $pRange Cell range (e.g. A1:E1) * * @throws Exception * * @return Worksheet */ public function mergeCells($pRange) { // Uppercase coordinate $pRange = strtoupper($pRange); if (strpos($pRange, ':') !== false) { $this->mergeCells[$pRange] = $pRange; // make sure cells are created // get the cells in the range $aReferences = Coordinate::extractAllCellReferencesInRange($pRange); // create upper left cell if it does not already exist $upperLeft = $aReferences[0]; if (!$this->cellExists($upperLeft)) { $this->getCell($upperLeft)->setValueExplicit(null, DataType::TYPE_NULL); } // Blank out the rest of the cells in the range (if they exist) $count = count($aReferences); for ($i = 1; $i < $count; ++$i) { if ($this->cellExists($aReferences[$i])) { $this->getCell($aReferences[$i])->setValueExplicit(null, DataType::TYPE_NULL); } } } else { throw new Exception('Merge must be set on a range of cells.'); } return $this; } /** * Set merge on a cell range by using numeric cell coordinates. * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * * @throws Exception * * @return Worksheet */ public function mergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2) { $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2; return $this->mergeCells($cellRange); } /** * Remove merge on a cell range. * * @param string $pRange Cell range (e.g. A1:E1) * * @throws Exception * * @return Worksheet */ public function unmergeCells($pRange) { // Uppercase coordinate $pRange = strtoupper($pRange); if (strpos($pRange, ':') !== false) { if (isset($this->mergeCells[$pRange])) { unset($this->mergeCells[$pRange]); } else { throw new Exception('Cell range ' . $pRange . ' not known as merged.'); } } else { throw new Exception('Merge can only be removed from a range of cells.'); } return $this; } /** * Remove merge on a cell range by using numeric cell coordinates. * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * * @throws Exception * * @return Worksheet */ public function unmergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2) { $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2; return $this->unmergeCells($cellRange); } /** * Get merge cells array. * * @return array[] */ public function getMergeCells() { return $this->mergeCells; } /** * Set merge cells array for the entire sheet. Use instead mergeCells() to merge * a single cell range. * * @param array $pValue * * @return Worksheet */ public function setMergeCells(array $pValue) { $this->mergeCells = $pValue; return $this; } /** * Set protection on a cell range. * * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1) * @param string $pPassword Password to unlock the protection * @param bool $pAlreadyHashed If the password has already been hashed, set this to true * * @return Worksheet */ public function protectCells($pRange, $pPassword, $pAlreadyHashed = false) { // Uppercase coordinate $pRange = strtoupper($pRange); if (!$pAlreadyHashed) { $pPassword = Shared\PasswordHasher::hashPassword($pPassword); } $this->protectedCells[$pRange] = $pPassword; return $this; } /** * Set protection on a cell range by using numeric cell coordinates. * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * @param string $password Password to unlock the protection * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return Worksheet */ public function protectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2, $password, $alreadyHashed = false) { $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2; return $this->protectCells($cellRange, $password, $alreadyHashed); } /** * Remove protection on a cell range. * * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1) * * @throws Exception * * @return Worksheet */ public function unprotectCells($pRange) { // Uppercase coordinate $pRange = strtoupper($pRange); if (isset($this->protectedCells[$pRange])) { unset($this->protectedCells[$pRange]); } else { throw new Exception('Cell range ' . $pRange . ' not known as protected.'); } return $this; } /** * Remove protection on a cell range by using numeric cell coordinates. * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * * @throws Exception * * @return Worksheet */ public function unprotectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2) { $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2; return $this->unprotectCells($cellRange); } /** * Get protected cells. * * @return array[] */ public function getProtectedCells() { return $this->protectedCells; } /** * Get Autofilter. * * @return AutoFilter */ public function getAutoFilter() { return $this->autoFilter; } /** * Set AutoFilter. * * @param AutoFilter|string $pValue * A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility * * @throws Exception * * @return Worksheet */ public function setAutoFilter($pValue) { if (is_string($pValue)) { $this->autoFilter->setRange($pValue); } elseif (is_object($pValue) && ($pValue instanceof AutoFilter)) { $this->autoFilter = $pValue; } return $this; } /** * Set Autofilter Range by using numeric cell coordinates. * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the second cell * @param int $row2 Numeric row coordinate of the second cell * * @throws Exception * * @return Worksheet */ public function setAutoFilterByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2) { return $this->setAutoFilter( Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2 ); } /** * Remove autofilter. * * @return Worksheet */ public function removeAutoFilter() { $this->autoFilter->setRange(null); return $this; } /** * Get Freeze Pane. * * @return string */ public function getFreezePane() { return $this->freezePane; } /** * Freeze Pane. * * Examples: * * - A2 will freeze the rows above cell A2 (i.e row 1) * - B1 will freeze the columns to the left of cell B1 (i.e column A) * - B2 will freeze the rows above and to the left of cell B2 (i.e row 1 and column A) * * @param null|string $cell Position of the split * @param null|string $topLeftCell default position of the right bottom pane * * @throws Exception * * @return Worksheet */ public function freezePane($cell, $topLeftCell = null) { if (is_string($cell) && Coordinate::coordinateIsRange($cell)) { throw new Exception('Freeze pane can not be set on a range of cells.'); } if ($cell !== null && $topLeftCell === null) { $coordinate = Coordinate::coordinateFromString($cell); $topLeftCell = $coordinate[0] . $coordinate[1]; } $this->freezePane = $cell; $this->topLeftCell = $topLeftCell; return $this; } /** * Freeze Pane by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * * @return Worksheet */ public function freezePaneByColumnAndRow($columnIndex, $row) { return $this->freezePane(Coordinate::stringFromColumnIndex($columnIndex) . $row); } /** * Unfreeze Pane. * * @return Worksheet */ public function unfreezePane() { return $this->freezePane(null); } /** * Get the default position of the right bottom pane. * * @return int */ public function getTopLeftCell() { return $this->topLeftCell; } /** * Insert a new row, updating all possible related data. * * @param int $pBefore Insert before this one * @param int $pNumRows Number of rows to insert * * @throws Exception * * @return Worksheet */ public function insertNewRowBefore($pBefore, $pNumRows = 1) { if ($pBefore >= 1) { $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this); } else { throw new Exception('Rows can only be inserted before at least row 1.'); } return $this; } /** * Insert a new column, updating all possible related data. * * @param string $pBefore Insert before this one, eg: 'A' * @param int $pNumCols Number of columns to insert * * @throws Exception * * @return Worksheet */ public function insertNewColumnBefore($pBefore, $pNumCols = 1) { if (!is_numeric($pBefore)) { $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore($pBefore . '1', $pNumCols, 0, $this); } else { throw new Exception('Column references should not be numeric.'); } return $this; } /** * Insert a new column, updating all possible related data. * * @param int $beforeColumnIndex Insert before this one (numeric column coordinate of the cell) * @param int $pNumCols Number of columns to insert * * @throws Exception * * @return Worksheet */ public function insertNewColumnBeforeByIndex($beforeColumnIndex, $pNumCols = 1) { if ($beforeColumnIndex >= 1) { return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $pNumCols); } throw new Exception('Columns can only be inserted before at least column A (1).'); } /** * Delete a row, updating all possible related data. * * @param int $pRow Remove starting with this one * @param int $pNumRows Number of rows to remove * * @throws Exception * * @return Worksheet */ public function removeRow($pRow, $pNumRows = 1) { if ($pRow >= 1) { $highestRow = $this->getHighestDataRow(); $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore('A' . ($pRow + $pNumRows), 0, -$pNumRows, $this); for ($r = 0; $r < $pNumRows; ++$r) { $this->getCellCollection()->removeRow($highestRow); --$highestRow; } } else { throw new Exception('Rows to be deleted should at least start from row 1.'); } return $this; } /** * Remove a column, updating all possible related data. * * @param string $pColumn Remove starting with this one, eg: 'A' * @param int $pNumCols Number of columns to remove * * @throws Exception * * @return Worksheet */ public function removeColumn($pColumn, $pNumCols = 1) { if (!is_numeric($pColumn)) { $highestColumn = $this->getHighestDataColumn(); $pColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($pColumn) + $pNumCols); $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore($pColumn . '1', -$pNumCols, 0, $this); for ($c = 0; $c < $pNumCols; ++$c) { $this->getCellCollection()->removeColumn($highestColumn); $highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1); } } else { throw new Exception('Column references should not be numeric.'); } return $this; } /** * Remove a column, updating all possible related data. * * @param int $columnIndex Remove starting with this one (numeric column coordinate of the cell) * @param int $numColumns Number of columns to remove * * @throws Exception * * @return Worksheet */ public function removeColumnByIndex($columnIndex, $numColumns = 1) { if ($columnIndex >= 1) { return $this->removeColumn(Coordinate::stringFromColumnIndex($columnIndex), $numColumns); } throw new Exception('Columns to be deleted should at least start from column A (1)'); } /** * Show gridlines? * * @return bool */ public function getShowGridlines() { return $this->showGridlines; } /** * Set show gridlines. * * @param bool $pValue Show gridlines (true/false) * * @return Worksheet */ public function setShowGridlines($pValue) { $this->showGridlines = $pValue; return $this; } /** * Print gridlines? * * @return bool */ public function getPrintGridlines() { return $this->printGridlines; } /** * Set print gridlines. * * @param bool $pValue Print gridlines (true/false) * * @return Worksheet */ public function setPrintGridlines($pValue) { $this->printGridlines = $pValue; return $this; } /** * Show row and column headers? * * @return bool */ public function getShowRowColHeaders() { return $this->showRowColHeaders; } /** * Set show row and column headers. * * @param bool $pValue Show row and column headers (true/false) * * @return Worksheet */ public function setShowRowColHeaders($pValue) { $this->showRowColHeaders = $pValue; return $this; } /** * Show summary below? (Row/Column outlining). * * @return bool */ public function getShowSummaryBelow() { return $this->showSummaryBelow; } /** * Set show summary below. * * @param bool $pValue Show summary below (true/false) * * @return Worksheet */ public function setShowSummaryBelow($pValue) { $this->showSummaryBelow = $pValue; return $this; } /** * Show summary right? (Row/Column outlining). * * @return bool */ public function getShowSummaryRight() { return $this->showSummaryRight; } /** * Set show summary right. * * @param bool $pValue Show summary right (true/false) * * @return Worksheet */ public function setShowSummaryRight($pValue) { $this->showSummaryRight = $pValue; return $this; } /** * Get comments. * * @return Comment[] */ public function getComments() { return $this->comments; } /** * Set comments array for the entire sheet. * * @param Comment[] $pValue * * @return Worksheet */ public function setComments(array $pValue) { $this->comments = $pValue; return $this; } /** * Get comment for cell. * * @param string $pCellCoordinate Cell coordinate to get comment for, eg: 'A1' * * @throws Exception * * @return Comment */ public function getComment($pCellCoordinate) { // Uppercase coordinate $pCellCoordinate = strtoupper($pCellCoordinate); if (Coordinate::coordinateIsRange($pCellCoordinate)) { throw new Exception('Cell coordinate string can not be a range of cells.'); } elseif (strpos($pCellCoordinate, '$') !== false) { throw new Exception('Cell coordinate string must not be absolute.'); } elseif ($pCellCoordinate == '') { throw new Exception('Cell coordinate can not be zero-length string.'); } // Check if we already have a comment for this cell. if (isset($this->comments[$pCellCoordinate])) { return $this->comments[$pCellCoordinate]; } // If not, create a new comment. $newComment = new Comment(); $this->comments[$pCellCoordinate] = $newComment; return $newComment; } /** * Get comment for cell by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * * @return Comment */ public function getCommentByColumnAndRow($columnIndex, $row) { return $this->getComment(Coordinate::stringFromColumnIndex($columnIndex) . $row); } /** * Get active cell. * * @return string Example: 'A1' */ public function getActiveCell() { return $this->activeCell; } /** * Get selected cells. * * @return string */ public function getSelectedCells() { return $this->selectedCells; } /** * Selected cell. * * @param string $pCoordinate Cell (i.e. A1) * * @return Worksheet */ public function setSelectedCell($pCoordinate) { return $this->setSelectedCells($pCoordinate); } /** * Select a range of cells. * * @param string $pCoordinate Cell range, examples: 'A1', 'B2:G5', 'A:C', '3:6' * * @return Worksheet */ public function setSelectedCells($pCoordinate) { // Uppercase coordinate $pCoordinate = strtoupper($pCoordinate); // Convert 'A' to 'A:A' $pCoordinate = preg_replace('/^([A-Z]+)$/', '${1}:${1}', $pCoordinate); // Convert '1' to '1:1' $pCoordinate = preg_replace('/^(\d+)$/', '${1}:${1}', $pCoordinate); // Convert 'A:C' to 'A1:C1048576' $pCoordinate = preg_replace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $pCoordinate); // Convert '1:3' to 'A1:XFD3' $pCoordinate = preg_replace('/^(\d+):(\d+)$/', 'A${1}:XFD${2}', $pCoordinate); if (Coordinate::coordinateIsRange($pCoordinate)) { list($first) = Coordinate::splitRange($pCoordinate); $this->activeCell = $first[0]; } else { $this->activeCell = $pCoordinate; } $this->selectedCells = $pCoordinate; return $this; } /** * Selected cell by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * * @throws Exception * * @return Worksheet */ public function setSelectedCellByColumnAndRow($columnIndex, $row) { return $this->setSelectedCells(Coordinate::stringFromColumnIndex($columnIndex) . $row); } /** * Get right-to-left. * * @return bool */ public function getRightToLeft() { return $this->rightToLeft; } /** * Set right-to-left. * * @param bool $value Right-to-left true/false * * @return Worksheet */ public function setRightToLeft($value) { $this->rightToLeft = $value; return $this; } /** * Fill worksheet from values in array. * * @param array $source Source array * @param mixed $nullValue Value in source array that stands for blank cell * @param string $startCell Insert array starting from this cell address as the top left coordinate * @param bool $strictNullComparison Apply strict comparison when testing for null values in the array * * @throws Exception * * @return Worksheet */ public function fromArray(array $source, $nullValue = null, $startCell = 'A1', $strictNullComparison = false) { // Convert a 1-D array to 2-D (for ease of looping) if (!is_array(end($source))) { $source = [$source]; } // start coordinate list($startColumn, $startRow) = Coordinate::coordinateFromString($startCell); // Loop through $source foreach ($source as $rowData) { $currentColumn = $startColumn; foreach ($rowData as $cellValue) { if ($strictNullComparison) { if ($cellValue !== $nullValue) { // Set cell value $this->getCell($currentColumn . $startRow)->setValue($cellValue); } } else { if ($cellValue != $nullValue) { // Set cell value $this->getCell($currentColumn . $startRow)->setValue($cellValue); } } ++$currentColumn; } ++$startRow; } return $this; } /** * Create array from a range of cells. * * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * * @return array */ public function rangeToArray($pRange, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) { // Returnvalue $returnValue = []; // Identify the range that we need to extract from the worksheet list($rangeStart, $rangeEnd) = Coordinate::rangeBoundaries($pRange); $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]); $minRow = $rangeStart[1]; $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]); $maxRow = $rangeEnd[1]; ++$maxCol; // Loop through rows $r = -1; for ($row = $minRow; $row <= $maxRow; ++$row) { $rRef = ($returnCellRef) ? $row : ++$r; $c = -1; // Loop through columns in the current row for ($col = $minCol; $col != $maxCol; ++$col) { $cRef = ($returnCellRef) ? $col : ++$c; // Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen // so we test and retrieve directly against cellCollection if ($this->cellCollection->has($col . $row)) { // Cell exists $cell = $this->cellCollection->get($col . $row); if ($cell->getValue() !== null) { if ($cell->getValue() instanceof RichText) { $returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText(); } else { if ($calculateFormulas) { $returnValue[$rRef][$cRef] = $cell->getCalculatedValue(); } else { $returnValue[$rRef][$cRef] = $cell->getValue(); } } if ($formatData) { $style = $this->parent->getCellXfByIndex($cell->getXfIndex()); $returnValue[$rRef][$cRef] = NumberFormat::toFormattedString( $returnValue[$rRef][$cRef], ($style && $style->getNumberFormat()) ? $style->getNumberFormat()->getFormatCode() : NumberFormat::FORMAT_GENERAL ); } } else { // Cell holds a NULL $returnValue[$rRef][$cRef] = $nullValue; } } else { // Cell doesn't exist $returnValue[$rRef][$cRef] = $nullValue; } } } // Return return $returnValue; } /** * Create array from a range of cells. * * @param string $pNamedRange Name of the Named Range * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * * @throws Exception * * @return array */ public function namedRangeToArray($pNamedRange, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) { $namedRange = NamedRange::resolveRange($pNamedRange, $this); if ($namedRange !== null) { $pWorkSheet = $namedRange->getWorksheet(); $pCellRange = $namedRange->getRange(); return $pWorkSheet->rangeToArray($pCellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef); } throw new Exception('Named Range ' . $pNamedRange . ' does not exist.'); } /** * Create array from worksheet. * * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * * @return array */ public function toArray($nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) { // Garbage collect... $this->garbageCollect(); // Identify the range that we need to extract from the worksheet $maxCol = $this->getHighestColumn(); $maxRow = $this->getHighestRow(); // Return return $this->rangeToArray('A1:' . $maxCol . $maxRow, $nullValue, $calculateFormulas, $formatData, $returnCellRef); } /** * Get row iterator. * * @param int $startRow The row number at which to start iterating * @param int $endRow The row number at which to stop iterating * * @return RowIterator */ public function getRowIterator($startRow = 1, $endRow = null) { return new RowIterator($this, $startRow, $endRow); } /** * Get column iterator. * * @param string $startColumn The column address at which to start iterating * @param string $endColumn The column address at which to stop iterating * * @return ColumnIterator */ public function getColumnIterator($startColumn = 'A', $endColumn = null) { return new ColumnIterator($this, $startColumn, $endColumn); } /** * Run PhpSpreadsheet garbage collector. * * @return Worksheet */ public function garbageCollect() { // Flush cache $this->cellCollection->get('A1'); // Lookup highest column and highest row if cells are cleaned $colRow = $this->cellCollection->getHighestRowAndColumn(); $highestRow = $colRow['row']; $highestColumn = Coordinate::columnIndexFromString($colRow['column']); // Loop through column dimensions foreach ($this->columnDimensions as $dimension) { $highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex())); } // Loop through row dimensions foreach ($this->rowDimensions as $dimension) { $highestRow = max($highestRow, $dimension->getRowIndex()); } // Cache values if ($highestColumn < 1) { $this->cachedHighestColumn = 'A'; } else { $this->cachedHighestColumn = Coordinate::stringFromColumnIndex($highestColumn); } $this->cachedHighestRow = $highestRow; // Return return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { if ($this->dirty) { $this->hash = md5($this->title . $this->autoFilter . ($this->protection->isProtectionEnabled() ? 't' : 'f') . __CLASS__); $this->dirty = false; } return $this->hash; } /** * Extract worksheet title from range. * * Example: extractSheetTitle("testSheet!A1") ==> 'A1' * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1']; * * @param string $pRange Range to extract title from * @param bool $returnRange Return range? (see example) * * @return mixed */ public static function extractSheetTitle($pRange, $returnRange = false) { // Sheet title included? if (($sep = strrpos($pRange, '!')) === false) { return $returnRange ? ['', $pRange] : ''; } if ($returnRange) { return [substr($pRange, 0, $sep), substr($pRange, $sep + 1)]; } return substr($pRange, $sep + 1); } /** * Get hyperlink. * * @param string $pCellCoordinate Cell coordinate to get hyperlink for, eg: 'A1' * * @return Hyperlink */ public function getHyperlink($pCellCoordinate) { // return hyperlink if we already have one if (isset($this->hyperlinkCollection[$pCellCoordinate])) { return $this->hyperlinkCollection[$pCellCoordinate]; } // else create hyperlink $this->hyperlinkCollection[$pCellCoordinate] = new Hyperlink(); return $this->hyperlinkCollection[$pCellCoordinate]; } /** * Set hyperlink. * * @param string $pCellCoordinate Cell coordinate to insert hyperlink, eg: 'A1' * @param null|Hyperlink $pHyperlink * * @return Worksheet */ public function setHyperlink($pCellCoordinate, Hyperlink $pHyperlink = null) { if ($pHyperlink === null) { unset($this->hyperlinkCollection[$pCellCoordinate]); } else { $this->hyperlinkCollection[$pCellCoordinate] = $pHyperlink; } return $this; } /** * Hyperlink at a specific coordinate exists? * * @param string $pCoordinate eg: 'A1' * * @return bool */ public function hyperlinkExists($pCoordinate) { return isset($this->hyperlinkCollection[$pCoordinate]); } /** * Get collection of hyperlinks. * * @return Hyperlink[] */ public function getHyperlinkCollection() { return $this->hyperlinkCollection; } /** * Get data validation. * * @param string $pCellCoordinate Cell coordinate to get data validation for, eg: 'A1' * * @return DataValidation */ public function getDataValidation($pCellCoordinate) { // return data validation if we already have one if (isset($this->dataValidationCollection[$pCellCoordinate])) { return $this->dataValidationCollection[$pCellCoordinate]; } // else create data validation $this->dataValidationCollection[$pCellCoordinate] = new DataValidation(); return $this->dataValidationCollection[$pCellCoordinate]; } /** * Set data validation. * * @param string $pCellCoordinate Cell coordinate to insert data validation, eg: 'A1' * @param null|DataValidation $pDataValidation * * @return Worksheet */ public function setDataValidation($pCellCoordinate, DataValidation $pDataValidation = null) { if ($pDataValidation === null) { unset($this->dataValidationCollection[$pCellCoordinate]); } else { $this->dataValidationCollection[$pCellCoordinate] = $pDataValidation; } return $this; } /** * Data validation at a specific coordinate exists? * * @param string $pCoordinate eg: 'A1' * * @return bool */ public function dataValidationExists($pCoordinate) { return isset($this->dataValidationCollection[$pCoordinate]); } /** * Get collection of data validations. * * @return DataValidation[] */ public function getDataValidationCollection() { return $this->dataValidationCollection; } /** * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet. * * @param string $range * * @return string Adjusted range value */ public function shrinkRangeToFit($range) { $maxCol = $this->getHighestColumn(); $maxRow = $this->getHighestRow(); $maxCol = Coordinate::columnIndexFromString($maxCol); $rangeBlocks = explode(' ', $range); foreach ($rangeBlocks as &$rangeSet) { $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet); if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) { $rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol); } if ($rangeBoundaries[0][1] > $maxRow) { $rangeBoundaries[0][1] = $maxRow; } if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) { $rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol); } if ($rangeBoundaries[1][1] > $maxRow) { $rangeBoundaries[1][1] = $maxRow; } $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1]; } unset($rangeSet); $stRange = implode(' ', $rangeBlocks); return $stRange; } /** * Get tab color. * * @return Color */ public function getTabColor() { if ($this->tabColor === null) { $this->tabColor = new Color(); } return $this->tabColor; } /** * Reset tab color. * * @return Worksheet */ public function resetTabColor() { $this->tabColor = null; unset($this->tabColor); return $this; } /** * Tab color set? * * @return bool */ public function isTabColorSet() { return $this->tabColor !== null; } /** * Copy worksheet (!= clone!). * * @return Worksheet */ public function copy() { $copied = clone $this; return $copied; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { foreach ($this as $key => $val) { if ($key == 'parent') { continue; } if (is_object($val) || (is_array($val))) { if ($key == 'cellCollection') { $newCollection = $this->cellCollection->cloneCellCollection($this); $this->cellCollection = $newCollection; } elseif ($key == 'drawingCollection') { $currentCollection = $this->drawingCollection; $this->drawingCollection = new ArrayObject(); foreach ($currentCollection as $item) { if (is_object($item)) { $newDrawing = clone $item; $newDrawing->setWorksheet($this); } } } elseif (($key == 'autoFilter') && ($this->autoFilter instanceof AutoFilter)) { $newAutoFilter = clone $this->autoFilter; $this->autoFilter = $newAutoFilter; $this->autoFilter->setParent($this); } else { $this->{$key} = unserialize(serialize($val)); } } } } /** * Define the code name of the sheet. * * @param string $pValue Same rule as Title minus space not allowed (but, like Excel, change * silently space to underscore) * @param bool $validate False to skip validation of new title. WARNING: This should only be set * at parse time (by Readers), where titles can be assumed to be valid. * * @throws Exception * * @return Worksheet */ public function setCodeName($pValue, $validate = true) { // Is this a 'rename' or not? if ($this->getCodeName() == $pValue) { return $this; } if ($validate) { $pValue = str_replace(' ', '_', $pValue); //Excel does this automatically without flinching, we are doing the same // Syntax check // throw an exception if not valid self::checkSheetCodeName($pValue); // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_' if ($this->getParent()) { // Is there already such sheet name? if ($this->getParent()->sheetCodeNameExists($pValue)) { // Use name, but append with lowest possible integer if (Shared\StringHelper::countCharacters($pValue) > 29) { $pValue = Shared\StringHelper::substring($pValue, 0, 29); } $i = 1; while ($this->getParent()->sheetCodeNameExists($pValue . '_' . $i)) { ++$i; if ($i == 10) { if (Shared\StringHelper::countCharacters($pValue) > 28) { $pValue = Shared\StringHelper::substring($pValue, 0, 28); } } elseif ($i == 100) { if (Shared\StringHelper::countCharacters($pValue) > 27) { $pValue = Shared\StringHelper::substring($pValue, 0, 27); } } } $pValue = $pValue . '_' . $i; // ok, we have a valid name } } } $this->codeName = $pValue; return $this; } /** * Return the code name of the sheet. * * @return null|string */ public function getCodeName() { return $this->codeName; } /** * Sheet has a code name ? * * @return bool */ public function hasCodeName() { return $this->codeName !== null; } }
keithbox/AngularJS-CRUD-PHP
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php
PHP
mit
87,851
import {addClass, hasClass, empty} from './../helpers/dom/element'; import {eventManager as eventManagerObject} from './../eventManager'; import {getRenderer, registerRenderer} from './../renderers'; import {WalkontableCellCoords} from './../3rdparty/walkontable/src/cell/coords'; var clonableWRAPPER = document.createElement('DIV'); clonableWRAPPER.className = 'htAutocompleteWrapper'; var clonableARROW = document.createElement('DIV'); clonableARROW.className = 'htAutocompleteArrow'; // workaround for https://github.com/handsontable/handsontable/issues/1946 // this is faster than innerHTML. See: https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips clonableARROW.appendChild(document.createTextNode(String.fromCharCode(9660))); var wrapTdContentWithWrapper = function(TD, WRAPPER) { WRAPPER.innerHTML = TD.innerHTML; empty(TD); TD.appendChild(WRAPPER); }; /** * Autocomplete renderer * * @private * @renderer AutocompleteRenderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ function autocompleteRenderer(instance, TD, row, col, prop, value, cellProperties) { var WRAPPER = clonableWRAPPER.cloneNode(true); //this is faster than createElement var ARROW = clonableARROW.cloneNode(true); //this is faster than createElement getRenderer('text')(instance, TD, row, col, prop, value, cellProperties); TD.appendChild(ARROW); addClass(TD, 'htAutocomplete'); if (!TD.firstChild) { //http://jsperf.com/empty-node-if-needed //otherwise empty fields appear borderless in demo/renderers.html (IE) TD.appendChild(document.createTextNode(String.fromCharCode(160))); // workaround for https://github.com/handsontable/handsontable/issues/1946 //this is faster than innerHTML. See: https://github.com/handsontable/handsontable/wiki/JavaScript-&-DOM-performance-tips } if (!instance.acArrowListener) { var eventManager = eventManagerObject(instance); //not very elegant but easy and fast instance.acArrowListener = function(event) { if (hasClass(event.target, 'htAutocompleteArrow')) { instance.view.wt.getSetting('onCellDblClick', null, new WalkontableCellCoords(row, col), TD); } }; eventManager.addEventListener(instance.rootElement, 'mousedown', instance.acArrowListener); //We need to unbind the listener after the table has been destroyed instance.addHookOnce('afterDestroy', function() { eventManager.destroy(); }); } } export {autocompleteRenderer}; registerRenderer('autocomplete', autocompleteRenderer);
pingyuanChen/handsontable
src/renderers/autocompleteRenderer.js
JavaScript
mit
2,882
//---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------------------- namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Security; using SR = System.ServiceModel.SR; sealed class TransactionChannelFactory<TChannel> : LayeredChannelFactory<TChannel>, ITransactionChannelManager { TransactionFlowOption flowIssuedTokens; SecurityStandardsManager standardsManager; Dictionary<DirectionalAction, TransactionFlowOption> dictionary; TransactionProtocol transactionProtocol; bool allowWildcardAction; public TransactionChannelFactory( TransactionProtocol transactionProtocol, BindingContext context, Dictionary<DirectionalAction, TransactionFlowOption> dictionary, bool allowWildcardAction) : base(context.Binding, context.BuildInnerChannelFactory<TChannel>()) { this.dictionary = dictionary; this.TransactionProtocol = transactionProtocol; this.allowWildcardAction = allowWildcardAction; this.standardsManager = SecurityStandardsHelper.CreateStandardsManager(this.TransactionProtocol); } public TransactionProtocol TransactionProtocol { get { return this.transactionProtocol; } set { if (!TransactionProtocol.IsDefined(value)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentException(SR.GetString(SR.SFxBadTransactionProtocols))); this.transactionProtocol = value; } } public TransactionFlowOption FlowIssuedTokens { get { return this.flowIssuedTokens; } set { this.flowIssuedTokens = value; } } public SecurityStandardsManager StandardsManager { get { return this.standardsManager; } set { this.standardsManager = (value != null ? value : SecurityStandardsHelper.CreateStandardsManager(this.transactionProtocol)); } } public IDictionary<DirectionalAction, TransactionFlowOption> Dictionary { get { return this.dictionary; } } public TransactionFlowOption GetTransaction(MessageDirection direction, string action) { TransactionFlowOption txOption; if (!dictionary.TryGetValue(new DirectionalAction(direction, action), out txOption)) { //Fixinng this for clients that opted in for lesser validation before flowing out a transaction if (this.allowWildcardAction && dictionary.TryGetValue(new DirectionalAction(direction, MessageHeaders.WildcardAction), out txOption)) { return txOption; } else return TransactionFlowOption.NotAllowed; } else return txOption; } protected override TChannel OnCreateChannel(EndpointAddress remoteAddress, Uri via) { TChannel innerChannel = ((IChannelFactory<TChannel>)InnerChannelFactory).CreateChannel(remoteAddress, via); return CreateTransactionChannel(innerChannel); } TChannel CreateTransactionChannel(TChannel innerChannel) { if (typeof(TChannel) == typeof(IDuplexSessionChannel)) { return (TChannel)(object)new TransactionDuplexSessionChannel(this, (IDuplexSessionChannel)(object)innerChannel); } else if (typeof(TChannel) == typeof(IRequestSessionChannel)) { return (TChannel)(object)new TransactionRequestSessionChannel(this, (IRequestSessionChannel)(object)innerChannel); } else if (typeof(TChannel) == typeof(IOutputSessionChannel)) { return (TChannel)(object)new TransactionOutputSessionChannel(this, (IOutputSessionChannel)(object)innerChannel); } else if (typeof(TChannel) == typeof(IOutputChannel)) { return (TChannel)(object)new TransactionOutputChannel(this, (IOutputChannel)(object)innerChannel); } else if (typeof(TChannel) == typeof(IRequestChannel)) { return (TChannel)(object)new TransactionRequestChannel(this, (IRequestChannel)(object)innerChannel); } else if (typeof(TChannel) == typeof(IDuplexChannel)) { return (TChannel)(object)new TransactionDuplexChannel(this, (IDuplexChannel)(object)innerChannel); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateChannelTypeNotSupportedException(typeof(TChannel))); } } //=========================================================== // Transaction Output Channel classes //=========================================================== sealed class TransactionOutputChannel : TransactionOutputChannelGeneric<IOutputChannel> { public TransactionOutputChannel(ChannelManagerBase channelManager, IOutputChannel innerChannel) : base(channelManager, innerChannel) { } } sealed class TransactionRequestChannel : TransactionRequestChannelGeneric<IRequestChannel> { public TransactionRequestChannel(ChannelManagerBase channelManager, IRequestChannel innerChannel) : base(channelManager, innerChannel) { } } sealed class TransactionDuplexChannel : TransactionOutputDuplexChannelGeneric<IDuplexChannel> { public TransactionDuplexChannel(ChannelManagerBase channelManager, IDuplexChannel innerChannel) : base(channelManager, innerChannel) { } } sealed class TransactionOutputSessionChannel : TransactionOutputChannelGeneric<IOutputSessionChannel>, IOutputSessionChannel { public TransactionOutputSessionChannel(ChannelManagerBase channelManager, IOutputSessionChannel innerChannel) : base(channelManager, innerChannel) { } public IOutputSession Session { get { return InnerChannel.Session; } } } sealed class TransactionRequestSessionChannel : TransactionRequestChannelGeneric<IRequestSessionChannel>, IRequestSessionChannel { public TransactionRequestSessionChannel(ChannelManagerBase channelManager, IRequestSessionChannel innerChannel) : base(channelManager, innerChannel) { } public IOutputSession Session { get { return InnerChannel.Session; } } } sealed class TransactionDuplexSessionChannel : TransactionOutputDuplexChannelGeneric<IDuplexSessionChannel>, IDuplexSessionChannel { public TransactionDuplexSessionChannel(ChannelManagerBase channelManager, IDuplexSessionChannel innerChannel) : base(channelManager, innerChannel) { } public IDuplexSession Session { get { return InnerChannel.Session; } } } } static class SecurityStandardsHelper { static SecurityStandardsManager SecurityStandardsManager2007 = CreateStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12); static SecurityStandardsManager CreateStandardsManager(MessageSecurityVersion securityVersion) { return new SecurityStandardsManager( securityVersion, new WSSecurityTokenSerializer(securityVersion.SecurityVersion, securityVersion.TrustVersion, securityVersion.SecureConversationVersion, false, null, null, null)); } public static SecurityStandardsManager CreateStandardsManager(TransactionProtocol transactionProtocol) { if (transactionProtocol == TransactionProtocol.WSAtomicTransactionOctober2004 || transactionProtocol == TransactionProtocol.OleTransactions) { return SecurityStandardsManager.DefaultInstance; } else { return SecurityStandardsHelper.SecurityStandardsManager2007; } } } //============================================================== // Transaction channel base generic classes //============================================================== class TransactionOutputChannelGeneric<TChannel> : TransactionChannel<TChannel>, IOutputChannel where TChannel : class, IOutputChannel { public TransactionOutputChannelGeneric(ChannelManagerBase channelManager, TChannel innerChannel) : base(channelManager, innerChannel) { } public EndpointAddress RemoteAddress { get { return InnerChannel.RemoteAddress; } } public Uri Via { get { return InnerChannel.Via; } } public IAsyncResult BeginSend(Message message, AsyncCallback callback, object state) { return this.BeginSend(message, this.DefaultSendTimeout, callback, state); } public IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback asyncCallback, object state) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); WriteTransactionDataToMessage(message, MessageDirection.Input); return InnerChannel.BeginSend(message, timeoutHelper.RemainingTime(), asyncCallback, state); } public void EndSend(IAsyncResult result) { InnerChannel.EndSend(result); } public void Send(Message message) { this.Send(message, this.DefaultSendTimeout); } public void Send(Message message, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); WriteTransactionDataToMessage(message, MessageDirection.Input); InnerChannel.Send(message, timeoutHelper.RemainingTime()); } } class TransactionRequestChannelGeneric<TChannel> : TransactionChannel<TChannel>, IRequestChannel where TChannel : class, IRequestChannel { public TransactionRequestChannelGeneric(ChannelManagerBase channelManager, TChannel innerChannel) : base(channelManager, innerChannel) { } public EndpointAddress RemoteAddress { get { return InnerChannel.RemoteAddress; } } public Uri Via { get { return InnerChannel.Via; } } public IAsyncResult BeginRequest(Message message, AsyncCallback callback, object state) { return this.BeginRequest(message, this.DefaultSendTimeout, callback, state); } public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback asyncCallback, object state) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); WriteTransactionDataToMessage(message, MessageDirection.Input); return InnerChannel.BeginRequest(message, timeoutHelper.RemainingTime(), asyncCallback, state); } public Message EndRequest(IAsyncResult result) { Message reply = InnerChannel.EndRequest(result); if (reply != null) this.ReadIssuedTokens(reply, MessageDirection.Output); return reply; } public Message Request(Message message) { return this.Request(message, this.DefaultSendTimeout); } public Message Request(Message message, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); WriteTransactionDataToMessage(message, MessageDirection.Input); Message reply = InnerChannel.Request(message, timeoutHelper.RemainingTime()); if (reply != null) this.ReadIssuedTokens(reply, MessageDirection.Output); return reply; } } class TransactionOutputDuplexChannelGeneric<TChannel> : TransactionDuplexChannelGeneric<TChannel> where TChannel : class, IDuplexChannel { public TransactionOutputDuplexChannelGeneric(ChannelManagerBase channelManager, TChannel innerChannel) : base(channelManager, innerChannel, MessageDirection.Output) { } } }
sekcheong/referencesource
System.ServiceModel/System/ServiceModel/Channels/TransactionChannelFactory.cs
C#
mit
13,242
/* * Copyright (C) Igor Sysoev * Copyright (C) Nginx, Inc. */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> typedef struct { uint32_t percent; ngx_http_variable_value_t value; } ngx_http_split_clients_part_t; typedef struct { ngx_http_complex_value_t value; ngx_array_t parts; } ngx_http_split_clients_ctx_t; static char *ngx_conf_split_clients_block(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static char *ngx_http_split_clients(ngx_conf_t *cf, ngx_command_t *dummy, void *conf); static ngx_command_t ngx_http_split_clients_commands[] = { { ngx_string("split_clients"), NGX_HTTP_MAIN_CONF|NGX_CONF_BLOCK|NGX_CONF_TAKE2, ngx_conf_split_clients_block, NGX_HTTP_MAIN_CONF_OFFSET, 0, NULL }, ngx_null_command }; static ngx_http_module_t ngx_http_split_clients_module_ctx = { NULL, /* preconfiguration */ NULL, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ NULL, /* create location configuration */ NULL /* merge location configuration */ }; ngx_module_t ngx_http_split_clients_module = { NGX_MODULE_V1, &ngx_http_split_clients_module_ctx, /* module context */ ngx_http_split_clients_commands, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static ngx_int_t ngx_http_split_clients_variable(ngx_http_request_t *r, ngx_http_variable_value_t *v, uintptr_t data) { ngx_http_split_clients_ctx_t *ctx = (ngx_http_split_clients_ctx_t *) data; uint32_t hash; ngx_str_t val; ngx_uint_t i; ngx_http_split_clients_part_t *part; *v = ngx_http_variable_null_value; if (ngx_http_complex_value(r, &ctx->value, &val) != NGX_OK) { return NGX_OK; } hash = ngx_murmur_hash2(val.data, val.len); part = ctx->parts.elts; for (i = 0; i < ctx->parts.nelts; i++) { ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "http split: %uD %uD", hash, part[i].percent); if (hash < part[i].percent) { *v = part[i].value; return NGX_OK; } } return NGX_OK; } static char * ngx_conf_split_clients_block(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { char *rv; ngx_str_t *value, name; ngx_uint_t i, sum, last; ngx_conf_t save; ngx_http_variable_t *var; ngx_http_split_clients_ctx_t *ctx; ngx_http_split_clients_part_t *part; ngx_http_compile_complex_value_t ccv; ctx = ngx_pcalloc(cf->pool, sizeof(ngx_http_split_clients_ctx_t)); if (ctx == NULL) { return NGX_CONF_ERROR; } value = cf->args->elts; ngx_memzero(&ccv, sizeof(ngx_http_compile_complex_value_t)); ccv.cf = cf; ccv.value = &value[1]; ccv.complex_value = &ctx->value; if (ngx_http_compile_complex_value(&ccv) != NGX_OK) { return NGX_CONF_ERROR; } name = value[2]; name.len--; name.data++; var = ngx_http_add_variable(cf, &name, NGX_HTTP_VAR_CHANGEABLE); if (var == NULL) { return NGX_CONF_ERROR; } var->get_handler = ngx_http_split_clients_variable; var->data = (uintptr_t) ctx; if (ngx_array_init(&ctx->parts, cf->pool, 2, sizeof(ngx_http_split_clients_part_t)) != NGX_OK) { return NGX_CONF_ERROR; } save = *cf; cf->ctx = ctx; cf->handler = ngx_http_split_clients; cf->handler_conf = conf; rv = ngx_conf_parse(cf, NULL); *cf = save; if (rv != NGX_CONF_OK) { return rv; } sum = 0; last = 0; part = ctx->parts.elts; for (i = 0; i < ctx->parts.nelts; i++) { sum = part[i].percent ? sum + part[i].percent : 10000; if (sum > 10000) { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "percent sum is more than 100%%"); return NGX_CONF_ERROR; } if (part[i].percent) { part[i].percent = (uint32_t) (last + 0xffffffff / 10000 * part[i].percent); } else { part[i].percent = 0xffffffff; } last = part[i].percent; } return rv; } static char * ngx_http_split_clients(ngx_conf_t *cf, ngx_command_t *dummy, void *conf) { ngx_int_t n; ngx_str_t *value; ngx_http_split_clients_ctx_t *ctx; ngx_http_split_clients_part_t *part; ctx = cf->ctx; value = cf->args->elts; part = ngx_array_push(&ctx->parts); if (part == NULL) { return NGX_CONF_ERROR; } if (value[0].len == 1 && value[0].data[0] == '*') { part->percent = 0; } else { if (value[0].data[value[0].len - 1] != '%') { goto invalid; } n = ngx_atofp(value[0].data, value[0].len - 1, 2); if (n == NGX_ERROR || n == 0) { goto invalid; } part->percent = (uint32_t) n; } part->value.len = value[1].len; part->value.valid = 1; part->value.no_cacheable = 0; part->value.not_found = 0; part->value.data = value[1].data; return NGX_CONF_OK; invalid: ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "invalid percent value \"%V\"", &value[0]); return NGX_CONF_ERROR; }
huangjilaiqin/nginx
src/http/modules/ngx_http_split_clients_module.c
C
mit
6,443
module Jekyll class TagIndex < Page def initialize(site, base, dir, tag) @site = site @base = base @dir = dir @name = 'index.html' self.process(@name) self.read_yaml(File.join(base, '_layouts'), 'tag_index.html') self.data['tag'] = tag self.data['title'] = "Posts Tagged &ldquo;"+tag+"&rdquo;" end end class TagGenerator < Generator safe true def generate(site) if site.layouts.key? 'tag_index' dir = 'tags' site.tags.keys.each do |tag| write_tag_index(site, File.join(dir, tag), tag) end end end def write_tag_index(site, dir, tag) index = TagIndex.new(site, site.source, dir, tag) index.render(site.layouts, site.site_payload) index.write(site.dest) site.pages << index end end end
johnDorian/johnDorian.github.io
_plugins/tag_gen.rb
Ruby
mit
853
// The MIT License (MIT) // Copyright (c) 2013-2016 Rapptz, ThePhD and contributors // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef SOL_DEMANGLE_HPP #define SOL_DEMANGLE_HPP #include <string> #include <array> #include <cctype> namespace sol { namespace detail { #ifdef _MSC_VER template <typename T> inline std::string ctti_get_type_name() { const static std::array<std::string, 7> removals = { { "public:", "private:", "protected:", "struct ", "class ", "`anonymous-namespace'", "`anonymous namespace'" } }; std::string name = __FUNCSIG__; std::size_t start = name.find("get_type_name"); if (start == std::string::npos) start = 0; else start += 13; if (start < name.size() - 1) start += 1; std::size_t end = name.find_last_of('>'); if (end == std::string::npos) end = name.size(); name = name.substr(start, end - start); if (name.find("struct", 0) == 0) name.replace(0, 6, "", 0); if (name.find("class", 0) == 0) name.replace(0, 5, "", 0); while (!name.empty() && std::isblank(name.front())) name.erase(name.begin()); while (!name.empty() && std::isblank(name.back())) name.pop_back(); for (std::size_t r = 0; r < removals.size(); ++r) { auto found = name.find(removals[r]); while (found != std::string::npos) { name.erase(found, removals[r].size()); found = name.find(removals[r]); } } return name; } #elif defined(__GNUC__) || defined(__clang__) template <typename T, class seperator_mark = int> inline std::string ctti_get_type_name() { const static std::array<std::string, 2> removals = { { "{anonymous}", "(anonymous namespace)" } }; std::string name = __PRETTY_FUNCTION__; std::size_t start = name.find_first_of('['); start = name.find_first_of('=', start); std::size_t end = name.find_last_of(']'); if (end == std::string::npos) end = name.size(); if (start == std::string::npos) start = 0; if (start < name.size() - 1) start += 1; name = name.substr(start, end - start); start = name.rfind("seperator_mark"); if (start != std::string::npos) { name.erase(start - 2, name.length()); } while (!name.empty() && std::isblank(name.front())) name.erase(name.begin()); while (!name.empty() && std::isblank(name.back())) name.pop_back(); for (std::size_t r = 0; r < removals.size(); ++r) { auto found = name.find(removals[r]); while (found != std::string::npos) { name.erase(found, removals[r].size()); found = name.find(removals[r]); } } return name; } #else #error Compiler not supported for demangling #endif // compilers template <typename T> inline std::string demangle_once() { std::string realname = ctti_get_type_name<T>(); return realname; } template <typename T> inline std::string short_demangle_once() { std::string realname = ctti_get_type_name<T>(); // This isn't the most complete but it'll do for now...? static const std::array<std::string, 10> ops = { { "operator<", "operator<<", "operator<<=", "operator<=", "operator>", "operator>>", "operator>>=", "operator>=", "operator->", "operator->*" } }; int level = 0; std::ptrdiff_t idx = 0; for (idx = static_cast<std::ptrdiff_t>(realname.empty() ? 0 : realname.size() - 1); idx > 0; --idx) { if (level == 0 && realname[idx] == ':') { break; } bool isleft = realname[idx] == '<'; bool isright = realname[idx] == '>'; if (!isleft && !isright) continue; bool earlybreak = false; for (const auto& op : ops) { std::size_t nisop = realname.rfind(op, idx); if (nisop == std::string::npos) continue; std::size_t nisopidx = idx - op.size() + 1; if (nisop == nisopidx) { idx = static_cast<std::ptrdiff_t>(nisopidx); earlybreak = true; } break; } if (earlybreak) { continue; } level += isleft ? -1 : 1; } if (idx > 0) { realname.erase(0, realname.length() < static_cast<std::size_t>(idx) ? realname.length() : idx + 1); } return realname; } template <typename T> inline const std::string& demangle() { static const std::string d = demangle_once<T>(); return d; } template <typename T> inline const std::string& short_demangle() { static const std::string d = short_demangle_once<T>(); return d; } } // detail } // sol #endif // SOL_DEMANGLE_HPP
devxkh/FrankE
src/ThirdParty/sol/sol/demangle.hpp
C++
mit
5,420
var one = { name: 'one' };
inodient/summer-mvc
node_modules/dojo/tests/functional/_base/loader/requirejs/urlfetch/one.js
JavaScript
mit
28
/* * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.java2d.opengl; import java.awt.AlphaComposite; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import java.awt.Transparency; import java.awt.image.ColorModel; import java.awt.image.Raster; import sun.awt.SunHints; import sun.awt.image.PixelConverter; import sun.java2d.pipe.hw.AccelSurface; import sun.java2d.SunGraphics2D; import sun.java2d.SurfaceData; import sun.java2d.SurfaceDataProxy; import sun.java2d.loops.CompositeType; import sun.java2d.loops.GraphicsPrimitive; import sun.java2d.loops.MaskFill; import sun.java2d.loops.SurfaceType; import sun.java2d.pipe.ParallelogramPipe; import sun.java2d.pipe.PixelToParallelogramConverter; import sun.java2d.pipe.RenderBuffer; import sun.java2d.pipe.TextPipe; import static sun.java2d.pipe.BufferedOpCodes.*; import static sun.java2d.opengl.OGLContext.OGLContextCaps.*; /** * This class describes an OpenGL "surface", that is, a region of pixels * managed via OpenGL. An OGLSurfaceData can be tagged with one of three * different SurfaceType objects for the purpose of registering loops, etc. * This diagram shows the hierarchy of OGL SurfaceTypes: * * Any * / \ * OpenGLSurface OpenGLTexture * | * OpenGLSurfaceRTT * * OpenGLSurface * This kind of surface can be rendered to using OpenGL APIs. It is also * possible to copy an OpenGLSurface to another OpenGLSurface (or to itself). * This is typically accomplished by calling MakeContextCurrent(dstSD, srcSD) * and then calling glCopyPixels() (although there are other techniques to * achieve the same goal). * * OpenGLTexture * This kind of surface cannot be rendered to using OpenGL (in the same sense * as in OpenGLSurface). However, it is possible to upload a region of pixels * to an OpenGLTexture object via glTexSubImage2D(). One can also copy a * surface of type OpenGLTexture to an OpenGLSurface by binding the texture * to a quad and then rendering it to the destination surface (this process * is known as "texture mapping"). * * OpenGLSurfaceRTT * This kind of surface can be thought of as a sort of hybrid between * OpenGLSurface and OpenGLTexture, in that one can render to this kind of * surface as if it were of type OpenGLSurface, but the process of copying * this kind of surface to another is more like an OpenGLTexture. (Note that * "RTT" stands for "render-to-texture".) * * In addition to these SurfaceType variants, we have also defined some * constants that describe in more detail the type of underlying OpenGL * surface. This table helps explain the relationships between those * "type" constants and their corresponding SurfaceType: * * OGL Type Corresponding SurfaceType * -------- ------------------------- * WINDOW OpenGLSurface * PBUFFER OpenGLSurface * TEXTURE OpenGLTexture * FLIP_BACKBUFFER OpenGLSurface * FBOBJECT OpenGLSurfaceRTT */ public abstract class OGLSurfaceData extends SurfaceData implements AccelSurface { /** * OGL-specific surface types * * @see sun.java2d.pipe.hw.AccelSurface */ public static final int PBUFFER = RT_PLAIN; public static final int FBOBJECT = RT_TEXTURE; /** * Pixel formats */ public static final int PF_INT_ARGB = 0; public static final int PF_INT_ARGB_PRE = 1; public static final int PF_INT_RGB = 2; public static final int PF_INT_RGBX = 3; public static final int PF_INT_BGR = 4; public static final int PF_INT_BGRX = 5; public static final int PF_USHORT_565_RGB = 6; public static final int PF_USHORT_555_RGB = 7; public static final int PF_USHORT_555_RGBX = 8; public static final int PF_BYTE_GRAY = 9; public static final int PF_USHORT_GRAY = 10; public static final int PF_3BYTE_BGR = 11; /** * SurfaceTypes */ private static final String DESC_OPENGL_SURFACE = "OpenGL Surface"; private static final String DESC_OPENGL_SURFACE_RTT = "OpenGL Surface (render-to-texture)"; private static final String DESC_OPENGL_TEXTURE = "OpenGL Texture"; static final SurfaceType OpenGLSurface = SurfaceType.Any.deriveSubType(DESC_OPENGL_SURFACE, PixelConverter.ArgbPre.instance); static final SurfaceType OpenGLSurfaceRTT = OpenGLSurface.deriveSubType(DESC_OPENGL_SURFACE_RTT); static final SurfaceType OpenGLTexture = SurfaceType.Any.deriveSubType(DESC_OPENGL_TEXTURE); /** This will be true if the fbobject system property has been enabled. */ private static boolean isFBObjectEnabled; /** This will be true if the lcdshader system property has been enabled.*/ private static boolean isLCDShaderEnabled; /** This will be true if the biopshader system property has been enabled.*/ private static boolean isBIOpShaderEnabled; /** This will be true if the gradshader system property has been enabled.*/ private static boolean isGradShaderEnabled; private OGLGraphicsConfig graphicsConfig; protected int type; // these fields are set from the native code when the surface is // initialized private int nativeWidth, nativeHeight; protected static OGLRenderer oglRenderPipe; protected static PixelToParallelogramConverter oglTxRenderPipe; protected static ParallelogramPipe oglAAPgramPipe; protected static OGLTextRenderer oglTextPipe; protected static OGLDrawImage oglImagePipe; protected native boolean initTexture(long pData, boolean isOpaque, boolean texNonPow2, boolean texRect, int width, int height); protected native boolean initFBObject(long pData, boolean isOpaque, boolean texNonPow2, boolean texRect, int width, int height); protected native boolean initFlipBackbuffer(long pData); protected abstract boolean initPbuffer(long pData, long pConfigInfo, boolean isOpaque, int width, int height); private native int getTextureTarget(long pData); private native int getTextureID(long pData); static { if (!GraphicsEnvironment.isHeadless()) { // fbobject currently enabled by default; use "false" to disable String fbo = (String)java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction( "sun.java2d.opengl.fbobject")); isFBObjectEnabled = !"false".equals(fbo); // lcdshader currently enabled by default; use "false" to disable String lcd = (String)java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction( "sun.java2d.opengl.lcdshader")); isLCDShaderEnabled = !"false".equals(lcd); // biopshader currently enabled by default; use "false" to disable String biop = (String)java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction( "sun.java2d.opengl.biopshader")); isBIOpShaderEnabled = !"false".equals(biop); // gradshader currently enabled by default; use "false" to disable String grad = (String)java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction( "sun.java2d.opengl.gradshader")); isGradShaderEnabled = !"false".equals(grad); OGLRenderQueue rq = OGLRenderQueue.getInstance(); oglImagePipe = new OGLDrawImage(); oglTextPipe = new OGLTextRenderer(rq); oglRenderPipe = new OGLRenderer(rq); if (GraphicsPrimitive.tracingEnabled()) { oglTextPipe = oglTextPipe.traceWrap(); //The wrapped oglRenderPipe will wrap the AA pipe as well... //oglAAPgramPipe = oglRenderPipe.traceWrap(); } oglAAPgramPipe = oglRenderPipe.getAAParallelogramPipe(); oglTxRenderPipe = new PixelToParallelogramConverter(oglRenderPipe, oglRenderPipe, 1.0, 0.25, true); OGLBlitLoops.register(); OGLMaskFill.register(); OGLMaskBlit.register(); } } protected OGLSurfaceData(OGLGraphicsConfig gc, ColorModel cm, int type) { super(getCustomSurfaceType(type), cm); this.graphicsConfig = gc; this.type = type; setBlitProxyKey(gc.getProxyKey()); } @Override public SurfaceDataProxy makeProxyFor(SurfaceData srcData) { return OGLSurfaceDataProxy.createProxy(srcData, graphicsConfig); } /** * Returns the appropriate SurfaceType corresponding to the given OpenGL * surface type constant (e.g. TEXTURE -> OpenGLTexture). */ private static SurfaceType getCustomSurfaceType(int oglType) { switch (oglType) { case TEXTURE: return OpenGLTexture; case FBOBJECT: return OpenGLSurfaceRTT; case PBUFFER: default: return OpenGLSurface; } } /** * Note: This should only be called from the QFT under the AWT lock. * This method is kept separate from the initSurface() method below just * to keep the code a bit cleaner. */ private void initSurfaceNow(int width, int height) { boolean isOpaque = (getTransparency() == Transparency.OPAQUE); boolean success = false; switch (type) { case PBUFFER: success = initPbuffer(getNativeOps(), graphicsConfig.getNativeConfigInfo(), isOpaque, width, height); break; case TEXTURE: success = initTexture(getNativeOps(), isOpaque, isTexNonPow2Available(), isTexRectAvailable(), width, height); break; case FBOBJECT: success = initFBObject(getNativeOps(), isOpaque, isTexNonPow2Available(), isTexRectAvailable(), width, height); break; case FLIP_BACKBUFFER: success = initFlipBackbuffer(getNativeOps()); break; default: break; } if (!success) { throw new OutOfMemoryError("can't create offscreen surface"); } } /** * Initializes the appropriate OpenGL offscreen surface based on the value * of the type parameter. If the surface creation fails for any reason, * an OutOfMemoryError will be thrown. */ protected void initSurface(final int width, final int height) { OGLRenderQueue rq = OGLRenderQueue.getInstance(); rq.lock(); try { switch (type) { case TEXTURE: case PBUFFER: case FBOBJECT: // need to make sure the context is current before // creating the texture (or pbuffer, or fbobject) OGLContext.setScratchSurface(graphicsConfig); break; default: break; } rq.flushAndInvokeNow(new Runnable() { public void run() { initSurfaceNow(width, height); } }); } finally { rq.unlock(); } } /** * Returns the OGLContext for the GraphicsConfig associated with this * surface. */ public final OGLContext getContext() { return graphicsConfig.getContext(); } /** * Returns the OGLGraphicsConfig associated with this surface. */ final OGLGraphicsConfig getOGLGraphicsConfig() { return graphicsConfig; } /** * Returns one of the surface type constants defined above. */ public final int getType() { return type; } /** * If this surface is backed by a texture object, returns the target * for that texture (either GL_TEXTURE_2D or GL_TEXTURE_RECTANGLE_ARB). * Otherwise, this method will return zero. */ public final int getTextureTarget() { return getTextureTarget(getNativeOps()); } /** * If this surface is backed by a texture object, returns the texture ID * for that texture. * Otherwise, this method will return zero. */ public final int getTextureID() { return getTextureID(getNativeOps()); } /** * Returns native resource of specified {@code resType} associated with * this surface. * * Specifically, for {@code OGLSurfaceData} this method returns the * the following: * <pre> * TEXTURE - texture id * </pre> * * Note: the resource returned by this method is only valid on the rendering * thread. * * @return native resource of specified type or 0L if * such resource doesn't exist or can not be retrieved. * @see sun.java2d.pipe.hw.AccelSurface#getNativeResource */ public long getNativeResource(int resType) { if (resType == TEXTURE) { return getTextureID(); } return 0L; } public Raster getRaster(int x, int y, int w, int h) { throw new InternalError("not implemented yet"); } /** * For now, we can only render LCD text if: * - the fragment shader extension is available, and * - blending is disabled, and * - the source color is opaque * - and the destination is opaque * * Eventually, we could enhance the native OGL text rendering code * and remove the above restrictions, but that would require significantly * more code just to support a few uncommon cases. */ public boolean canRenderLCDText(SunGraphics2D sg2d) { return graphicsConfig.isCapPresent(CAPS_EXT_LCD_SHADER) && sg2d.compositeState <= SunGraphics2D.COMP_ISCOPY && sg2d.paintState <= SunGraphics2D.PAINT_OPAQUECOLOR && sg2d.surfaceData.getTransparency() == Transparency.OPAQUE; } public void validatePipe(SunGraphics2D sg2d) { TextPipe textpipe; boolean validated = false; // OGLTextRenderer handles both AA and non-AA text, but // only works with the following modes: // (Note: For LCD text we only enter this code path if // canRenderLCDText() has already validated that the mode is // CompositeType.SrcNoEa (opaque color), which will be subsumed // by the CompositeType.SrcNoEa (any color) test below.) if (/* CompositeType.SrcNoEa (any color) */ (sg2d.compositeState <= sg2d.COMP_ISCOPY && sg2d.paintState <= sg2d.PAINT_ALPHACOLOR) || /* CompositeType.SrcOver (any color) */ (sg2d.compositeState == sg2d.COMP_ALPHA && sg2d.paintState <= sg2d.PAINT_ALPHACOLOR && (((AlphaComposite)sg2d.composite).getRule() == AlphaComposite.SRC_OVER)) || /* CompositeType.Xor (any color) */ (sg2d.compositeState == sg2d.COMP_XOR && sg2d.paintState <= sg2d.PAINT_ALPHACOLOR)) { textpipe = oglTextPipe; } else { // do this to initialize textpipe correctly; we will attempt // to override the non-text pipes below super.validatePipe(sg2d); textpipe = sg2d.textpipe; validated = true; } PixelToParallelogramConverter txPipe = null; OGLRenderer nonTxPipe = null; if (sg2d.antialiasHint != SunHints.INTVAL_ANTIALIAS_ON) { if (sg2d.paintState <= sg2d.PAINT_ALPHACOLOR) { if (sg2d.compositeState <= sg2d.COMP_XOR) { txPipe = oglTxRenderPipe; nonTxPipe = oglRenderPipe; } } else if (sg2d.compositeState <= sg2d.COMP_ALPHA) { if (OGLPaints.isValid(sg2d)) { txPipe = oglTxRenderPipe; nonTxPipe = oglRenderPipe; } // custom paints handled by super.validatePipe() below } } else { if (sg2d.paintState <= sg2d.PAINT_ALPHACOLOR) { if (graphicsConfig.isCapPresent(CAPS_PS30) && (sg2d.imageComp == CompositeType.SrcOverNoEa || sg2d.imageComp == CompositeType.SrcOver)) { if (!validated) { super.validatePipe(sg2d); validated = true; } PixelToParallelogramConverter aaConverter = new PixelToParallelogramConverter(sg2d.shapepipe, oglAAPgramPipe, 1.0/8.0, 0.499, false); sg2d.drawpipe = aaConverter; sg2d.fillpipe = aaConverter; sg2d.shapepipe = aaConverter; } else if (sg2d.compositeState == sg2d.COMP_XOR) { // install the solid pipes when AA and XOR are both enabled txPipe = oglTxRenderPipe; nonTxPipe = oglRenderPipe; } } // other cases handled by super.validatePipe() below } if (txPipe != null) { if (sg2d.transformState >= sg2d.TRANSFORM_TRANSLATESCALE) { sg2d.drawpipe = txPipe; sg2d.fillpipe = txPipe; } else if (sg2d.strokeState != sg2d.STROKE_THIN) { sg2d.drawpipe = txPipe; sg2d.fillpipe = nonTxPipe; } else { sg2d.drawpipe = nonTxPipe; sg2d.fillpipe = nonTxPipe; } // Note that we use the transforming pipe here because it // will examine the shape and possibly perform an optimized // operation if it can be simplified. The simplifications // will be valid for all STROKE and TRANSFORM types. sg2d.shapepipe = txPipe; } else { if (!validated) { super.validatePipe(sg2d); } } // install the text pipe based on our earlier decision sg2d.textpipe = textpipe; // always override the image pipe with the specialized OGL pipe sg2d.imagepipe = oglImagePipe; } @Override protected MaskFill getMaskFill(SunGraphics2D sg2d) { if (sg2d.paintState > sg2d.PAINT_ALPHACOLOR) { /* * We can only accelerate non-Color MaskFill operations if * all of the following conditions hold true: * - there is an implementation for the given paintState * - the current Paint can be accelerated for this destination * - multitexturing is available (since we need to modulate * the alpha mask texture with the paint texture) * * In all other cases, we return null, in which case the * validation code will choose a more general software-based loop. */ if (!OGLPaints.isValid(sg2d) || !graphicsConfig.isCapPresent(CAPS_MULTITEXTURE)) { return null; } } return super.getMaskFill(sg2d); } public boolean copyArea(SunGraphics2D sg2d, int x, int y, int w, int h, int dx, int dy) { if (sg2d.transformState < sg2d.TRANSFORM_TRANSLATESCALE && sg2d.compositeState < sg2d.COMP_XOR) { x += sg2d.transX; y += sg2d.transY; oglRenderPipe.copyArea(sg2d, x, y, w, h, dx, dy); return true; } return false; } public void flush() { invalidate(); OGLRenderQueue rq = OGLRenderQueue.getInstance(); rq.lock(); try { // make sure we have a current context before // disposing the native resources (e.g. texture object) OGLContext.setScratchSurface(graphicsConfig); RenderBuffer buf = rq.getBuffer(); rq.ensureCapacityAndAlignment(12, 4); buf.putInt(FLUSH_SURFACE); buf.putLong(getNativeOps()); // this call is expected to complete synchronously, so flush now rq.flushNow(); } finally { rq.unlock(); } } /** * Disposes the native resources associated with the given OGLSurfaceData * (referenced by the pData parameter). This method is invoked from * the native Dispose() method from the Disposer thread when the * Java-level OGLSurfaceData object is about to go away. Note that we * also pass a reference to the native GLX/WGLGraphicsConfigInfo * (pConfigInfo) for the purposes of making a context current. */ static void dispose(long pData, long pConfigInfo) { OGLRenderQueue rq = OGLRenderQueue.getInstance(); rq.lock(); try { // make sure we have a current context before // disposing the native resources (e.g. texture object) OGLContext.setScratchSurface(pConfigInfo); RenderBuffer buf = rq.getBuffer(); rq.ensureCapacityAndAlignment(12, 4); buf.putInt(DISPOSE_SURFACE); buf.putLong(pData); // this call is expected to complete synchronously, so flush now rq.flushNow(); } finally { rq.unlock(); } } static void swapBuffers(long window) { OGLRenderQueue rq = OGLRenderQueue.getInstance(); rq.lock(); try { RenderBuffer buf = rq.getBuffer(); rq.ensureCapacityAndAlignment(12, 4); buf.putInt(SWAP_BUFFERS); buf.putLong(window); rq.flushNow(); } finally { rq.unlock(); } } /** * Returns true if OpenGL textures can have non-power-of-two dimensions * when using the basic GL_TEXTURE_2D target. */ boolean isTexNonPow2Available() { return graphicsConfig.isCapPresent(CAPS_TEXNONPOW2); } /** * Returns true if OpenGL textures can have non-power-of-two dimensions * when using the GL_TEXTURE_RECTANGLE_ARB target (only available when the * GL_ARB_texture_rectangle extension is present). */ boolean isTexRectAvailable() { return graphicsConfig.isCapPresent(CAPS_EXT_TEXRECT); } public Rectangle getNativeBounds() { OGLRenderQueue rq = OGLRenderQueue.getInstance(); rq.lock(); try { return new Rectangle(nativeWidth, nativeHeight); } finally { rq.unlock(); } } }
rokn/Count_Words_2015
testing/openjdk/jdk/src/share/classes/sun/java2d/opengl/OGLSurfaceData.java
Java
mit
24,976
<?php /* * 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. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\MongoDB\Event; use Doctrine\Common\EventArgs as BaseEventArgs; /** * Event args. * * @license http://www.opensource.org/licenses/mit-license.php MIT * @link www.doctrine-project.com * @since 1.0 * @author Jonathan H. Wage <jonwage@gmail.com> */ class EventArgs extends BaseEventArgs { private $invoker; private $data; public function __construct($invoker, &$data = null) { $this->invoker = $invoker; $this->data = $data; } public function getInvoker() { return $this->invoker; } public function getData() { return $this->data; } }
rafaelcalleja/EmptySymfony2Project
vendor/doctrine/mongodb/lib/Doctrine/MongoDB/Event/EventArgs.php
PHP
mit
1,647
var crypto = require('crypto'); var scmp = require('scmp'); var utils = require('keystone-utils'); // The DISABLE_CSRF environment variable is available to automatically pass // CSRF validation. This is useful in development scenarios where you want to // restart the node process and aren't using a persistent session store, but // should NEVER be set in production environments!! var DISABLE_CSRF = process.env.DISABLE_CSRF === 'true'; exports.TOKEN_KEY = '_csrf'; exports.LOCAL_KEY = 'csrf_token_key'; exports.LOCAL_VALUE = 'csrf_token_value'; exports.SECRET_KEY = exports.TOKEN_KEY + '_secret'; exports.SECRET_LENGTH = 10; exports.CSRF_HEADER_KEY = 'x-csrf-token'; exports.XSRF_HEADER_KEY = 'x-xsrf-token'; exports.XSRF_COOKIE_KEY = 'XSRF-TOKEN'; function tokenize (salt, secret) { return salt + crypto.createHash('sha1').update(salt + secret).digest('hex'); } exports.createSecret = function () { return crypto.pseudoRandomBytes(exports.SECRET_LENGTH).toString('base64'); }; exports.getSecret = function (req) { return req.session[exports.SECRET_KEY] || (req.session[exports.SECRET_KEY] = exports.createSecret()); }; exports.createToken = function (req) { return tokenize(utils.randomString(exports.SECRET_LENGTH), exports.getSecret(req)); }; exports.getToken = function (req, res) { res.locals[exports.LOCAL_VALUE] = res.locals[exports.LOCAL_VALUE] || exports.createToken(req); res.cookie(exports.XSRF_COOKIE_KEY, res.locals[exports.LOCAL_VALUE]); return res.locals[exports.LOCAL_VALUE]; }; exports.requestToken = function (req) { if (req.body && req.body[exports.TOKEN_KEY]) { return req.body[exports.TOKEN_KEY]; } else if (req.query && req.query[exports.TOKEN_KEY]) { return req.query[exports.TOKEN_KEY]; } else if (req.headers && req.headers[exports.XSRF_HEADER_KEY]) { return req.headers[exports.XSRF_HEADER_KEY]; } else if (req.headers && req.headers[exports.CSRF_HEADER_KEY]) { return req.headers[exports.CSRF_HEADER_KEY]; } return ''; }; exports.validate = function (req, token) { // Allow environment variable to disable check if (DISABLE_CSRF) return true; if (arguments.length === 1) { token = exports.requestToken(req); } if (typeof token !== 'string') { return false; } return scmp(token, tokenize(token.slice(0, exports.SECRET_LENGTH), req.session[exports.SECRET_KEY])); }; exports.middleware = { init: function (req, res, next) { res.locals[exports.LOCAL_KEY] = exports.LOCAL_VALUE; exports.getToken(req, res); next(); }, validate: function (req, res, next) { // Allow environment variable to disable check if (DISABLE_CSRF) return next(); // Bail on safe methods if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') { return next(); } // Validate token if (exports.validate(req)) { next(); } else { res.statusCode = 403; next(new Error('CSRF token mismatch')); } }, };
alobodig/keystone
lib/security/csrf.js
JavaScript
mit
2,898
<?php /** * File containing the ezcDocumentDocbook class * * @package Document * @version //autogen// * @copyright Copyright (C) 2005-2010 eZ Systems AS. All rights reserved. * @license http://ez.no/licenses/new_bsd New BSD License */ /** * The document handler for the docbook document markup. * * @package Document * @version //autogen// */ class ezcDocumentDocbook extends ezcDocumentXmlBase { /** * Construct document xml base. * * @ignore * @param ezcDocumentDocbookOptions $options * @return void */ public function __construct( ezcDocumentDocbookOptions $options = null ) { parent::__construct( $options === null ? new ezcDocumentDocbookOptions() : $options ); } /** * Return document compiled to the docbook format * * The internal document structure is compiled to the docbook format and * the resulting docbook document is returned. * * This method is required for all formats to have one central format, so * that each format can be compiled into each other format using docbook as * an intermediate format. * * You may of course just call an existing converter for this conversion. * * @return ezcDocumentDocbook */ public function getAsDocbook() { return $this; } /** * Create document from docbook document * * A document of the docbook format is provided and the internal document * structure should be created out of this. * * This method is required for all formats to have one central format, so * that each format can be compiled into each other format using docbook as * an intermediate format. * * You may of course just call an existing converter for this conversion. * * @param ezcDocumentDocbook $document * @return void */ public function createFromDocbook( ezcDocumentDocbook $document ) { $this->path = $document->getPath(); $this->document = $document->getDomDocument(); } /** * Return document as string * * Serialize the document to a string an return it. * * @return string */ public function save() { return $this->document->saveXml(); } /** * Validate the input file * * Validate the input file against the specification of the current * document format. * * Returns true, if the validation succeded, and an array with * ezcDocumentValidationError objects otherwise. * * @param string $file * @return mixed */ public function validateFile( $file ) { $oldSetting = libxml_use_internal_errors( true ); libxml_clear_errors(); $document = new DOMDocument(); $document->load( $file ); $document->schemaValidate( $this->options->schema ); // Get all errors $xmlErrors = libxml_get_errors(); $errors = array(); foreach ( $xmlErrors as $error ) { $errors[] = ezcDocumentValidationError::createFromLibXmlError( $error ); } libxml_clear_errors(); libxml_use_internal_errors( $oldSetting ); return ( count( $errors ) ? $errors : true ); } /** * Validate the input string * * Validate the input string against the specification of the current * document format. * * Returns true, if the validation succeded, and an array with * ezcDocumentValidationError objects otherwise. * * @param string $string * @return mixed */ public function validateString( $string ) { $oldSetting = libxml_use_internal_errors( true ); libxml_clear_errors(); $document = new DOMDocument(); $document->loadXml( $string ); $document->schemaValidate( $this->options->schema ); // Get all errors $xmlErrors = libxml_get_errors(); $errors = array(); foreach ( $xmlErrors as $error ) { $errors[] = ezcDocumentValidationError::createFromLibXmlError( $error ); } libxml_clear_errors(); libxml_use_internal_errors( $oldSetting ); return ( count( $errors ) ? $errors : true ); } } ?>
jim835/qscene_ez
lib/ezc/Document/src/document/xml/docbook.php
PHP
gpl-2.0
4,312
<?php class Redux_Validation_preg_replace { /** * Field Constructor. * * Required - must call the parent constructor, then assign field and value to vars, and obviously call the render field function * * @since Redux_Options 1.0.0 */ function __construct($field, $value, $current) { $this->field = $field; $this->value = $value; $this->current = $current; $this->validate(); } /** * Field Render Function. * * Takes the vars and validates them * * @since Redux_Options 1.0.0 */ function validate() { $this->value = preg_replace($this->field['preg']['pattern'], $this->field['preg']['replacement'], $this->value); } }
joelcoxokc/joelcoxio
wp-content/themes/vcard/options/options/validation/preg_replace/validation_preg_replace.php
PHP
gpl-2.0
659
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Http * @subpackage UserAgent * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @see Zend_Browser_Exception */ #require_once 'Zend/Http/UserAgent/Exception.php'; /** * @category Zend * @package Zend_Http * @subpackage UserAgent * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Http_UserAgent_Features_Exception extends Zend_Http_UserAgent_Exception { }
Eristoff47/P2
src/public/lib/Zend/Http/UserAgent/Features/Exception.php
PHP
gpl-2.0
1,124
/* * Ioctl handler * Linux ethernet bridge * * Authors: * Lennert Buytenhek <buytenh@gnu.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. */ #include <linux/capability.h> #include <linux/kernel.h> #include <linux/if_bridge.h> #include <linux/netdevice.h> #include <linux/times.h> #include <net/net_namespace.h> #include <asm/uaccess.h> #include "br_private.h" /* called with RTNL */ static int get_bridge_ifindices(int *indices, int num) { struct net_device *dev; int i = 0; for_each_netdev(&init_net, dev) { if (i >= num) break; if (dev->priv_flags & IFF_EBRIDGE) indices[i++] = dev->ifindex; } return i; } /* called with RTNL */ static void get_port_ifindices(struct net_bridge *br, int *ifindices, int num) { struct net_bridge_port *p; list_for_each_entry(p, &br->port_list, list) { if (p->port_no < num) ifindices[p->port_no] = p->dev->ifindex; } } /* * Format up to a page worth of forwarding table entries * userbuf -- where to copy result * maxnum -- maximum number of entries desired * (limited to a page for sanity) * offset -- number of records to skip */ static int get_fdb_entries(struct net_bridge *br, void __user *userbuf, unsigned long maxnum, unsigned long offset) { int num; void *buf; size_t size; /* Clamp size to PAGE_SIZE, test maxnum to avoid overflow */ if (maxnum > PAGE_SIZE/sizeof(struct __fdb_entry)) maxnum = PAGE_SIZE/sizeof(struct __fdb_entry); size = maxnum * sizeof(struct __fdb_entry); buf = kmalloc(size, GFP_USER); if (!buf) return -ENOMEM; num = br_fdb_fillbuf(br, buf, maxnum, offset); if (num > 0) { if (copy_to_user(userbuf, buf, num*sizeof(struct __fdb_entry))) num = -EFAULT; } kfree(buf); return num; } static int add_del_if(struct net_bridge *br, int ifindex, int isadd) { struct net_device *dev; int ret; if (!capable(CAP_NET_ADMIN)) return -EPERM; dev = dev_get_by_index(&init_net, ifindex); if (dev == NULL) return -EINVAL; if (isadd) ret = br_add_if(br, dev); else ret = br_del_if(br, dev); dev_put(dev); return ret; } /* * Legacy ioctl's through SIOCDEVPRIVATE * This interface is deprecated because it was too difficult to * to do the translation for 32/64bit ioctl compatability. */ static int old_dev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { struct net_bridge *br = netdev_priv(dev); unsigned long args[4]; if (copy_from_user(args, rq->ifr_data, sizeof(args))) return -EFAULT; switch (args[0]) { case BRCTL_ADD_IF: case BRCTL_DEL_IF: return add_del_if(br, args[1], args[0] == BRCTL_ADD_IF); case BRCTL_GET_BRIDGE_INFO: { struct __bridge_info b; memset(&b, 0, sizeof(struct __bridge_info)); rcu_read_lock(); memcpy(&b.designated_root, &br->designated_root, 8); memcpy(&b.bridge_id, &br->bridge_id, 8); b.root_path_cost = br->root_path_cost; b.max_age = jiffies_to_clock_t(br->max_age); b.hello_time = jiffies_to_clock_t(br->hello_time); b.forward_delay = br->forward_delay; b.bridge_max_age = br->bridge_max_age; b.bridge_hello_time = br->bridge_hello_time; b.bridge_forward_delay = jiffies_to_clock_t(br->bridge_forward_delay); b.topology_change = br->topology_change; b.topology_change_detected = br->topology_change_detected; b.root_port = br->root_port; b.stp_enabled = (br->stp_enabled != BR_NO_STP); b.ageing_time = jiffies_to_clock_t(br->ageing_time); b.hello_timer_value = br_timer_value(&br->hello_timer); b.tcn_timer_value = br_timer_value(&br->tcn_timer); b.topology_change_timer_value = br_timer_value(&br->topology_change_timer); b.gc_timer_value = br_timer_value(&br->gc_timer); rcu_read_unlock(); if (copy_to_user((void __user *)args[1], &b, sizeof(b))) return -EFAULT; return 0; } case BRCTL_GET_PORT_LIST: { int num, *indices; num = args[2]; if (num < 0) return -EINVAL; if (num == 0) num = 256; if (num > BR_MAX_PORTS) num = BR_MAX_PORTS; indices = kcalloc(num, sizeof(int), GFP_KERNEL); if (indices == NULL) return -ENOMEM; get_port_ifindices(br, indices, num); if (copy_to_user((void __user *)args[1], indices, num*sizeof(int))) num = -EFAULT; kfree(indices); return num; } case BRCTL_SET_BRIDGE_FORWARD_DELAY: if (!capable(CAP_NET_ADMIN)) return -EPERM; spin_lock_bh(&br->lock); br->bridge_forward_delay = clock_t_to_jiffies(args[1]); if (br_is_root_bridge(br)) br->forward_delay = br->bridge_forward_delay; spin_unlock_bh(&br->lock); return 0; case BRCTL_SET_BRIDGE_HELLO_TIME: { unsigned long t = clock_t_to_jiffies(args[1]); if (!capable(CAP_NET_ADMIN)) return -EPERM; if (t < HZ) return -EINVAL; spin_lock_bh(&br->lock); br->bridge_hello_time = t; if (br_is_root_bridge(br)) br->hello_time = br->bridge_hello_time; spin_unlock_bh(&br->lock); return 0; } case BRCTL_SET_BRIDGE_MAX_AGE: if (!capable(CAP_NET_ADMIN)) return -EPERM; spin_lock_bh(&br->lock); br->bridge_max_age = clock_t_to_jiffies(args[1]); if (br_is_root_bridge(br)) br->max_age = br->bridge_max_age; spin_unlock_bh(&br->lock); return 0; case BRCTL_SET_AGEING_TIME: if (!capable(CAP_NET_ADMIN)) return -EPERM; br->ageing_time = clock_t_to_jiffies(args[1]); return 0; case BRCTL_GET_PORT_INFO: { struct __port_info p; struct net_bridge_port *pt; rcu_read_lock(); if ((pt = br_get_port(br, args[2])) == NULL) { rcu_read_unlock(); return -EINVAL; } memset(&p, 0, sizeof(struct __port_info)); memcpy(&p.designated_root, &pt->designated_root, 8); memcpy(&p.designated_bridge, &pt->designated_bridge, 8); p.port_id = pt->port_id; p.designated_port = pt->designated_port; p.path_cost = pt->path_cost; p.designated_cost = pt->designated_cost; p.state = pt->state; p.top_change_ack = pt->topology_change_ack; p.config_pending = pt->config_pending; p.message_age_timer_value = br_timer_value(&pt->message_age_timer); p.forward_delay_timer_value = br_timer_value(&pt->forward_delay_timer); p.hold_timer_value = br_timer_value(&pt->hold_timer); rcu_read_unlock(); if (copy_to_user((void __user *)args[1], &p, sizeof(p))) return -EFAULT; return 0; } case BRCTL_SET_BRIDGE_STP_STATE: if (!capable(CAP_NET_ADMIN)) return -EPERM; br_stp_set_enabled(br, args[1]); return 0; case BRCTL_SET_BRIDGE_PRIORITY: if (!capable(CAP_NET_ADMIN)) return -EPERM; spin_lock_bh(&br->lock); br_stp_set_bridge_priority(br, args[1]); spin_unlock_bh(&br->lock); return 0; case BRCTL_SET_PORT_PRIORITY: { struct net_bridge_port *p; int ret = 0; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (args[2] >= (1<<(16-BR_PORT_BITS))) return -ERANGE; spin_lock_bh(&br->lock); if ((p = br_get_port(br, args[1])) == NULL) ret = -EINVAL; else br_stp_set_port_priority(p, args[2]); spin_unlock_bh(&br->lock); return ret; } case BRCTL_SET_PATH_COST: { struct net_bridge_port *p; int ret = 0; if (!capable(CAP_NET_ADMIN)) return -EPERM; if ((p = br_get_port(br, args[1])) == NULL) ret = -EINVAL; else br_stp_set_path_cost(p, args[2]); return ret; } case BRCTL_GET_FDB_ENTRIES: return get_fdb_entries(br, (void __user *)args[1], args[2], args[3]); } return -EOPNOTSUPP; } static int old_deviceless(void __user *uarg) { unsigned long args[3]; if (copy_from_user(args, uarg, sizeof(args))) return -EFAULT; switch (args[0]) { case BRCTL_GET_VERSION: return BRCTL_VERSION; case BRCTL_GET_BRIDGES: { int *indices; int ret = 0; if (args[2] >= 2048) return -ENOMEM; indices = kcalloc(args[2], sizeof(int), GFP_KERNEL); if (indices == NULL) return -ENOMEM; args[2] = get_bridge_ifindices(indices, args[2]); ret = copy_to_user((void __user *)args[1], indices, args[2]*sizeof(int)) ? -EFAULT : args[2]; kfree(indices); return ret; } case BRCTL_ADD_BRIDGE: case BRCTL_DEL_BRIDGE: { char buf[IFNAMSIZ]; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(buf, (void __user *)args[1], IFNAMSIZ)) return -EFAULT; buf[IFNAMSIZ-1] = 0; if (args[0] == BRCTL_ADD_BRIDGE) return br_add_bridge(buf); return br_del_bridge(buf); } } return -EOPNOTSUPP; } int br_ioctl_deviceless_stub(struct net *net, unsigned int cmd, void __user *uarg) { switch (cmd) { case SIOCGIFBR: case SIOCSIFBR: return old_deviceless(uarg); case SIOCBRADDBR: case SIOCBRDELBR: { char buf[IFNAMSIZ]; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(buf, uarg, IFNAMSIZ)) return -EFAULT; buf[IFNAMSIZ-1] = 0; if (cmd == SIOCBRADDBR) return br_add_bridge(buf); return br_del_bridge(buf); } } return -EOPNOTSUPP; } int br_dev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { struct net_bridge *br = netdev_priv(dev); switch(cmd) { case SIOCDEVPRIVATE: return old_dev_ioctl(dev, rq, cmd); case SIOCBRADDIF: case SIOCBRDELIF: return add_del_if(br, rq->ifr_ifindex, cmd == SIOCBRADDIF); } pr_debug("Bridge does not support ioctl 0x%x\n", cmd); return -EOPNOTSUPP; }
getitnowmarketing/archos_kernel_27
net/bridge/br_ioctl.c
C
gpl-2.0
9,288
#undef container_of /* * The container_of construct: if p is a pointer to member m of * container class c, then return a pointer to the container of which * *p is a member. */ #define container_of(p, c, m) ((c *)((char *)(p) - offsetof(c,m))) #include <../../../com32/include/linux/list.h>
ErwanAliasr1/syslinux
tests/unittest/include/linux/list.h
C
gpl-2.0
295
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.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, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Trial Of the Champion SD%Complete: SDComment: SDCategory: trial_of_the_champion EndScriptData */ /* ContentData npc_announcer_toc5 EndContentData */ #include "ScriptPCH.h" #include "trial_of_the_champion.h" #include "Vehicle.h" #define GOSSIP_START_EVENT1 "I'm ready to start challenge." #define GOSSIP_START_EVENT2 "I'm ready for the next challenge." #define ORIENTATION 4.714f /*###### ## npc_announcer_toc5 ######*/ const Position SpawnPosition = {746.261f, 657.401f, 411.681f, 4.65f}; class npc_announcer_toc5 : public CreatureScript { public: npc_announcer_toc5() : CreatureScript("npc_announcer_toc5") { } struct npc_announcer_toc5AI : public ScriptedAI { npc_announcer_toc5AI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); uiSummonTimes = 0; uiPosition = 0; uiLesserChampions = 0; uiFirstBoss = 0; uiSecondBoss = 0; uiThirdBoss = 0; uiArgentChampion = 0; uiPhase = 0; uiTimer = 0; uiVehicle1GUID = 0; uiVehicle2GUID = 0; uiVehicle3GUID = 0; Champion1List.clear(); Champion2List.clear(); Champion3List.clear(); me->SetReactState(REACT_PASSIVE); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); SetGrandChampionsForEncounter(); SetArgentChampion(); } InstanceScript* instance; uint8 uiSummonTimes; uint8 uiPosition; uint8 uiLesserChampions; uint32 uiArgentChampion; uint32 uiFirstBoss; uint32 uiSecondBoss; uint32 uiThirdBoss; uint32 uiPhase; uint32 uiTimer; uint64 uiVehicle1GUID; uint64 uiVehicle2GUID; uint64 uiVehicle3GUID; uint64 uiGrandChampionBoss1; std::list<uint64> Champion1List; std::list<uint64> Champion2List; std::list<uint64> Champion3List; void NextStep(uint32 uiTimerStep, bool bNextStep = true, uint8 uiPhaseStep = 0) { uiTimer = uiTimerStep; if (bNextStep) ++uiPhase; else uiPhase = uiPhaseStep; } void SetData(uint32 uiType, uint32 /*uiData*/) { switch (uiType) { case DATA_START: DoSummonGrandChampion(uiFirstBoss); NextStep(10000, false, 1); break; case DATA_IN_POSITION: //movement done. me->GetMotionMaster()->MovePoint(1, 735.81f, 661.92f, 412.39f); if (GameObject* go = GameObject::GetGameObject(*me, instance->GetData64(DATA_MAIN_GATE))) instance->HandleGameObject(go->GetGUID(), false); NextStep(10000, false, 3); break; case DATA_LESSER_CHAMPIONS_DEFEATED: { ++uiLesserChampions; std::list<uint64> TempList; if (uiLesserChampions == 3 || uiLesserChampions == 6) { switch (uiLesserChampions) { case 3: TempList = Champion2List; break; case 6: TempList = Champion3List; break; } for (std::list<uint64>::const_iterator itr = TempList.begin(); itr != TempList.end(); ++itr) if (Creature* summon = Unit::GetCreature(*me, *itr)) AggroAllPlayers(summon); }else if (uiLesserChampions == 9) StartGrandChampionsAttack(); break; } } } void StartGrandChampionsAttack() { Creature* pGrandChampion1 = Unit::GetCreature(*me, uiVehicle1GUID); Creature* pGrandChampion2 = Unit::GetCreature(*me, uiVehicle2GUID); Creature* pGrandChampion3 = Unit::GetCreature(*me, uiVehicle3GUID); if (pGrandChampion1 && pGrandChampion2 && pGrandChampion3) { AggroAllPlayers(pGrandChampion1); AggroAllPlayers(pGrandChampion2); AggroAllPlayers(pGrandChampion3); } } void MovementInform(uint32 uiType, uint32 uiPointId) { if (uiType != POINT_MOTION_TYPE) return; if (uiPointId == 1) { me->SetOrientation(ORIENTATION); me->SendMovementFlagUpdate(); } } void DoSummonGrandChampion(uint32 uiBoss) { ++uiSummonTimes; uint32 VEHICLE_TO_SUMMON1 = 0; uint32 VEHICLE_TO_SUMMON2 = 0; switch (uiBoss) { case 0: VEHICLE_TO_SUMMON1 = VEHICLE_MOKRA_SKILLCRUSHER_MOUNT; VEHICLE_TO_SUMMON2 = VEHICLE_ORGRIMMAR_WOLF; break; case 1: VEHICLE_TO_SUMMON1 = VEHICLE_ERESSEA_DAWNSINGER_MOUNT; VEHICLE_TO_SUMMON2 = VEHICLE_SILVERMOON_HAWKSTRIDER; break; case 2: VEHICLE_TO_SUMMON1 = VEHICLE_RUNOK_WILDMANE_MOUNT; VEHICLE_TO_SUMMON2 = VEHICLE_THUNDER_BLUFF_KODO; break; case 3: VEHICLE_TO_SUMMON1 = VEHICLE_ZUL_TORE_MOUNT; VEHICLE_TO_SUMMON2 = VEHICLE_DARKSPEAR_RAPTOR; break; case 4: VEHICLE_TO_SUMMON1 = VEHICLE_DEATHSTALKER_VESCERI_MOUNT; VEHICLE_TO_SUMMON2 = VEHICLE_FORSAKE_WARHORSE; break; default: return; } if (Creature* pBoss = me->SummonCreature(VEHICLE_TO_SUMMON1, SpawnPosition)) { switch (uiSummonTimes) { case 1: { uiVehicle1GUID = pBoss->GetGUID(); uint64 uiGrandChampionBoss1 = 0; if (Vehicle* pVehicle = pBoss->GetVehicleKit()) if (Unit* unit = pVehicle->GetPassenger(0)) uiGrandChampionBoss1 = unit->GetGUID(); if (instance) { instance->SetData64(DATA_GRAND_CHAMPION_VEHICLE_1, uiVehicle1GUID); instance->SetData64(DATA_GRAND_CHAMPION_1, uiGrandChampionBoss1); } pBoss->AI()->SetData(1, 0); break; } case 2: { uiVehicle2GUID = pBoss->GetGUID(); uint64 uiGrandChampionBoss2 = 0; if (Vehicle* pVehicle = pBoss->GetVehicleKit()) if (Unit* unit = pVehicle->GetPassenger(0)) uiGrandChampionBoss2 = unit->GetGUID(); if (instance) { instance->SetData64(DATA_GRAND_CHAMPION_VEHICLE_2, uiVehicle2GUID); instance->SetData64(DATA_GRAND_CHAMPION_2, uiGrandChampionBoss2); } pBoss->AI()->SetData(2, 0); break; } case 3: { uiVehicle3GUID = pBoss->GetGUID(); uint64 uiGrandChampionBoss3 = 0; if (Vehicle* pVehicle = pBoss->GetVehicleKit()) if (Unit* unit = pVehicle->GetPassenger(0)) uiGrandChampionBoss3 = unit->GetGUID(); if (instance) { instance->SetData64(DATA_GRAND_CHAMPION_VEHICLE_3, uiVehicle3GUID); instance->SetData64(DATA_GRAND_CHAMPION_3, uiGrandChampionBoss3); } pBoss->AI()->SetData(3, 0); break; } default: return; } for (uint8 i = 0; i < 3; ++i) { if (Creature* pAdd = me->SummonCreature(VEHICLE_TO_SUMMON2, SpawnPosition, TEMPSUMMON_CORPSE_DESPAWN)) { switch (uiSummonTimes) { case 1: Champion1List.push_back(pAdd->GetGUID()); break; case 2: Champion2List.push_back(pAdd->GetGUID()); break; case 3: Champion3List.push_back(pAdd->GetGUID()); break; } switch (i) { case 0: pAdd->GetMotionMaster()->MoveFollow(pBoss, 2.0f, M_PI); break; case 1: pAdd->GetMotionMaster()->MoveFollow(pBoss, 2.0f, M_PI / 2); break; case 2: pAdd->GetMotionMaster()->MoveFollow(pBoss, 2.0f, M_PI / 2 + M_PI); break; } } } } } void DoStartArgentChampionEncounter() { me->GetMotionMaster()->MovePoint(1, 735.81f, 661.92f, 412.39f); if (me->SummonCreature(uiArgentChampion, SpawnPosition)) { for (uint8 i = 0; i < 3; ++i) { if (Creature* pTrash = me->SummonCreature(NPC_ARGENT_LIGHWIELDER, SpawnPosition)) pTrash->AI()->SetData(i, 0); if (Creature* pTrash = me->SummonCreature(NPC_ARGENT_MONK, SpawnPosition)) pTrash->AI()->SetData(i, 0); if (Creature* pTrash = me->SummonCreature(NPC_PRIESTESS, SpawnPosition)) pTrash->AI()->SetData(i, 0); } } } void SetGrandChampionsForEncounter() { uiFirstBoss = urand(0, 4); while (uiSecondBoss == uiFirstBoss || uiThirdBoss == uiFirstBoss || uiThirdBoss == uiSecondBoss) { uiSecondBoss = urand(0, 4); uiThirdBoss = urand(0, 4); } } void SetArgentChampion() { uint8 uiTempBoss = urand(0, 1); switch (uiTempBoss) { case 0: uiArgentChampion = NPC_EADRIC; break; case 1: uiArgentChampion = NPC_PALETRESS; break; } } void StartEncounter() { if (!instance) return; me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); if (instance->GetData(BOSS_BLACK_KNIGHT) == NOT_STARTED) { if (instance->GetData(BOSS_ARGENT_CHALLENGE_E) == NOT_STARTED && instance->GetData(BOSS_ARGENT_CHALLENGE_P) == NOT_STARTED) { if (instance->GetData(BOSS_GRAND_CHAMPIONS) == NOT_STARTED) me->AI()->SetData(DATA_START, 0); if (instance->GetData(BOSS_GRAND_CHAMPIONS) == DONE) DoStartArgentChampionEncounter(); } if ((instance->GetData(BOSS_GRAND_CHAMPIONS) == DONE && instance->GetData(BOSS_ARGENT_CHALLENGE_E) == DONE) || instance->GetData(BOSS_ARGENT_CHALLENGE_P) == DONE) me->SummonCreature(VEHICLE_BLACK_KNIGHT, 769.834f, 651.915f, 447.035f, 0); } } void AggroAllPlayers(Creature* temp) { Map::PlayerList const &PlList = me->GetMap()->GetPlayers(); if (PlList.isEmpty()) return; for (Map::PlayerList::const_iterator i = PlList.begin(); i != PlList.end(); ++i) { if (Player* player = i->getSource()) { if (player->isGameMaster()) continue; if (player->isAlive()) { temp->SetHomePosition(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation()); temp->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); temp->SetReactState(REACT_AGGRESSIVE); temp->SetInCombatWith(player); player->SetInCombatWith(temp); temp->AddThreat(player, 0.0f); } } } } void UpdateAI(const uint32 uiDiff) { ScriptedAI::UpdateAI(uiDiff); if (uiTimer <= uiDiff) { switch (uiPhase) { case 1: DoSummonGrandChampion(uiSecondBoss); NextStep(10000, true); break; case 2: DoSummonGrandChampion(uiThirdBoss); NextStep(0, false); break; case 3: if (!Champion1List.empty()) { for (std::list<uint64>::const_iterator itr = Champion1List.begin(); itr != Champion1List.end(); ++itr) if (Creature* summon = Unit::GetCreature(*me, *itr)) AggroAllPlayers(summon); NextStep(0, false); } break; } } else uiTimer -= uiDiff; if (!UpdateVictim()) return; } void JustSummoned(Creature* summon) { if (instance && instance->GetData(BOSS_GRAND_CHAMPIONS) == NOT_STARTED) { summon->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); summon->SetReactState(REACT_PASSIVE); } } void SummonedCreatureDespawn(Creature* summon) { switch (summon->GetEntry()) { case VEHICLE_DARNASSIA_NIGHTSABER: case VEHICLE_EXODAR_ELEKK: case VEHICLE_STORMWIND_STEED: case VEHICLE_GNOMEREGAN_MECHANOSTRIDER: case VEHICLE_IRONFORGE_RAM: case VEHICLE_FORSAKE_WARHORSE: case VEHICLE_THUNDER_BLUFF_KODO: case VEHICLE_ORGRIMMAR_WOLF: case VEHICLE_SILVERMOON_HAWKSTRIDER: case VEHICLE_DARKSPEAR_RAPTOR: me->AI()->SetData(DATA_LESSER_CHAMPIONS_DEFEATED, 0); break; } } }; CreatureAI* GetAI(Creature* creature) const { return new npc_announcer_toc5AI(creature); } bool OnGossipHello(Player* player, Creature* creature) { InstanceScript* instance = creature->GetInstanceScript(); if (instance && ((instance->GetData(BOSS_GRAND_CHAMPIONS) == DONE && instance->GetData(BOSS_BLACK_KNIGHT) == DONE && instance->GetData(BOSS_ARGENT_CHALLENGE_E) == DONE) || instance->GetData(BOSS_ARGENT_CHALLENGE_P) == DONE)) return false; if (instance && instance->GetData(BOSS_GRAND_CHAMPIONS) == NOT_STARTED && instance->GetData(BOSS_ARGENT_CHALLENGE_E) == NOT_STARTED && instance->GetData(BOSS_ARGENT_CHALLENGE_P) == NOT_STARTED && instance->GetData(BOSS_BLACK_KNIGHT) == NOT_STARTED) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_START_EVENT1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); else if (instance) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_START_EVENT2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); return true; } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) { player->PlayerTalkClass->ClearMenus(); if (action == GOSSIP_ACTION_INFO_DEF+1) { player->CLOSE_GOSSIP_MENU(); CAST_AI(npc_announcer_toc5::npc_announcer_toc5AI, creature->AI())->StartEncounter(); } return true; } }; void AddSC_trial_of_the_champion() { new npc_announcer_toc5(); }
pablo93/TrinityCore
src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.cpp
C++
gpl-2.0
18,304
#include <linux/string.h> #include <linux/timer.h> #include <linux/workqueue.h> #include <linux/platform_device.h> #include <mach/am_regs.h> #include <linux/amports/canvas.h> #include <linux/amports/vframe.h> #include <linux/amports/vframe_provider.h> #include "deinterlace.h" #ifdef DEBUG unsigned di_pre_underflow = 0, di_pre_overflow = 0; unsigned long debug_array[4 * 1024]; #endif #if 1 #define RECEIVER_NAME "amvideo" #else #define RECEIVER_NAME "deinterlace" #endif #define PATTERN32_NUM 2 #define PATTERN22_NUM 32 #if (PATTERN22_NUM < 32) #define PATTERN22_MARK ((1LL<<PATTERN22_NUM)-1) #elif (PATTERN22_NUM < 64) #define PATTERN22_MARK ((0x100000000LL<<(PATTERN22_NUM-32))-1) #else #define PATTERN22_MARK 0xffffffffffffffffLL #endif #define PRE_HOLD_LINE 4 #define DI_PRE_INTERVAL (HZ/100) // 0 - off // 1 - pre-post link // 2 - pre-post separate, only post in vsync static int deinterlace_mode = 0; #if defined(CONFIG_ARCH_MESON2) static int noise_reduction_level = 2; #endif static struct timer_list di_pre_timer; static struct work_struct di_pre_work; int di_pre_recycle_buf = -1; int prev_struct = 0; int prog_field_count = 0; int buf_recycle_done = 1; int di_pre_post_done = 1; int field_counter = 0, pre_field_counter = 0, di_checked_field = 0; int pattern_len = 0; int di_p32_counter = 0; unsigned int last_big_data = 0, last_big_num = 0; unsigned long blend_mode, pattern_22, di_info[4][83]; unsigned long long di_p32_info, di_p22_info, di_p32_info_2, di_p22_info_2; vframe_t *cur_buf; vframe_t di_buf_pool[DI_BUF_NUM]; DI_MIF_t di_inp_top_mif; DI_MIF_t di_inp_bot_mif; DI_MIF_t di_mem_mif; DI_MIF_t di_buf0_mif; DI_MIF_t di_buf1_mif; DI_MIF_t di_chan2_mif; DI_SIM_MIF_t di_nrwr_mif; DI_SIM_MIF_t di_mtnwr_mif; DI_SIM_MIF_t di_mtncrd_mif; DI_SIM_MIF_t di_mtnprd_mif; unsigned di_mem_start; int vdin_en = 0; vframe_t dummy_buf; int get_deinterlace_mode(void) { return deinterlace_mode; } void set_deinterlace_mode(int mode) { deinterlace_mode = mode; } #if defined(CONFIG_ARCH_MESON2) int get_noise_reduction_level(void) { return noise_reduction_level; } void set_noise_reduction_level(int level) { noise_reduction_level = level; } #endif int get_di_pre_recycle_buf(void) { return di_pre_recycle_buf; } vframe_t *peek_di_out_buf(void) { if (field_counter <= pre_field_counter - 2) { return &(di_buf_pool[field_counter % DI_BUF_NUM]); } else { return NULL; } } void inc_field_counter(void) { field_counter++; } void set_post_di_mem(int mode) { unsigned temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((field_counter + di_checked_field) % DI_BUF_NUM); canvas_config(di_buf0_mif.canvas0_addr0, temp, MAX_CANVAS_WIDTH * 2, MAX_CANVAS_HEIGHT / 2, 0, 0); if (mode == 1) { temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((field_counter + di_checked_field + 1) % DI_BUF_NUM); } else { temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((field_counter + di_checked_field - 1) % DI_BUF_NUM); } canvas_config(di_buf1_mif.canvas0_addr0, temp, MAX_CANVAS_WIDTH * 2, MAX_CANVAS_HEIGHT / 2, 0, 0); temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((field_counter + di_checked_field) % DI_BUF_NUM) + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT); canvas_config(di_mtncrd_mif.canvas_num, temp, MAX_CANVAS_WIDTH / 2, MAX_CANVAS_HEIGHT / 2, 0, 0); temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((field_counter + di_checked_field + 1) % DI_BUF_NUM) + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT); canvas_config(di_mtnprd_mif.canvas_num, temp, MAX_CANVAS_WIDTH / 2, MAX_CANVAS_HEIGHT / 2, 0, 0); } void disable_deinterlace(void) { WRITE_MPEG_REG(DI_PRE_CTRL, 0x3 << 30); WRITE_MPEG_REG(DI_POST_CTRL, 0x3 << 30); WRITE_MPEG_REG(DI_PRE_SIZE, (32 - 1) | ((64 - 1) << 16)); WRITE_MPEG_REG(DI_POST_SIZE, (32 - 1) | ((128 - 1) << 16)); WRITE_MPEG_REG(DI_INP_GEN_REG, READ_MPEG_REG(DI_INP_GEN_REG) & 0xfffffffe); WRITE_MPEG_REG(DI_MEM_GEN_REG, READ_MPEG_REG(DI_MEM_GEN_REG) & 0xfffffffe); WRITE_MPEG_REG(DI_CHAN2_GEN_REG, READ_MPEG_REG(DI_CHAN2_GEN_REG) & 0xfffffffe); WRITE_MPEG_REG(DI_IF1_GEN_REG, READ_MPEG_REG(DI_IF1_GEN_REG) & 0xfffffffe); } void disable_pre_deinterlace(void) { unsigned status = READ_MPEG_REG(DI_PRE_CTRL) & 0x2; if (prev_struct > 0) { unsigned temp = READ_MPEG_REG(DI_PRE_SIZE); unsigned total = (temp & 0xffff) * ((temp >> 16) & 0xffff); unsigned count = 0; while ((READ_MPEG_REG(DI_INTR_CTRL) & 0xf) != (status | 0x9)) { if (count++ >= total) { break; } } WRITE_MPEG_REG(DI_INTR_CTRL, READ_MPEG_REG(DI_INTR_CTRL)); } WRITE_MPEG_REG(DI_INP_GEN_REG, READ_MPEG_REG(DI_INP_GEN_REG) & 0xfffffffe); WRITE_MPEG_REG(DI_MEM_GEN_REG, READ_MPEG_REG(DI_MEM_GEN_REG) & 0xfffffffe); WRITE_MPEG_REG(DI_CHAN2_GEN_REG, READ_MPEG_REG(DI_CHAN2_GEN_REG) & 0xfffffffe); #ifdef DEBUG di_pre_underflow = 0; di_pre_overflow = 0; #endif prev_struct = 0; prog_field_count = 0; buf_recycle_done = 1; di_pre_post_done = 1; pre_field_counter = field_counter; di_pre_recycle_buf = -1; WRITE_MPEG_REG(DI_PRE_CTRL, 0x3 << 30); WRITE_MPEG_REG(DI_PRE_SIZE, (32 - 1) | ((64 - 1) << 16)); } void disable_post_deinterlace(void) { WRITE_MPEG_REG(DI_POST_CTRL, 0x3 << 30); WRITE_MPEG_REG(DI_POST_SIZE, (32 - 1) | ((128 - 1) << 16)); WRITE_MPEG_REG(DI_IF1_GEN_REG, READ_MPEG_REG(DI_IF1_GEN_REG) & 0xfffffffe); } void set_vd1_fmt_more( int hfmt_en, int hz_yc_ratio, //2bit int hz_ini_phase, //4bit int vfmt_en, int vt_yc_ratio, //2bit int vt_ini_phase, //4bit int y_length, int c_length, int hz_rpt //1bit ) { int vt_phase_step = (16 >> vt_yc_ratio); WRITE_MPEG_REG(VIU_VD1_FMT_CTRL, (hz_rpt << 28) | // hz rpt pixel (hz_ini_phase << 24) | // hz ini phase (0 << 23) | // repeat p0 enable (hz_yc_ratio << 21) | // hz yc ratio (hfmt_en << 20) | // hz enable (1 << 17) | // nrpt_phase0 enable (0 << 16) | // repeat l0 enable (0 << 12) | // skip line num (vt_ini_phase << 8) | // vt ini phase (vt_phase_step << 1) | // vt phase step (3.4) (vfmt_en << 0) // vt enable ); WRITE_MPEG_REG(VIU_VD1_FMT_W, (y_length << 16) | // hz format width (c_length << 0) // vt format width ); } void initial_di_prepost(int hsize_pre, int vsize_pre, int hsize_post, int vsize_post, int hold_line) { WRITE_MPEG_REG(DI_PRE_SIZE, (hsize_pre - 1) | ((vsize_pre - 1) << 16)); WRITE_MPEG_REG(DI_POST_SIZE, (hsize_post - 1) | ((vsize_post - 1) << 16)); WRITE_MPEG_REG(DI_BLEND_CTRL, (0x2 << 20) | // top mode. EI only 25); // KDEINT WRITE_MPEG_REG(DI_EI_CTRL0, (255 << 16) | // ei_filter. (5 << 8) | // ei_threshold. (1 << 2) | // ei bypass cf2. (1 << 1)); // ei bypass far1 WRITE_MPEG_REG(DI_EI_CTRL1, (180 << 24) | // ei diff (10 << 16) | // ei ang45 (15 << 8) | // ei peak. 45); // ei cross. WRITE_MPEG_REG(DI_EI_CTRL2, (10 << 23) | // close2 (10 << 16) | // close1 (10 << 8) | // far2 10); // far1 WRITE_MPEG_REG(DI_PRE_CTRL, 0 | // NR enable (0 << 1) | // MTN_EN (0 << 2) | // check 3:2 pulldown (0 << 3) | // check 2:2 pulldown (0 << 4) | // 2:2 check mid pixel come from next field after MTN. (0 << 5) | // hist check enable (0 << 6) | // hist check not use chan2. (0 << 7) | // hist check use data before noise reduction. (0 << 8) | // chan 2 enable for 2:2 pull down check. (0 << 9) | // line buffer 2 enable (0 << 10) | // pre drop first. (0 << 11) | // pre repeat. (1 << 12) | // pre viu link (hold_line << 16) | // pre hold line number (0 << 29) | // pre field number. (0x3 << 30) // pre soft rst, pre frame rst. ); WRITE_MPEG_REG(DI_POST_CTRL, (0 << 0) | // line buffer 0 enable (0 << 1) | // line buffer 1 enable (0 << 2) | // ei enable (0 << 3) | // mtn line buffer enable (0 << 4) | // mtnp read mif enable (0 << 5) | // di blend enble. (0 << 6) | // di mux output enable (0 << 7) | // di write to SDRAM enable. (1 << 8) | // di to VPP enable. (0 << 9) | // mif0 to VPP enable. (0 << 10) | // post drop first. (0 << 11) | // post repeat. (1 << 12) | // post viu link (1 << 13) | // prepost_link (hold_line << 16) | // post hold line number (0 << 29) | // post field number. (0x3 << 30) // post soft rst post frame rst. ); WRITE_MPEG_REG(DI_MC_22LVL0, (READ_MPEG_REG(DI_MC_22LVL0) & 0xffff0000) | 256); // field 22 level WRITE_MPEG_REG(DI_MC_32LVL0, (READ_MPEG_REG(DI_MC_32LVL0) & 0xffffff00) | 16); // field 32 level // set hold line for all ddr req interface. WRITE_MPEG_REG(DI_INP_GEN_REG, (hold_line << 19)); WRITE_MPEG_REG(DI_MEM_GEN_REG, (hold_line << 19)); WRITE_MPEG_REG(VD1_IF0_GEN_REG, (hold_line << 19)); WRITE_MPEG_REG(DI_IF1_GEN_REG, (hold_line << 19)); WRITE_MPEG_REG(DI_CHAN2_GEN_REG, (hold_line << 19)); } void initial_di_pre(int hsize_pre, int vsize_pre, int hold_line) { WRITE_MPEG_REG(DI_PRE_SIZE, (hsize_pre - 1) | ((vsize_pre - 1) << 16)); WRITE_MPEG_REG(DI_PRE_CTRL, 0 | // NR enable (0 << 1) | // MTN_EN (0 << 2) | // check 3:2 pulldown (0 << 3) | // check 2:2 pulldown (0 << 4) | // 2:2 check mid pixel come from next field after MTN. (0 << 5) | // hist check enable (0 << 6) | // hist check not use chan2. (0 << 7) | // hist check use data before noise reduction. (0 << 8) | // chan 2 enable for 2:2 pull down check. (0 << 9) | // line buffer 2 enable (0 << 10) | // pre drop first. (0 << 11) | // pre repeat. (0 << 12) | // pre viu link (hold_line << 16) | // pre hold line number (0 << 29) | // pre field number. (0x3 << 30) // pre soft rst, pre frame rst. ); WRITE_MPEG_REG(DI_MC_22LVL0, (READ_MPEG_REG(DI_MC_22LVL0) & 0xffff0000) | 256); // field 22 level WRITE_MPEG_REG(DI_MC_32LVL0, (READ_MPEG_REG(DI_MC_32LVL0) & 0xffffff00) | 16); // field 32 level } void initial_di_post(int hsize_post, int vsize_post, int hold_line) { WRITE_MPEG_REG(DI_POST_SIZE, (hsize_post - 1) | ((vsize_post - 1) << 16)); WRITE_MPEG_REG(DI_BLEND_CTRL, (0x2 << 20) | // top mode. EI only 25); // KDEINT WRITE_MPEG_REG(DI_EI_CTRL0, (255 << 16) | // ei_filter. (5 << 8) | // ei_threshold. (1 << 2) | // ei bypass cf2. (1 << 1)); // ei bypass far1 WRITE_MPEG_REG(DI_EI_CTRL1, (180 << 24) | // ei diff (10 << 16) | // ei ang45 (15 << 8) | // ei peak. 45); // ei cross. WRITE_MPEG_REG(DI_EI_CTRL2, (10 << 23) | // close2 (10 << 16) | // close1 (10 << 8) | // far2 10); // far1 WRITE_MPEG_REG(DI_POST_CTRL, (0 << 0) | // line buffer 0 enable (0 << 1) | // line buffer 1 enable (0 << 2) | // ei enable (0 << 3) | // mtn line buffer enable (0 << 4) | // mtnp read mif enable (0 << 5) | // di blend enble. (0 << 6) | // di mux output enable (0 << 7) | // di write to SDRAM enable. (1 << 8) | // di to VPP enable. (0 << 9) | // mif0 to VPP enable. (0 << 10) | // post drop first. (0 << 11) | // post repeat. (1 << 12) | // post viu link (hold_line << 16) | // post hold line number (0 << 29) | // post field number. (0x3 << 30) // post soft rst post frame rst. ); } void enable_di_mode_check(int win0_start_x, int win0_end_x, int win0_start_y, int win0_end_y, int win1_start_x, int win1_end_x, int win1_start_y, int win1_end_y, int win2_start_x, int win2_end_x, int win2_start_y, int win2_end_y, int win3_start_x, int win3_end_x, int win3_start_y, int win3_end_y, int win4_start_x, int win4_end_x, int win4_start_y, int win4_end_y, int win0_32lvl, int win1_32lvl, int win2_32lvl, int win3_32lvl, int win4_32lvl, int win0_22lvl, int win1_22lvl, int win2_22lvl, int win3_22lvl, int win4_22lvl, int field_32lvl, int field_22lvl) { WRITE_MPEG_REG(DI_MC_REG0_X, (win0_start_x << 16) | // start_x win0_end_x); // end_x WRITE_MPEG_REG(DI_MC_REG0_Y, (win0_start_y << 16) | // start_y win0_end_y); // end_x WRITE_MPEG_REG(DI_MC_REG1_X, (win1_start_x << 16) | // start_x win1_end_x); // end_x WRITE_MPEG_REG(DI_MC_REG1_Y, (win1_start_y << 16) | // start_y win1_end_y); // end_x WRITE_MPEG_REG(DI_MC_REG2_X, (win2_start_x << 16) | // start_x win2_end_x); // end_x WRITE_MPEG_REG(DI_MC_REG2_Y, (win2_start_y << 16) | // start_y win2_end_y); // end_x WRITE_MPEG_REG(DI_MC_REG3_X, (win3_start_x << 16) | // start_x win3_end_x); // end_x WRITE_MPEG_REG(DI_MC_REG3_Y, (win3_start_y << 16) | // start_y win3_end_y); // end_x WRITE_MPEG_REG(DI_MC_REG4_X, (win4_start_x << 16) | // start_x win4_end_x); // end_x WRITE_MPEG_REG(DI_MC_REG4_Y, (win4_start_y << 16) | // start_y win4_end_y); // end_x WRITE_MPEG_REG(DI_MC_32LVL1, win3_32lvl | //region 3 (win4_32lvl << 8)); //region 4 WRITE_MPEG_REG(DI_MC_32LVL0, field_32lvl | //field 32 level (win0_32lvl << 8) | //region 0 (win1_32lvl << 16) | //region 1 (win2_32lvl << 24)); //region 2. WRITE_MPEG_REG(DI_MC_22LVL0, field_22lvl | // field 22 level (win0_22lvl << 16)); // region 0. WRITE_MPEG_REG(DI_MC_22LVL1, win1_22lvl | // region 1 (win2_22lvl << 16)); // region 2. WRITE_MPEG_REG(DI_MC_22LVL2, win3_22lvl | // region 3 (win4_22lvl << 16)); // region 4. WRITE_MPEG_REG(DI_MC_CTRL, 0x1f); // enable region level } // handle all case of prepost link. void enable_di_prepost_full( DI_MIF_t *di_inp_mif, DI_MIF_t *di_mem_mif, DI_MIF_t *di_buf0_mif, DI_MIF_t *di_buf1_mif, DI_MIF_t *di_chan2_mif, DI_SIM_MIF_t *di_nrwr_mif, DI_SIM_MIF_t *di_diwr_mif, DI_SIM_MIF_t *di_mtnwr_mif, DI_SIM_MIF_t *di_mtncrd_mif, DI_SIM_MIF_t *di_mtnprd_mif, int nr_en, int mtn_en, int pd32_check_en, int pd22_check_en, int hist_check_en, int ei_en, int blend_en, int blend_mtn_en, int blend_mode, int di_vpp_en, int di_ddr_en, #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) int nr_hfilt_en, int nr_hfilt_mb_en, int mtn_modify_en, int blend_mtn_filt_en, int blend_data_filt_en, int post_mb_en, #endif int post_field_num, int pre_field_num, int prepost_link, int hold_line) { int hist_check_only; int ei_only; int buf1_en; #if defined(CONFIG_ARCH_MESON2) int nr_zone_0, nr_zone_1, nr_zone_2; if (noise_reduction_level == 0) { nr_zone_0 = 1; nr_zone_1 = 3; nr_zone_2 = 5; } else { nr_zone_0 = 3; nr_zone_1 = 6; nr_zone_2 = 10; } #endif hist_check_only = hist_check_en && !nr_en && !mtn_en && !pd22_check_en && !pd32_check_en; ei_only = ei_en && !blend_en && (di_vpp_en || di_ddr_en); #if defined(CONFIG_ARCH_MESON) buf1_en = (!prepost_link && !ei_only && (di_ddr_en || di_vpp_en)); #elif defined(CONFIG_ARCH_MESON2) if (ei_only) { buf1_en = 0; } else { buf1_en = 1; } #endif if (nr_en | mtn_en | pd22_check_en || pd32_check_en) { set_di_inp_mif(di_inp_mif, di_vpp_en && prepost_link , hold_line); set_di_mem_mif(di_mem_mif, di_vpp_en && prepost_link, hold_line); } if (pd22_check_en || hist_check_only) { set_di_chan2_mif(di_chan2_mif, di_vpp_en && prepost_link, hold_line); } #if defined(CONFIG_ARCH_MESON) if (ei_en || di_vpp_en || di_ddr_en) { set_di_if0_mif(di_buf0_mif, di_vpp_en, hold_line); } if (!prepost_link && !ei_only && (di_ddr_en || di_vpp_en)) { set_di_if1_mif(di_buf1_mif, di_vpp_en, hold_line); } #elif defined(CONFIG_ARCH_MESON2) if (prepost_link && !ei_only && (di_ddr_en || di_vpp_en)) { set_di_if1_mif(di_buf1_mif, di_vpp_en, hold_line); } else if (!prepost_link && (ei_en || di_vpp_en || di_ddr_en)) { set_di_if0_mif(di_buf0_mif, di_vpp_en, hold_line); set_di_if1_mif(di_buf1_mif, di_vpp_en, hold_line); } #endif // set nr wr mif interface. if (nr_en) { WRITE_MPEG_REG(DI_NRWR_X, (di_nrwr_mif->start_x << 16) | (di_nrwr_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_NRWR_Y, (di_nrwr_mif->start_y << 16) | (di_nrwr_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_NRWR_CTRL, di_nrwr_mif->canvas_num | // canvas index. ((prepost_link && di_vpp_en) << 8)); // urgent. #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_NR_CTRL0, (1 << 31) | // nr yuv enable. (1 << 30) | // nr range. 3 point (0 << 29) | // max of 3 point. (nr_hfilt_en << 28) | // nr hfilter enable. (nr_hfilt_mb_en << 27) | // nr hfilter motion_blur enable. (nr_zone_2 << 16) | // zone 2 (nr_zone_1 << 8) | // zone 1 (nr_zone_0 << 0)); // zone 0 WRITE_MPEG_REG(DI_NR_CTRL2, (10 << 24) | //intra noise level (1 << 16) | // intra no noise level. (10 << 8) | // inter noise level. (1 << 0)); // inter no noise level. WRITE_MPEG_REG(DI_NR_CTRL3, (16 << 16) | // if any one of 3 point mtn larger than 16 don't use 3 point. 720); // if one line eq cnt is larger than this number, this line is not conunted. #endif } // motion wr mif. if (mtn_en) { WRITE_MPEG_REG(DI_MTNWR_X, (di_mtnwr_mif->start_x << 16) | (di_mtnwr_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNWR_Y, (di_mtnwr_mif->start_y << 16) | (di_mtnwr_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_MTNWR_CTRL, di_mtnwr_mif->canvas_num | // canvas index. ((prepost_link && di_vpp_en) << 8)); // urgent. #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_MTN_CTRL, (1 << 31) | // lpf enable. (1 << 30) | // mtn uv enable. (mtn_modify_en << 29) | // no mtn modify. (2 << 24) | // char diff count. (40 << 16) | // black level. (196 << 8) | // white level. (64 << 0)); // char diff level. WRITE_MPEG_REG(DI_MTN_CTRL1, (3 << 8) | // mtn shift if mtn modifty_en 0); // mtn reduce before shift. #endif } // motion for current display field. #if defined(CONFIG_ARCH_MESON) if (blend_mtn_en) { WRITE_MPEG_REG(DI_MTNCRD_X, (di_mtncrd_mif->start_x << 16) | (di_mtncrd_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNCRD_Y, (di_mtncrd_mif->start_y << 16) | (di_mtncrd_mif->end_y)); // start_y 0 end_y 239. if (!prepost_link) { WRITE_MPEG_REG(DI_MTNRD_CTRL, (di_mtnprd_mif->canvas_num << 8) | //mtnp canvas index. (0 << 16) | // urgent di_mtncrd_mif->canvas_num); // current field mtn canvas index. } else { WRITE_MPEG_REG(DI_MTNRD_CTRL, (0 << 8) | //mtnp canvas index. ((prepost_link && di_vpp_en) << 16) | // urgent di_mtncrd_mif->canvas_num); // current field mtn canvas index. } } if (blend_mtn_en && !prepost_link) { WRITE_MPEG_REG(DI_MTNPRD_X, (di_mtnprd_mif->start_x << 16) | (di_mtnprd_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNPRD_Y, (di_mtnprd_mif->start_y << 16) | (di_mtnprd_mif->end_y)); // start_y 0 end_y 239. } #elif defined(CONFIG_ARCH_MESON2) if (blend_mtn_en) { WRITE_MPEG_REG(DI_MTNCRD_X, (di_mtncrd_mif->start_x << 16) | (di_mtncrd_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNCRD_Y, (di_mtncrd_mif->start_y << 16) | (di_mtncrd_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_MTNPRD_X, (di_mtnprd_mif->start_x << 16) | (di_mtnprd_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNPRD_Y, (di_mtnprd_mif->start_y << 16) | (di_mtnprd_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_MTNRD_CTRL, (di_mtnprd_mif->canvas_num << 8) | //mtnp canvas index. ((prepost_link && di_vpp_en) << 16) | // urgent di_mtncrd_mif->canvas_num); // current field mtn canvas index. } #endif if (di_ddr_en) { WRITE_MPEG_REG(DI_DIWR_X, (di_diwr_mif->start_x << 16) | (di_diwr_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_DIWR_Y, (di_diwr_mif->start_y << 16) | (di_diwr_mif->end_y * 2 + 1)); // start_y 0 end_y 479. WRITE_MPEG_REG(DI_DIWR_CTRL, di_diwr_mif->canvas_num | // canvas index. (di_vpp_en << 8)); // urgent. } #if defined(CONFIG_ARCH_MESON) WRITE_MPEG_REG(DI_PRE_CTRL, nr_en | // NR enable (mtn_en << 1) | // MTN_EN (pd32_check_en << 2) | // check 3:2 pulldown (pd22_check_en << 3) | // check 2:2 pulldown (1 << 4) | // 2:2 check mid pixel come from next field after MTN. (hist_check_en << 5) | // hist check enable (0 << 6) | // hist check not use chan2. ((!nr_en) << 7) | // hist check use data before noise reduction. (pd22_check_en << 8) | // chan 2 enable for 2:2 pull down check. (pd22_check_en << 9) | // line buffer 2 enable (0 << 10) | // pre drop first. (0 << 11) | // pre repeat. (di_vpp_en << 12) | // pre viu link (hold_line << 16) | // pre hold line number (pre_field_num << 29) | // pre field number. (0x1 << 30) // pre soft rst, pre frame rst. ); WRITE_MPEG_REG(DI_POST_CTRL, ((ei_en || di_vpp_en || di_ddr_en) << 0) | // line buffer 0 enable (buf1_en << 1) | // line buffer 1 enable (ei_en << 2) | // ei enable (blend_mtn_en << 3) | // mtn line buffer enable ((blend_mtn_en && !prepost_link) << 4) | // mtnp read mif enable (blend_en << 5) | // di blend enble. (1 << 6) | // di mux output enable (di_ddr_en << 7) | // di write to SDRAM enable. (di_vpp_en << 8) | // di to VPP enable. (0 << 9) | // mif0 to VPP enable. (0 << 10) | // post drop first. (0 << 11) | // post repeat. (1 << 12) | // post viu link (prepost_link << 13) | (hold_line << 16) | // post hold line number (post_field_num << 29) | // post field number. (0x1 << 30) // post soft rst post frame rst. ); #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_PRE_CTRL, nr_en | // NR enable (mtn_en << 1) | // MTN_EN (pd32_check_en << 2) | // check 3:2 pulldown (pd22_check_en << 3) | // check 2:2 pulldown (nr_en << 4) | // 2:2 check mid pixel come from next field after MTN. (hist_check_en << 5) | // hist check enable (1 << 6) | // hist check not use chan2. ((!nr_en) << 7) | // hist check use data before noise reduction. (pd22_check_en << 8) | // chan 2 enable for 2:2 pull down check. (pd22_check_en << 9) | // line buffer 2 enable (0 << 10) | // pre drop first. (0 << 11) | // pre repeat. (di_vpp_en << 12) | // pre viu link (hold_line << 16) | // pre hold line number (nr_en << 22) | // MTN after NR. (pre_field_num << 29) | // pre field number. (0x1 << 30) // pre soft rst, pre frame rst. ); WRITE_MPEG_REG(DI_POST_CTRL, ((ei_en || blend_en) << 0) | // line buffer 0 enable (buf1_en << 1) | // line buffer 1 enable (ei_en << 2) | // ei enable (blend_mtn_en << 3) | // mtn line buffer enable (blend_mtn_en << 4) | // mtnp read mif enable (blend_en << 5) | // di blend enble. (1 << 6) | // di mux output enable (di_ddr_en << 7) | // di write to SDRAM enable. (di_vpp_en << 8) | // di to VPP enable. (0 << 9) | // mif0 to VPP enable. (0 << 10) | // post drop first. (0 << 11) | // post repeat. (di_vpp_en << 12) | // post viu link (prepost_link << 13) | (hold_line << 16) | // post hold line number (post_field_num << 29) | // post field number. (0x1 << 30) // post soft rst post frame rst. ); #endif if (ei_only == 0) { #if defined(CONFIG_ARCH_MESON) WRITE_MPEG_REG(DI_BLEND_CTRL, (READ_MPEG_REG(DI_BLEND_CTRL) & (~((1 << 25) | (3 << 20)))) | // clean some bit we need to set. (blend_mtn_en << 26) | // blend mtn enable. (0 << 25) | // blend with the mtn of the pre display field and next display field. (1 << 24) | // blend with pre display field. (blend_mode << 20) // motion adaptive blend. ); #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_BLEND_CTRL, (post_mb_en << 28) | // post motion blur enable. (0 << 27) | // mtn3p(l, c, r) max. (0 << 26) | // mtn3p(l, c, r) min. (0 << 25) | // mtn3p(l, c, r) ave. (1 << 24) | // mtntopbot max (blend_mtn_filt_en << 23) | // blend mtn filter enable. (blend_data_filt_en << 22) | // blend data filter enable. (blend_mode << 20) | // motion adaptive blend. 25 // kdeint. ); WRITE_MPEG_REG(DI_BLEND_CTRL1, (196 << 24) | // char level (64 << 16) | // angle thredhold. (40 << 8) | // all_af filt thd. (64)); // all 4 equal WRITE_MPEG_REG(DI_BLEND_CTRL2, (4 << 8) | // mtn no mov level. (48)); //black level. #endif } } int di_mode_check(int cur_field) { int i; WRITE_MPEG_REG(DI_INFO_ADDR, 0); #if defined(CONFIG_ARCH_MESON) for (i = 0; i <= 76; i++) #elif defined(CONFIG_ARCH_MESON2) for (i = 0; i <= 82; i++) #endif { di_info[cur_field][i] = READ_MPEG_REG(DI_INFO_DATA); } WRITE_MPEG_REG(DI_PRE_CTRL, READ_MPEG_REG(DI_PRE_CTRL) | (0x1 << 30)); // pre soft rst WRITE_MPEG_REG(DI_POST_CTRL, READ_MPEG_REG(DI_POST_CTRL) | (0x1 << 30)); // post soft rst return (0); } void set_di_inp_fmt_more(int hfmt_en, int hz_yc_ratio, //2bit int hz_ini_phase, //4bit int vfmt_en, int vt_yc_ratio, //2bit int vt_ini_phase, //4bit int y_length, int c_length, int hz_rpt //1bit ) { int repeat_l0_en = 1, nrpt_phase0_en = 0; int vt_phase_step = (16 >> vt_yc_ratio); WRITE_MPEG_REG(DI_INP_FMT_CTRL, (hz_rpt << 28) | //hz rpt pixel (hz_ini_phase << 24) | //hz ini phase (0 << 23) | //repeat p0 enable (hz_yc_ratio << 21) | //hz yc ratio (hfmt_en << 20) | //hz enable (nrpt_phase0_en << 17) | //nrpt_phase0 enable (repeat_l0_en << 16) | //repeat l0 enable (0 << 12) | //skip line num (vt_ini_phase << 8) | //vt ini phase (vt_phase_step << 1) | //vt phase step (3.4) (vfmt_en << 0) //vt enable ); WRITE_MPEG_REG(DI_INP_FMT_W, (y_length << 16) | //hz format width (c_length << 0) //vt format width ); } void set_di_inp_mif(DI_MIF_t *mif, int urgent, int hold_line) { unsigned long bytes_per_pixel; unsigned long demux_mode; unsigned long chro_rpt_lastl_ctrl; unsigned long luma0_rpt_loop_start; unsigned long luma0_rpt_loop_end; unsigned long luma0_rpt_loop_pat; unsigned long chroma0_rpt_loop_start; unsigned long chroma0_rpt_loop_end; unsigned long chroma0_rpt_loop_pat; unsigned long vt_ini_phase = 0; if (mif->set_separate_en == 1 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; luma0_rpt_loop_start = 1; luma0_rpt_loop_end = 1; chroma0_rpt_loop_start = 1; chroma0_rpt_loop_end = 1; luma0_rpt_loop_pat = 0x80; chroma0_rpt_loop_pat = 0x80; if (mif->output_field_num == 0) { vt_ini_phase = 0xe; } else { vt_ini_phase = 0xa; } } else if (mif->set_separate_en == 1 && mif->src_field_mode == 0) { chro_rpt_lastl_ctrl = 1; luma0_rpt_loop_start = 0; luma0_rpt_loop_end = 0; chroma0_rpt_loop_start = 0; chroma0_rpt_loop_end = 0; luma0_rpt_loop_pat = 0x0; chroma0_rpt_loop_pat = 0x0; } else if (mif->set_separate_en == 0 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; luma0_rpt_loop_start = 1; luma0_rpt_loop_end = 1; chroma0_rpt_loop_start = 0; chroma0_rpt_loop_end = 0; luma0_rpt_loop_pat = 0x80; chroma0_rpt_loop_pat = 0x00; } else { chro_rpt_lastl_ctrl = 0; luma0_rpt_loop_start = 0; luma0_rpt_loop_end = 0; chroma0_rpt_loop_start = 0; chroma0_rpt_loop_end = 0; luma0_rpt_loop_pat = 0x00; chroma0_rpt_loop_pat = 0x00; } bytes_per_pixel = mif->set_separate_en ? 0 : (mif->video_mode ? 2 : 1); demux_mode = mif->video_mode; // ---------------------- // General register // ---------------------- WRITE_MPEG_REG(DI_INP_GEN_REG, (urgent << 28) | // chroma urgent bit (urgent << 27) | // luma urgent bit. (1 << 25) | // no dummy data. (hold_line << 19) | // hold lines (1 << 18) | // push dummy pixel (demux_mode << 16) | // demux_mode (bytes_per_pixel << 14) | (mif->burst_size_cr << 12) | (mif->burst_size_cb << 10) | (mif->burst_size_y << 8) | (chro_rpt_lastl_ctrl << 6) | (mif->set_separate_en << 1) | (1 << 0) // cntl_enable ); // ---------------------- // Canvas // ---------------------- WRITE_MPEG_REG(DI_INP_CANVAS0, (mif->canvas0_addr2 << 16) | // cntl_canvas0_addr2 (mif->canvas0_addr1 << 8) | // cntl_canvas0_addr1 (mif->canvas0_addr0 << 0) // cntl_canvas0_addr0 ); // ---------------------- // Picture 0 X/Y start,end // ---------------------- WRITE_MPEG_REG(DI_INP_LUMA_X0, (mif->luma_x_end0 << 16) | // cntl_luma_x_end0 (mif->luma_x_start0 << 0) // cntl_luma_x_start0 ); WRITE_MPEG_REG(DI_INP_LUMA_Y0, (mif->luma_y_end0 << 16) | // cntl_luma_y_end0 (mif->luma_y_start0 << 0) // cntl_luma_y_start0 ); WRITE_MPEG_REG(DI_INP_CHROMA_X0, (mif->chroma_x_end0 << 16) | (mif->chroma_x_start0 << 0) ); WRITE_MPEG_REG(DI_INP_CHROMA_Y0, (mif->chroma_y_end0 << 16) | (mif->chroma_y_start0 << 0) ); // ---------------------- // Repeat or skip // ---------------------- WRITE_MPEG_REG(DI_INP_RPT_LOOP, (0 << 28) | (0 << 24) | (0 << 20) | (0 << 16) | (chroma0_rpt_loop_start << 12) | (chroma0_rpt_loop_end << 8) | (luma0_rpt_loop_start << 4) | (luma0_rpt_loop_end << 0) ) ; WRITE_MPEG_REG(DI_INP_LUMA0_RPT_PAT, luma0_rpt_loop_pat); WRITE_MPEG_REG(DI_INP_CHROMA0_RPT_PAT, chroma0_rpt_loop_pat); // Dummy pixel value WRITE_MPEG_REG(DI_INP_DUMMY_PIXEL, 0x00808000); if ((mif->set_separate_en == 1)) { // 4:2:0 block mode. set_di_inp_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 1, // vfmt_en 1, // vt_yc_ratio vt_ini_phase, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length mif->chroma_x_end0 - mif->chroma_x_start0 + 1 , // c length 0); // hz repeat. } else { set_di_inp_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 0, // vfmt_en 0, // vt_yc_ratio 0, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length ((mif->luma_x_end0 >> 1) - (mif->luma_x_start0 >> 1) + 1), // c length 0); // hz repeat. } } void set_di_mem_fmt_more(int hfmt_en, int hz_yc_ratio, //2bit int hz_ini_phase, //4bit int vfmt_en, int vt_yc_ratio, //2bit int vt_ini_phase, //4bit int y_length, int c_length, int hz_rpt //1bit ) { int vt_phase_step = (16 >> vt_yc_ratio); WRITE_MPEG_REG(DI_MEM_FMT_CTRL, (hz_rpt << 28) | //hz rpt pixel (hz_ini_phase << 24) | //hz ini phase (0 << 23) | //repeat p0 enable (hz_yc_ratio << 21) | //hz yc ratio (hfmt_en << 20) | //hz enable (1 << 17) | //nrpt_phase0 enable (0 << 16) | //repeat l0 enable (0 << 12) | //skip line num (vt_ini_phase << 8) | //vt ini phase (vt_phase_step << 1) | //vt phase step (3.4) (vfmt_en << 0) //vt enable ); WRITE_MPEG_REG(DI_MEM_FMT_W, (y_length << 16) | //hz format width (c_length << 0) //vt format width ); } void set_di_mem_mif(DI_MIF_t *mif, int urgent, int hold_line) { unsigned long bytes_per_pixel; unsigned long demux_mode; unsigned long chro_rpt_lastl_ctrl; unsigned long luma0_rpt_loop_start; unsigned long luma0_rpt_loop_end; unsigned long luma0_rpt_loop_pat; unsigned long chroma0_rpt_loop_start; unsigned long chroma0_rpt_loop_end; unsigned long chroma0_rpt_loop_pat; if (mif->set_separate_en == 1 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; luma0_rpt_loop_start = 1; luma0_rpt_loop_end = 1; chroma0_rpt_loop_start = 1; chroma0_rpt_loop_end = 1; luma0_rpt_loop_pat = 0x80; chroma0_rpt_loop_pat = 0x80; } else if (mif->set_separate_en == 1 && mif->src_field_mode == 0) { chro_rpt_lastl_ctrl = 1; luma0_rpt_loop_start = 0; luma0_rpt_loop_end = 0; chroma0_rpt_loop_start = 0; chroma0_rpt_loop_end = 0; luma0_rpt_loop_pat = 0x0; chroma0_rpt_loop_pat = 0x0; } else if (mif->set_separate_en == 0 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; luma0_rpt_loop_start = 1; luma0_rpt_loop_end = 1; chroma0_rpt_loop_start = 0; chroma0_rpt_loop_end = 0; luma0_rpt_loop_pat = 0x80; chroma0_rpt_loop_pat = 0x00; } else { chro_rpt_lastl_ctrl = 0; luma0_rpt_loop_start = 0; luma0_rpt_loop_end = 0; chroma0_rpt_loop_start = 0; chroma0_rpt_loop_end = 0; luma0_rpt_loop_pat = 0x00; chroma0_rpt_loop_pat = 0x00; } bytes_per_pixel = mif->set_separate_en ? 0 : (mif->video_mode ? 2 : 1); demux_mode = mif->video_mode; // ---------------------- // General register // ---------------------- WRITE_MPEG_REG(DI_MEM_GEN_REG, (urgent << 28) | // urgent bit. (urgent << 27) | // urgent bit. (1 << 25) | // no dummy data. (hold_line << 19) | // hold lines (1 << 18) | // push dummy pixel (demux_mode << 16) | // demux_mode (bytes_per_pixel << 14) | (mif->burst_size_cr << 12) | (mif->burst_size_cb << 10) | (mif->burst_size_y << 8) | (chro_rpt_lastl_ctrl << 6) | (mif->set_separate_en << 1) | (1 << 0) // cntl_enable ); // ---------------------- // Canvas // ---------------------- WRITE_MPEG_REG(DI_MEM_CANVAS0, (mif->canvas0_addr2 << 16) | // cntl_canvas0_addr2 (mif->canvas0_addr1 << 8) | // cntl_canvas0_addr1 (mif->canvas0_addr0 << 0) // cntl_canvas0_addr0 ); // ---------------------- // Picture 0 X/Y start,end // ---------------------- WRITE_MPEG_REG(DI_MEM_LUMA_X0, (mif->luma_x_end0 << 16) | // cntl_luma_x_end0 (mif->luma_x_start0 << 0) // cntl_luma_x_start0 ); WRITE_MPEG_REG(DI_MEM_LUMA_Y0, (mif->luma_y_end0 << 16) | // cntl_luma_y_end0 (mif->luma_y_start0 << 0) // cntl_luma_y_start0 ); WRITE_MPEG_REG(DI_MEM_CHROMA_X0, (mif->chroma_x_end0 << 16) | (mif->chroma_x_start0 << 0) ); WRITE_MPEG_REG(DI_MEM_CHROMA_Y0, (mif->chroma_y_end0 << 16) | (mif->chroma_y_start0 << 0) ); // ---------------------- // Repeat or skip // ---------------------- WRITE_MPEG_REG(DI_MEM_RPT_LOOP, (0 << 28) | (0 << 24) | (0 << 20) | (0 << 16) | (chroma0_rpt_loop_start << 12) | (chroma0_rpt_loop_end << 8) | (luma0_rpt_loop_start << 4) | (luma0_rpt_loop_end << 0) ) ; WRITE_MPEG_REG(DI_MEM_LUMA0_RPT_PAT, luma0_rpt_loop_pat); WRITE_MPEG_REG(DI_MEM_CHROMA0_RPT_PAT, chroma0_rpt_loop_pat); // Dummy pixel value WRITE_MPEG_REG(DI_MEM_DUMMY_PIXEL, 0x00808000); if ((mif->set_separate_en == 1)) { // 4:2:0 block mode. set_di_mem_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 1, // vfmt_en 1, // vt_yc_ratio 0, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length mif->chroma_x_end0 - mif->chroma_x_start0 + 1, // c length 0); // hz repeat. } else { set_di_mem_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 0, // vfmt_en 0, // vt_yc_ratio 0, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length ((mif->luma_x_end0 >> 1) - (mif->luma_x_start0 >> 1) + 1), // c length 0); // hz repeat. } } void set_di_if1_fmt_more(int hfmt_en, int hz_yc_ratio, //2bit int hz_ini_phase, //4bit int vfmt_en, int vt_yc_ratio, //2bit int vt_ini_phase, //4bit int y_length, int c_length, int hz_rpt //1bit ) { int vt_phase_step = (16 >> vt_yc_ratio); WRITE_MPEG_REG(DI_IF1_FMT_CTRL, (hz_rpt << 28) | //hz rpt pixel (hz_ini_phase << 24) | //hz ini phase (0 << 23) | //repeat p0 enable (hz_yc_ratio << 21) | //hz yc ratio (hfmt_en << 20) | //hz enable (1 << 17) | //nrpt_phase0 enable (0 << 16) | //repeat l0 enable (0 << 12) | //skip line num (vt_ini_phase << 8) | //vt ini phase (vt_phase_step << 1) | //vt phase step (3.4) (vfmt_en << 0) //vt enable ); WRITE_MPEG_REG(DI_IF1_FMT_W, (y_length << 16) | //hz format width (c_length << 0) //vt format width ); } void set_di_if1_mif(DI_MIF_t *mif, int urgent, int hold_line) { unsigned long bytes_per_pixel; unsigned long demux_mode; unsigned long chro_rpt_lastl_ctrl; unsigned long luma0_rpt_loop_start; unsigned long luma0_rpt_loop_end; unsigned long luma0_rpt_loop_pat; unsigned long chroma0_rpt_loop_start; unsigned long chroma0_rpt_loop_end; unsigned long chroma0_rpt_loop_pat; if (mif->set_separate_en == 1 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; luma0_rpt_loop_start = 1; luma0_rpt_loop_end = 1; chroma0_rpt_loop_start = 1; chroma0_rpt_loop_end = 1; luma0_rpt_loop_pat = 0x80; chroma0_rpt_loop_pat = 0x80; } else if (mif->set_separate_en == 1 && mif->src_field_mode == 0) { chro_rpt_lastl_ctrl = 1; luma0_rpt_loop_start = 0; luma0_rpt_loop_end = 0; chroma0_rpt_loop_start = 0; chroma0_rpt_loop_end = 0; luma0_rpt_loop_pat = 0x0; chroma0_rpt_loop_pat = 0x0; } else if (mif->set_separate_en == 0 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; luma0_rpt_loop_start = 1; luma0_rpt_loop_end = 1; chroma0_rpt_loop_start = 0; chroma0_rpt_loop_end = 0; luma0_rpt_loop_pat = 0x80; chroma0_rpt_loop_pat = 0x00; } else { chro_rpt_lastl_ctrl = 0; luma0_rpt_loop_start = 0; luma0_rpt_loop_end = 0; chroma0_rpt_loop_start = 0; chroma0_rpt_loop_end = 0; luma0_rpt_loop_pat = 0x00; chroma0_rpt_loop_pat = 0x00; } bytes_per_pixel = mif->set_separate_en ? 0 : (mif->video_mode ? 2 : 1); demux_mode = mif->video_mode; // ---------------------- // General register // ---------------------- WRITE_MPEG_REG(DI_IF1_GEN_REG, (urgent << 28) | // urgent (urgent << 27) | // luma urgent (1 << 25) | // no dummy data. (hold_line << 19) | // hold lines (1 << 18) | // push dummy pixel (demux_mode << 16) | // demux_mode (bytes_per_pixel << 14) | (mif->burst_size_cr << 12) | (mif->burst_size_cb << 10) | (mif->burst_size_y << 8) | (chro_rpt_lastl_ctrl << 6) | (mif->set_separate_en << 1) | (1 << 0) // cntl_enable ); // ---------------------- // Canvas // ---------------------- WRITE_MPEG_REG(DI_IF1_CANVAS0, (mif->canvas0_addr2 << 16) | // cntl_canvas0_addr2 (mif->canvas0_addr1 << 8) | // cntl_canvas0_addr1 (mif->canvas0_addr0 << 0) // cntl_canvas0_addr0 ); // ---------------------- // Picture 0 X/Y start,end // ---------------------- WRITE_MPEG_REG(DI_IF1_LUMA_X0, (mif->luma_x_end0 << 16) | // cntl_luma_x_end0 (mif->luma_x_start0 << 0) // cntl_luma_x_start0 ); WRITE_MPEG_REG(DI_IF1_LUMA_Y0, (mif->luma_y_end0 << 16) | // cntl_luma_y_end0 (mif->luma_y_start0 << 0) // cntl_luma_y_start0 ); WRITE_MPEG_REG(DI_IF1_CHROMA_X0, (mif->chroma_x_end0 << 16) | (mif->chroma_x_start0 << 0) ); WRITE_MPEG_REG(DI_IF1_CHROMA_Y0, (mif->chroma_y_end0 << 16) | (mif->chroma_y_start0 << 0) ); // ---------------------- // Repeat or skip // ---------------------- WRITE_MPEG_REG(DI_IF1_RPT_LOOP, (0 << 28) | (0 << 24) | (0 << 20) | (0 << 16) | (chroma0_rpt_loop_start << 12) | (chroma0_rpt_loop_end << 8) | (luma0_rpt_loop_start << 4) | (luma0_rpt_loop_end << 0) ) ; WRITE_MPEG_REG(DI_IF1_LUMA0_RPT_PAT, luma0_rpt_loop_pat); WRITE_MPEG_REG(DI_IF1_CHROMA0_RPT_PAT, chroma0_rpt_loop_pat); // Dummy pixel value WRITE_MPEG_REG(DI_IF1_DUMMY_PIXEL, 0x00808000); if ((mif->set_separate_en == 1)) { // 4:2:0 block mode. set_di_if1_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 1, // vfmt_en 1, // vt_yc_ratio 0, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length mif->chroma_x_end0 - mif->chroma_x_start0 + 1 , // c length 0); // hz repeat. } else { set_di_if1_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 0, // vfmt_en 0, // vt_yc_ratio 0, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length ((mif->luma_x_end0 >> 1) - (mif->luma_x_start0 >> 1) + 1), // c length 0); // hz repeat. } } void set_di_chan2_mif(DI_MIF_t *mif, int urgent, int hold_line) { unsigned long bytes_per_pixel; unsigned long demux_mode; unsigned long luma0_rpt_loop_start; unsigned long luma0_rpt_loop_end; unsigned long luma0_rpt_loop_pat; bytes_per_pixel = mif->set_separate_en ? 0 : ((mif->video_mode == 1) ? 2 : 1); demux_mode = mif->video_mode & 1; if (mif->src_field_mode == 1) { luma0_rpt_loop_start = 1; luma0_rpt_loop_end = 1; luma0_rpt_loop_pat = 0x80; } else { luma0_rpt_loop_start = 0; luma0_rpt_loop_end = 0; luma0_rpt_loop_pat = 0; } // ---------------------- // General register // ---------------------- WRITE_MPEG_REG(DI_CHAN2_GEN_REG, (urgent << 28) | // urgent (urgent << 27) | // luma urgent (1 << 25) | // no dummy data. (hold_line << 19) | // hold lines (1 << 18) | // push dummy pixel (demux_mode << 16) | // demux_mode (bytes_per_pixel << 14) | (0 << 12) | (0 << 10) | (mif->burst_size_y << 8) | ((hold_line == 0 ? 1 : 0) << 7) | //manual start. (0 << 6) | (0 << 1) | (1 << 0) // cntl_enable ); // ---------------------- // Canvas // ---------------------- WRITE_MPEG_REG(DI_CHAN2_CANVAS, (0 << 16) | // cntl_canvas0_addr2 (0 << 8) | // cntl_canvas0_addr1 (mif->canvas0_addr0 << 0) // cntl_canvas0_addr0 ); // ---------------------- // Picture 0 X/Y start,end // ---------------------- WRITE_MPEG_REG(DI_CHAN2_LUMA_X, (mif->luma_x_end0 << 16) | // cntl_luma_x_end0 (mif->luma_x_start0 << 0) // cntl_luma_x_start0 ); WRITE_MPEG_REG(DI_CHAN2_LUMA_Y, (mif->luma_y_end0 << 16) | // cntl_luma_y_end0 (mif->luma_y_start0 << 0) // cntl_luma_y_start0 ); // ---------------------- // Repeat or skip // ---------------------- WRITE_MPEG_REG(DI_CHAN2_RPT_LOOP, (0 << 28) | (0 << 24) | (0 << 20) | (0 << 16) | (0 << 12) | (0 << 8) | (luma0_rpt_loop_start << 4) | (luma0_rpt_loop_end << 0) ); WRITE_MPEG_REG(DI_CHAN2_LUMA_RPT_PAT, luma0_rpt_loop_pat); // Dummy pixel value WRITE_MPEG_REG(DI_CHAN2_DUMMY_PIXEL, 0x00808000); } void set_di_if0_mif(DI_MIF_t *mif, int urgent, int hold_line) { unsigned long bytes_per_pixel; unsigned long demux_mode; unsigned long chro_rpt_lastl_ctrl; unsigned long luma0_rpt_loop_start; unsigned long luma0_rpt_loop_end; unsigned long luma0_rpt_loop_pat; unsigned long chroma0_rpt_loop_start; unsigned long chroma0_rpt_loop_end; unsigned long chroma0_rpt_loop_pat; if (mif->set_separate_en == 1 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; luma0_rpt_loop_start = 1; luma0_rpt_loop_end = 1; chroma0_rpt_loop_start = 1; chroma0_rpt_loop_end = 1; luma0_rpt_loop_pat = 0x80; chroma0_rpt_loop_pat = 0x80; } else if (mif->set_separate_en == 1 && mif->src_field_mode == 0) { chro_rpt_lastl_ctrl = 1; luma0_rpt_loop_start = 0; luma0_rpt_loop_end = 0; chroma0_rpt_loop_start = 0; chroma0_rpt_loop_end = 0; luma0_rpt_loop_pat = 0x0; chroma0_rpt_loop_pat = 0x0; } else if (mif->set_separate_en == 0 && mif->src_field_mode == 1) { chro_rpt_lastl_ctrl = 1; luma0_rpt_loop_start = 1; luma0_rpt_loop_end = 1; chroma0_rpt_loop_start = 0; chroma0_rpt_loop_end = 0; luma0_rpt_loop_pat = 0x80; chroma0_rpt_loop_pat = 0x00; } else { chro_rpt_lastl_ctrl = 0; luma0_rpt_loop_start = 0; luma0_rpt_loop_end = 0; chroma0_rpt_loop_start = 0; chroma0_rpt_loop_end = 0; luma0_rpt_loop_pat = 0x00; chroma0_rpt_loop_pat = 0x00; } bytes_per_pixel = mif->set_separate_en ? 0 : (mif->video_mode ? 2 : 1); demux_mode = mif->video_mode; // ---------------------- // General register // ---------------------- WRITE_MPEG_REG(VD1_IF0_GEN_REG, (urgent << 28) | // urgent (urgent << 27) | // luma urgent (1 << 25) | // no dummy data. (hold_line << 19) | // hold lines (1 << 18) | // push dummy pixel (demux_mode << 16) | // demux_mode (bytes_per_pixel << 14) | (mif->burst_size_cr << 12) | (mif->burst_size_cb << 10) | (mif->burst_size_y << 8) | (chro_rpt_lastl_ctrl << 6) | (mif->set_separate_en << 1) | (1 << 0) // cntl_enable ); // ---------------------- // Canvas // ---------------------- WRITE_MPEG_REG(VD1_IF0_CANVAS0, (mif->canvas0_addr2 << 16) | // cntl_canvas0_addr2 (mif->canvas0_addr1 << 8) | // cntl_canvas0_addr1 (mif->canvas0_addr0 << 0) // cntl_canvas0_addr0 ); // ---------------------- // Picture 0 X/Y start,end // ---------------------- WRITE_MPEG_REG(VD1_IF0_LUMA_X0, (mif->luma_x_end0 << 16) | // cntl_luma_x_end0 (mif->luma_x_start0 << 0) // cntl_luma_x_start0 ); WRITE_MPEG_REG(VD1_IF0_LUMA_Y0, (mif->luma_y_end0 << 16) | // cntl_luma_y_end0 (mif->luma_y_start0 << 0) // cntl_luma_y_start0 ); WRITE_MPEG_REG(VD1_IF0_CHROMA_X0, (mif->chroma_x_end0 << 16) | (mif->chroma_x_start0 << 0) ); WRITE_MPEG_REG(VD1_IF0_CHROMA_Y0, (mif->chroma_y_end0 << 16) | (mif->chroma_y_start0 << 0) ); // ---------------------- // Repeat or skip // ---------------------- WRITE_MPEG_REG(VD1_IF0_RPT_LOOP, (0 << 28) | (0 << 24) | (0 << 20) | (0 << 16) | (chroma0_rpt_loop_start << 12) | (chroma0_rpt_loop_end << 8) | (luma0_rpt_loop_start << 4) | (luma0_rpt_loop_end << 0) ) ; WRITE_MPEG_REG(VD1_IF0_LUMA0_RPT_PAT, luma0_rpt_loop_pat); WRITE_MPEG_REG(VD1_IF0_CHROMA0_RPT_PAT, chroma0_rpt_loop_pat); // Dummy pixel value WRITE_MPEG_REG(VD1_IF0_DUMMY_PIXEL, 0x00808000); // ---------------------- // Picture 1 unused // ---------------------- WRITE_MPEG_REG(VD1_IF0_LUMA_X1, 0); // unused WRITE_MPEG_REG(VD1_IF0_LUMA_Y1, 0); // unused WRITE_MPEG_REG(VD1_IF0_CHROMA_X1, 0); // unused WRITE_MPEG_REG(VD1_IF0_CHROMA_Y1, 0); // unused WRITE_MPEG_REG(VD1_IF0_LUMA_PSEL, 0); // unused only one picture WRITE_MPEG_REG(VD1_IF0_CHROMA_PSEL, 0); // unused only one picture if ((mif->set_separate_en == 1)) { // 4:2:0 block mode. set_vd1_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 1, // vfmt_en 1, // vt_yc_ratio 0, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length mif->chroma_x_end0 - mif->chroma_x_start0 + 1 , // c length 0); // hz repeat. } else { set_vd1_fmt_more( 1, // hfmt_en 1, // hz_yc_ratio 0, // hz_ini_phase 0, // vfmt_en 0, // vt_yc_ratio 0, // vt_ini_phase mif->luma_x_end0 - mif->luma_x_start0 + 1, // y_length ((mif->luma_x_end0 >> 1) - (mif->luma_x_start0 >> 1) + 1) , //c length 0); // hz repeat. } } //enable deinterlace pre module separated for pre post separate tests. void enable_di_pre( DI_MIF_t *di_inp_mif, DI_MIF_t *di_mem_mif, DI_MIF_t *di_chan2_mif, DI_SIM_MIF_t *di_nrwr_mif, DI_SIM_MIF_t *di_mtnwr_mif, int nr_en, int mtn_en, int pd32_check_en, int pd22_check_en, int hist_check_en, #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) int nr_hfilt_en, int nr_hfilt_mb_en, int mtn_modify_en, #endif int pre_field_num, int pre_viu_link, int hold_line) { int hist_check_only; #if defined(CONFIG_ARCH_MESON2) int nr_zone_0, nr_zone_1, nr_zone_2; if (noise_reduction_level == 0) { nr_zone_0 = 1; nr_zone_1 = 3; nr_zone_2 = 5; } else { nr_zone_0 = 3; nr_zone_1 = 6; nr_zone_2 = 10; } #endif hist_check_only = hist_check_en && !nr_en && !mtn_en && !pd22_check_en && !pd32_check_en ; if (nr_en | mtn_en | pd22_check_en || pd32_check_en) { set_di_mem_mif(di_mem_mif, 0, hold_line); // set urgent 0 if (!vdin_en) { set_di_inp_mif(di_inp_mif, 0, hold_line); // set urgent 0 } } if (pd22_check_en || hist_check_only) { set_di_chan2_mif(di_chan2_mif, 0, hold_line); // set urgent 0. } // set nr wr mif interface. if (nr_en) { WRITE_MPEG_REG(DI_NRWR_X, (di_nrwr_mif->start_x << 16) | (di_nrwr_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_NRWR_Y, (di_nrwr_mif->start_y << 16) | (di_nrwr_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_NRWR_CTRL, di_nrwr_mif->canvas_num); // canvas index. #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_NR_CTRL0, (1 << 31) | // nr yuv enable. (1 << 30) | // nr range. 3 point (0 << 29) | // max of 3 point. (nr_hfilt_en << 28) | // nr hfilter enable. (nr_hfilt_mb_en << 27) | // nr hfilter motion_blur enable. (nr_zone_2 << 16) | // zone 2 (nr_zone_1 << 8) | // zone 1 (nr_zone_0 << 0)); // zone 0 WRITE_MPEG_REG(DI_NR_CTRL2, (10 << 24) | //intra noise level (1 << 16) | // intra no noise level. (10 << 8) | // inter noise level. (1 << 0)); // inter no noise level. WRITE_MPEG_REG(DI_NR_CTRL3, (16 << 16) | // if any one of 3 point mtn larger than 16 don't use 3 point. 720); // if one line eq cnt is larger than this number, this line is not conunted. #endif } // motion wr mif. if (mtn_en) { WRITE_MPEG_REG(DI_MTNWR_X, (di_mtnwr_mif->start_x << 16) | (di_mtnwr_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNWR_Y, (di_mtnwr_mif->start_y << 16) | (di_mtnwr_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_MTNWR_CTRL, di_mtnwr_mif->canvas_num | // canvas index. (0 << 8)); // urgent. #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_MTN_CTRL, (1 << 31) | // lpf enable. (1 << 30) | // mtn uv enable. (mtn_modify_en << 29) | // no mtn modify. (2 << 24) | // char diff count. (40 << 16) | // black level. (196 << 8) | // white level. (64 << 0)); // char diff level. WRITE_MPEG_REG(DI_MTN_CTRL1, (3 << 8) | // mtn shift if mtn modifty_en 0); // mtn reduce before shift. #endif } // reset pre WRITE_MPEG_REG(DI_PRE_CTRL, READ_MPEG_REG(DI_PRE_CTRL) | 1 << 31); // frame reset for the pre modules. #if defined(CONFIG_ARCH_MESON) WRITE_MPEG_REG(DI_PRE_CTRL, nr_en | // NR enable (mtn_en << 1) | // MTN_EN (pd32_check_en << 2) | // check 3:2 pulldown (pd22_check_en << 3) | // check 2:2 pulldown (1 << 4) | // 2:2 check mid pixel come from next field after MTN. (hist_check_en << 5) | // hist check enable (hist_check_only << 6) | // hist check use chan2. ((!nr_en) << 7) | // hist check use data before noise reduction. ((pd22_check_en || hist_check_only) << 8) | // chan 2 enable for 2:2 pull down check. (pd22_check_en << 9) | // line buffer 2 enable (0 << 10) | // pre drop first. (0 << 11) | // pre repeat. (0 << 12) | // pre viu link (hold_line << 16) | // pre hold line number (pre_field_num << 29) | // pre field number. (0x1 << 30) // pre soft rst, pre frame rst. ); #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_PRE_CTRL, nr_en | // NR enable (mtn_en << 1) | // MTN_EN (pd32_check_en << 2) | // check 3:2 pulldown (pd22_check_en << 3) | // check 2:2 pulldown (1 << 4) | // 2:2 check mid pixel come from next field after MTN. (hist_check_en << 5) | // hist check enable (1 << 6) | // hist check use chan2. ((!nr_en) << 7) | // hist check use data before noise reduction. ((pd22_check_en || hist_check_only) << 8) | // chan 2 enable for 2:2 pull down check. (pd22_check_en << 9) | // line buffer 2 enable (0 << 10) | // pre drop first. (0 << 11) | // pre repeat. (0 << 12) | // pre viu link (hold_line << 16) | // pre hold line number (1 << 22) | // MTN after NR. (pre_field_num << 29) | // pre field number. (0x1 << 30) // pre soft rst, pre frame rst. ); #endif } // enable di post module for separate test. void enable_di_post( DI_MIF_t *di_buf0_mif, DI_MIF_t *di_buf1_mif, DI_SIM_MIF_t *di_diwr_mif, DI_SIM_MIF_t *di_mtncrd_mif, DI_SIM_MIF_t *di_mtnprd_mif, int ei_en, int blend_en, int blend_mtn_en, int blend_mode, int di_vpp_en, int di_ddr_en, #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) int blend_mtn_filt_en, int blend_data_filt_en, int post_mb_en, #endif int post_field_num, int hold_line) { int ei_only; int buf1_en; ei_only = ei_en && !blend_en && (di_vpp_en || di_ddr_en); buf1_en = (!ei_only && (di_ddr_en || di_vpp_en)); if (ei_en || di_vpp_en || di_ddr_en) { set_di_if0_mif(di_buf0_mif, di_vpp_en, hold_line); } if (!ei_only && (di_ddr_en || di_vpp_en)) { set_di_if1_mif(di_buf1_mif, di_vpp_en, hold_line); } // motion for current display field. if (blend_mtn_en) { WRITE_MPEG_REG(DI_MTNPRD_X, (di_mtnprd_mif->start_x << 16) | (di_mtnprd_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNPRD_Y, (di_mtnprd_mif->start_y << 16) | (di_mtnprd_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_MTNCRD_X, (di_mtncrd_mif->start_x << 16) | (di_mtncrd_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_MTNCRD_Y, (di_mtncrd_mif->start_y << 16) | (di_mtncrd_mif->end_y)); // start_y 0 end_y 239. WRITE_MPEG_REG(DI_MTNRD_CTRL, (di_mtnprd_mif->canvas_num << 8) | //mtnp canvas index. (1 << 16) | // urgent di_mtncrd_mif->canvas_num); // current field mtn canvas index. } if (di_ddr_en) { WRITE_MPEG_REG(DI_DIWR_X, (di_diwr_mif->start_x << 16) | (di_diwr_mif->end_x)); // start_x 0 end_x 719. WRITE_MPEG_REG(DI_DIWR_Y, (di_diwr_mif->start_y << 16) | (di_diwr_mif->end_y * 2 + 1)); // start_y 0 end_y 479. WRITE_MPEG_REG(DI_DIWR_CTRL, di_diwr_mif->canvas_num | // canvas index. (di_vpp_en << 8)); // urgent. } if (ei_only == 0) { #if defined(CONFIG_ARCH_MESON) WRITE_MPEG_REG(DI_BLEND_CTRL, (READ_MPEG_REG(DI_BLEND_CTRL) & (~((1 << 25) | (3 << 20)))) | // clean some bit we need to set. (blend_mtn_en << 26) | // blend mtn enable. (0 << 25) | // blend with the mtn of the pre display field and next display field. (1 << 24) | // blend with pre display field. (blend_mode << 20) // motion adaptive blend. ); #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_BLEND_CTRL, (post_mb_en << 28) | // post motion blur enable. (0 << 27) | // mtn3p(l, c, r) max. (0 << 26) | // mtn3p(l, c, r) min. (0 << 25) | // mtn3p(l, c, r) ave. (1 << 24) | // mtntopbot max (blend_mtn_filt_en << 23) | // blend mtn filter enable. (blend_data_filt_en << 22) | // blend data filter enable. (blend_mode << 20) | // motion adaptive blend. 25 // kdeint. ); WRITE_MPEG_REG(DI_BLEND_CTRL1, (196 << 24) | // char level (64 << 16) | // angle thredhold. (40 << 8) | // all_af filt thd. (64)); // all 4 equal WRITE_MPEG_REG(DI_BLEND_CTRL2, (4 << 8) | // mtn no mov level. (48)); //black level. #endif } #if defined(CONFIG_ARCH_MESON) WRITE_MPEG_REG(DI_POST_CTRL, ((ei_en | blend_en) << 0) | // line buffer 0 enable (0 << 1) | // line buffer 1 enable (ei_en << 2) | // ei enable (blend_mtn_en << 3) | // mtn line buffer enable (blend_mtn_en << 4) | // mtnp read mif enable (blend_en << 5) | // di blend enble. (1 << 6) | // di mux output enable (di_ddr_en << 7) | // di write to SDRAM enable. (di_vpp_en << 8) | // di to VPP enable. (0 << 9) | // mif0 to VPP enable. (0 << 10) | // post drop first. (0 << 11) | // post repeat. (1 << 12) | // post viu link (hold_line << 16) | // post hold line number (post_field_num << 29) | // post field number. (0x1 << 30) // post soft rst post frame rst. ); #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_POST_CTRL, ((ei_en | blend_en) << 0) | // line buffer 0 enable (0 << 1) | // line buffer 1 enable (ei_en << 2) | // ei enable (blend_mtn_en << 3) | // mtn line buffer enable (blend_mtn_en << 4) | // mtnp read mif enable (blend_en << 5) | // di blend enble. (1 << 6) | // di mux output enable (di_ddr_en << 7) | // di write to SDRAM enable. (di_vpp_en << 8) | // di to VPP enable. (0 << 9) | // mif0 to VPP enable. (0 << 10) | // post drop first. (0 << 11) | // post repeat. (di_vpp_en << 12) | // post viu link (hold_line << 16) | // post hold line number (post_field_num << 29) | // post field number. (0x1 << 30) // post soft rst post frame rst. ); #endif } int di_pre_mode_check(int cur_field) { int i; WRITE_MPEG_REG(DI_INFO_ADDR, 0); for (i = 0; i <= 68; i++) { di_info[cur_field][i] = READ_MPEG_REG(DI_INFO_DATA); } #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) WRITE_MPEG_REG(DI_INFO_ADDR, 77); for (i = 77; i <= 82; i++) { di_info[cur_field][i] = READ_MPEG_REG(DI_INFO_DATA); } #endif return (0); } int di_post_mode_check(int cur_field) { int i; WRITE_MPEG_REG(DI_INFO_ADDR, 69); for (i = 69; i <= 76; i++) { di_info[cur_field][i] = READ_MPEG_REG(DI_INFO_DATA); } return (0); } void enable_region_blend( int reg0_en, int reg0_start_x, int reg0_end_x, int reg0_start_y, int reg0_end_y, int reg0_mode, int reg1_en, int reg1_start_x, int reg1_end_x, int reg1_start_y, int reg1_end_y, int reg1_mode, int reg2_en, int reg2_start_x, int reg2_end_x, int reg2_start_y, int reg2_end_y, int reg2_mode, int reg3_en, int reg3_start_x, int reg3_end_x, int reg3_start_y, int reg3_end_y, int reg3_mode) { WRITE_MPEG_REG(DI_BLEND_REG0_X, (reg0_start_x << 16) | reg0_end_x); WRITE_MPEG_REG(DI_BLEND_REG0_Y, (reg0_start_y << 16) | reg0_end_y); WRITE_MPEG_REG(DI_BLEND_REG1_X, (reg1_start_x << 16) | reg1_end_x); WRITE_MPEG_REG(DI_BLEND_REG1_Y, (reg1_start_y << 16) | reg1_end_y); WRITE_MPEG_REG(DI_BLEND_REG2_X, (reg2_start_x << 16) | reg2_end_x); WRITE_MPEG_REG(DI_BLEND_REG2_Y, (reg2_start_y << 16) | reg2_end_y); WRITE_MPEG_REG(DI_BLEND_REG3_X, (reg3_start_x << 16) | reg3_end_x); WRITE_MPEG_REG(DI_BLEND_REG3_Y, (reg3_start_y << 16) | reg3_end_y); WRITE_MPEG_REG(DI_BLEND_CTRL, (READ_MPEG_REG(DI_BLEND_CTRL) & (~(0xfff << 8))) | (reg0_mode << 8) | (reg1_mode << 10) | (reg2_mode << 12) | (reg3_mode << 14) | (reg0_en << 16) | (reg1_en << 17) | (reg2_en << 18) | (reg3_en << 19)); } int check_p32_p22(int cur_field, int pre_field, int pre2_field) { unsigned int cur_data, pre_data, pre2_data; unsigned int cur_num, pre_num, pre2_num; unsigned int data_diff, num_diff; di_p22_info = di_p22_info << 1; cur_data = di_info[cur_field][2]; pre_data = di_info[pre_field][2]; pre2_data = di_info[pre2_field][2]; cur_num = di_info[cur_field][4] & 0xffffff; pre_num = di_info[pre_field][4] & 0xffffff; pre2_num = di_info[pre2_field][4] & 0xffffff; if (cur_data * 2 <= pre_data && pre2_data * 2 <= pre_data && cur_num * 2 <= pre_num && pre2_num * 2 <= pre_num) { di_p22_info |= 1; } di_p32_info = di_p32_info << 1; di_p32_info_2 = di_p32_info_2 << 1; di_p22_info_2 = di_p22_info_2 << 1; cur_data = di_info[cur_field][0]; cur_num = di_info[cur_field][1] & 0xffffff; pre_data = di_info[pre_field][0]; pre_num = di_info[pre_field][1] & 0xffffff; data_diff = cur_data > pre_data ? cur_data - pre_data : pre_data - cur_data; num_diff = cur_num > pre_num ? cur_num - pre_num : pre_num - cur_num; if ((di_p22_info & 0x1) && data_diff * 10 <= cur_data && num_diff * 10 <= cur_num) { di_p22_info_2 |= 1; } if (di_p32_counter > 0 || di_p32_info == 0) { if (cur_data * 2 <= pre_data && cur_num * 50 <= pre_num) { di_p32_info |= 1; last_big_data = pre_data; last_big_num = pre_num; di_p32_counter = -1; } else { last_big_data = 0; last_big_num = 0; if ((di_p32_counter & 0x1) && data_diff * 5 <= cur_data && num_diff * 5 <= cur_num) { di_p32_info_2 |= 1; } } } else { if (cur_data * 2 <= last_big_data && cur_num * 50 <= last_big_num) { di_p32_info |= 1; di_p32_counter = -1; } } di_p32_counter++; return 0; } void pattern_check_prepost(void) { if (pre_field_counter != di_checked_field) { di_checked_field = pre_field_counter; di_mode_check(pre_field_counter % 4); #ifdef DEBUG debug_array[(pre_field_counter & 0x3ff) * 4] = di_info[pre_field_counter % 4][0]; debug_array[(pre_field_counter & 0x3ff) * 4 + 1] = di_info[pre_field_counter % 4][1] & 0xffffff; debug_array[(pre_field_counter & 0x3ff) * 4 + 2] = di_info[pre_field_counter % 4][2]; debug_array[(pre_field_counter & 0x3ff) * 4 + 3] = di_info[pre_field_counter % 4][4]; #endif if (pre_field_counter >= 3) { check_p32_p22(pre_field_counter % 4, (pre_field_counter + 3) % 4, (pre_field_counter + 2) % 4); #if defined(CONFIG_ARCH_MESON) pattern_22 = pattern_22 << 1; if (di_info[pre_field_counter % 4][4] < di_info[(pre_field_counter + 3) % 4][4]) { pattern_22 |= 1; } #endif } } di_chan2_mif.canvas0_addr0 = DEINTERLACE_CANVAS_BASE_INDEX + (field_counter + 3) % 4; di_mem_mif.canvas0_addr0 = DEINTERLACE_CANVAS_BASE_INDEX + (field_counter + 2) % 4; blend_mode = 3; #if defined(CONFIG_ARCH_MESON) di_buf0_mif.canvas0_addr0 = DEINTERLACE_CANVAS_BASE_INDEX + (field_counter + 3) % 4; // 2:2 check if (((di_p22_info & PATTERN22_MARK) == (0xaaaaaaaaaaaaaaaaLL & PATTERN22_MARK)) && ((di_p22_info_2 & PATTERN22_MARK) == (0xaaaaaaaaaaaaaaaaLL & PATTERN22_MARK))) { blend_mode = 1; } else if (((di_p22_info & PATTERN22_MARK) == (0x5555555555555555LL & PATTERN22_MARK)) && ((di_p22_info_2 & PATTERN22_MARK) == (0x5555555555555555LL & PATTERN22_MARK))) { blend_mode = 0; } #elif defined(CONFIG_ARCH_MESON2) di_buf1_mif.canvas0_addr0 = DEINTERLACE_CANVAS_BASE_INDEX + (field_counter + 1) % 4; if (((di_p22_info & PATTERN22_MARK) == (0x5555555555555555LL & PATTERN22_MARK)) && ((di_p22_info_2 & PATTERN22_MARK) == (0x5555555555555555LL & PATTERN22_MARK))) { di_buf1_mif.canvas0_addr0 = DEINTERLACE_CANVAS_BASE_INDEX + (field_counter + 3) % 4; blend_mode = 1; } else if (((di_p22_info & PATTERN22_MARK) == (0xaaaaaaaaaaaaaaaaLL & PATTERN22_MARK)) && ((di_p22_info_2 & PATTERN22_MARK) == (0xaaaaaaaaaaaaaaaaLL & PATTERN22_MARK))) { di_buf1_mif.canvas0_addr0 = DEINTERLACE_CANVAS_BASE_INDEX + (field_counter + 1) % 4; blend_mode = 0; } #endif // pull down pattern check if (pattern_len == 0) { int i, j, pattern, pattern_2, mask; for (j = 5 ; j < 22 ; j++) { mask = (1 << j) - 1; pattern = di_p32_info & mask; pattern_2 = di_p32_info_2 & mask; if (pattern != 0 && pattern_2 != 0 && pattern != mask) { for (i = j ; i < j * 3 ; i += j) if (((di_p32_info >> i) & mask) != pattern || ((di_p32_info_2 >> i) & mask) != pattern_2) { break; } if (i == j * 3) { #if defined(CONFIG_ARCH_MESON) if (pattern_22 & (1 << (j - 1))) { blend_mode = 1; } else { blend_mode = 0; } #elif defined(CONFIG_ARCH_MESON2) if (di_info[(field_counter + 3) % 4][4] < di_info[(field_counter + 2) % 4][4]) { di_buf1_mif.canvas0_addr0 = DEINTERLACE_CANVAS_BASE_INDEX + (field_counter + 3) % 4; blend_mode = 1; } else { di_buf1_mif.canvas0_addr0 = DEINTERLACE_CANVAS_BASE_INDEX + (field_counter + 1) % 4; blend_mode = 0; } #endif pattern_len = j; break; } } } } else { int i, pattern, pattern_2, mask; mask = (1 << pattern_len) - 1; pattern = di_p32_info & mask; pattern_2 = di_p32_info_2 & mask; for (i = pattern_len ; i < pattern_len * 3 ; i += pattern_len) if (((di_p32_info >> i) & mask) != pattern || ((di_p32_info_2 >> i) & mask) != pattern_2) { break; } if (i == pattern_len * 3) { #if defined(CONFIG_ARCH_MESON) if (pattern_22 & (1 << (pattern_len - 1))) { blend_mode = 1; } else { blend_mode = 0; } #elif defined(CONFIG_ARCH_MESON2) if (di_info[(field_counter + 3) % 4][4] < di_info[(field_counter + 2) % 4][4]) { di_buf1_mif.canvas0_addr0 = DEINTERLACE_CANVAS_BASE_INDEX + (field_counter + 3) % 4; blend_mode = 1; } else { di_buf1_mif.canvas0_addr0 = DEINTERLACE_CANVAS_BASE_INDEX + (field_counter + 1) % 4; blend_mode = 0; } #endif } else { pattern_len = 0; } } di_nrwr_mif.canvas_num = DEINTERLACE_CANVAS_BASE_INDEX + field_counter % 4; di_mtnwr_mif.canvas_num = DEINTERLACE_CANVAS_BASE_INDEX + 4 + field_counter % 4; di_mtncrd_mif.canvas_num = DEINTERLACE_CANVAS_BASE_INDEX + 4 + (field_counter + 2) % 4; di_mtnprd_mif.canvas_num = DEINTERLACE_CANVAS_BASE_INDEX + 4 + (field_counter + 3) % 4; } void pattern_check_pre(void) { di_pre_mode_check(pre_field_counter % 4); #ifdef DEBUG debug_array[(pre_field_counter & 0x3ff) * 4] = di_info[pre_field_counter % 4][0]; debug_array[(pre_field_counter & 0x3ff) * 4 + 1] = di_info[pre_field_counter % 4][1] & 0xffffff; debug_array[(pre_field_counter & 0x3ff) * 4 + 2] = di_info[pre_field_counter % 4][2]; debug_array[(pre_field_counter & 0x3ff) * 4 + 3] = di_info[pre_field_counter % 4][4]; #endif if (pre_field_counter >= 3) { check_p32_p22(pre_field_counter % 4, (pre_field_counter - 1) % 4, (pre_field_counter - 2) % 4); if (di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode == 3) { if (((di_p22_info & PATTERN22_MARK) == (0x5555555555555555LL & PATTERN22_MARK)) && ((di_p22_info_2 & PATTERN22_MARK) == (0x5555555555555555LL & PATTERN22_MARK))) { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 1; } else if (((di_p22_info & PATTERN22_MARK) == (0xaaaaaaaaaaaaaaaaLL & PATTERN22_MARK)) && ((di_p22_info_2 & PATTERN22_MARK) == (0xaaaaaaaaaaaaaaaaLL & PATTERN22_MARK))) { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 0; } else if (pattern_len == 0) { di_buf_pool[(pre_field_counter - 2) % DI_BUF_NUM].blend_mode = 3; } if (pattern_len == 0) { int i, j, pattern, pattern_2, mask; for (j = 5 ; j < 22 ; j++) { mask = (1 << j) - 1; pattern = di_p32_info & mask; pattern_2 = di_p32_info_2 & mask; if (pattern != 0 && pattern_2 != 0 && pattern != mask) { for (i = j ; i < j * PATTERN32_NUM ; i += j) if (((di_p32_info >> i) & mask) != pattern || ((di_p32_info_2 >> i) & mask) != pattern_2) { break; } if (i == j * PATTERN32_NUM) { if ((pattern_len == 5) && ((pattern & (pattern - 1)) == 0)) { if ((di_p32_info & 0x1) || (di_p32_info & 0x2) || (di_p32_info & 0x8)) { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 0; } else { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 1; } } else { if ((pattern & (pattern - 1)) != 0) { if (di_info[pre_field_counter % 4][4] < di_info[(pre_field_counter - 1) % 4][4]) { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 1; } else { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 0; } } } pattern_len = j; break; } } } } else { int i, pattern, pattern_2, mask; mask = (1 << pattern_len) - 1; pattern = di_p32_info & mask; pattern_2 = di_p32_info_2 & mask; for (i = pattern_len ; i < pattern_len * PATTERN32_NUM ; i += pattern_len) if (((di_p32_info >> i) & mask) != pattern || ((di_p32_info_2 >> i) & mask) != pattern_2) { break; } if (i == pattern_len * PATTERN32_NUM) { if ((pattern_len == 5) && ((pattern & (pattern - 1)) == 0)) { if ((di_p32_info & 0x1) || (di_p32_info & 0x2) || (di_p32_info & 0x8)) { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 0; } else { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 1; } } else { if ((pattern & (pattern - 1)) != 0) { if (di_info[pre_field_counter % 4][4] < di_info[(pre_field_counter - 1) % 4][4]) { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 1; } else { di_buf_pool[(pre_field_counter - 1) % DI_BUF_NUM].blend_mode = 0; } } } } else { pattern_len = 0; di_buf_pool[(pre_field_counter - 2) % DI_BUF_NUM].blend_mode = 3; } } } } } void set_vdin_par(int flag, vframe_t *buf) { vdin_en = flag; memcpy(&dummy_buf, buf, sizeof(vframe_t)); } void di_pre_process(void) { unsigned temp = READ_MPEG_REG(DI_INTR_CTRL); unsigned status = READ_MPEG_REG(DI_PRE_CTRL) & 0x2; #if defined(CONFIG_ARCH_MESON2) int nr_hfilt_en, nr_hfilt_mb_en; if (noise_reduction_level == 2) { nr_hfilt_en = 1; nr_hfilt_mb_en = 1; } else { nr_hfilt_en = 0; nr_hfilt_mb_en = 0; } #endif if (deinterlace_mode != 2) { return; } if ((prev_struct == 0) && (READ_MPEG_REG(DI_PRE_SIZE) != ((32 - 1) | ((64 - 1) << 16)))) { disable_pre_deinterlace(); } if (prev_struct > 0) { #if defined(CONFIG_ARCH_MESON) if ((temp & 0xf) != (status | 0x9)) #elif defined(CONFIG_ARCH_MESON2) if ((temp & 0xf) != (status | 0x1)) #endif return; if (!vdin_en && (prog_field_count == 0) && (buf_recycle_done == 0)) { buf_recycle_done = 1; vf_put(cur_buf, RECEIVER_NAME); } if (di_pre_post_done == 0) { di_pre_post_done = 1; pattern_check_pre(); memcpy((&di_buf_pool[pre_field_counter % DI_BUF_NUM]), cur_buf, sizeof(vframe_t)); di_buf_pool[pre_field_counter % DI_BUF_NUM].blend_mode = blend_mode; di_buf_pool[pre_field_counter % DI_BUF_NUM].canvas0Addr = DEINTERLACE_CANVAS_BASE_INDEX + 4; di_buf_pool[pre_field_counter % DI_BUF_NUM].canvas1Addr = DEINTERLACE_CANVAS_BASE_INDEX + 4; if (prev_struct == 1) { di_buf_pool[pre_field_counter % DI_BUF_NUM].type = VIDTYPE_INTERLACE_TOP | VIDTYPE_VIU_422 | VIDTYPE_VIU_SINGLE_PLANE | VIDTYPE_VIU_FIELD; } else { di_buf_pool[pre_field_counter % DI_BUF_NUM].type = VIDTYPE_INTERLACE_BOTTOM | VIDTYPE_VIU_422 | VIDTYPE_VIU_SINGLE_PLANE | VIDTYPE_VIU_FIELD; } pre_field_counter++; } if ((pre_field_counter >= field_counter + DI_BUF_NUM - 3) && ((pre_field_counter >= field_counter + DI_BUF_NUM - 2) || (field_counter == 0))) { #ifdef DEBUG di_pre_overflow++; #endif return; } if (!vdin_en && (prog_field_count == 0) && (!vf_peek(RECEIVER_NAME))) { #ifdef DEBUG di_pre_underflow++; #endif return; } } if (prog_field_count > 0) { blend_mode = 0; prog_field_count--; prev_struct = 3 - prev_struct; } else { if (vdin_en) { di_pre_recycle_buf = 1; cur_buf = &dummy_buf; } else { cur_buf = vf_peek(RECEIVER_NAME); if (!cur_buf) { return; } if ((cur_buf->duration == 0) #if defined(CONFIG_AM_DEINTERLACE_SD_ONLY) || (cur_buf->width > 720) #endif ) { di_pre_recycle_buf = 0; return; } di_pre_recycle_buf = 1; cur_buf = vf_get(RECEIVER_NAME); } if (((cur_buf->type & VIDTYPE_TYPEMASK) == VIDTYPE_INTERLACE_TOP && prev_struct == 1) || ((cur_buf->type & VIDTYPE_TYPEMASK) == VIDTYPE_INTERLACE_BOTTOM && prev_struct == 2)) { if (!vdin_en) { vf_put(cur_buf, RECEIVER_NAME); } return; } di_inp_top_mif.canvas0_addr0 = di_inp_bot_mif.canvas0_addr0 = cur_buf->canvas0Addr & 0xff; di_inp_top_mif.canvas0_addr1 = di_inp_bot_mif.canvas0_addr1 = (cur_buf->canvas0Addr >> 8) & 0xff; di_inp_top_mif.canvas0_addr2 = di_inp_bot_mif.canvas0_addr2 = (cur_buf->canvas0Addr >> 16) & 0xff; blend_mode = 3; if ((cur_buf->type & VIDTYPE_TYPEMASK) == VIDTYPE_INTERLACE_TOP) { prev_struct = 1; prog_field_count = 0; } else if ((cur_buf->type & VIDTYPE_TYPEMASK) == VIDTYPE_INTERLACE_BOTTOM) { prev_struct = 2; prog_field_count = 0; } else { if (prev_struct == 0) { prev_struct = 1; } else { prev_struct = 3 - prev_struct; } if (cur_buf->duration_pulldown > 0) { prog_field_count = 2; } else { prog_field_count = 1; } blend_mode = 1; cur_buf->duration >>= 1; cur_buf->duration_pulldown = 0; } } buf_recycle_done = 0; di_pre_post_done = 0; WRITE_MPEG_REG(DI_INTR_CTRL, temp); if ((READ_MPEG_REG(DI_PRE_SIZE) != ((cur_buf->width - 1) | ((cur_buf->height / 2 - 1) << 16)))) { WRITE_MPEG_REG(DI_INTR_CTRL, 0x000f000f); initial_di_pre(cur_buf->width, cur_buf->height / 2, PRE_HOLD_LINE); di_checked_field = (field_counter + di_checked_field + 1) % DI_BUF_NUM; pre_field_counter = field_counter = 0; di_p32_info = di_p22_info = di_p32_info_2 = di_p22_info_2 = 0; pattern_len = 0; di_mem_mif.luma_x_start0 = 0; di_mem_mif.luma_x_end0 = cur_buf->width - 1; di_mem_mif.luma_y_start0 = 0; di_mem_mif.luma_y_end0 = cur_buf->height / 2 - 1; di_chan2_mif.luma_x_start0 = 0; di_chan2_mif.luma_x_end0 = cur_buf->width - 1; di_chan2_mif.luma_y_start0 = 0; di_chan2_mif.luma_y_end0 = cur_buf->height / 2 - 1; di_nrwr_mif.start_x = 0; di_nrwr_mif.end_x = cur_buf->width - 1; di_nrwr_mif.start_y = 0; di_nrwr_mif.end_y = cur_buf->height / 2 - 1; di_mtnwr_mif.start_x = 0; di_mtnwr_mif.end_x = cur_buf->width - 1; di_mtnwr_mif.start_y = 0; di_mtnwr_mif.end_y = cur_buf->height / 2 - 1; if (cur_buf->type & VIDTYPE_VIU_422) { di_inp_top_mif.video_mode = 0; di_inp_top_mif.set_separate_en = 0; di_inp_top_mif.src_field_mode = 0; di_inp_top_mif.output_field_num = 0; di_inp_top_mif.burst_size_y = 3; di_inp_top_mif.burst_size_cb = 0; di_inp_top_mif.burst_size_cr = 0; memcpy(&di_inp_bot_mif, &di_inp_top_mif, sizeof(DI_MIF_t)); di_inp_top_mif.luma_x_start0 = 0; di_inp_top_mif.luma_x_end0 = cur_buf->width - 1; di_inp_top_mif.luma_y_start0 = 0; di_inp_top_mif.luma_y_end0 = cur_buf->height / 2 - 1; di_inp_top_mif.chroma_x_start0 = 0; di_inp_top_mif.chroma_x_end0 = 0; di_inp_top_mif.chroma_y_start0 = 0; di_inp_top_mif.chroma_y_end0 = 0; di_inp_bot_mif.luma_x_start0 = 0; di_inp_bot_mif.luma_x_end0 = cur_buf->width - 1; di_inp_bot_mif.luma_y_start0 = 0; di_inp_bot_mif.luma_y_end0 = cur_buf->height / 2 - 1; di_inp_bot_mif.chroma_x_start0 = 0; di_inp_bot_mif.chroma_x_end0 = 0; di_inp_bot_mif.chroma_y_start0 = 0; di_inp_bot_mif.chroma_y_end0 = 0; } else { di_inp_top_mif.video_mode = 0; di_inp_top_mif.set_separate_en = 1; di_inp_top_mif.src_field_mode = 1; di_inp_top_mif.burst_size_y = 3; di_inp_top_mif.burst_size_cb = 1; di_inp_top_mif.burst_size_cr = 1; memcpy(&di_inp_bot_mif, &di_inp_top_mif, sizeof(DI_MIF_t)); di_inp_top_mif.output_field_num = 0; // top di_inp_bot_mif.output_field_num = 1; // bottom di_inp_top_mif.luma_x_start0 = 0; di_inp_top_mif.luma_x_end0 = cur_buf->width - 1; di_inp_top_mif.luma_y_start0 = 0; di_inp_top_mif.luma_y_end0 = cur_buf->height - 2; di_inp_top_mif.chroma_x_start0 = 0; di_inp_top_mif.chroma_x_end0 = cur_buf->width / 2 - 1; di_inp_top_mif.chroma_y_start0 = 0; di_inp_top_mif.chroma_y_end0 = cur_buf->height / 2 - 2; di_inp_bot_mif.luma_x_start0 = 0; di_inp_bot_mif.luma_x_end0 = cur_buf->width - 1; di_inp_bot_mif.luma_y_start0 = 1; di_inp_bot_mif.luma_y_end0 = cur_buf->height - 1; di_inp_bot_mif.chroma_x_start0 = 0; di_inp_bot_mif.chroma_x_end0 = cur_buf->width / 2 - 1; di_inp_bot_mif.chroma_y_start0 = 1; di_inp_bot_mif.chroma_y_end0 = cur_buf->height / 2 - 1; } di_nrwr_mif.canvas_num = DEINTERLACE_CANVAS_BASE_INDEX; di_mtnwr_mif.canvas_num = DEINTERLACE_CANVAS_BASE_INDEX + 1; di_chan2_mif.canvas0_addr0 = DEINTERLACE_CANVAS_BASE_INDEX + 2; di_mem_mif.canvas0_addr0 = DEINTERLACE_CANVAS_BASE_INDEX + 3; di_buf0_mif.canvas0_addr0 = DEINTERLACE_CANVAS_BASE_INDEX + 4; di_buf1_mif.canvas0_addr0 = DEINTERLACE_CANVAS_BASE_INDEX + 5; di_mtncrd_mif.canvas_num = DEINTERLACE_CANVAS_BASE_INDEX + 6; di_mtnprd_mif.canvas_num = DEINTERLACE_CANVAS_BASE_INDEX + 7; enable_di_mode_check( 0, cur_buf->width - 1, 0, cur_buf->height / 2 - 1, // window 0 ( start_x, end_x, start_y, end_y) 0, cur_buf->width - 1, 0, cur_buf->height / 2 - 1, // window 1 ( start_x, end_x, start_y, end_y) 0, cur_buf->width - 1, 0, cur_buf->height / 2 - 1, // window 2 ( start_x, end_x, start_y, end_y) 0, cur_buf->width - 1, 0, cur_buf->height / 2 - 1, // window 3 ( start_x, end_x, start_y, end_y) 0, cur_buf->width - 1, 0, cur_buf->height / 2 - 1, // window 4 ( start_x, end_x, start_y, end_y) 16, 16, 16, 16, 16, // windows 32 level 256, 256, 256, 256, 256, // windows 22 level 16, 256); // field 32 level; field 22 level } temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((pre_field_counter + di_checked_field) % DI_BUF_NUM); canvas_config(di_nrwr_mif.canvas_num, temp, MAX_CANVAS_WIDTH * 2, MAX_CANVAS_HEIGHT / 2, 0, 0); temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((pre_field_counter + di_checked_field) % DI_BUF_NUM) + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT); canvas_config(di_mtnwr_mif.canvas_num, temp, MAX_CANVAS_WIDTH / 2, MAX_CANVAS_HEIGHT / 2, 0, 0); temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((pre_field_counter + di_checked_field + DI_BUF_NUM - 1) % DI_BUF_NUM); canvas_config(di_chan2_mif.canvas0_addr0, temp, MAX_CANVAS_WIDTH * 2, MAX_CANVAS_HEIGHT / 2, 0, 0); temp = di_mem_start + (MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT * 5 / 4) * ((pre_field_counter + di_checked_field + DI_BUF_NUM - 2) % DI_BUF_NUM); canvas_config(di_mem_mif.canvas0_addr0, temp, MAX_CANVAS_WIDTH * 2, MAX_CANVAS_HEIGHT / 2, 0, 0); WRITE_MPEG_REG(DI_PRE_CTRL, 0x3 << 30); enable_di_pre( (prev_struct == 1) ? &di_inp_top_mif : &di_inp_bot_mif, (pre_field_counter < 2) ? ((prev_struct == 1) ? &di_inp_top_mif : &di_inp_bot_mif) : &di_mem_mif, &di_chan2_mif, &di_nrwr_mif, &di_mtnwr_mif, 1, // nr enable (pre_field_counter >= 2), // mtn enable (pre_field_counter >= 2), // 3:2 pulldown check enable (pre_field_counter >= 1), // 2:2 pulldown check enable #if defined(CONFIG_ARCH_MESON) 1, // hist check_en #elif defined(CONFIG_ARCH_MESON2) 0, // hist check_en nr_hfilt_en, // nr_hfilt_en nr_hfilt_mb_en, // nr_hfilt_mb_en 1, // mtn_modify_en, #elif defined(CONFIG_ARCH_MESON3) 1, // hist check_en #endif (prev_struct == 1) ? 1 : 0, // field num for chan2. 1 bottom, 0 top. 0, // pre viu link. PRE_HOLD_LINE ); } void di_pre_isr(struct work_struct *work) { if (!vf_get_provider(RECEIVER_NAME)) { return; } di_pre_process(); } void run_deinterlace(unsigned zoom_start_x_lines, unsigned zoom_end_x_lines, unsigned zoom_start_y_lines, unsigned zoom_end_y_lines, unsigned type, int mode, int hold_line) { int di_width, di_height, di_start_x, di_end_x, di_start_y, di_end_y, size_change, position_change; #if defined(CONFIG_ARCH_MESON2) int nr_hfilt_en, nr_hfilt_mb_en, post_mb_en; if (noise_reduction_level == 2) { nr_hfilt_en = 1; nr_hfilt_mb_en = 1; post_mb_en = 1; } else { nr_hfilt_en = 0; nr_hfilt_mb_en = 0; post_mb_en = 0; } #endif di_start_x = zoom_start_x_lines; di_end_x = zoom_end_x_lines; di_width = di_end_x - di_start_x + 1; di_start_y = (zoom_start_y_lines + 1) & 0xfffffffe; di_end_y = (zoom_end_y_lines - 1) | 0x1; di_height = di_end_y - di_start_y + 1; if (deinterlace_mode == 1) { int i; unsigned long addr = di_mem_start; size_change = (READ_MPEG_REG(DI_POST_SIZE) != ((di_width - 1) | ((di_height - 1) << 16))); position_change = ((di_inp_top_mif.luma_x_start0 != di_start_x) || (di_inp_top_mif.luma_y_start0 != di_start_y)); if (size_change || position_change) { if (size_change) { initial_di_prepost(di_width, di_height / 2, di_width, di_height, hold_line); pattern_22 = 0; di_p32_info = di_p22_info = di_p32_info_2 = di_p22_info_2 = 0; pattern_len = 0; } di_mem_mif.luma_x_start0 = di_start_x; di_mem_mif.luma_x_end0 = di_end_x; di_mem_mif.luma_y_start0 = di_start_y / 2; di_mem_mif.luma_y_end0 = (di_end_y + 1) / 2 - 1; di_buf0_mif.luma_x_start0 = di_start_x; di_buf0_mif.luma_x_end0 = di_end_x; di_buf0_mif.luma_y_start0 = di_start_y / 2; di_buf0_mif.luma_y_end0 = (di_end_y + 1) / 2 - 1; di_chan2_mif.luma_x_start0 = di_start_x; di_chan2_mif.luma_x_end0 = di_end_x; di_chan2_mif.luma_y_start0 = di_start_y / 2; di_chan2_mif.luma_y_end0 = (di_end_y + 1) / 2 - 1; di_nrwr_mif.start_x = di_start_x; di_nrwr_mif.end_x = di_end_x; di_nrwr_mif.start_y = di_start_y / 2; di_nrwr_mif.end_y = (di_end_y + 1) / 2 - 1; di_mtnwr_mif.start_x = di_start_x; di_mtnwr_mif.end_x = di_end_x; di_mtnwr_mif.start_y = di_start_y / 2; di_mtnwr_mif.end_y = (di_end_y + 1) / 2 - 1; di_mtncrd_mif.start_x = di_start_x; di_mtncrd_mif.end_x = di_end_x; di_mtncrd_mif.start_y = di_start_y / 2; di_mtncrd_mif.end_y = (di_end_y + 1) / 2 - 1; enable_di_mode_check( di_start_x, di_end_x, di_start_y, (di_end_y + 1) / 2 - 1, // window 0 ( start_x, end_x, start_y, end_y) di_start_x, di_end_x, di_start_y, (di_end_y + 1) / 2 - 1, // window 1 ( start_x, end_x, start_y, end_y) di_start_x, di_end_x, di_start_y, (di_end_y + 1) / 2 - 1, // window 2 ( start_x, end_x, start_y, end_y) di_start_x, di_end_x, di_start_y, (di_end_y + 1) / 2 - 1, // window 3 ( start_x, end_x, start_y, end_y) di_start_x, di_end_x, di_start_y, (di_end_y + 1) / 2 - 1, // window 4 ( start_x, end_x, start_y, end_y) 16, 16, 16, 16, 16, // windows 32 level 256, 256, 256, 256, 256, // windows 22 level 16, 256); // field 32 level; field 22 level pre_field_counter = field_counter = di_checked_field = 0; if (type & VIDTYPE_VIU_422) { di_inp_top_mif.video_mode = 0; di_inp_top_mif.set_separate_en = 0; di_inp_top_mif.src_field_mode = 0; di_inp_top_mif.output_field_num = 0; di_inp_top_mif.burst_size_y = 3; di_inp_top_mif.burst_size_cb = 0; di_inp_top_mif.burst_size_cr = 0; memcpy(&di_inp_bot_mif, &di_inp_top_mif, sizeof(DI_MIF_t)); di_inp_top_mif.luma_x_start0 = di_start_x; di_inp_top_mif.luma_x_end0 = di_end_x; di_inp_top_mif.luma_y_start0 = di_start_y; di_inp_top_mif.luma_y_end0 = (di_end_y + 1) / 2 - 1; di_inp_top_mif.chroma_x_start0 = 0; di_inp_top_mif.chroma_x_end0 = 0; di_inp_top_mif.chroma_y_start0 = 0; di_inp_top_mif.chroma_y_end0 = 0; di_inp_bot_mif.luma_x_start0 = di_start_x; di_inp_bot_mif.luma_x_end0 = di_end_x; di_inp_bot_mif.luma_y_start0 = di_start_y; di_inp_bot_mif.luma_y_end0 = (di_end_y + 1) / 2 - 1; di_inp_bot_mif.chroma_x_start0 = 0; di_inp_bot_mif.chroma_x_end0 = 0; di_inp_bot_mif.chroma_y_start0 = 0; di_inp_bot_mif.chroma_y_end0 = 0; } else { di_inp_top_mif.video_mode = 0; di_inp_top_mif.set_separate_en = 1; di_inp_top_mif.src_field_mode = 1; di_inp_top_mif.burst_size_y = 3; di_inp_top_mif.burst_size_cb = 1; di_inp_top_mif.burst_size_cr = 1; memcpy(&di_inp_bot_mif, &di_inp_top_mif, sizeof(DI_MIF_t)); di_inp_top_mif.output_field_num = 0; // top di_inp_bot_mif.output_field_num = 1; // bottom di_inp_top_mif.luma_x_start0 = di_start_x; di_inp_top_mif.luma_x_end0 = di_end_x; di_inp_top_mif.luma_y_start0 = di_start_y; di_inp_top_mif.luma_y_end0 = di_end_y - 1; di_inp_top_mif.chroma_x_start0 = di_start_x / 2; di_inp_top_mif.chroma_x_end0 = (di_end_x + 1) / 2 - 1; di_inp_top_mif.chroma_y_start0 = di_start_y / 2; di_inp_top_mif.chroma_y_end0 = (di_end_y + 1) / 2 - 2; di_inp_bot_mif.luma_x_start0 = di_start_x; di_inp_bot_mif.luma_x_end0 = di_end_x; di_inp_bot_mif.luma_y_start0 = di_start_y + 1; di_inp_bot_mif.luma_y_end0 = di_end_y; di_inp_bot_mif.chroma_x_start0 = di_start_x / 2; di_inp_bot_mif.chroma_x_end0 = (di_end_x + 1) / 2 - 1; di_inp_bot_mif.chroma_y_start0 = di_start_y / 2 + 1; di_inp_bot_mif.chroma_y_end0 = (di_end_y + 1) / 2 - 1; } for (i = 0 ; i < 4 ; i++) { canvas_config(DEINTERLACE_CANVAS_BASE_INDEX + i, addr, MAX_CANVAS_WIDTH * 2, MAX_CANVAS_HEIGHT / 2, 0, 0); addr += MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT; } for (i = 4 ; i < 8 ; i++) { canvas_config(DEINTERLACE_CANVAS_BASE_INDEX + i, addr, MAX_CANVAS_WIDTH / 2, MAX_CANVAS_HEIGHT / 2, 0, 0); addr += MAX_CANVAS_WIDTH * MAX_CANVAS_HEIGHT / 4; } di_inp_top_mif.canvas0_addr0 = di_inp_bot_mif.canvas0_addr0 = DISPLAY_CANVAS_BASE_INDEX; di_inp_top_mif.canvas0_addr1 = di_inp_bot_mif.canvas0_addr1 = DISPLAY_CANVAS_BASE_INDEX + 1; di_inp_top_mif.canvas0_addr2 = di_inp_bot_mif.canvas0_addr2 = DISPLAY_CANVAS_BASE_INDEX + 2; } pattern_check_prepost(); #if defined(CONFIG_ARCH_MESON) if ((type & VIDTYPE_TYPEMASK) == VIDTYPE_INTERLACE_TOP) { enable_di_prepost_full( &di_inp_top_mif, &di_mem_mif, (field_counter < 1 ? &di_inp_top_mif : &di_buf0_mif), NULL, &di_chan2_mif, &di_nrwr_mif, NULL, &di_mtnwr_mif, &di_mtncrd_mif, NULL, (pre_field_counter != field_counter || field_counter == 0), // noise reduction enable (field_counter >= 2), // motion check enable (pre_field_counter != field_counter && field_counter >= 2), // 3:2 pulldown check enable (pre_field_counter != field_counter && field_counter >= 1), // 2:2 pulldown check enable (pre_field_counter != field_counter || field_counter == 0), // video luma histogram check enable 1, // edge interpolation module enable. (field_counter >= 2), // blend enable. (field_counter >= 2), // blend with mtn. (field_counter < 2 ? 2 : blend_mode), // blend mode 1, // deinterlace output to VPP. 0, // deinterlace output to DDR SDRAM at same time. (field_counter >= 1), // 1 = current display field is bottom field, we need generated top field. (field_counter >= 1), // pre field num: 1 = current chan2 input field is bottom field. (field_counter >= 1), // prepost link. for the first field it look no need to be propost_link. hold_line ); } else { enable_di_prepost_full( &di_inp_bot_mif, &di_mem_mif, (field_counter < 1 ? &di_inp_bot_mif : &di_buf0_mif), NULL, &di_chan2_mif, &di_nrwr_mif, NULL, &di_mtnwr_mif, &di_mtncrd_mif, NULL, (pre_field_counter != field_counter || field_counter == 0), // noise reduction enable (field_counter >= 2), // motion check enable (pre_field_counter != field_counter && field_counter >= 2), // 3:2 pulldown check enable (pre_field_counter != field_counter && field_counter >= 1), // 2:2 pulldown check enable (pre_field_counter != field_counter || field_counter == 0), // video luma histogram check enable 1, // edge interpolation module enable. (field_counter >= 2), // blend enable. (field_counter >= 2), // blend with mtn. (field_counter < 2 ? 2 : blend_mode), // blend mode: 3 motion adapative blend. 1, // deinterlace output to VPP. 0, // deinterlace output to DDR SDRAM at same time. (field_counter < 1), // 1 = current display field is bottom field, we need generated top field. (field_counter < 1), // pre field num. 1 = current chan2 input field is bottom field. (field_counter >= 1), // prepost link. for the first field it look no need to be propost_link. hold_line ); } #elif defined(CONFIG_ARCH_MESON2) if ((type & VIDTYPE_TYPEMASK) == VIDTYPE_INTERLACE_TOP) { enable_di_prepost_full( &di_inp_top_mif, (field_counter < 2 ? &di_inp_top_mif : &di_mem_mif), NULL, &di_buf1_mif, &di_chan2_mif, &di_nrwr_mif, NULL, &di_mtnwr_mif, &di_mtncrd_mif, &di_mtnprd_mif, (pre_field_counter != field_counter || field_counter == 0), // noise reduction enable (field_counter >= 2), // motion check enable (pre_field_counter != field_counter && field_counter >= 2), // 3:2 pulldown check enable (pre_field_counter != field_counter && field_counter >= 1), // 2:2 pulldown check enable (pre_field_counter != field_counter || field_counter == 0), // video luma histogram check enable 1, // edge interpolation module enable. (field_counter >= 3), // blend enable. (field_counter >= 3), // blend with mtn. (field_counter < 3 ? 2 : blend_mode), // blend mode 1, // deinterlace output to VPP. 0, // deinterlace output to DDR SDRAM at same time. nr_hfilt_en, // nr_hfilt_en nr_hfilt_mb_en, // nr_hfilt_mb_en 1, // mtn_modify_en, 1, // blend_mtn_filt_en 1, // blend_data_filt_en post_mb_en, // post_mb_en 0, // 1 = current display field is bottom field, we need generated top field. 1, // pre field num: 1 = current chan2 input field is bottom field. (field_counter >= 2), // prepost link. for the first field it look no need to be propost_link. hold_line ); } else { enable_di_prepost_full( &di_inp_bot_mif, (field_counter < 2 ? &di_inp_top_mif : &di_mem_mif), NULL, &di_buf1_mif, &di_chan2_mif, &di_nrwr_mif, NULL, &di_mtnwr_mif, &di_mtncrd_mif, &di_mtnprd_mif, (pre_field_counter != field_counter || field_counter == 0), // noise reduction enable (field_counter >= 2), // motion check enable (pre_field_counter != field_counter && field_counter >= 2), // 3:2 pulldown check enable (pre_field_counter != field_counter && field_counter >= 1), // 2:2 pulldown check enable (pre_field_counter != field_counter || field_counter == 0), // video luma histogram check enable 1, // edge interpolation module enable. (field_counter >= 3), // blend enable. (field_counter >= 3), // blend with mtn. (field_counter < 3 ? 2 : blend_mode), // blend mode: 3 motion adapative blend. 1, // deinterlace output to VPP. 0, // deinterlace output to DDR SDRAM at same time. nr_hfilt_en, // nr_hfilt_en nr_hfilt_mb_en, // nr_hfilt_mb_en 1, // mtn_modify_en, 1, // blend_mtn_filt_en 1, // blend_data_filt_en post_mb_en, // post_mb_en 1, // 1 = current display field is bottom field, we need generated top field. 0, // pre field num. 1 = current chan2 input field is bottom field. (field_counter >= 2), // prepost link. for the first field it look no need to be propost_link. hold_line ); } #endif pre_field_counter = field_counter; } else { int post_blend_en, post_blend_mode; if (READ_MPEG_REG(DI_POST_SIZE) != ((di_width - 1) | ((di_height - 1) << 16)) || (di_buf0_mif.luma_x_start0 != di_start_x) || (di_buf0_mif.luma_y_start0 != di_start_y / 2)) { initial_di_post(di_width, di_height, hold_line); di_buf0_mif.luma_x_start0 = di_start_x; di_buf0_mif.luma_x_end0 = di_end_x; di_buf0_mif.luma_y_start0 = di_start_y / 2; di_buf0_mif.luma_y_end0 = (di_end_y + 1) / 2 - 1; di_buf1_mif.luma_x_start0 = di_start_x; di_buf1_mif.luma_x_end0 = di_end_x; di_buf1_mif.luma_y_start0 = di_start_y / 2; di_buf1_mif.luma_y_end0 = (di_end_y + 1) / 2 - 1; di_mtncrd_mif.start_x = di_start_x; di_mtncrd_mif.end_x = di_end_x; di_mtncrd_mif.start_y = di_start_y / 2; di_mtncrd_mif.end_y = (di_end_y + 1) / 2 - 1; di_mtnprd_mif.start_x = di_start_x; di_mtnprd_mif.end_x = di_end_x; di_mtnprd_mif.start_y = di_start_y / 2; di_mtnprd_mif.end_y = (di_end_y + 1) / 2 - 1; } post_blend_en = 1; post_blend_mode = mode; if ((post_blend_mode == 3) && (field_counter <= 2)) { post_blend_en = 0; post_blend_mode = 2; } enable_di_post( &di_buf0_mif, &di_buf1_mif, NULL, &di_mtncrd_mif, &di_mtnprd_mif, 1, // ei enable post_blend_en, // blend enable post_blend_en, // blend mtn enable post_blend_mode, // blend mode. 1, // di_vpp_en. 0, // di_ddr_en. #if defined(CONFIG_ARCH_MESON) #elif defined(CONFIG_ARCH_MESON2) 1, // blend_mtn_filt_en 1, // blend_data_filt_en post_mb_en, // post_mb_en #endif (type & VIDTYPE_TYPEMASK) == VIDTYPE_INTERLACE_TOP ? 0 : 1, // 1 bottom generate top hold_line ); } } void di_pre_timer_func(unsigned long arg) { struct timer_list *timer = (struct timer_list *)arg; schedule_work(&di_pre_work); timer->expires = jiffies + DI_PRE_INTERVAL; add_timer(timer); } void deinterlace_init(void) { di_mem_mif.chroma_x_start0 = 0; di_mem_mif.chroma_x_end0 = 0; di_mem_mif.chroma_y_start0 = 0; di_mem_mif.chroma_y_end0 = 0; di_mem_mif.video_mode = 0; di_mem_mif.set_separate_en = 0; di_mem_mif.src_field_mode = 0; di_mem_mif.output_field_num = 0; di_mem_mif.burst_size_y = 3; di_mem_mif.burst_size_cb = 0; di_mem_mif.burst_size_cr = 0; di_mem_mif.canvas0_addr1 = 0; di_mem_mif.canvas0_addr2 = 0; memcpy(&di_buf0_mif, &di_mem_mif, sizeof(DI_MIF_t)); memcpy(&di_buf1_mif, &di_mem_mif, sizeof(DI_MIF_t)); memcpy(&di_chan2_mif, &di_buf1_mif, sizeof(DI_MIF_t)); WRITE_MPEG_REG(DI_PRE_HOLD, (1 << 31) | (31 << 16) | 31); #if defined(CONFIG_ARCH_MESON) WRITE_MPEG_REG(DI_NRMTN_CTRL0, 0xb00a0603); #endif INIT_WORK(&di_pre_work, di_pre_isr); init_timer(&di_pre_timer); di_pre_timer.data = (ulong) & di_pre_timer; di_pre_timer.function = di_pre_timer_func; di_pre_timer.expires = jiffies + DI_PRE_INTERVAL; add_timer(&di_pre_timer); } static int deinterlace_probe(struct platform_device *pdev) { struct resource *mem; printk("Amlogic deinterlace init\n"); if (!(mem = platform_get_resource(pdev, IORESOURCE_MEM, 0))) { printk("\ndeinterlace memory resource undefined.\n"); return -EFAULT; } // declare deinterlace memory di_mem_start = mem->start; printk("Deinterlace memory: start = 0x%x, end = 0x%x\n", di_mem_start, mem->end); deinterlace_init(); return 0; } static int deinterlace_remove(struct platform_device *pdev) { printk("Amlogic deinterlace release\n"); del_timer_sync(&di_pre_timer); return 0; } static struct platform_driver deinterlace_driver = { .probe = deinterlace_probe, .remove = deinterlace_remove, .driver = { .name = "deinterlace", } }; static int __init deinterlace_module_init(void) { if (platform_driver_register(&deinterlace_driver)) { printk("failed to register deinterlace module\n"); return -ENODEV; } return 0; } static void __exit deinterlace_module_exit(void) { platform_driver_unregister(&deinterlace_driver); return; } MODULE_PARM_DESC(deinterlace_mode, "\n deinterlace mode \n"); module_param(deinterlace_mode, int, 0664); #if defined(CONFIG_ARCH_MESON2) MODULE_PARM_DESC(noise_reduction_level, "\n noise reduction level \n"); module_param(noise_reduction_level, int, 0664); #endif module_init(deinterlace_module_init); module_exit(deinterlace_module_exit); MODULE_DESCRIPTION("AMLOGIC deinterlace driver"); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Qi Wang <qi.wang@amlogic.com>");
j1nx/Openlinux.Amlogic.M3
drivers/amlogic/amports/deinterlace.c
C
gpl-2.0
136,980
// Copyright 2017 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #pragma once #include <functional> #include <utility> #include <variant> namespace Common { // A Lazy object holds a value. If a Lazy object is constructed using // a function as an argument, that function will be called to compute // the value the first time any code tries to access the value. template <typename T> class Lazy { public: Lazy() : m_value(T()) {} Lazy(const std::variant<T, std::function<T()>>& value) : m_value(value) {} Lazy(std::variant<T, std::function<T()>>&& value) : m_value(std::move(value)) {} const Lazy<T>& operator=(const std::variant<T, std::function<T()>>& value) { m_value = value; return *this; } const Lazy<T>& operator=(std::variant<T, std::function<T()>>&& value) { m_value = std::move(value); return *this; } const T& operator*() const { return *ComputeValue(); } const T* operator->() const { return ComputeValue(); } T& operator*() { return *ComputeValue(); } T* operator->() { return ComputeValue(); } private: T* ComputeValue() const { if (!std::holds_alternative<T>(m_value)) m_value = std::get<std::function<T()>>(m_value)(); return &std::get<T>(m_value); } mutable std::variant<T, std::function<T()>> m_value; }; }
degasus/dolphin
Source/Core/Common/Lazy.h
C
gpl-2.0
1,340
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */ #ifndef __CINNAMON_GENERIC_CONTAINER_H__ #define __CINNAMON_GENERIC_CONTAINER_H__ #include "st.h" #define CINNAMON_TYPE_GENERIC_CONTAINER (cinnamon_generic_container_get_type ()) #define CINNAMON_GENERIC_CONTAINER(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), CINNAMON_TYPE_GENERIC_CONTAINER, CinnamonGenericContainer)) #define CINNAMON_GENERIC_CONTAINER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), CINNAMON_TYPE_GENERIC_CONTAINER, CinnamonGenericContainerClass)) #define CINNAMON_IS_GENERIC_CONTAINER(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), CINNAMON_TYPE_GENERIC_CONTAINER)) #define CINNAMON_IS_GENERIC_CONTAINER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), CINNAMON_TYPE_GENERIC_CONTAINER)) #define CINNAMON_GENERIC_CONTAINER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), CINNAMON_TYPE_GENERIC_CONTAINER, CinnamonGenericContainerClass)) typedef struct { float min_size; float natural_size; /* <private> */ guint _refcount; } CinnamonGenericContainerAllocation; #define CINNAMON_TYPE_GENERIC_CONTAINER_ALLOCATION (cinnamon_generic_container_allocation_get_type ()) GType cinnamon_generic_container_allocation_get_type (void); typedef struct _CinnamonGenericContainer CinnamonGenericContainer; typedef struct _CinnamonGenericContainerClass CinnamonGenericContainerClass; typedef struct _CinnamonGenericContainerPrivate CinnamonGenericContainerPrivate; struct _CinnamonGenericContainer { StContainer parent; CinnamonGenericContainerPrivate *priv; }; struct _CinnamonGenericContainerClass { StContainerClass parent_class; }; GType cinnamon_generic_container_get_type (void) G_GNUC_CONST; guint cinnamon_generic_container_get_n_skip_paint (CinnamonGenericContainer *self); gboolean cinnamon_generic_container_get_skip_paint (CinnamonGenericContainer *self, ClutterActor *child); void cinnamon_generic_container_set_skip_paint (CinnamonGenericContainer *self, ClutterActor *child, gboolean skip); #endif /* __CINNAMON_GENERIC_CONTAINER_H__ */
Kulmerov/Cinnamon
src/cinnamon-generic-container.h
C
gpl-2.0
2,327
/* Top-level LTO routines. Copyright (C) 2009-2015 Free Software Foundation, Inc. Contributed by CodeSourcery, Inc. This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "opts.h" #include "toplev.h" #include "hash-set.h" #include "machmode.h" #include "vec.h" #include "double-int.h" #include "input.h" #include "alias.h" #include "symtab.h" #include "options.h" #include "wide-int.h" #include "inchash.h" #include "real.h" #include "fixed-value.h" #include "tree.h" #include "fold-const.h" #include "stor-layout.h" #include "diagnostic-core.h" #include "tm.h" #include "predict.h" #include "basic-block.h" #include "hash-map.h" #include "is-a.h" #include "plugin-api.h" #include "hard-reg-set.h" #include "input.h" #include "function.h" #include "ipa-ref.h" #include "cgraph.h" #include "tree-ssa-operands.h" #include "tree-pass.h" #include "langhooks.h" #include "bitmap.h" #include "inchash.h" #include "alloc-pool.h" #include "symbol-summary.h" #include "ipa-prop.h" #include "common.h" #include "debug.h" #include "tree-ssa-alias.h" #include "internal-fn.h" #include "gimple-expr.h" #include "gimple.h" #include "lto.h" #include "lto-tree.h" #include "lto-streamer.h" #include "lto-section-names.h" #include "tree-streamer.h" #include "splay-tree.h" #include "lto-partition.h" #include "data-streamer.h" #include "context.h" #include "pass_manager.h" #include "ipa-inline.h" #include "params.h" #include "ipa-utils.h" #include "gomp-constants.h" /* Number of parallel tasks to run, -1 if we want to use GNU Make jobserver. */ static int lto_parallelism; static GTY(()) tree first_personality_decl; static GTY(()) const unsigned char *lto_mode_identity_table; /* Returns a hash code for P. */ static hashval_t hash_name (const void *p) { const struct lto_section_slot *ds = (const struct lto_section_slot *) p; return (hashval_t) htab_hash_string (ds->name); } /* Returns nonzero if P1 and P2 are equal. */ static int eq_name (const void *p1, const void *p2) { const struct lto_section_slot *s1 = (const struct lto_section_slot *) p1; const struct lto_section_slot *s2 = (const struct lto_section_slot *) p2; return strcmp (s1->name, s2->name) == 0; } /* Free lto_section_slot */ static void free_with_string (void *arg) { struct lto_section_slot *s = (struct lto_section_slot *)arg; free (CONST_CAST (char *, s->name)); free (arg); } /* Create section hash table */ htab_t lto_obj_create_section_hash_table (void) { return htab_create (37, hash_name, eq_name, free_with_string); } /* Delete an allocated integer KEY in the splay tree. */ static void lto_splay_tree_delete_id (splay_tree_key key) { free ((void *) key); } /* Compare splay tree node ids A and B. */ static int lto_splay_tree_compare_ids (splay_tree_key a, splay_tree_key b) { unsigned HOST_WIDE_INT ai; unsigned HOST_WIDE_INT bi; ai = *(unsigned HOST_WIDE_INT *) a; bi = *(unsigned HOST_WIDE_INT *) b; if (ai < bi) return -1; else if (ai > bi) return 1; return 0; } /* Look up splay tree node by ID in splay tree T. */ static splay_tree_node lto_splay_tree_lookup (splay_tree t, unsigned HOST_WIDE_INT id) { return splay_tree_lookup (t, (splay_tree_key) &id); } /* Check if KEY has ID. */ static bool lto_splay_tree_id_equal_p (splay_tree_key key, unsigned HOST_WIDE_INT id) { return *(unsigned HOST_WIDE_INT *) key == id; } /* Insert a splay tree node into tree T with ID as key and FILE_DATA as value. The ID is allocated separately because we need HOST_WIDE_INTs which may be wider than a splay_tree_key. */ static void lto_splay_tree_insert (splay_tree t, unsigned HOST_WIDE_INT id, struct lto_file_decl_data *file_data) { unsigned HOST_WIDE_INT *idp = XCNEW (unsigned HOST_WIDE_INT); *idp = id; splay_tree_insert (t, (splay_tree_key) idp, (splay_tree_value) file_data); } /* Create a splay tree. */ static splay_tree lto_splay_tree_new (void) { return splay_tree_new (lto_splay_tree_compare_ids, lto_splay_tree_delete_id, NULL); } /* Return true when NODE has a clone that is analyzed (i.e. we need to load its body even if the node itself is not needed). */ static bool has_analyzed_clone_p (struct cgraph_node *node) { struct cgraph_node *orig = node; node = node->clones; if (node) while (node != orig) { if (node->analyzed) return true; if (node->clones) node = node->clones; else if (node->next_sibling_clone) node = node->next_sibling_clone; else { while (node != orig && !node->next_sibling_clone) node = node->clone_of; if (node != orig) node = node->next_sibling_clone; } } return false; } /* Read the function body for the function associated with NODE. */ static void lto_materialize_function (struct cgraph_node *node) { tree decl; decl = node->decl; /* Read in functions with body (analyzed nodes) and also functions that are needed to produce virtual clones. */ if ((node->has_gimple_body_p () && node->analyzed) || node->used_as_abstract_origin || has_analyzed_clone_p (node)) { /* Clones don't need to be read. */ if (node->clone_of) return; if (DECL_FUNCTION_PERSONALITY (decl) && !first_personality_decl) first_personality_decl = DECL_FUNCTION_PERSONALITY (decl); } /* Let the middle end know about the function. */ rest_of_decl_compilation (decl, 1, 0); } /* Decode the content of memory pointed to by DATA in the in decl state object STATE. DATA_IN points to a data_in structure for decoding. Return the address after the decoded object in the input. */ static const uint32_t * lto_read_in_decl_state (struct data_in *data_in, const uint32_t *data, struct lto_in_decl_state *state) { uint32_t ix; tree decl; uint32_t i, j; ix = *data++; decl = streamer_tree_cache_get_tree (data_in->reader_cache, ix); if (!VAR_OR_FUNCTION_DECL_P (decl)) { gcc_assert (decl == void_type_node); decl = NULL_TREE; } state->fn_decl = decl; for (i = 0; i < LTO_N_DECL_STREAMS; i++) { uint32_t size = *data++; vec<tree, va_gc> *decls = NULL; vec_alloc (decls, size); for (j = 0; j < size; j++) vec_safe_push (decls, streamer_tree_cache_get_tree (data_in->reader_cache, data[j])); state->streams[i] = decls; data += size; } return data; } /* Global canonical type table. */ static htab_t gimple_canonical_types; static hash_map<const_tree, hashval_t> *canonical_type_hash_cache; static unsigned long num_canonical_type_hash_entries; static unsigned long num_canonical_type_hash_queries; static void iterative_hash_canonical_type (tree type, inchash::hash &hstate); static hashval_t gimple_canonical_type_hash (const void *p); static void gimple_register_canonical_type_1 (tree t, hashval_t hash); /* Returning a hash value for gimple type TYPE. The hash value returned is equal for types considered compatible by gimple_canonical_types_compatible_p. */ static hashval_t hash_canonical_type (tree type) { inchash::hash hstate; /* Combine a few common features of types so that types are grouped into smaller sets; when searching for existing matching types to merge, only existing types having the same features as the new type will be checked. */ hstate.add_int (TREE_CODE (type)); hstate.add_int (TYPE_MODE (type)); /* Incorporate common features of numerical types. */ if (INTEGRAL_TYPE_P (type) || SCALAR_FLOAT_TYPE_P (type) || FIXED_POINT_TYPE_P (type) || TREE_CODE (type) == OFFSET_TYPE || POINTER_TYPE_P (type)) { hstate.add_int (TYPE_UNSIGNED (type)); hstate.add_int (TYPE_PRECISION (type)); } if (VECTOR_TYPE_P (type)) { hstate.add_int (TYPE_VECTOR_SUBPARTS (type)); hstate.add_int (TYPE_UNSIGNED (type)); } if (TREE_CODE (type) == COMPLEX_TYPE) hstate.add_int (TYPE_UNSIGNED (type)); /* For pointer and reference types, fold in information about the type pointed to but do not recurse to the pointed-to type. */ if (POINTER_TYPE_P (type)) { hstate.add_int (TYPE_ADDR_SPACE (TREE_TYPE (type))); hstate.add_int (TREE_CODE (TREE_TYPE (type))); } /* For integer types hash only the string flag. */ if (TREE_CODE (type) == INTEGER_TYPE) hstate.add_int (TYPE_STRING_FLAG (type)); /* For array types hash the domain bounds and the string flag. */ if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type)) { hstate.add_int (TYPE_STRING_FLAG (type)); /* OMP lowering can introduce error_mark_node in place of random local decls in types. */ if (TYPE_MIN_VALUE (TYPE_DOMAIN (type)) != error_mark_node) inchash::add_expr (TYPE_MIN_VALUE (TYPE_DOMAIN (type)), hstate); if (TYPE_MAX_VALUE (TYPE_DOMAIN (type)) != error_mark_node) inchash::add_expr (TYPE_MAX_VALUE (TYPE_DOMAIN (type)), hstate); } /* Recurse for aggregates with a single element type. */ if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == COMPLEX_TYPE || TREE_CODE (type) == VECTOR_TYPE) iterative_hash_canonical_type (TREE_TYPE (type), hstate); /* Incorporate function return and argument types. */ if (TREE_CODE (type) == FUNCTION_TYPE || TREE_CODE (type) == METHOD_TYPE) { unsigned na; tree p; /* For method types also incorporate their parent class. */ if (TREE_CODE (type) == METHOD_TYPE) iterative_hash_canonical_type (TYPE_METHOD_BASETYPE (type), hstate); iterative_hash_canonical_type (TREE_TYPE (type), hstate); for (p = TYPE_ARG_TYPES (type), na = 0; p; p = TREE_CHAIN (p)) { iterative_hash_canonical_type (TREE_VALUE (p), hstate); na++; } hstate.add_int (na); } if (RECORD_OR_UNION_TYPE_P (type)) { unsigned nf; tree f; for (f = TYPE_FIELDS (type), nf = 0; f; f = TREE_CHAIN (f)) if (TREE_CODE (f) == FIELD_DECL) { iterative_hash_canonical_type (TREE_TYPE (f), hstate); nf++; } hstate.add_int (nf); } return hstate.end(); } /* Returning a hash value for gimple type TYPE combined with VAL. */ static void iterative_hash_canonical_type (tree type, inchash::hash &hstate) { hashval_t v; /* An already processed type. */ if (TYPE_CANONICAL (type)) { type = TYPE_CANONICAL (type); v = gimple_canonical_type_hash (type); } else { /* Canonical types should not be able to form SCCs by design, this recursion is just because we do not register canonical types in optimal order. To avoid quadratic behavior also register the type here. */ v = hash_canonical_type (type); gimple_register_canonical_type_1 (type, v); } hstate.add_int (v); } /* Returns the hash for a canonical type P. */ static hashval_t gimple_canonical_type_hash (const void *p) { num_canonical_type_hash_queries++; hashval_t *slot = canonical_type_hash_cache->get ((const_tree) p); gcc_assert (slot != NULL); return *slot; } /* The TYPE_CANONICAL merging machinery. It should closely resemble the middle-end types_compatible_p function. It needs to avoid claiming types are different for types that should be treated the same with respect to TBAA. Canonical types are also used for IL consistency checks via the useless_type_conversion_p predicate which does not handle all type kinds itself but falls back to pointer-comparison of TYPE_CANONICAL for aggregates for example. */ /* Return true iff T1 and T2 are structurally identical for what TBAA is concerned. */ static bool gimple_canonical_types_compatible_p (tree t1, tree t2) { /* Before starting to set up the SCC machinery handle simple cases. */ /* Check first for the obvious case of pointer identity. */ if (t1 == t2) return true; /* Check that we have two types to compare. */ if (t1 == NULL_TREE || t2 == NULL_TREE) return false; /* If the types have been previously registered and found equal they still are. */ if (TYPE_CANONICAL (t1) && TYPE_CANONICAL (t1) == TYPE_CANONICAL (t2)) return true; /* Can't be the same type if the types don't have the same code. */ if (TREE_CODE (t1) != TREE_CODE (t2)) return false; /* Qualifiers do not matter for canonical type comparison purposes. */ /* Void types and nullptr types are always the same. */ if (TREE_CODE (t1) == VOID_TYPE || TREE_CODE (t1) == NULLPTR_TYPE) return true; /* Can't be the same type if they have different mode. */ if (TYPE_MODE (t1) != TYPE_MODE (t2)) return false; /* Non-aggregate types can be handled cheaply. */ if (INTEGRAL_TYPE_P (t1) || SCALAR_FLOAT_TYPE_P (t1) || FIXED_POINT_TYPE_P (t1) || TREE_CODE (t1) == VECTOR_TYPE || TREE_CODE (t1) == COMPLEX_TYPE || TREE_CODE (t1) == OFFSET_TYPE || POINTER_TYPE_P (t1)) { /* Can't be the same type if they have different sign or precision. */ if (TYPE_PRECISION (t1) != TYPE_PRECISION (t2) || TYPE_UNSIGNED (t1) != TYPE_UNSIGNED (t2)) return false; if (TREE_CODE (t1) == INTEGER_TYPE && TYPE_STRING_FLAG (t1) != TYPE_STRING_FLAG (t2)) return false; /* For canonical type comparisons we do not want to build SCCs so we cannot compare pointed-to types. But we can, for now, require the same pointed-to type kind and match what useless_type_conversion_p would do. */ if (POINTER_TYPE_P (t1)) { if (TYPE_ADDR_SPACE (TREE_TYPE (t1)) != TYPE_ADDR_SPACE (TREE_TYPE (t2))) return false; if (TREE_CODE (TREE_TYPE (t1)) != TREE_CODE (TREE_TYPE (t2))) return false; } /* Tail-recurse to components. */ if (TREE_CODE (t1) == VECTOR_TYPE || TREE_CODE (t1) == COMPLEX_TYPE) return gimple_canonical_types_compatible_p (TREE_TYPE (t1), TREE_TYPE (t2)); return true; } /* Do type-specific comparisons. */ switch (TREE_CODE (t1)) { case ARRAY_TYPE: /* Array types are the same if the element types are the same and the number of elements are the same. */ if (!gimple_canonical_types_compatible_p (TREE_TYPE (t1), TREE_TYPE (t2)) || TYPE_STRING_FLAG (t1) != TYPE_STRING_FLAG (t2) || TYPE_NONALIASED_COMPONENT (t1) != TYPE_NONALIASED_COMPONENT (t2)) return false; else { tree i1 = TYPE_DOMAIN (t1); tree i2 = TYPE_DOMAIN (t2); /* For an incomplete external array, the type domain can be NULL_TREE. Check this condition also. */ if (i1 == NULL_TREE && i2 == NULL_TREE) return true; else if (i1 == NULL_TREE || i2 == NULL_TREE) return false; else { tree min1 = TYPE_MIN_VALUE (i1); tree min2 = TYPE_MIN_VALUE (i2); tree max1 = TYPE_MAX_VALUE (i1); tree max2 = TYPE_MAX_VALUE (i2); /* The minimum/maximum values have to be the same. */ if ((min1 == min2 || (min1 && min2 && ((TREE_CODE (min1) == PLACEHOLDER_EXPR && TREE_CODE (min2) == PLACEHOLDER_EXPR) || operand_equal_p (min1, min2, 0)))) && (max1 == max2 || (max1 && max2 && ((TREE_CODE (max1) == PLACEHOLDER_EXPR && TREE_CODE (max2) == PLACEHOLDER_EXPR) || operand_equal_p (max1, max2, 0))))) return true; else return false; } } case METHOD_TYPE: case FUNCTION_TYPE: /* Function types are the same if the return type and arguments types are the same. */ if (!gimple_canonical_types_compatible_p (TREE_TYPE (t1), TREE_TYPE (t2))) return false; if (!comp_type_attributes (t1, t2)) return false; if (TYPE_ARG_TYPES (t1) == TYPE_ARG_TYPES (t2)) return true; else { tree parms1, parms2; for (parms1 = TYPE_ARG_TYPES (t1), parms2 = TYPE_ARG_TYPES (t2); parms1 && parms2; parms1 = TREE_CHAIN (parms1), parms2 = TREE_CHAIN (parms2)) { if (!gimple_canonical_types_compatible_p (TREE_VALUE (parms1), TREE_VALUE (parms2))) return false; } if (parms1 || parms2) return false; return true; } case RECORD_TYPE: case UNION_TYPE: case QUAL_UNION_TYPE: { tree f1, f2; /* For aggregate types, all the fields must be the same. */ for (f1 = TYPE_FIELDS (t1), f2 = TYPE_FIELDS (t2); f1 || f2; f1 = TREE_CHAIN (f1), f2 = TREE_CHAIN (f2)) { /* Skip non-fields. */ while (f1 && TREE_CODE (f1) != FIELD_DECL) f1 = TREE_CHAIN (f1); while (f2 && TREE_CODE (f2) != FIELD_DECL) f2 = TREE_CHAIN (f2); if (!f1 || !f2) break; /* The fields must have the same name, offset and type. */ if (DECL_NONADDRESSABLE_P (f1) != DECL_NONADDRESSABLE_P (f2) || !gimple_compare_field_offset (f1, f2) || !gimple_canonical_types_compatible_p (TREE_TYPE (f1), TREE_TYPE (f2))) return false; } /* If one aggregate has more fields than the other, they are not the same. */ if (f1 || f2) return false; return true; } default: gcc_unreachable (); } } /* Returns nonzero if P1 and P2 are equal. */ static int gimple_canonical_type_eq (const void *p1, const void *p2) { const_tree t1 = (const_tree) p1; const_tree t2 = (const_tree) p2; return gimple_canonical_types_compatible_p (CONST_CAST_TREE (t1), CONST_CAST_TREE (t2)); } /* Main worker for gimple_register_canonical_type. */ static void gimple_register_canonical_type_1 (tree t, hashval_t hash) { void **slot; gcc_checking_assert (TYPE_P (t) && !TYPE_CANONICAL (t)); slot = htab_find_slot_with_hash (gimple_canonical_types, t, hash, INSERT); if (*slot) { tree new_type = (tree)(*slot); gcc_checking_assert (new_type != t); TYPE_CANONICAL (t) = new_type; } else { TYPE_CANONICAL (t) = t; *slot = (void *) t; /* Cache the just computed hash value. */ num_canonical_type_hash_entries++; bool existed_p = canonical_type_hash_cache->put (t, hash); gcc_assert (!existed_p); } } /* Register type T in the global type table gimple_types and set TYPE_CANONICAL of T accordingly. This is used by LTO to merge structurally equivalent types for type-based aliasing purposes across different TUs and languages. ??? This merging does not exactly match how the tree.c middle-end functions will assign TYPE_CANONICAL when new types are created during optimization (which at least happens for pointer and array types). */ static void gimple_register_canonical_type (tree t) { if (TYPE_CANONICAL (t)) return; gimple_register_canonical_type_1 (t, hash_canonical_type (t)); } /* Re-compute TYPE_CANONICAL for NODE and related types. */ static void lto_register_canonical_types (tree node, bool first_p) { if (!node || !TYPE_P (node)) return; if (first_p) TYPE_CANONICAL (node) = NULL_TREE; if (POINTER_TYPE_P (node) || TREE_CODE (node) == COMPLEX_TYPE || TREE_CODE (node) == ARRAY_TYPE) lto_register_canonical_types (TREE_TYPE (node), first_p); if (!first_p) gimple_register_canonical_type (node); } /* Remember trees that contains references to declarations. */ static GTY(()) vec <tree, va_gc> *tree_with_vars; #define CHECK_VAR(tt) \ do \ { \ if ((tt) && VAR_OR_FUNCTION_DECL_P (tt) \ && (TREE_PUBLIC (tt) || DECL_EXTERNAL (tt))) \ return true; \ } while (0) #define CHECK_NO_VAR(tt) \ gcc_checking_assert (!(tt) || !VAR_OR_FUNCTION_DECL_P (tt)) /* Check presence of pointers to decls in fields of a tree_typed T. */ static inline bool mentions_vars_p_typed (tree t) { CHECK_NO_VAR (TREE_TYPE (t)); return false; } /* Check presence of pointers to decls in fields of a tree_common T. */ static inline bool mentions_vars_p_common (tree t) { if (mentions_vars_p_typed (t)) return true; CHECK_NO_VAR (TREE_CHAIN (t)); return false; } /* Check presence of pointers to decls in fields of a decl_minimal T. */ static inline bool mentions_vars_p_decl_minimal (tree t) { if (mentions_vars_p_common (t)) return true; CHECK_NO_VAR (DECL_NAME (t)); CHECK_VAR (DECL_CONTEXT (t)); return false; } /* Check presence of pointers to decls in fields of a decl_common T. */ static inline bool mentions_vars_p_decl_common (tree t) { if (mentions_vars_p_decl_minimal (t)) return true; CHECK_VAR (DECL_SIZE (t)); CHECK_VAR (DECL_SIZE_UNIT (t)); CHECK_VAR (DECL_INITIAL (t)); CHECK_NO_VAR (DECL_ATTRIBUTES (t)); CHECK_VAR (DECL_ABSTRACT_ORIGIN (t)); return false; } /* Check presence of pointers to decls in fields of a decl_with_vis T. */ static inline bool mentions_vars_p_decl_with_vis (tree t) { if (mentions_vars_p_decl_common (t)) return true; /* Accessor macro has side-effects, use field-name here. */ CHECK_NO_VAR (t->decl_with_vis.assembler_name); return false; } /* Check presence of pointers to decls in fields of a decl_non_common T. */ static inline bool mentions_vars_p_decl_non_common (tree t) { if (mentions_vars_p_decl_with_vis (t)) return true; CHECK_NO_VAR (DECL_RESULT_FLD (t)); return false; } /* Check presence of pointers to decls in fields of a decl_non_common T. */ static bool mentions_vars_p_function (tree t) { if (mentions_vars_p_decl_non_common (t)) return true; CHECK_NO_VAR (DECL_ARGUMENTS (t)); CHECK_NO_VAR (DECL_VINDEX (t)); CHECK_VAR (DECL_FUNCTION_PERSONALITY (t)); return false; } /* Check presence of pointers to decls in fields of a field_decl T. */ static bool mentions_vars_p_field_decl (tree t) { if (mentions_vars_p_decl_common (t)) return true; CHECK_VAR (DECL_FIELD_OFFSET (t)); CHECK_NO_VAR (DECL_BIT_FIELD_TYPE (t)); CHECK_NO_VAR (DECL_QUALIFIER (t)); CHECK_NO_VAR (DECL_FIELD_BIT_OFFSET (t)); CHECK_NO_VAR (DECL_FCONTEXT (t)); return false; } /* Check presence of pointers to decls in fields of a type T. */ static bool mentions_vars_p_type (tree t) { if (mentions_vars_p_common (t)) return true; CHECK_NO_VAR (TYPE_CACHED_VALUES (t)); CHECK_VAR (TYPE_SIZE (t)); CHECK_VAR (TYPE_SIZE_UNIT (t)); CHECK_NO_VAR (TYPE_ATTRIBUTES (t)); CHECK_NO_VAR (TYPE_NAME (t)); CHECK_VAR (TYPE_MINVAL (t)); CHECK_VAR (TYPE_MAXVAL (t)); /* Accessor is for derived node types only. */ CHECK_NO_VAR (t->type_non_common.binfo); CHECK_VAR (TYPE_CONTEXT (t)); CHECK_NO_VAR (TYPE_CANONICAL (t)); CHECK_NO_VAR (TYPE_MAIN_VARIANT (t)); CHECK_NO_VAR (TYPE_NEXT_VARIANT (t)); return false; } /* Check presence of pointers to decls in fields of a BINFO T. */ static bool mentions_vars_p_binfo (tree t) { unsigned HOST_WIDE_INT i, n; if (mentions_vars_p_common (t)) return true; CHECK_VAR (BINFO_VTABLE (t)); CHECK_NO_VAR (BINFO_OFFSET (t)); CHECK_NO_VAR (BINFO_VIRTUALS (t)); CHECK_NO_VAR (BINFO_VPTR_FIELD (t)); n = vec_safe_length (BINFO_BASE_ACCESSES (t)); for (i = 0; i < n; i++) CHECK_NO_VAR (BINFO_BASE_ACCESS (t, i)); /* Do not walk BINFO_INHERITANCE_CHAIN, BINFO_SUBVTT_INDEX and BINFO_VPTR_INDEX; these are used by C++ FE only. */ n = BINFO_N_BASE_BINFOS (t); for (i = 0; i < n; i++) CHECK_NO_VAR (BINFO_BASE_BINFO (t, i)); return false; } /* Check presence of pointers to decls in fields of a CONSTRUCTOR T. */ static bool mentions_vars_p_constructor (tree t) { unsigned HOST_WIDE_INT idx; constructor_elt *ce; if (mentions_vars_p_typed (t)) return true; for (idx = 0; vec_safe_iterate (CONSTRUCTOR_ELTS (t), idx, &ce); idx++) { CHECK_NO_VAR (ce->index); CHECK_VAR (ce->value); } return false; } /* Check presence of pointers to decls in fields of an expression tree T. */ static bool mentions_vars_p_expr (tree t) { int i; if (mentions_vars_p_typed (t)) return true; for (i = TREE_OPERAND_LENGTH (t) - 1; i >= 0; --i) CHECK_VAR (TREE_OPERAND (t, i)); return false; } /* Check presence of pointers to decls in fields of an OMP_CLAUSE T. */ static bool mentions_vars_p_omp_clause (tree t) { int i; if (mentions_vars_p_common (t)) return true; for (i = omp_clause_num_ops[OMP_CLAUSE_CODE (t)] - 1; i >= 0; --i) CHECK_VAR (OMP_CLAUSE_OPERAND (t, i)); return false; } /* Check presence of pointers to decls that needs later fixup in T. */ static bool mentions_vars_p (tree t) { switch (TREE_CODE (t)) { case IDENTIFIER_NODE: break; case TREE_LIST: CHECK_VAR (TREE_VALUE (t)); CHECK_VAR (TREE_PURPOSE (t)); CHECK_NO_VAR (TREE_CHAIN (t)); break; case FIELD_DECL: return mentions_vars_p_field_decl (t); case LABEL_DECL: case CONST_DECL: case PARM_DECL: case RESULT_DECL: case IMPORTED_DECL: case NAMESPACE_DECL: case NAMELIST_DECL: return mentions_vars_p_decl_common (t); case VAR_DECL: return mentions_vars_p_decl_with_vis (t); case TYPE_DECL: return mentions_vars_p_decl_non_common (t); case FUNCTION_DECL: return mentions_vars_p_function (t); case TREE_BINFO: return mentions_vars_p_binfo (t); case PLACEHOLDER_EXPR: return mentions_vars_p_common (t); case BLOCK: case TRANSLATION_UNIT_DECL: case OPTIMIZATION_NODE: case TARGET_OPTION_NODE: break; case CONSTRUCTOR: return mentions_vars_p_constructor (t); case OMP_CLAUSE: return mentions_vars_p_omp_clause (t); default: if (TYPE_P (t)) { if (mentions_vars_p_type (t)) return true; } else if (EXPR_P (t)) { if (mentions_vars_p_expr (t)) return true; } else if (CONSTANT_CLASS_P (t)) CHECK_NO_VAR (TREE_TYPE (t)); else gcc_unreachable (); } return false; } /* Return the resolution for the decl with index INDEX from DATA_IN. */ static enum ld_plugin_symbol_resolution get_resolution (struct data_in *data_in, unsigned index) { if (data_in->globals_resolution.exists ()) { ld_plugin_symbol_resolution_t ret; /* We can have references to not emitted functions in DECL_FUNCTION_PERSONALITY at least. So we can and have to indeed return LDPR_UNKNOWN in some cases. */ if (data_in->globals_resolution.length () <= index) return LDPR_UNKNOWN; ret = data_in->globals_resolution[index]; return ret; } else /* Delay resolution finding until decl merging. */ return LDPR_UNKNOWN; } /* We need to record resolutions until symbol table is read. */ static void register_resolution (struct lto_file_decl_data *file_data, tree decl, enum ld_plugin_symbol_resolution resolution) { if (resolution == LDPR_UNKNOWN) return; if (!file_data->resolution_map) file_data->resolution_map = new hash_map<tree, ld_plugin_symbol_resolution>; file_data->resolution_map->put (decl, resolution); } /* Register DECL with the global symbol table and change its name if necessary to avoid name clashes for static globals across different files. */ static void lto_register_var_decl_in_symtab (struct data_in *data_in, tree decl, unsigned ix) { tree context; /* Variable has file scope, not local. */ if (!TREE_PUBLIC (decl) && !((context = decl_function_context (decl)) && auto_var_in_fn_p (decl, context))) rest_of_decl_compilation (decl, 1, 0); /* If this variable has already been declared, queue the declaration for merging. */ if (TREE_PUBLIC (decl)) register_resolution (data_in->file_data, decl, get_resolution (data_in, ix)); } /* Register DECL with the global symbol table and change its name if necessary to avoid name clashes for static globals across different files. DATA_IN contains descriptors and tables for the file being read. */ static void lto_register_function_decl_in_symtab (struct data_in *data_in, tree decl, unsigned ix) { /* If this variable has already been declared, queue the declaration for merging. */ if (TREE_PUBLIC (decl) && !DECL_ABSTRACT_P (decl)) register_resolution (data_in->file_data, decl, get_resolution (data_in, ix)); } /* For the type T re-materialize it in the type variant list and the pointer/reference-to chains. */ static void lto_fixup_prevailing_type (tree t) { /* The following re-creates proper variant lists while fixing up the variant leaders. We do not stream TYPE_NEXT_VARIANT so the variant list state before fixup is broken. */ /* If we are not our own variant leader link us into our new leaders variant list. */ if (TYPE_MAIN_VARIANT (t) != t) { tree mv = TYPE_MAIN_VARIANT (t); TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (mv); TYPE_NEXT_VARIANT (mv) = t; } /* The following reconstructs the pointer chains of the new pointed-to type if we are a main variant. We do not stream those so they are broken before fixup. */ if (TREE_CODE (t) == POINTER_TYPE && TYPE_MAIN_VARIANT (t) == t) { TYPE_NEXT_PTR_TO (t) = TYPE_POINTER_TO (TREE_TYPE (t)); TYPE_POINTER_TO (TREE_TYPE (t)) = t; } else if (TREE_CODE (t) == REFERENCE_TYPE && TYPE_MAIN_VARIANT (t) == t) { TYPE_NEXT_REF_TO (t) = TYPE_REFERENCE_TO (TREE_TYPE (t)); TYPE_REFERENCE_TO (TREE_TYPE (t)) = t; } } /* We keep prevailing tree SCCs in a hashtable with manual collision handling (in case all hashes compare the same) and keep the colliding entries in the tree_scc->next chain. */ struct tree_scc { tree_scc *next; /* Hash of the whole SCC. */ hashval_t hash; /* Number of trees in the SCC. */ unsigned len; /* Number of possible entries into the SCC (tree nodes [0..entry_len-1] which share the same individual tree hash). */ unsigned entry_len; /* The members of the SCC. We only need to remember the first entry node candidate for prevailing SCCs (but of course have access to all entries for SCCs we are processing). ??? For prevailing SCCs we really only need hash and the first entry candidate, but that's too awkward to implement. */ tree entries[1]; }; struct tree_scc_hasher : typed_noop_remove <tree_scc> { typedef tree_scc value_type; typedef tree_scc compare_type; static inline hashval_t hash (const value_type *); static inline bool equal (const value_type *, const compare_type *); }; hashval_t tree_scc_hasher::hash (const value_type *scc) { return scc->hash; } bool tree_scc_hasher::equal (const value_type *scc1, const compare_type *scc2) { if (scc1->hash != scc2->hash || scc1->len != scc2->len || scc1->entry_len != scc2->entry_len) return false; return true; } static hash_table<tree_scc_hasher> *tree_scc_hash; static struct obstack tree_scc_hash_obstack; static unsigned long num_merged_types; static unsigned long num_prevailing_types; static unsigned long num_type_scc_trees; static unsigned long total_scc_size; static unsigned long num_sccs_read; static unsigned long total_scc_size_merged; static unsigned long num_sccs_merged; static unsigned long num_scc_compares; static unsigned long num_scc_compare_collisions; /* Compare the two entries T1 and T2 of two SCCs that are possibly equal, recursing through in-SCC tree edges. Returns true if the SCCs entered through T1 and T2 are equal and fills in *MAP with the pairs of SCC entries we visited, starting with (*MAP)[0] = T1 and (*MAP)[1] = T2. */ static bool compare_tree_sccs_1 (tree t1, tree t2, tree **map) { enum tree_code code; /* Mark already visited nodes. */ TREE_ASM_WRITTEN (t2) = 1; /* Push the pair onto map. */ (*map)[0] = t1; (*map)[1] = t2; *map = *map + 2; /* Compare value-fields. */ #define compare_values(X) \ do { \ if (X(t1) != X(t2)) \ return false; \ } while (0) compare_values (TREE_CODE); code = TREE_CODE (t1); if (!TYPE_P (t1)) { compare_values (TREE_SIDE_EFFECTS); compare_values (TREE_CONSTANT); compare_values (TREE_READONLY); compare_values (TREE_PUBLIC); } compare_values (TREE_ADDRESSABLE); compare_values (TREE_THIS_VOLATILE); if (DECL_P (t1)) compare_values (DECL_UNSIGNED); else if (TYPE_P (t1)) compare_values (TYPE_UNSIGNED); if (TYPE_P (t1)) compare_values (TYPE_ARTIFICIAL); else compare_values (TREE_NO_WARNING); compare_values (TREE_NOTHROW); compare_values (TREE_STATIC); if (code != TREE_BINFO) compare_values (TREE_PRIVATE); compare_values (TREE_PROTECTED); compare_values (TREE_DEPRECATED); if (TYPE_P (t1)) { compare_values (TYPE_SATURATING); compare_values (TYPE_ADDR_SPACE); } else if (code == SSA_NAME) compare_values (SSA_NAME_IS_DEFAULT_DEF); if (CODE_CONTAINS_STRUCT (code, TS_INT_CST)) { if (!wi::eq_p (t1, t2)) return false; } if (CODE_CONTAINS_STRUCT (code, TS_REAL_CST)) { /* ??? No suitable compare routine available. */ REAL_VALUE_TYPE r1 = TREE_REAL_CST (t1); REAL_VALUE_TYPE r2 = TREE_REAL_CST (t2); if (r1.cl != r2.cl || r1.decimal != r2.decimal || r1.sign != r2.sign || r1.signalling != r2.signalling || r1.canonical != r2.canonical || r1.uexp != r2.uexp) return false; for (unsigned i = 0; i < SIGSZ; ++i) if (r1.sig[i] != r2.sig[i]) return false; } if (CODE_CONTAINS_STRUCT (code, TS_FIXED_CST)) if (!fixed_compare (EQ_EXPR, TREE_FIXED_CST_PTR (t1), TREE_FIXED_CST_PTR (t2))) return false; /* We don't want to compare locations, so there is nothing do compare for TS_DECL_MINIMAL. */ if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON)) { compare_values (DECL_MODE); compare_values (DECL_NONLOCAL); compare_values (DECL_VIRTUAL_P); compare_values (DECL_IGNORED_P); compare_values (DECL_ABSTRACT_P); compare_values (DECL_ARTIFICIAL); compare_values (DECL_USER_ALIGN); compare_values (DECL_PRESERVE_P); compare_values (DECL_EXTERNAL); compare_values (DECL_GIMPLE_REG_P); compare_values (DECL_ALIGN); if (code == LABEL_DECL) { compare_values (EH_LANDING_PAD_NR); compare_values (LABEL_DECL_UID); } else if (code == FIELD_DECL) { compare_values (DECL_PACKED); compare_values (DECL_NONADDRESSABLE_P); compare_values (DECL_OFFSET_ALIGN); } else if (code == VAR_DECL) { compare_values (DECL_HAS_DEBUG_EXPR_P); compare_values (DECL_NONLOCAL_FRAME); } if (code == RESULT_DECL || code == PARM_DECL || code == VAR_DECL) { compare_values (DECL_BY_REFERENCE); if (code == VAR_DECL || code == PARM_DECL) compare_values (DECL_HAS_VALUE_EXPR_P); } } if (CODE_CONTAINS_STRUCT (code, TS_DECL_WRTL)) compare_values (DECL_REGISTER); if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS)) { compare_values (DECL_COMMON); compare_values (DECL_DLLIMPORT_P); compare_values (DECL_WEAK); compare_values (DECL_SEEN_IN_BIND_EXPR_P); compare_values (DECL_COMDAT); compare_values (DECL_VISIBILITY); compare_values (DECL_VISIBILITY_SPECIFIED); if (code == VAR_DECL) { compare_values (DECL_HARD_REGISTER); /* DECL_IN_TEXT_SECTION is set during final asm output only. */ compare_values (DECL_IN_CONSTANT_POOL); } } if (CODE_CONTAINS_STRUCT (code, TS_FUNCTION_DECL)) { compare_values (DECL_BUILT_IN_CLASS); compare_values (DECL_STATIC_CONSTRUCTOR); compare_values (DECL_STATIC_DESTRUCTOR); compare_values (DECL_UNINLINABLE); compare_values (DECL_POSSIBLY_INLINED); compare_values (DECL_IS_NOVOPS); compare_values (DECL_IS_RETURNS_TWICE); compare_values (DECL_IS_MALLOC); compare_values (DECL_IS_OPERATOR_NEW); compare_values (DECL_DECLARED_INLINE_P); compare_values (DECL_STATIC_CHAIN); compare_values (DECL_NO_INLINE_WARNING_P); compare_values (DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT); compare_values (DECL_NO_LIMIT_STACK); compare_values (DECL_DISREGARD_INLINE_LIMITS); compare_values (DECL_PURE_P); compare_values (DECL_LOOPING_CONST_OR_PURE_P); compare_values (DECL_FINAL_P); compare_values (DECL_CXX_CONSTRUCTOR_P); compare_values (DECL_CXX_DESTRUCTOR_P); if (DECL_BUILT_IN_CLASS (t1) != NOT_BUILT_IN) compare_values (DECL_FUNCTION_CODE); } if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON)) { compare_values (TYPE_MODE); compare_values (TYPE_STRING_FLAG); compare_values (TYPE_NO_FORCE_BLK); compare_values (TYPE_NEEDS_CONSTRUCTING); if (RECORD_OR_UNION_TYPE_P (t1)) { compare_values (TYPE_TRANSPARENT_AGGR); compare_values (TYPE_FINAL_P); } else if (code == ARRAY_TYPE) compare_values (TYPE_NONALIASED_COMPONENT); compare_values (TYPE_PACKED); compare_values (TYPE_RESTRICT); compare_values (TYPE_USER_ALIGN); compare_values (TYPE_READONLY); compare_values (TYPE_PRECISION); compare_values (TYPE_ALIGN); compare_values (TYPE_ALIAS_SET); } /* We don't want to compare locations, so there is nothing do compare for TS_EXP. */ /* BLOCKs are function local and we don't merge anything there, so simply refuse to merge. */ if (CODE_CONTAINS_STRUCT (code, TS_BLOCK)) return false; if (CODE_CONTAINS_STRUCT (code, TS_TRANSLATION_UNIT_DECL)) if (strcmp (TRANSLATION_UNIT_LANGUAGE (t1), TRANSLATION_UNIT_LANGUAGE (t2)) != 0) return false; if (CODE_CONTAINS_STRUCT (code, TS_TARGET_OPTION)) if (!cl_target_option_eq (TREE_TARGET_OPTION (t1), TREE_TARGET_OPTION (t2))) return false; if (CODE_CONTAINS_STRUCT (code, TS_OPTIMIZATION)) if (memcmp (TREE_OPTIMIZATION (t1), TREE_OPTIMIZATION (t2), sizeof (struct cl_optimization)) != 0) return false; if (CODE_CONTAINS_STRUCT (code, TS_BINFO)) if (vec_safe_length (BINFO_BASE_ACCESSES (t1)) != vec_safe_length (BINFO_BASE_ACCESSES (t2))) return false; if (CODE_CONTAINS_STRUCT (code, TS_CONSTRUCTOR)) compare_values (CONSTRUCTOR_NELTS); if (CODE_CONTAINS_STRUCT (code, TS_IDENTIFIER)) if (IDENTIFIER_LENGTH (t1) != IDENTIFIER_LENGTH (t2) || memcmp (IDENTIFIER_POINTER (t1), IDENTIFIER_POINTER (t2), IDENTIFIER_LENGTH (t1)) != 0) return false; if (CODE_CONTAINS_STRUCT (code, TS_STRING)) if (TREE_STRING_LENGTH (t1) != TREE_STRING_LENGTH (t2) || memcmp (TREE_STRING_POINTER (t1), TREE_STRING_POINTER (t2), TREE_STRING_LENGTH (t1)) != 0) return false; if (code == OMP_CLAUSE) { compare_values (OMP_CLAUSE_CODE); switch (OMP_CLAUSE_CODE (t1)) { case OMP_CLAUSE_DEFAULT: compare_values (OMP_CLAUSE_DEFAULT_KIND); break; case OMP_CLAUSE_SCHEDULE: compare_values (OMP_CLAUSE_SCHEDULE_KIND); break; case OMP_CLAUSE_DEPEND: compare_values (OMP_CLAUSE_DEPEND_KIND); break; case OMP_CLAUSE_MAP: compare_values (OMP_CLAUSE_MAP_KIND); break; case OMP_CLAUSE_PROC_BIND: compare_values (OMP_CLAUSE_PROC_BIND_KIND); break; case OMP_CLAUSE_REDUCTION: compare_values (OMP_CLAUSE_REDUCTION_CODE); compare_values (OMP_CLAUSE_REDUCTION_GIMPLE_INIT); compare_values (OMP_CLAUSE_REDUCTION_GIMPLE_MERGE); break; default: break; } } #undef compare_values /* Compare pointer fields. */ /* Recurse. Search & Replaced from DFS_write_tree_body. Folding the early checks into the compare_tree_edges recursion macro makes debugging way quicker as you are able to break on compare_tree_sccs_1 and simply finish until a call returns false to spot the SCC members with the difference. */ #define compare_tree_edges(E1, E2) \ do { \ tree t1_ = (E1), t2_ = (E2); \ if (t1_ != t2_ \ && (!t1_ || !t2_ \ || !TREE_VISITED (t2_) \ || (!TREE_ASM_WRITTEN (t2_) \ && !compare_tree_sccs_1 (t1_, t2_, map)))) \ return false; \ /* Only non-NULL trees outside of the SCC may compare equal. */ \ gcc_checking_assert (t1_ != t2_ || (!t2_ || !TREE_VISITED (t2_))); \ } while (0) if (CODE_CONTAINS_STRUCT (code, TS_TYPED)) { if (code != IDENTIFIER_NODE) compare_tree_edges (TREE_TYPE (t1), TREE_TYPE (t2)); } if (CODE_CONTAINS_STRUCT (code, TS_VECTOR)) { unsigned i; /* Note that the number of elements for EXPR has already been emitted in EXPR's header (see streamer_write_tree_header). */ for (i = 0; i < VECTOR_CST_NELTS (t1); ++i) compare_tree_edges (VECTOR_CST_ELT (t1, i), VECTOR_CST_ELT (t2, i)); } if (CODE_CONTAINS_STRUCT (code, TS_COMPLEX)) { compare_tree_edges (TREE_REALPART (t1), TREE_REALPART (t2)); compare_tree_edges (TREE_IMAGPART (t1), TREE_IMAGPART (t2)); } if (CODE_CONTAINS_STRUCT (code, TS_DECL_MINIMAL)) { compare_tree_edges (DECL_NAME (t1), DECL_NAME (t2)); /* ??? Global decls from different TUs have non-matching TRANSLATION_UNIT_DECLs. Only consider a small set of decls equivalent, we should not end up merging others. */ if ((code == TYPE_DECL || code == NAMESPACE_DECL || code == IMPORTED_DECL || code == CONST_DECL || (VAR_OR_FUNCTION_DECL_P (t1) && (TREE_PUBLIC (t1) || DECL_EXTERNAL (t1)))) && DECL_FILE_SCOPE_P (t1) && DECL_FILE_SCOPE_P (t2)) ; else compare_tree_edges (DECL_CONTEXT (t1), DECL_CONTEXT (t2)); } if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON)) { compare_tree_edges (DECL_SIZE (t1), DECL_SIZE (t2)); compare_tree_edges (DECL_SIZE_UNIT (t1), DECL_SIZE_UNIT (t2)); compare_tree_edges (DECL_ATTRIBUTES (t1), DECL_ATTRIBUTES (t2)); if ((code == VAR_DECL || code == PARM_DECL) && DECL_HAS_VALUE_EXPR_P (t1)) compare_tree_edges (DECL_VALUE_EXPR (t1), DECL_VALUE_EXPR (t2)); if (code == VAR_DECL && DECL_HAS_DEBUG_EXPR_P (t1)) compare_tree_edges (DECL_DEBUG_EXPR (t1), DECL_DEBUG_EXPR (t2)); /* LTO specific edges. */ if (code != FUNCTION_DECL && code != TRANSLATION_UNIT_DECL) compare_tree_edges (DECL_INITIAL (t1), DECL_INITIAL (t2)); } if (CODE_CONTAINS_STRUCT (code, TS_DECL_NON_COMMON)) { if (code == FUNCTION_DECL) { tree a1, a2; for (a1 = DECL_ARGUMENTS (t1), a2 = DECL_ARGUMENTS (t2); a1 || a2; a1 = TREE_CHAIN (a1), a2 = TREE_CHAIN (a2)) compare_tree_edges (a1, a2); compare_tree_edges (DECL_RESULT (t1), DECL_RESULT (t2)); } else if (code == TYPE_DECL) compare_tree_edges (DECL_ORIGINAL_TYPE (t1), DECL_ORIGINAL_TYPE (t2)); } if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS)) { /* Make sure we don't inadvertently set the assembler name. */ if (DECL_ASSEMBLER_NAME_SET_P (t1)) compare_tree_edges (DECL_ASSEMBLER_NAME (t1), DECL_ASSEMBLER_NAME (t2)); } if (CODE_CONTAINS_STRUCT (code, TS_FIELD_DECL)) { compare_tree_edges (DECL_FIELD_OFFSET (t1), DECL_FIELD_OFFSET (t2)); compare_tree_edges (DECL_BIT_FIELD_TYPE (t1), DECL_BIT_FIELD_TYPE (t2)); compare_tree_edges (DECL_BIT_FIELD_REPRESENTATIVE (t1), DECL_BIT_FIELD_REPRESENTATIVE (t2)); compare_tree_edges (DECL_FIELD_BIT_OFFSET (t1), DECL_FIELD_BIT_OFFSET (t2)); compare_tree_edges (DECL_FCONTEXT (t1), DECL_FCONTEXT (t2)); } if (CODE_CONTAINS_STRUCT (code, TS_FUNCTION_DECL)) { compare_tree_edges (DECL_FUNCTION_PERSONALITY (t1), DECL_FUNCTION_PERSONALITY (t2)); compare_tree_edges (DECL_VINDEX (t1), DECL_VINDEX (t2)); compare_tree_edges (DECL_FUNCTION_SPECIFIC_TARGET (t1), DECL_FUNCTION_SPECIFIC_TARGET (t2)); compare_tree_edges (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (t1), DECL_FUNCTION_SPECIFIC_OPTIMIZATION (t2)); } if (CODE_CONTAINS_STRUCT (code, TS_TYPE_COMMON)) { compare_tree_edges (TYPE_SIZE (t1), TYPE_SIZE (t2)); compare_tree_edges (TYPE_SIZE_UNIT (t1), TYPE_SIZE_UNIT (t2)); compare_tree_edges (TYPE_ATTRIBUTES (t1), TYPE_ATTRIBUTES (t2)); compare_tree_edges (TYPE_NAME (t1), TYPE_NAME (t2)); /* Do not compare TYPE_POINTER_TO or TYPE_REFERENCE_TO. They will be reconstructed during fixup. */ /* Do not compare TYPE_NEXT_VARIANT, we reconstruct the variant lists during fixup. */ compare_tree_edges (TYPE_MAIN_VARIANT (t1), TYPE_MAIN_VARIANT (t2)); /* ??? Global types from different TUs have non-matching TRANSLATION_UNIT_DECLs. Still merge them if they are otherwise equal. */ if (TYPE_FILE_SCOPE_P (t1) && TYPE_FILE_SCOPE_P (t2)) ; else compare_tree_edges (TYPE_CONTEXT (t1), TYPE_CONTEXT (t2)); /* TYPE_CANONICAL is re-computed during type merging, so do not compare it here. */ compare_tree_edges (TYPE_STUB_DECL (t1), TYPE_STUB_DECL (t2)); } if (CODE_CONTAINS_STRUCT (code, TS_TYPE_NON_COMMON)) { if (code == ENUMERAL_TYPE) compare_tree_edges (TYPE_VALUES (t1), TYPE_VALUES (t2)); else if (code == ARRAY_TYPE) compare_tree_edges (TYPE_DOMAIN (t1), TYPE_DOMAIN (t2)); else if (RECORD_OR_UNION_TYPE_P (t1)) { tree f1, f2; for (f1 = TYPE_FIELDS (t1), f2 = TYPE_FIELDS (t2); f1 || f2; f1 = TREE_CHAIN (f1), f2 = TREE_CHAIN (f2)) compare_tree_edges (f1, f2); compare_tree_edges (TYPE_BINFO (t1), TYPE_BINFO (t2)); } else if (code == FUNCTION_TYPE || code == METHOD_TYPE) compare_tree_edges (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2)); if (!POINTER_TYPE_P (t1)) compare_tree_edges (TYPE_MINVAL (t1), TYPE_MINVAL (t2)); compare_tree_edges (TYPE_MAXVAL (t1), TYPE_MAXVAL (t2)); } if (CODE_CONTAINS_STRUCT (code, TS_LIST)) { compare_tree_edges (TREE_PURPOSE (t1), TREE_PURPOSE (t2)); compare_tree_edges (TREE_VALUE (t1), TREE_VALUE (t2)); compare_tree_edges (TREE_CHAIN (t1), TREE_CHAIN (t2)); } if (CODE_CONTAINS_STRUCT (code, TS_VEC)) for (int i = 0; i < TREE_VEC_LENGTH (t1); i++) compare_tree_edges (TREE_VEC_ELT (t1, i), TREE_VEC_ELT (t2, i)); if (CODE_CONTAINS_STRUCT (code, TS_EXP)) { for (int i = 0; i < TREE_OPERAND_LENGTH (t1); i++) compare_tree_edges (TREE_OPERAND (t1, i), TREE_OPERAND (t2, i)); /* BLOCKs are function local and we don't merge anything there. */ if (TREE_BLOCK (t1) || TREE_BLOCK (t2)) return false; } if (CODE_CONTAINS_STRUCT (code, TS_BINFO)) { unsigned i; tree t; /* Lengths have already been compared above. */ FOR_EACH_VEC_ELT (*BINFO_BASE_BINFOS (t1), i, t) compare_tree_edges (t, BINFO_BASE_BINFO (t2, i)); FOR_EACH_VEC_SAFE_ELT (BINFO_BASE_ACCESSES (t1), i, t) compare_tree_edges (t, BINFO_BASE_ACCESS (t2, i)); compare_tree_edges (BINFO_OFFSET (t1), BINFO_OFFSET (t2)); compare_tree_edges (BINFO_VTABLE (t1), BINFO_VTABLE (t2)); compare_tree_edges (BINFO_VPTR_FIELD (t1), BINFO_VPTR_FIELD (t2)); /* Do not walk BINFO_INHERITANCE_CHAIN, BINFO_SUBVTT_INDEX and BINFO_VPTR_INDEX; these are used by C++ FE only. */ } if (CODE_CONTAINS_STRUCT (code, TS_CONSTRUCTOR)) { unsigned i; tree index, value; /* Lengths have already been compared above. */ FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t1), i, index, value) { compare_tree_edges (index, CONSTRUCTOR_ELT (t2, i)->index); compare_tree_edges (value, CONSTRUCTOR_ELT (t2, i)->value); } } if (code == OMP_CLAUSE) { int i; for (i = 0; i < omp_clause_num_ops[OMP_CLAUSE_CODE (t1)]; i++) compare_tree_edges (OMP_CLAUSE_OPERAND (t1, i), OMP_CLAUSE_OPERAND (t2, i)); compare_tree_edges (OMP_CLAUSE_CHAIN (t1), OMP_CLAUSE_CHAIN (t2)); } #undef compare_tree_edges return true; } /* Compare the tree scc SCC to the prevailing candidate PSCC, filling out MAP if they are equal. */ static bool compare_tree_sccs (tree_scc *pscc, tree_scc *scc, tree *map) { /* Assume SCC entry hashes are sorted after their cardinality. Which means we can simply take the first n-tuple of equal hashes (which is recorded as entry_len) and do n SCC entry candidate comparisons. */ for (unsigned i = 0; i < pscc->entry_len; ++i) { tree *mapp = map; num_scc_compare_collisions++; if (compare_tree_sccs_1 (pscc->entries[0], scc->entries[i], &mapp)) { /* Equal - no need to reset TREE_VISITED or TREE_ASM_WRITTEN on the scc as all trees will be freed. */ return true; } /* Reset TREE_ASM_WRITTEN on scc for the next compare or in case the SCC prevails. */ for (unsigned j = 0; j < scc->len; ++j) TREE_ASM_WRITTEN (scc->entries[j]) = 0; } return false; } /* QSort sort function to sort a map of two pointers after the 2nd pointer. */ static int cmp_tree (const void *p1_, const void *p2_) { tree *p1 = (tree *)(const_cast<void *>(p1_)); tree *p2 = (tree *)(const_cast<void *>(p2_)); if (p1[1] == p2[1]) return 0; return ((uintptr_t)p1[1] < (uintptr_t)p2[1]) ? -1 : 1; } /* Try to unify the SCC with nodes FROM to FROM + LEN in CACHE and hash value SCC_HASH with an already recorded SCC. Return true if that was successful, otherwise return false. */ static bool unify_scc (struct data_in *data_in, unsigned from, unsigned len, unsigned scc_entry_len, hashval_t scc_hash) { bool unified_p = false; struct streamer_tree_cache_d *cache = data_in->reader_cache; tree_scc *scc = (tree_scc *) alloca (sizeof (tree_scc) + (len - 1) * sizeof (tree)); scc->next = NULL; scc->hash = scc_hash; scc->len = len; scc->entry_len = scc_entry_len; for (unsigned i = 0; i < len; ++i) { tree t = streamer_tree_cache_get_tree (cache, from + i); scc->entries[i] = t; /* Do not merge SCCs with local entities inside them. Also do not merge TRANSLATION_UNIT_DECLs. */ if (TREE_CODE (t) == TRANSLATION_UNIT_DECL || (VAR_OR_FUNCTION_DECL_P (t) && !(TREE_PUBLIC (t) || DECL_EXTERNAL (t))) || TREE_CODE (t) == LABEL_DECL) { /* Avoid doing any work for these cases and do not worry to record the SCCs for further merging. */ return false; } } /* Look for the list of candidate SCCs to compare against. */ tree_scc **slot; slot = tree_scc_hash->find_slot_with_hash (scc, scc_hash, INSERT); if (*slot) { /* Try unifying against each candidate. */ num_scc_compares++; /* Set TREE_VISITED on the scc so we can easily identify tree nodes outside of the scc when following tree edges. Make sure that TREE_ASM_WRITTEN is unset so we can use it as 2nd bit to track whether we visited the SCC member during the compare. We cannot use TREE_VISITED on the pscc members as the extended scc and pscc can overlap. */ for (unsigned i = 0; i < scc->len; ++i) { TREE_VISITED (scc->entries[i]) = 1; gcc_checking_assert (!TREE_ASM_WRITTEN (scc->entries[i])); } tree *map = XALLOCAVEC (tree, 2 * len); for (tree_scc *pscc = *slot; pscc; pscc = pscc->next) { if (!compare_tree_sccs (pscc, scc, map)) continue; /* Found an equal SCC. */ unified_p = true; num_scc_compare_collisions--; num_sccs_merged++; total_scc_size_merged += len; #ifdef ENABLE_CHECKING for (unsigned i = 0; i < len; ++i) { tree t = map[2*i+1]; enum tree_code code = TREE_CODE (t); /* IDENTIFIER_NODEs should be singletons and are merged by the streamer. The others should be singletons, too, and we should not merge them in any way. */ gcc_assert (code != TRANSLATION_UNIT_DECL && code != IDENTIFIER_NODE && !streamer_handle_as_builtin_p (t)); } #endif /* Fixup the streamer cache with the prevailing nodes according to the tree node mapping computed by compare_tree_sccs. */ if (len == 1) streamer_tree_cache_replace_tree (cache, pscc->entries[0], from); else { tree *map2 = XALLOCAVEC (tree, 2 * len); for (unsigned i = 0; i < len; ++i) { map2[i*2] = (tree)(uintptr_t)(from + i); map2[i*2+1] = scc->entries[i]; } qsort (map2, len, 2 * sizeof (tree), cmp_tree); qsort (map, len, 2 * sizeof (tree), cmp_tree); for (unsigned i = 0; i < len; ++i) streamer_tree_cache_replace_tree (cache, map[2*i], (uintptr_t)map2[2*i]); } /* Free the tree nodes from the read SCC. */ data_in->location_cache.revert_location_cache (); for (unsigned i = 0; i < len; ++i) { enum tree_code code; if (TYPE_P (scc->entries[i])) num_merged_types++; code = TREE_CODE (scc->entries[i]); if (CODE_CONTAINS_STRUCT (code, TS_CONSTRUCTOR)) vec_free (CONSTRUCTOR_ELTS (scc->entries[i])); ggc_free (scc->entries[i]); } break; } /* Reset TREE_VISITED if we didn't unify the SCC with another. */ if (!unified_p) for (unsigned i = 0; i < scc->len; ++i) TREE_VISITED (scc->entries[i]) = 0; } /* If we didn't unify it to any candidate duplicate the relevant pieces to permanent storage and link it into the chain. */ if (!unified_p) { tree_scc *pscc = XOBNEWVAR (&tree_scc_hash_obstack, tree_scc, sizeof (tree_scc)); memcpy (pscc, scc, sizeof (tree_scc)); pscc->next = (*slot); *slot = pscc; } return unified_p; } /* Read all the symbols from buffer DATA, using descriptors in DECL_DATA. RESOLUTIONS is the set of symbols picked by the linker (read from the resolution file when the linker plugin is being used). */ static void lto_read_decls (struct lto_file_decl_data *decl_data, const void *data, vec<ld_plugin_symbol_resolution_t> resolutions) { const struct lto_decl_header *header = (const struct lto_decl_header *) data; const int decl_offset = sizeof (struct lto_decl_header); const int main_offset = decl_offset + header->decl_state_size; const int string_offset = main_offset + header->main_size; struct data_in *data_in; unsigned int i; const uint32_t *data_ptr, *data_end; uint32_t num_decl_states; lto_input_block ib_main ((const char *) data + main_offset, header->main_size, decl_data->mode_table); data_in = lto_data_in_create (decl_data, (const char *) data + string_offset, header->string_size, resolutions); /* We do not uniquify the pre-loaded cache entries, those are middle-end internal types that should not be merged. */ /* Read the global declarations and types. */ while (ib_main.p < ib_main.len) { tree t; unsigned from = data_in->reader_cache->nodes.length (); /* Read and uniquify SCCs as in the input stream. */ enum LTO_tags tag = streamer_read_record_start (&ib_main); if (tag == LTO_tree_scc) { unsigned len_; unsigned scc_entry_len; hashval_t scc_hash = lto_input_scc (&ib_main, data_in, &len_, &scc_entry_len); unsigned len = data_in->reader_cache->nodes.length () - from; gcc_assert (len == len_); total_scc_size += len; num_sccs_read++; /* We have the special case of size-1 SCCs that are pre-merged by means of identifier and string sharing for example. ??? Maybe we should avoid streaming those as SCCs. */ tree first = streamer_tree_cache_get_tree (data_in->reader_cache, from); if (len == 1 && (TREE_CODE (first) == IDENTIFIER_NODE || TREE_CODE (first) == INTEGER_CST || TREE_CODE (first) == TRANSLATION_UNIT_DECL || streamer_handle_as_builtin_p (first))) continue; /* Try to unify the SCC with already existing ones. */ if (!flag_ltrans && unify_scc (data_in, from, len, scc_entry_len, scc_hash)) continue; /* Tree merging failed, mark entries in location cache as permanent. */ data_in->location_cache.accept_location_cache (); bool seen_type = false; for (unsigned i = 0; i < len; ++i) { tree t = streamer_tree_cache_get_tree (data_in->reader_cache, from + i); /* Reconstruct the type variant and pointer-to/reference-to chains. */ if (TYPE_P (t)) { seen_type = true; num_prevailing_types++; lto_fixup_prevailing_type (t); } /* Compute the canonical type of all types. ??? Should be able to assert that !TYPE_CANONICAL. */ if (TYPE_P (t) && !TYPE_CANONICAL (t)) { gimple_register_canonical_type (t); if (odr_type_p (t)) register_odr_type (t); } /* Link shared INTEGER_CSTs into TYPE_CACHED_VALUEs of its type which is also member of this SCC. */ if (TREE_CODE (t) == INTEGER_CST && !TREE_OVERFLOW (t)) cache_integer_cst (t); /* Register TYPE_DECLs with the debuginfo machinery. */ if (!flag_wpa && TREE_CODE (t) == TYPE_DECL) { /* Dwarf2out needs location information. TODO: Moving this out of the streamer loop may noticealy improve ltrans linemap memory use. */ data_in->location_cache.apply_location_cache (); debug_hooks->type_decl (t, !DECL_FILE_SCOPE_P (t)); } if (!flag_ltrans) { /* Register variables and functions with the symbol table. */ if (TREE_CODE (t) == VAR_DECL) lto_register_var_decl_in_symtab (data_in, t, from + i); else if (TREE_CODE (t) == FUNCTION_DECL && !DECL_BUILT_IN (t)) lto_register_function_decl_in_symtab (data_in, t, from + i); /* Scan the tree for references to global functions or variables and record those for later fixup. */ if (mentions_vars_p (t)) vec_safe_push (tree_with_vars, t); } } if (seen_type) num_type_scc_trees += len; } else { /* Pickle stray references. */ t = lto_input_tree_1 (&ib_main, data_in, tag, 0); gcc_assert (t && data_in->reader_cache->nodes.length () == from); } } data_in->location_cache.apply_location_cache (); /* Read in lto_in_decl_state objects. */ data_ptr = (const uint32_t *) ((const char*) data + decl_offset); data_end = (const uint32_t *) ((const char*) data_ptr + header->decl_state_size); num_decl_states = *data_ptr++; gcc_assert (num_decl_states > 0); decl_data->global_decl_state = lto_new_in_decl_state (); data_ptr = lto_read_in_decl_state (data_in, data_ptr, decl_data->global_decl_state); /* Read in per-function decl states and enter them in hash table. */ decl_data->function_decl_states = hash_table<decl_state_hasher>::create_ggc (37); for (i = 1; i < num_decl_states; i++) { struct lto_in_decl_state *state = lto_new_in_decl_state (); data_ptr = lto_read_in_decl_state (data_in, data_ptr, state); lto_in_decl_state **slot = decl_data->function_decl_states->find_slot (state, INSERT); gcc_assert (*slot == NULL); *slot = state; } if (data_ptr != data_end) internal_error ("bytecode stream: garbage at the end of symbols section"); /* Set the current decl state to be the global state. */ decl_data->current_decl_state = decl_data->global_decl_state; lto_data_in_delete (data_in); } /* Custom version of strtoll, which is not portable. */ static int64_t lto_parse_hex (const char *p) { int64_t ret = 0; for (; *p != '\0'; ++p) { char c = *p; unsigned char part; ret <<= 4; if (c >= '0' && c <= '9') part = c - '0'; else if (c >= 'a' && c <= 'f') part = c - 'a' + 10; else if (c >= 'A' && c <= 'F') part = c - 'A' + 10; else internal_error ("could not parse hex number"); ret |= part; } return ret; } /* Read resolution for file named FILE_NAME. The resolution is read from RESOLUTION. */ static void lto_resolution_read (splay_tree file_ids, FILE *resolution, lto_file *file) { /* We require that objects in the resolution file are in the same order as the lto1 command line. */ unsigned int name_len; char *obj_name; unsigned int num_symbols; unsigned int i; struct lto_file_decl_data *file_data; splay_tree_node nd = NULL; if (!resolution) return; name_len = strlen (file->filename); obj_name = XNEWVEC (char, name_len + 1); fscanf (resolution, " "); /* Read white space. */ fread (obj_name, sizeof (char), name_len, resolution); obj_name[name_len] = '\0'; if (filename_cmp (obj_name, file->filename) != 0) internal_error ("unexpected file name %s in linker resolution file. " "Expected %s", obj_name, file->filename); if (file->offset != 0) { int t; char offset_p[17]; int64_t offset; t = fscanf (resolution, "@0x%16s", offset_p); if (t != 1) internal_error ("could not parse file offset"); offset = lto_parse_hex (offset_p); if (offset != file->offset) internal_error ("unexpected offset"); } free (obj_name); fscanf (resolution, "%u", &num_symbols); for (i = 0; i < num_symbols; i++) { int t; unsigned index; unsigned HOST_WIDE_INT id; char r_str[27]; enum ld_plugin_symbol_resolution r = (enum ld_plugin_symbol_resolution) 0; unsigned int j; unsigned int lto_resolution_str_len = sizeof (lto_resolution_str) / sizeof (char *); res_pair rp; t = fscanf (resolution, "%u " HOST_WIDE_INT_PRINT_HEX_PURE " %26s %*[^\n]\n", &index, &id, r_str); if (t != 3) internal_error ("invalid line in the resolution file"); for (j = 0; j < lto_resolution_str_len; j++) { if (strcmp (lto_resolution_str[j], r_str) == 0) { r = (enum ld_plugin_symbol_resolution) j; break; } } if (j == lto_resolution_str_len) internal_error ("invalid resolution in the resolution file"); if (!(nd && lto_splay_tree_id_equal_p (nd->key, id))) { nd = lto_splay_tree_lookup (file_ids, id); if (nd == NULL) internal_error ("resolution sub id %wx not in object file", id); } file_data = (struct lto_file_decl_data *)nd->value; /* The indexes are very sparse. To save memory save them in a compact format that is only unpacked later when the subfile is processed. */ rp.res = r; rp.index = index; file_data->respairs.safe_push (rp); if (file_data->max_index < index) file_data->max_index = index; } } /* List of file_decl_datas */ struct file_data_list { struct lto_file_decl_data *first, *last; }; /* Is the name for a id'ed LTO section? */ static int lto_section_with_id (const char *name, unsigned HOST_WIDE_INT *id) { const char *s; if (strncmp (name, section_name_prefix, strlen (section_name_prefix))) return 0; s = strrchr (name, '.'); return s && sscanf (s, "." HOST_WIDE_INT_PRINT_HEX_PURE, id) == 1; } /* Create file_data of each sub file id */ static int create_subid_section_table (struct lto_section_slot *ls, splay_tree file_ids, struct file_data_list *list) { struct lto_section_slot s_slot, *new_slot; unsigned HOST_WIDE_INT id; splay_tree_node nd; void **hash_slot; char *new_name; struct lto_file_decl_data *file_data; if (!lto_section_with_id (ls->name, &id)) return 1; /* Find hash table of sub module id */ nd = lto_splay_tree_lookup (file_ids, id); if (nd != NULL) { file_data = (struct lto_file_decl_data *)nd->value; } else { file_data = ggc_alloc<lto_file_decl_data> (); memset(file_data, 0, sizeof (struct lto_file_decl_data)); file_data->id = id; file_data->section_hash_table = lto_obj_create_section_hash_table ();; lto_splay_tree_insert (file_ids, id, file_data); /* Maintain list in linker order */ if (!list->first) list->first = file_data; if (list->last) list->last->next = file_data; list->last = file_data; } /* Copy section into sub module hash table */ new_name = XDUPVEC (char, ls->name, strlen (ls->name) + 1); s_slot.name = new_name; hash_slot = htab_find_slot (file_data->section_hash_table, &s_slot, INSERT); gcc_assert (*hash_slot == NULL); new_slot = XDUP (struct lto_section_slot, ls); new_slot->name = new_name; *hash_slot = new_slot; return 1; } /* Read declarations and other initializations for a FILE_DATA. */ static void lto_file_finalize (struct lto_file_decl_data *file_data, lto_file *file) { const char *data; size_t len; vec<ld_plugin_symbol_resolution_t> resolutions = vNULL; int i; res_pair *rp; /* Create vector for fast access of resolution. We do this lazily to save memory. */ resolutions.safe_grow_cleared (file_data->max_index + 1); for (i = 0; file_data->respairs.iterate (i, &rp); i++) resolutions[rp->index] = rp->res; file_data->respairs.release (); file_data->renaming_hash_table = lto_create_renaming_table (); file_data->file_name = file->filename; #ifdef ACCEL_COMPILER lto_input_mode_table (file_data); #else file_data->mode_table = lto_mode_identity_table; #endif data = lto_get_section_data (file_data, LTO_section_decls, NULL, &len); if (data == NULL) { internal_error ("cannot read LTO decls from %s", file_data->file_name); return; } /* Frees resolutions */ lto_read_decls (file_data, data, resolutions); lto_free_section_data (file_data, LTO_section_decls, NULL, data, len); } /* Finalize FILE_DATA in FILE and increase COUNT. */ static int lto_create_files_from_ids (lto_file *file, struct lto_file_decl_data *file_data, int *count) { lto_file_finalize (file_data, file); if (symtab->dump_file) fprintf (symtab->dump_file, "Creating file %s with sub id " HOST_WIDE_INT_PRINT_HEX "\n", file_data->file_name, file_data->id); (*count)++; return 0; } /* Generate a TREE representation for all types and external decls entities in FILE. Read all of the globals out of the file. Then read the cgraph and process the .o index into the cgraph nodes so that it can open the .o file to load the functions and ipa information. */ static struct lto_file_decl_data * lto_file_read (lto_file *file, FILE *resolution_file, int *count) { struct lto_file_decl_data *file_data = NULL; splay_tree file_ids; htab_t section_hash_table; struct lto_section_slot *section; struct file_data_list file_list; struct lto_section_list section_list; memset (&section_list, 0, sizeof (struct lto_section_list)); section_hash_table = lto_obj_build_section_table (file, &section_list); /* Find all sub modules in the object and put their sections into new hash tables in a splay tree. */ file_ids = lto_splay_tree_new (); memset (&file_list, 0, sizeof (struct file_data_list)); for (section = section_list.first; section != NULL; section = section->next) create_subid_section_table (section, file_ids, &file_list); /* Add resolutions to file ids */ lto_resolution_read (file_ids, resolution_file, file); /* Finalize each lto file for each submodule in the merged object */ for (file_data = file_list.first; file_data != NULL; file_data = file_data->next) lto_create_files_from_ids (file, file_data, count); splay_tree_delete (file_ids); htab_delete (section_hash_table); return file_list.first; } #if HAVE_MMAP_FILE && HAVE_SYSCONF && defined _SC_PAGE_SIZE #define LTO_MMAP_IO 1 #endif #if LTO_MMAP_IO /* Page size of machine is used for mmap and munmap calls. */ static size_t page_mask; #endif /* Get the section data of length LEN from FILENAME starting at OFFSET. The data segment must be freed by the caller when the caller is finished. Returns NULL if all was not well. */ static char * lto_read_section_data (struct lto_file_decl_data *file_data, intptr_t offset, size_t len) { char *result; static int fd = -1; static char *fd_name; #if LTO_MMAP_IO intptr_t computed_len; intptr_t computed_offset; intptr_t diff; #endif /* Keep a single-entry file-descriptor cache. The last file we touched will get closed at exit. ??? Eventually we want to add a more sophisticated larger cache or rather fix function body streaming to not stream them in practically random order. */ if (fd != -1 && filename_cmp (fd_name, file_data->file_name) != 0) { free (fd_name); close (fd); fd = -1; } if (fd == -1) { fd = open (file_data->file_name, O_RDONLY|O_BINARY); if (fd == -1) { fatal_error (input_location, "Cannot open %s", file_data->file_name); return NULL; } fd_name = xstrdup (file_data->file_name); } #if LTO_MMAP_IO if (!page_mask) { size_t page_size = sysconf (_SC_PAGE_SIZE); page_mask = ~(page_size - 1); } computed_offset = offset & page_mask; diff = offset - computed_offset; computed_len = len + diff; result = (char *) mmap (NULL, computed_len, PROT_READ, MAP_PRIVATE, fd, computed_offset); if (result == MAP_FAILED) { fatal_error (input_location, "Cannot map %s", file_data->file_name); return NULL; } return result + diff; #else result = (char *) xmalloc (len); if (lseek (fd, offset, SEEK_SET) != offset || read (fd, result, len) != (ssize_t) len) { free (result); fatal_error (input_location, "Cannot read %s", file_data->file_name); result = NULL; } #ifdef __MINGW32__ /* Native windows doesn't supports delayed unlink on opened file. So we close file here again. This produces higher I/O load, but at least it prevents to have dangling file handles preventing unlink. */ free (fd_name); fd_name = NULL; close (fd); fd = -1; #endif return result; #endif } /* Get the section data from FILE_DATA of SECTION_TYPE with NAME. NAME will be NULL unless the section type is for a function body. */ static const char * get_section_data (struct lto_file_decl_data *file_data, enum lto_section_type section_type, const char *name, size_t *len) { htab_t section_hash_table = file_data->section_hash_table; struct lto_section_slot *f_slot; struct lto_section_slot s_slot; const char *section_name = lto_get_section_name (section_type, name, file_data); char *data = NULL; *len = 0; s_slot.name = section_name; f_slot = (struct lto_section_slot *) htab_find (section_hash_table, &s_slot); if (f_slot) { data = lto_read_section_data (file_data, f_slot->start, f_slot->len); *len = f_slot->len; } free (CONST_CAST (char *, section_name)); return data; } /* Free the section data from FILE_DATA of SECTION_TYPE with NAME that starts at OFFSET and has LEN bytes. */ static void free_section_data (struct lto_file_decl_data *file_data ATTRIBUTE_UNUSED, enum lto_section_type section_type ATTRIBUTE_UNUSED, const char *name ATTRIBUTE_UNUSED, const char *offset, size_t len ATTRIBUTE_UNUSED) { #if LTO_MMAP_IO intptr_t computed_len; intptr_t computed_offset; intptr_t diff; #endif #if LTO_MMAP_IO computed_offset = ((intptr_t) offset) & page_mask; diff = (intptr_t) offset - computed_offset; computed_len = len + diff; munmap ((caddr_t) computed_offset, computed_len); #else free (CONST_CAST(char *, offset)); #endif } static lto_file *current_lto_file; /* Helper for qsort; compare partitions and return one with smaller size. We sort from greatest to smallest so parallel build doesn't stale on the longest compilation being executed too late. */ static int cmp_partitions_size (const void *a, const void *b) { const struct ltrans_partition_def *pa = *(struct ltrans_partition_def *const *)a; const struct ltrans_partition_def *pb = *(struct ltrans_partition_def *const *)b; return pb->insns - pa->insns; } /* Helper for qsort; compare partitions and return one with smaller order. */ static int cmp_partitions_order (const void *a, const void *b) { const struct ltrans_partition_def *pa = *(struct ltrans_partition_def *const *)a; const struct ltrans_partition_def *pb = *(struct ltrans_partition_def *const *)b; int ordera = -1, orderb = -1; if (lto_symtab_encoder_size (pa->encoder)) ordera = lto_symtab_encoder_deref (pa->encoder, 0)->order; if (lto_symtab_encoder_size (pb->encoder)) orderb = lto_symtab_encoder_deref (pb->encoder, 0)->order; return orderb - ordera; } /* Actually stream out ENCODER into TEMP_FILENAME. */ static void do_stream_out (char *temp_filename, lto_symtab_encoder_t encoder) { lto_file *file = lto_obj_file_open (temp_filename, true); if (!file) fatal_error (input_location, "lto_obj_file_open() failed"); lto_set_current_out_file (file); ipa_write_optimization_summaries (encoder); lto_set_current_out_file (NULL); lto_obj_file_close (file); free (file); } /* Wait for forked process and signal errors. */ #ifdef HAVE_WORKING_FORK static void wait_for_child () { int status; do { #ifndef WCONTINUED #define WCONTINUED 0 #endif int w = waitpid (0, &status, WUNTRACED | WCONTINUED); if (w == -1) fatal_error (input_location, "waitpid failed"); if (WIFEXITED (status) && WEXITSTATUS (status)) fatal_error (input_location, "streaming subprocess failed"); else if (WIFSIGNALED (status)) fatal_error (input_location, "streaming subprocess was killed by signal"); } while (!WIFEXITED (status) && !WIFSIGNALED (status)); } #endif /* Stream out ENCODER into TEMP_FILENAME Fork if that seems to help. */ static void stream_out (char *temp_filename, lto_symtab_encoder_t encoder, bool ARG_UNUSED (last)) { #ifdef HAVE_WORKING_FORK static int nruns; if (lto_parallelism <= 1) { do_stream_out (temp_filename, encoder); return; } /* Do not run more than LTO_PARALLELISM streamings FIXME: we ignore limits on jobserver. */ if (lto_parallelism > 0 && nruns >= lto_parallelism) { wait_for_child (); nruns --; } /* If this is not the last parallel partition, execute new streaming process. */ if (!last) { pid_t cpid = fork (); if (!cpid) { setproctitle ("lto1-wpa-streaming"); do_stream_out (temp_filename, encoder); exit (0); } /* Fork failed; lets do the job ourseleves. */ else if (cpid == -1) do_stream_out (temp_filename, encoder); else nruns++; } /* Last partition; stream it and wait for all children to die. */ else { int i; do_stream_out (temp_filename, encoder); for (i = 0; i < nruns; i++) wait_for_child (); } asm_nodes_output = true; #else do_stream_out (temp_filename, encoder); #endif } /* Write all output files in WPA mode and the file with the list of LTRANS units. */ static void lto_wpa_write_files (void) { unsigned i, n_sets; ltrans_partition part; FILE *ltrans_output_list_stream; char *temp_filename; vec <char *>temp_filenames = vNULL; size_t blen; /* Open the LTRANS output list. */ if (!ltrans_output_list) fatal_error (input_location, "no LTRANS output list filename provided"); timevar_push (TV_WHOPR_WPA); FOR_EACH_VEC_ELT (ltrans_partitions, i, part) lto_stats.num_output_symtab_nodes += lto_symtab_encoder_size (part->encoder); timevar_pop (TV_WHOPR_WPA); timevar_push (TV_WHOPR_WPA_IO); /* Generate a prefix for the LTRANS unit files. */ blen = strlen (ltrans_output_list); temp_filename = (char *) xmalloc (blen + sizeof ("2147483648.o")); strcpy (temp_filename, ltrans_output_list); if (blen > sizeof (".out") && strcmp (temp_filename + blen - sizeof (".out") + 1, ".out") == 0) temp_filename[blen - sizeof (".out") + 1] = '\0'; blen = strlen (temp_filename); n_sets = ltrans_partitions.length (); /* Sort partitions by size so small ones are compiled last. FIXME: Even when not reordering we may want to output one list for parallel make and other for final link command. */ if (!flag_profile_reorder_functions || !flag_profile_use) ltrans_partitions.qsort (flag_toplevel_reorder ? cmp_partitions_size : cmp_partitions_order); for (i = 0; i < n_sets; i++) { ltrans_partition part = ltrans_partitions[i]; /* Write all the nodes in SET. */ sprintf (temp_filename + blen, "%u.o", i); if (!quiet_flag) fprintf (stderr, " %s (%s %i insns)", temp_filename, part->name, part->insns); if (symtab->dump_file) { lto_symtab_encoder_iterator lsei; fprintf (symtab->dump_file, "Writing partition %s to file %s, %i insns\n", part->name, temp_filename, part->insns); fprintf (symtab->dump_file, " Symbols in partition: "); for (lsei = lsei_start_in_partition (part->encoder); !lsei_end_p (lsei); lsei_next_in_partition (&lsei)) { symtab_node *node = lsei_node (lsei); fprintf (symtab->dump_file, "%s ", node->asm_name ()); } fprintf (symtab->dump_file, "\n Symbols in boundary: "); for (lsei = lsei_start (part->encoder); !lsei_end_p (lsei); lsei_next (&lsei)) { symtab_node *node = lsei_node (lsei); if (!lto_symtab_encoder_in_partition_p (part->encoder, node)) { fprintf (symtab->dump_file, "%s ", node->asm_name ()); cgraph_node *cnode = dyn_cast <cgraph_node *> (node); if (cnode && lto_symtab_encoder_encode_body_p (part->encoder, cnode)) fprintf (symtab->dump_file, "(body included)"); else { varpool_node *vnode = dyn_cast <varpool_node *> (node); if (vnode && lto_symtab_encoder_encode_initializer_p (part->encoder, vnode)) fprintf (symtab->dump_file, "(initializer included)"); } } } fprintf (symtab->dump_file, "\n"); } gcc_checking_assert (lto_symtab_encoder_size (part->encoder) || !i); stream_out (temp_filename, part->encoder, i == n_sets - 1); part->encoder = NULL; temp_filenames.safe_push (xstrdup (temp_filename)); } ltrans_output_list_stream = fopen (ltrans_output_list, "w"); if (ltrans_output_list_stream == NULL) fatal_error (input_location, "opening LTRANS output list %s: %m", ltrans_output_list); for (i = 0; i < n_sets; i++) { unsigned int len = strlen (temp_filenames[i]); if (fwrite (temp_filenames[i], 1, len, ltrans_output_list_stream) < len || fwrite ("\n", 1, 1, ltrans_output_list_stream) < 1) fatal_error (input_location, "writing to LTRANS output list %s: %m", ltrans_output_list); free (temp_filenames[i]); } temp_filenames.release(); lto_stats.num_output_files += n_sets; /* Close the LTRANS output list. */ if (fclose (ltrans_output_list_stream)) fatal_error (input_location, "closing LTRANS output list %s: %m", ltrans_output_list); free_ltrans_partitions(); free (temp_filename); timevar_pop (TV_WHOPR_WPA_IO); } /* If TT is a variable or function decl replace it with its prevailing variant. */ #define LTO_SET_PREVAIL(tt) \ do {\ if ((tt) && VAR_OR_FUNCTION_DECL_P (tt) \ && (TREE_PUBLIC (tt) || DECL_EXTERNAL (tt))) \ { \ tt = lto_symtab_prevailing_decl (tt); \ fixed = true; \ } \ } while (0) /* Ensure that TT isn't a replacable var of function decl. */ #define LTO_NO_PREVAIL(tt) \ gcc_assert (!(tt) || !VAR_OR_FUNCTION_DECL_P (tt)) /* Given a tree T replace all fields referring to variables or functions with their prevailing variant. */ static void lto_fixup_prevailing_decls (tree t) { enum tree_code code = TREE_CODE (t); bool fixed = false; gcc_checking_assert (code != TREE_BINFO); LTO_NO_PREVAIL (TREE_TYPE (t)); if (CODE_CONTAINS_STRUCT (code, TS_COMMON)) LTO_NO_PREVAIL (TREE_CHAIN (t)); if (DECL_P (t)) { LTO_NO_PREVAIL (DECL_NAME (t)); LTO_SET_PREVAIL (DECL_CONTEXT (t)); if (CODE_CONTAINS_STRUCT (code, TS_DECL_COMMON)) { LTO_SET_PREVAIL (DECL_SIZE (t)); LTO_SET_PREVAIL (DECL_SIZE_UNIT (t)); LTO_SET_PREVAIL (DECL_INITIAL (t)); LTO_NO_PREVAIL (DECL_ATTRIBUTES (t)); LTO_SET_PREVAIL (DECL_ABSTRACT_ORIGIN (t)); } if (CODE_CONTAINS_STRUCT (code, TS_DECL_WITH_VIS)) { LTO_NO_PREVAIL (t->decl_with_vis.assembler_name); } if (CODE_CONTAINS_STRUCT (code, TS_DECL_NON_COMMON)) { LTO_NO_PREVAIL (DECL_RESULT_FLD (t)); } if (CODE_CONTAINS_STRUCT (code, TS_FUNCTION_DECL)) { LTO_NO_PREVAIL (DECL_ARGUMENTS (t)); LTO_SET_PREVAIL (DECL_FUNCTION_PERSONALITY (t)); LTO_NO_PREVAIL (DECL_VINDEX (t)); } if (CODE_CONTAINS_STRUCT (code, TS_FIELD_DECL)) { LTO_SET_PREVAIL (DECL_FIELD_OFFSET (t)); LTO_NO_PREVAIL (DECL_BIT_FIELD_TYPE (t)); LTO_NO_PREVAIL (DECL_QUALIFIER (t)); LTO_NO_PREVAIL (DECL_FIELD_BIT_OFFSET (t)); LTO_NO_PREVAIL (DECL_FCONTEXT (t)); } } else if (TYPE_P (t)) { LTO_NO_PREVAIL (TYPE_CACHED_VALUES (t)); LTO_SET_PREVAIL (TYPE_SIZE (t)); LTO_SET_PREVAIL (TYPE_SIZE_UNIT (t)); LTO_NO_PREVAIL (TYPE_ATTRIBUTES (t)); LTO_NO_PREVAIL (TYPE_NAME (t)); LTO_SET_PREVAIL (TYPE_MINVAL (t)); LTO_SET_PREVAIL (TYPE_MAXVAL (t)); LTO_NO_PREVAIL (t->type_non_common.binfo); LTO_SET_PREVAIL (TYPE_CONTEXT (t)); LTO_NO_PREVAIL (TYPE_CANONICAL (t)); LTO_NO_PREVAIL (TYPE_MAIN_VARIANT (t)); LTO_NO_PREVAIL (TYPE_NEXT_VARIANT (t)); } else if (EXPR_P (t)) { int i; for (i = TREE_OPERAND_LENGTH (t) - 1; i >= 0; --i) LTO_SET_PREVAIL (TREE_OPERAND (t, i)); } else if (TREE_CODE (t) == CONSTRUCTOR) { unsigned i; tree val; FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), i, val) LTO_SET_PREVAIL (val); } else { switch (code) { case TREE_LIST: LTO_SET_PREVAIL (TREE_VALUE (t)); LTO_SET_PREVAIL (TREE_PURPOSE (t)); LTO_NO_PREVAIL (TREE_PURPOSE (t)); break; default: gcc_unreachable (); } } /* If we fixed nothing, then we missed something seen by mentions_vars_p. */ gcc_checking_assert (fixed); } #undef LTO_SET_PREVAIL #undef LTO_NO_PREVAIL /* Helper function of lto_fixup_decls. Walks the var and fn streams in STATE, replaces var and function decls with the corresponding prevailing def. */ static void lto_fixup_state (struct lto_in_decl_state *state) { unsigned i, si; /* Although we only want to replace FUNCTION_DECLs and VAR_DECLs, we still need to walk from all DECLs to find the reachable FUNCTION_DECLs and VAR_DECLs. */ for (si = 0; si < LTO_N_DECL_STREAMS; si++) { vec<tree, va_gc> *trees = state->streams[si]; for (i = 0; i < vec_safe_length (trees); i++) { tree t = (*trees)[i]; if (VAR_OR_FUNCTION_DECL_P (t) && (TREE_PUBLIC (t) || DECL_EXTERNAL (t))) (*trees)[i] = lto_symtab_prevailing_decl (t); } } } /* Fix the decls from all FILES. Replaces each decl with the corresponding prevailing one. */ static void lto_fixup_decls (struct lto_file_decl_data **files) { unsigned int i; tree t; if (tree_with_vars) FOR_EACH_VEC_ELT ((*tree_with_vars), i, t) lto_fixup_prevailing_decls (t); for (i = 0; files[i]; i++) { struct lto_file_decl_data *file = files[i]; struct lto_in_decl_state *state = file->global_decl_state; lto_fixup_state (state); hash_table<decl_state_hasher>::iterator iter; lto_in_decl_state *elt; FOR_EACH_HASH_TABLE_ELEMENT (*file->function_decl_states, elt, lto_in_decl_state *, iter) lto_fixup_state (elt); } } static GTY((length ("lto_stats.num_input_files + 1"))) struct lto_file_decl_data **all_file_decl_data; /* Turn file datas for sub files into a single array, so that they look like separate files for further passes. */ static void lto_flatten_files (struct lto_file_decl_data **orig, int count, int last_file_ix) { struct lto_file_decl_data *n, *next; int i, k; lto_stats.num_input_files = count; all_file_decl_data = ggc_cleared_vec_alloc<lto_file_decl_data_ptr> (count + 1); /* Set the hooks so that all of the ipa passes can read in their data. */ lto_set_in_hooks (all_file_decl_data, get_section_data, free_section_data); for (i = 0, k = 0; i < last_file_ix; i++) { for (n = orig[i]; n != NULL; n = next) { all_file_decl_data[k++] = n; next = n->next; n->next = NULL; } } all_file_decl_data[k] = NULL; gcc_assert (k == count); } /* Input file data before flattening (i.e. splitting them to subfiles to support incremental linking. */ static int real_file_count; static GTY((length ("real_file_count + 1"))) struct lto_file_decl_data **real_file_decl_data; static void print_lto_report_1 (void); /* Read all the symbols from the input files FNAMES. NFILES is the number of files requested in the command line. Instantiate a global call graph by aggregating all the sub-graphs found in each file. */ static void read_cgraph_and_symbols (unsigned nfiles, const char **fnames) { unsigned int i, last_file_ix; FILE *resolution; int count = 0; struct lto_file_decl_data **decl_data; symtab_node *snode; symtab->initialize (); timevar_push (TV_IPA_LTO_DECL_IN); #ifdef ACCEL_COMPILER section_name_prefix = OFFLOAD_SECTION_NAME_PREFIX; lto_stream_offload_p = true; #endif real_file_decl_data = decl_data = ggc_cleared_vec_alloc<lto_file_decl_data_ptr> (nfiles + 1); real_file_count = nfiles; /* Read the resolution file. */ resolution = NULL; if (resolution_file_name) { int t; unsigned num_objects; resolution = fopen (resolution_file_name, "r"); if (resolution == NULL) fatal_error (input_location, "could not open symbol resolution file: %m"); t = fscanf (resolution, "%u", &num_objects); gcc_assert (t == 1); /* True, since the plugin splits the archives. */ gcc_assert (num_objects == nfiles); } symtab->state = LTO_STREAMING; canonical_type_hash_cache = new hash_map<const_tree, hashval_t> (251); gimple_canonical_types = htab_create (16381, gimple_canonical_type_hash, gimple_canonical_type_eq, NULL); gcc_obstack_init (&tree_scc_hash_obstack); tree_scc_hash = new hash_table<tree_scc_hasher> (4096); /* Register the common node types with the canonical type machinery so we properly share alias-sets across languages and TUs. Do not expose the common nodes as type merge target - those that should be are already exposed so by pre-loading the LTO streamer caches. Do two passes - first clear TYPE_CANONICAL and then re-compute it. */ for (i = 0; i < itk_none; ++i) lto_register_canonical_types (integer_types[i], true); for (i = 0; i < stk_type_kind_last; ++i) lto_register_canonical_types (sizetype_tab[i], true); for (i = 0; i < TI_MAX; ++i) lto_register_canonical_types (global_trees[i], true); for (i = 0; i < itk_none; ++i) lto_register_canonical_types (integer_types[i], false); for (i = 0; i < stk_type_kind_last; ++i) lto_register_canonical_types (sizetype_tab[i], false); for (i = 0; i < TI_MAX; ++i) lto_register_canonical_types (global_trees[i], false); if (!quiet_flag) fprintf (stderr, "Reading object files:"); /* Read all of the object files specified on the command line. */ for (i = 0, last_file_ix = 0; i < nfiles; ++i) { struct lto_file_decl_data *file_data = NULL; if (!quiet_flag) { fprintf (stderr, " %s", fnames[i]); fflush (stderr); } current_lto_file = lto_obj_file_open (fnames[i], false); if (!current_lto_file) break; file_data = lto_file_read (current_lto_file, resolution, &count); if (!file_data) { lto_obj_file_close (current_lto_file); free (current_lto_file); current_lto_file = NULL; break; } decl_data[last_file_ix++] = file_data; lto_obj_file_close (current_lto_file); free (current_lto_file); current_lto_file = NULL; } lto_flatten_files (decl_data, count, last_file_ix); lto_stats.num_input_files = count; ggc_free(decl_data); real_file_decl_data = NULL; if (resolution_file_name) fclose (resolution); /* Show the LTO report before launching LTRANS. */ if (flag_lto_report || (flag_wpa && flag_lto_report_wpa)) print_lto_report_1 (); /* Free gimple type merging datastructures. */ delete tree_scc_hash; tree_scc_hash = NULL; obstack_free (&tree_scc_hash_obstack, NULL); htab_delete (gimple_canonical_types); gimple_canonical_types = NULL; delete canonical_type_hash_cache; canonical_type_hash_cache = NULL; /* At this stage we know that majority of GGC memory is reachable. Growing the limits prevents unnecesary invocation of GGC. */ ggc_grow (); ggc_collect (); /* Set the hooks so that all of the ipa passes can read in their data. */ lto_set_in_hooks (all_file_decl_data, get_section_data, free_section_data); timevar_pop (TV_IPA_LTO_DECL_IN); if (!quiet_flag) fprintf (stderr, "\nReading the callgraph\n"); timevar_push (TV_IPA_LTO_CGRAPH_IO); /* Read the symtab. */ input_symtab (); input_offload_tables (); /* Store resolutions into the symbol table. */ ld_plugin_symbol_resolution_t *res; FOR_EACH_SYMBOL (snode) if (snode->real_symbol_p () && snode->lto_file_data && snode->lto_file_data->resolution_map && (res = snode->lto_file_data->resolution_map->get (snode->decl))) snode->resolution = *res; for (i = 0; all_file_decl_data[i]; i++) if (all_file_decl_data[i]->resolution_map) { delete all_file_decl_data[i]->resolution_map; all_file_decl_data[i]->resolution_map = NULL; } timevar_pop (TV_IPA_LTO_CGRAPH_IO); if (!quiet_flag) fprintf (stderr, "Merging declarations\n"); timevar_push (TV_IPA_LTO_DECL_MERGE); /* Merge global decls. In ltrans mode we read merged cgraph, we do not need to care about resolving symbols again, we only need to replace duplicated declarations read from the callgraph and from function sections. */ if (!flag_ltrans) { lto_symtab_merge_decls (); /* If there were errors during symbol merging bail out, we have no good way to recover here. */ if (seen_error ()) fatal_error (input_location, "errors during merging of translation units"); /* Fixup all decls. */ lto_fixup_decls (all_file_decl_data); } if (tree_with_vars) ggc_free (tree_with_vars); tree_with_vars = NULL; ggc_collect (); timevar_pop (TV_IPA_LTO_DECL_MERGE); /* Each pass will set the appropriate timer. */ if (!quiet_flag) fprintf (stderr, "Reading summaries\n"); /* Read the IPA summary data. */ if (flag_ltrans) ipa_read_optimization_summaries (); else ipa_read_summaries (); for (i = 0; all_file_decl_data[i]; i++) { gcc_assert (all_file_decl_data[i]->symtab_node_encoder); lto_symtab_encoder_delete (all_file_decl_data[i]->symtab_node_encoder); all_file_decl_data[i]->symtab_node_encoder = NULL; lto_free_function_in_decl_state (all_file_decl_data[i]->global_decl_state); all_file_decl_data[i]->global_decl_state = NULL; all_file_decl_data[i]->current_decl_state = NULL; } /* Finally merge the cgraph according to the decl merging decisions. */ timevar_push (TV_IPA_LTO_CGRAPH_MERGE); if (symtab->dump_file) { fprintf (symtab->dump_file, "Before merging:\n"); symtab_node::dump_table (symtab->dump_file); } if (!flag_ltrans) { lto_symtab_merge_symbols (); /* Removal of unreachable symbols is needed to make verify_symtab to pass; we are still having duplicated comdat groups containing local statics. We could also just remove them while merging. */ symtab->remove_unreachable_nodes (dump_file); } ggc_collect (); symtab->state = IPA_SSA; /* FIXME: Technically all node removals happening here are useless, because WPA should not stream them. */ if (flag_ltrans) symtab->remove_unreachable_nodes (dump_file); timevar_pop (TV_IPA_LTO_CGRAPH_MERGE); /* Indicate that the cgraph is built and ready. */ symtab->function_flags_ready = true; ggc_free (all_file_decl_data); all_file_decl_data = NULL; } /* Materialize all the bodies for all the nodes in the callgraph. */ static void materialize_cgraph (void) { struct cgraph_node *node; timevar_id_t lto_timer; if (!quiet_flag) fprintf (stderr, flag_wpa ? "Materializing decls:" : "Reading function bodies:"); FOR_EACH_FUNCTION (node) { if (node->lto_file_data) { lto_materialize_function (node); lto_stats.num_input_cgraph_nodes++; } } /* Start the appropriate timer depending on the mode that we are operating in. */ lto_timer = (flag_wpa) ? TV_WHOPR_WPA : (flag_ltrans) ? TV_WHOPR_LTRANS : TV_LTO; timevar_push (lto_timer); current_function_decl = NULL; set_cfun (NULL); if (!quiet_flag) fprintf (stderr, "\n"); timevar_pop (lto_timer); } /* Show various memory usage statistics related to LTO. */ static void print_lto_report_1 (void) { const char *pfx = (flag_lto) ? "LTO" : (flag_wpa) ? "WPA" : "LTRANS"; fprintf (stderr, "%s statistics\n", pfx); fprintf (stderr, "[%s] read %lu SCCs of average size %f\n", pfx, num_sccs_read, total_scc_size / (double)num_sccs_read); fprintf (stderr, "[%s] %lu tree bodies read in total\n", pfx, total_scc_size); if (flag_wpa && tree_scc_hash) { fprintf (stderr, "[%s] tree SCC table: size %ld, %ld elements, " "collision ratio: %f\n", pfx, (long) tree_scc_hash->size (), (long) tree_scc_hash->elements (), tree_scc_hash->collisions ()); hash_table<tree_scc_hasher>::iterator hiter; tree_scc *scc, *max_scc = NULL; unsigned max_length = 0; FOR_EACH_HASH_TABLE_ELEMENT (*tree_scc_hash, scc, x, hiter) { unsigned length = 0; tree_scc *s = scc; for (; s; s = s->next) length++; if (length > max_length) { max_length = length; max_scc = scc; } } fprintf (stderr, "[%s] tree SCC max chain length %u (size %u)\n", pfx, max_length, max_scc->len); fprintf (stderr, "[%s] Compared %lu SCCs, %lu collisions (%f)\n", pfx, num_scc_compares, num_scc_compare_collisions, num_scc_compare_collisions / (double) num_scc_compares); fprintf (stderr, "[%s] Merged %lu SCCs\n", pfx, num_sccs_merged); fprintf (stderr, "[%s] Merged %lu tree bodies\n", pfx, total_scc_size_merged); fprintf (stderr, "[%s] Merged %lu types\n", pfx, num_merged_types); fprintf (stderr, "[%s] %lu types prevailed (%lu associated trees)\n", pfx, num_prevailing_types, num_type_scc_trees); fprintf (stderr, "[%s] GIMPLE canonical type table: size %ld, " "%ld elements, %ld searches, %ld collisions (ratio: %f)\n", pfx, (long) htab_size (gimple_canonical_types), (long) htab_elements (gimple_canonical_types), (long) gimple_canonical_types->searches, (long) gimple_canonical_types->collisions, htab_collisions (gimple_canonical_types)); fprintf (stderr, "[%s] GIMPLE canonical type pointer-map: " "%lu elements, %ld searches\n", pfx, num_canonical_type_hash_entries, num_canonical_type_hash_queries); } print_lto_report (pfx); } /* Perform whole program analysis (WPA) on the callgraph and write out the optimization plan. */ static void do_whole_program_analysis (void) { symtab_node *node; lto_parallelism = 1; /* TODO: jobserver communicatoin is not supported, yet. */ if (!strcmp (flag_wpa, "jobserver")) lto_parallelism = -1; else { lto_parallelism = atoi (flag_wpa); if (lto_parallelism <= 0) lto_parallelism = 0; } timevar_start (TV_PHASE_OPT_GEN); /* Note that since we are in WPA mode, materialize_cgraph will not actually read in all the function bodies. It only materializes the decls and cgraph nodes so that analysis can be performed. */ materialize_cgraph (); /* Reading in the cgraph uses different timers, start timing WPA now. */ timevar_push (TV_WHOPR_WPA); if (pre_ipa_mem_report) { fprintf (stderr, "Memory consumption before IPA\n"); dump_memory_report (false); } symtab->function_flags_ready = true; if (symtab->dump_file) symtab_node::dump_table (symtab->dump_file); bitmap_obstack_initialize (NULL); symtab->state = IPA_SSA; execute_ipa_pass_list (g->get_passes ()->all_regular_ipa_passes); if (symtab->dump_file) { fprintf (symtab->dump_file, "Optimized "); symtab_node::dump_table (symtab->dump_file); } #ifdef ENABLE_CHECKING symtab_node::verify_symtab_nodes (); #endif bitmap_obstack_release (NULL); /* We are about to launch the final LTRANS phase, stop the WPA timer. */ timevar_pop (TV_WHOPR_WPA); timevar_push (TV_WHOPR_PARTITIONING); if (flag_lto_partition == LTO_PARTITION_1TO1) lto_1_to_1_map (); else if (flag_lto_partition == LTO_PARTITION_MAX) lto_max_map (); else if (flag_lto_partition == LTO_PARTITION_ONE) lto_balanced_map (1); else if (flag_lto_partition == LTO_PARTITION_BALANCED) lto_balanced_map (PARAM_VALUE (PARAM_LTO_PARTITIONS)); else gcc_unreachable (); /* Inline summaries are needed for balanced partitioning. Free them now so the memory can be used for streamer caches. */ inline_free_summary (); /* AUX pointers are used by partitioning code to bookkeep number of partitions symbol is in. This is no longer needed. */ FOR_EACH_SYMBOL (node) node->aux = NULL; lto_stats.num_cgraph_partitions += ltrans_partitions.length (); /* Find out statics that need to be promoted to globals with hidden visibility because they are accessed from multiple partitions. */ lto_promote_cross_file_statics (); timevar_pop (TV_WHOPR_PARTITIONING); timevar_stop (TV_PHASE_OPT_GEN); /* Collect a last time - in lto_wpa_write_files we may end up forking with the idea that this doesn't increase memory usage. So we absoultely do not want to collect after that. */ ggc_collect (); timevar_start (TV_PHASE_STREAM_OUT); if (!quiet_flag) { fprintf (stderr, "\nStreaming out"); fflush (stderr); } lto_wpa_write_files (); if (!quiet_flag) fprintf (stderr, "\n"); timevar_stop (TV_PHASE_STREAM_OUT); if (post_ipa_mem_report) { fprintf (stderr, "Memory consumption after IPA\n"); dump_memory_report (false); } /* Show the LTO report before launching LTRANS. */ if (flag_lto_report || (flag_wpa && flag_lto_report_wpa)) print_lto_report_1 (); if (mem_report_wpa) dump_memory_report (true); } static GTY(()) tree lto_eh_personality_decl; /* Return the LTO personality function decl. */ tree lto_eh_personality (void) { if (!lto_eh_personality_decl) { /* Use the first personality DECL for our personality if we don't support multiple ones. This ensures that we don't artificially create the need for them in a single-language program. */ if (first_personality_decl && !dwarf2out_do_cfi_asm ()) lto_eh_personality_decl = first_personality_decl; else lto_eh_personality_decl = lhd_gcc_personality (); } return lto_eh_personality_decl; } /* Set the process name based on the LTO mode. */ static void lto_process_name (void) { if (flag_lto) setproctitle ("lto1-lto"); if (flag_wpa) setproctitle ("lto1-wpa"); if (flag_ltrans) setproctitle ("lto1-ltrans"); } /* Initialize the LTO front end. */ static void lto_init (void) { lto_process_name (); lto_streamer_hooks_init (); lto_reader_init (); lto_set_in_hooks (NULL, get_section_data, free_section_data); memset (&lto_stats, 0, sizeof (lto_stats)); bitmap_obstack_initialize (NULL); gimple_register_cfg_hooks (); #ifndef ACCEL_COMPILER unsigned char *table = ggc_vec_alloc<unsigned char> (MAX_MACHINE_MODE); for (int m = 0; m < MAX_MACHINE_MODE; m++) table[m] = m; lto_mode_identity_table = table; #endif } /* Main entry point for the GIMPLE front end. This front end has three main personalities: - LTO (-flto). All the object files on the command line are loaded in memory and processed as a single translation unit. This is the traditional link-time optimization behavior. - WPA (-fwpa). Only the callgraph and summary information for files in the command file are loaded. A single callgraph (without function bodies) is instantiated for the whole set of files. IPA passes are only allowed to analyze the call graph and make transformation decisions. The callgraph is partitioned, each partition is written to a new object file together with the transformation decisions. - LTRANS (-fltrans). Similar to -flto but it prevents the IPA summary files from running again. Since WPA computed summary information and decided what transformations to apply, LTRANS simply applies them. */ void lto_main (void) { /* LTO is called as a front end, even though it is not a front end. Because it is called as a front end, TV_PHASE_PARSING and TV_PARSE_GLOBAL are active, and we need to turn them off while doing LTO. Later we turn them back on so they are active up in toplev.c. */ timevar_pop (TV_PARSE_GLOBAL); timevar_stop (TV_PHASE_PARSING); timevar_start (TV_PHASE_SETUP); /* Initialize the LTO front end. */ lto_init (); timevar_stop (TV_PHASE_SETUP); timevar_start (TV_PHASE_STREAM_IN); /* Read all the symbols and call graph from all the files in the command line. */ read_cgraph_and_symbols (num_in_fnames, in_fnames); timevar_stop (TV_PHASE_STREAM_IN); if (!seen_error ()) { /* If WPA is enabled analyze the whole call graph and create an optimization plan. Otherwise, read in all the function bodies and continue with optimization. */ if (flag_wpa) do_whole_program_analysis (); else { timevar_start (TV_PHASE_OPT_GEN); materialize_cgraph (); if (!flag_ltrans) lto_promote_statics_nonwpa (); /* Let the middle end know that we have read and merged all of the input files. */ symtab->compile (); timevar_stop (TV_PHASE_OPT_GEN); /* FIXME lto, if the processes spawned by WPA fail, we miss the chance to print WPA's report, so WPA will call print_lto_report before launching LTRANS. If LTRANS was launched directly by the driver we would not need to do this. */ if (flag_lto_report || (flag_wpa && flag_lto_report_wpa)) print_lto_report_1 (); } } /* Here we make LTO pretend to be a parser. */ timevar_start (TV_PHASE_PARSING); timevar_push (TV_PARSE_GLOBAL); } #include "gt-lto-lto.h"
apc-llc/gcc-5.1.1-knc
gcc/lto/lto.c
C
gpl-2.0
103,409
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Service * @subpackage DeveloperGarden * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: SearchParameters.php 24593 2012-01-05 20:35:02Z matthew $ */ /** * @category Zend * @package Zend_Service * @subpackage DeveloperGarden * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @author Marco Kaiser * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Service_DeveloperGarden_LocalSearch_SearchParameters { /** * possible search parameters, incl. default values * * @var array */ private $_parameters = array( 'what' => null, 'dymwhat' => null, 'dymrelated' => null, 'hits' => null, 'collapse' => null, 'where' => null, 'dywhere' => null, 'radius' => null, 'lx' => null, 'ly' => null, 'rx' => null, 'ry' => null, 'transformgeocode' => null, 'sort' => null, 'spatial' => null, 'sepcomm' => null, 'filter' => null, // can be ONLINER or OFFLINER 'openingtime' => null, // can be now or HH::MM 'kategorie' => null, // @see http://www.suchen.de/kategorie-katalog 'site' => null, 'typ' => null, 'name' => null, 'page' => null, 'city' => null, 'plz' => null, 'strasse' => null, 'bundesland' => null, ); /** * possible collapse values * * @var array */ private $_possibleCollapseValues = array( true, false, 'ADDRESS_COMPANY', 'DOMAIN' ); /** * sets a new search word * alias for setWhat * * @param string $searchValue * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setSearchValue($searchValue) { return $this->setWhat($searchValue); } /** * sets a new search word * * @param string $searchValue * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setWhat($searchValue) { $this->_parameters['what'] = $searchValue; return $this; } /** * enable the did you mean what feature * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function enableDidYouMeanWhat() { $this->_parameters['dymwhat'] = 'true'; return $this; } /** * disable the did you mean what feature * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function disableDidYouMeanWhat() { $this->_parameters['dymwhat'] = 'false'; return $this; } /** * enable the did you mean where feature * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function enableDidYouMeanWhere() { $this->_parameters['dymwhere'] = 'true'; return $this; } /** * disable the did you mean where feature * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function disableDidYouMeanWhere() { $this->_parameters['dymwhere'] = 'false'; return $this; } /** * enable did you mean related, if true Kihno will be corrected to Kino * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function enableDidYouMeanRelated() { $this->_parameters['dymrelated'] = 'true'; return $this; } /** * diable did you mean related, if false Kihno will not be corrected to Kino * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function disableDidYouMeanRelated() { $this->_parameters['dymrelated'] = 'true'; return $this; } /** * set the max result hits for this search * * @param integer $hits * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setHits($hits = 10) { #require_once 'Zend/Validate/Between.php'; $validator = new Zend_Validate_Between(0, 1000); if (!$validator->isValid($hits)) { $message = $validator->getMessages(); #require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new Zend_Service_DeveloperGarden_LocalSearch_Exception(current($message)); } $this->_parameters['hits'] = $hits; return $this; } /** * If true, addresses will be collapsed for a single domain, common values * are: * ADDRESS_COMPANY – to collapse by address * DOMAIN – to collapse by domain (same like collapse=true) * false * * @param mixed $value * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setCollapse($value) { if (!in_array($value, $this->_possibleCollapseValues, true)) { #require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new Zend_Service_DeveloperGarden_LocalSearch_Exception('Not a valid value provided.'); } $this->_parameters['collapse'] = $value; return $this; } /** * set a specific search location * examples: * +47°54’53.10”, 11° 10’ 56.76” * 47°54’53.10;11°10’56.76” * 47.914750,11.182533 * +47.914750 ; +11.1824 * Darmstadt * Berlin * * @param string $where * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setWhere($where) { #require_once 'Zend/Validate/NotEmpty.php'; $validator = new Zend_Validate_NotEmpty(); if (!$validator->isValid($where)) { $message = $validator->getMessages(); #require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new Zend_Service_DeveloperGarden_LocalSearch_Exception(current($message)); } $this->_parameters['where'] = $where; return $this; } /** * returns the defined search location (ie city, country) * * @return string */ public function getWhere() { return $this->_parameters['where']; } /** * enable the spatial search feature * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function enableSpatial() { $this->_parameters['spatial'] = 'true'; return $this; } /** * disable the spatial search feature * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function disableSpatial() { $this->_parameters['spatial'] = 'false'; return $this; } /** * sets spatial and the given radius for a circle search * * @param integer $radius * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setRadius($radius) { #require_once 'Zend/Validate/Int.php'; $validator = new Zend_Validate_Int(); if (!$validator->isValid($radius)) { $message = $validator->getMessages(); #require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new Zend_Service_DeveloperGarden_LocalSearch_Exception(current($message)); } $this->_parameters['radius'] = $radius; $this->_parameters['transformgeocode'] = 'false'; return $this; } /** * sets the values for a rectangle search * lx = longitude left top * ly = latitude left top * rx = longitude right bottom * ry = latitude right bottom * * @param float $lx * @param float $ly * @param float $rx * @param float $ry * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setRectangle($lx, $ly, $rx, $ry) { $this->_parameters['lx'] = $lx; $this->_parameters['ly'] = $ly; $this->_parameters['rx'] = $rx; $this->_parameters['ry'] = $ry; return $this; } /** * if set, the service returns the zipcode for the result * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setTransformGeoCode() { $this->_parameters['transformgeocode'] = 'true'; $this->_parameters['radius'] = null; return $this; } /** * sets the sort value * possible values are: 'relevance' and 'distance' (only with spatial enabled) * * @param string $sort * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setSort($sort) { if (!in_array($sort, array('relevance', 'distance'))) { #require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php'; throw new Zend_Service_DeveloperGarden_LocalSearch_Exception('Not a valid sort value provided.'); } $this->_parameters['sort'] = $sort; return $this; } /** * enable the separation of phone numbers * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function enablePhoneSeparation() { $this->_parameters['sepcomm'] = 'true'; return $this; } /** * disable the separation of phone numbers * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function disablePhoneSeparation() { $this->_parameters['sepcomm'] = 'true'; return $this; } /** * if this filter is set, only results with a website are returned * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setFilterOnliner() { $this->_parameters['filter'] = 'ONLINER'; return $this; } /** * if this filter is set, only results without a website are returned * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setFilterOffliner() { $this->_parameters['filter'] = 'OFFLINER'; return $this; } /** * removes the filter value * * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function disableFilter() { $this->_parameters['filter'] = null; return $this; } /** * set a filter to get just results who are open at the given time * possible values: * now = open right now * HH:MM = at the given time (ie 20:00) * * @param string $time * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setOpeningTime($time = null) { $this->_parameters['openingtime'] = $time; return $this; } /** * sets a category filter * * @see http://www.suchen.de/kategorie-katalog * @param string $category * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setCategory($category = null) { $this->_parameters['kategorie'] = $category; return $this; } /** * sets the site filter * ie: www.developergarden.com * * @param string $site * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setSite($site) { $this->_parameters['site'] = $site; return $this; } /** * sets a filter to the given document type * ie: pdf, html * * @param string $type * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setDocumentType($type) { $this->_parameters['typ'] = $type; return $this; } /** * sets a filter for the company name * ie: Deutsche Telekom * * @param string $name * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setName($name) { $this->_parameters['name'] = $name; return $this; } /** * sets a filter for the zip code * * @param string $zip * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setZipCode($zip) { $this->_parameters['plz'] = $zip; return $this; } /** * sets a filter for the street * * @param string $street * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setStreet($street) { $this->_parameters['strasse'] = $street; return $this; } /** * sets a filter for the county * * @param string $county * @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters */ public function setCounty($county) { $this->_parameters['bundesland'] = $county; return $this; } /** * sets a raw parameter with the value * * @param string $key * @param mixed $value * @return unknown_type */ public function setRawParameter($key, $value) { $this->_parameters[$key] = $value; return $this; } /** * returns the parameters as an array * * @return array */ public function getSearchParameters() { $retVal = array(); foreach ($this->_parameters as $key => $value) { if ($value === null) { continue; } $param = array( 'parameter' => $key, 'value' => $value ); $retVal[] = $param; } return $retVal; } }
chemissi/P2
src/public/lib/Zend/Service/DeveloperGarden/LocalSearch/SearchParameters.php
PHP
gpl-2.0
14,788
/* * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.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, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "magisters_terrace.h" enum Says { SAY_AGGRO = 0, SAY_ENERGY = 1, SAY_EMPOWERED = 2, SAY_KILL = 3, SAY_DEATH = 4, EMOTE_CRYSTAL = 5 }; enum Spells { // Crystal effect spells SPELL_FEL_CRYSTAL_DUMMY = 44329, SPELL_MANA_RAGE = 44320, // This spell triggers 44321, which changes scale and regens mana Requires an entry in spell_script_target // Selin's spells SPELL_DRAIN_LIFE = 44294, SPELL_FEL_EXPLOSION = 44314, SPELL_DRAIN_MANA = 46153 // Heroic only }; enum Phases { PHASE_NORMAL = 1, PHASE_DRAIN = 2 }; enum Events { EVENT_FEL_EXPLOSION = 1, EVENT_DRAIN_CRYSTAL, EVENT_DRAIN_MANA, EVENT_DRAIN_LIFE, EVENT_EMPOWER }; enum Misc { ACTION_SWITCH_PHASE = 1 }; class boss_selin_fireheart : public CreatureScript { public: boss_selin_fireheart() : CreatureScript("boss_selin_fireheart") { } struct boss_selin_fireheartAI : public BossAI { boss_selin_fireheartAI(Creature* creature) : BossAI(creature, DATA_SELIN) { _scheduledEvents = false; } void Reset() override { Crystals.clear(); me->GetCreatureListWithEntryInGrid(Crystals, NPC_FEL_CRYSTAL, 250.0f); for (Creature* creature : Crystals) { if (!creature->IsAlive()) creature->Respawn(); creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } _Reset(); CrystalGUID.Clear(); _scheduledEvents = false; } void DoAction(int32 action) override { switch (action) { case ACTION_SWITCH_PHASE: events.SetPhase(PHASE_NORMAL); events.ScheduleEvent(EVENT_FEL_EXPLOSION, 2000, 0, PHASE_NORMAL); AttackStart(me->GetVictim()); me->GetMotionMaster()->MoveChase(me->GetVictim()); break; default: break; } } void SelectNearestCrystal() { if (Crystals.empty()) return; Crystals.sort(Trinity::ObjectDistanceOrderPred(me)); if (Creature* CrystalChosen = Crystals.front()) { Talk(SAY_ENERGY); Talk(EMOTE_CRYSTAL); DoCast(CrystalChosen, SPELL_FEL_CRYSTAL_DUMMY); CrystalGUID = CrystalChosen->GetGUID(); Crystals.remove(CrystalChosen); float x, y, z; CrystalChosen->GetClosePoint(x, y, z, me->GetObjectSize(), CONTACT_DISTANCE); events.SetPhase(PHASE_DRAIN); me->SetWalk(false); me->GetMotionMaster()->MovePoint(1, x, y, z); } } void ShatterRemainingCrystals() { if (Crystals.empty()) return; for (Creature* crystal : Crystals) { if (crystal && crystal->IsAlive()) crystal->KillSelf(); } } void EnterCombat(Unit* /*who*/) override { Talk(SAY_AGGRO); _EnterCombat(); events.SetPhase(PHASE_NORMAL); events.ScheduleEvent(EVENT_FEL_EXPLOSION, 2100, 0, PHASE_NORMAL); } void KilledUnit(Unit* victim) override { if (victim->GetTypeId() == TYPEID_PLAYER) Talk(SAY_KILL); } void MovementInform(uint32 type, uint32 id) override { if (type == POINT_MOTION_TYPE && id == 1) { Unit* CrystalChosen = ObjectAccessor::GetUnit(*me, CrystalGUID); if (CrystalChosen && CrystalChosen->IsAlive()) { CrystalChosen->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); CrystalChosen->CastSpell(me, SPELL_MANA_RAGE, true); events.ScheduleEvent(EVENT_EMPOWER, 10000, PHASE_DRAIN); } } } void JustDied(Unit* /*killer*/) override { Talk(SAY_DEATH); _JustDied(); ShatterRemainingCrystals(); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_FEL_EXPLOSION: DoCastAOE(SPELL_FEL_EXPLOSION); events.ScheduleEvent(EVENT_FEL_EXPLOSION, 2000, 0, PHASE_NORMAL); break; case EVENT_DRAIN_CRYSTAL: SelectNearestCrystal(); _scheduledEvents = false; break; case EVENT_DRAIN_MANA: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 45.0f, true)) DoCast(target, SPELL_DRAIN_MANA); events.ScheduleEvent(EVENT_DRAIN_MANA, 10000, 0, PHASE_NORMAL); break; case EVENT_DRAIN_LIFE: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 20.0f, true)) DoCast(target, SPELL_DRAIN_LIFE); events.ScheduleEvent(EVENT_DRAIN_LIFE, 10000, 0, PHASE_NORMAL); break; case EVENT_EMPOWER: { Talk(SAY_EMPOWERED); Creature* CrystalChosen = ObjectAccessor::GetCreature(*me, CrystalGUID); if (CrystalChosen && CrystalChosen->IsAlive()) CrystalChosen->KillSelf(); CrystalGUID.Clear(); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MoveChase(me->GetVictim()); break; } default: break; } } if (me->GetPowerPct(POWER_MANA) < 10.f) { if (events.IsInPhase(PHASE_NORMAL) && !_scheduledEvents) { _scheduledEvents = true; uint32 timer = urand(3000, 7000); events.ScheduleEvent(EVENT_DRAIN_LIFE, timer, 0, PHASE_NORMAL); if (IsHeroic()) { events.ScheduleEvent(EVENT_DRAIN_CRYSTAL, urand(10000, 15000), 0, PHASE_NORMAL); events.ScheduleEvent(EVENT_DRAIN_MANA, timer + 5000, 0, PHASE_NORMAL); } else events.ScheduleEvent(EVENT_DRAIN_CRYSTAL, urand(20000, 25000), 0, PHASE_NORMAL); } } DoMeleeAttackIfReady(); } private: std::list<Creature*> Crystals; ObjectGuid CrystalGUID; bool _scheduledEvents; }; CreatureAI* GetAI(Creature* creature) const override { return GetInstanceAI<boss_selin_fireheartAI>(creature); }; }; class npc_fel_crystal : public CreatureScript { public: npc_fel_crystal() : CreatureScript("npc_fel_crystal") { } struct npc_fel_crystalAI : public ScriptedAI { npc_fel_crystalAI(Creature* creature) : ScriptedAI(creature) { } void JustDied(Unit* /*killer*/) override { if (InstanceScript* instance = me->GetInstanceScript()) { Creature* Selin = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_SELIN)); if (Selin && Selin->IsAlive()) Selin->AI()->DoAction(ACTION_SWITCH_PHASE); } } }; CreatureAI* GetAI(Creature* creature) const override { return GetInstanceAI<npc_fel_crystalAI>(creature); }; }; void AddSC_boss_selin_fireheart() { new boss_selin_fireheart(); new npc_fel_crystal(); }
AriDEV/TrinityCore
src/server/scripts/EasternKingdoms/MagistersTerrace/boss_selin_fireheart.cpp
C++
gpl-2.0
10,108
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2016 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". 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. } */ #ifndef XCSOAR_FIXED_WINDOW_WIDGET_HPP #define XCSOAR_FIXED_WINDOW_WIDGET_HPP #include "WindowWidget.hpp" #include "Screen/Window.hpp" class FixedWindowWidget : public WindowWidget { public: FixedWindowWidget() = default; FixedWindowWidget(Window *window):WindowWidget(window) {} PixelSize GetMinimumSize() const override { return GetWindow().GetSize(); } }; #endif
Exadios/XCSoar-the-library
src/Widget/FixedWindowWidget.hpp
C++
gpl-2.0
1,282
/* * EAP peer state machine functions (RFC 4137) * Copyright (c) 2004-2007, Jouni Malinen <j@w1.fi> * * 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. * * Alternatively, this software may be distributed under the terms of BSD * license. * * See README and COPYING for more details. */ #ifndef EAP_H #define EAP_H #include "common/defs.h" #include "eap_common/eap_defs.h" #include "eap_peer/eap_methods.h" struct eap_sm; struct wpa_config_blob; struct wpabuf; struct eap_method_type { int vendor; u32 method; }; #ifdef IEEE8021X_EAPOL /** * enum eapol_bool_var - EAPOL boolean state variables for EAP state machine * * These variables are used in the interface between EAP peer state machine and * lower layer. These are defined in RFC 4137, Sect. 4.1. Lower layer code is * expected to maintain these variables and register a callback functions for * EAP state machine to get and set the variables. */ enum eapol_bool_var { /** * EAPOL_eapSuccess - EAP SUCCESS state reached * * EAP state machine reads and writes this value. */ EAPOL_eapSuccess, /** * EAPOL_eapRestart - Lower layer request to restart authentication * * Set to TRUE in lower layer, FALSE in EAP state machine. */ EAPOL_eapRestart, /** * EAPOL_eapFail - EAP FAILURE state reached * * EAP state machine writes this value. */ EAPOL_eapFail, /** * EAPOL_eapResp - Response to send * * Set to TRUE in EAP state machine, FALSE in lower layer. */ EAPOL_eapResp, /** * EAPOL_eapNoResp - Request has been process; no response to send * * Set to TRUE in EAP state machine, FALSE in lower layer. */ EAPOL_eapNoResp, /** * EAPOL_eapReq - EAP request available from lower layer * * Set to TRUE in lower layer, FALSE in EAP state machine. */ EAPOL_eapReq, /** * EAPOL_portEnabled - Lower layer is ready for communication * * EAP state machines reads this value. */ EAPOL_portEnabled, /** * EAPOL_altAccept - Alternate indication of success (RFC3748) * * EAP state machines reads this value. */ EAPOL_altAccept, /** * EAPOL_altReject - Alternate indication of failure (RFC3748) * * EAP state machines reads this value. */ EAPOL_altReject }; /** * enum eapol_int_var - EAPOL integer state variables for EAP state machine * * These variables are used in the interface between EAP peer state machine and * lower layer. These are defined in RFC 4137, Sect. 4.1. Lower layer code is * expected to maintain these variables and register a callback functions for * EAP state machine to get and set the variables. */ enum eapol_int_var { /** * EAPOL_idleWhile - Outside time for EAP peer timeout * * This integer variable is used to provide an outside timer that the * external (to EAP state machine) code must decrement by one every * second until the value reaches zero. This is used in the same way as * EAPOL state machine timers. EAP state machine reads and writes this * value. */ EAPOL_idleWhile }; /** * struct eapol_callbacks - Callback functions from EAP to lower layer * * This structure defines the callback functions that EAP state machine * requires from the lower layer (usually EAPOL state machine) for updating * state variables and requesting information. eapol_ctx from * eap_peer_sm_init() call will be used as the ctx parameter for these * callback functions. */ struct eapol_callbacks { /** * get_config - Get pointer to the current network configuration * @ctx: eapol_ctx from eap_peer_sm_init() call */ struct eap_peer_config * (*get_config)(void *ctx); /** * get_bool - Get a boolean EAPOL state variable * @variable: EAPOL boolean variable to get * Returns: Value of the EAPOL variable */ Boolean (*get_bool)(void *ctx, enum eapol_bool_var variable); /** * set_bool - Set a boolean EAPOL state variable * @ctx: eapol_ctx from eap_peer_sm_init() call * @variable: EAPOL boolean variable to set * @value: Value for the EAPOL variable */ void (*set_bool)(void *ctx, enum eapol_bool_var variable, Boolean value); /** * get_int - Get an integer EAPOL state variable * @ctx: eapol_ctx from eap_peer_sm_init() call * @variable: EAPOL integer variable to get * Returns: Value of the EAPOL variable */ unsigned int (*get_int)(void *ctx, enum eapol_int_var variable); /** * set_int - Set an integer EAPOL state variable * @ctx: eapol_ctx from eap_peer_sm_init() call * @variable: EAPOL integer variable to set * @value: Value for the EAPOL variable */ void (*set_int)(void *ctx, enum eapol_int_var variable, unsigned int value); /** * get_eapReqData - Get EAP-Request data * @ctx: eapol_ctx from eap_peer_sm_init() call * @len: Pointer to variable that will be set to eapReqDataLen * Returns: Reference to eapReqData (EAP state machine will not free * this) or %NULL if eapReqData not available. */ struct wpabuf * (*get_eapReqData)(void *ctx); /** * set_config_blob - Set named configuration blob * @ctx: eapol_ctx from eap_peer_sm_init() call * @blob: New value for the blob * * Adds a new configuration blob or replaces the current value of an * existing blob. */ void (*set_config_blob)(void *ctx, struct wpa_config_blob *blob); /** * get_config_blob - Get a named configuration blob * @ctx: eapol_ctx from eap_peer_sm_init() call * @name: Name of the blob * Returns: Pointer to blob data or %NULL if not found */ const struct wpa_config_blob * (*get_config_blob)(void *ctx, const char *name); /** * notify_pending - Notify that a pending request can be retried * @ctx: eapol_ctx from eap_peer_sm_init() call * * An EAP method can perform a pending operation (e.g., to get a * response from an external process). Once the response is available, * this callback function can be used to request EAPOL state machine to * retry delivering the previously received (and still unanswered) EAP * request to EAP state machine. */ void (*notify_pending)(void *ctx); /** * eap_param_needed - Notify that EAP parameter is needed * @ctx: eapol_ctx from eap_peer_sm_init() call * @field: Field indicator (e.g., WPA_CTRL_REQ_EAP_IDENTITY) * @txt: User readable text describing the required parameter */ void (*eap_param_needed)(void *ctx, enum wpa_ctrl_req_type field, const char *txt); /** * notify_cert - Notification of a peer certificate * @ctx: eapol_ctx from eap_peer_sm_init() call * @depth: Depth in certificate chain (0 = server) * @subject: Subject of the peer certificate * @cert_hash: SHA-256 hash of the certificate * @cert: Peer certificate */ void (*notify_cert)(void *ctx, int depth, const char *subject, const char *cert_hash, const struct wpabuf *cert); }; /** * struct eap_config - Configuration for EAP state machine */ struct eap_config { /** * opensc_engine_path - OpenSC engine for OpenSSL engine support * * Usually, path to engine_opensc.so. */ const char *opensc_engine_path; /** * pkcs11_engine_path - PKCS#11 engine for OpenSSL engine support * * Usually, path to engine_pkcs11.so. */ const char *pkcs11_engine_path; /** * pkcs11_module_path - OpenSC PKCS#11 module for OpenSSL engine * * Usually, path to opensc-pkcs11.so. */ const char *pkcs11_module_path; /** * wps - WPS context data * * This is only used by EAP-WSC and can be left %NULL if not available. */ struct wps_context *wps; /** * cert_in_cb - Include server certificates in callback */ int cert_in_cb; }; struct eap_sm * eap_peer_sm_init(void *eapol_ctx, struct eapol_callbacks *eapol_cb, void *msg_ctx, struct eap_config *conf); void eap_peer_sm_deinit(struct eap_sm *sm); int eap_peer_sm_step(struct eap_sm *sm); void eap_sm_abort(struct eap_sm *sm); int eap_sm_get_status(struct eap_sm *sm, char *buf, size_t buflen, int verbose); const char * eap_sm_get_method_name(struct eap_sm *sm); struct wpabuf * eap_sm_buildIdentity(struct eap_sm *sm, int id, int encrypted); void eap_sm_request_identity(struct eap_sm *sm); void eap_sm_request_password(struct eap_sm *sm); void eap_sm_request_new_password(struct eap_sm *sm); void eap_sm_request_pin(struct eap_sm *sm); void eap_sm_request_otp(struct eap_sm *sm, const char *msg, size_t msg_len); void eap_sm_request_passphrase(struct eap_sm *sm); void eap_sm_notify_ctrl_attached(struct eap_sm *sm); u32 eap_get_phase2_type(const char *name, int *vendor); struct eap_method_type * eap_get_phase2_types(struct eap_peer_config *config, size_t *count); void eap_set_fast_reauth(struct eap_sm *sm, int enabled); void eap_set_workaround(struct eap_sm *sm, unsigned int workaround); void eap_set_force_disabled(struct eap_sm *sm, int disabled); int eap_key_available(struct eap_sm *sm); void eap_notify_success(struct eap_sm *sm); void eap_notify_lower_layer_success(struct eap_sm *sm); const u8 * eap_get_eapKeyData(struct eap_sm *sm, size_t *len); struct wpabuf * eap_get_eapRespData(struct eap_sm *sm); void eap_register_scard_ctx(struct eap_sm *sm, void *ctx); void eap_invalidate_cached_session(struct eap_sm *sm); int eap_is_wps_pbc_enrollee(struct eap_peer_config *conf); int eap_is_wps_pin_enrollee(struct eap_peer_config *conf); #endif /* IEEE8021X_EAPOL */ #endif /* EAP_H */
robacklin/uclinux-users
wpa_supplicant/src/eap_peer/eap.h
C
gpl-2.0
9,428
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2016 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". 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 "Init.hpp" #include <curl/curl.h> void Net::Initialise() { curl_global_init(CURL_GLOBAL_WIN32); } void Net::Deinitialise() { curl_global_cleanup(); }
Exadios/XCSoar-the-library
src/Net/HTTP/Init.cpp
C++
gpl-2.0
1,066
///////////////////////////////////////////////////////////////////////////// // Name: src/msw/mediactrl_qt.cpp // Purpose: QuickTime Media Backend for Windows // Author: Ryan Norton <wxprojects@comcast.net> // Modified by: Robin Dunn (moved QT code from mediactrl.cpp) // // Created: 11/07/04 // RCS-ID: $Id: mediactrl_qt.cpp 45498 2007-04-16 13:03:05Z VZ $ // Copyright: (c) Ryan Norton // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// //=========================================================================== // DECLARATIONS //=========================================================================== //--------------------------------------------------------------------------- // Pre-compiled header stuff //--------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_MEDIACTRL #include "wx/mediactrl.h" #ifndef WX_PRECOMP #include "wx/log.h" #include "wx/dcclient.h" #include "wx/timer.h" #include "wx/math.h" // log10 & pow #endif #include "wx/msw/private.h" // user info and wndproc setting/getting #include "wx/dynlib.h" //--------------------------------------------------------------------------- // Externals (somewhere in src/msw/app.cpp and src/msw/window.cpp) //--------------------------------------------------------------------------- extern "C" WXDLLIMPEXP_BASE HINSTANCE wxGetInstance(void); #ifdef __WXWINCE__ extern WXDLLIMPEXP_CORE wxChar *wxCanvasClassName; #else extern WXDLLIMPEXP_CORE const wxChar *wxCanvasClassName; #endif LRESULT WXDLLIMPEXP_CORE APIENTRY _EXPORT wxWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); //--------------------------------------------------------------------------- // Killed MSVC warnings //--------------------------------------------------------------------------- //disable "cast truncates constant value" for VARIANT_BOOL values //passed as parameters in VC5 and up #ifdef _MSC_VER #pragma warning (disable:4310) #endif //--------------------------------------------------------------------------- // wxQTMediaBackend // // We don't include Quicktime headers here and define all the types // ourselves because looking for the quicktime libaries etc. would // be tricky to do and making this a dependency for the MSVC projects // would be unrealistic. // // Thanks to Robert Roebling for the wxDL macro/library idea //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // QT Includes //--------------------------------------------------------------------------- //#include <qtml.h> // Windoze QT include //#include <QuickTimeComponents.h> // Standard QT stuff #include "wx/dynlib.h" //--------------------------------------------------------------------------- // QT Types //--------------------------------------------------------------------------- typedef struct MovieRecord* Movie; typedef wxInt16 OSErr; typedef wxInt32 OSStatus; #define noErr 0 #define fsRdPerm 1 typedef unsigned char Str255[256]; #define StringPtr unsigned char* #define newMovieActive 1 #define newMovieAsyncOK (1 << 8) #define Ptr char* #define Handle Ptr* #define Fixed long #define OSType unsigned long #define CGrafPtr struct GrafPort * #define TimeScale long #define TimeBase struct TimeBaseRecord * typedef struct ComponentInstanceRecord * ComponentInstance; #define kMovieLoadStatePlayable 10000 #define Boolean int #define MovieController ComponentInstance #ifndef URLDataHandlerSubType #if defined(__WATCOMC__) || defined(__MINGW32__) // use magic numbers for compilers which complain about multicharacter integers const OSType URLDataHandlerSubType = 1970433056; const OSType VisualMediaCharacteristic = 1702454643; #else const OSType URLDataHandlerSubType = 'url '; const OSType VisualMediaCharacteristic = 'eyes'; #endif #endif struct FSSpec { short vRefNum; long parID; Str255 name; // Str63 on mac, Str255 on msw }; struct Rect { short top; short left; short bottom; short right; }; struct wide { wxInt32 hi; wxUint32 lo; }; struct TimeRecord { wide value; // units TimeScale scale; // units per second TimeBase base; }; struct Point { short v; short h; }; struct EventRecord { wxUint16 what; wxUint32 message; wxUint32 when; Point where; wxUint16 modifiers; }; enum { mcTopLeftMovie = 1, mcScaleMovieToFit = 2, mcWithBadge = 4, mcNotVisible = 8, mcWithFrame = 16 }; //--------------------------------------------------------------------------- // QT Library //--------------------------------------------------------------------------- #define wxDL_METHOD_DEFINE( rettype, name, args, shortargs, defret ) \ typedef rettype (* name ## Type) args ; \ name ## Type pfn_ ## name; \ rettype name args \ { if (m_ok) return pfn_ ## name shortargs ; return defret; } #define wxDL_VOIDMETHOD_DEFINE( name, args, shortargs ) \ typedef void (* name ## Type) args ; \ name ## Type pfn_ ## name; \ void name args \ { if (m_ok) pfn_ ## name shortargs ; } #define wxDL_METHOD_LOAD( lib, name, success ) \ pfn_ ## name = (name ## Type) lib.GetSymbol( wxT(#name), &success ); \ if (!success) return false class WXDLLIMPEXP_MEDIA wxQuickTimeLibrary { public: ~wxQuickTimeLibrary() { if (m_dll.IsLoaded()) m_dll.Unload(); } bool Initialize(); bool IsOk() const {return m_ok;} protected: wxDynamicLibrary m_dll; bool m_ok; public: wxDL_VOIDMETHOD_DEFINE( StartMovie, (Movie m), (m) ) wxDL_VOIDMETHOD_DEFINE( StopMovie, (Movie m), (m) ) wxDL_METHOD_DEFINE( bool, IsMovieDone, (Movie m), (m), false) wxDL_VOIDMETHOD_DEFINE( GoToBeginningOfMovie, (Movie m), (m) ) wxDL_METHOD_DEFINE( OSErr, GetMoviesError, (), (), -1) wxDL_METHOD_DEFINE( OSErr, EnterMovies, (), (), -1) wxDL_VOIDMETHOD_DEFINE( ExitMovies, (), () ) wxDL_METHOD_DEFINE( OSErr, InitializeQTML, (long flags), (flags), -1) wxDL_VOIDMETHOD_DEFINE( TerminateQTML, (), () ) wxDL_METHOD_DEFINE( OSErr, NativePathNameToFSSpec, (char* inName, FSSpec* outFile, long flags), (inName, outFile, flags), -1) wxDL_METHOD_DEFINE( OSErr, OpenMovieFile, (const FSSpec * fileSpec, short * resRefNum, wxInt8 permission), (fileSpec, resRefNum, permission), -1 ) wxDL_METHOD_DEFINE( OSErr, CloseMovieFile, (short resRefNum), (resRefNum), -1) wxDL_METHOD_DEFINE( OSErr, NewMovieFromFile, (Movie * theMovie, short resRefNum, short * resId, StringPtr resName, short newMovieFlags, bool * dataRefWasChanged), (theMovie, resRefNum, resId, resName, newMovieFlags, dataRefWasChanged), -1) wxDL_VOIDMETHOD_DEFINE( SetMovieRate, (Movie m, Fixed rate), (m, rate) ) wxDL_METHOD_DEFINE( Fixed, GetMovieRate, (Movie m), (m), 0) wxDL_VOIDMETHOD_DEFINE( MoviesTask, (Movie m, long maxms), (m, maxms) ) wxDL_VOIDMETHOD_DEFINE( BlockMove, (const char* p1, const char* p2, long s), (p1,p2,s) ) wxDL_METHOD_DEFINE( Handle, NewHandleClear, (long s), (s), NULL ) wxDL_METHOD_DEFINE( OSErr, NewMovieFromDataRef, (Movie * m, short flags, short * id, Handle dataRef, OSType dataRefType), (m,flags,id,dataRef,dataRefType), -1 ) wxDL_VOIDMETHOD_DEFINE( DisposeHandle, (Handle h), (h) ) wxDL_VOIDMETHOD_DEFINE( GetMovieNaturalBoundsRect, (Movie m, Rect* r), (m,r) ) wxDL_METHOD_DEFINE( void*, GetMovieIndTrackType, (Movie m, long index, OSType type, long flags), (m,index,type,flags), NULL ) wxDL_VOIDMETHOD_DEFINE( CreatePortAssociation, (void* hWnd, void* junk, long morejunk), (hWnd, junk, morejunk) ) wxDL_METHOD_DEFINE(void*, GetNativeWindowPort, (void* hWnd), (hWnd), NULL) wxDL_VOIDMETHOD_DEFINE(SetMovieGWorld, (Movie m, CGrafPtr port, void* whatever), (m, port, whatever) ) wxDL_VOIDMETHOD_DEFINE(DisposeMovie, (Movie m), (m) ) wxDL_VOIDMETHOD_DEFINE(SetMovieBox, (Movie m, Rect* r), (m,r)) wxDL_VOIDMETHOD_DEFINE(SetMovieTimeScale, (Movie m, long s), (m,s)) wxDL_METHOD_DEFINE(long, GetMovieDuration, (Movie m), (m), 0) wxDL_METHOD_DEFINE(TimeBase, GetMovieTimeBase, (Movie m), (m), 0) wxDL_METHOD_DEFINE(TimeScale, GetMovieTimeScale, (Movie m), (m), 0) wxDL_METHOD_DEFINE(long, GetMovieTime, (Movie m, void* cruft), (m,cruft), 0) wxDL_VOIDMETHOD_DEFINE(SetMovieTime, (Movie m, TimeRecord* tr), (m,tr) ) wxDL_METHOD_DEFINE(short, GetMovieVolume, (Movie m), (m), 0) wxDL_VOIDMETHOD_DEFINE(SetMovieVolume, (Movie m, short sVolume), (m,sVolume) ) wxDL_VOIDMETHOD_DEFINE(SetMovieTimeValue, (Movie m, long s), (m,s)) wxDL_METHOD_DEFINE(ComponentInstance, NewMovieController, (Movie m, const Rect* mr, long fl), (m,mr,fl), 0) wxDL_VOIDMETHOD_DEFINE(DisposeMovieController, (ComponentInstance ci), (ci)) wxDL_METHOD_DEFINE(int, MCSetVisible, (ComponentInstance m, int b), (m, b), 0) wxDL_VOIDMETHOD_DEFINE(PrePrerollMovie, (Movie m, long t, Fixed r, WXFARPROC p1, void* p2), (m,t,r,p1,p2) ) wxDL_VOIDMETHOD_DEFINE(PrerollMovie, (Movie m, long t, Fixed r), (m,t,r) ) wxDL_METHOD_DEFINE(Fixed, GetMoviePreferredRate, (Movie m), (m), 0) wxDL_METHOD_DEFINE(long, GetMovieLoadState, (Movie m), (m), 0) wxDL_METHOD_DEFINE(void*, NewRoutineDescriptor, (WXFARPROC f, int l, void* junk), (f, l, junk), 0) wxDL_VOIDMETHOD_DEFINE(DisposeRoutineDescriptor, (void* f), (f)) wxDL_METHOD_DEFINE(void*, GetCurrentArchitecture, (), (), 0) wxDL_METHOD_DEFINE(int, MCDoAction, (ComponentInstance ci, long f, void* p), (ci,f,p), 0) wxDL_VOIDMETHOD_DEFINE(MCSetControllerBoundsRect, (ComponentInstance ci, Rect* r), (ci,r)) wxDL_VOIDMETHOD_DEFINE(DestroyPortAssociation, (CGrafPtr g), (g)) wxDL_VOIDMETHOD_DEFINE(NativeEventToMacEvent, (MSG* p1, EventRecord* p2), (p1,p2)) wxDL_VOIDMETHOD_DEFINE(MCIsPlayerEvent, (ComponentInstance ci, EventRecord* p2), (ci, p2)) wxDL_METHOD_DEFINE(int, MCSetMovie, (ComponentInstance ci, Movie m, void* p1, Point w), (ci,m,p1,w),0) wxDL_VOIDMETHOD_DEFINE(MCPositionController, (ComponentInstance ci, Rect* r, void* junk, void* morejunk), (ci,r,junk,morejunk)) wxDL_VOIDMETHOD_DEFINE(MCSetActionFilterWithRefCon, (ComponentInstance ci, WXFARPROC cb, void* ref), (ci,cb,ref)) wxDL_VOIDMETHOD_DEFINE(MCGetControllerInfo, (MovieController mc, long* flags), (mc,flags)) wxDL_VOIDMETHOD_DEFINE(BeginUpdate, (CGrafPtr port), (port)) wxDL_VOIDMETHOD_DEFINE(UpdateMovie, (Movie m), (m)) wxDL_VOIDMETHOD_DEFINE(EndUpdate, (CGrafPtr port), (port)) wxDL_METHOD_DEFINE( OSErr, GetMoviesStickyError, (), (), -1) }; bool wxQuickTimeLibrary::Initialize() { m_ok = false; // Turn off the wxDynamicLibrary logging as we're prepared to handle the // errors wxLogNull nolog; if (!m_dll.Load(wxT("qtmlClient.dll"))) { return false; } wxDL_METHOD_LOAD( m_dll, StartMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, StopMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, IsMovieDone, m_ok ); wxDL_METHOD_LOAD( m_dll, GoToBeginningOfMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMoviesError, m_ok ); wxDL_METHOD_LOAD( m_dll, EnterMovies, m_ok ); wxDL_METHOD_LOAD( m_dll, ExitMovies, m_ok ); wxDL_METHOD_LOAD( m_dll, InitializeQTML, m_ok ); wxDL_METHOD_LOAD( m_dll, TerminateQTML, m_ok ); wxDL_METHOD_LOAD( m_dll, NativePathNameToFSSpec, m_ok ); wxDL_METHOD_LOAD( m_dll, OpenMovieFile, m_ok ); wxDL_METHOD_LOAD( m_dll, CloseMovieFile, m_ok ); wxDL_METHOD_LOAD( m_dll, NewMovieFromFile, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieRate, m_ok ); wxDL_METHOD_LOAD( m_dll, SetMovieRate, m_ok ); wxDL_METHOD_LOAD( m_dll, MoviesTask, m_ok ); wxDL_METHOD_LOAD( m_dll, BlockMove, m_ok ); wxDL_METHOD_LOAD( m_dll, NewHandleClear, m_ok ); wxDL_METHOD_LOAD( m_dll, NewMovieFromDataRef, m_ok ); wxDL_METHOD_LOAD( m_dll, DisposeHandle, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieNaturalBoundsRect, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieIndTrackType, m_ok ); wxDL_METHOD_LOAD( m_dll, CreatePortAssociation, m_ok ); wxDL_METHOD_LOAD( m_dll, DestroyPortAssociation, m_ok ); wxDL_METHOD_LOAD( m_dll, GetNativeWindowPort, m_ok ); wxDL_METHOD_LOAD( m_dll, SetMovieGWorld, m_ok ); wxDL_METHOD_LOAD( m_dll, DisposeMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, SetMovieBox, m_ok ); wxDL_METHOD_LOAD( m_dll, SetMovieTimeScale, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieDuration, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieTimeBase, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieTimeScale, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieTime, m_ok ); wxDL_METHOD_LOAD( m_dll, SetMovieTime, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieVolume, m_ok ); wxDL_METHOD_LOAD( m_dll, SetMovieVolume, m_ok ); wxDL_METHOD_LOAD( m_dll, SetMovieTimeValue, m_ok ); wxDL_METHOD_LOAD( m_dll, NewMovieController, m_ok ); wxDL_METHOD_LOAD( m_dll, DisposeMovieController, m_ok ); wxDL_METHOD_LOAD( m_dll, MCSetVisible, m_ok ); wxDL_METHOD_LOAD( m_dll, PrePrerollMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, PrerollMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMoviePreferredRate, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMovieLoadState, m_ok ); wxDL_METHOD_LOAD( m_dll, MCDoAction, m_ok ); wxDL_METHOD_LOAD( m_dll, MCSetControllerBoundsRect, m_ok ); wxDL_METHOD_LOAD( m_dll, NativeEventToMacEvent, m_ok ); wxDL_METHOD_LOAD( m_dll, MCIsPlayerEvent, m_ok ); wxDL_METHOD_LOAD( m_dll, MCSetMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, MCSetActionFilterWithRefCon, m_ok ); wxDL_METHOD_LOAD( m_dll, MCGetControllerInfo, m_ok ); wxDL_METHOD_LOAD( m_dll, BeginUpdate, m_ok ); wxDL_METHOD_LOAD( m_dll, UpdateMovie, m_ok ); wxDL_METHOD_LOAD( m_dll, EndUpdate, m_ok ); wxDL_METHOD_LOAD( m_dll, GetMoviesStickyError, m_ok ); m_ok = true; return true; } class WXDLLIMPEXP_MEDIA wxQTMediaBackend : public wxMediaBackendCommonBase { public: wxQTMediaBackend(); virtual ~wxQTMediaBackend(); virtual bool CreateControl(wxControl* ctrl, wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name); virtual bool Play(); virtual bool Pause(); virtual bool Stop(); virtual bool Load(const wxURI& location, const wxURI& proxy) { return wxMediaBackend::Load(location, proxy); } virtual bool Load(const wxString& fileName); virtual bool Load(const wxURI& location); virtual wxMediaState GetState(); virtual bool SetPosition(wxLongLong where); virtual wxLongLong GetPosition(); virtual wxLongLong GetDuration(); virtual void Move(int x, int y, int w, int h); wxSize GetVideoSize() const; virtual double GetPlaybackRate(); virtual bool SetPlaybackRate(double dRate); virtual double GetVolume(); virtual bool SetVolume(double); void Cleanup(); void FinishLoad(); static void PPRMProc (Movie theMovie, OSErr theErr, void* theRefCon); // TODO: Last param actually long - does this work on 64bit machines? static Boolean MCFilterProc(MovieController theController, short action, void *params, LONG_PTR refCon); static LRESULT CALLBACK QTWndProc(HWND, UINT, WPARAM, LPARAM); virtual bool ShowPlayerControls(wxMediaCtrlPlayerControls flags); wxSize m_bestSize; // Original movie size Movie m_movie; // QT Movie handle/instance bool m_bVideo; // Whether or not we have video bool m_bPlaying; // Whether or not movie is playing wxTimer* m_timer; // Load or Play timer wxQuickTimeLibrary m_lib; // DLL to load functions from ComponentInstance m_pMC; // Movie Controller friend class wxQTMediaEvtHandler; DECLARE_DYNAMIC_CLASS(wxQTMediaBackend) }; // helper to hijack background erasing for the QT window class WXDLLIMPEXP_MEDIA wxQTMediaEvtHandler : public wxEvtHandler { public: wxQTMediaEvtHandler(wxQTMediaBackend *qtb, WXHWND hwnd) { m_qtb = qtb; m_hwnd = hwnd; m_qtb->m_ctrl->Connect(m_qtb->m_ctrl->GetId(), wxEVT_ERASE_BACKGROUND, wxEraseEventHandler(wxQTMediaEvtHandler::OnEraseBackground), NULL, this); } void OnEraseBackground(wxEraseEvent& event); private: wxQTMediaBackend *m_qtb; WXHWND m_hwnd; DECLARE_NO_COPY_CLASS(wxQTMediaEvtHandler) }; //=========================================================================== // IMPLEMENTATION //=========================================================================== //--------------------------------------------------------------------------- // wxQTMediaBackend // // TODO: Use a less kludgy way to pause/get state/set state // FIXME: Greg Hazel reports that sometimes files that cannot be played // with this backend are treated as playable anyway - not verified though. //--------------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxQTMediaBackend, wxMediaBackend) // Time between timer calls - this is the Apple recommendation to the TCL // team I believe #define MOVIE_DELAY 20 //--------------------------------------------------------------------------- // wxQTLoadTimer // // QT, esp. QT for Windows is very picky about how you go about // async loading. If you were to go through a Windows message loop // or a MoviesTask or both and then check the movie load state // it would still return 1000 (loading)... even (pre)prerolling doesn't // help. However, making a load timer like this works //--------------------------------------------------------------------------- class wxQTLoadTimer : public wxTimer { public: wxQTLoadTimer(Movie movie, wxQTMediaBackend* parent, wxQuickTimeLibrary* pLib) : m_movie(movie), m_parent(parent), m_pLib(pLib) {} void Notify() { m_pLib->MoviesTask(m_movie, 0); // kMovieLoadStatePlayable if (m_pLib->GetMovieLoadState(m_movie) >= 10000) { m_parent->FinishLoad(); delete this; } } protected: Movie m_movie; //Our movie instance wxQTMediaBackend* m_parent; //Backend pointer wxQuickTimeLibrary* m_pLib; //Interfaces }; // -------------------------------------------------------------------------- // wxQTPlayTimer - Handle Asyncronous Playing // // 1) Checks to see if the movie is done, and if not continues // streaming the movie // 2) Sends the wxEVT_MEDIA_STOP event if we have reached the end of // the movie. // -------------------------------------------------------------------------- class wxQTPlayTimer : public wxTimer { public: wxQTPlayTimer(Movie movie, wxQTMediaBackend* parent, wxQuickTimeLibrary* pLib) : m_movie(movie), m_parent(parent), m_pLib(pLib) {} void Notify() { // // OK, a little explaining - basically originally // we only called MoviesTask if the movie was actually // playing (not paused or stopped)... this was before // we realized MoviesTask actually handles repainting // of the current frame - so if you were to resize // or something it would previously not redraw that // portion of the movie. // // So now we call MoviesTask always so that it repaints // correctly. // m_pLib->MoviesTask(m_movie, 0); // // Handle the stop event - if the movie has reached // the end, notify our handler // // m_bPlaying == !(Stopped | Paused) // if (m_parent->m_bPlaying) { if (m_pLib->IsMovieDone(m_movie)) { if ( m_parent->SendStopEvent() ) { m_parent->Stop(); wxASSERT(m_pLib->GetMoviesError() == noErr); m_parent->QueueFinishEvent(); } } } } protected: Movie m_movie; // Our movie instance wxQTMediaBackend* m_parent; //Backend pointer wxQuickTimeLibrary* m_pLib; //Interfaces }; //--------------------------------------------------------------------------- // wxQTMediaBackend::QTWndProc // // Forwards events to the Movie Controller so that it can // redraw itself/process messages etc.. //--------------------------------------------------------------------------- LRESULT CALLBACK wxQTMediaBackend::QTWndProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam) { wxQTMediaBackend* pThis = (wxQTMediaBackend*)wxGetWindowUserData(hWnd); MSG msg; msg.hwnd = hWnd; msg.message = nMsg; msg.wParam = wParam; msg.lParam = lParam; msg.time = 0; msg.pt.x = 0; msg.pt.y = 0; EventRecord theEvent; pThis->m_lib.NativeEventToMacEvent(&msg, &theEvent); pThis->m_lib.MCIsPlayerEvent(pThis->m_pMC, &theEvent); return pThis->m_ctrl->MSWWindowProc(nMsg, wParam, lParam); } //--------------------------------------------------------------------------- // wxQTMediaBackend Destructor // // Sets m_timer to NULL signifying we havn't loaded anything yet //--------------------------------------------------------------------------- wxQTMediaBackend::wxQTMediaBackend() : m_movie(NULL), m_bPlaying(false), m_timer(NULL), m_pMC(NULL) { } //--------------------------------------------------------------------------- // wxQTMediaBackend Destructor // // 1) Cleans up the QuickTime movie instance // 2) Decrements the QuickTime reference counter - if this reaches // 0, QuickTime shuts down // 3) Decrements the QuickTime Windows Media Layer reference counter - // if this reaches 0, QuickTime shuts down the Windows Media Layer //--------------------------------------------------------------------------- wxQTMediaBackend::~wxQTMediaBackend() { if (m_movie) Cleanup(); if (m_lib.IsOk()) { if (m_pMC) { m_lib.DisposeMovieController(m_pMC); // m_pMC = NULL; } // destroy wxQTMediaEvtHandler we pushed on it m_ctrl->PopEventHandler(true); m_lib.DestroyPortAssociation( (CGrafPtr)m_lib.GetNativeWindowPort(m_ctrl->GetHWND())); //Note that ExitMovies() is not necessary, but //the docs are fuzzy on whether or not TerminateQTML is m_lib.ExitMovies(); m_lib.TerminateQTML(); } } //--------------------------------------------------------------------------- // wxQTMediaBackend::CreateControl // // 1) Intializes QuickTime // 2) Creates the control window //--------------------------------------------------------------------------- bool wxQTMediaBackend::CreateControl(wxControl* ctrl, wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name) { if (!m_lib.Initialize()) return false; int nError = m_lib.InitializeQTML(0); if (nError != noErr) //-2093 no dll { wxFAIL_MSG(wxString::Format(wxT("Couldn't Initialize Quicktime-%i"), nError)); return false; } m_lib.EnterMovies(); // Create window // By default wxWindow(s) is created with a border - // so we need to get rid of those // // Since we don't have a child window like most other // backends, we don't need wxCLIP_CHILDREN if ( !ctrl->wxControl::Create(parent, id, pos, size, (style & ~wxBORDER_MASK) | wxBORDER_NONE, validator, name) ) { return false; } m_ctrl = wxStaticCast(ctrl, wxMediaCtrl); // Create a port association for our window so we // can use it as a WindowRef m_lib.CreatePortAssociation(m_ctrl->GetHWND(), NULL, 0L); // Part of a suggestion from Greg Hazel // to repaint movie when idle m_ctrl->PushEventHandler(new wxQTMediaEvtHandler(this, m_ctrl->GetHWND())); // done return true; } //--------------------------------------------------------------------------- // wxQTMediaBackend::Load (file version) // // 1) Get an FSSpec from the Windows path name // 2) Open the movie // 3) Obtain the movie instance from the movie resource // 4) Close the movie resource // 5) Finish loading //--------------------------------------------------------------------------- bool wxQTMediaBackend::Load(const wxString& fileName) { if (m_movie) Cleanup(); bool result = true; OSErr err = noErr; short movieResFile = 0; //= 0 because of annoying VC6 warning FSSpec sfFile; err = m_lib.NativePathNameToFSSpec( (char*) (const char*) fileName.mb_str(), &sfFile, 0); result = (err == noErr); if (result) { err = m_lib.OpenMovieFile(&sfFile, &movieResFile, fsRdPerm); result = (err == noErr); } if (result) { short movieResID = 0; Str255 movieName; err = m_lib.NewMovieFromFile( &m_movie, movieResFile, &movieResID, movieName, newMovieActive, NULL ); // wasChanged result = (err == noErr /*&& m_lib.GetMoviesStickyError() == noErr*/); // check m_lib.GetMoviesStickyError() because it may not find the // proper codec and play black video and other strange effects, // not to mention mess up the dynamic backend loading scheme // of wxMediaCtrl - so it just does what the QuickTime player does if (result) { m_lib.CloseMovieFile(movieResFile); FinishLoad(); } } return result; } //--------------------------------------------------------------------------- // wxQTMediaBackend::PPRMProc (static) // // Called when done PrePrerolling the movie. // Note that in 99% of the cases this does nothing... // Anyway we set up the loading timer here to tell us when the movie is done //--------------------------------------------------------------------------- void wxQTMediaBackend::PPRMProc (Movie theMovie, OSErr WXUNUSED_UNLESS_DEBUG(theErr), void* theRefCon) { wxASSERT( theMovie ); wxASSERT( theRefCon ); wxASSERT( theErr == noErr ); wxQTMediaBackend* pBE = (wxQTMediaBackend*) theRefCon; long lTime = pBE->m_lib.GetMovieTime(theMovie,NULL); Fixed rate = pBE->m_lib.GetMoviePreferredRate(theMovie); pBE->m_lib.PrerollMovie(theMovie, lTime, rate); pBE->m_timer = new wxQTLoadTimer(pBE->m_movie, pBE, &pBE->m_lib); pBE->m_timer->Start(MOVIE_DELAY); } //--------------------------------------------------------------------------- // wxQTMediaBackend::Load (URL Version) // // 1) Build an escaped URI from location // 2) Create a handle to store the URI string // 3) Put the URI string inside the handle // 4) Make a QuickTime URL data ref from the handle with the URI in it // 5) Clean up the URI string handle // 6) Do some prerolling // 7) Finish Loading //--------------------------------------------------------------------------- bool wxQTMediaBackend::Load(const wxURI& location) { if (m_movie) Cleanup(); wxString theURI = location.BuildURI(); Handle theHandle = m_lib.NewHandleClear(theURI.length() + 1); wxASSERT(theHandle); m_lib.BlockMove(theURI.mb_str(), *theHandle, theURI.length() + 1); // create the movie from the handle that refers to the URI OSErr err = m_lib.NewMovieFromDataRef(&m_movie, newMovieActive | newMovieAsyncOK /* | newMovieIdleImportOK */, NULL, theHandle, URLDataHandlerSubType); m_lib.DisposeHandle(theHandle); if (err == noErr) { long timeNow; Fixed playRate; timeNow = m_lib.GetMovieTime(m_movie, NULL); wxASSERT(m_lib.GetMoviesError() == noErr); playRate = m_lib.GetMoviePreferredRate(m_movie); wxASSERT(m_lib.GetMoviesError() == noErr); // Note that the callback here is optional, // but without it PrePrerollMovie can be buggy // (see Apple ml). Also, some may wonder // why we need this at all - this is because // Apple docs say QuickTime streamed movies // require it if you don't use a Movie Controller, // which we don't by default. // m_lib.PrePrerollMovie(m_movie, timeNow, playRate, (WXFARPROC)wxQTMediaBackend::PPRMProc, (void*)this); return true; } else return false; } //--------------------------------------------------------------------------- // wxQTMediaBackend::FinishLoad // // 1) Create the movie timer // 2) Get real size of movie for GetBestSize/sizers // 3) Set the movie time scale to something usable so that seeking // etc. will work correctly // 4) Set our Movie Controller to display the movie if it exists, // otherwise set the bounds of the Movie // 5) Refresh parent window //--------------------------------------------------------------------------- void wxQTMediaBackend::FinishLoad() { // Create the playing/streaming timer m_timer = new wxQTPlayTimer(m_movie, (wxQTMediaBackend*) this, &m_lib); wxASSERT(m_timer); m_timer->Start(MOVIE_DELAY, wxTIMER_CONTINUOUS); // get the real size of the movie Rect outRect; memset(&outRect, 0, sizeof(Rect)); // suppress annoying VC6 warning m_lib.GetMovieNaturalBoundsRect (m_movie, &outRect); wxASSERT(m_lib.GetMoviesError() == noErr); m_bestSize.x = outRect.right - outRect.left; m_bestSize.y = outRect.bottom - outRect.top; // Handle the movie GWorld if (m_pMC) { Point thePoint; thePoint.h = thePoint.v = 0; m_lib.MCSetMovie(m_pMC, m_movie, m_lib.GetNativeWindowPort(m_ctrl->GetHandle()), thePoint); m_lib.MCSetVisible(m_pMC, true); m_bestSize.y += 16; } else { m_lib.SetMovieGWorld(m_movie, (CGrafPtr) m_lib.GetNativeWindowPort(m_ctrl->GetHWND()), NULL); } // Set the movie to millisecond precision m_lib.SetMovieTimeScale(m_movie, 1000); wxASSERT(m_lib.GetMoviesError() == noErr); NotifyMovieLoaded(); } //--------------------------------------------------------------------------- // wxQTMediaBackend::Play // // 1) Start the QT movie // 2) Start the movie loading timer // // NOTE: This will still return success even when // the movie is still loading, and as mentioned in wxQTLoadTimer // I don't know of a way to force this to be sync - so if its // still loading the function will return true but the movie will // still be in the stopped state //--------------------------------------------------------------------------- bool wxQTMediaBackend::Play() { m_lib.StartMovie(m_movie); m_bPlaying = true; return m_lib.GetMoviesError() == noErr; } //--------------------------------------------------------------------------- // wxQTMediaBackend::Pause // // 1) Stop the movie // 2) Stop the movie timer //--------------------------------------------------------------------------- bool wxQTMediaBackend::Pause() { m_bPlaying = false; m_lib.StopMovie(m_movie); return m_lib.GetMoviesError() == noErr; } //--------------------------------------------------------------------------- // wxQTMediaBackend::Stop // // 1) Stop the movie // 2) Stop the movie timer // 3) Seek to the beginning of the movie //--------------------------------------------------------------------------- bool wxQTMediaBackend::Stop() { m_bPlaying = false; m_lib.StopMovie(m_movie); if (m_lib.GetMoviesError() == noErr) m_lib.GoToBeginningOfMovie(m_movie); return m_lib.GetMoviesError() == noErr; } //--------------------------------------------------------------------------- // wxQTMediaBackend::GetPlaybackRate // // Get the movie playback rate from ::GetMovieRate //--------------------------------------------------------------------------- double wxQTMediaBackend::GetPlaybackRate() { return ( ((double)m_lib.GetMovieRate(m_movie)) / 0x10000); } //--------------------------------------------------------------------------- // wxQTMediaBackend::SetPlaybackRate // // Convert dRate to Fixed and Set the movie rate through SetMovieRate //--------------------------------------------------------------------------- bool wxQTMediaBackend::SetPlaybackRate(double dRate) { m_lib.SetMovieRate(m_movie, (Fixed) (dRate * 0x10000)); return m_lib.GetMoviesError() == noErr; } //--------------------------------------------------------------------------- // wxQTMediaBackend::SetPosition // // 1) Create a time record struct (TimeRecord) with appropriate values // 2) Pass struct to SetMovieTime //--------------------------------------------------------------------------- bool wxQTMediaBackend::SetPosition(wxLongLong where) { // NB: For some reason SetMovieTime does not work // correctly with the Quicktime Windows SDK (6) // From Muskelkatermann at the wxForum // http://www.solidsteel.nl/users/wxwidgets/viewtopic.php?t=2957 // RN - note that I have not verified this but there // is no harm in calling SetMovieTimeValue instead #if 0 TimeRecord theTimeRecord; memset(&theTimeRecord, 0, sizeof(TimeRecord)); theTimeRecord.value.lo = where.GetLo(); theTimeRecord.scale = m_lib.GetMovieTimeScale(m_movie); theTimeRecord.base = m_lib.GetMovieTimeBase(m_movie); m_lib.SetMovieTime(m_movie, &theTimeRecord); #else m_lib.SetMovieTimeValue(m_movie, where.GetLo()); #endif return (m_lib.GetMoviesError() == noErr); } //--------------------------------------------------------------------------- // wxQTMediaBackend::GetPosition // // 1) Calls GetMovieTime to get the position we are in in the movie // in milliseconds (we called //--------------------------------------------------------------------------- wxLongLong wxQTMediaBackend::GetPosition() { return m_lib.GetMovieTime(m_movie, NULL); } //--------------------------------------------------------------------------- // wxQTMediaBackend::GetVolume // // Gets the volume through GetMovieVolume - which returns a 16 bit short - // // +--------+--------+ // + (1) + (2) + // +--------+--------+ // // (1) first 8 bits are value before decimal // (2) second 8 bits are value after decimal // // Volume ranges from -1.0 (gain but no sound), 0 (no sound and no gain) to // 1 (full gain and sound) //--------------------------------------------------------------------------- double wxQTMediaBackend::GetVolume() { short sVolume = m_lib.GetMovieVolume(m_movie); wxASSERT(m_lib.GetMoviesError() == noErr); if (sVolume & (128 << 8)) //negative - no sound return 0.0; return sVolume / 256.0; } //--------------------------------------------------------------------------- // wxQTMediaBackend::SetVolume // // Sets the volume through SetMovieVolume - which takes a 16 bit short - // // +--------+--------+ // + (1) + (2) + // +--------+--------+ // // (1) first 8 bits are value before decimal // (2) second 8 bits are value after decimal // // Volume ranges from -1.0 (gain but no sound), 0 (no sound and no gain) to // 1 (full gain and sound) //--------------------------------------------------------------------------- bool wxQTMediaBackend::SetVolume(double dVolume) { m_lib.SetMovieVolume(m_movie, (short) (dVolume * 256)); return m_lib.GetMoviesError() == noErr; } //--------------------------------------------------------------------------- // wxQTMediaBackend::GetDuration // // Calls GetMovieDuration //--------------------------------------------------------------------------- wxLongLong wxQTMediaBackend::GetDuration() { return m_lib.GetMovieDuration(m_movie); } //--------------------------------------------------------------------------- // wxQTMediaBackend::GetState // // Determines the current state: // if we are at the beginning, then we are stopped //--------------------------------------------------------------------------- wxMediaState wxQTMediaBackend::GetState() { if (m_bPlaying) return wxMEDIASTATE_PLAYING; else if ( !m_movie || wxQTMediaBackend::GetPosition() == 0 ) return wxMEDIASTATE_STOPPED; else return wxMEDIASTATE_PAUSED; } //--------------------------------------------------------------------------- // wxQTMediaBackend::Cleanup // // Diposes of the movie timer, Disassociates the Movie Controller with // movie and hides it if it exists, and stops and disposes // of the QT movie //--------------------------------------------------------------------------- void wxQTMediaBackend::Cleanup() { m_bPlaying = false; if (m_timer) { delete m_timer; m_timer = NULL; } m_lib.StopMovie(m_movie); if (m_pMC) { Point thePoint; thePoint.h = thePoint.v = 0; m_lib.MCSetVisible(m_pMC, false); m_lib.MCSetMovie(m_pMC, NULL, NULL, thePoint); } m_lib.DisposeMovie(m_movie); m_movie = NULL; } //--------------------------------------------------------------------------- // wxQTMediaBackend::ShowPlayerControls // // Creates a movie controller for the Movie if the user wants it //--------------------------------------------------------------------------- bool wxQTMediaBackend::ShowPlayerControls(wxMediaCtrlPlayerControls flags) { if (m_pMC) { // restore old wndproc wxSetWindowProc((HWND)m_ctrl->GetHWND(), wxWndProc); m_lib.DisposeMovieController(m_pMC); m_pMC = NULL; // movie controller height m_bestSize.y -= 16; } if (flags && m_movie) { Rect rect; wxRect wxrect = m_ctrl->GetClientRect(); // make room for controller if (wxrect.width < 320) wxrect.width = 320; rect.top = (short)wxrect.y; rect.left = (short)wxrect.x; rect.right = (short)(rect.left + wxrect.width); rect.bottom = (short)(rect.top + wxrect.height); if (!m_pMC) { m_pMC = m_lib.NewMovieController(m_movie, &rect, mcTopLeftMovie | // mcScaleMovieToFit | // mcWithBadge | mcWithFrame); m_lib.MCDoAction(m_pMC, 32, (void*)true); // mcActionSetKeysEnabled m_lib.MCSetActionFilterWithRefCon(m_pMC, (WXFARPROC)wxQTMediaBackend::MCFilterProc, (void*)this); m_bestSize.y += 16; // movie controller height // By default the movie controller uses its own colour palette // for the movie which can be bad on some files, so turn it off. // Also turn off its frame / border for the movie // Also take care of a couple of the interface flags here long mcFlags = 0; m_lib.MCDoAction(m_pMC, 39/*mcActionGetFlags*/, (void*)&mcFlags); mcFlags |= // (1<< 0) /*mcFlagSuppressMovieFrame*/ | (1<< 3) /*mcFlagsUseWindowPalette*/ | ((flags & wxMEDIACTRLPLAYERCONTROLS_STEP) ? 0 : (1<< 1) /*mcFlagSuppressStepButtons*/) | ((flags & wxMEDIACTRLPLAYERCONTROLS_VOLUME) ? 0 : (1<< 2) /*mcFlagSuppressSpeakerButton*/) // | (1<< 4) /*mcFlagDontInvalidate*/ // if we take care of repainting ourselves ; m_lib.MCDoAction(m_pMC, 38/*mcActionSetFlags*/, (void*)mcFlags); // intercept the wndproc of our control window wxSetWindowProc((HWND)m_ctrl->GetHWND(), wxQTMediaBackend::QTWndProc); // set the user data of our window wxSetWindowUserData((HWND)m_ctrl->GetHWND(), this); } } NotifyMovieSizeChanged(); return m_lib.GetMoviesError() == noErr; } //--------------------------------------------------------------------------- // wxQTMediaBackend::MCFilterProc (static) // // Callback for when the movie controller recieves a message //--------------------------------------------------------------------------- Boolean wxQTMediaBackend::MCFilterProc(MovieController WXUNUSED(theController), short action, void * WXUNUSED(params), LONG_PTR refCon) { // NB: potential optimisation // if (action == 1) // return 0; wxQTMediaBackend* pThis = (wxQTMediaBackend*)refCon; switch (action) { case 1: // don't process idle events break; case 8: // play button triggered - MC will set movie to opposite state // of current - playing ? paused : playing if (pThis) pThis->m_bPlaying = !(pThis->m_bPlaying); // NB: Sometimes it doesn't redraw properly - // if you click on the button but don't move the mouse // the button will not change its state until you move // mcActionDraw and Refresh/Update combo do nothing // to help this unfortunately break; default: break; } return 0; } //--------------------------------------------------------------------------- // wxQTMediaBackend::GetVideoSize // // Returns the actual size of the QT movie //--------------------------------------------------------------------------- wxSize wxQTMediaBackend::GetVideoSize() const { return m_bestSize; } //--------------------------------------------------------------------------- // wxQTMediaBackend::Move // // Sets the bounds of either the Movie or Movie Controller //--------------------------------------------------------------------------- void wxQTMediaBackend::Move(int WXUNUSED(x), int WXUNUSED(y), int w, int h) { if (m_movie) { // make room for controller if (m_pMC) { if (w < 320) w = 320; Rect theRect = {0, 0, (short)h, (short)w}; m_lib.MCSetControllerBoundsRect(m_pMC, &theRect); } else { Rect theRect = {0, 0, (short)h, (short)w}; m_lib.SetMovieBox(m_movie, &theRect); } wxASSERT(m_lib.GetMoviesError() == noErr); } } //--------------------------------------------------------------------------- // wxQTMediaBackend::OnEraseBackground // // Suggestion from Greg Hazel to repaint the movie when idle // (on pause also) // // TODO: We may be repainting too much here - under what exact circumstances // do we need this? I think Move also repaints correctly for the Movie // Controller, so in that instance we don't need this either //--------------------------------------------------------------------------- void wxQTMediaEvtHandler::OnEraseBackground(wxEraseEvent& evt) { wxQuickTimeLibrary& m_pLib = m_qtb->m_lib; if ( m_qtb->m_pMC ) { // repaint movie controller m_pLib.MCDoAction(m_qtb->m_pMC, 2 /*mcActionDraw*/, m_pLib.GetNativeWindowPort(m_hwnd)); } else if ( m_qtb->m_movie ) { // no movie controller CGrafPtr port = (CGrafPtr)m_pLib.GetNativeWindowPort(m_hwnd); m_pLib.BeginUpdate(port); m_pLib.UpdateMovie(m_qtb->m_movie); wxASSERT(m_pLib.GetMoviesError() == noErr); m_pLib.EndUpdate(port); } else { // no movie // let the system repaint the window evt.Skip(); } } //--------------------------------------------------------------------------- // End QT Backend //--------------------------------------------------------------------------- // in source file that contains stuff you don't directly use #include "wx/html/forcelnk.h" FORCE_LINK_ME(wxmediabackend_qt) #endif // wxUSE_MEDIACTRL && wxUSE_ACTIVEX
radiaku/decoda
libs/wxWidgets/src/msw/mediactrl_qt.cpp
C++
gpl-3.0
45,849
///////////////////////////////////////////////////////////////////////////// // Name: src/msw/gdiobj.cpp // Purpose: wxGDIObject class // Author: Julian Smart // Modified by: // Created: 01/02/97 // RCS-ID: $Id: gdiobj.cpp 40626 2006-08-16 14:53:49Z VS $ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #include "wx/gdiobj.h" #ifndef WX_PRECOMP #include <stdio.h> #include "wx/list.h" #include "wx/utils.h" #include "wx/app.h" #endif #include "wx/msw/private.h" #define M_GDIDATA wx_static_cast(wxGDIRefData*, m_refData) /* void wxGDIObject::IncrementResourceUsage(void) { if ( !M_GDIDATA ) return; // wxDebugMsg("Object %ld about to be incremented: %d\n", (long)this, m_usageCount); M_GDIDATA->m_usageCount ++; }; void wxGDIObject::DecrementResourceUsage(void) { if ( !M_GDIDATA ) return; M_GDIDATA->m_usageCount --; if (wxTheApp) wxTheApp->SetPendingCleanup(true); // wxDebugMsg("Object %ld decremented: %d\n", (long)this, M_GDIDATA->m_usageCount); if (M_GDIDATA->m_usageCount < 0) { char buf[80]; sprintf(buf, "Object %ld usage count is %d\n", (long)this, M_GDIDATA->m_usageCount); wxDebugMsg(buf); } // assert(M_GDIDATA->m_usageCount >= 0); }; */
radiaku/decoda
libs/wxWidgets/src/msw/gdiobj.cpp
C++
gpl-3.0
1,489
/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "context" "strings" "sync" "google.golang.org/grpc/balancer" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/resolver" ) type balancerWrapperBuilder struct { b Balancer // The v1 balancer. } func (bwb *balancerWrapperBuilder) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer { targetAddr := cc.Target() targetSplitted := strings.Split(targetAddr, ":///") if len(targetSplitted) >= 2 { targetAddr = targetSplitted[1] } bwb.b.Start(targetAddr, BalancerConfig{ DialCreds: opts.DialCreds, Dialer: opts.Dialer, }) _, pickfirst := bwb.b.(*pickFirst) bw := &balancerWrapper{ balancer: bwb.b, pickfirst: pickfirst, cc: cc, targetAddr: targetAddr, startCh: make(chan struct{}), conns: make(map[resolver.Address]balancer.SubConn), connSt: make(map[balancer.SubConn]*scState), csEvltr: &balancer.ConnectivityStateEvaluator{}, state: connectivity.Idle, } cc.UpdateBalancerState(connectivity.Idle, bw) go bw.lbWatcher() return bw } func (bwb *balancerWrapperBuilder) Name() string { return "wrapper" } type scState struct { addr Address // The v1 address type. s connectivity.State down func(error) } type balancerWrapper struct { balancer Balancer // The v1 balancer. pickfirst bool cc balancer.ClientConn targetAddr string // Target without the scheme. mu sync.Mutex conns map[resolver.Address]balancer.SubConn connSt map[balancer.SubConn]*scState // This channel is closed when handling the first resolver result. // lbWatcher blocks until this is closed, to avoid race between // - NewSubConn is created, cc wants to notify balancer of state changes; // - Build hasn't return, cc doesn't have access to balancer. startCh chan struct{} // To aggregate the connectivity state. csEvltr *balancer.ConnectivityStateEvaluator state connectivity.State } // lbWatcher watches the Notify channel of the balancer and manages // connections accordingly. func (bw *balancerWrapper) lbWatcher() { <-bw.startCh notifyCh := bw.balancer.Notify() if notifyCh == nil { // There's no resolver in the balancer. Connect directly. a := resolver.Address{ Addr: bw.targetAddr, Type: resolver.Backend, } sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) if err != nil { grpclog.Warningf("Error creating connection to %v. Err: %v", a, err) } else { bw.mu.Lock() bw.conns[a] = sc bw.connSt[sc] = &scState{ addr: Address{Addr: bw.targetAddr}, s: connectivity.Idle, } bw.mu.Unlock() sc.Connect() } return } for addrs := range notifyCh { grpclog.Infof("balancerWrapper: got update addr from Notify: %v\n", addrs) if bw.pickfirst { var ( oldA resolver.Address oldSC balancer.SubConn ) bw.mu.Lock() for oldA, oldSC = range bw.conns { break } bw.mu.Unlock() if len(addrs) <= 0 { if oldSC != nil { // Teardown old sc. bw.mu.Lock() delete(bw.conns, oldA) delete(bw.connSt, oldSC) bw.mu.Unlock() bw.cc.RemoveSubConn(oldSC) } continue } var newAddrs []resolver.Address for _, a := range addrs { newAddr := resolver.Address{ Addr: a.Addr, Type: resolver.Backend, // All addresses from balancer are all backends. ServerName: "", Metadata: a.Metadata, } newAddrs = append(newAddrs, newAddr) } if oldSC == nil { // Create new sc. sc, err := bw.cc.NewSubConn(newAddrs, balancer.NewSubConnOptions{}) if err != nil { grpclog.Warningf("Error creating connection to %v. Err: %v", newAddrs, err) } else { bw.mu.Lock() // For pickfirst, there should be only one SubConn, so the // address doesn't matter. All states updating (up and down) // and picking should all happen on that only SubConn. bw.conns[resolver.Address{}] = sc bw.connSt[sc] = &scState{ addr: addrs[0], // Use the first address. s: connectivity.Idle, } bw.mu.Unlock() sc.Connect() } } else { bw.mu.Lock() bw.connSt[oldSC].addr = addrs[0] bw.mu.Unlock() oldSC.UpdateAddresses(newAddrs) } } else { var ( add []resolver.Address // Addresses need to setup connections. del []balancer.SubConn // Connections need to tear down. ) resAddrs := make(map[resolver.Address]Address) for _, a := range addrs { resAddrs[resolver.Address{ Addr: a.Addr, Type: resolver.Backend, // All addresses from balancer are all backends. ServerName: "", Metadata: a.Metadata, }] = a } bw.mu.Lock() for a := range resAddrs { if _, ok := bw.conns[a]; !ok { add = append(add, a) } } for a, c := range bw.conns { if _, ok := resAddrs[a]; !ok { del = append(del, c) delete(bw.conns, a) // Keep the state of this sc in bw.connSt until its state becomes Shutdown. } } bw.mu.Unlock() for _, a := range add { sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) if err != nil { grpclog.Warningf("Error creating connection to %v. Err: %v", a, err) } else { bw.mu.Lock() bw.conns[a] = sc bw.connSt[sc] = &scState{ addr: resAddrs[a], s: connectivity.Idle, } bw.mu.Unlock() sc.Connect() } } for _, c := range del { bw.cc.RemoveSubConn(c) } } } } func (bw *balancerWrapper) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { bw.mu.Lock() defer bw.mu.Unlock() scSt, ok := bw.connSt[sc] if !ok { return } if s == connectivity.Idle { sc.Connect() } oldS := scSt.s scSt.s = s if oldS != connectivity.Ready && s == connectivity.Ready { scSt.down = bw.balancer.Up(scSt.addr) } else if oldS == connectivity.Ready && s != connectivity.Ready { if scSt.down != nil { scSt.down(errConnClosing) } } sa := bw.csEvltr.RecordTransition(oldS, s) if bw.state != sa { bw.state = sa } bw.cc.UpdateBalancerState(bw.state, bw) if s == connectivity.Shutdown { // Remove state for this sc. delete(bw.connSt, sc) } } func (bw *balancerWrapper) HandleResolvedAddrs([]resolver.Address, error) { bw.mu.Lock() defer bw.mu.Unlock() select { case <-bw.startCh: default: close(bw.startCh) } // There should be a resolver inside the balancer. // All updates here, if any, are ignored. } func (bw *balancerWrapper) Close() { bw.mu.Lock() defer bw.mu.Unlock() select { case <-bw.startCh: default: close(bw.startCh) } bw.balancer.Close() } // The picker is the balancerWrapper itself. // Pick should never return ErrNoSubConnAvailable. // It either blocks or returns error, consistent with v1 balancer Get(). func (bw *balancerWrapper) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { failfast := true // Default failfast is true. if ss, ok := rpcInfoFromContext(ctx); ok { failfast = ss.failfast } a, p, err := bw.balancer.Get(ctx, BalancerGetOptions{BlockingWait: !failfast}) if err != nil { return nil, nil, err } var done func(balancer.DoneInfo) if p != nil { done = func(i balancer.DoneInfo) { p() } } var sc balancer.SubConn bw.mu.Lock() defer bw.mu.Unlock() if bw.pickfirst { // Get the first sc in conns. for _, sc = range bw.conns { break } } else { var ok bool sc, ok = bw.conns[resolver.Address{ Addr: a.Addr, Type: resolver.Backend, ServerName: "", Metadata: a.Metadata, }] if !ok && failfast { return nil, nil, balancer.ErrTransientFailure } if s, ok := bw.connSt[sc]; failfast && (!ok || s.s != connectivity.Ready) { // If the returned sc is not ready and RPC is failfast, // return error, and this RPC will fail. return nil, nil, balancer.ErrTransientFailure } } return sc, done, nil }
drebes/terraform
vendor/google.golang.org/grpc/balancer_v1_wrapper.go
GO
mpl-2.0
8,557
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.search.fetch.subphase; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.ReaderUtil; import org.elasticsearch.common.document.DocumentField; import org.elasticsearch.common.util.CollectionUtils; import org.elasticsearch.script.FieldScript; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.fetch.FetchSubPhase; import org.elasticsearch.search.internal.SearchContext; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; public final class ScriptFieldsFetchSubPhase implements FetchSubPhase { @Override public void hitsExecute(SearchContext context, SearchHit[] hits) throws IOException { if (context.hasScriptFields() == false) { return; } hits = hits.clone(); // don't modify the incoming hits Arrays.sort(hits, Comparator.comparingInt(SearchHit::docId)); int lastReaderId = -1; FieldScript[] leafScripts = null; List<ScriptFieldsContext.ScriptField> scriptFields = context.scriptFields().fields(); final IndexReader reader = context.searcher().getIndexReader(); for (SearchHit hit : hits) { int readerId = ReaderUtil.subIndex(hit.docId(), reader.leaves()); LeafReaderContext leafReaderContext = reader.leaves().get(readerId); if (readerId != lastReaderId) { leafScripts = createLeafScripts(leafReaderContext, scriptFields); lastReaderId = readerId; } int docId = hit.docId() - leafReaderContext.docBase; for (int i = 0; i < leafScripts.length; i++) { leafScripts[i].setDocument(docId); final Object value; try { value = leafScripts[i].execute(); CollectionUtils.ensureNoSelfReferences(value, "ScriptFieldsFetchSubPhase leaf script " + i); } catch (RuntimeException e) { if (scriptFields.get(i).ignoreException()) { continue; } throw e; } if (hit.fieldsOrNull() == null) { hit.fields(new HashMap<>(2)); } String scriptFieldName = scriptFields.get(i).name(); DocumentField hitField = hit.getFields().get(scriptFieldName); if (hitField == null) { final List<Object> values; if (value instanceof Collection) { values = new ArrayList<>((Collection<?>) value); } else { values = Collections.singletonList(value); } hitField = new DocumentField(scriptFieldName, values); hit.getFields().put(scriptFieldName, hitField); } } } } private FieldScript[] createLeafScripts(LeafReaderContext context, List<ScriptFieldsContext.ScriptField> scriptFields) { FieldScript[] scripts = new FieldScript[scriptFields.size()]; for (int i = 0; i < scripts.length; i++) { try { scripts[i] = scriptFields.get(i).script().newInstance(context); } catch (IOException e1) { throw new IllegalStateException("Failed to load script " + scriptFields.get(i).name(), e1); } } return scripts; } }
coding0011/elasticsearch
server/src/main/java/org/elasticsearch/search/fetch/subphase/ScriptFieldsFetchSubPhase.java
Java
apache-2.0
4,508
module.exports = require("./mime-functions"); module.exports.contentTypes = require("./content-types");
stephentcannon/anonistreamr
public/node_modules/nodemailer/node_modules/mailcomposer/node_modules/mimelib-noiconv/index.js
JavaScript
apache-2.0
104
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package upgrade import ( "fmt" "io/ioutil" "os" "path/filepath" "time" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/errors" clientset "k8s.io/client-go/kubernetes" certutil "k8s.io/client-go/util/cert" kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" kubeadmapiv1alpha3 "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1alpha3" kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants" "k8s.io/kubernetes/cmd/kubeadm/app/features" "k8s.io/kubernetes/cmd/kubeadm/app/phases/addons/dns" "k8s.io/kubernetes/cmd/kubeadm/app/phases/addons/proxy" "k8s.io/kubernetes/cmd/kubeadm/app/phases/bootstraptoken/clusterinfo" nodebootstraptoken "k8s.io/kubernetes/cmd/kubeadm/app/phases/bootstraptoken/node" certsphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/certs" kubeletphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/kubelet" patchnodephase "k8s.io/kubernetes/cmd/kubeadm/app/phases/patchnode" "k8s.io/kubernetes/cmd/kubeadm/app/phases/selfhosting" "k8s.io/kubernetes/cmd/kubeadm/app/phases/uploadconfig" "k8s.io/kubernetes/cmd/kubeadm/app/util/apiclient" dryrunutil "k8s.io/kubernetes/cmd/kubeadm/app/util/dryrun" "k8s.io/kubernetes/pkg/util/version" ) var expiry = 180 * 24 * time.Hour // PerformPostUpgradeTasks runs nearly the same functions as 'kubeadm init' would do // Note that the markmaster phase is left out, not needed, and no token is created as that doesn't belong to the upgrade func PerformPostUpgradeTasks(client clientset.Interface, cfg *kubeadmapi.InitConfiguration, newK8sVer *version.Version, dryRun bool) error { errs := []error{} // Upload currently used configuration to the cluster // Note: This is done right in the beginning of cluster initialization; as we might want to make other phases // depend on centralized information from this source in the future if err := uploadconfig.UploadConfiguration(cfg, client); err != nil { errs = append(errs, err) } // Create the new, version-branched kubelet ComponentConfig ConfigMap if err := kubeletphase.CreateConfigMap(cfg, client); err != nil { errs = append(errs, fmt.Errorf("error creating kubelet configuration ConfigMap: %v", err)) } // Write the new kubelet config down to disk and the env file if needed if err := writeKubeletConfigFiles(client, cfg, newK8sVer, dryRun); err != nil { errs = append(errs, err) } // Annotate the node with the crisocket information, sourced either from the InitConfiguration struct or // --cri-socket. // TODO: In the future we want to use something more official like NodeStatus or similar for detecting this properly if err := patchnodephase.AnnotateCRISocket(client, cfg.NodeRegistration.Name, cfg.NodeRegistration.CRISocket); err != nil { errs = append(errs, fmt.Errorf("error uploading crisocket: %v", err)) } // Create/update RBAC rules that makes the bootstrap tokens able to post CSRs if err := nodebootstraptoken.AllowBootstrapTokensToPostCSRs(client); err != nil { errs = append(errs, err) } // Create/update RBAC rules that makes the bootstrap tokens able to get their CSRs approved automatically if err := nodebootstraptoken.AutoApproveNodeBootstrapTokens(client); err != nil { errs = append(errs, err) } // Create/update RBAC rules that makes the nodes to rotate certificates and get their CSRs approved automatically if err := nodebootstraptoken.AutoApproveNodeCertificateRotation(client); err != nil { errs = append(errs, err) } // Upgrade to a self-hosted control plane if possible if err := upgradeToSelfHosting(client, cfg, dryRun); err != nil { errs = append(errs, err) } // TODO: Is this needed to do here? I think that updating cluster info should probably be separate from a normal upgrade // Create the cluster-info ConfigMap with the associated RBAC rules // if err := clusterinfo.CreateBootstrapConfigMapIfNotExists(client, kubeadmconstants.GetAdminKubeConfigPath()); err != nil { // return err //} // Create/update RBAC rules that makes the cluster-info ConfigMap reachable if err := clusterinfo.CreateClusterInfoRBACRules(client); err != nil { errs = append(errs, err) } // Rotate the kube-apiserver cert and key if needed if err := backupAPIServerCertIfNeeded(cfg, dryRun); err != nil { errs = append(errs, err) } // Upgrade kube-dns/CoreDNS and kube-proxy if err := dns.EnsureDNSAddon(cfg, client); err != nil { errs = append(errs, err) } // Remove the old DNS deployment if a new DNS service is now used (kube-dns to CoreDNS or vice versa) if err := removeOldDNSDeploymentIfAnotherDNSIsUsed(cfg, client, dryRun); err != nil { errs = append(errs, err) } if err := proxy.EnsureProxyAddon(cfg, client); err != nil { errs = append(errs, err) } return errors.NewAggregate(errs) } func removeOldDNSDeploymentIfAnotherDNSIsUsed(cfg *kubeadmapi.InitConfiguration, client clientset.Interface, dryRun bool) error { return apiclient.TryRunCommand(func() error { installedDeploymentName := kubeadmconstants.KubeDNS deploymentToDelete := kubeadmconstants.CoreDNS if features.Enabled(cfg.FeatureGates, features.CoreDNS) { installedDeploymentName = kubeadmconstants.CoreDNS deploymentToDelete = kubeadmconstants.KubeDNS } // If we're dry-running, we don't need to wait for the new DNS addon to become ready if !dryRun { dnsDeployment, err := client.AppsV1().Deployments(metav1.NamespaceSystem).Get(installedDeploymentName, metav1.GetOptions{}) if err != nil { return err } if dnsDeployment.Status.ReadyReplicas == 0 { return fmt.Errorf("the DNS deployment isn't ready yet") } } // We don't want to wait for the DNS deployment above to become ready when dryrunning (as it never will) // but here we should execute the DELETE command against the dryrun clientset, as it will only be logged err := apiclient.DeleteDeploymentForeground(client, metav1.NamespaceSystem, deploymentToDelete) if err != nil && !apierrors.IsNotFound(err) { return err } return nil }, 10) } func upgradeToSelfHosting(client clientset.Interface, cfg *kubeadmapi.InitConfiguration, dryRun bool) error { if features.Enabled(cfg.FeatureGates, features.SelfHosting) && !IsControlPlaneSelfHosted(client) { waiter := getWaiter(dryRun, client) // kubeadm will now convert the static Pod-hosted control plane into a self-hosted one fmt.Println("[self-hosted] Creating self-hosted control plane.") if err := selfhosting.CreateSelfHostedControlPlane(kubeadmconstants.GetStaticPodDirectory(), kubeadmconstants.KubernetesDir, cfg, client, waiter, dryRun); err != nil { return fmt.Errorf("error creating self hosted control plane: %v", err) } } return nil } func backupAPIServerCertIfNeeded(cfg *kubeadmapi.InitConfiguration, dryRun bool) error { certAndKeyDir := kubeadmapiv1alpha3.DefaultCertificatesDir shouldBackup, err := shouldBackupAPIServerCertAndKey(certAndKeyDir) if err != nil { // Don't fail the upgrade phase if failing to determine to backup kube-apiserver cert and key. return fmt.Errorf("[postupgrade] WARNING: failed to determine to backup kube-apiserver cert and key: %v", err) } if !shouldBackup { return nil } // If dry-running, just say that this would happen to the user and exit if dryRun { fmt.Println("[postupgrade] Would rotate the API server certificate and key.") return nil } // Don't fail the upgrade phase if failing to backup kube-apiserver cert and key, just continue rotating the cert // TODO: We might want to reconsider this choice. if err := backupAPIServerCertAndKey(certAndKeyDir); err != nil { fmt.Printf("[postupgrade] WARNING: failed to backup kube-apiserver cert and key: %v", err) } return certsphase.CreateAPIServerCertAndKeyFiles(cfg) } func writeKubeletConfigFiles(client clientset.Interface, cfg *kubeadmapi.InitConfiguration, newK8sVer *version.Version, dryRun bool) error { kubeletDir, err := getKubeletDir(dryRun) if err != nil { // The error here should never occur in reality, would only be thrown if /tmp doesn't exist on the machine. return err } errs := []error{} // Write the configuration for the kubelet down to disk so the upgraded kubelet can start with fresh config if err := kubeletphase.DownloadConfig(client, newK8sVer, kubeletDir); err != nil { // Tolerate the error being NotFound when dryrunning, as there is a pretty common scenario: the dryrun process // *would* post the new kubelet-config-1.X configmap that doesn't exist now when we're trying to download it // again. if !(apierrors.IsNotFound(err) && dryRun) { errs = append(errs, fmt.Errorf("error downloading kubelet configuration from the ConfigMap: %v", err)) } } if dryRun { // Print what contents would be written dryrunutil.PrintDryRunFile(kubeadmconstants.KubeletConfigurationFileName, kubeletDir, kubeadmconstants.KubeletRunDirectory, os.Stdout) } envFilePath := filepath.Join(kubeadmconstants.KubeletRunDirectory, kubeadmconstants.KubeletEnvFileName) if _, err := os.Stat(envFilePath); os.IsNotExist(err) { // Write env file with flags for the kubelet to use. We do not need to write the --register-with-taints for the master, // as we handle that ourselves in the markmaster phase // TODO: Maybe we want to do that some time in the future, in order to remove some logic from the markmaster phase? if err := kubeletphase.WriteKubeletDynamicEnvFile(&cfg.NodeRegistration, cfg.FeatureGates, false, kubeletDir); err != nil { errs = append(errs, fmt.Errorf("error writing a dynamic environment file for the kubelet: %v", err)) } if dryRun { // Print what contents would be written dryrunutil.PrintDryRunFile(kubeadmconstants.KubeletEnvFileName, kubeletDir, kubeadmconstants.KubeletRunDirectory, os.Stdout) } } return errors.NewAggregate(errs) } // getWaiter gets the right waiter implementation for the right occasion // TODO: Consolidate this with what's in init.go? func getWaiter(dryRun bool, client clientset.Interface) apiclient.Waiter { if dryRun { return dryrunutil.NewWaiter() } return apiclient.NewKubeWaiter(client, 30*time.Minute, os.Stdout) } // getKubeletDir gets the kubelet directory based on whether the user is dry-running this command or not. // TODO: Consolidate this with similar funcs? func getKubeletDir(dryRun bool) (string, error) { if dryRun { return ioutil.TempDir("", "kubeadm-upgrade-dryrun") } return kubeadmconstants.KubeletRunDirectory, nil } // backupAPIServerCertAndKey backups the old cert and key of kube-apiserver to a specified directory. func backupAPIServerCertAndKey(certAndKeyDir string) error { subDir := filepath.Join(certAndKeyDir, "expired") if err := os.Mkdir(subDir, 0766); err != nil { return fmt.Errorf("failed to created backup directory %s: %v", subDir, err) } filesToMove := map[string]string{ filepath.Join(certAndKeyDir, kubeadmconstants.APIServerCertName): filepath.Join(subDir, kubeadmconstants.APIServerCertName), filepath.Join(certAndKeyDir, kubeadmconstants.APIServerKeyName): filepath.Join(subDir, kubeadmconstants.APIServerKeyName), } return moveFiles(filesToMove) } // moveFiles moves files from one directory to another. func moveFiles(files map[string]string) error { filesToRecover := map[string]string{} for from, to := range files { if err := os.Rename(from, to); err != nil { return rollbackFiles(filesToRecover, err) } filesToRecover[to] = from } return nil } // rollbackFiles moves the files back to the original directory. func rollbackFiles(files map[string]string, originalErr error) error { errs := []error{originalErr} for from, to := range files { if err := os.Rename(from, to); err != nil { errs = append(errs, err) } } return fmt.Errorf("couldn't move these files: %v. Got errors: %v", files, errors.NewAggregate(errs)) } // shouldBackupAPIServerCertAndKey checks if the cert of kube-apiserver will be expired in 180 days. func shouldBackupAPIServerCertAndKey(certAndKeyDir string) (bool, error) { apiServerCert := filepath.Join(certAndKeyDir, kubeadmconstants.APIServerCertName) certs, err := certutil.CertsFromFile(apiServerCert) if err != nil { return false, fmt.Errorf("couldn't load the certificate file %s: %v", apiServerCert, err) } if len(certs) == 0 { return false, fmt.Errorf("no certificate data found") } if time.Now().Sub(certs[0].NotBefore) > expiry { return true, nil } return false, nil }
abgworrall/kubernetes
cmd/kubeadm/app/phases/upgrade/postupgrade.go
GO
apache-2.0
13,012
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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. */ package org.jetbrains.plugins.groovy.lang.resolve.ast.builder.strategy; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.impl.light.LightMethodBuilder; import com.intellij.psi.impl.light.LightPsiClassBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil; import org.jetbrains.plugins.groovy.lang.resolve.ast.builder.BuilderAnnotationContributor; import org.jetbrains.plugins.groovy.lang.resolve.ast.builder.BuilderHelperLightPsiClass; import org.jetbrains.plugins.groovy.transformations.TransformationContext; import java.util.Objects; import static org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType; public class DefaultBuilderStrategySupport extends BuilderAnnotationContributor { public static final String DEFAULT_STRATEGY_NAME = "DefaultStrategy"; @Override public void applyTransformation(@NotNull TransformationContext context) { new DefaultBuilderStrategyHandler(context).doProcess(); } private static class DefaultBuilderStrategyHandler { private final @NotNull TransformationContext myContext; private final @NotNull GrTypeDefinition myContainingClass; private DefaultBuilderStrategyHandler(@NotNull TransformationContext context) { myContext = context; myContainingClass = context.getCodeClass(); } public void doProcess() { processTypeDefinition(); processMethods(); } private void processTypeDefinition() { final PsiAnnotation builderAnno = PsiImplUtil.getAnnotation(myContainingClass, BUILDER_FQN); if (!isApplicable(builderAnno, DEFAULT_STRATEGY_NAME)) return; boolean includeSuper = isIncludeSuperProperties(builderAnno); final PsiClass builderClass = createBuilderClass(builderAnno, getFields(myContext, includeSuper)); myContext.addMethod(createBuilderMethod(builderClass, builderAnno)); myContext.addInnerClass(builderClass); } @NotNull private LightPsiClassBuilder createBuilderClass(@NotNull final PsiAnnotation annotation, @NotNull PsiVariable[] setters) { return createBuilderClass(annotation, setters, null); } @NotNull private LightPsiClassBuilder createBuilderClass(@NotNull final PsiAnnotation annotation, @NotNull PsiVariable[] setters, @Nullable PsiType builtType) { final LightPsiClassBuilder builderClass = new BuilderHelperLightPsiClass( myContainingClass, getBuilderClassName(annotation, myContainingClass) ); for (PsiVariable field : setters) { LightMethodBuilder setter = createFieldSetter(builderClass, field, annotation); builderClass.addMethod(setter); } final LightMethodBuilder buildMethod = createBuildMethod( annotation, builtType == null ? createType(myContainingClass) : builtType ); return builderClass.addMethod(buildMethod); } @NotNull private LightMethodBuilder createBuilderMethod(@NotNull PsiClass builderClass, @NotNull PsiAnnotation annotation) { final LightMethodBuilder builderMethod = new LightMethodBuilder(myContext.getManager(), getBuilderMethodName(annotation)); builderMethod.addModifier(PsiModifier.STATIC); builderMethod.setOriginInfo(ORIGIN_INFO); builderMethod.setNavigationElement(annotation); builderMethod.setMethodReturnType(createType(builderClass)); return builderMethod; } private void processMethods() { for (GrMethod method : myContext.getCodeClass().getCodeMethods()) { processMethod(method); } } private void processMethod(@NotNull GrMethod method) { final PsiAnnotation annotation = PsiImplUtil.getAnnotation(method, BUILDER_FQN); if (!isApplicable(annotation, DEFAULT_STRATEGY_NAME)) return; if (method.isConstructor()) { processConstructor(method, annotation); } else if (method.hasModifierProperty(PsiModifier.STATIC)) { processFactoryMethod(method, annotation); } } private void processConstructor(@NotNull GrMethod method, PsiAnnotation annotation) { PsiClass builderClass = createBuilderClass(annotation, method.getParameters()); myContext.addMethod(createBuilderMethod(builderClass, annotation)); myContext.addInnerClass(builderClass); } private void processFactoryMethod(@NotNull GrMethod method, PsiAnnotation annotation) { PsiClass builderClass = createBuilderClass(annotation, method.getParameters(), method.getReturnType()); myContext.addMethod(createBuilderMethod(builderClass, annotation)); myContext.addInnerClass(builderClass); } @NotNull private static String getBuilderMethodName(@NotNull PsiAnnotation annotation) { final String builderMethodName = AnnotationUtil.getDeclaredStringAttributeValue(annotation, "builderMethodName"); return StringUtil.isEmpty(builderMethodName) ? "builder" : builderMethodName; } } @NotNull public static String getBuilderClassName(@NotNull PsiAnnotation annotation, @NotNull GrTypeDefinition clazz) { final String builderClassName = AnnotationUtil.getDeclaredStringAttributeValue(annotation, "builderClassName"); return builderClassName == null ? String.format("%s%s", clazz.getName(), "Builder") : builderClassName; } @NotNull public static LightMethodBuilder createBuildMethod(@NotNull PsiAnnotation annotation, @NotNull PsiType builtType) { final LightMethodBuilder buildMethod = new LightMethodBuilder(annotation.getManager(), getBuildMethodName(annotation)); buildMethod.setOriginInfo(ORIGIN_INFO); buildMethod.setMethodReturnType(builtType); return buildMethod; } @NotNull public static LightMethodBuilder createFieldSetter(@NotNull PsiClass builderClass, @NotNull PsiVariable field, @NotNull PsiAnnotation annotation) { String name = Objects.requireNonNull(field.getName()); return createFieldSetter(builderClass, name, field.getType(), annotation, field); } @NotNull public static LightMethodBuilder createFieldSetter(@NotNull PsiClass builderClass, @NotNull String name, @NotNull PsiType type, @NotNull PsiAnnotation annotation, @NotNull PsiElement navigationElement) { final LightMethodBuilder fieldSetter = new LightMethodBuilder(builderClass.getManager(), getFieldMethodName(annotation, name)); fieldSetter.addModifier(PsiModifier.PUBLIC); fieldSetter.addParameter(name, type); fieldSetter.setContainingClass(builderClass); fieldSetter.setMethodReturnType(JavaPsiFacade.getElementFactory(builderClass.getProject()).createType(builderClass)); fieldSetter.setNavigationElement(navigationElement); fieldSetter.setOriginInfo(ORIGIN_INFO); return fieldSetter; } @NotNull public static String getFieldMethodName(@NotNull PsiAnnotation annotation, @NotNull String fieldName) { final String prefix = AnnotationUtil.getDeclaredStringAttributeValue(annotation, "prefix"); return StringUtil.isEmpty(prefix) ? fieldName : String.format("%s%s", prefix, StringUtil.capitalize(fieldName)); } @NotNull private static String getBuildMethodName(@NotNull PsiAnnotation annotation) { final String buildMethodName = AnnotationUtil.getDeclaredStringAttributeValue(annotation, "buildMethodName"); return StringUtil.isEmpty(buildMethodName) ? "build" : buildMethodName; } }
goodwinnk/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/builder/strategy/DefaultBuilderStrategySupport.java
Java
apache-2.0
8,689
/* * Copyright 2004,2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.registry.ws.client.test.security; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.ResourceImpl; import org.wso2.carbon.registry.core.utils.RegistryUtils; public class ContinuousOperations extends SecurityTestSetup { public ContinuousOperations(String text) { super(text); } public void testContinousDelete() throws Exception { int iterations = 100; for (int i = 0; i < iterations; i++) { Resource res1 = registry.newResource(); byte[] r1content = RegistryUtils.encodeString("R2 content"); res1.setContent(r1content); String path = "/con-delete/test/" + i + 1; registry.put(path, res1); Resource resource1 = registry.get(path); assertEquals("File content is not matching", RegistryUtils.decodeBytes((byte[]) resource1.getContent()), RegistryUtils.decodeBytes((byte[]) res1.getContent())); registry.delete(path); boolean value = false; if (registry.resourceExists(path)) { value = true; } assertFalse("Resoruce not found at the path", value); res1.discard(); resource1.discard(); Thread.sleep(100); } } public void testContinuousUpdate() throws Exception { int iterations = 100; for (int i = 0; i < iterations; i++) { Resource res1 = registry.newResource(); byte[] r1content = RegistryUtils.encodeString("R2 content"); res1.setContent(r1content); String path = "/con-delete/test-update/" + i + 1; registry.put(path, res1); Resource resource1 = registry.get(path); assertEquals("File content is not matching", RegistryUtils.decodeBytes((byte[]) resource1.getContent()), RegistryUtils.decodeBytes((byte[]) res1.getContent())); Resource resource = new ResourceImpl(); byte[] r1content1 = RegistryUtils.encodeString("R2 content updated"); resource.setContent(r1content1); resource.setProperty("abc", "abc"); registry.put(path, resource); Resource resource2 = registry.get(path); assertEquals("File content is not matching", RegistryUtils.decodeBytes((byte[]) resource.getContent()), RegistryUtils.decodeBytes((byte[]) resource2.getContent())); resource.discard(); res1.discard(); resource1.discard(); resource2.discard(); Thread.sleep(100); } } }
thusithathilina/carbon-registry
components/registry/org.wso2.carbon.registry.ws.client/src/main/ws-test/org/wso2/carbon/registry/ws/client/test/security/ContinuousOperations.java
Java
apache-2.0
3,380
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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.springframework.boot.test.autoconfigure.jooq; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; /** * {@link ImportAutoConfiguration Auto-configuration imports} for typical jOOQ tests. Most * tests should consider using {@link JooqTest @JooqTest} rather than using this * annotation directly. * * @author Michael Simons * @since 2.0.0 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @ImportAutoConfiguration public @interface AutoConfigureJooq { }
Buzzardo/spring-boot
spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/AutoConfigureJooq.java
Java
apache-2.0
1,395
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: --cfg fooA --cfg fooB // fooA AND !bar #[cfg(fooA, not(bar))] fn foo1() -> int { 1 } // !fooA AND !bar #[cfg(not(fooA), not(bar))] fn foo2() -> int { 2 } // fooC OR (fooB AND !bar) #[cfg(fooC)] #[cfg(fooB, not(bar))] fn foo2() -> int { 3 } // fooA AND bar #[cfg(fooA, bar)] fn foo3() -> int { 2 } // !(fooA AND bar) #[cfg(not(fooA, bar))] fn foo3() -> int { 3 } pub fn main() { assert_eq!(1, foo1()); assert_eq!(3, foo2()); assert_eq!(3, foo3()); }
erickt/rust
src/test/run-pass/cfgs-on-items.rs
Rust
apache-2.0
957
/* ******************************************************************************* * Copyright (C) 2002-2012, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* */ package com.ibm.icu.dev.util; import java.util.Collection; import java.util.Iterator; import java.util.Map; import com.ibm.icu.text.UnicodeSet; import com.ibm.icu.text.UnicodeSetIterator; public abstract class Visitor { public void doAt(Object item) { if (item instanceof Collection) { doAt((Collection) item); } else if (item instanceof Map) { doAt((Map) item); } else if (item instanceof Object[]) { doAt((Object[]) item); } else if (item instanceof UnicodeSet) { doAt((UnicodeSet) item); } else { doSimpleAt(item); } } public int count(Object item) { if (item instanceof Collection) { return ((Collection) item).size(); } else if (item instanceof Map) { return ((Map) item).size(); } else if (item instanceof Object[]) { return ((Object[]) item).length; } else if (item instanceof UnicodeSet) { return ((UnicodeSet) item).size(); } else { return 1; } } // the default implementation boxing public void doAt(int o) { doSimpleAt(new Integer(o)); } public void doAt(double o) { doSimpleAt(new Double(o)); } public void doAt(char o) { doSimpleAt(new Character(o)); } // for subclassing protected void doAt (Collection c) { if (c.size() == 0) doBefore(c, null); Iterator it = c.iterator(); boolean first = true; Object last = null; while (it.hasNext()) { Object item = it.next(); if (first) { doBefore(c, item); first = false; } else { doBetween(c, last, item); } doAt(last=item); } doAfter(c, last); } protected void doAt (Map c) { doAt(c.entrySet()); } protected void doAt (UnicodeSet c) { if (c.size() == 0) doBefore(c, null); UnicodeSetIterator it = new UnicodeSetIterator(c); boolean first = true; Object last = null; Object item; CodePointRange cpr0 = new CodePointRange(); CodePointRange cpr1 = new CodePointRange(); CodePointRange cpr; while(it.nextRange()) { if (it.codepoint == UnicodeSetIterator.IS_STRING) { item = it.string; } else { cpr = last == cpr0 ? cpr1 : cpr0; // make sure we don't override last cpr.codepoint = it.codepoint; cpr.codepointEnd = it.codepointEnd; item = cpr; } if (!first) { doBefore(c, item); first = true; } else { doBetween(c, last, item); } doAt(last = item); } doAfter(c, last); } protected void doAt (Object[] c) { doBefore(c, c.length == 0 ? null : c[0]); Object last = null; for (int i = 0; i < c.length; ++i) { if (i != 0) doBetween(c, last, c[i]); doAt(last = c[i]); } doAfter(c, last); } public static class CodePointRange{ public int codepoint, codepointEnd; } // ===== MUST BE OVERRIDEN ===== abstract protected void doBefore(Object container, Object item); abstract protected void doBetween(Object container, Object lastItem, Object nextItem); abstract protected void doAfter(Object container, Object item); abstract protected void doSimpleAt(Object o); }
nightauer/quickdic-dictionary.dictionary
jars/icu4j-52_1/main/tests/framework/src/com/ibm/icu/dev/util/Visitor.java
Java
apache-2.0
4,008
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html><head><title>FindBugs Bug Descriptions</title> <link rel="stylesheet" type="text/css" href="findbugs.css"/> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/> </head><body> <table width="100%"><tr> <td bgcolor="#b9b9fe" valign="top" align="left" width="20%"> <table width="100%" cellspacing="0" border="0"> <tr><td><a class="sidebar" href="index.html"><img src="umdFindbugs.png" alt="FindBugs"></a></td></tr> <tr><td>&nbsp;</td></tr> <tr><td><b>Docs and Info</b></td></tr> <tr><td><font size="-1"><a class="sidebar" href="findbugs2.html">FindBugs 2.0</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="demo.html">Demo and data</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="users.html">Users and supporters</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="http://findbugs.blogspot.com/">FindBugs blog</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="factSheet.html">Fact sheet</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="manual/index.html">Manual</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="ja/manual/index.html">Manual(ja/&#26085;&#26412;&#35486;)</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="FAQ.html">FAQ</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="bugDescriptions.html">Bug descriptions</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="mailingLists.html">Mailing lists</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="publications.html">Documents and Publications</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="links.html">Links</a></font></td></tr> <tr><td>&nbsp;</td></tr> <tr><td><a class="sidebar" href="downloads.html"><b>Downloads</b></a></td></tr> <tr><td>&nbsp;</td></tr> <tr><td><a class="sidebar" href="http://www.cafeshops.com/findbugs"><b>FindBugs Swag</b></a></td></tr> <tr><td>&nbsp;</td></tr> <tr><td><b>Development</b></td></tr> <tr><td><font size="-1"><a class="sidebar" href="http://sourceforge.net/tracker/?group_id=96405">Open bugs</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="reportingBugs.html">Reporting bugs</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="contributing.html">Contributing</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="team.html">Dev team</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="api/index.html">API</a> <a class="sidebar" href="api/overview-summary.html">[no frames]</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="Changes.html">Change log</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="http://sourceforge.net/projects/findbugs">SF project page</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="http://code.google.com/p/findbugs/source/browse/">Browse source</a></font></td></tr> <tr><td><font size="-1"><a class="sidebar" href="http://code.google.com/p/findbugs/source/list">Latest code changes</a></font></td></tr> </table> </td> <td align="left" valign="top"> <h1>FindBugs Bug Descriptions</h1> <p>This document lists the standard bug patterns reported by <a href="http://findbugs.sourceforge.net">FindBugs</a> version 2.0.3.</p> <h2>Summary</h2> <table width="100%"> <tr bgcolor="#b9b9fe"><th>Description</th><th>Category</th></tr> <tr bgcolor="#eeeeee"><td><a href="#BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS">BC: Equals method should not assume anything about the type of its argument</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#BIT_SIGNED_CHECK">BIT: Check for sign of bitwise operation</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#CN_IDIOM">CN: Class implements Cloneable but does not define or use clone method</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#CN_IDIOM_NO_SUPER_CALL">CN: clone method does not call super.clone()</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE">CN: Class defines clone() but doesn't implement Cloneable</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#CO_ABSTRACT_SELF">Co: Abstract class defines covariant compareTo() method</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#CO_SELF_NO_OBJECT">Co: Covariant compareTo() method defined</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#DE_MIGHT_DROP">DE: Method might drop exception</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DE_MIGHT_IGNORE">DE: Method might ignore exception</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#DMI_ENTRY_SETS_MAY_REUSE_ENTRY_OBJECTS">DMI: Adding elements of an entry set may fail due to reuse of Entry objects</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DMI_RANDOM_USED_ONLY_ONCE">DMI: Random object created and used only once</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#DMI_USING_REMOVEALL_TO_CLEAR_COLLECTION">DMI: Don't use removeAll to clear a collection</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DM_EXIT">Dm: Method invokes System.exit(...)</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#DM_RUN_FINALIZERS_ON_EXIT">Dm: Method invokes dangerous method runFinalizersOnExit</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#ES_COMPARING_PARAMETER_STRING_WITH_EQ">ES: Comparison of String parameter using == or !=</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#ES_COMPARING_STRINGS_WITH_EQ">ES: Comparison of String objects using == or !=</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#EQ_ABSTRACT_SELF">Eq: Abstract class defines covariant equals() method</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS">Eq: Equals checks for incompatible operand</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#EQ_COMPARETO_USE_OBJECT_EQUALS">Eq: Class defines compareTo(...) and uses Object.equals()</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#EQ_GETCLASS_AND_CLASS_CONSTANT">Eq: equals method fails for subtypes</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#EQ_SELF_NO_OBJECT">Eq: Covariant equals() method defined</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#FI_EMPTY">FI: Empty finalizer should be deleted</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#FI_EXPLICIT_INVOCATION">FI: Explicit invocation of finalizer</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#FI_FINALIZER_NULLS_FIELDS">FI: Finalizer nulls fields</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#FI_FINALIZER_ONLY_NULLS_FIELDS">FI: Finalizer only nulls fields</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#FI_MISSING_SUPER_CALL">FI: Finalizer does not call superclass finalizer</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#FI_NULLIFY_SUPER">FI: Finalizer nullifies superclass finalizer</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#FI_USELESS">FI: Finalizer does nothing but call superclass finalizer</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#VA_FORMAT_STRING_USES_NEWLINE">FS: Format string should use %n rather than \n</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#GC_UNCHECKED_TYPE_IN_GENERIC_CALL">GC: Unchecked type in generic call</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#HE_EQUALS_NO_HASHCODE">HE: Class defines equals() but not hashCode()</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#HE_EQUALS_USE_HASHCODE">HE: Class defines equals() and uses Object.hashCode()</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#HE_HASHCODE_NO_EQUALS">HE: Class defines hashCode() but not equals()</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#HE_HASHCODE_USE_OBJECT_EQUALS">HE: Class defines hashCode() and uses Object.equals()</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#HE_INHERITS_EQUALS_USE_HASHCODE">HE: Class inherits equals() and uses Object.hashCode()</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION">IC: Superclass uses subclass during initialization</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#IMSE_DONT_CATCH_IMSE">IMSE: Dubious catching of IllegalMonitorStateException</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#ISC_INSTANTIATE_STATIC_CLASS">ISC: Needless instantiation of class that only supplies static methods</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#IT_NO_SUCH_ELEMENT">It: Iterator next() method can't throw NoSuchElementException</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION">J2EE: Store of non serializable object into HttpSession</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_CLASS">JCIP: Fields of immutable classes should be final</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_BOOLEAN_RETURN_NULL">NP: Method with Boolean return type returns explicit null</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_CLONE_COULD_RETURN_NULL">NP: Clone method may return null</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT">NP: equals() method does not check for null argument</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_TOSTRING_COULD_RETURN_NULL">NP: toString method may return null</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#NM_CLASS_NAMING_CONVENTION">Nm: Class names should start with an upper case letter</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NM_CLASS_NOT_EXCEPTION">Nm: Class is not derived from an Exception, even though it is named as such</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#NM_CONFUSING">Nm: Confusing method names</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NM_FIELD_NAMING_CONVENTION">Nm: Field names should start with a lower case letter</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#NM_FUTURE_KEYWORD_USED_AS_IDENTIFIER">Nm: Use of identifier that is a keyword in later versions of Java</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NM_FUTURE_KEYWORD_USED_AS_MEMBER_IDENTIFIER">Nm: Use of identifier that is a keyword in later versions of Java</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#NM_METHOD_NAMING_CONVENTION">Nm: Method names should start with a lower case letter</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NM_SAME_SIMPLE_NAME_AS_INTERFACE">Nm: Class names shouldn't shadow simple name of implemented interface</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#NM_SAME_SIMPLE_NAME_AS_SUPERCLASS">Nm: Class names shouldn't shadow simple name of superclass</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NM_VERY_CONFUSING_INTENTIONAL">Nm: Very confusing method names (but perhaps intentional)</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#NM_WRONG_PACKAGE_INTENTIONAL">Nm: Method doesn't override method in superclass due to wrong package for parameter</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#ODR_OPEN_DATABASE_RESOURCE">ODR: Method may fail to close database resource</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#ODR_OPEN_DATABASE_RESOURCE_EXCEPTION_PATH">ODR: Method may fail to close database resource on exception</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#OS_OPEN_STREAM">OS: Method may fail to close stream</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#OS_OPEN_STREAM_EXCEPTION_PATH">OS: Method may fail to close stream on exception</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#PZ_DONT_REUSE_ENTRY_OBJECTS_IN_ITERATORS">PZ: Don't reuse entry objects in iterators</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#RC_REF_COMPARISON_BAD_PRACTICE">RC: Suspicious reference comparison to constant</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#RC_REF_COMPARISON_BAD_PRACTICE_BOOLEAN">RC: Suspicious reference comparison of Boolean values</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#RR_NOT_CHECKED">RR: Method ignores results of InputStream.read()</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SR_NOT_CHECKED">RR: Method ignores results of InputStream.skip()</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#RV_NEGATING_RESULT_OF_COMPARETO">RV: Negating the result of compareTo()/compare()</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#RV_RETURN_VALUE_IGNORED_BAD_PRACTICE">RV: Method ignores exceptional return value</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#SI_INSTANCE_BEFORE_FINALS_ASSIGNED">SI: Static initializer creates instance before all static final fields assigned</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SW_SWING_METHODS_INVOKED_IN_SWING_THREAD">SW: Certain swing methods needs to be invoked in Swing thread</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#SE_BAD_FIELD">Se: Non-transient non-serializable instance field in serializable class</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SE_BAD_FIELD_INNER_CLASS">Se: Non-serializable class has a serializable inner class</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#SE_BAD_FIELD_STORE">Se: Non-serializable value stored into instance field of a serializable class</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SE_COMPARATOR_SHOULD_BE_SERIALIZABLE">Se: Comparator doesn't implement Serializable</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#SE_INNER_CLASS">Se: Serializable inner class</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SE_NONFINAL_SERIALVERSIONID">Se: serialVersionUID isn't final</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#SE_NONLONG_SERIALVERSIONID">Se: serialVersionUID isn't long</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SE_NONSTATIC_SERIALVERSIONID">Se: serialVersionUID isn't static</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#SE_NO_SUITABLE_CONSTRUCTOR">Se: Class is Serializable but its superclass doesn't define a void constructor</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SE_NO_SUITABLE_CONSTRUCTOR_FOR_EXTERNALIZATION">Se: Class is Externalizable but doesn't define a void constructor</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#SE_READ_RESOLVE_MUST_RETURN_OBJECT">Se: The readResolve method must be declared with a return type of Object. </a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SE_TRANSIENT_FIELD_NOT_RESTORED">Se: Transient field that isn't set by deserialization. </a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#SE_NO_SERIALVERSIONID">SnVI: Class is Serializable, but doesn't define serialVersionUID</a></td><td>Bad practice</td></tr> <tr bgcolor="#eeeeee"><td><a href="#UI_INHERITANCE_UNSAFE_GETRESOURCE">UI: Usage of GetResource may be unsafe if class is extended</a></td><td>Bad practice</td></tr> <tr bgcolor="#ffffff"><td><a href="#BC_IMPOSSIBLE_CAST">BC: Impossible cast</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#BC_IMPOSSIBLE_DOWNCAST">BC: Impossible downcast</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY">BC: Impossible downcast of toArray() result</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#BC_IMPOSSIBLE_INSTANCEOF">BC: instanceof will always return false</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#BIT_ADD_OF_SIGNED_BYTE">BIT: Bitwise add of signed byte value</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#BIT_AND">BIT: Incompatible bit masks</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#BIT_AND_ZZ">BIT: Check to see if ((...) & 0) == 0</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#BIT_IOR">BIT: Incompatible bit masks</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#BIT_IOR_OF_SIGNED_BYTE">BIT: Bitwise OR of signed byte value</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#BIT_SIGNED_CHECK_HIGH_BIT">BIT: Check for sign of bitwise operation</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#BOA_BADLY_OVERRIDDEN_ADAPTER">BOA: Class overrides a method implemented in super class Adapter wrongly</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#ICAST_BAD_SHIFT_AMOUNT">BSHIFT: 32 bit int shifted by an amount not in the range -31..31</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#BX_UNBOXED_AND_COERCED_FOR_TERNARY_OPERATOR">Bx: Primitive value is unboxed and coerced for ternary operator</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#CO_COMPARETO_RESULTS_MIN_VALUE">Co: compareTo()/compare() returns Integer.MIN_VALUE</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#DLS_DEAD_LOCAL_INCREMENT_IN_RETURN">DLS: Useless increment in return statement</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DLS_DEAD_STORE_OF_CLASS_LITERAL">DLS: Dead store of class literal</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#DLS_OVERWRITTEN_INCREMENT">DLS: Overwritten increment</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DMI_ARGUMENTS_WRONG_ORDER">DMI: Reversed method arguments</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#DMI_BAD_MONTH">DMI: Bad constant value for month</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DMI_BIGDECIMAL_CONSTRUCTED_FROM_DOUBLE">DMI: BigDecimal constructed from double that isn't represented precisely</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#DMI_CALLING_NEXT_FROM_HASNEXT">DMI: hasNext method invokes next</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DMI_COLLECTIONS_SHOULD_NOT_CONTAIN_THEMSELVES">DMI: Collections should not contain themselves</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#DMI_DOH">DMI: D'oh! A nonsensical method invocation</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DMI_INVOKING_HASHCODE_ON_ARRAY">DMI: Invocation of hashCode on an array</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#DMI_LONG_BITS_TO_DOUBLE_INVOKED_ON_INT">DMI: Double.longBitsToDouble invoked on an int</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DMI_VACUOUS_SELF_COLLECTION_CALL">DMI: Vacuous call to collections</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#DMI_ANNOTATION_IS_NOT_VISIBLE_TO_REFLECTION">Dm: Can't use reflection to check for presence of annotation without runtime retention</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DMI_FUTILE_ATTEMPT_TO_CHANGE_MAXPOOL_SIZE_OF_SCHEDULED_THREAD_POOL_EXECUTOR">Dm: Futile attempt to change max pool size of ScheduledThreadPoolExecutor</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#DMI_SCHEDULED_THREAD_POOL_EXECUTOR_WITH_ZERO_CORE_THREADS">Dm: Creation of ScheduledThreadPoolExecutor with zero core threads</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DMI_VACUOUS_CALL_TO_EASYMOCK_METHOD">Dm: Useless/vacuous call to EasyMock method</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#EC_ARRAY_AND_NONARRAY">EC: equals() used to compare array and nonarray</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#EC_BAD_ARRAY_COMPARE">EC: Invocation of equals() on an array, which is equivalent to ==</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#EC_INCOMPATIBLE_ARRAY_COMPARE">EC: equals(...) used to compare incompatible arrays</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#EC_NULL_ARG">EC: Call to equals(null)</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#EC_UNRELATED_CLASS_AND_INTERFACE">EC: Call to equals() comparing unrelated class and interface</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#EC_UNRELATED_INTERFACES">EC: Call to equals() comparing different interface types</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#EC_UNRELATED_TYPES">EC: Call to equals() comparing different types</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#EC_UNRELATED_TYPES_USING_POINTER_EQUALITY">EC: Using pointer equality to compare different types</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#EQ_ALWAYS_FALSE">Eq: equals method always returns false</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#EQ_ALWAYS_TRUE">Eq: equals method always returns true</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#EQ_COMPARING_CLASS_NAMES">Eq: equals method compares class names rather than class objects</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#EQ_DONT_DEFINE_EQUALS_FOR_ENUM">Eq: Covariant equals() method defined for enum</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#EQ_OTHER_NO_OBJECT">Eq: equals() method defined that doesn't override equals(Object)</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#EQ_OTHER_USE_OBJECT">Eq: equals() method defined that doesn't override Object.equals(Object)</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC">Eq: equals method overrides equals in superclass and may not be symmetric</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#EQ_SELF_USE_OBJECT">Eq: Covariant equals() method defined, Object.equals(Object) inherited</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#FE_TEST_IF_EQUAL_TO_NOT_A_NUMBER">FE: Doomed test for equality to NaN</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#VA_FORMAT_STRING_BAD_ARGUMENT">FS: Format string placeholder incompatible with passed argument</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#VA_FORMAT_STRING_BAD_CONVERSION">FS: The type of a supplied argument doesn't match format specifier</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#VA_FORMAT_STRING_EXPECTED_MESSAGE_FORMAT_SUPPLIED">FS: MessageFormat supplied where printf style format expected</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#VA_FORMAT_STRING_EXTRA_ARGUMENTS_PASSED">FS: More arguments are passed than are actually used in the format string</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#VA_FORMAT_STRING_ILLEGAL">FS: Illegal format string</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#VA_FORMAT_STRING_MISSING_ARGUMENT">FS: Format string references missing argument</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#VA_FORMAT_STRING_NO_PREVIOUS_ARGUMENT">FS: No previous argument for format string</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#GC_UNRELATED_TYPES">GC: No relationship between generic parameter and method argument</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#HE_SIGNATURE_DECLARES_HASHING_OF_UNHASHABLE_CLASS">HE: Signature declares use of unhashable class in hashed construct</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#HE_USE_OF_UNHASHABLE_CLASS">HE: Use of class without a hashCode() method in a hashed data structure</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#ICAST_INT_2_LONG_AS_INSTANT">ICAST: int value converted to long and used as absolute time</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#ICAST_INT_CAST_TO_DOUBLE_PASSED_TO_CEIL">ICAST: Integral value cast to double and then passed to Math.ceil</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#ICAST_INT_CAST_TO_FLOAT_PASSED_TO_ROUND">ICAST: int value cast to float and then passed to Math.round</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#IJU_ASSERT_METHOD_INVOKED_FROM_RUN_METHOD">IJU: JUnit assertion in run method will not be noticed by JUnit</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#IJU_BAD_SUITE_METHOD">IJU: TestCase declares a bad suite method </a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#IJU_NO_TESTS">IJU: TestCase has no tests</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#IJU_SETUP_NO_SUPER">IJU: TestCase defines setUp that doesn't call super.setUp()</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#IJU_SUITE_NOT_STATIC">IJU: TestCase implements a non-static suite method </a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#IJU_TEARDOWN_NO_SUPER">IJU: TestCase defines tearDown that doesn't call super.tearDown()</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#IL_CONTAINER_ADDED_TO_ITSELF">IL: A collection is added to itself</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#IL_INFINITE_LOOP">IL: An apparent infinite loop</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#IL_INFINITE_RECURSIVE_LOOP">IL: An apparent infinite recursive loop</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#IM_MULTIPLYING_RESULT_OF_IREM">IM: Integer multiply of result of integer remainder</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#INT_BAD_COMPARISON_WITH_INT_VALUE">INT: Bad comparison of int value with long constant</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#INT_BAD_COMPARISON_WITH_NONNEGATIVE_VALUE">INT: Bad comparison of nonnegative value with negative constant</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#INT_BAD_COMPARISON_WITH_SIGNED_BYTE">INT: Bad comparison of signed byte</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#IO_APPENDING_TO_OBJECT_OUTPUT_STREAM">IO: Doomed attempt to append to an object output stream</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#IP_PARAMETER_IS_DEAD_BUT_OVERWRITTEN">IP: A parameter is dead upon entry to a method but overwritten</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#MF_CLASS_MASKS_FIELD">MF: Class defines field that masks a superclass field</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#MF_METHOD_MASKS_FIELD">MF: Method defines a variable that obscures a field</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_ALWAYS_NULL">NP: Null pointer dereference</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_ALWAYS_NULL_EXCEPTION">NP: Null pointer dereference in method on exception path</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_ARGUMENT_MIGHT_BE_NULL">NP: Method does not check for null argument</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_CLOSING_NULL">NP: close() invoked on a value that is always null</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_GUARANTEED_DEREF">NP: Null value is guaranteed to be dereferenced</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH">NP: Value is null and guaranteed to be dereferenced on exception path</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR">NP: Nonnull field is not initialized</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_NONNULL_PARAM_VIOLATION">NP: Method call passes null to a nonnull parameter </a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_NONNULL_RETURN_VIOLATION">NP: Method may return null, but is declared @NonNull</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_NULL_INSTANCEOF">NP: A known null value is checked to see if it is an instance of a type</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_NULL_ON_SOME_PATH">NP: Possible null pointer dereference</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_NULL_ON_SOME_PATH_EXCEPTION">NP: Possible null pointer dereference in method on exception path</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_NULL_PARAM_DEREF">NP: Method call passes null for nonnull parameter</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS">NP: Method call passes null for nonnull parameter</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_NULL_PARAM_DEREF_NONVIRTUAL">NP: Non-virtual method call passes null for nonnull parameter</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_STORE_INTO_NONNULL_FIELD">NP: Store of null value into field annotated NonNull</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_UNWRITTEN_FIELD">NP: Read of unwritten field</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#NM_BAD_EQUAL">Nm: Class defines equal(Object); should it be equals(Object)?</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NM_LCASE_HASHCODE">Nm: Class defines hashcode(); should it be hashCode()?</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#NM_LCASE_TOSTRING">Nm: Class defines tostring(); should it be toString()?</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NM_METHOD_CONSTRUCTOR_CONFUSION">Nm: Apparent method/constructor confusion</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#NM_VERY_CONFUSING">Nm: Very confusing method names</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NM_WRONG_PACKAGE">Nm: Method doesn't override method in superclass due to wrong package for parameter</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT">QBA: Method assigns boolean literal in boolean expression</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#RC_REF_COMPARISON">RC: Suspicious reference comparison</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE">RCN: Nullcheck of value previously dereferenced</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#RE_BAD_SYNTAX_FOR_REGULAR_EXPRESSION">RE: Invalid syntax for regular expression</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#RE_CANT_USE_FILE_SEPARATOR_AS_REGULAR_EXPRESSION">RE: File.separator used for regular expression</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#RE_POSSIBLE_UNINTENDED_PATTERN">RE: "." or "|" used for regular expression</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#RV_01_TO_INT">RV: Random value from 0 to 1 is coerced to the integer 0</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#RV_ABSOLUTE_VALUE_OF_HASHCODE">RV: Bad attempt to compute absolute value of signed 32-bit hashcode </a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#RV_ABSOLUTE_VALUE_OF_RANDOM_INT">RV: Bad attempt to compute absolute value of signed random integer</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#RV_CHECK_COMPARETO_FOR_SPECIFIC_RETURN_VALUE">RV: Code checks for specific values returned by compareTo</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#RV_EXCEPTION_NOT_THROWN">RV: Exception created and dropped rather than thrown</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#RV_RETURN_VALUE_IGNORED">RV: Method ignores return value</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#RpC_REPEATED_CONDITIONAL_TEST">RpC: Repeated conditional tests</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SA_FIELD_SELF_ASSIGNMENT">SA: Self assignment of field</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#SA_FIELD_SELF_COMPARISON">SA: Self comparison of field with itself</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SA_FIELD_SELF_COMPUTATION">SA: Nonsensical self computation involving a field (e.g., x & x)</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#SA_LOCAL_SELF_ASSIGNMENT_INSTEAD_OF_FIELD">SA: Self assignment of local rather than assignment to field</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SA_LOCAL_SELF_COMPARISON">SA: Self comparison of value with itself</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#SA_LOCAL_SELF_COMPUTATION">SA: Nonsensical self computation involving a variable (e.g., x & x)</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH">SF: Dead store due to switch statement fall through</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH_TO_THROW">SF: Dead store due to switch statement fall through to throw</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SIC_THREADLOCAL_DEADLY_EMBRACE">SIC: Deadly embrace of non-static inner class and thread local</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#SIO_SUPERFLUOUS_INSTANCEOF">SIO: Unnecessary type check done using instanceof operator</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SQL_BAD_PREPARED_STATEMENT_ACCESS">SQL: Method attempts to access a prepared statement parameter with index 0</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#SQL_BAD_RESULTSET_ACCESS">SQL: Method attempts to access a result set field with index 0</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#STI_INTERRUPTED_ON_CURRENTTHREAD">STI: Unneeded use of currentThread() call, to call interrupted() </a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#STI_INTERRUPTED_ON_UNKNOWNTHREAD">STI: Static Thread.interrupted() method invoked on thread instance</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SE_METHOD_MUST_BE_PRIVATE">Se: Method must be private in order for serialization to work</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#SE_READ_RESOLVE_IS_STATIC">Se: The readResolve method must not be declared as a static method. </a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#TQ_ALWAYS_VALUE_USED_WHERE_NEVER_REQUIRED">TQ: Value annotated as carrying a type qualifier used where a value that must not carry that qualifier is required</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#TQ_COMPARING_VALUES_WITH_INCOMPATIBLE_TYPE_QUALIFIERS">TQ: Comparing values with incompatible type qualifiers</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#TQ_MAYBE_SOURCE_VALUE_REACHES_ALWAYS_SINK">TQ: Value that might not carry a type qualifier is always used in a way requires that type qualifier</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#TQ_MAYBE_SOURCE_VALUE_REACHES_NEVER_SINK">TQ: Value that might carry a type qualifier is always used in a way prohibits it from having that type qualifier</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#TQ_NEVER_VALUE_USED_WHERE_ALWAYS_REQUIRED">TQ: Value annotated as never carrying a type qualifier used where value carrying that qualifier is required</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#TQ_UNKNOWN_VALUE_USED_WHERE_ALWAYS_STRICTLY_REQUIRED">TQ: Value without a type qualifier used where a value is required to have that qualifier</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS">UMAC: Uncallable method defined in anonymous class</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#UR_UNINIT_READ">UR: Uninitialized read of field in constructor</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR">UR: Uninitialized read of field method called from constructor of superclass</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#DMI_INVOKING_TOSTRING_ON_ANONYMOUS_ARRAY">USELESS_STRING: Invocation of toString on an unnamed array</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DMI_INVOKING_TOSTRING_ON_ARRAY">USELESS_STRING: Invocation of toString on an array</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#VA_FORMAT_STRING_BAD_CONVERSION_FROM_ARRAY">USELESS_STRING: Array formatted in useless way using format string</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#UWF_NULL_FIELD">UwF: Field only ever set to null</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#UWF_UNWRITTEN_FIELD">UwF: Unwritten field</a></td><td>Correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_VARARG">VA: Primitive array passed to function expecting a variable number of object arguments</a></td><td>Correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE">LG: Potential lost logger changes due to weak reference in OpenJDK</a></td><td>Experimental</td></tr> <tr bgcolor="#eeeeee"><td><a href="#OBL_UNSATISFIED_OBLIGATION">OBL: Method may fail to clean up stream or resource</a></td><td>Experimental</td></tr> <tr bgcolor="#ffffff"><td><a href="#OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE">OBL: Method may fail to clean up stream or resource on checked exception</a></td><td>Experimental</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DM_CONVERT_CASE">Dm: Consider using Locale parameterized version of invoked method</a></td><td>Internationalization</td></tr> <tr bgcolor="#ffffff"><td><a href="#DM_DEFAULT_ENCODING">Dm: Reliance on default encoding</a></td><td>Internationalization</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED">DP: Classloaders should only be created inside doPrivileged block</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#ffffff"><td><a href="#DP_DO_INSIDE_DO_PRIVILEGED">DP: Method invoked that should be only be invoked inside a doPrivileged block</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#eeeeee"><td><a href="#EI_EXPOSE_REP">EI: May expose internal representation by returning reference to mutable object</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#ffffff"><td><a href="#EI_EXPOSE_REP2">EI2: May expose internal representation by incorporating reference to mutable object</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#eeeeee"><td><a href="#FI_PUBLIC_SHOULD_BE_PROTECTED">FI: Finalizer should be protected, not public</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#ffffff"><td><a href="#EI_EXPOSE_STATIC_REP2">MS: May expose internal static state by storing a mutable object into a static field</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#eeeeee"><td><a href="#MS_CANNOT_BE_FINAL">MS: Field isn't final and can't be protected from malicious code</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#ffffff"><td><a href="#MS_EXPOSE_REP">MS: Public static method may expose internal representation by returning array</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#eeeeee"><td><a href="#MS_FINAL_PKGPROTECT">MS: Field should be both final and package protected</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#ffffff"><td><a href="#MS_MUTABLE_ARRAY">MS: Field is a mutable array</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#eeeeee"><td><a href="#MS_MUTABLE_HASHTABLE">MS: Field is a mutable Hashtable</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#ffffff"><td><a href="#MS_OOI_PKGPROTECT">MS: Field should be moved out of an interface and made package protected</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#eeeeee"><td><a href="#MS_PKGPROTECT">MS: Field should be package protected</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#ffffff"><td><a href="#MS_SHOULD_BE_FINAL">MS: Field isn't final but should be</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#eeeeee"><td><a href="#MS_SHOULD_BE_REFACTORED_TO_BE_FINAL">MS: Field isn't final but should be refactored to be so</a></td><td>Malicious code vulnerability</td></tr> <tr bgcolor="#ffffff"><td><a href="#AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION">AT: Sequence of calls to concurrent abstraction may not be atomic</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DC_DOUBLECHECK">DC: Possible double check of field</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#DL_SYNCHRONIZATION_ON_BOOLEAN">DL: Synchronization on Boolean</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE">DL: Synchronization on boxed primitive</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#DL_SYNCHRONIZATION_ON_SHARED_CONSTANT">DL: Synchronization on interned String </a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DL_SYNCHRONIZATION_ON_UNSHARED_BOXED_PRIMITIVE">DL: Synchronization on boxed primitive values</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#DM_MONITOR_WAIT_ON_CONDITION">Dm: Monitor wait() called on Condition</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DM_USELESS_THREAD">Dm: A thread was created using the default empty run method</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#ESync_EMPTY_SYNC">ESync: Empty synchronized block</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#IS2_INCONSISTENT_SYNC">IS: Inconsistent synchronization</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#IS_FIELD_NOT_GUARDED">IS: Field not guarded against concurrent access</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#JLM_JSR166_LOCK_MONITORENTER">JLM: Synchronization performed on Lock</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#JLM_JSR166_UTILCONCURRENT_MONITORENTER">JLM: Synchronization performed on util.concurrent instance</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#JML_JSR166_CALLING_WAIT_RATHER_THAN_AWAIT">JLM: Using monitor style wait methods on util.concurrent abstraction</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#LI_LAZY_INIT_STATIC">LI: Incorrect lazy initialization of static field</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#LI_LAZY_INIT_UPDATE_STATIC">LI: Incorrect lazy initialization and update of static field</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#ML_SYNC_ON_FIELD_TO_GUARD_CHANGING_THAT_FIELD">ML: Synchronization on field in futile attempt to guard that field</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#ML_SYNC_ON_UPDATED_FIELD">ML: Method synchronizes on an updated field</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#MSF_MUTABLE_SERVLET_FIELD">MSF: Mutable servlet field</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#MWN_MISMATCHED_NOTIFY">MWN: Mismatched notify()</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#MWN_MISMATCHED_WAIT">MWN: Mismatched wait()</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NN_NAKED_NOTIFY">NN: Naked notify</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_SYNC_AND_NULL_CHECK_FIELD">NP: Synchronize and null check on the same field.</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NO_NOTIFY_NOT_NOTIFYALL">No: Using notify() rather than notifyAll()</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#RS_READOBJECT_SYNC">RS: Class's readObject() method is synchronized</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED">RV: Return value of putIfAbsent ignored, value passed to putIfAbsent reused</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#RU_INVOKE_RUN">Ru: Invokes run on a thread (did you mean to start it instead?)</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SC_START_IN_CTOR">SC: Constructor invokes Thread.start()</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#SP_SPIN_ON_FIELD">SP: Method spins on field</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#STCAL_INVOKE_ON_STATIC_CALENDAR_INSTANCE">STCAL: Call to static Calendar</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#STCAL_INVOKE_ON_STATIC_DATE_FORMAT_INSTANCE">STCAL: Call to static DateFormat</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#STCAL_STATIC_CALENDAR_INSTANCE">STCAL: Static Calendar field</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#STCAL_STATIC_SIMPLE_DATE_FORMAT_INSTANCE">STCAL: Static DateFormat</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SWL_SLEEP_WITH_LOCK_HELD">SWL: Method calls Thread.sleep() with a lock held</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#TLW_TWO_LOCK_WAIT">TLW: Wait with two locks held</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#UG_SYNC_SET_UNSYNC_GET">UG: Unsynchronized get method, synchronized set method</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#UL_UNRELEASED_LOCK">UL: Method does not release lock on all paths</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#UL_UNRELEASED_LOCK_EXCEPTION_PATH">UL: Method does not release lock on all exception paths</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#UW_UNCOND_WAIT">UW: Unconditional wait</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#VO_VOLATILE_INCREMENT">VO: An increment to a volatile field isn't atomic</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#VO_VOLATILE_REFERENCE_TO_ARRAY">VO: A volatile reference to an array doesn't treat the array elements as volatile</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#WL_USING_GETCLASS_RATHER_THAN_CLASS_LITERAL">WL: Synchronization on getClass rather than class literal</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#WS_WRITEOBJECT_SYNC">WS: Class's writeObject() method is synchronized but nothing else is</a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#WA_AWAIT_NOT_IN_LOOP">Wa: Condition.await() not in loop </a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#ffffff"><td><a href="#WA_NOT_IN_LOOP">Wa: Wait not in loop </a></td><td>Multithreaded correctness</td></tr> <tr bgcolor="#eeeeee"><td><a href="#BX_BOXING_IMMEDIATELY_UNBOXED">Bx: Primitive value is boxed and then immediately unboxed</a></td><td>Performance</td></tr> <tr bgcolor="#ffffff"><td><a href="#BX_BOXING_IMMEDIATELY_UNBOXED_TO_PERFORM_COERCION">Bx: Primitive value is boxed then unboxed to perform primitive coercion</a></td><td>Performance</td></tr> <tr bgcolor="#eeeeee"><td><a href="#BX_UNBOXING_IMMEDIATELY_REBOXED">Bx: Boxed value is unboxed and then immediately reboxed</a></td><td>Performance</td></tr> <tr bgcolor="#ffffff"><td><a href="#DM_BOXED_PRIMITIVE_FOR_PARSING">Bx: Boxing/unboxing to parse a primitive</a></td><td>Performance</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DM_BOXED_PRIMITIVE_TOSTRING">Bx: Method allocates a boxed primitive just to call toString</a></td><td>Performance</td></tr> <tr bgcolor="#ffffff"><td><a href="#DM_FP_NUMBER_CTOR">Bx: Method invokes inefficient floating-point Number constructor; use static valueOf instead</a></td><td>Performance</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DM_NUMBER_CTOR">Bx: Method invokes inefficient Number constructor; use static valueOf instead</a></td><td>Performance</td></tr> <tr bgcolor="#ffffff"><td><a href="#DMI_BLOCKING_METHODS_ON_URL">Dm: The equals and hashCode methods of URL are blocking</a></td><td>Performance</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DMI_COLLECTION_OF_URLS">Dm: Maps and sets of URLs can be performance hogs</a></td><td>Performance</td></tr> <tr bgcolor="#ffffff"><td><a href="#DM_BOOLEAN_CTOR">Dm: Method invokes inefficient Boolean constructor; use Boolean.valueOf(...) instead</a></td><td>Performance</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DM_GC">Dm: Explicit garbage collection; extremely dubious except in benchmarking code</a></td><td>Performance</td></tr> <tr bgcolor="#ffffff"><td><a href="#DM_NEW_FOR_GETCLASS">Dm: Method allocates an object, only to get the class object</a></td><td>Performance</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DM_NEXTINT_VIA_NEXTDOUBLE">Dm: Use the nextInt method of Random rather than nextDouble to generate a random integer</a></td><td>Performance</td></tr> <tr bgcolor="#ffffff"><td><a href="#DM_STRING_CTOR">Dm: Method invokes inefficient new String(String) constructor</a></td><td>Performance</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DM_STRING_TOSTRING">Dm: Method invokes toString() method on a String</a></td><td>Performance</td></tr> <tr bgcolor="#ffffff"><td><a href="#DM_STRING_VOID_CTOR">Dm: Method invokes inefficient new String() constructor</a></td><td>Performance</td></tr> <tr bgcolor="#eeeeee"><td><a href="#HSC_HUGE_SHARED_STRING_CONSTANT">HSC: Huge string constants is duplicated across multiple class files</a></td><td>Performance</td></tr> <tr bgcolor="#ffffff"><td><a href="#ITA_INEFFICIENT_TO_ARRAY">ITA: Method uses toArray() with zero-length array argument</a></td><td>Performance</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SBSC_USE_STRINGBUFFER_CONCATENATION">SBSC: Method concatenates strings using + in a loop</a></td><td>Performance</td></tr> <tr bgcolor="#ffffff"><td><a href="#SIC_INNER_SHOULD_BE_STATIC">SIC: Should be a static inner class</a></td><td>Performance</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SIC_INNER_SHOULD_BE_STATIC_ANON">SIC: Could be refactored into a named static inner class</a></td><td>Performance</td></tr> <tr bgcolor="#ffffff"><td><a href="#SIC_INNER_SHOULD_BE_STATIC_NEEDS_THIS">SIC: Could be refactored into a static inner class</a></td><td>Performance</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SS_SHOULD_BE_STATIC">SS: Unread field: should this field be static?</a></td><td>Performance</td></tr> <tr bgcolor="#ffffff"><td><a href="#UM_UNNECESSARY_MATH">UM: Method calls static Math class method on a constant value</a></td><td>Performance</td></tr> <tr bgcolor="#eeeeee"><td><a href="#UPM_UNCALLED_PRIVATE_METHOD">UPM: Private method is never called</a></td><td>Performance</td></tr> <tr bgcolor="#ffffff"><td><a href="#URF_UNREAD_FIELD">UrF: Unread field</a></td><td>Performance</td></tr> <tr bgcolor="#eeeeee"><td><a href="#UUF_UNUSED_FIELD">UuF: Unused field</a></td><td>Performance</td></tr> <tr bgcolor="#ffffff"><td><a href="#WMI_WRONG_MAP_ITERATOR">WMI: Inefficient use of keySet iterator instead of entrySet iterator</a></td><td>Performance</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DMI_CONSTANT_DB_PASSWORD">Dm: Hardcoded constant database password</a></td><td>Security</td></tr> <tr bgcolor="#ffffff"><td><a href="#DMI_EMPTY_DB_PASSWORD">Dm: Empty database password</a></td><td>Security</td></tr> <tr bgcolor="#eeeeee"><td><a href="#HRS_REQUEST_PARAMETER_TO_COOKIE">HRS: HTTP cookie formed from untrusted input</a></td><td>Security</td></tr> <tr bgcolor="#ffffff"><td><a href="#HRS_REQUEST_PARAMETER_TO_HTTP_HEADER">HRS: HTTP Response splitting vulnerability</a></td><td>Security</td></tr> <tr bgcolor="#eeeeee"><td><a href="#PT_ABSOLUTE_PATH_TRAVERSAL">PT: Absolute path traversal in servlet</a></td><td>Security</td></tr> <tr bgcolor="#ffffff"><td><a href="#PT_RELATIVE_PATH_TRAVERSAL">PT: Relative path traversal in servlet</a></td><td>Security</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE">SQL: Nonconstant string passed to execute method on an SQL statement</a></td><td>Security</td></tr> <tr bgcolor="#ffffff"><td><a href="#SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING">SQL: A prepared statement is generated from a nonconstant String</a></td><td>Security</td></tr> <tr bgcolor="#eeeeee"><td><a href="#XSS_REQUEST_PARAMETER_TO_JSP_WRITER">XSS: JSP reflected cross site scripting vulnerability</a></td><td>Security</td></tr> <tr bgcolor="#ffffff"><td><a href="#XSS_REQUEST_PARAMETER_TO_SEND_ERROR">XSS: Servlet reflected cross site scripting vulnerability in error page</a></td><td>Security</td></tr> <tr bgcolor="#eeeeee"><td><a href="#XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER">XSS: Servlet reflected cross site scripting vulnerability</a></td><td>Security</td></tr> <tr bgcolor="#ffffff"><td><a href="#BC_BAD_CAST_TO_ABSTRACT_COLLECTION">BC: Questionable cast to abstract collection </a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#BC_BAD_CAST_TO_CONCRETE_COLLECTION">BC: Questionable cast to concrete collection</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#BC_UNCONFIRMED_CAST">BC: Unchecked/unconfirmed cast</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#BC_UNCONFIRMED_CAST_OF_RETURN_VALUE">BC: Unchecked/unconfirmed cast of return value from method</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#BC_VACUOUS_INSTANCEOF">BC: instanceof will always return true</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#ICAST_QUESTIONABLE_UNSIGNED_RIGHT_SHIFT">BSHIFT: Unsigned right shift cast to short/byte</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#CI_CONFUSED_INHERITANCE">CI: Class is final but declares protected field</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DB_DUPLICATE_BRANCHES">DB: Method uses the same code for two branches</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#DB_DUPLICATE_SWITCH_CLAUSES">DB: Method uses the same code for two switch clauses</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DLS_DEAD_LOCAL_STORE">DLS: Dead store to local variable</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#DLS_DEAD_LOCAL_STORE_IN_RETURN">DLS: Useless assignment in return statement</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DLS_DEAD_LOCAL_STORE_OF_NULL">DLS: Dead store of null to local variable</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#DLS_DEAD_LOCAL_STORE_SHADOWS_FIELD">DLS: Dead store to local variable that shadows field</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DMI_HARDCODED_ABSOLUTE_FILENAME">DMI: Code contains a hard coded reference to an absolute pathname</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#DMI_NONSERIALIZABLE_OBJECT_WRITTEN">DMI: Non serializable object written to ObjectOutput</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#DMI_USELESS_SUBSTRING">DMI: Invocation of substring(0), which returns the original value</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#DMI_THREAD_PASSED_WHERE_RUNNABLE_EXPECTED">Dm: Thread passed where Runnable expected</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#EQ_DOESNT_OVERRIDE_EQUALS">Eq: Class doesn't override equals in superclass</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#EQ_UNUSUAL">Eq: Unusual equals method </a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#FE_FLOATING_POINT_EQUALITY">FE: Test for floating point equality</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#VA_FORMAT_STRING_BAD_CONVERSION_TO_BOOLEAN">FS: Non-Boolean argument formatted using %b format specifier</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD">IA: Potentially ambiguous invocation of either an inherited or outer method</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#IC_INIT_CIRCULARITY">IC: Initialization circularity</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#ICAST_IDIV_CAST_TO_DOUBLE">ICAST: Integral division result cast to double or float</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#ICAST_INTEGER_MULTIPLY_CAST_TO_LONG">ICAST: Result of integer multiplication cast to long</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#IM_AVERAGE_COMPUTATION_COULD_OVERFLOW">IM: Computation of average could overflow</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#IM_BAD_CHECK_FOR_ODD">IM: Check for oddness that won't work for negative numbers </a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#INT_BAD_REM_BY_1">INT: Integer remainder modulo 1</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#INT_VACUOUS_BIT_OPERATION">INT: Vacuous bit mask operation on integer value</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#INT_VACUOUS_COMPARISON">INT: Vacuous comparison of integer value</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#MTIA_SUSPECT_SERVLET_INSTANCE_FIELD">MTIA: Class extends Servlet class and uses instance variables</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#MTIA_SUSPECT_STRUTS_INSTANCE_FIELD">MTIA: Class extends Struts Action class and uses instance variables</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_DEREFERENCE_OF_READLINE_VALUE">NP: Dereference of the result of readLine() without nullcheck</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_IMMEDIATE_DEREFERENCE_OF_READLINE">NP: Immediate dereference of the result of readLine()</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_LOAD_OF_KNOWN_NULL_VALUE">NP: Load of known null value</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_METHOD_PARAMETER_TIGHTENS_ANNOTATION">NP: Method tightens nullness annotation on parameter</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_METHOD_RETURN_RELAXING_ANNOTATION">NP: Method relaxes nullness annotation on return value</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE">NP: Possible null pointer dereference due to return value of called method</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_NULL_ON_SOME_PATH_MIGHT_BE_INFEASIBLE">NP: Possible null pointer dereference on branch that might be infeasible</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE">NP: Parameter must be nonnull but is marked as nullable</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#NP_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD">NP: Read of unwritten public or protected field</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#NS_DANGEROUS_NON_SHORT_CIRCUIT">NS: Potentially dangerous use of non-short-circuit logic</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#NS_NON_SHORT_CIRCUIT">NS: Questionable use of non-short-circuit logic</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#PZLA_PREFER_ZERO_LENGTH_ARRAYS">PZLA: Consider returning a zero length array rather than null</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#QF_QUESTIONABLE_FOR_LOOP">QF: Complicated, subtle or wrong increment in for-loop </a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#RCN_REDUNDANT_COMPARISON_OF_NULL_AND_NONNULL_VALUE">RCN: Redundant comparison of non-null value to null</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#RCN_REDUNDANT_COMPARISON_TWO_NULL_VALUES">RCN: Redundant comparison of two null values</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE">RCN: Redundant nullcheck of value known to be non-null</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE">RCN: Redundant nullcheck of value known to be null</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#REC_CATCH_EXCEPTION">REC: Exception is caught when Exception is not thrown</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#RI_REDUNDANT_INTERFACES">RI: Class implements same interface as superclass</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#RV_CHECK_FOR_POSITIVE_INDEXOF">RV: Method checks to see if result of String.indexOf is positive</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#RV_DONT_JUST_NULL_CHECK_READLINE">RV: Method discards result of readLine after checking if it is nonnull</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#RV_REM_OF_HASHCODE">RV: Remainder of hashCode could be negative</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#RV_REM_OF_RANDOM_INT">RV: Remainder of 32-bit signed random integer</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#RV_RETURN_VALUE_IGNORED_INFERRED">RV: Method ignores return value, is this OK?</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#SA_FIELD_DOUBLE_ASSIGNMENT">SA: Double assignment of field</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SA_LOCAL_DOUBLE_ASSIGNMENT">SA: Double assignment of local variable </a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#SA_LOCAL_SELF_ASSIGNMENT">SA: Self assignment of local variable</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SF_SWITCH_FALLTHROUGH">SF: Switch statement found where one case falls through to the next case</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#SF_SWITCH_NO_DEFAULT">SF: Switch statement found where default case is missing</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD">ST: Write to static field from instance method</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#SE_PRIVATE_READ_RESOLVE_NOT_INHERITED">Se: Private readResolve method not inherited by subclasses</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#SE_TRANSIENT_FIELD_OF_NONSERIALIZABLE_CLASS">Se: Transient field of class that isn't Serializable. </a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_ALWAYS_SINK">TQ: Value required to have type qualifier, but marked as unknown</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_NEVER_SINK">TQ: Value required to not have type qualifier, but marked as unknown</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#UCF_USELESS_CONTROL_FLOW">UCF: Useless control flow</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#UCF_USELESS_CONTROL_FLOW_NEXT_LINE">UCF: Useless control flow to next line</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD">UrF: Unread public/protected field</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD">UuF: Unused public or protected field</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR">UwF: Field not initialized in constructor but dereferenced without null check</a></td><td>Dodgy code</td></tr> <tr bgcolor="#eeeeee"><td><a href="#UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD">UwF: Unwritten public or protected field</a></td><td>Dodgy code</td></tr> <tr bgcolor="#ffffff"><td><a href="#XFB_XML_FACTORY_BYPASS">XFB: Method directly allocates a specific implementation of xml interfaces</a></td><td>Dodgy code</td></tr> </table> <h2>Descriptions</h2> <h3><a name="BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS">BC: Equals method should not assume anything about the type of its argument (BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS)</a></h3> <p> The <code>equals(Object o)</code> method shouldn't make any assumptions about the type of <code>o</code>. It should simply return false if <code>o</code> is not the same type as <code>this</code>. </p> <h3><a name="BIT_SIGNED_CHECK">BIT: Check for sign of bitwise operation (BIT_SIGNED_CHECK)</a></h3> <p> This method compares an expression such as</p> <pre>((event.detail &amp; SWT.SELECTED) &gt; 0)</pre>. <p>Using bit arithmetic and then comparing with the greater than operator can lead to unexpected results (of course depending on the value of SWT.SELECTED). If SWT.SELECTED is a negative number, this is a candidate for a bug. Even when SWT.SELECTED is not negative, it seems good practice to use '!= 0' instead of '&gt; 0'. </p> <p> <em>Boris Bokowski</em> </p> <h3><a name="CN_IDIOM">CN: Class implements Cloneable but does not define or use clone method (CN_IDIOM)</a></h3> <p> Class implements Cloneable but does not define or use the clone method.</p> <h3><a name="CN_IDIOM_NO_SUPER_CALL">CN: clone method does not call super.clone() (CN_IDIOM_NO_SUPER_CALL)</a></h3> <p> This non-final class defines a clone() method that does not call super.clone(). If this class ("<i>A</i>") is extended by a subclass ("<i>B</i>"), and the subclass <i>B</i> calls super.clone(), then it is likely that <i>B</i>'s clone() method will return an object of type <i>A</i>, which violates the standard contract for clone().</p> <p> If all clone() methods call super.clone(), then they are guaranteed to use Object.clone(), which always returns an object of the correct type.</p> <h3><a name="CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE">CN: Class defines clone() but doesn't implement Cloneable (CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE)</a></h3> <p> This class defines a clone() method but the class doesn't implement Cloneable. There are some situations in which this is OK (e.g., you want to control how subclasses can clone themselves), but just make sure that this is what you intended. </p> <h3><a name="CO_ABSTRACT_SELF">Co: Abstract class defines covariant compareTo() method (CO_ABSTRACT_SELF)</a></h3> <p> This class defines a covariant version of <code>compareTo()</code>.&nbsp; To correctly override the <code>compareTo()</code> method in the <code>Comparable</code> interface, the parameter of <code>compareTo()</code> must have type <code>java.lang.Object</code>.</p> <h3><a name="CO_SELF_NO_OBJECT">Co: Covariant compareTo() method defined (CO_SELF_NO_OBJECT)</a></h3> <p> This class defines a covariant version of <code>compareTo()</code>.&nbsp; To correctly override the <code>compareTo()</code> method in the <code>Comparable</code> interface, the parameter of <code>compareTo()</code> must have type <code>java.lang.Object</code>.</p> <h3><a name="DE_MIGHT_DROP">DE: Method might drop exception (DE_MIGHT_DROP)</a></h3> <p> This method might drop an exception.&nbsp; In general, exceptions should be handled or reported in some way, or they should be thrown out of the method.</p> <h3><a name="DE_MIGHT_IGNORE">DE: Method might ignore exception (DE_MIGHT_IGNORE)</a></h3> <p> This method might ignore an exception.&nbsp; In general, exceptions should be handled or reported in some way, or they should be thrown out of the method.</p> <h3><a name="DMI_ENTRY_SETS_MAY_REUSE_ENTRY_OBJECTS">DMI: Adding elements of an entry set may fail due to reuse of Entry objects (DMI_ENTRY_SETS_MAY_REUSE_ENTRY_OBJECTS)</a></h3> <p> The entrySet() method is allowed to return a view of the underlying Map in which a single Entry object is reused and returned during the iteration. As of Java 1.6, both IdentityHashMap and EnumMap did so. When iterating through such a Map, the Entry value is only valid until you advance to the next iteration. If, for example, you try to pass such an entrySet to an addAll method, things will go badly wrong. </p> <h3><a name="DMI_RANDOM_USED_ONLY_ONCE">DMI: Random object created and used only once (DMI_RANDOM_USED_ONLY_ONCE)</a></h3> <p> This code creates a java.util.Random object, uses it to generate one random number, and then discards the Random object. This produces mediocre quality random numbers and is inefficient. If possible, rewrite the code so that the Random object is created once and saved, and each time a new random number is required invoke a method on the existing Random object to obtain it. </p> <p>If it is important that the generated Random numbers not be guessable, you <em>must</em> not create a new Random for each random number; the values are too easily guessable. You should strongly consider using a java.security.SecureRandom instead (and avoid allocating a new SecureRandom for each random number needed). </p> <h3><a name="DMI_USING_REMOVEALL_TO_CLEAR_COLLECTION">DMI: Don't use removeAll to clear a collection (DMI_USING_REMOVEALL_TO_CLEAR_COLLECTION)</a></h3> <p> If you want to remove all elements from a collection <code>c</code>, use <code>c.clear</code>, not <code>c.removeAll(c)</code>. Calling <code>c.removeAll(c)</code> to clear a collection is less clear, susceptible to errors from typos, less efficient and for some collections, might throw a <code>ConcurrentModificationException</code>. </p> <h3><a name="DM_EXIT">Dm: Method invokes System.exit(...) (DM_EXIT)</a></h3> <p> Invoking System.exit shuts down the entire Java virtual machine. This should only been done when it is appropriate. Such calls make it hard or impossible for your code to be invoked by other code. Consider throwing a RuntimeException instead.</p> <h3><a name="DM_RUN_FINALIZERS_ON_EXIT">Dm: Method invokes dangerous method runFinalizersOnExit (DM_RUN_FINALIZERS_ON_EXIT)</a></h3> <p> <em>Never call System.runFinalizersOnExit or Runtime.runFinalizersOnExit for any reason: they are among the most dangerous methods in the Java libraries.</em> -- Joshua Bloch</p> <h3><a name="ES_COMPARING_PARAMETER_STRING_WITH_EQ">ES: Comparison of String parameter using == or != (ES_COMPARING_PARAMETER_STRING_WITH_EQ)</a></h3> <p>This code compares a <code>java.lang.String</code> parameter for reference equality using the == or != operators. Requiring callers to pass only String constants or interned strings to a method is unnecessarily fragile, and rarely leads to measurable performance gains. Consider using the <code>equals(Object)</code> method instead.</p> <h3><a name="ES_COMPARING_STRINGS_WITH_EQ">ES: Comparison of String objects using == or != (ES_COMPARING_STRINGS_WITH_EQ)</a></h3> <p>This code compares <code>java.lang.String</code> objects for reference equality using the == or != operators. Unless both strings are either constants in a source file, or have been interned using the <code>String.intern()</code> method, the same string value may be represented by two different String objects. Consider using the <code>equals(Object)</code> method instead.</p> <h3><a name="EQ_ABSTRACT_SELF">Eq: Abstract class defines covariant equals() method (EQ_ABSTRACT_SELF)</a></h3> <p> This class defines a covariant version of <code>equals()</code>.&nbsp; To correctly override the <code>equals()</code> method in <code>java.lang.Object</code>, the parameter of <code>equals()</code> must have type <code>java.lang.Object</code>.</p> <h3><a name="EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS">Eq: Equals checks for incompatible operand (EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS)</a></h3> <p> This equals method is checking to see if the argument is some incompatible type (i.e., a class that is neither a supertype nor subtype of the class that defines the equals method). For example, the Foo class might have an equals method that looks like: </p> <pre> public boolean equals(Object o) { if (o instanceof Foo) return name.equals(((Foo)o).name); else if (o instanceof String) return name.equals(o); else return false; </pre> <p>This is considered bad practice, as it makes it very hard to implement an equals method that is symmetric and transitive. Without those properties, very unexpected behavoirs are possible. </p> <h3><a name="EQ_COMPARETO_USE_OBJECT_EQUALS">Eq: Class defines compareTo(...) and uses Object.equals() (EQ_COMPARETO_USE_OBJECT_EQUALS)</a></h3> <p> This class defines a <code>compareTo(...)</code> method but inherits its <code>equals()</code> method from <code>java.lang.Object</code>. Generally, the value of compareTo should return zero if and only if equals returns true. If this is violated, weird and unpredictable failures will occur in classes such as PriorityQueue. In Java 5 the PriorityQueue.remove method uses the compareTo method, while in Java 6 it uses the equals method. <p>From the JavaDoc for the compareTo method in the Comparable interface: <blockquote> It is strongly recommended, but not strictly required that <code>(x.compareTo(y)==0) == (x.equals(y))</code>. Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals." </blockquote> <h3><a name="EQ_GETCLASS_AND_CLASS_CONSTANT">Eq: equals method fails for subtypes (EQ_GETCLASS_AND_CLASS_CONSTANT)</a></h3> <p> This class has an equals method that will be broken if it is inherited by subclasses. It compares a class literal with the class of the argument (e.g., in class <code>Foo</code> it might check if <code>Foo.class == o.getClass()</code>). It is better to check if <code>this.getClass() == o.getClass()</code>. </p> <h3><a name="EQ_SELF_NO_OBJECT">Eq: Covariant equals() method defined (EQ_SELF_NO_OBJECT)</a></h3> <p> This class defines a covariant version of <code>equals()</code>.&nbsp; To correctly override the <code>equals()</code> method in <code>java.lang.Object</code>, the parameter of <code>equals()</code> must have type <code>java.lang.Object</code>.</p> <h3><a name="FI_EMPTY">FI: Empty finalizer should be deleted (FI_EMPTY)</a></h3> <p> Empty <code>finalize()</code> methods are useless, so they should be deleted.</p> <h3><a name="FI_EXPLICIT_INVOCATION">FI: Explicit invocation of finalizer (FI_EXPLICIT_INVOCATION)</a></h3> <p> This method contains an explicit invocation of the <code>finalize()</code> method on an object.&nbsp; Because finalizer methods are supposed to be executed once, and only by the VM, this is a bad idea.</p> <p>If a connected set of objects beings finalizable, then the VM will invoke the finalize method on all the finalizable object, possibly at the same time in different threads. Thus, it is a particularly bad idea, in the finalize method for a class X, invoke finalize on objects referenced by X, because they may already be getting finalized in a separate thread. <h3><a name="FI_FINALIZER_NULLS_FIELDS">FI: Finalizer nulls fields (FI_FINALIZER_NULLS_FIELDS)</a></h3> <p> This finalizer nulls out fields. This is usually an error, as it does not aid garbage collection, and the object is going to be garbage collected anyway. <h3><a name="FI_FINALIZER_ONLY_NULLS_FIELDS">FI: Finalizer only nulls fields (FI_FINALIZER_ONLY_NULLS_FIELDS)</a></h3> <p> This finalizer does nothing except null out fields. This is completely pointless, and requires that the object be garbage collected, finalized, and then garbage collected again. You should just remove the finalize method. <h3><a name="FI_MISSING_SUPER_CALL">FI: Finalizer does not call superclass finalizer (FI_MISSING_SUPER_CALL)</a></h3> <p> This <code>finalize()</code> method does not make a call to its superclass's <code>finalize()</code> method.&nbsp; So, any finalizer actions defined for the superclass will not be performed.&nbsp; Add a call to <code>super.finalize()</code>.</p> <h3><a name="FI_NULLIFY_SUPER">FI: Finalizer nullifies superclass finalizer (FI_NULLIFY_SUPER)</a></h3> <p> This empty <code>finalize()</code> method explicitly negates the effect of any finalizer defined by its superclass.&nbsp; Any finalizer actions defined for the superclass will not be performed.&nbsp; Unless this is intended, delete this method.</p> <h3><a name="FI_USELESS">FI: Finalizer does nothing but call superclass finalizer (FI_USELESS)</a></h3> <p> The only thing this <code>finalize()</code> method does is call the superclass's <code>finalize()</code> method, making it redundant.&nbsp; Delete it.</p> <h3><a name="VA_FORMAT_STRING_USES_NEWLINE">FS: Format string should use %n rather than \n (VA_FORMAT_STRING_USES_NEWLINE)</a></h3> <p> This format string include a newline character (\n). In format strings, it is generally preferable better to use %n, which will produce the platform-specific line separator. </p> <h3><a name="GC_UNCHECKED_TYPE_IN_GENERIC_CALL">GC: Unchecked type in generic call (GC_UNCHECKED_TYPE_IN_GENERIC_CALL)</a></h3> <p> This call to a generic collection method passes an argument while compile type Object where a specific type from the generic type parameters is expected. Thus, neither the standard Java type system nor static analysis can provide useful information on whether the object being passed as a parameter is of an appropriate type. </p> <h3><a name="HE_EQUALS_NO_HASHCODE">HE: Class defines equals() but not hashCode() (HE_EQUALS_NO_HASHCODE)</a></h3> <p> This class overrides <code>equals(Object)</code>, but does not override <code>hashCode()</code>.&nbsp; Therefore, the class may violate the invariant that equal objects must have equal hashcodes.</p> <h3><a name="HE_EQUALS_USE_HASHCODE">HE: Class defines equals() and uses Object.hashCode() (HE_EQUALS_USE_HASHCODE)</a></h3> <p> This class overrides <code>equals(Object)</code>, but does not override <code>hashCode()</code>, and inherits the implementation of <code>hashCode()</code> from <code>java.lang.Object</code> (which returns the identity hash code, an arbitrary value assigned to the object by the VM).&nbsp; Therefore, the class is very likely to violate the invariant that equal objects must have equal hashcodes.</p> <p>If you don't think instances of this class will ever be inserted into a HashMap/HashTable, the recommended <code>hashCode</code> implementation to use is:</p> <pre>public int hashCode() { assert false : "hashCode not designed"; return 42; // any arbitrary constant will do }</pre> <h3><a name="HE_HASHCODE_NO_EQUALS">HE: Class defines hashCode() but not equals() (HE_HASHCODE_NO_EQUALS)</a></h3> <p> This class defines a <code>hashCode()</code> method but not an <code>equals()</code> method.&nbsp; Therefore, the class may violate the invariant that equal objects must have equal hashcodes.</p> <h3><a name="HE_HASHCODE_USE_OBJECT_EQUALS">HE: Class defines hashCode() and uses Object.equals() (HE_HASHCODE_USE_OBJECT_EQUALS)</a></h3> <p> This class defines a <code>hashCode()</code> method but inherits its <code>equals()</code> method from <code>java.lang.Object</code> (which defines equality by comparing object references).&nbsp; Although this will probably satisfy the contract that equal objects must have equal hashcodes, it is probably not what was intended by overriding the <code>hashCode()</code> method.&nbsp; (Overriding <code>hashCode()</code> implies that the object's identity is based on criteria more complicated than simple reference equality.)</p> <p>If you don't think instances of this class will ever be inserted into a HashMap/HashTable, the recommended <code>hashCode</code> implementation to use is:</p> <pre>public int hashCode() { assert false : "hashCode not designed"; return 42; // any arbitrary constant will do }</pre> <h3><a name="HE_INHERITS_EQUALS_USE_HASHCODE">HE: Class inherits equals() and uses Object.hashCode() (HE_INHERITS_EQUALS_USE_HASHCODE)</a></h3> <p> This class inherits <code>equals(Object)</code> from an abstract superclass, and <code>hashCode()</code> from <code>java.lang.Object</code> (which returns the identity hash code, an arbitrary value assigned to the object by the VM).&nbsp; Therefore, the class is very likely to violate the invariant that equal objects must have equal hashcodes.</p> <p>If you don't want to define a hashCode method, and/or don't believe the object will ever be put into a HashMap/Hashtable, define the <code>hashCode()</code> method to throw <code>UnsupportedOperationException</code>.</p> <h3><a name="IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION">IC: Superclass uses subclass during initialization (IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION)</a></h3> <p> During the initialization of a class, the class makes an active use of a subclass. That subclass will not yet be initialized at the time of this use. For example, in the following code, <code>foo</code> will be null.</p> <pre> public class CircularClassInitialization { static class InnerClassSingleton extends CircularClassInitialization { static InnerClassSingleton singleton = new InnerClassSingleton(); } static CircularClassInitialization foo = InnerClassSingleton.singleton; } </pre> <h3><a name="IMSE_DONT_CATCH_IMSE">IMSE: Dubious catching of IllegalMonitorStateException (IMSE_DONT_CATCH_IMSE)</a></h3> <p>IllegalMonitorStateException is generally only thrown in case of a design flaw in your code (calling wait or notify on an object you do not hold a lock on).</p> <h3><a name="ISC_INSTANTIATE_STATIC_CLASS">ISC: Needless instantiation of class that only supplies static methods (ISC_INSTANTIATE_STATIC_CLASS)</a></h3> <p> This class allocates an object that is based on a class that only supplies static methods. This object does not need to be created, just access the static methods directly using the class name as a qualifier.</p> <h3><a name="IT_NO_SUCH_ELEMENT">It: Iterator next() method can't throw NoSuchElementException (IT_NO_SUCH_ELEMENT)</a></h3> <p> This class implements the <code>java.util.Iterator</code> interface.&nbsp; However, its <code>next()</code> method is not capable of throwing <code>java.util.NoSuchElementException</code>.&nbsp; The <code>next()</code> method should be changed so it throws <code>NoSuchElementException</code> if is called when there are no more elements to return.</p> <h3><a name="J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION">J2EE: Store of non serializable object into HttpSession (J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION)</a></h3> <p> This code seems to be storing a non-serializable object into an HttpSession. If this session is passivated or migrated, an error will result. </p> <h3><a name="JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_CLASS">JCIP: Fields of immutable classes should be final (JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_CLASS)</a></h3> <p> The class is annotated with net.jcip.annotations.Immutable or javax.annotation.concurrent.Immutable, and the rules for those annotations require that all fields are final. .</p> <h3><a name="NP_BOOLEAN_RETURN_NULL">NP: Method with Boolean return type returns explicit null (NP_BOOLEAN_RETURN_NULL)</a></h3> <p> A method that returns either Boolean.TRUE, Boolean.FALSE or null is an accident waiting to happen. This method can be invoked as though it returned a value of type boolean, and the compiler will insert automatic unboxing of the Boolean value. If a null value is returned, this will result in a NullPointerException. </p> <h3><a name="NP_CLONE_COULD_RETURN_NULL">NP: Clone method may return null (NP_CLONE_COULD_RETURN_NULL)</a></h3> <p> This clone method seems to return null in some circumstances, but clone is never allowed to return a null value. If you are convinced this path is unreachable, throw an AssertionError instead. </p> <h3><a name="NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT">NP: equals() method does not check for null argument (NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT)</a></h3> <p> This implementation of equals(Object) violates the contract defined by java.lang.Object.equals() because it does not check for null being passed as the argument. All equals() methods should return false if passed a null value. </p> <h3><a name="NP_TOSTRING_COULD_RETURN_NULL">NP: toString method may return null (NP_TOSTRING_COULD_RETURN_NULL)</a></h3> <p> This toString method seems to return null in some circumstances. A liberal reading of the spec could be interpreted as allowing this, but it is probably a bad idea and could cause other code to break. Return the empty string or some other appropriate string rather than null. </p> <h3><a name="NM_CLASS_NAMING_CONVENTION">Nm: Class names should start with an upper case letter (NM_CLASS_NAMING_CONVENTION)</a></h3> <p> Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). </p> <h3><a name="NM_CLASS_NOT_EXCEPTION">Nm: Class is not derived from an Exception, even though it is named as such (NM_CLASS_NOT_EXCEPTION)</a></h3> <p> This class is not derived from another exception, but ends with 'Exception'. This will be confusing to users of this class.</p> <h3><a name="NM_CONFUSING">Nm: Confusing method names (NM_CONFUSING)</a></h3> <p> The referenced methods have names that differ only by capitalization.</p> <h3><a name="NM_FIELD_NAMING_CONVENTION">Nm: Field names should start with a lower case letter (NM_FIELD_NAMING_CONVENTION)</a></h3> <p> Names of fields that are not final should be in mixed case with a lowercase first letter and the first letters of subsequent words capitalized. </p> <h3><a name="NM_FUTURE_KEYWORD_USED_AS_IDENTIFIER">Nm: Use of identifier that is a keyword in later versions of Java (NM_FUTURE_KEYWORD_USED_AS_IDENTIFIER)</a></h3> <p>The identifier is a word that is reserved as a keyword in later versions of Java, and your code will need to be changed in order to compile it in later versions of Java.</p> <h3><a name="NM_FUTURE_KEYWORD_USED_AS_MEMBER_IDENTIFIER">Nm: Use of identifier that is a keyword in later versions of Java (NM_FUTURE_KEYWORD_USED_AS_MEMBER_IDENTIFIER)</a></h3> <p>This identifier is used as a keyword in later versions of Java. This code, and any code that references this API, will need to be changed in order to compile it in later versions of Java.</p> <h3><a name="NM_METHOD_NAMING_CONVENTION">Nm: Method names should start with a lower case letter (NM_METHOD_NAMING_CONVENTION)</a></h3> <p> Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. </p> <h3><a name="NM_SAME_SIMPLE_NAME_AS_INTERFACE">Nm: Class names shouldn't shadow simple name of implemented interface (NM_SAME_SIMPLE_NAME_AS_INTERFACE)</a></h3> <p> This class/interface has a simple name that is identical to that of an implemented/extended interface, except that the interface is in a different package (e.g., <code>alpha.Foo</code> extends <code>beta.Foo</code>). This can be exceptionally confusing, create lots of situations in which you have to look at import statements to resolve references and creates many opportunities to accidently define methods that do not override methods in their superclasses. </p> <h3><a name="NM_SAME_SIMPLE_NAME_AS_SUPERCLASS">Nm: Class names shouldn't shadow simple name of superclass (NM_SAME_SIMPLE_NAME_AS_SUPERCLASS)</a></h3> <p> This class has a simple name that is identical to that of its superclass, except that its superclass is in a different package (e.g., <code>alpha.Foo</code> extends <code>beta.Foo</code>). This can be exceptionally confusing, create lots of situations in which you have to look at import statements to resolve references and creates many opportunities to accidently define methods that do not override methods in their superclasses. </p> <h3><a name="NM_VERY_CONFUSING_INTENTIONAL">Nm: Very confusing method names (but perhaps intentional) (NM_VERY_CONFUSING_INTENTIONAL)</a></h3> <p> The referenced methods have names that differ only by capitalization. This is very confusing because if the capitalization were identical then one of the methods would override the other. From the existence of other methods, it seems that the existence of both of these methods is intentional, but is sure is confusing. You should try hard to eliminate one of them, unless you are forced to have both due to frozen APIs. </p> <h3><a name="NM_WRONG_PACKAGE_INTENTIONAL">Nm: Method doesn't override method in superclass due to wrong package for parameter (NM_WRONG_PACKAGE_INTENTIONAL)</a></h3> <p> The method in the subclass doesn't override a similar method in a superclass because the type of a parameter doesn't exactly match the type of the corresponding parameter in the superclass. For example, if you have:</p> <blockquote> <pre> import alpha.Foo; public class A { public int f(Foo x) { return 17; } } ---- import beta.Foo; public class B extends A { public int f(Foo x) { return 42; } public int f(alpha.Foo x) { return 27; } } </pre> </blockquote> <p>The <code>f(Foo)</code> method defined in class <code>B</code> doesn't override the <code>f(Foo)</code> method defined in class <code>A</code>, because the argument types are <code>Foo</code>'s from different packages. </p> <p>In this case, the subclass does define a method with a signature identical to the method in the superclass, so this is presumably understood. However, such methods are exceptionally confusing. You should strongly consider removing or deprecating the method with the similar but not identical signature. </p> <h3><a name="ODR_OPEN_DATABASE_RESOURCE">ODR: Method may fail to close database resource (ODR_OPEN_DATABASE_RESOURCE)</a></h3> <p> The method creates a database resource (such as a database connection or row set), does not assign it to any fields, pass it to other methods, or return it, and does not appear to close the object on all paths out of the method.&nbsp; Failure to close database resources on all paths out of a method may result in poor performance, and could cause the application to have problems communicating with the database. </p> <h3><a name="ODR_OPEN_DATABASE_RESOURCE_EXCEPTION_PATH">ODR: Method may fail to close database resource on exception (ODR_OPEN_DATABASE_RESOURCE_EXCEPTION_PATH)</a></h3> <p> The method creates a database resource (such as a database connection or row set), does not assign it to any fields, pass it to other methods, or return it, and does not appear to close the object on all exception paths out of the method.&nbsp; Failure to close database resources on all paths out of a method may result in poor performance, and could cause the application to have problems communicating with the database.</p> <h3><a name="OS_OPEN_STREAM">OS: Method may fail to close stream (OS_OPEN_STREAM)</a></h3> <p> The method creates an IO stream object, does not assign it to any fields, pass it to other methods that might close it, or return it, and does not appear to close the stream on all paths out of the method.&nbsp; This may result in a file descriptor leak.&nbsp; It is generally a good idea to use a <code>finally</code> block to ensure that streams are closed.</p> <h3><a name="OS_OPEN_STREAM_EXCEPTION_PATH">OS: Method may fail to close stream on exception (OS_OPEN_STREAM_EXCEPTION_PATH)</a></h3> <p> The method creates an IO stream object, does not assign it to any fields, pass it to other methods, or return it, and does not appear to close it on all possible exception paths out of the method.&nbsp; This may result in a file descriptor leak.&nbsp; It is generally a good idea to use a <code>finally</code> block to ensure that streams are closed.</p> <h3><a name="PZ_DONT_REUSE_ENTRY_OBJECTS_IN_ITERATORS">PZ: Don't reuse entry objects in iterators (PZ_DONT_REUSE_ENTRY_OBJECTS_IN_ITERATORS)</a></h3> <p> The entrySet() method is allowed to return a view of the underlying Map in which an Iterator and Map.Entry. This clever idea was used in several Map implementations, but introduces the possibility of nasty coding mistakes. If a map <code>m</code> returns such an iterator for an entrySet, then <code>c.addAll(m.entrySet())</code> will go badly wrong. All of the Map implementations in OpenJDK 1.7 have been rewritten to avoid this, you should to. </p> <h3><a name="RC_REF_COMPARISON_BAD_PRACTICE">RC: Suspicious reference comparison to constant (RC_REF_COMPARISON_BAD_PRACTICE)</a></h3> <p> This method compares a reference value to a constant using the == or != operator, where the correct way to compare instances of this type is generally with the equals() method. It is possible to create distinct instances that are equal but do not compare as == since they are different objects. Examples of classes which should generally not be compared by reference are java.lang.Integer, java.lang.Float, etc.</p> <h3><a name="RC_REF_COMPARISON_BAD_PRACTICE_BOOLEAN">RC: Suspicious reference comparison of Boolean values (RC_REF_COMPARISON_BAD_PRACTICE_BOOLEAN)</a></h3> <p> This method compares two Boolean values using the == or != operator. Normally, there are only two Boolean values (Boolean.TRUE and Boolean.FALSE), but it is possible to create other Boolean objects using the <code>new Boolean(b)</code> constructor. It is best to avoid such objects, but if they do exist, then checking Boolean objects for equality using == or != will give results than are different than you would get using <code>.equals(...)</code> </p> <h3><a name="RR_NOT_CHECKED">RR: Method ignores results of InputStream.read() (RR_NOT_CHECKED)</a></h3> <p> This method ignores the return value of one of the variants of <code>java.io.InputStream.read()</code> which can return multiple bytes.&nbsp; If the return value is not checked, the caller will not be able to correctly handle the case where fewer bytes were read than the caller requested.&nbsp; This is a particularly insidious kind of bug, because in many programs, reads from input streams usually do read the full amount of data requested, causing the program to fail only sporadically.</p> <h3><a name="SR_NOT_CHECKED">RR: Method ignores results of InputStream.skip() (SR_NOT_CHECKED)</a></h3> <p> This method ignores the return value of <code>java.io.InputStream.skip()</code> which can skip multiple bytes.&nbsp; If the return value is not checked, the caller will not be able to correctly handle the case where fewer bytes were skipped than the caller requested.&nbsp; This is a particularly insidious kind of bug, because in many programs, skips from input streams usually do skip the full amount of data requested, causing the program to fail only sporadically. With Buffered streams, however, skip() will only skip data in the buffer, and will routinely fail to skip the requested number of bytes.</p> <h3><a name="RV_NEGATING_RESULT_OF_COMPARETO">RV: Negating the result of compareTo()/compare() (RV_NEGATING_RESULT_OF_COMPARETO)</a></h3> <p> This code negatives the return value of a compareTo or compare method. This is a questionable or bad programming practice, since if the return value is Integer.MIN_VALUE, negating the return value won't negate the sign of the result. You can achieve the same intended result by reversing the order of the operands rather than by negating the results. </p> <h3><a name="RV_RETURN_VALUE_IGNORED_BAD_PRACTICE">RV: Method ignores exceptional return value (RV_RETURN_VALUE_IGNORED_BAD_PRACTICE)</a></h3> <p> This method returns a value that is not checked. The return value should be checked since it can indicate an unusual or unexpected function execution. For example, the <code>File.delete()</code> method returns false if the file could not be successfully deleted (rather than throwing an Exception). If you don't check the result, you won't notice if the method invocation signals unexpected behavior by returning an atypical return value. </p> <h3><a name="SI_INSTANCE_BEFORE_FINALS_ASSIGNED">SI: Static initializer creates instance before all static final fields assigned (SI_INSTANCE_BEFORE_FINALS_ASSIGNED)</a></h3> <p> The class's static initializer creates an instance of the class before all of the static final fields are assigned.</p> <h3><a name="SW_SWING_METHODS_INVOKED_IN_SWING_THREAD">SW: Certain swing methods needs to be invoked in Swing thread (SW_SWING_METHODS_INVOKED_IN_SWING_THREAD)</a></h3> <p>(<a href="http://web.archive.org/web/20090526170426/http://java.sun.com/developer/JDCTechTips/2003/tt1208.html">From JDC Tech Tip</a>): The Swing methods show(), setVisible(), and pack() will create the associated peer for the frame. With the creation of the peer, the system creates the event dispatch thread. This makes things problematic because the event dispatch thread could be notifying listeners while pack and validate are still processing. This situation could result in two threads going through the Swing component-based GUI -- it's a serious flaw that could result in deadlocks or other related threading issues. A pack call causes components to be realized. As they are being realized (that is, not necessarily visible), they could trigger listener notification on the event dispatch thread.</p> <h3><a name="SE_BAD_FIELD">Se: Non-transient non-serializable instance field in serializable class (SE_BAD_FIELD)</a></h3> <p> This Serializable class defines a non-primitive instance field which is neither transient, Serializable, or <code>java.lang.Object</code>, and does not appear to implement the <code>Externalizable</code> interface or the <code>readObject()</code> and <code>writeObject()</code> methods.&nbsp; Objects of this class will not be deserialized correctly if a non-Serializable object is stored in this field.</p> <h3><a name="SE_BAD_FIELD_INNER_CLASS">Se: Non-serializable class has a serializable inner class (SE_BAD_FIELD_INNER_CLASS)</a></h3> <p> This Serializable class is an inner class of a non-serializable class. Thus, attempts to serialize it will also attempt to associate instance of the outer class with which it is associated, leading to a runtime error. </p> <p>If possible, making the inner class a static inner class should solve the problem. Making the outer class serializable might also work, but that would mean serializing an instance of the inner class would always also serialize the instance of the outer class, which it often not what you really want. <h3><a name="SE_BAD_FIELD_STORE">Se: Non-serializable value stored into instance field of a serializable class (SE_BAD_FIELD_STORE)</a></h3> <p> A non-serializable value is stored into a non-transient field of a serializable class.</p> <h3><a name="SE_COMPARATOR_SHOULD_BE_SERIALIZABLE">Se: Comparator doesn't implement Serializable (SE_COMPARATOR_SHOULD_BE_SERIALIZABLE)</a></h3> <p> This class implements the <code>Comparator</code> interface. You should consider whether or not it should also implement the <code>Serializable</code> interface. If a comparator is used to construct an ordered collection such as a <code>TreeMap</code>, then the <code>TreeMap</code> will be serializable only if the comparator is also serializable. As most comparators have little or no state, making them serializable is generally easy and good defensive programming. </p> <h3><a name="SE_INNER_CLASS">Se: Serializable inner class (SE_INNER_CLASS)</a></h3> <p> This Serializable class is an inner class. Any attempt to serialize it will also serialize the associated outer instance. The outer instance is serializable, so this won't fail, but it might serialize a lot more data than intended. If possible, making the inner class a static inner class (also known as a nested class) should solve the problem. <h3><a name="SE_NONFINAL_SERIALVERSIONID">Se: serialVersionUID isn't final (SE_NONFINAL_SERIALVERSIONID)</a></h3> <p> This class defines a <code>serialVersionUID</code> field that is not final.&nbsp; The field should be made final if it is intended to specify the version UID for purposes of serialization.</p> <h3><a name="SE_NONLONG_SERIALVERSIONID">Se: serialVersionUID isn't long (SE_NONLONG_SERIALVERSIONID)</a></h3> <p> This class defines a <code>serialVersionUID</code> field that is not long.&nbsp; The field should be made long if it is intended to specify the version UID for purposes of serialization.</p> <h3><a name="SE_NONSTATIC_SERIALVERSIONID">Se: serialVersionUID isn't static (SE_NONSTATIC_SERIALVERSIONID)</a></h3> <p> This class defines a <code>serialVersionUID</code> field that is not static.&nbsp; The field should be made static if it is intended to specify the version UID for purposes of serialization.</p> <h3><a name="SE_NO_SUITABLE_CONSTRUCTOR">Se: Class is Serializable but its superclass doesn't define a void constructor (SE_NO_SUITABLE_CONSTRUCTOR)</a></h3> <p> This class implements the <code>Serializable</code> interface and its superclass does not. When such an object is deserialized, the fields of the superclass need to be initialized by invoking the void constructor of the superclass. Since the superclass does not have one, serialization and deserialization will fail at runtime.</p> <h3><a name="SE_NO_SUITABLE_CONSTRUCTOR_FOR_EXTERNALIZATION">Se: Class is Externalizable but doesn't define a void constructor (SE_NO_SUITABLE_CONSTRUCTOR_FOR_EXTERNALIZATION)</a></h3> <p> This class implements the <code>Externalizable</code> interface, but does not define a void constructor. When Externalizable objects are deserialized, they first need to be constructed by invoking the void constructor. Since this class does not have one, serialization and deserialization will fail at runtime.</p> <h3><a name="SE_READ_RESOLVE_MUST_RETURN_OBJECT">Se: The readResolve method must be declared with a return type of Object. (SE_READ_RESOLVE_MUST_RETURN_OBJECT)</a></h3> <p> In order for the readResolve method to be recognized by the serialization mechanism, it must be declared to have a return type of Object. </p> <h3><a name="SE_TRANSIENT_FIELD_NOT_RESTORED">Se: Transient field that isn't set by deserialization. (SE_TRANSIENT_FIELD_NOT_RESTORED)</a></h3> <p> This class contains a field that is updated at multiple places in the class, thus it seems to be part of the state of the class. However, since the field is marked as transient and not set in readObject or readResolve, it will contain the default value in any deserialized instance of the class. </p> <h3><a name="SE_NO_SERIALVERSIONID">SnVI: Class is Serializable, but doesn't define serialVersionUID (SE_NO_SERIALVERSIONID)</a></h3> <p> This class implements the <code>Serializable</code> interface, but does not define a <code>serialVersionUID</code> field.&nbsp; A change as simple as adding a reference to a .class object will add synthetic fields to the class, which will unfortunately change the implicit serialVersionUID (e.g., adding a reference to <code>String.class</code> will generate a static field <code>class$java$lang$String</code>). Also, different source code to bytecode compilers may use different naming conventions for synthetic variables generated for references to class objects or inner classes. To ensure interoperability of Serializable across versions, consider adding an explicit serialVersionUID.</p> <h3><a name="UI_INHERITANCE_UNSAFE_GETRESOURCE">UI: Usage of GetResource may be unsafe if class is extended (UI_INHERITANCE_UNSAFE_GETRESOURCE)</a></h3> <p>Calling <code>this.getClass().getResource(...)</code> could give results other than expected if this class is extended by a class in another package.</p> <h3><a name="BC_IMPOSSIBLE_CAST">BC: Impossible cast (BC_IMPOSSIBLE_CAST)</a></h3> <p> This cast will always throw a ClassCastException. FindBugs tracks type information from instanceof checks, and also uses more precise information about the types of values returned from methods and loaded from fields. Thus, it may have more precise information that just the declared type of a variable, and can use this to determine that a cast will always throw an exception at runtime. </p> <h3><a name="BC_IMPOSSIBLE_DOWNCAST">BC: Impossible downcast (BC_IMPOSSIBLE_DOWNCAST)</a></h3> <p> This cast will always throw a ClassCastException. The analysis believes it knows the precise type of the value being cast, and the attempt to downcast it to a subtype will always fail by throwing a ClassCastException. </p> <h3><a name="BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY">BC: Impossible downcast of toArray() result (BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY)</a></h3> <p> This code is casting the result of calling <code>toArray()</code> on a collection to a type more specific than <code>Object[]</code>, as in:</p> <pre> String[] getAsArray(Collection&lt;String&gt; c) { return (String[]) c.toArray(); } </pre> <p>This will usually fail by throwing a ClassCastException. The <code>toArray()</code> of almost all collections return an <code>Object[]</code>. They can't really do anything else, since the Collection object has no reference to the declared generic type of the collection. <p>The correct way to do get an array of a specific type from a collection is to use <code>c.toArray(new String[]);</code> or <code>c.toArray(new String[c.size()]);</code> (the latter is slightly more efficient). <p>There is one common/known exception exception to this. The <code>toArray()</code> method of lists returned by <code>Arrays.asList(...)</code> will return a covariantly typed array. For example, <code>Arrays.asArray(new String[] { "a" }).toArray()</code> will return a <code>String []</code>. FindBugs attempts to detect and suppress such cases, but may miss some. </p> <h3><a name="BC_IMPOSSIBLE_INSTANCEOF">BC: instanceof will always return false (BC_IMPOSSIBLE_INSTANCEOF)</a></h3> <p> This instanceof test will always return false. Although this is safe, make sure it isn't an indication of some misunderstanding or some other logic error. </p> <h3><a name="BIT_ADD_OF_SIGNED_BYTE">BIT: Bitwise add of signed byte value (BIT_ADD_OF_SIGNED_BYTE)</a></h3> <p> Adds a byte value and a value which is known to have the 8 lower bits clear. Values loaded from a byte array are sign extended to 32 bits before any any bitwise operations are performed on the value. Thus, if <code>b[0]</code> contains the value <code>0xff</code>, and <code>x</code> is initially 0, then the code <code>((x &lt;&lt; 8) + b[0])</code> will sign extend <code>0xff</code> to get <code>0xffffffff</code>, and thus give the value <code>0xffffffff</code> as the result. </p> <p>In particular, the following code for packing a byte array into an int is badly wrong: </p> <pre> int result = 0; for(int i = 0; i &lt; 4; i++) result = ((result &lt;&lt; 8) + b[i]); </pre> <p>The following idiom will work instead: </p> <pre> int result = 0; for(int i = 0; i &lt; 4; i++) result = ((result &lt;&lt; 8) + (b[i] &amp; 0xff)); </pre> <h3><a name="BIT_AND">BIT: Incompatible bit masks (BIT_AND)</a></h3> <p> This method compares an expression of the form (e &amp; C) to D, which will always compare unequal due to the specific values of constants C and D. This may indicate a logic error or typo.</p> <h3><a name="BIT_AND_ZZ">BIT: Check to see if ((...) & 0) == 0 (BIT_AND_ZZ)</a></h3> <p> This method compares an expression of the form (e &amp; 0) to 0, which will always compare equal. This may indicate a logic error or typo.</p> <h3><a name="BIT_IOR">BIT: Incompatible bit masks (BIT_IOR)</a></h3> <p> This method compares an expression of the form (e | C) to D. which will always compare unequal due to the specific values of constants C and D. This may indicate a logic error or typo.</p> <p> Typically, this bug occurs because the code wants to perform a membership test in a bit set, but uses the bitwise OR operator ("|") instead of bitwise AND ("&amp;").</p> <h3><a name="BIT_IOR_OF_SIGNED_BYTE">BIT: Bitwise OR of signed byte value (BIT_IOR_OF_SIGNED_BYTE)</a></h3> <p> Loads a byte value (e.g., a value loaded from a byte array or returned by a method with return type byte) and performs a bitwise OR with that value. Byte values are sign extended to 32 bits before any any bitwise operations are performed on the value. Thus, if <code>b[0]</code> contains the value <code>0xff</code>, and <code>x</code> is initially 0, then the code <code>((x &lt;&lt; 8) | b[0])</code> will sign extend <code>0xff</code> to get <code>0xffffffff</code>, and thus give the value <code>0xffffffff</code> as the result. </p> <p>In particular, the following code for packing a byte array into an int is badly wrong: </p> <pre> int result = 0; for(int i = 0; i &lt; 4; i++) result = ((result &lt;&lt; 8) | b[i]); </pre> <p>The following idiom will work instead: </p> <pre> int result = 0; for(int i = 0; i &lt; 4; i++) result = ((result &lt;&lt; 8) | (b[i] &amp; 0xff)); </pre> <h3><a name="BIT_SIGNED_CHECK_HIGH_BIT">BIT: Check for sign of bitwise operation (BIT_SIGNED_CHECK_HIGH_BIT)</a></h3> <p> This method compares an expression such as</p> <pre>((event.detail &amp; SWT.SELECTED) &gt; 0)</pre>. <p>Using bit arithmetic and then comparing with the greater than operator can lead to unexpected results (of course depending on the value of SWT.SELECTED). If SWT.SELECTED is a negative number, this is a candidate for a bug. Even when SWT.SELECTED is not negative, it seems good practice to use '!= 0' instead of '&gt; 0'. </p> <p> <em>Boris Bokowski</em> </p> <h3><a name="BOA_BADLY_OVERRIDDEN_ADAPTER">BOA: Class overrides a method implemented in super class Adapter wrongly (BOA_BADLY_OVERRIDDEN_ADAPTER)</a></h3> <p> This method overrides a method found in a parent class, where that class is an Adapter that implements a listener defined in the java.awt.event or javax.swing.event package. As a result, this method will not get called when the event occurs.</p> <h3><a name="ICAST_BAD_SHIFT_AMOUNT">BSHIFT: 32 bit int shifted by an amount not in the range -31..31 (ICAST_BAD_SHIFT_AMOUNT)</a></h3> <p> The code performs shift of a 32 bit int by a constant amount outside the range -31..31. The effect of this is to use the lower 5 bits of the integer value to decide how much to shift by (e.g., shifting by 40 bits is the same as shifting by 8 bits, and shifting by 32 bits is the same as shifting by zero bits). This probably isn't what was expected, and it is at least confusing. </p> <h3><a name="BX_UNBOXED_AND_COERCED_FOR_TERNARY_OPERATOR">Bx: Primitive value is unboxed and coerced for ternary operator (BX_UNBOXED_AND_COERCED_FOR_TERNARY_OPERATOR)</a></h3> <p>A wrapped primitive value is unboxed and converted to another primitive type as part of the evaluation of a conditional ternary operator (the <code> b ? e1 : e2</code> operator). The semantics of Java mandate that if <code>e1</code> and <code>e2</code> are wrapped numeric values, the values are unboxed and converted/coerced to their common type (e.g, if <code>e1</code> is of type <code>Integer</code> and <code>e2</code> is of type <code>Float</code>, then <code>e1</code> is unboxed, converted to a floating point value, and boxed. See JLS Section 15.25. </p> <h3><a name="CO_COMPARETO_RESULTS_MIN_VALUE">Co: compareTo()/compare() returns Integer.MIN_VALUE (CO_COMPARETO_RESULTS_MIN_VALUE)</a></h3> <p> In some situation, this compareTo or compare method returns the constant Integer.MIN_VALUE, which is an exceptionally bad practice. The only thing that matters about the return value of compareTo is the sign of the result. But people will sometimes negate the return value of compareTo, expecting that this will negate the sign of the result. And it will, except in the case where the value returned is Integer.MIN_VALUE. So just return -1 rather than Integer.MIN_VALUE. <h3><a name="DLS_DEAD_LOCAL_INCREMENT_IN_RETURN">DLS: Useless increment in return statement (DLS_DEAD_LOCAL_INCREMENT_IN_RETURN)</a></h3> <p>This statement has a return such as <code>return x++;</code>. A postfix increment/decrement does not impact the value of the expression, so this increment/decrement has no effect. Please verify that this statement does the right thing. </p> <h3><a name="DLS_DEAD_STORE_OF_CLASS_LITERAL">DLS: Dead store of class literal (DLS_DEAD_STORE_OF_CLASS_LITERAL)</a></h3> <p> This instruction assigns a class literal to a variable and then never uses it. <a href="//java.sun.com/j2se/1.5.0/compatibility.html#literal">The behavior of this differs in Java 1.4 and in Java 5.</a> In Java 1.4 and earlier, a reference to <code>Foo.class</code> would force the static initializer for <code>Foo</code> to be executed, if it has not been executed already. In Java 5 and later, it does not. </p> <p>See Sun's <a href="//java.sun.com/j2se/1.5.0/compatibility.html#literal">article on Java SE compatibility</a> for more details and examples, and suggestions on how to force class initialization in Java 5. </p> <h3><a name="DLS_OVERWRITTEN_INCREMENT">DLS: Overwritten increment (DLS_OVERWRITTEN_INCREMENT)</a></h3> <p> The code performs an increment operation (e.g., <code>i++</code>) and then immediately overwrites it. For example, <code>i = i++</code> immediately overwrites the incremented value with the original value. </p> <h3><a name="DMI_ARGUMENTS_WRONG_ORDER">DMI: Reversed method arguments (DMI_ARGUMENTS_WRONG_ORDER)</a></h3> <p> The arguments to this method call seem to be in the wrong order. For example, a call <code>Preconditions.checkNotNull("message", message)</code> has reserved arguments: the value to be checked is the first argument. </p> <h3><a name="DMI_BAD_MONTH">DMI: Bad constant value for month (DMI_BAD_MONTH)</a></h3> <p> This code passes a constant month value outside the expected range of 0..11 to a method. </p> <h3><a name="DMI_BIGDECIMAL_CONSTRUCTED_FROM_DOUBLE">DMI: BigDecimal constructed from double that isn't represented precisely (DMI_BIGDECIMAL_CONSTRUCTED_FROM_DOUBLE)</a></h3> <p> This code creates a BigDecimal from a double value that doesn't translate well to a decimal number. For example, one might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. You probably want to use the BigDecimal.valueOf(double d) method, which uses the String representation of the double to create the BigDecimal (e.g., BigDecimal.valueOf(0.1) gives 0.1). </p> <h3><a name="DMI_CALLING_NEXT_FROM_HASNEXT">DMI: hasNext method invokes next (DMI_CALLING_NEXT_FROM_HASNEXT)</a></h3> <p> The hasNext() method invokes the next() method. This is almost certainly wrong, since the hasNext() method is not supposed to change the state of the iterator, and the next method is supposed to change the state of the iterator. </p> <h3><a name="DMI_COLLECTIONS_SHOULD_NOT_CONTAIN_THEMSELVES">DMI: Collections should not contain themselves (DMI_COLLECTIONS_SHOULD_NOT_CONTAIN_THEMSELVES)</a></h3> <p> This call to a generic collection's method would only make sense if a collection contained itself (e.g., if <code>s.contains(s)</code> were true). This is unlikely to be true and would cause problems if it were true (such as the computation of the hash code resulting in infinite recursion). It is likely that the wrong value is being passed as a parameter. </p> <h3><a name="DMI_DOH">DMI: D'oh! A nonsensical method invocation (DMI_DOH)</a></h3> <p> This partical method invocation doesn't make sense, for reasons that should be apparent from inspection. </p> <h3><a name="DMI_INVOKING_HASHCODE_ON_ARRAY">DMI: Invocation of hashCode on an array (DMI_INVOKING_HASHCODE_ON_ARRAY)</a></h3> <p> The code invokes hashCode on an array. Calling hashCode on an array returns the same value as System.identityHashCode, and ingores the contents and length of the array. If you need a hashCode that depends on the contents of an array <code>a</code>, use <code>java.util.Arrays.hashCode(a)</code>. </p> <h3><a name="DMI_LONG_BITS_TO_DOUBLE_INVOKED_ON_INT">DMI: Double.longBitsToDouble invoked on an int (DMI_LONG_BITS_TO_DOUBLE_INVOKED_ON_INT)</a></h3> <p> The Double.longBitsToDouble method is invoked, but a 32 bit int value is passed as an argument. This almostly certainly is not intended and is unlikely to give the intended result. </p> <h3><a name="DMI_VACUOUS_SELF_COLLECTION_CALL">DMI: Vacuous call to collections (DMI_VACUOUS_SELF_COLLECTION_CALL)</a></h3> <p> This call doesn't make sense. For any collection <code>c</code>, calling <code>c.containsAll(c)</code> should always be true, and <code>c.retainAll(c)</code> should have no effect. </p> <h3><a name="DMI_ANNOTATION_IS_NOT_VISIBLE_TO_REFLECTION">Dm: Can't use reflection to check for presence of annotation without runtime retention (DMI_ANNOTATION_IS_NOT_VISIBLE_TO_REFLECTION)</a></h3> <p> Unless an annotation has itself been annotated with @Retention(RetentionPolicy.RUNTIME), the annotation can't be observed using reflection (e.g., by using the isAnnotationPresent method). .</p> <h3><a name="DMI_FUTILE_ATTEMPT_TO_CHANGE_MAXPOOL_SIZE_OF_SCHEDULED_THREAD_POOL_EXECUTOR">Dm: Futile attempt to change max pool size of ScheduledThreadPoolExecutor (DMI_FUTILE_ATTEMPT_TO_CHANGE_MAXPOOL_SIZE_OF_SCHEDULED_THREAD_POOL_EXECUTOR)</a></h3> <p>(<a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html">Javadoc</a>) While ScheduledThreadPoolExecutor inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect. </p> <h3><a name="DMI_SCHEDULED_THREAD_POOL_EXECUTOR_WITH_ZERO_CORE_THREADS">Dm: Creation of ScheduledThreadPoolExecutor with zero core threads (DMI_SCHEDULED_THREAD_POOL_EXECUTOR_WITH_ZERO_CORE_THREADS)</a></h3> <p>(<a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html#ScheduledThreadPoolExecutor(int)">Javadoc</a>) A ScheduledThreadPoolExecutor with zero core threads will never execute anything; changes to the max pool size are ignored. </p> <h3><a name="DMI_VACUOUS_CALL_TO_EASYMOCK_METHOD">Dm: Useless/vacuous call to EasyMock method (DMI_VACUOUS_CALL_TO_EASYMOCK_METHOD)</a></h3> <p>This call doesn't pass any objects to the EasyMock method, so the call doesn't do anything. </p> <h3><a name="EC_ARRAY_AND_NONARRAY">EC: equals() used to compare array and nonarray (EC_ARRAY_AND_NONARRAY)</a></h3> <p> This method invokes the .equals(Object o) to compare an array and a reference that doesn't seem to be an array. If things being compared are of different types, they are guaranteed to be unequal and the comparison is almost certainly an error. Even if they are both arrays, the equals method on arrays only determines of the two arrays are the same object. To compare the contents of the arrays, use java.util.Arrays.equals(Object[], Object[]). </p> <h3><a name="EC_BAD_ARRAY_COMPARE">EC: Invocation of equals() on an array, which is equivalent to == (EC_BAD_ARRAY_COMPARE)</a></h3> <p> This method invokes the .equals(Object o) method on an array. Since arrays do not override the equals method of Object, calling equals on an array is the same as comparing their addresses. To compare the contents of the arrays, use <code>java.util.Arrays.equals(Object[], Object[])</code>. To compare the addresses of the arrays, it would be less confusing to explicitly check pointer equality using <code>==</code>. </p> <h3><a name="EC_INCOMPATIBLE_ARRAY_COMPARE">EC: equals(...) used to compare incompatible arrays (EC_INCOMPATIBLE_ARRAY_COMPARE)</a></h3> <p> This method invokes the .equals(Object o) to compare two arrays, but the arrays of of incompatible types (e.g., String[] and StringBuffer[], or String[] and int[]). They will never be equal. In addition, when equals(...) is used to compare arrays it only checks to see if they are the same array, and ignores the contents of the arrays. </p> <h3><a name="EC_NULL_ARG">EC: Call to equals(null) (EC_NULL_ARG)</a></h3> <p> This method calls equals(Object), passing a null value as the argument. According to the contract of the equals() method, this call should always return <code>false</code>.</p> <h3><a name="EC_UNRELATED_CLASS_AND_INTERFACE">EC: Call to equals() comparing unrelated class and interface (EC_UNRELATED_CLASS_AND_INTERFACE)</a></h3> <p> This method calls equals(Object) on two references, one of which is a class and the other an interface, where neither the class nor any of its non-abstract subclasses implement the interface. Therefore, the objects being compared are unlikely to be members of the same class at runtime (unless some application classes were not analyzed, or dynamic class loading can occur at runtime). According to the contract of equals(), objects of different classes should always compare as unequal; therefore, according to the contract defined by java.lang.Object.equals(Object), the result of this comparison will always be false at runtime. </p> <h3><a name="EC_UNRELATED_INTERFACES">EC: Call to equals() comparing different interface types (EC_UNRELATED_INTERFACES)</a></h3> <p> This method calls equals(Object) on two references of unrelated interface types, where neither is a subtype of the other, and there are no known non-abstract classes which implement both interfaces. Therefore, the objects being compared are unlikely to be members of the same class at runtime (unless some application classes were not analyzed, or dynamic class loading can occur at runtime). According to the contract of equals(), objects of different classes should always compare as unequal; therefore, according to the contract defined by java.lang.Object.equals(Object), the result of this comparison will always be false at runtime. </p> <h3><a name="EC_UNRELATED_TYPES">EC: Call to equals() comparing different types (EC_UNRELATED_TYPES)</a></h3> <p> This method calls equals(Object) on two references of different class types with no common subclasses. Therefore, the objects being compared are unlikely to be members of the same class at runtime (unless some application classes were not analyzed, or dynamic class loading can occur at runtime). According to the contract of equals(), objects of different classes should always compare as unequal; therefore, according to the contract defined by java.lang.Object.equals(Object), the result of this comparison will always be false at runtime. </p> <h3><a name="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY">EC: Using pointer equality to compare different types (EC_UNRELATED_TYPES_USING_POINTER_EQUALITY)</a></h3> <p> This method uses using pointer equality to compare two references that seem to be of different types. The result of this comparison will always be false at runtime. </p> <h3><a name="EQ_ALWAYS_FALSE">Eq: equals method always returns false (EQ_ALWAYS_FALSE)</a></h3> <p> This class defines an equals method that always returns false. This means that an object is not equal to itself, and it is impossible to create useful Maps or Sets of this class. More fundamentally, it means that equals is not reflexive, one of the requirements of the equals method.</p> <p>The likely intended semantics are object identity: that an object is equal to itself. This is the behavior inherited from class <code>Object</code>. If you need to override an equals inherited from a different superclass, you can use use:</p> <pre> public boolean equals(Object o) { return this == o; } </pre> <h3><a name="EQ_ALWAYS_TRUE">Eq: equals method always returns true (EQ_ALWAYS_TRUE)</a></h3> <p> This class defines an equals method that always returns true. This is imaginative, but not very smart. Plus, it means that the equals method is not symmetric. </p> <h3><a name="EQ_COMPARING_CLASS_NAMES">Eq: equals method compares class names rather than class objects (EQ_COMPARING_CLASS_NAMES)</a></h3> <p> This method checks to see if two objects are the same class by checking to see if the names of their classes are equal. You can have different classes with the same name if they are loaded by different class loaders. Just check to see if the class objects are the same. </p> <h3><a name="EQ_DONT_DEFINE_EQUALS_FOR_ENUM">Eq: Covariant equals() method defined for enum (EQ_DONT_DEFINE_EQUALS_FOR_ENUM)</a></h3> <p> This class defines an enumeration, and equality on enumerations are defined using object identity. Defining a covariant equals method for an enumeration value is exceptionally bad practice, since it would likely result in having two different enumeration values that compare as equals using the covariant enum method, and as not equal when compared normally. Don't do it. </p> <h3><a name="EQ_OTHER_NO_OBJECT">Eq: equals() method defined that doesn't override equals(Object) (EQ_OTHER_NO_OBJECT)</a></h3> <p> This class defines an <code>equals()</code> method, that doesn't override the normal <code>equals(Object)</code> method defined in the base <code>java.lang.Object</code> class.&nbsp; Instead, it inherits an <code>equals(Object)</code> method from a superclass. The class should probably define a <code>boolean equals(Object)</code> method. </p> <h3><a name="EQ_OTHER_USE_OBJECT">Eq: equals() method defined that doesn't override Object.equals(Object) (EQ_OTHER_USE_OBJECT)</a></h3> <p> This class defines an <code>equals()</code> method, that doesn't override the normal <code>equals(Object)</code> method defined in the base <code>java.lang.Object</code> class.&nbsp; The class should probably define a <code>boolean equals(Object)</code> method. </p> <h3><a name="EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC">Eq: equals method overrides equals in superclass and may not be symmetric (EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC)</a></h3> <p> This class defines an equals method that overrides an equals method in a superclass. Both equals methods methods use <code>instanceof</code> in the determination of whether two objects are equal. This is fraught with peril, since it is important that the equals method is symmetrical (in other words, <code>a.equals(b) == b.equals(a)</code>). If B is a subtype of A, and A's equals method checks that the argument is an instanceof A, and B's equals method checks that the argument is an instanceof B, it is quite likely that the equivalence relation defined by these methods is not symmetric. </p> <h3><a name="EQ_SELF_USE_OBJECT">Eq: Covariant equals() method defined, Object.equals(Object) inherited (EQ_SELF_USE_OBJECT)</a></h3> <p> This class defines a covariant version of the <code>equals()</code> method, but inherits the normal <code>equals(Object)</code> method defined in the base <code>java.lang.Object</code> class.&nbsp; The class should probably define a <code>boolean equals(Object)</code> method. </p> <h3><a name="FE_TEST_IF_EQUAL_TO_NOT_A_NUMBER">FE: Doomed test for equality to NaN (FE_TEST_IF_EQUAL_TO_NOT_A_NUMBER)</a></h3> <p> This code checks to see if a floating point value is equal to the special Not A Number value (e.g., <code>if (x == Double.NaN)</code>). However, because of the special semantics of <code>NaN</code>, no value is equal to <code>Nan</code>, including <code>NaN</code>. Thus, <code>x == Double.NaN</code> always evaluates to false. To check to see if a value contained in <code>x</code> is the special Not A Number value, use <code>Double.isNaN(x)</code> (or <code>Float.isNaN(x)</code> if <code>x</code> is floating point precision). </p> <h3><a name="VA_FORMAT_STRING_BAD_ARGUMENT">FS: Format string placeholder incompatible with passed argument (VA_FORMAT_STRING_BAD_ARGUMENT)</a></h3> <p> The format string placeholder is incompatible with the corresponding argument. For example, <code> System.out.println("%d\n", "hello"); </code> <p>The %d placeholder requires a numeric argument, but a string value is passed instead. A runtime exception will occur when this statement is executed. </p> <h3><a name="VA_FORMAT_STRING_BAD_CONVERSION">FS: The type of a supplied argument doesn't match format specifier (VA_FORMAT_STRING_BAD_CONVERSION)</a></h3> <p> One of the arguments is uncompatible with the corresponding format string specifier. As a result, this will generate a runtime exception when executed. For example, <code>String.format("%d", "1")</code> will generate an exception, since the String "1" is incompatible with the format specifier %d. </p> <h3><a name="VA_FORMAT_STRING_EXPECTED_MESSAGE_FORMAT_SUPPLIED">FS: MessageFormat supplied where printf style format expected (VA_FORMAT_STRING_EXPECTED_MESSAGE_FORMAT_SUPPLIED)</a></h3> <p> A method is called that expects a Java printf format string and a list of arguments. However, the format string doesn't contain any format specifiers (e.g., %s) but does contain message format elements (e.g., {0}). It is likely that the code is supplying a MessageFormat string when a printf-style format string is required. At runtime, all of the arguments will be ignored and the format string will be returned exactly as provided without any formatting. </p> <h3><a name="VA_FORMAT_STRING_EXTRA_ARGUMENTS_PASSED">FS: More arguments are passed than are actually used in the format string (VA_FORMAT_STRING_EXTRA_ARGUMENTS_PASSED)</a></h3> <p> A format-string method with a variable number of arguments is called, but more arguments are passed than are actually used by the format string. This won't cause a runtime exception, but the code may be silently omitting information that was intended to be included in the formatted string. </p> <h3><a name="VA_FORMAT_STRING_ILLEGAL">FS: Illegal format string (VA_FORMAT_STRING_ILLEGAL)</a></h3> <p> The format string is syntactically invalid, and a runtime exception will occur when this statement is executed. </p> <h3><a name="VA_FORMAT_STRING_MISSING_ARGUMENT">FS: Format string references missing argument (VA_FORMAT_STRING_MISSING_ARGUMENT)</a></h3> <p> Not enough arguments are passed to satisfy a placeholder in the format string. A runtime exception will occur when this statement is executed. </p> <h3><a name="VA_FORMAT_STRING_NO_PREVIOUS_ARGUMENT">FS: No previous argument for format string (VA_FORMAT_STRING_NO_PREVIOUS_ARGUMENT)</a></h3> <p> The format string specifies a relative index to request that the argument for the previous format specifier be reused. However, there is no previous argument. For example, </p> <p><code>formatter.format("%&lt;s %s", "a", "b")</code> </p> <p>would throw a MissingFormatArgumentException when executed. </p> <h3><a name="GC_UNRELATED_TYPES">GC: No relationship between generic parameter and method argument (GC_UNRELATED_TYPES)</a></h3> <p> This call to a generic collection method contains an argument with an incompatible class from that of the collection's parameter (i.e., the type of the argument is neither a supertype nor a subtype of the corresponding generic type argument). Therefore, it is unlikely that the collection contains any objects that are equal to the method argument used here. Most likely, the wrong value is being passed to the method.</p> <p>In general, instances of two unrelated classes are not equal. For example, if the <code>Foo</code> and <code>Bar</code> classes are not related by subtyping, then an instance of <code>Foo</code> should not be equal to an instance of <code>Bar</code>. Among other issues, doing so will likely result in an equals method that is not symmetrical. For example, if you define the <code>Foo</code> class so that a <code>Foo</code> can be equal to a <code>String</code>, your equals method isn't symmetrical since a <code>String</code> can only be equal to a <code>String</code>. </p> <p>In rare cases, people do define nonsymmetrical equals methods and still manage to make their code work. Although none of the APIs document or guarantee it, it is typically the case that if you check if a <code>Collection&lt;String&gt;</code> contains a <code>Foo</code>, the equals method of argument (e.g., the equals method of the <code>Foo</code> class) used to perform the equality checks. </p> <h3><a name="HE_SIGNATURE_DECLARES_HASHING_OF_UNHASHABLE_CLASS">HE: Signature declares use of unhashable class in hashed construct (HE_SIGNATURE_DECLARES_HASHING_OF_UNHASHABLE_CLASS)</a></h3> <p> A method, field or class declares a generic signature where a non-hashable class is used in context where a hashable class is required. A class that declares an equals method but inherits a hashCode() method from Object is unhashable, since it doesn't fulfill the requirement that equal objects have equal hashCodes. </p> <h3><a name="HE_USE_OF_UNHASHABLE_CLASS">HE: Use of class without a hashCode() method in a hashed data structure (HE_USE_OF_UNHASHABLE_CLASS)</a></h3> <p> A class defines an equals(Object) method but not a hashCode() method, and thus doesn't fulfill the requirement that equal objects have equal hashCodes. An instance of this class is used in a hash data structure, making the need to fix this problem of highest importance. <h3><a name="ICAST_INT_2_LONG_AS_INSTANT">ICAST: int value converted to long and used as absolute time (ICAST_INT_2_LONG_AS_INSTANT)</a></h3> <p> This code converts a 32-bit int value to a 64-bit long value, and then passes that value for a method parameter that requires an absolute time value. An absolute time value is the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT. For example, the following method, intended to convert seconds since the epoc into a Date, is badly broken:</p> <pre> Date getDate(int seconds) { return new Date(seconds * 1000); } </pre> <p>The multiplication is done using 32-bit arithmetic, and then converted to a 64-bit value. When a 32-bit value is converted to 64-bits and used to express an absolute time value, only dates in December 1969 and January 1970 can be represented.</p> <p>Correct implementations for the above method are:</p> <pre> // Fails for dates after 2037 Date getDate(int seconds) { return new Date(seconds * 1000L); } // better, works for all dates Date getDate(long seconds) { return new Date(seconds * 1000); } </pre> <h3><a name="ICAST_INT_CAST_TO_DOUBLE_PASSED_TO_CEIL">ICAST: Integral value cast to double and then passed to Math.ceil (ICAST_INT_CAST_TO_DOUBLE_PASSED_TO_CEIL)</a></h3> <p> This code converts an integral value (e.g., int or long) to a double precision floating point number and then passing the result to the Math.ceil() function, which rounds a double to the next higher integer value. This operation should always be a no-op, since the converting an integer to a double should give a number with no fractional part. It is likely that the operation that generated the value to be passed to Math.ceil was intended to be performed using double precision floating point arithmetic. </p> <h3><a name="ICAST_INT_CAST_TO_FLOAT_PASSED_TO_ROUND">ICAST: int value cast to float and then passed to Math.round (ICAST_INT_CAST_TO_FLOAT_PASSED_TO_ROUND)</a></h3> <p> This code converts an int value to a float precision floating point number and then passing the result to the Math.round() function, which returns the int/long closest to the argument. This operation should always be a no-op, since the converting an integer to a float should give a number with no fractional part. It is likely that the operation that generated the value to be passed to Math.round was intended to be performed using floating point arithmetic. </p> <h3><a name="IJU_ASSERT_METHOD_INVOKED_FROM_RUN_METHOD">IJU: JUnit assertion in run method will not be noticed by JUnit (IJU_ASSERT_METHOD_INVOKED_FROM_RUN_METHOD)</a></h3> <p> A JUnit assertion is performed in a run method. Failed JUnit assertions just result in exceptions being thrown. Thus, if this exception occurs in a thread other than the thread that invokes the test method, the exception will terminate the thread but not result in the test failing. </p> <h3><a name="IJU_BAD_SUITE_METHOD">IJU: TestCase declares a bad suite method (IJU_BAD_SUITE_METHOD)</a></h3> <p> Class is a JUnit TestCase and defines a suite() method. However, the suite method needs to be declared as either</p> <pre>public static junit.framework.Test suite()</pre> or <pre>public static junit.framework.TestSuite suite()</pre> <h3><a name="IJU_NO_TESTS">IJU: TestCase has no tests (IJU_NO_TESTS)</a></h3> <p> Class is a JUnit TestCase but has not implemented any test methods</p> <h3><a name="IJU_SETUP_NO_SUPER">IJU: TestCase defines setUp that doesn't call super.setUp() (IJU_SETUP_NO_SUPER)</a></h3> <p> Class is a JUnit TestCase and implements the setUp method. The setUp method should call super.setUp(), but doesn't.</p> <h3><a name="IJU_SUITE_NOT_STATIC">IJU: TestCase implements a non-static suite method (IJU_SUITE_NOT_STATIC)</a></h3> <p> Class is a JUnit TestCase and implements the suite() method. The suite method should be declared as being static, but isn't.</p> <h3><a name="IJU_TEARDOWN_NO_SUPER">IJU: TestCase defines tearDown that doesn't call super.tearDown() (IJU_TEARDOWN_NO_SUPER)</a></h3> <p> Class is a JUnit TestCase and implements the tearDown method. The tearDown method should call super.tearDown(), but doesn't.</p> <h3><a name="IL_CONTAINER_ADDED_TO_ITSELF">IL: A collection is added to itself (IL_CONTAINER_ADDED_TO_ITSELF)</a></h3> <p>A collection is added to itself. As a result, computing the hashCode of this set will throw a StackOverflowException. </p> <h3><a name="IL_INFINITE_LOOP">IL: An apparent infinite loop (IL_INFINITE_LOOP)</a></h3> <p>This loop doesn't seem to have a way to terminate (other than by perhaps throwing an exception).</p> <h3><a name="IL_INFINITE_RECURSIVE_LOOP">IL: An apparent infinite recursive loop (IL_INFINITE_RECURSIVE_LOOP)</a></h3> <p>This method unconditionally invokes itself. This would seem to indicate an infinite recursive loop that will result in a stack overflow.</p> <h3><a name="IM_MULTIPLYING_RESULT_OF_IREM">IM: Integer multiply of result of integer remainder (IM_MULTIPLYING_RESULT_OF_IREM)</a></h3> <p> The code multiplies the result of an integer remaining by an integer constant. Be sure you don't have your operator precedence confused. For example i % 60 * 1000 is (i % 60) * 1000, not i % (60 * 1000). </p> <h3><a name="INT_BAD_COMPARISON_WITH_INT_VALUE">INT: Bad comparison of int value with long constant (INT_BAD_COMPARISON_WITH_INT_VALUE)</a></h3> <p> This code compares an int value with a long constant that is outside the range of values that can be represented as an int value. This comparison is vacuous and possibily to be incorrect. </p> <h3><a name="INT_BAD_COMPARISON_WITH_NONNEGATIVE_VALUE">INT: Bad comparison of nonnegative value with negative constant (INT_BAD_COMPARISON_WITH_NONNEGATIVE_VALUE)</a></h3> <p> This code compares a value that is guaranteed to be non-negative with a negative constant. </p> <h3><a name="INT_BAD_COMPARISON_WITH_SIGNED_BYTE">INT: Bad comparison of signed byte (INT_BAD_COMPARISON_WITH_SIGNED_BYTE)</a></h3> <p> Signed bytes can only have a value in the range -128 to 127. Comparing a signed byte with a value outside that range is vacuous and likely to be incorrect. To convert a signed byte <code>b</code> to an unsigned value in the range 0..255, use <code>0xff &amp; b</code> </p> <h3><a name="IO_APPENDING_TO_OBJECT_OUTPUT_STREAM">IO: Doomed attempt to append to an object output stream (IO_APPENDING_TO_OBJECT_OUTPUT_STREAM)</a></h3> <p> This code opens a file in append mode and then wraps the result in an object output stream. This won't allow you to append to an existing object output stream stored in a file. If you want to be able to append to an object output stream, you need to keep the object output stream open. </p> <p>The only situation in which opening a file in append mode and the writing an object output stream could work is if on reading the file you plan to open it in random access mode and seek to the byte offset where the append started. </p> <p> TODO: example. </p> <h3><a name="IP_PARAMETER_IS_DEAD_BUT_OVERWRITTEN">IP: A parameter is dead upon entry to a method but overwritten (IP_PARAMETER_IS_DEAD_BUT_OVERWRITTEN)</a></h3> <p> The initial value of this parameter is ignored, and the parameter is overwritten here. This often indicates a mistaken belief that the write to the parameter will be conveyed back to the caller. </p> <h3><a name="MF_CLASS_MASKS_FIELD">MF: Class defines field that masks a superclass field (MF_CLASS_MASKS_FIELD)</a></h3> <p> This class defines a field with the same name as a visible instance field in a superclass. This is confusing, and may indicate an error if methods update or access one of the fields when they wanted the other.</p> <h3><a name="MF_METHOD_MASKS_FIELD">MF: Method defines a variable that obscures a field (MF_METHOD_MASKS_FIELD)</a></h3> <p> This method defines a local variable with the same name as a field in this class or a superclass. This may cause the method to read an uninitialized value from the field, leave the field uninitialized, or both.</p> <h3><a name="NP_ALWAYS_NULL">NP: Null pointer dereference (NP_ALWAYS_NULL)</a></h3> <p> A null pointer is dereferenced here.&nbsp; This will lead to a <code>NullPointerException</code> when the code is executed.</p> <h3><a name="NP_ALWAYS_NULL_EXCEPTION">NP: Null pointer dereference in method on exception path (NP_ALWAYS_NULL_EXCEPTION)</a></h3> <p> A pointer which is null on an exception path is dereferenced here.&nbsp; This will lead to a <code>NullPointerException</code> when the code is executed.&nbsp; Note that because FindBugs currently does not prune infeasible exception paths, this may be a false warning.</p> <p> Also note that FindBugs considers the default case of a switch statement to be an exception path, since the default case is often infeasible.</p> <h3><a name="NP_ARGUMENT_MIGHT_BE_NULL">NP: Method does not check for null argument (NP_ARGUMENT_MIGHT_BE_NULL)</a></h3> <p> A parameter to this method has been identified as a value that should always be checked to see whether or not it is null, but it is being dereferenced without a preceding null check. </p> <h3><a name="NP_CLOSING_NULL">NP: close() invoked on a value that is always null (NP_CLOSING_NULL)</a></h3> <p> close() is being invoked on a value that is always null. If this statement is executed, a null pointer exception will occur. But the big risk here you never close something that should be closed. <h3><a name="NP_GUARANTEED_DEREF">NP: Null value is guaranteed to be dereferenced (NP_GUARANTEED_DEREF)</a></h3> <p> There is a statement or branch that if executed guarantees that a value is null at this point, and that value that is guaranteed to be dereferenced (except on forward paths involving runtime exceptions). </p> <p>Note that a check such as <code>if (x == null) throw new NullPointerException();</code> is treated as a dereference of <code>x</code>. <h3><a name="NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH">NP: Value is null and guaranteed to be dereferenced on exception path (NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH)</a></h3> <p> There is a statement or branch on an exception path that if executed guarantees that a value is null at this point, and that value that is guaranteed to be dereferenced (except on forward paths involving runtime exceptions). </p> <h3><a name="NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR">NP: Nonnull field is not initialized (NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR)</a></h3> <p> The field is marked as nonnull, but isn't written to by the constructor. The field might be initialized elsewhere during constructor, or might always be initialized before use. </p> <h3><a name="NP_NONNULL_PARAM_VIOLATION">NP: Method call passes null to a nonnull parameter (NP_NONNULL_PARAM_VIOLATION)</a></h3> <p> This method passes a null value as the parameter of a method which must be nonnull. Either this parameter has been explicitly marked as @Nonnull, or analysis has determined that this parameter is always dereferenced. </p> <h3><a name="NP_NONNULL_RETURN_VIOLATION">NP: Method may return null, but is declared @NonNull (NP_NONNULL_RETURN_VIOLATION)</a></h3> <p> This method may return a null value, but the method (or a superclass method which it overrides) is declared to return @NonNull. </p> <h3><a name="NP_NULL_INSTANCEOF">NP: A known null value is checked to see if it is an instance of a type (NP_NULL_INSTANCEOF)</a></h3> <p> This instanceof test will always return false, since the value being checked is guaranteed to be null. Although this is safe, make sure it isn't an indication of some misunderstanding or some other logic error. </p> <h3><a name="NP_NULL_ON_SOME_PATH">NP: Possible null pointer dereference (NP_NULL_ON_SOME_PATH)</a></h3> <p> There is a branch of statement that, <em>if executed,</em> guarantees that a null value will be dereferenced, which would generate a <code>NullPointerException</code> when the code is executed. Of course, the problem might be that the branch or statement is infeasible and that the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs. </p> <h3><a name="NP_NULL_ON_SOME_PATH_EXCEPTION">NP: Possible null pointer dereference in method on exception path (NP_NULL_ON_SOME_PATH_EXCEPTION)</a></h3> <p> A reference value which is null on some exception control path is dereferenced here.&nbsp; This may lead to a <code>NullPointerException</code> when the code is executed.&nbsp; Note that because FindBugs currently does not prune infeasible exception paths, this may be a false warning.</p> <p> Also note that FindBugs considers the default case of a switch statement to be an exception path, since the default case is often infeasible.</p> <h3><a name="NP_NULL_PARAM_DEREF">NP: Method call passes null for nonnull parameter (NP_NULL_PARAM_DEREF)</a></h3> <p> This method call passes a null value for a nonnull method parameter. Either the parameter is annotated as a parameter that should always be nonnull, or analysis has shown that it will always be dereferenced. </p> <h3><a name="NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS">NP: Method call passes null for nonnull parameter (NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS)</a></h3> <p> A possibly-null value is passed at a call site where all known target methods require the parameter to be nonnull. Either the parameter is annotated as a parameter that should always be nonnull, or analysis has shown that it will always be dereferenced. </p> <h3><a name="NP_NULL_PARAM_DEREF_NONVIRTUAL">NP: Non-virtual method call passes null for nonnull parameter (NP_NULL_PARAM_DEREF_NONVIRTUAL)</a></h3> <p> A possibly-null value is passed to a nonnull method parameter. Either the parameter is annotated as a parameter that should always be nonnull, or analysis has shown that it will always be dereferenced. </p> <h3><a name="NP_STORE_INTO_NONNULL_FIELD">NP: Store of null value into field annotated NonNull (NP_STORE_INTO_NONNULL_FIELD)</a></h3> <p> A value that could be null is stored into a field that has been annotated as NonNull. </p> <h3><a name="NP_UNWRITTEN_FIELD">NP: Read of unwritten field (NP_UNWRITTEN_FIELD)</a></h3> <p> The program is dereferencing a field that does not seem to ever have a non-null value written to it. Unless the field is initialized via some mechanism not seen by the analysis, dereferencing this value will generate a null pointer exception. </p> <h3><a name="NM_BAD_EQUAL">Nm: Class defines equal(Object); should it be equals(Object)? (NM_BAD_EQUAL)</a></h3> <p> This class defines a method <code>equal(Object)</code>.&nbsp; This method does not override the <code>equals(Object)</code> method in <code>java.lang.Object</code>, which is probably what was intended.</p> <h3><a name="NM_LCASE_HASHCODE">Nm: Class defines hashcode(); should it be hashCode()? (NM_LCASE_HASHCODE)</a></h3> <p> This class defines a method called <code>hashcode()</code>.&nbsp; This method does not override the <code>hashCode()</code> method in <code>java.lang.Object</code>, which is probably what was intended.</p> <h3><a name="NM_LCASE_TOSTRING">Nm: Class defines tostring(); should it be toString()? (NM_LCASE_TOSTRING)</a></h3> <p> This class defines a method called <code>tostring()</code>.&nbsp; This method does not override the <code>toString()</code> method in <code>java.lang.Object</code>, which is probably what was intended.</p> <h3><a name="NM_METHOD_CONSTRUCTOR_CONFUSION">Nm: Apparent method/constructor confusion (NM_METHOD_CONSTRUCTOR_CONFUSION)</a></h3> <p> This regular method has the same name as the class it is defined in. It is likely that this was intended to be a constructor. If it was intended to be a constructor, remove the declaration of a void return value. If you had accidently defined this method, realized the mistake, defined a proper constructor but can't get rid of this method due to backwards compatibility, deprecate the method. </p> <h3><a name="NM_VERY_CONFUSING">Nm: Very confusing method names (NM_VERY_CONFUSING)</a></h3> <p> The referenced methods have names that differ only by capitalization. This is very confusing because if the capitalization were identical then one of the methods would override the other. </p> <h3><a name="NM_WRONG_PACKAGE">Nm: Method doesn't override method in superclass due to wrong package for parameter (NM_WRONG_PACKAGE)</a></h3> <p> The method in the subclass doesn't override a similar method in a superclass because the type of a parameter doesn't exactly match the type of the corresponding parameter in the superclass. For example, if you have:</p> <blockquote> <pre> import alpha.Foo; public class A { public int f(Foo x) { return 17; } } ---- import beta.Foo; public class B extends A { public int f(Foo x) { return 42; } } </pre> </blockquote> <p>The <code>f(Foo)</code> method defined in class <code>B</code> doesn't override the <code>f(Foo)</code> method defined in class <code>A</code>, because the argument types are <code>Foo</code>'s from different packages. </p> <h3><a name="QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT">QBA: Method assigns boolean literal in boolean expression (QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT)</a></h3> <p> This method assigns a literal boolean value (true or false) to a boolean variable inside an if or while expression. Most probably this was supposed to be a boolean comparison using ==, not an assignment using =. </p> <h3><a name="RC_REF_COMPARISON">RC: Suspicious reference comparison (RC_REF_COMPARISON)</a></h3> <p> This method compares two reference values using the == or != operator, where the correct way to compare instances of this type is generally with the equals() method. It is possible to create distinct instances that are equal but do not compare as == since they are different objects. Examples of classes which should generally not be compared by reference are java.lang.Integer, java.lang.Float, etc.</p> <h3><a name="RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE">RCN: Nullcheck of value previously dereferenced (RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE)</a></h3> <p> A value is checked here to see whether it is null, but this value can't be null because it was previously dereferenced and if it were null a null pointer exception would have occurred at the earlier dereference. Essentially, this code and the previous dereference disagree as to whether this value is allowed to be null. Either the check is redundant or the previous dereference is erroneous.</p> <h3><a name="RE_BAD_SYNTAX_FOR_REGULAR_EXPRESSION">RE: Invalid syntax for regular expression (RE_BAD_SYNTAX_FOR_REGULAR_EXPRESSION)</a></h3> <p> The code here uses a regular expression that is invalid according to the syntax for regular expressions. This statement will throw a PatternSyntaxException when executed. </p> <h3><a name="RE_CANT_USE_FILE_SEPARATOR_AS_REGULAR_EXPRESSION">RE: File.separator used for regular expression (RE_CANT_USE_FILE_SEPARATOR_AS_REGULAR_EXPRESSION)</a></h3> <p> The code here uses <code>File.separator</code> where a regular expression is required. This will fail on Windows platforms, where the <code>File.separator</code> is a backslash, which is interpreted in a regular expression as an escape character. Amoung other options, you can just use <code>File.separatorChar=='\\' ? "\\\\" : File.separator</code> instead of <code>File.separator</code> </p> <h3><a name="RE_POSSIBLE_UNINTENDED_PATTERN">RE: "." or "|" used for regular expression (RE_POSSIBLE_UNINTENDED_PATTERN)</a></h3> <p> A String function is being invoked and "." or "|" is being passed to a parameter that takes a regular expression as an argument. Is this what you intended? For example <li>s.replaceAll(".", "/") will return a String in which <em>every</em> character has been replaced by a '/' character <li>s.split(".") <em>always</em> returns a zero length array of String <li>"ab|cd".replaceAll("|", "/") will return "/a/b/|/c/d/" <li>"ab|cd".split("|") will return array with six (!) elements: [, a, b, |, c, d] </p> <h3><a name="RV_01_TO_INT">RV: Random value from 0 to 1 is coerced to the integer 0 (RV_01_TO_INT)</a></h3> <p>A random value from 0 to 1 is being coerced to the integer value 0. You probably want to multiple the random value by something else before coercing it to an integer, or use the <code>Random.nextInt(n)</code> method. </p> <h3><a name="RV_ABSOLUTE_VALUE_OF_HASHCODE">RV: Bad attempt to compute absolute value of signed 32-bit hashcode (RV_ABSOLUTE_VALUE_OF_HASHCODE)</a></h3> <p> This code generates a hashcode and then computes the absolute value of that hashcode. If the hashcode is <code>Integer.MIN_VALUE</code>, then the result will be negative as well (since <code>Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE</code>). </p> <p>One out of 2^32 strings have a hashCode of Integer.MIN_VALUE, including "polygenelubricants" "GydZG_" and ""DESIGNING WORKHOUSES". </p> <h3><a name="RV_ABSOLUTE_VALUE_OF_RANDOM_INT">RV: Bad attempt to compute absolute value of signed random integer (RV_ABSOLUTE_VALUE_OF_RANDOM_INT)</a></h3> <p> This code generates a random signed integer and then computes the absolute value of that random integer. If the number returned by the random number generator is <code>Integer.MIN_VALUE</code>, then the result will be negative as well (since <code>Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE</code>). (Same problem arised for long values as well). </p> <h3><a name="RV_CHECK_COMPARETO_FOR_SPECIFIC_RETURN_VALUE">RV: Code checks for specific values returned by compareTo (RV_CHECK_COMPARETO_FOR_SPECIFIC_RETURN_VALUE)</a></h3> <p> This code invoked a compareTo or compare method, and checks to see if the return value is a specific value, such as 1 or -1. When invoking these methods, you should only check the sign of the result, not for any specific non-zero value. While many or most compareTo and compare methods only return -1, 0 or 1, some of them will return other values. <h3><a name="RV_EXCEPTION_NOT_THROWN">RV: Exception created and dropped rather than thrown (RV_EXCEPTION_NOT_THROWN)</a></h3> <p> This code creates an exception (or error) object, but doesn't do anything with it. For example, something like </p> <blockquote> <pre> if (x &lt; 0) new IllegalArgumentException("x must be nonnegative"); </pre> </blockquote> <p>It was probably the intent of the programmer to throw the created exception:</p> <blockquote> <pre> if (x &lt; 0) throw new IllegalArgumentException("x must be nonnegative"); </pre> </blockquote> <h3><a name="RV_RETURN_VALUE_IGNORED">RV: Method ignores return value (RV_RETURN_VALUE_IGNORED)</a></h3> <p> The return value of this method should be checked. One common cause of this warning is to invoke a method on an immutable object, thinking that it updates the object. For example, in the following code fragment,</p> <blockquote> <pre> String dateString = getHeaderField(name); dateString.trim(); </pre> </blockquote> <p>the programmer seems to be thinking that the trim() method will update the String referenced by dateString. But since Strings are immutable, the trim() function returns a new String value, which is being ignored here. The code should be corrected to: </p> <blockquote> <pre> String dateString = getHeaderField(name); dateString = dateString.trim(); </pre> </blockquote> <h3><a name="RpC_REPEATED_CONDITIONAL_TEST">RpC: Repeated conditional tests (RpC_REPEATED_CONDITIONAL_TEST)</a></h3> <p>The code contains a conditional test is performed twice, one right after the other (e.g., <code>x == 0 || x == 0</code>). Perhaps the second occurrence is intended to be something else (e.g., <code>x == 0 || y == 0</code>). </p> <h3><a name="SA_FIELD_SELF_ASSIGNMENT">SA: Self assignment of field (SA_FIELD_SELF_ASSIGNMENT)</a></h3> <p> This method contains a self assignment of a field; e.g. </p> <pre> int x; public void foo() { x = x; } </pre> <p>Such assignments are useless, and may indicate a logic error or typo.</p> <h3><a name="SA_FIELD_SELF_COMPARISON">SA: Self comparison of field with itself (SA_FIELD_SELF_COMPARISON)</a></h3> <p> This method compares a field with itself, and may indicate a typo or a logic error. Make sure that you are comparing the right things. </p> <h3><a name="SA_FIELD_SELF_COMPUTATION">SA: Nonsensical self computation involving a field (e.g., x & x) (SA_FIELD_SELF_COMPUTATION)</a></h3> <p> This method performs a nonsensical computation of a field with another reference to the same field (e.g., x&x or x-x). Because of the nature of the computation, this operation doesn't seem to make sense, and may indicate a typo or a logic error. Double check the computation. </p> <h3><a name="SA_LOCAL_SELF_ASSIGNMENT_INSTEAD_OF_FIELD">SA: Self assignment of local rather than assignment to field (SA_LOCAL_SELF_ASSIGNMENT_INSTEAD_OF_FIELD)</a></h3> <p> This method contains a self assignment of a local variable, and there is a field with an identical name. assignment appears to have been ; e.g.</p> <pre> int foo; public void setFoo(int foo) { foo = foo; } </pre> <p>The assignment is useless. Did you mean to assign to the field instead?</p> <h3><a name="SA_LOCAL_SELF_COMPARISON">SA: Self comparison of value with itself (SA_LOCAL_SELF_COMPARISON)</a></h3> <p> This method compares a local variable with itself, and may indicate a typo or a logic error. Make sure that you are comparing the right things. </p> <h3><a name="SA_LOCAL_SELF_COMPUTATION">SA: Nonsensical self computation involving a variable (e.g., x & x) (SA_LOCAL_SELF_COMPUTATION)</a></h3> <p> This method performs a nonsensical computation of a local variable with another reference to the same variable (e.g., x&x or x-x). Because of the nature of the computation, this operation doesn't seem to make sense, and may indicate a typo or a logic error. Double check the computation. </p> <h3><a name="SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH">SF: Dead store due to switch statement fall through (SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH)</a></h3> <p> A value stored in the previous switch case is overwritten here due to a switch fall through. It is likely that you forgot to put a break or return at the end of the previous case. </p> <h3><a name="SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH_TO_THROW">SF: Dead store due to switch statement fall through to throw (SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH_TO_THROW)</a></h3> <p> A value stored in the previous switch case is ignored here due to a switch fall through to a place where an exception is thrown. It is likely that you forgot to put a break or return at the end of the previous case. </p> <h3><a name="SIC_THREADLOCAL_DEADLY_EMBRACE">SIC: Deadly embrace of non-static inner class and thread local (SIC_THREADLOCAL_DEADLY_EMBRACE)</a></h3> <p> This class is an inner class, but should probably be a static inner class. As it is, there is a serious danger of a deadly embrace between the inner class and the thread local in the outer class. Because the inner class isn't static, it retains a reference to the outer class. If the thread local contains a reference to an instance of the inner class, the inner and outer instance will both be reachable and not eligible for garbage collection. </p> <h3><a name="SIO_SUPERFLUOUS_INSTANCEOF">SIO: Unnecessary type check done using instanceof operator (SIO_SUPERFLUOUS_INSTANCEOF)</a></h3> <p> Type check performed using the instanceof operator where it can be statically determined whether the object is of the type requested. </p> <h3><a name="SQL_BAD_PREPARED_STATEMENT_ACCESS">SQL: Method attempts to access a prepared statement parameter with index 0 (SQL_BAD_PREPARED_STATEMENT_ACCESS)</a></h3> <p> A call to a setXXX method of a prepared statement was made where the parameter index is 0. As parameter indexes start at index 1, this is always a mistake.</p> <h3><a name="SQL_BAD_RESULTSET_ACCESS">SQL: Method attempts to access a result set field with index 0 (SQL_BAD_RESULTSET_ACCESS)</a></h3> <p> A call to getXXX or updateXXX methods of a result set was made where the field index is 0. As ResultSet fields start at index 1, this is always a mistake.</p> <h3><a name="STI_INTERRUPTED_ON_CURRENTTHREAD">STI: Unneeded use of currentThread() call, to call interrupted() (STI_INTERRUPTED_ON_CURRENTTHREAD)</a></h3> <p> This method invokes the Thread.currentThread() call, just to call the interrupted() method. As interrupted() is a static method, is more simple and clear to use Thread.interrupted(). </p> <h3><a name="STI_INTERRUPTED_ON_UNKNOWNTHREAD">STI: Static Thread.interrupted() method invoked on thread instance (STI_INTERRUPTED_ON_UNKNOWNTHREAD)</a></h3> <p> This method invokes the Thread.interrupted() method on a Thread object that appears to be a Thread object that is not the current thread. As the interrupted() method is static, the interrupted method will be called on a different object than the one the author intended. </p> <h3><a name="SE_METHOD_MUST_BE_PRIVATE">Se: Method must be private in order for serialization to work (SE_METHOD_MUST_BE_PRIVATE)</a></h3> <p> This class implements the <code>Serializable</code> interface, and defines a method for custom serialization/deserialization. But since that method isn't declared private, it will be silently ignored by the serialization/deserialization API.</p> <h3><a name="SE_READ_RESOLVE_IS_STATIC">Se: The readResolve method must not be declared as a static method. (SE_READ_RESOLVE_IS_STATIC)</a></h3> <p> In order for the readResolve method to be recognized by the serialization mechanism, it must not be declared as a static method. </p> <h3><a name="TQ_ALWAYS_VALUE_USED_WHERE_NEVER_REQUIRED">TQ: Value annotated as carrying a type qualifier used where a value that must not carry that qualifier is required (TQ_ALWAYS_VALUE_USED_WHERE_NEVER_REQUIRED)</a></h3> <p> A value specified as carrying a type qualifier annotation is consumed in a location or locations requiring that the value not carry that annotation. </p> <p> More precisely, a value annotated with a type qualifier specifying when=ALWAYS is guaranteed to reach a use or uses where the same type qualifier specifies when=NEVER. </p> <p> For example, say that @NonNegative is a nickname for the type qualifier annotation @Negative(when=When.NEVER). The following code will generate this warning because the return statement requires a @NonNegative value, but receives one that is marked as @Negative. </p> <blockquote> <pre> public @NonNegative Integer example(@Negative Integer value) { return value; } </pre> </blockquote> <h3><a name="TQ_COMPARING_VALUES_WITH_INCOMPATIBLE_TYPE_QUALIFIERS">TQ: Comparing values with incompatible type qualifiers (TQ_COMPARING_VALUES_WITH_INCOMPATIBLE_TYPE_QUALIFIERS)</a></h3> <p> A value specified as carrying a type qualifier annotation is compared with a value that doesn't ever carry that qualifier. </p> <p> More precisely, a value annotated with a type qualifier specifying when=ALWAYS is compared with a value that where the same type qualifier specifies when=NEVER. </p> <p> For example, say that @NonNegative is a nickname for the type qualifier annotation @Negative(when=When.NEVER). The following code will generate this warning because the return statement requires a @NonNegative value, but receives one that is marked as @Negative. </p> <blockquote> <pre> public boolean example(@Negative Integer value1, @NonNegative Integer value2) { return value1.equals(value2); } </pre> </blockquote> <h3><a name="TQ_MAYBE_SOURCE_VALUE_REACHES_ALWAYS_SINK">TQ: Value that might not carry a type qualifier is always used in a way requires that type qualifier (TQ_MAYBE_SOURCE_VALUE_REACHES_ALWAYS_SINK)</a></h3> <p> A value that is annotated as possibility not being an instance of the values denoted by the type qualifier, and the value is guaranteed to be used in a way that requires values denoted by that type qualifier. </p> <h3><a name="TQ_MAYBE_SOURCE_VALUE_REACHES_NEVER_SINK">TQ: Value that might carry a type qualifier is always used in a way prohibits it from having that type qualifier (TQ_MAYBE_SOURCE_VALUE_REACHES_NEVER_SINK)</a></h3> <p> A value that is annotated as possibility being an instance of the values denoted by the type qualifier, and the value is guaranteed to be used in a way that prohibits values denoted by that type qualifier. </p> <h3><a name="TQ_NEVER_VALUE_USED_WHERE_ALWAYS_REQUIRED">TQ: Value annotated as never carrying a type qualifier used where value carrying that qualifier is required (TQ_NEVER_VALUE_USED_WHERE_ALWAYS_REQUIRED)</a></h3> <p> A value specified as not carrying a type qualifier annotation is guaranteed to be consumed in a location or locations requiring that the value does carry that annotation. </p> <p> More precisely, a value annotated with a type qualifier specifying when=NEVER is guaranteed to reach a use or uses where the same type qualifier specifies when=ALWAYS. </p> <p> TODO: example </p> <h3><a name="TQ_UNKNOWN_VALUE_USED_WHERE_ALWAYS_STRICTLY_REQUIRED">TQ: Value without a type qualifier used where a value is required to have that qualifier (TQ_UNKNOWN_VALUE_USED_WHERE_ALWAYS_STRICTLY_REQUIRED)</a></h3> <p> A value is being used in a way that requires the value be annotation with a type qualifier. The type qualifier is strict, so the tool rejects any values that do not have the appropriate annotation. </p> <p> To coerce a value to have a strict annotation, define an identity function where the return value is annotated with the strict annotation. This is the only way to turn a non-annotated value into a value with a strict type qualifier annotation. </p> <h3><a name="UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS">UMAC: Uncallable method defined in anonymous class (UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS)</a></h3> <p> This anonymous class defined a method that is not directly invoked and does not override a method in a superclass. Since methods in other classes cannot directly invoke methods declared in an anonymous class, it seems that this method is uncallable. The method might simply be dead code, but it is also possible that the method is intended to override a method declared in a superclass, and due to an typo or other error the method does not, in fact, override the method it is intended to. </p> <h3><a name="UR_UNINIT_READ">UR: Uninitialized read of field in constructor (UR_UNINIT_READ)</a></h3> <p> This constructor reads a field which has not yet been assigned a value.&nbsp; This is often caused when the programmer mistakenly uses the field instead of one of the constructor's parameters.</p> <h3><a name="UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR">UR: Uninitialized read of field method called from constructor of superclass (UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR)</a></h3> <p> This method is invoked in the constructor of of the superclass. At this point, the fields of the class have not yet initialized.</p> <p>To make this more concrete, consider the following classes:</p> <pre>abstract class A { int hashCode; abstract Object getValue(); A() { hashCode = getValue().hashCode(); } } class B extends A { Object value; B(Object v) { this.value = v; } Object getValue() { return value; } }</pre> <p>When a <code>B</code> is constructed, the constructor for the <code>A</code> class is invoked <em>before</em> the constructor for <code>B</code> sets <code>value</code>. Thus, when the constructor for <code>A</code> invokes <code>getValue</code>, an uninitialized value is read for <code>value</code> </p> <h3><a name="DMI_INVOKING_TOSTRING_ON_ANONYMOUS_ARRAY">USELESS_STRING: Invocation of toString on an unnamed array (DMI_INVOKING_TOSTRING_ON_ANONYMOUS_ARRAY)</a></h3> <p> The code invokes toString on an (anonymous) array. Calling toString on an array generates a fairly useless result such as [C@16f0472. Consider using Arrays.toString to convert the array into a readable String that gives the contents of the array. See Programming Puzzlers, chapter 3, puzzle 12. </p> <h3><a name="DMI_INVOKING_TOSTRING_ON_ARRAY">USELESS_STRING: Invocation of toString on an array (DMI_INVOKING_TOSTRING_ON_ARRAY)</a></h3> <p> The code invokes toString on an array, which will generate a fairly useless result such as [C@16f0472. Consider using Arrays.toString to convert the array into a readable String that gives the contents of the array. See Programming Puzzlers, chapter 3, puzzle 12. </p> <h3><a name="VA_FORMAT_STRING_BAD_CONVERSION_FROM_ARRAY">USELESS_STRING: Array formatted in useless way using format string (VA_FORMAT_STRING_BAD_CONVERSION_FROM_ARRAY)</a></h3> <p> One of the arguments being formatted with a format string is an array. This will be formatted using a fairly useless format, such as [I@304282, which doesn't actually show the contents of the array. Consider wrapping the array using <code>Arrays.asList(...)</code> before handling it off to a formatted. </p> <h3><a name="UWF_NULL_FIELD">UwF: Field only ever set to null (UWF_NULL_FIELD)</a></h3> <p> All writes to this field are of the constant value null, and thus all reads of the field will return null. Check for errors, or remove it if it is useless.</p> <h3><a name="UWF_UNWRITTEN_FIELD">UwF: Unwritten field (UWF_UNWRITTEN_FIELD)</a></h3> <p> This field is never written.&nbsp; All reads of it will return the default value. Check for errors (should it have been initialized?), or remove it if it is useless.</p> <h3><a name="VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_VARARG">VA: Primitive array passed to function expecting a variable number of object arguments (VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_VARARG)</a></h3> <p> This code passes a primitive array to a function that takes a variable number of object arguments. This creates an array of length one to hold the primitive array and passes it to the function. </p> <h3><a name="LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE">LG: Potential lost logger changes due to weak reference in OpenJDK (LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE)</a></h3> <p>OpenJDK introduces a potential incompatibility. In particular, the java.util.logging.Logger behavior has changed. Instead of using strong references, it now uses weak references internally. That's a reasonable change, but unfortunately some code relies on the old behavior - when changing logger configuration, it simply drops the logger reference. That means that the garbage collector is free to reclaim that memory, which means that the logger configuration is lost. For example, consider: </p> <pre>public static void initLogging() throws Exception { Logger logger = Logger.getLogger("edu.umd.cs"); logger.addHandler(new FileHandler()); // call to change logger configuration logger.setUseParentHandlers(false); // another call to change logger configuration }</pre> <p>The logger reference is lost at the end of the method (it doesn't escape the method), so if you have a garbage collection cycle just after the call to initLogging, the logger configuration is lost (because Logger only keeps weak references).</p> <pre>public static void main(String[] args) throws Exception { initLogging(); // adds a file handler to the logger System.gc(); // logger configuration lost Logger.getLogger("edu.umd.cs").info("Some message"); // this isn't logged to the file as expected }</pre> <p><em>Ulf Ochsenfahrt and Eric Fellheimer</em></p> <h3><a name="OBL_UNSATISFIED_OBLIGATION">OBL: Method may fail to clean up stream or resource (OBL_UNSATISFIED_OBLIGATION)</a></h3> <p> This method may fail to clean up (close, dispose of) a stream, database object, or other resource requiring an explicit cleanup operation. </p> <p> In general, if a method opens a stream or other resource, the method should use a try/finally block to ensure that the stream or resource is cleaned up before the method returns. </p> <p> This bug pattern is essentially the same as the OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE bug patterns, but is based on a different (and hopefully better) static analysis technique. We are interested is getting feedback about the usefulness of this bug pattern. To send feedback, either: </p> <ul> <li>send email to findbugs@cs.umd.edu</li> <li>file a bug report: <a href="http://findbugs.sourceforge.net/reportingBugs.html">http://findbugs.sourceforge.net/reportingBugs.html</a></li> </ul> <p> In particular, the false-positive suppression heuristics for this bug pattern have not been extensively tuned, so reports about false positives are helpful to us. </p> <p> See Weimer and Necula, <i>Finding and Preventing Run-Time Error Handling Mistakes</i>, for a description of the analysis technique. </p> <h3><a name="OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE">OBL: Method may fail to clean up stream or resource on checked exception (OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE)</a></h3> <p> This method may fail to clean up (close, dispose of) a stream, database object, or other resource requiring an explicit cleanup operation. </p> <p> In general, if a method opens a stream or other resource, the method should use a try/finally block to ensure that the stream or resource is cleaned up before the method returns. </p> <p> This bug pattern is essentially the same as the OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE bug patterns, but is based on a different (and hopefully better) static analysis technique. We are interested is getting feedback about the usefulness of this bug pattern. To send feedback, either: </p> <ul> <li>send email to findbugs@cs.umd.edu</li> <li>file a bug report: <a href="http://findbugs.sourceforge.net/reportingBugs.html">http://findbugs.sourceforge.net/reportingBugs.html</a></li> </ul> <p> In particular, the false-positive suppression heuristics for this bug pattern have not been extensively tuned, so reports about false positives are helpful to us. </p> <p> See Weimer and Necula, <i>Finding and Preventing Run-Time Error Handling Mistakes</i>, for a description of the analysis technique. </p> <h3><a name="DM_CONVERT_CASE">Dm: Consider using Locale parameterized version of invoked method (DM_CONVERT_CASE)</a></h3> <p> A String is being converted to upper or lowercase, using the platform's default encoding. This may result in improper conversions when used with international characters. Use the </p> <ul> <li>String.toUpperCase( Locale l )</li> <li>String.toLowerCase( Locale l )</li> </ul> <p>versions instead.</p> <h3><a name="DM_DEFAULT_ENCODING">Dm: Reliance on default encoding (DM_DEFAULT_ENCODING)</a></h3> <p> Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly. </p> <h3><a name="DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED">DP: Classloaders should only be created inside doPrivileged block (DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED)</a></h3> <p> This code creates a classloader, which needs permission if a security manage is installed. If this code might be invoked by code that does not have security permissions, then the classloader creation needs to occur inside a doPrivileged block.</p> <h3><a name="DP_DO_INSIDE_DO_PRIVILEGED">DP: Method invoked that should be only be invoked inside a doPrivileged block (DP_DO_INSIDE_DO_PRIVILEGED)</a></h3> <p> This code invokes a method that requires a security permission check. If this code will be granted security permissions, but might be invoked by code that does not have security permissions, then the invocation needs to occur inside a doPrivileged block.</p> <h3><a name="EI_EXPOSE_REP">EI: May expose internal representation by returning reference to mutable object (EI_EXPOSE_REP)</a></h3> <p> Returning a reference to a mutable object value stored in one of the object's fields exposes the internal representation of the object.&nbsp; If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Returning a new copy of the object is better approach in many situations.</p> <h3><a name="EI_EXPOSE_REP2">EI2: May expose internal representation by incorporating reference to mutable object (EI_EXPOSE_REP2)</a></h3> <p> This code stores a reference to an externally mutable object into the internal representation of the object.&nbsp; If instances are accessed by untrusted code, and unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Storing a copy of the object is better approach in many situations.</p> <h3><a name="FI_PUBLIC_SHOULD_BE_PROTECTED">FI: Finalizer should be protected, not public (FI_PUBLIC_SHOULD_BE_PROTECTED)</a></h3> <p> A class's <code>finalize()</code> method should have protected access, not public.</p> <h3><a name="EI_EXPOSE_STATIC_REP2">MS: May expose internal static state by storing a mutable object into a static field (EI_EXPOSE_STATIC_REP2)</a></h3> <p> This code stores a reference to an externally mutable object into a static field. If unchecked changes to the mutable object would compromise security or other important properties, you will need to do something different. Storing a copy of the object is better approach in many situations.</p> <h3><a name="MS_CANNOT_BE_FINAL">MS: Field isn't final and can't be protected from malicious code (MS_CANNOT_BE_FINAL)</a></h3> <p> A mutable static field could be changed by malicious code or by accident from another package. Unfortunately, the way the field is used doesn't allow any easy fix to this problem.</p> <h3><a name="MS_EXPOSE_REP">MS: Public static method may expose internal representation by returning array (MS_EXPOSE_REP)</a></h3> <p> A public static method returns a reference to an array that is part of the static state of the class. Any code that calls this method can freely modify the underlying array. One fix is to return a copy of the array.</p> <h3><a name="MS_FINAL_PKGPROTECT">MS: Field should be both final and package protected (MS_FINAL_PKGPROTECT)</a></h3> <p> A mutable static field could be changed by malicious code or by accident from another package. The field could be made package protected and/or made final to avoid this vulnerability.</p> <h3><a name="MS_MUTABLE_ARRAY">MS: Field is a mutable array (MS_MUTABLE_ARRAY)</a></h3> <p> A final static field references an array and can be accessed by malicious code or by accident from another package. This code can freely modify the contents of the array.</p> <h3><a name="MS_MUTABLE_HASHTABLE">MS: Field is a mutable Hashtable (MS_MUTABLE_HASHTABLE)</a></h3> <p>A final static field references a Hashtable and can be accessed by malicious code or by accident from another package. This code can freely modify the contents of the Hashtable.</p> <h3><a name="MS_OOI_PKGPROTECT">MS: Field should be moved out of an interface and made package protected (MS_OOI_PKGPROTECT)</a></h3> <p> A final static field that is defined in an interface references a mutable object such as an array or hashtable. This mutable object could be changed by malicious code or by accident from another package. To solve this, the field needs to be moved to a class and made package protected to avoid this vulnerability.</p> <h3><a name="MS_PKGPROTECT">MS: Field should be package protected (MS_PKGPROTECT)</a></h3> <p> A mutable static field could be changed by malicious code or by accident. The field could be made package protected to avoid this vulnerability.</p> <h3><a name="MS_SHOULD_BE_FINAL">MS: Field isn't final but should be (MS_SHOULD_BE_FINAL)</a></h3> <p> This static field public but not final, and could be changed by malicious code or by accident from another package. The field could be made final to avoid this vulnerability.</p> <h3><a name="MS_SHOULD_BE_REFACTORED_TO_BE_FINAL">MS: Field isn't final but should be refactored to be so (MS_SHOULD_BE_REFACTORED_TO_BE_FINAL)</a></h3> <p> This static field public but not final, and could be changed by malicious code or by accident from another package. The field could be made final to avoid this vulnerability. However, the static initializer contains more than one write to the field, so doing so will require some refactoring. </p> <h3><a name="AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION">AT: Sequence of calls to concurrent abstraction may not be atomic (AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION)</a></h3> <p>This code contains a sequence of calls to a concurrent abstraction (such as a concurrent hash map). These calls will not be executed atomically. <h3><a name="DC_DOUBLECHECK">DC: Possible double check of field (DC_DOUBLECHECK)</a></h3> <p> This method may contain an instance of double-checked locking.&nbsp; This idiom is not correct according to the semantics of the Java memory model.&nbsp; For more information, see the web page <a href="http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html" >http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html</a>.</p> <h3><a name="DL_SYNCHRONIZATION_ON_BOOLEAN">DL: Synchronization on Boolean (DL_SYNCHRONIZATION_ON_BOOLEAN)</a></h3> <p> The code synchronizes on a boxed primitive constant, such as an Boolean.</p> <pre> private static Boolean inited = Boolean.FALSE; ... synchronized(inited) { if (!inited) { init(); inited = Boolean.TRUE; } } ... </pre> <p>Since there normally exist only two Boolean objects, this code could be synchronizing on the same object as other, unrelated code, leading to unresponsiveness and possible deadlock</p> <p>See CERT <a href="https://www.securecoding.cert.org/confluence/display/java/CON08-J.+Do+not+synchronize+on+objects+that+may+be+reused">CON08-J. Do not synchronize on objects that may be reused</a> for more information.</p> <h3><a name="DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE">DL: Synchronization on boxed primitive (DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE)</a></h3> <p> The code synchronizes on a boxed primitive constant, such as an Integer.</p> <pre> private static Integer count = 0; ... synchronized(count) { count++; } ... </pre> <p>Since Integer objects can be cached and shared, this code could be synchronizing on the same object as other, unrelated code, leading to unresponsiveness and possible deadlock</p> <p>See CERT <a href="https://www.securecoding.cert.org/confluence/display/java/CON08-J.+Do+not+synchronize+on+objects+that+may+be+reused">CON08-J. Do not synchronize on objects that may be reused</a> for more information.</p> <h3><a name="DL_SYNCHRONIZATION_ON_SHARED_CONSTANT">DL: Synchronization on interned String (DL_SYNCHRONIZATION_ON_SHARED_CONSTANT)</a></h3> <p> The code synchronizes on interned String.</p> <pre> private static String LOCK = "LOCK"; ... synchronized(LOCK) { ...} ... </pre> <p>Constant Strings are interned and shared across all other classes loaded by the JVM. Thus, this could is locking on something that other code might also be locking. This could result in very strange and hard to diagnose blocking and deadlock behavior. See <a href="http://www.javalobby.org/java/forums/t96352.html">http://www.javalobby.org/java/forums/t96352.html</a> and <a href="http://jira.codehaus.org/browse/JETTY-352">http://jira.codehaus.org/browse/JETTY-352</a>. </p> <p>See CERT <a href="https://www.securecoding.cert.org/confluence/display/java/CON08-J.+Do+not+synchronize+on+objects+that+may+be+reused">CON08-J. Do not synchronize on objects that may be reused</a> for more information.</p> <h3><a name="DL_SYNCHRONIZATION_ON_UNSHARED_BOXED_PRIMITIVE">DL: Synchronization on boxed primitive values (DL_SYNCHRONIZATION_ON_UNSHARED_BOXED_PRIMITIVE)</a></h3> <p> The code synchronizes on an apparently unshared boxed primitive, such as an Integer.</p> <pre> private static final Integer fileLock = new Integer(1); ... synchronized(fileLock) { .. do something .. } ... </pre> <p>It would be much better, in this code, to redeclare fileLock as</p> <pre> private static final Object fileLock = new Object(); </pre> <p> The existing code might be OK, but it is confusing and a future refactoring, such as the "Remove Boxing" refactoring in IntelliJ, might replace this with the use of an interned Integer object shared throughout the JVM, leading to very confusing behavior and potential deadlock. </p> <h3><a name="DM_MONITOR_WAIT_ON_CONDITION">Dm: Monitor wait() called on Condition (DM_MONITOR_WAIT_ON_CONDITION)</a></h3> <p> This method calls <code>wait()</code> on a <code>java.util.concurrent.locks.Condition</code> object.&nbsp; Waiting for a <code>Condition</code> should be done using one of the <code>await()</code> methods defined by the <code>Condition</code> interface. </p> <h3><a name="DM_USELESS_THREAD">Dm: A thread was created using the default empty run method (DM_USELESS_THREAD)</a></h3> <p>This method creates a thread without specifying a run method either by deriving from the Thread class, or by passing a Runnable object. This thread, then, does nothing but waste time. </p> <h3><a name="ESync_EMPTY_SYNC">ESync: Empty synchronized block (ESync_EMPTY_SYNC)</a></h3> <p> The code contains an empty synchronized block:</p> <pre> synchronized() {} </pre> <p>Empty synchronized blocks are far more subtle and hard to use correctly than most people recognize, and empty synchronized blocks are almost never a better solution than less contrived solutions. </p> <h3><a name="IS2_INCONSISTENT_SYNC">IS: Inconsistent synchronization (IS2_INCONSISTENT_SYNC)</a></h3> <p> The fields of this class appear to be accessed inconsistently with respect to synchronization.&nbsp; This bug report indicates that the bug pattern detector judged that </p> <ul> <li> The class contains a mix of locked and unlocked accesses,</li> <li> The class is <b>not</b> annotated as javax.annotation.concurrent.NotThreadSafe,</li> <li> At least one locked access was performed by one of the class's own methods, and</li> <li> The number of unsynchronized field accesses (reads and writes) was no more than one third of all accesses, with writes being weighed twice as high as reads</li> </ul> <p> A typical bug matching this bug pattern is forgetting to synchronize one of the methods in a class that is intended to be thread-safe.</p> <p> You can select the nodes labeled "Unsynchronized access" to show the code locations where the detector believed that a field was accessed without synchronization.</p> <p> Note that there are various sources of inaccuracy in this detector; for example, the detector cannot statically detect all situations in which a lock is held.&nbsp; Also, even when the detector is accurate in distinguishing locked vs. unlocked accesses, the code in question may still be correct.</p> <h3><a name="IS_FIELD_NOT_GUARDED">IS: Field not guarded against concurrent access (IS_FIELD_NOT_GUARDED)</a></h3> <p> This field is annotated with net.jcip.annotations.GuardedBy or javax.annotation.concurrent.GuardedBy, but can be accessed in a way that seems to violate those annotations.</p> <h3><a name="JLM_JSR166_LOCK_MONITORENTER">JLM: Synchronization performed on Lock (JLM_JSR166_LOCK_MONITORENTER)</a></h3> <p> This method performs synchronization an object that implements java.util.concurrent.locks.Lock. Such an object is locked/unlocked using <code>acquire()</code>/<code>release()</code> rather than using the <code>synchronized (...)</code> construct. </p> <h3><a name="JLM_JSR166_UTILCONCURRENT_MONITORENTER">JLM: Synchronization performed on util.concurrent instance (JLM_JSR166_UTILCONCURRENT_MONITORENTER)</a></h3> <p> This method performs synchronization an object that is an instance of a class from the java.util.concurrent package (or its subclasses). Instances of these classes have their own concurrency control mechanisms that are orthogonal to the synchronization provided by the Java keyword <code>synchronized</code>. For example, synchronizing on an <code>AtomicBoolean</code> will not prevent other threads from modifying the <code>AtomicBoolean</code>.</p> <p>Such code may be correct, but should be carefully reviewed and documented, and may confuse people who have to maintain the code at a later date. </p> <h3><a name="JML_JSR166_CALLING_WAIT_RATHER_THAN_AWAIT">JLM: Using monitor style wait methods on util.concurrent abstraction (JML_JSR166_CALLING_WAIT_RATHER_THAN_AWAIT)</a></h3> <p> This method calls <code>wait()</code>, <code>notify()</code> or <code>notifyAll()()</code> on an object that also provides an <code>await()</code>, <code>signal()</code>, <code>signalAll()</code> method (such as util.concurrent Condition objects). This probably isn't what you want, and even if you do want it, you should consider changing your design, as other developers will find it exceptionally confusing. </p> <h3><a name="LI_LAZY_INIT_STATIC">LI: Incorrect lazy initialization of static field (LI_LAZY_INIT_STATIC)</a></h3> <p> This method contains an unsynchronized lazy initialization of a non-volatile static field. Because the compiler or processor may reorder instructions, threads are not guaranteed to see a completely initialized object, <em>if the method can be called by multiple threads</em>. You can make the field volatile to correct the problem. For more information, see the <a href="http://www.cs.umd.edu/~pugh/java/memoryModel/">Java Memory Model web site</a>. </p> <h3><a name="LI_LAZY_INIT_UPDATE_STATIC">LI: Incorrect lazy initialization and update of static field (LI_LAZY_INIT_UPDATE_STATIC)</a></h3> <p> This method contains an unsynchronized lazy initialization of a static field. After the field is set, the object stored into that location is further updated or accessed. The setting of the field is visible to other threads as soon as it is set. If the futher accesses in the method that set the field serve to initialize the object, then you have a <em>very serious</em> multithreading bug, unless something else prevents any other thread from accessing the stored object until it is fully initialized. </p> <p>Even if you feel confident that the method is never called by multiple threads, it might be better to not set the static field until the value you are setting it to is fully populated/initialized. <h3><a name="ML_SYNC_ON_FIELD_TO_GUARD_CHANGING_THAT_FIELD">ML: Synchronization on field in futile attempt to guard that field (ML_SYNC_ON_FIELD_TO_GUARD_CHANGING_THAT_FIELD)</a></h3> <p> This method synchronizes on a field in what appears to be an attempt to guard against simultaneous updates to that field. But guarding a field gets a lock on the referenced object, not on the field. This may not provide the mutual exclusion you need, and other threads might be obtaining locks on the referenced objects (for other purposes). An example of this pattern would be:</p> <pre> private Long myNtfSeqNbrCounter = new Long(0); private Long getNotificationSequenceNumber() { Long result = null; synchronized(myNtfSeqNbrCounter) { result = new Long(myNtfSeqNbrCounter.longValue() + 1); myNtfSeqNbrCounter = new Long(result.longValue()); } return result; } </pre> <h3><a name="ML_SYNC_ON_UPDATED_FIELD">ML: Method synchronizes on an updated field (ML_SYNC_ON_UPDATED_FIELD)</a></h3> <p> This method synchronizes on an object referenced from a mutable field. This is unlikely to have useful semantics, since different threads may be synchronizing on different objects.</p> <h3><a name="MSF_MUTABLE_SERVLET_FIELD">MSF: Mutable servlet field (MSF_MUTABLE_SERVLET_FIELD)</a></h3> <p>A web server generally only creates one instance of servlet or jsp class (i.e., treats the class as a Singleton), and will have multiple threads invoke methods on that instance to service multiple simultaneous requests. Thus, having a mutable instance field generally creates race conditions. <h3><a name="MWN_MISMATCHED_NOTIFY">MWN: Mismatched notify() (MWN_MISMATCHED_NOTIFY)</a></h3> <p> This method calls Object.notify() or Object.notifyAll() without obviously holding a lock on the object.&nbsp; Calling notify() or notifyAll() without a lock held will result in an <code>IllegalMonitorStateException</code> being thrown.</p> <h3><a name="MWN_MISMATCHED_WAIT">MWN: Mismatched wait() (MWN_MISMATCHED_WAIT)</a></h3> <p> This method calls Object.wait() without obviously holding a lock on the object.&nbsp; Calling wait() without a lock held will result in an <code>IllegalMonitorStateException</code> being thrown.</p> <h3><a name="NN_NAKED_NOTIFY">NN: Naked notify (NN_NAKED_NOTIFY)</a></h3> <p> A call to <code>notify()</code> or <code>notifyAll()</code> was made without any (apparent) accompanying modification to mutable object state.&nbsp; In general, calling a notify method on a monitor is done because some condition another thread is waiting for has become true.&nbsp; However, for the condition to be meaningful, it must involve a heap object that is visible to both threads.</p> <p> This bug does not necessarily indicate an error, since the change to mutable object state may have taken place in a method which then called the method containing the notification.</p> <h3><a name="NP_SYNC_AND_NULL_CHECK_FIELD">NP: Synchronize and null check on the same field. (NP_SYNC_AND_NULL_CHECK_FIELD)</a></h3> <p>Since the field is synchronized on, it seems not likely to be null. If it is null and then synchronized on a NullPointerException will be thrown and the check would be pointless. Better to synchronize on another field.</p> <h3><a name="NO_NOTIFY_NOT_NOTIFYALL">No: Using notify() rather than notifyAll() (NO_NOTIFY_NOT_NOTIFYALL)</a></h3> <p> This method calls <code>notify()</code> rather than <code>notifyAll()</code>.&nbsp; Java monitors are often used for multiple conditions.&nbsp; Calling <code>notify()</code> only wakes up one thread, meaning that the thread woken up might not be the one waiting for the condition that the caller just satisfied.</p> <h3><a name="RS_READOBJECT_SYNC">RS: Class's readObject() method is synchronized (RS_READOBJECT_SYNC)</a></h3> <p> This serializable class defines a <code>readObject()</code> which is synchronized.&nbsp; By definition, an object created by deserialization is only reachable by one thread, and thus there is no need for <code>readObject()</code> to be synchronized.&nbsp; If the <code>readObject()</code> method itself is causing the object to become visible to another thread, that is an example of very dubious coding style.</p> <h3><a name="RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED">RV: Return value of putIfAbsent ignored, value passed to putIfAbsent reused (RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED)</a></h3> The <code>putIfAbsent</code> method is typically used to ensure that a single value is associated with a given key (the first value for which put if absent succeeds). If you ignore the return value and retain a reference to the value passed in, you run the risk of retaining a value that is not the one that is associated with the key in the map. If it matters which one you use and you use the one that isn't stored in the map, your program will behave incorrectly. <h3><a name="RU_INVOKE_RUN">Ru: Invokes run on a thread (did you mean to start it instead?) (RU_INVOKE_RUN)</a></h3> <p> This method explicitly invokes <code>run()</code> on an object.&nbsp; In general, classes implement the <code>Runnable</code> interface because they are going to have their <code>run()</code> method invoked in a new thread, in which case <code>Thread.start()</code> is the right method to call.</p> <h3><a name="SC_START_IN_CTOR">SC: Constructor invokes Thread.start() (SC_START_IN_CTOR)</a></h3> <p> The constructor starts a thread. This is likely to be wrong if the class is ever extended/subclassed, since the thread will be started before the subclass constructor is started.</p> <h3><a name="SP_SPIN_ON_FIELD">SP: Method spins on field (SP_SPIN_ON_FIELD)</a></h3> <p> This method spins in a loop which reads a field.&nbsp; The compiler may legally hoist the read out of the loop, turning the code into an infinite loop.&nbsp; The class should be changed so it uses proper synchronization (including wait and notify calls).</p> <h3><a name="STCAL_INVOKE_ON_STATIC_CALENDAR_INSTANCE">STCAL: Call to static Calendar (STCAL_INVOKE_ON_STATIC_CALENDAR_INSTANCE)</a></h3> <p>Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multihtreaded use. The detector has found a call to an instance of Calendar that has been obtained via a static field. This looks suspicous.</p> <p>For more information on this see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6231579">Sun Bug #6231579</a> and <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6178997">Sun Bug #6178997</a>.</p> <h3><a name="STCAL_INVOKE_ON_STATIC_DATE_FORMAT_INSTANCE">STCAL: Call to static DateFormat (STCAL_INVOKE_ON_STATIC_DATE_FORMAT_INSTANCE)</a></h3> <p>As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. The detector has found a call to an instance of DateFormat that has been obtained via a static field. This looks suspicous.</p> <p>For more information on this see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6231579">Sun Bug #6231579</a> and <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6178997">Sun Bug #6178997</a>.</p> <h3><a name="STCAL_STATIC_CALENDAR_INSTANCE">STCAL: Static Calendar field (STCAL_STATIC_CALENDAR_INSTANCE)</a></h3> <p>Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multihtreaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application. Under 1.4 problems seem to surface less often than under Java 5 where you will probably see random ArrayIndexOutOfBoundsExceptions or IndexOutOfBoundsExceptions in sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate().</p> <p>You may also experience serialization problems.</p> <p>Using an instance field is recommended.</p> <p>For more information on this see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6231579">Sun Bug #6231579</a> and <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6178997">Sun Bug #6178997</a>.</p> <h3><a name="STCAL_STATIC_SIMPLE_DATE_FORMAT_INSTANCE">STCAL: Static DateFormat (STCAL_STATIC_SIMPLE_DATE_FORMAT_INSTANCE)</a></h3> <p>As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application.</p> <p>You may also experience serialization problems.</p> <p>Using an instance field is recommended.</p> <p>For more information on this see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6231579">Sun Bug #6231579</a> and <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6178997">Sun Bug #6178997</a>.</p> <h3><a name="SWL_SLEEP_WITH_LOCK_HELD">SWL: Method calls Thread.sleep() with a lock held (SWL_SLEEP_WITH_LOCK_HELD)</a></h3> <p> This method calls Thread.sleep() with a lock held. This may result in very poor performance and scalability, or a deadlock, since other threads may be waiting to acquire the lock. It is a much better idea to call wait() on the lock, which releases the lock and allows other threads to run. </p> <h3><a name="TLW_TWO_LOCK_WAIT">TLW: Wait with two locks held (TLW_TWO_LOCK_WAIT)</a></h3> <p> Waiting on a monitor while two locks are held may cause deadlock. &nbsp; Performing a wait only releases the lock on the object being waited on, not any other locks. &nbsp; This not necessarily a bug, but is worth examining closely.</p> <h3><a name="UG_SYNC_SET_UNSYNC_GET">UG: Unsynchronized get method, synchronized set method (UG_SYNC_SET_UNSYNC_GET)</a></h3> <p> This class contains similarly-named get and set methods where the set method is synchronized and the get method is not.&nbsp; This may result in incorrect behavior at runtime, as callers of the get method will not necessarily see a consistent state for the object.&nbsp; The get method should be made synchronized.</p> <h3><a name="UL_UNRELEASED_LOCK">UL: Method does not release lock on all paths (UL_UNRELEASED_LOCK)</a></h3> <p> This method acquires a JSR-166 (<code>java.util.concurrent</code>) lock, but does not release it on all paths out of the method. In general, the correct idiom for using a JSR-166 lock is: </p> <pre> Lock l = ...; l.lock(); try { // do something } finally { l.unlock(); } </pre> <h3><a name="UL_UNRELEASED_LOCK_EXCEPTION_PATH">UL: Method does not release lock on all exception paths (UL_UNRELEASED_LOCK_EXCEPTION_PATH)</a></h3> <p> This method acquires a JSR-166 (<code>java.util.concurrent</code>) lock, but does not release it on all exception paths out of the method. In general, the correct idiom for using a JSR-166 lock is: </p> <pre> Lock l = ...; l.lock(); try { // do something } finally { l.unlock(); } </pre> <h3><a name="UW_UNCOND_WAIT">UW: Unconditional wait (UW_UNCOND_WAIT)</a></h3> <p> This method contains a call to <code>java.lang.Object.wait()</code> which is not guarded by conditional control flow.&nbsp; The code should verify that condition it intends to wait for is not already satisfied before calling wait; any previous notifications will be ignored. </p> <h3><a name="VO_VOLATILE_INCREMENT">VO: An increment to a volatile field isn't atomic (VO_VOLATILE_INCREMENT)</a></h3> <p>This code increments a volatile field. Increments of volatile fields aren't atomic. If more than one thread is incrementing the field at the same time, increments could be lost. </p> <h3><a name="VO_VOLATILE_REFERENCE_TO_ARRAY">VO: A volatile reference to an array doesn't treat the array elements as volatile (VO_VOLATILE_REFERENCE_TO_ARRAY)</a></h3> <p>This declares a volatile reference to an array, which might not be what you want. With a volatile reference to an array, reads and writes of the reference to the array are treated as volatile, but the array elements are non-volatile. To get volatile array elements, you will need to use one of the atomic array classes in java.util.concurrent (provided in Java 5.0).</p> <h3><a name="WL_USING_GETCLASS_RATHER_THAN_CLASS_LITERAL">WL: Synchronization on getClass rather than class literal (WL_USING_GETCLASS_RATHER_THAN_CLASS_LITERAL)</a></h3> <p> This instance method synchronizes on <code>this.getClass()</code>. If this class is subclassed, subclasses will synchronize on the class object for the subclass, which isn't likely what was intended. For example, consider this code from java.awt.Label:</p> <pre> private static final String base = "label"; private static int nameCounter = 0; String constructComponentName() { synchronized (getClass()) { return base + nameCounter++; } } </pre> <p>Subclasses of <code>Label</code> won't synchronize on the same subclass, giving rise to a datarace. Instead, this code should be synchronizing on <code>Label.class</code></p> <pre> private static final String base = "label"; private static int nameCounter = 0; String constructComponentName() { synchronized (Label.class) { return base + nameCounter++; } } </pre> <p>Bug pattern contributed by Jason Mehrens</p> <h3><a name="WS_WRITEOBJECT_SYNC">WS: Class's writeObject() method is synchronized but nothing else is (WS_WRITEOBJECT_SYNC)</a></h3> <p> This class has a <code>writeObject()</code> method which is synchronized; however, no other method of the class is synchronized.</p> <h3><a name="WA_AWAIT_NOT_IN_LOOP">Wa: Condition.await() not in loop (WA_AWAIT_NOT_IN_LOOP)</a></h3> <p> This method contains a call to <code>java.util.concurrent.await()</code> (or variants) which is not in a loop.&nbsp; If the object is used for multiple conditions, the condition the caller intended to wait for might not be the one that actually occurred.</p> <h3><a name="WA_NOT_IN_LOOP">Wa: Wait not in loop (WA_NOT_IN_LOOP)</a></h3> <p> This method contains a call to <code>java.lang.Object.wait()</code> which is not in a loop.&nbsp; If the monitor is used for multiple conditions, the condition the caller intended to wait for might not be the one that actually occurred.</p> <h3><a name="BX_BOXING_IMMEDIATELY_UNBOXED">Bx: Primitive value is boxed and then immediately unboxed (BX_BOXING_IMMEDIATELY_UNBOXED)</a></h3> <p>A primitive is boxed, and then immediately unboxed. This probably is due to a manual boxing in a place where an unboxed value is required, thus forcing the compiler to immediately undo the work of the boxing. </p> <h3><a name="BX_BOXING_IMMEDIATELY_UNBOXED_TO_PERFORM_COERCION">Bx: Primitive value is boxed then unboxed to perform primitive coercion (BX_BOXING_IMMEDIATELY_UNBOXED_TO_PERFORM_COERCION)</a></h3> <p>A primitive boxed value constructed and then immediately converted into a different primitive type (e.g., <code>new Double(d).intValue()</code>). Just perform direct primitive coercion (e.g., <code>(int) d</code>).</p> <h3><a name="BX_UNBOXING_IMMEDIATELY_REBOXED">Bx: Boxed value is unboxed and then immediately reboxed (BX_UNBOXING_IMMEDIATELY_REBOXED)</a></h3> <p>A boxed value is unboxed and then immediately reboxed. </p> <h3><a name="DM_BOXED_PRIMITIVE_FOR_PARSING">Bx: Boxing/unboxing to parse a primitive (DM_BOXED_PRIMITIVE_FOR_PARSING)</a></h3> <p>A boxed primitive is created from a String, just to extract the unboxed primitive value. It is more efficient to just call the static parseXXX method.</p> <h3><a name="DM_BOXED_PRIMITIVE_TOSTRING">Bx: Method allocates a boxed primitive just to call toString (DM_BOXED_PRIMITIVE_TOSTRING)</a></h3> <p>A boxed primitive is allocated just to call toString(). It is more effective to just use the static form of toString which takes the primitive value. So,</p> <table> <tr><th>Replace...</th><th>With this...</th></tr> <tr><td>new Integer(1).toString()</td><td>Integer.toString(1)</td></tr> <tr><td>new Long(1).toString()</td><td>Long.toString(1)</td></tr> <tr><td>new Float(1.0).toString()</td><td>Float.toString(1.0)</td></tr> <tr><td>new Double(1.0).toString()</td><td>Double.toString(1.0)</td></tr> <tr><td>new Byte(1).toString()</td><td>Byte.toString(1)</td></tr> <tr><td>new Short(1).toString()</td><td>Short.toString(1)</td></tr> <tr><td>new Boolean(true).toString()</td><td>Boolean.toString(true)</td></tr> </table> <h3><a name="DM_FP_NUMBER_CTOR">Bx: Method invokes inefficient floating-point Number constructor; use static valueOf instead (DM_FP_NUMBER_CTOR)</a></h3> <p> Using <code>new Double(double)</code> is guaranteed to always result in a new object whereas <code>Double.valueOf(double)</code> allows caching of values to be done by the compiler, class library, or JVM. Using of cached values avoids object allocation and the code will be faster. </p> <p> Unless the class must be compatible with JVMs predating Java 1.5, use either autoboxing or the <code>valueOf()</code> method when creating instances of <code>Double</code> and <code>Float</code>. </p> <h3><a name="DM_NUMBER_CTOR">Bx: Method invokes inefficient Number constructor; use static valueOf instead (DM_NUMBER_CTOR)</a></h3> <p> Using <code>new Integer(int)</code> is guaranteed to always result in a new object whereas <code>Integer.valueOf(int)</code> allows caching of values to be done by the compiler, class library, or JVM. Using of cached values avoids object allocation and the code will be faster. </p> <p> Values between -128 and 127 are guaranteed to have corresponding cached instances and using <code>valueOf</code> is approximately 3.5 times faster than using constructor. For values outside the constant range the performance of both styles is the same. </p> <p> Unless the class must be compatible with JVMs predating Java 1.5, use either autoboxing or the <code>valueOf()</code> method when creating instances of <code>Long</code>, <code>Integer</code>, <code>Short</code>, <code>Character</code>, and <code>Byte</code>. </p> <h3><a name="DMI_BLOCKING_METHODS_ON_URL">Dm: The equals and hashCode methods of URL are blocking (DMI_BLOCKING_METHODS_ON_URL)</a></h3> <p> The equals and hashCode method of URL perform domain name resolution, this can result in a big performance hit. See <a href="http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html">http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html</a> for more information. Consider using <code>java.net.URI</code> instead. </p> <h3><a name="DMI_COLLECTION_OF_URLS">Dm: Maps and sets of URLs can be performance hogs (DMI_COLLECTION_OF_URLS)</a></h3> <p> This method or field is or uses a Map or Set of URLs. Since both the equals and hashCode method of URL perform domain name resolution, this can result in a big performance hit. See <a href="http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html">http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html</a> for more information. Consider using <code>java.net.URI</code> instead. </p> <h3><a name="DM_BOOLEAN_CTOR">Dm: Method invokes inefficient Boolean constructor; use Boolean.valueOf(...) instead (DM_BOOLEAN_CTOR)</a></h3> <p> Creating new instances of <code>java.lang.Boolean</code> wastes memory, since <code>Boolean</code> objects are immutable and there are only two useful values of this type.&nbsp; Use the <code>Boolean.valueOf()</code> method (or Java 1.5 autoboxing) to create <code>Boolean</code> objects instead.</p> <h3><a name="DM_GC">Dm: Explicit garbage collection; extremely dubious except in benchmarking code (DM_GC)</a></h3> <p> Code explicitly invokes garbage collection. Except for specific use in benchmarking, this is very dubious.</p> <p>In the past, situations where people have explicitly invoked the garbage collector in routines such as close or finalize methods has led to huge performance black holes. Garbage collection can be expensive. Any situation that forces hundreds or thousands of garbage collections will bring the machine to a crawl.</p> <h3><a name="DM_NEW_FOR_GETCLASS">Dm: Method allocates an object, only to get the class object (DM_NEW_FOR_GETCLASS)</a></h3> <p>This method allocates an object just to call getClass() on it, in order to retrieve the Class object for it. It is simpler to just access the .class property of the class.</p> <h3><a name="DM_NEXTINT_VIA_NEXTDOUBLE">Dm: Use the nextInt method of Random rather than nextDouble to generate a random integer (DM_NEXTINT_VIA_NEXTDOUBLE)</a></h3> <p>If <code>r</code> is a <code>java.util.Random</code>, you can generate a random number from <code>0</code> to <code>n-1</code> using <code>r.nextInt(n)</code>, rather than using <code>(int)(r.nextDouble() * n)</code>. </p> <p>The argument to nextInt must be positive. If, for example, you want to generate a random value from -99 to 0, use <code>-r.nextInt(100)</code>. </p> <h3><a name="DM_STRING_CTOR">Dm: Method invokes inefficient new String(String) constructor (DM_STRING_CTOR)</a></h3> <p> Using the <code>java.lang.String(String)</code> constructor wastes memory because the object so constructed will be functionally indistinguishable from the <code>String</code> passed as a parameter.&nbsp; Just use the argument <code>String</code> directly.</p> <h3><a name="DM_STRING_TOSTRING">Dm: Method invokes toString() method on a String (DM_STRING_TOSTRING)</a></h3> <p> Calling <code>String.toString()</code> is just a redundant operation. Just use the String.</p> <h3><a name="DM_STRING_VOID_CTOR">Dm: Method invokes inefficient new String() constructor (DM_STRING_VOID_CTOR)</a></h3> <p> Creating a new <code>java.lang.String</code> object using the no-argument constructor wastes memory because the object so created will be functionally indistinguishable from the empty string constant <code>""</code>.&nbsp; Java guarantees that identical string constants will be represented by the same <code>String</code> object.&nbsp; Therefore, you should just use the empty string constant directly.</p> <h3><a name="HSC_HUGE_SHARED_STRING_CONSTANT">HSC: Huge string constants is duplicated across multiple class files (HSC_HUGE_SHARED_STRING_CONSTANT)</a></h3> <p> A large String constant is duplicated across multiple class files. This is likely because a final field is initialized to a String constant, and the Java language mandates that all references to a final field from other classes be inlined into that classfile. See <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6447475">JDK bug 6447475</a> for a description of an occurrence of this bug in the JDK and how resolving it reduced the size of the JDK by 1 megabyte. </p> <h3><a name="ITA_INEFFICIENT_TO_ARRAY">ITA: Method uses toArray() with zero-length array argument (ITA_INEFFICIENT_TO_ARRAY)</a></h3> <p> This method uses the toArray() method of a collection derived class, and passes in a zero-length prototype array argument. It is more efficient to use <code>myCollection.toArray(new Foo[myCollection.size()])</code> If the array passed in is big enough to store all of the elements of the collection, then it is populated and returned directly. This avoids the need to create a second array (by reflection) to return as the result.</p> <h3><a name="SBSC_USE_STRINGBUFFER_CONCATENATION">SBSC: Method concatenates strings using + in a loop (SBSC_USE_STRINGBUFFER_CONCATENATION)</a></h3> <p> The method seems to be building a String using concatenation in a loop. In each iteration, the String is converted to a StringBuffer/StringBuilder, appended to, and converted back to a String. This can lead to a cost quadratic in the number of iterations, as the growing string is recopied in each iteration. </p> <p>Better performance can be obtained by using a StringBuffer (or StringBuilder in Java 1.5) explicitly.</p> <p> For example:</p> <pre> // This is bad String s = ""; for (int i = 0; i &lt; field.length; ++i) { s = s + field[i]; } // This is better StringBuffer buf = new StringBuffer(); for (int i = 0; i &lt; field.length; ++i) { buf.append(field[i]); } String s = buf.toString(); </pre> <h3><a name="SIC_INNER_SHOULD_BE_STATIC">SIC: Should be a static inner class (SIC_INNER_SHOULD_BE_STATIC)</a></h3> <p> This class is an inner class, but does not use its embedded reference to the object which created it.&nbsp; This reference makes the instances of the class larger, and may keep the reference to the creator object alive longer than necessary.&nbsp; If possible, the class should be made static. </p> <h3><a name="SIC_INNER_SHOULD_BE_STATIC_ANON">SIC: Could be refactored into a named static inner class (SIC_INNER_SHOULD_BE_STATIC_ANON)</a></h3> <p> This class is an inner class, but does not use its embedded reference to the object which created it.&nbsp; This reference makes the instances of the class larger, and may keep the reference to the creator object alive longer than necessary.&nbsp; If possible, the class should be made into a <em>static</em> inner class. Since anonymous inner classes cannot be marked as static, doing this will require refactoring the inner class so that it is a named inner class.</p> <h3><a name="SIC_INNER_SHOULD_BE_STATIC_NEEDS_THIS">SIC: Could be refactored into a static inner class (SIC_INNER_SHOULD_BE_STATIC_NEEDS_THIS)</a></h3> <p> This class is an inner class, but does not use its embedded reference to the object which created it except during construction of the inner object.&nbsp; This reference makes the instances of the class larger, and may keep the reference to the creator object alive longer than necessary.&nbsp; If possible, the class should be made into a <em>static</em> inner class. Since the reference to the outer object is required during construction of the inner instance, the inner class will need to be refactored so as to pass a reference to the outer instance to the constructor for the inner class.</p> <h3><a name="SS_SHOULD_BE_STATIC">SS: Unread field: should this field be static? (SS_SHOULD_BE_STATIC)</a></h3> <p> This class contains an instance final field that is initialized to a compile-time static value. Consider making the field static.</p> <h3><a name="UM_UNNECESSARY_MATH">UM: Method calls static Math class method on a constant value (UM_UNNECESSARY_MATH)</a></h3> <p> This method uses a static method from java.lang.Math on a constant value. This method's result in this case, can be determined statically, and is faster and sometimes more accurate to just use the constant. Methods detected are: </p> <table> <tr> <th>Method</th> <th>Parameter</th> </tr> <tr> <td>abs</td> <td>-any-</td> </tr> <tr> <td>acos</td> <td>0.0 or 1.0</td> </tr> <tr> <td>asin</td> <td>0.0 or 1.0</td> </tr> <tr> <td>atan</td> <td>0.0 or 1.0</td> </tr> <tr> <td>atan2</td> <td>0.0</td> </tr> <tr> <td>cbrt</td> <td>0.0 or 1.0</td> </tr> <tr> <td>ceil</td> <td>-any-</td> </tr> <tr> <td>cos</td> <td>0.0</td> </tr> <tr> <td>cosh</td> <td>0.0</td> </tr> <tr> <td>exp</td> <td>0.0 or 1.0</td> </tr> <tr> <td>expm1</td> <td>0.0</td> </tr> <tr> <td>floor</td> <td>-any-</td> </tr> <tr> <td>log</td> <td>0.0 or 1.0</td> </tr> <tr> <td>log10</td> <td>0.0 or 1.0</td> </tr> <tr> <td>rint</td> <td>-any-</td> </tr> <tr> <td>round</td> <td>-any-</td> </tr> <tr> <td>sin</td> <td>0.0</td> </tr> <tr> <td>sinh</td> <td>0.0</td> </tr> <tr> <td>sqrt</td> <td>0.0 or 1.0</td> </tr> <tr> <td>tan</td> <td>0.0</td> </tr> <tr> <td>tanh</td> <td>0.0</td> </tr> <tr> <td>toDegrees</td> <td>0.0 or 1.0</td> </tr> <tr> <td>toRadians</td> <td>0.0</td> </tr> </table> <h3><a name="UPM_UNCALLED_PRIVATE_METHOD">UPM: Private method is never called (UPM_UNCALLED_PRIVATE_METHOD)</a></h3> <p> This private method is never called. Although it is possible that the method will be invoked through reflection, it is more likely that the method is never used, and should be removed. </p> <h3><a name="URF_UNREAD_FIELD">UrF: Unread field (URF_UNREAD_FIELD)</a></h3> <p> This field is never read.&nbsp; Consider removing it from the class.</p> <h3><a name="UUF_UNUSED_FIELD">UuF: Unused field (UUF_UNUSED_FIELD)</a></h3> <p> This field is never used.&nbsp; Consider removing it from the class.</p> <h3><a name="WMI_WRONG_MAP_ITERATOR">WMI: Inefficient use of keySet iterator instead of entrySet iterator (WMI_WRONG_MAP_ITERATOR)</a></h3> <p> This method accesses the value of a Map entry, using a key that was retrieved from a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the Map.get(key) lookup.</p> <h3><a name="DMI_CONSTANT_DB_PASSWORD">Dm: Hardcoded constant database password (DMI_CONSTANT_DB_PASSWORD)</a></h3> <p>This code creates a database connect using a hardcoded, constant password. Anyone with access to either the source code or the compiled code can easily learn the password. </p> <h3><a name="DMI_EMPTY_DB_PASSWORD">Dm: Empty database password (DMI_EMPTY_DB_PASSWORD)</a></h3> <p>This code creates a database connect using a blank or empty password. This indicates that the database is not protected by a password. </p> <h3><a name="HRS_REQUEST_PARAMETER_TO_COOKIE">HRS: HTTP cookie formed from untrusted input (HRS_REQUEST_PARAMETER_TO_COOKIE)</a></h3> <p>This code constructs an HTTP Cookie using an untrusted HTTP parameter. If this cookie is added to an HTTP response, it will allow a HTTP response splitting vulnerability. See <a href="http://en.wikipedia.org/wiki/HTTP_response_splitting">http://en.wikipedia.org/wiki/HTTP_response_splitting</a> for more information.</p> <p>FindBugs looks only for the most blatant, obvious cases of HTTP response splitting. If FindBugs found <em>any</em>, you <em>almost certainly</em> have more vulnerabilities that FindBugs doesn't report. If you are concerned about HTTP response splitting, you should seriously consider using a commercial static analysis or pen-testing tool. </p> <h3><a name="HRS_REQUEST_PARAMETER_TO_HTTP_HEADER">HRS: HTTP Response splitting vulnerability (HRS_REQUEST_PARAMETER_TO_HTTP_HEADER)</a></h3> <p>This code directly writes an HTTP parameter to an HTTP header, which allows for a HTTP response splitting vulnerability. See <a href="http://en.wikipedia.org/wiki/HTTP_response_splitting">http://en.wikipedia.org/wiki/HTTP_response_splitting</a> for more information.</p> <p>FindBugs looks only for the most blatant, obvious cases of HTTP response splitting. If FindBugs found <em>any</em>, you <em>almost certainly</em> have more vulnerabilities that FindBugs doesn't report. If you are concerned about HTTP response splitting, you should seriously consider using a commercial static analysis or pen-testing tool. </p> <h3><a name="PT_ABSOLUTE_PATH_TRAVERSAL">PT: Absolute path traversal in servlet (PT_ABSOLUTE_PATH_TRAVERSAL)</a></h3> <p>The software uses an HTTP request parameter to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. See <a href="http://cwe.mitre.org/data/definitions/36.html">http://cwe.mitre.org/data/definitions/36.html</a> for more information.</p> <p>FindBugs looks only for the most blatant, obvious cases of absolute path traversal. If FindBugs found <em>any</em>, you <em>almost certainly</em> have more vulnerabilities that FindBugs doesn't report. If you are concerned about absolute path traversal, you should seriously consider using a commercial static analysis or pen-testing tool. </p> <h3><a name="PT_RELATIVE_PATH_TRAVERSAL">PT: Relative path traversal in servlet (PT_RELATIVE_PATH_TRAVERSAL)</a></h3> <p>The software uses an HTTP request parameter to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory. See <a href="http://cwe.mitre.org/data/definitions/23.html">http://cwe.mitre.org/data/definitions/23.html</a> for more information.</p> <p>FindBugs looks only for the most blatant, obvious cases of relative path traversal. If FindBugs found <em>any</em>, you <em>almost certainly</em> have more vulnerabilities that FindBugs doesn't report. If you are concerned about relative path traversal, you should seriously consider using a commercial static analysis or pen-testing tool. </p> <h3><a name="SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE">SQL: Nonconstant string passed to execute method on an SQL statement (SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE)</a></h3> <p>The method invokes the execute method on an SQL statement with a String that seems to be dynamically generated. Consider using a prepared statement instead. It is more efficient and less vulnerable to SQL injection attacks. </p> <h3><a name="SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING">SQL: A prepared statement is generated from a nonconstant String (SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING)</a></h3> <p>The code creates an SQL prepared statement from a nonconstant String. If unchecked, tainted data from a user is used in building this String, SQL injection could be used to make the prepared statement do something unexpected and undesirable. </p> <h3><a name="XSS_REQUEST_PARAMETER_TO_JSP_WRITER">XSS: JSP reflected cross site scripting vulnerability (XSS_REQUEST_PARAMETER_TO_JSP_WRITER)</a></h3> <p>This code directly writes an HTTP parameter to JSP output, which allows for a cross site scripting vulnerability. See <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">http://en.wikipedia.org/wiki/Cross-site_scripting</a> for more information.</p> <p>FindBugs looks only for the most blatant, obvious cases of cross site scripting. If FindBugs found <em>any</em>, you <em>almost certainly</em> have more cross site scripting vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously consider using a commercial static analysis or pen-testing tool. </p> <h3><a name="XSS_REQUEST_PARAMETER_TO_SEND_ERROR">XSS: Servlet reflected cross site scripting vulnerability in error page (XSS_REQUEST_PARAMETER_TO_SEND_ERROR)</a></h3> <p>This code directly writes an HTTP parameter to a Server error page (using HttpServletResponse.sendError). Echoing this untrusted input allows for a reflected cross site scripting vulnerability. See <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">http://en.wikipedia.org/wiki/Cross-site_scripting</a> for more information.</p> <p>FindBugs looks only for the most blatant, obvious cases of cross site scripting. If FindBugs found <em>any</em>, you <em>almost certainly</em> have more cross site scripting vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously consider using a commercial static analysis or pen-testing tool. </p> <h3><a name="XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER">XSS: Servlet reflected cross site scripting vulnerability (XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER)</a></h3> <p>This code directly writes an HTTP parameter to Servlet output, which allows for a reflected cross site scripting vulnerability. See <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">http://en.wikipedia.org/wiki/Cross-site_scripting</a> for more information.</p> <p>FindBugs looks only for the most blatant, obvious cases of cross site scripting. If FindBugs found <em>any</em>, you <em>almost certainly</em> have more cross site scripting vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously consider using a commercial static analysis or pen-testing tool. </p> <h3><a name="BC_BAD_CAST_TO_ABSTRACT_COLLECTION">BC: Questionable cast to abstract collection (BC_BAD_CAST_TO_ABSTRACT_COLLECTION)</a></h3> <p> This code casts a Collection to an abstract collection (such as <code>List</code>, <code>Set</code>, or <code>Map</code>). Ensure that you are guaranteed that the object is of the type you are casting to. If all you need is to be able to iterate through a collection, you don't need to cast it to a Set or List. </p> <h3><a name="BC_BAD_CAST_TO_CONCRETE_COLLECTION">BC: Questionable cast to concrete collection (BC_BAD_CAST_TO_CONCRETE_COLLECTION)</a></h3> <p> This code casts an abstract collection (such as a Collection, List, or Set) to a specific concrete implementation (such as an ArrayList or HashSet). This might not be correct, and it may make your code fragile, since it makes it harder to switch to other concrete implementations at a future point. Unless you have a particular reason to do so, just use the abstract collection class. </p> <h3><a name="BC_UNCONFIRMED_CAST">BC: Unchecked/unconfirmed cast (BC_UNCONFIRMED_CAST)</a></h3> <p> This cast is unchecked, and not all instances of the type casted from can be cast to the type it is being cast to. Check that your program logic ensures that this cast will not fail. </p> <h3><a name="BC_UNCONFIRMED_CAST_OF_RETURN_VALUE">BC: Unchecked/unconfirmed cast of return value from method (BC_UNCONFIRMED_CAST_OF_RETURN_VALUE)</a></h3> <p> This code performs an unchecked cast of the return value of a method. The code might be calling the method in such a way that the cast is guaranteed to be safe, but FindBugs is unable to verify that the cast is safe. Check that your program logic ensures that this cast will not fail. </p> <h3><a name="BC_VACUOUS_INSTANCEOF">BC: instanceof will always return true (BC_VACUOUS_INSTANCEOF)</a></h3> <p> This instanceof test will always return true (unless the value being tested is null). Although this is safe, make sure it isn't an indication of some misunderstanding or some other logic error. If you really want to test the value for being null, perhaps it would be clearer to do better to do a null test rather than an instanceof test. </p> <h3><a name="ICAST_QUESTIONABLE_UNSIGNED_RIGHT_SHIFT">BSHIFT: Unsigned right shift cast to short/byte (ICAST_QUESTIONABLE_UNSIGNED_RIGHT_SHIFT)</a></h3> <p> The code performs an unsigned right shift, whose result is then cast to a short or byte, which discards the upper bits of the result. Since the upper bits are discarded, there may be no difference between a signed and unsigned right shift (depending upon the size of the shift). </p> <h3><a name="CI_CONFUSED_INHERITANCE">CI: Class is final but declares protected field (CI_CONFUSED_INHERITANCE)</a></h3> <p> This class is declared to be final, but declares fields to be protected. Since the class is final, it can not be derived from, and the use of protected is confusing. The access modifier for the field should be changed to private or public to represent the true use for the field. </p> <h3><a name="DB_DUPLICATE_BRANCHES">DB: Method uses the same code for two branches (DB_DUPLICATE_BRANCHES)</a></h3> <p> This method uses the same code to implement two branches of a conditional branch. Check to ensure that this isn't a coding mistake. </p> <h3><a name="DB_DUPLICATE_SWITCH_CLAUSES">DB: Method uses the same code for two switch clauses (DB_DUPLICATE_SWITCH_CLAUSES)</a></h3> <p> This method uses the same code to implement two clauses of a switch statement. This could be a case of duplicate code, but it might also indicate a coding mistake. </p> <h3><a name="DLS_DEAD_LOCAL_STORE">DLS: Dead store to local variable (DLS_DEAD_LOCAL_STORE)</a></h3> <p> This instruction assigns a value to a local variable, but the value is not read or used in any subsequent instruction. Often, this indicates an error, because the value computed is never used. </p> <p> Note that Sun's javac compiler often generates dead stores for final local variables. Because FindBugs is a bytecode-based tool, there is no easy way to eliminate these false positives. </p> <h3><a name="DLS_DEAD_LOCAL_STORE_IN_RETURN">DLS: Useless assignment in return statement (DLS_DEAD_LOCAL_STORE_IN_RETURN)</a></h3> <p> This statement assigns to a local variable in a return statement. This assignment has effect. Please verify that this statement does the right thing. </p> <h3><a name="DLS_DEAD_LOCAL_STORE_OF_NULL">DLS: Dead store of null to local variable (DLS_DEAD_LOCAL_STORE_OF_NULL)</a></h3> <p>The code stores null into a local variable, and the stored value is not read. This store may have been introduced to assist the garbage collector, but as of Java SE 6.0, this is no longer needed or useful. </p> <h3><a name="DLS_DEAD_LOCAL_STORE_SHADOWS_FIELD">DLS: Dead store to local variable that shadows field (DLS_DEAD_LOCAL_STORE_SHADOWS_FIELD)</a></h3> <p> This instruction assigns a value to a local variable, but the value is not read or used in any subsequent instruction. Often, this indicates an error, because the value computed is never used. There is a field with the same name as the local variable. Did you mean to assign to that variable instead? </p> <h3><a name="DMI_HARDCODED_ABSOLUTE_FILENAME">DMI: Code contains a hard coded reference to an absolute pathname (DMI_HARDCODED_ABSOLUTE_FILENAME)</a></h3> <p>This code constructs a File object using a hard coded to an absolute pathname (e.g., <code>new File("/home/dannyc/workspace/j2ee/src/share/com/sun/enterprise/deployment");</code> </p> <h3><a name="DMI_NONSERIALIZABLE_OBJECT_WRITTEN">DMI: Non serializable object written to ObjectOutput (DMI_NONSERIALIZABLE_OBJECT_WRITTEN)</a></h3> <p> This code seems to be passing a non-serializable object to the ObjectOutput.writeObject method. If the object is, indeed, non-serializable, an error will result. </p> <h3><a name="DMI_USELESS_SUBSTRING">DMI: Invocation of substring(0), which returns the original value (DMI_USELESS_SUBSTRING)</a></h3> <p> This code invokes substring(0) on a String, which returns the original value. </p> <h3><a name="DMI_THREAD_PASSED_WHERE_RUNNABLE_EXPECTED">Dm: Thread passed where Runnable expected (DMI_THREAD_PASSED_WHERE_RUNNABLE_EXPECTED)</a></h3> <p> A Thread object is passed as a parameter to a method where a Runnable is expected. This is rather unusual, and may indicate a logic error or cause unexpected behavior. </p> <h3><a name="EQ_DOESNT_OVERRIDE_EQUALS">Eq: Class doesn't override equals in superclass (EQ_DOESNT_OVERRIDE_EQUALS)</a></h3> <p> This class extends a class that defines an equals method and adds fields, but doesn't define an equals method itself. Thus, equality on instances of this class will ignore the identity of the subclass and the added fields. Be sure this is what is intended, and that you don't need to override the equals method. Even if you don't need to override the equals method, consider overriding it anyway to document the fact that the equals method for the subclass just return the result of invoking super.equals(o). </p> <h3><a name="EQ_UNUSUAL">Eq: Unusual equals method (EQ_UNUSUAL)</a></h3> <p> This class doesn't do any of the patterns we recognize for checking that the type of the argument is compatible with the type of the <code>this</code> object. There might not be anything wrong with this code, but it is worth reviewing. </p> <h3><a name="FE_FLOATING_POINT_EQUALITY">FE: Test for floating point equality (FE_FLOATING_POINT_EQUALITY)</a></h3> <p> This operation compares two floating point values for equality. Because floating point calculations may involve rounding, calculated float and double values may not be accurate. For values that must be precise, such as monetary values, consider using a fixed-precision type such as BigDecimal. For values that need not be precise, consider comparing for equality within some range, for example: <code>if ( Math.abs(x - y) &lt; .0000001 )</code>. See the Java Language Specification, section 4.2.4. </p> <h3><a name="VA_FORMAT_STRING_BAD_CONVERSION_TO_BOOLEAN">FS: Non-Boolean argument formatted using %b format specifier (VA_FORMAT_STRING_BAD_CONVERSION_TO_BOOLEAN)</a></h3> <p> An argument not of type Boolean is being formatted with a %b format specifier. This won't throw an exception; instead, it will print true for any nonnull value, and false for null. This feature of format strings is strange, and may not be what you intended. </p> <h3><a name="IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD">IA: Potentially ambiguous invocation of either an inherited or outer method (IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD)</a></h3> <p> An inner class is invoking a method that could be resolved to either a inherited method or a method defined in an outer class. For example, you invoke <code>foo(17)</code>, which is defined in both a superclass and in an outer method. By the Java semantics, it will be resolved to invoke the inherited method, but this may not be want you intend. </p> <p>If you really intend to invoke the inherited method, invoke it by invoking the method on super (e.g., invoke super.foo(17)), and thus it will be clear to other readers of your code and to FindBugs that you want to invoke the inherited method, not the method in the outer class. </p> <p>If you call <code>this.foo(17)</code>, then the inherited method will be invoked. However, since FindBugs only looks at classfiles, it can't tell the difference between an invocation of <code>this.foo(17)</code> and <code>foo(17)</code>, it will still complain about a potential ambiguous invocation. </p> <h3><a name="IC_INIT_CIRCULARITY">IC: Initialization circularity (IC_INIT_CIRCULARITY)</a></h3> <p> A circularity was detected in the static initializers of the two classes referenced by the bug instance.&nbsp; Many kinds of unexpected behavior may arise from such circularity.</p> <h3><a name="ICAST_IDIV_CAST_TO_DOUBLE">ICAST: Integral division result cast to double or float (ICAST_IDIV_CAST_TO_DOUBLE)</a></h3> <p> This code casts the result of an integral division (e.g., int or long division) operation to double or float. Doing division on integers truncates the result to the integer value closest to zero. The fact that the result was cast to double suggests that this precision should have been retained. What was probably meant was to cast one or both of the operands to double <em>before</em> performing the division. Here is an example: </p> <blockquote> <pre> int x = 2; int y = 5; // Wrong: yields result 0.0 double value1 = x / y; // Right: yields result 0.4 double value2 = x / (double) y; </pre> </blockquote> <h3><a name="ICAST_INTEGER_MULTIPLY_CAST_TO_LONG">ICAST: Result of integer multiplication cast to long (ICAST_INTEGER_MULTIPLY_CAST_TO_LONG)</a></h3> <p> This code performs integer multiply and then converts the result to a long, as in:</p> <pre> long convertDaysToMilliseconds(int days) { return 1000*3600*24*days; } </pre> <p> If the multiplication is done using long arithmetic, you can avoid the possibility that the result will overflow. For example, you could fix the above code to:</p> <pre> long convertDaysToMilliseconds(int days) { return 1000L*3600*24*days; } </pre> or <pre> static final long MILLISECONDS_PER_DAY = 24L*3600*1000; long convertDaysToMilliseconds(int days) { return days * MILLISECONDS_PER_DAY; } </pre> <h3><a name="IM_AVERAGE_COMPUTATION_COULD_OVERFLOW">IM: Computation of average could overflow (IM_AVERAGE_COMPUTATION_COULD_OVERFLOW)</a></h3> <p>The code computes the average of two integers using either division or signed right shift, and then uses the result as the index of an array. If the values being averaged are very large, this can overflow (resulting in the computation of a negative average). Assuming that the result is intended to be nonnegative, you can use an unsigned right shift instead. In other words, rather that using <code>(low+high)/2</code>, use <code>(low+high) &gt;&gt;&gt; 1</code> </p> <p>This bug exists in many earlier implementations of binary search and merge sort. Martin Buchholz <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6412541">found and fixed it</a> in the JDK libraries, and Joshua Bloch <a href="http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html">widely publicized the bug pattern</a>. </p> <h3><a name="IM_BAD_CHECK_FOR_ODD">IM: Check for oddness that won't work for negative numbers (IM_BAD_CHECK_FOR_ODD)</a></h3> <p> The code uses x % 2 == 1 to check to see if a value is odd, but this won't work for negative numbers (e.g., (-5) % 2 == -1). If this code is intending to check for oddness, consider using x &amp; 1 == 1, or x % 2 != 0. </p> <h3><a name="INT_BAD_REM_BY_1">INT: Integer remainder modulo 1 (INT_BAD_REM_BY_1)</a></h3> <p> Any expression (exp % 1) is guaranteed to always return zero. Did you mean (exp &amp; 1) or (exp % 2) instead? </p> <h3><a name="INT_VACUOUS_BIT_OPERATION">INT: Vacuous bit mask operation on integer value (INT_VACUOUS_BIT_OPERATION)</a></h3> <p> This is an integer bit operation (and, or, or exclusive or) that doesn't do any useful work (e.g., <code>v & 0xffffffff</code>). </p> <h3><a name="INT_VACUOUS_COMPARISON">INT: Vacuous comparison of integer value (INT_VACUOUS_COMPARISON)</a></h3> <p> There is an integer comparison that always returns the same value (e.g., x &lt;= Integer.MAX_VALUE). </p> <h3><a name="MTIA_SUSPECT_SERVLET_INSTANCE_FIELD">MTIA: Class extends Servlet class and uses instance variables (MTIA_SUSPECT_SERVLET_INSTANCE_FIELD)</a></h3> <p> This class extends from a Servlet class, and uses an instance member variable. Since only one instance of a Servlet class is created by the J2EE framework, and used in a multithreaded way, this paradigm is highly discouraged and most likely problematic. Consider only using method local variables. </p> <h3><a name="MTIA_SUSPECT_STRUTS_INSTANCE_FIELD">MTIA: Class extends Struts Action class and uses instance variables (MTIA_SUSPECT_STRUTS_INSTANCE_FIELD)</a></h3> <p> This class extends from a Struts Action class, and uses an instance member variable. Since only one instance of a struts Action class is created by the Struts framework, and used in a multithreaded way, this paradigm is highly discouraged and most likely problematic. Consider only using method local variables. Only instance fields that are written outside of a monitor are reported. </p> <h3><a name="NP_DEREFERENCE_OF_READLINE_VALUE">NP: Dereference of the result of readLine() without nullcheck (NP_DEREFERENCE_OF_READLINE_VALUE)</a></h3> <p> The result of invoking readLine() is dereferenced without checking to see if the result is null. If there are no more lines of text to read, readLine() will return null and dereferencing that will generate a null pointer exception. </p> <h3><a name="NP_IMMEDIATE_DEREFERENCE_OF_READLINE">NP: Immediate dereference of the result of readLine() (NP_IMMEDIATE_DEREFERENCE_OF_READLINE)</a></h3> <p> The result of invoking readLine() is immediately dereferenced. If there are no more lines of text to read, readLine() will return null and dereferencing that will generate a null pointer exception. </p> <h3><a name="NP_LOAD_OF_KNOWN_NULL_VALUE">NP: Load of known null value (NP_LOAD_OF_KNOWN_NULL_VALUE)</a></h3> <p> The variable referenced at this point is known to be null due to an earlier check against null. Although this is valid, it might be a mistake (perhaps you intended to refer to a different variable, or perhaps the earlier check to see if the variable is null should have been a check to see if it was nonnull). </p> <h3><a name="NP_METHOD_PARAMETER_TIGHTENS_ANNOTATION">NP: Method tightens nullness annotation on parameter (NP_METHOD_PARAMETER_TIGHTENS_ANNOTATION)</a></h3> <p> A method should always implement the contract of a method it overrides. Thus, if a method takes a parameter that is marked as @Nullable, you shouldn't override that method in a subclass with a method where that parameter is @Nonnull. Doing so violates the contract that the method should handle a null parameter. </p> <h3><a name="NP_METHOD_RETURN_RELAXING_ANNOTATION">NP: Method relaxes nullness annotation on return value (NP_METHOD_RETURN_RELAXING_ANNOTATION)</a></h3> <p> A method should always implement the contract of a method it overrides. Thus, if a method takes is annotated as returning a @Nonnull value, you shouldn't override that method in a subclass with a method annotated as returning a @Nullable or @CheckForNull value. Doing so violates the contract that the method shouldn't return null. </p> <h3><a name="NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE">NP: Possible null pointer dereference due to return value of called method (NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE)</a></h3> <p> The return value from a method is dereferenced without a null check, and the return value of that method is one that should generally be checked for null. This may lead to a <code>NullPointerException</code> when the code is executed. </p> <h3><a name="NP_NULL_ON_SOME_PATH_MIGHT_BE_INFEASIBLE">NP: Possible null pointer dereference on branch that might be infeasible (NP_NULL_ON_SOME_PATH_MIGHT_BE_INFEASIBLE)</a></h3> <p> There is a branch of statement that, <em>if executed,</em> guarantees that a null value will be dereferenced, which would generate a <code>NullPointerException</code> when the code is executed. Of course, the problem might be that the branch or statement is infeasible and that the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs. Due to the fact that this value had been previously tested for nullness, this is a definite possibility. </p> <h3><a name="NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE">NP: Parameter must be nonnull but is marked as nullable (NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE)</a></h3> <p> This parameter is always used in a way that requires it to be nonnull, but the parameter is explicitly annotated as being Nullable. Either the use of the parameter or the annotation is wrong. </p> <h3><a name="NP_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD">NP: Read of unwritten public or protected field (NP_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD)</a></h3> <p> The program is dereferencing a public or protected field that does not seem to ever have a non-null value written to it. Unless the field is initialized via some mechanism not seen by the analysis, dereferencing this value will generate a null pointer exception. </p> <h3><a name="NS_DANGEROUS_NON_SHORT_CIRCUIT">NS: Potentially dangerous use of non-short-circuit logic (NS_DANGEROUS_NON_SHORT_CIRCUIT)</a></h3> <p> This code seems to be using non-short-circuit logic (e.g., &amp; or |) rather than short-circuit logic (&amp;&amp; or ||). In addition, it seem possible that, depending on the value of the left hand side, you might not want to evaluate the right hand side (because it would have side effects, could cause an exception or could be expensive.</p> <p> Non-short-circuit logic causes both sides of the expression to be evaluated even when the result can be inferred from knowing the left-hand side. This can be less efficient and can result in errors if the left-hand side guards cases when evaluating the right-hand side can generate an error. </p> <p>See <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.22.2">the Java Language Specification</a> for details </p> <h3><a name="NS_NON_SHORT_CIRCUIT">NS: Questionable use of non-short-circuit logic (NS_NON_SHORT_CIRCUIT)</a></h3> <p> This code seems to be using non-short-circuit logic (e.g., &amp; or |) rather than short-circuit logic (&amp;&amp; or ||). Non-short-circuit logic causes both sides of the expression to be evaluated even when the result can be inferred from knowing the left-hand side. This can be less efficient and can result in errors if the left-hand side guards cases when evaluating the right-hand side can generate an error. <p>See <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.22.2">the Java Language Specification</a> for details </p> <h3><a name="PZLA_PREFER_ZERO_LENGTH_ARRAYS">PZLA: Consider returning a zero length array rather than null (PZLA_PREFER_ZERO_LENGTH_ARRAYS)</a></h3> <p> It is often a better design to return a length zero array rather than a null reference to indicate that there are no results (i.e., an empty list of results). This way, no explicit check for null is needed by clients of the method.</p> <p>On the other hand, using null to indicate "there is no answer to this question" is probably appropriate. For example, <code>File.listFiles()</code> returns an empty list if given a directory containing no files, and returns null if the file is not a directory.</p> <h3><a name="QF_QUESTIONABLE_FOR_LOOP">QF: Complicated, subtle or wrong increment in for-loop (QF_QUESTIONABLE_FOR_LOOP)</a></h3> <p>Are you sure this for loop is incrementing the correct variable? It appears that another variable is being initialized and checked by the for loop. </p> <h3><a name="RCN_REDUNDANT_COMPARISON_OF_NULL_AND_NONNULL_VALUE">RCN: Redundant comparison of non-null value to null (RCN_REDUNDANT_COMPARISON_OF_NULL_AND_NONNULL_VALUE)</a></h3> <p> This method contains a reference known to be non-null with another reference known to be null.</p> <h3><a name="RCN_REDUNDANT_COMPARISON_TWO_NULL_VALUES">RCN: Redundant comparison of two null values (RCN_REDUNDANT_COMPARISON_TWO_NULL_VALUES)</a></h3> <p> This method contains a redundant comparison of two references known to both be definitely null.</p> <h3><a name="RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE">RCN: Redundant nullcheck of value known to be non-null (RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE)</a></h3> <p> This method contains a redundant check of a known non-null value against the constant null.</p> <h3><a name="RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE">RCN: Redundant nullcheck of value known to be null (RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE)</a></h3> <p> This method contains a redundant check of a known null value against the constant null.</p> <h3><a name="REC_CATCH_EXCEPTION">REC: Exception is caught when Exception is not thrown (REC_CATCH_EXCEPTION)</a></h3> <p> This method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, masking potential bugs. </p> <p>A better approach is to either explicitly catch the specific exceptions that are thrown, or to explicitly catch RuntimeException exception, rethrow it, and then catch all non-Runtime Exceptions, as shown below:</p> <pre> try { ... } catch (RuntimeException e) { throw e; } catch (Exception e) { ... deal with all non-runtime exceptions ... }</pre> <h3><a name="RI_REDUNDANT_INTERFACES">RI: Class implements same interface as superclass (RI_REDUNDANT_INTERFACES)</a></h3> <p> This class declares that it implements an interface that is also implemented by a superclass. This is redundant because once a superclass implements an interface, all subclasses by default also implement this interface. It may point out that the inheritance hierarchy has changed since this class was created, and consideration should be given to the ownership of the interface's implementation. </p> <h3><a name="RV_CHECK_FOR_POSITIVE_INDEXOF">RV: Method checks to see if result of String.indexOf is positive (RV_CHECK_FOR_POSITIVE_INDEXOF)</a></h3> <p> The method invokes String.indexOf and checks to see if the result is positive or non-positive. It is much more typical to check to see if the result is negative or non-negative. It is positive only if the substring checked for occurs at some place other than at the beginning of the String.</p> <h3><a name="RV_DONT_JUST_NULL_CHECK_READLINE">RV: Method discards result of readLine after checking if it is nonnull (RV_DONT_JUST_NULL_CHECK_READLINE)</a></h3> <p> The value returned by readLine is discarded after checking to see if the return value is non-null. In almost all situations, if the result is non-null, you will want to use that non-null value. Calling readLine again will give you a different line.</p> <h3><a name="RV_REM_OF_HASHCODE">RV: Remainder of hashCode could be negative (RV_REM_OF_HASHCODE)</a></h3> <p> This code computes a hashCode, and then computes the remainder of that value modulo another value. Since the hashCode can be negative, the result of the remainder operation can also be negative. </p> <p> Assuming you want to ensure that the result of your computation is nonnegative, you may need to change your code. If you know the divisor is a power of 2, you can use a bitwise and operator instead (i.e., instead of using <code>x.hashCode()%n</code>, use <code>x.hashCode()&amp;(n-1)</code>. This is probably faster than computing the remainder as well. If you don't know that the divisor is a power of 2, take the absolute value of the result of the remainder operation (i.e., use <code>Math.abs(x.hashCode()%n)</code> </p> <h3><a name="RV_REM_OF_RANDOM_INT">RV: Remainder of 32-bit signed random integer (RV_REM_OF_RANDOM_INT)</a></h3> <p> This code generates a random signed integer and then computes the remainder of that value modulo another value. Since the random number can be negative, the result of the remainder operation can also be negative. Be sure this is intended, and strongly consider using the Random.nextInt(int) method instead. </p> <h3><a name="RV_RETURN_VALUE_IGNORED_INFERRED">RV: Method ignores return value, is this OK? (RV_RETURN_VALUE_IGNORED_INFERRED)</a></h3> <p>This code calls a method and ignores the return value. The return value is the same type as the type the method is invoked on, and from our analysis it looks like the return value might be important (e.g., like ignoring the return value of <code>String.toLowerCase()</code>). </p> <p>We are guessing that ignoring the return value might be a bad idea just from a simple analysis of the body of the method. You can use a @CheckReturnValue annotation to instruct FindBugs as to whether ignoring the return value of this method is important or acceptable. </p> <p>Please investigate this closely to decide whether it is OK to ignore the return value. </p> <h3><a name="SA_FIELD_DOUBLE_ASSIGNMENT">SA: Double assignment of field (SA_FIELD_DOUBLE_ASSIGNMENT)</a></h3> <p> This method contains a double assignment of a field; e.g. </p> <pre> int x,y; public void foo() { x = x = 17; } </pre> <p>Assigning to a field twice is useless, and may indicate a logic error or typo.</p> <h3><a name="SA_LOCAL_DOUBLE_ASSIGNMENT">SA: Double assignment of local variable (SA_LOCAL_DOUBLE_ASSIGNMENT)</a></h3> <p> This method contains a double assignment of a local variable; e.g. </p> <pre> public void foo() { int x,y; x = x = 17; } </pre> <p>Assigning the same value to a variable twice is useless, and may indicate a logic error or typo.</p> <h3><a name="SA_LOCAL_SELF_ASSIGNMENT">SA: Self assignment of local variable (SA_LOCAL_SELF_ASSIGNMENT)</a></h3> <p> This method contains a self assignment of a local variable; e.g.</p> <pre> public void foo() { int x = 3; x = x; } </pre> <p> Such assignments are useless, and may indicate a logic error or typo. </p> <h3><a name="SF_SWITCH_FALLTHROUGH">SF: Switch statement found where one case falls through to the next case (SF_SWITCH_FALLTHROUGH)</a></h3> <p> This method contains a switch statement where one case branch will fall through to the next case. Usually you need to end this case with a break or return.</p> <h3><a name="SF_SWITCH_NO_DEFAULT">SF: Switch statement found where default case is missing (SF_SWITCH_NO_DEFAULT)</a></h3> <p> This method contains a switch statement where default case is missing. Usually you need to provide a default case.</p> <p>Because the analysis only looks at the generated bytecode, this warning can be incorrect triggered if the default case is at the end of the switch statement and doesn't end with a break statement. <h3><a name="ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD">ST: Write to static field from instance method (ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD)</a></h3> <p> This instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice. </p> <h3><a name="SE_PRIVATE_READ_RESOLVE_NOT_INHERITED">Se: Private readResolve method not inherited by subclasses (SE_PRIVATE_READ_RESOLVE_NOT_INHERITED)</a></h3> <p> This class defines a private readResolve method. Since it is private, it won't be inherited by subclasses. This might be intentional and OK, but should be reviewed to ensure it is what is intended. </p> <h3><a name="SE_TRANSIENT_FIELD_OF_NONSERIALIZABLE_CLASS">Se: Transient field of class that isn't Serializable. (SE_TRANSIENT_FIELD_OF_NONSERIALIZABLE_CLASS)</a></h3> <p> The field is marked as transient, but the class isn't Serializable, so marking it as transient has absolutely no effect. This may be leftover marking from a previous version of the code in which the class was transient, or it may indicate a misunderstanding of how serialization works. </p> <h3><a name="TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_ALWAYS_SINK">TQ: Value required to have type qualifier, but marked as unknown (TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_ALWAYS_SINK)</a></h3> <p> A value is used in a way that requires it to be always be a value denoted by a type qualifier, but there is an explicit annotation stating that it is not known where the value is required to have that type qualifier. Either the usage or the annotation is incorrect. </p> <h3><a name="TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_NEVER_SINK">TQ: Value required to not have type qualifier, but marked as unknown (TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_NEVER_SINK)</a></h3> <p> A value is used in a way that requires it to be never be a value denoted by a type qualifier, but there is an explicit annotation stating that it is not known where the value is prohibited from having that type qualifier. Either the usage or the annotation is incorrect. </p> <h3><a name="UCF_USELESS_CONTROL_FLOW">UCF: Useless control flow (UCF_USELESS_CONTROL_FLOW)</a></h3> <p> This method contains a useless control flow statement, where control flow continues onto the same place regardless of whether or not the branch is taken. For example, this is caused by having an empty statement block for an <code>if</code> statement:</p> <pre> if (argv.length == 0) { // TODO: handle this case } </pre> <h3><a name="UCF_USELESS_CONTROL_FLOW_NEXT_LINE">UCF: Useless control flow to next line (UCF_USELESS_CONTROL_FLOW_NEXT_LINE)</a></h3> <p> This method contains a useless control flow statement in which control flow follows to the same or following line regardless of whether or not the branch is taken. Often, this is caused by inadvertently using an empty statement as the body of an <code>if</code> statement, e.g.:</p> <pre> if (argv.length == 1); System.out.println("Hello, " + argv[0]); </pre> <h3><a name="URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD">UrF: Unread public/protected field (URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD)</a></h3> <p> This field is never read.&nbsp; The field is public or protected, so perhaps it is intended to be used with classes not seen as part of the analysis. If not, consider removing it from the class.</p> <h3><a name="UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD">UuF: Unused public or protected field (UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD)</a></h3> <p> This field is never used.&nbsp; The field is public or protected, so perhaps it is intended to be used with classes not seen as part of the analysis. If not, consider removing it from the class.</p> <h3><a name="UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR">UwF: Field not initialized in constructor but dereferenced without null check (UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR)</a></h3> <p> This field is never initialized within any constructor, and is therefore could be null after the object is constructed. Elsewhere, it is loaded and dereferenced without a null check. This could be a either an error or a questionable design, since it means a null pointer exception will be generated if that field is dereferenced before being initialized. </p> <h3><a name="UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD">UwF: Unwritten public or protected field (UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD)</a></h3> <p> No writes were seen to this public/protected field.&nbsp; All reads of it will return the default value. Check for errors (should it have been initialized?), or remove it if it is useless.</p> <h3><a name="XFB_XML_FACTORY_BYPASS">XFB: Method directly allocates a specific implementation of xml interfaces (XFB_XML_FACTORY_BYPASS)</a></h3> <p> This method allocates a specific implementation of an xml interface. It is preferable to use the supplied factory classes to create these objects so that the implementation can be changed at runtime. See </p> <ul> <li>javax.xml.parsers.DocumentBuilderFactory</li> <li>javax.xml.parsers.SAXParserFactory</li> <li>javax.xml.transform.TransformerFactory</li> <li>org.w3c.dom.Document.create<i>XXXX</i></li> </ul> <p>for details.</p> <hr> <p> <script language="JavaScript" type="text/javascript"> <!---//hide script from old browsers document.write( "Last updated "+ document.lastModified + "." ); //end hiding contents ---> </script> <p> Send comments to <a class="sidebar" href="mailto:findbugs@cs.umd.edu">findbugs@cs.umd.edu</a> <p> <A href="http://sourceforge.net"><IMG src="http://sourceforge.net/sflogo.php?group_id=96405&amp;type=5" width="210" height="62" border="0" alt="SourceForge.net Logo" /></A> </td></tr></table> </body></html>
1049884729/owasp-java-html-sanitizer
tools/findbugs/doc/bugDescriptions.html
HTML
apache-2.0
271,009